@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
@@ -2,15 +2,16 @@
2
2
  // SRS BACKLOG DEBUGGER
3
3
  // ============================================================================
4
4
  //
5
- // A tiny module-level capture of the SRS generator's per-run backlog state,
6
- // so the live session overlay can show how much runway remains before reviews
7
- // out-compete the current (boosted) new/prescribed cards: the backlog
8
- // multiplier is exponential and uncapped, so it always has headroom to climb
9
- // further — the question is just how large the backlog needs to get before it
10
- // crosses whatever the competing boosts currently sit at.
5
+ // A tiny module-level capture of per-run review backlog state, so the live
6
+ // session overlay can show how much runway remains before reviews out-compete
7
+ // the current (boosted) new/prescribed cards: the review-mass multiplier is
8
+ // exponential and uncapped, so it always has headroom to climb further — the
9
+ // question is just how large the backlog's mass needs to get before it crosses
10
+ // whatever the competing boosts currently sit at.
11
11
  //
12
- // Mirrors MixerDebugger/PipelineDebugger: the generator pushes a snapshot each
13
- // run (keyed by course, latest wins); the overlay reads it via the controller's
12
+ // The SRS generator captures counts each run; the pipeline's regulator stage
13
+ // then patches in the review mass and the multiplier (noteReviewPressure).
14
+ // Keyed by course, latest wins; the overlay reads it via the controller's
14
15
  // getDebugSnapshot(). No DB load on the read path.
15
16
  //
16
17
  // ============================================================================
@@ -22,13 +23,18 @@ export interface SrsBacklogDebug {
22
23
  scheduledTotal: number;
23
24
  /** Reviews eligible (due) right now. */
24
25
  dueNow: number;
25
- /** Healthy backlog threshold; multiplier is ×1.0 at or below this. */
26
+ /** Healthy review mass (card-equivalents); the multiplier is ×1.0 at or below it. */
26
27
  healthyBacklog: number;
27
- /** Global multiplier applied to every due review's urgency this run (>= 1.0, unbounded). */
28
+ /**
29
+ * Review mass: the due reviews' filtered scores against a reference, each at
30
+ * most 1. Set by the regulator stage; null until it has run.
31
+ */
32
+ reviewMass: number | null;
33
+ /** Multiplier the regulator stage applied to every due review this run (>= 1.0, unbounded). */
28
34
  backlogMultiplier: number;
29
- /** Exponential growth-rate base the multiplier climbs by per multiple of healthyBacklog excess. */
35
+ /** Exponential growth-rate base the multiplier climbs by per multiple of healthy mass in excess. */
30
36
  backlogGrowthRate: number;
31
- /** Highest review score produced this run (post-multiplier; can exceed 1.0); null if none due. */
37
+ /** Highest review urgency score from the SRS generator (before filters and regulators); null if none due. */
32
38
  topReviewScore: number | null;
33
39
  /** Human-readable time until the next review comes due, or null if some are due now. */
34
40
  nextDueIn: string | null;
@@ -43,6 +49,25 @@ export function captureSrsBacklog(snapshot: SrsBacklogDebug): void {
43
49
  snapshots.set(snapshot.courseId, snapshot);
44
50
  }
45
51
 
52
+ /**
53
+ * Called by the pipeline's regulator stage once per run: the review mass and
54
+ * the multiplier it set. Patches the course's latest SRS snapshot.
55
+ */
56
+ export function noteReviewPressure(
57
+ courseId: string,
58
+ pressure: { mass: number; healthyMass: number; rate: number; multiplier: number }
59
+ ): void {
60
+ const snapshot = snapshots.get(courseId);
61
+ if (!snapshot) return;
62
+ snapshots.set(courseId, {
63
+ ...snapshot,
64
+ reviewMass: pressure.mass,
65
+ healthyBacklog: pressure.healthyMass,
66
+ backlogGrowthRate: pressure.rate,
67
+ backlogMultiplier: pressure.multiplier,
68
+ });
69
+ }
70
+
46
71
  /** Current backlog snapshot for every course seen, newest-first. */
47
72
  export function getSrsBacklogDebug(): SrsBacklogDebug[] {
48
73
  return [...snapshots.values()].sort((a, b) => b.timestamp - a.timestamp);
@@ -3,7 +3,7 @@ import { Pipeline } from './Pipeline';
3
3
  import CompositeGenerator from './generators/CompositeGenerator';
4
4
  import ELONavigator from './generators/elo';
5
5
  import SRSNavigator from './generators/srs';
6
- import { createEloDistanceFilter } from './filters/eloDistance';
6
+ import EloDistanceFilter, { DEFAULT_ELO_DISTANCE_CONFIG } from './filters/eloDistance';
7
7
  import type { ContentNavigationStrategyData } from '../types/contentNavigationStrategy';
8
8
  import { DocType } from '../types/types-legacy';
9
9
  import type { CourseDBInterface, UserDBInterface } from '../interfaces';
@@ -53,13 +53,33 @@ export function createDefaultSrsStrategy(courseId: string): ContentNavigationStr
53
53
  };
54
54
  }
