@vue-skuilder/db 0.2.36 → 0.3.0

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 (59) hide show
  1. package/dist/{contentSource-D_E7JaxR.d.ts → contentSource-2zVmcjKA.d.ts} +6 -1
  2. package/dist/core/index.cjs +203 -148
  3. package/dist/core/index.cjs.map +1 -1
  4. package/dist/core/index.d.ts +5 -5
  5. package/dist/core/navigators/Pipeline.mjs +8 -0
  6. package/dist/core/navigators/Pipeline.mjs.map +1 -1
  7. package/dist/core/navigators/generators/prescribed.mjs +29 -11
  8. package/dist/core/navigators/generators/prescribed.mjs.map +1 -1
  9. package/dist/core/versionStamps.mjs +1 -1
  10. package/dist/{dataLayerProvider-BDshhSp_.d.ts → dataLayerProvider-rGyLQ93v.d.ts} +1 -1
  11. package/dist/diagnostics/index.d.ts +3 -3
  12. package/dist/impl/common/BaseUserDB.mjs +32 -15
  13. package/dist/impl/common/BaseUserDB.mjs.map +1 -1
  14. package/dist/impl/couch/CourseSyncService.mjs +111 -11
  15. package/dist/impl/couch/CourseSyncService.mjs.map +1 -1
  16. package/dist/impl/couch/PouchDataLayerProvider.mjs +16 -1
  17. package/dist/impl/couch/PouchDataLayerProvider.mjs.map +1 -1
  18. package/dist/impl/couch/courseAPI.mjs +24 -10
  19. package/dist/impl/couch/courseAPI.mjs.map +1 -1
  20. package/dist/impl/couch/courseDB.mjs +19 -9
  21. package/dist/impl/couch/courseDB.mjs.map +1 -1
  22. package/dist/impl/couch/index.cjs +297 -141
  23. package/dist/impl/couch/index.cjs.map +1 -1
  24. package/dist/impl/couch/index.d.ts +27 -4
  25. package/dist/impl/couch/index.mjs +20 -3
  26. package/dist/impl/couch/index.mjs.map +1 -1
  27. package/dist/impl/couch/updateQueue.mjs +69 -46
  28. package/dist/impl/couch/updateQueue.mjs.map +1 -1
  29. package/dist/impl/static/index.cjs +147 -93
  30. package/dist/impl/static/index.cjs.map +1 -1
  31. package/dist/impl/static/index.d.ts +4 -4
  32. package/dist/{index-BLDpFYG3.d.ts → index-C745YB_6.d.ts} +1 -1
  33. package/dist/index.cjs +345 -171
  34. package/dist/index.cjs.map +1 -1
  35. package/dist/index.d.ts +23 -10
  36. package/dist/index.mjs +2 -1
  37. package/dist/study/SessionController.mjs +4 -0
  38. package/dist/study/SessionController.mjs.map +1 -1
  39. package/dist/{types-DChCz22D.d.ts → types-DF0JuPbs.d.ts} +1 -1
  40. package/dist/{types-legacy-fT5Y1Wuy.d.ts → types-legacy-DdVjg81H.d.ts} +1 -1
  41. package/dist/util/packer/index.d.ts +3 -3
  42. package/dist/util/perfMarks.mjs +30 -0
  43. package/dist/util/perfMarks.mjs.map +1 -0
  44. package/package.json +3 -3
  45. package/src/core/interfaces/courseDB.ts +6 -0
  46. package/src/core/navigators/Pipeline.ts +8 -0
  47. package/src/core/navigators/generators/prescribed.ts +42 -16
  48. package/src/impl/common/BaseUserDB.ts +42 -23
  49. package/src/impl/couch/CourseSyncService.ts +149 -22
  50. package/src/impl/couch/PouchDataLayerProvider.ts +14 -1
  51. package/src/impl/couch/courseAPI.ts +26 -12
  52. package/src/impl/couch/courseDB.ts +25 -12
  53. package/src/impl/couch/index.ts +16 -5
  54. package/src/impl/couch/updateQueue.ts +86 -82
  55. package/src/study/SessionController.ts +4 -0
  56. package/src/util/index.ts +1 -0
  57. package/src/util/perfMarks.ts +35 -0
  58. package/tests/impl/courseSync.test.ts +139 -0
  59. package/tests/impl/updateQueue.test.ts +57 -0
