@vue-skuilder/db 0.3.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/{contentSource-2zVmcjKA.d.ts → contentSource-CSI0pJ2D.d.ts} +10 -0
  2. package/dist/core/index.cjs +62 -14
  3. package/dist/core/index.cjs.map +1 -1
  4. package/dist/core/index.d.ts +3 -3
  5. package/dist/core/interfaces/contentSource.mjs.map +1 -1
  6. package/dist/core/navigators/Pipeline.mjs +7 -1
  7. package/dist/core/navigators/Pipeline.mjs.map +1 -1
  8. package/dist/core/navigators/filters/eloDistance.mjs +17 -2
  9. package/dist/core/navigators/filters/eloDistance.mjs.map +1 -1
  10. package/dist/core/navigators/generators/prescribed.mjs +20 -10
  11. package/dist/core/navigators/generators/prescribed.mjs.map +1 -1
  12. package/dist/core/navigators/index.mjs +2 -0
  13. package/dist/core/navigators/index.mjs.map +1 -1
  14. package/dist/core/versionStamps.mjs +1 -1
  15. package/dist/{dataLayerProvider-rGyLQ93v.d.ts → dataLayerProvider-D5n1gGc_.d.ts} +1 -1
  16. package/dist/diagnostics/index.d.ts +2 -2
  17. package/dist/impl/couch/courseDB.mjs +5 -0
  18. package/dist/impl/couch/courseDB.mjs.map +1 -1
  19. package/dist/impl/couch/index.cjs +37 -2
  20. package/dist/impl/couch/index.cjs.map +1 -1
  21. package/dist/impl/couch/index.d.ts +4 -2
  22. package/dist/impl/static/courseDB.mjs +5 -0
  23. package/dist/impl/static/courseDB.mjs.map +1 -1
  24. package/dist/impl/static/index.cjs +37 -2
  25. package/dist/impl/static/index.cjs.map +1 -1
  26. package/dist/impl/static/index.d.ts +4 -2
  27. package/dist/index.cjs +73 -15
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.d.ts +3 -3
  30. package/dist/study/SessionController.mjs +1 -0
  31. package/dist/study/SessionController.mjs.map +1 -1
  32. package/package.json +3 -3
  33. package/src/core/interfaces/contentSource.ts +7 -0
  34. package/src/core/navigators/Pipeline.ts +7 -0
  35. package/src/core/navigators/filters/eloDistance.ts +31 -2
  36. package/src/core/navigators/generators/prescribed.ts +56 -11
  37. package/src/core/navigators/generators/types.ts +3 -0
  38. package/src/core/navigators/index.ts +5 -0
  39. package/src/impl/couch/courseDB.ts +13 -0
  40. package/src/impl/static/courseDB.ts +13 -0
  41. package/src/study/SessionController.ts +3 -0
  42. package/tests/core/navigators/eloDistanceFilter.test.ts +15 -0
@@ -1,7 +1,7 @@
1
1
  export { A as AdminDBInterface, d as AssignedCard, a as AssignedContent, c as AssignedCourse, b as AssignedTag, C as ClassroomDBInterface, S as StudentClassroomDBInterface, T as TeacherClassroomDBInterface } from '../classroomDB-DLTtLZct.js';
2
- import { av as LearnableWeight, T as UserOutcomeRecord, aw as OrchestrationContext, W as WeightedCard, C as CourseDBInterface } from '../contentSource-2zVmcjKA.js';
3
- export { P as ActivityRecord, ae as CardFilter, ag as CardFilterFactory, ah as CardGenerator, aj as CardGeneratorFactory, K as ClassroomRegistration, J as ClassroomRegistrationDesignation, L as ClassroomRegistrationDoc, c as ContentNavigationStrategyData, d as ContentNavigator, v as ContentSourceID, b as CourseInfo, Q as CourseRegistration, g as CourseRegistrationDoc, a as CoursesDBInterface, af as FilterContext, at as FilterImpact, F as FilterKind, ai as GeneratorContext, G as GeneratorResult, as as GeneratorSummary, _ as HYDRATION_MARKER_ID, $ as HydrationMarker, a0 as NavigatorConstructor, N as NavigatorRole, ab as NavigatorRoles, aa as Navigators, au as PipelineForecaster, aq as PipelineRunReport, R as ReplanHints, ar as RunReportCard, f as ScheduledCard, m as SessionEloEvent, h as SessionStateSnapshot, x as SessionStateSnapshotProvider, M as SessionTrackingData, a8 as StrategyContribution, o as StudyContentSource, e as StudySessionDoc, p as StudySessionFailedItem, q as StudySessionFailedNewItem, r as StudySessionFailedReviewItem, S as StudySessionItem, s as StudySessionNewItem, t as StudySessionReviewItem, k as StudySessionRunCard, n as StudySessionRunCardTrail, i as StudySessionRunSummary, O as UserConfig, H as UserCourseSetting, E as UserCourseSettings, B as UserDBAuthenticator, U as UserDBInterface, z as UserDBReader, A as UserDBWriter, Y as UserHydrationState, Z as UserHydrationStatus, I as UsrCrsDataInterface, ax as computeDeviation, az as computeEffectiveWeight, ay as computeSpread, aA as createOrchestrationContext, ap as drainCapturedRuns, am as getActivePipeline, a9 as getCardOrigin, a5 as getRegisteredFilterKind, a2 as getRegisteredNavigator, a6 as getRegisteredNavigatorNames, a4 as getRegisteredNavigatorRole, ao as getRunsForSession, w as getStudySource, a3 as hasRegisteredNavigator, a7 as initializeNavigatorRegistry, ad as isFilter, ac as isGenerator, u as isReview, V as makeStudySessionId, al as mountPipelineDebugger, X as newSessionId, ak as pipelineDebugAPI, a1 as registerNavigator, an as setDebugSessionId } from '../contentSource-2zVmcjKA.js';
4
- export { D as DataLayerProvider } from '../dataLayerProvider-rGyLQ93v.js';
2
+ import { av as LearnableWeight, T as UserOutcomeRecord, aw as OrchestrationContext, W as WeightedCard, C as CourseDBInterface } from '../contentSource-CSI0pJ2D.js';
3
+ export { P as ActivityRecord, ae as CardFilter, ag as CardFilterFactory, ah as CardGenerator, aj as CardGeneratorFactory, K as ClassroomRegistration, J as ClassroomRegistrationDesignation, L as ClassroomRegistrationDoc, c as ContentNavigationStrategyData, d as ContentNavigator, v as ContentSourceID, b as CourseInfo, Q as CourseRegistration, g as CourseRegistrationDoc, a as CoursesDBInterface, af as FilterContext, at as FilterImpact, F as FilterKind, ai as GeneratorContext, G as GeneratorResult, as as GeneratorSummary, _ as HYDRATION_MARKER_ID, $ as HydrationMarker, a0 as NavigatorConstructor, N as NavigatorRole, ab as NavigatorRoles, aa as Navigators, au as PipelineForecaster, aq as PipelineRunReport, R as ReplanHints, ar as RunReportCard, f as ScheduledCard, m as SessionEloEvent, h as SessionStateSnapshot, x as SessionStateSnapshotProvider, M as SessionTrackingData, a8 as StrategyContribution, o as StudyContentSource, e as StudySessionDoc, p as StudySessionFailedItem, q as StudySessionFailedNewItem, r as StudySessionFailedReviewItem, S as StudySessionItem, s as StudySessionNewItem, t as StudySessionReviewItem, k as StudySessionRunCard, n as StudySessionRunCardTrail, i as StudySessionRunSummary, O as UserConfig, H as UserCourseSetting, E as UserCourseSettings, B as UserDBAuthenticator, U as UserDBInterface, z as UserDBReader, A as UserDBWriter, Y as UserHydrationState, Z as UserHydrationStatus, I as UsrCrsDataInterface, ax as computeDeviation, az as computeEffectiveWeight, ay as computeSpread, aA as createOrchestrationContext, ap as drainCapturedRuns, am as getActivePipeline, a9 as getCardOrigin, a5 as getRegisteredFilterKind, a2 as getRegisteredNavigator, a6 as getRegisteredNavigatorNames, a4 as getRegisteredNavigatorRole, ao as getRunsForSession, w as getStudySource, a3 as hasRegisteredNavigator, a7 as initializeNavigatorRegistry, ad as isFilter, ac as isGenerator, u as isReview, V as makeStudySessionId, al as mountPipelineDebugger, X as newSessionId, ak as pipelineDebugAPI, a1 as registerNavigator, an as setDebugSessionId } from '../contentSource-CSI0pJ2D.js';
4
+ export { D as DataLayerProvider } from '../dataLayerProvider-D5n1gGc_.js';
5
5
  import { D as DocType, d as QuestionRecord, f as DocTypePrefixes, e as CardHistory, c as CardRecord } from '../types-legacy-DdVjg81H.js';
6
6
  export { C as CardData, g as CourseListData, h as DataShapeData, b as DisplayableData, F as Field, G as GuestUsername, Q as QualifiedCardID, i as QuestionData, S as SkuilderCourseData, a as Tag, T as TagStub, l as log } from '../types-legacy-DdVjg81H.js';
7
7
  import { DataShape, ParsedCard } from '@vue-skuilder/common';