55
55
 
56
+ /**
57
+ * Create default ELO distance filter strategy data. The assembler adds it to
58
+ * any pipeline whose strategy docs declare no `eloDistance` filter.
59
+ *
60
+ * @param courseId - The course ID to associate with this strategy
61
+ * @returns Strategy data for the default ELO distance filter (default curve)
62
+ */
63
+ export function createDefaultEloDistanceStrategy(courseId: string): ContentNavigationStrategyData {
64
+ return {
65
+ _id: 'NAVIGATION_STRATEGY-eloDistance-default',
66
+ docType: DocType.NAVIGATION_STRATEGY,
67
+ name: 'ELO Distance (default)',
68
+ description: 'Scales every candidate, new or review, by its distance from the learner\'s ELO',
69
+ implementingClass: Navigators.ELO_DISTANCE,
70
+ course: courseId,
71
+ // Explicit, though the filter would default to it anyway: views show what runs.
72
+ serializedData: JSON.stringify(DEFAULT_ELO_DISTANCE_CONFIG),
73
+ };
74
+ }
75
+
56
76
  /**
57
77
  * Creates the default navigation pipeline for courses with no configured strategies.
58
78
  *
59
- * Default: Pipeline(Composite(ELO, SRS), [eloDistanceFilter])
60
- * - ELO generator: scores new cards by skill proximity
79
+ * Default: Pipeline(Composite(ELO, SRS), [ELO distance])
80
+ * - ELO generator: retrieves new cards near the learner's ELO
61
81
  * - SRS generator: scores reviews by overdueness and interval recency
62
- * - ELO distance filter: penalizes cards far from user's current level
82
+ * - ELO distance filter: scales every card by its distance from the learner's ELO
63
83
  *
64
84
  * This is the canonical default configuration used when:
65
85
  * - No navigation strategy documents exist in the course
@@ -78,7 +98,11 @@ export function createDefaultPipeline(
78
98
  const srsNavigator = new SRSNavigator(user, course, createDefaultSrsStrategy(courseId));
79
99
 
80
100
  const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);
81
- const eloDistanceFilter = createEloDistanceFilter();
101
+ const eloDistanceFilter = new EloDistanceFilter(
102
+ user,
103
+ course,
104
+ createDefaultEloDistanceStrategy(courseId)
105
+ );
82
106
 
83
107
  return new Pipeline(compositeGenerator, [eloDistanceFilter], user, course);
84
108
  }
@@ -1,4 +1,4 @@
1
- import { CardFilter, FilterContext } from './types';
1
+ import { CardFilter, FilterContext, FilterKind } from './types';
2
2
  import { WeightedCard } from '../index';
3
3
  import { LearnableWeight, DEFAULT_LEARNABLE_WEIGHT } from '../../types/contentNavigationStrategy';
4
4
 
@@ -18,6 +18,8 @@ import { LearnableWeight, DEFAULT_LEARNABLE_WEIGHT } from '../../types/contentNa
18
18
  */