@@ -1 +1 @@
1
- {"version":3,"file":"prescribed.mjs","names":[],"sources":["../../../../src/core/navigators/generators/prescribed.ts"],"sourcesContent":["import { tagRole, withTagRole } from '@vue-skuilder/common';\nimport type { CourseDBInterface } from '../../interfaces/courseDB';\nimport type { UserDBInterface } from '../../interfaces/userDB';\nimport { ContentNavigator } from '../index';\nimport type { WeightedCard } from '../index';\nimport type { ContentNavigationStrategyData } from '../../types/contentNavigationStrategy';\nimport type { CardGenerator, GeneratorContext, GeneratorResult, ReplanHints } from './types';\nimport {\n captureStrategyPressure,\n type PressureGaugeDebug,\n} from '../StrategyPressureDebugger';\nimport { logger } from '@db/util/logger';\n\n// ============================================================================\n// PRESCRIBED CARDS GENERATOR\n// ============================================================================\n//\n// A stateful generator for authored, course-prescribed content.\n//\n// Unlike ELO/SRS, prescribed content is explicitly authored curriculum intent.\n// This generator therefore tracks whether prescribed targets have actually been\n// encountered by the user, applies progressive pressure to stale/pending target\n// groups, and can emit upstream support cards when direct targets remain\n// blocked behind prerequisite chains.\n//\n// The first intended use case is intro-card reliability:\n//\n// - direct targets: intro cards that must eventually surface\n// - support cards: low-complexity cards that help satisfy prereqs for blocked\n// intro targets\n//\n// Prescribed content still participates in the normal pipeline. Hierarchy,\n// lesson gating, letter gating, interference, and priority filters continue to\n// shape final ordering.\n//\n// ============================================================================\n\ninterface HierarchyWalkConfig {\n enabled?: boolean;\n maxDepth?: number;\n}\n\ninterface PrescribedGroupConfig {\n id: string;\n targetCardIds: string[];\n supportCardIds?: string[];\n supportTagPatterns?: string[];\n freshnessWindowSessions?: number;\n maxDirectTargetsPerRun?: number;\n maxSupportCardsPerRun?: number;\n hierarchyWalk?: HierarchyWalkConfig;\n /**\n * Exposure an intro target needs before it may surface. Each target is held\n * back — and cards bearing its missing exposure tags are emitted as support —\n * until every exposure tag it implies (its own `gpc:expose:*` tags, plus\n * `gpc:expose:X` for each `gpc:intro:X`) reaches this count. Default 3: a\n * letter is met incidentally inside other words before it is introduced.\n * Set 0 for targets that must be introduced *before* any exposure — e.g.\n * irregular words, which only ever appear in their own cards.\n */\n introExposeMinCount?: number;\n retireOnEncounter?: boolean;\n /**\n * Tag patterns identifying *practice* skills to drill once unlocked. For each\n * course tag matching one of these patterns that is (a) unlocked — all its\n * hierarchy prerequisites met, i.e. the learner has been introduced to it —\n * but (b) still under-practiced (per-tag attempt count below\n * `practiceMinCount`), the generator emits cards carrying that tag into the\n * candidate pool. This closes the post-intro drilling gap independent of\n * global-ELO retrieval (easy drill cards that the ELO window never reaches).\n * Ordering/emphasis is left to the pipeline's scoring + decaying boost.\n */\n practiceTagPatterns?: string[];\n /** Attempt-count threshold below which a practice skill is \"under-practiced\". */\n practiceMinCount?: number;\n /** Cap on practice cards emitted per run (across all under-practiced skills). */\n maxPracticeCardsPerRun?: number;\n}\n\ninterface PrescribedConfig {\n groups: PrescribedGroupConfig[];\n}\n\ninterface GroupCardState {\n encounteredCardIds: string[];\n pendingTargetIds: string[];\n lastSurfacedAt: string | null;\n sessionsSinceSurfaced: number;\n lastSupportAt: string | null;\n blockedTargetIds: string[];\n lastResolvedSupportTags: string[];\n}\n\ninterface PrescribedProgressState {\n updatedAt: string;\n groups: Record<string, GroupCardState>;\n /**\n * Per-practice-tag debt age: tag → ISO timestamp when the skill first appeared\n * unlocked-but-under-practiced. Drives the practice-debt staleness escalation\n * (older unpaid debt → higher pressure). An entry is carried while the debt is\n * open and dropped the moment the skill reaches `practiceMinCount` — so the\n * map self-prunes and \"staleness\" is measured from first-owed, not last-seen.\n */\n practiceDebt?: Record<string, string>;\n}\n\ninterface TagPrerequisite {\n tag: string;\n masteryThreshold?: {\n minElo?: number;\n minCount?: number;\n };\n preReqBoost?: number;\n targetBoost?: number;\n}\n\ninterface HierarchyConfig {\n prerequisites: Record<string, TagPrerequisite[]>;\n}\n\ninterface GroupRuntimeState {\n group: PrescribedGroupConfig;\n encounteredTargets: Set<string>;\n pendingTargets: string[];\n blockedTargets: string[];\n surfaceableTargets: string[];\n targetTags: Map<string, string[]>;\n supportCandidates: string[];\n discoveredSupportCandidates: string[];\n supportTags: string[];\n pressureMultiplier: number;\n supportMultiplier: number;\n /** Carried-forward staleness count driving the pressure multipliers. */\n sessionsSinceSurfaced: number;\n debugVersion: string;\n}\n\n/** One open practice debt, surfaced for the strategy-pressure debug channel. */\ninterface PracticeDebtDebug {\n tag: string;\n multiplier: number;\n /** ISO timestamp when the skill first appeared unlocked-but-under-practiced. */\n firstOwedAt: string;\n}\n\ninterface HintEmissionSummary {\n boostTags: Record<string, number>;\n blockedTargetIds: string[];\n supportTags: string[];\n}\n\nconst DEFAULT_FRESHNESS_WINDOW = 3;\nconst DEFAULT_MAX_DIRECT_PER_RUN = 3;\nconst DEFAULT_MAX_SUPPORT_PER_RUN = 3;\nconst DEFAULT_HIERARCHY_DEPTH = 2;\nconst DEFAULT_MIN_COUNT = 3;\nconst DEFAULT_PRACTICE_MIN_COUNT = 3;\nconst DEFAULT_MAX_PRACTICE_PER_RUN = 4;\nconst BASE_TARGET_SCORE = 1.0;\nconst BASE_SUPPORT_SCORE = 0.8;\nconst DISCOVERED_SUPPORT_SCORE = 12.0;\n// Practice drill cards: a *practice-debt pressure*, parallel to the SRS backlog\n// multiplier. An unlocked-but-under-practiced skill owes reps; that debt is\n// durable (keyed off per-tag attempt count) and discharges by practice, not\n// time. The score is base × a debt multiplier that starts at PRACTICE_BASE_MULT\n// (so a few reps land promptly after intro, competing with pressured reviews)\n// and escalates by how long the debt has stayed open (capped), so a chronically\n// out-competed skill eventually forces exposure rather than competing at flat\n// parity forever. Replaces the old flat 1.0, which punted emphasis to the\n// session-scoped intro boost that evaporates at session end.\nconst BASE_PRACTICE_SCORE = 1.0;\nconst PRACTICE_BASE_MULT = 2.0;\nconst MAX_PRACTICE_MULTIPLIER = 4.0;\n// Added to the multiplier per day the debt stays open (linear, then clamped).\nconst PRACTICE_STALENESS_BUMP_PER_DAY = 0.5;\nconst MAX_TARGET_MULTIPLIER = 8.0;\nconst MAX_SUPPORT_MULTIPLIER = 4.0;\n\nconst PRESCRIBED_DEBUG_VERSION = 'testversion-prescribed-v3';\n\nfunction dedupe<T>(arr: T[]): T[] {\n return [...new Set(arr)];\n}\n\nfunction isoNow(): string {\n return new Date().toISOString();\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction matchesTagPattern(tag: string, pattern: string): boolean {\n if (pattern === '*') return true;\n const escaped = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*/g, '.*');\n const re = new RegExp(`^${escaped}$`);\n return re.test(tag);\n}\n\n/**\n * Extract the word stem from a card ID for deduplication.\n * ML: c-ml-{word}-{blanks} → {word}\n * WS: c-ws-{word}-{contrast} → {word}\n * Other: full cardId as fallback.\n */\nfunction extractWordStem(cardId: string): string {\n for (const prefix of ['c-ml-', 'c-ws-', 'c-spelling-']) {\n if (cardId.startsWith(prefix)) {\n const rest = cardId.slice(prefix.length);\n const lastDash = rest.lastIndexOf('-');\n return lastDash > 0 ? rest.slice(0, lastDash) : rest;\n }\n }\n return cardId;\n}\n\n/** Fisher-Yates shuffle in place. */\nfunction shuffleInPlace<T>(arr: T[]): void {\n for (let i = arr.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n [arr[i], arr[j]] = [arr[j], arr[i]];\n }\n}\n\n/** Compact age string for debt-open durations: 42m / 7h / 3d. */\nfunction formatAge(ms: number): string {\n const minutes = Math.max(0, Math.round(ms / 60000));\n if (minutes < 60) return `${minutes}m`;\n const hours = Math.round(minutes / 60);\n if (hours < 24) return `${hours}h`;\n return `${Math.round(hours / 24)}d`;\n}\n\n/**\n * The exposure tags an intro target still lacks before it may surface: its own\n * `expose` tags plus the `expose` counterpart of each `intro` tag (tag roles,\n * see common's tagRoles.ts: `gpc:intro:X` → `gpc:expose:X`), each needing\n * `minCount` attempts. A `minCount` of 0 requires nothing — not even an entry\n * in `userTagElo`.\n */\nexport function unmetIntroExposeTags(\n tags: string[],\n userTagElo: Record<string, { count: number }>,\n minCount: number\n): string[] {\n if (minCount <= 0) return [];\n\n const exposeTags = new Set(tags.filter((tag) => tagRole(tag) === 'expose'));\n for (const tag of tags) {\n if (tagRole(tag) !== 'intro') continue;\n const expose = withTagRole(tag, 'expose');\n if (expose) exposeTags.add(expose);\n }\n\n return [...exposeTags].filter((tag) => {\n const tagElo = userTagElo[tag];\n return !tagElo || tagElo.count < minCount;\n });\n}\n\nfunction pickTopByScore(cards: WeightedCard[], limit: number): WeightedCard[] {\n return [...cards]\n .sort((a, b) => b.score - a.score || a.cardId.localeCompare(b.cardId))\n .slice(0, limit);\n}\n\nexport default class PrescribedCardsGenerator extends ContentNavigator implements CardGenerator {\n name: string;\n private config: PrescribedConfig;\n\n constructor(\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n ) {\n super(user, course, strategyData);\n this.name = strategyData.name || 'Prescribed Cards';\n this.config = this.parseConfig(strategyData.serializedData);\n\n logger.debug(\n `[Prescribed] Initialized with ${this.config.groups.length} groups and ` +\n `${this.config.groups.reduce((n, g) => n + g.targetCardIds.length, 0)} targets`\n );\n }\n\n protected override get strategyKey(): string {\n return 'PrescribedProgress';\n }\n\n async getWeightedCards(limit: number, context?: GeneratorContext): Promise<GeneratorResult> {\n if (this.config.groups.length === 0 || limit <= 0) {\n return { cards: [] };\n }\n\n const courseId = this.course.getCourseID();\n const activeCards = await this.user.getActiveCards();\n const activeIds = new Set(activeCards.map((ac) => ac.cardID));\n\n const seenCards = await this.user.getSeenCards(courseId).catch(() => []);\n const seenIds = new Set(seenCards);\n\n const progress = (await this.getStrategyState<PrescribedProgressState>()) ?? {\n updatedAt: isoNow(),\n groups: {},\n };\n\n const hierarchyConfigs = await this.loadHierarchyConfigs();\n const courseReg = await this.user.getCourseRegDoc(courseId).catch(() => null);\n const userGlobalElo =\n typeof courseReg?.elo === 'number'\n ? courseReg.elo\n : courseReg?.elo?.global?.score ?? context?.userElo ?? 1000;\n const userTagElo =\n typeof courseReg?.elo === 'number'\n ? {}\n : courseReg?.elo?.tags ?? {};\n\n const allTargetIds = dedupe(this.config.groups.flatMap((g) => g.targetCardIds));\n const allSupportIds = dedupe(this.config.groups.flatMap((g) => g.supportCardIds ?? []));\n const allRelevantIds = dedupe([...allTargetIds, ...allSupportIds]);\n\n const tagsByCard =\n allRelevantIds.length > 0\n ? await this.course.getAppliedTagsBatch(allRelevantIds)\n : new Map<string, string[]>();\n\n const courseTagDocs = await this.course.getCourseTagStubs().catch(\n () =>\n ({\n rows: [],\n offset: 0,\n total_rows: 0,\n }) as unknown as Awaited<ReturnType<CourseDBInterface['getCourseTagStubs']>>\n );\n const cardsByTag = new Map<string, string[]>();\n for (const row of courseTagDocs.rows ?? []) {\n const tagDoc = row.doc as { name?: string; taggedCards?: string[] } | undefined;\n if (tagDoc?.name && Array.isArray(tagDoc.taggedCards)) {\n cardsByTag.set(tagDoc.name, [...tagDoc.taggedCards]);\n }\n }\n\n const nextState: PrescribedProgressState = {\n updatedAt: isoNow(),\n groups: {},\n };\n\n const emitted: WeightedCard[] = [];\n const emittedIds = new Set<string>();\n const groupRuntimes: GroupRuntimeState[] = [];\n // Practice-debt ages carried forward: stamped when a skill first appears\n // under-practiced, dropped once it's discharged (see buildPracticeCards).\n const priorPracticeDebt = progress.practiceDebt ?? {};\n const nextPracticeDebt: Record<string, string> = {};\n const practiceDebtsByGroup = new Map<string, PracticeDebtDebug[]>();\n\n for (const group of this.config.groups) {\n const runtime = this.buildGroupRuntimeState({\n group,\n priorState: progress.groups[group.id],\n activeIds,\n seenIds,\n tagsByCard,\n cardsByTag,\n hierarchyConfigs,\n userTagElo,\n userGlobalElo,\n });\n\n groupRuntimes.push(runtime);\n\n logger.info(\n `[Prescribed] Group '${group.id}': ` +\n `${group.targetCardIds.length} targets total, ` +\n `${runtime.encounteredTargets.size} encountered, ` +\n `${runtime.pendingTargets.length} pending ` +\n `(${runtime.surfaceableTargets.length} surfaceable, ${runtime.blockedTargets.length} blocked), ` +\n `${runtime.supportCandidates.length} authored support candidates, ` +\n `${runtime.discoveredSupportCandidates.length} discovered support candidates, ` +\n `pressure=${runtime.pressureMultiplier.toFixed(2)}`\n );\n if (runtime.blockedTargets.length > 0) {\n logger.info(\n `[Prescribed] Group '${group.id}' blocked targets: ${runtime.blockedTargets.join(', ')}`\n );\n logger.info(\n `[Prescribed] Group '${group.id}' support tags needed: ${runtime.supportTags.join(', ') || '(none)'}`\n );\n logger.info(\n `[Prescribed] Group '${group.id}' escalation mode: ` +\n (runtime.supportCandidates.length > 0\n ? 'direct-support'\n : runtime.discoveredSupportCandidates.length > 0\n ? 'inserted-support-candidates'\n : 'boost-only')\n );\n if (runtime.discoveredSupportCandidates.length > 0) {\n logger.info(\n `[Prescribed] Group '${group.id}' discovered support candidates: ${runtime.discoveredSupportCandidates.join(', ')}`\n );\n }\n }\n\n nextState.groups[group.id] = this.buildNextGroupState(runtime, progress.groups[group.id]);\n\n const directCards = this.buildDirectTargetCards(\n runtime,\n courseId,\n emittedIds\n );\n const supportCards = this.buildSupportCards(\n runtime,\n courseId,\n emittedIds\n );\n const discoveredSupportCards = this.buildDiscoveredSupportCards(\n runtime,\n courseId,\n emittedIds\n );\n const practice = this.buildPracticeCards({\n group,\n courseId,\n emittedIds,\n cardsByTag,\n hierarchyConfigs,\n userTagElo,\n userGlobalElo,\n activeIds,\n seenIds,\n priorPracticeDebt,\n nextPracticeDebt,\n });\n practiceDebtsByGroup.set(group.id, practice.debts);\n\n emitted.push(...directCards, ...supportCards, ...discoveredSupportCards, ...practice.cards);\n }\n\n // Persist the carried-forward practice debt (self-pruned: discharged skills\n // simply aren't re-stamped above, so they drop out of the next state).\n nextState.practiceDebt = nextPracticeDebt;\n\n const hintSummary = this.buildSupportHintSummary(groupRuntimes);\n const hints: ReplanHints | undefined =\n Object.keys(hintSummary.boostTags).length > 0\n ? {\n boostTags: hintSummary.boostTags,\n _label:\n `prescribed-support (${hintSummary.supportTags.length} tags; ` +\n `blocked=${hintSummary.blockedTargetIds.length}; ` +\n `testversion=${PRESCRIBED_DEBUG_VERSION})`,\n }\n : undefined;\n\n if (hints) {\n const tagEntries = Object.entries(hints.boostTags ?? {}) as Array<[string, number]>;\n logger.info(\n `[Prescribed] Emitting ${tagEntries.length} boost hint(s): ` +\n tagEntries.map(([tag, mult]) => `${tag}×${mult.toFixed(1)}`).join(', ')\n );\n } else {\n logger.info('[Prescribed] No hints to emit (no blocked targets or no support tags)');\n }\n\n // Push this run's pressure state to the live-overlay debug channel. Done\n // before the empty-emission return — an all-blocked run is exactly the\n // state the overlay most needs to show.\n this.capturePressureSnapshot(courseId, groupRuntimes, practiceDebtsByGroup, emitted, hints);\n\n if (emitted.length === 0) {\n logger.info(\n '[Prescribed] 0 cards emitted (all targets blocked, authored/discovered support candidates exhausted)' +\n (hints ? ' — boost hints emitted but may not survive filters' : '')\n );\n await this.putStrategyState(nextState).catch((e) => {\n logger.debug(`[Prescribed] Failed to persist empty-state update: ${e}`);\n });\n return hints ? { cards: [], hints } : { cards: [] };\n }\n\n const finalCards = pickTopByScore(emitted, limit);\n\n const surfacedByGroup = new Map<string, { targetIds: string[]; supportIds: string[] }>();\n for (const card of finalCards) {\n const prov = card.provenance[0];\n // Practice cards are not target/support surfacing — they must not reset a\n // group's freshness/pressure state (which tracks whether *intro targets*\n // are getting through). Skip them here.\n if (prov?.reason.includes('mode=practice')) continue;\n const groupId = prov?.reason.match(/group=([^;]+)/)?.[1];\n const mode = prov?.reason.includes('mode=support') ? 'supportIds' : 'targetIds';\n if (!groupId) continue;\n if (!surfacedByGroup.has(groupId)) {\n surfacedByGroup.set(groupId, { targetIds: [], supportIds: [] });\n }\n surfacedByGroup.get(groupId)![mode].push(card.cardId);\n }\n\n for (const group of this.config.groups) {\n const groupState = nextState.groups[group.id];\n const surfaced = surfacedByGroup.get(group.id);\n if (surfaced && (surfaced.targetIds.length > 0 || surfaced.supportIds.length > 0)) {\n groupState.lastSurfacedAt = isoNow();\n groupState.sessionsSinceSurfaced = 0;\n if (surfaced.supportIds.length > 0) {\n groupState.lastSupportAt = isoNow();\n }\n }\n }\n\n await this.putStrategyState(nextState).catch((e) => {\n logger.debug(`[Prescribed] Failed to persist prescribed progress: ${e}`);\n });\n\n logger.info(\n `[Prescribed] Emitting ${finalCards.length} cards ` +\n `(${finalCards.filter((c) => c.provenance[0]?.reason.includes('mode=target')).length} target, ` +\n `${finalCards.filter((c) => c.provenance[0]?.reason.includes('mode=support')).length} support, ` +\n `${finalCards.filter((c) => c.provenance[0]?.reason.includes('mode=discovered-support')).length} discovered support)`\n );\n\n return hints ? { cards: finalCards, hints } : { cards: finalCards };\n }\n\n private buildSupportHintSummary(groupRuntimes: GroupRuntimeState[]): HintEmissionSummary {\n const boostTags: Record<string, number> = {};\n const blockedTargetIds = new Set<string>();\n const supportTags = new Set<string>();\n\n for (const runtime of groupRuntimes) {\n if (runtime.blockedTargets.length === 0 || runtime.supportTags.length === 0) {\n continue;\n }\n\n runtime.blockedTargets.forEach((cardId) => blockedTargetIds.add(cardId));\n\n for (const tag of runtime.supportTags) {\n supportTags.add(tag);\n boostTags[tag] = (boostTags[tag] ?? 1) * runtime.supportMultiplier;\n }\n }\n\n return {\n boostTags,\n blockedTargetIds: [...blockedTargetIds].sort(),\n supportTags: [...supportTags].sort(),\n };\n }\n\n /**\n * Translate this run's per-group runtimes and practice debts into gauges on\n * the generic strategy-pressure debug channel (rendered by the live session\n * overlay's \"strategy backpressure\" section).\n */\n private capturePressureSnapshot(\n courseId: string,\n groupRuntimes: GroupRuntimeState[],\n practiceDebtsByGroup: Map<string, PracticeDebtDebug[]>,\n emitted: WeightedCard[],\n hints: ReplanHints | undefined\n ): void {\n const now = Date.now();\n const gauges: PressureGaugeDebug[] = [];\n\n for (const runtime of groupRuntimes) {\n const group = runtime.group;\n const window = group.freshnessWindowSessions ?? DEFAULT_FRESHNESS_WINDOW;\n\n gauges.push({\n id: `group:${group.id}:target`,\n label: `${group.id} targets`,\n multiplier: runtime.pressureMultiplier,\n max: MAX_TARGET_MULTIPLIER,\n detail:\n `${runtime.pendingTargets.length} pending ` +\n `(${runtime.surfaceableTargets.length} surfaceable, ${runtime.blockedTargets.length} blocked) · ` +\n `sinceSurfaced ${runtime.sessionsSinceSurfaced}/${window}`,\n items: runtime.blockedTargets.map((cardId) => ({ label: cardId, value: 'blocked' })),\n });\n\n if (runtime.blockedTargets.length > 0) {\n const mode =\n runtime.supportCandidates.length > 0\n ? 'direct-support'\n : runtime.discoveredSupportCandidates.length > 0\n ? 'inserted-support'\n : 'boost-only';\n gauges.push({\n id: `group:${group.id}:support`,\n label: `${group.id} support`,\n multiplier: runtime.supportMultiplier,\n max: MAX_SUPPORT_MULTIPLIER,\n detail: `mode=${mode} · ${runtime.supportTags.length} support tag(s)`,\n items: runtime.supportTags.map((tag) => ({ label: tag })),\n });\n }\n\n const debts = practiceDebtsByGroup.get(group.id) ?? [];\n if (debts.length > 0) {\n gauges.push({\n id: `group:${group.id}:practice-debt`,\n label: `${group.id} practice debt`,\n multiplier: Math.max(...debts.map((d) => d.multiplier)),\n max: MAX_PRACTICE_MULTIPLIER,\n detail: `${debts.length} under-practiced skill(s)`,\n items: debts.map((d) => ({\n label: d.tag,\n value: `×${d.multiplier.toFixed(2)} · open ${formatAge(now - new Date(d.firstOwedAt).getTime())}`,\n })),\n });\n }\n }\n\n captureStrategyPressure({\n source: 'prescribed',\n courseId,\n gauges,\n topScore: emitted.length > 0 ? Math.max(...emitted.map((c) => c.score)) : null,\n hintsLabel: hints?._label,\n timestamp: now,\n });\n }\n\n private parseConfig(serializedData: string): PrescribedConfig {\n try {\n const parsed = JSON.parse(serializedData) as { groups?: unknown[] };\n const groupsRaw = Array.isArray(parsed.groups) ? parsed.groups : [];\n const groups: PrescribedGroupConfig[] = groupsRaw\n .map((raw: any, i: number): PrescribedGroupConfig => ({\n id: typeof raw.id === 'string' && raw.id.trim().length > 0 ? raw.id : `group-${i + 1}`,\n targetCardIds: dedupe(\n (Array.isArray(raw.targetCardIds) ? raw.targetCardIds.filter((v: unknown): v is string => typeof v === 'string') : [])\n ),\n supportCardIds: dedupe(\n (Array.isArray(raw.supportCardIds) ? raw.supportCardIds.filter((v: unknown): v is string => typeof v === 'string') : [])\n ),\n supportTagPatterns: dedupe(\n (Array.isArray(raw.supportTagPatterns)\n ? raw.supportTagPatterns.filter((v: unknown): v is string => typeof v === 'string')\n : [])\n ),\n freshnessWindowSessions:\n typeof raw.freshnessWindowSessions === 'number' ? raw.freshnessWindowSessions : DEFAULT_FRESHNESS_WINDOW,\n maxDirectTargetsPerRun:\n typeof raw.maxDirectTargetsPerRun === 'number' ? raw.maxDirectTargetsPerRun : DEFAULT_MAX_DIRECT_PER_RUN,\n maxSupportCardsPerRun:\n typeof raw.maxSupportCardsPerRun === 'number' ? raw.maxSupportCardsPerRun : DEFAULT_MAX_SUPPORT_PER_RUN,\n introExposeMinCount:\n typeof raw.introExposeMinCount === 'number' ? raw.introExposeMinCount : DEFAULT_MIN_COUNT,\n hierarchyWalk: {\n enabled: raw.hierarchyWalk?.enabled !== false,\n maxDepth:\n typeof raw.hierarchyWalk?.maxDepth === 'number'\n ? raw.hierarchyWalk.maxDepth\n : DEFAULT_HIERARCHY_DEPTH,\n },\n retireOnEncounter: raw.retireOnEncounter !== false,\n practiceTagPatterns: dedupe(\n Array.isArray(raw.practiceTagPatterns)\n ? raw.practiceTagPatterns.filter((v: unknown): v is string => typeof v === 'string')\n : []\n ),\n practiceMinCount:\n typeof raw.practiceMinCount === 'number' ? raw.practiceMinCount : DEFAULT_PRACTICE_MIN_COUNT,\n maxPracticeCardsPerRun:\n typeof raw.maxPracticeCardsPerRun === 'number'\n ? raw.maxPracticeCardsPerRun\n : DEFAULT_MAX_PRACTICE_PER_RUN,\n }))\n .filter((g) => g.targetCardIds.length > 0);\n\n return { groups };\n } catch {\n return { groups: [] };\n }\n }\n\n private async loadHierarchyConfigs(): Promise<HierarchyConfig[]> {\n try {\n const strategies = await this.course.getAllNavigationStrategies();\n return strategies\n .filter((s: ContentNavigationStrategyData) => s.implementingClass === 'hierarchyDefinition')\n .map((s: ContentNavigationStrategyData) => {\n try {\n const parsed = JSON.parse(s.serializedData) as { prerequisites?: Record<string, TagPrerequisite[]> };\n return {\n prerequisites: parsed.prerequisites || {},\n } as HierarchyConfig;\n } catch {\n return { prerequisites: {} };\n }\n });\n } catch (e) {\n logger.debug(`[Prescribed] Failed to load hierarchy configs: ${e}`);\n return [];\n }\n }\n\n private buildGroupRuntimeState(args: {\n group: PrescribedGroupConfig;\n priorState?: GroupCardState;\n activeIds: Set<string>;\n seenIds: Set<string>;\n tagsByCard: Map<string, string[]>;\n cardsByTag: Map<string, string[]>;\n hierarchyConfigs: HierarchyConfig[];\n userTagElo: Record<string, { score: number; count: number }>;\n userGlobalElo: number;\n }): GroupRuntimeState {\n const {\n group,\n priorState,\n activeIds,\n seenIds,\n tagsByCard,\n cardsByTag,\n hierarchyConfigs,\n userTagElo,\n userGlobalElo,\n } = args;\n\n const encounteredTargets = new Set<string>();\n for (const cardId of group.targetCardIds) {\n if (activeIds.has(cardId) || seenIds.has(cardId)) {\n encounteredTargets.add(cardId);\n }\n }\n\n if (priorState?.encounteredCardIds?.length) {\n for (const cardId of priorState.encounteredCardIds) {\n encounteredTargets.add(cardId);\n }\n }\n\n const pendingTargets = group.targetCardIds.filter((id) => !encounteredTargets.has(id));\n const targetTags = new Map<string, string[]>();\n for (const cardId of pendingTargets) {\n targetTags.set(cardId, tagsByCard.get(cardId) ?? []);\n }\n\n const blockedTargets: string[] = [];\n const surfaceableTargets: string[] = [];\n const supportTags = new Set<string>();\n\n for (const cardId of pendingTargets) {\n const tags = targetTags.get(cardId) ?? [];\n const resolution = this.resolveBlockedSupportTags(\n tags,\n hierarchyConfigs,\n userTagElo,\n userGlobalElo,\n group.hierarchyWalk?.enabled !== false,\n group.hierarchyWalk?.maxDepth ?? DEFAULT_HIERARCHY_DEPTH\n );\n\n const unmetExposeTags = unmetIntroExposeTags(\n tags,\n userTagElo,\n group.introExposeMinCount ?? DEFAULT_MIN_COUNT\n );\n\n if (unmetExposeTags.length > 0) {\n unmetExposeTags.forEach((tag) => supportTags.add(tag));\n }\n\n if (resolution.blocked || unmetExposeTags.length > 0) {\n blockedTargets.push(cardId);\n resolution.supportTags.forEach((t) => supportTags.add(t));\n } else {\n surfaceableTargets.push(cardId);\n }\n }\n\n const supportCandidates = dedupe([\n ...(group.supportCardIds ?? []),\n ...this.findSupportCardsByTags(\n group,\n tagsByCard,\n [...supportTags]\n ),\n ]).filter((id) => !activeIds.has(id) && !seenIds.has(id));\n\n const discoveredSupportCandidates =\n blockedTargets.length > 0 && supportTags.size > 0 && supportCandidates.length === 0\n ? this.findDiscoveredSupportCards({\n supportTags: [...supportTags],\n cardsByTag,\n activeIds,\n seenIds,\n excludedIds: new Set([\n ...group.targetCardIds,\n ...(group.supportCardIds ?? []),\n ]),\n limit: group.maxSupportCardsPerRun ?? DEFAULT_MAX_SUPPORT_PER_RUN,\n })\n : [];\n\n if (blockedTargets.length > 0 && supportTags.size > 0 && discoveredSupportCandidates.length === 0) {\n logger.info(\n `[Prescribed] Group '${group.id}' discovered 0 broader support candidates ` +\n `(blocked=${blockedTargets.length}; authoredSupport=${supportCandidates.length})`\n );\n }\n\n const sessionsSinceSurfaced = priorState?.sessionsSinceSurfaced ?? 0;\n const freshnessWindow = group.freshnessWindowSessions ?? DEFAULT_FRESHNESS_WINDOW;\n const staleSessions = Math.max(0, sessionsSinceSurfaced - freshnessWindow);\n\n const pressureMultiplier = pendingTargets.length === 0\n ? 1.0\n : clamp(1 + staleSessions * 0.75 + Math.min(2, pendingTargets.length * 0.1), 1.0, MAX_TARGET_MULTIPLIER);\n\n const supportMultiplier = blockedTargets.length === 0\n ? 1.0\n : clamp(1 + staleSessions * 0.5 + Math.min(1.5, blockedTargets.length * 0.15), 1.0, MAX_SUPPORT_MULTIPLIER);\n\n return {\n group,\n encounteredTargets,\n pendingTargets,\n blockedTargets,\n surfaceableTargets,\n targetTags,\n supportCandidates,\n discoveredSupportCandidates,\n supportTags: [...supportTags],\n pressureMultiplier,\n supportMultiplier,\n sessionsSinceSurfaced,\n debugVersion: PRESCRIBED_DEBUG_VERSION,\n };\n }\n\n private buildNextGroupState(runtime: GroupRuntimeState, prior?: GroupCardState): GroupCardState {\n const carriedSessions = prior?.sessionsSinceSurfaced ?? 0;\n const surfacedThisRun = false;\n\n return {\n encounteredCardIds: [...runtime.encounteredTargets].sort(),\n pendingTargetIds: [...runtime.pendingTargets].sort(),\n lastSurfacedAt: prior?.lastSurfacedAt ?? null,\n sessionsSinceSurfaced: surfacedThisRun ? 0 : carriedSessions + 1,\n lastSupportAt: prior?.lastSupportAt ?? null,\n blockedTargetIds: [...runtime.blockedTargets].sort(),\n lastResolvedSupportTags: [...runtime.supportTags].sort(),\n };\n }\n\n private buildDirectTargetCards(\n runtime: GroupRuntimeState,\n courseId: string,\n emittedIds: Set<string>\n ): WeightedCard[] {\n const maxDirect = runtime.group.maxDirectTargetsPerRun ?? DEFAULT_MAX_DIRECT_PER_RUN;\n\n const directIds = runtime.surfaceableTargets\n .filter((id) => !emittedIds.has(id))\n .slice(0, maxDirect);\n\n const cards: WeightedCard[] = [];\n for (const cardId of directIds) {\n emittedIds.add(cardId);\n cards.push({\n cardId,\n courseId,\n score: BASE_TARGET_SCORE * runtime.pressureMultiplier,\n provenance: [\n {\n strategy: 'prescribed',\n strategyName: this.strategyName || this.name,\n strategyId: this.strategyId || 'NAVIGATION_STRATEGY-prescribed',\n action: 'generated' as const,\n score: BASE_TARGET_SCORE * runtime.pressureMultiplier,\n reason:\n `mode=target;group=${runtime.group.id};pending=${runtime.pendingTargets.length};` +\n `surfaceable=${runtime.surfaceableTargets.length};blocked=${runtime.blockedTargets.length};` +\n `blockedTargets=${runtime.blockedTargets.join('|') || 'none'};` +\n `supportTags=${runtime.supportTags.join('|') || 'none'};` +\n `multiplier=${runtime.pressureMultiplier.toFixed(2)};` +\n `testversion=${runtime.debugVersion}`,\n },\n ],\n });\n }\n\n return cards;\n }\n\n private buildSupportCards(\n runtime: GroupRuntimeState,\n courseId: string,\n emittedIds: Set<string>\n ): WeightedCard[] {\n if (runtime.blockedTargets.length === 0 || runtime.supportCandidates.length === 0) {\n return [];\n }\n\n const maxSupport = runtime.group.maxSupportCardsPerRun ?? DEFAULT_MAX_SUPPORT_PER_RUN;\n const supportIds = runtime.supportCandidates\n .filter((id) => !emittedIds.has(id))\n .slice(0, maxSupport);\n\n const cards: WeightedCard[] = [];\n for (const cardId of supportIds) {\n emittedIds.add(cardId);\n cards.push({\n cardId,\n courseId,\n score: BASE_SUPPORT_SCORE * runtime.supportMultiplier,\n provenance: [\n {\n strategy: 'prescribed',\n strategyName: this.strategyName || this.name,\n strategyId: this.strategyId || 'NAVIGATION_STRATEGY-prescribed',\n action: 'generated' as const,\n score: BASE_SUPPORT_SCORE * runtime.supportMultiplier,\n reason:\n `mode=support;group=${runtime.group.id};pending=${runtime.pendingTargets.length};` +\n `blocked=${runtime.blockedTargets.length};` +\n `blockedTargets=${runtime.blockedTargets.join('|') || 'none'};` +\n `supportCard=${cardId};` +\n `supportTags=${runtime.supportTags.join('|') || 'none'};` +\n `multiplier=${runtime.supportMultiplier.toFixed(2)};` +\n `testversion=${runtime.debugVersion}`,\n },\n ],\n });\n }\n\n return cards;\n }\n\n private buildDiscoveredSupportCards(\n runtime: GroupRuntimeState,\n courseId: string,\n emittedIds: Set<string>\n ): WeightedCard[] {\n if (runtime.blockedTargets.length === 0 || runtime.discoveredSupportCandidates.length === 0) {\n return [];\n }\n\n const maxSupport = runtime.group.maxSupportCardsPerRun ?? DEFAULT_MAX_SUPPORT_PER_RUN;\n const supportIds = runtime.discoveredSupportCandidates\n .filter((id) => !emittedIds.has(id))\n .slice(0, maxSupport);\n\n const cards: WeightedCard[] = [];\n for (const cardId of supportIds) {\n emittedIds.add(cardId);\n cards.push({\n cardId,\n courseId,\n score: DISCOVERED_SUPPORT_SCORE * runtime.supportMultiplier,\n provenance: [\n {\n strategy: 'prescribed',\n strategyName: this.strategyName || this.name,\n strategyId: this.strategyId || 'NAVIGATION_STRATEGY-prescribed',\n action: 'generated' as const,\n score: DISCOVERED_SUPPORT_SCORE * runtime.supportMultiplier,\n reason:\n `mode=discovered-support;group=${runtime.group.id};pending=${runtime.pendingTargets.length};` +\n `blocked=${runtime.blockedTargets.length};` +\n `blockedTargets=${runtime.blockedTargets.join('|') || 'none'};` +\n `supportCard=${cardId};` +\n `supportTags=${runtime.supportTags.join('|') || 'none'};` +\n `multiplier=${runtime.supportMultiplier.toFixed(2)};` +\n `testversion=${runtime.debugVersion}`,\n },\n ],\n });\n }\n\n return cards;\n }\n\n /**\n * Emit drill cards for *unlocked-but-under-practiced* skills.\n *\n * For each course tag matching the group's `practiceTagPatterns` that is both\n * unlocked (all hierarchy prerequisites met — i.e. the learner has been\n * introduced to it) and under-practiced (per-tag attempt count below\n * `practiceMinCount`), this resolves cards carrying that tag and emits them\n * into the candidate pool. It exists because global-ELO retrieval\n * systematically fails to fetch the (low-ELO) drill cards for a\n * freshly-introduced skill — putting them in the pool here guarantees presence.\n *\n * Emphasis is a **practice-debt pressure** (parallel to SRS backlog pressure):\n * cards score `base × multiplier`, where the multiplier starts at\n * PRACTICE_BASE_MULT (so a few reps land promptly post-intro, competing with\n * pressured reviews) and escalates by how long the debt has stayed open\n * (per-tag, time-based via `priorPracticeDebt`/`nextPracticeDebt`), clamped at\n * MAX_PRACTICE_MULTIPLIER. The debt is durable and self-discharges the instant\n * the skill reaches `practiceMinCount` — so this no longer relies on the\n * session-scoped intro boost to actually surface.\n *\n * Fully data-driven: the unlock relation comes from the hierarchy config and\n * practice-status from per-tag ELO. No card-id or tag-namespace hard-coding.\n */\n private buildPracticeCards(args: {\n group: PrescribedGroupConfig;\n courseId: string;\n emittedIds: Set<string>;\n cardsByTag: Map<string, string[]>;\n hierarchyConfigs: HierarchyConfig[];\n userTagElo: Record<string, { score: number; count: number }>;\n userGlobalElo: number;\n activeIds: Set<string>;\n seenIds: Set<string>;\n priorPracticeDebt: Record<string, string>;\n nextPracticeDebt: Record<string, string>;\n }): { cards: WeightedCard[]; debts: PracticeDebtDebug[] } {\n const {\n group,\n courseId,\n emittedIds,\n cardsByTag,\n hierarchyConfigs,\n userTagElo,\n userGlobalElo,\n activeIds,\n seenIds,\n priorPracticeDebt,\n nextPracticeDebt,\n } = args;\n\n const patterns = group.practiceTagPatterns ?? [];\n if (patterns.length === 0) return { cards: [], debts: [] };\n\n const practiceMinCount = group.practiceMinCount ?? DEFAULT_PRACTICE_MIN_COUNT;\n const maxPractice = group.maxPracticeCardsPerRun ?? DEFAULT_MAX_PRACTICE_PER_RUN;\n\n const practiceTags = [...cardsByTag.keys()].filter(\n (tag) =>\n patterns.some((p) => matchesTagPattern(tag, p)) &&\n this.isUnlockedGatedSkill(tag, hierarchyConfigs, userTagElo, userGlobalElo) &&\n (userTagElo[tag]?.count ?? 0) < practiceMinCount\n );\n\n if (practiceTags.length === 0) return { cards: [], debts: [] };\n\n // Carry forward (or open) each under-practiced skill's debt age, and derive\n // its practice multiplier: base + staleness-since-first-owed, clamped. Done\n // for every under-practiced tag (not just emitted ones) so the debt clock\n // keeps running even on runs where the cap or de-dup emits nothing.\n const now = Date.now();\n const DAY_MS = 24 * 60 * 60 * 1000;\n const tagMultiplier = new Map<string, number>();\n for (const tag of practiceTags) {\n const firstOwedAt = priorPracticeDebt[tag] ?? isoNow();\n nextPracticeDebt[tag] = firstOwedAt;\n const staleDays = Math.max(0, (now - new Date(firstOwedAt).getTime()) / DAY_MS);\n const mult = clamp(\n PRACTICE_BASE_MULT + staleDays * PRACTICE_STALENESS_BUMP_PER_DAY,\n PRACTICE_BASE_MULT,\n MAX_PRACTICE_MULTIPLIER\n );\n tagMultiplier.set(tag, mult);\n }\n\n // Debug view of every open debt (built before the emission early-return so\n // the pressure channel sees debts even on runs that emit no drill cards).\n const debts: PracticeDebtDebug[] = practiceTags\n .map((tag) => ({\n tag,\n multiplier: tagMultiplier.get(tag) ?? PRACTICE_BASE_MULT,\n firstOwedAt: nextPracticeDebt[tag],\n }))\n .sort((a, b) => b.multiplier - a.multiplier || a.tag.localeCompare(b.tag));\n\n // Reuse the diversity-aware tag→cards collector (stem-dedup + shuffle).\n const practiceCardIds = this.findDiscoveredSupportCards({\n supportTags: practiceTags,\n cardsByTag,\n activeIds,\n seenIds,\n excludedIds: emittedIds,\n limit: maxPractice,\n });\n\n if (practiceCardIds.length === 0) return { cards: [], debts };\n\n logger.info(\n `[Prescribed] Group '${group.id}' practice: ${practiceTags.length} unlocked under-practiced ` +\n `skill(s), emitting ${practiceCardIds.length} drill card(s)`\n );\n\n const cards: WeightedCard[] = [];\n for (const cardId of practiceCardIds) {\n emittedIds.add(cardId);\n // Most-stale wins: a card may carry several practice tags; take the\n // highest debt multiplier among the ones it serves.\n let mult = PRACTICE_BASE_MULT;\n for (const tag of practiceTags) {\n if ((cardsByTag.get(tag)?.includes(cardId) ?? false)) {\n mult = Math.max(mult, tagMultiplier.get(tag) ?? PRACTICE_BASE_MULT);\n }\n }\n const score = BASE_PRACTICE_SCORE * mult;\n cards.push({\n cardId,\n courseId,\n score,\n provenance: [\n {\n strategy: 'prescribed',\n strategyName: this.strategyName || this.name,\n strategyId: this.strategyId || 'NAVIGATION_STRATEGY-prescribed',\n action: 'generated' as const,\n score,\n reason:\n `mode=practice;group=${group.id};debtMult=×${mult.toFixed(2)};` +\n `underPracticedSkills=${practiceTags.length};` +\n `practiceTags=${practiceTags.slice(0, 8).join('|')}${practiceTags.length > 8 ? '|…' : ''};` +\n `testversion=${PRESCRIBED_DEBUG_VERSION}`,\n },\n ],\n });\n }\n\n return { cards, debts };\n }\n\n /**\n * True for a skill that was *gated and is now reached*: it has at least one\n * declared hierarchy prerequisite set, and every set is fully satisfied by the\n * learner's per-tag ELO. This deliberately EXCLUDES tags with no prerequisites\n * — an ungated tag was never \"introduced\" in the curricular sense, so it isn't\n * a post-intro drill target (e.g. whole-word spelling tags that share the\n * `gpc:exercise:*` prefix but have no intro gate). Those are left to normal\n * ELO retrieval. This is the precise population the retrieval gap strands:\n * just-unlocked, low-ELO skills.\n */\n private isUnlockedGatedSkill(\n tag: string,\n hierarchyConfigs: HierarchyConfig[],\n userTagElo: Record<string, { score: number; count: number }>,\n userGlobalElo: number\n ): boolean {\n const prereqSets = hierarchyConfigs\n .map((hierarchy) => hierarchy.prerequisites[tag])\n .filter((prereqs): prereqs is TagPrerequisite[] => Array.isArray(prereqs) && prereqs.length > 0);\n\n if (prereqSets.length === 0) return false;\n\n return prereqSets.every((prereqs) =>\n prereqs.every((pr) => this.isPrerequisiteMet(pr, userTagElo[pr.tag], userGlobalElo))\n );\n }\n\n private findSupportCardsByTags(\n group: PrescribedGroupConfig,\n tagsByCard: Map<string, string[]>,\n supportTags: string[]\n ): string[] {\n if (supportTags.length === 0) {\n return [];\n }\n\n const explicitSupportIds = group.supportCardIds ?? [];\n const explicitPatterns = group.supportTagPatterns ?? [];\n if (explicitSupportIds.length === 0 && explicitPatterns.length === 0) {\n return [];\n }\n\n const candidates = new Set<string>();\n\n for (const cardId of explicitSupportIds) {\n const cardTags = tagsByCard.get(cardId) ?? [];\n const matchesResolved = supportTags.some((supportTag) => cardTags.includes(supportTag));\n const matchesPattern = explicitPatterns.some((pattern) =>\n cardTags.some((tag) => matchesTagPattern(tag, pattern))\n );\n\n if (matchesResolved || matchesPattern) {\n candidates.add(cardId);\n }\n }\n\n return [...candidates];\n }\n\n private findDiscoveredSupportCards(args: {\n supportTags: string[];\n cardsByTag: Map<string, string[]>;\n activeIds: Set<string>;\n seenIds: Set<string>;\n excludedIds: Set<string>;\n limit: number;\n }): string[] {\n const { supportTags, cardsByTag, activeIds, seenIds, excludedIds, limit } = args;\n\n const byCardId = new Map<string, { cardId: string; matches: number }>();\n\n for (const supportTag of supportTags) {\n const taggedCards = cardsByTag.get(supportTag) ?? [];\n for (const cardId of taggedCards) {\n if (activeIds.has(cardId) || seenIds.has(cardId) || excludedIds.has(cardId)) {\n continue;\n }\n const existing = byCardId.get(cardId);\n if (existing) {\n existing.matches += 1;\n } else {\n byCardId.set(cardId, { cardId, matches: 1 });\n }\n }\n }\n\n const candidates = [...byCardId.values()]\n .sort((a, b) => b.matches - a.matches || a.cardId.localeCompare(b.cardId));\n\n // Diversify by word stem — avoid returning 4 variants of \"year\".\n // ML cards follow c-ml-{word}-{blanks}, so the stem is everything before\n // the last dash-delimited segment of digits/commas.\n const usedStems = new Set<string>();\n const diverse: typeof candidates = [];\n const deferred: typeof candidates = [];\n\n for (const entry of candidates) {\n const stem = extractWordStem(entry.cardId);\n if (!usedStems.has(stem)) {\n usedStems.add(stem);\n diverse.push(entry);\n } else {\n deferred.push(entry);\n }\n }\n\n // Combine diverse-first, then deferred for overflow, and shuffle within\n // each tier so we don't always pick the same card for a given word.\n shuffleInPlace(diverse);\n shuffleInPlace(deferred);\n\n return [...diverse, ...deferred]\n .slice(0, limit)\n .map((entry) => entry.cardId);\n }\n\n private resolveBlockedSupportTags(\n targetTags: string[],\n hierarchyConfigs: HierarchyConfig[],\n userTagElo: Record<string, { score: number; count: number }>,\n userGlobalElo: number,\n hierarchyWalkEnabled: boolean,\n maxDepth: number\n ): { blocked: boolean; supportTags: string[] } {\n const supportTags = new Set<string>();\n let blocked = false;\n\n for (const targetTag of targetTags) {\n const prereqSets = hierarchyConfigs\n .map((hierarchy) => hierarchy.prerequisites[targetTag])\n .filter((prereqs): prereqs is TagPrerequisite[] => Array.isArray(prereqs) && prereqs.length > 0);\n\n if (prereqSets.length === 0) {\n continue;\n }\n\n const tagBlocked = prereqSets.some((prereqs) =>\n prereqs.some((pr) => !this.isPrerequisiteMet(pr, userTagElo[pr.tag], userGlobalElo))\n );\n\n if (!tagBlocked) {\n continue;\n }\n\n blocked = true;\n\n if (!hierarchyWalkEnabled) {\n for (const prereqs of prereqSets) {\n for (const prereq of prereqs) {\n if (!this.isPrerequisiteMet(prereq, userTagElo[prereq.tag], userGlobalElo)) {\n supportTags.add(prereq.tag);\n }\n }\n }\n continue;\n }\n\n for (const prereqs of prereqSets) {\n for (const prereq of prereqs) {\n if (!this.isPrerequisiteMet(prereq, userTagElo[prereq.tag], userGlobalElo)) {\n this.collectSupportTagsRecursive(\n prereq.tag,\n hierarchyConfigs,\n userTagElo,\n userGlobalElo,\n maxDepth,\n new Set<string>(),\n supportTags\n );\n }\n }\n }\n }\n\n return { blocked, supportTags: [...supportTags] };\n }\n\n private collectSupportTagsRecursive(\n tag: string,\n hierarchyConfigs: HierarchyConfig[],\n userTagElo: Record<string, { score: number; count: number }>,\n userGlobalElo: number,\n depth: number,\n visited: Set<string>,\n out: Set<string>\n ): void {\n if (depth < 0 || visited.has(tag)) return;\n\n visited.add(tag);\n\n let walkedFurther = false;\n\n for (const hierarchy of hierarchyConfigs) {\n const prereqs = hierarchy.prerequisites[tag];\n if (!prereqs || prereqs.length === 0) continue;\n\n const unmet = prereqs.filter(\n (pr) => !this.isPrerequisiteMet(pr, userTagElo[pr.tag], userGlobalElo)\n );\n\n if (unmet.length > 0 && depth > 0) {\n walkedFurther = true;\n for (const prereq of unmet) {\n this.collectSupportTagsRecursive(\n prereq.tag,\n hierarchyConfigs,\n userTagElo,\n userGlobalElo,\n depth - 1,\n visited,\n out\n );\n }\n }\n }\n\n if (!walkedFurther) {\n out.add(tag);\n }\n }\n\n\n\n private isPrerequisiteMet(\n prereq: TagPrerequisite,\n userTagElo: { score: number; count: number } | undefined,\n userGlobalElo: number\n ): boolean {\n if (!userTagElo) return false;\n\n const minCount = prereq.masteryThreshold?.minCount ?? DEFAULT_MIN_COUNT;\n if (userTagElo.count < minCount) return false;\n\n if (prereq.masteryThreshold?.minElo !== undefined) {\n return userTagElo.score >= prereq.masteryThreshold.minElo;\n }\n if (prereq.masteryThreshold?.minCount !== undefined) {\n return true;\n }\n\n return userTagElo.score >= userGlobalElo;\n }\n}"],"mappings":";;;;;;AAuJA,MAAM,2BAA2B;AACjC,MAAM,6BAA6B;AACnC,MAAM,8BAA8B;AACpC,MAAM,0BAA0B;AAChC,MAAM,oBAAoB;AAC1B,MAAM,6BAA6B;AACnC,MAAM,+BAA+B;AACrC,MAAM,oBAAoB;AAC1B,MAAM,qBAAqB;AAC3B,MAAM,2BAA2B;AAUjC,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;AAC3B,MAAM,0BAA0B;AAEhC,MAAM,kCAAkC;AACxC,MAAM,wBAAwB;AAC9B,MAAM,yBAAyB;AAE/B,MAAM,2BAA2B;AAEjC,SAAS,OAA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O;AAExC,MAAI,OAAO,kBAAkB,WAAW,KAAA,EACtC,QAAO,WAAW,SAAS,OAAO,iBAAiB;AAErD,MAAI,OAAO,kBAAkB,aAAa,KAAA,EACxC,QAAO;AAGT,SAAO,WAAW,SAAS"}
1
+ {"version":3,"file":"prescribed.mjs","names":[],"sources":["../../../../src/core/navigators/generators/prescribed.ts"],"sourcesContent":["import { tagRole, withTagRole } from '@vue-skuilder/common';\nimport type { CourseDBInterface } from '../../interfaces/courseDB';\nimport type { UserDBInterface } from '../../interfaces/userDB';\nimport { ContentNavigator } from '../index';\nimport type { WeightedCard } from '../index';\nimport type { ContentNavigationStrategyData } from '../../types/contentNavigationStrategy';\nimport type { CardGenerator, GeneratorContext, GeneratorResult, ReplanHints } from './types';\nimport {\n captureStrategyPressure,\n type PressureGaugeDebug,\n} from '../StrategyPressureDebugger';\nimport { logger } from '@db/util/logger';\n\n// ============================================================================\n// PRESCRIBED CARDS GENERATOR\n// ============================================================================\n//\n// A stateful generator for authored, course-prescribed content.\n//\n// Unlike ELO/SRS, prescribed content is explicitly authored curriculum intent.\n// This generator therefore tracks whether prescribed targets have actually been\n// encountered by the user, applies progressive pressure to stale/pending target\n// groups, and can emit upstream support cards when direct targets remain\n// blocked behind prerequisite chains.\n//\n// The first intended use case is intro-card reliability:\n//\n// - direct targets: intro cards that must eventually surface\n// - support cards: low-complexity cards that help satisfy prereqs for blocked\n// intro targets\n//\n// Prescribed content still participates in the normal pipeline. Hierarchy,\n// lesson gating, letter gating, interference, and priority filters continue to\n// shape final ordering.\n//\n// ============================================================================\n\ninterface HierarchyWalkConfig {\n enabled?: boolean;\n maxDepth?: number;\n}\n\ninterface PrescribedGroupConfig {\n id: string;\n targetCardIds: string[];\n supportCardIds?: string[];\n supportTagPatterns?: string[];\n freshnessWindowSessions?: number;\n maxDirectTargetsPerRun?: number;\n maxSupportCardsPerRun?: number;\n hierarchyWalk?: HierarchyWalkConfig;\n /**\n * Exposure an intro target needs before it may surface. Each target is held\n * back — and cards bearing its missing exposure tags are emitted as support —\n * until every exposure tag it implies (its own `gpc:expose:*` tags, plus\n * `gpc:expose:X` for each `gpc:intro:X`) reaches this count. Default 3: a\n * letter is met incidentally inside other words before it is introduced.\n * Set 0 for targets that must be introduced *before* any exposure — e.g.\n * irregular words, which only ever appear in their own cards.\n */\n introExposeMinCount?: number;\n retireOnEncounter?: boolean;\n /**\n * Tag patterns identifying *practice* skills to drill once unlocked. For each\n * course tag matching one of these patterns that is (a) unlocked — all its\n * hierarchy prerequisites met, i.e. the learner has been introduced to it —\n * but (b) still under-practiced (per-tag attempt count below\n * `practiceMinCount`), the generator emits cards carrying that tag into the\n * candidate pool. This closes the post-intro drilling gap independent of\n * global-ELO retrieval (easy drill cards that the ELO window never reaches).\n * Ordering/emphasis is left to the pipeline's scoring + decaying boost.\n */\n practiceTagPatterns?: string[];\n /** Attempt-count threshold below which a practice skill is \"under-practiced\". */\n practiceMinCount?: number;\n /** Cap on practice cards emitted per run (across all under-practiced skills). */\n maxPracticeCardsPerRun?: number;\n}\n\ninterface PrescribedConfig {\n groups: PrescribedGroupConfig[];\n}\n\ninterface GroupCardState {\n encounteredCardIds: string[];\n pendingTargetIds: string[];\n lastSurfacedAt: string | null;\n sessionsSinceSurfaced: number;\n lastSupportAt: string | null;\n blockedTargetIds: string[];\n lastResolvedSupportTags: string[];\n}\n\ninterface PrescribedProgressState {\n updatedAt: string;\n groups: Record<string, GroupCardState>;\n /**\n * Per-practice-tag debt age: tag → ISO timestamp when the skill first appeared\n * unlocked-but-under-practiced. Drives the practice-debt staleness escalation\n * (older unpaid debt → higher pressure). An entry is carried while the debt is\n * open and dropped the moment the skill reaches `practiceMinCount` — so the\n * map self-prunes and \"staleness\" is measured from first-owed, not last-seen.\n */\n practiceDebt?: Record<string, string>;\n}\n\ninterface TagPrerequisite {\n tag: string;\n masteryThreshold?: {\n minElo?: number;\n minCount?: number;\n };\n preReqBoost?: number;\n targetBoost?: number;\n}\n\ninterface HierarchyConfig {\n prerequisites: Record<string, TagPrerequisite[]>;\n}\n\ninterface GroupRuntimeState {\n group: PrescribedGroupConfig;\n encounteredTargets: Set<string>;\n pendingTargets: string[];\n blockedTargets: string[];\n surfaceableTargets: string[];\n targetTags: Map<string, string[]>;\n supportCandidates: string[];\n discoveredSupportCandidates: string[];\n supportTags: string[];\n pressureMultiplier: number;\n supportMultiplier: number;\n /** Carried-forward staleness count driving the pressure multipliers. */\n sessionsSinceSurfaced: number;\n debugVersion: string;\n}\n\n/** One open practice debt, surfaced for the strategy-pressure debug channel. */\ninterface PracticeDebtDebug {\n tag: string;\n multiplier: number;\n /** ISO timestamp when the skill first appeared unlocked-but-under-practiced. */\n firstOwedAt: string;\n}\n\ninterface HintEmissionSummary {\n boostTags: Record<string, number>;\n blockedTargetIds: string[];\n supportTags: string[];\n}\n\nconst DEFAULT_FRESHNESS_WINDOW = 3;\nconst DEFAULT_MAX_DIRECT_PER_RUN = 3;\nconst DEFAULT_MAX_SUPPORT_PER_RUN = 3;\nconst DEFAULT_HIERARCHY_DEPTH = 2;\nconst DEFAULT_MIN_COUNT = 3;\nconst DEFAULT_PRACTICE_MIN_COUNT = 3;\nconst DEFAULT_MAX_PRACTICE_PER_RUN = 4;\nconst BASE_TARGET_SCORE = 1.0;\nconst BASE_SUPPORT_SCORE = 0.8;\nconst DISCOVERED_SUPPORT_SCORE = 12.0;\n// Practice drill cards: a *practice-debt pressure*, parallel to the SRS backlog\n// multiplier. An unlocked-but-under-practiced skill owes reps; that debt is\n// durable (keyed off per-tag attempt count) and discharges by practice, not\n// time. The score is base × a debt multiplier that starts at PRACTICE_BASE_MULT\n// (so a few reps land promptly after intro, competing with pressured reviews)\n// and escalates by how long the debt has stayed open (capped), so a chronically\n// out-competed skill eventually forces exposure rather than competing at flat\n// parity forever. Replaces the old flat 1.0, which punted emphasis to the\n// session-scoped intro boost that evaporates at session end.\nconst BASE_PRACTICE_SCORE = 1.0;\nconst PRACTICE_BASE_MULT = 2.0;\nconst MAX_PRACTICE_MULTIPLIER = 4.0;\n// Added to the multiplier per day the debt stays open (linear, then clamped).\nconst PRACTICE_STALENESS_BUMP_PER_DAY = 0.5;\nconst MAX_TARGET_MULTIPLIER = 8.0;\nconst MAX_SUPPORT_MULTIPLIER = 4.0;\n\nconst PRESCRIBED_DEBUG_VERSION = 'testversion-prescribed-v3';\n\nfunction dedupe<T>(arr: T[]): T[] {\n return [...new Set(arr)];\n}\n\nfunction isoNow(): string {\n return new Date().toISOString();\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction matchesTagPattern(tag: string, pattern: string): boolean {\n if (pattern === '*') return true;\n const escaped = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*/g, '.*');\n const re = new RegExp(`^${escaped}$`);\n return re.test(tag);\n}\n\n/**\n * Extract the word stem from a card ID for deduplication.\n * ML: c-ml-{word}-{blanks} → {word}\n * WS: c-ws-{word}-{contrast} → {word}\n * Other: full cardId as fallback.\n */\nfunction extractWordStem(cardId: string): string {\n for (const prefix of ['c-ml-', 'c-ws-', 'c-spelling-']) {\n if (cardId.startsWith(prefix)) {\n const rest = cardId.slice(prefix.length);\n const lastDash = rest.lastIndexOf('-');\n return lastDash > 0 ? rest.slice(0, lastDash) : rest;\n }\n }\n return cardId;\n}\n\n/** Fisher-Yates shuffle in place. */\nfunction shuffleInPlace<T>(arr: T[]): void {\n for (let i = arr.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n [arr[i], arr[j]] = [arr[j], arr[i]];\n }\n}\n\n/** Compact age string for debt-open durations: 42m / 7h / 3d. */\nfunction formatAge(ms: number): string {\n const minutes = Math.max(0, Math.round(ms / 60000));\n if (minutes < 60) return `${minutes}m`;\n const hours = Math.round(minutes / 60);\n if (hours < 24) return `${hours}h`;\n return `${Math.round(hours / 24)}d`;\n}\n\n/**\n * The exposure tags an intro target still lacks before it may surface: its own\n * `expose` tags plus the `expose` counterpart of each `intro` tag (tag roles,\n * see common's tagRoles.ts: `gpc:intro:X` → `gpc:expose:X`), each needing\n * `minCount` attempts. A `minCount` of 0 requires nothing — not even an entry\n * in `userTagElo`.\n */\nexport function unmetIntroExposeTags(\n tags: string[],\n userTagElo: Record<string, { count: number }>,\n minCount: number\n): string[] {\n if (minCount <= 0) return [];\n\n const exposeTags = new Set(tags.filter((tag) => tagRole(tag) === 'expose'));\n for (const tag of tags) {\n if (tagRole(tag) !== 'intro') continue;\n const expose = withTagRole(tag, 'expose');\n if (expose) exposeTags.add(expose);\n }\n\n return [...exposeTags].filter((tag) => {\n const tagElo = userTagElo[tag];\n return !tagElo || tagElo.count < minCount;\n });\n}\n\nfunction pickTopByScore(cards: WeightedCard[], limit: number): WeightedCard[] {\n return [...cards]\n .sort((a, b) => b.score - a.score || a.cardId.localeCompare(b.cardId))\n .slice(0, limit);\n}\n\nexport default class PrescribedCardsGenerator extends ContentNavigator implements CardGenerator {\n name: string;\n private config: PrescribedConfig;\n /**\n * Course-wide reads that don't change within a navigator's lifetime (the\n * navigator is cached per CourseDB, minutes), loaded once, not per run.\n */\n private _cardsByTag: Promise<Map<string, string[]>> | null = null;\n private _hierarchyConfigs: Promise<HierarchyConfig[]> | null = null;\n\n constructor(\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n ) {\n super(user, course, strategyData);\n this.name = strategyData.name || 'Prescribed Cards';\n this.config = this.parseConfig(strategyData.serializedData);\n\n logger.debug(\n `[Prescribed] Initialized with ${this.config.groups.length} groups and ` +\n `${this.config.groups.reduce((n, g) => n + g.targetCardIds.length, 0)} targets`\n );\n }\n\n protected override get strategyKey(): string {\n return 'PrescribedProgress';\n }\n\n async getWeightedCards(limit: number, context?: GeneratorContext): Promise<GeneratorResult> {\n if (this.config.groups.length === 0 || limit <= 0) {\n return { cards: [] };\n }\n\n const courseId = this.course.getCourseID();\n const activeCards = await this.user.getActiveCards();\n const activeIds = new Set(activeCards.map((ac) => ac.cardID));\n\n const seenCards = await this.user.getSeenCards(courseId).catch(() => []);\n const seenIds = new Set(seenCards);\n\n const progress = (await this.getStrategyState<PrescribedProgressState>()) ?? {\n updatedAt: isoNow(),\n groups: {},\n };\n\n const hierarchyConfigs = await this.loadHierarchyConfigs();\n const courseReg = await this.user.getCourseRegDoc(courseId).catch(() => null);\n const userGlobalElo =\n typeof courseReg?.elo === 'number'\n ? courseReg.elo\n : courseReg?.elo?.global?.score ?? context?.userElo ?? 1000;\n const userTagElo =\n typeof courseReg?.elo === 'number'\n ? {}\n : courseReg?.elo?.tags ?? {};\n\n const allTargetIds = dedupe(this.config.groups.flatMap((g) => g.targetCardIds));\n const allSupportIds = dedupe(this.config.groups.flatMap((g) => g.supportCardIds ?? []));\n const allRelevantIds = dedupe([...allTargetIds, ...allSupportIds]);\n\n const tagsByCard =\n allRelevantIds.length > 0\n ? await this.course.getAppliedTagsBatch(allRelevantIds)\n : new Map<string, string[]>();\n\n const cardsByTag = await this.loadCardsByTag();\n\n const nextState: PrescribedProgressState = {\n updatedAt: isoNow(),\n groups: {},\n };\n\n const emitted: WeightedCard[] = [];\n const emittedIds = new Set<string>();\n const groupRuntimes: GroupRuntimeState[] = [];\n // Practice-debt ages carried forward: stamped when a skill first appears\n // under-practiced, dropped once it's discharged (see buildPracticeCards).\n const priorPracticeDebt = progress.practiceDebt ?? {};\n const nextPracticeDebt: Record<string, string> = {};\n const practiceDebtsByGroup = new Map<string, PracticeDebtDebug[]>();\n\n for (const group of this.config.groups) {\n const runtime = this.buildGroupRuntimeState({\n group,\n priorState: progress.groups[group.id],\n activeIds,\n seenIds,\n tagsByCard,\n cardsByTag,\n hierarchyConfigs,\n userTagElo,\n userGlobalElo,\n });\n\n groupRuntimes.push(runtime);\n\n logger.info(\n `[Prescribed] Group '${group.id}': ` +\n `${group.targetCardIds.length} targets total, ` +\n `${runtime.encounteredTargets.size} encountered, ` +\n `${runtime.pendingTargets.length} pending ` +\n `(${runtime.surfaceableTargets.length} surfaceable, ${runtime.blockedTargets.length} blocked), ` +\n `${runtime.supportCandidates.length} authored support candidates, ` +\n `${runtime.discoveredSupportCandidates.length} discovered support candidates, ` +\n `pressure=${runtime.pressureMultiplier.toFixed(2)}`\n );\n if (runtime.blockedTargets.length > 0) {\n logger.info(\n `[Prescribed] Group '${group.id}' blocked targets: ${runtime.blockedTargets.join(', ')}`\n );\n logger.info(\n `[Prescribed] Group '${group.id}' support tags needed: ${runtime.supportTags.join(', ') || '(none)'}`\n );\n logger.info(\n `[Prescribed] Group '${group.id}' escalation mode: ` +\n (runtime.supportCandidates.length > 0\n ? 'direct-support'\n : runtime.discoveredSupportCandidates.length > 0\n ? 'inserted-support-candidates'\n : 'boost-only')\n );\n if (runtime.discoveredSupportCandidates.length > 0) {\n logger.info(\n `[Prescribed] Group '${group.id}' discovered support candidates: ${runtime.discoveredSupportCandidates.join(', ')}`\n );\n }\n }\n\n nextState.groups[group.id] = this.buildNextGroupState(runtime, progress.groups[group.id]);\n\n const directCards = this.buildDirectTargetCards(\n runtime,\n courseId,\n emittedIds\n );\n const supportCards = this.buildSupportCards(\n runtime,\n courseId,\n emittedIds\n );\n const discoveredSupportCards = this.buildDiscoveredSupportCards(\n runtime,\n courseId,\n emittedIds\n );\n const practice = this.buildPracticeCards({\n group,\n courseId,\n emittedIds,\n cardsByTag,\n hierarchyConfigs,\n userTagElo,\n userGlobalElo,\n activeIds,\n seenIds,\n priorPracticeDebt,\n nextPracticeDebt,\n });\n practiceDebtsByGroup.set(group.id, practice.debts);\n\n emitted.push(...directCards, ...supportCards, ...discoveredSupportCards, ...practice.cards);\n }\n\n // Persist the carried-forward practice debt (self-pruned: discharged skills\n // simply aren't re-stamped above, so they drop out of the next state).\n nextState.practiceDebt = nextPracticeDebt;\n\n const hintSummary = this.buildSupportHintSummary(groupRuntimes);\n const hints: ReplanHints | undefined =\n Object.keys(hintSummary.boostTags).length > 0\n ? {\n boostTags: hintSummary.boostTags,\n _label:\n `prescribed-support (${hintSummary.supportTags.length} tags; ` +\n `blocked=${hintSummary.blockedTargetIds.length}; ` +\n `testversion=${PRESCRIBED_DEBUG_VERSION})`,\n }\n : undefined;\n\n if (hints) {\n const tagEntries = Object.entries(hints.boostTags ?? {}) as Array<[string, number]>;\n logger.info(\n `[Prescribed] Emitting ${tagEntries.length} boost hint(s): ` +\n tagEntries.map(([tag, mult]) => `${tag}×${mult.toFixed(1)}`).join(', ')\n );\n } else {\n logger.info('[Prescribed] No hints to emit (no blocked targets or no support tags)');\n }\n\n // Push this run's pressure state to the live-overlay debug channel. Done\n // before the empty-emission return — an all-blocked run is exactly the\n // state the overlay most needs to show.\n this.capturePressureSnapshot(courseId, groupRuntimes, practiceDebtsByGroup, emitted, hints);\n\n if (emitted.length === 0) {\n logger.info(\n '[Prescribed] 0 cards emitted (all targets blocked, authored/discovered support candidates exhausted)' +\n (hints ? ' — boost hints emitted but may not survive filters' : '')\n );\n await this.putStrategyState(nextState).catch((e) => {\n logger.debug(`[Prescribed] Failed to persist empty-state update: ${e}`);\n });\n return hints ? { cards: [], hints } : { cards: [] };\n }\n\n const finalCards = pickTopByScore(emitted, limit);\n\n const surfacedByGroup = new Map<string, { targetIds: string[]; supportIds: string[] }>();\n for (const card of finalCards) {\n const prov = card.provenance[0];\n // Practice cards are not target/support surfacing — they must not reset a\n // group's freshness/pressure state (which tracks whether *intro targets*\n // are getting through). Skip them here.\n if (prov?.reason.includes('mode=practice')) continue;\n const groupId = prov?.reason.match(/group=([^;]+)/)?.[1];\n const mode = prov?.reason.includes('mode=support') ? 'supportIds' : 'targetIds';\n if (!groupId) continue;\n if (!surfacedByGroup.has(groupId)) {\n surfacedByGroup.set(groupId, { targetIds: [], supportIds: [] });\n }\n surfacedByGroup.get(groupId)![mode].push(card.cardId);\n }\n\n for (const group of this.config.groups) {\n const groupState = nextState.groups[group.id];\n const surfaced = surfacedByGroup.get(group.id);\n if (surfaced && (surfaced.targetIds.length > 0 || surfaced.supportIds.length > 0)) {\n groupState.lastSurfacedAt = isoNow();\n groupState.sessionsSinceSurfaced = 0;\n if (surfaced.supportIds.length > 0) {\n groupState.lastSupportAt = isoNow();\n }\n }\n }\n\n await this.putStrategyState(nextState).catch((e) => {\n logger.debug(`[Prescribed] Failed to persist prescribed progress: ${e}`);\n });\n\n logger.info(\n `[Prescribed] Emitting ${finalCards.length} cards ` +\n `(${finalCards.filter((c) => c.provenance[0]?.reason.includes('mode=target')).length} target, ` +\n `${finalCards.filter((c) => c.provenance[0]?.reason.includes('mode=support')).length} support, ` +\n `${finalCards.filter((c) => c.provenance[0]?.reason.includes('mode=discovered-support')).length} discovered support)`\n );\n\n return hints ? { cards: finalCards, hints } : { cards: finalCards };\n }\n\n private buildSupportHintSummary(groupRuntimes: GroupRuntimeState[]): HintEmissionSummary {\n const boostTags: Record<string, number> = {};\n const blockedTargetIds = new Set<string>();\n const supportTags = new Set<string>();\n\n for (const runtime of groupRuntimes) {\n if (runtime.blockedTargets.length === 0 || runtime.supportTags.length === 0) {\n continue;\n }\n\n runtime.blockedTargets.forEach((cardId) => blockedTargetIds.add(cardId));\n\n for (const tag of runtime.supportTags) {\n supportTags.add(tag);\n boostTags[tag] = (boostTags[tag] ?? 1) * runtime.supportMultiplier;\n }\n }\n\n return {\n boostTags,\n blockedTargetIds: [...blockedTargetIds].sort(),\n supportTags: [...supportTags].sort(),\n };\n }\n\n /**\n * Translate this run's per-group runtimes and practice debts into gauges on\n * the generic strategy-pressure debug channel (rendered by the live session\n * overlay's \"strategy backpressure\" section).\n */\n private capturePressureSnapshot(\n courseId: string,\n groupRuntimes: GroupRuntimeState[],\n practiceDebtsByGroup: Map<string, PracticeDebtDebug[]>,\n emitted: WeightedCard[],\n hints: ReplanHints | undefined\n ): void {\n const now = Date.now();\n const gauges: PressureGaugeDebug[] = [];\n\n for (const runtime of groupRuntimes) {\n const group = runtime.group;\n const window = group.freshnessWindowSessions ?? DEFAULT_FRESHNESS_WINDOW;\n\n gauges.push({\n id: `group:${group.id}:target`,\n label: `${group.id} targets`,\n multiplier: runtime.pressureMultiplier,\n max: MAX_TARGET_MULTIPLIER,\n detail:\n `${runtime.pendingTargets.length} pending ` +\n `(${runtime.surfaceableTargets.length} surfaceable, ${runtime.blockedTargets.length} blocked) · ` +\n `sinceSurfaced ${runtime.sessionsSinceSurfaced}/${window}`,\n items: runtime.blockedTargets.map((cardId) => ({ label: cardId, value: 'blocked' })),\n });\n\n if (runtime.blockedTargets.length > 0) {\n const mode =\n runtime.supportCandidates.length > 0\n ? 'direct-support'\n : runtime.discoveredSupportCandidates.length > 0\n ? 'inserted-support'\n : 'boost-only';\n gauges.push({\n id: `group:${group.id}:support`,\n label: `${group.id} support`,\n multiplier: runtime.supportMultiplier,\n max: MAX_SUPPORT_MULTIPLIER,\n detail: `mode=${mode} · ${runtime.supportTags.length} support tag(s)`,\n items: runtime.supportTags.map((tag) => ({ label: tag })),\n });\n }\n\n const debts = practiceDebtsByGroup.get(group.id) ?? [];\n if (debts.length > 0) {\n gauges.push({\n id: `group:${group.id}:practice-debt`,\n label: `${group.id} practice debt`,\n multiplier: Math.max(...debts.map((d) => d.multiplier)),\n max: MAX_PRACTICE_MULTIPLIER,\n detail: `${debts.length} under-practiced skill(s)`,\n items: debts.map((d) => ({\n label: d.tag,\n value: `×${d.multiplier.toFixed(2)} · open ${formatAge(now - new Date(d.firstOwedAt).getTime())}`,\n })),\n });\n }\n }\n\n captureStrategyPressure({\n source: 'prescribed',\n courseId,\n gauges,\n topScore: emitted.length > 0 ? Math.max(...emitted.map((c) => c.score)) : null,\n hintsLabel: hints?._label,\n timestamp: now,\n });\n }\n\n private parseConfig(serializedData: string): PrescribedConfig {\n try {\n const parsed = JSON.parse(serializedData) as { groups?: unknown[] };\n const groupsRaw = Array.isArray(parsed.groups) ? parsed.groups : [];\n const groups: PrescribedGroupConfig[] = groupsRaw\n .map((raw: any, i: number): PrescribedGroupConfig => ({\n id: typeof raw.id === 'string' && raw.id.trim().length > 0 ? raw.id : `group-${i + 1}`,\n targetCardIds: dedupe(\n (Array.isArray(raw.targetCardIds) ? raw.targetCardIds.filter((v: unknown): v is string => typeof v === 'string') : [])\n ),\n supportCardIds: dedupe(\n (Array.isArray(raw.supportCardIds) ? raw.supportCardIds.filter((v: unknown): v is string => typeof v === 'string') : [])\n ),\n supportTagPatterns: dedupe(\n (Array.isArray(raw.supportTagPatterns)\n ? raw.supportTagPatterns.filter((v: unknown): v is string => typeof v === 'string')\n : [])\n ),\n freshnessWindowSessions:\n typeof raw.freshnessWindowSessions === 'number' ? raw.freshnessWindowSessions : DEFAULT_FRESHNESS_WINDOW,\n maxDirectTargetsPerRun:\n typeof raw.maxDirectTargetsPerRun === 'number' ? raw.maxDirectTargetsPerRun : DEFAULT_MAX_DIRECT_PER_RUN,\n maxSupportCardsPerRun:\n typeof raw.maxSupportCardsPerRun === 'number' ? raw.maxSupportCardsPerRun : DEFAULT_MAX_SUPPORT_PER_RUN,\n introExposeMinCount:\n typeof raw.introExposeMinCount === 'number' ? raw.introExposeMinCount : DEFAULT_MIN_COUNT,\n hierarchyWalk: {\n enabled: raw.hierarchyWalk?.enabled !== false,\n maxDepth:\n typeof raw.hierarchyWalk?.maxDepth === 'number'\n ? raw.hierarchyWalk.maxDepth\n : DEFAULT_HIERARCHY_DEPTH,\n },\n retireOnEncounter: raw.retireOnEncounter !== false,\n practiceTagPatterns: dedupe(\n Array.isArray(raw.practiceTagPatterns)\n ? raw.practiceTagPatterns.filter((v: unknown): v is string => typeof v === 'string')\n : []\n ),\n practiceMinCount:\n typeof raw.practiceMinCount === 'number' ? raw.practiceMinCount : DEFAULT_PRACTICE_MIN_COUNT,\n maxPracticeCardsPerRun:\n typeof raw.maxPracticeCardsPerRun === 'number'\n ? raw.maxPracticeCardsPerRun\n : DEFAULT_MAX_PRACTICE_PER_RUN,\n }))\n .filter((g) => g.targetCardIds.length > 0);\n\n return { groups };\n } catch {\n return { groups: [] };\n }\n }\n\n /** Tag name → tagged card IDs, from the course's tag docs (once per instance). */\n private loadCardsByTag(): Promise<Map<string, string[]>> {\n if (!this._cardsByTag) {\n this._cardsByTag = this.course\n .getCourseTagStubs()\n .then((docs) => {\n const cardsByTag = new Map<string, string[]>();\n for (const row of docs.rows ?? []) {\n const tagDoc = row.doc as { name?: string; taggedCards?: string[] } | undefined;\n if (tagDoc?.name && Array.isArray(tagDoc.taggedCards)) {\n cardsByTag.set(tagDoc.name, [...tagDoc.taggedCards]);\n }\n }\n return cardsByTag;\n })\n .catch((e) => {\n // Not cached: the next run retries.\n this._cardsByTag = null;\n logger.debug(`[Prescribed] Failed to load tag docs: ${e}`);\n return new Map<string, string[]>();\n });\n }\n return this._cardsByTag;\n }\n\n private loadHierarchyConfigs(): Promise<HierarchyConfig[]> {\n if (!this._hierarchyConfigs) {\n this._hierarchyConfigs = this.fetchHierarchyConfigs();\n }\n return this._hierarchyConfigs;\n }\n\n private async fetchHierarchyConfigs(): Promise<HierarchyConfig[]> {\n try {\n const strategies = await this.course.getAllNavigationStrategies();\n return strategies\n .filter((s: ContentNavigationStrategyData) => s.implementingClass === 'hierarchyDefinition')\n .map((s: ContentNavigationStrategyData) => {\n try {\n const parsed = JSON.parse(s.serializedData) as { prerequisites?: Record<string, TagPrerequisite[]> };\n return {\n prerequisites: parsed.prerequisites || {},\n } as HierarchyConfig;\n } catch {\n return { prerequisites: {} };\n }\n });\n } catch (e) {\n // Not cached: the next run retries.\n this._hierarchyConfigs = null;\n logger.debug(`[Prescribed] Failed to load hierarchy configs: ${e}`);\n return [];\n }\n }\n\n private buildGroupRuntimeState(args: {\n group: PrescribedGroupConfig;\n priorState?: GroupCardState;\n activeIds: Set<string>;\n seenIds: Set<string>;\n tagsByCard: Map<string, string[]>;\n cardsByTag: Map<string, string[]>;\n hierarchyConfigs: HierarchyConfig[];\n userTagElo: Record<string, { score: number; count: number }>;\n userGlobalElo: number;\n }): GroupRuntimeState {\n const {\n group,\n priorState,\n activeIds,\n seenIds,\n tagsByCard,\n cardsByTag,\n hierarchyConfigs,\n userTagElo,\n userGlobalElo,\n } = args;\n\n const encounteredTargets = new Set<string>();\n for (const cardId of group.targetCardIds) {\n if (activeIds.has(cardId) || seenIds.has(cardId)) {\n encounteredTargets.add(cardId);\n }\n }\n\n if (priorState?.encounteredCardIds?.length) {\n for (const cardId of priorState.encounteredCardIds) {\n encounteredTargets.add(cardId);\n }\n }\n\n const pendingTargets = group.targetCardIds.filter((id) => !encounteredTargets.has(id));\n const targetTags = new Map<string, string[]>();\n for (const cardId of pendingTargets) {\n targetTags.set(cardId, tagsByCard.get(cardId) ?? []);\n }\n\n const blockedTargets: string[] = [];\n const surfaceableTargets: string[] = [];\n const supportTags = new Set<string>();\n\n for (const cardId of pendingTargets) {\n const tags = targetTags.get(cardId) ?? [];\n const resolution = this.resolveBlockedSupportTags(\n tags,\n hierarchyConfigs,\n userTagElo,\n userGlobalElo,\n group.hierarchyWalk?.enabled !== false,\n group.hierarchyWalk?.maxDepth ?? DEFAULT_HIERARCHY_DEPTH\n );\n\n const unmetExposeTags = unmetIntroExposeTags(\n tags,\n userTagElo,\n group.introExposeMinCount ?? DEFAULT_MIN_COUNT\n );\n\n if (unmetExposeTags.length > 0) {\n unmetExposeTags.forEach((tag) => supportTags.add(tag));\n }\n\n if (resolution.blocked || unmetExposeTags.length > 0) {\n blockedTargets.push(cardId);\n resolution.supportTags.forEach((t) => supportTags.add(t));\n } else {\n surfaceableTargets.push(cardId);\n }\n }\n\n const supportCandidates = dedupe([\n ...(group.supportCardIds ?? []),\n ...this.findSupportCardsByTags(\n group,\n tagsByCard,\n [...supportTags]\n ),\n ]).filter((id) => !activeIds.has(id) && !seenIds.has(id));\n\n const discoveredSupportCandidates =\n blockedTargets.length > 0 && supportTags.size > 0 && supportCandidates.length === 0\n ? this.findDiscoveredSupportCards({\n supportTags: [...supportTags],\n cardsByTag,\n activeIds,\n seenIds,\n excludedIds: new Set([\n ...group.targetCardIds,\n ...(group.supportCardIds ?? []),\n ]),\n limit: group.maxSupportCardsPerRun ?? DEFAULT_MAX_SUPPORT_PER_RUN,\n })\n : [];\n\n if (blockedTargets.length > 0 && supportTags.size > 0 && discoveredSupportCandidates.length === 0) {\n logger.info(\n `[Prescribed] Group '${group.id}' discovered 0 broader support candidates ` +\n `(blocked=${blockedTargets.length}; authoredSupport=${supportCandidates.length})`\n );\n }\n\n const sessionsSinceSurfaced = priorState?.sessionsSinceSurfaced ?? 0;\n const freshnessWindow = group.freshnessWindowSessions ?? DEFAULT_FRESHNESS_WINDOW;\n const staleSessions = Math.max(0, sessionsSinceSurfaced - freshnessWindow);\n\n const pressureMultiplier = pendingTargets.length === 0\n ? 1.0\n : clamp(1 + staleSessions * 0.75 + Math.min(2, pendingTargets.length * 0.1), 1.0, MAX_TARGET_MULTIPLIER);\n\n const supportMultiplier = blockedTargets.length === 0\n ? 1.0\n : clamp(1 + staleSessions * 0.5 + Math.min(1.5, blockedTargets.length * 0.15), 1.0, MAX_SUPPORT_MULTIPLIER);\n\n return {\n group,\n encounteredTargets,\n pendingTargets,\n blockedTargets,\n surfaceableTargets,\n targetTags,\n supportCandidates,\n discoveredSupportCandidates,\n supportTags: [...supportTags],\n pressureMultiplier,\n supportMultiplier,\n sessionsSinceSurfaced,\n debugVersion: PRESCRIBED_DEBUG_VERSION,\n };\n }\n\n private buildNextGroupState(runtime: GroupRuntimeState, prior?: GroupCardState): GroupCardState {\n const carriedSessions = prior?.sessionsSinceSurfaced ?? 0;\n const surfacedThisRun = false;\n\n return {\n encounteredCardIds: [...runtime.encounteredTargets].sort(),\n pendingTargetIds: [...runtime.pendingTargets].sort(),\n lastSurfacedAt: prior?.lastSurfacedAt ?? null,\n sessionsSinceSurfaced: surfacedThisRun ? 0 : carriedSessions + 1,\n lastSupportAt: prior?.lastSupportAt ?? null,\n blockedTargetIds: [...runtime.blockedTargets].sort(),\n lastResolvedSupportTags: [...runtime.supportTags].sort(),\n };\n }\n\n private buildDirectTargetCards(\n runtime: GroupRuntimeState,\n courseId: string,\n emittedIds: Set<string>\n ): WeightedCard[] {\n const maxDirect = runtime.group.maxDirectTargetsPerRun ?? DEFAULT_MAX_DIRECT_PER_RUN;\n\n const directIds = runtime.surfaceableTargets\n .filter((id) => !emittedIds.has(id))\n .slice(0, maxDirect);\n\n const cards: WeightedCard[] = [];\n for (const cardId of directIds) {\n emittedIds.add(cardId);\n cards.push({\n cardId,\n courseId,\n score: BASE_TARGET_SCORE * runtime.pressureMultiplier,\n provenance: [\n {\n strategy: 'prescribed',\n strategyName: this.strategyName || this.name,\n strategyId: this.strategyId || 'NAVIGATION_STRATEGY-prescribed',\n action: 'generated' as const,\n score: BASE_TARGET_SCORE * runtime.pressureMultiplier,\n reason:\n `mode=target;group=${runtime.group.id};pending=${runtime.pendingTargets.length};` +\n `surfaceable=${runtime.surfaceableTargets.length};blocked=${runtime.blockedTargets.length};` +\n `blockedTargets=${runtime.blockedTargets.join('|') || 'none'};` +\n `supportTags=${runtime.supportTags.join('|') || 'none'};` +\n `multiplier=${runtime.pressureMultiplier.toFixed(2)};` +\n `testversion=${runtime.debugVersion}`,\n },\n ],\n });\n }\n\n return cards;\n }\n\n private buildSupportCards(\n runtime: GroupRuntimeState,\n courseId: string,\n emittedIds: Set<string>\n ): WeightedCard[] {\n if (runtime.blockedTargets.length === 0 || runtime.supportCandidates.length === 0) {\n return [];\n }\n\n const maxSupport = runtime.group.maxSupportCardsPerRun ?? DEFAULT_MAX_SUPPORT_PER_RUN;\n const supportIds = runtime.supportCandidates\n .filter((id) => !emittedIds.has(id))\n .slice(0, maxSupport);\n\n const cards: WeightedCard[] = [];\n for (const cardId of supportIds) {\n emittedIds.add(cardId);\n cards.push({\n cardId,\n courseId,\n score: BASE_SUPPORT_SCORE * runtime.supportMultiplier,\n provenance: [\n {\n strategy: 'prescribed',\n strategyName: this.strategyName || this.name,\n strategyId: this.strategyId || 'NAVIGATION_STRATEGY-prescribed',\n action: 'generated' as const,\n score: BASE_SUPPORT_SCORE * runtime.supportMultiplier,\n reason:\n `mode=support;group=${runtime.group.id};pending=${runtime.pendingTargets.length};` +\n `blocked=${runtime.blockedTargets.length};` +\n `blockedTargets=${runtime.blockedTargets.join('|') || 'none'};` +\n `supportCard=${cardId};` +\n `supportTags=${runtime.supportTags.join('|') || 'none'};` +\n `multiplier=${runtime.supportMultiplier.toFixed(2)};` +\n `testversion=${runtime.debugVersion}`,\n },\n ],\n });\n }\n\n return cards;\n }\n\n private buildDiscoveredSupportCards(\n runtime: GroupRuntimeState,\n courseId: string,\n emittedIds: Set<string>\n ): WeightedCard[] {\n if (runtime.blockedTargets.length === 0 || runtime.discoveredSupportCandidates.length === 0) {\n return [];\n }\n\n const maxSupport = runtime.group.maxSupportCardsPerRun ?? DEFAULT_MAX_SUPPORT_PER_RUN;\n const supportIds = runtime.discoveredSupportCandidates\n .filter((id) => !emittedIds.has(id))\n .slice(0, maxSupport);\n\n const cards: WeightedCard[] = [];\n for (const cardId of supportIds) {\n emittedIds.add(cardId);\n cards.push({\n cardId,\n courseId,\n score: DISCOVERED_SUPPORT_SCORE * runtime.supportMultiplier,\n provenance: [\n {\n strategy: 'prescribed',\n strategyName: this.strategyName || this.name,\n strategyId: this.strategyId || 'NAVIGATION_STRATEGY-prescribed',\n action: 'generated' as const,\n score: DISCOVERED_SUPPORT_SCORE * runtime.supportMultiplier,\n reason:\n `mode=discovered-support;group=${runtime.group.id};pending=${runtime.pendingTargets.length};` +\n `blocked=${runtime.blockedTargets.length};` +\n `blockedTargets=${runtime.blockedTargets.join('|') || 'none'};` +\n `supportCard=${cardId};` +\n `supportTags=${runtime.supportTags.join('|') || 'none'};` +\n `multiplier=${runtime.supportMultiplier.toFixed(2)};` +\n `testversion=${runtime.debugVersion}`,\n },\n ],\n });\n }\n\n return cards;\n }\n\n /**\n * Emit drill cards for *unlocked-but-under-practiced* skills.\n *\n * For each course tag matching the group's `practiceTagPatterns` that is both\n * unlocked (all hierarchy prerequisites met — i.e. the learner has been\n * introduced to it) and under-practiced (per-tag attempt count below\n * `practiceMinCount`), this resolves cards carrying that tag and emits them\n * into the candidate pool. It exists because global-ELO retrieval\n * systematically fails to fetch the (low-ELO) drill cards for a\n * freshly-introduced skill — putting them in the pool here guarantees presence.\n *\n * Emphasis is a **practice-debt pressure** (parallel to SRS backlog pressure):\n * cards score `base × multiplier`, where the multiplier starts at\n * PRACTICE_BASE_MULT (so a few reps land promptly post-intro, competing with\n * pressured reviews) and escalates by how long the debt has stayed open\n * (per-tag, time-based via `priorPracticeDebt`/`nextPracticeDebt`), clamped at\n * MAX_PRACTICE_MULTIPLIER. The debt is durable and self-discharges the instant\n * the skill reaches `practiceMinCount` — so this no longer relies on the\n * session-scoped intro boost to actually surface.\n *\n * Fully data-driven: the unlock relation comes from the hierarchy config and\n * practice-status from per-tag ELO. No card-id or tag-namespace hard-coding.\n */\n private buildPracticeCards(args: {\n group: PrescribedGroupConfig;\n courseId: string;\n emittedIds: Set<string>;\n cardsByTag: Map<string, string[]>;\n hierarchyConfigs: HierarchyConfig[];\n userTagElo: Record<string, { score: number; count: number }>;\n userGlobalElo: number;\n activeIds: Set<string>;\n seenIds: Set<string>;\n priorPracticeDebt: Record<string, string>;\n nextPracticeDebt: Record<string, string>;\n }): { cards: WeightedCard[]; debts: PracticeDebtDebug[] } {\n const {\n group,\n courseId,\n emittedIds,\n cardsByTag,\n hierarchyConfigs,\n userTagElo,\n userGlobalElo,\n activeIds,\n seenIds,\n priorPracticeDebt,\n nextPracticeDebt,\n } = args;\n\n const patterns = group.practiceTagPatterns ?? [];\n if (patterns.length === 0) return { cards: [], debts: [] };\n\n const practiceMinCount = group.practiceMinCount ?? DEFAULT_PRACTICE_MIN_COUNT;\n const maxPractice = group.maxPracticeCardsPerRun ?? DEFAULT_MAX_PRACTICE_PER_RUN;\n\n const practiceTags = [...cardsByTag.keys()].filter(\n (tag) =>\n patterns.some((p) => matchesTagPattern(tag, p)) &&\n this.isUnlockedGatedSkill(tag, hierarchyConfigs, userTagElo, userGlobalElo) &&\n (userTagElo[tag]?.count ?? 0) < practiceMinCount\n );\n\n if (practiceTags.length === 0) return { cards: [], debts: [] };\n\n // Carry forward (or open) each under-practiced skill's debt age, and derive\n // its practice multiplier: base + staleness-since-first-owed, clamped. Done\n // for every under-practiced tag (not just emitted ones) so the debt clock\n // keeps running even on runs where the cap or de-dup emits nothing.\n const now = Date.now();\n const DAY_MS = 24 * 60 * 60 * 1000;\n const tagMultiplier = new Map<string, number>();\n for (const tag of practiceTags) {\n const firstOwedAt = priorPracticeDebt[tag] ?? isoNow();\n nextPracticeDebt[tag] = firstOwedAt;\n const staleDays = Math.max(0, (now - new Date(firstOwedAt).getTime()) / DAY_MS);\n const mult = clamp(\n PRACTICE_BASE_MULT + staleDays * PRACTICE_STALENESS_BUMP_PER_DAY,\n PRACTICE_BASE_MULT,\n MAX_PRACTICE_MULTIPLIER\n );\n tagMultiplier.set(tag, mult);\n }\n\n // Debug view of every open debt (built before the emission early-return so\n // the pressure channel sees debts even on runs that emit no drill cards).\n const debts: PracticeDebtDebug[] = practiceTags\n .map((tag) => ({\n tag,\n multiplier: tagMultiplier.get(tag) ?? PRACTICE_BASE_MULT,\n firstOwedAt: nextPracticeDebt[tag],\n }))\n .sort((a, b) => b.multiplier - a.multiplier || a.tag.localeCompare(b.tag));\n\n // Reuse the diversity-aware tag→cards collector (stem-dedup + shuffle).\n const practiceCardIds = this.findDiscoveredSupportCards({\n supportTags: practiceTags,\n cardsByTag,\n activeIds,\n seenIds,\n excludedIds: emittedIds,\n limit: maxPractice,\n });\n\n if (practiceCardIds.length === 0) return { cards: [], debts };\n\n logger.info(\n `[Prescribed] Group '${group.id}' practice: ${practiceTags.length} unlocked under-practiced ` +\n `skill(s), emitting ${practiceCardIds.length} drill card(s)`\n );\n\n const cards: WeightedCard[] = [];\n for (const cardId of practiceCardIds) {\n emittedIds.add(cardId);\n // Most-stale wins: a card may carry several practice tags; take the\n // highest debt multiplier among the ones it serves.\n let mult = PRACTICE_BASE_MULT;\n for (const tag of practiceTags) {\n if ((cardsByTag.get(tag)?.includes(cardId) ?? false)) {\n mult = Math.max(mult, tagMultiplier.get(tag) ?? PRACTICE_BASE_MULT);\n }\n }\n const score = BASE_PRACTICE_SCORE * mult;\n cards.push({\n cardId,\n courseId,\n score,\n provenance: [\n {\n strategy: 'prescribed',\n strategyName: this.strategyName || this.name,\n strategyId: this.strategyId || 'NAVIGATION_STRATEGY-prescribed',\n action: 'generated' as const,\n score,\n reason:\n `mode=practice;group=${group.id};debtMult=×${mult.toFixed(2)};` +\n `underPracticedSkills=${practiceTags.length};` +\n `practiceTags=${practiceTags.slice(0, 8).join('|')}${practiceTags.length > 8 ? '|…' : ''};` +\n `testversion=${PRESCRIBED_DEBUG_VERSION}`,\n },\n ],\n });\n }\n\n return { cards, debts };\n }\n\n /**\n * True for a skill that was *gated and is now reached*: it has at least one\n * declared hierarchy prerequisite set, and every set is fully satisfied by the\n * learner's per-tag ELO. This deliberately EXCLUDES tags with no prerequisites\n * — an ungated tag was never \"introduced\" in the curricular sense, so it isn't\n * a post-intro drill target (e.g. whole-word spelling tags that share the\n * `gpc:exercise:*` prefix but have no intro gate). Those are left to normal\n * ELO retrieval. This is the precise population the retrieval gap strands:\n * just-unlocked, low-ELO skills.\n */\n private isUnlockedGatedSkill(\n tag: string,\n hierarchyConfigs: HierarchyConfig[],\n userTagElo: Record<string, { score: number; count: number }>,\n userGlobalElo: number\n ): boolean {\n const prereqSets = hierarchyConfigs\n .map((hierarchy) => hierarchy.prerequisites[tag])\n .filter((prereqs): prereqs is TagPrerequisite[] => Array.isArray(prereqs) && prereqs.length > 0);\n\n if (prereqSets.length === 0) return false;\n\n return prereqSets.every((prereqs) =>\n prereqs.every((pr) => this.isPrerequisiteMet(pr, userTagElo[pr.tag], userGlobalElo))\n );\n }\n\n private findSupportCardsByTags(\n group: PrescribedGroupConfig,\n tagsByCard: Map<string, string[]>,\n supportTags: string[]\n ): string[] {\n if (supportTags.length === 0) {\n return [];\n }\n\n const explicitSupportIds = group.supportCardIds ?? [];\n const explicitPatterns = group.supportTagPatterns ?? [];\n if (explicitSupportIds.length === 0 && explicitPatterns.length === 0) {\n return [];\n }\n\n const candidates = new Set<string>();\n\n for (const cardId of explicitSupportIds) {\n const cardTags = tagsByCard.get(cardId) ?? [];\n const matchesResolved = supportTags.some((supportTag) => cardTags.includes(supportTag));\n const matchesPattern = explicitPatterns.some((pattern) =>\n cardTags.some((tag) => matchesTagPattern(tag, pattern))\n );\n\n if (matchesResolved || matchesPattern) {\n candidates.add(cardId);\n }\n }\n\n return [...candidates];\n }\n\n private findDiscoveredSupportCards(args: {\n supportTags: string[];\n cardsByTag: Map<string, string[]>;\n activeIds: Set<string>;\n seenIds: Set<string>;\n excludedIds: Set<string>;\n limit: number;\n }): string[] {\n const { supportTags, cardsByTag, activeIds, seenIds, excludedIds, limit } = args;\n\n const byCardId = new Map<string, { cardId: string; matches: number }>();\n\n for (const supportTag of supportTags) {\n const taggedCards = cardsByTag.get(supportTag) ?? [];\n for (const cardId of taggedCards) {\n if (activeIds.has(cardId) || seenIds.has(cardId) || excludedIds.has(cardId)) {\n continue;\n }\n const existing = byCardId.get(cardId);\n if (existing) {\n existing.matches += 1;\n } else {\n byCardId.set(cardId, { cardId, matches: 1 });\n }\n }\n }\n\n const candidates = [...byCardId.values()]\n .sort((a, b) => b.matches - a.matches || a.cardId.localeCompare(b.cardId));\n\n // Diversify by word stem — avoid returning 4 variants of \"year\".\n // ML cards follow c-ml-{word}-{blanks}, so the stem is everything before\n // the last dash-delimited segment of digits/commas.\n const usedStems = new Set<string>();\n const diverse: typeof candidates = [];\n const deferred: typeof candidates = [];\n\n for (const entry of candidates) {\n const stem = extractWordStem(entry.cardId);\n if (!usedStems.has(stem)) {\n usedStems.add(stem);\n diverse.push(entry);\n } else {\n deferred.push(entry);\n }\n }\n\n // Combine diverse-first, then deferred for overflow, and shuffle within\n // each tier so we don't always pick the same card for a given word.\n shuffleInPlace(diverse);\n shuffleInPlace(deferred);\n\n return [...diverse, ...deferred]\n .slice(0, limit)\n .map((entry) => entry.cardId);\n }\n\n private resolveBlockedSupportTags(\n targetTags: string[],\n hierarchyConfigs: HierarchyConfig[],\n userTagElo: Record<string, { score: number; count: number }>,\n userGlobalElo: number,\n hierarchyWalkEnabled: boolean,\n maxDepth: number\n ): { blocked: boolean; supportTags: string[] } {\n const supportTags = new Set<string>();\n let blocked = false;\n\n for (const targetTag of targetTags) {\n const prereqSets = hierarchyConfigs\n .map((hierarchy) => hierarchy.prerequisites[targetTag])\n .filter((prereqs): prereqs is TagPrerequisite[] => Array.isArray(prereqs) && prereqs.length > 0);\n\n if (prereqSets.length === 0) {\n continue;\n }\n\n const tagBlocked = prereqSets.some((prereqs) =>\n prereqs.some((pr) => !this.isPrerequisiteMet(pr, userTagElo[pr.tag], userGlobalElo))\n );\n\n if (!tagBlocked) {\n continue;\n }\n\n blocked = true;\n\n if (!hierarchyWalkEnabled) {\n for (const prereqs of prereqSets) {\n for (const prereq of prereqs) {\n if (!this.isPrerequisiteMet(prereq, userTagElo[prereq.tag], userGlobalElo)) {\n supportTags.add(prereq.tag);\n }\n }\n }\n continue;\n }\n\n for (const prereqs of prereqSets) {\n for (const prereq of prereqs) {\n if (!this.isPrerequisiteMet(prereq, userTagElo[prereq.tag], userGlobalElo)) {\n this.collectSupportTagsRecursive(\n prereq.tag,\n hierarchyConfigs,\n userTagElo,\n userGlobalElo,\n maxDepth,\n new Set<string>(),\n supportTags\n );\n }\n }\n }\n }\n\n return { blocked, supportTags: [...supportTags] };\n }\n\n private collectSupportTagsRecursive(\n tag: string,\n hierarchyConfigs: HierarchyConfig[],\n userTagElo: Record<string, { score: number; count: number }>,\n userGlobalElo: number,\n depth: number,\n visited: Set<string>,\n out: Set<string>\n ): void {\n if (depth < 0 || visited.has(tag)) return;\n\n visited.add(tag);\n\n let walkedFurther = false;\n\n for (const hierarchy of hierarchyConfigs) {\n const prereqs = hierarchy.prerequisites[tag];\n if (!prereqs || prereqs.length === 0) continue;\n\n const unmet = prereqs.filter(\n (pr) => !this.isPrerequisiteMet(pr, userTagElo[pr.tag], userGlobalElo)\n );\n\n if (unmet.length > 0 && depth > 0) {\n walkedFurther = true;\n for (const prereq of unmet) {\n this.collectSupportTagsRecursive(\n prereq.tag,\n hierarchyConfigs,\n userTagElo,\n userGlobalElo,\n depth - 1,\n visited,\n out\n );\n }\n }\n }\n\n if (!walkedFurther) {\n out.add(tag);\n }\n }\n\n\n\n private isPrerequisiteMet(\n prereq: TagPrerequisite,\n userTagElo: { score: number; count: number } | undefined,\n userGlobalElo: number\n ): boolean {\n if (!userTagElo) return false;\n\n const minCount = prereq.masteryThreshold?.minCount ?? DEFAULT_MIN_COUNT;\n if (userTagElo.count < minCount) return false;\n\n if (prereq.masteryThreshold?.minElo !== undefined) {\n return userTagElo.score >= prereq.masteryThreshold.minElo;\n }\n if (prereq.masteryThreshold?.minCount !== undefined) {\n return true;\n }\n\n return userTagElo.score >= userGlobalElo;\n }\n}"],"mappings":";;;;;;AAuJA,MAAM,2BAA2B;AACjC,MAAM,6BAA6B;AACnC,MAAM,8BAA8B;AACpC,MAAM,0BAA0B;AAChC,MAAM,oBAAoB;AAC1B,MAAM,6BAA6B;AACnC,MAAM,+BAA+B;AACrC,MAAM,oBAAoB;AAC1B,MAAM,qBAAqB;AAC3B,MAAM,2BAA2B;AAUjC,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;AAC3B,MAAM,0BAA0B;AAEhC,MAAM,kCAAkC;AACxC,MAAM,wBAAwB;AAC9B,MAAM,yBAAyB;AAE/B,MAAM,2BAA2B;AAEjC,SAAS,OAAU,KAAe;AAChC,QAAO,CAAC,GAAG,IAAI,IAAI,IAAI,CAAC;;AAG1B,SAAS,SAAiB;AACxB,yBAAO,IAAI,MAAM,EAAC,aAAa;;AAGjC,SAAS,MAAM,OAAe,KAAa,KAAqB;AAC9D,QAAO,KAAK,IAAI,KAAK,KAAK,IAAI,KAAK,MAAM,CAAC;;AAG5C,SAAS,kBAAkB,KAAa,SAA0B;AAChE,KAAI,YAAY,IAAK,QAAO;CAC5B,MAAM,UAAU,QACb,Q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AAO;AAExC,MAAI,OAAO,kBAAkB,WAAW,KAAA,EACtC,QAAO,WAAW,SAAS,OAAO,iBAAiB;AAErD,MAAI,OAAO,kBAAkB,aAAa,KAAA,EACxC,QAAO;AAGT,SAAO,WAAW,SAAS"}
@@ -1,7 +1,7 @@
1
1
  import "../_virtual/_rolldown/runtime.mjs";
