@vue-skuilder/db 0.1.23 → 0.1.25
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-BP9hznNV.d.ts → contentSource-BmnmvH8C.d.ts} +268 -3
- package/dist/{contentSource-DsJadoBU.d.cts → contentSource-DfBbaLA-.d.cts} +268 -3
- package/dist/core/index.d.cts +310 -6
- package/dist/core/index.d.ts +310 -6
- package/dist/core/index.js +2606 -666
- package/dist/core/index.js.map +1 -1
- package/dist/core/index.mjs +2564 -639
- package/dist/core/index.mjs.map +1 -1
- package/dist/{dataLayerProvider-CHYrQ5pB.d.cts → dataLayerProvider-BeRXVMs5.d.cts} +1 -1
- package/dist/{dataLayerProvider-MDTxXq2l.d.ts → dataLayerProvider-CG9GfaAY.d.ts} +1 -1
- package/dist/impl/couch/index.d.cts +11 -3
- package/dist/impl/couch/index.d.ts +11 -3
- package/dist/impl/couch/index.js +2336 -656
- package/dist/impl/couch/index.js.map +1 -1
- package/dist/impl/couch/index.mjs +2316 -631
- package/dist/impl/couch/index.mjs.map +1 -1
- package/dist/impl/static/index.d.cts +4 -4
- package/dist/impl/static/index.d.ts +4 -4
- package/dist/impl/static/index.js +2312 -632
- package/dist/impl/static/index.js.map +1 -1
- package/dist/impl/static/index.mjs +2315 -630
- package/dist/impl/static/index.mjs.map +1 -1
- package/dist/{index-Dj0SEgk3.d.ts → index-BWvO-_rJ.d.ts} +1 -1
- package/dist/{index-B_j6u5E4.d.cts → index-Ba7hYbHj.d.cts} +1 -1
- package/dist/index.d.cts +278 -20
- package/dist/index.d.ts +278 -20
- package/dist/index.js +3603 -720
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +3529 -674
- package/dist/index.mjs.map +1 -1
- package/dist/{types-DQaXnuoc.d.ts → types-CJrLM1Ew.d.ts} +1 -1
- package/dist/{types-Bn0itutr.d.cts → types-W8n-B6HG.d.cts} +1 -1
- package/dist/{types-legacy-DDY4N-Uq.d.cts → types-legacy-JXDxinpU.d.cts} +5 -1
- package/dist/{types-legacy-DDY4N-Uq.d.ts → types-legacy-JXDxinpU.d.ts} +5 -1
- package/dist/util/packer/index.d.cts +3 -3
- package/dist/util/packer/index.d.ts +3 -3
- package/docs/brainstorm-navigation-paradigm.md +40 -34
- package/docs/future-orchestration-vision.md +216 -0
- package/docs/navigators-architecture.md +210 -9
- package/docs/todo-review-urgency-adaptation.md +205 -0
- package/docs/todo-strategy-authoring.md +8 -6
- package/package.json +3 -3
- package/src/core/index.ts +2 -0
- package/src/core/interfaces/contentSource.ts +7 -0
- package/src/core/interfaces/userDB.ts +50 -0
- package/src/core/navigators/Pipeline.ts +132 -5
- package/src/core/navigators/PipelineAssembler.ts +21 -22
- package/src/core/navigators/PipelineDebugger.ts +426 -0
- package/src/core/navigators/filters/WeightedFilter.ts +141 -0
- package/src/core/navigators/filters/types.ts +4 -0
- package/src/core/navigators/generators/CompositeGenerator.ts +82 -19
- package/src/core/navigators/generators/elo.ts +14 -1
- package/src/core/navigators/generators/srs.ts +146 -18
- package/src/core/navigators/generators/types.ts +4 -0
- package/src/core/navigators/index.ts +203 -13
- package/src/core/orchestration/gradient.ts +133 -0
- package/src/core/orchestration/index.ts +210 -0
- package/src/core/orchestration/learning.ts +250 -0
- package/src/core/orchestration/recording.ts +92 -0
- package/src/core/orchestration/signal.ts +67 -0
- package/src/core/types/contentNavigationStrategy.ts +38 -0
- package/src/core/types/learningState.ts +77 -0
- package/src/core/types/types-legacy.ts +4 -0
- package/src/core/types/userOutcome.ts +51 -0
- package/src/courseConfigRegistration.ts +107 -0
- package/src/factory.ts +6 -0
- package/src/impl/common/BaseUserDB.ts +16 -0
- package/src/impl/couch/user-course-relDB.ts +12 -0
- package/src/study/MixerDebugger.ts +555 -0
- package/src/study/SessionController.ts +159 -20
- package/src/study/SessionDebugger.ts +442 -0
- package/src/study/SourceMixer.ts +36 -17
- package/src/study/TODO-session-scheduling.md +133 -0
- package/src/study/index.ts +2 -0
- package/src/study/services/EloService.ts +79 -4
- package/src/study/services/ResponseProcessor.ts +130 -72
- package/src/study/services/SrsService.ts +9 -0
- package/tests/core/navigators/Pipeline.test.ts +2 -0
- package/tests/core/navigators/PipelineAssembler.test.ts +4 -4
- package/docs/todo-evolutionary-orchestration.md +0 -310
package/dist/core/index.mjs
CHANGED
|
@@ -1,7 +1,17 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
1
2
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
3
|
+
var __glob = (map) => (path2) => {
|
|
4
|
+
var fn = map[path2];
|
|
5
|
+
if (fn) return fn();
|
|
6
|
+
throw new Error("Module not found in bundle: " + path2);
|
|
7
|
+
};
|
|
2
8
|
var __esm = (fn, res) => function __init() {
|
|
3
9
|
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
4
10
|
};
|
|
11
|
+
var __export = (target, all) => {
|
|
12
|
+
for (var name in all)
|
|
13
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
14
|
+
};
|
|
5
15
|
|
|
6
16
|
// src/core/interfaces/adminDB.ts
|
|
7
17
|
var init_adminDB = __esm({
|
|
@@ -91,6 +101,8 @@ var init_types_legacy = __esm({
|
|
|
91
101
|
DocType2["TAG"] = "TAG";
|
|
92
102
|
DocType2["NAVIGATION_STRATEGY"] = "NAVIGATION_STRATEGY";
|
|
93
103
|
DocType2["STRATEGY_STATE"] = "STRATEGY_STATE";
|
|
104
|
+
DocType2["USER_OUTCOME"] = "USER_OUTCOME";
|
|
105
|
+
DocType2["STRATEGY_LEARNING_STATE"] = "STRATEGY_LEARNING_STATE";
|
|
94
106
|
return DocType2;
|
|
95
107
|
})(DocType || {});
|
|
96
108
|
DocTypePrefixes = {
|
|
@@ -105,7 +117,9 @@ var init_types_legacy = __esm({
|
|
|
105
117
|
["VIEW" /* VIEW */]: "VIEW",
|
|
106
118
|
["PEDAGOGY" /* PEDAGOGY */]: "PEDAGOGY",
|
|
107
119
|
["NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */]: "NAVIGATION_STRATEGY",
|
|
108
|
-
["STRATEGY_STATE" /* STRATEGY_STATE */]: "STRATEGY_STATE"
|
|
120
|
+
["STRATEGY_STATE" /* STRATEGY_STATE */]: "STRATEGY_STATE",
|
|
121
|
+
["USER_OUTCOME" /* USER_OUTCOME */]: "USER_OUTCOME",
|
|
122
|
+
["STRATEGY_LEARNING_STATE" /* STRATEGY_LEARNING_STATE */]: "STRATEGY_LEARNING_STATE"
|
|
109
123
|
};
|
|
110
124
|
}
|
|
111
125
|
});
|
|
@@ -434,6 +448,15 @@ var init_user_course_relDB = __esm({
|
|
|
434
448
|
void this.user.updateCourseSettings(this._courseId, updates);
|
|
435
449
|
}
|
|
436
450
|
}
|
|
451
|
+
async getStrategyState(strategyKey) {
|
|
452
|
+
return this.user.getStrategyState(this._courseId, strategyKey);
|
|
453
|
+
}
|
|
454
|
+
async putStrategyState(strategyKey, data) {
|
|
455
|
+
return this.user.putStrategyState(this._courseId, strategyKey, data);
|
|
456
|
+
}
|
|
457
|
+
async deleteStrategyState(strategyKey) {
|
|
458
|
+
return this.user.deleteStrategyState(this._courseId, strategyKey);
|
|
459
|
+
}
|
|
437
460
|
async getReviewstoDate(targetDate) {
|
|
438
461
|
const allReviews = await this.user.getPendingReviews(this._courseId);
|
|
439
462
|
logger.debug(
|
|
@@ -673,359 +696,289 @@ var init_courseLookupDB = __esm({
|
|
|
673
696
|
}
|
|
674
697
|
});
|
|
675
698
|
|
|
676
|
-
// src/core/navigators/
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
699
|
+
// src/core/navigators/PipelineDebugger.ts
|
|
700
|
+
var PipelineDebugger_exports = {};
|
|
701
|
+
__export(PipelineDebugger_exports, {
|
|
702
|
+
buildRunReport: () => buildRunReport,
|
|
703
|
+
captureRun: () => captureRun,
|
|
704
|
+
mountPipelineDebugger: () => mountPipelineDebugger,
|
|
705
|
+
pipelineDebugAPI: () => pipelineDebugAPI
|
|
706
|
+
});
|
|
707
|
+
function getOrigin(card) {
|
|
681
708
|
const firstEntry = card.provenance[0];
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
709
|
+
if (!firstEntry) return "unknown";
|
|
710
|
+
const reason = firstEntry.reason?.toLowerCase() || "";
|
|
711
|
+
if (reason.includes("new card")) return "new";
|
|
712
|
+
if (reason.includes("review")) return "review";
|
|
713
|
+
return "unknown";
|
|
714
|
+
}
|
|
715
|
+
function captureRun(report) {
|
|
716
|
+
const fullReport = {
|
|
717
|
+
...report,
|
|
718
|
+
runId: `run-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
|
|
719
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
720
|
+
};
|
|
721
|
+
runHistory.unshift(fullReport);
|
|
722
|
+
if (runHistory.length > MAX_RUNS) {
|
|
723
|
+
runHistory.pop();
|
|
688
724
|
}
|
|
689
|
-
return "new";
|
|
690
725
|
}
|
|
691
|
-
function
|
|
692
|
-
|
|
726
|
+
function buildRunReport(courseId, courseName, generatorName, generators, generatedCount, filters, allCards, selectedCards) {
|
|
727
|
+
const selectedIds = new Set(selectedCards.map((c) => c.cardId));
|
|
728
|
+
const cards = allCards.map((card) => ({
|
|
729
|
+
cardId: card.cardId,
|
|
730
|
+
courseId: card.courseId,
|
|
731
|
+
origin: getOrigin(card),
|
|
732
|
+
finalScore: card.score,
|
|
733
|
+
provenance: card.provenance,
|
|
734
|
+
selected: selectedIds.has(card.cardId)
|
|
735
|
+
}));
|
|
736
|
+
const reviewsSelected = selectedCards.filter((c) => getOrigin(c) === "review").length;
|
|
737
|
+
const newSelected = selectedCards.filter((c) => getOrigin(c) === "new").length;
|
|
738
|
+
return {
|
|
739
|
+
courseId,
|
|
740
|
+
courseName,
|
|
741
|
+
generatorName,
|
|
742
|
+
generators,
|
|
743
|
+
generatedCount,
|
|
744
|
+
filters,
|
|
745
|
+
finalCount: selectedCards.length,
|
|
746
|
+
reviewsSelected,
|
|
747
|
+
newSelected,
|
|
748
|
+
cards
|
|
749
|
+
};
|
|
693
750
|
}
|
|
694
|
-
function
|
|
695
|
-
return
|
|
751
|
+
function formatProvenance(provenance) {
|
|
752
|
+
return provenance.map((p) => {
|
|
753
|
+
const actionSymbol = p.action === "generated" ? "\u{1F3B2}" : p.action === "boosted" ? "\u2B06\uFE0F" : p.action === "penalized" ? "\u2B07\uFE0F" : "\u27A1\uFE0F";
|
|
754
|
+
return ` ${actionSymbol} ${p.strategyName}: ${p.score.toFixed(3)} - ${p.reason}`;
|
|
755
|
+
}).join("\n");
|
|
696
756
|
}
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
757
|
+
function printRunSummary(run) {
|
|
758
|
+
console.group(`\u{1F50D} Pipeline Run: ${run.courseId} (${run.courseName || "unnamed"})`);
|
|
759
|
+
logger.info(`Run ID: ${run.runId}`);
|
|
760
|
+
logger.info(`Time: ${run.timestamp.toISOString()}`);
|
|
761
|
+
logger.info(`Generator: ${run.generatorName} \u2192 ${run.generatedCount} candidates`);
|
|
762
|
+
if (run.generators && run.generators.length > 0) {
|
|
763
|
+
console.group("Generator breakdown:");
|
|
764
|
+
for (const g of run.generators) {
|
|
765
|
+
logger.info(
|
|
766
|
+
` ${g.name}: ${g.cardCount} cards (${g.newCount} new, ${g.reviewCount} reviews, top: ${g.topScore.toFixed(2)})`
|
|
767
|
+
);
|
|
768
|
+
}
|
|
769
|
+
console.groupEnd();
|
|
770
|
+
}
|
|
771
|
+
if (run.filters.length > 0) {
|
|
772
|
+
console.group("Filter impact:");
|
|
773
|
+
for (const f of run.filters) {
|
|
774
|
+
logger.info(` ${f.name}: \u2191${f.boosted} \u2193${f.penalized} =${f.passed} \u2715${f.removed}`);
|
|
775
|
+
}
|
|
776
|
+
console.groupEnd();
|
|
777
|
+
}
|
|
778
|
+
logger.info(
|
|
779
|
+
`Result: ${run.finalCount} cards selected (${run.newSelected} new, ${run.reviewsSelected} reviews)`
|
|
780
|
+
);
|
|
781
|
+
console.groupEnd();
|
|
782
|
+
}
|
|
783
|
+
function mountPipelineDebugger() {
|
|
784
|
+
if (typeof window === "undefined") return;
|
|
785
|
+
const win = window;
|
|
786
|
+
win.skuilder = win.skuilder || {};
|
|
787
|
+
win.skuilder.pipeline = pipelineDebugAPI;
|
|
788
|
+
}
|
|
789
|
+
var MAX_RUNS, runHistory, pipelineDebugAPI;
|
|
790
|
+
var init_PipelineDebugger = __esm({
|
|
791
|
+
"src/core/navigators/PipelineDebugger.ts"() {
|
|
700
792
|
"use strict";
|
|
701
793
|
init_logger();
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
Navigators2["HIERARCHY"] = "hierarchyDefinition";
|
|
706
|
-
Navigators2["INTERFERENCE"] = "interferenceMitigator";
|
|
707
|
-
Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
|
|
708
|
-
Navigators2["USER_TAG_PREFERENCE"] = "userTagPreference";
|
|
709
|
-
return Navigators2;
|
|
710
|
-
})(Navigators || {});
|
|
711
|
-
NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
|
|
712
|
-
NavigatorRole2["GENERATOR"] = "generator";
|
|
713
|
-
NavigatorRole2["FILTER"] = "filter";
|
|
714
|
-
return NavigatorRole2;
|
|
715
|
-
})(NavigatorRole || {});
|
|
716
|
-
NavigatorRoles = {
|
|
717
|
-
["elo" /* ELO */]: "generator" /* GENERATOR */,
|
|
718
|
-
["srs" /* SRS */]: "generator" /* GENERATOR */,
|
|
719
|
-
["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
|
|
720
|
-
["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
|
|
721
|
-
["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
|
|
722
|
-
["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
|
|
723
|
-
};
|
|
724
|
-
ContentNavigator = class {
|
|
725
|
-
/** User interface for this navigation session */
|
|
726
|
-
user;
|
|
727
|
-
/** Course interface for this navigation session */
|
|
728
|
-
course;
|
|
729
|
-
/** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
|
|
730
|
-
strategyName;
|
|
731
|
-
/** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
|
|
732
|
-
strategyId;
|
|
794
|
+
MAX_RUNS = 10;
|
|
795
|
+
runHistory = [];
|
|
796
|
+
pipelineDebugAPI = {
|
|
733
797
|
/**
|
|
734
|
-
*
|
|
735
|
-
* Call this from subclass constructors to initialize common fields.
|
|
736
|
-
*
|
|
737
|
-
* Note: CompositeGenerator and Pipeline call super() without args, then set
|
|
738
|
-
* user/course fields directly if needed.
|
|
798
|
+
* Get raw run history for programmatic access.
|
|
739
799
|
*/
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
if (strategyData) {
|
|
744
|
-
this.strategyName = strategyData.name;
|
|
745
|
-
this.strategyId = strategyData._id;
|
|
746
|
-
}
|
|
747
|
-
}
|
|
748
|
-
// ============================================================================
|
|
749
|
-
// STRATEGY STATE HELPERS
|
|
750
|
-
// ============================================================================
|
|
751
|
-
//
|
|
752
|
-
// These methods allow strategies to persist their own state (user preferences,
|
|
753
|
-
// learned patterns, temporal tracking) in the user database.
|
|
754
|
-
//
|
|
755
|
-
// ============================================================================
|
|
800
|
+
get runs() {
|
|
801
|
+
return [...runHistory];
|
|
802
|
+
},
|
|
756
803
|
/**
|
|
757
|
-
*
|
|
758
|
-
*
|
|
759
|
-
* Defaults to the constructor name (e.g., "UserTagPreferenceFilter").
|
|
760
|
-
* Override in subclasses if multiple instances of the same strategy type
|
|
761
|
-
* need separate state storage.
|
|
804
|
+
* Show summary of a specific pipeline run.
|
|
762
805
|
*/
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
806
|
+
showRun(idOrIndex = 0) {
|
|
807
|
+
if (runHistory.length === 0) {
|
|
808
|
+
logger.info("[Pipeline Debug] No runs captured yet.");
|
|
809
|
+
return;
|
|
810
|
+
}
|
|
811
|
+
let run;
|
|
812
|
+
if (typeof idOrIndex === "number") {
|
|
813
|
+
run = runHistory[idOrIndex];
|
|
814
|
+
if (!run) {
|
|
815
|
+
logger.info(
|
|
816
|
+
`[Pipeline Debug] No run found at index ${idOrIndex}. History length: ${runHistory.length}`
|
|
817
|
+
);
|
|
818
|
+
return;
|
|
819
|
+
}
|
|
820
|
+
} else {
|
|
821
|
+
run = runHistory.find((r) => r.runId.endsWith(idOrIndex));
|
|
822
|
+
if (!run) {
|
|
823
|
+
logger.info(`[Pipeline Debug] No run found matching ID '${idOrIndex}'.`);
|
|
824
|
+
return;
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
printRunSummary(run);
|
|
828
|
+
},
|
|
766
829
|
/**
|
|
767
|
-
*
|
|
768
|
-
*
|
|
769
|
-
* @returns The strategy's data payload, or null if no state exists
|
|
770
|
-
* @throws Error if user or course is not initialized
|
|
830
|
+
* Show summary of the last pipeline run.
|
|
771
831
|
*/
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
`Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
|
|
776
|
-
);
|
|
777
|
-
}
|
|
778
|
-
return this.user.getStrategyState(this.course.getCourseID(), this.strategyKey);
|
|
779
|
-
}
|
|
832
|
+
showLastRun() {
|
|
833
|
+
this.showRun(0);
|
|
834
|
+
},
|
|
780
835
|
/**
|
|
781
|
-
*
|
|
782
|
-
*
|
|
783
|
-
* @param data - The strategy's data payload to store
|
|
784
|
-
* @throws Error if user or course is not initialized
|
|
836
|
+
* Show detailed provenance for a specific card.
|
|
785
837
|
*/
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
838
|
+
showCard(cardId) {
|
|
839
|
+
for (const run of runHistory) {
|
|
840
|
+
const card = run.cards.find((c) => c.cardId === cardId);
|
|
841
|
+
if (card) {
|
|
842
|
+
console.group(`\u{1F3B4} Card: ${cardId}`);
|
|
843
|
+
logger.info(`Course: ${card.courseId}`);
|
|
844
|
+
logger.info(`Origin: ${card.origin}`);
|
|
845
|
+
logger.info(`Final score: ${card.finalScore.toFixed(3)}`);
|
|
846
|
+
logger.info(`Selected: ${card.selected ? "Yes \u2705" : "No \u274C"}`);
|
|
847
|
+
logger.info("Provenance:");
|
|
848
|
+
logger.info(formatProvenance(card.provenance));
|
|
849
|
+
console.groupEnd();
|
|
850
|
+
return;
|
|
851
|
+
}
|
|
791
852
|
}
|
|
792
|
-
|
|
793
|
-
}
|
|
853
|
+
logger.info(`[Pipeline Debug] Card '${cardId}' not found in recent runs.`);
|
|
854
|
+
},
|
|
794
855
|
/**
|
|
795
|
-
*
|
|
796
|
-
*
|
|
797
|
-
* @param user - User interface
|
|
798
|
-
* @param course - Course interface
|
|
799
|
-
* @param strategyData - Strategy configuration document
|
|
800
|
-
* @returns the runtime object used to steer a study session.
|
|
856
|
+
* Explain why reviews may or may not have been selected.
|
|
801
857
|
*/
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
858
|
+
explainReviews() {
|
|
859
|
+
if (runHistory.length === 0) {
|
|
860
|
+
logger.info("[Pipeline Debug] No runs captured yet.");
|
|
861
|
+
return;
|
|
862
|
+
}
|
|
863
|
+
console.group("\u{1F4CB} Review Selection Analysis");
|
|
864
|
+
for (const run of runHistory) {
|
|
865
|
+
console.group(`Run: ${run.courseId} @ ${run.timestamp.toLocaleTimeString()}`);
|
|
866
|
+
const allReviews = run.cards.filter((c) => c.origin === "review");
|
|
867
|
+
const selectedReviews = allReviews.filter((c) => c.selected);
|
|
868
|
+
if (allReviews.length === 0) {
|
|
869
|
+
logger.info("\u274C No reviews were generated. Check SRS logs for why.");
|
|
870
|
+
} else if (selectedReviews.length === 0) {
|
|
871
|
+
logger.info(`\u26A0\uFE0F ${allReviews.length} reviews generated but none selected.`);
|
|
872
|
+
logger.info("Possible reasons:");
|
|
873
|
+
const topNewScore = Math.max(
|
|
874
|
+
...run.cards.filter((c) => c.origin === "new" && c.selected).map((c) => c.finalScore),
|
|
875
|
+
0
|
|
876
|
+
);
|
|
877
|
+
const topReviewScore = Math.max(...allReviews.map((c) => c.finalScore), 0);
|
|
878
|
+
if (topReviewScore < topNewScore) {
|
|
879
|
+
logger.info(
|
|
880
|
+
` - New cards scored higher (top new: ${topNewScore.toFixed(2)}, top review: ${topReviewScore.toFixed(2)})`
|
|
881
|
+
);
|
|
882
|
+
}
|
|
883
|
+
const topReview = allReviews.sort((a, b) => b.finalScore - a.finalScore)[0];
|
|
884
|
+
if (topReview) {
|
|
885
|
+
logger.info(` - Top review score: ${topReview.finalScore.toFixed(3)}`);
|
|
886
|
+
logger.info(" - Its provenance:");
|
|
887
|
+
logger.info(formatProvenance(topReview.provenance));
|
|
816
888
|
}
|
|
889
|
+
} else {
|
|
890
|
+
logger.info(`\u2705 ${selectedReviews.length}/${allReviews.length} reviews selected.`);
|
|
891
|
+
logger.info("Top selected review:");
|
|
892
|
+
const topSelected = selectedReviews.sort((a, b) => b.finalScore - a.finalScore)[0];
|
|
893
|
+
logger.info(formatProvenance(topSelected.provenance));
|
|
817
894
|
}
|
|
895
|
+
console.groupEnd();
|
|
818
896
|
}
|
|
819
|
-
|
|
820
|
-
|
|
897
|
+
console.groupEnd();
|
|
898
|
+
},
|
|
899
|
+
/**
|
|
900
|
+
* Show all runs in compact format.
|
|
901
|
+
*/
|
|
902
|
+
listRuns() {
|
|
903
|
+
if (runHistory.length === 0) {
|
|
904
|
+
logger.info("[Pipeline Debug] No runs captured yet.");
|
|
905
|
+
return;
|
|
821
906
|
}
|
|
822
|
-
|
|
823
|
-
|
|
907
|
+
console.table(
|
|
908
|
+
runHistory.map((r) => ({
|
|
909
|
+
id: r.runId.slice(-8),
|
|
910
|
+
time: r.timestamp.toLocaleTimeString(),
|
|
911
|
+
course: r.courseName || r.courseId.slice(0, 8),
|
|
912
|
+
generated: r.generatedCount,
|
|
913
|
+
selected: r.finalCount,
|
|
914
|
+
new: r.newSelected,
|
|
915
|
+
reviews: r.reviewsSelected
|
|
916
|
+
}))
|
|
917
|
+
);
|
|
918
|
+
},
|
|
824
919
|
/**
|
|
825
|
-
*
|
|
826
|
-
*
|
|
827
|
-
* **This is the PRIMARY API for navigation strategies.**
|
|
828
|
-
*
|
|
829
|
-
* Returns cards ranked by suitability score (0-1). Higher scores indicate
|
|
830
|
-
* better candidates for presentation. Each card includes a provenance trail
|
|
831
|
-
* documenting how strategies contributed to the final score.
|
|
832
|
-
*
|
|
833
|
-
* ## Implementation Required
|
|
834
|
-
* All navigation strategies MUST override this method. The base class does
|
|
835
|
-
* not provide a default implementation.
|
|
836
|
-
*
|
|
837
|
-
* ## For Generators
|
|
838
|
-
* Override this method to generate candidates and compute scores based on
|
|
839
|
-
* your strategy's logic (e.g., ELO proximity, review urgency). Create the
|
|
840
|
-
* initial provenance entry with action='generated'.
|
|
841
|
-
*
|
|
842
|
-
* ## For Filters
|
|
843
|
-
* Filters should implement the CardFilter interface instead and be composed
|
|
844
|
-
* via Pipeline. Filters do not directly implement getWeightedCards().
|
|
845
|
-
*
|
|
846
|
-
* @param limit - Maximum cards to return
|
|
847
|
-
* @returns Cards sorted by score descending, with provenance trails
|
|
920
|
+
* Export run history as JSON for bug reports.
|
|
848
921
|
*/
|
|
849
|
-
|
|
850
|
-
|
|
922
|
+
export() {
|
|
923
|
+
const json = JSON.stringify(runHistory, null, 2);
|
|
924
|
+
logger.info("[Pipeline Debug] Run history exported. Copy the returned string or use:");
|
|
925
|
+
logger.info(" copy(window.skuilder.pipeline.export())");
|
|
926
|
+
return json;
|
|
927
|
+
},
|
|
928
|
+
/**
|
|
929
|
+
* Clear run history.
|
|
930
|
+
*/
|
|
931
|
+
clear() {
|
|
932
|
+
runHistory.length = 0;
|
|
933
|
+
logger.info("[Pipeline Debug] Run history cleared.");
|
|
934
|
+
},
|
|
935
|
+
/**
|
|
936
|
+
* Show help.
|
|
937
|
+
*/
|
|
938
|
+
help() {
|
|
939
|
+
logger.info(`
|
|
940
|
+
\u{1F527} Pipeline Debug API
|
|
941
|
+
|
|
942
|
+
Commands:
|
|
943
|
+
.showLastRun() Show summary of most recent pipeline run
|
|
944
|
+
.showRun(id|index) Show summary of a specific run (by index or ID suffix)
|
|
945
|
+
.showCard(cardId) Show provenance trail for a specific card
|
|
946
|
+
.explainReviews() Analyze why reviews were/weren't selected
|
|
947
|
+
.listRuns() List all captured runs in table format
|
|
948
|
+
.export() Export run history as JSON for bug reports
|
|
949
|
+
.clear() Clear run history
|
|
950
|
+
.runs Access raw run history array
|
|
951
|
+
.help() Show this help message
|
|
952
|
+
|
|
953
|
+
Example:
|
|
954
|
+
window.skuilder.pipeline.showLastRun()
|
|
955
|
+
window.skuilder.pipeline.showRun(1)
|
|
956
|
+
window.skuilder.pipeline.showCard('abc123')
|
|
957
|
+
`);
|
|
851
958
|
}
|
|
852
959
|
};
|
|
960
|
+
mountPipelineDebugger();
|
|
853
961
|
}
|
|
854
962
|
});
|
|
855
963
|
|
|
856
|
-
// src/core/navigators/
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
)
|
|
865
|
-
}
|
|
866
|
-
function logTagHydration(cards, tagsByCard) {
|
|
867
|
-
const totalTags = Array.from(tagsByCard.values()).reduce((sum, tags) => sum + tags.length, 0);
|
|
868
|
-
const cardsWithTags = Array.from(tagsByCard.values()).filter((tags) => tags.length > 0).length;
|
|
869
|
-
logger.debug(
|
|
870
|
-
`[Pipeline] Tag hydration: ${cards.length} cards, ${cardsWithTags} have tags (${totalTags} total tags) - single batch query`
|
|
871
|
-
);
|
|
872
|
-
}
|
|
873
|
-
function logExecutionSummary(generatorName, generatedCount, filterCount, finalCount, topScores) {
|
|
874
|
-
const scoreDisplay = topScores.length > 0 ? topScores.map((s) => s.toFixed(2)).join(", ") : "none";
|
|
875
|
-
logger.info(
|
|
876
|
-
`[Pipeline] Execution: ${generatorName} produced ${generatedCount} \u2192 ${filterCount} filters \u2192 ${finalCount} results (top scores: ${scoreDisplay})`
|
|
877
|
-
);
|
|
878
|
-
}
|
|
879
|
-
function logCardProvenance(cards, maxCards = 3) {
|
|
880
|
-
const cardsToLog = cards.slice(0, maxCards);
|
|
881
|
-
logger.debug(`[Pipeline] Provenance for top ${cardsToLog.length} cards:`);
|
|
882
|
-
for (const card of cardsToLog) {
|
|
883
|
-
logger.debug(`[Pipeline] ${card.cardId} (final score: ${card.score.toFixed(3)}):`);
|
|
884
|
-
for (const entry of card.provenance) {
|
|
885
|
-
const scoreChange = entry.score.toFixed(3);
|
|
886
|
-
const action = entry.action.padEnd(9);
|
|
887
|
-
logger.debug(
|
|
888
|
-
`[Pipeline] ${action} ${scoreChange} - ${entry.strategyName}: ${entry.reason}`
|
|
889
|
-
);
|
|
890
|
-
}
|
|
891
|
-
}
|
|
892
|
-
}
|
|
893
|
-
var Pipeline;
|
|
894
|
-
var init_Pipeline = __esm({
|
|
895
|
-
"src/core/navigators/Pipeline.ts"() {
|
|
896
|
-
"use strict";
|
|
897
|
-
init_navigators();
|
|
898
|
-
init_logger();
|
|
899
|
-
Pipeline = class extends ContentNavigator {
|
|
900
|
-
generator;
|
|
901
|
-
filters;
|
|
902
|
-
/**
|
|
903
|
-
* Create a new pipeline.
|
|
904
|
-
*
|
|
905
|
-
* @param generator - The generator (or CompositeGenerator) that produces candidates
|
|
906
|
-
* @param filters - Filters to apply sequentially (order doesn't matter for multipliers)
|
|
907
|
-
* @param user - User database interface
|
|
908
|
-
* @param course - Course database interface
|
|
909
|
-
*/
|
|
910
|
-
constructor(generator, filters, user, course) {
|
|
911
|
-
super();
|
|
912
|
-
this.generator = generator;
|
|
913
|
-
this.filters = filters;
|
|
914
|
-
this.user = user;
|
|
915
|
-
this.course = course;
|
|
916
|
-
course.getCourseConfig().then((cfg) => {
|
|
917
|
-
logger.debug(`[pipeline] Crated pipeline for ${cfg.name}`);
|
|
918
|
-
}).catch((e) => {
|
|
919
|
-
logger.error(`[pipeline] Failed to lookup courseCfg: ${e}`);
|
|
920
|
-
});
|
|
921
|
-
logPipelineConfig(generator, filters);
|
|
922
|
-
}
|
|
923
|
-
/**
|
|
924
|
-
* Get weighted cards by running generator and applying filters.
|
|
925
|
-
*
|
|
926
|
-
* 1. Build shared context (user ELO, etc.)
|
|
927
|
-
* 2. Get candidates from generator (passing context)
|
|
928
|
-
* 3. Batch hydrate tags for all candidates
|
|
929
|
-
* 4. Apply each filter sequentially
|
|
930
|
-
* 5. Remove zero-score cards
|
|
931
|
-
* 6. Sort by score descending
|
|
932
|
-
* 7. Return top N
|
|
933
|
-
*
|
|
934
|
-
* @param limit - Maximum number of cards to return
|
|
935
|
-
* @returns Cards sorted by score descending
|
|
936
|
-
*/
|
|
937
|
-
async getWeightedCards(limit) {
|
|
938
|
-
const context = await this.buildContext();
|
|
939
|
-
const overFetchMultiplier = 2 + this.filters.length * 0.5;
|
|
940
|
-
const fetchLimit = Math.ceil(limit * overFetchMultiplier);
|
|
941
|
-
logger.debug(
|
|
942
|
-
`[Pipeline] Fetching ${fetchLimit} candidates from generator '${this.generator.name}'`
|
|
943
|
-
);
|
|
944
|
-
let cards = await this.generator.getWeightedCards(fetchLimit, context);
|
|
945
|
-
const generatedCount = cards.length;
|
|
946
|
-
logger.debug(`[Pipeline] Generator returned ${generatedCount} candidates`);
|
|
947
|
-
cards = await this.hydrateTags(cards);
|
|
948
|
-
for (const filter of this.filters) {
|
|
949
|
-
const beforeCount = cards.length;
|
|
950
|
-
cards = await filter.transform(cards, context);
|
|
951
|
-
logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeCount} \u2192 ${cards.length} cards`);
|
|
952
|
-
}
|
|
953
|
-
cards = cards.filter((c) => c.score > 0);
|
|
954
|
-
cards.sort((a, b) => b.score - a.score);
|
|
955
|
-
const result = cards.slice(0, limit);
|
|
956
|
-
const topScores = result.slice(0, 3).map((c) => c.score);
|
|
957
|
-
logExecutionSummary(
|
|
958
|
-
this.generator.name,
|
|
959
|
-
generatedCount,
|
|
960
|
-
this.filters.length,
|
|
961
|
-
result.length,
|
|
962
|
-
topScores
|
|
963
|
-
);
|
|
964
|
-
logCardProvenance(result, 3);
|
|
965
|
-
return result;
|
|
966
|
-
}
|
|
967
|
-
/**
|
|
968
|
-
* Batch hydrate tags for all cards.
|
|
969
|
-
*
|
|
970
|
-
* Fetches tags for all cards in a single database query and attaches them
|
|
971
|
-
* to the WeightedCard objects. Filters can then use card.tags instead of
|
|
972
|
-
* making individual getAppliedTags() calls.
|
|
973
|
-
*
|
|
974
|
-
* @param cards - Cards to hydrate
|
|
975
|
-
* @returns Cards with tags populated
|
|
976
|
-
*/
|
|
977
|
-
async hydrateTags(cards) {
|
|
978
|
-
if (cards.length === 0) {
|
|
979
|
-
return cards;
|
|
980
|
-
}
|
|
981
|
-
const cardIds = cards.map((c) => c.cardId);
|
|
982
|
-
const tagsByCard = await this.course.getAppliedTagsBatch(cardIds);
|
|
983
|
-
logTagHydration(cards, tagsByCard);
|
|
984
|
-
return cards.map((card) => ({
|
|
985
|
-
...card,
|
|
986
|
-
tags: tagsByCard.get(card.cardId) ?? []
|
|
987
|
-
}));
|
|
988
|
-
}
|
|
989
|
-
/**
|
|
990
|
-
* Build shared context for generator and filters.
|
|
991
|
-
*
|
|
992
|
-
* Called once per getWeightedCards() invocation.
|
|
993
|
-
* Contains data that the generator and multiple filters might need.
|
|
994
|
-
*
|
|
995
|
-
* The context satisfies both GeneratorContext and FilterContext interfaces.
|
|
996
|
-
*/
|
|
997
|
-
async buildContext() {
|
|
998
|
-
let userElo = 1e3;
|
|
999
|
-
try {
|
|
1000
|
-
const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
|
|
1001
|
-
const courseElo = toCourseElo2(courseReg.elo);
|
|
1002
|
-
userElo = courseElo.global.score;
|
|
1003
|
-
} catch (e) {
|
|
1004
|
-
logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
|
|
1005
|
-
}
|
|
1006
|
-
return {
|
|
1007
|
-
user: this.user,
|
|
1008
|
-
course: this.course,
|
|
1009
|
-
userElo
|
|
1010
|
-
};
|
|
1011
|
-
}
|
|
1012
|
-
/**
|
|
1013
|
-
* Get the course ID for this pipeline.
|
|
1014
|
-
*/
|
|
1015
|
-
getCourseID() {
|
|
1016
|
-
return this.course.getCourseID();
|
|
1017
|
-
}
|
|
1018
|
-
};
|
|
1019
|
-
}
|
|
1020
|
-
});
|
|
1021
|
-
|
|
1022
|
-
// src/core/navigators/generators/CompositeGenerator.ts
|
|
1023
|
-
var DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
|
|
1024
|
-
var init_CompositeGenerator = __esm({
|
|
1025
|
-
"src/core/navigators/generators/CompositeGenerator.ts"() {
|
|
964
|
+
// src/core/navigators/generators/CompositeGenerator.ts
|
|
965
|
+
var CompositeGenerator_exports = {};
|
|
966
|
+
__export(CompositeGenerator_exports, {
|
|
967
|
+
AggregationMode: () => AggregationMode,
|
|
968
|
+
default: () => CompositeGenerator
|
|
969
|
+
});
|
|
970
|
+
var AggregationMode, DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
|
|
971
|
+
var init_CompositeGenerator = __esm({
|
|
972
|
+
"src/core/navigators/generators/CompositeGenerator.ts"() {
|
|
1026
973
|
"use strict";
|
|
1027
974
|
init_navigators();
|
|
1028
975
|
init_logger();
|
|
976
|
+
AggregationMode = /* @__PURE__ */ ((AggregationMode2) => {
|
|
977
|
+
AggregationMode2["MAX"] = "max";
|
|
978
|
+
AggregationMode2["AVERAGE"] = "average";
|
|
979
|
+
AggregationMode2["FREQUENCY_BOOST"] = "frequencyBoost";
|
|
980
|
+
return AggregationMode2;
|
|
981
|
+
})(AggregationMode || {});
|
|
1029
982
|
DEFAULT_AGGREGATION_MODE = "frequencyBoost" /* FREQUENCY_BOOST */;
|
|
1030
983
|
FREQUENCY_BOOST_FACTOR = 0.1;
|
|
1031
984
|
CompositeGenerator = class _CompositeGenerator extends ContentNavigator {
|
|
@@ -1076,22 +1029,55 @@ var init_CompositeGenerator = __esm({
|
|
|
1076
1029
|
const results = await Promise.all(
|
|
1077
1030
|
this.generators.map((g) => g.getWeightedCards(limit, context))
|
|
1078
1031
|
);
|
|
1032
|
+
const generatorSummaries = [];
|
|
1033
|
+
results.forEach((cards, index) => {
|
|
1034
|
+
const gen = this.generators[index];
|
|
1035
|
+
const genName = gen.name || `Generator ${index}`;
|
|
1036
|
+
const newCards = cards.filter((c) => c.provenance[0]?.reason?.includes("new card"));
|
|
1037
|
+
const reviewCards = cards.filter((c) => c.provenance[0]?.reason?.includes("review"));
|
|
1038
|
+
if (cards.length > 0) {
|
|
1039
|
+
const topScore = Math.max(...cards.map((c) => c.score)).toFixed(2);
|
|
1040
|
+
const parts = [];
|
|
1041
|
+
if (newCards.length > 0) parts.push(`${newCards.length} new`);
|
|
1042
|
+
if (reviewCards.length > 0) parts.push(`${reviewCards.length} reviews`);
|
|
1043
|
+
const breakdown = parts.length > 0 ? parts.join(", ") : `${cards.length} cards`;
|
|
1044
|
+
generatorSummaries.push(`${genName}: ${breakdown} (top: ${topScore})`);
|
|
1045
|
+
} else {
|
|
1046
|
+
generatorSummaries.push(`${genName}: 0 cards`);
|
|
1047
|
+
}
|
|
1048
|
+
});
|
|
1049
|
+
logger.info(`[Composite] Generator breakdown: ${generatorSummaries.join(" | ")}`);
|
|
1079
1050
|
const byCardId = /* @__PURE__ */ new Map();
|
|
1080
|
-
|
|
1051
|
+
results.forEach((cards, index) => {
|
|
1052
|
+
const gen = this.generators[index];
|
|
1053
|
+
let weight = gen.learnable?.weight ?? 1;
|
|
1054
|
+
let deviation;
|
|
1055
|
+
if (gen.learnable && !gen.staticWeight && context.orchestration) {
|
|
1056
|
+
const strategyId = gen.strategyId;
|
|
1057
|
+
if (strategyId) {
|
|
1058
|
+
weight = context.orchestration.getEffectiveWeight(strategyId, gen.learnable);
|
|
1059
|
+
deviation = context.orchestration.getDeviation(strategyId);
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1081
1062
|
for (const card of cards) {
|
|
1063
|
+
if (card.provenance.length > 0) {
|
|
1064
|
+
card.provenance[0].effectiveWeight = weight;
|
|
1065
|
+
card.provenance[0].deviation = deviation;
|
|
1066
|
+
}
|
|
1082
1067
|
const existing = byCardId.get(card.cardId) || [];
|
|
1083
|
-
existing.push(card);
|
|
1068
|
+
existing.push({ card, weight });
|
|
1084
1069
|
byCardId.set(card.cardId, existing);
|
|
1085
1070
|
}
|
|
1086
|
-
}
|
|
1071
|
+
});
|
|
1087
1072
|
const merged = [];
|
|
1088
|
-
for (const [,
|
|
1089
|
-
const
|
|
1073
|
+
for (const [, items] of byCardId) {
|
|
1074
|
+
const cards = items.map((i) => i.card);
|
|
1075
|
+
const aggregatedScore = this.aggregateScores(items);
|
|
1090
1076
|
const finalScore = Math.min(1, aggregatedScore);
|
|
1091
1077
|
const mergedProvenance = cards.flatMap((c) => c.provenance);
|
|
1092
1078
|
const initialScore = cards[0].score;
|
|
1093
1079
|
const action = finalScore > initialScore ? "boosted" : finalScore < initialScore ? "penalized" : "passed";
|
|
1094
|
-
const reason = this.buildAggregationReason(
|
|
1080
|
+
const reason = this.buildAggregationReason(items, finalScore);
|
|
1095
1081
|
merged.push({
|
|
1096
1082
|
...cards[0],
|
|
1097
1083
|
score: finalScore,
|
|
@@ -1113,22 +1099,26 @@ var init_CompositeGenerator = __esm({
|
|
|
1113
1099
|
/**
|
|
1114
1100
|
* Build human-readable reason for score aggregation.
|
|
1115
1101
|
*/
|
|
1116
|
-
buildAggregationReason(
|
|
1102
|
+
buildAggregationReason(items, finalScore) {
|
|
1103
|
+
const cards = items.map((i) => i.card);
|
|
1117
1104
|
const count = cards.length;
|
|
1118
1105
|
const scores = cards.map((c) => c.score.toFixed(2)).join(", ");
|
|
1119
1106
|
if (count === 1) {
|
|
1120
|
-
|
|
1107
|
+
const weightMsg = Math.abs(items[0].weight - 1) > 1e-3 ? ` (w=${items[0].weight.toFixed(2)})` : "";
|
|
1108
|
+
return `Single generator, score ${finalScore.toFixed(2)}${weightMsg}`;
|
|
1121
1109
|
}
|
|
1122
1110
|
const strategies = cards.map((c) => c.provenance[0]?.strategy || "unknown").join(", ");
|
|
1123
1111
|
switch (this.aggregationMode) {
|
|
1124
1112
|
case "max" /* MAX */:
|
|
1125
1113
|
return `Max of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
|
|
1126
1114
|
case "average" /* AVERAGE */:
|
|
1127
|
-
return `
|
|
1115
|
+
return `Weighted Avg of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
|
|
1128
1116
|
case "frequencyBoost" /* FREQUENCY_BOOST */: {
|
|
1129
|
-
const
|
|
1117
|
+
const totalWeight = items.reduce((sum, i) => sum + i.weight, 0);
|
|
1118
|
+
const weightedSum = items.reduce((sum, i) => sum + i.card.score * i.weight, 0);
|
|
1119
|
+
const avg = totalWeight > 0 ? weightedSum / totalWeight : 0;
|
|
1130
1120
|
const boost = 1 + FREQUENCY_BOOST_FACTOR * (count - 1);
|
|
1131
|
-
return `Frequency boost from ${count} generators (${strategies}): avg ${avg.toFixed(2)} \xD7 ${boost.toFixed(2)} \u2192 ${finalScore.toFixed(2)}`;
|
|
1121
|
+
return `Frequency boost from ${count} generators (${strategies}): w-avg ${avg.toFixed(2)} \xD7 ${boost.toFixed(2)} \u2192 ${finalScore.toFixed(2)}`;
|
|
1132
1122
|
}
|
|
1133
1123
|
default:
|
|
1134
1124
|
return `Aggregated from ${count} generators: ${finalScore.toFixed(2)}`;
|
|
@@ -1137,16 +1127,22 @@ var init_CompositeGenerator = __esm({
|
|
|
1137
1127
|
/**
|
|
1138
1128
|
* Aggregate scores from multiple generators for the same card.
|
|
1139
1129
|
*/
|
|
1140
|
-
aggregateScores(
|
|
1141
|
-
const scores =
|
|
1130
|
+
aggregateScores(items) {
|
|
1131
|
+
const scores = items.map((i) => i.card.score);
|
|
1142
1132
|
switch (this.aggregationMode) {
|
|
1143
1133
|
case "max" /* MAX */:
|
|
1144
1134
|
return Math.max(...scores);
|
|
1145
|
-
case "average" /* AVERAGE */:
|
|
1146
|
-
|
|
1135
|
+
case "average" /* AVERAGE */: {
|
|
1136
|
+
const totalWeight = items.reduce((sum, i) => sum + i.weight, 0);
|
|
1137
|
+
if (totalWeight === 0) return 0;
|
|
1138
|
+
const weightedSum = items.reduce((sum, i) => sum + i.card.score * i.weight, 0);
|
|
1139
|
+
return weightedSum / totalWeight;
|
|
1140
|
+
}
|
|
1147
1141
|
case "frequencyBoost" /* FREQUENCY_BOOST */: {
|
|
1148
|
-
const
|
|
1149
|
-
const
|
|
1142
|
+
const totalWeight = items.reduce((sum, i) => sum + i.weight, 0);
|
|
1143
|
+
const weightedSum = items.reduce((sum, i) => sum + i.card.score * i.weight, 0);
|
|
1144
|
+
const avg = totalWeight > 0 ? weightedSum / totalWeight : 0;
|
|
1145
|
+
const frequencyBoost = 1 + FREQUENCY_BOOST_FACTOR * (items.length - 1);
|
|
1150
1146
|
return avg * frequencyBoost;
|
|
1151
1147
|
}
|
|
1152
1148
|
default:
|
|
@@ -1157,134 +1153,18 @@ var init_CompositeGenerator = __esm({
|
|
|
1157
1153
|
}
|
|
1158
1154
|
});
|
|
1159
1155
|
|
|
1160
|
-
// src/core/navigators/PipelineAssembler.ts
|
|
1161
|
-
var PipelineAssembler;
|
|
1162
|
-
var init_PipelineAssembler = __esm({
|
|
1163
|
-
"src/core/navigators/PipelineAssembler.ts"() {
|
|
1164
|
-
"use strict";
|
|
1165
|
-
init_navigators();
|
|
1166
|
-
init_Pipeline();
|
|
1167
|
-
init_types_legacy();
|
|
1168
|
-
init_logger();
|
|
1169
|
-
init_CompositeGenerator();
|
|
1170
|
-
PipelineAssembler = class {
|
|
1171
|
-
/**
|
|
1172
|
-
* Assembles a navigation pipeline from strategy documents.
|
|
1173
|
-
*
|
|
1174
|
-
* 1. Separates into generators and filters by role
|
|
1175
|
-
* 2. Validates at least one generator exists (or creates default ELO)
|
|
1176
|
-
* 3. Instantiates generators - wraps multiple in CompositeGenerator
|
|
1177
|
-
* 4. Instantiates filters
|
|
1178
|
-
* 5. Returns Pipeline(generator, filters)
|
|
1179
|
-
*
|
|
1180
|
-
* @param input - Strategy documents plus user/course interfaces
|
|
1181
|
-
* @returns Assembled pipeline and any warnings
|
|
1182
|
-
*/
|
|
1183
|
-
async assemble(input) {
|
|
1184
|
-
const { strategies, user, course } = input;
|
|
1185
|
-
const warnings = [];
|
|
1186
|
-
if (strategies.length === 0) {
|
|
1187
|
-
return {
|
|
1188
|
-
pipeline: null,
|
|
1189
|
-
generatorStrategies: [],
|
|
1190
|
-
filterStrategies: [],
|
|
1191
|
-
warnings
|
|
1192
|
-
};
|
|
1193
|
-
}
|
|
1194
|
-
const generatorStrategies = [];
|
|
1195
|
-
const filterStrategies = [];
|
|
1196
|
-
for (const s of strategies) {
|
|
1197
|
-
if (isGenerator(s.implementingClass)) {
|
|
1198
|
-
generatorStrategies.push(s);
|
|
1199
|
-
} else if (isFilter(s.implementingClass)) {
|
|
1200
|
-
filterStrategies.push(s);
|
|
1201
|
-
} else {
|
|
1202
|
-
warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
|
|
1203
|
-
}
|
|
1204
|
-
}
|
|
1205
|
-
if (generatorStrategies.length === 0) {
|
|
1206
|
-
if (filterStrategies.length > 0) {
|
|
1207
|
-
logger.debug(
|
|
1208
|
-
"[PipelineAssembler] No generator found, using default ELO with configured filters"
|
|
1209
|
-
);
|
|
1210
|
-
generatorStrategies.push(this.makeDefaultEloStrategy(course.getCourseID()));
|
|
1211
|
-
} else {
|
|
1212
|
-
warnings.push("No generator strategy found");
|
|
1213
|
-
return {
|
|
1214
|
-
pipeline: null,
|
|
1215
|
-
generatorStrategies: [],
|
|
1216
|
-
filterStrategies: [],
|
|
1217
|
-
warnings
|
|
1218
|
-
};
|
|
1219
|
-
}
|
|
1220
|
-
}
|
|
1221
|
-
let generator;
|
|
1222
|
-
if (generatorStrategies.length === 1) {
|
|
1223
|
-
const nav = await ContentNavigator.create(user, course, generatorStrategies[0]);
|
|
1224
|
-
generator = nav;
|
|
1225
|
-
logger.debug(`[PipelineAssembler] Using single generator: ${generatorStrategies[0].name}`);
|
|
1226
|
-
} else {
|
|
1227
|
-
logger.debug(
|
|
1228
|
-
`[PipelineAssembler] Using CompositeGenerator for ${generatorStrategies.length} generators: ${generatorStrategies.map((g) => g.name).join(", ")}`
|
|
1229
|
-
);
|
|
1230
|
-
generator = await CompositeGenerator.fromStrategies(user, course, generatorStrategies);
|
|
1231
|
-
}
|
|
1232
|
-
const filters = [];
|
|
1233
|
-
const sortedFilterStrategies = [...filterStrategies].sort(
|
|
1234
|
-
(a, b) => a.name.localeCompare(b.name)
|
|
1235
|
-
);
|
|
1236
|
-
for (const filterStrategy of sortedFilterStrategies) {
|
|
1237
|
-
try {
|
|
1238
|
-
const nav = await ContentNavigator.create(user, course, filterStrategy);
|
|
1239
|
-
if ("transform" in nav && typeof nav.transform === "function") {
|
|
1240
|
-
filters.push(nav);
|
|
1241
|
-
logger.debug(`[PipelineAssembler] Added filter: ${filterStrategy.name}`);
|
|
1242
|
-
} else {
|
|
1243
|
-
warnings.push(
|
|
1244
|
-
`Filter '${filterStrategy.name}' does not implement CardFilter.transform(), skipping`
|
|
1245
|
-
);
|
|
1246
|
-
}
|
|
1247
|
-
} catch (e) {
|
|
1248
|
-
warnings.push(`Failed to instantiate filter '${filterStrategy.name}': ${e}`);
|
|
1249
|
-
}
|
|
1250
|
-
}
|
|
1251
|
-
const pipeline = new Pipeline(generator, filters, user, course);
|
|
1252
|
-
logger.debug(
|
|
1253
|
-
`[PipelineAssembler] Assembled pipeline with ${generatorStrategies.length} generator(s) and ${filters.length} filter(s)`
|
|
1254
|
-
);
|
|
1255
|
-
return {
|
|
1256
|
-
pipeline,
|
|
1257
|
-
generatorStrategies,
|
|
1258
|
-
filterStrategies: sortedFilterStrategies,
|
|
1259
|
-
warnings
|
|
1260
|
-
};
|
|
1261
|
-
}
|
|
1262
|
-
/**
|
|
1263
|
-
* Creates a default ELO generator strategy.
|
|
1264
|
-
* Used when filters are configured but no generator is specified.
|
|
1265
|
-
*/
|
|
1266
|
-
makeDefaultEloStrategy(courseId) {
|
|
1267
|
-
return {
|
|
1268
|
-
_id: "NAVIGATION_STRATEGY-ELO-default",
|
|
1269
|
-
course: courseId,
|
|
1270
|
-
docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
|
|
1271
|
-
name: "ELO (default)",
|
|
1272
|
-
description: "Default ELO-based generator",
|
|
1273
|
-
implementingClass: "elo" /* ELO */,
|
|
1274
|
-
serializedData: ""
|
|
1275
|
-
};
|
|
1276
|
-
}
|
|
1277
|
-
};
|
|
1278
|
-
}
|
|
1279
|
-
});
|
|
1280
|
-
|
|
1281
1156
|
// src/core/navigators/generators/elo.ts
|
|
1282
|
-
|
|
1157
|
+
var elo_exports = {};
|
|
1158
|
+
__export(elo_exports, {
|
|
1159
|
+
default: () => ELONavigator
|
|
1160
|
+
});
|
|
1161
|
+
import { toCourseElo as toCourseElo2 } from "@vue-skuilder/common";
|
|
1283
1162
|
var ELONavigator;
|
|
1284
1163
|
var init_elo = __esm({
|
|
1285
1164
|
"src/core/navigators/generators/elo.ts"() {
|
|
1286
1165
|
"use strict";
|
|
1287
1166
|
init_navigators();
|
|
1167
|
+
init_logger();
|
|
1288
1168
|
ELONavigator = class extends ContentNavigator {
|
|
1289
1169
|
/** Human-readable name for CardGenerator interface */
|
|
1290
1170
|
name;
|
|
@@ -1313,7 +1193,7 @@ var init_elo = __esm({
|
|
|
1313
1193
|
userGlobalElo = context.userElo;
|
|
1314
1194
|
} else {
|
|
1315
1195
|
const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
|
|
1316
|
-
const userElo =
|
|
1196
|
+
const userElo = toCourseElo2(courseReg.elo);
|
|
1317
1197
|
userGlobalElo = userElo.global.score;
|
|
1318
1198
|
}
|
|
1319
1199
|
const activeCards = await this.user.getActiveCards();
|
|
@@ -1344,205 +1224,2207 @@ var init_elo = __esm({
|
|
|
1344
1224
|
};
|
|
1345
1225
|
});
|
|
1346
1226
|
scored.sort((a, b) => b.score - a.score);
|
|
1347
|
-
|
|
1227
|
+
const result = scored.slice(0, limit);
|
|
1228
|
+
if (result.length > 0) {
|
|
1229
|
+
const topScores = result.slice(0, 3).map((c) => c.score.toFixed(2)).join(", ");
|
|
1230
|
+
logger.info(
|
|
1231
|
+
`[ELO] Course ${this.course.getCourseID()}: ${result.length} new cards (top scores: ${topScores})`
|
|
1232
|
+
);
|
|
1233
|
+
} else {
|
|
1234
|
+
logger.info(`[ELO] Course ${this.course.getCourseID()}: No new cards available`);
|
|
1235
|
+
}
|
|
1236
|
+
return result;
|
|
1237
|
+
}
|
|
1238
|
+
};
|
|
1239
|
+
}
|
|
1240
|
+
});
|
|
1241
|
+
|
|
1242
|
+
// src/core/navigators/generators/index.ts
|
|
1243
|
+
var generators_exports = {};
|
|
1244
|
+
var init_generators = __esm({
|
|
1245
|
+
"src/core/navigators/generators/index.ts"() {
|
|
1246
|
+
"use strict";
|
|
1247
|
+
}
|
|
1248
|
+
});
|
|
1249
|
+
|
|
1250
|
+
// src/core/navigators/generators/srs.ts
|
|
1251
|
+
var srs_exports = {};
|
|
1252
|
+
__export(srs_exports, {
|
|
1253
|
+
default: () => SRSNavigator
|
|
1254
|
+
});
|
|
1255
|
+
import moment3 from "moment";
|
|
1256
|
+
var DEFAULT_HEALTHY_BACKLOG, MAX_BACKLOG_PRESSURE, SRSNavigator;
|
|
1257
|
+
var init_srs = __esm({
|
|
1258
|
+
"src/core/navigators/generators/srs.ts"() {
|
|
1259
|
+
"use strict";
|
|
1260
|
+
init_navigators();
|
|
1261
|
+
init_logger();
|
|
1262
|
+
DEFAULT_HEALTHY_BACKLOG = 20;
|
|
1263
|
+
MAX_BACKLOG_PRESSURE = 0.5;
|
|
1264
|
+
SRSNavigator = class extends ContentNavigator {
|
|
1265
|
+
/** Human-readable name for CardGenerator interface */
|
|
1266
|
+
name;
|
|
1267
|
+
/** Healthy backlog threshold - when exceeded, backlog pressure kicks in */
|
|
1268
|
+
healthyBacklog;
|
|
1269
|
+
constructor(user, course, strategyData) {
|
|
1270
|
+
super(user, course, strategyData);
|
|
1271
|
+
this.name = strategyData?.name || "SRS";
|
|
1272
|
+
const config = this.parseConfig(strategyData?.serializedData);
|
|
1273
|
+
this.healthyBacklog = config.healthyBacklog ?? DEFAULT_HEALTHY_BACKLOG;
|
|
1274
|
+
}
|
|
1275
|
+
/**
|
|
1276
|
+
* Parse configuration from serialized JSON.
|
|
1277
|
+
*/
|
|
1278
|
+
parseConfig(serializedData) {
|
|
1279
|
+
if (!serializedData) return {};
|
|
1280
|
+
try {
|
|
1281
|
+
return JSON.parse(serializedData);
|
|
1282
|
+
} catch {
|
|
1283
|
+
logger.warn("[SRS] Failed to parse strategy config, using defaults");
|
|
1284
|
+
return {};
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
/**
|
|
1288
|
+
* Get review cards scored by urgency.
|
|
1289
|
+
*
|
|
1290
|
+
* Score formula combines:
|
|
1291
|
+
* - Relative overdueness: hoursOverdue / intervalHours
|
|
1292
|
+
* - Interval recency: exponential decay favoring shorter intervals
|
|
1293
|
+
* - Backlog pressure: boost when due reviews exceed healthy threshold
|
|
1294
|
+
*
|
|
1295
|
+
* Cards not yet due are excluded (not scored as 0).
|
|
1296
|
+
*
|
|
1297
|
+
* This method supports both the legacy signature (limit only) and the
|
|
1298
|
+
* CardGenerator interface signature (limit, context).
|
|
1299
|
+
*
|
|
1300
|
+
* @param limit - Maximum number of cards to return
|
|
1301
|
+
* @param _context - Optional GeneratorContext (currently unused, but required for interface)
|
|
1302
|
+
*/
|
|
1303
|
+
async getWeightedCards(limit, _context) {
|
|
1304
|
+
if (!this.user || !this.course) {
|
|
1305
|
+
throw new Error("SRSNavigator requires user and course to be set");
|
|
1306
|
+
}
|
|
1307
|
+
const courseId = this.course.getCourseID();
|
|
1308
|
+
const reviews = await this.user.getPendingReviews(courseId);
|
|
1309
|
+
const now = moment3.utc();
|
|
1310
|
+
const dueReviews = reviews.filter((r) => now.isAfter(moment3.utc(r.reviewTime)));
|
|
1311
|
+
const backlogPressure = this.computeBacklogPressure(dueReviews.length);
|
|
1312
|
+
if (dueReviews.length > 0) {
|
|
1313
|
+
const pressureNote = backlogPressure > 0 ? ` [backlog pressure: +${backlogPressure.toFixed(2)}]` : ` [healthy backlog]`;
|
|
1314
|
+
logger.info(
|
|
1315
|
+
`[SRS] Course ${courseId}: ${dueReviews.length} reviews due now (of ${reviews.length} scheduled)${pressureNote}`
|
|
1316
|
+
);
|
|
1317
|
+
} else if (reviews.length > 0) {
|
|
1318
|
+
const sortedByDue = [...reviews].sort(
|
|
1319
|
+
(a, b) => moment3.utc(a.reviewTime).diff(moment3.utc(b.reviewTime))
|
|
1320
|
+
);
|
|
1321
|
+
const nextDue = sortedByDue[0];
|
|
1322
|
+
const nextDueTime = moment3.utc(nextDue.reviewTime);
|
|
1323
|
+
const untilDue = moment3.duration(nextDueTime.diff(now));
|
|
1324
|
+
const untilDueStr = untilDue.asHours() < 1 ? `${Math.round(untilDue.asMinutes())}m` : untilDue.asHours() < 24 ? `${Math.round(untilDue.asHours())}h` : `${Math.round(untilDue.asDays())}d`;
|
|
1325
|
+
logger.info(
|
|
1326
|
+
`[SRS] Course ${courseId}: 0 reviews due now (${reviews.length} scheduled, next in ${untilDueStr})`
|
|
1327
|
+
);
|
|
1328
|
+
} else {
|
|
1329
|
+
logger.info(`[SRS] Course ${courseId}: No reviews scheduled`);
|
|
1330
|
+
}
|
|
1331
|
+
const scored = dueReviews.map((review) => {
|
|
1332
|
+
const { score, reason } = this.computeUrgencyScore(review, now, backlogPressure);
|
|
1333
|
+
return {
|
|
1334
|
+
cardId: review.cardId,
|
|
1335
|
+
courseId: review.courseId,
|
|
1336
|
+
score,
|
|
1337
|
+
reviewID: review._id,
|
|
1338
|
+
provenance: [
|
|
1339
|
+
{
|
|
1340
|
+
strategy: "srs",
|
|
1341
|
+
strategyName: this.strategyName || this.name,
|
|
1342
|
+
strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
|
|
1343
|
+
action: "generated",
|
|
1344
|
+
score,
|
|
1345
|
+
reason
|
|
1346
|
+
}
|
|
1347
|
+
]
|
|
1348
|
+
};
|
|
1349
|
+
});
|
|
1350
|
+
return scored.sort((a, b) => b.score - a.score).slice(0, limit);
|
|
1351
|
+
}
|
|
1352
|
+
/**
|
|
1353
|
+
* Compute backlog pressure based on number of due reviews.
|
|
1354
|
+
*
|
|
1355
|
+
* Backlog pressure is 0 when at or below healthy threshold,
|
|
1356
|
+
* and increases linearly above it, maxing out at MAX_BACKLOG_PRESSURE.
|
|
1357
|
+
*
|
|
1358
|
+
* Examples (with default healthyBacklog=20):
|
|
1359
|
+
* - 10 due reviews → 0.00 (healthy)
|
|
1360
|
+
* - 20 due reviews → 0.00 (at threshold)
|
|
1361
|
+
* - 40 due reviews → 0.25 (2x threshold)
|
|
1362
|
+
* - 60 due reviews → 0.50 (3x threshold, maxed)
|
|
1363
|
+
*
|
|
1364
|
+
* @param dueCount - Number of reviews currently due
|
|
1365
|
+
* @returns Backlog pressure score to add to urgency (0 to MAX_BACKLOG_PRESSURE)
|
|
1366
|
+
*/
|
|
1367
|
+
computeBacklogPressure(dueCount) {
|
|
1368
|
+
if (dueCount <= this.healthyBacklog) {
|
|
1369
|
+
return 0;
|
|
1370
|
+
}
|
|
1371
|
+
const excess = dueCount - this.healthyBacklog;
|
|
1372
|
+
const pressure = excess / this.healthyBacklog * (MAX_BACKLOG_PRESSURE / 2);
|
|
1373
|
+
return Math.min(MAX_BACKLOG_PRESSURE, pressure);
|
|
1374
|
+
}
|
|
1375
|
+
/**
|
|
1376
|
+
* Compute urgency score for a review card.
|
|
1377
|
+
*
|
|
1378
|
+
* Three factors:
|
|
1379
|
+
* 1. Relative overdueness = hoursOverdue / intervalHours
|
|
1380
|
+
* - 2 days overdue on 3-day interval = 0.67 (urgent)
|
|
1381
|
+
* - 2 days overdue on 180-day interval = 0.01 (not urgent)
|
|
1382
|
+
*
|
|
1383
|
+
* 2. Interval recency factor = 0.3 + 0.7 * exp(-intervalHours / 720)
|
|
1384
|
+
* - 24h interval → ~1.0 (very recent learning)
|
|
1385
|
+
* - 30 days (720h) → ~0.56
|
|
1386
|
+
* - 180 days → ~0.30
|
|
1387
|
+
*
|
|
1388
|
+
* 3. Backlog pressure = global boost when review backlog exceeds healthy threshold
|
|
1389
|
+
* - At healthy backlog: 0
|
|
1390
|
+
* - At 2x healthy: +0.25
|
|
1391
|
+
* - At 3x+ healthy: +0.50 (max)
|
|
1392
|
+
*
|
|
1393
|
+
* Combined: base 0.5 + (urgency factors * 0.45) + backlog pressure
|
|
1394
|
+
* Result range: 0.5 to 1.0 (uncapped to allow high-urgency reviews to compete with new cards)
|
|
1395
|
+
*
|
|
1396
|
+
* @param review - The scheduled card to score
|
|
1397
|
+
* @param now - Current time
|
|
1398
|
+
* @param backlogPressure - Pre-computed backlog pressure (0 to 0.5)
|
|
1399
|
+
*/
|
|
1400
|
+
computeUrgencyScore(review, now, backlogPressure) {
|
|
1401
|
+
const scheduledAt = moment3.utc(review.scheduledAt);
|
|
1402
|
+
const due = moment3.utc(review.reviewTime);
|
|
1403
|
+
const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
|
|
1404
|
+
const hoursOverdue = now.diff(due, "hours");
|
|
1405
|
+
const relativeOverdue = hoursOverdue / intervalHours;
|
|
1406
|
+
const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
|
|
1407
|
+
const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
|
|
1408
|
+
const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
|
|
1409
|
+
const baseScore = 0.5 + urgency * 0.45;
|
|
1410
|
+
const score = Math.min(1, baseScore + backlogPressure);
|
|
1411
|
+
const reasonParts = [
|
|
1412
|
+
`${Math.round(hoursOverdue)}h overdue`,
|
|
1413
|
+
`interval: ${Math.round(intervalHours)}h`,
|
|
1414
|
+
`relative: ${relativeOverdue.toFixed(2)}`,
|
|
1415
|
+
`recency: ${recencyFactor.toFixed(2)}`
|
|
1416
|
+
];
|
|
1417
|
+
if (backlogPressure > 0) {
|
|
1418
|
+
reasonParts.push(`backlog: +${backlogPressure.toFixed(2)}`);
|
|
1419
|
+
}
|
|
1420
|
+
reasonParts.push("review");
|
|
1421
|
+
const reason = reasonParts.join(", ");
|
|
1422
|
+
return { score, reason };
|
|
1423
|
+
}
|
|
1424
|
+
};
|
|
1425
|
+
}
|
|
1426
|
+
});
|
|
1427
|
+
|
|
1428
|
+
// src/core/navigators/generators/types.ts
|
|
1429
|
+
var types_exports = {};
|
|
1430
|
+
var init_types = __esm({
|
|
1431
|
+
"src/core/navigators/generators/types.ts"() {
|
|
1432
|
+
"use strict";
|
|
1433
|
+
}
|
|
1434
|
+
});
|
|
1435
|
+
|
|
1436
|
+
// import("./generators/**/*") in src/core/navigators/index.ts
|
|
1437
|
+
var globImport_generators;
|
|
1438
|
+
var init_ = __esm({
|
|
1439
|
+
'import("./generators/**/*") in src/core/navigators/index.ts'() {
|
|
1440
|
+
globImport_generators = __glob({
|
|
1441
|
+
"./generators/CompositeGenerator.ts": () => Promise.resolve().then(() => (init_CompositeGenerator(), CompositeGenerator_exports)),
|
|
1442
|
+
"./generators/elo.ts": () => Promise.resolve().then(() => (init_elo(), elo_exports)),
|
|
1443
|
+
"./generators/index.ts": () => Promise.resolve().then(() => (init_generators(), generators_exports)),
|
|
1444
|
+
"./generators/srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
|
|
1445
|
+
"./generators/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports))
|
|
1446
|
+
});
|
|
1447
|
+
}
|
|
1448
|
+
});
|
|
1449
|
+
|
|
1450
|
+
// src/core/types/contentNavigationStrategy.ts
|
|
1451
|
+
var DEFAULT_LEARNABLE_WEIGHT;
|
|
1452
|
+
var init_contentNavigationStrategy = __esm({
|
|
1453
|
+
"src/core/types/contentNavigationStrategy.ts"() {
|
|
1454
|
+
"use strict";
|
|
1455
|
+
DEFAULT_LEARNABLE_WEIGHT = {
|
|
1456
|
+
weight: 1,
|
|
1457
|
+
confidence: 0.1,
|
|
1458
|
+
// Low confidence initially = wide exploration
|
|
1459
|
+
sampleSize: 0
|
|
1460
|
+
};
|
|
1461
|
+
}
|
|
1462
|
+
});
|
|
1463
|
+
|
|
1464
|
+
// src/core/navigators/filters/WeightedFilter.ts
|
|
1465
|
+
var WeightedFilter_exports = {};
|
|
1466
|
+
__export(WeightedFilter_exports, {
|
|
1467
|
+
WeightedFilter: () => WeightedFilter
|
|
1468
|
+
});
|
|
1469
|
+
var WeightedFilter;
|
|
1470
|
+
var init_WeightedFilter = __esm({
|
|
1471
|
+
"src/core/navigators/filters/WeightedFilter.ts"() {
|
|
1472
|
+
"use strict";
|
|
1473
|
+
init_contentNavigationStrategy();
|
|
1474
|
+
WeightedFilter = class {
|
|
1475
|
+
name;
|
|
1476
|
+
inner;
|
|
1477
|
+
learnable;
|
|
1478
|
+
staticWeight;
|
|
1479
|
+
strategyId;
|
|
1480
|
+
constructor(inner, learnable = DEFAULT_LEARNABLE_WEIGHT, staticWeight = false, strategyId) {
|
|
1481
|
+
this.inner = inner;
|
|
1482
|
+
this.name = inner.name;
|
|
1483
|
+
this.learnable = learnable;
|
|
1484
|
+
this.staticWeight = staticWeight;
|
|
1485
|
+
this.strategyId = strategyId;
|
|
1486
|
+
}
|
|
1487
|
+
/**
|
|
1488
|
+
* Apply the inner filter, then scale its effect by the configured weight.
|
|
1489
|
+
*/
|
|
1490
|
+
async transform(cards, context) {
|
|
1491
|
+
let effectiveWeight = this.learnable.weight;
|
|
1492
|
+
let deviation;
|
|
1493
|
+
if (!this.staticWeight && context.orchestration) {
|
|
1494
|
+
const strategyId = this.strategyId || this.inner.strategyId || this.name;
|
|
1495
|
+
effectiveWeight = context.orchestration.getEffectiveWeight(strategyId, this.learnable);
|
|
1496
|
+
deviation = context.orchestration.getDeviation(strategyId);
|
|
1497
|
+
}
|
|
1498
|
+
if (Math.abs(effectiveWeight - 1) < 1e-3) {
|
|
1499
|
+
return this.inner.transform(cards, context);
|
|
1500
|
+
}
|
|
1501
|
+
const originalScores = /* @__PURE__ */ new Map();
|
|
1502
|
+
for (const card of cards) {
|
|
1503
|
+
originalScores.set(card.cardId, card.score);
|
|
1504
|
+
}
|
|
1505
|
+
const transformedCards = await this.inner.transform(cards, context);
|
|
1506
|
+
return transformedCards.map((card) => {
|
|
1507
|
+
const originalScore = originalScores.get(card.cardId);
|
|
1508
|
+
if (originalScore === void 0 || originalScore === 0 || card.score === 0) {
|
|
1509
|
+
return card;
|
|
1510
|
+
}
|
|
1511
|
+
const rawEffect = card.score / originalScore;
|
|
1512
|
+
if (Math.abs(rawEffect - 1) < 1e-4) {
|
|
1513
|
+
return card;
|
|
1514
|
+
}
|
|
1515
|
+
const weightedEffect = Math.pow(rawEffect, effectiveWeight);
|
|
1516
|
+
const newScore = originalScore * weightedEffect;
|
|
1517
|
+
const lastProvIndex = card.provenance.length - 1;
|
|
1518
|
+
const lastProv = card.provenance[lastProvIndex];
|
|
1519
|
+
if (lastProv) {
|
|
1520
|
+
const updatedProvenance = [...card.provenance];
|
|
1521
|
+
updatedProvenance[lastProvIndex] = {
|
|
1522
|
+
...lastProv,
|
|
1523
|
+
score: newScore,
|
|
1524
|
+
effectiveWeight,
|
|
1525
|
+
deviation
|
|
1526
|
+
// We can optionally append to the reason, but the structured field is key
|
|
1527
|
+
};
|
|
1528
|
+
return {
|
|
1529
|
+
...card,
|
|
1530
|
+
score: newScore,
|
|
1531
|
+
provenance: updatedProvenance
|
|
1532
|
+
};
|
|
1533
|
+
}
|
|
1534
|
+
return {
|
|
1535
|
+
...card,
|
|
1536
|
+
score: newScore
|
|
1537
|
+
};
|
|
1538
|
+
});
|
|
1539
|
+
}
|
|
1540
|
+
};
|
|
1541
|
+
}
|
|
1542
|
+
});
|
|
1543
|
+
|
|
1544
|
+
// src/core/navigators/filters/eloDistance.ts
|
|
1545
|
+
var eloDistance_exports = {};
|
|
1546
|
+
__export(eloDistance_exports, {
|
|
1547
|
+
DEFAULT_HALF_LIFE: () => DEFAULT_HALF_LIFE,
|
|
1548
|
+
DEFAULT_MAX_MULTIPLIER: () => DEFAULT_MAX_MULTIPLIER,
|
|
1549
|
+
DEFAULT_MIN_MULTIPLIER: () => DEFAULT_MIN_MULTIPLIER,
|
|
1550
|
+
createEloDistanceFilter: () => createEloDistanceFilter
|
|
1551
|
+
});
|
|
1552
|
+
function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
|
|
1553
|
+
const normalizedDistance = distance / halfLife;
|
|
1554
|
+
const decay = Math.exp(-(normalizedDistance * normalizedDistance));
|
|
1555
|
+
return minMultiplier + (maxMultiplier - minMultiplier) * decay;
|
|
1556
|
+
}
|
|
1557
|
+
function createEloDistanceFilter(config) {
|
|
1558
|
+
const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
|
|
1559
|
+
const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
|
|
1560
|
+
const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
|
|
1561
|
+
return {
|
|
1562
|
+
name: "ELO Distance Filter",
|
|
1563
|
+
async transform(cards, context) {
|
|
1564
|
+
const { course, userElo } = context;
|
|
1565
|
+
const cardIds = cards.map((c) => c.cardId);
|
|
1566
|
+
const cardElos = await course.getCardEloData(cardIds);
|
|
1567
|
+
return cards.map((card, i) => {
|
|
1568
|
+
const cardElo = cardElos[i]?.global?.score ?? 1e3;
|
|
1569
|
+
const distance = Math.abs(cardElo - userElo);
|
|
1570
|
+
const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
|
|
1571
|
+
const newScore = card.score * multiplier;
|
|
1572
|
+
const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
|
|
1573
|
+
return {
|
|
1574
|
+
...card,
|
|
1575
|
+
score: newScore,
|
|
1576
|
+
provenance: [
|
|
1577
|
+
...card.provenance,
|
|
1578
|
+
{
|
|
1579
|
+
strategy: "eloDistance",
|
|
1580
|
+
strategyName: "ELO Distance Filter",
|
|
1581
|
+
strategyId: "ELO_DISTANCE_FILTER",
|
|
1582
|
+
action,
|
|
1583
|
+
score: newScore,
|
|
1584
|
+
reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
|
|
1585
|
+
}
|
|
1586
|
+
]
|
|
1587
|
+
};
|
|
1588
|
+
});
|
|
1589
|
+
}
|
|
1590
|
+
};
|
|
1591
|
+
}
|
|
1592
|
+
var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
|
|
1593
|
+
var init_eloDistance = __esm({
|
|
1594
|
+
"src/core/navigators/filters/eloDistance.ts"() {
|
|
1595
|
+
"use strict";
|
|
1596
|
+
DEFAULT_HALF_LIFE = 200;
|
|
1597
|
+
DEFAULT_MIN_MULTIPLIER = 0.3;
|
|
1598
|
+
DEFAULT_MAX_MULTIPLIER = 1;
|
|
1599
|
+
}
|
|
1600
|
+
});
|
|
1601
|
+
|
|
1602
|
+
// src/core/navigators/filters/hierarchyDefinition.ts
|
|
1603
|
+
var hierarchyDefinition_exports = {};
|
|
1604
|
+
__export(hierarchyDefinition_exports, {
|
|
1605
|
+
default: () => HierarchyDefinitionNavigator
|
|
1606
|
+
});
|
|
1607
|
+
import { toCourseElo as toCourseElo3 } from "@vue-skuilder/common";
|
|
1608
|
+
var DEFAULT_MIN_COUNT, HierarchyDefinitionNavigator;
|
|
1609
|
+
var init_hierarchyDefinition = __esm({
|
|
1610
|
+
"src/core/navigators/filters/hierarchyDefinition.ts"() {
|
|
1611
|
+
"use strict";
|
|
1612
|
+
init_navigators();
|
|
1613
|
+
DEFAULT_MIN_COUNT = 3;
|
|
1614
|
+
HierarchyDefinitionNavigator = class extends ContentNavigator {
|
|
1615
|
+
config;
|
|
1616
|
+
/** Human-readable name for CardFilter interface */
|
|
1617
|
+
name;
|
|
1618
|
+
constructor(user, course, strategyData) {
|
|
1619
|
+
super(user, course, strategyData);
|
|
1620
|
+
this.config = this.parseConfig(strategyData.serializedData);
|
|
1621
|
+
this.name = strategyData.name || "Hierarchy Definition";
|
|
1622
|
+
}
|
|
1623
|
+
parseConfig(serializedData) {
|
|
1624
|
+
try {
|
|
1625
|
+
const parsed = JSON.parse(serializedData);
|
|
1626
|
+
return {
|
|
1627
|
+
prerequisites: parsed.prerequisites || {}
|
|
1628
|
+
};
|
|
1629
|
+
} catch {
|
|
1630
|
+
return {
|
|
1631
|
+
prerequisites: {}
|
|
1632
|
+
};
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
/**
|
|
1636
|
+
* Check if a specific prerequisite is satisfied
|
|
1637
|
+
*/
|
|
1638
|
+
isPrerequisiteMet(prereq, userTagElo, userGlobalElo) {
|
|
1639
|
+
if (!userTagElo) return false;
|
|
1640
|
+
const minCount = prereq.masteryThreshold?.minCount ?? DEFAULT_MIN_COUNT;
|
|
1641
|
+
if (userTagElo.count < minCount) return false;
|
|
1642
|
+
if (prereq.masteryThreshold?.minElo !== void 0) {
|
|
1643
|
+
return userTagElo.score >= prereq.masteryThreshold.minElo;
|
|
1644
|
+
} else {
|
|
1645
|
+
return userTagElo.score >= userGlobalElo;
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
/**
|
|
1649
|
+
* Get the set of tags the user has mastered.
|
|
1650
|
+
* A tag is "mastered" if it appears as a prerequisite somewhere and meets its threshold.
|
|
1651
|
+
*/
|
|
1652
|
+
async getMasteredTags(context) {
|
|
1653
|
+
const mastered = /* @__PURE__ */ new Set();
|
|
1654
|
+
try {
|
|
1655
|
+
const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
|
|
1656
|
+
const userElo = toCourseElo3(courseReg.elo);
|
|
1657
|
+
for (const prereqs of Object.values(this.config.prerequisites)) {
|
|
1658
|
+
for (const prereq of prereqs) {
|
|
1659
|
+
const tagElo = userElo.tags[prereq.tag];
|
|
1660
|
+
if (this.isPrerequisiteMet(prereq, tagElo, userElo.global.score)) {
|
|
1661
|
+
mastered.add(prereq.tag);
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
} catch {
|
|
1666
|
+
}
|
|
1667
|
+
return mastered;
|
|
1668
|
+
}
|
|
1669
|
+
/**
|
|
1670
|
+
* Get the set of tags that are unlocked (prerequisites met)
|
|
1671
|
+
*/
|
|
1672
|
+
getUnlockedTags(masteredTags) {
|
|
1673
|
+
const unlocked = /* @__PURE__ */ new Set();
|
|
1674
|
+
for (const [tagId, prereqs] of Object.entries(this.config.prerequisites)) {
|
|
1675
|
+
const allPrereqsMet = prereqs.every((prereq) => masteredTags.has(prereq.tag));
|
|
1676
|
+
if (allPrereqsMet) {
|
|
1677
|
+
unlocked.add(tagId);
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
return unlocked;
|
|
1681
|
+
}
|
|
1682
|
+
/**
|
|
1683
|
+
* Check if a tag has prerequisites defined in config
|
|
1684
|
+
*/
|
|
1685
|
+
hasPrerequisites(tagId) {
|
|
1686
|
+
return tagId in this.config.prerequisites;
|
|
1687
|
+
}
|
|
1688
|
+
/**
|
|
1689
|
+
* Check if a card is unlocked and generate reason.
|
|
1690
|
+
*/
|
|
1691
|
+
async checkCardUnlock(card, _course, unlockedTags, masteredTags) {
|
|
1692
|
+
try {
|
|
1693
|
+
const cardTags = card.tags ?? [];
|
|
1694
|
+
const lockedTags = cardTags.filter(
|
|
1695
|
+
(tag) => this.hasPrerequisites(tag) && !unlockedTags.has(tag)
|
|
1696
|
+
);
|
|
1697
|
+
if (lockedTags.length === 0) {
|
|
1698
|
+
const tagList = cardTags.length > 0 ? cardTags.join(", ") : "none";
|
|
1699
|
+
return {
|
|
1700
|
+
isUnlocked: true,
|
|
1701
|
+
reason: `Prerequisites met, tags: ${tagList}`
|
|
1702
|
+
};
|
|
1703
|
+
}
|
|
1704
|
+
const missingPrereqs = lockedTags.flatMap((tag) => {
|
|
1705
|
+
const prereqs = this.config.prerequisites[tag] || [];
|
|
1706
|
+
return prereqs.filter((p) => !masteredTags.has(p.tag)).map((p) => p.tag);
|
|
1707
|
+
});
|
|
1708
|
+
return {
|
|
1709
|
+
isUnlocked: false,
|
|
1710
|
+
reason: `Blocked: missing prerequisites ${missingPrereqs.join(", ")} for tags ${lockedTags.join(", ")}`
|
|
1711
|
+
};
|
|
1712
|
+
} catch {
|
|
1713
|
+
return {
|
|
1714
|
+
isUnlocked: true,
|
|
1715
|
+
reason: "Prerequisites check skipped (tag lookup failed)"
|
|
1716
|
+
};
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
/**
|
|
1720
|
+
* CardFilter.transform implementation.
|
|
1721
|
+
*
|
|
1722
|
+
* Apply prerequisite gating to cards. Cards with locked tags receive score: 0.
|
|
1723
|
+
*/
|
|
1724
|
+
async transform(cards, context) {
|
|
1725
|
+
const masteredTags = await this.getMasteredTags(context);
|
|
1726
|
+
const unlockedTags = this.getUnlockedTags(masteredTags);
|
|
1727
|
+
const gated = [];
|
|
1728
|
+
for (const card of cards) {
|
|
1729
|
+
const { isUnlocked, reason } = await this.checkCardUnlock(
|
|
1730
|
+
card,
|
|
1731
|
+
context.course,
|
|
1732
|
+
unlockedTags,
|
|
1733
|
+
masteredTags
|
|
1734
|
+
);
|
|
1735
|
+
const finalScore = isUnlocked ? card.score : 0;
|
|
1736
|
+
const action = isUnlocked ? "passed" : "penalized";
|
|
1737
|
+
gated.push({
|
|
1738
|
+
...card,
|
|
1739
|
+
score: finalScore,
|
|
1740
|
+
provenance: [
|
|
1741
|
+
...card.provenance,
|
|
1742
|
+
{
|
|
1743
|
+
strategy: "hierarchyDefinition",
|
|
1744
|
+
strategyName: this.strategyName || this.name,
|
|
1745
|
+
strategyId: this.strategyId || "NAVIGATION_STRATEGY-hierarchy",
|
|
1746
|
+
action,
|
|
1747
|
+
score: finalScore,
|
|
1748
|
+
reason
|
|
1749
|
+
}
|
|
1750
|
+
]
|
|
1751
|
+
});
|
|
1752
|
+
}
|
|
1753
|
+
return gated;
|
|
1754
|
+
}
|
|
1755
|
+
/**
|
|
1756
|
+
* Legacy getWeightedCards - now throws as filters should not be used as generators.
|
|
1757
|
+
*
|
|
1758
|
+
* Use transform() via Pipeline instead.
|
|
1759
|
+
*/
|
|
1760
|
+
async getWeightedCards(_limit) {
|
|
1761
|
+
throw new Error(
|
|
1762
|
+
"HierarchyDefinitionNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
|
|
1763
|
+
);
|
|
1764
|
+
}
|
|
1765
|
+
};
|
|
1766
|
+
}
|
|
1767
|
+
});
|
|
1768
|
+
|
|
1769
|
+
// src/core/navigators/filters/userTagPreference.ts
|
|
1770
|
+
var userTagPreference_exports = {};
|
|
1771
|
+
__export(userTagPreference_exports, {
|
|
1772
|
+
default: () => UserTagPreferenceFilter
|
|
1773
|
+
});
|
|
1774
|
+
var UserTagPreferenceFilter;
|
|
1775
|
+
var init_userTagPreference = __esm({
|
|
1776
|
+
"src/core/navigators/filters/userTagPreference.ts"() {
|
|
1777
|
+
"use strict";
|
|
1778
|
+
init_navigators();
|
|
1779
|
+
UserTagPreferenceFilter = class extends ContentNavigator {
|
|
1780
|
+
_strategyData;
|
|
1781
|
+
/** Human-readable name for CardFilter interface */
|
|
1782
|
+
name;
|
|
1783
|
+
constructor(user, course, strategyData) {
|
|
1784
|
+
super(user, course, strategyData);
|
|
1785
|
+
this._strategyData = strategyData;
|
|
1786
|
+
this.name = strategyData.name || "User Tag Preferences";
|
|
1787
|
+
}
|
|
1788
|
+
/**
|
|
1789
|
+
* Compute multiplier for a card based on its tags and user preferences.
|
|
1790
|
+
* Returns the maximum multiplier among all matching tags, or 1.0 if no matches.
|
|
1791
|
+
*/
|
|
1792
|
+
computeMultiplier(cardTags, boostMap) {
|
|
1793
|
+
const multipliers = cardTags.map((tag) => boostMap[tag]).filter((val) => val !== void 0);
|
|
1794
|
+
if (multipliers.length === 0) {
|
|
1795
|
+
return 1;
|
|
1796
|
+
}
|
|
1797
|
+
return Math.max(...multipliers);
|
|
1798
|
+
}
|
|
1799
|
+
/**
|
|
1800
|
+
* Build human-readable reason for the filter's decision.
|
|
1801
|
+
*/
|
|
1802
|
+
buildReason(cardTags, boostMap, multiplier) {
|
|
1803
|
+
const matchingTags = cardTags.filter((tag) => boostMap[tag] === multiplier);
|
|
1804
|
+
if (multiplier === 0) {
|
|
1805
|
+
return `Excluded by user preference: ${matchingTags.join(", ")} (${multiplier}x)`;
|
|
1806
|
+
}
|
|
1807
|
+
if (multiplier < 1) {
|
|
1808
|
+
return `Penalized by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
|
|
1809
|
+
}
|
|
1810
|
+
if (multiplier > 1) {
|
|
1811
|
+
return `Boosted by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
|
|
1812
|
+
}
|
|
1813
|
+
return "No matching user preferences";
|
|
1814
|
+
}
|
|
1815
|
+
/**
|
|
1816
|
+
* CardFilter.transform implementation.
|
|
1817
|
+
*
|
|
1818
|
+
* Apply user tag preferences:
|
|
1819
|
+
* 1. Read preferences from strategy state
|
|
1820
|
+
* 2. If no preferences, pass through unchanged
|
|
1821
|
+
* 3. For each card:
|
|
1822
|
+
* - Look up tag in boost record
|
|
1823
|
+
* - If tag found: apply multiplier (0 = exclude, 1 = neutral, >1 = boost)
|
|
1824
|
+
* - If multiple tags match: use max multiplier
|
|
1825
|
+
* - Append provenance with clear reason
|
|
1826
|
+
*/
|
|
1827
|
+
async transform(cards, _context) {
|
|
1828
|
+
const prefs = await this.getStrategyState();
|
|
1829
|
+
if (!prefs || Object.keys(prefs.boost).length === 0) {
|
|
1830
|
+
return cards.map((card) => ({
|
|
1831
|
+
...card,
|
|
1832
|
+
provenance: [
|
|
1833
|
+
...card.provenance,
|
|
1834
|
+
{
|
|
1835
|
+
strategy: "userTagPreference",
|
|
1836
|
+
strategyName: this.strategyName || this.name,
|
|
1837
|
+
strategyId: this.strategyId || this._strategyData._id,
|
|
1838
|
+
action: "passed",
|
|
1839
|
+
score: card.score,
|
|
1840
|
+
reason: "No user tag preferences configured"
|
|
1841
|
+
}
|
|
1842
|
+
]
|
|
1843
|
+
}));
|
|
1844
|
+
}
|
|
1845
|
+
const adjusted = await Promise.all(
|
|
1846
|
+
cards.map(async (card) => {
|
|
1847
|
+
const cardTags = card.tags ?? [];
|
|
1848
|
+
const multiplier = this.computeMultiplier(cardTags, prefs.boost);
|
|
1849
|
+
const finalScore = Math.min(1, card.score * multiplier);
|
|
1850
|
+
let action;
|
|
1851
|
+
if (multiplier === 0 || multiplier < 1) {
|
|
1852
|
+
action = "penalized";
|
|
1853
|
+
} else if (multiplier > 1) {
|
|
1854
|
+
action = "boosted";
|
|
1855
|
+
} else {
|
|
1856
|
+
action = "passed";
|
|
1857
|
+
}
|
|
1858
|
+
return {
|
|
1859
|
+
...card,
|
|
1860
|
+
score: finalScore,
|
|
1861
|
+
provenance: [
|
|
1862
|
+
...card.provenance,
|
|
1863
|
+
{
|
|
1864
|
+
strategy: "userTagPreference",
|
|
1865
|
+
strategyName: this.strategyName || this.name,
|
|
1866
|
+
strategyId: this.strategyId || this._strategyData._id,
|
|
1867
|
+
action,
|
|
1868
|
+
score: finalScore,
|
|
1869
|
+
reason: this.buildReason(cardTags, prefs.boost, multiplier)
|
|
1870
|
+
}
|
|
1871
|
+
]
|
|
1872
|
+
};
|
|
1873
|
+
})
|
|
1874
|
+
);
|
|
1875
|
+
return adjusted;
|
|
1876
|
+
}
|
|
1877
|
+
/**
|
|
1878
|
+
* Legacy getWeightedCards - throws as filters should not be used as generators.
|
|
1879
|
+
*/
|
|
1880
|
+
async getWeightedCards(_limit) {
|
|
1881
|
+
throw new Error(
|
|
1882
|
+
"UserTagPreferenceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
|
|
1883
|
+
);
|
|
1884
|
+
}
|
|
1885
|
+
};
|
|
1886
|
+
}
|
|
1887
|
+
});
|
|
1888
|
+
|
|
1889
|
+
// src/core/navigators/filters/index.ts
|
|
1890
|
+
var filters_exports = {};
|
|
1891
|
+
__export(filters_exports, {
|
|
1892
|
+
UserTagPreferenceFilter: () => UserTagPreferenceFilter,
|
|
1893
|
+
createEloDistanceFilter: () => createEloDistanceFilter
|
|
1894
|
+
});
|
|
1895
|
+
var init_filters = __esm({
|
|
1896
|
+
"src/core/navigators/filters/index.ts"() {
|
|
1897
|
+
"use strict";
|
|
1898
|
+
init_eloDistance();
|
|
1899
|
+
init_userTagPreference();
|
|
1900
|
+
}
|
|
1901
|
+
});
|
|
1902
|
+
|
|
1903
|
+
// src/core/navigators/filters/inferredPreferenceStub.ts
|
|
1904
|
+
var inferredPreferenceStub_exports = {};
|
|
1905
|
+
__export(inferredPreferenceStub_exports, {
|
|
1906
|
+
INFERRED_PREFERENCE_NAVIGATOR_STUB: () => INFERRED_PREFERENCE_NAVIGATOR_STUB
|
|
1907
|
+
});
|
|
1908
|
+
var INFERRED_PREFERENCE_NAVIGATOR_STUB;
|
|
1909
|
+
var init_inferredPreferenceStub = __esm({
|
|
1910
|
+
"src/core/navigators/filters/inferredPreferenceStub.ts"() {
|
|
1911
|
+
"use strict";
|
|
1912
|
+
INFERRED_PREFERENCE_NAVIGATOR_STUB = true;
|
|
1913
|
+
}
|
|
1914
|
+
});
|
|
1915
|
+
|
|
1916
|
+
// src/core/navigators/filters/interferenceMitigator.ts
|
|
1917
|
+
var interferenceMitigator_exports = {};
|
|
1918
|
+
__export(interferenceMitigator_exports, {
|
|
1919
|
+
default: () => InterferenceMitigatorNavigator
|
|
1920
|
+
});
|
|
1921
|
+
import { toCourseElo as toCourseElo4 } from "@vue-skuilder/common";
|
|
1922
|
+
var DEFAULT_MIN_COUNT2, DEFAULT_MIN_ELAPSED_DAYS, DEFAULT_INTERFERENCE_DECAY, InterferenceMitigatorNavigator;
|
|
1923
|
+
var init_interferenceMitigator = __esm({
|
|
1924
|
+
"src/core/navigators/filters/interferenceMitigator.ts"() {
|
|
1925
|
+
"use strict";
|
|
1926
|
+
init_navigators();
|
|
1927
|
+
DEFAULT_MIN_COUNT2 = 10;
|
|
1928
|
+
DEFAULT_MIN_ELAPSED_DAYS = 3;
|
|
1929
|
+
DEFAULT_INTERFERENCE_DECAY = 0.8;
|
|
1930
|
+
InterferenceMitigatorNavigator = class extends ContentNavigator {
|
|
1931
|
+
config;
|
|
1932
|
+
/** Human-readable name for CardFilter interface */
|
|
1933
|
+
name;
|
|
1934
|
+
/** Precomputed map: tag -> set of { partner, decay } it interferes with */
|
|
1935
|
+
interferenceMap;
|
|
1936
|
+
constructor(user, course, strategyData) {
|
|
1937
|
+
super(user, course, strategyData);
|
|
1938
|
+
this.config = this.parseConfig(strategyData.serializedData);
|
|
1939
|
+
this.interferenceMap = this.buildInterferenceMap();
|
|
1940
|
+
this.name = strategyData.name || "Interference Mitigator";
|
|
1941
|
+
}
|
|
1942
|
+
parseConfig(serializedData) {
|
|
1943
|
+
try {
|
|
1944
|
+
const parsed = JSON.parse(serializedData);
|
|
1945
|
+
let sets = parsed.interferenceSets || [];
|
|
1946
|
+
if (sets.length > 0 && Array.isArray(sets[0])) {
|
|
1947
|
+
sets = sets.map((tags) => ({ tags }));
|
|
1948
|
+
}
|
|
1949
|
+
return {
|
|
1950
|
+
interferenceSets: sets,
|
|
1951
|
+
maturityThreshold: {
|
|
1952
|
+
minCount: parsed.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2,
|
|
1953
|
+
minElo: parsed.maturityThreshold?.minElo,
|
|
1954
|
+
minElapsedDays: parsed.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS
|
|
1955
|
+
},
|
|
1956
|
+
defaultDecay: parsed.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY
|
|
1957
|
+
};
|
|
1958
|
+
} catch {
|
|
1959
|
+
return {
|
|
1960
|
+
interferenceSets: [],
|
|
1961
|
+
maturityThreshold: {
|
|
1962
|
+
minCount: DEFAULT_MIN_COUNT2,
|
|
1963
|
+
minElapsedDays: DEFAULT_MIN_ELAPSED_DAYS
|
|
1964
|
+
},
|
|
1965
|
+
defaultDecay: DEFAULT_INTERFERENCE_DECAY
|
|
1966
|
+
};
|
|
1967
|
+
}
|
|
1968
|
+
}
|
|
1969
|
+
/**
|
|
1970
|
+
* Build a map from each tag to its interference partners with decay coefficients.
|
|
1971
|
+
* If tags A, B, C are in an interference group with decay 0.8, then:
|
|
1972
|
+
* - A interferes with B (decay 0.8) and C (decay 0.8)
|
|
1973
|
+
* - B interferes with A (decay 0.8) and C (decay 0.8)
|
|
1974
|
+
* - etc.
|
|
1975
|
+
*/
|
|
1976
|
+
buildInterferenceMap() {
|
|
1977
|
+
const map = /* @__PURE__ */ new Map();
|
|
1978
|
+
for (const group of this.config.interferenceSets) {
|
|
1979
|
+
const decay = group.decay ?? this.config.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY;
|
|
1980
|
+
for (const tag of group.tags) {
|
|
1981
|
+
if (!map.has(tag)) {
|
|
1982
|
+
map.set(tag, []);
|
|
1983
|
+
}
|
|
1984
|
+
const partners = map.get(tag);
|
|
1985
|
+
for (const other of group.tags) {
|
|
1986
|
+
if (other !== tag) {
|
|
1987
|
+
const existing = partners.find((p) => p.partner === other);
|
|
1988
|
+
if (existing) {
|
|
1989
|
+
existing.decay = Math.max(existing.decay, decay);
|
|
1990
|
+
} else {
|
|
1991
|
+
partners.push({ partner: other, decay });
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
}
|
|
1995
|
+
}
|
|
1996
|
+
}
|
|
1997
|
+
return map;
|
|
1998
|
+
}
|
|
1999
|
+
/**
|
|
2000
|
+
* Get the set of tags that are currently immature for this user.
|
|
2001
|
+
* A tag is immature if the user has interacted with it but hasn't
|
|
2002
|
+
* reached the maturity threshold.
|
|
2003
|
+
*/
|
|
2004
|
+
async getImmatureTags(context) {
|
|
2005
|
+
const immature = /* @__PURE__ */ new Set();
|
|
2006
|
+
try {
|
|
2007
|
+
const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
|
|
2008
|
+
const userElo = toCourseElo4(courseReg.elo);
|
|
2009
|
+
const minCount = this.config.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2;
|
|
2010
|
+
const minElo = this.config.maturityThreshold?.minElo;
|
|
2011
|
+
const minElapsedDays = this.config.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS;
|
|
2012
|
+
const minCountForElapsed = minElapsedDays * 2;
|
|
2013
|
+
for (const [tagId, tagElo] of Object.entries(userElo.tags)) {
|
|
2014
|
+
if (tagElo.count === 0) continue;
|
|
2015
|
+
const belowCount = tagElo.count < minCount;
|
|
2016
|
+
const belowElo = minElo !== void 0 && tagElo.score < minElo;
|
|
2017
|
+
const belowElapsed = tagElo.count < minCountForElapsed;
|
|
2018
|
+
if (belowCount || belowElo || belowElapsed) {
|
|
2019
|
+
immature.add(tagId);
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
} catch {
|
|
2023
|
+
}
|
|
2024
|
+
return immature;
|
|
2025
|
+
}
|
|
2026
|
+
/**
|
|
2027
|
+
* Get all tags that interfere with any immature tag, along with their decay coefficients.
|
|
2028
|
+
* These are the tags we want to avoid introducing.
|
|
2029
|
+
*/
|
|
2030
|
+
getTagsToAvoid(immatureTags) {
|
|
2031
|
+
const avoid = /* @__PURE__ */ new Map();
|
|
2032
|
+
for (const immatureTag of immatureTags) {
|
|
2033
|
+
const partners = this.interferenceMap.get(immatureTag);
|
|
2034
|
+
if (partners) {
|
|
2035
|
+
for (const { partner, decay } of partners) {
|
|
2036
|
+
if (!immatureTags.has(partner)) {
|
|
2037
|
+
const existing = avoid.get(partner) ?? 0;
|
|
2038
|
+
avoid.set(partner, Math.max(existing, decay));
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
}
|
|
2043
|
+
return avoid;
|
|
2044
|
+
}
|
|
2045
|
+
/**
|
|
2046
|
+
* Compute interference score reduction for a card.
|
|
2047
|
+
* Returns: { multiplier, interfering tags, reason }
|
|
2048
|
+
*/
|
|
2049
|
+
computeInterferenceEffect(cardTags, tagsToAvoid, immatureTags) {
|
|
2050
|
+
if (tagsToAvoid.size === 0) {
|
|
2051
|
+
return {
|
|
2052
|
+
multiplier: 1,
|
|
2053
|
+
interferingTags: [],
|
|
2054
|
+
reason: "No interference detected"
|
|
2055
|
+
};
|
|
2056
|
+
}
|
|
2057
|
+
let multiplier = 1;
|
|
2058
|
+
const interferingTags = [];
|
|
2059
|
+
for (const tag of cardTags) {
|
|
2060
|
+
const decay = tagsToAvoid.get(tag);
|
|
2061
|
+
if (decay !== void 0) {
|
|
2062
|
+
interferingTags.push(tag);
|
|
2063
|
+
multiplier *= 1 - decay;
|
|
2064
|
+
}
|
|
2065
|
+
}
|
|
2066
|
+
if (interferingTags.length === 0) {
|
|
2067
|
+
return {
|
|
2068
|
+
multiplier: 1,
|
|
2069
|
+
interferingTags: [],
|
|
2070
|
+
reason: "No interference detected"
|
|
2071
|
+
};
|
|
2072
|
+
}
|
|
2073
|
+
const causingTags = /* @__PURE__ */ new Set();
|
|
2074
|
+
for (const tag of interferingTags) {
|
|
2075
|
+
for (const immatureTag of immatureTags) {
|
|
2076
|
+
const partners = this.interferenceMap.get(immatureTag);
|
|
2077
|
+
if (partners?.some((p) => p.partner === tag)) {
|
|
2078
|
+
causingTags.add(immatureTag);
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
2081
|
+
}
|
|
2082
|
+
const reason = `Interferes with immature tags ${Array.from(causingTags).join(", ")} (tags: ${interferingTags.join(", ")}, multiplier: ${multiplier.toFixed(2)})`;
|
|
2083
|
+
return { multiplier, interferingTags, reason };
|
|
2084
|
+
}
|
|
2085
|
+
/**
|
|
2086
|
+
* CardFilter.transform implementation.
|
|
2087
|
+
*
|
|
2088
|
+
* Apply interference-aware scoring. Cards with tags that interfere with
|
|
2089
|
+
* immature learnings get reduced scores.
|
|
2090
|
+
*/
|
|
2091
|
+
async transform(cards, context) {
|
|
2092
|
+
const immatureTags = await this.getImmatureTags(context);
|
|
2093
|
+
const tagsToAvoid = this.getTagsToAvoid(immatureTags);
|
|
2094
|
+
const adjusted = [];
|
|
2095
|
+
for (const card of cards) {
|
|
2096
|
+
const cardTags = card.tags ?? [];
|
|
2097
|
+
const { multiplier, reason } = this.computeInterferenceEffect(
|
|
2098
|
+
cardTags,
|
|
2099
|
+
tagsToAvoid,
|
|
2100
|
+
immatureTags
|
|
2101
|
+
);
|
|
2102
|
+
const finalScore = card.score * multiplier;
|
|
2103
|
+
const action = multiplier < 1 ? "penalized" : multiplier > 1 ? "boosted" : "passed";
|
|
2104
|
+
adjusted.push({
|
|
2105
|
+
...card,
|
|
2106
|
+
score: finalScore,
|
|
2107
|
+
provenance: [
|
|
2108
|
+
...card.provenance,
|
|
2109
|
+
{
|
|
2110
|
+
strategy: "interferenceMitigator",
|
|
2111
|
+
strategyName: this.strategyName || this.name,
|
|
2112
|
+
strategyId: this.strategyId || "NAVIGATION_STRATEGY-interference",
|
|
2113
|
+
action,
|
|
2114
|
+
score: finalScore,
|
|
2115
|
+
reason
|
|
2116
|
+
}
|
|
2117
|
+
]
|
|
2118
|
+
});
|
|
2119
|
+
}
|
|
2120
|
+
return adjusted;
|
|
2121
|
+
}
|
|
2122
|
+
/**
|
|
2123
|
+
* Legacy getWeightedCards - now throws as filters should not be used as generators.
|
|
2124
|
+
*
|
|
2125
|
+
* Use transform() via Pipeline instead.
|
|
2126
|
+
*/
|
|
2127
|
+
async getWeightedCards(_limit) {
|
|
2128
|
+
throw new Error(
|
|
2129
|
+
"InterferenceMitigatorNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
|
|
2130
|
+
);
|
|
2131
|
+
}
|
|
2132
|
+
};
|
|
2133
|
+
}
|
|
2134
|
+
});
|
|
2135
|
+
|
|
2136
|
+
// src/core/navigators/filters/relativePriority.ts
|
|
2137
|
+
var relativePriority_exports = {};
|
|
2138
|
+
__export(relativePriority_exports, {
|
|
2139
|
+
default: () => RelativePriorityNavigator
|
|
2140
|
+
});
|
|
2141
|
+
var DEFAULT_PRIORITY, DEFAULT_PRIORITY_INFLUENCE, DEFAULT_COMBINE_MODE, RelativePriorityNavigator;
|
|
2142
|
+
var init_relativePriority = __esm({
|
|
2143
|
+
"src/core/navigators/filters/relativePriority.ts"() {
|
|
2144
|
+
"use strict";
|
|
2145
|
+
init_navigators();
|
|
2146
|
+
DEFAULT_PRIORITY = 0.5;
|
|
2147
|
+
DEFAULT_PRIORITY_INFLUENCE = 0.5;
|
|
2148
|
+
DEFAULT_COMBINE_MODE = "max";
|
|
2149
|
+
RelativePriorityNavigator = class extends ContentNavigator {
|
|
2150
|
+
config;
|
|
2151
|
+
/** Human-readable name for CardFilter interface */
|
|
2152
|
+
name;
|
|
2153
|
+
constructor(user, course, strategyData) {
|
|
2154
|
+
super(user, course, strategyData);
|
|
2155
|
+
this.config = this.parseConfig(strategyData.serializedData);
|
|
2156
|
+
this.name = strategyData.name || "Relative Priority";
|
|
2157
|
+
}
|
|
2158
|
+
parseConfig(serializedData) {
|
|
2159
|
+
try {
|
|
2160
|
+
const parsed = JSON.parse(serializedData);
|
|
2161
|
+
return {
|
|
2162
|
+
tagPriorities: parsed.tagPriorities || {},
|
|
2163
|
+
defaultPriority: parsed.defaultPriority ?? DEFAULT_PRIORITY,
|
|
2164
|
+
combineMode: parsed.combineMode ?? DEFAULT_COMBINE_MODE,
|
|
2165
|
+
priorityInfluence: parsed.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE
|
|
2166
|
+
};
|
|
2167
|
+
} catch {
|
|
2168
|
+
return {
|
|
2169
|
+
tagPriorities: {},
|
|
2170
|
+
defaultPriority: DEFAULT_PRIORITY,
|
|
2171
|
+
combineMode: DEFAULT_COMBINE_MODE,
|
|
2172
|
+
priorityInfluence: DEFAULT_PRIORITY_INFLUENCE
|
|
2173
|
+
};
|
|
2174
|
+
}
|
|
2175
|
+
}
|
|
2176
|
+
/**
|
|
2177
|
+
* Look up the priority for a tag.
|
|
2178
|
+
*/
|
|
2179
|
+
getTagPriority(tagId) {
|
|
2180
|
+
return this.config.tagPriorities[tagId] ?? this.config.defaultPriority ?? DEFAULT_PRIORITY;
|
|
2181
|
+
}
|
|
2182
|
+
/**
|
|
2183
|
+
* Compute combined priority for a card based on its tags.
|
|
2184
|
+
*/
|
|
2185
|
+
computeCardPriority(cardTags) {
|
|
2186
|
+
if (cardTags.length === 0) {
|
|
2187
|
+
return this.config.defaultPriority ?? DEFAULT_PRIORITY;
|
|
2188
|
+
}
|
|
2189
|
+
const priorities = cardTags.map((tag) => this.getTagPriority(tag));
|
|
2190
|
+
switch (this.config.combineMode) {
|
|
2191
|
+
case "max":
|
|
2192
|
+
return Math.max(...priorities);
|
|
2193
|
+
case "min":
|
|
2194
|
+
return Math.min(...priorities);
|
|
2195
|
+
case "average":
|
|
2196
|
+
return priorities.reduce((sum, p) => sum + p, 0) / priorities.length;
|
|
2197
|
+
default:
|
|
2198
|
+
return Math.max(...priorities);
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
/**
|
|
2202
|
+
* Compute boost factor based on priority.
|
|
2203
|
+
*
|
|
2204
|
+
* The formula: 1 + (priority - 0.5) * priorityInfluence
|
|
2205
|
+
*
|
|
2206
|
+
* This creates a multiplier centered around 1.0:
|
|
2207
|
+
* - Priority 1.0 with influence 0.5 → 1.25 (25% boost)
|
|
2208
|
+
* - Priority 0.5 with any influence → 1.00 (neutral)
|
|
2209
|
+
* - Priority 0.0 with influence 0.5 → 0.75 (25% reduction)
|
|
2210
|
+
*/
|
|
2211
|
+
computeBoostFactor(priority) {
|
|
2212
|
+
const influence = this.config.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE;
|
|
2213
|
+
return 1 + (priority - 0.5) * influence;
|
|
2214
|
+
}
|
|
2215
|
+
/**
|
|
2216
|
+
* Build human-readable reason for priority adjustment.
|
|
2217
|
+
*/
|
|
2218
|
+
buildPriorityReason(cardTags, priority, boostFactor, finalScore) {
|
|
2219
|
+
if (cardTags.length === 0) {
|
|
2220
|
+
return `No tags, neutral priority (${priority.toFixed(2)})`;
|
|
2221
|
+
}
|
|
2222
|
+
const tagList = cardTags.slice(0, 3).join(", ");
|
|
2223
|
+
const more = cardTags.length > 3 ? ` (+${cardTags.length - 3} more)` : "";
|
|
2224
|
+
if (boostFactor === 1) {
|
|
2225
|
+
return `Neutral priority (${priority.toFixed(2)}) for tags: ${tagList}${more}`;
|
|
2226
|
+
} else if (boostFactor > 1) {
|
|
2227
|
+
return `High-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 boost ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
|
|
2228
|
+
} else {
|
|
2229
|
+
return `Low-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 reduce ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
|
|
2230
|
+
}
|
|
2231
|
+
}
|
|
2232
|
+
/**
|
|
2233
|
+
* CardFilter.transform implementation.
|
|
2234
|
+
*
|
|
2235
|
+
* Apply priority-adjusted scoring. Cards with high-priority tags get boosted,
|
|
2236
|
+
* cards with low-priority tags get reduced scores.
|
|
2237
|
+
*/
|
|
2238
|
+
async transform(cards, _context) {
|
|
2239
|
+
const adjusted = await Promise.all(
|
|
2240
|
+
cards.map(async (card) => {
|
|
2241
|
+
const cardTags = card.tags ?? [];
|
|
2242
|
+
const priority = this.computeCardPriority(cardTags);
|
|
2243
|
+
const boostFactor = this.computeBoostFactor(priority);
|
|
2244
|
+
const finalScore = Math.max(0, Math.min(1, card.score * boostFactor));
|
|
2245
|
+
const action = boostFactor > 1 ? "boosted" : boostFactor < 1 ? "penalized" : "passed";
|
|
2246
|
+
const reason = this.buildPriorityReason(cardTags, priority, boostFactor, finalScore);
|
|
2247
|
+
return {
|
|
2248
|
+
...card,
|
|
2249
|
+
score: finalScore,
|
|
2250
|
+
provenance: [
|
|
2251
|
+
...card.provenance,
|
|
2252
|
+
{
|
|
2253
|
+
strategy: "relativePriority",
|
|
2254
|
+
strategyName: this.strategyName || this.name,
|
|
2255
|
+
strategyId: this.strategyId || "NAVIGATION_STRATEGY-priority",
|
|
2256
|
+
action,
|
|
2257
|
+
score: finalScore,
|
|
2258
|
+
reason
|
|
2259
|
+
}
|
|
2260
|
+
]
|
|
2261
|
+
};
|
|
2262
|
+
})
|
|
2263
|
+
);
|
|
2264
|
+
return adjusted;
|
|
2265
|
+
}
|
|
2266
|
+
/**
|
|
2267
|
+
* Legacy getWeightedCards - now throws as filters should not be used as generators.
|
|
2268
|
+
*
|
|
2269
|
+
* Use transform() via Pipeline instead.
|
|
2270
|
+
*/
|
|
2271
|
+
async getWeightedCards(_limit) {
|
|
2272
|
+
throw new Error(
|
|
2273
|
+
"RelativePriorityNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
|
|
2274
|
+
);
|
|
2275
|
+
}
|
|
2276
|
+
};
|
|
2277
|
+
}
|
|
2278
|
+
});
|
|
2279
|
+
|
|
2280
|
+
// src/core/navigators/filters/types.ts
|
|
2281
|
+
var types_exports2 = {};
|
|
2282
|
+
var init_types2 = __esm({
|
|
2283
|
+
"src/core/navigators/filters/types.ts"() {
|
|
2284
|
+
"use strict";
|
|
2285
|
+
}
|
|
2286
|
+
});
|
|
2287
|
+
|
|
2288
|
+
// src/core/navigators/filters/userGoalStub.ts
|
|
2289
|
+
var userGoalStub_exports = {};
|
|
2290
|
+
__export(userGoalStub_exports, {
|
|
2291
|
+
USER_GOAL_NAVIGATOR_STUB: () => USER_GOAL_NAVIGATOR_STUB
|
|
2292
|
+
});
|
|
2293
|
+
var USER_GOAL_NAVIGATOR_STUB;
|
|
2294
|
+
var init_userGoalStub = __esm({
|
|
2295
|
+
"src/core/navigators/filters/userGoalStub.ts"() {
|
|
2296
|
+
"use strict";
|
|
2297
|
+
USER_GOAL_NAVIGATOR_STUB = true;
|
|
2298
|
+
}
|
|
2299
|
+
});
|
|
2300
|
+
|
|
2301
|
+
// import("./filters/**/*") in src/core/navigators/index.ts
|
|
2302
|
+
var globImport_filters;
|
|
2303
|
+
var init_2 = __esm({
|
|
2304
|
+
'import("./filters/**/*") in src/core/navigators/index.ts'() {
|
|
2305
|
+
globImport_filters = __glob({
|
|
2306
|
+
"./filters/WeightedFilter.ts": () => Promise.resolve().then(() => (init_WeightedFilter(), WeightedFilter_exports)),
|
|
2307
|
+
"./filters/eloDistance.ts": () => Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports)),
|
|
2308
|
+
"./filters/hierarchyDefinition.ts": () => Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
|
|
2309
|
+
"./filters/index.ts": () => Promise.resolve().then(() => (init_filters(), filters_exports)),
|
|
2310
|
+
"./filters/inferredPreferenceStub.ts": () => Promise.resolve().then(() => (init_inferredPreferenceStub(), inferredPreferenceStub_exports)),
|
|
2311
|
+
"./filters/interferenceMitigator.ts": () => Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
|
|
2312
|
+
"./filters/relativePriority.ts": () => Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
|
|
2313
|
+
"./filters/types.ts": () => Promise.resolve().then(() => (init_types2(), types_exports2)),
|
|
2314
|
+
"./filters/userGoalStub.ts": () => Promise.resolve().then(() => (init_userGoalStub(), userGoalStub_exports)),
|
|
2315
|
+
"./filters/userTagPreference.ts": () => Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports))
|
|
2316
|
+
});
|
|
2317
|
+
}
|
|
2318
|
+
});
|
|
2319
|
+
|
|
2320
|
+
// src/core/orchestration/gradient.ts
|
|
2321
|
+
function aggregateOutcomesForGradient(outcomes, strategyId) {
|
|
2322
|
+
const observations = [];
|
|
2323
|
+
for (const outcome of outcomes) {
|
|
2324
|
+
const deviation = outcome.deviations[strategyId];
|
|
2325
|
+
if (deviation === void 0) {
|
|
2326
|
+
continue;
|
|
2327
|
+
}
|
|
2328
|
+
observations.push({
|
|
2329
|
+
deviation,
|
|
2330
|
+
outcomeValue: outcome.outcomeValue,
|
|
2331
|
+
weight: 1
|
|
2332
|
+
});
|
|
2333
|
+
}
|
|
2334
|
+
logger.debug(
|
|
2335
|
+
`[Orchestration] Aggregated ${observations.length} observations for strategy ${strategyId}`
|
|
2336
|
+
);
|
|
2337
|
+
return observations;
|
|
2338
|
+
}
|
|
2339
|
+
function computeStrategyGradient(observations) {
|
|
2340
|
+
const n = observations.length;
|
|
2341
|
+
if (n < 3) {
|
|
2342
|
+
logger.debug(`[Orchestration] Insufficient observations for gradient (${n} < 3)`);
|
|
2343
|
+
return null;
|
|
2344
|
+
}
|
|
2345
|
+
let sumX = 0;
|
|
2346
|
+
let sumY = 0;
|
|
2347
|
+
let sumW = 0;
|
|
2348
|
+
for (const obs of observations) {
|
|
2349
|
+
const w = obs.weight ?? 1;
|
|
2350
|
+
sumX += obs.deviation * w;
|
|
2351
|
+
sumY += obs.outcomeValue * w;
|
|
2352
|
+
sumW += w;
|
|
2353
|
+
}
|
|
2354
|
+
const meanX = sumX / sumW;
|
|
2355
|
+
const meanY = sumY / sumW;
|
|
2356
|
+
let numerator = 0;
|
|
2357
|
+
let denominator = 0;
|
|
2358
|
+
let ssTotal = 0;
|
|
2359
|
+
for (const obs of observations) {
|
|
2360
|
+
const w = obs.weight ?? 1;
|
|
2361
|
+
const dx = obs.deviation - meanX;
|
|
2362
|
+
const dy = obs.outcomeValue - meanY;
|
|
2363
|
+
numerator += w * dx * dy;
|
|
2364
|
+
denominator += w * dx * dx;
|
|
2365
|
+
ssTotal += w * dy * dy;
|
|
2366
|
+
}
|
|
2367
|
+
if (denominator < 1e-10) {
|
|
2368
|
+
logger.debug(`[Orchestration] No variance in deviations, cannot compute gradient`);
|
|
2369
|
+
return {
|
|
2370
|
+
gradient: 0,
|
|
2371
|
+
intercept: meanY,
|
|
2372
|
+
rSquared: 0,
|
|
2373
|
+
sampleSize: n
|
|
2374
|
+
};
|
|
2375
|
+
}
|
|
2376
|
+
const gradient = numerator / denominator;
|
|
2377
|
+
const intercept = meanY - gradient * meanX;
|
|
2378
|
+
let ssResidual = 0;
|
|
2379
|
+
for (const obs of observations) {
|
|
2380
|
+
const w = obs.weight ?? 1;
|
|
2381
|
+
const predicted = gradient * obs.deviation + intercept;
|
|
2382
|
+
const residual = obs.outcomeValue - predicted;
|
|
2383
|
+
ssResidual += w * residual * residual;
|
|
2384
|
+
}
|
|
2385
|
+
const rSquared = ssTotal > 1e-10 ? 1 - ssResidual / ssTotal : 0;
|
|
2386
|
+
logger.debug(
|
|
2387
|
+
`[Orchestration] Computed gradient: ${gradient.toFixed(4)}, intercept: ${intercept.toFixed(4)}, R\xB2: ${rSquared.toFixed(4)}, n=${n}`
|
|
2388
|
+
);
|
|
2389
|
+
return {
|
|
2390
|
+
gradient,
|
|
2391
|
+
intercept,
|
|
2392
|
+
rSquared: Math.max(0, Math.min(1, rSquared)),
|
|
2393
|
+
// Clamp to [0,1]
|
|
2394
|
+
sampleSize: n
|
|
2395
|
+
};
|
|
2396
|
+
}
|
|
2397
|
+
var init_gradient = __esm({
|
|
2398
|
+
"src/core/orchestration/gradient.ts"() {
|
|
2399
|
+
"use strict";
|
|
2400
|
+
init_logger();
|
|
2401
|
+
}
|
|
2402
|
+
});
|
|
2403
|
+
|
|
2404
|
+
// src/core/orchestration/learning.ts
|
|
2405
|
+
function updateStrategyWeight(current, gradient) {
|
|
2406
|
+
if (gradient.sampleSize < MIN_OBSERVATIONS_FOR_UPDATE) {
|
|
2407
|
+
logger.debug(
|
|
2408
|
+
`[Orchestration] Insufficient samples (${gradient.sampleSize} < ${MIN_OBSERVATIONS_FOR_UPDATE}), keeping current weight`
|
|
2409
|
+
);
|
|
2410
|
+
return {
|
|
2411
|
+
...current,
|
|
2412
|
+
sampleSize: current.sampleSize + gradient.sampleSize
|
|
2413
|
+
};
|
|
2414
|
+
}
|
|
2415
|
+
const isReliable = gradient.rSquared >= MIN_R_SQUARED_FOR_GRADIENT;
|
|
2416
|
+
const isFlat = Math.abs(gradient.gradient) < FLAT_GRADIENT_THRESHOLD;
|
|
2417
|
+
let newWeight = current.weight;
|
|
2418
|
+
let newConfidence = current.confidence;
|
|
2419
|
+
if (!isReliable || isFlat) {
|
|
2420
|
+
const confidenceGain = 0.05 * (1 - current.confidence);
|
|
2421
|
+
newConfidence = Math.min(1, current.confidence + confidenceGain);
|
|
2422
|
+
logger.debug(
|
|
2423
|
+
`[Orchestration] Flat/unreliable gradient (|g|=${Math.abs(gradient.gradient).toFixed(4)}, R\xB2=${gradient.rSquared.toFixed(4)}). Increasing confidence: ${current.confidence.toFixed(3)} \u2192 ${newConfidence.toFixed(3)}`
|
|
2424
|
+
);
|
|
2425
|
+
} else {
|
|
2426
|
+
let delta = gradient.gradient * LEARNING_RATE;
|
|
2427
|
+
delta = Math.max(-MAX_WEIGHT_DELTA, Math.min(MAX_WEIGHT_DELTA, delta));
|
|
2428
|
+
newWeight = current.weight + delta;
|
|
2429
|
+
newWeight = Math.max(0.1, Math.min(3, newWeight));
|
|
2430
|
+
const confidenceGain = 0.02 * (1 - current.confidence);
|
|
2431
|
+
newConfidence = Math.min(1, current.confidence + confidenceGain);
|
|
2432
|
+
logger.debug(
|
|
2433
|
+
`[Orchestration] Adjusting weight: ${current.weight.toFixed(3)} \u2192 ${newWeight.toFixed(3)} (gradient=${gradient.gradient.toFixed(4)}, delta=${delta.toFixed(4)})`
|
|
2434
|
+
);
|
|
2435
|
+
}
|
|
2436
|
+
return {
|
|
2437
|
+
weight: newWeight,
|
|
2438
|
+
confidence: newConfidence,
|
|
2439
|
+
sampleSize: current.sampleSize + gradient.sampleSize
|
|
2440
|
+
};
|
|
2441
|
+
}
|
|
2442
|
+
function updateLearningState(courseId, strategyId, currentWeight, gradient, existing) {
|
|
2443
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
2444
|
+
const id = `STRATEGY_LEARNING_STATE::${courseId}::${strategyId}`;
|
|
2445
|
+
const historyEntry = {
|
|
2446
|
+
timestamp: now,
|
|
2447
|
+
weight: currentWeight.weight,
|
|
2448
|
+
confidence: currentWeight.confidence,
|
|
2449
|
+
gradient: gradient.gradient
|
|
2450
|
+
};
|
|
2451
|
+
let history = existing?.history ?? [];
|
|
2452
|
+
history = [...history, historyEntry];
|
|
2453
|
+
if (history.length > MAX_HISTORY_LENGTH) {
|
|
2454
|
+
history = history.slice(history.length - MAX_HISTORY_LENGTH);
|
|
2455
|
+
}
|
|
2456
|
+
const state = {
|
|
2457
|
+
_id: id,
|
|
2458
|
+
_rev: existing?._rev,
|
|
2459
|
+
docType: "STRATEGY_LEARNING_STATE" /* STRATEGY_LEARNING_STATE */,
|
|
2460
|
+
courseId,
|
|
2461
|
+
strategyId,
|
|
2462
|
+
currentWeight,
|
|
2463
|
+
regression: {
|
|
2464
|
+
gradient: gradient.gradient,
|
|
2465
|
+
intercept: gradient.intercept,
|
|
2466
|
+
rSquared: gradient.rSquared,
|
|
2467
|
+
sampleSize: gradient.sampleSize,
|
|
2468
|
+
computedAt: now
|
|
2469
|
+
},
|
|
2470
|
+
history,
|
|
2471
|
+
updatedAt: now
|
|
2472
|
+
};
|
|
2473
|
+
return state;
|
|
2474
|
+
}
|
|
2475
|
+
function runPeriodUpdate(input) {
|
|
2476
|
+
const { courseId, strategyId, currentWeight, gradient, existingState } = input;
|
|
2477
|
+
logger.info(
|
|
2478
|
+
`[Orchestration] Running period update for strategy ${strategyId} (${gradient.sampleSize} observations)`
|
|
2479
|
+
);
|
|
2480
|
+
const newWeight = updateStrategyWeight(currentWeight, gradient);
|
|
2481
|
+
const updated = newWeight.weight !== currentWeight.weight;
|
|
2482
|
+
const learningState = updateLearningState(
|
|
2483
|
+
courseId,
|
|
2484
|
+
strategyId,
|
|
2485
|
+
newWeight,
|
|
2486
|
+
gradient,
|
|
2487
|
+
existingState
|
|
2488
|
+
);
|
|
2489
|
+
logger.info(
|
|
2490
|
+
`[Orchestration] Period update complete for ${strategyId}: weight ${currentWeight.weight.toFixed(3)} \u2192 ${newWeight.weight.toFixed(3)}, confidence ${currentWeight.confidence.toFixed(3)} \u2192 ${newWeight.confidence.toFixed(3)}`
|
|
2491
|
+
);
|
|
2492
|
+
return {
|
|
2493
|
+
strategyId,
|
|
2494
|
+
previousWeight: currentWeight,
|
|
2495
|
+
newWeight,
|
|
2496
|
+
gradient,
|
|
2497
|
+
learningState,
|
|
2498
|
+
updated
|
|
2499
|
+
};
|
|
2500
|
+
}
|
|
2501
|
+
function getDefaultLearnableWeight() {
|
|
2502
|
+
return { ...DEFAULT_LEARNABLE_WEIGHT };
|
|
2503
|
+
}
|
|
2504
|
+
var MIN_OBSERVATIONS_FOR_UPDATE, LEARNING_RATE, MAX_WEIGHT_DELTA, MIN_R_SQUARED_FOR_GRADIENT, FLAT_GRADIENT_THRESHOLD, MAX_HISTORY_LENGTH;
|
|
2505
|
+
var init_learning = __esm({
|
|
2506
|
+
"src/core/orchestration/learning.ts"() {
|
|
2507
|
+
"use strict";
|
|
2508
|
+
init_contentNavigationStrategy();
|
|
2509
|
+
init_types_legacy();
|
|
2510
|
+
init_logger();
|
|
2511
|
+
MIN_OBSERVATIONS_FOR_UPDATE = 10;
|
|
2512
|
+
LEARNING_RATE = 0.1;
|
|
2513
|
+
MAX_WEIGHT_DELTA = 0.3;
|
|
2514
|
+
MIN_R_SQUARED_FOR_GRADIENT = 0.05;
|
|
2515
|
+
FLAT_GRADIENT_THRESHOLD = 0.02;
|
|
2516
|
+
MAX_HISTORY_LENGTH = 100;
|
|
2517
|
+
}
|
|
2518
|
+
});
|
|
2519
|
+
|
|
2520
|
+
// src/core/orchestration/signal.ts
|
|
2521
|
+
function computeOutcomeSignal(records, config = {}) {
|
|
2522
|
+
if (!records || records.length === 0) {
|
|
2523
|
+
return null;
|
|
2524
|
+
}
|
|
2525
|
+
const target = config.targetAccuracy ?? 0.85;
|
|
2526
|
+
const tolerance = config.tolerance ?? 0.05;
|
|
2527
|
+
let correct = 0;
|
|
2528
|
+
for (const r of records) {
|
|
2529
|
+
if (r.isCorrect) correct++;
|
|
2530
|
+
}
|
|
2531
|
+
const accuracy = correct / records.length;
|
|
2532
|
+
return scoreAccuracyInZone(accuracy, target, tolerance);
|
|
2533
|
+
}
|
|
2534
|
+
function scoreAccuracyInZone(accuracy, target, tolerance) {
|
|
2535
|
+
const dist = Math.abs(accuracy - target);
|
|
2536
|
+
if (dist <= tolerance) {
|
|
2537
|
+
return 1;
|
|
2538
|
+
}
|
|
2539
|
+
const excess = dist - tolerance;
|
|
2540
|
+
const slope = 2.5;
|
|
2541
|
+
return Math.max(0, 1 - excess * slope);
|
|
2542
|
+
}
|
|
2543
|
+
var init_signal = __esm({
|
|
2544
|
+
"src/core/orchestration/signal.ts"() {
|
|
2545
|
+
"use strict";
|
|
2546
|
+
}
|
|
2547
|
+
});
|
|
2548
|
+
|
|
2549
|
+
// src/core/orchestration/recording.ts
|
|
2550
|
+
async function recordUserOutcome(context, periodStart, periodEnd, records, activeStrategyIds, eloStart = 0, eloEnd = 0, config) {
|
|
2551
|
+
const { user, course, userId } = context;
|
|
2552
|
+
const courseId = course.getCourseID();
|
|
2553
|
+
const outcomeValue = computeOutcomeSignal(records, config);
|
|
2554
|
+
if (outcomeValue === null) {
|
|
2555
|
+
logger.debug(
|
|
2556
|
+
`[Orchestration] No outcome signal computed for ${userId} (insufficient data). Skipping record.`
|
|
2557
|
+
);
|
|
2558
|
+
return;
|
|
2559
|
+
}
|
|
2560
|
+
const deviations = {};
|
|
2561
|
+
for (const strategyId of activeStrategyIds) {
|
|
2562
|
+
deviations[strategyId] = context.getDeviation(strategyId);
|
|
2563
|
+
}
|
|
2564
|
+
const id = `USER_OUTCOME::${courseId}::${userId}::${periodEnd}`;
|
|
2565
|
+
const record = {
|
|
2566
|
+
_id: id,
|
|
2567
|
+
docType: "USER_OUTCOME" /* USER_OUTCOME */,
|
|
2568
|
+
courseId,
|
|
2569
|
+
userId,
|
|
2570
|
+
periodStart,
|
|
2571
|
+
periodEnd,
|
|
2572
|
+
outcomeValue,
|
|
2573
|
+
deviations,
|
|
2574
|
+
metadata: {
|
|
2575
|
+
sessionsCount: 1,
|
|
2576
|
+
// Assumes recording is triggered per-session currently
|
|
2577
|
+
cardsSeen: records.length,
|
|
2578
|
+
eloStart,
|
|
2579
|
+
eloEnd,
|
|
2580
|
+
signalType: "accuracy_in_zone"
|
|
2581
|
+
}
|
|
2582
|
+
};
|
|
2583
|
+
try {
|
|
2584
|
+
await user.putUserOutcome(record);
|
|
2585
|
+
logger.debug(
|
|
2586
|
+
`[Orchestration] Recorded outcome ${outcomeValue.toFixed(3)} for ${userId} (doc: ${id})`
|
|
2587
|
+
);
|
|
2588
|
+
} catch (e) {
|
|
2589
|
+
logger.error(`[Orchestration] Failed to record outcome: ${e}`);
|
|
2590
|
+
}
|
|
2591
|
+
}
|
|
2592
|
+
var init_recording = __esm({
|
|
2593
|
+
"src/core/orchestration/recording.ts"() {
|
|
2594
|
+
"use strict";
|
|
2595
|
+
init_signal();
|
|
2596
|
+
init_types_legacy();
|
|
2597
|
+
init_logger();
|
|
2598
|
+
}
|
|
2599
|
+
});
|
|
2600
|
+
|
|
2601
|
+
// src/core/orchestration/index.ts
|
|
2602
|
+
function fnv1a(str) {
|
|
2603
|
+
let hash = 2166136261;
|
|
2604
|
+
for (let i = 0; i < str.length; i++) {
|
|
2605
|
+
hash ^= str.charCodeAt(i);
|
|
2606
|
+
hash = Math.imul(hash, 16777619);
|
|
2607
|
+
}
|
|
2608
|
+
return hash >>> 0;
|
|
2609
|
+
}
|
|
2610
|
+
function computeDeviation(userId, strategyId, salt) {
|
|
2611
|
+
const input = `${userId}:${strategyId}:${salt}`;
|
|
2612
|
+
const hash = fnv1a(input);
|
|
2613
|
+
const normalized = hash / 4294967296;
|
|
2614
|
+
return normalized * 2 - 1;
|
|
2615
|
+
}
|
|
2616
|
+
function computeSpread(confidence) {
|
|
2617
|
+
const clampedConfidence = Math.max(0, Math.min(1, confidence));
|
|
2618
|
+
return MAX_SPREAD - clampedConfidence * (MAX_SPREAD - MIN_SPREAD);
|
|
2619
|
+
}
|
|
2620
|
+
function computeEffectiveWeight(learnable, userId, strategyId, salt) {
|
|
2621
|
+
const deviation = computeDeviation(userId, strategyId, salt);
|
|
2622
|
+
const spread = computeSpread(learnable.confidence);
|
|
2623
|
+
const adjustment = deviation * spread * learnable.weight;
|
|
2624
|
+
const effective = learnable.weight + adjustment;
|
|
2625
|
+
return Math.max(MIN_WEIGHT, Math.min(MAX_WEIGHT, effective));
|
|
2626
|
+
}
|
|
2627
|
+
async function createOrchestrationContext(user, course) {
|
|
2628
|
+
let courseConfig;
|
|
2629
|
+
try {
|
|
2630
|
+
courseConfig = await course.getCourseConfig();
|
|
2631
|
+
} catch (e) {
|
|
2632
|
+
logger.error(`[Orchestration] Failed to load course config: ${e}`);
|
|
2633
|
+
courseConfig = {
|
|
2634
|
+
name: "Unknown",
|
|
2635
|
+
description: "",
|
|
2636
|
+
public: false,
|
|
2637
|
+
deleted: false,
|
|
2638
|
+
creator: "",
|
|
2639
|
+
admins: [],
|
|
2640
|
+
moderators: [],
|
|
2641
|
+
dataShapes: [],
|
|
2642
|
+
questionTypes: [],
|
|
2643
|
+
orchestration: { salt: "default" }
|
|
2644
|
+
};
|
|
2645
|
+
}
|
|
2646
|
+
const userId = user.getUsername();
|
|
2647
|
+
const salt = courseConfig.orchestration?.salt || "default_salt";
|
|
2648
|
+
return {
|
|
2649
|
+
user,
|
|
2650
|
+
course,
|
|
2651
|
+
userId,
|
|
2652
|
+
courseConfig,
|
|
2653
|
+
getEffectiveWeight(strategyId, learnable) {
|
|
2654
|
+
return computeEffectiveWeight(learnable, userId, strategyId, salt);
|
|
2655
|
+
},
|
|
2656
|
+
getDeviation(strategyId) {
|
|
2657
|
+
return computeDeviation(userId, strategyId, salt);
|
|
2658
|
+
}
|
|
2659
|
+
};
|
|
2660
|
+
}
|
|
2661
|
+
var MIN_SPREAD, MAX_SPREAD, MIN_WEIGHT, MAX_WEIGHT;
|
|
2662
|
+
var init_orchestration = __esm({
|
|
2663
|
+
"src/core/orchestration/index.ts"() {
|
|
2664
|
+
"use strict";
|
|
2665
|
+
init_logger();
|
|
2666
|
+
init_gradient();
|
|
2667
|
+
init_learning();
|
|
2668
|
+
init_signal();
|
|
2669
|
+
init_recording();
|
|
2670
|
+
MIN_SPREAD = 0.1;
|
|
2671
|
+
MAX_SPREAD = 0.5;
|
|
2672
|
+
MIN_WEIGHT = 0.1;
|
|
2673
|
+
MAX_WEIGHT = 3;
|
|
2674
|
+
}
|
|
2675
|
+
});
|
|
2676
|
+
|
|
2677
|
+
// src/core/navigators/Pipeline.ts
|
|
2678
|
+
var Pipeline_exports = {};
|
|
2679
|
+
__export(Pipeline_exports, {
|
|
2680
|
+
Pipeline: () => Pipeline
|
|
2681
|
+
});
|
|
2682
|
+
import { toCourseElo as toCourseElo5 } from "@vue-skuilder/common";
|
|
2683
|
+
function logPipelineConfig(generator, filters) {
|
|
2684
|
+
const filterList = filters.length > 0 ? "\n - " + filters.map((f) => f.name).join("\n - ") : " none";
|
|
2685
|
+
logger.info(
|
|
2686
|
+
`[Pipeline] Configuration:
|
|
2687
|
+
Generator: ${generator.name}
|
|
2688
|
+
Filters:${filterList}`
|
|
2689
|
+
);
|
|
2690
|
+
}
|
|
2691
|
+
function logTagHydration(cards, tagsByCard) {
|
|
2692
|
+
const totalTags = Array.from(tagsByCard.values()).reduce((sum, tags) => sum + tags.length, 0);
|
|
2693
|
+
const cardsWithTags = Array.from(tagsByCard.values()).filter((tags) => tags.length > 0).length;
|
|
2694
|
+
logger.debug(
|
|
2695
|
+
`[Pipeline] Tag hydration: ${cards.length} cards, ${cardsWithTags} have tags (${totalTags} total tags) - single batch query`
|
|
2696
|
+
);
|
|
2697
|
+
}
|
|
2698
|
+
function logExecutionSummary(generatorName, generatedCount, filterCount, finalCount, topScores, filterImpacts) {
|
|
2699
|
+
const scoreDisplay = topScores.length > 0 ? topScores.map((s) => s.toFixed(2)).join(", ") : "none";
|
|
2700
|
+
let filterSummary = "";
|
|
2701
|
+
if (filterImpacts.length > 0) {
|
|
2702
|
+
const impacts = filterImpacts.map((f) => {
|
|
2703
|
+
const parts = [];
|
|
2704
|
+
if (f.boosted > 0) parts.push(`+${f.boosted}`);
|
|
2705
|
+
if (f.penalized > 0) parts.push(`-${f.penalized}`);
|
|
2706
|
+
if (f.passed > 0) parts.push(`=${f.passed}`);
|
|
2707
|
+
return `${f.name}: ${parts.join("/")}`;
|
|
2708
|
+
});
|
|
2709
|
+
filterSummary = `
|
|
2710
|
+
Filter impact: ${impacts.join(", ")}`;
|
|
2711
|
+
}
|
|
2712
|
+
logger.info(
|
|
2713
|
+
`[Pipeline] Execution: ${generatorName} produced ${generatedCount} \u2192 ${filterCount} filters \u2192 ${finalCount} results (top scores: ${scoreDisplay})` + filterSummary + `
|
|
2714
|
+
\u{1F4A1} Inspect: window.skuilder.pipeline`
|
|
2715
|
+
);
|
|
2716
|
+
}
|
|
2717
|
+
function logCardProvenance(cards, maxCards = 3) {
|
|
2718
|
+
const cardsToLog = cards.slice(0, maxCards);
|
|
2719
|
+
logger.debug(`[Pipeline] Provenance for top ${cardsToLog.length} cards:`);
|
|
2720
|
+
for (const card of cardsToLog) {
|
|
2721
|
+
logger.debug(`[Pipeline] ${card.cardId} (final score: ${card.score.toFixed(3)}):`);
|
|
2722
|
+
for (const entry of card.provenance) {
|
|
2723
|
+
const scoreChange = entry.score.toFixed(3);
|
|
2724
|
+
const action = entry.action.padEnd(9);
|
|
2725
|
+
logger.debug(
|
|
2726
|
+
`[Pipeline] ${action} ${scoreChange} - ${entry.strategyName}: ${entry.reason}`
|
|
2727
|
+
);
|
|
2728
|
+
}
|
|
2729
|
+
}
|
|
2730
|
+
}
|
|
2731
|
+
var Pipeline;
|
|
2732
|
+
var init_Pipeline = __esm({
|
|
2733
|
+
"src/core/navigators/Pipeline.ts"() {
|
|
2734
|
+
"use strict";
|
|
2735
|
+
init_navigators();
|
|
2736
|
+
init_logger();
|
|
2737
|
+
init_orchestration();
|
|
2738
|
+
init_PipelineDebugger();
|
|
2739
|
+
Pipeline = class extends ContentNavigator {
|
|
2740
|
+
generator;
|
|
2741
|
+
filters;
|
|
2742
|
+
/**
|
|
2743
|
+
* Create a new pipeline.
|
|
2744
|
+
*
|
|
2745
|
+
* @param generator - The generator (or CompositeGenerator) that produces candidates
|
|
2746
|
+
* @param filters - Filters to apply sequentially (order doesn't matter for multipliers)
|
|
2747
|
+
* @param user - User database interface
|
|
2748
|
+
* @param course - Course database interface
|
|
2749
|
+
*/
|
|
2750
|
+
constructor(generator, filters, user, course) {
|
|
2751
|
+
super();
|
|
2752
|
+
this.generator = generator;
|
|
2753
|
+
this.filters = filters;
|
|
2754
|
+
this.user = user;
|
|
2755
|
+
this.course = course;
|
|
2756
|
+
course.getCourseConfig().then((cfg) => {
|
|
2757
|
+
logger.debug(`[pipeline] Crated pipeline for ${cfg.name}`);
|
|
2758
|
+
}).catch((e) => {
|
|
2759
|
+
logger.error(`[pipeline] Failed to lookup courseCfg: ${e}`);
|
|
2760
|
+
});
|
|
2761
|
+
logPipelineConfig(generator, filters);
|
|
2762
|
+
}
|
|
2763
|
+
/**
|
|
2764
|
+
* Get weighted cards by running generator and applying filters.
|
|
2765
|
+
*
|
|
2766
|
+
* 1. Build shared context (user ELO, etc.)
|
|
2767
|
+
* 2. Get candidates from generator (passing context)
|
|
2768
|
+
* 3. Batch hydrate tags for all candidates
|
|
2769
|
+
* 4. Apply each filter sequentially
|
|
2770
|
+
* 5. Remove zero-score cards
|
|
2771
|
+
* 6. Sort by score descending
|
|
2772
|
+
* 7. Return top N
|
|
2773
|
+
*
|
|
2774
|
+
* @param limit - Maximum number of cards to return
|
|
2775
|
+
* @returns Cards sorted by score descending
|
|
2776
|
+
*/
|
|
2777
|
+
async getWeightedCards(limit) {
|
|
2778
|
+
const context = await this.buildContext();
|
|
2779
|
+
const overFetchMultiplier = 2 + this.filters.length * 0.5;
|
|
2780
|
+
const fetchLimit = Math.ceil(limit * overFetchMultiplier);
|
|
2781
|
+
logger.debug(
|
|
2782
|
+
`[Pipeline] Fetching ${fetchLimit} candidates from generator '${this.generator.name}'`
|
|
2783
|
+
);
|
|
2784
|
+
let cards = await this.generator.getWeightedCards(fetchLimit, context);
|
|
2785
|
+
const generatedCount = cards.length;
|
|
2786
|
+
let generatorSummaries;
|
|
2787
|
+
if (this.generator.generators) {
|
|
2788
|
+
const genMap = /* @__PURE__ */ new Map();
|
|
2789
|
+
for (const card of cards) {
|
|
2790
|
+
const firstProv = card.provenance[0];
|
|
2791
|
+
if (firstProv) {
|
|
2792
|
+
const genName = firstProv.strategyName;
|
|
2793
|
+
if (!genMap.has(genName)) {
|
|
2794
|
+
genMap.set(genName, { cards: [] });
|
|
2795
|
+
}
|
|
2796
|
+
genMap.get(genName).cards.push(card);
|
|
2797
|
+
}
|
|
2798
|
+
}
|
|
2799
|
+
generatorSummaries = Array.from(genMap.entries()).map(([name, data]) => {
|
|
2800
|
+
const newCards = data.cards.filter((c) => c.provenance[0]?.reason?.includes("new card"));
|
|
2801
|
+
const reviewCards = data.cards.filter((c) => c.provenance[0]?.reason?.includes("review"));
|
|
2802
|
+
return {
|
|
2803
|
+
name,
|
|
2804
|
+
cardCount: data.cards.length,
|
|
2805
|
+
newCount: newCards.length,
|
|
2806
|
+
reviewCount: reviewCards.length,
|
|
2807
|
+
topScore: Math.max(...data.cards.map((c) => c.score), 0)
|
|
2808
|
+
};
|
|
2809
|
+
});
|
|
2810
|
+
}
|
|
2811
|
+
logger.debug(`[Pipeline] Generator returned ${generatedCount} candidates`);
|
|
2812
|
+
cards = await this.hydrateTags(cards);
|
|
2813
|
+
const allCardsBeforeFiltering = [...cards];
|
|
2814
|
+
const filterImpacts = [];
|
|
2815
|
+
for (const filter of this.filters) {
|
|
2816
|
+
const beforeCount = cards.length;
|
|
2817
|
+
const beforeScores = new Map(cards.map((c) => [c.cardId, c.score]));
|
|
2818
|
+
cards = await filter.transform(cards, context);
|
|
2819
|
+
let boosted = 0, penalized = 0, passed = 0;
|
|
2820
|
+
const removed = beforeCount - cards.length;
|
|
2821
|
+
for (const card of cards) {
|
|
2822
|
+
const before = beforeScores.get(card.cardId) ?? 0;
|
|
2823
|
+
if (card.score > before) boosted++;
|
|
2824
|
+
else if (card.score < before) penalized++;
|
|
2825
|
+
else passed++;
|
|
2826
|
+
}
|
|
2827
|
+
filterImpacts.push({ name: filter.name, boosted, penalized, passed, removed });
|
|
2828
|
+
logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeScores.size} \u2192 ${cards.length} cards (\u2191${boosted} \u2193${penalized} =${passed})`);
|
|
2829
|
+
}
|
|
2830
|
+
cards = cards.filter((c) => c.score > 0);
|
|
2831
|
+
cards.sort((a, b) => b.score - a.score);
|
|
2832
|
+
const result = cards.slice(0, limit);
|
|
2833
|
+
const topScores = result.slice(0, 3).map((c) => c.score);
|
|
2834
|
+
logExecutionSummary(
|
|
2835
|
+
this.generator.name,
|
|
2836
|
+
generatedCount,
|
|
2837
|
+
this.filters.length,
|
|
2838
|
+
result.length,
|
|
2839
|
+
topScores,
|
|
2840
|
+
filterImpacts
|
|
2841
|
+
);
|
|
2842
|
+
logCardProvenance(result, 3);
|
|
2843
|
+
try {
|
|
2844
|
+
const courseName = await this.course?.getCourseConfig().then((c) => c.name).catch(() => void 0);
|
|
2845
|
+
const report = buildRunReport(
|
|
2846
|
+
this.course?.getCourseID() || "unknown",
|
|
2847
|
+
courseName,
|
|
2848
|
+
this.generator.name,
|
|
2849
|
+
generatorSummaries,
|
|
2850
|
+
generatedCount,
|
|
2851
|
+
filterImpacts,
|
|
2852
|
+
allCardsBeforeFiltering,
|
|
2853
|
+
result
|
|
2854
|
+
);
|
|
2855
|
+
captureRun(report);
|
|
2856
|
+
} catch (e) {
|
|
2857
|
+
logger.debug(`[Pipeline] Failed to capture debug run: ${e}`);
|
|
2858
|
+
}
|
|
2859
|
+
return result;
|
|
2860
|
+
}
|
|
2861
|
+
/**
|
|
2862
|
+
* Batch hydrate tags for all cards.
|
|
2863
|
+
*
|
|
2864
|
+
* Fetches tags for all cards in a single database query and attaches them
|
|
2865
|
+
* to the WeightedCard objects. Filters can then use card.tags instead of
|
|
2866
|
+
* making individual getAppliedTags() calls.
|
|
2867
|
+
*
|
|
2868
|
+
* @param cards - Cards to hydrate
|
|
2869
|
+
* @returns Cards with tags populated
|
|
2870
|
+
*/
|
|
2871
|
+
async hydrateTags(cards) {
|
|
2872
|
+
if (cards.length === 0) {
|
|
2873
|
+
return cards;
|
|
2874
|
+
}
|
|
2875
|
+
const cardIds = cards.map((c) => c.cardId);
|
|
2876
|
+
const tagsByCard = await this.course.getAppliedTagsBatch(cardIds);
|
|
2877
|
+
logTagHydration(cards, tagsByCard);
|
|
2878
|
+
return cards.map((card) => ({
|
|
2879
|
+
...card,
|
|
2880
|
+
tags: tagsByCard.get(card.cardId) ?? []
|
|
2881
|
+
}));
|
|
2882
|
+
}
|
|
2883
|
+
/**
|
|
2884
|
+
* Build shared context for generator and filters.
|
|
2885
|
+
*
|
|
2886
|
+
* Called once per getWeightedCards() invocation.
|
|
2887
|
+
* Contains data that the generator and multiple filters might need.
|
|
2888
|
+
*
|
|
2889
|
+
* The context satisfies both GeneratorContext and FilterContext interfaces.
|
|
2890
|
+
*/
|
|
2891
|
+
async buildContext() {
|
|
2892
|
+
let userElo = 1e3;
|
|
2893
|
+
try {
|
|
2894
|
+
const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
|
|
2895
|
+
const courseElo = toCourseElo5(courseReg.elo);
|
|
2896
|
+
userElo = courseElo.global.score;
|
|
2897
|
+
} catch (e) {
|
|
2898
|
+
logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
|
|
2899
|
+
}
|
|
2900
|
+
const orchestration = await createOrchestrationContext(this.user, this.course);
|
|
2901
|
+
return {
|
|
2902
|
+
user: this.user,
|
|
2903
|
+
course: this.course,
|
|
2904
|
+
userElo,
|
|
2905
|
+
orchestration
|
|
2906
|
+
};
|
|
2907
|
+
}
|
|
2908
|
+
/**
|
|
2909
|
+
* Get the course ID for this pipeline.
|
|
2910
|
+
*/
|
|
2911
|
+
getCourseID() {
|
|
2912
|
+
return this.course.getCourseID();
|
|
2913
|
+
}
|
|
2914
|
+
/**
|
|
2915
|
+
* Get orchestration context for outcome recording.
|
|
2916
|
+
*/
|
|
2917
|
+
async getOrchestrationContext() {
|
|
2918
|
+
return createOrchestrationContext(this.user, this.course);
|
|
2919
|
+
}
|
|
2920
|
+
/**
|
|
2921
|
+
* Get IDs of all strategies in this pipeline.
|
|
2922
|
+
* Used to record which strategies contributed to an outcome.
|
|
2923
|
+
*/
|
|
2924
|
+
getStrategyIds() {
|
|
2925
|
+
const ids = [];
|
|
2926
|
+
const extractId = (obj) => {
|
|
2927
|
+
if (obj.strategyId) return obj.strategyId;
|
|
2928
|
+
return null;
|
|
2929
|
+
};
|
|
2930
|
+
const genId = extractId(this.generator);
|
|
2931
|
+
if (genId) ids.push(genId);
|
|
2932
|
+
if (this.generator.generators && Array.isArray(this.generator.generators)) {
|
|
2933
|
+
this.generator.generators.forEach((g) => {
|
|
2934
|
+
const subId = extractId(g);
|
|
2935
|
+
if (subId) ids.push(subId);
|
|
2936
|
+
});
|
|
2937
|
+
}
|
|
2938
|
+
for (const filter of this.filters) {
|
|
2939
|
+
const fId = extractId(filter);
|
|
2940
|
+
if (fId) ids.push(fId);
|
|
2941
|
+
}
|
|
2942
|
+
return [...new Set(ids)];
|
|
2943
|
+
}
|
|
2944
|
+
};
|
|
2945
|
+
}
|
|
2946
|
+
});
|
|
2947
|
+
|
|
2948
|
+
// src/core/navigators/defaults.ts
|
|
2949
|
+
var defaults_exports = {};
|
|
2950
|
+
__export(defaults_exports, {
|
|
2951
|
+
createDefaultEloStrategy: () => createDefaultEloStrategy,
|
|
2952
|
+
createDefaultPipeline: () => createDefaultPipeline,
|
|
2953
|
+
createDefaultSrsStrategy: () => createDefaultSrsStrategy
|
|
2954
|
+
});
|
|
2955
|
+
function createDefaultEloStrategy(courseId) {
|
|
2956
|
+
return {
|
|
2957
|
+
_id: "NAVIGATION_STRATEGY-ELO-default",
|
|
2958
|
+
docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
|
|
2959
|
+
name: "ELO (default)",
|
|
2960
|
+
description: "Default ELO-based navigation strategy for new cards",
|
|
2961
|
+
implementingClass: "elo" /* ELO */,
|
|
2962
|
+
course: courseId,
|
|
2963
|
+
serializedData: ""
|
|
2964
|
+
};
|
|
2965
|
+
}
|
|
2966
|
+
function createDefaultSrsStrategy(courseId) {
|
|
2967
|
+
return {
|
|
2968
|
+
_id: "NAVIGATION_STRATEGY-SRS-default",
|
|
2969
|
+
docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
|
|
2970
|
+
name: "SRS (default)",
|
|
2971
|
+
description: "Default SRS-based navigation strategy for reviews",
|
|
2972
|
+
implementingClass: "srs" /* SRS */,
|
|
2973
|
+
course: courseId,
|
|
2974
|
+
serializedData: ""
|
|
2975
|
+
};
|
|
2976
|
+
}
|
|
2977
|
+
function createDefaultPipeline(user, course) {
|
|
2978
|
+
const courseId = course.getCourseID();
|
|
2979
|
+
const eloNavigator = new ELONavigator(user, course, createDefaultEloStrategy(courseId));
|
|
2980
|
+
const srsNavigator = new SRSNavigator(user, course, createDefaultSrsStrategy(courseId));
|
|
2981
|
+
const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);
|
|
2982
|
+
const eloDistanceFilter = createEloDistanceFilter();
|
|
2983
|
+
return new Pipeline(compositeGenerator, [eloDistanceFilter], user, course);
|
|
2984
|
+
}
|
|
2985
|
+
var init_defaults = __esm({
|
|
2986
|
+
"src/core/navigators/defaults.ts"() {
|
|
2987
|
+
"use strict";
|
|
2988
|
+
init_navigators();
|
|
2989
|
+
init_Pipeline();
|
|
2990
|
+
init_CompositeGenerator();
|
|
2991
|
+
init_elo();
|
|
2992
|
+
init_srs();
|
|
2993
|
+
init_eloDistance();
|
|
2994
|
+
init_types_legacy();
|
|
2995
|
+
}
|
|
2996
|
+
});
|
|
2997
|
+
|
|
2998
|
+
// src/core/navigators/PipelineAssembler.ts
|
|
2999
|
+
var PipelineAssembler_exports = {};
|
|
3000
|
+
__export(PipelineAssembler_exports, {
|
|
3001
|
+
PipelineAssembler: () => PipelineAssembler
|
|
3002
|
+
});
|
|
3003
|
+
var PipelineAssembler;
|
|
3004
|
+
var init_PipelineAssembler = __esm({
|
|
3005
|
+
"src/core/navigators/PipelineAssembler.ts"() {
|
|
3006
|
+
"use strict";
|
|
3007
|
+
init_navigators();
|
|
3008
|
+
init_WeightedFilter();
|
|
3009
|
+
init_Pipeline();
|
|
3010
|
+
init_logger();
|
|
3011
|
+
init_CompositeGenerator();
|
|
3012
|
+
init_defaults();
|
|
3013
|
+
PipelineAssembler = class {
|
|
3014
|
+
/**
|
|
3015
|
+
* Assembles a navigation pipeline from strategy documents.
|
|
3016
|
+
*
|
|
3017
|
+
* 1. Separates into generators and filters by role
|
|
3018
|
+
* 2. Validates at least one generator exists (or creates default ELO)
|
|
3019
|
+
* 3. Instantiates generators - wraps multiple in CompositeGenerator
|
|
3020
|
+
* 4. Instantiates filters
|
|
3021
|
+
* 5. Returns Pipeline(generator, filters)
|
|
3022
|
+
*
|
|
3023
|
+
* @param input - Strategy documents plus user/course interfaces
|
|
3024
|
+
* @returns Assembled pipeline and any warnings
|
|
3025
|
+
*/
|
|
3026
|
+
async assemble(input) {
|
|
3027
|
+
const { strategies, user, course } = input;
|
|
3028
|
+
const warnings = [];
|
|
3029
|
+
if (strategies.length === 0) {
|
|
3030
|
+
return {
|
|
3031
|
+
pipeline: null,
|
|
3032
|
+
generatorStrategies: [],
|
|
3033
|
+
filterStrategies: [],
|
|
3034
|
+
warnings
|
|
3035
|
+
};
|
|
3036
|
+
}
|
|
3037
|
+
const generatorStrategies = [];
|
|
3038
|
+
const filterStrategies = [];
|
|
3039
|
+
for (const s of strategies) {
|
|
3040
|
+
if (isGenerator(s.implementingClass)) {
|
|
3041
|
+
generatorStrategies.push(s);
|
|
3042
|
+
} else if (isFilter(s.implementingClass)) {
|
|
3043
|
+
filterStrategies.push(s);
|
|
3044
|
+
} else {
|
|
3045
|
+
warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
|
|
3046
|
+
}
|
|
3047
|
+
}
|
|
3048
|
+
if (generatorStrategies.length === 0) {
|
|
3049
|
+
if (filterStrategies.length > 0) {
|
|
3050
|
+
logger.debug(
|
|
3051
|
+
"[PipelineAssembler] No generator found, using default ELO and SRS with configured filters"
|
|
3052
|
+
);
|
|
3053
|
+
const courseId = course.getCourseID();
|
|
3054
|
+
generatorStrategies.push(createDefaultEloStrategy(courseId));
|
|
3055
|
+
generatorStrategies.push(createDefaultSrsStrategy(courseId));
|
|
3056
|
+
} else {
|
|
3057
|
+
warnings.push("No generator strategy found");
|
|
3058
|
+
return {
|
|
3059
|
+
pipeline: null,
|
|
3060
|
+
generatorStrategies: [],
|
|
3061
|
+
filterStrategies: [],
|
|
3062
|
+
warnings
|
|
3063
|
+
};
|
|
3064
|
+
}
|
|
3065
|
+
}
|
|
3066
|
+
let generator;
|
|
3067
|
+
if (generatorStrategies.length === 1) {
|
|
3068
|
+
const nav = await ContentNavigator.create(user, course, generatorStrategies[0]);
|
|
3069
|
+
generator = nav;
|
|
3070
|
+
logger.debug(`[PipelineAssembler] Using single generator: ${generatorStrategies[0].name}`);
|
|
3071
|
+
} else {
|
|
3072
|
+
logger.debug(
|
|
3073
|
+
`[PipelineAssembler] Using CompositeGenerator for ${generatorStrategies.length} generators: ${generatorStrategies.map((g) => g.name).join(", ")}`
|
|
3074
|
+
);
|
|
3075
|
+
generator = await CompositeGenerator.fromStrategies(user, course, generatorStrategies);
|
|
3076
|
+
}
|
|
3077
|
+
const filters = [];
|
|
3078
|
+
const sortedFilterStrategies = [...filterStrategies].sort(
|
|
3079
|
+
(a, b) => a.name.localeCompare(b.name)
|
|
3080
|
+
);
|
|
3081
|
+
for (const filterStrategy of sortedFilterStrategies) {
|
|
3082
|
+
try {
|
|
3083
|
+
const nav = await ContentNavigator.create(user, course, filterStrategy);
|
|
3084
|
+
if ("transform" in nav && typeof nav.transform === "function") {
|
|
3085
|
+
let filter = nav;
|
|
3086
|
+
if (filterStrategy.learnable) {
|
|
3087
|
+
filter = new WeightedFilter(
|
|
3088
|
+
filter,
|
|
3089
|
+
filterStrategy.learnable,
|
|
3090
|
+
filterStrategy.staticWeight,
|
|
3091
|
+
filterStrategy._id
|
|
3092
|
+
);
|
|
3093
|
+
}
|
|
3094
|
+
filters.push(filter);
|
|
3095
|
+
logger.debug(`[PipelineAssembler] Added filter: ${filterStrategy.name}`);
|
|
3096
|
+
} else {
|
|
3097
|
+
warnings.push(
|
|
3098
|
+
`Filter '${filterStrategy.name}' does not implement CardFilter.transform(), skipping`
|
|
3099
|
+
);
|
|
3100
|
+
}
|
|
3101
|
+
} catch (e) {
|
|
3102
|
+
warnings.push(`Failed to instantiate filter '${filterStrategy.name}': ${e}`);
|
|
3103
|
+
}
|
|
3104
|
+
}
|
|
3105
|
+
const pipeline = new Pipeline(generator, filters, user, course);
|
|
3106
|
+
logger.debug(
|
|
3107
|
+
`[PipelineAssembler] Assembled pipeline with ${generatorStrategies.length} generator(s) and ${filters.length} filter(s)`
|
|
3108
|
+
);
|
|
3109
|
+
return {
|
|
3110
|
+
pipeline,
|
|
3111
|
+
generatorStrategies,
|
|
3112
|
+
filterStrategies: sortedFilterStrategies,
|
|
3113
|
+
warnings
|
|
3114
|
+
};
|
|
3115
|
+
}
|
|
3116
|
+
};
|
|
3117
|
+
}
|
|
3118
|
+
});
|
|
3119
|
+
|
|
3120
|
+
// import("./**/*") in src/core/navigators/index.ts
|
|
3121
|
+
var globImport;
|
|
3122
|
+
var init_3 = __esm({
|
|
3123
|
+
'import("./**/*") in src/core/navigators/index.ts'() {
|
|
3124
|
+
globImport = __glob({
|
|
3125
|
+
"./Pipeline.ts": () => Promise.resolve().then(() => (init_Pipeline(), Pipeline_exports)),
|
|
3126
|
+
"./PipelineAssembler.ts": () => Promise.resolve().then(() => (init_PipelineAssembler(), PipelineAssembler_exports)),
|
|
3127
|
+
"./PipelineDebugger.ts": () => Promise.resolve().then(() => (init_PipelineDebugger(), PipelineDebugger_exports)),
|
|
3128
|
+
"./defaults.ts": () => Promise.resolve().then(() => (init_defaults(), defaults_exports)),
|
|
3129
|
+
"./filters/WeightedFilter.ts": () => Promise.resolve().then(() => (init_WeightedFilter(), WeightedFilter_exports)),
|
|
3130
|
+
"./filters/eloDistance.ts": () => Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports)),
|
|
3131
|
+
"./filters/hierarchyDefinition.ts": () => Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
|
|
3132
|
+
"./filters/index.ts": () => Promise.resolve().then(() => (init_filters(), filters_exports)),
|
|
3133
|
+
"./filters/inferredPreferenceStub.ts": () => Promise.resolve().then(() => (init_inferredPreferenceStub(), inferredPreferenceStub_exports)),
|
|
3134
|
+
"./filters/interferenceMitigator.ts": () => Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
|
|
3135
|
+
"./filters/relativePriority.ts": () => Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
|
|
3136
|
+
"./filters/types.ts": () => Promise.resolve().then(() => (init_types2(), types_exports2)),
|
|
3137
|
+
"./filters/userGoalStub.ts": () => Promise.resolve().then(() => (init_userGoalStub(), userGoalStub_exports)),
|
|
3138
|
+
"./filters/userTagPreference.ts": () => Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports)),
|
|
3139
|
+
"./generators/CompositeGenerator.ts": () => Promise.resolve().then(() => (init_CompositeGenerator(), CompositeGenerator_exports)),
|
|
3140
|
+
"./generators/elo.ts": () => Promise.resolve().then(() => (init_elo(), elo_exports)),
|
|
3141
|
+
"./generators/index.ts": () => Promise.resolve().then(() => (init_generators(), generators_exports)),
|
|
3142
|
+
"./generators/srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
|
|
3143
|
+
"./generators/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports)),
|
|
3144
|
+
"./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports))
|
|
3145
|
+
});
|
|
3146
|
+
}
|
|
3147
|
+
});
|
|
3148
|
+
|
|
3149
|
+
// src/core/navigators/index.ts
|
|
3150
|
+
var navigators_exports = {};
|
|
3151
|
+
__export(navigators_exports, {
|
|
3152
|
+
ContentNavigator: () => ContentNavigator,
|
|
3153
|
+
NavigatorRole: () => NavigatorRole,
|
|
3154
|
+
NavigatorRoles: () => NavigatorRoles,
|
|
3155
|
+
Navigators: () => Navigators,
|
|
3156
|
+
getCardOrigin: () => getCardOrigin,
|
|
3157
|
+
getRegisteredNavigator: () => getRegisteredNavigator,
|
|
3158
|
+
getRegisteredNavigatorNames: () => getRegisteredNavigatorNames,
|
|
3159
|
+
hasRegisteredNavigator: () => hasRegisteredNavigator,
|
|
3160
|
+
initializeNavigatorRegistry: () => initializeNavigatorRegistry,
|
|
3161
|
+
isFilter: () => isFilter,
|
|
3162
|
+
isGenerator: () => isGenerator,
|
|
3163
|
+
mountPipelineDebugger: () => mountPipelineDebugger,
|
|
3164
|
+
pipelineDebugAPI: () => pipelineDebugAPI,
|
|
3165
|
+
registerNavigator: () => registerNavigator
|
|
3166
|
+
});
|
|
3167
|
+
function registerNavigator(implementingClass, constructor) {
|
|
3168
|
+
navigatorRegistry.set(implementingClass, constructor);
|
|
3169
|
+
logger.debug(`[NavigatorRegistry] Registered: ${implementingClass}`);
|
|
3170
|
+
}
|
|
3171
|
+
function getRegisteredNavigator(implementingClass) {
|
|
3172
|
+
return navigatorRegistry.get(implementingClass);
|
|
3173
|
+
}
|
|
3174
|
+
function hasRegisteredNavigator(implementingClass) {
|
|
3175
|
+
return navigatorRegistry.has(implementingClass);
|
|
3176
|
+
}
|
|
3177
|
+
function getRegisteredNavigatorNames() {
|
|
3178
|
+
return Array.from(navigatorRegistry.keys());
|
|
3179
|
+
}
|
|
3180
|
+
async function initializeNavigatorRegistry() {
|
|
3181
|
+
logger.debug("[NavigatorRegistry] Initializing built-in navigators...");
|
|
3182
|
+
const [eloModule, srsModule] = await Promise.all([
|
|
3183
|
+
Promise.resolve().then(() => (init_elo(), elo_exports)),
|
|
3184
|
+
Promise.resolve().then(() => (init_srs(), srs_exports))
|
|
3185
|
+
]);
|
|
3186
|
+
registerNavigator("elo", eloModule.default);
|
|
3187
|
+
registerNavigator("srs", srsModule.default);
|
|
3188
|
+
const [
|
|
3189
|
+
hierarchyModule,
|
|
3190
|
+
interferenceModule,
|
|
3191
|
+
relativePriorityModule,
|
|
3192
|
+
userTagPreferenceModule
|
|
3193
|
+
] = await Promise.all([
|
|
3194
|
+
Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
|
|
3195
|
+
Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
|
|
3196
|
+
Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
|
|
3197
|
+
Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports))
|
|
3198
|
+
]);
|
|
3199
|
+
registerNavigator("hierarchyDefinition", hierarchyModule.default);
|
|
3200
|
+
registerNavigator("interferenceMitigator", interferenceModule.default);
|
|
3201
|
+
registerNavigator("relativePriority", relativePriorityModule.default);
|
|
3202
|
+
registerNavigator("userTagPreference", userTagPreferenceModule.default);
|
|
3203
|
+
logger.debug(
|
|
3204
|
+
`[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(", ")}`
|
|
3205
|
+
);
|
|
3206
|
+
}
|
|
3207
|
+
function getCardOrigin(card) {
|
|
3208
|
+
if (card.provenance.length === 0) {
|
|
3209
|
+
throw new Error("Card has no provenance - cannot determine origin");
|
|
3210
|
+
}
|
|
3211
|
+
const firstEntry = card.provenance[0];
|
|
3212
|
+
const reason = firstEntry.reason.toLowerCase();
|
|
3213
|
+
if (reason.includes("failed")) {
|
|
3214
|
+
return "failed";
|
|
3215
|
+
}
|
|
3216
|
+
if (reason.includes("review")) {
|
|
3217
|
+
return "review";
|
|
3218
|
+
}
|
|
3219
|
+
return "new";
|
|
3220
|
+
}
|
|
3221
|
+
function isGenerator(impl) {
|
|
3222
|
+
return NavigatorRoles[impl] === "generator" /* GENERATOR */;
|
|
3223
|
+
}
|
|
3224
|
+
function isFilter(impl) {
|
|
3225
|
+
return NavigatorRoles[impl] === "filter" /* FILTER */;
|
|
3226
|
+
}
|
|
3227
|
+
var navigatorRegistry, Navigators, NavigatorRole, NavigatorRoles, ContentNavigator;
|
|
3228
|
+
var init_navigators = __esm({
|
|
3229
|
+
"src/core/navigators/index.ts"() {
|
|
3230
|
+
"use strict";
|
|
3231
|
+
init_PipelineDebugger();
|
|
3232
|
+
init_logger();
|
|
3233
|
+
init_();
|
|
3234
|
+
init_2();
|
|
3235
|
+
init_3();
|
|
3236
|
+
navigatorRegistry = /* @__PURE__ */ new Map();
|
|
3237
|
+
Navigators = /* @__PURE__ */ ((Navigators2) => {
|
|
3238
|
+
Navigators2["ELO"] = "elo";
|
|
3239
|
+
Navigators2["SRS"] = "srs";
|
|
3240
|
+
Navigators2["HIERARCHY"] = "hierarchyDefinition";
|
|
3241
|
+
Navigators2["INTERFERENCE"] = "interferenceMitigator";
|
|
3242
|
+
Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
|
|
3243
|
+
Navigators2["USER_TAG_PREFERENCE"] = "userTagPreference";
|
|
3244
|
+
return Navigators2;
|
|
3245
|
+
})(Navigators || {});
|
|
3246
|
+
NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
|
|
3247
|
+
NavigatorRole2["GENERATOR"] = "generator";
|
|
3248
|
+
NavigatorRole2["FILTER"] = "filter";
|
|
3249
|
+
return NavigatorRole2;
|
|
3250
|
+
})(NavigatorRole || {});
|
|
3251
|
+
NavigatorRoles = {
|
|
3252
|
+
["elo" /* ELO */]: "generator" /* GENERATOR */,
|
|
3253
|
+
["srs" /* SRS */]: "generator" /* GENERATOR */,
|
|
3254
|
+
["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
|
|
3255
|
+
["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
|
|
3256
|
+
["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
|
|
3257
|
+
["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
|
|
3258
|
+
};
|
|
3259
|
+
ContentNavigator = class {
|
|
3260
|
+
/** User interface for this navigation session */
|
|
3261
|
+
user;
|
|
3262
|
+
/** Course interface for this navigation session */
|
|
3263
|
+
course;
|
|
3264
|
+
/** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
|
|
3265
|
+
strategyName;
|
|
3266
|
+
/** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
|
|
3267
|
+
strategyId;
|
|
3268
|
+
/** Evolutionary weighting configuration */
|
|
3269
|
+
learnable;
|
|
3270
|
+
/** Whether to bypass deviation (manual/static weighting) */
|
|
3271
|
+
staticWeight;
|
|
3272
|
+
/**
|
|
3273
|
+
* Constructor for standard navigators.
|
|
3274
|
+
* Call this from subclass constructors to initialize common fields.
|
|
3275
|
+
*
|
|
3276
|
+
* Note: CompositeGenerator and Pipeline call super() without args, then set
|
|
3277
|
+
* user/course fields directly if needed.
|
|
3278
|
+
*/
|
|
3279
|
+
constructor(user, course, strategyData) {
|
|
3280
|
+
this.user = user;
|
|
3281
|
+
this.course = course;
|
|
3282
|
+
if (strategyData) {
|
|
3283
|
+
this.strategyName = strategyData.name;
|
|
3284
|
+
this.strategyId = strategyData._id;
|
|
3285
|
+
this.learnable = strategyData.learnable;
|
|
3286
|
+
this.staticWeight = strategyData.staticWeight;
|
|
3287
|
+
}
|
|
3288
|
+
}
|
|
3289
|
+
// ============================================================================
|
|
3290
|
+
// STRATEGY STATE HELPERS
|
|
3291
|
+
// ============================================================================
|
|
3292
|
+
//
|
|
3293
|
+
// These methods allow strategies to persist their own state (user preferences,
|
|
3294
|
+
// learned patterns, temporal tracking) in the user database.
|
|
3295
|
+
//
|
|
3296
|
+
// ============================================================================
|
|
3297
|
+
/**
|
|
3298
|
+
* Unique key identifying this strategy for state storage.
|
|
3299
|
+
*
|
|
3300
|
+
* Defaults to the constructor name (e.g., "UserTagPreferenceFilter").
|
|
3301
|
+
* Override in subclasses if multiple instances of the same strategy type
|
|
3302
|
+
* need separate state storage.
|
|
3303
|
+
*/
|
|
3304
|
+
get strategyKey() {
|
|
3305
|
+
return this.constructor.name;
|
|
1348
3306
|
}
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
/** Human-readable name for CardGenerator interface */
|
|
1363
|
-
name;
|
|
1364
|
-
constructor(user, course, strategyData) {
|
|
1365
|
-
super(user, course, strategyData);
|
|
1366
|
-
this.name = strategyData?.name || "SRS";
|
|
3307
|
+
/**
|
|
3308
|
+
* Get this strategy's persisted state for the current course.
|
|
3309
|
+
*
|
|
3310
|
+
* @returns The strategy's data payload, or null if no state exists
|
|
3311
|
+
* @throws Error if user or course is not initialized
|
|
3312
|
+
*/
|
|
3313
|
+
async getStrategyState() {
|
|
3314
|
+
if (!this.user || !this.course) {
|
|
3315
|
+
throw new Error(
|
|
3316
|
+
`Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
|
|
3317
|
+
);
|
|
3318
|
+
}
|
|
3319
|
+
return this.user.getStrategyState(this.course.getCourseID(), this.strategyKey);
|
|
1367
3320
|
}
|
|
1368
3321
|
/**
|
|
1369
|
-
*
|
|
3322
|
+
* Persist this strategy's state for the current course.
|
|
1370
3323
|
*
|
|
1371
|
-
*
|
|
1372
|
-
*
|
|
1373
|
-
|
|
3324
|
+
* @param data - The strategy's data payload to store
|
|
3325
|
+
* @throws Error if user or course is not initialized
|
|
3326
|
+
*/
|
|
3327
|
+
async putStrategyState(data) {
|
|
3328
|
+
if (!this.user || !this.course) {
|
|
3329
|
+
throw new Error(
|
|
3330
|
+
`Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
|
|
3331
|
+
);
|
|
3332
|
+
}
|
|
3333
|
+
return this.user.putStrategyState(this.course.getCourseID(), this.strategyKey, data);
|
|
3334
|
+
}
|
|
3335
|
+
/**
|
|
3336
|
+
* Factory method to create navigator instances.
|
|
1374
3337
|
*
|
|
1375
|
-
*
|
|
3338
|
+
* First checks the navigator registry for a pre-registered constructor.
|
|
3339
|
+
* If not found, falls back to dynamic import (for custom navigators).
|
|
1376
3340
|
*
|
|
1377
|
-
*
|
|
1378
|
-
*
|
|
3341
|
+
* For reliable operation in test environments, call initializeNavigatorRegistry()
|
|
3342
|
+
* before using this method.
|
|
1379
3343
|
*
|
|
1380
|
-
* @param
|
|
1381
|
-
* @param
|
|
3344
|
+
* @param user - User interface
|
|
3345
|
+
* @param course - Course interface
|
|
3346
|
+
* @param strategyData - Strategy configuration document
|
|
3347
|
+
* @returns the runtime object used to steer a study session.
|
|
1382
3348
|
*/
|
|
1383
|
-
async
|
|
1384
|
-
|
|
1385
|
-
|
|
3349
|
+
static async create(user, course, strategyData) {
|
|
3350
|
+
const implementingClass = strategyData.implementingClass;
|
|
3351
|
+
const RegisteredImpl = getRegisteredNavigator(implementingClass);
|
|
3352
|
+
if (RegisteredImpl) {
|
|
3353
|
+
logger.debug(`[ContentNavigator.create] Using registered navigator: ${implementingClass}`);
|
|
3354
|
+
return new RegisteredImpl(user, course, strategyData);
|
|
1386
3355
|
}
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
3356
|
+
logger.debug(
|
|
3357
|
+
`[ContentNavigator.create] Navigator not in registry, attempting dynamic import: ${implementingClass}`
|
|
3358
|
+
);
|
|
3359
|
+
let NavigatorImpl;
|
|
3360
|
+
const variations = [".ts", ".js", ""];
|
|
3361
|
+
for (const ext of variations) {
|
|
3362
|
+
try {
|
|
3363
|
+
const module = await globImport_generators(`./generators/${implementingClass}${ext}`);
|
|
3364
|
+
NavigatorImpl = module.default;
|
|
3365
|
+
if (NavigatorImpl) break;
|
|
3366
|
+
} catch (e) {
|
|
3367
|
+
logger.debug(`Failed to load generator ${implementingClass}${ext}:`, e);
|
|
3368
|
+
}
|
|
3369
|
+
try {
|
|
3370
|
+
const module = await globImport_filters(`./filters/${implementingClass}${ext}`);
|
|
3371
|
+
NavigatorImpl = module.default;
|
|
3372
|
+
if (NavigatorImpl) break;
|
|
3373
|
+
} catch (e) {
|
|
3374
|
+
logger.debug(`Failed to load filter ${implementingClass}${ext}:`, e);
|
|
3375
|
+
}
|
|
3376
|
+
try {
|
|
3377
|
+
const module = await globImport(`./${implementingClass}${ext}`);
|
|
3378
|
+
NavigatorImpl = module.default;
|
|
3379
|
+
if (NavigatorImpl) break;
|
|
3380
|
+
} catch (e) {
|
|
3381
|
+
logger.debug(`Failed to load legacy ${implementingClass}${ext}:`, e);
|
|
3382
|
+
}
|
|
3383
|
+
if (NavigatorImpl) break;
|
|
3384
|
+
}
|
|
3385
|
+
if (!NavigatorImpl) {
|
|
3386
|
+
throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
|
|
3387
|
+
}
|
|
3388
|
+
return new NavigatorImpl(user, course, strategyData);
|
|
1411
3389
|
}
|
|
1412
3390
|
/**
|
|
1413
|
-
*
|
|
3391
|
+
* Get cards with suitability scores and provenance trails.
|
|
1414
3392
|
*
|
|
1415
|
-
*
|
|
1416
|
-
* 1. Relative overdueness = hoursOverdue / intervalHours
|
|
1417
|
-
* - 2 days overdue on 3-day interval = 0.67 (urgent)
|
|
1418
|
-
* - 2 days overdue on 180-day interval = 0.01 (not urgent)
|
|
3393
|
+
* **This is the PRIMARY API for navigation strategies.**
|
|
1419
3394
|
*
|
|
1420
|
-
*
|
|
1421
|
-
*
|
|
1422
|
-
*
|
|
1423
|
-
*
|
|
3395
|
+
* Returns cards ranked by suitability score (0-1). Higher scores indicate
|
|
3396
|
+
* better candidates for presentation. Each card includes a provenance trail
|
|
3397
|
+
* documenting how strategies contributed to the final score.
|
|
3398
|
+
*
|
|
3399
|
+
* ## Implementation Required
|
|
3400
|
+
* All navigation strategies MUST override this method. The base class does
|
|
3401
|
+
* not provide a default implementation.
|
|
3402
|
+
*
|
|
3403
|
+
* ## For Generators
|
|
3404
|
+
* Override this method to generate candidates and compute scores based on
|
|
3405
|
+
* your strategy's logic (e.g., ELO proximity, review urgency). Create the
|
|
3406
|
+
* initial provenance entry with action='generated'.
|
|
3407
|
+
*
|
|
3408
|
+
* ## For Filters
|
|
3409
|
+
* Filters should implement the CardFilter interface instead and be composed
|
|
3410
|
+
* via Pipeline. Filters do not directly implement getWeightedCards().
|
|
1424
3411
|
*
|
|
1425
|
-
*
|
|
1426
|
-
*
|
|
3412
|
+
* @param limit - Maximum cards to return
|
|
3413
|
+
* @returns Cards sorted by score descending, with provenance trails
|
|
1427
3414
|
*/
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
const due = moment3.utc(review.reviewTime);
|
|
1431
|
-
const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
|
|
1432
|
-
const hoursOverdue = now.diff(due, "hours");
|
|
1433
|
-
const relativeOverdue = hoursOverdue / intervalHours;
|
|
1434
|
-
const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
|
|
1435
|
-
const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
|
|
1436
|
-
const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
|
|
1437
|
-
const score = Math.min(0.95, 0.5 + urgency * 0.45);
|
|
1438
|
-
const reason = `${Math.round(hoursOverdue)}h overdue (interval: ${Math.round(intervalHours)}h, relative: ${relativeOverdue.toFixed(2)}), recency: ${recencyFactor.toFixed(2)}, review`;
|
|
1439
|
-
return { score, reason };
|
|
3415
|
+
async getWeightedCards(_limit) {
|
|
3416
|
+
throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);
|
|
1440
3417
|
}
|
|
1441
3418
|
};
|
|
1442
3419
|
}
|
|
1443
3420
|
});
|
|
1444
3421
|
|
|
1445
|
-
// src/core/navigators/filters/eloDistance.ts
|
|
1446
|
-
function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
|
|
1447
|
-
const normalizedDistance = distance / halfLife;
|
|
1448
|
-
const decay = Math.exp(-(normalizedDistance * normalizedDistance));
|
|
1449
|
-
return minMultiplier + (maxMultiplier - minMultiplier) * decay;
|
|
1450
|
-
}
|
|
1451
|
-
function createEloDistanceFilter(config) {
|
|
1452
|
-
const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
|
|
1453
|
-
const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
|
|
1454
|
-
const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
|
|
1455
|
-
return {
|
|
1456
|
-
name: "ELO Distance Filter",
|
|
1457
|
-
async transform(cards, context) {
|
|
1458
|
-
const { course, userElo } = context;
|
|
1459
|
-
const cardIds = cards.map((c) => c.cardId);
|
|
1460
|
-
const cardElos = await course.getCardEloData(cardIds);
|
|
1461
|
-
return cards.map((card, i) => {
|
|
1462
|
-
const cardElo = cardElos[i]?.global?.score ?? 1e3;
|
|
1463
|
-
const distance = Math.abs(cardElo - userElo);
|
|
1464
|
-
const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
|
|
1465
|
-
const newScore = card.score * multiplier;
|
|
1466
|
-
const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
|
|
1467
|
-
return {
|
|
1468
|
-
...card,
|
|
1469
|
-
score: newScore,
|
|
1470
|
-
provenance: [
|
|
1471
|
-
...card.provenance,
|
|
1472
|
-
{
|
|
1473
|
-
strategy: "eloDistance",
|
|
1474
|
-
strategyName: "ELO Distance Filter",
|
|
1475
|
-
strategyId: "ELO_DISTANCE_FILTER",
|
|
1476
|
-
action,
|
|
1477
|
-
score: newScore,
|
|
1478
|
-
reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
|
|
1479
|
-
}
|
|
1480
|
-
]
|
|
1481
|
-
};
|
|
1482
|
-
});
|
|
1483
|
-
}
|
|
1484
|
-
};
|
|
1485
|
-
}
|
|
1486
|
-
var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
|
|
1487
|
-
var init_eloDistance = __esm({
|
|
1488
|
-
"src/core/navigators/filters/eloDistance.ts"() {
|
|
1489
|
-
"use strict";
|
|
1490
|
-
DEFAULT_HALF_LIFE = 200;
|
|
1491
|
-
DEFAULT_MIN_MULTIPLIER = 0.3;
|
|
1492
|
-
DEFAULT_MAX_MULTIPLIER = 1;
|
|
1493
|
-
}
|
|
1494
|
-
});
|
|
1495
|
-
|
|
1496
|
-
// src/core/navigators/defaults.ts
|
|
1497
|
-
function createDefaultEloStrategy(courseId) {
|
|
1498
|
-
return {
|
|
1499
|
-
_id: "NAVIGATION_STRATEGY-ELO-default",
|
|
1500
|
-
docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
|
|
1501
|
-
name: "ELO (default)",
|
|
1502
|
-
description: "Default ELO-based navigation strategy for new cards",
|
|
1503
|
-
implementingClass: "elo" /* ELO */,
|
|
1504
|
-
course: courseId,
|
|
1505
|
-
serializedData: ""
|
|
1506
|
-
};
|
|
1507
|
-
}
|
|
1508
|
-
function createDefaultSrsStrategy(courseId) {
|
|
1509
|
-
return {
|
|
1510
|
-
_id: "NAVIGATION_STRATEGY-SRS-default",
|
|
1511
|
-
docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
|
|
1512
|
-
name: "SRS (default)",
|
|
1513
|
-
description: "Default SRS-based navigation strategy for reviews",
|
|
1514
|
-
implementingClass: "srs" /* SRS */,
|
|
1515
|
-
course: courseId,
|
|
1516
|
-
serializedData: ""
|
|
1517
|
-
};
|
|
1518
|
-
}
|
|
1519
|
-
function createDefaultPipeline(user, course) {
|
|
1520
|
-
const courseId = course.getCourseID();
|
|
1521
|
-
const eloNavigator = new ELONavigator(user, course, createDefaultEloStrategy(courseId));
|
|
1522
|
-
const srsNavigator = new SRSNavigator(user, course, createDefaultSrsStrategy(courseId));
|
|
1523
|
-
const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);
|
|
1524
|
-
const eloDistanceFilter = createEloDistanceFilter();
|
|
1525
|
-
return new Pipeline(compositeGenerator, [eloDistanceFilter], user, course);
|
|
1526
|
-
}
|
|
1527
|
-
var init_defaults = __esm({
|
|
1528
|
-
"src/core/navigators/defaults.ts"() {
|
|
1529
|
-
"use strict";
|
|
1530
|
-
init_navigators();
|
|
1531
|
-
init_Pipeline();
|
|
1532
|
-
init_CompositeGenerator();
|
|
1533
|
-
init_elo();
|
|
1534
|
-
init_srs();
|
|
1535
|
-
init_eloDistance();
|
|
1536
|
-
init_types_legacy();
|
|
1537
|
-
}
|
|
1538
|
-
});
|
|
1539
|
-
|
|
1540
3422
|
// src/impl/couch/courseDB.ts
|
|
1541
3423
|
import {
|
|
1542
3424
|
EloToNumber,
|
|
1543
3425
|
Status,
|
|
1544
3426
|
blankCourseElo as blankCourseElo2,
|
|
1545
|
-
toCourseElo as
|
|
3427
|
+
toCourseElo as toCourseElo6
|
|
1546
3428
|
} from "@vue-skuilder/common";
|
|
1547
3429
|
function randIntWeightedTowardZero(n) {
|
|
1548
3430
|
return Math.floor(Math.random() * Math.random() * Math.random() * n);
|
|
@@ -1699,7 +3581,7 @@ var init_courseDB = __esm({
|
|
|
1699
3581
|
docs.rows.forEach((r) => {
|
|
1700
3582
|
if (isSuccessRow(r)) {
|
|
1701
3583
|
if (r.doc && r.doc.elo) {
|
|
1702
|
-
ret.push(
|
|
3584
|
+
ret.push(toCourseElo6(r.doc.elo));
|
|
1703
3585
|
} else {
|
|
1704
3586
|
logger.warn("no elo data for card: " + r.id);
|
|
1705
3587
|
ret.push(blankCourseElo2());
|
|
@@ -3444,6 +5326,19 @@ Currently logged-in as ${this._username}.`
|
|
|
3444
5326
|
};
|
|
3445
5327
|
await this.localDB.put(doc);
|
|
3446
5328
|
}
|
|
5329
|
+
async putUserOutcome(record) {
|
|
5330
|
+
try {
|
|
5331
|
+
await this.localDB.put(record);
|
|
5332
|
+
} catch (err) {
|
|
5333
|
+
if (err.status === 409) {
|
|
5334
|
+
const existing = await this.localDB.get(record._id);
|
|
5335
|
+
record._rev = existing._rev;
|
|
5336
|
+
await this.localDB.put(record);
|
|
5337
|
+
} else {
|
|
5338
|
+
throw err;
|
|
5339
|
+
}
|
|
5340
|
+
}
|
|
5341
|
+
}
|
|
3447
5342
|
async deleteStrategyState(courseId, strategyKey) {
|
|
3448
5343
|
const docId = buildStrategyStateId(courseId, strategyKey);
|
|
3449
5344
|
try {
|
|
@@ -3486,6 +5381,7 @@ var init_factory = __esm({
|
|
|
3486
5381
|
"use strict";
|
|
3487
5382
|
init_common();
|
|
3488
5383
|
init_logger();
|
|
5384
|
+
init_navigators();
|
|
3489
5385
|
NOT_SET = "NOT_SET";
|
|
3490
5386
|
ENV = {
|
|
3491
5387
|
COUCHDB_SERVER_PROTOCOL: NOT_SET,
|
|
@@ -3742,6 +5638,13 @@ var init_strategyState = __esm({
|
|
|
3742
5638
|
}
|
|
3743
5639
|
});
|
|
3744
5640
|
|
|
5641
|
+
// src/core/types/userOutcome.ts
|
|
5642
|
+
var init_userOutcome = __esm({
|
|
5643
|
+
"src/core/types/userOutcome.ts"() {
|
|
5644
|
+
"use strict";
|
|
5645
|
+
}
|
|
5646
|
+
});
|
|
5647
|
+
|
|
3745
5648
|
// src/core/bulkImport/cardProcessor.ts
|
|
3746
5649
|
import { Status as Status4 } from "@vue-skuilder/common";
|
|
3747
5650
|
async function importParsedCards(parsedCards, courseDB, config) {
|
|
@@ -3863,7 +5766,7 @@ var init_cardProcessor = __esm({
|
|
|
3863
5766
|
});
|
|
3864
5767
|
|
|
3865
5768
|
// src/core/bulkImport/types.ts
|
|
3866
|
-
var
|
|
5769
|
+
var init_types3 = __esm({
|
|
3867
5770
|
"src/core/bulkImport/types.ts"() {
|
|
3868
5771
|
"use strict";
|
|
3869
5772
|
}
|
|
@@ -3874,7 +5777,7 @@ var init_bulkImport = __esm({
|
|
|
3874
5777
|
"src/core/bulkImport/index.ts"() {
|
|
3875
5778
|
"use strict";
|
|
3876
5779
|
init_cardProcessor();
|
|
3877
|
-
|
|
5780
|
+
init_types3();
|
|
3878
5781
|
}
|
|
3879
5782
|
});
|
|
3880
5783
|
|
|
@@ -3885,10 +5788,12 @@ var init_core = __esm({
|
|
|
3885
5788
|
init_types_legacy();
|
|
3886
5789
|
init_user();
|
|
3887
5790
|
init_strategyState();
|
|
5791
|
+
init_userOutcome();
|
|
3888
5792
|
init_Loggable();
|
|
3889
5793
|
init_util();
|
|
3890
5794
|
init_navigators();
|
|
3891
5795
|
init_bulkImport();
|
|
5796
|
+
init_orchestration();
|
|
3892
5797
|
}
|
|
3893
5798
|
});
|
|
3894
5799
|
init_core();
|
|
@@ -3901,19 +5806,39 @@ export {
|
|
|
3901
5806
|
NavigatorRole,
|
|
3902
5807
|
NavigatorRoles,
|
|
3903
5808
|
Navigators,
|
|
5809
|
+
aggregateOutcomesForGradient,
|
|
3904
5810
|
areQuestionRecords,
|
|
3905
5811
|
buildStrategyStateId,
|
|
5812
|
+
computeDeviation,
|
|
5813
|
+
computeEffectiveWeight,
|
|
5814
|
+
computeOutcomeSignal,
|
|
5815
|
+
computeSpread,
|
|
5816
|
+
computeStrategyGradient,
|
|
5817
|
+
createOrchestrationContext,
|
|
3906
5818
|
docIsDeleted,
|
|
3907
5819
|
getCardHistoryID,
|
|
3908
5820
|
getCardOrigin,
|
|
5821
|
+
getDefaultLearnableWeight,
|
|
5822
|
+
getRegisteredNavigator,
|
|
5823
|
+
getRegisteredNavigatorNames,
|
|
3909
5824
|
getStudySource,
|
|
5825
|
+
hasRegisteredNavigator,
|
|
3910
5826
|
importParsedCards,
|
|
5827
|
+
initializeNavigatorRegistry,
|
|
3911
5828
|
isFilter,
|
|
3912
5829
|
isGenerator,
|
|
3913
5830
|
isQuestionRecord,
|
|
3914
5831
|
isReview,
|
|
3915
5832
|
log,
|
|
5833
|
+
mountPipelineDebugger,
|
|
3916
5834
|
parseCardHistoryID,
|
|
5835
|
+
pipelineDebugAPI,
|
|
5836
|
+
recordUserOutcome,
|
|
5837
|
+
registerNavigator,
|
|
5838
|
+
runPeriodUpdate,
|
|
5839
|
+
scoreAccuracyInZone,
|
|
5840
|
+
updateLearningState,
|
|
5841
|
+
updateStrategyWeight,
|
|
3917
5842
|
validateProcessorConfig
|
|
3918
5843
|
};
|
|
3919
5844
|
//# sourceMappingURL=index.mjs.map
|