@vue-skuilder/db 0.2.37 → 0.3.0

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 (46) hide show
  1. package/dist/{contentSource-D_E7JaxR.d.ts → contentSource-2zVmcjKA.d.ts} +6 -1
  2. package/dist/core/index.cjs +112 -78
  3. package/dist/core/index.cjs.map +1 -1
  4. package/dist/core/index.d.ts +5 -5
  5. package/dist/core/navigators/Pipeline.mjs +8 -0
  6. package/dist/core/navigators/Pipeline.mjs.map +1 -1
  7. package/dist/core/versionStamps.mjs +1 -1
  8. package/dist/{dataLayerProvider-BDshhSp_.d.ts → dataLayerProvider-rGyLQ93v.d.ts} +1 -1
  9. package/dist/diagnostics/index.d.ts +3 -3
  10. package/dist/impl/common/BaseUserDB.mjs +18 -13
  11. package/dist/impl/common/BaseUserDB.mjs.map +1 -1
  12. package/dist/impl/couch/CourseSyncService.mjs +23 -1
  13. package/dist/impl/couch/CourseSyncService.mjs.map +1 -1
  14. package/dist/impl/couch/courseDB.mjs +4 -0
  15. package/dist/impl/couch/courseDB.mjs.map +1 -1
  16. package/dist/impl/couch/index.cjs +134 -79
  17. package/dist/impl/couch/index.cjs.map +1 -1
  18. package/dist/impl/couch/index.d.ts +5 -3
  19. package/dist/impl/couch/updateQueue.mjs +69 -46
  20. package/dist/impl/couch/updateQueue.mjs.map +1 -1
  21. package/dist/impl/static/index.cjs +108 -78
  22. package/dist/impl/static/index.cjs.map +1 -1
  23. package/dist/impl/static/index.d.ts +4 -4
  24. package/dist/{index-BLDpFYG3.d.ts → index-C745YB_6.d.ts} +1 -1
  25. package/dist/index.cjs +144 -80
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.d.ts +23 -10
  28. package/dist/index.mjs +2 -1
  29. package/dist/study/SessionController.mjs +4 -0
  30. package/dist/study/SessionController.mjs.map +1 -1
  31. package/dist/{types-DChCz22D.d.ts → types-DF0JuPbs.d.ts} +1 -1
  32. package/dist/{types-legacy-fT5Y1Wuy.d.ts → types-legacy-DdVjg81H.d.ts} +1 -1
  33. package/dist/util/packer/index.d.ts +3 -3
  34. package/dist/util/perfMarks.mjs +30 -0
  35. package/dist/util/perfMarks.mjs.map +1 -0
  36. package/package.json +3 -3
  37. package/src/core/interfaces/courseDB.ts +6 -0
  38. package/src/core/navigators/Pipeline.ts +8 -0
  39. package/src/impl/common/BaseUserDB.ts +27 -21
  40. package/src/impl/couch/CourseSyncService.ts +19 -2
  41. package/src/impl/couch/courseDB.ts +5 -0
  42. package/src/impl/couch/updateQueue.ts +86 -82
  43. package/src/study/SessionController.ts +4 -0
  44. package/src/util/index.ts +1 -0
  45. package/src/util/perfMarks.ts +35 -0
  46. package/tests/impl/updateQueue.test.ts +57 -0
