@vue-skuilder/db 0.2.37 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{contentSource-D_E7JaxR.d.ts → contentSource-2zVmcjKA.d.ts} +6 -1
- package/dist/core/index.cjs +155 -100
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.ts +5 -5
- package/dist/core/navigators/Pipeline.mjs +8 -0
- package/dist/core/navigators/Pipeline.mjs.map +1 -1
- package/dist/core/versionStamps.mjs +1 -1
- package/dist/{dataLayerProvider-BDshhSp_.d.ts → dataLayerProvider-rGyLQ93v.d.ts} +1 -1
- package/dist/diagnostics/index.d.ts +3 -3
- package/dist/impl/common/BaseUserDB.mjs +61 -34
- package/dist/impl/common/BaseUserDB.mjs.map +1 -1
- package/dist/impl/couch/CourseSyncService.mjs +23 -1
- package/dist/impl/couch/CourseSyncService.mjs.map +1 -1
- package/dist/impl/couch/courseDB.mjs +4 -0
- package/dist/impl/couch/courseDB.mjs.map +1 -1
- package/dist/impl/couch/index.cjs +177 -101
- package/dist/impl/couch/index.cjs.map +1 -1
- package/dist/impl/couch/index.d.ts +5 -3
- package/dist/impl/couch/updateQueue.mjs +69 -46
- package/dist/impl/couch/updateQueue.mjs.map +1 -1
- package/dist/impl/static/index.cjs +151 -100
- package/dist/impl/static/index.cjs.map +1 -1
- package/dist/impl/static/index.d.ts +4 -4
- package/dist/{index-BLDpFYG3.d.ts → index-C745YB_6.d.ts} +1 -1
- package/dist/index.cjs +187 -102
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +23 -10
- package/dist/index.mjs +2 -1
- package/dist/study/SessionController.mjs +4 -0
- package/dist/study/SessionController.mjs.map +1 -1
- package/dist/{types-DChCz22D.d.ts → types-DF0JuPbs.d.ts} +1 -1
- package/dist/{types-legacy-fT5Y1Wuy.d.ts → types-legacy-DdVjg81H.d.ts} +1 -1
- package/dist/util/packer/index.d.ts +3 -3
- package/dist/util/perfMarks.mjs +30 -0
- package/dist/util/perfMarks.mjs.map +1 -0
- package/docs/session-lifecycle-and-replan.md +71 -58
- package/package.json +3 -3
- package/src/core/interfaces/courseDB.ts +6 -0
- package/src/core/navigators/Pipeline.ts +8 -0
- package/src/impl/common/BaseUserDB.ts +74 -46
- package/src/impl/couch/CourseSyncService.ts +19 -2
- package/src/impl/couch/courseDB.ts +5 -0
- package/src/impl/couch/updateQueue.ts +86 -82
- package/src/study/SessionController.ts +4 -0
- package/src/util/index.ts +1 -0
- package/src/util/perfMarks.ts +35 -0
- package/tests/impl/updateQueue.test.ts +57 -0
package/dist/core/index.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
export { A as AdminDBInterface, d as AssignedCard, a as AssignedContent, c as AssignedCourse, b as AssignedTag, C as ClassroomDBInterface, S as StudentClassroomDBInterface, T as TeacherClassroomDBInterface } from '../classroomDB-DLTtLZct.js';
|
|
2
|
-
import { av as LearnableWeight, T as UserOutcomeRecord, aw as OrchestrationContext, W as WeightedCard, C as CourseDBInterface } from '../contentSource-
|
|
3
|
-
export { P as ActivityRecord, ae as CardFilter, ag as CardFilterFactory, ah as CardGenerator, aj as CardGeneratorFactory, K as ClassroomRegistration, J as ClassroomRegistrationDesignation, L as ClassroomRegistrationDoc, c as ContentNavigationStrategyData, d as ContentNavigator, v as ContentSourceID, b as CourseInfo, Q as CourseRegistration, g as CourseRegistrationDoc, a as CoursesDBInterface, af as FilterContext, at as FilterImpact, F as FilterKind, ai as GeneratorContext, G as GeneratorResult, as as GeneratorSummary, _ as HYDRATION_MARKER_ID, $ as HydrationMarker, a0 as NavigatorConstructor, N as NavigatorRole, ab as NavigatorRoles, aa as Navigators, au as PipelineForecaster, aq as PipelineRunReport, R as ReplanHints, ar as RunReportCard, f as ScheduledCard, m as SessionEloEvent, h as SessionStateSnapshot, x as SessionStateSnapshotProvider, M as SessionTrackingData, a8 as StrategyContribution, o as StudyContentSource, e as StudySessionDoc, p as StudySessionFailedItem, q as StudySessionFailedNewItem, r as StudySessionFailedReviewItem, S as StudySessionItem, s as StudySessionNewItem, t as StudySessionReviewItem, k as StudySessionRunCard, n as StudySessionRunCardTrail, i as StudySessionRunSummary, O as UserConfig, H as UserCourseSetting, E as UserCourseSettings, B as UserDBAuthenticator, U as UserDBInterface, z as UserDBReader, A as UserDBWriter, Y as UserHydrationState, Z as UserHydrationStatus, I as UsrCrsDataInterface, ax as computeDeviation, az as computeEffectiveWeight, ay as computeSpread, aA as createOrchestrationContext, ap as drainCapturedRuns, am as getActivePipeline, a9 as getCardOrigin, a5 as getRegisteredFilterKind, a2 as getRegisteredNavigator, a6 as getRegisteredNavigatorNames, a4 as getRegisteredNavigatorRole, ao as getRunsForSession, w as getStudySource, a3 as hasRegisteredNavigator, a7 as initializeNavigatorRegistry, ad as isFilter, ac as isGenerator, u as isReview, V as makeStudySessionId, al as mountPipelineDebugger, X as newSessionId, ak as pipelineDebugAPI, a1 as registerNavigator, an as setDebugSessionId } from '../contentSource-
|
|
4
|
-
export { D as DataLayerProvider } from '../dataLayerProvider-
|
|
5
|
-
import { D as DocType, d as QuestionRecord,
|
|
6
|
-
export { C as CardData,
|
|
2
|
+
import { av as LearnableWeight, T as UserOutcomeRecord, aw as OrchestrationContext, W as WeightedCard, C as CourseDBInterface } from '../contentSource-2zVmcjKA.js';
|
|
3
|
+
export { P as ActivityRecord, ae as CardFilter, ag as CardFilterFactory, ah as CardGenerator, aj as CardGeneratorFactory, K as ClassroomRegistration, J as ClassroomRegistrationDesignation, L as ClassroomRegistrationDoc, c as ContentNavigationStrategyData, d as ContentNavigator, v as ContentSourceID, b as CourseInfo, Q as CourseRegistration, g as CourseRegistrationDoc, a as CoursesDBInterface, af as FilterContext, at as FilterImpact, F as FilterKind, ai as GeneratorContext, G as GeneratorResult, as as GeneratorSummary, _ as HYDRATION_MARKER_ID, $ as HydrationMarker, a0 as NavigatorConstructor, N as NavigatorRole, ab as NavigatorRoles, aa as Navigators, au as PipelineForecaster, aq as PipelineRunReport, R as ReplanHints, ar as RunReportCard, f as ScheduledCard, m as SessionEloEvent, h as SessionStateSnapshot, x as SessionStateSnapshotProvider, M as SessionTrackingData, a8 as StrategyContribution, o as StudyContentSource, e as StudySessionDoc, p as StudySessionFailedItem, q as StudySessionFailedNewItem, r as StudySessionFailedReviewItem, S as StudySessionItem, s as StudySessionNewItem, t as StudySessionReviewItem, k as StudySessionRunCard, n as StudySessionRunCardTrail, i as StudySessionRunSummary, O as UserConfig, H as UserCourseSetting, E as UserCourseSettings, B as UserDBAuthenticator, U as UserDBInterface, z as UserDBReader, A as UserDBWriter, Y as UserHydrationState, Z as UserHydrationStatus, I as UsrCrsDataInterface, ax as computeDeviation, az as computeEffectiveWeight, ay as computeSpread, aA as createOrchestrationContext, ap as drainCapturedRuns, am as getActivePipeline, a9 as getCardOrigin, a5 as getRegisteredFilterKind, a2 as getRegisteredNavigator, a6 as getRegisteredNavigatorNames, a4 as getRegisteredNavigatorRole, ao as getRunsForSession, w as getStudySource, a3 as hasRegisteredNavigator, a7 as initializeNavigatorRegistry, ad as isFilter, ac as isGenerator, u as isReview, V as makeStudySessionId, al as mountPipelineDebugger, X as newSessionId, ak as pipelineDebugAPI, a1 as registerNavigator, an as setDebugSessionId } from '../contentSource-2zVmcjKA.js';
|
|
4
|
+
export { D as DataLayerProvider } from '../dataLayerProvider-rGyLQ93v.js';
|
|
5
|
+
import { D as DocType, d as QuestionRecord, f as DocTypePrefixes, e as CardHistory, c as CardRecord } from '../types-legacy-DdVjg81H.js';
|
|
6
|
+
export { C as CardData, g as CourseListData, h as DataShapeData, b as DisplayableData, F as Field, G as GuestUsername, Q as QualifiedCardID, i as QuestionData, S as SkuilderCourseData, a as Tag, T as TagStub, l as log } from '../types-legacy-DdVjg81H.js';
|
|
7
7
|
import { DataShape, ParsedCard } from '@vue-skuilder/common';
|
|
8
8
|
import 'moment';
|
|
9
9
|
|
|
@@ -4,6 +4,7 @@ import { diversityRerank } from "./diversityRerank.mjs";
|
|
|
4
4
|
import { buildRunReport, captureRun, registerPipelineForDebug } from "./PipelineDebugger.mjs";
|
|
5
5
|
import { noteReviewPressure } from "./SrsDebugger.mjs";
|
|
6
6
|
import { ContentNavigator } from "./index.mjs";
|
|
7
|
+
import { perfMeasure } from "../../util/perfMarks.mjs";
|
|
7
8
|
import { createOrchestrationContext } from "../orchestration/index.mjs";
|
|
8
9
|
import { DEFAULT_REGULATOR_CONFIG, INTAKE_CLOCK_KEY, applyReading, intakeReading, resetIntakeClock, reviewMassReading, stepIntakeClock } from "./regulators.mjs";
|
|
9
10
|
import { toCourseElo } from "@vue-skuilder/common";
|
|
@@ -287,6 +288,13 @@ var Pipeline = class extends ContentNavigator {
|
|
|
287
288
|
const tFilter = performance.now();
|
|
288
289
|
const result = cards.slice(0, limit);
|
|
289
290
|
logger.info(`[Pipeline:timing] total=${(tFilter - t0).toFixed(0)}ms (context=${(tContext - t0).toFixed(0)} generate=${(tGenerate - tContext).toFixed(0)} hydrate=${(tHydrate - tGenerate).toFixed(0)} filter=${(tFilter - tHydrate).toFixed(0)})`);
|
|
291
|
+
perfMeasure("sk:pipeline-run", t0, tFilter, {
|
|
292
|
+
context: Math.round(tContext - t0),
|
|
293
|
+
generate: Math.round(tGenerate - tContext),
|
|
294
|
+
hydrate: Math.round(tHydrate - tGenerate),
|
|
295
|
+
filter: Math.round(tFilter - tHydrate),
|
|
296
|
+
binding: this.course?.readsLocal === void 0 ? "unknown" : this.course.readsLocal ? "local" : "remote"
|
|
297
|
+
});
|
|
290
298
|
const topScores = result.slice(0, 3).map((c) => c.score);
|
|
291
299
|
logExecutionSummary(this.generator.name, generatedCount, this.filters.length, result.length, topScores, filterImpacts);
|
|
292
300
|
logResultCards(result);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Pipeline.mjs","names":[],"sources":["../../../src/core/navigators/Pipeline.ts"],"sourcesContent":["import { toCourseElo, type CourseElo } 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 { CardFilter, FilterContext } from './filters/types';\nimport type { CardGenerator, GeneratorContext } from './generators/types';\nimport type { GeneratorResult } from './generators/types';\nimport { logger } from '../../util/logger';\nimport { createOrchestrationContext, OrchestrationContext } from '../orchestration';\nimport { captureRun, buildRunReport, registerPipelineForDebug, type GeneratorSummary, type FilterImpact } from './PipelineDebugger';\nimport { diversityRerank } from './diversityRerank';\nimport {\n applyReading,\n DEFAULT_REGULATOR_CONFIG,\n INTAKE_CLOCK_KEY,\n intakeReading,\n resetIntakeClock,\n reviewMassReading,\n stepIntakeClock,\n type IntakeClockState,\n type RegulatorReading,\n} from './regulators';\nimport { noteReviewPressure } from './SrsDebugger';\n\n// ============================================================================\n// REPLAN HINTS\n// ============================================================================\n//\n// Ephemeral, one-shot scoring hints passed at replan time.\n// Applied after the filter chain, consumed after one pipeline run.\n//\n// Tag patterns support glob-style matching:\n// 'gpc:exercise:t-T' — exact match\n// 'gpc:intro:*' — all intro tags\n// 'gpc:exercise:t-*' — all t-variant exercises\n//\n\n// ReplanHints is defined in generators/types — re-export for consumers that import from Pipeline\nimport type { ReplanHints } from './generators/types';\nexport type { ReplanHints };\n\n/**\n * Convert a glob pattern (with `*` wildcards) to a RegExp.\n * Only `*` is supported as a wildcard (matches any characters).\n */\nfunction globToRegex(pattern: string): RegExp {\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const withWildcards = escaped.replace(/\\*/g, '.*');\n return new RegExp(`^${withWildcards}$`);\n}\n\n/** Test whether a string matches a glob pattern. */\nfunction globMatch(value: string, pattern: string): boolean {\n if (!pattern.includes('*')) return value === pattern;\n return globToRegex(pattern).test(value);\n}\n\n/** Test whether any of a card's tags match a glob pattern. */\nfunction cardMatchesTagPattern(card: WeightedCard, pattern: string): boolean {\n return (card.tags ?? []).some((tag) => globMatch(tag, pattern));\n}\n\nexport function mergeHints(allHints: Array<ReplanHints | null | undefined>): ReplanHints | undefined {\n const defined = allHints.filter((h): h is ReplanHints => h !== null && h !== undefined);\n if (defined.length === 0) return undefined;\n\n const merged: ReplanHints = {};\n\n const boostTags: Record<string, number> = {};\n for (const hints of defined) {\n for (const [pattern, factor] of Object.entries(hints.boostTags ?? {})) {\n boostTags[pattern] = (boostTags[pattern] ?? 1) * factor;\n }\n }\n if (Object.keys(boostTags).length > 0) {\n merged.boostTags = boostTags;\n }\n\n const boostCards: Record<string, number> = {};\n for (const hints of defined) {\n for (const [pattern, factor] of Object.entries(hints.boostCards ?? {})) {\n boostCards[pattern] = (boostCards[pattern] ?? 1) * factor;\n }\n }\n if (Object.keys(boostCards).length > 0) {\n merged.boostCards = boostCards;\n }\n\n const concatUnique = (\n field: 'requireTags' | 'requireCards' | 'excludeTags' | 'excludeCards'\n ): void => {\n const values = defined.flatMap((h) => h[field] ?? []);\n if (values.length > 0) {\n merged[field] = [...new Set(values)];\n }\n };\n\n concatUnique('requireTags');\n concatUnique('requireCards');\n concatUnique('excludeTags');\n concatUnique('excludeCards');\n\n const labels = defined.map((h) => h._label).filter(Boolean);\n if (labels.length > 0) {\n merged._label = labels.join('; ');\n }\n\n return Object.keys(merged).length > 0 ? merged : undefined;\n}\n\n// ============================================================================\n// PIPELINE LOGGING HELPERS\n// ============================================================================\n//\n// Focused logging functions that can be toggled by commenting single lines.\n// Use these to inspect pipeline behavior in development/production.\n//\n\n/**\n * Log pipeline configuration on construction.\n * Shows generator and filter chain structure.\n */\nfunction logPipelineConfig(generator: CardGenerator, filters: CardFilter[]): void {\n const filterList =\n filters.length > 0 ? '\\n - ' + filters.map((f) => f.name).join('\\n - ') : ' none';\n\n logger.info(\n `[Pipeline] Configuration:\\n` + ` Generator: ${generator.name}\\n` + ` Filters:${filterList}`\n );\n}\n\n/**\n * Log tag hydration results.\n * Shows effectiveness of batch query (how many cards/tags were hydrated).\n */\nfunction logTagHydration(cards: WeightedCard[], tagsByCard: Map<string, string[]>): void {\n const totalTags = Array.from(tagsByCard.values()).reduce((sum, tags) => sum + tags.length, 0);\n const cardsWithTags = Array.from(tagsByCard.values()).filter((tags) => tags.length > 0).length;\n\n logger.debug(\n `[Pipeline] Tag hydration: ${cards.length} cards, ` +\n `${cardsWithTags} have tags (${totalTags} total tags) - single batch query`\n );\n}\n\n/**\n * Log pipeline execution summary.\n * Shows complete flow from generator through filters to final results.\n */\nfunction logExecutionSummary(\n generatorName: string,\n generatedCount: number,\n filterCount: number,\n finalCount: number,\n topScores: number[],\n filterImpacts: Array<{ name: string; boosted: number; penalized: number; passed: number }>\n): void {\n const scoreDisplay =\n topScores.length > 0 ? topScores.map((s) => s.toFixed(2)).join(', ') : 'none';\n\n let filterSummary = '';\n if (filterImpacts.length > 0) {\n const impacts = filterImpacts.map((f) => {\n const parts: string[] = [];\n if (f.boosted > 0) parts.push(`+${f.boosted}`);\n if (f.penalized > 0) parts.push(`-${f.penalized}`);\n if (f.passed > 0) parts.push(`=${f.passed}`);\n return `${f.name}: ${parts.join('/')}`;\n });\n filterSummary = `\\n Filter impact: ${impacts.join(', ')}`;\n }\n\n logger.info(\n `[Pipeline] Execution: ${generatorName} produced ${generatedCount} → ` +\n `${filterCount} filters → ${finalCount} results (top scores: ${scoreDisplay})` +\n filterSummary +\n `\\n 💡 Inspect: window.skuilder.pipeline`\n );\n}\n\n/**\n * Log all result cards with score, cardId, and key provenance.\n * Toggle: set VERBOSE_RESULTS = true to enable.\n */\nconst VERBOSE_RESULTS = false;\n\nfunction logResultCards(cards: WeightedCard[]): void {\n if (!VERBOSE_RESULTS || cards.length === 0) return;\n\n logger.info(`[Pipeline] Results (${cards.length} cards):`);\n for (let i = 0; i < cards.length; i++) {\n const c = cards[i];\n const tags = c.tags?.slice(0, 3).join(', ') || '';\n const filters = c.provenance\n .filter((p) => p.strategy === 'hierarchyDefinition' || p.strategy === 'priorityDefinition' || p.strategy === 'interferenceFilter' || p.strategy === 'letterGating' || p.strategy === 'ephemeralHint' || p.strategy === 'diversityRerank')\n .map((p) => {\n const arrow = p.action === 'boosted' ? '↑' : p.action === 'penalized' ? '↓' : '=';\n return `${p.strategyName}${arrow}${p.score.toFixed(2)}`;\n })\n .join(' | ');\n logger.info(\n `[Pipeline] ${String(i + 1).padStart(2)}. ${c.score.toFixed(4)} ${c.cardId} [${tags}]${filters ? ` {${filters}}` : ''}`\n );\n }\n}\n\n/**\n * Log provenance trails for cards.\n * Shows the complete scoring history for each card through the pipeline.\n * Useful for debugging why cards scored the way they did.\n */\nfunction logCardProvenance(cards: WeightedCard[], maxCards: number = 3): void {\n const cardsToLog = cards.slice(0, maxCards);\n\n logger.debug(`[Pipeline] Provenance for top ${cardsToLog.length} cards:`);\n\n for (const card of cardsToLog) {\n logger.debug(`[Pipeline] ${card.cardId} (final score: ${card.score.toFixed(3)}):`);\n\n for (const entry of card.provenance) {\n const scoreChange = entry.score.toFixed(3);\n const action = entry.action.padEnd(9); // Align columns\n logger.debug(\n `[Pipeline] ${action} ${scoreChange} - ${entry.strategyName}: ${entry.reason}`\n );\n }\n }\n}\n\n// ============================================================================\n// PIPELINE\n// ============================================================================\n//\n// Executes a navigation pipeline: generator → filters → sorted results.\n//\n// Architecture:\n// cards = generator.getWeightedCards(limit, context)\n// cards = filter1.transform(cards, context)\n// cards = filter2.transform(cards, context)\n// cards = filter3.transform(cards, context)\n// return sorted(cards).slice(0, limit)\n//\n// Benefits:\n// - Clear separation: generators produce, filters transform\n// - No nested instantiation complexity\n// - Filters don't need to know about each other\n// - Shared context built once, passed to all stages\n//\n// ============================================================================\n\n/**\n * A navigation pipeline that runs a generator and applies filters sequentially.\n *\n * Implements StudyContentSource for backward compatibility with SessionController.\n *\n * ## Usage\n *\n * ```typescript\n * const pipeline = new Pipeline(\n * compositeGenerator, // or single generator\n * [eloDistanceFilter, interferenceFilter],\n * user,\n * course\n * );\n *\n * const cards = await pipeline.getWeightedCards(20);\n * ```\n */\n\n/**\n * Narrow capability surface for out-of-band, commit-free reads against a live\n * pipeline (see {@link getActivePipeline}). Kept minimal on purpose — consumers\n * get the forecast capability, not the whole `Pipeline` class.\n */\nexport interface PipelineForecaster {\n forecast(opts?: {\n hints?: ReplanHints;\n unseenOnly?: boolean;\n threshold?: number;\n limit?: number;\n }): Promise<WeightedCard[]>;\n}\n\nexport class Pipeline extends ContentNavigator implements PipelineForecaster {\n private generator: CardGenerator;\n private filters: CardFilter[];\n\n /**\n * Cached orchestration context. Course config and salt don't change within\n * a page load, so we build the orchestration context once and reuse it on\n * subsequent getWeightedCards() calls (e.g. mid-session replans).\n *\n * This eliminates a remote getCourseConfig() round trip per pipeline run.\n */\n private _cachedOrchestration: OrchestrationContext | null = null;\n\n /**\n * Hash of the strategy docs this pipeline was assembled from (see\n * versionStamps.ts), set by whoever builds it. Stamped on every run.\n */\n strategyHash?: string;\n\n /**\n * Persistent tag cache. Maps cardId → tag names.\n *\n * Tags are static within a session (they're set at card generation time),\n * so we cache them across pipeline runs. On replans, many of the same cards\n * reappear — cache hits avoid redundant remote getAppliedTagsBatch() queries.\n */\n private _tagCache: Map<string, string[]> = new Map();\n\n /**\n * One-shot replan hints. Applied after the filter chain on the next\n * getWeightedCards() call, then cleared.\n */\n private _ephemeralHints: ReplanHints | null = null;\n\n /**\n * The intake valve's clock (see regulators.ts), loaded from strategy state on\n * first use and kept in memory. Writes are chained so a presentation and a\n * run can't race each other's revision.\n */\n private _intakeClock: IntakeClockState | null = null;\n private _intakeClockWrite: Promise<void> = Promise.resolve();\n\n /**\n * Create a new pipeline.\n *\n * @param generator - The generator (or CompositeGenerator) that produces candidates\n * @param filters - Filters to apply sequentially (order doesn't matter for multipliers)\n * @param user - User database interface\n * @param course - Course database interface\n */\n constructor(\n generator: CardGenerator,\n filters: CardFilter[],\n user: UserDBInterface,\n course: CourseDBInterface\n ) {\n super();\n this.generator = generator;\n this.filters = filters;\n this.user = user;\n this.course = course;\n\n course\n .getCourseConfig()\n .then((cfg) => {\n logger.debug(`[pipeline] Crated pipeline for ${cfg.name}`);\n })\n .catch((e) => {\n logger.error(`[pipeline] Failed to lookup courseCfg: ${e}`);\n });\n // Toggle pipeline configuration logging:\n logPipelineConfig(generator, filters);\n\n // Register for debug API access\n registerPipelineForDebug(this);\n }\n\n /**\n * Set one-shot hints for the next pipeline run.\n * Consumed after one getWeightedCards() call, then cleared.\n *\n * Overrides ContentNavigator.setEphemeralHints() no-op.\n */\n override setEphemeralHints(hints: ReplanHints): void {\n this._ephemeralHints = hints;\n logger.info(`[Pipeline] Ephemeral hints set: ${JSON.stringify(hints)}`);\n }\n\n /**\n * Get weighted cards by running generator and applying filters.\n *\n * 1. Build shared context (user ELO, etc.)\n * 2. Get candidates from generator (passing context)\n * 3. Batch hydrate tags for all candidates\n * 4. Apply each filter sequentially\n * 5. Remove zero-score cards\n * 6. Sort by score descending\n * 7. Return top N\n *\n * @param limit - Maximum number of cards to return\n * @returns Cards sorted by score descending\n */\n async getWeightedCards(limit: number): Promise<GeneratorResult> {\n const t0 = performance.now();\n\n // Build shared context once\n const context = await this.buildContext();\n const tContext = performance.now();\n\n // Over-fetch from generator to give filters a wide candidate pool.\n // With local course DB the cost is negligible (~20ms for 500 cards).\n // Filters (hierarchy, letter gating, etc.) can be aggressive — a wide\n // pool ensures enough well-indicated candidates survive.\n const fetchLimit = 500;\n\n logger.debug(\n `[Pipeline] Fetching ${fetchLimit} candidates from generator '${this.generator.name}'`\n );\n\n // Get candidates from generator, passing context\n const generatorResult = await this.generator.getWeightedCards(fetchLimit, context);\n let cards = generatorResult.cards;\n const tGenerate = performance.now();\n const generatedCount = cards.length;\n\n // Merge generator-emitted hints with any externally supplied one-shot hints\n const mergedHints = mergeHints([this._ephemeralHints, generatorResult.hints]);\n this._ephemeralHints = mergedHints ?? null;\n \n // Capture generator breakdown for debugging (if CompositeGenerator)\n let generatorSummaries: GeneratorSummary[] | undefined;\n if ((this.generator as any).generators) {\n // This is a CompositeGenerator - extract per-generator info from provenance\n const genMap = new Map<string, { cards: WeightedCard[] }>();\n for (const card of cards) {\n const firstProv = card.provenance[0];\n if (firstProv) {\n const genName = firstProv.strategyName;\n if (!genMap.has(genName)) {\n genMap.set(genName, { cards: [] });\n }\n genMap.get(genName)!.cards.push(card);\n }\n }\n generatorSummaries = Array.from(genMap.entries()).map(([name, data]) => {\n // Reviews carry `reviewID`; everything else a generator emits is unseen.\n // (Reason text can't tell: the ELO generator's never says \"new card\".)\n const reviewCount = data.cards.filter((c) => c.reviewID).length;\n return {\n name,\n cardCount: data.cards.length,\n newCount: data.cards.length - reviewCount,\n reviewCount,\n topScore: Math.max(...data.cards.map((c) => c.score), 0),\n };\n });\n }\n\n logger.debug(`[Pipeline] Generator returned ${generatedCount} candidates`);\n\n // Batch hydrate tags before filters run\n cards = await this.hydrateTags(cards);\n const tHydrate = performance.now();\n \n // Keep a copy of all cards for debug capture (before filtering removes any)\n const allCardsBeforeFiltering = [...cards];\n\n // Pre-fetch any literal requireCards IDs that the generator didn't produce.\n // requireCards is a hard guarantee — required cards bypass the filter chain\n // and are injected directly into the final result by applyHints. We need\n // them present in allCardsBeforeFiltering for that injection to find them.\n // (Glob patterns are left to the existing pool-search behaviour.)\n const pendingHints = this._ephemeralHints;\n if (pendingHints?.requireCards?.length) {\n const poolIds = new Set(allCardsBeforeFiltering.map((c) => c.cardId));\n const missingIds = pendingHints.requireCards.filter(\n (p) => !p.includes('*') && !poolIds.has(p)\n );\n if (missingIds.length > 0) {\n const fetchedTags = await this.course!.getAppliedTagsBatch(missingIds);\n const courseId = this.course!.getCourseID();\n for (const cardId of missingIds) {\n allCardsBeforeFiltering.push({\n cardId,\n courseId,\n score: 1.0,\n tags: fetchedTags.get(cardId) ?? [],\n provenance: [],\n });\n }\n logger.info(\n `[Pipeline] Pre-fetched ${missingIds.length} required card(s) into pool: ${missingIds.join(', ')}`\n );\n }\n }\n\n // Apply filters sequentially, tracking impact\n // Track prescribed-origin cards through the filter chain for diagnostics\n const prescribedIds = new Set(\n cards\n .filter((c) => c.provenance.some((p) => p.strategy === 'prescribed'))\n .map((c) => c.cardId)\n );\n const filterImpacts: FilterImpact[] = [];\n // Scores as generated, so regulators can read the filters' net effect on each card.\n const generatedScores = new Map(cards.map((c) => [c.cardId, c.score]));\n // Cards a gate penalized: not ready, so regulators won't lift them.\n const gated = new Set<string>();\n // [perf] parked 2026-05 (pipeline-docs-workup) — uncomment to re-measure\n // const filterTimings: string[] = [];\n for (const filter of this.filters) {\n // const tFilterStart = performance.now();\n const beforeCount = cards.length;\n const beforeScores = new Map(cards.map((c) => [c.cardId, c.score]));\n cards = await filter.transform(cards, context);\n // filterTimings.push(`${filter.name}=${(performance.now() - tFilterStart).toFixed(0)}ms`);\n\n // Count boost/penalize/pass/removed for this filter\n let boosted = 0, penalized = 0, passed = 0;\n const removed = beforeCount - cards.length;\n\n // Undeclared filters count as gates (see CardFilter.kind).\n const kind = filter.kind ?? 'gate';\n for (const card of cards) {\n const before = beforeScores.get(card.cardId) ?? 0;\n if (card.score > before) boosted++;\n else if (card.score < before) {\n penalized++;\n if (kind === 'gate') gated.add(card.cardId);\n } else passed++;\n }\n filterImpacts.push({ name: filter.name, kind, boosted, penalized, passed, removed });\n\n // Report prescribed card fate through each filter\n if (prescribedIds.size > 0) {\n const survivingIds = new Set(cards.map((c) => c.cardId));\n const killedPrescribed = [...prescribedIds].filter((id) => !survivingIds.has(id));\n const zeroedPrescribed = cards\n .filter((c) => prescribedIds.has(c.cardId) && c.score === 0)\n .map((c) => c.cardId);\n if (killedPrescribed.length > 0 || zeroedPrescribed.length > 0) {\n logger.info(\n `[Pipeline] Filter '${filter.name}' impact on prescribed cards: ` +\n (killedPrescribed.length > 0 ? `removed=[${killedPrescribed.join(', ')}] ` : '') +\n (zeroedPrescribed.length > 0 ? `zeroed=[${zeroedPrescribed.join(', ')}]` : '')\n );\n // Remove killed ones from tracking set\n killedPrescribed.forEach((id) => prescribedIds.delete(id));\n }\n }\n\n logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeScores.size} → ${cards.length} cards (↑${boosted} ↓${penalized} =${passed})`);\n }\n\n // Remove zero-score cards (hard filtered). The debug report still wants\n // them: they're the answer to \"which filter sank this card?\"\n const scoredCards = cards;\n cards = cards.filter((c) => c.score > 0);\n\n // Regulators: class-level pressure between reviews and new cards, from the\n // filtered scores (see regulators.ts). Before hints, so session intent wins.\n const regulators = await this.regulate(cards, generatedScores, gated);\n\n // Apply ephemeral hints (one-shot, post-filter)\n const hints = this._ephemeralHints;\n if (hints) {\n this._ephemeralHints = null; // consume\n cards = this.applyHints(cards, hints, allCardsBeforeFiltering);\n }\n\n // Stage 3: diversity re-rank (post-filter, post-hints, pre-sort). Demotes\n // cards whose distinctive tags already appeared among higher-ranked\n // candidates so a single answer/concept can't monopolise the head of the\n // queue. Tag-agnostic (rarity-weighted overlap — no namespace privileged)\n // and expressed as score penalties so the ordering survives the final sort\n // here AND the SourceMixer's score-descending re-sort downstream.\n cards = diversityRerank(cards);\n\n // Sort by score descending\n cards.sort((a, b) => b.score - a.score);\n\n // Return top N\n const tFilter = performance.now();\n const result = cards.slice(0, limit);\n\n logger.info(\n `[Pipeline:timing] total=${(tFilter - t0).toFixed(0)}ms ` +\n `(context=${(tContext - t0).toFixed(0)} generate=${(tGenerate - tContext).toFixed(0)} ` +\n `hydrate=${(tHydrate - tGenerate).toFixed(0)} filter=${(tFilter - tHydrate).toFixed(0)})`\n );\n\n // Toggle execution summary logging:\n const topScores = result.slice(0, 3).map((c) => c.score);\n logExecutionSummary(\n this.generator.name,\n generatedCount,\n this.filters.length,\n result.length,\n topScores,\n filterImpacts\n );\n\n // Toggle verbose result listing:\n logResultCards(result);\n\n // Toggle provenance logging (shows scoring history for top cards):\n logCardProvenance(result, 3);\n\n // Capture run for debug API\n try {\n const courseConfig = await this.course?.getCourseConfig().catch(() => undefined);\n const courseName = courseConfig?.name;\n // Pass the full post-filter sorted array; buildRunReport retains all\n // selected cards plus the top-N highest-scoring near-misses and\n // summarizes the discarded tail (see DISCARDED_KEEP_TOP). This keeps\n // showCard() useful for \"why didn't this rank?\" inspection without\n // pinning hundreds of low-score candidates' provenance per run.\n // `cards` is the post-filter, post-hints, sorted array.\n const report = buildRunReport(\n this.course?.getCourseID() || 'unknown',\n courseName,\n this.generator.name,\n generatorSummaries,\n generatedCount,\n filterImpacts,\n cards,\n result,\n context.userElo,\n hints?? undefined,\n scoredCards,\n regulators\n );\n const versions = {\n ...(this.strategyHash ? { strategies: this.strategyHash } : {}),\n ...(courseConfig?.contentVersion ? { content: courseConfig.contentVersion } : {}),\n };\n captureRun({ ...report, ...(Object.keys(versions).length ? { versions } : {}) });\n } catch (e) {\n logger.debug(`[Pipeline] Failed to capture debug run: ${e}`);\n }\n\n return { cards: result };\n }\n\n /**\n * Batch hydrate tags for all cards.\n *\n * Fetches tags for all cards in a single database query and attaches them\n * to the WeightedCard objects. Filters can then use card.tags instead of\n * making individual getAppliedTags() calls.\n *\n * Uses a persistent tag cache across pipeline runs — tags are static within\n * a session, so cards seen in a prior run (e.g. before a replan) don't\n * require a second DB query.\n *\n * @param cards - Cards to hydrate\n * @returns Cards with tags populated\n */\n private async hydrateTags(cards: WeightedCard[]): Promise<WeightedCard[]> {\n if (cards.length === 0) {\n return cards;\n }\n\n // Separate cards with cached tags from those needing a DB query\n const uncachedIds: string[] = [];\n for (const card of cards) {\n if (!this._tagCache.has(card.cardId)) {\n uncachedIds.push(card.cardId);\n }\n }\n\n // Only query the DB for cards not already in cache\n if (uncachedIds.length > 0) {\n const freshTags = await this.course!.getAppliedTagsBatch(uncachedIds);\n for (const [cardId, tags] of freshTags) {\n this._tagCache.set(cardId, tags);\n }\n }\n\n // Build the tagsByCard map from cache (for logging compatibility)\n const tagsByCard = new Map<string, string[]>();\n for (const card of cards) {\n tagsByCard.set(card.cardId, this._tagCache.get(card.cardId) ?? []);\n }\n\n // Toggle tag hydration logging:\n logTagHydration(cards, tagsByCard);\n\n return cards.map((card) => ({\n ...card,\n tags: this._tagCache.get(card.cardId) ?? [],\n }));\n }\n\n // ---------------------------------------------------------------------------\n // Ephemeral hints application\n // ---------------------------------------------------------------------------\n\n /**\n * Apply one-shot replan hints to the post-filter card set.\n *\n * Order of operations:\n * 1. Exclude (remove unwanted cards)\n * 2. Boost (multiply scores)\n * 3. Require (inject must-have cards from the full pre-filter pool)\n *\n * @param cards - Post-filter cards (score > 0)\n * @param hints - The ephemeral hints to apply\n * @param allCards - Full pre-filter card pool (for require injection)\n */\n private applyHints(\n cards: WeightedCard[],\n hints: ReplanHints,\n allCards: WeightedCard[]\n ): WeightedCard[] {\n const beforeCount = cards.length;\n\n // 1. Exclude\n if (hints.excludeCards?.length) {\n cards = cards.filter(\n (c) => !hints.excludeCards!.some((pat) => globMatch(c.cardId, pat))\n );\n }\n if (hints.excludeTags?.length) {\n cards = cards.filter(\n (c) => !hints.excludeTags!.some((pat) => cardMatchesTagPattern(c, pat))\n );\n }\n\n // 2. Boost\n if (hints.boostTags) {\n for (const [pattern, factor] of Object.entries(hints.boostTags)) {\n for (const card of cards) {\n if (cardMatchesTagPattern(card, pattern)) {\n card.score *= factor;\n card.provenance.push({\n strategy: 'ephemeralHint',\n strategyId: 'ephemeral-hint',\n strategyName: hints._label ? `Replan Hint (${hints._label})` : 'Replan Hint',\n action: 'boosted',\n score: card.score,\n reason: `boostTag ${pattern} ×${factor}`,\n });\n }\n }\n }\n }\n if (hints.boostCards) {\n for (const [pattern, factor] of Object.entries(hints.boostCards)) {\n for (const card of cards) {\n if (globMatch(card.cardId, pattern)) {\n card.score *= factor;\n card.provenance.push({\n strategy: 'ephemeralHint',\n strategyId: 'ephemeral-hint',\n strategyName: hints._label ? `Replan Hint (${hints._label})` : 'Replan Hint',\n action: 'boosted',\n score: card.score,\n reason: `boostCard ${pattern} ×${factor}`,\n });\n }\n }\n }\n }\n\n // 3. Require — ensure mandatory cards have floor score and are in the pool\n const cardIds = new Set(cards.map((c) => c.cardId));\n const cardMap = new Map(cards.map((c) => [c.cardId, c]));\n const hintLabel = hints._label ? `Replan Hint (${hints._label})` : 'Replan Hint';\n\n const applyRequirement = (card: WeightedCard, reason: string) => {\n const mandatoryScore = Number.POSITIVE_INFINITY;\n const existing = cardMap.get(card.cardId);\n\n if (existing) {\n // If already in the pool, upgrade to mandatory score if not already infinite\n if (existing.score < mandatoryScore) {\n existing.score = mandatoryScore;\n existing.provenance.push({\n strategy: 'ephemeralHint',\n strategyId: 'ephemeral-hint',\n strategyName: hintLabel,\n action: 'boosted',\n score: mandatoryScore,\n reason: `${reason} (upgrade to mandatory score)`,\n });\n }\n } else {\n // If missing, inject from the full pool\n cards.push({\n ...card,\n score: mandatoryScore,\n provenance: [\n ...card.provenance,\n {\n strategy: 'ephemeralHint',\n strategyId: 'ephemeral-hint',\n strategyName: hintLabel,\n action: 'boosted',\n score: mandatoryScore,\n reason,\n },\n ],\n });\n cardIds.add(card.cardId);\n cardMap.set(card.cardId, cards[cards.length - 1]);\n }\n };\n\n if (hints.requireCards?.length) {\n for (const pattern of hints.requireCards) {\n // First check candidates already in the pool\n for (const cardId of cardIds) {\n if (globMatch(cardId, pattern)) {\n applyRequirement(cardMap.get(cardId)!, `requireCard ${pattern}`);\n }\n }\n // Then check full pool for injection\n for (const card of allCards) {\n if (globMatch(card.cardId, pattern)) {\n applyRequirement(card, `requireCard ${pattern}`);\n }\n }\n }\n }\n if (hints.requireTags?.length) {\n for (const pattern of hints.requireTags) {\n // First check candidates already in the pool\n for (const cardId of cardIds) {\n const card = cardMap.get(cardId)!;\n if (cardMatchesTagPattern(card, pattern)) {\n applyRequirement(card, `requireTag ${pattern}`);\n }\n }\n // Then check full pool for injection\n for (const card of allCards) {\n if (cardMatchesTagPattern(card, pattern)) {\n applyRequirement(card, `requireTag ${pattern}`);\n }\n }\n }\n }\n\n logger.info(`[Pipeline] Hints applied: ${beforeCount} → ${cards.length} cards`);\n\n return cards;\n }\n\n /**\n * The regulator stage: measure each class's pressure and scale it.\n *\n * - Review mass: every due review's SRS urgency times the filters' net\n * effect on it.\n * - Intake: servable hours since a new card was presented, applied only to\n * eligible new cards (no gate penalized them). With none eligible, the\n * clock freezes.\n *\n * Mutates `cards` in place; returns the readings for the run report.\n */\n private async regulate(\n cards: WeightedCard[],\n generatedScores: ReadonlyMap<string, number>,\n gated: Set<string>\n ): Promise<RegulatorReading[]> {\n const config = DEFAULT_REGULATOR_CONFIG;\n const reviews = cards.filter((c) => c.reviewID);\n const newCards = cards.filter((c) => !c.reviewID);\n const eligibleNew = newCards.filter((c) => !gated.has(c.cardId));\n\n const mass = reviewMassReading(reviews, generatedScores, config.reviewMass);\n applyReading(reviews, mass);\n noteReviewPressure(this.course!.getCourseID(), {\n mass: mass.urgency,\n healthyMass: config.reviewMass.healthyMass,\n rate: config.reviewMass.rate,\n multiplier: mass.multiplier,\n });\n\n const now = Date.now();\n const clock = await this.loadIntakeClock(now);\n const stepped = stepIntakeClock(clock, now, eligibleNew.length);\n if (stepped !== clock) this.saveIntakeClock(stepped);\n const intake = intakeReading(\n stepped,\n now,\n { eligibleNew: eligibleNew.length, newCandidates: newCards.length },\n config.intake\n );\n applyReading(eligibleNew, intake);\n\n logger.info(\n `[Pipeline:regulators] review mass ${mass.urgency.toFixed(1)} over ${reviews.length} due → ` +\n `×${mass.multiplier.toFixed(2)}; intake ${intake.urgency.toFixed(1)}h, ` +\n `${eligibleNew.length}/${newCards.length} new eligible → ×${intake.multiplier.toFixed(2)}`\n );\n return [mass, intake];\n }\n\n /**\n * A card was presented. A new card's first presentation discharges the\n * intake valve: its clock restarts. Called by the SessionController.\n */\n notePresented(card: { cardId: string; courseId: string; status: string }): void {\n if (card.status !== 'new' || card.courseId !== this.course?.getCourseID()) return;\n this.saveIntakeClock(resetIntakeClock(Date.now()));\n }\n\n private async loadIntakeClock(nowMs: number): Promise<IntakeClockState> {\n if (this._intakeClock) return this._intakeClock;\n let stored: IntakeClockState | null = null;\n try {\n stored = await this.user!.getStrategyState<IntakeClockState>(\n this.course!.getCourseID(),\n INTAKE_CLOCK_KEY\n );\n } catch (e) {\n logger.warn(`[Pipeline:regulators] Could not read the intake clock: ${e}`);\n }\n if (stored) {\n this._intakeClock = stored;\n } else {\n // No clock yet: start it now.\n this.saveIntakeClock(resetIntakeClock(nowMs));\n }\n return this._intakeClock!;\n }\n\n private saveIntakeClock(state: IntakeClockState): void {\n this._intakeClock = state;\n const courseId = this.course!.getCourseID();\n this._intakeClockWrite = this._intakeClockWrite\n .then(() => this.user!.putStrategyState(courseId, INTAKE_CLOCK_KEY, state))\n .catch((e) => logger.warn(`[Pipeline:regulators] Could not save the intake clock: ${e}`));\n }\n\n /**\n * Build shared context for generator and filters.\n *\n * Called once per getWeightedCards() invocation.\n * Contains data that the generator and multiple filters might need.\n *\n * The context satisfies both GeneratorContext and FilterContext interfaces.\n */\n private async buildContext(): Promise<GeneratorContext & FilterContext> {\n let userElo = 1000; // Default ELO\n let userCourseElo: CourseElo | undefined;\n\n try {\n const courseReg = await this.user!.getCourseRegDoc(this.course!.getCourseID());\n userCourseElo = toCourseElo(courseReg.elo);\n userElo = userCourseElo.global.score;\n } catch (e) {\n logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);\n }\n\n // Reuse cached orchestration context if available (course config is stable\n // within a page load). This avoids a remote getCourseConfig() call on\n // subsequent pipeline runs (e.g. mid-session replans).\n if (!this._cachedOrchestration) {\n this._cachedOrchestration = await createOrchestrationContext(this.user!, this.course!);\n }\n const orchestration = this._cachedOrchestration;\n\n return {\n user: this.user!,\n course: this.course!,\n userElo,\n ...(userCourseElo ? { userCourseElo } : {}),\n orchestration,\n };\n }\n\n /**\n * Get the course ID for this pipeline.\n */\n getCourseID(): string {\n return this.course!.getCourseID();\n }\n\n /**\n * Get orchestration context for outcome recording.\n */\n async getOrchestrationContext(): Promise<OrchestrationContext> {\n return createOrchestrationContext(this.user!, this.course!);\n }\n\n /**\n * Get IDs of all strategies in this pipeline.\n * Used to record which strategies contributed to an outcome.\n */\n getStrategyIds(): string[] {\n const ids: string[] = [];\n\n const extractId = (obj: any): string | null => {\n // Check for strategyId property (ContentNavigator, WeightedFilter)\n if (obj.strategyId) return obj.strategyId;\n return null;\n };\n\n // Generator(s)\n const genId = extractId(this.generator);\n if (genId) ids.push(genId);\n\n // Inspect CompositeGenerator children (accessing private field via cast)\n if ((this.generator as any).generators && Array.isArray((this.generator as any).generators)) {\n (this.generator as any).generators.forEach((g: any) => {\n const subId = extractId(g);\n if (subId) ids.push(subId);\n });\n }\n\n // Filters\n for (const filter of this.filters) {\n const fId = extractId(filter);\n if (fId) ids.push(fId);\n }\n\n return [...new Set(ids)];\n }\n\n // ---------------------------------------------------------------------------\n // Tag ELO diagnostic\n // ---------------------------------------------------------------------------\n\n /**\n * Get the user's per-tag ELO data for specified tags (or all tags).\n * Useful for diagnosing why hierarchy gates are open/closed.\n */\n async getTagEloStatus(\n tagFilter?: string | string[]\n ): Promise<Record<string, { score: number; count: number }>> {\n const courseReg = await this.user!.getCourseRegDoc(this.course!.getCourseID());\n const courseElo = toCourseElo(courseReg.elo);\n\n const result: Record<string, { score: number; count: number }> = {};\n\n if (!tagFilter) {\n // Return all tags\n for (const [tag, data] of Object.entries(courseElo.tags)) {\n result[tag] = { score: data.score, count: data.count };\n }\n } else {\n const patterns = Array.isArray(tagFilter) ? tagFilter : [tagFilter];\n for (const pattern of patterns) {\n const regex = globToRegex(pattern);\n for (const [tag, data] of Object.entries(courseElo.tags)) {\n if (regex.test(tag)) {\n result[tag] = { score: data.score, count: data.count };\n }\n }\n }\n }\n\n return result;\n }\n\n // ---------------------------------------------------------------------------\n // Card-space diagnostic\n // ---------------------------------------------------------------------------\n\n /**\n * Commit-free forecast: score the user's full card space through the filter\n * chain and return the cards that are currently *reachable* (score >=\n * threshold), optionally nudged by caller-supplied hints and/or restricted\n * to cards the user hasn't seen yet.\n *\n * This is a GENERIC primitive — it returns scored, tag-hydrated cards and\n * stops there. It has no knowledge of any particular tag convention; callers\n * decide what the surviving cards mean (e.g. filter to their own \"intro\"\n * tag family). Nothing is written and no session is started.\n *\n * The optional `hints` are the \"out-of-band kick\": they run through the same\n * {@link applyHints} path a live replan uses, so the two semantics carry over —\n * - `boostTags`/`boostCards` reweight *within* gating (a gated score-0 card\n * stays out), and\n * - `requireTags`/`requireCards` inject from the full pre-filter pool,\n * *bypassing* gating (use when you want a card regardless of reachability).\n * Note `unseenOnly` is applied LAST, so it can drop a `require`d card that the\n * user has already seen — pass `unseenOnly: false` if that matters.\n *\n * Cost note: like {@link diagnoseCardSpace}, this scans every card through the\n * filters, so it's heavier than a normal replan. Intended for one-shot\n * out-of-band use (e.g. a session-end \"what's next\" snapshot), not the hot path.\n *\n * @param opts.hints Optional ephemeral hints to apply after the filter chain.\n * @param opts.unseenOnly Only return cards the user hasn't encountered (default true).\n * @param opts.threshold Min score to count as reachable (default 0.10).\n * @param opts.limit Optional cap on results (already sorted desc).\n */\n async forecast(opts?: {\n hints?: ReplanHints;\n unseenOnly?: boolean;\n threshold?: number;\n limit?: number;\n }): Promise<WeightedCard[]> {\n const threshold = opts?.threshold ?? 0.10;\n const unseenOnly = opts?.unseenOnly ?? true;\n\n const courseId = this.course!.getCourseID();\n const allCardIds = await this.course!.getAllCardIds();\n\n let cards: WeightedCard[] = allCardIds.map((cardId) => ({\n cardId,\n courseId,\n score: 1.0,\n provenance: [],\n }));\n\n cards = await this.hydrateTags(cards);\n // Snapshot the full pool before filtering, for require-injection in applyHints.\n const fullPool = cards.slice();\n\n const context = await this.buildContext();\n for (const filter of this.forecastFilters()) {\n cards = await filter.transform(cards, context);\n }\n\n if (opts?.hints) {\n cards = this.applyHints(cards, opts.hints, fullPool);\n }\n\n cards = cards.filter((c) => c.score >= threshold);\n\n if (unseenOnly) {\n let encountered: Set<string>;\n try {\n encountered = new Set(await this.user!.getSeenCards(courseId));\n } catch {\n encountered = new Set();\n }\n cards = cards.filter((c) => !encountered.has(c.cardId));\n }\n\n cards.sort((a, b) => b.score - a.score);\n return opts?.limit ? cards.slice(0, opts.limit) : cards;\n }\n\n /**\n * The filters a forecast or card-space scan applies. Those start every card at\n * 1.0 without a generator, so they skip `liveOnly` filters (ELO distance),\n * which only make sense against generator scores.\n */\n private forecastFilters(): CardFilter[] {\n return this.filters.filter((f) => !f.liveOnly);\n }\n\n /**\n * Scan every card in the course through the filter chain and report\n * how many are \"well indicated\" (score >= threshold) for the current user.\n *\n * Also reports how many well-indicated cards the user has NOT yet encountered.\n *\n * Exposed via `window.skuilder.pipeline.diagnoseCardSpace()`.\n */\n async diagnoseCardSpace(opts?: { threshold?: number }): Promise<CardSpaceDiagnosis> {\n const THRESHOLD = opts?.threshold ?? 0.10;\n const t0 = performance.now();\n\n // 1. Get all card IDs\n const allCardIds = await this.course!.getAllCardIds();\n\n // 2. Build dummy WeightedCards (score=1.0, no provenance)\n let cards: WeightedCard[] = allCardIds.map((cardId) => ({\n cardId,\n courseId: this.course!.getCourseID(),\n score: 1.0,\n provenance: [],\n }));\n\n // 3. Hydrate tags\n cards = await this.hydrateTags(cards);\n\n // 4. Run through filters\n const context = await this.buildContext();\n const filterBreakdown: Array<{ name: string; wellIndicated: number }> = [];\n\n // Track cumulative filter effects\n for (const filter of this.forecastFilters()) {\n cards = await filter.transform(cards, context);\n const wi = cards.filter((c) => c.score >= THRESHOLD).length;\n filterBreakdown.push({ name: filter.name, wellIndicated: wi });\n }\n\n // 5. Count well-indicated\n const wellIndicated = cards.filter((c) => c.score >= THRESHOLD);\n const wellIndicatedIds = new Set(wellIndicated.map((c) => c.cardId));\n\n // 6. Get encountered cards\n let encounteredIds: Set<string>;\n try {\n const courseId = this.course!.getCourseID();\n const seenCards = await this.user!.getSeenCards(courseId);\n encounteredIds = new Set(seenCards);\n } catch {\n encounteredIds = new Set();\n }\n\n const wellIndicatedNew = wellIndicated.filter((c) => !encounteredIds.has(c.cardId));\n\n // 7. Group by card type\n const byType = new Map<string, { total: number; wellIndicated: number; new: number }>();\n for (const card of cards) {\n const type = card.cardId.split('-')[1] || 'unknown'; // c-ws-... → ws, c-intro-... → intro, etc.\n if (!byType.has(type)) {\n byType.set(type, { total: 0, wellIndicated: 0, new: 0 });\n }\n const entry = byType.get(type)!;\n entry.total++;\n if (card.score >= THRESHOLD) {\n entry.wellIndicated++;\n if (!encounteredIds.has(card.cardId)) entry.new++;\n }\n }\n\n const elapsed = performance.now() - t0;\n\n const result: CardSpaceDiagnosis = {\n totalCards: allCardIds.length,\n threshold: THRESHOLD,\n wellIndicated: wellIndicatedIds.size,\n encountered: encounteredIds.size,\n wellIndicatedNew: wellIndicatedNew.length,\n byType: Object.fromEntries(byType),\n filterBreakdown,\n elapsedMs: Math.round(elapsed),\n };\n\n // Log to console\n logger.print(`[Pipeline:diagnose] Card space scan (${result.elapsedMs}ms):`);\n logger.print(`[Pipeline:diagnose] Total cards: ${result.totalCards}`);\n logger.print(`[Pipeline:diagnose] Well-indicated (score >= ${THRESHOLD}): ${result.wellIndicated}`);\n logger.print(`[Pipeline:diagnose] Encountered: ${result.encountered}`);\n logger.print(`[Pipeline:diagnose] Well-indicated & new: ${result.wellIndicatedNew}`);\n logger.print(`[Pipeline:diagnose] By type:`);\n for (const [type, counts] of byType) {\n logger.print(\n `[Pipeline:diagnose] ${type}: ${counts.wellIndicated}/${counts.total} well-indicated, ${counts.new} new`\n );\n }\n logger.print(`[Pipeline:diagnose] After each filter:`);\n for (const fb of filterBreakdown) {\n logger.print(`[Pipeline:diagnose] ${fb.name}: ${fb.wellIndicated} well-indicated`);\n }\n\n return result;\n }\n\n}\n\n/**\n * Diagnosis of the full card space for the current user.\n */\nexport interface CardSpaceDiagnosis {\n totalCards: number;\n threshold: number;\n wellIndicated: number;\n encountered: number;\n wellIndicatedNew: number;\n byType: Record<string, { total: number; wellIndicated: number; new: number }>;\n filterBreakdown: Array<{ name: string; wellIndicated: number }>;\n elapsedMs: number;\n}\n"],"mappings":";;;;;;;;;;;;;;AA8CA,SAAS,YAAY,SAAyB;CAE5C,MAAM,gBADU,QAAQ,QAAQ,sBAAsB,OAAO,CAC/B,QAAQ,OAAO,KAAK;AAClD,QAAO,IAAI,OAAO,IAAI,cA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AAO,MAAM,sCAAsC,OAAO,aAAa;AACvE,SAAO,MAAM,kDAAkD,UAAU,KAAK,OAAO,gBAAgB;AACrG,SAAO,MAAM,sCAAsC,OAAO,cAAc;AACxE,SAAO,MAAM,+CAA+C,OAAO,mBAAmB;AACtF,SAAO,MAAM,iCAAiC;AAC9C,OAAK,MAAM,CAAC,MAAM,WAAW,OAC3B,QAAO,MACL,2BAA2B,KAAK,IAAI,OAAO,cAAc,GAAG,OAAO,MAAM,mBAAmB,OAAO,IAAI,MACxG;AAEH,SAAO,MAAM,2CAA2C;AACxD,OAAK,MAAM,MAAM,gBACf,QAAO,MAAM,2BAA2B,GAAG,KAAK,IAAI,GAAG,cAAc,iBAAiB;AAGxF,SAAO"}
|
|
1
|
+
{"version":3,"file":"Pipeline.mjs","names":[],"sources":["../../../src/core/navigators/Pipeline.ts"],"sourcesContent":["import { toCourseElo, type CourseElo } 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 { CardFilter, FilterContext } from './filters/types';\nimport type { CardGenerator, GeneratorContext } from './generators/types';\nimport type { GeneratorResult } from './generators/types';\nimport { logger } from '../../util/logger';\nimport { perfMeasure } from '../../util/perfMarks';\nimport { createOrchestrationContext, OrchestrationContext } from '../orchestration';\nimport { captureRun, buildRunReport, registerPipelineForDebug, type GeneratorSummary, type FilterImpact } from './PipelineDebugger';\nimport { diversityRerank } from './diversityRerank';\nimport {\n applyReading,\n DEFAULT_REGULATOR_CONFIG,\n INTAKE_CLOCK_KEY,\n intakeReading,\n resetIntakeClock,\n reviewMassReading,\n stepIntakeClock,\n type IntakeClockState,\n type RegulatorReading,\n} from './regulators';\nimport { noteReviewPressure } from './SrsDebugger';\n\n// ============================================================================\n// REPLAN HINTS\n// ============================================================================\n//\n// Ephemeral, one-shot scoring hints passed at replan time.\n// Applied after the filter chain, consumed after one pipeline run.\n//\n// Tag patterns support glob-style matching:\n// 'gpc:exercise:t-T' — exact match\n// 'gpc:intro:*' — all intro tags\n// 'gpc:exercise:t-*' — all t-variant exercises\n//\n\n// ReplanHints is defined in generators/types — re-export for consumers that import from Pipeline\nimport type { ReplanHints } from './generators/types';\nexport type { ReplanHints };\n\n/**\n * Convert a glob pattern (with `*` wildcards) to a RegExp.\n * Only `*` is supported as a wildcard (matches any characters).\n */\nfunction globToRegex(pattern: string): RegExp {\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const withWildcards = escaped.replace(/\\*/g, '.*');\n return new RegExp(`^${withWildcards}$`);\n}\n\n/** Test whether a string matches a glob pattern. */\nfunction globMatch(value: string, pattern: string): boolean {\n if (!pattern.includes('*')) return value === pattern;\n return globToRegex(pattern).test(value);\n}\n\n/** Test whether any of a card's tags match a glob pattern. */\nfunction cardMatchesTagPattern(card: WeightedCard, pattern: string): boolean {\n return (card.tags ?? []).some((tag) => globMatch(tag, pattern));\n}\n\nexport function mergeHints(allHints: Array<ReplanHints | null | undefined>): ReplanHints | undefined {\n const defined = allHints.filter((h): h is ReplanHints => h !== null && h !== undefined);\n if (defined.length === 0) return undefined;\n\n const merged: ReplanHints = {};\n\n const boostTags: Record<string, number> = {};\n for (const hints of defined) {\n for (const [pattern, factor] of Object.entries(hints.boostTags ?? {})) {\n boostTags[pattern] = (boostTags[pattern] ?? 1) * factor;\n }\n }\n if (Object.keys(boostTags).length > 0) {\n merged.boostTags = boostTags;\n }\n\n const boostCards: Record<string, number> = {};\n for (const hints of defined) {\n for (const [pattern, factor] of Object.entries(hints.boostCards ?? {})) {\n boostCards[pattern] = (boostCards[pattern] ?? 1) * factor;\n }\n }\n if (Object.keys(boostCards).length > 0) {\n merged.boostCards = boostCards;\n }\n\n const concatUnique = (\n field: 'requireTags' | 'requireCards' | 'excludeTags' | 'excludeCards'\n ): void => {\n const values = defined.flatMap((h) => h[field] ?? []);\n if (values.length > 0) {\n merged[field] = [...new Set(values)];\n }\n };\n\n concatUnique('requireTags');\n concatUnique('requireCards');\n concatUnique('excludeTags');\n concatUnique('excludeCards');\n\n const labels = defined.map((h) => h._label).filter(Boolean);\n if (labels.length > 0) {\n merged._label = labels.join('; ');\n }\n\n return Object.keys(merged).length > 0 ? merged : undefined;\n}\n\n// ============================================================================\n// PIPELINE LOGGING HELPERS\n// ============================================================================\n//\n// Focused logging functions that can be toggled by commenting single lines.\n// Use these to inspect pipeline behavior in development/production.\n//\n\n/**\n * Log pipeline configuration on construction.\n * Shows generator and filter chain structure.\n */\nfunction logPipelineConfig(generator: CardGenerator, filters: CardFilter[]): void {\n const filterList =\n filters.length > 0 ? '\\n - ' + filters.map((f) => f.name).join('\\n - ') : ' none';\n\n logger.info(\n `[Pipeline] Configuration:\\n` + ` Generator: ${generator.name}\\n` + ` Filters:${filterList}`\n );\n}\n\n/**\n * Log tag hydration results.\n * Shows effectiveness of batch query (how many cards/tags were hydrated).\n */\nfunction logTagHydration(cards: WeightedCard[], tagsByCard: Map<string, string[]>): void {\n const totalTags = Array.from(tagsByCard.values()).reduce((sum, tags) => sum + tags.length, 0);\n const cardsWithTags = Array.from(tagsByCard.values()).filter((tags) => tags.length > 0).length;\n\n logger.debug(\n `[Pipeline] Tag hydration: ${cards.length} cards, ` +\n `${cardsWithTags} have tags (${totalTags} total tags) - single batch query`\n );\n}\n\n/**\n * Log pipeline execution summary.\n * Shows complete flow from generator through filters to final results.\n */\nfunction logExecutionSummary(\n generatorName: string,\n generatedCount: number,\n filterCount: number,\n finalCount: number,\n topScores: number[],\n filterImpacts: Array<{ name: string; boosted: number; penalized: number; passed: number }>\n): void {\n const scoreDisplay =\n topScores.length > 0 ? topScores.map((s) => s.toFixed(2)).join(', ') : 'none';\n\n let filterSummary = '';\n if (filterImpacts.length > 0) {\n const impacts = filterImpacts.map((f) => {\n const parts: string[] = [];\n if (f.boosted > 0) parts.push(`+${f.boosted}`);\n if (f.penalized > 0) parts.push(`-${f.penalized}`);\n if (f.passed > 0) parts.push(`=${f.passed}`);\n return `${f.name}: ${parts.join('/')}`;\n });\n filterSummary = `\\n Filter impact: ${impacts.join(', ')}`;\n }\n\n logger.info(\n `[Pipeline] Execution: ${generatorName} produced ${generatedCount} → ` +\n `${filterCount} filters → ${finalCount} results (top scores: ${scoreDisplay})` +\n filterSummary +\n `\\n 💡 Inspect: window.skuilder.pipeline`\n );\n}\n\n/**\n * Log all result cards with score, cardId, and key provenance.\n * Toggle: set VERBOSE_RESULTS = true to enable.\n */\nconst VERBOSE_RESULTS = false;\n\nfunction logResultCards(cards: WeightedCard[]): void {\n if (!VERBOSE_RESULTS || cards.length === 0) return;\n\n logger.info(`[Pipeline] Results (${cards.length} cards):`);\n for (let i = 0; i < cards.length; i++) {\n const c = cards[i];\n const tags = c.tags?.slice(0, 3).join(', ') || '';\n const filters = c.provenance\n .filter((p) => p.strategy === 'hierarchyDefinition' || p.strategy === 'priorityDefinition' || p.strategy === 'interferenceFilter' || p.strategy === 'letterGating' || p.strategy === 'ephemeralHint' || p.strategy === 'diversityRerank')\n .map((p) => {\n const arrow = p.action === 'boosted' ? '↑' : p.action === 'penalized' ? '↓' : '=';\n return `${p.strategyName}${arrow}${p.score.toFixed(2)}`;\n })\n .join(' | ');\n logger.info(\n `[Pipeline] ${String(i + 1).padStart(2)}. ${c.score.toFixed(4)} ${c.cardId} [${tags}]${filters ? ` {${filters}}` : ''}`\n );\n }\n}\n\n/**\n * Log provenance trails for cards.\n * Shows the complete scoring history for each card through the pipeline.\n * Useful for debugging why cards scored the way they did.\n */\nfunction logCardProvenance(cards: WeightedCard[], maxCards: number = 3): void {\n const cardsToLog = cards.slice(0, maxCards);\n\n logger.debug(`[Pipeline] Provenance for top ${cardsToLog.length} cards:`);\n\n for (const card of cardsToLog) {\n logger.debug(`[Pipeline] ${card.cardId} (final score: ${card.score.toFixed(3)}):`);\n\n for (const entry of card.provenance) {\n const scoreChange = entry.score.toFixed(3);\n const action = entry.action.padEnd(9); // Align columns\n logger.debug(\n `[Pipeline] ${action} ${scoreChange} - ${entry.strategyName}: ${entry.reason}`\n );\n }\n }\n}\n\n// ============================================================================\n// PIPELINE\n// ============================================================================\n//\n// Executes a navigation pipeline: generator → filters → sorted results.\n//\n// Architecture:\n// cards = generator.getWeightedCards(limit, context)\n// cards = filter1.transform(cards, context)\n// cards = filter2.transform(cards, context)\n// cards = filter3.transform(cards, context)\n// return sorted(cards).slice(0, limit)\n//\n// Benefits:\n// - Clear separation: generators produce, filters transform\n// - No nested instantiation complexity\n// - Filters don't need to know about each other\n// - Shared context built once, passed to all stages\n//\n// ============================================================================\n\n/**\n * A navigation pipeline that runs a generator and applies filters sequentially.\n *\n * Implements StudyContentSource for backward compatibility with SessionController.\n *\n * ## Usage\n *\n * ```typescript\n * const pipeline = new Pipeline(\n * compositeGenerator, // or single generator\n * [eloDistanceFilter, interferenceFilter],\n * user,\n * course\n * );\n *\n * const cards = await pipeline.getWeightedCards(20);\n * ```\n */\n\n/**\n * Narrow capability surface for out-of-band, commit-free reads against a live\n * pipeline (see {@link getActivePipeline}). Kept minimal on purpose — consumers\n * get the forecast capability, not the whole `Pipeline` class.\n */\nexport interface PipelineForecaster {\n forecast(opts?: {\n hints?: ReplanHints;\n unseenOnly?: boolean;\n threshold?: number;\n limit?: number;\n }): Promise<WeightedCard[]>;\n}\n\nexport class Pipeline extends ContentNavigator implements PipelineForecaster {\n private generator: CardGenerator;\n private filters: CardFilter[];\n\n /**\n * Cached orchestration context. Course config and salt don't change within\n * a page load, so we build the orchestration context once and reuse it on\n * subsequent getWeightedCards() calls (e.g. mid-session replans).\n *\n * This eliminates a remote getCourseConfig() round trip per pipeline run.\n */\n private _cachedOrchestration: OrchestrationContext | null = null;\n\n /**\n * Hash of the strategy docs this pipeline was assembled from (see\n * versionStamps.ts), set by whoever builds it. Stamped on every run.\n */\n strategyHash?: string;\n\n /**\n * Persistent tag cache. Maps cardId → tag names.\n *\n * Tags are static within a session (they're set at card generation time),\n * so we cache them across pipeline runs. On replans, many of the same cards\n * reappear — cache hits avoid redundant remote getAppliedTagsBatch() queries.\n */\n private _tagCache: Map<string, string[]> = new Map();\n\n /**\n * One-shot replan hints. Applied after the filter chain on the next\n * getWeightedCards() call, then cleared.\n */\n private _ephemeralHints: ReplanHints | null = null;\n\n /**\n * The intake valve's clock (see regulators.ts), loaded from strategy state on\n * first use and kept in memory. Writes are chained so a presentation and a\n * run can't race each other's revision.\n */\n private _intakeClock: IntakeClockState | null = null;\n private _intakeClockWrite: Promise<void> = Promise.resolve();\n\n /**\n * Create a new pipeline.\n *\n * @param generator - The generator (or CompositeGenerator) that produces candidates\n * @param filters - Filters to apply sequentially (order doesn't matter for multipliers)\n * @param user - User database interface\n * @param course - Course database interface\n */\n constructor(\n generator: CardGenerator,\n filters: CardFilter[],\n user: UserDBInterface,\n course: CourseDBInterface\n ) {\n super();\n this.generator = generator;\n this.filters = filters;\n this.user = user;\n this.course = course;\n\n course\n .getCourseConfig()\n .then((cfg) => {\n logger.debug(`[pipeline] Crated pipeline for ${cfg.name}`);\n })\n .catch((e) => {\n logger.error(`[pipeline] Failed to lookup courseCfg: ${e}`);\n });\n // Toggle pipeline configuration logging:\n logPipelineConfig(generator, filters);\n\n // Register for debug API access\n registerPipelineForDebug(this);\n }\n\n /**\n * Set one-shot hints for the next pipeline run.\n * Consumed after one getWeightedCards() call, then cleared.\n *\n * Overrides ContentNavigator.setEphemeralHints() no-op.\n */\n override setEphemeralHints(hints: ReplanHints): void {\n this._ephemeralHints = hints;\n logger.info(`[Pipeline] Ephemeral hints set: ${JSON.stringify(hints)}`);\n }\n\n /**\n * Get weighted cards by running generator and applying filters.\n *\n * 1. Build shared context (user ELO, etc.)\n * 2. Get candidates from generator (passing context)\n * 3. Batch hydrate tags for all candidates\n * 4. Apply each filter sequentially\n * 5. Remove zero-score cards\n * 6. Sort by score descending\n * 7. Return top N\n *\n * @param limit - Maximum number of cards to return\n * @returns Cards sorted by score descending\n */\n async getWeightedCards(limit: number): Promise<GeneratorResult> {\n const t0 = performance.now();\n\n // Build shared context once\n const context = await this.buildContext();\n const tContext = performance.now();\n\n // Over-fetch from generator to give filters a wide candidate pool.\n // With local course DB the cost is negligible (~20ms for 500 cards).\n // Filters (hierarchy, letter gating, etc.) can be aggressive — a wide\n // pool ensures enough well-indicated candidates survive.\n const fetchLimit = 500;\n\n logger.debug(\n `[Pipeline] Fetching ${fetchLimit} candidates from generator '${this.generator.name}'`\n );\n\n // Get candidates from generator, passing context\n const generatorResult = await this.generator.getWeightedCards(fetchLimit, context);\n let cards = generatorResult.cards;\n const tGenerate = performance.now();\n const generatedCount = cards.length;\n\n // Merge generator-emitted hints with any externally supplied one-shot hints\n const mergedHints = mergeHints([this._ephemeralHints, generatorResult.hints]);\n this._ephemeralHints = mergedHints ?? null;\n \n // Capture generator breakdown for debugging (if CompositeGenerator)\n let generatorSummaries: GeneratorSummary[] | undefined;\n if ((this.generator as any).generators) {\n // This is a CompositeGenerator - extract per-generator info from provenance\n const genMap = new Map<string, { cards: WeightedCard[] }>();\n for (const card of cards) {\n const firstProv = card.provenance[0];\n if (firstProv) {\n const genName = firstProv.strategyName;\n if (!genMap.has(genName)) {\n genMap.set(genName, { cards: [] });\n }\n genMap.get(genName)!.cards.push(card);\n }\n }\n generatorSummaries = Array.from(genMap.entries()).map(([name, data]) => {\n // Reviews carry `reviewID`; everything else a generator emits is unseen.\n // (Reason text can't tell: the ELO generator's never says \"new card\".)\n const reviewCount = data.cards.filter((c) => c.reviewID).length;\n return {\n name,\n cardCount: data.cards.length,\n newCount: data.cards.length - reviewCount,\n reviewCount,\n topScore: Math.max(...data.cards.map((c) => c.score), 0),\n };\n });\n }\n\n logger.debug(`[Pipeline] Generator returned ${generatedCount} candidates`);\n\n // Batch hydrate tags before filters run\n cards = await this.hydrateTags(cards);\n const tHydrate = performance.now();\n \n // Keep a copy of all cards for debug capture (before filtering removes any)\n const allCardsBeforeFiltering = [...cards];\n\n // Pre-fetch any literal requireCards IDs that the generator didn't produce.\n // requireCards is a hard guarantee — required cards bypass the filter chain\n // and are injected directly into the final result by applyHints. We need\n // them present in allCardsBeforeFiltering for that injection to find them.\n // (Glob patterns are left to the existing pool-search behaviour.)\n const pendingHints = this._ephemeralHints;\n if (pendingHints?.requireCards?.length) {\n const poolIds = new Set(allCardsBeforeFiltering.map((c) => c.cardId));\n const missingIds = pendingHints.requireCards.filter(\n (p) => !p.includes('*') && !poolIds.has(p)\n );\n if (missingIds.length > 0) {\n const fetchedTags = await this.course!.getAppliedTagsBatch(missingIds);\n const courseId = this.course!.getCourseID();\n for (const cardId of missingIds) {\n allCardsBeforeFiltering.push({\n cardId,\n courseId,\n score: 1.0,\n tags: fetchedTags.get(cardId) ?? [],\n provenance: [],\n });\n }\n logger.info(\n `[Pipeline] Pre-fetched ${missingIds.length} required card(s) into pool: ${missingIds.join(', ')}`\n );\n }\n }\n\n // Apply filters sequentially, tracking impact\n // Track prescribed-origin cards through the filter chain for diagnostics\n const prescribedIds = new Set(\n cards\n .filter((c) => c.provenance.some((p) => p.strategy === 'prescribed'))\n .map((c) => c.cardId)\n );\n const filterImpacts: FilterImpact[] = [];\n // Scores as generated, so regulators can read the filters' net effect on each card.\n const generatedScores = new Map(cards.map((c) => [c.cardId, c.score]));\n // Cards a gate penalized: not ready, so regulators won't lift them.\n const gated = new Set<string>();\n // [perf] parked 2026-05 (pipeline-docs-workup) — uncomment to re-measure\n // const filterTimings: string[] = [];\n for (const filter of this.filters) {\n // const tFilterStart = performance.now();\n const beforeCount = cards.length;\n const beforeScores = new Map(cards.map((c) => [c.cardId, c.score]));\n cards = await filter.transform(cards, context);\n // filterTimings.push(`${filter.name}=${(performance.now() - tFilterStart).toFixed(0)}ms`);\n\n // Count boost/penalize/pass/removed for this filter\n let boosted = 0, penalized = 0, passed = 0;\n const removed = beforeCount - cards.length;\n\n // Undeclared filters count as gates (see CardFilter.kind).\n const kind = filter.kind ?? 'gate';\n for (const card of cards) {\n const before = beforeScores.get(card.cardId) ?? 0;\n if (card.score > before) boosted++;\n else if (card.score < before) {\n penalized++;\n if (kind === 'gate') gated.add(card.cardId);\n } else passed++;\n }\n filterImpacts.push({ name: filter.name, kind, boosted, penalized, passed, removed });\n\n // Report prescribed card fate through each filter\n if (prescribedIds.size > 0) {\n const survivingIds = new Set(cards.map((c) => c.cardId));\n const killedPrescribed = [...prescribedIds].filter((id) => !survivingIds.has(id));\n const zeroedPrescribed = cards\n .filter((c) => prescribedIds.has(c.cardId) && c.score === 0)\n .map((c) => c.cardId);\n if (killedPrescribed.length > 0 || zeroedPrescribed.length > 0) {\n logger.info(\n `[Pipeline] Filter '${filter.name}' impact on prescribed cards: ` +\n (killedPrescribed.length > 0 ? `removed=[${killedPrescribed.join(', ')}] ` : '') +\n (zeroedPrescribed.length > 0 ? `zeroed=[${zeroedPrescribed.join(', ')}]` : '')\n );\n // Remove killed ones from tracking set\n killedPrescribed.forEach((id) => prescribedIds.delete(id));\n }\n }\n\n logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeScores.size} → ${cards.length} cards (↑${boosted} ↓${penalized} =${passed})`);\n }\n\n // Remove zero-score cards (hard filtered). The debug report still wants\n // them: they're the answer to \"which filter sank this card?\"\n const scoredCards = cards;\n cards = cards.filter((c) => c.score > 0);\n\n // Regulators: class-level pressure between reviews and new cards, from the\n // filtered scores (see regulators.ts). Before hints, so session intent wins.\n const regulators = await this.regulate(cards, generatedScores, gated);\n\n // Apply ephemeral hints (one-shot, post-filter)\n const hints = this._ephemeralHints;\n if (hints) {\n this._ephemeralHints = null; // consume\n cards = this.applyHints(cards, hints, allCardsBeforeFiltering);\n }\n\n // Stage 3: diversity re-rank (post-filter, post-hints, pre-sort). Demotes\n // cards whose distinctive tags already appeared among higher-ranked\n // candidates so a single answer/concept can't monopolise the head of the\n // queue. Tag-agnostic (rarity-weighted overlap — no namespace privileged)\n // and expressed as score penalties so the ordering survives the final sort\n // here AND the SourceMixer's score-descending re-sort downstream.\n cards = diversityRerank(cards);\n\n // Sort by score descending\n cards.sort((a, b) => b.score - a.score);\n\n // Return top N\n const tFilter = performance.now();\n const result = cards.slice(0, limit);\n\n logger.info(\n `[Pipeline:timing] total=${(tFilter - t0).toFixed(0)}ms ` +\n `(context=${(tContext - t0).toFixed(0)} generate=${(tGenerate - tContext).toFixed(0)} ` +\n `hydrate=${(tHydrate - tGenerate).toFixed(0)} filter=${(tFilter - tHydrate).toFixed(0)})`\n );\n perfMeasure('sk:pipeline-run', t0, tFilter, {\n context: Math.round(tContext - t0),\n generate: Math.round(tGenerate - tContext),\n hydrate: Math.round(tHydrate - tGenerate),\n filter: Math.round(tFilter - tHydrate),\n binding: this.course?.readsLocal === undefined ? 'unknown' : this.course.readsLocal ? 'local' : 'remote',\n });\n\n // Toggle execution summary logging:\n const topScores = result.slice(0, 3).map((c) => c.score);\n logExecutionSummary(\n this.generator.name,\n generatedCount,\n this.filters.length,\n result.length,\n topScores,\n filterImpacts\n );\n\n // Toggle verbose result listing:\n logResultCards(result);\n\n // Toggle provenance logging (shows scoring history for top cards):\n logCardProvenance(result, 3);\n\n // Capture run for debug API\n try {\n const courseConfig = await this.course?.getCourseConfig().catch(() => undefined);\n const courseName = courseConfig?.name;\n // Pass the full post-filter sorted array; buildRunReport retains all\n // selected cards plus the top-N highest-scoring near-misses and\n // summarizes the discarded tail (see DISCARDED_KEEP_TOP). This keeps\n // showCard() useful for \"why didn't this rank?\" inspection without\n // pinning hundreds of low-score candidates' provenance per run.\n // `cards` is the post-filter, post-hints, sorted array.\n const report = buildRunReport(\n this.course?.getCourseID() || 'unknown',\n courseName,\n this.generator.name,\n generatorSummaries,\n generatedCount,\n filterImpacts,\n cards,\n result,\n context.userElo,\n hints?? undefined,\n scoredCards,\n regulators\n );\n const versions = {\n ...(this.strategyHash ? { strategies: this.strategyHash } : {}),\n ...(courseConfig?.contentVersion ? { content: courseConfig.contentVersion } : {}),\n };\n captureRun({ ...report, ...(Object.keys(versions).length ? { versions } : {}) });\n } catch (e) {\n logger.debug(`[Pipeline] Failed to capture debug run: ${e}`);\n }\n\n return { cards: result };\n }\n\n /**\n * Batch hydrate tags for all cards.\n *\n * Fetches tags for all cards in a single database query and attaches them\n * to the WeightedCard objects. Filters can then use card.tags instead of\n * making individual getAppliedTags() calls.\n *\n * Uses a persistent tag cache across pipeline runs — tags are static within\n * a session, so cards seen in a prior run (e.g. before a replan) don't\n * require a second DB query.\n *\n * @param cards - Cards to hydrate\n * @returns Cards with tags populated\n */\n private async hydrateTags(cards: WeightedCard[]): Promise<WeightedCard[]> {\n if (cards.length === 0) {\n return cards;\n }\n\n // Separate cards with cached tags from those needing a DB query\n const uncachedIds: string[] = [];\n for (const card of cards) {\n if (!this._tagCache.has(card.cardId)) {\n uncachedIds.push(card.cardId);\n }\n }\n\n // Only query the DB for cards not already in cache\n if (uncachedIds.length > 0) {\n const freshTags = await this.course!.getAppliedTagsBatch(uncachedIds);\n for (const [cardId, tags] of freshTags) {\n this._tagCache.set(cardId, tags);\n }\n }\n\n // Build the tagsByCard map from cache (for logging compatibility)\n const tagsByCard = new Map<string, string[]>();\n for (const card of cards) {\n tagsByCard.set(card.cardId, this._tagCache.get(card.cardId) ?? []);\n }\n\n // Toggle tag hydration logging:\n logTagHydration(cards, tagsByCard);\n\n return cards.map((card) => ({\n ...card,\n tags: this._tagCache.get(card.cardId) ?? [],\n }));\n }\n\n // ---------------------------------------------------------------------------\n // Ephemeral hints application\n // ---------------------------------------------------------------------------\n\n /**\n * Apply one-shot replan hints to the post-filter card set.\n *\n * Order of operations:\n * 1. Exclude (remove unwanted cards)\n * 2. Boost (multiply scores)\n * 3. Require (inject must-have cards from the full pre-filter pool)\n *\n * @param cards - Post-filter cards (score > 0)\n * @param hints - The ephemeral hints to apply\n * @param allCards - Full pre-filter card pool (for require injection)\n */\n private applyHints(\n cards: WeightedCard[],\n hints: ReplanHints,\n allCards: WeightedCard[]\n ): WeightedCard[] {\n const beforeCount = cards.length;\n\n // 1. Exclude\n if (hints.excludeCards?.length) {\n cards = cards.filter(\n (c) => !hints.excludeCards!.some((pat) => globMatch(c.cardId, pat))\n );\n }\n if (hints.excludeTags?.length) {\n cards = cards.filter(\n (c) => !hints.excludeTags!.some((pat) => cardMatchesTagPattern(c, pat))\n );\n }\n\n // 2. Boost\n if (hints.boostTags) {\n for (const [pattern, factor] of Object.entries(hints.boostTags)) {\n for (const card of cards) {\n if (cardMatchesTagPattern(card, pattern)) {\n card.score *= factor;\n card.provenance.push({\n strategy: 'ephemeralHint',\n strategyId: 'ephemeral-hint',\n strategyName: hints._label ? `Replan Hint (${hints._label})` : 'Replan Hint',\n action: 'boosted',\n score: card.score,\n reason: `boostTag ${pattern} ×${factor}`,\n });\n }\n }\n }\n }\n if (hints.boostCards) {\n for (const [pattern, factor] of Object.entries(hints.boostCards)) {\n for (const card of cards) {\n if (globMatch(card.cardId, pattern)) {\n card.score *= factor;\n card.provenance.push({\n strategy: 'ephemeralHint',\n strategyId: 'ephemeral-hint',\n strategyName: hints._label ? `Replan Hint (${hints._label})` : 'Replan Hint',\n action: 'boosted',\n score: card.score,\n reason: `boostCard ${pattern} ×${factor}`,\n });\n }\n }\n }\n }\n\n // 3. Require — ensure mandatory cards have floor score and are in the pool\n const cardIds = new Set(cards.map((c) => c.cardId));\n const cardMap = new Map(cards.map((c) => [c.cardId, c]));\n const hintLabel = hints._label ? `Replan Hint (${hints._label})` : 'Replan Hint';\n\n const applyRequirement = (card: WeightedCard, reason: string) => {\n const mandatoryScore = Number.POSITIVE_INFINITY;\n const existing = cardMap.get(card.cardId);\n\n if (existing) {\n // If already in the pool, upgrade to mandatory score if not already infinite\n if (existing.score < mandatoryScore) {\n existing.score = mandatoryScore;\n existing.provenance.push({\n strategy: 'ephemeralHint',\n strategyId: 'ephemeral-hint',\n strategyName: hintLabel,\n action: 'boosted',\n score: mandatoryScore,\n reason: `${reason} (upgrade to mandatory score)`,\n });\n }\n } else {\n // If missing, inject from the full pool\n cards.push({\n ...card,\n score: mandatoryScore,\n provenance: [\n ...card.provenance,\n {\n strategy: 'ephemeralHint',\n strategyId: 'ephemeral-hint',\n strategyName: hintLabel,\n action: 'boosted',\n score: mandatoryScore,\n reason,\n },\n ],\n });\n cardIds.add(card.cardId);\n cardMap.set(card.cardId, cards[cards.length - 1]);\n }\n };\n\n if (hints.requireCards?.length) {\n for (const pattern of hints.requireCards) {\n // First check candidates already in the pool\n for (const cardId of cardIds) {\n if (globMatch(cardId, pattern)) {\n applyRequirement(cardMap.get(cardId)!, `requireCard ${pattern}`);\n }\n }\n // Then check full pool for injection\n for (const card of allCards) {\n if (globMatch(card.cardId, pattern)) {\n applyRequirement(card, `requireCard ${pattern}`);\n }\n }\n }\n }\n if (hints.requireTags?.length) {\n for (const pattern of hints.requireTags) {\n // First check candidates already in the pool\n for (const cardId of cardIds) {\n const card = cardMap.get(cardId)!;\n if (cardMatchesTagPattern(card, pattern)) {\n applyRequirement(card, `requireTag ${pattern}`);\n }\n }\n // Then check full pool for injection\n for (const card of allCards) {\n if (cardMatchesTagPattern(card, pattern)) {\n applyRequirement(card, `requireTag ${pattern}`);\n }\n }\n }\n }\n\n logger.info(`[Pipeline] Hints applied: ${beforeCount} → ${cards.length} cards`);\n\n return cards;\n }\n\n /**\n * The regulator stage: measure each class's pressure and scale it.\n *\n * - Review mass: every due review's SRS urgency times the filters' net\n * effect on it.\n * - Intake: servable hours since a new card was presented, applied only to\n * eligible new cards (no gate penalized them). With none eligible, the\n * clock freezes.\n *\n * Mutates `cards` in place; returns the readings for the run report.\n */\n private async regulate(\n cards: WeightedCard[],\n generatedScores: ReadonlyMap<string, number>,\n gated: Set<string>\n ): Promise<RegulatorReading[]> {\n const config = DEFAULT_REGULATOR_CONFIG;\n const reviews = cards.filter((c) => c.reviewID);\n const newCards = cards.filter((c) => !c.reviewID);\n const eligibleNew = newCards.filter((c) => !gated.has(c.cardId));\n\n const mass = reviewMassReading(reviews, generatedScores, config.reviewMass);\n applyReading(reviews, mass);\n noteReviewPressure(this.course!.getCourseID(), {\n mass: mass.urgency,\n healthyMass: config.reviewMass.healthyMass,\n rate: config.reviewMass.rate,\n multiplier: mass.multiplier,\n });\n\n const now = Date.now();\n const clock = await this.loadIntakeClock(now);\n const stepped = stepIntakeClock(clock, now, eligibleNew.length);\n if (stepped !== clock) this.saveIntakeClock(stepped);\n const intake = intakeReading(\n stepped,\n now,\n { eligibleNew: eligibleNew.length, newCandidates: newCards.length },\n config.intake\n );\n applyReading(eligibleNew, intake);\n\n logger.info(\n `[Pipeline:regulators] review mass ${mass.urgency.toFixed(1)} over ${reviews.length} due → ` +\n `×${mass.multiplier.toFixed(2)}; intake ${intake.urgency.toFixed(1)}h, ` +\n `${eligibleNew.length}/${newCards.length} new eligible → ×${intake.multiplier.toFixed(2)}`\n );\n return [mass, intake];\n }\n\n /**\n * A card was presented. A new card's first presentation discharges the\n * intake valve: its clock restarts. Called by the SessionController.\n */\n notePresented(card: { cardId: string; courseId: string; status: string }): void {\n if (card.status !== 'new' || card.courseId !== this.course?.getCourseID()) return;\n this.saveIntakeClock(resetIntakeClock(Date.now()));\n }\n\n private async loadIntakeClock(nowMs: number): Promise<IntakeClockState> {\n if (this._intakeClock) return this._intakeClock;\n let stored: IntakeClockState | null = null;\n try {\n stored = await this.user!.getStrategyState<IntakeClockState>(\n this.course!.getCourseID(),\n INTAKE_CLOCK_KEY\n );\n } catch (e) {\n logger.warn(`[Pipeline:regulators] Could not read the intake clock: ${e}`);\n }\n if (stored) {\n this._intakeClock = stored;\n } else {\n // No clock yet: start it now.\n this.saveIntakeClock(resetIntakeClock(nowMs));\n }\n return this._intakeClock!;\n }\n\n private saveIntakeClock(state: IntakeClockState): void {\n this._intakeClock = state;\n const courseId = this.course!.getCourseID();\n this._intakeClockWrite = this._intakeClockWrite\n .then(() => this.user!.putStrategyState(courseId, INTAKE_CLOCK_KEY, state))\n .catch((e) => logger.warn(`[Pipeline:regulators] Could not save the intake clock: ${e}`));\n }\n\n /**\n * Build shared context for generator and filters.\n *\n * Called once per getWeightedCards() invocation.\n * Contains data that the generator and multiple filters might need.\n *\n * The context satisfies both GeneratorContext and FilterContext interfaces.\n */\n private async buildContext(): Promise<GeneratorContext & FilterContext> {\n let userElo = 1000; // Default ELO\n let userCourseElo: CourseElo | undefined;\n\n try {\n const courseReg = await this.user!.getCourseRegDoc(this.course!.getCourseID());\n userCourseElo = toCourseElo(courseReg.elo);\n userElo = userCourseElo.global.score;\n } catch (e) {\n logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);\n }\n\n // Reuse cached orchestration context if available (course config is stable\n // within a page load). This avoids a remote getCourseConfig() call on\n // subsequent pipeline runs (e.g. mid-session replans).\n if (!this._cachedOrchestration) {\n this._cachedOrchestration = await createOrchestrationContext(this.user!, this.course!);\n }\n const orchestration = this._cachedOrchestration;\n\n return {\n user: this.user!,\n course: this.course!,\n userElo,\n ...(userCourseElo ? { userCourseElo } : {}),\n orchestration,\n };\n }\n\n /**\n * Get the course ID for this pipeline.\n */\n getCourseID(): string {\n return this.course!.getCourseID();\n }\n\n /**\n * Get orchestration context for outcome recording.\n */\n async getOrchestrationContext(): Promise<OrchestrationContext> {\n return createOrchestrationContext(this.user!, this.course!);\n }\n\n /**\n * Get IDs of all strategies in this pipeline.\n * Used to record which strategies contributed to an outcome.\n */\n getStrategyIds(): string[] {\n const ids: string[] = [];\n\n const extractId = (obj: any): string | null => {\n // Check for strategyId property (ContentNavigator, WeightedFilter)\n if (obj.strategyId) return obj.strategyId;\n return null;\n };\n\n // Generator(s)\n const genId = extractId(this.generator);\n if (genId) ids.push(genId);\n\n // Inspect CompositeGenerator children (accessing private field via cast)\n if ((this.generator as any).generators && Array.isArray((this.generator as any).generators)) {\n (this.generator as any).generators.forEach((g: any) => {\n const subId = extractId(g);\n if (subId) ids.push(subId);\n });\n }\n\n // Filters\n for (const filter of this.filters) {\n const fId = extractId(filter);\n if (fId) ids.push(fId);\n }\n\n return [...new Set(ids)];\n }\n\n // ---------------------------------------------------------------------------\n // Tag ELO diagnostic\n // ---------------------------------------------------------------------------\n\n /**\n * Get the user's per-tag ELO data for specified tags (or all tags).\n * Useful for diagnosing why hierarchy gates are open/closed.\n */\n async getTagEloStatus(\n tagFilter?: string | string[]\n ): Promise<Record<string, { score: number; count: number }>> {\n const courseReg = await this.user!.getCourseRegDoc(this.course!.getCourseID());\n const courseElo = toCourseElo(courseReg.elo);\n\n const result: Record<string, { score: number; count: number }> = {};\n\n if (!tagFilter) {\n // Return all tags\n for (const [tag, data] of Object.entries(courseElo.tags)) {\n result[tag] = { score: data.score, count: data.count };\n }\n } else {\n const patterns = Array.isArray(tagFilter) ? tagFilter : [tagFilter];\n for (const pattern of patterns) {\n const regex = globToRegex(pattern);\n for (const [tag, data] of Object.entries(courseElo.tags)) {\n if (regex.test(tag)) {\n result[tag] = { score: data.score, count: data.count };\n }\n }\n }\n }\n\n return result;\n }\n\n // ---------------------------------------------------------------------------\n // Card-space diagnostic\n // ---------------------------------------------------------------------------\n\n /**\n * Commit-free forecast: score the user's full card space through the filter\n * chain and return the cards that are currently *reachable* (score >=\n * threshold), optionally nudged by caller-supplied hints and/or restricted\n * to cards the user hasn't seen yet.\n *\n * This is a GENERIC primitive — it returns scored, tag-hydrated cards and\n * stops there. It has no knowledge of any particular tag convention; callers\n * decide what the surviving cards mean (e.g. filter to their own \"intro\"\n * tag family). Nothing is written and no session is started.\n *\n * The optional `hints` are the \"out-of-band kick\": they run through the same\n * {@link applyHints} path a live replan uses, so the two semantics carry over —\n * - `boostTags`/`boostCards` reweight *within* gating (a gated score-0 card\n * stays out), and\n * - `requireTags`/`requireCards` inject from the full pre-filter pool,\n * *bypassing* gating (use when you want a card regardless of reachability).\n * Note `unseenOnly` is applied LAST, so it can drop a `require`d card that the\n * user has already seen — pass `unseenOnly: false` if that matters.\n *\n * Cost note: like {@link diagnoseCardSpace}, this scans every card through the\n * filters, so it's heavier than a normal replan. Intended for one-shot\n * out-of-band use (e.g. a session-end \"what's next\" snapshot), not the hot path.\n *\n * @param opts.hints Optional ephemeral hints to apply after the filter chain.\n * @param opts.unseenOnly Only return cards the user hasn't encountered (default true).\n * @param opts.threshold Min score to count as reachable (default 0.10).\n * @param opts.limit Optional cap on results (already sorted desc).\n */\n async forecast(opts?: {\n hints?: ReplanHints;\n unseenOnly?: boolean;\n threshold?: number;\n limit?: number;\n }): Promise<WeightedCard[]> {\n const threshold = opts?.threshold ?? 0.10;\n const unseenOnly = opts?.unseenOnly ?? true;\n\n const courseId = this.course!.getCourseID();\n const allCardIds = await this.course!.getAllCardIds();\n\n let cards: WeightedCard[] = allCardIds.map((cardId) => ({\n cardId,\n courseId,\n score: 1.0,\n provenance: [],\n }));\n\n cards = await this.hydrateTags(cards);\n // Snapshot the full pool before filtering, for require-injection in applyHints.\n const fullPool = cards.slice();\n\n const context = await this.buildContext();\n for (const filter of this.forecastFilters()) {\n cards = await filter.transform(cards, context);\n }\n\n if (opts?.hints) {\n cards = this.applyHints(cards, opts.hints, fullPool);\n }\n\n cards = cards.filter((c) => c.score >= threshold);\n\n if (unseenOnly) {\n let encountered: Set<string>;\n try {\n encountered = new Set(await this.user!.getSeenCards(courseId));\n } catch {\n encountered = new Set();\n }\n cards = cards.filter((c) => !encountered.has(c.cardId));\n }\n\n cards.sort((a, b) => b.score - a.score);\n return opts?.limit ? cards.slice(0, opts.limit) : cards;\n }\n\n /**\n * The filters a forecast or card-space scan applies. Those start every card at\n * 1.0 without a generator, so they skip `liveOnly` filters (ELO distance),\n * which only make sense against generator scores.\n */\n private forecastFilters(): CardFilter[] {\n return this.filters.filter((f) => !f.liveOnly);\n }\n\n /**\n * Scan every card in the course through the filter chain and report\n * how many are \"well indicated\" (score >= threshold) for the current user.\n *\n * Also reports how many well-indicated cards the user has NOT yet encountered.\n *\n * Exposed via `window.skuilder.pipeline.diagnoseCardSpace()`.\n */\n async diagnoseCardSpace(opts?: { threshold?: number }): Promise<CardSpaceDiagnosis> {\n const THRESHOLD = opts?.threshold ?? 0.10;\n const t0 = performance.now();\n\n // 1. Get all card IDs\n const allCardIds = await this.course!.getAllCardIds();\n\n // 2. Build dummy WeightedCards (score=1.0, no provenance)\n let cards: WeightedCard[] = allCardIds.map((cardId) => ({\n cardId,\n courseId: this.course!.getCourseID(),\n score: 1.0,\n provenance: [],\n }));\n\n // 3. Hydrate tags\n cards = await this.hydrateTags(cards);\n\n // 4. Run through filters\n const context = await this.buildContext();\n const filterBreakdown: Array<{ name: string; wellIndicated: number }> = [];\n\n // Track cumulative filter effects\n for (const filter of this.forecastFilters()) {\n cards = await filter.transform(cards, context);\n const wi = cards.filter((c) => c.score >= THRESHOLD).length;\n filterBreakdown.push({ name: filter.name, wellIndicated: wi });\n }\n\n // 5. Count well-indicated\n const wellIndicated = cards.filter((c) => c.score >= THRESHOLD);\n const wellIndicatedIds = new Set(wellIndicated.map((c) => c.cardId));\n\n // 6. Get encountered cards\n let encounteredIds: Set<string>;\n try {\n const courseId = this.course!.getCourseID();\n const seenCards = await this.user!.getSeenCards(courseId);\n encounteredIds = new Set(seenCards);\n } catch {\n encounteredIds = new Set();\n }\n\n const wellIndicatedNew = wellIndicated.filter((c) => !encounteredIds.has(c.cardId));\n\n // 7. Group by card type\n const byType = new Map<string, { total: number; wellIndicated: number; new: number }>();\n for (const card of cards) {\n const type = card.cardId.split('-')[1] || 'unknown'; // c-ws-... → ws, c-intro-... → intro, etc.\n if (!byType.has(type)) {\n byType.set(type, { total: 0, wellIndicated: 0, new: 0 });\n }\n const entry = byType.get(type)!;\n entry.total++;\n if (card.score >= THRESHOLD) {\n entry.wellIndicated++;\n if (!encounteredIds.has(card.cardId)) entry.new++;\n }\n }\n\n const elapsed = performance.now() - t0;\n\n const result: CardSpaceDiagnosis = {\n totalCards: allCardIds.length,\n threshold: THRESHOLD,\n wellIndicated: wellIndicatedIds.size,\n encountered: encounteredIds.size,\n wellIndicatedNew: wellIndicatedNew.length,\n byType: Object.fromEntries(byType),\n filterBreakdown,\n elapsedMs: Math.round(elapsed),\n };\n\n // Log to console\n logger.print(`[Pipeline:diagnose] Card space scan (${result.elapsedMs}ms):`);\n logger.print(`[Pipeline:diagnose] Total cards: ${result.totalCards}`);\n logger.print(`[Pipeline:diagnose] Well-indicated (score >= ${THRESHOLD}): ${result.wellIndicated}`);\n logger.print(`[Pipeline:diagnose] Encountered: ${result.encountered}`);\n logger.print(`[Pipeline:diagnose] Well-indicated & new: ${result.wellIndicatedNew}`);\n logger.print(`[Pipeline:diagnose] By type:`);\n for (const [type, counts] of byType) {\n logger.print(\n `[Pipeline:diagnose] ${type}: ${counts.wellIndicated}/${counts.total} well-indicated, ${counts.new} new`\n );\n }\n logger.print(`[Pipeline:diagnose] After each filter:`);\n for (const fb of filterBreakdown) {\n logger.print(`[Pipeline:diagnose] ${fb.name}: ${fb.wellIndicated} well-indicated`);\n }\n\n return result;\n }\n\n}\n\n/**\n * Diagnosis of the full card space for the current user.\n */\nexport interface CardSpaceDiagnosis {\n totalCards: number;\n threshold: number;\n wellIndicated: number;\n encountered: number;\n wellIndicatedNew: number;\n byType: Record<string, { total: number; wellIndicated: number; new: number }>;\n filterBreakdown: Array<{ name: string; wellIndicated: number }>;\n elapsedMs: number;\n}\n"],"mappings":";;;;;;;;;;;;;;;AA+CA,SAAS,YAAY,SAAyB;CAE5C,MAAM,gBADU,QAAQ,QAAQ,sBAAsB,OAAO,CAC/B,QAAQ,OAAO,KAAK;AAClD,QAAO,IAAI,OAAO,IAAI,cAAc,GAAG;;;AAIzC,SAAS,UAAU,OAAe,SAA0B;AAC1D,KAAI,CAAC,QAAQ,SAAS,IAAI,CAAE,QAAO,UAAU;AAC7C,QAAO,YAAY,QAAQ,CAAC,KAAK,MAAM;;;AAIzC,SAAS,sBAAsB,MAAoB,SAA0B;AAC3E,SAAQ,KAAK,QAAQ,EAAE,EAAE,MAAM,QAAQ,UAAU,KAAK,QAAQ,CAAC;;AAGjE,SAAgB,WAAW,UAA0E;CACnG,MAAM,UAAU,SAAS,QAAQ,MAAwB,MAAM,QAAQ,MAAM,KAAA,EAAU;AACvF,KAAI,QAAQ,WAAW,EAAG,QAAO,KAAA;CA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CAA+C,OAAO,mBAAmB;AACtF,SAAO,MAAM,iCAAiC;AAC9C,OAAK,MAAM,CAAC,MAAM,WAAW,OAC3B,QAAO,MACL,2BAA2B,KAAK,IAAI,OAAO,cAAc,GAAG,OAAO,MAAM,mBAAmB,OAAO,IAAI,MACxG;AAEH,SAAO,MAAM,2CAA2C;AACxD,OAAK,MAAM,MAAM,gBACf,QAAO,MAAM,2BAA2B,GAAG,KAAK,IAAI,GAAG,cAAc,iBAAiB;AAGxF,SAAO"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import "../_virtual/_rolldown/runtime.mjs";
|
|
2
2
|
//#region src/core/versionStamps.ts
|
|
3
3
|
/** This build's @vue-skuilder/db version, set at build time; `'dev'` when run from source. */
|
|
4
|
-
const FRAMEWORK_VERSION = "0.
|
|
4
|
+
const FRAMEWORK_VERSION = "0.3.1";
|
|
5
5
|
let hostAppVersion;
|
|
6
6
|
/** Record the host app's version (the data layer's `appVersion` option). */
|
|
7
7
|
function setAppVersion(version) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { U as UserDBInterface, C as CourseDBInterface, a as CoursesDBInterface } from './contentSource-
|
|
1
|
+
import { U as UserDBInterface, C as CourseDBInterface, a as CoursesDBInterface } from './contentSource-2zVmcjKA.js';
|
|
2
2
|
import { C as ClassroomDBInterface, A as AdminDBInterface } from './classroomDB-DLTtLZct.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { C as CardData, b as DisplayableData, a as Tag, c as CardRecord, d as QuestionRecord, e as CardHistory } from '../types-legacy-
|
|
2
|
-
import { c as ContentNavigationStrategyData, e as StudySessionDoc, f as ScheduledCard, g as CourseRegistrationDoc, h as SessionStateSnapshot, i as StudySessionRunSummary, j as RegulatorReading, k as StudySessionRunCard, F as FilterKind, l as RegulatorName } from '../contentSource-
|
|
3
|
-
export { m as SessionEloEvent, n as StudySessionRunCardTrail } from '../contentSource-
|
|
1
|
+
import { C as CardData, b as DisplayableData, a as Tag, c as CardRecord, d as QuestionRecord, e as CardHistory } from '../types-legacy-DdVjg81H.js';
|
|
2
|
+
import { c as ContentNavigationStrategyData, e as StudySessionDoc, f as ScheduledCard, g as CourseRegistrationDoc, h as SessionStateSnapshot, i as StudySessionRunSummary, j as RegulatorReading, k as StudySessionRunCard, F as FilterKind, l as RegulatorName } from '../contentSource-2zVmcjKA.js';
|
|
3
|
+
export { m as SessionEloEvent, n as StudySessionRunCardTrail } from '../contentSource-2zVmcjKA.js';
|
|
4
4
|
import { TagRole, TagPresentation, EloRank, CourseElo } from '@vue-skuilder/common';
|
|
5
5
|
import 'moment';
|
|
6
6
|
|
|
@@ -68,6 +68,9 @@ var BaseUser = class BaseUser {
|
|
|
68
68
|
writeDB;
|
|
69
69
|
updateQueue;
|
|
70
70
|
_hydration = { state: "not-required" };
|
|
71
|
+
/** See scanScheduledCards. Bumped by every write to scheduled reviews. */
|
|
72
|
+
_scheduledScan = null;
|
|
73
|
+
_scheduledGeneration = 0;
|
|
71
74
|
/** In-flight hydration, so concurrent callers can wait for a real answer. */
|
|
72
75
|
_hydrationPromise = null;
|
|
73
76
|
/**
|
|
@@ -274,17 +277,38 @@ Currently logged-in as ${this._username}.`);
|
|
|
274
277
|
*
|
|
275
278
|
*/
|
|
276
279
|
async getActiveCards() {
|
|
280
|
+
return (await this.scanScheduledCards()).map((doc) => ({
|
|
281
|
+
courseID: doc.courseId,
|
|
282
|
+
cardID: doc.cardId
|
|
283
|
+
}));
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* The user's scheduled reviews (`card_review_*`), all of them: one `allDocs`
|
|
287
|
+
* scan shared by concurrent readers. A pipeline run's generators start
|
|
288
|
+
* together (`CompositeGenerator`), and each used to scan the range itself
|
|
289
|
+
* (`getActiveCards` from ELO and Prescribed, `getReviewstoDate` from SRS).
|
|
290
|
+
* Sharing only an in-flight scan keeps reads as fresh as before; a schedule
|
|
291
|
+
* or removal of a review starts a new scan for anyone reading after it.
|
|
292
|
+
* Docs are shared between callers: copy before mutating.
|
|
293
|
+
*/
|
|
294
|
+
scanScheduledCards() {
|
|
295
|
+
const inFlight = this._scheduledScan;
|
|
296
|
+
if (inFlight && inFlight.generation === this._scheduledGeneration) return inFlight.scan;
|
|
277
297
|
const keys = getStartAndEndKeys(DocTypePrefixes[DocType.SCHEDULED_CARD]);
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
298
|
+
const entry = {
|
|
299
|
+
generation: this._scheduledGeneration,
|
|
300
|
+
scan: this.remoteDB.allDocs({
|
|
301
|
+
startkey: keys.startkey,
|
|
302
|
+
endkey: keys.endkey,
|
|
303
|
+
include_docs: true
|
|
304
|
+
}).then((res) => res.rows.map((row) => row.doc))
|
|
305
|
+
};
|
|
306
|
+
this._scheduledScan = entry;
|
|
307
|
+
const done = () => {
|
|
308
|
+
if (this._scheduledScan === entry) this._scheduledScan = null;
|
|
309
|
+
};
|
|
310
|
+
entry.scan.then(done, done);
|
|
311
|
+
return entry.scan;
|
|
288
312
|
}
|
|
289
313
|
async getActivityRecords() {
|
|
290
314
|
try {
|
|
@@ -335,21 +359,16 @@ Currently logged-in as ${this._username}.`);
|
|
|
335
359
|
}
|
|
336
360
|
}
|
|
337
361
|
async getReviewstoDate(targetDate, course_id) {
|
|
338
|
-
const
|
|
339
|
-
const reviews = await this.remoteDB.allDocs({
|
|
340
|
-
startkey: keys.startkey,
|
|
341
|
-
endkey: keys.endkey,
|
|
342
|
-
include_docs: true
|
|
343
|
-
});
|
|
362
|
+
const reviews = await this.scanScheduledCards();
|
|
344
363
|
log(`Fetching ${this._username}'s scheduled reviews${course_id ? ` for course ${course_id}` : ""}.`);
|
|
345
|
-
return reviews.
|
|
346
|
-
if (
|
|
347
|
-
const date = moment.utc(
|
|
364
|
+
return reviews.filter((doc) => {
|
|
365
|
+
if (doc._id.startsWith(DocTypePrefixes[DocType.SCHEDULED_CARD])) {
|
|
366
|
+
const date = moment.utc(doc._id.substr(DocTypePrefixes[DocType.SCHEDULED_CARD].length), REVIEW_TIME_FORMAT);
|
|
348
367
|
if (targetDate.isAfter(date)) {
|
|
349
|
-
if (course_id === void 0 ||
|
|
368
|
+
if (course_id === void 0 || doc.courseId === course_id) return true;
|
|
350
369
|
}
|
|
351
370
|
}
|
|
352
|
-
}).map((
|
|
371
|
+
}).map((doc) => ({ ...doc }));
|
|
353
372
|
}
|
|
354
373
|
async getReviewsForcast(daysCount, course_id) {
|
|
355
374
|
const time = moment.utc().add(daysCount, "days");
|
|
@@ -676,25 +695,29 @@ Currently logged-in as ${this._username}.`);
|
|
|
676
695
|
async putCardRecord(record) {
|
|
677
696
|
const cardHistoryID = getCardHistoryID(record.courseID, record.cardID);
|
|
678
697
|
record.timeStamp = moment.utc(record.timeStamp).toString();
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
698
|
+
const append = (h) => {
|
|
699
|
+
h.records.push(record);
|
|
700
|
+
h.bestInterval = h.bestInterval || 0;
|
|
701
|
+
if (areQuestionRecords(h)) {
|
|
702
|
+
h.lapses = getLapses(h.records);
|
|
703
|
+
h.streak = getStreak(h.records);
|
|
704
|
+
} else {
|
|
705
|
+
h.lapses = h.lapses || 0;
|
|
706
|
+
h.streak = h.streak || 0;
|
|
707
|
+
}
|
|
708
|
+
return h;
|
|
709
|
+
};
|
|
710
|
+
const appendToExisting = async () => {
|
|
711
|
+
const cardHistory = await this.update(cardHistoryID, append);
|
|
692
712
|
cardHistory.records = cardHistory.records.map((record) => {
|
|
693
713
|
const ret = { ...record };
|
|
694
714
|
ret.timeStamp = moment.utc(record.timeStamp);
|
|
695
715
|
return ret;
|
|
696
716
|
});
|
|
697
717
|
return cardHistory;
|
|
718
|
+
};
|
|
719
|
+
try {
|
|
720
|
+
return await appendToExisting();
|
|
698
721
|
} catch (e) {
|
|
699
722
|
const reason = e;
|
|
700
723
|
if (reason.status === 404) try {
|
|
@@ -713,6 +736,7 @@ Currently logged-in as ${this._username}.`);
|
|
|
713
736
|
_rev: putResult.rev
|
|
714
737
|
};
|
|
715
738
|
} catch (creationError) {
|
|
739
|
+
if (creationError.name === "conflict") return appendToExisting();
|
|
716
740
|
throw new Error(`Failed to create CardHistory for ${cardHistoryID}. Reason: ${creationError}`);
|
|
717
741
|
}
|
|
718
742
|
else throw new Error(`putCardRecord failed because of:
|
|
@@ -754,6 +778,7 @@ Currently logged-in as ${this._username}.`);
|
|
|
754
778
|
const deletePromises = duplicateDocIds.map(async (docId) => {
|
|
755
779
|
try {
|
|
756
780
|
const doc = await this.remoteDB.get(docId);
|
|
781
|
+
this._scheduledGeneration++;
|
|
757
782
|
await this.writeDB.remove(doc);
|
|
758
783
|
log(`Successfully removed duplicate review: ${docId}`);
|
|
759
784
|
} catch (error) {
|
|
@@ -863,9 +888,11 @@ Currently logged-in as ${this._username}.`);
|
|
|
863
888
|
}
|
|
864
889
|
}
|
|
865
890
|
async scheduleCardReview(review) {
|
|
891
|
+
this._scheduledGeneration++;
|
|
866
892
|
return scheduleCardReviewLocal(this.writeDB, review);
|
|
867
893
|
}
|
|
868
894
|
async removeScheduledCardReview(reviewId) {
|
|
895
|
+
this._scheduledGeneration++;
|
|
869
896
|
return removeScheduledCardReviewLocal(this.writeDB, reviewId);
|
|
870
897
|
}
|
|
871
898
|
async registerForClassroom(_classId, _registerAs) {
|