@vue-skuilder/db 0.2.34 → 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 (262) 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-CTQ4kWhR.d.cts → contentSource-D_E7JaxR.d.ts} +2 -2
  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-rlLE2Mf-.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} +130 -1
  87. package/dist/diagnostics/index.cjs.map +1 -0
  88. package/dist/diagnostics/index.d.ts +108 -5
  89. package/dist/diagnostics/index.mjs +7 -914
  90. package/dist/diagnostics/loader.mjs +151 -0
  91. package/dist/diagnostics/loader.mjs.map +1 -0
  92. package/dist/diagnostics/pipeline.mjs +161 -0
  93. package/dist/diagnostics/pipeline.mjs.map +1 -0
  94. package/dist/diagnostics/tagElo.mjs +177 -0
  95. package/dist/diagnostics/tagElo.mjs.map +1 -0
  96. package/dist/diagnostics/text.mjs +174 -0
  97. package/dist/diagnostics/text.mjs.map +1 -0
  98. package/dist/factory.mjs +70 -0
  99. package/dist/factory.mjs.map +1 -0
  100. package/dist/impl/common/BaseUserDB.mjs +1103 -0
  101. package/dist/impl/common/BaseUserDB.mjs.map +1 -0
  102. package/dist/impl/common/userDBHelpers.mjs +49 -0
  103. package/dist/impl/common/userDBHelpers.mjs.map +1 -0
  104. package/dist/impl/common/userDBKeys.mjs +45 -0
  105. package/dist/impl/common/userDBKeys.mjs.map +1 -0
  106. package/dist/impl/couch/CouchDBSyncStrategy.mjs +272 -0
  107. package/dist/impl/couch/CouchDBSyncStrategy.mjs.map +1 -0
  108. package/dist/impl/couch/CourseSyncService.mjs +242 -0
  109. package/dist/impl/couch/CourseSyncService.mjs.map +1 -0
  110. package/dist/impl/couch/PouchDataLayerProvider.mjs +74 -0
  111. package/dist/impl/couch/PouchDataLayerProvider.mjs.map +1 -0
  112. package/dist/impl/couch/adminDB.mjs +61 -0
  113. package/dist/impl/couch/adminDB.mjs.map +1 -0
  114. package/dist/impl/couch/auth.mjs +33 -0
  115. package/dist/impl/couch/auth.mjs.map +1 -0
  116. package/dist/impl/couch/classroomDB.mjs +227 -0
  117. package/dist/impl/couch/classroomDB.mjs.map +1 -0
  118. package/dist/impl/couch/clientCache.mjs +15 -0
  119. package/dist/impl/couch/clientCache.mjs.map +1 -0
  120. package/dist/impl/couch/courseAPI.mjs +183 -0
  121. package/dist/impl/couch/courseAPI.mjs.map +1 -0
  122. package/dist/impl/couch/courseDB.mjs +729 -0
  123. package/dist/impl/couch/courseDB.mjs.map +1 -0
  124. package/dist/impl/couch/courseLookupDB.mjs +94 -0
  125. package/dist/impl/couch/courseLookupDB.mjs.map +1 -0
  126. package/dist/impl/couch/{index.js → index.cjs} +6911 -10367
  127. package/dist/impl/couch/index.cjs.map +1 -0
  128. package/dist/impl/couch/index.d.ts +12 -5
  129. package/dist/impl/couch/index.mjs +134 -12146
  130. package/dist/impl/couch/index.mjs.map +1 -1
  131. package/dist/impl/couch/pouchdb-setup.mjs +15 -0
  132. package/dist/impl/couch/pouchdb-setup.mjs.map +1 -0
  133. package/dist/impl/couch/updateQueue.mjs +101 -0
  134. package/dist/impl/couch/updateQueue.mjs.map +1 -0
  135. package/dist/impl/couch/user-course-relDB.mjs +55 -0
  136. package/dist/impl/couch/user-course-relDB.mjs.map +1 -0
  137. package/dist/impl/static/NoOpSyncStrategy.mjs +49 -0
  138. package/dist/impl/static/NoOpSyncStrategy.mjs.map +1 -0
  139. package/dist/impl/static/StaticDataLayerProvider.mjs +94 -0
  140. package/dist/impl/static/StaticDataLayerProvider.mjs.map +1 -0
  141. package/dist/impl/static/StaticDataUnpacker.mjs +311 -0
  142. package/dist/impl/static/StaticDataUnpacker.mjs.map +1 -0
  143. package/dist/impl/static/courseDB.mjs +368 -0
  144. package/dist/impl/static/courseDB.mjs.map +1 -0
  145. package/dist/impl/static/coursesDB.mjs +38 -0
  146. package/dist/impl/static/coursesDB.mjs.map +1 -0
  147. package/dist/impl/static/{index.js → index.cjs} +2461 -5992
  148. package/dist/impl/static/index.cjs.map +1 -0
  149. package/dist/impl/static/index.d.ts +4 -4
  150. package/dist/impl/static/index.mjs +6 -10741
  151. package/dist/{index-CVGehe_t.d.ts → index-BLDpFYG3.d.ts} +1 -1
  152. package/dist/{index.js → index.cjs} +14070 -14239
  153. package/dist/index.cjs.map +1 -0
  154. package/dist/index.d.ts +12 -23
  155. package/dist/index.mjs +38 -16937
  156. package/dist/pouch/{index.js → index.cjs} +5 -1
  157. package/dist/pouch/index.cjs.map +1 -0
  158. package/dist/pouch/index.mjs +2 -19
  159. package/dist/study/ItemQueue.mjs +95 -0
  160. package/dist/study/ItemQueue.mjs.map +1 -0
  161. package/dist/study/MixerDebugger.mjs +303 -0
  162. package/dist/study/MixerDebugger.mjs.map +1 -0
  163. package/dist/study/SessionController.mjs +1187 -0
  164. package/dist/study/SessionController.mjs.map +1 -0
  165. package/dist/study/SessionDebugger.mjs +271 -0
  166. package/dist/study/SessionDebugger.mjs.map +1 -0
  167. package/dist/study/SessionOverlay.mjs +407 -0
  168. package/dist/study/SessionOverlay.mjs.map +1 -0
  169. package/dist/study/SourceMixer.mjs +45 -0
  170. package/dist/study/SourceMixer.mjs.map +1 -0
  171. package/dist/study/SpacedRepetition.mjs +108 -0
  172. package/dist/study/SpacedRepetition.mjs.map +1 -0
  173. package/dist/study/TagFilteredContentSource.mjs +136 -0
  174. package/dist/study/TagFilteredContentSource.mjs.map +1 -0
  175. package/dist/study/services/CardHydrationService.mjs +172 -0
  176. package/dist/study/services/CardHydrationService.mjs.map +1 -0
  177. package/dist/study/services/EloService.mjs +217 -0
  178. package/dist/study/services/EloService.mjs.map +1 -0
  179. package/dist/study/services/ResponseProcessor.mjs +190 -0
  180. package/dist/study/services/ResponseProcessor.mjs.map +1 -0
  181. package/dist/study/services/SrsService.mjs +49 -0
  182. package/dist/study/services/SrsService.mjs.map +1 -0
  183. package/dist/study/services/tagRecent.mjs +65 -0
  184. package/dist/study/services/tagRecent.mjs.map +1 -0
  185. package/dist/{types-dXWfyz9B.d.ts → types-DChCz22D.d.ts} +1 -1
  186. package/dist/{types-legacy-BkOYOR6U.d.cts → types-legacy-fT5Y1Wuy.d.ts} +1 -1
  187. package/dist/userDBKeys-ne1g4Xuq.d.ts +16 -0
  188. package/dist/util/Loggable.mjs +14 -0
  189. package/dist/util/Loggable.mjs.map +1 -0
  190. package/dist/util/dataDirectory.mjs +47 -0
  191. package/dist/util/dataDirectory.mjs.map +1 -0
  192. package/dist/util/logger.mjs +86 -0
  193. package/dist/util/logger.mjs.map +1 -0
  194. package/dist/util/migrator/FileSystemAdapter.mjs +18 -0
  195. package/dist/util/migrator/FileSystemAdapter.mjs.map +1 -0
  196. package/dist/util/migrator/StaticToCouchDBMigrator.mjs +428 -0
  197. package/dist/util/migrator/StaticToCouchDBMigrator.mjs.map +1 -0
  198. package/dist/util/migrator/types.mjs +11 -0
  199. package/dist/util/migrator/types.mjs.map +1 -0
  200. package/dist/util/migrator/validation.mjs +334 -0
  201. package/dist/util/migrator/validation.mjs.map +1 -0
  202. package/dist/util/packer/CouchDBToStaticPacker.mjs +438 -0
  203. package/dist/util/packer/CouchDBToStaticPacker.mjs.map +1 -0
  204. package/dist/util/packer/{index.js → index.cjs} +73 -9
  205. package/dist/util/packer/index.cjs.map +1 -0
  206. package/dist/util/packer/index.d.ts +3 -3
  207. package/dist/util/packer/index.mjs +2 -537
  208. package/eslint.config.mjs +9 -1
  209. package/package.json +25 -13
  210. package/rolldown.config.mjs +44 -0
  211. package/src/core/UserDBDebugger.ts +47 -46
  212. package/src/core/navigators/Pipeline.ts +10 -10
  213. package/src/core/navigators/PipelineDebugger.ts +55 -55
  214. package/src/core/navigators/filters/eloDistance.ts +11 -1
  215. package/src/core/navigators/generators/elo.ts +5 -1
  216. package/src/core/navigators/index.ts +9 -3
  217. package/src/diagnostics/derive.ts +6 -0
  218. package/src/diagnostics/index.ts +1 -0
  219. package/src/diagnostics/tagElo.ts +257 -0
  220. package/src/factory.ts +10 -1
  221. package/src/impl/common/BaseUserDB.ts +1 -3
  222. package/src/impl/common/index.ts +2 -0
  223. package/src/impl/common/userDBHelpers.ts +4 -58
  224. package/src/impl/common/userDBKeys.ts +64 -0
  225. package/src/impl/couch/courseDB.ts +15 -3
  226. package/src/impl/couch/index.ts +2 -18
  227. package/src/impl/couch/pouchdb-setup.ts +8 -0
  228. package/src/index.ts +1 -1
  229. package/src/study/MixerDebugger.ts +46 -46
  230. package/src/study/SessionDebugger.ts +20 -20
  231. package/src/study/SessionOverlay.ts +4 -4
  232. package/src/util/logger.ts +112 -13
  233. package/tests/core/navigators/eloGenerator.test.ts +36 -0
  234. package/tsup.config.ts +24 -21
  235. package/dist/SyncStrategy-BXliog1m.d.cts +0 -116
  236. package/dist/classroomDB-DLTtLZct.d.cts +0 -86
  237. package/dist/contentSource-JmWYu8IK.d.ts +0 -2007
  238. package/dist/core/index.d.cts +0 -521
  239. package/dist/core/index.js.map +0 -1
  240. package/dist/core/index.mjs.map +0 -1
  241. package/dist/dataLayerProvider-DfI_KYAe.d.cts +0 -61
  242. package/dist/diagnostics/index.d.cts +0 -458
  243. package/dist/diagnostics/index.js.map +0 -1
  244. package/dist/diagnostics/index.mjs.map +0 -1
  245. package/dist/impl/couch/index.d.cts +0 -620
  246. package/dist/impl/couch/index.js.map +0 -1
  247. package/dist/impl/static/index.d.cts +0 -232
  248. package/dist/impl/static/index.js.map +0 -1
  249. package/dist/impl/static/index.mjs.map +0 -1
  250. package/dist/index-Ktg72jKb.d.cts +0 -137
  251. package/dist/index.d.cts +0 -1663
  252. package/dist/index.js.map +0 -1
  253. package/dist/index.mjs.map +0 -1
  254. package/dist/pouch/index.d.cts +0 -1
  255. package/dist/pouch/index.js.map +0 -1
  256. package/dist/pouch/index.mjs.map +0 -1
  257. package/dist/types-D0oQeJAi.d.cts +0 -58
  258. package/dist/types-legacy-BkOYOR6U.d.ts +0 -168
  259. package/dist/util/packer/index.d.cts +0 -5
  260. package/dist/util/packer/index.js.map +0 -1
  261. package/dist/util/packer/index.mjs.map +0 -1
  262. package/src/study/getCardDataShape.ts +0 -34
