@vue-skuilder/db 0.2.35 → 0.2.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +15 -4
- package/build.entries.mjs +12 -0
- package/dist/_virtual/_rolldown/runtime.mjs +8 -0
- package/dist/{contentSource-BteiDpxH.d.ts → contentSource-D_E7JaxR.d.ts} +1 -1
- package/dist/core/UserDBDebugger.mjs +285 -0
- package/dist/core/UserDBDebugger.mjs.map +1 -0
- package/dist/core/bulkImport/cardProcessor.mjs +106 -0
- package/dist/core/bulkImport/cardProcessor.mjs.map +1 -0
- package/dist/core/{index.js → index.cjs} +6413 -7738
- package/dist/core/index.cjs.map +1 -0
- package/dist/core/index.d.ts +5 -5
- package/dist/core/index.mjs +20 -11368
- package/dist/core/interfaces/contentSource.mjs +20 -0
- package/dist/core/interfaces/contentSource.mjs.map +1 -0
- package/dist/core/navigators/Pipeline.mjs +723 -0
- package/dist/core/navigators/Pipeline.mjs.map +1 -0
- package/dist/core/navigators/PipelineAssembler.mjs +86 -0
- package/dist/core/navigators/PipelineAssembler.mjs.map +1 -0
- package/dist/core/navigators/PipelineDebugger.mjs +771 -0
- package/dist/core/navigators/PipelineDebugger.mjs.map +1 -0
- package/dist/core/navigators/SrsDebugger.mjs +34 -0
- package/dist/core/navigators/SrsDebugger.mjs.map +1 -0
- package/dist/core/navigators/StrategyPressureDebugger.mjs +19 -0
- package/dist/core/navigators/StrategyPressureDebugger.mjs.map +1 -0
- package/dist/core/navigators/defaults.mjs +96 -0
- package/dist/core/navigators/defaults.mjs.map +1 -0
- package/dist/core/navigators/diversityRerank.mjs +85 -0
- package/dist/core/navigators/diversityRerank.mjs.map +1 -0
- package/dist/core/navigators/filters/WeightedFilter.mjs +81 -0
- package/dist/core/navigators/filters/WeightedFilter.mjs.map +1 -0
- package/dist/core/navigators/filters/eloDistance.mjs +244 -0
- package/dist/core/navigators/filters/eloDistance.mjs.map +1 -0
- package/dist/core/navigators/filters/hierarchyDefinition.mjs +235 -0
- package/dist/core/navigators/filters/hierarchyDefinition.mjs.map +1 -0
- package/dist/core/navigators/filters/interferenceMitigator.mjs +201 -0
- package/dist/core/navigators/filters/interferenceMitigator.mjs.map +1 -0
- package/dist/core/navigators/filters/relativePriority.mjs +135 -0
- package/dist/core/navigators/filters/relativePriority.mjs.map +1 -0
- package/dist/core/navigators/filters/userTagPreference.mjs +101 -0
- package/dist/core/navigators/filters/userTagPreference.mjs.map +1 -0
- package/dist/core/navigators/generators/CompositeGenerator.mjs +203 -0
- package/dist/core/navigators/generators/CompositeGenerator.mjs.map +1 -0
- package/dist/core/navigators/generators/elo.mjs +77 -0
- package/dist/core/navigators/generators/elo.mjs.map +1 -0
- package/dist/core/navigators/generators/prescribed.mjs +694 -0
- package/dist/core/navigators/generators/prescribed.mjs.map +1 -0
- package/dist/core/navigators/generators/srs.mjs +158 -0
- package/dist/core/navigators/generators/srs.mjs.map +1 -0
- package/dist/core/navigators/index.mjs +345 -0
- package/dist/core/navigators/index.mjs.map +1 -0
- package/dist/core/navigators/pipelinePlan.mjs +109 -0
- package/dist/core/navigators/pipelinePlan.mjs.map +1 -0
- package/dist/core/navigators/regulators.mjs +128 -0
- package/dist/core/navigators/regulators.mjs.map +1 -0
- package/dist/core/orchestration/gradient.mjs +101 -0
- package/dist/core/orchestration/gradient.mjs.map +1 -0
- package/dist/core/orchestration/index.mjs +115 -0
- package/dist/core/orchestration/index.mjs.map +1 -0
- package/dist/core/orchestration/learning.mjs +140 -0
- package/dist/core/orchestration/learning.mjs.map +1 -0
- package/dist/core/orchestration/recording.mjs +64 -0
- package/dist/core/orchestration/recording.mjs.map +1 -0
- package/dist/core/orchestration/signal.mjs +40 -0
- package/dist/core/orchestration/signal.mjs.map +1 -0
- package/dist/core/types/contentNavigationStrategy.mjs +10 -0
- package/dist/core/types/contentNavigationStrategy.mjs.map +1 -0
- package/dist/core/types/hydration.mjs +13 -0
- package/dist/core/types/hydration.mjs.map +1 -0
- package/dist/core/types/strategyState.mjs +16 -0
- package/dist/core/types/strategyState.mjs.map +1 -0
- package/dist/core/types/studySession.mjs +14 -0
- package/dist/core/types/studySession.mjs.map +1 -0
- package/dist/core/types/types-legacy.mjs +44 -0
- package/dist/core/types/types-legacy.mjs.map +1 -0
- package/dist/core/util/index.mjs +31 -0
- package/dist/core/util/index.mjs.map +1 -0
- package/dist/core/versionStamps.mjs +46 -0
- package/dist/core/versionStamps.mjs.map +1 -0
- package/dist/courseConfigRegistration.mjs +306 -0
- package/dist/courseConfigRegistration.mjs.map +1 -0
- package/dist/{dataLayerProvider-C_QWzHf-.d.ts → dataLayerProvider-BDshhSp_.d.ts} +1 -1
- package/dist/diagnostics/dataset.mjs +118 -0
- package/dist/diagnostics/dataset.mjs.map +1 -0
- package/dist/diagnostics/derive.mjs +318 -0
- package/dist/diagnostics/derive.mjs.map +1 -0
- package/dist/diagnostics/{index.js → index.cjs} +1 -1
- package/dist/diagnostics/index.d.ts +3 -3
- package/dist/diagnostics/index.mjs +7 -1042
- package/dist/diagnostics/loader.mjs +151 -0
- package/dist/diagnostics/loader.mjs.map +1 -0
- package/dist/diagnostics/pipeline.mjs +161 -0
- package/dist/diagnostics/pipeline.mjs.map +1 -0
- package/dist/diagnostics/tagElo.mjs +177 -0
- package/dist/diagnostics/tagElo.mjs.map +1 -0
- package/dist/diagnostics/text.mjs +174 -0
- package/dist/diagnostics/text.mjs.map +1 -0
- package/dist/factory.mjs +70 -0
- package/dist/factory.mjs.map +1 -0
- package/dist/impl/common/BaseUserDB.mjs +1115 -0
- package/dist/impl/common/BaseUserDB.mjs.map +1 -0
- package/dist/impl/common/userDBHelpers.mjs +49 -0
- package/dist/impl/common/userDBHelpers.mjs.map +1 -0
- package/dist/impl/common/userDBKeys.mjs +45 -0
- package/dist/impl/common/userDBKeys.mjs.map +1 -0
- package/dist/impl/couch/CouchDBSyncStrategy.mjs +272 -0
- package/dist/impl/couch/CouchDBSyncStrategy.mjs.map +1 -0
- package/dist/impl/couch/CourseSyncService.mjs +320 -0
- package/dist/impl/couch/CourseSyncService.mjs.map +1 -0
- package/dist/impl/couch/PouchDataLayerProvider.mjs +89 -0
- package/dist/impl/couch/PouchDataLayerProvider.mjs.map +1 -0
- package/dist/impl/couch/adminDB.mjs +61 -0
- package/dist/impl/couch/adminDB.mjs.map +1 -0
- package/dist/impl/couch/auth.mjs +33 -0
- package/dist/impl/couch/auth.mjs.map +1 -0
- package/dist/impl/couch/classroomDB.mjs +227 -0
- package/dist/impl/couch/classroomDB.mjs.map +1 -0
- package/dist/impl/couch/clientCache.mjs +15 -0
- package/dist/impl/couch/clientCache.mjs.map +1 -0
- package/dist/impl/couch/courseAPI.mjs +197 -0
- package/dist/impl/couch/courseAPI.mjs.map +1 -0
- package/dist/impl/couch/courseDB.mjs +735 -0
- package/dist/impl/couch/courseDB.mjs.map +1 -0
- package/dist/impl/couch/courseLookupDB.mjs +94 -0
- package/dist/impl/couch/courseLookupDB.mjs.map +1 -0
- package/dist/impl/couch/{index.js → index.cjs} +7003 -10358
- package/dist/impl/couch/index.cjs.map +1 -0
- package/dist/impl/couch/index.d.ts +33 -5
- package/dist/impl/couch/index.mjs +152 -12147
- package/dist/impl/couch/index.mjs.map +1 -1
- package/dist/impl/couch/pouchdb-setup.mjs +15 -0
- package/dist/impl/couch/pouchdb-setup.mjs.map +1 -0
- package/dist/impl/couch/updateQueue.mjs +101 -0
- package/dist/impl/couch/updateQueue.mjs.map +1 -0
- package/dist/impl/couch/user-course-relDB.mjs +55 -0
- package/dist/impl/couch/user-course-relDB.mjs.map +1 -0
- package/dist/impl/static/NoOpSyncStrategy.mjs +49 -0
- package/dist/impl/static/NoOpSyncStrategy.mjs.map +1 -0
- package/dist/impl/static/StaticDataLayerProvider.mjs +94 -0
- package/dist/impl/static/StaticDataLayerProvider.mjs.map +1 -0
- package/dist/impl/static/StaticDataUnpacker.mjs +311 -0
- package/dist/impl/static/StaticDataUnpacker.mjs.map +1 -0
- package/dist/impl/static/courseDB.mjs +368 -0
- package/dist/impl/static/courseDB.mjs.map +1 -0
- package/dist/impl/static/coursesDB.mjs +38 -0
- package/dist/impl/static/coursesDB.mjs.map +1 -0
- package/dist/impl/static/{index.js → index.cjs} +2486 -5993
- package/dist/impl/static/index.cjs.map +1 -0
- package/dist/impl/static/index.d.ts +4 -4
- package/dist/impl/static/index.mjs +6 -10741
- package/dist/{index-C745YB_6.d.ts → index-BLDpFYG3.d.ts} +1 -1
- package/dist/{index.js → index.cjs} +14190 -14249
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +12 -23
- package/dist/index.mjs +38 -16937
- package/dist/pouch/{index.js → index.cjs} +5 -1
- package/dist/pouch/index.cjs.map +1 -0
- package/dist/pouch/index.mjs +2 -19
- package/dist/study/ItemQueue.mjs +95 -0
- package/dist/study/ItemQueue.mjs.map +1 -0
- package/dist/study/MixerDebugger.mjs +303 -0
- package/dist/study/MixerDebugger.mjs.map +1 -0
- package/dist/study/SessionController.mjs +1187 -0
- package/dist/study/SessionController.mjs.map +1 -0
- package/dist/study/SessionDebugger.mjs +271 -0
- package/dist/study/SessionDebugger.mjs.map +1 -0
- package/dist/study/SessionOverlay.mjs +407 -0
- package/dist/study/SessionOverlay.mjs.map +1 -0
- package/dist/study/SourceMixer.mjs +45 -0
- package/dist/study/SourceMixer.mjs.map +1 -0
- package/dist/study/SpacedRepetition.mjs +108 -0
- package/dist/study/SpacedRepetition.mjs.map +1 -0
- package/dist/study/TagFilteredContentSource.mjs +136 -0
- package/dist/study/TagFilteredContentSource.mjs.map +1 -0
- package/dist/study/services/CardHydrationService.mjs +172 -0
- package/dist/study/services/CardHydrationService.mjs.map +1 -0
- package/dist/study/services/EloService.mjs +217 -0
- package/dist/study/services/EloService.mjs.map +1 -0
- package/dist/study/services/ResponseProcessor.mjs +190 -0
- package/dist/study/services/ResponseProcessor.mjs.map +1 -0
- package/dist/study/services/SrsService.mjs +49 -0
- package/dist/study/services/SrsService.mjs.map +1 -0
- package/dist/study/services/tagRecent.mjs +65 -0
- package/dist/study/services/tagRecent.mjs.map +1 -0
- package/dist/{types-DF0JuPbs.d.ts → types-DChCz22D.d.ts} +1 -1
- package/dist/{types-legacy-DdVjg81H.d.cts → types-legacy-fT5Y1Wuy.d.ts} +1 -1
- package/dist/userDBKeys-ne1g4Xuq.d.ts +16 -0
- package/dist/util/Loggable.mjs +14 -0
- package/dist/util/Loggable.mjs.map +1 -0
- package/dist/util/dataDirectory.mjs +47 -0
- package/dist/util/dataDirectory.mjs.map +1 -0
- package/dist/util/logger.mjs +86 -0
- package/dist/util/logger.mjs.map +1 -0
- package/dist/util/migrator/FileSystemAdapter.mjs +18 -0
- package/dist/util/migrator/FileSystemAdapter.mjs.map +1 -0
- package/dist/util/migrator/StaticToCouchDBMigrator.mjs +428 -0
- package/dist/util/migrator/StaticToCouchDBMigrator.mjs.map +1 -0
- package/dist/util/migrator/types.mjs +11 -0
- package/dist/util/migrator/types.mjs.map +1 -0
- package/dist/util/migrator/validation.mjs +334 -0
- package/dist/util/migrator/validation.mjs.map +1 -0
- package/dist/util/packer/CouchDBToStaticPacker.mjs +438 -0
- package/dist/util/packer/CouchDBToStaticPacker.mjs.map +1 -0
- package/dist/util/packer/{index.js → index.cjs} +73 -9
- package/dist/util/packer/index.cjs.map +1 -0
- package/dist/util/packer/index.d.ts +3 -3
- package/dist/util/packer/index.mjs +2 -537
- package/eslint.config.mjs +9 -1
- package/package.json +25 -13
- package/rolldown.config.mjs +44 -0
- package/src/core/UserDBDebugger.ts +47 -46
- package/src/core/navigators/Pipeline.ts +10 -10
- package/src/core/navigators/PipelineDebugger.ts +55 -55
- package/src/core/navigators/filters/eloDistance.ts +1 -1
- package/src/core/navigators/generators/elo.ts +5 -1
- package/src/core/navigators/generators/prescribed.ts +42 -16
- package/src/core/navigators/index.ts +9 -3
- package/src/factory.ts +10 -1
- package/src/impl/common/BaseUserDB.ts +16 -5
- package/src/impl/common/index.ts +2 -0
- package/src/impl/common/userDBHelpers.ts +4 -58
- package/src/impl/common/userDBKeys.ts +64 -0
- package/src/impl/couch/CourseSyncService.ts +130 -20
- package/src/impl/couch/PouchDataLayerProvider.ts +14 -1
- package/src/impl/couch/courseAPI.ts +26 -12
- package/src/impl/couch/courseDB.ts +35 -15
- package/src/impl/couch/index.ts +18 -23
- package/src/impl/couch/pouchdb-setup.ts +8 -0
- package/src/index.ts +1 -1
- package/src/study/MixerDebugger.ts +46 -46
- package/src/study/SessionDebugger.ts +20 -20
- package/src/study/SessionOverlay.ts +4 -4
- package/src/util/logger.ts +112 -13
- package/tests/core/navigators/eloGenerator.test.ts +36 -0
- package/tests/impl/courseSync.test.ts +139 -0
- package/tsup.config.ts +24 -21
- package/dist/SyncStrategy-BXliog1m.d.cts +0 -116
- package/dist/classroomDB-DLTtLZct.d.cts +0 -86
- package/dist/contentSource-FQZcZopC.d.cts +0 -2007
- package/dist/core/index.d.cts +0 -521
- package/dist/core/index.js.map +0 -1
- package/dist/core/index.mjs.map +0 -1
- package/dist/dataLayerProvider-3y21KtF-.d.cts +0 -61
- package/dist/diagnostics/index.d.cts +0 -561
- package/dist/diagnostics/index.mjs.map +0 -1
- package/dist/impl/couch/index.d.cts +0 -620
- package/dist/impl/couch/index.js.map +0 -1
- package/dist/impl/static/index.d.cts +0 -232
- package/dist/impl/static/index.js.map +0 -1
- package/dist/impl/static/index.mjs.map +0 -1
- package/dist/index-BIum9Ue2.d.cts +0 -137
- package/dist/index.d.cts +0 -1663
- package/dist/index.js.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/pouch/index.d.cts +0 -1
- package/dist/pouch/index.js.map +0 -1
- package/dist/pouch/index.mjs.map +0 -1
- package/dist/types-BcWVH4ww.d.cts +0 -58
- package/dist/types-legacy-DdVjg81H.d.ts +0 -168
- package/dist/util/packer/index.d.cts +0 -5
- package/dist/util/packer/index.js.map +0 -1
- package/dist/util/packer/index.mjs.map +0 -1
- package/src/study/getCardDataShape.ts +0 -34
- /package/dist/diagnostics/{index.js.map → index.cjs.map} +0 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import "../../../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
import { ContentNavigator } from "../index.mjs";
|
|
3
|
+
import { toCourseElo } from "@vue-skuilder/common";
|
|
4
|
+
//#region src/core/navigators/filters/interferenceMitigator.ts
|
|
5
|
+
const DEFAULT_MIN_COUNT = 10;
|
|
6
|
+
const DEFAULT_MIN_ELAPSED_DAYS = 3;
|
|
7
|
+
const DEFAULT_INTERFERENCE_DECAY = .8;
|
|
8
|
+
/**
|
|
9
|
+
* A filter strategy that avoids introducing confusable concepts simultaneously.
|
|
10
|
+
*
|
|
11
|
+
* When a user is learning a concept (tag is "immature"), this strategy reduces
|
|
12
|
+
* scores for cards tagged with interfering concepts. This encourages the system
|
|
13
|
+
* to introduce new content that is maximally distant from current learning focus.
|
|
14
|
+
*
|
|
15
|
+
* Example: While learning 'd', prefer introducing 'x' over 'b' (visual interference)
|
|
16
|
+
* or 't' (phonetic interference).
|
|
17
|
+
*
|
|
18
|
+
* Implements CardFilter for use in Pipeline architecture.
|
|
19
|
+
* Also extends ContentNavigator for backward compatibility.
|
|
20
|
+
*/
|
|
21
|
+
var InterferenceMitigatorNavigator = class InterferenceMitigatorNavigator extends ContentNavigator {
|
|
22
|
+
config;
|
|
23
|
+
/** Human-readable name for CardFilter interface */
|
|
24
|
+
name;
|
|
25
|
+
/** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
|
|
26
|
+
static kind = "signal";
|
|
27
|
+
kind = InterferenceMitigatorNavigator.kind;
|
|
28
|
+
/** Precomputed map: tag -> set of { partner, decay } it interferes with */
|
|
29
|
+
interferenceMap;
|
|
30
|
+
constructor(user, course, strategyData) {
|
|
31
|
+
super(user, course, strategyData);
|
|
32
|
+
this.config = this.parseConfig(strategyData.serializedData);
|
|
33
|
+
this.interferenceMap = this.buildInterferenceMap();
|
|
34
|
+
this.name = strategyData.name || "Interference Mitigator";
|
|
35
|
+
}
|
|
36
|
+
parseConfig(serializedData) {
|
|
37
|
+
try {
|
|
38
|
+
const parsed = JSON.parse(serializedData);
|
|
39
|
+
let sets = parsed.interferenceSets || [];
|
|
40
|
+
if (sets.length > 0 && Array.isArray(sets[0])) sets = sets.map((tags) => ({ tags }));
|
|
41
|
+
return {
|
|
42
|
+
interferenceSets: sets,
|
|
43
|
+
maturityThreshold: {
|
|
44
|
+
minCount: parsed.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT,
|
|
45
|
+
minElo: parsed.maturityThreshold?.minElo,
|
|
46
|
+
minElapsedDays: parsed.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS
|
|
47
|
+
},
|
|
48
|
+
defaultDecay: parsed.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY
|
|
49
|
+
};
|
|
50
|
+
} catch {
|
|
51
|
+
return {
|
|
52
|
+
interferenceSets: [],
|
|
53
|
+
maturityThreshold: {
|
|
54
|
+
minCount: DEFAULT_MIN_COUNT,
|
|
55
|
+
minElapsedDays: DEFAULT_MIN_ELAPSED_DAYS
|
|
56
|
+
},
|
|
57
|
+
defaultDecay: DEFAULT_INTERFERENCE_DECAY
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Build a map from each tag to its interference partners with decay coefficients.
|
|
63
|
+
* If tags A, B, C are in an interference group with decay 0.8, then:
|
|
64
|
+
* - A interferes with B (decay 0.8) and C (decay 0.8)
|
|
65
|
+
* - B interferes with A (decay 0.8) and C (decay 0.8)
|
|
66
|
+
* - etc.
|
|
67
|
+
*/
|
|
68
|
+
buildInterferenceMap() {
|
|
69
|
+
const map = /* @__PURE__ */ new Map();
|
|
70
|
+
for (const group of this.config.interferenceSets) {
|
|
71
|
+
const decay = group.decay ?? this.config.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY;
|
|
72
|
+
for (const tag of group.tags) {
|
|
73
|
+
if (!map.has(tag)) map.set(tag, []);
|
|
74
|
+
const partners = map.get(tag);
|
|
75
|
+
for (const other of group.tags) if (other !== tag) {
|
|
76
|
+
const existing = partners.find((p) => p.partner === other);
|
|
77
|
+
if (existing) existing.decay = Math.max(existing.decay, decay);
|
|
78
|
+
else partners.push({
|
|
79
|
+
partner: other,
|
|
80
|
+
decay
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return map;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Get the set of tags that are currently immature for this user.
|
|
89
|
+
* A tag is immature if the user has interacted with it but hasn't
|
|
90
|
+
* reached the maturity threshold.
|
|
91
|
+
*/
|
|
92
|
+
async getImmatureTags(context) {
|
|
93
|
+
const immature = /* @__PURE__ */ new Set();
|
|
94
|
+
try {
|
|
95
|
+
const userElo = toCourseElo((await context.user.getCourseRegDoc(context.course.getCourseID())).elo);
|
|
96
|
+
const minCount = this.config.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT;
|
|
97
|
+
const minElo = this.config.maturityThreshold?.minElo;
|
|
98
|
+
const minCountForElapsed = (this.config.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS) * 2;
|
|
99
|
+
for (const [tagId, tagElo] of Object.entries(userElo.tags)) {
|
|
100
|
+
if (tagElo.count === 0) continue;
|
|
101
|
+
const belowCount = tagElo.count < minCount;
|
|
102
|
+
const belowElo = minElo !== void 0 && tagElo.score < minElo;
|
|
103
|
+
const belowElapsed = tagElo.count < minCountForElapsed;
|
|
104
|
+
if (belowCount || belowElo || belowElapsed) immature.add(tagId);
|
|
105
|
+
}
|
|
106
|
+
} catch {}
|
|
107
|
+
return immature;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Get all tags that interfere with any immature tag, along with their decay coefficients.
|
|
111
|
+
* These are the tags we want to avoid introducing.
|
|
112
|
+
*/
|
|
113
|
+
getTagsToAvoid(immatureTags) {
|
|
114
|
+
const avoid = /* @__PURE__ */ new Map();
|
|
115
|
+
for (const immatureTag of immatureTags) {
|
|
116
|
+
const partners = this.interferenceMap.get(immatureTag);
|
|
117
|
+
if (partners) {
|
|
118
|
+
for (const { partner, decay } of partners) if (!immatureTags.has(partner)) {
|
|
119
|
+
const existing = avoid.get(partner) ?? 0;
|
|
120
|
+
avoid.set(partner, Math.max(existing, decay));
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return avoid;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Compute interference score reduction for a card.
|
|
128
|
+
* Returns: { multiplier, interfering tags, reason }
|
|
129
|
+
*/
|
|
130
|
+
computeInterferenceEffect(cardTags, tagsToAvoid, immatureTags) {
|
|
131
|
+
if (tagsToAvoid.size === 0) return {
|
|
132
|
+
multiplier: 1,
|
|
133
|
+
interferingTags: [],
|
|
134
|
+
reason: "No interference detected"
|
|
135
|
+
};
|
|
136
|
+
let multiplier = 1;
|
|
137
|
+
const interferingTags = [];
|
|
138
|
+
for (const tag of cardTags) {
|
|
139
|
+
const decay = tagsToAvoid.get(tag);
|
|
140
|
+
if (decay !== void 0) {
|
|
141
|
+
interferingTags.push(tag);
|
|
142
|
+
multiplier *= 1 - decay;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
if (interferingTags.length === 0) return {
|
|
146
|
+
multiplier: 1,
|
|
147
|
+
interferingTags: [],
|
|
148
|
+
reason: "No interference detected"
|
|
149
|
+
};
|
|
150
|
+
const causingTags = /* @__PURE__ */ new Set();
|
|
151
|
+
for (const tag of interferingTags) for (const immatureTag of immatureTags) if (this.interferenceMap.get(immatureTag)?.some((p) => p.partner === tag)) causingTags.add(immatureTag);
|
|
152
|
+
const reason = `Interferes with immature tags ${Array.from(causingTags).join(", ")} (tags: ${interferingTags.join(", ")}, multiplier: ${multiplier.toFixed(2)})`;
|
|
153
|
+
return {
|
|
154
|
+
multiplier,
|
|
155
|
+
interferingTags,
|
|
156
|
+
reason
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* CardFilter.transform implementation.
|
|
161
|
+
*
|
|
162
|
+
* Apply interference-aware scoring. Cards with tags that interfere with
|
|
163
|
+
* immature learnings get reduced scores.
|
|
164
|
+
*/
|
|
165
|
+
async transform(cards, context) {
|
|
166
|
+
const immatureTags = await this.getImmatureTags(context);
|
|
167
|
+
const tagsToAvoid = this.getTagsToAvoid(immatureTags);
|
|
168
|
+
const adjusted = [];
|
|
169
|
+
for (const card of cards) {
|
|
170
|
+
const cardTags = card.tags ?? [];
|
|
171
|
+
const { multiplier, reason } = this.computeInterferenceEffect(cardTags, tagsToAvoid, immatureTags);
|
|
172
|
+
const finalScore = card.score * multiplier;
|
|
173
|
+
const action = multiplier < 1 ? "penalized" : multiplier > 1 ? "boosted" : "passed";
|
|
174
|
+
adjusted.push({
|
|
175
|
+
...card,
|
|
176
|
+
score: finalScore,
|
|
177
|
+
provenance: [...card.provenance, {
|
|
178
|
+
strategy: "interferenceMitigator",
|
|
179
|
+
strategyName: this.strategyName || this.name,
|
|
180
|
+
strategyId: this.strategyId || "NAVIGATION_STRATEGY-interference",
|
|
181
|
+
action,
|
|
182
|
+
score: finalScore,
|
|
183
|
+
reason
|
|
184
|
+
}]
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
return adjusted;
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Legacy getWeightedCards - now throws as filters should not be used as generators.
|
|
191
|
+
*
|
|
192
|
+
* Use transform() via Pipeline instead.
|
|
193
|
+
*/
|
|
194
|
+
async getWeightedCards(_limit) {
|
|
195
|
+
throw new Error("InterferenceMitigatorNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().");
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
//#endregion
|
|
199
|
+
export { InterferenceMitigatorNavigator as default };
|
|
200
|
+
|
|
201
|
+
//# sourceMappingURL=interferenceMitigator.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"interferenceMitigator.mjs","names":[],"sources":["../../../../src/core/navigators/filters/interferenceMitigator.ts"],"sourcesContent":["import type { CourseDBInterface } from '../../interfaces/courseDB';\nimport type { UserDBInterface } from '../../interfaces/userDB';\nimport { ContentNavigator } from '../index';\nimport type { WeightedCard } from '../index';\nimport type { ContentNavigationStrategyData } from '../../types/contentNavigationStrategy';\nimport type { CardFilter, FilterContext, FilterKind } from './types';\nimport type { GeneratorResult } from '../generators/types';\nimport { toCourseElo } from '@vue-skuilder/common';\n\n/**\n * Configuration for the InterferenceMitigator strategy.\n *\n * Course authors define explicit interference relationships between tags.\n * The mitigator discourages introducing new concepts that interfere with\n * currently immature learnings.\n */\n/**\n * A single interference group with its own decay coefficient.\n */\nexport interface InterferenceGroup {\n /** Tags that interfere with each other in this group */\n tags: string[];\n /** How strongly these tags interfere (0-1, default: 0.8). Higher = stronger avoidance. */\n decay?: number;\n}\n\nexport interface InterferenceConfig {\n /**\n * Groups of tags that interfere with each other.\n * Each group can have its own decay coefficient.\n *\n * Example: [\n * { tags: [\"b\", \"d\", \"p\"], decay: 0.9 }, // visual similarity - strong\n * { tags: [\"d\", \"t\"], decay: 0.7 }, // phonetic similarity - moderate\n * { tags: [\"m\", \"n\"], decay: 0.8 }\n * ]\n */\n interferenceSets: InterferenceGroup[];\n\n /**\n * Threshold below which a tag is considered \"immature\" (still being learned).\n * Immature tags trigger interference avoidance for their interference partners.\n */\n maturityThreshold?: {\n /** Minimum interaction count to be considered mature (default: 10) */\n minCount?: number;\n /** Minimum ELO score to be considered mature (optional) */\n minElo?: number;\n /**\n * Minimum elapsed time (in days) since first interaction to be considered mature.\n * Prevents recent cramming success from indicating maturity.\n * The skill should be \"lindy\" — maintained over time.\n */\n minElapsedDays?: number;\n };\n\n /**\n * Default decay for groups that don't specify their own (0-1, default: 0.8).\n */\n defaultDecay?: number;\n}\n\nconst DEFAULT_MIN_COUNT = 10;\nconst DEFAULT_MIN_ELAPSED_DAYS = 3;\nconst DEFAULT_INTERFERENCE_DECAY = 0.8;\n\n/**\n * A filter strategy that avoids introducing confusable concepts simultaneously.\n *\n * When a user is learning a concept (tag is \"immature\"), this strategy reduces\n * scores for cards tagged with interfering concepts. This encourages the system\n * to introduce new content that is maximally distant from current learning focus.\n *\n * Example: While learning 'd', prefer introducing 'x' over 'b' (visual interference)\n * or 't' (phonetic interference).\n *\n * Implements CardFilter for use in Pipeline architecture.\n * Also extends ContentNavigator for backward compatibility.\n */\nexport default class InterferenceMitigatorNavigator extends ContentNavigator implements CardFilter {\n private config: InterferenceConfig;\n\n /** Human-readable name for CardFilter interface */\n name: string;\n\n /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */\n static readonly kind: FilterKind = 'signal';\n readonly kind = InterferenceMitigatorNavigator.kind;\n\n /** Precomputed map: tag -> set of { partner, decay } it interferes with */\n private interferenceMap: Map<string, Array<{ partner: string; decay: number }>>;\n\n constructor(\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n ) {\n super(user, course, strategyData);\n this.config = this.parseConfig(strategyData.serializedData);\n this.interferenceMap = this.buildInterferenceMap();\n this.name = strategyData.name || 'Interference Mitigator';\n }\n\n private parseConfig(serializedData: string): InterferenceConfig {\n try {\n const parsed = JSON.parse(serializedData);\n // Normalize legacy format (string[][]) to new format (InterferenceGroup[])\n let sets: InterferenceGroup[] = parsed.interferenceSets || [];\n if (sets.length > 0 && Array.isArray(sets[0])) {\n // Legacy format: convert string[][] to InterferenceGroup[]\n sets = (sets as unknown as string[][]).map((tags) => ({ tags }));\n }\n\n return {\n interferenceSets: sets,\n maturityThreshold: {\n minCount: parsed.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT,\n minElo: parsed.maturityThreshold?.minElo,\n minElapsedDays: parsed.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS,\n },\n defaultDecay: parsed.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY,\n };\n } catch {\n return {\n interferenceSets: [],\n maturityThreshold: {\n minCount: DEFAULT_MIN_COUNT,\n minElapsedDays: DEFAULT_MIN_ELAPSED_DAYS,\n },\n defaultDecay: DEFAULT_INTERFERENCE_DECAY,\n };\n }\n }\n\n /**\n * Build a map from each tag to its interference partners with decay coefficients.\n * If tags A, B, C are in an interference group with decay 0.8, then:\n * - A interferes with B (decay 0.8) and C (decay 0.8)\n * - B interferes with A (decay 0.8) and C (decay 0.8)\n * - etc.\n */\n private buildInterferenceMap(): Map<string, Array<{ partner: string; decay: number }>> {\n const map = new Map<string, Array<{ partner: string; decay: number }>>();\n\n for (const group of this.config.interferenceSets) {\n const decay = group.decay ?? this.config.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY;\n\n for (const tag of group.tags) {\n if (!map.has(tag)) {\n map.set(tag, []);\n }\n const partners = map.get(tag)!;\n for (const other of group.tags) {\n if (other !== tag) {\n // Check if partner already exists (from overlapping groups)\n const existing = partners.find((p) => p.partner === other);\n if (existing) {\n // Use the stronger (higher) decay\n existing.decay = Math.max(existing.decay, decay);\n } else {\n partners.push({ partner: other, decay });\n }\n }\n }\n }\n }\n\n return map;\n }\n\n /**\n * Get the set of tags that are currently immature for this user.\n * A tag is immature if the user has interacted with it but hasn't\n * reached the maturity threshold.\n */\n private async getImmatureTags(context: FilterContext): Promise<Set<string>> {\n const immature = new Set<string>();\n\n try {\n const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());\n const userElo = toCourseElo(courseReg.elo);\n\n const minCount = this.config.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT;\n const minElo = this.config.maturityThreshold?.minElo;\n\n // TODO: To properly check elapsed time, we need access to first interaction timestamp.\n // For now, we use count as a proxy (more interactions = more time elapsed).\n // Future: query card history for earliest timestamp per tag.\n const minElapsedDays =\n this.config.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS;\n const minCountForElapsed = minElapsedDays * 2; // Rough proxy: ~2 interactions per day\n\n for (const [tagId, tagElo] of Object.entries(userElo.tags)) {\n // Only consider tags that have been started (count > 0)\n if (tagElo.count === 0) continue;\n\n // Check if below maturity threshold\n const belowCount = tagElo.count < minCount;\n const belowElo = minElo !== undefined && tagElo.score < minElo;\n const belowElapsed = tagElo.count < minCountForElapsed; // Proxy for time\n\n if (belowCount || belowElo || belowElapsed) {\n immature.add(tagId);\n }\n }\n } catch {\n // If we can't get user data, assume no immature tags\n }\n\n return immature;\n }\n\n /**\n * Get all tags that interfere with any immature tag, along with their decay coefficients.\n * These are the tags we want to avoid introducing.\n */\n private getTagsToAvoid(immatureTags: Set<string>): Map<string, number> {\n const avoid = new Map<string, number>();\n\n for (const immatureTag of immatureTags) {\n const partners = this.interferenceMap.get(immatureTag);\n if (partners) {\n for (const { partner, decay } of partners) {\n // Avoid the partner, but not if it's also immature\n // (if both are immature, we're already learning both)\n if (!immatureTags.has(partner)) {\n // Use the strongest (highest) decay if partner appears multiple times\n const existing = avoid.get(partner) ?? 0;\n avoid.set(partner, Math.max(existing, decay));\n }\n }\n }\n }\n\n return avoid;\n }\n\n /**\n * Compute interference score reduction for a card.\n * Returns: { multiplier, interfering tags, reason }\n */\n private computeInterferenceEffect(\n cardTags: string[],\n tagsToAvoid: Map<string, number>,\n immatureTags: Set<string>\n ): { multiplier: number; interferingTags: string[]; reason: string } {\n if (tagsToAvoid.size === 0) {\n return {\n multiplier: 1.0,\n interferingTags: [],\n reason: 'No interference detected',\n };\n }\n\n let multiplier = 1.0;\n const interferingTags: string[] = [];\n\n for (const tag of cardTags) {\n const decay = tagsToAvoid.get(tag);\n if (decay !== undefined) {\n interferingTags.push(tag);\n multiplier *= 1.0 - decay;\n }\n }\n\n if (interferingTags.length === 0) {\n return {\n multiplier: 1.0,\n interferingTags: [],\n reason: 'No interference detected',\n };\n }\n\n // Find which immature tags these interfere with\n const causingTags = new Set<string>();\n for (const tag of interferingTags) {\n for (const immatureTag of immatureTags) {\n const partners = this.interferenceMap.get(immatureTag);\n if (partners?.some((p) => p.partner === tag)) {\n causingTags.add(immatureTag);\n }\n }\n }\n\n const reason = `Interferes with immature tags ${Array.from(causingTags).join(', ')} (tags: ${interferingTags.join(', ')}, multiplier: ${multiplier.toFixed(2)})`;\n\n return { multiplier, interferingTags, reason };\n }\n\n /**\n * CardFilter.transform implementation.\n *\n * Apply interference-aware scoring. Cards with tags that interfere with\n * immature learnings get reduced scores.\n */\n async transform(cards: WeightedCard[], context: FilterContext): Promise<WeightedCard[]> {\n // Identify what to avoid\n const immatureTags = await this.getImmatureTags(context);\n const tagsToAvoid = this.getTagsToAvoid(immatureTags);\n\n // Adjust scores based on interference\n const adjusted: WeightedCard[] = [];\n\n for (const card of cards) {\n const cardTags = card.tags ?? [];\n const { multiplier, reason } = this.computeInterferenceEffect(\n cardTags,\n tagsToAvoid,\n immatureTags\n );\n const finalScore = card.score * multiplier;\n\n const action = multiplier < 1.0 ? 'penalized' : multiplier > 1.0 ? 'boosted' : 'passed';\n\n adjusted.push({\n ...card,\n score: finalScore,\n provenance: [\n ...card.provenance,\n {\n strategy: 'interferenceMitigator',\n strategyName: this.strategyName || this.name,\n strategyId: this.strategyId || 'NAVIGATION_STRATEGY-interference',\n action,\n score: finalScore,\n reason,\n },\n ],\n });\n }\n\n return adjusted;\n }\n\n /**\n * Legacy getWeightedCards - now throws as filters should not be used as generators.\n *\n * Use transform() via Pipeline instead.\n */\n async getWeightedCards(_limit: number): Promise<GeneratorResult> {\n throw new Error(\n 'InterferenceMitigatorNavigator 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":";;;;AA8DA,MAAM,oBAAoB;AAC1B,MAAM,2BAA2B;AACjC,MAAM,6BAA6B;;;;;;;;;;;;;;AAenC,IAAqB,iCAArB,MAAqB,uCAAuC,iBAAuC;CACjG;;CAGA;;CAGA,OAAgB,OAAmB;CACnC,OAAgB,+BAA+B;;CAG/C;CAEA,YACE,MACA,QACA,cACA;AACA,QAAM,MAAM,QAAQ,aAAa;AACjC,O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GACT;EAIH,MAAM,8BAAc,IAAI,KAAa;AACrC,OAAK,MAAM,OAAO,gBAChB,MAAK,MAAM,eAAe,aAExB,KADiB,KAAK,gBAAgB,IAAI,YAAY,EACxC,MAAM,MAAM,EAAE,YAAY,IAAI,CAC1C,aAAY,IAAI,YAAY;EAKlC,MAAM,SAAS,iCAAiC,MAAM,KAAK,YAAY,CAAC,KAAK,KAAK,CAAC,UAAU,gBAAgB,KAAK,KAAK,CAAC,gBAAgB,WAAW,QAAQ,EAAE,CAAC;AAE9J,SAAO;GAAE;GAAY;GAAiB;GAAQ;;;;;;;;CAShD,MAAM,UAAU,OAAuB,SAAiD;EAEtF,MAAM,eAAe,MAAM,KAAK,gBAAgB,QAAQ;EACxD,MAAM,cAAc,KAAK,eAAe,aAAa;EAGrD,MAAM,WAA2B,EAAE;AAEnC,OAAK,MAAM,QAAQ,OAAO;GACxB,MAAM,WAAW,KAAK,QAAQ,EAAE;GAChC,MAAM,EAAE,YAAY,WAAW,KAAK,0BAClC,UACA,aACA,aACD;GACD,MAAM,aAAa,KAAK,QAAQ;GAEhC,MAAM,SAAS,aAAa,IAAM,cAAc,aAAa,IAAM,YAAY;AAE/E,YAAS,KAAK;IACZ,GAAG;IACH,OAAO;IACP,YAAY,CACV,GAAG,KAAK,YACR;KACE,UAAU;KACV,cAAc,KAAK,gBAAgB,KAAK;KACxC,YAAY,KAAK,cAAc;KAC/B;KACA,OAAO;KACP;KACD,CACF;IACF,CAAC;;AAGJ,SAAO;;;;;;;CAQT,MAAM,iBAAiB,QAA0C;AAC/D,QAAM,IAAI,MACR,mJAED"}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import "../../../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
import { ContentNavigator } from "../index.mjs";
|
|
3
|
+
//#region src/core/navigators/filters/relativePriority.ts
|
|
4
|
+
const DEFAULT_PRIORITY = .5;
|
|
5
|
+
const DEFAULT_PRIORITY_INFLUENCE = .5;
|
|
6
|
+
const DEFAULT_COMBINE_MODE = "max";
|
|
7
|
+
/**
|
|
8
|
+
* A filter strategy that boosts scores for high-utility content.
|
|
9
|
+
*
|
|
10
|
+
* Course authors assign priority weights to tags. Cards with high-priority
|
|
11
|
+
* tags get boosted scores, making them more likely to be presented first.
|
|
12
|
+
* This allows teaching the most useful, well-behaved concepts before
|
|
13
|
+
* moving on to rarer or more irregular ones.
|
|
14
|
+
*
|
|
15
|
+
* Example: When teaching phonics, prioritize common letters (s, t, a) over
|
|
16
|
+
* rare ones (x, z, q) by assigning higher priority weights to common letters.
|
|
17
|
+
*
|
|
18
|
+
* Implements CardFilter for use in Pipeline architecture.
|
|
19
|
+
* Also extends ContentNavigator for backward compatibility.
|
|
20
|
+
*/
|
|
21
|
+
var RelativePriorityNavigator = class RelativePriorityNavigator extends ContentNavigator {
|
|
22
|
+
config;
|
|
23
|
+
/** Human-readable name for CardFilter interface */
|
|
24
|
+
name;
|
|
25
|
+
/** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
|
|
26
|
+
static kind = "signal";
|
|
27
|
+
kind = RelativePriorityNavigator.kind;
|
|
28
|
+
constructor(user, course, strategyData) {
|
|
29
|
+
super(user, course, strategyData);
|
|
30
|
+
this.config = this.parseConfig(strategyData.serializedData);
|
|
31
|
+
this.name = strategyData.name || "Relative Priority";
|
|
32
|
+
}
|
|
33
|
+
parseConfig(serializedData) {
|
|
34
|
+
try {
|
|
35
|
+
const parsed = JSON.parse(serializedData);
|
|
36
|
+
return {
|
|
37
|
+
tagPriorities: parsed.tagPriorities || {},
|
|
38
|
+
defaultPriority: parsed.defaultPriority ?? DEFAULT_PRIORITY,
|
|
39
|
+
combineMode: parsed.combineMode ?? DEFAULT_COMBINE_MODE,
|
|
40
|
+
priorityInfluence: parsed.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE
|
|
41
|
+
};
|
|
42
|
+
} catch {
|
|
43
|
+
return {
|
|
44
|
+
tagPriorities: {},
|
|
45
|
+
defaultPriority: DEFAULT_PRIORITY,
|
|
46
|
+
combineMode: DEFAULT_COMBINE_MODE,
|
|
47
|
+
priorityInfluence: DEFAULT_PRIORITY_INFLUENCE
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Look up the priority for a tag.
|
|
53
|
+
*/
|
|
54
|
+
getTagPriority(tagId) {
|
|
55
|
+
return this.config.tagPriorities[tagId] ?? this.config.defaultPriority ?? DEFAULT_PRIORITY;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Compute combined priority for a card based on its tags.
|
|
59
|
+
*/
|
|
60
|
+
computeCardPriority(cardTags) {
|
|
61
|
+
if (cardTags.length === 0) return this.config.defaultPriority ?? DEFAULT_PRIORITY;
|
|
62
|
+
const priorities = cardTags.map((tag) => this.getTagPriority(tag));
|
|
63
|
+
switch (this.config.combineMode) {
|
|
64
|
+
case "max": return Math.max(...priorities);
|
|
65
|
+
case "min": return Math.min(...priorities);
|
|
66
|
+
case "average": return priorities.reduce((sum, p) => sum + p, 0) / priorities.length;
|
|
67
|
+
default: return Math.max(...priorities);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Compute boost factor based on priority.
|
|
72
|
+
*
|
|
73
|
+
* The formula: 1 + (priority - 0.5) * priorityInfluence
|
|
74
|
+
*
|
|
75
|
+
* This creates a multiplier centered around 1.0:
|
|
76
|
+
* - Priority 1.0 with influence 0.5 → 1.25 (25% boost)
|
|
77
|
+
* - Priority 0.5 with any influence → 1.00 (neutral)
|
|
78
|
+
* - Priority 0.0 with influence 0.5 → 0.75 (25% reduction)
|
|
79
|
+
*/
|
|
80
|
+
computeBoostFactor(priority) {
|
|
81
|
+
const influence = this.config.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE;
|
|
82
|
+
return 1 + (priority - .5) * influence;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Build human-readable reason for priority adjustment.
|
|
86
|
+
*/
|
|
87
|
+
buildPriorityReason(cardTags, priority, boostFactor, finalScore) {
|
|
88
|
+
if (cardTags.length === 0) return `No tags, neutral priority (${priority.toFixed(2)})`;
|
|
89
|
+
const tagList = cardTags.slice(0, 3).join(", ");
|
|
90
|
+
const more = cardTags.length > 3 ? ` (+${cardTags.length - 3} more)` : "";
|
|
91
|
+
if (boostFactor === 1) return `Neutral priority (${priority.toFixed(2)}) for tags: ${tagList}${more}`;
|
|
92
|
+
else if (boostFactor > 1) return `High-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} → boost ${boostFactor.toFixed(2)}x → ${finalScore.toFixed(2)})`;
|
|
93
|
+
else return `Low-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} → reduce ${boostFactor.toFixed(2)}x → ${finalScore.toFixed(2)})`;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* CardFilter.transform implementation.
|
|
97
|
+
*
|
|
98
|
+
* Apply priority-adjusted scoring. Cards with high-priority tags get boosted,
|
|
99
|
+
* cards with low-priority tags get reduced scores.
|
|
100
|
+
*/
|
|
101
|
+
async transform(cards, _context) {
|
|
102
|
+
return await Promise.all(cards.map(async (card) => {
|
|
103
|
+
const cardTags = card.tags ?? [];
|
|
104
|
+
const priority = this.computeCardPriority(cardTags);
|
|
105
|
+
const boostFactor = this.computeBoostFactor(priority);
|
|
106
|
+
const finalScore = Math.max(0, card.score * boostFactor);
|
|
107
|
+
const action = boostFactor > 1 ? "boosted" : boostFactor < 1 ? "penalized" : "passed";
|
|
108
|
+
const reason = this.buildPriorityReason(cardTags, priority, boostFactor, finalScore);
|
|
109
|
+
return {
|
|
110
|
+
...card,
|
|
111
|
+
score: finalScore,
|
|
112
|
+
provenance: [...card.provenance, {
|
|
113
|
+
strategy: "relativePriority",
|
|
114
|
+
strategyName: this.strategyName || this.name,
|
|
115
|
+
strategyId: this.strategyId || "NAVIGATION_STRATEGY-priority",
|
|
116
|
+
action,
|
|
117
|
+
score: finalScore,
|
|
118
|
+
reason
|
|
119
|
+
}]
|
|
120
|
+
};
|
|
121
|
+
}));
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Legacy getWeightedCards - now throws as filters should not be used as generators.
|
|
125
|
+
*
|
|
126
|
+
* Use transform() via Pipeline instead.
|
|
127
|
+
*/
|
|
128
|
+
async getWeightedCards(_limit) {
|
|
129
|
+
throw new Error("RelativePriorityNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().");
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
//#endregion
|
|
133
|
+
export { RelativePriorityNavigator as default };
|
|
134
|
+
|
|
135
|
+
//# sourceMappingURL=relativePriority.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"relativePriority.mjs","names":[],"sources":["../../../../src/core/navigators/filters/relativePriority.ts"],"sourcesContent":["import type { CourseDBInterface } from '../../interfaces/courseDB';\nimport type { UserDBInterface } from '../../interfaces/userDB';\nimport { ContentNavigator } from '../index';\nimport type { WeightedCard } from '../index';\nimport type { ContentNavigationStrategyData } from '../../types/contentNavigationStrategy';\nimport type { CardFilter, FilterContext, FilterKind } from './types';\nimport type { GeneratorResult } from '../generators/types';\n\n/**\n * Configuration for the RelativePriority strategy.\n *\n * Course authors define priority weights for tags, allowing the system\n * to prefer high-utility content (common, well-behaved patterns) over\n * lower-utility content (rare, irregular patterns).\n *\n * Example use case: In phonics, prefer teaching 's' (common, consistent)\n * before 'x' or 'z' (rare, sometimes irregular).\n */\nexport interface RelativePriorityConfig {\n /**\n * Map of tag ID to priority weight (0-1).\n *\n * 1.0 = highest priority (present first)\n * 0.5 = neutral\n * 0.0 = lowest priority (defer until later)\n *\n * Example:\n * {\n * \"letter-s\": 0.95,\n * \"letter-t\": 0.90,\n * \"letter-x\": 0.10,\n * \"letter-z\": 0.05\n * }\n */\n tagPriorities: { [tagId: string]: number };\n\n /**\n * Priority for tags not explicitly listed (default: 0.5).\n * 0.5 means unlisted tags have neutral effect on scoring.\n */\n defaultPriority?: number;\n\n /**\n * How to combine priorities when a card has multiple tags.\n *\n * - 'max': Use the highest priority among the card's tags (default)\n * - 'average': Average all tag priorities\n * - 'min': Use the lowest priority (conservative)\n */\n combineMode?: 'max' | 'average' | 'min';\n\n /**\n * How strongly priority influences the final score (0-1, default: 0.5).\n *\n * At 0.0: Priority has no effect (pure delegate scoring)\n * At 0.5: Priority can boost/reduce scores by up to 25%\n * At 1.0: Priority can boost/reduce scores by up to 50%\n *\n * The boost factor formula: 1 + (priority - 0.5) * priorityInfluence\n * - Priority 1.0 with influence 0.5 → boost of 1.25\n * - Priority 0.5 with influence 0.5 → boost of 1.00 (neutral)\n * - Priority 0.0 with influence 0.5 → boost of 0.75\n */\n priorityInfluence?: number;\n}\n\nconst DEFAULT_PRIORITY = 0.5;\nconst DEFAULT_PRIORITY_INFLUENCE = 0.5;\nconst DEFAULT_COMBINE_MODE: 'max' | 'average' | 'min' = 'max';\n\n/**\n * A filter strategy that boosts scores for high-utility content.\n *\n * Course authors assign priority weights to tags. Cards with high-priority\n * tags get boosted scores, making them more likely to be presented first.\n * This allows teaching the most useful, well-behaved concepts before\n * moving on to rarer or more irregular ones.\n *\n * Example: When teaching phonics, prioritize common letters (s, t, a) over\n * rare ones (x, z, q) by assigning higher priority weights to common letters.\n *\n * Implements CardFilter for use in Pipeline architecture.\n * Also extends ContentNavigator for backward compatibility.\n */\nexport default class RelativePriorityNavigator extends ContentNavigator implements CardFilter {\n private config: RelativePriorityConfig;\n\n /** Human-readable name for CardFilter interface */\n name: string;\n\n /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */\n static readonly kind: FilterKind = 'signal';\n readonly kind = RelativePriorityNavigator.kind;\n\n constructor(\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n ) {\n super(user, course, strategyData);\n this.config = this.parseConfig(strategyData.serializedData);\n this.name = strategyData.name || 'Relative Priority';\n }\n\n private parseConfig(serializedData: string): RelativePriorityConfig {\n try {\n const parsed = JSON.parse(serializedData);\n return {\n tagPriorities: parsed.tagPriorities || {},\n defaultPriority: parsed.defaultPriority ?? DEFAULT_PRIORITY,\n combineMode: parsed.combineMode ?? DEFAULT_COMBINE_MODE,\n priorityInfluence: parsed.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE,\n };\n } catch {\n // Return safe defaults if parsing fails\n return {\n tagPriorities: {},\n defaultPriority: DEFAULT_PRIORITY,\n combineMode: DEFAULT_COMBINE_MODE,\n priorityInfluence: DEFAULT_PRIORITY_INFLUENCE,\n };\n }\n }\n\n /**\n * Look up the priority for a tag.\n */\n private getTagPriority(tagId: string): number {\n return this.config.tagPriorities[tagId] ?? this.config.defaultPriority ?? DEFAULT_PRIORITY;\n }\n\n /**\n * Compute combined priority for a card based on its tags.\n */\n private computeCardPriority(cardTags: string[]): number {\n if (cardTags.length === 0) {\n return this.config.defaultPriority ?? DEFAULT_PRIORITY;\n }\n\n const priorities = cardTags.map((tag) => this.getTagPriority(tag));\n\n switch (this.config.combineMode) {\n case 'max':\n return Math.max(...priorities);\n case 'min':\n return Math.min(...priorities);\n case 'average':\n return priorities.reduce((sum, p) => sum + p, 0) / priorities.length;\n default:\n return Math.max(...priorities);\n }\n }\n\n /**\n * Compute boost factor based on priority.\n *\n * The formula: 1 + (priority - 0.5) * priorityInfluence\n *\n * This creates a multiplier centered around 1.0:\n * - Priority 1.0 with influence 0.5 → 1.25 (25% boost)\n * - Priority 0.5 with any influence → 1.00 (neutral)\n * - Priority 0.0 with influence 0.5 → 0.75 (25% reduction)\n */\n private computeBoostFactor(priority: number): number {\n const influence = this.config.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE;\n return 1 + (priority - 0.5) * influence;\n }\n\n /**\n * Build human-readable reason for priority adjustment.\n */\n private buildPriorityReason(\n cardTags: string[],\n priority: number,\n boostFactor: number,\n finalScore: number\n ): string {\n if (cardTags.length === 0) {\n return `No tags, neutral priority (${priority.toFixed(2)})`;\n }\n\n const tagList = cardTags.slice(0, 3).join(', ');\n const more = cardTags.length > 3 ? ` (+${cardTags.length - 3} more)` : '';\n\n if (boostFactor === 1.0) {\n return `Neutral priority (${priority.toFixed(2)}) for tags: ${tagList}${more}`;\n } else if (boostFactor > 1.0) {\n return `High-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} → boost ${boostFactor.toFixed(2)}x → ${finalScore.toFixed(2)})`;\n } else {\n return `Low-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} → reduce ${boostFactor.toFixed(2)}x → ${finalScore.toFixed(2)})`;\n }\n }\n\n /**\n * CardFilter.transform implementation.\n *\n * Apply priority-adjusted scoring. Cards with high-priority tags get boosted,\n * cards with low-priority tags get reduced scores.\n */\n async transform(cards: WeightedCard[], _context: FilterContext): Promise<WeightedCard[]> {\n const adjusted: WeightedCard[] = await Promise.all(\n cards.map(async (card) => {\n const cardTags = card.tags ?? [];\n const priority = this.computeCardPriority(cardTags);\n const boostFactor = this.computeBoostFactor(priority);\n // No upper clamp — scores may exceed 1.0 intentionally.\n // Scores are only used for relative ordering within a pipeline run,\n // so absolute magnitude doesn't matter. Clamping to 1.0 here collapsed\n // differentiation when GPC preReqBoosts and priority boosts compounded\n // (e.g. 0.96 × 2.5 × 1.24 → 2.98, previously crushed back to 1.0).\n // Floor of 0 is kept: negative scores have no meaning.\n const finalScore = Math.max(0, card.score * boostFactor);\n\n // Determine action based on boost factor\n const action = boostFactor > 1.0 ? 'boosted' : boostFactor < 1.0 ? 'penalized' : 'passed';\n\n // Build reason explaining priority adjustment\n const reason = this.buildPriorityReason(cardTags, priority, boostFactor, finalScore);\n\n return {\n ...card,\n score: finalScore,\n provenance: [\n ...card.provenance,\n {\n strategy: 'relativePriority',\n strategyName: this.strategyName || this.name,\n strategyId: this.strategyId || 'NAVIGATION_STRATEGY-priority',\n action,\n score: finalScore,\n reason,\n },\n ],\n };\n })\n );\n\n return adjusted;\n }\n\n /**\n * Legacy getWeightedCards - now throws as filters should not be used as generators.\n *\n * Use transform() via Pipeline instead.\n */\n async getWeightedCards(_limit: number): Promise<GeneratorResult> {\n throw new Error(\n 'RelativePriorityNavigator 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":";;;AAkEA,MAAM,mBAAmB;AACzB,MAAM,6BAA6B;AACnC,MAAM,uBAAkD;;;;;;;;;;;;;;;AAgBxD,IAAqB,4BAArB,MAAqB,kCAAkC,iBAAuC;CAC5F;;CAGA;;CAGA,OAAgB,OAAmB;CACnC,OAAgB,0BAA0B;CAE1C,YACE,MACA,QACA,cACA;AACA,QAAM,MAAM,QAAQ,aAAa;AACjC,OAAK,SAAS,KAAK,YAAY,aAAa,eAAe;AAC3D,OAAK,OAAO,aAAa,QAAQ;;CAGnC,YAAoB,gBAAgD;AAClE,MAAI;GACF,MAAM,SAAS,KAAK,MAAM,eAAe;AACzC,UAAO;IACL,eAAe,OAAO,iBAAiB,EAAE;IACzC,iBAAiB,OAAO,mBAAmB;IAC3C,aAAa,OAAO,eAAe;IACnC,mBAAmB,OAAO,qBAAqB;IAChD;UACK;AAEN,UAAO;IACL,eAAe,EAAE;IACjB,iBAAiB;IACjB,aAAa;IACb,mBAAmB;IACpB;;;;;;CAOL,eAAuB,OAAuB;AAC5C,SAAO,KAAK,OAAO,cAAc,UAAU,KAAK,OAAO,mBAAmB;;;;;CAM5E,oBAA4B,UAA4B;AACtD,MAAI,SAAS,WAAW,EACtB,QAAO,KAAK,OAAO,mBAAmB;EAGxC,MAAM,aAAa,SAAS,KAAK,QAAQ,KAAK,eAAe,IAAI,CAAC;AAElE,UAAQ,KAAK,OAAO,aAApB;GACE,KAAK,MACH,QAAO,KAAK,IAAI,GAAG,WAAW;GAChC,KAAK,MACH,QAAO,KAAK,IAAI,GAAG,WAAW;GAChC,KAAK,UACH,QAAO,WAAW,QAAQ,KAAK,MAAM,MAAM,GAAG,EAAE,GAAG,WAAW;GAChE,QACE,QAAO,KAAK,IAAI,GAAG,WAAW;;;;;;;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F;IACF;IACD,CACH;;;;;;;CAUH,MAAM,iBAAiB,QAA0C;AAC/D,QAAM,IAAI,MACR,8IAED"}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import "../../../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
import { ContentNavigator } from "../index.mjs";
|
|
3
|
+
//#region src/core/navigators/filters/userTagPreference.ts
|
|
4
|
+
/**
|
|
5
|
+
* A filter that applies user-configured tag preferences.
|
|
6
|
+
*
|
|
7
|
+
* Reads preferences from STRATEGY_STATE document in user's database.
|
|
8
|
+
* If no preferences exist, passes through unchanged (no-op).
|
|
9
|
+
*
|
|
10
|
+
* Implements CardFilter for use in Pipeline architecture.
|
|
11
|
+
* Also extends ContentNavigator for compatibility with dynamic loading.
|
|
12
|
+
*/
|
|
13
|
+
var UserTagPreferenceFilter = class UserTagPreferenceFilter extends ContentNavigator {
|
|
14
|
+
_strategyData;
|
|
15
|
+
/** Human-readable name for CardFilter interface */
|
|
16
|
+
name;
|
|
17
|
+
/** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
|
|
18
|
+
static kind = "signal";
|
|
19
|
+
kind = UserTagPreferenceFilter.kind;
|
|
20
|
+
constructor(user, course, strategyData) {
|
|
21
|
+
super(user, course, strategyData);
|
|
22
|
+
this._strategyData = strategyData;
|
|
23
|
+
this.name = strategyData.name || "User Tag Preferences";
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Compute multiplier for a card based on its tags and user preferences.
|
|
27
|
+
* Returns the maximum multiplier among all matching tags, or 1.0 if no matches.
|
|
28
|
+
*/
|
|
29
|
+
computeMultiplier(cardTags, boostMap) {
|
|
30
|
+
const multipliers = cardTags.map((tag) => boostMap[tag]).filter((val) => val !== void 0);
|
|
31
|
+
if (multipliers.length === 0) return 1;
|
|
32
|
+
return Math.max(...multipliers);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Build human-readable reason for the filter's decision.
|
|
36
|
+
*/
|
|
37
|
+
buildReason(cardTags, boostMap, multiplier) {
|
|
38
|
+
const matchingTags = cardTags.filter((tag) => boostMap[tag] === multiplier);
|
|
39
|
+
if (multiplier === 0) return `Excluded by user preference: ${matchingTags.join(", ")} (${multiplier}x)`;
|
|
40
|
+
if (multiplier < 1) return `Penalized by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
|
|
41
|
+
if (multiplier > 1) return `Boosted by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
|
|
42
|
+
return "No matching user preferences";
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* CardFilter.transform implementation.
|
|
46
|
+
*
|
|
47
|
+
* Apply user tag preferences:
|
|
48
|
+
* 1. Read preferences from strategy state
|
|
49
|
+
* 2. If no preferences, pass through unchanged
|
|
50
|
+
* 3. For each card:
|
|
51
|
+
* - Look up tag in boost record
|
|
52
|
+
* - If tag found: apply multiplier (0 = exclude, 1 = neutral, >1 = boost)
|
|
53
|
+
* - If multiple tags match: use max multiplier
|
|
54
|
+
* - Append provenance with clear reason
|
|
55
|
+
*/
|
|
56
|
+
async transform(cards, _context) {
|
|
57
|
+
const prefs = await this.getStrategyState();
|
|
58
|
+
if (!prefs || Object.keys(prefs.boost).length === 0) return cards.map((card) => ({
|
|
59
|
+
...card,
|
|
60
|
+
provenance: [...card.provenance, {
|
|
61
|
+
strategy: "userTagPreference",
|
|
62
|
+
strategyName: this.strategyName || this.name,
|
|
63
|
+
strategyId: this.strategyId || this._strategyData._id,
|
|
64
|
+
action: "passed",
|
|
65
|
+
score: card.score,
|
|
66
|
+
reason: "No user tag preferences configured"
|
|
67
|
+
}]
|
|
68
|
+
}));
|
|
69
|
+
return await Promise.all(cards.map(async (card) => {
|
|
70
|
+
const cardTags = card.tags ?? [];
|
|
71
|
+
const multiplier = this.computeMultiplier(cardTags, prefs.boost);
|
|
72
|
+
const finalScore = Math.min(1, card.score * multiplier);
|
|
73
|
+
let action;
|
|
74
|
+
if (multiplier === 0 || multiplier < 1) action = "penalized";
|
|
75
|
+
else if (multiplier > 1) action = "boosted";
|
|
76
|
+
else action = "passed";
|
|
77
|
+
return {
|
|
78
|
+
...card,
|
|
79
|
+
score: finalScore,
|
|
80
|
+
provenance: [...card.provenance, {
|
|
81
|
+
strategy: "userTagPreference",
|
|
82
|
+
strategyName: this.strategyName || this.name,
|
|
83
|
+
strategyId: this.strategyId || this._strategyData._id,
|
|
84
|
+
action,
|
|
85
|
+
score: finalScore,
|
|
86
|
+
reason: this.buildReason(cardTags, prefs.boost, multiplier)
|
|
87
|
+
}]
|
|
88
|
+
};
|
|
89
|
+
}));
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Legacy getWeightedCards - throws as filters should not be used as generators.
|
|
93
|
+
*/
|
|
94
|
+
async getWeightedCards(_limit) {
|
|
95
|
+
throw new Error("UserTagPreferenceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().");
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
//#endregion
|
|
99
|
+
export { UserTagPreferenceFilter as default };
|
|
100
|
+
|
|
101
|
+
//# sourceMappingURL=userTagPreference.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"userTagPreference.mjs","names":[],"sources":["../../../../src/core/navigators/filters/userTagPreference.ts"],"sourcesContent":["import type { CourseDBInterface } from '../../interfaces/courseDB';\nimport type { UserDBInterface } from '../../interfaces/userDB';\nimport { ContentNavigator } from '../index';\nimport type { WeightedCard } from '../index';\nimport type { ContentNavigationStrategyData } from '../../types/contentNavigationStrategy';\nimport type { CardFilter, FilterContext, FilterKind } from './types';\nimport type { GeneratorResult } from '../generators/types';\n\n// ============================================================================\n// USER TAG PREFERENCE FILTER\n// ============================================================================\n//\n// Allows users to personalize their learning experience by specifying:\n// - Tags to boost/penalize (score multiplied by boost factor)\n//\n// User preferences are stored in STRATEGY_STATE documents in the user's\n// database, enabling persistence across sessions and sync across devices.\n//\n// Use cases:\n// - Goal-based learning: \"I want to learn piano by ear, skip sight-reading\"\n// - Selective focus: \"I only want to practice chess endgames\"\n// - Accessibility: \"Skip text-heavy cards, prefer visual content\"\n// - Difficulty customization: \"Skip beginner content I already know\"\n//\n// ============================================================================\n\n/**\n * User's tag preference state, stored in STRATEGY_STATE document.\n *\n * This interface defines what gets persisted to the user's database.\n * UI components write to this structure, and the filter reads from it.\n *\n * ## Preferences vs Goals\n *\n * Preferences are **path constraints** — they affect HOW the user learns,\n * not WHAT they're trying to learn. Examples:\n * - \"Skip text-heavy cards\" (accessibility)\n * - \"Prefer visual content\"\n *\n * For **goal-based** filtering (defining WHAT to learn), see the separate\n * UserGoalNavigator (stub). Goals affect progress tracking and completion\n * criteria; preferences only affect card selection.\n *\n * ## Slider Semantics\n *\n * Each tag maps to a multiplier value in the `boost` record:\n * - `0` = banish/exclude (card score = 0)\n * - `0.5` = penalize by 50%\n * - `1.0` = neutral/no effect (default when tag added)\n * - `2.0` = 2x preference boost\n * - Higher values = stronger preference\n *\n * If multiple tags on a card have preferences, the maximum multiplier wins.\n */\nexport interface UserTagPreferenceState {\n /**\n * Tag-specific multipliers.\n * Maps tag name to score multiplier (0 = exclude, 1 = neutral, >1 = boost).\n */\n boost: Record<string, number>;\n\n /**\n * ISO timestamp of last update.\n * Use `moment.utc(updatedAt)` to parse into a Moment object.\n */\n updatedAt: string;\n}\n\n/**\n * A filter that applies user-configured tag preferences.\n *\n * Reads preferences from STRATEGY_STATE document in user's database.\n * If no preferences exist, passes through unchanged (no-op).\n *\n * Implements CardFilter for use in Pipeline architecture.\n * Also extends ContentNavigator for compatibility with dynamic loading.\n */\nexport default class UserTagPreferenceFilter extends ContentNavigator implements CardFilter {\n private _strategyData: ContentNavigationStrategyData;\n\n /** Human-readable name for CardFilter interface */\n name: string;\n\n /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */\n static readonly kind: FilterKind = 'signal';\n readonly kind = UserTagPreferenceFilter.kind;\n\n constructor(\n user: UserDBInterface,\n course: CourseDBInterface,\n strategyData: ContentNavigationStrategyData\n ) {\n super(user, course, strategyData);\n this._strategyData = strategyData;\n this.name = strategyData.name || 'User Tag Preferences';\n }\n\n /**\n * Compute multiplier for a card based on its tags and user preferences.\n * Returns the maximum multiplier among all matching tags, or 1.0 if no matches.\n */\n private computeMultiplier(cardTags: string[], boostMap: Record<string, number>): number {\n const multipliers = cardTags.map((tag) => boostMap[tag]).filter((val) => val !== undefined);\n\n if (multipliers.length === 0) {\n return 1.0;\n }\n\n // Use max multiplier among matching tags\n return Math.max(...multipliers);\n }\n\n /**\n * Build human-readable reason for the filter's decision.\n */\n private buildReason(\n cardTags: string[],\n boostMap: Record<string, number>,\n multiplier: number\n ): string {\n // Find which tag(s) contributed to the multiplier\n const matchingTags = cardTags.filter((tag) => boostMap[tag] === multiplier);\n\n if (multiplier === 0) {\n return `Excluded by user preference: ${matchingTags.join(', ')} (${multiplier}x)`;\n }\n\n if (multiplier < 1.0) {\n return `Penalized by user preference: ${matchingTags.join(', ')} (${multiplier.toFixed(2)}x)`;\n }\n\n if (multiplier > 1.0) {\n return `Boosted by user preference: ${matchingTags.join(', ')} (${multiplier.toFixed(2)}x)`;\n }\n\n return 'No matching user preferences';\n }\n\n /**\n * CardFilter.transform implementation.\n *\n * Apply user tag preferences:\n * 1. Read preferences from strategy state\n * 2. If no preferences, pass through unchanged\n * 3. For each card:\n * - Look up tag in boost record\n * - If tag found: apply multiplier (0 = exclude, 1 = neutral, >1 = boost)\n * - If multiple tags match: use max multiplier\n * - Append provenance with clear reason\n */\n async transform(cards: WeightedCard[], _context: FilterContext): Promise<WeightedCard[]> {\n // Read user preferences from strategy state\n const prefs = await this.getStrategyState<UserTagPreferenceState>();\n\n // No preferences configured → pass through unchanged\n if (!prefs || Object.keys(prefs.boost).length === 0) {\n return cards.map((card) => ({\n ...card,\n provenance: [\n ...card.provenance,\n {\n strategy: 'userTagPreference',\n strategyName: this.strategyName || this.name,\n strategyId: this.strategyId || this._strategyData._id,\n action: 'passed' as const,\n score: card.score,\n reason: 'No user tag preferences configured',\n },\n ],\n }));\n }\n\n // Process each card\n const adjusted: WeightedCard[] = await Promise.all(\n cards.map(async (card) => {\n const cardTags = card.tags ?? [];\n\n // Compute multiplier based on card tags and user preferences\n const multiplier = this.computeMultiplier(cardTags, prefs.boost);\n const finalScore = Math.min(1, card.score * multiplier);\n\n // Determine action for provenance\n let action: 'passed' | 'boosted' | 'penalized';\n if (multiplier === 0 || multiplier < 1.0) {\n action = 'penalized';\n } else if (multiplier > 1.0) {\n action = 'boosted';\n } else {\n action = 'passed';\n }\n\n return {\n ...card,\n score: finalScore,\n provenance: [\n ...card.provenance,\n {\n strategy: 'userTagPreference',\n strategyName: this.strategyName || this.name,\n strategyId: this.strategyId || this._strategyData._id,\n action,\n score: finalScore,\n reason: this.buildReason(cardTags, prefs.boost, multiplier),\n },\n ],\n };\n })\n );\n\n return adjusted;\n }\n\n /**\n * Legacy getWeightedCards - throws as filters should not be used as generators.\n */\n async getWeightedCards(_limit: number): Promise<GeneratorResult> {\n throw new Error(\n 'UserTagPreferenceFilter 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":";;;;;;;;;;;;AA6EA,IAAqB,0BAArB,MAAqB,gCAAgC,iBAAuC;CAC1F;;CAGA;;CAGA,OAAgB,OAAmB;CACnC,OAAgB,wBAAwB;CAExC,YACE,MACA,QACA,cACA;AACA,QAAM,MAAM,QAAQ,aAAa;AACjC,OAAK,gBAAgB;AACrB,OAAK,OAAO,aAAa,QAAQ;;;;;;CAOnC,kBAA0B,UAAoB,UAA0C;EACtF,MAAM,cAAc,SAAS,KAAK,QAAQ,SAAS,KAAK,CAAC,QAAQ,QAAQ,QAAQ,KAAA,EAAU;AAE3F,MAAI,YAAY,WAAW,EACzB,QAAO;AAIT,SAAO,KAAK,IAAI,GAAG,YAAY;;;;;CAMjC,YACE,UACA,UACA,YACQ;EAER,MAAM,eAAe,SAAS,QAAQ,QAAQ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