19
19
  export class WeightedFilter implements CardFilter {
20
20
  public name: string;
21
+ public kind?: FilterKind;
22
+ public liveOnly?: boolean;
21
23
  private inner: CardFilter;
22
24
  private learnable: LearnableWeight;
23
25
  private staticWeight: boolean;
@@ -31,6 +33,8 @@ export class WeightedFilter implements CardFilter {
31
33
  ) {
32
34
  this.inner = inner;
33
35
  this.name = inner.name;
36
+ this.kind = inner.kind;
37
+ this.liveOnly = inner.liveOnly;
34
38
  this.learnable = learnable;
35
39
  this.staticWeight = staticWeight;
36
40
  this.strategyId = strategyId;
@@ -1,132 +1,317 @@
1
+ import type { CourseDBInterface } from '../../interfaces/courseDB';
2
+ import type { UserDBInterface } from '../../interfaces/userDB';
3
+ import type { ContentNavigationStrategyData } from '../../types/contentNavigationStrategy';
4
+ import { ContentNavigator } from '../index';
1
5
  import type { WeightedCard } from '../index';
2
- import type { CardFilter, FilterContext } from './types';
6
+ import type { GeneratorResult } from '../generators/types';
7
+ import type { CardFilter, FilterContext, FilterKind } from './types';
8
+ import type { CourseElo } from '@vue-skuilder/common';
3
9
 
4
10
  // ============================================================================
5
11
  // ELO DISTANCE FILTER
6
12
  // ============================================================================
7
13
  //
8
- // Penalizes cards that are far from the user's current ELO using a smooth curve.
14
+ // Scales every candidate by how close its ELO is to the learner's, on a smooth
15
+ // Gaussian (no discontinuities, never zero).
9
16
  //
10
- // This filter addresses cross-strategy coordination:
11
- // - SRS generates reviews based on scheduling
12
- // - But some scheduled cards may be "below" the user's current level
13
- // - Or "above" (shouldn't happen often, but possible)
17
+ // The one place ELO distance counts. Generators retrieve (the ELO generator
18
+ // pulls a window of cards near the learner's ELO) and score only on what's
19
+ // specific to their source; a signal that applies to every card lives in one
20
+ // heap-wide filter, so new cards and reviews are weighed on the same terms:
21
+ // - reviews the learner has moved beyond fade, and may never surface over
22
+ // higher-priority work;
23
+ // - new cards far from the learner's level rank low (this used to live in the
24
+ // ELO generator's own score, which double-counted alongside this filter).
14
25
  //
15
- // By applying ELO distance penalties, we can:
16
- // - Deprioritize reviews the user has "moved beyond"
17
- // - Deprioritize cards that are too hard for current skill level
26
+ // Tag-aware (default): a card's difficulty for this learner is read on the
27
+ // skills they share, not only on global ELO. Card and learner keep paired
28
+ // ratings per tag (each graded response adjusts both), so a tag's gap
29
+ // (card − learner) is as meaningful as the global one, and often more: a card
30
+ // can sit at the learner's global level while testing their weakest skill.
31
+ // See tagAwareGap for the combination.
18
32
  //
19
- // The penalty curve is smooth (no discontinuities) using a Gaussian-like decay.
33
+ // A `signal`, not a gate: it expresses preference, not readiness. `liveOnly`:
34
+ // forecasts and card-space scans start every card at 1.0 without a generator,
35
+ // and never applied ELO distance, so they skip it.
36
+ //
37
+ // The assembler adds this filter (as "ELO Distance (default)") to every
38
+ // pipeline whose strategy docs don't declare one. A course tunes it by
39
+ // declaring its own `eloDistance` strategy doc with an EloDistanceConfig.
20
40
  //
21
41
  // ============================================================================
22
42
 
23
43
  /**
24
- * Configuration for the ELO distance filter.
44
+ * Configuration for the ELO distance curve:
45
+ * `minMultiplier + (maxMultiplier − minMultiplier) · exp(−(distance / halfLife)²)`.
25
46
  */
26
47
  export interface EloDistanceConfig {
27
48
  /**
28
- * The ELO distance at which the multiplier is ~0.6 (one standard deviation).
29
- * Default: 200 ELO points.
49
+ * The Gaussian's scale in ELO points (despite the name, not a half-life).
50
+ * Default 300: distance 250 → ~0.5, as the ELO generator scored new cards.
30
51
  *
31
- * - At distance 0: multiplier ≈ 1.0
32
- * - At distance = halfLife: multiplier ≈ 0.6
33
- * - At distance = 2 * halfLife: multiplier ≈ 0.37
34
- * - At distance = 3 * halfLife: multiplier ≈ 0.22
52
+ * - distance 0: maxMultiplier
53
+ * - distance = halfLife: ~0.4 (with the default floor)
54
+ * - distance = 2 · halfLife: ~0.07
35
55
  */
36
56
  halfLife?: number;
37
57
 
38
58
  /**
39
- * Minimum multiplier (floor) to prevent scores from going too low.
40
- * Default: 0.3
59
+ * Floor, so far-off cards keep a nonzero score (the pipeline drops zero
60
+ * scores before hints, and a hint must be able to lift any card). Default 0.05.
41
61
  */
42
62
  minMultiplier?: number;
43
63
 
64
+ /** Ceiling. Usually 1.0 (no boost for close cards). Default 1.0. */
65
+ maxMultiplier?: number;
66
+
44
67
  /**
45
- * Maximum multiplier (ceiling). Usually 1.0 (no boost for close cards).
46
- * Default: 1.0
68
+ * Measure distance on the tags the card and learner share (see
69
+ * tagAwareGap), falling back to global ELO where they share none.
70
+ * Default true.
47
71
  */
48
- maxMultiplier?: number;
72
+ tagAware?: boolean;
73
+
74
+ /**
75
+ * A learner's tag rating counts once it rests on at least this many graded
76
+ * responses. Count-only (exposure) tags never count. Default 3.
77
+ */
78
+ minTagCount?: number;
49
79
  }
50
80
 
51
- const DEFAULT_HALF_LIFE = 200;
52
- const DEFAULT_MIN_MULTIPLIER = 0.3;
53
- const DEFAULT_MAX_MULTIPLIER = 1.0;
81
+ /**
82
+ * The default curve. The default strategy doc carries it as its config, so
83
+ * the admin pipeline view shows what runs.
84
+ */
85
+ export const DEFAULT_ELO_DISTANCE_CONFIG: Required<EloDistanceConfig> = {
86
+ halfLife: 300,
87
+ minMultiplier: 0.05,
88
+ maxMultiplier: 1.0,
89
+ tagAware: true,
90
+ minTagCount: 3,
91
+ };
54
92
 
55
93
  /**
56
- * Compute the multiplier for a given ELO distance using Gaussian decay.
57
- *
58
- * Formula: minMultiplier + (maxMultiplier - minMultiplier) * exp(-(distance/halfLife)^2)
59
- *
60
- * This produces a smooth bell curve centered at distance=0:
61
- * - At distance 0: multiplier = maxMultiplier (1.0)
62
- * - As distance increases: multiplier smoothly decays toward minMultiplier
63
- * - No discontinuities or sudden jumps
94
+ * Graded responses at which a tag's gap carries half its full weight. Thin
95
+ * tag evidence leans on global ELO; well-practised tags dominate.
64
96
  */
97
+ const TAG_CONFIDENCE_HALF = 10;
98
+
99
+ /** Count-only tag ratings (exposure tracking) carry this sentinel score. */
100
+ const COUNT_ONLY_SENTINEL = -1;
101
+
102
+ /** Fallback card ELO when a card has none recorded. */
103
+ const DEFAULT_CARD_ELO = 1000;
104
+
65
105
  function computeMultiplier(
66
106
  distance: number,
67
107
  halfLife: number,
68
108
  minMultiplier: number,
69
109
  maxMultiplier: number
70
110
  ): number {
71
- // Gaussian decay: exp(-(d/h)^2)
72
111
  const normalizedDistance = distance / halfLife;
73
112
  const decay = Math.exp(-(normalizedDistance * normalizedDistance));
74
-
75
- // Scale between min and max
76
113
  return minMultiplier + (maxMultiplier - minMultiplier) * decay;
77
114
  }
78
115
 
116
+ function resolveConfig(config?: EloDistanceConfig): Required<EloDistanceConfig> {
117
+ return { ...DEFAULT_ELO_DISTANCE_CONFIG, ...config };
118
+ }
119
+
120
+ /** One shared tag's contribution to a card's tag-aware gap. */
121
+ interface TagGap {
122
+ tag: string;
123
+ /** Card's tag rating minus the learner's: positive = harder than their level. */
124
+ gap: number;
125
+ weight: number;
126
+ }
127
+
79
128
  /**
80
- * Create an ELO distance filter.
129
+ * The card's difficulty for this learner, in ELO points (card − learner),
130
+ * read on the tags they share.
131
+ *
132
+ * - Shared tags: the card's tags on which the learner has a real rating
133
+ * (not the count-only sentinel) resting on at least `minTagCount` graded
134
+ * responses. A card with no rating of its own on a tag uses its global, as
135
+ * the ELO update does when it first grades that tag.
136
+ * - Each tag's gap is weighted by the learner's evidence on it,
137
+ * n / (n + TAG_CONFIDENCE_HALF).
138
+ * - The weighted mean of the tag gaps is blended with the global gap by the
139
+ * total evidence W: λ = W / (W + 1). One thin tag barely moves it; several
140
+ * practised tags dominate it.
81
141
  *
82
- * Penalizes cards that are far from the user's current ELO level
83
- * using a smooth Gaussian decay curve. No discontinuities.
142
+ * OPEN (draft, 2026-10-01; uncommitted, to sit on). On one LP learner's
143
+ * 09-30 dump the effect was modest: every touched card shared a rated tag
144
+ * (median 4); mean multiplier ×0.70 → ×0.75 over 352 touched cards, ×0.84 →
145
+ * ×0.88 over 42 due reviews. The biggest movers were old who-said-that cards:
146
+ * ~400 below the learner globally, ~280 below on their own skills.
84
147
  *
85
- * @param config - Optional configuration for the decay curve
86
- * @returns A CardFilter that applies ELO distance penalties
148
+ * 1. Compensatory or conjunctive. This averages: a weak skill is offset by
149
+ * strong ones. For spelling a word, which needs every grapheme, the hardest
150
+ * shared skill arguably sets the difficulty: take the largest gap instead.
151
+ * The main design question.
152
+ * 2. Which tags count. Broad tags (`concept:match:simple`, `ui:*`) sit on most
153
+ * cards and act like a second global rating. The framework may want the
154
+ * course to say which tags are skills (cf. LP's diagnostics interpreter
155
+ * `isSkillTag`), e.g. as tag patterns in the strategy config.
156
+ * 3. New cards matter most, and that dump couldn't show them. An unseen
157
+ * card's tag ratings fall back to its global, so for new cards this reads
158
+ * "card global vs the learner's rating on that skill". Measuring it needs a
159
+ * `--course all` dump.
160
+ * 4. Cost. Tag-aware fetches full ratings for every candidate (~500 card docs
161
+ * per run); global-only fetches only reviews'.
162
+ * 5. Retrieval stays global. The ELO generator's window is the cards nearest
163
+ * the learner's global ELO, so a card that's well matched on its skills but
164
+ * far off globally may never be retrieved.
165
+ * 6. Target. Distance 0 means ~50% expected success. Early learners may do
166
+ * better aiming higher: a shift of the curve's centre, independent of this.
87
167
  */
88
- export function createEloDistanceFilter(config?: EloDistanceConfig): CardFilter {
89
- const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
90
- const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
91
- const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
168
+ export function tagAwareGap(
169
+ cardTags: readonly string[],
170
+ cardElo: CourseElo,
171
+ userElo: CourseElo,
172
+ minTagCount: number
173
+ ): { gap: number; globalGap: number; tags: TagGap[] } {
174
+ const globalGap = cardElo.global.score - userElo.global.score;
175
+ const tags: TagGap[] = [];
176
+ for (const tag of cardTags) {
177
+ const user = userElo.tags[tag];
178
+ if (!user || user.score === COUNT_ONLY_SENTINEL || user.count < minTagCount) continue;
179
+ const card = cardElo.tags[tag]?.score ?? cardElo.global.score;
180
+ tags.push({
181
+ tag,
182
+ gap: card - user.score,
183
+ weight: user.count / (user.count + TAG_CONFIDENCE_HALF),
184
+ });
185
+ }
186
+ if (tags.length === 0) return { gap: globalGap, globalGap, tags };
92
187
 
93
- return {
94
- name: 'ELO Distance Filter',
188
+ const total = tags.reduce((w, t) => w + t.weight, 0);
189
+ const tagGap = tags.reduce((g, t) => g + t.weight * t.gap, 0) / total;
190
+ const lambda = total / (total + 1);
191
+ return { gap: lambda * tagGap + (1 - lambda) * globalGap, globalGap, tags };
192
+ }
193
+
194
+ function tagReason(tags: TagGap[], globalGap: number): string {
195
+ const shown = [...tags]
196
+ .sort((a, b) => Math.abs(b.gap) * b.weight - Math.abs(a.gap) * a.weight)
197
+ .slice(0, 3)
198
+ .map((t) => `${t.tag} ${t.gap >= 0 ? '+' : ''}${Math.round(t.gap)}`)
199
+ .join(', ');
200
+ const more = tags.length > 3 ? `, +${tags.length - 3} more` : '';
201
+ return ` on ${tags.length} shared tag(s) [${shown}${more}] (global ${globalGap >= 0 ? '+' : ''}${Math.round(globalGap)})`;
202
+ }
95
203
 
96
- async transform(cards: WeightedCard[], context: FilterContext): Promise<WeightedCard[]> {
97
- const { course, userElo } = context;
204
+ async function applyEloDistance(
205
+ cards: WeightedCard[],
206
+ context: FilterContext,
207
+ config: Required<EloDistanceConfig>,
208
+ source: { name: string; strategyId: string }
209
+ ): Promise<WeightedCard[]> {
210
+ const { course, userElo, userCourseElo } = context;
211
+ const { halfLife, minMultiplier, maxMultiplier } = config;
212
+ const tagAware = config.tagAware && userCourseElo !== undefined;
98
213
 
99
- // Batch fetch ELO data for all cards
100
- const cardIds = cards.map((c) => c.cardId);
101
- const cardElos = await course.getCardEloData(cardIds);
214
+ // Tag-aware needs every card's full ratings; otherwise only the ELO of cards
215
+ // that don't carry it (reviews). One batch either way.
216
+ const missing = cards.filter((c) => tagAware || c.cardElo === undefined).map((c) => c.cardId);
217
+ const fetched = new Map<string, CourseElo>();
218
+ if (missing.length > 0) {
219
+ const elos = await course.getCardEloData(missing);
220
+ missing.forEach((id, i) => {
221
+ if (elos[i]) fetched.set(id, elos[i]);
222
+ });
223
+ }
102
224
 
103
- return cards.map((card, i) => {
104
- const cardElo = cardElos[i]?.global?.score ?? 1000;
105
- const distance = Math.abs(cardElo - userElo);
106
- const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
107
- const newScore = card.score * multiplier;
225
+ return cards.map((card) => {
226
+ const full = fetched.get(card.cardId);
227
+ const cardElo = full?.global?.score ?? card.cardElo ?? DEFAULT_CARD_ELO;
108
228
 
109
- const action = multiplier < maxMultiplier - 0.01 ? 'penalized' : 'passed';
229
+ let distance = Math.abs(cardElo - userElo);
230
+ let how = '';
231
+ if (tagAware && full) {
232
+ const t = tagAwareGap(card.tags ?? [], full, userCourseElo!, config.minTagCount);
233
+ distance = Math.abs(t.gap);
234
+ if (t.tags.length > 0) how = tagReason(t.tags, t.globalGap);
235
+ }
110
236
 
111
- return {
112
- ...card,
237
+ const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
238
+ const newScore = card.score * multiplier;
239
+ const action = multiplier < maxMultiplier - 0.01 ? 'penalized' : 'passed';
240
+
241
+ return {
242
+ ...card,
243
+ cardElo,
244
+ score: newScore,
245
+ provenance: [
246
+ ...card.provenance,
247
+ {
248
+ strategy: 'eloDistance',
249
+ strategyName: source.name,
250
+ strategyId: source.strategyId,
251
+ action,
113
252
  score: newScore,
114
- provenance: [
115
- ...card.provenance,
116
- {
117
- strategy: 'eloDistance',
118
- strategyName: 'ELO Distance Filter',
119
- strategyId: 'ELO_DISTANCE_FILTER',
120
- action,
121
- score: newScore,
122
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) → ${multiplier.toFixed(2)}x`,
123
- },
124
- ],
125
- };
126
- });
127
- },
253
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)})${how} → ${multiplier.toFixed(2)}x`,
254
+ },
255
+ ],
256
+ };
257
+ });
258
+ }
259
+
260
+ /**
261
+ * Create an ELO distance filter outside the strategy-doc path.
262
+ *
263
+ * @param config - Optional configuration for the curve
264
+ */
265
+ export function createEloDistanceFilter(config?: EloDistanceConfig): CardFilter {
266
+ const resolved = resolveConfig(config);
267
+ const source = { name: 'ELO Distance Filter', strategyId: 'ELO_DISTANCE_FILTER' };
268
+ return {
269
+ name: source.name,
270
+ kind: 'signal',
271
+ liveOnly: true,
272
+ transform: (cards, context) => applyEloDistance(cards, context, resolved, source),
128
273
  };
129
274
  }
130
275
 
131
- // Export defaults for testing
132
- export { DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER };
276
+ /**
277
+ * The ELO distance filter as a strategy-doc navigator (`implementingClass:
278
+ * 'eloDistance'`, serializedData: an EloDistanceConfig as JSON, or empty).
279
+ */
280
+ export default class EloDistanceFilter extends ContentNavigator implements CardFilter {
281
+ name: string;
282
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
283
+ static readonly kind: FilterKind = 'signal';
284
+ readonly kind = EloDistanceFilter.kind;
285
+ readonly liveOnly = true;
286
+ private config: Required<EloDistanceConfig>;
287
+
288
+ constructor(
289
+ user: UserDBInterface,
290
+ course: CourseDBInterface,
291
+ strategyData: ContentNavigationStrategyData
292
+ ) {
293
+ super(user, course, strategyData);
294
+ this.name = strategyData.name || 'ELO Distance';
295
+ let parsed: EloDistanceConfig | undefined;
296
+ try {
297
+ parsed = strategyData.serializedData ? JSON.parse(strategyData.serializedData) : undefined;
298
+ } catch {
299
+ parsed = undefined;
300
+ }
301
+ this.config = resolveConfig(parsed);
302
+ }
303
+
304
+ transform(cards: WeightedCard[], context: FilterContext): Promise<WeightedCard[]> {
305
+ return applyEloDistance(cards, context, this.config, {
306
+ name: this.name,
307
+ strategyId: this.strategyId || 'NAVIGATION_STRATEGY-eloDistance-default',
308
+ });
309
+ }
310
+
311
+ async getWeightedCards(_limit: number): Promise<GeneratorResult> {
312
+ throw new Error(
313
+ 'EloDistanceFilter is a filter and should not be used as a generator. ' +
314
+ 'Use Pipeline with a generator and this filter via transform().'
315
+ );
316
+ }
317
+ }
@@ -3,7 +3,7 @@ import type { UserDBInterface } from '../../interfaces/userDB';
3
3
  import { ContentNavigator } from '../index';
4
4
  import type { WeightedCard } from '../index';
5
5
  import type { ContentNavigationStrategyData } from '../../types/contentNavigationStrategy';
6
- import type { CardFilter, FilterContext } from './types';
6
+ import type { CardFilter, FilterContext, FilterKind } from './types';
7
7
  import type { GeneratorResult } from '../generators/types';
8
8
  import { toCourseElo } from '@vue-skuilder/common';
9
9
  import { logger } from '../../../util/logger';
@@ -78,6 +78,10 @@ export default class HierarchyDefinitionNavigator extends ContentNavigator imple
78
78
  /** Human-readable name for CardFilter interface */
79
79
  name: string;
80
80
 
81
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
82
+ static readonly kind: FilterKind = 'gate';
83
+ readonly kind = HierarchyDefinitionNavigator.kind;
84
+
81
85
  constructor(
82
86
  user: UserDBInterface,
83
87
  course: CourseDBInterface,
@@ -1,8 +1,8 @@
1
1
  // Filter types and interfaces
2
- export type { CardFilter, FilterContext, CardFilterFactory } from './types';
2
+ export type { CardFilter, FilterContext, CardFilterFactory, FilterKind } from './types';
3
3
 
4
4
  // Filter implementations
5
- export { createEloDistanceFilter } from './eloDistance';
5
+ export { createEloDistanceFilter, default as EloDistanceFilter } from './eloDistance';
6
6
  export type { EloDistanceConfig } from './eloDistance';
7
7
 
8
8
  export { default as UserTagPreferenceFilter } from './userTagPreference';
@@ -3,7 +3,7 @@ import type { UserDBInterface } from '../../interfaces/userDB';
3
3
  import { ContentNavigator } from '../index';
4
4
  import type { WeightedCard } from '../index';
5
5
  import type { ContentNavigationStrategyData } from '../../types/contentNavigationStrategy';
6
- import type { CardFilter, FilterContext } from './types';
6
+ import type { CardFilter, FilterContext, FilterKind } from './types';
7
7
  import type { GeneratorResult } from '../generators/types';
8
8
  import { toCourseElo } from '@vue-skuilder/common';
9
9
 
@@ -83,6 +83,10 @@ export default class InterferenceMitigatorNavigator extends ContentNavigator imp
83
83
  /** Human-readable name for CardFilter interface */
84
84
  name: string;
85
85
 
86
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
87
+ static readonly kind: FilterKind = 'signal';
88
+ readonly kind = InterferenceMitigatorNavigator.kind;
89
+
86
90
  /** Precomputed map: tag -> set of { partner, decay } it interferes with */
87
91
  private interferenceMap: Map<string, Array<{ partner: string; decay: number }>>;
88
92
 
@@ -3,7 +3,7 @@ import type { UserDBInterface } from '../../interfaces/userDB';
3
3
  import { ContentNavigator } from '../index';
4
4
  import type { WeightedCard } from '../index';
5
5
  import type { ContentNavigationStrategyData } from '../../types/contentNavigationStrategy';
6
- import type { CardFilter, FilterContext } from './types';
6
+ import type { CardFilter, FilterContext, FilterKind } from './types';
7
7
  import type { GeneratorResult } from '../generators/types';
8
8
 
9
9
  /**
@@ -88,6 +88,10 @@ export default class RelativePriorityNavigator extends ContentNavigator implemen
88
88
  /** Human-readable name for CardFilter interface */
89
89
  name: string;
90
90
 
91
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
92
+ static readonly kind: FilterKind = 'signal';
93
+ readonly kind = RelativePriorityNavigator.kind;
94
+
91
95
  constructor(
92
96
  user: UserDBInterface,
93
97
  course: CourseDBInterface,