@vue-skuilder/db 0.3.2 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/navigators/filters/eloDistance.mjs.map +1 -1
- package/dist/core/navigators/generators/prescribed.mjs.map +1 -1
- package/dist/core/versionStamps.mjs +1 -1
- package/dist/diagnostics/derive.mjs.map +1 -1
- package/dist/diagnostics/index.cjs +16 -3
- package/dist/diagnostics/index.cjs.map +1 -1
- package/dist/diagnostics/index.d.ts +27 -4
- package/dist/diagnostics/tagElo.mjs +20 -4
- package/dist/diagnostics/tagElo.mjs.map +1 -1
- package/dist/impl/couch/index.cjs.map +1 -1
- package/dist/impl/static/index.cjs.map +1 -1
- package/dist/index.cjs +8 -2
- package/dist/index.cjs.map +1 -1
- package/dist/study/services/tagRecent.mjs +2 -1
- package/dist/study/services/tagRecent.mjs.map +1 -1
- package/package.json +3 -3
- package/src/core/navigators/filters/eloDistance.ts +2 -2
- package/src/core/navigators/generators/prescribed.ts +5 -6
- package/src/diagnostics/derive.ts +6 -1
- package/src/diagnostics/tagElo.ts +43 -3
- package/src/study/services/tagRecent.test.ts +57 -3
- package/src/study/services/tagRecent.ts +8 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"eloDistance.mjs","names":[],"sources":["../../../../src/core/navigators/filters/eloDistance.ts"],"sourcesContent":["import type { CourseDBInterface } from '../../interfaces/courseDB';\nimport type { UserDBInterface } from '../../interfaces/userDB';\nimport type { ContentNavigationStrategyData } from '../../types/contentNavigationStrategy';\nimport { ContentNavigator } from '../index';\nimport type { WeightedCard } from '../index';\nimport type { GeneratorResult } from '../generators/types';\nimport type { CardFilter, FilterContext, FilterKind } from './types';\nimport { COUNT_ONLY_SCORE, isCountOnlyTag, tagRole, type CourseElo } from '@vue-skuilder/common';\nimport { logger } from '../../../util/logger';\n\n// ============================================================================\n// ELO DISTANCE FILTER\n// ============================================================================\n//\n// Scales every candidate by how close its ELO is to the learner's, on a smooth\n// Gaussian (no discontinuities, never zero).\n//\n// The one place ELO distance counts. Generators retrieve (the ELO generator\n// pulls a window of cards near the learner's ELO) and score only on what's\n// specific to their source; a signal that applies to every card lives in one\n// heap-wide filter, so new cards and reviews are weighed on the same terms:\n// - reviews the learner has moved beyond fade, and may never surface over\n// higher-priority work;\n// - new cards far from the learner's level rank low (this used to live in the\n// ELO generator's own score, which double-counted alongside this filter).\n//\n// Tag-aware (opt-in, experimental): a card's difficulty for this learner is\n// read on the skills they share, not only on global ELO. Card and learner keep\n// paired ratings per tag (each graded response adjusts both), so a tag's gap\n// (card − learner) is as meaningful as the global one, and often more: a card\n// can sit at the learner's global level while testing their weakest skill.\n// See tagAwareGap for the combination. Global distance is the default; a course\n// opts in with `tagAware`, a browser with `window.skuilder.multiDimElo = true`\n// (see the toggle below), for side-by-side testing.\n//\n// Intro cards pass through untouched. They carry an `intro`-role tag, grade\n// nothing, and their ELO is a placeholder, so a distance on it means nothing.\n// Penalising them starved established learners of every intro (an LP learner\n// at ~1600 saw sight-word intros at 1000 scored ×0.05 for six weeks).\n//\n// A `signal`, not a gate: it expresses preference, not readiness. `liveOnly`:\n// forecasts and card-space scans start every card at 1.0 without a generator,\n// and never applied ELO distance, so they skip it.\n//\n// The assembler adds this filter (as \"ELO Distance (default)\") to every\n// pipeline whose strategy docs don't declare one. A course tunes it by\n// declaring its own `eloDistance` strategy doc with an EloDistanceConfig.\n//\n// ============================================================================\n\n/**\n * Configuration for the ELO distance curve:\n * `minMultiplier + (maxMultiplier − minMultiplier) · exp(−(distance / halfLife)²)`.\n */\nexport interface EloDistanceConfig {\n /**\n * The Gaussian's scale in ELO points (despite the name, not a half-life).\n * Default 300: distance 250 → ~0.5, as the ELO generator scored new cards.\n *\n * - distance 0: maxMultiplier\n * - distance = halfLife: ~0.4 (with the default floor)\n * - distance = 2 · halfLife: ~0.07\n */\n halfLife?: number;\n\n /**\n * Floor, so far-off cards keep a nonzero score (the pipeline drops zero\n * scores before hints, and a hint must be able to lift any card). Default 0.05.\n */\n minMultiplier?: number;\n\n /** Ceiling. Usually 1.0 (no boost for close cards). Default 1.0. */\n maxMultiplier?: number;\n\n /**\n * Measure distance on the tags the card and learner share (see\n * tagAwareGap), falling back to global ELO where they share none.\n * Default false. `window.skuilder.multiDimElo` turns it on in one browser.\n */\n tagAware?: boolean;\n\n /**\n * A learner's tag rating counts once it rests on at least this many graded\n * responses. Count-only (exposure) tags never count. Default 3.\n */\n minTagCount?: number;\n}\n\n/**\n * The default curve. The default strategy doc carries it as its config, so\n * the admin pipeline view shows what runs.\n */\nexport const DEFAULT_ELO_DISTANCE_CONFIG: Required<EloDistanceConfig> = {\n halfLife: 300,\n minMultiplier: 0.05,\n maxMultiplier: 1.0,\n tagAware: false,\n minTagCount: 3,\n};\n\n/**\n * Graded responses at which a tag's gap carries half its full weight. Thin\n * tag evidence leans on global ELO; well-practised tags dominate.\n */\nconst TAG_CONFIDENCE_HALF = 10;\n\n/** Whether the card is an intro: any `intro`-role tag. Its ELO is a placeholder. */\nfunction isIntroCard(card: WeightedCard): boolean {\n return (card.tags ?? []).some((t) => tagRole(t) === 'intro');\n}\n\n/** Fallback card ELO when a card has none recorded. */\nconst DEFAULT_CARD_ELO = 1000;\n\nfunction computeMultiplier(\n distance: number,\n halfLife: number,\n minMultiplier: number,\n maxMultiplier: number\n): number {\n const normalizedDistance = distance / halfLife;\n const decay = Math.exp(-(normalizedDistance * normalizedDistance));\n return minMultiplier + (maxMultiplier - minMultiplier) * decay;\n}\n\nfunction resolveConfig(config?: EloDistanceConfig): Required<EloDistanceConfig> {\n return { ...DEFAULT_ELO_DISTANCE_CONFIG, ...config };\n}\n\n// ----------------------------------------------------------------------------\n// Live toggle: window.skuilder.multiDimElo\n// ----------------------------------------------------------------------------\n//\n// `window.skuilder.multiDimElo = true` turns tag-aware distance on in this\n// browser, whatever the strategy config says; `false` returns it to the\n// config. Read on every run, so it takes effect at the next replan. Kept in\n// localStorage so it survives reloads across a testing stretch. Runs it shapes\n// say so in every card's ELO distance reason (\"tag-aware\").\n\nconst MULTI_DIM_ELO_KEY = 'skuilder:multiDimElo';\n\nlet multiDimElo = readMultiDimElo();\n\nfunction readMultiDimElo(): boolean {\n try {\n return typeof localStorage !== 'undefined' && localStorage.getItem(MULTI_DIM_ELO_KEY) === 'true';\n } catch {\n return false;\n }\n}\n\n/**\n * Mount the toggle on window.skuilder.multiDimElo.\n */\nexport function mountMultiDimEloToggle(): void {\n if (typeof window === 'undefined') return;\n\n const win = window as any;\n win.skuilder = win.skuilder || {};\n Object.defineProperty(win.skuilder, 'multiDimElo', {\n configurable: true,\n enumerable: true,\n get: () => multiDimElo,\n set: (on: unknown) => {\n multiDimElo = on === true;\n try {\n if (multiDimElo) localStorage.setItem(MULTI_DIM_ELO_KEY, 'true');\n else localStorage.removeItem(MULTI_DIM_ELO_KEY);\n } catch (e) {\n logger.warn(`[EloDistance] multiDimElo not persisted (localStorage unavailable): ${e}`);\n }\n logger.print(\n `[EloDistance] multiDimElo ${multiDimElo ? 'on: tag-aware' : 'off: per strategy config'}` +\n ' ELO distance from the next replan'\n );\n },\n });\n}\n\n// Auto-mount when module is loaded\nmountMultiDimEloToggle();\n\n/** One shared tag's contribution to a card's tag-aware gap. */\ninterface TagGap {\n tag: string;\n /** Card's tag rating minus the learner's: positive = harder than their level. */\n gap: number;\n weight: number;\n}\n\n/**\n * The card's difficulty for this learner, in ELO points (card − learner),\n * read on the tags they share.\n *\n * - Shared tags: the card's tags on which the learner has a real rating\n * (not a bookkeeping role, nor the count-only sentinel) resting on at least\n * `minTagCount` graded responses. A card with no rating of its own on a tag\n * uses its global, as the ELO update does when it first grades that tag.\n * - Each tag's gap is weighted by the learner's evidence on it,\n * n / (n + TAG_CONFIDENCE_HALF).\n * - The weighted mean of the tag gaps is blended with the global gap by the\n * total evidence W: λ = W / (W + 1). One thin tag barely moves it; several\n * practised tags dominate it.\n *\n * OPEN (draft, 2026-10-01). Shipped on by default in 0.2.29 by accident (it\n * rode along in the version-bump commit); off by default since, and live only\n * behind the toggle. On one LP learner's 09-30 dump the effect was modest: every touched card shared a rated tag\n * (median 4); mean multiplier ×0.70 → ×0.75 over 352 touched cards, ×0.84 →\n * ×0.88 over 42 due reviews. The biggest movers were old who-said-that cards:\n * ~400 below the learner globally, ~280 below on their own skills.\n *\n * 1. Compensatory or conjunctive. This averages: a weak skill is offset by\n * strong ones. For spelling a word, which needs every grapheme, the hardest\n * shared skill arguably sets the difficulty: take the largest gap instead.\n * The main design question.\n * 2. Which tags count. Broad tags (`concept:match:simple`, `ui:*`) sit on most\n * cards and act like a second global rating. The framework may want the\n * course to say which tags are skills (cf. LP's diagnostics interpreter\n * `isSkillTag`), e.g. as tag patterns in the strategy config.\n * The admin ELO viewer (in progress, 2026-10) answers the same question for\n * display with its own tag batches (role × namespace). Before tag-aware goes\n * on by default, make that one predicate:\n * - a serializable selector (roles, prefix patterns), beside `tagRoles.ts`\n * in common, so a strategy doc can carry it;\n * - an `EloDistanceConfig` field for it, read by `tagAwareGap`;\n * - `tagAwareGap` moved to a pure module (this file imports `core`, which\n * the diagnostics entry can't), so the viewer can show what the filter\n * would compute;\n * - the viewer's default batch read from the course's eloDistance config.\n * 3. New cards matter most, and that dump couldn't show them. An unseen\n * card's tag ratings fall back to its global, so for new cards this reads\n * \"card global vs the learner's rating on that skill\". Measuring it needs a\n * `--course all` dump.\n * 4. Cost. Tag-aware fetches full ratings for every candidate (~500 card docs\n * per run); global-only fetches only reviews'.\n * 5. Retrieval stays global. The ELO generator's window is the cards nearest\n * the learner's global ELO, so a card that's well matched on its skills but\n * far off globally may never be retrieved.\n * 6. Target. Distance 0 means ~50% expected success. Early learners may do\n * better aiming higher: a shift of the curve's centre, independent of this.\n */\nexport function tagAwareGap(\n cardTags: readonly string[],\n cardElo: CourseElo,\n userElo: CourseElo,\n minTagCount: number\n): { gap: number; globalGap: number; tags: TagGap[] } {\n const globalGap = cardElo.global.score - userElo.global.score;\n const tags: TagGap[] = [];\n for (const tag of cardTags) {\n const user = userElo.tags[tag];\n if (isCountOnlyTag(tag) || !user || user.score === COUNT_ONLY_SCORE || user.count < minTagCount) {\n continue;\n }\n const card = cardElo.tags[tag]?.score ?? cardElo.global.score;\n tags.push({\n tag,\n gap: card - user.score,\n weight: user.count / (user.count + TAG_CONFIDENCE_HALF),\n });\n }\n if (tags.length === 0) return { gap: globalGap, globalGap, tags };\n\n const total = tags.reduce((w, t) => w + t.weight, 0);\n const tagGap = tags.reduce((g, t) => g + t.weight * t.gap, 0) / total;\n const lambda = total / (total + 1);\n return { gap: lambda * tagGap + (1 - lambda) * globalGap, globalGap, tags };\n}\n\nfunction tagReason(tags: TagGap[], globalGap: number): string {\n const shown = [...tags]\n .sort((a, b) => Math.abs(b.gap) * b.weight - Math.abs(a.gap) * a.weight)\n .slice(0, 3)\n .map((t) => `${t.tag} ${t.gap >= 0 ? '+' : ''}${Math.round(t.gap)}`)\n .join(', ');\n const more = tags.length > 3 ? `, +${tags.length - 3} more` : '';\n return ` on ${tags.length} shared tag(s) [${shown}${more}] (global ${globalGap >= 0 ? '+' : ''}${Math.round(globalGap)})`;\n}\n\nasync function applyEloDistance(\n cards: WeightedCard[],\n context: FilterContext,\n config: Required<EloDistanceConfig>,\n source: { name: string; strategyId: string }\n): Promise<WeightedCard[]> {\n const { course, userElo, userCourseElo } = context;\n const { halfLife, minMultiplier, maxMultiplier } = config;\n const tagAware = (config.tagAware || multiDimElo) && userCourseElo !== undefined;\n\n // Tag-aware needs every card's full ratings; otherwise only the ELO of cards\n // that don't carry it (reviews). One batch either way.\n const missing = cards\n .filter((c) => !isIntroCard(c) && (tagAware || c.cardElo === undefined))\n .map((c) => c.cardId);\n const fetched = new Map<string, CourseElo>();\n if (missing.length > 0) {\n const elos = await course.getCardEloData(missing);\n missing.forEach((id, i) => {\n if (elos[i]) fetched.set(id, elos[i]);\n });\n }\n\n return cards.map((card) => {\n if (isIntroCard(card)) {\n return {\n ...card,\n provenance: [\n ...card.provenance,\n {\n strategy: 'eloDistance',\n strategyName: source.name,\n strategyId: source.strategyId,\n action: 'passed',\n score: card.score,\n reason: 'intro card: ELO is a placeholder, distance not applied → 1.00x',\n },\n ],\n };\n }\n\n const full = fetched.get(card.cardId);\n const cardElo = full?.global?.score ?? card.cardElo ?? DEFAULT_CARD_ELO;\n\n let distance = Math.abs(cardElo - userElo);\n let how = '';\n if (tagAware) {\n const t = full ? tagAwareGap(card.tags ?? [], full, userCourseElo!, config.minTagCount) : undefined;\n if (t) distance = Math.abs(t.gap);\n how = t?.tags.length\n ? `, tag-aware${tagReason(t.tags, t.globalGap)}`\n : ', tag-aware: global (no shared tags)';\n }\n\n const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);\n const newScore = card.score * multiplier;\n const action = multiplier < maxMultiplier - 0.01 ? 'penalized' : 'passed';\n\n return {\n ...card,\n cardElo,\n score: newScore,\n provenance: [\n ...card.provenance,\n {\n strategy: 'eloDistance',\n strategyName: source.name,\n strategyId: source.strategyId,\n action,\n score: newScore,\n reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)})${how} → ${multiplier.toFixed(2)}x`,\n },\n ],\n };\n });\n}\n\n/**\n * Create an ELO distance filter outside the strategy-doc path.\n *\n * @param config - Optional configuration for the curve\n */\nexport function createEloDistanceFilter(config?: EloDistanceConfig): CardFilter {\n const resolved = resolveConfig(config);\n const source = { name: 'ELO Distance Filter', strategyId: 'ELO_DISTANCE_FILTER' };\n return {\n name: source.name,\n kind: 'signal',\n liveOnly: true,\n transform: (cards, context) => applyEloDistance(cards, context, resolved, source),\n };\n}\n\n/**\n * The ELO distance filter as a strategy-doc navigator (`implementingClass:\n * 'eloDistance'`, serializedData: an EloDistanceConfig as JSON, or empty).\n */\nexport default class EloDistanceFilter extends ContentNavigator implements CardFilter {\n name: string;\n /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */\n static readonly kind: FilterKind = 'signal';\n readonly kind = EloDistanceFilter.kind;\n readonly liveOnly = true;\n private config: Required<EloDistanceConfig>;\n\n constructor(\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n ) {\n super(user, course, strategyData);\n this.name = strategyData.name || 'ELO Distance';\n let parsed: EloDistanceConfig | undefined;\n try {\n parsed = strategyData.serializedData ? JSON.parse(strategyData.serializedData) : undefined;\n } catch {\n parsed = undefined;\n }\n this.config = resolveConfig(parsed);\n }\n\n transform(cards: WeightedCard[], context: FilterContext): Promise<WeightedCard[]> {\n return applyEloDistance(cards, context, this.config, {\n name: this.name,\n strategyId: this.strategyId || 'NAVIGATION_STRATEGY-eloDistance-default',\n });\n }\n\n async getWeightedCards(_limit: number): Promise<GeneratorResult> {\n throw new Error(\n 'EloDistanceFilter is a filter and should not be used as a generator. ' +\n 'Use Pipeline with a generator and this filter via transform().'\n );\n }\n}\n"],"mappings":";;;;;;;;;AA4FA,MAAa,8BAA2D;CACtE,UAAU;CACV,eAAe;CACf,eAAe;CACf,UAAU;CACV,aAAa;CACd;;;;;AAMD,MAAM,sBAAsB;;AAG5B,SAAS,YAAY,MAA6B;AAChD,SAAQ,KAAK,QAAQ,EAAE,EAAE,MAAM,MAAM,QAAQ,EAAE,KAAK,QAAQ;;;AAI9D,MAAM,mBAAmB;AAEzB,SAAS,kBACP,UACA,UACA,eACA,eACQ;CACR,MAAM,qBAAqB,WAAW;CACtC,MAAM,QAAQ,KAAK,IAAI,EAAE,qBAAqB,oBAAoB;AAClE,QAAO,iBAAiB,gBAAgB,iBAAiB;;AAG3D,SAAS,cAAc,QAAyD;AAC9E,QAAO;EAAE,GAAG;EAA6B,GAAG;EAAQ;;AAatD,MAAM,oBAAoB;AAE1B,IAAI,cAAc,iBAAiB;AAEnC,SAAS,kBAA2B;AAClC,KAAI;AACF,SAAO,OAAO,iBAAiB,eAAe,aAAa,QAAQ,kBAAkB,KAAK;SACpF;AACN,SAAO;;;;;;AAOX,SAAgB,yBAA+B;A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,MAAI;AACF,YAAS,aAAa,iBAAiB,KAAK,MAAM,aAAa,eAAe,GAAG,KAAA;UAC3E;AACN,YAAS,KAAA;;AAEX,OAAK,SAAS,cAAc,OAAO;;CAGrC,UAAU,OAAuB,SAAiD;AAChF,SAAO,iBAAiB,OAAO,SAAS,KAAK,QAAQ;GACnD,MAAM,KAAK;GACX,YAAY,KAAK,cAAc;GAChC,CAAC;;CAGJ,MAAM,iBAAiB,QAA0C;AAC/D,QAAM,IAAI,MACR,sIAED"}
|
|
1
|
+
{"version":3,"file":"eloDistance.mjs","names":[],"sources":["../../../../src/core/navigators/filters/eloDistance.ts"],"sourcesContent":["import type { CourseDBInterface } from '../../interfaces/courseDB';\nimport type { UserDBInterface } from '../../interfaces/userDB';\nimport type { ContentNavigationStrategyData } from '../../types/contentNavigationStrategy';\nimport { ContentNavigator } from '../index';\nimport type { WeightedCard } from '../index';\nimport type { GeneratorResult } from '../generators/types';\nimport type { CardFilter, FilterContext, FilterKind } from './types';\nimport { COUNT_ONLY_SCORE, isCountOnlyTag, tagRole, type CourseElo } from '@vue-skuilder/common';\nimport { logger } from '../../../util/logger';\n\n// ============================================================================\n// ELO DISTANCE FILTER\n// ============================================================================\n//\n// Scales every candidate by how close its ELO is to the learner's, on a smooth\n// Gaussian (no discontinuities, never zero).\n//\n// The one place ELO distance counts. Generators retrieve (the ELO generator\n// pulls a window of cards near the learner's ELO) and score only on what's\n// specific to their source; a signal that applies to every card lives in one\n// heap-wide filter, so new cards and reviews are weighed on the same terms:\n// - reviews the learner has moved beyond fade, and may never surface over\n// higher-priority work;\n// - new cards far from the learner's level rank low (this used to live in the\n// ELO generator's own score, which double-counted alongside this filter).\n//\n// Tag-aware (opt-in, experimental): a card's difficulty for this learner is\n// read on the skills they share, not only on global ELO. Card and learner keep\n// paired ratings per tag (each graded response adjusts both), so a tag's gap\n// (card − learner) is as meaningful as the global one, and often more: a card\n// can sit at the learner's global level while testing their weakest skill.\n// See tagAwareGap for the combination. Global distance is the default; a course\n// opts in with `tagAware`, a browser with `window.skuilder.multiDimElo = true`\n// (see the toggle below), for side-by-side testing.\n//\n// Intro cards pass through untouched. They carry an `intro`-role tag, grade\n// nothing, and their ELO is a placeholder, so a distance on it means nothing.\n// Penalising them starves established learners of intros: a learner rated\n// well above the placeholder sees every intro at the curve's floor.\n//\n// A `signal`, not a gate: it expresses preference, not readiness. `liveOnly`:\n// forecasts and card-space scans start every card at 1.0 without a generator,\n// and never applied ELO distance, so they skip it.\n//\n// The assembler adds this filter (as \"ELO Distance (default)\") to every\n// pipeline whose strategy docs don't declare one. A course tunes it by\n// declaring its own `eloDistance` strategy doc with an EloDistanceConfig.\n//\n// ============================================================================\n\n/**\n * Configuration for the ELO distance curve:\n * `minMultiplier + (maxMultiplier − minMultiplier) · exp(−(distance / halfLife)²)`.\n */\nexport interface EloDistanceConfig {\n /**\n * The Gaussian's scale in ELO points (despite the name, not a half-life).\n * Default 300: distance 250 → ~0.5, as the ELO generator scored new cards.\n *\n * - distance 0: maxMultiplier\n * - distance = halfLife: ~0.4 (with the default floor)\n * - distance = 2 · halfLife: ~0.07\n */\n halfLife?: number;\n\n /**\n * Floor, so far-off cards keep a nonzero score (the pipeline drops zero\n * scores before hints, and a hint must be able to lift any card). Default 0.05.\n */\n minMultiplier?: number;\n\n /** Ceiling. Usually 1.0 (no boost for close cards). Default 1.0. */\n maxMultiplier?: number;\n\n /**\n * Measure distance on the tags the card and learner share (see\n * tagAwareGap), falling back to global ELO where they share none.\n * Default false. `window.skuilder.multiDimElo` turns it on in one browser.\n */\n tagAware?: boolean;\n\n /**\n * A learner's tag rating counts once it rests on at least this many graded\n * responses. Count-only (exposure) tags never count. Default 3.\n */\n minTagCount?: number;\n}\n\n/**\n * The default curve. The default strategy doc carries it as its config, so\n * the admin pipeline view shows what runs.\n */\nexport const DEFAULT_ELO_DISTANCE_CONFIG: Required<EloDistanceConfig> = {\n halfLife: 300,\n minMultiplier: 0.05,\n maxMultiplier: 1.0,\n tagAware: false,\n minTagCount: 3,\n};\n\n/**\n * Graded responses at which a tag's gap carries half its full weight. Thin\n * tag evidence leans on global ELO; well-practised tags dominate.\n */\nconst TAG_CONFIDENCE_HALF = 10;\n\n/** Whether the card is an intro: any `intro`-role tag. Its ELO is a placeholder. */\nfunction isIntroCard(card: WeightedCard): boolean {\n return (card.tags ?? []).some((t) => tagRole(t) === 'intro');\n}\n\n/** Fallback card ELO when a card has none recorded. */\nconst DEFAULT_CARD_ELO = 1000;\n\nfunction computeMultiplier(\n distance: number,\n halfLife: number,\n minMultiplier: number,\n maxMultiplier: number\n): number {\n const normalizedDistance = distance / halfLife;\n const decay = Math.exp(-(normalizedDistance * normalizedDistance));\n return minMultiplier + (maxMultiplier - minMultiplier) * decay;\n}\n\nfunction resolveConfig(config?: EloDistanceConfig): Required<EloDistanceConfig> {\n return { ...DEFAULT_ELO_DISTANCE_CONFIG, ...config };\n}\n\n// ----------------------------------------------------------------------------\n// Live toggle: window.skuilder.multiDimElo\n// ----------------------------------------------------------------------------\n//\n// `window.skuilder.multiDimElo = true` turns tag-aware distance on in this\n// browser, whatever the strategy config says; `false` returns it to the\n// config. Read on every run, so it takes effect at the next replan. Kept in\n// localStorage so it survives reloads across a testing stretch. Runs it shapes\n// say so in every card's ELO distance reason (\"tag-aware\").\n\nconst MULTI_DIM_ELO_KEY = 'skuilder:multiDimElo';\n\nlet multiDimElo = readMultiDimElo();\n\nfunction readMultiDimElo(): boolean {\n try {\n return typeof localStorage !== 'undefined' && localStorage.getItem(MULTI_DIM_ELO_KEY) === 'true';\n } catch {\n return false;\n }\n}\n\n/**\n * Mount the toggle on window.skuilder.multiDimElo.\n */\nexport function mountMultiDimEloToggle(): void {\n if (typeof window === 'undefined') return;\n\n const win = window as any;\n win.skuilder = win.skuilder || {};\n Object.defineProperty(win.skuilder, 'multiDimElo', {\n configurable: true,\n enumerable: true,\n get: () => multiDimElo,\n set: (on: unknown) => {\n multiDimElo = on === true;\n try {\n if (multiDimElo) localStorage.setItem(MULTI_DIM_ELO_KEY, 'true');\n else localStorage.removeItem(MULTI_DIM_ELO_KEY);\n } catch (e) {\n logger.warn(`[EloDistance] multiDimElo not persisted (localStorage unavailable): ${e}`);\n }\n logger.print(\n `[EloDistance] multiDimElo ${multiDimElo ? 'on: tag-aware' : 'off: per strategy config'}` +\n ' ELO distance from the next replan'\n );\n },\n });\n}\n\n// Auto-mount when module is loaded\nmountMultiDimEloToggle();\n\n/** One shared tag's contribution to a card's tag-aware gap. */\ninterface TagGap {\n tag: string;\n /** Card's tag rating minus the learner's: positive = harder than their level. */\n gap: number;\n weight: number;\n}\n\n/**\n * The card's difficulty for this learner, in ELO points (card − learner),\n * read on the tags they share.\n *\n * - Shared tags: the card's tags on which the learner has a real rating\n * (not a bookkeeping role, nor the count-only sentinel) resting on at least\n * `minTagCount` graded responses. A card with no rating of its own on a tag\n * uses its global, as the ELO update does when it first grades that tag.\n * - Each tag's gap is weighted by the learner's evidence on it,\n * n / (n + TAG_CONFIDENCE_HALF).\n * - The weighted mean of the tag gaps is blended with the global gap by the\n * total evidence W: λ = W / (W + 1). One thin tag barely moves it; several\n * practised tags dominate it.\n *\n * OPEN (draft, 2026-10-01). Shipped on by default in 0.2.29 by accident (it\n * rode along in the version-bump commit); off by default since, and live only\n * behind the toggle. On one LP learner's 09-30 dump the effect was modest: every touched card shared a rated tag\n * (median 4); mean multiplier ×0.70 → ×0.75 over 352 touched cards, ×0.84 →\n * ×0.88 over 42 due reviews. The biggest movers were old who-said-that cards:\n * ~400 below the learner globally, ~280 below on their own skills.\n *\n * 1. Compensatory or conjunctive. This averages: a weak skill is offset by\n * strong ones. For spelling a word, which needs every grapheme, the hardest\n * shared skill arguably sets the difficulty: take the largest gap instead.\n * The main design question.\n * 2. Which tags count. Broad tags (`concept:match:simple`, `ui:*`) sit on most\n * cards and act like a second global rating. The framework may want the\n * course to say which tags are skills (cf. LP's diagnostics interpreter\n * `isSkillTag`), e.g. as tag patterns in the strategy config.\n * The admin ELO viewer (in progress, 2026-10) answers the same question for\n * display with its own tag batches (role × namespace). Before tag-aware goes\n * on by default, make that one predicate:\n * - a serializable selector (roles, prefix patterns), beside `tagRoles.ts`\n * in common, so a strategy doc can carry it;\n * - an `EloDistanceConfig` field for it, read by `tagAwareGap`;\n * - `tagAwareGap` moved to a pure module (this file imports `core`, which\n * the diagnostics entry can't), so the viewer can show what the filter\n * would compute;\n * - the viewer's default batch read from the course's eloDistance config.\n * 3. New cards matter most, and that dump couldn't show them. An unseen\n * card's tag ratings fall back to its global, so for new cards this reads\n * \"card global vs the learner's rating on that skill\". Measuring it needs a\n * `--course all` dump.\n * 4. Cost. Tag-aware fetches full ratings for every candidate (~500 card docs\n * per run); global-only fetches only reviews'.\n * 5. Retrieval stays global. The ELO generator's window is the cards nearest\n * the learner's global ELO, so a card that's well matched on its skills but\n * far off globally may never be retrieved.\n * 6. Target. Distance 0 means ~50% expected success. Early learners may do\n * better aiming higher: a shift of the curve's centre, independent of this.\n */\nexport function tagAwareGap(\n cardTags: readonly string[],\n cardElo: CourseElo,\n userElo: CourseElo,\n minTagCount: number\n): { gap: number; globalGap: number; tags: TagGap[] } {\n const globalGap = cardElo.global.score - userElo.global.score;\n const tags: TagGap[] = [];\n for (const tag of cardTags) {\n const user = userElo.tags[tag];\n if (isCountOnlyTag(tag) || !user || user.score === COUNT_ONLY_SCORE || user.count < minTagCount) {\n continue;\n }\n const card = cardElo.tags[tag]?.score ?? cardElo.global.score;\n tags.push({\n tag,\n gap: card - user.score,\n weight: user.count / (user.count + TAG_CONFIDENCE_HALF),\n });\n }\n if (tags.length === 0) return { gap: globalGap, globalGap, tags };\n\n const total = tags.reduce((w, t) => w + t.weight, 0);\n const tagGap = tags.reduce((g, t) => g + t.weight * t.gap, 0) / total;\n const lambda = total / (total + 1);\n return { gap: lambda * tagGap + (1 - lambda) * globalGap, globalGap, tags };\n}\n\nfunction tagReason(tags: TagGap[], globalGap: number): string {\n const shown = [...tags]\n .sort((a, b) => Math.abs(b.gap) * b.weight - Math.abs(a.gap) * a.weight)\n .slice(0, 3)\n .map((t) => `${t.tag} ${t.gap >= 0 ? '+' : ''}${Math.round(t.gap)}`)\n .join(', ');\n const more = tags.length > 3 ? `, +${tags.length - 3} more` : '';\n return ` on ${tags.length} shared tag(s) [${shown}${more}] (global ${globalGap >= 0 ? '+' : ''}${Math.round(globalGap)})`;\n}\n\nasync function applyEloDistance(\n cards: WeightedCard[],\n context: FilterContext,\n config: Required<EloDistanceConfig>,\n source: { name: string; strategyId: string }\n): Promise<WeightedCard[]> {\n const { course, userElo, userCourseElo } = context;\n const { halfLife, minMultiplier, maxMultiplier } = config;\n const tagAware = (config.tagAware || multiDimElo) && userCourseElo !== undefined;\n\n // Tag-aware needs every card's full ratings; otherwise only the ELO of cards\n // that don't carry it (reviews). One batch either way.\n const missing = cards\n .filter((c) => !isIntroCard(c) && (tagAware || c.cardElo === undefined))\n .map((c) => c.cardId);\n const fetched = new Map<string, CourseElo>();\n if (missing.length > 0) {\n const elos = await course.getCardEloData(missing);\n missing.forEach((id, i) => {\n if (elos[i]) fetched.set(id, elos[i]);\n });\n }\n\n return cards.map((card) => {\n if (isIntroCard(card)) {\n return {\n ...card,\n provenance: [\n ...card.provenance,\n {\n strategy: 'eloDistance',\n strategyName: source.name,\n strategyId: source.strategyId,\n action: 'passed',\n score: card.score,\n reason: 'intro card: ELO is a placeholder, distance not applied → 1.00x',\n },\n ],\n };\n }\n\n const full = fetched.get(card.cardId);\n const cardElo = full?.global?.score ?? card.cardElo ?? DEFAULT_CARD_ELO;\n\n let distance = Math.abs(cardElo - userElo);\n let how = '';\n if (tagAware) {\n const t = full ? tagAwareGap(card.tags ?? [], full, userCourseElo!, config.minTagCount) : undefined;\n if (t) distance = Math.abs(t.gap);\n how = t?.tags.length\n ? `, tag-aware${tagReason(t.tags, t.globalGap)}`\n : ', tag-aware: global (no shared tags)';\n }\n\n const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);\n const newScore = card.score * multiplier;\n const action = multiplier < maxMultiplier - 0.01 ? 'penalized' : 'passed';\n\n return {\n ...card,\n cardElo,\n score: newScore,\n provenance: [\n ...card.provenance,\n {\n strategy: 'eloDistance',\n strategyName: source.name,\n strategyId: source.strategyId,\n action,\n score: newScore,\n reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)})${how} → ${multiplier.toFixed(2)}x`,\n },\n ],\n };\n });\n}\n\n/**\n * Create an ELO distance filter outside the strategy-doc path.\n *\n * @param config - Optional configuration for the curve\n */\nexport function createEloDistanceFilter(config?: EloDistanceConfig): CardFilter {\n const resolved = resolveConfig(config);\n const source = { name: 'ELO Distance Filter', strategyId: 'ELO_DISTANCE_FILTER' };\n return {\n name: source.name,\n kind: 'signal',\n liveOnly: true,\n transform: (cards, context) => applyEloDistance(cards, context, resolved, source),\n };\n}\n\n/**\n * The ELO distance filter as a strategy-doc navigator (`implementingClass:\n * 'eloDistance'`, serializedData: an EloDistanceConfig as JSON, or empty).\n */\nexport default class EloDistanceFilter extends ContentNavigator implements CardFilter {\n name: string;\n /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */\n static readonly kind: FilterKind = 'signal';\n readonly kind = EloDistanceFilter.kind;\n readonly liveOnly = true;\n private config: Required<EloDistanceConfig>;\n\n constructor(\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n ) {\n super(user, course, strategyData);\n this.name = strategyData.name || 'ELO Distance';\n let parsed: EloDistanceConfig | undefined;\n try {\n parsed = strategyData.serializedData ? JSON.parse(strategyData.serializedData) : undefined;\n } catch {\n parsed = undefined;\n }\n this.config = resolveConfig(parsed);\n }\n\n transform(cards: WeightedCard[], context: FilterContext): Promise<WeightedCard[]> {\n return applyEloDistance(cards, context, this.config, {\n name: this.name,\n strategyId: this.strategyId || 'NAVIGATION_STRATEGY-eloDistance-default',\n });\n }\n\n async getWeightedCards(_limit: number): Promise<GeneratorResult> {\n throw new Error(\n 'EloDistanceFilter is a filter and should not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OAAO;GACP,YAAY,CACV,GAAG,KAAK,YACR;IACE,UAAU;IACV,cAAc,OAAO;IACrB,YAAY,OAAO;IACnB;IACA,OAAO;IACP,QAAQ,gBAAgB,KAAK,MAAM,SAAS,CAAC,UAAU,KAAK,MAAM,QAAQ,CAAC,UAAU,KAAK,MAAM,QAAQ,CAAC,GAAG,IAAI,KAAK,WAAW,QAAQ,EAAE,CAAC;IAC5I,CACF;GACF;GACD;;;;;;;AAQJ,SAAgB,wBAAwB,QAAwC;CAC9E,MAAM,WAAW,cAAc,OAAO;CACtC,MAAM,SAAS;EAAE,MAAM;EAAuB,YAAY;EAAuB;AACjF,QAAO;EACL,MAAM,OAAO;EACb,MAAM;EACN,UAAU;EACV,YAAY,OAAO,YAAY,iBAAiB,OAAO,SAAS,UAAU,OAAO;EAClF;;;;;;AAOH,IAAqB,oBAArB,MAAqB,0BAA0B,iBAAuC;CACpF;;CAEA,OAAgB,OAAmB;CACnC,OAAgB,kBAAkB;CAClC,WAAoB;CACpB;CAEA,YACE,MACA,QACA,cACA;AACA,QAAM,MAAM,QAAQ,aAAa;AACjC,OAAK,OAAO,aAAa,QAAQ;EACjC,IAAI;AACJ,MAAI;AACF,YAAS,aAAa,iBAAiB,KAAK,MAAM,aAAa,eAAe,GAAG,KAAA;UAC3E;AACN,YAAS,KAAA;;AAEX,OAAK,SAAS,cAAc,OAAO;;CAGrC,UAAU,OAAuB,SAAiD;AAChF,SAAO,iBAAiB,OAAO,SAAS,KAAK,QAAQ;GACnD,MAAM,KAAK;GACX,YAAY,KAAK,cAAc;GAChC,CAAC;;CAGJ,MAAM,iBAAiB,QAA0C;AAC/D,QAAM,IAAI,MACR,sIAED"}
|
|
@@ -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// 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;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I,CAAC,KAAK,kBAAkB,QAAQ,WAAW,OAAO,MAAM,cAAc,CACxE,aAAY,IAAI,OAAO,IAAI;AAIjC;;AAGF,QAAK,MAAM,WAAW,WACpB,MAAK,MAAM,UAAU,QACnB,KAAI,CAAC,KAAK,kBAAkB,QAAQ,WAAW,OAAO,MAAM,cAAc,CACxE,MAAK,4BACH,OAAO,KACP,kBACA,YACA,eACA,0BACA,IAAI,KAAa,EACjB,YACD;;AAMT,SAAO;GAAE;GAAS,aAAa,CAAC,GAAG,YAAY;GAAE;;CAGnD,4BACE,KACA,kBACA,YACA,eACA,OACA,SACA,KACM;AACN,MAAI,QAAQ,KAAK,QAAQ,IAAI,IAAI,CAAE;AAEnC,UAAQ,IAAI,IAAI;EAEhB,IAAI,gBAAgB;AAEpB,OAAK,MAAM,aAAa,kBAAkB;GACxC,MAAM,UAAU,UAAU,cAAc;AACxC,OAAI,CAAC,WAAW,QAAQ,WAAW,EAAG;GAEtC,MAAM,QAAQ,QAAQ,QACnB,OAAO,CAAC,KAAK,kBAAkB,IAAI,WAAW,GAAG,MAAM,cAAc,CACvE;AAED,OAAI,MAAM,SAAS,KAAK,QAAQ,GAAG;AACjC,oBAAgB;AAChB,SAAK,MAAM,UAAU,MACnB,MAAK,4BACH,OAAO,KACP,kBACA,YACA,eACA,QAAQ,GACR,SACA,IACD;;;AAKP,MAAI,CAAC,cACH,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"}
|
|
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 (e.g. a\n// target whose prerequisites sit behind a course gate that never opens), so\n// the group can never complete. Harmless while every such card stays gated;\n// but staleness escalates the support boost hint to its cap 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.\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.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_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.3";
|
|
5
5
|
let hostAppVersion;
|
|
6
6
|
/** Record the host app's version (the data layer's `appVersion` option). */
|
|
7
7
|
function setAppVersion(version) {
|