@@ -1 +1 @@
1
- {"version":3,"file":"contentSource.mjs","names":[],"sources":["../../../src/core/interfaces/contentSource.ts"],"sourcesContent":["import { getDataLayer } from '@db/factory';\nimport { UserDBInterface } from '..';\nimport { StudentClassroomDB } from '../../impl/couch/classroomDB';\nimport type { GeneratorResult, ReplanHints } from '../navigators/generators/types';\nimport { TagFilter, hasActiveFilter } from '@vue-skuilder/common';\nimport { TagFilteredContentSource } from '../../study/TagFilteredContentSource';\nimport { OrchestrationContext } from '../orchestration';\n\nexport type StudySessionFailedItem = StudySessionFailedNewItem | StudySessionFailedReviewItem;\n\nexport interface StudySessionFailedNewItem extends StudySessionItem {\n status: 'failed-new';\n}\nexport interface StudySessionFailedReviewItem extends StudySessionReviewItem {\n status: 'failed-review';\n}\n\nexport interface StudySessionNewItem extends StudySessionItem {\n status: 'new';\n}\n\nexport interface StudySessionReviewItem extends StudySessionItem {\n reviewID: string;\n status: 'review' | 'failed-review';\n}\nexport function isReview(item: StudySessionItem): item is StudySessionReviewItem {\n const ret = item.status === 'review' || item.status === 'failed-review' || 'reviewID' in item;\n\n // console.log(`itemIsReview: ${ret}\n // \\t${JSON.stringify(item)}`);\n\n return ret;\n}\n\nexport interface StudySessionItem {\n status: 'new' | 'review' | 'failed-new' | 'failed-review';\n contentSourceType: 'course' | 'classroom';\n contentSourceID: string;\n // qualifiedID: `${string}-${string}` | `${string}-${string}-${number}`;\n cardID: string;\n courseID: string;\n elo?: number;\n /**\n * Pipeline suitability score at queue-build time, carried for observability\n * (the debug overlay renders the now-load-bearing supply ranking). `+INF`\n * marks a mandatory required card. Not used for any draw decision — the\n * supplyQ is already ordered, so the controller draws front-to-back.\n */\n score?: number;\n // reviewID?: string;\n}\n\nexport interface ContentSourceID {\n type: 'course' | 'classroom';\n id: string;\n /**\n * Optional tag filter for scoped study sessions.\n * When present, creates a TagFilteredContentSource instead of a regular course source.\n */\n tagFilter?: TagFilter;\n}\n\n// #region docs_StudyContentSource\n/**\n * Interface for sources that provide study content to SessionController.\n *\n * Content sources return scored candidates via getWeightedCards(), which\n * SessionController uses to populate study queues.\n *\n * See: packages/db/docs/navigators-architecture.md\n */\nexport interface StudyContentSource {\n /**\n * Get cards with suitability scores for presentation.\n *\n * Returns unified scored candidates that can be sorted and selected by SessionController.\n * The card origin ('new' | 'review' | 'failed') is determined by provenance metadata.\n *\n * @param limit - Maximum number of cards to return\n * @returns Cards sorted by score descending\n */\n getWeightedCards(limit: number): Promise<GeneratorResult>;\n\n /**\n * Get the orchestration context for this source.\n * Used for recording learning outcomes.\n */\n getOrchestrationContext?(): Promise<OrchestrationContext>;\n\n /**\n * Set ephemeral hints for the next pipeline run.\n * No-op for sources that don't support hints.\n */\n setEphemeralHints?(hints: ReplanHints): void;\n\n /**\n * A card was just presented. `status` is the session item's (`'new'`,\n * `'review'`, `'failed-new'`, ...). Pipelines use a new card's first\n * presentation to restart their intake valve's clock.\n */\n notePresented?(card: { cardId: string; courseId: string; status: string }): void;\n}\n// #endregion docs_StudyContentSource\n\nexport async function getStudySource(\n source: ContentSourceID,\n user: UserDBInterface\n): Promise<StudyContentSource> {\n if (source.type === 'classroom') {\n return await StudentClassroomDB.factory(source.id, user);\n } else {\n // Check if this is a tag-filtered course source\n if (hasActiveFilter(source.tagFilter)) {\n return new TagFilteredContentSource(source.id, source.tagFilter!, user);\n }\n\n // Regular course source\n return getDataLayer().getCourseDB(source.id) as unknown as StudyContentSource;\n }\n}\n"],"mappings":";;;;;;AAyBA,SAAgB,SAAS,MAAwD;AAM/E,QALY,KAAK,WAAW,YAAY,KAAK,WAAW,mBAAmB,cAAc;;AA8E3F,eAAsB,eACpB,QACA,MAC6B;AAC7B,KAAI,OAAO,SAAS,YAClB,QAAO,MAAM,mBAAmB,QAAQ,OAAO,IAAI,KAAK;MACnD;AAEL,MAAI,gBAAgB,OAAO,UAAU,CACnC,QAAO,IAAI,yBAAyB,OAAO,IAAI,OAAO,WAAY,KAAK;AAIzE,SAAO,cAAc,CAAC,YAAY,OAAO,GAAG"}
1
+ {"version":3,"file":"contentSource.mjs","names":[],"sources":["../../../src/core/interfaces/contentSource.ts"],"sourcesContent":["import { getDataLayer } from '@db/factory';\nimport { UserDBInterface } from '..';\nimport { StudentClassroomDB } from '../../impl/couch/classroomDB';\nimport type { GeneratorResult, ReplanHints } from '../navigators/generators/types';\nimport { TagFilter, hasActiveFilter } from '@vue-skuilder/common';\nimport { TagFilteredContentSource } from '../../study/TagFilteredContentSource';\nimport { OrchestrationContext } from '../orchestration';\n\nexport type StudySessionFailedItem = StudySessionFailedNewItem | StudySessionFailedReviewItem;\n\nexport interface StudySessionFailedNewItem extends StudySessionItem {\n status: 'failed-new';\n}\nexport interface StudySessionFailedReviewItem extends StudySessionReviewItem {\n status: 'failed-review';\n}\n\nexport interface StudySessionNewItem extends StudySessionItem {\n status: 'new';\n}\n\nexport interface StudySessionReviewItem extends StudySessionItem {\n reviewID: string;\n status: 'review' | 'failed-review';\n}\nexport function isReview(item: StudySessionItem): item is StudySessionReviewItem {\n const ret = item.status === 'review' || item.status === 'failed-review' || 'reviewID' in item;\n\n // console.log(`itemIsReview: ${ret}\n // \\t${JSON.stringify(item)}`);\n\n return ret;\n}\n\nexport interface StudySessionItem {\n status: 'new' | 'review' | 'failed-new' | 'failed-review';\n contentSourceType: 'course' | 'classroom';\n contentSourceID: string;\n // qualifiedID: `${string}-${string}` | `${string}-${string}-${number}`;\n cardID: string;\n courseID: string;\n elo?: number;\n /**\n * Pipeline suitability score at queue-build time, carried for observability\n * (the debug overlay renders the now-load-bearing supply ranking). `+INF`\n * marks a mandatory required card. Not used for any draw decision — the\n * supplyQ is already ordered, so the controller draws front-to-back.\n */\n score?: number;\n // reviewID?: string;\n}\n\nexport interface ContentSourceID {\n type: 'course' | 'classroom';\n id: string;\n /**\n * Optional tag filter for scoped study sessions.\n * When present, creates a TagFilteredContentSource instead of a regular course source.\n */\n tagFilter?: TagFilter;\n}\n\n// #region docs_StudyContentSource\n/**\n * Interface for sources that provide study content to SessionController.\n *\n * Content sources return scored candidates via getWeightedCards(), which\n * SessionController uses to populate study queues.\n *\n * See: packages/db/docs/navigators-architecture.md\n */\nexport interface StudyContentSource {\n /**\n * Get cards with suitability scores for presentation.\n *\n * Returns unified scored candidates that can be sorted and selected by SessionController.\n * The card origin ('new' | 'review' | 'failed') is determined by provenance metadata.\n *\n * @param limit - Maximum number of cards to return\n * @returns Cards sorted by score descending\n */\n getWeightedCards(limit: number): Promise<GeneratorResult>;\n\n /**\n * Get the orchestration context for this source.\n * Used for recording learning outcomes.\n */\n getOrchestrationContext?(): Promise<OrchestrationContext>;\n\n /**\n * Set ephemeral hints for the next pipeline run.\n * No-op for sources that don't support hints.\n */\n setEphemeralHints?(hints: ReplanHints): void;\n\n /**\n * The study session the following runs belong to. Persists until replaced\n * (unlike hints). Generators read it from their context, e.g. to count\n * sessions rather than runs.\n */\n setSessionId?(sessionId: string): void;\n\n /**\n * A card was just presented. `status` is the session item's (`'new'`,\n * `'review'`, `'failed-new'`, ...). Pipelines use a new card's first\n * presentation to restart their intake valve's clock.\n */\n notePresented?(card: { cardId: string; courseId: string; status: string }): void;\n}\n// #endregion docs_StudyContentSource\n\nexport async function getStudySource(\n source: ContentSourceID,\n user: UserDBInterface\n): Promise<StudyContentSource> {\n if (source.type === 'classroom') {\n return await StudentClassroomDB.factory(source.id, user);\n } else {\n // Check if this is a tag-filtered course source\n if (hasActiveFilter(source.tagFilter)) {\n return new TagFilteredContentSource(source.id, source.tagFilter!, user);\n }\n\n // Regular course source\n return getDataLayer().getCourseDB(source.id) as unknown as StudyContentSource;\n }\n}\n"],"mappings":";;;;;;AAyBA,SAAgB,SAAS,MAAwD;AAM/E,QALY,KAAK,WAAW,YAAY,KAAK,WAAW,mBAAmB,cAAc;;AAqF3F,eAAsB,eACpB,QACA,MAC6B;AAC7B,KAAI,OAAO,SAAS,YAClB,QAAO,MAAM,mBAAmB,QAAQ,OAAO,IAAI,KAAK;MACnD;AAEL,MAAI,gBAAgB,OAAO,UAAU,CACnC,QAAO,IAAI,yBAAyB,OAAO,IAAI,OAAO,WAAY,KAAK;AAIzE,SAAO,cAAc,CAAC,YAAY,OAAO,GAAG"}
@@ -128,6 +128,7 @@ var Pipeline = class extends ContentNavigator {
128
128
  * getWeightedCards() call, then cleared.
129
129
  */
130
130
  _ephemeralHints = null;
131
+ _sessionId;
131
132
  /**
132
133
  * The intake valve's clock (see regulators.ts), loaded from strategy state on
133
134
  * first use and kept in memory. Writes are chained so a presentation and a
@@ -163,6 +164,10 @@ var Pipeline = class extends ContentNavigator {
163
164
  *
164
165
  * Overrides ContentNavigator.setEphemeralHints() no-op.
165
166
  */
167
+ /** See StudyContentSource.setSessionId. Carried into every run's context. */
168
+ setSessionId(sessionId) {
169
+ this._sessionId = sessionId;
170
+ }
166
171
  setEphemeralHints(hints) {
167
172
  this._ephemeralHints = hints;
168
173
  logger.info(`[Pipeline] Ephemeral hints set: ${JSON.stringify(hints)}`);
@@ -522,7 +527,8 @@ var Pipeline = class extends ContentNavigator {
522
527
  course: this.course,
523
528
  userElo,
524
529
  ...userCourseElo ? { userCourseElo } : {},
525
- orchestration
530
+ orchestration,
531
+ ...this._sessionId ? { sessionId: this._sessionId } : {}
526
532
  };
527
533
  }
528
534
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"Pipeline.mjs","names":[],"sources":["../../../src/core/navigators/Pipeline.ts"],"sourcesContent":["import { toCourseElo, type CourseElo } from '@vue-skuilder/common';\nimport type { CourseDBInterface } from '../interfaces/courseDB';\nimport type { UserDBInterface } from '../interfaces/userDB';\nimport { ContentNavigator } from './index';\nimport type { WeightedCard } from './index';\nimport type { CardFilter, FilterContext } from './filters/types';\nimport type { CardGenerator, GeneratorContext } from './generators/types';\nimport type { GeneratorResult } from './generators/types';\nimport { logger } from '../../util/logger';\nimport { perfMeasure } from '../../util/perfMarks';\nimport { createOrchestrationContext, OrchestrationContext } from '../orchestration';\nimport { captureRun, buildRunReport, registerPipelineForDebug, type GeneratorSummary, type FilterImpact } from './PipelineDebugger';\nimport { diversityRerank } from './diversityRerank';\nimport {\n applyReading,\n DEFAULT_REGULATOR_CONFIG,\n INTAKE_CLOCK_KEY,\n intakeReading,\n resetIntakeClock,\n reviewMassReading,\n stepIntakeClock,\n type IntakeClockState,\n type RegulatorReading,\n} from './regulators';\nimport { noteReviewPressure } from './SrsDebugger';\n\n// ============================================================================\n// REPLAN HINTS\n// ============================================================================\n//\n// Ephemeral, one-shot scoring hints passed at replan time.\n// Applied after the filter chain, consumed after one pipeline run.\n//\n// Tag patterns support glob-style matching:\n// 'gpc:exercise:t-T' — exact match\n// 'gpc:intro:*' — all intro tags\n// 'gpc:exercise:t-*' — all t-variant exercises\n//\n\n// ReplanHints is defined in generators/types — re-export for consumers that import from Pipeline\nimport type { ReplanHints } from './generators/types';\nexport type { ReplanHints };\n\n/**\n * Convert a glob pattern (with `*` wildcards) to a RegExp.\n * Only `*` is supported as a wildcard (matches any characters).\n */\nfunction globToRegex(pattern: string): RegExp {\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const withWildcards = escaped.replace(/\\*/g, '.*');\n return new RegExp(`^${withWildcards}$`);\n}\n\n/** Test whether a string matches a glob pattern. */\nfunction globMatch(value: string, pattern: string): boolean {\n if (!pattern.includes('*')) return value === pattern;\n return globToRegex(pattern).test(value);\n}\n\n/** Test whether any of a card's tags match a glob pattern. */\nfunction cardMatchesTagPattern(card: WeightedCard, pattern: string): boolean {\n return (card.tags ?? []).some((tag) => globMatch(tag, pattern));\n}\n\nexport function mergeHints(allHints: Array<ReplanHints | null | undefined>): ReplanHints | undefined {\n const defined = allHints.filter((h): h is ReplanHints => h !== null && h !== undefined);\n if (defined.length === 0) return undefined;\n\n const merged: ReplanHints = {};\n\n const boostTags: Record<string, number> = {};\n for (const hints of defined) {\n for (const [pattern, factor] of Object.entries(hints.boostTags ?? {})) {\n boostTags[pattern] = (boostTags[pattern] ?? 1) * factor;\n }\n }\n if (Object.keys(boostTags).length > 0) {\n merged.boostTags = boostTags;\n }\n\n const boostCards: Record<string, number> = {};\n for (const hints of defined) {\n for (const [pattern, factor] of Object.entries(hints.boostCards ?? {})) {\n boostCards[pattern] = (boostCards[pattern] ?? 1) * factor;\n }\n }\n if (Object.keys(boostCards).length > 0) {\n merged.boostCards = boostCards;\n }\n\n const concatUnique = (\n field: 'requireTags' | 'requireCards' | 'excludeTags' | 'excludeCards'\n ): void => {\n const values = defined.flatMap((h) => h[field] ?? []);\n if (values.length > 0) {\n merged[field] = [...new Set(values)];\n }\n };\n\n concatUnique('requireTags');\n concatUnique('requireCards');\n concatUnique('excludeTags');\n concatUnique('excludeCards');\n\n const labels = defined.map((h) => h._label).filter(Boolean);\n if (labels.length > 0) {\n merged._label = labels.join('; ');\n }\n\n return Object.keys(merged).length > 0 ? merged : undefined;\n}\n\n// ============================================================================\n// PIPELINE LOGGING HELPERS\n// ============================================================================\n//\n// Focused logging functions that can be toggled by commenting single lines.\n// Use these to inspect pipeline behavior in development/production.\n//\n\n/**\n * Log pipeline configuration on construction.\n * Shows generator and filter chain structure.\n */\nfunction logPipelineConfig(generator: CardGenerator, filters: CardFilter[]): void {\n const filterList =\n filters.length > 0 ? '\\n - ' + filters.map((f) => f.name).join('\\n - ') : ' none';\n\n logger.info(\n `[Pipeline] Configuration:\\n` + ` Generator: ${generator.name}\\n` + ` Filters:${filterList}`\n );\n}\n\n/**\n * Log tag hydration results.\n * Shows effectiveness of batch query (how many cards/tags were hydrated).\n */\nfunction logTagHydration(cards: WeightedCard[], tagsByCard: Map<string, string[]>): void {\n const totalTags = Array.from(tagsByCard.values()).reduce((sum, tags) => sum + tags.length, 0);\n const cardsWithTags = Array.from(tagsByCard.values()).filter((tags) => tags.length > 0).length;\n\n logger.debug(\n `[Pipeline] Tag hydration: ${cards.length} cards, ` +\n `${cardsWithTags} have tags (${totalTags} total tags) - single batch query`\n );\n}\n\n/**\n * Log pipeline execution summary.\n * Shows complete flow from generator through filters to final results.\n */\nfunction logExecutionSummary(\n generatorName: string,\n generatedCount: number,\n filterCount: number,\n finalCount: number,\n topScores: number[],\n filterImpacts: Array<{ name: string; boosted: number; penalized: number; passed: number }>\n): void {\n const scoreDisplay =\n topScores.length > 0 ? topScores.map((s) => s.toFixed(2)).join(', ') : 'none';\n\n let filterSummary = '';\n if (filterImpacts.length > 0) {\n const impacts = filterImpacts.map((f) => {\n const parts: string[] = [];\n if (f.boosted > 0) parts.push(`+${f.boosted}`);\n if (f.penalized > 0) parts.push(`-${f.penalized}`);\n if (f.passed > 0) parts.push(`=${f.passed}`);\n return `${f.name}: ${parts.join('/')}`;\n });\n filterSummary = `\\n Filter impact: ${impacts.join(', ')}`;\n }\n\n logger.info(\n `[Pipeline] Execution: ${generatorName} produced ${generatedCount} → ` +\n `${filterCount} filters → ${finalCount} results (top scores: ${scoreDisplay})` +\n filterSummary +\n `\\n 💡 Inspect: window.skuilder.pipeline`\n );\n}\n\n/**\n * Log all result cards with score, cardId, and key provenance.\n * Toggle: set VERBOSE_RESULTS = true to enable.\n */\nconst VERBOSE_RESULTS = false;\n\nfunction logResultCards(cards: WeightedCard[]): void {\n if (!VERBOSE_RESULTS || cards.length === 0) return;\n\n logger.info(`[Pipeline] Results (${cards.length} cards):`);\n for (let i = 0; i < cards.length; i++) {\n const c = cards[i];\n const tags = c.tags?.slice(0, 3).join(', ') || '';\n const filters = c.provenance\n .filter((p) => p.strategy === 'hierarchyDefinition' || p.strategy === 'priorityDefinition' || p.strategy === 'interferenceFilter' || p.strategy === 'letterGating' || p.strategy === 'ephemeralHint' || p.strategy === 'diversityRerank')\n .map((p) => {\n const arrow = p.action === 'boosted' ? '↑' : p.action === 'penalized' ? '↓' : '=';\n return `${p.strategyName}${arrow}${p.score.toFixed(2)}`;\n })\n .join(' | ');\n logger.info(\n `[Pipeline] ${String(i + 1).padStart(2)}. ${c.score.toFixed(4)} ${c.cardId} [${tags}]${filters ? ` {${filters}}` : ''}`\n );\n }\n}\n\n/**\n * Log provenance trails for cards.\n * Shows the complete scoring history for each card through the pipeline.\n * Useful for debugging why cards scored the way they did.\n */\nfunction logCardProvenance(cards: WeightedCard[], maxCards: number = 3): void {\n const cardsToLog = cards.slice(0, maxCards);\n\n logger.debug(`[Pipeline] Provenance for top ${cardsToLog.length} cards:`);\n\n for (const card of cardsToLog) {\n logger.debug(`[Pipeline] ${card.cardId} (final score: ${card.score.toFixed(3)}):`);\n\n for (const entry of card.provenance) {\n const scoreChange = entry.score.toFixed(3);\n const action = entry.action.padEnd(9); // Align columns\n logger.debug(\n `[Pipeline] ${action} ${scoreChange} - ${entry.strategyName}: ${entry.reason}`\n );\n }\n }\n}\n\n// ============================================================================\n// PIPELINE\n// ============================================================================\n//\n// Executes a navigation pipeline: generator → filters → sorted results.\n//\n// Architecture:\n// cards = generator.getWeightedCards(limit, context)\n// cards = filter1.transform(cards, context)\n// cards = filter2.transform(cards, context)\n// cards = filter3.transform(cards, context)\n// return sorted(cards).slice(0, limit)\n//\n// Benefits:\n// - Clear separation: generators produce, filters transform\n// - No nested instantiation complexity\n// - Filters don't need to know about each other\n// - Shared context built once, passed to all stages\n//\n// ============================================================================\n\n/**\n * A navigation pipeline that runs a generator and applies filters sequentially.\n *\n * Implements StudyContentSource for backward compatibility with SessionController.\n *\n * ## Usage\n *\n * ```typescript\n * const pipeline = new Pipeline(\n * compositeGenerator, // or single generator\n * [eloDistanceFilter, interferenceFilter],\n * user,\n * course\n * );\n *\n * const cards = await pipeline.getWeightedCards(20);\n * ```\n */\n\n/**\n * Narrow capability surface for out-of-band, commit-free reads against a live\n * pipeline (see {@link getActivePipeline}). Kept minimal on purpose — consumers\n * get the forecast capability, not the whole `Pipeline` class.\n */\nexport interface PipelineForecaster {\n forecast(opts?: {\n hints?: ReplanHints;\n unseenOnly?: boolean;\n threshold?: number;\n limit?: number;\n }): Promise<WeightedCard[]>;\n}\n\nexport class Pipeline extends ContentNavigator implements PipelineForecaster {\n private generator: CardGenerator;\n private filters: CardFilter[];\n\n /**\n * Cached orchestration context. Course config and salt don't change within\n * a page load, so we build the orchestration context once and reuse it on\n * subsequent getWeightedCards() calls (e.g. mid-session replans).\n *\n * This eliminates a remote getCourseConfig() round trip per pipeline run.\n */\n private _cachedOrchestration: OrchestrationContext | null = null;\n\n /**\n * Hash of the strategy docs this pipeline was assembled from (see\n * versionStamps.ts), set by whoever builds it. Stamped on every run.\n */\n strategyHash?: string;\n\n /**\n * Persistent tag cache. Maps cardId → tag names.\n *\n * Tags are static within a session (they're set at card generation time),\n * so we cache them across pipeline runs. On replans, many of the same cards\n * reappear — cache hits avoid redundant remote getAppliedTagsBatch() queries.\n */\n private _tagCache: Map<string, string[]> = new Map();\n\n /**\n * One-shot replan hints. Applied after the filter chain on the next\n * getWeightedCards() call, then cleared.\n */\n private _ephemeralHints: ReplanHints | null = null;\n\n /**\n * The intake valve's clock (see regulators.ts), loaded from strategy state on\n * first use and kept in memory. Writes are chained so a presentation and a\n * run can't race each other's revision.\n */\n private _intakeClock: IntakeClockState | null = null;\n private _intakeClockWrite: Promise<void> = Promise.resolve();\n\n /**\n * Create a new pipeline.\n *\n * @param generator - The generator (or CompositeGenerator) that produces candidates\n * @param filters - Filters to apply sequentially (order doesn't matter for multipliers)\n * @param user - User database interface\n * @param course - Course database interface\n */\n constructor(\n generator: CardGenerator,\n filters: CardFilter[],\n user: UserDBInterface,\n course: CourseDBInterface\n ) {\n super();\n this.generator = generator;\n this.filters = filters;\n this.user = user;\n this.course = course;\n\n course\n .getCourseConfig()\n .then((cfg) => {\n logger.debug(`[pipeline] Crated pipeline for ${cfg.name}`);\n })\n .catch((e) => {\n logger.error(`[pipeline] Failed to lookup courseCfg: ${e}`);\n });\n // Toggle pipeline configuration logging:\n logPipelineConfig(generator, filters);\n\n // Register for debug API access\n registerPipelineForDebug(this);\n }\n\n /**\n * Set one-shot hints for the next pipeline run.\n * Consumed after one getWeightedCards() call, then cleared.\n *\n * Overrides ContentNavigator.setEphemeralHints() no-op.\n */\n override setEphemeralHints(hints: ReplanHints): void {\n this._ephemeralHints = hints;\n logger.info(`[Pipeline] Ephemeral hints set: ${JSON.stringify(hints)}`);\n }\n\n /**\n * Get weighted cards by running generator and applying filters.\n *\n * 1. Build shared context (user ELO, etc.)\n * 2. Get candidates from generator (passing context)\n * 3. Batch hydrate tags for all candidates\n * 4. Apply each filter sequentially\n * 5. Remove zero-score cards\n * 6. Sort by score descending\n * 7. Return top N\n *\n * @param limit - Maximum number of cards to return\n * @returns Cards sorted by score descending\n */\n async getWeightedCards(limit: number): Promise<GeneratorResult> {\n const t0 = performance.now();\n\n // Build shared context once\n const context = await this.buildContext();\n const tContext = performance.now();\n\n // Over-fetch from generator to give filters a wide candidate pool.\n // With local course DB the cost is negligible (~20ms for 500 cards).\n // Filters (hierarchy, letter gating, etc.) can be aggressive — a wide\n // pool ensures enough well-indicated candidates survive.\n const fetchLimit = 500;\n\n logger.debug(\n `[Pipeline] Fetching ${fetchLimit} candidates from generator '${this.generator.name}'`\n );\n\n // Get candidates from generator, passing context\n const generatorResult = await this.generator.getWeightedCards(fetchLimit, context);\n let cards = generatorResult.cards;\n const tGenerate = performance.now();\n const generatedCount = cards.length;\n\n // Merge generator-emitted hints with any externally supplied one-shot hints\n const mergedHints = mergeHints([this._ephemeralHints, generatorResult.hints]);\n this._ephemeralHints = mergedHints ?? null;\n \n // Capture generator breakdown for debugging (if CompositeGenerator)\n let generatorSummaries: GeneratorSummary[] | undefined;\n if ((this.generator as any).generators) {\n // This is a CompositeGenerator - extract per-generator info from provenance\n const genMap = new Map<string, { cards: WeightedCard[] }>();\n for (const card of cards) {\n const firstProv = card.provenance[0];\n if (firstProv) {\n const genName = firstProv.strategyName;\n if (!genMap.has(genName)) {\n genMap.set(genName, { cards: [] });\n }\n genMap.get(genName)!.cards.push(card);\n }\n }\n generatorSummaries = Array.from(genMap.entries()).map(([name, data]) => {\n // Reviews carry `reviewID`; everything else a generator emits is unseen.\n // (Reason text can't tell: the ELO generator's never says \"new card\".)\n const reviewCount = data.cards.filter((c) => c.reviewID).length;\n return {\n name,\n cardCount: data.cards.length,\n newCount: data.cards.length - reviewCount,\n reviewCount,\n topScore: Math.max(...data.cards.map((c) => c.score), 0),\n };\n });\n }\n\n logger.debug(`[Pipeline] Generator returned ${generatedCount} candidates`);\n\n // Batch hydrate tags before filters run\n cards = await this.hydrateTags(cards);\n const tHydrate = performance.now();\n \n // Keep a copy of all cards for debug capture (before filtering removes any)\n const allCardsBeforeFiltering = [...cards];\n\n // Pre-fetch any literal requireCards IDs that the generator didn't produce.\n // requireCards is a hard guarantee — required cards bypass the filter chain\n // and are injected directly into the final result by applyHints. We need\n // them present in allCardsBeforeFiltering for that injection to find them.\n // (Glob patterns are left to the existing pool-search behaviour.)\n const pendingHints = this._ephemeralHints;\n if (pendingHints?.requireCards?.length) {\n const poolIds = new Set(allCardsBeforeFiltering.map((c) => c.cardId));\n const missingIds = pendingHints.requireCards.filter(\n (p) => !p.includes('*') && !poolIds.has(p)\n );\n if (missingIds.length > 0) {\n const fetchedTags = await this.course!.getAppliedTagsBatch(missingIds);\n const courseId = this.course!.getCourseID();\n for (const cardId of missingIds) {\n allCardsBeforeFiltering.push({\n cardId,\n courseId,\n score: 1.0,\n tags: fetchedTags.get(cardId) ?? [],\n provenance: [],\n });\n }\n logger.info(\n `[Pipeline] Pre-fetched ${missingIds.length} required card(s) into pool: ${missingIds.join(', ')}`\n );\n }\n }\n\n // Apply filters sequentially, tracking impact\n // Track prescribed-origin cards through the filter chain for diagnostics\n const prescribedIds = new Set(\n cards\n .filter((c) => c.provenance.some((p) => p.strategy === 'prescribed'))\n .map((c) => c.cardId)\n );\n const filterImpacts: FilterImpact[] = [];\n // Scores as generated, so regulators can read the filters' net effect on each card.\n const generatedScores = new Map(cards.map((c) => [c.cardId, c.score]));\n // Cards a gate penalized: not ready, so regulators won't lift them.\n const gated = new Set<string>();\n // [perf] parked 2026-05 (pipeline-docs-workup) — uncomment to re-measure\n // const filterTimings: string[] = [];\n for (const filter of this.filters) {\n // const tFilterStart = performance.now();\n const beforeCount = cards.length;\n const beforeScores = new Map(cards.map((c) => [c.cardId, c.score]));\n cards = await filter.transform(cards, context);\n // filterTimings.push(`${filter.name}=${(performance.now() - tFilterStart).toFixed(0)}ms`);\n\n // Count boost/penalize/pass/removed for this filter\n let boosted = 0, penalized = 0, passed = 0;\n const removed = beforeCount - cards.length;\n\n // Undeclared filters count as gates (see CardFilter.kind).\n const kind = filter.kind ?? 'gate';\n for (const card of cards) {\n const before = beforeScores.get(card.cardId) ?? 0;\n if (card.score > before) boosted++;\n else if (card.score < before) {\n penalized++;\n if (kind === 'gate') gated.add(card.cardId);\n } else passed++;\n }\n filterImpacts.push({ name: filter.name, kind, boosted, penalized, passed, removed });\n\n // Report prescribed card fate through each filter\n if (prescribedIds.size > 0) {\n const survivingIds = new Set(cards.map((c) => c.cardId));\n const killedPrescribed = [...prescribedIds].filter((id) => !survivingIds.has(id));\n const zeroedPrescribed = cards\n .filter((c) => prescribedIds.has(c.cardId) && c.score === 0)\n .map((c) => c.cardId);\n if (killedPrescribed.length > 0 || zeroedPrescribed.length > 0) {\n logger.info(\n `[Pipeline] Filter '${filter.name}' impact on prescribed cards: ` +\n (killedPrescribed.length > 0 ? `removed=[${killedPrescribed.join(', ')}] ` : '') +\n (zeroedPrescribed.length > 0 ? `zeroed=[${zeroedPrescribed.join(', ')}]` : '')\n );\n // Remove killed ones from tracking set\n killedPrescribed.forEach((id) => prescribedIds.delete(id));\n }\n }\n\n logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeScores.size} → ${cards.length} cards (↑${boosted} ↓${penalized} =${passed})`);\n }\n\n // Remove zero-score cards (hard filtered). The debug report still wants\n // them: they're the answer to \"which filter sank this card?\"\n const scoredCards = cards;\n cards = cards.filter((c) => c.score > 0);\n\n // Regulators: class-level pressure between reviews and new cards, from the\n // filtered scores (see regulators.ts). Before hints, so session intent wins.\n const regulators = await this.regulate(cards, generatedScores, gated);\n\n // Apply ephemeral hints (one-shot, post-filter)\n const hints = this._ephemeralHints;\n if (hints) {\n this._ephemeralHints = null; // consume\n cards = this.applyHints(cards, hints, allCardsBeforeFiltering);\n }\n\n // Stage 3: diversity re-rank (post-filter, post-hints, pre-sort). Demotes\n // cards whose distinctive tags already appeared among higher-ranked\n // candidates so a single answer/concept can't monopolise the head of the\n // queue. Tag-agnostic (rarity-weighted overlap — no namespace privileged)\n // and expressed as score penalties so the ordering survives the final sort\n // here AND the SourceMixer's score-descending re-sort downstream.\n cards = diversityRerank(cards);\n\n // Sort by score descending\n cards.sort((a, b) => b.score - a.score);\n\n // Return top N\n const tFilter = performance.now();\n const result = cards.slice(0, limit);\n\n logger.info(\n `[Pipeline:timing] total=${(tFilter - t0).toFixed(0)}ms ` +\n `(context=${(tContext - t0).toFixed(0)} generate=${(tGenerate - tContext).toFixed(0)} ` +\n `hydrate=${(tHydrate - tGenerate).toFixed(0)} filter=${(tFilter - tHydrate).toFixed(0)})`\n );\n perfMeasure('sk:pipeline-run', t0, tFilter, {\n context: Math.round(tContext - t0),\n generate: Math.round(tGenerate - tContext),\n hydrate: Math.round(tHydrate - tGenerate),\n filter: Math.round(tFilter - tHydrate),\n binding: this.course?.readsLocal === undefined ? 'unknown' : this.course.readsLocal ? 'local' : 'remote',\n });\n\n // Toggle execution summary logging:\n const topScores = result.slice(0, 3).map((c) => c.score);\n logExecutionSummary(\n this.generator.name,\n generatedCount,\n this.filters.length,\n result.length,\n topScores,\n filterImpacts\n );\n\n // Toggle verbose result listing:\n logResultCards(result);\n\n // Toggle provenance logging (shows scoring history for top cards):\n logCardProvenance(result, 3);\n\n // Capture run for debug API\n try {\n const courseConfig = await this.course?.getCourseConfig().catch(() => undefined);\n const courseName = courseConfig?.name;\n // Pass the full post-filter sorted array; buildRunReport retains all\n // selected cards plus the top-N highest-scoring near-misses and\n // summarizes the discarded tail (see DISCARDED_KEEP_TOP). This keeps\n // showCard() useful for \"why didn't this rank?\" inspection without\n // pinning hundreds of low-score candidates' provenance per run.\n // `cards` is the post-filter, post-hints, sorted array.\n const report = buildRunReport(\n this.course?.getCourseID() || 'unknown',\n courseName,\n this.generator.name,\n generatorSummaries,\n generatedCount,\n filterImpacts,\n cards,\n result,\n context.userElo,\n hints?? undefined,\n scoredCards,\n regulators\n );\n const versions = {\n ...(this.strategyHash ? { strategies: this.strategyHash } : {}),\n ...(courseConfig?.contentVersion ? { content: courseConfig.contentVersion } : {}),\n };\n captureRun({ ...report, ...(Object.keys(versions).length ? { versions } : {}) });\n } catch (e) {\n logger.debug(`[Pipeline] Failed to capture debug run: ${e}`);\n }\n\n return { cards: result };\n }\n\n /**\n * Batch hydrate tags for all cards.\n *\n * Fetches tags for all cards in a single database query and attaches them\n * to the WeightedCard objects. Filters can then use card.tags instead of\n * making individual getAppliedTags() calls.\n *\n * Uses a persistent tag cache across pipeline runs — tags are static within\n * a session, so cards seen in a prior run (e.g. before a replan) don't\n * require a second DB query.\n *\n * @param cards - Cards to hydrate\n * @returns Cards with tags populated\n */\n private async hydrateTags(cards: WeightedCard[]): Promise<WeightedCard[]> {\n if (cards.length === 0) {\n return cards;\n }\n\n // Separate cards with cached tags from those needing a DB query\n const uncachedIds: string[] = [];\n for (const card of cards) {\n if (!this._tagCache.has(card.cardId)) {\n uncachedIds.push(card.cardId);\n }\n }\n\n // Only query the DB for cards not already in cache\n if (uncachedIds.length > 0) {\n const freshTags = await this.course!.getAppliedTagsBatch(uncachedIds);\n for (const [cardId, tags] of freshTags) {\n this._tagCache.set(cardId, tags);\n }\n }\n\n // Build the tagsByCard map from cache (for logging compatibility)\n const tagsByCard = new Map<string, string[]>();\n for (const card of cards) {\n tagsByCard.set(card.cardId, this._tagCache.get(card.cardId) ?? []);\n }\n\n // Toggle tag hydration logging:\n logTagHydration(cards, tagsByCard);\n\n return cards.map((card) => ({\n ...card,\n tags: this._tagCache.get(card.cardId) ?? [],\n }));\n }\n\n // ---------------------------------------------------------------------------\n // Ephemeral hints application\n // ---------------------------------------------------------------------------\n\n /**\n * Apply one-shot replan hints to the post-filter card set.\n *\n * Order of operations:\n * 1. Exclude (remove unwanted cards)\n * 2. Boost (multiply scores)\n * 3. Require (inject must-have cards from the full pre-filter pool)\n *\n * @param cards - Post-filter cards (score > 0)\n * @param hints - The ephemeral hints to apply\n * @param allCards - Full pre-filter card pool (for require injection)\n */\n private applyHints(\n cards: WeightedCard[],\n hints: ReplanHints,\n allCards: WeightedCard[]\n ): WeightedCard[] {\n const beforeCount = cards.length;\n\n // 1. Exclude\n if (hints.excludeCards?.length) {\n cards = cards.filter(\n (c) => !hints.excludeCards!.some((pat) => globMatch(c.cardId, pat))\n );\n }\n if (hints.excludeTags?.length) {\n cards = cards.filter(\n (c) => !hints.excludeTags!.some((pat) => cardMatchesTagPattern(c, pat))\n );\n }\n\n // 2. Boost\n if (hints.boostTags) {\n for (const [pattern, factor] of Object.entries(hints.boostTags)) {\n for (const card of cards) {\n if (cardMatchesTagPattern(card, pattern)) {\n card.score *= factor;\n card.provenance.push({\n strategy: 'ephemeralHint',\n strategyId: 'ephemeral-hint',\n strategyName: hints._label ? `Replan Hint (${hints._label})` : 'Replan Hint',\n action: 'boosted',\n score: card.score,\n reason: `boostTag ${pattern} ×${factor}`,\n });\n }\n }\n }\n }\n if (hints.boostCards) {\n for (const [pattern, factor] of Object.entries(hints.boostCards)) {\n for (const card of cards) {\n if (globMatch(card.cardId, pattern)) {\n card.score *= factor;\n card.provenance.push({\n strategy: 'ephemeralHint',\n strategyId: 'ephemeral-hint',\n strategyName: hints._label ? `Replan Hint (${hints._label})` : 'Replan Hint',\n action: 'boosted',\n score: card.score,\n reason: `boostCard ${pattern} ×${factor}`,\n });\n }\n }\n }\n }\n\n // 3. Require — ensure mandatory cards have floor score and are in the pool\n const cardIds = new Set(cards.map((c) => c.cardId));\n const cardMap = new Map(cards.map((c) => [c.cardId, c]));\n const hintLabel = hints._label ? `Replan Hint (${hints._label})` : 'Replan Hint';\n\n const applyRequirement = (card: WeightedCard, reason: string) => {\n const mandatoryScore = Number.POSITIVE_INFINITY;\n const existing = cardMap.get(card.cardId);\n\n if (existing) {\n // If already in the pool, upgrade to mandatory score if not already infinite\n if (existing.score < mandatoryScore) {\n existing.score = mandatoryScore;\n existing.provenance.push({\n strategy: 'ephemeralHint',\n strategyId: 'ephemeral-hint',\n strategyName: hintLabel,\n action: 'boosted',\n score: mandatoryScore,\n reason: `${reason} (upgrade to mandatory score)`,\n });\n }\n } else {\n // If missing, inject from the full pool\n cards.push({\n ...card,\n score: mandatoryScore,\n provenance: [\n ...card.provenance,\n {\n strategy: 'ephemeralHint',\n strategyId: 'ephemeral-hint',\n strategyName: hintLabel,\n action: 'boosted',\n score: mandatoryScore,\n reason,\n },\n ],\n });\n cardIds.add(card.cardId);\n cardMap.set(card.cardId, cards[cards.length - 1]);\n }\n };\n\n if (hints.requireCards?.length) {\n for (const pattern of hints.requireCards) {\n // First check candidates already in the pool\n for (const cardId of cardIds) {\n if (globMatch(cardId, pattern)) {\n applyRequirement(cardMap.get(cardId)!, `requireCard ${pattern}`);\n }\n }\n // Then check full pool for injection\n for (const card of allCards) {\n if (globMatch(card.cardId, pattern)) {\n applyRequirement(card, `requireCard ${pattern}`);\n }\n }\n }\n }\n if (hints.requireTags?.length) {\n for (const pattern of hints.requireTags) {\n // First check candidates already in the pool\n for (const cardId of cardIds) {\n const card = cardMap.get(cardId)!;\n if (cardMatchesTagPattern(card, pattern)) {\n applyRequirement(card, `requireTag ${pattern}`);\n }\n }\n // Then check full pool for injection\n for (const card of allCards) {\n if (cardMatchesTagPattern(card, pattern)) {\n applyRequirement(card, `requireTag ${pattern}`);\n }\n }\n }\n }\n\n logger.info(`[Pipeline] Hints applied: ${beforeCount} → ${cards.length} cards`);\n\n return cards;\n }\n\n /**\n * The regulator stage: measure each class's pressure and scale it.\n *\n * - Review mass: every due review's SRS urgency times the filters' net\n * effect on it.\n * - Intake: servable hours since a new card was presented, applied only to\n * eligible new cards (no gate penalized them). With none eligible, the\n * clock freezes.\n *\n * Mutates `cards` in place; returns the readings for the run report.\n */\n private async regulate(\n cards: WeightedCard[],\n generatedScores: ReadonlyMap<string, number>,\n gated: Set<string>\n ): Promise<RegulatorReading[]> {\n const config = DEFAULT_REGULATOR_CONFIG;\n const reviews = cards.filter((c) => c.reviewID);\n const newCards = cards.filter((c) => !c.reviewID);\n const eligibleNew = newCards.filter((c) => !gated.has(c.cardId));\n\n const mass = reviewMassReading(reviews, generatedScores, config.reviewMass);\n applyReading(reviews, mass);\n noteReviewPressure(this.course!.getCourseID(), {\n mass: mass.urgency,\n healthyMass: config.reviewMass.healthyMass,\n rate: config.reviewMass.rate,\n multiplier: mass.multiplier,\n });\n\n const now = Date.now();\n const clock = await this.loadIntakeClock(now);\n const stepped = stepIntakeClock(clock, now, eligibleNew.length);\n if (stepped !== clock) this.saveIntakeClock(stepped);\n const intake = intakeReading(\n stepped,\n now,\n { eligibleNew: eligibleNew.length, newCandidates: newCards.length },\n config.intake\n );\n applyReading(eligibleNew, intake);\n\n logger.info(\n `[Pipeline:regulators] review mass ${mass.urgency.toFixed(1)} over ${reviews.length} due → ` +\n `×${mass.multiplier.toFixed(2)}; intake ${intake.urgency.toFixed(1)}h, ` +\n `${eligibleNew.length}/${newCards.length} new eligible → ×${intake.multiplier.toFixed(2)}`\n );\n return [mass, intake];\n }\n\n /**\n * A card was presented. A new card's first presentation discharges the\n * intake valve: its clock restarts. Called by the SessionController.\n */\n notePresented(card: { cardId: string; courseId: string; status: string }): void {\n if (card.status !== 'new' || card.courseId !== this.course?.getCourseID()) return;\n this.saveIntakeClock(resetIntakeClock(Date.now()));\n }\n\n private async loadIntakeClock(nowMs: number): Promise<IntakeClockState> {\n if (this._intakeClock) return this._intakeClock;\n let stored: IntakeClockState | null = null;\n try {\n stored = await this.user!.getStrategyState<IntakeClockState>(\n this.course!.getCourseID(),\n INTAKE_CLOCK_KEY\n );\n } catch (e) {\n logger.warn(`[Pipeline:regulators] Could not read the intake clock: ${e}`);\n }\n if (stored) {\n this._intakeClock = stored;\n } else {\n // No clock yet: start it now.\n this.saveIntakeClock(resetIntakeClock(nowMs));\n }\n return this._intakeClock!;\n }\n\n private saveIntakeClock(state: IntakeClockState): void {\n this._intakeClock = state;\n const courseId = this.course!.getCourseID();\n this._intakeClockWrite = this._intakeClockWrite\n .then(() => this.user!.putStrategyState(courseId, INTAKE_CLOCK_KEY, state))\n .catch((e) => logger.warn(`[Pipeline:regulators] Could not save the intake clock: ${e}`));\n }\n\n /**\n * Build shared context for generator and filters.\n *\n * Called once per getWeightedCards() invocation.\n * Contains data that the generator and multiple filters might need.\n *\n * The context satisfies both GeneratorContext and FilterContext interfaces.\n */\n private async buildContext(): Promise<GeneratorContext & FilterContext> {\n let userElo = 1000; // Default ELO\n let userCourseElo: CourseElo | undefined;\n\n try {\n const courseReg = await this.user!.getCourseRegDoc(this.course!.getCourseID());\n userCourseElo = toCourseElo(courseReg.elo);\n userElo = userCourseElo.global.score;\n } catch (e) {\n logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);\n }\n\n // Reuse cached orchestration context if available (course config is stable\n // within a page load). This avoids a remote getCourseConfig() call on\n // subsequent pipeline runs (e.g. mid-session replans).\n if (!this._cachedOrchestration) {\n this._cachedOrchestration = await createOrchestrationContext(this.user!, this.course!);\n }\n const orchestration = this._cachedOrchestration;\n\n return {\n user: this.user!,\n course: this.course!,\n userElo,\n ...(userCourseElo ? { userCourseElo } : {}),\n orchestration,\n };\n }\n\n /**\n * Get the course ID for this pipeline.\n */\n getCourseID(): string {\n return this.course!.getCourseID();\n }\n\n /**\n * Get orchestration context for outcome recording.\n */\n async getOrchestrationContext(): Promise<OrchestrationContext> {\n return createOrchestrationContext(this.user!, this.course!);\n }\n\n /**\n * Get IDs of all strategies in this pipeline.\n * Used to record which strategies contributed to an outcome.\n */\n getStrategyIds(): string[] {\n const ids: string[] = [];\n\n const extractId = (obj: any): string | null => {\n // Check for strategyId property (ContentNavigator, WeightedFilter)\n if (obj.strategyId) return obj.strategyId;\n return null;\n };\n\n // Generator(s)\n const genId = extractId(this.generator);\n if (genId) ids.push(genId);\n\n // Inspect CompositeGenerator children (accessing private field via cast)\n if ((this.generator as any).generators && Array.isArray((this.generator as any).generators)) {\n (this.generator as any).generators.forEach((g: any) => {\n const subId = extractId(g);\n if (subId) ids.push(subId);\n });\n }\n\n // Filters\n for (const filter of this.filters) {\n const fId = extractId(filter);\n if (fId) ids.push(fId);\n }\n\n return [...new Set(ids)];\n }\n\n // ---------------------------------------------------------------------------\n // Tag ELO diagnostic\n // ---------------------------------------------------------------------------\n\n /**\n * Get the user's per-tag ELO data for specified tags (or all tags).\n * Useful for diagnosing why hierarchy gates are open/closed.\n */\n async getTagEloStatus(\n tagFilter?: string | string[]\n ): Promise<Record<string, { score: number; count: number }>> {\n const courseReg = await this.user!.getCourseRegDoc(this.course!.getCourseID());\n const courseElo = toCourseElo(courseReg.elo);\n\n const result: Record<string, { score: number; count: number }> = {};\n\n if (!tagFilter) {\n // Return all tags\n for (const [tag, data] of Object.entries(courseElo.tags)) {\n result[tag] = { score: data.score, count: data.count };\n }\n } else {\n const patterns = Array.isArray(tagFilter) ? tagFilter : [tagFilter];\n for (const pattern of patterns) {\n const regex = globToRegex(pattern);\n for (const [tag, data] of Object.entries(courseElo.tags)) {\n if (regex.test(tag)) {\n result[tag] = { score: data.score, count: data.count };\n }\n }\n }\n }\n\n return result;\n }\n\n // ---------------------------------------------------------------------------\n // Card-space diagnostic\n // ---------------------------------------------------------------------------\n\n /**\n * Commit-free forecast: score the user's full card space through the filter\n * chain and return the cards that are currently *reachable* (score >=\n * threshold), optionally nudged by caller-supplied hints and/or restricted\n * to cards the user hasn't seen yet.\n *\n * This is a GENERIC primitive — it returns scored, tag-hydrated cards and\n * stops there. It has no knowledge of any particular tag convention; callers\n * decide what the surviving cards mean (e.g. filter to their own \"intro\"\n * tag family). Nothing is written and no session is started.\n *\n * The optional `hints` are the \"out-of-band kick\": they run through the same\n * {@link applyHints} path a live replan uses, so the two semantics carry over —\n * - `boostTags`/`boostCards` reweight *within* gating (a gated score-0 card\n * stays out), and\n * - `requireTags`/`requireCards` inject from the full pre-filter pool,\n * *bypassing* gating (use when you want a card regardless of reachability).\n * Note `unseenOnly` is applied LAST, so it can drop a `require`d card that the\n * user has already seen — pass `unseenOnly: false` if that matters.\n *\n * Cost note: like {@link diagnoseCardSpace}, this scans every card through the\n * filters, so it's heavier than a normal replan. Intended for one-shot\n * out-of-band use (e.g. a session-end \"what's next\" snapshot), not the hot path.\n *\n * @param opts.hints Optional ephemeral hints to apply after the filter chain.\n * @param opts.unseenOnly Only return cards the user hasn't encountered (default true).\n * @param opts.threshold Min score to count as reachable (default 0.10).\n * @param opts.limit Optional cap on results (already sorted desc).\n */\n async forecast(opts?: {\n hints?: ReplanHints;\n unseenOnly?: boolean;\n threshold?: number;\n limit?: number;\n }): Promise<WeightedCard[]> {\n const threshold = opts?.threshold ?? 0.10;\n const unseenOnly = opts?.unseenOnly ?? true;\n\n const courseId = this.course!.getCourseID();\n const allCardIds = await this.course!.getAllCardIds();\n\n let cards: WeightedCard[] = allCardIds.map((cardId) => ({\n cardId,\n courseId,\n score: 1.0,\n provenance: [],\n }));\n\n cards = await this.hydrateTags(cards);\n // Snapshot the full pool before filtering, for require-injection in applyHints.\n const fullPool = cards.slice();\n\n const context = await this.buildContext();\n for (const filter of this.forecastFilters()) {\n cards = await filter.transform(cards, context);\n }\n\n if (opts?.hints) {\n cards = this.applyHints(cards, opts.hints, fullPool);\n }\n\n cards = cards.filter((c) => c.score >= threshold);\n\n if (unseenOnly) {\n let encountered: Set<string>;\n try {\n encountered = new Set(await this.user!.getSeenCards(courseId));\n } catch {\n encountered = new Set();\n }\n cards = cards.filter((c) => !encountered.has(c.cardId));\n }\n\n cards.sort((a, b) => b.score - a.score);\n return opts?.limit ? cards.slice(0, opts.limit) : cards;\n }\n\n /**\n * The filters a forecast or card-space scan applies. Those start every card at\n * 1.0 without a generator, so they skip `liveOnly` filters (ELO distance),\n * which only make sense against generator scores.\n */\n private forecastFilters(): CardFilter[] {\n return this.filters.filter((f) => !f.liveOnly);\n }\n\n /**\n * Scan every card in the course through the filter chain and report\n * how many are \"well indicated\" (score >= threshold) for the current user.\n *\n * Also reports how many well-indicated cards the user has NOT yet encountered.\n *\n * Exposed via `window.skuilder.pipeline.diagnoseCardSpace()`.\n */\n async diagnoseCardSpace(opts?: { threshold?: number }): Promise<CardSpaceDiagnosis> {\n const THRESHOLD = opts?.threshold ?? 0.10;\n const t0 = performance.now();\n\n // 1. Get all card IDs\n const allCardIds = await this.course!.getAllCardIds();\n\n // 2. Build dummy WeightedCards (score=1.0, no provenance)\n let cards: WeightedCard[] = allCardIds.map((cardId) => ({\n cardId,\n courseId: this.course!.getCourseID(),\n score: 1.0,\n provenance: [],\n }));\n\n // 3. Hydrate tags\n cards = await this.hydrateTags(cards);\n\n // 4. Run through filters\n const context = await this.buildContext();\n const filterBreakdown: Array<{ name: string; wellIndicated: number }> = [];\n\n // Track cumulative filter effects\n for (const filter of this.forecastFilters()) {\n cards = await filter.transform(cards, context);\n const wi = cards.filter((c) => c.score >= THRESHOLD).length;\n filterBreakdown.push({ name: filter.name, wellIndicated: wi });\n }\n\n // 5. Count well-indicated\n const wellIndicated = cards.filter((c) => c.score >= THRESHOLD);\n const wellIndicatedIds = new Set(wellIndicated.map((c) => c.cardId));\n\n // 6. Get encountered cards\n let encounteredIds: Set<string>;\n try {\n const courseId = this.course!.getCourseID();\n const seenCards = await this.user!.getSeenCards(courseId);\n encounteredIds = new Set(seenCards);\n } catch {\n encounteredIds = new Set();\n }\n\n const wellIndicatedNew = wellIndicated.filter((c) => !encounteredIds.has(c.cardId));\n\n // 7. Group by card type\n const byType = new Map<string, { total: number; wellIndicated: number; new: number }>();\n for (const card of cards) {\n const type = card.cardId.split('-')[1] || 'unknown'; // c-ws-... → ws, c-intro-... → intro, etc.\n if (!byType.has(type)) {\n byType.set(type, { total: 0, wellIndicated: 0, new: 0 });\n }\n const entry = byType.get(type)!;\n entry.total++;\n if (card.score >= THRESHOLD) {\n entry.wellIndicated++;\n if (!encounteredIds.has(card.cardId)) entry.new++;\n }\n }\n\n const elapsed = performance.now() - t0;\n\n const result: CardSpaceDiagnosis = {\n totalCards: allCardIds.length,\n threshold: THRESHOLD,\n wellIndicated: wellIndicatedIds.size,\n encountered: encounteredIds.size,\n wellIndicatedNew: wellIndicatedNew.length,\n byType: Object.fromEntries(byType),\n filterBreakdown,\n elapsedMs: Math.round(elapsed),\n };\n\n // Log to console\n logger.print(`[Pipeline:diagnose] Card space scan (${result.elapsedMs}ms):`);\n logger.print(`[Pipeline:diagnose] Total cards: ${result.totalCards}`);\n logger.print(`[Pipeline:diagnose] Well-indicated (score >= ${THRESHOLD}): ${result.wellIndicated}`);\n logger.print(`[Pipeline:diagnose] Encountered: ${result.encountered}`);\n logger.print(`[Pipeline:diagnose] Well-indicated & new: ${result.wellIndicatedNew}`);\n logger.print(`[Pipeline:diagnose] By type:`);\n for (const [type, counts] of byType) {\n logger.print(\n `[Pipeline:diagnose] ${type}: ${counts.wellIndicated}/${counts.total} well-indicated, ${counts.new} new`\n );\n }\n logger.print(`[Pipeline:diagnose] After each filter:`);\n for (const fb of filterBreakdown) {\n logger.print(`[Pipeline:diagnose] ${fb.name}: ${fb.wellIndicated} well-indicated`);\n }\n\n return result;\n }\n\n}\n\n/**\n * Diagnosis of the full card space for the current user.\n */\nexport interface CardSpaceDiagnosis {\n totalCards: number;\n threshold: number;\n wellIndicated: number;\n encountered: number;\n wellIndicatedNew: number;\n byType: Record<string, { total: number; wellIndicated: number; new: number }>;\n filterBreakdown: Array<{ name: string; wellIndicated: number }>;\n elapsedMs: number;\n}\n"],"mappings":";;;;;;;;;;;;;;;AA+CA,SAAS,YAAY,SAAyB;CAE5C,MAAM,gBADU,QAAQ,QAAQ,sBAAsB,OAAO,CAC/B,QAAQ,OAAO,KAAK;AAClD,QAAO,IAAI,OAAO,IAAI,cAAc,GAAG;;;AAIzC,SAAS,UAAU,OAAe,SAA0B;AAC1D,KAAI,CAAC,QAAQ,SAAS,IAAI,CAAE,QAAO,UAAU;AAC7C,QAAO,YAAY,QAAQ,CAAC,KAAK,MAAM;;;AAIzC,SAAS,sBAAsB,MAAoB,SAA0B;AAC3E,SAAQ,KAAK,QAAQ,EAAE,EAAE,MAAM,QAAQ,UAAU,KAAK,QAAQ,CAAC;;AAGjE,SAAgB,WAAW,UAA0E;CACnG,MAAM,UAAU,SAAS,QAAQ,MAAwB,MAAM,QAAQ,MAAM,KAAA,EAAU;AACvF,KAAI,QAAQ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O,cAAc;AACxE,SAAO,MAAM,+CAA+C,OAAO,mBAAmB;AACtF,SAAO,MAAM,iCAAiC;AAC9C,OAAK,MAAM,CAAC,MAAM,WAAW,OAC3B,QAAO,MACL,2BAA2B,KAAK,IAAI,OAAO,cAAc,GAAG,OAAO,MAAM,mBAAmB,OAAO,IAAI,MACxG;AAEH,SAAO,MAAM,2CAA2C;AACxD,OAAK,MAAM,MAAM,gBACf,QAAO,MAAM,2BAA2B,GAAG,KAAK,IAAI,GAAG,cAAc,iBAAiB;AAGxF,SAAO"}
1
+ {"version":3,"file":"Pipeline.mjs","names":[],"sources":["../../../src/core/navigators/Pipeline.ts"],"sourcesContent":["import { toCourseElo, type CourseElo } from '@vue-skuilder/common';\nimport type { CourseDBInterface } from '../interfaces/courseDB';\nimport type { UserDBInterface } from '../interfaces/userDB';\nimport { ContentNavigator } from './index';\nimport type { WeightedCard } from './index';\nimport type { CardFilter, FilterContext } from './filters/types';\nimport type { CardGenerator, GeneratorContext } from './generators/types';\nimport type { GeneratorResult } from './generators/types';\nimport { logger } from '../../util/logger';\nimport { perfMeasure } from '../../util/perfMarks';\nimport { createOrchestrationContext, OrchestrationContext } from '../orchestration';\nimport { captureRun, buildRunReport, registerPipelineForDebug, type GeneratorSummary, type FilterImpact } from './PipelineDebugger';\nimport { diversityRerank } from './diversityRerank';\nimport {\n applyReading,\n DEFAULT_REGULATOR_CONFIG,\n INTAKE_CLOCK_KEY,\n intakeReading,\n resetIntakeClock,\n reviewMassReading,\n stepIntakeClock,\n type IntakeClockState,\n type RegulatorReading,\n} from './regulators';\nimport { noteReviewPressure } from './SrsDebugger';\n\n// ============================================================================\n// REPLAN HINTS\n// ============================================================================\n//\n// Ephemeral, one-shot scoring hints passed at replan time.\n// Applied after the filter chain, consumed after one pipeline run.\n//\n// Tag patterns support glob-style matching:\n// 'gpc:exercise:t-T' — exact match\n// 'gpc:intro:*' — all intro tags\n// 'gpc:exercise:t-*' — all t-variant exercises\n//\n\n// ReplanHints is defined in generators/types — re-export for consumers that import from Pipeline\nimport type { ReplanHints } from './generators/types';\nexport type { ReplanHints };\n\n/**\n * Convert a glob pattern (with `*` wildcards) to a RegExp.\n * Only `*` is supported as a wildcard (matches any characters).\n */\nfunction globToRegex(pattern: string): RegExp {\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const withWildcards = escaped.replace(/\\*/g, '.*');\n return new RegExp(`^${withWildcards}$`);\n}\n\n/** Test whether a string matches a glob pattern. */\nfunction globMatch(value: string, pattern: string): boolean {\n if (!pattern.includes('*')) return value === pattern;\n return globToRegex(pattern).test(value);\n}\n\n/** Test whether any of a card's tags match a glob pattern. */\nfunction cardMatchesTagPattern(card: WeightedCard, pattern: string): boolean {\n return (card.tags ?? []).some((tag) => globMatch(tag, pattern));\n}\n\nexport function mergeHints(allHints: Array<ReplanHints | null | undefined>): ReplanHints | undefined {\n const defined = allHints.filter((h): h is ReplanHints => h !== null && h !== undefined);\n if (defined.length === 0) return undefined;\n\n const merged: ReplanHints = {};\n\n const boostTags: Record<string, number> = {};\n for (const hints of defined) {\n for (const [pattern, factor] of Object.entries(hints.boostTags ?? {})) {\n boostTags[pattern] = (boostTags[pattern] ?? 1) * factor;\n }\n }\n if (Object.keys(boostTags).length > 0) {\n merged.boostTags = boostTags;\n }\n\n const boostCards: Record<string, number> = {};\n for (const hints of defined) {\n for (const [pattern, factor] of Object.entries(hints.boostCards ?? {})) {\n boostCards[pattern] = (boostCards[pattern] ?? 1) * factor;\n }\n }\n if (Object.keys(boostCards).length > 0) {\n merged.boostCards = boostCards;\n }\n\n const concatUnique = (\n field: 'requireTags' | 'requireCards' | 'excludeTags' | 'excludeCards'\n ): void => {\n const values = defined.flatMap((h) => h[field] ?? []);\n if (values.length > 0) {\n merged[field] = [...new Set(values)];\n }\n };\n\n concatUnique('requireTags');\n concatUnique('requireCards');\n concatUnique('excludeTags');\n concatUnique('excludeCards');\n\n const labels = defined.map((h) => h._label).filter(Boolean);\n if (labels.length > 0) {\n merged._label = labels.join('; ');\n }\n\n return Object.keys(merged).length > 0 ? merged : undefined;\n}\n\n// ============================================================================\n// PIPELINE LOGGING HELPERS\n// ============================================================================\n//\n// Focused logging functions that can be toggled by commenting single lines.\n// Use these to inspect pipeline behavior in development/production.\n//\n\n/**\n * Log pipeline configuration on construction.\n * Shows generator and filter chain structure.\n */\nfunction logPipelineConfig(generator: CardGenerator, filters: CardFilter[]): void {\n const filterList =\n filters.length > 0 ? '\\n - ' + filters.map((f) => f.name).join('\\n - ') : ' none';\n\n logger.info(\n `[Pipeline] Configuration:\\n` + ` Generator: ${generator.name}\\n` + ` Filters:${filterList}`\n );\n}\n\n/**\n * Log tag hydration results.\n * Shows effectiveness of batch query (how many cards/tags were hydrated).\n */\nfunction logTagHydration(cards: WeightedCard[], tagsByCard: Map<string, string[]>): void {\n const totalTags = Array.from(tagsByCard.values()).reduce((sum, tags) => sum + tags.length, 0);\n const cardsWithTags = Array.from(tagsByCard.values()).filter((tags) => tags.length > 0).length;\n\n logger.debug(\n `[Pipeline] Tag hydration: ${cards.length} cards, ` +\n `${cardsWithTags} have tags (${totalTags} total tags) - single batch query`\n );\n}\n\n/**\n * Log pipeline execution summary.\n * Shows complete flow from generator through filters to final results.\n */\nfunction logExecutionSummary(\n generatorName: string,\n generatedCount: number,\n filterCount: number,\n finalCount: number,\n topScores: number[],\n filterImpacts: Array<{ name: string; boosted: number; penalized: number; passed: number }>\n): void {\n const scoreDisplay =\n topScores.length > 0 ? topScores.map((s) => s.toFixed(2)).join(', ') : 'none';\n\n let filterSummary = '';\n if (filterImpacts.length > 0) {\n const impacts = filterImpacts.map((f) => {\n const parts: string[] = [];\n if (f.boosted > 0) parts.push(`+${f.boosted}`);\n if (f.penalized > 0) parts.push(`-${f.penalized}`);\n if (f.passed > 0) parts.push(`=${f.passed}`);\n return `${f.name}: ${parts.join('/')}`;\n });\n filterSummary = `\\n Filter impact: ${impacts.join(', ')}`;\n }\n\n logger.info(\n `[Pipeline] Execution: ${generatorName} produced ${generatedCount} → ` +\n `${filterCount} filters → ${finalCount} results (top scores: ${scoreDisplay})` +\n filterSummary +\n `\\n 💡 Inspect: window.skuilder.pipeline`\n );\n}\n\n/**\n * Log all result cards with score, cardId, and key provenance.\n * Toggle: set VERBOSE_RESULTS = true to enable.\n */\nconst VERBOSE_RESULTS = false;\n\nfunction logResultCards(cards: WeightedCard[]): void {\n if (!VERBOSE_RESULTS || cards.length === 0) return;\n\n logger.info(`[Pipeline] Results (${cards.length} cards):`);\n for (let i = 0; i < cards.length; i++) {\n const c = cards[i];\n const tags = c.tags?.slice(0, 3).join(', ') || '';\n const filters = c.provenance\n .filter((p) => p.strategy === 'hierarchyDefinition' || p.strategy === 'priorityDefinition' || p.strategy === 'interferenceFilter' || p.strategy === 'letterGating' || p.strategy === 'ephemeralHint' || p.strategy === 'diversityRerank')\n .map((p) => {\n const arrow = p.action === 'boosted' ? '↑' : p.action === 'penalized' ? '↓' : '=';\n return `${p.strategyName}${arrow}${p.score.toFixed(2)}`;\n })\n .join(' | ');\n logger.info(\n `[Pipeline] ${String(i + 1).padStart(2)}. ${c.score.toFixed(4)} ${c.cardId} [${tags}]${filters ? ` {${filters}}` : ''}`\n );\n }\n}\n\n/**\n * Log provenance trails for cards.\n * Shows the complete scoring history for each card through the pipeline.\n * Useful for debugging why cards scored the way they did.\n */\nfunction logCardProvenance(cards: WeightedCard[], maxCards: number = 3): void {\n const cardsToLog = cards.slice(0, maxCards);\n\n logger.debug(`[Pipeline] Provenance for top ${cardsToLog.length} cards:`);\n\n for (const card of cardsToLog) {\n logger.debug(`[Pipeline] ${card.cardId} (final score: ${card.score.toFixed(3)}):`);\n\n for (const entry of card.provenance) {\n const scoreChange = entry.score.toFixed(3);\n const action = entry.action.padEnd(9); // Align columns\n logger.debug(\n `[Pipeline] ${action} ${scoreChange} - ${entry.strategyName}: ${entry.reason}`\n );\n }\n }\n}\n\n// ============================================================================\n// PIPELINE\n// ============================================================================\n//\n// Executes a navigation pipeline: generator → filters → sorted results.\n//\n// Architecture:\n// cards = generator.getWeightedCards(limit, context)\n// cards = filter1.transform(cards, context)\n// cards = filter2.transform(cards, context)\n// cards = filter3.transform(cards, context)\n// return sorted(cards).slice(0, limit)\n//\n// Benefits:\n// - Clear separation: generators produce, filters transform\n// - No nested instantiation complexity\n// - Filters don't need to know about each other\n// - Shared context built once, passed to all stages\n//\n// ============================================================================\n\n/**\n * A navigation pipeline that runs a generator and applies filters sequentially.\n *\n * Implements StudyContentSource for backward compatibility with SessionController.\n *\n * ## Usage\n *\n * ```typescript\n * const pipeline = new Pipeline(\n * compositeGenerator, // or single generator\n * [eloDistanceFilter, interferenceFilter],\n * user,\n * course\n * );\n *\n * const cards = await pipeline.getWeightedCards(20);\n * ```\n */\n\n/**\n * Narrow capability surface for out-of-band, commit-free reads against a live\n * pipeline (see {@link getActivePipeline}). Kept minimal on purpose — consumers\n * get the forecast capability, not the whole `Pipeline` class.\n */\nexport interface PipelineForecaster {\n forecast(opts?: {\n hints?: ReplanHints;\n unseenOnly?: boolean;\n threshold?: number;\n limit?: number;\n }): Promise<WeightedCard[]>;\n}\n\nexport class Pipeline extends ContentNavigator implements PipelineForecaster {\n private generator: CardGenerator;\n private filters: CardFilter[];\n\n /**\n * Cached orchestration context. Course config and salt don't change within\n * a page load, so we build the orchestration context once and reuse it on\n * subsequent getWeightedCards() calls (e.g. mid-session replans).\n *\n * This eliminates a remote getCourseConfig() round trip per pipeline run.\n */\n private _cachedOrchestration: OrchestrationContext | null = null;\n\n /**\n * Hash of the strategy docs this pipeline was assembled from (see\n * versionStamps.ts), set by whoever builds it. Stamped on every run.\n */\n strategyHash?: string;\n\n /**\n * Persistent tag cache. Maps cardId → tag names.\n *\n * Tags are static within a session (they're set at card generation time),\n * so we cache them across pipeline runs. On replans, many of the same cards\n * reappear — cache hits avoid redundant remote getAppliedTagsBatch() queries.\n */\n private _tagCache: Map<string, string[]> = new Map();\n\n /**\n * One-shot replan hints. Applied after the filter chain on the next\n * getWeightedCards() call, then cleared.\n */\n private _ephemeralHints: ReplanHints | null = null;\n private _sessionId: string | undefined;\n\n /**\n * The intake valve's clock (see regulators.ts), loaded from strategy state on\n * first use and kept in memory. Writes are chained so a presentation and a\n * run can't race each other's revision.\n */\n private _intakeClock: IntakeClockState | null = null;\n private _intakeClockWrite: Promise<void> = Promise.resolve();\n\n /**\n * Create a new pipeline.\n *\n * @param generator - The generator (or CompositeGenerator) that produces candidates\n * @param filters - Filters to apply sequentially (order doesn't matter for multipliers)\n * @param user - User database interface\n * @param course - Course database interface\n */\n constructor(\n generator: CardGenerator,\n filters: CardFilter[],\n user: UserDBInterface,\n course: CourseDBInterface\n ) {\n super();\n this.generator = generator;\n this.filters = filters;\n this.user = user;\n this.course = course;\n\n course\n .getCourseConfig()\n .then((cfg) => {\n logger.debug(`[pipeline] Crated pipeline for ${cfg.name}`);\n })\n .catch((e) => {\n logger.error(`[pipeline] Failed to lookup courseCfg: ${e}`);\n });\n // Toggle pipeline configuration logging:\n logPipelineConfig(generator, filters);\n\n // Register for debug API access\n registerPipelineForDebug(this);\n }\n\n /**\n * Set one-shot hints for the next pipeline run.\n * Consumed after one getWeightedCards() call, then cleared.\n *\n * Overrides ContentNavigator.setEphemeralHints() no-op.\n */\n /** See StudyContentSource.setSessionId. Carried into every run's context. */\n override setSessionId(sessionId: string): void {\n this._sessionId = sessionId;\n }\n\n override setEphemeralHints(hints: ReplanHints): void {\n this._ephemeralHints = hints;\n logger.info(`[Pipeline] Ephemeral hints set: ${JSON.stringify(hints)}`);\n }\n\n /**\n * Get weighted cards by running generator and applying filters.\n *\n * 1. Build shared context (user ELO, etc.)\n * 2. Get candidates from generator (passing context)\n * 3. Batch hydrate tags for all candidates\n * 4. Apply each filter sequentially\n * 5. Remove zero-score cards\n * 6. Sort by score descending\n * 7. Return top N\n *\n * @param limit - Maximum number of cards to return\n * @returns Cards sorted by score descending\n */\n async getWeightedCards(limit: number): Promise<GeneratorResult> {\n const t0 = performance.now();\n\n // Build shared context once\n const context = await this.buildContext();\n const tContext = performance.now();\n\n // Over-fetch from generator to give filters a wide candidate pool.\n // With local course DB the cost is negligible (~20ms for 500 cards).\n // Filters (hierarchy, letter gating, etc.) can be aggressive — a wide\n // pool ensures enough well-indicated candidates survive.\n const fetchLimit = 500;\n\n logger.debug(\n `[Pipeline] Fetching ${fetchLimit} candidates from generator '${this.generator.name}'`\n );\n\n // Get candidates from generator, passing context\n const generatorResult = await this.generator.getWeightedCards(fetchLimit, context);\n let cards = generatorResult.cards;\n const tGenerate = performance.now();\n const generatedCount = cards.length;\n\n // Merge generator-emitted hints with any externally supplied one-shot hints\n const mergedHints = mergeHints([this._ephemeralHints, generatorResult.hints]);\n this._ephemeralHints = mergedHints ?? null;\n \n // Capture generator breakdown for debugging (if CompositeGenerator)\n let generatorSummaries: GeneratorSummary[] | undefined;\n if ((this.generator as any).generators) {\n // This is a CompositeGenerator - extract per-generator info from provenance\n const genMap = new Map<string, { cards: WeightedCard[] }>();\n for (const card of cards) {\n const firstProv = card.provenance[0];\n if (firstProv) {\n const genName = firstProv.strategyName;\n if (!genMap.has(genName)) {\n genMap.set(genName, { cards: [] });\n }\n genMap.get(genName)!.cards.push(card);\n }\n }\n generatorSummaries = Array.from(genMap.entries()).map(([name, data]) => {\n // Reviews carry `reviewID`; everything else a generator emits is unseen.\n // (Reason text can't tell: the ELO generator's never says \"new card\".)\n const reviewCount = data.cards.filter((c) => c.reviewID).length;\n return {\n name,\n cardCount: data.cards.length,\n newCount: data.cards.length - reviewCount,\n reviewCount,\n topScore: Math.max(...data.cards.map((c) => c.score), 0),\n };\n });\n }\n\n logger.debug(`[Pipeline] Generator returned ${generatedCount} candidates`);\n\n // Batch hydrate tags before filters run\n cards = await this.hydrateTags(cards);\n const tHydrate = performance.now();\n \n // Keep a copy of all cards for debug capture (before filtering removes any)\n const allCardsBeforeFiltering = [...cards];\n\n // Pre-fetch any literal requireCards IDs that the generator didn't produce.\n // requireCards is a hard guarantee — required cards bypass the filter chain\n // and are injected directly into the final result by applyHints. We need\n // them present in allCardsBeforeFiltering for that injection to find them.\n // (Glob patterns are left to the existing pool-search behaviour.)\n const pendingHints = this._ephemeralHints;\n if (pendingHints?.requireCards?.length) {\n const poolIds = new Set(allCardsBeforeFiltering.map((c) => c.cardId));\n const missingIds = pendingHints.requireCards.filter(\n (p) => !p.includes('*') && !poolIds.has(p)\n );\n if (missingIds.length > 0) {\n const fetchedTags = await this.course!.getAppliedTagsBatch(missingIds);\n const courseId = this.course!.getCourseID();\n for (const cardId of missingIds) {\n allCardsBeforeFiltering.push({\n cardId,\n courseId,\n score: 1.0,\n tags: fetchedTags.get(cardId) ?? [],\n provenance: [],\n });\n }\n logger.info(\n `[Pipeline] Pre-fetched ${missingIds.length} required card(s) into pool: ${missingIds.join(', ')}`\n );\n }\n }\n\n // Apply filters sequentially, tracking impact\n // Track prescribed-origin cards through the filter chain for diagnostics\n const prescribedIds = new Set(\n cards\n .filter((c) => c.provenance.some((p) => p.strategy === 'prescribed'))\n .map((c) => c.cardId)\n );\n const filterImpacts: FilterImpact[] = [];\n // Scores as generated, so regulators can read the filters' net effect on each card.\n const generatedScores = new Map(cards.map((c) => [c.cardId, c.score]));\n // Cards a gate penalized: not ready, so regulators won't lift them.\n const gated = new Set<string>();\n // [perf] parked 2026-05 (pipeline-docs-workup) — uncomment to re-measure\n // const filterTimings: string[] = [];\n for (const filter of this.filters) {\n // const tFilterStart = performance.now();\n const beforeCount = cards.length;\n const beforeScores = new Map(cards.map((c) => [c.cardId, c.score]));\n cards = await filter.transform(cards, context);\n // filterTimings.push(`${filter.name}=${(performance.now() - tFilterStart).toFixed(0)}ms`);\n\n // Count boost/penalize/pass/removed for this filter\n let boosted = 0, penalized = 0, passed = 0;\n const removed = beforeCount - cards.length;\n\n // Undeclared filters count as gates (see CardFilter.kind).\n const kind = filter.kind ?? 'gate';\n for (const card of cards) {\n const before = beforeScores.get(card.cardId) ?? 0;\n if (card.score > before) boosted++;\n else if (card.score < before) {\n penalized++;\n if (kind === 'gate') gated.add(card.cardId);\n } else passed++;\n }\n filterImpacts.push({ name: filter.name, kind, boosted, penalized, passed, removed });\n\n // Report prescribed card fate through each filter\n if (prescribedIds.size > 0) {\n const survivingIds = new Set(cards.map((c) => c.cardId));\n const killedPrescribed = [...prescribedIds].filter((id) => !survivingIds.has(id));\n const zeroedPrescribed = cards\n .filter((c) => prescribedIds.has(c.cardId) && c.score === 0)\n .map((c) => c.cardId);\n if (killedPrescribed.length > 0 || zeroedPrescribed.length > 0) {\n logger.info(\n `[Pipeline] Filter '${filter.name}' impact on prescribed cards: ` +\n (killedPrescribed.length > 0 ? `removed=[${killedPrescribed.join(', ')}] ` : '') +\n (zeroedPrescribed.length > 0 ? `zeroed=[${zeroedPrescribed.join(', ')}]` : '')\n );\n // Remove killed ones from tracking set\n killedPrescribed.forEach((id) => prescribedIds.delete(id));\n }\n }\n\n logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeScores.size} → ${cards.length} cards (↑${boosted} ↓${penalized} =${passed})`);\n }\n\n // Remove zero-score cards (hard filtered). The debug report still wants\n // them: they're the answer to \"which filter sank this card?\"\n const scoredCards = cards;\n cards = cards.filter((c) => c.score > 0);\n\n // Regulators: class-level pressure between reviews and new cards, from the\n // filtered scores (see regulators.ts). Before hints, so session intent wins.\n const regulators = await this.regulate(cards, generatedScores, gated);\n\n // Apply ephemeral hints (one-shot, post-filter)\n const hints = this._ephemeralHints;\n if (hints) {\n this._ephemeralHints = null; // consume\n cards = this.applyHints(cards, hints, allCardsBeforeFiltering);\n }\n\n // Stage 3: diversity re-rank (post-filter, post-hints, pre-sort). Demotes\n // cards whose distinctive tags already appeared among higher-ranked\n // candidates so a single answer/concept can't monopolise the head of the\n // queue. Tag-agnostic (rarity-weighted overlap — no namespace privileged)\n // and expressed as score penalties so the ordering survives the final sort\n // here AND the SourceMixer's score-descending re-sort downstream.\n cards = diversityRerank(cards);\n\n // Sort by score descending\n cards.sort((a, b) => b.score - a.score);\n\n // Return top N\n const tFilter = performance.now();\n const result = cards.slice(0, limit);\n\n logger.info(\n `[Pipeline:timing] total=${(tFilter - t0).toFixed(0)}ms ` +\n `(context=${(tContext - t0).toFixed(0)} generate=${(tGenerate - tContext).toFixed(0)} ` +\n `hydrate=${(tHydrate - tGenerate).toFixed(0)} filter=${(tFilter - tHydrate).toFixed(0)})`\n );\n perfMeasure('sk:pipeline-run', t0, tFilter, {\n context: Math.round(tContext - t0),\n generate: Math.round(tGenerate - tContext),\n hydrate: Math.round(tHydrate - tGenerate),\n filter: Math.round(tFilter - tHydrate),\n binding: this.course?.readsLocal === undefined ? 'unknown' : this.course.readsLocal ? 'local' : 'remote',\n });\n\n // Toggle execution summary logging:\n const topScores = result.slice(0, 3).map((c) => c.score);\n logExecutionSummary(\n this.generator.name,\n generatedCount,\n this.filters.length,\n result.length,\n topScores,\n filterImpacts\n );\n\n // Toggle verbose result listing:\n logResultCards(result);\n\n // Toggle provenance logging (shows scoring history for top cards):\n logCardProvenance(result, 3);\n\n // Capture run for debug API\n try {\n const courseConfig = await this.course?.getCourseConfig().catch(() => undefined);\n const courseName = courseConfig?.name;\n // Pass the full post-filter sorted array; buildRunReport retains all\n // selected cards plus the top-N highest-scoring near-misses and\n // summarizes the discarded tail (see DISCARDED_KEEP_TOP). This keeps\n // showCard() useful for \"why didn't this rank?\" inspection without\n // pinning hundreds of low-score candidates' provenance per run.\n // `cards` is the post-filter, post-hints, sorted array.\n const report = buildRunReport(\n this.course?.getCourseID() || 'unknown',\n courseName,\n this.generator.name,\n generatorSummaries,\n generatedCount,\n filterImpacts,\n cards,\n result,\n context.userElo,\n hints?? undefined,\n scoredCards,\n regulators\n );\n const versions = {\n ...(this.strategyHash ? { strategies: this.strategyHash } : {}),\n ...(courseConfig?.contentVersion ? { content: courseConfig.contentVersion } : {}),\n };\n captureRun({ ...report, ...(Object.keys(versions).length ? { versions } : {}) });\n } catch (e) {\n logger.debug(`[Pipeline] Failed to capture debug run: ${e}`);\n }\n\n return { cards: result };\n }\n\n /**\n * Batch hydrate tags for all cards.\n *\n * Fetches tags for all cards in a single database query and attaches them\n * to the WeightedCard objects. Filters can then use card.tags instead of\n * making individual getAppliedTags() calls.\n *\n * Uses a persistent tag cache across pipeline runs — tags are static within\n * a session, so cards seen in a prior run (e.g. before a replan) don't\n * require a second DB query.\n *\n * @param cards - Cards to hydrate\n * @returns Cards with tags populated\n */\n private async hydrateTags(cards: WeightedCard[]): Promise<WeightedCard[]> {\n if (cards.length === 0) {\n return cards;\n }\n\n // Separate cards with cached tags from those needing a DB query\n const uncachedIds: string[] = [];\n for (const card of cards) {\n if (!this._tagCache.has(card.cardId)) {\n uncachedIds.push(card.cardId);\n }\n }\n\n // Only query the DB for cards not already in cache\n if (uncachedIds.length > 0) {\n const freshTags = await this.course!.getAppliedTagsBatch(uncachedIds);\n for (const [cardId, tags] of freshTags) {\n this._tagCache.set(cardId, tags);\n }\n }\n\n // Build the tagsByCard map from cache (for logging compatibility)\n const tagsByCard = new Map<string, string[]>();\n for (const card of cards) {\n tagsByCard.set(card.cardId, this._tagCache.get(card.cardId) ?? []);\n }\n\n // Toggle tag hydration logging:\n logTagHydration(cards, tagsByCard);\n\n return cards.map((card) => ({\n ...card,\n tags: this._tagCache.get(card.cardId) ?? [],\n }));\n }\n\n // ---------------------------------------------------------------------------\n // Ephemeral hints application\n // ---------------------------------------------------------------------------\n\n /**\n * Apply one-shot replan hints to the post-filter card set.\n *\n * Order of operations:\n * 1. Exclude (remove unwanted cards)\n * 2. Boost (multiply scores)\n * 3. Require (inject must-have cards from the full pre-filter pool)\n *\n * @param cards - Post-filter cards (score > 0)\n * @param hints - The ephemeral hints to apply\n * @param allCards - Full pre-filter card pool (for require injection)\n */\n private applyHints(\n cards: WeightedCard[],\n hints: ReplanHints,\n allCards: WeightedCard[]\n ): WeightedCard[] {\n const beforeCount = cards.length;\n\n // 1. Exclude\n if (hints.excludeCards?.length) {\n cards = cards.filter(\n (c) => !hints.excludeCards!.some((pat) => globMatch(c.cardId, pat))\n );\n }\n if (hints.excludeTags?.length) {\n cards = cards.filter(\n (c) => !hints.excludeTags!.some((pat) => cardMatchesTagPattern(c, pat))\n );\n }\n\n // 2. Boost\n if (hints.boostTags) {\n for (const [pattern, factor] of Object.entries(hints.boostTags)) {\n for (const card of cards) {\n if (cardMatchesTagPattern(card, pattern)) {\n card.score *= factor;\n card.provenance.push({\n strategy: 'ephemeralHint',\n strategyId: 'ephemeral-hint',\n strategyName: hints._label ? `Replan Hint (${hints._label})` : 'Replan Hint',\n action: 'boosted',\n score: card.score,\n reason: `boostTag ${pattern} ×${factor}`,\n });\n }\n }\n }\n }\n if (hints.boostCards) {\n for (const [pattern, factor] of Object.entries(hints.boostCards)) {\n for (const card of cards) {\n if (globMatch(card.cardId, pattern)) {\n card.score *= factor;\n card.provenance.push({\n strategy: 'ephemeralHint',\n strategyId: 'ephemeral-hint',\n strategyName: hints._label ? `Replan Hint (${hints._label})` : 'Replan Hint',\n action: 'boosted',\n score: card.score,\n reason: `boostCard ${pattern} ×${factor}`,\n });\n }\n }\n }\n }\n\n // 3. Require — ensure mandatory cards have floor score and are in the pool\n const cardIds = new Set(cards.map((c) => c.cardId));\n const cardMap = new Map(cards.map((c) => [c.cardId, c]));\n const hintLabel = hints._label ? `Replan Hint (${hints._label})` : 'Replan Hint';\n\n const applyRequirement = (card: WeightedCard, reason: string) => {\n const mandatoryScore = Number.POSITIVE_INFINITY;\n const existing = cardMap.get(card.cardId);\n\n if (existing) {\n // If already in the pool, upgrade to mandatory score if not already infinite\n if (existing.score < mandatoryScore) {\n existing.score = mandatoryScore;\n existing.provenance.push({\n strategy: 'ephemeralHint',\n strategyId: 'ephemeral-hint',\n strategyName: hintLabel,\n action: 'boosted',\n score: mandatoryScore,\n reason: `${reason} (upgrade to mandatory score)`,\n });\n }\n } else {\n // If missing, inject from the full pool\n cards.push({\n ...card,\n score: mandatoryScore,\n provenance: [\n ...card.provenance,\n {\n strategy: 'ephemeralHint',\n strategyId: 'ephemeral-hint',\n strategyName: hintLabel,\n action: 'boosted',\n score: mandatoryScore,\n reason,\n },\n ],\n });\n cardIds.add(card.cardId);\n cardMap.set(card.cardId, cards[cards.length - 1]);\n }\n };\n\n if (hints.requireCards?.length) {\n for (const pattern of hints.requireCards) {\n // First check candidates already in the pool\n for (const cardId of cardIds) {\n if (globMatch(cardId, pattern)) {\n applyRequirement(cardMap.get(cardId)!, `requireCard ${pattern}`);\n }\n }\n // Then check full pool for injection\n for (const card of allCards) {\n if (globMatch(card.cardId, pattern)) {\n applyRequirement(card, `requireCard ${pattern}`);\n }\n }\n }\n }\n if (hints.requireTags?.length) {\n for (const pattern of hints.requireTags) {\n // First check candidates already in the pool\n for (const cardId of cardIds) {\n const card = cardMap.get(cardId)!;\n if (cardMatchesTagPattern(card, pattern)) {\n applyRequirement(card, `requireTag ${pattern}`);\n }\n }\n // Then check full pool for injection\n for (const card of allCards) {\n if (cardMatchesTagPattern(card, pattern)) {\n applyRequirement(card, `requireTag ${pattern}`);\n }\n }\n }\n }\n\n logger.info(`[Pipeline] Hints applied: ${beforeCount} → ${cards.length} cards`);\n\n return cards;\n }\n\n /**\n * The regulator stage: measure each class's pressure and scale it.\n *\n * - Review mass: every due review's SRS urgency times the filters' net\n * effect on it.\n * - Intake: servable hours since a new card was presented, applied only to\n * eligible new cards (no gate penalized them). With none eligible, the\n * clock freezes.\n *\n * Mutates `cards` in place; returns the readings for the run report.\n */\n private async regulate(\n cards: WeightedCard[],\n generatedScores: ReadonlyMap<string, number>,\n gated: Set<string>\n ): Promise<RegulatorReading[]> {\n const config = DEFAULT_REGULATOR_CONFIG;\n const reviews = cards.filter((c) => c.reviewID);\n const newCards = cards.filter((c) => !c.reviewID);\n const eligibleNew = newCards.filter((c) => !gated.has(c.cardId));\n\n const mass = reviewMassReading(reviews, generatedScores, config.reviewMass);\n applyReading(reviews, mass);\n noteReviewPressure(this.course!.getCourseID(), {\n mass: mass.urgency,\n healthyMass: config.reviewMass.healthyMass,\n rate: config.reviewMass.rate,\n multiplier: mass.multiplier,\n });\n\n const now = Date.now();\n const clock = await this.loadIntakeClock(now);\n const stepped = stepIntakeClock(clock, now, eligibleNew.length);\n if (stepped !== clock) this.saveIntakeClock(stepped);\n const intake = intakeReading(\n stepped,\n now,\n { eligibleNew: eligibleNew.length, newCandidates: newCards.length },\n config.intake\n );\n applyReading(eligibleNew, intake);\n\n logger.info(\n `[Pipeline:regulators] review mass ${mass.urgency.toFixed(1)} over ${reviews.length} due → ` +\n `×${mass.multiplier.toFixed(2)}; intake ${intake.urgency.toFixed(1)}h, ` +\n `${eligibleNew.length}/${newCards.length} new eligible → ×${intake.multiplier.toFixed(2)}`\n );\n return [mass, intake];\n }\n\n /**\n * A card was presented. A new card's first presentation discharges the\n * intake valve: its clock restarts. Called by the SessionController.\n */\n notePresented(card: { cardId: string; courseId: string; status: string }): void {\n if (card.status !== 'new' || card.courseId !== this.course?.getCourseID()) return;\n this.saveIntakeClock(resetIntakeClock(Date.now()));\n }\n\n private async loadIntakeClock(nowMs: number): Promise<IntakeClockState> {\n if (this._intakeClock) return this._intakeClock;\n let stored: IntakeClockState | null = null;\n try {\n stored = await this.user!.getStrategyState<IntakeClockState>(\n this.course!.getCourseID(),\n INTAKE_CLOCK_KEY\n );\n } catch (e) {\n logger.warn(`[Pipeline:regulators] Could not read the intake clock: ${e}`);\n }\n if (stored) {\n this._intakeClock = stored;\n } else {\n // No clock yet: start it now.\n this.saveIntakeClock(resetIntakeClock(nowMs));\n }\n return this._intakeClock!;\n }\n\n private saveIntakeClock(state: IntakeClockState): void {\n this._intakeClock = state;\n const courseId = this.course!.getCourseID();\n this._intakeClockWrite = this._intakeClockWrite\n .then(() => this.user!.putStrategyState(courseId, INTAKE_CLOCK_KEY, state))\n .catch((e) => logger.warn(`[Pipeline:regulators] Could not save the intake clock: ${e}`));\n }\n\n /**\n * Build shared context for generator and filters.\n *\n * Called once per getWeightedCards() invocation.\n * Contains data that the generator and multiple filters might need.\n *\n * The context satisfies both GeneratorContext and FilterContext interfaces.\n */\n private async buildContext(): Promise<GeneratorContext & FilterContext> {\n let userElo = 1000; // Default ELO\n let userCourseElo: CourseElo | undefined;\n\n try {\n const courseReg = await this.user!.getCourseRegDoc(this.course!.getCourseID());\n userCourseElo = toCourseElo(courseReg.elo);\n userElo = userCourseElo.global.score;\n } catch (e) {\n logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);\n }\n\n // Reuse cached orchestration context if available (course config is stable\n // within a page load). This avoids a remote getCourseConfig() call on\n // subsequent pipeline runs (e.g. mid-session replans).\n if (!this._cachedOrchestration) {\n this._cachedOrchestration = await createOrchestrationContext(this.user!, this.course!);\n }\n const orchestration = this._cachedOrchestration;\n\n return {\n user: this.user!,\n course: this.course!,\n userElo,\n ...(userCourseElo ? { userCourseElo } : {}),\n orchestration,\n ...(this._sessionId ? { sessionId: this._sessionId } : {}),\n };\n }\n\n /**\n * Get the course ID for this pipeline.\n */\n getCourseID(): string {\n return this.course!.getCourseID();\n }\n\n /**\n * Get orchestration context for outcome recording.\n */\n async getOrchestrationContext(): Promise<OrchestrationContext> {\n return createOrchestrationContext(this.user!, this.course!);\n }\n\n /**\n * Get IDs of all strategies in this pipeline.\n * Used to record which strategies contributed to an outcome.\n */\n getStrategyIds(): string[] {\n const ids: string[] = [];\n\n const extractId = (obj: any): string | null => {\n // Check for strategyId property (ContentNavigator, WeightedFilter)\n if (obj.strategyId) return obj.strategyId;\n return null;\n };\n\n // Generator(s)\n const genId = extractId(this.generator);\n if (genId) ids.push(genId);\n\n // Inspect CompositeGenerator children (accessing private field via cast)\n if ((this.generator as any).generators && Array.isArray((this.generator as any).generators)) {\n (this.generator as any).generators.forEach((g: any) => {\n const subId = extractId(g);\n if (subId) ids.push(subId);\n });\n }\n\n // Filters\n for (const filter of this.filters) {\n const fId = extractId(filter);\n if (fId) ids.push(fId);\n }\n\n return [...new Set(ids)];\n }\n\n // ---------------------------------------------------------------------------\n // Tag ELO diagnostic\n // ---------------------------------------------------------------------------\n\n /**\n * Get the user's per-tag ELO data for specified tags (or all tags).\n * Useful for diagnosing why hierarchy gates are open/closed.\n */\n async getTagEloStatus(\n tagFilter?: string | string[]\n ): Promise<Record<string, { score: number; count: number }>> {\n const courseReg = await this.user!.getCourseRegDoc(this.course!.getCourseID());\n const courseElo = toCourseElo(courseReg.elo);\n\n const result: Record<string, { score: number; count: number }> = {};\n\n if (!tagFilter) {\n // Return all tags\n for (const [tag, data] of Object.entries(courseElo.tags)) {\n result[tag] = { score: data.score, count: data.count };\n }\n } else {\n const patterns = Array.isArray(tagFilter) ? tagFilter : [tagFilter];\n for (const pattern of patterns) {\n const regex = globToRegex(pattern);\n for (const [tag, data] of Object.entries(courseElo.tags)) {\n if (regex.test(tag)) {\n result[tag] = { score: data.score, count: data.count };\n }\n }\n }\n }\n\n return result;\n }\n\n // ---------------------------------------------------------------------------\n // Card-space diagnostic\n // ---------------------------------------------------------------------------\n\n /**\n * Commit-free forecast: score the user's full card space through the filter\n * chain and return the cards that are currently *reachable* (score >=\n * threshold), optionally nudged by caller-supplied hints and/or restricted\n * to cards the user hasn't seen yet.\n *\n * This is a GENERIC primitive — it returns scored, tag-hydrated cards and\n * stops there. It has no knowledge of any particular tag convention; callers\n * decide what the surviving cards mean (e.g. filter to their own \"intro\"\n * tag family). Nothing is written and no session is started.\n *\n * The optional `hints` are the \"out-of-band kick\": they run through the same\n * {@link applyHints} path a live replan uses, so the two semantics carry over —\n * - `boostTags`/`boostCards` reweight *within* gating (a gated score-0 card\n * stays out), and\n * - `requireTags`/`requireCards` inject from the full pre-filter pool,\n * *bypassing* gating (use when you want a card regardless of reachability).\n * Note `unseenOnly` is applied LAST, so it can drop a `require`d card that the\n * user has already seen — pass `unseenOnly: false` if that matters.\n *\n * Cost note: like {@link diagnoseCardSpace}, this scans every card through the\n * filters, so it's heavier than a normal replan. Intended for one-shot\n * out-of-band use (e.g. a session-end \"what's next\" snapshot), not the hot path.\n *\n * @param opts.hints Optional ephemeral hints to apply after the filter chain.\n * @param opts.unseenOnly Only return cards the user hasn't encountered (default true).\n * @param opts.threshold Min score to count as reachable (default 0.10).\n * @param opts.limit Optional cap on results (already sorted desc).\n */\n async forecast(opts?: {\n hints?: ReplanHints;\n unseenOnly?: boolean;\n threshold?: number;\n limit?: number;\n }): Promise<WeightedCard[]> {\n const threshold = opts?.threshold ?? 0.10;\n const unseenOnly = opts?.unseenOnly ?? true;\n\n const courseId = this.course!.getCourseID();\n const allCardIds = await this.course!.getAllCardIds();\n\n let cards: WeightedCard[] = allCardIds.map((cardId) => ({\n cardId,\n courseId,\n score: 1.0,\n provenance: [],\n }));\n\n cards = await this.hydrateTags(cards);\n // Snapshot the full pool before filtering, for require-injection in applyHints.\n const fullPool = cards.slice();\n\n const context = await this.buildContext();\n for (const filter of this.forecastFilters()) {\n cards = await filter.transform(cards, context);\n }\n\n if (opts?.hints) {\n cards = this.applyHints(cards, opts.hints, fullPool);\n }\n\n cards = cards.filter((c) => c.score >= threshold);\n\n if (unseenOnly) {\n let encountered: Set<string>;\n try {\n encountered = new Set(await this.user!.getSeenCards(courseId));\n } catch {\n encountered = new Set();\n }\n cards = cards.filter((c) => !encountered.has(c.cardId));\n }\n\n cards.sort((a, b) => b.score - a.score);\n return opts?.limit ? cards.slice(0, opts.limit) : cards;\n }\n\n /**\n * The filters a forecast or card-space scan applies. Those start every card at\n * 1.0 without a generator, so they skip `liveOnly` filters (ELO distance),\n * which only make sense against generator scores.\n */\n private forecastFilters(): CardFilter[] {\n return this.filters.filter((f) => !f.liveOnly);\n }\n\n /**\n * Scan every card in the course through the filter chain and report\n * how many are \"well indicated\" (score >= threshold) for the current user.\n *\n * Also reports how many well-indicated cards the user has NOT yet encountered.\n *\n * Exposed via `window.skuilder.pipeline.diagnoseCardSpace()`.\n */\n async diagnoseCardSpace(opts?: { threshold?: number }): Promise<CardSpaceDiagnosis> {\n const THRESHOLD = opts?.threshold ?? 0.10;\n const t0 = performance.now();\n\n // 1. Get all card IDs\n const allCardIds = await this.course!.getAllCardIds();\n\n // 2. Build dummy WeightedCards (score=1.0, no provenance)\n let cards: WeightedCard[] = allCardIds.map((cardId) => ({\n cardId,\n courseId: this.course!.getCourseID(),\n score: 1.0,\n provenance: [],\n }));\n\n // 3. Hydrate tags\n cards = await this.hydrateTags(cards);\n\n // 4. Run through filters\n const context = await this.buildContext();\n const filterBreakdown: Array<{ name: string; wellIndicated: number }> = [];\n\n // Track cumulative filter effects\n for (const filter of this.forecastFilters()) {\n cards = await filter.transform(cards, context);\n const wi = cards.filter((c) => c.score >= THRESHOLD).length;\n filterBreakdown.push({ name: filter.name, wellIndicated: wi });\n }\n\n // 5. Count well-indicated\n const wellIndicated = cards.filter((c) => c.score >= THRESHOLD);\n const wellIndicatedIds = new Set(wellIndicated.map((c) => c.cardId));\n\n // 6. Get encountered cards\n let encounteredIds: Set<string>;\n try {\n const courseId = this.course!.getCourseID();\n const seenCards = await this.user!.getSeenCards(courseId);\n encounteredIds = new Set(seenCards);\n } catch {\n encounteredIds = new Set();\n }\n\n const wellIndicatedNew = wellIndicated.filter((c) => !encounteredIds.has(c.cardId));\n\n // 7. Group by card type\n const byType = new Map<string, { total: number; wellIndicated: number; new: number }>();\n for (const card of cards) {\n const type = card.cardId.split('-')[1] || 'unknown'; // c-ws-... → ws, c-intro-... → intro, etc.\n if (!byType.has(type)) {\n byType.set(type, { total: 0, wellIndicated: 0, new: 0 });\n }\n const entry = byType.get(type)!;\n entry.total++;\n if (card.score >= THRESHOLD) {\n entry.wellIndicated++;\n if (!encounteredIds.has(card.cardId)) entry.new++;\n }\n }\n\n const elapsed = performance.now() - t0;\n\n const result: CardSpaceDiagnosis = {\n totalCards: allCardIds.length,\n threshold: THRESHOLD,\n wellIndicated: wellIndicatedIds.size,\n encountered: encounteredIds.size,\n wellIndicatedNew: wellIndicatedNew.length,\n byType: Object.fromEntries(byType),\n filterBreakdown,\n elapsedMs: Math.round(elapsed),\n };\n\n // Log to console\n logger.print(`[Pipeline:diagnose] Card space scan (${result.elapsedMs}ms):`);\n logger.print(`[Pipeline:diagnose] Total cards: ${result.totalCards}`);\n logger.print(`[Pipeline:diagnose] Well-indicated (score >= ${THRESHOLD}): ${result.wellIndicated}`);\n logger.print(`[Pipeline:diagnose] Encountered: ${result.encountered}`);\n logger.print(`[Pipeline:diagnose] Well-indicated & new: ${result.wellIndicatedNew}`);\n logger.print(`[Pipeline:diagnose] By type:`);\n for (const [type, counts] of byType) {\n logger.print(\n `[Pipeline:diagnose] ${type}: ${counts.wellIndicated}/${counts.total} well-indicated, ${counts.new} new`\n );\n }\n logger.print(`[Pipeline:diagnose] After each filter:`);\n for (const fb of filterBreakdown) {\n logger.print(`[Pipeline:diagnose] ${fb.name}: ${fb.wellIndicated} well-indicated`);\n }\n\n return result;\n }\n\n}\n\n/**\n * Diagnosis of the full card space for the current user.\n */\nexport interface CardSpaceDiagnosis {\n totalCards: number;\n threshold: number;\n wellIndicated: number;\n encountered: number;\n wellIndicatedNew: number;\n byType: Record<string, { total: number; wellIndicated: number; new: number }>;\n filterBreakdown: Array<{ name: string; wellIndicated: number }>;\n elapsedMs: number;\n}\n"],"mappings":";;;;;;;;;;;;;;;AA+CA,SAAS,YAAY,SAAyB;CAE5C,MAAM,gBADU,QAAQ,QAAQ,sBAAsB,OAAO,CAC/B,QAAQ,OAAO,KAAK;AAClD,QAAO,IAAI,OAAO,IAAI,cAAc,GAAG;;;AAIzC,SAAS,UAAU,OAAe,SAA0B;AAC1D,KAAI,CAAC,QAAQ,SAAS,IAAI,CAAE,QAAO,UAAU;AAC7C,QAAO,YAAY,QAAQ,CAAC,KAAK,MAAM;;;AAIzC,SAAS,sBAAsB,MAAoB,SAA0B;AAC3E,SAAQ,KAAK,QAAQ,EAAE,EAAE,MAAM,QAAQ,UAAU,KAAK,QAAQ,CAAC;;AAGjE,SAAgB,WAAW,UAA0E;CACnG,MAAM,UAAU,SAAS,QAAQ,MAAwB,MAAM,QAAQ,MAAM,KAAA,EAAU;AACvF,KAAI,QAAQ,WAAW,EAAG,QA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,OAAO,aAAa;AACvE,SAAO,MAAM,kDAAkD,UAAU,KAAK,OAAO,gBAAgB;AACrG,SAAO,MAAM,sCAAsC,OAAO,cAAc;AACxE,SAAO,MAAM,+CAA+C,OAAO,mBAAmB;AACtF,SAAO,MAAM,iCAAiC;AAC9C,OAAK,MAAM,CAAC,MAAM,WAAW,OAC3B,QAAO,MACL,2BAA2B,KAAK,IAAI,OAAO,cAAc,GAAG,OAAO,MAAM,mBAAmB,OAAO,IAAI,MACxG;AAEH,SAAO,MAAM,2CAA2C;AACxD,OAAK,MAAM,MAAM,gBACf,QAAO,MAAM,2BAA2B,GAAG,KAAK,IAAI,GAAG,cAAc,iBAAiB;AAGxF,SAAO"}
@@ -1,7 +1,7 @@
1
1
  import "../../../_virtual/_rolldown/runtime.mjs";
