@vue-skuilder/db 0.2.28 → 0.2.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/{contentSource-DpQqTG3m.d.cts → contentSource-B6FrSihy.d.cts} +218 -2
  2. package/dist/{contentSource-BoFBwvYa.d.ts → contentSource-CqJmbOZN.d.ts} +218 -2
  3. package/dist/core/index.d.cts +13 -90
  4. package/dist/core/index.d.ts +13 -90
  5. package/dist/core/index.js +587 -179
  6. package/dist/core/index.js.map +1 -1
  7. package/dist/core/index.mjs +586 -179
  8. package/dist/core/index.mjs.map +1 -1
  9. package/dist/{dataLayerProvider-D_LJT3F4.d.ts → dataLayerProvider-B9_UCvkR.d.ts} +1 -1
  10. package/dist/{dataLayerProvider-Dl3cAAvQ.d.cts → dataLayerProvider-DUxDqMtZ.d.cts} +1 -1
  11. package/dist/diagnostics/index.d.cts +79 -6
  12. package/dist/diagnostics/index.d.ts +79 -6
  13. package/dist/diagnostics/index.js +158 -4
  14. package/dist/diagnostics/index.js.map +1 -1
  15. package/dist/diagnostics/index.mjs +156 -4
  16. package/dist/diagnostics/index.mjs.map +1 -1
  17. package/dist/impl/couch/index.d.cts +11 -2
  18. package/dist/impl/couch/index.d.ts +11 -2
  19. package/dist/impl/couch/index.js +585 -179
  20. package/dist/impl/couch/index.js.map +1 -1
  21. package/dist/impl/couch/index.mjs +585 -179
  22. package/dist/impl/couch/index.mjs.map +1 -1
  23. package/dist/impl/static/index.d.cts +8 -2
  24. package/dist/impl/static/index.d.ts +8 -2
  25. package/dist/impl/static/index.js +582 -179
  26. package/dist/impl/static/index.js.map +1 -1
  27. package/dist/impl/static/index.mjs +582 -179
  28. package/dist/impl/static/index.mjs.map +1 -1
  29. package/dist/index.d.cts +66 -5
  30. package/dist/index.d.ts +66 -5
  31. package/dist/index.js +635 -180
  32. package/dist/index.js.map +1 -1
  33. package/dist/index.mjs +622 -180
  34. package/dist/index.mjs.map +1 -1
  35. package/package.json +3 -3
  36. package/src/core/interfaces/contentSource.ts +7 -0
  37. package/src/core/navigators/Pipeline.ts +145 -13
  38. package/src/core/navigators/PipelineAssembler.ts +19 -40
  39. package/src/core/navigators/PipelineDebugger.ts +11 -2
  40. package/src/core/navigators/SrsDebugger.ts +37 -12
  41. package/src/core/navigators/defaults.ts +29 -5
  42. package/src/core/navigators/filters/WeightedFilter.ts +5 -1
  43. package/src/core/navigators/filters/eloDistance.ts +261 -76
  44. package/src/core/navigators/filters/hierarchyDefinition.ts +5 -1
  45. package/src/core/navigators/filters/index.ts +2 -2
  46. package/src/core/navigators/filters/interferenceMitigator.ts +5 -1
  47. package/src/core/navigators/filters/relativePriority.ts +5 -1
  48. package/src/core/navigators/filters/types.ts +24 -1
  49. package/src/core/navigators/filters/userTagPreference.ts +5 -1
  50. package/src/core/navigators/generators/elo.ts +23 -53
  51. package/src/core/navigators/generators/srs.ts +27 -124
  52. package/src/core/navigators/index.ts +31 -5
  53. package/src/core/navigators/pipelinePlan.ts +245 -0
  54. package/src/core/navigators/regulators.ts +230 -0
  55. package/src/core/types/studySession.ts +3 -0
  56. package/src/diagnostics/dataset.ts +13 -2
  57. package/src/diagnostics/index.ts +3 -0
  58. package/src/diagnostics/loader.ts +5 -2
  59. package/src/diagnostics/pipeline.ts +236 -0
  60. package/src/diagnostics/text.ts +26 -3
  61. package/src/impl/couch/courseDB.ts +13 -0
  62. package/src/impl/static/courseDB.ts +9 -0
  63. package/src/index.ts +4 -0
  64. package/src/study/SessionController.ts +20 -0
  65. package/src/study/SessionOverlay.ts +7 -4
  66. package/tests/core/navigators/PipelineAssembler.test.ts +20 -5
  67. package/tests/core/navigators/eloDistanceFilter.test.ts +9 -9
package/dist/index.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,141 @@ 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
+ tagAwareGap: () => tagAwareGap
3214
3278
  });
3215
3279
  function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
3216
3280
  const normalizedDistance = distance / halfLife;
3217
3281
  const decay = Math.exp(-(normalizedDistance * normalizedDistance));
3218
3282
  return minMultiplier + (maxMultiplier - minMultiplier) * decay;
3219
3283
  }
