@vue-skuilder/db 0.1.32-c → 0.1.33-vite8-4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{dataLayerProvider-BAn-LRh5.d.ts → contentSource-BMlMwSiG.d.cts} +202 -626
- package/dist/{dataLayerProvider-BJqBlMIl.d.cts → contentSource-Ht3N2f-y.d.ts} +202 -626
- package/dist/core/index.d.cts +40 -84
- package/dist/core/index.d.ts +40 -84
- package/dist/core/index.js +907 -1821
- package/dist/core/index.js.map +1 -1
- package/dist/core/index.mjs +886 -1804
- package/dist/core/index.mjs.map +1 -1
- package/dist/dataLayerProvider-BEqB8VBR.d.cts +67 -0
- package/dist/dataLayerProvider-DObSXjnf.d.ts +67 -0
- package/dist/impl/couch/index.d.cts +5 -5
- package/dist/impl/couch/index.d.ts +5 -5
- package/dist/impl/couch/index.js +913 -1827
- package/dist/impl/couch/index.js.map +1 -1
- package/dist/impl/couch/index.mjs +892 -1810
- package/dist/impl/couch/index.mjs.map +1 -1
- package/dist/impl/static/index.d.cts +5 -4
- package/dist/impl/static/index.d.ts +5 -4
- package/dist/impl/static/index.js +892 -1806
- package/dist/impl/static/index.js.map +1 -1
- package/dist/impl/static/index.mjs +888 -1806
- package/dist/impl/static/index.mjs.map +1 -1
- package/dist/{index-X6wHrURm.d.ts → index-BWvO-_rJ.d.ts} +1 -1
- package/dist/{index-m8MMGxxR.d.cts → index-Ba7hYbHj.d.cts} +1 -1
- package/dist/index.d.cts +461 -11
- package/dist/index.d.ts +461 -11
- package/dist/index.js +9651 -9142
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +9619 -9110
- package/dist/index.mjs.map +1 -1
- package/dist/{types-DZ5dUqbL.d.ts → types-CJrLM1Ew.d.ts} +1 -1
- package/dist/{types-ZL8tOPQZ.d.cts → types-W8n-B6HG.d.cts} +1 -1
- package/dist/{types-legacy-C7r0T4OV.d.cts → types-legacy-JXDxinpU.d.cts} +1 -1
- package/dist/{types-legacy-C7r0T4OV.d.ts → types-legacy-JXDxinpU.d.ts} +1 -1
- package/dist/util/packer/index.d.cts +3 -3
- package/dist/util/packer/index.d.ts +3 -3
- package/package.json +4 -4
- package/src/core/interfaces/contentSource.ts +2 -3
- package/src/core/navigators/Pipeline.ts +164 -19
- package/src/core/navigators/PipelineDebugger.ts +399 -3
- package/src/core/navigators/filters/hierarchyDefinition.ts +2 -1
- package/src/core/navigators/filters/interferenceMitigator.ts +2 -1
- package/src/core/navigators/filters/relativePriority.ts +2 -1
- package/src/core/navigators/filters/userTagPreference.ts +2 -1
- package/src/core/navigators/generators/CompositeGenerator.ts +62 -6
- package/src/core/navigators/generators/elo.ts +7 -7
- package/src/core/navigators/generators/prescribed.ts +367 -54
- package/src/core/navigators/generators/srs.ts +3 -4
- package/src/core/navigators/generators/types.ts +48 -2
- package/src/core/navigators/index.ts +3 -3
- package/src/impl/couch/classroomDB.ts +4 -3
- package/src/impl/couch/courseDB.ts +3 -3
- package/src/impl/static/courseDB.ts +3 -3
- package/src/study/SessionController.ts +5 -27
- package/src/study/TagFilteredContentSource.ts +4 -3
- package/tests/core/navigators/CompositeGenerator.test.ts +14 -50
- package/tests/core/navigators/Pipeline.test.ts +13 -12
package/dist/core/index.js
CHANGED
|
@@ -735,8 +735,9 @@ function getOrigin(card) {
|
|
|
735
735
|
const firstEntry = card.provenance[0];
|
|
736
736
|
if (!firstEntry) return "unknown";
|
|
737
737
|
const reason = firstEntry.reason?.toLowerCase() || "";
|
|
738
|
-
|
|
739
|
-
if (reason.includes("
|
|
738
|
+
const strategy = firstEntry.strategy?.toLowerCase() || "";
|
|
739
|
+
if (reason.includes("new card") || strategy.includes("elo")) return "new";
|
|
740
|
+
if (reason.includes("review") || strategy.includes("srs")) return "review";
|
|
740
741
|
return "unknown";
|
|
741
742
|
}
|
|
742
743
|
function captureRun(report) {
|
|
@@ -756,12 +757,13 @@ function parseCardElo(provenance) {
|
|
|
756
757
|
const match = eloEntry.reason.match(/card:\s*(\d+)/);
|
|
757
758
|
return match ? parseInt(match[1], 10) : void 0;
|
|
758
759
|
}
|
|
759
|
-
function buildRunReport(courseId, courseName, generatorName, generators, generatedCount, filters, allCards, selectedCards, userElo) {
|
|
760
|
+
function buildRunReport(courseId, courseName, generatorName, generators, generatedCount, filters, allCards, selectedCards, userElo, hints) {
|
|
760
761
|
const selectedIds = new Set(selectedCards.map((c) => c.cardId));
|
|
761
762
|
const cards = allCards.map((card) => ({
|
|
762
763
|
cardId: card.cardId,
|
|
763
764
|
courseId: card.courseId,
|
|
764
765
|
origin: getOrigin(card),
|
|
766
|
+
generator: card.provenance[0]?.strategyName || card.provenance[0]?.strategy,
|
|
765
767
|
finalScore: card.score,
|
|
766
768
|
cardElo: parseCardElo(card.provenance),
|
|
767
769
|
provenance: card.provenance,
|
|
@@ -778,6 +780,7 @@ function buildRunReport(courseId, courseName, generatorName, generators, generat
|
|
|
778
780
|
generators,
|
|
779
781
|
generatedCount,
|
|
780
782
|
filters,
|
|
783
|
+
hints,
|
|
781
784
|
finalCount: selectedCards.length,
|
|
782
785
|
reviewsSelected,
|
|
783
786
|
newSelected,
|
|
@@ -817,13 +820,169 @@ function printRunSummary(run) {
|
|
|
817
820
|
);
|
|
818
821
|
console.groupEnd();
|
|
819
822
|
}
|
|
823
|
+
function renderUI() {
|
|
824
|
+
if (!_uiContainer) return;
|
|
825
|
+
const runs = runHistory;
|
|
826
|
+
const selectedRun = _selectedRunIndex !== null ? runs[_selectedRunIndex] : null;
|
|
827
|
+
const styles = `
|
|
828
|
+
#sk-pipeline-debugger {
|
|
829
|
+
position: fixed;
|
|
830
|
+
top: 0;
|
|
831
|
+
left: 0;
|
|
832
|
+
width: 100vw;
|
|
833
|
+
height: 100vh;
|
|
834
|
+
background: #f8f9fa;
|
|
835
|
+
color: #212529;
|
|
836
|
+
z-index: 999999;
|
|
837
|
+
display: flex;
|
|
838
|
+
flex-direction: column;
|
|
839
|
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
|
840
|
+
font-size: 14px;
|
|
841
|
+
}
|
|
842
|
+
#sk-pipeline-debugger header {
|
|
843
|
+
padding: 1rem;
|
|
844
|
+
background: #343a40;
|
|
845
|
+
color: white;
|
|
846
|
+
display: flex;
|
|
847
|
+
justify-content: space-between;
|
|
848
|
+
align-items: center;
|
|
849
|
+
}
|
|
850
|
+
#sk-pipeline-debugger .container {
|
|
851
|
+
display: flex;
|
|
852
|
+
flex: 1;
|
|
853
|
+
overflow: hidden;
|
|
854
|
+
}
|
|
855
|
+
#sk-pipeline-debugger .sidebar {
|
|
856
|
+
width: 300px;
|
|
857
|
+
border-right: 1px solid #dee2e6;
|
|
858
|
+
overflow-y: auto;
|
|
859
|
+
background: white;
|
|
860
|
+
}
|
|
861
|
+
#sk-pipeline-debugger .main-content {
|
|
862
|
+
flex: 1;
|
|
863
|
+
overflow-y: auto;
|
|
864
|
+
padding: 1.5rem;
|
|
865
|
+
}
|
|
866
|
+
#sk-pipeline-debugger .run-item {
|
|
867
|
+
padding: 0.75rem 1rem;
|
|
868
|
+
border-bottom: 1px solid #eee;
|
|
869
|
+
cursor: pointer;
|
|
870
|
+
}
|
|
871
|
+
#sk-pipeline-debugger .run-item:hover { background: #f1f3f5; }
|
|
872
|
+
#sk-pipeline-debugger .run-item.active { background: #e9ecef; border-left: 4px solid #007bff; }
|
|
873
|
+
#sk-pipeline-debugger h2, #sk-pipeline-debugger h3 { margin-top: 0; }
|
|
874
|
+
#sk-pipeline-debugger table { width: 100%; border-collapse: collapse; margin-bottom: 1rem; background: white; }
|
|
875
|
+
#sk-pipeline-debugger th, #sk-pipeline-debugger td { border: 1px solid #dee2e6; padding: 0.5rem; text-align: left; }
|
|
876
|
+
#sk-pipeline-debugger th { background: #f1f3f5; }
|
|
877
|
+
#sk-pipeline-debugger code { background: #f1f3f5; padding: 0.1rem 0.3rem; border-radius: 3px; font-family: monospace; }
|
|
878
|
+
#sk-pipeline-debugger .close-btn { background: #dc3545; color: white; border: none; padding: 0.5rem 1rem; border-radius: 4px; cursor: pointer; }
|
|
879
|
+
#sk-pipeline-debugger .search-box { margin-bottom: 1rem; width: 100%; padding: 0.5rem; border: 1px solid #ced4da; border-radius: 4px; }
|
|
880
|
+
#sk-pipeline-debugger .provenance { font-size: 12px; color: #666; margin-top: 0.25rem; white-space: pre-wrap; font-family: monospace; background: #f8f9fa; padding: 0.5rem; border-radius: 4px; }
|
|
881
|
+
`;
|
|
882
|
+
const runListHtml = runs.length === 0 ? '<div style="padding: 1rem;">No runs captured yet.</div>' : runs.map(
|
|
883
|
+
(r, i) => `
|
|
884
|
+
<div class="run-item ${i === _selectedRunIndex ? "active" : ""}" onclick="window.skuilder.pipeline._selectRun(${i})">
|
|
885
|
+
<strong>${r.timestamp.toLocaleTimeString()}</strong><br/>
|
|
886
|
+
<small>${r.courseName || r.courseId.slice(0, 8)}</small><br/>
|
|
887
|
+
<small>${r.finalCount} cards selected</small>
|
|
888
|
+
</div>
|
|
889
|
+
`
|
|
890
|
+
).join("");
|
|
891
|
+
let detailsHtml = '<div style="color: #6c757d; text-align: center; margin-top: 5rem;">Select a run to see details</div>';
|
|
892
|
+
if (selectedRun) {
|
|
893
|
+
const filteredCards = selectedRun.cards.filter(
|
|
894
|
+
(c) => !_cardSearchQuery || c.cardId.toLowerCase().includes(_cardSearchQuery.toLowerCase())
|
|
895
|
+
);
|
|
896
|
+
detailsHtml = `
|
|
897
|
+
<h2>Run: ${selectedRun.runId}</h2>
|
|
898
|
+
<p>
|
|
899
|
+
<strong>Time:</strong> ${selectedRun.timestamp.toLocaleString()} |
|
|
900
|
+
<strong>Course:</strong> ${selectedRun.courseName || selectedRun.courseId} |
|
|
901
|
+
<strong>User ELO:</strong> ${selectedRun.userElo ?? "unknown"}
|
|
902
|
+
</p>
|
|
903
|
+
|
|
904
|
+
<h3>Pipeline Config</h3>
|
|
905
|
+
<table>
|
|
906
|
+
<tr><th>Generator</th><td>${selectedRun.generatorName} (${selectedRun.generatedCount} candidates)</td></tr>
|
|
907
|
+
${(selectedRun.generators || []).map(
|
|
908
|
+
(g) => `
|
|
909
|
+
<tr><td style="padding-left: 2rem;">\u21B3 ${g.name}</td><td>${g.cardCount} cards (${g.newCount} new, ${g.reviewCount} review, top: ${g.topScore.toFixed(2)})</td></tr>
|
|
910
|
+
`
|
|
911
|
+
).join("")}
|
|
912
|
+
</table>
|
|
913
|
+
|
|
914
|
+
${selectedRun.hints ? `
|
|
915
|
+
<h3>Ephemeral Hints</h3>
|
|
916
|
+
<table>
|
|
917
|
+
${selectedRun.hints._label ? `<tr><th>Label</th><td>${selectedRun.hints._label}</td></tr>` : ""}
|
|
918
|
+
${selectedRun.hints.boostTags ? `<tr><th>Boost Tags</th><td><pre style="margin:0">${JSON.stringify(selectedRun.hints.boostTags, null, 2)}</pre></td></tr>` : ""}
|
|
919
|
+
${selectedRun.hints.boostCards ? `<tr><th>Boost Cards</th><td><pre style="margin:0">${JSON.stringify(selectedRun.hints.boostCards, null, 2)}</pre></td></tr>` : ""}
|
|
920
|
+
${selectedRun.hints.requireTags ? `<tr><th>Require Tags</th><td>${selectedRun.hints.requireTags.join(", ")}</td></tr>` : ""}
|
|
921
|
+
${selectedRun.hints.requireCards ? `<tr><th>Require Cards</th><td>${selectedRun.hints.requireCards.join(", ")}</td></tr>` : ""}
|
|
922
|
+
${selectedRun.hints.excludeTags ? `<tr><th>Exclude Tags</th><td>${selectedRun.hints.excludeTags.join(", ")}</td></tr>` : ""}
|
|
923
|
+
${selectedRun.hints.excludeCards ? `<tr><th>Exclude Cards</th><td>${selectedRun.hints.excludeCards.join(", ")}</td></tr>` : ""}
|
|
924
|
+
</table>
|
|
925
|
+
` : ""}
|
|
926
|
+
|
|
927
|
+
<h3>Filter Impact</h3>
|
|
928
|
+
<table>
|
|
929
|
+
<thead><tr><th>Filter</th><th>Boosted</th><th>Penalized</th><th>Passed</th><th>Removed</th></tr></thead>
|
|
930
|
+
<tbody>
|
|
931
|
+
${selectedRun.filters.map(
|
|
932
|
+
(f) => `
|
|
933
|
+
<tr><td>${f.name}</td><td>\u2191${f.boosted}</td><td>\u2193${f.penalized}</td><td>=${f.passed}</td><td>\u2715${f.removed}</td></tr>
|
|
934
|
+
`
|
|
935
|
+
).join("")}
|
|
936
|
+
</tbody>
|
|
937
|
+
</table>
|
|
938
|
+
|
|
939
|
+
<h3>Cards (${selectedRun.finalCount} selected / ${selectedRun.cards.length} total)</h3>
|
|
940
|
+
<input type="text" class="search-box" placeholder="Search Card ID..." value="${_cardSearchQuery}" oninput="window.skuilder.pipeline._setSearch(this.value)">
|
|
941
|
+
|
|
942
|
+
<table>
|
|
943
|
+
<thead><tr><th>ID</th><th>Generator</th><th>Origin</th><th>Score</th><th>Selected</th></tr></thead>
|
|
944
|
+
<tbody>
|
|
945
|
+
${filteredCards.map(
|
|
946
|
+
(c) => `
|
|
947
|
+
<tr>
|
|
948
|
+
<td><code>${c.cardId}</code></td>
|
|
949
|
+
<td>${c.generator || "unknown"}</td>
|
|
950
|
+
<td>${c.origin}</td>
|
|
951
|
+
<td>${c.finalScore.toFixed(3)}</td>
|
|
952
|
+
<td>${c.selected ? "\u2705" : "\u274C"}</td>
|
|
953
|
+
</tr>
|
|
954
|
+
${c.selected || _cardSearchQuery ? `
|
|
955
|
+
<tr>
|
|
956
|
+
<td colspan="5">
|
|
957
|
+
<div class="provenance">${formatProvenance(c.provenance)}</div>
|
|
958
|
+
</td>
|
|
959
|
+
</tr>
|
|
960
|
+
` : ""}
|
|
961
|
+
`
|
|
962
|
+
).join("")}
|
|
963
|
+
</tbody>
|
|
964
|
+
</table>
|
|
965
|
+
`;
|
|
966
|
+
}
|
|
967
|
+
_uiContainer.innerHTML = `
|
|
968
|
+
<style>${styles}</style>
|
|
969
|
+
<header>
|
|
970
|
+
<strong>Pipeline Debugger</strong>
|
|
971
|
+
<button class="close-btn" onclick="window.skuilder.pipeline.ui()">Close</button>
|
|
972
|
+
</header>
|
|
973
|
+
<div class="container">
|
|
974
|
+
<div class="sidebar">${runListHtml}</div>
|
|
975
|
+
<div class="main-content">${detailsHtml}</div>
|
|
976
|
+
</div>
|
|
977
|
+
`;
|
|
978
|
+
}
|
|
820
979
|
function mountPipelineDebugger() {
|
|
821
980
|
if (typeof window === "undefined") return;
|
|
822
981
|
const win = window;
|
|
823
982
|
win.skuilder = win.skuilder || {};
|
|
824
983
|
win.skuilder.pipeline = pipelineDebugAPI;
|
|
825
984
|
}
|
|
826
|
-
var _activePipeline, MAX_RUNS, runHistory, pipelineDebugAPI;
|
|
985
|
+
var _activePipeline, MAX_RUNS, runHistory, _uiContainer, _selectedRunIndex, _cardSearchQuery, pipelineDebugAPI;
|
|
827
986
|
var init_PipelineDebugger = __esm({
|
|
828
987
|
"src/core/navigators/PipelineDebugger.ts"() {
|
|
829
988
|
"use strict";
|
|
@@ -832,6 +991,9 @@ var init_PipelineDebugger = __esm({
|
|
|
832
991
|
_activePipeline = null;
|
|
833
992
|
MAX_RUNS = 10;
|
|
834
993
|
runHistory = [];
|
|
994
|
+
_uiContainer = null;
|
|
995
|
+
_selectedRunIndex = null;
|
|
996
|
+
_cardSearchQuery = "";
|
|
835
997
|
pipelineDebugAPI = {
|
|
836
998
|
/**
|
|
837
999
|
* Get raw run history for programmatic access.
|
|
@@ -939,6 +1101,100 @@ var init_PipelineDebugger = __esm({
|
|
|
939
1101
|
}
|
|
940
1102
|
console.groupEnd();
|
|
941
1103
|
},
|
|
1104
|
+
/**
|
|
1105
|
+
* Show prescribed-related cards from the most recent run.
|
|
1106
|
+
*
|
|
1107
|
+
* Highlights:
|
|
1108
|
+
* - cards directly generated by the prescribed strategy
|
|
1109
|
+
* - blocked prescribed targets mentioned in provenance
|
|
1110
|
+
* - support tags resolved for blocked targets
|
|
1111
|
+
*
|
|
1112
|
+
* @param groupId - Optional prescribed group ID filter (e.g. 'intro-core')
|
|
1113
|
+
*/
|
|
1114
|
+
showPrescribed(groupId) {
|
|
1115
|
+
if (runHistory.length === 0) {
|
|
1116
|
+
logger.info("[Pipeline Debug] No runs captured yet.");
|
|
1117
|
+
return;
|
|
1118
|
+
}
|
|
1119
|
+
const run = runHistory[0];
|
|
1120
|
+
const prescribedCards = run.cards.filter(
|
|
1121
|
+
(c) => c.provenance.some((p) => p.strategy === "prescribed")
|
|
1122
|
+
);
|
|
1123
|
+
console.group(`\u{1F9ED} Prescribed Debug (${run.courseId})`);
|
|
1124
|
+
if (prescribedCards.length === 0) {
|
|
1125
|
+
logger.info("No prescribed-generated cards were present in the most recent run.");
|
|
1126
|
+
console.groupEnd();
|
|
1127
|
+
return;
|
|
1128
|
+
}
|
|
1129
|
+
const rows = prescribedCards.map((card) => {
|
|
1130
|
+
const prescribedProv = card.provenance.find((p) => p.strategy === "prescribed");
|
|
1131
|
+
const reason = prescribedProv?.reason ?? "";
|
|
1132
|
+
const parsedGroup = reason.match(/group=([^;]+)/)?.[1] ?? "unknown";
|
|
1133
|
+
const mode = reason.match(/mode=([^;]+)/)?.[1] ?? "unknown";
|
|
1134
|
+
const blocked = reason.match(/blocked=([^;]+)/)?.[1] ?? "unknown";
|
|
1135
|
+
const blockedTargets = reason.match(/blockedTargets=([^;]+)/)?.[1] ?? "none";
|
|
1136
|
+
const supportCard = reason.match(/supportCard=([^;]+)/)?.[1] ?? "none";
|
|
1137
|
+
const supportTags = reason.match(/supportTags=([^;]+)/)?.[1] ?? "none";
|
|
1138
|
+
const multiplier = reason.match(/multiplier=([^;]+)/)?.[1] ?? "unknown";
|
|
1139
|
+
const supportSource = mode === "discovered-support" ? "discovered" : mode === "support" ? "authored" : "n/a";
|
|
1140
|
+
return {
|
|
1141
|
+
group: parsedGroup,
|
|
1142
|
+
mode,
|
|
1143
|
+
supportSource,
|
|
1144
|
+
cardId: card.cardId,
|
|
1145
|
+
selected: card.selected ? "yes" : "no",
|
|
1146
|
+
finalScore: card.finalScore.toFixed(3),
|
|
1147
|
+
blocked,
|
|
1148
|
+
blockedTargets,
|
|
1149
|
+
supportCard,
|
|
1150
|
+
supportTags,
|
|
1151
|
+
multiplier
|
|
1152
|
+
};
|
|
1153
|
+
}).filter((row) => !groupId || row.group === groupId).sort((a, b) => Number(b.finalScore) - Number(a.finalScore));
|
|
1154
|
+
if (rows.length === 0) {
|
|
1155
|
+
logger.info(
|
|
1156
|
+
`[Pipeline Debug] No prescribed cards matched group '${groupId}' in the most recent run.`
|
|
1157
|
+
);
|
|
1158
|
+
console.groupEnd();
|
|
1159
|
+
return;
|
|
1160
|
+
}
|
|
1161
|
+
console.table(rows);
|
|
1162
|
+
const selectedRows = rows.filter((r) => r.selected === "yes");
|
|
1163
|
+
const blockedTargetSet = /* @__PURE__ */ new Set();
|
|
1164
|
+
const supportTagSet = /* @__PURE__ */ new Set();
|
|
1165
|
+
const authoredSupportSet = /* @__PURE__ */ new Set();
|
|
1166
|
+
const discoveredSupportSet = /* @__PURE__ */ new Set();
|
|
1167
|
+
for (const row of rows) {
|
|
1168
|
+
if (row.blockedTargets && row.blockedTargets !== "none") {
|
|
1169
|
+
row.blockedTargets.split("|").filter(Boolean).forEach((t) => blockedTargetSet.add(t));
|
|
1170
|
+
}
|
|
1171
|
+
if (row.supportTags && row.supportTags !== "none") {
|
|
1172
|
+
row.supportTags.split("|").filter(Boolean).forEach((t) => supportTagSet.add(t));
|
|
1173
|
+
}
|
|
1174
|
+
if (row.supportCard && row.supportCard !== "none") {
|
|
1175
|
+
if (row.supportSource === "discovered") {
|
|
1176
|
+
discoveredSupportSet.add(row.supportCard);
|
|
1177
|
+
} else if (row.supportSource === "authored") {
|
|
1178
|
+
authoredSupportSet.add(row.supportCard);
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
logger.info(`Prescribed cards in run: ${rows.length}`);
|
|
1183
|
+
logger.info(`Selected prescribed cards: ${selectedRows.length}`);
|
|
1184
|
+
logger.info(
|
|
1185
|
+
`Blocked prescribed targets referenced: ${blockedTargetSet.size > 0 ? [...blockedTargetSet].join(", ") : "none"}`
|
|
1186
|
+
);
|
|
1187
|
+
logger.info(
|
|
1188
|
+
`Resolved support tags referenced: ${supportTagSet.size > 0 ? [...supportTagSet].join(", ") : "none"}`
|
|
1189
|
+
);
|
|
1190
|
+
logger.info(
|
|
1191
|
+
`Authored support cards emitted: ${authoredSupportSet.size > 0 ? [...authoredSupportSet].join(", ") : "none"}`
|
|
1192
|
+
);
|
|
1193
|
+
logger.info(
|
|
1194
|
+
`Discovered support cards emitted: ${discoveredSupportSet.size > 0 ? [...discoveredSupportSet].join(", ") : "none"}`
|
|
1195
|
+
);
|
|
1196
|
+
console.groupEnd();
|
|
1197
|
+
},
|
|
942
1198
|
/**
|
|
943
1199
|
* Show all runs in compact format.
|
|
944
1200
|
*/
|
|
@@ -1071,6 +1327,39 @@ var init_PipelineDebugger = __esm({
|
|
|
1071
1327
|
Object.fromEntries(entries.map(([tag, data]) => [tag, { score: Math.round(data.score), count: data.count }]))
|
|
1072
1328
|
);
|
|
1073
1329
|
},
|
|
1330
|
+
/**
|
|
1331
|
+
* Toggle the full-screen UI debugger.
|
|
1332
|
+
*/
|
|
1333
|
+
ui() {
|
|
1334
|
+
if (_uiContainer) {
|
|
1335
|
+
document.body.removeChild(_uiContainer);
|
|
1336
|
+
_uiContainer = null;
|
|
1337
|
+
return;
|
|
1338
|
+
}
|
|
1339
|
+
_uiContainer = document.createElement("div");
|
|
1340
|
+
_uiContainer.id = "sk-pipeline-debugger";
|
|
1341
|
+
document.body.appendChild(_uiContainer);
|
|
1342
|
+
if (_selectedRunIndex === null && runHistory.length > 0) {
|
|
1343
|
+
_selectedRunIndex = 0;
|
|
1344
|
+
}
|
|
1345
|
+
renderUI();
|
|
1346
|
+
},
|
|
1347
|
+
/**
|
|
1348
|
+
* Internal UI helpers
|
|
1349
|
+
* @internal
|
|
1350
|
+
*/
|
|
1351
|
+
_selectRun(index) {
|
|
1352
|
+
_selectedRunIndex = index;
|
|
1353
|
+
renderUI();
|
|
1354
|
+
},
|
|
1355
|
+
/**
|
|
1356
|
+
* Internal UI helpers
|
|
1357
|
+
* @internal
|
|
1358
|
+
*/
|
|
1359
|
+
_setSearch(query) {
|
|
1360
|
+
_cardSearchQuery = query;
|
|
1361
|
+
renderUI();
|
|
1362
|
+
},
|
|
1074
1363
|
/**
|
|
1075
1364
|
* Show help.
|
|
1076
1365
|
*/
|
|
@@ -1079,6 +1368,7 @@ var init_PipelineDebugger = __esm({
|
|
|
1079
1368
|
\u{1F527} Pipeline Debug API
|
|
1080
1369
|
|
|
1081
1370
|
Commands:
|
|
1371
|
+
.ui() Toggle full-screen UI debugger
|
|
1082
1372
|
.showLastRun() Show summary of most recent pipeline run
|
|
1083
1373
|
.showRun(id|index) Show summary of a specific run (by index or ID suffix)
|
|
1084
1374
|
.showCard(cardId) Show provenance trail for a specific card
|
|
@@ -1087,6 +1377,7 @@ Commands:
|
|
|
1087
1377
|
.diagnoseCardSpace() Scan full card space through filters (async)
|
|
1088
1378
|
.showRegistry() Show navigator registry (classes + roles)
|
|
1089
1379
|
.showStrategies() Show registry + strategy mapping from last run
|
|
1380
|
+
.showPrescribed(id?) Show prescribed-generated cards and blocked/support details from last run
|
|
1090
1381
|
.listRuns() List all captured runs in table format
|
|
1091
1382
|
.export() Export run history as JSON for bug reports
|
|
1092
1383
|
.clear() Clear run history
|
|
@@ -1094,6 +1385,7 @@ Commands:
|
|
|
1094
1385
|
.help() Show this help message
|
|
1095
1386
|
|
|
1096
1387
|
Example:
|
|
1388
|
+
window.skuilder.pipeline.ui()
|
|
1097
1389
|
window.skuilder.pipeline.showLastRun()
|
|
1098
1390
|
window.skuilder.pipeline.showRun(1)
|
|
1099
1391
|
await window.skuilder.pipeline.diagnoseCardSpace()
|
|
@@ -1110,6 +1402,44 @@ __export(CompositeGenerator_exports, {
|
|
|
1110
1402
|
AggregationMode: () => AggregationMode,
|
|
1111
1403
|
default: () => CompositeGenerator
|
|
1112
1404
|
});
|
|
1405
|
+
function mergeHints(allHints) {
|
|
1406
|
+
const defined = allHints.filter((h) => h !== void 0);
|
|
1407
|
+
if (defined.length === 0) return void 0;
|
|
1408
|
+
const merged = {};
|
|
1409
|
+
const boostTags = {};
|
|
1410
|
+
for (const hints of defined) {
|
|
1411
|
+
for (const [pattern, factor] of Object.entries(hints.boostTags ?? {})) {
|
|
1412
|
+
boostTags[pattern] = (boostTags[pattern] ?? 1) * factor;
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
if (Object.keys(boostTags).length > 0) {
|
|
1416
|
+
merged.boostTags = boostTags;
|
|
1417
|
+
}
|
|
1418
|
+
const boostCards = {};
|
|
1419
|
+
for (const hints of defined) {
|
|
1420
|
+
for (const [pattern, factor] of Object.entries(hints.boostCards ?? {})) {
|
|
1421
|
+
boostCards[pattern] = (boostCards[pattern] ?? 1) * factor;
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
if (Object.keys(boostCards).length > 0) {
|
|
1425
|
+
merged.boostCards = boostCards;
|
|
1426
|
+
}
|
|
1427
|
+
const concatUnique = (field) => {
|
|
1428
|
+
const values = defined.flatMap((h) => h[field] ?? []);
|
|
1429
|
+
if (values.length > 0) {
|
|
1430
|
+
merged[field] = [...new Set(values)];
|
|
1431
|
+
}
|
|
1432
|
+
};
|
|
1433
|
+
concatUnique("requireTags");
|
|
1434
|
+
concatUnique("requireCards");
|
|
1435
|
+
concatUnique("excludeTags");
|
|
1436
|
+
concatUnique("excludeCards");
|
|
1437
|
+
const labels = defined.map((h) => h._label).filter(Boolean);
|
|
1438
|
+
if (labels.length > 0) {
|
|
1439
|
+
merged._label = labels.join("; ");
|
|
1440
|
+
}
|
|
1441
|
+
return Object.keys(merged).length > 0 ? merged : void 0;
|
|
1442
|
+
}
|
|
1113
1443
|
var AggregationMode, DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
|
|
1114
1444
|
var init_CompositeGenerator = __esm({
|
|
1115
1445
|
"src/core/navigators/generators/CompositeGenerator.ts"() {
|
|
@@ -1173,17 +1503,18 @@ var init_CompositeGenerator = __esm({
|
|
|
1173
1503
|
this.generators.map((g) => g.getWeightedCards(limit, context))
|
|
1174
1504
|
);
|
|
1175
1505
|
const generatorSummaries = [];
|
|
1176
|
-
results.forEach((
|
|
1506
|
+
results.forEach((result, index) => {
|
|
1507
|
+
const cards2 = result.cards;
|
|
1177
1508
|
const gen = this.generators[index];
|
|
1178
1509
|
const genName = gen.name || `Generator ${index}`;
|
|
1179
|
-
const newCards =
|
|
1180
|
-
const reviewCards =
|
|
1181
|
-
if (
|
|
1182
|
-
const topScore = Math.max(...
|
|
1510
|
+
const newCards = cards2.filter((c) => c.provenance[0]?.reason?.includes("new card"));
|
|
1511
|
+
const reviewCards = cards2.filter((c) => c.provenance[0]?.reason?.includes("review"));
|
|
1512
|
+
if (cards2.length > 0) {
|
|
1513
|
+
const topScore = Math.max(...cards2.map((c) => c.score)).toFixed(2);
|
|
1183
1514
|
const parts = [];
|
|
1184
1515
|
if (newCards.length > 0) parts.push(`${newCards.length} new`);
|
|
1185
1516
|
if (reviewCards.length > 0) parts.push(`${reviewCards.length} reviews`);
|
|
1186
|
-
const breakdown = parts.length > 0 ? parts.join(", ") : `${
|
|
1517
|
+
const breakdown = parts.length > 0 ? parts.join(", ") : `${cards2.length} cards`;
|
|
1187
1518
|
generatorSummaries.push(`${genName}: ${breakdown} (top: ${topScore})`);
|
|
1188
1519
|
} else {
|
|
1189
1520
|
generatorSummaries.push(`${genName}: 0 cards`);
|
|
@@ -1191,7 +1522,8 @@ var init_CompositeGenerator = __esm({
|
|
|
1191
1522
|
});
|
|
1192
1523
|
logger.info(`[Composite] Generator breakdown: ${generatorSummaries.join(" | ")}`);
|
|
1193
1524
|
const byCardId = /* @__PURE__ */ new Map();
|
|
1194
|
-
results.forEach((
|
|
1525
|
+
results.forEach((result, index) => {
|
|
1526
|
+
const cards2 = result.cards;
|
|
1195
1527
|
const gen = this.generators[index];
|
|
1196
1528
|
let weight = gen.learnable?.weight ?? 1;
|
|
1197
1529
|
let deviation;
|
|
@@ -1202,7 +1534,7 @@ var init_CompositeGenerator = __esm({
|
|
|
1202
1534
|
deviation = context.orchestration.getDeviation(strategyId);
|
|
1203
1535
|
}
|
|
1204
1536
|
}
|
|
1205
|
-
for (const card of
|
|
1537
|
+
for (const card of cards2) {
|
|
1206
1538
|
if (card.provenance.length > 0) {
|
|
1207
1539
|
card.provenance[0].effectiveWeight = weight;
|
|
1208
1540
|
card.provenance[0].deviation = deviation;
|
|
@@ -1214,15 +1546,15 @@ var init_CompositeGenerator = __esm({
|
|
|
1214
1546
|
});
|
|
1215
1547
|
const merged = [];
|
|
1216
1548
|
for (const [, items] of byCardId) {
|
|
1217
|
-
const
|
|
1549
|
+
const cards2 = items.map((i) => i.card);
|
|
1218
1550
|
const aggregatedScore = this.aggregateScores(items);
|
|
1219
|
-
const finalScore = Math.
|
|
1220
|
-
const mergedProvenance =
|
|
1221
|
-
const initialScore =
|
|
1551
|
+
const finalScore = Math.max(0, aggregatedScore);
|
|
1552
|
+
const mergedProvenance = cards2.flatMap((c) => c.provenance);
|
|
1553
|
+
const initialScore = cards2[0].score;
|
|
1222
1554
|
const action = finalScore > initialScore ? "boosted" : finalScore < initialScore ? "penalized" : "passed";
|
|
1223
1555
|
const reason = this.buildAggregationReason(items, finalScore);
|
|
1224
1556
|
merged.push({
|
|
1225
|
-
...
|
|
1557
|
+
...cards2[0],
|
|
1226
1558
|
score: finalScore,
|
|
1227
1559
|
provenance: [
|
|
1228
1560
|
...mergedProvenance,
|
|
@@ -1237,7 +1569,9 @@ var init_CompositeGenerator = __esm({
|
|
|
1237
1569
|
]
|
|
1238
1570
|
});
|
|
1239
1571
|
}
|
|
1240
|
-
|
|
1572
|
+
const cards = merged.sort((a, b) => b.score - a.score).slice(0, limit);
|
|
1573
|
+
const hints = mergeHints(results.map((result) => result.hints));
|
|
1574
|
+
return { cards, hints };
|
|
1241
1575
|
}
|
|
1242
1576
|
/**
|
|
1243
1577
|
* Build human-readable reason for score aggregation.
|
|
@@ -1368,16 +1702,16 @@ var init_elo = __esm({
|
|
|
1368
1702
|
};
|
|
1369
1703
|
});
|
|
1370
1704
|
scored.sort((a, b) => b.score - a.score);
|
|
1371
|
-
const
|
|
1372
|
-
if (
|
|
1373
|
-
const topScores =
|
|
1705
|
+
const cards = scored.slice(0, limit);
|
|
1706
|
+
if (cards.length > 0) {
|
|
1707
|
+
const topScores = cards.slice(0, 3).map((c) => c.score.toFixed(2)).join(", ");
|
|
1374
1708
|
logger.info(
|
|
1375
|
-
`[ELO] Course ${this.course.getCourseID()}: ${
|
|
1709
|
+
`[ELO] Course ${this.course.getCourseID()}: ${cards.length} new cards (top scores: ${topScores})`
|
|
1376
1710
|
);
|
|
1377
1711
|
} else {
|
|
1378
1712
|
logger.info(`[ELO] Course ${this.course.getCourseID()}: No new cards available`);
|
|
1379
1713
|
}
|
|
1380
|
-
return
|
|
1714
|
+
return { cards };
|
|
1381
1715
|
}
|
|
1382
1716
|
};
|
|
1383
1717
|
}
|
|
@@ -1411,10 +1745,26 @@ function matchesTagPattern(tag, pattern) {
|
|
|
1411
1745
|
const re = new RegExp(`^${escaped}$`);
|
|
1412
1746
|
return re.test(tag);
|
|
1413
1747
|
}
|
|
1748
|
+
function extractWordStem(cardId) {
|
|
1749
|
+
for (const prefix of ["c-ml-", "c-ws-", "c-spelling-"]) {
|
|
1750
|
+
if (cardId.startsWith(prefix)) {
|
|
1751
|
+
const rest = cardId.slice(prefix.length);
|
|
1752
|
+
const lastDash = rest.lastIndexOf("-");
|
|
1753
|
+
return lastDash > 0 ? rest.slice(0, lastDash) : rest;
|
|
1754
|
+
}
|
|
1755
|
+
}
|
|
1756
|
+
return cardId;
|
|
1757
|
+
}
|
|
1758
|
+
function shuffleInPlace(arr) {
|
|
1759
|
+
for (let i = arr.length - 1; i > 0; i--) {
|
|
1760
|
+
const j = Math.floor(Math.random() * (i + 1));
|
|
1761
|
+
[arr[i], arr[j]] = [arr[j], arr[i]];
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1414
1764
|
function pickTopByScore(cards, limit) {
|
|
1415
1765
|
return [...cards].sort((a, b) => b.score - a.score || a.cardId.localeCompare(b.cardId)).slice(0, limit);
|
|
1416
1766
|
}
|
|
1417
|
-
var DEFAULT_FRESHNESS_WINDOW, DEFAULT_MAX_DIRECT_PER_RUN, DEFAULT_MAX_SUPPORT_PER_RUN, DEFAULT_HIERARCHY_DEPTH, DEFAULT_MIN_COUNT, BASE_TARGET_SCORE, BASE_SUPPORT_SCORE, MAX_TARGET_MULTIPLIER, MAX_SUPPORT_MULTIPLIER,
|
|
1767
|
+
var DEFAULT_FRESHNESS_WINDOW, DEFAULT_MAX_DIRECT_PER_RUN, DEFAULT_MAX_SUPPORT_PER_RUN, DEFAULT_HIERARCHY_DEPTH, DEFAULT_MIN_COUNT, BASE_TARGET_SCORE, BASE_SUPPORT_SCORE, DISCOVERED_SUPPORT_SCORE, MAX_TARGET_MULTIPLIER, MAX_SUPPORT_MULTIPLIER, PRESCRIBED_DEBUG_VERSION, PrescribedCardsGenerator;
|
|
1418
1768
|
var init_prescribed = __esm({
|
|
1419
1769
|
"src/core/navigators/generators/prescribed.ts"() {
|
|
1420
1770
|
"use strict";
|
|
@@ -1427,10 +1777,10 @@ var init_prescribed = __esm({
|
|
|
1427
1777
|
DEFAULT_MIN_COUNT = 3;
|
|
1428
1778
|
BASE_TARGET_SCORE = 1;
|
|
1429
1779
|
BASE_SUPPORT_SCORE = 0.8;
|
|
1780
|
+
DISCOVERED_SUPPORT_SCORE = 12;
|
|
1430
1781
|
MAX_TARGET_MULTIPLIER = 8;
|
|
1431
1782
|
MAX_SUPPORT_MULTIPLIER = 4;
|
|
1432
|
-
|
|
1433
|
-
LESSON_GATE_PENALTY_TAG_HINT = "concept:";
|
|
1783
|
+
PRESCRIBED_DEBUG_VERSION = "testversion-prescribed-v3";
|
|
1434
1784
|
PrescribedCardsGenerator = class extends ContentNavigator {
|
|
1435
1785
|
name;
|
|
1436
1786
|
config;
|
|
@@ -1447,7 +1797,7 @@ var init_prescribed = __esm({
|
|
|
1447
1797
|
}
|
|
1448
1798
|
async getWeightedCards(limit, context) {
|
|
1449
1799
|
if (this.config.groups.length === 0 || limit <= 0) {
|
|
1450
|
-
return [];
|
|
1800
|
+
return { cards: [] };
|
|
1451
1801
|
}
|
|
1452
1802
|
const courseId = this.course.getCourseID();
|
|
1453
1803
|
const activeCards = await this.user.getActiveCards();
|
|
@@ -1466,12 +1816,27 @@ var init_prescribed = __esm({
|
|
|
1466
1816
|
const allSupportIds = dedupe(this.config.groups.flatMap((g) => g.supportCardIds ?? []));
|
|
1467
1817
|
const allRelevantIds = dedupe([...allTargetIds, ...allSupportIds]);
|
|
1468
1818
|
const tagsByCard = allRelevantIds.length > 0 ? await this.course.getAppliedTagsBatch(allRelevantIds) : /* @__PURE__ */ new Map();
|
|
1819
|
+
const courseTagDocs = await this.course.getCourseTagStubs().catch(
|
|
1820
|
+
() => ({
|
|
1821
|
+
rows: [],
|
|
1822
|
+
offset: 0,
|
|
1823
|
+
total_rows: 0
|
|
1824
|
+
})
|
|
1825
|
+
);
|
|
1826
|
+
const cardsByTag = /* @__PURE__ */ new Map();
|
|
1827
|
+
for (const row of courseTagDocs.rows ?? []) {
|
|
1828
|
+
const tagDoc = row.doc;
|
|
1829
|
+
if (tagDoc?.name && Array.isArray(tagDoc.taggedCards)) {
|
|
1830
|
+
cardsByTag.set(tagDoc.name, [...tagDoc.taggedCards]);
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1469
1833
|
const nextState = {
|
|
1470
1834
|
updatedAt: isoNow(),
|
|
1471
1835
|
groups: {}
|
|
1472
1836
|
};
|
|
1473
1837
|
const emitted = [];
|
|
1474
1838
|
const emittedIds = /* @__PURE__ */ new Set();
|
|
1839
|
+
const groupRuntimes = [];
|
|
1475
1840
|
for (const group of this.config.groups) {
|
|
1476
1841
|
const runtime = this.buildGroupRuntimeState({
|
|
1477
1842
|
group,
|
|
@@ -1479,10 +1844,31 @@ var init_prescribed = __esm({
|
|
|
1479
1844
|
activeIds,
|
|
1480
1845
|
seenIds,
|
|
1481
1846
|
tagsByCard,
|
|
1847
|
+
cardsByTag,
|
|
1482
1848
|
hierarchyConfigs,
|
|
1483
1849
|
userTagElo,
|
|
1484
1850
|
userGlobalElo
|
|
1485
1851
|
});
|
|
1852
|
+
groupRuntimes.push(runtime);
|
|
1853
|
+
logger.info(
|
|
1854
|
+
`[Prescribed] Group '${group.id}': ${group.targetCardIds.length} targets total, ${runtime.encounteredTargets.size} encountered, ${runtime.pendingTargets.length} pending (${runtime.surfaceableTargets.length} surfaceable, ${runtime.blockedTargets.length} blocked), ${runtime.supportCandidates.length} authored support candidates, ${runtime.discoveredSupportCandidates.length} discovered support candidates, pressure=${runtime.pressureMultiplier.toFixed(2)}`
|
|
1855
|
+
);
|
|
1856
|
+
if (runtime.blockedTargets.length > 0) {
|
|
1857
|
+
logger.info(
|
|
1858
|
+
`[Prescribed] Group '${group.id}' blocked targets: ${runtime.blockedTargets.join(", ")}`
|
|
1859
|
+
);
|
|
1860
|
+
logger.info(
|
|
1861
|
+
`[Prescribed] Group '${group.id}' support tags needed: ${runtime.supportTags.join(", ") || "(none)"}`
|
|
1862
|
+
);
|
|
1863
|
+
logger.info(
|
|
1864
|
+
`[Prescribed] Group '${group.id}' escalation mode: ` + (runtime.supportCandidates.length > 0 ? "direct-support" : runtime.discoveredSupportCandidates.length > 0 ? "inserted-support-candidates" : "boost-only")
|
|
1865
|
+
);
|
|
1866
|
+
if (runtime.discoveredSupportCandidates.length > 0) {
|
|
1867
|
+
logger.info(
|
|
1868
|
+
`[Prescribed] Group '${group.id}' discovered support candidates: ${runtime.discoveredSupportCandidates.join(", ")}`
|
|
1869
|
+
);
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1486
1872
|
nextState.groups[group.id] = this.buildNextGroupState(runtime, progress.groups[group.id]);
|
|
1487
1873
|
const directCards = this.buildDirectTargetCards(
|
|
1488
1874
|
runtime,
|
|
@@ -1494,14 +1880,34 @@ var init_prescribed = __esm({
|
|
|
1494
1880
|
courseId,
|
|
1495
1881
|
emittedIds
|
|
1496
1882
|
);
|
|
1497
|
-
|
|
1883
|
+
const discoveredSupportCards = this.buildDiscoveredSupportCards(
|
|
1884
|
+
runtime,
|
|
1885
|
+
courseId,
|
|
1886
|
+
emittedIds
|
|
1887
|
+
);
|
|
1888
|
+
emitted.push(...directCards, ...supportCards, ...discoveredSupportCards);
|
|
1889
|
+
}
|
|
1890
|
+
const hintSummary = this.buildSupportHintSummary(groupRuntimes);
|
|
1891
|
+
const hints = Object.keys(hintSummary.boostTags).length > 0 ? {
|
|
1892
|
+
boostTags: hintSummary.boostTags,
|
|
1893
|
+
_label: `prescribed-support (${hintSummary.supportTags.length} tags; blocked=${hintSummary.blockedTargetIds.length}; testversion=${PRESCRIBED_DEBUG_VERSION})`
|
|
1894
|
+
} : void 0;
|
|
1895
|
+
if (hints) {
|
|
1896
|
+
const tagEntries = Object.entries(hints.boostTags ?? {});
|
|
1897
|
+
logger.info(
|
|
1898
|
+
`[Prescribed] Emitting ${tagEntries.length} boost hint(s): ` + tagEntries.map(([tag, mult]) => `${tag}\xD7${mult.toFixed(1)}`).join(", ")
|
|
1899
|
+
);
|
|
1900
|
+
} else {
|
|
1901
|
+
logger.info("[Prescribed] No hints to emit (no blocked targets or no support tags)");
|
|
1498
1902
|
}
|
|
1499
1903
|
if (emitted.length === 0) {
|
|
1500
|
-
logger.
|
|
1904
|
+
logger.info(
|
|
1905
|
+
"[Prescribed] 0 cards emitted (all targets blocked, authored/discovered support candidates exhausted)" + (hints ? " \u2014 boost hints emitted but may not survive filters" : "")
|
|
1906
|
+
);
|
|
1501
1907
|
await this.putStrategyState(nextState).catch((e) => {
|
|
1502
1908
|
logger.debug(`[Prescribed] Failed to persist empty-state update: ${e}`);
|
|
1503
1909
|
});
|
|
1504
|
-
return [];
|
|
1910
|
+
return hints ? { cards: [], hints } : { cards: [] };
|
|
1505
1911
|
}
|
|
1506
1912
|
const finalCards = pickTopByScore(emitted, limit);
|
|
1507
1913
|
const surfacedByGroup = /* @__PURE__ */ new Map();
|
|
@@ -1530,9 +1936,29 @@ var init_prescribed = __esm({
|
|
|
1530
1936
|
logger.debug(`[Prescribed] Failed to persist prescribed progress: ${e}`);
|
|
1531
1937
|
});
|
|
1532
1938
|
logger.info(
|
|
1533
|
-
`[Prescribed] Emitting ${finalCards.length} cards (${finalCards.filter((c) => c.provenance[0]?.reason.includes("mode=target")).length} target, ${finalCards.filter((c) => c.provenance[0]?.reason.includes("mode=support")).length} support)`
|
|
1939
|
+
`[Prescribed] Emitting ${finalCards.length} cards (${finalCards.filter((c) => c.provenance[0]?.reason.includes("mode=target")).length} target, ${finalCards.filter((c) => c.provenance[0]?.reason.includes("mode=support")).length} support, ${finalCards.filter((c) => c.provenance[0]?.reason.includes("mode=discovered-support")).length} discovered support)`
|
|
1534
1940
|
);
|
|
1535
|
-
return finalCards;
|
|
1941
|
+
return hints ? { cards: finalCards, hints } : { cards: finalCards };
|
|
1942
|
+
}
|
|
1943
|
+
buildSupportHintSummary(groupRuntimes) {
|
|
1944
|
+
const boostTags = {};
|
|
1945
|
+
const blockedTargetIds = /* @__PURE__ */ new Set();
|
|
1946
|
+
const supportTags = /* @__PURE__ */ new Set();
|
|
1947
|
+
for (const runtime of groupRuntimes) {
|
|
1948
|
+
if (runtime.blockedTargets.length === 0 || runtime.supportTags.length === 0) {
|
|
1949
|
+
continue;
|
|
1950
|
+
}
|
|
1951
|
+
runtime.blockedTargets.forEach((cardId) => blockedTargetIds.add(cardId));
|
|
1952
|
+
for (const tag of runtime.supportTags) {
|
|
1953
|
+
supportTags.add(tag);
|
|
1954
|
+
boostTags[tag] = (boostTags[tag] ?? 1) * runtime.supportMultiplier;
|
|
1955
|
+
}
|
|
1956
|
+
}
|
|
1957
|
+
return {
|
|
1958
|
+
boostTags,
|
|
1959
|
+
blockedTargetIds: [...blockedTargetIds].sort(),
|
|
1960
|
+
supportTags: [...supportTags].sort()
|
|
1961
|
+
};
|
|
1536
1962
|
}
|
|
1537
1963
|
parseConfig(serializedData) {
|
|
1538
1964
|
try {
|
|
@@ -1540,9 +1966,15 @@ var init_prescribed = __esm({
|
|
|
1540
1966
|
const groupsRaw = Array.isArray(parsed.groups) ? parsed.groups : [];
|
|
1541
1967
|
const groups = groupsRaw.map((raw, i) => ({
|
|
1542
1968
|
id: typeof raw.id === "string" && raw.id.trim().length > 0 ? raw.id : `group-${i + 1}`,
|
|
1543
|
-
targetCardIds: dedupe(
|
|
1544
|
-
|
|
1545
|
-
|
|
1969
|
+
targetCardIds: dedupe(
|
|
1970
|
+
Array.isArray(raw.targetCardIds) ? raw.targetCardIds.filter((v) => typeof v === "string") : []
|
|
1971
|
+
),
|
|
1972
|
+
supportCardIds: dedupe(
|
|
1973
|
+
Array.isArray(raw.supportCardIds) ? raw.supportCardIds.filter((v) => typeof v === "string") : []
|
|
1974
|
+
),
|
|
1975
|
+
supportTagPatterns: dedupe(
|
|
1976
|
+
Array.isArray(raw.supportTagPatterns) ? raw.supportTagPatterns.filter((v) => typeof v === "string") : []
|
|
1977
|
+
),
|
|
1546
1978
|
freshnessWindowSessions: typeof raw.freshnessWindowSessions === "number" ? raw.freshnessWindowSessions : DEFAULT_FRESHNESS_WINDOW,
|
|
1547
1979
|
maxDirectTargetsPerRun: typeof raw.maxDirectTargetsPerRun === "number" ? raw.maxDirectTargetsPerRun : DEFAULT_MAX_DIRECT_PER_RUN,
|
|
1548
1980
|
maxSupportCardsPerRun: typeof raw.maxSupportCardsPerRun === "number" ? raw.maxSupportCardsPerRun : DEFAULT_MAX_SUPPORT_PER_RUN,
|
|
@@ -1559,7 +1991,7 @@ var init_prescribed = __esm({
|
|
|
1559
1991
|
}
|
|
1560
1992
|
async loadHierarchyConfigs() {
|
|
1561
1993
|
try {
|
|
1562
|
-
const strategies = await this.course.
|
|
1994
|
+
const strategies = await this.course.getAllNavigationStrategies();
|
|
1563
1995
|
return strategies.filter((s) => s.implementingClass === "hierarchyDefinition").map((s) => {
|
|
1564
1996
|
try {
|
|
1565
1997
|
const parsed = JSON.parse(s.serializedData);
|
|
@@ -1582,6 +2014,7 @@ var init_prescribed = __esm({
|
|
|
1582
2014
|
activeIds,
|
|
1583
2015
|
seenIds,
|
|
1584
2016
|
tagsByCard,
|
|
2017
|
+
cardsByTag,
|
|
1585
2018
|
hierarchyConfigs,
|
|
1586
2019
|
userTagElo,
|
|
1587
2020
|
userGlobalElo
|
|
@@ -1615,7 +2048,22 @@ var init_prescribed = __esm({
|
|
|
1615
2048
|
group.hierarchyWalk?.enabled !== false,
|
|
1616
2049
|
group.hierarchyWalk?.maxDepth ?? DEFAULT_HIERARCHY_DEPTH
|
|
1617
2050
|
);
|
|
1618
|
-
|
|
2051
|
+
const introTags = tags.filter((tag) => tag.startsWith("gpc:intro:"));
|
|
2052
|
+
const exposeTags = new Set(tags.filter((tag) => tag.startsWith("gpc:expose:")));
|
|
2053
|
+
for (const introTag of introTags) {
|
|
2054
|
+
const suffix = introTag.slice("gpc:intro:".length);
|
|
2055
|
+
if (suffix) {
|
|
2056
|
+
exposeTags.add(`gpc:expose:${suffix}`);
|
|
2057
|
+
}
|
|
2058
|
+
}
|
|
2059
|
+
const unmetExposeTags = [...exposeTags].filter((tag) => {
|
|
2060
|
+
const tagElo = userTagElo[tag];
|
|
2061
|
+
return !tagElo || tagElo.count < DEFAULT_MIN_COUNT;
|
|
2062
|
+
});
|
|
2063
|
+
if (unmetExposeTags.length > 0) {
|
|
2064
|
+
unmetExposeTags.forEach((tag) => supportTags.add(tag));
|
|
2065
|
+
}
|
|
2066
|
+
if (resolution.blocked || unmetExposeTags.length > 0) {
|
|
1619
2067
|
blockedTargets.push(cardId);
|
|
1620
2068
|
resolution.supportTags.forEach((t) => supportTags.add(t));
|
|
1621
2069
|
} else {
|
|
@@ -1630,6 +2078,22 @@ var init_prescribed = __esm({
|
|
|
1630
2078
|
[...supportTags]
|
|
1631
2079
|
)
|
|
1632
2080
|
]).filter((id) => !activeIds.has(id) && !seenIds.has(id));
|
|
2081
|
+
const discoveredSupportCandidates = blockedTargets.length > 0 && supportTags.size > 0 && supportCandidates.length === 0 ? this.findDiscoveredSupportCards({
|
|
2082
|
+
supportTags: [...supportTags],
|
|
2083
|
+
cardsByTag,
|
|
2084
|
+
activeIds,
|
|
2085
|
+
seenIds,
|
|
2086
|
+
excludedIds: /* @__PURE__ */ new Set([
|
|
2087
|
+
...group.targetCardIds,
|
|
2088
|
+
...group.supportCardIds ?? []
|
|
2089
|
+
]),
|
|
2090
|
+
limit: group.maxSupportCardsPerRun ?? DEFAULT_MAX_SUPPORT_PER_RUN
|
|
2091
|
+
}) : [];
|
|
2092
|
+
if (blockedTargets.length > 0 && supportTags.size > 0 && discoveredSupportCandidates.length === 0) {
|
|
2093
|
+
logger.info(
|
|
2094
|
+
`[Prescribed] Group '${group.id}' discovered 0 broader support candidates (blocked=${blockedTargets.length}; authoredSupport=${supportCandidates.length})`
|
|
2095
|
+
);
|
|
2096
|
+
}
|
|
1633
2097
|
const sessionsSinceSurfaced = priorState?.sessionsSinceSurfaced ?? 0;
|
|
1634
2098
|
const freshnessWindow = group.freshnessWindowSessions ?? DEFAULT_FRESHNESS_WINDOW;
|
|
1635
2099
|
const staleSessions = Math.max(0, sessionsSinceSurfaced - freshnessWindow);
|
|
@@ -1643,9 +2107,11 @@ var init_prescribed = __esm({
|
|
|
1643
2107
|
surfaceableTargets,
|
|
1644
2108
|
targetTags,
|
|
1645
2109
|
supportCandidates,
|
|
2110
|
+
discoveredSupportCandidates,
|
|
1646
2111
|
supportTags: [...supportTags],
|
|
1647
2112
|
pressureMultiplier,
|
|
1648
|
-
supportMultiplier
|
|
2113
|
+
supportMultiplier,
|
|
2114
|
+
debugVersion: PRESCRIBED_DEBUG_VERSION
|
|
1649
2115
|
};
|
|
1650
2116
|
}
|
|
1651
2117
|
buildNextGroupState(runtime, prior) {
|
|
@@ -1653,6 +2119,7 @@ var init_prescribed = __esm({
|
|
|
1653
2119
|
const surfacedThisRun = false;
|
|
1654
2120
|
return {
|
|
1655
2121
|
encounteredCardIds: [...runtime.encounteredTargets].sort(),
|
|
2122
|
+
pendingTargetIds: [...runtime.pendingTargets].sort(),
|
|
1656
2123
|
lastSurfacedAt: prior?.lastSurfacedAt ?? null,
|
|
1657
2124
|
sessionsSinceSurfaced: surfacedThisRun ? 0 : carriedSessions + 1,
|
|
1658
2125
|
lastSupportAt: prior?.lastSupportAt ?? null,
|
|
@@ -1677,7 +2144,7 @@ var init_prescribed = __esm({
|
|
|
1677
2144
|
strategyId: this.strategyId || "NAVIGATION_STRATEGY-prescribed",
|
|
1678
2145
|
action: "generated",
|
|
1679
2146
|
score: BASE_TARGET_SCORE * runtime.pressureMultiplier,
|
|
1680
|
-
reason: `mode=target;group=${runtime.group.id};pending=${runtime.pendingTargets.length};surfaceable=${runtime.surfaceableTargets.length};blocked=${runtime.blockedTargets.length};multiplier=${runtime.pressureMultiplier.toFixed(2)}`
|
|
2147
|
+
reason: `mode=target;group=${runtime.group.id};pending=${runtime.pendingTargets.length};surfaceable=${runtime.surfaceableTargets.length};blocked=${runtime.blockedTargets.length};blockedTargets=${runtime.blockedTargets.join("|") || "none"};supportTags=${runtime.supportTags.join("|") || "none"};multiplier=${runtime.pressureMultiplier.toFixed(2)};testversion=${runtime.debugVersion}`
|
|
1681
2148
|
}
|
|
1682
2149
|
]
|
|
1683
2150
|
});
|
|
@@ -1704,7 +2171,34 @@ var init_prescribed = __esm({
|
|
|
1704
2171
|
strategyId: this.strategyId || "NAVIGATION_STRATEGY-prescribed",
|
|
1705
2172
|
action: "generated",
|
|
1706
2173
|
score: BASE_SUPPORT_SCORE * runtime.supportMultiplier,
|
|
1707
|
-
reason: `mode=support;group=${runtime.group.id};blocked=${runtime.blockedTargets.length};supportTags=${runtime.supportTags.join("|") || "none"};multiplier=${runtime.supportMultiplier.toFixed(2)}`
|
|
2174
|
+
reason: `mode=support;group=${runtime.group.id};pending=${runtime.pendingTargets.length};blocked=${runtime.blockedTargets.length};blockedTargets=${runtime.blockedTargets.join("|") || "none"};supportCard=${cardId};supportTags=${runtime.supportTags.join("|") || "none"};multiplier=${runtime.supportMultiplier.toFixed(2)};testversion=${runtime.debugVersion}`
|
|
2175
|
+
}
|
|
2176
|
+
]
|
|
2177
|
+
});
|
|
2178
|
+
}
|
|
2179
|
+
return cards;
|
|
2180
|
+
}
|
|
2181
|
+
buildDiscoveredSupportCards(runtime, courseId, emittedIds) {
|
|
2182
|
+
if (runtime.blockedTargets.length === 0 || runtime.discoveredSupportCandidates.length === 0) {
|
|
2183
|
+
return [];
|
|
2184
|
+
}
|
|
2185
|
+
const maxSupport = runtime.group.maxSupportCardsPerRun ?? DEFAULT_MAX_SUPPORT_PER_RUN;
|
|
2186
|
+
const supportIds = runtime.discoveredSupportCandidates.filter((id) => !emittedIds.has(id)).slice(0, maxSupport);
|
|
2187
|
+
const cards = [];
|
|
2188
|
+
for (const cardId of supportIds) {
|
|
2189
|
+
emittedIds.add(cardId);
|
|
2190
|
+
cards.push({
|
|
2191
|
+
cardId,
|
|
2192
|
+
courseId,
|
|
2193
|
+
score: DISCOVERED_SUPPORT_SCORE * runtime.supportMultiplier,
|
|
2194
|
+
provenance: [
|
|
2195
|
+
{
|
|
2196
|
+
strategy: "prescribed",
|
|
2197
|
+
strategyName: this.strategyName || this.name,
|
|
2198
|
+
strategyId: this.strategyId || "NAVIGATION_STRATEGY-prescribed",
|
|
2199
|
+
action: "generated",
|
|
2200
|
+
score: DISCOVERED_SUPPORT_SCORE * runtime.supportMultiplier,
|
|
2201
|
+
reason: `mode=discovered-support;group=${runtime.group.id};pending=${runtime.pendingTargets.length};blocked=${runtime.blockedTargets.length};blockedTargets=${runtime.blockedTargets.join("|") || "none"};supportCard=${cardId};supportTags=${runtime.supportTags.join("|") || "none"};multiplier=${runtime.supportMultiplier.toFixed(2)};testversion=${runtime.debugVersion}`
|
|
1708
2202
|
}
|
|
1709
2203
|
]
|
|
1710
2204
|
});
|
|
@@ -1733,36 +2227,78 @@ var init_prescribed = __esm({
|
|
|
1733
2227
|
}
|
|
1734
2228
|
return [...candidates];
|
|
1735
2229
|
}
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
2230
|
+
findDiscoveredSupportCards(args) {
|
|
2231
|
+
const { supportTags, cardsByTag, activeIds, seenIds, excludedIds, limit } = args;
|
|
2232
|
+
const byCardId = /* @__PURE__ */ new Map();
|
|
2233
|
+
for (const supportTag of supportTags) {
|
|
2234
|
+
const taggedCards = cardsByTag.get(supportTag) ?? [];
|
|
2235
|
+
for (const cardId of taggedCards) {
|
|
2236
|
+
if (activeIds.has(cardId) || seenIds.has(cardId) || excludedIds.has(cardId)) {
|
|
2237
|
+
continue;
|
|
2238
|
+
}
|
|
2239
|
+
const existing = byCardId.get(cardId);
|
|
2240
|
+
if (existing) {
|
|
2241
|
+
existing.matches += 1;
|
|
2242
|
+
} else {
|
|
2243
|
+
byCardId.set(cardId, { cardId, matches: 1 });
|
|
2244
|
+
}
|
|
2245
|
+
}
|
|
2246
|
+
}
|
|
2247
|
+
const candidates = [...byCardId.values()].sort((a, b) => b.matches - a.matches || a.cardId.localeCompare(b.cardId));
|
|
2248
|
+
const usedStems = /* @__PURE__ */ new Set();
|
|
2249
|
+
const diverse = [];
|
|
2250
|
+
const deferred = [];
|
|
2251
|
+
for (const entry of candidates) {
|
|
2252
|
+
const stem = extractWordStem(entry.cardId);
|
|
2253
|
+
if (!usedStems.has(stem)) {
|
|
2254
|
+
usedStems.add(stem);
|
|
2255
|
+
diverse.push(entry);
|
|
2256
|
+
} else {
|
|
2257
|
+
deferred.push(entry);
|
|
2258
|
+
}
|
|
1742
2259
|
}
|
|
2260
|
+
shuffleInPlace(diverse);
|
|
2261
|
+
shuffleInPlace(deferred);
|
|
2262
|
+
return [...diverse, ...deferred].slice(0, limit).map((entry) => entry.cardId);
|
|
2263
|
+
}
|
|
2264
|
+
resolveBlockedSupportTags(targetTags, hierarchyConfigs, userTagElo, userGlobalElo, hierarchyWalkEnabled, maxDepth) {
|
|
1743
2265
|
const supportTags = /* @__PURE__ */ new Set();
|
|
1744
2266
|
let blocked = false;
|
|
1745
2267
|
for (const targetTag of targetTags) {
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
)
|
|
1752
|
-
|
|
1753
|
-
|
|
2268
|
+
const prereqSets = hierarchyConfigs.map((hierarchy) => hierarchy.prerequisites[targetTag]).filter((prereqs) => Array.isArray(prereqs) && prereqs.length > 0);
|
|
2269
|
+
if (prereqSets.length === 0) {
|
|
2270
|
+
continue;
|
|
2271
|
+
}
|
|
2272
|
+
const tagBlocked = prereqSets.some(
|
|
2273
|
+
(prereqs) => prereqs.some((pr) => !this.isPrerequisiteMet(pr, userTagElo[pr.tag], userGlobalElo))
|
|
2274
|
+
);
|
|
2275
|
+
if (!tagBlocked) {
|
|
2276
|
+
continue;
|
|
2277
|
+
}
|
|
2278
|
+
blocked = true;
|
|
2279
|
+
if (!hierarchyWalkEnabled) {
|
|
2280
|
+
for (const prereqs of prereqSets) {
|
|
2281
|
+
for (const prereq of prereqs) {
|
|
2282
|
+
if (!this.isPrerequisiteMet(prereq, userTagElo[prereq.tag], userGlobalElo)) {
|
|
2283
|
+
supportTags.add(prereq.tag);
|
|
2284
|
+
}
|
|
2285
|
+
}
|
|
1754
2286
|
}
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
2287
|
+
continue;
|
|
2288
|
+
}
|
|
2289
|
+
for (const prereqs of prereqSets) {
|
|
2290
|
+
for (const prereq of prereqs) {
|
|
2291
|
+
if (!this.isPrerequisiteMet(prereq, userTagElo[prereq.tag], userGlobalElo)) {
|
|
2292
|
+
this.collectSupportTagsRecursive(
|
|
2293
|
+
prereq.tag,
|
|
2294
|
+
hierarchyConfigs,
|
|
2295
|
+
userTagElo,
|
|
2296
|
+
userGlobalElo,
|
|
2297
|
+
maxDepth,
|
|
2298
|
+
/* @__PURE__ */ new Set(),
|
|
2299
|
+
supportTags
|
|
2300
|
+
);
|
|
2301
|
+
}
|
|
1766
2302
|
}
|
|
1767
2303
|
}
|
|
1768
2304
|
}
|
|
@@ -1770,7 +2306,6 @@ var init_prescribed = __esm({
|
|
|
1770
2306
|
}
|
|
1771
2307
|
collectSupportTagsRecursive(tag, hierarchyConfigs, userTagElo, userGlobalElo, depth, visited, out) {
|
|
1772
2308
|
if (depth < 0 || visited.has(tag)) return;
|
|
1773
|
-
if (this.isHardGatedTag(tag)) return;
|
|
1774
2309
|
visited.add(tag);
|
|
1775
2310
|
let walkedFurther = false;
|
|
1776
2311
|
for (const hierarchy of hierarchyConfigs) {
|
|
@@ -1798,9 +2333,6 @@ var init_prescribed = __esm({
|
|
|
1798
2333
|
out.add(tag);
|
|
1799
2334
|
}
|
|
1800
2335
|
}
|
|
1801
|
-
isHardGatedTag(tag) {
|
|
1802
|
-
return LOCKED_TAG_PREFIXES.some((prefix) => tag.startsWith(prefix)) && tag.startsWith(LESSON_GATE_PENALTY_TAG_HINT);
|
|
1803
|
-
}
|
|
1804
2336
|
isPrerequisiteMet(prereq, userTagElo, userGlobalElo) {
|
|
1805
2337
|
if (!userTagElo) return false;
|
|
1806
2338
|
const minCount = prereq.masteryThreshold?.minCount ?? DEFAULT_MIN_COUNT;
|
|
@@ -1917,7 +2449,7 @@ var init_srs = __esm({
|
|
|
1917
2449
|
]
|
|
1918
2450
|
};
|
|
1919
2451
|
});
|
|
1920
|
-
return scored.sort((a, b) => b.score - a.score).slice(0, limit);
|
|
2452
|
+
return { cards: scored.sort((a, b) => b.score - a.score).slice(0, limit) };
|
|
1921
2453
|
}
|
|
1922
2454
|
/**
|
|
1923
2455
|
* Compute backlog pressure based on number of due reviews.
|
|
@@ -3194,1714 +3726,160 @@ var init_learning = __esm({
|
|
|
3194
3726
|
}
|
|
3195
3727
|
});
|
|
3196
3728
|
|
|
3197
|
-
// src/core/orchestration/signal.ts
|
|
3198
|
-
function computeOutcomeSignal(records, config = {}) {
|
|
3199
|
-
if (!records || records.length === 0) {
|
|
3200
|
-
return null;
|
|
3201
|
-
}
|
|
3202
|
-
const target = config.targetAccuracy ?? 0.85;
|
|
3203
|
-
const tolerance = config.tolerance ?? 0.05;
|
|
3204
|
-
let correct = 0;
|
|
3205
|
-
for (const r of records) {
|
|
3206
|
-
if (r.isCorrect) correct++;
|
|
3207
|
-
}
|
|
3208
|
-
const accuracy = correct / records.length;
|
|
3209
|
-
return scoreAccuracyInZone(accuracy, target, tolerance);
|
|
3210
|
-
}
|
|
3211
|
-
function scoreAccuracyInZone(accuracy, target, tolerance) {
|
|
3212
|
-
const dist = Math.abs(accuracy - target);
|
|
3213
|
-
if (dist <= tolerance) {
|
|
3214
|
-
return 1;
|
|
3215
|
-
}
|
|
3216
|
-
const excess = dist - tolerance;
|
|
3217
|
-
const slope = 2.5;
|
|
3218
|
-
return Math.max(0, 1 - excess * slope);
|
|
3219
|
-
}
|
|
3220
|
-
var init_signal = __esm({
|
|
3221
|
-
"src/core/orchestration/signal.ts"() {
|
|
3222
|
-
"use strict";
|
|
3223
|
-
}
|
|
3224
|
-
});
|
|
3225
|
-
|
|
3226
|
-
// src/core/orchestration/recording.ts
|
|
3227
|
-
async function recordUserOutcome(context, periodStart, periodEnd, records, activeStrategyIds, eloStart = 0, eloEnd = 0, config) {
|
|
3228
|
-
const { user, course, userId } = context;
|
|
3229
|
-
const courseId = course.getCourseID();
|
|
3230
|
-
const outcomeValue = computeOutcomeSignal(records, config);
|
|
3231
|
-
if (outcomeValue === null) {
|
|
3232
|
-
logger.debug(
|
|
3233
|
-
`[Orchestration] No outcome signal computed for ${userId} (insufficient data). Skipping record.`
|
|
3234
|
-
);
|
|
3235
|
-
return;
|
|
3236
|
-
}
|
|
3237
|
-
const deviations = {};
|
|
3238
|
-
for (const strategyId of activeStrategyIds) {
|
|
3239
|
-
deviations[strategyId] = context.getDeviation(strategyId);
|
|
3240
|
-
}
|
|
3241
|
-
const id = `USER_OUTCOME::${courseId}::${userId}::${periodEnd}`;
|
|
3242
|
-
const record = {
|
|
3243
|
-
_id: id,
|
|
3244
|
-
docType: "USER_OUTCOME" /* USER_OUTCOME */,
|
|
3245
|
-
courseId,
|
|
3246
|
-
userId,
|
|
3247
|
-
periodStart,
|
|
3248
|
-
periodEnd,
|
|
3249
|
-
outcomeValue,
|
|
3250
|
-
deviations,
|
|
3251
|
-
metadata: {
|
|
3252
|
-
sessionsCount: 1,
|
|
3253
|
-
// Assumes recording is triggered per-session currently
|
|
3254
|
-
cardsSeen: records.length,
|
|
3255
|
-
eloStart,
|
|
3256
|
-
eloEnd,
|
|
3257
|
-
signalType: "accuracy_in_zone"
|
|
3258
|
-
}
|
|
3259
|
-
};
|
|
3260
|
-
try {
|
|
3261
|
-
await user.putUserOutcome(record);
|
|
3262
|
-
logger.debug(
|
|
3263
|
-
`[Orchestration] Recorded outcome ${outcomeValue.toFixed(3)} for ${userId} (doc: ${id})`
|
|
3264
|
-
);
|
|
3265
|
-
} catch (e) {
|
|
3266
|
-
logger.error(`[Orchestration] Failed to record outcome: ${e}`);
|
|
3267
|
-
}
|
|
3268
|
-
}
|
|
3269
|
-
var init_recording = __esm({
|
|
3270
|
-
"src/core/orchestration/recording.ts"() {
|
|
3271
|
-
"use strict";
|
|
3272
|
-
init_signal();
|
|
3273
|
-
init_types_legacy();
|
|
3274
|
-
init_logger();
|
|
3275
|
-
}
|
|
3276
|
-
});
|
|
3277
|
-
|
|
3278
|
-
// src/core/orchestration/index.ts
|
|
3279
|
-
function fnv1a(str) {
|
|
3280
|
-
let hash = 2166136261;
|
|
3281
|
-
for (let i = 0; i < str.length; i++) {
|
|
3282
|
-
hash ^= str.charCodeAt(i);
|
|
3283
|
-
hash = Math.imul(hash, 16777619);
|
|
3284
|
-
}
|
|
3285
|
-
return hash >>> 0;
|
|
3286
|
-
}
|
|
3287
|
-
function computeDeviation(userId, strategyId, salt) {
|
|
3288
|
-
const input = `${userId}:${strategyId}:${salt}`;
|
|
3289
|
-
const hash = fnv1a(input);
|
|
3290
|
-
const normalized = hash / 4294967296;
|
|
3291
|
-
return normalized * 2 - 1;
|
|
3292
|
-
}
|
|
3293
|
-
function computeSpread(confidence) {
|
|
3294
|
-
const clampedConfidence = Math.max(0, Math.min(1, confidence));
|
|
3295
|
-
return MAX_SPREAD - clampedConfidence * (MAX_SPREAD - MIN_SPREAD);
|
|
3296
|
-
}
|
|
3297
|
-
function computeEffectiveWeight(learnable, userId, strategyId, salt) {
|
|
3298
|
-
const deviation = computeDeviation(userId, strategyId, salt);
|
|
3299
|
-
const spread = computeSpread(learnable.confidence);
|
|
3300
|
-
const adjustment = deviation * spread * learnable.weight;
|
|
3301
|
-
const effective = learnable.weight + adjustment;
|
|
3302
|
-
return Math.max(MIN_WEIGHT, Math.min(MAX_WEIGHT, effective));
|
|
3303
|
-
}
|
|
3304
|
-
async function createOrchestrationContext(user, course) {
|
|
3305
|
-
let courseConfig;
|
|
3306
|
-
try {
|
|
3307
|
-
courseConfig = await course.getCourseConfig();
|
|
3308
|
-
} catch (e) {
|
|
3309
|
-
logger.error(`[Orchestration] Failed to load course config: ${e}`);
|
|
3310
|
-
courseConfig = {
|
|
3311
|
-
name: "Unknown",
|
|
3312
|
-
description: "",
|
|
3313
|
-
public: false,
|
|
3314
|
-
deleted: false,
|
|
3315
|
-
creator: "",
|
|
3316
|
-
admins: [],
|
|
3317
|
-
moderators: [],
|
|
3318
|
-
dataShapes: [],
|
|
3319
|
-
questionTypes: [],
|
|
3320
|
-
orchestration: { salt: "default" }
|
|
3321
|
-
};
|
|
3322
|
-
}
|
|
3323
|
-
const userId = user.getUsername();
|
|
3324
|
-
const salt = courseConfig.orchestration?.salt || "default_salt";
|
|
3325
|
-
return {
|
|
3326
|
-
user,
|
|
3327
|
-
course,
|
|
3328
|
-
userId,
|
|
3329
|
-
courseConfig,
|
|
3330
|
-
getEffectiveWeight(strategyId, learnable) {
|
|
3331
|
-
return computeEffectiveWeight(learnable, userId, strategyId, salt);
|
|
3332
|
-
},
|
|
3333
|
-
getDeviation(strategyId) {
|
|
3334
|
-
return computeDeviation(userId, strategyId, salt);
|
|
3335
|
-
}
|
|
3336
|
-
};
|
|
3337
|
-
}
|
|
3338
|
-
var MIN_SPREAD, MAX_SPREAD, MIN_WEIGHT, MAX_WEIGHT;
|
|
3339
|
-
var init_orchestration = __esm({
|
|
3340
|
-
"src/core/orchestration/index.ts"() {
|
|
3341
|
-
"use strict";
|
|
3342
|
-
init_logger();
|
|
3343
|
-
init_gradient();
|
|
3344
|
-
init_learning();
|
|
3345
|
-
init_signal();
|
|
3346
|
-
init_recording();
|
|
3347
|
-
MIN_SPREAD = 0.1;
|
|
3348
|
-
MAX_SPREAD = 0.5;
|
|
3349
|
-
MIN_WEIGHT = 0.1;
|
|
3350
|
-
MAX_WEIGHT = 3;
|
|
3351
|
-
}
|
|
3352
|
-
});
|
|
3353
|
-
|
|
3354
|
-
// src/study/SpacedRepetition.ts
|
|
3355
|
-
var import_moment4, import_common8, duration;
|
|
3356
|
-
var init_SpacedRepetition = __esm({
|
|
3357
|
-
"src/study/SpacedRepetition.ts"() {
|
|
3358
|
-
"use strict";
|
|
3359
|
-
init_util();
|
|
3360
|
-
import_moment4 = __toESM(require("moment"), 1);
|
|
3361
|
-
import_common8 = require("@vue-skuilder/common");
|
|
3362
|
-
init_logger();
|
|
3363
|
-
duration = import_moment4.default.duration;
|
|
3364
|
-
}
|
|
3365
|
-
});
|
|
3366
|
-
|
|
3367
|
-
// src/study/services/SrsService.ts
|
|
3368
|
-
var import_moment5;
|
|
3369
|
-
var init_SrsService = __esm({
|
|
3370
|
-
"src/study/services/SrsService.ts"() {
|
|
3371
|
-
"use strict";
|
|
3372
|
-
import_moment5 = __toESM(require("moment"), 1);
|
|
3373
|
-
init_couch();
|
|
3374
|
-
init_SpacedRepetition();
|
|
3375
|
-
init_logger();
|
|
3376
|
-
}
|
|
3377
|
-
});
|
|
3378
|
-
|
|
3379
|
-
// src/study/services/EloService.ts
|
|
3380
|
-
var import_common9;
|
|
3381
|
-
var init_EloService = __esm({
|
|
3382
|
-
"src/study/services/EloService.ts"() {
|
|
3383
|
-
"use strict";
|
|
3384
|
-
import_common9 = require("@vue-skuilder/common");
|
|
3385
|
-
init_logger();
|
|
3386
|
-
}
|
|
3387
|
-
});
|
|
3388
|
-
|
|
3389
|
-
// src/study/services/ResponseProcessor.ts
|
|
3390
|
-
var import_common10;
|
|
3391
|
-
var init_ResponseProcessor = __esm({
|
|
3392
|
-
"src/study/services/ResponseProcessor.ts"() {
|
|
3393
|
-
"use strict";
|
|
3394
|
-
init_core();
|
|
3395
|
-
init_logger();
|
|
3396
|
-
import_common10 = require("@vue-skuilder/common");
|
|
3397
|
-
}
|
|
3398
|
-
});
|
|
3399
|
-
|
|
3400
|
-
// src/study/services/CardHydrationService.ts
|
|
3401
|
-
var import_common11;
|
|
3402
|
-
var init_CardHydrationService = __esm({
|
|
3403
|
-
"src/study/services/CardHydrationService.ts"() {
|
|
3404
|
-
"use strict";
|
|
3405
|
-
import_common11 = require("@vue-skuilder/common");
|
|
3406
|
-
init_logger();
|
|
3407
|
-
}
|
|
3408
|
-
});
|
|
3409
|
-
|
|
3410
|
-
// src/study/ItemQueue.ts
|
|
3411
|
-
var init_ItemQueue = __esm({
|
|
3412
|
-
"src/study/ItemQueue.ts"() {
|
|
3413
|
-
"use strict";
|
|
3414
|
-
}
|
|
3415
|
-
});
|
|
3416
|
-
|
|
3417
|
-
// src/util/packer/types.ts
|
|
3418
|
-
var init_types3 = __esm({
|
|
3419
|
-
"src/util/packer/types.ts"() {
|
|
3420
|
-
"use strict";
|
|
3421
|
-
}
|
|
3422
|
-
});
|
|
3423
|
-
|
|
3424
|
-
// src/util/packer/CouchDBToStaticPacker.ts
|
|
3425
|
-
var init_CouchDBToStaticPacker = __esm({
|
|
3426
|
-
"src/util/packer/CouchDBToStaticPacker.ts"() {
|
|
3427
|
-
"use strict";
|
|
3428
|
-
init_types_legacy();
|
|
3429
|
-
init_logger();
|
|
3430
|
-
}
|
|
3431
|
-
});
|
|
3432
|
-
|
|
3433
|
-
// src/util/packer/index.ts
|
|
3434
|
-
var init_packer = __esm({
|
|
3435
|
-
"src/util/packer/index.ts"() {
|
|
3436
|
-
"use strict";
|
|
3437
|
-
init_types3();
|
|
3438
|
-
init_CouchDBToStaticPacker();
|
|
3439
|
-
}
|
|
3440
|
-
});
|
|
3441
|
-
|
|
3442
|
-
// src/util/migrator/types.ts
|
|
3443
|
-
var DEFAULT_MIGRATION_OPTIONS;
|
|
3444
|
-
var init_types4 = __esm({
|
|
3445
|
-
"src/util/migrator/types.ts"() {
|
|
3446
|
-
"use strict";
|
|
3447
|
-
DEFAULT_MIGRATION_OPTIONS = {
|
|
3448
|
-
chunkBatchSize: 100,
|
|
3449
|
-
validateRoundTrip: false,
|
|
3450
|
-
cleanupOnFailure: true,
|
|
3451
|
-
timeout: 3e5
|
|
3452
|
-
// 5 minutes
|
|
3453
|
-
};
|
|
3454
|
-
}
|
|
3455
|
-
});
|
|
3456
|
-
|
|
3457
|
-
// src/util/migrator/FileSystemAdapter.ts
|
|
3458
|
-
var FileSystemError;
|
|
3459
|
-
var init_FileSystemAdapter = __esm({
|
|
3460
|
-
"src/util/migrator/FileSystemAdapter.ts"() {
|
|
3461
|
-
"use strict";
|
|
3462
|
-
FileSystemError = class extends Error {
|
|
3463
|
-
constructor(message, operation, filePath, cause) {
|
|
3464
|
-
super(message);
|
|
3465
|
-
this.operation = operation;
|
|
3466
|
-
this.filePath = filePath;
|
|
3467
|
-
this.cause = cause;
|
|
3468
|
-
this.name = "FileSystemError";
|
|
3469
|
-
}
|
|
3470
|
-
};
|
|
3471
|
-
}
|
|
3472
|
-
});
|
|
3473
|
-
|
|
3474
|
-
// src/util/migrator/validation.ts
|
|
3475
|
-
async function validateStaticCourse(staticPath, fs) {
|
|
3476
|
-
const validation = {
|
|
3477
|
-
valid: true,
|
|
3478
|
-
manifestExists: false,
|
|
3479
|
-
chunksExist: false,
|
|
3480
|
-
attachmentsExist: false,
|
|
3481
|
-
errors: [],
|
|
3482
|
-
warnings: []
|
|
3483
|
-
};
|
|
3484
|
-
try {
|
|
3485
|
-
if (fs) {
|
|
3486
|
-
const stats = await fs.stat(staticPath);
|
|
3487
|
-
if (!stats.isDirectory()) {
|
|
3488
|
-
validation.errors.push(`Path is not a directory: ${staticPath}`);
|
|
3489
|
-
validation.valid = false;
|
|
3490
|
-
return validation;
|
|
3491
|
-
}
|
|
3492
|
-
} else if (!nodeFS) {
|
|
3493
|
-
validation.errors.push("File system access not available - validation skipped");
|
|
3494
|
-
validation.valid = false;
|
|
3495
|
-
return validation;
|
|
3496
|
-
} else {
|
|
3497
|
-
const stats = await nodeFS.promises.stat(staticPath);
|
|
3498
|
-
if (!stats.isDirectory()) {
|
|
3499
|
-
validation.errors.push(`Path is not a directory: ${staticPath}`);
|
|
3500
|
-
validation.valid = false;
|
|
3501
|
-
return validation;
|
|
3502
|
-
}
|
|
3503
|
-
}
|
|
3504
|
-
let manifestPath = `${staticPath}/manifest.json`;
|
|
3505
|
-
try {
|
|
3506
|
-
if (fs) {
|
|
3507
|
-
manifestPath = fs.joinPath(staticPath, "manifest.json");
|
|
3508
|
-
if (await fs.exists(manifestPath)) {
|
|
3509
|
-
validation.manifestExists = true;
|
|
3510
|
-
const manifestContent = await fs.readFile(manifestPath);
|
|
3511
|
-
const manifest = JSON.parse(manifestContent);
|
|
3512
|
-
validation.courseId = manifest.courseId;
|
|
3513
|
-
validation.courseName = manifest.courseName;
|
|
3514
|
-
if (!manifest.version || !manifest.courseId || !manifest.chunks || !Array.isArray(manifest.chunks)) {
|
|
3515
|
-
validation.errors.push("Invalid manifest structure");
|
|
3516
|
-
validation.valid = false;
|
|
3517
|
-
}
|
|
3518
|
-
} else {
|
|
3519
|
-
validation.errors.push(`Manifest not found: ${manifestPath}`);
|
|
3520
|
-
validation.valid = false;
|
|
3521
|
-
}
|
|
3522
|
-
} else {
|
|
3523
|
-
manifestPath = `${staticPath}/manifest.json`;
|
|
3524
|
-
await nodeFS.promises.access(manifestPath);
|
|
3525
|
-
validation.manifestExists = true;
|
|
3526
|
-
const manifestContent = await nodeFS.promises.readFile(manifestPath, "utf8");
|
|
3527
|
-
const manifest = JSON.parse(manifestContent);
|
|
3528
|
-
validation.courseId = manifest.courseId;
|
|
3529
|
-
validation.courseName = manifest.courseName;
|
|
3530
|
-
if (!manifest.version || !manifest.courseId || !manifest.chunks || !Array.isArray(manifest.chunks)) {
|
|
3531
|
-
validation.errors.push("Invalid manifest structure");
|
|
3532
|
-
validation.valid = false;
|
|
3533
|
-
}
|
|
3534
|
-
}
|
|
3535
|
-
} catch (error) {
|
|
3536
|
-
const errorMessage = error instanceof FileSystemError ? error.message : `Manifest not found or invalid: ${manifestPath}`;
|
|
3537
|
-
validation.errors.push(errorMessage);
|
|
3538
|
-
validation.valid = false;
|
|
3539
|
-
}
|
|
3540
|
-
let chunksPath = `${staticPath}/chunks`;
|
|
3541
|
-
try {
|
|
3542
|
-
if (fs) {
|
|
3543
|
-
chunksPath = fs.joinPath(staticPath, "chunks");
|
|
3544
|
-
if (await fs.exists(chunksPath)) {
|
|
3545
|
-
const chunksStats = await fs.stat(chunksPath);
|
|
3546
|
-
if (chunksStats.isDirectory()) {
|
|
3547
|
-
validation.chunksExist = true;
|
|
3548
|
-
} else {
|
|
3549
|
-
validation.errors.push(`Chunks path is not a directory: ${chunksPath}`);
|
|
3550
|
-
validation.valid = false;
|
|
3551
|
-
}
|
|
3552
|
-
} else {
|
|
3553
|
-
validation.errors.push(`Chunks directory not found: ${chunksPath}`);
|
|
3554
|
-
validation.valid = false;
|
|
3555
|
-
}
|
|
3556
|
-
} else {
|
|
3557
|
-
chunksPath = `${staticPath}/chunks`;
|
|
3558
|
-
const chunksStats = await nodeFS.promises.stat(chunksPath);
|
|
3559
|
-
if (chunksStats.isDirectory()) {
|
|
3560
|
-
validation.chunksExist = true;
|
|
3561
|
-
} else {
|
|
3562
|
-
validation.errors.push(`Chunks path is not a directory: ${chunksPath}`);
|
|
3563
|
-
validation.valid = false;
|
|
3564
|
-
}
|
|
3565
|
-
}
|
|
3566
|
-
} catch (error) {
|
|
3567
|
-
const errorMessage = error instanceof FileSystemError ? error.message : `Chunks directory not found: ${chunksPath}`;
|
|
3568
|
-
validation.errors.push(errorMessage);
|
|
3569
|
-
validation.valid = false;
|
|
3570
|
-
}
|
|
3571
|
-
let attachmentsPath;
|
|
3572
|
-
try {
|
|
3573
|
-
if (fs) {
|
|
3574
|
-
attachmentsPath = fs.joinPath(staticPath, "attachments");
|
|
3575
|
-
if (await fs.exists(attachmentsPath)) {
|
|
3576
|
-
const attachmentsStats = await fs.stat(attachmentsPath);
|
|
3577
|
-
if (attachmentsStats.isDirectory()) {
|
|
3578
|
-
validation.attachmentsExist = true;
|
|
3579
|
-
}
|
|
3580
|
-
} else {
|
|
3581
|
-
validation.warnings.push(
|
|
3582
|
-
`Attachments directory not found: ${attachmentsPath} (this is OK if course has no attachments)`
|
|
3583
|
-
);
|
|
3584
|
-
}
|
|
3585
|
-
} else {
|
|
3586
|
-
attachmentsPath = `${staticPath}/attachments`;
|
|
3587
|
-
const attachmentsStats = await nodeFS.promises.stat(attachmentsPath);
|
|
3588
|
-
if (attachmentsStats.isDirectory()) {
|
|
3589
|
-
validation.attachmentsExist = true;
|
|
3590
|
-
}
|
|
3591
|
-
}
|
|
3592
|
-
} catch (error) {
|
|
3593
|
-
attachmentsPath = attachmentsPath || `${staticPath}/attachments`;
|
|
3594
|
-
const warningMessage = error instanceof FileSystemError ? error.message : `Attachments directory not found: ${attachmentsPath} (this is OK if course has no attachments)`;
|
|
3595
|
-
validation.warnings.push(warningMessage);
|
|
3596
|
-
}
|
|
3597
|
-
} catch (error) {
|
|
3598
|
-
validation.errors.push(
|
|
3599
|
-
`Failed to validate static course: ${error instanceof Error ? error.message : String(error)}`
|
|
3600
|
-
);
|
|
3601
|
-
validation.valid = false;
|
|
3602
|
-
}
|
|
3603
|
-
return validation;
|
|
3604
|
-
}
|
|
3605
|
-
async function validateMigration(targetDB, expectedCounts, manifest) {
|
|
3606
|
-
const validation = {
|
|
3607
|
-
valid: true,
|
|
3608
|
-
documentCountMatch: false,
|
|
3609
|
-
attachmentIntegrity: false,
|
|
3610
|
-
viewFunctionality: false,
|
|
3611
|
-
issues: []
|
|
3612
|
-
};
|
|
3613
|
-
try {
|
|
3614
|
-
logger.info("Starting migration validation...");
|
|
3615
|
-
const actualCounts = await getActualDocumentCounts(targetDB);
|
|
3616
|
-
validation.documentCountMatch = compareDocumentCounts(
|
|
3617
|
-
expectedCounts,
|
|
3618
|
-
actualCounts,
|
|
3619
|
-
validation.issues
|
|
3620
|
-
);
|
|
3621
|
-
await validateCourseConfig(targetDB, manifest, validation.issues);
|
|
3622
|
-
validation.viewFunctionality = await validateViews(targetDB, manifest, validation.issues);
|
|
3623
|
-
validation.attachmentIntegrity = await validateAttachmentIntegrity(targetDB, validation.issues);
|
|
3624
|
-
validation.valid = validation.documentCountMatch && validation.viewFunctionality && validation.attachmentIntegrity;
|
|
3625
|
-
logger.info(`Migration validation completed. Valid: ${validation.valid}`);
|
|
3626
|
-
if (validation.issues.length > 0) {
|
|
3627
|
-
logger.info(`Validation issues: ${validation.issues.length}`);
|
|
3628
|
-
validation.issues.forEach((issue) => {
|
|
3629
|
-
if (issue.type === "error") {
|
|
3630
|
-
logger.error(`${issue.category}: ${issue.message}`);
|
|
3631
|
-
} else {
|
|
3632
|
-
logger.warn(`${issue.category}: ${issue.message}`);
|
|
3633
|
-
}
|
|
3634
|
-
});
|
|
3635
|
-
}
|
|
3636
|
-
} catch (error) {
|
|
3637
|
-
validation.valid = false;
|
|
3638
|
-
validation.issues.push({
|
|
3639
|
-
type: "error",
|
|
3640
|
-
category: "metadata",
|
|
3641
|
-
message: `Validation failed: ${error instanceof Error ? error.message : String(error)}`
|
|
3642
|
-
});
|
|
3643
|
-
}
|
|
3644
|
-
return validation;
|
|
3645
|
-
}
|
|
3646
|
-
async function getActualDocumentCounts(db) {
|
|
3647
|
-
const counts = {};
|
|
3648
|
-
try {
|
|
3649
|
-
const allDocs = await db.allDocs({ include_docs: true });
|
|
3650
|
-
for (const row of allDocs.rows) {
|
|
3651
|
-
if (row.id.startsWith("_design/")) {
|
|
3652
|
-
counts["_design"] = (counts["_design"] || 0) + 1;
|
|
3653
|
-
continue;
|
|
3654
|
-
}
|
|
3655
|
-
const doc = row.doc;
|
|
3656
|
-
if (doc && doc.docType) {
|
|
3657
|
-
counts[doc.docType] = (counts[doc.docType] || 0) + 1;
|
|
3658
|
-
} else {
|
|
3659
|
-
counts["unknown"] = (counts["unknown"] || 0) + 1;
|
|
3660
|
-
}
|
|
3661
|
-
}
|
|
3662
|
-
} catch (error) {
|
|
3663
|
-
logger.error("Failed to get actual document counts:", error);
|
|
3664
|
-
}
|
|
3665
|
-
return counts;
|
|
3666
|
-
}
|
|
3667
|
-
function compareDocumentCounts(expected, actual, issues) {
|
|
3668
|
-
let countsMatch = true;
|
|
3669
|
-
for (const [docType, expectedCount] of Object.entries(expected)) {
|
|
3670
|
-
const actualCount = actual[docType] || 0;
|
|
3671
|
-
if (actualCount !== expectedCount) {
|
|
3672
|
-
countsMatch = false;
|
|
3673
|
-
issues.push({
|
|
3674
|
-
type: "error",
|
|
3675
|
-
category: "documents",
|
|
3676
|
-
message: `Document count mismatch for ${docType}: expected ${expectedCount}, got ${actualCount}`
|
|
3677
|
-
});
|
|
3678
|
-
}
|
|
3679
|
-
}
|
|
3680
|
-
for (const [docType, actualCount] of Object.entries(actual)) {
|
|
3681
|
-
if (!expected[docType] && docType !== "_design") {
|
|
3682
|
-
issues.push({
|
|
3683
|
-
type: "warning",
|
|
3684
|
-
category: "documents",
|
|
3685
|
-
message: `Unexpected document type found: ${docType} (${actualCount} documents)`
|
|
3686
|
-
});
|
|
3687
|
-
}
|
|
3688
|
-
}
|
|
3689
|
-
return countsMatch;
|
|
3690
|
-
}
|
|
3691
|
-
async function validateCourseConfig(db, manifest, issues) {
|
|
3692
|
-
try {
|
|
3693
|
-
const courseConfig = await db.get("CourseConfig");
|
|
3694
|
-
if (!courseConfig) {
|
|
3695
|
-
issues.push({
|
|
3696
|
-
type: "error",
|
|
3697
|
-
category: "course_config",
|
|
3698
|
-
message: "CourseConfig document not found after migration"
|
|
3699
|
-
});
|
|
3700
|
-
return;
|
|
3701
|
-
}
|
|
3702
|
-
if (!courseConfig.courseID) {
|
|
3703
|
-
issues.push({
|
|
3704
|
-
type: "warning",
|
|
3705
|
-
category: "course_config",
|
|
3706
|
-
message: "CourseConfig document missing courseID field"
|
|
3707
|
-
});
|
|
3708
|
-
}
|
|
3709
|
-
if (courseConfig.courseID !== manifest.courseId) {
|
|
3710
|
-
issues.push({
|
|
3711
|
-
type: "warning",
|
|
3712
|
-
category: "course_config",
|
|
3713
|
-
message: `CourseConfig courseID mismatch: expected ${manifest.courseId}, got ${courseConfig.courseID}`
|
|
3714
|
-
});
|
|
3715
|
-
}
|
|
3716
|
-
logger.debug("CourseConfig document validation passed");
|
|
3717
|
-
} catch (error) {
|
|
3718
|
-
if (error.status === 404) {
|
|
3719
|
-
issues.push({
|
|
3720
|
-
type: "error",
|
|
3721
|
-
category: "course_config",
|
|
3722
|
-
message: "CourseConfig document not found in database"
|
|
3723
|
-
});
|
|
3724
|
-
} else {
|
|
3725
|
-
issues.push({
|
|
3726
|
-
type: "error",
|
|
3727
|
-
category: "course_config",
|
|
3728
|
-
message: `Failed to validate CourseConfig document: ${error instanceof Error ? error.message : String(error)}`
|
|
3729
|
-
});
|
|
3730
|
-
}
|
|
3731
|
-
}
|
|
3732
|
-
}
|
|
3733
|
-
async function validateViews(db, manifest, issues) {
|
|
3734
|
-
let viewsValid = true;
|
|
3735
|
-
try {
|
|
3736
|
-
for (const designDoc of manifest.designDocs) {
|
|
3737
|
-
try {
|
|
3738
|
-
const doc = await db.get(designDoc._id);
|
|
3739
|
-
if (!doc) {
|
|
3740
|
-
viewsValid = false;
|
|
3741
|
-
issues.push({
|
|
3742
|
-
type: "error",
|
|
3743
|
-
category: "views",
|
|
3744
|
-
message: `Design document not found: ${designDoc._id}`
|
|
3745
|
-
});
|
|
3746
|
-
continue;
|
|
3747
|
-
}
|
|
3748
|
-
for (const viewName of Object.keys(designDoc.views)) {
|
|
3749
|
-
try {
|
|
3750
|
-
const viewPath = `${designDoc._id}/${viewName}`;
|
|
3751
|
-
await db.query(viewPath, { limit: 1 });
|
|
3752
|
-
} catch (viewError) {
|
|
3753
|
-
viewsValid = false;
|
|
3754
|
-
issues.push({
|
|
3755
|
-
type: "error",
|
|
3756
|
-
category: "views",
|
|
3757
|
-
message: `View not accessible: ${designDoc._id}/${viewName} - ${viewError}`
|
|
3758
|
-
});
|
|
3759
|
-
}
|
|
3760
|
-
}
|
|
3761
|
-
} catch (error) {
|
|
3762
|
-
viewsValid = false;
|
|
3763
|
-
issues.push({
|
|
3764
|
-
type: "error",
|
|
3765
|
-
category: "views",
|
|
3766
|
-
message: `Failed to validate design document ${designDoc._id}: ${error}`
|
|
3767
|
-
});
|
|
3768
|
-
}
|
|
3769
|
-
}
|
|
3770
|
-
} catch (error) {
|
|
3771
|
-
viewsValid = false;
|
|
3772
|
-
issues.push({
|
|
3773
|
-
type: "error",
|
|
3774
|
-
category: "views",
|
|
3775
|
-
message: `View validation failed: ${error instanceof Error ? error.message : String(error)}`
|
|
3776
|
-
});
|
|
3777
|
-
}
|
|
3778
|
-
return viewsValid;
|
|
3779
|
-
}
|
|
3780
|
-
async function validateAttachmentIntegrity(db, issues) {
|
|
3781
|
-
let attachmentsValid = true;
|
|
3782
|
-
try {
|
|
3783
|
-
const allDocs = await db.allDocs({
|
|
3784
|
-
include_docs: true,
|
|
3785
|
-
limit: 10
|
|
3786
|
-
// Sample first 10 documents for performance
|
|
3787
|
-
});
|
|
3788
|
-
let attachmentCount = 0;
|
|
3789
|
-
let validAttachments = 0;
|
|
3790
|
-
for (const row of allDocs.rows) {
|
|
3791
|
-
const doc = row.doc;
|
|
3792
|
-
if (doc && doc._attachments) {
|
|
3793
|
-
for (const [attachmentName, _attachmentMeta] of Object.entries(doc._attachments)) {
|
|
3794
|
-
attachmentCount++;
|
|
3795
|
-
try {
|
|
3796
|
-
const attachment = await db.getAttachment(doc._id, attachmentName);
|
|
3797
|
-
if (attachment) {
|
|
3798
|
-
validAttachments++;
|
|
3799
|
-
}
|
|
3800
|
-
} catch (attachmentError) {
|
|
3801
|
-
attachmentsValid = false;
|
|
3802
|
-
issues.push({
|
|
3803
|
-
type: "error",
|
|
3804
|
-
category: "attachments",
|
|
3805
|
-
message: `Attachment not accessible: ${doc._id}/${attachmentName} - ${attachmentError}`
|
|
3806
|
-
});
|
|
3807
|
-
}
|
|
3808
|
-
}
|
|
3809
|
-
}
|
|
3810
|
-
}
|
|
3811
|
-
if (attachmentCount === 0) {
|
|
3812
|
-
issues.push({
|
|
3813
|
-
type: "warning",
|
|
3814
|
-
category: "attachments",
|
|
3815
|
-
message: "No attachments found in sampled documents"
|
|
3816
|
-
});
|
|
3817
|
-
} else {
|
|
3818
|
-
logger.info(`Validated ${validAttachments}/${attachmentCount} sampled attachments`);
|
|
3819
|
-
}
|
|
3820
|
-
} catch (error) {
|
|
3821
|
-
attachmentsValid = false;
|
|
3822
|
-
issues.push({
|
|
3823
|
-
type: "error",
|
|
3824
|
-
category: "attachments",
|
|
3825
|
-
message: `Attachment validation failed: ${error instanceof Error ? error.message : String(error)}`
|
|
3826
|
-
});
|
|
3827
|
-
}
|
|
3828
|
-
return attachmentsValid;
|
|
3829
|
-
}
|
|
3830
|
-
var nodeFS;
|
|
3831
|
-
var init_validation = __esm({
|
|
3832
|
-
"src/util/migrator/validation.ts"() {
|
|
3833
|
-
"use strict";
|
|
3834
|
-
init_logger();
|
|
3835
|
-
init_FileSystemAdapter();
|
|
3836
|
-
nodeFS = null;
|
|
3837
|
-
try {
|
|
3838
|
-
if (typeof window === "undefined" && typeof process !== "undefined" && process.versions?.node) {
|
|
3839
|
-
nodeFS = eval("require")("fs");
|
|
3840
|
-
nodeFS.promises = nodeFS.promises || eval("require")("fs").promises;
|
|
3841
|
-
}
|
|
3842
|
-
} catch {
|
|
3843
|
-
}
|
|
3844
|
-
}
|
|
3845
|
-
});
|
|
3846
|
-
|
|
3847
|
-
// src/util/migrator/StaticToCouchDBMigrator.ts
|
|
3848
|
-
var nodeFS2, nodePath, StaticToCouchDBMigrator;
|
|
3849
|
-
var init_StaticToCouchDBMigrator = __esm({
|
|
3850
|
-
"src/util/migrator/StaticToCouchDBMigrator.ts"() {
|
|
3851
|
-
"use strict";
|
|
3852
|
-
init_logger();
|
|
3853
|
-
init_types4();
|
|
3854
|
-
init_validation();
|
|
3855
|
-
init_FileSystemAdapter();
|
|
3856
|
-
nodeFS2 = null;
|
|
3857
|
-
nodePath = null;
|
|
3858
|
-
try {
|
|
3859
|
-
if (typeof window === "undefined" && typeof process !== "undefined" && process.versions?.node) {
|
|
3860
|
-
nodeFS2 = eval("require")("fs");
|
|
3861
|
-
nodePath = eval("require")("path");
|
|
3862
|
-
nodeFS2.promises = nodeFS2.promises || eval("require")("fs").promises;
|
|
3863
|
-
}
|
|
3864
|
-
} catch {
|
|
3865
|
-
}
|
|
3866
|
-
StaticToCouchDBMigrator = class {
|
|
3867
|
-
options;
|
|
3868
|
-
progressCallback;
|
|
3869
|
-
fs;
|
|
3870
|
-
constructor(options = {}, fileSystemAdapter) {
|
|
3871
|
-
this.options = {
|
|
3872
|
-
...DEFAULT_MIGRATION_OPTIONS,
|
|
3873
|
-
...options
|
|
3874
|
-
};
|
|
3875
|
-
this.fs = fileSystemAdapter;
|
|
3876
|
-
}
|
|
3877
|
-
/**
|
|
3878
|
-
* Set a progress callback to receive updates during migration
|
|
3879
|
-
*/
|
|
3880
|
-
setProgressCallback(callback) {
|
|
3881
|
-
this.progressCallback = callback;
|
|
3882
|
-
}
|
|
3883
|
-
/**
|
|
3884
|
-
* Migrate a static course to CouchDB
|
|
3885
|
-
*/
|
|
3886
|
-
async migrateCourse(staticPath, targetDB) {
|
|
3887
|
-
const startTime = Date.now();
|
|
3888
|
-
const result = {
|
|
3889
|
-
success: false,
|
|
3890
|
-
documentsRestored: 0,
|
|
3891
|
-
attachmentsRestored: 0,
|
|
3892
|
-
designDocsRestored: 0,
|
|
3893
|
-
courseConfigRestored: 0,
|
|
3894
|
-
errors: [],
|
|
3895
|
-
warnings: [],
|
|
3896
|
-
migrationTime: 0
|
|
3897
|
-
};
|
|
3898
|
-
try {
|
|
3899
|
-
logger.info(`Starting migration from ${staticPath} to CouchDB`);
|
|
3900
|
-
this.reportProgress("manifest", 0, 1, "Validating static course...");
|
|
3901
|
-
const validation = await validateStaticCourse(staticPath, this.fs);
|
|
3902
|
-
if (!validation.valid) {
|
|
3903
|
-
result.errors.push(...validation.errors);
|
|
3904
|
-
throw new Error(`Static course validation failed: ${validation.errors.join(", ")}`);
|
|
3905
|
-
}
|
|
3906
|
-
result.warnings.push(...validation.warnings);
|
|
3907
|
-
this.reportProgress("manifest", 1, 1, "Loading course manifest...");
|
|
3908
|
-
const manifest = await this.loadManifest(staticPath);
|
|
3909
|
-
logger.info(`Loaded manifest for course: ${manifest.courseId} (${manifest.courseName})`);
|
|
3910
|
-
this.reportProgress(
|
|
3911
|
-
"design_docs",
|
|
3912
|
-
0,
|
|
3913
|
-
manifest.designDocs.length,
|
|
3914
|
-
"Restoring design documents..."
|
|
3915
|
-
);
|
|
3916
|
-
const designDocResults = await this.restoreDesignDocuments(manifest.designDocs, targetDB);
|
|
3917
|
-
result.designDocsRestored = designDocResults.restored;
|
|
3918
|
-
result.errors.push(...designDocResults.errors);
|
|
3919
|
-
result.warnings.push(...designDocResults.warnings);
|
|
3920
|
-
this.reportProgress("course_config", 0, 1, "Restoring CourseConfig document...");
|
|
3921
|
-
const courseConfigResults = await this.restoreCourseConfig(manifest, targetDB);
|
|
3922
|
-
result.courseConfigRestored = courseConfigResults.restored;
|
|
3923
|
-
result.errors.push(...courseConfigResults.errors);
|
|
3924
|
-
result.warnings.push(...courseConfigResults.warnings);
|
|
3925
|
-
this.reportProgress("course_config", 1, 1, "CourseConfig document restored");
|
|
3926
|
-
const expectedCounts = this.calculateExpectedCounts(manifest);
|
|
3927
|
-
this.reportProgress(
|
|
3928
|
-
"documents",
|
|
3929
|
-
0,
|
|
3930
|
-
manifest.documentCount,
|
|
3931
|
-
"Aggregating documents from chunks..."
|
|
3932
|
-
);
|
|
3933
|
-
const documents = await this.aggregateDocuments(staticPath, manifest);
|
|
3934
|
-
const filteredDocuments = documents.filter((doc) => doc._id !== "CourseConfig");
|
|
3935
|
-
if (documents.length !== filteredDocuments.length) {
|
|
3936
|
-
result.warnings.push(
|
|
3937
|
-
`Filtered out ${documents.length - filteredDocuments.length} CourseConfig document(s) from chunks to prevent conflicts`
|
|
3938
|
-
);
|
|
3939
|
-
}
|
|
3940
|
-
this.reportProgress(
|
|
3941
|
-
"documents",
|
|
3942
|
-
filteredDocuments.length,
|
|
3943
|
-
manifest.documentCount,
|
|
3944
|
-
"Uploading documents to CouchDB..."
|
|
3945
|
-
);
|
|
3946
|
-
const docResults = await this.uploadDocuments(filteredDocuments, targetDB);
|
|
3947
|
-
result.documentsRestored = docResults.restored;
|
|
3948
|
-
result.errors.push(...docResults.errors);
|
|
3949
|
-
result.warnings.push(...docResults.warnings);
|
|
3950
|
-
const docsWithAttachments = documents.filter(
|
|
3951
|
-
(doc) => doc._attachments && Object.keys(doc._attachments).length > 0
|
|
3952
|
-
);
|
|
3953
|
-
this.reportProgress("attachments", 0, docsWithAttachments.length, "Uploading attachments...");
|
|
3954
|
-
const attachmentResults = await this.uploadAttachments(
|
|
3955
|
-
staticPath,
|
|
3956
|
-
docsWithAttachments,
|
|
3957
|
-
targetDB
|
|
3958
|
-
);
|
|
3959
|
-
result.attachmentsRestored = attachmentResults.restored;
|
|
3960
|
-
result.errors.push(...attachmentResults.errors);
|
|
3961
|
-
result.warnings.push(...attachmentResults.warnings);
|
|
3962
|
-
if (this.options.validateRoundTrip) {
|
|
3963
|
-
this.reportProgress("validation", 0, 1, "Validating migration...");
|
|
3964
|
-
const validationResult = await validateMigration(targetDB, expectedCounts, manifest);
|
|
3965
|
-
if (!validationResult.valid) {
|
|
3966
|
-
result.warnings.push("Migration validation found issues");
|
|
3967
|
-
validationResult.issues.forEach((issue) => {
|
|
3968
|
-
if (issue.type === "error") {
|
|
3969
|
-
result.errors.push(`Validation: ${issue.message}`);
|
|
3970
|
-
} else {
|
|
3971
|
-
result.warnings.push(`Validation: ${issue.message}`);
|
|
3972
|
-
}
|
|
3973
|
-
});
|
|
3974
|
-
}
|
|
3975
|
-
this.reportProgress("validation", 1, 1, "Migration validation completed");
|
|
3976
|
-
}
|
|
3977
|
-
result.success = result.errors.length === 0;
|
|
3978
|
-
result.migrationTime = Date.now() - startTime;
|
|
3979
|
-
logger.info(`Migration completed in ${result.migrationTime}ms`);
|
|
3980
|
-
logger.info(`Documents restored: ${result.documentsRestored}`);
|
|
3981
|
-
logger.info(`Attachments restored: ${result.attachmentsRestored}`);
|
|
3982
|
-
logger.info(`Design docs restored: ${result.designDocsRestored}`);
|
|
3983
|
-
logger.info(`CourseConfig restored: ${result.courseConfigRestored}`);
|
|
3984
|
-
if (result.errors.length > 0) {
|
|
3985
|
-
logger.error(`Migration completed with ${result.errors.length} errors`);
|
|
3986
|
-
}
|
|
3987
|
-
if (result.warnings.length > 0) {
|
|
3988
|
-
logger.warn(`Migration completed with ${result.warnings.length} warnings`);
|
|
3989
|
-
}
|
|
3990
|
-
} catch (error) {
|
|
3991
|
-
result.success = false;
|
|
3992
|
-
result.migrationTime = Date.now() - startTime;
|
|
3993
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
3994
|
-
result.errors.push(`Migration failed: ${errorMessage}`);
|
|
3995
|
-
logger.error("Migration failed:", error);
|
|
3996
|
-
if (this.options.cleanupOnFailure) {
|
|
3997
|
-
try {
|
|
3998
|
-
await this.cleanupFailedMigration(targetDB);
|
|
3999
|
-
} catch (cleanupError) {
|
|
4000
|
-
logger.error("Failed to cleanup after migration failure:", cleanupError);
|
|
4001
|
-
result.warnings.push("Failed to cleanup after migration failure");
|
|
4002
|
-
}
|
|
4003
|
-
}
|
|
4004
|
-
}
|
|
4005
|
-
return result;
|
|
4006
|
-
}
|
|
4007
|
-
/**
|
|
4008
|
-
* Load and parse the manifest file
|
|
4009
|
-
*/
|
|
4010
|
-
async loadManifest(staticPath) {
|
|
4011
|
-
try {
|
|
4012
|
-
let manifestContent;
|
|
4013
|
-
let manifestPath;
|
|
4014
|
-
if (this.fs) {
|
|
4015
|
-
manifestPath = this.fs.joinPath(staticPath, "manifest.json");
|
|
4016
|
-
manifestContent = await this.fs.readFile(manifestPath);
|
|
4017
|
-
} else {
|
|
4018
|
-
manifestPath = nodeFS2 && nodePath ? nodePath.join(staticPath, "manifest.json") : `${staticPath}/manifest.json`;
|
|
4019
|
-
if (nodeFS2 && this.isLocalPath(staticPath)) {
|
|
4020
|
-
manifestContent = await nodeFS2.promises.readFile(manifestPath, "utf8");
|
|
4021
|
-
} else {
|
|
4022
|
-
const response = await fetch(manifestPath);
|
|
4023
|
-
if (!response.ok) {
|
|
4024
|
-
throw new Error(`Failed to fetch manifest: ${response.status} ${response.statusText}`);
|
|
4025
|
-
}
|
|
4026
|
-
manifestContent = await response.text();
|
|
4027
|
-
}
|
|
4028
|
-
}
|
|
4029
|
-
const manifest = JSON.parse(manifestContent);
|
|
4030
|
-
if (!manifest.version || !manifest.courseId || !manifest.chunks) {
|
|
4031
|
-
throw new Error("Invalid manifest structure");
|
|
4032
|
-
}
|
|
4033
|
-
return manifest;
|
|
4034
|
-
} catch (error) {
|
|
4035
|
-
const errorMessage = error instanceof FileSystemError ? error.message : `Failed to load manifest: ${error instanceof Error ? error.message : String(error)}`;
|
|
4036
|
-
throw new Error(errorMessage);
|
|
4037
|
-
}
|
|
4038
|
-
}
|
|
4039
|
-
/**
|
|
4040
|
-
* Restore design documents to CouchDB
|
|
4041
|
-
*/
|
|
4042
|
-
async restoreDesignDocuments(designDocs, db) {
|
|
4043
|
-
const result = { restored: 0, errors: [], warnings: [] };
|
|
4044
|
-
for (let i = 0; i < designDocs.length; i++) {
|
|
4045
|
-
const designDoc = designDocs[i];
|
|
4046
|
-
this.reportProgress("design_docs", i, designDocs.length, `Restoring ${designDoc._id}...`);
|
|
4047
|
-
try {
|
|
4048
|
-
let existingDoc;
|
|
4049
|
-
try {
|
|
4050
|
-
existingDoc = await db.get(designDoc._id);
|
|
4051
|
-
} catch {
|
|
4052
|
-
}
|
|
4053
|
-
const docToInsert = {
|
|
4054
|
-
_id: designDoc._id,
|
|
4055
|
-
views: designDoc.views
|
|
4056
|
-
};
|
|
4057
|
-
if (existingDoc) {
|
|
4058
|
-
docToInsert._rev = existingDoc._rev;
|
|
4059
|
-
logger.debug(`Updating existing design document: ${designDoc._id}`);
|
|
4060
|
-
} else {
|
|
4061
|
-
logger.debug(`Creating new design document: ${designDoc._id}`);
|
|
4062
|
-
}
|
|
4063
|
-
await db.put(docToInsert);
|
|
4064
|
-
result.restored++;
|
|
4065
|
-
} catch (error) {
|
|
4066
|
-
const errorMessage = `Failed to restore design document ${designDoc._id}: ${error instanceof Error ? error.message : String(error)}`;
|
|
4067
|
-
result.errors.push(errorMessage);
|
|
4068
|
-
logger.error(errorMessage);
|
|
4069
|
-
}
|
|
4070
|
-
}
|
|
4071
|
-
this.reportProgress(
|
|
4072
|
-
"design_docs",
|
|
4073
|
-
designDocs.length,
|
|
4074
|
-
designDocs.length,
|
|
4075
|
-
`Restored ${result.restored} design documents`
|
|
4076
|
-
);
|
|
4077
|
-
return result;
|
|
4078
|
-
}
|
|
4079
|
-
/**
|
|
4080
|
-
* Aggregate documents from all chunks
|
|
4081
|
-
*/
|
|
4082
|
-
async aggregateDocuments(staticPath, manifest) {
|
|
4083
|
-
const allDocuments = [];
|
|
4084
|
-
const documentMap = /* @__PURE__ */ new Map();
|
|
4085
|
-
for (let i = 0; i < manifest.chunks.length; i++) {
|
|
4086
|
-
const chunk = manifest.chunks[i];
|
|
4087
|
-
this.reportProgress(
|
|
4088
|
-
"documents",
|
|
4089
|
-
allDocuments.length,
|
|
4090
|
-
manifest.documentCount,
|
|
4091
|
-
`Loading chunk ${chunk.id}...`
|
|
4092
|
-
);
|
|
4093
|
-
try {
|
|
4094
|
-
const documents = await this.loadChunk(staticPath, chunk);
|
|
4095
|
-
for (const doc of documents) {
|
|
4096
|
-
if (!doc._id) {
|
|
4097
|
-
logger.warn(`Document without _id found in chunk ${chunk.id}, skipping`);
|
|
4098
|
-
continue;
|
|
4099
|
-
}
|
|
4100
|
-
if (documentMap.has(doc._id)) {
|
|
4101
|
-
logger.warn(`Duplicate document ID found: ${doc._id}, using latest version`);
|
|
4102
|
-
}
|
|
4103
|
-
documentMap.set(doc._id, doc);
|
|
4104
|
-
}
|
|
4105
|
-
} catch (error) {
|
|
4106
|
-
throw new Error(
|
|
4107
|
-
`Failed to load chunk ${chunk.id}: ${error instanceof Error ? error.message : String(error)}`
|
|
4108
|
-
);
|
|
4109
|
-
}
|
|
4110
|
-
}
|
|
4111
|
-
allDocuments.push(...documentMap.values());
|
|
4112
|
-
logger.info(
|
|
4113
|
-
`Aggregated ${allDocuments.length} unique documents from ${manifest.chunks.length} chunks`
|
|
4114
|
-
);
|
|
4115
|
-
return allDocuments;
|
|
4116
|
-
}
|
|
4117
|
-
/**
|
|
4118
|
-
* Load documents from a single chunk file
|
|
4119
|
-
*/
|
|
4120
|
-
async loadChunk(staticPath, chunk) {
|
|
4121
|
-
try {
|
|
4122
|
-
let chunkContent;
|
|
4123
|
-
let chunkPath;
|
|
4124
|
-
if (this.fs) {
|
|
4125
|
-
chunkPath = this.fs.joinPath(staticPath, chunk.path);
|
|
4126
|
-
chunkContent = await this.fs.readFile(chunkPath);
|
|
4127
|
-
} else {
|
|
4128
|
-
chunkPath = nodeFS2 && nodePath ? nodePath.join(staticPath, chunk.path) : `${staticPath}/${chunk.path}`;
|
|
4129
|
-
if (nodeFS2 && this.isLocalPath(staticPath)) {
|
|
4130
|
-
chunkContent = await nodeFS2.promises.readFile(chunkPath, "utf8");
|
|
4131
|
-
} else {
|
|
4132
|
-
const response = await fetch(chunkPath);
|
|
4133
|
-
if (!response.ok) {
|
|
4134
|
-
throw new Error(`Failed to fetch chunk: ${response.status} ${response.statusText}`);
|
|
4135
|
-
}
|
|
4136
|
-
chunkContent = await response.text();
|
|
4137
|
-
}
|
|
4138
|
-
}
|
|
4139
|
-
const documents = JSON.parse(chunkContent);
|
|
4140
|
-
if (!Array.isArray(documents)) {
|
|
4141
|
-
throw new Error("Chunk file does not contain an array of documents");
|
|
4142
|
-
}
|
|
4143
|
-
return documents;
|
|
4144
|
-
} catch (error) {
|
|
4145
|
-
const errorMessage = error instanceof FileSystemError ? error.message : `Failed to load chunk: ${error instanceof Error ? error.message : String(error)}`;
|
|
4146
|
-
throw new Error(errorMessage);
|
|
4147
|
-
}
|
|
4148
|
-
}
|
|
4149
|
-
/**
|
|
4150
|
-
* Upload documents to CouchDB in batches
|
|
4151
|
-
*/
|
|
4152
|
-
async uploadDocuments(documents, db) {
|
|
4153
|
-
const result = { restored: 0, errors: [], warnings: [] };
|
|
4154
|
-
const batchSize = this.options.chunkBatchSize;
|
|
4155
|
-
for (let i = 0; i < documents.length; i += batchSize) {
|
|
4156
|
-
const batch = documents.slice(i, i + batchSize);
|
|
4157
|
-
this.reportProgress(
|
|
4158
|
-
"documents",
|
|
4159
|
-
i,
|
|
4160
|
-
documents.length,
|
|
4161
|
-
`Uploading batch ${Math.floor(i / batchSize) + 1}...`
|
|
4162
|
-
);
|
|
4163
|
-
try {
|
|
4164
|
-
const docsToInsert = batch.map((doc) => {
|
|
4165
|
-
const cleanDoc = { ...doc };
|
|
4166
|
-
delete cleanDoc._rev;
|
|
4167
|
-
delete cleanDoc._attachments;
|
|
4168
|
-
return cleanDoc;
|
|
4169
|
-
});
|
|
4170
|
-
const bulkResult = await db.bulkDocs(docsToInsert);
|
|
4171
|
-
for (let j = 0; j < bulkResult.length; j++) {
|
|
4172
|
-
const docResult = bulkResult[j];
|
|
4173
|
-
const originalDoc = batch[j];
|
|
4174
|
-
if ("error" in docResult) {
|
|
4175
|
-
const errorMessage = `Failed to upload document ${originalDoc._id}: ${docResult.error} - ${docResult.reason}`;
|
|
4176
|
-
result.errors.push(errorMessage);
|
|
4177
|
-
logger.error(errorMessage);
|
|
4178
|
-
} else {
|
|
4179
|
-
result.restored++;
|
|
4180
|
-
}
|
|
4181
|
-
}
|
|
4182
|
-
} catch (error) {
|
|
4183
|
-
let errorMessage;
|
|
4184
|
-
if (error instanceof Error) {
|
|
4185
|
-
errorMessage = `Failed to upload document batch starting at index ${i}: ${error.message}`;
|
|
4186
|
-
} else if (error && typeof error === "object" && "message" in error) {
|
|
4187
|
-
errorMessage = `Failed to upload document batch starting at index ${i}: ${error.message}`;
|
|
4188
|
-
} else {
|
|
4189
|
-
errorMessage = `Failed to upload document batch starting at index ${i}: ${JSON.stringify(error)}`;
|
|
4190
|
-
}
|
|
4191
|
-
result.errors.push(errorMessage);
|
|
4192
|
-
logger.error(errorMessage);
|
|
4193
|
-
}
|
|
4194
|
-
}
|
|
4195
|
-
this.reportProgress(
|
|
4196
|
-
"documents",
|
|
4197
|
-
documents.length,
|
|
4198
|
-
documents.length,
|
|
4199
|
-
`Uploaded ${result.restored} documents`
|
|
4200
|
-
);
|
|
4201
|
-
return result;
|
|
4202
|
-
}
|
|
4203
|
-
/**
|
|
4204
|
-
* Upload attachments from filesystem to CouchDB
|
|
4205
|
-
*/
|
|
4206
|
-
async uploadAttachments(staticPath, documents, db) {
|
|
4207
|
-
const result = { restored: 0, errors: [], warnings: [] };
|
|
4208
|
-
let processedDocs = 0;
|
|
4209
|
-
for (const doc of documents) {
|
|
4210
|
-
this.reportProgress(
|
|
4211
|
-
"attachments",
|
|
4212
|
-
processedDocs,
|
|
4213
|
-
documents.length,
|
|
4214
|
-
`Processing attachments for ${doc._id}...`
|
|
4215
|
-
);
|
|
4216
|
-
processedDocs++;
|
|
4217
|
-
if (!doc._attachments) {
|
|
4218
|
-
continue;
|
|
4219
|
-
}
|
|
4220
|
-
for (const [attachmentName, attachmentMeta] of Object.entries(doc._attachments)) {
|
|
4221
|
-
try {
|
|
4222
|
-
const uploadResult = await this.uploadSingleAttachment(
|
|
4223
|
-
staticPath,
|
|
4224
|
-
doc._id,
|
|
4225
|
-
attachmentName,
|
|
4226
|
-
attachmentMeta,
|
|
4227
|
-
db
|
|
4228
|
-
);
|
|
4229
|
-
if (uploadResult.success) {
|
|
4230
|
-
result.restored++;
|
|
4231
|
-
} else {
|
|
4232
|
-
result.errors.push(uploadResult.error || "Unknown attachment upload error");
|
|
4233
|
-
}
|
|
4234
|
-
} catch (error) {
|
|
4235
|
-
const errorMessage = `Failed to upload attachment ${doc._id}/${attachmentName}: ${error instanceof Error ? error.message : String(error)}`;
|
|
4236
|
-
result.errors.push(errorMessage);
|
|
4237
|
-
logger.error(errorMessage);
|
|
4238
|
-
}
|
|
4239
|
-
}
|
|
4240
|
-
}
|
|
4241
|
-
this.reportProgress(
|
|
4242
|
-
"attachments",
|
|
4243
|
-
documents.length,
|
|
4244
|
-
documents.length,
|
|
4245
|
-
`Uploaded ${result.restored} attachments`
|
|
4246
|
-
);
|
|
4247
|
-
return result;
|
|
4248
|
-
}
|
|
4249
|
-
/**
|
|
4250
|
-
* Upload a single attachment file
|
|
4251
|
-
*/
|
|
4252
|
-
async uploadSingleAttachment(staticPath, docId, attachmentName, attachmentMeta, db) {
|
|
4253
|
-
const result = {
|
|
4254
|
-
success: false,
|
|
4255
|
-
attachmentName,
|
|
4256
|
-
docId
|
|
4257
|
-
};
|
|
4258
|
-
try {
|
|
4259
|
-
if (!attachmentMeta.path) {
|
|
4260
|
-
result.error = "Attachment metadata missing file path";
|
|
4261
|
-
return result;
|
|
4262
|
-
}
|
|
4263
|
-
let attachmentData;
|
|
4264
|
-
let attachmentPath;
|
|
4265
|
-
if (this.fs) {
|
|
4266
|
-
attachmentPath = this.fs.joinPath(staticPath, attachmentMeta.path);
|
|
4267
|
-
attachmentData = await this.fs.readBinary(attachmentPath);
|
|
4268
|
-
} else {
|
|
4269
|
-
attachmentPath = nodeFS2 && nodePath ? nodePath.join(staticPath, attachmentMeta.path) : `${staticPath}/${attachmentMeta.path}`;
|
|
4270
|
-
if (nodeFS2 && this.isLocalPath(staticPath)) {
|
|
4271
|
-
attachmentData = await nodeFS2.promises.readFile(attachmentPath);
|
|
4272
|
-
} else {
|
|
4273
|
-
const response = await fetch(attachmentPath);
|
|
4274
|
-
if (!response.ok) {
|
|
4275
|
-
result.error = `Failed to fetch attachment: ${response.status} ${response.statusText}`;
|
|
4276
|
-
return result;
|
|
4277
|
-
}
|
|
4278
|
-
attachmentData = await response.arrayBuffer();
|
|
4279
|
-
}
|
|
4280
|
-
}
|
|
4281
|
-
const doc = await db.get(docId);
|
|
4282
|
-
await db.putAttachment(
|
|
4283
|
-
docId,
|
|
4284
|
-
attachmentName,
|
|
4285
|
-
doc._rev,
|
|
4286
|
-
attachmentData,
|
|
4287
|
-
// PouchDB accepts both ArrayBuffer and Buffer
|
|
4288
|
-
attachmentMeta.content_type
|
|
4289
|
-
);
|
|
4290
|
-
result.success = true;
|
|
4291
|
-
} catch (error) {
|
|
4292
|
-
result.error = error instanceof Error ? error.message : String(error);
|
|
4293
|
-
}
|
|
4294
|
-
return result;
|
|
4295
|
-
}
|
|
4296
|
-
/**
|
|
4297
|
-
* Restore CourseConfig document from manifest
|
|
4298
|
-
*/
|
|
4299
|
-
async restoreCourseConfig(manifest, targetDB) {
|
|
4300
|
-
const results = {
|
|
4301
|
-
restored: 0,
|
|
4302
|
-
errors: [],
|
|
4303
|
-
warnings: []
|
|
4304
|
-
};
|
|
4305
|
-
try {
|
|
4306
|
-
if (!manifest.courseConfig) {
|
|
4307
|
-
results.warnings.push(
|
|
4308
|
-
"No courseConfig found in manifest, skipping CourseConfig document creation"
|
|
4309
|
-
);
|
|
4310
|
-
return results;
|
|
4311
|
-
}
|
|
4312
|
-
const courseConfigDoc = {
|
|
4313
|
-
_id: "CourseConfig",
|
|
4314
|
-
...manifest.courseConfig,
|
|
4315
|
-
courseID: manifest.courseId
|
|
4316
|
-
};
|
|
4317
|
-
delete courseConfigDoc._rev;
|
|
4318
|
-
await targetDB.put(courseConfigDoc);
|
|
4319
|
-
results.restored = 1;
|
|
4320
|
-
logger.info(`CourseConfig document created for course: ${manifest.courseId}`);
|
|
4321
|
-
} catch (error) {
|
|
4322
|
-
const errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
|
|
4323
|
-
results.errors.push(`Failed to restore CourseConfig: ${errorMessage}`);
|
|
4324
|
-
logger.error("CourseConfig restoration failed:", error);
|
|
4325
|
-
}
|
|
4326
|
-
return results;
|
|
4327
|
-
}
|
|
4328
|
-
/**
|
|
4329
|
-
* Calculate expected document counts from manifest
|
|
4330
|
-
*/
|
|
4331
|
-
calculateExpectedCounts(manifest) {
|
|
4332
|
-
const counts = {};
|
|
4333
|
-
for (const chunk of manifest.chunks) {
|
|
4334
|
-
counts[chunk.docType] = (counts[chunk.docType] || 0) + chunk.documentCount;
|
|
4335
|
-
}
|
|
4336
|
-
if (manifest.designDocs.length > 0) {
|
|
4337
|
-
counts["_design"] = manifest.designDocs.length;
|
|
4338
|
-
}
|
|
4339
|
-
return counts;
|
|
4340
|
-
}
|
|
4341
|
-
/**
|
|
4342
|
-
* Clean up database after failed migration
|
|
4343
|
-
*/
|
|
4344
|
-
async cleanupFailedMigration(db) {
|
|
4345
|
-
logger.info("Cleaning up failed migration...");
|
|
4346
|
-
try {
|
|
4347
|
-
const allDocs = await db.allDocs();
|
|
4348
|
-
const docsToDelete = allDocs.rows.map((row) => ({
|
|
4349
|
-
_id: row.id,
|
|
4350
|
-
_rev: row.value.rev,
|
|
4351
|
-
_deleted: true
|
|
4352
|
-
}));
|
|
4353
|
-
if (docsToDelete.length > 0) {
|
|
4354
|
-
await db.bulkDocs(docsToDelete);
|
|
4355
|
-
logger.info(`Cleaned up ${docsToDelete.length} documents from failed migration`);
|
|
4356
|
-
}
|
|
4357
|
-
} catch (error) {
|
|
4358
|
-
logger.error("Failed to cleanup documents:", error);
|
|
4359
|
-
throw error;
|
|
4360
|
-
}
|
|
4361
|
-
}
|
|
4362
|
-
/**
|
|
4363
|
-
* Report progress to callback if available
|
|
4364
|
-
*/
|
|
4365
|
-
reportProgress(phase, current, total, message) {
|
|
4366
|
-
if (this.progressCallback) {
|
|
4367
|
-
this.progressCallback({
|
|
4368
|
-
phase,
|
|
4369
|
-
current,
|
|
4370
|
-
total,
|
|
4371
|
-
message
|
|
4372
|
-
});
|
|
4373
|
-
}
|
|
4374
|
-
}
|
|
4375
|
-
/**
|
|
4376
|
-
* Check if a path is a local file path (vs URL)
|
|
4377
|
-
*/
|
|
4378
|
-
isLocalPath(path2) {
|
|
4379
|
-
return !path2.startsWith("http://") && !path2.startsWith("https://");
|
|
4380
|
-
}
|
|
4381
|
-
};
|
|
4382
|
-
}
|
|
4383
|
-
});
|
|
4384
|
-
|
|
4385
|
-
// src/util/migrator/index.ts
|
|
4386
|
-
var init_migrator = __esm({
|
|
4387
|
-
"src/util/migrator/index.ts"() {
|
|
4388
|
-
"use strict";
|
|
4389
|
-
init_StaticToCouchDBMigrator();
|
|
4390
|
-
init_validation();
|
|
4391
|
-
init_FileSystemAdapter();
|
|
4392
|
-
}
|
|
4393
|
-
});
|
|
4394
|
-
|
|
4395
|
-
// src/util/index.ts
|
|
4396
|
-
var init_util2 = __esm({
|
|
4397
|
-
"src/util/index.ts"() {
|
|
4398
|
-
"use strict";
|
|
4399
|
-
init_Loggable();
|
|
4400
|
-
init_packer();
|
|
4401
|
-
init_migrator();
|
|
4402
|
-
init_dataDirectory();
|
|
4403
|
-
}
|
|
4404
|
-
});
|
|
4405
|
-
|
|
4406
|
-
// src/study/SourceMixer.ts
|
|
4407
|
-
var init_SourceMixer = __esm({
|
|
4408
|
-
"src/study/SourceMixer.ts"() {
|
|
4409
|
-
"use strict";
|
|
4410
|
-
}
|
|
4411
|
-
});
|
|
4412
|
-
|
|
4413
|
-
// src/study/MixerDebugger.ts
|
|
4414
|
-
function printMixerSummary(run) {
|
|
4415
|
-
console.group(`\u{1F3A8} Mixer Run: ${run.mixerType}`);
|
|
4416
|
-
logger.info(`Run ID: ${run.runId}`);
|
|
4417
|
-
logger.info(`Time: ${run.timestamp.toISOString()}`);
|
|
4418
|
-
logger.info(
|
|
4419
|
-
`Config: limit=${run.requestedLimit}${run.quotaPerSource ? `, quota/source=${run.quotaPerSource}` : ""}`
|
|
4420
|
-
);
|
|
4421
|
-
console.group(`\u{1F4E5} Input: ${run.sourceSummaries.length} sources`);
|
|
4422
|
-
for (const src of run.sourceSummaries) {
|
|
4423
|
-
logger.info(
|
|
4424
|
-
` ${src.sourceName || src.sourceId}: ${src.totalCards} cards (${src.reviewCount} reviews, ${src.newCount} new)`
|
|
4425
|
-
);
|
|
4426
|
-
logger.info(` Score range: [${src.scoreRange[0].toFixed(2)}, ${src.scoreRange[1].toFixed(2)}], avg: ${src.avgScore.toFixed(2)}`);
|
|
4427
|
-
}
|
|
4428
|
-
console.groupEnd();
|
|
4429
|
-
console.group(`\u{1F4E4} Output: ${run.finalCount} cards selected (${run.reviewsSelected} reviews, ${run.newSelected} new)`);
|
|
4430
|
-
for (const breakdown of run.sourceBreakdowns) {
|
|
4431
|
-
const name = breakdown.sourceName || breakdown.sourceId;
|
|
4432
|
-
logger.info(
|
|
4433
|
-
` ${name}: ${breakdown.totalSelected} selected (${breakdown.reviewsSelected} reviews, ${breakdown.newSelected} new) - ${breakdown.selectionRate.toFixed(1)}% selection rate`
|
|
4434
|
-
);
|
|
4435
|
-
}
|
|
4436
|
-
console.groupEnd();
|
|
4437
|
-
console.groupEnd();
|
|
4438
|
-
}
|
|
4439
|
-
function mountMixerDebugger() {
|
|
4440
|
-
if (typeof window === "undefined") return;
|
|
4441
|
-
const win = window;
|
|
4442
|
-
win.skuilder = win.skuilder || {};
|
|
4443
|
-
win.skuilder.mixer = mixerDebugAPI;
|
|
4444
|
-
}
|
|
4445
|
-
var runHistory2, mixerDebugAPI;
|
|
4446
|
-
var init_MixerDebugger = __esm({
|
|
4447
|
-
"src/study/MixerDebugger.ts"() {
|
|
4448
|
-
"use strict";
|
|
4449
|
-
init_logger();
|
|
4450
|
-
init_navigators();
|
|
4451
|
-
runHistory2 = [];
|
|
4452
|
-
mixerDebugAPI = {
|
|
4453
|
-
/**
|
|
4454
|
-
* Get raw run history for programmatic access.
|
|
4455
|
-
*/
|
|
4456
|
-
get runs() {
|
|
4457
|
-
return [...runHistory2];
|
|
4458
|
-
},
|
|
4459
|
-
/**
|
|
4460
|
-
* Show summary of a specific mixer run.
|
|
4461
|
-
*/
|
|
4462
|
-
showRun(idOrIndex = 0) {
|
|
4463
|
-
if (runHistory2.length === 0) {
|
|
4464
|
-
logger.info("[Mixer Debug] No runs captured yet.");
|
|
4465
|
-
return;
|
|
4466
|
-
}
|
|
4467
|
-
let run;
|
|
4468
|
-
if (typeof idOrIndex === "number") {
|
|
4469
|
-
run = runHistory2[idOrIndex];
|
|
4470
|
-
if (!run) {
|
|
4471
|
-
logger.info(`[Mixer Debug] No run found at index ${idOrIndex}. History length: ${runHistory2.length}`);
|
|
4472
|
-
return;
|
|
4473
|
-
}
|
|
4474
|
-
} else {
|
|
4475
|
-
run = runHistory2.find((r) => r.runId.endsWith(idOrIndex));
|
|
4476
|
-
if (!run) {
|
|
4477
|
-
logger.info(`[Mixer Debug] No run found matching ID '${idOrIndex}'.`);
|
|
4478
|
-
return;
|
|
4479
|
-
}
|
|
4480
|
-
}
|
|
4481
|
-
printMixerSummary(run);
|
|
4482
|
-
},
|
|
4483
|
-
/**
|
|
4484
|
-
* Show summary of the last mixer run.
|
|
4485
|
-
*/
|
|
4486
|
-
showLastMix() {
|
|
4487
|
-
this.showRun(0);
|
|
4488
|
-
},
|
|
4489
|
-
/**
|
|
4490
|
-
* Explain source balance in the last run.
|
|
4491
|
-
*/
|
|
4492
|
-
explainSourceBalance() {
|
|
4493
|
-
if (runHistory2.length === 0) {
|
|
4494
|
-
logger.info("[Mixer Debug] No runs captured yet.");
|
|
4495
|
-
return;
|
|
4496
|
-
}
|
|
4497
|
-
const run = runHistory2[0];
|
|
4498
|
-
console.group("\u2696\uFE0F Source Balance Analysis");
|
|
4499
|
-
logger.info(`Mixer: ${run.mixerType}`);
|
|
4500
|
-
logger.info(`Requested limit: ${run.requestedLimit}`);
|
|
4501
|
-
if (run.quotaPerSource) {
|
|
4502
|
-
logger.info(`Quota per source: ${run.quotaPerSource}`);
|
|
4503
|
-
}
|
|
4504
|
-
console.group("Input Distribution:");
|
|
4505
|
-
for (const src of run.sourceSummaries) {
|
|
4506
|
-
const name = src.sourceName || src.sourceId;
|
|
4507
|
-
logger.info(`${name}:`);
|
|
4508
|
-
logger.info(` Provided: ${src.totalCards} cards (${src.reviewCount} reviews, ${src.newCount} new)`);
|
|
4509
|
-
logger.info(` Score range: [${src.scoreRange[0].toFixed(2)}, ${src.scoreRange[1].toFixed(2)}]`);
|
|
4510
|
-
}
|
|
4511
|
-
console.groupEnd();
|
|
4512
|
-
console.group("Selection Results:");
|
|
4513
|
-
for (const breakdown of run.sourceBreakdowns) {
|
|
4514
|
-
const name = breakdown.sourceName || breakdown.sourceId;
|
|
4515
|
-
logger.info(`${name}:`);
|
|
4516
|
-
logger.info(
|
|
4517
|
-
` Selected: ${breakdown.totalSelected}/${breakdown.reviewsProvided + breakdown.newProvided} (${breakdown.selectionRate.toFixed(1)}%)`
|
|
4518
|
-
);
|
|
4519
|
-
logger.info(` Reviews: ${breakdown.reviewsSelected}/${breakdown.reviewsProvided}`);
|
|
4520
|
-
logger.info(` New: ${breakdown.newSelected}/${breakdown.newProvided}`);
|
|
4521
|
-
if (breakdown.reviewsProvided > 0 && breakdown.reviewsSelected === 0) {
|
|
4522
|
-
logger.info(` \u26A0\uFE0F Had reviews but none selected!`);
|
|
4523
|
-
}
|
|
4524
|
-
if (breakdown.totalSelected === 0 && breakdown.reviewsProvided + breakdown.newProvided > 0) {
|
|
4525
|
-
logger.info(` \u26A0\uFE0F Had cards but none selected!`);
|
|
4526
|
-
}
|
|
4527
|
-
}
|
|
4528
|
-
console.groupEnd();
|
|
4529
|
-
const selectionRates = run.sourceBreakdowns.map((b) => b.selectionRate);
|
|
4530
|
-
const avgRate = selectionRates.reduce((a, b) => a + b, 0) / selectionRates.length;
|
|
4531
|
-
const maxDeviation = Math.max(...selectionRates.map((r) => Math.abs(r - avgRate)));
|
|
4532
|
-
if (maxDeviation > 20) {
|
|
4533
|
-
logger.info(`
|
|
4534
|
-
\u26A0\uFE0F Significant imbalance detected (max deviation: ${maxDeviation.toFixed(1)}%)`);
|
|
4535
|
-
logger.info("Possible causes:");
|
|
4536
|
-
logger.info(" - Score range differences between sources");
|
|
4537
|
-
logger.info(" - One source has much better quality cards");
|
|
4538
|
-
logger.info(" - Different card availability (reviews vs new)");
|
|
4539
|
-
}
|
|
4540
|
-
console.groupEnd();
|
|
4541
|
-
},
|
|
4542
|
-
/**
|
|
4543
|
-
* Compare score distributions across sources.
|
|
4544
|
-
*/
|
|
4545
|
-
compareScores() {
|
|
4546
|
-
if (runHistory2.length === 0) {
|
|
4547
|
-
logger.info("[Mixer Debug] No runs captured yet.");
|
|
4548
|
-
return;
|
|
4549
|
-
}
|
|
4550
|
-
const run = runHistory2[0];
|
|
4551
|
-
console.group("\u{1F4CA} Score Distribution Comparison");
|
|
4552
|
-
console.table(
|
|
4553
|
-
run.sourceSummaries.map((src) => ({
|
|
4554
|
-
source: src.sourceName || src.sourceId,
|
|
4555
|
-
cards: src.totalCards,
|
|
4556
|
-
min: src.bottomScore.toFixed(3),
|
|
4557
|
-
max: src.topScore.toFixed(3),
|
|
4558
|
-
avg: src.avgScore.toFixed(3),
|
|
4559
|
-
range: (src.topScore - src.bottomScore).toFixed(3)
|
|
4560
|
-
}))
|
|
4561
|
-
);
|
|
4562
|
-
const ranges = run.sourceSummaries.map((s) => s.topScore - s.bottomScore);
|
|
4563
|
-
const avgScores = run.sourceSummaries.map((s) => s.avgScore);
|
|
4564
|
-
const rangeDiff = Math.max(...ranges) - Math.min(...ranges);
|
|
4565
|
-
const avgDiff = Math.max(...avgScores) - Math.min(...avgScores);
|
|
4566
|
-
if (rangeDiff > 0.3 || avgDiff > 0.2) {
|
|
4567
|
-
logger.info("\n\u26A0\uFE0F Significant score distribution differences detected");
|
|
4568
|
-
logger.info(
|
|
4569
|
-
"This may cause one source to dominate selection if using global sorting (not quota-based)"
|
|
4570
|
-
);
|
|
4571
|
-
}
|
|
4572
|
-
console.groupEnd();
|
|
4573
|
-
},
|
|
4574
|
-
/**
|
|
4575
|
-
* Show detailed information for a specific card.
|
|
4576
|
-
*/
|
|
4577
|
-
showCard(cardId) {
|
|
4578
|
-
for (const run of runHistory2) {
|
|
4579
|
-
const card = run.cards.find((c) => c.cardId === cardId);
|
|
4580
|
-
if (card) {
|
|
4581
|
-
const source = run.sourceSummaries.find((s) => s.sourceIndex === card.sourceIndex);
|
|
4582
|
-
console.group(`\u{1F3B4} Card: ${cardId}`);
|
|
4583
|
-
logger.info(`Course: ${card.courseId}`);
|
|
4584
|
-
logger.info(`Source: ${source?.sourceName || source?.sourceId || "unknown"}`);
|
|
4585
|
-
logger.info(`Origin: ${card.origin}`);
|
|
4586
|
-
logger.info(`Score: ${card.score.toFixed(3)}`);
|
|
4587
|
-
if (card.rankInSource) {
|
|
4588
|
-
logger.info(`Rank in source: #${card.rankInSource}`);
|
|
4589
|
-
}
|
|
4590
|
-
if (card.rankInMix) {
|
|
4591
|
-
logger.info(`Rank in mixed results: #${card.rankInMix}`);
|
|
4592
|
-
}
|
|
4593
|
-
logger.info(`Selected: ${card.selected ? "Yes \u2705" : "No \u274C"}`);
|
|
4594
|
-
if (!card.selected && card.rankInSource) {
|
|
4595
|
-
logger.info("\nWhy not selected:");
|
|
4596
|
-
if (run.quotaPerSource && card.rankInSource > run.quotaPerSource) {
|
|
4597
|
-
logger.info(` - Ranked #${card.rankInSource} in source, but quota was ${run.quotaPerSource}`);
|
|
4598
|
-
}
|
|
4599
|
-
logger.info(" - Check score compared to selected cards using .showRun()");
|
|
4600
|
-
}
|
|
4601
|
-
console.groupEnd();
|
|
4602
|
-
return;
|
|
4603
|
-
}
|
|
4604
|
-
}
|
|
4605
|
-
logger.info(`[Mixer Debug] Card '${cardId}' not found in recent runs.`);
|
|
4606
|
-
},
|
|
4607
|
-
/**
|
|
4608
|
-
* Show all runs in compact format.
|
|
4609
|
-
*/
|
|
4610
|
-
listRuns() {
|
|
4611
|
-
if (runHistory2.length === 0) {
|
|
4612
|
-
logger.info("[Mixer Debug] No runs captured yet.");
|
|
4613
|
-
return;
|
|
4614
|
-
}
|
|
4615
|
-
console.table(
|
|
4616
|
-
runHistory2.map((r) => ({
|
|
4617
|
-
id: r.runId.slice(-8),
|
|
4618
|
-
time: r.timestamp.toLocaleTimeString(),
|
|
4619
|
-
mixer: r.mixerType,
|
|
4620
|
-
sources: r.sourceSummaries.length,
|
|
4621
|
-
selected: r.finalCount,
|
|
4622
|
-
reviews: r.reviewsSelected,
|
|
4623
|
-
new: r.newSelected
|
|
4624
|
-
}))
|
|
4625
|
-
);
|
|
4626
|
-
},
|
|
4627
|
-
/**
|
|
4628
|
-
* Export run history as JSON for bug reports.
|
|
4629
|
-
*/
|
|
4630
|
-
export() {
|
|
4631
|
-
const json = JSON.stringify(runHistory2, null, 2);
|
|
4632
|
-
logger.info("[Mixer Debug] Run history exported. Copy the returned string or use:");
|
|
4633
|
-
logger.info(" copy(window.skuilder.mixer.export())");
|
|
4634
|
-
return json;
|
|
4635
|
-
},
|
|
4636
|
-
/**
|
|
4637
|
-
* Clear run history.
|
|
4638
|
-
*/
|
|
4639
|
-
clear() {
|
|
4640
|
-
runHistory2.length = 0;
|
|
4641
|
-
logger.info("[Mixer Debug] Run history cleared.");
|
|
4642
|
-
},
|
|
4643
|
-
/**
|
|
4644
|
-
* Show help.
|
|
4645
|
-
*/
|
|
4646
|
-
help() {
|
|
4647
|
-
logger.info(`
|
|
4648
|
-
\u{1F3A8} Mixer Debug API
|
|
4649
|
-
|
|
4650
|
-
Commands:
|
|
4651
|
-
.showLastMix() Show summary of most recent mixer run
|
|
4652
|
-
.showRun(id|index) Show summary of a specific run (by index or ID suffix)
|
|
4653
|
-
.explainSourceBalance() Analyze source balance and selection patterns
|
|
4654
|
-
.compareScores() Compare score distributions across sources
|
|
4655
|
-
.showCard(cardId) Show mixer decisions for a specific card
|
|
4656
|
-
.listRuns() List all captured runs in table format
|
|
4657
|
-
.export() Export run history as JSON for bug reports
|
|
4658
|
-
.clear() Clear run history
|
|
4659
|
-
.runs Access raw run history array
|
|
4660
|
-
.help() Show this help message
|
|
4661
|
-
|
|
4662
|
-
Example:
|
|
4663
|
-
window.skuilder.mixer.showLastMix()
|
|
4664
|
-
window.skuilder.mixer.explainSourceBalance()
|
|
4665
|
-
window.skuilder.mixer.compareScores()
|
|
4666
|
-
`);
|
|
4667
|
-
}
|
|
4668
|
-
};
|
|
4669
|
-
mountMixerDebugger();
|
|
4670
|
-
}
|
|
4671
|
-
});
|
|
4672
|
-
|
|
4673
|
-
// src/study/SessionDebugger.ts
|
|
4674
|
-
function showCurrentQueue() {
|
|
4675
|
-
if (!activeSession) {
|
|
4676
|
-
logger.info("[Session Debug] No active session.");
|
|
4677
|
-
return;
|
|
3729
|
+
// src/core/orchestration/signal.ts
|
|
3730
|
+
function computeOutcomeSignal(records, config = {}) {
|
|
3731
|
+
if (!records || records.length === 0) {
|
|
3732
|
+
return null;
|
|
4678
3733
|
}
|
|
4679
|
-
const
|
|
4680
|
-
|
|
4681
|
-
|
|
4682
|
-
|
|
4683
|
-
|
|
3734
|
+
const target = config.targetAccuracy ?? 0.85;
|
|
3735
|
+
const tolerance = config.tolerance ?? 0.05;
|
|
3736
|
+
let correct = 0;
|
|
3737
|
+
for (const r of records) {
|
|
3738
|
+
if (r.isCorrect) correct++;
|
|
4684
3739
|
}
|
|
4685
|
-
|
|
4686
|
-
|
|
4687
|
-
|
|
3740
|
+
const accuracy = correct / records.length;
|
|
3741
|
+
return scoreAccuracyInZone(accuracy, target, tolerance);
|
|
3742
|
+
}
|
|
3743
|
+
function scoreAccuracyInZone(accuracy, target, tolerance) {
|
|
3744
|
+
const dist = Math.abs(accuracy - target);
|
|
3745
|
+
if (dist <= tolerance) {
|
|
3746
|
+
return 1;
|
|
4688
3747
|
}
|
|
4689
|
-
|
|
4690
|
-
|
|
3748
|
+
const excess = dist - tolerance;
|
|
3749
|
+
const slope = 2.5;
|
|
3750
|
+
return Math.max(0, 1 - excess * slope);
|
|
4691
3751
|
}
|
|
4692
|
-
|
|
4693
|
-
|
|
4694
|
-
|
|
4695
|
-
logger.info(`[Session Debug] No session found at index ${sessionIndex}`);
|
|
4696
|
-
return;
|
|
3752
|
+
var init_signal = __esm({
|
|
3753
|
+
"src/core/orchestration/signal.ts"() {
|
|
3754
|
+
"use strict";
|
|
4697
3755
|
}
|
|
4698
|
-
|
|
4699
|
-
|
|
4700
|
-
|
|
4701
|
-
|
|
4702
|
-
}
|
|
4703
|
-
|
|
4704
|
-
|
|
4705
|
-
|
|
4706
|
-
|
|
4707
|
-
|
|
4708
|
-
course: p.courseName || p.courseId.slice(0, 8),
|
|
4709
|
-
origin: p.origin,
|
|
4710
|
-
queue: p.queueSource,
|
|
4711
|
-
score: p.score?.toFixed(3) || "-",
|
|
4712
|
-
time: p.timestamp.toLocaleTimeString()
|
|
4713
|
-
}))
|
|
3756
|
+
});
|
|
3757
|
+
|
|
3758
|
+
// src/core/orchestration/recording.ts
|
|
3759
|
+
async function recordUserOutcome(context, periodStart, periodEnd, records, activeStrategyIds, eloStart = 0, eloEnd = 0, config) {
|
|
3760
|
+
const { user, course, userId } = context;
|
|
3761
|
+
const courseId = course.getCourseID();
|
|
3762
|
+
const outcomeValue = computeOutcomeSignal(records, config);
|
|
3763
|
+
if (outcomeValue === null) {
|
|
3764
|
+
logger.debug(
|
|
3765
|
+
`[Orchestration] No outcome signal computed for ${userId} (insufficient data). Skipping record.`
|
|
4714
3766
|
);
|
|
4715
|
-
}
|
|
4716
|
-
console.groupEnd();
|
|
4717
|
-
}
|
|
4718
|
-
function showInterleaving(sessionIndex = 0) {
|
|
4719
|
-
const session = sessionIndex === 0 && activeSession ? activeSession : sessionHistory[sessionIndex];
|
|
4720
|
-
if (!session) {
|
|
4721
|
-
logger.info(`[Session Debug] No session found at index ${sessionIndex}`);
|
|
4722
3767
|
return;
|
|
4723
3768
|
}
|
|
4724
|
-
|
|
4725
|
-
const
|
|
4726
|
-
|
|
4727
|
-
session.presentations.forEach((p) => {
|
|
4728
|
-
const name = p.courseName || p.courseId;
|
|
4729
|
-
courseCounts.set(name, (courseCounts.get(name) || 0) + 1);
|
|
4730
|
-
if (!courseOrigins.has(name)) {
|
|
4731
|
-
courseOrigins.set(name, { review: 0, new: 0, failed: 0 });
|
|
4732
|
-
}
|
|
4733
|
-
const origins = courseOrigins.get(name);
|
|
4734
|
-
origins[p.origin]++;
|
|
4735
|
-
});
|
|
4736
|
-
logger.info("Course distribution:");
|
|
4737
|
-
console.table(
|
|
4738
|
-
Array.from(courseCounts.entries()).map(([course, count]) => {
|
|
4739
|
-
const origins = courseOrigins.get(course);
|
|
4740
|
-
return {
|
|
4741
|
-
course,
|
|
4742
|
-
total: count,
|
|
4743
|
-
reviews: origins.review,
|
|
4744
|
-
new: origins.new,
|
|
4745
|
-
failed: origins.failed,
|
|
4746
|
-
percentage: (count / session.presentations.length * 100).toFixed(1) + "%"
|
|
4747
|
-
};
|
|
4748
|
-
})
|
|
4749
|
-
);
|
|
4750
|
-
if (session.presentations.length > 0) {
|
|
4751
|
-
logger.info("\nPresentation sequence (first 20):");
|
|
4752
|
-
const sequence = session.presentations.slice(0, 20).map((p, idx) => `${idx + 1}. ${p.courseName || p.courseId.slice(0, 8)} (${p.origin})`).join("\n");
|
|
4753
|
-
logger.info(sequence);
|
|
4754
|
-
}
|
|
4755
|
-
let maxCluster = 0;
|
|
4756
|
-
let currentCluster = 1;
|
|
4757
|
-
let currentCourse = session.presentations[0]?.courseId;
|
|
4758
|
-
for (let i = 1; i < session.presentations.length; i++) {
|
|
4759
|
-
if (session.presentations[i].courseId === currentCourse) {
|
|
4760
|
-
currentCluster++;
|
|
4761
|
-
maxCluster = Math.max(maxCluster, currentCluster);
|
|
4762
|
-
} else {
|
|
4763
|
-
currentCourse = session.presentations[i].courseId;
|
|
4764
|
-
currentCluster = 1;
|
|
4765
|
-
}
|
|
3769
|
+
const deviations = {};
|
|
3770
|
+
for (const strategyId of activeStrategyIds) {
|
|
3771
|
+
deviations[strategyId] = context.getDeviation(strategyId);
|
|
4766
3772
|
}
|
|
4767
|
-
|
|
4768
|
-
|
|
4769
|
-
|
|
4770
|
-
|
|
3773
|
+
const id = `USER_OUTCOME::${courseId}::${userId}::${periodEnd}`;
|
|
3774
|
+
const record = {
|
|
3775
|
+
_id: id,
|
|
3776
|
+
docType: "USER_OUTCOME" /* USER_OUTCOME */,
|
|
3777
|
+
courseId,
|
|
3778
|
+
userId,
|
|
3779
|
+
periodStart,
|
|
3780
|
+
periodEnd,
|
|
3781
|
+
outcomeValue,
|
|
3782
|
+
deviations,
|
|
3783
|
+
metadata: {
|
|
3784
|
+
sessionsCount: 1,
|
|
3785
|
+
// Assumes recording is triggered per-session currently
|
|
3786
|
+
cardsSeen: records.length,
|
|
3787
|
+
eloStart,
|
|
3788
|
+
eloEnd,
|
|
3789
|
+
signalType: "accuracy_in_zone"
|
|
3790
|
+
}
|
|
3791
|
+
};
|
|
3792
|
+
try {
|
|
3793
|
+
await user.putUserOutcome(record);
|
|
3794
|
+
logger.debug(
|
|
3795
|
+
`[Orchestration] Recorded outcome ${outcomeValue.toFixed(3)} for ${userId} (doc: ${id})`
|
|
3796
|
+
);
|
|
3797
|
+
} catch (e) {
|
|
3798
|
+
logger.error(`[Orchestration] Failed to record outcome: ${e}`);
|
|
4771
3799
|
}
|
|
4772
|
-
console.groupEnd();
|
|
4773
|
-
}
|
|
4774
|
-
function mountSessionDebugger() {
|
|
4775
|
-
if (typeof window === "undefined") return;
|
|
4776
|
-
const win = window;
|
|
4777
|
-
win.skuilder = win.skuilder || {};
|
|
4778
|
-
win.skuilder.session = sessionDebugAPI;
|
|
4779
3800
|
}
|
|
4780
|
-
var
|
|
4781
|
-
|
|
4782
|
-
"src/study/SessionDebugger.ts"() {
|
|
3801
|
+
var init_recording = __esm({
|
|
3802
|
+
"src/core/orchestration/recording.ts"() {
|
|
4783
3803
|
"use strict";
|
|
3804
|
+
init_signal();
|
|
3805
|
+
init_types_legacy();
|
|
4784
3806
|
init_logger();
|
|
4785
|
-
activeSession = null;
|
|
4786
|
-
sessionHistory = [];
|
|
4787
|
-
sessionDebugAPI = {
|
|
4788
|
-
/**
|
|
4789
|
-
* Get raw session history for programmatic access.
|
|
4790
|
-
*/
|
|
4791
|
-
get sessions() {
|
|
4792
|
-
return [...sessionHistory];
|
|
4793
|
-
},
|
|
4794
|
-
/**
|
|
4795
|
-
* Get active session if any.
|
|
4796
|
-
*/
|
|
4797
|
-
get active() {
|
|
4798
|
-
return activeSession;
|
|
4799
|
-
},
|
|
4800
|
-
/**
|
|
4801
|
-
* Show current queue state.
|
|
4802
|
-
*/
|
|
4803
|
-
showQueue() {
|
|
4804
|
-
showCurrentQueue();
|
|
4805
|
-
},
|
|
4806
|
-
/**
|
|
4807
|
-
* Show presentation history for current or past session.
|
|
4808
|
-
*/
|
|
4809
|
-
showHistory(sessionIndex = 0) {
|
|
4810
|
-
showPresentationHistory(sessionIndex);
|
|
4811
|
-
},
|
|
4812
|
-
/**
|
|
4813
|
-
* Analyze course interleaving pattern.
|
|
4814
|
-
*/
|
|
4815
|
-
showInterleaving(sessionIndex = 0) {
|
|
4816
|
-
showInterleaving(sessionIndex);
|
|
4817
|
-
},
|
|
4818
|
-
/**
|
|
4819
|
-
* List all tracked sessions.
|
|
4820
|
-
*/
|
|
4821
|
-
listSessions() {
|
|
4822
|
-
if (activeSession) {
|
|
4823
|
-
logger.info(`Active session: ${activeSession.sessionId} (${activeSession.presentations.length} cards presented)`);
|
|
4824
|
-
}
|
|
4825
|
-
if (sessionHistory.length === 0) {
|
|
4826
|
-
logger.info("[Session Debug] No completed sessions in history.");
|
|
4827
|
-
return;
|
|
4828
|
-
}
|
|
4829
|
-
console.table(
|
|
4830
|
-
sessionHistory.map((s, idx) => ({
|
|
4831
|
-
index: idx,
|
|
4832
|
-
id: s.sessionId.slice(-8),
|
|
4833
|
-
started: s.startTime.toLocaleTimeString(),
|
|
4834
|
-
ended: s.endTime?.toLocaleTimeString() || "incomplete",
|
|
4835
|
-
cards: s.presentations.length
|
|
4836
|
-
}))
|
|
4837
|
-
);
|
|
4838
|
-
},
|
|
4839
|
-
/**
|
|
4840
|
-
* Export session history as JSON for bug reports.
|
|
4841
|
-
*/
|
|
4842
|
-
export() {
|
|
4843
|
-
const data = {
|
|
4844
|
-
active: activeSession,
|
|
4845
|
-
history: sessionHistory
|
|
4846
|
-
};
|
|
4847
|
-
const json = JSON.stringify(data, null, 2);
|
|
4848
|
-
logger.info("[Session Debug] Session data exported. Copy the returned string or use:");
|
|
4849
|
-
logger.info(" copy(window.skuilder.session.export())");
|
|
4850
|
-
return json;
|
|
4851
|
-
},
|
|
4852
|
-
/**
|
|
4853
|
-
* Clear session history.
|
|
4854
|
-
*/
|
|
4855
|
-
clear() {
|
|
4856
|
-
sessionHistory.length = 0;
|
|
4857
|
-
logger.info("[Session Debug] Session history cleared.");
|
|
4858
|
-
},
|
|
4859
|
-
/**
|
|
4860
|
-
* Show help.
|
|
4861
|
-
*/
|
|
4862
|
-
help() {
|
|
4863
|
-
logger.info(`
|
|
4864
|
-
\u{1F3AF} Session Debug API
|
|
4865
|
-
|
|
4866
|
-
Commands:
|
|
4867
|
-
.showQueue() Show current queue state (active session only)
|
|
4868
|
-
.showHistory(index?) Show presentation history (0=current/last, 1=previous, etc)
|
|
4869
|
-
.showInterleaving(index?) Analyze course interleaving pattern
|
|
4870
|
-
.listSessions() List all tracked sessions
|
|
4871
|
-
.export() Export session data as JSON for bug reports
|
|
4872
|
-
.clear() Clear session history
|
|
4873
|
-
.sessions Access raw session history array
|
|
4874
|
-
.active Access active session (if any)
|
|
4875
|
-
.help() Show this help message
|
|
4876
|
-
|
|
4877
|
-
Example:
|
|
4878
|
-
window.skuilder.session.showHistory()
|
|
4879
|
-
window.skuilder.session.showInterleaving()
|
|
4880
|
-
window.skuilder.session.showQueue()
|
|
4881
|
-
`);
|
|
4882
|
-
}
|
|
4883
|
-
};
|
|
4884
|
-
mountSessionDebugger();
|
|
4885
3807
|
}
|
|
4886
3808
|
});
|
|
4887
3809
|
|
|
4888
|
-
// src/
|
|
4889
|
-
|
|
4890
|
-
|
|
3810
|
+
// src/core/orchestration/index.ts
|
|
3811
|
+
function fnv1a(str) {
|
|
3812
|
+
let hash = 2166136261;
|
|
3813
|
+
for (let i = 0; i < str.length; i++) {
|
|
3814
|
+
hash ^= str.charCodeAt(i);
|
|
3815
|
+
hash = Math.imul(hash, 16777619);
|
|
3816
|
+
}
|
|
3817
|
+
return hash >>> 0;
|
|
3818
|
+
}
|
|
3819
|
+
function computeDeviation(userId, strategyId, salt) {
|
|
3820
|
+
const input = `${userId}:${strategyId}:${salt}`;
|
|
3821
|
+
const hash = fnv1a(input);
|
|
3822
|
+
const normalized = hash / 4294967296;
|
|
3823
|
+
return normalized * 2 - 1;
|
|
3824
|
+
}
|
|
3825
|
+
function computeSpread(confidence) {
|
|
3826
|
+
const clampedConfidence = Math.max(0, Math.min(1, confidence));
|
|
3827
|
+
return MAX_SPREAD - clampedConfidence * (MAX_SPREAD - MIN_SPREAD);
|
|
3828
|
+
}
|
|
3829
|
+
function computeEffectiveWeight(learnable, userId, strategyId, salt) {
|
|
3830
|
+
const deviation = computeDeviation(userId, strategyId, salt);
|
|
3831
|
+
const spread = computeSpread(learnable.confidence);
|
|
3832
|
+
const adjustment = deviation * spread * learnable.weight;
|
|
3833
|
+
const effective = learnable.weight + adjustment;
|
|
3834
|
+
return Math.max(MIN_WEIGHT, Math.min(MAX_WEIGHT, effective));
|
|
3835
|
+
}
|
|
3836
|
+
async function createOrchestrationContext(user, course) {
|
|
3837
|
+
let courseConfig;
|
|
3838
|
+
try {
|
|
3839
|
+
courseConfig = await course.getCourseConfig();
|
|
3840
|
+
} catch (e) {
|
|
3841
|
+
logger.error(`[Orchestration] Failed to load course config: ${e}`);
|
|
3842
|
+
courseConfig = {
|
|
3843
|
+
name: "Unknown",
|
|
3844
|
+
description: "",
|
|
3845
|
+
public: false,
|
|
3846
|
+
deleted: false,
|
|
3847
|
+
creator: "",
|
|
3848
|
+
admins: [],
|
|
3849
|
+
moderators: [],
|
|
3850
|
+
dataShapes: [],
|
|
3851
|
+
questionTypes: [],
|
|
3852
|
+
orchestration: { salt: "default" }
|
|
3853
|
+
};
|
|
3854
|
+
}
|
|
3855
|
+
const userId = user.getUsername();
|
|
3856
|
+
const salt = courseConfig.orchestration?.salt || "default_salt";
|
|
3857
|
+
return {
|
|
3858
|
+
user,
|
|
3859
|
+
course,
|
|
3860
|
+
userId,
|
|
3861
|
+
courseConfig,
|
|
3862
|
+
getEffectiveWeight(strategyId, learnable) {
|
|
3863
|
+
return computeEffectiveWeight(learnable, userId, strategyId, salt);
|
|
3864
|
+
},
|
|
3865
|
+
getDeviation(strategyId) {
|
|
3866
|
+
return computeDeviation(userId, strategyId, salt);
|
|
3867
|
+
}
|
|
3868
|
+
};
|
|
3869
|
+
}
|
|
3870
|
+
var MIN_SPREAD, MAX_SPREAD, MIN_WEIGHT, MAX_WEIGHT;
|
|
3871
|
+
var init_orchestration = __esm({
|
|
3872
|
+
"src/core/orchestration/index.ts"() {
|
|
4891
3873
|
"use strict";
|
|
4892
|
-
init_SrsService();
|
|
4893
|
-
init_EloService();
|
|
4894
|
-
init_ResponseProcessor();
|
|
4895
|
-
init_CardHydrationService();
|
|
4896
|
-
init_ItemQueue();
|
|
4897
|
-
init_couch();
|
|
4898
|
-
init_recording();
|
|
4899
|
-
init_util2();
|
|
4900
|
-
init_navigators();
|
|
4901
|
-
init_SourceMixer();
|
|
4902
|
-
init_MixerDebugger();
|
|
4903
|
-
init_SessionDebugger();
|
|
4904
3874
|
init_logger();
|
|
3875
|
+
init_gradient();
|
|
3876
|
+
init_learning();
|
|
3877
|
+
init_signal();
|
|
3878
|
+
init_recording();
|
|
3879
|
+
MIN_SPREAD = 0.1;
|
|
3880
|
+
MAX_SPREAD = 0.5;
|
|
3881
|
+
MIN_WEIGHT = 0.1;
|
|
3882
|
+
MAX_WEIGHT = 3;
|
|
4905
3883
|
}
|
|
4906
3884
|
});
|
|
4907
3885
|
|
|
@@ -4922,6 +3900,44 @@ function globMatch(value, pattern) {
|
|
|
4922
3900
|
function cardMatchesTagPattern(card, pattern) {
|
|
4923
3901
|
return (card.tags ?? []).some((tag) => globMatch(tag, pattern));
|
|
4924
3902
|
}
|
|
3903
|
+
function mergeHints2(allHints) {
|
|
3904
|
+
const defined = allHints.filter((h) => h !== null && h !== void 0);
|
|
3905
|
+
if (defined.length === 0) return void 0;
|
|
3906
|
+
const merged = {};
|
|
3907
|
+
const boostTags = {};
|
|
3908
|
+
for (const hints of defined) {
|
|
3909
|
+
for (const [pattern, factor] of Object.entries(hints.boostTags ?? {})) {
|
|
3910
|
+
boostTags[pattern] = (boostTags[pattern] ?? 1) * factor;
|
|
3911
|
+
}
|
|
3912
|
+
}
|
|
3913
|
+
if (Object.keys(boostTags).length > 0) {
|
|
3914
|
+
merged.boostTags = boostTags;
|
|
3915
|
+
}
|
|
3916
|
+
const boostCards = {};
|
|
3917
|
+
for (const hints of defined) {
|
|
3918
|
+
for (const [pattern, factor] of Object.entries(hints.boostCards ?? {})) {
|
|
3919
|
+
boostCards[pattern] = (boostCards[pattern] ?? 1) * factor;
|
|
3920
|
+
}
|
|
3921
|
+
}
|
|
3922
|
+
if (Object.keys(boostCards).length > 0) {
|
|
3923
|
+
merged.boostCards = boostCards;
|
|
3924
|
+
}
|
|
3925
|
+
const concatUnique = (field) => {
|
|
3926
|
+
const values = defined.flatMap((h) => h[field] ?? []);
|
|
3927
|
+
if (values.length > 0) {
|
|
3928
|
+
merged[field] = [...new Set(values)];
|
|
3929
|
+
}
|
|
3930
|
+
};
|
|
3931
|
+
concatUnique("requireTags");
|
|
3932
|
+
concatUnique("requireCards");
|
|
3933
|
+
concatUnique("excludeTags");
|
|
3934
|
+
concatUnique("excludeCards");
|
|
3935
|
+
const labels = defined.map((h) => h._label).filter(Boolean);
|
|
3936
|
+
if (labels.length > 0) {
|
|
3937
|
+
merged._label = labels.join("; ");
|
|
3938
|
+
}
|
|
3939
|
+
return Object.keys(merged).length > 0 ? merged : void 0;
|
|
3940
|
+
}
|
|
4925
3941
|
function logPipelineConfig(generator, filters) {
|
|
4926
3942
|
const filterList = filters.length > 0 ? "\n - " + filters.map((f) => f.name).join("\n - ") : " none";
|
|
4927
3943
|
logger.info(
|
|
@@ -4985,16 +4001,15 @@ function logCardProvenance(cards, maxCards = 3) {
|
|
|
4985
4001
|
}
|
|
4986
4002
|
}
|
|
4987
4003
|
}
|
|
4988
|
-
var
|
|
4004
|
+
var import_common8, VERBOSE_RESULTS, Pipeline;
|
|
4989
4005
|
var init_Pipeline = __esm({
|
|
4990
4006
|
"src/core/navigators/Pipeline.ts"() {
|
|
4991
4007
|
"use strict";
|
|
4992
|
-
|
|
4008
|
+
import_common8 = require("@vue-skuilder/common");
|
|
4993
4009
|
init_navigators();
|
|
4994
4010
|
init_logger();
|
|
4995
4011
|
init_orchestration();
|
|
4996
4012
|
init_PipelineDebugger();
|
|
4997
|
-
init_SessionController();
|
|
4998
4013
|
VERBOSE_RESULTS = true;
|
|
4999
4014
|
Pipeline = class extends ContentNavigator {
|
|
5000
4015
|
generator;
|
|
@@ -5074,9 +4089,12 @@ var init_Pipeline = __esm({
|
|
|
5074
4089
|
logger.debug(
|
|
5075
4090
|
`[Pipeline] Fetching ${fetchLimit} candidates from generator '${this.generator.name}'`
|
|
5076
4091
|
);
|
|
5077
|
-
|
|
4092
|
+
const generatorResult = await this.generator.getWeightedCards(fetchLimit, context);
|
|
4093
|
+
let cards = generatorResult.cards;
|
|
5078
4094
|
const tGenerate = performance.now();
|
|
5079
4095
|
const generatedCount = cards.length;
|
|
4096
|
+
const mergedHints = mergeHints2([this._ephemeralHints, generatorResult.hints]);
|
|
4097
|
+
this._ephemeralHints = mergedHints ?? null;
|
|
5080
4098
|
let generatorSummaries;
|
|
5081
4099
|
if (this.generator.generators) {
|
|
5082
4100
|
const genMap = /* @__PURE__ */ new Map();
|
|
@@ -5106,6 +4124,32 @@ var init_Pipeline = __esm({
|
|
|
5106
4124
|
cards = await this.hydrateTags(cards);
|
|
5107
4125
|
const tHydrate = performance.now();
|
|
5108
4126
|
const allCardsBeforeFiltering = [...cards];
|
|
4127
|
+
const pendingHints = this._ephemeralHints;
|
|
4128
|
+
if (pendingHints?.requireCards?.length) {
|
|
4129
|
+
const poolIds = new Set(allCardsBeforeFiltering.map((c) => c.cardId));
|
|
4130
|
+
const missingIds = pendingHints.requireCards.filter(
|
|
4131
|
+
(p) => !p.includes("*") && !poolIds.has(p)
|
|
4132
|
+
);
|
|
4133
|
+
if (missingIds.length > 0) {
|
|
4134
|
+
const fetchedTags = await this.course.getAppliedTagsBatch(missingIds);
|
|
4135
|
+
const courseId = this.course.getCourseID();
|
|
4136
|
+
for (const cardId of missingIds) {
|
|
4137
|
+
allCardsBeforeFiltering.push({
|
|
4138
|
+
cardId,
|
|
4139
|
+
courseId,
|
|
4140
|
+
score: 1,
|
|
4141
|
+
tags: fetchedTags.get(cardId) ?? [],
|
|
4142
|
+
provenance: []
|
|
4143
|
+
});
|
|
4144
|
+
}
|
|
4145
|
+
logger.info(
|
|
4146
|
+
`[Pipeline] Pre-fetched ${missingIds.length} required card(s) into pool: ${missingIds.join(", ")}`
|
|
4147
|
+
);
|
|
4148
|
+
}
|
|
4149
|
+
}
|
|
4150
|
+
const prescribedIds = new Set(
|
|
4151
|
+
cards.filter((c) => c.provenance.some((p) => p.strategy === "prescribed")).map((c) => c.cardId)
|
|
4152
|
+
);
|
|
5109
4153
|
const filterImpacts = [];
|
|
5110
4154
|
for (const filter of this.filters) {
|
|
5111
4155
|
const beforeCount = cards.length;
|
|
@@ -5120,6 +4164,17 @@ var init_Pipeline = __esm({
|
|
|
5120
4164
|
else passed++;
|
|
5121
4165
|
}
|
|
5122
4166
|
filterImpacts.push({ name: filter.name, boosted, penalized, passed, removed });
|
|
4167
|
+
if (prescribedIds.size > 0) {
|
|
4168
|
+
const survivingIds = new Set(cards.map((c) => c.cardId));
|
|
4169
|
+
const killedPrescribed = [...prescribedIds].filter((id) => !survivingIds.has(id));
|
|
4170
|
+
const zeroedPrescribed = cards.filter((c) => prescribedIds.has(c.cardId) && c.score === 0).map((c) => c.cardId);
|
|
4171
|
+
if (killedPrescribed.length > 0 || zeroedPrescribed.length > 0) {
|
|
4172
|
+
logger.info(
|
|
4173
|
+
`[Pipeline] Filter '${filter.name}' impact on prescribed cards: ` + (killedPrescribed.length > 0 ? `removed=[${killedPrescribed.join(", ")}] ` : "") + (zeroedPrescribed.length > 0 ? `zeroed=[${zeroedPrescribed.join(", ")}]` : "")
|
|
4174
|
+
);
|
|
4175
|
+
killedPrescribed.forEach((id) => prescribedIds.delete(id));
|
|
4176
|
+
}
|
|
4177
|
+
}
|
|
5123
4178
|
logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeScores.size} \u2192 ${cards.length} cards (\u2191${boosted} \u2193${penalized} =${passed})`);
|
|
5124
4179
|
}
|
|
5125
4180
|
cards = cards.filter((c) => c.score > 0);
|
|
@@ -5156,13 +4211,14 @@ var init_Pipeline = __esm({
|
|
|
5156
4211
|
filterImpacts,
|
|
5157
4212
|
cards,
|
|
5158
4213
|
result,
|
|
5159
|
-
context.userElo
|
|
4214
|
+
context.userElo,
|
|
4215
|
+
hints ?? void 0
|
|
5160
4216
|
);
|
|
5161
4217
|
captureRun(report);
|
|
5162
4218
|
} catch (e) {
|
|
5163
4219
|
logger.debug(`[Pipeline] Failed to capture debug run: ${e}`);
|
|
5164
4220
|
}
|
|
5165
|
-
return result;
|
|
4221
|
+
return { cards: result };
|
|
5166
4222
|
}
|
|
5167
4223
|
/**
|
|
5168
4224
|
* Batch hydrate tags for all cards.
|
|
@@ -5266,13 +4322,27 @@ var init_Pipeline = __esm({
|
|
|
5266
4322
|
}
|
|
5267
4323
|
}
|
|
5268
4324
|
const cardIds = new Set(cards.map((c) => c.cardId));
|
|
4325
|
+
const cardMap = new Map(cards.map((c) => [c.cardId, c]));
|
|
5269
4326
|
const hintLabel = hints._label ? `Replan Hint (${hints._label})` : "Replan Hint";
|
|
5270
|
-
const
|
|
5271
|
-
|
|
5272
|
-
|
|
4327
|
+
const applyRequirement = (card, reason) => {
|
|
4328
|
+
const mandatoryScore = Number.POSITIVE_INFINITY;
|
|
4329
|
+
const existing = cardMap.get(card.cardId);
|
|
4330
|
+
if (existing) {
|
|
4331
|
+
if (existing.score < mandatoryScore) {
|
|
4332
|
+
existing.score = mandatoryScore;
|
|
4333
|
+
existing.provenance.push({
|
|
4334
|
+
strategy: "ephemeralHint",
|
|
4335
|
+
strategyId: "ephemeral-hint",
|
|
4336
|
+
strategyName: hintLabel,
|
|
4337
|
+
action: "boosted",
|
|
4338
|
+
score: mandatoryScore,
|
|
4339
|
+
reason: `${reason} (upgrade to mandatory score)`
|
|
4340
|
+
});
|
|
4341
|
+
}
|
|
4342
|
+
} else {
|
|
5273
4343
|
cards.push({
|
|
5274
4344
|
...card,
|
|
5275
|
-
score:
|
|
4345
|
+
score: mandatoryScore,
|
|
5276
4346
|
provenance: [
|
|
5277
4347
|
...card.provenance,
|
|
5278
4348
|
{
|
|
@@ -5280,25 +4350,41 @@ var init_Pipeline = __esm({
|
|
|
5280
4350
|
strategyId: "ephemeral-hint",
|
|
5281
4351
|
strategyName: hintLabel,
|
|
5282
4352
|
action: "boosted",
|
|
5283
|
-
score:
|
|
4353
|
+
score: mandatoryScore,
|
|
5284
4354
|
reason
|
|
5285
4355
|
}
|
|
5286
4356
|
]
|
|
5287
4357
|
});
|
|
5288
4358
|
cardIds.add(card.cardId);
|
|
4359
|
+
cardMap.set(card.cardId, cards[cards.length - 1]);
|
|
5289
4360
|
}
|
|
5290
4361
|
};
|
|
5291
4362
|
if (hints.requireCards?.length) {
|
|
5292
4363
|
for (const pattern of hints.requireCards) {
|
|
4364
|
+
for (const cardId of cardIds) {
|
|
4365
|
+
if (globMatch(cardId, pattern)) {
|
|
4366
|
+
applyRequirement(cardMap.get(cardId), `requireCard ${pattern}`);
|
|
4367
|
+
}
|
|
4368
|
+
}
|
|
5293
4369
|
for (const card of allCards) {
|
|
5294
|
-
if (globMatch(card.cardId, pattern))
|
|
4370
|
+
if (globMatch(card.cardId, pattern)) {
|
|
4371
|
+
applyRequirement(card, `requireCard ${pattern}`);
|
|
4372
|
+
}
|
|
5295
4373
|
}
|
|
5296
4374
|
}
|
|
5297
4375
|
}
|
|
5298
4376
|
if (hints.requireTags?.length) {
|
|
5299
4377
|
for (const pattern of hints.requireTags) {
|
|
4378
|
+
for (const cardId of cardIds) {
|
|
4379
|
+
const card = cardMap.get(cardId);
|
|
4380
|
+
if (cardMatchesTagPattern(card, pattern)) {
|
|
4381
|
+
applyRequirement(card, `requireTag ${pattern}`);
|
|
4382
|
+
}
|
|
4383
|
+
}
|
|
5300
4384
|
for (const card of allCards) {
|
|
5301
|
-
if (cardMatchesTagPattern(card, pattern))
|
|
4385
|
+
if (cardMatchesTagPattern(card, pattern)) {
|
|
4386
|
+
applyRequirement(card, `requireTag ${pattern}`);
|
|
4387
|
+
}
|
|
5302
4388
|
}
|
|
5303
4389
|
}
|
|
5304
4390
|
}
|
|
@@ -5317,7 +4403,7 @@ var init_Pipeline = __esm({
|
|
|
5317
4403
|
let userElo = 1e3;
|
|
5318
4404
|
try {
|
|
5319
4405
|
const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
|
|
5320
|
-
const courseElo = (0,
|
|
4406
|
+
const courseElo = (0, import_common8.toCourseElo)(courseReg.elo);
|
|
5321
4407
|
userElo = courseElo.global.score;
|
|
5322
4408
|
} catch (e) {
|
|
5323
4409
|
logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
|
|
@@ -5378,7 +4464,7 @@ var init_Pipeline = __esm({
|
|
|
5378
4464
|
*/
|
|
5379
4465
|
async getTagEloStatus(tagFilter) {
|
|
5380
4466
|
const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
|
|
5381
|
-
const courseElo = (0,
|
|
4467
|
+
const courseElo = (0, import_common8.toCourseElo)(courseReg.elo);
|
|
5382
4468
|
const result = {};
|
|
5383
4469
|
if (!tagFilter) {
|
|
5384
4470
|
for (const [tag, data] of Object.entries(courseElo.tags)) {
|
|
@@ -6051,11 +5137,11 @@ ${JSON.stringify(config)}
|
|
|
6051
5137
|
function isSuccessRow(row) {
|
|
6052
5138
|
return "doc" in row && row.doc !== null && row.doc !== void 0;
|
|
6053
5139
|
}
|
|
6054
|
-
var
|
|
5140
|
+
var import_common9, CourseDB;
|
|
6055
5141
|
var init_courseDB = __esm({
|
|
6056
5142
|
"src/impl/couch/courseDB.ts"() {
|
|
6057
5143
|
"use strict";
|
|
6058
|
-
|
|
5144
|
+
import_common9 = require("@vue-skuilder/common");
|
|
6059
5145
|
init_couch();
|
|
6060
5146
|
init_updateQueue();
|
|
6061
5147
|
init_types_legacy();
|
|
@@ -6159,14 +5245,14 @@ var init_courseDB = __esm({
|
|
|
6159
5245
|
docs.rows.forEach((r) => {
|
|
6160
5246
|
if (isSuccessRow(r)) {
|
|
6161
5247
|
if (r.doc && r.doc.elo) {
|
|
6162
|
-
ret.push((0,
|
|
5248
|
+
ret.push((0, import_common9.toCourseElo)(r.doc.elo));
|
|
6163
5249
|
} else {
|
|
6164
5250
|
logger.warn("no elo data for card: " + r.id);
|
|
6165
|
-
ret.push((0,
|
|
5251
|
+
ret.push((0, import_common9.blankCourseElo)());
|
|
6166
5252
|
}
|
|
6167
5253
|
} else {
|
|
6168
5254
|
logger.warn("no elo data for card: " + JSON.stringify(r));
|
|
6169
|
-
ret.push((0,
|
|
5255
|
+
ret.push((0, import_common9.blankCourseElo)());
|
|
6170
5256
|
}
|
|
6171
5257
|
});
|
|
6172
5258
|
return ret;
|
|
@@ -6368,7 +5454,7 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
|
|
|
6368
5454
|
async getCourseTagStubs() {
|
|
6369
5455
|
return getCourseTagStubs(this.id);
|
|
6370
5456
|
}
|
|
6371
|
-
async addNote(codeCourse, shape, data, author, tags, uploads, elo = (0,
|
|
5457
|
+
async addNote(codeCourse, shape, data, author, tags, uploads, elo = (0, import_common9.blankCourseElo)()) {
|
|
6372
5458
|
try {
|
|
6373
5459
|
const resp = await addNote55(this.id, codeCourse, shape, data, author, tags, uploads, elo);
|
|
6374
5460
|
if (resp.ok) {
|
|
@@ -6377,19 +5463,19 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
|
|
|
6377
5463
|
`[courseDB.addNote] Note added but card creation failed: ${resp.cardCreationError}`
|
|
6378
5464
|
);
|
|
6379
5465
|
return {
|
|
6380
|
-
status:
|
|
5466
|
+
status: import_common9.Status.error,
|
|
6381
5467
|
message: `Note was added but no cards were created: ${resp.cardCreationError}`,
|
|
6382
5468
|
id: resp.id
|
|
6383
5469
|
};
|
|
6384
5470
|
}
|
|
6385
5471
|
return {
|
|
6386
|
-
status:
|
|
5472
|
+
status: import_common9.Status.ok,
|
|
6387
5473
|
message: "",
|
|
6388
5474
|
id: resp.id
|
|
6389
5475
|
};
|
|
6390
5476
|
} else {
|
|
6391
5477
|
return {
|
|
6392
|
-
status:
|
|
5478
|
+
status: import_common9.Status.error,
|
|
6393
5479
|
message: "Unexpected error adding note"
|
|
6394
5480
|
};
|
|
6395
5481
|
}
|
|
@@ -6401,7 +5487,7 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
|
|
|
6401
5487
|
message: ${err.message}`
|
|
6402
5488
|
);
|
|
6403
5489
|
return {
|
|
6404
|
-
status:
|
|
5490
|
+
status: import_common9.Status.error,
|
|
6405
5491
|
message: `Error adding note to course. ${e.reason || err.message}`
|
|
6406
5492
|
};
|
|
6407
5493
|
}
|
|
@@ -6540,7 +5626,7 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
|
|
|
6540
5626
|
const courseDoc = (await u.getCourseRegistrationsDoc()).courses.find((c) => {
|
|
6541
5627
|
return c.courseID === this.id;
|
|
6542
5628
|
});
|
|
6543
|
-
targetElo = (0,
|
|
5629
|
+
targetElo = (0, import_common9.EloToNumber)(courseDoc.elo);
|
|
6544
5630
|
} catch {
|
|
6545
5631
|
targetElo = 1e3;
|
|
6546
5632
|
}
|
|
@@ -6664,13 +5750,13 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
|
|
|
6664
5750
|
});
|
|
6665
5751
|
|
|
6666
5752
|
// src/impl/couch/classroomDB.ts
|
|
6667
|
-
var
|
|
5753
|
+
var import_moment4, CLASSROOM_CONFIG, ClassroomDBBase, StudentClassroomDB;
|
|
6668
5754
|
var init_classroomDB2 = __esm({
|
|
6669
5755
|
"src/impl/couch/classroomDB.ts"() {
|
|
6670
5756
|
"use strict";
|
|
6671
5757
|
init_factory();
|
|
6672
5758
|
init_logger();
|
|
6673
|
-
|
|
5759
|
+
import_moment4 = __toESM(require("moment"), 1);
|
|
6674
5760
|
init_pouchdb_setup();
|
|
6675
5761
|
init_couch();
|
|
6676
5762
|
init_courseDB();
|
|
@@ -6782,14 +5868,14 @@ var init_classroomDB2 = __esm({
|
|
|
6782
5868
|
}
|
|
6783
5869
|
const activeCards = await this._user.getActiveCards();
|
|
6784
5870
|
const activeCardIds = new Set(activeCards.map((ac) => ac.cardID));
|
|
6785
|
-
const now =
|
|
5871
|
+
const now = import_moment4.default.utc();
|
|
6786
5872
|
const assigned = await this.getAssignedContent();
|
|
6787
|
-
const due = assigned.filter((c) => now.isAfter(
|
|
5873
|
+
const due = assigned.filter((c) => now.isAfter(import_moment4.default.utc(c.activeOn, REVIEW_TIME_FORMAT2)));
|
|
6788
5874
|
logger.info(`[StudentClassroomDB] Due content: ${JSON.stringify(due)}`);
|
|
6789
5875
|
for (const content of due) {
|
|
6790
5876
|
if (content.type === "course") {
|
|
6791
5877
|
const db = new CourseDB(content.courseID, async () => this._user);
|
|
6792
|
-
const courseCards = await db.getWeightedCards(limit);
|
|
5878
|
+
const { cards: courseCards } = await db.getWeightedCards(limit);
|
|
6793
5879
|
for (const card of courseCards) {
|
|
6794
5880
|
if (!activeCardIds.has(card.cardId)) {
|
|
6795
5881
|
weighted.push({
|
|
@@ -6852,7 +5938,7 @@ var init_classroomDB2 = __esm({
|
|
|
6852
5938
|
logger.info(
|
|
6853
5939
|
`[StudentClassroomDB] New cards from classroom ${this._cfg.name}: ${weighted.length} total (reviews + new)`
|
|
6854
5940
|
);
|
|
6855
|
-
return weighted.sort((a, b) => b.score - a.score).slice(0, limit);
|
|
5941
|
+
return { cards: weighted.sort((a, b) => b.score - a.score).slice(0, limit) };
|
|
6856
5942
|
}
|
|
6857
5943
|
};
|
|
6858
5944
|
}
|
|
@@ -6893,14 +5979,14 @@ var init_auth = __esm({
|
|
|
6893
5979
|
});
|
|
6894
5980
|
|
|
6895
5981
|
// src/impl/couch/CouchDBSyncStrategy.ts
|
|
6896
|
-
var
|
|
5982
|
+
var import_common10;
|
|
6897
5983
|
var init_CouchDBSyncStrategy = __esm({
|
|
6898
5984
|
"src/impl/couch/CouchDBSyncStrategy.ts"() {
|
|
6899
5985
|
"use strict";
|
|
6900
5986
|
init_factory();
|
|
6901
5987
|
init_types_legacy();
|
|
6902
5988
|
init_logger();
|
|
6903
|
-
|
|
5989
|
+
import_common10 = require("@vue-skuilder/common");
|
|
6904
5990
|
init_common();
|
|
6905
5991
|
init_pouchdb_setup();
|
|
6906
5992
|
init_couch();
|
|
@@ -6951,14 +6037,14 @@ function getStartAndEndKeys2(key) {
|
|
|
6951
6037
|
endkey: key + "\uFFF0"
|
|
6952
6038
|
};
|
|
6953
6039
|
}
|
|
6954
|
-
var import_cross_fetch2,
|
|
6040
|
+
var import_cross_fetch2, import_moment5, import_process, isBrowser, GUEST_LOCAL_DB, localUserDB, pouchDBincludeCredentialsConfig, REVIEW_TIME_FORMAT2;
|
|
6955
6041
|
var init_couch = __esm({
|
|
6956
6042
|
"src/impl/couch/index.ts"() {
|
|
6957
6043
|
"use strict";
|
|
6958
6044
|
init_factory();
|
|
6959
6045
|
init_types_legacy();
|
|
6960
6046
|
import_cross_fetch2 = __toESM(require("cross-fetch"), 1);
|
|
6961
|
-
|
|
6047
|
+
import_moment5 = __toESM(require("moment"), 1);
|
|
6962
6048
|
init_logger();
|
|
6963
6049
|
init_pouchdb_setup();
|
|
6964
6050
|
import_process = __toESM(require("process"), 1);
|
|
@@ -7078,14 +6164,14 @@ async function dropUserFromClassroom(user, classID) {
|
|
|
7078
6164
|
async function getUserClassrooms(user) {
|
|
7079
6165
|
return getOrCreateClassroomRegistrationsDoc(user);
|
|
7080
6166
|
}
|
|
7081
|
-
var
|
|
6167
|
+
var import_common12, import_moment6, log3, BaseUser, userCoursesDoc, userClassroomsDoc;
|
|
7082
6168
|
var init_BaseUserDB = __esm({
|
|
7083
6169
|
"src/impl/common/BaseUserDB.ts"() {
|
|
7084
6170
|
"use strict";
|
|
7085
6171
|
init_core();
|
|
7086
6172
|
init_util();
|
|
7087
|
-
|
|
7088
|
-
|
|
6173
|
+
import_common12 = require("@vue-skuilder/common");
|
|
6174
|
+
import_moment6 = __toESM(require("moment"), 1);
|
|
7089
6175
|
init_types_legacy();
|
|
7090
6176
|
init_logger();
|
|
7091
6177
|
init_userDBHelpers();
|
|
@@ -7134,7 +6220,7 @@ Currently logged-in as ${this._username}.`
|
|
|
7134
6220
|
);
|
|
7135
6221
|
}
|
|
7136
6222
|
const result = await this.syncStrategy.createAccount(username, password);
|
|
7137
|
-
if (result.status ===
|
|
6223
|
+
if (result.status === import_common12.Status.ok) {
|
|
7138
6224
|
log3(`Account created successfully, updating username to ${username}`);
|
|
7139
6225
|
this._username = username;
|
|
7140
6226
|
try {
|
|
@@ -7176,7 +6262,7 @@ Currently logged-in as ${this._username}.`
|
|
|
7176
6262
|
async resetUserData() {
|
|
7177
6263
|
if (this.syncStrategy.canAuthenticate()) {
|
|
7178
6264
|
return {
|
|
7179
|
-
status:
|
|
6265
|
+
status: import_common12.Status.error,
|
|
7180
6266
|
error: "Reset user data is only available for local-only mode. Use logout instead for remote sync."
|
|
7181
6267
|
};
|
|
7182
6268
|
}
|
|
@@ -7198,11 +6284,11 @@ Currently logged-in as ${this._username}.`
|
|
|
7198
6284
|
await localDB.bulkDocs(docsToDelete);
|
|
7199
6285
|
}
|
|
7200
6286
|
await this.init();
|
|
7201
|
-
return { status:
|
|
6287
|
+
return { status: import_common12.Status.ok };
|
|
7202
6288
|
} catch (error) {
|
|
7203
6289
|
logger.error("Failed to reset user data:", error);
|
|
7204
6290
|
return {
|
|
7205
|
-
status:
|
|
6291
|
+
status: import_common12.Status.error,
|
|
7206
6292
|
error: error instanceof Error ? error.message : "Unknown error during reset"
|
|
7207
6293
|
};
|
|
7208
6294
|
}
|
|
@@ -7349,7 +6435,7 @@ Currently logged-in as ${this._username}.`
|
|
|
7349
6435
|
);
|
|
7350
6436
|
return reviews.rows.filter((r) => {
|
|
7351
6437
|
if (r.id.startsWith(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */])) {
|
|
7352
|
-
const date =
|
|
6438
|
+
const date = import_moment6.default.utc(
|
|
7353
6439
|
r.id.substr(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */].length),
|
|
7354
6440
|
REVIEW_TIME_FORMAT
|
|
7355
6441
|
);
|
|
@@ -7362,11 +6448,11 @@ Currently logged-in as ${this._username}.`
|
|
|
7362
6448
|
}).map((r) => r.doc);
|
|
7363
6449
|
}
|
|
7364
6450
|
async getReviewsForcast(daysCount) {
|
|
7365
|
-
const time =
|
|
6451
|
+
const time = import_moment6.default.utc().add(daysCount, "days");
|
|
7366
6452
|
return this.getReviewstoDate(time);
|
|
7367
6453
|
}
|
|
7368
6454
|
async getPendingReviews(course_id) {
|
|
7369
|
-
const now =
|
|
6455
|
+
const now = import_moment6.default.utc();
|
|
7370
6456
|
return this.getReviewstoDate(now, course_id);
|
|
7371
6457
|
}
|
|
7372
6458
|
async getScheduledReviewCount(course_id) {
|
|
@@ -7653,7 +6739,7 @@ Currently logged-in as ${this._username}.`
|
|
|
7653
6739
|
*/
|
|
7654
6740
|
async putCardRecord(record) {
|
|
7655
6741
|
const cardHistoryID = getCardHistoryID(record.courseID, record.cardID);
|
|
7656
|
-
record.timeStamp =
|
|
6742
|
+
record.timeStamp = import_moment6.default.utc(record.timeStamp).toString();
|
|
7657
6743
|
try {
|
|
7658
6744
|
const cardHistory = await this.update(
|
|
7659
6745
|
cardHistoryID,
|
|
@@ -7669,7 +6755,7 @@ Currently logged-in as ${this._username}.`
|
|
|
7669
6755
|
const ret = {
|
|
7670
6756
|
...record2
|
|
7671
6757
|
};
|
|
7672
|
-
ret.timeStamp =
|
|
6758
|
+
ret.timeStamp = import_moment6.default.utc(record2.timeStamp);
|
|
7673
6759
|
return ret;
|
|
7674
6760
|
});
|
|
7675
6761
|
return cardHistory;
|
|
@@ -7996,11 +7082,11 @@ var init_factory = __esm({
|
|
|
7996
7082
|
});
|
|
7997
7083
|
|
|
7998
7084
|
// src/study/TagFilteredContentSource.ts
|
|
7999
|
-
var
|
|
7085
|
+
var import_common14, TagFilteredContentSource;
|
|
8000
7086
|
var init_TagFilteredContentSource = __esm({
|
|
8001
7087
|
"src/study/TagFilteredContentSource.ts"() {
|
|
8002
7088
|
"use strict";
|
|
8003
|
-
|
|
7089
|
+
import_common14 = require("@vue-skuilder/common");
|
|
8004
7090
|
init_courseDB();
|
|
8005
7091
|
init_logger();
|
|
8006
7092
|
TagFilteredContentSource = class {
|
|
@@ -8086,9 +7172,9 @@ var init_TagFilteredContentSource = __esm({
|
|
|
8086
7172
|
* @returns Cards sorted by score descending (all scores = 1.0)
|
|
8087
7173
|
*/
|
|
8088
7174
|
async getWeightedCards(limit) {
|
|
8089
|
-
if (!(0,
|
|
7175
|
+
if (!(0, import_common14.hasActiveFilter)(this.filter)) {
|
|
8090
7176
|
logger.warn("[TagFilteredContentSource] getWeightedCards called with no active filter");
|
|
8091
|
-
return [];
|
|
7177
|
+
return { cards: [] };
|
|
8092
7178
|
}
|
|
8093
7179
|
const eligibleCardIds = await this.resolveFilteredCardIds();
|
|
8094
7180
|
const activeCards = await this.user.getActiveCards();
|
|
@@ -8140,7 +7226,7 @@ var init_TagFilteredContentSource = __esm({
|
|
|
8140
7226
|
}
|
|
8141
7227
|
]
|
|
8142
7228
|
}));
|
|
8143
|
-
return [...reviewWeighted, ...newCardWeighted].slice(0, limit);
|
|
7229
|
+
return { cards: [...reviewWeighted, ...newCardWeighted].slice(0, limit) };
|
|
8144
7230
|
}
|
|
8145
7231
|
/**
|
|
8146
7232
|
* Clears the cached resolved card IDs.
|
|
@@ -8174,19 +7260,19 @@ async function getStudySource(source, user) {
|
|
|
8174
7260
|
if (source.type === "classroom") {
|
|
8175
7261
|
return await StudentClassroomDB.factory(source.id, user);
|
|
8176
7262
|
} else {
|
|
8177
|
-
if ((0,
|
|
7263
|
+
if ((0, import_common15.hasActiveFilter)(source.tagFilter)) {
|
|
8178
7264
|
return new TagFilteredContentSource(source.id, source.tagFilter, user);
|
|
8179
7265
|
}
|
|
8180
7266
|
return getDataLayer().getCourseDB(source.id);
|
|
8181
7267
|
}
|
|
8182
7268
|
}
|
|
8183
|
-
var
|
|
7269
|
+
var import_common15;
|
|
8184
7270
|
var init_contentSource = __esm({
|
|
8185
7271
|
"src/core/interfaces/contentSource.ts"() {
|
|
8186
7272
|
"use strict";
|
|
8187
7273
|
init_factory();
|
|
8188
7274
|
init_classroomDB2();
|
|
8189
|
-
|
|
7275
|
+
import_common15 = require("@vue-skuilder/common");
|
|
8190
7276
|
init_TagFilteredContentSource();
|
|
8191
7277
|
}
|
|
8192
7278
|
});
|
|
@@ -8317,7 +7403,7 @@ elo: ${elo}`;
|
|
|
8317
7403
|
misc: {}
|
|
8318
7404
|
} : void 0
|
|
8319
7405
|
);
|
|
8320
|
-
if (result.status ===
|
|
7406
|
+
if (result.status === import_common16.Status.ok) {
|
|
8321
7407
|
return {
|
|
8322
7408
|
originalText,
|
|
8323
7409
|
status: "success",
|
|
@@ -8361,17 +7447,17 @@ function validateProcessorConfig(config) {
|
|
|
8361
7447
|
}
|
|
8362
7448
|
return { isValid: true };
|
|
8363
7449
|
}
|
|
8364
|
-
var
|
|
7450
|
+
var import_common16;
|
|
8365
7451
|
var init_cardProcessor = __esm({
|
|
8366
7452
|
"src/core/bulkImport/cardProcessor.ts"() {
|
|
8367
7453
|
"use strict";
|
|
8368
|
-
|
|
7454
|
+
import_common16 = require("@vue-skuilder/common");
|
|
8369
7455
|
init_logger();
|
|
8370
7456
|
}
|
|
8371
7457
|
});
|
|
8372
7458
|
|
|
8373
7459
|
// src/core/bulkImport/types.ts
|
|
8374
|
-
var
|
|
7460
|
+
var init_types3 = __esm({
|
|
8375
7461
|
"src/core/bulkImport/types.ts"() {
|
|
8376
7462
|
"use strict";
|
|
8377
7463
|
}
|
|
@@ -8382,7 +7468,7 @@ var init_bulkImport = __esm({
|
|
|
8382
7468
|
"src/core/bulkImport/index.ts"() {
|
|
8383
7469
|
"use strict";
|
|
8384
7470
|
init_cardProcessor();
|
|
8385
|
-
|
|
7471
|
+
init_types3();
|
|
8386
7472
|
}
|
|
8387
7473
|
});
|
|
8388
7474
|
|