2
2
  import { logger } from "../../../util/logger.mjs";
3
3
  import { ContentNavigator } from "../index.mjs";
4
- import { COUNT_ONLY_SCORE, isCountOnlyTag } from "@vue-skuilder/common";
4
+ import { COUNT_ONLY_SCORE, isCountOnlyTag, tagRole } from "@vue-skuilder/common";
5
5
  //#region src/core/navigators/filters/eloDistance.ts
6
6
  /**
7
7
  * The default curve. The default strategy doc carries it as its config, so
@@ -19,6 +19,10 @@ const DEFAULT_ELO_DISTANCE_CONFIG = {
19
19
  * tag evidence leans on global ELO; well-practised tags dominate.
20
20
  */
21
21
  const TAG_CONFIDENCE_HALF = 10;
22
+ /** Whether the card is an intro: any `intro`-role tag. Its ELO is a placeholder. */
23
+ function isIntroCard(card) {
24
+ return (card.tags ?? []).some((t) => tagRole(t) === "intro");
25
+ }
22
26
  /** Fallback card ELO when a card has none recorded. */
23
27
  const DEFAULT_CARD_ELO = 1e3;
24
28
  function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
@@ -152,7 +156,7 @@ async function applyEloDistance(cards, context, config, source) {
152
156
  const { course, userElo, userCourseElo } = context;
153
157
  const { halfLife, minMultiplier, maxMultiplier } = config;
154
158
  const tagAware = (config.tagAware || multiDimElo) && userCourseElo !== void 0;
155
- const missing = cards.filter((c) => tagAware || c.cardElo === void 0).map((c) => c.cardId);
159
+ const missing = cards.filter((c) => !isIntroCard(c) && (tagAware || c.cardElo === void 0)).map((c) => c.cardId);
156
160
  const fetched = /* @__PURE__ */ new Map();
157
161
  if (missing.length > 0) {
158
162
  const elos = await course.getCardEloData(missing);
@@ -161,6 +165,17 @@ async function applyEloDistance(cards, context, config, source) {
161
165
  });
162
166
  }