3284
+ function resolveConfig(config) {
3285
+ return { ...DEFAULT_ELO_DISTANCE_CONFIG, ...config };
3286
+ }
3287
+ function tagAwareGap(cardTags, cardElo, userElo, minTagCount) {
3288
+ const globalGap = cardElo.global.score - userElo.global.score;
3289
+ const tags = [];
3290
+ for (const tag of cardTags) {
3291
+ const user = userElo.tags[tag];
3292
+ if (!user || user.score === COUNT_ONLY_SENTINEL || user.count < minTagCount) continue;
3293
+ const card = cardElo.tags[tag]?.score ?? cardElo.global.score;
3294
+ tags.push({
3295
+ tag,
3296
+ gap: card - user.score,
3297
+ weight: user.count / (user.count + TAG_CONFIDENCE_HALF)
3298
+ });
3299
+ }
3300
+ if (tags.length === 0) return { gap: globalGap, globalGap, tags };
3301
+ const total = tags.reduce((w, t) => w + t.weight, 0);
3302
+ const tagGap = tags.reduce((g, t) => g + t.weight * t.gap, 0) / total;
3303
+ const lambda = total / (total + 1);
3304
+ return { gap: lambda * tagGap + (1 - lambda) * globalGap, globalGap, tags };
3305
+ }
3306
+ function tagReason(tags, globalGap) {
3307
+ 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(", ");
3308
+ const more = tags.length > 3 ? `, +${tags.length - 3} more` : "";
3309
+ return ` on ${tags.length} shared tag(s) [${shown}${more}] (global ${globalGap >= 0 ? "+" : ""}${Math.round(globalGap)})`;
3310
+ }
3311
+ async function applyEloDistance(cards, context, config, source) {
3312
+ const { course, userElo, userCourseElo } = context;
3313
+ const { halfLife, minMultiplier, maxMultiplier } = config;
3314
+ const tagAware = config.tagAware && userCourseElo !== void 0;
3315
+ const missing = cards.filter((c) => tagAware || c.cardElo === void 0).map((c) => c.cardId);
3316
+ const fetched = /* @__PURE__ */ new Map();
3317
+ if (missing.length > 0) {
3318
+ const elos = await course.getCardEloData(missing);
3319
+ missing.forEach((id, i) => {
3320
+ if (elos[i]) fetched.set(id, elos[i]);
3321
+ });
3322
+ }
3323
+ return cards.map((card) => {
3324
+ const full = fetched.get(card.cardId);
3325
+ const cardElo = full?.global?.score ?? card.cardElo ?? DEFAULT_CARD_ELO;
3326
+ let distance = Math.abs(cardElo - userElo);
3327
+ let how = "";
3328
+ if (tagAware && full) {
3329
+ const t = tagAwareGap(card.tags ?? [], full, userCourseElo, config.minTagCount);
3330
+ distance = Math.abs(t.gap);
3331
+ if (t.tags.length > 0) how = tagReason(t.tags, t.globalGap);
3332
+ }
3333
+ const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
3334
+ const newScore = card.score * multiplier;
3335
+ const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
3336
+ return {
3337
+ ...card,
3338
+ cardElo,
3339
+ score: newScore,
3340
+ provenance: [
3341
+ ...card.provenance,
3342
+ {
3343
+ strategy: "eloDistance",
3344
+ strategyName: source.name,
3345
+ strategyId: source.strategyId,
3346
+ action,
3347
+ score: newScore,
3348
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)})${how} \u2192 ${multiplier.toFixed(2)}x`
3349
+ }
3350
+ ]
3351
+ };
3352
+ });
3353
+ }
3220
3354
  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;
3355
+ const resolved = resolveConfig(config);
3356
+ const source = { name: "ELO Distance Filter", strategyId: "ELO_DISTANCE_FILTER" };
3224
3357
  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
- }
3358
+ name: source.name,
3359
+ kind: "signal",
3360
+ liveOnly: true,
3361
+ transform: (cards, context) => applyEloDistance(cards, context, resolved, source)
3253
3362
  };
3254
3363
  }
3255
- var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
3364
+ var DEFAULT_ELO_DISTANCE_CONFIG, TAG_CONFIDENCE_HALF, COUNT_ONLY_SENTINEL, DEFAULT_CARD_ELO, EloDistanceFilter;
3256
3365
  var init_eloDistance = __esm({
3257
3366
  "src/core/navigators/filters/eloDistance.ts"() {
3258
3367
  "use strict";
3259
- DEFAULT_HALF_LIFE = 200;
3260
- DEFAULT_MIN_MULTIPLIER = 0.3;
3261
- DEFAULT_MAX_MULTIPLIER = 1;
3368
+ init_navigators();
3369
+ DEFAULT_ELO_DISTANCE_CONFIG = {
3370
+ halfLife: 300,
3371
+ minMultiplier: 0.05,
3372
+ maxMultiplier: 1,
3373
+ tagAware: true,
3374
+ minTagCount: 3
3375
+ };
3376
+ TAG_CONFIDENCE_HALF = 10;
3377
+ COUNT_ONLY_SENTINEL = -1;
3378
+ DEFAULT_CARD_ELO = 1e3;
3379
+ EloDistanceFilter = class _EloDistanceFilter extends ContentNavigator {
3380
+ name;
3381
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3382
+ static kind = "signal";
3383
+ kind = _EloDistanceFilter.kind;
3384
+ liveOnly = true;
3385
+ config;
3386
+ constructor(user, course, strategyData) {
3387
+ super(user, course, strategyData);
3388
+ this.name = strategyData.name || "ELO Distance";
3389
+ let parsed;
3390
+ try {
3391
+ parsed = strategyData.serializedData ? JSON.parse(strategyData.serializedData) : void 0;
3392
+ } catch {
3393
+ parsed = void 0;
3394
+ }
3395
+ this.config = resolveConfig(parsed);
3396
+ }
3397
+ transform(cards, context) {
3398
+ return applyEloDistance(cards, context, this.config, {
3399
+ name: this.name,
3400
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-eloDistance-default"
3401
+ });
3402
+ }
3403
+ async getWeightedCards(_limit) {
3404
+ throw new Error(
3405
+ "EloDistanceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
3406
+ );
3407
+ }
3408
+ };
3262
3409
  }
3263
3410
  });
3264
3411
 
@@ -3275,10 +3422,13 @@ var init_hierarchyDefinition = __esm({
3275
3422
  import_common6 = require("@vue-skuilder/common");
3276
3423
  init_logger();
3277
3424
  DEFAULT_MIN_COUNT2 = 3;
3278
- HierarchyDefinitionNavigator = class extends ContentNavigator {
3425
+ HierarchyDefinitionNavigator = class _HierarchyDefinitionNavigator extends ContentNavigator {
3279
3426
  config;
3280
3427
  /** Human-readable name for CardFilter interface */
3281
3428
  name;
3429
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3430
+ static kind = "gate";
3431
+ kind = _HierarchyDefinitionNavigator.kind;
3282
3432
  constructor(user, course, strategyData) {
3283
3433
  super(user, course, strategyData);
3284
3434
  this.config = this.parseConfig(strategyData.serializedData);
@@ -3545,10 +3695,13 @@ var init_userTagPreference = __esm({
3545
3695
  "src/core/navigators/filters/userTagPreference.ts"() {
3546
3696
  "use strict";
3547
3697
  init_navigators();
3548
- UserTagPreferenceFilter = class extends ContentNavigator {
3698
+ UserTagPreferenceFilter = class _UserTagPreferenceFilter extends ContentNavigator {
3549
3699
  _strategyData;
3550
3700
  /** Human-readable name for CardFilter interface */
3551
3701
  name;
3702
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3703
+ static kind = "signal";
3704
+ kind = _UserTagPreferenceFilter.kind;
3552
3705
  constructor(user, course, strategyData) {
3553
3706
  super(user, course, strategyData);
3554
3707
  this._strategyData = strategyData;
@@ -3658,6 +3811,7 @@ var init_userTagPreference = __esm({
3658
3811
  // src/core/navigators/filters/index.ts
3659
3812
  var filters_exports = {};
3660
3813
  __export(filters_exports, {
3814
+ EloDistanceFilter: () => EloDistanceFilter,
3661
3815
  UserTagPreferenceFilter: () => UserTagPreferenceFilter,
3662
3816
  createEloDistanceFilter: () => createEloDistanceFilter
3663
3817
  });
@@ -3696,10 +3850,13 @@ var init_interferenceMitigator = __esm({
3696
3850
  DEFAULT_MIN_COUNT3 = 10;
3697
3851
  DEFAULT_MIN_ELAPSED_DAYS = 3;
3698
3852
  DEFAULT_INTERFERENCE_DECAY = 0.8;
3699
- InterferenceMitigatorNavigator = class extends ContentNavigator {
3853
+ InterferenceMitigatorNavigator = class _InterferenceMitigatorNavigator extends ContentNavigator {
3700
3854
  config;
3701
3855
  /** Human-readable name for CardFilter interface */
3702
3856
  name;
3857
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3858
+ static kind = "signal";
3859
+ kind = _InterferenceMitigatorNavigator.kind;
3703
3860
  /** Precomputed map: tag -> set of { partner, decay } it interferes with */
3704
3861
  interferenceMap;
3705
3862
  constructor(user, course, strategyData) {
@@ -3915,10 +4072,13 @@ var init_relativePriority = __esm({
3915
4072
  DEFAULT_PRIORITY = 0.5;
3916
4073
  DEFAULT_PRIORITY_INFLUENCE = 0.5;
3917
4074
  DEFAULT_COMBINE_MODE = "max";
3918
- RelativePriorityNavigator = class extends ContentNavigator {
4075
+ RelativePriorityNavigator = class _RelativePriorityNavigator extends ContentNavigator {
3919
4076
  config;
3920
4077
  /** Human-readable name for CardFilter interface */
3921
4078
  name;
4079
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
4080
+ static kind = "signal";
4081
+ kind = _RelativePriorityNavigator.kind;
3922
4082
  constructor(user, course, strategyData) {
3923
4083
  super(user, course, strategyData);
3924
4084
  this.config = this.parseConfig(strategyData.serializedData);
@@ -4572,6 +4732,8 @@ var init_Pipeline = __esm({
4572
4732
  init_orchestration();
4573
4733
  init_PipelineDebugger();
4574
4734
  init_diversityRerank();
4735
+ init_regulators();
4736
+ init_SrsDebugger();
4575
4737
  VERBOSE_RESULTS = true;
4576
4738
  Pipeline = class extends ContentNavigator {
4577
4739
  generator;
@@ -4597,6 +4759,13 @@ var init_Pipeline = __esm({
4597
4759
  * getWeightedCards() call, then cleared.
4598
4760
  */
4599
4761
  _ephemeralHints = null;
4762
+ /**
4763
+ * The intake valve's clock (see regulators.ts), loaded from strategy state on
4764
+ * first use and kept in memory. Writes are chained so a presentation and a
4765
+ * run can't race each other's revision.
4766
+ */
4767
+ _intakeClock = null;
4768
+ _intakeClockWrite = Promise.resolve();
4600
4769
  /**
4601
4770
  * Create a new pipeline.
4602
4771
  *
@@ -4671,13 +4840,12 @@ var init_Pipeline = __esm({
4671
4840
  }
4672
4841
  }
4673
4842
  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"));
4843
+ const reviewCount = data.cards.filter((c) => c.reviewID).length;
4676
4844
  return {
4677
4845
  name,
4678
4846
  cardCount: data.cards.length,
4679
- newCount: newCards.length,
4680
- reviewCount: reviewCards.length,
4847
+ newCount: data.cards.length - reviewCount,
4848
+ reviewCount,
4681
4849
  topScore: Math.max(...data.cards.map((c) => c.score), 0)
4682
4850
  };
4683
4851
  });
@@ -4713,19 +4881,24 @@ var init_Pipeline = __esm({
4713
4881
  cards.filter((c) => c.provenance.some((p) => p.strategy === "prescribed")).map((c) => c.cardId)
4714
4882
  );
4715
4883
  const filterImpacts = [];
4884
+ const generatedScores = new Map(cards.map((c) => [c.cardId, c.score]));
4885
+ const gated = /* @__PURE__ */ new Set();
4716
4886
  for (const filter of this.filters) {
4717
4887
  const beforeCount = cards.length;
4718
4888
  const beforeScores = new Map(cards.map((c) => [c.cardId, c.score]));
4719
4889
  cards = await filter.transform(cards, context);
4720
4890
  let boosted = 0, penalized = 0, passed = 0;
4721
4891
  const removed = beforeCount - cards.length;
4892
+ const kind = filter.kind ?? "gate";
4722
4893
  for (const card of cards) {
4723
4894
  const before = beforeScores.get(card.cardId) ?? 0;
4724
4895
  if (card.score > before) boosted++;
4725
- else if (card.score < before) penalized++;
4726
- else passed++;
4896
+ else if (card.score < before) {
4897
+ penalized++;
4898
+ if (kind === "gate") gated.add(card.cardId);
4899
+ } else passed++;
4727
4900
  }
4728
- filterImpacts.push({ name: filter.name, boosted, penalized, passed, removed });
4901
+ filterImpacts.push({ name: filter.name, kind, boosted, penalized, passed, removed });
4729
4902
  if (prescribedIds.size > 0) {
4730
4903
  const survivingIds = new Set(cards.map((c) => c.cardId));
4731
4904
  const killedPrescribed = [...prescribedIds].filter((id) => !survivingIds.has(id));
@@ -4741,6 +4914,7 @@ var init_Pipeline = __esm({
4741
4914
  }
4742
4915
  const scoredCards = cards;
4743
4916
  cards = cards.filter((c) => c.score > 0);
4917
+ const regulators = await this.regulate(cards, generatedScores, gated);
4744
4918
  const hints = this._ephemeralHints;
4745
4919
  if (hints) {
4746
4920
  this._ephemeralHints = null;
@@ -4777,7 +4951,8 @@ var init_Pipeline = __esm({
4777
4951
  result,
4778
4952
  context.userElo,
4779
4953
  hints ?? void 0,
4780
- scoredCards
4954
+ scoredCards,
4955
+ regulators
4781
4956
  );
4782
4957
  captureRun(report);
4783
4958
  } catch (e) {
@@ -4956,6 +5131,77 @@ var init_Pipeline = __esm({
4956
5131
  logger.info(`[Pipeline] Hints applied: ${beforeCount} \u2192 ${cards.length} cards`);
4957
5132
  return cards;
4958
5133
  }
5134
+ /**
5135
+ * The regulator stage: measure each class's pressure and scale it.
5136
+ *
5137
+ * - Review mass: every due review's SRS urgency times the filters' net
5138
+ * effect on it.
5139
+ * - Intake: servable hours since a new card was presented, applied only to
5140
+ * eligible new cards (no gate penalized them). With none eligible, the
5141
+ * clock freezes.
5142
+ *
5143
+ * Mutates `cards` in place; returns the readings for the run report.
5144
+ */
5145
+ async regulate(cards, generatedScores, gated) {
5146
+ const config = DEFAULT_REGULATOR_CONFIG;
5147
+ const reviews = cards.filter((c) => c.reviewID);
5148
+ const newCards = cards.filter((c) => !c.reviewID);
5149
+ const eligibleNew = newCards.filter((c) => !gated.has(c.cardId));
5150
+ const mass = reviewMassReading(reviews, generatedScores, config.reviewMass);
5151
+ applyReading(reviews, mass);
5152
+ noteReviewPressure(this.course.getCourseID(), {
5153
+ mass: mass.urgency,
5154
+ healthyMass: config.reviewMass.healthyMass,
5155
+ rate: config.reviewMass.rate,
5156
+ multiplier: mass.multiplier
5157
+ });
5158
+ const now = Date.now();
5159
+ const clock = await this.loadIntakeClock(now);
5160
+ const stepped = stepIntakeClock(clock, now, eligibleNew.length);
5161
+ if (stepped !== clock) this.saveIntakeClock(stepped);
5162
+ const intake = intakeReading(
5163
+ stepped,
5164
+ now,
5165
+ { eligibleNew: eligibleNew.length, newCandidates: newCards.length },
5166
+ config.intake
5167
+ );
5168
+ applyReading(eligibleNew, intake);
5169
+ logger.info(
5170
+ `[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)}`
5171
+ );
5172
+ return [mass, intake];
5173
+ }
5174
+ /**
5175
+ * A card was presented. A new card's first presentation discharges the
5176
+ * intake valve: its clock restarts. Called by the SessionController.
5177
+ */
5178
+ notePresented(card) {
5179
+ if (card.status !== "new" || card.courseId !== this.course?.getCourseID()) return;
5180
+ this.saveIntakeClock(resetIntakeClock(Date.now()));
5181
+ }
5182
+ async loadIntakeClock(nowMs) {
5183
+ if (this._intakeClock) return this._intakeClock;
5184
+ let stored = null;
5185
+ try {
5186
+ stored = await this.user.getStrategyState(
5187
+ this.course.getCourseID(),
5188
+ INTAKE_CLOCK_KEY
5189
+ );
5190
+ } catch (e) {
5191
+ logger.warn(`[Pipeline:regulators] Could not read the intake clock: ${e}`);
5192
+ }
5193
+ if (stored) {
5194
+ this._intakeClock = stored;
5195
+ } else {
5196
+ this.saveIntakeClock(resetIntakeClock(nowMs));
5197
+ }
5198
+ return this._intakeClock;
5199
+ }
5200
+ saveIntakeClock(state) {
5201
+ this._intakeClock = state;
5202
+ const courseId = this.course.getCourseID();
5203
+ 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}`));
5204
+ }
4959
5205
  /**
4960
5206
  * Build shared context for generator and filters.
4961
5207
  *
@@ -4966,10 +5212,11 @@ var init_Pipeline = __esm({
4966
5212
  */
