@vue-skuilder/db 0.3.3 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{contentSource-CSI0pJ2D.d.ts → contentSource-CPM872yn.d.ts} +2 -1
- package/dist/core/index.cjs +163 -49
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.ts +3 -3
- package/dist/core/navigators/filters/skillPressure.mjs +109 -0
- package/dist/core/navigators/filters/skillPressure.mjs.map +1 -0
- package/dist/core/navigators/index.mjs +7 -3
- package/dist/core/navigators/index.mjs.map +1 -1
- package/dist/core/versionStamps.mjs +1 -1
- package/dist/{dataLayerProvider-D5n1gGc_.d.ts → dataLayerProvider-CaNgzRCz.d.ts} +1 -1
- package/dist/diagnostics/index.d.ts +2 -2
- package/dist/impl/couch/index.cjs +2 -1
- package/dist/impl/couch/index.cjs.map +1 -1
- package/dist/impl/couch/index.d.ts +2 -2
- package/dist/impl/static/index.cjs +2 -1
- package/dist/impl/static/index.cjs.map +1 -1
- package/dist/impl/static/index.d.ts +2 -2
- package/dist/index.cjs +205 -91
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +3 -3
- package/package.json +3 -3
- package/src/core/navigators/filters/index.ts +3 -0
- package/src/core/navigators/filters/skillPressure.ts +194 -0
- package/src/core/navigators/index.ts +5 -0
- package/tests/core/navigators/skillPressureFilter.test.ts +84 -0
package/dist/core/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { A as AdminDBInterface, d as AssignedCard, a as AssignedContent, c as AssignedCourse, b as AssignedTag, C as ClassroomDBInterface, S as StudentClassroomDBInterface, T as TeacherClassroomDBInterface } from '../classroomDB-DLTtLZct.js';
|
|
2
|
-
import { av as LearnableWeight, T as UserOutcomeRecord, aw as OrchestrationContext, W as WeightedCard, C as CourseDBInterface } from '../contentSource-
|
|
3
|
-
export { P as ActivityRecord, ae as CardFilter, ag as CardFilterFactory, ah as CardGenerator, aj as CardGeneratorFactory, K as ClassroomRegistration, J as ClassroomRegistrationDesignation, L as ClassroomRegistrationDoc, c as ContentNavigationStrategyData, d as ContentNavigator, v as ContentSourceID, b as CourseInfo, Q as CourseRegistration, g as CourseRegistrationDoc, a as CoursesDBInterface, af as FilterContext, at as FilterImpact, F as FilterKind, ai as GeneratorContext, G as GeneratorResult, as as GeneratorSummary, _ as HYDRATION_MARKER_ID, $ as HydrationMarker, a0 as NavigatorConstructor, N as NavigatorRole, ab as NavigatorRoles, aa as Navigators, au as PipelineForecaster, aq as PipelineRunReport, R as ReplanHints, ar as RunReportCard, f as ScheduledCard, m as SessionEloEvent, h as SessionStateSnapshot, x as SessionStateSnapshotProvider, M as SessionTrackingData, a8 as StrategyContribution, o as StudyContentSource, e as StudySessionDoc, p as StudySessionFailedItem, q as StudySessionFailedNewItem, r as StudySessionFailedReviewItem, S as StudySessionItem, s as StudySessionNewItem, t as StudySessionReviewItem, k as StudySessionRunCard, n as StudySessionRunCardTrail, i as StudySessionRunSummary, O as UserConfig, H as UserCourseSetting, E as UserCourseSettings, B as UserDBAuthenticator, U as UserDBInterface, z as UserDBReader, A as UserDBWriter, Y as UserHydrationState, Z as UserHydrationStatus, I as UsrCrsDataInterface, ax as computeDeviation, az as computeEffectiveWeight, ay as computeSpread, aA as createOrchestrationContext, ap as drainCapturedRuns, am as getActivePipeline, a9 as getCardOrigin, a5 as getRegisteredFilterKind, a2 as getRegisteredNavigator, a6 as getRegisteredNavigatorNames, a4 as getRegisteredNavigatorRole, ao as getRunsForSession, w as getStudySource, a3 as hasRegisteredNavigator, a7 as initializeNavigatorRegistry, ad as isFilter, ac as isGenerator, u as isReview, V as makeStudySessionId, al as mountPipelineDebugger, X as newSessionId, ak as pipelineDebugAPI, a1 as registerNavigator, an as setDebugSessionId } from '../contentSource-
|
|
4
|
-
export { D as DataLayerProvider } from '../dataLayerProvider-
|
|
2
|
+
import { av as LearnableWeight, T as UserOutcomeRecord, aw as OrchestrationContext, W as WeightedCard, C as CourseDBInterface } from '../contentSource-CPM872yn.js';
|
|
3
|
+
export { P as ActivityRecord, ae as CardFilter, ag as CardFilterFactory, ah as CardGenerator, aj as CardGeneratorFactory, K as ClassroomRegistration, J as ClassroomRegistrationDesignation, L as ClassroomRegistrationDoc, c as ContentNavigationStrategyData, d as ContentNavigator, v as ContentSourceID, b as CourseInfo, Q as CourseRegistration, g as CourseRegistrationDoc, a as CoursesDBInterface, af as FilterContext, at as FilterImpact, F as FilterKind, ai as GeneratorContext, G as GeneratorResult, as as GeneratorSummary, _ as HYDRATION_MARKER_ID, $ as HydrationMarker, a0 as NavigatorConstructor, N as NavigatorRole, ab as NavigatorRoles, aa as Navigators, au as PipelineForecaster, aq as PipelineRunReport, R as ReplanHints, ar as RunReportCard, f as ScheduledCard, m as SessionEloEvent, h as SessionStateSnapshot, x as SessionStateSnapshotProvider, M as SessionTrackingData, a8 as StrategyContribution, o as StudyContentSource, e as StudySessionDoc, p as StudySessionFailedItem, q as StudySessionFailedNewItem, r as StudySessionFailedReviewItem, S as StudySessionItem, s as StudySessionNewItem, t as StudySessionReviewItem, k as StudySessionRunCard, n as StudySessionRunCardTrail, i as StudySessionRunSummary, O as UserConfig, H as UserCourseSetting, E as UserCourseSettings, B as UserDBAuthenticator, U as UserDBInterface, z as UserDBReader, A as UserDBWriter, Y as UserHydrationState, Z as UserHydrationStatus, I as UsrCrsDataInterface, ax as computeDeviation, az as computeEffectiveWeight, ay as computeSpread, aA as createOrchestrationContext, ap as drainCapturedRuns, am as getActivePipeline, a9 as getCardOrigin, a5 as getRegisteredFilterKind, a2 as getRegisteredNavigator, a6 as getRegisteredNavigatorNames, a4 as getRegisteredNavigatorRole, ao as getRunsForSession, w as getStudySource, a3 as hasRegisteredNavigator, a7 as initializeNavigatorRegistry, ad as isFilter, ac as isGenerator, u as isReview, V as makeStudySessionId, al as mountPipelineDebugger, X as newSessionId, ak as pipelineDebugAPI, a1 as registerNavigator, an as setDebugSessionId } from '../contentSource-CPM872yn.js';
|
|
4
|
+
export { D as DataLayerProvider } from '../dataLayerProvider-CaNgzRCz.js';
|
|
5
5
|
import { D as DocType, d as QuestionRecord, f as DocTypePrefixes, e as CardHistory, c as CardRecord } from '../types-legacy-DdVjg81H.js';
|
|
6
6
|
export { C as CardData, g as CourseListData, h as DataShapeData, b as DisplayableData, F as Field, G as GuestUsername, Q as QualifiedCardID, i as QuestionData, S as SkuilderCourseData, a as Tag, T as TagStub, l as log } from '../types-legacy-DdVjg81H.js';
|
|
7
7
|
import { DataShape, ParsedCard } from '@vue-skuilder/common';
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import "../../../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
import { ContentNavigator } from "../index.mjs";
|
|
3
|
+
import { courseSecurity, skillNeed } from "@vue-skuilder/common";
|
|
4
|
+
//#region src/core/navigators/filters/skillPressure.ts
|
|
5
|
+
const DEFAULT_GAIN = .5;
|
|
6
|
+
const DEFAULT_SECURITY_WEIGHTS = {
|
|
7
|
+
shaky: .8,
|
|
8
|
+
unproven: .5
|
|
9
|
+
};
|
|
10
|
+
/** Pressure per skill tag for this learner; tags under no pressure are absent. */
|
|
11
|
+
function skillPressures(elo, config = {}) {
|
|
12
|
+
const out = /* @__PURE__ */ new Map();
|
|
13
|
+
const raise = (tag, pressure, why) => {
|
|
14
|
+
if (pressure <= 0) return;
|
|
15
|
+
const prev = out.get(tag);
|
|
16
|
+
if (!prev || pressure > prev.pressure) out.set(tag, {
|
|
17
|
+
pressure,
|
|
18
|
+
why
|
|
19
|
+
});
|
|
20
|
+
};
|
|
21
|
+
for (const s of skillNeed(elo, config).skills) raise(s.tag, s.need, `need ${s.need.toFixed(2)} (${Math.round(s.deficit)} below the skill median)`);
|
|
22
|
+
if (config.security !== false) {
|
|
23
|
+
const weights = {
|
|
24
|
+
...DEFAULT_SECURITY_WEIGHTS,
|
|
25
|
+
...config.security ?? {}
|
|
26
|
+
};
|
|
27
|
+
const { include, exclude, roles } = config;
|
|
28
|
+
const security = courseSecurity(elo, {
|
|
29
|
+
selector: {
|
|
30
|
+
include,
|
|
31
|
+
exclude,
|
|
32
|
+
roles
|
|
33
|
+
},
|
|
34
|
+
config: config.security ? config.security.config : void 0
|
|
35
|
+
});
|
|
36
|
+
for (const s of security.tags) {
|
|
37
|
+
if (s.status === "secure") continue;
|
|
38
|
+
const n = Math.min(s.attempts, 12);
|
|
39
|
+
raise(s.tag, weights[s.status], s.status === "shaky" ? `shaky (${s.right}/${n} right)` : `unproven (${s.attempts} recent attempts)`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
async function applySkillPressure(cards, context, config, source) {
|
|
45
|
+
if (!context.userCourseElo) return cards;
|
|
46
|
+
const pressures = skillPressures(context.userCourseElo, config);
|
|
47
|
+
if (pressures.size === 0) return cards;
|
|
48
|
+
const gain = config.gain ?? DEFAULT_GAIN;
|
|
49
|
+
return cards.map((card) => {
|
|
50
|
+
let top = null;
|
|
51
|
+
for (const tag of card.tags ?? []) {
|
|
52
|
+
const entry = pressures.get(tag);
|
|
53
|
+
if (entry && (!top || entry.pressure > top.entry.pressure)) top = {
|
|
54
|
+
tag,
|
|
55
|
+
entry
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
if (!top) return card;
|
|
59
|
+
const multiplier = 1 + gain * top.entry.pressure;
|
|
60
|
+
const score = card.score * multiplier;
|
|
61
|
+
return {
|
|
62
|
+
...card,
|
|
63
|
+
score,
|
|
64
|
+
provenance: [...card.provenance, {
|
|
65
|
+
strategy: "skillPressure",
|
|
66
|
+
strategyName: source.name,
|
|
67
|
+
strategyId: source.strategyId,
|
|
68
|
+
action: "boosted",
|
|
69
|
+
score,
|
|
70
|
+
reason: `skill pressure: ${top.tag} ${top.entry.why} → ×${multiplier.toFixed(2)}`
|
|
71
|
+
}]
|
|
72
|
+
};
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The skill pressure filter as a strategy-doc navigator (`implementingClass:
|
|
77
|
+
* 'skillPressure'`, serializedData: a SkillPressureConfig as JSON, or empty).
|
|
78
|
+
*/
|
|
79
|
+
var SkillPressureFilter = class SkillPressureFilter extends ContentNavigator {
|
|
80
|
+
name;
|
|
81
|
+
/** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
|
|
82
|
+
static kind = "signal";
|
|
83
|
+
kind = SkillPressureFilter.kind;
|
|
84
|
+
config;
|
|
85
|
+
constructor(user, course, strategyData) {
|
|
86
|
+
super(user, course, strategyData);
|
|
87
|
+
this.name = strategyData.name || "Skill Pressure";
|
|
88
|
+
let parsed = {};
|
|
89
|
+
try {
|
|
90
|
+
parsed = strategyData.serializedData ? JSON.parse(strategyData.serializedData) : {};
|
|
91
|
+
} catch {
|
|
92
|
+
parsed = {};
|
|
93
|
+
}
|
|
94
|
+
this.config = parsed;
|
|
95
|
+
}
|
|
96
|
+
transform(cards, context) {
|
|
97
|
+
return applySkillPressure(cards, context, this.config, {
|
|
98
|
+
name: this.name,
|
|
99
|
+
strategyId: this.strategyId || "NAVIGATION_STRATEGY-skillPressure"
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
async getWeightedCards(_limit) {
|
|
103
|
+
throw new Error("SkillPressureFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().");
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
//#endregion
|
|
107
|
+
export { SkillPressureFilter as default, skillPressures };
|
|
108
|
+
|
|
109
|
+
//# sourceMappingURL=skillPressure.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"skillPressure.mjs","names":[],"sources":["../../../../src/core/navigators/filters/skillPressure.ts"],"sourcesContent":["import {\n courseSecurity,\n skillNeed,\n type CourseElo,\n type SkillNeedConfig,\n type TagSecurityConfig,\n type TagSecurityStatus,\n} from '@vue-skuilder/common';\nimport type { CourseDBInterface } from '../../interfaces/courseDB';\nimport type { UserDBInterface } from '../../interfaces/userDB';\nimport type { ContentNavigationStrategyData } from '../../types/contentNavigationStrategy';\nimport { ContentNavigator } from '../index';\nimport type { WeightedCard } from '../index';\nimport type { GeneratorResult } from '../generators/types';\nimport type { CardFilter, FilterContext, FilterKind } from './types';\n\n// ============================================================================\n// SKILL PRESSURE FILTER\n// ============================================================================\n//\n// Leans selection toward the learner's weakest skills: a card exercising a\n// skill under pressure gets a small, bounded boost. \"Which skill\", kept\n// separate from ELO distance's \"what difficulty\", so each is its own line in\n// a card's provenance.\n//\n// A skill's pressure (0–1) is the larger of:\n// - need (common/skillNeed): how far its rating sits below the median of the\n// learner's skills;\n// - insecurity (common/tagSecurity), when enabled: a fixed weight for a met\n// skill that is shaky (right too rarely lately) or unproven (too little\n// recent evidence). This is what works down the insecure count a course may\n// gate new material on; need alone misses skills rated near the median but\n// missed lately, and skills with too few responses to rate.\n//\n// multiplier = 1 + gain · (the card's highest skill pressure). The max over a\n// card's tags, never the product, so a card naming several weak skills isn't\n// boosted several times.\n//\n// Acts on the whole heap, reviews included: its first effect under a review\n// backlog is on *which* reviews are served. A boost can't bring a card that no\n// generator retrieved; retrieval of a weak skill's unseen cards is a\n// generator's job.\n//\n// A `signal`. Not added by default: it re-weights every candidate, so a course\n// opts in with a `skillPressure` strategy doc (serializedData: a\n// SkillPressureConfig as JSON, or empty for the defaults).\n//\n// ============================================================================\n\nexport interface SkillPressureConfig extends SkillNeedConfig {\n /** Boost at pressure 1: multiplier = 1 + gain · pressure. Default 0.5 (cap ×1.5). */\n gain?: number;\n /**\n * Insecurity as pressure. `false` turns it off (need only). Weights are\n * need-equivalents, 0–1. Default: shaky 0.8, unproven 0.5. Uses the same\n * tag selector as need.\n */\n security?:\n | false\n | {\n shaky?: number;\n unproven?: number;\n /** Thresholds for secure / shaky / unproven. Default: the framework's. */\n config?: TagSecurityConfig;\n };\n}\n\nconst DEFAULT_GAIN = 0.5;\nconst DEFAULT_SECURITY_WEIGHTS: Record<Exclude<TagSecurityStatus, 'secure'>, number> = {\n shaky: 0.8,\n unproven: 0.5,\n};\n\ninterface SkillPressureEntry {\n pressure: number;\n why: string;\n}\n\n/** Pressure per skill tag for this learner; tags under no pressure are absent. */\nexport function skillPressures(\n elo: CourseElo,\n config: SkillPressureConfig = {}\n): Map<string, SkillPressureEntry> {\n const out = new Map<string, SkillPressureEntry>();\n const raise = (tag: string, pressure: number, why: string): void => {\n if (pressure <= 0) return;\n const prev = out.get(tag);\n if (!prev || pressure > prev.pressure) out.set(tag, { pressure, why });\n };\n\n for (const s of skillNeed(elo, config).skills) {\n raise(s.tag, s.need, `need ${s.need.toFixed(2)} (${Math.round(s.deficit)} below the skill median)`);\n }\n\n if (config.security !== false) {\n const weights = { ...DEFAULT_SECURITY_WEIGHTS, ...(config.security ?? {}) };\n const { include, exclude, roles } = config;\n const security = courseSecurity(elo, {\n selector: { include, exclude, roles },\n config: config.security ? config.security.config : undefined,\n });\n for (const s of security.tags) {\n if (s.status === 'secure') continue;\n const n = Math.min(s.attempts, 12);\n raise(\n s.tag,\n weights[s.status],\n s.status === 'shaky' ? `shaky (${s.right}/${n} right)` : `unproven (${s.attempts} recent attempts)`\n );\n }\n }\n return out;\n}\n\nasync function applySkillPressure(\n cards: WeightedCard[],\n context: FilterContext,\n config: SkillPressureConfig,\n source: { name: string; strategyId: string }\n): Promise<WeightedCard[]> {\n if (!context.userCourseElo) return cards;\n const pressures = skillPressures(context.userCourseElo, config);\n if (pressures.size === 0) return cards;\n const gain = config.gain ?? DEFAULT_GAIN;\n\n return cards.map((card) => {\n let top: { tag: string; entry: SkillPressureEntry } | null = null;\n for (const tag of card.tags ?? []) {\n const entry = pressures.get(tag);\n if (entry && (!top || entry.pressure > top.entry.pressure)) top = { tag, entry };\n }\n if (!top) return card;\n\n const multiplier = 1 + gain * top.entry.pressure;\n const score = card.score * multiplier;\n return {\n ...card,\n score,\n provenance: [\n ...card.provenance,\n {\n strategy: 'skillPressure',\n strategyName: source.name,\n strategyId: source.strategyId,\n action: 'boosted',\n score,\n reason: `skill pressure: ${top.tag} ${top.entry.why} → ×${multiplier.toFixed(2)}`,\n },\n ],\n };\n });\n}\n\n/**\n * The skill pressure filter as a strategy-doc navigator (`implementingClass:\n * 'skillPressure'`, serializedData: a SkillPressureConfig as JSON, or empty).\n */\nexport default class SkillPressureFilter extends ContentNavigator implements CardFilter {\n name: string;\n /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */\n static readonly kind: FilterKind = 'signal';\n readonly kind = SkillPressureFilter.kind;\n private config: SkillPressureConfig;\n\n constructor(\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n ) {\n super(user, course, strategyData);\n this.name = strategyData.name || 'Skill Pressure';\n let parsed: SkillPressureConfig = {};\n try {\n parsed = strategyData.serializedData ? JSON.parse(strategyData.serializedData) : {};\n } catch {\n parsed = {};\n }\n this.config = parsed;\n }\n\n transform(cards: WeightedCard[], context: FilterContext): Promise<WeightedCard[]> {\n return applySkillPressure(cards, context, this.config, {\n name: this.name,\n strategyId: this.strategyId || 'NAVIGATION_STRATEGY-skillPressure',\n });\n }\n\n async getWeightedCards(_limit: number): Promise<GeneratorResult> {\n throw new Error(\n 'SkillPressureFilter is a filter and should not be used as a generator. ' +\n 'Use Pipeline with a generator and this filter via transform().'\n );\n }\n}\n"],"mappings":";;;;AAmEA,MAAM,eAAe;AACrB,MAAM,2BAAiF;CACrF,OAAO;CACP,UAAU;CACX;;AAQD,SAAgB,eACd,KACA,SAA8B,EAAE,EACC;CACjC,MAAM,sBAAM,IAAI,KAAiC;CACjD,MAAM,SAAS,KAAa,UAAkB,QAAsB;AAClE,MAAI,YAAY,EAAG;EACnB,MAAM,OAAO,IAAI,IAAI,IAAI;AACzB,MAAI,CAAC,QAAQ,WAAW,KAAK,SAAU,KAAI,IAAI,KAAK;GAAE;GAAU;GAAK,CAAC;;AAGxE,MAAK,MAAM,KAAK,UAAU,KAAK,OAAO,CAAC,OACrC,OAAM,EAAE,KAAK,EAAE,MA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,QAAQ;IACR;IACA,QAAQ,mBAAmB,IAAI,IAAI,GAAG,IAAI,MAAM,IAAI,MAAM,WAAW,QAAQ,EAAE;IAChF,CACF;GACF;GACD;;;;;;AAOJ,IAAqB,sBAArB,MAAqB,4BAA4B,iBAAuC;CACtF;;CAEA,OAAgB,OAAmB;CACnC,OAAgB,oBAAoB;CACpC;CAEA,YACE,MACA,QACA,cACA;AACA,QAAM,MAAM,QAAQ,aAAa;AACjC,OAAK,OAAO,aAAa,QAAQ;EACjC,IAAI,SAA8B,EAAE;AACpC,MAAI;AACF,YAAS,aAAa,iBAAiB,KAAK,MAAM,aAAa,eAAe,GAAG,EAAE;UAC7E;AACN,YAAS,EAAE;;AAEb,OAAK,SAAS;;CAGhB,UAAU,OAAuB,SAAiD;AAChF,SAAO,mBAAmB,OAAO,SAAS,KAAK,QAAQ;GACrD,MAAM,KAAK;GACX,YAAY,KAAK,cAAc;GAChC,CAAC;;CAGJ,MAAM,iBAAiB,QAA0C;AAC/D,QAAM,IAAI,MACR,wIAED"}
|
|
@@ -91,18 +91,20 @@ async function initializeNavigatorRegistry() {
|
|
|
91
91
|
registerNavigator("elo", eloModule.default);
|
|
92
92
|
registerNavigator("srs", srsModule.default);
|
|
93
93
|
registerNavigator("prescribed", prescribedModule.default);
|
|
94
|
-
const [hierarchyModule, interferenceModule, relativePriorityModule, userTagPreferenceModule, eloDistanceModule] = await Promise.all([
|
|
94
|
+
const [hierarchyModule, interferenceModule, relativePriorityModule, userTagPreferenceModule, eloDistanceModule, skillPressureModule] = await Promise.all([
|
|
95
95
|
import("./filters/hierarchyDefinition.mjs"),
|
|
96
96
|
import("./filters/interferenceMitigator.mjs"),
|
|
97
97
|
import("./filters/relativePriority.mjs"),
|
|
98
98
|
import("./filters/userTagPreference.mjs"),
|
|
99
|
-
import("./filters/eloDistance.mjs")
|
|
99
|
+
import("./filters/eloDistance.mjs"),
|
|
100
|
+
import("./filters/skillPressure.mjs")
|
|
100
101
|
]);
|
|
101
102
|
registerNavigator("hierarchyDefinition", hierarchyModule.default);
|
|
102
103
|
registerNavigator("interferenceMitigator", interferenceModule.default);
|
|
103
104
|
registerNavigator("relativePriority", relativePriorityModule.default);
|
|
104
105
|
registerNavigator("userTagPreference", userTagPreferenceModule.default);
|
|
105
106
|
registerNavigator("eloDistance", eloDistanceModule.default);
|
|
107
|
+
registerNavigator("skillPressure", skillPressureModule.default);
|
|
106
108
|
logger.debug(`[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(", ")}`);
|
|
107
109
|
}
|
|
108
110
|
/**
|
|
@@ -131,6 +133,7 @@ let Navigators = /* @__PURE__ */ function(Navigators) {
|
|
|
131
133
|
Navigators["RELATIVE_PRIORITY"] = "relativePriority";
|
|
132
134
|
Navigators["USER_TAG_PREFERENCE"] = "userTagPreference";
|
|
133
135
|
Navigators["ELO_DISTANCE"] = "eloDistance";
|
|
136
|
+
Navigators["SKILL_PRESSURE"] = "skillPressure";
|
|
134
137
|
return Navigators;
|
|
135
138
|
}({});
|
|
136
139
|
/**
|
|
@@ -155,7 +158,8 @@ const NavigatorRoles = {
|
|
|
155
158
|
[Navigators.INTERFERENCE]: NavigatorRole.FILTER,
|
|
156
159
|
[Navigators.RELATIVE_PRIORITY]: NavigatorRole.FILTER,
|
|
157
160
|
[Navigators.USER_TAG_PREFERENCE]: NavigatorRole.FILTER,
|
|
158
|
-
[Navigators.ELO_DISTANCE]: NavigatorRole.FILTER
|
|
161
|
+
[Navigators.ELO_DISTANCE]: NavigatorRole.FILTER,
|
|
162
|
+
[Navigators.SKILL_PRESSURE]: NavigatorRole.FILTER
|
|
159
163
|
};
|
|
160
164
|
/**
|
|
161
165
|
* Check if a navigator implementation is a generator.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/core/navigators/index.ts"],"sourcesContent":["import { StudyContentSource, UserDBInterface, CourseDBInterface } from '..';\nimport type { FilterKind } from './filters/types';\n\n// Re-export filter types\nexport type { CardFilter, FilterContext, CardFilterFactory, FilterKind } from './filters/types';\n\n// Re-export generator types\nexport type { CardGenerator, GeneratorContext, CardGeneratorFactory, GeneratorResult, ReplanHints } from './generators/types';\n\n// Re-export the diversity re-rank stage (pipeline stage 3)\nexport {\n diversityRerank,\n DIVERSITY_STRENGTH,\n DIVERSITY_FLOOR,\n type DiversityRerankOptions,\n} from './diversityRerank';\nimport type { GeneratorResult, ReplanHints } from './generators/types';\n\n// Re-export pipeline debugger API\nexport {\n pipelineDebugAPI,\n mountPipelineDebugger,\n getActivePipeline,\n setDebugSessionId,\n getRunsForSession,\n drainCapturedRuns,\n type PipelineRunReport,\n type RunReportCard,\n type GeneratorSummary,\n type FilterImpact,\n} from './PipelineDebugger';\n\n// Re-export the commit-free forecast capability surface.\nexport type { PipelineForecaster } from './Pipeline';\nexport {\n getSrsBacklogDebug,\n clearSrsBacklogDebug,\n type SrsBacklogDebug,\n} from './SrsDebugger';\n\n// Re-export the generic strategy-pressure debug channel. `captureStrategyPressure`\n// is part of the consumer surface: client-defined strategies (registered via\n// registerNavigator) push their backpressure state through it for the live\n// session overlay.\nexport {\n captureStrategyPressure,\n getStrategyPressureDebug,\n clearStrategyPressureDebug,\n type StrategyPressureDebug,\n type PressureGaugeDebug,\n} from './StrategyPressureDebugger';\n\nimport { LearnableWeight } from '../types/contentNavigationStrategy';\nexport type { ContentNavigationStrategyData, LearnableWeight } from '../types/contentNavigationStrategy';\nimport type { ContentNavigationStrategyData } from '../types/contentNavigationStrategy';\nimport { logger } from '../../util/logger';\n\n// ============================================================================\n// NAVIGATOR REGISTRY\n// ============================================================================\n//\n// Static registry of navigator implementations. This allows ContentNavigator.create()\n// to instantiate navigators without relying on dynamic imports, which don't work\n// reliably in all environments (e.g., test runners, bundled code).\n//\n// Usage:\n// 1. Import your navigator class\n// 2. Call registerNavigator('implementingClass', YourNavigatorClass)\n// 3. ContentNavigator.create() will use the registry before falling back to\n// dynamic import\n//\n// ============================================================================\n\n/**\n * Type for navigator constructor functions.\n */\nexport type NavigatorConstructor = new (\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n) => ContentNavigator;\n\n/**\n * Entry in the navigator registry, storing the constructor and an optional\n * pipeline role. The role is used by PipelineAssembler to classify\n * consumer-registered navigators that aren't in the built-in Navigators enum.\n */\ninterface NavigatorRegistryEntry {\n constructor: NavigatorConstructor;\n role?: NavigatorRole;\n}\n\n/**\n * Registry mapping implementingClass names to navigator entries.\n * Populated by registerNavigator() and used by ContentNavigator.create().\n */\nconst navigatorRegistry = new Map<string, NavigatorRegistryEntry>();\n\n/**\n * Register a navigator implementation.\n *\n * Call this to make a navigator available for instantiation by\n * ContentNavigator.create() without relying on dynamic imports.\n *\n * Passing a `role` is optional for built-in navigators (whose roles are in\n * the hardcoded `NavigatorRoles` record), but **required** for consumer-\n * defined navigators that need to participate in pipeline assembly.\n *\n * @param implementingClass - The class name (e.g., 'elo', 'letterGatingFilter')\n * @param constructor - The navigator class constructor\n * @param role - Optional pipeline role (GENERATOR or FILTER)\n */\nexport function registerNavigator(\n implementingClass: string,\n constructor: NavigatorConstructor,\n role?: NavigatorRole\n): void {\n navigatorRegistry.set(implementingClass, { constructor, role });\n logger.debug(`[NavigatorRegistry] Registered: ${implementingClass}${role ? ` (${role})` : ''}`);\n}\n\n/**\n * Get a navigator constructor from the registry.\n *\n * @param implementingClass - The class name to look up\n * @returns The constructor, or undefined if not registered\n */\nexport function getRegisteredNavigator(implementingClass: string): NavigatorConstructor | undefined {\n return navigatorRegistry.get(implementingClass)?.constructor;\n}\n\n/**\n * Check if a navigator is registered.\n *\n * @param implementingClass - The class name to check\n * @returns true if registered, false otherwise\n */\nexport function hasRegisteredNavigator(implementingClass: string): boolean {\n return navigatorRegistry.has(implementingClass);\n}\n\n/**\n * Get the registered role for a navigator, if one was provided at registration.\n *\n * @param implementingClass - The class name to look up\n * @returns The role, or undefined if not registered or no role was specified\n */\nexport function getRegisteredNavigatorRole(implementingClass: string): NavigatorRole | undefined {\n return navigatorRegistry.get(implementingClass)?.role;\n}\n\n/**\n * A registered filter's declared kind (see `CardFilter.kind`): the static\n * `kind` on its class. Undefined if unregistered or undeclared; undeclared\n * filters count as gates at run time.\n * @param implementingClass - The class name to look up\n */\nexport function getRegisteredFilterKind(implementingClass: string): FilterKind | undefined {\n const ctor = navigatorRegistry.get(implementingClass)?.constructor as\n | { kind?: FilterKind }\n | undefined;\n return ctor?.kind;\n}\n\n/**\n * Get all registered navigator names.\n * Useful for debugging and testing.\n */\nexport function getRegisteredNavigatorNames(): string[] {\n return Array.from(navigatorRegistry.keys());\n}\n\n/**\n * Initialize the navigator registry with all built-in navigators.\n *\n * This function dynamically imports all standard navigator implementations\n * and registers them. Call this once at application startup to ensure\n * all navigators are available.\n *\n * In test environments, this may need to be called explicitly before\n * using ContentNavigator.create().\n */\nexport async function initializeNavigatorRegistry(): Promise<void> {\n logger.debug('[NavigatorRegistry] Initializing built-in navigators...');\n\n // Import and register generators\n const [eloModule, srsModule] = await Promise.all([\n import('./generators/elo'),\n import('./generators/srs'),\n ]);\n const prescribedModule = await import('./generators/prescribed');\n registerNavigator('elo', eloModule.default);\n registerNavigator('srs', srsModule.default);\n registerNavigator('prescribed', prescribedModule.default);\n\n // Import and register filters\n const [\n hierarchyModule,\n interferenceModule,\n relativePriorityModule,\n userTagPreferenceModule,\n eloDistanceModule,\n ] = await Promise.all([\n import('./filters/hierarchyDefinition'),\n import('./filters/interferenceMitigator'),\n import('./filters/relativePriority'),\n import('./filters/userTagPreference'),\n import('./filters/eloDistance'),\n ]);\n registerNavigator('hierarchyDefinition', hierarchyModule.default);\n registerNavigator('interferenceMitigator', interferenceModule.default);\n registerNavigator('relativePriority', relativePriorityModule.default);\n registerNavigator('userTagPreference', userTagPreferenceModule.default);\n registerNavigator('eloDistance', eloDistanceModule.default);\n\n logger.debug(\n `[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(', ')}`\n );\n}\n\n// ============================================================================\n// NAVIGATION STRATEGY API\n// ============================================================================\n//\n// This module defines the ContentNavigator base class and the WeightedCard type,\n// which form the foundation of the pluggable navigation strategy system.\n//\n// KEY CONCEPTS:\n//\n// 1. WeightedCard - A card with a suitability score (0-1) and provenance trail.\n// The provenance tracks how each strategy in the pipeline contributed to\n// the card's final score, ensuring transparency and debuggability.\n//\n// 2. ContentNavigator - Abstract base class for backward compatibility.\n// New code should use CardGenerator or CardFilter interfaces directly.\n//\n// 3. CardGenerator vs CardFilter:\n// - Generators (ELO, SRS) produce candidate cards with scores\n// - Filters (Hierarchy, Interference, Priority, EloDistance) transform scores\n//\n// 4. Pipeline architecture:\n// Pipeline(generator, [filter1, filter2, ...]) executes:\n// cards = generator.getWeightedCards()\n// cards = filter1.transform(cards, context)\n// cards = filter2.transform(cards, context)\n// return sorted(cards)\n//\n// 5. Provenance tracking - Each strategy adds an entry explaining its contribution.\n// This makes the system transparent and debuggable.\n//\n// ============================================================================\n\n/**\n * Tracks a single strategy's contribution to a card's final score.\n *\n * Each strategy in the pipeline adds a StrategyContribution entry to the\n * card's provenance array, creating an audit trail of scoring decisions.\n */\nexport interface StrategyContribution {\n /**\n * Strategy type (implementing class name).\n * Examples: 'elo', 'hierarchyDefinition', 'interferenceMitigator'\n */\n strategy: string;\n\n /**\n * Human-readable name identifying this specific strategy instance.\n * Extracted from ContentNavigationStrategyData.name.\n * Courses may have multiple instances of the same strategy type with\n * different configurations.\n *\n * Examples:\n * - \"ELO (default)\"\n * - \"Interference: b/d/p confusion\"\n * - \"Interference: phonetic confusables\"\n * - \"Priority: Common letters first\"\n */\n strategyName: string;\n\n /**\n * Unique database document ID for this strategy instance.\n * Extracted from ContentNavigationStrategyData._id.\n * Use this to fetch the full strategy configuration document.\n *\n * Examples:\n * - \"NAVIGATION_STRATEGY-ELO-default\"\n * - \"NAVIGATION_STRATEGY-interference-bdp\"\n * - \"NAVIGATION_STRATEGY-priority-common-letters\"\n */\n strategyId: string;\n\n /**\n * What the strategy did:\n * - 'generated': Strategy produced this card (generators only)\n * - 'passed': Strategy evaluated but didn't change score (transparent pass-through)\n * - 'boosted': Strategy increased the score\n * - 'penalized': Strategy decreased the score\n */\n action: 'generated' | 'passed' | 'boosted' | 'penalized';\n\n /** Score after this strategy's processing */\n score: number;\n\n /**\n * The effective weight applied for this strategy instance.\n * If using evolutionary orchestration, this includes deviation.\n * If omitted, implies weight 1.0 (legacy behavior).\n */\n effectiveWeight?: number;\n\n /**\n * The deviation factor applied to this user's cohort for this strategy.\n * Range [-1.0, 1.0].\n */\n deviation?: number;\n\n /**\n * Human-readable explanation of the strategy's decision.\n *\n * Examples:\n * - \"ELO distance 75, new card\"\n * - \"Prerequisites met: letter-sounds\"\n * - \"Interferes with immature tag 'd' (decay 0.8)\"\n * - \"High-priority tag 's' (0.95) → boost 1.15x\"\n *\n * Required for transparency - silent adjusters are anti-patterns.\n */\n reason: string;\n}\n\n/**\n * A card with a suitability score and provenance trail.\n *\n * Scores range from 0-1:\n * - 1.0 = fully suitable\n * - 0.0 = hard filter (e.g., prerequisite not met)\n * - 0.5 = neutral\n * - Intermediate values = soft preference\n *\n * Provenance tracks the scoring pipeline:\n * - First entry: Generator that produced the card\n * - Subsequent entries: Filters that transformed the score\n * - Each entry includes action and human-readable reason\n */\nexport interface WeightedCard {\n cardId: string;\n courseId: string;\n /** Suitability score from 0-1 */\n score: number;\n /**\n * Audit trail of strategy contributions.\n * First entry is from the generator, subsequent entries from filters.\n */\n provenance: StrategyContribution[];\n /**\n * Pre-fetched tags. Populated by Pipeline before filters run.\n * Filters should use this instead of querying getAppliedTags() individually.\n */\n tags?: string[];\n /**\n * Review document ID (_id from ScheduledCard).\n * Present when this card originated from SRS review scheduling.\n * Used by SessionController to track review outcomes and maintain review state.\n */\n reviewID?: string;\n /**\n * The card's global ELO, when the generator already knows it (the ELO\n * generator reads it during retrieval). Lets the ELO distance filter skip a\n * fetch.\n */\n cardElo?: number;\n /**\n * A review's SRS urgency in [0, 1] (overdueness and interval recency), set by\n * the SRS generator. The review-mass regulator weighs the backlog by it.\n */\n reviewUrgency?: number;\n}\n\n/**\n * Extract card origin from provenance trail.\n *\n * The first provenance entry (from the generator) indicates whether\n * this is a new card, review, or failed card. We parse the reason\n * string to extract this information.\n *\n * @param card - Card with provenance trail\n * @returns Card origin ('new', 'review', or 'failed')\n */\nexport function getCardOrigin(card: WeightedCard): 'new' | 'review' | 'failed' {\n if (card.provenance.length === 0) {\n throw new Error('Card has no provenance - cannot determine origin');\n }\n\n const firstEntry = card.provenance[0];\n const reason = firstEntry.reason.toLowerCase();\n\n if (reason.includes('failed')) {\n return 'failed';\n }\n if (reason.includes('review')) {\n return 'review';\n }\n return 'new';\n}\n\nexport enum Navigators {\n ELO = 'elo',\n SRS = 'srs',\n PRESCRIBED = 'prescribed',\n HIERARCHY = 'hierarchyDefinition',\n INTERFERENCE = 'interferenceMitigator',\n RELATIVE_PRIORITY = 'relativePriority',\n USER_TAG_PREFERENCE = 'userTagPreference',\n ELO_DISTANCE = 'eloDistance',\n}\n\n// ============================================================================\n// NAVIGATOR ROLE CLASSIFICATION\n// ============================================================================\n//\n// Navigators are classified as either generators or filters:\n// - Generators: Produce candidate cards (ELO, SRS)\n// - Filters: Transform/score candidates (Hierarchy, Interference, RelativePriority)\n//\n// This classification is used by PipelineAssembler to build pipelines:\n// 1. Instantiate generators (possibly into a CompositeGenerator)\n// 2. Instantiate filters\n// 3. Create Pipeline(generator, filters)\n//\n// ============================================================================\n\n/**\n * Role classification for navigation strategies.\n *\n * - GENERATOR: Produces candidate cards with initial scores\n * - FILTER: Transforms cards with score multipliers\n */\nexport enum NavigatorRole {\n GENERATOR = 'generator',\n FILTER = 'filter',\n}\n\n/**\n * Registry mapping navigator implementations to their roles.\n */\nexport const NavigatorRoles: Record<Navigators, NavigatorRole> = {\n [Navigators.ELO]: NavigatorRole.GENERATOR,\n [Navigators.SRS]: NavigatorRole.GENERATOR,\n [Navigators.PRESCRIBED]: NavigatorRole.GENERATOR,\n [Navigators.HIERARCHY]: NavigatorRole.FILTER,\n [Navigators.INTERFERENCE]: NavigatorRole.FILTER,\n [Navigators.RELATIVE_PRIORITY]: NavigatorRole.FILTER,\n [Navigators.USER_TAG_PREFERENCE]: NavigatorRole.FILTER,\n [Navigators.ELO_DISTANCE]: NavigatorRole.FILTER,\n};\n\n/**\n * Check if a navigator implementation is a generator.\n *\n * @param impl - Navigator implementation name (e.g., 'elo', 'hierarchyDefinition')\n * @returns true if the navigator is a generator, false otherwise\n */\nexport function isGenerator(impl: string): boolean {\n if (NavigatorRoles[impl as Navigators] === NavigatorRole.GENERATOR) return true;\n // Fallback: check the registry for consumer-registered navigators\n return getRegisteredNavigatorRole(impl) === NavigatorRole.GENERATOR;\n}\n\n/**\n * Check if a navigator implementation is a filter.\n *\n * Checks the built-in NavigatorRoles enum first, then falls back to the\n * navigator registry for consumer-registered navigators.\n *\n * @param impl - Navigator implementation name (e.g., 'elo', 'letterGatingFilter')\n * @returns true if the navigator is a filter, false otherwise\n */\nexport function isFilter(impl: string): boolean {\n if (NavigatorRoles[impl as Navigators] === NavigatorRole.FILTER) return true;\n // Fallback: check the registry for consumer-registered navigators\n return getRegisteredNavigatorRole(impl) === NavigatorRole.FILTER;\n}\n\n/**\n * Abstract base class for navigation strategies.\n *\n * This class exists primarily for backward compatibility with legacy code.\n * New code should use CardGenerator or CardFilter interfaces directly.\n *\n * The class implements StudyContentSource for compatibility with SessionController.\n * Once SessionController migrates to use getWeightedCards() exclusively,\n * the legacy methods can be removed.\n */\nexport abstract class ContentNavigator implements StudyContentSource {\n /** User interface for this navigation session */\n protected user: UserDBInterface;\n\n /** Course interface for this navigation session */\n protected course: CourseDBInterface;\n\n /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */\n protected strategyName?: string;\n\n /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */\n protected strategyId?: string;\n\n /** Evolutionary weighting configuration */\n public learnable?: LearnableWeight;\n\n /** Whether to bypass deviation (manual/static weighting) */\n public staticWeight?: boolean;\n\n /**\n * Constructor for standard navigators.\n * Call this from subclass constructors to initialize common fields.\n *\n * Note: CompositeGenerator and Pipeline call super() without args, then set\n * user/course fields directly if needed.\n */\n constructor(\n user?: UserDBInterface,\n course?: CourseDBInterface,\n strategyData?: ContentNavigationStrategyData\n ) {\n this.user = user!;\n this.course = course!;\n if (strategyData) {\n this.strategyName = strategyData.name;\n this.strategyId = strategyData._id;\n this.learnable = strategyData.learnable;\n this.staticWeight = strategyData.staticWeight;\n }\n }\n\n // ============================================================================\n // STRATEGY STATE HELPERS\n // ============================================================================\n //\n // These methods allow strategies to persist their own state (user preferences,\n // learned patterns, temporal tracking) in the user database.\n //\n // ============================================================================\n\n /**\n * Unique key identifying this strategy for state storage.\n *\n * Defaults to the constructor name (e.g., \"UserTagPreferenceFilter\").\n * Override in subclasses if multiple instances of the same strategy type\n * need separate state storage.\n */\n protected get strategyKey(): string {\n return this.constructor.name;\n }\n\n /**\n * Get this strategy's persisted state for the current course.\n *\n * @returns The strategy's data payload, or null if no state exists\n * @throws Error if user or course is not initialized\n */\n protected async getStrategyState<T>(): Promise<T | null> {\n if (!this.user || !this.course) {\n throw new Error(\n `Cannot get strategy state: navigator not properly initialized. ` +\n `Ensure user and course are provided to constructor.`\n );\n }\n return this.user.getStrategyState<T>(this.course.getCourseID(), this.strategyKey);\n }\n\n /**\n * Persist this strategy's state for the current course.\n *\n * @param data - The strategy's data payload to store\n * @throws Error if user or course is not initialized\n */\n protected async putStrategyState<T>(data: T): Promise<void> {\n if (!this.user || !this.course) {\n throw new Error(\n `Cannot put strategy state: navigator not properly initialized. ` +\n `Ensure user and course are provided to constructor.`\n );\n }\n return this.user.putStrategyState<T>(this.course.getCourseID(), this.strategyKey, data);\n }\n\n /**\n * Factory method to create navigator instances.\n *\n * First checks the navigator registry for a pre-registered constructor.\n * If not found, falls back to dynamic import (for custom navigators).\n *\n * For reliable operation in test environments, call initializeNavigatorRegistry()\n * before using this method.\n *\n * @param user - User interface\n * @param course - Course interface\n * @param strategyData - Strategy configuration document\n * @returns the runtime object used to steer a study session.\n */\n static async create(\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n ): Promise<ContentNavigator> {\n const implementingClass = strategyData.implementingClass;\n\n // First, check the registry for a pre-registered constructor\n const RegisteredImpl = getRegisteredNavigator(implementingClass);\n if (RegisteredImpl) {\n logger.debug(`[ContentNavigator.create] Using registered navigator: ${implementingClass}`);\n return new RegisteredImpl(user, course, strategyData);\n }\n\n // Fall back to dynamic import for custom/unknown navigators\n logger.debug(\n `[ContentNavigator.create] Navigator not in registry, attempting dynamic import: ${implementingClass}`\n );\n\n let NavigatorImpl;\n\n // Specifiers built at runtime, never template literals: bundlers expand\n // `import(`./generators/${x}`)` into a glob over the directory, which in a\n // per-module dist matches .map and .d.ts files and breaks the app's build.\n // This fallback only resolves from source (no '.mjs' variation).\n const load = (specifier: string) => import(/* @vite-ignore */ specifier);\n\n // Try different extension variations\n const variations = ['.ts', '.js', ''];\n\n for (const ext of variations) {\n // Try generators directory\n try {\n const module = await load(`./generators/${implementingClass}${ext}`);\n NavigatorImpl = module.default;\n if (NavigatorImpl) break;\n } catch (e) {\n logger.debug(`Failed to load generator ${implementingClass}${ext}:`, e);\n }\n\n // Try filters directory\n try {\n const module = await load(`./filters/${implementingClass}${ext}`);\n NavigatorImpl = module.default;\n if (NavigatorImpl) break;\n } catch (e) {\n logger.debug(`Failed to load filter ${implementingClass}${ext}:`, e);\n }\n\n // Try current directory (legacy)\n try {\n const module = await load(`./${implementingClass}${ext}`);\n NavigatorImpl = module.default;\n if (NavigatorImpl) break;\n } catch (e) {\n logger.debug(`Failed to load legacy ${implementingClass}${ext}:`, e);\n }\n \n if (NavigatorImpl) break;\n }\n\n if (!NavigatorImpl) {\n throw new Error(`Could not load navigator implementation for: ${implementingClass}`);\n }\n\n return new NavigatorImpl(user, course, strategyData);\n }\n\n /**\n * Get cards with suitability scores and provenance trails.\n *\n * **This is the PRIMARY API for navigation strategies.**\n *\n * Returns cards ranked by suitability score (0-1). Higher scores indicate\n * better candidates for presentation. Each card includes a provenance trail\n * documenting how strategies contributed to the final score.\n *\n * ## Implementation Required\n * All navigation strategies MUST override this method. The base class does\n * not provide a default implementation.\n *\n * ## For Generators\n * Override this method to generate candidates and compute scores based on\n * your strategy's logic (e.g., ELO proximity, review urgency). Create the\n * initial provenance entry with action='generated'.\n *\n * ## For Filters\n * Filters should implement the CardFilter interface instead and be composed\n * via Pipeline. Filters do not directly implement getWeightedCards().\n *\n * @param limit - Maximum cards to return\n * @returns Cards sorted by score descending, with provenance trails\n */\n async getWeightedCards(_limit: number): Promise<GeneratorResult> {\n throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);\n }\n\n /**\n * Set ephemeral hints for the next pipeline run.\n * No-op for non-Pipeline navigators. Pipeline overrides this.\n */\n setEphemeralHints(_hints: ReplanHints): void {\n // no-op — only Pipeline implements this\n }\n\n /** See StudyContentSource.setSessionId. No-op for non-Pipeline navigators. */\n setSessionId(_sessionId: string): void {\n // no-op — only Pipeline implements this\n }\n}\n"],"mappings":";;;;;;;;;;;AAgGA,MAAM,oCAAoB,IAAI,KAAqC;;;;;;;;;;;;;;;AAgBnE,SAAgB,kBACd,mBACA,aACA,MACM;AACN,mBAAkB,IAAI,mBAAmB;EAAE;EAAa;EAAM,CAAC;AAC/D,QAAO,MAAM,mCAAmC,oBAAoB,OAAO,KAAK,KAAK,KAAK,KAAK;;;;;;;;AASjG,SAAgB,uBAAuB,mBAA6D;AAClG,QAAO,kBAAkB,IAAI,kBAAkB,EAAE;;;;;;;;AASnD,SAAgB,uBAAuB,mBAAoC;AACzE,QAAO,kBAAkB,IAAI,kBAAkB;;;;;;;;AASjD,SAAgB,2BAA2B,mBAAsD;AAC/F,QAAO,kBAAkB,IAAI,kBAAkB,EAAE;;;;;;;;AASnD,SAAgB,wBAAwB,mBAAmD;AAIzF,SAHa,kBAAkB,IAAI,kBAAkB,E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AiBzF,aAAa,OACX,MACA,QACA,cAC2B;EAC3B,MAAM,oBAAoB,aAAa;EAGvC,MAAM,iBAAiB,uBAAuB,kBAAkB;AAChE,MAAI,gBAAgB;AAClB,UAAO,MAAM,yDAAyD,oBAAoB;AAC1F,UAAO,IAAI,eAAe,MAAM,QAAQ,aAAa;;AAIvD,SAAO,MACL,mFAAmF,oBACpF;EAED,IAAI;EAMJ,MAAM,QAAQ,cAAsB;;GAA0B;;AAK9D,OAAK,MAAM,OAFQ;GAAC;GAAO;GAAO;GAAG,EAEP;AAE5B,OAAI;AAEF,qBADe,MAAM,KAAK,gBAAgB,oBAAoB,MAAM,EAC7C;AACvB,QAAI,cAAe;YACZ,GAAG;AACV,WAAO,MAAM,4BAA4B,oBAAoB,IAAI,IAAI,EAAE;;AAIzE,OAAI;AAEF,qBADe,MAAM,KAAK,aAAa,oBAAoB,MAAM,EAC1C;AACvB,QAAI,cAAe;YACZ,GAAG;AACV,WAAO,MAAM,yBAAyB,oBAAoB,IAAI,IAAI,EAAE;;AAItE,OAAI;AAEF,qBADe,MAAM,KAAK,KAAK,oBAAoB,MAAM,EAClC;AACvB,QAAI,cAAe;YACZ,GAAG;AACV,WAAO,MAAM,yBAAyB,oBAAoB,IAAI,IAAI,EAAE;;AAGtE,OAAI,cAAe;;AAGrB,MAAI,CAAC,cACH,OAAM,IAAI,MAAM,gDAAgD,oBAAoB;AAGtF,SAAO,IAAI,cAAc,MAAM,QAAQ,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BtD,MAAM,iBAAiB,QAA0C;AAC/D,QAAM,IAAI,MAAM,GAAG,KAAK,YAAY,KAAK,sCAAsC;;;;;;CAOjF,kBAAkB,QAA2B;;CAK7C,aAAa,YAA0B"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/core/navigators/index.ts"],"sourcesContent":["import { StudyContentSource, UserDBInterface, CourseDBInterface } from '..';\nimport type { FilterKind } from './filters/types';\n\n// Re-export filter types\nexport type { CardFilter, FilterContext, CardFilterFactory, FilterKind } from './filters/types';\n\n// Re-export generator types\nexport type { CardGenerator, GeneratorContext, CardGeneratorFactory, GeneratorResult, ReplanHints } from './generators/types';\n\n// Re-export the diversity re-rank stage (pipeline stage 3)\nexport {\n diversityRerank,\n DIVERSITY_STRENGTH,\n DIVERSITY_FLOOR,\n type DiversityRerankOptions,\n} from './diversityRerank';\nimport type { GeneratorResult, ReplanHints } from './generators/types';\n\n// Re-export pipeline debugger API\nexport {\n pipelineDebugAPI,\n mountPipelineDebugger,\n getActivePipeline,\n setDebugSessionId,\n getRunsForSession,\n drainCapturedRuns,\n type PipelineRunReport,\n type RunReportCard,\n type GeneratorSummary,\n type FilterImpact,\n} from './PipelineDebugger';\n\n// Re-export the commit-free forecast capability surface.\nexport type { PipelineForecaster } from './Pipeline';\nexport {\n getSrsBacklogDebug,\n clearSrsBacklogDebug,\n type SrsBacklogDebug,\n} from './SrsDebugger';\n\n// Re-export the generic strategy-pressure debug channel. `captureStrategyPressure`\n// is part of the consumer surface: client-defined strategies (registered via\n// registerNavigator) push their backpressure state through it for the live\n// session overlay.\nexport {\n captureStrategyPressure,\n getStrategyPressureDebug,\n clearStrategyPressureDebug,\n type StrategyPressureDebug,\n type PressureGaugeDebug,\n} from './StrategyPressureDebugger';\n\nimport { LearnableWeight } from '../types/contentNavigationStrategy';\nexport type { ContentNavigationStrategyData, LearnableWeight } from '../types/contentNavigationStrategy';\nimport type { ContentNavigationStrategyData } from '../types/contentNavigationStrategy';\nimport { logger } from '../../util/logger';\n\n// ============================================================================\n// NAVIGATOR REGISTRY\n// ============================================================================\n//\n// Static registry of navigator implementations. This allows ContentNavigator.create()\n// to instantiate navigators without relying on dynamic imports, which don't work\n// reliably in all environments (e.g., test runners, bundled code).\n//\n// Usage:\n// 1. Import your navigator class\n// 2. Call registerNavigator('implementingClass', YourNavigatorClass)\n// 3. ContentNavigator.create() will use the registry before falling back to\n// dynamic import\n//\n// ============================================================================\n\n/**\n * Type for navigator constructor functions.\n */\nexport type NavigatorConstructor = new (\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n) => ContentNavigator;\n\n/**\n * Entry in the navigator registry, storing the constructor and an optional\n * pipeline role. The role is used by PipelineAssembler to classify\n * consumer-registered navigators that aren't in the built-in Navigators enum.\n */\ninterface NavigatorRegistryEntry {\n constructor: NavigatorConstructor;\n role?: NavigatorRole;\n}\n\n/**\n * Registry mapping implementingClass names to navigator entries.\n * Populated by registerNavigator() and used by ContentNavigator.create().\n */\nconst navigatorRegistry = new Map<string, NavigatorRegistryEntry>();\n\n/**\n * Register a navigator implementation.\n *\n * Call this to make a navigator available for instantiation by\n * ContentNavigator.create() without relying on dynamic imports.\n *\n * Passing a `role` is optional for built-in navigators (whose roles are in\n * the hardcoded `NavigatorRoles` record), but **required** for consumer-\n * defined navigators that need to participate in pipeline assembly.\n *\n * @param implementingClass - The class name (e.g., 'elo', 'letterGatingFilter')\n * @param constructor - The navigator class constructor\n * @param role - Optional pipeline role (GENERATOR or FILTER)\n */\nexport function registerNavigator(\n implementingClass: string,\n constructor: NavigatorConstructor,\n role?: NavigatorRole\n): void {\n navigatorRegistry.set(implementingClass, { constructor, role });\n logger.debug(`[NavigatorRegistry] Registered: ${implementingClass}${role ? ` (${role})` : ''}`);\n}\n\n/**\n * Get a navigator constructor from the registry.\n *\n * @param implementingClass - The class name to look up\n * @returns The constructor, or undefined if not registered\n */\nexport function getRegisteredNavigator(implementingClass: string): NavigatorConstructor | undefined {\n return navigatorRegistry.get(implementingClass)?.constructor;\n}\n\n/**\n * Check if a navigator is registered.\n *\n * @param implementingClass - The class name to check\n * @returns true if registered, false otherwise\n */\nexport function hasRegisteredNavigator(implementingClass: string): boolean {\n return navigatorRegistry.has(implementingClass);\n}\n\n/**\n * Get the registered role for a navigator, if one was provided at registration.\n *\n * @param implementingClass - The class name to look up\n * @returns The role, or undefined if not registered or no role was specified\n */\nexport function getRegisteredNavigatorRole(implementingClass: string): NavigatorRole | undefined {\n return navigatorRegistry.get(implementingClass)?.role;\n}\n\n/**\n * A registered filter's declared kind (see `CardFilter.kind`): the static\n * `kind` on its class. Undefined if unregistered or undeclared; undeclared\n * filters count as gates at run time.\n * @param implementingClass - The class name to look up\n */\nexport function getRegisteredFilterKind(implementingClass: string): FilterKind | undefined {\n const ctor = navigatorRegistry.get(implementingClass)?.constructor as\n | { kind?: FilterKind }\n | undefined;\n return ctor?.kind;\n}\n\n/**\n * Get all registered navigator names.\n * Useful for debugging and testing.\n */\nexport function getRegisteredNavigatorNames(): string[] {\n return Array.from(navigatorRegistry.keys());\n}\n\n/**\n * Initialize the navigator registry with all built-in navigators.\n *\n * This function dynamically imports all standard navigator implementations\n * and registers them. Call this once at application startup to ensure\n * all navigators are available.\n *\n * In test environments, this may need to be called explicitly before\n * using ContentNavigator.create().\n */\nexport async function initializeNavigatorRegistry(): Promise<void> {\n logger.debug('[NavigatorRegistry] Initializing built-in navigators...');\n\n // Import and register generators\n const [eloModule, srsModule] = await Promise.all([\n import('./generators/elo'),\n import('./generators/srs'),\n ]);\n const prescribedModule = await import('./generators/prescribed');\n registerNavigator('elo', eloModule.default);\n registerNavigator('srs', srsModule.default);\n registerNavigator('prescribed', prescribedModule.default);\n\n // Import and register filters\n const [\n hierarchyModule,\n interferenceModule,\n relativePriorityModule,\n userTagPreferenceModule,\n eloDistanceModule,\n skillPressureModule,\n ] = await Promise.all([\n import('./filters/hierarchyDefinition'),\n import('./filters/interferenceMitigator'),\n import('./filters/relativePriority'),\n import('./filters/userTagPreference'),\n import('./filters/eloDistance'),\n import('./filters/skillPressure'),\n ]);\n registerNavigator('hierarchyDefinition', hierarchyModule.default);\n registerNavigator('interferenceMitigator', interferenceModule.default);\n registerNavigator('relativePriority', relativePriorityModule.default);\n registerNavigator('userTagPreference', userTagPreferenceModule.default);\n registerNavigator('eloDistance', eloDistanceModule.default);\n registerNavigator('skillPressure', skillPressureModule.default);\n\n logger.debug(\n `[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(', ')}`\n );\n}\n\n// ============================================================================\n// NAVIGATION STRATEGY API\n// ============================================================================\n//\n// This module defines the ContentNavigator base class and the WeightedCard type,\n// which form the foundation of the pluggable navigation strategy system.\n//\n// KEY CONCEPTS:\n//\n// 1. WeightedCard - A card with a suitability score (0-1) and provenance trail.\n// The provenance tracks how each strategy in the pipeline contributed to\n// the card's final score, ensuring transparency and debuggability.\n//\n// 2. ContentNavigator - Abstract base class for backward compatibility.\n// New code should use CardGenerator or CardFilter interfaces directly.\n//\n// 3. CardGenerator vs CardFilter:\n// - Generators (ELO, SRS) produce candidate cards with scores\n// - Filters (Hierarchy, Interference, Priority, EloDistance) transform scores\n//\n// 4. Pipeline architecture:\n// Pipeline(generator, [filter1, filter2, ...]) executes:\n// cards = generator.getWeightedCards()\n// cards = filter1.transform(cards, context)\n// cards = filter2.transform(cards, context)\n// return sorted(cards)\n//\n// 5. Provenance tracking - Each strategy adds an entry explaining its contribution.\n// This makes the system transparent and debuggable.\n//\n// ============================================================================\n\n/**\n * Tracks a single strategy's contribution to a card's final score.\n *\n * Each strategy in the pipeline adds a StrategyContribution entry to the\n * card's provenance array, creating an audit trail of scoring decisions.\n */\nexport interface StrategyContribution {\n /**\n * Strategy type (implementing class name).\n * Examples: 'elo', 'hierarchyDefinition', 'interferenceMitigator'\n */\n strategy: string;\n\n /**\n * Human-readable name identifying this specific strategy instance.\n * Extracted from ContentNavigationStrategyData.name.\n * Courses may have multiple instances of the same strategy type with\n * different configurations.\n *\n * Examples:\n * - \"ELO (default)\"\n * - \"Interference: b/d/p confusion\"\n * - \"Interference: phonetic confusables\"\n * - \"Priority: Common letters first\"\n */\n strategyName: string;\n\n /**\n * Unique database document ID for this strategy instance.\n * Extracted from ContentNavigationStrategyData._id.\n * Use this to fetch the full strategy configuration document.\n *\n * Examples:\n * - \"NAVIGATION_STRATEGY-ELO-default\"\n * - \"NAVIGATION_STRATEGY-interference-bdp\"\n * - \"NAVIGATION_STRATEGY-priority-common-letters\"\n */\n strategyId: string;\n\n /**\n * What the strategy did:\n * - 'generated': Strategy produced this card (generators only)\n * - 'passed': Strategy evaluated but didn't change score (transparent pass-through)\n * - 'boosted': Strategy increased the score\n * - 'penalized': Strategy decreased the score\n */\n action: 'generated' | 'passed' | 'boosted' | 'penalized';\n\n /** Score after this strategy's processing */\n score: number;\n\n /**\n * The effective weight applied for this strategy instance.\n * If using evolutionary orchestration, this includes deviation.\n * If omitted, implies weight 1.0 (legacy behavior).\n */\n effectiveWeight?: number;\n\n /**\n * The deviation factor applied to this user's cohort for this strategy.\n * Range [-1.0, 1.0].\n */\n deviation?: number;\n\n /**\n * Human-readable explanation of the strategy's decision.\n *\n * Examples:\n * - \"ELO distance 75, new card\"\n * - \"Prerequisites met: letter-sounds\"\n * - \"Interferes with immature tag 'd' (decay 0.8)\"\n * - \"High-priority tag 's' (0.95) → boost 1.15x\"\n *\n * Required for transparency - silent adjusters are anti-patterns.\n */\n reason: string;\n}\n\n/**\n * A card with a suitability score and provenance trail.\n *\n * Scores range from 0-1:\n * - 1.0 = fully suitable\n * - 0.0 = hard filter (e.g., prerequisite not met)\n * - 0.5 = neutral\n * - Intermediate values = soft preference\n *\n * Provenance tracks the scoring pipeline:\n * - First entry: Generator that produced the card\n * - Subsequent entries: Filters that transformed the score\n * - Each entry includes action and human-readable reason\n */\nexport interface WeightedCard {\n cardId: string;\n courseId: string;\n /** Suitability score from 0-1 */\n score: number;\n /**\n * Audit trail of strategy contributions.\n * First entry is from the generator, subsequent entries from filters.\n */\n provenance: StrategyContribution[];\n /**\n * Pre-fetched tags. Populated by Pipeline before filters run.\n * Filters should use this instead of querying getAppliedTags() individually.\n */\n tags?: string[];\n /**\n * Review document ID (_id from ScheduledCard).\n * Present when this card originated from SRS review scheduling.\n * Used by SessionController to track review outcomes and maintain review state.\n */\n reviewID?: string;\n /**\n * The card's global ELO, when the generator already knows it (the ELO\n * generator reads it during retrieval). Lets the ELO distance filter skip a\n * fetch.\n */\n cardElo?: number;\n /**\n * A review's SRS urgency in [0, 1] (overdueness and interval recency), set by\n * the SRS generator. The review-mass regulator weighs the backlog by it.\n */\n reviewUrgency?: number;\n}\n\n/**\n * Extract card origin from provenance trail.\n *\n * The first provenance entry (from the generator) indicates whether\n * this is a new card, review, or failed card. We parse the reason\n * string to extract this information.\n *\n * @param card - Card with provenance trail\n * @returns Card origin ('new', 'review', or 'failed')\n */\nexport function getCardOrigin(card: WeightedCard): 'new' | 'review' | 'failed' {\n if (card.provenance.length === 0) {\n throw new Error('Card has no provenance - cannot determine origin');\n }\n\n const firstEntry = card.provenance[0];\n const reason = firstEntry.reason.toLowerCase();\n\n if (reason.includes('failed')) {\n return 'failed';\n }\n if (reason.includes('review')) {\n return 'review';\n }\n return 'new';\n}\n\nexport enum Navigators {\n ELO = 'elo',\n SRS = 'srs',\n PRESCRIBED = 'prescribed',\n HIERARCHY = 'hierarchyDefinition',\n INTERFERENCE = 'interferenceMitigator',\n RELATIVE_PRIORITY = 'relativePriority',\n USER_TAG_PREFERENCE = 'userTagPreference',\n ELO_DISTANCE = 'eloDistance',\n SKILL_PRESSURE = 'skillPressure',\n}\n\n// ============================================================================\n// NAVIGATOR ROLE CLASSIFICATION\n// ============================================================================\n//\n// Navigators are classified as either generators or filters:\n// - Generators: Produce candidate cards (ELO, SRS)\n// - Filters: Transform/score candidates (Hierarchy, Interference, RelativePriority)\n//\n// This classification is used by PipelineAssembler to build pipelines:\n// 1. Instantiate generators (possibly into a CompositeGenerator)\n// 2. Instantiate filters\n// 3. Create Pipeline(generator, filters)\n//\n// ============================================================================\n\n/**\n * Role classification for navigation strategies.\n *\n * - GENERATOR: Produces candidate cards with initial scores\n * - FILTER: Transforms cards with score multipliers\n */\nexport enum NavigatorRole {\n GENERATOR = 'generator',\n FILTER = 'filter',\n}\n\n/**\n * Registry mapping navigator implementations to their roles.\n */\nexport const NavigatorRoles: Record<Navigators, NavigatorRole> = {\n [Navigators.ELO]: NavigatorRole.GENERATOR,\n [Navigators.SRS]: NavigatorRole.GENERATOR,\n [Navigators.PRESCRIBED]: NavigatorRole.GENERATOR,\n [Navigators.HIERARCHY]: NavigatorRole.FILTER,\n [Navigators.INTERFERENCE]: NavigatorRole.FILTER,\n [Navigators.RELATIVE_PRIORITY]: NavigatorRole.FILTER,\n [Navigators.USER_TAG_PREFERENCE]: NavigatorRole.FILTER,\n [Navigators.ELO_DISTANCE]: NavigatorRole.FILTER,\n [Navigators.SKILL_PRESSURE]: NavigatorRole.FILTER,\n};\n\n/**\n * Check if a navigator implementation is a generator.\n *\n * @param impl - Navigator implementation name (e.g., 'elo', 'hierarchyDefinition')\n * @returns true if the navigator is a generator, false otherwise\n */\nexport function isGenerator(impl: string): boolean {\n if (NavigatorRoles[impl as Navigators] === NavigatorRole.GENERATOR) return true;\n // Fallback: check the registry for consumer-registered navigators\n return getRegisteredNavigatorRole(impl) === NavigatorRole.GENERATOR;\n}\n\n/**\n * Check if a navigator implementation is a filter.\n *\n * Checks the built-in NavigatorRoles enum first, then falls back to the\n * navigator registry for consumer-registered navigators.\n *\n * @param impl - Navigator implementation name (e.g., 'elo', 'letterGatingFilter')\n * @returns true if the navigator is a filter, false otherwise\n */\nexport function isFilter(impl: string): boolean {\n if (NavigatorRoles[impl as Navigators] === NavigatorRole.FILTER) return true;\n // Fallback: check the registry for consumer-registered navigators\n return getRegisteredNavigatorRole(impl) === NavigatorRole.FILTER;\n}\n\n/**\n * Abstract base class for navigation strategies.\n *\n * This class exists primarily for backward compatibility with legacy code.\n * New code should use CardGenerator or CardFilter interfaces directly.\n *\n * The class implements StudyContentSource for compatibility with SessionController.\n * Once SessionController migrates to use getWeightedCards() exclusively,\n * the legacy methods can be removed.\n */\nexport abstract class ContentNavigator implements StudyContentSource {\n /** User interface for this navigation session */\n protected user: UserDBInterface;\n\n /** Course interface for this navigation session */\n protected course: CourseDBInterface;\n\n /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */\n protected strategyName?: string;\n\n /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */\n protected strategyId?: string;\n\n /** Evolutionary weighting configuration */\n public learnable?: LearnableWeight;\n\n /** Whether to bypass deviation (manual/static weighting) */\n public staticWeight?: boolean;\n\n /**\n * Constructor for standard navigators.\n * Call this from subclass constructors to initialize common fields.\n *\n * Note: CompositeGenerator and Pipeline call super() without args, then set\n * user/course fields directly if needed.\n */\n constructor(\n user?: UserDBInterface,\n course?: CourseDBInterface,\n strategyData?: ContentNavigationStrategyData\n ) {\n this.user = user!;\n this.course = course!;\n if (strategyData) {\n this.strategyName = strategyData.name;\n this.strategyId = strategyData._id;\n this.learnable = strategyData.learnable;\n this.staticWeight = strategyData.staticWeight;\n }\n }\n\n // ============================================================================\n // STRATEGY STATE HELPERS\n // ============================================================================\n //\n // These methods allow strategies to persist their own state (user preferences,\n // learned patterns, temporal tracking) in the user database.\n //\n // ============================================================================\n\n /**\n * Unique key identifying this strategy for state storage.\n *\n * Defaults to the constructor name (e.g., \"UserTagPreferenceFilter\").\n * Override in subclasses if multiple instances of the same strategy type\n * need separate state storage.\n */\n protected get strategyKey(): string {\n return this.constructor.name;\n }\n\n /**\n * Get this strategy's persisted state for the current course.\n *\n * @returns The strategy's data payload, or null if no state exists\n * @throws Error if user or course is not initialized\n */\n protected async getStrategyState<T>(): Promise<T | null> {\n if (!this.user || !this.course) {\n throw new Error(\n `Cannot get strategy state: navigator not properly initialized. ` +\n `Ensure user and course are provided to constructor.`\n );\n }\n return this.user.getStrategyState<T>(this.course.getCourseID(), this.strategyKey);\n }\n\n /**\n * Persist this strategy's state for the current course.\n *\n * @param data - The strategy's data payload to store\n * @throws Error if user or course is not initialized\n */\n protected async putStrategyState<T>(data: T): Promise<void> {\n if (!this.user || !this.course) {\n throw new Error(\n `Cannot put strategy state: navigator not properly initialized. ` +\n `Ensure user and course are provided to constructor.`\n );\n }\n return this.user.putStrategyState<T>(this.course.getCourseID(), this.strategyKey, data);\n }\n\n /**\n * Factory method to create navigator instances.\n *\n * First checks the navigator registry for a pre-registered constructor.\n * If not found, falls back to dynamic import (for custom navigators).\n *\n * For reliable operation in test environments, call initializeNavigatorRegistry()\n * before using this method.\n *\n * @param user - User interface\n * @param course - Course interface\n * @param strategyData - Strategy configuration document\n * @returns the runtime object used to steer a study session.\n */\n static async create(\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n ): Promise<ContentNavigator> {\n const implementingClass = strategyData.implementingClass;\n\n // First, check the registry for a pre-registered constructor\n const RegisteredImpl = getRegisteredNavigator(implementingClass);\n if (RegisteredImpl) {\n logger.debug(`[ContentNavigator.create] Using registered navigator: ${implementingClass}`);\n return new RegisteredImpl(user, course, strategyData);\n }\n\n // Fall back to dynamic import for custom/unknown navigators\n logger.debug(\n `[ContentNavigator.create] Navigator not in registry, attempting dynamic import: ${implementingClass}`\n );\n\n let NavigatorImpl;\n\n // Specifiers built at runtime, never template literals: bundlers expand\n // `import(`./generators/${x}`)` into a glob over the directory, which in a\n // per-module dist matches .map and .d.ts files and breaks the app's build.\n // This fallback only resolves from source (no '.mjs' variation).\n const load = (specifier: string) => import(/* @vite-ignore */ specifier);\n\n // Try different extension variations\n const variations = ['.ts', '.js', ''];\n\n for (const ext of variations) {\n // Try generators directory\n try {\n const module = await load(`./generators/${implementingClass}${ext}`);\n NavigatorImpl = module.default;\n if (NavigatorImpl) break;\n } catch (e) {\n logger.debug(`Failed to load generator ${implementingClass}${ext}:`, e);\n }\n\n // Try filters directory\n try {\n const module = await load(`./filters/${implementingClass}${ext}`);\n NavigatorImpl = module.default;\n if (NavigatorImpl) break;\n } catch (e) {\n logger.debug(`Failed to load filter ${implementingClass}${ext}:`, e);\n }\n\n // Try current directory (legacy)\n try {\n const module = await load(`./${implementingClass}${ext}`);\n NavigatorImpl = module.default;\n if (NavigatorImpl) break;\n } catch (e) {\n logger.debug(`Failed to load legacy ${implementingClass}${ext}:`, e);\n }\n \n if (NavigatorImpl) break;\n }\n\n if (!NavigatorImpl) {\n throw new Error(`Could not load navigator implementation for: ${implementingClass}`);\n }\n\n return new NavigatorImpl(user, course, strategyData);\n }\n\n /**\n * Get cards with suitability scores and provenance trails.\n *\n * **This is the PRIMARY API for navigation strategies.**\n *\n * Returns cards ranked by suitability score (0-1). Higher scores indicate\n * better candidates for presentation. Each card includes a provenance trail\n * documenting how strategies contributed to the final score.\n *\n * ## Implementation Required\n * All navigation strategies MUST override this method. The base class does\n * not provide a default implementation.\n *\n * ## For Generators\n * Override this method to generate candidates and compute scores based on\n * your strategy's logic (e.g., ELO proximity, review urgency). Create the\n * initial provenance entry with action='generated'.\n *\n * ## For Filters\n * Filters should implement the CardFilter interface instead and be composed\n * via Pipeline. Filters do not directly implement getWeightedCards().\n *\n * @param limit - Maximum cards to return\n * @returns Cards sorted by score descending, with provenance trails\n */\n async getWeightedCards(_limit: number): Promise<GeneratorResult> {\n throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);\n }\n\n /**\n * Set ephemeral hints for the next pipeline run.\n * No-op for non-Pipeline navigators. Pipeline overrides this.\n */\n setEphemeralHints(_hints: ReplanHints): void {\n // no-op — only Pipeline implements this\n }\n\n /** See StudyContentSource.setSessionId. No-op for non-Pipeline navigators. */\n setSessionId(_sessionId: string): void {\n // no-op — only Pipeline implements this\n }\n}\n"],"mappings":";;;;;;;;;;;AAgGA,MAAM,oCAAoB,IAAI,KAAqC;;;;;;;;;;;;;;;AAgBnE,SAAgB,kBACd,mBACA,aACA,MACM;AACN,mBAAkB,IAAI,mBAAmB;EAAE;EAAa;EAAM,CAAC;AAC/D,QAAO,MAAM,mCAAmC,oBAAoB,OAAO,KAAK,KAAK,KAAK,KAAK;;;;;;;;AASjG,SAAgB,uBAAuB,mBAA6D;AAClG,QAAO,kBAAkB,IAAI,kBAAkB,EAAE;;;;;;;;AASnD,SAAgB,uBAAuB,mBAAoC;AACzE,QAAO,kBAAkB,IAAI,kBAAkB;;;;;;;;AASjD,SAAgB,2BAA2B,mBAAsD;AAC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K,sCAAsC;;;;;;CAOjF,kBAAkB,QAA2B;;CAK7C,aAAa,YAA0B"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import "../_virtual/_rolldown/runtime.mjs";
|
|
2
2
|
//#region src/core/versionStamps.ts
|
|
3
3
|
/** This build's @vue-skuilder/db version, set at build time; `'dev'` when run from source. */
|
|
4
|
-
const FRAMEWORK_VERSION = "0.3.
|
|
4
|
+
const FRAMEWORK_VERSION = "0.3.4";
|
|
5
5
|
let hostAppVersion;
|
|
6
6
|
/** Record the host app's version (the data layer's `appVersion` option). */
|
|
7
7
|
function setAppVersion(version) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { U as UserDBInterface, C as CourseDBInterface, a as CoursesDBInterface } from './contentSource-
|
|
1
|
+
import { U as UserDBInterface, C as CourseDBInterface, a as CoursesDBInterface } from './contentSource-CPM872yn.js';
|
|
2
2
|
import { C as ClassroomDBInterface, A as AdminDBInterface } from './classroomDB-DLTtLZct.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { C as CardData, b as DisplayableData, a as Tag, c as CardRecord, d as QuestionRecord, e as CardHistory } from '../types-legacy-DdVjg81H.js';
|
|
2
|
-
import { c as ContentNavigationStrategyData, e as StudySessionDoc, f as ScheduledCard, g as CourseRegistrationDoc, h as SessionStateSnapshot, i as StudySessionRunSummary, j as RegulatorReading, k as StudySessionRunCard, F as FilterKind, l as RegulatorName } from '../contentSource-
|
|
3
|
-
export { m as SessionEloEvent, n as StudySessionRunCardTrail } from '../contentSource-
|
|
2
|
+
import { c as ContentNavigationStrategyData, e as StudySessionDoc, f as ScheduledCard, g as CourseRegistrationDoc, h as SessionStateSnapshot, i as StudySessionRunSummary, j as RegulatorReading, k as StudySessionRunCard, F as FilterKind, l as RegulatorName } from '../contentSource-CPM872yn.js';
|
|
3
|
+
export { m as SessionEloEvent, n as StudySessionRunCardTrail } from '../contentSource-CPM872yn.js';
|
|
4
4
|
import { TagRole, TagSelector, TagSecurityConfig, SkillNeedConfig, TagPresentation, TagSecurity, EloRank, CourseSecurity, CourseElo } from '@vue-skuilder/common';
|
|
5
5
|
import 'moment';
|
|
6
6
|
|
|
@@ -1125,7 +1125,8 @@ var init_navigators = __esm({
|
|
|
1125
1125
|
["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
|
|
1126
1126
|
["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
|
|
1127
1127
|
["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */,
|
|
1128
|
-
["eloDistance" /* ELO_DISTANCE */]: "filter" /* FILTER
|
|
1128
|
+
["eloDistance" /* ELO_DISTANCE */]: "filter" /* FILTER */,
|
|
1129
|
+
["skillPressure" /* SKILL_PRESSURE */]: "filter" /* FILTER */
|
|
1129
1130
|
};
|
|
1130
1131
|
ContentNavigator = class {
|
|
1131
1132
|
/** User interface for this navigation session */
|