2
2
  //#region src/core/versionStamps.ts
3
3
  /** This build's @vue-skuilder/db version, set at build time; `'dev'` when run from source. */
4
- const FRAMEWORK_VERSION = "0.2.36";
4
+ const FRAMEWORK_VERSION = "0.3.0";
5
5
  let hostAppVersion;
6
6
  /** Record the host app's version (the data layer's `appVersion` option). */
7
7
  function setAppVersion(version) {
@@ -1,4 +1,4 @@
1
- import { U as UserDBInterface, C as CourseDBInterface, a as CoursesDBInterface } from './contentSource-D_E7JaxR.js';
1
+ import { U as UserDBInterface, C as CourseDBInterface, a as CoursesDBInterface } from './contentSource-2zVmcjKA.js';
2
2
  import { C as ClassroomDBInterface, A as AdminDBInterface } from './classroomDB-DLTtLZct.js';
3
3
 
4
4
  /**
@@ -1,6 +1,6 @@
1
- import { C as CardData, b as DisplayableData, a as Tag, c as CardRecord, d as QuestionRecord, e as CardHistory } from '../types-legacy-fT5Y1Wuy.js';
2
- import { c as ContentNavigationStrategyData, e as StudySessionDoc, f as ScheduledCard, g as CourseRegistrationDoc, h as SessionStateSnapshot, i as StudySessionRunSummary, j as RegulatorReading, k as StudySessionRunCard, F as FilterKind, l as RegulatorName } from '../contentSource-D_E7JaxR.js';
3
- export { m as SessionEloEvent, n as StudySessionRunCardTrail } from '../contentSource-D_E7JaxR.js';
1
+ import { C as CardData, b as DisplayableData, a as Tag, c as CardRecord, d as QuestionRecord, e as CardHistory } from '../types-legacy-DdVjg81H.js';
2
+ import { c as ContentNavigationStrategyData, e as StudySessionDoc, f as ScheduledCard, g as CourseRegistrationDoc, h as SessionStateSnapshot, i as StudySessionRunSummary, j as RegulatorReading, k as StudySessionRunCard, F as FilterKind, l as RegulatorName } from '../contentSource-2zVmcjKA.js';
3
+ export { m as SessionEloEvent, n as StudySessionRunCardTrail } from '../contentSource-2zVmcjKA.js';
4
4
  import { TagRole, TagPresentation, EloRank, CourseElo } from '@vue-skuilder/common';
5
5
  import 'moment';
6
6
 
@@ -233,6 +233,18 @@ Currently logged-in as ${this._username}.`);
233
233
  update(id, update) {
234
234
  return this.updateQueue.update(id, update);
235
235
  }
236
+ /**
237
+ * Create a default doc after a 404. Concurrent first reads (e.g. two
238
+ * components on a brand-new user) both see the 404 and both create; the
239
+ * loser's conflict just means the doc now exists, which is what it wanted.
240
+ */
241
+ async putDefaultUnlessCreated(doc) {
242
+ try {
243
+ await this.localDB.put(doc);
244
+ } catch (e) {
245
+ if (e.status !== 409) throw e;
246
+ }
247
+ }
236
248
  async getCourseRegistrationsDoc() {
237
249
  logger.debug(`Fetching courseRegistrations for ${this.getUsername()}`);
238
250
  let ret;
@@ -241,7 +253,7 @@ Currently logged-in as ${this._username}.`);
241
253
  } catch (e) {
242
254
  if (e.status === 404) {
243
255
  if (!this.canMaterializeDefaults()) throw new Error(`Cannot read course registrations for ${this._username}: the local mirror is unavailable (hydration state '${this._hydration.state}'). Refusing to create an empty registration doc — that would report an existing user as unregistered, and then lose to their real document once sync resumes.`);
244
- await this.localDB.put({
256
+ await this.putDefaultUnlessCreated({
245
257
  _id: BaseUser.DOC_IDS.COURSE_REGISTRATIONS,
246
258
  courses: [],
247
259
  studyWeight: {}
@@ -434,7 +446,7 @@ Currently logged-in as ${this._username}.`);
434
446
  const err = e;
435
447
  if (err.name && err.name === "not_found") {
436
448
  if (!this.canMaterializeDefaults()) throw new Error(`Cannot read config for ${this._username}: the local mirror is unavailable (hydration state '${this._hydration.state}'). Refusing to write a default config over what may be an existing one.`);
437
- await this.localDB.put(defaultConfig);
449
+ await this.putDefaultUnlessCreated(defaultConfig);
438
450
  return this.getConfig();
439
451
  } else {
440
452
  logger.error(`Error setting user default config:`, e);
@@ -664,25 +676,29 @@ Currently logged-in as ${this._username}.`);
664
676
  async putCardRecord(record) {
665
677
  const cardHistoryID = getCardHistoryID(record.courseID, record.cardID);
666
678
  record.timeStamp = moment.utc(record.timeStamp).toString();
667
- try {
668
- const cardHistory = await this.update(cardHistoryID, function(h) {
669
- h.records.push(record);
670
- h.bestInterval = h.bestInterval || 0;
671
- if (areQuestionRecords(h)) {
672
- h.lapses = getLapses(h.records);
673
- h.streak = getStreak(h.records);
674
- } else {
675
- h.lapses = h.lapses || 0;
676
- h.streak = h.streak || 0;
677
- }
678
- return h;
679
- });
679
+ const append = (h) => {
680
+ h.records.push(record);
681
+ h.bestInterval = h.bestInterval || 0;
682
+ if (areQuestionRecords(h)) {
683
+ h.lapses = getLapses(h.records);
684
+ h.streak = getStreak(h.records);
685
+ } else {
686
+ h.lapses = h.lapses || 0;
687
+ h.streak = h.streak || 0;
688
+ }
689
+ return h;
690
+ };
691
+ const appendToExisting = async () => {
692
+ const cardHistory = await this.update(cardHistoryID, append);
680
693
  cardHistory.records = cardHistory.records.map((record) => {
681
694
  const ret = { ...record };
682
695
  ret.timeStamp = moment.utc(record.timeStamp);
683
696
  return ret;
684
697
  });
685
698
  return cardHistory;
699
+ };
700
+ try {
701
+ return await appendToExisting();
686
702
  } catch (e) {
687
703
  const reason = e;
688
704
  if (reason.status === 404) try {
@@ -701,6 +717,7 @@ Currently logged-in as ${this._username}.`);
701
717
  _rev: putResult.rev
702
718
  };
703
719
  } catch (creationError) {
720
+ if (creationError.name === "conflict") return appendToExisting();
704
721
  throw new Error(`Failed to create CardHistory for ${cardHistoryID}. Reason: ${creationError}`);
705
722
  }
706
723
  else throw new Error(`putCardRecord failed because of: