@vue-skuilder/db 0.2.34 → 0.2.36
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/CLAUDE.md +15 -4
- package/build.entries.mjs +12 -0
- package/dist/_virtual/_rolldown/runtime.mjs +8 -0
- package/dist/{contentSource-CTQ4kWhR.d.cts → contentSource-D_E7JaxR.d.ts} +2 -2
- package/dist/core/UserDBDebugger.mjs +285 -0
- package/dist/core/UserDBDebugger.mjs.map +1 -0
- package/dist/core/bulkImport/cardProcessor.mjs +106 -0
- package/dist/core/bulkImport/cardProcessor.mjs.map +1 -0
- package/dist/core/{index.js → index.cjs} +6438 -7784
- package/dist/core/index.cjs.map +1 -0
- package/dist/core/index.d.ts +5 -5
- package/dist/core/index.mjs +20 -11368
- package/dist/core/interfaces/contentSource.mjs +20 -0
- package/dist/core/interfaces/contentSource.mjs.map +1 -0
- package/dist/core/navigators/Pipeline.mjs +723 -0
- package/dist/core/navigators/Pipeline.mjs.map +1 -0
- package/dist/core/navigators/PipelineAssembler.mjs +86 -0
- package/dist/core/navigators/PipelineAssembler.mjs.map +1 -0
- package/dist/core/navigators/PipelineDebugger.mjs +771 -0
- package/dist/core/navigators/PipelineDebugger.mjs.map +1 -0
- package/dist/core/navigators/SrsDebugger.mjs +34 -0
- package/dist/core/navigators/SrsDebugger.mjs.map +1 -0
- package/dist/core/navigators/StrategyPressureDebugger.mjs +19 -0
- package/dist/core/navigators/StrategyPressureDebugger.mjs.map +1 -0
- package/dist/core/navigators/defaults.mjs +96 -0
- package/dist/core/navigators/defaults.mjs.map +1 -0
- package/dist/core/navigators/diversityRerank.mjs +85 -0
- package/dist/core/navigators/diversityRerank.mjs.map +1 -0
- package/dist/core/navigators/filters/WeightedFilter.mjs +81 -0
- package/dist/core/navigators/filters/WeightedFilter.mjs.map +1 -0
- package/dist/core/navigators/filters/eloDistance.mjs +244 -0
- package/dist/core/navigators/filters/eloDistance.mjs.map +1 -0
- package/dist/core/navigators/filters/hierarchyDefinition.mjs +235 -0
- package/dist/core/navigators/filters/hierarchyDefinition.mjs.map +1 -0
- package/dist/core/navigators/filters/interferenceMitigator.mjs +201 -0
- package/dist/core/navigators/filters/interferenceMitigator.mjs.map +1 -0
- package/dist/core/navigators/filters/relativePriority.mjs +135 -0
- package/dist/core/navigators/filters/relativePriority.mjs.map +1 -0
- package/dist/core/navigators/filters/userTagPreference.mjs +101 -0
- package/dist/core/navigators/filters/userTagPreference.mjs.map +1 -0
- package/dist/core/navigators/generators/CompositeGenerator.mjs +203 -0
- package/dist/core/navigators/generators/CompositeGenerator.mjs.map +1 -0
- package/dist/core/navigators/generators/elo.mjs +77 -0
- package/dist/core/navigators/generators/elo.mjs.map +1 -0
- package/dist/core/navigators/generators/prescribed.mjs +676 -0
- package/dist/core/navigators/generators/prescribed.mjs.map +1 -0
- package/dist/core/navigators/generators/srs.mjs +158 -0
- package/dist/core/navigators/generators/srs.mjs.map +1 -0
- package/dist/core/navigators/index.mjs +345 -0
- package/dist/core/navigators/index.mjs.map +1 -0
- package/dist/core/navigators/pipelinePlan.mjs +109 -0
- package/dist/core/navigators/pipelinePlan.mjs.map +1 -0
- package/dist/core/navigators/regulators.mjs +128 -0
- package/dist/core/navigators/regulators.mjs.map +1 -0
- package/dist/core/orchestration/gradient.mjs +101 -0
- package/dist/core/orchestration/gradient.mjs.map +1 -0
- package/dist/core/orchestration/index.mjs +115 -0
- package/dist/core/orchestration/index.mjs.map +1 -0
- package/dist/core/orchestration/learning.mjs +140 -0
- package/dist/core/orchestration/learning.mjs.map +1 -0
- package/dist/core/orchestration/recording.mjs +64 -0
- package/dist/core/orchestration/recording.mjs.map +1 -0
- package/dist/core/orchestration/signal.mjs +40 -0
- package/dist/core/orchestration/signal.mjs.map +1 -0
- package/dist/core/types/contentNavigationStrategy.mjs +10 -0
- package/dist/core/types/contentNavigationStrategy.mjs.map +1 -0
- package/dist/core/types/hydration.mjs +13 -0
- package/dist/core/types/hydration.mjs.map +1 -0
- package/dist/core/types/strategyState.mjs +16 -0
- package/dist/core/types/strategyState.mjs.map +1 -0
- package/dist/core/types/studySession.mjs +14 -0
- package/dist/core/types/studySession.mjs.map +1 -0
- package/dist/core/types/types-legacy.mjs +44 -0
- package/dist/core/types/types-legacy.mjs.map +1 -0
- package/dist/core/util/index.mjs +31 -0
- package/dist/core/util/index.mjs.map +1 -0
- package/dist/core/versionStamps.mjs +46 -0
- package/dist/core/versionStamps.mjs.map +1 -0
- package/dist/courseConfigRegistration.mjs +306 -0
- package/dist/courseConfigRegistration.mjs.map +1 -0
- package/dist/{dataLayerProvider-rlLE2Mf-.d.ts → dataLayerProvider-BDshhSp_.d.ts} +1 -1
- package/dist/diagnostics/dataset.mjs +118 -0
- package/dist/diagnostics/dataset.mjs.map +1 -0
- package/dist/diagnostics/derive.mjs +318 -0
- package/dist/diagnostics/derive.mjs.map +1 -0
- package/dist/diagnostics/{index.js → index.cjs} +130 -1
- package/dist/diagnostics/index.cjs.map +1 -0
- package/dist/diagnostics/index.d.ts +108 -5
- package/dist/diagnostics/index.mjs +7 -914
- package/dist/diagnostics/loader.mjs +151 -0
- package/dist/diagnostics/loader.mjs.map +1 -0
- package/dist/diagnostics/pipeline.mjs +161 -0
- package/dist/diagnostics/pipeline.mjs.map +1 -0
- package/dist/diagnostics/tagElo.mjs +177 -0
- package/dist/diagnostics/tagElo.mjs.map +1 -0
- package/dist/diagnostics/text.mjs +174 -0
- package/dist/diagnostics/text.mjs.map +1 -0
- package/dist/factory.mjs +70 -0
- package/dist/factory.mjs.map +1 -0
- package/dist/impl/common/BaseUserDB.mjs +1103 -0
- package/dist/impl/common/BaseUserDB.mjs.map +1 -0
- package/dist/impl/common/userDBHelpers.mjs +49 -0
- package/dist/impl/common/userDBHelpers.mjs.map +1 -0
- package/dist/impl/common/userDBKeys.mjs +45 -0
- package/dist/impl/common/userDBKeys.mjs.map +1 -0
- package/dist/impl/couch/CouchDBSyncStrategy.mjs +272 -0
- package/dist/impl/couch/CouchDBSyncStrategy.mjs.map +1 -0
- package/dist/impl/couch/CourseSyncService.mjs +242 -0
- package/dist/impl/couch/CourseSyncService.mjs.map +1 -0
- package/dist/impl/couch/PouchDataLayerProvider.mjs +74 -0
- package/dist/impl/couch/PouchDataLayerProvider.mjs.map +1 -0
- package/dist/impl/couch/adminDB.mjs +61 -0
- package/dist/impl/couch/adminDB.mjs.map +1 -0
- package/dist/impl/couch/auth.mjs +33 -0
- package/dist/impl/couch/auth.mjs.map +1 -0
- package/dist/impl/couch/classroomDB.mjs +227 -0
- package/dist/impl/couch/classroomDB.mjs.map +1 -0
- package/dist/impl/couch/clientCache.mjs +15 -0
- package/dist/impl/couch/clientCache.mjs.map +1 -0
- package/dist/impl/couch/courseAPI.mjs +183 -0
- package/dist/impl/couch/courseAPI.mjs.map +1 -0
- package/dist/impl/couch/courseDB.mjs +729 -0
- package/dist/impl/couch/courseDB.mjs.map +1 -0
- package/dist/impl/couch/courseLookupDB.mjs +94 -0
- package/dist/impl/couch/courseLookupDB.mjs.map +1 -0
- package/dist/impl/couch/{index.js → index.cjs} +6911 -10367
- package/dist/impl/couch/index.cjs.map +1 -0
- package/dist/impl/couch/index.d.ts +12 -5
- package/dist/impl/couch/index.mjs +134 -12146
- package/dist/impl/couch/index.mjs.map +1 -1
- package/dist/impl/couch/pouchdb-setup.mjs +15 -0
- package/dist/impl/couch/pouchdb-setup.mjs.map +1 -0
- package/dist/impl/couch/updateQueue.mjs +101 -0
- package/dist/impl/couch/updateQueue.mjs.map +1 -0
- package/dist/impl/couch/user-course-relDB.mjs +55 -0
- package/dist/impl/couch/user-course-relDB.mjs.map +1 -0
- package/dist/impl/static/NoOpSyncStrategy.mjs +49 -0
- package/dist/impl/static/NoOpSyncStrategy.mjs.map +1 -0
- package/dist/impl/static/StaticDataLayerProvider.mjs +94 -0
- package/dist/impl/static/StaticDataLayerProvider.mjs.map +1 -0
- package/dist/impl/static/StaticDataUnpacker.mjs +311 -0
- package/dist/impl/static/StaticDataUnpacker.mjs.map +1 -0
- package/dist/impl/static/courseDB.mjs +368 -0
- package/dist/impl/static/courseDB.mjs.map +1 -0
- package/dist/impl/static/coursesDB.mjs +38 -0
- package/dist/impl/static/coursesDB.mjs.map +1 -0
- package/dist/impl/static/{index.js → index.cjs} +2461 -5992
- package/dist/impl/static/index.cjs.map +1 -0
- package/dist/impl/static/index.d.ts +4 -4
- package/dist/impl/static/index.mjs +6 -10741
- package/dist/{index-CVGehe_t.d.ts → index-BLDpFYG3.d.ts} +1 -1
- package/dist/{index.js → index.cjs} +14070 -14239
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +12 -23
- package/dist/index.mjs +38 -16937
- package/dist/pouch/{index.js → index.cjs} +5 -1
- package/dist/pouch/index.cjs.map +1 -0
- package/dist/pouch/index.mjs +2 -19
- package/dist/study/ItemQueue.mjs +95 -0
- package/dist/study/ItemQueue.mjs.map +1 -0
- package/dist/study/MixerDebugger.mjs +303 -0
- package/dist/study/MixerDebugger.mjs.map +1 -0
- package/dist/study/SessionController.mjs +1187 -0
- package/dist/study/SessionController.mjs.map +1 -0
- package/dist/study/SessionDebugger.mjs +271 -0
- package/dist/study/SessionDebugger.mjs.map +1 -0
- package/dist/study/SessionOverlay.mjs +407 -0
- package/dist/study/SessionOverlay.mjs.map +1 -0
- package/dist/study/SourceMixer.mjs +45 -0
- package/dist/study/SourceMixer.mjs.map +1 -0
- package/dist/study/SpacedRepetition.mjs +108 -0
- package/dist/study/SpacedRepetition.mjs.map +1 -0
- package/dist/study/TagFilteredContentSource.mjs +136 -0
- package/dist/study/TagFilteredContentSource.mjs.map +1 -0
- package/dist/study/services/CardHydrationService.mjs +172 -0
- package/dist/study/services/CardHydrationService.mjs.map +1 -0
- package/dist/study/services/EloService.mjs +217 -0
- package/dist/study/services/EloService.mjs.map +1 -0
- package/dist/study/services/ResponseProcessor.mjs +190 -0
- package/dist/study/services/ResponseProcessor.mjs.map +1 -0
- package/dist/study/services/SrsService.mjs +49 -0
- package/dist/study/services/SrsService.mjs.map +1 -0
- package/dist/study/services/tagRecent.mjs +65 -0
- package/dist/study/services/tagRecent.mjs.map +1 -0
- package/dist/{types-dXWfyz9B.d.ts → types-DChCz22D.d.ts} +1 -1
- package/dist/{types-legacy-BkOYOR6U.d.cts → types-legacy-fT5Y1Wuy.d.ts} +1 -1
- package/dist/userDBKeys-ne1g4Xuq.d.ts +16 -0
- package/dist/util/Loggable.mjs +14 -0
- package/dist/util/Loggable.mjs.map +1 -0
- package/dist/util/dataDirectory.mjs +47 -0
- package/dist/util/dataDirectory.mjs.map +1 -0
- package/dist/util/logger.mjs +86 -0
- package/dist/util/logger.mjs.map +1 -0
- package/dist/util/migrator/FileSystemAdapter.mjs +18 -0
- package/dist/util/migrator/FileSystemAdapter.mjs.map +1 -0
- package/dist/util/migrator/StaticToCouchDBMigrator.mjs +428 -0
- package/dist/util/migrator/StaticToCouchDBMigrator.mjs.map +1 -0
- package/dist/util/migrator/types.mjs +11 -0
- package/dist/util/migrator/types.mjs.map +1 -0
- package/dist/util/migrator/validation.mjs +334 -0
- package/dist/util/migrator/validation.mjs.map +1 -0
- package/dist/util/packer/CouchDBToStaticPacker.mjs +438 -0
- package/dist/util/packer/CouchDBToStaticPacker.mjs.map +1 -0
- package/dist/util/packer/{index.js → index.cjs} +73 -9
- package/dist/util/packer/index.cjs.map +1 -0
- package/dist/util/packer/index.d.ts +3 -3
- package/dist/util/packer/index.mjs +2 -537
- package/eslint.config.mjs +9 -1
- package/package.json +25 -13
- package/rolldown.config.mjs +44 -0
- package/src/core/UserDBDebugger.ts +47 -46
- package/src/core/navigators/Pipeline.ts +10 -10
- package/src/core/navigators/PipelineDebugger.ts +55 -55
- package/src/core/navigators/filters/eloDistance.ts +11 -1
- package/src/core/navigators/generators/elo.ts +5 -1
- package/src/core/navigators/index.ts +9 -3
- package/src/diagnostics/derive.ts +6 -0
- package/src/diagnostics/index.ts +1 -0
- package/src/diagnostics/tagElo.ts +257 -0
- package/src/factory.ts +10 -1
- package/src/impl/common/BaseUserDB.ts +1 -3
- package/src/impl/common/index.ts +2 -0
- package/src/impl/common/userDBHelpers.ts +4 -58
- package/src/impl/common/userDBKeys.ts +64 -0
- package/src/impl/couch/courseDB.ts +15 -3
- package/src/impl/couch/index.ts +2 -18
- package/src/impl/couch/pouchdb-setup.ts +8 -0
- package/src/index.ts +1 -1
- package/src/study/MixerDebugger.ts +46 -46
- package/src/study/SessionDebugger.ts +20 -20
- package/src/study/SessionOverlay.ts +4 -4
- package/src/util/logger.ts +112 -13
- package/tests/core/navigators/eloGenerator.test.ts +36 -0
- package/tsup.config.ts +24 -21
- package/dist/SyncStrategy-BXliog1m.d.cts +0 -116
- package/dist/classroomDB-DLTtLZct.d.cts +0 -86
- package/dist/contentSource-JmWYu8IK.d.ts +0 -2007
- package/dist/core/index.d.cts +0 -521
- package/dist/core/index.js.map +0 -1
- package/dist/core/index.mjs.map +0 -1
- package/dist/dataLayerProvider-DfI_KYAe.d.cts +0 -61
- package/dist/diagnostics/index.d.cts +0 -458
- package/dist/diagnostics/index.js.map +0 -1
- package/dist/diagnostics/index.mjs.map +0 -1
- package/dist/impl/couch/index.d.cts +0 -620
- package/dist/impl/couch/index.js.map +0 -1
- package/dist/impl/static/index.d.cts +0 -232
- package/dist/impl/static/index.js.map +0 -1
- package/dist/impl/static/index.mjs.map +0 -1
- package/dist/index-Ktg72jKb.d.cts +0 -137
- package/dist/index.d.cts +0 -1663
- package/dist/index.js.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/pouch/index.d.cts +0 -1
- package/dist/pouch/index.js.map +0 -1
- package/dist/pouch/index.mjs.map +0 -1
- package/dist/types-D0oQeJAi.d.cts +0 -58
- package/dist/types-legacy-BkOYOR6U.d.ts +0 -168
- package/dist/util/packer/index.d.cts +0 -5
- package/dist/util/packer/index.js.map +0 -1
- package/dist/util/packer/index.mjs.map +0 -1
- package/src/study/getCardDataShape.ts +0 -34
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PipelineDebugger.mjs","names":[],"sources":["../../../src/core/navigators/PipelineDebugger.ts"],"sourcesContent":["import type { WeightedCard, StrategyContribution } from './index';\nimport {\n getRegisteredNavigatorNames,\n getRegisteredNavigatorRole,\n NavigatorRoles,\n type Navigators,\n isGenerator,\n isFilter,\n} from './index';\nimport { logger } from '../../util/logger';\nimport type { Pipeline, CardSpaceDiagnosis, PipelineForecaster } from './Pipeline';\nimport type { ReplanHints } from './generators/types';\nimport type { FilterKind } from './filters/types';\nimport type { RegulatorReading } from './regulators';\n\n/**\n * Captured reference to the most recently created Pipeline instance.\n * Used by the debug API to run diagnostics against the live pipeline.\n */\nlet _activePipeline: Pipeline | null = null;\n\n/**\n * Register a pipeline instance for diagnostic access.\n * Called by Pipeline constructor.\n */\nexport function registerPipelineForDebug(pipeline: Pipeline): void {\n _activePipeline = pipeline;\n}\n\n/**\n * The most recently constructed pipeline for the current session, or null if\n * none has been built yet. This is the supported, non-debug accessor for\n * out-of-band reads against the live pipeline (e.g. a commit-free\n * `forecast()`), replacing reach-ins through `window.skuilder.pipeline`.\n */\nexport function getActivePipeline(): PipelineForecaster | null {\n return _activePipeline;\n}\n\n// ============================================================================\n// PIPELINE DEBUGGER\n// ============================================================================\n//\n// Console-accessible debug API for inspecting pipeline decisions.\n//\n// Exposed as `window.skuilder.pipeline` for interactive exploration.\n//\n// Usage:\n// window.skuilder.pipeline.showLastRun()\n// window.skuilder.pipeline.showCard('cardId123')\n// window.skuilder.pipeline.explainReviews()\n// window.skuilder.pipeline.showPrescribed()\n// window.skuilder.pipeline.export()\n//\n// ============================================================================\n\n/**\n * Summary of a single generator's contribution.\n */\nexport interface GeneratorSummary {\n name: string;\n cardCount: number;\n newCount: number;\n reviewCount: number;\n topScore: number;\n}\n\n/**\n * Summary of a filter's impact on scores.\n */\nexport interface FilterImpact {\n name: string;\n /** Effective kind: undeclared filters count as gates. Absent on runs before 0.2.29. */\n kind?: FilterKind;\n boosted: number;\n penalized: number;\n passed: number;\n removed: number;\n}\n\n/** A run's version stamps. Either may be absent: no strategy hash, or no content version set. */\nexport interface RunVersions {\n strategies?: string;\n content?: string;\n}\n\n/** One card as retained in a {@link PipelineRunReport}. */\nexport interface RunReportCard {\n cardId: string;\n courseId: string;\n /** `'review'`: a scheduled review. `'new'`: anything else. */\n origin: 'new' | 'review';\n /** The strategy that produced the card (first provenance entry). Absent if a hint injected it. */\n generator?: string;\n /** The hint that made the card mandatory, if one did. Its source, over `generator`. */\n required?: string;\n finalScore: number;\n /** Card's ELO (parsed from ELO generator provenance, if available) */\n cardElo?: number;\n provenance: StrategyContribution[];\n tags?: string[];\n selected: boolean;\n}\n\n/**\n * Complete record of a single pipeline execution.\n */\nexport interface PipelineRunReport {\n runId: string;\n /** Absent for runs fired outside a session (forecasts, editor probes). */\n sessionId?: string;\n timestamp: Date;\n courseId: string;\n courseName?: string;\n\n /** User's global ELO at the time of this pipeline run */\n userElo?: number;\n\n // Generator phase\n generatorName: string;\n generators?: GeneratorSummary[];\n generatedCount: number;\n\n // Filter phase\n filters: FilterImpact[];\n\n /** Ephemeral hints applied during this run */\n hints?: ReplanHints;\n\n // Results\n finalCount: number;\n reviewsSelected: number;\n newSelected: number;\n\n /**\n * Card data for inspection.\n *\n * To keep the in-memory ring buffer small, this contains:\n * - All selected cards (the actual session output).\n * - The top-N highest-scoring non-selected cards (see DISCARDED_KEEP_TOP),\n * useful for understanding \"near misses\" and filter behavior.\n *\n * The remaining low-score tail of the candidate pool (mostly ELO-window\n * pull remnants that filters scored down) is summarized in `discardedTail`\n * rather than retained verbatim — each retained card carries a multi-KB\n * provenance trail, and the tail is typically hundreds of cards per run.\n */\n cards: RunReportCard[];\n\n /**\n * The two unselected non-review cards most worth explaining when a run\n * picks no new content. Non-review means no `reviewID`, so prescribed and\n * required cards count.\n *\n * - `nextInLine`: highest final score. How close new content came.\n * - `topGenerated`: highest generator score, zero-scored cards included.\n * Its provenance shows which filter sank it. Omitted when it is the same\n * card as `nextInLine`.\n */\n unselectedNew?: {\n nextInLine?: RunReportCard;\n topGenerated?: RunReportCard;\n };\n\n /** The regulator stage's readings: each class's pressure and the multiplier it got. */\n regulators?: RegulatorReading[];\n\n /**\n * What this run ran on (see versionStamps.ts): the hash of the strategy docs\n * the pipeline was assembled from, and the course's content version.\n */\n versions?: RunVersions;\n\n /**\n * Summary of the discarded tail of the candidate pool — cards that were\n * generated and scored but neither selected nor retained in `cards`.\n *\n * Provides breadcrumbs for \"where did card X go?\" investigations without\n * the memory cost of keeping every dropped candidate's provenance.\n *\n * Future: may carry a bloom filter of discarded cardIds so callers can\n * ask \"was X in this run's discard tail?\" with bounded memory cost.\n */\n discardedTail?: {\n count: number;\n /** [min, max] finalScore across the discarded tail. */\n scoreRange?: [number, number];\n /** [min, max] cardElo across the discarded tail (where parseable). */\n eloRange?: [number, number];\n /** Human-readable note for console display. */\n note: string;\n };\n}\n\n/**\n * Ring buffer for storing recent pipeline runs.\n */\nconst MAX_RUNS = 10;\nconst runHistory: PipelineRunReport[] = [];\n\n/**\n * Ambient, like `registerPipelineForDebug` — a pipeline is per content-source\n * and can outlive any one session. Set by `SessionController`.\n */\nlet _currentSessionId: string | undefined;\n\nexport function setDebugSessionId(sessionId: string | undefined): void {\n _currentSessionId = sessionId;\n}\n\n/**\n * Runs captured since the last drain. `SessionController` drains after each\n * plan and applies its own label — one plan can be several runs (one per\n * source), and the label is the controller's knowledge, not the pipeline's.\n */\nlet _pendingRuns: PipelineRunReport[] = [];\n\n/** Take and clear the runs captured since the previous call, in execution order. */\nexport function drainCapturedRuns(): PipelineRunReport[] {\n const drained = _pendingRuns;\n _pendingRuns = [];\n return drained;\n}\n\n/**\n * Runs for `sessionId`, oldest first. Bounded by {@link MAX_RUNS} — the\n * complete record is `StudySessionDoc.runs`.\n */\nexport function getRunsForSession(sessionId: string): PipelineRunReport[] {\n return runHistory.filter((r) => r.sessionId === sessionId).reverse();\n}\n\n/**\n * Cap on non-selected (\"discarded\") cards retained per run report.\n *\n * Pipeline candidate pools are typically hundreds of cards (ELO window pull\n * + generators), but most are scored down by filters and never selected.\n * Their provenance trails are the dominant text-memory cost in the ring\n * buffer (each entry ~1–2 KB). Retaining only the top-N \"near misses\"\n * preserves debugging value while collapsing memory roughly an order of\n * magnitude or more.\n */\nconst DISCARDED_KEEP_TOP = 25;\n\n/**\n * Programmatic clear of pipeline run history.\n *\n * Called by session-lifecycle hooks (session end, course switch, logout)\n * to release retained provenance/tag arrays once they're no longer useful\n * for in-session debugging. The interactive `clear()` debug method remains\n * for manual use.\n */\nexport function clearRunHistory(): void {\n runHistory.length = 0;\n _pendingRuns = [];\n}\n\n/**\n * What a card is to the learner's queue: a scheduled review (it carries a\n * `reviewID`) or new. The same test as the generator counts and\n * `unselectedNew`. What put it in the queue is {@link RunReportCard.generator}\n * and {@link RunReportCard.required}.\n */\nfunction getOrigin(card: WeightedCard): 'new' | 'review' {\n return card.reviewID ? 'review' : 'new';\n}\n\n/**\n * The hint that made a card mandatory (its provenance name), if one did.\n * applyHints marks a requireCards/requireTags requirement with an infinite\n * score, and nothing else scores a card infinite.\n */\nfunction requiredBy(card: WeightedCard): string | undefined {\n return card.provenance.find(\n (p) => p.strategy === 'ephemeralHint' && p.score === Number.POSITIVE_INFINITY\n )?.strategyName;\n}\n\n/**\n * Capture a pipeline run for later inspection.\n */\nexport function captureRun(\n report: Omit<PipelineRunReport, 'runId' | 'timestamp' | 'sessionId'>\n): PipelineRunReport {\n const fullReport: PipelineRunReport = {\n ...report,\n runId: `run-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n sessionId: _currentSessionId,\n timestamp: new Date(),\n };\n\n runHistory.unshift(fullReport);\n if (runHistory.length > MAX_RUNS) {\n runHistory.pop();\n }\n _pendingRuns.push(fullReport);\n return fullReport;\n}\n\n/**\n * Build a capture-ready report from pipeline execution data.\n */\n/**\n * Parse card ELO from the ELO generator's provenance reason string.\n * Format: \"ELO distance XX (card: YYYY, user: ZZZZ), ...\"\n */\nfunction parseCardElo(provenance: StrategyContribution[]): number | undefined {\n const eloEntry = provenance.find((p) => p.strategy === 'elo');\n if (!eloEntry?.reason) return undefined;\n const match = eloEntry.reason.match(/card:\\s*(\\d+)/);\n return match ? parseInt(match[1], 10) : undefined;\n}\n\nexport function buildRunReport(\n courseId: string,\n courseName: string | undefined,\n generatorName: string,\n generators: GeneratorSummary[] | undefined,\n generatedCount: number,\n filters: FilterImpact[],\n allCards: WeightedCard[],\n selectedCards: WeightedCard[],\n userElo?: number,\n hints?: ReplanHints,\n /** Post-filter cards before zero-scored ones are dropped. Defaults to `allCards`. */\n scoredCards?: WeightedCard[],\n regulators?: RegulatorReading[]\n): Omit<PipelineRunReport, 'runId' | 'timestamp'> {\n const selectedIds = new Set(selectedCards.map((c) => c.cardId));\n\n // `allCards` arrives post-filter and sorted by score (desc). Partition\n // into selected vs not-selected, then retain only the top-N of the\n // non-selected group to bound memory. The remaining low-score tail is\n // summarized rather than kept (see discardedTail).\n const toReport = (card: WeightedCard): RunReportCard => {\n const required = requiredBy(card);\n // A required card no generator produced starts at its hint: no generator.\n const first = card.provenance[0];\n const generator =\n first && first.strategy !== 'ephemeralHint' ? first.strategyName || first.strategy : undefined;\n return {\n cardId: card.cardId,\n courseId: card.courseId,\n origin: getOrigin(card),\n ...(generator ? { generator } : {}),\n ...(required ? { required } : {}),\n finalScore: card.score,\n cardElo: card.cardElo ?? parseCardElo(card.provenance),\n provenance: card.provenance,\n tags: card.tags,\n selected: selectedIds.has(card.cardId),\n };\n };\n\n const selectedReported: RunReportCard[] = [];\n const nearMissReported: RunReportCard[] = [];\n const discardedTailCards: WeightedCard[] = [];\n\n let nonSelectedSeen = 0;\n for (const card of allCards) {\n if (selectedIds.has(card.cardId)) {\n selectedReported.push(toReport(card));\n } else if (nonSelectedSeen < DISCARDED_KEEP_TOP) {\n nearMissReported.push(toReport(card));\n nonSelectedSeen++;\n } else {\n discardedTailCards.push(card);\n }\n }\n\n const cards = [...selectedReported, ...nearMissReported];\n\n let discardedTail: PipelineRunReport['discardedTail'];\n if (discardedTailCards.length > 0) {\n let scoreMin = Infinity;\n let scoreMax = -Infinity;\n let eloMin = Infinity;\n let eloMax = -Infinity;\n let eloSeen = false;\n for (const c of discardedTailCards) {\n if (c.score < scoreMin) scoreMin = c.score;\n if (c.score > scoreMax) scoreMax = c.score;\n const elo = parseCardElo(c.provenance);\n if (elo !== undefined) {\n eloSeen = true;\n if (elo < eloMin) eloMin = elo;\n if (elo > eloMax) eloMax = elo;\n }\n }\n const eloFragment = eloSeen ? `, ELO ${eloMin}–${eloMax}` : '';\n discardedTail = {\n count: discardedTailCards.length,\n scoreRange: [scoreMin, scoreMax],\n eloRange: eloSeen ? [eloMin, eloMax] : undefined,\n note:\n `${discardedTailCards.length} additional candidate(s) scored below the ` +\n `top ${DISCARDED_KEEP_TOP} near-misses and were not retained ` +\n `(score ${scoreMin.toExponential(2)}–${scoreMax.toExponential(2)}${eloFragment}). ` +\n `Likely ELO-window pull remnants filtered out by hierarchy/lesson/priority gates.`,\n };\n }\n\n // Unselected non-review candidates. `nextInLine` ranks by final score, so it\n // comes from `allCards` (post-hints; zero-scored dropped). `topGenerated`\n // ranks by generator score and must see the zero-scored cards too, but not\n // cards a hint excluded: exclusion leaves no provenance to explain them.\n const isUnselectedNew = (c: WeightedCard) => !c.reviewID && !selectedIds.has(c.cardId);\n const generatorScore = (c: WeightedCard) => c.provenance[0]?.score ?? 0;\n const keptIds = new Set(allCards.map((c) => c.cardId));\n const hintExcluded = (c: WeightedCard) => c.score > 0 && !keptIds.has(c.cardId);\n let nextInLine: WeightedCard | undefined;\n for (const c of allCards) {\n if (isUnselectedNew(c) && (!nextInLine || c.score > nextInLine.score)) nextInLine = c;\n }\n let topGenerated: WeightedCard | undefined;\n for (const c of scoredCards ?? allCards) {\n if (!isUnselectedNew(c) || hintExcluded(c)) continue;\n if (!topGenerated || generatorScore(c) > generatorScore(topGenerated)) topGenerated = c;\n }\n const unselectedNew =\n nextInLine || topGenerated\n ? {\n ...(nextInLine ? { nextInLine: toReport(nextInLine) } : {}),\n ...(topGenerated && topGenerated.cardId !== nextInLine?.cardId\n ? { topGenerated: toReport(topGenerated) }\n : {}),\n }\n : undefined;\n\n const reviewsSelected = selectedCards.filter((c) => getOrigin(c) === 'review').length;\n const newSelected = selectedCards.filter((c) => getOrigin(c) === 'new').length;\n\n return {\n courseId,\n courseName,\n userElo,\n generatorName,\n generators,\n generatedCount,\n filters,\n hints,\n finalCount: selectedCards.length,\n reviewsSelected,\n newSelected,\n cards,\n unselectedNew,\n discardedTail,\n ...(regulators ? { regulators } : {}),\n };\n}\n\n// ============================================================================\n// CONSOLE API\n// ============================================================================\n\n/**\n * Format a provenance trail for console display.\n */\nfunction formatProvenance(provenance: StrategyContribution[]): string {\n return provenance\n .map((p) => {\n const actionSymbol =\n p.action === 'generated'\n ? '🎲'\n : p.action === 'boosted'\n ? '⬆️'\n : p.action === 'penalized'\n ? '⬇️'\n : '➡️';\n return ` ${actionSymbol} ${p.strategyName}: ${p.score.toFixed(3)} - ${p.reason}`;\n })\n .join('\\n');\n}\n\n/**\n * Print summary of a single pipeline run.\n */\nfunction printRunSummary(run: PipelineRunReport): void {\n // eslint-disable-next-line no-console\n console.group(`🔍 Pipeline Run: ${run.courseId} (${run.courseName || 'unnamed'})`);\n logger.print(`Run ID: ${run.runId}`);\n logger.print(`Time: ${run.timestamp.toISOString()}`);\n logger.print(`User ELO: ${run.userElo ?? 'unknown'}`);\n logger.print(`Generator: ${run.generatorName} → ${run.generatedCount} candidates`);\n\n if (run.generators && run.generators.length > 0) {\n // eslint-disable-next-line no-console\n console.group('Generator breakdown:');\n for (const g of run.generators) {\n logger.print(\n ` ${g.name}: ${g.cardCount} cards (${g.newCount} new, ${g.reviewCount} reviews, top: ${g.topScore.toFixed(2)})`\n );\n }\n // eslint-disable-next-line no-console\n console.groupEnd();\n }\n\n if (run.filters.length > 0) {\n // eslint-disable-next-line no-console\n console.group('Filter impact:');\n for (const f of run.filters) {\n logger.print(` ${f.name}: ↑${f.boosted} ↓${f.penalized} =${f.passed} ✕${f.removed}`);\n }\n // eslint-disable-next-line no-console\n console.groupEnd();\n }\n\n logger.print(\n `Result: ${run.finalCount} cards selected (${run.newSelected} new, ${run.reviewsSelected} reviews)`\n );\n // eslint-disable-next-line no-console\n console.groupEnd();\n}\n\n// ============================================================================\n// UI DEBUGGER (VANILLA HTML)\n// ============================================================================\n\nlet _uiContainer: HTMLElement | null = null;\nlet _selectedRunIndex: number | null = null;\nlet _cardSearchQuery = '';\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>');\n}\n\nfunction escapeAttr(s: string): string {\n return escapeHtml(s).replace(/\"/g, '"');\n}\n\nfunction copyTextToClipboard(text: string, btn?: HTMLElement): void {\n const done = () => {\n if (!btn) return;\n const orig = btn.textContent ?? 'Copy';\n btn.textContent = 'Copied!';\n btn.classList.add('copied');\n setTimeout(() => {\n btn.textContent = orig;\n btn.classList.remove('copied');\n }, 1200);\n };\n const fallback = () => {\n const ta = document.createElement('textarea');\n ta.value = text;\n ta.style.position = 'fixed';\n ta.style.opacity = '0';\n document.body.appendChild(ta);\n ta.select();\n try {\n document.execCommand('copy');\n } catch (e) {\n logger.warn(`[Pipeline Debug] Copy failed: ${e}`);\n }\n document.body.removeChild(ta);\n done();\n };\n if (navigator.clipboard?.writeText) {\n navigator.clipboard.writeText(text).then(done).catch(fallback);\n } else {\n fallback();\n }\n}\n\nfunction renderUI(): void {\n if (!_uiContainer) return;\n\n const runs = runHistory;\n const selectedRun = _selectedRunIndex !== null ? runs[_selectedRunIndex] : null;\n\n const styles = `\n #sk-pipeline-debugger {\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background: #f8f9fa;\n color: #212529;\n z-index: 999999;\n display: flex;\n flex-direction: column;\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Helvetica, Arial, sans-serif;\n font-size: 14px;\n }\n #sk-pipeline-debugger header {\n padding: 1rem;\n background: #343a40;\n color: white;\n display: flex;\n justify-content: space-between;\n align-items: center;\n }\n #sk-pipeline-debugger .container {\n display: flex;\n flex: 1;\n overflow: hidden;\n }\n #sk-pipeline-debugger .sidebar {\n width: 300px;\n border-right: 1px solid #dee2e6;\n overflow-y: auto;\n background: white;\n }\n #sk-pipeline-debugger .main-content {\n flex: 1;\n overflow-y: auto;\n padding: 1.5rem;\n }\n #sk-pipeline-debugger .run-item {\n padding: 0.75rem 1rem;\n border-bottom: 1px solid #eee;\n cursor: pointer;\n }\n #sk-pipeline-debugger .run-item:hover { background: #f1f3f5; }\n #sk-pipeline-debugger .run-item.active { background: #e9ecef; border-left: 4px solid #007bff; }\n #sk-pipeline-debugger h2, #sk-pipeline-debugger h3 { margin-top: 0; }\n #sk-pipeline-debugger table { width: 100%; border-collapse: collapse; margin-bottom: 1rem; background: white; }\n #sk-pipeline-debugger th, #sk-pipeline-debugger td { border: 1px solid #dee2e6; padding: 0.5rem; text-align: left; }\n #sk-pipeline-debugger th { background: #f1f3f5; }\n #sk-pipeline-debugger code { background: #f1f3f5; padding: 0.1rem 0.3rem; border-radius: 3px; font-family: monospace; }\n #sk-pipeline-debugger .close-btn { background: #dc3545; color: white; border: none; padding: 0.5rem 1rem; border-radius: 4px; cursor: pointer; }\n #sk-pipeline-debugger .search-box { margin-bottom: 1rem; width: 100%; padding: 0.5rem; border: 1px solid #ced4da; border-radius: 4px; }\n #sk-pipeline-debugger .provenance { font-size: 12px; color: #666; margin-top: 0.25rem; white-space: pre-wrap; font-family: monospace; background: #f8f9fa; padding: 0.5rem; border-radius: 4px; }\n #sk-pipeline-debugger .run-label { display: inline-block; margin-top: 0.25rem; padding: 0.1rem 0.4rem; background: #fff3cd; color: #664d03; border-radius: 3px; font-family: monospace; font-size: 11px; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: bottom; }\n #sk-pipeline-debugger .label-banner { display: inline-block; padding: 0.25rem 0.6rem; background: #fff3cd; color: #664d03; border-radius: 4px; font-family: monospace; font-size: 13px; margin: 0 0 0.75rem 0; }\n #sk-pipeline-debugger .copy-btn { background: #0d6efd; color: white; border: none; padding: 0.25rem 0.6rem; border-radius: 3px; cursor: pointer; font-size: 12px; margin-left: 0.5rem; }\n #sk-pipeline-debugger .copy-btn:hover { background: #0b5ed7; }\n #sk-pipeline-debugger .copy-btn.copied { background: #198754; }\n #sk-pipeline-debugger .section-head { display: flex; align-items: center; justify-content: space-between; margin-top: 1rem; }\n #sk-pipeline-debugger .section-head h3 { margin: 0; }\n `;\n\n const runListHtml =\n runs.length === 0\n ? '<div style=\"padding: 1rem;\">No runs captured yet.</div>'\n : runs\n .map(\n (r, i) => `\n <div class=\"run-item ${i === _selectedRunIndex ? 'active' : ''}\" onclick=\"window.skuilder.pipeline._selectRun(${i})\">\n <strong>${r.timestamp.toLocaleTimeString()}</strong><br/>\n <small>${r.courseName || r.courseId.slice(0, 8)}</small><br/>\n <small>${r.finalCount} cards selected</small>\n ${r.hints?._label ? `<br/><span class=\"run-label\" title=\"${escapeAttr(r.hints._label)}\">${escapeHtml(r.hints._label)}</span>` : ''}\n </div>\n `\n )\n .join('');\n\n let detailsHtml =\n '<div style=\"color: #6c757d; text-align: center; margin-top: 5rem;\">Select a run to see details</div>';\n\n if (selectedRun) {\n const filteredCards = selectedRun.cards.filter(\n (c) =>\n !_cardSearchQuery || c.cardId.toLowerCase().includes(_cardSearchQuery.toLowerCase())\n );\n\n const labelText = selectedRun.hints?._label ?? '(no label)';\n detailsHtml = `\n <h2>Run: ${selectedRun.runId}</h2>\n <div class=\"label-banner\" title=\"${escapeAttr(labelText)}\">${escapeHtml(labelText)}</div>\n <p>\n <strong>Time:</strong> ${selectedRun.timestamp.toLocaleString()} |\n <strong>Course:</strong> ${selectedRun.courseName || selectedRun.courseId} |\n <strong>User ELO:</strong> ${selectedRun.userElo ?? 'unknown'}\n </p>\n\n <h3>Pipeline Config</h3>\n <table>\n <tr><th>Generator</th><td>${selectedRun.generatorName} (${selectedRun.generatedCount} candidates)</td></tr>\n ${(selectedRun.generators || [])\n .map(\n (g) => `\n <tr><td style=\"padding-left: 2rem;\">↳ ${g.name}</td><td>${g.cardCount} cards (${g.newCount} new, ${g.reviewCount} review, top: ${g.topScore.toFixed(2)})</td></tr>\n `\n )\n .join('')}\n </table>\n\n ${\n selectedRun.hints\n ? `\n <div class=\"section-head\">\n <h3>Ephemeral Hints</h3>\n <button class=\"copy-btn\" onclick=\"window.skuilder.pipeline._copyConfig('${selectedRun.runId}', this)\">Copy config</button>\n </div>\n <table>\n ${selectedRun.hints._label ? `<tr><th>Label</th><td>${selectedRun.hints._label}</td></tr>` : ''}\n ${\n selectedRun.hints.boostTags\n ? `<tr><th>Boost Tags</th><td><pre style=\"margin:0\">${JSON.stringify(selectedRun.hints.boostTags, null, 2)}</pre></td></tr>`\n : ''\n }\n ${\n selectedRun.hints.boostCards\n ? `<tr><th>Boost Cards</th><td><pre style=\"margin:0\">${JSON.stringify(selectedRun.hints.boostCards, null, 2)}</pre></td></tr>`\n : ''\n }\n ${\n selectedRun.hints.requireTags\n ? `<tr><th>Require Tags</th><td>${selectedRun.hints.requireTags.join(', ')}</td></tr>`\n : ''\n }\n ${\n selectedRun.hints.requireCards\n ? `<tr><th>Require Cards</th><td>${selectedRun.hints.requireCards.join(', ')}</td></tr>`\n : ''\n }\n ${\n selectedRun.hints.excludeTags\n ? `<tr><th>Exclude Tags</th><td>${selectedRun.hints.excludeTags.join(', ')}</td></tr>`\n : ''\n }\n ${\n selectedRun.hints.excludeCards\n ? `<tr><th>Exclude Cards</th><td>${selectedRun.hints.excludeCards.join(', ')}</td></tr>`\n : ''\n }\n </table>\n `\n : ''\n }\n\n <h3>Filter Impact</h3>\n <table>\n <thead><tr><th>Filter</th><th>Boosted</th><th>Penalized</th><th>Passed</th><th>Removed</th></tr></thead>\n <tbody>\n ${selectedRun.filters\n .map(\n (f) => `\n <tr><td>${f.name}</td><td>↑${f.boosted}</td><td>↓${f.penalized}</td><td>=${f.passed}</td><td>✕${f.removed}</td></tr>\n `\n )\n .join('')}\n </tbody>\n </table>\n\n <div class=\"section-head\">\n <h3>Cards (${selectedRun.finalCount} selected / ${selectedRun.cards.length} total)</h3>\n <button class=\"copy-btn\" onclick=\"window.skuilder.pipeline._copyResults('${selectedRun.runId}', this)\">Copy results</button>\n </div>\n <input type=\"text\" class=\"search-box\" placeholder=\"Search Card ID...\" value=\"${_cardSearchQuery}\" oninput=\"window.skuilder.pipeline._setSearch(this.value)\">\n \n <table>\n <thead><tr><th>ID</th><th>Generator</th><th>Origin</th><th>Score</th><th>Selected</th></tr></thead>\n <tbody>\n ${filteredCards\n .map(\n (c) => `\n <tr>\n <td><code>${c.cardId}</code></td>\n <td>${c.generator || 'unknown'}</td>\n <td>${c.origin}</td>\n <td>${c.finalScore.toFixed(3)}</td>\n <td>${c.selected ? '✅' : '❌'}</td>\n </tr>\n ${\n c.selected || _cardSearchQuery\n ? `\n <tr>\n <td colspan=\"5\">\n <div class=\"provenance\">${formatProvenance(c.provenance)}</div>\n </td>\n </tr>\n `\n : ''\n }\n `\n )\n .join('')}\n </tbody>\n </table>\n `;\n }\n\n _uiContainer.innerHTML = `\n <style>${styles}</style>\n <header>\n <strong>Pipeline Debugger</strong>\n <button class=\"close-btn\" onclick=\"window.skuilder.pipeline.ui()\">Close</button>\n </header>\n <div class=\"container\">\n <div class=\"sidebar\">${runListHtml}</div>\n <div class=\"main-content\">${detailsHtml}</div>\n </div>\n `;\n}\n\n/**\n * Console API object exposed on window.skuilder.pipeline\n */\nexport const pipelineDebugAPI = {\n /**\n * Get raw run history for programmatic access.\n */\n get runs(): PipelineRunReport[] {\n return [...runHistory];\n },\n\n /**\n * Show summary of a specific pipeline run.\n */\n showRun(idOrIndex: string | number = 0): void {\n if (runHistory.length === 0) {\n logger.print('[Pipeline Debug] No runs captured yet.');\n return;\n }\n\n let run: PipelineRunReport | undefined;\n\n if (typeof idOrIndex === 'number') {\n run = runHistory[idOrIndex];\n if (!run) {\n logger.print(\n `[Pipeline Debug] No run found at index ${idOrIndex}. History length: ${runHistory.length}`\n );\n return;\n }\n } else {\n run = runHistory.find((r) => r.runId.endsWith(idOrIndex));\n if (!run) {\n logger.print(`[Pipeline Debug] No run found matching ID '${idOrIndex}'.`);\n return;\n }\n }\n\n printRunSummary(run);\n },\n\n /**\n * Show summary of the last pipeline run.\n */\n showLastRun(): void {\n this.showRun(0);\n },\n\n /**\n * Show detailed provenance for a specific card.\n */\n showCard(cardId: string): void {\n for (const run of runHistory) {\n const card = run.cards.find((c) => c.cardId === cardId);\n if (card) {\n // eslint-disable-next-line no-console\n console.group(`🎴 Card: ${cardId}`);\n logger.print(`Course: ${card.courseId}`);\n logger.print(`Origin: ${card.origin}`);\n logger.print(`Card ELO: ${card.cardElo ?? 'unknown'} | User ELO: ${run.userElo ?? 'unknown'}`);\n logger.print(`Final score: ${card.finalScore.toFixed(3)}`);\n logger.print(`Selected: ${card.selected ? 'Yes ✅' : 'No ❌'}`);\n if (card.tags && card.tags.length > 0) {\n logger.print(`Tags (${card.tags.length}): ${card.tags.join(', ')}`);\n }\n logger.print('Provenance:');\n logger.print(formatProvenance(card.provenance));\n // eslint-disable-next-line no-console\n console.groupEnd();\n return;\n }\n }\n // Not found in any retained card list. If runs have discarded tails, the\n // card may have been in the low-score remnant pool — surface that as a\n // breadcrumb rather than a flat \"not found\".\n const runsWithTails = runHistory.filter((r) => r.discardedTail && r.discardedTail.count > 0);\n if (runsWithTails.length > 0) {\n logger.print(\n `[Pipeline Debug] Card '${cardId}' not found in retained cards. ` +\n `${runsWithTails.length} run(s) have discarded tails that were not retained — ` +\n `the card may have been a low-score candidate. See run.discardedTail for ranges.`\n );\n } else {\n logger.print(`[Pipeline Debug] Card '${cardId}' not found in recent runs.`);\n }\n },\n\n /**\n * Explain why reviews may or may not have been selected.\n */\n explainReviews(): void {\n if (runHistory.length === 0) {\n logger.print('[Pipeline Debug] No runs captured yet.');\n return;\n }\n\n // eslint-disable-next-line no-console\n console.group('📋 Review Selection Analysis');\n\n for (const run of runHistory) {\n // eslint-disable-next-line no-console\n console.group(`Run: ${run.courseId} @ ${run.timestamp.toLocaleTimeString()}`);\n\n const allReviews = run.cards.filter((c) => c.origin === 'review');\n const selectedReviews = allReviews.filter((c) => c.selected);\n\n if (allReviews.length === 0) {\n logger.print('❌ No reviews were generated. Check SRS logs for why.');\n } else if (selectedReviews.length === 0) {\n logger.print(`⚠️ ${allReviews.length} reviews generated but none selected.`);\n logger.print('Possible reasons:');\n\n // Check if new cards scored higher\n const topNewScore = Math.max(\n ...run.cards.filter((c) => c.origin === 'new' && c.selected).map((c) => c.finalScore),\n 0\n );\n const topReviewScore = Math.max(...allReviews.map((c) => c.finalScore), 0);\n\n if (topReviewScore < topNewScore) {\n logger.print(\n ` - New cards scored higher (top new: ${topNewScore.toFixed(2)}, top review: ${topReviewScore.toFixed(2)})`\n );\n }\n\n // Show top review that didn't make it\n const topReview = allReviews.sort((a, b) => b.finalScore - a.finalScore)[0];\n if (topReview) {\n logger.print(` - Top review score: ${topReview.finalScore.toFixed(3)}`);\n logger.print(' - Its provenance:');\n logger.print(formatProvenance(topReview.provenance));\n }\n } else {\n logger.print(`✅ ${selectedReviews.length}/${allReviews.length} reviews selected.`);\n logger.print('Top selected review:');\n const topSelected = selectedReviews.sort((a, b) => b.finalScore - a.finalScore)[0];\n logger.print(formatProvenance(topSelected.provenance));\n }\n\n // eslint-disable-next-line no-console\n console.groupEnd();\n }\n\n // eslint-disable-next-line no-console\n console.groupEnd();\n },\n\n /**\n * Show prescribed-related cards from the most recent run.\n *\n * Highlights:\n * - cards directly generated by the prescribed strategy\n * - blocked prescribed targets mentioned in provenance\n * - support tags resolved for blocked targets\n *\n * @param groupId - Optional prescribed group ID filter (e.g. 'intro-core')\n */\n showPrescribed(groupId?: string): void {\n if (runHistory.length === 0) {\n logger.print('[Pipeline Debug] No runs captured yet.');\n return;\n }\n\n const run = runHistory[0];\n const prescribedCards = run.cards.filter((c) =>\n c.provenance.some((p) => p.strategy === 'prescribed')\n );\n\n // eslint-disable-next-line no-console\n console.group(`🧭 Prescribed Debug (${run.courseId})`);\n\n if (prescribedCards.length === 0) {\n logger.print('No prescribed-generated cards were present in the most recent run.');\n // eslint-disable-next-line no-console\n console.groupEnd();\n return;\n }\n\n const rows = prescribedCards\n .map((card) => {\n const prescribedProv = card.provenance.find((p) => p.strategy === 'prescribed');\n const reason = prescribedProv?.reason ?? '';\n const parsedGroup = reason.match(/group=([^;]+)/)?.[1] ?? 'unknown';\n const mode = reason.match(/mode=([^;]+)/)?.[1] ?? 'unknown';\n const blocked = reason.match(/blocked=([^;]+)/)?.[1] ?? 'unknown';\n const blockedTargets = reason.match(/blockedTargets=([^;]+)/)?.[1] ?? 'none';\n const supportCard = reason.match(/supportCard=([^;]+)/)?.[1] ?? 'none';\n const supportTags = reason.match(/supportTags=([^;]+)/)?.[1] ?? 'none';\n const multiplier = reason.match(/multiplier=([^;]+)/)?.[1] ?? 'unknown';\n const supportSource =\n mode === 'discovered-support'\n ? 'discovered'\n : mode === 'support'\n ? 'authored'\n : 'n/a';\n\n return {\n group: parsedGroup,\n mode,\n supportSource,\n cardId: card.cardId,\n selected: card.selected ? 'yes' : 'no',\n finalScore: card.finalScore.toFixed(3),\n blocked,\n blockedTargets,\n supportCard,\n supportTags,\n multiplier,\n };\n })\n .filter((row) => !groupId || row.group === groupId)\n .sort((a, b) => Number(b.finalScore) - Number(a.finalScore));\n\n if (rows.length === 0) {\n logger.print(\n `[Pipeline Debug] No prescribed cards matched group '${groupId}' in the most recent run.`\n );\n // eslint-disable-next-line no-console\n console.groupEnd();\n return;\n }\n\n // eslint-disable-next-line no-console\n console.table(rows);\n\n const selectedRows = rows.filter((r) => r.selected === 'yes');\n const blockedTargetSet = new Set<string>();\n const supportTagSet = new Set<string>();\n const authoredSupportSet = new Set<string>();\n const discoveredSupportSet = new Set<string>();\n\n for (const row of rows) {\n if (row.blockedTargets && row.blockedTargets !== 'none') {\n row.blockedTargets\n .split('|')\n .filter(Boolean)\n .forEach((t) => blockedTargetSet.add(t));\n }\n if (row.supportTags && row.supportTags !== 'none') {\n row.supportTags\n .split('|')\n .filter(Boolean)\n .forEach((t) => supportTagSet.add(t));\n }\n if (row.supportCard && row.supportCard !== 'none') {\n if (row.supportSource === 'discovered') {\n discoveredSupportSet.add(row.supportCard);\n } else if (row.supportSource === 'authored') {\n authoredSupportSet.add(row.supportCard);\n }\n }\n }\n\n logger.print(`Prescribed cards in run: ${rows.length}`);\n logger.print(`Selected prescribed cards: ${selectedRows.length}`);\n logger.print(\n `Blocked prescribed targets referenced: ${blockedTargetSet.size > 0 ? [...blockedTargetSet].join(', ') : 'none'}`\n );\n logger.print(\n `Resolved support tags referenced: ${supportTagSet.size > 0 ? [...supportTagSet].join(', ') : 'none'}`\n );\n logger.print(\n `Authored support cards emitted: ${authoredSupportSet.size > 0 ? [...authoredSupportSet].join(', ') : 'none'}`\n );\n logger.print(\n `Discovered support cards emitted: ${discoveredSupportSet.size > 0 ? [...discoveredSupportSet].join(', ') : 'none'}`\n );\n\n // eslint-disable-next-line no-console\n console.groupEnd();\n },\n\n /**\n * Show all runs in compact format.\n */\n listRuns(): void {\n if (runHistory.length === 0) {\n logger.print('[Pipeline Debug] No runs captured yet.');\n return;\n }\n\n // eslint-disable-next-line no-console\n console.table(\n runHistory.map((r) => ({\n id: r.runId.slice(-8),\n time: r.timestamp.toLocaleTimeString(),\n course: r.courseName || r.courseId.slice(0, 8),\n generated: r.generatedCount,\n selected: r.finalCount,\n new: r.newSelected,\n reviews: r.reviewsSelected,\n }))\n );\n },\n\n /**\n * Export run history as JSON for bug reports.\n */\n export(): string {\n const json = JSON.stringify(runHistory, null, 2);\n logger.print('[Pipeline Debug] Run history exported. Copy the returned string or use:');\n logger.print(' copy(window.skuilder.pipeline.export())');\n return json;\n },\n\n /**\n * Clear run history.\n */\n clear(): void {\n runHistory.length = 0;\n logger.print('[Pipeline Debug] Run history cleared.');\n },\n\n /**\n * Show the navigator registry: all registered classes and their roles.\n *\n * Useful for verifying that consumer-defined navigators were registered\n * before pipeline assembly.\n */\n showRegistry(): void {\n const names = getRegisteredNavigatorNames();\n if (names.length === 0) {\n logger.print('[Pipeline Debug] Navigator registry is empty.');\n return;\n }\n\n // eslint-disable-next-line no-console\n console.group('📦 Navigator Registry');\n // eslint-disable-next-line no-console\n console.table(\n names.map((name) => {\n const registryRole = getRegisteredNavigatorRole(name);\n const builtinRole = NavigatorRoles[name as Navigators];\n const effectiveRole = builtinRole || registryRole || '⚠️ NONE';\n const source = builtinRole ? 'built-in' : registryRole ? 'consumer' : 'unclassified';\n return {\n name,\n role: effectiveRole,\n source,\n isGenerator: isGenerator(name),\n isFilter: isFilter(name),\n };\n })\n );\n // eslint-disable-next-line no-console\n console.groupEnd();\n },\n\n /**\n * Show strategy documents from the last pipeline run and how they mapped\n * to the registry.\n *\n * If no runs are captured yet, falls back to showing just the registry.\n */\n showStrategies(): void {\n this.showRegistry();\n\n if (runHistory.length === 0) {\n logger.print('[Pipeline Debug] No pipeline runs captured yet — cannot show strategy doc mapping.');\n return;\n }\n\n const run = runHistory[0];\n // eslint-disable-next-line no-console\n console.group('🔌 Pipeline Strategy Mapping (last run)');\n logger.print(`Generator: ${run.generatorName}`);\n if (run.generators && run.generators.length > 0) {\n for (const g of run.generators) {\n logger.print(` 📥 ${g.name}: ${g.cardCount} cards (${g.newCount} new, ${g.reviewCount} reviews)`);\n }\n }\n if (run.filters.length > 0) {\n logger.print('Filters:');\n for (const f of run.filters) {\n logger.print(` 🔸 ${f.name}: ↑${f.boosted} ↓${f.penalized} =${f.passed} ✕${f.removed}`);\n }\n } else {\n logger.print('Filters: (none)');\n }\n // eslint-disable-next-line no-console\n console.groupEnd();\n },\n\n /**\n * Scan the full card space through the filter chain for the current user.\n *\n * Reports how many cards are well-indicated and how many are new.\n * Use this to understand how the search space grows during onboarding.\n *\n * @param threshold - Score threshold for \"well indicated\" (default 0.10)\n */\n async diagnoseCardSpace(threshold?: number): Promise<CardSpaceDiagnosis | null> {\n if (!_activePipeline) {\n logger.print('[Pipeline Debug] No active pipeline. Run a session first.');\n return null;\n }\n return _activePipeline.diagnoseCardSpace({ threshold });\n },\n\n /**\n * Show user's per-tag ELO data. Useful for diagnosing hierarchy gate status.\n *\n * @param tagFilter - Optional glob pattern(s) to filter tags.\n * Examples: 'gpc:expose:*', 'gpc:intro:t-T', ['gpc:expose:t-*', 'gpc:intro:t-*']\n */\n async showTagElo(tagFilter?: string | string[]): Promise<void> {\n if (!_activePipeline) {\n logger.print('[Pipeline Debug] No active pipeline. Run a session first.');\n return;\n }\n const status = await _activePipeline.getTagEloStatus(tagFilter);\n const entries = Object.entries(status).sort(([a], [b]) => a.localeCompare(b));\n if (entries.length === 0) {\n logger.print(`[Pipeline Debug] No tag ELO data found${tagFilter ? ` for pattern: ${tagFilter}` : ''}.`);\n return;\n }\n // eslint-disable-next-line no-console\n console.table(\n Object.fromEntries(entries.map(([tag, data]) => [tag, { score: Math.round(data.score), count: data.count }]))\n );\n },\n\n /**\n * Toggle the full-screen UI debugger.\n */\n ui(): void {\n if (_uiContainer) {\n document.body.removeChild(_uiContainer);\n _uiContainer = null;\n return;\n }\n\n _uiContainer = document.createElement('div');\n _uiContainer.id = 'sk-pipeline-debugger';\n document.body.appendChild(_uiContainer);\n\n // Initial select last run if any\n if (_selectedRunIndex === null && runHistory.length > 0) {\n _selectedRunIndex = 0;\n }\n\n renderUI();\n },\n\n /**\n * Internal UI helpers\n * @internal\n */\n _selectRun(index: number): void {\n _selectedRunIndex = index;\n renderUI();\n },\n\n /**\n * Internal UI helpers\n * @internal\n */\n _setSearch(query: string): void {\n _cardSearchQuery = query;\n renderUI();\n },\n\n /**\n * Internal UI helpers\n * @internal\n */\n _copyConfig(runId: string, btn?: HTMLElement): void {\n const run = runHistory.find((r) => r.runId === runId);\n if (!run) return;\n const payload = {\n runId: run.runId,\n timestamp: run.timestamp.toISOString(),\n courseId: run.courseId,\n courseName: run.courseName,\n hints: run.hints ?? null,\n };\n copyTextToClipboard(JSON.stringify(payload, null, 2), btn);\n },\n\n /**\n * Internal UI helpers\n * @internal\n *\n * Copies an \"abridged\" view of results: just the selected cards with their\n * generator, origin, final score, and the top provenance reason. Designed\n * for pasting into bug reports without flooding with full provenance.\n */\n _copyResults(runId: string, btn?: HTMLElement): void {\n const run = runHistory.find((r) => r.runId === runId);\n if (!run) return;\n const selected = run.cards\n .filter((c) => c.selected)\n .sort((a, b) => b.finalScore - a.finalScore)\n .map((c) => ({\n cardId: c.cardId,\n generator: c.generator,\n origin: c.origin,\n score: Number(c.finalScore.toFixed(3)),\n topReason: c.provenance[0]?.reason ?? '',\n }));\n const payload = {\n runId: run.runId,\n label: run.hints?._label ?? null,\n finalCount: run.finalCount,\n newSelected: run.newSelected,\n reviewsSelected: run.reviewsSelected,\n selected,\n };\n copyTextToClipboard(JSON.stringify(payload, null, 2), btn);\n },\n\n /**\n * Show help.\n */\n help(): void {\n logger.print(`\n🔧 Pipeline Debug API\n\nCommands:\n .ui() Toggle full-screen UI debugger\n .showLastRun() Show summary of most recent pipeline run\n .showRun(id|index) Show summary of a specific run (by index or ID suffix)\n .showCard(cardId) Show provenance trail for a specific card\n .showTagElo(pattern) Show user's tag ELO data (async). E.g. 'gpc:expose:*'\n .explainReviews() Analyze why reviews were/weren't selected\n .diagnoseCardSpace() Scan full card space through filters (async)\n .showRegistry() Show navigator registry (classes + roles)\n .showStrategies() Show registry + strategy mapping from last run\n .showPrescribed(id?) Show prescribed-generated cards and blocked/support details from last run\n .listRuns() List all captured runs in table format\n .export() Export run history as JSON for bug reports\n .clear() Clear run history\n .runs Access raw run history array\n .help() Show this help message\n\nExample:\n window.skuilder.pipeline.ui()\n window.skuilder.pipeline.showLastRun()\n window.skuilder.pipeline.showRun(1)\n await window.skuilder.pipeline.diagnoseCardSpace()\n`);\n },\n};\n\n// ============================================================================\n// WINDOW MOUNT\n// ============================================================================\n\n/**\n * Mount the debug API on window.skuilder.pipeline\n */\nexport function mountPipelineDebugger(): void {\n if (typeof window === 'undefined') return;\n\n const win = window as any;\n win.skuilder = win.skuilder || {};\n win.skuilder.pipeline = pipelineDebugAPI;\n}\n\n// Auto-mount when module is loaded\nmountPipelineDebugger();"],"mappings":";;;;;;;;AAmBA,IAAI,kBAAmC;;;;;AAMvC,SAAgB,yBAAyB,UAA0B;AACjE,mBAAkB;;;;;;;;AASpB,SAAgB,oBAA+C;AAC7D,QAAO;;;;;AAiKT,MAAM,WAAW;AACjB,MAAM,aAAkC,EAAE;;;;;AAM1C,IAAI;AAEJ,SAAgB,kBAAkB,WAAqC;AACrE,qBAAoB;;;;;;;AAQtB,IAAI,eAAoC,EAAE;;AAG1C,SAAgB,oBAAyC;CACvD,MAAM,UAAU;AAChB,gBAAe,EAAE;AACjB,QAAO;;;;;;AAOT,SAAgB,kBAAkB,WAAwC;AACxE,QAAO,WAAW,QAAQ,MAAM,EAAE,cAAc,UAAU,CAAC,SAAS;;;;;;;;;;;;AAatE,MAAM,qBAAqB;;;;;;;;;AAU3B,SAAgB,kBAAwB;AACtC,YAAW,SAAS;AACpB,gBAAe,EAAE;;;;;;;;AASnB,SAAS,UAAU,MAAsC;AACvD,QAAO,KAAK,WAAW,WAAW;;;;;;;AAQpC,SAAS,WAAW,MAAwC;AAC1D,QAAO,KAAK,WAAW,MACpB,MAAM,EAAE,aAAa,mBAAmB,EAAE,UAAU,OAAO,kBAC7D,EAAE;;;;;AAML,SAAgB,WACd,QACmB;CACnB,MAAM,aAAgC;EACpC,GAAG;EACH,OAAO,OAAO,KAAK,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,GAAG,EAAE;EAClE,WAAW;EACX,2BAAW,IAAI,MAAM;EACtB;AAED,YAAW,QAAQ,WAAW;AAC9B,KAAI,WAAW,SAAS,SACtB,YAAW,KAAK;AAElB,cAAa,KAAK,WAAW;AAC7B,QAAO;;;;;;;;;AAUT,SAAS,aAAa,YAAwD;CAC5E,MAAM,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AI,CAAC,IAAK;EACV,MAAM,UAAU;GACd,OAAO,IAAI;GACX,WAAW,IAAI,UAAU,aAAa;GACtC,UAAU,IAAI;GACd,YAAY,IAAI;GAChB,OAAO,IAAI,SAAS;GACrB;AACD,sBAAoB,KAAK,UAAU,SAAS,MAAM,EAAE,EAAE,IAAI;;CAW5D,aAAa,OAAe,KAAyB;EACnD,MAAM,MAAM,WAAW,MAAM,MAAM,EAAE,UAAU,MAAM;AACrD,MAAI,CAAC,IAAK;EACV,MAAM,WAAW,IAAI,MAClB,QAAQ,MAAM,EAAE,SAAS,CACzB,MAAM,GAAG,MAAM,EAAE,aAAa,EAAE,WAAW,CAC3C,KAAK,OAAO;GACX,QAAQ,EAAE;GACV,WAAW,EAAE;GACb,QAAQ,EAAE;GACV,OAAO,OAAO,EAAE,WAAW,QAAQ,EAAE,CAAC;GACtC,WAAW,EAAE,WAAW,IAAI,UAAU;GACvC,EAAE;EACL,MAAM,UAAU;GACd,OAAO,IAAI;GACX,OAAO,IAAI,OAAO,UAAU;GAC5B,YAAY,IAAI;GAChB,aAAa,IAAI;GACjB,iBAAiB,IAAI;GACrB;GACD;AACD,sBAAoB,KAAK,UAAU,SAAS,MAAM,EAAE,EAAE,IAAI;;CAM5D,OAAa;AACX,SAAO,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;EAyBf;;CAED;;;;AASD,SAAgB,wBAA8B;AAC5C,KAAI,OAAO,WAAW,YAAa;CAEnC,MAAM,MAAM;AACZ,KAAI,WAAW,IAAI,YAAY,EAAE;AACjC,KAAI,SAAS,WAAW;;AAI1B,uBAAuB"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import "../../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
//#region src/core/navigators/SrsDebugger.ts
|
|
3
|
+
const snapshots = /* @__PURE__ */ new Map();
|
|
4
|
+
/** Called by the SRS generator once per run. Latest snapshot per course wins. */
|
|
5
|
+
function captureSrsBacklog(snapshot) {
|
|
6
|
+
snapshots.set(snapshot.courseId, snapshot);
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Called by the pipeline's regulator stage once per run: the review mass and
|
|
10
|
+
* the multiplier it set. Patches the course's latest SRS snapshot.
|
|
11
|
+
*/
|
|
12
|
+
function noteReviewPressure(courseId, pressure) {
|
|
13
|
+
const snapshot = snapshots.get(courseId);
|
|
14
|
+
if (!snapshot) return;
|
|
15
|
+
snapshots.set(courseId, {
|
|
16
|
+
...snapshot,
|
|
17
|
+
reviewMass: pressure.mass,
|
|
18
|
+
healthyBacklog: pressure.healthyMass,
|
|
19
|
+
backlogGrowthRate: pressure.rate,
|
|
20
|
+
backlogMultiplier: pressure.multiplier
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
/** Current backlog snapshot for every course seen, newest-first. */
|
|
24
|
+
function getSrsBacklogDebug() {
|
|
25
|
+
return [...snapshots.values()].sort((a, b) => b.timestamp - a.timestamp);
|
|
26
|
+
}
|
|
27
|
+
/** Drop all captured snapshots (called on session start, alongside pipeline history). */
|
|
28
|
+
function clearSrsBacklogDebug() {
|
|
29
|
+
snapshots.clear();
|
|
30
|
+
}
|
|
31
|
+
//#endregion
|
|
32
|
+
export { captureSrsBacklog, clearSrsBacklogDebug, getSrsBacklogDebug, noteReviewPressure };
|
|
33
|
+
|
|
34
|
+
//# sourceMappingURL=SrsDebugger.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SrsDebugger.mjs","names":[],"sources":["../../../src/core/navigators/SrsDebugger.ts"],"sourcesContent":["// ============================================================================\n// SRS BACKLOG DEBUGGER\n// ============================================================================\n//\n// A tiny module-level capture of per-run review backlog state, so the live\n// session overlay can show how much runway remains before reviews out-compete\n// the current (boosted) new/prescribed cards: the review-mass multiplier is\n// exponential and uncapped, so it always has headroom to climb further — the\n// question is just how large the backlog's mass needs to get before it crosses\n// whatever the competing boosts currently sit at.\n//\n// The SRS generator captures counts each run; the pipeline's regulator stage\n// then patches in the review mass and the multiplier (noteReviewPressure).\n// Keyed by course, latest wins; the overlay reads it via the controller's\n// getDebugSnapshot(). No DB load on the read path.\n//\n// ============================================================================\n\n/** Per-course snapshot of SRS backlog state, captured on each SRS generator run. */\nexport interface SrsBacklogDebug {\n courseId: string;\n /** Total reviews scheduled for this course (due + not-yet-due). */\n scheduledTotal: number;\n /** Reviews eligible (due) right now. */\n dueNow: number;\n /** Healthy review mass (card-equivalents); the multiplier is ×1.0 at or below it. */\n healthyBacklog: number;\n /**\n * Review mass: the due reviews' filtered scores against a reference, each at\n * most 1. Set by the regulator stage; null until it has run.\n */\n reviewMass: number | null;\n /** Multiplier the regulator stage applied to every due review this run (>= 1.0, unbounded). */\n backlogMultiplier: number;\n /** Exponential growth-rate base the multiplier climbs by per multiple of healthy mass in excess. */\n backlogGrowthRate: number;\n /** Highest review urgency score from the SRS generator (before filters and regulators); null if none due. */\n topReviewScore: number | null;\n /** Human-readable time until the next review comes due, or null if some are due now. */\n nextDueIn: string | null;\n /** Epoch ms of capture. */\n timestamp: number;\n}\n\nconst snapshots = new Map<string, SrsBacklogDebug>();\n\n/** Called by the SRS generator once per run. Latest snapshot per course wins. */\nexport function captureSrsBacklog(snapshot: SrsBacklogDebug): void {\n snapshots.set(snapshot.courseId, snapshot);\n}\n\n/**\n * Called by the pipeline's regulator stage once per run: the review mass and\n * the multiplier it set. Patches the course's latest SRS snapshot.\n */\nexport function noteReviewPressure(\n courseId: string,\n pressure: { mass: number; healthyMass: number; rate: number; multiplier: number }\n): void {\n const snapshot = snapshots.get(courseId);\n if (!snapshot) return;\n snapshots.set(courseId, {\n ...snapshot,\n reviewMass: pressure.mass,\n healthyBacklog: pressure.healthyMass,\n backlogGrowthRate: pressure.rate,\n backlogMultiplier: pressure.multiplier,\n });\n}\n\n/** Current backlog snapshot for every course seen, newest-first. */\nexport function getSrsBacklogDebug(): SrsBacklogDebug[] {\n return [...snapshots.values()].sort((a, b) => b.timestamp - a.timestamp);\n}\n\n/** Drop all captured snapshots (called on session start, alongside pipeline history). */\nexport function clearSrsBacklogDebug(): void {\n snapshots.clear();\n}\n"],"mappings":";;AA4CA,MAAM,4BAAY,IAAI,KAA8B;;AAGpD,SAAgB,kBAAkB,UAAiC;AACjE,WAAU,IAAI,SAAS,UAAU,SAAS;;;;;;AAO5C,SAAgB,mBACd,UACA,UACM;CACN,MAAM,WAAW,UAAU,IAAI,SAAS;AACxC,KAAI,CAAC,SAAU;AACf,WAAU,IAAI,UAAU;EACtB,GAAG;EACH,YAAY,SAAS;EACrB,gBAAgB,SAAS;EACzB,mBAAmB,SAAS;EAC5B,mBAAmB,SAAS;EAC7B,CAAC;;;AAIJ,SAAgB,qBAAwC;AACtD,QAAO,CAAC,GAAG,UAAU,QAAQ,CAAC,CAAC,MAAM,GAAG,MAAM,EAAE,YAAY,EAAE,UAAU;;;AAI1E,SAAgB,uBAA6B;AAC3C,WAAU,OAAO"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import "../../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
//#region src/core/navigators/StrategyPressureDebugger.ts
|
|
3
|
+
const snapshots = /* @__PURE__ */ new Map();
|
|
4
|
+
/** Called by a strategy once per run. Latest snapshot per (source, course) wins. */
|
|
5
|
+
function captureStrategyPressure(snapshot) {
|
|
6
|
+
snapshots.set(`${snapshot.source}:${snapshot.courseId}`, snapshot);
|
|
7
|
+
}
|
|
8
|
+
/** Current pressure snapshot for every source seen, newest-first. */
|
|
9
|
+
function getStrategyPressureDebug() {
|
|
10
|
+
return [...snapshots.values()].sort((a, b) => b.timestamp - a.timestamp);
|
|
11
|
+
}
|
|
12
|
+
/** Drop all captured snapshots (called on session start, alongside pipeline history). */
|
|
13
|
+
function clearStrategyPressureDebug() {
|
|
14
|
+
snapshots.clear();
|
|
15
|
+
}
|
|
16
|
+
//#endregion
|
|
17
|
+
export { captureStrategyPressure, clearStrategyPressureDebug, getStrategyPressureDebug };
|
|
18
|
+
|
|
19
|
+
//# sourceMappingURL=StrategyPressureDebugger.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"StrategyPressureDebugger.mjs","names":[],"sources":["../../../src/core/navigators/StrategyPressureDebugger.ts"],"sourcesContent":["// ============================================================================\n// STRATEGY PRESSURE DEBUGGER\n// ============================================================================\n//\n// A generic, semi-structured capture channel for the backpressures that\n// navigation strategies exert on the pipeline — the general-purpose sibling\n// of SrsDebugger's bespoke review-backlog capture.\n//\n// Any strategy (built-in or consumer-registered via `registerNavigator`) may\n// push a snapshot of its current pressure state once per run. The live\n// session overlay renders every captured source in a \"strategy backpressure\"\n// section without knowing producer semantics: each snapshot is a list of\n// *gauges* — named multipliers, optionally capped, with human-readable detail\n// and expandable item lists (blocked targets, per-tag debt ages, ...).\n//\n// Mirrors SrsDebugger's lifecycle: latest snapshot per (source, course) wins;\n// the controller reads via getDebugSnapshot() with no DB load; cleared on\n// session start alongside the pipeline run history.\n//\n// ============================================================================\n\n/**\n * A single named pressure reading. The common shape across strategies: a\n * multiplier that climbs under some accumulated condition (staleness, debt,\n * blockage), optionally clamped at a cap.\n */\nexport interface PressureGaugeDebug {\n /** Stable identifier within the source (e.g. 'group:intro-core:target'). */\n id: string;\n /** Short display label (e.g. 'intro-core targets'). */\n label: string;\n /** Current pressure multiplier (×1.0 = no pressure). */\n multiplier: number;\n /** Clamp ceiling, if the multiplier is capped. Omit for unbounded. */\n max?: number;\n /** One-line context for the reading (counts, mode, staleness). */\n detail?: string;\n /** Expandable rows (blocked target ids, per-tag debt ages, ...). */\n items?: Array<{ label: string; value?: string }>;\n}\n\n/** One strategy's pressure snapshot for one course, captured once per run. */\nexport interface StrategyPressureDebug {\n /** Producer identity — implementingClass name (e.g. 'prescribed'). */\n source: string;\n courseId: string;\n gauges: PressureGaugeDebug[];\n /**\n * Highest score this strategy emitted into the candidate pool this run;\n * null if it emitted nothing. Compare against the supplyQ head score to\n * read how the pressure is competing for slots (same crossover read as the\n * SRS panel's `top review`).\n */\n topScore?: number | null;\n /** Label of any one-shot hints emitted alongside the cards this run. */\n hintsLabel?: string;\n /** Epoch ms of capture. */\n timestamp: number;\n}\n\nconst snapshots = new Map<string, StrategyPressureDebug>();\n\n/** Called by a strategy once per run. Latest snapshot per (source, course) wins. */\nexport function captureStrategyPressure(snapshot: StrategyPressureDebug): void {\n snapshots.set(`${snapshot.source}:${snapshot.courseId}`, snapshot);\n}\n\n/** Current pressure snapshot for every source seen, newest-first. */\nexport function getStrategyPressureDebug(): StrategyPressureDebug[] {\n return [...snapshots.values()].sort((a, b) => b.timestamp - a.timestamp);\n}\n\n/** Drop all captured snapshots (called on session start, alongside pipeline history). */\nexport function clearStrategyPressureDebug(): void {\n snapshots.clear();\n}\n"],"mappings":";;AA4DA,MAAM,4BAAY,IAAI,KAAoC;;AAG1D,SAAgB,wBAAwB,UAAuC;AAC7E,WAAU,IAAI,GAAG,SAAS,OAAO,GAAG,SAAS,YAAY,SAAS;;;AAIpE,SAAgB,2BAAoD;AAClE,QAAO,CAAC,GAAG,UAAU,QAAQ,CAAC,CAAC,MAAM,GAAG,MAAM,EAAE,YAAY,EAAE,UAAU;;;AAI1E,SAAgB,6BAAmC;AACjD,WAAU,OAAO"}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import "../../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
import { Navigators } from "./index.mjs";
|
|
3
|
+
import { DEFAULT_STRATEGY_HASH } from "../versionStamps.mjs";
|
|
4
|
+
import { DocType } from "../types/types-legacy.mjs";
|
|
5
|
+
import { Pipeline } from "./Pipeline.mjs";
|
|
6
|
+
import CompositeGenerator from "./generators/CompositeGenerator.mjs";
|
|
7
|
+
import ELONavigator from "./generators/elo.mjs";
|
|
8
|
+
import SRSNavigator from "./generators/srs.mjs";
|
|
9
|
+
import EloDistanceFilter, { DEFAULT_ELO_DISTANCE_CONFIG } from "./filters/eloDistance.mjs";
|
|
10
|
+
//#region src/core/navigators/defaults.ts
|
|
11
|
+
/**
|
|
12
|
+
* Default navigation pipeline configuration.
|
|
13
|
+
*
|
|
14
|
+
* This module provides factory functions for creating the canonical default
|
|
15
|
+
* navigation pipeline used by both CouchDB and static course implementations.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* Create default ELO navigation strategy data.
|
|
19
|
+
* Used when no custom strategies are configured.
|
|
20
|
+
*
|
|
21
|
+
* @param courseId - The course ID to associate with this strategy
|
|
22
|
+
* @returns Strategy data for default ELO navigation
|
|
23
|
+
*/
|
|
24
|
+
function createDefaultEloStrategy(courseId) {
|
|
25
|
+
return {
|
|
26
|
+
_id: "NAVIGATION_STRATEGY-ELO-default",
|
|
27
|
+
docType: DocType.NAVIGATION_STRATEGY,
|
|
28
|
+
name: "ELO (default)",
|
|
29
|
+
description: "Default ELO-based navigation strategy for new cards",
|
|
30
|
+
implementingClass: Navigators.ELO,
|
|
31
|
+
course: courseId,
|
|
32
|
+
serializedData: ""
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Create default SRS navigation strategy data.
|
|
37
|
+
* Used when no custom strategies are configured.
|
|
38
|
+
*
|
|
39
|
+
* @param courseId - The course ID to associate with this strategy
|
|
40
|
+
* @returns Strategy data for default SRS navigation
|
|
41
|
+
*/
|
|
42
|
+
function createDefaultSrsStrategy(courseId) {
|
|
43
|
+
return {
|
|
44
|
+
_id: "NAVIGATION_STRATEGY-SRS-default",
|
|
45
|
+
docType: DocType.NAVIGATION_STRATEGY,
|
|
46
|
+
name: "SRS (default)",
|
|
47
|
+
description: "Default SRS-based navigation strategy for reviews",
|
|
48
|
+
implementingClass: Navigators.SRS,
|
|
49
|
+
course: courseId,
|
|
50
|
+
serializedData: ""
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Create default ELO distance filter strategy data. The assembler adds it to
|
|
55
|
+
* any pipeline whose strategy docs declare no `eloDistance` filter.
|
|
56
|
+
*
|
|
57
|
+
* @param courseId - The course ID to associate with this strategy
|
|
58
|
+
* @returns Strategy data for the default ELO distance filter (default curve)
|
|
59
|
+
*/
|
|
60
|
+
function createDefaultEloDistanceStrategy(courseId) {
|
|
61
|
+
return {
|
|
62
|
+
_id: "NAVIGATION_STRATEGY-eloDistance-default",
|
|
63
|
+
docType: DocType.NAVIGATION_STRATEGY,
|
|
64
|
+
name: "ELO Distance (default)",
|
|
65
|
+
description: "Scales every candidate, new or review, by its distance from the learner's ELO",
|
|
66
|
+
implementingClass: Navigators.ELO_DISTANCE,
|
|
67
|
+
course: courseId,
|
|
68
|
+
serializedData: JSON.stringify(DEFAULT_ELO_DISTANCE_CONFIG)
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Creates the default navigation pipeline for courses with no configured strategies.
|
|
73
|
+
*
|
|
74
|
+
* Default: Pipeline(Composite(ELO, SRS), [ELO distance])
|
|
75
|
+
* - ELO generator: retrieves new cards near the learner's ELO
|
|
76
|
+
* - SRS generator: scores reviews by overdueness and interval recency
|
|
77
|
+
* - ELO distance filter: scales every card by its distance from the learner's ELO
|
|
78
|
+
*
|
|
79
|
+
* This is the canonical default configuration used when:
|
|
80
|
+
* - No navigation strategy documents exist in the course
|
|
81
|
+
* - PipelineAssembler fails to build from strategy documents
|
|
82
|
+
*
|
|
83
|
+
* @param user - User database interface for accessing user state
|
|
84
|
+
* @param course - Course database interface for accessing course data
|
|
85
|
+
* @returns Configured Pipeline ready for use
|
|
86
|
+
*/
|
|
87
|
+
function createDefaultPipeline(user, course) {
|
|
88
|
+
const courseId = course.getCourseID();
|
|
89
|
+
const pipeline = new Pipeline(new CompositeGenerator([new ELONavigator(user, course, createDefaultEloStrategy(courseId)), new SRSNavigator(user, course, createDefaultSrsStrategy(courseId))]), [new EloDistanceFilter(user, course, createDefaultEloDistanceStrategy(courseId))], user, course);
|
|
90
|
+
pipeline.strategyHash = DEFAULT_STRATEGY_HASH;
|
|
91
|
+
return pipeline;
|
|
92
|
+
}
|
|
93
|
+
//#endregion
|
|
94
|
+
export { createDefaultEloDistanceStrategy, createDefaultEloStrategy, createDefaultPipeline, createDefaultSrsStrategy };
|
|
95
|
+
|
|
96
|
+
//# sourceMappingURL=defaults.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"defaults.mjs","names":[],"sources":["../../../src/core/navigators/defaults.ts"],"sourcesContent":["import { Navigators } from './index';\nimport { Pipeline } from './Pipeline';\nimport CompositeGenerator from './generators/CompositeGenerator';\nimport ELONavigator from './generators/elo';\nimport SRSNavigator from './generators/srs';\nimport EloDistanceFilter, { DEFAULT_ELO_DISTANCE_CONFIG } from './filters/eloDistance';\nimport type { ContentNavigationStrategyData } from '../types/contentNavigationStrategy';\nimport { DocType } from '../types/types-legacy';\nimport { DEFAULT_STRATEGY_HASH } from '../versionStamps';\nimport type { CourseDBInterface, UserDBInterface } from '../interfaces';\n\n/**\n * Default navigation pipeline configuration.\n *\n * This module provides factory functions for creating the canonical default\n * navigation pipeline used by both CouchDB and static course implementations.\n */\n\n/**\n * Create default ELO navigation strategy data.\n * Used when no custom strategies are configured.\n *\n * @param courseId - The course ID to associate with this strategy\n * @returns Strategy data for default ELO navigation\n */\nexport function createDefaultEloStrategy(courseId: string): ContentNavigationStrategyData {\n return {\n _id: 'NAVIGATION_STRATEGY-ELO-default',\n docType: DocType.NAVIGATION_STRATEGY,\n name: 'ELO (default)',\n description: 'Default ELO-based navigation strategy for new cards',\n implementingClass: Navigators.ELO,\n course: courseId,\n serializedData: '',\n };\n}\n\n/**\n * Create default SRS navigation strategy data.\n * Used when no custom strategies are configured.\n *\n * @param courseId - The course ID to associate with this strategy\n * @returns Strategy data for default SRS navigation\n */\nexport function createDefaultSrsStrategy(courseId: string): ContentNavigationStrategyData {\n return {\n _id: 'NAVIGATION_STRATEGY-SRS-default',\n docType: DocType.NAVIGATION_STRATEGY,\n name: 'SRS (default)',\n description: 'Default SRS-based navigation strategy for reviews',\n implementingClass: Navigators.SRS,\n course: courseId,\n serializedData: '',\n };\n}\n\n/**\n * Create default ELO distance filter strategy data. The assembler adds it to\n * any pipeline whose strategy docs declare no `eloDistance` filter.\n *\n * @param courseId - The course ID to associate with this strategy\n * @returns Strategy data for the default ELO distance filter (default curve)\n */\nexport function createDefaultEloDistanceStrategy(courseId: string): ContentNavigationStrategyData {\n return {\n _id: 'NAVIGATION_STRATEGY-eloDistance-default',\n docType: DocType.NAVIGATION_STRATEGY,\n name: 'ELO Distance (default)',\n description: 'Scales every candidate, new or review, by its distance from the learner\\'s ELO',\n implementingClass: Navigators.ELO_DISTANCE,\n course: courseId,\n // Explicit, though the filter would default to it anyway: views show what runs.\n serializedData: JSON.stringify(DEFAULT_ELO_DISTANCE_CONFIG),\n };\n}\n\n/**\n * Creates the default navigation pipeline for courses with no configured strategies.\n *\n * Default: Pipeline(Composite(ELO, SRS), [ELO distance])\n * - ELO generator: retrieves new cards near the learner's ELO\n * - SRS generator: scores reviews by overdueness and interval recency\n * - ELO distance filter: scales every card by its distance from the learner's ELO\n *\n * This is the canonical default configuration used when:\n * - No navigation strategy documents exist in the course\n * - PipelineAssembler fails to build from strategy documents\n *\n * @param user - User database interface for accessing user state\n * @param course - Course database interface for accessing course data\n * @returns Configured Pipeline ready for use\n */\nexport function createDefaultPipeline(\n user: UserDBInterface,\n course: CourseDBInterface\n): Pipeline {\n const courseId = course.getCourseID();\n const eloNavigator = new ELONavigator(user, course, createDefaultEloStrategy(courseId));\n const srsNavigator = new SRSNavigator(user, course, createDefaultSrsStrategy(courseId));\n\n const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);\n const eloDistanceFilter = new EloDistanceFilter(\n user,\n course,\n createDefaultEloDistanceStrategy(courseId)\n );\n\n const pipeline = new Pipeline(compositeGenerator, [eloDistanceFilter], user, course);\n pipeline.strategyHash = DEFAULT_STRATEGY_HASH;\n return pipeline;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,yBAAyB,UAAiD;AACxF,QAAO;EACL,KAAK;EACL,SAAS,QAAQ;EACjB,MAAM;EACN,aAAa;EACb,mBAAmB,WAAW;EAC9B,QAAQ;EACR,gBAAgB;EACjB;;;;;;;;;AAUH,SAAgB,yBAAyB,UAAiD;AACxF,QAAO;EACL,KAAK;EACL,SAAS,QAAQ;EACjB,MAAM;EACN,aAAa;EACb,mBAAmB,WAAW;EAC9B,QAAQ;EACR,gBAAgB;EACjB;;;;;;;;;AAUH,SAAgB,iCAAiC,UAAiD;AAChG,QAAO;EACL,KAAK;EACL,SAAS,QAAQ;EACjB,MAAM;EACN,aAAa;EACb,mBAAmB,WAAW;EAC9B,QAAQ;EAER,gBAAgB,KAAK,UAAU,4BAA4B;EAC5D;;;;;;;;;;;;;;;;;;AAmBH,SAAgB,sBACd,MACA,QACU;CACV,MAAM,WAAW,OAAO,aAAa;CAWrC,MAAM,WAAW,IAAI,SAPM,IAAI,mBAAmB,CAH7B,IAAI,aAAa,MAAM,QAAQ,yBAAyB,SAAS,CAAC,EAClE,IAAI,aAAa,MAAM,QAAQ,yBAAyB,SAAS,CAAC,CAET,CAAC,EAO7B,CANxB,IAAI,kBAC5B,MACA,QACA,iCAAiC,SAAS,CAC3C,CAEoE,EAAE,MAAM,OAAO;AACpF,UAAS,eAAe;AACxB,QAAO"}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import "../../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
//#region src/core/navigators/diversityRerank.ts
|
|
3
|
+
/** Default repetition strength. See DiversityRerankOptions.strength. */
|
|
4
|
+
const DIVERSITY_STRENGTH = .6;
|
|
5
|
+
/** Default penalty floor. See DiversityRerankOptions.floor. */
|
|
6
|
+
const DIVERSITY_FLOOR = .3;
|
|
7
|
+
const STRATEGY = "diversityRerank";
|
|
8
|
+
const STRATEGY_ID = "DIVERSITY_RERANK";
|
|
9
|
+
const STRATEGY_NAME = "Diversity Re-rank";
|
|
10
|
+
/**
|
|
11
|
+
* Re-rank a scored candidate pool for answer/concept variety.
|
|
12
|
+
*
|
|
13
|
+
* Pure: returns a new array (diversified order, adjusted scores, appended
|
|
14
|
+
* provenance) and does not mutate the input cards. Cards entering are assumed
|
|
15
|
+
* to have score > 0 (the Pipeline strips zero-score cards before this stage).
|
|
16
|
+
* Non-finite scores (mandatory `requireCards`, score = +Infinity) are emitted
|
|
17
|
+
* untouched and still count toward repetition for later cards.
|
|
18
|
+
*
|
|
19
|
+
* @param cards - Post-filter, post-hint candidates.
|
|
20
|
+
* @param opts - Optional strength/floor overrides (defaults are sane and
|
|
21
|
+
* course-general; promote to strategy config if you ever want
|
|
22
|
+
* this learnable under the orchestration layer).
|
|
23
|
+
* @returns Cards in diversified order with penalised scores.
|
|
24
|
+
*/
|
|
25
|
+
function diversityRerank(cards, opts = {}) {
|
|
26
|
+
const strength = opts.strength ?? .6;
|
|
27
|
+
const floor = opts.floor ?? .3;
|
|
28
|
+
const n = cards.length;
|
|
29
|
+
if (n <= 1) return cards;
|
|
30
|
+
const df = /* @__PURE__ */ new Map();
|
|
31
|
+
for (const card of cards) for (const tag of card.tags ?? []) df.set(tag, (df.get(tag) ?? 0) + 1);
|
|
32
|
+
const idf = /* @__PURE__ */ new Map();
|
|
33
|
+
for (const [tag, freq] of df) idf.set(tag, Math.log(n / freq));
|
|
34
|
+
const remaining = [...cards];
|
|
35
|
+
const emittedCount = /* @__PURE__ */ new Map();
|
|
36
|
+
const out = [];
|
|
37
|
+
const repetitionLoad = (card) => {
|
|
38
|
+
let load = 0;
|
|
39
|
+
for (const tag of card.tags ?? []) {
|
|
40
|
+
const seen = emittedCount.get(tag);
|
|
41
|
+
if (seen) load += (idf.get(tag) ?? 0) * seen;
|
|
42
|
+
}
|
|
43
|
+
return load;
|
|
44
|
+
};
|
|
45
|
+
while (remaining.length > 0) {
|
|
46
|
+
let bestIdx = 0;
|
|
47
|
+
let bestValue = -Infinity;
|
|
48
|
+
let bestPenalty = 1;
|
|
49
|
+
let bestLoad = 0;
|
|
50
|
+
for (let i = 0; i < remaining.length; i++) {
|
|
51
|
+
const card = remaining[i];
|
|
52
|
+
const load = repetitionLoad(card);
|
|
53
|
+
const penalty = load > 0 ? Math.max(floor, 1 / (1 + strength * load)) : 1;
|
|
54
|
+
const value = card.score * penalty;
|
|
55
|
+
if (value > bestValue) {
|
|
56
|
+
bestValue = value;
|
|
57
|
+
bestIdx = i;
|
|
58
|
+
bestPenalty = penalty;
|
|
59
|
+
bestLoad = load;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const [picked] = remaining.splice(bestIdx, 1);
|
|
63
|
+
if (Number.isFinite(picked.score) && bestPenalty < 1) {
|
|
64
|
+
const newScore = picked.score * bestPenalty;
|
|
65
|
+
out.push({
|
|
66
|
+
...picked,
|
|
67
|
+
score: newScore,
|
|
68
|
+
provenance: [...picked.provenance, {
|
|
69
|
+
strategy: STRATEGY,
|
|
70
|
+
strategyId: STRATEGY_ID,
|
|
71
|
+
strategyName: STRATEGY_NAME,
|
|
72
|
+
action: "penalized",
|
|
73
|
+
score: newScore,
|
|
74
|
+
reason: `repeated tags (load ${bestLoad.toFixed(2)}) → ×${bestPenalty.toFixed(2)}`
|
|
75
|
+
}]
|
|
76
|
+
});
|
|
77
|
+
} else out.push(picked);
|
|
78
|
+
for (const tag of picked.tags ?? []) emittedCount.set(tag, (emittedCount.get(tag) ?? 0) + 1);
|
|
79
|
+
}
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
//#endregion
|
|
83
|
+
export { DIVERSITY_FLOOR, DIVERSITY_STRENGTH, diversityRerank };
|
|
84
|
+
|
|
85
|
+
//# sourceMappingURL=diversityRerank.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"diversityRerank.mjs","names":[],"sources":["../../../src/core/navigators/diversityRerank.ts"],"sourcesContent":["import type { WeightedCard } from './index';\n\n// ============================================================================\n// DIVERSITY RE-RANK (pipeline stage 3)\n// ============================================================================\n//\n// Generators produce candidates → filters weigh them → THIS stage diversifies\n// the ranking. It demotes cards whose distinctive tags already appeared among\n// higher-ranked candidates, so a single answer/concept can't monopolise the\n// head of the queue (the \"press `i` repeatedly\" rut).\n//\n// ## Tag-agnostic by construction\n//\n// The framework has no first-class notion of an \"answer\" — tags are the only\n// structured similarity signal it carries. This stage privileges NO tag: it\n// hardcodes no namespace and works on whatever tags a course happens to apply.\n// \"Tag-agnostic\" means \"no tag is special,\" not \"ignores tags\": a course that\n// never tags its sameness axis is invisible to the re-rank (acceptable — tags\n// are the framework's content contract).\n//\n// ## Why rarity weighting (IDF)\n//\n// Naive \"penalize by count of shared tags\" is noisy: cards share lots of\n// scaffolding tags (`ui:*`, incidental `gpc:expose:*`) that say nothing about\n// sameness. We weight each shared tag by its rarity in the candidate pool\n// (inverse document frequency). Ubiquitous tags contribute ~0; the distinctive\n// tag a cluster shares — exactly what makes a rut a rut — dominates. This is\n// self-tuning and needs no per-course configuration: a math course clustering\n// on \"answer = 7\" or a music course on \"interval = M3\" gets the same benefit\n// for free, provided that axis is tagged.\n//\n// ## Algorithm — greedy maximal-marginal-relevance\n//\n// 1. df[tag] = #cards carrying tag; idf[tag] = ln(N / df[tag])\n// (tag in every card → idf 0; rarer → larger).\n// 2. Walk candidates in score order, emitting one at a time. Track how many\n// already-emitted cards carry each tag (`emittedCount`).\n// 3. A candidate's repetition load = Σ_{t ∈ card.tags} idf[t]·emittedCount[t].\n// penalty = max(floor, 1 / (1 + strength·load)).\n// 4. Each step emit argmax(score·penalty); freeze that penalised score.\n//\n// Because each step picks the current maximum and selecting a card only lowers\n// (never raises) the remaining cards' values, the frozen scores are\n// monotonically non-increasing in pick order — so a subsequent sort-by-score\n// (the Pipeline's, and the SourceMixer's) reproduces this exact order. This is\n// why the stage expresses itself as SCORE penalties rather than a bare array\n// reorder: a positional shuffle would be silently undone by the mixer's\n// score-descending re-sort.\n//\n// ============================================================================\n\nexport interface DiversityRerankOptions {\n /**\n * How hard repetition is penalised. Larger → steeper demotion of repeated\n * distinctive tags. Penalty = 1 / (1 + strength·load).\n */\n strength?: number;\n /**\n * Minimum penalty multiplier. A card is never demoted below `floor × score`,\n * however much it repeats. Keeps a strong-but-repeated card from being driven\n * under downstream \"well-indicated\" thresholds (which would mislabel it as\n * filler and could trigger spurious quality-replans). Tunes \"perturb ordering\"\n * vs \"annihilate candidates.\"\n */\n floor?: number;\n}\n\n/** Default repetition strength. See DiversityRerankOptions.strength. */\nexport const DIVERSITY_STRENGTH = 0.6;\n\n/** Default penalty floor. See DiversityRerankOptions.floor. */\nexport const DIVERSITY_FLOOR = 0.3;\n\nconst STRATEGY = 'diversityRerank';\nconst STRATEGY_ID = 'DIVERSITY_RERANK';\nconst STRATEGY_NAME = 'Diversity Re-rank';\n\n/**\n * Re-rank a scored candidate pool for answer/concept variety.\n *\n * Pure: returns a new array (diversified order, adjusted scores, appended\n * provenance) and does not mutate the input cards. Cards entering are assumed\n * to have score > 0 (the Pipeline strips zero-score cards before this stage).\n * Non-finite scores (mandatory `requireCards`, score = +Infinity) are emitted\n * untouched and still count toward repetition for later cards.\n *\n * @param cards - Post-filter, post-hint candidates.\n * @param opts - Optional strength/floor overrides (defaults are sane and\n * course-general; promote to strategy config if you ever want\n * this learnable under the orchestration layer).\n * @returns Cards in diversified order with penalised scores.\n */\nexport function diversityRerank(\n cards: WeightedCard[],\n opts: DiversityRerankOptions = {}\n): WeightedCard[] {\n const strength = opts.strength ?? DIVERSITY_STRENGTH;\n const floor = opts.floor ?? DIVERSITY_FLOOR;\n\n const n = cards.length;\n if (n <= 1) return cards;\n\n // 1. Document frequency → IDF. A tag in every card carries no discriminative\n // signal (idf 0); a rare tag dominates the repetition load.\n const df = new Map<string, number>();\n for (const card of cards) {\n for (const tag of card.tags ?? []) {\n df.set(tag, (df.get(tag) ?? 0) + 1);\n }\n }\n const idf = new Map<string, number>();\n for (const [tag, freq] of df) {\n idf.set(tag, Math.log(n / freq));\n }\n\n // 2-4. Greedy MMR. `remaining` holds candidates not yet emitted; `emitted`\n // counts selected cards per tag.\n const remaining = [...cards];\n const emittedCount = new Map<string, number>();\n const out: WeightedCard[] = [];\n\n const repetitionLoad = (card: WeightedCard): number => {\n let load = 0;\n for (const tag of card.tags ?? []) {\n const seen = emittedCount.get(tag);\n if (seen) load += (idf.get(tag) ?? 0) * seen;\n }\n return load;\n };\n\n while (remaining.length > 0) {\n let bestIdx = 0;\n let bestValue = -Infinity;\n let bestPenalty = 1;\n let bestLoad = 0;\n\n for (let i = 0; i < remaining.length; i++) {\n const card = remaining[i];\n const load = repetitionLoad(card);\n const penalty = load > 0 ? Math.max(floor, 1 / (1 + strength * load)) : 1;\n // Non-finite (mandatory) scores stay non-finite: Infinity × penalty =\n // Infinity, so they argmax first and ride through unchanged.\n const value = card.score * penalty;\n // Strict \">\" keeps the scan stable: ties resolve to the earlier (already\n // higher-ranked-by-incoming-score) card.\n if (value > bestValue) {\n bestValue = value;\n bestIdx = i;\n bestPenalty = penalty;\n bestLoad = load;\n }\n }\n\n const [picked] = remaining.splice(bestIdx, 1);\n\n if (Number.isFinite(picked.score) && bestPenalty < 1) {\n const newScore = picked.score * bestPenalty;\n out.push({\n ...picked,\n score: newScore,\n provenance: [\n ...picked.provenance,\n {\n strategy: STRATEGY,\n strategyId: STRATEGY_ID,\n strategyName: STRATEGY_NAME,\n action: 'penalized',\n score: newScore,\n reason: `repeated tags (load ${bestLoad.toFixed(2)}) → ×${bestPenalty.toFixed(2)}`,\n },\n ],\n });\n } else {\n // No penalty (fresh card, or mandatory/non-finite): emit untouched but\n // still let it count toward later cards' repetition load below.\n out.push(picked);\n }\n\n for (const tag of picked.tags ?? []) {\n emittedCount.set(tag, (emittedCount.get(tag) ?? 0) + 1);\n }\n }\n\n return out;\n}\n"],"mappings":";;;AAoEA,MAAa,qBAAqB;;AAGlC,MAAa,kBAAkB;AAE/B,MAAM,WAAW;AACjB,MAAM,cAAc;AACpB,MAAM,gBAAgB;;;;;;;;;;;;;;;;AAiBtB,SAAgB,gBACd,OACA,OAA+B,EAAE,EACjB;CAChB,MAAM,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AAI,KAAK;IACP,GAAG;IACH,OAAO;IACP,YAAY,CACV,GAAG,OAAO,YACV;KACE,UAAU;KACV,YAAY;KACZ,cAAc;KACd,QAAQ;KACR,OAAO;KACP,QAAQ,uBAAuB,SAAS,QAAQ,EAAE,CAAC,OAAO,YAAY,QAAQ,EAAE;KACjF,CACF;IACF,CAAC;QAIF,KAAI,KAAK,OAAO;AAGlB,OAAK,MAAM,OAAO,OAAO,QAAQ,EAAE,CACjC,cAAa,IAAI,MAAM,aAAa,IAAI,IAAI,IAAI,KAAK,EAAE;;AAI3D,QAAO"}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import "../../../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
import { DEFAULT_LEARNABLE_WEIGHT } from "../../types/contentNavigationStrategy.mjs";
|
|
3
|
+
//#region src/core/navigators/filters/WeightedFilter.ts
|
|
4
|
+
/**
|
|
5
|
+
* Wraps a CardFilter to apply evolutionary weighting to its effects.
|
|
6
|
+
*
|
|
7
|
+
* If a filter applies a multiplier M (score * M), and the strategy has
|
|
8
|
+
* an effective weight W, the final multiplier becomes M^W.
|
|
9
|
+
*
|
|
10
|
+
* - W=1.0: Original behavior
|
|
11
|
+
* - W>1.0: Amplifies the filter's opinion (stronger boost/penalty)
|
|
12
|
+
* - W<1.0: Dampens the filter's opinion (weaker boost/penalty)
|
|
13
|
+
* - W=0.0: Nullifies the filter (identity)
|
|
14
|
+
*
|
|
15
|
+
* This wrapper handles the math of scaling the filter's impact and updating
|
|
16
|
+
* the provenance trail with the effective weight used.
|
|
17
|
+
*/
|
|
18
|
+
var WeightedFilter = class {
|
|
19
|
+
name;
|
|
20
|
+
kind;
|
|
21
|
+
liveOnly;
|
|
22
|
+
inner;
|
|
23
|
+
learnable;
|
|
24
|
+
staticWeight;
|
|
25
|
+
strategyId;
|
|
26
|
+
constructor(inner, learnable = DEFAULT_LEARNABLE_WEIGHT, staticWeight = false, strategyId) {
|
|
27
|
+
this.inner = inner;
|
|
28
|
+
this.name = inner.name;
|
|
29
|
+
this.kind = inner.kind;
|
|
30
|
+
this.liveOnly = inner.liveOnly;
|
|
31
|
+
this.learnable = learnable;
|
|
32
|
+
this.staticWeight = staticWeight;
|
|
33
|
+
this.strategyId = strategyId;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Apply the inner filter, then scale its effect by the configured weight.
|
|
37
|
+
*/
|
|
38
|
+
async transform(cards, context) {
|
|
39
|
+
let effectiveWeight = this.learnable.weight;
|
|
40
|
+
let deviation;
|
|
41
|
+
if (!this.staticWeight && context.orchestration) {
|
|
42
|
+
const strategyId = this.strategyId || this.inner.strategyId || this.name;
|
|
43
|
+
effectiveWeight = context.orchestration.getEffectiveWeight(strategyId, this.learnable);
|
|
44
|
+
deviation = context.orchestration.getDeviation(strategyId);
|
|
45
|
+
}
|
|
46
|
+
if (Math.abs(effectiveWeight - 1) < .001) return this.inner.transform(cards, context);
|
|
47
|
+
const originalScores = /* @__PURE__ */ new Map();
|
|
48
|
+
for (const card of cards) originalScores.set(card.cardId, card.score);
|
|
49
|
+
return (await this.inner.transform(cards, context)).map((card) => {
|
|
50
|
+
const originalScore = originalScores.get(card.cardId);
|
|
51
|
+
if (originalScore === void 0 || originalScore === 0 || card.score === 0) return card;
|
|
52
|
+
const rawEffect = card.score / originalScore;
|
|
53
|
+
if (Math.abs(rawEffect - 1) < 1e-4) return card;
|
|
54
|
+
const newScore = originalScore * Math.pow(rawEffect, effectiveWeight);
|
|
55
|
+
const lastProvIndex = card.provenance.length - 1;
|
|
56
|
+
const lastProv = card.provenance[lastProvIndex];
|
|
57
|
+
if (lastProv) {
|
|
58
|
+
const updatedProvenance = [...card.provenance];
|
|
59
|
+
updatedProvenance[lastProvIndex] = {
|
|
60
|
+
...lastProv,
|
|
61
|
+
score: newScore,
|
|
62
|
+
effectiveWeight,
|
|
63
|
+
deviation
|
|
64
|
+
};
|
|
65
|
+
return {
|
|
66
|
+
...card,
|
|
67
|
+
score: newScore,
|
|
68
|
+
provenance: updatedProvenance
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
...card,
|
|
73
|
+
score: newScore
|
|
74
|
+
};
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
//#endregion
|
|
79
|
+
export { WeightedFilter };
|
|
80
|
+
|
|
81
|
+
//# sourceMappingURL=WeightedFilter.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"WeightedFilter.mjs","names":[],"sources":["../../../../src/core/navigators/filters/WeightedFilter.ts"],"sourcesContent":["import { CardFilter, FilterContext, FilterKind } from './types';\nimport { WeightedCard } from '../index';\nimport { LearnableWeight, DEFAULT_LEARNABLE_WEIGHT } from '../../types/contentNavigationStrategy';\n\n/**\n * Wraps a CardFilter to apply evolutionary weighting to its effects.\n *\n * If a filter applies a multiplier M (score * M), and the strategy has\n * an effective weight W, the final multiplier becomes M^W.\n *\n * - W=1.0: Original behavior\n * - W>1.0: Amplifies the filter's opinion (stronger boost/penalty)\n * - W<1.0: Dampens the filter's opinion (weaker boost/penalty)\n * - W=0.0: Nullifies the filter (identity)\n *\n * This wrapper handles the math of scaling the filter's impact and updating\n * the provenance trail with the effective weight used.\n */\nexport class WeightedFilter implements CardFilter {\n public name: string;\n public kind?: FilterKind;\n public liveOnly?: boolean;\n private inner: CardFilter;\n private learnable: LearnableWeight;\n private staticWeight: boolean;\n private strategyId?: string;\n\n constructor(\n inner: CardFilter,\n learnable: LearnableWeight = DEFAULT_LEARNABLE_WEIGHT,\n staticWeight: boolean = false,\n strategyId?: string\n ) {\n this.inner = inner;\n this.name = inner.name;\n this.kind = inner.kind;\n this.liveOnly = inner.liveOnly;\n this.learnable = learnable;\n this.staticWeight = staticWeight;\n this.strategyId = strategyId;\n }\n\n /**\n * Apply the inner filter, then scale its effect by the configured weight.\n */\n async transform(cards: WeightedCard[], context: FilterContext): Promise<WeightedCard[]> {\n // ========================================================================\n // 1. DETERMINE EFFECTIVE WEIGHT\n // ========================================================================\n \n // Determine effective weight using orchestration context if available\n let effectiveWeight = this.learnable.weight;\n let deviation: number | undefined;\n\n if (!this.staticWeight && context.orchestration) {\n // ContentNavigator instances have a strategyId property (protected/private)\n // We assume inner filter is a ContentNavigator or has a strategyId property.\n // Fallback to name if not present.\n const strategyId = this.strategyId || (this.inner as any).strategyId || this.name;\n effectiveWeight = context.orchestration.getEffectiveWeight(strategyId, this.learnable);\n deviation = context.orchestration.getDeviation(strategyId);\n }\n\n // Optimization: If weight is 1.0, the scaling is an identity operation.\n // Just run the inner filter directly.\n if (Math.abs(effectiveWeight - 1.0) < 0.001) {\n return this.inner.transform(cards, context);\n }\n\n // ========================================================================\n // 2. CAPTURE STATE BEFORE FILTER\n // ========================================================================\n \n // We need original scores to calculate what the filter did (M = new/old)\n const originalScores = new Map<string, number>();\n for (const card of cards) {\n originalScores.set(card.cardId, card.score);\n }\n\n // ========================================================================\n // 3. RUN INNER FILTER\n // ========================================================================\n \n const transformedCards = await this.inner.transform(cards, context);\n\n // ========================================================================\n // 4. APPLY WEIGHT SCALING\n // ========================================================================\n \n return transformedCards.map((card) => {\n const originalScore = originalScores.get(card.cardId);\n\n // Edge cases where we can't or shouldn't scale:\n // - Original score missing (shouldn't happen)\n // - Original score 0 (was already excluded)\n // - New score 0 (filter excluded it / vetoed) - we treat vetoes as absolute\n if (originalScore === undefined || originalScore === 0 || card.score === 0) {\n return card;\n }\n\n // Calculate raw effect multiplier: M = new / old\n const rawEffect = card.score / originalScore;\n\n // If filter didn't change this card, nothing to scale\n if (Math.abs(rawEffect - 1.0) < 0.0001) {\n return card;\n }\n\n // Apply weight: scaled = M ^ W\n // Example: 0.5 penalty ^ 2.0 weight = 0.25 (stronger penalty)\n // Example: 0.5 penalty ^ 0.5 weight = 0.707 (weaker penalty)\n const weightedEffect = Math.pow(rawEffect, effectiveWeight);\n const newScore = originalScore * weightedEffect;\n\n // Update provenance\n // The inner filter just added the last entry. We need to update it\n // to reflect the weighted score and record the effective weight.\n const lastProvIndex = card.provenance.length - 1;\n const lastProv = card.provenance[lastProvIndex];\n\n if (lastProv) {\n const updatedProvenance = [...card.provenance];\n updatedProvenance[lastProvIndex] = {\n ...lastProv,\n score: newScore,\n effectiveWeight: effectiveWeight,\n deviation: deviation,\n // We can optionally append to the reason, but the structured field is key\n };\n\n return {\n ...card,\n score: newScore,\n provenance: updatedProvenance,\n };\n }\n\n // Fallback if no provenance found (rare)\n return {\n ...card,\n score: newScore,\n };\n });\n }\n}"],"mappings":";;;;;;;;;;;;;;;;;AAkBA,IAAa,iBAAb,MAAkD;CAChD;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YACE,OACA,YAA6B,0BAC7B,eAAwB,OACxB,YACA;AACA,OAAK,QAAQ;AACb,OAAK,OAAO,MAAM;AAClB,OAAK,OAAO,MAAM;AAClB,OAAK,WAAW,MAAM;AACtB,OAAK,YAAY;AACjB,OAAK,eAAe;AACpB,OAAK,aAAa;;;;;CAMpB,MAAM,UAAU,OAAuB,SAAiD;EAMtF,IAAI,kBAAkB,KAAK,UAAU;EACrC,IAAI;AAEJ,MAAI,CAAC,KAAK,gBAAgB,QAAQ,eAAe;GAI/C,MAAM,aAAa,KAAK,cAAe,KAAK,MAAc,cAAc,KAAK;AAC7E,qBAAkB,QAAQ,cAAc,mBAAmB,YAAY,KAAK,UAAU;AACtF,eAAY,QAAQ,cAAc,aAAa,WAAW;;AAK5D,MAAI,KAAK,IAAI,kBAAkB,EAAI,GAAG,KACpC,QAAO,KAAK,MAAM,UAAU,OAAO,QAAQ;EAQ7C,MAAM,iCAAiB,IAAI,KAAqB;AAChD,OAAK,MAAM,QAAQ,MACjB,gBAAe,IAAI,KAAK,QAAQ,KAAK,MAAM;AAa7C,UANyB,MAAM,KAAK,MAAM,UAAU,OAAO,QAAQ,EAM3C,KAAK,SAAS;GACpC,MAAM,gBAAgB,eAAe,IAAI,KAAK,OAAO;AAMrD,OAAI,kBAAkB,KAAA,KAAa,kBA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