@vue-skuilder/db 0.2.34 → 0.2.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +15 -4
- package/build.entries.mjs +12 -0
- package/dist/_virtual/_rolldown/runtime.mjs +8 -0
- package/dist/{contentSource-CTQ4kWhR.d.cts → contentSource-D_E7JaxR.d.ts} +2 -2
- package/dist/core/UserDBDebugger.mjs +285 -0
- package/dist/core/UserDBDebugger.mjs.map +1 -0
- package/dist/core/bulkImport/cardProcessor.mjs +106 -0
- package/dist/core/bulkImport/cardProcessor.mjs.map +1 -0
- package/dist/core/{index.js → index.cjs} +6438 -7784
- package/dist/core/index.cjs.map +1 -0
- package/dist/core/index.d.ts +5 -5
- package/dist/core/index.mjs +20 -11368
- package/dist/core/interfaces/contentSource.mjs +20 -0
- package/dist/core/interfaces/contentSource.mjs.map +1 -0
- package/dist/core/navigators/Pipeline.mjs +723 -0
- package/dist/core/navigators/Pipeline.mjs.map +1 -0
- package/dist/core/navigators/PipelineAssembler.mjs +86 -0
- package/dist/core/navigators/PipelineAssembler.mjs.map +1 -0
- package/dist/core/navigators/PipelineDebugger.mjs +771 -0
- package/dist/core/navigators/PipelineDebugger.mjs.map +1 -0
- package/dist/core/navigators/SrsDebugger.mjs +34 -0
- package/dist/core/navigators/SrsDebugger.mjs.map +1 -0
- package/dist/core/navigators/StrategyPressureDebugger.mjs +19 -0
- package/dist/core/navigators/StrategyPressureDebugger.mjs.map +1 -0
- package/dist/core/navigators/defaults.mjs +96 -0
- package/dist/core/navigators/defaults.mjs.map +1 -0
- package/dist/core/navigators/diversityRerank.mjs +85 -0
- package/dist/core/navigators/diversityRerank.mjs.map +1 -0
- package/dist/core/navigators/filters/WeightedFilter.mjs +81 -0
- package/dist/core/navigators/filters/WeightedFilter.mjs.map +1 -0
- package/dist/core/navigators/filters/eloDistance.mjs +244 -0
- package/dist/core/navigators/filters/eloDistance.mjs.map +1 -0
- package/dist/core/navigators/filters/hierarchyDefinition.mjs +235 -0
- package/dist/core/navigators/filters/hierarchyDefinition.mjs.map +1 -0
- package/dist/core/navigators/filters/interferenceMitigator.mjs +201 -0
- package/dist/core/navigators/filters/interferenceMitigator.mjs.map +1 -0
- package/dist/core/navigators/filters/relativePriority.mjs +135 -0
- package/dist/core/navigators/filters/relativePriority.mjs.map +1 -0
- package/dist/core/navigators/filters/userTagPreference.mjs +101 -0
- package/dist/core/navigators/filters/userTagPreference.mjs.map +1 -0
- package/dist/core/navigators/generators/CompositeGenerator.mjs +203 -0
- package/dist/core/navigators/generators/CompositeGenerator.mjs.map +1 -0
- package/dist/core/navigators/generators/elo.mjs +77 -0
- package/dist/core/navigators/generators/elo.mjs.map +1 -0
- package/dist/core/navigators/generators/prescribed.mjs +676 -0
- package/dist/core/navigators/generators/prescribed.mjs.map +1 -0
- package/dist/core/navigators/generators/srs.mjs +158 -0
- package/dist/core/navigators/generators/srs.mjs.map +1 -0
- package/dist/core/navigators/index.mjs +345 -0
- package/dist/core/navigators/index.mjs.map +1 -0
- package/dist/core/navigators/pipelinePlan.mjs +109 -0
- package/dist/core/navigators/pipelinePlan.mjs.map +1 -0
- package/dist/core/navigators/regulators.mjs +128 -0
- package/dist/core/navigators/regulators.mjs.map +1 -0
- package/dist/core/orchestration/gradient.mjs +101 -0
- package/dist/core/orchestration/gradient.mjs.map +1 -0
- package/dist/core/orchestration/index.mjs +115 -0
- package/dist/core/orchestration/index.mjs.map +1 -0
- package/dist/core/orchestration/learning.mjs +140 -0
- package/dist/core/orchestration/learning.mjs.map +1 -0
- package/dist/core/orchestration/recording.mjs +64 -0
- package/dist/core/orchestration/recording.mjs.map +1 -0
- package/dist/core/orchestration/signal.mjs +40 -0
- package/dist/core/orchestration/signal.mjs.map +1 -0
- package/dist/core/types/contentNavigationStrategy.mjs +10 -0
- package/dist/core/types/contentNavigationStrategy.mjs.map +1 -0
- package/dist/core/types/hydration.mjs +13 -0
- package/dist/core/types/hydration.mjs.map +1 -0
- package/dist/core/types/strategyState.mjs +16 -0
- package/dist/core/types/strategyState.mjs.map +1 -0
- package/dist/core/types/studySession.mjs +14 -0
- package/dist/core/types/studySession.mjs.map +1 -0
- package/dist/core/types/types-legacy.mjs +44 -0
- package/dist/core/types/types-legacy.mjs.map +1 -0
- package/dist/core/util/index.mjs +31 -0
- package/dist/core/util/index.mjs.map +1 -0
- package/dist/core/versionStamps.mjs +46 -0
- package/dist/core/versionStamps.mjs.map +1 -0
- package/dist/courseConfigRegistration.mjs +306 -0
- package/dist/courseConfigRegistration.mjs.map +1 -0
- package/dist/{dataLayerProvider-rlLE2Mf-.d.ts → dataLayerProvider-BDshhSp_.d.ts} +1 -1
- package/dist/diagnostics/dataset.mjs +118 -0
- package/dist/diagnostics/dataset.mjs.map +1 -0
- package/dist/diagnostics/derive.mjs +318 -0
- package/dist/diagnostics/derive.mjs.map +1 -0
- package/dist/diagnostics/{index.js → index.cjs} +130 -1
- package/dist/diagnostics/index.cjs.map +1 -0
- package/dist/diagnostics/index.d.ts +108 -5
- package/dist/diagnostics/index.mjs +7 -914
- package/dist/diagnostics/loader.mjs +151 -0
- package/dist/diagnostics/loader.mjs.map +1 -0
- package/dist/diagnostics/pipeline.mjs +161 -0
- package/dist/diagnostics/pipeline.mjs.map +1 -0
- package/dist/diagnostics/tagElo.mjs +177 -0
- package/dist/diagnostics/tagElo.mjs.map +1 -0
- package/dist/diagnostics/text.mjs +174 -0
- package/dist/diagnostics/text.mjs.map +1 -0
- package/dist/factory.mjs +70 -0
- package/dist/factory.mjs.map +1 -0
- package/dist/impl/common/BaseUserDB.mjs +1103 -0
- package/dist/impl/common/BaseUserDB.mjs.map +1 -0
- package/dist/impl/common/userDBHelpers.mjs +49 -0
- package/dist/impl/common/userDBHelpers.mjs.map +1 -0
- package/dist/impl/common/userDBKeys.mjs +45 -0
- package/dist/impl/common/userDBKeys.mjs.map +1 -0
- package/dist/impl/couch/CouchDBSyncStrategy.mjs +272 -0
- package/dist/impl/couch/CouchDBSyncStrategy.mjs.map +1 -0
- package/dist/impl/couch/CourseSyncService.mjs +242 -0
- package/dist/impl/couch/CourseSyncService.mjs.map +1 -0
- package/dist/impl/couch/PouchDataLayerProvider.mjs +74 -0
- package/dist/impl/couch/PouchDataLayerProvider.mjs.map +1 -0
- package/dist/impl/couch/adminDB.mjs +61 -0
- package/dist/impl/couch/adminDB.mjs.map +1 -0
- package/dist/impl/couch/auth.mjs +33 -0
- package/dist/impl/couch/auth.mjs.map +1 -0
- package/dist/impl/couch/classroomDB.mjs +227 -0
- package/dist/impl/couch/classroomDB.mjs.map +1 -0
- package/dist/impl/couch/clientCache.mjs +15 -0
- package/dist/impl/couch/clientCache.mjs.map +1 -0
- package/dist/impl/couch/courseAPI.mjs +183 -0
- package/dist/impl/couch/courseAPI.mjs.map +1 -0
- package/dist/impl/couch/courseDB.mjs +729 -0
- package/dist/impl/couch/courseDB.mjs.map +1 -0
- package/dist/impl/couch/courseLookupDB.mjs +94 -0
- package/dist/impl/couch/courseLookupDB.mjs.map +1 -0
- package/dist/impl/couch/{index.js → index.cjs} +6911 -10367
- package/dist/impl/couch/index.cjs.map +1 -0
- package/dist/impl/couch/index.d.ts +12 -5
- package/dist/impl/couch/index.mjs +134 -12146
- package/dist/impl/couch/index.mjs.map +1 -1
- package/dist/impl/couch/pouchdb-setup.mjs +15 -0
- package/dist/impl/couch/pouchdb-setup.mjs.map +1 -0
- package/dist/impl/couch/updateQueue.mjs +101 -0
- package/dist/impl/couch/updateQueue.mjs.map +1 -0
- package/dist/impl/couch/user-course-relDB.mjs +55 -0
- package/dist/impl/couch/user-course-relDB.mjs.map +1 -0
- package/dist/impl/static/NoOpSyncStrategy.mjs +49 -0
- package/dist/impl/static/NoOpSyncStrategy.mjs.map +1 -0
- package/dist/impl/static/StaticDataLayerProvider.mjs +94 -0
- package/dist/impl/static/StaticDataLayerProvider.mjs.map +1 -0
- package/dist/impl/static/StaticDataUnpacker.mjs +311 -0
- package/dist/impl/static/StaticDataUnpacker.mjs.map +1 -0
- package/dist/impl/static/courseDB.mjs +368 -0
- package/dist/impl/static/courseDB.mjs.map +1 -0
- package/dist/impl/static/coursesDB.mjs +38 -0
- package/dist/impl/static/coursesDB.mjs.map +1 -0
- package/dist/impl/static/{index.js → index.cjs} +2461 -5992
- package/dist/impl/static/index.cjs.map +1 -0
- package/dist/impl/static/index.d.ts +4 -4
- package/dist/impl/static/index.mjs +6 -10741
- package/dist/{index-CVGehe_t.d.ts → index-BLDpFYG3.d.ts} +1 -1
- package/dist/{index.js → index.cjs} +14070 -14239
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +12 -23
- package/dist/index.mjs +38 -16937
- package/dist/pouch/{index.js → index.cjs} +5 -1
- package/dist/pouch/index.cjs.map +1 -0
- package/dist/pouch/index.mjs +2 -19
- package/dist/study/ItemQueue.mjs +95 -0
- package/dist/study/ItemQueue.mjs.map +1 -0
- package/dist/study/MixerDebugger.mjs +303 -0
- package/dist/study/MixerDebugger.mjs.map +1 -0
- package/dist/study/SessionController.mjs +1187 -0
- package/dist/study/SessionController.mjs.map +1 -0
- package/dist/study/SessionDebugger.mjs +271 -0
- package/dist/study/SessionDebugger.mjs.map +1 -0
- package/dist/study/SessionOverlay.mjs +407 -0
- package/dist/study/SessionOverlay.mjs.map +1 -0
- package/dist/study/SourceMixer.mjs +45 -0
- package/dist/study/SourceMixer.mjs.map +1 -0
- package/dist/study/SpacedRepetition.mjs +108 -0
- package/dist/study/SpacedRepetition.mjs.map +1 -0
- package/dist/study/TagFilteredContentSource.mjs +136 -0
- package/dist/study/TagFilteredContentSource.mjs.map +1 -0
- package/dist/study/services/CardHydrationService.mjs +172 -0
- package/dist/study/services/CardHydrationService.mjs.map +1 -0
- package/dist/study/services/EloService.mjs +217 -0
- package/dist/study/services/EloService.mjs.map +1 -0
- package/dist/study/services/ResponseProcessor.mjs +190 -0
- package/dist/study/services/ResponseProcessor.mjs.map +1 -0
- package/dist/study/services/SrsService.mjs +49 -0
- package/dist/study/services/SrsService.mjs.map +1 -0
- package/dist/study/services/tagRecent.mjs +65 -0
- package/dist/study/services/tagRecent.mjs.map +1 -0
- package/dist/{types-dXWfyz9B.d.ts → types-DChCz22D.d.ts} +1 -1
- package/dist/{types-legacy-BkOYOR6U.d.cts → types-legacy-fT5Y1Wuy.d.ts} +1 -1
- package/dist/userDBKeys-ne1g4Xuq.d.ts +16 -0
- package/dist/util/Loggable.mjs +14 -0
- package/dist/util/Loggable.mjs.map +1 -0
- package/dist/util/dataDirectory.mjs +47 -0
- package/dist/util/dataDirectory.mjs.map +1 -0
- package/dist/util/logger.mjs +86 -0
- package/dist/util/logger.mjs.map +1 -0
- package/dist/util/migrator/FileSystemAdapter.mjs +18 -0
- package/dist/util/migrator/FileSystemAdapter.mjs.map +1 -0
- package/dist/util/migrator/StaticToCouchDBMigrator.mjs +428 -0
- package/dist/util/migrator/StaticToCouchDBMigrator.mjs.map +1 -0
- package/dist/util/migrator/types.mjs +11 -0
- package/dist/util/migrator/types.mjs.map +1 -0
- package/dist/util/migrator/validation.mjs +334 -0
- package/dist/util/migrator/validation.mjs.map +1 -0
- package/dist/util/packer/CouchDBToStaticPacker.mjs +438 -0
- package/dist/util/packer/CouchDBToStaticPacker.mjs.map +1 -0
- package/dist/util/packer/{index.js → index.cjs} +73 -9
- package/dist/util/packer/index.cjs.map +1 -0
- package/dist/util/packer/index.d.ts +3 -3
- package/dist/util/packer/index.mjs +2 -537
- package/eslint.config.mjs +9 -1
- package/package.json +25 -13
- package/rolldown.config.mjs +44 -0
- package/src/core/UserDBDebugger.ts +47 -46
- package/src/core/navigators/Pipeline.ts +10 -10
- package/src/core/navigators/PipelineDebugger.ts +55 -55
- package/src/core/navigators/filters/eloDistance.ts +11 -1
- package/src/core/navigators/generators/elo.ts +5 -1
- package/src/core/navigators/index.ts +9 -3
- package/src/diagnostics/derive.ts +6 -0
- package/src/diagnostics/index.ts +1 -0
- package/src/diagnostics/tagElo.ts +257 -0
- package/src/factory.ts +10 -1
- package/src/impl/common/BaseUserDB.ts +1 -3
- package/src/impl/common/index.ts +2 -0
- package/src/impl/common/userDBHelpers.ts +4 -58
- package/src/impl/common/userDBKeys.ts +64 -0
- package/src/impl/couch/courseDB.ts +15 -3
- package/src/impl/couch/index.ts +2 -18
- package/src/impl/couch/pouchdb-setup.ts +8 -0
- package/src/index.ts +1 -1
- package/src/study/MixerDebugger.ts +46 -46
- package/src/study/SessionDebugger.ts +20 -20
- package/src/study/SessionOverlay.ts +4 -4
- package/src/util/logger.ts +112 -13
- package/tests/core/navigators/eloGenerator.test.ts +36 -0
- package/tsup.config.ts +24 -21
- package/dist/SyncStrategy-BXliog1m.d.cts +0 -116
- package/dist/classroomDB-DLTtLZct.d.cts +0 -86
- package/dist/contentSource-JmWYu8IK.d.ts +0 -2007
- package/dist/core/index.d.cts +0 -521
- package/dist/core/index.js.map +0 -1
- package/dist/core/index.mjs.map +0 -1
- package/dist/dataLayerProvider-DfI_KYAe.d.cts +0 -61
- package/dist/diagnostics/index.d.cts +0 -458
- package/dist/diagnostics/index.js.map +0 -1
- package/dist/diagnostics/index.mjs.map +0 -1
- package/dist/impl/couch/index.d.cts +0 -620
- package/dist/impl/couch/index.js.map +0 -1
- package/dist/impl/static/index.d.cts +0 -232
- package/dist/impl/static/index.js.map +0 -1
- package/dist/impl/static/index.mjs.map +0 -1
- package/dist/index-Ktg72jKb.d.cts +0 -137
- package/dist/index.d.cts +0 -1663
- package/dist/index.js.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/pouch/index.d.cts +0 -1
- package/dist/pouch/index.js.map +0 -1
- package/dist/pouch/index.mjs.map +0 -1
- package/dist/types-D0oQeJAi.d.cts +0 -58
- package/dist/types-legacy-BkOYOR6U.d.ts +0 -168
- package/dist/util/packer/index.d.cts +0 -5
- package/dist/util/packer/index.js.map +0 -1
- package/dist/util/packer/index.mjs.map +0 -1
- package/src/study/getCardDataShape.ts +0 -34
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import "../../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
//#region src/core/navigators/regulators.ts
|
|
3
|
+
/**
|
|
4
|
+
* Defaults. Review mass keeps the SRS generator's former healthy threshold and
|
|
5
|
+
* growth rate (20, ×2), now applied to mass instead of count. Intake doubles
|
|
6
|
+
* per day of servable time without a new card.
|
|
7
|
+
*/
|
|
8
|
+
const DEFAULT_REGULATOR_CONFIG = {
|
|
9
|
+
reviewMass: {
|
|
10
|
+
referenceScore: .95,
|
|
11
|
+
healthyMass: 20,
|
|
12
|
+
rate: 2
|
|
13
|
+
},
|
|
14
|
+
intake: {
|
|
15
|
+
rate: 2,
|
|
16
|
+
scaleHours: 24
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
function clamp01(x) {
|
|
20
|
+
return Math.min(1, Math.max(0, x));
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* One due review's weight in the mass, in [0, 1]: its SRS urgency times the
|
|
24
|
+
* filters' net effect on it (filtered score ÷ the score it was generated
|
|
25
|
+
* with), so every course signal discounts it. A review without an urgency
|
|
26
|
+
* weighs its filtered score against the reference.
|
|
27
|
+
*/
|
|
28
|
+
function reviewWeight(card, generatedScore, referenceScore) {
|
|
29
|
+
if (card.reviewUrgency !== void 0 && generatedScore !== void 0 && generatedScore > 0) return clamp01(card.reviewUrgency * (card.score / generatedScore));
|
|
30
|
+
return clamp01(card.score / referenceScore);
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* @param reviews - Due reviews, after filters
|
|
34
|
+
* @param generatedScores - Each card's score as generated, before filters
|
|
35
|
+
*/
|
|
36
|
+
function reviewMassReading(reviews, generatedScores, config = DEFAULT_REGULATOR_CONFIG.reviewMass) {
|
|
37
|
+
const mass = reviews.reduce((m, c) => m + reviewWeight(c, generatedScores.get(c.cardId), config.referenceScore), 0);
|
|
38
|
+
return {
|
|
39
|
+
name: "review-mass",
|
|
40
|
+
class: "review",
|
|
41
|
+
urgency: mass,
|
|
42
|
+
multiplier: mass > config.healthyMass ? Math.pow(config.rate, (mass - config.healthyMass) / config.healthyMass) : 1,
|
|
43
|
+
applied: reviews.length,
|
|
44
|
+
inputs: {
|
|
45
|
+
due: reviews.length,
|
|
46
|
+
mass,
|
|
47
|
+
healthyMass: config.healthyMass
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** Strategy-state key for the intake clock. */
|
|
52
|
+
const INTAKE_CLOCK_KEY = "IntakeClock";
|
|
53
|
+
/** A fresh clock: a new card was just presented (or the clock is starting). */
|
|
54
|
+
function resetIntakeClock(nowMs) {
|
|
55
|
+
return {
|
|
56
|
+
lastNewAt: new Date(nowMs).toISOString(),
|
|
57
|
+
frozenMs: 0,
|
|
58
|
+
unservableSince: null
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/** Frozen time so far, including an open unservable stretch. */
|
|
62
|
+
function frozenMsAt(state, nowMs) {
|
|
63
|
+
const open = state.unservableSince ? Math.max(0, nowMs - Date.parse(state.unservableSince)) : 0;
|
|
64
|
+
return state.frozenMs + open;
|
|
65
|
+
}
|
|
66
|
+
/** Servable hours since a new card was last presented. */
|
|
67
|
+
function intakeHours(state, nowMs) {
|
|
68
|
+
const elapsed = nowMs - Date.parse(state.lastNewAt);
|
|
69
|
+
return Math.max(0, elapsed - frozenMsAt(state, nowMs)) / 36e5;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Advance the clock's freeze bookkeeping for a run that found `eligibleNew`
|
|
73
|
+
* eligible new candidates. The clock freezes while there are none (exhaustion
|
|
74
|
+
* isn't starvation) and resumes when some appear. Returns the same object when
|
|
75
|
+
* nothing changed, so callers persist only on transitions.
|
|
76
|
+
*/
|
|
77
|
+
function stepIntakeClock(state, nowMs, eligibleNew) {
|
|
78
|
+
if (eligibleNew === 0 && !state.unservableSince) return {
|
|
79
|
+
...state,
|
|
80
|
+
unservableSince: new Date(nowMs).toISOString()
|
|
81
|
+
};
|
|
82
|
+
if (eligibleNew > 0 && state.unservableSince) return {
|
|
83
|
+
...state,
|
|
84
|
+
frozenMs: frozenMsAt(state, nowMs),
|
|
85
|
+
unservableSince: null
|
|
86
|
+
};
|
|
87
|
+
return state;
|
|
88
|
+
}
|
|
89
|
+
function intakeReading(state, nowMs, counts, config = DEFAULT_REGULATOR_CONFIG.intake) {
|
|
90
|
+
const hours = intakeHours(state, nowMs);
|
|
91
|
+
return {
|
|
92
|
+
name: "intake",
|
|
93
|
+
class: "new",
|
|
94
|
+
urgency: hours,
|
|
95
|
+
multiplier: counts.eligibleNew > 0 ? Math.pow(config.rate, hours / config.scaleHours) : 1,
|
|
96
|
+
applied: counts.eligibleNew,
|
|
97
|
+
inputs: {
|
|
98
|
+
hoursSinceNew: hours,
|
|
99
|
+
frozenHours: frozenMsAt(state, nowMs) / 36e5,
|
|
100
|
+
eligibleNew: counts.eligibleNew,
|
|
101
|
+
newCandidates: counts.newCandidates
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
const REGULATOR_LABEL = {
|
|
106
|
+
"review-mass": "Review mass",
|
|
107
|
+
intake: "Intake"
|
|
108
|
+
};
|
|
109
|
+
/** Multiply `cards` (in place) by a reading's multiplier, with a provenance entry when it changes them. */
|
|
110
|
+
function applyReading(cards, reading) {
|
|
111
|
+
if (reading.multiplier === 1) return;
|
|
112
|
+
const reason = reading.name === "review-mass" ? `review mass ${reading.urgency.toFixed(1)} (healthy ${reading.inputs.healthyMass}) → ×${reading.multiplier.toFixed(2)}` : `${reading.urgency.toFixed(1)}h since a new card → ×${reading.multiplier.toFixed(2)}`;
|
|
113
|
+
for (const card of cards) {
|
|
114
|
+
card.score *= reading.multiplier;
|
|
115
|
+
card.provenance.push({
|
|
116
|
+
strategy: "regulator",
|
|
117
|
+
strategyName: `Regulator: ${REGULATOR_LABEL[reading.name]}`,
|
|
118
|
+
strategyId: `regulator-${reading.name}`,
|
|
119
|
+
action: reading.multiplier > 1 ? "boosted" : "penalized",
|
|
120
|
+
score: card.score,
|
|
121
|
+
reason
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
//#endregion
|
|
126
|
+
export { DEFAULT_REGULATOR_CONFIG, INTAKE_CLOCK_KEY, applyReading, frozenMsAt, intakeHours, intakeReading, resetIntakeClock, reviewMassReading, reviewWeight, stepIntakeClock };
|
|
127
|
+
|
|
128
|
+
//# sourceMappingURL=regulators.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"regulators.mjs","names":[],"sources":["../../../src/core/navigators/regulators.ts"],"sourcesContent":["import type { WeightedCard } from './index';\n\n// ============================================================================\n// REGULATORS (pipeline stage, after filters, before hints)\n// ============================================================================\n//\n// Review and new cards compete in one ranking. Regulators set the balance\n// between the two classes: each valve measures an urgency `u` for its class\n// and multiplies that class's scores by `rate^(u / scale)` above a threshold.\n// Uncapped on both sides, so neither class can be permanently silenced.\n//\n// - Review mass: reviews pile up. Measured as the *value* of the due backlog,\n// not its count: each due review weighs its SRS urgency (0–1) times the\n// filters' net effect on it, so the reserve lake of low-value reviews\n// (moved-beyond, long-interval, barely overdue) weighs little. The SRS\n// score itself won't do: it carries a fixed 0.5 ranking offset, so every\n// review would weigh at least ~0.6.\n// - Intake: new content stalls. Measured as hours since a new card was last\n// presented, counting only time when an eligible new card existed.\n//\n// A stage, not a filter: a regulator reads an aggregate of every candidate's\n// *final* filtered score, so it must run after all filters (which run in name\n// order and are assumed commutative). Before hints, so session intent (an\n// intro's follow-up, a difficulty boost) still wins over pressure.\n//\n// Design note: agent/pipeline-regulation/a.0.regulator-stage.md.\n//\n// ============================================================================\n\nexport type RegulatorName = 'review-mass' | 'intake';\n\n/** One regulator's reading for one pipeline run. Persisted on run summaries. */\nexport interface RegulatorReading {\n name: RegulatorName;\n /** The class the multiplier applies to. */\n class: 'review' | 'new';\n /** The valve's urgency: review mass (card-equivalents) or intake hours. */\n urgency: number;\n multiplier: number;\n /** Candidates the multiplier applied to. */\n applied: number;\n inputs: Record<string, number>;\n}\n\nexport interface RegulatorConfig {\n reviewMass: {\n /**\n * Unit of mass for reviews without an SRS urgency (from another\n * generator): a filtered score this high weighs 1.\n */\n referenceScore: number;\n /** Mass (card-equivalents) at or below which there's no pressure. */\n healthyMass: number;\n /** Multiplier growth per multiple of `healthyMass` in excess. */\n rate: number;\n };\n intake: {\n /** Multiplier growth per `scaleHours` without a new card. */\n rate: number;\n scaleHours: number;\n };\n}\n\n/**\n * Defaults. Review mass keeps the SRS generator's former healthy threshold and\n * growth rate (20, ×2), now applied to mass instead of count. Intake doubles\n * per day of servable time without a new card.\n */\nexport const DEFAULT_REGULATOR_CONFIG: RegulatorConfig = {\n reviewMass: { referenceScore: 0.95, healthyMass: 20, rate: 2 },\n intake: { rate: 2, scaleHours: 24 },\n};\n\n// ----------------------------------------------------------------------------\n// Review mass\n// ----------------------------------------------------------------------------\n\nfunction clamp01(x: number): number {\n return Math.min(1, Math.max(0, x));\n}\n\n/**\n * One due review's weight in the mass, in [0, 1]: its SRS urgency times the\n * filters' net effect on it (filtered score ÷ the score it was generated\n * with), so every course signal discounts it. A review without an urgency\n * weighs its filtered score against the reference.\n */\nexport function reviewWeight(\n card: WeightedCard,\n generatedScore: number | undefined,\n referenceScore: number\n): number {\n if (card.reviewUrgency !== undefined && generatedScore !== undefined && generatedScore > 0) {\n return clamp01(card.reviewUrgency * (card.score / generatedScore));\n }\n return clamp01(card.score / referenceScore);\n}\n\n/**\n * @param reviews - Due reviews, after filters\n * @param generatedScores - Each card's score as generated, before filters\n */\nexport function reviewMassReading(\n reviews: WeightedCard[],\n generatedScores: ReadonlyMap<string, number>,\n config: RegulatorConfig['reviewMass'] = DEFAULT_REGULATOR_CONFIG.reviewMass\n): RegulatorReading {\n const mass = reviews.reduce(\n (m, c) => m + reviewWeight(c, generatedScores.get(c.cardId), config.referenceScore),\n 0\n );\n const multiplier =\n mass > config.healthyMass\n ? Math.pow(config.rate, (mass - config.healthyMass) / config.healthyMass)\n : 1;\n return {\n name: 'review-mass',\n class: 'review',\n urgency: mass,\n multiplier,\n applied: reviews.length,\n inputs: { due: reviews.length, mass, healthyMass: config.healthyMass },\n };\n}\n\n// ----------------------------------------------------------------------------\n// Intake\n// ----------------------------------------------------------------------------\n\n/** The intake valve's clock, persisted per user and course (strategy state). */\nexport interface IntakeClockState {\n /** When a new card was last presented (ISO). */\n lastNewAt: string;\n /** Closed stretches since then during which no eligible new card existed (ms). */\n frozenMs: number;\n /** Start of the current stretch with no eligible new card (ISO), or null. */\n unservableSince: string | null;\n}\n\n/** Strategy-state key for the intake clock. */\nexport const INTAKE_CLOCK_KEY = 'IntakeClock';\n\n/** A fresh clock: a new card was just presented (or the clock is starting). */\nexport function resetIntakeClock(nowMs: number): IntakeClockState {\n return { lastNewAt: new Date(nowMs).toISOString(), frozenMs: 0, unservableSince: null };\n}\n\n/** Frozen time so far, including an open unservable stretch. */\nexport function frozenMsAt(state: IntakeClockState, nowMs: number): number {\n const open = state.unservableSince ? Math.max(0, nowMs - Date.parse(state.unservableSince)) : 0;\n return state.frozenMs + open;\n}\n\n/** Servable hours since a new card was last presented. */\nexport function intakeHours(state: IntakeClockState, nowMs: number): number {\n const elapsed = nowMs - Date.parse(state.lastNewAt);\n return Math.max(0, elapsed - frozenMsAt(state, nowMs)) / 3_600_000;\n}\n\n/**\n * Advance the clock's freeze bookkeeping for a run that found `eligibleNew`\n * eligible new candidates. The clock freezes while there are none (exhaustion\n * isn't starvation) and resumes when some appear. Returns the same object when\n * nothing changed, so callers persist only on transitions.\n */\nexport function stepIntakeClock(\n state: IntakeClockState,\n nowMs: number,\n eligibleNew: number\n): IntakeClockState {\n if (eligibleNew === 0 && !state.unservableSince) {\n return { ...state, unservableSince: new Date(nowMs).toISOString() };\n }\n if (eligibleNew > 0 && state.unservableSince) {\n return { ...state, frozenMs: frozenMsAt(state, nowMs), unservableSince: null };\n }\n return state;\n}\n\nexport function intakeReading(\n state: IntakeClockState,\n nowMs: number,\n counts: { eligibleNew: number; newCandidates: number },\n config: RegulatorConfig['intake'] = DEFAULT_REGULATOR_CONFIG.intake\n): RegulatorReading {\n const hours = intakeHours(state, nowMs);\n const multiplier = counts.eligibleNew > 0 ? Math.pow(config.rate, hours / config.scaleHours) : 1;\n return {\n name: 'intake',\n class: 'new',\n urgency: hours,\n multiplier,\n applied: counts.eligibleNew,\n inputs: {\n hoursSinceNew: hours,\n frozenHours: frozenMsAt(state, nowMs) / 3_600_000,\n eligibleNew: counts.eligibleNew,\n newCandidates: counts.newCandidates,\n },\n };\n}\n\n// ----------------------------------------------------------------------------\n// Applying\n// ----------------------------------------------------------------------------\n\nconst REGULATOR_LABEL: Record<RegulatorName, string> = {\n 'review-mass': 'Review mass',\n intake: 'Intake',\n};\n\n/** Multiply `cards` (in place) by a reading's multiplier, with a provenance entry when it changes them. */\nexport function applyReading(cards: WeightedCard[], reading: RegulatorReading): void {\n if (reading.multiplier === 1) return;\n const reason =\n reading.name === 'review-mass'\n ? `review mass ${reading.urgency.toFixed(1)} (healthy ${reading.inputs.healthyMass}) → ×${reading.multiplier.toFixed(2)}`\n : `${reading.urgency.toFixed(1)}h since a new card → ×${reading.multiplier.toFixed(2)}`;\n for (const card of cards) {\n card.score *= reading.multiplier;\n card.provenance.push({\n strategy: 'regulator',\n strategyName: `Regulator: ${REGULATOR_LABEL[reading.name]}`,\n strategyId: `regulator-${reading.name}`,\n action: reading.multiplier > 1 ? 'boosted' : 'penalized',\n score: card.score,\n reason,\n });\n }\n}\n"],"mappings":"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"}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import "../../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
import { logger } from "../../util/logger.mjs";
|
|
3
|
+
//#region src/core/orchestration/gradient.ts
|
|
4
|
+
/**
|
|
5
|
+
* Extract (deviation, outcome) observations for a specific strategy
|
|
6
|
+
* from a collection of UserOutcomeRecords.
|
|
7
|
+
*
|
|
8
|
+
* @param outcomes - Collection of outcome records (from multiple users)
|
|
9
|
+
* @param strategyId - The strategy to extract observations for
|
|
10
|
+
* @returns Array of gradient observations
|
|
11
|
+
*/
|
|
12
|
+
function aggregateOutcomesForGradient(outcomes, strategyId) {
|
|
13
|
+
const observations = [];
|
|
14
|
+
for (const outcome of outcomes) {
|
|
15
|
+
const deviation = outcome.deviations[strategyId];
|
|
16
|
+
if (deviation === void 0) continue;
|
|
17
|
+
observations.push({
|
|
18
|
+
deviation,
|
|
19
|
+
outcomeValue: outcome.outcomeValue,
|
|
20
|
+
weight: 1
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
logger.debug(`[Orchestration] Aggregated ${observations.length} observations for strategy ${strategyId}`);
|
|
24
|
+
return observations;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Compute linear regression on (deviation, outcome) pairs.
|
|
28
|
+
*
|
|
29
|
+
* Uses ordinary least squares to find the best fit line:
|
|
30
|
+
* outcome = gradient * deviation + intercept
|
|
31
|
+
*
|
|
32
|
+
* The gradient tells us:
|
|
33
|
+
* - Positive: users with higher deviation (higher weight) had better outcomes
|
|
34
|
+
* → we should increase the peak weight
|
|
35
|
+
* - Negative: users with higher deviation (higher weight) had worse outcomes
|
|
36
|
+
* → we should decrease the peak weight
|
|
37
|
+
* - Near zero: weight doesn't affect outcomes much
|
|
38
|
+
* → we're near optimal, increase confidence
|
|
39
|
+
*
|
|
40
|
+
* @param observations - Array of (deviation, outcome) pairs
|
|
41
|
+
* @returns Regression result, or null if insufficient data
|
|
42
|
+
*/
|
|
43
|
+
function computeStrategyGradient(observations) {
|
|
44
|
+
const n = observations.length;
|
|
45
|
+
if (n < 3) {
|
|
46
|
+
logger.debug(`[Orchestration] Insufficient observations for gradient (${n} < 3)`);
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
let sumX = 0;
|
|
50
|
+
let sumY = 0;
|
|
51
|
+
let sumW = 0;
|
|
52
|
+
for (const obs of observations) {
|
|
53
|
+
const w = obs.weight ?? 1;
|
|
54
|
+
sumX += obs.deviation * w;
|
|
55
|
+
sumY += obs.outcomeValue * w;
|
|
56
|
+
sumW += w;
|
|
57
|
+
}
|
|
58
|
+
const meanX = sumX / sumW;
|
|
59
|
+
const meanY = sumY / sumW;
|
|
60
|
+
let numerator = 0;
|
|
61
|
+
let denominator = 0;
|
|
62
|
+
let ssTotal = 0;
|
|
63
|
+
for (const obs of observations) {
|
|
64
|
+
const w = obs.weight ?? 1;
|
|
65
|
+
const dx = obs.deviation - meanX;
|
|
66
|
+
const dy = obs.outcomeValue - meanY;
|
|
67
|
+
numerator += w * dx * dy;
|
|
68
|
+
denominator += w * dx * dx;
|
|
69
|
+
ssTotal += w * dy * dy;
|
|
70
|
+
}
|
|
71
|
+
if (denominator < 1e-10) {
|
|
72
|
+
logger.debug(`[Orchestration] No variance in deviations, cannot compute gradient`);
|
|
73
|
+
return {
|
|
74
|
+
gradient: 0,
|
|
75
|
+
intercept: meanY,
|
|
76
|
+
rSquared: 0,
|
|
77
|
+
sampleSize: n
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
const gradient = numerator / denominator;
|
|
81
|
+
const intercept = meanY - gradient * meanX;
|
|
82
|
+
let ssResidual = 0;
|
|
83
|
+
for (const obs of observations) {
|
|
84
|
+
const w = obs.weight ?? 1;
|
|
85
|
+
const predicted = gradient * obs.deviation + intercept;
|
|
86
|
+
const residual = obs.outcomeValue - predicted;
|
|
87
|
+
ssResidual += w * residual * residual;
|
|
88
|
+
}
|
|
89
|
+
const rSquared = ssTotal > 1e-10 ? 1 - ssResidual / ssTotal : 0;
|
|
90
|
+
logger.debug(`[Orchestration] Computed gradient: ${gradient.toFixed(4)}, intercept: ${intercept.toFixed(4)}, R²: ${rSquared.toFixed(4)}, n=${n}`);
|
|
91
|
+
return {
|
|
92
|
+
gradient,
|
|
93
|
+
intercept,
|
|
94
|
+
rSquared: Math.max(0, Math.min(1, rSquared)),
|
|
95
|
+
sampleSize: n
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
//#endregion
|
|
99
|
+
export { aggregateOutcomesForGradient, computeStrategyGradient };
|
|
100
|
+
|
|
101
|
+
//# sourceMappingURL=gradient.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"gradient.mjs","names":[],"sources":["../../../src/core/orchestration/gradient.ts"],"sourcesContent":["import { UserOutcomeRecord } from '../types/userOutcome';\nimport { GradientObservation, GradientResult } from '../types/learningState';\nimport { logger } from '../../util/logger';\n\n/**\n * Extract (deviation, outcome) observations for a specific strategy\n * from a collection of UserOutcomeRecords.\n *\n * @param outcomes - Collection of outcome records (from multiple users)\n * @param strategyId - The strategy to extract observations for\n * @returns Array of gradient observations\n */\nexport function aggregateOutcomesForGradient(\n outcomes: UserOutcomeRecord[],\n strategyId: string\n): GradientObservation[] {\n const observations: GradientObservation[] = [];\n\n for (const outcome of outcomes) {\n // Skip if this outcome doesn't have a deviation for this strategy\n const deviation = outcome.deviations[strategyId];\n if (deviation === undefined) {\n continue;\n }\n\n observations.push({\n deviation,\n outcomeValue: outcome.outcomeValue,\n weight: 1.0,\n });\n }\n\n logger.debug(\n `[Orchestration] Aggregated ${observations.length} observations for strategy ${strategyId}`\n );\n\n return observations;\n}\n\n/**\n * Compute linear regression on (deviation, outcome) pairs.\n *\n * Uses ordinary least squares to find the best fit line:\n * outcome = gradient * deviation + intercept\n *\n * The gradient tells us:\n * - Positive: users with higher deviation (higher weight) had better outcomes\n * → we should increase the peak weight\n * - Negative: users with higher deviation (higher weight) had worse outcomes\n * → we should decrease the peak weight\n * - Near zero: weight doesn't affect outcomes much\n * → we're near optimal, increase confidence\n *\n * @param observations - Array of (deviation, outcome) pairs\n * @returns Regression result, or null if insufficient data\n */\nexport function computeStrategyGradient(\n observations: GradientObservation[]\n): GradientResult | null {\n const n = observations.length;\n\n if (n < 3) {\n logger.debug(`[Orchestration] Insufficient observations for gradient (${n} < 3)`);\n return null;\n }\n\n // Compute means\n let sumX = 0;\n let sumY = 0;\n let sumW = 0;\n\n for (const obs of observations) {\n const w = obs.weight ?? 1.0;\n sumX += obs.deviation * w;\n sumY += obs.outcomeValue * w;\n sumW += w;\n }\n\n const meanX = sumX / sumW;\n const meanY = sumY / sumW;\n\n // Compute slope (gradient) and intercept using weighted least squares\n let numerator = 0;\n let denominator = 0;\n let ssTotal = 0;\n\n for (const obs of observations) {\n const w = obs.weight ?? 1.0;\n const dx = obs.deviation - meanX;\n const dy = obs.outcomeValue - meanY;\n\n numerator += w * dx * dy;\n denominator += w * dx * dx;\n ssTotal += w * dy * dy;\n }\n\n // Avoid division by zero if all deviations are the same\n if (denominator < 1e-10) {\n logger.debug(`[Orchestration] No variance in deviations, cannot compute gradient`);\n return {\n gradient: 0,\n intercept: meanY,\n rSquared: 0,\n sampleSize: n,\n };\n }\n\n const gradient = numerator / denominator;\n const intercept = meanY - gradient * meanX;\n\n // Compute R-squared\n let ssResidual = 0;\n for (const obs of observations) {\n const w = obs.weight ?? 1.0;\n const predicted = gradient * obs.deviation + intercept;\n const residual = obs.outcomeValue - predicted;\n ssResidual += w * residual * residual;\n }\n\n const rSquared = ssTotal > 1e-10 ? 1 - ssResidual / ssTotal : 0;\n\n logger.debug(\n `[Orchestration] Computed gradient: ${gradient.toFixed(4)}, ` +\n `intercept: ${intercept.toFixed(4)}, R²: ${rSquared.toFixed(4)}, n=${n}`\n );\n\n return {\n gradient,\n intercept,\n rSquared: Math.max(0, Math.min(1, rSquared)), // Clamp to [0,1]\n sampleSize: n,\n };\n}\n"],"mappings":";;;;;;;;;;;AAYA,SAAgB,6BACd,UACA,YACuB;CACvB,MAAM,eAAsC,EAAE;AAE9C,MAAK,MAAM,WAAW,UAAU;EAE9B,MAAM,YAAY,QAAQ,WAAW;AACrC,MAAI,cAAc,KAAA,EAChB;AAGF,eAAa,KAAK;GAChB;GACA,cAAc,QAAQ;GACtB,QAAQ;GACT,CAAC;;AAGJ,QAAO,MACL,8BAA8B,aAAa,OAAO,6BAA6B,aAChF;AAED,QAAO;;;;;;;;;;;;;;;;;;;AAoBT,SAAgB,wBACd,cACuB;CACvB,MAAM,IAAI,aAAa;AAEvB,KAAI,IAAI,GAAG;AACT,SAAO,MAAM,2DAA2D,EAAE,OAAO;AACjF,SAAO;;CAIT,IAAI,OAAO;CACX,IAAI,OAAO;CACX,IAAI,OAAO;AAEX,MAAK,MAAM,OAAO,cAAc;EAC9B,MAAM,IAAI,IAAI,UAAU;AACxB,UAAQ,IAAI,YAAY;AACxB,UAAQ,IAAI,eAAe;AAC3B,UAAQ;;CAGV,MAAM,QAAQ,OAAO;CACrB,MAAM,QAAQ,OAAO;CAGrB,IAAI,YAAY;CAChB,IAAI,cAAc;CAClB,IAAI,UAAU;AAEd,MAAK,MAAM,OAAO,cAAc;EAC9B,MAAM,IAAI,IAAI,UAAU;EACxB,MAAM,KAAK,IAAI,YAAY;EAC3B,MAAM,KAAK,IAAI,eAAe;AAE9B,eAAa,IAAI,KAAK;AACtB,iBAAe,IAAI,KAAK;AACxB,aAAW,IAAI,KAAK;;AAItB,KAAI,cAAc,OAAO;AACvB,SAAO,MAAM,qEAAqE;AAClF,SAAO;GACL,UAAU;GACV,WAAW;GACX,UAAU;GACV,YAAY;GACb;;CAGH,MAAM,WAAW,YAAY;CAC7B,MAAM,YAAY,QAAQ,WAAW;CAGrC,IAAI,aAAa;AACjB,MAAK,MAAM,OAAO,cAAc;EAC9B,MAAM,IAAI,IAAI,UAAU;EACxB,MAAM,YAAY,WAAW,IAAI,YAAY;EAC7C,MAAM,WAAW,IAAI,eAAe;AACpC,gBAAc,IAAI,WAAW;;CAG/B,MAAM,WAAW,UAAU,QAAQ,IAAI,aAAa,UAAU;AAE9D,QAAO,MACL,sCAAsC,SAAS,QAAQ,EAAE,CAAC,eAC1C,UAAU,QAAQ,EAAE,CAAC,QAAQ,SAAS,QAAQ,EAAE,CAAC,MAAM,IACxE;AAED,QAAO;EACL;EACA;EACA,UAAU,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,SAAS,CAAC;EAC5C,YAAY;EACb"}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import "../../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
import { logger } from "../../util/logger.mjs";
|
|
3
|
+
import "./gradient.mjs";
|
|
4
|
+
import "./learning.mjs";
|
|
5
|
+
import "./signal.mjs";
|
|
6
|
+
import "./recording.mjs";
|
|
7
|
+
//#region src/core/orchestration/index.ts
|
|
8
|
+
const MIN_SPREAD = .1;
|
|
9
|
+
const MAX_SPREAD = .5;
|
|
10
|
+
const MIN_WEIGHT = .1;
|
|
11
|
+
const MAX_WEIGHT = 3;
|
|
12
|
+
/**
|
|
13
|
+
* FNV-1a hash implementation for deterministic distribution.
|
|
14
|
+
*/
|
|
15
|
+
function fnv1a(str) {
|
|
16
|
+
let hash = 2166136261;
|
|
17
|
+
for (let i = 0; i < str.length; i++) {
|
|
18
|
+
hash ^= str.charCodeAt(i);
|
|
19
|
+
hash = Math.imul(hash, 16777619);
|
|
20
|
+
}
|
|
21
|
+
return hash >>> 0;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Compute a user's deviation for a specific strategy.
|
|
25
|
+
*
|
|
26
|
+
* Returns a value in [-1, 1] that is:
|
|
27
|
+
* 1. Deterministic for the same (user, strategy, salt) tuple
|
|
28
|
+
* 2. Uniformly distributed across users
|
|
29
|
+
* 3. Uncorrelated between different strategies (due to strategyId in hash)
|
|
30
|
+
* 4. Rotatable by changing the salt
|
|
31
|
+
*
|
|
32
|
+
* @param userId - ID of the user
|
|
33
|
+
* @param strategyId - ID of the strategy
|
|
34
|
+
* @param salt - Random seed from course config
|
|
35
|
+
* @returns Deviation factor between -1.0 and 1.0
|
|
36
|
+
*/
|
|
37
|
+
function computeDeviation(userId, strategyId, salt) {
|
|
38
|
+
return fnv1a(`${userId}:${strategyId}:${salt}`) / 4294967296 * 2 - 1;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Compute the exploration spread based on confidence.
|
|
42
|
+
*
|
|
43
|
+
* - Low confidence (0.0) -> Max spread (Explore broadly)
|
|
44
|
+
* - High confidence (1.0) -> Min spread (Exploit known good weight)
|
|
45
|
+
*
|
|
46
|
+
* @param confidence - Confidence level 0-1
|
|
47
|
+
* @returns Spread magnitude (half-width of the distribution)
|
|
48
|
+
*/
|
|
49
|
+
function computeSpread(confidence) {
|
|
50
|
+
return MAX_SPREAD - Math.max(0, Math.min(1, confidence)) * (MAX_SPREAD - MIN_SPREAD);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Calculate the effective weight for a strategy instance.
|
|
54
|
+
*
|
|
55
|
+
* Combines the learnable weight (peak) with the user's deviation and the
|
|
56
|
+
* allowed spread (based on confidence).
|
|
57
|
+
*
|
|
58
|
+
* @param learnable - Strategy learning config
|
|
59
|
+
* @param userId - User ID
|
|
60
|
+
* @param strategyId - Strategy ID
|
|
61
|
+
* @param salt - Course salt
|
|
62
|
+
* @returns Effective weight multiplier
|
|
63
|
+
*/
|
|
64
|
+
function computeEffectiveWeight(learnable, userId, strategyId, salt) {
|
|
65
|
+
const adjustment = computeDeviation(userId, strategyId, salt) * computeSpread(learnable.confidence) * learnable.weight;
|
|
66
|
+
const effective = learnable.weight + adjustment;
|
|
67
|
+
return Math.max(MIN_WEIGHT, Math.min(MAX_WEIGHT, effective));
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Create an orchestration context for a study session.
|
|
71
|
+
*
|
|
72
|
+
* Fetches necessary configuration to enable deterministic weight calculation.
|
|
73
|
+
*
|
|
74
|
+
* @param user - User DB interface
|
|
75
|
+
* @param course - Course DB interface
|
|
76
|
+
* @returns Initialized orchestration context
|
|
77
|
+
*/
|
|
78
|
+
async function createOrchestrationContext(user, course) {
|
|
79
|
+
let courseConfig;
|
|
80
|
+
try {
|
|
81
|
+
courseConfig = await course.getCourseConfig();
|
|
82
|
+
} catch (e) {
|
|
83
|
+
logger.error(`[Orchestration] Failed to load course config: ${e}`);
|
|
84
|
+
courseConfig = {
|
|
85
|
+
name: "Unknown",
|
|
86
|
+
description: "",
|
|
87
|
+
public: false,
|
|
88
|
+
deleted: false,
|
|
89
|
+
creator: "",
|
|
90
|
+
admins: [],
|
|
91
|
+
moderators: [],
|
|
92
|
+
dataShapes: [],
|
|
93
|
+
questionTypes: [],
|
|
94
|
+
orchestration: { salt: "default" }
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
const userId = user.getUsername();
|
|
98
|
+
const salt = courseConfig.orchestration?.salt || "default_salt";
|
|
99
|
+
return {
|
|
100
|
+
user,
|
|
101
|
+
course,
|
|
102
|
+
userId,
|
|
103
|
+
courseConfig,
|
|
104
|
+
getEffectiveWeight(strategyId, learnable) {
|
|
105
|
+
return computeEffectiveWeight(learnable, userId, strategyId, salt);
|
|
106
|
+
},
|
|
107
|
+
getDeviation(strategyId) {
|
|
108
|
+
return computeDeviation(userId, strategyId, salt);
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
//#endregion
|
|
113
|
+
export { computeDeviation, computeEffectiveWeight, computeSpread, createOrchestrationContext };
|
|
114
|
+
|
|
115
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/core/orchestration/index.ts"],"sourcesContent":["import type { UserDBInterface } from '../interfaces/userDB';\nimport type { CourseDBInterface } from '../interfaces/courseDB';\nimport type { LearnableWeight } from '../types/contentNavigationStrategy';\nimport type { CourseConfig } from '@vue-skuilder/common';\nimport { logger } from '../../util/logger';\n\n// Re-export gradient and learning functions\nexport { aggregateOutcomesForGradient, computeStrategyGradient } from './gradient';\nexport {\n updateStrategyWeight,\n updateLearningState,\n runPeriodUpdate,\n getDefaultLearnableWeight,\n} from './learning';\nexport type { PeriodUpdateInput, PeriodUpdateResult } from './learning';\n\n// Re-export signal functions\nexport { computeOutcomeSignal, scoreAccuracyInZone } from './signal';\nexport type { SignalConfig } from './signal';\n\n// Re-export recording functions\nexport { recordUserOutcome } from './recording';\n\n// Re-export types\nexport type { GradientObservation, GradientResult, StrategyLearningState } from '../types/learningState';\nexport type { UserOutcomeRecord } from '../types/userOutcome';\n\n// ============================================================================\n// TYPES\n// ============================================================================\n\n/**\n * Context for orchestration decisions during a session.\n * \n * Provides access to user/course data and helper methods for determining\n * effective strategy weights based on the user's cohort assignment.\n */\nexport interface OrchestrationContext {\n user: UserDBInterface;\n course: CourseDBInterface;\n userId: string;\n courseConfig: CourseConfig;\n \n /**\n * Calculate the effective weight for a strategy for this user.\n * \n * Applies deviation based on the user's cohort assignment (derived from\n * userId, strategyId, and course salt).\n * \n * @param strategyId - Unique ID of the strategy\n * @param learnable - The strategy's learning configuration\n * @returns Effective weight multiplier (typically 0.1 - 3.0)\n */\n getEffectiveWeight(strategyId: string, learnable: LearnableWeight): number;\n\n /**\n * Get the deviation factor for this user/strategy.\n * Range [-1.0, 1.0].\n */\n getDeviation(strategyId: string): number;\n}\n\n// ============================================================================\n// DEVIATION LOGIC\n// ============================================================================\n\nconst MIN_SPREAD = 0.1;\nconst MAX_SPREAD = 0.5;\nconst MIN_WEIGHT = 0.1;\nconst MAX_WEIGHT = 3.0;\n\n/**\n * FNV-1a hash implementation for deterministic distribution.\n */\nfunction fnv1a(str: string): number {\n let hash = 2166136261;\n for (let i = 0; i < str.length; i++) {\n hash ^= str.charCodeAt(i);\n hash = Math.imul(hash, 16777619);\n }\n return hash >>> 0;\n}\n\n/**\n * Compute a user's deviation for a specific strategy.\n * \n * Returns a value in [-1, 1] that is:\n * 1. Deterministic for the same (user, strategy, salt) tuple\n * 2. Uniformly distributed across users\n * 3. Uncorrelated between different strategies (due to strategyId in hash)\n * 4. Rotatable by changing the salt\n * \n * @param userId - ID of the user\n * @param strategyId - ID of the strategy\n * @param salt - Random seed from course config\n * @returns Deviation factor between -1.0 and 1.0\n */\nexport function computeDeviation(userId: string, strategyId: string, salt: string): number {\n const input = `${userId}:${strategyId}:${salt}`;\n const hash = fnv1a(input);\n \n // Normalize 32-bit unsigned integer to [0, 1]\n const normalized = hash / 4294967296;\n \n // Map [0, 1] to [-1, 1]\n return (normalized * 2) - 1;\n}\n\n/**\n * Compute the exploration spread based on confidence.\n * \n * - Low confidence (0.0) -> Max spread (Explore broadly)\n * - High confidence (1.0) -> Min spread (Exploit known good weight)\n * \n * @param confidence - Confidence level 0-1\n * @returns Spread magnitude (half-width of the distribution)\n */\nexport function computeSpread(confidence: number): number {\n // Linear interpolation: confidence 0 -> MAX_SPREAD, confidence 1 -> MIN_SPREAD\n const clampedConfidence = Math.max(0, Math.min(1, confidence));\n return MAX_SPREAD - (clampedConfidence * (MAX_SPREAD - MIN_SPREAD));\n}\n\n/**\n * Calculate the effective weight for a strategy instance.\n * \n * Combines the learnable weight (peak) with the user's deviation and the\n * allowed spread (based on confidence).\n * \n * @param learnable - Strategy learning config\n * @param userId - User ID\n * @param strategyId - Strategy ID\n * @param salt - Course salt\n * @returns Effective weight multiplier\n */\nexport function computeEffectiveWeight(\n learnable: LearnableWeight,\n userId: string,\n strategyId: string,\n salt: string\n): number {\n const deviation = computeDeviation(userId, strategyId, salt);\n const spread = computeSpread(learnable.confidence);\n \n // Apply deviation: effective = weight + (deviation * spread * weight)\n // We scale the spread relative to the weight itself so it's proportional.\n // e.g. weight 2.0, deviation -0.5, spread 0.2 -> 2.0 + (-0.5 * 0.2 * 2.0) = 1.8\n const adjustment = deviation * spread * learnable.weight;\n \n const effective = learnable.weight + adjustment;\n \n // Clamp to sane bounds to prevent runaway weights or negative multipliers\n return Math.max(MIN_WEIGHT, Math.min(MAX_WEIGHT, effective));\n}\n\n// ============================================================================\n// CONTEXT FACTORY\n// ============================================================================\n\n/**\n * Create an orchestration context for a study session.\n * \n * Fetches necessary configuration to enable deterministic weight calculation.\n * \n * @param user - User DB interface\n * @param course - Course DB interface\n * @returns Initialized orchestration context\n */\nexport async function createOrchestrationContext(\n user: UserDBInterface,\n course: CourseDBInterface\n): Promise<OrchestrationContext> {\n let courseConfig: CourseConfig;\n try {\n courseConfig = await course.getCourseConfig();\n } catch (e) {\n logger.error(`[Orchestration] Failed to load course config: ${e}`);\n // Fallback stub if config load fails\n courseConfig = {\n name: 'Unknown',\n description: '',\n public: false,\n deleted: false,\n creator: '',\n admins: [],\n moderators: [],\n dataShapes: [],\n questionTypes: [],\n orchestration: { salt: 'default' },\n };\n }\n\n const userId = user.getUsername(); // Or user ID if available on interface\n const salt = courseConfig.orchestration?.salt || 'default_salt';\n\n return {\n user,\n course,\n userId,\n courseConfig,\n \n getEffectiveWeight(strategyId: string, learnable: LearnableWeight): number {\n return computeEffectiveWeight(learnable, userId, strategyId, salt);\n },\n\n getDeviation(strategyId: string): number {\n return computeDeviation(userId, strategyId, salt);\n }\n };\n}"],"mappings":";;;;;;;AAkEA,MAAM,aAAa;AACnB,MAAM,aAAa;AACnB,MAAM,aAAa;AACnB,MAAM,aAAa;;;;AAKnB,SAAS,MAAM,KAAqB;CAClC,IAAI,OAAO;AACX,MAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,UAAQ,IAAI,WAAW,EAAE;AACzB,SAAO,KAAK,KAAK,MAAM,SAAS;;AAElC,QAAO,SAAS;;;;;;;;;;;;;;;;AAiBlB,SAAgB,iBAAiB,QAAgB,YAAoB,MAAsB;AAQzF,QANa,MADC,GAAG,OAAO,GAAG,WAAW,GAAG,OAChB,GAGC,aAGL,IAAK;;;;;;;;;;;AAY5B,SAAgB,cAAc,YAA4B;AAGxD,QAAO,aADmB,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,WAAW,CAAC,IACpB,aAAa;;;;;;;;;;;;;;AAezD,SAAgB,uBACd,WACA,QACA,YACA,MACQ;CAOR,MAAM,aANY,iBAAiB,QAAQ,YAAY,KAAK,GAC7C,cAAc,UAAU,WAAW,GAKV,UAAU;CAElD,MAAM,YAAY,UAAU,SAAS;AAGrC,QAAO,KAAK,IAAI,YAAY,KAAK,IAAI,YAAY,UAAU,CAAC;;;;;;;;;;;AAgB9D,eAAsB,2BACpB,MACA,QAC+B;CAC/B,IAAI;AACJ,KAAI;AACF,iBAAe,MAAM,OAAO,iBAAiB;UACtC,GAAG;AACV,SAAO,MAAM,iDAAiD,IAAI;AAElE,iBAAe;GACb,MAAM;GACN,aAAa;GACb,QAAQ;GACR,SAAS;GACT,SAAS;GACT,QAAQ,EAAE;GACV,YAAY,EAAE;GACd,YAAY,EAAE;GACd,eAAe,EAAE;GACjB,eAAe,EAAE,MAAM,WAAW;GACnC;;CAGH,MAAM,SAAS,KAAK,aAAa;CACjC,MAAM,OAAO,aAAa,eAAe,QAAQ;AAEjD,QAAO;EACL;EACA;EACA;EACA;EAEA,mBAAmB,YAAoB,WAAoC;AACzE,UAAO,uBAAuB,WAAW,QAAQ,YAAY,KAAK;;EAGpE,aAAa,YAA4B;AACvC,UAAO,iBAAiB,QAAQ,YAAY,KAAK;;EAEpD"}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import "../../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
import { logger } from "../../util/logger.mjs";
|
|
3
|
+
import { DocType } from "../types/types-legacy.mjs";
|
|
4
|
+
import { DEFAULT_LEARNABLE_WEIGHT } from "../types/contentNavigationStrategy.mjs";
|
|
5
|
+
//#region src/core/orchestration/learning.ts
|
|
6
|
+
/** Minimum observations required before adjusting weight */
|
|
7
|
+
const MIN_OBSERVATIONS_FOR_UPDATE = 10;
|
|
8
|
+
/** How much to adjust weight per gradient unit */
|
|
9
|
+
const LEARNING_RATE = .1;
|
|
10
|
+
/** Maximum weight adjustment per update cycle */
|
|
11
|
+
const MAX_WEIGHT_DELTA = .3;
|
|
12
|
+
/** R-squared threshold below which we consider gradient unreliable */
|
|
13
|
+
const MIN_R_SQUARED_FOR_GRADIENT = .05;
|
|
14
|
+
/** Gradient magnitude below which we consider it "flat" (near optimal) */
|
|
15
|
+
const FLAT_GRADIENT_THRESHOLD = .02;
|
|
16
|
+
/** Maximum history entries to retain */
|
|
17
|
+
const MAX_HISTORY_LENGTH = 100;
|
|
18
|
+
/**
|
|
19
|
+
* Compute updated weight based on gradient result.
|
|
20
|
+
*
|
|
21
|
+
* The update logic:
|
|
22
|
+
* - Positive gradient: users with higher weight did better → increase weight
|
|
23
|
+
* - Negative gradient: users with higher weight did worse → decrease weight
|
|
24
|
+
* - Flat gradient: weight doesn't affect outcome → increase confidence
|
|
25
|
+
*
|
|
26
|
+
* @param current - Current learnable weight
|
|
27
|
+
* @param gradient - Computed gradient result
|
|
28
|
+
* @returns Updated learnable weight
|
|
29
|
+
*/
|
|
30
|
+
function updateStrategyWeight(current, gradient) {
|
|
31
|
+
if (gradient.sampleSize < MIN_OBSERVATIONS_FOR_UPDATE) {
|
|
32
|
+
logger.debug(`[Orchestration] Insufficient samples (${gradient.sampleSize} < ${MIN_OBSERVATIONS_FOR_UPDATE}), keeping current weight`);
|
|
33
|
+
return {
|
|
34
|
+
...current,
|
|
35
|
+
sampleSize: current.sampleSize + gradient.sampleSize
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
const isReliable = gradient.rSquared >= MIN_R_SQUARED_FOR_GRADIENT;
|
|
39
|
+
const isFlat = Math.abs(gradient.gradient) < FLAT_GRADIENT_THRESHOLD;
|
|
40
|
+
let newWeight = current.weight;
|
|
41
|
+
let newConfidence = current.confidence;
|
|
42
|
+
if (!isReliable || isFlat) {
|
|
43
|
+
const confidenceGain = .05 * (1 - current.confidence);
|
|
44
|
+
newConfidence = Math.min(1, current.confidence + confidenceGain);
|
|
45
|
+
logger.debug(`[Orchestration] Flat/unreliable gradient (|g|=${Math.abs(gradient.gradient).toFixed(4)}, R²=${gradient.rSquared.toFixed(4)}). Increasing confidence: ${current.confidence.toFixed(3)} → ${newConfidence.toFixed(3)}`);
|
|
46
|
+
} else {
|
|
47
|
+
let delta = gradient.gradient * LEARNING_RATE;
|
|
48
|
+
delta = Math.max(-MAX_WEIGHT_DELTA, Math.min(MAX_WEIGHT_DELTA, delta));
|
|
49
|
+
newWeight = current.weight + delta;
|
|
50
|
+
newWeight = Math.max(.1, Math.min(3, newWeight));
|
|
51
|
+
const confidenceGain = .02 * (1 - current.confidence);
|
|
52
|
+
newConfidence = Math.min(1, current.confidence + confidenceGain);
|
|
53
|
+
logger.debug(`[Orchestration] Adjusting weight: ${current.weight.toFixed(3)} → ${newWeight.toFixed(3)} (gradient=${gradient.gradient.toFixed(4)}, delta=${delta.toFixed(4)})`);
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
weight: newWeight,
|
|
57
|
+
confidence: newConfidence,
|
|
58
|
+
sampleSize: current.sampleSize + gradient.sampleSize
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Create or update a StrategyLearningState document.
|
|
63
|
+
*
|
|
64
|
+
* @param courseId - Course ID
|
|
65
|
+
* @param strategyId - Strategy ID
|
|
66
|
+
* @param currentWeight - Current learned weight
|
|
67
|
+
* @param gradient - Gradient result from recent computation
|
|
68
|
+
* @param existing - Existing learning state (if any)
|
|
69
|
+
* @returns Updated learning state document
|
|
70
|
+
*/
|
|
71
|
+
function updateLearningState(courseId, strategyId, currentWeight, gradient, existing) {
|
|
72
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
73
|
+
const id = `STRATEGY_LEARNING_STATE::${courseId}::${strategyId}`;
|
|
74
|
+
const historyEntry = {
|
|
75
|
+
timestamp: now,
|
|
76
|
+
weight: currentWeight.weight,
|
|
77
|
+
confidence: currentWeight.confidence,
|
|
78
|
+
gradient: gradient.gradient
|
|
79
|
+
};
|
|
80
|
+
let history = existing?.history ?? [];
|
|
81
|
+
history = [...history, historyEntry];
|
|
82
|
+
if (history.length > MAX_HISTORY_LENGTH) history = history.slice(history.length - MAX_HISTORY_LENGTH);
|
|
83
|
+
return {
|
|
84
|
+
_id: id,
|
|
85
|
+
_rev: existing?._rev,
|
|
86
|
+
docType: DocType.STRATEGY_LEARNING_STATE,
|
|
87
|
+
courseId,
|
|
88
|
+
strategyId,
|
|
89
|
+
currentWeight,
|
|
90
|
+
regression: {
|
|
91
|
+
gradient: gradient.gradient,
|
|
92
|
+
intercept: gradient.intercept,
|
|
93
|
+
rSquared: gradient.rSquared,
|
|
94
|
+
sampleSize: gradient.sampleSize,
|
|
95
|
+
computedAt: now
|
|
96
|
+
},
|
|
97
|
+
history,
|
|
98
|
+
updatedAt: now
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Run a period update for a single strategy.
|
|
103
|
+
*
|
|
104
|
+
* This function:
|
|
105
|
+
* 1. Takes the computed gradient
|
|
106
|
+
* 2. Computes the new weight
|
|
107
|
+
* 3. Generates the updated learning state
|
|
108
|
+
*
|
|
109
|
+
* Note: Actual persistence (updating strategy doc, saving learning state)
|
|
110
|
+
* must be done by the caller with appropriate DB access.
|
|
111
|
+
*
|
|
112
|
+
* @param input - Update input data
|
|
113
|
+
* @returns Update result with new weight and learning state
|
|
114
|
+
*/
|
|
115
|
+
function runPeriodUpdate(input) {
|
|
116
|
+
const { courseId, strategyId, currentWeight, gradient, existingState } = input;
|
|
117
|
+
logger.info(`[Orchestration] Running period update for strategy ${strategyId} (${gradient.sampleSize} observations)`);
|
|
118
|
+
const newWeight = updateStrategyWeight(currentWeight, gradient);
|
|
119
|
+
const updated = newWeight.weight !== currentWeight.weight;
|
|
120
|
+
const learningState = updateLearningState(courseId, strategyId, newWeight, gradient, existingState);
|
|
121
|
+
logger.info(`[Orchestration] Period update complete for ${strategyId}: weight ${currentWeight.weight.toFixed(3)} → ${newWeight.weight.toFixed(3)}, confidence ${currentWeight.confidence.toFixed(3)} → ${newWeight.confidence.toFixed(3)}`);
|
|
122
|
+
return {
|
|
123
|
+
strategyId,
|
|
124
|
+
previousWeight: currentWeight,
|
|
125
|
+
newWeight,
|
|
126
|
+
gradient,
|
|
127
|
+
learningState,
|
|
128
|
+
updated
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Create a default LearnableWeight for strategies that don't have one.
|
|
133
|
+
*/
|
|
134
|
+
function getDefaultLearnableWeight() {
|
|
135
|
+
return { ...DEFAULT_LEARNABLE_WEIGHT };
|
|
136
|
+
}
|
|
137
|
+
//#endregion
|
|
138
|
+
export { getDefaultLearnableWeight, runPeriodUpdate, updateLearningState, updateStrategyWeight };
|
|
139
|
+
|
|
140
|
+
//# sourceMappingURL=learning.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"learning.mjs","names":[],"sources":["../../../src/core/orchestration/learning.ts"],"sourcesContent":["import { LearnableWeight, DEFAULT_LEARNABLE_WEIGHT } from '../types/contentNavigationStrategy';\nimport { StrategyLearningState, GradientResult } from '../types/learningState';\nimport { DocType } from '../types/types-legacy';\nimport { logger } from '../../util/logger';\n\n// ============================================================================\n// CONSTANTS\n// ============================================================================\n\n/** Minimum observations required before adjusting weight */\nconst MIN_OBSERVATIONS_FOR_UPDATE = 10;\n\n/** How much to adjust weight per gradient unit */\nconst LEARNING_RATE = 0.1;\n\n/** Maximum weight adjustment per update cycle */\nconst MAX_WEIGHT_DELTA = 0.3;\n\n/** R-squared threshold below which we consider gradient unreliable */\nconst MIN_R_SQUARED_FOR_GRADIENT = 0.05;\n\n/** Gradient magnitude below which we consider it \"flat\" (near optimal) */\nconst FLAT_GRADIENT_THRESHOLD = 0.02;\n\n/** Maximum history entries to retain */\nconst MAX_HISTORY_LENGTH = 100;\n\n// ============================================================================\n// WEIGHT UPDATE\n// ============================================================================\n\n/**\n * Compute updated weight based on gradient result.\n *\n * The update logic:\n * - Positive gradient: users with higher weight did better → increase weight\n * - Negative gradient: users with higher weight did worse → decrease weight\n * - Flat gradient: weight doesn't affect outcome → increase confidence\n *\n * @param current - Current learnable weight\n * @param gradient - Computed gradient result\n * @returns Updated learnable weight\n */\nexport function updateStrategyWeight(\n current: LearnableWeight,\n gradient: GradientResult\n): LearnableWeight {\n // Not enough data to make reliable updates\n if (gradient.sampleSize < MIN_OBSERVATIONS_FOR_UPDATE) {\n logger.debug(\n `[Orchestration] Insufficient samples (${gradient.sampleSize} < ${MIN_OBSERVATIONS_FOR_UPDATE}), ` +\n `keeping current weight`\n );\n return {\n ...current,\n sampleSize: current.sampleSize + gradient.sampleSize,\n };\n }\n\n // Check if gradient is reliable (R² threshold)\n const isReliable = gradient.rSquared >= MIN_R_SQUARED_FOR_GRADIENT;\n const isFlat = Math.abs(gradient.gradient) < FLAT_GRADIENT_THRESHOLD;\n\n let newWeight = current.weight;\n let newConfidence = current.confidence;\n\n if (!isReliable || isFlat) {\n // Gradient is unreliable or flat - we're likely near optimal\n // Increase confidence (narrow the exploration spread)\n const confidenceGain = 0.05 * (1 - current.confidence);\n newConfidence = Math.min(1.0, current.confidence + confidenceGain);\n\n logger.debug(\n `[Orchestration] Flat/unreliable gradient (|g|=${Math.abs(gradient.gradient).toFixed(4)}, ` +\n `R²=${gradient.rSquared.toFixed(4)}). Increasing confidence: ${current.confidence.toFixed(3)} → ${newConfidence.toFixed(3)}`\n );\n } else {\n // Reliable gradient - adjust weight in gradient direction\n // Scale by learning rate and clamp to max delta\n let delta = gradient.gradient * LEARNING_RATE;\n delta = Math.max(-MAX_WEIGHT_DELTA, Math.min(MAX_WEIGHT_DELTA, delta));\n\n newWeight = current.weight + delta;\n\n // Clamp weight to reasonable bounds\n newWeight = Math.max(0.1, Math.min(3.0, newWeight));\n\n // Slight confidence increase for having made an observation\n const confidenceGain = 0.02 * (1 - current.confidence);\n newConfidence = Math.min(1.0, current.confidence + confidenceGain);\n\n logger.debug(\n `[Orchestration] Adjusting weight: ${current.weight.toFixed(3)} → ${newWeight.toFixed(3)} ` +\n `(gradient=${gradient.gradient.toFixed(4)}, delta=${delta.toFixed(4)})`\n );\n }\n\n return {\n weight: newWeight,\n confidence: newConfidence,\n sampleSize: current.sampleSize + gradient.sampleSize,\n };\n}\n\n// ============================================================================\n// LEARNING STATE MANAGEMENT\n// ============================================================================\n\n/**\n * Create or update a StrategyLearningState document.\n *\n * @param courseId - Course ID\n * @param strategyId - Strategy ID\n * @param currentWeight - Current learned weight\n * @param gradient - Gradient result from recent computation\n * @param existing - Existing learning state (if any)\n * @returns Updated learning state document\n */\nexport function updateLearningState(\n courseId: string,\n strategyId: string,\n currentWeight: LearnableWeight,\n gradient: GradientResult,\n existing?: StrategyLearningState\n): StrategyLearningState {\n const now = new Date().toISOString();\n const id = `STRATEGY_LEARNING_STATE::${courseId}::${strategyId}`;\n\n // Build history entry\n const historyEntry = {\n timestamp: now,\n weight: currentWeight.weight,\n confidence: currentWeight.confidence,\n gradient: gradient.gradient,\n };\n\n // Append to existing history or start fresh\n let history = existing?.history ?? [];\n history = [...history, historyEntry];\n\n // Trim history if too long\n if (history.length > MAX_HISTORY_LENGTH) {\n history = history.slice(history.length - MAX_HISTORY_LENGTH);\n }\n\n const state: StrategyLearningState = {\n _id: id,\n _rev: existing?._rev,\n docType: DocType.STRATEGY_LEARNING_STATE,\n courseId,\n strategyId,\n currentWeight,\n regression: {\n gradient: gradient.gradient,\n intercept: gradient.intercept,\n rSquared: gradient.rSquared,\n sampleSize: gradient.sampleSize,\n computedAt: now,\n },\n history,\n updatedAt: now,\n };\n\n return state;\n}\n\n// ============================================================================\n// PERIOD UPDATE ORCHESTRATOR\n// ============================================================================\n\n/**\n * Input data for running a period update on a single strategy.\n */\nexport interface PeriodUpdateInput {\n courseId: string;\n strategyId: string;\n currentWeight: LearnableWeight;\n gradient: GradientResult;\n existingState?: StrategyLearningState;\n}\n\n/**\n * Result of a period update for a single strategy.\n */\nexport interface PeriodUpdateResult {\n strategyId: string;\n previousWeight: LearnableWeight;\n newWeight: LearnableWeight;\n gradient: GradientResult;\n learningState: StrategyLearningState;\n updated: boolean;\n}\n\n/**\n * Run a period update for a single strategy.\n *\n * This function:\n * 1. Takes the computed gradient\n * 2. Computes the new weight\n * 3. Generates the updated learning state\n *\n * Note: Actual persistence (updating strategy doc, saving learning state)\n * must be done by the caller with appropriate DB access.\n *\n * @param input - Update input data\n * @returns Update result with new weight and learning state\n */\nexport function runPeriodUpdate(input: PeriodUpdateInput): PeriodUpdateResult {\n const { courseId, strategyId, currentWeight, gradient, existingState } = input;\n\n logger.info(\n `[Orchestration] Running period update for strategy ${strategyId} ` +\n `(${gradient.sampleSize} observations)`\n );\n\n // Compute new weight\n const newWeight = updateStrategyWeight(currentWeight, gradient);\n const updated = newWeight.weight !== currentWeight.weight;\n\n // Generate learning state\n const learningState = updateLearningState(\n courseId,\n strategyId,\n newWeight,\n gradient,\n existingState\n );\n\n logger.info(\n `[Orchestration] Period update complete for ${strategyId}: ` +\n `weight ${currentWeight.weight.toFixed(3)} → ${newWeight.weight.toFixed(3)}, ` +\n `confidence ${currentWeight.confidence.toFixed(3)} → ${newWeight.confidence.toFixed(3)}`\n );\n\n return {\n strategyId,\n previousWeight: currentWeight,\n newWeight,\n gradient,\n learningState,\n updated,\n };\n}\n\n/**\n * Create a default LearnableWeight for strategies that don't have one.\n */\nexport function getDefaultLearnableWeight(): LearnableWeight {\n return { ...DEFAULT_LEARNABLE_WEIGHT };\n}\n"],"mappings":"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"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import "../../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
import { logger } from "../../util/logger.mjs";
|
|
3
|
+
import { DocType } from "../types/types-legacy.mjs";
|
|
4
|
+
import { computeOutcomeSignal } from "./signal.mjs";
|
|
5
|
+
//#region src/core/orchestration/recording.ts
|
|
6
|
+
/**
|
|
7
|
+
* Records a learning outcome for a specific period of time.
|
|
8
|
+
*
|
|
9
|
+
* This function:
|
|
10
|
+
* 1. Computes a scalar "success" signal from the provided question records
|
|
11
|
+
* 2. Re-computes the deviations that were active for this user/course
|
|
12
|
+
* 3. Persists a UserOutcomeRecord to the user's database
|
|
13
|
+
*
|
|
14
|
+
* This record is later used by the optimization job to correlate
|
|
15
|
+
* deviations with outcomes (Evolutionary Orchestration).
|
|
16
|
+
*
|
|
17
|
+
* @param context - Orchestration context (user, course, etc.)
|
|
18
|
+
* @param periodStart - ISO timestamp of period start
|
|
19
|
+
* @param periodEnd - ISO timestamp of period end (now)
|
|
20
|
+
* @param records - Question records generated during this period
|
|
21
|
+
* @param activeStrategyIds - IDs of strategies active in this course
|
|
22
|
+
* @param eloStart - User's ELO at start of period (optional)
|
|
23
|
+
* @param eloEnd - User's ELO at end of period (optional)
|
|
24
|
+
* @param config - Optional configuration for signal computation
|
|
25
|
+
*/
|
|
26
|
+
async function recordUserOutcome(context, periodStart, periodEnd, records, activeStrategyIds, eloStart = 0, eloEnd = 0, config) {
|
|
27
|
+
const { user, course, userId } = context;
|
|
28
|
+
const courseId = course.getCourseID();
|
|
29
|
+
const outcomeValue = computeOutcomeSignal(records, config);
|
|
30
|
+
if (outcomeValue === null) {
|
|
31
|
+
logger.debug(`[Orchestration] No outcome signal computed for ${userId} (insufficient data). Skipping record.`);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const deviations = {};
|
|
35
|
+
for (const strategyId of activeStrategyIds) deviations[strategyId] = context.getDeviation(strategyId);
|
|
36
|
+
const id = `USER_OUTCOME::${courseId}::${userId}::${periodEnd}`;
|
|
37
|
+
const record = {
|
|
38
|
+
_id: id,
|
|
39
|
+
docType: DocType.USER_OUTCOME,
|
|
40
|
+
courseId,
|
|
41
|
+
userId,
|
|
42
|
+
periodStart,
|
|
43
|
+
periodEnd,
|
|
44
|
+
outcomeValue,
|
|
45
|
+
deviations,
|
|
46
|
+
metadata: {
|
|
47
|
+
sessionsCount: 1,
|
|
48
|
+
cardsSeen: records.length,
|
|
49
|
+
eloStart,
|
|
50
|
+
eloEnd,
|
|
51
|
+
signalType: "accuracy_in_zone"
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
try {
|
|
55
|
+
await user.putUserOutcome(record);
|
|
56
|
+
logger.debug(`[Orchestration] Recorded outcome ${outcomeValue.toFixed(3)} for ${userId} (doc: ${id})`);
|
|
57
|
+
} catch (e) {
|
|
58
|
+
logger.error(`[Orchestration] Failed to record outcome: ${e}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
//#endregion
|
|
62
|
+
export { recordUserOutcome };
|
|
63
|
+
|
|
64
|
+
//# sourceMappingURL=recording.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recording.mjs","names":[],"sources":["../../../src/core/orchestration/recording.ts"],"sourcesContent":["import { OrchestrationContext } from './index';\nimport { computeOutcomeSignal, SignalConfig } from './signal';\nimport { UserOutcomeRecord } from '../types/userOutcome';\nimport { DocType, QuestionRecord } from '../types/types-legacy';\nimport { logger } from '../../util/logger';\n\n/**\n * Records a learning outcome for a specific period of time.\n *\n * This function:\n * 1. Computes a scalar \"success\" signal from the provided question records\n * 2. Re-computes the deviations that were active for this user/course\n * 3. Persists a UserOutcomeRecord to the user's database\n *\n * This record is later used by the optimization job to correlate\n * deviations with outcomes (Evolutionary Orchestration).\n *\n * @param context - Orchestration context (user, course, etc.)\n * @param periodStart - ISO timestamp of period start\n * @param periodEnd - ISO timestamp of period end (now)\n * @param records - Question records generated during this period\n * @param activeStrategyIds - IDs of strategies active in this course\n * @param eloStart - User's ELO at start of period (optional)\n * @param eloEnd - User's ELO at end of period (optional)\n * @param config - Optional configuration for signal computation\n */\nexport async function recordUserOutcome(\n context: OrchestrationContext,\n periodStart: string,\n periodEnd: string,\n records: QuestionRecord[],\n activeStrategyIds: string[],\n eloStart: number = 0,\n eloEnd: number = 0,\n config?: SignalConfig\n): Promise<void> {\n const { user, course, userId } = context;\n const courseId = course.getCourseID();\n\n // 1. Compute Signal\n // If we have no records, we can't determine an outcome.\n const outcomeValue = computeOutcomeSignal(records, config);\n\n if (outcomeValue === null) {\n logger.debug(\n `[Orchestration] No outcome signal computed for ${userId} (insufficient data). Skipping record.`\n );\n return;\n }\n\n // 2. Capture Deviations\n // We re-compute the deterministic deviations for all active strategies.\n // This tells the learning algorithm \"what parameter adjustments were active\n // when this outcome was achieved\".\n const deviations: Record<string, number> = {};\n for (const strategyId of activeStrategyIds) {\n deviations[strategyId] = context.getDeviation(strategyId);\n }\n\n // 3. Construct Record\n // ID format: USER_OUTCOME::{courseId}::{userId}::{periodEnd}\n // This ensures uniqueness per user/course/time-period.\n const id = `USER_OUTCOME::${courseId}::${userId}::${periodEnd}`;\n\n const record: UserOutcomeRecord = {\n _id: id,\n docType: DocType.USER_OUTCOME,\n courseId,\n userId,\n periodStart,\n periodEnd,\n outcomeValue,\n deviations,\n metadata: {\n sessionsCount: 1, // Assumes recording is triggered per-session currently\n cardsSeen: records.length,\n eloStart,\n eloEnd,\n signalType: 'accuracy_in_zone',\n },\n };\n\n // 4. Persist\n try {\n await user.putUserOutcome(record);\n logger.debug(\n `[Orchestration] Recorded outcome ${outcomeValue.toFixed(3)} for ${userId} (doc: ${id})`\n );\n } catch (e) {\n logger.error(`[Orchestration] Failed to record outcome: ${e}`);\n }\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,eAAsB,kBACpB,SACA,aACA,WACA,SACA,mBACA,WAAmB,GACnB,SAAiB,GACjB,QACe;CACf,MAAM,EAAE,MAAM,QAAQ,WAAW;CACjC,MAAM,WAAW,OAAO,aAAa;CAIrC,MAAM,eAAe,qBAAqB,SAAS,OAAO;AAE1D,KAAI,iBAAiB,MAAM;AACzB,SAAO,MACL,kDAAkD,OAAO,wCAC1D;AACD;;CAOF,MAAM,aAAqC,EAAE;AAC7C,MAAK,MAAM,cAAc,kBACvB,YAAW,cAAc,QAAQ,aAAa,WAAW;CAM3D,MAAM,KAAK,iBAAiB,SAAS,IAAI,OAAO,IAAI;CAEpD,MAAM,SAA4B;EAChC,KAAK;EACL,SAAS,QAAQ;EACjB;EACA;EACA;EACA;EACA;EACA;EACA,UAAU;GACR,eAAe;GACf,WAAW,QAAQ;GACnB;GACA;GACA,YAAY;GACb;EACF;AAGD,KAAI;AACF,QAAM,KAAK,eAAe,OAAO;AACjC,SAAO,MACL,oCAAoC,aAAa,QAAQ,EAAE,CAAC,OAAO,OAAO,SAAS,GAAG,GACvF;UACM,GAAG;AACV,SAAO,MAAM,6CAA6C,IAAI"}
|