@@ -0,0 +1,676 @@
1
+ import "../../../_virtual/_rolldown/runtime.mjs";
2
+ import { logger } from "../../../util/logger.mjs";
3
+ import { captureStrategyPressure } from "../StrategyPressureDebugger.mjs";
4
+ import { ContentNavigator } from "../index.mjs";
5
+ import { tagRole, withTagRole } from "@vue-skuilder/common";
6
+ //#region src/core/navigators/generators/prescribed.ts
7
+ const DEFAULT_FRESHNESS_WINDOW = 3;
8
+ const DEFAULT_MAX_DIRECT_PER_RUN = 3;
9
+ const DEFAULT_MAX_SUPPORT_PER_RUN = 3;
10
+ const DEFAULT_HIERARCHY_DEPTH = 2;
11
+ const DEFAULT_MIN_COUNT = 3;
12
+ const DEFAULT_PRACTICE_MIN_COUNT = 3;
13
+ const DEFAULT_MAX_PRACTICE_PER_RUN = 4;
14
+ const BASE_TARGET_SCORE = 1;
15
+ const BASE_SUPPORT_SCORE = .8;
16
+ const DISCOVERED_SUPPORT_SCORE = 12;
17
+ const BASE_PRACTICE_SCORE = 1;
18
+ const PRACTICE_BASE_MULT = 2;
19
+ const MAX_PRACTICE_MULTIPLIER = 4;
20
+ const PRACTICE_STALENESS_BUMP_PER_DAY = .5;
21
+ const MAX_TARGET_MULTIPLIER = 8;
22
+ const MAX_SUPPORT_MULTIPLIER = 4;
23
+ const PRESCRIBED_DEBUG_VERSION = "testversion-prescribed-v3";
24
+ function dedupe(arr) {
25
+ return [...new Set(arr)];
26
+ }
27
+ function isoNow() {
28
+ return (/* @__PURE__ */ new Date()).toISOString();
29
+ }
30
+ function clamp(value, min, max) {
31
+ return Math.max(min, Math.min(max, value));
32
+ }
33
+ function matchesTagPattern(tag, pattern) {
34
+ if (pattern === "*") return true;
35
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
36
+ return new RegExp(`^${escaped}$`).test(tag);
37
+ }
38
+ /**
39
+ * Extract the word stem from a card ID for deduplication.
40
+ * ML: c-ml-{word}-{blanks} → {word}
41
+ * WS: c-ws-{word}-{contrast} → {word}
42
+ * Other: full cardId as fallback.
43
+ */
44
+ function extractWordStem(cardId) {
45
+ for (const prefix of [
46
+ "c-ml-",
47
+ "c-ws-",
48
+ "c-spelling-"
49
+ ]) if (cardId.startsWith(prefix)) {
50
+ const rest = cardId.slice(prefix.length);
51
+ const lastDash = rest.lastIndexOf("-");
52
+ return lastDash > 0 ? rest.slice(0, lastDash) : rest;
53
+ }
54
+ return cardId;
55
+ }
56
+ /** Fisher-Yates shuffle in place. */
57
+ function shuffleInPlace(arr) {
58
+ for (let i = arr.length - 1; i > 0; i--) {
59
+ const j = Math.floor(Math.random() * (i + 1));
60
+ [arr[i], arr[j]] = [arr[j], arr[i]];
61
+ }
62
+ }
63
+ /** Compact age string for debt-open durations: 42m / 7h / 3d. */
64
+ function formatAge(ms) {
65
+ const minutes = Math.max(0, Math.round(ms / 6e4));
66
+ if (minutes < 60) return `${minutes}m`;
67
+ const hours = Math.round(minutes / 60);
68
+ if (hours < 24) return `${hours}h`;
69
+ return `${Math.round(hours / 24)}d`;
70
+ }
71
+ /**
72
+ * The exposure tags an intro target still lacks before it may surface: its own
73
+ * `expose` tags plus the `expose` counterpart of each `intro` tag (tag roles,
74
+ * see common's tagRoles.ts: `gpc:intro:X` → `gpc:expose:X`), each needing
75
+ * `minCount` attempts. A `minCount` of 0 requires nothing — not even an entry
76
+ * in `userTagElo`.
77
+ */
78
+ function unmetIntroExposeTags(tags, userTagElo, minCount) {
79
+ if (minCount <= 0) return [];
80
+ const exposeTags = new Set(tags.filter((tag) => tagRole(tag) === "expose"));
81
+ for (const tag of tags) {
82
+ if (tagRole(tag) !== "intro") continue;
83
+ const expose = withTagRole(tag, "expose");
84
+ if (expose) exposeTags.add(expose);
85
+ }
86
+ return [...exposeTags].filter((tag) => {
87
+ const tagElo = userTagElo[tag];
88
+ return !tagElo || tagElo.count < minCount;
89
+ });
90
+ }
91
+ function pickTopByScore(cards, limit) {
92
+ return [...cards].sort((a, b) => b.score - a.score || a.cardId.localeCompare(b.cardId)).slice(0, limit);
93
+ }
94
+ var PrescribedCardsGenerator = class extends ContentNavigator {
95
+ name;
96
+ config;
97
+ constructor(user, course, strategyData) {
98
+ super(user, course, strategyData);
99
+ this.name = strategyData.name || "Prescribed Cards";
100
+ this.config = this.parseConfig(strategyData.serializedData);
101
+ logger.debug(`[Prescribed] Initialized with ${this.config.groups.length} groups and ${this.config.groups.reduce((n, g) => n + g.targetCardIds.length, 0)} targets`);
102
+ }
103
+ get strategyKey() {
104
+ return "PrescribedProgress";
105
+ }
106
+ async getWeightedCards(limit, context) {
107
+ if (this.config.groups.length === 0 || limit <= 0) return { cards: [] };
108
+ const courseId = this.course.getCourseID();
109
+ const activeCards = await this.user.getActiveCards();
110
+ const activeIds = new Set(activeCards.map((ac) => ac.cardID));
111
+ const seenCards = await this.user.getSeenCards(courseId).catch(() => []);
112
+ const seenIds = new Set(seenCards);
113
+ const progress = await this.getStrategyState() ?? {
114
+ updatedAt: isoNow(),
115
+ groups: {}
116
+ };
117
+ const hierarchyConfigs = await this.loadHierarchyConfigs();
118
+ const courseReg = await this.user.getCourseRegDoc(courseId).catch(() => null);
119
+ const userGlobalElo = typeof courseReg?.elo === "number" ? courseReg.elo : courseReg?.elo?.global?.score ?? context?.userElo ?? 1e3;
120
+ const userTagElo = typeof courseReg?.elo === "number" ? {} : courseReg?.elo?.tags ?? {};
121
+ const allTargetIds = dedupe(this.config.groups.flatMap((g) => g.targetCardIds));
122
+ const allSupportIds = dedupe(this.config.groups.flatMap((g) => g.supportCardIds ?? []));
123
+ const allRelevantIds = dedupe([...allTargetIds, ...allSupportIds]);
124
+ const tagsByCard = allRelevantIds.length > 0 ? await this.course.getAppliedTagsBatch(allRelevantIds) : /* @__PURE__ */ new Map();
125
+ const courseTagDocs = await this.course.getCourseTagStubs().catch(() => ({
126
+ rows: [],
127
+ offset: 0,
128
+ total_rows: 0
129
+ }));
130
+ const cardsByTag = /* @__PURE__ */ new Map();
131
+ for (const row of courseTagDocs.rows ?? []) {
132
+ const tagDoc = row.doc;
133
+ if (tagDoc?.name && Array.isArray(tagDoc.taggedCards)) cardsByTag.set(tagDoc.name, [...tagDoc.taggedCards]);
134
+ }
135
+ const nextState = {
136
+ updatedAt: isoNow(),
137
+ groups: {}
138
+ };
139
+ const emitted = [];
140
+ const emittedIds = /* @__PURE__ */ new Set();
141
+ const groupRuntimes = [];
142
+ const priorPracticeDebt = progress.practiceDebt ?? {};
143
+ const nextPracticeDebt = {};
144
+ const practiceDebtsByGroup = /* @__PURE__ */ new Map();
145
+ for (const group of this.config.groups) {
146
+ const runtime = this.buildGroupRuntimeState({
147
+ group,
148
+ priorState: progress.groups[group.id],
149
+ activeIds,
150
+ seenIds,
151
+ tagsByCard,
152
+ cardsByTag,
153
+ hierarchyConfigs,
154
+ userTagElo,
155
+ userGlobalElo
156
+ });
157
+ groupRuntimes.push(runtime);
158
+ logger.info(`[Prescribed] Group '${group.id}': ${group.targetCardIds.length} targets total, ${runtime.encounteredTargets.size} encountered, ${runtime.pendingTargets.length} pending (${runtime.surfaceableTargets.length} surfaceable, ${runtime.blockedTargets.length} blocked), ${runtime.supportCandidates.length} authored support candidates, ${runtime.discoveredSupportCandidates.length} discovered support candidates, pressure=${runtime.pressureMultiplier.toFixed(2)}`);
159
+ if (runtime.blockedTargets.length > 0) {
160
+ logger.info(`[Prescribed] Group '${group.id}' blocked targets: ${runtime.blockedTargets.join(", ")}`);
161
+ logger.info(`[Prescribed] Group '${group.id}' support tags needed: ${runtime.supportTags.join(", ") || "(none)"}`);
162
+ logger.info(`[Prescribed] Group '${group.id}' escalation mode: ` + (runtime.supportCandidates.length > 0 ? "direct-support" : runtime.discoveredSupportCandidates.length > 0 ? "inserted-support-candidates" : "boost-only"));
163
+ if (runtime.discoveredSupportCandidates.length > 0) logger.info(`[Prescribed] Group '${group.id}' discovered support candidates: ${runtime.discoveredSupportCandidates.join(", ")}`);
164
+ }
165
+ nextState.groups[group.id] = this.buildNextGroupState(runtime, progress.groups[group.id]);
166
+ const directCards = this.buildDirectTargetCards(runtime, courseId, emittedIds);
167
+ const supportCards = this.buildSupportCards(runtime, courseId, emittedIds);
168
+ const discoveredSupportCards = this.buildDiscoveredSupportCards(runtime, courseId, emittedIds);
169
+ const practice = this.buildPracticeCards({
170
+ group,
171
+ courseId,
172
+ emittedIds,
173
+ cardsByTag,
174
+ hierarchyConfigs,
175
+ userTagElo,
176
+ userGlobalElo,
177
+ activeIds,
178
+ seenIds,
179
+ priorPracticeDebt,
180
+ nextPracticeDebt
181
+ });
182
+ practiceDebtsByGroup.set(group.id, practice.debts);
183
+ emitted.push(...directCards, ...supportCards, ...discoveredSupportCards, ...practice.cards);
184
+ }
185
+ nextState.practiceDebt = nextPracticeDebt;
186
+ const hintSummary = this.buildSupportHintSummary(groupRuntimes);
187
+ const hints = Object.keys(hintSummary.boostTags).length > 0 ? {
188
+ boostTags: hintSummary.boostTags,
189
+ _label: `prescribed-support (${hintSummary.supportTags.length} tags; blocked=${hintSummary.blockedTargetIds.length}; testversion=${PRESCRIBED_DEBUG_VERSION})`
190
+ } : void 0;
191
+ if (hints) {
192
+ const tagEntries = Object.entries(hints.boostTags ?? {});
193
+ logger.info(`[Prescribed] Emitting ${tagEntries.length} boost hint(s): ` + tagEntries.map(([tag, mult]) => `${tag}×${mult.toFixed(1)}`).join(", "));
194
+ } else logger.info("[Prescribed] No hints to emit (no blocked targets or no support tags)");
195
+ this.capturePressureSnapshot(courseId, groupRuntimes, practiceDebtsByGroup, emitted, hints);
196
+ if (emitted.length === 0) {
197
+ logger.info("[Prescribed] 0 cards emitted (all targets blocked, authored/discovered support candidates exhausted)" + (hints ? " — boost hints emitted but may not survive filters" : ""));
198
+ await this.putStrategyState(nextState).catch((e) => {
199
+ logger.debug(`[Prescribed] Failed to persist empty-state update: ${e}`);
200
+ });
201
+ return hints ? {
202
+ cards: [],
203
+ hints
204
+ } : { cards: [] };
205
+ }
206
+ const finalCards = pickTopByScore(emitted, limit);
207
+ const surfacedByGroup = /* @__PURE__ */ new Map();
208
+ for (const card of finalCards) {
209
+ const prov = card.provenance[0];
210
+ if (prov?.reason.includes("mode=practice")) continue;
211
+ const groupId = prov?.reason.match(/group=([^;]+)/)?.[1];
212
+ const mode = prov?.reason.includes("mode=support") ? "supportIds" : "targetIds";
213
+ if (!groupId) continue;
214
+ if (!surfacedByGroup.has(groupId)) surfacedByGroup.set(groupId, {
215
+ targetIds: [],
216
+ supportIds: []
217
+ });
218
+ surfacedByGroup.get(groupId)[mode].push(card.cardId);
219
+ }
220
+ for (const group of this.config.groups) {
221
+ const groupState = nextState.groups[group.id];
222
+ const surfaced = surfacedByGroup.get(group.id);
223
+ if (surfaced && (surfaced.targetIds.length > 0 || surfaced.supportIds.length > 0)) {
224
+ groupState.lastSurfacedAt = isoNow();
225
+ groupState.sessionsSinceSurfaced = 0;
226
+ if (surfaced.supportIds.length > 0) groupState.lastSupportAt = isoNow();
227
+ }
228
+ }
229
+ await this.putStrategyState(nextState).catch((e) => {
230
+ logger.debug(`[Prescribed] Failed to persist prescribed progress: ${e}`);
231
+ });
232
+ logger.info(`[Prescribed] Emitting ${finalCards.length} cards (${finalCards.filter((c) => c.provenance[0]?.reason.includes("mode=target")).length} target, ${finalCards.filter((c) => c.provenance[0]?.reason.includes("mode=support")).length} support, ${finalCards.filter((c) => c.provenance[0]?.reason.includes("mode=discovered-support")).length} discovered support)`);
233
+ return hints ? {
234
+ cards: finalCards,
235
+ hints
236
+ } : { cards: finalCards };
237
+ }
238
+ buildSupportHintSummary(groupRuntimes) {
239
+ const boostTags = {};
240
+ const blockedTargetIds = /* @__PURE__ */ new Set();
241
+ const supportTags = /* @__PURE__ */ new Set();
242
+ for (const runtime of groupRuntimes) {
243
+ if (runtime.blockedTargets.length === 0 || runtime.supportTags.length === 0) continue;
244
+ runtime.blockedTargets.forEach((cardId) => blockedTargetIds.add(cardId));
245
+ for (const tag of runtime.supportTags) {
246
+ supportTags.add(tag);
247
+ boostTags[tag] = (boostTags[tag] ?? 1) * runtime.supportMultiplier;
248
+ }
249
+ }
250
+ return {
251
+ boostTags,
252
+ blockedTargetIds: [...blockedTargetIds].sort(),
253
+ supportTags: [...supportTags].sort()
254
+ };
255
+ }
256
+ /**
257
+ * Translate this run's per-group runtimes and practice debts into gauges on
258
+ * the generic strategy-pressure debug channel (rendered by the live session
259
+ * overlay's "strategy backpressure" section).
260
+ */
261
+ capturePressureSnapshot(courseId, groupRuntimes, practiceDebtsByGroup, emitted, hints) {
262
+ const now = Date.now();
263
+ const gauges = [];
264
+ for (const runtime of groupRuntimes) {
265
+ const group = runtime.group;
266
+ const window = group.freshnessWindowSessions ?? DEFAULT_FRESHNESS_WINDOW;
267
+ gauges.push({
268
+ id: `group:${group.id}:target`,
269
+ label: `${group.id} targets`,
270
+ multiplier: runtime.pressureMultiplier,
271
+ max: MAX_TARGET_MULTIPLIER,
272
+ detail: `${runtime.pendingTargets.length} pending (${runtime.surfaceableTargets.length} surfaceable, ${runtime.blockedTargets.length} blocked) · sinceSurfaced ${runtime.sessionsSinceSurfaced}/${window}`,
273
+ items: runtime.blockedTargets.map((cardId) => ({
274
+ label: cardId,
275
+ value: "blocked"
276
+ }))
277
+ });
278
+ if (runtime.blockedTargets.length > 0) {
279
+ const mode = runtime.supportCandidates.length > 0 ? "direct-support" : runtime.discoveredSupportCandidates.length > 0 ? "inserted-support" : "boost-only";
280
+ gauges.push({
281
+ id: `group:${group.id}:support`,
282
+ label: `${group.id} support`,
283
+ multiplier: runtime.supportMultiplier,
284
+ max: MAX_SUPPORT_MULTIPLIER,
285
+ detail: `mode=${mode} · ${runtime.supportTags.length} support tag(s)`,
286
+ items: runtime.supportTags.map((tag) => ({ label: tag }))
287
+ });
288
+ }
289
+ const debts = practiceDebtsByGroup.get(group.id) ?? [];
290
+ if (debts.length > 0) gauges.push({
291
+ id: `group:${group.id}:practice-debt`,
292
+ label: `${group.id} practice debt`,
293
+ multiplier: Math.max(...debts.map((d) => d.multiplier)),
294
+ max: MAX_PRACTICE_MULTIPLIER,
295
+ detail: `${debts.length} under-practiced skill(s)`,
296
+ items: debts.map((d) => ({
297
+ label: d.tag,
298
+ value: `×${d.multiplier.toFixed(2)} · open ${formatAge(now - new Date(d.firstOwedAt).getTime())}`
299
+ }))
300
+ });
301
+ }
302
+ captureStrategyPressure({
303
+ source: "prescribed",
304
+ courseId,
305
+ gauges,
306
+ topScore: emitted.length > 0 ? Math.max(...emitted.map((c) => c.score)) : null,
307
+ hintsLabel: hints?._label,
308
+ timestamp: now
309
+ });
310
+ }
311
+ parseConfig(serializedData) {
312
+ try {
313
+ const parsed = JSON.parse(serializedData);
314
+ return { groups: (Array.isArray(parsed.groups) ? parsed.groups : []).map((raw, i) => ({
315
+ id: typeof raw.id === "string" && raw.id.trim().length > 0 ? raw.id : `group-${i + 1}`,
316
+ targetCardIds: dedupe(Array.isArray(raw.targetCardIds) ? raw.targetCardIds.filter((v) => typeof v === "string") : []),
317
+ supportCardIds: dedupe(Array.isArray(raw.supportCardIds) ? raw.supportCardIds.filter((v) => typeof v === "string") : []),
318
+ supportTagPatterns: dedupe(Array.isArray(raw.supportTagPatterns) ? raw.supportTagPatterns.filter((v) => typeof v === "string") : []),
319
+ freshnessWindowSessions: typeof raw.freshnessWindowSessions === "number" ? raw.freshnessWindowSessions : DEFAULT_FRESHNESS_WINDOW,
320
+ maxDirectTargetsPerRun: typeof raw.maxDirectTargetsPerRun === "number" ? raw.maxDirectTargetsPerRun : DEFAULT_MAX_DIRECT_PER_RUN,
321
+ maxSupportCardsPerRun: typeof raw.maxSupportCardsPerRun === "number" ? raw.maxSupportCardsPerRun : DEFAULT_MAX_SUPPORT_PER_RUN,
322
+ introExposeMinCount: typeof raw.introExposeMinCount === "number" ? raw.introExposeMinCount : DEFAULT_MIN_COUNT,
323
+ hierarchyWalk: {
324
+ enabled: raw.hierarchyWalk?.enabled !== false,
325
+ maxDepth: typeof raw.hierarchyWalk?.maxDepth === "number" ? raw.hierarchyWalk.maxDepth : DEFAULT_HIERARCHY_DEPTH
326
+ },
327
+ retireOnEncounter: raw.retireOnEncounter !== false,
328
+ practiceTagPatterns: dedupe(Array.isArray(raw.practiceTagPatterns) ? raw.practiceTagPatterns.filter((v) => typeof v === "string") : []),
329
+ practiceMinCount: typeof raw.practiceMinCount === "number" ? raw.practiceMinCount : DEFAULT_PRACTICE_MIN_COUNT,
330
+ maxPracticeCardsPerRun: typeof raw.maxPracticeCardsPerRun === "number" ? raw.maxPracticeCardsPerRun : DEFAULT_MAX_PRACTICE_PER_RUN
331
+ })).filter((g) => g.targetCardIds.length > 0) };
332
+ } catch {
333
+ return { groups: [] };
334
+ }
335
+ }
336
+ async loadHierarchyConfigs() {
337
+ try {
338
+ return (await this.course.getAllNavigationStrategies()).filter((s) => s.implementingClass === "hierarchyDefinition").map((s) => {
339
+ try {
340
+ return { prerequisites: JSON.parse(s.serializedData).prerequisites || {} };
341
+ } catch {
342
+ return { prerequisites: {} };
343
+ }
344
+ });
345
+ } catch (e) {
346
+ logger.debug(`[Prescribed] Failed to load hierarchy configs: ${e}`);
347
+ return [];
348
+ }
349
+ }
350
+ buildGroupRuntimeState(args) {
351
+ const { group, priorState, activeIds, seenIds, tagsByCard, cardsByTag, hierarchyConfigs, userTagElo, userGlobalElo } = args;
352
+ const encounteredTargets = /* @__PURE__ */ new Set();
353
+ for (const cardId of group.targetCardIds) if (activeIds.has(cardId) || seenIds.has(cardId)) encounteredTargets.add(cardId);
354
+ if (priorState?.encounteredCardIds?.length) for (const cardId of priorState.encounteredCardIds) encounteredTargets.add(cardId);
355
+ const pendingTargets = group.targetCardIds.filter((id) => !encounteredTargets.has(id));
356
+ const targetTags = /* @__PURE__ */ new Map();
357
+ for (const cardId of pendingTargets) targetTags.set(cardId, tagsByCard.get(cardId) ?? []);
358
+ const blockedTargets = [];
359
+ const surfaceableTargets = [];
360
+ const supportTags = /* @__PURE__ */ new Set();
361
+ for (const cardId of pendingTargets) {
362
+ const tags = targetTags.get(cardId) ?? [];
363
+ const resolution = this.resolveBlockedSupportTags(tags, hierarchyConfigs, userTagElo, userGlobalElo, group.hierarchyWalk?.enabled !== false, group.hierarchyWalk?.maxDepth ?? DEFAULT_HIERARCHY_DEPTH);
364
+ const unmetExposeTags = unmetIntroExposeTags(tags, userTagElo, group.introExposeMinCount ?? DEFAULT_MIN_COUNT);
365
+ if (unmetExposeTags.length > 0) unmetExposeTags.forEach((tag) => supportTags.add(tag));
366
+ if (resolution.blocked || unmetExposeTags.length > 0) {
367
+ blockedTargets.push(cardId);
368
+ resolution.supportTags.forEach((t) => supportTags.add(t));
369
+ } else surfaceableTargets.push(cardId);
370
+ }
371
+ const supportCandidates = dedupe([...group.supportCardIds ?? [], ...this.findSupportCardsByTags(group, tagsByCard, [...supportTags])]).filter((id) => !activeIds.has(id) && !seenIds.has(id));
372
+ const discoveredSupportCandidates = blockedTargets.length > 0 && supportTags.size > 0 && supportCandidates.length === 0 ? this.findDiscoveredSupportCards({
373
+ supportTags: [...supportTags],
374
+ cardsByTag,
375
+ activeIds,
376
+ seenIds,
377
+ excludedIds: new Set([...group.targetCardIds, ...group.supportCardIds ?? []]),
378
+ limit: group.maxSupportCardsPerRun ?? DEFAULT_MAX_SUPPORT_PER_RUN
379
+ }) : [];
380
+ if (blockedTargets.length > 0 && supportTags.size > 0 && discoveredSupportCandidates.length === 0) logger.info(`[Prescribed] Group '${group.id}' discovered 0 broader support candidates (blocked=${blockedTargets.length}; authoredSupport=${supportCandidates.length})`);
381
+ const sessionsSinceSurfaced = priorState?.sessionsSinceSurfaced ?? 0;
382
+ const freshnessWindow = group.freshnessWindowSessions ?? DEFAULT_FRESHNESS_WINDOW;
383
+ const staleSessions = Math.max(0, sessionsSinceSurfaced - freshnessWindow);
384
+ const pressureMultiplier = pendingTargets.length === 0 ? 1 : clamp(1 + staleSessions * .75 + Math.min(2, pendingTargets.length * .1), 1, MAX_TARGET_MULTIPLIER);
385
+ const supportMultiplier = blockedTargets.length === 0 ? 1 : clamp(1 + staleSessions * .5 + Math.min(1.5, blockedTargets.length * .15), 1, MAX_SUPPORT_MULTIPLIER);
386
+ return {
387
+ group,
388
+ encounteredTargets,
389
+ pendingTargets,
390
+ blockedTargets,
391
+ surfaceableTargets,
392
+ targetTags,
393
+ supportCandidates,
394
+ discoveredSupportCandidates,
395
+ supportTags: [...supportTags],
396
+ pressureMultiplier,
397
+ supportMultiplier,
398
+ sessionsSinceSurfaced,
399
+ debugVersion: PRESCRIBED_DEBUG_VERSION
400
+ };
401
+ }
402
+ buildNextGroupState(runtime, prior) {
403
+ const carriedSessions = prior?.sessionsSinceSurfaced ?? 0;
404
+ return {
405
+ encounteredCardIds: [...runtime.encounteredTargets].sort(),
406
+ pendingTargetIds: [...runtime.pendingTargets].sort(),
407
+ lastSurfacedAt: prior?.lastSurfacedAt ?? null,
408
+ sessionsSinceSurfaced: carriedSessions + 1,
409
+ lastSupportAt: prior?.lastSupportAt ?? null,
410
+ blockedTargetIds: [...runtime.blockedTargets].sort(),
411
+ lastResolvedSupportTags: [...runtime.supportTags].sort()
412
+ };
413
+ }
414
+ buildDirectTargetCards(runtime, courseId, emittedIds) {
415
+ const maxDirect = runtime.group.maxDirectTargetsPerRun ?? DEFAULT_MAX_DIRECT_PER_RUN;
416
+ const directIds = runtime.surfaceableTargets.filter((id) => !emittedIds.has(id)).slice(0, maxDirect);
417
+ const cards = [];
418
+ for (const cardId of directIds) {
419
+ emittedIds.add(cardId);
420
+ cards.push({
421
+ cardId,
422
+ courseId,
423
+ score: BASE_TARGET_SCORE * runtime.pressureMultiplier,
424
+ provenance: [{
425
+ strategy: "prescribed",
426
+ strategyName: this.strategyName || this.name,
427
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-prescribed",
428
+ action: "generated",
429
+ score: BASE_TARGET_SCORE * runtime.pressureMultiplier,
430
+ reason: `mode=target;group=${runtime.group.id};pending=${runtime.pendingTargets.length};surfaceable=${runtime.surfaceableTargets.length};blocked=${runtime.blockedTargets.length};blockedTargets=${runtime.blockedTargets.join("|") || "none"};supportTags=${runtime.supportTags.join("|") || "none"};multiplier=${runtime.pressureMultiplier.toFixed(2)};testversion=${runtime.debugVersion}`
431
+ }]
432
+ });
433
+ }
434
+ return cards;
435
+ }
436
+ buildSupportCards(runtime, courseId, emittedIds) {
437
+ if (runtime.blockedTargets.length === 0 || runtime.supportCandidates.length === 0) return [];
438
+ const maxSupport = runtime.group.maxSupportCardsPerRun ?? DEFAULT_MAX_SUPPORT_PER_RUN;
439
+ const supportIds = runtime.supportCandidates.filter((id) => !emittedIds.has(id)).slice(0, maxSupport);
440
+ const cards = [];
441
+ for (const cardId of supportIds) {
442
+ emittedIds.add(cardId);
443
+ cards.push({
444
+ cardId,
445
+ courseId,
446
+ score: BASE_SUPPORT_SCORE * runtime.supportMultiplier,
447
+ provenance: [{
448
+ strategy: "prescribed",
449
+ strategyName: this.strategyName || this.name,
450
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-prescribed",
451
+ action: "generated",
452
+ score: BASE_SUPPORT_SCORE * runtime.supportMultiplier,
453
+ reason: `mode=support;group=${runtime.group.id};pending=${runtime.pendingTargets.length};blocked=${runtime.blockedTargets.length};blockedTargets=${runtime.blockedTargets.join("|") || "none"};supportCard=${cardId};supportTags=${runtime.supportTags.join("|") || "none"};multiplier=${runtime.supportMultiplier.toFixed(2)};testversion=${runtime.debugVersion}`
454
+ }]
455
+ });
456
+ }
457
+ return cards;
458
+ }
459
+ buildDiscoveredSupportCards(runtime, courseId, emittedIds) {
460
+ if (runtime.blockedTargets.length === 0 || runtime.discoveredSupportCandidates.length === 0) return [];
461
+ const maxSupport = runtime.group.maxSupportCardsPerRun ?? DEFAULT_MAX_SUPPORT_PER_RUN;
462
+ const supportIds = runtime.discoveredSupportCandidates.filter((id) => !emittedIds.has(id)).slice(0, maxSupport);
463
+ const cards = [];
464
+ for (const cardId of supportIds) {
465
+ emittedIds.add(cardId);
466
+ cards.push({
467
+ cardId,
468
+ courseId,
469
+ score: DISCOVERED_SUPPORT_SCORE * runtime.supportMultiplier,
470
+ provenance: [{
471
+ strategy: "prescribed",
472
+ strategyName: this.strategyName || this.name,
473
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-prescribed",
474
+ action: "generated",
475
+ score: DISCOVERED_SUPPORT_SCORE * runtime.supportMultiplier,
476
+ reason: `mode=discovered-support;group=${runtime.group.id};pending=${runtime.pendingTargets.length};blocked=${runtime.blockedTargets.length};blockedTargets=${runtime.blockedTargets.join("|") || "none"};supportCard=${cardId};supportTags=${runtime.supportTags.join("|") || "none"};multiplier=${runtime.supportMultiplier.toFixed(2)};testversion=${runtime.debugVersion}`
477
+ }]
478
+ });
479
+ }
480
+ return cards;
481
+ }
482
+ /**
483
+ * Emit drill cards for *unlocked-but-under-practiced* skills.
484
+ *
485
+ * For each course tag matching the group's `practiceTagPatterns` that is both
486
+ * unlocked (all hierarchy prerequisites met — i.e. the learner has been
487
+ * introduced to it) and under-practiced (per-tag attempt count below
488
+ * `practiceMinCount`), this resolves cards carrying that tag and emits them
489
+ * into the candidate pool. It exists because global-ELO retrieval
490
+ * systematically fails to fetch the (low-ELO) drill cards for a
491
+ * freshly-introduced skill — putting them in the pool here guarantees presence.
492
+ *
493
+ * Emphasis is a **practice-debt pressure** (parallel to SRS backlog pressure):
494
+ * cards score `base × multiplier`, where the multiplier starts at
495
+ * PRACTICE_BASE_MULT (so a few reps land promptly post-intro, competing with
496
+ * pressured reviews) and escalates by how long the debt has stayed open
497
+ * (per-tag, time-based via `priorPracticeDebt`/`nextPracticeDebt`), clamped at
498
+ * MAX_PRACTICE_MULTIPLIER. The debt is durable and self-discharges the instant
499
+ * the skill reaches `practiceMinCount` — so this no longer relies on the
500
+ * session-scoped intro boost to actually surface.
501
+ *
502
+ * Fully data-driven: the unlock relation comes from the hierarchy config and
503
+ * practice-status from per-tag ELO. No card-id or tag-namespace hard-coding.
504
+ */
505
+ buildPracticeCards(args) {
506
+ const { group, courseId, emittedIds, cardsByTag, hierarchyConfigs, userTagElo, userGlobalElo, activeIds, seenIds, priorPracticeDebt, nextPracticeDebt } = args;
507
+ const patterns = group.practiceTagPatterns ?? [];
508
+ if (patterns.length === 0) return {
509
+ cards: [],
510
+ debts: []
511
+ };
512
+ const practiceMinCount = group.practiceMinCount ?? DEFAULT_PRACTICE_MIN_COUNT;
513
+ const maxPractice = group.maxPracticeCardsPerRun ?? DEFAULT_MAX_PRACTICE_PER_RUN;
514
+ const practiceTags = [...cardsByTag.keys()].filter((tag) => patterns.some((p) => matchesTagPattern(tag, p)) && this.isUnlockedGatedSkill(tag, hierarchyConfigs, userTagElo, userGlobalElo) && (userTagElo[tag]?.count ?? 0) < practiceMinCount);
515
+ if (practiceTags.length === 0) return {
516
+ cards: [],
517
+ debts: []
518
+ };
519
+ const now = Date.now();
520
+ const DAY_MS = 1440 * 60 * 1e3;
521
+ const tagMultiplier = /* @__PURE__ */ new Map();
522
+ for (const tag of practiceTags) {
523
+ const firstOwedAt = priorPracticeDebt[tag] ?? isoNow();
524
+ nextPracticeDebt[tag] = firstOwedAt;
525
+ const mult = clamp(PRACTICE_BASE_MULT + Math.max(0, (now - new Date(firstOwedAt).getTime()) / DAY_MS) * PRACTICE_STALENESS_BUMP_PER_DAY, PRACTICE_BASE_MULT, MAX_PRACTICE_MULTIPLIER);
526
+ tagMultiplier.set(tag, mult);
527
+ }
528
+ const debts = practiceTags.map((tag) => ({
529
+ tag,
530
+ multiplier: tagMultiplier.get(tag) ?? PRACTICE_BASE_MULT,
531
+ firstOwedAt: nextPracticeDebt[tag]
532
+ })).sort((a, b) => b.multiplier - a.multiplier || a.tag.localeCompare(b.tag));
533
+ const practiceCardIds = this.findDiscoveredSupportCards({
534
+ supportTags: practiceTags,
535
+ cardsByTag,
536
+ activeIds,
537
+ seenIds,
538
+ excludedIds: emittedIds,
539
+ limit: maxPractice
540
+ });
541
+ if (practiceCardIds.length === 0) return {
542
+ cards: [],
543
+ debts
544
+ };
545
+ logger.info(`[Prescribed] Group '${group.id}' practice: ${practiceTags.length} unlocked under-practiced skill(s), emitting ${practiceCardIds.length} drill card(s)`);
546
+ const cards = [];
547
+ for (const cardId of practiceCardIds) {
548
+ emittedIds.add(cardId);
549
+ let mult = PRACTICE_BASE_MULT;
550
+ for (const tag of practiceTags) if (cardsByTag.get(tag)?.includes(cardId) ?? false) mult = Math.max(mult, tagMultiplier.get(tag) ?? PRACTICE_BASE_MULT);
551
+ const score = BASE_PRACTICE_SCORE * mult;
552
+ cards.push({
553
+ cardId,
554
+ courseId,
555
+ score,
556
+ provenance: [{
557
+ strategy: "prescribed",
558
+ strategyName: this.strategyName || this.name,
559
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-prescribed",
560
+ action: "generated",
561
+ score,
562
+ reason: `mode=practice;group=${group.id};debtMult=×${mult.toFixed(2)};underPracticedSkills=${practiceTags.length};practiceTags=${practiceTags.slice(0, 8).join("|")}${practiceTags.length > 8 ? "|…" : ""};testversion=${PRESCRIBED_DEBUG_VERSION}`
563
+ }]
564
+ });
565
+ }
566
+ return {
567
+ cards,
568
+ debts
569
+ };
570
+ }
571
+ /**
572
+ * True for a skill that was *gated and is now reached*: it has at least one
573
+ * declared hierarchy prerequisite set, and every set is fully satisfied by the
574
+ * learner's per-tag ELO. This deliberately EXCLUDES tags with no prerequisites
575
+ * — an ungated tag was never "introduced" in the curricular sense, so it isn't
576
+ * a post-intro drill target (e.g. whole-word spelling tags that share the
577
+ * `gpc:exercise:*` prefix but have no intro gate). Those are left to normal
578
+ * ELO retrieval. This is the precise population the retrieval gap strands:
579
+ * just-unlocked, low-ELO skills.
580
+ */
581
+ isUnlockedGatedSkill(tag, hierarchyConfigs, userTagElo, userGlobalElo) {
582
+ const prereqSets = hierarchyConfigs.map((hierarchy) => hierarchy.prerequisites[tag]).filter((prereqs) => Array.isArray(prereqs) && prereqs.length > 0);
583
+ if (prereqSets.length === 0) return false;
584
+ return prereqSets.every((prereqs) => prereqs.every((pr) => this.isPrerequisiteMet(pr, userTagElo[pr.tag], userGlobalElo)));
585
+ }
586
+ findSupportCardsByTags(group, tagsByCard, supportTags) {
587
+ if (supportTags.length === 0) return [];
588
+ const explicitSupportIds = group.supportCardIds ?? [];
589
+ const explicitPatterns = group.supportTagPatterns ?? [];
590
+ if (explicitSupportIds.length === 0 && explicitPatterns.length === 0) return [];
591
+ const candidates = /* @__PURE__ */ new Set();
592
+ for (const cardId of explicitSupportIds) {
593
+ const cardTags = tagsByCard.get(cardId) ?? [];
594
+ const matchesResolved = supportTags.some((supportTag) => cardTags.includes(supportTag));
595
+ const matchesPattern = explicitPatterns.some((pattern) => cardTags.some((tag) => matchesTagPattern(tag, pattern)));
596
+ if (matchesResolved || matchesPattern) candidates.add(cardId);
597
+ }
598
+ return [...candidates];
599
+ }
600
+ findDiscoveredSupportCards(args) {
601
+ const { supportTags, cardsByTag, activeIds, seenIds, excludedIds, limit } = args;
602
+ const byCardId = /* @__PURE__ */ new Map();
603
+ for (const supportTag of supportTags) {
604
+ const taggedCards = cardsByTag.get(supportTag) ?? [];
605
+ for (const cardId of taggedCards) {
606
+ if (activeIds.has(cardId) || seenIds.has(cardId) || excludedIds.has(cardId)) continue;
607
+ const existing = byCardId.get(cardId);
608
+ if (existing) existing.matches += 1;
609
+ else byCardId.set(cardId, {
610
+ cardId,
611
+ matches: 1
612
+ });
613
+ }
614
+ }
615
+ const candidates = [...byCardId.values()].sort((a, b) => b.matches - a.matches || a.cardId.localeCompare(b.cardId));
616
+ const usedStems = /* @__PURE__ */ new Set();
617
+ const diverse = [];
618
+ const deferred = [];
619
+ for (const entry of candidates) {
620
+ const stem = extractWordStem(entry.cardId);
621
+ if (!usedStems.has(stem)) {
622
+ usedStems.add(stem);
623
+ diverse.push(entry);
624
+ } else deferred.push(entry);
625
+ }
626
+ shuffleInPlace(diverse);
627
+ shuffleInPlace(deferred);
628
+ return [...diverse, ...deferred].slice(0, limit).map((entry) => entry.cardId);
629
+ }
630
+ resolveBlockedSupportTags(targetTags, hierarchyConfigs, userTagElo, userGlobalElo, hierarchyWalkEnabled, maxDepth) {
631
+ const supportTags = /* @__PURE__ */ new Set();
632
+ let blocked = false;
633
+ for (const targetTag of targetTags) {
634
+ const prereqSets = hierarchyConfigs.map((hierarchy) => hierarchy.prerequisites[targetTag]).filter((prereqs) => Array.isArray(prereqs) && prereqs.length > 0);
635
+ if (prereqSets.length === 0) continue;
636
+ if (!prereqSets.some((prereqs) => prereqs.some((pr) => !this.isPrerequisiteMet(pr, userTagElo[pr.tag], userGlobalElo)))) continue;
637
+ blocked = true;
638
+ if (!hierarchyWalkEnabled) {
639
+ for (const prereqs of prereqSets) for (const prereq of prereqs) if (!this.isPrerequisiteMet(prereq, userTagElo[prereq.tag], userGlobalElo)) supportTags.add(prereq.tag);
640
+ continue;
641
+ }
642
+ for (const prereqs of prereqSets) for (const prereq of prereqs) if (!this.isPrerequisiteMet(prereq, userTagElo[prereq.tag], userGlobalElo)) this.collectSupportTagsRecursive(prereq.tag, hierarchyConfigs, userTagElo, userGlobalElo, maxDepth, /* @__PURE__ */ new Set(), supportTags);
643
+ }
644
+ return {
645
+ blocked,
646
+ supportTags: [...supportTags]
647
+ };
648
+ }
649
+ collectSupportTagsRecursive(tag, hierarchyConfigs, userTagElo, userGlobalElo, depth, visited, out) {
650
+ if (depth < 0 || visited.has(tag)) return;
651
+ visited.add(tag);
652
+ let walkedFurther = false;
653
+ for (const hierarchy of hierarchyConfigs) {
654
+ const prereqs = hierarchy.prerequisites[tag];
655
+ if (!prereqs || prereqs.length === 0) continue;
656
+ const unmet = prereqs.filter((pr) => !this.isPrerequisiteMet(pr, userTagElo[pr.tag], userGlobalElo));
657
+ if (unmet.length > 0 && depth > 0) {
658
+ walkedFurther = true;
659
+ for (const prereq of unmet) this.collectSupportTagsRecursive(prereq.tag, hierarchyConfigs, userTagElo, userGlobalElo, depth - 1, visited, out);
660
+ }
661
+ }
662
+ if (!walkedFurther) out.add(tag);
663
+ }
664
+ isPrerequisiteMet(prereq, userTagElo, userGlobalElo) {
665
+ if (!userTagElo) return false;
666
+ const minCount = prereq.masteryThreshold?.minCount ?? DEFAULT_MIN_COUNT;
667
+ if (userTagElo.count < minCount) return false;
668
+ if (prereq.masteryThreshold?.minElo !== void 0) return userTagElo.score >= prereq.masteryThreshold.minElo;
669
+ if (prereq.masteryThreshold?.minCount !== void 0) return true;
670
+ return userTagElo.score >= userGlobalElo;
671
+ }
672
+ };
673
+ //#endregion
674
+ export { PrescribedCardsGenerator as default };
675
+
676
+ //# sourceMappingURL=prescribed.mjs.map