@vue-skuilder/db 0.2.27 → 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 (82) hide show
  1. package/dist/classroomDB-DLTtLZct.d.cts +86 -0
  2. package/dist/classroomDB-DLTtLZct.d.ts +86 -0
  3. package/dist/{contentSource-LPf044hY.d.ts → contentSource-B6FrSihy.d.cts} +282 -99
  4. package/dist/{contentSource-D3c1fMAk.d.cts → contentSource-CqJmbOZN.d.ts} +282 -99
  5. package/dist/core/index.d.cts +16 -92
  6. package/dist/core/index.d.ts +16 -92
  7. package/dist/core/index.js +607 -179
  8. package/dist/core/index.js.map +1 -1
  9. package/dist/core/index.mjs +606 -179
  10. package/dist/core/index.mjs.map +1 -1
  11. package/dist/{dataLayerProvider-DaAootVV.d.ts → dataLayerProvider-B9_UCvkR.d.ts} +2 -8
  12. package/dist/{dataLayerProvider-CeLiFbHv.d.cts → dataLayerProvider-DUxDqMtZ.d.cts} +2 -8
  13. package/dist/diagnostics/index.d.cts +443 -0
  14. package/dist/diagnostics/index.d.ts +443 -0
  15. package/dist/diagnostics/index.js +932 -0
  16. package/dist/diagnostics/index.js.map +1 -0
  17. package/dist/diagnostics/index.mjs +881 -0
  18. package/dist/diagnostics/index.mjs.map +1 -0
  19. package/dist/impl/couch/index.d.cts +13 -3
  20. package/dist/impl/couch/index.d.ts +13 -3
  21. package/dist/impl/couch/index.js +605 -179
  22. package/dist/impl/couch/index.js.map +1 -1
  23. package/dist/impl/couch/index.mjs +605 -179
  24. package/dist/impl/couch/index.mjs.map +1 -1
  25. package/dist/impl/static/index.d.cts +11 -5
  26. package/dist/impl/static/index.d.ts +11 -5
  27. package/dist/impl/static/index.js +602 -185
  28. package/dist/impl/static/index.js.map +1 -1
  29. package/dist/impl/static/index.mjs +602 -185
  30. package/dist/impl/static/index.mjs.map +1 -1
  31. package/dist/{index-BkBJlGDX.d.ts → index-CVGehe_t.d.ts} +1 -1
  32. package/dist/{index-D7WdMDAs.d.cts → index-Ktg72jKb.d.cts} +1 -1
  33. package/dist/index.d.cts +73 -11
  34. package/dist/index.d.ts +73 -11
  35. package/dist/index.js +696 -200
  36. package/dist/index.js.map +1 -1
  37. package/dist/index.mjs +683 -200
  38. package/dist/index.mjs.map +1 -1
  39. package/dist/{types-DjiFOZxJ.d.cts → types-D0oQeJAi.d.cts} +1 -1
  40. package/dist/{types-uJ2Xn3_X.d.ts → types-dXWfyz9B.d.ts} +1 -1
  41. package/dist/{types-legacy-CrwyZIvI.d.cts → types-legacy-BkOYOR6U.d.cts} +1 -1
  42. package/dist/{types-legacy-CrwyZIvI.d.ts → types-legacy-BkOYOR6U.d.ts} +1 -1
  43. package/dist/util/packer/index.d.cts +3 -3
  44. package/dist/util/packer/index.d.ts +3 -3
  45. package/package.json +15 -3
  46. package/src/core/interfaces/contentSource.ts +7 -0
  47. package/src/core/interfaces/dataLayerProvider.ts +3 -8
  48. package/src/core/navigators/Pipeline.ts +149 -14
  49. package/src/core/navigators/PipelineAssembler.ts +19 -40
  50. package/src/core/navigators/PipelineDebugger.ts +74 -17
  51. package/src/core/navigators/SrsDebugger.ts +37 -12
  52. package/src/core/navigators/defaults.ts +29 -5
  53. package/src/core/navigators/filters/WeightedFilter.ts +5 -1
  54. package/src/core/navigators/filters/eloDistance.ts +261 -76
  55. package/src/core/navigators/filters/hierarchyDefinition.ts +5 -1
  56. package/src/core/navigators/filters/index.ts +2 -2
  57. package/src/core/navigators/filters/interferenceMitigator.ts +5 -1
  58. package/src/core/navigators/filters/relativePriority.ts +5 -1
  59. package/src/core/navigators/filters/types.ts +24 -1
  60. package/src/core/navigators/filters/userTagPreference.ts +5 -1
  61. package/src/core/navigators/generators/elo.ts +23 -53
  62. package/src/core/navigators/generators/srs.ts +27 -124
  63. package/src/core/navigators/index.ts +32 -5
  64. package/src/core/navigators/pipelinePlan.ts +245 -0
  65. package/src/core/navigators/regulators.ts +230 -0
  66. package/src/core/types/studySession.ts +40 -0
  67. package/src/diagnostics/dataset.ts +242 -0
  68. package/src/diagnostics/derive.ts +555 -0
  69. package/src/diagnostics/index.ts +27 -0
  70. package/src/diagnostics/loader.ts +194 -0
  71. package/src/diagnostics/pipeline.ts +236 -0
  72. package/src/diagnostics/text.ts +265 -0
  73. package/src/impl/couch/PouchDataLayerProvider.ts +0 -23
  74. package/src/impl/couch/courseDB.ts +13 -0
  75. package/src/impl/static/StaticDataLayerProvider.ts +0 -11
  76. package/src/impl/static/courseDB.ts +9 -0
  77. package/src/index.ts +4 -0
  78. package/src/study/SessionController.ts +76 -2
  79. package/src/study/SessionOverlay.ts +7 -4
  80. package/tests/core/navigators/PipelineAssembler.test.ts +20 -5
  81. package/tests/core/navigators/eloDistanceFilter.test.ts +9 -9
  82. package/tsup.config.ts +1 -0
package/dist/index.mjs CHANGED
@@ -812,7 +812,7 @@ function parseCardElo(provenance) {
812
812
  const match = eloEntry.reason.match(/card:\s*(\d+)/);
813
813
  return match ? parseInt(match[1], 10) : void 0;
814
814
  }