163
167
  return cards.map((card) => {
168
+ if (isIntroCard(card)) return {
169
+ ...card,
170
+ provenance: [...card.provenance, {
171
+ strategy: "eloDistance",
172
+ strategyName: source.name,
173
+ strategyId: source.strategyId,
174
+ action: "passed",
175
+ score: card.score,
176
+ reason: "intro card: ELO is a placeholder, distance not applied → 1.00x"
177
+ }]
178
+ };
164
179
  const full = fetched.get(card.cardId);
165
180
  const cardElo = full?.global?.score ?? card.cardElo ?? DEFAULT_CARD_ELO;
166
181
  let distance = Math.abs(cardElo - userElo);
@@ -1 +1 @@
1
- {"version":3,"file":"eloDistance.mjs","names":[],"sources":["../../../../src/core/navigators/filters/eloDistance.ts"],"sourcesContent":["import type { CourseDBInterface } from '../../interfaces/courseDB';\nimport type { UserDBInterface } from '../../interfaces/userDB';\nimport type { ContentNavigationStrategyData } from '../../types/contentNavigationStrategy';\nimport { ContentNavigator } from '../index';\nimport type { WeightedCard } from '../index';\nimport type { GeneratorResult } from '../generators/types';\nimport type { CardFilter, FilterContext, FilterKind } from './types';\nimport { COUNT_ONLY_SCORE, isCountOnlyTag, type CourseElo } from '@vue-skuilder/common';\nimport { logger } from '../../../util/logger';\n\n// ============================================================================\n// ELO DISTANCE FILTER\n// ============================================================================\n//\n// Scales every candidate by how close its ELO is to the learner's, on a smooth\n// Gaussian (no discontinuities, never zero).\n//\n// The one place ELO distance counts. Generators retrieve (the ELO generator\n// pulls a window of cards near the learner's ELO) and score only on what's\n// specific to their source; a signal that applies to every card lives in one\n// heap-wide filter, so new cards and reviews are weighed on the same terms:\n// - reviews the learner has moved beyond fade, and may never surface over\n// higher-priority work;\n// - new cards far from the learner's level rank low (this used to live in the\n// ELO generator's own score, which double-counted alongside this filter).\n//\n// Tag-aware (opt-in, experimental): a card's difficulty for this learner is\n// read on the skills they share, not only on global ELO. Card and learner keep\n// paired ratings per tag (each graded response adjusts both), so a tag's gap\n// (card − learner) is as meaningful as the global one, and often more: a card\n// can sit at the learner's global level while testing their weakest skill.\n// See tagAwareGap for the combination. Global distance is the default; a course\n// opts in with `tagAware`, a browser with `window.skuilder.multiDimElo = true`\n// (see the toggle below), for side-by-side testing.\n//\n// A `signal`, not a gate: it expresses preference, not readiness. `liveOnly`:\n// forecasts and card-space scans start every card at 1.0 without a generator,\n// and never applied ELO distance, so they skip it.\n//\n// The assembler adds this filter (as \"ELO Distance (default)\") to every\n// pipeline whose strategy docs don't declare one. A course tunes it by\n// declaring its own `eloDistance` strategy doc with an EloDistanceConfig.\n//\n// ============================================================================\n\n/**\n * Configuration for the ELO distance curve:\n * `minMultiplier + (maxMultiplier − minMultiplier) · exp(−(distance / halfLife)²)`.\n */\nexport interface EloDistanceConfig {\n /**\n * The Gaussian's scale in ELO points (despite the name, not a half-life).\n * Default 300: distance 250 → ~0.5, as the ELO generator scored new cards.\n *\n * - distance 0: maxMultiplier\n * - distance = halfLife: ~0.4 (with the default floor)\n * - distance = 2 · halfLife: ~0.07\n */\n halfLife?: number;\n\n /**\n * Floor, so far-off cards keep a nonzero score (the pipeline drops zero\n * scores before hints, and a hint must be able to lift any card). Default 0.05.\n */\n minMultiplier?: number;\n\n /** Ceiling. Usually 1.0 (no boost for close cards). Default 1.0. */\n maxMultiplier?: number;\n\n /**\n * Measure distance on the tags the card and learner share (see\n * tagAwareGap), falling back to global ELO where they share none.\n * Default false. `window.skuilder.multiDimElo` turns it on in one browser.\n */\n tagAware?: boolean;\n\n /**\n * A learner's tag rating counts once it rests on at least this many graded\n * responses. Count-only (exposure) tags never count. Default 3.\n */\n minTagCount?: number;\n}\n\n/**\n * The default curve. The default strategy doc carries it as its config, so\n * the admin pipeline view shows what runs.\n */\nexport const DEFAULT_ELO_DISTANCE_CONFIG: Required<EloDistanceConfig> = {\n halfLife: 300,\n minMultiplier: 0.05,\n maxMultiplier: 1.0,\n tagAware: false,\n minTagCount: 3,\n};\n\n/**\n * Graded responses at which a tag's gap carries half its full weight. Thin\n * tag evidence leans on global ELO; well-practised tags dominate.\n */\nconst TAG_CONFIDENCE_HALF = 10;\n\n/** Fallback card ELO when a card has none recorded. */\nconst DEFAULT_CARD_ELO = 1000;\n\nfunction computeMultiplier(\n distance: number,\n halfLife: number,\n minMultiplier: number,\n maxMultiplier: number\n): number {\n const normalizedDistance = distance / halfLife;\n const decay = Math.exp(-(normalizedDistance * normalizedDistance));\n return minMultiplier + (maxMultiplier - minMultiplier) * decay;\n}\n\nfunction resolveConfig(config?: EloDistanceConfig): Required<EloDistanceConfig> {\n return { ...DEFAULT_ELO_DISTANCE_CONFIG, ...config };\n}\n\n// ----------------------------------------------------------------------------\n// Live toggle: window.skuilder.multiDimElo\n// ----------------------------------------------------------------------------\n//\n// `window.skuilder.multiDimElo = true` turns tag-aware distance on in this\n// browser, whatever the strategy config says; `false` returns it to the\n// config. Read on every run, so it takes effect at the next replan. Kept in\n// localStorage so it survives reloads across a testing stretch. Runs it shapes\n// say so in every card's ELO distance reason (\"tag-aware\").\n\nconst MULTI_DIM_ELO_KEY = 'skuilder:multiDimElo';\n\nlet multiDimElo = readMultiDimElo();\n\nfunction readMultiDimElo(): boolean {\n try {\n return typeof localStorage !== 'undefined' && localStorage.getItem(MULTI_DIM_ELO_KEY) === 'true';\n } catch {\n return false;\n }\n}\n\n/**\n * Mount the toggle on window.skuilder.multiDimElo.\n */\nexport function mountMultiDimEloToggle(): void {\n if (typeof window === 'undefined') return;\n\n const win = window as any;\n win.skuilder = win.skuilder || {};\n Object.defineProperty(win.skuilder, 'multiDimElo', {\n configurable: true,\n enumerable: true,\n get: () => multiDimElo,\n set: (on: unknown) => {\n multiDimElo = on === true;\n try {\n if (multiDimElo) localStorage.setItem(MULTI_DIM_ELO_KEY, 'true');\n else localStorage.removeItem(MULTI_DIM_ELO_KEY);\n } catch (e) {\n logger.warn(`[EloDistance] multiDimElo not persisted (localStorage unavailable): ${e}`);\n }\n logger.print(\n `[EloDistance] multiDimElo ${multiDimElo ? 'on: tag-aware' : 'off: per strategy config'}` +\n ' ELO distance from the next replan'\n );\n },\n });\n}\n\n// Auto-mount when module is loaded\nmountMultiDimEloToggle();\n\n/** One shared tag's contribution to a card's tag-aware gap. */\ninterface TagGap {\n tag: string;\n /** Card's tag rating minus the learner's: positive = harder than their level. */\n gap: number;\n weight: number;\n}\n\n/**\n * The card's difficulty for this learner, in ELO points (card − learner),\n * read on the tags they share.\n *\n * - Shared tags: the card's tags on which the learner has a real rating\n * (not a bookkeeping role, nor the count-only sentinel) resting on at least\n * `minTagCount` graded responses. A card with no rating of its own on a tag\n * uses its global, as the ELO update does when it first grades that tag.\n * - Each tag's gap is weighted by the learner's evidence on it,\n * n / (n + TAG_CONFIDENCE_HALF).\n * - The weighted mean of the tag gaps is blended with the global gap by the\n * total evidence W: λ = W / (W + 1). One thin tag barely moves it; several\n * practised tags dominate it.\n *\n * OPEN (draft, 2026-10-01). Shipped on by default in 0.2.29 by accident (it\n * rode along in the version-bump commit); off by default since, and live only\n * behind the toggle. On one LP learner's 09-30 dump the effect was modest: every touched card shared a rated tag\n * (median 4); mean multiplier ×0.70 → ×0.75 over 352 touched cards, ×0.84 →\n * ×0.88 over 42 due reviews. The biggest movers were old who-said-that cards:\n * ~400 below the learner globally, ~280 below on their own skills.\n *\n * 1. Compensatory or conjunctive. This averages: a weak skill is offset by\n * strong ones. For spelling a word, which needs every grapheme, the hardest\n * shared skill arguably sets the difficulty: take the largest gap instead.\n * The main design question.\n * 2. Which tags count. Broad tags (`concept:match:simple`, `ui:*`) sit on most\n * cards and act like a second global rating. The framework may want the\n * course to say which tags are skills (cf. LP's diagnostics interpreter\n * `isSkillTag`), e.g. as tag patterns in the strategy config.\n * The admin ELO viewer (in progress, 2026-10) answers the same question for\n * display with its own tag batches (role × namespace). Before tag-aware goes\n * on by default, make that one predicate:\n * - a serializable selector (roles, prefix patterns), beside `tagRoles.ts`\n * in common, so a strategy doc can carry it;\n * - an `EloDistanceConfig` field for it, read by `tagAwareGap`;\n * - `tagAwareGap` moved to a pure module (this file imports `core`, which\n * the diagnostics entry can't), so the viewer can show what the filter\n * would compute;\n * - the viewer's default batch read from the course's eloDistance config.\n * 3. New cards matter most, and that dump couldn't show them. An unseen\n * card's tag ratings fall back to its global, so for new cards this reads\n * \"card global vs the learner's rating on that skill\". Measuring it needs a\n * `--course all` dump.\n * 4. Cost. Tag-aware fetches full ratings for every candidate (~500 card docs\n * per run); global-only fetches only reviews'.\n * 5. Retrieval stays global. The ELO generator's window is the cards nearest\n * the learner's global ELO, so a card that's well matched on its skills but\n * far off globally may never be retrieved.\n * 6. Target. Distance 0 means ~50% expected success. Early learners may do\n * better aiming higher: a shift of the curve's centre, independent of this.\n */\nexport function tagAwareGap(\n cardTags: readonly string[],\n cardElo: CourseElo,\n userElo: CourseElo,\n minTagCount: number\n): { gap: number; globalGap: number; tags: TagGap[] } {\n const globalGap = cardElo.global.score - userElo.global.score;\n const tags: TagGap[] = [];\n for (const tag of cardTags) {\n const user = userElo.tags[tag];\n if (isCountOnlyTag(tag) || !user || user.score === COUNT_ONLY_SCORE || user.count < minTagCount) {\n continue;\n }\n const card = cardElo.tags[tag]?.score ?? cardElo.global.score;\n tags.push({\n tag,\n gap: card - user.score,\n weight: user.count / (user.count + TAG_CONFIDENCE_HALF),\n });\n }\n if (tags.length === 0) return { gap: globalGap, globalGap, tags };\n\n const total = tags.reduce((w, t) => w + t.weight, 0);\n const tagGap = tags.reduce((g, t) => g + t.weight * t.gap, 0) / total;\n const lambda = total / (total + 1);\n return { gap: lambda * tagGap + (1 - lambda) * globalGap, globalGap, tags };\n}\n\nfunction tagReason(tags: TagGap[], globalGap: number): string {\n const shown = [...tags]\n .sort((a, b) => Math.abs(b.gap) * b.weight - Math.abs(a.gap) * a.weight)\n .slice(0, 3)\n .map((t) => `${t.tag} ${t.gap >= 0 ? '+' : ''}${Math.round(t.gap)}`)\n .join(', ');\n const more = tags.length > 3 ? `, +${tags.length - 3} more` : '';\n return ` on ${tags.length} shared tag(s) [${shown}${more}] (global ${globalGap >= 0 ? '+' : ''}${Math.round(globalGap)})`;\n}\n\nasync function applyEloDistance(\n cards: WeightedCard[],\n context: FilterContext,\n config: Required<EloDistanceConfig>,\n source: { name: string; strategyId: string }\n): Promise<WeightedCard[]> {\n const { course, userElo, userCourseElo } = context;\n const { halfLife, minMultiplier, maxMultiplier } = config;\n const tagAware = (config.tagAware || multiDimElo) && userCourseElo !== undefined;\n\n // Tag-aware needs every card's full ratings; otherwise only the ELO of cards\n // that don't carry it (reviews). One batch either way.\n const missing = cards.filter((c) => tagAware || c.cardElo === undefined).map((c) => c.cardId);\n const fetched = new Map<string, CourseElo>();\n if (missing.length > 0) {\n const elos = await course.getCardEloData(missing);\n missing.forEach((id, i) => {\n if (elos[i]) fetched.set(id, elos[i]);\n });\n }\n\n return cards.map((card) => {\n const full = fetched.get(card.cardId);\n const cardElo = full?.global?.score ?? card.cardElo ?? DEFAULT_CARD_ELO;\n\n let distance = Math.abs(cardElo - userElo);\n let how = '';\n if (tagAware) {\n const t = full ? tagAwareGap(card.tags ?? [], full, userCourseElo!, config.minTagCount) : undefined;\n if (t) distance = Math.abs(t.gap);\n how = t?.tags.length\n ? `, tag-aware${tagReason(t.tags, t.globalGap)}`\n : ', tag-aware: global (no shared tags)';\n }\n\n const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);\n const newScore = card.score * multiplier;\n const action = multiplier < maxMultiplier - 0.01 ? 'penalized' : 'passed';\n\n return {\n ...card,\n cardElo,\n score: newScore,\n provenance: [\n ...card.provenance,\n {\n strategy: 'eloDistance',\n strategyName: source.name,\n strategyId: source.strategyId,\n action,\n score: newScore,\n reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)})${how} → ${multiplier.toFixed(2)}x`,\n },\n ],\n };\n });\n}\n\n/**\n * Create an ELO distance filter outside the strategy-doc path.\n *\n * @param config - Optional configuration for the curve\n */\nexport function createEloDistanceFilter(config?: EloDistanceConfig): CardFilter {\n const resolved = resolveConfig(config);\n const source = { name: 'ELO Distance Filter', strategyId: 'ELO_DISTANCE_FILTER' };\n return {\n name: source.name,\n kind: 'signal',\n liveOnly: true,\n transform: (cards, context) => applyEloDistance(cards, context, resolved, source),\n };\n}\n\n/**\n * The ELO distance filter as a strategy-doc navigator (`implementingClass:\n * 'eloDistance'`, serializedData: an EloDistanceConfig as JSON, or empty).\n */\nexport default class EloDistanceFilter extends ContentNavigator implements CardFilter {\n name: string;\n /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */\n static readonly kind: FilterKind = 'signal';\n readonly kind = EloDistanceFilter.kind;\n readonly liveOnly = true;\n private config: Required<EloDistanceConfig>;\n\n constructor(\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n ) {\n super(user, course, strategyData);\n this.name = strategyData.name || 'ELO Distance';\n let parsed: EloDistanceConfig | undefined;\n try {\n parsed = strategyData.serializedData ? JSON.parse(strategyData.serializedData) : undefined;\n } catch {\n parsed = undefined;\n }\n this.config = resolveConfig(parsed);\n }\n\n transform(cards: WeightedCard[], context: FilterContext): Promise<WeightedCard[]> {\n return applyEloDistance(cards, context, this.config, {\n name: this.name,\n strategyId: this.strategyId || 'NAVIGATION_STRATEGY-eloDistance-default',\n });\n }\n\n async getWeightedCards(_limit: number): Promise<GeneratorResult> {\n throw new Error(\n 'EloDistanceFilter is a filter and should not be used as a generator. ' +\n 'Use Pipeline with a generator and this filter via transform().'\n );\n }\n}\n"],"mappings":";;;;;;;;;AAuFA,MAAa,8BAA2D;CACtE,UAAU;CACV,eAAe;CACf,eAAe;CACf,UAAU;CACV,aAAa;C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AY,iBAAiB,OAAO,SAAS,UAAU,OAAO;EAClF;;;;;;AAOH,IAAqB,oBAArB,MAAqB,0BAA0B,iBAAuC;CACpF;;CAEA,OAAgB,OAAmB;CACnC,OAAgB,kBAAkB;CAClC,WAAoB;CACpB;CAEA,YACE,MACA,QACA,cACA;AACA,QAAM,MAAM,QAAQ,aAAa;AACjC,OAAK,OAAO,aAAa,QAAQ;EACjC,IAAI;AACJ,MAAI;AACF,YAAS,aAAa,iBAAiB,KAAK,MAAM,aAAa,eAAe,GAAG,KAAA;UAC3E;AACN,YAAS,KAAA;;AAEX,OAAK,SAAS,cAAc,OAAO;;CAGrC,UAAU,OAAuB,SAAiD;AAChF,SAAO,iBAAiB,OAAO,SAAS,KAAK,QAAQ;GACnD,MAAM,KAAK;GACX,YAAY,KAAK,cAAc;GAChC,CAAC;;CAGJ,MAAM,iBAAiB,QAA0C;AAC/D,QAAM,IAAI,MACR,sIAED"}
1
+ {"version":3,"file":"eloDistance.mjs","names":[],"sources":["../../../../src/core/navigators/filters/eloDistance.ts"],"sourcesContent":["import type { CourseDBInterface } from '../../interfaces/courseDB';\nimport type { UserDBInterface } from '../../interfaces/userDB';\nimport type { ContentNavigationStrategyData } from '../../types/contentNavigationStrategy';\nimport { ContentNavigator } from '../index';\nimport type { WeightedCard } from '../index';\nimport type { GeneratorResult } from '../generators/types';\nimport type { CardFilter, FilterContext, FilterKind } from './types';\nimport { COUNT_ONLY_SCORE, isCountOnlyTag, tagRole, type CourseElo } from '@vue-skuilder/common';\nimport { logger } from '../../../util/logger';\n\n// ============================================================================\n// ELO DISTANCE FILTER\n// ============================================================================\n//\n// Scales every candidate by how close its ELO is to the learner's, on a smooth\n// Gaussian (no discontinuities, never zero).\n//\n// The one place ELO distance counts. Generators retrieve (the ELO generator\n// pulls a window of cards near the learner's ELO) and score only on what's\n// specific to their source; a signal that applies to every card lives in one\n// heap-wide filter, so new cards and reviews are weighed on the same terms:\n// - reviews the learner has moved beyond fade, and may never surface over\n// higher-priority work;\n// - new cards far from the learner's level rank low (this used to live in the\n// ELO generator's own score, which double-counted alongside this filter).\n//\n// Tag-aware (opt-in, experimental): a card's difficulty for this learner is\n// read on the skills they share, not only on global ELO. Card and learner keep\n// paired ratings per tag (each graded response adjusts both), so a tag's gap\n// (card − learner) is as meaningful as the global one, and often more: a card\n// can sit at the learner's global level while testing their weakest skill.\n// See tagAwareGap for the combination. Global distance is the default; a course\n// opts in with `tagAware`, a browser with `window.skuilder.multiDimElo = true`\n// (see the toggle below), for side-by-side testing.\n//\n// Intro cards pass through untouched. They carry an `intro`-role tag, grade\n// nothing, and their ELO is a placeholder, so a distance on it means nothing.\n// Penalising them starved established learners of every intro (an LP learner\n// at ~1600 saw sight-word intros at 1000 scored ×0.05 for six weeks).\n//\n// A `signal`, not a gate: it expresses preference, not readiness. `liveOnly`:\n// forecasts and card-space scans start every card at 1.0 without a generator,\n// and never applied ELO distance, so they skip it.\n//\n// The assembler adds this filter (as \"ELO Distance (default)\") to every\n// pipeline whose strategy docs don't declare one. A course tunes it by\n// declaring its own `eloDistance` strategy doc with an EloDistanceConfig.\n//\n// ============================================================================\n\n/**\n * Configuration for the ELO distance curve:\n * `minMultiplier + (maxMultiplier − minMultiplier) · exp(−(distance / halfLife)²)`.\n */\nexport interface EloDistanceConfig {\n /**\n * The Gaussian's scale in ELO points (despite the name, not a half-life).\n * Default 300: distance 250 → ~0.5, as the ELO generator scored new cards.\n *\n * - distance 0: maxMultiplier\n * - distance = halfLife: ~0.4 (with the default floor)\n * - distance = 2 · halfLife: ~0.07\n */\n halfLife?: number;\n\n /**\n * Floor, so far-off cards keep a nonzero score (the pipeline drops zero\n * scores before hints, and a hint must be able to lift any card). Default 0.05.\n */\n minMultiplier?: number;\n\n /** Ceiling. Usually 1.0 (no boost for close cards). Default 1.0. */\n maxMultiplier?: number;\n\n /**\n * Measure distance on the tags the card and learner share (see\n * tagAwareGap), falling back to global ELO where they share none.\n * Default false. `window.skuilder.multiDimElo` turns it on in one browser.\n */\n tagAware?: boolean;\n\n /**\n * A learner's tag rating counts once it rests on at least this many graded\n * responses. Count-only (exposure) tags never count. Default 3.\n */\n minTagCount?: number;\n}\n\n/**\n * The default curve. The default strategy doc carries it as its config, so\n * the admin pipeline view shows what runs.\n */\nexport const DEFAULT_ELO_DISTANCE_CONFIG: Required<EloDistanceConfig> = {\n halfLife: 300,\n minMultiplier: 0.05,\n maxMultiplier: 1.0,\n tagAware: false,\n minTagCount: 3,\n};\n\n/**\n * Graded responses at which a tag's gap carries half its full weight. Thin\n * tag evidence leans on global ELO; well-practised tags dominate.\n */\nconst TAG_CONFIDENCE_HALF = 10;\n\n/** Whether the card is an intro: any `intro`-role tag. Its ELO is a placeholder. */\nfunction isIntroCard(card: WeightedCard): boolean {\n return (card.tags ?? []).some((t) => tagRole(t) === 'intro');\n}\n\n/** Fallback card ELO when a card has none recorded. */\nconst DEFAULT_CARD_ELO = 1000;\n\nfunction computeMultiplier(\n distance: number,\n halfLife: number,\n minMultiplier: number,\n maxMultiplier: number\n): number {\n const normalizedDistance = distance / halfLife;\n const decay = Math.exp(-(normalizedDistance * normalizedDistance));\n return minMultiplier + (maxMultiplier - minMultiplier) * decay;\n}\n\nfunction resolveConfig(config?: EloDistanceConfig): Required<EloDistanceConfig> {\n return { ...DEFAULT_ELO_DISTANCE_CONFIG, ...config };\n}\n\n// ----------------------------------------------------------------------------\n// Live toggle: window.skuilder.multiDimElo\n// ----------------------------------------------------------------------------\n//\n// `window.skuilder.multiDimElo = true` turns tag-aware distance on in this\n// browser, whatever the strategy config says; `false` returns it to the\n// config. Read on every run, so it takes effect at the next replan. Kept in\n// localStorage so it survives reloads across a testing stretch. Runs it shapes\n// say so in every card's ELO distance reason (\"tag-aware\").\n\nconst MULTI_DIM_ELO_KEY = 'skuilder:multiDimElo';\n\nlet multiDimElo = readMultiDimElo();\n\nfunction readMultiDimElo(): boolean {\n try {\n return typeof localStorage !== 'undefined' && localStorage.getItem(MULTI_DIM_ELO_KEY) === 'true';\n } catch {\n return false;\n }\n}\n\n/**\n * Mount the toggle on window.skuilder.multiDimElo.\n */\nexport function mountMultiDimEloToggle(): void {\n if (typeof window === 'undefined') return;\n\n const win = window as any;\n win.skuilder = win.skuilder || {};\n Object.defineProperty(win.skuilder, 'multiDimElo', {\n configurable: true,\n enumerable: true,\n get: () => multiDimElo,\n set: (on: unknown) => {\n multiDimElo = on === true;\n try {\n if (multiDimElo) localStorage.setItem(MULTI_DIM_ELO_KEY, 'true');\n else localStorage.removeItem(MULTI_DIM_ELO_KEY);\n } catch (e) {\n logger.warn(`[EloDistance] multiDimElo not persisted (localStorage unavailable): ${e}`);\n }\n logger.print(\n `[EloDistance] multiDimElo ${multiDimElo ? 'on: tag-aware' : 'off: per strategy config'}` +\n ' ELO distance from the next replan'\n );\n },\n });\n}\n\n// Auto-mount when module is loaded\nmountMultiDimEloToggle();\n\n/** One shared tag's contribution to a card's tag-aware gap. */\ninterface TagGap {\n tag: string;\n /** Card's tag rating minus the learner's: positive = harder than their level. */\n gap: number;\n weight: number;\n}\n\n/**\n * The card's difficulty for this learner, in ELO points (card − learner),\n * read on the tags they share.\n *\n * - Shared tags: the card's tags on which the learner has a real rating\n * (not a bookkeeping role, nor the count-only sentinel) resting on at least\n * `minTagCount` graded responses. A card with no rating of its own on a tag\n * uses its global, as the ELO update does when it first grades that tag.\n * - Each tag's gap is weighted by the learner's evidence on it,\n * n / (n + TAG_CONFIDENCE_HALF).\n * - The weighted mean of the tag gaps is blended with the global gap by the\n * total evidence W: λ = W / (W + 1). One thin tag barely moves it; several\n * practised tags dominate it.\n *\n * OPEN (draft, 2026-10-01). Shipped on by default in 0.2.29 by accident (it\n * rode along in the version-bump commit); off by default since, and live only\n * behind the toggle. On one LP learner's 09-30 dump the effect was modest: every touched card shared a rated tag\n * (median 4); mean multiplier ×0.70 → ×0.75 over 352 touched cards, ×0.84 →\n * ×0.88 over 42 due reviews. The biggest movers were old who-said-that cards:\n * ~400 below the learner globally, ~280 below on their own skills.\n *\n * 1. Compensatory or conjunctive. This averages: a weak skill is offset by\n * strong ones. For spelling a word, which needs every grapheme, the hardest\n * shared skill arguably sets the difficulty: take the largest gap instead.\n * The main design question.\n * 2. Which tags count. Broad tags (`concept:match:simple`, `ui:*`) sit on most\n * cards and act like a second global rating. The framework may want the\n * course to say which tags are skills (cf. LP's diagnostics interpreter\n * `isSkillTag`), e.g. as tag patterns in the strategy config.\n * The admin ELO viewer (in progress, 2026-10) answers the same question for\n * display with its own tag batches (role × namespace). Before tag-aware goes\n * on by default, make that one predicate:\n * - a serializable selector (roles, prefix patterns), beside `tagRoles.ts`\n * in common, so a strategy doc can carry it;\n * - an `EloDistanceConfig` field for it, read by `tagAwareGap`;\n * - `tagAwareGap` moved to a pure module (this file imports `core`, which\n * the diagnostics entry can't), so the viewer can show what the filter\n * would compute;\n * - the viewer's default batch read from the course's eloDistance config.\n * 3. New cards matter most, and that dump couldn't show them. An unseen\n * card's tag ratings fall back to its global, so for new cards this reads\n * \"card global vs the learner's rating on that skill\". Measuring it needs a\n * `--course all` dump.\n * 4. Cost. Tag-aware fetches full ratings for every candidate (~500 card docs\n * per run); global-only fetches only reviews'.\n * 5. Retrieval stays global. The ELO generator's window is the cards nearest\n * the learner's global ELO, so a card that's well matched on its skills but\n * far off globally may never be retrieved.\n * 6. Target. Distance 0 means ~50% expected success. Early learners may do\n * better aiming higher: a shift of the curve's centre, independent of this.\n */\nexport function tagAwareGap(\n cardTags: readonly string[],\n cardElo: CourseElo,\n userElo: CourseElo,\n minTagCount: number\n): { gap: number; globalGap: number; tags: TagGap[] } {\n const globalGap = cardElo.global.score - userElo.global.score;\n const tags: TagGap[] = [];\n for (const tag of cardTags) {\n const user = userElo.tags[tag];\n if (isCountOnlyTag(tag) || !user || user.score === COUNT_ONLY_SCORE || user.count < minTagCount) {\n continue;\n }\n const card = cardElo.tags[tag]?.score ?? cardElo.global.score;\n tags.push({\n tag,\n gap: card - user.score,\n weight: user.count / (user.count + TAG_CONFIDENCE_HALF),\n });\n }\n if (tags.length === 0) return { gap: globalGap, globalGap, tags };\n\n const total = tags.reduce((w, t) => w + t.weight, 0);\n const tagGap = tags.reduce((g, t) => g + t.weight * t.gap, 0) / total;\n const lambda = total / (total + 1);\n return { gap: lambda * tagGap + (1 - lambda) * globalGap, globalGap, tags };\n}\n\nfunction tagReason(tags: TagGap[], globalGap: number): string {\n const shown = [...tags]\n .sort((a, b) => Math.abs(b.gap) * b.weight - Math.abs(a.gap) * a.weight)\n .slice(0, 3)\n .map((t) => `${t.tag} ${t.gap >= 0 ? '+' : ''}${Math.round(t.gap)}`)\n .join(', ');\n const more = tags.length > 3 ? `, +${tags.length - 3} more` : '';\n return ` on ${tags.length} shared tag(s) [${shown}${more}] (global ${globalGap >= 0 ? '+' : ''}${Math.round(globalGap)})`;\n}\n\nasync function applyEloDistance(\n cards: WeightedCard[],\n context: FilterContext,\n config: Required<EloDistanceConfig>,\n source: { name: string; strategyId: string }\n): Promise<WeightedCard[]> {\n const { course, userElo, userCourseElo } = context;\n const { halfLife, minMultiplier, maxMultiplier } = config;\n const tagAware = (config.tagAware || multiDimElo) && userCourseElo !== undefined;\n\n // Tag-aware needs every card's full ratings; otherwise only the ELO of cards\n // that don't carry it (reviews). One batch either way.\n const missing = cards\n .filter((c) => !isIntroCard(c) && (tagAware || c.cardElo === undefined))\n .map((c) => c.cardId);\n const fetched = new Map<string, CourseElo>();\n if (missing.length > 0) {\n const elos = await course.getCardEloData(missing);\n missing.forEach((id, i) => {\n if (elos[i]) fetched.set(id, elos[i]);\n });\n }\n\n return cards.map((card) => {\n if (isIntroCard(card)) {\n return {\n ...card,\n provenance: [\n ...card.provenance,\n {\n strategy: 'eloDistance',\n strategyName: source.name,\n strategyId: source.strategyId,\n action: 'passed',\n score: card.score,\n reason: 'intro card: ELO is a placeholder, distance not applied → 1.00x',\n },\n ],\n };\n }\n\n const full = fetched.get(card.cardId);\n const cardElo = full?.global?.score ?? card.cardElo ?? DEFAULT_CARD_ELO;\n\n let distance = Math.abs(cardElo - userElo);\n let how = '';\n if (tagAware) {\n const t = full ? tagAwareGap(card.tags ?? [], full, userCourseElo!, config.minTagCount) : undefined;\n if (t) distance = Math.abs(t.gap);\n how = t?.tags.length\n ? `, tag-aware${tagReason(t.tags, t.globalGap)}`\n : ', tag-aware: global (no shared tags)';\n }\n\n const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);\n const newScore = card.score * multiplier;\n const action = multiplier < maxMultiplier - 0.01 ? 'penalized' : 'passed';\n\n return {\n ...card,\n cardElo,\n score: newScore,\n provenance: [\n ...card.provenance,\n {\n strategy: 'eloDistance',\n strategyName: source.name,\n strategyId: source.strategyId,\n action,\n score: newScore,\n reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)})${how} → ${multiplier.toFixed(2)}x`,\n },\n ],\n };\n });\n}\n\n/**\n * Create an ELO distance filter outside the strategy-doc path.\n *\n * @param config - Optional configuration for the curve\n */\nexport function createEloDistanceFilter(config?: EloDistanceConfig): CardFilter {\n const resolved = resolveConfig(config);\n const source = { name: 'ELO Distance Filter', strategyId: 'ELO_DISTANCE_FILTER' };\n return {\n name: source.name,\n kind: 'signal',\n liveOnly: true,\n transform: (cards, context) => applyEloDistance(cards, context, resolved, source),\n };\n}\n\n/**\n * The ELO distance filter as a strategy-doc navigator (`implementingClass:\n * 'eloDistance'`, serializedData: an EloDistanceConfig as JSON, or empty).\n */\nexport default class EloDistanceFilter extends ContentNavigator implements CardFilter {\n name: string;\n /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */\n static readonly kind: FilterKind = 'signal';\n readonly kind = EloDistanceFilter.kind;\n readonly liveOnly = true;\n private config: Required<EloDistanceConfig>;\n\n constructor(\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n ) {\n super(user, course, strategyData);\n this.name = strategyData.name || 'ELO Distance';\n let parsed: EloDistanceConfig | undefined;\n try {\n parsed = strategyData.serializedData ? JSON.parse(strategyData.serializedData) : undefined;\n } catch {\n parsed = undefined;\n }\n this.config = resolveConfig(parsed);\n }\n\n transform(cards: WeightedCard[], context: FilterContext): Promise<WeightedCard[]> {\n return applyEloDistance(cards, context, this.config, {\n name: this.name,\n strategyId: this.strategyId || 'NAVIGATION_STRATEGY-eloDistance-default',\n });\n }\n\n async getWeightedCards(_limit: number): Promise<GeneratorResult> {\n throw new Error(\n 'EloDistanceFilter is a filter and should not be used as a generator. ' +\n 'Use Pipeline with a generator and this filter via transform().'\n );\n }\n}\n"],"mappings":";;;;;;;;;AA4FA,MAAa,8BAA2D;CACtE,UAAU;CACV,eAAe;CACf,eAAe;CACf,UAAU;CACV,aAAa;CACd;;;;;AAMD,MAAM,sBAAsB;;AAG5B,SAAS,YAAY,MAA6B;AAChD,SAAQ,KAAK,QAAQ,EAAE,EAAE,MAAM,MAAM,QAAQ,EAAE,KAAK,QAAQ;;;AAI9D,MAAM,mBAAmB;AAEzB,SAAS,kBACP,UACA,UACA,eACA,eACQ;CACR,MAAM,qBAAqB,WAAW;CACtC,MAAM,QAAQ,KAAK,IAAI,EAAE,qBAAqB,oBAAoB;AAClE,QAAO,iBAAiB,gBAAgB,iBAAiB;;AAG3D,SAAS,cAAc,QAAyD;AAC9E,QAAO;EAAE,GAAG;EAA6B,GAAG;EAAQ;;AAatD,MAAM,oBAAoB;AAE1B,IAAI,cAAc,iBAAiB;AAEnC,SAAS,kBAA2B;AAClC,KAAI;AACF,SAAO,OAAO,iBAAiB,eAAe,aAAa,QAAQ,kBAAkB,KAAK;SACpF;AACN,SAAO;;;;;;AAOX,SAAgB,yBAA+B;AAC7C,KAAI,OAAO,WAAW,YAAa;CAEnC,MAAM,MAAM;AACZ,KAAI,WAAW,IAAI,YAAY,EAAE;AACjC,QAAO,eAAe,IAAI,UAAU,eAAe;EACjD,cAAc;EACd,YAAY;EACZ,WAAW;EACX,MAAM,OAAgB;AACpB,iBAAc,OAAO;AACrB,OAAI;AACF,QAAI,YAAa,cAAa,QA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K,cAAc;GAChC,CAAC;;CAGJ,MAAM,iBAAiB,QAA0C;AAC/D,QAAM,IAAI,MACR,sIAED"}
@@ -129,9 +129,12 @@ var PrescribedCardsGenerator = class extends ContentNavigator {
129
129
  const allRelevantIds = dedupe([...allTargetIds, ...allSupportIds]);
130
130
  const tagsByCard = allRelevantIds.length > 0 ? await this.course.getAppliedTagsBatch(allRelevantIds) : /* @__PURE__ */ new Map();
131
131
  const cardsByTag = await this.loadCardsByTag();
132
+ const sessionId = context?.sessionId;
133
+ const newSession = sessionId === void 0 || sessionId !== progress.lastSessionId;
132
134
  const nextState = {
133
135
  updatedAt: isoNow(),
134
- groups: {}
136
+ groups: {},
137
+ ...sessionId || progress.lastSessionId ? { lastSessionId: sessionId ?? progress.lastSessionId } : {}
135
138
  };
136
139
  const emitted = [];
137
140
  const emittedIds = /* @__PURE__ */ new Set();
@@ -159,7 +162,7 @@ var PrescribedCardsGenerator = class extends ContentNavigator {
159
162
  logger.info(`[Prescribed] Group '${group.id}' escalation mode: ` + (runtime.supportCandidates.length > 0 ? "direct-support" : runtime.discoveredSupportCandidates.length > 0 ? "inserted-support-candidates" : "boost-only"));
160
163
  if (runtime.discoveredSupportCandidates.length > 0) logger.info(`[Prescribed] Group '${group.id}' discovered support candidates: ${runtime.discoveredSupportCandidates.join(", ")}`);
161
164
  }
162
- nextState.groups[group.id] = this.buildNextGroupState(runtime, progress.groups[group.id]);
165
+ nextState.groups[group.id] = this.buildNextGroupState(runtime, progress.groups[group.id], newSession);
163
166
  const directCards = this.buildDirectTargetCards(runtime, courseId, emittedIds);
164
167
  const supportCards = this.buildSupportCards(runtime, courseId, emittedIds);
165
168
  const discoveredSupportCards = this.buildDiscoveredSupportCards(runtime, courseId, emittedIds);
@@ -217,11 +220,7 @@ var PrescribedCardsGenerator = class extends ContentNavigator {
217
220
  for (const group of this.config.groups) {
218
221
  const groupState = nextState.groups[group.id];
219
222
  const surfaced = surfacedByGroup.get(group.id);
220
- if (surfaced && (surfaced.targetIds.length > 0 || surfaced.supportIds.length > 0)) {
221
- groupState.lastSurfacedAt = isoNow();
222
- groupState.sessionsSinceSurfaced = 0;
223
- if (surfaced.supportIds.length > 0) groupState.lastSupportAt = isoNow();
224
- }
223
+ if (surfaced && surfaced.supportIds.length > 0) groupState.lastSupportAt = isoNow();
225
224
  }
226
225
  await this.putStrategyState(nextState).catch((e) => {
227
226
  logger.debug(`[Prescribed] Failed to persist prescribed progress: ${e}`);
@@ -417,13 +416,24 @@ var PrescribedCardsGenerator = class extends ContentNavigator {
417
416
  debugVersion: PRESCRIBED_DEBUG_VERSION
418
417
  };
419
418
  }
420
- buildNextGroupState(runtime, prior) {
419
+ /**
420
+ * The group's state after this run. The staleness clock resets only when a
421
+ * target has reached the learner since the last run: it is newly in
422
+ * `encounteredTargets`, which reads card history and scheduled reviews, so
423
+ * the card was shown and answered. Emitting a target does not count; it may
424
+ * lose to the rest of the heap. (Before 2026-11, emission reset the clock,
425
+ * and a group that emitted every run never escalated.) The clock advances
426
+ * once per study session, not per run.
427
+ */
428
+ buildNextGroupState(runtime, prior, newSession) {
421
429
  const carriedSessions = prior?.sessionsSinceSurfaced ?? 0;
430
+ const previouslyEncountered = new Set(prior?.encounteredCardIds ?? []);
431
+ const surfacedThisRun = prior !== void 0 && [...runtime.encounteredTargets].some((id) => !previouslyEncountered.has(id));
422
432
  return {
423
433
  encounteredCardIds: [...runtime.encounteredTargets].sort(),
424
434
  pendingTargetIds: [...runtime.pendingTargets].sort(),
425
- lastSurfacedAt: prior?.lastSurfacedAt ?? null,
426
- sessionsSinceSurfaced: carriedSessions + 1,
435
+ lastSurfacedAt: surfacedThisRun ? isoNow() : prior?.lastSurfacedAt ?? null,
436
+ sessionsSinceSurfaced: surfacedThisRun ? 0 : carriedSessions + (newSession ? 1 : 0),
427
437
  lastSupportAt: prior?.lastSupportAt ?? null,
428
438
  blockedTargetIds: [...runtime.blockedTargets].sort(),
429
439
  lastResolvedSupportTags: [...runtime.supportTags].sort()