@vue-skuilder/db 0.2.35 → 0.2.36

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 (258) hide show
  1. package/CLAUDE.md +15 -4
  2. package/build.entries.mjs +12 -0
  3. package/dist/_virtual/_rolldown/runtime.mjs +8 -0
  4. package/dist/{contentSource-BteiDpxH.d.ts → contentSource-D_E7JaxR.d.ts} +1 -1
  5. package/dist/core/UserDBDebugger.mjs +285 -0
  6. package/dist/core/UserDBDebugger.mjs.map +1 -0
  7. package/dist/core/bulkImport/cardProcessor.mjs +106 -0
  8. package/dist/core/bulkImport/cardProcessor.mjs.map +1 -0
  9. package/dist/core/{index.js → index.cjs} +6438 -7784
  10. package/dist/core/index.cjs.map +1 -0
  11. package/dist/core/index.d.ts +5 -5
  12. package/dist/core/index.mjs +20 -11368
  13. package/dist/core/interfaces/contentSource.mjs +20 -0
  14. package/dist/core/interfaces/contentSource.mjs.map +1 -0
  15. package/dist/core/navigators/Pipeline.mjs +723 -0
  16. package/dist/core/navigators/Pipeline.mjs.map +1 -0
  17. package/dist/core/navigators/PipelineAssembler.mjs +86 -0
  18. package/dist/core/navigators/PipelineAssembler.mjs.map +1 -0
  19. package/dist/core/navigators/PipelineDebugger.mjs +771 -0
  20. package/dist/core/navigators/PipelineDebugger.mjs.map +1 -0
  21. package/dist/core/navigators/SrsDebugger.mjs +34 -0
  22. package/dist/core/navigators/SrsDebugger.mjs.map +1 -0
  23. package/dist/core/navigators/StrategyPressureDebugger.mjs +19 -0
  24. package/dist/core/navigators/StrategyPressureDebugger.mjs.map +1 -0
  25. package/dist/core/navigators/defaults.mjs +96 -0
  26. package/dist/core/navigators/defaults.mjs.map +1 -0
  27. package/dist/core/navigators/diversityRerank.mjs +85 -0
  28. package/dist/core/navigators/diversityRerank.mjs.map +1 -0
  29. package/dist/core/navigators/filters/WeightedFilter.mjs +81 -0
  30. package/dist/core/navigators/filters/WeightedFilter.mjs.map +1 -0
  31. package/dist/core/navigators/filters/eloDistance.mjs +244 -0
  32. package/dist/core/navigators/filters/eloDistance.mjs.map +1 -0
  33. package/dist/core/navigators/filters/hierarchyDefinition.mjs +235 -0
  34. package/dist/core/navigators/filters/hierarchyDefinition.mjs.map +1 -0
  35. package/dist/core/navigators/filters/interferenceMitigator.mjs +201 -0
  36. package/dist/core/navigators/filters/interferenceMitigator.mjs.map +1 -0
  37. package/dist/core/navigators/filters/relativePriority.mjs +135 -0
  38. package/dist/core/navigators/filters/relativePriority.mjs.map +1 -0
  39. package/dist/core/navigators/filters/userTagPreference.mjs +101 -0
  40. package/dist/core/navigators/filters/userTagPreference.mjs.map +1 -0
  41. package/dist/core/navigators/generators/CompositeGenerator.mjs +203 -0
  42. package/dist/core/navigators/generators/CompositeGenerator.mjs.map +1 -0
  43. package/dist/core/navigators/generators/elo.mjs +77 -0
  44. package/dist/core/navigators/generators/elo.mjs.map +1 -0
  45. package/dist/core/navigators/generators/prescribed.mjs +676 -0
  46. package/dist/core/navigators/generators/prescribed.mjs.map +1 -0
  47. package/dist/core/navigators/generators/srs.mjs +158 -0
  48. package/dist/core/navigators/generators/srs.mjs.map +1 -0
  49. package/dist/core/navigators/index.mjs +345 -0
  50. package/dist/core/navigators/index.mjs.map +1 -0
  51. package/dist/core/navigators/pipelinePlan.mjs +109 -0
  52. package/dist/core/navigators/pipelinePlan.mjs.map +1 -0
  53. package/dist/core/navigators/regulators.mjs +128 -0
  54. package/dist/core/navigators/regulators.mjs.map +1 -0
  55. package/dist/core/orchestration/gradient.mjs +101 -0
  56. package/dist/core/orchestration/gradient.mjs.map +1 -0
  57. package/dist/core/orchestration/index.mjs +115 -0
  58. package/dist/core/orchestration/index.mjs.map +1 -0
  59. package/dist/core/orchestration/learning.mjs +140 -0
  60. package/dist/core/orchestration/learning.mjs.map +1 -0
  61. package/dist/core/orchestration/recording.mjs +64 -0
  62. package/dist/core/orchestration/recording.mjs.map +1 -0
  63. package/dist/core/orchestration/signal.mjs +40 -0
  64. package/dist/core/orchestration/signal.mjs.map +1 -0
  65. package/dist/core/types/contentNavigationStrategy.mjs +10 -0
  66. package/dist/core/types/contentNavigationStrategy.mjs.map +1 -0
  67. package/dist/core/types/hydration.mjs +13 -0
  68. package/dist/core/types/hydration.mjs.map +1 -0
  69. package/dist/core/types/strategyState.mjs +16 -0
  70. package/dist/core/types/strategyState.mjs.map +1 -0
  71. package/dist/core/types/studySession.mjs +14 -0
  72. package/dist/core/types/studySession.mjs.map +1 -0
  73. package/dist/core/types/types-legacy.mjs +44 -0
  74. package/dist/core/types/types-legacy.mjs.map +1 -0
  75. package/dist/core/util/index.mjs +31 -0
  76. package/dist/core/util/index.mjs.map +1 -0
  77. package/dist/core/versionStamps.mjs +46 -0
  78. package/dist/core/versionStamps.mjs.map +1 -0
  79. package/dist/courseConfigRegistration.mjs +306 -0
  80. package/dist/courseConfigRegistration.mjs.map +1 -0
  81. package/dist/{dataLayerProvider-C_QWzHf-.d.ts → dataLayerProvider-BDshhSp_.d.ts} +1 -1
  82. package/dist/diagnostics/dataset.mjs +118 -0
  83. package/dist/diagnostics/dataset.mjs.map +1 -0
  84. package/dist/diagnostics/derive.mjs +318 -0
  85. package/dist/diagnostics/derive.mjs.map +1 -0
  86. package/dist/diagnostics/{index.js → index.cjs} +1 -1
  87. package/dist/diagnostics/index.d.ts +3 -3
  88. package/dist/diagnostics/index.mjs +7 -1042
  89. package/dist/diagnostics/loader.mjs +151 -0
  90. package/dist/diagnostics/loader.mjs.map +1 -0
  91. package/dist/diagnostics/pipeline.mjs +161 -0
  92. package/dist/diagnostics/pipeline.mjs.map +1 -0
  93. package/dist/diagnostics/tagElo.mjs +177 -0
  94. package/dist/diagnostics/tagElo.mjs.map +1 -0
  95. package/dist/diagnostics/text.mjs +174 -0
  96. package/dist/diagnostics/text.mjs.map +1 -0
  97. package/dist/factory.mjs +70 -0
  98. package/dist/factory.mjs.map +1 -0
  99. package/dist/impl/common/BaseUserDB.mjs +1103 -0
  100. package/dist/impl/common/BaseUserDB.mjs.map +1 -0
  101. package/dist/impl/common/userDBHelpers.mjs +49 -0
  102. package/dist/impl/common/userDBHelpers.mjs.map +1 -0
  103. package/dist/impl/common/userDBKeys.mjs +45 -0
  104. package/dist/impl/common/userDBKeys.mjs.map +1 -0
  105. package/dist/impl/couch/CouchDBSyncStrategy.mjs +272 -0
  106. package/dist/impl/couch/CouchDBSyncStrategy.mjs.map +1 -0
  107. package/dist/impl/couch/CourseSyncService.mjs +242 -0
  108. package/dist/impl/couch/CourseSyncService.mjs.map +1 -0
  109. package/dist/impl/couch/PouchDataLayerProvider.mjs +74 -0
  110. package/dist/impl/couch/PouchDataLayerProvider.mjs.map +1 -0
  111. package/dist/impl/couch/adminDB.mjs +61 -0
  112. package/dist/impl/couch/adminDB.mjs.map +1 -0
  113. package/dist/impl/couch/auth.mjs +33 -0
  114. package/dist/impl/couch/auth.mjs.map +1 -0
  115. package/dist/impl/couch/classroomDB.mjs +227 -0
  116. package/dist/impl/couch/classroomDB.mjs.map +1 -0
  117. package/dist/impl/couch/clientCache.mjs +15 -0
  118. package/dist/impl/couch/clientCache.mjs.map +1 -0
  119. package/dist/impl/couch/courseAPI.mjs +183 -0
  120. package/dist/impl/couch/courseAPI.mjs.map +1 -0
  121. package/dist/impl/couch/courseDB.mjs +729 -0
  122. package/dist/impl/couch/courseDB.mjs.map +1 -0
  123. package/dist/impl/couch/courseLookupDB.mjs +94 -0
  124. package/dist/impl/couch/courseLookupDB.mjs.map +1 -0
  125. package/dist/impl/couch/{index.js → index.cjs} +6911 -10367
  126. package/dist/impl/couch/index.cjs.map +1 -0
  127. package/dist/impl/couch/index.d.ts +12 -5
  128. package/dist/impl/couch/index.mjs +134 -12146
  129. package/dist/impl/couch/index.mjs.map +1 -1
  130. package/dist/impl/couch/pouchdb-setup.mjs +15 -0
  131. package/dist/impl/couch/pouchdb-setup.mjs.map +1 -0
  132. package/dist/impl/couch/updateQueue.mjs +101 -0
  133. package/dist/impl/couch/updateQueue.mjs.map +1 -0
  134. package/dist/impl/couch/user-course-relDB.mjs +55 -0
  135. package/dist/impl/couch/user-course-relDB.mjs.map +1 -0
  136. package/dist/impl/static/NoOpSyncStrategy.mjs +49 -0
  137. package/dist/impl/static/NoOpSyncStrategy.mjs.map +1 -0
  138. package/dist/impl/static/StaticDataLayerProvider.mjs +94 -0
  139. package/dist/impl/static/StaticDataLayerProvider.mjs.map +1 -0
  140. package/dist/impl/static/StaticDataUnpacker.mjs +311 -0
  141. package/dist/impl/static/StaticDataUnpacker.mjs.map +1 -0
  142. package/dist/impl/static/courseDB.mjs +368 -0
  143. package/dist/impl/static/courseDB.mjs.map +1 -0
  144. package/dist/impl/static/coursesDB.mjs +38 -0
  145. package/dist/impl/static/coursesDB.mjs.map +1 -0
  146. package/dist/impl/static/{index.js → index.cjs} +2461 -5992
  147. package/dist/impl/static/index.cjs.map +1 -0
  148. package/dist/impl/static/index.d.ts +4 -4
  149. package/dist/impl/static/index.mjs +6 -10741
  150. package/dist/{index-C745YB_6.d.ts → index-BLDpFYG3.d.ts} +1 -1
  151. package/dist/{index.js → index.cjs} +14070 -14239
  152. package/dist/index.cjs.map +1 -0
  153. package/dist/index.d.ts +12 -23
  154. package/dist/index.mjs +38 -16937
  155. package/dist/pouch/{index.js → index.cjs} +5 -1
  156. package/dist/pouch/index.cjs.map +1 -0
  157. package/dist/pouch/index.mjs +2 -19
  158. package/dist/study/ItemQueue.mjs +95 -0
  159. package/dist/study/ItemQueue.mjs.map +1 -0
  160. package/dist/study/MixerDebugger.mjs +303 -0
  161. package/dist/study/MixerDebugger.mjs.map +1 -0
  162. package/dist/study/SessionController.mjs +1187 -0
  163. package/dist/study/SessionController.mjs.map +1 -0
  164. package/dist/study/SessionDebugger.mjs +271 -0
  165. package/dist/study/SessionDebugger.mjs.map +1 -0
  166. package/dist/study/SessionOverlay.mjs +407 -0
  167. package/dist/study/SessionOverlay.mjs.map +1 -0
  168. package/dist/study/SourceMixer.mjs +45 -0
  169. package/dist/study/SourceMixer.mjs.map +1 -0
  170. package/dist/study/SpacedRepetition.mjs +108 -0
  171. package/dist/study/SpacedRepetition.mjs.map +1 -0
  172. package/dist/study/TagFilteredContentSource.mjs +136 -0
  173. package/dist/study/TagFilteredContentSource.mjs.map +1 -0
  174. package/dist/study/services/CardHydrationService.mjs +172 -0
  175. package/dist/study/services/CardHydrationService.mjs.map +1 -0
  176. package/dist/study/services/EloService.mjs +217 -0
  177. package/dist/study/services/EloService.mjs.map +1 -0
  178. package/dist/study/services/ResponseProcessor.mjs +190 -0
  179. package/dist/study/services/ResponseProcessor.mjs.map +1 -0
  180. package/dist/study/services/SrsService.mjs +49 -0
  181. package/dist/study/services/SrsService.mjs.map +1 -0
  182. package/dist/study/services/tagRecent.mjs +65 -0
  183. package/dist/study/services/tagRecent.mjs.map +1 -0
  184. package/dist/{types-DF0JuPbs.d.ts → types-DChCz22D.d.ts} +1 -1
  185. package/dist/{types-legacy-DdVjg81H.d.cts → types-legacy-fT5Y1Wuy.d.ts} +1 -1
  186. package/dist/userDBKeys-ne1g4Xuq.d.ts +16 -0
  187. package/dist/util/Loggable.mjs +14 -0
  188. package/dist/util/Loggable.mjs.map +1 -0
  189. package/dist/util/dataDirectory.mjs +47 -0
  190. package/dist/util/dataDirectory.mjs.map +1 -0
  191. package/dist/util/logger.mjs +86 -0
  192. package/dist/util/logger.mjs.map +1 -0
  193. package/dist/util/migrator/FileSystemAdapter.mjs +18 -0
  194. package/dist/util/migrator/FileSystemAdapter.mjs.map +1 -0
  195. package/dist/util/migrator/StaticToCouchDBMigrator.mjs +428 -0
  196. package/dist/util/migrator/StaticToCouchDBMigrator.mjs.map +1 -0
  197. package/dist/util/migrator/types.mjs +11 -0
  198. package/dist/util/migrator/types.mjs.map +1 -0
  199. package/dist/util/migrator/validation.mjs +334 -0
  200. package/dist/util/migrator/validation.mjs.map +1 -0
  201. package/dist/util/packer/CouchDBToStaticPacker.mjs +438 -0
  202. package/dist/util/packer/CouchDBToStaticPacker.mjs.map +1 -0
  203. package/dist/util/packer/{index.js → index.cjs} +73 -9
  204. package/dist/util/packer/index.cjs.map +1 -0
  205. package/dist/util/packer/index.d.ts +3 -3
  206. package/dist/util/packer/index.mjs +2 -537
  207. package/eslint.config.mjs +9 -1
  208. package/package.json +25 -13
  209. package/rolldown.config.mjs +44 -0
  210. package/src/core/UserDBDebugger.ts +47 -46
  211. package/src/core/navigators/Pipeline.ts +10 -10
  212. package/src/core/navigators/PipelineDebugger.ts +55 -55
  213. package/src/core/navigators/filters/eloDistance.ts +1 -1
  214. package/src/core/navigators/generators/elo.ts +5 -1
  215. package/src/core/navigators/index.ts +9 -3
  216. package/src/factory.ts +10 -1
  217. package/src/impl/common/BaseUserDB.ts +1 -3
  218. package/src/impl/common/index.ts +2 -0
  219. package/src/impl/common/userDBHelpers.ts +4 -58
  220. package/src/impl/common/userDBKeys.ts +64 -0
  221. package/src/impl/couch/courseDB.ts +15 -3
  222. package/src/impl/couch/index.ts +2 -18
  223. package/src/impl/couch/pouchdb-setup.ts +8 -0
  224. package/src/index.ts +1 -1
  225. package/src/study/MixerDebugger.ts +46 -46
  226. package/src/study/SessionDebugger.ts +20 -20
  227. package/src/study/SessionOverlay.ts +4 -4
  228. package/src/util/logger.ts +112 -13
  229. package/tests/core/navigators/eloGenerator.test.ts +36 -0
  230. package/tsup.config.ts +24 -21
  231. package/dist/SyncStrategy-BXliog1m.d.cts +0 -116
  232. package/dist/classroomDB-DLTtLZct.d.cts +0 -86
  233. package/dist/contentSource-FQZcZopC.d.cts +0 -2007
  234. package/dist/core/index.d.cts +0 -521
  235. package/dist/core/index.js.map +0 -1
  236. package/dist/core/index.mjs.map +0 -1
  237. package/dist/dataLayerProvider-3y21KtF-.d.cts +0 -61
  238. package/dist/diagnostics/index.d.cts +0 -561
  239. package/dist/diagnostics/index.mjs.map +0 -1
  240. package/dist/impl/couch/index.d.cts +0 -620
  241. package/dist/impl/couch/index.js.map +0 -1
  242. package/dist/impl/static/index.d.cts +0 -232
  243. package/dist/impl/static/index.js.map +0 -1
  244. package/dist/impl/static/index.mjs.map +0 -1
  245. package/dist/index-BIum9Ue2.d.cts +0 -137
  246. package/dist/index.d.cts +0 -1663
  247. package/dist/index.js.map +0 -1
  248. package/dist/index.mjs.map +0 -1
  249. package/dist/pouch/index.d.cts +0 -1
  250. package/dist/pouch/index.js.map +0 -1
  251. package/dist/pouch/index.mjs.map +0 -1
  252. package/dist/types-BcWVH4ww.d.cts +0 -58
  253. package/dist/types-legacy-DdVjg81H.d.ts +0 -168
  254. package/dist/util/packer/index.d.cts +0 -5
  255. package/dist/util/packer/index.js.map +0 -1
  256. package/dist/util/packer/index.mjs.map +0 -1
  257. package/src/study/getCardDataShape.ts +0 -34
  258. /package/dist/diagnostics/{index.js.map → index.cjs.map} +0 -0
