@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.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) {
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)
@@ -887,6 +887,23 @@ function buildRunReport(courseId, courseName, generatorName, generators, generat
887
887
  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.`
888
888
  };
889
889
  }
890
+ const isUnselectedNew = (c) => !c.reviewID && !selectedIds.has(c.cardId);
891
+ const generatorScore = (c) => c.provenance[0]?.score ?? 0;
892
+ const keptIds = new Set(allCards.map((c) => c.cardId));
893
+ const hintExcluded = (c) => c.score > 0 && !keptIds.has(c.cardId);
894
+ let nextInLine;
895
+ for (const c of allCards) {
896
+ if (isUnselectedNew(c) && (!nextInLine || c.score > nextInLine.score)) nextInLine = c;
897
+ }
898
+ let topGenerated;
899
+ for (const c of scoredCards ?? allCards) {
900
+ if (!isUnselectedNew(c) || hintExcluded(c)) continue;
901
+ if (!topGenerated || generatorScore(c) > generatorScore(topGenerated)) topGenerated = c;
902
+ }
903
+ const unselectedNew = nextInLine || topGenerated ? {
904
+ ...nextInLine ? { nextInLine: toReport(nextInLine) } : {},
905
+ ...topGenerated && topGenerated.cardId !== nextInLine?.cardId ? { topGenerated: toReport(topGenerated) } : {}
906
+ } : void 0;
890
907
  const reviewsSelected = selectedCards.filter((c) => getOrigin(c) === "review").length;
891
908
  const newSelected = selectedCards.filter((c) => getOrigin(c) === "new").length;
892
909
  return {
@@ -902,7 +919,9 @@ function buildRunReport(courseId, courseName, generatorName, generators, generat
902
919
  reviewsSelected,
903
920
  newSelected,
904
921
  cards,
905
- discardedTail
922
+ unselectedNew,
923
+ discardedTail,
924
+ ...regulators ? { regulators } : {}
906
925
  };
907
926
  }
908
927
  function formatProvenance(provenance) {
@@ -1626,11 +1645,23 @@ var SrsDebugger_exports = {};
1626
1645
  __export(SrsDebugger_exports, {
1627
1646
  captureSrsBacklog: () => captureSrsBacklog,
1628
1647
  clearSrsBacklogDebug: () => clearSrsBacklogDebug,
1629
- getSrsBacklogDebug: () => getSrsBacklogDebug
1648
+ getSrsBacklogDebug: () => getSrsBacklogDebug,
1649
+ noteReviewPressure: () => noteReviewPressure
1630
1650
  });
1631
1651
  function captureSrsBacklog(snapshot) {
1632
1652
  snapshots.set(snapshot.courseId, snapshot);
1633
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
+ }
1634
1665
  function getSrsBacklogDebug() {
1635
1666
  return [...snapshots.values()].sort((a, b) => b.timestamp - a.timestamp);
1636
1667
  }
@@ -1908,14 +1939,13 @@ var elo_exports = {};
1908
1939
  __export(elo_exports, {
1909
1940
  default: () => ELONavigator
1910
1941
  });
1911
- var import_common5, ELO_RELEVANCE_SIGMA, ELONavigator;
1942
+ var import_common5, ELONavigator;
1912
1943
  var init_elo = __esm({
1913
1944
  "src/core/navigators/generators/elo.ts"() {
1914
1945
  "use strict";
1915
1946
  init_navigators();
1916
1947
  import_common5 = require("@vue-skuilder/common");
1917
1948
  init_logger();
1918
- ELO_RELEVANCE_SIGMA = 300;
1919
1949
  ELONavigator = class extends ContentNavigator {
1920
1950
  /** Human-readable name for CardGenerator interface */
1921
1951
  name;
@@ -1924,10 +1954,8 @@ var init_elo = __esm({
1924
1954
  this.name = strategyData?.name || "ELO";
1925
1955
  }
1926
1956
  /**
1927
- * Get new cards with suitability scores based on ELO distance.
1928
- *
1929
- * Cards closer to user's ELO get higher scores.
1930
- * 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.
1931
1959
  *
1932
1960
  * NOTE: This generator only handles NEW cards. Reviews are handled by
1933
1961
  * SRSNavigator. Use CompositeGenerator to combine both.
@@ -1955,20 +1983,20 @@ var init_elo = __esm({
1955
1983
  const scored = newCards.map((c) => {
1956
1984
  const cardElo = c.elo ?? 1e3;
1957
1985
  const distance = Math.abs(cardElo - userGlobalElo);
1958
- const relevance = Math.exp(-((distance / ELO_RELEVANCE_SIGMA) ** 2));
1959
- const samplingKey = relevance * (0.5 + 0.5 * Math.random());
1986
+ const jitter = 0.5 + 0.5 * Math.random();
1960
1987
  return {
1961
1988
  cardId: c.cardID,
1962
1989
  courseId: c.courseID,
1963
- score: samplingKey,
1990
+ score: jitter,
1991
+ cardElo,
1964
1992
  provenance: [
1965
1993
  {
1966
1994
  strategy: "elo",
1967
1995
  strategyName: this.strategyName || this.name,
1968
1996
  strategyId: this.strategyId || "NAVIGATION_STRATEGY-ELO-default",
1969
1997
  action: "generated",
1970
- score: samplingKey,
1971
- 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)}`
1972
2000
  }
1973
2001
  ]
1974
2002
  };
@@ -2844,43 +2872,132 @@ var init_prescribed = __esm({
2844
2872
  }
2845
2873
  });
2846
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
+
2847
2981
  // src/core/navigators/generators/srs.ts
2848
2982
  var srs_exports = {};
2849
2983
  __export(srs_exports, {
2850
2984
  default: () => SRSNavigator
2851
2985
  });