815
- function buildRunReport(courseId, courseName, generatorName, generators, generatedCount, filters, allCards, selectedCards, userElo, hints) {
815
+ function buildRunReport(courseId, courseName, generatorName, generators, generatedCount, filters, allCards, selectedCards, userElo, hints, scoredCards, regulators) {
816
816
  const selectedIds = new Set(selectedCards.map((c) => c.cardId));
817
817
  const toReport = (card) => ({
818
818
  cardId: card.cardId,
@@ -820,7 +820,7 @@ function buildRunReport(courseId, courseName, generatorName, generators, generat
820
820
  origin: getOrigin(card),
821
821
  generator: card.provenance[0]?.strategyName || card.provenance[0]?.strategy,
822
822
  finalScore: card.score,
823
- cardElo: parseCardElo(card.provenance),
823
+ cardElo: card.cardElo ?? parseCardElo(card.provenance),
824
824
  provenance: card.provenance,
825
825
  tags: card.tags,
826
826
  selected: selectedIds.has(card.cardId)
@@ -865,6 +865,23 @@ function buildRunReport(courseId, courseName, generatorName, generators, generat
865
865
  note: `${discardedTailCards.length} additional candidate(s) scored below the top ${DISCARDED_KEEP_TOP} near-misses and were not retained (score ${scoreMin.toExponential(2)}\u2013${scoreMax.toExponential(2)}${eloFragment}). Likely ELO-window pull remnants filtered out by hierarchy/lesson/priority gates.`
866
866
  };
867
867
  }
868
+ const isUnselectedNew = (c) => !c.reviewID && !selectedIds.has(c.cardId);
869
+ const generatorScore = (c) => c.provenance[0]?.score ?? 0;
870
+ const keptIds = new Set(allCards.map((c) => c.cardId));
871
+ const hintExcluded = (c) => c.score > 0 && !keptIds.has(c.cardId);
872
+ let nextInLine;
873
+ for (const c of allCards) {
874
+ if (isUnselectedNew(c) && (!nextInLine || c.score > nextInLine.score)) nextInLine = c;
875
+ }
876
+ let topGenerated;
877
+ for (const c of scoredCards ?? allCards) {
878
+ if (!isUnselectedNew(c) || hintExcluded(c)) continue;
879
+ if (!topGenerated || generatorScore(c) > generatorScore(topGenerated)) topGenerated = c;
880
+ }
881
+ const unselectedNew = nextInLine || topGenerated ? {
882
+ ...nextInLine ? { nextInLine: toReport(nextInLine) } : {},
883
+ ...topGenerated && topGenerated.cardId !== nextInLine?.cardId ? { topGenerated: toReport(topGenerated) } : {}
884
+ } : void 0;
868
885
  const reviewsSelected = selectedCards.filter((c) => getOrigin(c) === "review").length;
869
886
  const newSelected = selectedCards.filter((c) => getOrigin(c) === "new").length;
870
887
  return {
@@ -880,7 +897,9 @@ function buildRunReport(courseId, courseName, generatorName, generators, generat
880
897
  reviewsSelected,
881
898
  newSelected,
882
899
  cards,
883
- discardedTail
900
+ unselectedNew,
901
+ discardedTail,
902
+ ...regulators ? { regulators } : {}
884
903
  };
885
904
  }
886
905
  function formatProvenance(provenance) {
@@ -1604,11 +1623,23 @@ var SrsDebugger_exports = {};
1604
1623
  __export(SrsDebugger_exports, {
1605
1624
  captureSrsBacklog: () => captureSrsBacklog,
1606
1625
  clearSrsBacklogDebug: () => clearSrsBacklogDebug,
1607
- getSrsBacklogDebug: () => getSrsBacklogDebug
1626
+ getSrsBacklogDebug: () => getSrsBacklogDebug,
1627
+ noteReviewPressure: () => noteReviewPressure
1608
1628
  });
1609
1629
  function captureSrsBacklog(snapshot) {
1610
1630
  snapshots.set(snapshot.courseId, snapshot);
1611
1631
  }
1632
+ function noteReviewPressure(courseId, pressure) {
1633
+ const snapshot = snapshots.get(courseId);
1634
+ if (!snapshot) return;
1635
+ snapshots.set(courseId, {
1636
+ ...snapshot,
1637
+ reviewMass: pressure.mass,
1638
+ healthyBacklog: pressure.healthyMass,
1639
+ backlogGrowthRate: pressure.rate,
1640
+ backlogMultiplier: pressure.multiplier
1641
+ });
1642
+ }
1612
1643
  function getSrsBacklogDebug() {
1613
1644
  return [...snapshots.values()].sort((a, b) => b.timestamp - a.timestamp);
1614
1645
  }
@@ -1887,13 +1918,12 @@ __export(elo_exports, {
1887
1918
  default: () => ELONavigator
1888
1919
  });
1889
1920
  import { toCourseElo as toCourseElo2 } from "@vue-skuilder/common";
1890
- var ELO_RELEVANCE_SIGMA, ELONavigator;
1921
+ var ELONavigator;
1891
1922
  var init_elo = __esm({
1892
1923
  "src/core/navigators/generators/elo.ts"() {
1893
1924
  "use strict";
1894
1925
  init_navigators();
1895
1926
  init_logger();
1896
- ELO_RELEVANCE_SIGMA = 300;
1897
1927
  ELONavigator = class extends ContentNavigator {
1898
1928
  /** Human-readable name for CardGenerator interface */
1899
1929
  name;
@@ -1902,10 +1932,8 @@ var init_elo = __esm({
1902
1932
  this.name = strategyData?.name || "ELO";
1903
1933
  }
1904
1934
  /**
1905
- * Get new cards with suitability scores based on ELO distance.
1906
- *
1907
- * Cards closer to user's ELO get higher scores.
1908
- * Score formula: max(0, 1 - distance / 500)
1935
+ * Get the new cards nearest the learner's ELO, each scored with a flat
1936
+ * jitter in [0.5, 1]. Carries each card's ELO for the ELO distance filter.
1909
1937
  *
1910
1938
  * NOTE: This generator only handles NEW cards. Reviews are handled by
1911
1939
  * SRSNavigator. Use CompositeGenerator to combine both.
@@ -1933,20 +1961,20 @@ var init_elo = __esm({
1933
1961
  const scored = newCards.map((c) => {
1934
1962
  const cardElo = c.elo ?? 1e3;
1935
1963
  const distance = Math.abs(cardElo - userGlobalElo);
1936
- const relevance = Math.exp(-((distance / ELO_RELEVANCE_SIGMA) ** 2));
1937
- const samplingKey = relevance * (0.5 + 0.5 * Math.random());
1964
+ const jitter = 0.5 + 0.5 * Math.random();
1938
1965
  return {
1939
1966
  cardId: c.cardID,
1940
1967
  courseId: c.courseID,
1941
- score: samplingKey,
1968
+ score: jitter,
1969
+ cardElo,
1942
1970
  provenance: [
1943
1971
  {
1944
1972
  strategy: "elo",
1945
1973
  strategyName: this.strategyName || this.name,
1946
1974
  strategyId: this.strategyId || "NAVIGATION_STRATEGY-ELO-default",
1947
1975
  action: "generated",
1948
- score: samplingKey,
1949
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userGlobalElo)}), relevance ${relevance.toFixed(3)}, key ${samplingKey.toFixed(3)}`
1976
+ score: jitter,
1977
+ reason: `new card near learner ELO: distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userGlobalElo)}), jitter ${jitter.toFixed(3)}`
1950
1978
  }
1951
1979
  ]
1952
1980
  };
@@ -2822,43 +2850,132 @@ var init_prescribed = __esm({
2822
2850
  }
2823
2851
  });
2824
2852
 
2853
+ // src/core/navigators/regulators.ts
2854
+ var regulators_exports = {};
2855
+ __export(regulators_exports, {
2856
+ DEFAULT_REGULATOR_CONFIG: () => DEFAULT_REGULATOR_CONFIG,
2857
+ INTAKE_CLOCK_KEY: () => INTAKE_CLOCK_KEY,
2858
+ applyReading: () => applyReading,
2859
+ frozenMsAt: () => frozenMsAt,
2860
+ intakeHours: () => intakeHours,
2861
+ intakeReading: () => intakeReading,
2862
+ resetIntakeClock: () => resetIntakeClock,
2863
+ reviewMassReading: () => reviewMassReading,
2864
+ reviewWeight: () => reviewWeight,
2865
+ stepIntakeClock: () => stepIntakeClock
2866
+ });
2867
+ function clamp01(x) {
2868
+ return Math.min(1, Math.max(0, x));
2869
+ }
2870
+ function reviewWeight(card, generatedScore, referenceScore) {
2871
+ if (card.reviewUrgency !== void 0 && generatedScore !== void 0 && generatedScore > 0) {
2872
+ return clamp01(card.reviewUrgency * (card.score / generatedScore));
2873
+ }
2874
+ return clamp01(card.score / referenceScore);
2875
+ }
2876
+ function reviewMassReading(reviews, generatedScores, config = DEFAULT_REGULATOR_CONFIG.reviewMass) {
2877
+ const mass = reviews.reduce(
2878
+ (m, c) => m + reviewWeight(c, generatedScores.get(c.cardId), config.referenceScore),
2879
+ 0
2880
+ );
2881
+ const multiplier = mass > config.healthyMass ? Math.pow(config.rate, (mass - config.healthyMass) / config.healthyMass) : 1;
2882
+ return {
2883
+ name: "review-mass",
2884
+ class: "review",
2885
+ urgency: mass,
2886
+ multiplier,
2887
+ applied: reviews.length,
2888
+ inputs: { due: reviews.length, mass, healthyMass: config.healthyMass }
2889
+ };
2890
+ }
2891
+ function resetIntakeClock(nowMs) {
2892
+ return { lastNewAt: new Date(nowMs).toISOString(), frozenMs: 0, unservableSince: null };
2893
+ }
2894
+ function frozenMsAt(state, nowMs) {
2895
+ const open = state.unservableSince ? Math.max(0, nowMs - Date.parse(state.unservableSince)) : 0;
2896
+ return state.frozenMs + open;
2897
+ }
2898
+ function intakeHours(state, nowMs) {
2899
+ const elapsed = nowMs - Date.parse(state.lastNewAt);
2900
+ return Math.max(0, elapsed - frozenMsAt(state, nowMs)) / 36e5;
2901
+ }
2902
+ function stepIntakeClock(state, nowMs, eligibleNew) {
2903
+ if (eligibleNew === 0 && !state.unservableSince) {
2904
+ return { ...state, unservableSince: new Date(nowMs).toISOString() };
2905
+ }
2906
+ if (eligibleNew > 0 && state.unservableSince) {
2907
+ return { ...state, frozenMs: frozenMsAt(state, nowMs), unservableSince: null };
2908
+ }
2909
+ return state;
2910
+ }
2911
+ function intakeReading(state, nowMs, counts, config = DEFAULT_REGULATOR_CONFIG.intake) {
2912
+ const hours = intakeHours(state, nowMs);
2913
+ const multiplier = counts.eligibleNew > 0 ? Math.pow(config.rate, hours / config.scaleHours) : 1;
2914
+ return {
2915
+ name: "intake",
2916
+ class: "new",
2917
+ urgency: hours,
2918
+ multiplier,
2919
+ applied: counts.eligibleNew,
2920
+ inputs: {
2921
+ hoursSinceNew: hours,
2922
+ frozenHours: frozenMsAt(state, nowMs) / 36e5,
2923
+ eligibleNew: counts.eligibleNew,
2924
+ newCandidates: counts.newCandidates
2925
+ }
2926
+ };
2927
+ }
2928
+ function applyReading(cards, reading) {
2929
+ if (reading.multiplier === 1) return;
2930
+ const reason = reading.name === "review-mass" ? `review mass ${reading.urgency.toFixed(1)} (healthy ${reading.inputs.healthyMass}) \u2192 \xD7${reading.multiplier.toFixed(2)}` : `${reading.urgency.toFixed(1)}h since a new card \u2192 \xD7${reading.multiplier.toFixed(2)}`;
2931
+ for (const card of cards) {
2932
+ card.score *= reading.multiplier;
2933
+ card.provenance.push({
2934
+ strategy: "regulator",
2935
+ strategyName: `Regulator: ${REGULATOR_LABEL[reading.name]}`,
2936
+ strategyId: `regulator-${reading.name}`,
2937
+ action: reading.multiplier > 1 ? "boosted" : "penalized",
2938
+ score: card.score,
2939
+ reason
2940
+ });
2941
+ }
2942
+ }
2943
+ var DEFAULT_REGULATOR_CONFIG, INTAKE_CLOCK_KEY, REGULATOR_LABEL;
2944
+ var init_regulators = __esm({
2945
+ "src/core/navigators/regulators.ts"() {
2946
+ "use strict";
2947
+ DEFAULT_REGULATOR_CONFIG = {
2948
+ reviewMass: { referenceScore: 0.95, healthyMass: 20, rate: 2 },
2949
+ intake: { rate: 2, scaleHours: 24 }
2950
+ };
2951
+ INTAKE_CLOCK_KEY = "IntakeClock";
2952
+ REGULATOR_LABEL = {
2953
+ "review-mass": "Review mass",
2954
+ intake: "Intake"
2955
+ };
2956
+ }
2957
+ });
2958
+
2825
2959
  // src/core/navigators/generators/srs.ts
2826
2960
  var srs_exports = {};
2827
2961
  __export(srs_exports, {
2828
2962
  default: () => SRSNavigator
2829
2963
  });
2830
2964
  import moment from "moment";
2831
- var DEFAULT_HEALTHY_BACKLOG, BACKLOG_GROWTH_RATE, SRSNavigator;
2965
+ var SRSNavigator;
2832
2966
  var init_srs = __esm({
2833
2967
  "src/core/navigators/generators/srs.ts"() {
2834
2968
  "use strict";
2835
2969
  init_navigators();
2836
2970
  init_SrsDebugger();
2971
+ init_regulators();
2837
2972
  init_logger();
2838
- DEFAULT_HEALTHY_BACKLOG = 20;
2839
- BACKLOG_GROWTH_RATE = 2;
2840
2973
  SRSNavigator = class extends ContentNavigator {
2841
2974
  /** Human-readable name for CardGenerator interface */
2842
2975
  name;
2843
- /** Healthy backlog threshold - when exceeded, backlog pressure kicks in */
2844
- healthyBacklog;
2845
2976
  constructor(user, course, strategyData) {
2846
2977
  super(user, course, strategyData);
2847
2978
  this.name = strategyData?.name || "SRS";
2848
- const config = this.parseConfig(strategyData?.serializedData);
2849
- this.healthyBacklog = config.healthyBacklog ?? DEFAULT_HEALTHY_BACKLOG;
2850
- }
2851
- /**
2852
- * Parse configuration from serialized JSON.
2853
- */
2854
- parseConfig(serializedData) {
2855
- if (!serializedData) return {};
2856
- try {
2857
- return JSON.parse(serializedData);
2858
- } catch {
2859
- logger.warn("[SRS] Failed to parse strategy config, using defaults");
2860
- return {};
2861
- }
2862
2979
  }
2863
2980
  /**
2864
2981
  * Get review cards scored by urgency.
@@ -2866,7 +2983,6 @@ var init_srs = __esm({
2866
2983
  * Score formula combines:
2867
2984
  * - Relative overdueness: hoursOverdue / intervalHours
2868
2985
  * - Interval recency: exponential decay favoring shorter intervals
2869
- * - Backlog pressure: boost when due reviews exceed healthy threshold
2870
2986
  *
2871
2987
  * Cards not yet due are excluded (not scored as 0).
2872
2988
  *
@@ -2903,7 +3019,6 @@ var init_srs = __esm({
2903
3019
  }
2904
3020
  }
2905
3021
  }
2906
- const backlogMultiplier = this.computeBacklogMultiplier(dueReviews.length);
2907
3022
  const notDue = reviews.filter((r) => !now.isAfter(moment.utc(r.reviewTime)));
2908
3023
  let nextDueIn = null;
2909
3024
  if (notDue.length > 0) {
@@ -2914,9 +3029,8 @@ var init_srs = __esm({
2914
3029
  nextDueIn = until.asHours() < 1 ? `${Math.round(until.asMinutes())}m` : until.asHours() < 24 ? `${Math.round(until.asHours())}h` : `${Math.round(until.asDays())}d`;
2915
3030
  }
2916
3031
  if (dueReviews.length > 0) {
2917
- const pressureNote = backlogMultiplier > 1 ? ` [backlog pressure: \xD7${backlogMultiplier.toFixed(2)}]` : ` [healthy backlog]`;
2918
3032
  logger.info(
2919
- `[SRS] Course ${courseId}: ${dueReviews.length} reviews due now (of ${reviews.length} scheduled)${pressureNote}`
3033
+ `[SRS] Course ${courseId}: ${dueReviews.length} reviews due now (of ${reviews.length} scheduled)`
2920
3034
  );
2921
3035
  } else if (reviews.length > 0) {
2922
3036
  const sortedByDue = [...reviews].sort(
@@ -2933,11 +3047,12 @@ var init_srs = __esm({
2933
3047
  logger.info(`[SRS] Course ${courseId}: No reviews scheduled`);
2934
3048
  }
2935
3049
  const scored = dueReviews.map((review) => {
2936
- const { score, reason } = this.computeUrgencyScore(review, now, backlogMultiplier);
3050
+ const { score, urgency, reason } = this.computeUrgencyScore(review, now);
2937
3051
  return {
2938
3052
  cardId: review.cardId,
2939
3053
  courseId: review.courseId,
2940
3054
  score,
3055
+ reviewUrgency: urgency,
2941
3056
  reviewID: review._id,
2942
3057
  provenance: [
2943
3058
  {
@@ -2956,47 +3071,20 @@ var init_srs = __esm({
2956
3071
  courseId,
2957
3072
  scheduledTotal: reviews.length,
2958
3073
  dueNow: dueReviews.length,
2959
- healthyBacklog: this.healthyBacklog,
2960
- backlogMultiplier,
2961
- backlogGrowthRate: BACKLOG_GROWTH_RATE,
3074
+ healthyBacklog: DEFAULT_REGULATOR_CONFIG.reviewMass.healthyMass,
3075
+ reviewMass: null,
3076
+ backlogMultiplier: 1,
3077
+ backlogGrowthRate: DEFAULT_REGULATOR_CONFIG.reviewMass.rate,
2962
3078
  topReviewScore: sorted.length > 0 ? sorted[0].score : null,
2963
3079
  nextDueIn,
2964
3080
  timestamp: Date.now()
2965
3081
  });
2966
3082
  return { cards: sorted.slice(0, limit) };
2967
3083
  }
2968
- /**
2969
- * Compute the multiplicative backlog pressure based on number of due reviews.
2970
- *
2971
- * ×1.0 at or below the healthy threshold (no boost); above it, grows as
2972
- * BACKLOG_GROWTH_RATE raised to the excess expressed in multiples of the
2973
- * healthy threshold. Uncapped — self-regulating instead: reviews winning
2974
- * slots depletes dueCount, which drops the ratio and relaxes the multiplier
2975
- * next run.
2976
- *
2977
- * Examples (with default healthyBacklog=20, BACKLOG_GROWTH_RATE=1.5):
2978
- * - 10 due reviews → ×1.00 (healthy)
2979
- * - 20 due reviews → ×1.00 (at threshold, ratio 0)
2980
- * - 40 due reviews → ×1.50 (ratio 1, 2x threshold)
2981
- * - 60 due reviews → ×2.25 (ratio 2, 3x threshold — old hard cap was ×2.00 here)
2982
- * - 100 due reviews → ×5.06 (ratio 4, 5x threshold)
2983
- * - 160 due reviews → ×17.09 (ratio 7, 8x threshold)
2984
- *
2985
- * @param dueCount - Number of reviews currently due
2986
- * @returns Multiplier applied to review urgency (>= 1.0, unbounded)
2987
- */
2988
- computeBacklogMultiplier(dueCount) {
2989
- if (dueCount <= this.healthyBacklog) {
2990
- return 1;
2991
- }
2992
- const excess = dueCount - this.healthyBacklog;
2993
- const ratio = excess / this.healthyBacklog;
2994
- return Math.pow(BACKLOG_GROWTH_RATE, ratio);
2995
- }
2996
3084
  /**
2997
3085
  * Compute urgency score for a review card.
2998
3086
  *
2999
- * Three factors:
3087
+ * Two factors:
3000
3088
  * 1. Relative overdueness = hoursOverdue / intervalHours
3001
3089
  * - 2 days overdue on 3-day interval = 0.67 (urgent)
3002
3090
  * - 2 days overdue on 180-day interval = 0.01 (not urgent)
@@ -3006,20 +3094,14 @@ var init_srs = __esm({
3006
3094
  * - 30 days (720h) → ~0.56
3007
3095
  * - 180 days → ~0.30
3008
3096
  *
3009
- * 3. Backlog pressure = global *multiplier* when review backlog exceeds the
3010
- * healthy threshold (×1.0 healthy → exponential growth, uncapped, above it).
3011
- *
3012
- * Combined: (base 0.5 + urgency factors * 0.45) × backlog multiplier.
3013
- * Per-card range before pressure: ~0.57–0.95. NOT clamped to 1.0 — under a
3014
- * heavy backlog reviews scale onto the open scale to compete with (and exceed)
3015
- * new cards; there's no ceiling at all now, so a bad enough backlog always
3016
- * wins eventually — self-regulating because winning slots depletes dueCount.
3097
+ * Combined: base 0.5 + urgency factors * 0.45, so ~0.57–0.95 per card.
3098
+ * Backlog pressure is applied later, by the regulator stage, which can lift
3099
+ * reviews onto the open scale above new cards (see regulators.ts).
3017
3100
  *
3018
3101
  * @param review - The scheduled card to score
3019
3102
  * @param now - Current time
3020
- * @param backlogMultiplier - Pre-computed backlog multiplier (>= 1.0, unbounded)
3021
3103
  */
3022
- computeUrgencyScore(review, now, backlogMultiplier) {
3104
+ computeUrgencyScore(review, now) {
3023
3105
  const scheduledAt = moment.utc(review.scheduledAt);
3024
3106
  const due = moment.utc(review.reviewTime);
3025
3107
  const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
@@ -3028,20 +3110,16 @@ var init_srs = __esm({
3028
3110
  const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
3029
3111
  const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
3030
3112
  const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
3031
- const baseScore = 0.5 + urgency * 0.45;
3032
- const score = baseScore * backlogMultiplier;
3113
+ const score = 0.5 + urgency * 0.45;
3033
3114
  const reasonParts = [
3034
3115
  `${Math.round(hoursOverdue)}h overdue`,
3035
3116
  `interval: ${Math.round(intervalHours)}h`,
3036
3117
  `relative: ${relativeOverdue.toFixed(2)}`,
3037
3118
  `recency: ${recencyFactor.toFixed(2)}`
3038
3119
  ];
3039
- if (backlogMultiplier > 1) {
3040
- reasonParts.push(`backlog: \xD7${backlogMultiplier.toFixed(2)}`);
3041
- }
3042
3120
  reasonParts.push("review");
3043
3121
  const reason = reasonParts.join(", ");
3044
- return { score, reason };
3122
+ return { score, urgency, reason };
3045
3123
  }
3046
3124
  };
3047
3125
  }
@@ -3096,6 +3174,8 @@ var init_WeightedFilter = __esm({
3096
3174
  init_contentNavigationStrategy();
3097
3175
  WeightedFilter = class {
3098
3176
  name;
3177
+ kind;
3178
+ liveOnly;
3099
3179
  inner;
3100
3180
  learnable;
3101
3181
  staticWeight;
@@ -3103,6 +3183,8 @@ var init_WeightedFilter = __esm({
3103
3183
  constructor(inner, learnable = DEFAULT_LEARNABLE_WEIGHT, staticWeight = false, strategyId) {
3104
3184
  this.inner = inner;
3105
3185
  this.name = inner.name;
3186
+ this.kind = inner.kind;
3187
+ this.liveOnly = inner.liveOnly;
3106
3188
  this.learnable = learnable;
3107
3189
  this.staticWeight = staticWeight;
3108
3190
  this.strategyId = strategyId;
@@ -3167,58 +3249,141 @@ var init_WeightedFilter = __esm({
3167
3249
  // src/core/navigators/filters/eloDistance.ts
3168
3250
  var eloDistance_exports = {};
3169
3251
  __export(eloDistance_exports, {
3170
- DEFAULT_HALF_LIFE: () => DEFAULT_HALF_LIFE,
3171
- DEFAULT_MAX_MULTIPLIER: () => DEFAULT_MAX_MULTIPLIER,
3172
- DEFAULT_MIN_MULTIPLIER: () => DEFAULT_MIN_MULTIPLIER,
3173
- createEloDistanceFilter: () => createEloDistanceFilter
3252
+ DEFAULT_ELO_DISTANCE_CONFIG: () => DEFAULT_ELO_DISTANCE_CONFIG,
3253
+ createEloDistanceFilter: () => createEloDistanceFilter,
3254
+ default: () => EloDistanceFilter,
3255
+ tagAwareGap: () => tagAwareGap
3174
3256
  });
3175
3257
  function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
3176
3258
  const normalizedDistance = distance / halfLife;
3177
3259
  const decay = Math.exp(-(normalizedDistance * normalizedDistance));
3178
3260
  return minMultiplier + (maxMultiplier - minMultiplier) * decay;
3179
3261
  }
3262
+ function resolveConfig(config) {
3263
+ return { ...DEFAULT_ELO_DISTANCE_CONFIG, ...config };
3264
+ }
3265
+ function tagAwareGap(cardTags, cardElo, userElo, minTagCount) {
3266
+ const globalGap = cardElo.global.score - userElo.global.score;
3267
+ const tags = [];
3268
+ for (const tag of cardTags) {
3269
+ const user = userElo.tags[tag];
3270
+ if (!user || user.score === COUNT_ONLY_SENTINEL || user.count < minTagCount) continue;
3271
+ const card = cardElo.tags[tag]?.score ?? cardElo.global.score;
3272
+ tags.push({
3273
+ tag,
3274
+ gap: card - user.score,
3275
+ weight: user.count / (user.count + TAG_CONFIDENCE_HALF)
3276
+ });
3277
+ }
3278
+ if (tags.length === 0) return { gap: globalGap, globalGap, tags };
3279
+ const total = tags.reduce((w, t) => w + t.weight, 0);
3280
+ const tagGap = tags.reduce((g, t) => g + t.weight * t.gap, 0) / total;
3281
+ const lambda = total / (total + 1);
3282
+ return { gap: lambda * tagGap + (1 - lambda) * globalGap, globalGap, tags };
3283
+ }
3284
+ function tagReason(tags, globalGap) {
3285
+ const shown = [...tags].sort((a, b) => Math.abs(b.gap) * b.weight - Math.abs(a.gap) * a.weight).slice(0, 3).map((t) => `${t.tag} ${t.gap >= 0 ? "+" : ""}${Math.round(t.gap)}`).join(", ");
3286
+ const more = tags.length > 3 ? `, +${tags.length - 3} more` : "";
3287
+ return ` on ${tags.length} shared tag(s) [${shown}${more}] (global ${globalGap >= 0 ? "+" : ""}${Math.round(globalGap)})`;
3288
+ }
3289
+ async function applyEloDistance(cards, context, config, source) {
3290
+ const { course, userElo, userCourseElo } = context;
3291
+ const { halfLife, minMultiplier, maxMultiplier } = config;
3292
+ const tagAware = config.tagAware && userCourseElo !== void 0;
3293
+ const missing = cards.filter((c) => tagAware || c.cardElo === void 0).map((c) => c.cardId);
3294
+ const fetched = /* @__PURE__ */ new Map();
3295
+ if (missing.length > 0) {
3296
+ const elos = await course.getCardEloData(missing);
3297
+ missing.forEach((id, i) => {
3298
+ if (elos[i]) fetched.set(id, elos[i]);
3299
+ });
3300
+ }
3301
+ return cards.map((card) => {
3302
+ const full = fetched.get(card.cardId);
3303
+ const cardElo = full?.global?.score ?? card.cardElo ?? DEFAULT_CARD_ELO;
3304
+ let distance = Math.abs(cardElo - userElo);
3305
+ let how = "";
3306
+ if (tagAware && full) {
3307
+ const t = tagAwareGap(card.tags ?? [], full, userCourseElo, config.minTagCount);
3308
+ distance = Math.abs(t.gap);
3309
+ if (t.tags.length > 0) how = tagReason(t.tags, t.globalGap);
3310
+ }
3311
+ const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
3312
+ const newScore = card.score * multiplier;
3313
+ const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
3314
+ return {
3315
+ ...card,
3316
+ cardElo,
3317
+ score: newScore,
3318
+ provenance: [
3319
+ ...card.provenance,
3320
+ {
3321
+ strategy: "eloDistance",
3322
+ strategyName: source.name,
3323
+ strategyId: source.strategyId,
3324
+ action,
3325
+ score: newScore,
3326
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)})${how} \u2192 ${multiplier.toFixed(2)}x`
3327
+ }
3328
+ ]
3329
+ };
3330
+ });
3331
+ }
3180
3332
  function createEloDistanceFilter(config) {
3181
- const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
3182
- const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
3183
- const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
3333
+ const resolved = resolveConfig(config);
3334
+ const source = { name: "ELO Distance Filter", strategyId: "ELO_DISTANCE_FILTER" };
3184
3335
  return {
3185
- name: "ELO Distance Filter",
3186
- async transform(cards, context) {
3187
- const { course, userElo } = context;
3188
- const cardIds = cards.map((c) => c.cardId);
3189
- const cardElos = await course.getCardEloData(cardIds);
3190
- return cards.map((card, i) => {
3191
- const cardElo = cardElos[i]?.global?.score ?? 1e3;
3192
- const distance = Math.abs(cardElo - userElo);
3193
- const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
3194
- const newScore = card.score * multiplier;
3195
- const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
3196
- return {
3197
- ...card,
3198
- score: newScore,
3199
- provenance: [
3200
- ...card.provenance,
3201
- {
3202
- strategy: "eloDistance",
3203
- strategyName: "ELO Distance Filter",
3204
- strategyId: "ELO_DISTANCE_FILTER",
3205
- action,
3206
- score: newScore,
3207
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
3208
- }
3209
- ]
3210
- };
3211
- });
3212
- }
3336
+ name: source.name,
3337
+ kind: "signal",
3338
+ liveOnly: true,
3339
+ transform: (cards, context) => applyEloDistance(cards, context, resolved, source)
3213
3340
  };
3214
3341
  }
3215
- var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
3342
+ var DEFAULT_ELO_DISTANCE_CONFIG, TAG_CONFIDENCE_HALF, COUNT_ONLY_SENTINEL, DEFAULT_CARD_ELO, EloDistanceFilter;
3216
3343
  var init_eloDistance = __esm({
3217
3344
  "src/core/navigators/filters/eloDistance.ts"() {
3218
3345
  "use strict";
3219
- DEFAULT_HALF_LIFE = 200;
3220
- DEFAULT_MIN_MULTIPLIER = 0.3;
3221
- DEFAULT_MAX_MULTIPLIER = 1;
3346
+ init_navigators();
3347
+ DEFAULT_ELO_DISTANCE_CONFIG = {
3348
+ halfLife: 300,
3349
+ minMultiplier: 0.05,
3350
+ maxMultiplier: 1,
3351
+ tagAware: true,
3352
+ minTagCount: 3
3353
+ };
3354
+ TAG_CONFIDENCE_HALF = 10;
3355
+ COUNT_ONLY_SENTINEL = -1;
3356
+ DEFAULT_CARD_ELO = 1e3;
3357
+ EloDistanceFilter = class _EloDistanceFilter extends ContentNavigator {
3358
+ name;
3359
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3360
+ static kind = "signal";
3361
+ kind = _EloDistanceFilter.kind;
3362
+ liveOnly = true;
3363
+ config;
3364
+ constructor(user, course, strategyData) {
3365
+ super(user, course, strategyData);
3366
+ this.name = strategyData.name || "ELO Distance";
3367
+ let parsed;
3368
+ try {
3369
+ parsed = strategyData.serializedData ? JSON.parse(strategyData.serializedData) : void 0;
3370
+ } catch {
3371
+ parsed = void 0;
3372
+ }
3373
+ this.config = resolveConfig(parsed);
3374
+ }
3375
+ transform(cards, context) {
3376
+ return applyEloDistance(cards, context, this.config, {
3377
+ name: this.name,
3378
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-eloDistance-default"
3379
+ });
3380
+ }
3381
+ async getWeightedCards(_limit) {
3382
+ throw new Error(
3383
+ "EloDistanceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
3384
+ );
3385
+ }
3386
+ };
3222
3387
  }
3223
3388
  });
3224
3389
 
@@ -3235,10 +3400,13 @@ var init_hierarchyDefinition = __esm({
3235
3400
  init_navigators();
3236
3401
  init_logger();
3237
3402
  DEFAULT_MIN_COUNT2 = 3;
3238
- HierarchyDefinitionNavigator = class extends ContentNavigator {
3403
+ HierarchyDefinitionNavigator = class _HierarchyDefinitionNavigator extends ContentNavigator {
3239
3404
  config;
3240
3405
  /** Human-readable name for CardFilter interface */
3241
3406
  name;
3407
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3408
+ static kind = "gate";
3409
+ kind = _HierarchyDefinitionNavigator.kind;
3242
3410
  constructor(user, course, strategyData) {
3243
3411
  super(user, course, strategyData);
3244
3412
  this.config = this.parseConfig(strategyData.serializedData);
@@ -3505,10 +3673,13 @@ var init_userTagPreference = __esm({
3505
3673
  "src/core/navigators/filters/userTagPreference.ts"() {
3506
3674
  "use strict";
3507
3675
  init_navigators();
3508
- UserTagPreferenceFilter = class extends ContentNavigator {
3676
+ UserTagPreferenceFilter = class _UserTagPreferenceFilter extends ContentNavigator {
3509
3677
  _strategyData;
3510
3678
  /** Human-readable name for CardFilter interface */
3511
3679
  name;
3680
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3681
+ static kind = "signal";
3682
+ kind = _UserTagPreferenceFilter.kind;
3512
3683
  constructor(user, course, strategyData) {
3513
3684
  super(user, course, strategyData);
3514
3685
  this._strategyData = strategyData;
@@ -3618,6 +3789,7 @@ var init_userTagPreference = __esm({
3618
3789
  // src/core/navigators/filters/index.ts
3619
3790
  var filters_exports = {};
3620
3791
  __export(filters_exports, {
3792
+ EloDistanceFilter: () => EloDistanceFilter,
3621
3793
  UserTagPreferenceFilter: () => UserTagPreferenceFilter,
3622
3794
  createEloDistanceFilter: () => createEloDistanceFilter
3623
3795
  });
@@ -3656,10 +3828,13 @@ var init_interferenceMitigator = __esm({
3656
3828
  DEFAULT_MIN_COUNT3 = 10;
3657
3829
  DEFAULT_MIN_ELAPSED_DAYS = 3;
3658
3830
  DEFAULT_INTERFERENCE_DECAY = 0.8;
3659
- InterferenceMitigatorNavigator = class extends ContentNavigator {
3831
+ InterferenceMitigatorNavigator = class _InterferenceMitigatorNavigator extends ContentNavigator {
3660
3832
  config;
3661
3833
  /** Human-readable name for CardFilter interface */
3662
3834
  name;
3835
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3836
+ static kind = "signal";
3837
+ kind = _InterferenceMitigatorNavigator.kind;
3663
3838
  /** Precomputed map: tag -> set of { partner, decay } it interferes with */
3664
3839
  interferenceMap;
3665
3840
  constructor(user, course, strategyData) {
@@ -3875,10 +4050,13 @@ var init_relativePriority = __esm({
3875
4050
  DEFAULT_PRIORITY = 0.5;
3876
4051
  DEFAULT_PRIORITY_INFLUENCE = 0.5;
3877
4052
  DEFAULT_COMBINE_MODE = "max";
3878
- RelativePriorityNavigator = class extends ContentNavigator {
4053
+ RelativePriorityNavigator = class _RelativePriorityNavigator extends ContentNavigator {
3879
4054
  config;
3880
4055
  /** Human-readable name for CardFilter interface */
3881
4056
  name;
4057
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
4058
+ static kind = "signal";
4059
+ kind = _RelativePriorityNavigator.kind;
3882
4060
  constructor(user, course, strategyData) {
3883
4061
  super(user, course, strategyData);
3884
4062
  this.config = this.parseConfig(strategyData.serializedData);
@@ -4532,6 +4710,8 @@ var init_Pipeline = __esm({
4532
4710
  init_orchestration();
4533
4711
  init_PipelineDebugger();
4534
4712
  init_diversityRerank();
4713
+ init_regulators();
4714
+ init_SrsDebugger();
4535
4715
  VERBOSE_RESULTS = true;
4536
4716
  Pipeline = class extends ContentNavigator {
4537
4717
  generator;
@@ -4557,6 +4737,13 @@ var init_Pipeline = __esm({
4557
4737
  * getWeightedCards() call, then cleared.
4558
4738
  */
4559
4739
  _ephemeralHints = null;
4740
+ /**
4741
+ * The intake valve's clock (see regulators.ts), loaded from strategy state on
4742
+ * first use and kept in memory. Writes are chained so a presentation and a
4743
+ * run can't race each other's revision.
4744
+ */
4745
+ _intakeClock = null;
4746
+ _intakeClockWrite = Promise.resolve();
4560
4747
  /**
4561
4748
  * Create a new pipeline.
4562
4749
  *
@@ -4631,13 +4818,12 @@ var init_Pipeline = __esm({
4631
4818
  }
4632
4819
  }
4633
4820
  generatorSummaries = Array.from(genMap.entries()).map(([name, data]) => {
4634
- const newCards = data.cards.filter((c) => c.provenance[0]?.reason?.includes("new card"));
4635
- const reviewCards = data.cards.filter((c) => c.provenance[0]?.reason?.includes("review"));
4821
+ const reviewCount = data.cards.filter((c) => c.reviewID).length;
4636
4822
  return {
4637
4823
  name,
4638
4824
  cardCount: data.cards.length,
4639
- newCount: newCards.length,
4640
- reviewCount: reviewCards.length,
4825
+ newCount: data.cards.length - reviewCount,
4826
+ reviewCount,
4641
4827
  topScore: Math.max(...data.cards.map((c) => c.score), 0)
4642
4828
  };
4643
4829
  });
@@ -4673,19 +4859,24 @@ var init_Pipeline = __esm({
4673
4859
  cards.filter((c) => c.provenance.some((p) => p.strategy === "prescribed")).map((c) => c.cardId)
4674
4860
  );
4675
4861
  const filterImpacts = [];
4862
+ const generatedScores = new Map(cards.map((c) => [c.cardId, c.score]));
4863
+ const gated = /* @__PURE__ */ new Set();
4676
4864
  for (const filter of this.filters) {
4677
4865
  const beforeCount = cards.length;
4678
4866
  const beforeScores = new Map(cards.map((c) => [c.cardId, c.score]));
4679
4867
  cards = await filter.transform(cards, context);
4680
4868
  let boosted = 0, penalized = 0, passed = 0;
4681
4869
  const removed = beforeCount - cards.length;
4870
+ const kind = filter.kind ?? "gate";
4682
4871
  for (const card of cards) {
4683
4872
  const before = beforeScores.get(card.cardId) ?? 0;
4684
4873
  if (card.score > before) boosted++;
4685
- else if (card.score < before) penalized++;
4686
- else passed++;
4874
+ else if (card.score < before) {
4875
+ penalized++;
4876
+ if (kind === "gate") gated.add(card.cardId);
4877
+ } else passed++;
4687
4878
  }
4688
- filterImpacts.push({ name: filter.name, boosted, penalized, passed, removed });
4879
+ filterImpacts.push({ name: filter.name, kind, boosted, penalized, passed, removed });
4689
4880
  if (prescribedIds.size > 0) {
4690
4881
  const survivingIds = new Set(cards.map((c) => c.cardId));
4691
4882
  const killedPrescribed = [...prescribedIds].filter((id) => !survivingIds.has(id));
@@ -4699,7 +4890,9 @@ var init_Pipeline = __esm({
4699
4890
  }
4700
4891
  logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeScores.size} \u2192 ${cards.length} cards (\u2191${boosted} \u2193${penalized} =${passed})`);
4701
4892
  }
4893
+ const scoredCards = cards;
4702
4894
  cards = cards.filter((c) => c.score > 0);
4895
+ const regulators = await this.regulate(cards, generatedScores, gated);
4703
4896
  const hints = this._ephemeralHints;
4704
4897
  if (hints) {
4705
4898
  this._ephemeralHints = null;
@@ -4735,7 +4928,9 @@ var init_Pipeline = __esm({
4735
4928
  cards,
4736
4929
  result,
4737
4930
  context.userElo,
4738
- hints ?? void 0
4931
+ hints ?? void 0,
4932
+ scoredCards,
4933
+ regulators
4739
4934
  );
4740
4935
  captureRun(report);
4741
4936
  } catch (e) {
@@ -4914,6 +5109,77 @@ var init_Pipeline = __esm({
4914
5109
  logger.info(`[Pipeline] Hints applied: ${beforeCount} \u2192 ${cards.length} cards`);
4915
5110
  return cards;
4916
5111
  }
5112
+ /**
5113
+ * The regulator stage: measure each class's pressure and scale it.
5114
+ *
5115
+ * - Review mass: every due review's SRS urgency times the filters' net
5116
+ * effect on it.
5117
+ * - Intake: servable hours since a new card was presented, applied only to
5118
+ * eligible new cards (no gate penalized them). With none eligible, the
5119
+ * clock freezes.
5120
+ *
5121
+ * Mutates `cards` in place; returns the readings for the run report.
5122
+ */
5123
+ async regulate(cards, generatedScores, gated) {
5124
+ const config = DEFAULT_REGULATOR_CONFIG;
5125
+ const reviews = cards.filter((c) => c.reviewID);
5126
+ const newCards = cards.filter((c) => !c.reviewID);
5127
+ const eligibleNew = newCards.filter((c) => !gated.has(c.cardId));
5128
+ const mass = reviewMassReading(reviews, generatedScores, config.reviewMass);
5129
+ applyReading(reviews, mass);
5130
+ noteReviewPressure(this.course.getCourseID(), {
5131
+ mass: mass.urgency,
5132
+ healthyMass: config.reviewMass.healthyMass,
5133
+ rate: config.reviewMass.rate,
5134
+ multiplier: mass.multiplier
5135
+ });
5136
+ const now = Date.now();
5137
+ const clock = await this.loadIntakeClock(now);
5138
+ const stepped = stepIntakeClock(clock, now, eligibleNew.length);
5139
+ if (stepped !== clock) this.saveIntakeClock(stepped);
5140
+ const intake = intakeReading(
5141
+ stepped,
5142
+ now,
5143
+ { eligibleNew: eligibleNew.length, newCandidates: newCards.length },
5144
+ config.intake
5145
+ );
5146
+ applyReading(eligibleNew, intake);
5147
+ logger.info(
5148
+ `[Pipeline:regulators] review mass ${mass.urgency.toFixed(1)} over ${reviews.length} due \u2192 \xD7${mass.multiplier.toFixed(2)}; intake ${intake.urgency.toFixed(1)}h, ${eligibleNew.length}/${newCards.length} new eligible \u2192 \xD7${intake.multiplier.toFixed(2)}`
5149
+ );
5150
+ return [mass, intake];
5151
+ }
5152
+ /**
5153
+ * A card was presented. A new card's first presentation discharges the
5154
+ * intake valve: its clock restarts. Called by the SessionController.
5155
+ */
5156
+ notePresented(card) {
5157
+ if (card.status !== "new" || card.courseId !== this.course?.getCourseID()) return;
5158
+ this.saveIntakeClock(resetIntakeClock(Date.now()));
5159
+ }
5160
+ async loadIntakeClock(nowMs) {
5161
+ if (this._intakeClock) return this._intakeClock;
5162
+ let stored = null;
5163
+ try {
5164
+ stored = await this.user.getStrategyState(
5165
+ this.course.getCourseID(),
5166
+ INTAKE_CLOCK_KEY
5167
+ );
5168
+ } catch (e) {
5169
+ logger.warn(`[Pipeline:regulators] Could not read the intake clock: ${e}`);
5170
+ }
5171
+ if (stored) {
5172
+ this._intakeClock = stored;
5173
+ } else {
5174
+ this.saveIntakeClock(resetIntakeClock(nowMs));
5175
+ }
5176
+ return this._intakeClock;
5177
+ }
5178
+ saveIntakeClock(state) {
5179
+ this._intakeClock = state;
5180
+ const courseId = this.course.getCourseID();
5181
+ this._intakeClockWrite = this._intakeClockWrite.then(() => this.user.putStrategyState(courseId, INTAKE_CLOCK_KEY, state)).catch((e) => logger.warn(`[Pipeline:regulators] Could not save the intake clock: ${e}`));
5182
+ }
4917
5183
  /**
4918
5184
  * Build shared context for generator and filters.
4919
5185
  *
@@ -4924,10 +5190,11 @@ var init_Pipeline = __esm({
4924
5190
  */
4925
5191
  async buildContext() {
4926
5192
  let userElo = 1e3;
5193
+ let userCourseElo;
4927
5194
  try {
4928
5195
  const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
4929
- const courseElo = toCourseElo5(courseReg.elo);
4930
- userElo = courseElo.global.score;
5196
+ userCourseElo = toCourseElo5(courseReg.elo);
5197
+ userElo = userCourseElo.global.score;
4931
5198
  } catch (e) {
4932
5199
  logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
4933
5200
  }
@@ -4939,6 +5206,7 @@ var init_Pipeline = __esm({
4939
5206
  user: this.user,
4940
5207
  course: this.course,
4941
5208
  userElo,
5209
+ ...userCourseElo ? { userCourseElo } : {},
4942
5210
  orchestration
4943
5211
  };
4944
5212
  }
@@ -5052,7 +5320,7 @@ var init_Pipeline = __esm({
5052
5320
  cards = await this.hydrateTags(cards);
5053
5321
  const fullPool = cards.slice();
5054
5322
  const context = await this.buildContext();
5055
- for (const filter of this.filters) {
5323
+ for (const filter of this.forecastFilters()) {
5056
5324
  cards = await filter.transform(cards, context);
5057
5325
  }
5058
5326
  if (opts?.hints) {
@@ -5071,6 +5339,14 @@ var init_Pipeline = __esm({
5071
5339
  cards.sort((a, b) => b.score - a.score);
5072
5340
  return opts?.limit ? cards.slice(0, opts.limit) : cards;
5073
5341
  }
5342
+ /**
5343
+ * The filters a forecast or card-space scan applies. Those start every card at
5344
+ * 1.0 without a generator, so they skip `liveOnly` filters (ELO distance),
5345
+ * which only make sense against generator scores.
5346
+ */
5347
+ forecastFilters() {
5348
+ return this.filters.filter((f) => !f.liveOnly);
5349
+ }
5074
5350
  /**
5075
5351
  * Scan every card in the course through the filter chain and report
5076
5352
  * how many are "well indicated" (score >= threshold) for the current user.
@@ -5092,7 +5368,7 @@ var init_Pipeline = __esm({
5092
5368
  cards = await this.hydrateTags(cards);
5093
5369
  const context = await this.buildContext();
5094
5370
  const filterBreakdown = [];
5095
- for (const filter of this.filters) {
5371
+ for (const filter of this.forecastFilters()) {
5096
5372
  cards = await filter.transform(cards, context);
5097
5373
  const wi = cards.filter((c) => c.score >= THRESHOLD).length;
5098
5374
  filterBreakdown.push({ name: filter.name, wellIndicated: wi });
@@ -5156,6 +5432,7 @@ var init_Pipeline = __esm({
5156
5432
  // src/core/navigators/defaults.ts
5157
5433
  var defaults_exports = {};
5158
5434
  __export(defaults_exports, {
5435
+ createDefaultEloDistanceStrategy: () => createDefaultEloDistanceStrategy,
5159
5436
  createDefaultEloStrategy: () => createDefaultEloStrategy,
5160
5437
  createDefaultPipeline: () => createDefaultPipeline,
5161
5438
  createDefaultSrsStrategy: () => createDefaultSrsStrategy
@@ -5182,12 +5459,28 @@ function createDefaultSrsStrategy(courseId) {
5182
5459
  serializedData: ""
5183
5460
  };
5184
5461
  }
5462
+ function createDefaultEloDistanceStrategy(courseId) {
5463
+ return {
5464
+ _id: "NAVIGATION_STRATEGY-eloDistance-default",
5465
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
5466
+ name: "ELO Distance (default)",
5467
+ description: "Scales every candidate, new or review, by its distance from the learner's ELO",
5468
+ implementingClass: "eloDistance" /* ELO_DISTANCE */,
5469
+ course: courseId,
5470
+ // Explicit, though the filter would default to it anyway: views show what runs.
5471
+ serializedData: JSON.stringify(DEFAULT_ELO_DISTANCE_CONFIG)
5472
+ };
5473
+ }
5185
5474
  function createDefaultPipeline(user, course) {
5186
5475
  const courseId = course.getCourseID();
5187
5476
  const eloNavigator = new ELONavigator(user, course, createDefaultEloStrategy(courseId));
5188
5477
  const srsNavigator = new SRSNavigator(user, course, createDefaultSrsStrategy(courseId));
5189
5478
  const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);
5190
- const eloDistanceFilter = createEloDistanceFilter();
5479
+ const eloDistanceFilter = new EloDistanceFilter(
5480
+ user,
5481
+ course,
5482
+ createDefaultEloDistanceStrategy(courseId)
5483
+ );
5191
5484
  return new Pipeline(compositeGenerator, [eloDistanceFilter], user, course);
5192
5485
  }
5193
5486
  var init_defaults = __esm({
@@ -5203,6 +5496,131 @@ var init_defaults = __esm({
5203
5496
  }
5204
5497
  });
5205
5498
 
5499
+ // src/core/navigators/pipelinePlan.ts
5500
+ var pipelinePlan_exports = {};
5501
+ __export(pipelinePlan_exports, {
5502
+ PIPELINE_STAGES: () => PIPELINE_STAGES,
5503
+ planPipeline: () => planPipeline
5504
+ });
5505
+ function planned(strategy, role, origin) {
5506
+ const kind = role === "filter" /* FILTER */ ? getRegisteredFilterKind(strategy.implementingClass) : void 0;
5507
+ return {
5508
+ role,
5509
+ origin,
5510
+ name: strategy.name,
5511
+ implementingClass: strategy.implementingClass,
5512
+ strategy,
5513
+ ...kind ? { kind } : {}
5514
+ };
5515
+ }
5516
+ function planPipeline(strategies, courseId) {
5517
+ if (strategies.length === 0) {
5518
+ return {
5519
+ kind: "default",
5520
+ generators: [
5521
+ planned(createDefaultEloStrategy(courseId), "generator" /* GENERATOR */, "default-pipeline"),
5522
+ planned(createDefaultSrsStrategy(courseId), "generator" /* GENERATOR */, "default-pipeline")
5523
+ ],
5524
+ filters: [
5525
+ planned(
5526
+ createDefaultEloDistanceStrategy(courseId),
5527
+ "filter" /* FILTER */,
5528
+ "default-pipeline"
5529
+ )
5530
+ ],
5531
+ skipped: [],
5532
+ warnings: [],
5533
+ notes: [],
5534
+ regulators: DEFAULT_REGULATOR_CONFIG
5535
+ };
5536
+ }
5537
+ const generators = [];
5538
+ const filters = [];
5539
+ const skipped = [];
5540
+ const warnings = [];
5541
+ for (const s of strategies) {
5542
+ if (isGenerator(s.implementingClass)) {
5543
+ generators.push(planned(s, "generator" /* GENERATOR */, "strategy-doc"));
5544
+ } else if (isFilter(s.implementingClass)) {
5545
+ filters.push(planned(s, "filter" /* FILTER */, "strategy-doc"));
5546
+ } else {
5547
+ skipped.push({ strategy: s, reason: "not a registered generator or filter" });
5548
+ warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
5549
+ }
5550
+ }
5551
+ const declared = new Set(generators.map((g) => g.implementingClass));
5552
+ if (!declared.has(createDefaultEloStrategy(courseId).implementingClass)) {
5553
+ generators.push(
5554
+ planned(createDefaultEloStrategy(courseId), "generator" /* GENERATOR */, "assembler-default")
5555
+ );
5556
+ }
5557
+ if (!declared.has(createDefaultSrsStrategy(courseId).implementingClass)) {
5558
+ generators.push(
5559
+ planned(createDefaultSrsStrategy(courseId), "generator" /* GENERATOR */, "assembler-default")
5560
+ );
5561
+ }
5562
+ const eloDistance = createDefaultEloDistanceStrategy(courseId);
5563
+ if (!filters.some((f) => f.implementingClass === eloDistance.implementingClass)) {
5564
+ filters.push(planned(eloDistance, "filter" /* FILTER */, "assembler-default"));
5565
+ }
5566
+ filters.sort((a, b) => a.name.localeCompare(b.name));
5567
+ return {
5568
+ kind: "assembled",
5569
+ generators,
5570
+ filters,
5571
+ skipped,
5572
+ warnings,
5573
+ notes: [],
5574
+ regulators: DEFAULT_REGULATOR_CONFIG
5575
+ };
5576
+ }
5577
+ var PIPELINE_STAGES;
5578
+ var init_pipelinePlan = __esm({
5579
+ "src/core/navigators/pipelinePlan.ts"() {
5580
+ "use strict";
5581
+ init_navigators();
5582
+ init_regulators();
5583
+ init_defaults();
5584
+ PIPELINE_STAGES = [
5585
+ {
5586
+ key: "generate",
5587
+ title: "Generate",
5588
+ summary: "Each generator proposes candidates (up to 500 in all), scored on what is specific to its source. A card proposed by several generators keeps their mean score, raised 10% per extra generator."
5589
+ },
5590
+ {
5591
+ key: "filter",
5592
+ title: "Filter",
5593
+ summary: "Each filter multiplies candidate scores, in the order shown. A gate says a card is not ready yet; a signal expresses preference. Gates usually penalize rather than remove, so a gated card stays in the pool at a low score."
5594
+ },
5595
+ {
5596
+ key: "drop-zero",
5597
+ title: "Drop zero scores",
5598
+ summary: "Candidates whose score reached 0 leave the pool."
5599
+ },
5600
+ {
5601
+ key: "regulate",
5602
+ title: "Regulate",
5603
+ summary: "Balances reviews against new cards. Review mass: the due reviews weighed by their filtered scores; above a healthy level, every review is lifted. Intake: hours since a new card was last presented; new cards no gate penalized are lifted, and the clock stops while there are none."
5604
+ },
5605
+ {
5606
+ key: "hints",
5607
+ title: "Apply hints",
5608
+ summary: "The session's hints (from the app: an intro's follow-up, a difficulty boost) exclude, boost, or require cards. Required cards skip the filters entirely."
5609
+ },
5610
+ {
5611
+ key: "diversity",
5612
+ title: "Diversity re-rank",
5613
+ summary: "Demotes candidates that repeat a distinctive tag already ranked above them, so one concept or answer cannot take the whole head of the queue. Sees this run only, not what the session already served."
5614
+ },
5615
+ {
5616
+ key: "select",
5617
+ title: "Select",
5618
+ summary: "Highest scores first, up to the run's limit. The session mixes them into its supply queue."
5619
+ }
5620
+ ];
5621
+ }
5622
+ });
5623
+
5206
5624
  // src/core/navigators/PipelineAssembler.ts
5207
5625
  var PipelineAssembler_exports = {};
5208
5626
  __export(PipelineAssembler_exports, {
@@ -5217,16 +5635,16 @@ var init_PipelineAssembler = __esm({
5217
5635
  init_Pipeline();
5218
5636
  init_logger();
5219
5637
  init_CompositeGenerator();
5220
- init_defaults();
5638
+ init_pipelinePlan();
5221
5639
  PipelineAssembler = class {
5222
5640
  /**
5223
5641
  * Assembles a navigation pipeline from strategy documents.
5224
5642
  *
5225
- * 1. Separates into generators and filters by role
5226
- * 2. Validates at least one generator exists (or creates default ELO)
5227
- * 3. Instantiates generators - wraps multiple in CompositeGenerator
5228
- * 4. Instantiates filters
5229
- * 5. Returns Pipeline(generator, filters)
5643
+ * 1. Plans: classifies by role, adds default ELO/SRS and ELO distance, orders filters
5644
+ * (`planPipeline`)
5645
+ * 2. Instantiates generators - wraps multiple in CompositeGenerator
5646
+ * 3. Instantiates filters
5647
+ * 4. Returns Pipeline(generator, filters)
5230
5648
  *
5231
5649
  * @param input - Strategy documents plus user/course interfaces
5232
5650
  * @returns Assembled pipeline and any warnings
@@ -5242,28 +5660,17 @@ var init_PipelineAssembler = __esm({
5242
5660
  warnings
5243
5661
  };
5244
5662
  }
5245
- const generatorStrategies = [];
5246
- const filterStrategies = [];
5247
- for (const s of strategies) {
5248
- if (isGenerator(s.implementingClass)) {
5249
- generatorStrategies.push(s);
5250
- } else if (isFilter(s.implementingClass)) {
5251
- filterStrategies.push(s);
5252
- } else {
5253
- warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
5663
+ const plan = planPipeline(strategies, course.getCourseID());
5664
+ warnings.push(...plan.warnings);
5665
+ for (const n of [...plan.generators, ...plan.filters]) {
5666
+ if (n.origin === "assembler-default") {
5667
+ logger.debug(
5668
+ `[PipelineAssembler] No ${n.implementingClass} ${n.role} configured, adding default`
5669
+ );
5254
5670
  }
5255
5671
  }
5256
- const courseId = course.getCourseID();
5257
- const hasElo = generatorStrategies.some((s) => s.implementingClass === "elo" /* ELO */);
5258
- const hasSrs = generatorStrategies.some((s) => s.implementingClass === "srs" /* SRS */);
5259
- if (!hasElo) {
5260
- logger.debug("[PipelineAssembler] No ELO generator configured, adding default");
5261
- generatorStrategies.push(createDefaultEloStrategy(courseId));
5262
- }
5263
- if (!hasSrs) {
5264
- logger.debug("[PipelineAssembler] No SRS generator configured, adding default");
5265
- generatorStrategies.push(createDefaultSrsStrategy(courseId));
5266
- }
5672
+ const generatorStrategies = plan.generators.map((g) => g.strategy);
5673
+ const sortedFilterStrategies = plan.filters.map((f) => f.strategy);
5267
5674
  if (generatorStrategies.length === 0) {
5268
5675
  warnings.push("No generator strategy found");
5269
5676
  return {
@@ -5285,9 +5692,6 @@ var init_PipelineAssembler = __esm({
5285
5692
  generator = await CompositeGenerator.fromStrategies(user, course, generatorStrategies);
5286
5693
  }
5287
5694
  const filters = [];
5288
- const sortedFilterStrategies = [...filterStrategies].sort(
5289
- (a, b) => a.name.localeCompare(b.name)
5290
- );
5291
5695
  for (const filterStrategy of sortedFilterStrategies) {
5292
5696
  try {
5293
5697
  const nav = await ContentNavigator.create(user, course, filterStrategy);
@@ -5355,7 +5759,9 @@ var init_3 = __esm({
5355
5759
  "./generators/prescribed.ts": () => Promise.resolve().then(() => (init_prescribed(), prescribed_exports)),
5356
5760
  "./generators/srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
5357
5761
  "./generators/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports)),
5358
- "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports))
5762
+ "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports)),
5763
+ "./pipelinePlan.ts": () => Promise.resolve().then(() => (init_pipelinePlan(), pipelinePlan_exports)),
5764
+ "./regulators.ts": () => Promise.resolve().then(() => (init_regulators(), regulators_exports))
5359
5765
  });
5360
5766
  }
5361
5767
  });
@@ -5376,6 +5782,7 @@ __export(navigators_exports, {
5376
5782
  drainCapturedRuns: () => drainCapturedRuns,
5377
5783
  getActivePipeline: () => getActivePipeline,
5378
5784
  getCardOrigin: () => getCardOrigin,
5785
+ getRegisteredFilterKind: () => getRegisteredFilterKind,
5379
5786
  getRegisteredNavigator: () => getRegisteredNavigator,
5380
5787
  getRegisteredNavigatorNames: () => getRegisteredNavigatorNames,
5381
5788
  getRegisteredNavigatorRole: () => getRegisteredNavigatorRole,
@@ -5404,6 +5811,10 @@ function hasRegisteredNavigator(implementingClass) {
5404
5811
  function getRegisteredNavigatorRole(implementingClass) {
5405
5812
  return navigatorRegistry.get(implementingClass)?.role;
5406
5813
  }
5814
+ function getRegisteredFilterKind(implementingClass) {
5815
+ const ctor = navigatorRegistry.get(implementingClass)?.constructor;
5816
+ return ctor?.kind;
5817
+ }
5407
5818
  function getRegisteredNavigatorNames() {
5408
5819
  return Array.from(navigatorRegistry.keys());
5409
5820
  }
@@ -5421,17 +5832,20 @@ async function initializeNavigatorRegistry() {
5421
5832
  hierarchyModule,
5422
5833
  interferenceModule,
5423
5834
  relativePriorityModule,
5424
- userTagPreferenceModule
5835
+ userTagPreferenceModule,
5836
+ eloDistanceModule
5425
5837
  ] = await Promise.all([
5426
5838
  Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
5427
5839
  Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
5428
5840
  Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
5429
- Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports))
5841
+ Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports)),
5842
+ Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports))
5430
5843
  ]);
5431
5844
  registerNavigator("hierarchyDefinition", hierarchyModule.default);
5432
5845
  registerNavigator("interferenceMitigator", interferenceModule.default);
5433
5846
  registerNavigator("relativePriority", relativePriorityModule.default);
5434
5847
  registerNavigator("userTagPreference", userTagPreferenceModule.default);
5848
+ registerNavigator("eloDistance", eloDistanceModule.default);
5435
5849
  logger.debug(
5436
5850
  `[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(", ")}`
5437
5851
  );
@@ -5479,6 +5893,7 @@ var init_navigators = __esm({
5479
5893
  Navigators2["INTERFERENCE"] = "interferenceMitigator";
5480
5894
  Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
5481
5895
  Navigators2["USER_TAG_PREFERENCE"] = "userTagPreference";
5896
+ Navigators2["ELO_DISTANCE"] = "eloDistance";
5482
5897
  return Navigators2;
5483
5898
  })(Navigators || {});
5484
5899
  NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
@@ -5493,7 +5908,8 @@ var init_navigators = __esm({
5493
5908
  ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
5494
5909
  ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
5495
5910
  ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
5496
- ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
5911
+ ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */,
5912
+ ["eloDistance" /* ELO_DISTANCE */]: "filter" /* FILTER */
5497
5913
  };
5498
5914
  ContentNavigator = class {
5499
5915
  /** User interface for this navigation session */
@@ -6277,6 +6693,14 @@ ${e.stack}` : JSON.stringify(e);
6277
6693
  setEphemeralHints(hints) {
6278
6694
  this._pendingHints = hints;
6279
6695
  }
6696
+ /**
6697
+ * Forward a presentation to the navigator (a new card restarts its intake
6698
+ * clock). Builds the navigator if the cached one has expired.
6699
+ */
6700
+ notePresented(card) {
6701
+ if (card.status !== "new") return;
6702
+ void this._getCurrentUser().then((u) => this._getCachedNavigator(u)).then(({ navigator: navigator2 }) => navigator2.notePresented?.(card)).catch((e) => logger.warn(`[courseDB] Could not note a presentation: ${e}`));
6703
+ }
6280
6704
  async getWeightedCards(limit) {
6281
6705
  const u = await this._getCurrentUser();
6282
6706
  try {
@@ -10647,10 +11071,11 @@ function backlogHtml(backlog) {
10647
11071
  const rows = backlog.map((b) => {
10648
11072
  const hot = b.backlogMultiplier >= 3;
10649
11073
  const multColor = b.backlogMultiplier <= 1 ? "#86efac" : hot ? "#fca5a5" : "#fcd34d";
10650
- const headroom = b.backlogMultiplier > 1 ? `climbing (\xD7${b.backlogGrowthRate.toFixed(2)} per ${b.healthyBacklog}-review excess, unbounded)` : "healthy \u2014 no pressure";
11074
+ const headroom = b.backlogMultiplier > 1 ? `climbing (\xD7${b.backlogGrowthRate.toFixed(2)} per ${b.healthyBacklog} of mass in excess, unbounded)` : "healthy \u2014 no pressure";
11075
+ const mass = b.reviewMass !== null ? ` \xB7 mass ${b.reviewMass.toFixed(1)}` : "";
10651
11076
  const top = b.topReviewScore !== null ? b.topReviewScore.toFixed(2) : "\u2014";
10652
11077
  const next = b.nextDueIn ? ` <span style="opacity:.6">\xB7 next due ${esc(b.nextDueIn)}</span>` : "";
10653
- return `<div style="margin-left:6px"><span style="opacity:.7">${esc(b.courseId.slice(0, 8))}</span> due ${b.dueNow}/${b.scheduledTotal} <span style="opacity:.6">(healthy ${b.healthyBacklog})</span>${next}<div style="margin-left:6px">pressure <span style="color:${multColor}">\xD7${b.backlogMultiplier.toFixed(2)}</span> <span style="opacity:.6">${headroom} \xB7 top review ${top}</span></div></div>`;
11078
+ return `<div style="margin-left:6px"><span style="opacity:.7">${esc(b.courseId.slice(0, 8))}</span> due ${b.dueNow}/${b.scheduledTotal}${mass} <span style="opacity:.6">(healthy mass ${b.healthyBacklog})</span>${next}<div style="margin-left:6px">pressure <span style="color:${multColor}">\xD7${b.backlogMultiplier.toFixed(2)}</span> <span style="opacity:.6">${headroom} \xB7 top review ${top}</span></div></div>`;
10654
11079
  }).join("");
10655
11080
  return `<div style="margin-bottom:6px"><div style="color:#93c5fd">review backpressure</div>${rows}</div>`;
10656
11081
  }
@@ -10789,8 +11214,9 @@ function snapshotToText(s) {
10789
11214
  const headroom = b.backlogMultiplier > 1 ? "climbing" : "healthy";
10790
11215
  const top = b.topReviewScore !== null ? b.topReviewScore.toFixed(2) : "\u2014";
10791
11216
  const next = b.nextDueIn ? `, next due ${b.nextDueIn}` : "";
11217
+ const mass = b.reviewMass !== null ? `, mass ${b.reviewMass.toFixed(1)}` : "";
10792
11218
  lines.push(
10793
- ` ${b.courseId.slice(0, 8)}: due ${b.dueNow}/${b.scheduledTotal} (healthy ${b.healthyBacklog})${next}; pressure \xD7${b.backlogMultiplier.toFixed(2)} ${headroom}; top review ${top}`
11219
+ ` ${b.courseId.slice(0, 8)}: due ${b.dueNow}/${b.scheduledTotal}${mass} (healthy mass ${b.healthyBacklog})${next}; pressure \xD7${b.backlogMultiplier.toFixed(2)} ${headroom}; top review ${top}`
10794
11220
  );
10795
11221
  }
10796
11222
  }
@@ -11148,7 +11574,49 @@ Example:
11148
11574
  });
11149
11575
 
11150
11576
  // src/study/SessionController.ts
11151
- var SessionController;
11577
+ function sig4(x) {
11578
+ return Number(x.toPrecision(4));
11579
+ }
11580
+ function toRunCard(c) {
11581
+ return {
11582
+ cardId: c.cardId,
11583
+ origin: c.origin,
11584
+ ...c.generator ? { generator: c.generator } : {},
11585
+ score: sig4(c.finalScore),
11586
+ selected: c.selected
11587
+ };
11588
+ }
11589
+ function toRunCardTrail(c) {
11590
+ return {
11591
+ ...toRunCard(c),
11592
+ trail: c.provenance.filter((p) => p.action !== "passed").map((p) => ({
11593
+ strategyName: p.strategyName,
11594
+ action: p.action,
11595
+ score: sig4(p.score),
11596
+ reason: p.reason
11597
+ }))
11598
+ };
11599
+ }
11600
+ function persistedReading(r) {
11601
+ return {
11602
+ ...r,
11603
+ urgency: sig4(r.urgency),
11604
+ multiplier: sig4(r.multiplier),
11605
+ inputs: Object.fromEntries(Object.entries(r.inputs).map(([k, v]) => [k, sig4(v)]))
11606
+ };
11607
+ }
11608
+ function persistedRunCards(run) {
11609
+ const selected = run.cards.filter((c) => c.selected);
11610
+ const runnersUp = run.cards.filter((c) => !c.selected).slice(0, PERSISTED_RUNNERS_UP);
11611
+ return [...selected, ...runnersUp].map(toRunCard);
11612
+ }
11613
+ function persistedUnselectedNew(u) {
11614
+ return {
11615
+ ...u.nextInLine ? { nextInLine: toRunCardTrail(u.nextInLine) } : {},
11616
+ ...u.topGenerated ? { topGenerated: toRunCardTrail(u.topGenerated) } : {}
11617
+ };
11618
+ }
11619
+ var PERSISTED_RUNNERS_UP, SessionController;
11152
11620
  var init_SessionController = __esm({
11153
11621
  "src/study/SessionController.ts"() {
11154
11622
  "use strict";
@@ -11170,6 +11638,7 @@ var init_SessionController = __esm({
11170
11638
  init_SessionDebugger();
11171
11639
  init_SessionOverlay();
11172
11640
  init_logger();
11641
+ PERSISTED_RUNNERS_UP = 5;
11173
11642
  SessionController = class _SessionController extends Loggable {
11174
11643
  _className = "SessionController";
11175
11644
  services;
@@ -11452,13 +11921,17 @@ var init_SessionController = __esm({
11452
11921
  newSelected: run.newSelected,
11453
11922
  // Compact detail projected off the full report so a persisted run is
11454
11923
  // self-explanatory once the in-memory ring buffer has rolled over.
11455
- // Per-card provenance (`run.cards`) is intentionally left out — it's
11456
- // the dominant memory cost and not worth persisting per run.
11924
+ // Per-card provenance is the dominant cost, so it's kept only for the
11925
+ // (at most two) `unselectedNew` cards, and only its score-changing
11926
+ // entries. Everything else is ids and scores.
11457
11927
  ...typeof run.userElo === "number" ? { userElo: run.userElo } : {},
11458
11928
  ...run.generators ? { generators: run.generators } : {},
11459
11929
  ...run.filters ? { filters: run.filters } : {},
11460
11930
  ...run.hints ? { hints: run.hints } : {},
11461
- ...run.discardedTail ? { discardedTail: run.discardedTail } : {}
11931
+ ...run.discardedTail ? { discardedTail: run.discardedTail } : {},
11932
+ cards: persistedRunCards(run),
11933
+ ...run.unselectedNew ? { unselectedNew: persistedUnselectedNew(run.unselectedNew) } : {},
11934
+ ...run.regulators ? { regulators: run.regulators.map(persistedReading) } : {}
11462
11935
  });
11463
11936
  }
11464
11937
  }
@@ -12219,6 +12692,13 @@ var init_SessionController = __esm({
12219
12692
  queueSource,
12220
12693
  nextItem.score
12221
12694
  );
12695
+ for (const source of this.sources) {
12696
+ source.notePresented?.({
12697
+ cardId: nextItem.cardID,
12698
+ courseId: nextItem.courseID,
12699
+ status: nextItem.status
12700
+ });
12701
+ }
12222
12702
  snapshotQueues(this.supplyQ.length, this.failedQ.length);
12223
12703
  return card;
12224
12704
  }
@@ -14087,7 +14567,6 @@ var init_PouchDataLayerProvider = __esm({
14087
14567
  "use strict";
14088
14568
  init_logger();
14089
14569
  init_dataDirectory();
14090
- init_auth();
14091
14570
  init_adminDB2();
14092
14571
  init_classroomDB2();
14093
14572
  init_courseDB();
@@ -14161,16 +14640,6 @@ var init_PouchDataLayerProvider = __esm({
14161
14640
  getAdminDB() {
14162
14641
  return new AdminDB();
14163
14642
  }
14164
- async createUserReaderForUser(targetUsername) {
14165
- const requestingUsername = await getLoggedInUsername();
14166
- if (requestingUsername !== "admin") {
14167
- throw new Error("Unauthorized: Only admin users can access other users' data");
14168
- }
14169
- logger.info(`Admin user '${requestingUsername}' requesting UserDBReader for '${targetUsername}'`);
14170
- const syncStrategy = new CouchDBSyncStrategy();
14171
- const targetUserDB = await BaseUser.instance(syncStrategy, targetUsername);
14172
- return targetUserDB;
14173
- }
14174
14643
  isReadOnly() {
14175
14644
  return false;
14176
14645
  }
@@ -14937,6 +15406,11 @@ var init_courseDB2 = __esm({
14937
15406
  setEphemeralHints(hints) {
14938
15407
  this._pendingHints = hints;
14939
15408
  }
15409
+ /** Forward a presentation to the navigator (a new card restarts its intake clock). */
15410
+ notePresented(card) {
15411
+ if (card.status !== "new") return;
15412
+ void this.createNavigator(this.userDB).then((navigator2) => navigator2.notePresented?.(card)).catch((e) => logger.warn(`[static/courseDB] Could not note a presentation: ${e}`));
15413
+ }
14940
15414
  async getWeightedCards(limit) {
14941
15415
  try {
14942
15416
  const navigator2 = await this.createNavigator(this.userDB);
@@ -15183,12 +15657,6 @@ var init_StaticDataLayerProvider = __esm({
15183
15657
  getAdminDB() {
15184
15658
  throw new Error("Admin functions not supported in static mode");
15185
15659
  }
15186
- async createUserReaderForUser(targetUsername) {
15187
- logger.warn(`StaticDataLayerProvider: Multi-user access not supported in static mode`);
15188
- logger.warn(`Request: trying to access data for ${targetUsername}`);
15189
- logger.warn(`Returning current user's data instead`);
15190
- return this.getUserDB();
15191
- }
15192
15660
  isReadOnly() {
15193
15661
  return true;
15194
15662
  }
@@ -15856,6 +16324,8 @@ var init_core = __esm({
15856
16324
 
15857
16325
  // src/index.ts
15858
16326
  init_core();
16327
+ init_pipelinePlan();
16328
+ init_regulators();
15859
16329
  init_courseLookupDB();
15860
16330
 
15861
16331
  // src/courseConfigRegistration.ts
@@ -16172,6 +16642,7 @@ export {
16172
16642
  ContentNavigator,
16173
16643
  CouchDBToStaticPacker,
16174
16644
  CourseLookup,
16645
+ DEFAULT_REGULATOR_CONFIG,
16175
16646
  DIVERSITY_FLOOR,
16176
16647
  DIVERSITY_STRENGTH,
16177
16648
  DocType,
@@ -16180,11 +16651,13 @@ export {
16180
16651
  FileSystemError,
16181
16652
  GuestUsername,
16182
16653
  HYDRATION_MARKER_ID,
16654
+ INTAKE_CLOCK_KEY,
16183
16655
  Loggable,
16184
16656
  NOT_SET,
16185
16657
  NavigatorRole,
16186
16658
  NavigatorRoles,
16187
16659
  Navigators,
16660
+ PIPELINE_STAGES,
16188
16661
  QuotaRoundRobinMixer,
16189
16662
  REVIEW_TIME_FORMAT2 as REVIEW_TIME_FORMAT,
16190
16663
  SessionController,
@@ -16192,6 +16665,7 @@ export {
16192
16665
  TagFilteredContentSource,
16193
16666
  _resetDataLayer,
16194
16667
  aggregateOutcomesForGradient,
16668
+ applyReading,
16195
16669
  areQuestionRecords,
16196
16670
  buildStrategyStateId,
16197
16671
  captureMixerRun,
@@ -16210,6 +16684,7 @@ export {
16210
16684
  drainCapturedRuns,
16211
16685
  endSessionTracking,
16212
16686
  ensureAppDataDirectory,
16687
+ frozenMsAt,
16213
16688
  getActiveController,
16214
16689
  getActivePipeline,
16215
16690
  getAppDataDirectory,
@@ -16219,6 +16694,7 @@ export {
16219
16694
  getDbPath,
16220
16695
  getDefaultLearnableWeight,
16221
16696
  getLapses,
16697
+ getRegisteredFilterKind,
16222
16698
  getRegisteredNavigator,
16223
16699
  getRegisteredNavigatorNames,
16224
16700
  getRegisteredNavigatorRole,
@@ -16232,6 +16708,8 @@ export {
16232
16708
  initializeDataDirectory,
16233
16709
  initializeDataLayer,
16234
16710
  initializeNavigatorRegistry,
16711
+ intakeHours,
16712
+ intakeReading,
16235
16713
  isDataShapeRegistered,
16236
16714
  isDataShapeSchemaAvailable,
16237
16715
  isFilter,
@@ -16251,6 +16729,7 @@ export {
16251
16729
  newSessionId,
16252
16730
  parseCardHistoryID,
16253
16731
  pipelineDebugAPI,
16732
+ planPipeline,
16254
16733
  processCustomQuestionsData,
16255
16734
  recordCardPresentation,
16256
16735
  recordUserOutcome,
@@ -16264,12 +16743,16 @@ export {
16264
16743
  removeCustomQuestionTypes,
16265
16744
  removeDataShape,
16266
16745
  removeQuestionType,
16746
+ resetIntakeClock,
16747
+ reviewMassReading,
16748
+ reviewWeight,
16267
16749
  runPeriodUpdate,
16268
16750
  scoreAccuracyInZone,
16269
16751
  sessionDebugAPI,
16270
16752
  setDebugSessionId,
16271
16753
  snapshotQueues,
16272
16754
  startSessionTracking,
16755
+ stepIntakeClock,
16273
16756
  toggleSessionOverlay,
16274
16757
  updateLearningState,
16275
16758
  updateStrategyWeight,