@@ -0,0 +1,244 @@
1
+ import "../../../_virtual/_rolldown/runtime.mjs";
2
+ import { logger } from "../../../util/logger.mjs";
3
+ import { ContentNavigator } from "../index.mjs";
4
+ import { COUNT_ONLY_SCORE, isCountOnlyTag } from "@vue-skuilder/common";
5
+ //#region src/core/navigators/filters/eloDistance.ts
6
+ /**
7
+ * The default curve. The default strategy doc carries it as its config, so
8
+ * the admin pipeline view shows what runs.
9
+ */
10
+ const DEFAULT_ELO_DISTANCE_CONFIG = {
11
+ halfLife: 300,
12
+ minMultiplier: .05,
13
+ maxMultiplier: 1,
14
+ tagAware: false,
15
+ minTagCount: 3
16
+ };
17
+ /**
18
+ * Graded responses at which a tag's gap carries half its full weight. Thin
19
+ * tag evidence leans on global ELO; well-practised tags dominate.
20
+ */
21
+ const TAG_CONFIDENCE_HALF = 10;
22
+ /** Fallback card ELO when a card has none recorded. */
23
+ const DEFAULT_CARD_ELO = 1e3;
24
+ function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
25
+ const normalizedDistance = distance / halfLife;
26
+ const decay = Math.exp(-(normalizedDistance * normalizedDistance));
27
+ return minMultiplier + (maxMultiplier - minMultiplier) * decay;
28
+ }
29
+ function resolveConfig(config) {
30
+ return {
31
+ ...DEFAULT_ELO_DISTANCE_CONFIG,
32
+ ...config
33
+ };
34
+ }
35
+ const MULTI_DIM_ELO_KEY = "skuilder:multiDimElo";
36
+ let multiDimElo = readMultiDimElo();
37
+ function readMultiDimElo() {
38
+ try {
39
+ return typeof localStorage !== "undefined" && localStorage.getItem(MULTI_DIM_ELO_KEY) === "true";
40
+ } catch {
41
+ return false;
42
+ }
43
+ }
44
+ /**
45
+ * Mount the toggle on window.skuilder.multiDimElo.
46
+ */
47
+ function mountMultiDimEloToggle() {
48
+ if (typeof window === "undefined") return;
49
+ const win = window;
50
+ win.skuilder = win.skuilder || {};
51
+ Object.defineProperty(win.skuilder, "multiDimElo", {
52
+ configurable: true,
53
+ enumerable: true,
54
+ get: () => multiDimElo,
55
+ set: (on) => {
56
+ multiDimElo = on === true;
57
+ try {
58
+ if (multiDimElo) localStorage.setItem(MULTI_DIM_ELO_KEY, "true");
59
+ else localStorage.removeItem(MULTI_DIM_ELO_KEY);
60
+ } catch (e) {
61
+ logger.warn(`[EloDistance] multiDimElo not persisted (localStorage unavailable): ${e}`);
62
+ }
63
+ logger.print(`[EloDistance] multiDimElo ${multiDimElo ? "on: tag-aware" : "off: per strategy config"} ELO distance from the next replan`);
64
+ }
65
+ });
66
+ }
67
+ mountMultiDimEloToggle();
68
+ /**
69
+ * The card's difficulty for this learner, in ELO points (card − learner),
70
+ * read on the tags they share.
71
+ *
72
+ * - Shared tags: the card's tags on which the learner has a real rating
73
+ * (not a bookkeeping role, nor the count-only sentinel) resting on at least
74
+ * `minTagCount` graded responses. A card with no rating of its own on a tag
75
+ * uses its global, as the ELO update does when it first grades that tag.
76
+ * - Each tag's gap is weighted by the learner's evidence on it,
77
+ * n / (n + TAG_CONFIDENCE_HALF).
78
+ * - The weighted mean of the tag gaps is blended with the global gap by the
79
+ * total evidence W: λ = W / (W + 1). One thin tag barely moves it; several
80
+ * practised tags dominate it.
81
+ *
82
+ * OPEN (draft, 2026-10-01). Shipped on by default in 0.2.29 by accident (it
83
+ * rode along in the version-bump commit); off by default since, and live only
84
+ * behind the toggle. On one LP learner's 09-30 dump the effect was modest: every touched card shared a rated tag
85
+ * (median 4); mean multiplier ×0.70 → ×0.75 over 352 touched cards, ×0.84 →
86
+ * ×0.88 over 42 due reviews. The biggest movers were old who-said-that cards:
87
+ * ~400 below the learner globally, ~280 below on their own skills.
88
+ *
89
+ * 1. Compensatory or conjunctive. This averages: a weak skill is offset by
90
+ * strong ones. For spelling a word, which needs every grapheme, the hardest
91
+ * shared skill arguably sets the difficulty: take the largest gap instead.
92
+ * The main design question.
93
+ * 2. Which tags count. Broad tags (`concept:match:simple`, `ui:*`) sit on most
94
+ * cards and act like a second global rating. The framework may want the
95
+ * course to say which tags are skills (cf. LP's diagnostics interpreter
96
+ * `isSkillTag`), e.g. as tag patterns in the strategy config.
97
+ * The admin ELO viewer (in progress, 2026-10) answers the same question for
98
+ * display with its own tag batches (role × namespace). Before tag-aware goes
99
+ * on by default, make that one predicate:
100
+ * - a serializable selector (roles, prefix patterns), beside `tagRoles.ts`
101
+ * in common, so a strategy doc can carry it;
102
+ * - an `EloDistanceConfig` field for it, read by `tagAwareGap`;
103
+ * - `tagAwareGap` moved to a pure module (this file imports `core`, which
104
+ * the diagnostics entry can't), so the viewer can show what the filter
105
+ * would compute;
106
+ * - the viewer's default batch read from the course's eloDistance config.
107
+ * 3. New cards matter most, and that dump couldn't show them. An unseen
108
+ * card's tag ratings fall back to its global, so for new cards this reads
109
+ * "card global vs the learner's rating on that skill". Measuring it needs a
110
+ * `--course all` dump.
111
+ * 4. Cost. Tag-aware fetches full ratings for every candidate (~500 card docs
112
+ * per run); global-only fetches only reviews'.
113
+ * 5. Retrieval stays global. The ELO generator's window is the cards nearest
114
+ * the learner's global ELO, so a card that's well matched on its skills but
115
+ * far off globally may never be retrieved.
116
+ * 6. Target. Distance 0 means ~50% expected success. Early learners may do
117
+ * better aiming higher: a shift of the curve's centre, independent of this.
118
+ */
119
+ function tagAwareGap(cardTags, cardElo, userElo, minTagCount) {
120
+ const globalGap = cardElo.global.score - userElo.global.score;
121
+ const tags = [];
122
+ for (const tag of cardTags) {
123
+ const user = userElo.tags[tag];
124
+ if (isCountOnlyTag(tag) || !user || user.score === COUNT_ONLY_SCORE || user.count < minTagCount) continue;
125
+ const card = cardElo.tags[tag]?.score ?? cardElo.global.score;
126
+ tags.push({
127
+ tag,
128
+ gap: card - user.score,
129
+ weight: user.count / (user.count + TAG_CONFIDENCE_HALF)
130
+ });
131
+ }
132
+ if (tags.length === 0) return {
133
+ gap: globalGap,
134
+ globalGap,
135
+ tags
136
+ };
137
+ const total = tags.reduce((w, t) => w + t.weight, 0);
138
+ const tagGap = tags.reduce((g, t) => g + t.weight * t.gap, 0) / total;
139
+ const lambda = total / (total + 1);
140
+ return {
141
+ gap: lambda * tagGap + (1 - lambda) * globalGap,
142
+ globalGap,
143
+ tags
144
+ };
145
+ }
146
+ function tagReason(tags, globalGap) {
147
+ 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(", ");
148
+ const more = tags.length > 3 ? `, +${tags.length - 3} more` : "";
149
+ return ` on ${tags.length} shared tag(s) [${shown}${more}] (global ${globalGap >= 0 ? "+" : ""}${Math.round(globalGap)})`;
150
+ }
151
+ async function applyEloDistance(cards, context, config, source) {
152
+ const { course, userElo, userCourseElo } = context;
153
+ const { halfLife, minMultiplier, maxMultiplier } = config;
154
+ const tagAware = (config.tagAware || multiDimElo) && userCourseElo !== void 0;
155
+ const missing = cards.filter((c) => tagAware || c.cardElo === void 0).map((c) => c.cardId);
156
+ const fetched = /* @__PURE__ */ new Map();
157
+ if (missing.length > 0) {
158
+ const elos = await course.getCardEloData(missing);
159
+ missing.forEach((id, i) => {
160
+ if (elos[i]) fetched.set(id, elos[i]);
161
+ });
162
+ }
163
+ return cards.map((card) => {
164
+ const full = fetched.get(card.cardId);
165
+ const cardElo = full?.global?.score ?? card.cardElo ?? DEFAULT_CARD_ELO;
166
+ let distance = Math.abs(cardElo - userElo);
167
+ let how = "";
168
+ if (tagAware) {
169
+ const t = full ? tagAwareGap(card.tags ?? [], full, userCourseElo, config.minTagCount) : void 0;
170
+ if (t) distance = Math.abs(t.gap);
171
+ how = t?.tags.length ? `, tag-aware${tagReason(t.tags, t.globalGap)}` : ", tag-aware: global (no shared tags)";
172
+ }
173
+ const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
174
+ const newScore = card.score * multiplier;
175
+ const action = multiplier < maxMultiplier - .01 ? "penalized" : "passed";
176
+ return {
177
+ ...card,
178
+ cardElo,
179
+ score: newScore,
180
+ provenance: [...card.provenance, {
181
+ strategy: "eloDistance",
182
+ strategyName: source.name,
183
+ strategyId: source.strategyId,
184
+ action,
185
+ score: newScore,
186
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)})${how} → ${multiplier.toFixed(2)}x`
187
+ }]
188
+ };
189
+ });
190
+ }
191
+ /**
192
+ * Create an ELO distance filter outside the strategy-doc path.
193
+ *
194
+ * @param config - Optional configuration for the curve
195
+ */
196
+ function createEloDistanceFilter(config) {
197
+ const resolved = resolveConfig(config);
198
+ const source = {
199
+ name: "ELO Distance Filter",
200
+ strategyId: "ELO_DISTANCE_FILTER"
201
+ };
202
+ return {
203
+ name: source.name,
204
+ kind: "signal",
205
+ liveOnly: true,
206
+ transform: (cards, context) => applyEloDistance(cards, context, resolved, source)
207
+ };
208
+ }
209
+ /**
210
+ * The ELO distance filter as a strategy-doc navigator (`implementingClass:
211
+ * 'eloDistance'`, serializedData: an EloDistanceConfig as JSON, or empty).
212
+ */
213
+ var EloDistanceFilter = class EloDistanceFilter extends ContentNavigator {
214
+ name;
215
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
216
+ static kind = "signal";
217
+ kind = EloDistanceFilter.kind;
218
+ liveOnly = true;
219
+ config;
220
+ constructor(user, course, strategyData) {
221
+ super(user, course, strategyData);
222
+ this.name = strategyData.name || "ELO Distance";
223
+ let parsed;
224
+ try {
225
+ parsed = strategyData.serializedData ? JSON.parse(strategyData.serializedData) : void 0;
226
+ } catch {
227
+ parsed = void 0;
228
+ }
229
+ this.config = resolveConfig(parsed);
230
+ }
231
+ transform(cards, context) {
232
+ return applyEloDistance(cards, context, this.config, {
233
+ name: this.name,
234
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-eloDistance-default"
235
+ });
236
+ }
237
+ async getWeightedCards(_limit) {
238
+ throw new Error("EloDistanceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().");
239
+ }
240
+ };
241
+ //#endregion
242
+ export { DEFAULT_ELO_DISTANCE_CONFIG, createEloDistanceFilter, EloDistanceFilter as default, mountMultiDimEloToggle, tagAwareGap };
243
+
244
+ //# sourceMappingURL=eloDistance.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"eloDistance.mjs","names":[],"sources":["../../../../src/core/navigators/filters/eloDistance.ts"],"sourcesContent":["import type { CourseDBInterface } from '../../interfaces/courseDB';\nimport type { UserDBInterface } from '../../interfaces/userDB';\nimport type { ContentNavigationStrategyData } from '../../types/contentNavigationStrategy';\nimport { ContentNavigator } from '../index';\nimport type { WeightedCard } from '../index';\nimport type { GeneratorResult } from '../generators/types';\nimport type { CardFilter, FilterContext, FilterKind } from './types';\nimport { COUNT_ONLY_SCORE, isCountOnlyTag, type CourseElo } from '@vue-skuilder/common';\nimport { logger } from '../../../util/logger';\n\n// ============================================================================\n// ELO DISTANCE FILTER\n// ============================================================================\n//\n// Scales every candidate by how close its ELO is to the learner's, on a smooth\n// Gaussian (no discontinuities, never zero).\n//\n// The one place ELO distance counts. Generators retrieve (the ELO generator\n// pulls a window of cards near the learner's ELO) and score only on what's\n// specific to their source; a signal that applies to every card lives in one\n// heap-wide filter, so new cards and reviews are weighed on the same terms:\n// - reviews the learner has moved beyond fade, and may never surface over\n// higher-priority work;\n// - new cards far from the learner's level rank low (this used to live in the\n// ELO generator's own score, which double-counted alongside this filter).\n//\n// Tag-aware (opt-in, experimental): a card's difficulty for this learner is\n// read on the skills they share, not only on global ELO. Card and learner keep\n// paired ratings per tag (each graded response adjusts both), so a tag's gap\n// (card − learner) is as meaningful as the global one, and often more: a card\n// can sit at the learner's global level while testing their weakest skill.\n// See tagAwareGap for the combination. Global distance is the default; a course\n// opts in with `tagAware`, a browser with `window.skuilder.multiDimElo = true`\n// (see the toggle below), for side-by-side testing.\n//\n// A `signal`, not a gate: it expresses preference, not readiness. `liveOnly`:\n// forecasts and card-space scans start every card at 1.0 without a generator,\n// and never applied ELO distance, so they skip it.\n//\n// The assembler adds this filter (as \"ELO Distance (default)\") to every\n// pipeline whose strategy docs don't declare one. A course tunes it by\n// declaring its own `eloDistance` strategy doc with an EloDistanceConfig.\n//\n// ============================================================================\n\n/**\n * Configuration for the ELO distance curve:\n * `minMultiplier + (maxMultiplier − minMultiplier) · exp(−(distance / halfLife)²)`.\n */\nexport interface EloDistanceConfig {\n /**\n * The Gaussian's scale in ELO points (despite the name, not a half-life).\n * Default 300: distance 250 → ~0.5, as the ELO generator scored new cards.\n *\n * - distance 0: maxMultiplier\n * - distance = halfLife: ~0.4 (with the default floor)\n * - distance = 2 · halfLife: ~0.07\n */\n halfLife?: number;\n\n /**\n * Floor, so far-off cards keep a nonzero score (the pipeline drops zero\n * scores before hints, and a hint must be able to lift any card). Default 0.05.\n */\n minMultiplier?: number;\n\n /** Ceiling. Usually 1.0 (no boost for close cards). Default 1.0. */\n maxMultiplier?: number;\n\n /**\n * Measure distance on the tags the card and learner share (see\n * tagAwareGap), falling back to global ELO where they share none.\n * Default false. `window.skuilder.multiDimElo` turns it on in one browser.\n */\n tagAware?: boolean;\n\n /**\n * A learner's tag rating counts once it rests on at least this many graded\n * responses. Count-only (exposure) tags never count. Default 3.\n */\n minTagCount?: number;\n}\n\n/**\n * The default curve. The default strategy doc carries it as its config, so\n * the admin pipeline view shows what runs.\n */\nexport const DEFAULT_ELO_DISTANCE_CONFIG: Required<EloDistanceConfig> = {\n halfLife: 300,\n minMultiplier: 0.05,\n maxMultiplier: 1.0,\n tagAware: false,\n minTagCount: 3,\n};\n\n/**\n * Graded responses at which a tag's gap carries half its full weight. Thin\n * tag evidence leans on global ELO; well-practised tags dominate.\n */\nconst TAG_CONFIDENCE_HALF = 10;\n\n/** Fallback card ELO when a card has none recorded. */\nconst DEFAULT_CARD_ELO = 1000;\n\nfunction computeMultiplier(\n distance: number,\n halfLife: number,\n minMultiplier: number,\n maxMultiplier: number\n): number {\n const normalizedDistance = distance / halfLife;\n const decay = Math.exp(-(normalizedDistance * normalizedDistance));\n return minMultiplier + (maxMultiplier - minMultiplier) * decay;\n}\n\nfunction resolveConfig(config?: EloDistanceConfig): Required<EloDistanceConfig> {\n return { ...DEFAULT_ELO_DISTANCE_CONFIG, ...config };\n}\n\n// ----------------------------------------------------------------------------\n// Live toggle: window.skuilder.multiDimElo\n// ----------------------------------------------------------------------------\n//\n// `window.skuilder.multiDimElo = true` turns tag-aware distance on in this\n// browser, whatever the strategy config says; `false` returns it to the\n// config. Read on every run, so it takes effect at the next replan. Kept in\n// localStorage so it survives reloads across a testing stretch. Runs it shapes\n// say so in every card's ELO distance reason (\"tag-aware\").\n\nconst MULTI_DIM_ELO_KEY = 'skuilder:multiDimElo';\n\nlet multiDimElo = readMultiDimElo();\n\nfunction readMultiDimElo(): boolean {\n try {\n return typeof localStorage !== 'undefined' && localStorage.getItem(MULTI_DIM_ELO_KEY) === 'true';\n } catch {\n return false;\n }\n}\n\n/**\n * Mount the toggle on window.skuilder.multiDimElo.\n */\nexport function mountMultiDimEloToggle(): void {\n if (typeof window === 'undefined') return;\n\n const win = window as any;\n win.skuilder = win.skuilder || {};\n Object.defineProperty(win.skuilder, 'multiDimElo', {\n configurable: true,\n enumerable: true,\n get: () => multiDimElo,\n set: (on: unknown) => {\n multiDimElo = on === true;\n try {\n if (multiDimElo) localStorage.setItem(MULTI_DIM_ELO_KEY, 'true');\n else localStorage.removeItem(MULTI_DIM_ELO_KEY);\n } catch (e) {\n logger.warn(`[EloDistance] multiDimElo not persisted (localStorage unavailable): ${e}`);\n }\n logger.print(\n `[EloDistance] multiDimElo ${multiDimElo ? 'on: tag-aware' : 'off: per strategy config'}` +\n ' ELO distance from the next replan'\n );\n },\n });\n}\n\n// Auto-mount when module is loaded\nmountMultiDimEloToggle();\n\n/** One shared tag's contribution to a card's tag-aware gap. */\ninterface TagGap {\n tag: string;\n /** Card's tag rating minus the learner's: positive = harder than their level. */\n gap: number;\n weight: number;\n}\n\n/**\n * The card's difficulty for this learner, in ELO points (card − learner),\n * read on the tags they share.\n *\n * - Shared tags: the card's tags on which the learner has a real rating\n * (not a bookkeeping role, nor the count-only sentinel) resting on at least\n * `minTagCount` graded responses. A card with no rating of its own on a tag\n * uses its global, as the ELO update does when it first grades that tag.\n * - Each tag's gap is weighted by the learner's evidence on it,\n * n / (n + TAG_CONFIDENCE_HALF).\n * - The weighted mean of the tag gaps is blended with the global gap by the\n * total evidence W: λ = W / (W + 1). One thin tag barely moves it; several\n * practised tags dominate it.\n *\n * OPEN (draft, 2026-10-01). Shipped on by default in 0.2.29 by accident (it\n * rode along in the version-bump commit); off by default since, and live only\n * behind the toggle. On one LP learner's 09-30 dump the effect was modest: every touched card shared a rated tag\n * (median 4); mean multiplier ×0.70 → ×0.75 over 352 touched cards, ×0.84 →\n * ×0.88 over 42 due reviews. The biggest movers were old who-said-that cards:\n * ~400 below the learner globally, ~280 below on their own skills.\n *\n * 1. Compensatory or conjunctive. This averages: a weak skill is offset by\n * strong ones. For spelling a word, which needs every grapheme, the hardest\n * shared skill arguably sets the difficulty: take the largest gap instead.\n * The main design question.\n * 2. Which tags count. Broad tags (`concept:match:simple`, `ui:*`) sit on most\n * cards and act like a second global rating. The framework may want the\n * course to say which tags are skills (cf. LP's diagnostics interpreter\n * `isSkillTag`), e.g. as tag patterns in the strategy config.\n * The admin ELO viewer (in progress, 2026-10) answers the same question for\n * display with its own tag batches (role × namespace). Before tag-aware goes\n * on by default, make that one predicate:\n * - a serializable selector (roles, prefix patterns), beside `tagRoles.ts`\n * in common, so a strategy doc can carry it;\n * - an `EloDistanceConfig` field for it, read by `tagAwareGap`;\n * - `tagAwareGap` moved to a pure module (this file imports `core`, which\n * the diagnostics entry can't), so the viewer can show what the filter\n * would compute;\n * - the viewer's default batch read from the course's eloDistance config.\n * 3. New cards matter most, and that dump couldn't show them. An unseen\n * card's tag ratings fall back to its global, so for new cards this reads\n * \"card global vs the learner's rating on that skill\". Measuring it needs a\n * `--course all` dump.\n * 4. Cost. Tag-aware fetches full ratings for every candidate (~500 card docs\n * per run); global-only fetches only reviews'.\n * 5. Retrieval stays global. The ELO generator's window is the cards nearest\n * the learner's global ELO, so a card that's well matched on its skills but\n * far off globally may never be retrieved.\n * 6. Target. Distance 0 means ~50% expected success. Early learners may do\n * better aiming higher: a shift of the curve's centre, independent of this.\n */\nexport function tagAwareGap(\n cardTags: readonly string[],\n cardElo: CourseElo,\n userElo: CourseElo,\n minTagCount: number\n): { gap: number; globalGap: number; tags: TagGap[] } {\n const globalGap = cardElo.global.score - userElo.global.score;\n const tags: TagGap[] = [];\n for (const tag of cardTags) {\n const user = userElo.tags[tag];\n if (isCountOnlyTag(tag) || !user || user.score === COUNT_ONLY_SCORE || user.count < minTagCount) {\n continue;\n }\n const card = cardElo.tags[tag]?.score ?? cardElo.global.score;\n tags.push({\n tag,\n gap: card - user.score,\n weight: user.count / (user.count + TAG_CONFIDENCE_HALF),\n });\n }\n if (tags.length === 0) return { gap: globalGap, globalGap, tags };\n\n const total = tags.reduce((w, t) => w + t.weight, 0);\n const tagGap = tags.reduce((g, t) => g + t.weight * t.gap, 0) / total;\n const lambda = total / (total + 1);\n return { gap: lambda * tagGap + (1 - lambda) * globalGap, globalGap, tags };\n}\n\nfunction tagReason(tags: TagGap[], globalGap: number): string {\n const shown = [...tags]\n .sort((a, b) => Math.abs(b.gap) * b.weight - Math.abs(a.gap) * a.weight)\n .slice(0, 3)\n .map((t) => `${t.tag} ${t.gap >= 0 ? '+' : ''}${Math.round(t.gap)}`)\n .join(', ');\n const more = tags.length > 3 ? `, +${tags.length - 3} more` : '';\n return ` on ${tags.length} shared tag(s) [${shown}${more}] (global ${globalGap >= 0 ? '+' : ''}${Math.round(globalGap)})`;\n}\n\nasync function applyEloDistance(\n cards: WeightedCard[],\n context: FilterContext,\n config: Required<EloDistanceConfig>,\n source: { name: string; strategyId: string }\n): Promise<WeightedCard[]> {\n const { course, userElo, userCourseElo } = context;\n const { halfLife, minMultiplier, maxMultiplier } = config;\n const tagAware = (config.tagAware || multiDimElo) && userCourseElo !== undefined;\n\n // Tag-aware needs every card's full ratings; otherwise only the ELO of cards\n // that don't carry it (reviews). One batch either way.\n const missing = cards.filter((c) => tagAware || c.cardElo === undefined).map((c) => c.cardId);\n const fetched = new Map<string, CourseElo>();\n if (missing.length > 0) {\n const elos = await course.getCardEloData(missing);\n missing.forEach((id, i) => {\n if (elos[i]) fetched.set(id, elos[i]);\n });\n }\n\n return cards.map((card) => {\n const full = fetched.get(card.cardId);\n const cardElo = full?.global?.score ?? card.cardElo ?? DEFAULT_CARD_ELO;\n\n let distance = Math.abs(cardElo - userElo);\n let how = '';\n if (tagAware) {\n const t = full ? tagAwareGap(card.tags ?? [], full, userCourseElo!, config.minTagCount) : undefined;\n if (t) distance = Math.abs(t.gap);\n how = t?.tags.length\n ? `, tag-aware${tagReason(t.tags, t.globalGap)}`\n : ', tag-aware: global (no shared tags)';\n }\n\n const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);\n const newScore = card.score * multiplier;\n const action = multiplier < maxMultiplier - 0.01 ? 'penalized' : 'passed';\n\n return {\n ...card,\n cardElo,\n score: newScore,\n provenance: [\n ...card.provenance,\n {\n strategy: 'eloDistance',\n strategyName: source.name,\n strategyId: source.strategyId,\n action,\n score: newScore,\n reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)})${how} → ${multiplier.toFixed(2)}x`,\n },\n ],\n };\n });\n}\n\n/**\n * Create an ELO distance filter outside the strategy-doc path.\n *\n * @param config - Optional configuration for the curve\n */\nexport function createEloDistanceFilter(config?: EloDistanceConfig): CardFilter {\n const resolved = resolveConfig(config);\n const source = { name: 'ELO Distance Filter', strategyId: 'ELO_DISTANCE_FILTER' };\n return {\n name: source.name,\n kind: 'signal',\n liveOnly: true,\n transform: (cards, context) => applyEloDistance(cards, context, resolved, source),\n };\n}\n\n/**\n * The ELO distance filter as a strategy-doc navigator (`implementingClass:\n * 'eloDistance'`, serializedData: an EloDistanceConfig as JSON, or empty).\n */\nexport default class EloDistanceFilter extends ContentNavigator implements CardFilter {\n name: string;\n /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */\n static readonly kind: FilterKind = 'signal';\n readonly kind = EloDistanceFilter.kind;\n readonly liveOnly = true;\n private config: Required<EloDistanceConfig>;\n\n constructor(\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n ) {\n super(user, course, strategyData);\n this.name = strategyData.name || 'ELO Distance';\n let parsed: EloDistanceConfig | undefined;\n try {\n parsed = strategyData.serializedData ? JSON.parse(strategyData.serializedData) : undefined;\n } catch {\n parsed = undefined;\n }\n this.config = resolveConfig(parsed);\n }\n\n transform(cards: WeightedCard[], context: FilterContext): Promise<WeightedCard[]> {\n return applyEloDistance(cards, context, this.config, {\n name: this.name,\n strategyId: this.strategyId || 'NAVIGATION_STRATEGY-eloDistance-default',\n });\n }\n\n async getWeightedCards(_limit: number): Promise<GeneratorResult> {\n throw new Error(\n 'EloDistanceFilter is a filter and should not be used as a generator. ' +\n 'Use Pipeline with a generator and this filter via transform().'\n );\n }\n}\n"],"mappings":";;;;;;;;;AAuFA,MAAa,8BAA2D;CACtE,UAAU;CACV,eAAe;CACf,eAAe;CACf,UAAU;CACV,aAAa;CACd;;;;;AAMD,MAA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SAAS,UAAU,OAAO;EAClF;;;;;;AAOH,IAAqB,oBAArB,MAAqB,0BAA0B,iBAAuC;CACpF;;CAEA,OAAgB,OAAmB;CACnC,OAAgB,kBAAkB;CAClC,WAAoB;CACpB;CAEA,YACE,MACA,QACA,cACA;AACA,QAAM,MAAM,QAAQ,aAAa;AACjC,OAAK,OAAO,aAAa,QAAQ;EACjC,IAAI;AACJ,MAAI;AACF,YAAS,aAAa,iBAAiB,KAAK,MAAM,aAAa,eAAe,GAAG,KAAA;UAC3E;AACN,YAAS,KAAA;;AAEX,OAAK,SAAS,cAAc,OAAO;;CAGrC,UAAU,OAAuB,SAAiD;AAChF,SAAO,iBAAiB,OAAO,SAAS,KAAK,QAAQ;GACnD,MAAM,KAAK;GACX,YAAY,KAAK,cAAc;GAChC,CAAC;;CAGJ,MAAM,iBAAiB,QAA0C;AAC/D,QAAM,IAAI,MACR,sIAED"}
@@ -0,0 +1,235 @@
1
+ import "../../../_virtual/_rolldown/runtime.mjs";
2
+ import { logger } from "../../../util/logger.mjs";
3
+ import { ContentNavigator } from "../index.mjs";
4
+ import { toCourseElo } from "@vue-skuilder/common";
5
+ //#region src/core/navigators/filters/hierarchyDefinition.ts
6
+ const DEFAULT_MIN_COUNT = 3;
7
+ /**
8
+ * A filter strategy that gates cards based on prerequisite mastery.
9
+ *
10
+ * Cards are locked until the user masters all prerequisite tags.
11
+ * Locked cards receive score * 0.05 (strong penalty, not hard filter).
12
+ *
13
+ * Mastery is determined by:
14
+ * - User's ELO for the tag exceeds threshold (or avgElo if not specified)
15
+ * - User has minimum interaction count with the tag
16
+ *
17
+ * Tags with no prerequisites are always unlocked.
18
+ *
19
+ * Implements CardFilter for use in Pipeline architecture.
20
+ * Also extends ContentNavigator for backward compatibility.
21
+ */
22
+ var HierarchyDefinitionNavigator = class HierarchyDefinitionNavigator extends ContentNavigator {
23
+ config;
24
+ /** Human-readable name for CardFilter interface */
25
+ name;
26
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
27
+ static kind = "gate";
28
+ kind = HierarchyDefinitionNavigator.kind;
29
+ constructor(user, course, strategyData) {
30
+ super(user, course, strategyData);
31
+ this.config = this.parseConfig(strategyData.serializedData);
32
+ this.name = strategyData.name || "Hierarchy Definition";
33
+ }
34
+ parseConfig(serializedData) {
35
+ try {
36
+ return { prerequisites: JSON.parse(serializedData).prerequisites || {} };
37
+ } catch {
38
+ return { prerequisites: {} };
39
+ }
40
+ }
41
+ /**
42
+ * Check if a specific prerequisite is satisfied
43
+ */
44
+ isPrerequisiteMet(prereq, userTagElo, userGlobalElo) {
45
+ if (!userTagElo) return false;
46
+ const minCount = prereq.masteryThreshold?.minCount ?? DEFAULT_MIN_COUNT;
47
+ if (userTagElo.count < minCount) return false;
48
+ if (prereq.masteryThreshold?.minElo !== void 0) return userTagElo.score >= prereq.masteryThreshold.minElo;
49
+ else if (prereq.masteryThreshold?.minCount !== void 0) return true;
50
+ else return userTagElo.score >= userGlobalElo;
51
+ }
52
+ /**
53
+ * Get the set of tags the user has mastered.
54
+ * A tag is "mastered" if it appears as a prerequisite somewhere and meets its threshold.
55
+ */
56
+ async getMasteredTags(context) {
57
+ const mastered = /* @__PURE__ */ new Set();
58
+ try {
59
+ const userElo = toCourseElo((await context.user.getCourseRegDoc(context.course.getCourseID())).elo);
60
+ for (const prereqs of Object.values(this.config.prerequisites)) for (const prereq of prereqs) {
61
+ const tagElo = userElo.tags[prereq.tag];
62
+ if (this.isPrerequisiteMet(prereq, tagElo, userElo.global.score)) mastered.add(prereq.tag);
63
+ }
64
+ } catch {}
65
+ return mastered;
66
+ }
67
+ /**
68
+ * Get the set of tags that are unlocked (prerequisites met)
69
+ */
70
+ getUnlockedTags(masteredTags) {
71
+ const unlocked = /* @__PURE__ */ new Set();
72
+ for (const [tagId, prereqs] of Object.entries(this.config.prerequisites)) if (prereqs.every((prereq) => masteredTags.has(prereq.tag))) unlocked.add(tagId);
73
+ return unlocked;
74
+ }
75
+ /**
76
+ * Check if a tag has prerequisites defined in config
77
+ */
78
+ hasPrerequisites(tagId) {
79
+ return tagId in this.config.prerequisites;
80
+ }
81
+ /**
82
+ * Check if a card is unlocked and generate reason.
83
+ */
84
+ async checkCardUnlock(card, _course, unlockedTags, masteredTags) {
85
+ try {
86
+ const cardTags = card.tags ?? [];
87
+ const lockedTags = cardTags.filter((tag) => this.hasPrerequisites(tag) && !unlockedTags.has(tag));
88
+ if (lockedTags.length === 0) return {
89
+ isUnlocked: true,
90
+ reason: `Prerequisites met, tags: ${cardTags.length > 0 ? cardTags.join(", ") : "none"}`
91
+ };
92
+ return {
93
+ isUnlocked: false,
94
+ reason: `Blocked: missing prerequisites ${lockedTags.flatMap((tag) => {
95
+ return (this.config.prerequisites[tag] || []).filter((p) => !masteredTags.has(p.tag)).map((p) => p.tag);
96
+ }).join(", ")} for tags ${lockedTags.join(", ")}`
97
+ };
98
+ } catch {
99
+ return {
100
+ isUnlocked: true,
101
+ reason: "Prerequisites check skipped (tag lookup failed)"
102
+ };
103
+ }
104
+ }
105
+ /**
106
+ * Build a map of prereq tag → max configured boost for all *closed* gates.
107
+ *
108
+ * When a gate is closed (prereqs unmet), cards carrying that gate's prereq
109
+ * tags get boosted — steering the pipeline toward content that helps unlock
110
+ * the gated material. Once the gate opens, the boost disappears.
111
+ */
112
+ getPreReqBoosts(unlockedTags, masteredTags) {
113
+ const boosts = /* @__PURE__ */ new Map();
114
+ for (const [tagId, prereqs] of Object.entries(this.config.prerequisites)) {
115
+ if (unlockedTags.has(tagId)) continue;
116
+ for (const prereq of prereqs) {
117
+ if (!prereq.preReqBoost || prereq.preReqBoost <= 1) continue;
118
+ if (masteredTags.has(prereq.tag)) continue;
119
+ const existing = boosts.get(prereq.tag) ?? 1;
120
+ boosts.set(prereq.tag, Math.max(existing, prereq.preReqBoost));
121
+ }
122
+ }
123
+ return boosts;
124
+ }
125
+ /**
126
+ * Build a map of gated tag → max configured targetBoost for all *open* gates.
127
+ *
128
+ * When a gate opens (prereqs met), cards carrying the gated tag get boosted —
129
+ * ensuring newly-unlocked content surfaces promptly. The boost is a static
130
+ * multiplier; natural ELO/SRS deprioritization after interaction handles decay.
131
+ */
132
+ getTargetBoosts(unlockedTags) {
133
+ const boosts = /* @__PURE__ */ new Map();
134
+ const configKeys = Object.keys(this.config.prerequisites);
135
+ const unlockedArr = [...unlockedTags];
136
+ logger.info(`[HierarchyDefinition:targetBoost:trace] ${this.name} | configKeys=${configKeys.length}, unlocked=${unlockedArr.length} (${unlockedArr.slice(0, 5).join(", ")}${unlockedArr.length > 5 ? "..." : ""})`);
137
+ for (const [tagId, prereqs] of Object.entries(this.config.prerequisites)) {
138
+ if (!unlockedTags.has(tagId)) continue;
139
+ logger.info(`[HierarchyDefinition:targetBoost:trace] UNLOCKED ${tagId}: ${prereqs.length} prereqs, raw=${JSON.stringify(prereqs.map((p) => ({
140
+ tag: p.tag,
141
+ tb: p.targetBoost
142
+ })))}`);
143
+ for (const prereq of prereqs) {
144
+ if (!prereq.targetBoost || prereq.targetBoost <= 1) continue;
145
+ const existing = boosts.get(tagId) ?? 1;
146
+ boosts.set(tagId, Math.max(existing, prereq.targetBoost));
147
+ }
148
+ }
149
+ if (boosts.size > 0) logger.info(`[HierarchyDefinition] targetBoosts active: ${[...boosts.entries()].map(([t, b]) => `${t}=×${b}`).join(", ")}`);
150
+ else logger.info(`[HierarchyDefinition:targetBoost:trace] no targetBoosts found despite ${unlockedArr.length} unlocked tags`);
151
+ return boosts;
152
+ }
153
+ /**
154
+ * CardFilter.transform implementation.
155
+ *
156
+ * Three effects:
157
+ * 1. Cards with locked tags receive score * 0.02 (gating penalty)
158
+ * 2. Cards carrying prereq tags of closed gates receive preReqBoost
159
+ * 3. Cards carrying gated tags of open gates receive targetBoost
160
+ */
161
+ async transform(cards, context) {
162
+ const masteredTags = await this.getMasteredTags(context);
163
+ const unlockedTags = this.getUnlockedTags(masteredTags);
164
+ const preReqBoosts = this.getPreReqBoosts(unlockedTags, masteredTags);
165
+ const targetBoosts = this.getTargetBoosts(unlockedTags);
166
+ const gated = [];
167
+ for (const card of cards) {
168
+ const { isUnlocked, reason } = await this.checkCardUnlock(card, context.course, unlockedTags, masteredTags);
169
+ let finalScore = isUnlocked ? card.score : card.score * .02;
170
+ let action = isUnlocked ? "passed" : "penalized";
171
+ let finalReason = reason;
172
+ if (isUnlocked && preReqBoosts.size > 0) {
173
+ const cardTags = card.tags ?? [];
174
+ let maxBoost = 1;
175
+ const boostedPrereqs = [];
176
+ for (const tag of cardTags) {
177
+ const boost = preReqBoosts.get(tag);
178
+ if (boost && boost > maxBoost) {
179
+ maxBoost = boost;
180
+ boostedPrereqs.push(tag);
181
+ }
182
+ }
183
+ if (maxBoost > 1) {
184
+ finalScore *= maxBoost;
185
+ action = "boosted";
186
+ finalReason = `${reason} | preReqBoost ×${maxBoost.toFixed(2)} for ${boostedPrereqs.join(", ")}`;
187
+ logger.info(`[HierarchyDefinition] preReqBoost ×${maxBoost.toFixed(2)} applied to card ${card.cardId} via tags [${boostedPrereqs.join(", ")}] (score: ${card.score.toFixed(3)} → ${finalScore.toFixed(3)})`);
188
+ }
189
+ }
190
+ if (isUnlocked && targetBoosts.size > 0) {
191
+ const cardTags = card.tags ?? [];
192
+ let maxTargetBoost = 1;
193
+ const boostedTargets = [];
194
+ for (const tag of cardTags) {
195
+ const boost = targetBoosts.get(tag);
196
+ if (boost && boost > maxTargetBoost) {
197
+ maxTargetBoost = boost;
198
+ boostedTargets.push(tag);
199
+ }
200
+ }
201
+ if (maxTargetBoost > 1) {
202
+ finalScore *= maxTargetBoost;
203
+ action = "boosted";
204
+ finalReason = `${finalReason} | targetBoost ×${maxTargetBoost.toFixed(2)} for ${boostedTargets.join(", ")}`;
205
+ logger.info(`[HierarchyDefinition] targetBoost ×${maxTargetBoost.toFixed(2)} applied to card ${card.cardId} via tags [${boostedTargets.join(", ")}] (score: ${card.score.toFixed(3)} → ${finalScore.toFixed(3)})`);
206
+ }
207
+ }
208
+ gated.push({
209
+ ...card,
210
+ score: finalScore,
211
+ provenance: [...card.provenance, {
212
+ strategy: "hierarchyDefinition",
213
+ strategyName: this.strategyName || this.name,
214
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-hierarchy",
215
+ action,
216
+ score: finalScore,
217
+ reason: finalReason
218
+ }]
219
+ });
220
+ }
221
+ return gated;
222
+ }
223
+ /**
224
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
225
+ *
226
+ * Use transform() via Pipeline instead.
227
+ */
228
+ async getWeightedCards(_limit) {
229
+ throw new Error("HierarchyDefinitionNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().");
230
+ }
231
+ };
232
+ //#endregion
233
+ export { HierarchyDefinitionNavigator as default };
234
+
235
+ //# sourceMappingURL=hierarchyDefinition.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hierarchyDefinition.mjs","names":[],"sources":["../../../../src/core/navigators/filters/hierarchyDefinition.ts"],"sourcesContent":["import type { CourseDBInterface } from '../../interfaces/courseDB';\nimport type { UserDBInterface } from '../../interfaces/userDB';\nimport { ContentNavigator } from '../index';\nimport type { WeightedCard } from '../index';\nimport type { ContentNavigationStrategyData } from '../../types/contentNavigationStrategy';\nimport type { CardFilter, FilterContext, FilterKind } from './types';\nimport type { GeneratorResult } from '../generators/types';\nimport { toCourseElo } from '@vue-skuilder/common';\nimport { logger } from '../../../util/logger';\n\n/**\n * A single prerequisite requirement for a tag.\n * Each prerequisite refers to one tag with its own mastery threshold.\n */\ninterface TagPrerequisite {\n /** The tag that must be mastered */\n tag: string;\n /** Thresholds for considering this prerequisite tag \"mastered\" */\n masteryThreshold?: {\n /** Minimum ELO score for mastery. If not set, uses avgElo comparison */\n minElo?: number;\n /** Minimum interaction count (default: 3) */\n minCount?: number;\n };\n /**\n * Score multiplier applied to cards that carry this prereq tag while\n * the gate is still closed. Steers the pipeline toward cards that help\n * unlock the gated content. Falls away once the prereq is met.\n *\n * Example: `preReqBoost: 1.3` gives a 30% score increase to cards\n * tagged `gpc:expose:t-T` while `gpc:intro:t-T` is still locked.\n */\n preReqBoost?: number;\n /**\n * Score multiplier applied to cards carrying the *gated* tag once the\n * gate opens (all prereqs met). Ensures newly-unlocked content surfaces\n * promptly before natural ELO/SRS scoring takes over.\n *\n * Falls away naturally as generators stop surfacing the card after\n * the user interacts with it.\n *\n * Example: `targetBoost: 4` on intro-t-T's prerequisite gives a 4×\n * score increase to intro-t-T cards once their expose gate is met.\n */\n targetBoost?: number;\n}\n\n/**\n * Configuration for the HierarchyDefinition strategy\n */\nexport interface HierarchyConfig {\n /** Map of tag ID to its list of prerequisites (each with individual thresholds) */\n prerequisites: {\n [tagId: string]: TagPrerequisite[];\n };\n}\n\nconst DEFAULT_MIN_COUNT = 3;\n\n/**\n * A filter strategy that gates cards based on prerequisite mastery.\n *\n * Cards are locked until the user masters all prerequisite tags.\n * Locked cards receive score * 0.05 (strong penalty, not hard filter).\n *\n * Mastery is determined by:\n * - User's ELO for the tag exceeds threshold (or avgElo if not specified)\n * - User has minimum interaction count with the tag\n *\n * Tags with no prerequisites are always unlocked.\n *\n * Implements CardFilter for use in Pipeline architecture.\n * Also extends ContentNavigator for backward compatibility.\n */\nexport default class HierarchyDefinitionNavigator extends ContentNavigator implements CardFilter {\n private config: HierarchyConfig;\n\n /** Human-readable name for CardFilter interface */\n name: string;\n\n /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */\n static readonly kind: FilterKind = 'gate';\n readonly kind = HierarchyDefinitionNavigator.kind;\n\n constructor(\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n ) {\n super(user, course, strategyData);\n this.config = this.parseConfig(strategyData.serializedData);\n this.name = strategyData.name || 'Hierarchy Definition';\n }\n\n private parseConfig(serializedData: string): HierarchyConfig {\n try {\n const parsed = JSON.parse(serializedData);\n return {\n prerequisites: parsed.prerequisites || {},\n };\n } catch {\n // Return safe defaults if parsing fails\n return {\n prerequisites: {},\n };\n }\n }\n\n /**\n * Check if a specific prerequisite is satisfied\n */\n private isPrerequisiteMet(\n prereq: TagPrerequisite,\n userTagElo: { score: number; count: number } | undefined,\n userGlobalElo: number\n ): boolean {\n if (!userTagElo) return false;\n\n const minCount = prereq.masteryThreshold?.minCount ?? DEFAULT_MIN_COUNT;\n if (userTagElo.count < minCount) return false;\n\n if (prereq.masteryThreshold?.minElo !== undefined) {\n return userTagElo.score >= prereq.masteryThreshold.minElo;\n } else if (prereq.masteryThreshold?.minCount !== undefined) {\n // Explicit minCount without minElo: count alone is sufficient.\n // The config author specified a concrete interaction threshold —\n // don't additionally require above-average ELO.\n return true;\n } else {\n // No thresholds specified at all: fall back to above-average ELO\n return userTagElo.score >= userGlobalElo;\n }\n }\n\n /**\n * Get the set of tags the user has mastered.\n * A tag is \"mastered\" if it appears as a prerequisite somewhere and meets its threshold.\n */\n private async getMasteredTags(context: FilterContext): Promise<Set<string>> {\n const mastered = new Set<string>();\n\n try {\n const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());\n const userElo = toCourseElo(courseReg.elo);\n\n // Collect all unique prerequisite tags and check mastery for each\n for (const prereqs of Object.values(this.config.prerequisites)) {\n for (const prereq of prereqs) {\n const tagElo = userElo.tags[prereq.tag];\n if (this.isPrerequisiteMet(prereq, tagElo, userElo.global.score)) {\n mastered.add(prereq.tag);\n }\n }\n }\n } catch {\n // If we can't get user data, return empty set (no tags mastered)\n }\n\n return mastered;\n }\n\n /**\n * Get the set of tags that are unlocked (prerequisites met)\n */\n private getUnlockedTags(masteredTags: Set<string>): Set<string> {\n const unlocked = new Set<string>();\n\n for (const [tagId, prereqs] of Object.entries(this.config.prerequisites)) {\n const allPrereqsMet = prereqs.every((prereq) => masteredTags.has(prereq.tag));\n if (allPrereqsMet) {\n unlocked.add(tagId);\n }\n }\n\n return unlocked;\n }\n\n /**\n * Check if a tag has prerequisites defined in config\n */\n private hasPrerequisites(tagId: string): boolean {\n return tagId in this.config.prerequisites;\n }\n\n /**\n * Check if a card is unlocked and generate reason.\n */\n private async checkCardUnlock(\n card: WeightedCard,\n _course: CourseDBInterface,\n unlockedTags: Set<string>,\n masteredTags: Set<string>\n ): Promise<{ isUnlocked: boolean; reason: string }> {\n try {\n // Pipeline hydrates tags before filters run\n const cardTags = card.tags ?? [];\n\n // Check each tag's prerequisite status\n const lockedTags = cardTags.filter(\n (tag) => this.hasPrerequisites(tag) && !unlockedTags.has(tag)\n );\n\n if (lockedTags.length === 0) {\n const tagList = cardTags.length > 0 ? cardTags.join(', ') : 'none';\n return {\n isUnlocked: true,\n reason: `Prerequisites met, tags: ${tagList}`,\n };\n }\n\n // Find missing prerequisites for locked tags\n const missingPrereqs = lockedTags.flatMap((tag) => {\n const prereqs = this.config.prerequisites[tag] || [];\n return prereqs.filter((p) => !masteredTags.has(p.tag)).map((p) => p.tag);\n });\n\n return {\n isUnlocked: false,\n reason: `Blocked: missing prerequisites ${missingPrereqs.join(', ')} for tags ${lockedTags.join(', ')}`,\n };\n } catch {\n // If we can't get tags, assume unlocked (fail open)\n return {\n isUnlocked: true,\n reason: 'Prerequisites check skipped (tag lookup failed)',\n };\n }\n }\n\n /**\n * Build a map of prereq tag → max configured boost for all *closed* gates.\n *\n * When a gate is closed (prereqs unmet), cards carrying that gate's prereq\n * tags get boosted — steering the pipeline toward content that helps unlock\n * the gated material. Once the gate opens, the boost disappears.\n */\n private getPreReqBoosts(\n unlockedTags: Set<string>,\n masteredTags: Set<string>\n ): Map<string, number> {\n const boosts = new Map<string, number>();\n\n for (const [tagId, prereqs] of Object.entries(this.config.prerequisites)) {\n // Only boost prereqs of closed gates\n if (unlockedTags.has(tagId)) continue;\n\n for (const prereq of prereqs) {\n if (!prereq.preReqBoost || prereq.preReqBoost <= 1.0) continue;\n // Only boost prereqs that aren't already met\n if (masteredTags.has(prereq.tag)) continue;\n\n const existing = boosts.get(prereq.tag) ?? 1.0;\n boosts.set(prereq.tag, Math.max(existing, prereq.preReqBoost));\n }\n }\n\n return boosts;\n }\n\n /**\n * Build a map of gated tag → max configured targetBoost for all *open* gates.\n *\n * When a gate opens (prereqs met), cards carrying the gated tag get boosted —\n * ensuring newly-unlocked content surfaces promptly. The boost is a static\n * multiplier; natural ELO/SRS deprioritization after interaction handles decay.\n */\n private getTargetBoosts(unlockedTags: Set<string>): Map<string, number> {\n const boosts = new Map<string, number>();\n\n const configKeys = Object.keys(this.config.prerequisites);\n const unlockedArr = [...unlockedTags];\n logger.info(\n `[HierarchyDefinition:targetBoost:trace] ${this.name} | configKeys=${configKeys.length}, unlocked=${unlockedArr.length} (${unlockedArr.slice(0, 5).join(', ')}${unlockedArr.length > 5 ? '...' : ''})`\n );\n\n for (const [tagId, prereqs] of Object.entries(this.config.prerequisites)) {\n // Only boost targets of open gates\n if (!unlockedTags.has(tagId)) continue;\n\n // TRACE: dump prereq details for unlocked tags\n logger.info(\n `[HierarchyDefinition:targetBoost:trace] UNLOCKED ${tagId}: ${prereqs.length} prereqs, raw=${JSON.stringify(prereqs.map(p => ({ tag: p.tag, tb: p.targetBoost })))}`\n );\n\n for (const prereq of prereqs) {\n if (!prereq.targetBoost || prereq.targetBoost <= 1.0) continue;\n\n const existing = boosts.get(tagId) ?? 1.0;\n boosts.set(tagId, Math.max(existing, prereq.targetBoost));\n }\n }\n\n if (boosts.size > 0) {\n logger.info(\n `[HierarchyDefinition] targetBoosts active: ${[...boosts.entries()].map(([t, b]) => `${t}=×${b}`).join(', ')}`\n );\n } else {\n logger.info(\n `[HierarchyDefinition:targetBoost:trace] no targetBoosts found despite ${unlockedArr.length} unlocked tags`\n );\n }\n\n return boosts;\n }\n\n /**\n * CardFilter.transform implementation.\n *\n * Three effects:\n * 1. Cards with locked tags receive score * 0.02 (gating penalty)\n * 2. Cards carrying prereq tags of closed gates receive preReqBoost\n * 3. Cards carrying gated tags of open gates receive targetBoost\n */\n async transform(cards: WeightedCard[], context: FilterContext): Promise<WeightedCard[]> {\n // Get mastery state\n const masteredTags = await this.getMasteredTags(context);\n const unlockedTags = this.getUnlockedTags(masteredTags);\n const preReqBoosts = this.getPreReqBoosts(unlockedTags, masteredTags);\n const targetBoosts = this.getTargetBoosts(unlockedTags);\n\n // Apply prerequisite gating + prereq/target boosting\n const gated: WeightedCard[] = [];\n\n for (const card of cards) {\n const { isUnlocked, reason } = await this.checkCardUnlock(\n card,\n context.course,\n unlockedTags,\n masteredTags\n );\n const LOCKED_PENALTY = 0.02;\n let finalScore = isUnlocked ? card.score : card.score * LOCKED_PENALTY;\n let action: 'passed' | 'penalized' | 'boosted' = isUnlocked ? 'passed' : 'penalized';\n let finalReason = reason;\n\n // Apply prereq boost to cards that passed gating (don't boost locked cards)\n if (isUnlocked && preReqBoosts.size > 0) {\n const cardTags = card.tags ?? [];\n let maxBoost = 1.0;\n const boostedPrereqs: string[] = [];\n\n for (const tag of cardTags) {\n const boost = preReqBoosts.get(tag);\n if (boost && boost > maxBoost) {\n maxBoost = boost;\n boostedPrereqs.push(tag);\n }\n }\n\n if (maxBoost > 1.0) {\n finalScore *= maxBoost;\n action = 'boosted';\n finalReason = `${reason} | preReqBoost ×${maxBoost.toFixed(2)} for ${boostedPrereqs.join(', ')}`;\n logger.info(\n `[HierarchyDefinition] preReqBoost ×${maxBoost.toFixed(2)} applied to card ${card.cardId} via tags [${boostedPrereqs.join(', ')}] (score: ${card.score.toFixed(3)} → ${finalScore.toFixed(3)})`\n );\n }\n }\n\n // Apply target boost to unlocked cards whose gated tag just opened\n if (isUnlocked && targetBoosts.size > 0) {\n const cardTags = card.tags ?? [];\n let maxTargetBoost = 1.0;\n const boostedTargets: string[] = [];\n\n for (const tag of cardTags) {\n const boost = targetBoosts.get(tag);\n if (boost && boost > maxTargetBoost) {\n maxTargetBoost = boost;\n boostedTargets.push(tag);\n }\n }\n\n if (maxTargetBoost > 1.0) {\n finalScore *= maxTargetBoost;\n action = 'boosted';\n finalReason = `${finalReason} | targetBoost ×${maxTargetBoost.toFixed(2)} for ${boostedTargets.join(', ')}`;\n logger.info(\n `[HierarchyDefinition] targetBoost ×${maxTargetBoost.toFixed(2)} applied to card ${card.cardId} via tags [${boostedTargets.join(', ')}] (score: ${card.score.toFixed(3)} → ${finalScore.toFixed(3)})`\n );\n }\n }\n\n gated.push({\n ...card,\n score: finalScore,\n provenance: [\n ...card.provenance,\n {\n strategy: 'hierarchyDefinition',\n strategyName: this.strategyName || this.name,\n strategyId: this.strategyId || 'NAVIGATION_STRATEGY-hierarchy',\n action,\n score: finalScore,\n reason: finalReason,\n },\n ],\n });\n }\n\n return gated;\n }\n\n /**\n * Legacy getWeightedCards - now throws as filters should not be used as generators.\n *\n * Use transform() via Pipeline instead.\n */\n async getWeightedCards(_limit: number): Promise<GeneratorResult> {\n throw new Error(\n 'HierarchyDefinitionNavigator is a filter and should not be used as a generator. ' +\n 'Use Pipeline with a generator and this filter via transform().'\n );\n }\n}\n"],"mappings":";;;;;AAyDA,MAAM,oBAAoB;;;;;;;;;;;;;;;;AAiB1B,IAAqB,+BAArB,MAAqB,qCAAqC,iBAAuC;CAC/F;;CAGA;;CAGA,OAAgB,OAAmB;CACnC,OAAgB,6BAA6B;CAE7C,YACE,MACA,QACA,cACA;AACA,QAAM,MAAM,QAAQ,aAAa;AACjC,OAAK,SAAS,KAAK,YAAY,aAAa,eAAe;AAC3D,OAAK,OAAO,aAAa,QAAQ;;CAGnC,YAAoB,gBAAyC;AAC3D,MAAI;AAEF,UAAO,EACL,eAFa,KAAK,MAAM,eAAe,CAEjB,iBAAiB,EAAE,EAC1C;UACK;AAEN,UAAO,EACL,eAAe,EAAE,EAClB;;;;;;CAOL,kBACE,QACA,YACA,eACS;AACT,MAAI,CAAC,WAAY,QAAO;EAExB,MAAM,WAAW,OAAO,kBAAkB,YAAY;AACtD,MAAI,WAAW,QAAQ,SAAU,QAAO;AAExC,MAAI,OAAO,kBAAkB,WAAW,KAAA,EACtC,QAAO,WAAW,SAAS,OAAO,iBAAiB;WAC1C,OAAO,kBAAkB,aAAa,KAAA,EAI/C,QAAO;MAGP,QAAO,WAAW,SAAS;;;;;;CAQ/B,MAAc,gBA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