@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,151 @@
1
+ import "../_virtual/_rolldown/runtime.mjs";
2
+ //#region src/diagnostics/loader.ts
3
+ /** couch_peruser convention: `userdb-` + lowercase hex of the username's UTF-8 bytes. */
4
+ function userDbName(username) {
5
+ let hex = "";
6
+ for (const b of new TextEncoder().encode(username)) hex += b.toString(16).padStart(2, "0");
7
+ return "userdb-" + hex;
8
+ }
9
+ function base64(s) {
10
+ let binary = "";
11
+ for (const b of new TextEncoder().encode(s)) binary += String.fromCharCode(b);
12
+ return btoa(binary);
13
+ }
14
+ /** Drop trailing slashes. A loop, not `/\/+$/`, which is quadratic on long runs of '/'. */
15
+ function trimTrailingSlashes(url) {
16
+ let end = url.length;
17
+ while (end > 0 && url[end - 1] === "/") end--;
18
+ return url.slice(0, end);
19
+ }
20
+ /** A tiny read-only couch client. No Pouch, no user object, no sync. */
21
+ function couchReader(opts) {
22
+ const doFetch = opts.fetchImpl ?? fetch;
23
+ const base = trimTrailingSlashes(opts.couchUrl);
24
+ const headers = { Accept: "application/json" };
25
+ if (opts.auth.kind === "basic") headers.Authorization = "Basic " + base64(`${opts.auth.username}:${opts.auth.password}`);
26
+ const credentials = opts.auth.kind === "cookie" ? "include" : void 0;
27
+ async function get(path, init = {}) {
28
+ const res = await doFetch(`${base}/${path}`, {
29
+ method: init.method ?? "GET",
30
+ headers: init.body ? {
31
+ ...headers,
32
+ "Content-Type": "application/json"
33
+ } : headers,
34
+ ...init.body ? { body: JSON.stringify(init.body) } : {},
35
+ ...credentials ? { credentials } : {}
36
+ });
37
+ if (!res.ok) {
38
+ const detail = await res.text().catch(() => "");
39
+ throw new Error(`[diagnostics] ${init.method ?? "GET"} ${path} -> ${res.status} ${detail}`);
40
+ }
41
+ return await res.json();
42
+ }
43
+ async function byKeys(db, keys) {
44
+ const out = [];
45
+ const CHUNK = 500;
46
+ for (let i = 0; i < keys.length; i += CHUNK) {
47
+ const body = await get(`${db}/_all_docs?include_docs=true`, {
48
+ method: "POST",
49
+ body: { keys: keys.slice(i, i + CHUNK) }
50
+ });
51
+ for (const row of body.rows) if (row.doc) out.push(row.doc);
52
+ }
53
+ return out;
54
+ }
55
+ async function byPrefix(db, prefix) {
56
+ return (await get(`${db}/_all_docs?${new URLSearchParams({
57
+ include_docs: "true",
58
+ startkey: JSON.stringify(prefix),
59
+ endkey: JSON.stringify(prefix + "￰")
60
+ })}`)).rows.map((r) => r.doc).filter((d) => !!d);
61
+ }
62
+ return {
63
+ base,
64
+ get,
65
+ byKeys,
66
+ byPrefix
67
+ };
68
+ }
69
+ /** Card ids the user has any trace of: history, pending schedule, or session ELO events. */
70
+ function touchedCardIds(docs) {
71
+ const ids = /* @__PURE__ */ new Set();
72
+ for (const d of docs) if (d._id.startsWith("cardH") && typeof d.cardID === "string") ids.add(d.cardID);
73
+ else if (d._id.startsWith("card_review_") && typeof d.cardId === "string") ids.add(d.cardId);
74
+ else if (d._id.startsWith("SESSION::") && Array.isArray(d.eloEvents)) {
75
+ for (const e of d.eloEvents) if (e.cardId) ids.add(e.cardId);
76
+ }
77
+ return [...ids];
78
+ }
79
+ /**
80
+ * Read one learner's records for one course into a {@link LearnerDump}: the
81
+ * whole user DB, its tombstones, and (by default) the course cards the user
82
+ * has touched, with their displayable data and tags, plus the course's strategy
83
+ * docs. Needs admin rights on the couch, via basic auth or the browser's
84
+ * session cookie.
85
+ */
86
+ async function fetchLearnerDump(opts) {
87
+ const couch = couchReader(opts);
88
+ const dbName = userDbName(opts.username);
89
+ const fetchedAt = (/* @__PURE__ */ new Date()).toISOString();
90
+ const info = await couch.get(dbName);
91
+ const q = new URLSearchParams({ include_docs: "true" });
92
+ if (opts.attachments) q.set("attachments", "true");
93
+ const docs = (await couch.get(`${dbName}/_all_docs?${q}`)).rows.map((r) => r.doc).filter((d) => !!d);
94
+ const tombstones = (await couch.get(`${dbName}/_changes?style=main_only`)).results.filter((c) => c.deleted).map((c) => ({
95
+ id: c.id,
96
+ rev: c.changes[0]?.rev,
97
+ seq: Number(String(c.seq).split("-")[0])
98
+ }));
99
+ const scope = opts.cards ?? "touched";
100
+ let course;
101
+ if (scope !== "none") {
102
+ const courseDb = `coursedb-${opts.courseId}`;
103
+ let cards;
104
+ if (scope === "all") cards = (await couch.get(`${courseDb}/_find`, {
105
+ method: "POST",
106
+ body: {
107
+ selector: { docType: "CARD" },
108
+ limit: 1e6
109
+ }
110
+ })).docs;
111
+ else cards = await couch.byKeys(courseDb, touchedCardIds(docs));
112
+ const cardIds = new Set(cards.map((c) => c._id));
113
+ const ddIds = /* @__PURE__ */ new Set();
114
+ for (const c of cards) for (const id of c.id_displayable_data ?? []) ddIds.add(id);
115
+ const displayableData = await couch.byKeys(courseDb, [...ddIds]);
116
+ const tags = (await couch.byPrefix(courseDb, "TAG")).map((t) => {
117
+ const tagged = Array.isArray(t.taggedCards) ? t.taggedCards : [];
118
+ return {
119
+ ...t,
120
+ taggedCount: tagged.length,
121
+ taggedCards: scope === "all" ? tagged : tagged.filter((id) => cardIds.has(id))
122
+ };
123
+ }).filter((t) => scope === "all" || t.taggedCards.length > 0);
124
+ const strategies = await couch.byPrefix(courseDb, "NAVIGATION_STRATEGY");
125
+ course = {
126
+ courseId: opts.courseId,
127
+ source: `${couch.base}/${courseDb}`,
128
+ scope,
129
+ cards,
130
+ displayableData,
131
+ tags,
132
+ strategies
133
+ };
134
+ }
135
+ return {
136
+ formatVersion: 1,
137
+ username: opts.username,
138
+ dbName,
139
+ source: couch.base,
140
+ fetchedAt,
141
+ courseId: opts.courseId,
142
+ info,
143
+ docs,
144
+ tombstones,
145
+ ...course ? { course } : {}
146
+ };
147
+ }
148
+ //#endregion
149
+ export { fetchLearnerDump, userDbName };
150
+
151
+ //# sourceMappingURL=loader.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loader.mjs","names":[],"sources":["../../src/diagnostics/loader.ts"],"sourcesContent":["import type { CourseSlice, LearnerDump } from './dataset';\n\ntype RawDoc = { _id: string; [key: string]: unknown };\n\nexport type CouchAuth =\n | { kind: 'basic'; username: string; password: string }\n /** Browser: the signed-in admin's couch session cookie. */\n | { kind: 'cookie' };\n\nexport interface FetchLearnerDumpOptions {\n /** Couch base URL, e.g. `https://example.com/couch`. */\n couchUrl: string;\n username: string;\n courseId: string;\n auth: CouchAuth;\n /** Course-DB slice to include. Default `touched`. */\n cards?: 'touched' | 'all' | 'none';\n /** Inline user-DB attachments as base64. Default false. */\n attachments?: boolean;\n /** Defaults to the global `fetch`. */\n fetchImpl?: typeof fetch;\n}\n\n/** couch_peruser convention: `userdb-` + lowercase hex of the username's UTF-8 bytes. */\nexport function userDbName(username: string): string {\n let hex = '';\n for (const b of new TextEncoder().encode(username)) hex += b.toString(16).padStart(2, '0');\n return 'userdb-' + hex;\n}\n\nfunction base64(s: string): string {\n let binary = '';\n for (const b of new TextEncoder().encode(s)) binary += String.fromCharCode(b);\n return btoa(binary);\n}\n\n/** Drop trailing slashes. A loop, not `/\\/+$/`, which is quadratic on long runs of '/'. */\nfunction trimTrailingSlashes(url: string): string {\n let end = url.length;\n while (end > 0 && url[end - 1] === '/') end--;\n return url.slice(0, end);\n}\n\n/** A tiny read-only couch client. No Pouch, no user object, no sync. */\nfunction couchReader(opts: FetchLearnerDumpOptions) {\n const doFetch = opts.fetchImpl ?? fetch;\n const base = trimTrailingSlashes(opts.couchUrl);\n const headers: Record<string, string> = { Accept: 'application/json' };\n if (opts.auth.kind === 'basic') {\n headers.Authorization = 'Basic ' + base64(`${opts.auth.username}:${opts.auth.password}`);\n }\n const credentials: RequestCredentials | undefined =\n opts.auth.kind === 'cookie' ? 'include' : undefined;\n\n async function get<T>(path: string, init: { method?: string; body?: unknown } = {}): Promise<T> {\n const res = await doFetch(`${base}/${path}`, {\n method: init.method ?? 'GET',\n headers: init.body ? { ...headers, 'Content-Type': 'application/json' } : headers,\n ...(init.body ? { body: JSON.stringify(init.body) } : {}),\n ...(credentials ? { credentials } : {}),\n });\n if (!res.ok) {\n const detail = await res.text().catch(() => '');\n throw new Error(`[diagnostics] ${init.method ?? 'GET'} ${path} -> ${res.status} ${detail}`);\n }\n return (await res.json()) as T;\n }\n\n async function byKeys(db: string, keys: string[]): Promise<RawDoc[]> {\n const out: RawDoc[] = [];\n const CHUNK = 500;\n for (let i = 0; i < keys.length; i += CHUNK) {\n const body = await get<{ rows: Array<{ doc?: RawDoc | null }> }>(\n `${db}/_all_docs?include_docs=true`,\n { method: 'POST', body: { keys: keys.slice(i, i + CHUNK) } }\n );\n for (const row of body.rows) if (row.doc) out.push(row.doc);\n }\n return out;\n }\n\n async function byPrefix(db: string, prefix: string): Promise<RawDoc[]> {\n const q = new URLSearchParams({\n include_docs: 'true',\n startkey: JSON.stringify(prefix),\n endkey: JSON.stringify(prefix + '￰'),\n });\n const body = await get<{ rows: Array<{ doc?: RawDoc }> }>(`${db}/_all_docs?${q}`);\n return body.rows.map((r) => r.doc).filter((d): d is RawDoc => !!d);\n }\n\n return { base, get, byKeys, byPrefix };\n}\n\n/** Card ids the user has any trace of: history, pending schedule, or session ELO events. */\nfunction touchedCardIds(docs: RawDoc[]): string[] {\n const ids = new Set<string>();\n for (const d of docs) {\n if (d._id.startsWith('cardH') && typeof d.cardID === 'string') ids.add(d.cardID);\n else if (d._id.startsWith('card_review_') && typeof d.cardId === 'string') ids.add(d.cardId);\n else if (d._id.startsWith('SESSION::') && Array.isArray(d.eloEvents)) {\n for (const e of d.eloEvents as Array<{ cardId?: string }>) if (e.cardId) ids.add(e.cardId);\n }\n }\n return [...ids];\n}\n\n/**\n * Read one learner's records for one course into a {@link LearnerDump}: the\n * whole user DB, its tombstones, and (by default) the course cards the user\n * has touched, with their displayable data and tags, plus the course's strategy\n * docs. Needs admin rights on the couch, via basic auth or the browser's\n * session cookie.\n */\nexport async function fetchLearnerDump(opts: FetchLearnerDumpOptions): Promise<LearnerDump> {\n const couch = couchReader(opts);\n const dbName = userDbName(opts.username);\n const fetchedAt = new Date().toISOString();\n\n const info = await couch.get<unknown>(dbName);\n\n const q = new URLSearchParams({ include_docs: 'true' });\n if (opts.attachments) q.set('attachments', 'true');\n const all = await couch.get<{ rows: Array<{ doc?: RawDoc }> }>(`${dbName}/_all_docs?${q}`);\n const docs = all.rows.map((r) => r.doc).filter((d): d is RawDoc => !!d);\n\n const changes = await couch.get<{\n results: Array<{\n id: string;\n seq: string | number;\n deleted?: boolean;\n changes: Array<{ rev: string }>;\n }>;\n }>(`${dbName}/_changes?style=main_only`);\n const tombstones = changes.results\n .filter((c) => c.deleted)\n .map((c) => ({ id: c.id, rev: c.changes[0]?.rev, seq: Number(String(c.seq).split('-')[0]) }));\n\n const scope = opts.cards ?? 'touched';\n let course: CourseSlice | undefined;\n if (scope !== 'none') {\n const courseDb = `coursedb-${opts.courseId}`;\n let cards: RawDoc[];\n if (scope === 'all') {\n const found = await couch.get<{ docs: RawDoc[] }>(`${courseDb}/_find`, {\n method: 'POST',\n body: { selector: { docType: 'CARD' }, limit: 1_000_000 },\n });\n cards = found.docs;\n } else {\n cards = await couch.byKeys(courseDb, touchedCardIds(docs));\n }\n const cardIds = new Set(cards.map((c) => c._id));\n const ddIds = new Set<string>();\n for (const c of cards) {\n for (const id of (c.id_displayable_data as string[] | undefined) ?? []) ddIds.add(id);\n }\n const displayableData = await couch.byKeys(courseDb, [...ddIds]);\n const tags = (await couch.byPrefix(courseDb, 'TAG'))\n .map((t) => {\n const tagged = Array.isArray(t.taggedCards) ? (t.taggedCards as string[]) : [];\n return {\n ...t,\n taggedCount: tagged.length,\n taggedCards: scope === 'all' ? tagged : tagged.filter((id) => cardIds.has(id)),\n };\n })\n .filter((t) => scope === 'all' || t.taggedCards.length > 0);\n const strategies = await couch.byPrefix(courseDb, 'NAVIGATION_STRATEGY');\n\n course = {\n courseId: opts.courseId,\n source: `${couch.base}/${courseDb}`,\n scope,\n cards,\n displayableData,\n tags,\n strategies,\n } as unknown as CourseSlice;\n }\n\n return {\n formatVersion: 1,\n username: opts.username,\n dbName,\n source: couch.base,\n fetchedAt,\n courseId: opts.courseId,\n info,\n docs,\n tombstones,\n ...(course ? { course } : {}),\n };\n}\n"],"mappings":";;;AAwBA,SAAgB,WAAW,UAA0B;CACnD,IAAI,MAAM;AACV,MAAK,MAAM,KAAK,IAAI,aAAa,CAAC,OAAO,SAAS,CAAE,QAAO,EAAE,SAAS,GAAG,CAAC,SAAS,GAAG,IAAI;AAC1F,QAAO,YAAY;;AAGrB,SAAS,OAAO,GAAmB;CACjC,IAAI,SAAS;AACb,MAAK,MAAM,KAAK,IAAI,aAAa,CAAC,OAAO,EAAE,CAAE,WAAU,OAAO,aAAa,EAAE;AAC7E,QAAO,KAAK,OAAO;;;AAIrB,SAAS,oBAAoB,KAAqB;CAChD,IAAI,MAAM,IAAI;AACd,QAAO,MAAM,KAAK,IAAI,MAAM,OAAO,IAAK;AACxC,QAAO,IAAI,MAAM,GAAG,IAAI;;;AAI1B,SAAS,YAAY,MAA+B;CAClD,MAAM,UAAU,KAAK,aAAa;CAClC,MAAM,OAAO,oBAAoB,KAAK,SAAS;CAC/C,MAAM,UAAkC,EAAE,QAAQ,oBA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}
@@ -0,0 +1,161 @@
1
+ import "../_virtual/_rolldown/runtime.mjs";
2
+ //#region src/diagnostics/pipeline.ts
3
+ /**
4
+ * What put a run's card in the queue: the hint that required it, else the
5
+ * generator that produced it. Its `origin` says what it is (review or new).
6
+ */
7
+ function runCardSource(card) {
8
+ if (card.required) return `required: ${card.required}`;
9
+ return card.generator ?? "unknown";
10
+ }
11
+ /**
12
+ * A run's selected cards counted by source, most first. Empty for runs that
13
+ * don't persist their cards (before 0.2.28).
14
+ */
15
+ function selectedBySource(run) {
16
+ const counts = /* @__PURE__ */ new Map();
17
+ for (const c of run.cards ?? []) {
18
+ if (!c.selected) continue;
19
+ const source = runCardSource(c);
20
+ counts.set(source, (counts.get(source) ?? 0) + 1);
21
+ }
22
+ return [...counts].map(([source, count]) => ({
23
+ source,
24
+ count
25
+ })).sort((a, b) => b.count - a.count);
26
+ }
27
+ /** Aggregate a learner's persisted pipeline runs, optionally only sessions started at or after `since` (ISO). */
28
+ function pipelineRunStats(ds, opts = {}) {
29
+ const sessions = ds.sessions.filter((s) => !opts.since || s.startTime >= opts.since);
30
+ const recordsBySession = /* @__PURE__ */ new Map();
31
+ for (const h of ds.cardHistories) for (const record of h.records) {
32
+ if (!record.sessionId) continue;
33
+ const list = recordsBySession.get(record.sessionId) ?? [];
34
+ list.push({
35
+ cardId: h.cardID,
36
+ record
37
+ });
38
+ recordsBySession.set(record.sessionId, list);
39
+ }
40
+ const gens = /* @__PURE__ */ new Map();
41
+ const gen = (name) => {
42
+ let g = gens.get(name);
43
+ if (!g) {
44
+ g = {
45
+ name,
46
+ runs: 0,
47
+ cards: 0,
48
+ newCards: 0,
49
+ reviewCards: 0,
50
+ topScoreMax: 0,
51
+ topScoreLast: 0,
52
+ selected: 0,
53
+ firstAttempts: 0,
54
+ firstAttemptsCorrect: 0
55
+ };
56
+ gens.set(name, g);
57
+ }
58
+ return g;
59
+ };
60
+ const filters = /* @__PURE__ */ new Map();
61
+ const regulators = /* @__PURE__ */ new Map();
62
+ let runs = 0;
63
+ let runsWithSelection = 0;
64
+ let selectedUnattributed = 0;
65
+ let firstRunAt;
66
+ let lastRunAt;
67
+ for (const session of sessions) {
68
+ const originBySelectedCard = /* @__PURE__ */ new Map();
69
+ for (const run of session.runs ?? []) {
70
+ runs++;
71
+ if (!firstRunAt || run.at < firstRunAt) firstRunAt = run.at;
72
+ if (!lastRunAt || run.at > lastRunAt) lastRunAt = run.at;
73
+ for (const s of run.generators ?? []) {
74
+ const g = gen(s.name);
75
+ g.runs++;
76
+ g.cards += s.cardCount;
77
+ g.newCards += s.newCount;
78
+ g.reviewCards += s.reviewCount;
79
+ g.topScoreMax = Math.max(g.topScoreMax, s.topScore);
80
+ g.topScoreLast = s.topScore;
81
+ }
82
+ for (const f of run.filters ?? []) {
83
+ const acc = filters.get(f.name) ?? {
84
+ name: f.name,
85
+ runs: 0,
86
+ boosted: 0,
87
+ penalized: 0,
88
+ passed: 0,
89
+ removed: 0
90
+ };
91
+ acc.runs++;
92
+ if (f.kind) acc.kind = f.kind;
93
+ acc.boosted += f.boosted;
94
+ acc.penalized += f.penalized;
95
+ acc.passed += f.passed;
96
+ acc.removed += f.removed;
97
+ filters.set(f.name, acc);
98
+ }
99
+ for (const r of run.regulators ?? []) {
100
+ const acc = regulators.get(r.name) ?? {
101
+ name: r.name,
102
+ class: r.class,
103
+ runs: 0,
104
+ meanMultiplier: 0,
105
+ maxMultiplier: 0,
106
+ runsActive: 0,
107
+ last: r,
108
+ sumMultiplier: 0
109
+ };
110
+ acc.runs++;
111
+ acc.sumMultiplier += r.multiplier;
112
+ acc.maxMultiplier = Math.max(acc.maxMultiplier, r.multiplier);
113
+ if (r.multiplier > 1) acc.runsActive++;
114
+ acc.last = r;
115
+ regulators.set(r.name, acc);
116
+ }
117
+ if (run.cards) {
118
+ runsWithSelection++;
119
+ for (const c of run.cards) {
120
+ if (!c.selected) continue;
121
+ if (!c.generator) {
122
+ selectedUnattributed++;
123
+ continue;
124
+ }
125
+ gen(c.generator).selected++;
126
+ if (!originBySelectedCard.has(c.cardId)) originBySelectedCard.set(c.cardId, c.generator);
127
+ }
128
+ }
129
+ }
130
+ for (const { cardId, record } of recordsBySession.get(session.sessionId) ?? []) {
131
+ const origin = originBySelectedCard.get(cardId);
132
+ if (!origin || record.priorAttemps !== 0) continue;
133
+ const g = gen(origin);
134
+ g.firstAttempts++;
135
+ if (record.isCorrect === true) g.firstAttemptsCorrect++;
136
+ }
137
+ }
138
+ return {
139
+ sessions: sessions.length,
140
+ runs,
141
+ runsWithSelection,
142
+ firstRunAt,
143
+ lastRunAt,
144
+ generators: [...gens.values()].map(({ cards, newCards, reviewCards, ...g }) => ({
145
+ ...g,
146
+ meanCards: g.runs ? cards / g.runs : 0,
147
+ meanNew: g.runs ? newCards / g.runs : 0,
148
+ meanReview: g.runs ? reviewCards / g.runs : 0
149
+ })).sort((a, b) => b.runs - a.runs || a.name.localeCompare(b.name)),
150
+ filters: [...filters.values()].sort((a, b) => a.name.localeCompare(b.name)),
151
+ regulators: [...regulators.values()].map(({ sumMultiplier, ...r }) => ({
152
+ ...r,
153
+ meanMultiplier: r.runs ? sumMultiplier / r.runs : 0
154
+ })),
155
+ selectedUnattributed
156
+ };
157
+ }
158
+ //#endregion
159
+ export { pipelineRunStats, runCardSource, selectedBySource };
160
+
161
+ //# sourceMappingURL=pipeline.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pipeline.mjs","names":[],"sources":["../../src/diagnostics/pipeline.ts"],"sourcesContent":["import type { DatasetRecord, LearnerDataset } from './dataset';\nimport type { FilterKind } from '../core/navigators/filters/types';\nimport type { RegulatorName, RegulatorReading } from '../core/navigators/regulators';\nimport type { StudySessionRunCard, StudySessionRunSummary } from '../core/types/studySession';\n\n/**\n * What put a run's card in the queue: the hint that required it, else the\n * generator that produced it. Its `origin` says what it is (review or new).\n */\nexport function runCardSource(card: Pick<StudySessionRunCard, 'generator' | 'required'>): string {\n if (card.required) return `required: ${card.required}`;\n return card.generator ?? 'unknown';\n}\n\n/**\n * A run's selected cards counted by source, most first. Empty for runs that\n * don't persist their cards (before 0.2.28).\n */\nexport function selectedBySource(\n run: Pick<StudySessionRunSummary, 'cards'>\n): Array<{ source: string; count: number }> {\n const counts = new Map<string, number>();\n for (const c of run.cards ?? []) {\n if (!c.selected) continue;\n const source = runCardSource(c);\n counts.set(source, (counts.get(source) ?? 0) + 1);\n }\n return [...counts]\n .map(([source, count]) => ({ source, count }))\n .sort((a, b) => b.count - a.count);\n}\n\n// ============================================================================\n// Pipeline run stats\n// ============================================================================\n//\n// What each pipeline piece did across a learner's persisted runs, keyed by the\n// names runs report generators and filters under. Those are the strategy docs'\n// names, so these join to a `PipelinePlan` (`@vue-skuilder/db`) by name.\n//\n// Selection and outcome counts need runs that persist their selected cards\n// (`StudySessionRunSummary.cards`, 0.2.28+). Older runs contribute only their\n// generator and filter summaries.\n//\n// Generator new/review counts: before 0.2.29 the ELO generator's cards were\n// counted as neither (the counts went by reason text), so means over older\n// runs undercount `new`.\n//\n// ============================================================================\n\n/** One generator across persisted runs. */\nexport interface GeneratorRunStat {\n /** The name runs report it under (its strategy doc's name). */\n name: string;\n /** Runs it emitted at least one candidate in. */\n runs: number;\n /** Mean candidates per run, over the runs it appeared in. */\n meanCards: number;\n meanNew: number;\n meanReview: number;\n topScoreMax: number;\n /** Top score in the most recent run it appeared in. */\n topScoreLast: number;\n /** Selected cards it originated (first provenance entry), over runs that persist selection. */\n selected: number;\n /** First attempts at those cards in the same session. */\n firstAttempts: number;\n firstAttemptsCorrect: number;\n}\n\n/** One filter across persisted runs: candidate counts summed over runs. */\nexport interface FilterRunStat {\n name: string;\n /** As recorded by the most recent run that recorded it (0.2.29+). */\n kind?: FilterKind;\n runs: number;\n boosted: number;\n penalized: number;\n passed: number;\n removed: number;\n}\n\n/** One regulator across persisted runs (0.2.29+). */\nexport interface RegulatorRunStat {\n name: RegulatorName;\n class: RegulatorReading['class'];\n runs: number;\n meanMultiplier: number;\n maxMultiplier: number;\n /** Runs where the multiplier was above 1. */\n runsActive: number;\n /** The most recent reading. */\n last: RegulatorReading;\n}\n\nexport interface PipelineRunStats {\n sessions: number;\n runs: number;\n /** Runs that persist their selected cards. Selection and outcome counts cover only these. */\n runsWithSelection: number;\n firstRunAt?: string;\n lastRunAt?: string;\n /** Busiest first. */\n generators: GeneratorRunStat[];\n /** By name. */\n filters: FilterRunStat[];\n /** Empty before 0.2.29. */\n regulators: RegulatorRunStat[];\n /** Selected cards with no originating generator: cards forced in by `requireCards`. */\n selectedUnattributed: number;\n}\n\n/** Aggregate a learner's persisted pipeline runs, optionally only sessions started at or after `since` (ISO). */\nexport function pipelineRunStats(\n ds: LearnerDataset,\n opts: { since?: string } = {}\n): PipelineRunStats {\n const sessions = ds.sessions.filter((s) => !opts.since || s.startTime >= opts.since);\n\n const recordsBySession = new Map<string, Array<{ cardId: string; record: DatasetRecord }>>();\n for (const h of ds.cardHistories) {\n for (const record of h.records) {\n if (!record.sessionId) continue;\n const list = recordsBySession.get(record.sessionId) ?? [];\n list.push({ cardId: h.cardID, record });\n recordsBySession.set(record.sessionId, list);\n }\n }\n\n type GenAcc = Omit<GeneratorRunStat, 'meanCards' | 'meanNew' | 'meanReview'> & {\n cards: number;\n newCards: number;\n reviewCards: number;\n };\n const gens = new Map<string, GenAcc>();\n const gen = (name: string): GenAcc => {\n let g = gens.get(name);\n if (!g) {\n g = {\n name,\n runs: 0,\n cards: 0,\n newCards: 0,\n reviewCards: 0,\n topScoreMax: 0,\n topScoreLast: 0,\n selected: 0,\n firstAttempts: 0,\n firstAttemptsCorrect: 0,\n };\n gens.set(name, g);\n }\n return g;\n };\n const filters = new Map<string, FilterRunStat>();\n const regulators = new Map<RegulatorName, RegulatorRunStat & { sumMultiplier: number }>();\n\n let runs = 0;\n let runsWithSelection = 0;\n let selectedUnattributed = 0;\n let firstRunAt: string | undefined;\n let lastRunAt: string | undefined;\n\n for (const session of sessions) {\n // A card selected by several runs is credited to the first run that chose it.\n const originBySelectedCard = new Map<string, string>();\n\n for (const run of session.runs ?? []) {\n runs++;\n if (!firstRunAt || run.at < firstRunAt) firstRunAt = run.at;\n if (!lastRunAt || run.at > lastRunAt) lastRunAt = run.at;\n\n for (const s of run.generators ?? []) {\n const g = gen(s.name);\n g.runs++;\n g.cards += s.cardCount;\n g.newCards += s.newCount;\n g.reviewCards += s.reviewCount;\n g.topScoreMax = Math.max(g.topScoreMax, s.topScore);\n g.topScoreLast = s.topScore;\n }\n\n for (const f of run.filters ?? []) {\n const acc = filters.get(f.name) ?? {\n name: f.name,\n runs: 0,\n boosted: 0,\n penalized: 0,\n passed: 0,\n removed: 0,\n };\n acc.runs++;\n if (f.kind) acc.kind = f.kind;\n acc.boosted += f.boosted;\n acc.penalized += f.penalized;\n acc.passed += f.passed;\n acc.removed += f.removed;\n filters.set(f.name, acc);\n }\n\n for (const r of run.regulators ?? []) {\n const acc = regulators.get(r.name) ?? {\n name: r.name,\n class: r.class,\n runs: 0,\n meanMultiplier: 0,\n maxMultiplier: 0,\n runsActive: 0,\n last: r,\n sumMultiplier: 0,\n };\n acc.runs++;\n acc.sumMultiplier += r.multiplier;\n acc.maxMultiplier = Math.max(acc.maxMultiplier, r.multiplier);\n if (r.multiplier > 1) acc.runsActive++;\n acc.last = r;\n regulators.set(r.name, acc);\n }\n\n if (run.cards) {\n runsWithSelection++;\n for (const c of run.cards) {\n if (!c.selected) continue;\n if (!c.generator) {\n selectedUnattributed++;\n continue;\n }\n gen(c.generator).selected++;\n if (!originBySelectedCard.has(c.cardId)) originBySelectedCard.set(c.cardId, c.generator);\n }\n }\n }\n\n for (const { cardId, record } of recordsBySession.get(session.sessionId) ?? []) {\n const origin = originBySelectedCard.get(cardId);\n if (!origin || record.priorAttemps !== 0) continue;\n const g = gen(origin);\n g.firstAttempts++;\n if (record.isCorrect === true) g.firstAttemptsCorrect++;\n }\n }\n\n return {\n sessions: sessions.length,\n runs,\n runsWithSelection,\n firstRunAt,\n lastRunAt,\n generators: [...gens.values()]\n .map(({ cards, newCards, reviewCards, ...g }) => ({\n ...g,\n meanCards: g.runs ? cards / g.runs : 0,\n meanNew: g.runs ? newCards / g.runs : 0,\n meanReview: g.runs ? reviewCards / g.runs : 0,\n }))\n .sort((a, b) => b.runs - a.runs || a.name.localeCompare(b.name)),\n filters: [...filters.values()].sort((a, b) => a.name.localeCompare(b.name)),\n regulators: [...regulators.values()].map(({ sumMultiplier, ...r }) => ({\n ...r,\n meanMultiplier: r.runs ? sumMultiplier / r.runs : 0,\n })),\n selectedUnattributed,\n };\n}\n"],"mappings":";;;;;;AASA,SAAgB,cAAc,MAAmE;AAC/F,KAAI,KAAK,SAAU,QAAO,aAAa,KAAK;AAC5C,QAAO,KAAK,aAAa;;;;;;AAO3B,SAAgB,iBACd,KAC0C;CAC1C,MAAM,yBAAS,IAAI,KAAqB;AACxC,MAAK,MAAM,KAAK,IAAI,SAAS,EAAE,EAAE;AAC/B,MAAI,CAAC,EAAE,SAAU;EACjB,MAAM,SAAS,cAAc,EAAE;AAC/B,SAAO,IAAI,SAAS,OAAO,IAAI,OAAO,IAAI,KAAK,EAAE;;AAEnD,QAAO,CAAC,GAAG,OAAO,CACf,KAAK,CAAC,QAAQ,YAAY;EAAE;EAAQ;EAAO,EAAE,CAC7C,MAAM,GAAG,MAAM,EAAE,QAAQ,EAAE,MAAM;;;AAoFtC,SAAgB,iBACd,IACA,OAA2B,EAAE,EACX;CAClB,MAAM,WAAW,GAAG,SAAS,QAAQ,MAAM,CAAC,KAAK,SAAS,EAAE,aAAa,KAAK,MAAM;CAEpF,MAAM,mCAAmB,IAAI,KAA+D;AAC5F,MAAK,MAAM,KAAK,GAAG,cACjB,MAAK,MAAM,UAAU,EAAE,SAAS;AAC9B,MAAI,CAAC,OAAO,UAAW;EACvB,MAAM,OAAO,iBAAiB,IAAI,OAAO,UAAU,IAAI,EAAE;AACzD,OAAK,KAAK;GAAE,QAAQ,EAAE;GAAQ;GAAQ,CAAC;AACvC,mBAAiB,IAAI,OAAO,WAAW,KA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;GAC7C,EAAE,CACF,MAAM,GAAG,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,KAAK,cAAc,EAAE,KAAK,CAAC;EAClE,SAAS,CAAC,GAAG,QAAQ,QAAQ,CAAC,CAAC,MAAM,GAAG,MAAM,EAAE,KAAK,cAAc,EAAE,KAAK,CAAC;EAC3E,YAAY,CAAC,GAAG,WAAW,QAAQ,CAAC,CAAC,KAAK,EAAE,eAAe,GAAG,SAAS;GACrE,GAAG;GACH,gBAAgB,EAAE,OAAO,gBAAgB,EAAE,OAAO;GACnD,EAAE;EACH;EACD"}
@@ -0,0 +1,177 @@
1
+ import "../_virtual/_rolldown/runtime.mjs";
2
+ import { COUNT_ONLY_SCORE, isCountOnlyTag, tagRole } from "@vue-skuilder/common";
3
+ //#region src/diagnostics/tagElo.ts
4
+ /**
5
+ * A learner's per-tag ELO, read for display: one row per tag on their course
6
+ * registration, the batches a view filters those rows by, and each rating's
7
+ * trajectory through the dataset's sessions.
8
+ *
9
+ * The source is the learner's `CourseElo` (global + per-tag `{score, count,
10
+ * recent}`). Session `eloEvents` add trajectories (per-tag before → after,
11
+ * from when sessions began recording them); card-history records add when a
12
+ * tag was first and last named by a response.
13
+ */
14
+ /** What precedes a tag's role segment: `gpc` in `gpc:exercise:x`, `''` in `expose:x`. */
15
+ function beforeRole(tag, role) {
16
+ const match = new RegExp(`(^|:)${role}:(?=.)`).exec(tag);
17
+ return match ? tag.slice(0, match.index) : "";
18
+ }
19
+ /**
20
+ * The colon-delimited segments that scope a tag: what comes before its role
21
+ * (`gpc:exercise:x` → `gpc`), else its first segment (`concept:match:x` →
22
+ * `concept`). `''` for a tag with neither (`femur`, `expose:x`).
23
+ */
24
+ function tagNamespace(tag) {
25
+ const role = tagRole(tag);
26
+ if (role) return beforeRole(tag, role);
27
+ const colon = tag.indexOf(":");
28
+ return colon > 0 ? tag.slice(0, colon) : "";
29
+ }
30
+ function matchesTagBatch(tag, batch, role = tagRole(tag)) {
31
+ if (batch.namespaces && !batch.namespaces.includes(tagNamespace(tag))) return false;
32
+ if (batch.roles && !batch.roles.includes(role ?? "none")) return false;
33
+ if (batch.prefixes && !batch.prefixes.some((p) => tag.startsWith(p))) return false;
34
+ if (batch.excludePrefixes?.some((p) => tag.startsWith(p))) return false;
35
+ return true;
36
+ }
37
+ /** The namespace × role batch a tag falls in, e.g. `gpc:exercise`, `concept`, or `(no namespace)`. */
38
+ function tagGroupBatch(tag) {
39
+ const role = tagRole(tag);
40
+ const ns = tagNamespace(tag);
41
+ const id = [ns, role].filter(Boolean).join(":") || "(no namespace)";
42
+ return {
43
+ id,
44
+ label: id,
45
+ namespaces: [ns],
46
+ roles: [role ?? "none"]
47
+ };
48
+ }
49
+ /** The learner's `CourseElo` for the dataset's course, or null if not registered. */
50
+ function learnerCourseElo(ds) {
51
+ const elo = ds.registration?.courses?.find((c) => c.courseID === ds.courseId)?.elo;
52
+ if (typeof elo === "number") return {
53
+ global: {
54
+ score: elo,
55
+ count: 0
56
+ },
57
+ tags: {},
58
+ misc: {}
59
+ };
60
+ if (!elo || typeof elo !== "object" || !elo.global) return null;
61
+ return {
62
+ ...elo,
63
+ tags: elo.tags ?? {},
64
+ misc: elo.misc ?? {}
65
+ };
66
+ }
67
+ function minIso(a, b) {
68
+ return a === null || b < a ? b : a;
69
+ }
70
+ function maxIso(a, b) {
71
+ return a === null || b > a ? b : a;
72
+ }
73
+ /**
74
+ * Extend a series by one event. A `before` that differs from where the line
75
+ * stands gets its own point: the rating moved between recorded events (a
76
+ * session that closed without saving its events), shown as a step here.
77
+ */
78
+ function step(line, at, before, after) {
79
+ if (before !== COUNT_ONLY_SCORE && line[line.length - 1]?.score !== before) line.push({
80
+ at,
81
+ score: before
82
+ });
83
+ line.push({
84
+ at,
85
+ score: after
86
+ });
87
+ }
88
+ /** The learner's per-tag ELO for display. Null if the dataset has no registration for its course. */
89
+ function tagEloView(ds) {
90
+ const elo = learnerCourseElo(ds);
91
+ if (!elo) return null;
92
+ const seen = /* @__PURE__ */ new Map();
93
+ for (const h of ds.cardHistories) for (const r of h.records) {
94
+ const p = r.performance;
95
+ if (!p || typeof p !== "object") continue;
96
+ for (const tag of Object.keys(p)) {
97
+ if (tag === "_global") continue;
98
+ const s = seen.get(tag) ?? {
99
+ first: null,
100
+ last: null
101
+ };
102
+ s.first = minIso(s.first, r.timeStamp);
103
+ s.last = maxIso(s.last, r.timeStamp);
104
+ seen.set(tag, s);
105
+ }
106
+ }
107
+ const events = ds.sessions.flatMap((s) => s.eloEvents ?? []).sort((a, b) => a.at.localeCompare(b.at));
108
+ const globalSeries = [];
109
+ const tagSeries = {};
110
+ const eventCounts = /* @__PURE__ */ new Map();
111
+ for (const e of events) {
112
+ step(globalSeries, e.at, e.global.before, e.global.after);
113
+ for (const [tag, t] of Object.entries(e.tags ?? {})) {
114
+ eventCounts.set(tag, (eventCounts.get(tag) ?? 0) + 1);
115
+ if (t.score === null || isCountOnlyTag(tag) || t.after === COUNT_ONLY_SCORE) continue;
116
+ step(tagSeries[tag] ??= [], e.at, t.before, t.after);
117
+ }
118
+ }
119
+ const rows = Object.entries(elo.tags).map(([tag, rank]) => {
120
+ const role = tagRole(tag);
121
+ const countOnly = isCountOnlyTag(tag) || rank.score === COUNT_ONLY_SCORE;
122
+ const score = countOnly ? null : rank.score;
123
+ const recent = rank.recent ?? [];
124
+ let { first, last } = seen.get(tag) ?? {
125
+ first: null,
126
+ last: null
127
+ };
128
+ for (const p of recent) {
129
+ first = minIso(first, p.at);
130
+ last = maxIso(last, p.at);
131
+ }
132
+ return {
133
+ tag,
134
+ role,
135
+ namespace: tagNamespace(tag),
136
+ group: tagGroupBatch(tag).id,
137
+ score,
138
+ ...countOnly && rank.score !== COUNT_ONLY_SCORE ? { staleScore: rank.score } : {},
139
+ count: rank.count,
140
+ vsGlobal: score === null ? null : score - elo.global.score,
141
+ recent,
142
+ recentOk: recent.filter((p) => p.ok).length,
143
+ firstSeen: first,
144
+ lastSeen: last,
145
+ events: eventCounts.get(tag) ?? 0
146
+ };
147
+ });
148
+ rows.sort((a, b) => a.score === null || b.score === null ? Number(a.score === null) - Number(b.score === null) || a.tag.localeCompare(b.tag) : b.score - a.score || a.tag.localeCompare(b.tag));
149
+ if (globalSeries.length > 0) globalSeries.push({
150
+ at: ds.asOf,
151
+ score: elo.global.score
152
+ });
153
+ for (const row of rows) {
154
+ const line = tagSeries[row.tag];
155
+ if (line && row.score !== null) line.push({
156
+ at: ds.asOf,
157
+ score: row.score
158
+ });
159
+ }
160
+ const groups = /* @__PURE__ */ new Map();
161
+ for (const row of rows) if (!groups.has(row.group)) groups.set(row.group, tagGroupBatch(row.tag));
162
+ const countOnlyGroup = (b) => b.roles?.some((r) => r === "intro" || r === "expose") ?? false;
163
+ return {
164
+ global: elo.global,
165
+ rows,
166
+ groups: [...groups.values()].sort((a, b) => Number(countOnlyGroup(a)) - Number(countOnlyGroup(b)) || a.id.localeCompare(b.id)),
167
+ series: {
168
+ global: globalSeries,
169
+ tags: tagSeries
170
+ },
171
+ seriesFrom: events[0]?.at ?? null
172
+ };
173
+ }
174
+ //#endregion
175
+ export { learnerCourseElo, matchesTagBatch, tagEloView, tagGroupBatch, tagNamespace };
176
+
177
+ //# sourceMappingURL=tagElo.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tagElo.mjs","names":[],"sources":["../../src/diagnostics/tagElo.ts"],"sourcesContent":["/**\n * A learner's per-tag ELO, read for display: one row per tag on their course\n * registration, the batches a view filters those rows by, and each rating's\n * trajectory through the dataset's sessions.\n *\n * The source is the learner's `CourseElo` (global + per-tag `{score, count,\n * recent}`). Session `eloEvents` add trajectories (per-tag before → after,\n * from when sessions began recording them); card-history records add when a\n * tag was first and last named by a response.\n */\nimport {\n COUNT_ONLY_SCORE,\n isCountOnlyTag,\n tagRole,\n type CourseElo,\n type EloRank,\n type TagPresentation,\n type TagRole,\n} from '@vue-skuilder/common';\nimport type { LearnerDataset } from './dataset';\n\n// ============================================================================\n// Batches\n// ============================================================================\n\n/**\n * A set of tags to view together, as data: every criterion given must hold.\n *\n * Plain data on purpose. Choosing which tags count is the same question the\n * tag-aware ELO distance filter has open (`tagAwareGap` in\n * `filters/eloDistance.ts`); a serializable batch can later move into a\n * strategy config and serve both.\n */\nexport interface TagBatch {\n id: string;\n label: string;\n /** Tag namespaces (see {@link tagNamespace}); `''` is tags with none. */\n namespaces?: string[];\n /** Tag roles; `'none'` is tags without one. */\n roles?: Array<TagRole | 'none'>;\n /** Tags starting with any of these. */\n prefixes?: string[];\n /** Tags starting with any of these are left out. */\n excludePrefixes?: string[];\n}\n\n/** What precedes a tag's role segment: `gpc` in `gpc:exercise:x`, `''` in `expose:x`. */\nfunction beforeRole(tag: string, role: TagRole): string {\n // tagRole takes the leftmost role segment; the leftmost of this one is it.\n const match = new RegExp(`(^|:)${role}:(?=.)`).exec(tag);\n return match ? tag.slice(0, match.index) : '';\n}\n\n/**\n * The colon-delimited segments that scope a tag: what comes before its role\n * (`gpc:exercise:x` → `gpc`), else its first segment (`concept:match:x` →\n * `concept`). `''` for a tag with neither (`femur`, `expose:x`).\n */\nexport function tagNamespace(tag: string): string {\n const role = tagRole(tag);\n if (role) return beforeRole(tag, role);\n const colon = tag.indexOf(':');\n return colon > 0 ? tag.slice(0, colon) : '';\n}\n\nexport function matchesTagBatch(tag: string, batch: TagBatch, role = tagRole(tag)): boolean {\n if (batch.namespaces && !batch.namespaces.includes(tagNamespace(tag))) return false;\n if (batch.roles && !batch.roles.includes(role ?? 'none')) return false;\n if (batch.prefixes && !batch.prefixes.some((p) => tag.startsWith(p))) return false;\n if (batch.excludePrefixes?.some((p) => tag.startsWith(p))) return false;\n return true;\n}\n\n/** The namespace × role batch a tag falls in, e.g. `gpc:exercise`, `concept`, or `(no namespace)`. */\nexport function tagGroupBatch(tag: string): TagBatch {\n const role = tagRole(tag);\n const ns = tagNamespace(tag);\n const id = [ns, role].filter(Boolean).join(':') || '(no namespace)';\n return { id, label: id, namespaces: [ns], roles: [role ?? 'none'] };\n}\n\n// ============================================================================\n// Rows\n// ============================================================================\n\nexport interface TagEloRow {\n tag: string;\n role: TagRole | null;\n namespace: string;\n /** Id of the tag's {@link tagGroupBatch}. */\n group: string;\n /**\n * The learner's rating on the tag. Null for a count-only tag: a bookkeeping\n * role (`intro`, `expose`), or the count-only sentinel.\n */\n score: number | null;\n /**\n * A real score stored on a bookkeeping-role tag, from before roles were\n * count-only. Not a rating: the framework ignores it.\n */\n staleScore?: number;\n count: number;\n /** `score − global`; null when score is. */\n vsGlobal: number | null;\n /** The rating's ring buffer of recent first attempts, oldest first. */\n recent: TagPresentation[];\n /** First-attempt correct entries in `recent`. */\n recentOk: number;\n /** First and last response whose per-tag performance named the tag, or a recent entry. */\n firstSeen: string | null;\n lastSeen: string | null;\n /** ELO events on the tag in the dataset's sessions. */\n events: number;\n}\n\nexport interface EloPoint {\n at: string;\n score: number;\n}\n\nexport interface TagEloView {\n global: EloRank;\n /** Every tag on the registration, highest score first, count-only tags last. */\n rows: TagEloRow[];\n /** The namespace × role batches present, graded ones first. */\n groups: TagBatch[];\n /**\n * Ratings through the dataset's ELO events: each series starts at its first\n * event's `before`, has a point per event, and ends at the current score at\n * `asOf`. A move between recorded events (a session that didn't save its\n * events) shows as a step at the next event, or at `asOf`. Tags with no\n * events have no series; count-only tags have none.\n */\n series: { global: EloPoint[]; tags: Record<string, EloPoint[]> };\n /** The first ELO event, or null: trajectories start here. */\n seriesFrom: string | null;\n}\n\n/** The learner's `CourseElo` for the dataset's course, or null if not registered. */\nexport function learnerCourseElo(ds: LearnerDataset): CourseElo | null {\n const elo = ds.registration?.courses?.find((c) => c.courseID === ds.courseId)?.elo;\n if (typeof elo === 'number') return { global: { score: elo, count: 0 }, tags: {}, misc: {} };\n if (!elo || typeof elo !== 'object' || !elo.global) return null;\n return { ...elo, tags: elo.tags ?? {}, misc: elo.misc ?? {} };\n}\n\nfunction minIso(a: string | null, b: string): string {\n return a === null || b < a ? b : a;\n}\n\nfunction maxIso(a: string | null, b: string): string {\n return a === null || b > a ? b : a;\n}\n\n/**\n * Extend a series by one event. A `before` that differs from where the line\n * stands gets its own point: the rating moved between recorded events (a\n * session that closed without saving its events), shown as a step here.\n */\nfunction step(line: EloPoint[], at: string, before: number, after: number): void {\n if (before !== COUNT_ONLY_SCORE && line[line.length - 1]?.score !== before)\n line.push({ at, score: before });\n line.push({ at, score: after });\n}\n\n/** The learner's per-tag ELO for display. Null if the dataset has no registration for its course. */\nexport function tagEloView(ds: LearnerDataset): TagEloView | null {\n const elo = learnerCourseElo(ds);\n if (!elo) return null;\n\n // When each tag was named by a response, from card history.\n const seen = new Map<string, { first: string | null; last: string | null }>();\n for (const h of ds.cardHistories) {\n for (const r of h.records) {\n const p = r.performance as unknown;\n if (!p || typeof p !== 'object') continue;\n for (const tag of Object.keys(p)) {\n if (tag === '_global') continue;\n const s = seen.get(tag) ?? { first: null, last: null };\n s.first = minIso(s.first, r.timeStamp);\n s.last = maxIso(s.last, r.timeStamp);\n seen.set(tag, s);\n }\n }\n }\n\n // Trajectories, from session ELO events in time order.\n const events = ds.sessions\n .flatMap((s) => s.eloEvents ?? [])\n .sort((a, b) => a.at.localeCompare(b.at));\n const globalSeries: EloPoint[] = [];\n const tagSeries: Record<string, EloPoint[]> = {};\n const eventCounts = new Map<string, number>();\n for (const e of events) {\n step(globalSeries, e.at, e.global.before, e.global.after);\n for (const [tag, t] of Object.entries(e.tags ?? {})) {\n eventCounts.set(tag, (eventCounts.get(tag) ?? 0) + 1);\n if (t.score === null || isCountOnlyTag(tag) || t.after === COUNT_ONLY_SCORE) continue;\n step((tagSeries[tag] ??= []), e.at, t.before, t.after);\n }\n }\n\n const rows: TagEloRow[] = Object.entries(elo.tags).map(([tag, rank]) => {\n const role = tagRole(tag);\n const countOnly = isCountOnlyTag(tag) || rank.score === COUNT_ONLY_SCORE;\n const score = countOnly ? null : rank.score;\n const recent = rank.recent ?? [];\n let { first, last } = seen.get(tag) ?? { first: null, last: null };\n for (const p of recent) {\n first = minIso(first, p.at);\n last = maxIso(last, p.at);\n }\n return {\n tag,\n role,\n namespace: tagNamespace(tag),\n group: tagGroupBatch(tag).id,\n score,\n ...(countOnly && rank.score !== COUNT_ONLY_SCORE ? { staleScore: rank.score } : {}),\n count: rank.count,\n vsGlobal: score === null ? null : score - elo.global.score,\n recent,\n recentOk: recent.filter((p) => p.ok).length,\n firstSeen: first,\n lastSeen: last,\n events: eventCounts.get(tag) ?? 0,\n };\n });\n rows.sort((a, b) =>\n a.score === null || b.score === null\n ? Number(a.score === null) - Number(b.score === null) || a.tag.localeCompare(b.tag)\n : b.score - a.score || a.tag.localeCompare(b.tag)\n );\n\n // Close each line at the current rating, so it reaches `asOf` and shows any\n // move the events didn't record.\n if (globalSeries.length > 0) globalSeries.push({ at: ds.asOf, score: elo.global.score });\n for (const row of rows) {\n const line = tagSeries[row.tag];\n if (line && row.score !== null) line.push({ at: ds.asOf, score: row.score });\n }\n\n const groups = new Map<string, TagBatch>();\n for (const row of rows) if (!groups.has(row.group)) groups.set(row.group, tagGroupBatch(row.tag));\n const countOnlyGroup = (b: TagBatch): boolean =>\n b.roles?.some((r) => r === 'intro' || r === 'expose') ?? false;\n\n return {\n global: elo.global,\n rows,\n groups: [...groups.values()].sort(\n (a, b) => Number(countOnlyGroup(a)) - Number(countOnlyGroup(b)) || a.id.localeCompare(b.id)\n ),\n series: { global: globalSeries, tags: tagSeries },\n seriesFrom: events[0]?.at ?? null,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AA+CA,SAAS,WAAW,KAAa,MAAuB;CAEtD,MAAM,QAAQ,IAAI,OAAO,QAAQ,KAAK,QAAQ,CAAC,KAAK,IAAI;AACxD,QAAO,QAAQ,IAAI,MAAM,GAAG,MAAM,MAAM,GAAG;;;;;;;AAQ7C,SAAgB,aAAa,KAAqB;CAChD,MAAM,OAAO,QAAQ,IAAI;AACzB,KAAI,KAAM,QAAO,WAAW,KAAK,KAAK;CACtC,MAAM,QAAQ,IAAI,QAAQ,IAAI;AAC9B,QAAO,QA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