4967
5213
  async buildContext() {
4968
5214
  let userElo = 1e3;
5215
+ let userCourseElo;
4969
5216
  try {
4970
5217
  const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
4971
- const courseElo = (0, import_common8.toCourseElo)(courseReg.elo);
4972
- userElo = courseElo.global.score;
5218
+ userCourseElo = (0, import_common8.toCourseElo)(courseReg.elo);
5219
+ userElo = userCourseElo.global.score;
4973
5220
  } catch (e) {
4974
5221
  logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
4975
5222
  }
@@ -4981,6 +5228,7 @@ var init_Pipeline = __esm({
4981
5228
  user: this.user,
4982
5229
  course: this.course,
4983
5230
  userElo,
5231
+ ...userCourseElo ? { userCourseElo } : {},
4984
5232
  orchestration
4985
5233
  };
4986
5234
  }
@@ -5094,7 +5342,7 @@ var init_Pipeline = __esm({
5094
5342
  cards = await this.hydrateTags(cards);
5095
5343
  const fullPool = cards.slice();
5096
5344
  const context = await this.buildContext();
5097
- for (const filter of this.filters) {
5345
+ for (const filter of this.forecastFilters()) {
5098
5346
  cards = await filter.transform(cards, context);
5099
5347
  }
5100
5348
  if (opts?.hints) {
@@ -5113,6 +5361,14 @@ var init_Pipeline = __esm({
5113
5361
  cards.sort((a, b) => b.score - a.score);
5114
5362
  return opts?.limit ? cards.slice(0, opts.limit) : cards;
5115
5363
  }
5364
+ /**
5365
+ * The filters a forecast or card-space scan applies. Those start every card at
5366
+ * 1.0 without a generator, so they skip `liveOnly` filters (ELO distance),
5367
+ * which only make sense against generator scores.
5368
+ */
5369
+ forecastFilters() {
5370
+ return this.filters.filter((f) => !f.liveOnly);
5371
+ }
5116
5372
  /**
5117
5373
  * Scan every card in the course through the filter chain and report
5118
5374
  * how many are "well indicated" (score >= threshold) for the current user.
@@ -5134,7 +5390,7 @@ var init_Pipeline = __esm({
5134
5390
  cards = await this.hydrateTags(cards);
5135
5391
  const context = await this.buildContext();
5136
5392
  const filterBreakdown = [];
5137
- for (const filter of this.filters) {
5393
+ for (const filter of this.forecastFilters()) {
5138
5394
  cards = await filter.transform(cards, context);
5139
5395
  const wi = cards.filter((c) => c.score >= THRESHOLD).length;
5140
5396
  filterBreakdown.push({ name: filter.name, wellIndicated: wi });
@@ -5198,6 +5454,7 @@ var init_Pipeline = __esm({
5198
5454
  // src/core/navigators/defaults.ts
5199
5455
  var defaults_exports = {};
5200
5456
  __export(defaults_exports, {
5457
+ createDefaultEloDistanceStrategy: () => createDefaultEloDistanceStrategy,
5201
5458
  createDefaultEloStrategy: () => createDefaultEloStrategy,
5202
5459
  createDefaultPipeline: () => createDefaultPipeline,
5203
5460
  createDefaultSrsStrategy: () => createDefaultSrsStrategy
@@ -5224,12 +5481,28 @@ function createDefaultSrsStrategy(courseId) {
5224
5481
  serializedData: ""
5225
5482
  };
5226
5483
  }
5484
+ function createDefaultEloDistanceStrategy(courseId) {
5485
+ return {
5486
+ _id: "NAVIGATION_STRATEGY-eloDistance-default",
5487
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
5488
+ name: "ELO Distance (default)",
5489
+ description: "Scales every candidate, new or review, by its distance from the learner's ELO",
5490
+ implementingClass: "eloDistance" /* ELO_DISTANCE */,
5491
+ course: courseId,
5492
+ // Explicit, though the filter would default to it anyway: views show what runs.
5493
+ serializedData: JSON.stringify(DEFAULT_ELO_DISTANCE_CONFIG)
5494
+ };
5495
+ }
5227
5496
  function createDefaultPipeline(user, course) {
5228
5497
  const courseId = course.getCourseID();
5229
5498
  const eloNavigator = new ELONavigator(user, course, createDefaultEloStrategy(courseId));
5230
5499
  const srsNavigator = new SRSNavigator(user, course, createDefaultSrsStrategy(courseId));
5231
5500
  const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);
5232
- const eloDistanceFilter = createEloDistanceFilter();
5501
+ const eloDistanceFilter = new EloDistanceFilter(
5502
+ user,
5503
+ course,
5504
+ createDefaultEloDistanceStrategy(courseId)
5505
+ );
5233
5506
  return new Pipeline(compositeGenerator, [eloDistanceFilter], user, course);
5234
5507
  }
5235
5508
  var init_defaults = __esm({
@@ -5245,6 +5518,131 @@ var init_defaults = __esm({
5245
5518
  }
5246
5519
  });
5247
5520
 
5521
+ // src/core/navigators/pipelinePlan.ts
5522
+ var pipelinePlan_exports = {};
5523
+ __export(pipelinePlan_exports, {
5524
+ PIPELINE_STAGES: () => PIPELINE_STAGES,
5525
+ planPipeline: () => planPipeline
5526
+ });
5527
+ function planned(strategy, role, origin) {
5528
+ const kind = role === "filter" /* FILTER */ ? getRegisteredFilterKind(strategy.implementingClass) : void 0;
5529
+ return {
5530
+ role,
5531
+ origin,
5532
+ name: strategy.name,
5533
+ implementingClass: strategy.implementingClass,
5534
+ strategy,
5535
+ ...kind ? { kind } : {}
5536
+ };
5537
+ }
5538
+ function planPipeline(strategies, courseId) {
5539
+ if (strategies.length === 0) {
5540
+ return {
5541
+ kind: "default",
5542
+ generators: [
5543
+ planned(createDefaultEloStrategy(courseId), "generator" /* GENERATOR */, "default-pipeline"),
5544
+ planned(createDefaultSrsStrategy(courseId), "generator" /* GENERATOR */, "default-pipeline")
5545
+ ],
5546
+ filters: [
5547
+ planned(
5548
+ createDefaultEloDistanceStrategy(courseId),
5549
+ "filter" /* FILTER */,
5550
+ "default-pipeline"
5551
+ )
5552
+ ],
5553
+ skipped: [],
5554
+ warnings: [],
5555
+ notes: [],
5556
+ regulators: DEFAULT_REGULATOR_CONFIG
5557
+ };
5558
+ }
5559
+ const generators = [];
5560
+ const filters = [];
5561
+ const skipped = [];
5562
+ const warnings = [];
5563
+ for (const s of strategies) {
5564
+ if (isGenerator(s.implementingClass)) {
5565
+ generators.push(planned(s, "generator" /* GENERATOR */, "strategy-doc"));
5566
+ } else if (isFilter(s.implementingClass)) {
5567
+ filters.push(planned(s, "filter" /* FILTER */, "strategy-doc"));
5568
+ } else {
5569
+ skipped.push({ strategy: s, reason: "not a registered generator or filter" });
5570
+ warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
5571
+ }
5572
+ }
5573
+ const declared = new Set(generators.map((g) => g.implementingClass));
5574
+ if (!declared.has(createDefaultEloStrategy(courseId).implementingClass)) {
5575
+ generators.push(
5576
+ planned(createDefaultEloStrategy(courseId), "generator" /* GENERATOR */, "assembler-default")
5577
+ );
5578
+ }
5579
+ if (!declared.has(createDefaultSrsStrategy(courseId).implementingClass)) {
5580
+ generators.push(
5581
+ planned(createDefaultSrsStrategy(courseId), "generator" /* GENERATOR */, "assembler-default")
5582
+ );
5583
+ }
5584
+ const eloDistance = createDefaultEloDistanceStrategy(courseId);
5585
+ if (!filters.some((f) => f.implementingClass === eloDistance.implementingClass)) {
5586
+ filters.push(planned(eloDistance, "filter" /* FILTER */, "assembler-default"));
5587
+ }
5588
+ filters.sort((a, b) => a.name.localeCompare(b.name));
5589
+ return {
5590
+ kind: "assembled",
5591
+ generators,
5592
+ filters,
5593
+ skipped,
5594
+ warnings,
5595
+ notes: [],
5596
+ regulators: DEFAULT_REGULATOR_CONFIG
5597
+ };
5598
+ }
5599
+ var PIPELINE_STAGES;
5600
+ var init_pipelinePlan = __esm({
5601
+ "src/core/navigators/pipelinePlan.ts"() {
5602
+ "use strict";
5603
+ init_navigators();
5604
+ init_regulators();
5605
+ init_defaults();
5606
+ PIPELINE_STAGES = [
5607
+ {
5608
+ key: "generate",
5609
+ title: "Generate",
5610
+ 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."
5611
+ },
5612
+ {
5613
+ key: "filter",
5614
+ title: "Filter",
5615
+ 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."
5616
+ },
5617
+ {
5618
+ key: "drop-zero",
5619
+ title: "Drop zero scores",
5620
+ summary: "Candidates whose score reached 0 leave the pool."
5621
+ },
5622
+ {
5623
+ key: "regulate",
5624
+ title: "Regulate",
5625
+ 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."
5626
+ },
5627
+ {
5628
+ key: "hints",
5629
+ title: "Apply hints",
5630
+ 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."
5631
+ },
5632
+ {
5633
+ key: "diversity",
5634
+ title: "Diversity re-rank",
5635
+ 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."
5636
+ },
5637
+ {
5638
+ key: "select",
5639
+ title: "Select",
5640
+ summary: "Highest scores first, up to the run's limit. The session mixes them into its supply queue."
5641
+ }
5642
+ ];
5643
+ }
5644
+ });
5645
+
5248
5646
  // src/core/navigators/PipelineAssembler.ts
5249
5647
  var PipelineAssembler_exports = {};
5250
5648
  __export(PipelineAssembler_exports, {
@@ -5259,16 +5657,16 @@ var init_PipelineAssembler = __esm({
5259
5657
  init_Pipeline();
5260
5658
  init_logger();
5261
5659
  init_CompositeGenerator();
5262
- init_defaults();
5660
+ init_pipelinePlan();
5263
5661
  PipelineAssembler = class {
5264
5662
  /**
5265
5663
  * Assembles a navigation pipeline from strategy documents.
5266
5664
  *
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)
5665
+ * 1. Plans: classifies by role, adds default ELO/SRS and ELO distance, orders filters
5666
+ * (`planPipeline`)
5667
+ * 2. Instantiates generators - wraps multiple in CompositeGenerator
5668
+ * 3. Instantiates filters
5669
+ * 4. Returns Pipeline(generator, filters)
5272
5670
  *
5273
5671
  * @param input - Strategy documents plus user/course interfaces
5274
5672
  * @returns Assembled pipeline and any warnings
@@ -5284,28 +5682,17 @@ var init_PipelineAssembler = __esm({
5284
5682
  warnings
5285
5683
  };
5286
5684
  }
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}`);
5685
+ const plan = planPipeline(strategies, course.getCourseID());
5686
+ warnings.push(...plan.warnings);
5687
+ for (const n of [...plan.generators, ...plan.filters]) {
5688
+ if (n.origin === "assembler-default") {
5689
+ logger.debug(
5690
+ `[PipelineAssembler] No ${n.implementingClass} ${n.role} configured, adding default`
5691
+ );
5296
5692
  }
5297
5693
  }
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
- }
5694
+ const generatorStrategies = plan.generators.map((g) => g.strategy);
5695
+ const sortedFilterStrategies = plan.filters.map((f) => f.strategy);
5309
5696
  if (generatorStrategies.length === 0) {
5310
5697
  warnings.push("No generator strategy found");
5311
5698
  return {
@@ -5327,9 +5714,6 @@ var init_PipelineAssembler = __esm({
5327
5714
  generator = await CompositeGenerator.fromStrategies(user, course, generatorStrategies);
5328
5715
  }
5329
5716
  const filters = [];
5330
- const sortedFilterStrategies = [...filterStrategies].sort(
5331
- (a, b) => a.name.localeCompare(b.name)
5332
- );
5333
5717
  for (const filterStrategy of sortedFilterStrategies) {
5334
5718
  try {
5335
5719
  const nav = await ContentNavigator.create(user, course, filterStrategy);
@@ -5397,7 +5781,9 @@ var init_3 = __esm({
5397
5781
  "./generators/prescribed.ts": () => Promise.resolve().then(() => (init_prescribed(), prescribed_exports)),
5398
5782
  "./generators/srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
5399
5783
  "./generators/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports)),
5400
- "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports))
5784
+ "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports)),
5785
+ "./pipelinePlan.ts": () => Promise.resolve().then(() => (init_pipelinePlan(), pipelinePlan_exports)),
5786
+ "./regulators.ts": () => Promise.resolve().then(() => (init_regulators(), regulators_exports))
5401
5787
  });
5402
5788
  }
5403
5789
  });
@@ -5418,6 +5804,7 @@ __export(navigators_exports, {
5418
5804
  drainCapturedRuns: () => drainCapturedRuns,
5419
5805
  getActivePipeline: () => getActivePipeline,
5420
5806
  getCardOrigin: () => getCardOrigin,
5807
+ getRegisteredFilterKind: () => getRegisteredFilterKind,
5421
5808
  getRegisteredNavigator: () => getRegisteredNavigator,
5422
5809
  getRegisteredNavigatorNames: () => getRegisteredNavigatorNames,
5423
5810
  getRegisteredNavigatorRole: () => getRegisteredNavigatorRole,
@@ -5446,6 +5833,10 @@ function hasRegisteredNavigator(implementingClass) {
5446
5833
  function getRegisteredNavigatorRole(implementingClass) {
5447
5834
  return navigatorRegistry.get(implementingClass)?.role;
5448
5835
  }
5836
+ function getRegisteredFilterKind(implementingClass) {
5837
+ const ctor = navigatorRegistry.get(implementingClass)?.constructor;
5838
+ return ctor?.kind;
5839
+ }
5449
5840
  function getRegisteredNavigatorNames() {
5450
5841
  return Array.from(navigatorRegistry.keys());
5451
5842
  }
@@ -5463,17 +5854,20 @@ async function initializeNavigatorRegistry() {
5463
5854
  hierarchyModule,
5464
5855
  interferenceModule,
5465
5856
  relativePriorityModule,
5466
- userTagPreferenceModule
5857
+ userTagPreferenceModule,
5858
+ eloDistanceModule
5467
5859
  ] = await Promise.all([
5468
5860
  Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
5469
5861
  Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
5470
5862
  Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
5471
- Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports))
5863
+ Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports)),
5864
+ Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports))
5472
5865
  ]);
5473
5866
  registerNavigator("hierarchyDefinition", hierarchyModule.default);
5474
5867
  registerNavigator("interferenceMitigator", interferenceModule.default);
5475
5868
  registerNavigator("relativePriority", relativePriorityModule.default);
5476
5869
  registerNavigator("userTagPreference", userTagPreferenceModule.default);
5870
+ registerNavigator("eloDistance", eloDistanceModule.default);
5477
5871
  logger.debug(
5478
5872
  `[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(", ")}`
5479
5873
  );
@@ -5521,6 +5915,7 @@ var init_navigators = __esm({
5521
5915
  Navigators2["INTERFERENCE"] = "interferenceMitigator";
5522
5916
  Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
5523
5917
  Navigators2["USER_TAG_PREFERENCE"] = "userTagPreference";
5918
+ Navigators2["ELO_DISTANCE"] = "eloDistance";
5524
5919
  return Navigators2;
5525
5920
  })(Navigators || {});
5526
5921
  NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
@@ -5535,7 +5930,8 @@ var init_navigators = __esm({
5535
5930
  ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
5536
5931
  ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
5537
5932
  ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
5538
- ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
5933
+ ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */,
5934
+ ["eloDistance" /* ELO_DISTANCE */]: "filter" /* FILTER */
5539
5935
  };
5540
5936
  ContentNavigator = class {
5541
5937
  /** User interface for this navigation session */
@@ -6314,6 +6710,14 @@ ${e.stack}` : JSON.stringify(e);
6314
6710
  setEphemeralHints(hints) {
6315
6711
  this._pendingHints = hints;
6316
6712
  }
6713
+ /**
6714
+ * Forward a presentation to the navigator (a new card restarts its intake
6715
+ * clock). Builds the navigator if the cached one has expired.
6716
+ */
6717
+ notePresented(card) {
6718
+ if (card.status !== "new") return;
6719
+ 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}`));
6720
+ }
6317
6721
  async getWeightedCards(limit) {
6318
6722
  const u = await this._getCurrentUser();
6319
6723
  try {
@@ -10677,10 +11081,11 @@ function backlogHtml(backlog) {
10677
11081
  const rows = backlog.map((b) => {
10678
11082
  const hot = b.backlogMultiplier >= 3;
10679
11083
  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";
11084
+ const headroom = b.backlogMultiplier > 1 ? `climbing (\xD7${b.backlogGrowthRate.toFixed(2)} per ${b.healthyBacklog} of mass in excess, unbounded)` : "healthy \u2014 no pressure";
11085
+ const mass = b.reviewMass !== null ? ` \xB7 mass ${b.reviewMass.toFixed(1)}` : "";
10681
11086
  const top = b.topReviewScore !== null ? b.topReviewScore.toFixed(2) : "\u2014";
10682
11087
  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>`;
11088
+ 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
11089
  }).join("");
10685
11090
  return `<div style="margin-bottom:6px"><div style="color:#93c5fd">review backpressure</div>${rows}</div>`;
10686
11091
  }
@@ -10819,8 +11224,9 @@ function snapshotToText(s) {
10819
11224
  const headroom = b.backlogMultiplier > 1 ? "climbing" : "healthy";
10820
11225
  const top = b.topReviewScore !== null ? b.topReviewScore.toFixed(2) : "\u2014";
10821
11226
  const next = b.nextDueIn ? `, next due ${b.nextDueIn}` : "";
11227
+ const mass = b.reviewMass !== null ? `, mass ${b.reviewMass.toFixed(1)}` : "";
10822
11228
  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}`
11229
+ ` ${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
11230
  );
10825
11231
  }
10826
11232
  }
@@ -11201,6 +11607,14 @@ function toRunCardTrail(c) {
11201
11607
  }))
11202
11608
  };
11203
11609
  }
11610
+ function persistedReading(r) {
11611
+ return {
11612
+ ...r,
11613
+ urgency: sig4(r.urgency),
11614
+ multiplier: sig4(r.multiplier),
11615
+ inputs: Object.fromEntries(Object.entries(r.inputs).map(([k, v]) => [k, sig4(v)]))
11616
+ };
11617
+ }
11204
11618
  function persistedRunCards(run) {
11205
11619
  const selected = run.cards.filter((c) => c.selected);
11206
11620
  const runnersUp = run.cards.filter((c) => !c.selected).slice(0, PERSISTED_RUNNERS_UP);
@@ -11526,7 +11940,8 @@ var init_SessionController = __esm({
11526
11940
  ...run.hints ? { hints: run.hints } : {},
11527
11941
  ...run.discardedTail ? { discardedTail: run.discardedTail } : {},
11528
11942
  cards: persistedRunCards(run),
11529
- ...run.unselectedNew ? { unselectedNew: persistedUnselectedNew(run.unselectedNew) } : {}
11943
+ ...run.unselectedNew ? { unselectedNew: persistedUnselectedNew(run.unselectedNew) } : {},
11944
+ ...run.regulators ? { regulators: run.regulators.map(persistedReading) } : {}
11530
11945
  });
11531
11946
  }
11532
11947
  }
@@ -12287,6 +12702,13 @@ var init_SessionController = __esm({
12287
12702
  queueSource,
12288
12703
  nextItem.score
12289
12704
  );
12705
+ for (const source of this.sources) {
12706
+ source.notePresented?.({
12707
+ cardId: nextItem.cardID,
12708
+ courseId: nextItem.courseID,
12709
+ status: nextItem.status
12710
+ });
12711
+ }
12290
12712
  snapshotQueues(this.supplyQ.length, this.failedQ.length);
12291
12713
  return card;
12292
12714
  }
@@ -14994,6 +15416,11 @@ var init_courseDB2 = __esm({
14994
15416
  setEphemeralHints(hints) {
14995
15417
  this._pendingHints = hints;
14996
15418
  }
15419
+ /** Forward a presentation to the navigator (a new card restarts its intake clock). */
15420
+ notePresented(card) {
15421
+ if (card.status !== "new") return;
15422
+ void this.createNavigator(this.userDB).then((navigator2) => navigator2.notePresented?.(card)).catch((e) => logger.warn(`[static/courseDB] Could not note a presentation: ${e}`));
15423
+ }
14997
15424
  async getWeightedCards(limit) {
14998
15425
  try {
14999
15426
  const navigator2 = await this.createNavigator(this.userDB);
@@ -15913,6 +16340,7 @@ __export(index_exports, {
15913
16340
  ContentNavigator: () => ContentNavigator,
15914
16341
  CouchDBToStaticPacker: () => CouchDBToStaticPacker,
15915
16342
  CourseLookup: () => CourseLookup,
16343
+ DEFAULT_REGULATOR_CONFIG: () => DEFAULT_REGULATOR_CONFIG,
15916
16344
  DIVERSITY_FLOOR: () => DIVERSITY_FLOOR,
15917
16345
  DIVERSITY_STRENGTH: () => DIVERSITY_STRENGTH,
15918
16346
  DocType: () => DocType,
@@ -15921,11 +16349,13 @@ __export(index_exports, {
15921
16349
  FileSystemError: () => FileSystemError,
15922
16350
  GuestUsername: () => GuestUsername,
15923
16351
  HYDRATION_MARKER_ID: () => HYDRATION_MARKER_ID,
16352
+ INTAKE_CLOCK_KEY: () => INTAKE_CLOCK_KEY,
15924
16353
  Loggable: () => Loggable,
15925
16354
  NOT_SET: () => NOT_SET,
15926
16355
  NavigatorRole: () => NavigatorRole,
15927
16356
  NavigatorRoles: () => NavigatorRoles,
15928
16357
  Navigators: () => Navigators,
16358
+ PIPELINE_STAGES: () => PIPELINE_STAGES,
15929
16359
  QuotaRoundRobinMixer: () => QuotaRoundRobinMixer,
15930
16360
  REVIEW_TIME_FORMAT: () => REVIEW_TIME_FORMAT2,
15931
16361
  SessionController: () => SessionController,
@@ -15933,6 +16363,7 @@ __export(index_exports, {
15933
16363
  TagFilteredContentSource: () => TagFilteredContentSource,
15934
16364
  _resetDataLayer: () => _resetDataLayer,
15935
16365
  aggregateOutcomesForGradient: () => aggregateOutcomesForGradient,
16366
+ applyReading: () => applyReading,
15936
16367
  areQuestionRecords: () => areQuestionRecords,
15937
16368
  buildStrategyStateId: () => buildStrategyStateId,
15938
16369
  captureMixerRun: () => captureMixerRun,
@@ -15951,6 +16382,7 @@ __export(index_exports, {
15951
16382
  drainCapturedRuns: () => drainCapturedRuns,
15952
16383
  endSessionTracking: () => endSessionTracking,
15953
16384
  ensureAppDataDirectory: () => ensureAppDataDirectory,
16385
+ frozenMsAt: () => frozenMsAt,
15954
16386
  getActiveController: () => getActiveController,
15955
16387
  getActivePipeline: () => getActivePipeline,
15956
16388
  getAppDataDirectory: () => getAppDataDirectory,
@@ -15960,6 +16392,7 @@ __export(index_exports, {
15960
16392
  getDbPath: () => getDbPath,
15961
16393
  getDefaultLearnableWeight: () => getDefaultLearnableWeight,
15962
16394
  getLapses: () => getLapses,
16395
+ getRegisteredFilterKind: () => getRegisteredFilterKind,
15963
16396
  getRegisteredNavigator: () => getRegisteredNavigator,
15964
16397
  getRegisteredNavigatorNames: () => getRegisteredNavigatorNames,
15965
16398
  getRegisteredNavigatorRole: () => getRegisteredNavigatorRole,
@@ -15973,6 +16406,8 @@ __export(index_exports, {
15973
16406
  initializeDataDirectory: () => initializeDataDirectory,
15974
16407
  initializeDataLayer: () => initializeDataLayer,
15975
16408
  initializeNavigatorRegistry: () => initializeNavigatorRegistry,
16409
+ intakeHours: () => intakeHours,
16410
+ intakeReading: () => intakeReading,
15976
16411
  isDataShapeRegistered: () => isDataShapeRegistered,
15977
16412
  isDataShapeSchemaAvailable: () => isDataShapeSchemaAvailable,
15978
16413
  isFilter: () => isFilter,
@@ -15992,6 +16427,7 @@ __export(index_exports, {
15992
16427
  newSessionId: () => newSessionId,
15993
16428
  parseCardHistoryID: () => parseCardHistoryID,
15994
16429
  pipelineDebugAPI: () => pipelineDebugAPI,
16430
+ planPipeline: () => planPipeline,
15995
16431
  processCustomQuestionsData: () => processCustomQuestionsData,
15996
16432
  recordCardPresentation: () => recordCardPresentation,
15997
16433
  recordUserOutcome: () => recordUserOutcome,
@@ -16005,12 +16441,16 @@ __export(index_exports, {
16005
16441
  removeCustomQuestionTypes: () => removeCustomQuestionTypes,
16006
16442
  removeDataShape: () => removeDataShape,
16007
16443
  removeQuestionType: () => removeQuestionType,
16444
+ resetIntakeClock: () => resetIntakeClock,
16445
+ reviewMassReading: () => reviewMassReading,
16446
+ reviewWeight: () => reviewWeight,
16008
16447
  runPeriodUpdate: () => runPeriodUpdate,
16009
16448
  scoreAccuracyInZone: () => scoreAccuracyInZone,
16010
16449
  sessionDebugAPI: () => sessionDebugAPI,
16011
16450
  setDebugSessionId: () => setDebugSessionId,
16012
16451
  snapshotQueues: () => snapshotQueues,
16013
16452
  startSessionTracking: () => startSessionTracking,
16453
+ stepIntakeClock: () => stepIntakeClock,
16014
16454
  toggleSessionOverlay: () => toggleSessionOverlay,
16015
16455
  updateLearningState: () => updateLearningState,
16016
16456
  updateStrategyWeight: () => updateStrategyWeight,
@@ -16021,6 +16461,8 @@ __export(index_exports, {
16021
16461
  });
16022
16462
  module.exports = __toCommonJS(index_exports);
16023
16463
  init_core();
16464
+ init_pipelinePlan();
16465
+ init_regulators();
16024
16466
  init_courseLookupDB();
16025
16467
 
16026
16468
  // src/courseConfigRegistration.ts
@@ -16338,6 +16780,7 @@ init_userDBHelpers();
16338
16780
  ContentNavigator,
16339
16781
  CouchDBToStaticPacker,
16340
16782
  CourseLookup,
16783
+ DEFAULT_REGULATOR_CONFIG,
16341
16784
  DIVERSITY_FLOOR,
16342
16785
  DIVERSITY_STRENGTH,
16343
16786
  DocType,
@@ -16346,11 +16789,13 @@ init_userDBHelpers();
16346
16789
  FileSystemError,
16347
16790
  GuestUsername,
16348
16791
  HYDRATION_MARKER_ID,
16792
+ INTAKE_CLOCK_KEY,
16349
16793
  Loggable,
16350
16794
  NOT_SET,
16351
16795
  NavigatorRole,
16352
16796
  NavigatorRoles,
16353
16797
  Navigators,
16798
+ PIPELINE_STAGES,
16354
16799
  QuotaRoundRobinMixer,
16355
16800
  REVIEW_TIME_FORMAT,
16356
16801
  SessionController,
@@ -16358,6 +16803,7 @@ init_userDBHelpers();
16358
16803
  TagFilteredContentSource,
16359
16804
  _resetDataLayer,
16360
16805
  aggregateOutcomesForGradient,
16806
+ applyReading,
16361
16807
  areQuestionRecords,
16362
16808
  buildStrategyStateId,
16363
16809
  captureMixerRun,
@@ -16376,6 +16822,7 @@ init_userDBHelpers();
16376
16822
  drainCapturedRuns,
16377
16823
  endSessionTracking,
16378
16824
  ensureAppDataDirectory,
16825
+ frozenMsAt,
16379
16826
  getActiveController,
16380
16827
  getActivePipeline,
16381
16828
  getAppDataDirectory,
@@ -16385,6 +16832,7 @@ init_userDBHelpers();
16385
16832
  getDbPath,
16386
16833
  getDefaultLearnableWeight,
16387
16834
  getLapses,
16835
+ getRegisteredFilterKind,
16388
16836
  getRegisteredNavigator,
16389
16837
  getRegisteredNavigatorNames,
16390
16838
  getRegisteredNavigatorRole,
@@ -16398,6 +16846,8 @@ init_userDBHelpers();
16398
16846
  initializeDataDirectory,
16399
16847
  initializeDataLayer,
16400
16848
  initializeNavigatorRegistry,
16849
+ intakeHours,
16850
+ intakeReading,
16401
16851
  isDataShapeRegistered,
16402
16852
  isDataShapeSchemaAvailable,
16403
16853
  isFilter,
@@ -16417,6 +16867,7 @@ init_userDBHelpers();
16417
16867
  newSessionId,
16418
16868
  parseCardHistoryID,
16419
16869
  pipelineDebugAPI,
16870
+ planPipeline,
16420
16871
  processCustomQuestionsData,
16421
16872
  recordCardPresentation,
16422
16873
  recordUserOutcome,
@@ -16430,12 +16881,16 @@ init_userDBHelpers();
16430
16881
  removeCustomQuestionTypes,
16431
16882
  removeDataShape,
16432
16883
  removeQuestionType,
16884
+ resetIntakeClock,
16885
+ reviewMassReading,
16886
+ reviewWeight,
16433
16887
  runPeriodUpdate,
16434
16888
  scoreAccuracyInZone,
16435
16889
  sessionDebugAPI,
16436
16890
  setDebugSessionId,
16437
16891
  snapshotQueues,
16438
16892
  startSessionTracking,
16893
+ stepIntakeClock,
16439
16894
  toggleSessionOverlay,
16440
16895
  updateLearningState,
16441
16896
  updateStrategyWeight,