@vue-skuilder/db 0.3.1 → 0.3.3

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 (53) hide show
  1. package/dist/{contentSource-2zVmcjKA.d.ts → contentSource-CSI0pJ2D.d.ts} +10 -0
  2. package/dist/core/index.cjs +62 -14
  3. package/dist/core/index.cjs.map +1 -1
  4. package/dist/core/index.d.ts +3 -3
  5. package/dist/core/interfaces/contentSource.mjs.map +1 -1
  6. package/dist/core/navigators/Pipeline.mjs +7 -1
  7. package/dist/core/navigators/Pipeline.mjs.map +1 -1
  8. package/dist/core/navigators/filters/eloDistance.mjs +17 -2
  9. package/dist/core/navigators/filters/eloDistance.mjs.map +1 -1
  10. package/dist/core/navigators/generators/prescribed.mjs +20 -10
  11. package/dist/core/navigators/generators/prescribed.mjs.map +1 -1
  12. package/dist/core/navigators/index.mjs +2 -0
  13. package/dist/core/navigators/index.mjs.map +1 -1
  14. package/dist/core/versionStamps.mjs +1 -1
  15. package/dist/{dataLayerProvider-rGyLQ93v.d.ts → dataLayerProvider-D5n1gGc_.d.ts} +1 -1
  16. package/dist/diagnostics/derive.mjs.map +1 -1
  17. package/dist/diagnostics/index.cjs +16 -3
  18. package/dist/diagnostics/index.cjs.map +1 -1
  19. package/dist/diagnostics/index.d.ts +29 -6
  20. package/dist/diagnostics/tagElo.mjs +20 -4
  21. package/dist/diagnostics/tagElo.mjs.map +1 -1
  22. package/dist/impl/couch/courseDB.mjs +5 -0
  23. package/dist/impl/couch/courseDB.mjs.map +1 -1
  24. package/dist/impl/couch/index.cjs +37 -2
  25. package/dist/impl/couch/index.cjs.map +1 -1
  26. package/dist/impl/couch/index.d.ts +4 -2
  27. package/dist/impl/static/courseDB.mjs +5 -0
  28. package/dist/impl/static/courseDB.mjs.map +1 -1
  29. package/dist/impl/static/index.cjs +37 -2
  30. package/dist/impl/static/index.cjs.map +1 -1
  31. package/dist/impl/static/index.d.ts +4 -2
  32. package/dist/index.cjs +80 -16
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.d.ts +3 -3
  35. package/dist/study/SessionController.mjs +1 -0
  36. package/dist/study/SessionController.mjs.map +1 -1
  37. package/dist/study/services/tagRecent.mjs +2 -1
  38. package/dist/study/services/tagRecent.mjs.map +1 -1
  39. package/package.json +3 -3
  40. package/src/core/interfaces/contentSource.ts +7 -0
  41. package/src/core/navigators/Pipeline.ts +7 -0
  42. package/src/core/navigators/filters/eloDistance.ts +31 -2
  43. package/src/core/navigators/generators/prescribed.ts +55 -11
  44. package/src/core/navigators/generators/types.ts +3 -0
  45. package/src/core/navigators/index.ts +5 -0
  46. package/src/diagnostics/derive.ts +6 -1
  47. package/src/diagnostics/tagElo.ts +43 -3
  48. package/src/impl/couch/courseDB.ts +13 -0
  49. package/src/impl/static/courseDB.ts +13 -0
  50. package/src/study/SessionController.ts +3 -0
  51. package/src/study/services/tagRecent.test.ts +57 -3
  52. package/src/study/services/tagRecent.ts +8 -1
  53. package/tests/core/navigators/eloDistanceFilter.test.ts +15 -0
@@ -1,5 +1,5 @@
1
1
  import "../_virtual/_rolldown/runtime.mjs";
2
- import { COUNT_ONLY_SCORE, isCountOnlyTag, tagRole } from "@vue-skuilder/common";
2
+ import { COUNT_ONLY_SCORE, courseSecurity, isCountOnlyTag, presentationOk, skillNeed, tagRole } from "@vue-skuilder/common";
3
3
  //#region src/diagnostics/tagElo.ts
4
4
  /**
5
5
  * A learner's per-tag ELO, read for display: one row per tag on their course
@@ -86,9 +86,13 @@ function step(line, at, before, after) {
86
86
  });
87
87
  }
88
88
  /** The learner's per-tag ELO for display. Null if the dataset has no registration for its course. */
