@vue-skuilder/db 0.3.1 → 0.3.2
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.
- package/dist/{contentSource-2zVmcjKA.d.ts → contentSource-CSI0pJ2D.d.ts} +10 -0
- package/dist/core/index.cjs +62 -14
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.ts +3 -3
- package/dist/core/interfaces/contentSource.mjs.map +1 -1
- package/dist/core/navigators/Pipeline.mjs +7 -1
- package/dist/core/navigators/Pipeline.mjs.map +1 -1
- package/dist/core/navigators/filters/eloDistance.mjs +17 -2
- package/dist/core/navigators/filters/eloDistance.mjs.map +1 -1
- package/dist/core/navigators/generators/prescribed.mjs +20 -10
- package/dist/core/navigators/generators/prescribed.mjs.map +1 -1
- package/dist/core/navigators/index.mjs +2 -0
- package/dist/core/navigators/index.mjs.map +1 -1
- package/dist/core/versionStamps.mjs +1 -1
- package/dist/{dataLayerProvider-rGyLQ93v.d.ts → dataLayerProvider-D5n1gGc_.d.ts} +1 -1
- package/dist/diagnostics/index.d.ts +2 -2
- package/dist/impl/couch/courseDB.mjs +5 -0
- package/dist/impl/couch/courseDB.mjs.map +1 -1
- package/dist/impl/couch/index.cjs +37 -2
- package/dist/impl/couch/index.cjs.map +1 -1
- package/dist/impl/couch/index.d.ts +4 -2
- package/dist/impl/static/courseDB.mjs +5 -0
- package/dist/impl/static/courseDB.mjs.map +1 -1
- package/dist/impl/static/index.cjs +37 -2
- package/dist/impl/static/index.cjs.map +1 -1
- package/dist/impl/static/index.d.ts +4 -2
- package/dist/index.cjs +73 -15
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/study/SessionController.mjs +1 -0
- package/dist/study/SessionController.mjs.map +1 -1
- package/package.json +3 -3
- package/src/core/interfaces/contentSource.ts +7 -0
- package/src/core/navigators/Pipeline.ts +7 -0
- package/src/core/navigators/filters/eloDistance.ts +31 -2
- package/src/core/navigators/generators/prescribed.ts +56 -11
- package/src/core/navigators/generators/types.ts +3 -0
- package/src/core/navigators/index.ts +5 -0
- package/src/impl/couch/courseDB.ts +13 -0
- package/src/impl/static/courseDB.ts +13 -0
- package/src/study/SessionController.ts +3 -0
- package/tests/core/navigators/eloDistanceFilter.test.ts +15 -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 * 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;AACh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AAO,kBAAkB,YAAY;AACtD,MAAI,WAAW,QAAQ,SAAU,QAAO;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// KNOWN LATENT BUG (2026-11-17): this generator decides targets, support,\n// boost hints and pressure *before* the gates run, and knows nothing about\n// them. It will target and support cards a gate is certain to block (LP:\n// intro-core's ck-K / wh-W and their doubled-consonant support, behind a\n// deferred lesson, cut to ~x0.002). Harmless while every such card stays\n// gated; but staleness escalates the support boost hint to x4 on those tags,\n// so the day one becomes ungated it gets that boost at once (a pressure\n// mania). Proposed fix: Pipeline offers generators the gate-kind filters\n// (e.g. `context.gate(cardIds)`), and prescribed treats gated candidates as\n// blocked: not emitted, not boosted, not escalating. That would also replace\n// this file's own hierarchy walk. LP tracking: agent/curriculum-log/concerns.md\n// (Watch: \"Prescribed targets gated cards\").\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 * The study session of the last run. `sessionsSinceSurfaced` advances once\n * per new session, not once per run (a session replans several times).\n * Absent when the caller set no session id; then each run counts.\n */\n lastSessionId?: 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 sessionId = context?.sessionId;\n // A run with no session id counts as its own session (the old behaviour).\n const newSession = sessionId === undefined || sessionId !== progress.lastSessionId;\n const nextState: PrescribedProgressState = {\n updatedAt: isoNow(),\n groups: {},\n ...(sessionId || progress.lastSessionId\n ? { lastSessionId: sessionId ?? progress.lastSessionId }\n : {}),\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(\n runtime,\n progress.groups[group.id],\n newSession\n );\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 // Emission is not surfacing. A card emitted here can still lose to the rest\n // of the heap and never be shown, so it does not reset the staleness clock;\n // only a target reaching the learner does (buildNextGroupState). Support\n // emission is still recorded, as bookkeeping.\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.supportIds.length > 0) {\n groupState.lastSupportAt = isoNow();\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 /**\n * The group's state after this run. The staleness clock resets only when a\n * target has reached the learner since the last run: it is newly in\n * `encounteredTargets`, which reads card history and scheduled reviews, so\n * the card was shown and answered. Emitting a target does not count; it may\n * lose to the rest of the heap. (Before 2026-11, emission reset the clock,\n * and a group that emitted every run never escalated.) The clock advances\n * once per study session, not per run.\n */\n private buildNextGroupState(\n runtime: GroupRuntimeState,\n prior: GroupCardState | undefined,\n newSession: boolean\n ): GroupCardState {\n const carriedSessions = prior?.sessionsSinceSurfaced ?? 0;\n const previouslyEncountered = new Set(prior?.encounteredCardIds ?? []);\n const surfacedThisRun =\n prior !== undefined &&\n [...runtime.encounteredTargets].some((id) => !previouslyEncountered.has(id));\n\n return {\n encounteredCardIds: [...runtime.encounteredTargets].sort(),\n pendingTargetIds: [...runtime.pendingTargets].sort(),\n lastSurfacedAt: surfacedThisRun ? isoNow() : (prior?.lastSurfacedAt ?? null),\n sessionsSinceSurfaced: surfacedThisRun ? 0 : carriedSessions + (newSession ? 1 : 0),\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":";;;;;;AA0KA,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,QAAQ,qBAAqB,OAAO,CACpC,QAAQ,OAAO,KAAK;AAEvB,QADW,IAAI,OAAO,IAAI,QAAQ,GAAG,CAC3B,KAAK,IAAI;;;;;;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ACH,KAAI,IAAI,IAAI;;CAMhB,kBACE,QACA,YACA,eACS;AACT,MAAI,CAAC,WAAY,QAAO;EAExB,MAAM,WAAW,OAAO,kBAAkB,YAAY;AACtD,MAAI,WAAW,QAAQ,SAAU,QAAO;AAExC,MAAI,OAAO,kBAAkB,WAAW,KAAA,EACtC,QAAO,WAAW,SAAS,OAAO,iBAAiB;AAErD,MAAI,OAAO,kBAAkB,aAAa,KAAA,EACxC,QAAO;AAGT,SAAO,WAAW,SAAS"}
|
|
@@ -338,6 +338,8 @@ var ContentNavigator = class {
|
|
|
338
338
|
* No-op for non-Pipeline navigators. Pipeline overrides this.
|
|
339
339
|
*/
|
|
340
340
|
setEphemeralHints(_hints) {}
|
|
341
|
+
/** See StudyContentSource.setSessionId. No-op for non-Pipeline navigators. */
|
|
342
|
+
setSessionId(_sessionId) {}
|
|
341
343
|
};
|
|
342
344
|
//#endregion
|
|
343
345
|
export { ContentNavigator, NavigatorRole, NavigatorRoles, Navigators, getCardOrigin, getRegisteredFilterKind, getRegisteredNavigator, getRegisteredNavigatorNames, getRegisteredNavigatorRole, hasRegisteredNavigator, initializeNavigatorRegistry, isFilter, isGenerator, registerNavigator };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/core/navigators/index.ts"],"sourcesContent":["import { StudyContentSource, UserDBInterface, CourseDBInterface } from '..';\nimport type { FilterKind } from './filters/types';\n\n// Re-export filter types\nexport type { CardFilter, FilterContext, CardFilterFactory, FilterKind } from './filters/types';\n\n// Re-export generator types\nexport type { CardGenerator, GeneratorContext, CardGeneratorFactory, GeneratorResult, ReplanHints } from './generators/types';\n\n// Re-export the diversity re-rank stage (pipeline stage 3)\nexport {\n diversityRerank,\n DIVERSITY_STRENGTH,\n DIVERSITY_FLOOR,\n type DiversityRerankOptions,\n} from './diversityRerank';\nimport type { GeneratorResult, ReplanHints } from './generators/types';\n\n// Re-export pipeline debugger API\nexport {\n pipelineDebugAPI,\n mountPipelineDebugger,\n getActivePipeline,\n setDebugSessionId,\n getRunsForSession,\n drainCapturedRuns,\n type PipelineRunReport,\n type RunReportCard,\n type GeneratorSummary,\n type FilterImpact,\n} from './PipelineDebugger';\n\n// Re-export the commit-free forecast capability surface.\nexport type { PipelineForecaster } from './Pipeline';\nexport {\n getSrsBacklogDebug,\n clearSrsBacklogDebug,\n type SrsBacklogDebug,\n} from './SrsDebugger';\n\n// Re-export the generic strategy-pressure debug channel. `captureStrategyPressure`\n// is part of the consumer surface: client-defined strategies (registered via\n// registerNavigator) push their backpressure state through it for the live\n// session overlay.\nexport {\n captureStrategyPressure,\n getStrategyPressureDebug,\n clearStrategyPressureDebug,\n type StrategyPressureDebug,\n type PressureGaugeDebug,\n} from './StrategyPressureDebugger';\n\nimport { LearnableWeight } from '../types/contentNavigationStrategy';\nexport type { ContentNavigationStrategyData, LearnableWeight } from '../types/contentNavigationStrategy';\nimport type { ContentNavigationStrategyData } from '../types/contentNavigationStrategy';\nimport { logger } from '../../util/logger';\n\n// ============================================================================\n// NAVIGATOR REGISTRY\n// ============================================================================\n//\n// Static registry of navigator implementations. This allows ContentNavigator.create()\n// to instantiate navigators without relying on dynamic imports, which don't work\n// reliably in all environments (e.g., test runners, bundled code).\n//\n// Usage:\n// 1. Import your navigator class\n// 2. Call registerNavigator('implementingClass', YourNavigatorClass)\n// 3. ContentNavigator.create() will use the registry before falling back to\n// dynamic import\n//\n// ============================================================================\n\n/**\n * Type for navigator constructor functions.\n */\nexport type NavigatorConstructor = new (\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n) => ContentNavigator;\n\n/**\n * Entry in the navigator registry, storing the constructor and an optional\n * pipeline role. The role is used by PipelineAssembler to classify\n * consumer-registered navigators that aren't in the built-in Navigators enum.\n */\ninterface NavigatorRegistryEntry {\n constructor: NavigatorConstructor;\n role?: NavigatorRole;\n}\n\n/**\n * Registry mapping implementingClass names to navigator entries.\n * Populated by registerNavigator() and used by ContentNavigator.create().\n */\nconst navigatorRegistry = new Map<string, NavigatorRegistryEntry>();\n\n/**\n * Register a navigator implementation.\n *\n * Call this to make a navigator available for instantiation by\n * ContentNavigator.create() without relying on dynamic imports.\n *\n * Passing a `role` is optional for built-in navigators (whose roles are in\n * the hardcoded `NavigatorRoles` record), but **required** for consumer-\n * defined navigators that need to participate in pipeline assembly.\n *\n * @param implementingClass - The class name (e.g., 'elo', 'letterGatingFilter')\n * @param constructor - The navigator class constructor\n * @param role - Optional pipeline role (GENERATOR or FILTER)\n */\nexport function registerNavigator(\n implementingClass: string,\n constructor: NavigatorConstructor,\n role?: NavigatorRole\n): void {\n navigatorRegistry.set(implementingClass, { constructor, role });\n logger.debug(`[NavigatorRegistry] Registered: ${implementingClass}${role ? ` (${role})` : ''}`);\n}\n\n/**\n * Get a navigator constructor from the registry.\n *\n * @param implementingClass - The class name to look up\n * @returns The constructor, or undefined if not registered\n */\nexport function getRegisteredNavigator(implementingClass: string): NavigatorConstructor | undefined {\n return navigatorRegistry.get(implementingClass)?.constructor;\n}\n\n/**\n * Check if a navigator is registered.\n *\n * @param implementingClass - The class name to check\n * @returns true if registered, false otherwise\n */\nexport function hasRegisteredNavigator(implementingClass: string): boolean {\n return navigatorRegistry.has(implementingClass);\n}\n\n/**\n * Get the registered role for a navigator, if one was provided at registration.\n *\n * @param implementingClass - The class name to look up\n * @returns The role, or undefined if not registered or no role was specified\n */\nexport function getRegisteredNavigatorRole(implementingClass: string): NavigatorRole | undefined {\n return navigatorRegistry.get(implementingClass)?.role;\n}\n\n/**\n * A registered filter's declared kind (see `CardFilter.kind`): the static\n * `kind` on its class. Undefined if unregistered or undeclared; undeclared\n * filters count as gates at run time.\n * @param implementingClass - The class name to look up\n */\nexport function getRegisteredFilterKind(implementingClass: string): FilterKind | undefined {\n const ctor = navigatorRegistry.get(implementingClass)?.constructor as\n | { kind?: FilterKind }\n | undefined;\n return ctor?.kind;\n}\n\n/**\n * Get all registered navigator names.\n * Useful for debugging and testing.\n */\nexport function getRegisteredNavigatorNames(): string[] {\n return Array.from(navigatorRegistry.keys());\n}\n\n/**\n * Initialize the navigator registry with all built-in navigators.\n *\n * This function dynamically imports all standard navigator implementations\n * and registers them. Call this once at application startup to ensure\n * all navigators are available.\n *\n * In test environments, this may need to be called explicitly before\n * using ContentNavigator.create().\n */\nexport async function initializeNavigatorRegistry(): Promise<void> {\n logger.debug('[NavigatorRegistry] Initializing built-in navigators...');\n\n // Import and register generators\n const [eloModule, srsModule] = await Promise.all([\n import('./generators/elo'),\n import('./generators/srs'),\n ]);\n const prescribedModule = await import('./generators/prescribed');\n registerNavigator('elo', eloModule.default);\n registerNavigator('srs', srsModule.default);\n registerNavigator('prescribed', prescribedModule.default);\n\n // Import and register filters\n const [\n hierarchyModule,\n interferenceModule,\n relativePriorityModule,\n userTagPreferenceModule,\n eloDistanceModule,\n ] = await Promise.all([\n import('./filters/hierarchyDefinition'),\n import('./filters/interferenceMitigator'),\n import('./filters/relativePriority'),\n import('./filters/userTagPreference'),\n import('./filters/eloDistance'),\n ]);\n registerNavigator('hierarchyDefinition', hierarchyModule.default);\n registerNavigator('interferenceMitigator', interferenceModule.default);\n registerNavigator('relativePriority', relativePriorityModule.default);\n registerNavigator('userTagPreference', userTagPreferenceModule.default);\n registerNavigator('eloDistance', eloDistanceModule.default);\n\n logger.debug(\n `[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(', ')}`\n );\n}\n\n// ============================================================================\n// NAVIGATION STRATEGY API\n// ============================================================================\n//\n// This module defines the ContentNavigator base class and the WeightedCard type,\n// which form the foundation of the pluggable navigation strategy system.\n//\n// KEY CONCEPTS:\n//\n// 1. WeightedCard - A card with a suitability score (0-1) and provenance trail.\n// The provenance tracks how each strategy in the pipeline contributed to\n// the card's final score, ensuring transparency and debuggability.\n//\n// 2. ContentNavigator - Abstract base class for backward compatibility.\n// New code should use CardGenerator or CardFilter interfaces directly.\n//\n// 3. CardGenerator vs CardFilter:\n// - Generators (ELO, SRS) produce candidate cards with scores\n// - Filters (Hierarchy, Interference, Priority, EloDistance) transform scores\n//\n// 4. Pipeline architecture:\n// Pipeline(generator, [filter1, filter2, ...]) executes:\n// cards = generator.getWeightedCards()\n// cards = filter1.transform(cards, context)\n// cards = filter2.transform(cards, context)\n// return sorted(cards)\n//\n// 5. Provenance tracking - Each strategy adds an entry explaining its contribution.\n// This makes the system transparent and debuggable.\n//\n// ============================================================================\n\n/**\n * Tracks a single strategy's contribution to a card's final score.\n *\n * Each strategy in the pipeline adds a StrategyContribution entry to the\n * card's provenance array, creating an audit trail of scoring decisions.\n */\nexport interface StrategyContribution {\n /**\n * Strategy type (implementing class name).\n * Examples: 'elo', 'hierarchyDefinition', 'interferenceMitigator'\n */\n strategy: string;\n\n /**\n * Human-readable name identifying this specific strategy instance.\n * Extracted from ContentNavigationStrategyData.name.\n * Courses may have multiple instances of the same strategy type with\n * different configurations.\n *\n * Examples:\n * - \"ELO (default)\"\n * - \"Interference: b/d/p confusion\"\n * - \"Interference: phonetic confusables\"\n * - \"Priority: Common letters first\"\n */\n strategyName: string;\n\n /**\n * Unique database document ID for this strategy instance.\n * Extracted from ContentNavigationStrategyData._id.\n * Use this to fetch the full strategy configuration document.\n *\n * Examples:\n * - \"NAVIGATION_STRATEGY-ELO-default\"\n * - \"NAVIGATION_STRATEGY-interference-bdp\"\n * - \"NAVIGATION_STRATEGY-priority-common-letters\"\n */\n strategyId: string;\n\n /**\n * What the strategy did:\n * - 'generated': Strategy produced this card (generators only)\n * - 'passed': Strategy evaluated but didn't change score (transparent pass-through)\n * - 'boosted': Strategy increased the score\n * - 'penalized': Strategy decreased the score\n */\n action: 'generated' | 'passed' | 'boosted' | 'penalized';\n\n /** Score after this strategy's processing */\n score: number;\n\n /**\n * The effective weight applied for this strategy instance.\n * If using evolutionary orchestration, this includes deviation.\n * If omitted, implies weight 1.0 (legacy behavior).\n */\n effectiveWeight?: number;\n\n /**\n * The deviation factor applied to this user's cohort for this strategy.\n * Range [-1.0, 1.0].\n */\n deviation?: number;\n\n /**\n * Human-readable explanation of the strategy's decision.\n *\n * Examples:\n * - \"ELO distance 75, new card\"\n * - \"Prerequisites met: letter-sounds\"\n * - \"Interferes with immature tag 'd' (decay 0.8)\"\n * - \"High-priority tag 's' (0.95) → boost 1.15x\"\n *\n * Required for transparency - silent adjusters are anti-patterns.\n */\n reason: string;\n}\n\n/**\n * A card with a suitability score and provenance trail.\n *\n * Scores range from 0-1:\n * - 1.0 = fully suitable\n * - 0.0 = hard filter (e.g., prerequisite not met)\n * - 0.5 = neutral\n * - Intermediate values = soft preference\n *\n * Provenance tracks the scoring pipeline:\n * - First entry: Generator that produced the card\n * - Subsequent entries: Filters that transformed the score\n * - Each entry includes action and human-readable reason\n */\nexport interface WeightedCard {\n cardId: string;\n courseId: string;\n /** Suitability score from 0-1 */\n score: number;\n /**\n * Audit trail of strategy contributions.\n * First entry is from the generator, subsequent entries from filters.\n */\n provenance: StrategyContribution[];\n /**\n * Pre-fetched tags. Populated by Pipeline before filters run.\n * Filters should use this instead of querying getAppliedTags() individually.\n */\n tags?: string[];\n /**\n * Review document ID (_id from ScheduledCard).\n * Present when this card originated from SRS review scheduling.\n * Used by SessionController to track review outcomes and maintain review state.\n */\n reviewID?: string;\n /**\n * The card's global ELO, when the generator already knows it (the ELO\n * generator reads it during retrieval). Lets the ELO distance filter skip a\n * fetch.\n */\n cardElo?: number;\n /**\n * A review's SRS urgency in [0, 1] (overdueness and interval recency), set by\n * the SRS generator. The review-mass regulator weighs the backlog by it.\n */\n reviewUrgency?: number;\n}\n\n/**\n * Extract card origin from provenance trail.\n *\n * The first provenance entry (from the generator) indicates whether\n * this is a new card, review, or failed card. We parse the reason\n * string to extract this information.\n *\n * @param card - Card with provenance trail\n * @returns Card origin ('new', 'review', or 'failed')\n */\nexport function getCardOrigin(card: WeightedCard): 'new' | 'review' | 'failed' {\n if (card.provenance.length === 0) {\n throw new Error('Card has no provenance - cannot determine origin');\n }\n\n const firstEntry = card.provenance[0];\n const reason = firstEntry.reason.toLowerCase();\n\n if (reason.includes('failed')) {\n return 'failed';\n }\n if (reason.includes('review')) {\n return 'review';\n }\n return 'new';\n}\n\nexport enum Navigators {\n ELO = 'elo',\n SRS = 'srs',\n PRESCRIBED = 'prescribed',\n HIERARCHY = 'hierarchyDefinition',\n INTERFERENCE = 'interferenceMitigator',\n RELATIVE_PRIORITY = 'relativePriority',\n USER_TAG_PREFERENCE = 'userTagPreference',\n ELO_DISTANCE = 'eloDistance',\n}\n\n// ============================================================================\n// NAVIGATOR ROLE CLASSIFICATION\n// ============================================================================\n//\n// Navigators are classified as either generators or filters:\n// - Generators: Produce candidate cards (ELO, SRS)\n// - Filters: Transform/score candidates (Hierarchy, Interference, RelativePriority)\n//\n// This classification is used by PipelineAssembler to build pipelines:\n// 1. Instantiate generators (possibly into a CompositeGenerator)\n// 2. Instantiate filters\n// 3. Create Pipeline(generator, filters)\n//\n// ============================================================================\n\n/**\n * Role classification for navigation strategies.\n *\n * - GENERATOR: Produces candidate cards with initial scores\n * - FILTER: Transforms cards with score multipliers\n */\nexport enum NavigatorRole {\n GENERATOR = 'generator',\n FILTER = 'filter',\n}\n\n/**\n * Registry mapping navigator implementations to their roles.\n */\nexport const NavigatorRoles: Record<Navigators, NavigatorRole> = {\n [Navigators.ELO]: NavigatorRole.GENERATOR,\n [Navigators.SRS]: NavigatorRole.GENERATOR,\n [Navigators.PRESCRIBED]: NavigatorRole.GENERATOR,\n [Navigators.HIERARCHY]: NavigatorRole.FILTER,\n [Navigators.INTERFERENCE]: NavigatorRole.FILTER,\n [Navigators.RELATIVE_PRIORITY]: NavigatorRole.FILTER,\n [Navigators.USER_TAG_PREFERENCE]: NavigatorRole.FILTER,\n [Navigators.ELO_DISTANCE]: NavigatorRole.FILTER,\n};\n\n/**\n * Check if a navigator implementation is a generator.\n *\n * @param impl - Navigator implementation name (e.g., 'elo', 'hierarchyDefinition')\n * @returns true if the navigator is a generator, false otherwise\n */\nexport function isGenerator(impl: string): boolean {\n if (NavigatorRoles[impl as Navigators] === NavigatorRole.GENERATOR) return true;\n // Fallback: check the registry for consumer-registered navigators\n return getRegisteredNavigatorRole(impl) === NavigatorRole.GENERATOR;\n}\n\n/**\n * Check if a navigator implementation is a filter.\n *\n * Checks the built-in NavigatorRoles enum first, then falls back to the\n * navigator registry for consumer-registered navigators.\n *\n * @param impl - Navigator implementation name (e.g., 'elo', 'letterGatingFilter')\n * @returns true if the navigator is a filter, false otherwise\n */\nexport function isFilter(impl: string): boolean {\n if (NavigatorRoles[impl as Navigators] === NavigatorRole.FILTER) return true;\n // Fallback: check the registry for consumer-registered navigators\n return getRegisteredNavigatorRole(impl) === NavigatorRole.FILTER;\n}\n\n/**\n * Abstract base class for navigation strategies.\n *\n * This class exists primarily for backward compatibility with legacy code.\n * New code should use CardGenerator or CardFilter interfaces directly.\n *\n * The class implements StudyContentSource for compatibility with SessionController.\n * Once SessionController migrates to use getWeightedCards() exclusively,\n * the legacy methods can be removed.\n */\nexport abstract class ContentNavigator implements StudyContentSource {\n /** User interface for this navigation session */\n protected user: UserDBInterface;\n\n /** Course interface for this navigation session */\n protected course: CourseDBInterface;\n\n /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */\n protected strategyName?: string;\n\n /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */\n protected strategyId?: string;\n\n /** Evolutionary weighting configuration */\n public learnable?: LearnableWeight;\n\n /** Whether to bypass deviation (manual/static weighting) */\n public staticWeight?: boolean;\n\n /**\n * Constructor for standard navigators.\n * Call this from subclass constructors to initialize common fields.\n *\n * Note: CompositeGenerator and Pipeline call super() without args, then set\n * user/course fields directly if needed.\n */\n constructor(\n user?: UserDBInterface,\n course?: CourseDBInterface,\n strategyData?: ContentNavigationStrategyData\n ) {\n this.user = user!;\n this.course = course!;\n if (strategyData) {\n this.strategyName = strategyData.name;\n this.strategyId = strategyData._id;\n this.learnable = strategyData.learnable;\n this.staticWeight = strategyData.staticWeight;\n }\n }\n\n // ============================================================================\n // STRATEGY STATE HELPERS\n // ============================================================================\n //\n // These methods allow strategies to persist their own state (user preferences,\n // learned patterns, temporal tracking) in the user database.\n //\n // ============================================================================\n\n /**\n * Unique key identifying this strategy for state storage.\n *\n * Defaults to the constructor name (e.g., \"UserTagPreferenceFilter\").\n * Override in subclasses if multiple instances of the same strategy type\n * need separate state storage.\n */\n protected get strategyKey(): string {\n return this.constructor.name;\n }\n\n /**\n * Get this strategy's persisted state for the current course.\n *\n * @returns The strategy's data payload, or null if no state exists\n * @throws Error if user or course is not initialized\n */\n protected async getStrategyState<T>(): Promise<T | null> {\n if (!this.user || !this.course) {\n throw new Error(\n `Cannot get strategy state: navigator not properly initialized. ` +\n `Ensure user and course are provided to constructor.`\n );\n }\n return this.user.getStrategyState<T>(this.course.getCourseID(), this.strategyKey);\n }\n\n /**\n * Persist this strategy's state for the current course.\n *\n * @param data - The strategy's data payload to store\n * @throws Error if user or course is not initialized\n */\n protected async putStrategyState<T>(data: T): Promise<void> {\n if (!this.user || !this.course) {\n throw new Error(\n `Cannot put strategy state: navigator not properly initialized. ` +\n `Ensure user and course are provided to constructor.`\n );\n }\n return this.user.putStrategyState<T>(this.course.getCourseID(), this.strategyKey, data);\n }\n\n /**\n * Factory method to create navigator instances.\n *\n * First checks the navigator registry for a pre-registered constructor.\n * If not found, falls back to dynamic import (for custom navigators).\n *\n * For reliable operation in test environments, call initializeNavigatorRegistry()\n * before using this method.\n *\n * @param user - User interface\n * @param course - Course interface\n * @param strategyData - Strategy configuration document\n * @returns the runtime object used to steer a study session.\n */\n static async create(\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n ): Promise<ContentNavigator> {\n const implementingClass = strategyData.implementingClass;\n\n // First, check the registry for a pre-registered constructor\n const RegisteredImpl = getRegisteredNavigator(implementingClass);\n if (RegisteredImpl) {\n logger.debug(`[ContentNavigator.create] Using registered navigator: ${implementingClass}`);\n return new RegisteredImpl(user, course, strategyData);\n }\n\n // Fall back to dynamic import for custom/unknown navigators\n logger.debug(\n `[ContentNavigator.create] Navigator not in registry, attempting dynamic import: ${implementingClass}`\n );\n\n let NavigatorImpl;\n\n // Specifiers built at runtime, never template literals: bundlers expand\n // `import(`./generators/${x}`)` into a glob over the directory, which in a\n // per-module dist matches .map and .d.ts files and breaks the app's build.\n // This fallback only resolves from source (no '.mjs' variation).\n const load = (specifier: string) => import(/* @vite-ignore */ specifier);\n\n // Try different extension variations\n const variations = ['.ts', '.js', ''];\n\n for (const ext of variations) {\n // Try generators directory\n try {\n const module = await load(`./generators/${implementingClass}${ext}`);\n NavigatorImpl = module.default;\n if (NavigatorImpl) break;\n } catch (e) {\n logger.debug(`Failed to load generator ${implementingClass}${ext}:`, e);\n }\n\n // Try filters directory\n try {\n const module = await load(`./filters/${implementingClass}${ext}`);\n NavigatorImpl = module.default;\n if (NavigatorImpl) break;\n } catch (e) {\n logger.debug(`Failed to load filter ${implementingClass}${ext}:`, e);\n }\n\n // Try current directory (legacy)\n try {\n const module = await load(`./${implementingClass}${ext}`);\n NavigatorImpl = module.default;\n if (NavigatorImpl) break;\n } catch (e) {\n logger.debug(`Failed to load legacy ${implementingClass}${ext}:`, e);\n }\n \n if (NavigatorImpl) break;\n }\n\n if (!NavigatorImpl) {\n throw new Error(`Could not load navigator implementation for: ${implementingClass}`);\n }\n\n return new NavigatorImpl(user, course, strategyData);\n }\n\n /**\n * Get cards with suitability scores and provenance trails.\n *\n * **This is the PRIMARY API for navigation strategies.**\n *\n * Returns cards ranked by suitability score (0-1). Higher scores indicate\n * better candidates for presentation. Each card includes a provenance trail\n * documenting how strategies contributed to the final score.\n *\n * ## Implementation Required\n * All navigation strategies MUST override this method. The base class does\n * not provide a default implementation.\n *\n * ## For Generators\n * Override this method to generate candidates and compute scores based on\n * your strategy's logic (e.g., ELO proximity, review urgency). Create the\n * initial provenance entry with action='generated'.\n *\n * ## For Filters\n * Filters should implement the CardFilter interface instead and be composed\n * via Pipeline. Filters do not directly implement getWeightedCards().\n *\n * @param limit - Maximum cards to return\n * @returns Cards sorted by score descending, with provenance trails\n */\n async getWeightedCards(_limit: number): Promise<GeneratorResult> {\n throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);\n }\n\n /**\n * Set ephemeral hints for the next pipeline run.\n * No-op for non-Pipeline navigators. Pipeline overrides this.\n */\n setEphemeralHints(_hints: ReplanHints): void {\n // no-op — only Pipeline implements this\n }\n}\n"],"mappings":";;;;;;;;;;;AAgGA,MAAM,oCAAoB,IAAI,KAAqC;;;;;;;;;;;;;;;AAgBnE,SAAgB,kBACd,mBACA,aACA,MACM;AACN,mBAAkB,IAAI,mBAAmB;EAAE;EAAa;EAAM,CAAC;AAC/D,QAAO,MAAM,mCAAmC,oBAAoB,OAAO,KAAK,KAAK,KAAK,KAAK;;;;;;;;AASjG,SAAgB,uBAAuB,mBAA6D;AAClG,QAAO,kBAAkB,IAAI,kBAAkB,EAAE;;;;;;;;AASnD,SAAgB,uBAAuB,mBAAoC;AACzE,QAAO,kBAAkB,IAAI,kBAAkB;;;;;;;;AASjD,SAAgB,2BAA2B,mBAAsD;AAC/F,QAAO,kBAAkB,IAAI,kBAAkB,EAAE;;;;;;;;AASnD,SAAgB,wBAAwB,mBAAmD;AAIzF,SAHa,kBAAkB,IAAI,kBAAkB,EAAE,cAG1C;;;;;;AAOf,SAAgB,8BAAwC;AACtD,QAAO,MAAM,KAAK,kBAAkB,MAAM,CAAC;;;;;;;;;;;;AAa7C,eAAsB,8BAA6C;AACjE,QAAO,MAAM,0DAA0D;CAGvE,MAAM,CAAC,WAAW,aAAa,MAAM,QAAQ,IAAI,CAC/C,OAAO,yBACP,OAAO,wBACR,CAAC;CACF,MAAM,mBAAmB,MAAM,OAAO;AACtC,mBAAkB,OAAO,UAAU,QAAQ;AAC3C,mBAAkB,OAAO,UAAU,QAAQ;AAC3C,mBAAkB,cAAc,iBAAiB,QAAQ;CAGzD,MAAM,CACJ,iBACA,oBACA,wBACA,yBACA,qBACE,MAAM,Q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Z,GAAG;AACV,WAAO,MAAM,4BAA4B,oBAAoB,IAAI,IAAI,EAAE;;AAIzE,OAAI;AAEF,qBADe,MAAM,KAAK,aAAa,oBAAoB,MAAM,EAC1C;AACvB,QAAI,cAAe;YACZ,GAAG;AACV,WAAO,MAAM,yBAAyB,oBAAoB,IAAI,IAAI,EAAE;;AAItE,OAAI;AAEF,qBADe,MAAM,KAAK,KAAK,oBAAoB,MAAM,EAClC;AACvB,QAAI,cAAe;YACZ,GAAG;AACV,WAAO,MAAM,yBAAyB,oBAAoB,IAAI,IAAI,EAAE;;AAGtE,OAAI,cAAe;;AAGrB,MAAI,CAAC,cACH,OAAM,IAAI,MAAM,gDAAgD,oBAAoB;AAGtF,SAAO,IAAI,cAAc,MAAM,QAAQ,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BtD,MAAM,iBAAiB,QAA0C;AAC/D,QAAM,IAAI,MAAM,GAAG,KAAK,YAAY,KAAK,sCAAsC;;;;;;CAOjF,kBAAkB,QAA2B"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/core/navigators/index.ts"],"sourcesContent":["import { StudyContentSource, UserDBInterface, CourseDBInterface } from '..';\nimport type { FilterKind } from './filters/types';\n\n// Re-export filter types\nexport type { CardFilter, FilterContext, CardFilterFactory, FilterKind } from './filters/types';\n\n// Re-export generator types\nexport type { CardGenerator, GeneratorContext, CardGeneratorFactory, GeneratorResult, ReplanHints } from './generators/types';\n\n// Re-export the diversity re-rank stage (pipeline stage 3)\nexport {\n diversityRerank,\n DIVERSITY_STRENGTH,\n DIVERSITY_FLOOR,\n type DiversityRerankOptions,\n} from './diversityRerank';\nimport type { GeneratorResult, ReplanHints } from './generators/types';\n\n// Re-export pipeline debugger API\nexport {\n pipelineDebugAPI,\n mountPipelineDebugger,\n getActivePipeline,\n setDebugSessionId,\n getRunsForSession,\n drainCapturedRuns,\n type PipelineRunReport,\n type RunReportCard,\n type GeneratorSummary,\n type FilterImpact,\n} from './PipelineDebugger';\n\n// Re-export the commit-free forecast capability surface.\nexport type { PipelineForecaster } from './Pipeline';\nexport {\n getSrsBacklogDebug,\n clearSrsBacklogDebug,\n type SrsBacklogDebug,\n} from './SrsDebugger';\n\n// Re-export the generic strategy-pressure debug channel. `captureStrategyPressure`\n// is part of the consumer surface: client-defined strategies (registered via\n// registerNavigator) push their backpressure state through it for the live\n// session overlay.\nexport {\n captureStrategyPressure,\n getStrategyPressureDebug,\n clearStrategyPressureDebug,\n type StrategyPressureDebug,\n type PressureGaugeDebug,\n} from './StrategyPressureDebugger';\n\nimport { LearnableWeight } from '../types/contentNavigationStrategy';\nexport type { ContentNavigationStrategyData, LearnableWeight } from '../types/contentNavigationStrategy';\nimport type { ContentNavigationStrategyData } from '../types/contentNavigationStrategy';\nimport { logger } from '../../util/logger';\n\n// ============================================================================\n// NAVIGATOR REGISTRY\n// ============================================================================\n//\n// Static registry of navigator implementations. This allows ContentNavigator.create()\n// to instantiate navigators without relying on dynamic imports, which don't work\n// reliably in all environments (e.g., test runners, bundled code).\n//\n// Usage:\n// 1. Import your navigator class\n// 2. Call registerNavigator('implementingClass', YourNavigatorClass)\n// 3. ContentNavigator.create() will use the registry before falling back to\n// dynamic import\n//\n// ============================================================================\n\n/**\n * Type for navigator constructor functions.\n */\nexport type NavigatorConstructor = new (\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n) => ContentNavigator;\n\n/**\n * Entry in the navigator registry, storing the constructor and an optional\n * pipeline role. The role is used by PipelineAssembler to classify\n * consumer-registered navigators that aren't in the built-in Navigators enum.\n */\ninterface NavigatorRegistryEntry {\n constructor: NavigatorConstructor;\n role?: NavigatorRole;\n}\n\n/**\n * Registry mapping implementingClass names to navigator entries.\n * Populated by registerNavigator() and used by ContentNavigator.create().\n */\nconst navigatorRegistry = new Map<string, NavigatorRegistryEntry>();\n\n/**\n * Register a navigator implementation.\n *\n * Call this to make a navigator available for instantiation by\n * ContentNavigator.create() without relying on dynamic imports.\n *\n * Passing a `role` is optional for built-in navigators (whose roles are in\n * the hardcoded `NavigatorRoles` record), but **required** for consumer-\n * defined navigators that need to participate in pipeline assembly.\n *\n * @param implementingClass - The class name (e.g., 'elo', 'letterGatingFilter')\n * @param constructor - The navigator class constructor\n * @param role - Optional pipeline role (GENERATOR or FILTER)\n */\nexport function registerNavigator(\n implementingClass: string,\n constructor: NavigatorConstructor,\n role?: NavigatorRole\n): void {\n navigatorRegistry.set(implementingClass, { constructor, role });\n logger.debug(`[NavigatorRegistry] Registered: ${implementingClass}${role ? ` (${role})` : ''}`);\n}\n\n/**\n * Get a navigator constructor from the registry.\n *\n * @param implementingClass - The class name to look up\n * @returns The constructor, or undefined if not registered\n */\nexport function getRegisteredNavigator(implementingClass: string): NavigatorConstructor | undefined {\n return navigatorRegistry.get(implementingClass)?.constructor;\n}\n\n/**\n * Check if a navigator is registered.\n *\n * @param implementingClass - The class name to check\n * @returns true if registered, false otherwise\n */\nexport function hasRegisteredNavigator(implementingClass: string): boolean {\n return navigatorRegistry.has(implementingClass);\n}\n\n/**\n * Get the registered role for a navigator, if one was provided at registration.\n *\n * @param implementingClass - The class name to look up\n * @returns The role, or undefined if not registered or no role was specified\n */\nexport function getRegisteredNavigatorRole(implementingClass: string): NavigatorRole | undefined {\n return navigatorRegistry.get(implementingClass)?.role;\n}\n\n/**\n * A registered filter's declared kind (see `CardFilter.kind`): the static\n * `kind` on its class. Undefined if unregistered or undeclared; undeclared\n * filters count as gates at run time.\n * @param implementingClass - The class name to look up\n */\nexport function getRegisteredFilterKind(implementingClass: string): FilterKind | undefined {\n const ctor = navigatorRegistry.get(implementingClass)?.constructor as\n | { kind?: FilterKind }\n | undefined;\n return ctor?.kind;\n}\n\n/**\n * Get all registered navigator names.\n * Useful for debugging and testing.\n */\nexport function getRegisteredNavigatorNames(): string[] {\n return Array.from(navigatorRegistry.keys());\n}\n\n/**\n * Initialize the navigator registry with all built-in navigators.\n *\n * This function dynamically imports all standard navigator implementations\n * and registers them. Call this once at application startup to ensure\n * all navigators are available.\n *\n * In test environments, this may need to be called explicitly before\n * using ContentNavigator.create().\n */\nexport async function initializeNavigatorRegistry(): Promise<void> {\n logger.debug('[NavigatorRegistry] Initializing built-in navigators...');\n\n // Import and register generators\n const [eloModule, srsModule] = await Promise.all([\n import('./generators/elo'),\n import('./generators/srs'),\n ]);\n const prescribedModule = await import('./generators/prescribed');\n registerNavigator('elo', eloModule.default);\n registerNavigator('srs', srsModule.default);\n registerNavigator('prescribed', prescribedModule.default);\n\n // Import and register filters\n const [\n hierarchyModule,\n interferenceModule,\n relativePriorityModule,\n userTagPreferenceModule,\n eloDistanceModule,\n ] = await Promise.all([\n import('./filters/hierarchyDefinition'),\n import('./filters/interferenceMitigator'),\n import('./filters/relativePriority'),\n import('./filters/userTagPreference'),\n import('./filters/eloDistance'),\n ]);\n registerNavigator('hierarchyDefinition', hierarchyModule.default);\n registerNavigator('interferenceMitigator', interferenceModule.default);\n registerNavigator('relativePriority', relativePriorityModule.default);\n registerNavigator('userTagPreference', userTagPreferenceModule.default);\n registerNavigator('eloDistance', eloDistanceModule.default);\n\n logger.debug(\n `[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(', ')}`\n );\n}\n\n// ============================================================================\n// NAVIGATION STRATEGY API\n// ============================================================================\n//\n// This module defines the ContentNavigator base class and the WeightedCard type,\n// which form the foundation of the pluggable navigation strategy system.\n//\n// KEY CONCEPTS:\n//\n// 1. WeightedCard - A card with a suitability score (0-1) and provenance trail.\n// The provenance tracks how each strategy in the pipeline contributed to\n// the card's final score, ensuring transparency and debuggability.\n//\n// 2. ContentNavigator - Abstract base class for backward compatibility.\n// New code should use CardGenerator or CardFilter interfaces directly.\n//\n// 3. CardGenerator vs CardFilter:\n// - Generators (ELO, SRS) produce candidate cards with scores\n// - Filters (Hierarchy, Interference, Priority, EloDistance) transform scores\n//\n// 4. Pipeline architecture:\n// Pipeline(generator, [filter1, filter2, ...]) executes:\n// cards = generator.getWeightedCards()\n// cards = filter1.transform(cards, context)\n// cards = filter2.transform(cards, context)\n// return sorted(cards)\n//\n// 5. Provenance tracking - Each strategy adds an entry explaining its contribution.\n// This makes the system transparent and debuggable.\n//\n// ============================================================================\n\n/**\n * Tracks a single strategy's contribution to a card's final score.\n *\n * Each strategy in the pipeline adds a StrategyContribution entry to the\n * card's provenance array, creating an audit trail of scoring decisions.\n */\nexport interface StrategyContribution {\n /**\n * Strategy type (implementing class name).\n * Examples: 'elo', 'hierarchyDefinition', 'interferenceMitigator'\n */\n strategy: string;\n\n /**\n * Human-readable name identifying this specific strategy instance.\n * Extracted from ContentNavigationStrategyData.name.\n * Courses may have multiple instances of the same strategy type with\n * different configurations.\n *\n * Examples:\n * - \"ELO (default)\"\n * - \"Interference: b/d/p confusion\"\n * - \"Interference: phonetic confusables\"\n * - \"Priority: Common letters first\"\n */\n strategyName: string;\n\n /**\n * Unique database document ID for this strategy instance.\n * Extracted from ContentNavigationStrategyData._id.\n * Use this to fetch the full strategy configuration document.\n *\n * Examples:\n * - \"NAVIGATION_STRATEGY-ELO-default\"\n * - \"NAVIGATION_STRATEGY-interference-bdp\"\n * - \"NAVIGATION_STRATEGY-priority-common-letters\"\n */\n strategyId: string;\n\n /**\n * What the strategy did:\n * - 'generated': Strategy produced this card (generators only)\n * - 'passed': Strategy evaluated but didn't change score (transparent pass-through)\n * - 'boosted': Strategy increased the score\n * - 'penalized': Strategy decreased the score\n */\n action: 'generated' | 'passed' | 'boosted' | 'penalized';\n\n /** Score after this strategy's processing */\n score: number;\n\n /**\n * The effective weight applied for this strategy instance.\n * If using evolutionary orchestration, this includes deviation.\n * If omitted, implies weight 1.0 (legacy behavior).\n */\n effectiveWeight?: number;\n\n /**\n * The deviation factor applied to this user's cohort for this strategy.\n * Range [-1.0, 1.0].\n */\n deviation?: number;\n\n /**\n * Human-readable explanation of the strategy's decision.\n *\n * Examples:\n * - \"ELO distance 75, new card\"\n * - \"Prerequisites met: letter-sounds\"\n * - \"Interferes with immature tag 'd' (decay 0.8)\"\n * - \"High-priority tag 's' (0.95) → boost 1.15x\"\n *\n * Required for transparency - silent adjusters are anti-patterns.\n */\n reason: string;\n}\n\n/**\n * A card with a suitability score and provenance trail.\n *\n * Scores range from 0-1:\n * - 1.0 = fully suitable\n * - 0.0 = hard filter (e.g., prerequisite not met)\n * - 0.5 = neutral\n * - Intermediate values = soft preference\n *\n * Provenance tracks the scoring pipeline:\n * - First entry: Generator that produced the card\n * - Subsequent entries: Filters that transformed the score\n * - Each entry includes action and human-readable reason\n */\nexport interface WeightedCard {\n cardId: string;\n courseId: string;\n /** Suitability score from 0-1 */\n score: number;\n /**\n * Audit trail of strategy contributions.\n * First entry is from the generator, subsequent entries from filters.\n */\n provenance: StrategyContribution[];\n /**\n * Pre-fetched tags. Populated by Pipeline before filters run.\n * Filters should use this instead of querying getAppliedTags() individually.\n */\n tags?: string[];\n /**\n * Review document ID (_id from ScheduledCard).\n * Present when this card originated from SRS review scheduling.\n * Used by SessionController to track review outcomes and maintain review state.\n */\n reviewID?: string;\n /**\n * The card's global ELO, when the generator already knows it (the ELO\n * generator reads it during retrieval). Lets the ELO distance filter skip a\n * fetch.\n */\n cardElo?: number;\n /**\n * A review's SRS urgency in [0, 1] (overdueness and interval recency), set by\n * the SRS generator. The review-mass regulator weighs the backlog by it.\n */\n reviewUrgency?: number;\n}\n\n/**\n * Extract card origin from provenance trail.\n *\n * The first provenance entry (from the generator) indicates whether\n * this is a new card, review, or failed card. We parse the reason\n * string to extract this information.\n *\n * @param card - Card with provenance trail\n * @returns Card origin ('new', 'review', or 'failed')\n */\nexport function getCardOrigin(card: WeightedCard): 'new' | 'review' | 'failed' {\n if (card.provenance.length === 0) {\n throw new Error('Card has no provenance - cannot determine origin');\n }\n\n const firstEntry = card.provenance[0];\n const reason = firstEntry.reason.toLowerCase();\n\n if (reason.includes('failed')) {\n return 'failed';\n }\n if (reason.includes('review')) {\n return 'review';\n }\n return 'new';\n}\n\nexport enum Navigators {\n ELO = 'elo',\n SRS = 'srs',\n PRESCRIBED = 'prescribed',\n HIERARCHY = 'hierarchyDefinition',\n INTERFERENCE = 'interferenceMitigator',\n RELATIVE_PRIORITY = 'relativePriority',\n USER_TAG_PREFERENCE = 'userTagPreference',\n ELO_DISTANCE = 'eloDistance',\n}\n\n// ============================================================================\n// NAVIGATOR ROLE CLASSIFICATION\n// ============================================================================\n//\n// Navigators are classified as either generators or filters:\n// - Generators: Produce candidate cards (ELO, SRS)\n// - Filters: Transform/score candidates (Hierarchy, Interference, RelativePriority)\n//\n// This classification is used by PipelineAssembler to build pipelines:\n// 1. Instantiate generators (possibly into a CompositeGenerator)\n// 2. Instantiate filters\n// 3. Create Pipeline(generator, filters)\n//\n// ============================================================================\n\n/**\n * Role classification for navigation strategies.\n *\n * - GENERATOR: Produces candidate cards with initial scores\n * - FILTER: Transforms cards with score multipliers\n */\nexport enum NavigatorRole {\n GENERATOR = 'generator',\n FILTER = 'filter',\n}\n\n/**\n * Registry mapping navigator implementations to their roles.\n */\nexport const NavigatorRoles: Record<Navigators, NavigatorRole> = {\n [Navigators.ELO]: NavigatorRole.GENERATOR,\n [Navigators.SRS]: NavigatorRole.GENERATOR,\n [Navigators.PRESCRIBED]: NavigatorRole.GENERATOR,\n [Navigators.HIERARCHY]: NavigatorRole.FILTER,\n [Navigators.INTERFERENCE]: NavigatorRole.FILTER,\n [Navigators.RELATIVE_PRIORITY]: NavigatorRole.FILTER,\n [Navigators.USER_TAG_PREFERENCE]: NavigatorRole.FILTER,\n [Navigators.ELO_DISTANCE]: NavigatorRole.FILTER,\n};\n\n/**\n * Check if a navigator implementation is a generator.\n *\n * @param impl - Navigator implementation name (e.g., 'elo', 'hierarchyDefinition')\n * @returns true if the navigator is a generator, false otherwise\n */\nexport function isGenerator(impl: string): boolean {\n if (NavigatorRoles[impl as Navigators] === NavigatorRole.GENERATOR) return true;\n // Fallback: check the registry for consumer-registered navigators\n return getRegisteredNavigatorRole(impl) === NavigatorRole.GENERATOR;\n}\n\n/**\n * Check if a navigator implementation is a filter.\n *\n * Checks the built-in NavigatorRoles enum first, then falls back to the\n * navigator registry for consumer-registered navigators.\n *\n * @param impl - Navigator implementation name (e.g., 'elo', 'letterGatingFilter')\n * @returns true if the navigator is a filter, false otherwise\n */\nexport function isFilter(impl: string): boolean {\n if (NavigatorRoles[impl as Navigators] === NavigatorRole.FILTER) return true;\n // Fallback: check the registry for consumer-registered navigators\n return getRegisteredNavigatorRole(impl) === NavigatorRole.FILTER;\n}\n\n/**\n * Abstract base class for navigation strategies.\n *\n * This class exists primarily for backward compatibility with legacy code.\n * New code should use CardGenerator or CardFilter interfaces directly.\n *\n * The class implements StudyContentSource for compatibility with SessionController.\n * Once SessionController migrates to use getWeightedCards() exclusively,\n * the legacy methods can be removed.\n */\nexport abstract class ContentNavigator implements StudyContentSource {\n /** User interface for this navigation session */\n protected user: UserDBInterface;\n\n /** Course interface for this navigation session */\n protected course: CourseDBInterface;\n\n /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */\n protected strategyName?: string;\n\n /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */\n protected strategyId?: string;\n\n /** Evolutionary weighting configuration */\n public learnable?: LearnableWeight;\n\n /** Whether to bypass deviation (manual/static weighting) */\n public staticWeight?: boolean;\n\n /**\n * Constructor for standard navigators.\n * Call this from subclass constructors to initialize common fields.\n *\n * Note: CompositeGenerator and Pipeline call super() without args, then set\n * user/course fields directly if needed.\n */\n constructor(\n user?: UserDBInterface,\n course?: CourseDBInterface,\n strategyData?: ContentNavigationStrategyData\n ) {\n this.user = user!;\n this.course = course!;\n if (strategyData) {\n this.strategyName = strategyData.name;\n this.strategyId = strategyData._id;\n this.learnable = strategyData.learnable;\n this.staticWeight = strategyData.staticWeight;\n }\n }\n\n // ============================================================================\n // STRATEGY STATE HELPERS\n // ============================================================================\n //\n // These methods allow strategies to persist their own state (user preferences,\n // learned patterns, temporal tracking) in the user database.\n //\n // ============================================================================\n\n /**\n * Unique key identifying this strategy for state storage.\n *\n * Defaults to the constructor name (e.g., \"UserTagPreferenceFilter\").\n * Override in subclasses if multiple instances of the same strategy type\n * need separate state storage.\n */\n protected get strategyKey(): string {\n return this.constructor.name;\n }\n\n /**\n * Get this strategy's persisted state for the current course.\n *\n * @returns The strategy's data payload, or null if no state exists\n * @throws Error if user or course is not initialized\n */\n protected async getStrategyState<T>(): Promise<T | null> {\n if (!this.user || !this.course) {\n throw new Error(\n `Cannot get strategy state: navigator not properly initialized. ` +\n `Ensure user and course are provided to constructor.`\n );\n }\n return this.user.getStrategyState<T>(this.course.getCourseID(), this.strategyKey);\n }\n\n /**\n * Persist this strategy's state for the current course.\n *\n * @param data - The strategy's data payload to store\n * @throws Error if user or course is not initialized\n */\n protected async putStrategyState<T>(data: T): Promise<void> {\n if (!this.user || !this.course) {\n throw new Error(\n `Cannot put strategy state: navigator not properly initialized. ` +\n `Ensure user and course are provided to constructor.`\n );\n }\n return this.user.putStrategyState<T>(this.course.getCourseID(), this.strategyKey, data);\n }\n\n /**\n * Factory method to create navigator instances.\n *\n * First checks the navigator registry for a pre-registered constructor.\n * If not found, falls back to dynamic import (for custom navigators).\n *\n * For reliable operation in test environments, call initializeNavigatorRegistry()\n * before using this method.\n *\n * @param user - User interface\n * @param course - Course interface\n * @param strategyData - Strategy configuration document\n * @returns the runtime object used to steer a study session.\n */\n static async create(\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n ): Promise<ContentNavigator> {\n const implementingClass = strategyData.implementingClass;\n\n // First, check the registry for a pre-registered constructor\n const RegisteredImpl = getRegisteredNavigator(implementingClass);\n if (RegisteredImpl) {\n logger.debug(`[ContentNavigator.create] Using registered navigator: ${implementingClass}`);\n return new RegisteredImpl(user, course, strategyData);\n }\n\n // Fall back to dynamic import for custom/unknown navigators\n logger.debug(\n `[ContentNavigator.create] Navigator not in registry, attempting dynamic import: ${implementingClass}`\n );\n\n let NavigatorImpl;\n\n // Specifiers built at runtime, never template literals: bundlers expand\n // `import(`./generators/${x}`)` into a glob over the directory, which in a\n // per-module dist matches .map and .d.ts files and breaks the app's build.\n // This fallback only resolves from source (no '.mjs' variation).\n const load = (specifier: string) => import(/* @vite-ignore */ specifier);\n\n // Try different extension variations\n const variations = ['.ts', '.js', ''];\n\n for (const ext of variations) {\n // Try generators directory\n try {\n const module = await load(`./generators/${implementingClass}${ext}`);\n NavigatorImpl = module.default;\n if (NavigatorImpl) break;\n } catch (e) {\n logger.debug(`Failed to load generator ${implementingClass}${ext}:`, e);\n }\n\n // Try filters directory\n try {\n const module = await load(`./filters/${implementingClass}${ext}`);\n NavigatorImpl = module.default;\n if (NavigatorImpl) break;\n } catch (e) {\n logger.debug(`Failed to load filter ${implementingClass}${ext}:`, e);\n }\n\n // Try current directory (legacy)\n try {\n const module = await load(`./${implementingClass}${ext}`);\n NavigatorImpl = module.default;\n if (NavigatorImpl) break;\n } catch (e) {\n logger.debug(`Failed to load legacy ${implementingClass}${ext}:`, e);\n }\n \n if (NavigatorImpl) break;\n }\n\n if (!NavigatorImpl) {\n throw new Error(`Could not load navigator implementation for: ${implementingClass}`);\n }\n\n return new NavigatorImpl(user, course, strategyData);\n }\n\n /**\n * Get cards with suitability scores and provenance trails.\n *\n * **This is the PRIMARY API for navigation strategies.**\n *\n * Returns cards ranked by suitability score (0-1). Higher scores indicate\n * better candidates for presentation. Each card includes a provenance trail\n * documenting how strategies contributed to the final score.\n *\n * ## Implementation Required\n * All navigation strategies MUST override this method. The base class does\n * not provide a default implementation.\n *\n * ## For Generators\n * Override this method to generate candidates and compute scores based on\n * your strategy's logic (e.g., ELO proximity, review urgency). Create the\n * initial provenance entry with action='generated'.\n *\n * ## For Filters\n * Filters should implement the CardFilter interface instead and be composed\n * via Pipeline. Filters do not directly implement getWeightedCards().\n *\n * @param limit - Maximum cards to return\n * @returns Cards sorted by score descending, with provenance trails\n */\n async getWeightedCards(_limit: number): Promise<GeneratorResult> {\n throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);\n }\n\n /**\n * Set ephemeral hints for the next pipeline run.\n * No-op for non-Pipeline navigators. Pipeline overrides this.\n */\n setEphemeralHints(_hints: ReplanHints): void {\n // no-op — only Pipeline implements this\n }\n\n /** See StudyContentSource.setSessionId. No-op for non-Pipeline navigators. */\n setSessionId(_sessionId: string): void {\n // no-op — only Pipeline implements this\n }\n}\n"],"mappings":";;;;;;;;;;;AAgGA,MAAM,oCAAoB,IAAI,KAAqC;;;;;;;;;;;;;;;AAgBnE,SAAgB,kBACd,mBACA,aACA,MACM;AACN,mBAAkB,IAAI,mBAAmB;EAAE;EAAa;EAAM,CAAC;AAC/D,QAAO,MAAM,mCAAmC,oBAAoB,OAAO,KAAK,KAAK,KAAK,KAAK;;;;;;;;AASjG,SAAgB,uBAAuB,mBAA6D;AAClG,QAAO,kBAAkB,IAAI,kBAAkB,EAAE;;;;;;;;AASnD,SAAgB,uBAAuB,mBAAoC;AACzE,QAAO,kBAAkB,IAAI,kBAAkB;;;;;;;;AASjD,SAAgB,2BAA2B,mBAAsD;AAC/F,QAAO,kBAAkB,IAAI,kBAAkB,EAAE;;;;;;;;AASnD,SAAgB,wBAAwB,mBAAmD;AAIzF,SAHa,kBAAkB,IAAI,kBAAkB,EAAE,cAG1C;;;;;;AAOf,SAAgB,8BAAwC;AACtD,QAAO,MAAM,KAAK,kBAAkB,MAAM,CAAC;;;;;;;;;;;;AAa7C,eAAsB,8BAA6C;AACjE,QAAO,MAAM,0DAA0D;CAGvE,MAAM,CAAC,WAAW,aAAa,MAAM,QAAQ,IAAI,CAC/C,OAAO,yBACP,OAAO,wBACR,CAAC;CACF,MAAM,mBAAmB,MAAM,OAAO;AACtC,mBAAkB,OAAO,UAAU,QAAQ;AAC3C,mBAAkB,OAAO,UAAU,QAAQ;AAC3C,mBAAkB,cAAc,iBAAiB,QAAQ;CAGzD,MAAM,CACJ,iBACA,oBACA,wBACA,yBACA,qBACE,MAAM,QAAQ,IAAI;EACpB,OAAO;EACP,OAAO;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oBAAoB,IAAI,IAAI,EAAE;;AAIzE,OAAI;AAEF,qBADe,MAAM,KAAK,aAAa,oBAAoB,MAAM,EAC1C;AACvB,QAAI,cAAe;YACZ,GAAG;AACV,WAAO,MAAM,yBAAyB,oBAAoB,IAAI,IAAI,EAAE;;AAItE,OAAI;AAEF,qBADe,MAAM,KAAK,KAAK,oBAAoB,MAAM,EAClC;AACvB,QAAI,cAAe;YACZ,GAAG;AACV,WAAO,MAAM,yBAAyB,oBAAoB,IAAI,IAAI,EAAE;;AAGtE,OAAI,cAAe;;AAGrB,MAAI,CAAC,cACH,OAAM,IAAI,MAAM,gDAAgD,oBAAoB;AAGtF,SAAO,IAAI,cAAc,MAAM,QAAQ,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BtD,MAAM,iBAAiB,QAA0C;AAC/D,QAAM,IAAI,MAAM,GAAG,KAAK,YAAY,KAAK,sCAAsC;;;;;;CAOjF,kBAAkB,QAA2B;;CAK7C,aAAa,YAA0B"}
|
|
@@ -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.3.
|
|
4
|
+
const FRAMEWORK_VERSION = "0.3.2";
|
|
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-
|
|
1
|
+
import { U as UserDBInterface, C as CourseDBInterface, a as CoursesDBInterface } from './contentSource-CSI0pJ2D.js';
|
|
2
2
|
import { C as ClassroomDBInterface, A as AdminDBInterface } from './classroomDB-DLTtLZct.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
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-
|
|
3
|
-
export { m as SessionEloEvent, n as StudySessionRunCardTrail } from '../contentSource-
|
|
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-CSI0pJ2D.js';
|
|
3
|
+
export { m as SessionEloEvent, n as StudySessionRunCardTrail } from '../contentSource-CSI0pJ2D.js';
|
|
4
4
|
import { TagRole, TagPresentation, EloRank, CourseElo } from '@vue-skuilder/common';
|
|
5
5
|
import 'moment';
|
|
6
6
|
|
|
@@ -449,6 +449,10 @@ above:\n${above.rows.map((r) => `\t${r.id}-${r.key}\n`)}`;
|
|
|
449
449
|
setEphemeralHints(hints) {
|
|
450
450
|
this._pendingHints = hints;
|
|
451
451
|
}
|
|
452
|
+
_sessionId = null;
|
|
453
|
+
setSessionId(sessionId) {
|
|
454
|
+
this._sessionId = sessionId;
|
|
455
|
+
}
|
|
452
456
|
/**
|
|
453
457
|
* Forward a presentation to the navigator (a new card restarts its intake
|
|
454
458
|
* clock). Builds the navigator if the cached one has expired.
|
|
@@ -465,6 +469,7 @@ above:\n${above.rows.map((r) => `\t${r.id}-${r.key}\n`)}`;
|
|
|
465
469
|
navigator.setEphemeralHints(this._pendingHints);
|
|
466
470
|
this._pendingHints = null;
|
|
467
471
|
}
|
|
472
|
+
if (this._sessionId) navigator.setSessionId(this._sessionId);
|
|
468
473
|
return await navigator.getWeightedCards(limit);
|
|
469
474
|
} catch (e) {
|
|
470
475
|
logger.error(`[courseDB] Error getting weighted cards: ${e}`);
|