@@ -1 +1 @@
1
- {"version":3,"file":"SessionController.mjs","names":[],"sources":["../../src/study/SessionController.ts"],"sourcesContent":["import { SrsService } from './services/SrsService';\nimport { EloService } from './services/EloService';\nimport { ResponseProcessor } from './services/ResponseProcessor';\nimport { CardHydrationService, HydratedCard } from './services/CardHydrationService';\nimport { ItemQueue } from './ItemQueue';\nimport {\n isReview,\n StudyContentSource,\n StudySessionFailedItem,\n StudySessionItem,\n StudySessionNewItem,\n StudySessionReviewItem,\n} from '@db/impl/couch';\n\nimport { CardRecord, CardHistory, CourseRegistrationDoc, QuestionRecord, isQuestionRecord } from '@db/core';\nimport { DocType } from '@db/core/types/types-legacy';\nimport {\n makeStudySessionId,\n newSessionId,\n type SessionEloEvent,\n type SessionStateSnapshot,\n type SessionStateSnapshotProvider,\n type StudySessionDoc,\n type StudySessionRunCard,\n type StudySessionRunCardTrail,\n type StudySessionRunSummary,\n} from '@db/core/types/studySession';\nimport { recordUserOutcome } from '@db/core/orchestration/recording';\nimport { Loggable } from '@db/util';\nimport {\n getCardOrigin,\n WeightedCard,\n getSrsBacklogDebug,\n getStrategyPressureDebug,\n setDebugSessionId,\n drainCapturedRuns,\n} from '@db/core/navigators';\nimport type { PipelineRunReport, RunReportCard } from '@db/core/navigators';\nimport { ReplanHints } from '@db/core/navigators/generators/types';\nimport { mergeHints } from '@db/core/navigators/Pipeline';\nimport type { RegulatorReading } from '@db/core/navigators/regulators';\nimport { sessionVersions } from '@db/core/versionStamps';\nimport { SourceMixer, QuotaRoundRobinMixer, SourceBatch } from './SourceMixer';\nimport { captureMixerRun } from './MixerDebugger';\nimport { startSessionTracking, recordCardPresentation, snapshotQueues, endSessionTracking, clearStaleSessionDebugState } from './SessionDebugger';\nimport {\n registerActiveController,\n type SessionDebugSnapshot,\n type SessionDrawnCardDebug,\n type SessionQueueDebug,\n type SessionQueueItemDebug,\n} from './SessionOverlay';\n\n// ReplanHints is defined in generators/types to avoid circular dependencies.\n// Re-exported here for backward compatibility.\nexport type { ReplanHints } from '@db/core/navigators/generators/types';\n\n/**\n * Options for requesting a mid-session replan.\n *\n * All fields are optional — callers can pass just the fields they need.\n * When omitted, defaults match the existing behaviour (full 20-card\n * replace with no hints).\n */\nexport interface ReplanOptions {\n /** Scoring hints forwarded to the pipeline (boost/exclude/require). */\n hints?: ReplanHints;\n /**\n * Session-durable scoring hints. Unlike `hints` (one-shot, applied to\n * exactly the run this replan triggers), `sessionHints` are stashed on\n * the controller and re-merged into *every* subsequent pipeline run for\n * the remainder of the session — including the bare auto-replans\n * (depletion/quality) that carry no caller hints, and the wedge-breaker.\n *\n * Use for \"emphasis that should outlive a single queue rebuild\" — e.g.\n * boosting a just-failed concept tag, or a post-lesson concept boost set\n * at session start. Without this, a one-shot `hints` boost evaporates on\n * the next replan and the freshly-rebuilt (replace-mode) queue clobbers\n * whatever it surfaced.\n *\n * Semantics (KISS): setting `sessionHints` *replaces* the prior session\n * hints wholesale (caller beware — no accumulation, no decay). They live\n * until session end or until explicitly overwritten. Normal usage applies\n * a fixed boost, so repeated identical requests are no-ops.\n *\n * Merged with per-run `hints` via the pipeline's `mergeHints` (boosts\n * multiply, require/exclude lists concatenate).\n */\n sessionHints?: ReplanHints;\n /**\n * Like `sessionHints`, but *merged* into the existing session-durable hints\n * (via `mergeHints`) instead of replacing them. Use when emphasis should\n * *accumulate* across replans rather than clobber — e.g. introducing a second\n * concept mid-session must not wipe the first concept's boost, nor any\n * `difficultyBooster`/`conceptBackoff` state on other concepts.\n *\n * Merge semantics (see `mergeHints`): boosts MULTIPLY, require/exclude lists\n * concat-dedup. Re-emphasising the *same* tag therefore compounds — callers\n * boosting a tag they may have already boosted should clamp at the call site.\n *\n * If both `sessionHints` and `mergeSessionHints` are supplied, the replace is\n * applied first, then the merge — but they are normally mutually exclusive.\n */\n mergeSessionHints?: ReplanHints;\n /**\n * Maximum number of new cards to return from the pipeline.\n * Default: 20 (the standard session batch size).\n */\n limit?: number;\n /**\n * How to integrate the new cards into the existing supplyQ.\n * - `'replace'` (default): atomically swap the entire supplyQ.\n * - `'merge'`: insert new cards at the front, keeping existing cards.\n */\n mode?: 'replace' | 'merge';\n /**\n * Guarantee that at least this many cards will be served after the\n * replan, even if the session timer has expired. Prevents intro cards\n * from surfacing at the end of a session with zero follow-up exercise.\n * Decremented on each card draw while active.\n */\n minFollowUpCards?: number;\n /**\n * Human-readable label for debugging / provenance.\n * Appears in console logs and in card provenance entries created\n * by ephemeral hint application.\n */\n label?: string;\n}\n\nexport interface StudySessionRecord {\n card: {\n course_id: string;\n card_id: string;\n card_elo: number;\n tags: string[];\n };\n item: StudySessionItem;\n records: CardRecord[];\n}\n\nimport { DataLayerProvider } from '@db/core';\nimport { logger } from '@db/util/logger';\n\nexport type SessionAction =\n | 'dismiss-success'\n | 'dismiss-failed'\n | 'marked-failed'\n | 'dismiss-error';\n\nexport interface ResponseResult {\n // Navigation\n nextCardAction: Exclude<SessionAction, 'dismiss-error'> | 'none';\n shouldLoadNextCard: boolean;\n\n /**\n * When true, the card requested deferred advancement via `deferAdvance`.\n * The record was logged and ELO updated, but navigation was suppressed.\n * StudySession should stash `nextCardAction` and wait for a\n * `ready-to-advance` event from the card before calling `nextCard()`.\n */\n deferred?: boolean;\n\n // UI Data (let view decide how to render)\n isCorrect: boolean;\n performanceScore?: number; // for shadow color calculation\n\n // Cleanup\n shouldClearFeedbackShadow: boolean;\n}\n\n/**\n * Read-only snapshot of a single processed response, handed to every\n * registered {@link OutcomeObserver} after ELO/SRS have been recorded.\n *\n * Only emitted for question records (non-question dismisses are skipped).\n */\nexport interface SessionOutcome {\n /** The user's response. Includes `isCorrect`, `performance`, `priorAttemps`. */\n readonly record: QuestionRecord;\n /**\n * The card that was answered, including its `tags` — the primary key an\n * observer matches against (e.g. `gpc:exercise:*`). `card_elo` reflects\n * pre-update state; the ELO write for this response is already in flight.\n */\n readonly card: StudySessionRecord['card'];\n /** The navigation decision produced for this response (read-only). */\n readonly result: Readonly<ResponseResult>;\n}\n\n/**\n * The narrow capability surface handed to an {@link OutcomeObserver}. This is\n * the *only* way an observer can affect the session — it cannot touch ELO,\n * the queues, the timer, or mutate the `ResponseResult`. A misbehaving\n * observer degrades to \"wrong boost\", never \"corrupted session\".\n */\nexport interface SessionControls {\n /** Current session-durable hints, or null. For read-modify-write. */\n getSessionHints(): ReplanHints | null;\n /** Replace the session-durable hints wholesale (no decay). */\n setSessionHints(hints: ReplanHints | null): void;\n /**\n * Merge `hints` into the existing session-durable hints via the pipeline's\n * `mergeHints` (boosts multiply, require/exclude lists concat-dedup).\n * Convenience for the common \"add a boost on top of what's there\" case.\n * Note: multiplicative + no decay — clamp boost factors yourself if a\n * repeatedly-failed tag could compound unboundedly.\n */\n mergeSessionHints(hints: ReplanHints): void;\n /** Request a replan (e.g. `{ mode: 'merge' }` for immediate visibility). */\n requestReplan(opts?: ReplanOptions): Promise<void>;\n}\n\n/**\n * A consumer-supplied hook invoked after each question response is processed.\n *\n * Fires on *every* question response (gate inside on `record.isCorrect` /\n * `result.nextCardAction` as needed). Awaited but isolated: a throwing\n * observer is caught and logged, never wedging the session. Keep the\n * synchronous body cheap and `void` any long work (e.g. a triggered replan)\n * so you don't stall navigation.\n *\n * Registered via `StudySessionConfig.outcomeObservers` → constructor options.\n */\nexport type OutcomeObserver = (\n outcome: SessionOutcome,\n controls: SessionControls\n) => void | Promise<void>;\n\n/** Unselected cards persisted per run, after the selected ones. */\nconst PERSISTED_RUNNERS_UP = 5;\n\n/** 4 significant figures: keeps 6.4e-7 distinguishable from 0 without 17-digit floats. */\nfunction sig4(x: number): number {\n return Number(x.toPrecision(4));\n}\n\nfunction toRunCard(c: RunReportCard): StudySessionRunCard {\n return {\n cardId: c.cardId,\n origin: c.origin,\n ...(c.generator ? { generator: c.generator } : {}),\n ...(c.required ? { required: c.required } : {}),\n // A required card's score is infinite, which JSON can't hold: say so with null.\n score: Number.isFinite(c.finalScore) ? sig4(c.finalScore) : null,\n selected: c.selected,\n };\n}\n\nfunction toRunCardTrail(c: RunReportCard): StudySessionRunCardTrail {\n return {\n ...toRunCard(c),\n trail: c.provenance\n .filter((p) => p.action !== 'passed')\n .map((p) => ({\n strategyName: p.strategyName,\n action: p.action,\n score: sig4(p.score),\n reason: p.reason,\n })),\n };\n}\n\nfunction persistedReading(r: RegulatorReading): RegulatorReading {\n return {\n ...r,\n urgency: sig4(r.urgency),\n multiplier: sig4(r.multiplier),\n inputs: Object.fromEntries(Object.entries(r.inputs).map(([k, v]) => [k, sig4(v)])),\n };\n}\n\n/** `run.cards` is selected-then-near-misses, each in score order. */\nfunction persistedRunCards(run: PipelineRunReport): StudySessionRunCard[] {\n const selected = run.cards.filter((c) => c.selected);\n const runnersUp = run.cards.filter((c) => !c.selected).slice(0, PERSISTED_RUNNERS_UP);\n return [...selected, ...runnersUp].map(toRunCard);\n}\n\nfunction persistedUnselectedNew(\n u: NonNullable<PipelineRunReport['unselectedNew']>\n): StudySessionRunSummary['unselectedNew'] {\n return {\n ...(u.nextInLine ? { nextInLine: toRunCardTrail(u.nextInLine) } : {}),\n ...(u.topGenerated ? { topGenerated: toRunCardTrail(u.topGenerated) } : {}),\n };\n}\n\ninterface SessionServices {\n response: ResponseProcessor;\n}\n\nexport class SessionController<TView = unknown> extends Loggable {\n _className = 'SessionController';\n\n public services: SessionServices;\n private srsService: SrsService;\n private eloService: EloService;\n private hydrationService: CardHydrationService<TView>;\n private mixer: SourceMixer;\n private dataLayer: DataLayerProvider;\n private courseNameCache: Map<string, string> = new Map();\n\n /**\n * Default pipeline batch size for new-card planning.\n * Set via constructor options; falls back to 20 when not specified.\n * Individual replans can override via `ReplanOptions.limit`.\n */\n private _defaultBatchLimit: number = 20;\n\n private sources: StudyContentSource[];\n // dataLayer and getViewComponent now injected into CardHydrationService\n private _sessionRecord: StudySessionRecord[] = [];\n public set sessionRecord(r: StudySessionRecord[]) {\n this._sessionRecord = r;\n }\n\n // Session card stores\n private _currentCard: HydratedCard<TView> | null = null;\n\n /**\n * The single supply queue: `new` + `review` items interleaved in pipeline\n * rank order (the mixer's score-ordered, source-interleaved output, with\n * `+INF` required cards floated to the front). Drawn front-to-back; reviews\n * and new compete on one cross-comparable scale rather than being re-mixed\n * by a probability gate. Replaced/re-ranked wholesale on replan. See\n * `docs/decision-single-supply-queue.md`.\n */\n private supplyQ: ItemQueue<StudySessionItem> = new ItemQueue<StudySessionItem>();\n private failedQ: ItemQueue<StudySessionFailedItem> = new ItemQueue<StudySessionFailedItem>();\n // END Session card stores\n\n /**\n * Supply draws since the last failed-queue *event* (a failed draw, or a card\n * entering failedQ on failure). Drives the light steady failed-interleave\n * (§7): after this many consecutive supply draws, a pending failed card is\n * drawn so remediation doesn't starve mid-session. Incremented on each supply\n * draw; reset to 0 both when a failed card is drawn AND when one is added to\n * failedQ — the latter gives a just-failed card spacing instead of an instant\n * retry (the counter would otherwise already be ≥ threshold from the preceding\n * supply run).\n */\n private _supplyDrawsSinceFailed: number = 0;\n\n /**\n * Promise tracking a currently in-progress replan, or null if idle.\n * Used by nextCard() to await completion before drawing from queues.\n */\n private _replanPromise: Promise<void> | null = null;\n\n /**\n * Reason for the replan currently executing in `_runReplan`, surfaced by the\n * debug overlay's spinner. The caller's `opts.label` when present, else\n * `'(auto)'`. Only meaningful while `_replanPromise` is non-null; cleared\n * when the in-flight chain settles.\n */\n private _activeReplanLabel: string | null = null;\n\n /**\n * Number of well-indicated supply cards remaining before the queue\n * degrades to poorly-indicated content. Decremented on each supplyQ\n * draw; when it hits 0, a replan is triggered automatically\n * (user state has changed from completing good cards).\n */\n private _wellIndicatedRemaining: number = 0;\n\n /**\n * When true, suppresses the quality-based auto-replan trigger in\n * nextCard(). Set after a burst replan (small limit) to prevent the\n * auto-replan from clobbering the burst cards before they're consumed.\n * Cleared when the depletion-triggered replan fires (supplyQ exhausted).\n */\n private _suppressQualityReplan: boolean = false;\n\n /**\n * When > 0, the session timer cannot end the session. Decremented on\n * each nextCard() draw. Set by replans that include `minFollowUpCards`.\n */\n private _minCardsGuarantee: number = 0;\n\n /**\n * Session-durable scoring hints. Re-merged into every pipeline run for\n * the rest of the session (initial plan + every replan, including bare\n * auto-replans and the wedge-breaker), via `_applyHintsToSources`.\n *\n * Set by `setSessionHints()` (e.g. session-start post-lesson boost) or by\n * any replan carrying `ReplanOptions.sessionHints` (e.g. a just-failed\n * concept boost). Replace semantics, no decay — lives until overwritten\n * or session end. See `ReplanOptions.sessionHints` for rationale.\n *\n * Note: the controller-managed auto-excludes (current card, session\n * record, imminent draw) are intentionally NOT folded in here — those are\n * recomputed per-run in `_runReplan` and would otherwise go stale.\n */\n private _sessionHints: ReplanHints | null = null;\n\n /**\n * Card IDs that have been *served* (drawn/consumed) this session. Populated\n * at the single consumption choke-point (removeItemFromQueue), so it reflects\n * a draw the instant it happens — earlier than `_sessionRecord`, which only\n * lands once the card is *responded to*.\n *\n * Used to keep already-served cards out of supplyQ on every (re)plan, across\n * ALL origins: a `new` card shown once must never re-enter, and once replans\n * re-pull reviews, an answered/in-flight review must not re-enter the supply\n * before its SRS reschedule clears the due-window (the review-loop guard,\n * decision doc §4). This is the general guard against re-presentation —\n * including the case where a replan in flight captured a now-drawn card (e.g.\n * a +INF require-injected follow-up the depletion prefetch grabbed just before\n * it was drawn). failedQ is separate and controller-owned, so failed cards\n * legitimately recur there without being gated here.\n */\n private _servedCardIds: Set<string> = new Set();\n\n /**\n * Consumer-supplied hooks invoked after each question response is processed.\n * Seeded from constructor options (threaded from\n * `StudySessionConfig.outcomeObservers`). See {@link OutcomeObserver}.\n */\n private _outcomeObservers: OutcomeObserver[] = [];\n\n /**\n * Lazily-built, stable capability object handed to observers. Bound to\n * `this`; constructed once so observers can rely on referential identity.\n */\n private _sessionControls: SessionControls | null = null;\n\n /**\n * Minted at construction so the bootstrap pipeline run in `prepareSession()`\n * can carry it. Stamped onto every CardRecord and pipeline run this session.\n */\n public readonly sessionId: string;\n\n /** Host-supplied. Without it, no durable session doc is written. */\n private _courseId?: string;\n private _stateSnapshotProvider?: SessionStateSnapshotProvider;\n\n private _sessionDoc: StudySessionDoc | null = null;\n\n /**\n * Awaited by the close path — the open write is slow (time-boxed snapshot)\n * and would otherwise land last, leaving a finished session marked `open`.\n */\n private _openDocPromise: Promise<void> | null = null;\n\n private _runLog: StudySessionRunSummary[] = [];\n private static readonly MAX_LOGGED_RUNS = 100;\n\n /**\n * Per-response ELO exchanges as they resolve (see `SessionEloEvent`). Fed by\n * the ResponseProcessor's `onEloEvent` sink; flushed to the session doc at\n * close. Bounded so a runaway session can't grow it without limit.\n */\n private _eloLog: SessionEloEvent[] = [];\n private static readonly MAX_LOGGED_ELO_EVENTS = 2000;\n\n /** Guards `endSession()` against the several termination paths racing it. */\n private _sessionClosed: boolean = false;\n\n private startTime: Date;\n private endTime: Date;\n private _secondsRemaining: number;\n public get secondsRemaining(): number {\n return this._secondsRemaining;\n }\n /** True when a card guarantee is active, preventing timer-based session end. */\n public get hasCardGuarantee(): boolean {\n return this._minCardsGuarantee > 0;\n }\n public get report(): string {\n const supplyCount = this.supplyQ.dequeueCount;\n const supplyWord = supplyCount === 1 ? 'card' : 'cards';\n return `${supplyCount} supply ${supplyWord} drawn`;\n }\n public get detailedReport(): string {\n return this.supplyQ.toString + '\\n' + this.failedQ.toString;\n }\n // @ts-expect-error NodeJS.Timeout type not available in browser context\n private _intervalHandle: NodeJS.Timeout;\n\n /**\n * @param sources - Array of content sources to mix for the session\n * @param time - Session duration in seconds\n * @param dataLayer - Data layer provider\n * @param getViewComponent - Function to resolve view components\n * @param mixer - Optional source mixer strategy (defaults to QuotaRoundRobinMixer)\n * @param options - Optional session-level configuration\n * @param options.defaultBatchLimit - Default supply working-set size (default: 20).\n * Smaller values for newer users cause more frequent replans, keeping plans\n * aligned with rapidly-changing user state.\n */\n constructor(\n sources: StudyContentSource[],\n time: number,\n dataLayer: DataLayerProvider,\n getViewComponent: (viewId: string) => TView,\n mixer?: SourceMixer,\n options?: {\n defaultBatchLimit?: number;\n outcomeObservers?: OutcomeObserver[];\n /** Omit to run without durable session recording. */\n courseId?: string;\n stateSnapshotProvider?: SessionStateSnapshotProvider;\n }\n ) {\n super();\n\n this.sessionId = newSessionId();\n setDebugSessionId(this.sessionId);\n\n this.dataLayer = dataLayer;\n this.mixer = mixer || new QuotaRoundRobinMixer();\n this.srsService = new SrsService(dataLayer.getUserDB());\n this.eloService = new EloService(dataLayer, dataLayer.getUserDB());\n\n this.hydrationService = new CardHydrationService<TView>(\n getViewComponent,\n (courseId: string) => dataLayer.getCourseDB(courseId),\n () => this._getItemsToHydrate()\n );\n\n this.services = {\n response: new ResponseProcessor(this.srsService, this.eloService, (event) =>\n this._recordEloEvent(event)\n ),\n };\n\n this.sources = sources;\n this.startTime = new Date();\n this._secondsRemaining = time;\n this.endTime = new Date(this.startTime.valueOf() + 1000 * this._secondsRemaining);\n\n if (options?.defaultBatchLimit !== undefined) {\n this._defaultBatchLimit = options.defaultBatchLimit;\n }\n if (options?.outcomeObservers?.length) {\n this._outcomeObservers = [...options.outcomeObservers];\n }\n this._courseId = options?.courseId;\n this._stateSnapshotProvider = options?.stateSnapshotProvider;\n\n this.log(`Session constructed:\n sessionId: ${this.sessionId}\n startTime: ${this.startTime}\n endTime: ${this.endTime}\n defaultBatchLimit: ${this._defaultBatchLimit}`);\n\n // Expose this (now the most-recently-constructed) controller to the debug\n // overlay (window.skuilder.session.dbgOverlay()). A new session overwrites\n // the prior handle; no-op overhead when the overlay is never opened.\n registerActiveController(this);\n }\n\n private tick() {\n this._secondsRemaining = Math.floor((this.endTime.valueOf() - Date.now()) / 1000);\n // this.log(this.secondsRemaining);\n\n if (this._secondsRemaining <= 0) {\n clearInterval(this._intervalHandle);\n }\n }\n\n /**\n * Returns a rough, erring toward conservative, guess at\n * the amount of time the failed cards queue will require\n * to clean up.\n *\n * (seconds)\n */\n private estimateCleanupTime(): number {\n let time: number = 0;\n for (let i = 0; i < this.failedQ.length; i++) {\n const c = this.failedQ.peek(i);\n // this.log(`Failed card ${c.qualifiedID} found`)\n\n const record = this._sessionRecord.find((r) => r.item.cardID === c.cardID);\n let cardTime = 0;\n\n if (record) {\n // this.log(`Card Record Found...`);\n for (let j = 0; j < record.records.length; j++) {\n cardTime += record.records[j].timeSpent;\n }\n cardTime = cardTime / record.records.length;\n time += cardTime;\n }\n }\n\n const ret: number = time / 1000;\n this.log(`Failed card cleanup estimate: ${Math.round(ret)}`);\n return ret;\n }\n\n public async prepareSession() {\n // All content sources must implement getWeightedCards()\n if (this.sources.some((s) => typeof s.getWeightedCards !== 'function')) {\n throw new Error(\n '[SessionController] All content sources must implement getWeightedCards().'\n );\n }\n\n // Clear the previous session's debug state before this session's\n // bootstrap pipeline run fires, so that run's own report isn't wiped out.\n clearStaleSessionDebugState();\n\n const wellIndicated = await this.getWeightedContent();\n this._recordRuns('bootstrap');\n this._wellIndicatedRemaining = wellIndicated;\n if (wellIndicated >= 0 && wellIndicated < SessionController.MIN_WELL_INDICATED) {\n this.log(\n `[Init] Only ${wellIndicated}/${SessionController.MIN_WELL_INDICATED} well-indicated cards in initial load`\n );\n }\n await this.hydrationService.ensureHydratedCards();\n\n // Start session tracking for debugging\n startSessionTracking(this.sessionId, this.supplyQ.length, this.failedQ.length);\n\n // Not awaited — a session must never block on an analytics write.\n this._openDocPromise = this._openSessionDoc();\n\n this._intervalHandle = setInterval(() => {\n this.tick();\n }, 1000);\n }\n\n /** Label the runs the last plan produced. The pipeline can't know the why. */\n private _recordRuns(label: string, mode?: string): void {\n for (const run of drainCapturedRuns()) {\n if (this._runLog.length >= SessionController.MAX_LOGGED_RUNS) break;\n this._runLog.push({\n runId: run.runId,\n at: run.timestamp.toISOString(),\n label,\n ...(mode ? { mode } : {}),\n generatedCount: run.generatedCount,\n finalCount: run.finalCount,\n reviewsSelected: run.reviewsSelected,\n newSelected: run.newSelected,\n // Compact detail projected off the full report so a persisted run is\n // self-explanatory once the in-memory ring buffer has rolled over.\n // Per-card provenance is the dominant cost, so it's kept only for the\n // (at most two) `unselectedNew` cards, and only its score-changing\n // entries. Everything else is ids and scores.\n ...(typeof run.userElo === 'number' ? { userElo: run.userElo } : {}),\n ...(run.generators ? { generators: run.generators } : {}),\n ...(run.filters ? { filters: run.filters } : {}),\n ...(run.hints ? { hints: run.hints } : {}),\n ...(run.discardedTail ? { discardedTail: run.discardedTail } : {}),\n cards: persistedRunCards(run),\n ...(run.unselectedNew ? { unselectedNew: persistedUnselectedNew(run.unselectedNew) } : {}),\n ...(run.regulators ? { regulators: run.regulators.map(persistedReading) } : {}),\n ...(run.versions ? { versions: run.versions } : {}),\n });\n }\n }\n\n /** Time-boxed and isolated — a bad provider degrades the record, not the session. */\n private async _captureState(\n phase: 'start' | 'end'\n ): Promise<SessionStateSnapshot | undefined> {\n if (!this._stateSnapshotProvider) return undefined;\n const TIMEOUT_MS = 3000;\n try {\n return await Promise.race([\n Promise.resolve(this._stateSnapshotProvider(phase)),\n new Promise<undefined>((resolve) => setTimeout(() => resolve(undefined), TIMEOUT_MS)),\n ]);\n } catch (e) {\n this.log(`[Session] state snapshot (${phase}) failed: ${e}`);\n return undefined;\n }\n }\n\n /** Writing at open is what makes an unclosed session visible at all. */\n private async _openSessionDoc(): Promise<void> {\n if (!this._courseId) return;\n try {\n const user = this.dataLayer.getUserDB();\n const doc: StudySessionDoc = {\n _id: makeStudySessionId(this._courseId, user.getUsername(), this.sessionId),\n docType: DocType.STUDY_SESSION,\n sessionId: this.sessionId,\n courseId: this._courseId,\n userId: user.getUsername(),\n startTime: this.startTime.toISOString(),\n status: 'open',\n plannedSeconds: Math.round((this.endTime.valueOf() - this.startTime.valueOf()) / 1000),\n config: {\n defaultBatchLimit: this._defaultBatchLimit,\n sourceCount: this.sources.length,\n initHints: this._sessionHints,\n },\n versions: sessionVersions(),\n initialQueues: { supplyQ: this.supplyQ.length, failedQ: this.failedQ.length },\n runs: [...this._runLog],\n stateAtStart: await this._captureState('start'),\n };\n this._sessionDoc = doc;\n await user.putStudySession(doc);\n this.log(`[Session] Opened session record ${doc._id}`);\n } catch (e) {\n logger.warn(`[SessionController] Failed to open session record: ${e}`);\n }\n }\n\n /**\n * Request a mid-session replan. Re-runs the pipeline with current user state\n * and atomically replaces (or merges into) the supplyQ contents. Safe to call\n * at any time during a session.\n *\n * Concurrency policy:\n * - Two unhinted auto-replans never run in parallel; the second coalesces\n * into the first (returns the same promise).\n * - A hint-bearing replan that arrives while another replan is in flight\n * is queued to run **after** the in-flight one rather than dropped.\n * This preserves caller intent (label, requireCards, excludeTags,\n * limit, minFollowUpCards) instead of silently discarding it. Without\n * queueing, a background auto-replan that started just before a\n * completion-triggered replan would clobber the queue with unhinted\n * results (e.g. surfacing another gpc-intro card right after one\n * completed, skipping the prescribed `c-wst-*` follow-up).\n *\n * Re-pulls and re-ranks the whole supply (including reviews); does NOT affect\n * failedQ (controller-owned remediation).\n *\n * If nextCard() is called while a replan is in flight, it will automatically\n * await the replan before drawing from queues, ensuring the user always sees\n * cards scored against their latest state.\n *\n * Typical trigger: application-level code (e.g. after a GPC intro completion)\n * calls this to ensure newly-unlocked content appears in the session.\n */\n public async requestReplan(options?: ReplanOptions | ReplanHints): Promise<void> {\n // Normalise: bare hints object (legacy callers) → ReplanOptions wrapper\n const opts = this.normalizeReplanOptions(options);\n\n const hasIntent = this._replanHasIntent(opts);\n\n if (this._replanPromise) {\n if (!hasIntent) {\n this.log('Replan already in progress, coalescing unhinted auto-replan');\n return this._replanPromise;\n }\n\n // Queue the hint-bearing replan behind the in-flight one rather than\n // dropping its hints. See class comment above for rationale.\n const labelTag = opts.label ? ` [${opts.label}]` : '';\n this.log(\n `Replan in progress; queueing hint-bearing replan${labelTag} behind in-flight run`\n );\n const inflight = this._replanPromise;\n const queued: Promise<void> = inflight\n // Swallow errors in the upstream replan so the downstream still runs\n // (the user's intent is independent of whether the prior run succeeded).\n .catch(() => undefined)\n .then(() => this._runReplan(opts));\n\n // Compare against the promise we actually store. `.finally()` returns a\n // NEW promise, so guarding on `=== queued` (the pre-finally promise) never\n // matches and would leak _replanPromise. `tracked` is read only inside the\n // async callback (after init), so the self-reference is safe.\n const tracked: Promise<void> = queued.finally(() => {\n if (this._replanPromise === tracked) {\n this._replanPromise = null;\n this._activeReplanLabel = null;\n }\n });\n this._replanPromise = tracked;\n\n return queued;\n }\n\n const run = this._runReplan(opts);\n // Compare against the wrapped promise we store, not `run` — `.finally()`\n // returns a new promise, so `=== run` never matches and _replanPromise\n // would never clear (perpetual \"replan in progress\"). Safe self-reference:\n // `tracked` is read only in the async callback, after initialization.\n const tracked: Promise<void> = run.finally(() => {\n if (this._replanPromise === tracked) {\n this._replanPromise = null;\n this._activeReplanLabel = null;\n }\n });\n this._replanPromise = tracked;\n\n await run;\n }\n\n /**\n * True when a requestReplan call carries caller intent that must not be\n * silently dropped. Bare unhinted auto-replans (depletion / quality\n * triggers in nextCard) return false and may coalesce.\n */\n private _replanHasIntent(opts: ReplanOptions): boolean {\n // NOTE: `label` is intentionally NOT an intent signal. It is observability-\n // only metadata (debug overlay spinner, log tags, Pipeline strategy names),\n // so labelling a replan must never change scheduling. Intent is strictly\n // \"does this replan carry scheduling-relevant options\". This lets the\n // unlabeled-but-named auto-replans (auto:depletion / auto:quality) keep\n // coalescing while still showing a reason in the overlay.\n if (opts.limit !== undefined) return true;\n if (opts.minFollowUpCards !== undefined) return true;\n if (opts.mode && opts.mode !== 'replace') return true;\n if (opts.hints && Object.keys(opts.hints).length > 0) return true;\n if (opts.sessionHints !== undefined) return true;\n if (opts.mergeSessionHints !== undefined) return true;\n return false;\n }\n\n /**\n * Body of a single replan: populate auto-excludes, stash hints on\n * sources, log, then run the pipeline. Extracted so it can be invoked\n * either immediately (no in-flight replan) or queued (chained after\n * the in-flight one resolves).\n *\n * IMPORTANT: hint stash and the queue-state snapshot used to build\n * excludeCards happen at *invocation* time, not at *queue* time. For a\n * queued replan that means excludes reflect the state after the prior\n * replan landed — which is what we want, since the prior replan's\n * supplyQ.peek(0) is the imminent draw we need to exclude.\n */\n private async _runReplan(opts: ReplanOptions): Promise<void> {\n // Surface the executing replan's reason to the debug overlay spinner.\n // `label` is observability-only (see _replanHasIntent); '(auto)' covers any\n // unlabeled path.\n this._activeReplanLabel = opts.label ?? '(auto)';\n\n // Exclude all cards already presented this session. The pipeline may\n // not yet see their encounter records (async writes), so without this\n // they can re-enter supplyQ via replaceAll and cause duplicates.\n //\n // Also exclude supplyQ.peek(0): the imminent draw. When a replan fires\n // from inside nextCard() (auto depletion/quality trigger) or as a\n // deferred post-submit replan, the next-up card is about to become\n // _currentCard but isn't yet, and hasn't yet landed in _sessionRecord.\n // Without this, the just-drawn card can be re-seated at the head of\n // the replaced supplyQ and shown twice in a row — most visible in early\n // sessions where state is sparse and triggers fire aggressively.\n // Only the head is excluded; deeper supplyQ entries are still fair game\n // for the new plan (they aren't at risk of double-display since the\n // old queue is replaced atomically and only its head gets drawn).\n if (!opts.hints) opts.hints = {};\n const hints = opts.hints;\n const excludeSet = new Set(hints.excludeCards ?? []);\n\n if (this._currentCard?.item.cardID) {\n excludeSet.add(this._currentCard.item.cardID);\n }\n for (const rec of this._sessionRecord) {\n excludeSet.add(rec.card.card_id);\n }\n if (this.supplyQ.length > 0) {\n excludeSet.add(this.supplyQ.peek(0).cardID);\n }\n\n hints.excludeCards = [...excludeSet];\n\n // Replace session-durable hints if this replan carries them. KISS:\n // wholesale replace, no accumulation/decay (see ReplanOptions.sessionHints).\n if (opts.sessionHints !== undefined) {\n this._sessionHints = opts.sessionHints;\n this.log(\n `[Replan] Session hints ${opts.sessionHints ? 'set' : 'cleared'}: ` +\n `${JSON.stringify(opts.sessionHints)}`\n );\n }\n\n // Additive emphasis: merge (don't clobber) into durable hints. Lets a new\n // concept's boost accumulate on top of prior concepts' boosts and any\n // observer-managed boost/decay state. Boosts multiply, lists concat-dedup.\n if (opts.mergeSessionHints !== undefined) {\n this._sessionHints = mergeHints([this._sessionHints, opts.mergeSessionHints]) ?? null;\n this.log(`[Replan] Session hints merged: ${JSON.stringify(this._sessionHints)}`);\n }\n\n // Forward hints to all sources (CourseDB stashes them, Pipeline consumes\n // them). The one-shot `opts.hints` are merged with the durable\n // `_sessionHints` so session emphasis survives this and every later run.\n this._applyHintsToSources(opts.hints, opts.label);\n\n const labelTag = opts.label ? ` [${opts.label}]` : '';\n this.log(\n `Mid-session replan requested${labelTag}` +\n ` (limit: ${opts.limit ?? 'default'}, mode: ${opts.mode ?? 'replace'}` +\n `${opts.hints ? ', with hints' : ''})`\n );\n // Update card guarantee if requested\n if (opts.minFollowUpCards !== undefined && opts.minFollowUpCards > 0) {\n this._minCardsGuarantee = Math.max(this._minCardsGuarantee, opts.minFollowUpCards);\n this.log(`[Replan] Card guarantee set to ${this._minCardsGuarantee}`);\n }\n\n // [perf] parked 2026-05 (pipeline-docs-workup) — uncomment to re-measure\n // const tReplan0 = performance.now();\n await this._executeReplan(opts);\n // logger.info(\n // `[perf][SessionController] replan${labelTag} (limit=${opts.limit ?? 'default'}, ` +\n // `mode=${opts.mode ?? 'replace'}) took ${(performance.now() - tReplan0).toFixed(0)}ms`\n // );\n }\n\n /**\n * Set the session-durable scoring hints (replace semantics, no decay).\n *\n * Unlike a one-shot replan hint, these are re-merged into every pipeline\n * run for the rest of the session — including the initial plan when set\n * before `prepareSession()`, every replan, the bare auto-replans, and the\n * wedge-breaker. Pass `null` to clear.\n *\n * Typical callers:\n * - `StudySession` at session start, threading `StudySessionConfig.initHints`\n * (e.g. a post-lesson concept boost) — so the boost outlives the first\n * queue rebuild instead of being clobbered by the first auto-replan.\n * - A consumer view on a failure, boosting the just-failed concept tag.\n *\n * Does not itself trigger a replan; the next plan/replan picks it up.\n */\n public setSessionHints(hints: ReplanHints | null): void {\n this._sessionHints = hints;\n this.log(`Session hints ${hints ? 'set' : 'cleared'}: ${JSON.stringify(hints)}`);\n }\n\n /**\n * Read the current session-durable hints (for read-modify-write callers,\n * e.g. an outcome observer that clamps a compounding boost).\n */\n public getSessionHints(): ReplanHints | null {\n return this._sessionHints;\n }\n\n /**\n * Live state snapshot for the debug overlay (window.skuilder.session\n * .dbgOverlay()). Reads directly from the private queues and hints, so it\n * always reflects the current moment — unlike the passive SessionDebugger\n * snapshots, which only capture what was explicitly pushed to them.\n */\n public getDebugSnapshot(): SessionDebugSnapshot {\n const describe = <T extends StudySessionItem>(q: ItemQueue<T>): SessionQueueDebug => {\n const cards: SessionQueueItemDebug[] = [];\n for (let i = 0; i < q.length; i++) {\n const item = q.peek(i);\n cards.push({\n cardID: item.cardID,\n status: item.status,\n origin: isReview(item) ? 'review' : 'new',\n score: item.score,\n });\n }\n return { length: q.length, dequeueCount: q.dequeueCount, cards };\n };\n const drawnCards: SessionDrawnCardDebug[] = this._sessionRecord.map((r) => {\n const last = r.records[r.records.length - 1];\n return {\n cardID: r.item.cardID,\n status: r.item.status,\n attempts: r.records.length,\n correct: last && isQuestionRecord(last) ? last.isCorrect : null,\n timeSpentMs: r.records.reduce((sum, rec) => sum + rec.timeSpent, 0),\n };\n });\n return {\n sessionId: this.sessionId,\n secondsRemaining: this.secondsRemaining,\n hasCardGuarantee: this.hasCardGuarantee,\n minCardsGuarantee: this._minCardsGuarantee,\n wellIndicatedRemaining: this._wellIndicatedRemaining,\n currentCard: this._currentCard?.item.cardID ?? null,\n sessionHints: this._sessionHints,\n replanActive: this._replanPromise !== null,\n replanLabel: this._activeReplanLabel,\n supplyQ: describe(this.supplyQ),\n failedQ: describe(this.failedQ),\n reviewBacklog: getSrsBacklogDebug(),\n strategyPressure: getStrategyPressureDebug(),\n drawnCards,\n };\n }\n\n /**\n * Merge `hints` into the durable session hints via the pipeline's\n * `mergeHints` (boosts multiply, require/exclude lists concat-dedup).\n * Convenience over get-then-set for the common additive case. Note the\n * multiplicative, no-decay semantics — clamp boost factors at the call\n * site if a repeatedly-emphasised tag could compound unboundedly.\n */\n public mergeSessionHints(hints: ReplanHints): void {\n this._sessionHints = mergeHints([this._sessionHints, hints]) ?? null;\n this.log(`Session hints merged: ${JSON.stringify(this._sessionHints)}`);\n }\n\n /**\n * Merge the durable `_sessionHints` with this run's one-shot hints and\n * push the result to every source for consumption on the next pipeline\n * run. Centralised so the initial plan and all replan paths apply session\n * emphasis identically. No-op when there are no hints of either kind.\n */\n private _applyHintsToSources(oneShot?: ReplanHints, label?: string): void {\n // Thread the provenance label into the one-shot layer; mergeHints will\n // fold it into the combined `_label`.\n const oneShotWithLabel: ReplanHints | undefined =\n oneShot && label ? { ...oneShot, _label: label } : oneShot;\n\n const merged = mergeHints([this._sessionHints, oneShotWithLabel]);\n if (!merged) return;\n\n for (const source of this.sources) {\n source.setEphemeralHints?.(merged);\n }\n }\n\n /**\n * Build (once) the stable capability object handed to outcome observers.\n * Methods are bound to `this`; the object identity is stable across calls\n * so observers may key off it.\n */\n private _getSessionControls(): SessionControls {\n if (!this._sessionControls) {\n this._sessionControls = {\n getSessionHints: () => this.getSessionHints(),\n setSessionHints: (h) => this.setSessionHints(h),\n mergeSessionHints: (h) => this.mergeSessionHints(h),\n requestReplan: (opts) => this.requestReplan(opts),\n };\n }\n return this._sessionControls;\n }\n\n /**\n * Notify registered outcome observers about a processed response.\n *\n * Only question records are surfaced (non-question dismisses are skipped).\n * Observers run after ELO/SRS are recorded and before navigation. Each is\n * awaited but isolated in try/catch — a throwing observer is logged and\n * skipped, never wedging the session. Keep observers cheap and `void` any\n * long work (e.g. a triggered replan) to avoid stalling the draw.\n */\n /**\n * Append a resolved ELO exchange to the in-memory log. Fires async (the ELO\n * update is non-blocking), so an event can land after the response that\n * produced it has returned — but well before close, which is when the log is\n * persisted. Bounded to avoid unbounded growth.\n */\n private _recordEloEvent(event: SessionEloEvent): void {\n if (this._eloLog.length >= SessionController.MAX_LOGGED_ELO_EVENTS) return;\n this._eloLog.push(event);\n }\n\n private async _notifyOutcomeObservers(\n record: CardRecord,\n currentCard: StudySessionRecord,\n result: ResponseResult\n ): Promise<void> {\n if (this._outcomeObservers.length === 0) return;\n if (!isQuestionRecord(record)) return;\n\n const outcome: SessionOutcome = {\n record,\n card: currentCard.card,\n result,\n };\n const controls = this._getSessionControls();\n\n for (const observer of this._outcomeObservers) {\n try {\n await observer(outcome, controls);\n } catch (e) {\n this.error('[OutcomeObserver] observer threw; ignoring', e);\n }\n }\n }\n\n /**\n * Run a replan, bypassing requestReplan()'s coalesce logic.\n *\n * Use this when correctness depends on a *fresh* pipeline run, not on\n * the existence of *some* in-flight replan. Specifically: the\n * wedge-breaker path in nextCard(), where coalescing into a previous\n * run that we now know produced insufficient content would re-create\n * the bug we're trying to prevent.\n *\n * Still tracks _replanPromise like requestReplan() does so concurrent\n * observers (auto-trigger guards in nextCard()) see consistent state.\n */\n private async _replanUncoalesced(opts: ReplanOptions): Promise<void> {\n const run = this._runReplan(opts);\n // See requestReplan: guard against the wrapped promise we store, not `run`.\n const tracked: Promise<void> = run.finally(() => {\n if (this._replanPromise === tracked) {\n this._replanPromise = null;\n this._activeReplanLabel = null;\n }\n });\n this._replanPromise = tracked;\n await run;\n }\n\n /**\n * Normalise the requestReplan argument. Accepts either a ReplanOptions\n * object (new API) or a plain Record<string, unknown> (legacy callers\n * that passed hints directly). Distinguishes the two by checking for\n * the presence of ReplanOptions-specific keys.\n */\n private normalizeReplanOptions(\n input?: ReplanOptions | ReplanHints\n ): ReplanOptions {\n if (!input) return {};\n\n // If the input has any ReplanOptions-specific key, treat it as ReplanOptions\n const replanKeys = ['hints', 'sessionHints', 'limit', 'mode', 'label', 'minFollowUpCards'];\n const inputKeys = Object.keys(input);\n if (inputKeys.some((k) => replanKeys.includes(k))) {\n return input as ReplanOptions;\n }\n\n // Otherwise treat as legacy bare-hints object\n return { hints: input as ReplanHints };\n }\n\n /** Minimum well-indicated cards before an additive retry is attempted */\n private static readonly MIN_WELL_INDICATED = 5;\n\n /**\n * Score threshold for considering a card \"well-indicated.\"\n * Cards below this score are treated as fallback filler — present only\n * because no strategy hard-removed them, but likely penalized by one\n * or more filters. Strategy-agnostic: the SessionController doesn't\n * know or care which strategy assigned the score.\n */\n private static readonly WELL_INDICATED_SCORE = 0.10;\n\n /**\n * supplyQ length at or below which the opportunistic depletion-prefetch\n * fires. Sets the lead time available for the background replan to land\n * before the user actually empties the queue and falls into the\n * (synchronous) wedge-breaker path.\n *\n * Set to a small absolute value (not a fraction of batch limit) because\n * pipeline latency is roughly fixed regardless of batch size — what\n * matters is \"how many cards of user-pace do we have left.\" 3 cards\n * × ~3-5s/card = ~10-15s of lead time, comfortably exceeding typical\n * pipeline latency.\n */\n private static readonly DEPLETION_PREFETCH_THRESHOLD = 3;\n\n /**\n * Internal replan execution. Runs the pipeline, rebuilds the supplyQ,\n * atomically swaps it in, and triggers hydration for the new contents.\n *\n * If the initial replan produces fewer than MIN_WELL_INDICATED cards that\n * pass all hierarchy filters, one additive retry is attempted — merging\n * any new high-quality candidates into the front of the queue.\n */\n private async _executeReplan(opts: ReplanOptions = {}): Promise<void> {\n const limit = opts.limit;\n const mode = opts.mode ?? 'replace';\n\n const wellIndicated = await this.getWeightedContent({\n replan: true,\n additive: mode === 'merge',\n limit,\n });\n this._recordRuns(opts.label ?? '(auto)', mode);\n this._wellIndicatedRemaining = wellIndicated;\n\n // Burst replan: suppress quality-based auto-replan so the background\n // replan doesn't clobber the small hinted queue before it's consumed.\n // The depletion trigger (supplyQ empty) takes over instead.\n if (limit !== undefined && limit < this._defaultBatchLimit) {\n this._suppressQualityReplan = true;\n this.log(`[Replan] Burst mode (limit=${limit}): suppressing quality-based auto-replan`);\n } else {\n // Normal or auto-replan — clear the burst suppression flag\n this._suppressQualityReplan = false;\n }\n\n if (wellIndicated >= 0 && wellIndicated < SessionController.MIN_WELL_INDICATED) {\n this.log(\n `[Replan] Only ${wellIndicated}/${SessionController.MIN_WELL_INDICATED} well-indicated cards after replan`\n );\n }\n\n await this.hydrationService.ensureHydratedCards();\n const labelTag = opts.label ? ` [${opts.label}]` : '';\n this.log(`Replan complete${labelTag}: supplyQ now has ${this.supplyQ.length} cards (mode=${mode})`);\n\n // Snapshot queue state for debugging\n snapshotQueues(this.supplyQ.length, this.failedQ.length);\n }\n\n public addTime(seconds: number) {\n this.endTime = new Date(this.endTime.valueOf() + 1000 * seconds);\n }\n\n public get failedCount(): number {\n return this.failedQ.length;\n }\n\n public toString() {\n return `Session: ${this.supplyQ.length} supply, ${this.failedQ.length} failed`;\n }\n public reportString() {\n return `${this.supplyQ.dequeueCount} supply, ${this.failedQ.dequeueCount} failed`;\n }\n\n /**\n * Returns debug information about the current session state.\n * Used by SessionControllerDebug component for runtime inspection.\n */\n public getDebugInfo() {\n // Check if sources support weighted cards\n const supportsWeightedCards = this.sources.some(\n (s) => typeof s.getWeightedCards === 'function'\n );\n\n const extractQueueItems = (queue: ItemQueue<any>, limit: number = 10) => {\n const items = [];\n for (let i = 0; i < Math.min(queue.length, limit); i++) {\n const item = queue.peek(i);\n items.push({\n courseID: item.courseID || 'unknown',\n cardID: item.cardID || 'unknown',\n status: item.status || 'unknown',\n score: item.score,\n });\n }\n return items;\n };\n\n return {\n api: {\n mode: supportsWeightedCards ? 'weighted' : 'legacy',\n description: supportsWeightedCards\n ? 'Using getWeightedCards() API with scored candidates'\n : 'ERROR: getWeightedCards() not a function.',\n },\n supplyQueue: {\n length: this.supplyQ.length,\n dequeueCount: this.supplyQ.dequeueCount,\n items: extractQueueItems(this.supplyQ),\n },\n failedQueue: {\n length: this.failedQ.length,\n dequeueCount: this.failedQ.dequeueCount,\n items: extractQueueItems(this.failedQ),\n },\n hydratedCache: {\n count: this.hydrationService.hydratedCount,\n cardIds: this.hydrationService.getHydratedCardIds(),\n },\n replan: {\n inProgress: this._replanPromise !== null,\n suppressQualityReplan: this._suppressQualityReplan,\n defaultBatchLimit: this._defaultBatchLimit,\n minCardsGuarantee: this._minCardsGuarantee,\n },\n };\n }\n\n /**\n * Fetch weighted content from all sources, mix across sources, and populate\n * the single supply queue in pipeline rank order.\n *\n * Reviews and new cards compete on one cross-comparable scale (SRS 0.5–1.0\n * w/ backlog pressure vs ELO 0.0–1.0) — there is no origin split and no\n * second mixer. The working set is `supplyLimit` cards (the top of the mixed\n * ranking, plus any `+INF` required cards floated to the front); replans\n * re-pull and re-rank the whole supply, so a heavy review backlog surfaces as\n * a refreshed top-ranked working set rather than a frozen 200-card snapshot.\n *\n * @param options.replan - If true, this is a mid-session replan rather than\n * initial session setup. Atomically replaces supplyQ contents and treats\n * empty results as non-fatal.\n * @param options.additive - If true (replan only), merge high-quality\n * candidates into the front of the existing supplyQ instead of replacing it.\n * @returns Number of \"well-indicated\" cards (passed all hierarchy filters)\n * in the new content. Returns -1 if no content was loaded.\n */\n private async getWeightedContent(options?: {\n replan?: boolean;\n additive?: boolean;\n limit?: number;\n }): Promise<number> {\n // const tGwc0 = performance.now(); // [perf] parked\n const replan = options?.replan ?? false;\n const additive = options?.additive ?? false;\n const supplyLimit = options?.limit ?? this._defaultBatchLimit;\n // Single working set: fetch the top `supplyLimit` from each source and let\n // the mixer interleave them. Reviews and new are ranked together, so there\n // is no separate review budget to inflate for (cf. the old dual-budget\n // fetch that over-fetched to fill a frozen review cap).\n const fetchLimit = supplyLimit;\n\n // Initial plan: push session-durable hints to sources so the very first\n // pipeline run reflects them (e.g. a post-lesson boost). Replans push\n // their own session+one-shot merge via _runReplan before reaching here,\n // so we must NOT re-apply here or we'd drop their per-run excludeCards.\n if (!replan) {\n this._applyHintsToSources();\n }\n\n // Collect batches from each source\n const batches: SourceBatch[] = [];\n\n for (let i = 0; i < this.sources.length; i++) {\n const source = this.sources[i];\n try {\n // Fetch weighted cards for mixing\n const weighted = (await source.getWeightedCards!(fetchLimit)).cards;\n\n batches.push({\n sourceIndex: i,\n weighted,\n });\n } catch (error) {\n this.error(`Failed to get content from source ${i}:`, error);\n // Re-throw if this is the only source - we can't proceed without any content.\n // Initial load only: a replan falls through to the non-fatal\n // `batches.length === 0` path below and keeps the existing queue.\n // Throwing there would escape nextCard() (via the wedge-breaker) and\n // strand the host mid-session with neither a card nor a null.\n if (this.sources.length === 1 && !replan) {\n throw new Error(`Cannot start session: failed to load content from source ${i}`);\n }\n }\n }\n\n // const tSources = performance.now(); // [perf] parked\n\n // Verify we got content from at least one source\n if (batches.length === 0) {\n if (replan) {\n // Replan finding no content is non-fatal — old queue remains\n this.log('Replan: no content from any source, keeping existing supplyQ');\n return -1;\n }\n throw new Error(\n `Cannot start session: failed to load content from all ${this.sources.length} source(s). ` +\n `Check logs for details.`\n );\n }\n\n // Mix weighted cards across sources using configured strategy\n const mixedWeighted = this.mixer.mix(batches, fetchLimit * this.sources.length);\n // const tMixed = performance.now(); // [perf] parked\n\n // Capture mixer run for debugging - fetch course names\n const sourceIds = batches.map((b) => {\n const firstCard = b.weighted[0];\n return firstCard?.courseId || `source-${b.sourceIndex}`;\n });\n // Populate course name cache (one-time fetch, reused by SessionDebugger)\n await Promise.all(\n sourceIds.map(async (id) => {\n if (!this.courseNameCache.has(id)) {\n try {\n const config = await this.dataLayer.getCoursesDB().getCourseConfig(id);\n this.courseNameCache.set(id, config.name);\n } catch {\n // leave unmapped\n }\n }\n })\n );\n const sourceNames = sourceIds.map((id) => this.courseNameCache.get(id));\n const quotaPerSource =\n this.mixer instanceof QuotaRoundRobinMixer ? Math.ceil((fetchLimit * this.sources.length) / batches.length) : undefined;\n captureMixerRun(\n this.mixer.constructor.name,\n batches,\n sourceIds,\n sourceNames,\n fetchLimit * this.sources.length,\n quotaPerSource,\n mixedWeighted\n );\n\n // Single supply working set — no origin split. Reviews and new compete on\n // one rank. Drop already-served cards across ALL origins: a `new` card\n // shown once must never recur, and once replans re-pull reviews, an\n // answered/in-flight review must not re-enter the supply before its SRS\n // reschedule clears the due-window (the review-loop guard, decision doc §4).\n // failedQ is separate, so this never blocks legitimate failed re-presentation.\n const candidates = mixedWeighted.filter((w) => !this._servedCardIds.has(w.cardId));\n\n // `+INF` is the hard \"include at all costs\" sentinel applied by require*\n // injection (see Pipeline.applyRequirement). Float these mandatory cards to\n // the front and exempt them from the supplyLimit slice, so neither the\n // mixer's source-shuffle/round-robin nor the cap can bury or drop a required\n // card. This preserves rank-respect through the mixer — it is NOT a per-item\n // \"mandatory\" flag (the supplyQ is drawn front-to-back, and the timer guards\n // honour `_minCardsGuarantee`, so a required follow-up is served on its own\n // merits; see decision doc §3). The set is also handed to mergeToFront so an\n // already-queued required card gets re-fronted rather than leapfrogged.\n const mandatoryWeighted = candidates.filter((w) => w.score === Number.POSITIVE_INFINITY);\n const optionalWeighted = candidates.filter((w) => w.score !== Number.POSITIVE_INFINITY);\n const supplyWeighted = [\n ...mandatoryWeighted,\n ...optionalWeighted.slice(0, Math.max(0, supplyLimit - mandatoryWeighted.length)),\n ];\n const mandatoryIds = new Set(mandatoryWeighted.map((w) => w.cardId));\n\n // Count well-indicated cards by final score. Cards above the threshold\n // are genuinely appropriate content; cards below are fallback filler\n // that survived only because no strategy hard-removed them.\n const wellIndicated = supplyWeighted.filter(\n (w) => w.score >= SessionController.WELL_INDICATED_SCORE\n ).length;\n\n // Build heterogeneous supply items in rank order (review items carry\n // reviewID; score is carried for the debug overlay).\n let report = replan ? 'Replan content:\\n' : 'Mixed content session created with:\\n';\n const supplyItems: StudySessionItem[] = supplyWeighted.map((w) => {\n const origin = getCardOrigin(w);\n const scoreStr = Number.isFinite(w.score) ? w.score.toFixed(2) : '+INF';\n report += `${origin === 'review' ? 'Review' : 'New'}: ${w.courseId}::${w.cardId} (score: ${scoreStr})\\n`;\n return this._buildSupplyItem(w, origin);\n });\n\n if (additive) {\n // Additive replan: merge candidates into front of existing queue.\n // Pass mandatory (+INF) ids so an already-queued required card is pulled\n // back to the front instead of being buried by fresh non-required cards.\n const added = this.supplyQ.mergeToFront(supplyItems, (item) => item.cardID, mandatoryIds);\n report += `Additive merge: ${added} cards added to front of supplyQ\\n`;\n } else if (replan) {\n // Atomic swap: replace entire supplyQ contents at once (no empty-queue window)\n this.supplyQ.replaceAll(supplyItems, (item) => item.cardID);\n } else {\n // Initial session setup: add items normally\n for (const item of supplyItems) {\n this.supplyQ.add(item, item.cardID);\n }\n }\n\n this.log(report);\n\n // [perf] parked: getWeightedContent stage timing\n // const tEnd = performance.now();\n // logger.info(\n // `[perf][SessionController] getWeightedContent(replan=${replan}): ` +\n // `sources=${(tSources - tGwc0).toFixed(0)}ms ` +\n // `mix=${(tMixed - tSources).toFixed(0)}ms ` +\n // `post=${(tEnd - tMixed).toFixed(0)}ms ` +\n // `total=${(tEnd - tGwc0).toFixed(0)}ms ` +\n // `[sources=${this.sources.length} fetchLimit=${fetchLimit} supplyLimit=${supplyLimit}]`\n // );\n\n return wellIndicated;\n }\n\n /**\n * Build a supply item from a weighted candidate. Review-origin cards carry\n * their `reviewID` so SRS outcome tracking and re-presentation work; new\n * cards do not. `score` is carried on both for the debug overlay.\n */\n private _buildSupplyItem(w: WeightedCard, origin = getCardOrigin(w)): StudySessionItem {\n const base = {\n cardID: w.cardId,\n courseID: w.courseId,\n contentSourceType: 'course' as const,\n contentSourceID: w.courseId,\n score: w.score,\n };\n if (origin === 'review') {\n const reviewItem: StudySessionReviewItem = { ...base, status: 'review', reviewID: w.reviewID! };\n return reviewItem;\n }\n const newItem: StudySessionNewItem = { ...base, status: 'new' };\n return newItem;\n }\n\n /**\n * Returns items that should be pre-hydrated.\n * Deterministic: top N items from each queue to ensure coverage.\n * Failed queue items will typically already be hydrated (from initial render).\n */\n private _getItemsToHydrate(): StudySessionItem[] {\n const items: StudySessionItem[] = [];\n // Prefetch a little deeper into supplyQ (the primary draw source) than the\n // intermittently-drawn failedQ.\n const SUPPLY_PREFETCH = 3;\n const FAILED_PREFETCH = 2;\n\n for (let i = 0; i < Math.min(SUPPLY_PREFETCH, this.supplyQ.length); i++) {\n items.push(this.supplyQ.peek(i));\n }\n for (let i = 0; i < Math.min(FAILED_PREFETCH, this.failedQ.length); i++) {\n items.push(this.failedQ.peek(i));\n }\n\n return items;\n }\n\n /**\n * Selects the next item to present to the user.\n *\n * The supplyQ is already rank-ordered (the pipeline + mixer did the mixing,\n * with `+INF` required cards floated to the front), so the primary path is a\n * deterministic front-to-back draw — no second new-vs-review mixer. The only\n * remaining decisions are (a) when the session ends and (b) when to interleave\n * a remediation card from failedQ. See decision doc §2/§3/§7.\n */\n private _selectNextItemToHydrate(): StudySessionItem | null {\n if (this.supplyQ.length === 0 && this.failedQ.length === 0) {\n // all queues empty - session is over (and course is complete?)\n return null;\n }\n\n // Near/at session end with no remediation pending and no guarantee active:\n // don't start a card we can't finish. A `_minCardsGuarantee` (set by a\n // replan's minFollowUpCards) holds the session open so a required follow-up\n // and its practice can still be drawn past the timer — see decision doc §3.\n if (\n this._secondsRemaining < 2 &&\n this.failedQ.length === 0 &&\n this._minCardsGuarantee <= 0\n ) {\n return null;\n }\n\n // Timer expired, no guarantee: drain remediation only, then end.\n if (this._secondsRemaining <= 0 && this._minCardsGuarantee <= 0) {\n return this.failedQ.length > 0 ? this.failedQ.peek(0) : null;\n }\n\n const supplyTop = this.supplyQ.length > 0 ? this.supplyQ.peek(0) : null;\n\n // A card guarantee exists to surface supplyQ follow-ups past the timer\n // (e.g. an intro's required WST + practice). Don't let the failed-interleave\n // consume those guaranteed draws.\n if (this._minCardsGuarantee > 0 && supplyTop) {\n return supplyTop;\n }\n\n // Failed-interleave (§7): pressure-based endgame + a light steady cadence so\n // remediation neither starves mid-session nor overruns the clock.\n if (this.failedQ.length > 0 && this._shouldInterleaveFailed(supplyTop !== null)) {\n return this.failedQ.peek(0);\n }\n\n if (supplyTop) {\n return supplyTop;\n }\n\n // Supply exhausted; remediation remains.\n if (this.failedQ.length > 0) {\n return this.failedQ.peek(0);\n }\n\n this.log(`No more cards available for the session!`);\n return null;\n }\n\n /** Supply draws between forced failed-queue interleaves (light steady cadence). */\n private static readonly FAILED_INTERLEAVE_EVERY = 4;\n /**\n * Slack (seconds) below which the endgame failed-pressure kicks in: when the\n * time left after clearing remediation drops under this, bias hard to failed\n * so the session doesn't end with un-cleared remediation. Mirrors the old\n * `availableTime > 20` ladder thresholds.\n */\n private static readonly FAILED_ENDGAME_SLACK_SECONDS = 20;\n\n /**\n * Whether to interleave a failed (remediation) card now instead of drawing\n * the supply head. Replaces the old `newBound`/`reviewBound` probability\n * ladder's failed path (decision doc §7).\n *\n * @param supplyAvailable - whether supplyQ has a card to draw instead.\n */\n private _shouldInterleaveFailed(supplyAvailable: boolean): boolean {\n if (this.failedQ.length === 0) return false;\n // Nothing else to draw — failed is all that's left.\n if (!supplyAvailable) return true;\n\n // Endgame pressure: as estimateCleanupTime → secondsRemaining, the time\n // left after clearing remediation shrinks; once it's under the slack,\n // prioritise failed so remediation isn't stranded by session end.\n const availableTime = this._secondsRemaining - this.estimateCleanupTime();\n if (availableTime <= SessionController.FAILED_ENDGAME_SLACK_SECONDS) return true;\n\n // Light steady interleave so failed doesn't starve while supply is healthy.\n return this._supplyDrawsSinceFailed >= SessionController.FAILED_INTERLEAVE_EVERY;\n }\n\n public async nextCard(\n action: SessionAction = 'dismiss-success'\n ): Promise<HydratedCard<TView> | null> {\n // [perf] parked: nextCard provenance/timing (awaitedReplan, wedgeRuns)\n // const tNext0 = performance.now();\n // let awaitedInFlightReplan = false;\n // let wedgeRuns = 0;\n // dismiss (or sort to failedQ) the current card\n this.dismissCurrentCard(action);\n\n // Decrement card guarantee counter\n if (this._minCardsGuarantee > 0) {\n this._minCardsGuarantee--;\n this.log(`[CardGuarantee] ${this._minCardsGuarantee} guaranteed cards remaining`);\n }\n\n // If a replan is in flight AND we have nothing queued to serve, wait for\n // it. When queues still have cards, draw from them immediately and let\n // the replan land asynchronously — blocking here adds visible lag\n // between cards for a marginal scoring-freshness benefit. The\n // wedge-breaker below handles the genuinely-empty case.\n if (\n this._replanPromise &&\n this.supplyQ.length === 0 &&\n this.failedQ.length === 0\n ) {\n this.log('nextCard: queues empty, awaiting in-flight replan before drawing');\n // awaitedInFlightReplan = true; // [perf] parked\n await this._replanPromise;\n }\n\n // --- Replan triggers ---\n //\n // Two flavors:\n //\n // (a) OPPORTUNISTIC PREFETCH (best-effort, may coalesce, may no-op):\n // `depletion` and `quality` triggers below. Their job is to make\n // replans happen *early*, so the user doesn't wait. They are\n // *not* responsible for making replans happen *at all* — if every\n // one of them gets eaten by coalescing or suppression, that's\n // fine. They are perf optimizations.\n //\n // (b) LOAD-BEARING WEDGE-BREAKER (correctness):\n // Below, right before the draw loop. Invariant: if the clock is\n // ticking and we'd otherwise serve null, the pipeline runs. No\n // coalesce, no latch, no flag. This is the *only* guarantee.\n //\n // Rule of thumb: a redundant pipeline run is a perf bug, a missing\n // pipeline run is a correctness bug. Bias toward the cheaper failure.\n\n // Opportunistic depletion: supplyQ running dry → background prefetch.\n // No latch — if this fires repeatedly when the pipeline keeps coming\n // back empty, the wedge-breaker's local backoff handles spin protection.\n //\n // Threshold sized to give the pipeline enough lead time to land the\n // replan before the user empties the queue. Previously hardcoded to 1,\n // which raced user pace against pipeline latency — fast users would hit\n // an empty queue mid-session and feel the wedge-breaker's synchronous\n // pipeline call as a \"hang\". DEPLETION_PREFETCH_THRESHOLD trades a\n // slightly earlier prefetch (which is anyway desirable for content\n // freshness) for a much more reliable lead time.\n if (\n this.supplyQ.length <= SessionController.DEPLETION_PREFETCH_THRESHOLD &&\n this._secondsRemaining > 0 &&\n !this._replanPromise\n ) {\n this._suppressQualityReplan = false; // burst is (nearly) consumed\n this.log(\n `[AutoReplan:depletion] supplyQ has ${this.supplyQ.length} card(s) ` +\n `(${this.failedQ.length} failed pending) with ${this._secondsRemaining}s remaining. ` +\n `Triggering background replan.`\n );\n // label is observability-only (overlay/logs); does not affect coalescing.\n // mode:'merge' preserves any already-queued cards (e.g. an undrawn\n // prescribed WST whose one-shot requireCards won't be re-asserted by this\n // bare replan) instead of replaceAll() wiping them. See mergeToFront.\n void this.requestReplan({ label: 'auto:depletion', mode: 'merge' });\n }\n\n // Opportunistic quality: few well-indicated cards remain.\n // Suppressed after a burst replan to avoid clobbering burst cards.\n const REPLAN_BUFFER = 3;\n if (\n !this._suppressQualityReplan &&\n this._wellIndicatedRemaining <= REPLAN_BUFFER &&\n this.supplyQ.length > 0 &&\n !this._replanPromise\n ) {\n this.log(\n `[AutoReplan:quality] ${this._wellIndicatedRemaining} well-indicated cards remaining ` +\n `(supplyQ: ${this.supplyQ.length}). Triggering background replan.`\n );\n // label is observability-only (overlay/logs); does not affect coalescing.\n void this.requestReplan({ label: 'auto:quality' });\n }\n\n if (this._secondsRemaining <= 0 && this.failedQ.length === 0 && this._minCardsGuarantee <= 0) {\n this._currentCard = null;\n endSessionTracking();\n void this._terminate();\n return null;\n }\n\n // Wedge-breaker (correctness path).\n //\n // If we'd otherwise be about to draw from empty queues with time on\n // the clock, run the pipeline. Bypasses requestReplan() coalesce\n // because coalescing into a previous run that we now know produced\n // insufficient content is the exact failure mode this defends against.\n //\n // Bounded by an empty-streak counter: if the pipeline consistently\n // returns nothing, we eventually give up and let the session end\n // gracefully rather than spin forever.\n const WEDGE_MAX_EMPTY_STREAK = 3;\n const WEDGE_BACKOFF_MS = 250;\n let wedgeEmptyStreak = 0;\n while (\n this._secondsRemaining > 0 &&\n this.supplyQ.length === 0 &&\n this.failedQ.length === 0\n ) {\n this.log(\n `[WedgeBreaker] All queues empty with ${this._secondsRemaining}s remaining. ` +\n `Running pipeline (attempt ${wedgeEmptyStreak + 1}/${WEDGE_MAX_EMPTY_STREAK}).`\n );\n await this._replanUncoalesced({ label: 'wedge-breaker' });\n // wedgeRuns++; // [perf] parked\n if (\n this.supplyQ.length === 0 &&\n this.failedQ.length === 0\n ) {\n wedgeEmptyStreak++;\n if (wedgeEmptyStreak >= WEDGE_MAX_EMPTY_STREAK) {\n this.log(\n `[WedgeBreaker] Pipeline returned no content ${WEDGE_MAX_EMPTY_STREAK} consecutive ` +\n `times. Giving up; session will end.`\n );\n break;\n }\n await new Promise((resolve) => setTimeout(resolve, WEDGE_BACKOFF_MS));\n } else {\n wedgeEmptyStreak = 0;\n }\n }\n\n // Try multiple cards in case some fail hydration (e.g., deleted from DB)\n const MAX_SKIP = 20;\n for (let attempt = 0; attempt < MAX_SKIP; attempt++) {\n const nextItem = this._selectNextItemToHydrate();\n if (!nextItem) {\n this._currentCard = null;\n endSessionTracking();\n void this._terminate();\n return null;\n }\n\n // Look up in hydration cache\n let card = this.hydrationService.getHydratedCard(nextItem.cardID);\n\n // If not ready, wait for it\n if (!card) {\n card = await this.hydrationService.waitForCard(nextItem.cardID);\n }\n\n // Remove from source queue now that we're consuming it\n this.removeItemFromQueue(nextItem);\n\n if (card) {\n // Trigger background hydration to maintain cache (async, non-blocking)\n await this.hydrationService.ensureHydratedCards();\n this._currentCard = card;\n\n // Record presentation for debugging. `origin` is the item's nature\n // (new vs review); `queueSource` is which controller queue it was drawn\n // from (supplyQ vs the remediation failedQ).\n const origin = nextItem.status === 'review' || nextItem.status === 'failed-review' ? 'review' :\n nextItem.status === 'new' || nextItem.status === 'failed-new' ? 'new' : 'failed';\n const queueSource = nextItem.status.startsWith('failed') ? 'failedQ' : 'supplyQ';\n\n recordCardPresentation(\n nextItem.cardID,\n nextItem.courseID,\n this.courseNameCache.get(nextItem.courseID),\n origin,\n queueSource,\n nextItem.score\n );\n\n // Tell the sources (a new card discharges a pipeline's intake valve).\n for (const source of this.sources) {\n source.notePresented?.({\n cardId: nextItem.cardID,\n courseId: nextItem.courseID,\n status: nextItem.status,\n });\n }\n\n // Snapshot queue state\n snapshotQueues(this.supplyQ.length, this.failedQ.length);\n\n // [perf] parked: per-draw nextCard timing\n // logger.info(\n // `[perf][nextCard] -> ${card.item.cardID} in ${(performance.now() - tNext0).toFixed(0)}ms ` +\n // `(awaitedReplan=${awaitedInFlightReplan} wedgeRuns=${wedgeRuns})`\n // );\n return card;\n }\n\n // Card failed hydration (deleted from DB?) — skip and clean up\n this.log(`Skipping card ${nextItem.cardID}: hydration failed, trying next`);\n if (isReview(nextItem)) {\n this.srsService.removeReview(nextItem.reviewID);\n }\n }\n\n this.log(`Exhausted ${MAX_SKIP} skip attempts finding a hydratable card`);\n this._currentCard = null;\n endSessionTracking();\n void this._terminate();\n return null;\n }\n\n /** Not awaited — the host renders the end screen off `nextCard()`'s null. */\n private _terminate(): void {\n void this.endSession().catch((e) => {\n logger.warn(`[SessionController] endSession failed: ${e}`);\n });\n }\n\n /**\n * Public API for processing user responses to cards.\n * @param cardRecord User's response record\n * @param cardHistory Promise resolving to the card's history\n * @param courseRegistrationDoc User's course registration document\n * @param currentCard Current study session record\n * @param courseId Course identifier\n * @param cardId Card identifier\n * @param maxAttemptsPerView Maximum attempts allowed per view\n * @param maxSessionViews Maximum session views for this card\n * @param sessionViews Current number of session views\n * @returns ResponseResult with navigation and UI instructions\n */\n public async submitResponse(\n cardRecord: CardRecord,\n cardHistory: Promise<CardHistory<CardRecord>>,\n courseRegistrationDoc: CourseRegistrationDoc,\n currentCard: StudySessionRecord,\n courseId: string,\n cardId: string,\n maxAttemptsPerView: number,\n maxSessionViews: number,\n sessionViews: number\n ): Promise<ResponseResult> {\n const studySessionItem: StudySessionItem = {\n ...currentCard.item,\n };\n\n const result = await this.services.response.processResponse(\n cardRecord,\n cardHistory,\n studySessionItem,\n courseRegistrationDoc,\n currentCard,\n courseId,\n cardId,\n maxAttemptsPerView,\n maxSessionViews,\n sessionViews\n );\n\n // Surface the processed outcome to any registered observers (e.g. a\n // difficulty-booster that bumps session hints on a failed exercise tag).\n // Runs after ELO/SRS recording, before the caller navigates. Isolated so\n // a faulty observer can't break response handling.\n await this._notifyOutcomeObservers(cardRecord, currentCard, result);\n\n return result;\n }\n\n private dismissCurrentCard(action: SessionAction = 'dismiss-success') {\n if (this._currentCard) {\n // this.log(`Running dismissCurrentCard on ${this._currentCard!.qualifiedID}`);\n // if (action.includes('dismiss')) {\n // if (this._currentCard.status === 'review' ||\n // this._currentCard.status === 'failed-review') {\n // removeScheduledCardReview(this.user.getUsername(),\n // (this._currentCard as StudySessionReviewItem).reviewID);\n // this.log(`Dismissed review card: ${this._currentCard.qualifiedID}`)\n // }\n // }\n\n if (action === 'dismiss-success') {\n // Remove from hydration cache to free memory\n this.hydrationService.removeCard(this._currentCard.item.cardID);\n // schedule a review - currently done in Study.vue\n } else if (action === 'marked-failed') {\n // Card stays in hydration cache for re-use (no removeCard call)\n\n let failedItem: StudySessionFailedItem;\n\n if (isReview(this._currentCard.item)) {\n failedItem = {\n cardID: this._currentCard.item.cardID,\n courseID: this._currentCard.item.courseID,\n contentSourceID: this._currentCard.item.contentSourceID,\n contentSourceType: this._currentCard.item.contentSourceType,\n status: 'failed-review',\n reviewID: this._currentCard.item.reviewID,\n };\n } else {\n failedItem = {\n cardID: this._currentCard.item.cardID,\n courseID: this._currentCard.item.courseID,\n contentSourceID: this._currentCard.item.contentSourceID,\n contentSourceType: this._currentCard.item.contentSourceType,\n status: 'failed-new',\n };\n }\n\n this.failedQ.add(failedItem, failedItem.cardID);\n // Reset the failed-interleave cadence so a just-failed card gets spacing:\n // it now waits FAILED_INTERLEAVE_EVERY supply draws before being\n // re-presented, rather than being instantly \"due\" because the counter\n // had already climbed during a healthy supply run. (Endgame pressure in\n // _shouldInterleaveFailed still overrides this near session end.)\n this._supplyDrawsSinceFailed = 0;\n } else if (action === 'dismiss-error') {\n // Remove from cache on error as well\n this.hydrationService.removeCard(this._currentCard.item.cardID);\n } else if (action === 'dismiss-failed') {\n // Remove from cache - card has been fully processed after failure cleanup\n this.hydrationService.removeCard(this._currentCard.item.cardID);\n }\n }\n }\n\n /**\n * Remove an item from its source queue after consumption by nextCard().\n */\n private removeItemFromQueue(item: StudySessionItem): void {\n // Durable-until-drawn requirements: a caller may place a card ID in the\n // session-durable `requireCards` (via mergeSessionHints) so every later\n // replan re-asserts it at +INF until it actually surfaces — e.g. a\n // prescribed intro follow-up that must survive the replace-mode burst/auto\n // replans that would otherwise clobber a one-shot requirement. The\n // requirement is satisfied the instant the card is drawn, so clear it here\n // (the single consumption choke-point) to stop it being re-injected forever\n // and to bound accumulation. Generic: card-ID only, no domain vocabulary.\n this._clearDurableRequirement(item.cardID);\n\n // Record the draw immediately (earlier than _sessionRecord, which waits for\n // a response) so getWeightedContent can keep this card out of supplyQ on any\n // replan that lands after this draw.\n this._servedCardIds.add(item.cardID);\n\n // Item should be at the front of one of the two queues. Track the\n // failed-interleave cadence: reset on a failed draw, advance on a supply draw.\n if (this.failedQ.peek(0)?.cardID === item.cardID) {\n this.failedQ.dequeue((queueItem) => queueItem.cardID);\n this._supplyDrawsSinceFailed = 0;\n } else if (this.supplyQ.peek(0)?.cardID === item.cardID) {\n this.supplyQ.dequeue((queueItem) => queueItem.cardID);\n this._supplyDrawsSinceFailed++;\n if (this._wellIndicatedRemaining > 0) {\n this._wellIndicatedRemaining--;\n }\n }\n }\n\n /**\n * Remove a satisfied card ID from the durable session-hint `requireCards`\n * list. Called when a card is consumed (see removeItemFromQueue). No-op if\n * the card was not a durable requirement.\n *\n * Matches literal IDs only: a glob/pattern requirement (which may stand for\n * several cards) is NOT considered satisfied by a single draw and is left in\n * place — durable patterns are the caller's responsibility, one-shot `hints`\n * remain the right tool for them.\n */\n private _clearDurableRequirement(cardID: string): void {\n const req = this._sessionHints?.requireCards;\n if (!req || req.length === 0) return;\n const next = req.filter((id) => id !== cardID);\n if (next.length === req.length) return; // not a durable requirement\n this._sessionHints = {\n ...this._sessionHints!,\n requireCards: next.length > 0 ? next : undefined,\n };\n this.log(`[Replan] Durable requirement satisfied & cleared on draw: ${cardID}`);\n }\n\n /**\n * End the session and record learning outcomes.\n *\n * This method aggregates all responses from the session and records a\n * UserOutcomeRecord if evolutionary orchestration is enabled.\n */\n /**\n * Idempotent. Called from every `nextCard()` path that returns null; hosts\n * should also call it with `'abandoned'` when tearing down mid-session.\n */\n public async endSession(reason: 'closed' | 'abandoned' = 'closed'): Promise<void> {\n if (this._sessionClosed) return;\n this._sessionClosed = true;\n\n clearInterval(this._intervalHandle);\n setDebugSessionId(undefined);\n\n // Closed even with zero responses — \"answered nothing\" is itself a finding.\n await this._closeSessionDoc(reason);\n\n if (!this._sessionRecord || this._sessionRecord.length === 0) {\n return;\n }\n\n const questionRecords = this._sessionRecord\n .flatMap((r) => r.records)\n .filter((r): r is QuestionRecord => (r as any).userAnswer !== undefined);\n\n if (questionRecords.length === 0) {\n return;\n }\n\n // We need to access the orchestration context.\n // Ideally this would be passed in or available via services.\n // For now, we'll try to get it from one of the content sources if possible,\n // or skip if we can't access it.\n\n // Try to find a source that supports orchestration\n let orchestrationContext = null;\n const strategies: string[] = [];\n\n for (const source of this.sources) {\n if (source.getOrchestrationContext) {\n try {\n orchestrationContext = await source.getOrchestrationContext();\n // Also try to get strategy IDs if available on the source (e.g. Pipeline)\n if ((source as any).getStrategyIds) {\n strategies.push(...(source as any).getStrategyIds());\n }\n } catch (e) {\n logger.warn(`[SessionController] Failed to get orchestration context: ${e}`);\n }\n if (orchestrationContext) break;\n }\n }\n\n if (!orchestrationContext) {\n logger.debug('[SessionController] No orchestration context available, skipping outcome recording');\n return;\n }\n\n // Use current time as period end\n const periodEnd = new Date().toISOString();\n // Use session start time as period start\n const periodStart = new Date(this.startTime).toISOString();\n\n await recordUserOutcome(\n orchestrationContext,\n periodStart,\n periodEnd,\n questionRecords,\n strategies\n );\n }\n\n private async _closeSessionDoc(reason: 'closed' | 'abandoned'): Promise<void> {\n // Ordered behind the open write; it swallows its own errors.\n if (this._openDocPromise) await this._openDocPromise;\n\n const doc = this._sessionDoc;\n if (!doc) return;\n\n const records = this._sessionRecord.flatMap((r) => r.records);\n const questionRecords = records.filter(isQuestionRecord);\n\n try {\n const closed: StudySessionDoc = {\n ...doc,\n status: reason,\n endTime: new Date().toISOString(),\n tally: {\n cardsPresented: this._sessionRecord.length,\n responses: records.length,\n correct: questionRecords.filter((r) => r.isCorrect).length,\n incorrect: questionRecords.filter((r) => !r.isCorrect).length,\n failedQRemaining: this.failedQ.length,\n secondsRemaining: Math.max(0, this._secondsRemaining),\n },\n runs: [...this._runLog],\n eloEvents: [...this._eloLog],\n finalHints: this._sessionHints,\n stateAtEnd: await this._captureState('end'),\n };\n this._sessionDoc = closed;\n await this.dataLayer.getUserDB().putStudySession(closed);\n this.log(\n `[Session] Session record ${closed._id} -> ${reason} ` +\n `(${closed.tally!.cardsPresented} cards, ${closed.tally!.responses} responses, ` +\n `${this._runLog.length} pipeline runs)`\n );\n } catch (e) {\n logger.warn(`[SessionController] Failed to close session record: ${e}`);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsOA,MAAM,uBAAuB;;AAG7B,SAAS,KAAK,GAAmB;AAC/B,QAAO,OAAO,EAAE,YAAY,EAAE,CAAC;;AAGjC,SAAS,UAAU,GAAuC;AACxD,QAAO;EACL,QAAQ,EAAE;EACV,QAAQ,EAAE;EACV,GAAI,EAAE,YAAY,EAAE,WAAW,EAAE,WAAW,GAAG,EAAE;EACjD,GAAI,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,GAAG,EAAE;EAE9C,OAAO,OAAO,SAAS,EAAE,WAAW,GAAG,KAAK,EAAE,WAAW,GAAG;EAC5D,UAAU,EAAE;EACb;;AAGH,SAAS,eAAe,GAA4C;AAClE,QAAO;EACL,GAAG,UAAU,EAAE;EACf,OAAO,EAAE,WACN,QAAQ,MAAM,EAAE,WAAW,SAAS,CACpC,KAAK,OAAO;GACX,cAAc,EAAE;GAChB,QAAQ,EAAE;GACV,OAAO,KAAK,EAAE,MAAM;GACpB,QAAQ,EAAE;GACX,EAAE;EACN;;AAGH,SAAS,iBAAiB,GAAuC;AAC/D,QAAO;EACL,GAAG;EACH,SAAS,KAAK,EAAE,QAAQ;EACxB,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;KACpC,WAAW,QAAQ;KACnB,SAAS,gBAAgB,QAAQ,MAAM,EAAE,UAAU,CAAC;KACpD,WAAW,gBAAgB,QAAQ,MAAM,CAAC,EAAE,UAAU,CAAC;KACvD,kBAAkB,KAAK,QAAQ;KAC/B,kBAAkB,KAAK,IAAI,GAAG,KAAK,kBAAkB;KACtD;IACD,MAAM,CAAC,GAAG,KAAK,QAAQ;IACvB,WAAW,CAAC,GAAG,KAAK,QAAQ;IAC5B,YAAY,KAAK;IACjB,YAAY,MAAM,KAAK,cAAc,MAAM;IAC5C;AACD,QAAK,cAAc;AACnB,SAAM,KAAK,UAAU,WAAW,CAAC,gBAAgB,OAAO;AACxD,QAAK,IACH,4BAA4B,OAAO,IAAI,MAAM,OAAO,IAChD,OAAO,MAAO,eAAe,UAAU,OAAO,MAAO,UAAU,cAChE,KAAK,QAAQ,OAAO,iBACxB;WACM,GAAG;AACV,UAAO,KAAK,uDAAuD,IAAI"}
1
+ {"version":3,"file":"SessionController.mjs","names":[],"sources":["../../src/study/SessionController.ts"],"sourcesContent":["import { SrsService } from './services/SrsService';\nimport { EloService } from './services/EloService';\nimport { ResponseProcessor } from './services/ResponseProcessor';\nimport { CardHydrationService, HydratedCard } from './services/CardHydrationService';\nimport { ItemQueue } from './ItemQueue';\nimport {\n isReview,\n StudyContentSource,\n StudySessionFailedItem,\n StudySessionItem,\n StudySessionNewItem,\n StudySessionReviewItem,\n} from '@db/impl/couch';\n\nimport { CardRecord, CardHistory, CourseRegistrationDoc, QuestionRecord, isQuestionRecord } from '@db/core';\nimport { DocType } from '@db/core/types/types-legacy';\nimport {\n makeStudySessionId,\n newSessionId,\n type SessionEloEvent,\n type SessionStateSnapshot,\n type SessionStateSnapshotProvider,\n type StudySessionDoc,\n type StudySessionRunCard,\n type StudySessionRunCardTrail,\n type StudySessionRunSummary,\n} from '@db/core/types/studySession';\nimport { recordUserOutcome } from '@db/core/orchestration/recording';\nimport { Loggable } from '@db/util';\nimport { perfMark, perfMeasure } from '@db/util/perfMarks';\nimport {\n getCardOrigin,\n WeightedCard,\n getSrsBacklogDebug,\n getStrategyPressureDebug,\n setDebugSessionId,\n drainCapturedRuns,\n} from '@db/core/navigators';\nimport type { PipelineRunReport, RunReportCard } from '@db/core/navigators';\nimport { ReplanHints } from '@db/core/navigators/generators/types';\nimport { mergeHints } from '@db/core/navigators/Pipeline';\nimport type { RegulatorReading } from '@db/core/navigators/regulators';\nimport { sessionVersions } from '@db/core/versionStamps';\nimport { SourceMixer, QuotaRoundRobinMixer, SourceBatch } from './SourceMixer';\nimport { captureMixerRun } from './MixerDebugger';\nimport { startSessionTracking, recordCardPresentation, snapshotQueues, endSessionTracking, clearStaleSessionDebugState } from './SessionDebugger';\nimport {\n registerActiveController,\n type SessionDebugSnapshot,\n type SessionDrawnCardDebug,\n type SessionQueueDebug,\n type SessionQueueItemDebug,\n} from './SessionOverlay';\n\n// ReplanHints is defined in generators/types to avoid circular dependencies.\n// Re-exported here for backward compatibility.\nexport type { ReplanHints } from '@db/core/navigators/generators/types';\n\n/**\n * Options for requesting a mid-session replan.\n *\n * All fields are optional — callers can pass just the fields they need.\n * When omitted, defaults match the existing behaviour (full 20-card\n * replace with no hints).\n */\nexport interface ReplanOptions {\n /** Scoring hints forwarded to the pipeline (boost/exclude/require). */\n hints?: ReplanHints;\n /**\n * Session-durable scoring hints. Unlike `hints` (one-shot, applied to\n * exactly the run this replan triggers), `sessionHints` are stashed on\n * the controller and re-merged into *every* subsequent pipeline run for\n * the remainder of the session — including the bare auto-replans\n * (depletion/quality) that carry no caller hints, and the wedge-breaker.\n *\n * Use for \"emphasis that should outlive a single queue rebuild\" — e.g.\n * boosting a just-failed concept tag, or a post-lesson concept boost set\n * at session start. Without this, a one-shot `hints` boost evaporates on\n * the next replan and the freshly-rebuilt (replace-mode) queue clobbers\n * whatever it surfaced.\n *\n * Semantics (KISS): setting `sessionHints` *replaces* the prior session\n * hints wholesale (caller beware — no accumulation, no decay). They live\n * until session end or until explicitly overwritten. Normal usage applies\n * a fixed boost, so repeated identical requests are no-ops.\n *\n * Merged with per-run `hints` via the pipeline's `mergeHints` (boosts\n * multiply, require/exclude lists concatenate).\n */\n sessionHints?: ReplanHints;\n /**\n * Like `sessionHints`, but *merged* into the existing session-durable hints\n * (via `mergeHints`) instead of replacing them. Use when emphasis should\n * *accumulate* across replans rather than clobber — e.g. introducing a second\n * concept mid-session must not wipe the first concept's boost, nor any\n * `difficultyBooster`/`conceptBackoff` state on other concepts.\n *\n * Merge semantics (see `mergeHints`): boosts MULTIPLY, require/exclude lists\n * concat-dedup. Re-emphasising the *same* tag therefore compounds — callers\n * boosting a tag they may have already boosted should clamp at the call site.\n *\n * If both `sessionHints` and `mergeSessionHints` are supplied, the replace is\n * applied first, then the merge — but they are normally mutually exclusive.\n */\n mergeSessionHints?: ReplanHints;\n /**\n * Maximum number of new cards to return from the pipeline.\n * Default: 20 (the standard session batch size).\n */\n limit?: number;\n /**\n * How to integrate the new cards into the existing supplyQ.\n * - `'replace'` (default): atomically swap the entire supplyQ.\n * - `'merge'`: insert new cards at the front, keeping existing cards.\n */\n mode?: 'replace' | 'merge';\n /**\n * Guarantee that at least this many cards will be served after the\n * replan, even if the session timer has expired. Prevents intro cards\n * from surfacing at the end of a session with zero follow-up exercise.\n * Decremented on each card draw while active.\n */\n minFollowUpCards?: number;\n /**\n * Human-readable label for debugging / provenance.\n * Appears in console logs and in card provenance entries created\n * by ephemeral hint application.\n */\n label?: string;\n}\n\nexport interface StudySessionRecord {\n card: {\n course_id: string;\n card_id: string;\n card_elo: number;\n tags: string[];\n };\n item: StudySessionItem;\n records: CardRecord[];\n}\n\nimport { DataLayerProvider } from '@db/core';\nimport { logger } from '@db/util/logger';\n\nexport type SessionAction =\n | 'dismiss-success'\n | 'dismiss-failed'\n | 'marked-failed'\n | 'dismiss-error';\n\nexport interface ResponseResult {\n // Navigation\n nextCardAction: Exclude<SessionAction, 'dismiss-error'> | 'none';\n shouldLoadNextCard: boolean;\n\n /**\n * When true, the card requested deferred advancement via `deferAdvance`.\n * The record was logged and ELO updated, but navigation was suppressed.\n * StudySession should stash `nextCardAction` and wait for a\n * `ready-to-advance` event from the card before calling `nextCard()`.\n */\n deferred?: boolean;\n\n // UI Data (let view decide how to render)\n isCorrect: boolean;\n performanceScore?: number; // for shadow color calculation\n\n // Cleanup\n shouldClearFeedbackShadow: boolean;\n}\n\n/**\n * Read-only snapshot of a single processed response, handed to every\n * registered {@link OutcomeObserver} after ELO/SRS have been recorded.\n *\n * Only emitted for question records (non-question dismisses are skipped).\n */\nexport interface SessionOutcome {\n /** The user's response. Includes `isCorrect`, `performance`, `priorAttemps`. */\n readonly record: QuestionRecord;\n /**\n * The card that was answered, including its `tags` — the primary key an\n * observer matches against (e.g. `gpc:exercise:*`). `card_elo` reflects\n * pre-update state; the ELO write for this response is already in flight.\n */\n readonly card: StudySessionRecord['card'];\n /** The navigation decision produced for this response (read-only). */\n readonly result: Readonly<ResponseResult>;\n}\n\n/**\n * The narrow capability surface handed to an {@link OutcomeObserver}. This is\n * the *only* way an observer can affect the session — it cannot touch ELO,\n * the queues, the timer, or mutate the `ResponseResult`. A misbehaving\n * observer degrades to \"wrong boost\", never \"corrupted session\".\n */\nexport interface SessionControls {\n /** Current session-durable hints, or null. For read-modify-write. */\n getSessionHints(): ReplanHints | null;\n /** Replace the session-durable hints wholesale (no decay). */\n setSessionHints(hints: ReplanHints | null): void;\n /**\n * Merge `hints` into the existing session-durable hints via the pipeline's\n * `mergeHints` (boosts multiply, require/exclude lists concat-dedup).\n * Convenience for the common \"add a boost on top of what's there\" case.\n * Note: multiplicative + no decay — clamp boost factors yourself if a\n * repeatedly-failed tag could compound unboundedly.\n */\n mergeSessionHints(hints: ReplanHints): void;\n /** Request a replan (e.g. `{ mode: 'merge' }` for immediate visibility). */\n requestReplan(opts?: ReplanOptions): Promise<void>;\n}\n\n/**\n * A consumer-supplied hook invoked after each question response is processed.\n *\n * Fires on *every* question response (gate inside on `record.isCorrect` /\n * `result.nextCardAction` as needed). Awaited but isolated: a throwing\n * observer is caught and logged, never wedging the session. Keep the\n * synchronous body cheap and `void` any long work (e.g. a triggered replan)\n * so you don't stall navigation.\n *\n * Registered via `StudySessionConfig.outcomeObservers` → constructor options.\n */\nexport type OutcomeObserver = (\n outcome: SessionOutcome,\n controls: SessionControls\n) => void | Promise<void>;\n\n/** Unselected cards persisted per run, after the selected ones. */\nconst PERSISTED_RUNNERS_UP = 5;\n\n/** 4 significant figures: keeps 6.4e-7 distinguishable from 0 without 17-digit floats. */\nfunction sig4(x: number): number {\n return Number(x.toPrecision(4));\n}\n\nfunction toRunCard(c: RunReportCard): StudySessionRunCard {\n return {\n cardId: c.cardId,\n origin: c.origin,\n ...(c.generator ? { generator: c.generator } : {}),\n ...(c.required ? { required: c.required } : {}),\n // A required card's score is infinite, which JSON can't hold: say so with null.\n score: Number.isFinite(c.finalScore) ? sig4(c.finalScore) : null,\n selected: c.selected,\n };\n}\n\nfunction toRunCardTrail(c: RunReportCard): StudySessionRunCardTrail {\n return {\n ...toRunCard(c),\n trail: c.provenance\n .filter((p) => p.action !== 'passed')\n .map((p) => ({\n strategyName: p.strategyName,\n action: p.action,\n score: sig4(p.score),\n reason: p.reason,\n })),\n };\n}\n\nfunction persistedReading(r: RegulatorReading): RegulatorReading {\n return {\n ...r,\n urgency: sig4(r.urgency),\n multiplier: sig4(r.multiplier),\n inputs: Object.fromEntries(Object.entries(r.inputs).map(([k, v]) => [k, sig4(v)])),\n };\n}\n\n/** `run.cards` is selected-then-near-misses, each in score order. */\nfunction persistedRunCards(run: PipelineRunReport): StudySessionRunCard[] {\n const selected = run.cards.filter((c) => c.selected);\n const runnersUp = run.cards.filter((c) => !c.selected).slice(0, PERSISTED_RUNNERS_UP);\n return [...selected, ...runnersUp].map(toRunCard);\n}\n\nfunction persistedUnselectedNew(\n u: NonNullable<PipelineRunReport['unselectedNew']>\n): StudySessionRunSummary['unselectedNew'] {\n return {\n ...(u.nextInLine ? { nextInLine: toRunCardTrail(u.nextInLine) } : {}),\n ...(u.topGenerated ? { topGenerated: toRunCardTrail(u.topGenerated) } : {}),\n };\n}\n\ninterface SessionServices {\n response: ResponseProcessor;\n}\n\nexport class SessionController<TView = unknown> extends Loggable {\n _className = 'SessionController';\n\n public services: SessionServices;\n private srsService: SrsService;\n private eloService: EloService;\n private hydrationService: CardHydrationService<TView>;\n private mixer: SourceMixer;\n private dataLayer: DataLayerProvider;\n private courseNameCache: Map<string, string> = new Map();\n\n /**\n * Default pipeline batch size for new-card planning.\n * Set via constructor options; falls back to 20 when not specified.\n * Individual replans can override via `ReplanOptions.limit`.\n */\n private _defaultBatchLimit: number = 20;\n\n private sources: StudyContentSource[];\n // dataLayer and getViewComponent now injected into CardHydrationService\n private _sessionRecord: StudySessionRecord[] = [];\n public set sessionRecord(r: StudySessionRecord[]) {\n this._sessionRecord = r;\n }\n\n // Session card stores\n private _currentCard: HydratedCard<TView> | null = null;\n\n /**\n * The single supply queue: `new` + `review` items interleaved in pipeline\n * rank order (the mixer's score-ordered, source-interleaved output, with\n * `+INF` required cards floated to the front). Drawn front-to-back; reviews\n * and new compete on one cross-comparable scale rather than being re-mixed\n * by a probability gate. Replaced/re-ranked wholesale on replan. See\n * `docs/decision-single-supply-queue.md`.\n */\n private supplyQ: ItemQueue<StudySessionItem> = new ItemQueue<StudySessionItem>();\n private failedQ: ItemQueue<StudySessionFailedItem> = new ItemQueue<StudySessionFailedItem>();\n // END Session card stores\n\n /**\n * Supply draws since the last failed-queue *event* (a failed draw, or a card\n * entering failedQ on failure). Drives the light steady failed-interleave\n * (§7): after this many consecutive supply draws, a pending failed card is\n * drawn so remediation doesn't starve mid-session. Incremented on each supply\n * draw; reset to 0 both when a failed card is drawn AND when one is added to\n * failedQ — the latter gives a just-failed card spacing instead of an instant\n * retry (the counter would otherwise already be ≥ threshold from the preceding\n * supply run).\n */\n private _supplyDrawsSinceFailed: number = 0;\n\n /**\n * Promise tracking a currently in-progress replan, or null if idle.\n * Used by nextCard() to await completion before drawing from queues.\n */\n private _replanPromise: Promise<void> | null = null;\n\n /**\n * Reason for the replan currently executing in `_runReplan`, surfaced by the\n * debug overlay's spinner. The caller's `opts.label` when present, else\n * `'(auto)'`. Only meaningful while `_replanPromise` is non-null; cleared\n * when the in-flight chain settles.\n */\n private _activeReplanLabel: string | null = null;\n\n /**\n * Number of well-indicated supply cards remaining before the queue\n * degrades to poorly-indicated content. Decremented on each supplyQ\n * draw; when it hits 0, a replan is triggered automatically\n * (user state has changed from completing good cards).\n */\n private _wellIndicatedRemaining: number = 0;\n\n /**\n * When true, suppresses the quality-based auto-replan trigger in\n * nextCard(). Set after a burst replan (small limit) to prevent the\n * auto-replan from clobbering the burst cards before they're consumed.\n * Cleared when the depletion-triggered replan fires (supplyQ exhausted).\n */\n private _suppressQualityReplan: boolean = false;\n\n /**\n * When > 0, the session timer cannot end the session. Decremented on\n * each nextCard() draw. Set by replans that include `minFollowUpCards`.\n */\n private _minCardsGuarantee: number = 0;\n\n /**\n * Session-durable scoring hints. Re-merged into every pipeline run for\n * the rest of the session (initial plan + every replan, including bare\n * auto-replans and the wedge-breaker), via `_applyHintsToSources`.\n *\n * Set by `setSessionHints()` (e.g. session-start post-lesson boost) or by\n * any replan carrying `ReplanOptions.sessionHints` (e.g. a just-failed\n * concept boost). Replace semantics, no decay — lives until overwritten\n * or session end. See `ReplanOptions.sessionHints` for rationale.\n *\n * Note: the controller-managed auto-excludes (current card, session\n * record, imminent draw) are intentionally NOT folded in here — those are\n * recomputed per-run in `_runReplan` and would otherwise go stale.\n */\n private _sessionHints: ReplanHints | null = null;\n\n /**\n * Card IDs that have been *served* (drawn/consumed) this session. Populated\n * at the single consumption choke-point (removeItemFromQueue), so it reflects\n * a draw the instant it happens — earlier than `_sessionRecord`, which only\n * lands once the card is *responded to*.\n *\n * Used to keep already-served cards out of supplyQ on every (re)plan, across\n * ALL origins: a `new` card shown once must never re-enter, and once replans\n * re-pull reviews, an answered/in-flight review must not re-enter the supply\n * before its SRS reschedule clears the due-window (the review-loop guard,\n * decision doc §4). This is the general guard against re-presentation —\n * including the case where a replan in flight captured a now-drawn card (e.g.\n * a +INF require-injected follow-up the depletion prefetch grabbed just before\n * it was drawn). failedQ is separate and controller-owned, so failed cards\n * legitimately recur there without being gated here.\n */\n private _servedCardIds: Set<string> = new Set();\n\n /**\n * Consumer-supplied hooks invoked after each question response is processed.\n * Seeded from constructor options (threaded from\n * `StudySessionConfig.outcomeObservers`). See {@link OutcomeObserver}.\n */\n private _outcomeObservers: OutcomeObserver[] = [];\n\n /**\n * Lazily-built, stable capability object handed to observers. Bound to\n * `this`; constructed once so observers can rely on referential identity.\n */\n private _sessionControls: SessionControls | null = null;\n\n /**\n * Minted at construction so the bootstrap pipeline run in `prepareSession()`\n * can carry it. Stamped onto every CardRecord and pipeline run this session.\n */\n public readonly sessionId: string;\n\n /** Host-supplied. Without it, no durable session doc is written. */\n private _courseId?: string;\n private _stateSnapshotProvider?: SessionStateSnapshotProvider;\n\n private _sessionDoc: StudySessionDoc | null = null;\n\n /**\n * Awaited by the close path — the open write is slow (time-boxed snapshot)\n * and would otherwise land last, leaving a finished session marked `open`.\n */\n private _openDocPromise: Promise<void> | null = null;\n\n private _runLog: StudySessionRunSummary[] = [];\n private static readonly MAX_LOGGED_RUNS = 100;\n\n /**\n * Per-response ELO exchanges as they resolve (see `SessionEloEvent`). Fed by\n * the ResponseProcessor's `onEloEvent` sink; flushed to the session doc at\n * close. Bounded so a runaway session can't grow it without limit.\n */\n private _eloLog: SessionEloEvent[] = [];\n private static readonly MAX_LOGGED_ELO_EVENTS = 2000;\n\n /** Guards `endSession()` against the several termination paths racing it. */\n private _sessionClosed: boolean = false;\n\n private startTime: Date;\n private endTime: Date;\n private _secondsRemaining: number;\n public get secondsRemaining(): number {\n return this._secondsRemaining;\n }\n /** True when a card guarantee is active, preventing timer-based session end. */\n public get hasCardGuarantee(): boolean {\n return this._minCardsGuarantee > 0;\n }\n public get report(): string {\n const supplyCount = this.supplyQ.dequeueCount;\n const supplyWord = supplyCount === 1 ? 'card' : 'cards';\n return `${supplyCount} supply ${supplyWord} drawn`;\n }\n public get detailedReport(): string {\n return this.supplyQ.toString + '\\n' + this.failedQ.toString;\n }\n // @ts-expect-error NodeJS.Timeout type not available in browser context\n private _intervalHandle: NodeJS.Timeout;\n\n /**\n * @param sources - Array of content sources to mix for the session\n * @param time - Session duration in seconds\n * @param dataLayer - Data layer provider\n * @param getViewComponent - Function to resolve view components\n * @param mixer - Optional source mixer strategy (defaults to QuotaRoundRobinMixer)\n * @param options - Optional session-level configuration\n * @param options.defaultBatchLimit - Default supply working-set size (default: 20).\n * Smaller values for newer users cause more frequent replans, keeping plans\n * aligned with rapidly-changing user state.\n */\n constructor(\n sources: StudyContentSource[],\n time: number,\n dataLayer: DataLayerProvider,\n getViewComponent: (viewId: string) => TView,\n mixer?: SourceMixer,\n options?: {\n defaultBatchLimit?: number;\n outcomeObservers?: OutcomeObserver[];\n /** Omit to run without durable session recording. */\n courseId?: string;\n stateSnapshotProvider?: SessionStateSnapshotProvider;\n }\n ) {\n super();\n\n this.sessionId = newSessionId();\n setDebugSessionId(this.sessionId);\n\n this.dataLayer = dataLayer;\n this.mixer = mixer || new QuotaRoundRobinMixer();\n this.srsService = new SrsService(dataLayer.getUserDB());\n this.eloService = new EloService(dataLayer, dataLayer.getUserDB());\n\n this.hydrationService = new CardHydrationService<TView>(\n getViewComponent,\n (courseId: string) => dataLayer.getCourseDB(courseId),\n () => this._getItemsToHydrate()\n );\n\n this.services = {\n response: new ResponseProcessor(this.srsService, this.eloService, (event) =>\n this._recordEloEvent(event)\n ),\n };\n\n this.sources = sources;\n this.startTime = new Date();\n this._secondsRemaining = time;\n this.endTime = new Date(this.startTime.valueOf() + 1000 * this._secondsRemaining);\n\n if (options?.defaultBatchLimit !== undefined) {\n this._defaultBatchLimit = options.defaultBatchLimit;\n }\n if (options?.outcomeObservers?.length) {\n this._outcomeObservers = [...options.outcomeObservers];\n }\n this._courseId = options?.courseId;\n this._stateSnapshotProvider = options?.stateSnapshotProvider;\n\n this.log(`Session constructed:\n sessionId: ${this.sessionId}\n startTime: ${this.startTime}\n endTime: ${this.endTime}\n defaultBatchLimit: ${this._defaultBatchLimit}`);\n\n // Expose this (now the most-recently-constructed) controller to the debug\n // overlay (window.skuilder.session.dbgOverlay()). A new session overwrites\n // the prior handle; no-op overhead when the overlay is never opened.\n registerActiveController(this);\n }\n\n private tick() {\n this._secondsRemaining = Math.floor((this.endTime.valueOf() - Date.now()) / 1000);\n // this.log(this.secondsRemaining);\n\n if (this._secondsRemaining <= 0) {\n clearInterval(this._intervalHandle);\n }\n }\n\n /**\n * Returns a rough, erring toward conservative, guess at\n * the amount of time the failed cards queue will require\n * to clean up.\n *\n * (seconds)\n */\n private estimateCleanupTime(): number {\n let time: number = 0;\n for (let i = 0; i < this.failedQ.length; i++) {\n const c = this.failedQ.peek(i);\n // this.log(`Failed card ${c.qualifiedID} found`)\n\n const record = this._sessionRecord.find((r) => r.item.cardID === c.cardID);\n let cardTime = 0;\n\n if (record) {\n // this.log(`Card Record Found...`);\n for (let j = 0; j < record.records.length; j++) {\n cardTime += record.records[j].timeSpent;\n }\n cardTime = cardTime / record.records.length;\n time += cardTime;\n }\n }\n\n const ret: number = time / 1000;\n this.log(`Failed card cleanup estimate: ${Math.round(ret)}`);\n return ret;\n }\n\n public async prepareSession() {\n // All content sources must implement getWeightedCards()\n if (this.sources.some((s) => typeof s.getWeightedCards !== 'function')) {\n throw new Error(\n '[SessionController] All content sources must implement getWeightedCards().'\n );\n }\n\n // Clear the previous session's debug state before this session's\n // bootstrap pipeline run fires, so that run's own report isn't wiped out.\n clearStaleSessionDebugState();\n\n perfMark('sk:session-prepare-start');\n const wellIndicated = await this.getWeightedContent();\n this._recordRuns('bootstrap');\n this._wellIndicatedRemaining = wellIndicated;\n if (wellIndicated >= 0 && wellIndicated < SessionController.MIN_WELL_INDICATED) {\n this.log(\n `[Init] Only ${wellIndicated}/${SessionController.MIN_WELL_INDICATED} well-indicated cards in initial load`\n );\n }\n await this.hydrationService.ensureHydratedCards();\n perfMark('sk:session-prepared');\n perfMeasure('sk:session-prepare', 'sk:session-prepare-start', 'sk:session-prepared');\n\n // Start session tracking for debugging\n startSessionTracking(this.sessionId, this.supplyQ.length, this.failedQ.length);\n\n // Not awaited — a session must never block on an analytics write.\n this._openDocPromise = this._openSessionDoc();\n\n this._intervalHandle = setInterval(() => {\n this.tick();\n }, 1000);\n }\n\n /** Label the runs the last plan produced. The pipeline can't know the why. */\n private _recordRuns(label: string, mode?: string): void {\n for (const run of drainCapturedRuns()) {\n if (this._runLog.length >= SessionController.MAX_LOGGED_RUNS) break;\n this._runLog.push({\n runId: run.runId,\n at: run.timestamp.toISOString(),\n label,\n ...(mode ? { mode } : {}),\n generatedCount: run.generatedCount,\n finalCount: run.finalCount,\n reviewsSelected: run.reviewsSelected,\n newSelected: run.newSelected,\n // Compact detail projected off the full report so a persisted run is\n // self-explanatory once the in-memory ring buffer has rolled over.\n // Per-card provenance is the dominant cost, so it's kept only for the\n // (at most two) `unselectedNew` cards, and only its score-changing\n // entries. Everything else is ids and scores.\n ...(typeof run.userElo === 'number' ? { userElo: run.userElo } : {}),\n ...(run.generators ? { generators: run.generators } : {}),\n ...(run.filters ? { filters: run.filters } : {}),\n ...(run.hints ? { hints: run.hints } : {}),\n ...(run.discardedTail ? { discardedTail: run.discardedTail } : {}),\n cards: persistedRunCards(run),\n ...(run.unselectedNew ? { unselectedNew: persistedUnselectedNew(run.unselectedNew) } : {}),\n ...(run.regulators ? { regulators: run.regulators.map(persistedReading) } : {}),\n ...(run.versions ? { versions: run.versions } : {}),\n });\n }\n }\n\n /** Time-boxed and isolated — a bad provider degrades the record, not the session. */\n private async _captureState(\n phase: 'start' | 'end'\n ): Promise<SessionStateSnapshot | undefined> {\n if (!this._stateSnapshotProvider) return undefined;\n const TIMEOUT_MS = 3000;\n try {\n return await Promise.race([\n Promise.resolve(this._stateSnapshotProvider(phase)),\n new Promise<undefined>((resolve) => setTimeout(() => resolve(undefined), TIMEOUT_MS)),\n ]);\n } catch (e) {\n this.log(`[Session] state snapshot (${phase}) failed: ${e}`);\n return undefined;\n }\n }\n\n /** Writing at open is what makes an unclosed session visible at all. */\n private async _openSessionDoc(): Promise<void> {\n if (!this._courseId) return;\n try {\n const user = this.dataLayer.getUserDB();\n const doc: StudySessionDoc = {\n _id: makeStudySessionId(this._courseId, user.getUsername(), this.sessionId),\n docType: DocType.STUDY_SESSION,\n sessionId: this.sessionId,\n courseId: this._courseId,\n userId: user.getUsername(),\n startTime: this.startTime.toISOString(),\n status: 'open',\n plannedSeconds: Math.round((this.endTime.valueOf() - this.startTime.valueOf()) / 1000),\n config: {\n defaultBatchLimit: this._defaultBatchLimit,\n sourceCount: this.sources.length,\n initHints: this._sessionHints,\n },\n versions: sessionVersions(),\n initialQueues: { supplyQ: this.supplyQ.length, failedQ: this.failedQ.length },\n runs: [...this._runLog],\n stateAtStart: await this._captureState('start'),\n };\n this._sessionDoc = doc;\n await user.putStudySession(doc);\n this.log(`[Session] Opened session record ${doc._id}`);\n } catch (e) {\n logger.warn(`[SessionController] Failed to open session record: ${e}`);\n }\n }\n\n /**\n * Request a mid-session replan. Re-runs the pipeline with current user state\n * and atomically replaces (or merges into) the supplyQ contents. Safe to call\n * at any time during a session.\n *\n * Concurrency policy:\n * - Two unhinted auto-replans never run in parallel; the second coalesces\n * into the first (returns the same promise).\n * - A hint-bearing replan that arrives while another replan is in flight\n * is queued to run **after** the in-flight one rather than dropped.\n * This preserves caller intent (label, requireCards, excludeTags,\n * limit, minFollowUpCards) instead of silently discarding it. Without\n * queueing, a background auto-replan that started just before a\n * completion-triggered replan would clobber the queue with unhinted\n * results (e.g. surfacing another gpc-intro card right after one\n * completed, skipping the prescribed `c-wst-*` follow-up).\n *\n * Re-pulls and re-ranks the whole supply (including reviews); does NOT affect\n * failedQ (controller-owned remediation).\n *\n * If nextCard() is called while a replan is in flight, it will automatically\n * await the replan before drawing from queues, ensuring the user always sees\n * cards scored against their latest state.\n *\n * Typical trigger: application-level code (e.g. after a GPC intro completion)\n * calls this to ensure newly-unlocked content appears in the session.\n */\n public async requestReplan(options?: ReplanOptions | ReplanHints): Promise<void> {\n // Normalise: bare hints object (legacy callers) → ReplanOptions wrapper\n const opts = this.normalizeReplanOptions(options);\n\n const hasIntent = this._replanHasIntent(opts);\n\n if (this._replanPromise) {\n if (!hasIntent) {\n this.log('Replan already in progress, coalescing unhinted auto-replan');\n return this._replanPromise;\n }\n\n // Queue the hint-bearing replan behind the in-flight one rather than\n // dropping its hints. See class comment above for rationale.\n const labelTag = opts.label ? ` [${opts.label}]` : '';\n this.log(\n `Replan in progress; queueing hint-bearing replan${labelTag} behind in-flight run`\n );\n const inflight = this._replanPromise;\n const queued: Promise<void> = inflight\n // Swallow errors in the upstream replan so the downstream still runs\n // (the user's intent is independent of whether the prior run succeeded).\n .catch(() => undefined)\n .then(() => this._runReplan(opts));\n\n // Compare against the promise we actually store. `.finally()` returns a\n // NEW promise, so guarding on `=== queued` (the pre-finally promise) never\n // matches and would leak _replanPromise. `tracked` is read only inside the\n // async callback (after init), so the self-reference is safe.\n const tracked: Promise<void> = queued.finally(() => {\n if (this._replanPromise === tracked) {\n this._replanPromise = null;\n this._activeReplanLabel = null;\n }\n });\n this._replanPromise = tracked;\n\n return queued;\n }\n\n const run = this._runReplan(opts);\n // Compare against the wrapped promise we store, not `run` — `.finally()`\n // returns a new promise, so `=== run` never matches and _replanPromise\n // would never clear (perpetual \"replan in progress\"). Safe self-reference:\n // `tracked` is read only in the async callback, after initialization.\n const tracked: Promise<void> = run.finally(() => {\n if (this._replanPromise === tracked) {\n this._replanPromise = null;\n this._activeReplanLabel = null;\n }\n });\n this._replanPromise = tracked;\n\n await run;\n }\n\n /**\n * True when a requestReplan call carries caller intent that must not be\n * silently dropped. Bare unhinted auto-replans (depletion / quality\n * triggers in nextCard) return false and may coalesce.\n */\n private _replanHasIntent(opts: ReplanOptions): boolean {\n // NOTE: `label` is intentionally NOT an intent signal. It is observability-\n // only metadata (debug overlay spinner, log tags, Pipeline strategy names),\n // so labelling a replan must never change scheduling. Intent is strictly\n // \"does this replan carry scheduling-relevant options\". This lets the\n // unlabeled-but-named auto-replans (auto:depletion / auto:quality) keep\n // coalescing while still showing a reason in the overlay.\n if (opts.limit !== undefined) return true;\n if (opts.minFollowUpCards !== undefined) return true;\n if (opts.mode && opts.mode !== 'replace') return true;\n if (opts.hints && Object.keys(opts.hints).length > 0) return true;\n if (opts.sessionHints !== undefined) return true;\n if (opts.mergeSessionHints !== undefined) return true;\n return false;\n }\n\n /**\n * Body of a single replan: populate auto-excludes, stash hints on\n * sources, log, then run the pipeline. Extracted so it can be invoked\n * either immediately (no in-flight replan) or queued (chained after\n * the in-flight one resolves).\n *\n * IMPORTANT: hint stash and the queue-state snapshot used to build\n * excludeCards happen at *invocation* time, not at *queue* time. For a\n * queued replan that means excludes reflect the state after the prior\n * replan landed — which is what we want, since the prior replan's\n * supplyQ.peek(0) is the imminent draw we need to exclude.\n */\n private async _runReplan(opts: ReplanOptions): Promise<void> {\n // Surface the executing replan's reason to the debug overlay spinner.\n // `label` is observability-only (see _replanHasIntent); '(auto)' covers any\n // unlabeled path.\n this._activeReplanLabel = opts.label ?? '(auto)';\n\n // Exclude all cards already presented this session. The pipeline may\n // not yet see their encounter records (async writes), so without this\n // they can re-enter supplyQ via replaceAll and cause duplicates.\n //\n // Also exclude supplyQ.peek(0): the imminent draw. When a replan fires\n // from inside nextCard() (auto depletion/quality trigger) or as a\n // deferred post-submit replan, the next-up card is about to become\n // _currentCard but isn't yet, and hasn't yet landed in _sessionRecord.\n // Without this, the just-drawn card can be re-seated at the head of\n // the replaced supplyQ and shown twice in a row — most visible in early\n // sessions where state is sparse and triggers fire aggressively.\n // Only the head is excluded; deeper supplyQ entries are still fair game\n // for the new plan (they aren't at risk of double-display since the\n // old queue is replaced atomically and only its head gets drawn).\n if (!opts.hints) opts.hints = {};\n const hints = opts.hints;\n const excludeSet = new Set(hints.excludeCards ?? []);\n\n if (this._currentCard?.item.cardID) {\n excludeSet.add(this._currentCard.item.cardID);\n }\n for (const rec of this._sessionRecord) {\n excludeSet.add(rec.card.card_id);\n }\n if (this.supplyQ.length > 0) {\n excludeSet.add(this.supplyQ.peek(0).cardID);\n }\n\n hints.excludeCards = [...excludeSet];\n\n // Replace session-durable hints if this replan carries them. KISS:\n // wholesale replace, no accumulation/decay (see ReplanOptions.sessionHints).\n if (opts.sessionHints !== undefined) {\n this._sessionHints = opts.sessionHints;\n this.log(\n `[Replan] Session hints ${opts.sessionHints ? 'set' : 'cleared'}: ` +\n `${JSON.stringify(opts.sessionHints)}`\n );\n }\n\n // Additive emphasis: merge (don't clobber) into durable hints. Lets a new\n // concept's boost accumulate on top of prior concepts' boosts and any\n // observer-managed boost/decay state. Boosts multiply, lists concat-dedup.\n if (opts.mergeSessionHints !== undefined) {\n this._sessionHints = mergeHints([this._sessionHints, opts.mergeSessionHints]) ?? null;\n this.log(`[Replan] Session hints merged: ${JSON.stringify(this._sessionHints)}`);\n }\n\n // Forward hints to all sources (CourseDB stashes them, Pipeline consumes\n // them). The one-shot `opts.hints` are merged with the durable\n // `_sessionHints` so session emphasis survives this and every later run.\n this._applyHintsToSources(opts.hints, opts.label);\n\n const labelTag = opts.label ? ` [${opts.label}]` : '';\n this.log(\n `Mid-session replan requested${labelTag}` +\n ` (limit: ${opts.limit ?? 'default'}, mode: ${opts.mode ?? 'replace'}` +\n `${opts.hints ? ', with hints' : ''})`\n );\n // Update card guarantee if requested\n if (opts.minFollowUpCards !== undefined && opts.minFollowUpCards > 0) {\n this._minCardsGuarantee = Math.max(this._minCardsGuarantee, opts.minFollowUpCards);\n this.log(`[Replan] Card guarantee set to ${this._minCardsGuarantee}`);\n }\n\n // [perf] parked 2026-05 (pipeline-docs-workup) — uncomment to re-measure\n // const tReplan0 = performance.now();\n await this._executeReplan(opts);\n // logger.info(\n // `[perf][SessionController] replan${labelTag} (limit=${opts.limit ?? 'default'}, ` +\n // `mode=${opts.mode ?? 'replace'}) took ${(performance.now() - tReplan0).toFixed(0)}ms`\n // );\n }\n\n /**\n * Set the session-durable scoring hints (replace semantics, no decay).\n *\n * Unlike a one-shot replan hint, these are re-merged into every pipeline\n * run for the rest of the session — including the initial plan when set\n * before `prepareSession()`, every replan, the bare auto-replans, and the\n * wedge-breaker. Pass `null` to clear.\n *\n * Typical callers:\n * - `StudySession` at session start, threading `StudySessionConfig.initHints`\n * (e.g. a post-lesson concept boost) — so the boost outlives the first\n * queue rebuild instead of being clobbered by the first auto-replan.\n * - A consumer view on a failure, boosting the just-failed concept tag.\n *\n * Does not itself trigger a replan; the next plan/replan picks it up.\n */\n public setSessionHints(hints: ReplanHints | null): void {\n this._sessionHints = hints;\n this.log(`Session hints ${hints ? 'set' : 'cleared'}: ${JSON.stringify(hints)}`);\n }\n\n /**\n * Read the current session-durable hints (for read-modify-write callers,\n * e.g. an outcome observer that clamps a compounding boost).\n */\n public getSessionHints(): ReplanHints | null {\n return this._sessionHints;\n }\n\n /**\n * Live state snapshot for the debug overlay (window.skuilder.session\n * .dbgOverlay()). Reads directly from the private queues and hints, so it\n * always reflects the current moment — unlike the passive SessionDebugger\n * snapshots, which only capture what was explicitly pushed to them.\n */\n public getDebugSnapshot(): SessionDebugSnapshot {\n const describe = <T extends StudySessionItem>(q: ItemQueue<T>): SessionQueueDebug => {\n const cards: SessionQueueItemDebug[] = [];\n for (let i = 0; i < q.length; i++) {\n const item = q.peek(i);\n cards.push({\n cardID: item.cardID,\n status: item.status,\n origin: isReview(item) ? 'review' : 'new',\n score: item.score,\n });\n }\n return { length: q.length, dequeueCount: q.dequeueCount, cards };\n };\n const drawnCards: SessionDrawnCardDebug[] = this._sessionRecord.map((r) => {\n const last = r.records[r.records.length - 1];\n return {\n cardID: r.item.cardID,\n status: r.item.status,\n attempts: r.records.length,\n correct: last && isQuestionRecord(last) ? last.isCorrect : null,\n timeSpentMs: r.records.reduce((sum, rec) => sum + rec.timeSpent, 0),\n };\n });\n return {\n sessionId: this.sessionId,\n secondsRemaining: this.secondsRemaining,\n hasCardGuarantee: this.hasCardGuarantee,\n minCardsGuarantee: this._minCardsGuarantee,\n wellIndicatedRemaining: this._wellIndicatedRemaining,\n currentCard: this._currentCard?.item.cardID ?? null,\n sessionHints: this._sessionHints,\n replanActive: this._replanPromise !== null,\n replanLabel: this._activeReplanLabel,\n supplyQ: describe(this.supplyQ),\n failedQ: describe(this.failedQ),\n reviewBacklog: getSrsBacklogDebug(),\n strategyPressure: getStrategyPressureDebug(),\n drawnCards,\n };\n }\n\n /**\n * Merge `hints` into the durable session hints via the pipeline's\n * `mergeHints` (boosts multiply, require/exclude lists concat-dedup).\n * Convenience over get-then-set for the common additive case. Note the\n * multiplicative, no-decay semantics — clamp boost factors at the call\n * site if a repeatedly-emphasised tag could compound unboundedly.\n */\n public mergeSessionHints(hints: ReplanHints): void {\n this._sessionHints = mergeHints([this._sessionHints, hints]) ?? null;\n this.log(`Session hints merged: ${JSON.stringify(this._sessionHints)}`);\n }\n\n /**\n * Merge the durable `_sessionHints` with this run's one-shot hints and\n * push the result to every source for consumption on the next pipeline\n * run. Centralised so the initial plan and all replan paths apply session\n * emphasis identically. No-op when there are no hints of either kind.\n */\n private _applyHintsToSources(oneShot?: ReplanHints, label?: string): void {\n // Thread the provenance label into the one-shot layer; mergeHints will\n // fold it into the combined `_label`.\n const oneShotWithLabel: ReplanHints | undefined =\n oneShot && label ? { ...oneShot, _label: label } : oneShot;\n\n const merged = mergeHints([this._sessionHints, oneShotWithLabel]);\n if (!merged) return;\n\n for (const source of this.sources) {\n source.setEphemeralHints?.(merged);\n }\n }\n\n /**\n * Build (once) the stable capability object handed to outcome observers.\n * Methods are bound to `this`; the object identity is stable across calls\n * so observers may key off it.\n */\n private _getSessionControls(): SessionControls {\n if (!this._sessionControls) {\n this._sessionControls = {\n getSessionHints: () => this.getSessionHints(),\n setSessionHints: (h) => this.setSessionHints(h),\n mergeSessionHints: (h) => this.mergeSessionHints(h),\n requestReplan: (opts) => this.requestReplan(opts),\n };\n }\n return this._sessionControls;\n }\n\n /**\n * Notify registered outcome observers about a processed response.\n *\n * Only question records are surfaced (non-question dismisses are skipped).\n * Observers run after ELO/SRS are recorded and before navigation. Each is\n * awaited but isolated in try/catch — a throwing observer is logged and\n * skipped, never wedging the session. Keep observers cheap and `void` any\n * long work (e.g. a triggered replan) to avoid stalling the draw.\n */\n /**\n * Append a resolved ELO exchange to the in-memory log. Fires async (the ELO\n * update is non-blocking), so an event can land after the response that\n * produced it has returned — but well before close, which is when the log is\n * persisted. Bounded to avoid unbounded growth.\n */\n private _recordEloEvent(event: SessionEloEvent): void {\n if (this._eloLog.length >= SessionController.MAX_LOGGED_ELO_EVENTS) return;\n this._eloLog.push(event);\n }\n\n private async _notifyOutcomeObservers(\n record: CardRecord,\n currentCard: StudySessionRecord,\n result: ResponseResult\n ): Promise<void> {\n if (this._outcomeObservers.length === 0) return;\n if (!isQuestionRecord(record)) return;\n\n const outcome: SessionOutcome = {\n record,\n card: currentCard.card,\n result,\n };\n const controls = this._getSessionControls();\n\n for (const observer of this._outcomeObservers) {\n try {\n await observer(outcome, controls);\n } catch (e) {\n this.error('[OutcomeObserver] observer threw; ignoring', e);\n }\n }\n }\n\n /**\n * Run a replan, bypassing requestReplan()'s coalesce logic.\n *\n * Use this when correctness depends on a *fresh* pipeline run, not on\n * the existence of *some* in-flight replan. Specifically: the\n * wedge-breaker path in nextCard(), where coalescing into a previous\n * run that we now know produced insufficient content would re-create\n * the bug we're trying to prevent.\n *\n * Still tracks _replanPromise like requestReplan() does so concurrent\n * observers (auto-trigger guards in nextCard()) see consistent state.\n */\n private async _replanUncoalesced(opts: ReplanOptions): Promise<void> {\n const run = this._runReplan(opts);\n // See requestReplan: guard against the wrapped promise we store, not `run`.\n const tracked: Promise<void> = run.finally(() => {\n if (this._replanPromise === tracked) {\n this._replanPromise = null;\n this._activeReplanLabel = null;\n }\n });\n this._replanPromise = tracked;\n await run;\n }\n\n /**\n * Normalise the requestReplan argument. Accepts either a ReplanOptions\n * object (new API) or a plain Record<string, unknown> (legacy callers\n * that passed hints directly). Distinguishes the two by checking for\n * the presence of ReplanOptions-specific keys.\n */\n private normalizeReplanOptions(\n input?: ReplanOptions | ReplanHints\n ): ReplanOptions {\n if (!input) return {};\n\n // If the input has any ReplanOptions-specific key, treat it as ReplanOptions\n const replanKeys = ['hints', 'sessionHints', 'limit', 'mode', 'label', 'minFollowUpCards'];\n const inputKeys = Object.keys(input);\n if (inputKeys.some((k) => replanKeys.includes(k))) {\n return input as ReplanOptions;\n }\n\n // Otherwise treat as legacy bare-hints object\n return { hints: input as ReplanHints };\n }\n\n /** Minimum well-indicated cards before an additive retry is attempted */\n private static readonly MIN_WELL_INDICATED = 5;\n\n /**\n * Score threshold for considering a card \"well-indicated.\"\n * Cards below this score are treated as fallback filler — present only\n * because no strategy hard-removed them, but likely penalized by one\n * or more filters. Strategy-agnostic: the SessionController doesn't\n * know or care which strategy assigned the score.\n */\n private static readonly WELL_INDICATED_SCORE = 0.10;\n\n /**\n * supplyQ length at or below which the opportunistic depletion-prefetch\n * fires. Sets the lead time available for the background replan to land\n * before the user actually empties the queue and falls into the\n * (synchronous) wedge-breaker path.\n *\n * Set to a small absolute value (not a fraction of batch limit) because\n * pipeline latency is roughly fixed regardless of batch size — what\n * matters is \"how many cards of user-pace do we have left.\" 3 cards\n * × ~3-5s/card = ~10-15s of lead time, comfortably exceeding typical\n * pipeline latency.\n */\n private static readonly DEPLETION_PREFETCH_THRESHOLD = 3;\n\n /**\n * Internal replan execution. Runs the pipeline, rebuilds the supplyQ,\n * atomically swaps it in, and triggers hydration for the new contents.\n *\n * If the initial replan produces fewer than MIN_WELL_INDICATED cards that\n * pass all hierarchy filters, one additive retry is attempted — merging\n * any new high-quality candidates into the front of the queue.\n */\n private async _executeReplan(opts: ReplanOptions = {}): Promise<void> {\n const limit = opts.limit;\n const mode = opts.mode ?? 'replace';\n\n const wellIndicated = await this.getWeightedContent({\n replan: true,\n additive: mode === 'merge',\n limit,\n });\n this._recordRuns(opts.label ?? '(auto)', mode);\n this._wellIndicatedRemaining = wellIndicated;\n\n // Burst replan: suppress quality-based auto-replan so the background\n // replan doesn't clobber the small hinted queue before it's consumed.\n // The depletion trigger (supplyQ empty) takes over instead.\n if (limit !== undefined && limit < this._defaultBatchLimit) {\n this._suppressQualityReplan = true;\n this.log(`[Replan] Burst mode (limit=${limit}): suppressing quality-based auto-replan`);\n } else {\n // Normal or auto-replan — clear the burst suppression flag\n this._suppressQualityReplan = false;\n }\n\n if (wellIndicated >= 0 && wellIndicated < SessionController.MIN_WELL_INDICATED) {\n this.log(\n `[Replan] Only ${wellIndicated}/${SessionController.MIN_WELL_INDICATED} well-indicated cards after replan`\n );\n }\n\n await this.hydrationService.ensureHydratedCards();\n const labelTag = opts.label ? ` [${opts.label}]` : '';\n this.log(`Replan complete${labelTag}: supplyQ now has ${this.supplyQ.length} cards (mode=${mode})`);\n\n // Snapshot queue state for debugging\n snapshotQueues(this.supplyQ.length, this.failedQ.length);\n }\n\n public addTime(seconds: number) {\n this.endTime = new Date(this.endTime.valueOf() + 1000 * seconds);\n }\n\n public get failedCount(): number {\n return this.failedQ.length;\n }\n\n public toString() {\n return `Session: ${this.supplyQ.length} supply, ${this.failedQ.length} failed`;\n }\n public reportString() {\n return `${this.supplyQ.dequeueCount} supply, ${this.failedQ.dequeueCount} failed`;\n }\n\n /**\n * Returns debug information about the current session state.\n * Used by SessionControllerDebug component for runtime inspection.\n */\n public getDebugInfo() {\n // Check if sources support weighted cards\n const supportsWeightedCards = this.sources.some(\n (s) => typeof s.getWeightedCards === 'function'\n );\n\n const extractQueueItems = (queue: ItemQueue<any>, limit: number = 10) => {\n const items = [];\n for (let i = 0; i < Math.min(queue.length, limit); i++) {\n const item = queue.peek(i);\n items.push({\n courseID: item.courseID || 'unknown',\n cardID: item.cardID || 'unknown',\n status: item.status || 'unknown',\n score: item.score,\n });\n }\n return items;\n };\n\n return {\n api: {\n mode: supportsWeightedCards ? 'weighted' : 'legacy',\n description: supportsWeightedCards\n ? 'Using getWeightedCards() API with scored candidates'\n : 'ERROR: getWeightedCards() not a function.',\n },\n supplyQueue: {\n length: this.supplyQ.length,\n dequeueCount: this.supplyQ.dequeueCount,\n items: extractQueueItems(this.supplyQ),\n },\n failedQueue: {\n length: this.failedQ.length,\n dequeueCount: this.failedQ.dequeueCount,\n items: extractQueueItems(this.failedQ),\n },\n hydratedCache: {\n count: this.hydrationService.hydratedCount,\n cardIds: this.hydrationService.getHydratedCardIds(),\n },\n replan: {\n inProgress: this._replanPromise !== null,\n suppressQualityReplan: this._suppressQualityReplan,\n defaultBatchLimit: this._defaultBatchLimit,\n minCardsGuarantee: this._minCardsGuarantee,\n },\n };\n }\n\n /**\n * Fetch weighted content from all sources, mix across sources, and populate\n * the single supply queue in pipeline rank order.\n *\n * Reviews and new cards compete on one cross-comparable scale (SRS 0.5–1.0\n * w/ backlog pressure vs ELO 0.0–1.0) — there is no origin split and no\n * second mixer. The working set is `supplyLimit` cards (the top of the mixed\n * ranking, plus any `+INF` required cards floated to the front); replans\n * re-pull and re-rank the whole supply, so a heavy review backlog surfaces as\n * a refreshed top-ranked working set rather than a frozen 200-card snapshot.\n *\n * @param options.replan - If true, this is a mid-session replan rather than\n * initial session setup. Atomically replaces supplyQ contents and treats\n * empty results as non-fatal.\n * @param options.additive - If true (replan only), merge high-quality\n * candidates into the front of the existing supplyQ instead of replacing it.\n * @returns Number of \"well-indicated\" cards (passed all hierarchy filters)\n * in the new content. Returns -1 if no content was loaded.\n */\n private async getWeightedContent(options?: {\n replan?: boolean;\n additive?: boolean;\n limit?: number;\n }): Promise<number> {\n // const tGwc0 = performance.now(); // [perf] parked\n const replan = options?.replan ?? false;\n const additive = options?.additive ?? false;\n const supplyLimit = options?.limit ?? this._defaultBatchLimit;\n // Single working set: fetch the top `supplyLimit` from each source and let\n // the mixer interleave them. Reviews and new are ranked together, so there\n // is no separate review budget to inflate for (cf. the old dual-budget\n // fetch that over-fetched to fill a frozen review cap).\n const fetchLimit = supplyLimit;\n\n // Initial plan: push session-durable hints to sources so the very first\n // pipeline run reflects them (e.g. a post-lesson boost). Replans push\n // their own session+one-shot merge via _runReplan before reaching here,\n // so we must NOT re-apply here or we'd drop their per-run excludeCards.\n if (!replan) {\n this._applyHintsToSources();\n }\n\n // Collect batches from each source\n const batches: SourceBatch[] = [];\n\n for (let i = 0; i < this.sources.length; i++) {\n const source = this.sources[i];\n try {\n // Fetch weighted cards for mixing\n const weighted = (await source.getWeightedCards!(fetchLimit)).cards;\n\n batches.push({\n sourceIndex: i,\n weighted,\n });\n } catch (error) {\n this.error(`Failed to get content from source ${i}:`, error);\n // Re-throw if this is the only source - we can't proceed without any content.\n // Initial load only: a replan falls through to the non-fatal\n // `batches.length === 0` path below and keeps the existing queue.\n // Throwing there would escape nextCard() (via the wedge-breaker) and\n // strand the host mid-session with neither a card nor a null.\n if (this.sources.length === 1 && !replan) {\n throw new Error(`Cannot start session: failed to load content from source ${i}`);\n }\n }\n }\n\n // const tSources = performance.now(); // [perf] parked\n\n // Verify we got content from at least one source\n if (batches.length === 0) {\n if (replan) {\n // Replan finding no content is non-fatal — old queue remains\n this.log('Replan: no content from any source, keeping existing supplyQ');\n return -1;\n }\n throw new Error(\n `Cannot start session: failed to load content from all ${this.sources.length} source(s). ` +\n `Check logs for details.`\n );\n }\n\n // Mix weighted cards across sources using configured strategy\n const mixedWeighted = this.mixer.mix(batches, fetchLimit * this.sources.length);\n // const tMixed = performance.now(); // [perf] parked\n\n // Capture mixer run for debugging - fetch course names\n const sourceIds = batches.map((b) => {\n const firstCard = b.weighted[0];\n return firstCard?.courseId || `source-${b.sourceIndex}`;\n });\n // Populate course name cache (one-time fetch, reused by SessionDebugger)\n await Promise.all(\n sourceIds.map(async (id) => {\n if (!this.courseNameCache.has(id)) {\n try {\n const config = await this.dataLayer.getCoursesDB().getCourseConfig(id);\n this.courseNameCache.set(id, config.name);\n } catch {\n // leave unmapped\n }\n }\n })\n );\n const sourceNames = sourceIds.map((id) => this.courseNameCache.get(id));\n const quotaPerSource =\n this.mixer instanceof QuotaRoundRobinMixer ? Math.ceil((fetchLimit * this.sources.length) / batches.length) : undefined;\n captureMixerRun(\n this.mixer.constructor.name,\n batches,\n sourceIds,\n sourceNames,\n fetchLimit * this.sources.length,\n quotaPerSource,\n mixedWeighted\n );\n\n // Single supply working set — no origin split. Reviews and new compete on\n // one rank. Drop already-served cards across ALL origins: a `new` card\n // shown once must never recur, and once replans re-pull reviews, an\n // answered/in-flight review must not re-enter the supply before its SRS\n // reschedule clears the due-window (the review-loop guard, decision doc §4).\n // failedQ is separate, so this never blocks legitimate failed re-presentation.\n const candidates = mixedWeighted.filter((w) => !this._servedCardIds.has(w.cardId));\n\n // `+INF` is the hard \"include at all costs\" sentinel applied by require*\n // injection (see Pipeline.applyRequirement). Float these mandatory cards to\n // the front and exempt them from the supplyLimit slice, so neither the\n // mixer's source-shuffle/round-robin nor the cap can bury or drop a required\n // card. This preserves rank-respect through the mixer — it is NOT a per-item\n // \"mandatory\" flag (the supplyQ is drawn front-to-back, and the timer guards\n // honour `_minCardsGuarantee`, so a required follow-up is served on its own\n // merits; see decision doc §3). The set is also handed to mergeToFront so an\n // already-queued required card gets re-fronted rather than leapfrogged.\n const mandatoryWeighted = candidates.filter((w) => w.score === Number.POSITIVE_INFINITY);\n const optionalWeighted = candidates.filter((w) => w.score !== Number.POSITIVE_INFINITY);\n const supplyWeighted = [\n ...mandatoryWeighted,\n ...optionalWeighted.slice(0, Math.max(0, supplyLimit - mandatoryWeighted.length)),\n ];\n const mandatoryIds = new Set(mandatoryWeighted.map((w) => w.cardId));\n\n // Count well-indicated cards by final score. Cards above the threshold\n // are genuinely appropriate content; cards below are fallback filler\n // that survived only because no strategy hard-removed them.\n const wellIndicated = supplyWeighted.filter(\n (w) => w.score >= SessionController.WELL_INDICATED_SCORE\n ).length;\n\n // Build heterogeneous supply items in rank order (review items carry\n // reviewID; score is carried for the debug overlay).\n let report = replan ? 'Replan content:\\n' : 'Mixed content session created with:\\n';\n const supplyItems: StudySessionItem[] = supplyWeighted.map((w) => {\n const origin = getCardOrigin(w);\n const scoreStr = Number.isFinite(w.score) ? w.score.toFixed(2) : '+INF';\n report += `${origin === 'review' ? 'Review' : 'New'}: ${w.courseId}::${w.cardId} (score: ${scoreStr})\\n`;\n return this._buildSupplyItem(w, origin);\n });\n\n if (additive) {\n // Additive replan: merge candidates into front of existing queue.\n // Pass mandatory (+INF) ids so an already-queued required card is pulled\n // back to the front instead of being buried by fresh non-required cards.\n const added = this.supplyQ.mergeToFront(supplyItems, (item) => item.cardID, mandatoryIds);\n report += `Additive merge: ${added} cards added to front of supplyQ\\n`;\n } else if (replan) {\n // Atomic swap: replace entire supplyQ contents at once (no empty-queue window)\n this.supplyQ.replaceAll(supplyItems, (item) => item.cardID);\n } else {\n // Initial session setup: add items normally\n for (const item of supplyItems) {\n this.supplyQ.add(item, item.cardID);\n }\n }\n\n this.log(report);\n\n // [perf] parked: getWeightedContent stage timing\n // const tEnd = performance.now();\n // logger.info(\n // `[perf][SessionController] getWeightedContent(replan=${replan}): ` +\n // `sources=${(tSources - tGwc0).toFixed(0)}ms ` +\n // `mix=${(tMixed - tSources).toFixed(0)}ms ` +\n // `post=${(tEnd - tMixed).toFixed(0)}ms ` +\n // `total=${(tEnd - tGwc0).toFixed(0)}ms ` +\n // `[sources=${this.sources.length} fetchLimit=${fetchLimit} supplyLimit=${supplyLimit}]`\n // );\n\n return wellIndicated;\n }\n\n /**\n * Build a supply item from a weighted candidate. Review-origin cards carry\n * their `reviewID` so SRS outcome tracking and re-presentation work; new\n * cards do not. `score` is carried on both for the debug overlay.\n */\n private _buildSupplyItem(w: WeightedCard, origin = getCardOrigin(w)): StudySessionItem {\n const base = {\n cardID: w.cardId,\n courseID: w.courseId,\n contentSourceType: 'course' as const,\n contentSourceID: w.courseId,\n score: w.score,\n };\n if (origin === 'review') {\n const reviewItem: StudySessionReviewItem = { ...base, status: 'review', reviewID: w.reviewID! };\n return reviewItem;\n }\n const newItem: StudySessionNewItem = { ...base, status: 'new' };\n return newItem;\n }\n\n /**\n * Returns items that should be pre-hydrated.\n * Deterministic: top N items from each queue to ensure coverage.\n * Failed queue items will typically already be hydrated (from initial render).\n */\n private _getItemsToHydrate(): StudySessionItem[] {\n const items: StudySessionItem[] = [];\n // Prefetch a little deeper into supplyQ (the primary draw source) than the\n // intermittently-drawn failedQ.\n const SUPPLY_PREFETCH = 3;\n const FAILED_PREFETCH = 2;\n\n for (let i = 0; i < Math.min(SUPPLY_PREFETCH, this.supplyQ.length); i++) {\n items.push(this.supplyQ.peek(i));\n }\n for (let i = 0; i < Math.min(FAILED_PREFETCH, this.failedQ.length); i++) {\n items.push(this.failedQ.peek(i));\n }\n\n return items;\n }\n\n /**\n * Selects the next item to present to the user.\n *\n * The supplyQ is already rank-ordered (the pipeline + mixer did the mixing,\n * with `+INF` required cards floated to the front), so the primary path is a\n * deterministic front-to-back draw — no second new-vs-review mixer. The only\n * remaining decisions are (a) when the session ends and (b) when to interleave\n * a remediation card from failedQ. See decision doc §2/§3/§7.\n */\n private _selectNextItemToHydrate(): StudySessionItem | null {\n if (this.supplyQ.length === 0 && this.failedQ.length === 0) {\n // all queues empty - session is over (and course is complete?)\n return null;\n }\n\n // Near/at session end with no remediation pending and no guarantee active:\n // don't start a card we can't finish. A `_minCardsGuarantee` (set by a\n // replan's minFollowUpCards) holds the session open so a required follow-up\n // and its practice can still be drawn past the timer — see decision doc §3.\n if (\n this._secondsRemaining < 2 &&\n this.failedQ.length === 0 &&\n this._minCardsGuarantee <= 0\n ) {\n return null;\n }\n\n // Timer expired, no guarantee: drain remediation only, then end.\n if (this._secondsRemaining <= 0 && this._minCardsGuarantee <= 0) {\n return this.failedQ.length > 0 ? this.failedQ.peek(0) : null;\n }\n\n const supplyTop = this.supplyQ.length > 0 ? this.supplyQ.peek(0) : null;\n\n // A card guarantee exists to surface supplyQ follow-ups past the timer\n // (e.g. an intro's required WST + practice). Don't let the failed-interleave\n // consume those guaranteed draws.\n if (this._minCardsGuarantee > 0 && supplyTop) {\n return supplyTop;\n }\n\n // Failed-interleave (§7): pressure-based endgame + a light steady cadence so\n // remediation neither starves mid-session nor overruns the clock.\n if (this.failedQ.length > 0 && this._shouldInterleaveFailed(supplyTop !== null)) {\n return this.failedQ.peek(0);\n }\n\n if (supplyTop) {\n return supplyTop;\n }\n\n // Supply exhausted; remediation remains.\n if (this.failedQ.length > 0) {\n return this.failedQ.peek(0);\n }\n\n this.log(`No more cards available for the session!`);\n return null;\n }\n\n /** Supply draws between forced failed-queue interleaves (light steady cadence). */\n private static readonly FAILED_INTERLEAVE_EVERY = 4;\n /**\n * Slack (seconds) below which the endgame failed-pressure kicks in: when the\n * time left after clearing remediation drops under this, bias hard to failed\n * so the session doesn't end with un-cleared remediation. Mirrors the old\n * `availableTime > 20` ladder thresholds.\n */\n private static readonly FAILED_ENDGAME_SLACK_SECONDS = 20;\n\n /**\n * Whether to interleave a failed (remediation) card now instead of drawing\n * the supply head. Replaces the old `newBound`/`reviewBound` probability\n * ladder's failed path (decision doc §7).\n *\n * @param supplyAvailable - whether supplyQ has a card to draw instead.\n */\n private _shouldInterleaveFailed(supplyAvailable: boolean): boolean {\n if (this.failedQ.length === 0) return false;\n // Nothing else to draw — failed is all that's left.\n if (!supplyAvailable) return true;\n\n // Endgame pressure: as estimateCleanupTime → secondsRemaining, the time\n // left after clearing remediation shrinks; once it's under the slack,\n // prioritise failed so remediation isn't stranded by session end.\n const availableTime = this._secondsRemaining - this.estimateCleanupTime();\n if (availableTime <= SessionController.FAILED_ENDGAME_SLACK_SECONDS) return true;\n\n // Light steady interleave so failed doesn't starve while supply is healthy.\n return this._supplyDrawsSinceFailed >= SessionController.FAILED_INTERLEAVE_EVERY;\n }\n\n public async nextCard(\n action: SessionAction = 'dismiss-success'\n ): Promise<HydratedCard<TView> | null> {\n // [perf] parked: nextCard provenance/timing (awaitedReplan, wedgeRuns)\n // const tNext0 = performance.now();\n // let awaitedInFlightReplan = false;\n // let wedgeRuns = 0;\n // dismiss (or sort to failedQ) the current card\n this.dismissCurrentCard(action);\n\n // Decrement card guarantee counter\n if (this._minCardsGuarantee > 0) {\n this._minCardsGuarantee--;\n this.log(`[CardGuarantee] ${this._minCardsGuarantee} guaranteed cards remaining`);\n }\n\n // If a replan is in flight AND we have nothing queued to serve, wait for\n // it. When queues still have cards, draw from them immediately and let\n // the replan land asynchronously — blocking here adds visible lag\n // between cards for a marginal scoring-freshness benefit. The\n // wedge-breaker below handles the genuinely-empty case.\n if (\n this._replanPromise &&\n this.supplyQ.length === 0 &&\n this.failedQ.length === 0\n ) {\n this.log('nextCard: queues empty, awaiting in-flight replan before drawing');\n // awaitedInFlightReplan = true; // [perf] parked\n await this._replanPromise;\n }\n\n // --- Replan triggers ---\n //\n // Two flavors:\n //\n // (a) OPPORTUNISTIC PREFETCH (best-effort, may coalesce, may no-op):\n // `depletion` and `quality` triggers below. Their job is to make\n // replans happen *early*, so the user doesn't wait. They are\n // *not* responsible for making replans happen *at all* — if every\n // one of them gets eaten by coalescing or suppression, that's\n // fine. They are perf optimizations.\n //\n // (b) LOAD-BEARING WEDGE-BREAKER (correctness):\n // Below, right before the draw loop. Invariant: if the clock is\n // ticking and we'd otherwise serve null, the pipeline runs. No\n // coalesce, no latch, no flag. This is the *only* guarantee.\n //\n // Rule of thumb: a redundant pipeline run is a perf bug, a missing\n // pipeline run is a correctness bug. Bias toward the cheaper failure.\n\n // Opportunistic depletion: supplyQ running dry → background prefetch.\n // No latch — if this fires repeatedly when the pipeline keeps coming\n // back empty, the wedge-breaker's local backoff handles spin protection.\n //\n // Threshold sized to give the pipeline enough lead time to land the\n // replan before the user empties the queue. Previously hardcoded to 1,\n // which raced user pace against pipeline latency — fast users would hit\n // an empty queue mid-session and feel the wedge-breaker's synchronous\n // pipeline call as a \"hang\". DEPLETION_PREFETCH_THRESHOLD trades a\n // slightly earlier prefetch (which is anyway desirable for content\n // freshness) for a much more reliable lead time.\n if (\n this.supplyQ.length <= SessionController.DEPLETION_PREFETCH_THRESHOLD &&\n this._secondsRemaining > 0 &&\n !this._replanPromise\n ) {\n this._suppressQualityReplan = false; // burst is (nearly) consumed\n this.log(\n `[AutoReplan:depletion] supplyQ has ${this.supplyQ.length} card(s) ` +\n `(${this.failedQ.length} failed pending) with ${this._secondsRemaining}s remaining. ` +\n `Triggering background replan.`\n );\n // label is observability-only (overlay/logs); does not affect coalescing.\n // mode:'merge' preserves any already-queued cards (e.g. an undrawn\n // prescribed WST whose one-shot requireCards won't be re-asserted by this\n // bare replan) instead of replaceAll() wiping them. See mergeToFront.\n void this.requestReplan({ label: 'auto:depletion', mode: 'merge' });\n }\n\n // Opportunistic quality: few well-indicated cards remain.\n // Suppressed after a burst replan to avoid clobbering burst cards.\n const REPLAN_BUFFER = 3;\n if (\n !this._suppressQualityReplan &&\n this._wellIndicatedRemaining <= REPLAN_BUFFER &&\n this.supplyQ.length > 0 &&\n !this._replanPromise\n ) {\n this.log(\n `[AutoReplan:quality] ${this._wellIndicatedRemaining} well-indicated cards remaining ` +\n `(supplyQ: ${this.supplyQ.length}). Triggering background replan.`\n );\n // label is observability-only (overlay/logs); does not affect coalescing.\n void this.requestReplan({ label: 'auto:quality' });\n }\n\n if (this._secondsRemaining <= 0 && this.failedQ.length === 0 && this._minCardsGuarantee <= 0) {\n this._currentCard = null;\n endSessionTracking();\n void this._terminate();\n return null;\n }\n\n // Wedge-breaker (correctness path).\n //\n // If we'd otherwise be about to draw from empty queues with time on\n // the clock, run the pipeline. Bypasses requestReplan() coalesce\n // because coalescing into a previous run that we now know produced\n // insufficient content is the exact failure mode this defends against.\n //\n // Bounded by an empty-streak counter: if the pipeline consistently\n // returns nothing, we eventually give up and let the session end\n // gracefully rather than spin forever.\n const WEDGE_MAX_EMPTY_STREAK = 3;\n const WEDGE_BACKOFF_MS = 250;\n let wedgeEmptyStreak = 0;\n while (\n this._secondsRemaining > 0 &&\n this.supplyQ.length === 0 &&\n this.failedQ.length === 0\n ) {\n this.log(\n `[WedgeBreaker] All queues empty with ${this._secondsRemaining}s remaining. ` +\n `Running pipeline (attempt ${wedgeEmptyStreak + 1}/${WEDGE_MAX_EMPTY_STREAK}).`\n );\n await this._replanUncoalesced({ label: 'wedge-breaker' });\n // wedgeRuns++; // [perf] parked\n if (\n this.supplyQ.length === 0 &&\n this.failedQ.length === 0\n ) {\n wedgeEmptyStreak++;\n if (wedgeEmptyStreak >= WEDGE_MAX_EMPTY_STREAK) {\n this.log(\n `[WedgeBreaker] Pipeline returned no content ${WEDGE_MAX_EMPTY_STREAK} consecutive ` +\n `times. Giving up; session will end.`\n );\n break;\n }\n await new Promise((resolve) => setTimeout(resolve, WEDGE_BACKOFF_MS));\n } else {\n wedgeEmptyStreak = 0;\n }\n }\n\n // Try multiple cards in case some fail hydration (e.g., deleted from DB)\n const MAX_SKIP = 20;\n for (let attempt = 0; attempt < MAX_SKIP; attempt++) {\n const nextItem = this._selectNextItemToHydrate();\n if (!nextItem) {\n this._currentCard = null;\n endSessionTracking();\n void this._terminate();\n return null;\n }\n\n // Look up in hydration cache\n let card = this.hydrationService.getHydratedCard(nextItem.cardID);\n\n // If not ready, wait for it\n if (!card) {\n card = await this.hydrationService.waitForCard(nextItem.cardID);\n }\n\n // Remove from source queue now that we're consuming it\n this.removeItemFromQueue(nextItem);\n\n if (card) {\n // Trigger background hydration to maintain cache (async, non-blocking)\n await this.hydrationService.ensureHydratedCards();\n this._currentCard = card;\n\n // Record presentation for debugging. `origin` is the item's nature\n // (new vs review); `queueSource` is which controller queue it was drawn\n // from (supplyQ vs the remediation failedQ).\n const origin = nextItem.status === 'review' || nextItem.status === 'failed-review' ? 'review' :\n nextItem.status === 'new' || nextItem.status === 'failed-new' ? 'new' : 'failed';\n const queueSource = nextItem.status.startsWith('failed') ? 'failedQ' : 'supplyQ';\n\n recordCardPresentation(\n nextItem.cardID,\n nextItem.courseID,\n this.courseNameCache.get(nextItem.courseID),\n origin,\n queueSource,\n nextItem.score\n );\n\n // Tell the sources (a new card discharges a pipeline's intake valve).\n for (const source of this.sources) {\n source.notePresented?.({\n cardId: nextItem.cardID,\n courseId: nextItem.courseID,\n status: nextItem.status,\n });\n }\n\n // Snapshot queue state\n snapshotQueues(this.supplyQ.length, this.failedQ.length);\n\n // [perf] parked: per-draw nextCard timing\n // logger.info(\n // `[perf][nextCard] -> ${card.item.cardID} in ${(performance.now() - tNext0).toFixed(0)}ms ` +\n // `(awaitedReplan=${awaitedInFlightReplan} wedgeRuns=${wedgeRuns})`\n // );\n return card;\n }\n\n // Card failed hydration (deleted from DB?) — skip and clean up\n this.log(`Skipping card ${nextItem.cardID}: hydration failed, trying next`);\n if (isReview(nextItem)) {\n this.srsService.removeReview(nextItem.reviewID);\n }\n }\n\n this.log(`Exhausted ${MAX_SKIP} skip attempts finding a hydratable card`);\n this._currentCard = null;\n endSessionTracking();\n void this._terminate();\n return null;\n }\n\n /** Not awaited — the host renders the end screen off `nextCard()`'s null. */\n private _terminate(): void {\n void this.endSession().catch((e) => {\n logger.warn(`[SessionController] endSession failed: ${e}`);\n });\n }\n\n /**\n * Public API for processing user responses to cards.\n * @param cardRecord User's response record\n * @param cardHistory Promise resolving to the card's history\n * @param courseRegistrationDoc User's course registration document\n * @param currentCard Current study session record\n * @param courseId Course identifier\n * @param cardId Card identifier\n * @param maxAttemptsPerView Maximum attempts allowed per view\n * @param maxSessionViews Maximum session views for this card\n * @param sessionViews Current number of session views\n * @returns ResponseResult with navigation and UI instructions\n */\n public async submitResponse(\n cardRecord: CardRecord,\n cardHistory: Promise<CardHistory<CardRecord>>,\n courseRegistrationDoc: CourseRegistrationDoc,\n currentCard: StudySessionRecord,\n courseId: string,\n cardId: string,\n maxAttemptsPerView: number,\n maxSessionViews: number,\n sessionViews: number\n ): Promise<ResponseResult> {\n const studySessionItem: StudySessionItem = {\n ...currentCard.item,\n };\n\n const result = await this.services.response.processResponse(\n cardRecord,\n cardHistory,\n studySessionItem,\n courseRegistrationDoc,\n currentCard,\n courseId,\n cardId,\n maxAttemptsPerView,\n maxSessionViews,\n sessionViews\n );\n\n // Surface the processed outcome to any registered observers (e.g. a\n // difficulty-booster that bumps session hints on a failed exercise tag).\n // Runs after ELO/SRS recording, before the caller navigates. Isolated so\n // a faulty observer can't break response handling.\n await this._notifyOutcomeObservers(cardRecord, currentCard, result);\n\n return result;\n }\n\n private dismissCurrentCard(action: SessionAction = 'dismiss-success') {\n if (this._currentCard) {\n // this.log(`Running dismissCurrentCard on ${this._currentCard!.qualifiedID}`);\n // if (action.includes('dismiss')) {\n // if (this._currentCard.status === 'review' ||\n // this._currentCard.status === 'failed-review') {\n // removeScheduledCardReview(this.user.getUsername(),\n // (this._currentCard as StudySessionReviewItem).reviewID);\n // this.log(`Dismissed review card: ${this._currentCard.qualifiedID}`)\n // }\n // }\n\n if (action === 'dismiss-success') {\n // Remove from hydration cache to free memory\n this.hydrationService.removeCard(this._currentCard.item.cardID);\n // schedule a review - currently done in Study.vue\n } else if (action === 'marked-failed') {\n // Card stays in hydration cache for re-use (no removeCard call)\n\n let failedItem: StudySessionFailedItem;\n\n if (isReview(this._currentCard.item)) {\n failedItem = {\n cardID: this._currentCard.item.cardID,\n courseID: this._currentCard.item.courseID,\n contentSourceID: this._currentCard.item.contentSourceID,\n contentSourceType: this._currentCard.item.contentSourceType,\n status: 'failed-review',\n reviewID: this._currentCard.item.reviewID,\n };\n } else {\n failedItem = {\n cardID: this._currentCard.item.cardID,\n courseID: this._currentCard.item.courseID,\n contentSourceID: this._currentCard.item.contentSourceID,\n contentSourceType: this._currentCard.item.contentSourceType,\n status: 'failed-new',\n };\n }\n\n this.failedQ.add(failedItem, failedItem.cardID);\n // Reset the failed-interleave cadence so a just-failed card gets spacing:\n // it now waits FAILED_INTERLEAVE_EVERY supply draws before being\n // re-presented, rather than being instantly \"due\" because the counter\n // had already climbed during a healthy supply run. (Endgame pressure in\n // _shouldInterleaveFailed still overrides this near session end.)\n this._supplyDrawsSinceFailed = 0;\n } else if (action === 'dismiss-error') {\n // Remove from cache on error as well\n this.hydrationService.removeCard(this._currentCard.item.cardID);\n } else if (action === 'dismiss-failed') {\n // Remove from cache - card has been fully processed after failure cleanup\n this.hydrationService.removeCard(this._currentCard.item.cardID);\n }\n }\n }\n\n /**\n * Remove an item from its source queue after consumption by nextCard().\n */\n private removeItemFromQueue(item: StudySessionItem): void {\n // Durable-until-drawn requirements: a caller may place a card ID in the\n // session-durable `requireCards` (via mergeSessionHints) so every later\n // replan re-asserts it at +INF until it actually surfaces — e.g. a\n // prescribed intro follow-up that must survive the replace-mode burst/auto\n // replans that would otherwise clobber a one-shot requirement. The\n // requirement is satisfied the instant the card is drawn, so clear it here\n // (the single consumption choke-point) to stop it being re-injected forever\n // and to bound accumulation. Generic: card-ID only, no domain vocabulary.\n this._clearDurableRequirement(item.cardID);\n\n // Record the draw immediately (earlier than _sessionRecord, which waits for\n // a response) so getWeightedContent can keep this card out of supplyQ on any\n // replan that lands after this draw.\n this._servedCardIds.add(item.cardID);\n\n // Item should be at the front of one of the two queues. Track the\n // failed-interleave cadence: reset on a failed draw, advance on a supply draw.\n if (this.failedQ.peek(0)?.cardID === item.cardID) {\n this.failedQ.dequeue((queueItem) => queueItem.cardID);\n this._supplyDrawsSinceFailed = 0;\n } else if (this.supplyQ.peek(0)?.cardID === item.cardID) {\n this.supplyQ.dequeue((queueItem) => queueItem.cardID);\n this._supplyDrawsSinceFailed++;\n if (this._wellIndicatedRemaining > 0) {\n this._wellIndicatedRemaining--;\n }\n }\n }\n\n /**\n * Remove a satisfied card ID from the durable session-hint `requireCards`\n * list. Called when a card is consumed (see removeItemFromQueue). No-op if\n * the card was not a durable requirement.\n *\n * Matches literal IDs only: a glob/pattern requirement (which may stand for\n * several cards) is NOT considered satisfied by a single draw and is left in\n * place — durable patterns are the caller's responsibility, one-shot `hints`\n * remain the right tool for them.\n */\n private _clearDurableRequirement(cardID: string): void {\n const req = this._sessionHints?.requireCards;\n if (!req || req.length === 0) return;\n const next = req.filter((id) => id !== cardID);\n if (next.length === req.length) return; // not a durable requirement\n this._sessionHints = {\n ...this._sessionHints!,\n requireCards: next.length > 0 ? next : undefined,\n };\n this.log(`[Replan] Durable requirement satisfied & cleared on draw: ${cardID}`);\n }\n\n /**\n * End the session and record learning outcomes.\n *\n * This method aggregates all responses from the session and records a\n * UserOutcomeRecord if evolutionary orchestration is enabled.\n */\n /**\n * Idempotent. Called from every `nextCard()` path that returns null; hosts\n * should also call it with `'abandoned'` when tearing down mid-session.\n */\n public async endSession(reason: 'closed' | 'abandoned' = 'closed'): Promise<void> {\n if (this._sessionClosed) return;\n this._sessionClosed = true;\n\n clearInterval(this._intervalHandle);\n setDebugSessionId(undefined);\n\n // Closed even with zero responses — \"answered nothing\" is itself a finding.\n await this._closeSessionDoc(reason);\n\n if (!this._sessionRecord || this._sessionRecord.length === 0) {\n return;\n }\n\n const questionRecords = this._sessionRecord\n .flatMap((r) => r.records)\n .filter((r): r is QuestionRecord => (r as any).userAnswer !== undefined);\n\n if (questionRecords.length === 0) {\n return;\n }\n\n // We need to access the orchestration context.\n // Ideally this would be passed in or available via services.\n // For now, we'll try to get it from one of the content sources if possible,\n // or skip if we can't access it.\n\n // Try to find a source that supports orchestration\n let orchestrationContext = null;\n const strategies: string[] = [];\n\n for (const source of this.sources) {\n if (source.getOrchestrationContext) {\n try {\n orchestrationContext = await source.getOrchestrationContext();\n // Also try to get strategy IDs if available on the source (e.g. Pipeline)\n if ((source as any).getStrategyIds) {\n strategies.push(...(source as any).getStrategyIds());\n }\n } catch (e) {\n logger.warn(`[SessionController] Failed to get orchestration context: ${e}`);\n }\n if (orchestrationContext) break;\n }\n }\n\n if (!orchestrationContext) {\n logger.debug('[SessionController] No orchestration context available, skipping outcome recording');\n return;\n }\n\n // Use current time as period end\n const periodEnd = new Date().toISOString();\n // Use session start time as period start\n const periodStart = new Date(this.startTime).toISOString();\n\n await recordUserOutcome(\n orchestrationContext,\n periodStart,\n periodEnd,\n questionRecords,\n strategies\n );\n }\n\n private async _closeSessionDoc(reason: 'closed' | 'abandoned'): Promise<void> {\n // Ordered behind the open write; it swallows its own errors.\n if (this._openDocPromise) await this._openDocPromise;\n\n const doc = this._sessionDoc;\n if (!doc) return;\n\n const records = this._sessionRecord.flatMap((r) => r.records);\n const questionRecords = records.filter(isQuestionRecord);\n\n try {\n const closed: StudySessionDoc = {\n ...doc,\n status: reason,\n endTime: new Date().toISOString(),\n tally: {\n cardsPresented: this._sessionRecord.length,\n responses: records.length,\n correct: questionRecords.filter((r) => r.isCorrect).length,\n incorrect: questionRecords.filter((r) => !r.isCorrect).length,\n failedQRemaining: this.failedQ.length,\n secondsRemaining: Math.max(0, this._secondsRemaining),\n },\n runs: [...this._runLog],\n eloEvents: [...this._eloLog],\n finalHints: this._sessionHints,\n stateAtEnd: await this._captureState('end'),\n };\n this._sessionDoc = closed;\n await this.dataLayer.getUserDB().putStudySession(closed);\n this.log(\n `[Session] Session record ${closed._id} -> ${reason} ` +\n `(${closed.tally!.cardsPresented} cards, ${closed.tally!.responses} responses, ` +\n `${this._runLog.length} pipeline runs)`\n );\n } catch (e) {\n logger.warn(`[SessionController] Failed to close session record: ${e}`);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAuOA,MAAM,uBAAuB;;AAG7B,SAAS,KAAK,GAAmB;AAC/B,QAAO,OAAO,EAAE,YAAY,EAAE,CAAC;;AAGjC,SAAS,UAAU,GAAuC;AACxD,QAAO;EACL,QAAQ,EAAE;EACV,QAAQ,EAAE;EACV,GAAI,EAAE,YAAY,EAAE,WAAW,EAAE,WAAW,GAAG,EAAE;EACjD,GAAI,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,GAAG,EAAE;EAE9C,OAAO,OAAO,SAAS,EAAE,WAAW,GAAG,KAAK,EAAE,WAAW,GAAG;EAC5D,UAAU,EAAE;EACb;;AAGH,SAAS,eAAe,GAA4C;AAClE,QAAO;EACL,GAAG,UAAU,EAAE;EACf,OAAO,EAAE,WACN,Q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C;AAE5E,MAAI,KAAK,gBAAiB,OAAM,KAAK;EAErC,MAAM,MAAM,KAAK;AACjB,MAAI,CAAC,IAAK;EAEV,MAAM,UAAU,KAAK,eAAe,SAAS,MAAM,EAAE,QAAQ;EAC7D,MAAM,kBAAkB,QAAQ,OAAO,iBAAiB;AAExD,MAAI;GACF,MAAM,SAA0B;IAC9B,GAAG;IACH,QAAQ;IACR,0BAAS,IAAI,MAAM,EAAC,aAAa;IACjC,OAAO;KACL,gBAAgB,KAAK,eAAe;KACpC,WAAW,QAAQ;KACnB,SAAS,gBAAgB,QAAQ,MAAM,EAAE,UAAU,CAAC;KACpD,WAAW,gBAAgB,QAAQ,MAAM,CAAC,EAAE,UAAU,CAAC;KACvD,kBAAkB,KAAK,QAAQ;KAC/B,kBAAkB,KAAK,IAAI,GAAG,KAAK,kBAAkB;KACtD;IACD,MAAM,CAAC,GAAG,KAAK,QAAQ;IACvB,WAAW,CAAC,GAAG,KAAK,QAAQ;IAC5B,YAAY,KAAK;IACjB,YAAY,MAAM,KAAK,cAAc,MAAM;IAC5C;AACD,QAAK,cAAc;AACnB,SAAM,KAAK,UAAU,WAAW,CAAC,gBAAgB,OAAO;AACxD,QAAK,IACH,4BAA4B,OAAO,IAAI,MAAM,OAAO,IAChD,OAAO,MAAO,eAAe,UAAU,OAAO,MAAO,UAAU,cAChE,KAAK,QAAQ,OAAO,iBACxB;WACM,GAAG;AACV,UAAO,KAAK,uDAAuD,IAAI"}
@@ -1,5 +1,5 @@
1
1
  import { CourseConfig } from '@vue-skuilder/common';
2
- import { D as DocType } from './types-legacy-fT5Y1Wuy.js';
2
+ import { D as DocType } from './types-legacy-DdVjg81H.js';
3
3
 
4
4
  interface StaticCourseManifest {
5
5
  version: string;
@@ -165,4 +165,4 @@ interface QuestionRecord extends CardRecord, Evaluation {
165
165
  priorAttemps: number;
166
166
  }
167
167
 
168
- export { type CardData as C, DocType as D, type Field as F, GuestUsername as G, type QualifiedCardID as Q, type SkuilderCourseData as S, type TagStub as T, type Tag as a, type DisplayableData as b, type CardRecord as c, type QuestionRecord as d, type CardHistory as e, type CourseListData as f, type DataShapeData as g, type QuestionData as h, DocTypePrefixes as i, log as l };
168
+ export { type CardData as C, DocType as D, type Field as F, GuestUsername as G, type QualifiedCardID as Q, type SkuilderCourseData as S, type TagStub as T, type Tag as a, type DisplayableData as b, type CardRecord as c, type QuestionRecord as d, type CardHistory as e, DocTypePrefixes as f, type CourseListData as g, type DataShapeData as h, type QuestionData as i, log as l };
@@ -1,5 +1,5 @@
1
- export { A as AttachmentData, C as ChunkMetadata, D as DesignDocument, I as IndexMetadata, a as PackedCourseData, P as PackerConfig, S as StaticCourseManifest } from '../../types-DChCz22D.js';
2
- export { C as CouchDBToStaticPacker } from '../../index-BLDpFYG3.js';
1
+ export { A as AttachmentData, C as ChunkMetadata, D as DesignDocument, I as IndexMetadata, a as PackedCourseData, P as PackerConfig, S as StaticCourseManifest } from '../../types-DF0JuPbs.js';
2
+ export { C as CouchDBToStaticPacker } from '../../index-C745YB_6.js';
3
3
  import '@vue-skuilder/common';
4
- import '../../types-legacy-fT5Y1Wuy.js';
4
+ import '../../types-legacy-DdVjg81H.js';
5
5
  import 'moment';
@@ -0,0 +1,30 @@
1
+ import "../_virtual/_rolldown/runtime.mjs";
2
+ //#region src/util/perfMarks.ts
3
+ /**
4
+ * User Timing marks for session and sync milestones.
5
+ *
6
+ * Names are `sk:`-prefixed (apps add their own, e.g. LP's `lp:`). Read them with
7
+ * `performance.getEntriesByType('mark' | 'measure')`: synthetic runs (Playwright,
8
+ * Lighthouse's `user-timings`) and, later, real-user measurement.
9
+ *
10
+ * Marks never throw: a missing or partial User Timing API is a no-op.
11
+ */
12
+ function perfMark(name, detail) {
13
+ try {
14
+ globalThis.performance?.mark(name, detail ? { detail } : void 0);
15
+ } catch {}
16
+ }
17
+ /** A measure from `start` (a mark name or a `performance.now()` value) to now or `end`. */
18
+ function perfMeasure(name, start, end, detail) {
19
+ try {
20
+ globalThis.performance?.measure(name, {
21
+ start,
22
+ ...end !== void 0 ? { end } : {},
23
+ ...detail ? { detail } : {}
24
+ });
25
+ } catch {}
26
+ }
27
+ //#endregion
28
+ export { perfMark, perfMeasure };
29
+
30
+ //# sourceMappingURL=perfMarks.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"perfMarks.mjs","names":[],"sources":["../../src/util/perfMarks.ts"],"sourcesContent":["/**\n * User Timing marks for session and sync milestones.\n *\n * Names are `sk:`-prefixed (apps add their own, e.g. LP's `lp:`). Read them with\n * `performance.getEntriesByType('mark' | 'measure')`: synthetic runs (Playwright,\n * Lighthouse's `user-timings`) and, later, real-user measurement.\n *\n * Marks never throw: a missing or partial User Timing API is a no-op.\n */\n\nexport function perfMark(name: string, detail?: Record<string, unknown>): void {\n try {\n globalThis.performance?.mark(name, detail ? { detail } : undefined);\n } catch {\n // no User Timing (or no `detail` support): nothing to record\n }\n}\n\n/** A measure from `start` (a mark name or a `performance.now()` value) to now or `end`. */\nexport function perfMeasure(\n name: string,\n start: string | number,\n end?: string | number,\n detail?: Record<string, unknown>\n): void {\n try {\n globalThis.performance?.measure(name, {\n start,\n ...(end !== undefined ? { end } : {}),\n ...(detail ? { detail } : {}),\n });\n } catch {\n // unknown start mark, or no User Timing: nothing to record\n }\n}\n"],"mappings":";;;;;;;;;;;AAUA,SAAgB,SAAS,MAAc,QAAwC;AAC7E,KAAI;AACF,aAAW,aAAa,KAAK,MAAM,SAAS,EAAE,QAAQ,GAAG,KAAA,EAAU;SAC7D;;;AAMV,SAAgB,YACd,MACA,OACA,KACA,QACM;AACN,KAAI;AACF,aAAW,aAAa,QAAQ,MAAM;GACpC;GACA,GAAI,QAAQ,KAAA,IAAY,EAAE,KAAK,GAAG,EAAE;GACpC,GAAI,SAAS,EAAE,QAAQ,GAAG,EAAE;GAC7B,CAAC;SACI"}