89
- function tagEloView(ds) {
89
+ function tagEloView(ds, options = {}) {
90
90
  const elo = learnerCourseElo(ds);
91
91
  if (!elo) return null;
92
+ const security = courseSecurity(elo, options.security);
93
+ const securityByTag = new Map(security.tags.map((s) => [s.tag, s]));
94
+ const need = skillNeed(elo, options.need);
95
+ const needByTag = new Map(need.skills.map((s) => [s.tag, s]));
92
96
  const seen = /* @__PURE__ */ new Map();
93
97
  for (const h of ds.cardHistories) for (const r of h.records) {
94
98
  const p = r.performance;
@@ -139,7 +143,12 @@ function tagEloView(ds) {
139
143
  count: rank.count,
140
144
  vsGlobal: score === null ? null : score - elo.global.score,
141
145
  recent,
142
- recentOk: recent.filter((p) => p.ok).length,
146
+ recentOk: recent.filter(presentationOk).length,
147
+ ...securityByTag.has(tag) ? { security: securityByTag.get(tag) } : {},
148
+ ...needByTag.has(tag) ? {
149
+ need: needByTag.get(tag).need,
150
+ deficit: needByTag.get(tag).deficit
151
+ } : {},
143
152
  firstSeen: first,
144
153
  lastSeen: last,
145
154
  events: eventCounts.get(tag) ?? 0
@@ -168,7 +177,14 @@ function tagEloView(ds) {
168
177
  global: globalSeries,
169
178
  tags: tagSeries
170
179
  },
171
- seriesFrom: events[0]?.at ?? null
180
+ seriesFrom: events[0]?.at ?? null,
181
+ skillReference: need.reference,
182
+ security: {
183
+ secure: security.secure,
184
+ shaky: security.shaky,
185
+ unproven: security.unproven,
186
+ debt: security.debt
187
+ }
172
188
  };
173
189
  }
174
190
  //#endregion
@@ -1 +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,QAAQ,IAAI,IAAI,MAAM,GAAG,MAAM,GAAG;;AAG3C,SAAgB,gBAAg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QAAQ,IAAI,UAAU,KAAM,MAAK,KAAK;GAAE,IAAI,GAAG;GAAM,OAAO,IAAI;GAAO,CAAC;;CAG9E,MAAM,yBAAS,IAAI,KAAuB;AAC1C,MAAK,MAAM,OAAO,KAAM,KAAI,CAAC,OAAO,IAAI,IAAI,MAAM,CAAE,QAAO,IAAI,IAAI,OAAO,cAAc,IAAI,IAAI,CAAC;CACjG,MAAM,kBAAkB,MACtB,EAAE,OAAO,MAAM,MAAM,MAAM,WAAW,MAAM,SAAS,IAAI;AAE3D,QAAO;EACL,QAAQ,IAAI;EACZ;EACA,QAAQ,CAAC,GAAG,OAAO,QAAQ,CAAC,CAAC,MAC1B,GAAG,MAAM,OAAO,eAAe,EAAE,CAAC,GAAG,OAAO,eAAe,EAAE,CAAC,IAAI,EAAE,GAAG,cAAc,EAAE,GAAG,CAC5F;EACD,QAAQ;GAAE,QAAQ;GAAc,MAAM;GAAW;EACjD,YAAY,OAAO,IAAI,MAAM;EAC9B"}
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 courseSecurity,\n isCountOnlyTag,\n presentationOk,\n skillNeed,\n tagRole,\n type CourseElo,\n type CourseSecurity,\n type SkillNeedConfig,\n type TagSecurity,\n type TagSecurityConfig,\n type TagSelector,\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 /** Entries in `recent` right on this tag (per-tag, not the card's ok). */\n recentOk: number;\n /** Secure / shaky / unproven, for tags the security selector picks (met exercise tags by default). */\n security?: TagSecurity;\n /** 0–1 need from skillNeed; absent for tags that don't qualify as skills. */\n need?: number;\n /** Skill reference − rating; absent with need. */\n deficit?: 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 /** Median rating over the learner's qualifying skills (skillNeed); null if too few. */\n skillReference: number | null;\n /** Security totals over the selected tags. */\n security: Omit<CourseSecurity, 'tags'>;\n}\n\n/** How the view reads skills: a course may pass its own selectors and thresholds. */\nexport interface TagEloViewOptions {\n security?: { selector?: TagSelector; config?: TagSecurityConfig };\n need?: SkillNeedConfig;\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, options: TagEloViewOptions = {}): TagEloView | null {\n const elo = learnerCourseElo(ds);\n if (!elo) return null;\n\n const security = courseSecurity(elo, options.security);\n const securityByTag = new Map(security.tags.map((s) => [s.tag, s]));\n const need = skillNeed(elo, options.need);\n const needByTag = new Map(need.skills.map((s) => [s.tag, s]));\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(presentationOk).length,\n ...(securityByTag.has(tag) ? { security: securityByTag.get(tag) } : {}),\n ...(needByTag.has(tag)\n ? { need: needByTag.get(tag)!.need, deficit: needByTag.get(tag)!.deficit }\n : {}),\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 skillReference: need.reference,\n security: {\n secure: security.secure,\n shaky: security.shaky,\n unproven: security.unproven,\n debt: security.debt,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAuDA,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,QAAQ,IAAI,IAAI,MAAM,GAAG,MAAM,GAAG;;AAG3C,SAAgB,gBAAgB,KAAa,OAAiB,OAAO,QAAQ,IAAI,EAAW;AAC1F,KAAI,MAAM,cAAc,CAAC,MAAM,WAAW,SAAS,aAAa,IAAI,CAAC,CAAE,QAAO;AAC9E,KAAI,MAAM,SAAS,CAAC,MAAM,MAAM,SAAS,QAAQ,OAAO,CAAE,QAAO;AACjE,KAAI,MAAM,YAAY,CAAC,MAAM,SAAS,MAAM,MAAM,IAAI,WAAW,EAAE,CAAC,CAAE,QAAO;AAC7E,KAAI,MAAM,iBAAiB,MAAM,MAAM,IAAI,WAAW,EAAE,CAAC,CAAE,QAAO;AAClE,QAAO;;;AAIT,SAAgB,cAAc,KAAuB;CACnD,MAAM,OAAO,QAAQ,IAAI;CACzB,MAAM,KAAK,aAAa,IAAI;CAC5B,MAAM,KAAK,CAAC,IAAI,KAAK,CAAC,OAAO,QAAQ,CAAC,KAAK,IAAI,IAAI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GAAM,OAAO,IAAI;GAAO,CAAC;;CAG9E,MAAM,yBAAS,IAAI,KAAuB;AAC1C,MAAK,MAAM,OAAO,KAAM,KAAI,CAAC,OAAO,IAAI,IAAI,MAAM,CAAE,QAAO,IAAI,IAAI,OAAO,cAAc,IAAI,IAAI,CAAC;CACjG,MAAM,kBAAkB,MACtB,EAAE,OAAO,MAAM,MAAM,MAAM,WAAW,MAAM,SAAS,IAAI;AAE3D,QAAO;EACL,QAAQ,IAAI;EACZ;EACA,QAAQ,CAAC,GAAG,OAAO,QAAQ,CAAC,CAAC,MAC1B,GAAG,MAAM,OAAO,eAAe,EAAE,CAAC,GAAG,OAAO,eAAe,EAAE,CAAC,IAAI,EAAE,GAAG,cAAc,EAAE,GAAG,CAC5F;EACD,QAAQ;GAAE,QAAQ;GAAc,MAAM;GAAW;EACjD,YAAY,OAAO,IAAI,MAAM;EAC7B,gBAAgB,KAAK;EACrB,UAAU;GACR,QAAQ,SAAS;GACjB,OAAO,SAAS;GAChB,UAAU,SAAS;GACnB,MAAM,SAAS;GAChB;EACF"}
@@ -449,6 +449,10 @@ above:\n${above.rows.map((r) => `\t${r.id}-${r.key}\n`)}`;
449
449
  setEphemeralHints(hints) {
450
450
  this._pendingHints = hints;
451
451
  }
452
+ _sessionId = null;
453
+ setSessionId(sessionId) {
454
+ this._sessionId = sessionId;
455
+ }
452
456
  /**
453
457
  * Forward a presentation to the navigator (a new card restarts its intake
454
458
  * clock). Builds the navigator if the cached one has expired.
@@ -465,6 +469,7 @@ above:\n${above.rows.map((r) => `\t${r.id}-${r.key}\n`)}`;
465
469
  navigator.setEphemeralHints(this._pendingHints);
466
470
  this._pendingHints = null;
467
471
  }
472
+ if (this._sessionId) navigator.setSessionId(this._sessionId);
468
473
  return await navigator.getWeightedCards(limit);
469
474
  } catch (e) {
470
475
  logger.error(`[courseDB] Error getting weighted cards: ${e}`);
@@ -1 +1 @@
1
- {"version":3,"file":"courseDB.mjs","names":[],"sources":["../../../src/impl/couch/courseDB.ts"],"sourcesContent":["import { CourseDBInterface, CourseInfo, CoursesDBInterface, UserDBInterface } from '@db/core';\nimport type { GeneratorResult, ReplanHints } from '@db/core/navigators/generators/types';\nimport {\n CourseConfig,\n CourseElo,\n DataShape,\n EloToNumber,\n Status,\n blankCourseElo,\n toCourseElo,\n} from '@vue-skuilder/common';\n\nimport { filterAllDocsByPrefix, getCourseDB } from '.';\nimport UpdateQueue from './updateQueue';\nimport type { StudyContentSource } from '../../core/interfaces/contentSource';\nimport { StudySessionItem } from '../../core/interfaces/contentSource';\nimport {\n CardData,\n DocType,\n QualifiedCardID,\n SkuilderCourseData,\n Tag,\n TagStub,\n DocTypePrefixes,\n} from '../../core/types/types-legacy';\nimport { logger } from '../../util/logger';\nimport { GET_CACHED } from './clientCache';\nimport {\n addNote55,\n addTagToCard,\n getCredentialledCourseConfig,\n getTagID,\n invalidateCourseConfigCache,\n} from './courseAPI';\nimport { DataLayerResult } from '@db/core/types/db';\nimport { PouchError } from './types';\nimport CourseLookup from './courseLookupDB';\nimport { ContentNavigationStrategyData } from '@db/core/types/contentNavigationStrategy';\nimport { ContentNavigator, Navigators } from '@db/core/navigators';\nimport { PipelineAssembler } from '@db/core/navigators/PipelineAssembler';\nimport { createDefaultPipeline } from '@db/core/navigators/defaults';\n\nexport class CoursesDB implements CoursesDBInterface {\n _courseIDs: string[] | undefined;\n\n constructor(courseIDs?: string[]) {\n if (courseIDs && courseIDs.length > 0) {\n this._courseIDs = courseIDs;\n } else {\n this._courseIDs = undefined;\n }\n }\n\n public async getCourseList(): Promise<CourseConfig[]> {\n let crsList = await CourseLookup.allCourseWare();\n logger.debug(`AllCourses: ${crsList.map((c) => c.name + ', ' + c._id + '\\n\\t')}`);\n if (this._courseIDs) {\n crsList = crsList.filter((c) => this._courseIDs!.includes(c._id));\n }\n\n logger.debug(`AllCourses.filtered: ${crsList.map((c) => c.name + ', ' + c._id + '\\n\\t')}`);\n\n const cfgs = await Promise.all(\n crsList.map(async (c) => {\n try {\n const cfg = await getCredentialledCourseConfig(c._id);\n logger.debug(`Found cfg: ${JSON.stringify(cfg)}`);\n return cfg;\n } catch (e) {\n logger.warn(`Error fetching cfg for course ${c.name}, ${c._id}: ${e}`);\n return undefined;\n }\n })\n );\n return cfgs.filter((c) => !!c);\n }\n\n async getCourseConfig(courseId: string): Promise<CourseConfig> {\n if (this._courseIDs && this._courseIDs.length && !this._courseIDs.includes(courseId)) {\n throw new Error(`Course ${courseId} not in course list`);\n }\n\n const cfg = await getCredentialledCourseConfig(courseId);\n if (cfg === undefined) {\n throw new Error(`Error fetching cfg for course ${courseId}`);\n } else {\n return cfg;\n }\n }\n\n public async disambiguateCourse(courseId: string, disambiguator: string): Promise<void> {\n await CourseLookup.updateDisambiguator(courseId, disambiguator);\n }\n}\n\nfunction randIntWeightedTowardZero(n: number) {\n return Math.floor(Math.random() * Math.random() * Math.random() * n);\n}\n\nexport class CourseDB implements CourseDBInterface {\n // private log(msg: string): void {\n // log(`CourseLog: ${this.id}\\n ${msg}`);\n // }\n\n /**\n * Primary database handle used for all **read** operations (queries, gets).\n *\n * When local sync is active, this points to the local PouchDB replica for\n * fast, network-free reads. Otherwise it points to the remote CouchDB.\n */\n private db: PouchDB.Database;\n\n /**\n * Remote database handle used for all **write** operations.\n *\n * Always points to the remote CouchDB so that writes (ELO updates, tag\n * mutations, admin operations) aggregate on the server. The local replica\n * is a read-only snapshot that refreshes on the next page load.\n *\n * When local sync is NOT active, this is the same instance as `this.db`.\n */\n private remoteDB: PouchDB.Database;\n\n private id: string;\n private _getCurrentUser: () => Promise<UserDBInterface>;\n private updateQueue: UpdateQueue;\n\n /**\n * @param id - Course ID\n * @param userLookup - Async function returning the current user DB\n * @param localDB - Optional local PouchDB replica for reads. When provided,\n * `this.db` uses the local replica and `this.remoteDB` stays remote.\n * The UpdateQueue reads from remote and writes to remote (local `_rev`\n * values may be stale, so read-modify-write cycles must go through\n * the remote DB to avoid conflicts).\n */\n /** Reads go to this device's replica (perf marks report it as the session's binding). */\n public get readsLocal(): boolean {\n return this.db !== this.remoteDB;\n }\n\n constructor(id: string, userLookup: () => Promise<UserDBInterface>, localDB?: PouchDB.Database) {\n this.id = id;\n const remote = getCourseDB(this.id);\n this.remoteDB = remote;\n this.db = localDB ?? remote;\n this._getCurrentUser = userLookup;\n // UpdateQueue always operates against the remote DB for its\n // read-modify-write cycle. Local _rev values may be stale (the local\n // replica is a snapshot), so conflict retries must read from remote.\n this.updateQueue = new UpdateQueue(this.remoteDB, this.remoteDB);\n }\n\n public getCourseID(): string {\n return this.id;\n }\n\n public async getCourseInfo(): Promise<CourseInfo> {\n const cardCount = (\n await this.db.find({\n selector: {\n docType: DocType.CARD,\n },\n limit: 1000,\n })\n ).docs.length;\n\n return {\n cardCount,\n registeredUsers: 0,\n };\n }\n\n public async getInexperiencedCards(limit: number = 2) {\n return (\n await this.db.query('cardsByInexperience', {\n limit,\n })\n ).rows.map((r) => {\n const ret = {\n courseId: this.id,\n cardId: r.id,\n count: r.key,\n elo: r.value,\n };\n return ret;\n });\n }\n\n public async getCardsByEloLimits(\n options: {\n low: number;\n high: number;\n limit: number;\n page: number;\n } = {\n low: 0,\n high: Number.MIN_SAFE_INTEGER,\n limit: 25,\n page: 0,\n }\n ) {\n return (\n await this.db.query('elo', {\n startkey: options.low,\n endkey: options.high,\n limit: options.limit,\n skip: options.limit * options.page,\n })\n ).rows.map((r) => {\n return `${this.id}-${r.id}-${r.key}`;\n });\n }\n public async getCardEloData(id: string[]): Promise<CourseElo[]> {\n const docs = await this.db.allDocs<CardData>({\n keys: id,\n include_docs: true,\n });\n const ret: CourseElo[] = [];\n docs.rows.forEach((r) => {\n // [ ] remove these ts-ignore directives.\n if (isSuccessRow(r)) {\n if (r.doc && r.doc.elo) {\n ret.push(toCourseElo(r.doc.elo));\n } else {\n logger.warn('no elo data for card: ' + r.id);\n ret.push(blankCourseElo());\n }\n } else {\n logger.warn('no elo data for card: ' + JSON.stringify(r));\n ret.push(blankCourseElo());\n }\n });\n return ret;\n }\n\n /**\n * Returns the lowest and highest `global` ELO ratings in the course\n */\n public async getELOBounds() {\n const [low, high] = await Promise.all([\n (\n await this.db.query('elo', {\n startkey: 0,\n limit: 1,\n include_docs: false,\n })\n ).rows[0].key,\n (\n await this.db.query('elo', {\n limit: 1,\n descending: true,\n startkey: 100_000,\n })\n ).rows[0].key,\n ]);\n\n return {\n low: low,\n high: high,\n };\n }\n\n public async removeCard(id: string) {\n // Admin operation — read and write both go through remote DB to ensure\n // we have the current _rev for the delete.\n const doc = await this.remoteDB.get<CardData>(id);\n if (!doc.docType || !(doc.docType === DocType.CARD)) {\n throw new Error(`failed to remove ${id} from course ${this.id}. id does not point to a card`);\n }\n\n // Remove card from all associated tags before deleting the card\n try {\n const appliedTags = await this.getAppliedTags(id);\n const results = await Promise.allSettled(\n appliedTags.rows.map(async (tagRow) => {\n const tagId = tagRow.id;\n await this.removeTagFromCard(id, tagId);\n })\n );\n\n // Log any individual tag cleanup failures\n results.forEach((result, index) => {\n if (result.status === 'rejected') {\n const tagId = appliedTags.rows[index].id;\n logger.error(`Failed to remove card ${id} from tag ${tagId}: ${result.reason}`);\n }\n });\n } catch (error) {\n logger.error(`Error removing card ${id} from tags: ${error}`);\n // Continue with card deletion even if tag cleanup fails\n }\n\n return this.remoteDB.remove(doc);\n }\n\n public async getCardDisplayableDataIDs(id: string[]) {\n logger.debug(id.join(', '));\n const cards = await this.db.allDocs<CardData>({\n keys: id,\n include_docs: true,\n });\n const ret: { [card: string]: string[] } = {};\n cards.rows.forEach((r) => {\n if (isSuccessRow(r)) {\n ret[r.id] = r.doc!.id_displayable_data;\n }\n });\n\n return ret;\n }\n\n async getCardsByELO(elo: number, cardLimit?: number) {\n elo = parseInt(elo as any);\n const limit = cardLimit ? cardLimit : 25;\n\n // const tQ0 = performance.now();\n // NOTE: `stale: 'update_after'` was tried here and removed — it gave no\n // measurable speedup (PouchDB 9 effectively ignores it for the reindex\n // cost) AND it can return an empty result on the first query after a cold\n // DB open (index not yet loaded), which then poisons the pool cache. The\n // session pool cache (see getCardsCenteredAtELO) is what removes the\n // per-run cost, so we read the view normally (always-fresh) here.\n const below: PouchDB.Query.Response<object> = await this.db.query('elo', {\n limit: Math.ceil(limit / 2),\n startkey: elo,\n descending: true,\n });\n // const tBelowQ = performance.now();\n\n const aboveLimit = limit - below.rows.length;\n\n const above: PouchDB.Query.Response<object> = await this.db.query('elo', {\n limit: aboveLimit,\n startkey: elo + 1,\n });\n // const tAbove = performance.now();\n // [perf] parked: getCardsByELO view-query timing (below/above split)\n // logger.info(\n // `[perf][getCardsByELO] reqLimit=${limit} ` +\n // `below=${(tBelowQ - tQ0).toFixed(0)}ms(${below.rows.length}r) ` +\n // `above=${(tAbove - tBelowQ).toFixed(0)}ms(${above.rows.length}r)`\n // );\n\n let cards = below.rows;\n cards = cards.concat(above.rows);\n\n const ret = cards\n .sort((a, b) => {\n const s = Math.abs(a.key - elo) - Math.abs(b.key - elo);\n if (s === 0) {\n return Math.random() - 0.5;\n } else {\n return s;\n }\n })\n .map((c) => {\n return {\n courseID: this.id,\n cardID: c.id,\n elo: c.key,\n };\n });\n\n const str = `below:\\n${below.rows.map((r) => `\\t${r.id}-${r.key}\\n`)}\n\nabove:\\n${above.rows.map((r) => `\\t${r.id}-${r.key}\\n`)}`;\n\n logger.debug(`Getting ${limit} cards centered around elo: ${elo}:\\n\\n` + str);\n\n return ret;\n }\n\n async getCourseConfig(): Promise<CourseConfig> {\n const ret = await getCredentialledCourseConfig(this.id);\n if (ret) {\n return ret;\n } else {\n throw new Error(`Course config not found for course ID: ${this.id}`);\n }\n }\n\n async updateCourseConfig(cfg: CourseConfig): Promise<PouchDB.Core.Response> {\n logger.debug(`Updating: ${JSON.stringify(cfg)}`);\n // write both to the course DB:\n try {\n return await updateCredentialledCourseConfig(this.id, cfg);\n } catch (error) {\n logger.error(`Error updating course config in course DB: ${error}`);\n throw error;\n }\n }\n\n async updateCardElo(cardId: string, elo: CourseElo): Promise<PouchDB.Core.Response> {\n if (!elo) {\n throw new Error(`Cannot update card elo with null or undefined value for card ID: ${cardId}`);\n }\n\n try {\n const result = await this.updateQueue.update<\n CardData & PouchDB.Core.GetMeta & PouchDB.Core.IdMeta\n >(cardId, (card) => {\n logger.debug(`Replacing ${JSON.stringify(card.elo)} with ${JSON.stringify(elo)}`);\n card.elo = elo;\n return card;\n });\n return { ok: true, id: cardId, rev: result._rev };\n } catch (error) {\n logger.error(`Failed to update card elo for card ID: ${cardId}`, error);\n throw new Error(`Failed to update card elo for card ID: ${cardId}`);\n }\n }\n\n async getAppliedTags(cardId: string): Promise<PouchDB.Query.Response<TagStub>> {\n // this.db: the local replica when one is ready (the module function is remote).\n return this.db.query<TagStub>('getTags', { startkey: cardId, endkey: cardId });\n }\n\n async getAppliedTagsBatch(cardIds: string[]): Promise<Map<string, string[]>> {\n if (cardIds.length === 0) {\n return new Map();\n }\n\n const result = await this.db.query<TagStub>('getTags', {\n keys: cardIds,\n include_docs: false,\n });\n\n const tagsByCard = new Map<string, string[]>();\n\n // Initialize all requested cards with empty arrays\n for (const cardId of cardIds) {\n tagsByCard.set(cardId, []);\n }\n\n // Populate from query results\n for (const row of result.rows) {\n const cardId = row.key as string;\n const tagName = row.value?.name;\n if (tagName && tagsByCard.has(cardId)) {\n tagsByCard.get(cardId)!.push(tagName);\n }\n }\n\n return tagsByCard;\n }\n\n async getAllCardIds(): Promise<string[]> {\n // Card `_id`s are minted as `<DocTypePrefixes[CARD]>-<...>` (see courseAPI),\n // i.e. the `c-` prefix \\u2014 for both framework-minted uuid ids (`c-<uuid>`) and\n // course-authored deterministic ids (e.g. LettersPractice's `c-intro-s-S`).\n //\n // The previous implementation hardcoded a `CARD-` prefix range, which never\n // matched any card and silently returned an EMPTY list, starving the only\n // callers (`forecast()` / `diagnoseCardSpace()`). Use the prefix const so\n // the range stays correct if the scheme ever changes.\n const prefix = `${DocTypePrefixes[DocType.CARD]}-`;\n const result = await this.db.allDocs({\n startkey: prefix,\n endkey: `${prefix}\\ufff0`,\n include_docs: false,\n });\n return result.rows.map((row) => row.id);\n }\n\n async addTagToCard(\n cardId: string,\n tagId: string,\n updateELO?: boolean\n ): Promise<PouchDB.Core.Response> {\n return await addTagToCard(\n this.id,\n cardId,\n tagId,\n (await this._getCurrentUser()).getUsername(),\n updateELO\n );\n }\n\n async removeTagFromCard(cardId: string, tagId: string): Promise<PouchDB.Core.Response> {\n return await removeTagFromCard(this.id, cardId, tagId);\n }\n\n async createTag(name: string, author: string): Promise<PouchDB.Core.Response> {\n return await createTag(this.id, name, author);\n }\n\n async getTag(tagId: string): Promise<PouchDB.Core.GetMeta & PouchDB.Core.Document<Tag>> {\n return await getTag(this.id, tagId);\n }\n\n async updateTag(tag: Tag): Promise<PouchDB.Core.Response> {\n if (tag.course !== this.id) {\n throw new Error(`Tag ${JSON.stringify(tag)} does not belong to course ${this.id}`);\n }\n\n return await updateTag(tag);\n }\n\n async getCourseTagStubs(): Promise<PouchDB.Core.AllDocsResponse<Tag>> {\n // this.db: the local replica when one is ready (the module function is remote).\n return filterAllDocsByPrefix<Tag>(this.db, DocType.TAG.valueOf() + '-');\n }\n\n async addNote(\n codeCourse: string,\n shape: DataShape,\n data: unknown,\n author: string,\n tags: string[],\n uploads?: { [key: string]: PouchDB.Core.FullAttachment },\n elo: CourseElo = blankCourseElo()\n ): Promise<DataLayerResult> {\n try {\n const resp = await addNote55(this.id, codeCourse, shape, data, author, tags, uploads, elo);\n if (resp.ok) {\n // Check if card creation failed (property added by addNote55)\n if ((resp as any).cardCreationFailed) {\n logger.warn(\n `[courseDB.addNote] Note added but card creation failed: ${\n (resp as any).cardCreationError\n }`\n );\n return {\n status: Status.error,\n message: `Note was added but no cards were created: ${(resp as any).cardCreationError}`,\n id: resp.id,\n };\n }\n return {\n status: Status.ok,\n message: '',\n id: resp.id,\n };\n } else {\n return {\n status: Status.error,\n message: 'Unexpected error adding note',\n };\n }\n } catch (e) {\n const err = e as PouchDB.Core.Error;\n logger.error(\n `[addNote] error ${err.name}\\n\\treason: ${err.reason}\\n\\tmessage: ${err.message}`\n );\n return {\n status: Status.error,\n message: `Error adding note to course. ${(e as PouchError).reason || err.message}`,\n };\n }\n }\n\n async getCourseDoc<T extends SkuilderCourseData>(\n id: string,\n options?: PouchDB.Core.GetOptions\n ): Promise<PouchDB.Core.GetMeta & PouchDB.Core.Document<T>> {\n // Use this.db (local when available) for read operations.\n // Falls back to the standalone helper (always remote) only if needed.\n return await this.db.get<T>(id, options ?? {}) as PouchDB.Core.GetMeta & PouchDB.Core.Document<T>;\n }\n\n async getCourseDocs<T extends SkuilderCourseData>(\n ids: string[],\n options: PouchDB.Core.AllDocsOptions = {}\n ): Promise<PouchDB.Core.AllDocsWithKeysResponse<{} & T>> {\n // Use this.db (local when available) for read operations.\n return await this.db.allDocs<T>({\n ...options,\n keys: ids,\n }) as PouchDB.Core.AllDocsWithKeysResponse<{} & T>;\n }\n\n ////////////////////////////////////\n // NavigationStrategyManager implementation\n ////////////////////////////////////\n\n getNavigationStrategy(id: string): Promise<ContentNavigationStrategyData> {\n logger.debug(`[courseDB] Getting navigation strategy: ${id}`);\n\n if (id == '') {\n const strategy: ContentNavigationStrategyData = {\n _id: 'NAVIGATION_STRATEGY-ELO',\n docType: DocType.NAVIGATION_STRATEGY,\n name: 'ELO',\n description: 'ELO-based navigation strategy for ordering content by difficulty',\n implementingClass: Navigators.ELO,\n course: this.id,\n serializedData: '', // serde is a noop for ELO navigator.\n };\n return Promise.resolve(strategy);\n } else {\n return this.db.get(id);\n }\n }\n\n async getAllNavigationStrategies(): Promise<ContentNavigationStrategyData[]> {\n const prefix = DocTypePrefixes[DocType.NAVIGATION_STRATEGY];\n const result = await this.db.allDocs<ContentNavigationStrategyData>({\n startkey: prefix,\n endkey: `${prefix}\\ufff0`,\n include_docs: true,\n });\n return result.rows.map((row) => row.doc!);\n }\n\n async addNavigationStrategy(data: ContentNavigationStrategyData): Promise<void> {\n logger.debug(`[courseDB] Adding navigation strategy: ${data._id}`);\n // Strategy set changed — drop the cached navigator so it rebuilds.\n this.invalidateNavigatorCache();\n // Admin write operation — use remote DB.\n return this.remoteDB.put(data).then(() => {});\n }\n updateNavigationStrategy(id: string, data: ContentNavigationStrategyData): Promise<void> {\n logger.debug(`[courseDB] Updating navigation strategy: ${id}`);\n // For now, just log the data and return success\n logger.debug(JSON.stringify(data));\n return Promise.resolve();\n }\n\n /**\n * Creates an instantiated navigator for this course.\n *\n * Handles multiple generators by wrapping them in CompositeGenerator.\n * This is the preferred method for getting a ready-to-use navigator.\n *\n * @param user - User database interface\n * @returns Instantiated ContentNavigator ready for use\n */\n async createNavigator(user: UserDBInterface): Promise<ContentNavigator> {\n try {\n const allStrategies = await this.getAllNavigationStrategies();\n\n if (allStrategies.length === 0) {\n // No strategies configured: use default Pipeline(Composite(ELO, SRS), [eloDistanceFilter])\n logger.debug(\n '[courseDB] No strategy documents found, using default Pipeline(Composite(ELO, SRS), [eloDistanceFilter])'\n );\n return createDefaultPipeline(user, this);\n }\n\n // Use PipelineAssembler to build a Pipeline from strategy documents\n const assembler = new PipelineAssembler();\n const { pipeline, generatorStrategies, filterStrategies, warnings } =\n await assembler.assemble({\n strategies: allStrategies,\n user,\n course: this,\n });\n\n // Log any warnings from assembly\n for (const warning of warnings) {\n logger.warn(`[PipelineAssembler] ${warning}`);\n }\n\n if (!pipeline) {\n // Assembly failed - fall back to default\n logger.debug('[courseDB] Pipeline assembly failed, using default pipeline');\n return createDefaultPipeline(user, this);\n }\n\n logger.debug(\n `[courseDB] Using assembled pipeline with ${generatorStrategies.length} generator(s) and ${filterStrategies.length} filter(s)`\n );\n return pipeline;\n } catch (e) {\n const msg = e instanceof Error ? `${e.message}\\n${e.stack}` : JSON.stringify(e);\n logger.error(`[courseDB] Error creating navigator: ${msg}`);\n throw e;\n }\n }\n\n ////////////////////////////////////\n // END NavigationStrategyManager implementation\n ////////////////////////////////////\n\n ////////////////////////////////////\n // StudyContentSource implementation\n ////////////////////////////////////\n\n /**\n * Get cards with suitability scores for presentation.\n *\n * This is the PRIMARY API for content sources going forward. Delegates to the\n * course's configured NavigationStrategy to get scored candidates.\n *\n * @param limit - Maximum number of cards to return\n * @returns Cards sorted by score descending\n */\n private _pendingHints: ReplanHints | null = null;\n\n /**\n * Session-scoped cache of the broad ELO-neighbor pool used by\n * getCardsCenteredAtELO. The `elo` view query re-indexes on first touch per\n * call (PouchDB 9 ignores `stale`), so without this each plan/replan pays\n * ~1.5-2s. The pool is fetched once and re-ranked against the live (roaming)\n * ELO in memory on subsequent calls.\n */\n private _eloPoolCache: {\n rows: (QualifiedCardID & { elo?: number })[];\n fetchedAt: number;\n /** The ELO the pool was fetched around. */\n centerElo: number;\n } | null = null;\n private readonly _eloPoolTtlMs = 5 * 60 * 1000;\n /**\n * How far the target may move from the pool's centre before the pool is\n * refetched. Well above a learner's in-session roam; a different learner (or\n * a far-off explicit ELO) on the same CourseDB gets a pool of their own.\n */\n private readonly _eloPoolMaxDrift = 200;\n\n /**\n * Cached assembled navigator (Pipeline). createNavigator() reads strategy\n * docs and builds a fresh Pipeline every call — whose internal `_tagCache`\n * and `_cachedOrchestration` are designed to make replans cheap but never\n * survive, because the instance is discarded each run. Caching it lets those\n * caches persist across plan/replan within a session (SessionController holds\n * one CourseDB instance for the session's lifetime). Rebuilt on user change,\n * TTL expiry, or explicit invalidation after a strategy-doc write.\n */\n private _cachedNavigator: {\n navigator: ContentNavigator;\n userId: string;\n builtAt: number;\n } | null = null;\n private readonly _navigatorTtlMs = 5 * 60 * 1000;\n\n public setEphemeralHints(hints: ReplanHints): void {\n this._pendingHints = hints;\n }\n\n /**\n * Forward a presentation to the navigator (a new card restarts its intake\n * clock). Builds the navigator if the cached one has expired.\n */\n public notePresented(card: { cardId: string; courseId: string; status: string }): void {\n if (card.status !== 'new') return;\n void this._getCurrentUser()\n .then((u) => this._getCachedNavigator(u))\n .then(({ navigator }) => (navigator as StudyContentSource).notePresented?.(card))\n .catch((e) => logger.warn(`[courseDB] Could not note a presentation: ${e}`));\n }\n\n public async getWeightedCards(limit: number): Promise<GeneratorResult> {\n const u = await this._getCurrentUser();\n\n try {\n // const tNav0 = performance.now(); // [perf] parked\n const { navigator } = await this._getCachedNavigator(u);\n // const tNav1 = performance.now(); // [perf] parked\n if (this._pendingHints) {\n navigator.setEphemeralHints(this._pendingHints);\n this._pendingHints = null;\n }\n const result = await navigator.getWeightedCards(limit);\n // const tRun = performance.now(); // [perf] parked\n // [perf] parked 2026-05 (pipeline-docs-workup) — uncomment to re-measure\n // logger.info(\n // `[perf][courseDB] getWeightedCards(limit=${limit}): ` +\n // `navigator=${(tNav1 - tNav0).toFixed(0)}ms(${navCache}) ` +\n // `pipelineRun=${(tRun - tNav1).toFixed(0)}ms ` +\n // `total=${(tRun - tNav0).toFixed(0)}ms`\n // );\n return result;\n } catch (e) {\n logger.error(`[courseDB] Error getting weighted cards: ${e}`);\n throw e;\n }\n }\n\n /**\n * Return the assembled navigator, reusing the cached instance when possible.\n * Reuse preserves the Pipeline's per-session caches (tags, orchestration\n * context) across replans, which is the dominant per-replan cost once the\n * ELO-pool cost is removed. Rebuilds on user change or TTL expiry.\n */\n private async _getCachedNavigator(\n user: UserDBInterface\n ): Promise<{ navigator: ContentNavigator; cacheStatus: 'hit' | 'miss' }> {\n const userId = user.getUsername();\n const now = Date.now();\n if (\n this._cachedNavigator &&\n this._cachedNavigator.userId === userId &&\n now - this._cachedNavigator.builtAt < this._navigatorTtlMs\n ) {\n return { navigator: this._cachedNavigator.navigator, cacheStatus: 'hit' };\n }\n const navigator = await this.createNavigator(user);\n this._cachedNavigator = { navigator, userId, builtAt: now };\n return { navigator, cacheStatus: 'miss' };\n }\n\n /**\n * Drop the cached navigator so the next getWeightedCards() rebuilds it.\n * Call after mutating this course's navigation strategy documents.\n */\n public invalidateNavigatorCache(): void {\n this._cachedNavigator = null;\n }\n\n public async getCardsCenteredAtELO(\n options: {\n limit: number;\n elo: 'user' | 'random' | number;\n } = {\n limit: 99,\n elo: 'user',\n },\n filter?: (a: QualifiedCardID) => boolean\n ): Promise<StudySessionItem[]> {\n // [perf] parked: getCardsCenteredAtELO rewrite banner\n // logger.info('[perf][run] getCardsCenteredAtELO rewrite (session pool cache + in-memory recenter)');\n // const tCelo0 = performance.now();\n let targetElo: number;\n\n if (options.elo === 'user') {\n const u = await this._getCurrentUser();\n\n targetElo = -1;\n try {\n const courseDoc = (await u.getCourseRegistrationsDoc()).courses.find((c) => {\n return c.courseID === this.id;\n })!;\n targetElo = EloToNumber(courseDoc.elo);\n } catch {\n targetElo = 1000;\n }\n } else if (options.elo === 'random') {\n const bounds = await GET_CACHED(`elo-bounds-${this.id}`, () => this.getELOBounds());\n targetElo = Math.round(bounds.low + Math.random() * (bounds.high - bounds.low));\n // logger.log(`Picked ${targetElo} from [${bounds.low}, ${bounds.high}]`);\n } else {\n targetElo = options.elo;\n }\n\n // const tReg = performance.now();\n\n // Broad neighbor pool fetched once per session and re-used. We over-fetch\n // (POOL_SIZE >> limit) so that the in-memory active-card filter and the\n // slowly-roaming ELO both have ample headroom before a refetch is needed.\n const POOL_SIZE = Math.max(2000, options.limit * 4);\n const nowMs = Date.now();\n let cacheStatus: 'hit' | 'miss' | 'refresh' = 'hit';\n\n if (\n !this._eloPoolCache ||\n nowMs - this._eloPoolCache.fetchedAt > this._eloPoolTtlMs ||\n Math.abs(targetElo - this._eloPoolCache.centerElo) > this._eloPoolMaxDrift\n ) {\n // MISS: pay the (reindexing) view query once, then cache the raw pool.\n // Guard: never cache an EMPTY pool. A cold-DB-open or sync-race fetch can\n // transiently return [], and caching it would starve the session for the\n // whole TTL. Leaving the cache untouched lets the next call retry.\n const fetched = await this.getCardsByELO(targetElo, POOL_SIZE);\n if (fetched.length > 0) {\n this._eloPoolCache = { rows: fetched, fetchedAt: nowMs, centerElo: targetElo };\n }\n cacheStatus = 'miss';\n }\n\n // Apply the (fresh) caller filter, then re-center against the *current* ELO.\n // Returns a new array each call — the cached pool is never mutated, and the\n // ranking reflects the live ELO even as it drifts within a session.\n const rankAgainstCurrentElo = (): (QualifiedCardID & { elo?: number })[] => {\n const raw = this._eloPoolCache?.rows ?? [];\n const survivors = filter ? raw.filter((c) => filter(c)) : raw;\n return survivors\n .map((c) => ({ ...c }))\n .sort(\n (a, b) =>\n Math.abs((a.elo ?? targetElo) - targetElo) -\n Math.abs((b.elo ?? targetElo) - targetElo)\n );\n };\n\n let cards = rankAgainstCurrentElo();\n\n // Refetch once if the pool can't satisfy the limit — either the active-card\n // filter has grown past pool coverage (hit), or the pool is missing because\n // a prior fetch came back empty (cold open / sync race). A miss that cached\n // a non-empty-but-small pool (genuinely small course) is left alone.\n if (cards.length < options.limit && (cacheStatus === 'hit' || !this._eloPoolCache)) {\n const fetched = await this.getCardsByELO(targetElo, POOL_SIZE);\n if (fetched.length > 0) {\n this._eloPoolCache = { rows: fetched, fetchedAt: nowMs, centerElo: targetElo };\n }\n cards = rankAgainstCurrentElo();\n cacheStatus = 'refresh';\n }\n\n // [perf] parked: centeredAtELO regDoc / pool-cache timing\n // logger.info(\n // `[perf][centeredAtELO] regDoc=${(tReg - tCelo0).toFixed(0)}ms ` +\n // `cache=${cacheStatus} build=${(performance.now() - tReg).toFixed(0)}ms ` +\n // `poolRaw=${this._eloPoolCache?.rows.length ?? 0} postFilter=${cards.length} ` +\n // `limit=${options.limit} targetElo=${targetElo}`\n // );\n\n const selectedCards: {\n courseID: string;\n cardID: string;\n elo?: number;\n }[] = [];\n\n while (selectedCards.length < options.limit && cards.length > 0) {\n const index = randIntWeightedTowardZero(cards.length);\n const card = cards.splice(index, 1)[0];\n selectedCards.push(card);\n }\n\n return selectedCards.map((c) => {\n return {\n courseID: this.id,\n cardID: c.cardID,\n contentSourceType: 'course',\n contentSourceID: this.id,\n elo: c.elo,\n status: 'new',\n };\n });\n }\n\n // Admin search methods\n public async searchCards(query: string): Promise<any[]> {\n logger.log(`[CourseDB ${this.id}] Searching for: \"${query}\"`);\n\n // Try multiple search approaches\n let displayableData;\n\n try {\n // Try regex search on the correct data structure: data[0].data\n displayableData = await this.db.find({\n selector: {\n docType: 'DISPLAYABLE_DATA',\n 'data.0.data': { $regex: `.*${query}.*` },\n },\n });\n logger.log(`[CourseDB ${this.id}] Regex search on data[0].data successful`);\n } catch (regexError) {\n logger.log(\n `[CourseDB ${this.id}] Regex search failed, falling back to manual search:`,\n regexError\n );\n\n // Fallback: get all displayable data and filter manually\n const allDisplayable = await this.db.find({\n selector: {\n docType: 'DISPLAYABLE_DATA',\n },\n });\n\n logger.log(\n `[CourseDB ${this.id}] Retrieved ${allDisplayable.docs.length} documents for manual filtering`\n );\n\n displayableData = {\n docs: allDisplayable.docs.filter((doc) => {\n // Search entire document as JSON string - inclusive approach for admin tool\n const docString = JSON.stringify(doc).toLowerCase();\n const match = docString.includes(query.toLowerCase());\n if (match) {\n logger.log(`[CourseDB ${this.id}] Manual match found in document: ${doc._id}`);\n }\n return match;\n }),\n };\n }\n\n logger.log(\n `[CourseDB ${this.id}] Found ${displayableData.docs.length} displayable data documents`\n );\n\n if (displayableData.docs.length === 0) {\n // Debug: Let's see what displayable data exists\n const allDisplayableData = await this.db.find({\n selector: {\n docType: 'DISPLAYABLE_DATA',\n },\n limit: 5, // Just sample a few\n });\n\n logger.log(\n `[CourseDB ${this.id}] Sample displayable data:`,\n allDisplayableData.docs.map((d) => ({\n id: d._id,\n docType: (d as any).docType,\n dataStructure: (d as any).data ? Object.keys((d as any).data) : 'no data field',\n dataContent: (d as any).data,\n fullDoc: d,\n }))\n );\n }\n\n const allResults: any[] = [];\n\n for (const dd of displayableData.docs) {\n const cards = await this.db.find({\n selector: {\n docType: 'CARD',\n id_displayable_data: { $in: [dd._id] },\n },\n });\n\n logger.log(\n `[CourseDB ${this.id}] Displayable data ${dd._id} linked to ${cards.docs.length} cards`\n );\n allResults.push(...cards.docs);\n }\n\n logger.log(`[CourseDB ${this.id}] Total cards found: ${allResults.length}`);\n return allResults;\n }\n\n public async find(\n request: PouchDB.Find.FindRequest<any>\n ): Promise<PouchDB.Find.FindResponse<any>> {\n return this.db.find(request);\n }\n}\n\n/**\n * Returns a list of registered datashapes for the specified\n * course.\n * @param courseID The ID of the course\n */\nexport async function getCourseDataShapes(courseID: string) {\n const cfg = await getCredentialledCourseConfig(courseID);\n return cfg!.dataShapes;\n}\n\nexport async function getCredentialledDataShapes(courseID: string) {\n const cfg = await getCredentialledCourseConfig(courseID);\n\n return cfg.dataShapes;\n}\n\nexport async function getCourseQuestionTypes(courseID: string) {\n const cfg = await getCredentialledCourseConfig(courseID);\n return cfg!.questionTypes;\n}\n\n// todo: this is actually returning full tag docs now.\n// - performance issue when tags have lots of\n// applied docs\n// - will require a computed couch DB view\nexport async function getCourseTagStubs(\n courseID: string\n): Promise<PouchDB.Core.AllDocsResponse<Tag>> {\n logger.debug(`Getting tag stubs for course: ${courseID}`);\n const stubs = await filterAllDocsByPrefix<Tag>(\n getCourseDB(courseID),\n DocType.TAG.valueOf() + '-'\n );\n\n stubs.rows.forEach((row) => {\n logger.debug(`\\tTag stub for doc: ${row.id}`);\n });\n\n return stubs;\n}\n\nexport async function deleteTag(courseID: string, tagName: string) {\n tagName = getTagID(tagName);\n const courseDB = getCourseDB(courseID);\n const doc = await courseDB.get<Tag>(DocType.TAG.valueOf() + '-' + tagName);\n const resp = await courseDB.remove(doc);\n return resp;\n}\n\nexport async function createTag(courseID: string, tagName: string, author: string) {\n logger.debug(`Creating tag: ${tagName}...`);\n const tagID = getTagID(tagName);\n const courseDB = getCourseDB(courseID);\n const resp = await courseDB.put<Tag>({\n course: courseID,\n docType: DocType.TAG,\n name: tagName,\n snippet: '',\n taggedCards: [],\n wiki: '',\n author,\n _id: tagID,\n });\n return resp;\n}\n\nexport async function updateTag(tag: Tag) {\n const prior = await getTag(tag.course, tag.name);\n return await getCourseDB(tag.course).put<Tag>({\n ...tag,\n _rev: prior._rev,\n });\n}\n\nexport async function getTag(courseID: string, tagName: string) {\n const tagID = getTagID(tagName);\n const courseDB = getCourseDB(courseID);\n return courseDB.get<Tag>(tagID);\n}\n\nexport async function removeTagFromCard(courseID: string, cardID: string, tagID: string) {\n // todo: possible future perf. hit if tags have large #s of taggedCards.\n // In this case, should be converted to a server-request\n tagID = getTagID(tagID);\n const courseDB = getCourseDB(courseID);\n const tag = await courseDB.get<Tag>(tagID);\n tag.taggedCards = tag.taggedCards.filter((taggedID) => {\n return cardID !== taggedID;\n });\n return courseDB.put<Tag>(tag);\n}\n\n/**\n * Returns an array of ancestor tag IDs, where:\n * return[0] = parent,\n * return[1] = grandparent,\n * return[2] = great grandparent,\n * etc.\n *\n * If ret is empty, the tag itself is a root\n */\nexport function getAncestorTagIDs(courseID: string, tagID: string): string[] {\n tagID = getTagID(tagID);\n const split = tagID.split('>');\n if (split.length === 1) {\n return [];\n } else {\n split.pop();\n const parent = split.join('>');\n return [parent].concat(getAncestorTagIDs(courseID, parent));\n }\n}\n\nexport async function getChildTagStubs(courseID: string, tagID: string) {\n return await filterAllDocsByPrefix(getCourseDB(courseID), tagID + '>');\n}\n\nexport async function getAppliedTags(id_course: string, id_card: string) {\n const db = getCourseDB(id_course);\n\n const result = await db.query<TagStub>('getTags', {\n startkey: id_card,\n endkey: id_card,\n // include_docs: true\n });\n\n // log(`getAppliedTags looked up: ${id_card}`);\n // log(`getAppliedTags returning: ${JSON.stringify(result)}`);\n\n return result;\n}\n\nexport async function updateCardElo(courseID: string, cardID: string, elo: CourseElo) {\n if (elo) {\n // checking against null, undefined, NaN\n const cDB = getCourseDB(courseID);\n const card = await cDB.get<CardData>(cardID);\n logger.debug(`Replacing ${JSON.stringify(card.elo)} with ${JSON.stringify(elo)}`);\n card.elo = elo;\n return cDB.put(card); // race conditions - is it important? probably not (net-zero effect)\n }\n}\n\nexport async function updateCredentialledCourseConfig(courseID: string, config: CourseConfig) {\n logger.debug(`Updating course config:\n\n${JSON.stringify(config)}\n`);\n\n const db = getCourseDB(courseID);\n invalidateCourseConfigCache(courseID);\n const old = await getCredentialledCourseConfig(courseID);\n\n try {\n return await db.put<CourseConfig>({\n ...config,\n _rev: (old as any)._rev,\n });\n } finally {\n invalidateCourseConfigCache(courseID);\n }\n}\n\nfunction isSuccessRow<T>(\n row:\n | {\n key: PouchDB.Core.DocumentKey;\n error: 'not_found';\n }\n | {\n doc?: PouchDB.Core.ExistingDocument<PouchDB.Core.AllDocsMeta & T> | null | undefined;\n id: PouchDB.Core.DocumentId;\n key: PouchDB.Core.DocumentKey;\n value: {\n rev: PouchDB.Core.RevisionId;\n deleted?: boolean | undefined;\n };\n }\n): row is {\n doc?: PouchDB.Core.ExistingDocument<PouchDB.Core.AllDocsMeta & T> | null | undefined;\n id: PouchDB.Core.DocumentId;\n key: PouchDB.Core.DocumentKey;\n value: {\n rev: PouchDB.Core.RevisionId;\n deleted?: boolean | undefined;\n };\n} {\n return 'doc' in row && row.doc !== null && row.doc !== undefined;\n}\n"],"mappings":";;;;;;;;;;;;;AA0CA,IAAa,YAAb,MAAqD;CACnD;CAEA,YAAY,WAAsB;AAChC,MAAI,aAAa,UAAU,SAAS,EAClC,MAAK,aAAa;MAElB,MAAK,aAAa,KAAA;;CAItB,MAAa,gBAAyC;EACpD,IAAI,UAAU,MAAM,aAAa,eAAe;AAChD,SAAO,MAAM,eAAe,QAAQ,KAAK,MAAM,EAAE,OAAO,OAAO,EAAE,MAAM,MAAO,GAAG;AACjF,MAAI,KAAK,WACP,WAAU,QAAQ,QAAQ,MAAM,KAAK,WAAY,SAAS,EAAE,IAAI,CAAC;AAGnE,SAAO,MAAM,wBAAwB,QAAQ,KAAK,MAAM,EAAE,OAAO,OAAO,EAAE,MAAM,MAAO,GAAG;AAc1F,UAZa,MAAM,QAAQ,IACzB,QAAQ,IAAI,OAAO,MAAM;AACvB,OAAI;IACF,MAAM,MAAM,MAAM,6BAA6B,EAAE,IAAI;AACrD,WAAO,MAAM,cAAc,KAAK,UAAU,IAAI,GAAG;AACjD,WAAO;YACA,GAAG;AACV,WAAO,KAAK,iCAAiC,EAAE,KAAK,IAAI,EAAE,IAAI,IAAI,IAAI;AACtE;;IAEF,C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AAiB,UAAkB,OAAe;AACtE,QAAO,MAAM,sBAAsB,YAAY,SAAS,EAAE,QAAQ,IAAI;;AAGxE,eAAsB,eAAe,WAAmB,SAAiB;AAYvE,QATe,MAFJ,YAAY,UAAU,CAET,MAAe,WAAW;EAChD,UAAU;EACV,QAAQ;EAET,CAAC;;AAQJ,eAAsB,cAAc,UAAkB,QAAgB,KAAgB;AACpF,KAAI,KAAK;EAEP,MAAM,MAAM,YAAY,SAAS;EACjC,MAAM,OAAO,MAAM,IAAI,IAAc,OAAO;AAC5C,SAAO,MAAM,aAAa,KAAK,UAAU,KAAK,IAAI,CAAC,QAAQ,KAAK,UAAU,IAAI,GAAG;AACjF,OAAK,MAAM;AACX,SAAO,IAAI,IAAI,KAAK;;;AAIxB,eAAsB,gCAAgC,UAAkB,QAAsB;AAC5F,QAAO,MAAM;;EAEb,KAAK,UAAU,OAAO,CAAC;EACvB;CAEA,MAAM,KAAK,YAAY,SAAS;AAChC,6BAA4B,SAAS;CACrC,MAAM,MAAM,MAAM,6BAA6B,SAAS;AAExD,KAAI;AACF,SAAO,MAAM,GAAG,IAAkB;GAChC,GAAG;GACH,MAAO,IAAY;GACpB,CAAC;WACM;AACR,8BAA4B,SAAS;;;AAIzC,SAAS,aACP,KAsBA;AACA,QAAO,SAAS,OAAO,IAAI,QAAQ,QAAQ,IAAI,QAAQ,KAAA"}
1
+ {"version":3,"file":"courseDB.mjs","names":[],"sources":["../../../src/impl/couch/courseDB.ts"],"sourcesContent":["import { CourseDBInterface, CourseInfo, CoursesDBInterface, UserDBInterface } from '@db/core';\nimport type { GeneratorResult, ReplanHints } from '@db/core/navigators/generators/types';\nimport {\n CourseConfig,\n CourseElo,\n DataShape,\n EloToNumber,\n Status,\n blankCourseElo,\n toCourseElo,\n} from '@vue-skuilder/common';\n\nimport { filterAllDocsByPrefix, getCourseDB } from '.';\nimport UpdateQueue from './updateQueue';\nimport type { StudyContentSource } from '../../core/interfaces/contentSource';\nimport { StudySessionItem } from '../../core/interfaces/contentSource';\nimport {\n CardData,\n DocType,\n QualifiedCardID,\n SkuilderCourseData,\n Tag,\n TagStub,\n DocTypePrefixes,\n} from '../../core/types/types-legacy';\nimport { logger } from '../../util/logger';\nimport { GET_CACHED } from './clientCache';\nimport {\n addNote55,\n addTagToCard,\n getCredentialledCourseConfig,\n getTagID,\n invalidateCourseConfigCache,\n} from './courseAPI';\nimport { DataLayerResult } from '@db/core/types/db';\nimport { PouchError } from './types';\nimport CourseLookup from './courseLookupDB';\nimport { ContentNavigationStrategyData } from '@db/core/types/contentNavigationStrategy';\nimport { ContentNavigator, Navigators } from '@db/core/navigators';\nimport { PipelineAssembler } from '@db/core/navigators/PipelineAssembler';\nimport { createDefaultPipeline } from '@db/core/navigators/defaults';\n\nexport class CoursesDB implements CoursesDBInterface {\n _courseIDs: string[] | undefined;\n\n constructor(courseIDs?: string[]) {\n if (courseIDs && courseIDs.length > 0) {\n this._courseIDs = courseIDs;\n } else {\n this._courseIDs = undefined;\n }\n }\n\n public async getCourseList(): Promise<CourseConfig[]> {\n let crsList = await CourseLookup.allCourseWare();\n logger.debug(`AllCourses: ${crsList.map((c) => c.name + ', ' + c._id + '\\n\\t')}`);\n if (this._courseIDs) {\n crsList = crsList.filter((c) => this._courseIDs!.includes(c._id));\n }\n\n logger.debug(`AllCourses.filtered: ${crsList.map((c) => c.name + ', ' + c._id + '\\n\\t')}`);\n\n const cfgs = await Promise.all(\n crsList.map(async (c) => {\n try {\n const cfg = await getCredentialledCourseConfig(c._id);\n logger.debug(`Found cfg: ${JSON.stringify(cfg)}`);\n return cfg;\n } catch (e) {\n logger.warn(`Error fetching cfg for course ${c.name}, ${c._id}: ${e}`);\n return undefined;\n }\n })\n );\n return cfgs.filter((c) => !!c);\n }\n\n async getCourseConfig(courseId: string): Promise<CourseConfig> {\n if (this._courseIDs && this._courseIDs.length && !this._courseIDs.includes(courseId)) {\n throw new Error(`Course ${courseId} not in course list`);\n }\n\n const cfg = await getCredentialledCourseConfig(courseId);\n if (cfg === undefined) {\n throw new Error(`Error fetching cfg for course ${courseId}`);\n } else {\n return cfg;\n }\n }\n\n public async disambiguateCourse(courseId: string, disambiguator: string): Promise<void> {\n await CourseLookup.updateDisambiguator(courseId, disambiguator);\n }\n}\n\nfunction randIntWeightedTowardZero(n: number) {\n return Math.floor(Math.random() * Math.random() * Math.random() * n);\n}\n\nexport class CourseDB implements CourseDBInterface {\n // private log(msg: string): void {\n // log(`CourseLog: ${this.id}\\n ${msg}`);\n // }\n\n /**\n * Primary database handle used for all **read** operations (queries, gets).\n *\n * When local sync is active, this points to the local PouchDB replica for\n * fast, network-free reads. Otherwise it points to the remote CouchDB.\n */\n private db: PouchDB.Database;\n\n /**\n * Remote database handle used for all **write** operations.\n *\n * Always points to the remote CouchDB so that writes (ELO updates, tag\n * mutations, admin operations) aggregate on the server. The local replica\n * is a read-only snapshot that refreshes on the next page load.\n *\n * When local sync is NOT active, this is the same instance as `this.db`.\n */\n private remoteDB: PouchDB.Database;\n\n private id: string;\n private _getCurrentUser: () => Promise<UserDBInterface>;\n private updateQueue: UpdateQueue;\n\n /**\n * @param id - Course ID\n * @param userLookup - Async function returning the current user DB\n * @param localDB - Optional local PouchDB replica for reads. When provided,\n * `this.db` uses the local replica and `this.remoteDB` stays remote.\n * The UpdateQueue reads from remote and writes to remote (local `_rev`\n * values may be stale, so read-modify-write cycles must go through\n * the remote DB to avoid conflicts).\n */\n /** Reads go to this device's replica (perf marks report it as the session's binding). */\n public get readsLocal(): boolean {\n return this.db !== this.remoteDB;\n }\n\n constructor(id: string, userLookup: () => Promise<UserDBInterface>, localDB?: PouchDB.Database) {\n this.id = id;\n const remote = getCourseDB(this.id);\n this.remoteDB = remote;\n this.db = localDB ?? remote;\n this._getCurrentUser = userLookup;\n // UpdateQueue always operates against the remote DB for its\n // read-modify-write cycle. Local _rev values may be stale (the local\n // replica is a snapshot), so conflict retries must read from remote.\n this.updateQueue = new UpdateQueue(this.remoteDB, this.remoteDB);\n }\n\n public getCourseID(): string {\n return this.id;\n }\n\n public async getCourseInfo(): Promise<CourseInfo> {\n const cardCount = (\n await this.db.find({\n selector: {\n docType: DocType.CARD,\n },\n limit: 1000,\n })\n ).docs.length;\n\n return {\n cardCount,\n registeredUsers: 0,\n };\n }\n\n public async getInexperiencedCards(limit: number = 2) {\n return (\n await this.db.query('cardsByInexperience', {\n limit,\n })\n ).rows.map((r) => {\n const ret = {\n courseId: this.id,\n cardId: r.id,\n count: r.key,\n elo: r.value,\n };\n return ret;\n });\n }\n\n public async getCardsByEloLimits(\n options: {\n low: number;\n high: number;\n limit: number;\n page: number;\n } = {\n low: 0,\n high: Number.MIN_SAFE_INTEGER,\n limit: 25,\n page: 0,\n }\n ) {\n return (\n await this.db.query('elo', {\n startkey: options.low,\n endkey: options.high,\n limit: options.limit,\n skip: options.limit * options.page,\n })\n ).rows.map((r) => {\n return `${this.id}-${r.id}-${r.key}`;\n });\n }\n public async getCardEloData(id: string[]): Promise<CourseElo[]> {\n const docs = await this.db.allDocs<CardData>({\n keys: id,\n include_docs: true,\n });\n const ret: CourseElo[] = [];\n docs.rows.forEach((r) => {\n // [ ] remove these ts-ignore directives.\n if (isSuccessRow(r)) {\n if (r.doc && r.doc.elo) {\n ret.push(toCourseElo(r.doc.elo));\n } else {\n logger.warn('no elo data for card: ' + r.id);\n ret.push(blankCourseElo());\n }\n } else {\n logger.warn('no elo data for card: ' + JSON.stringify(r));\n ret.push(blankCourseElo());\n }\n });\n return ret;\n }\n\n /**\n * Returns the lowest and highest `global` ELO ratings in the course\n */\n public async getELOBounds() {\n const [low, high] = await Promise.all([\n (\n await this.db.query('elo', {\n startkey: 0,\n limit: 1,\n include_docs: false,\n })\n ).rows[0].key,\n (\n await this.db.query('elo', {\n limit: 1,\n descending: true,\n startkey: 100_000,\n })\n ).rows[0].key,\n ]);\n\n return {\n low: low,\n high: high,\n };\n }\n\n public async removeCard(id: string) {\n // Admin operation — read and write both go through remote DB to ensure\n // we have the current _rev for the delete.\n const doc = await this.remoteDB.get<CardData>(id);\n if (!doc.docType || !(doc.docType === DocType.CARD)) {\n throw new Error(`failed to remove ${id} from course ${this.id}. id does not point to a card`);\n }\n\n // Remove card from all associated tags before deleting the card\n try {\n const appliedTags = await this.getAppliedTags(id);\n const results = await Promise.allSettled(\n appliedTags.rows.map(async (tagRow) => {\n const tagId = tagRow.id;\n await this.removeTagFromCard(id, tagId);\n })\n );\n\n // Log any individual tag cleanup failures\n results.forEach((result, index) => {\n if (result.status === 'rejected') {\n const tagId = appliedTags.rows[index].id;\n logger.error(`Failed to remove card ${id} from tag ${tagId}: ${result.reason}`);\n }\n });\n } catch (error) {\n logger.error(`Error removing card ${id} from tags: ${error}`);\n // Continue with card deletion even if tag cleanup fails\n }\n\n return this.remoteDB.remove(doc);\n }\n\n public async getCardDisplayableDataIDs(id: string[]) {\n logger.debug(id.join(', '));\n const cards = await this.db.allDocs<CardData>({\n keys: id,\n include_docs: true,\n });\n const ret: { [card: string]: string[] } = {};\n cards.rows.forEach((r) => {\n if (isSuccessRow(r)) {\n ret[r.id] = r.doc!.id_displayable_data;\n }\n });\n\n return ret;\n }\n\n async getCardsByELO(elo: number, cardLimit?: number) {\n elo = parseInt(elo as any);\n const limit = cardLimit ? cardLimit : 25;\n\n // const tQ0 = performance.now();\n // NOTE: `stale: 'update_after'` was tried here and removed — it gave no\n // measurable speedup (PouchDB 9 effectively ignores it for the reindex\n // cost) AND it can return an empty result on the first query after a cold\n // DB open (index not yet loaded), which then poisons the pool cache. The\n // session pool cache (see getCardsCenteredAtELO) is what removes the\n // per-run cost, so we read the view normally (always-fresh) here.\n const below: PouchDB.Query.Response<object> = await this.db.query('elo', {\n limit: Math.ceil(limit / 2),\n startkey: elo,\n descending: true,\n });\n // const tBelowQ = performance.now();\n\n const aboveLimit = limit - below.rows.length;\n\n const above: PouchDB.Query.Response<object> = await this.db.query('elo', {\n limit: aboveLimit,\n startkey: elo + 1,\n });\n // const tAbove = performance.now();\n // [perf] parked: getCardsByELO view-query timing (below/above split)\n // logger.info(\n // `[perf][getCardsByELO] reqLimit=${limit} ` +\n // `below=${(tBelowQ - tQ0).toFixed(0)}ms(${below.rows.length}r) ` +\n // `above=${(tAbove - tBelowQ).toFixed(0)}ms(${above.rows.length}r)`\n // );\n\n let cards = below.rows;\n cards = cards.concat(above.rows);\n\n const ret = cards\n .sort((a, b) => {\n const s = Math.abs(a.key - elo) - Math.abs(b.key - elo);\n if (s === 0) {\n return Math.random() - 0.5;\n } else {\n return s;\n }\n })\n .map((c) => {\n return {\n courseID: this.id,\n cardID: c.id,\n elo: c.key,\n };\n });\n\n const str = `below:\\n${below.rows.map((r) => `\\t${r.id}-${r.key}\\n`)}\n\nabove:\\n${above.rows.map((r) => `\\t${r.id}-${r.key}\\n`)}`;\n\n logger.debug(`Getting ${limit} cards centered around elo: ${elo}:\\n\\n` + str);\n\n return ret;\n }\n\n async getCourseConfig(): Promise<CourseConfig> {\n const ret = await getCredentialledCourseConfig(this.id);\n if (ret) {\n return ret;\n } else {\n throw new Error(`Course config not found for course ID: ${this.id}`);\n }\n }\n\n async updateCourseConfig(cfg: CourseConfig): Promise<PouchDB.Core.Response> {\n logger.debug(`Updating: ${JSON.stringify(cfg)}`);\n // write both to the course DB:\n try {\n return await updateCredentialledCourseConfig(this.id, cfg);\n } catch (error) {\n logger.error(`Error updating course config in course DB: ${error}`);\n throw error;\n }\n }\n\n async updateCardElo(cardId: string, elo: CourseElo): Promise<PouchDB.Core.Response> {\n if (!elo) {\n throw new Error(`Cannot update card elo with null or undefined value for card ID: ${cardId}`);\n }\n\n try {\n const result = await this.updateQueue.update<\n CardData & PouchDB.Core.GetMeta & PouchDB.Core.IdMeta\n >(cardId, (card) => {\n logger.debug(`Replacing ${JSON.stringify(card.elo)} with ${JSON.stringify(elo)}`);\n card.elo = elo;\n return card;\n });\n return { ok: true, id: cardId, rev: result._rev };\n } catch (error) {\n logger.error(`Failed to update card elo for card ID: ${cardId}`, error);\n throw new Error(`Failed to update card elo for card ID: ${cardId}`);\n }\n }\n\n async getAppliedTags(cardId: string): Promise<PouchDB.Query.Response<TagStub>> {\n // this.db: the local replica when one is ready (the module function is remote).\n return this.db.query<TagStub>('getTags', { startkey: cardId, endkey: cardId });\n }\n\n async getAppliedTagsBatch(cardIds: string[]): Promise<Map<string, string[]>> {\n if (cardIds.length === 0) {\n return new Map();\n }\n\n const result = await this.db.query<TagStub>('getTags', {\n keys: cardIds,\n include_docs: false,\n });\n\n const tagsByCard = new Map<string, string[]>();\n\n // Initialize all requested cards with empty arrays\n for (const cardId of cardIds) {\n tagsByCard.set(cardId, []);\n }\n\n // Populate from query results\n for (const row of result.rows) {\n const cardId = row.key as string;\n const tagName = row.value?.name;\n if (tagName && tagsByCard.has(cardId)) {\n tagsByCard.get(cardId)!.push(tagName);\n }\n }\n\n return tagsByCard;\n }\n\n async getAllCardIds(): Promise<string[]> {\n // Card `_id`s are minted as `<DocTypePrefixes[CARD]>-<...>` (see courseAPI),\n // i.e. the `c-` prefix \\u2014 for both framework-minted uuid ids (`c-<uuid>`) and\n // course-authored deterministic ids (e.g. LettersPractice's `c-intro-s-S`).\n //\n // The previous implementation hardcoded a `CARD-` prefix range, which never\n // matched any card and silently returned an EMPTY list, starving the only\n // callers (`forecast()` / `diagnoseCardSpace()`). Use the prefix const so\n // the range stays correct if the scheme ever changes.\n const prefix = `${DocTypePrefixes[DocType.CARD]}-`;\n const result = await this.db.allDocs({\n startkey: prefix,\n endkey: `${prefix}\\ufff0`,\n include_docs: false,\n });\n return result.rows.map((row) => row.id);\n }\n\n async addTagToCard(\n cardId: string,\n tagId: string,\n updateELO?: boolean\n ): Promise<PouchDB.Core.Response> {\n return await addTagToCard(\n this.id,\n cardId,\n tagId,\n (await this._getCurrentUser()).getUsername(),\n updateELO\n );\n }\n\n async removeTagFromCard(cardId: string, tagId: string): Promise<PouchDB.Core.Response> {\n return await removeTagFromCard(this.id, cardId, tagId);\n }\n\n async createTag(name: string, author: string): Promise<PouchDB.Core.Response> {\n return await createTag(this.id, name, author);\n }\n\n async getTag(tagId: string): Promise<PouchDB.Core.GetMeta & PouchDB.Core.Document<Tag>> {\n return await getTag(this.id, tagId);\n }\n\n async updateTag(tag: Tag): Promise<PouchDB.Core.Response> {\n if (tag.course !== this.id) {\n throw new Error(`Tag ${JSON.stringify(tag)} does not belong to course ${this.id}`);\n }\n\n return await updateTag(tag);\n }\n\n async getCourseTagStubs(): Promise<PouchDB.Core.AllDocsResponse<Tag>> {\n // this.db: the local replica when one is ready (the module function is remote).\n return filterAllDocsByPrefix<Tag>(this.db, DocType.TAG.valueOf() + '-');\n }\n\n async addNote(\n codeCourse: string,\n shape: DataShape,\n data: unknown,\n author: string,\n tags: string[],\n uploads?: { [key: string]: PouchDB.Core.FullAttachment },\n elo: CourseElo = blankCourseElo()\n ): Promise<DataLayerResult> {\n try {\n const resp = await addNote55(this.id, codeCourse, shape, data, author, tags, uploads, elo);\n if (resp.ok) {\n // Check if card creation failed (property added by addNote55)\n if ((resp as any).cardCreationFailed) {\n logger.warn(\n `[courseDB.addNote] Note added but card creation failed: ${\n (resp as any).cardCreationError\n }`\n );\n return {\n status: Status.error,\n message: `Note was added but no cards were created: ${(resp as any).cardCreationError}`,\n id: resp.id,\n };\n }\n return {\n status: Status.ok,\n message: '',\n id: resp.id,\n };\n } else {\n return {\n status: Status.error,\n message: 'Unexpected error adding note',\n };\n }\n } catch (e) {\n const err = e as PouchDB.Core.Error;\n logger.error(\n `[addNote] error ${err.name}\\n\\treason: ${err.reason}\\n\\tmessage: ${err.message}`\n );\n return {\n status: Status.error,\n message: `Error adding note to course. ${(e as PouchError).reason || err.message}`,\n };\n }\n }\n\n async getCourseDoc<T extends SkuilderCourseData>(\n id: string,\n options?: PouchDB.Core.GetOptions\n ): Promise<PouchDB.Core.GetMeta & PouchDB.Core.Document<T>> {\n // Use this.db (local when available) for read operations.\n // Falls back to the standalone helper (always remote) only if needed.\n return await this.db.get<T>(id, options ?? {}) as PouchDB.Core.GetMeta & PouchDB.Core.Document<T>;\n }\n\n async getCourseDocs<T extends SkuilderCourseData>(\n ids: string[],\n options: PouchDB.Core.AllDocsOptions = {}\n ): Promise<PouchDB.Core.AllDocsWithKeysResponse<{} & T>> {\n // Use this.db (local when available) for read operations.\n return await this.db.allDocs<T>({\n ...options,\n keys: ids,\n }) as PouchDB.Core.AllDocsWithKeysResponse<{} & T>;\n }\n\n ////////////////////////////////////\n // NavigationStrategyManager implementation\n ////////////////////////////////////\n\n getNavigationStrategy(id: string): Promise<ContentNavigationStrategyData> {\n logger.debug(`[courseDB] Getting navigation strategy: ${id}`);\n\n if (id == '') {\n const strategy: ContentNavigationStrategyData = {\n _id: 'NAVIGATION_STRATEGY-ELO',\n docType: DocType.NAVIGATION_STRATEGY,\n name: 'ELO',\n description: 'ELO-based navigation strategy for ordering content by difficulty',\n implementingClass: Navigators.ELO,\n course: this.id,\n serializedData: '', // serde is a noop for ELO navigator.\n };\n return Promise.resolve(strategy);\n } else {\n return this.db.get(id);\n }\n }\n\n async getAllNavigationStrategies(): Promise<ContentNavigationStrategyData[]> {\n const prefix = DocTypePrefixes[DocType.NAVIGATION_STRATEGY];\n const result = await this.db.allDocs<ContentNavigationStrategyData>({\n startkey: prefix,\n endkey: `${prefix}\\ufff0`,\n include_docs: true,\n });\n return result.rows.map((row) => row.doc!);\n }\n\n async addNavigationStrategy(data: ContentNavigationStrategyData): Promise<void> {\n logger.debug(`[courseDB] Adding navigation strategy: ${data._id}`);\n // Strategy set changed — drop the cached navigator so it rebuilds.\n this.invalidateNavigatorCache();\n // Admin write operation — use remote DB.\n return this.remoteDB.put(data).then(() => {});\n }\n updateNavigationStrategy(id: string, data: ContentNavigationStrategyData): Promise<void> {\n logger.debug(`[courseDB] Updating navigation strategy: ${id}`);\n // For now, just log the data and return success\n logger.debug(JSON.stringify(data));\n return Promise.resolve();\n }\n\n /**\n * Creates an instantiated navigator for this course.\n *\n * Handles multiple generators by wrapping them in CompositeGenerator.\n * This is the preferred method for getting a ready-to-use navigator.\n *\n * @param user - User database interface\n * @returns Instantiated ContentNavigator ready for use\n */\n async createNavigator(user: UserDBInterface): Promise<ContentNavigator> {\n try {\n const allStrategies = await this.getAllNavigationStrategies();\n\n if (allStrategies.length === 0) {\n // No strategies configured: use default Pipeline(Composite(ELO, SRS), [eloDistanceFilter])\n logger.debug(\n '[courseDB] No strategy documents found, using default Pipeline(Composite(ELO, SRS), [eloDistanceFilter])'\n );\n return createDefaultPipeline(user, this);\n }\n\n // Use PipelineAssembler to build a Pipeline from strategy documents\n const assembler = new PipelineAssembler();\n const { pipeline, generatorStrategies, filterStrategies, warnings } =\n await assembler.assemble({\n strategies: allStrategies,\n user,\n course: this,\n });\n\n // Log any warnings from assembly\n for (const warning of warnings) {\n logger.warn(`[PipelineAssembler] ${warning}`);\n }\n\n if (!pipeline) {\n // Assembly failed - fall back to default\n logger.debug('[courseDB] Pipeline assembly failed, using default pipeline');\n return createDefaultPipeline(user, this);\n }\n\n logger.debug(\n `[courseDB] Using assembled pipeline with ${generatorStrategies.length} generator(s) and ${filterStrategies.length} filter(s)`\n );\n return pipeline;\n } catch (e) {\n const msg = e instanceof Error ? `${e.message}\\n${e.stack}` : JSON.stringify(e);\n logger.error(`[courseDB] Error creating navigator: ${msg}`);\n throw e;\n }\n }\n\n ////////////////////////////////////\n // END NavigationStrategyManager implementation\n ////////////////////////////////////\n\n ////////////////////////////////////\n // StudyContentSource implementation\n ////////////////////////////////////\n\n /**\n * Get cards with suitability scores for presentation.\n *\n * This is the PRIMARY API for content sources going forward. Delegates to the\n * course's configured NavigationStrategy to get scored candidates.\n *\n * @param limit - Maximum number of cards to return\n * @returns Cards sorted by score descending\n */\n private _pendingHints: ReplanHints | null = null;\n\n /**\n * Session-scoped cache of the broad ELO-neighbor pool used by\n * getCardsCenteredAtELO. The `elo` view query re-indexes on first touch per\n * call (PouchDB 9 ignores `stale`), so without this each plan/replan pays\n * ~1.5-2s. The pool is fetched once and re-ranked against the live (roaming)\n * ELO in memory on subsequent calls.\n */\n private _eloPoolCache: {\n rows: (QualifiedCardID & { elo?: number })[];\n fetchedAt: number;\n /** The ELO the pool was fetched around. */\n centerElo: number;\n } | null = null;\n private readonly _eloPoolTtlMs = 5 * 60 * 1000;\n /**\n * How far the target may move from the pool's centre before the pool is\n * refetched. Well above a learner's in-session roam; a different learner (or\n * a far-off explicit ELO) on the same CourseDB gets a pool of their own.\n */\n private readonly _eloPoolMaxDrift = 200;\n\n /**\n * Cached assembled navigator (Pipeline). createNavigator() reads strategy\n * docs and builds a fresh Pipeline every call — whose internal `_tagCache`\n * and `_cachedOrchestration` are designed to make replans cheap but never\n * survive, because the instance is discarded each run. Caching it lets those\n * caches persist across plan/replan within a session (SessionController holds\n * one CourseDB instance for the session's lifetime). Rebuilt on user change,\n * TTL expiry, or explicit invalidation after a strategy-doc write.\n */\n private _cachedNavigator: {\n navigator: ContentNavigator;\n userId: string;\n builtAt: number;\n } | null = null;\n private readonly _navigatorTtlMs = 5 * 60 * 1000;\n\n public setEphemeralHints(hints: ReplanHints): void {\n this._pendingHints = hints;\n }\n\n\n private _sessionId: string | null = null;\n\n\n public setSessionId(sessionId: string): void {\n\n this._sessionId = sessionId;\n\n }\n\n /**\n * Forward a presentation to the navigator (a new card restarts its intake\n * clock). Builds the navigator if the cached one has expired.\n */\n public notePresented(card: { cardId: string; courseId: string; status: string }): void {\n if (card.status !== 'new') return;\n void this._getCurrentUser()\n .then((u) => this._getCachedNavigator(u))\n .then(({ navigator }) => (navigator as StudyContentSource).notePresented?.(card))\n .catch((e) => logger.warn(`[courseDB] Could not note a presentation: ${e}`));\n }\n\n public async getWeightedCards(limit: number): Promise<GeneratorResult> {\n const u = await this._getCurrentUser();\n\n try {\n // const tNav0 = performance.now(); // [perf] parked\n const { navigator } = await this._getCachedNavigator(u);\n // const tNav1 = performance.now(); // [perf] parked\n if (this._pendingHints) {\n navigator.setEphemeralHints(this._pendingHints);\n this._pendingHints = null;\n }\n if (this._sessionId) {\n navigator.setSessionId(this._sessionId);\n }\n const result = await navigator.getWeightedCards(limit);\n // const tRun = performance.now(); // [perf] parked\n // [perf] parked 2026-05 (pipeline-docs-workup) — uncomment to re-measure\n // logger.info(\n // `[perf][courseDB] getWeightedCards(limit=${limit}): ` +\n // `navigator=${(tNav1 - tNav0).toFixed(0)}ms(${navCache}) ` +\n // `pipelineRun=${(tRun - tNav1).toFixed(0)}ms ` +\n // `total=${(tRun - tNav0).toFixed(0)}ms`\n // );\n return result;\n } catch (e) {\n logger.error(`[courseDB] Error getting weighted cards: ${e}`);\n throw e;\n }\n }\n\n /**\n * Return the assembled navigator, reusing the cached instance when possible.\n * Reuse preserves the Pipeline's per-session caches (tags, orchestration\n * context) across replans, which is the dominant per-replan cost once the\n * ELO-pool cost is removed. Rebuilds on user change or TTL expiry.\n */\n private async _getCachedNavigator(\n user: UserDBInterface\n ): Promise<{ navigator: ContentNavigator; cacheStatus: 'hit' | 'miss' }> {\n const userId = user.getUsername();\n const now = Date.now();\n if (\n this._cachedNavigator &&\n this._cachedNavigator.userId === userId &&\n now - this._cachedNavigator.builtAt < this._navigatorTtlMs\n ) {\n return { navigator: this._cachedNavigator.navigator, cacheStatus: 'hit' };\n }\n const navigator = await this.createNavigator(user);\n this._cachedNavigator = { navigator, userId, builtAt: now };\n return { navigator, cacheStatus: 'miss' };\n }\n\n /**\n * Drop the cached navigator so the next getWeightedCards() rebuilds it.\n * Call after mutating this course's navigation strategy documents.\n */\n public invalidateNavigatorCache(): void {\n this._cachedNavigator = null;\n }\n\n public async getCardsCenteredAtELO(\n options: {\n limit: number;\n elo: 'user' | 'random' | number;\n } = {\n limit: 99,\n elo: 'user',\n },\n filter?: (a: QualifiedCardID) => boolean\n ): Promise<StudySessionItem[]> {\n // [perf] parked: getCardsCenteredAtELO rewrite banner\n // logger.info('[perf][run] getCardsCenteredAtELO rewrite (session pool cache + in-memory recenter)');\n // const tCelo0 = performance.now();\n let targetElo: number;\n\n if (options.elo === 'user') {\n const u = await this._getCurrentUser();\n\n targetElo = -1;\n try {\n const courseDoc = (await u.getCourseRegistrationsDoc()).courses.find((c) => {\n return c.courseID === this.id;\n })!;\n targetElo = EloToNumber(courseDoc.elo);\n } catch {\n targetElo = 1000;\n }\n } else if (options.elo === 'random') {\n const bounds = await GET_CACHED(`elo-bounds-${this.id}`, () => this.getELOBounds());\n targetElo = Math.round(bounds.low + Math.random() * (bounds.high - bounds.low));\n // logger.log(`Picked ${targetElo} from [${bounds.low}, ${bounds.high}]`);\n } else {\n targetElo = options.elo;\n }\n\n // const tReg = performance.now();\n\n // Broad neighbor pool fetched once per session and re-used. We over-fetch\n // (POOL_SIZE >> limit) so that the in-memory active-card filter and the\n // slowly-roaming ELO both have ample headroom before a refetch is needed.\n const POOL_SIZE = Math.max(2000, options.limit * 4);\n const nowMs = Date.now();\n let cacheStatus: 'hit' | 'miss' | 'refresh' = 'hit';\n\n if (\n !this._eloPoolCache ||\n nowMs - this._eloPoolCache.fetchedAt > this._eloPoolTtlMs ||\n Math.abs(targetElo - this._eloPoolCache.centerElo) > this._eloPoolMaxDrift\n ) {\n // MISS: pay the (reindexing) view query once, then cache the raw pool.\n // Guard: never cache an EMPTY pool. A cold-DB-open or sync-race fetch can\n // transiently return [], and caching it would starve the session for the\n // whole TTL. Leaving the cache untouched lets the next call retry.\n const fetched = await this.getCardsByELO(targetElo, POOL_SIZE);\n if (fetched.length > 0) {\n this._eloPoolCache = { rows: fetched, fetchedAt: nowMs, centerElo: targetElo };\n }\n cacheStatus = 'miss';\n }\n\n // Apply the (fresh) caller filter, then re-center against the *current* ELO.\n // Returns a new array each call — the cached pool is never mutated, and the\n // ranking reflects the live ELO even as it drifts within a session.\n const rankAgainstCurrentElo = (): (QualifiedCardID & { elo?: number })[] => {\n const raw = this._eloPoolCache?.rows ?? [];\n const survivors = filter ? raw.filter((c) => filter(c)) : raw;\n return survivors\n .map((c) => ({ ...c }))\n .sort(\n (a, b) =>\n Math.abs((a.elo ?? targetElo) - targetElo) -\n Math.abs((b.elo ?? targetElo) - targetElo)\n );\n };\n\n let cards = rankAgainstCurrentElo();\n\n // Refetch once if the pool can't satisfy the limit — either the active-card\n // filter has grown past pool coverage (hit), or the pool is missing because\n // a prior fetch came back empty (cold open / sync race). A miss that cached\n // a non-empty-but-small pool (genuinely small course) is left alone.\n if (cards.length < options.limit && (cacheStatus === 'hit' || !this._eloPoolCache)) {\n const fetched = await this.getCardsByELO(targetElo, POOL_SIZE);\n if (fetched.length > 0) {\n this._eloPoolCache = { rows: fetched, fetchedAt: nowMs, centerElo: targetElo };\n }\n cards = rankAgainstCurrentElo();\n cacheStatus = 'refresh';\n }\n\n // [perf] parked: centeredAtELO regDoc / pool-cache timing\n // logger.info(\n // `[perf][centeredAtELO] regDoc=${(tReg - tCelo0).toFixed(0)}ms ` +\n // `cache=${cacheStatus} build=${(performance.now() - tReg).toFixed(0)}ms ` +\n // `poolRaw=${this._eloPoolCache?.rows.length ?? 0} postFilter=${cards.length} ` +\n // `limit=${options.limit} targetElo=${targetElo}`\n // );\n\n const selectedCards: {\n courseID: string;\n cardID: string;\n elo?: number;\n }[] = [];\n\n while (selectedCards.length < options.limit && cards.length > 0) {\n const index = randIntWeightedTowardZero(cards.length);\n const card = cards.splice(index, 1)[0];\n selectedCards.push(card);\n }\n\n return selectedCards.map((c) => {\n return {\n courseID: this.id,\n cardID: c.cardID,\n contentSourceType: 'course',\n contentSourceID: this.id,\n elo: c.elo,\n status: 'new',\n };\n });\n }\n\n // Admin search methods\n public async searchCards(query: string): Promise<any[]> {\n logger.log(`[CourseDB ${this.id}] Searching for: \"${query}\"`);\n\n // Try multiple search approaches\n let displayableData;\n\n try {\n // Try regex search on the correct data structure: data[0].data\n displayableData = await this.db.find({\n selector: {\n docType: 'DISPLAYABLE_DATA',\n 'data.0.data': { $regex: `.*${query}.*` },\n },\n });\n logger.log(`[CourseDB ${this.id}] Regex search on data[0].data successful`);\n } catch (regexError) {\n logger.log(\n `[CourseDB ${this.id}] Regex search failed, falling back to manual search:`,\n regexError\n );\n\n // Fallback: get all displayable data and filter manually\n const allDisplayable = await this.db.find({\n selector: {\n docType: 'DISPLAYABLE_DATA',\n },\n });\n\n logger.log(\n `[CourseDB ${this.id}] Retrieved ${allDisplayable.docs.length} documents for manual filtering`\n );\n\n displayableData = {\n docs: allDisplayable.docs.filter((doc) => {\n // Search entire document as JSON string - inclusive approach for admin tool\n const docString = JSON.stringify(doc).toLowerCase();\n const match = docString.includes(query.toLowerCase());\n if (match) {\n logger.log(`[CourseDB ${this.id}] Manual match found in document: ${doc._id}`);\n }\n return match;\n }),\n };\n }\n\n logger.log(\n `[CourseDB ${this.id}] Found ${displayableData.docs.length} displayable data documents`\n );\n\n if (displayableData.docs.length === 0) {\n // Debug: Let's see what displayable data exists\n const allDisplayableData = await this.db.find({\n selector: {\n docType: 'DISPLAYABLE_DATA',\n },\n limit: 5, // Just sample a few\n });\n\n logger.log(\n `[CourseDB ${this.id}] Sample displayable data:`,\n allDisplayableData.docs.map((d) => ({\n id: d._id,\n docType: (d as any).docType,\n dataStructure: (d as any).data ? Object.keys((d as any).data) : 'no data field',\n dataContent: (d as any).data,\n fullDoc: d,\n }))\n );\n }\n\n const allResults: any[] = [];\n\n for (const dd of displayableData.docs) {\n const cards = await this.db.find({\n selector: {\n docType: 'CARD',\n id_displayable_data: { $in: [dd._id] },\n },\n });\n\n logger.log(\n `[CourseDB ${this.id}] Displayable data ${dd._id} linked to ${cards.docs.length} cards`\n );\n allResults.push(...cards.docs);\n }\n\n logger.log(`[CourseDB ${this.id}] Total cards found: ${allResults.length}`);\n return allResults;\n }\n\n public async find(\n request: PouchDB.Find.FindRequest<any>\n ): Promise<PouchDB.Find.FindResponse<any>> {\n return this.db.find(request);\n }\n}\n\n/**\n * Returns a list of registered datashapes for the specified\n * course.\n * @param courseID The ID of the course\n */\nexport async function getCourseDataShapes(courseID: string) {\n const cfg = await getCredentialledCourseConfig(courseID);\n return cfg!.dataShapes;\n}\n\nexport async function getCredentialledDataShapes(courseID: string) {\n const cfg = await getCredentialledCourseConfig(courseID);\n\n return cfg.dataShapes;\n}\n\nexport async function getCourseQuestionTypes(courseID: string) {\n const cfg = await getCredentialledCourseConfig(courseID);\n return cfg!.questionTypes;\n}\n\n// todo: this is actually returning full tag docs now.\n// - performance issue when tags have lots of\n// applied docs\n// - will require a computed couch DB view\nexport async function getCourseTagStubs(\n courseID: string\n): Promise<PouchDB.Core.AllDocsResponse<Tag>> {\n logger.debug(`Getting tag stubs for course: ${courseID}`);\n const stubs = await filterAllDocsByPrefix<Tag>(\n getCourseDB(courseID),\n DocType.TAG.valueOf() + '-'\n );\n\n stubs.rows.forEach((row) => {\n logger.debug(`\\tTag stub for doc: ${row.id}`);\n });\n\n return stubs;\n}\n\nexport async function deleteTag(courseID: string, tagName: string) {\n tagName = getTagID(tagName);\n const courseDB = getCourseDB(courseID);\n const doc = await courseDB.get<Tag>(DocType.TAG.valueOf() + '-' + tagName);\n const resp = await courseDB.remove(doc);\n return resp;\n}\n\nexport async function createTag(courseID: string, tagName: string, author: string) {\n logger.debug(`Creating tag: ${tagName}...`);\n const tagID = getTagID(tagName);\n const courseDB = getCourseDB(courseID);\n const resp = await courseDB.put<Tag>({\n course: courseID,\n docType: DocType.TAG,\n name: tagName,\n snippet: '',\n taggedCards: [],\n wiki: '',\n author,\n _id: tagID,\n });\n return resp;\n}\n\nexport async function updateTag(tag: Tag) {\n const prior = await getTag(tag.course, tag.name);\n return await getCourseDB(tag.course).put<Tag>({\n ...tag,\n _rev: prior._rev,\n });\n}\n\nexport async function getTag(courseID: string, tagName: string) {\n const tagID = getTagID(tagName);\n const courseDB = getCourseDB(courseID);\n return courseDB.get<Tag>(tagID);\n}\n\nexport async function removeTagFromCard(courseID: string, cardID: string, tagID: string) {\n // todo: possible future perf. hit if tags have large #s of taggedCards.\n // In this case, should be converted to a server-request\n tagID = getTagID(tagID);\n const courseDB = getCourseDB(courseID);\n const tag = await courseDB.get<Tag>(tagID);\n tag.taggedCards = tag.taggedCards.filter((taggedID) => {\n return cardID !== taggedID;\n });\n return courseDB.put<Tag>(tag);\n}\n\n/**\n * Returns an array of ancestor tag IDs, where:\n * return[0] = parent,\n * return[1] = grandparent,\n * return[2] = great grandparent,\n * etc.\n *\n * If ret is empty, the tag itself is a root\n */\nexport function getAncestorTagIDs(courseID: string, tagID: string): string[] {\n tagID = getTagID(tagID);\n const split = tagID.split('>');\n if (split.length === 1) {\n return [];\n } else {\n split.pop();\n const parent = split.join('>');\n return [parent].concat(getAncestorTagIDs(courseID, parent));\n }\n}\n\nexport async function getChildTagStubs(courseID: string, tagID: string) {\n return await filterAllDocsByPrefix(getCourseDB(courseID), tagID + '>');\n}\n\nexport async function getAppliedTags(id_course: string, id_card: string) {\n const db = getCourseDB(id_course);\n\n const result = await db.query<TagStub>('getTags', {\n startkey: id_card,\n endkey: id_card,\n // include_docs: true\n });\n\n // log(`getAppliedTags looked up: ${id_card}`);\n // log(`getAppliedTags returning: ${JSON.stringify(result)}`);\n\n return result;\n}\n\nexport async function updateCardElo(courseID: string, cardID: string, elo: CourseElo) {\n if (elo) {\n // checking against null, undefined, NaN\n const cDB = getCourseDB(courseID);\n const card = await cDB.get<CardData>(cardID);\n logger.debug(`Replacing ${JSON.stringify(card.elo)} with ${JSON.stringify(elo)}`);\n card.elo = elo;\n return cDB.put(card); // race conditions - is it important? probably not (net-zero effect)\n }\n}\n\nexport async function updateCredentialledCourseConfig(courseID: string, config: CourseConfig) {\n logger.debug(`Updating course config:\n\n${JSON.stringify(config)}\n`);\n\n const db = getCourseDB(courseID);\n invalidateCourseConfigCache(courseID);\n const old = await getCredentialledCourseConfig(courseID);\n\n try {\n return await db.put<CourseConfig>({\n ...config,\n _rev: (old as any)._rev,\n });\n } finally {\n invalidateCourseConfigCache(courseID);\n }\n}\n\nfunction isSuccessRow<T>(\n row:\n | {\n key: PouchDB.Core.DocumentKey;\n error: 'not_found';\n }\n | {\n doc?: PouchDB.Core.ExistingDocument<PouchDB.Core.AllDocsMeta & T> | null | undefined;\n id: PouchDB.Core.DocumentId;\n key: PouchDB.Core.DocumentKey;\n value: {\n rev: PouchDB.Core.RevisionId;\n deleted?: boolean | undefined;\n };\n }\n): row is {\n doc?: PouchDB.Core.ExistingDocument<PouchDB.Core.AllDocsMeta & T> | null | undefined;\n id: PouchDB.Core.DocumentId;\n key: PouchDB.Core.DocumentKey;\n value: {\n rev: PouchDB.Core.RevisionId;\n deleted?: boolean | undefined;\n };\n} {\n return 'doc' in row && row.doc !== null && row.doc !== undefined;\n}\n"],"mappings":";;;;;;;;;;;;;AA0CA,IAAa,YAAb,MAAqD;CACnD;CAEA,YAAY,WAAsB;AAChC,MAAI,aAAa,UAAU,SAAS,EAClC,MAAK,aAAa;MAElB,MAAK,aAAa,KAAA;;CAItB,MAAa,gBAAyC;EACpD,IAAI,UAAU,MAAM,aAAa,eAAe;AAChD,SAAO,MAAM,eAAe,QAAQ,KAAK,MAAM,EAAE,OAAO,OAAO,EAAE,MAAM,MAAO,GAAG;AACjF,MAAI,KAAK,WACP,WAAU,QAAQ,QAAQ,MAAM,KAAK,WAAY,SAAS,EAAE,IAAI,CAAC;AAGnE,SAAO,MAAM,wBAAwB,QAAQ,KAAK,MAAM,EAAE,OAAO,OAAO,EAAE,MAAM,MAAO,GAAG;AAc1F,UAZa,MAAM,QAAQ,IACzB,QAAQ,IAAI,OAAO,MAAM;AACvB,OAAI;IACF,MAAM,MAAM,MAAM,6BAA6B,EAAE,IAAI;AACrD,WAAO,MAAM,cAAc,KAAK,UAAU,IAAI,GAAG;AACjD,WAAO;YACA,GAAG;AACV,WAAO,KAAK,iCAAiC,EAAE,KAAK,IAAI,EAAE,IAAI,IAAI,IAAI;AACtE;;IAEF,CACH,EACW,QAAQ,MAAM,CAAC,CAAC,EAAE;;CAGhC,MAAM,gBAAgB,UAAyC;AAC7D,MAAI,KAAK,cAAc,KAAK,WAAW,UAAU,CAAC,KAAK,WAAW,SAAS,SAAS,CAClF,OAAM,IAAI,MAAM,UAAU,SAAS,qBAAqB;EAG1D,MAAM,MAAM,MAAM,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AiB;AAYvE,QATe,MAFJ,YAAY,UAAU,CAET,MAAe,WAAW;EAChD,UAAU;EACV,QAAQ;EAET,CAAC;;AAQJ,eAAsB,cAAc,UAAkB,QAAgB,KAAgB;AACpF,KAAI,KAAK;EAEP,MAAM,MAAM,YAAY,SAAS;EACjC,MAAM,OAAO,MAAM,IAAI,IAAc,OAAO;AAC5C,SAAO,MAAM,aAAa,KAAK,UAAU,KAAK,IAAI,CAAC,QAAQ,KAAK,UAAU,IAAI,GAAG;AACjF,OAAK,MAAM;AACX,SAAO,IAAI,IAAI,KAAK;;;AAIxB,eAAsB,gCAAgC,UAAkB,QAAsB;AAC5F,QAAO,MAAM;;EAEb,KAAK,UAAU,OAAO,CAAC;EACvB;CAEA,MAAM,KAAK,YAAY,SAAS;AAChC,6BAA4B,SAAS;CACrC,MAAM,MAAM,MAAM,6BAA6B,SAAS;AAExD,KAAI;AACF,SAAO,MAAM,GAAG,IAAkB;GAChC,GAAG;GACH,MAAO,IAAY;GACpB,CAAC;WACM;AACR,8BAA4B,SAAS;;;AAIzC,SAAS,aACP,KAsBA;AACA,QAAO,SAAS,OAAO,IAAI,QAAQ,QAAQ,IAAI,QAAQ,KAAA"}
@@ -1296,6 +1296,9 @@ var init_navigators = __esm({
1296
1296
  */
1297
1297
  setEphemeralHints(_hints) {
1298
1298
  }
1299
+ /** See StudyContentSource.setSessionId. No-op for non-Pipeline navigators. */
1300
+ setSessionId(_sessionId) {
1301
+ }
1299
1302
  };
1300
1303
  }
1301
1304
  });