2852
- var import_moment, DEFAULT_HEALTHY_BACKLOG, BACKLOG_GROWTH_RATE, SRSNavigator;
2986
+ var import_moment, SRSNavigator;
2853
2987
  var init_srs = __esm({
2854
2988
  "src/core/navigators/generators/srs.ts"() {
2855
2989
  "use strict";
2856
2990
  import_moment = __toESM(require("moment"), 1);
2857
2991
  init_navigators();
2858
2992
  init_SrsDebugger();
2993
+ init_regulators();
2859
2994
  init_logger();
2860
- DEFAULT_HEALTHY_BACKLOG = 20;
2861
- BACKLOG_GROWTH_RATE = 2;
2862
2995
  SRSNavigator = class extends ContentNavigator {
2863
2996
  /** Human-readable name for CardGenerator interface */
2864
2997
  name;
2865
- /** Healthy backlog threshold - when exceeded, backlog pressure kicks in */
2866
- healthyBacklog;
2867
2998
  constructor(user, course, strategyData) {
2868
2999
  super(user, course, strategyData);
2869
3000
  this.name = strategyData?.name || "SRS";
2870
- const config = this.parseConfig(strategyData?.serializedData);
2871
- this.healthyBacklog = config.healthyBacklog ?? DEFAULT_HEALTHY_BACKLOG;
2872
- }
2873
- /**
2874
- * Parse configuration from serialized JSON.
2875
- */
2876
- parseConfig(serializedData) {
2877
- if (!serializedData) return {};
2878
- try {
2879
- return JSON.parse(serializedData);
2880
- } catch {
2881
- logger.warn("[SRS] Failed to parse strategy config, using defaults");
2882
- return {};
2883
- }
2884
3001
  }
2885
3002
  /**
2886
3003
  * Get review cards scored by urgency.
@@ -2888,7 +3005,6 @@ var init_srs = __esm({
2888
3005
  * Score formula combines:
2889
3006
  * - Relative overdueness: hoursOverdue / intervalHours
2890
3007
  * - Interval recency: exponential decay favoring shorter intervals
2891
- * - Backlog pressure: boost when due reviews exceed healthy threshold
2892
3008
  *
2893
3009
  * Cards not yet due are excluded (not scored as 0).
2894
3010
  *
@@ -2925,7 +3041,6 @@ var init_srs = __esm({
2925
3041
  }
2926
3042
  }
2927
3043
  }
2928
- const backlogMultiplier = this.computeBacklogMultiplier(dueReviews.length);
2929
3044
  const notDue = reviews.filter((r) => !now.isAfter(import_moment.default.utc(r.reviewTime)));
2930
3045
  let nextDueIn = null;
2931
3046
  if (notDue.length > 0) {
@@ -2936,9 +3051,8 @@ var init_srs = __esm({
2936
3051
  nextDueIn = until.asHours() < 1 ? `${Math.round(until.asMinutes())}m` : until.asHours() < 24 ? `${Math.round(until.asHours())}h` : `${Math.round(until.asDays())}d`;
2937
3052
  }
2938
3053
  if (dueReviews.length > 0) {
2939
- const pressureNote = backlogMultiplier > 1 ? ` [backlog pressure: \xD7${backlogMultiplier.toFixed(2)}]` : ` [healthy backlog]`;
2940
3054
  logger.info(
2941
- `[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)`
2942
3056
  );
2943
3057
  } else if (reviews.length > 0) {
2944
3058
  const sortedByDue = [...reviews].sort(
@@ -2955,11 +3069,12 @@ var init_srs = __esm({
2955
3069
  logger.info(`[SRS] Course ${courseId}: No reviews scheduled`);
2956
3070
  }
2957
3071
  const scored = dueReviews.map((review) => {
2958
- const { score, reason } = this.computeUrgencyScore(review, now, backlogMultiplier);
3072
+ const { score, urgency, reason } = this.computeUrgencyScore(review, now);
2959
3073
  return {
2960
3074
  cardId: review.cardId,
2961
3075
  courseId: review.courseId,
2962
3076
  score,
3077
+ reviewUrgency: urgency,
2963
3078
  reviewID: review._id,
2964
3079
  provenance: [
2965
3080
  {
@@ -2978,47 +3093,20 @@ var init_srs = __esm({
2978
3093
  courseId,
2979
3094
  scheduledTotal: reviews.length,
2980
3095
  dueNow: dueReviews.length,
2981
- healthyBacklog: this.healthyBacklog,
2982
- backlogMultiplier,
2983
- backlogGrowthRate: BACKLOG_GROWTH_RATE,
3096
+ healthyBacklog: DEFAULT_REGULATOR_CONFIG.reviewMass.healthyMass,
3097
+ reviewMass: null,
3098
+ backlogMultiplier: 1,
3099
+ backlogGrowthRate: DEFAULT_REGULATOR_CONFIG.reviewMass.rate,
2984
3100
  topReviewScore: sorted.length > 0 ? sorted[0].score : null,
2985
3101
  nextDueIn,
2986
3102
  timestamp: Date.now()
2987
3103
  });
2988
3104
  return { cards: sorted.slice(0, limit) };
2989
3105
  }
2990
- /**
2991
- * Compute the multiplicative backlog pressure based on number of due reviews.
2992
- *
2993
- * ×1.0 at or below the healthy threshold (no boost); above it, grows as
2994
- * BACKLOG_GROWTH_RATE raised to the excess expressed in multiples of the
2995
- * healthy threshold. Uncapped — self-regulating instead: reviews winning
2996
- * slots depletes dueCount, which drops the ratio and relaxes the multiplier
2997
- * next run.
2998
- *
2999
- * Examples (with default healthyBacklog=20, BACKLOG_GROWTH_RATE=1.5):
3000
- * - 10 due reviews → ×1.00 (healthy)
3001
- * - 20 due reviews → ×1.00 (at threshold, ratio 0)
3002
- * - 40 due reviews → ×1.50 (ratio 1, 2x threshold)
3003
- * - 60 due reviews → ×2.25 (ratio 2, 3x threshold — old hard cap was ×2.00 here)
3004
- * - 100 due reviews → ×5.06 (ratio 4, 5x threshold)
3005
- * - 160 due reviews → ×17.09 (ratio 7, 8x threshold)
3006
- *
3007
- * @param dueCount - Number of reviews currently due
3008
- * @returns Multiplier applied to review urgency (>= 1.0, unbounded)
3009
- */
3010
- computeBacklogMultiplier(dueCount) {
3011
- if (dueCount <= this.healthyBacklog) {
3012
- return 1;
3013
- }
3014
- const excess = dueCount - this.healthyBacklog;
3015
- const ratio = excess / this.healthyBacklog;
3016
- return Math.pow(BACKLOG_GROWTH_RATE, ratio);
3017
- }
3018
3106
  /**
3019
3107
  * Compute urgency score for a review card.
3020
3108
  *
3021
- * Three factors:
3109
+ * Two factors:
3022
3110
  * 1. Relative overdueness = hoursOverdue / intervalHours
3023
3111
  * - 2 days overdue on 3-day interval = 0.67 (urgent)
3024
3112
  * - 2 days overdue on 180-day interval = 0.01 (not urgent)
@@ -3028,20 +3116,14 @@ var init_srs = __esm({
3028
3116
  * - 30 days (720h) → ~0.56
3029
3117
  * - 180 days → ~0.30
3030
3118
  *
3031
- * 3. Backlog pressure = global *multiplier* when review backlog exceeds the
3032
- * healthy threshold (×1.0 healthy → exponential growth, uncapped, above it).
3033
- *
3034
- * Combined: (base 0.5 + urgency factors * 0.45) × backlog multiplier.
3035
- * Per-card range before pressure: ~0.57–0.95. NOT clamped to 1.0 — under a
3036
- * heavy backlog reviews scale onto the open scale to compete with (and exceed)
3037
- * new cards; there's no ceiling at all now, so a bad enough backlog always
3038
- * 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).
3039
3122
  *
3040
3123
  * @param review - The scheduled card to score
3041
3124
  * @param now - Current time
3042
- * @param backlogMultiplier - Pre-computed backlog multiplier (>= 1.0, unbounded)
3043
3125
  */
3044
- computeUrgencyScore(review, now, backlogMultiplier) {
3126
+ computeUrgencyScore(review, now) {
3045
3127
  const scheduledAt = import_moment.default.utc(review.scheduledAt);
3046
3128
  const due = import_moment.default.utc(review.reviewTime);
3047
3129
  const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
@@ -3050,20 +3132,16 @@ var init_srs = __esm({
3050
3132
  const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
3051
3133
  const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
3052
3134
  const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
3053
- const baseScore = 0.5 + urgency * 0.45;
3054
- const score = baseScore * backlogMultiplier;
3135
+ const score = 0.5 + urgency * 0.45;
3055
3136
  const reasonParts = [
3056
3137
  `${Math.round(hoursOverdue)}h overdue`,
3057
3138
  `interval: ${Math.round(intervalHours)}h`,
3058
3139
  `relative: ${relativeOverdue.toFixed(2)}`,
3059
3140
  `recency: ${recencyFactor.toFixed(2)}`
3060
3141
  ];
3061
- if (backlogMultiplier > 1) {
3062
- reasonParts.push(`backlog: \xD7${backlogMultiplier.toFixed(2)}`);
3063
- }
3064
3142
  reasonParts.push("review");
3065
3143
  const reason = reasonParts.join(", ");
3066
- return { score, reason };
3144
+ return { score, urgency, reason };
3067
3145
  }
3068
3146
  };
3069
3147
  }
@@ -3118,6 +3196,8 @@ var init_WeightedFilter = __esm({
3118
3196
  init_contentNavigationStrategy();
3119
3197
  WeightedFilter = class {
3120
3198
  name;
3199
+ kind;
3200
+ liveOnly;
3121
3201
  inner;
3122
3202
  learnable;
3123
3203
  staticWeight;
@@ -3125,6 +3205,8 @@ var init_WeightedFilter = __esm({
3125
3205
  constructor(inner, learnable = DEFAULT_LEARNABLE_WEIGHT, staticWeight = false, strategyId) {
3126
3206
  this.inner = inner;
3127
3207
  this.name = inner.name;
3208
+ this.kind = inner.kind;
3209
+ this.liveOnly = inner.liveOnly;
3128
3210
  this.learnable = learnable;
3129
3211
  this.staticWeight = staticWeight;
3130
3212
  this.strategyId = strategyId;
@@ -3189,58 +3271,141 @@ var init_WeightedFilter = __esm({
3189
3271
  // src/core/navigators/filters/eloDistance.ts
3190
3272
  var eloDistance_exports = {};
3191
3273
  __export(eloDistance_exports, {
3192
- DEFAULT_HALF_LIFE: () => DEFAULT_HALF_LIFE,
3193
- DEFAULT_MAX_MULTIPLIER: () => DEFAULT_MAX_MULTIPLIER,
3194
- DEFAULT_MIN_MULTIPLIER: () => DEFAULT_MIN_MULTIPLIER,
3195
- createEloDistanceFilter: () => createEloDistanceFilter
3274
+ DEFAULT_ELO_DISTANCE_CONFIG: () => DEFAULT_ELO_DISTANCE_CONFIG,
3275
+ createEloDistanceFilter: () => createEloDistanceFilter,
3276
+ default: () => EloDistanceFilter,
3277
+ tagAwareGap: () => tagAwareGap
3196
3278
  });
3197
3279
  function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
3198
3280
  const normalizedDistance = distance / halfLife;
3199
3281
  const decay = Math.exp(-(normalizedDistance * normalizedDistance));
3200
3282
  return minMultiplier + (maxMultiplier - minMultiplier) * decay;
3201
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
+ }
3202
3354
  function createEloDistanceFilter(config) {
3203
- const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
3204
- const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
3205
- const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
3355
+ const resolved = resolveConfig(config);
3356
+ const source = { name: "ELO Distance Filter", strategyId: "ELO_DISTANCE_FILTER" };
3206
3357
  return {
3207
- name: "ELO Distance Filter",
3208
- async transform(cards, context) {
3209
- const { course, userElo } = context;
3210
- const cardIds = cards.map((c) => c.cardId);
3211
- const cardElos = await course.getCardEloData(cardIds);
3212
- return cards.map((card, i) => {
3213
- const cardElo = cardElos[i]?.global?.score ?? 1e3;
3214
- const distance = Math.abs(cardElo - userElo);
3215
- const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
3216
- const newScore = card.score * multiplier;
3217
- const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
3218
- return {
3219
- ...card,
3220
- score: newScore,
3221
- provenance: [
3222
- ...card.provenance,
3223
- {
3224
- strategy: "eloDistance",
3225
- strategyName: "ELO Distance Filter",
3226
- strategyId: "ELO_DISTANCE_FILTER",
3227
- action,
3228
- score: newScore,
3229
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
3230
- }
3231
- ]
3232
- };
3233
- });
3234
- }
3358
+ name: source.name,
3359
+ kind: "signal",
3360
+ liveOnly: true,
3361
+ transform: (cards, context) => applyEloDistance(cards, context, resolved, source)
3235
3362
  };
3236
3363
  }
3237
- 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;
3238
3365
  var init_eloDistance = __esm({
3239
3366
  "src/core/navigators/filters/eloDistance.ts"() {
3240
3367
  "use strict";
3241
- DEFAULT_HALF_LIFE = 200;
3242
- DEFAULT_MIN_MULTIPLIER = 0.3;
3243
- 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
+ };
3244
3409
  }
3245
3410
  });
3246
3411
 
@@ -3257,10 +3422,13 @@ var init_hierarchyDefinition = __esm({
3257
3422
  import_common6 = require("@vue-skuilder/common");
3258
3423
  init_logger();
3259
3424
  DEFAULT_MIN_COUNT2 = 3;
3260
- HierarchyDefinitionNavigator = class extends ContentNavigator {
3425
+ HierarchyDefinitionNavigator = class _HierarchyDefinitionNavigator extends ContentNavigator {
3261
3426
  config;
3262
3427
  /** Human-readable name for CardFilter interface */
3263
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;
3264
3432
  constructor(user, course, strategyData) {
3265
3433
  super(user, course, strategyData);
3266
3434
  this.config = this.parseConfig(strategyData.serializedData);
@@ -3527,10 +3695,13 @@ var init_userTagPreference = __esm({
3527
3695
  "src/core/navigators/filters/userTagPreference.ts"() {
3528
3696
  "use strict";
3529
3697
  init_navigators();
3530
- UserTagPreferenceFilter = class extends ContentNavigator {
3698
+ UserTagPreferenceFilter = class _UserTagPreferenceFilter extends ContentNavigator {
3531
3699
  _strategyData;
3532
3700
  /** Human-readable name for CardFilter interface */
3533
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;
3534
3705
  constructor(user, course, strategyData) {
3535
3706
  super(user, course, strategyData);
3536
3707
  this._strategyData = strategyData;
@@ -3640,6 +3811,7 @@ var init_userTagPreference = __esm({
3640
3811
  // src/core/navigators/filters/index.ts
3641
3812
  var filters_exports = {};
3642
3813
  __export(filters_exports, {
3814
+ EloDistanceFilter: () => EloDistanceFilter,
3643
3815
  UserTagPreferenceFilter: () => UserTagPreferenceFilter,
3644
3816
  createEloDistanceFilter: () => createEloDistanceFilter
3645
3817
  });
@@ -3678,10 +3850,13 @@ var init_interferenceMitigator = __esm({
3678
3850
  DEFAULT_MIN_COUNT3 = 10;
3679
3851
  DEFAULT_MIN_ELAPSED_DAYS = 3;
3680
3852
  DEFAULT_INTERFERENCE_DECAY = 0.8;
3681
- InterferenceMitigatorNavigator = class extends ContentNavigator {
3853
+ InterferenceMitigatorNavigator = class _InterferenceMitigatorNavigator extends ContentNavigator {
3682
3854
  config;
3683
3855
  /** Human-readable name for CardFilter interface */
3684
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;
3685
3860
  /** Precomputed map: tag -> set of { partner, decay } it interferes with */
3686
3861
  interferenceMap;
3687
3862
  constructor(user, course, strategyData) {
@@ -3897,10 +4072,13 @@ var init_relativePriority = __esm({
3897
4072
  DEFAULT_PRIORITY = 0.5;
3898
4073
  DEFAULT_PRIORITY_INFLUENCE = 0.5;
3899
4074
  DEFAULT_COMBINE_MODE = "max";
3900
- RelativePriorityNavigator = class extends ContentNavigator {
4075
+ RelativePriorityNavigator = class _RelativePriorityNavigator extends ContentNavigator {
3901
4076
  config;
3902
4077
  /** Human-readable name for CardFilter interface */
3903
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;
3904
4082
  constructor(user, course, strategyData) {
3905
4083
  super(user, course, strategyData);
3906
4084
  this.config = this.parseConfig(strategyData.serializedData);
@@ -4554,6 +4732,8 @@ var init_Pipeline = __esm({
4554
4732
  init_orchestration();
4555
4733
  init_PipelineDebugger();
4556
4734
  init_diversityRerank();
4735
+ init_regulators();
4736
+ init_SrsDebugger();
4557
4737
  VERBOSE_RESULTS = true;
4558
4738
  Pipeline = class extends ContentNavigator {
4559
4739
  generator;
@@ -4579,6 +4759,13 @@ var init_Pipeline = __esm({
4579
4759
  * getWeightedCards() call, then cleared.
4580
4760
  */
4581
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();
4582
4769
  /**
4583
4770
  * Create a new pipeline.
4584
4771
  *
@@ -4653,13 +4840,12 @@ var init_Pipeline = __esm({
4653
4840
  }
4654
4841
  }
4655
4842
  generatorSummaries = Array.from(genMap.entries()).map(([name, data]) => {
4656
- const newCards = data.cards.filter((c) => c.provenance[0]?.reason?.includes("new card"));
4657
- const reviewCards = data.cards.filter((c) => c.provenance[0]?.reason?.includes("review"));
4843
+ const reviewCount = data.cards.filter((c) => c.reviewID).length;
4658
4844
  return {
4659
4845
  name,
4660
4846
  cardCount: data.cards.length,
4661
- newCount: newCards.length,
4662
- reviewCount: reviewCards.length,
4847
+ newCount: data.cards.length - reviewCount,
4848
+ reviewCount,
4663
4849
  topScore: Math.max(...data.cards.map((c) => c.score), 0)
4664
4850
  };
4665
4851
  });
@@ -4695,19 +4881,24 @@ var init_Pipeline = __esm({
4695
4881
  cards.filter((c) => c.provenance.some((p) => p.strategy === "prescribed")).map((c) => c.cardId)
4696
4882
  );
4697
4883
  const filterImpacts = [];
4884
+ const generatedScores = new Map(cards.map((c) => [c.cardId, c.score]));
4885
+ const gated = /* @__PURE__ */ new Set();
4698
4886
  for (const filter of this.filters) {
4699
4887
  const beforeCount = cards.length;
4700
4888
  const beforeScores = new Map(cards.map((c) => [c.cardId, c.score]));
4701
4889
  cards = await filter.transform(cards, context);
4702
4890
  let boosted = 0, penalized = 0, passed = 0;
4703
4891
  const removed = beforeCount - cards.length;
4892
+ const kind = filter.kind ?? "gate";
4704
4893
  for (const card of cards) {
4705
4894
  const before = beforeScores.get(card.cardId) ?? 0;
4706
4895
  if (card.score > before) boosted++;
4707
- else if (card.score < before) penalized++;
4708
- else passed++;
4896
+ else if (card.score < before) {
4897
+ penalized++;
4898
+ if (kind === "gate") gated.add(card.cardId);
4899
+ } else passed++;
4709
4900
  }
4710
- filterImpacts.push({ name: filter.name, boosted, penalized, passed, removed });
4901
+ filterImpacts.push({ name: filter.name, kind, boosted, penalized, passed, removed });
4711
4902
  if (prescribedIds.size > 0) {
4712
4903
  const survivingIds = new Set(cards.map((c) => c.cardId));
4713
4904
  const killedPrescribed = [...prescribedIds].filter((id) => !survivingIds.has(id));
@@ -4721,7 +4912,9 @@ var init_Pipeline = __esm({
4721
4912
  }
4722
4913
  logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeScores.size} \u2192 ${cards.length} cards (\u2191${boosted} \u2193${penalized} =${passed})`);
4723
4914
  }
4915
+ const scoredCards = cards;
4724
4916
  cards = cards.filter((c) => c.score > 0);
4917
+ const regulators = await this.regulate(cards, generatedScores, gated);
4725
4918
  const hints = this._ephemeralHints;
4726
4919
  if (hints) {
4727
4920
  this._ephemeralHints = null;
@@ -4757,7 +4950,9 @@ var init_Pipeline = __esm({
4757
4950
  cards,
4758
4951
  result,
4759
4952
  context.userElo,
4760
- hints ?? void 0
4953
+ hints ?? void 0,
4954
+ scoredCards,
4955
+ regulators
4761
4956
  );
4762
4957
  captureRun(report);
4763
4958
  } catch (e) {
@@ -4936,6 +5131,77 @@ var init_Pipeline = __esm({
4936
5131
  logger.info(`[Pipeline] Hints applied: ${beforeCount} \u2192 ${cards.length} cards`);
4937
5132
  return cards;
4938
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
+ }
4939
5205
  /**
4940
5206
  * Build shared context for generator and filters.
4941
5207
  *
@@ -4946,10 +5212,11 @@ var init_Pipeline = __esm({
4946
5212
  */
4947
5213
  async buildContext() {
4948
5214
  let userElo = 1e3;
5215
+ let userCourseElo;
4949
5216
  try {
4950
5217
  const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
4951
- const courseElo = (0, import_common8.toCourseElo)(courseReg.elo);
4952
- userElo = courseElo.global.score;
5218
+ userCourseElo = (0, import_common8.toCourseElo)(courseReg.elo);
5219
+ userElo = userCourseElo.global.score;
4953
5220
  } catch (e) {
4954
5221
  logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
4955
5222
  }
@@ -4961,6 +5228,7 @@ var init_Pipeline = __esm({
4961
5228
  user: this.user,
4962
5229
  course: this.course,
4963
5230
  userElo,
5231
+ ...userCourseElo ? { userCourseElo } : {},
4964
5232
  orchestration
4965
5233
  };
4966
5234
  }
@@ -5074,7 +5342,7 @@ var init_Pipeline = __esm({
5074
5342
  cards = await this.hydrateTags(cards);
5075
5343
  const fullPool = cards.slice();
5076
5344
  const context = await this.buildContext();
5077
- for (const filter of this.filters) {
5345
+ for (const filter of this.forecastFilters()) {
5078
5346
  cards = await filter.transform(cards, context);
5079
5347
  }
5080
5348
  if (opts?.hints) {
@@ -5093,6 +5361,14 @@ var init_Pipeline = __esm({
5093
5361
  cards.sort((a, b) => b.score - a.score);
5094
5362
  return opts?.limit ? cards.slice(0, opts.limit) : cards;
5095
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
+ }
5096
5372
  /**
5097
5373
  * Scan every card in the course through the filter chain and report
5098
5374
  * how many are "well indicated" (score >= threshold) for the current user.
@@ -5114,7 +5390,7 @@ var init_Pipeline = __esm({
5114
5390
  cards = await this.hydrateTags(cards);
5115
5391
  const context = await this.buildContext();
5116
5392
  const filterBreakdown = [];
5117
- for (const filter of this.filters) {
5393
+ for (const filter of this.forecastFilters()) {
5118
5394
  cards = await filter.transform(cards, context);
5119
5395
  const wi = cards.filter((c) => c.score >= THRESHOLD).length;
5120
5396
  filterBreakdown.push({ name: filter.name, wellIndicated: wi });
@@ -5178,6 +5454,7 @@ var init_Pipeline = __esm({
5178
5454
  // src/core/navigators/defaults.ts
5179
5455
  var defaults_exports = {};
5180
5456
  __export(defaults_exports, {
5457
+ createDefaultEloDistanceStrategy: () => createDefaultEloDistanceStrategy,
5181
5458
  createDefaultEloStrategy: () => createDefaultEloStrategy,
5182
5459
  createDefaultPipeline: () => createDefaultPipeline,
5183
5460
  createDefaultSrsStrategy: () => createDefaultSrsStrategy
@@ -5204,12 +5481,28 @@ function createDefaultSrsStrategy(courseId) {
5204
5481
  serializedData: ""
5205
5482
  };
5206
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
+ }
5207
5496
  function createDefaultPipeline(user, course) {
5208
5497
  const courseId = course.getCourseID();
5209
5498
  const eloNavigator = new ELONavigator(user, course, createDefaultEloStrategy(courseId));
5210
5499
  const srsNavigator = new SRSNavigator(user, course, createDefaultSrsStrategy(courseId));
5211
5500
  const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);
5212
- const eloDistanceFilter = createEloDistanceFilter();
5501
+ const eloDistanceFilter = new EloDistanceFilter(
5502
+ user,
5503
+ course,
5504
+ createDefaultEloDistanceStrategy(courseId)
5505
+ );
5213
5506
  return new Pipeline(compositeGenerator, [eloDistanceFilter], user, course);
5214
5507
  }
5215
5508
  var init_defaults = __esm({
@@ -5225,6 +5518,131 @@ var init_defaults = __esm({
5225
5518
  }
5226
5519
  });
5227
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
+
5228
5646
  // src/core/navigators/PipelineAssembler.ts
5229
5647
  var PipelineAssembler_exports = {};
5230
5648
  __export(PipelineAssembler_exports, {
@@ -5239,16 +5657,16 @@ var init_PipelineAssembler = __esm({
5239
5657
  init_Pipeline();
5240
5658
  init_logger();
5241
5659
  init_CompositeGenerator();
5242
- init_defaults();
5660
+ init_pipelinePlan();
5243
5661
  PipelineAssembler = class {
5244
5662
  /**
5245
5663
  * Assembles a navigation pipeline from strategy documents.
5246
5664
  *
5247
- * 1. Separates into generators and filters by role
5248
- * 2. Validates at least one generator exists (or creates default ELO)
5249
- * 3. Instantiates generators - wraps multiple in CompositeGenerator
5250
- * 4. Instantiates filters
5251
- * 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)
5252
5670
  *
5253
5671
  * @param input - Strategy documents plus user/course interfaces
5254
5672
  * @returns Assembled pipeline and any warnings
@@ -5264,28 +5682,17 @@ var init_PipelineAssembler = __esm({
5264
5682
  warnings
5265
5683
  };
5266
5684
  }
5267
- const generatorStrategies = [];
5268
- const filterStrategies = [];
5269
- for (const s of strategies) {
5270
- if (isGenerator(s.implementingClass)) {
5271
- generatorStrategies.push(s);
5272
- } else if (isFilter(s.implementingClass)) {
5273
- filterStrategies.push(s);
5274
- } else {
5275
- 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
+ );
5276
5692
  }
5277
5693
  }
5278
- const courseId = course.getCourseID();
5279
- const hasElo = generatorStrategies.some((s) => s.implementingClass === "elo" /* ELO */);
5280
- const hasSrs = generatorStrategies.some((s) => s.implementingClass === "srs" /* SRS */);
5281
- if (!hasElo) {
5282
- logger.debug("[PipelineAssembler] No ELO generator configured, adding default");
5283
- generatorStrategies.push(createDefaultEloStrategy(courseId));
5284
- }
5285
- if (!hasSrs) {
5286
- logger.debug("[PipelineAssembler] No SRS generator configured, adding default");
5287
- generatorStrategies.push(createDefaultSrsStrategy(courseId));
5288
- }
5694
+ const generatorStrategies = plan.generators.map((g) => g.strategy);
5695
+ const sortedFilterStrategies = plan.filters.map((f) => f.strategy);
5289
5696
  if (generatorStrategies.length === 0) {
5290
5697
  warnings.push("No generator strategy found");
5291
5698
  return {
@@ -5307,9 +5714,6 @@ var init_PipelineAssembler = __esm({
5307
5714
  generator = await CompositeGenerator.fromStrategies(user, course, generatorStrategies);
5308
5715
  }
5309
5716
  const filters = [];
5310
- const sortedFilterStrategies = [...filterStrategies].sort(
5311
- (a, b) => a.name.localeCompare(b.name)
5312
- );
5313
5717
  for (const filterStrategy of sortedFilterStrategies) {
5314
5718
  try {
5315
5719
  const nav = await ContentNavigator.create(user, course, filterStrategy);
@@ -5377,7 +5781,9 @@ var init_3 = __esm({
5377
5781
  "./generators/prescribed.ts": () => Promise.resolve().then(() => (init_prescribed(), prescribed_exports)),
5378
5782
  "./generators/srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
5379
5783
  "./generators/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports)),
5380
- "./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))
5381
5787
  });
5382
5788
  }
5383
5789
  });
@@ -5398,6 +5804,7 @@ __export(navigators_exports, {
5398
5804
  drainCapturedRuns: () => drainCapturedRuns,
5399
5805
  getActivePipeline: () => getActivePipeline,
5400
5806
  getCardOrigin: () => getCardOrigin,
5807
+ getRegisteredFilterKind: () => getRegisteredFilterKind,
5401
5808
  getRegisteredNavigator: () => getRegisteredNavigator,
5402
5809
  getRegisteredNavigatorNames: () => getRegisteredNavigatorNames,
5403
5810
  getRegisteredNavigatorRole: () => getRegisteredNavigatorRole,
@@ -5426,6 +5833,10 @@ function hasRegisteredNavigator(implementingClass) {
5426
5833
  function getRegisteredNavigatorRole(implementingClass) {
5427
5834
  return navigatorRegistry.get(implementingClass)?.role;
5428
5835
  }
5836
+ function getRegisteredFilterKind(implementingClass) {
5837
+ const ctor = navigatorRegistry.get(implementingClass)?.constructor;
5838
+ return ctor?.kind;
5839
+ }
5429
5840
  function getRegisteredNavigatorNames() {
5430
5841
  return Array.from(navigatorRegistry.keys());
5431
5842
  }
@@ -5443,17 +5854,20 @@ async function initializeNavigatorRegistry() {
5443
5854
  hierarchyModule,
5444
5855
  interferenceModule,
5445
5856
  relativePriorityModule,
5446
- userTagPreferenceModule
5857
+ userTagPreferenceModule,
5858
+ eloDistanceModule
5447
5859
  ] = await Promise.all([
5448
5860
  Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
5449
5861
  Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
5450
5862
  Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
5451
- Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports))
5863
+ Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports)),
5864
+ Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports))
5452
5865
  ]);
5453
5866
  registerNavigator("hierarchyDefinition", hierarchyModule.default);
5454
5867
  registerNavigator("interferenceMitigator", interferenceModule.default);
5455
5868
  registerNavigator("relativePriority", relativePriorityModule.default);
5456
5869
  registerNavigator("userTagPreference", userTagPreferenceModule.default);
5870
+ registerNavigator("eloDistance", eloDistanceModule.default);
5457
5871
  logger.debug(
5458
5872
  `[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(", ")}`
5459
5873
  );
@@ -5501,6 +5915,7 @@ var init_navigators = __esm({
5501
5915
  Navigators2["INTERFERENCE"] = "interferenceMitigator";
5502
5916
  Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
5503
5917
  Navigators2["USER_TAG_PREFERENCE"] = "userTagPreference";
5918
+ Navigators2["ELO_DISTANCE"] = "eloDistance";
5504
5919
  return Navigators2;
5505
5920
  })(Navigators || {});
5506
5921
  NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
@@ -5515,7 +5930,8 @@ var init_navigators = __esm({
5515
5930
  ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
5516
5931
  ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
5517
5932
  ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
5518
- ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
5933
+ ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */,
5934
+ ["eloDistance" /* ELO_DISTANCE */]: "filter" /* FILTER */
5519
5935
  };
5520
5936
  ContentNavigator = class {
5521
5937
  /** User interface for this navigation session */
@@ -6294,6 +6710,14 @@ ${e.stack}` : JSON.stringify(e);
6294
6710
  setEphemeralHints(hints) {
6295
6711
  this._pendingHints = hints;
6296
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
+ }
6297
6721
  async getWeightedCards(limit) {
6298
6722
  const u = await this._getCurrentUser();
6299
6723
  try {
@@ -10657,10 +11081,11 @@ function backlogHtml(backlog) {
10657
11081
  const rows = backlog.map((b) => {
10658
11082
  const hot = b.backlogMultiplier >= 3;
10659
11083
  const multColor = b.backlogMultiplier <= 1 ? "#86efac" : hot ? "#fca5a5" : "#fcd34d";
10660
- 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)}` : "";
10661
11086
  const top = b.topReviewScore !== null ? b.topReviewScore.toFixed(2) : "\u2014";
10662
11087
  const next = b.nextDueIn ? ` <span style="opacity:.6">\xB7 next due ${esc(b.nextDueIn)}</span>` : "";
10663
- 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>`;
10664
11089
  }).join("");
10665
11090
  return `<div style="margin-bottom:6px"><div style="color:#93c5fd">review backpressure</div>${rows}</div>`;
10666
11091
  }
@@ -10799,8 +11224,9 @@ function snapshotToText(s) {
10799
11224
  const headroom = b.backlogMultiplier > 1 ? "climbing" : "healthy";
10800
11225
  const top = b.topReviewScore !== null ? b.topReviewScore.toFixed(2) : "\u2014";
10801
11226
  const next = b.nextDueIn ? `, next due ${b.nextDueIn}` : "";
11227
+ const mass = b.reviewMass !== null ? `, mass ${b.reviewMass.toFixed(1)}` : "";
10802
11228
  lines.push(
10803
- ` ${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}`
10804
11230
  );
10805
11231
  }
10806
11232
  }
@@ -11158,7 +11584,49 @@ Example:
11158
11584
  });
11159
11585
 
11160
11586
  // src/study/SessionController.ts
11161
- var SessionController;
11587
+ function sig4(x) {
11588
+ return Number(x.toPrecision(4));
11589
+ }
11590
+ function toRunCard(c) {
11591
+ return {
11592
+ cardId: c.cardId,
11593
+ origin: c.origin,
11594
+ ...c.generator ? { generator: c.generator } : {},
11595
+ score: sig4(c.finalScore),
11596
+ selected: c.selected
11597
+ };
11598
+ }
11599
+ function toRunCardTrail(c) {
11600
+ return {
11601
+ ...toRunCard(c),
11602
+ trail: c.provenance.filter((p) => p.action !== "passed").map((p) => ({
11603
+ strategyName: p.strategyName,
11604
+ action: p.action,
11605
+ score: sig4(p.score),
11606
+ reason: p.reason
11607
+ }))
11608
+ };
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
+ }
11618
+ function persistedRunCards(run) {
11619
+ const selected = run.cards.filter((c) => c.selected);
11620
+ const runnersUp = run.cards.filter((c) => !c.selected).slice(0, PERSISTED_RUNNERS_UP);
11621
+ return [...selected, ...runnersUp].map(toRunCard);
11622
+ }
11623
+ function persistedUnselectedNew(u) {
11624
+ return {
11625
+ ...u.nextInLine ? { nextInLine: toRunCardTrail(u.nextInLine) } : {},
11626
+ ...u.topGenerated ? { topGenerated: toRunCardTrail(u.topGenerated) } : {}
11627
+ };
11628
+ }
11629
+ var PERSISTED_RUNNERS_UP, SessionController;
11162
11630
  var init_SessionController = __esm({
11163
11631
  "src/study/SessionController.ts"() {
11164
11632
  "use strict";
@@ -11180,6 +11648,7 @@ var init_SessionController = __esm({
11180
11648
  init_SessionDebugger();
11181
11649
  init_SessionOverlay();
11182
11650
  init_logger();
11651
+ PERSISTED_RUNNERS_UP = 5;
11183
11652
  SessionController = class _SessionController extends Loggable {
11184
11653
  _className = "SessionController";
11185
11654
  services;
@@ -11462,13 +11931,17 @@ var init_SessionController = __esm({
11462
11931
  newSelected: run.newSelected,
11463
11932
  // Compact detail projected off the full report so a persisted run is
11464
11933
  // self-explanatory once the in-memory ring buffer has rolled over.
11465
- // Per-card provenance (`run.cards`) is intentionally left out — it's
11466
- // the dominant memory cost and not worth persisting per run.
11934
+ // Per-card provenance is the dominant cost, so it's kept only for the
11935
+ // (at most two) `unselectedNew` cards, and only its score-changing
11936
+ // entries. Everything else is ids and scores.
11467
11937
  ...typeof run.userElo === "number" ? { userElo: run.userElo } : {},
11468
11938
  ...run.generators ? { generators: run.generators } : {},
11469
11939
  ...run.filters ? { filters: run.filters } : {},
11470
11940
  ...run.hints ? { hints: run.hints } : {},
11471
- ...run.discardedTail ? { discardedTail: run.discardedTail } : {}
11941
+ ...run.discardedTail ? { discardedTail: run.discardedTail } : {},
11942
+ cards: persistedRunCards(run),
11943
+ ...run.unselectedNew ? { unselectedNew: persistedUnselectedNew(run.unselectedNew) } : {},
11944
+ ...run.regulators ? { regulators: run.regulators.map(persistedReading) } : {}
11472
11945
  });
11473
11946
  }
11474
11947
  }
@@ -12229,6 +12702,13 @@ var init_SessionController = __esm({
12229
12702
  queueSource,
12230
12703
  nextItem.score
12231
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
+ }
12232
12712
  snapshotQueues(this.supplyQ.length, this.failedQ.length);
12233
12713
  return card;
12234
12714
  }
@@ -14097,7 +14577,6 @@ var init_PouchDataLayerProvider = __esm({
14097
14577
  "use strict";
14098
14578
  init_logger();
14099
14579
  init_dataDirectory();
14100
- init_auth();
14101
14580
  init_adminDB2();
14102
14581
  init_classroomDB2();
14103
14582
  init_courseDB();
@@ -14171,16 +14650,6 @@ var init_PouchDataLayerProvider = __esm({
14171
14650
  getAdminDB() {
14172
14651
  return new AdminDB();
14173
14652
  }
14174
- async createUserReaderForUser(targetUsername) {
14175
- const requestingUsername = await getLoggedInUsername();
14176
- if (requestingUsername !== "admin") {
14177
- throw new Error("Unauthorized: Only admin users can access other users' data");
14178
- }
14179
- logger.info(`Admin user '${requestingUsername}' requesting UserDBReader for '${targetUsername}'`);
14180
- const syncStrategy = new CouchDBSyncStrategy();
14181
- const targetUserDB = await BaseUser.instance(syncStrategy, targetUsername);
14182
- return targetUserDB;
14183
- }
14184
14653
  isReadOnly() {
14185
14654
  return false;
14186
14655
  }
@@ -14947,6 +15416,11 @@ var init_courseDB2 = __esm({
14947
15416
  setEphemeralHints(hints) {
14948
15417
  this._pendingHints = hints;
14949
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
+ }
14950
15424
  async getWeightedCards(limit) {
14951
15425
  try {
14952
15426
  const navigator2 = await this.createNavigator(this.userDB);
@@ -15193,12 +15667,6 @@ var init_StaticDataLayerProvider = __esm({
15193
15667
  getAdminDB() {
15194
15668
  throw new Error("Admin functions not supported in static mode");
15195
15669
  }
15196
- async createUserReaderForUser(targetUsername) {
15197
- logger.warn(`StaticDataLayerProvider: Multi-user access not supported in static mode`);
15198
- logger.warn(`Request: trying to access data for ${targetUsername}`);
15199
- logger.warn(`Returning current user's data instead`);
15200
- return this.getUserDB();
15201
- }
15202
15670
  isReadOnly() {
15203
15671
  return true;
15204
15672
  }
@@ -15872,6 +16340,7 @@ __export(index_exports, {
15872
16340
  ContentNavigator: () => ContentNavigator,
15873
16341
  CouchDBToStaticPacker: () => CouchDBToStaticPacker,
15874
16342
  CourseLookup: () => CourseLookup,
16343
+ DEFAULT_REGULATOR_CONFIG: () => DEFAULT_REGULATOR_CONFIG,
15875
16344
  DIVERSITY_FLOOR: () => DIVERSITY_FLOOR,
15876
16345
  DIVERSITY_STRENGTH: () => DIVERSITY_STRENGTH,
15877
16346
  DocType: () => DocType,
@@ -15880,11 +16349,13 @@ __export(index_exports, {
15880
16349
  FileSystemError: () => FileSystemError,
15881
16350
  GuestUsername: () => GuestUsername,
15882
16351
  HYDRATION_MARKER_ID: () => HYDRATION_MARKER_ID,
16352
+ INTAKE_CLOCK_KEY: () => INTAKE_CLOCK_KEY,
15883
16353
  Loggable: () => Loggable,
15884
16354
  NOT_SET: () => NOT_SET,
15885
16355
  NavigatorRole: () => NavigatorRole,
15886
16356
  NavigatorRoles: () => NavigatorRoles,
15887
16357
  Navigators: () => Navigators,
16358
+ PIPELINE_STAGES: () => PIPELINE_STAGES,
15888
16359
  QuotaRoundRobinMixer: () => QuotaRoundRobinMixer,
15889
16360
  REVIEW_TIME_FORMAT: () => REVIEW_TIME_FORMAT2,
15890
16361
  SessionController: () => SessionController,
@@ -15892,6 +16363,7 @@ __export(index_exports, {
15892
16363
  TagFilteredContentSource: () => TagFilteredContentSource,
15893
16364
  _resetDataLayer: () => _resetDataLayer,
15894
16365
  aggregateOutcomesForGradient: () => aggregateOutcomesForGradient,
16366
+ applyReading: () => applyReading,
15895
16367
  areQuestionRecords: () => areQuestionRecords,
15896
16368
  buildStrategyStateId: () => buildStrategyStateId,
15897
16369
  captureMixerRun: () => captureMixerRun,
@@ -15910,6 +16382,7 @@ __export(index_exports, {
15910
16382
  drainCapturedRuns: () => drainCapturedRuns,
15911
16383
  endSessionTracking: () => endSessionTracking,
15912
16384
  ensureAppDataDirectory: () => ensureAppDataDirectory,
16385
+ frozenMsAt: () => frozenMsAt,
15913
16386
  getActiveController: () => getActiveController,
15914
16387
  getActivePipeline: () => getActivePipeline,
15915
16388
  getAppDataDirectory: () => getAppDataDirectory,
@@ -15919,6 +16392,7 @@ __export(index_exports, {
15919
16392
  getDbPath: () => getDbPath,
15920
16393
  getDefaultLearnableWeight: () => getDefaultLearnableWeight,
15921
16394
  getLapses: () => getLapses,
16395
+ getRegisteredFilterKind: () => getRegisteredFilterKind,
15922
16396
  getRegisteredNavigator: () => getRegisteredNavigator,
15923
16397
  getRegisteredNavigatorNames: () => getRegisteredNavigatorNames,
15924
16398
  getRegisteredNavigatorRole: () => getRegisteredNavigatorRole,
@@ -15932,6 +16406,8 @@ __export(index_exports, {
15932
16406
  initializeDataDirectory: () => initializeDataDirectory,
15933
16407
  initializeDataLayer: () => initializeDataLayer,
15934
16408
  initializeNavigatorRegistry: () => initializeNavigatorRegistry,
16409
+ intakeHours: () => intakeHours,
16410
+ intakeReading: () => intakeReading,
15935
16411
  isDataShapeRegistered: () => isDataShapeRegistered,
15936
16412
  isDataShapeSchemaAvailable: () => isDataShapeSchemaAvailable,
15937
16413
  isFilter: () => isFilter,
@@ -15951,6 +16427,7 @@ __export(index_exports, {
15951
16427
  newSessionId: () => newSessionId,
15952
16428
  parseCardHistoryID: () => parseCardHistoryID,
15953
16429
  pipelineDebugAPI: () => pipelineDebugAPI,
16430
+ planPipeline: () => planPipeline,
15954
16431
  processCustomQuestionsData: () => processCustomQuestionsData,
15955
16432
  recordCardPresentation: () => recordCardPresentation,
15956
16433
  recordUserOutcome: () => recordUserOutcome,
@@ -15964,12 +16441,16 @@ __export(index_exports, {
15964
16441
  removeCustomQuestionTypes: () => removeCustomQuestionTypes,
15965
16442
  removeDataShape: () => removeDataShape,
15966
16443
  removeQuestionType: () => removeQuestionType,
16444
+ resetIntakeClock: () => resetIntakeClock,
16445
+ reviewMassReading: () => reviewMassReading,
16446
+ reviewWeight: () => reviewWeight,
15967
16447
  runPeriodUpdate: () => runPeriodUpdate,
15968
16448
  scoreAccuracyInZone: () => scoreAccuracyInZone,
15969
16449
  sessionDebugAPI: () => sessionDebugAPI,
15970
16450
  setDebugSessionId: () => setDebugSessionId,
15971
16451
  snapshotQueues: () => snapshotQueues,
15972
16452
  startSessionTracking: () => startSessionTracking,
16453
+ stepIntakeClock: () => stepIntakeClock,
15973
16454
  toggleSessionOverlay: () => toggleSessionOverlay,
15974
16455
  updateLearningState: () => updateLearningState,
15975
16456
  updateStrategyWeight: () => updateStrategyWeight,
@@ -15980,6 +16461,8 @@ __export(index_exports, {
15980
16461
  });
15981
16462
  module.exports = __toCommonJS(index_exports);
15982
16463
  init_core();
16464
+ init_pipelinePlan();
16465
+ init_regulators();
15983
16466
  init_courseLookupDB();
15984
16467
 
15985
16468
  // src/courseConfigRegistration.ts
@@ -16297,6 +16780,7 @@ init_userDBHelpers();
16297
16780
  ContentNavigator,
16298
16781
  CouchDBToStaticPacker,
16299
16782
  CourseLookup,
16783
+ DEFAULT_REGULATOR_CONFIG,
16300
16784
  DIVERSITY_FLOOR,
16301
16785
  DIVERSITY_STRENGTH,
16302
16786
  DocType,
@@ -16305,11 +16789,13 @@ init_userDBHelpers();
16305
16789
  FileSystemError,
16306
16790
  GuestUsername,
16307
16791
  HYDRATION_MARKER_ID,
16792
+ INTAKE_CLOCK_KEY,
16308
16793
  Loggable,
16309
16794
  NOT_SET,
16310
16795
  NavigatorRole,
16311
16796
  NavigatorRoles,
16312
16797
  Navigators,
16798
+ PIPELINE_STAGES,
16313
16799
  QuotaRoundRobinMixer,
16314
16800
  REVIEW_TIME_FORMAT,
16315
16801
  SessionController,
@@ -16317,6 +16803,7 @@ init_userDBHelpers();
16317
16803
  TagFilteredContentSource,
16318
16804
  _resetDataLayer,
16319
16805
  aggregateOutcomesForGradient,
16806
+ applyReading,
16320
16807
  areQuestionRecords,
16321
16808
  buildStrategyStateId,
16322
16809
  captureMixerRun,
@@ -16335,6 +16822,7 @@ init_userDBHelpers();
16335
16822
  drainCapturedRuns,
16336
16823
  endSessionTracking,
16337
16824
  ensureAppDataDirectory,
16825
+ frozenMsAt,
16338
16826
  getActiveController,
16339
16827
  getActivePipeline,
16340
16828
  getAppDataDirectory,
@@ -16344,6 +16832,7 @@ init_userDBHelpers();
16344
16832
  getDbPath,
16345
16833
  getDefaultLearnableWeight,
16346
16834
  getLapses,
16835
+ getRegisteredFilterKind,
16347
16836
  getRegisteredNavigator,
16348
16837
  getRegisteredNavigatorNames,
16349
16838
  getRegisteredNavigatorRole,
@@ -16357,6 +16846,8 @@ init_userDBHelpers();
16357
16846
  initializeDataDirectory,
16358
16847
  initializeDataLayer,
16359
16848
  initializeNavigatorRegistry,
16849
+ intakeHours,
16850
+ intakeReading,
16360
16851
  isDataShapeRegistered,
16361
16852
  isDataShapeSchemaAvailable,
16362
16853
  isFilter,
@@ -16376,6 +16867,7 @@ init_userDBHelpers();
16376
16867
  newSessionId,
16377
16868
  parseCardHistoryID,
16378
16869
  pipelineDebugAPI,
16870
+ planPipeline,
16379
16871
  processCustomQuestionsData,
16380
16872
  recordCardPresentation,
16381
16873
  recordUserOutcome,
@@ -16389,12 +16881,16 @@ init_userDBHelpers();
16389
16881
  removeCustomQuestionTypes,
16390
16882
  removeDataShape,
16391
16883
  removeQuestionType,
16884
+ resetIntakeClock,
16885
+ reviewMassReading,
16886
+ reviewWeight,
16392
16887
  runPeriodUpdate,
16393
16888
  scoreAccuracyInZone,
16394
16889
  sessionDebugAPI,
16395
16890
  setDebugSessionId,
16396
16891
  snapshotQueues,
16397
16892
  startSessionTracking,
16893
+ stepIntakeClock,
16398
16894
  toggleSessionOverlay,
16399
16895
  updateLearningState,
16400
16896
  updateStrategyWeight,