@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.js CHANGED
@@ -834,7 +834,7 @@ function parseCardElo(provenance) {
834
834
  const match = eloEntry.reason.match(/card:\s*(\d+)/);
835
835
  return match ? parseInt(match[1], 10) : void 0;
836
836
  }
837
- function buildRunReport(courseId, courseName, generatorName, generators, generatedCount, filters, allCards, selectedCards, userElo, hints, scoredCards) {
837
+ function buildRunReport(courseId, courseName, generatorName, generators, generatedCount, filters, allCards, selectedCards, userElo, hints, scoredCards, regulators) {
838
838
  const selectedIds = new Set(selectedCards.map((c) => c.cardId));
839
839
  const toReport = (card) => ({
840
840
  cardId: card.cardId,
@@ -842,7 +842,7 @@ function buildRunReport(courseId, courseName, generatorName, generators, generat
842
842
  origin: getOrigin(card),
843
843
  generator: card.provenance[0]?.strategyName || card.provenance[0]?.strategy,
844
844
  finalScore: card.score,
845
- cardElo: parseCardElo(card.provenance),
845
+ cardElo: card.cardElo ?? parseCardElo(card.provenance),
846
846
  provenance: card.provenance,
847
847
  tags: card.tags,
848
848
  selected: selectedIds.has(card.cardId)
@@ -920,7 +920,8 @@ function buildRunReport(courseId, courseName, generatorName, generators, generat
920
920
  newSelected,
921
921
  cards,
922
922
  unselectedNew,
923
- discardedTail
923
+ discardedTail,
924
+ ...regulators ? { regulators } : {}
924
925
  };
925
926
  }
926
927
  function formatProvenance(provenance) {
@@ -1644,11 +1645,23 @@ var SrsDebugger_exports = {};
1644
1645
  __export(SrsDebugger_exports, {
1645
1646
  captureSrsBacklog: () => captureSrsBacklog,
1646
1647
  clearSrsBacklogDebug: () => clearSrsBacklogDebug,
1647
- getSrsBacklogDebug: () => getSrsBacklogDebug
1648
+ getSrsBacklogDebug: () => getSrsBacklogDebug,
1649
+ noteReviewPressure: () => noteReviewPressure
1648
1650
  });
1649
1651
  function captureSrsBacklog(snapshot) {
1650
1652
  snapshots.set(snapshot.courseId, snapshot);
1651
1653
  }
1654
+ function noteReviewPressure(courseId, pressure) {
1655
+ const snapshot = snapshots.get(courseId);
1656
+ if (!snapshot) return;
1657
+ snapshots.set(courseId, {
1658
+ ...snapshot,
1659
+ reviewMass: pressure.mass,
1660
+ healthyBacklog: pressure.healthyMass,
1661
+ backlogGrowthRate: pressure.rate,
1662
+ backlogMultiplier: pressure.multiplier
1663
+ });
1664
+ }
1652
1665
  function getSrsBacklogDebug() {
1653
1666
  return [...snapshots.values()].sort((a, b) => b.timestamp - a.timestamp);
1654
1667
  }
@@ -1926,14 +1939,13 @@ var elo_exports = {};
1926
1939
  __export(elo_exports, {
1927
1940
  default: () => ELONavigator
1928
1941
  });
1929
- var import_common5, ELO_RELEVANCE_SIGMA, ELONavigator;
1942
+ var import_common5, ELONavigator;
1930
1943
  var init_elo = __esm({
1931
1944
  "src/core/navigators/generators/elo.ts"() {
1932
1945
  "use strict";
1933
1946
  init_navigators();
1934
1947
  import_common5 = require("@vue-skuilder/common");
1935
1948
  init_logger();
1936
- ELO_RELEVANCE_SIGMA = 300;
1937
1949
  ELONavigator = class extends ContentNavigator {
1938
1950
  /** Human-readable name for CardGenerator interface */
1939
1951
  name;
@@ -1942,10 +1954,8 @@ var init_elo = __esm({
1942
1954
  this.name = strategyData?.name || "ELO";
1943
1955
  }
1944
1956
  /**
1945
- * Get new cards with suitability scores based on ELO distance.
1946
- *
1947
- * Cards closer to user's ELO get higher scores.
1948
- * Score formula: max(0, 1 - distance / 500)
1957
+ * Get the new cards nearest the learner's ELO, each scored with a flat
1958
+ * jitter in [0.5, 1]. Carries each card's ELO for the ELO distance filter.
1949
1959
  *
1950
1960
  * NOTE: This generator only handles NEW cards. Reviews are handled by
1951
1961
  * SRSNavigator. Use CompositeGenerator to combine both.
@@ -1973,20 +1983,20 @@ var init_elo = __esm({
1973
1983
  const scored = newCards.map((c) => {
1974
1984
  const cardElo = c.elo ?? 1e3;
1975
1985
  const distance = Math.abs(cardElo - userGlobalElo);
1976
- const relevance = Math.exp(-((distance / ELO_RELEVANCE_SIGMA) ** 2));
1977
- const samplingKey = relevance * (0.5 + 0.5 * Math.random());
1986
+ const jitter = 0.5 + 0.5 * Math.random();
1978
1987
  return {
1979
1988
  cardId: c.cardID,
1980
1989
  courseId: c.courseID,
1981
- score: samplingKey,
1990
+ score: jitter,
1991
+ cardElo,
1982
1992
  provenance: [
1983
1993
  {
1984
1994
  strategy: "elo",
1985
1995
  strategyName: this.strategyName || this.name,
1986
1996
  strategyId: this.strategyId || "NAVIGATION_STRATEGY-ELO-default",
1987
1997
  action: "generated",
1988
- score: samplingKey,
1989
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userGlobalElo)}), relevance ${relevance.toFixed(3)}, key ${samplingKey.toFixed(3)}`
1998
+ score: jitter,
1999
+ reason: `new card near learner ELO: distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userGlobalElo)}), jitter ${jitter.toFixed(3)}`
1990
2000
  }
1991
2001
  ]
1992
2002
  };
@@ -2862,43 +2872,132 @@ var init_prescribed = __esm({
2862
2872
  }
2863
2873
  });
2864
2874
 
2875
+ // src/core/navigators/regulators.ts
2876
+ var regulators_exports = {};
2877
+ __export(regulators_exports, {
2878
+ DEFAULT_REGULATOR_CONFIG: () => DEFAULT_REGULATOR_CONFIG,
2879
+ INTAKE_CLOCK_KEY: () => INTAKE_CLOCK_KEY,
2880
+ applyReading: () => applyReading,
2881
+ frozenMsAt: () => frozenMsAt,
2882
+ intakeHours: () => intakeHours,
2883
+ intakeReading: () => intakeReading,
2884
+ resetIntakeClock: () => resetIntakeClock,
2885
+ reviewMassReading: () => reviewMassReading,
2886
+ reviewWeight: () => reviewWeight,
2887
+ stepIntakeClock: () => stepIntakeClock
2888
+ });
2889
+ function clamp01(x) {
2890
+ return Math.min(1, Math.max(0, x));
2891
+ }
2892
+ function reviewWeight(card, generatedScore, referenceScore) {
2893
+ if (card.reviewUrgency !== void 0 && generatedScore !== void 0 && generatedScore > 0) {
2894
+ return clamp01(card.reviewUrgency * (card.score / generatedScore));
2895
+ }
2896
+ return clamp01(card.score / referenceScore);
2897
+ }
2898
+ function reviewMassReading(reviews, generatedScores, config = DEFAULT_REGULATOR_CONFIG.reviewMass) {
2899
+ const mass = reviews.reduce(
2900
+ (m, c) => m + reviewWeight(c, generatedScores.get(c.cardId), config.referenceScore),
2901
+ 0
2902
+ );
2903
+ const multiplier = mass > config.healthyMass ? Math.pow(config.rate, (mass - config.healthyMass) / config.healthyMass) : 1;
2904
+ return {
2905
+ name: "review-mass",
2906
+ class: "review",
2907
+ urgency: mass,
2908
+ multiplier,
2909
+ applied: reviews.length,
2910
+ inputs: { due: reviews.length, mass, healthyMass: config.healthyMass }
2911
+ };
2912
+ }
2913
+ function resetIntakeClock(nowMs) {
2914
+ return { lastNewAt: new Date(nowMs).toISOString(), frozenMs: 0, unservableSince: null };
2915
+ }
2916
+ function frozenMsAt(state, nowMs) {
2917
+ const open = state.unservableSince ? Math.max(0, nowMs - Date.parse(state.unservableSince)) : 0;
2918
+ return state.frozenMs + open;
2919
+ }
2920
+ function intakeHours(state, nowMs) {
2921
+ const elapsed = nowMs - Date.parse(state.lastNewAt);
2922
+ return Math.max(0, elapsed - frozenMsAt(state, nowMs)) / 36e5;
2923
+ }
2924
+ function stepIntakeClock(state, nowMs, eligibleNew) {
2925
+ if (eligibleNew === 0 && !state.unservableSince) {
2926
+ return { ...state, unservableSince: new Date(nowMs).toISOString() };
2927
+ }
2928
+ if (eligibleNew > 0 && state.unservableSince) {
2929
+ return { ...state, frozenMs: frozenMsAt(state, nowMs), unservableSince: null };
2930
+ }
2931
+ return state;
2932
+ }
2933
+ function intakeReading(state, nowMs, counts, config = DEFAULT_REGULATOR_CONFIG.intake) {
2934
+ const hours = intakeHours(state, nowMs);
2935
+ const multiplier = counts.eligibleNew > 0 ? Math.pow(config.rate, hours / config.scaleHours) : 1;
2936
+ return {
2937
+ name: "intake",
2938
+ class: "new",
2939
+ urgency: hours,
2940
+ multiplier,
2941
+ applied: counts.eligibleNew,
2942
+ inputs: {
2943
+ hoursSinceNew: hours,
2944
+ frozenHours: frozenMsAt(state, nowMs) / 36e5,
2945
+ eligibleNew: counts.eligibleNew,
2946
+ newCandidates: counts.newCandidates
2947
+ }
2948
+ };
2949
+ }
2950
+ function applyReading(cards, reading) {
2951
+ if (reading.multiplier === 1) return;
2952
+ 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)}`;
2953
+ for (const card of cards) {
2954
+ card.score *= reading.multiplier;
2955
+ card.provenance.push({
2956
+ strategy: "regulator",
2957
+ strategyName: `Regulator: ${REGULATOR_LABEL[reading.name]}`,
2958
+ strategyId: `regulator-${reading.name}`,
2959
+ action: reading.multiplier > 1 ? "boosted" : "penalized",
2960
+ score: card.score,
2961
+ reason
2962
+ });
2963
+ }
2964
+ }
2965
+ var DEFAULT_REGULATOR_CONFIG, INTAKE_CLOCK_KEY, REGULATOR_LABEL;
2966
+ var init_regulators = __esm({
2967
+ "src/core/navigators/regulators.ts"() {
2968
+ "use strict";
2969
+ DEFAULT_REGULATOR_CONFIG = {
2970
+ reviewMass: { referenceScore: 0.95, healthyMass: 20, rate: 2 },
2971
+ intake: { rate: 2, scaleHours: 24 }
2972
+ };
2973
+ INTAKE_CLOCK_KEY = "IntakeClock";
2974
+ REGULATOR_LABEL = {
2975
+ "review-mass": "Review mass",
2976
+ intake: "Intake"
2977
+ };
2978
+ }
2979
+ });
2980
+
2865
2981
  // src/core/navigators/generators/srs.ts
2866
2982
  var srs_exports = {};
2867
2983
  __export(srs_exports, {
2868
2984
  default: () => SRSNavigator
2869
2985
  });
2870
- var import_moment, DEFAULT_HEALTHY_BACKLOG, BACKLOG_GROWTH_RATE, SRSNavigator;
2986
+ var import_moment, SRSNavigator;
2871
2987
  var init_srs = __esm({
2872
2988
  "src/core/navigators/generators/srs.ts"() {
2873
2989
  "use strict";
2874
2990
  import_moment = __toESM(require("moment"), 1);
2875
2991
  init_navigators();
2876
2992
  init_SrsDebugger();
2993
+ init_regulators();
2877
2994
  init_logger();
2878
- DEFAULT_HEALTHY_BACKLOG = 20;
2879
- BACKLOG_GROWTH_RATE = 2;
2880
2995
  SRSNavigator = class extends ContentNavigator {
2881
2996
  /** Human-readable name for CardGenerator interface */
2882
2997
  name;
2883
- /** Healthy backlog threshold - when exceeded, backlog pressure kicks in */
2884
- healthyBacklog;
2885
2998
  constructor(user, course, strategyData) {
2886
2999
  super(user, course, strategyData);
2887
3000
  this.name = strategyData?.name || "SRS";
2888
- const config = this.parseConfig(strategyData?.serializedData);
2889
- this.healthyBacklog = config.healthyBacklog ?? DEFAULT_HEALTHY_BACKLOG;
2890
- }
2891
- /**
2892
- * Parse configuration from serialized JSON.
2893
- */
2894
- parseConfig(serializedData) {
2895
- if (!serializedData) return {};
2896
- try {
2897
- return JSON.parse(serializedData);
2898
- } catch {
2899
- logger.warn("[SRS] Failed to parse strategy config, using defaults");
2900
- return {};
2901
- }
2902
3001
  }
2903
3002
  /**
2904
3003
  * Get review cards scored by urgency.
@@ -2906,7 +3005,6 @@ var init_srs = __esm({
2906
3005
  * Score formula combines:
2907
3006
  * - Relative overdueness: hoursOverdue / intervalHours
2908
3007
  * - Interval recency: exponential decay favoring shorter intervals
2909
- * - Backlog pressure: boost when due reviews exceed healthy threshold
2910
3008
  *
2911
3009
  * Cards not yet due are excluded (not scored as 0).
2912
3010
  *
@@ -2943,7 +3041,6 @@ var init_srs = __esm({
2943
3041
  }
2944
3042
  }
2945
3043
  }
2946
- const backlogMultiplier = this.computeBacklogMultiplier(dueReviews.length);
2947
3044
  const notDue = reviews.filter((r) => !now.isAfter(import_moment.default.utc(r.reviewTime)));
2948
3045
  let nextDueIn = null;
2949
3046
  if (notDue.length > 0) {
@@ -2954,9 +3051,8 @@ var init_srs = __esm({
2954
3051
  nextDueIn = until.asHours() < 1 ? `${Math.round(until.asMinutes())}m` : until.asHours() < 24 ? `${Math.round(until.asHours())}h` : `${Math.round(until.asDays())}d`;
2955
3052
  }
2956
3053
  if (dueReviews.length > 0) {
2957
- const pressureNote = backlogMultiplier > 1 ? ` [backlog pressure: \xD7${backlogMultiplier.toFixed(2)}]` : ` [healthy backlog]`;
2958
3054
  logger.info(
2959
- `[SRS] Course ${courseId}: ${dueReviews.length} reviews due now (of ${reviews.length} scheduled)${pressureNote}`
3055
+ `[SRS] Course ${courseId}: ${dueReviews.length} reviews due now (of ${reviews.length} scheduled)`
2960
3056
  );
2961
3057
  } else if (reviews.length > 0) {
2962
3058
  const sortedByDue = [...reviews].sort(
@@ -2973,11 +3069,12 @@ var init_srs = __esm({
2973
3069
  logger.info(`[SRS] Course ${courseId}: No reviews scheduled`);
2974
3070
  }
2975
3071
  const scored = dueReviews.map((review) => {
2976
- const { score, reason } = this.computeUrgencyScore(review, now, backlogMultiplier);
3072
+ const { score, urgency, reason } = this.computeUrgencyScore(review, now);
2977
3073
  return {
2978
3074
  cardId: review.cardId,
2979
3075
  courseId: review.courseId,
2980
3076
  score,
3077
+ reviewUrgency: urgency,
2981
3078
  reviewID: review._id,
2982
3079
  provenance: [
2983
3080
  {
@@ -2996,47 +3093,20 @@ var init_srs = __esm({
2996
3093
  courseId,
2997
3094
  scheduledTotal: reviews.length,
2998
3095
  dueNow: dueReviews.length,
2999
- healthyBacklog: this.healthyBacklog,
3000
- backlogMultiplier,
3001
- backlogGrowthRate: BACKLOG_GROWTH_RATE,
3096
+ healthyBacklog: DEFAULT_REGULATOR_CONFIG.reviewMass.healthyMass,
3097
+ reviewMass: null,
3098
+ backlogMultiplier: 1,
3099
+ backlogGrowthRate: DEFAULT_REGULATOR_CONFIG.reviewMass.rate,
3002
3100
  topReviewScore: sorted.length > 0 ? sorted[0].score : null,
3003
3101
  nextDueIn,
3004
3102
  timestamp: Date.now()
3005
3103
  });
3006
3104
  return { cards: sorted.slice(0, limit) };
3007
3105
  }
3008
- /**
3009
- * Compute the multiplicative backlog pressure based on number of due reviews.
3010
- *
3011
- * ×1.0 at or below the healthy threshold (no boost); above it, grows as
3012
- * BACKLOG_GROWTH_RATE raised to the excess expressed in multiples of the
3013
- * healthy threshold. Uncapped — self-regulating instead: reviews winning
3014
- * slots depletes dueCount, which drops the ratio and relaxes the multiplier
3015
- * next run.
3016
- *
3017
- * Examples (with default healthyBacklog=20, BACKLOG_GROWTH_RATE=1.5):
3018
- * - 10 due reviews → ×1.00 (healthy)
3019
- * - 20 due reviews → ×1.00 (at threshold, ratio 0)
3020
- * - 40 due reviews → ×1.50 (ratio 1, 2x threshold)
3021
- * - 60 due reviews → ×2.25 (ratio 2, 3x threshold — old hard cap was ×2.00 here)
3022
- * - 100 due reviews → ×5.06 (ratio 4, 5x threshold)
3023
- * - 160 due reviews → ×17.09 (ratio 7, 8x threshold)
3024
- *
3025
- * @param dueCount - Number of reviews currently due
3026
- * @returns Multiplier applied to review urgency (>= 1.0, unbounded)
3027
- */
3028
- computeBacklogMultiplier(dueCount) {
3029
- if (dueCount <= this.healthyBacklog) {
3030
- return 1;
3031
- }
3032
- const excess = dueCount - this.healthyBacklog;
3033
- const ratio = excess / this.healthyBacklog;
3034
- return Math.pow(BACKLOG_GROWTH_RATE, ratio);
3035
- }
3036
3106
  /**
3037
3107
  * Compute urgency score for a review card.
3038
3108
  *
3039
- * Three factors:
3109
+ * Two factors:
3040
3110
  * 1. Relative overdueness = hoursOverdue / intervalHours
3041
3111
  * - 2 days overdue on 3-day interval = 0.67 (urgent)
3042
3112
  * - 2 days overdue on 180-day interval = 0.01 (not urgent)
@@ -3046,20 +3116,14 @@ var init_srs = __esm({
3046
3116
  * - 30 days (720h) → ~0.56
3047
3117
  * - 180 days → ~0.30
3048
3118
  *
3049
- * 3. Backlog pressure = global *multiplier* when review backlog exceeds the
3050
- * healthy threshold (×1.0 healthy → exponential growth, uncapped, above it).
3051
- *
3052
- * Combined: (base 0.5 + urgency factors * 0.45) × backlog multiplier.
3053
- * Per-card range before pressure: ~0.57–0.95. NOT clamped to 1.0 — under a
3054
- * heavy backlog reviews scale onto the open scale to compete with (and exceed)
3055
- * new cards; there's no ceiling at all now, so a bad enough backlog always
3056
- * wins eventually — self-regulating because winning slots depletes dueCount.
3119
+ * Combined: base 0.5 + urgency factors * 0.45, so ~0.57–0.95 per card.
3120
+ * Backlog pressure is applied later, by the regulator stage, which can lift
3121
+ * reviews onto the open scale above new cards (see regulators.ts).
3057
3122
  *
3058
3123
  * @param review - The scheduled card to score
3059
3124
  * @param now - Current time
3060
- * @param backlogMultiplier - Pre-computed backlog multiplier (>= 1.0, unbounded)
3061
3125
  */
3062
- computeUrgencyScore(review, now, backlogMultiplier) {
3126
+ computeUrgencyScore(review, now) {
3063
3127
  const scheduledAt = import_moment.default.utc(review.scheduledAt);
3064
3128
  const due = import_moment.default.utc(review.reviewTime);
3065
3129
  const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
@@ -3068,20 +3132,16 @@ var init_srs = __esm({
3068
3132
  const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
3069
3133
  const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
3070
3134
  const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
3071
- const baseScore = 0.5 + urgency * 0.45;
3072
- const score = baseScore * backlogMultiplier;
3135
+ const score = 0.5 + urgency * 0.45;
3073
3136
  const reasonParts = [
3074
3137
  `${Math.round(hoursOverdue)}h overdue`,
3075
3138
  `interval: ${Math.round(intervalHours)}h`,
3076
3139
  `relative: ${relativeOverdue.toFixed(2)}`,
3077
3140
  `recency: ${recencyFactor.toFixed(2)}`
3078
3141
  ];
3079
- if (backlogMultiplier > 1) {
3080
- reasonParts.push(`backlog: \xD7${backlogMultiplier.toFixed(2)}`);
3081
- }
3082
3142
  reasonParts.push("review");
3083
3143
  const reason = reasonParts.join(", ");
3084
- return { score, reason };
3144
+ return { score, urgency, reason };
3085
3145
  }
3086
3146
  };
3087
3147
  }
@@ -3136,6 +3196,8 @@ var init_WeightedFilter = __esm({
3136
3196
  init_contentNavigationStrategy();
3137
3197
  WeightedFilter = class {
3138
3198
  name;
3199
+ kind;
3200
+ liveOnly;
3139
3201
  inner;
3140
3202
  learnable;
3141
3203
  staticWeight;
@@ -3143,6 +3205,8 @@ var init_WeightedFilter = __esm({
3143
3205
  constructor(inner, learnable = DEFAULT_LEARNABLE_WEIGHT, staticWeight = false, strategyId) {
3144
3206
  this.inner = inner;
3145
3207
  this.name = inner.name;
3208
+ this.kind = inner.kind;
3209
+ this.liveOnly = inner.liveOnly;
3146
3210
  this.learnable = learnable;
3147
3211
  this.staticWeight = staticWeight;
3148
3212
  this.strategyId = strategyId;
@@ -3207,58 +3271,175 @@ var init_WeightedFilter = __esm({
3207
3271
  // src/core/navigators/filters/eloDistance.ts
3208
3272
  var eloDistance_exports = {};
3209
3273
  __export(eloDistance_exports, {
3210
- DEFAULT_HALF_LIFE: () => DEFAULT_HALF_LIFE,
3211
- DEFAULT_MAX_MULTIPLIER: () => DEFAULT_MAX_MULTIPLIER,
3212
- DEFAULT_MIN_MULTIPLIER: () => DEFAULT_MIN_MULTIPLIER,
3213
- createEloDistanceFilter: () => createEloDistanceFilter
3274
+ DEFAULT_ELO_DISTANCE_CONFIG: () => DEFAULT_ELO_DISTANCE_CONFIG,
3275
+ createEloDistanceFilter: () => createEloDistanceFilter,
3276
+ default: () => EloDistanceFilter,
3277
+ mountMultiDimEloToggle: () => mountMultiDimEloToggle,
3278
+ tagAwareGap: () => tagAwareGap
3214
3279
  });
3215
3280
  function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
3216
3281
  const normalizedDistance = distance / halfLife;
3217
3282
  const decay = Math.exp(-(normalizedDistance * normalizedDistance));
3218
3283
  return minMultiplier + (maxMultiplier - minMultiplier) * decay;
3219
3284
  }
3285
+ function resolveConfig(config) {
3286
+ return { ...DEFAULT_ELO_DISTANCE_CONFIG, ...config };
3287
+ }
3288
+ function readMultiDimElo() {
3289
+ try {
3290
+ return typeof localStorage !== "undefined" && localStorage.getItem(MULTI_DIM_ELO_KEY) === "true";
3291
+ } catch {
3292
+ return false;
3293
+ }
3294
+ }
3295
+ function mountMultiDimEloToggle() {
3296
+ if (typeof window === "undefined") return;
3297
+ const win = window;
3298
+ win.skuilder = win.skuilder || {};
3299
+ Object.defineProperty(win.skuilder, "multiDimElo", {
3300
+ configurable: true,
3301
+ enumerable: true,
3302
+ get: () => multiDimElo,
3303
+ set: (on) => {
3304
+ multiDimElo = on === true;
3305
+ try {
3306
+ if (multiDimElo) localStorage.setItem(MULTI_DIM_ELO_KEY, "true");
3307
+ else localStorage.removeItem(MULTI_DIM_ELO_KEY);
3308
+ } catch (e) {
3309
+ logger.warn(`[EloDistance] multiDimElo not persisted (localStorage unavailable): ${e}`);
3310
+ }
3311
+ logger.info(
3312
+ `[EloDistance] multiDimElo ${multiDimElo ? "on: tag-aware" : "off: per strategy config"} ELO distance from the next replan`
3313
+ );
3314
+ }
3315
+ });
3316
+ }
3317
+ function tagAwareGap(cardTags, cardElo, userElo, minTagCount) {
3318
+ const globalGap = cardElo.global.score - userElo.global.score;
3319
+ const tags = [];
3320
+ for (const tag of cardTags) {
3321
+ const user = userElo.tags[tag];
3322
+ if (!user || user.score === COUNT_ONLY_SENTINEL || user.count < minTagCount) continue;
3323
+ const card = cardElo.tags[tag]?.score ?? cardElo.global.score;
3324
+ tags.push({
3325
+ tag,
3326
+ gap: card - user.score,
3327
+ weight: user.count / (user.count + TAG_CONFIDENCE_HALF)
3328
+ });
3329
+ }
3330
+ if (tags.length === 0) return { gap: globalGap, globalGap, tags };
3331
+ const total = tags.reduce((w, t) => w + t.weight, 0);
3332
+ const tagGap = tags.reduce((g, t) => g + t.weight * t.gap, 0) / total;
3333
+ const lambda = total / (total + 1);
3334
+ return { gap: lambda * tagGap + (1 - lambda) * globalGap, globalGap, tags };
3335
+ }
3336
+ function tagReason(tags, globalGap) {
3337
+ 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(", ");
3338
+ const more = tags.length > 3 ? `, +${tags.length - 3} more` : "";
3339
+ return ` on ${tags.length} shared tag(s) [${shown}${more}] (global ${globalGap >= 0 ? "+" : ""}${Math.round(globalGap)})`;
3340
+ }
3341
+ async function applyEloDistance(cards, context, config, source) {
3342
+ const { course, userElo, userCourseElo } = context;
3343
+ const { halfLife, minMultiplier, maxMultiplier } = config;
3344
+ const tagAware = (config.tagAware || multiDimElo) && userCourseElo !== void 0;
3345
+ const missing = cards.filter((c) => tagAware || c.cardElo === void 0).map((c) => c.cardId);
3346
+ const fetched = /* @__PURE__ */ new Map();
3347
+ if (missing.length > 0) {
3348
+ const elos = await course.getCardEloData(missing);
3349
+ missing.forEach((id, i) => {
3350
+ if (elos[i]) fetched.set(id, elos[i]);
3351
+ });
3352
+ }
3353
+ return cards.map((card) => {
3354
+ const full = fetched.get(card.cardId);
3355
+ const cardElo = full?.global?.score ?? card.cardElo ?? DEFAULT_CARD_ELO;
3356
+ let distance = Math.abs(cardElo - userElo);
3357
+ let how = "";
3358
+ if (tagAware) {
3359
+ const t = full ? tagAwareGap(card.tags ?? [], full, userCourseElo, config.minTagCount) : void 0;
3360
+ if (t) distance = Math.abs(t.gap);
3361
+ how = t?.tags.length ? `, tag-aware${tagReason(t.tags, t.globalGap)}` : ", tag-aware: global (no shared tags)";
3362
+ }
3363
+ const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
3364
+ const newScore = card.score * multiplier;
3365
+ const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
3366
+ return {
3367
+ ...card,
3368
+ cardElo,
3369
+ score: newScore,
3370
+ provenance: [
3371
+ ...card.provenance,
3372
+ {
3373
+ strategy: "eloDistance",
3374
+ strategyName: source.name,
3375
+ strategyId: source.strategyId,
3376
+ action,
3377
+ score: newScore,
3378
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)})${how} \u2192 ${multiplier.toFixed(2)}x`
3379
+ }
3380
+ ]
3381
+ };
3382
+ });
3383
+ }
3220
3384
  function createEloDistanceFilter(config) {
3221
- const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
3222
- const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
3223
- const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
3385
+ const resolved = resolveConfig(config);
3386
+ const source = { name: "ELO Distance Filter", strategyId: "ELO_DISTANCE_FILTER" };
3224
3387
  return {
3225
- name: "ELO Distance Filter",
3226
- async transform(cards, context) {
3227
- const { course, userElo } = context;
3228
- const cardIds = cards.map((c) => c.cardId);
3229
- const cardElos = await course.getCardEloData(cardIds);
3230
- return cards.map((card, i) => {
3231
- const cardElo = cardElos[i]?.global?.score ?? 1e3;
3232
- const distance = Math.abs(cardElo - userElo);
3233
- const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
3234
- const newScore = card.score * multiplier;
3235
- const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
3236
- return {
3237
- ...card,
3238
- score: newScore,
3239
- provenance: [
3240
- ...card.provenance,
3241
- {
3242
- strategy: "eloDistance",
3243
- strategyName: "ELO Distance Filter",
3244
- strategyId: "ELO_DISTANCE_FILTER",
3245
- action,
3246
- score: newScore,
3247
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
3248
- }
3249
- ]
3250
- };
3251
- });
3252
- }
3388
+ name: source.name,
3389
+ kind: "signal",
3390
+ liveOnly: true,
3391
+ transform: (cards, context) => applyEloDistance(cards, context, resolved, source)
3253
3392
  };
3254
3393
  }
3255
- var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
3394
+ var DEFAULT_ELO_DISTANCE_CONFIG, TAG_CONFIDENCE_HALF, COUNT_ONLY_SENTINEL, DEFAULT_CARD_ELO, MULTI_DIM_ELO_KEY, multiDimElo, EloDistanceFilter;
3256
3395
  var init_eloDistance = __esm({
3257
3396
  "src/core/navigators/filters/eloDistance.ts"() {
3258
3397
  "use strict";
3259
- DEFAULT_HALF_LIFE = 200;
3260
- DEFAULT_MIN_MULTIPLIER = 0.3;
3261
- DEFAULT_MAX_MULTIPLIER = 1;
3398
+ init_navigators();
3399
+ init_logger();
3400
+ DEFAULT_ELO_DISTANCE_CONFIG = {
3401
+ halfLife: 300,
3402
+ minMultiplier: 0.05,
3403
+ maxMultiplier: 1,
3404
+ tagAware: false,
3405
+ minTagCount: 3
3406
+ };
3407
+ TAG_CONFIDENCE_HALF = 10;
3408
+ COUNT_ONLY_SENTINEL = -1;
3409
+ DEFAULT_CARD_ELO = 1e3;
3410
+ MULTI_DIM_ELO_KEY = "skuilder:multiDimElo";
3411
+ multiDimElo = readMultiDimElo();
3412
+ mountMultiDimEloToggle();
3413
+ EloDistanceFilter = class _EloDistanceFilter extends ContentNavigator {
3414
+ name;
3415
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3416
+ static kind = "signal";
3417
+ kind = _EloDistanceFilter.kind;
3418
+ liveOnly = true;
3419
+ config;
3420
+ constructor(user, course, strategyData) {
3421
+ super(user, course, strategyData);
3422
+ this.name = strategyData.name || "ELO Distance";
3423
+ let parsed;
3424
+ try {
3425
+ parsed = strategyData.serializedData ? JSON.parse(strategyData.serializedData) : void 0;
3426
+ } catch {
3427
+ parsed = void 0;
3428
+ }
3429
+ this.config = resolveConfig(parsed);
3430
+ }
3431
+ transform(cards, context) {
3432
+ return applyEloDistance(cards, context, this.config, {
3433
+ name: this.name,
3434
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-eloDistance-default"
3435
+ });
3436
+ }
3437
+ async getWeightedCards(_limit) {
3438
+ throw new Error(
3439
+ "EloDistanceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
3440
+ );
3441
+ }
3442
+ };
3262
3443
  }
3263
3444
  });
3264
3445
 
@@ -3275,10 +3456,13 @@ var init_hierarchyDefinition = __esm({
3275
3456
  import_common6 = require("@vue-skuilder/common");
3276
3457
  init_logger();
3277
3458
  DEFAULT_MIN_COUNT2 = 3;
3278
- HierarchyDefinitionNavigator = class extends ContentNavigator {
3459
+ HierarchyDefinitionNavigator = class _HierarchyDefinitionNavigator extends ContentNavigator {
3279
3460
  config;
3280
3461
  /** Human-readable name for CardFilter interface */
3281
3462
  name;
3463
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3464
+ static kind = "gate";
3465
+ kind = _HierarchyDefinitionNavigator.kind;
3282
3466
  constructor(user, course, strategyData) {
3283
3467
  super(user, course, strategyData);
3284
3468
  this.config = this.parseConfig(strategyData.serializedData);
@@ -3545,10 +3729,13 @@ var init_userTagPreference = __esm({
3545
3729
  "src/core/navigators/filters/userTagPreference.ts"() {
3546
3730
  "use strict";
3547
3731
  init_navigators();
3548
- UserTagPreferenceFilter = class extends ContentNavigator {
3732
+ UserTagPreferenceFilter = class _UserTagPreferenceFilter extends ContentNavigator {
3549
3733
  _strategyData;
3550
3734
  /** Human-readable name for CardFilter interface */
3551
3735
  name;
3736
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3737
+ static kind = "signal";
3738
+ kind = _UserTagPreferenceFilter.kind;
3552
3739
  constructor(user, course, strategyData) {
3553
3740
  super(user, course, strategyData);
3554
3741
  this._strategyData = strategyData;
@@ -3658,6 +3845,7 @@ var init_userTagPreference = __esm({
3658
3845
  // src/core/navigators/filters/index.ts
3659
3846
  var filters_exports = {};
3660
3847
  __export(filters_exports, {
3848
+ EloDistanceFilter: () => EloDistanceFilter,
3661
3849
  UserTagPreferenceFilter: () => UserTagPreferenceFilter,
3662
3850
  createEloDistanceFilter: () => createEloDistanceFilter
3663
3851
  });
@@ -3696,10 +3884,13 @@ var init_interferenceMitigator = __esm({
3696
3884
  DEFAULT_MIN_COUNT3 = 10;
3697
3885
  DEFAULT_MIN_ELAPSED_DAYS = 3;
3698
3886
  DEFAULT_INTERFERENCE_DECAY = 0.8;
3699
- InterferenceMitigatorNavigator = class extends ContentNavigator {
3887
+ InterferenceMitigatorNavigator = class _InterferenceMitigatorNavigator extends ContentNavigator {
3700
3888
  config;
3701
3889
  /** Human-readable name for CardFilter interface */
3702
3890
  name;
3891
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3892
+ static kind = "signal";
3893
+ kind = _InterferenceMitigatorNavigator.kind;
3703
3894
  /** Precomputed map: tag -> set of { partner, decay } it interferes with */
3704
3895
  interferenceMap;
3705
3896
  constructor(user, course, strategyData) {
@@ -3915,10 +4106,13 @@ var init_relativePriority = __esm({
3915
4106
  DEFAULT_PRIORITY = 0.5;
3916
4107
  DEFAULT_PRIORITY_INFLUENCE = 0.5;
3917
4108
  DEFAULT_COMBINE_MODE = "max";
3918
- RelativePriorityNavigator = class extends ContentNavigator {
4109
+ RelativePriorityNavigator = class _RelativePriorityNavigator extends ContentNavigator {
3919
4110
  config;
3920
4111
  /** Human-readable name for CardFilter interface */
3921
4112
  name;
4113
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
4114
+ static kind = "signal";
4115
+ kind = _RelativePriorityNavigator.kind;
3922
4116
  constructor(user, course, strategyData) {
3923
4117
  super(user, course, strategyData);
3924
4118
  this.config = this.parseConfig(strategyData.serializedData);
@@ -4572,6 +4766,8 @@ var init_Pipeline = __esm({
4572
4766
  init_orchestration();
4573
4767
  init_PipelineDebugger();
4574
4768
  init_diversityRerank();
4769
+ init_regulators();
4770
+ init_SrsDebugger();
4575
4771
  VERBOSE_RESULTS = true;
4576
4772
  Pipeline = class extends ContentNavigator {
4577
4773
  generator;
@@ -4597,6 +4793,13 @@ var init_Pipeline = __esm({
4597
4793
  * getWeightedCards() call, then cleared.
4598
4794
  */
4599
4795
  _ephemeralHints = null;
4796
+ /**
4797
+ * The intake valve's clock (see regulators.ts), loaded from strategy state on
4798
+ * first use and kept in memory. Writes are chained so a presentation and a
4799
+ * run can't race each other's revision.
4800
+ */
4801
+ _intakeClock = null;
4802
+ _intakeClockWrite = Promise.resolve();
4600
4803
  /**
4601
4804
  * Create a new pipeline.
4602
4805
  *
@@ -4671,13 +4874,12 @@ var init_Pipeline = __esm({
4671
4874
  }
4672
4875
  }
4673
4876
  generatorSummaries = Array.from(genMap.entries()).map(([name, data]) => {
4674
- const newCards = data.cards.filter((c) => c.provenance[0]?.reason?.includes("new card"));
4675
- const reviewCards = data.cards.filter((c) => c.provenance[0]?.reason?.includes("review"));
4877
+ const reviewCount = data.cards.filter((c) => c.reviewID).length;
4676
4878
  return {
4677
4879
  name,
4678
4880
  cardCount: data.cards.length,
4679
- newCount: newCards.length,
4680
- reviewCount: reviewCards.length,
4881
+ newCount: data.cards.length - reviewCount,
4882
+ reviewCount,
4681
4883
  topScore: Math.max(...data.cards.map((c) => c.score), 0)
4682
4884
  };
4683
4885
  });
@@ -4713,19 +4915,24 @@ var init_Pipeline = __esm({
4713
4915
  cards.filter((c) => c.provenance.some((p) => p.strategy === "prescribed")).map((c) => c.cardId)
4714
4916
  );
4715
4917
  const filterImpacts = [];
4918
+ const generatedScores = new Map(cards.map((c) => [c.cardId, c.score]));
4919
+ const gated = /* @__PURE__ */ new Set();
4716
4920
  for (const filter of this.filters) {
4717
4921
  const beforeCount = cards.length;
4718
4922
  const beforeScores = new Map(cards.map((c) => [c.cardId, c.score]));
4719
4923
  cards = await filter.transform(cards, context);
4720
4924
  let boosted = 0, penalized = 0, passed = 0;
4721
4925
  const removed = beforeCount - cards.length;
4926
+ const kind = filter.kind ?? "gate";
4722
4927
  for (const card of cards) {
4723
4928
  const before = beforeScores.get(card.cardId) ?? 0;
4724
4929
  if (card.score > before) boosted++;
4725
- else if (card.score < before) penalized++;
4726
- else passed++;
4930
+ else if (card.score < before) {
4931
+ penalized++;
4932
+ if (kind === "gate") gated.add(card.cardId);
4933
+ } else passed++;
4727
4934
  }
4728
- filterImpacts.push({ name: filter.name, boosted, penalized, passed, removed });
4935
+ filterImpacts.push({ name: filter.name, kind, boosted, penalized, passed, removed });
4729
4936
  if (prescribedIds.size > 0) {
4730
4937
  const survivingIds = new Set(cards.map((c) => c.cardId));
4731
4938
  const killedPrescribed = [...prescribedIds].filter((id) => !survivingIds.has(id));
@@ -4741,6 +4948,7 @@ var init_Pipeline = __esm({
4741
4948
  }
4742
4949
  const scoredCards = cards;
4743
4950
  cards = cards.filter((c) => c.score > 0);
4951
+ const regulators = await this.regulate(cards, generatedScores, gated);
4744
4952
  const hints = this._ephemeralHints;
4745
4953
  if (hints) {
4746
4954
  this._ephemeralHints = null;
@@ -4777,7 +4985,8 @@ var init_Pipeline = __esm({
4777
4985
  result,
4778
4986
  context.userElo,
4779
4987
  hints ?? void 0,
4780
- scoredCards
4988
+ scoredCards,
4989
+ regulators
4781
4990
  );
4782
4991
  captureRun(report);
4783
4992
  } catch (e) {
@@ -4956,6 +5165,77 @@ var init_Pipeline = __esm({
4956
5165
  logger.info(`[Pipeline] Hints applied: ${beforeCount} \u2192 ${cards.length} cards`);
4957
5166
  return cards;
4958
5167
  }
5168
+ /**
5169
+ * The regulator stage: measure each class's pressure and scale it.
5170
+ *
5171
+ * - Review mass: every due review's SRS urgency times the filters' net
5172
+ * effect on it.
5173
+ * - Intake: servable hours since a new card was presented, applied only to
5174
+ * eligible new cards (no gate penalized them). With none eligible, the
5175
+ * clock freezes.
5176
+ *
5177
+ * Mutates `cards` in place; returns the readings for the run report.
5178
+ */
5179
+ async regulate(cards, generatedScores, gated) {
5180
+ const config = DEFAULT_REGULATOR_CONFIG;
5181
+ const reviews = cards.filter((c) => c.reviewID);
5182
+ const newCards = cards.filter((c) => !c.reviewID);
5183
+ const eligibleNew = newCards.filter((c) => !gated.has(c.cardId));
5184
+ const mass = reviewMassReading(reviews, generatedScores, config.reviewMass);
5185
+ applyReading(reviews, mass);
5186
+ noteReviewPressure(this.course.getCourseID(), {
5187
+ mass: mass.urgency,
5188
+ healthyMass: config.reviewMass.healthyMass,
5189
+ rate: config.reviewMass.rate,
5190
+ multiplier: mass.multiplier
5191
+ });
5192
+ const now = Date.now();
5193
+ const clock = await this.loadIntakeClock(now);
5194
+ const stepped = stepIntakeClock(clock, now, eligibleNew.length);
5195
+ if (stepped !== clock) this.saveIntakeClock(stepped);
5196
+ const intake = intakeReading(
5197
+ stepped,
5198
+ now,
5199
+ { eligibleNew: eligibleNew.length, newCandidates: newCards.length },
5200
+ config.intake
5201
+ );
5202
+ applyReading(eligibleNew, intake);
5203
+ logger.info(
5204
+ `[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)}`
5205
+ );
5206
+ return [mass, intake];
5207
+ }
5208
+ /**
5209
+ * A card was presented. A new card's first presentation discharges the
5210
+ * intake valve: its clock restarts. Called by the SessionController.
5211
+ */
5212
+ notePresented(card) {
5213
+ if (card.status !== "new" || card.courseId !== this.course?.getCourseID()) return;
5214
+ this.saveIntakeClock(resetIntakeClock(Date.now()));
5215
+ }
5216
+ async loadIntakeClock(nowMs) {
5217
+ if (this._intakeClock) return this._intakeClock;
5218
+ let stored = null;
5219
+ try {
5220
+ stored = await this.user.getStrategyState(
5221
+ this.course.getCourseID(),
5222
+ INTAKE_CLOCK_KEY
5223
+ );
5224
+ } catch (e) {
5225
+ logger.warn(`[Pipeline:regulators] Could not read the intake clock: ${e}`);
5226
+ }
5227
+ if (stored) {
5228
+ this._intakeClock = stored;
5229
+ } else {
5230
+ this.saveIntakeClock(resetIntakeClock(nowMs));
5231
+ }
5232
+ return this._intakeClock;
5233
+ }
5234
+ saveIntakeClock(state) {
5235
+ this._intakeClock = state;
5236
+ const courseId = this.course.getCourseID();
5237
+ 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}`));
5238
+ }
4959
5239
  /**
4960
5240
  * Build shared context for generator and filters.
4961
5241
  *
@@ -4966,10 +5246,11 @@ var init_Pipeline = __esm({
4966
5246
  */
4967
5247
  async buildContext() {
4968
5248
  let userElo = 1e3;
5249
+ let userCourseElo;
4969
5250
  try {
4970
5251
  const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
4971
- const courseElo = (0, import_common8.toCourseElo)(courseReg.elo);
4972
- userElo = courseElo.global.score;
5252
+ userCourseElo = (0, import_common8.toCourseElo)(courseReg.elo);
5253
+ userElo = userCourseElo.global.score;
4973
5254
  } catch (e) {
4974
5255
  logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
4975
5256
  }
@@ -4981,6 +5262,7 @@ var init_Pipeline = __esm({
4981
5262
  user: this.user,
4982
5263
  course: this.course,
4983
5264
  userElo,
5265
+ ...userCourseElo ? { userCourseElo } : {},
4984
5266
  orchestration
4985
5267
  };
4986
5268
  }
@@ -5094,7 +5376,7 @@ var init_Pipeline = __esm({
5094
5376
  cards = await this.hydrateTags(cards);
5095
5377
  const fullPool = cards.slice();
5096
5378
  const context = await this.buildContext();
5097
- for (const filter of this.filters) {
5379
+ for (const filter of this.forecastFilters()) {
5098
5380
  cards = await filter.transform(cards, context);
5099
5381
  }
5100
5382
  if (opts?.hints) {
@@ -5113,6 +5395,14 @@ var init_Pipeline = __esm({
5113
5395
  cards.sort((a, b) => b.score - a.score);
5114
5396
  return opts?.limit ? cards.slice(0, opts.limit) : cards;
5115
5397
  }
5398
+ /**
5399
+ * The filters a forecast or card-space scan applies. Those start every card at
5400
+ * 1.0 without a generator, so they skip `liveOnly` filters (ELO distance),
5401
+ * which only make sense against generator scores.
5402
+ */
5403
+ forecastFilters() {
5404
+ return this.filters.filter((f) => !f.liveOnly);
5405
+ }
5116
5406
  /**
5117
5407
  * Scan every card in the course through the filter chain and report
5118
5408
  * how many are "well indicated" (score >= threshold) for the current user.
@@ -5134,7 +5424,7 @@ var init_Pipeline = __esm({
5134
5424
  cards = await this.hydrateTags(cards);
5135
5425
  const context = await this.buildContext();
5136
5426
  const filterBreakdown = [];
5137
- for (const filter of this.filters) {
5427
+ for (const filter of this.forecastFilters()) {
5138
5428
  cards = await filter.transform(cards, context);
5139
5429
  const wi = cards.filter((c) => c.score >= THRESHOLD).length;
5140
5430
  filterBreakdown.push({ name: filter.name, wellIndicated: wi });
@@ -5198,6 +5488,7 @@ var init_Pipeline = __esm({
5198
5488
  // src/core/navigators/defaults.ts
5199
5489
  var defaults_exports = {};
5200
5490
  __export(defaults_exports, {
5491
+ createDefaultEloDistanceStrategy: () => createDefaultEloDistanceStrategy,
5201
5492
  createDefaultEloStrategy: () => createDefaultEloStrategy,
5202
5493
  createDefaultPipeline: () => createDefaultPipeline,
5203
5494
  createDefaultSrsStrategy: () => createDefaultSrsStrategy
@@ -5224,12 +5515,28 @@ function createDefaultSrsStrategy(courseId) {
5224
5515
  serializedData: ""
5225
5516
  };
5226
5517
  }
5518
+ function createDefaultEloDistanceStrategy(courseId) {
5519
+ return {
5520
+ _id: "NAVIGATION_STRATEGY-eloDistance-default",
5521
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
5522
+ name: "ELO Distance (default)",
5523
+ description: "Scales every candidate, new or review, by its distance from the learner's ELO",
5524
+ implementingClass: "eloDistance" /* ELO_DISTANCE */,
5525
+ course: courseId,
5526
+ // Explicit, though the filter would default to it anyway: views show what runs.
5527
+ serializedData: JSON.stringify(DEFAULT_ELO_DISTANCE_CONFIG)
5528
+ };
5529
+ }
5227
5530
  function createDefaultPipeline(user, course) {
5228
5531
  const courseId = course.getCourseID();
5229
5532
  const eloNavigator = new ELONavigator(user, course, createDefaultEloStrategy(courseId));
5230
5533
  const srsNavigator = new SRSNavigator(user, course, createDefaultSrsStrategy(courseId));
5231
5534
  const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);
5232
- const eloDistanceFilter = createEloDistanceFilter();
5535
+ const eloDistanceFilter = new EloDistanceFilter(
5536
+ user,
5537
+ course,
5538
+ createDefaultEloDistanceStrategy(courseId)
5539
+ );
5233
5540
  return new Pipeline(compositeGenerator, [eloDistanceFilter], user, course);
5234
5541
  }
5235
5542
  var init_defaults = __esm({
@@ -5245,6 +5552,131 @@ var init_defaults = __esm({
5245
5552
  }
5246
5553
  });
5247
5554
 
5555
+ // src/core/navigators/pipelinePlan.ts
5556
+ var pipelinePlan_exports = {};
5557
+ __export(pipelinePlan_exports, {
5558
+ PIPELINE_STAGES: () => PIPELINE_STAGES,
5559
+ planPipeline: () => planPipeline
5560
+ });
5561
+ function planned(strategy, role, origin) {
5562
+ const kind = role === "filter" /* FILTER */ ? getRegisteredFilterKind(strategy.implementingClass) : void 0;
5563
+ return {
5564
+ role,
5565
+ origin,
5566
+ name: strategy.name,
5567
+ implementingClass: strategy.implementingClass,
5568
+ strategy,
5569
+ ...kind ? { kind } : {}
5570
+ };
5571
+ }
5572
+ function planPipeline(strategies, courseId) {
5573
+ if (strategies.length === 0) {
5574
+ return {
5575
+ kind: "default",
5576
+ generators: [
5577
+ planned(createDefaultEloStrategy(courseId), "generator" /* GENERATOR */, "default-pipeline"),
5578
+ planned(createDefaultSrsStrategy(courseId), "generator" /* GENERATOR */, "default-pipeline")
5579
+ ],
5580
+ filters: [
5581
+ planned(
5582
+ createDefaultEloDistanceStrategy(courseId),
5583
+ "filter" /* FILTER */,
5584
+ "default-pipeline"
5585
+ )
5586
+ ],
5587
+ skipped: [],
5588
+ warnings: [],
5589
+ notes: [],
5590
+ regulators: DEFAULT_REGULATOR_CONFIG
5591
+ };
5592
+ }
5593
+ const generators = [];
5594
+ const filters = [];
5595
+ const skipped = [];
5596
+ const warnings = [];
5597
+ for (const s of strategies) {
5598
+ if (isGenerator(s.implementingClass)) {
5599
+ generators.push(planned(s, "generator" /* GENERATOR */, "strategy-doc"));
5600
+ } else if (isFilter(s.implementingClass)) {
5601
+ filters.push(planned(s, "filter" /* FILTER */, "strategy-doc"));
5602
+ } else {
5603
+ skipped.push({ strategy: s, reason: "not a registered generator or filter" });
5604
+ warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
5605
+ }
5606
+ }
5607
+ const declared = new Set(generators.map((g) => g.implementingClass));
5608
+ if (!declared.has(createDefaultEloStrategy(courseId).implementingClass)) {
5609
+ generators.push(
5610
+ planned(createDefaultEloStrategy(courseId), "generator" /* GENERATOR */, "assembler-default")
5611
+ );
5612
+ }
5613
+ if (!declared.has(createDefaultSrsStrategy(courseId).implementingClass)) {
5614
+ generators.push(
5615
+ planned(createDefaultSrsStrategy(courseId), "generator" /* GENERATOR */, "assembler-default")
5616
+ );
5617
+ }
5618
+ const eloDistance = createDefaultEloDistanceStrategy(courseId);
5619
+ if (!filters.some((f) => f.implementingClass === eloDistance.implementingClass)) {
5620
+ filters.push(planned(eloDistance, "filter" /* FILTER */, "assembler-default"));
5621
+ }
5622
+ filters.sort((a, b) => a.name.localeCompare(b.name));
5623
+ return {
5624
+ kind: "assembled",
5625
+ generators,
5626
+ filters,
5627
+ skipped,
5628
+ warnings,
5629
+ notes: [],
5630
+ regulators: DEFAULT_REGULATOR_CONFIG
5631
+ };
5632
+ }
5633
+ var PIPELINE_STAGES;
5634
+ var init_pipelinePlan = __esm({
5635
+ "src/core/navigators/pipelinePlan.ts"() {
5636
+ "use strict";
5637
+ init_navigators();
5638
+ init_regulators();
5639
+ init_defaults();
5640
+ PIPELINE_STAGES = [
5641
+ {
5642
+ key: "generate",
5643
+ title: "Generate",
5644
+ 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."
5645
+ },
5646
+ {
5647
+ key: "filter",
5648
+ title: "Filter",
5649
+ 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."
5650
+ },
5651
+ {
5652
+ key: "drop-zero",
5653
+ title: "Drop zero scores",
5654
+ summary: "Candidates whose score reached 0 leave the pool."
5655
+ },
5656
+ {
5657
+ key: "regulate",
5658
+ title: "Regulate",
5659
+ 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."
5660
+ },
5661
+ {
5662
+ key: "hints",
5663
+ title: "Apply hints",
5664
+ 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."
5665
+ },
5666
+ {
5667
+ key: "diversity",
5668
+ title: "Diversity re-rank",
5669
+ 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."
5670
+ },
5671
+ {
5672
+ key: "select",
5673
+ title: "Select",
5674
+ summary: "Highest scores first, up to the run's limit. The session mixes them into its supply queue."
5675
+ }
5676
+ ];
5677
+ }
5678
+ });
5679
+
5248
5680
  // src/core/navigators/PipelineAssembler.ts
5249
5681
  var PipelineAssembler_exports = {};
5250
5682
  __export(PipelineAssembler_exports, {
@@ -5259,16 +5691,16 @@ var init_PipelineAssembler = __esm({
5259
5691
  init_Pipeline();
5260
5692
  init_logger();
5261
5693
  init_CompositeGenerator();
5262
- init_defaults();
5694
+ init_pipelinePlan();
5263
5695
  PipelineAssembler = class {
5264
5696
  /**
5265
5697
  * Assembles a navigation pipeline from strategy documents.
5266
5698
  *
5267
- * 1. Separates into generators and filters by role
5268
- * 2. Validates at least one generator exists (or creates default ELO)
5269
- * 3. Instantiates generators - wraps multiple in CompositeGenerator
5270
- * 4. Instantiates filters
5271
- * 5. Returns Pipeline(generator, filters)
5699
+ * 1. Plans: classifies by role, adds default ELO/SRS and ELO distance, orders filters
5700
+ * (`planPipeline`)
5701
+ * 2. Instantiates generators - wraps multiple in CompositeGenerator
5702
+ * 3. Instantiates filters
5703
+ * 4. Returns Pipeline(generator, filters)
5272
5704
  *
5273
5705
  * @param input - Strategy documents plus user/course interfaces
5274
5706
  * @returns Assembled pipeline and any warnings
@@ -5284,28 +5716,17 @@ var init_PipelineAssembler = __esm({
5284
5716
  warnings
5285
5717
  };
5286
5718
  }
5287
- const generatorStrategies = [];
5288
- const filterStrategies = [];
5289
- for (const s of strategies) {
5290
- if (isGenerator(s.implementingClass)) {
5291
- generatorStrategies.push(s);
5292
- } else if (isFilter(s.implementingClass)) {
5293
- filterStrategies.push(s);
5294
- } else {
5295
- warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
5719
+ const plan = planPipeline(strategies, course.getCourseID());
5720
+ warnings.push(...plan.warnings);
5721
+ for (const n of [...plan.generators, ...plan.filters]) {
5722
+ if (n.origin === "assembler-default") {
5723
+ logger.debug(
5724
+ `[PipelineAssembler] No ${n.implementingClass} ${n.role} configured, adding default`
5725
+ );
5296
5726
  }
5297
5727
  }
5298
- const courseId = course.getCourseID();
5299
- const hasElo = generatorStrategies.some((s) => s.implementingClass === "elo" /* ELO */);
5300
- const hasSrs = generatorStrategies.some((s) => s.implementingClass === "srs" /* SRS */);
5301
- if (!hasElo) {
5302
- logger.debug("[PipelineAssembler] No ELO generator configured, adding default");
5303
- generatorStrategies.push(createDefaultEloStrategy(courseId));
5304
- }
5305
- if (!hasSrs) {
5306
- logger.debug("[PipelineAssembler] No SRS generator configured, adding default");
5307
- generatorStrategies.push(createDefaultSrsStrategy(courseId));
5308
- }
5728
+ const generatorStrategies = plan.generators.map((g) => g.strategy);
5729
+ const sortedFilterStrategies = plan.filters.map((f) => f.strategy);
5309
5730
  if (generatorStrategies.length === 0) {
5310
5731
  warnings.push("No generator strategy found");
5311
5732
  return {
@@ -5327,9 +5748,6 @@ var init_PipelineAssembler = __esm({
5327
5748
  generator = await CompositeGenerator.fromStrategies(user, course, generatorStrategies);
5328
5749
  }
5329
5750
  const filters = [];
5330
- const sortedFilterStrategies = [...filterStrategies].sort(
5331
- (a, b) => a.name.localeCompare(b.name)
5332
- );
5333
5751
  for (const filterStrategy of sortedFilterStrategies) {
5334
5752
  try {
5335
5753
  const nav = await ContentNavigator.create(user, course, filterStrategy);
@@ -5397,7 +5815,9 @@ var init_3 = __esm({
5397
5815
  "./generators/prescribed.ts": () => Promise.resolve().then(() => (init_prescribed(), prescribed_exports)),
5398
5816
  "./generators/srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
5399
5817
  "./generators/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports)),
5400
- "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports))
5818
+ "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports)),
5819
+ "./pipelinePlan.ts": () => Promise.resolve().then(() => (init_pipelinePlan(), pipelinePlan_exports)),
5820
+ "./regulators.ts": () => Promise.resolve().then(() => (init_regulators(), regulators_exports))
5401
5821
  });
5402
5822
  }
5403
5823
  });
@@ -5418,6 +5838,7 @@ __export(navigators_exports, {
5418
5838
  drainCapturedRuns: () => drainCapturedRuns,
5419
5839
  getActivePipeline: () => getActivePipeline,
5420
5840
  getCardOrigin: () => getCardOrigin,
5841
+ getRegisteredFilterKind: () => getRegisteredFilterKind,
5421
5842
  getRegisteredNavigator: () => getRegisteredNavigator,
5422
5843
  getRegisteredNavigatorNames: () => getRegisteredNavigatorNames,
5423
5844
  getRegisteredNavigatorRole: () => getRegisteredNavigatorRole,
@@ -5446,6 +5867,10 @@ function hasRegisteredNavigator(implementingClass) {
5446
5867
  function getRegisteredNavigatorRole(implementingClass) {
5447
5868
  return navigatorRegistry.get(implementingClass)?.role;
5448
5869
  }
5870
+ function getRegisteredFilterKind(implementingClass) {
5871
+ const ctor = navigatorRegistry.get(implementingClass)?.constructor;
5872
+ return ctor?.kind;
5873
+ }
5449
5874
  function getRegisteredNavigatorNames() {
5450
5875
  return Array.from(navigatorRegistry.keys());
5451
5876
  }
@@ -5463,17 +5888,20 @@ async function initializeNavigatorRegistry() {
5463
5888
  hierarchyModule,
5464
5889
  interferenceModule,
5465
5890
  relativePriorityModule,
5466
- userTagPreferenceModule
5891
+ userTagPreferenceModule,
5892
+ eloDistanceModule
5467
5893
  ] = await Promise.all([
5468
5894
  Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
5469
5895
  Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
5470
5896
  Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
5471
- Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports))
5897
+ Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports)),
5898
+ Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports))
5472
5899
  ]);
5473
5900
  registerNavigator("hierarchyDefinition", hierarchyModule.default);
5474
5901
  registerNavigator("interferenceMitigator", interferenceModule.default);
5475
5902
  registerNavigator("relativePriority", relativePriorityModule.default);
5476
5903
  registerNavigator("userTagPreference", userTagPreferenceModule.default);
5904
+ registerNavigator("eloDistance", eloDistanceModule.default);
5477
5905
  logger.debug(
5478
5906
  `[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(", ")}`
5479
5907
  );
@@ -5521,6 +5949,7 @@ var init_navigators = __esm({
5521
5949
  Navigators2["INTERFERENCE"] = "interferenceMitigator";
5522
5950
  Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
5523
5951
  Navigators2["USER_TAG_PREFERENCE"] = "userTagPreference";
5952
+ Navigators2["ELO_DISTANCE"] = "eloDistance";
5524
5953
  return Navigators2;
5525
5954
  })(Navigators || {});
5526
5955
  NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
@@ -5535,7 +5964,8 @@ var init_navigators = __esm({
5535
5964
  ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
5536
5965
  ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
5537
5966
  ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
5538
- ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
5967
+ ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */,
5968
+ ["eloDistance" /* ELO_DISTANCE */]: "filter" /* FILTER */
5539
5969
  };
5540
5970
  ContentNavigator = class {
5541
5971
  /** User interface for this navigation session */
@@ -6314,6 +6744,14 @@ ${e.stack}` : JSON.stringify(e);
6314
6744
  setEphemeralHints(hints) {
6315
6745
  this._pendingHints = hints;
6316
6746
  }
6747
+ /**
6748
+ * Forward a presentation to the navigator (a new card restarts its intake
6749
+ * clock). Builds the navigator if the cached one has expired.
6750
+ */
6751
+ notePresented(card) {
6752
+ if (card.status !== "new") return;
6753
+ 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}`));
6754
+ }
6317
6755
  async getWeightedCards(limit) {
6318
6756
  const u = await this._getCurrentUser();
6319
6757
  try {
@@ -10677,10 +11115,11 @@ function backlogHtml(backlog) {
10677
11115
  const rows = backlog.map((b) => {
10678
11116
  const hot = b.backlogMultiplier >= 3;
10679
11117
  const multColor = b.backlogMultiplier <= 1 ? "#86efac" : hot ? "#fca5a5" : "#fcd34d";
10680
- const headroom = b.backlogMultiplier > 1 ? `climbing (\xD7${b.backlogGrowthRate.toFixed(2)} per ${b.healthyBacklog}-review excess, unbounded)` : "healthy \u2014 no pressure";
11118
+ const headroom = b.backlogMultiplier > 1 ? `climbing (\xD7${b.backlogGrowthRate.toFixed(2)} per ${b.healthyBacklog} of mass in excess, unbounded)` : "healthy \u2014 no pressure";
11119
+ const mass = b.reviewMass !== null ? ` \xB7 mass ${b.reviewMass.toFixed(1)}` : "";
10681
11120
  const top = b.topReviewScore !== null ? b.topReviewScore.toFixed(2) : "\u2014";
10682
11121
  const next = b.nextDueIn ? ` <span style="opacity:.6">\xB7 next due ${esc(b.nextDueIn)}</span>` : "";
10683
- 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>`;
11122
+ 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>`;
10684
11123
  }).join("");
10685
11124
  return `<div style="margin-bottom:6px"><div style="color:#93c5fd">review backpressure</div>${rows}</div>`;
10686
11125
  }
@@ -10819,8 +11258,9 @@ function snapshotToText(s) {
10819
11258
  const headroom = b.backlogMultiplier > 1 ? "climbing" : "healthy";
10820
11259
  const top = b.topReviewScore !== null ? b.topReviewScore.toFixed(2) : "\u2014";
10821
11260
  const next = b.nextDueIn ? `, next due ${b.nextDueIn}` : "";
11261
+ const mass = b.reviewMass !== null ? `, mass ${b.reviewMass.toFixed(1)}` : "";
10822
11262
  lines.push(
10823
- ` ${b.courseId.slice(0, 8)}: due ${b.dueNow}/${b.scheduledTotal} (healthy ${b.healthyBacklog})${next}; pressure \xD7${b.backlogMultiplier.toFixed(2)} ${headroom}; top review ${top}`
11263
+ ` ${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}`
10824
11264
  );
10825
11265
  }
10826
11266
  }
@@ -11201,6 +11641,14 @@ function toRunCardTrail(c) {
11201
11641
  }))
11202
11642
  };
11203
11643
  }
11644
+ function persistedReading(r) {
11645
+ return {
11646
+ ...r,
11647
+ urgency: sig4(r.urgency),
11648
+ multiplier: sig4(r.multiplier),
11649
+ inputs: Object.fromEntries(Object.entries(r.inputs).map(([k, v]) => [k, sig4(v)]))
11650
+ };
11651
+ }
11204
11652
  function persistedRunCards(run) {
11205
11653
  const selected = run.cards.filter((c) => c.selected);
11206
11654
  const runnersUp = run.cards.filter((c) => !c.selected).slice(0, PERSISTED_RUNNERS_UP);
@@ -11526,7 +11974,8 @@ var init_SessionController = __esm({
11526
11974
  ...run.hints ? { hints: run.hints } : {},
11527
11975
  ...run.discardedTail ? { discardedTail: run.discardedTail } : {},
11528
11976
  cards: persistedRunCards(run),
11529
- ...run.unselectedNew ? { unselectedNew: persistedUnselectedNew(run.unselectedNew) } : {}
11977
+ ...run.unselectedNew ? { unselectedNew: persistedUnselectedNew(run.unselectedNew) } : {},
11978
+ ...run.regulators ? { regulators: run.regulators.map(persistedReading) } : {}
11530
11979
  });
11531
11980
  }
11532
11981
  }
@@ -12287,6 +12736,13 @@ var init_SessionController = __esm({
12287
12736
  queueSource,
12288
12737
  nextItem.score
12289
12738
  );
12739
+ for (const source of this.sources) {
12740
+ source.notePresented?.({
12741
+ cardId: nextItem.cardID,
12742
+ courseId: nextItem.courseID,
12743
+ status: nextItem.status
12744
+ });
12745
+ }
12290
12746
  snapshotQueues(this.supplyQ.length, this.failedQ.length);
12291
12747
  return card;
12292
12748
  }
@@ -14994,6 +15450,11 @@ var init_courseDB2 = __esm({
14994
15450
  setEphemeralHints(hints) {
14995
15451
  this._pendingHints = hints;
14996
15452
  }
15453
+ /** Forward a presentation to the navigator (a new card restarts its intake clock). */
15454
+ notePresented(card) {
15455
+ if (card.status !== "new") return;
15456
+ void this.createNavigator(this.userDB).then((navigator2) => navigator2.notePresented?.(card)).catch((e) => logger.warn(`[static/courseDB] Could not note a presentation: ${e}`));
15457
+ }
14997
15458
  async getWeightedCards(limit) {
14998
15459
  try {
14999
15460
  const navigator2 = await this.createNavigator(this.userDB);
@@ -15913,6 +16374,7 @@ __export(index_exports, {
15913
16374
  ContentNavigator: () => ContentNavigator,
15914
16375
  CouchDBToStaticPacker: () => CouchDBToStaticPacker,
15915
16376
  CourseLookup: () => CourseLookup,
16377
+ DEFAULT_REGULATOR_CONFIG: () => DEFAULT_REGULATOR_CONFIG,
15916
16378
  DIVERSITY_FLOOR: () => DIVERSITY_FLOOR,
15917
16379
  DIVERSITY_STRENGTH: () => DIVERSITY_STRENGTH,
15918
16380
  DocType: () => DocType,
@@ -15921,11 +16383,13 @@ __export(index_exports, {
15921
16383
  FileSystemError: () => FileSystemError,
15922
16384
  GuestUsername: () => GuestUsername,
15923
16385
  HYDRATION_MARKER_ID: () => HYDRATION_MARKER_ID,
16386
+ INTAKE_CLOCK_KEY: () => INTAKE_CLOCK_KEY,
15924
16387
  Loggable: () => Loggable,
15925
16388
  NOT_SET: () => NOT_SET,
15926
16389
  NavigatorRole: () => NavigatorRole,
15927
16390
  NavigatorRoles: () => NavigatorRoles,
15928
16391
  Navigators: () => Navigators,
16392
+ PIPELINE_STAGES: () => PIPELINE_STAGES,
15929
16393
  QuotaRoundRobinMixer: () => QuotaRoundRobinMixer,
15930
16394
  REVIEW_TIME_FORMAT: () => REVIEW_TIME_FORMAT2,
15931
16395
  SessionController: () => SessionController,
@@ -15933,6 +16397,7 @@ __export(index_exports, {
15933
16397
  TagFilteredContentSource: () => TagFilteredContentSource,
15934
16398
  _resetDataLayer: () => _resetDataLayer,
15935
16399
  aggregateOutcomesForGradient: () => aggregateOutcomesForGradient,
16400
+ applyReading: () => applyReading,
15936
16401
  areQuestionRecords: () => areQuestionRecords,
15937
16402
  buildStrategyStateId: () => buildStrategyStateId,
15938
16403
  captureMixerRun: () => captureMixerRun,
@@ -15951,6 +16416,7 @@ __export(index_exports, {
15951
16416
  drainCapturedRuns: () => drainCapturedRuns,
15952
16417
  endSessionTracking: () => endSessionTracking,
15953
16418
  ensureAppDataDirectory: () => ensureAppDataDirectory,
16419
+ frozenMsAt: () => frozenMsAt,
15954
16420
  getActiveController: () => getActiveController,
15955
16421
  getActivePipeline: () => getActivePipeline,
15956
16422
  getAppDataDirectory: () => getAppDataDirectory,
@@ -15960,6 +16426,7 @@ __export(index_exports, {
15960
16426
  getDbPath: () => getDbPath,
15961
16427
  getDefaultLearnableWeight: () => getDefaultLearnableWeight,
15962
16428
  getLapses: () => getLapses,
16429
+ getRegisteredFilterKind: () => getRegisteredFilterKind,
15963
16430
  getRegisteredNavigator: () => getRegisteredNavigator,
15964
16431
  getRegisteredNavigatorNames: () => getRegisteredNavigatorNames,
15965
16432
  getRegisteredNavigatorRole: () => getRegisteredNavigatorRole,
@@ -15973,6 +16440,8 @@ __export(index_exports, {
15973
16440
  initializeDataDirectory: () => initializeDataDirectory,
15974
16441
  initializeDataLayer: () => initializeDataLayer,
15975
16442
  initializeNavigatorRegistry: () => initializeNavigatorRegistry,
16443
+ intakeHours: () => intakeHours,
16444
+ intakeReading: () => intakeReading,
15976
16445
  isDataShapeRegistered: () => isDataShapeRegistered,
15977
16446
  isDataShapeSchemaAvailable: () => isDataShapeSchemaAvailable,
15978
16447
  isFilter: () => isFilter,
@@ -15992,6 +16461,7 @@ __export(index_exports, {
15992
16461
  newSessionId: () => newSessionId,
15993
16462
  parseCardHistoryID: () => parseCardHistoryID,
15994
16463
  pipelineDebugAPI: () => pipelineDebugAPI,
16464
+ planPipeline: () => planPipeline,
15995
16465
  processCustomQuestionsData: () => processCustomQuestionsData,
15996
16466
  recordCardPresentation: () => recordCardPresentation,
15997
16467
  recordUserOutcome: () => recordUserOutcome,
@@ -16005,12 +16475,16 @@ __export(index_exports, {
16005
16475
  removeCustomQuestionTypes: () => removeCustomQuestionTypes,
16006
16476
  removeDataShape: () => removeDataShape,
16007
16477
  removeQuestionType: () => removeQuestionType,
16478
+ resetIntakeClock: () => resetIntakeClock,
16479
+ reviewMassReading: () => reviewMassReading,
16480
+ reviewWeight: () => reviewWeight,
16008
16481
  runPeriodUpdate: () => runPeriodUpdate,
16009
16482
  scoreAccuracyInZone: () => scoreAccuracyInZone,
16010
16483
  sessionDebugAPI: () => sessionDebugAPI,
16011
16484
  setDebugSessionId: () => setDebugSessionId,
16012
16485
  snapshotQueues: () => snapshotQueues,
16013
16486
  startSessionTracking: () => startSessionTracking,
16487
+ stepIntakeClock: () => stepIntakeClock,
16014
16488
  toggleSessionOverlay: () => toggleSessionOverlay,
16015
16489
  updateLearningState: () => updateLearningState,
16016
16490
  updateStrategyWeight: () => updateStrategyWeight,
@@ -16021,6 +16495,8 @@ __export(index_exports, {
16021
16495
  });
16022
16496
  module.exports = __toCommonJS(index_exports);
16023
16497
  init_core();
16498
+ init_pipelinePlan();
16499
+ init_regulators();
16024
16500
  init_courseLookupDB();
16025
16501
 
16026
16502
  // src/courseConfigRegistration.ts
@@ -16338,6 +16814,7 @@ init_userDBHelpers();
16338
16814
  ContentNavigator,
16339
16815
  CouchDBToStaticPacker,
16340
16816
  CourseLookup,
16817
+ DEFAULT_REGULATOR_CONFIG,
16341
16818
  DIVERSITY_FLOOR,
16342
16819
  DIVERSITY_STRENGTH,
16343
16820
  DocType,
@@ -16346,11 +16823,13 @@ init_userDBHelpers();
16346
16823
  FileSystemError,
16347
16824
  GuestUsername,
16348
16825
  HYDRATION_MARKER_ID,
16826
+ INTAKE_CLOCK_KEY,
16349
16827
  Loggable,
16350
16828
  NOT_SET,
16351
16829
  NavigatorRole,
16352
16830
  NavigatorRoles,
16353
16831
  Navigators,
16832
+ PIPELINE_STAGES,
16354
16833
  QuotaRoundRobinMixer,
16355
16834
  REVIEW_TIME_FORMAT,
16356
16835
  SessionController,
@@ -16358,6 +16837,7 @@ init_userDBHelpers();
16358
16837
  TagFilteredContentSource,
16359
16838
  _resetDataLayer,
16360
16839
  aggregateOutcomesForGradient,
16840
+ applyReading,
16361
16841
  areQuestionRecords,
16362
16842
  buildStrategyStateId,
16363
16843
  captureMixerRun,
@@ -16376,6 +16856,7 @@ init_userDBHelpers();
16376
16856
  drainCapturedRuns,
16377
16857
  endSessionTracking,
16378
16858
  ensureAppDataDirectory,
16859
+ frozenMsAt,
16379
16860
  getActiveController,
16380
16861
  getActivePipeline,
16381
16862
  getAppDataDirectory,
@@ -16385,6 +16866,7 @@ init_userDBHelpers();
16385
16866
  getDbPath,
16386
16867
  getDefaultLearnableWeight,
16387
16868
  getLapses,
16869
+ getRegisteredFilterKind,
16388
16870
  getRegisteredNavigator,
16389
16871
  getRegisteredNavigatorNames,
16390
16872
  getRegisteredNavigatorRole,
@@ -16398,6 +16880,8 @@ init_userDBHelpers();
16398
16880
  initializeDataDirectory,
16399
16881
  initializeDataLayer,
16400
16882
  initializeNavigatorRegistry,
16883
+ intakeHours,
16884
+ intakeReading,
16401
16885
  isDataShapeRegistered,
16402
16886
  isDataShapeSchemaAvailable,
16403
16887
  isFilter,
@@ -16417,6 +16901,7 @@ init_userDBHelpers();
16417
16901
  newSessionId,
16418
16902
  parseCardHistoryID,
16419
16903
  pipelineDebugAPI,
16904
+ planPipeline,
16420
16905
  processCustomQuestionsData,
16421
16906
  recordCardPresentation,
16422
16907
  recordUserOutcome,
@@ -16430,12 +16915,16 @@ init_userDBHelpers();
16430
16915
  removeCustomQuestionTypes,
16431
16916
  removeDataShape,
16432
16917
  removeQuestionType,
16918
+ resetIntakeClock,
16919
+ reviewMassReading,
16920
+ reviewWeight,
16433
16921
  runPeriodUpdate,
16434
16922
  scoreAccuracyInZone,
16435
16923
  sessionDebugAPI,
16436
16924
  setDebugSessionId,
16437
16925
  snapshotQueues,
16438
16926
  startSessionTracking,
16927
+ stepIntakeClock,
16439
16928
  toggleSessionOverlay,
16440
16929
  updateLearningState,
16441
16930
  updateStrategyWeight,