@vue-skuilder/db 0.2.35 → 0.2.37

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