@@ -2159,6 +2162,7 @@ var init_Pipeline = __esm({
2159
2162
  * getWeightedCards() call, then cleared.
2160
2163
  */
2161
2164
  _ephemeralHints = null;
2165
+ _sessionId;
2162
2166
  /**
2163
2167
  * The intake valve's clock (see regulators.ts), loaded from strategy state on
2164
2168
  * first use and kept in memory. Writes are chained so a presentation and a
@@ -2194,6 +2198,10 @@ var init_Pipeline = __esm({
2194
2198
  *
2195
2199
  * Overrides ContentNavigator.setEphemeralHints() no-op.
2196
2200
  */
2201
+ /** See StudyContentSource.setSessionId. Carried into every run's context. */
2202
+ setSessionId(sessionId) {
2203
+ this._sessionId = sessionId;
2204
+ }
2197
2205
  setEphemeralHints(hints) {
2198
2206
  this._ephemeralHints = hints;
2199
2207
  logger.info(`[Pipeline] Ephemeral hints set: ${JSON.stringify(hints)}`);
@@ -2641,7 +2649,8 @@ var init_Pipeline = __esm({
2641
2649
  course: this.course,
2642
2650
  userElo,
2643
2651
  ...userCourseElo ? { userCourseElo } : {},
2644
- orchestration
2652
+ orchestration,
2653
+ ...this._sessionId ? { sessionId: this._sessionId } : {}
2645
2654
  };
2646
2655
  }
2647
2656
  /**
@@ -6269,6 +6278,9 @@ var init_srs = __esm({
6269
6278
  });
6270
6279
 
6271
6280
  // src/core/navigators/filters/eloDistance.ts
6281
+ function isIntroCard(card) {
6282
+ return (card.tags ?? []).some((t) => (0, import_common11.tagRole)(t) === "intro");
6283
+ }
6272
6284
  function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
6273
6285
  const normalizedDistance = distance / halfLife;
6274
6286
  const decay = Math.exp(-(normalizedDistance * normalizedDistance));
@@ -6336,7 +6348,7 @@ async function applyEloDistance(cards, context, config, source) {
6336
6348
  const { course, userElo, userCourseElo } = context;
6337
6349
  const { halfLife, minMultiplier, maxMultiplier } = config;
6338
6350
  const tagAware = (config.tagAware || multiDimElo) && userCourseElo !== void 0;
6339
- const missing = cards.filter((c) => tagAware || c.cardElo === void 0).map((c) => c.cardId);
6351
+ const missing = cards.filter((c) => !isIntroCard(c) && (tagAware || c.cardElo === void 0)).map((c) => c.cardId);
6340
6352
  const fetched = /* @__PURE__ */ new Map();
6341
6353
  if (missing.length > 0) {
6342
6354
  const elos = await course.getCardEloData(missing);
@@ -6345,6 +6357,22 @@ async function applyEloDistance(cards, context, config, source) {
6345
6357
  });
6346
6358
  }
6347
6359
  return cards.map((card) => {
6360
+ if (isIntroCard(card)) {
6361
+ return {
6362
+ ...card,
6363
+ provenance: [
6364
+ ...card.provenance,
6365
+ {
6366
+ strategy: "eloDistance",
6367
+ strategyName: source.name,
6368
+ strategyId: source.strategyId,
6369
+ action: "passed",
6370
+ score: card.score,
6371
+ reason: "intro card: ELO is a placeholder, distance not applied \u2192 1.00x"
6372
+ }
6373
+ ]
6374
+ };
6375
+ }
6348
6376
  const full = fetched.get(card.cardId);
6349
6377
  const cardElo = full?.global?.score ?? card.cardElo ?? DEFAULT_CARD_ELO;
6350
6378
  let distance = Math.abs(cardElo - userElo);
@@ -7337,6 +7365,10 @@ ${e.stack}` : JSON.stringify(e);
7337
7365
  setEphemeralHints(hints) {
7338
7366
  this._pendingHints = hints;
7339
7367
  }
7368
+ _sessionId = null;
7369
+ setSessionId(sessionId) {
7370
+ this._sessionId = sessionId;
7371
+ }
7340
7372
  /**
7341
7373
  * Forward a presentation to the navigator (a new card restarts its intake
7342
7374
  * clock). Builds the navigator if the cached one has expired.
@@ -7353,6 +7385,9 @@ ${e.stack}` : JSON.stringify(e);
7353
7385
  navigator2.setEphemeralHints(this._pendingHints);
7354
7386
  this._pendingHints = null;
7355
7387
  }
7388
+ if (this._sessionId) {
7389
+ navigator2.setSessionId(this._sessionId);
7390
+ }
7356
7391
  const result = await navigator2.getWeightedCards(limit);
7357
7392
  return result;
7358
7393
  } catch (e) {