@vue-skuilder/standalone-ui 0.2.34 → 0.2.35
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/assets/{AdminLearnerView-Cfzt4Vei.css → AdminLearnerView-CMwKoROX.css} +1 -1
- package/dist/assets/AdminLearnerView-DkmBo1K4.js +21 -0
- package/dist/assets/AdminLearnerView-DkmBo1K4.js.map +1 -0
- package/dist/assets/{TagViewer-CsJPYLLJ.js → TagViewer-BIh942gd.js} +2 -2
- package/dist/assets/{TagViewer-CsJPYLLJ.js.map → TagViewer-BIh942gd.js.map} +1 -1
- package/dist/assets/{common-ui.es-U-dEx724.js → common-ui.es-CV5W--Bx.js} +1 -1
- package/dist/assets/{common-ui.es-vPdOOHv3.js → common-ui.es-n5i6_PmR.js} +4 -4
- package/dist/assets/{common-ui.es-vPdOOHv3.js.map → common-ui.es-n5i6_PmR.js.map} +1 -1
- package/dist/assets/{dist-BaF-5MhF.js → dist-CwGL17md.js} +2 -2
- package/dist/assets/{dist-BaF-5MhF.js.map → dist-CwGL17md.js.map} +1 -1
- package/dist/assets/{index-pyKdwi5m.js → index-CrxkJjnE.js} +5 -5
- package/dist/assets/{index-pyKdwi5m.js.map → index-CrxkJjnE.js.map} +1 -1
- package/dist/index.html +3 -3
- package/dist-lib/questions.cjs.js +1 -1
- package/dist-lib/questions.cjs.js.map +1 -1
- package/dist-lib/questions.mjs +1 -1
- package/dist-lib/questions.mjs.map +1 -1
- package/package.json +6 -6
- package/dist/assets/AdminLearnerView-BuTqWHqE.js +0 -4
- package/dist/assets/AdminLearnerView-BuTqWHqE.js.map +0 -1
package/dist/index.html
CHANGED
|
@@ -9,13 +9,13 @@
|
|
|
9
9
|
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"
|
|
10
10
|
rel="stylesheet"
|
|
11
11
|
/>
|
|
12
|
-
<script type="module" crossorigin src="/assets/index-
|
|
12
|
+
<script type="module" crossorigin src="/assets/index-CrxkJjnE.js"></script>
|
|
13
13
|
<link rel="modulepreload" crossorigin href="/assets/dist-D75GbuPa.js">
|
|
14
|
-
<link rel="modulepreload" crossorigin href="/assets/dist-
|
|
14
|
+
<link rel="modulepreload" crossorigin href="/assets/dist-CwGL17md.js">
|
|
15
15
|
<link rel="modulepreload" crossorigin href="/assets/vue.runtime.esm-bundler-CkuGwaik.js">
|
|
16
16
|
<link rel="modulepreload" crossorigin href="/assets/MarkdownRenderer-U_iPiA2x-DBpIWMFD.js">
|
|
17
17
|
<link rel="modulepreload" crossorigin href="/assets/vue-router-Cao8UAh1.js">
|
|
18
|
-
<link rel="modulepreload" crossorigin href="/assets/common-ui.es-
|
|
18
|
+
<link rel="modulepreload" crossorigin href="/assets/common-ui.es-n5i6_PmR.js">
|
|
19
19
|
<link rel="stylesheet" crossorigin href="/assets/common-ui-BY2Ut5jf.css">
|
|
20
20
|
<link rel="stylesheet" crossorigin href="/assets/index-Ci9rmWrX.css">
|
|
21
21
|
</head>
|
|
@@ -350,7 +350,7 @@ Example:
|
|
|
350
350
|
window.skuilder.pipeline.showLastRun()
|
|
351
351
|
window.skuilder.pipeline.showRun(1)
|
|
352
352
|
await window.skuilder.pipeline.diagnoseCardSpace()
|
|
353
|
-
`)}},mountPipelineDebugger()}}),SrsDebugger_exports={},__export(SrsDebugger_exports,{captureSrsBacklog:()=>captureSrsBacklog,clearSrsBacklogDebug:()=>clearSrsBacklogDebug,getSrsBacklogDebug:()=>getSrsBacklogDebug,noteReviewPressure:()=>noteReviewPressure}),init_SrsDebugger=__esm({"src/core/navigators/SrsDebugger.ts"(){"use strict";snapshots=new Map}}),StrategyPressureDebugger_exports={},__export(StrategyPressureDebugger_exports,{captureStrategyPressure:()=>captureStrategyPressure,clearStrategyPressureDebug:()=>clearStrategyPressureDebug,getStrategyPressureDebug:()=>getStrategyPressureDebug}),init_StrategyPressureDebugger=__esm({"src/core/navigators/StrategyPressureDebugger.ts"(){"use strict";snapshots2=new Map}}),CompositeGenerator_exports={},__export(CompositeGenerator_exports,{AggregationMode:()=>AggregationMode,default:()=>CompositeGenerator}),init_CompositeGenerator=__esm({"src/core/navigators/generators/CompositeGenerator.ts"(){"use strict";init_navigators(),init_logger(),AggregationMode=(t=>(t.MAX=`max`,t.AVERAGE=`average`,t.FREQUENCY_BOOST=`frequencyBoost`,t))(AggregationMode||{}),DEFAULT_AGGREGATION_MODE=`frequencyBoost`,FREQUENCY_BOOST_FACTOR=.1,CompositeGenerator=class _CompositeGenerator extends ContentNavigator{constructor(t,c=DEFAULT_AGGREGATION_MODE){if(super(),_defineProperty$2(this,`name`,`Composite Generator`),_defineProperty$2(this,`generators`,void 0),_defineProperty$2(this,`aggregationMode`,void 0),this.generators=t,this.aggregationMode=c,t.length===0)throw Error(`CompositeGenerator requires at least one generator`);logger.debug(`[CompositeGenerator] Created with ${t.length} generators, mode: ${c}`)}static async fromStrategies(t,c,u,d=DEFAULT_AGGREGATION_MODE){return new _CompositeGenerator(await Promise.all(u.map(u=>ContentNavigator.create(t,c,u))),d)}async getWeightedCards(t,c){if(!c)throw Error(`CompositeGenerator.getWeightedCards requires a GeneratorContext. It should be called via Pipeline, not directly.`);let u=await Promise.all(this.generators.map(u=>u.getWeightedCards(t,c))),d=[];u.forEach((t,c)=>{let u=t.cards,m=this.generators[c].name||`Generator ${c}`,g=u.filter(t=>t.provenance[0]?.reason?.includes(`new card`)),b=u.filter(t=>t.provenance[0]?.reason?.includes(`review`));if(u.length>0){let t=Math.max(...u.map(t=>t.score)).toFixed(2),c=[];g.length>0&&c.push(`${g.length} new`),b.length>0&&c.push(`${b.length} reviews`);let S=c.length>0?c.join(`, `):`${u.length} cards`;d.push(`${m}: ${S} (top: ${t})`)}else d.push(`${m}: 0 cards`)}),logger.info(`[Composite] Generator breakdown: ${d.join(` | `)}`);let m=new Map;u.forEach((t,u)=>{let d=t.cards,g=this.generators[u],b=g.learnable?.weight??1,S;if(g.learnable&&!g.staticWeight&&c.orchestration){let t=g.strategyId;t&&(b=c.orchestration.getEffectiveWeight(t,g.learnable),S=c.orchestration.getDeviation(t))}for(let t of d){t.provenance.length>0&&(t.provenance[0].effectiveWeight=b,t.provenance[0].deviation=S);let c=m.get(t.cardId)||[];c.push({card:t,weight:b}),m.set(t.cardId,c)}});let g=[];for(let[,t]of m){let c=t.map(t=>t.card),u=this.aggregateScores(t),d=Math.max(0,u),m=c.flatMap(t=>t.provenance),b=c[0].score,S=d>b?`boosted`:d<b?`penalized`:`passed`,C=this.buildAggregationReason(t,d);g.push({...c[0],score:d,provenance:[...m,{strategy:`composite`,strategyName:`Composite Generator`,strategyId:`COMPOSITE_GENERATOR`,action:S,score:d,reason:C}]})}return{cards:g.sort((t,c)=>c.score-t.score).slice(0,t),hints:mergeHints(u.map(t=>t.hints))}}buildAggregationReason(t,c){let u=t.map(t=>t.card),d=u.length,m=u.map(t=>t.score.toFixed(2)).join(`, `);if(d===1){let u=Math.abs(t[0].weight-1)>.001?` (w=${t[0].weight.toFixed(2)})`:``;return`Single generator, score ${c.toFixed(2)}${u}`}let g=u.map(t=>t.provenance[0]?.strategy||`unknown`).join(`, `);switch(this.aggregationMode){case`max`:return`Max of ${d} generators (${g}): scores [${m}] \u2192 ${c.toFixed(2)}`;case`average`:return`Weighted Avg of ${d} generators (${g}): scores [${m}] \u2192 ${c.toFixed(2)}`;case`frequencyBoost`:{let u=t.reduce((t,c)=>t+c.weight,0),m=t.reduce((t,c)=>t+c.card.score*c.weight,0),b=u>0?m/u:0,S=1+FREQUENCY_BOOST_FACTOR*(d-1);return`Frequency boost from ${d} generators (${g}): w-avg ${b.toFixed(2)} \xD7 ${S.toFixed(2)} \u2192 ${c.toFixed(2)}`}default:return`Aggregated from ${d} generators: ${c.toFixed(2)}`}}aggregateScores(t){let c=t.map(t=>t.card.score);switch(this.aggregationMode){case`max`:return Math.max(...c);case`average`:{let c=t.reduce((t,c)=>t+c.weight,0);return c===0?0:t.reduce((t,c)=>t+c.card.score*c.weight,0)/c}case`frequencyBoost`:{let c=t.reduce((t,c)=>t+c.weight,0),u=t.reduce((t,c)=>t+c.card.score*c.weight,0);return(c>0?u/c:0)*(1+FREQUENCY_BOOST_FACTOR*(t.length-1))}default:return c[0]}}}}}),elo_exports={},__export(elo_exports,{default:()=>ELONavigator}),init_elo=__esm({"src/core/navigators/generators/elo.ts"(){"use strict";init_navigators(),init_logger(),ELONavigator=class extends ContentNavigator{constructor(t,c,u){super(t,c,u),_defineProperty$2(this,`name`,void 0),this.name=u?.name||`ELO`}async getWeightedCards(t,c){let u;u=c?.userElo===void 0?toCourseElo((await this.user.getCourseRegDoc(this.course.getCourseID())).elo).global.score:c.userElo;let[d,m]=await Promise.all([this.user.getActiveCards(),this.user.getSeenCards(this.course.getCourseID()).catch(()=>[])]),g=new Set([...d.map(t=>t.cardID),...m]),b=(await this.course.getCardsCenteredAtELO({limit:t,elo:`user`},t=>!g.has(t.cardID))).map(t=>({...t,status:`new`})).map(t=>{let c=t.elo??1e3,d=Math.abs(c-u),m=.5+.5*Math.random();return{cardId:t.cardID,courseId:t.courseID,score:m,cardElo:c,provenance:[{strategy:`elo`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-ELO-default`,action:`generated`,score:m,reason:`new card near learner ELO: distance ${Math.round(d)} (card: ${Math.round(c)}, user: ${Math.round(u)}), jitter ${m.toFixed(3)}`}]}});b.sort((t,c)=>c.score-t.score);let S=b.slice(0,t);if(S.length>0){let t=S.slice(0,3).map(t=>t.score.toFixed(2)).join(`, `);logger.info(`[ELO] Course ${this.course.getCourseID()}: ${S.length} new cards (top scores: ${t})`)}else logger.info(`[ELO] Course ${this.course.getCourseID()}: No new cards available`);return{cards:S}}}}}),generators_exports={},init_generators=__esm({"src/core/navigators/generators/index.ts"(){"use strict";}}),prescribed_exports={},__export(prescribed_exports,{default:()=>PrescribedCardsGenerator,unmetIntroExposeTags:()=>unmetIntroExposeTags}),init_prescribed=__esm({"src/core/navigators/generators/prescribed.ts"(){"use strict";init_navigators(),init_StrategyPressureDebugger(),init_logger(),DEFAULT_FRESHNESS_WINDOW=3,DEFAULT_MAX_DIRECT_PER_RUN=3,DEFAULT_MAX_SUPPORT_PER_RUN=3,DEFAULT_HIERARCHY_DEPTH=2,DEFAULT_MIN_COUNT=3,DEFAULT_PRACTICE_MIN_COUNT=3,DEFAULT_MAX_PRACTICE_PER_RUN=4,BASE_TARGET_SCORE=1,BASE_SUPPORT_SCORE=.8,DISCOVERED_SUPPORT_SCORE=12,BASE_PRACTICE_SCORE=1,PRACTICE_BASE_MULT=2,MAX_PRACTICE_MULTIPLIER=4,PRACTICE_STALENESS_BUMP_PER_DAY=.5,MAX_TARGET_MULTIPLIER=8,MAX_SUPPORT_MULTIPLIER=4,PRESCRIBED_DEBUG_VERSION=`testversion-prescribed-v3`,PrescribedCardsGenerator=class extends ContentNavigator{constructor(t,c,u){super(t,c,u),_defineProperty$2(this,`name`,void 0),_defineProperty$2(this,`config`,void 0),this.name=u.name||`Prescribed Cards`,this.config=this.parseConfig(u.serializedData),logger.debug(`[Prescribed] Initialized with ${this.config.groups.length} groups and ${this.config.groups.reduce((t,c)=>t+c.targetCardIds.length,0)} targets`)}get strategyKey(){return`PrescribedProgress`}async getWeightedCards(t,c){if(this.config.groups.length===0||t<=0)return{cards:[]};let u=this.course.getCourseID(),d=await this.user.getActiveCards(),m=new Set(d.map(t=>t.cardID)),g=await this.user.getSeenCards(u).catch(()=>[]),b=new Set(g),S=await this.getStrategyState()??{updatedAt:isoNow(),groups:{}},C=await this.loadHierarchyConfigs(),w=await this.user.getCourseRegDoc(u).catch(()=>null),T=typeof w?.elo==`number`?w.elo:w?.elo?.global?.score??c?.userElo??1e3,E=typeof w?.elo==`number`?{}:w?.elo?.tags??{},D=dedupe(this.config.groups.flatMap(t=>t.targetCardIds)),O=dedupe(this.config.groups.flatMap(t=>t.supportCardIds??[])),xr=dedupe([...D,...O]),Sr=xr.length>0?await this.course.getAppliedTagsBatch(xr):new Map,Cr=await this.course.getCourseTagStubs().catch(()=>({rows:[],offset:0,total_rows:0})),wr=new Map;for(let t of Cr.rows??[]){let c=t.doc;c?.name&&Array.isArray(c.taggedCards)&&wr.set(c.name,[...c.taggedCards])}let Tr={updatedAt:isoNow(),groups:{}},Er=[],Dr=new Set,Or=[],kr=S.practiceDebt??{},Ar={},jr=new Map;for(let t of this.config.groups){let c=this.buildGroupRuntimeState({group:t,priorState:S.groups[t.id],activeIds:m,seenIds:b,tagsByCard:Sr,cardsByTag:wr,hierarchyConfigs:C,userTagElo:E,userGlobalElo:T});Or.push(c),logger.info(`[Prescribed] Group '${t.id}': ${t.targetCardIds.length} targets total, ${c.encounteredTargets.size} encountered, ${c.pendingTargets.length} pending (${c.surfaceableTargets.length} surfaceable, ${c.blockedTargets.length} blocked), ${c.supportCandidates.length} authored support candidates, ${c.discoveredSupportCandidates.length} discovered support candidates, pressure=${c.pressureMultiplier.toFixed(2)}`),c.blockedTargets.length>0&&(logger.info(`[Prescribed] Group '${t.id}' blocked targets: ${c.blockedTargets.join(`, `)}`),logger.info(`[Prescribed] Group '${t.id}' support tags needed: ${c.supportTags.join(`, `)||`(none)`}`),logger.info(`[Prescribed] Group '${t.id}' escalation mode: `+(c.supportCandidates.length>0?`direct-support`:c.discoveredSupportCandidates.length>0?`inserted-support-candidates`:`boost-only`)),c.discoveredSupportCandidates.length>0&&logger.info(`[Prescribed] Group '${t.id}' discovered support candidates: ${c.discoveredSupportCandidates.join(`, `)}`)),Tr.groups[t.id]=this.buildNextGroupState(c,S.groups[t.id]);let d=this.buildDirectTargetCards(c,u,Dr),g=this.buildSupportCards(c,u,Dr),w=this.buildDiscoveredSupportCards(c,u,Dr),D=this.buildPracticeCards({group:t,courseId:u,emittedIds:Dr,cardsByTag:wr,hierarchyConfigs:C,userTagElo:E,userGlobalElo:T,activeIds:m,seenIds:b,priorPracticeDebt:kr,nextPracticeDebt:Ar});jr.set(t.id,D.debts),Er.push(...d,...g,...w,...D.cards)}Tr.practiceDebt=Ar;let Mr=this.buildSupportHintSummary(Or),Nr=Object.keys(Mr.boostTags).length>0?{boostTags:Mr.boostTags,_label:`prescribed-support (${Mr.supportTags.length} tags; blocked=${Mr.blockedTargetIds.length}; testversion=${PRESCRIBED_DEBUG_VERSION})`}:void 0;if(Nr){let t=Object.entries(Nr.boostTags??{});logger.info(`[Prescribed] Emitting ${t.length} boost hint(s): `+t.map(([t,c])=>`${t}\xD7${c.toFixed(1)}`).join(`, `))}else logger.info(`[Prescribed] No hints to emit (no blocked targets or no support tags)`);if(this.capturePressureSnapshot(u,Or,jr,Er,Nr),Er.length===0)return logger.info(`[Prescribed] 0 cards emitted (all targets blocked, authored/discovered support candidates exhausted)`+(Nr?` — boost hints emitted but may not survive filters`:``)),await this.putStrategyState(Tr).catch(t=>{logger.debug(`[Prescribed] Failed to persist empty-state update: ${t}`)}),Nr?{cards:[],hints:Nr}:{cards:[]};let Pr=pickTopByScore(Er,t),Fr=new Map;for(let t of Pr){let c=t.provenance[0];if(c?.reason.includes(`mode=practice`))continue;let u=c?.reason.match(/group=([^;]+)/)?.[1],d=c?.reason.includes(`mode=support`)?`supportIds`:`targetIds`;u&&(Fr.has(u)||Fr.set(u,{targetIds:[],supportIds:[]}),Fr.get(u)[d].push(t.cardId))}for(let t of this.config.groups){let c=Tr.groups[t.id],u=Fr.get(t.id);u&&(u.targetIds.length>0||u.supportIds.length>0)&&(c.lastSurfacedAt=isoNow(),c.sessionsSinceSurfaced=0,u.supportIds.length>0&&(c.lastSupportAt=isoNow()))}return await this.putStrategyState(Tr).catch(t=>{logger.debug(`[Prescribed] Failed to persist prescribed progress: ${t}`)}),logger.info(`[Prescribed] Emitting ${Pr.length} cards (${Pr.filter(t=>t.provenance[0]?.reason.includes(`mode=target`)).length} target, ${Pr.filter(t=>t.provenance[0]?.reason.includes(`mode=support`)).length} support, ${Pr.filter(t=>t.provenance[0]?.reason.includes(`mode=discovered-support`)).length} discovered support)`),Nr?{cards:Pr,hints:Nr}:{cards:Pr}}buildSupportHintSummary(t){let c={},u=new Set,d=new Set;for(let m of t)if(!(m.blockedTargets.length===0||m.supportTags.length===0)){m.blockedTargets.forEach(t=>u.add(t));for(let t of m.supportTags)d.add(t),c[t]=(c[t]??1)*m.supportMultiplier}return{boostTags:c,blockedTargetIds:[...u].sort(),supportTags:[...d].sort()}}capturePressureSnapshot(t,c,u,d,m){let g=Date.now(),b=[];for(let t of c){let c=t.group,d=c.freshnessWindowSessions??DEFAULT_FRESHNESS_WINDOW;if(b.push({id:`group:${c.id}:target`,label:`${c.id} targets`,multiplier:t.pressureMultiplier,max:MAX_TARGET_MULTIPLIER,detail:`${t.pendingTargets.length} pending (${t.surfaceableTargets.length} surfaceable, ${t.blockedTargets.length} blocked) \xB7 sinceSurfaced ${t.sessionsSinceSurfaced}/${d}`,items:t.blockedTargets.map(t=>({label:t,value:`blocked`}))}),t.blockedTargets.length>0){let u=t.supportCandidates.length>0?`direct-support`:t.discoveredSupportCandidates.length>0?`inserted-support`:`boost-only`;b.push({id:`group:${c.id}:support`,label:`${c.id} support`,multiplier:t.supportMultiplier,max:MAX_SUPPORT_MULTIPLIER,detail:`mode=${u} \xB7 ${t.supportTags.length} support tag(s)`,items:t.supportTags.map(t=>({label:t}))})}let m=u.get(c.id)??[];m.length>0&&b.push({id:`group:${c.id}:practice-debt`,label:`${c.id} practice debt`,multiplier:Math.max(...m.map(t=>t.multiplier)),max:MAX_PRACTICE_MULTIPLIER,detail:`${m.length} under-practiced skill(s)`,items:m.map(t=>({label:t.tag,value:`\xD7${t.multiplier.toFixed(2)} \xB7 open ${formatAge(g-new Date(t.firstOwedAt).getTime())}`}))})}captureStrategyPressure({source:`prescribed`,courseId:t,gauges:b,topScore:d.length>0?Math.max(...d.map(t=>t.score)):null,hintsLabel:m?._label,timestamp:g})}parseConfig(t){try{let c=JSON.parse(t);return{groups:(Array.isArray(c.groups)?c.groups:[]).map((t,c)=>({id:typeof t.id==`string`&&t.id.trim().length>0?t.id:`group-${c+1}`,targetCardIds:dedupe(Array.isArray(t.targetCardIds)?t.targetCardIds.filter(t=>typeof t==`string`):[]),supportCardIds:dedupe(Array.isArray(t.supportCardIds)?t.supportCardIds.filter(t=>typeof t==`string`):[]),supportTagPatterns:dedupe(Array.isArray(t.supportTagPatterns)?t.supportTagPatterns.filter(t=>typeof t==`string`):[]),freshnessWindowSessions:typeof t.freshnessWindowSessions==`number`?t.freshnessWindowSessions:DEFAULT_FRESHNESS_WINDOW,maxDirectTargetsPerRun:typeof t.maxDirectTargetsPerRun==`number`?t.maxDirectTargetsPerRun:DEFAULT_MAX_DIRECT_PER_RUN,maxSupportCardsPerRun:typeof t.maxSupportCardsPerRun==`number`?t.maxSupportCardsPerRun:DEFAULT_MAX_SUPPORT_PER_RUN,introExposeMinCount:typeof t.introExposeMinCount==`number`?t.introExposeMinCount:DEFAULT_MIN_COUNT,hierarchyWalk:{enabled:t.hierarchyWalk?.enabled!==!1,maxDepth:typeof t.hierarchyWalk?.maxDepth==`number`?t.hierarchyWalk.maxDepth:DEFAULT_HIERARCHY_DEPTH},retireOnEncounter:t.retireOnEncounter!==!1,practiceTagPatterns:dedupe(Array.isArray(t.practiceTagPatterns)?t.practiceTagPatterns.filter(t=>typeof t==`string`):[]),practiceMinCount:typeof t.practiceMinCount==`number`?t.practiceMinCount:DEFAULT_PRACTICE_MIN_COUNT,maxPracticeCardsPerRun:typeof t.maxPracticeCardsPerRun==`number`?t.maxPracticeCardsPerRun:DEFAULT_MAX_PRACTICE_PER_RUN})).filter(t=>t.targetCardIds.length>0)}}catch{return{groups:[]}}}async loadHierarchyConfigs(){try{return(await this.course.getAllNavigationStrategies()).filter(t=>t.implementingClass===`hierarchyDefinition`).map(t=>{try{return{prerequisites:JSON.parse(t.serializedData).prerequisites||{}}}catch{return{prerequisites:{}}}})}catch(t){return logger.debug(`[Prescribed] Failed to load hierarchy configs: ${t}`),[]}}buildGroupRuntimeState(t){let{group:c,priorState:u,activeIds:d,seenIds:m,tagsByCard:g,cardsByTag:b,hierarchyConfigs:S,userTagElo:C,userGlobalElo:w}=t,T=new Set;for(let t of c.targetCardIds)(d.has(t)||m.has(t))&&T.add(t);if(u?.encounteredCardIds?.length)for(let t of u.encounteredCardIds)T.add(t);let E=c.targetCardIds.filter(t=>!T.has(t)),D=new Map;for(let t of E)D.set(t,g.get(t)??[]);let O=[],xr=[],Sr=new Set;for(let t of E){let u=D.get(t)??[],d=this.resolveBlockedSupportTags(u,S,C,w,c.hierarchyWalk?.enabled!==!1,c.hierarchyWalk?.maxDepth??DEFAULT_HIERARCHY_DEPTH),m=unmetIntroExposeTags(u,C,c.introExposeMinCount??DEFAULT_MIN_COUNT);m.length>0&&m.forEach(t=>Sr.add(t)),d.blocked||m.length>0?(O.push(t),d.supportTags.forEach(t=>Sr.add(t))):xr.push(t)}let Cr=dedupe([...c.supportCardIds??[],...this.findSupportCardsByTags(c,g,[...Sr])]).filter(t=>!d.has(t)&&!m.has(t)),wr=O.length>0&&Sr.size>0&&Cr.length===0?this.findDiscoveredSupportCards({supportTags:[...Sr],cardsByTag:b,activeIds:d,seenIds:m,excludedIds:new Set([...c.targetCardIds,...c.supportCardIds??[]]),limit:c.maxSupportCardsPerRun??DEFAULT_MAX_SUPPORT_PER_RUN}):[];O.length>0&&Sr.size>0&&wr.length===0&&logger.info(`[Prescribed] Group '${c.id}' discovered 0 broader support candidates (blocked=${O.length}; authoredSupport=${Cr.length})`);let Tr=u?.sessionsSinceSurfaced??0,Er=c.freshnessWindowSessions??DEFAULT_FRESHNESS_WINDOW,Dr=Math.max(0,Tr-Er),Or=E.length===0?1:clamp(1+Dr*.75+Math.min(2,E.length*.1),1,MAX_TARGET_MULTIPLIER),kr=O.length===0?1:clamp(1+Dr*.5+Math.min(1.5,O.length*.15),1,MAX_SUPPORT_MULTIPLIER);return{group:c,encounteredTargets:T,pendingTargets:E,blockedTargets:O,surfaceableTargets:xr,targetTags:D,supportCandidates:Cr,discoveredSupportCandidates:wr,supportTags:[...Sr],pressureMultiplier:Or,supportMultiplier:kr,sessionsSinceSurfaced:Tr,debugVersion:PRESCRIBED_DEBUG_VERSION}}buildNextGroupState(t,c){let u=c?.sessionsSinceSurfaced??0,d=!1;return{encounteredCardIds:[...t.encounteredTargets].sort(),pendingTargetIds:[...t.pendingTargets].sort(),lastSurfacedAt:c?.lastSurfacedAt??null,sessionsSinceSurfaced:u+1,lastSupportAt:c?.lastSupportAt??null,blockedTargetIds:[...t.blockedTargets].sort(),lastResolvedSupportTags:[...t.supportTags].sort()}}buildDirectTargetCards(t,c,u){let d=t.group.maxDirectTargetsPerRun??DEFAULT_MAX_DIRECT_PER_RUN,m=t.surfaceableTargets.filter(t=>!u.has(t)).slice(0,d),g=[];for(let d of m)u.add(d),g.push({cardId:d,courseId:c,score:BASE_TARGET_SCORE*t.pressureMultiplier,provenance:[{strategy:`prescribed`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-prescribed`,action:`generated`,score:BASE_TARGET_SCORE*t.pressureMultiplier,reason:`mode=target;group=${t.group.id};pending=${t.pendingTargets.length};surfaceable=${t.surfaceableTargets.length};blocked=${t.blockedTargets.length};blockedTargets=${t.blockedTargets.join(`|`)||`none`};supportTags=${t.supportTags.join(`|`)||`none`};multiplier=${t.pressureMultiplier.toFixed(2)};testversion=${t.debugVersion}`}]});return g}buildSupportCards(t,c,u){if(t.blockedTargets.length===0||t.supportCandidates.length===0)return[];let d=t.group.maxSupportCardsPerRun??DEFAULT_MAX_SUPPORT_PER_RUN,m=t.supportCandidates.filter(t=>!u.has(t)).slice(0,d),g=[];for(let d of m)u.add(d),g.push({cardId:d,courseId:c,score:BASE_SUPPORT_SCORE*t.supportMultiplier,provenance:[{strategy:`prescribed`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-prescribed`,action:`generated`,score:BASE_SUPPORT_SCORE*t.supportMultiplier,reason:`mode=support;group=${t.group.id};pending=${t.pendingTargets.length};blocked=${t.blockedTargets.length};blockedTargets=${t.blockedTargets.join(`|`)||`none`};supportCard=${d};supportTags=${t.supportTags.join(`|`)||`none`};multiplier=${t.supportMultiplier.toFixed(2)};testversion=${t.debugVersion}`}]});return g}buildDiscoveredSupportCards(t,c,u){if(t.blockedTargets.length===0||t.discoveredSupportCandidates.length===0)return[];let d=t.group.maxSupportCardsPerRun??DEFAULT_MAX_SUPPORT_PER_RUN,m=t.discoveredSupportCandidates.filter(t=>!u.has(t)).slice(0,d),g=[];for(let d of m)u.add(d),g.push({cardId:d,courseId:c,score:DISCOVERED_SUPPORT_SCORE*t.supportMultiplier,provenance:[{strategy:`prescribed`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-prescribed`,action:`generated`,score:DISCOVERED_SUPPORT_SCORE*t.supportMultiplier,reason:`mode=discovered-support;group=${t.group.id};pending=${t.pendingTargets.length};blocked=${t.blockedTargets.length};blockedTargets=${t.blockedTargets.join(`|`)||`none`};supportCard=${d};supportTags=${t.supportTags.join(`|`)||`none`};multiplier=${t.supportMultiplier.toFixed(2)};testversion=${t.debugVersion}`}]});return g}buildPracticeCards(t){let{group:c,courseId:u,emittedIds:d,cardsByTag:m,hierarchyConfigs:g,userTagElo:b,userGlobalElo:S,activeIds:C,seenIds:w,priorPracticeDebt:T,nextPracticeDebt:E}=t,D=c.practiceTagPatterns??[];if(D.length===0)return{cards:[],debts:[]};let O=c.practiceMinCount??DEFAULT_PRACTICE_MIN_COUNT,xr=c.maxPracticeCardsPerRun??DEFAULT_MAX_PRACTICE_PER_RUN,Sr=[...m.keys()].filter(t=>D.some(c=>matchesTagPattern(t,c))&&this.isUnlockedGatedSkill(t,g,b,S)&&(b[t]?.count??0)<O);if(Sr.length===0)return{cards:[],debts:[]};let Cr=Date.now(),wr=1440*60*1e3,Tr=new Map;for(let t of Sr){let c=T[t]??isoNow();E[t]=c;let u=Math.max(0,(Cr-new Date(c).getTime())/864e5),d=clamp(PRACTICE_BASE_MULT+u*PRACTICE_STALENESS_BUMP_PER_DAY,PRACTICE_BASE_MULT,MAX_PRACTICE_MULTIPLIER);Tr.set(t,d)}let Er=Sr.map(t=>({tag:t,multiplier:Tr.get(t)??PRACTICE_BASE_MULT,firstOwedAt:E[t]})).sort((t,c)=>c.multiplier-t.multiplier||t.tag.localeCompare(c.tag)),Dr=this.findDiscoveredSupportCards({supportTags:Sr,cardsByTag:m,activeIds:C,seenIds:w,excludedIds:d,limit:xr});if(Dr.length===0)return{cards:[],debts:Er};logger.info(`[Prescribed] Group '${c.id}' practice: ${Sr.length} unlocked under-practiced skill(s), emitting ${Dr.length} drill card(s)`);let Or=[];for(let t of Dr){d.add(t);let g=PRACTICE_BASE_MULT;for(let c of Sr)(m.get(c)?.includes(t)??!1)&&(g=Math.max(g,Tr.get(c)??PRACTICE_BASE_MULT));let b=BASE_PRACTICE_SCORE*g;Or.push({cardId:t,courseId:u,score:b,provenance:[{strategy:`prescribed`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-prescribed`,action:`generated`,score:b,reason:`mode=practice;group=${c.id};debtMult=\xD7${g.toFixed(2)};underPracticedSkills=${Sr.length};practiceTags=${Sr.slice(0,8).join(`|`)}${Sr.length>8?`|…`:``};testversion=${PRESCRIBED_DEBUG_VERSION}`}]})}return{cards:Or,debts:Er}}isUnlockedGatedSkill(t,c,u,d){let m=c.map(c=>c.prerequisites[t]).filter(t=>Array.isArray(t)&&t.length>0);return m.length===0?!1:m.every(t=>t.every(t=>this.isPrerequisiteMet(t,u[t.tag],d)))}findSupportCardsByTags(t,c,u){if(u.length===0)return[];let d=t.supportCardIds??[],m=t.supportTagPatterns??[];if(d.length===0&&m.length===0)return[];let g=new Set;for(let t of d){let d=c.get(t)??[],b=u.some(t=>d.includes(t)),S=m.some(t=>d.some(c=>matchesTagPattern(c,t)));(b||S)&&g.add(t)}return[...g]}findDiscoveredSupportCards(t){let{supportTags:c,cardsByTag:u,activeIds:d,seenIds:m,excludedIds:g,limit:b}=t,S=new Map;for(let t of c){let c=u.get(t)??[];for(let t of c){if(d.has(t)||m.has(t)||g.has(t))continue;let c=S.get(t);c?c.matches+=1:S.set(t,{cardId:t,matches:1})}}let C=[...S.values()].sort((t,c)=>c.matches-t.matches||t.cardId.localeCompare(c.cardId)),w=new Set,T=[],E=[];for(let t of C){let c=extractWordStem(t.cardId);w.has(c)?E.push(t):(w.add(c),T.push(t))}return shuffleInPlace(T),shuffleInPlace(E),[...T,...E].slice(0,b).map(t=>t.cardId)}resolveBlockedSupportTags(t,c,u,d,m,g){let b=new Set,S=!1;for(let C of t){let t=c.map(t=>t.prerequisites[C]).filter(t=>Array.isArray(t)&&t.length>0);if(t.length!==0&&t.some(t=>t.some(t=>!this.isPrerequisiteMet(t,u[t.tag],d)))){if(S=!0,!m){for(let c of t)for(let t of c)this.isPrerequisiteMet(t,u[t.tag],d)||b.add(t.tag);continue}for(let m of t)for(let t of m)this.isPrerequisiteMet(t,u[t.tag],d)||this.collectSupportTagsRecursive(t.tag,c,u,d,g,new Set,b)}}return{blocked:S,supportTags:[...b]}}collectSupportTagsRecursive(t,c,u,d,m,g,b){if(m<0||g.has(t))return;g.add(t);let S=!1;for(let C of c){let w=C.prerequisites[t];if(!w||w.length===0)continue;let T=w.filter(t=>!this.isPrerequisiteMet(t,u[t.tag],d));if(T.length>0&&m>0){S=!0;for(let t of T)this.collectSupportTagsRecursive(t.tag,c,u,d,m-1,g,b)}}S||b.add(t)}isPrerequisiteMet(t,c,u){if(!c)return!1;let d=t.masteryThreshold?.minCount??DEFAULT_MIN_COUNT;return c.count<d?!1:t.masteryThreshold?.minElo===void 0?t.masteryThreshold?.minCount===void 0?c.score>=u:!0:c.score>=t.masteryThreshold.minElo}}}}),regulators_exports={},__export(regulators_exports,{DEFAULT_REGULATOR_CONFIG:()=>DEFAULT_REGULATOR_CONFIG,INTAKE_CLOCK_KEY:()=>INTAKE_CLOCK_KEY,applyReading:()=>applyReading,frozenMsAt:()=>frozenMsAt,intakeHours:()=>intakeHours,intakeReading:()=>intakeReading,resetIntakeClock:()=>resetIntakeClock,reviewMassReading:()=>reviewMassReading,reviewWeight:()=>reviewWeight,stepIntakeClock:()=>stepIntakeClock}),init_regulators=__esm({"src/core/navigators/regulators.ts"(){"use strict";DEFAULT_REGULATOR_CONFIG={reviewMass:{referenceScore:.95,healthyMass:20,rate:2},intake:{rate:2,scaleHours:24}},INTAKE_CLOCK_KEY=`IntakeClock`,REGULATOR_LABEL={"review-mass":`Review mass`,intake:`Intake`}}}),srs_exports={},__export(srs_exports,{default:()=>SRSNavigator}),init_srs=__esm({"src/core/navigators/generators/srs.ts"(){"use strict";init_navigators(),init_SrsDebugger(),init_regulators(),init_logger(),SRSNavigator=class extends ContentNavigator{constructor(t,c,u){super(t,c,u),_defineProperty$2(this,`name`,void 0),this.name=u?.name||`SRS`}async getWeightedCards(t,c){if(!this.user||!this.course)throw Error(`SRSNavigator requires user and course to be set`);let u=this.course.getCourseID(),d=await this.user.getPendingReviews(u),m=hooks.utc(),g=d.filter(t=>m.isAfter(hooks.utc(t.reviewTime)));if(g.length>0){let t=[...new Set(g.map(t=>t.cardId))],c=await this.course.getAppliedTagsBatch(t),u=[];if(g=g.filter(t=>(c.get(t.cardId)??[]).includes(`srs:skip`)?(u.push(t._id),!1):!0),u.length>0){logger.info(`[SRS] Removing ${u.length} scheduled reviews for srs:skip cards`);for(let t of u)this.user.removeScheduledCardReview(t)}}let b=d.filter(t=>!m.isAfter(hooks.utc(t.reviewTime))),S=null;if(b.length>0){let t=b.reduce((t,c)=>hooks.utc(t.reviewTime).isBefore(hooks.utc(c.reviewTime))?t:c),c=hooks.duration(hooks.utc(t.reviewTime).diff(m));S=c.asHours()<1?`${Math.round(c.asMinutes())}m`:c.asHours()<24?`${Math.round(c.asHours())}h`:`${Math.round(c.asDays())}d`}if(g.length>0)logger.info(`[SRS] Course ${u}: ${g.length} reviews due now (of ${d.length} scheduled)`);else if(d.length>0){let t=[...d].sort((t,c)=>hooks.utc(t.reviewTime).diff(hooks.utc(c.reviewTime)))[0],c=hooks.utc(t.reviewTime),g=hooks.duration(c.diff(m)),b=g.asHours()<1?`${Math.round(g.asMinutes())}m`:g.asHours()<24?`${Math.round(g.asHours())}h`:`${Math.round(g.asDays())}d`;logger.info(`[SRS] Course ${u}: 0 reviews due now (${d.length} scheduled, next in ${b})`)}else logger.info(`[SRS] Course ${u}: No reviews scheduled`);let C=g.map(t=>{let{score:c,urgency:u,reason:d}=this.computeUrgencyScore(t,m);return{cardId:t.cardId,courseId:t.courseId,score:c,reviewUrgency:u,reviewID:t._id,provenance:[{strategy:`srs`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-SRS-default`,action:`generated`,score:c,reason:d}]}}).sort((t,c)=>c.score-t.score);return captureSrsBacklog({courseId:u,scheduledTotal:d.length,dueNow:g.length,healthyBacklog:DEFAULT_REGULATOR_CONFIG.reviewMass.healthyMass,reviewMass:null,backlogMultiplier:1,backlogGrowthRate:DEFAULT_REGULATOR_CONFIG.reviewMass.rate,topReviewScore:C.length>0?C[0].score:null,nextDueIn:S,timestamp:Date.now()}),{cards:C.slice(0,t)}}computeUrgencyScore(t,c){let u=hooks.utc(t.scheduledAt),d=hooks.utc(t.reviewTime),m=Math.max(1,d.diff(u,`hours`)),g=c.diff(d,`hours`),b=g/m,S=.3+.7*Math.exp(-m/720),C=Math.min(1,Math.max(0,b))*.5+S*.5,w=.5+C*.45,T=[`${Math.round(g)}h overdue`,`interval: ${Math.round(m)}h`,`relative: ${b.toFixed(2)}`,`recency: ${S.toFixed(2)}`];return T.push(`review`),{score:w,urgency:C,reason:T.join(`, `)}}}}}),types_exports={},init_types=__esm({"src/core/navigators/generators/types.ts"(){"use strict";}}),init_=__esm({'import("./generators/**/*") in src/core/navigators/index.ts'(){globImport_generators=__glob({"./generators/CompositeGenerator.ts":()=>Promise.resolve().then(()=>(init_CompositeGenerator(),CompositeGenerator_exports)),"./generators/elo.ts":()=>Promise.resolve().then(()=>(init_elo(),elo_exports)),"./generators/index.ts":()=>Promise.resolve().then(()=>(init_generators(),generators_exports)),"./generators/prescribed.ts":()=>Promise.resolve().then(()=>(init_prescribed(),prescribed_exports)),"./generators/srs.ts":()=>Promise.resolve().then(()=>(init_srs(),srs_exports)),"./generators/types.ts":()=>Promise.resolve().then(()=>(init_types(),types_exports))})}}),init_contentNavigationStrategy=__esm({"src/core/types/contentNavigationStrategy.ts"(){"use strict";DEFAULT_LEARNABLE_WEIGHT={weight:1,confidence:.1,sampleSize:0}}}),WeightedFilter_exports={},__export(WeightedFilter_exports,{WeightedFilter:()=>WeightedFilter}),init_WeightedFilter=__esm({"src/core/navigators/filters/WeightedFilter.ts"(){"use strict";init_contentNavigationStrategy(),WeightedFilter=class{constructor(t,c=DEFAULT_LEARNABLE_WEIGHT,u=!1,d){_defineProperty$2(this,`name`,void 0),_defineProperty$2(this,`kind`,void 0),_defineProperty$2(this,`liveOnly`,void 0),_defineProperty$2(this,`inner`,void 0),_defineProperty$2(this,`learnable`,void 0),_defineProperty$2(this,`staticWeight`,void 0),_defineProperty$2(this,`strategyId`,void 0),this.inner=t,this.name=t.name,this.kind=t.kind,this.liveOnly=t.liveOnly,this.learnable=c,this.staticWeight=u,this.strategyId=d}async transform(t,c){let u=this.learnable.weight,d;if(!this.staticWeight&&c.orchestration){let t=this.strategyId||this.inner.strategyId||this.name;u=c.orchestration.getEffectiveWeight(t,this.learnable),d=c.orchestration.getDeviation(t)}if(Math.abs(u-1)<.001)return this.inner.transform(t,c);let m=new Map;for(let c of t)m.set(c.cardId,c.score);return(await this.inner.transform(t,c)).map(t=>{let c=m.get(t.cardId);if(c===void 0||c===0||t.score===0)return t;let g=t.score/c;if(Math.abs(g-1)<1e-4)return t;let b=c*g**+u,S=t.provenance.length-1,C=t.provenance[S];if(C){let c=[...t.provenance];return c[S]={...C,score:b,effectiveWeight:u,deviation:d},{...t,score:b,provenance:c}}return{...t,score:b}})}}}}),eloDistance_exports={},__export(eloDistance_exports,{DEFAULT_ELO_DISTANCE_CONFIG:()=>DEFAULT_ELO_DISTANCE_CONFIG,createEloDistanceFilter:()=>createEloDistanceFilter,default:()=>EloDistanceFilter,mountMultiDimEloToggle:()=>mountMultiDimEloToggle,tagAwareGap:()=>tagAwareGap}),init_eloDistance=__esm({"src/core/navigators/filters/eloDistance.ts"(){"use strict";var t;init_navigators(),init_logger(),DEFAULT_ELO_DISTANCE_CONFIG={halfLife:300,minMultiplier:.05,maxMultiplier:1,tagAware:!1,minTagCount:3},TAG_CONFIDENCE_HALF=10,DEFAULT_CARD_ELO=1e3,MULTI_DIM_ELO_KEY=`skuilder:multiDimElo`,multiDimElo=readMultiDimElo(),mountMultiDimEloToggle(),EloDistanceFilter=(t=class _EloDistanceFilter extends ContentNavigator{constructor(t,c,u){super(t,c,u),_defineProperty$2(this,`name`,void 0),_defineProperty$2(this,`kind`,_EloDistanceFilter.kind),_defineProperty$2(this,`liveOnly`,!0),_defineProperty$2(this,`config`,void 0),this.name=u.name||`ELO Distance`;let d;try{d=u.serializedData?JSON.parse(u.serializedData):void 0}catch{d=void 0}this.config=resolveConfig(d)}transform(t,c){return applyEloDistance(t,c,this.config,{name:this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-eloDistance-default`})}async getWeightedCards(t){throw Error(`EloDistanceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().`)}},_defineProperty$2(t,`kind`,`signal`),t)}}),hierarchyDefinition_exports={},__export(hierarchyDefinition_exports,{default:()=>HierarchyDefinitionNavigator}),init_hierarchyDefinition=__esm({"src/core/navigators/filters/hierarchyDefinition.ts"(){"use strict";var t;init_navigators(),init_logger(),DEFAULT_MIN_COUNT2=3,HierarchyDefinitionNavigator=(t=class _HierarchyDefinitionNavigator extends ContentNavigator{constructor(t,c,u){super(t,c,u),_defineProperty$2(this,`config`,void 0),_defineProperty$2(this,`name`,void 0),_defineProperty$2(this,`kind`,_HierarchyDefinitionNavigator.kind),this.config=this.parseConfig(u.serializedData),this.name=u.name||`Hierarchy Definition`}parseConfig(t){try{return{prerequisites:JSON.parse(t).prerequisites||{}}}catch{return{prerequisites:{}}}}isPrerequisiteMet(t,c,u){if(!c)return!1;let d=t.masteryThreshold?.minCount??DEFAULT_MIN_COUNT2;return c.count<d?!1:t.masteryThreshold?.minElo===void 0?t.masteryThreshold?.minCount===void 0?c.score>=u:!0:c.score>=t.masteryThreshold.minElo}async getMasteredTags(t){let c=new Set;try{let u=toCourseElo((await t.user.getCourseRegDoc(t.course.getCourseID())).elo);for(let t of Object.values(this.config.prerequisites))for(let d of t){let t=u.tags[d.tag];this.isPrerequisiteMet(d,t,u.global.score)&&c.add(d.tag)}}catch{}return c}getUnlockedTags(t){let c=new Set;for(let[u,d]of Object.entries(this.config.prerequisites))d.every(c=>t.has(c.tag))&&c.add(u);return c}hasPrerequisites(t){return t in this.config.prerequisites}async checkCardUnlock(t,c,u,d){try{let c=t.tags??[],m=c.filter(t=>this.hasPrerequisites(t)&&!u.has(t));return m.length===0?{isUnlocked:!0,reason:`Prerequisites met, tags: ${c.length>0?c.join(`, `):`none`}`}:{isUnlocked:!1,reason:`Blocked: missing prerequisites ${m.flatMap(t=>(this.config.prerequisites[t]||[]).filter(t=>!d.has(t.tag)).map(t=>t.tag)).join(`, `)} for tags ${m.join(`, `)}`}}catch{return{isUnlocked:!0,reason:`Prerequisites check skipped (tag lookup failed)`}}}getPreReqBoosts(t,c){let u=new Map;for(let[d,m]of Object.entries(this.config.prerequisites))if(!t.has(d))for(let t of m){if(!t.preReqBoost||t.preReqBoost<=1||c.has(t.tag))continue;let d=u.get(t.tag)??1;u.set(t.tag,Math.max(d,t.preReqBoost))}return u}getTargetBoosts(t){let c=new Map,u=Object.keys(this.config.prerequisites),d=[...t];logger.info(`[HierarchyDefinition:targetBoost:trace] ${this.name} | configKeys=${u.length}, unlocked=${d.length} (${d.slice(0,5).join(`, `)}${d.length>5?`...`:``})`);for(let[u,d]of Object.entries(this.config.prerequisites))if(t.has(u)){logger.info(`[HierarchyDefinition:targetBoost:trace] UNLOCKED ${u}: ${d.length} prereqs, raw=${JSON.stringify(d.map(t=>({tag:t.tag,tb:t.targetBoost})))}`);for(let t of d){if(!t.targetBoost||t.targetBoost<=1)continue;let d=c.get(u)??1;c.set(u,Math.max(d,t.targetBoost))}}return c.size>0?logger.info(`[HierarchyDefinition] targetBoosts active: ${[...c.entries()].map(([t,c])=>`${t}=\xD7${c}`).join(`, `)}`):logger.info(`[HierarchyDefinition:targetBoost:trace] no targetBoosts found despite ${d.length} unlocked tags`),c}async transform(t,c){let u=await this.getMasteredTags(c),d=this.getUnlockedTags(u),m=this.getPreReqBoosts(d,u),g=this.getTargetBoosts(d),b=[];for(let S of t){let{isUnlocked:t,reason:C}=await this.checkCardUnlock(S,c.course,d,u),w=t?S.score:S.score*.02,T=t?`passed`:`penalized`,E=C;if(t&&m.size>0){let t=S.tags??[],c=1,u=[];for(let d of t){let t=m.get(d);t&&t>c&&(c=t,u.push(d))}c>1&&(w*=c,T=`boosted`,E=`${C} | preReqBoost \xD7${c.toFixed(2)} for ${u.join(`, `)}`,logger.info(`[HierarchyDefinition] preReqBoost \xD7${c.toFixed(2)} applied to card ${S.cardId} via tags [${u.join(`, `)}] (score: ${S.score.toFixed(3)} \u2192 ${w.toFixed(3)})`))}if(t&&g.size>0){let t=S.tags??[],c=1,u=[];for(let d of t){let t=g.get(d);t&&t>c&&(c=t,u.push(d))}c>1&&(w*=c,T=`boosted`,E=`${E} | targetBoost \xD7${c.toFixed(2)} for ${u.join(`, `)}`,logger.info(`[HierarchyDefinition] targetBoost \xD7${c.toFixed(2)} applied to card ${S.cardId} via tags [${u.join(`, `)}] (score: ${S.score.toFixed(3)} \u2192 ${w.toFixed(3)})`))}b.push({...S,score:w,provenance:[...S.provenance,{strategy:`hierarchyDefinition`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-hierarchy`,action:T,score:w,reason:E}]})}return b}async getWeightedCards(t){throw Error(`HierarchyDefinitionNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().`)}},_defineProperty$2(t,`kind`,`gate`),t)}}),userTagPreference_exports={},__export(userTagPreference_exports,{default:()=>UserTagPreferenceFilter}),init_userTagPreference=__esm({"src/core/navigators/filters/userTagPreference.ts"(){"use strict";var t;init_navigators(),UserTagPreferenceFilter=(t=class _UserTagPreferenceFilter extends ContentNavigator{constructor(t,c,u){super(t,c,u),_defineProperty$2(this,`_strategyData`,void 0),_defineProperty$2(this,`name`,void 0),_defineProperty$2(this,`kind`,_UserTagPreferenceFilter.kind),this._strategyData=u,this.name=u.name||`User Tag Preferences`}computeMultiplier(t,c){let u=t.map(t=>c[t]).filter(t=>t!==void 0);return u.length===0?1:Math.max(...u)}buildReason(t,c,u){let d=t.filter(t=>c[t]===u);return u===0?`Excluded by user preference: ${d.join(`, `)} (${u}x)`:u<1?`Penalized by user preference: ${d.join(`, `)} (${u.toFixed(2)}x)`:u>1?`Boosted by user preference: ${d.join(`, `)} (${u.toFixed(2)}x)`:`No matching user preferences`}async transform(t,c){let u=await this.getStrategyState();return!u||Object.keys(u.boost).length===0?t.map(t=>({...t,provenance:[...t.provenance,{strategy:`userTagPreference`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||this._strategyData._id,action:`passed`,score:t.score,reason:`No user tag preferences configured`}]})):await Promise.all(t.map(async t=>{let c=t.tags??[],d=this.computeMultiplier(c,u.boost),m=Math.min(1,t.score*d),g;return g=d===0||d<1?`penalized`:d>1?`boosted`:`passed`,{...t,score:m,provenance:[...t.provenance,{strategy:`userTagPreference`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||this._strategyData._id,action:g,score:m,reason:this.buildReason(c,u.boost,d)}]}}))}async getWeightedCards(t){throw Error(`UserTagPreferenceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().`)}},_defineProperty$2(t,`kind`,`signal`),t)}}),filters_exports={},__export(filters_exports,{EloDistanceFilter:()=>EloDistanceFilter,UserTagPreferenceFilter:()=>UserTagPreferenceFilter,createEloDistanceFilter:()=>createEloDistanceFilter}),init_filters=__esm({"src/core/navigators/filters/index.ts"(){"use strict";init_eloDistance(),init_userTagPreference()}}),inferredPreferenceStub_exports={},__export(inferredPreferenceStub_exports,{INFERRED_PREFERENCE_NAVIGATOR_STUB:()=>INFERRED_PREFERENCE_NAVIGATOR_STUB}),init_inferredPreferenceStub=__esm({"src/core/navigators/filters/inferredPreferenceStub.ts"(){"use strict";INFERRED_PREFERENCE_NAVIGATOR_STUB=!0}}),interferenceMitigator_exports={},__export(interferenceMitigator_exports,{default:()=>InterferenceMitigatorNavigator}),init_interferenceMitigator=__esm({"src/core/navigators/filters/interferenceMitigator.ts"(){"use strict";var t;init_navigators(),DEFAULT_MIN_COUNT3=10,DEFAULT_MIN_ELAPSED_DAYS=3,DEFAULT_INTERFERENCE_DECAY=.8,InterferenceMitigatorNavigator=(t=class _InterferenceMitigatorNavigator extends ContentNavigator{constructor(t,c,u){super(t,c,u),_defineProperty$2(this,`config`,void 0),_defineProperty$2(this,`name`,void 0),_defineProperty$2(this,`kind`,_InterferenceMitigatorNavigator.kind),_defineProperty$2(this,`interferenceMap`,void 0),this.config=this.parseConfig(u.serializedData),this.interferenceMap=this.buildInterferenceMap(),this.name=u.name||`Interference Mitigator`}parseConfig(t){try{let c=JSON.parse(t),u=c.interferenceSets||[];return u.length>0&&Array.isArray(u[0])&&(u=u.map(t=>({tags:t}))),{interferenceSets:u,maturityThreshold:{minCount:c.maturityThreshold?.minCount??DEFAULT_MIN_COUNT3,minElo:c.maturityThreshold?.minElo,minElapsedDays:c.maturityThreshold?.minElapsedDays??DEFAULT_MIN_ELAPSED_DAYS},defaultDecay:c.defaultDecay??DEFAULT_INTERFERENCE_DECAY}}catch{return{interferenceSets:[],maturityThreshold:{minCount:DEFAULT_MIN_COUNT3,minElapsedDays:DEFAULT_MIN_ELAPSED_DAYS},defaultDecay:DEFAULT_INTERFERENCE_DECAY}}}buildInterferenceMap(){let t=new Map;for(let c of this.config.interferenceSets){let u=c.decay??this.config.defaultDecay??DEFAULT_INTERFERENCE_DECAY;for(let d of c.tags){t.has(d)||t.set(d,[]);let m=t.get(d);for(let t of c.tags)if(t!==d){let c=m.find(c=>c.partner===t);c?c.decay=Math.max(c.decay,u):m.push({partner:t,decay:u})}}}return t}async getImmatureTags(t){let c=new Set;try{let u=toCourseElo((await t.user.getCourseRegDoc(t.course.getCourseID())).elo),d=this.config.maturityThreshold?.minCount??DEFAULT_MIN_COUNT3,m=this.config.maturityThreshold?.minElo,g=(this.config.maturityThreshold?.minElapsedDays??DEFAULT_MIN_ELAPSED_DAYS)*2;for(let[t,b]of Object.entries(u.tags)){if(b.count===0)continue;let u=b.count<d,S=m!==void 0&&b.score<m,C=b.count<g;(u||S||C)&&c.add(t)}}catch{}return c}getTagsToAvoid(t){let c=new Map;for(let u of t){let d=this.interferenceMap.get(u);if(d){for(let{partner:u,decay:m}of d)if(!t.has(u)){let t=c.get(u)??0;c.set(u,Math.max(t,m))}}}return c}computeInterferenceEffect(t,c,u){if(c.size===0)return{multiplier:1,interferingTags:[],reason:`No interference detected`};let d=1,m=[];for(let u of t){let t=c.get(u);t!==void 0&&(m.push(u),d*=1-t)}if(m.length===0)return{multiplier:1,interferingTags:[],reason:`No interference detected`};let g=new Set;for(let t of m)for(let c of u)this.interferenceMap.get(c)?.some(c=>c.partner===t)&&g.add(c);let b=`Interferes with immature tags ${Array.from(g).join(`, `)} (tags: ${m.join(`, `)}, multiplier: ${d.toFixed(2)})`;return{multiplier:d,interferingTags:m,reason:b}}async transform(t,c){let u=await this.getImmatureTags(c),d=this.getTagsToAvoid(u),m=[];for(let c of t){let t=c.tags??[],{multiplier:g,reason:b}=this.computeInterferenceEffect(t,d,u),S=c.score*g,C=g<1?`penalized`:g>1?`boosted`:`passed`;m.push({...c,score:S,provenance:[...c.provenance,{strategy:`interferenceMitigator`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-interference`,action:C,score:S,reason:b}]})}return m}async getWeightedCards(t){throw Error(`InterferenceMitigatorNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().`)}},_defineProperty$2(t,`kind`,`signal`),t)}}),relativePriority_exports={},__export(relativePriority_exports,{default:()=>RelativePriorityNavigator}),init_relativePriority=__esm({"src/core/navigators/filters/relativePriority.ts"(){"use strict";var t;init_navigators(),DEFAULT_PRIORITY=.5,DEFAULT_PRIORITY_INFLUENCE=.5,DEFAULT_COMBINE_MODE=`max`,RelativePriorityNavigator=(t=class _RelativePriorityNavigator extends ContentNavigator{constructor(t,c,u){super(t,c,u),_defineProperty$2(this,`config`,void 0),_defineProperty$2(this,`name`,void 0),_defineProperty$2(this,`kind`,_RelativePriorityNavigator.kind),this.config=this.parseConfig(u.serializedData),this.name=u.name||`Relative Priority`}parseConfig(t){try{let c=JSON.parse(t);return{tagPriorities:c.tagPriorities||{},defaultPriority:c.defaultPriority??DEFAULT_PRIORITY,combineMode:c.combineMode??DEFAULT_COMBINE_MODE,priorityInfluence:c.priorityInfluence??DEFAULT_PRIORITY_INFLUENCE}}catch{return{tagPriorities:{},defaultPriority:DEFAULT_PRIORITY,combineMode:DEFAULT_COMBINE_MODE,priorityInfluence:DEFAULT_PRIORITY_INFLUENCE}}}getTagPriority(t){return this.config.tagPriorities[t]??this.config.defaultPriority??DEFAULT_PRIORITY}computeCardPriority(t){if(t.length===0)return this.config.defaultPriority??DEFAULT_PRIORITY;let c=t.map(t=>this.getTagPriority(t));switch(this.config.combineMode){case`max`:return Math.max(...c);case`min`:return Math.min(...c);case`average`:return c.reduce((t,c)=>t+c,0)/c.length;default:return Math.max(...c)}}computeBoostFactor(t){let c=this.config.priorityInfluence??DEFAULT_PRIORITY_INFLUENCE;return 1+(t-.5)*c}buildPriorityReason(t,c,u,d){if(t.length===0)return`No tags, neutral priority (${c.toFixed(2)})`;let m=t.slice(0,3).join(`, `),g=t.length>3?` (+${t.length-3} more)`:``;return u===1?`Neutral priority (${c.toFixed(2)}) for tags: ${m}${g}`:u>1?`High-priority tags: ${m}${g} (priority ${c.toFixed(2)} \u2192 boost ${u.toFixed(2)}x \u2192 ${d.toFixed(2)})`:`Low-priority tags: ${m}${g} (priority ${c.toFixed(2)} \u2192 reduce ${u.toFixed(2)}x \u2192 ${d.toFixed(2)})`}async transform(t,c){return await Promise.all(t.map(async t=>{let c=t.tags??[],u=this.computeCardPriority(c),d=this.computeBoostFactor(u),m=Math.max(0,t.score*d),g=d>1?`boosted`:d<1?`penalized`:`passed`,b=this.buildPriorityReason(c,u,d,m);return{...t,score:m,provenance:[...t.provenance,{strategy:`relativePriority`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-priority`,action:g,score:m,reason:b}]}}))}async getWeightedCards(t){throw Error(`RelativePriorityNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().`)}},_defineProperty$2(t,`kind`,`signal`),t)}}),types_exports2={},init_types2=__esm({"src/core/navigators/filters/types.ts"(){"use strict";}}),userGoalStub_exports={},__export(userGoalStub_exports,{USER_GOAL_NAVIGATOR_STUB:()=>USER_GOAL_NAVIGATOR_STUB}),init_userGoalStub=__esm({"src/core/navigators/filters/userGoalStub.ts"(){"use strict";USER_GOAL_NAVIGATOR_STUB=!0}}),init_2=__esm({'import("./filters/**/*") in src/core/navigators/index.ts'(){globImport_filters=__glob({"./filters/WeightedFilter.ts":()=>Promise.resolve().then(()=>(init_WeightedFilter(),WeightedFilter_exports)),"./filters/eloDistance.ts":()=>Promise.resolve().then(()=>(init_eloDistance(),eloDistance_exports)),"./filters/hierarchyDefinition.ts":()=>Promise.resolve().then(()=>(init_hierarchyDefinition(),hierarchyDefinition_exports)),"./filters/index.ts":()=>Promise.resolve().then(()=>(init_filters(),filters_exports)),"./filters/inferredPreferenceStub.ts":()=>Promise.resolve().then(()=>(init_inferredPreferenceStub(),inferredPreferenceStub_exports)),"./filters/interferenceMitigator.ts":()=>Promise.resolve().then(()=>(init_interferenceMitigator(),interferenceMitigator_exports)),"./filters/relativePriority.ts":()=>Promise.resolve().then(()=>(init_relativePriority(),relativePriority_exports)),"./filters/types.ts":()=>Promise.resolve().then(()=>(init_types2(),types_exports2)),"./filters/userGoalStub.ts":()=>Promise.resolve().then(()=>(init_userGoalStub(),userGoalStub_exports)),"./filters/userTagPreference.ts":()=>Promise.resolve().then(()=>(init_userTagPreference(),userTagPreference_exports))})}}),init_gradient=__esm({"src/core/orchestration/gradient.ts"(){"use strict";init_logger()}}),init_learning=__esm({"src/core/orchestration/learning.ts"(){"use strict";init_contentNavigationStrategy(),init_types_legacy(),init_logger(),MIN_OBSERVATIONS_FOR_UPDATE=10,LEARNING_RATE=.1,MAX_WEIGHT_DELTA=.3,MIN_R_SQUARED_FOR_GRADIENT=.05,FLAT_GRADIENT_THRESHOLD=.02,MAX_HISTORY_LENGTH=100}}),init_signal=__esm({"src/core/orchestration/signal.ts"(){"use strict";}}),init_recording=__esm({"src/core/orchestration/recording.ts"(){"use strict";init_signal(),init_types_legacy(),init_logger()}}),init_orchestration=__esm({"src/core/orchestration/index.ts"(){"use strict";init_logger(),init_gradient(),init_learning(),init_signal(),init_recording(),MIN_SPREAD=.1,MAX_SPREAD=.5,MIN_WEIGHT=.1,MAX_WEIGHT=3}}),Pipeline_exports={},__export(Pipeline_exports,{Pipeline:()=>Pipeline,mergeHints:()=>mergeHints2}),init_Pipeline=__esm({"src/core/navigators/Pipeline.ts"(){"use strict";init_navigators(),init_logger(),init_orchestration(),init_PipelineDebugger(),init_diversityRerank(),init_regulators(),init_SrsDebugger(),VERBOSE_RESULTS=!0,Pipeline=class extends ContentNavigator{constructor(t,c,u,d){super(),_defineProperty$2(this,`generator`,void 0),_defineProperty$2(this,`filters`,void 0),_defineProperty$2(this,`_cachedOrchestration`,null),_defineProperty$2(this,`strategyHash`,void 0),_defineProperty$2(this,`_tagCache`,new Map),_defineProperty$2(this,`_ephemeralHints`,null),_defineProperty$2(this,`_intakeClock`,null),_defineProperty$2(this,`_intakeClockWrite`,Promise.resolve()),this.generator=t,this.filters=c,this.user=u,this.course=d,d.getCourseConfig().then(t=>{logger.debug(`[pipeline] Crated pipeline for ${t.name}`)}).catch(t=>{logger.error(`[pipeline] Failed to lookup courseCfg: ${t}`)}),logPipelineConfig(t,c),registerPipelineForDebug(this)}setEphemeralHints(t){this._ephemeralHints=t,logger.info(`[Pipeline] Ephemeral hints set: ${JSON.stringify(t)}`)}async getWeightedCards(t){let c=performance.now(),u=await this.buildContext(),d=performance.now(),m=500;logger.debug(`[Pipeline] Fetching 500 candidates from generator '${this.generator.name}'`);let g=await this.generator.getWeightedCards(500,u),b=g.cards,S=performance.now(),C=b.length;this._ephemeralHints=mergeHints2([this._ephemeralHints,g.hints])??null;let w;if(this.generator.generators){let t=new Map;for(let c of b){let u=c.provenance[0];if(u){let d=u.strategyName;t.has(d)||t.set(d,{cards:[]}),t.get(d).cards.push(c)}}w=Array.from(t.entries()).map(([t,c])=>{let u=c.cards.filter(t=>t.reviewID).length;return{name:t,cardCount:c.cards.length,newCount:c.cards.length-u,reviewCount:u,topScore:Math.max(...c.cards.map(t=>t.score),0)}})}logger.debug(`[Pipeline] Generator returned ${C} candidates`),b=await this.hydrateTags(b);let T=performance.now(),E=[...b],D=this._ephemeralHints;if(D?.requireCards?.length){let t=new Set(E.map(t=>t.cardId)),c=D.requireCards.filter(c=>!c.includes(`*`)&&!t.has(c));if(c.length>0){let t=await this.course.getAppliedTagsBatch(c),u=this.course.getCourseID();for(let d of c)E.push({cardId:d,courseId:u,score:1,tags:t.get(d)??[],provenance:[]});logger.info(`[Pipeline] Pre-fetched ${c.length} required card(s) into pool: ${c.join(`, `)}`)}}let O=new Set(b.filter(t=>t.provenance.some(t=>t.strategy===`prescribed`)).map(t=>t.cardId)),xr=[],Sr=new Map(b.map(t=>[t.cardId,t.score])),Cr=new Set;for(let t of this.filters){let c=b.length,d=new Map(b.map(t=>[t.cardId,t.score]));b=await t.transform(b,u);let m=0,g=0,S=0,C=c-b.length,w=t.kind??`gate`;for(let t of b){let c=d.get(t.cardId)??0;t.score>c?m++:t.score<c?(g++,w===`gate`&&Cr.add(t.cardId)):S++}if(xr.push({name:t.name,kind:w,boosted:m,penalized:g,passed:S,removed:C}),O.size>0){let c=new Set(b.map(t=>t.cardId)),u=[...O].filter(t=>!c.has(t)),d=b.filter(t=>O.has(t.cardId)&&t.score===0).map(t=>t.cardId);(u.length>0||d.length>0)&&(logger.info(`[Pipeline] Filter '${t.name}' impact on prescribed cards: `+(u.length>0?`removed=[${u.join(`, `)}] `:``)+(d.length>0?`zeroed=[${d.join(`, `)}]`:``)),u.forEach(t=>O.delete(t)))}logger.debug(`[Pipeline] Filter '${t.name}': ${d.size} \u2192 ${b.length} cards (\u2191${m} \u2193${g} =${S})`)}let wr=b;b=b.filter(t=>t.score>0);let Tr=await this.regulate(b,Sr,Cr),Er=this._ephemeralHints;Er&&(this._ephemeralHints=null,b=this.applyHints(b,Er,E)),b=diversityRerank(b),b.sort((t,c)=>c.score-t.score);let Dr=performance.now(),Or=b.slice(0,t);logger.info(`[Pipeline:timing] total=${(Dr-c).toFixed(0)}ms (context=${(d-c).toFixed(0)} generate=${(S-d).toFixed(0)} hydrate=${(T-S).toFixed(0)} filter=${(Dr-T).toFixed(0)})`);let kr=Or.slice(0,3).map(t=>t.score);logExecutionSummary(this.generator.name,C,this.filters.length,Or.length,kr,xr),logResultCards(Or),logCardProvenance(Or,3);try{let t=await this.course?.getCourseConfig().catch(()=>void 0),c=t?.name,d=buildRunReport(this.course?.getCourseID()||`unknown`,c,this.generator.name,w,C,xr,b,Or,u.userElo,Er??void 0,wr,Tr),m={...this.strategyHash?{strategies:this.strategyHash}:{},...t?.contentVersion?{content:t.contentVersion}:{}};captureRun({...d,...Object.keys(m).length?{versions:m}:{}})}catch(t){logger.debug(`[Pipeline] Failed to capture debug run: ${t}`)}return{cards:Or}}async hydrateTags(t){if(t.length===0)return t;let c=[];for(let u of t)this._tagCache.has(u.cardId)||c.push(u.cardId);if(c.length>0){let t=await this.course.getAppliedTagsBatch(c);for(let[c,u]of t)this._tagCache.set(c,u)}let u=new Map;for(let c of t)u.set(c.cardId,this._tagCache.get(c.cardId)??[]);return logTagHydration(t,u),t.map(t=>({...t,tags:this._tagCache.get(t.cardId)??[]}))}applyHints(t,c,u){let d=t.length;if(c.excludeCards?.length&&(t=t.filter(t=>!c.excludeCards.some(c=>globMatch(t.cardId,c)))),c.excludeTags?.length&&(t=t.filter(t=>!c.excludeTags.some(c=>cardMatchesTagPattern(t,c)))),c.boostTags)for(let[u,d]of Object.entries(c.boostTags))for(let m of t)cardMatchesTagPattern(m,u)&&(m.score*=d,m.provenance.push({strategy:`ephemeralHint`,strategyId:`ephemeral-hint`,strategyName:c._label?`Replan Hint (${c._label})`:`Replan Hint`,action:`boosted`,score:m.score,reason:`boostTag ${u} \xD7${d}`}));if(c.boostCards)for(let[u,d]of Object.entries(c.boostCards))for(let m of t)globMatch(m.cardId,u)&&(m.score*=d,m.provenance.push({strategy:`ephemeralHint`,strategyId:`ephemeral-hint`,strategyName:c._label?`Replan Hint (${c._label})`:`Replan Hint`,action:`boosted`,score:m.score,reason:`boostCard ${u} \xD7${d}`}));let m=new Set(t.map(t=>t.cardId)),g=new Map(t.map(t=>[t.cardId,t])),b=c._label?`Replan Hint (${c._label})`:`Replan Hint`,applyRequirement=(c,u)=>{let d=1/0,S=g.get(c.cardId);S?S.score<d&&(S.score=d,S.provenance.push({strategy:`ephemeralHint`,strategyId:`ephemeral-hint`,strategyName:b,action:`boosted`,score:d,reason:`${u} (upgrade to mandatory score)`})):(t.push({...c,score:d,provenance:[...c.provenance,{strategy:`ephemeralHint`,strategyId:`ephemeral-hint`,strategyName:b,action:`boosted`,score:d,reason:u}]}),m.add(c.cardId),g.set(c.cardId,t[t.length-1]))};if(c.requireCards?.length)for(let t of c.requireCards){for(let c of m)globMatch(c,t)&&applyRequirement(g.get(c),`requireCard ${t}`);for(let c of u)globMatch(c.cardId,t)&&applyRequirement(c,`requireCard ${t}`)}if(c.requireTags?.length)for(let t of c.requireTags){for(let c of m){let u=g.get(c);cardMatchesTagPattern(u,t)&&applyRequirement(u,`requireTag ${t}`)}for(let c of u)cardMatchesTagPattern(c,t)&&applyRequirement(c,`requireTag ${t}`)}return logger.info(`[Pipeline] Hints applied: ${d} \u2192 ${t.length} cards`),t}async regulate(t,c,u){let d=DEFAULT_REGULATOR_CONFIG,m=t.filter(t=>t.reviewID),g=t.filter(t=>!t.reviewID),b=g.filter(t=>!u.has(t.cardId)),S=reviewMassReading(m,c,d.reviewMass);applyReading(m,S),noteReviewPressure(this.course.getCourseID(),{mass:S.urgency,healthyMass:d.reviewMass.healthyMass,rate:d.reviewMass.rate,multiplier:S.multiplier});let C=Date.now(),w=await this.loadIntakeClock(C),T=stepIntakeClock(w,C,b.length);T!==w&&this.saveIntakeClock(T);let E=intakeReading(T,C,{eligibleNew:b.length,newCandidates:g.length},d.intake);return applyReading(b,E),logger.info(`[Pipeline:regulators] review mass ${S.urgency.toFixed(1)} over ${m.length} due \u2192 \xD7${S.multiplier.toFixed(2)}; intake ${E.urgency.toFixed(1)}h, ${b.length}/${g.length} new eligible \u2192 \xD7${E.multiplier.toFixed(2)}`),[S,E]}notePresented(t){t.status!==`new`||t.courseId!==this.course?.getCourseID()||this.saveIntakeClock(resetIntakeClock(Date.now()))}async loadIntakeClock(t){if(this._intakeClock)return this._intakeClock;let c=null;try{c=await this.user.getStrategyState(this.course.getCourseID(),INTAKE_CLOCK_KEY)}catch(t){logger.warn(`[Pipeline:regulators] Could not read the intake clock: ${t}`)}return c?this._intakeClock=c:this.saveIntakeClock(resetIntakeClock(t)),this._intakeClock}saveIntakeClock(t){this._intakeClock=t;let c=this.course.getCourseID();this._intakeClockWrite=this._intakeClockWrite.then(()=>this.user.putStrategyState(c,INTAKE_CLOCK_KEY,t)).catch(t=>logger.warn(`[Pipeline:regulators] Could not save the intake clock: ${t}`))}async buildContext(){let t=1e3,c;try{c=toCourseElo((await this.user.getCourseRegDoc(this.course.getCourseID())).elo),t=c.global.score}catch(t){logger.debug(`[Pipeline] Could not get user ELO, using default: ${t}`)}this._cachedOrchestration||(this._cachedOrchestration=await createOrchestrationContext(this.user,this.course));let u=this._cachedOrchestration;return{user:this.user,course:this.course,userElo:t,...c?{userCourseElo:c}:{},orchestration:u}}getCourseID(){return this.course.getCourseID()}async getOrchestrationContext(){return createOrchestrationContext(this.user,this.course)}getStrategyIds(){let t=[],extractId=t=>t.strategyId?t.strategyId:null,c=extractId(this.generator);c&&t.push(c),this.generator.generators&&Array.isArray(this.generator.generators)&&this.generator.generators.forEach(c=>{let u=extractId(c);u&&t.push(u)});for(let c of this.filters){let u=extractId(c);u&&t.push(u)}return[...new Set(t)]}async getTagEloStatus(t){let c=toCourseElo((await this.user.getCourseRegDoc(this.course.getCourseID())).elo),u={};if(t){let d=Array.isArray(t)?t:[t];for(let t of d){let d=globToRegex(t);for(let[t,m]of Object.entries(c.tags))d.test(t)&&(u[t]={score:m.score,count:m.count})}}else for(let[t,d]of Object.entries(c.tags))u[t]={score:d.score,count:d.count};return u}async forecast(t){let c=t?.threshold??.1,u=t?.unseenOnly??!0,d=this.course.getCourseID(),m=(await this.course.getAllCardIds()).map(t=>({cardId:t,courseId:d,score:1,provenance:[]}));m=await this.hydrateTags(m);let g=m.slice(),b=await this.buildContext();for(let t of this.forecastFilters())m=await t.transform(m,b);if(t?.hints&&(m=this.applyHints(m,t.hints,g)),m=m.filter(t=>t.score>=c),u){let t;try{t=new Set(await this.user.getSeenCards(d))}catch{t=new Set}m=m.filter(c=>!t.has(c.cardId))}return m.sort((t,c)=>c.score-t.score),t?.limit?m.slice(0,t.limit):m}forecastFilters(){return this.filters.filter(t=>!t.liveOnly)}async diagnoseCardSpace(t){let c=t?.threshold??.1,u=performance.now(),d=await this.course.getAllCardIds(),m=d.map(t=>({cardId:t,courseId:this.course.getCourseID(),score:1,provenance:[]}));m=await this.hydrateTags(m);let g=await this.buildContext(),b=[];for(let t of this.forecastFilters()){m=await t.transform(m,g);let u=m.filter(t=>t.score>=c).length;b.push({name:t.name,wellIndicated:u})}let S=m.filter(t=>t.score>=c),C=new Set(S.map(t=>t.cardId)),w;try{let t=this.course.getCourseID(),c=await this.user.getSeenCards(t);w=new Set(c)}catch{w=new Set}let T=S.filter(t=>!w.has(t.cardId)),E=new Map;for(let t of m){let u=t.cardId.split(`-`)[1]||`unknown`;E.has(u)||E.set(u,{total:0,wellIndicated:0,new:0});let d=E.get(u);d.total++,t.score>=c&&(d.wellIndicated++,w.has(t.cardId)||d.new++)}let D=performance.now()-u,O={totalCards:d.length,threshold:c,wellIndicated:C.size,encountered:w.size,wellIndicatedNew:T.length,byType:Object.fromEntries(E),filterBreakdown:b,elapsedMs:Math.round(D)};logger.info(`[Pipeline:diagnose] Card space scan (${O.elapsedMs}ms):`),logger.info(`[Pipeline:diagnose] Total cards: ${O.totalCards}`),logger.info(`[Pipeline:diagnose] Well-indicated (score >= ${c}): ${O.wellIndicated}`),logger.info(`[Pipeline:diagnose] Encountered: ${O.encountered}`),logger.info(`[Pipeline:diagnose] Well-indicated & new: ${O.wellIndicatedNew}`),logger.info(`[Pipeline:diagnose] By type:`);for(let[t,c]of E)logger.info(`[Pipeline:diagnose] ${t}: ${c.wellIndicated}/${c.total} well-indicated, ${c.new} new`);logger.info(`[Pipeline:diagnose] After each filter:`);for(let t of b)logger.info(`[Pipeline:diagnose] ${t.name}: ${t.wellIndicated} well-indicated`);return O}}}}),init_versionStamps=__esm({"src/core/versionStamps.ts"(){"use strict";FRAMEWORK_VERSION=`0.2.34`,DEFAULT_STRATEGY_HASH=`default`}}),defaults_exports={},__export(defaults_exports,{createDefaultEloDistanceStrategy:()=>createDefaultEloDistanceStrategy,createDefaultEloStrategy:()=>createDefaultEloStrategy,createDefaultPipeline:()=>createDefaultPipeline,createDefaultSrsStrategy:()=>createDefaultSrsStrategy}),init_defaults=__esm({"src/core/navigators/defaults.ts"(){"use strict";init_navigators(),init_Pipeline(),init_CompositeGenerator(),init_elo(),init_srs(),init_eloDistance(),init_types_legacy(),init_versionStamps()}}),pipelinePlan_exports={},__export(pipelinePlan_exports,{PIPELINE_STAGES:()=>PIPELINE_STAGES,planPipeline:()=>planPipeline}),init_pipelinePlan=__esm({"src/core/navigators/pipelinePlan.ts"(){"use strict";init_navigators(),init_regulators(),init_defaults(),PIPELINE_STAGES=[{key:`generate`,title:`Generate`,summary:`Each generator proposes candidates (up to 500 in all), scored on what is specific to its source. A card proposed by several generators keeps their mean score, raised 10% per extra generator.`},{key:`filter`,title:`Filter`,summary:`Each filter multiplies candidate scores, in the order shown. A gate says a card is not ready yet; a signal expresses preference. Gates usually penalize rather than remove, so a gated card stays in the pool at a low score.`},{key:`drop-zero`,title:`Drop zero scores`,summary:`Candidates whose score reached 0 leave the pool.`},{key:`regulate`,title:`Regulate`,summary:`Balances reviews against new cards. Review mass: the due reviews weighed by their filtered scores; above a healthy level, every review is lifted. Intake: hours since a new card was last presented; new cards no gate penalized are lifted, and the clock stops while there are none.`},{key:`hints`,title:`Apply hints`,summary:`The session's hints (from the app: an intro's follow-up, a difficulty boost) exclude, boost, or require cards. Required cards skip the filters entirely.`},{key:`diversity`,title:`Diversity re-rank`,summary:`Demotes candidates that repeat a distinctive tag already ranked above them, so one concept or answer cannot take the whole head of the queue. Sees this run only, not what the session already served.`},{key:`select`,title:`Select`,summary:`Highest scores first, up to the run's limit. The session mixes them into its supply queue.`}]}}),PipelineAssembler_exports={},__export(PipelineAssembler_exports,{PipelineAssembler:()=>PipelineAssembler}),init_PipelineAssembler=__esm({"src/core/navigators/PipelineAssembler.ts"(){"use strict";init_navigators(),init_WeightedFilter(),init_Pipeline(),init_logger(),init_CompositeGenerator(),init_pipelinePlan(),init_versionStamps(),PipelineAssembler=class{async assemble(t){let{strategies:c,user:u,course:d}=t,m=[];if(c.length===0)return{pipeline:null,generatorStrategies:[],filterStrategies:[],warnings:m};let g=planPipeline(c,d.getCourseID());m.push(...g.warnings);for(let t of[...g.generators,...g.filters])t.origin===`assembler-default`&&logger.debug(`[PipelineAssembler] No ${t.implementingClass} ${t.role} configured, adding default`);let b=g.generators.map(t=>t.strategy),S=g.filters.map(t=>t.strategy);if(b.length===0)return m.push(`No generator strategy found`),{pipeline:null,generatorStrategies:[],filterStrategies:[],warnings:m};let C;b.length===1?(C=await ContentNavigator.create(u,d,b[0]),logger.debug(`[PipelineAssembler] Using single generator: ${b[0].name}`)):(logger.debug(`[PipelineAssembler] Using CompositeGenerator for ${b.length} generators: ${b.map(t=>t.name).join(`, `)}`),C=await CompositeGenerator.fromStrategies(u,d,b));let w=[];for(let t of S)try{let c=await ContentNavigator.create(u,d,t);if(`transform`in c&&typeof c.transform==`function`){let u=c;t.learnable&&(u=new WeightedFilter(u,t.learnable,t.staticWeight,t._id)),w.push(u),logger.debug(`[PipelineAssembler] Added filter: ${t.name}`)}else m.push(`Filter '${t.name}' does not implement CardFilter.transform(), skipping`)}catch(c){m.push(`Failed to instantiate filter '${t.name}': ${c}`)}let T=new Pipeline(C,w,u,d);return T.strategyHash=strategyHash(c),logger.debug(`[PipelineAssembler] Assembled pipeline with ${b.length} generator(s) and ${w.length} filter(s)`),{pipeline:T,generatorStrategies:b,filterStrategies:S,warnings:m}}}}}),init_3=__esm({'import("./**/*") in src/core/navigators/index.ts'(){globImport=__glob({"./Pipeline.ts":()=>Promise.resolve().then(()=>(init_Pipeline(),Pipeline_exports)),"./PipelineAssembler.ts":()=>Promise.resolve().then(()=>(init_PipelineAssembler(),PipelineAssembler_exports)),"./PipelineDebugger.ts":()=>Promise.resolve().then(()=>(init_PipelineDebugger(),PipelineDebugger_exports)),"./SrsDebugger.ts":()=>Promise.resolve().then(()=>(init_SrsDebugger(),SrsDebugger_exports)),"./StrategyPressureDebugger.ts":()=>Promise.resolve().then(()=>(init_StrategyPressureDebugger(),StrategyPressureDebugger_exports)),"./defaults.ts":()=>Promise.resolve().then(()=>(init_defaults(),defaults_exports)),"./diversityRerank.ts":()=>Promise.resolve().then(()=>(init_diversityRerank(),diversityRerank_exports)),"./filters/WeightedFilter.ts":()=>Promise.resolve().then(()=>(init_WeightedFilter(),WeightedFilter_exports)),"./filters/eloDistance.ts":()=>Promise.resolve().then(()=>(init_eloDistance(),eloDistance_exports)),"./filters/hierarchyDefinition.ts":()=>Promise.resolve().then(()=>(init_hierarchyDefinition(),hierarchyDefinition_exports)),"./filters/index.ts":()=>Promise.resolve().then(()=>(init_filters(),filters_exports)),"./filters/inferredPreferenceStub.ts":()=>Promise.resolve().then(()=>(init_inferredPreferenceStub(),inferredPreferenceStub_exports)),"./filters/interferenceMitigator.ts":()=>Promise.resolve().then(()=>(init_interferenceMitigator(),interferenceMitigator_exports)),"./filters/relativePriority.ts":()=>Promise.resolve().then(()=>(init_relativePriority(),relativePriority_exports)),"./filters/types.ts":()=>Promise.resolve().then(()=>(init_types2(),types_exports2)),"./filters/userGoalStub.ts":()=>Promise.resolve().then(()=>(init_userGoalStub(),userGoalStub_exports)),"./filters/userTagPreference.ts":()=>Promise.resolve().then(()=>(init_userTagPreference(),userTagPreference_exports)),"./generators/CompositeGenerator.ts":()=>Promise.resolve().then(()=>(init_CompositeGenerator(),CompositeGenerator_exports)),"./generators/elo.ts":()=>Promise.resolve().then(()=>(init_elo(),elo_exports)),"./generators/index.ts":()=>Promise.resolve().then(()=>(init_generators(),generators_exports)),"./generators/prescribed.ts":()=>Promise.resolve().then(()=>(init_prescribed(),prescribed_exports)),"./generators/srs.ts":()=>Promise.resolve().then(()=>(init_srs(),srs_exports)),"./generators/types.ts":()=>Promise.resolve().then(()=>(init_types(),types_exports)),"./index.ts":()=>Promise.resolve().then(()=>(init_navigators(),navigators_exports)),"./pipelinePlan.ts":()=>Promise.resolve().then(()=>(init_pipelinePlan(),pipelinePlan_exports)),"./regulators.ts":()=>Promise.resolve().then(()=>(init_regulators(),regulators_exports))})}}),navigators_exports={},__export(navigators_exports,{ContentNavigator:()=>ContentNavigator,DIVERSITY_FLOOR:()=>DIVERSITY_FLOOR,DIVERSITY_STRENGTH:()=>DIVERSITY_STRENGTH,NavigatorRole:()=>NavigatorRole,NavigatorRoles:()=>NavigatorRoles,Navigators:()=>Navigators,captureStrategyPressure:()=>captureStrategyPressure,clearSrsBacklogDebug:()=>clearSrsBacklogDebug,clearStrategyPressureDebug:()=>clearStrategyPressureDebug,diversityRerank:()=>diversityRerank,drainCapturedRuns:()=>drainCapturedRuns,getActivePipeline:()=>getActivePipeline,getCardOrigin:()=>getCardOrigin,getRegisteredFilterKind:()=>getRegisteredFilterKind,getRegisteredNavigator:()=>getRegisteredNavigator,getRegisteredNavigatorNames:()=>getRegisteredNavigatorNames,getRegisteredNavigatorRole:()=>getRegisteredNavigatorRole,getRunsForSession:()=>getRunsForSession,getSrsBacklogDebug:()=>getSrsBacklogDebug,getStrategyPressureDebug:()=>getStrategyPressureDebug,hasRegisteredNavigator:()=>hasRegisteredNavigator,initializeNavigatorRegistry:()=>initializeNavigatorRegistry,isFilter:()=>isFilter,isGenerator:()=>isGenerator,mountPipelineDebugger:()=>mountPipelineDebugger,pipelineDebugAPI:()=>pipelineDebugAPI,registerNavigator:()=>registerNavigator,setDebugSessionId:()=>setDebugSessionId}),init_navigators=__esm({"src/core/navigators/index.ts"(){"use strict";init_diversityRerank(),init_PipelineDebugger(),init_SrsDebugger(),init_StrategyPressureDebugger(),init_logger(),init_(),init_2(),init_3(),navigatorRegistry=new Map,Navigators=(t=>(t.ELO=`elo`,t.SRS=`srs`,t.PRESCRIBED=`prescribed`,t.HIERARCHY=`hierarchyDefinition`,t.INTERFERENCE=`interferenceMitigator`,t.RELATIVE_PRIORITY=`relativePriority`,t.USER_TAG_PREFERENCE=`userTagPreference`,t.ELO_DISTANCE=`eloDistance`,t))(Navigators||{}),NavigatorRole=(t=>(t.GENERATOR=`generator`,t.FILTER=`filter`,t))(NavigatorRole||{}),NavigatorRoles={elo:`generator`,srs:`generator`,prescribed:`generator`,hierarchyDefinition:`filter`,interferenceMitigator:`filter`,relativePriority:`filter`,userTagPreference:`filter`,eloDistance:`filter`},ContentNavigator=class{constructor(t,c,u){_defineProperty$2(this,`user`,void 0),_defineProperty$2(this,`course`,void 0),_defineProperty$2(this,`strategyName`,void 0),_defineProperty$2(this,`strategyId`,void 0),_defineProperty$2(this,`learnable`,void 0),_defineProperty$2(this,`staticWeight`,void 0),this.user=t,this.course=c,u&&(this.strategyName=u.name,this.strategyId=u._id,this.learnable=u.learnable,this.staticWeight=u.staticWeight)}get strategyKey(){return this.constructor.name}async getStrategyState(){if(!this.user||!this.course)throw Error(`Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`);return this.user.getStrategyState(this.course.getCourseID(),this.strategyKey)}async putStrategyState(t){if(!this.user||!this.course)throw Error(`Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`);return this.user.putStrategyState(this.course.getCourseID(),this.strategyKey,t)}static async create(t,c,u){let d=u.implementingClass,m=getRegisteredNavigator(d);if(m)return logger.debug(`[ContentNavigator.create] Using registered navigator: ${d}`),new m(t,c,u);logger.debug(`[ContentNavigator.create] Navigator not in registry, attempting dynamic import: ${d}`);let g;for(let t of[`.ts`,`.js`,``]){try{if(g=(await globImport_generators(`./generators/${d}${t}`)).default,g)break}catch(c){logger.debug(`Failed to load generator ${d}${t}:`,c)}try{if(g=(await globImport_filters(`./filters/${d}${t}`)).default,g)break}catch(c){logger.debug(`Failed to load filter ${d}${t}:`,c)}try{if(g=(await globImport(`./${d}${t}`)).default,g)break}catch(c){logger.debug(`Failed to load legacy ${d}${t}:`,c)}if(g)break}if(!g)throw Error(`Could not load navigator implementation for: ${d}`);return new g(t,c,u)}async getWeightedCards(t){throw Error(`${this.constructor.name} must implement getWeightedCards(). `)}setEphemeralHints(t){}}}}),init_courseDB=__esm({"src/impl/couch/courseDB.ts"(){"use strict";init_couch(),init_updateQueue(),init_types_legacy(),init_logger(),init_clientCache(),init_courseAPI(),init_courseLookupDB(),init_navigators(),init_PipelineAssembler(),init_defaults(),CoursesDB=class{constructor(t){_defineProperty$2(this,`_courseIDs`,void 0),t&&t.length>0?this._courseIDs=t:this._courseIDs=void 0}async getCourseList(){let t=await CourseLookup.allCourseWare();return logger.debug(`AllCourses: ${t.map(t=>t.name+`, `+t._id+`
|
|
353
|
+
`)}},mountPipelineDebugger()}}),SrsDebugger_exports={},__export(SrsDebugger_exports,{captureSrsBacklog:()=>captureSrsBacklog,clearSrsBacklogDebug:()=>clearSrsBacklogDebug,getSrsBacklogDebug:()=>getSrsBacklogDebug,noteReviewPressure:()=>noteReviewPressure}),init_SrsDebugger=__esm({"src/core/navigators/SrsDebugger.ts"(){"use strict";snapshots=new Map}}),StrategyPressureDebugger_exports={},__export(StrategyPressureDebugger_exports,{captureStrategyPressure:()=>captureStrategyPressure,clearStrategyPressureDebug:()=>clearStrategyPressureDebug,getStrategyPressureDebug:()=>getStrategyPressureDebug}),init_StrategyPressureDebugger=__esm({"src/core/navigators/StrategyPressureDebugger.ts"(){"use strict";snapshots2=new Map}}),CompositeGenerator_exports={},__export(CompositeGenerator_exports,{AggregationMode:()=>AggregationMode,default:()=>CompositeGenerator}),init_CompositeGenerator=__esm({"src/core/navigators/generators/CompositeGenerator.ts"(){"use strict";init_navigators(),init_logger(),AggregationMode=(t=>(t.MAX=`max`,t.AVERAGE=`average`,t.FREQUENCY_BOOST=`frequencyBoost`,t))(AggregationMode||{}),DEFAULT_AGGREGATION_MODE=`frequencyBoost`,FREQUENCY_BOOST_FACTOR=.1,CompositeGenerator=class _CompositeGenerator extends ContentNavigator{constructor(t,c=DEFAULT_AGGREGATION_MODE){if(super(),_defineProperty$2(this,`name`,`Composite Generator`),_defineProperty$2(this,`generators`,void 0),_defineProperty$2(this,`aggregationMode`,void 0),this.generators=t,this.aggregationMode=c,t.length===0)throw Error(`CompositeGenerator requires at least one generator`);logger.debug(`[CompositeGenerator] Created with ${t.length} generators, mode: ${c}`)}static async fromStrategies(t,c,u,d=DEFAULT_AGGREGATION_MODE){return new _CompositeGenerator(await Promise.all(u.map(u=>ContentNavigator.create(t,c,u))),d)}async getWeightedCards(t,c){if(!c)throw Error(`CompositeGenerator.getWeightedCards requires a GeneratorContext. It should be called via Pipeline, not directly.`);let u=await Promise.all(this.generators.map(u=>u.getWeightedCards(t,c))),d=[];u.forEach((t,c)=>{let u=t.cards,m=this.generators[c].name||`Generator ${c}`,g=u.filter(t=>t.provenance[0]?.reason?.includes(`new card`)),b=u.filter(t=>t.provenance[0]?.reason?.includes(`review`));if(u.length>0){let t=Math.max(...u.map(t=>t.score)).toFixed(2),c=[];g.length>0&&c.push(`${g.length} new`),b.length>0&&c.push(`${b.length} reviews`);let S=c.length>0?c.join(`, `):`${u.length} cards`;d.push(`${m}: ${S} (top: ${t})`)}else d.push(`${m}: 0 cards`)}),logger.info(`[Composite] Generator breakdown: ${d.join(` | `)}`);let m=new Map;u.forEach((t,u)=>{let d=t.cards,g=this.generators[u],b=g.learnable?.weight??1,S;if(g.learnable&&!g.staticWeight&&c.orchestration){let t=g.strategyId;t&&(b=c.orchestration.getEffectiveWeight(t,g.learnable),S=c.orchestration.getDeviation(t))}for(let t of d){t.provenance.length>0&&(t.provenance[0].effectiveWeight=b,t.provenance[0].deviation=S);let c=m.get(t.cardId)||[];c.push({card:t,weight:b}),m.set(t.cardId,c)}});let g=[];for(let[,t]of m){let c=t.map(t=>t.card),u=this.aggregateScores(t),d=Math.max(0,u),m=c.flatMap(t=>t.provenance),b=c[0].score,S=d>b?`boosted`:d<b?`penalized`:`passed`,C=this.buildAggregationReason(t,d);g.push({...c[0],score:d,provenance:[...m,{strategy:`composite`,strategyName:`Composite Generator`,strategyId:`COMPOSITE_GENERATOR`,action:S,score:d,reason:C}]})}return{cards:g.sort((t,c)=>c.score-t.score).slice(0,t),hints:mergeHints(u.map(t=>t.hints))}}buildAggregationReason(t,c){let u=t.map(t=>t.card),d=u.length,m=u.map(t=>t.score.toFixed(2)).join(`, `);if(d===1){let u=Math.abs(t[0].weight-1)>.001?` (w=${t[0].weight.toFixed(2)})`:``;return`Single generator, score ${c.toFixed(2)}${u}`}let g=u.map(t=>t.provenance[0]?.strategy||`unknown`).join(`, `);switch(this.aggregationMode){case`max`:return`Max of ${d} generators (${g}): scores [${m}] \u2192 ${c.toFixed(2)}`;case`average`:return`Weighted Avg of ${d} generators (${g}): scores [${m}] \u2192 ${c.toFixed(2)}`;case`frequencyBoost`:{let u=t.reduce((t,c)=>t+c.weight,0),m=t.reduce((t,c)=>t+c.card.score*c.weight,0),b=u>0?m/u:0,S=1+FREQUENCY_BOOST_FACTOR*(d-1);return`Frequency boost from ${d} generators (${g}): w-avg ${b.toFixed(2)} \xD7 ${S.toFixed(2)} \u2192 ${c.toFixed(2)}`}default:return`Aggregated from ${d} generators: ${c.toFixed(2)}`}}aggregateScores(t){let c=t.map(t=>t.card.score);switch(this.aggregationMode){case`max`:return Math.max(...c);case`average`:{let c=t.reduce((t,c)=>t+c.weight,0);return c===0?0:t.reduce((t,c)=>t+c.card.score*c.weight,0)/c}case`frequencyBoost`:{let c=t.reduce((t,c)=>t+c.weight,0),u=t.reduce((t,c)=>t+c.card.score*c.weight,0);return(c>0?u/c:0)*(1+FREQUENCY_BOOST_FACTOR*(t.length-1))}default:return c[0]}}}}}),elo_exports={},__export(elo_exports,{default:()=>ELONavigator}),init_elo=__esm({"src/core/navigators/generators/elo.ts"(){"use strict";init_navigators(),init_logger(),ELONavigator=class extends ContentNavigator{constructor(t,c,u){super(t,c,u),_defineProperty$2(this,`name`,void 0),this.name=u?.name||`ELO`}async getWeightedCards(t,c){let u;u=c?.userElo===void 0?toCourseElo((await this.user.getCourseRegDoc(this.course.getCourseID())).elo).global.score:c.userElo;let[d,m]=await Promise.all([this.user.getActiveCards(),this.user.getSeenCards(this.course.getCourseID()).catch(()=>[])]),g=new Set([...d.map(t=>t.cardID),...m]),b=(await this.course.getCardsCenteredAtELO({limit:t,elo:`user`},t=>!g.has(t.cardID))).map(t=>({...t,status:`new`})).map(t=>{let c=t.elo??1e3,d=Math.abs(c-u),m=.5+.5*Math.random();return{cardId:t.cardID,courseId:t.courseID,score:m,cardElo:c,provenance:[{strategy:`elo`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-ELO-default`,action:`generated`,score:m,reason:`new card near learner ELO: distance ${Math.round(d)} (card: ${Math.round(c)}, user: ${Math.round(u)}), jitter ${m.toFixed(3)}`}]}});b.sort((t,c)=>c.score-t.score);let S=b.slice(0,t);if(S.length>0){let t=S.slice(0,3).map(t=>t.score.toFixed(2)).join(`, `);logger.info(`[ELO] Course ${this.course.getCourseID()}: ${S.length} new cards (top scores: ${t})`)}else logger.info(`[ELO] Course ${this.course.getCourseID()}: No new cards available`);return{cards:S}}}}}),generators_exports={},init_generators=__esm({"src/core/navigators/generators/index.ts"(){"use strict";}}),prescribed_exports={},__export(prescribed_exports,{default:()=>PrescribedCardsGenerator,unmetIntroExposeTags:()=>unmetIntroExposeTags}),init_prescribed=__esm({"src/core/navigators/generators/prescribed.ts"(){"use strict";init_navigators(),init_StrategyPressureDebugger(),init_logger(),DEFAULT_FRESHNESS_WINDOW=3,DEFAULT_MAX_DIRECT_PER_RUN=3,DEFAULT_MAX_SUPPORT_PER_RUN=3,DEFAULT_HIERARCHY_DEPTH=2,DEFAULT_MIN_COUNT=3,DEFAULT_PRACTICE_MIN_COUNT=3,DEFAULT_MAX_PRACTICE_PER_RUN=4,BASE_TARGET_SCORE=1,BASE_SUPPORT_SCORE=.8,DISCOVERED_SUPPORT_SCORE=12,BASE_PRACTICE_SCORE=1,PRACTICE_BASE_MULT=2,MAX_PRACTICE_MULTIPLIER=4,PRACTICE_STALENESS_BUMP_PER_DAY=.5,MAX_TARGET_MULTIPLIER=8,MAX_SUPPORT_MULTIPLIER=4,PRESCRIBED_DEBUG_VERSION=`testversion-prescribed-v3`,PrescribedCardsGenerator=class extends ContentNavigator{constructor(t,c,u){super(t,c,u),_defineProperty$2(this,`name`,void 0),_defineProperty$2(this,`config`,void 0),this.name=u.name||`Prescribed Cards`,this.config=this.parseConfig(u.serializedData),logger.debug(`[Prescribed] Initialized with ${this.config.groups.length} groups and ${this.config.groups.reduce((t,c)=>t+c.targetCardIds.length,0)} targets`)}get strategyKey(){return`PrescribedProgress`}async getWeightedCards(t,c){if(this.config.groups.length===0||t<=0)return{cards:[]};let u=this.course.getCourseID(),d=await this.user.getActiveCards(),m=new Set(d.map(t=>t.cardID)),g=await this.user.getSeenCards(u).catch(()=>[]),b=new Set(g),S=await this.getStrategyState()??{updatedAt:isoNow(),groups:{}},C=await this.loadHierarchyConfigs(),w=await this.user.getCourseRegDoc(u).catch(()=>null),T=typeof w?.elo==`number`?w.elo:w?.elo?.global?.score??c?.userElo??1e3,E=typeof w?.elo==`number`?{}:w?.elo?.tags??{},D=dedupe(this.config.groups.flatMap(t=>t.targetCardIds)),O=dedupe(this.config.groups.flatMap(t=>t.supportCardIds??[])),xr=dedupe([...D,...O]),Sr=xr.length>0?await this.course.getAppliedTagsBatch(xr):new Map,Cr=await this.course.getCourseTagStubs().catch(()=>({rows:[],offset:0,total_rows:0})),wr=new Map;for(let t of Cr.rows??[]){let c=t.doc;c?.name&&Array.isArray(c.taggedCards)&&wr.set(c.name,[...c.taggedCards])}let Tr={updatedAt:isoNow(),groups:{}},Er=[],Dr=new Set,Or=[],kr=S.practiceDebt??{},Ar={},jr=new Map;for(let t of this.config.groups){let c=this.buildGroupRuntimeState({group:t,priorState:S.groups[t.id],activeIds:m,seenIds:b,tagsByCard:Sr,cardsByTag:wr,hierarchyConfigs:C,userTagElo:E,userGlobalElo:T});Or.push(c),logger.info(`[Prescribed] Group '${t.id}': ${t.targetCardIds.length} targets total, ${c.encounteredTargets.size} encountered, ${c.pendingTargets.length} pending (${c.surfaceableTargets.length} surfaceable, ${c.blockedTargets.length} blocked), ${c.supportCandidates.length} authored support candidates, ${c.discoveredSupportCandidates.length} discovered support candidates, pressure=${c.pressureMultiplier.toFixed(2)}`),c.blockedTargets.length>0&&(logger.info(`[Prescribed] Group '${t.id}' blocked targets: ${c.blockedTargets.join(`, `)}`),logger.info(`[Prescribed] Group '${t.id}' support tags needed: ${c.supportTags.join(`, `)||`(none)`}`),logger.info(`[Prescribed] Group '${t.id}' escalation mode: `+(c.supportCandidates.length>0?`direct-support`:c.discoveredSupportCandidates.length>0?`inserted-support-candidates`:`boost-only`)),c.discoveredSupportCandidates.length>0&&logger.info(`[Prescribed] Group '${t.id}' discovered support candidates: ${c.discoveredSupportCandidates.join(`, `)}`)),Tr.groups[t.id]=this.buildNextGroupState(c,S.groups[t.id]);let d=this.buildDirectTargetCards(c,u,Dr),g=this.buildSupportCards(c,u,Dr),w=this.buildDiscoveredSupportCards(c,u,Dr),D=this.buildPracticeCards({group:t,courseId:u,emittedIds:Dr,cardsByTag:wr,hierarchyConfigs:C,userTagElo:E,userGlobalElo:T,activeIds:m,seenIds:b,priorPracticeDebt:kr,nextPracticeDebt:Ar});jr.set(t.id,D.debts),Er.push(...d,...g,...w,...D.cards)}Tr.practiceDebt=Ar;let Mr=this.buildSupportHintSummary(Or),Nr=Object.keys(Mr.boostTags).length>0?{boostTags:Mr.boostTags,_label:`prescribed-support (${Mr.supportTags.length} tags; blocked=${Mr.blockedTargetIds.length}; testversion=${PRESCRIBED_DEBUG_VERSION})`}:void 0;if(Nr){let t=Object.entries(Nr.boostTags??{});logger.info(`[Prescribed] Emitting ${t.length} boost hint(s): `+t.map(([t,c])=>`${t}\xD7${c.toFixed(1)}`).join(`, `))}else logger.info(`[Prescribed] No hints to emit (no blocked targets or no support tags)`);if(this.capturePressureSnapshot(u,Or,jr,Er,Nr),Er.length===0)return logger.info(`[Prescribed] 0 cards emitted (all targets blocked, authored/discovered support candidates exhausted)`+(Nr?` — boost hints emitted but may not survive filters`:``)),await this.putStrategyState(Tr).catch(t=>{logger.debug(`[Prescribed] Failed to persist empty-state update: ${t}`)}),Nr?{cards:[],hints:Nr}:{cards:[]};let Pr=pickTopByScore(Er,t),Fr=new Map;for(let t of Pr){let c=t.provenance[0];if(c?.reason.includes(`mode=practice`))continue;let u=c?.reason.match(/group=([^;]+)/)?.[1],d=c?.reason.includes(`mode=support`)?`supportIds`:`targetIds`;u&&(Fr.has(u)||Fr.set(u,{targetIds:[],supportIds:[]}),Fr.get(u)[d].push(t.cardId))}for(let t of this.config.groups){let c=Tr.groups[t.id],u=Fr.get(t.id);u&&(u.targetIds.length>0||u.supportIds.length>0)&&(c.lastSurfacedAt=isoNow(),c.sessionsSinceSurfaced=0,u.supportIds.length>0&&(c.lastSupportAt=isoNow()))}return await this.putStrategyState(Tr).catch(t=>{logger.debug(`[Prescribed] Failed to persist prescribed progress: ${t}`)}),logger.info(`[Prescribed] Emitting ${Pr.length} cards (${Pr.filter(t=>t.provenance[0]?.reason.includes(`mode=target`)).length} target, ${Pr.filter(t=>t.provenance[0]?.reason.includes(`mode=support`)).length} support, ${Pr.filter(t=>t.provenance[0]?.reason.includes(`mode=discovered-support`)).length} discovered support)`),Nr?{cards:Pr,hints:Nr}:{cards:Pr}}buildSupportHintSummary(t){let c={},u=new Set,d=new Set;for(let m of t)if(!(m.blockedTargets.length===0||m.supportTags.length===0)){m.blockedTargets.forEach(t=>u.add(t));for(let t of m.supportTags)d.add(t),c[t]=(c[t]??1)*m.supportMultiplier}return{boostTags:c,blockedTargetIds:[...u].sort(),supportTags:[...d].sort()}}capturePressureSnapshot(t,c,u,d,m){let g=Date.now(),b=[];for(let t of c){let c=t.group,d=c.freshnessWindowSessions??DEFAULT_FRESHNESS_WINDOW;if(b.push({id:`group:${c.id}:target`,label:`${c.id} targets`,multiplier:t.pressureMultiplier,max:MAX_TARGET_MULTIPLIER,detail:`${t.pendingTargets.length} pending (${t.surfaceableTargets.length} surfaceable, ${t.blockedTargets.length} blocked) \xB7 sinceSurfaced ${t.sessionsSinceSurfaced}/${d}`,items:t.blockedTargets.map(t=>({label:t,value:`blocked`}))}),t.blockedTargets.length>0){let u=t.supportCandidates.length>0?`direct-support`:t.discoveredSupportCandidates.length>0?`inserted-support`:`boost-only`;b.push({id:`group:${c.id}:support`,label:`${c.id} support`,multiplier:t.supportMultiplier,max:MAX_SUPPORT_MULTIPLIER,detail:`mode=${u} \xB7 ${t.supportTags.length} support tag(s)`,items:t.supportTags.map(t=>({label:t}))})}let m=u.get(c.id)??[];m.length>0&&b.push({id:`group:${c.id}:practice-debt`,label:`${c.id} practice debt`,multiplier:Math.max(...m.map(t=>t.multiplier)),max:MAX_PRACTICE_MULTIPLIER,detail:`${m.length} under-practiced skill(s)`,items:m.map(t=>({label:t.tag,value:`\xD7${t.multiplier.toFixed(2)} \xB7 open ${formatAge(g-new Date(t.firstOwedAt).getTime())}`}))})}captureStrategyPressure({source:`prescribed`,courseId:t,gauges:b,topScore:d.length>0?Math.max(...d.map(t=>t.score)):null,hintsLabel:m?._label,timestamp:g})}parseConfig(t){try{let c=JSON.parse(t);return{groups:(Array.isArray(c.groups)?c.groups:[]).map((t,c)=>({id:typeof t.id==`string`&&t.id.trim().length>0?t.id:`group-${c+1}`,targetCardIds:dedupe(Array.isArray(t.targetCardIds)?t.targetCardIds.filter(t=>typeof t==`string`):[]),supportCardIds:dedupe(Array.isArray(t.supportCardIds)?t.supportCardIds.filter(t=>typeof t==`string`):[]),supportTagPatterns:dedupe(Array.isArray(t.supportTagPatterns)?t.supportTagPatterns.filter(t=>typeof t==`string`):[]),freshnessWindowSessions:typeof t.freshnessWindowSessions==`number`?t.freshnessWindowSessions:DEFAULT_FRESHNESS_WINDOW,maxDirectTargetsPerRun:typeof t.maxDirectTargetsPerRun==`number`?t.maxDirectTargetsPerRun:DEFAULT_MAX_DIRECT_PER_RUN,maxSupportCardsPerRun:typeof t.maxSupportCardsPerRun==`number`?t.maxSupportCardsPerRun:DEFAULT_MAX_SUPPORT_PER_RUN,introExposeMinCount:typeof t.introExposeMinCount==`number`?t.introExposeMinCount:DEFAULT_MIN_COUNT,hierarchyWalk:{enabled:t.hierarchyWalk?.enabled!==!1,maxDepth:typeof t.hierarchyWalk?.maxDepth==`number`?t.hierarchyWalk.maxDepth:DEFAULT_HIERARCHY_DEPTH},retireOnEncounter:t.retireOnEncounter!==!1,practiceTagPatterns:dedupe(Array.isArray(t.practiceTagPatterns)?t.practiceTagPatterns.filter(t=>typeof t==`string`):[]),practiceMinCount:typeof t.practiceMinCount==`number`?t.practiceMinCount:DEFAULT_PRACTICE_MIN_COUNT,maxPracticeCardsPerRun:typeof t.maxPracticeCardsPerRun==`number`?t.maxPracticeCardsPerRun:DEFAULT_MAX_PRACTICE_PER_RUN})).filter(t=>t.targetCardIds.length>0)}}catch{return{groups:[]}}}async loadHierarchyConfigs(){try{return(await this.course.getAllNavigationStrategies()).filter(t=>t.implementingClass===`hierarchyDefinition`).map(t=>{try{return{prerequisites:JSON.parse(t.serializedData).prerequisites||{}}}catch{return{prerequisites:{}}}})}catch(t){return logger.debug(`[Prescribed] Failed to load hierarchy configs: ${t}`),[]}}buildGroupRuntimeState(t){let{group:c,priorState:u,activeIds:d,seenIds:m,tagsByCard:g,cardsByTag:b,hierarchyConfigs:S,userTagElo:C,userGlobalElo:w}=t,T=new Set;for(let t of c.targetCardIds)(d.has(t)||m.has(t))&&T.add(t);if(u?.encounteredCardIds?.length)for(let t of u.encounteredCardIds)T.add(t);let E=c.targetCardIds.filter(t=>!T.has(t)),D=new Map;for(let t of E)D.set(t,g.get(t)??[]);let O=[],xr=[],Sr=new Set;for(let t of E){let u=D.get(t)??[],d=this.resolveBlockedSupportTags(u,S,C,w,c.hierarchyWalk?.enabled!==!1,c.hierarchyWalk?.maxDepth??DEFAULT_HIERARCHY_DEPTH),m=unmetIntroExposeTags(u,C,c.introExposeMinCount??DEFAULT_MIN_COUNT);m.length>0&&m.forEach(t=>Sr.add(t)),d.blocked||m.length>0?(O.push(t),d.supportTags.forEach(t=>Sr.add(t))):xr.push(t)}let Cr=dedupe([...c.supportCardIds??[],...this.findSupportCardsByTags(c,g,[...Sr])]).filter(t=>!d.has(t)&&!m.has(t)),wr=O.length>0&&Sr.size>0&&Cr.length===0?this.findDiscoveredSupportCards({supportTags:[...Sr],cardsByTag:b,activeIds:d,seenIds:m,excludedIds:new Set([...c.targetCardIds,...c.supportCardIds??[]]),limit:c.maxSupportCardsPerRun??DEFAULT_MAX_SUPPORT_PER_RUN}):[];O.length>0&&Sr.size>0&&wr.length===0&&logger.info(`[Prescribed] Group '${c.id}' discovered 0 broader support candidates (blocked=${O.length}; authoredSupport=${Cr.length})`);let Tr=u?.sessionsSinceSurfaced??0,Er=c.freshnessWindowSessions??DEFAULT_FRESHNESS_WINDOW,Dr=Math.max(0,Tr-Er),Or=E.length===0?1:clamp(1+Dr*.75+Math.min(2,E.length*.1),1,MAX_TARGET_MULTIPLIER),kr=O.length===0?1:clamp(1+Dr*.5+Math.min(1.5,O.length*.15),1,MAX_SUPPORT_MULTIPLIER);return{group:c,encounteredTargets:T,pendingTargets:E,blockedTargets:O,surfaceableTargets:xr,targetTags:D,supportCandidates:Cr,discoveredSupportCandidates:wr,supportTags:[...Sr],pressureMultiplier:Or,supportMultiplier:kr,sessionsSinceSurfaced:Tr,debugVersion:PRESCRIBED_DEBUG_VERSION}}buildNextGroupState(t,c){let u=c?.sessionsSinceSurfaced??0,d=!1;return{encounteredCardIds:[...t.encounteredTargets].sort(),pendingTargetIds:[...t.pendingTargets].sort(),lastSurfacedAt:c?.lastSurfacedAt??null,sessionsSinceSurfaced:u+1,lastSupportAt:c?.lastSupportAt??null,blockedTargetIds:[...t.blockedTargets].sort(),lastResolvedSupportTags:[...t.supportTags].sort()}}buildDirectTargetCards(t,c,u){let d=t.group.maxDirectTargetsPerRun??DEFAULT_MAX_DIRECT_PER_RUN,m=t.surfaceableTargets.filter(t=>!u.has(t)).slice(0,d),g=[];for(let d of m)u.add(d),g.push({cardId:d,courseId:c,score:BASE_TARGET_SCORE*t.pressureMultiplier,provenance:[{strategy:`prescribed`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-prescribed`,action:`generated`,score:BASE_TARGET_SCORE*t.pressureMultiplier,reason:`mode=target;group=${t.group.id};pending=${t.pendingTargets.length};surfaceable=${t.surfaceableTargets.length};blocked=${t.blockedTargets.length};blockedTargets=${t.blockedTargets.join(`|`)||`none`};supportTags=${t.supportTags.join(`|`)||`none`};multiplier=${t.pressureMultiplier.toFixed(2)};testversion=${t.debugVersion}`}]});return g}buildSupportCards(t,c,u){if(t.blockedTargets.length===0||t.supportCandidates.length===0)return[];let d=t.group.maxSupportCardsPerRun??DEFAULT_MAX_SUPPORT_PER_RUN,m=t.supportCandidates.filter(t=>!u.has(t)).slice(0,d),g=[];for(let d of m)u.add(d),g.push({cardId:d,courseId:c,score:BASE_SUPPORT_SCORE*t.supportMultiplier,provenance:[{strategy:`prescribed`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-prescribed`,action:`generated`,score:BASE_SUPPORT_SCORE*t.supportMultiplier,reason:`mode=support;group=${t.group.id};pending=${t.pendingTargets.length};blocked=${t.blockedTargets.length};blockedTargets=${t.blockedTargets.join(`|`)||`none`};supportCard=${d};supportTags=${t.supportTags.join(`|`)||`none`};multiplier=${t.supportMultiplier.toFixed(2)};testversion=${t.debugVersion}`}]});return g}buildDiscoveredSupportCards(t,c,u){if(t.blockedTargets.length===0||t.discoveredSupportCandidates.length===0)return[];let d=t.group.maxSupportCardsPerRun??DEFAULT_MAX_SUPPORT_PER_RUN,m=t.discoveredSupportCandidates.filter(t=>!u.has(t)).slice(0,d),g=[];for(let d of m)u.add(d),g.push({cardId:d,courseId:c,score:DISCOVERED_SUPPORT_SCORE*t.supportMultiplier,provenance:[{strategy:`prescribed`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-prescribed`,action:`generated`,score:DISCOVERED_SUPPORT_SCORE*t.supportMultiplier,reason:`mode=discovered-support;group=${t.group.id};pending=${t.pendingTargets.length};blocked=${t.blockedTargets.length};blockedTargets=${t.blockedTargets.join(`|`)||`none`};supportCard=${d};supportTags=${t.supportTags.join(`|`)||`none`};multiplier=${t.supportMultiplier.toFixed(2)};testversion=${t.debugVersion}`}]});return g}buildPracticeCards(t){let{group:c,courseId:u,emittedIds:d,cardsByTag:m,hierarchyConfigs:g,userTagElo:b,userGlobalElo:S,activeIds:C,seenIds:w,priorPracticeDebt:T,nextPracticeDebt:E}=t,D=c.practiceTagPatterns??[];if(D.length===0)return{cards:[],debts:[]};let O=c.practiceMinCount??DEFAULT_PRACTICE_MIN_COUNT,xr=c.maxPracticeCardsPerRun??DEFAULT_MAX_PRACTICE_PER_RUN,Sr=[...m.keys()].filter(t=>D.some(c=>matchesTagPattern(t,c))&&this.isUnlockedGatedSkill(t,g,b,S)&&(b[t]?.count??0)<O);if(Sr.length===0)return{cards:[],debts:[]};let Cr=Date.now(),wr=1440*60*1e3,Tr=new Map;for(let t of Sr){let c=T[t]??isoNow();E[t]=c;let u=Math.max(0,(Cr-new Date(c).getTime())/864e5),d=clamp(PRACTICE_BASE_MULT+u*PRACTICE_STALENESS_BUMP_PER_DAY,PRACTICE_BASE_MULT,MAX_PRACTICE_MULTIPLIER);Tr.set(t,d)}let Er=Sr.map(t=>({tag:t,multiplier:Tr.get(t)??PRACTICE_BASE_MULT,firstOwedAt:E[t]})).sort((t,c)=>c.multiplier-t.multiplier||t.tag.localeCompare(c.tag)),Dr=this.findDiscoveredSupportCards({supportTags:Sr,cardsByTag:m,activeIds:C,seenIds:w,excludedIds:d,limit:xr});if(Dr.length===0)return{cards:[],debts:Er};logger.info(`[Prescribed] Group '${c.id}' practice: ${Sr.length} unlocked under-practiced skill(s), emitting ${Dr.length} drill card(s)`);let Or=[];for(let t of Dr){d.add(t);let g=PRACTICE_BASE_MULT;for(let c of Sr)(m.get(c)?.includes(t)??!1)&&(g=Math.max(g,Tr.get(c)??PRACTICE_BASE_MULT));let b=BASE_PRACTICE_SCORE*g;Or.push({cardId:t,courseId:u,score:b,provenance:[{strategy:`prescribed`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-prescribed`,action:`generated`,score:b,reason:`mode=practice;group=${c.id};debtMult=\xD7${g.toFixed(2)};underPracticedSkills=${Sr.length};practiceTags=${Sr.slice(0,8).join(`|`)}${Sr.length>8?`|…`:``};testversion=${PRESCRIBED_DEBUG_VERSION}`}]})}return{cards:Or,debts:Er}}isUnlockedGatedSkill(t,c,u,d){let m=c.map(c=>c.prerequisites[t]).filter(t=>Array.isArray(t)&&t.length>0);return m.length===0?!1:m.every(t=>t.every(t=>this.isPrerequisiteMet(t,u[t.tag],d)))}findSupportCardsByTags(t,c,u){if(u.length===0)return[];let d=t.supportCardIds??[],m=t.supportTagPatterns??[];if(d.length===0&&m.length===0)return[];let g=new Set;for(let t of d){let d=c.get(t)??[],b=u.some(t=>d.includes(t)),S=m.some(t=>d.some(c=>matchesTagPattern(c,t)));(b||S)&&g.add(t)}return[...g]}findDiscoveredSupportCards(t){let{supportTags:c,cardsByTag:u,activeIds:d,seenIds:m,excludedIds:g,limit:b}=t,S=new Map;for(let t of c){let c=u.get(t)??[];for(let t of c){if(d.has(t)||m.has(t)||g.has(t))continue;let c=S.get(t);c?c.matches+=1:S.set(t,{cardId:t,matches:1})}}let C=[...S.values()].sort((t,c)=>c.matches-t.matches||t.cardId.localeCompare(c.cardId)),w=new Set,T=[],E=[];for(let t of C){let c=extractWordStem(t.cardId);w.has(c)?E.push(t):(w.add(c),T.push(t))}return shuffleInPlace(T),shuffleInPlace(E),[...T,...E].slice(0,b).map(t=>t.cardId)}resolveBlockedSupportTags(t,c,u,d,m,g){let b=new Set,S=!1;for(let C of t){let t=c.map(t=>t.prerequisites[C]).filter(t=>Array.isArray(t)&&t.length>0);if(t.length!==0&&t.some(t=>t.some(t=>!this.isPrerequisiteMet(t,u[t.tag],d)))){if(S=!0,!m){for(let c of t)for(let t of c)this.isPrerequisiteMet(t,u[t.tag],d)||b.add(t.tag);continue}for(let m of t)for(let t of m)this.isPrerequisiteMet(t,u[t.tag],d)||this.collectSupportTagsRecursive(t.tag,c,u,d,g,new Set,b)}}return{blocked:S,supportTags:[...b]}}collectSupportTagsRecursive(t,c,u,d,m,g,b){if(m<0||g.has(t))return;g.add(t);let S=!1;for(let C of c){let w=C.prerequisites[t];if(!w||w.length===0)continue;let T=w.filter(t=>!this.isPrerequisiteMet(t,u[t.tag],d));if(T.length>0&&m>0){S=!0;for(let t of T)this.collectSupportTagsRecursive(t.tag,c,u,d,m-1,g,b)}}S||b.add(t)}isPrerequisiteMet(t,c,u){if(!c)return!1;let d=t.masteryThreshold?.minCount??DEFAULT_MIN_COUNT;return c.count<d?!1:t.masteryThreshold?.minElo===void 0?t.masteryThreshold?.minCount===void 0?c.score>=u:!0:c.score>=t.masteryThreshold.minElo}}}}),regulators_exports={},__export(regulators_exports,{DEFAULT_REGULATOR_CONFIG:()=>DEFAULT_REGULATOR_CONFIG,INTAKE_CLOCK_KEY:()=>INTAKE_CLOCK_KEY,applyReading:()=>applyReading,frozenMsAt:()=>frozenMsAt,intakeHours:()=>intakeHours,intakeReading:()=>intakeReading,resetIntakeClock:()=>resetIntakeClock,reviewMassReading:()=>reviewMassReading,reviewWeight:()=>reviewWeight,stepIntakeClock:()=>stepIntakeClock}),init_regulators=__esm({"src/core/navigators/regulators.ts"(){"use strict";DEFAULT_REGULATOR_CONFIG={reviewMass:{referenceScore:.95,healthyMass:20,rate:2},intake:{rate:2,scaleHours:24}},INTAKE_CLOCK_KEY=`IntakeClock`,REGULATOR_LABEL={"review-mass":`Review mass`,intake:`Intake`}}}),srs_exports={},__export(srs_exports,{default:()=>SRSNavigator}),init_srs=__esm({"src/core/navigators/generators/srs.ts"(){"use strict";init_navigators(),init_SrsDebugger(),init_regulators(),init_logger(),SRSNavigator=class extends ContentNavigator{constructor(t,c,u){super(t,c,u),_defineProperty$2(this,`name`,void 0),this.name=u?.name||`SRS`}async getWeightedCards(t,c){if(!this.user||!this.course)throw Error(`SRSNavigator requires user and course to be set`);let u=this.course.getCourseID(),d=await this.user.getPendingReviews(u),m=hooks.utc(),g=d.filter(t=>m.isAfter(hooks.utc(t.reviewTime)));if(g.length>0){let t=[...new Set(g.map(t=>t.cardId))],c=await this.course.getAppliedTagsBatch(t),u=[];if(g=g.filter(t=>(c.get(t.cardId)??[]).includes(`srs:skip`)?(u.push(t._id),!1):!0),u.length>0){logger.info(`[SRS] Removing ${u.length} scheduled reviews for srs:skip cards`);for(let t of u)this.user.removeScheduledCardReview(t)}}let b=d.filter(t=>!m.isAfter(hooks.utc(t.reviewTime))),S=null;if(b.length>0){let t=b.reduce((t,c)=>hooks.utc(t.reviewTime).isBefore(hooks.utc(c.reviewTime))?t:c),c=hooks.duration(hooks.utc(t.reviewTime).diff(m));S=c.asHours()<1?`${Math.round(c.asMinutes())}m`:c.asHours()<24?`${Math.round(c.asHours())}h`:`${Math.round(c.asDays())}d`}if(g.length>0)logger.info(`[SRS] Course ${u}: ${g.length} reviews due now (of ${d.length} scheduled)`);else if(d.length>0){let t=[...d].sort((t,c)=>hooks.utc(t.reviewTime).diff(hooks.utc(c.reviewTime)))[0],c=hooks.utc(t.reviewTime),g=hooks.duration(c.diff(m)),b=g.asHours()<1?`${Math.round(g.asMinutes())}m`:g.asHours()<24?`${Math.round(g.asHours())}h`:`${Math.round(g.asDays())}d`;logger.info(`[SRS] Course ${u}: 0 reviews due now (${d.length} scheduled, next in ${b})`)}else logger.info(`[SRS] Course ${u}: No reviews scheduled`);let C=g.map(t=>{let{score:c,urgency:u,reason:d}=this.computeUrgencyScore(t,m);return{cardId:t.cardId,courseId:t.courseId,score:c,reviewUrgency:u,reviewID:t._id,provenance:[{strategy:`srs`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-SRS-default`,action:`generated`,score:c,reason:d}]}}).sort((t,c)=>c.score-t.score);return captureSrsBacklog({courseId:u,scheduledTotal:d.length,dueNow:g.length,healthyBacklog:DEFAULT_REGULATOR_CONFIG.reviewMass.healthyMass,reviewMass:null,backlogMultiplier:1,backlogGrowthRate:DEFAULT_REGULATOR_CONFIG.reviewMass.rate,topReviewScore:C.length>0?C[0].score:null,nextDueIn:S,timestamp:Date.now()}),{cards:C.slice(0,t)}}computeUrgencyScore(t,c){let u=hooks.utc(t.scheduledAt),d=hooks.utc(t.reviewTime),m=Math.max(1,d.diff(u,`hours`)),g=c.diff(d,`hours`),b=g/m,S=.3+.7*Math.exp(-m/720),C=Math.min(1,Math.max(0,b))*.5+S*.5,w=.5+C*.45,T=[`${Math.round(g)}h overdue`,`interval: ${Math.round(m)}h`,`relative: ${b.toFixed(2)}`,`recency: ${S.toFixed(2)}`];return T.push(`review`),{score:w,urgency:C,reason:T.join(`, `)}}}}}),types_exports={},init_types=__esm({"src/core/navigators/generators/types.ts"(){"use strict";}}),init_=__esm({'import("./generators/**/*") in src/core/navigators/index.ts'(){globImport_generators=__glob({"./generators/CompositeGenerator.ts":()=>Promise.resolve().then(()=>(init_CompositeGenerator(),CompositeGenerator_exports)),"./generators/elo.ts":()=>Promise.resolve().then(()=>(init_elo(),elo_exports)),"./generators/index.ts":()=>Promise.resolve().then(()=>(init_generators(),generators_exports)),"./generators/prescribed.ts":()=>Promise.resolve().then(()=>(init_prescribed(),prescribed_exports)),"./generators/srs.ts":()=>Promise.resolve().then(()=>(init_srs(),srs_exports)),"./generators/types.ts":()=>Promise.resolve().then(()=>(init_types(),types_exports))})}}),init_contentNavigationStrategy=__esm({"src/core/types/contentNavigationStrategy.ts"(){"use strict";DEFAULT_LEARNABLE_WEIGHT={weight:1,confidence:.1,sampleSize:0}}}),WeightedFilter_exports={},__export(WeightedFilter_exports,{WeightedFilter:()=>WeightedFilter}),init_WeightedFilter=__esm({"src/core/navigators/filters/WeightedFilter.ts"(){"use strict";init_contentNavigationStrategy(),WeightedFilter=class{constructor(t,c=DEFAULT_LEARNABLE_WEIGHT,u=!1,d){_defineProperty$2(this,`name`,void 0),_defineProperty$2(this,`kind`,void 0),_defineProperty$2(this,`liveOnly`,void 0),_defineProperty$2(this,`inner`,void 0),_defineProperty$2(this,`learnable`,void 0),_defineProperty$2(this,`staticWeight`,void 0),_defineProperty$2(this,`strategyId`,void 0),this.inner=t,this.name=t.name,this.kind=t.kind,this.liveOnly=t.liveOnly,this.learnable=c,this.staticWeight=u,this.strategyId=d}async transform(t,c){let u=this.learnable.weight,d;if(!this.staticWeight&&c.orchestration){let t=this.strategyId||this.inner.strategyId||this.name;u=c.orchestration.getEffectiveWeight(t,this.learnable),d=c.orchestration.getDeviation(t)}if(Math.abs(u-1)<.001)return this.inner.transform(t,c);let m=new Map;for(let c of t)m.set(c.cardId,c.score);return(await this.inner.transform(t,c)).map(t=>{let c=m.get(t.cardId);if(c===void 0||c===0||t.score===0)return t;let g=t.score/c;if(Math.abs(g-1)<1e-4)return t;let b=c*g**+u,S=t.provenance.length-1,C=t.provenance[S];if(C){let c=[...t.provenance];return c[S]={...C,score:b,effectiveWeight:u,deviation:d},{...t,score:b,provenance:c}}return{...t,score:b}})}}}}),eloDistance_exports={},__export(eloDistance_exports,{DEFAULT_ELO_DISTANCE_CONFIG:()=>DEFAULT_ELO_DISTANCE_CONFIG,createEloDistanceFilter:()=>createEloDistanceFilter,default:()=>EloDistanceFilter,mountMultiDimEloToggle:()=>mountMultiDimEloToggle,tagAwareGap:()=>tagAwareGap}),init_eloDistance=__esm({"src/core/navigators/filters/eloDistance.ts"(){"use strict";var t;init_navigators(),init_logger(),DEFAULT_ELO_DISTANCE_CONFIG={halfLife:300,minMultiplier:.05,maxMultiplier:1,tagAware:!1,minTagCount:3},TAG_CONFIDENCE_HALF=10,DEFAULT_CARD_ELO=1e3,MULTI_DIM_ELO_KEY=`skuilder:multiDimElo`,multiDimElo=readMultiDimElo(),mountMultiDimEloToggle(),EloDistanceFilter=(t=class _EloDistanceFilter extends ContentNavigator{constructor(t,c,u){super(t,c,u),_defineProperty$2(this,`name`,void 0),_defineProperty$2(this,`kind`,_EloDistanceFilter.kind),_defineProperty$2(this,`liveOnly`,!0),_defineProperty$2(this,`config`,void 0),this.name=u.name||`ELO Distance`;let d;try{d=u.serializedData?JSON.parse(u.serializedData):void 0}catch{d=void 0}this.config=resolveConfig(d)}transform(t,c){return applyEloDistance(t,c,this.config,{name:this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-eloDistance-default`})}async getWeightedCards(t){throw Error(`EloDistanceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().`)}},_defineProperty$2(t,`kind`,`signal`),t)}}),hierarchyDefinition_exports={},__export(hierarchyDefinition_exports,{default:()=>HierarchyDefinitionNavigator}),init_hierarchyDefinition=__esm({"src/core/navigators/filters/hierarchyDefinition.ts"(){"use strict";var t;init_navigators(),init_logger(),DEFAULT_MIN_COUNT2=3,HierarchyDefinitionNavigator=(t=class _HierarchyDefinitionNavigator extends ContentNavigator{constructor(t,c,u){super(t,c,u),_defineProperty$2(this,`config`,void 0),_defineProperty$2(this,`name`,void 0),_defineProperty$2(this,`kind`,_HierarchyDefinitionNavigator.kind),this.config=this.parseConfig(u.serializedData),this.name=u.name||`Hierarchy Definition`}parseConfig(t){try{return{prerequisites:JSON.parse(t).prerequisites||{}}}catch{return{prerequisites:{}}}}isPrerequisiteMet(t,c,u){if(!c)return!1;let d=t.masteryThreshold?.minCount??DEFAULT_MIN_COUNT2;return c.count<d?!1:t.masteryThreshold?.minElo===void 0?t.masteryThreshold?.minCount===void 0?c.score>=u:!0:c.score>=t.masteryThreshold.minElo}async getMasteredTags(t){let c=new Set;try{let u=toCourseElo((await t.user.getCourseRegDoc(t.course.getCourseID())).elo);for(let t of Object.values(this.config.prerequisites))for(let d of t){let t=u.tags[d.tag];this.isPrerequisiteMet(d,t,u.global.score)&&c.add(d.tag)}}catch{}return c}getUnlockedTags(t){let c=new Set;for(let[u,d]of Object.entries(this.config.prerequisites))d.every(c=>t.has(c.tag))&&c.add(u);return c}hasPrerequisites(t){return t in this.config.prerequisites}async checkCardUnlock(t,c,u,d){try{let c=t.tags??[],m=c.filter(t=>this.hasPrerequisites(t)&&!u.has(t));return m.length===0?{isUnlocked:!0,reason:`Prerequisites met, tags: ${c.length>0?c.join(`, `):`none`}`}:{isUnlocked:!1,reason:`Blocked: missing prerequisites ${m.flatMap(t=>(this.config.prerequisites[t]||[]).filter(t=>!d.has(t.tag)).map(t=>t.tag)).join(`, `)} for tags ${m.join(`, `)}`}}catch{return{isUnlocked:!0,reason:`Prerequisites check skipped (tag lookup failed)`}}}getPreReqBoosts(t,c){let u=new Map;for(let[d,m]of Object.entries(this.config.prerequisites))if(!t.has(d))for(let t of m){if(!t.preReqBoost||t.preReqBoost<=1||c.has(t.tag))continue;let d=u.get(t.tag)??1;u.set(t.tag,Math.max(d,t.preReqBoost))}return u}getTargetBoosts(t){let c=new Map,u=Object.keys(this.config.prerequisites),d=[...t];logger.info(`[HierarchyDefinition:targetBoost:trace] ${this.name} | configKeys=${u.length}, unlocked=${d.length} (${d.slice(0,5).join(`, `)}${d.length>5?`...`:``})`);for(let[u,d]of Object.entries(this.config.prerequisites))if(t.has(u)){logger.info(`[HierarchyDefinition:targetBoost:trace] UNLOCKED ${u}: ${d.length} prereqs, raw=${JSON.stringify(d.map(t=>({tag:t.tag,tb:t.targetBoost})))}`);for(let t of d){if(!t.targetBoost||t.targetBoost<=1)continue;let d=c.get(u)??1;c.set(u,Math.max(d,t.targetBoost))}}return c.size>0?logger.info(`[HierarchyDefinition] targetBoosts active: ${[...c.entries()].map(([t,c])=>`${t}=\xD7${c}`).join(`, `)}`):logger.info(`[HierarchyDefinition:targetBoost:trace] no targetBoosts found despite ${d.length} unlocked tags`),c}async transform(t,c){let u=await this.getMasteredTags(c),d=this.getUnlockedTags(u),m=this.getPreReqBoosts(d,u),g=this.getTargetBoosts(d),b=[];for(let S of t){let{isUnlocked:t,reason:C}=await this.checkCardUnlock(S,c.course,d,u),w=t?S.score:S.score*.02,T=t?`passed`:`penalized`,E=C;if(t&&m.size>0){let t=S.tags??[],c=1,u=[];for(let d of t){let t=m.get(d);t&&t>c&&(c=t,u.push(d))}c>1&&(w*=c,T=`boosted`,E=`${C} | preReqBoost \xD7${c.toFixed(2)} for ${u.join(`, `)}`,logger.info(`[HierarchyDefinition] preReqBoost \xD7${c.toFixed(2)} applied to card ${S.cardId} via tags [${u.join(`, `)}] (score: ${S.score.toFixed(3)} \u2192 ${w.toFixed(3)})`))}if(t&&g.size>0){let t=S.tags??[],c=1,u=[];for(let d of t){let t=g.get(d);t&&t>c&&(c=t,u.push(d))}c>1&&(w*=c,T=`boosted`,E=`${E} | targetBoost \xD7${c.toFixed(2)} for ${u.join(`, `)}`,logger.info(`[HierarchyDefinition] targetBoost \xD7${c.toFixed(2)} applied to card ${S.cardId} via tags [${u.join(`, `)}] (score: ${S.score.toFixed(3)} \u2192 ${w.toFixed(3)})`))}b.push({...S,score:w,provenance:[...S.provenance,{strategy:`hierarchyDefinition`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-hierarchy`,action:T,score:w,reason:E}]})}return b}async getWeightedCards(t){throw Error(`HierarchyDefinitionNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().`)}},_defineProperty$2(t,`kind`,`gate`),t)}}),userTagPreference_exports={},__export(userTagPreference_exports,{default:()=>UserTagPreferenceFilter}),init_userTagPreference=__esm({"src/core/navigators/filters/userTagPreference.ts"(){"use strict";var t;init_navigators(),UserTagPreferenceFilter=(t=class _UserTagPreferenceFilter extends ContentNavigator{constructor(t,c,u){super(t,c,u),_defineProperty$2(this,`_strategyData`,void 0),_defineProperty$2(this,`name`,void 0),_defineProperty$2(this,`kind`,_UserTagPreferenceFilter.kind),this._strategyData=u,this.name=u.name||`User Tag Preferences`}computeMultiplier(t,c){let u=t.map(t=>c[t]).filter(t=>t!==void 0);return u.length===0?1:Math.max(...u)}buildReason(t,c,u){let d=t.filter(t=>c[t]===u);return u===0?`Excluded by user preference: ${d.join(`, `)} (${u}x)`:u<1?`Penalized by user preference: ${d.join(`, `)} (${u.toFixed(2)}x)`:u>1?`Boosted by user preference: ${d.join(`, `)} (${u.toFixed(2)}x)`:`No matching user preferences`}async transform(t,c){let u=await this.getStrategyState();return!u||Object.keys(u.boost).length===0?t.map(t=>({...t,provenance:[...t.provenance,{strategy:`userTagPreference`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||this._strategyData._id,action:`passed`,score:t.score,reason:`No user tag preferences configured`}]})):await Promise.all(t.map(async t=>{let c=t.tags??[],d=this.computeMultiplier(c,u.boost),m=Math.min(1,t.score*d),g;return g=d===0||d<1?`penalized`:d>1?`boosted`:`passed`,{...t,score:m,provenance:[...t.provenance,{strategy:`userTagPreference`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||this._strategyData._id,action:g,score:m,reason:this.buildReason(c,u.boost,d)}]}}))}async getWeightedCards(t){throw Error(`UserTagPreferenceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().`)}},_defineProperty$2(t,`kind`,`signal`),t)}}),filters_exports={},__export(filters_exports,{EloDistanceFilter:()=>EloDistanceFilter,UserTagPreferenceFilter:()=>UserTagPreferenceFilter,createEloDistanceFilter:()=>createEloDistanceFilter}),init_filters=__esm({"src/core/navigators/filters/index.ts"(){"use strict";init_eloDistance(),init_userTagPreference()}}),inferredPreferenceStub_exports={},__export(inferredPreferenceStub_exports,{INFERRED_PREFERENCE_NAVIGATOR_STUB:()=>INFERRED_PREFERENCE_NAVIGATOR_STUB}),init_inferredPreferenceStub=__esm({"src/core/navigators/filters/inferredPreferenceStub.ts"(){"use strict";INFERRED_PREFERENCE_NAVIGATOR_STUB=!0}}),interferenceMitigator_exports={},__export(interferenceMitigator_exports,{default:()=>InterferenceMitigatorNavigator}),init_interferenceMitigator=__esm({"src/core/navigators/filters/interferenceMitigator.ts"(){"use strict";var t;init_navigators(),DEFAULT_MIN_COUNT3=10,DEFAULT_MIN_ELAPSED_DAYS=3,DEFAULT_INTERFERENCE_DECAY=.8,InterferenceMitigatorNavigator=(t=class _InterferenceMitigatorNavigator extends ContentNavigator{constructor(t,c,u){super(t,c,u),_defineProperty$2(this,`config`,void 0),_defineProperty$2(this,`name`,void 0),_defineProperty$2(this,`kind`,_InterferenceMitigatorNavigator.kind),_defineProperty$2(this,`interferenceMap`,void 0),this.config=this.parseConfig(u.serializedData),this.interferenceMap=this.buildInterferenceMap(),this.name=u.name||`Interference Mitigator`}parseConfig(t){try{let c=JSON.parse(t),u=c.interferenceSets||[];return u.length>0&&Array.isArray(u[0])&&(u=u.map(t=>({tags:t}))),{interferenceSets:u,maturityThreshold:{minCount:c.maturityThreshold?.minCount??DEFAULT_MIN_COUNT3,minElo:c.maturityThreshold?.minElo,minElapsedDays:c.maturityThreshold?.minElapsedDays??DEFAULT_MIN_ELAPSED_DAYS},defaultDecay:c.defaultDecay??DEFAULT_INTERFERENCE_DECAY}}catch{return{interferenceSets:[],maturityThreshold:{minCount:DEFAULT_MIN_COUNT3,minElapsedDays:DEFAULT_MIN_ELAPSED_DAYS},defaultDecay:DEFAULT_INTERFERENCE_DECAY}}}buildInterferenceMap(){let t=new Map;for(let c of this.config.interferenceSets){let u=c.decay??this.config.defaultDecay??DEFAULT_INTERFERENCE_DECAY;for(let d of c.tags){t.has(d)||t.set(d,[]);let m=t.get(d);for(let t of c.tags)if(t!==d){let c=m.find(c=>c.partner===t);c?c.decay=Math.max(c.decay,u):m.push({partner:t,decay:u})}}}return t}async getImmatureTags(t){let c=new Set;try{let u=toCourseElo((await t.user.getCourseRegDoc(t.course.getCourseID())).elo),d=this.config.maturityThreshold?.minCount??DEFAULT_MIN_COUNT3,m=this.config.maturityThreshold?.minElo,g=(this.config.maturityThreshold?.minElapsedDays??DEFAULT_MIN_ELAPSED_DAYS)*2;for(let[t,b]of Object.entries(u.tags)){if(b.count===0)continue;let u=b.count<d,S=m!==void 0&&b.score<m,C=b.count<g;(u||S||C)&&c.add(t)}}catch{}return c}getTagsToAvoid(t){let c=new Map;for(let u of t){let d=this.interferenceMap.get(u);if(d){for(let{partner:u,decay:m}of d)if(!t.has(u)){let t=c.get(u)??0;c.set(u,Math.max(t,m))}}}return c}computeInterferenceEffect(t,c,u){if(c.size===0)return{multiplier:1,interferingTags:[],reason:`No interference detected`};let d=1,m=[];for(let u of t){let t=c.get(u);t!==void 0&&(m.push(u),d*=1-t)}if(m.length===0)return{multiplier:1,interferingTags:[],reason:`No interference detected`};let g=new Set;for(let t of m)for(let c of u)this.interferenceMap.get(c)?.some(c=>c.partner===t)&&g.add(c);let b=`Interferes with immature tags ${Array.from(g).join(`, `)} (tags: ${m.join(`, `)}, multiplier: ${d.toFixed(2)})`;return{multiplier:d,interferingTags:m,reason:b}}async transform(t,c){let u=await this.getImmatureTags(c),d=this.getTagsToAvoid(u),m=[];for(let c of t){let t=c.tags??[],{multiplier:g,reason:b}=this.computeInterferenceEffect(t,d,u),S=c.score*g,C=g<1?`penalized`:g>1?`boosted`:`passed`;m.push({...c,score:S,provenance:[...c.provenance,{strategy:`interferenceMitigator`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-interference`,action:C,score:S,reason:b}]})}return m}async getWeightedCards(t){throw Error(`InterferenceMitigatorNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().`)}},_defineProperty$2(t,`kind`,`signal`),t)}}),relativePriority_exports={},__export(relativePriority_exports,{default:()=>RelativePriorityNavigator}),init_relativePriority=__esm({"src/core/navigators/filters/relativePriority.ts"(){"use strict";var t;init_navigators(),DEFAULT_PRIORITY=.5,DEFAULT_PRIORITY_INFLUENCE=.5,DEFAULT_COMBINE_MODE=`max`,RelativePriorityNavigator=(t=class _RelativePriorityNavigator extends ContentNavigator{constructor(t,c,u){super(t,c,u),_defineProperty$2(this,`config`,void 0),_defineProperty$2(this,`name`,void 0),_defineProperty$2(this,`kind`,_RelativePriorityNavigator.kind),this.config=this.parseConfig(u.serializedData),this.name=u.name||`Relative Priority`}parseConfig(t){try{let c=JSON.parse(t);return{tagPriorities:c.tagPriorities||{},defaultPriority:c.defaultPriority??DEFAULT_PRIORITY,combineMode:c.combineMode??DEFAULT_COMBINE_MODE,priorityInfluence:c.priorityInfluence??DEFAULT_PRIORITY_INFLUENCE}}catch{return{tagPriorities:{},defaultPriority:DEFAULT_PRIORITY,combineMode:DEFAULT_COMBINE_MODE,priorityInfluence:DEFAULT_PRIORITY_INFLUENCE}}}getTagPriority(t){return this.config.tagPriorities[t]??this.config.defaultPriority??DEFAULT_PRIORITY}computeCardPriority(t){if(t.length===0)return this.config.defaultPriority??DEFAULT_PRIORITY;let c=t.map(t=>this.getTagPriority(t));switch(this.config.combineMode){case`max`:return Math.max(...c);case`min`:return Math.min(...c);case`average`:return c.reduce((t,c)=>t+c,0)/c.length;default:return Math.max(...c)}}computeBoostFactor(t){let c=this.config.priorityInfluence??DEFAULT_PRIORITY_INFLUENCE;return 1+(t-.5)*c}buildPriorityReason(t,c,u,d){if(t.length===0)return`No tags, neutral priority (${c.toFixed(2)})`;let m=t.slice(0,3).join(`, `),g=t.length>3?` (+${t.length-3} more)`:``;return u===1?`Neutral priority (${c.toFixed(2)}) for tags: ${m}${g}`:u>1?`High-priority tags: ${m}${g} (priority ${c.toFixed(2)} \u2192 boost ${u.toFixed(2)}x \u2192 ${d.toFixed(2)})`:`Low-priority tags: ${m}${g} (priority ${c.toFixed(2)} \u2192 reduce ${u.toFixed(2)}x \u2192 ${d.toFixed(2)})`}async transform(t,c){return await Promise.all(t.map(async t=>{let c=t.tags??[],u=this.computeCardPriority(c),d=this.computeBoostFactor(u),m=Math.max(0,t.score*d),g=d>1?`boosted`:d<1?`penalized`:`passed`,b=this.buildPriorityReason(c,u,d,m);return{...t,score:m,provenance:[...t.provenance,{strategy:`relativePriority`,strategyName:this.strategyName||this.name,strategyId:this.strategyId||`NAVIGATION_STRATEGY-priority`,action:g,score:m,reason:b}]}}))}async getWeightedCards(t){throw Error(`RelativePriorityNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform().`)}},_defineProperty$2(t,`kind`,`signal`),t)}}),types_exports2={},init_types2=__esm({"src/core/navigators/filters/types.ts"(){"use strict";}}),userGoalStub_exports={},__export(userGoalStub_exports,{USER_GOAL_NAVIGATOR_STUB:()=>USER_GOAL_NAVIGATOR_STUB}),init_userGoalStub=__esm({"src/core/navigators/filters/userGoalStub.ts"(){"use strict";USER_GOAL_NAVIGATOR_STUB=!0}}),init_2=__esm({'import("./filters/**/*") in src/core/navigators/index.ts'(){globImport_filters=__glob({"./filters/WeightedFilter.ts":()=>Promise.resolve().then(()=>(init_WeightedFilter(),WeightedFilter_exports)),"./filters/eloDistance.ts":()=>Promise.resolve().then(()=>(init_eloDistance(),eloDistance_exports)),"./filters/hierarchyDefinition.ts":()=>Promise.resolve().then(()=>(init_hierarchyDefinition(),hierarchyDefinition_exports)),"./filters/index.ts":()=>Promise.resolve().then(()=>(init_filters(),filters_exports)),"./filters/inferredPreferenceStub.ts":()=>Promise.resolve().then(()=>(init_inferredPreferenceStub(),inferredPreferenceStub_exports)),"./filters/interferenceMitigator.ts":()=>Promise.resolve().then(()=>(init_interferenceMitigator(),interferenceMitigator_exports)),"./filters/relativePriority.ts":()=>Promise.resolve().then(()=>(init_relativePriority(),relativePriority_exports)),"./filters/types.ts":()=>Promise.resolve().then(()=>(init_types2(),types_exports2)),"./filters/userGoalStub.ts":()=>Promise.resolve().then(()=>(init_userGoalStub(),userGoalStub_exports)),"./filters/userTagPreference.ts":()=>Promise.resolve().then(()=>(init_userTagPreference(),userTagPreference_exports))})}}),init_gradient=__esm({"src/core/orchestration/gradient.ts"(){"use strict";init_logger()}}),init_learning=__esm({"src/core/orchestration/learning.ts"(){"use strict";init_contentNavigationStrategy(),init_types_legacy(),init_logger(),MIN_OBSERVATIONS_FOR_UPDATE=10,LEARNING_RATE=.1,MAX_WEIGHT_DELTA=.3,MIN_R_SQUARED_FOR_GRADIENT=.05,FLAT_GRADIENT_THRESHOLD=.02,MAX_HISTORY_LENGTH=100}}),init_signal=__esm({"src/core/orchestration/signal.ts"(){"use strict";}}),init_recording=__esm({"src/core/orchestration/recording.ts"(){"use strict";init_signal(),init_types_legacy(),init_logger()}}),init_orchestration=__esm({"src/core/orchestration/index.ts"(){"use strict";init_logger(),init_gradient(),init_learning(),init_signal(),init_recording(),MIN_SPREAD=.1,MAX_SPREAD=.5,MIN_WEIGHT=.1,MAX_WEIGHT=3}}),Pipeline_exports={},__export(Pipeline_exports,{Pipeline:()=>Pipeline,mergeHints:()=>mergeHints2}),init_Pipeline=__esm({"src/core/navigators/Pipeline.ts"(){"use strict";init_navigators(),init_logger(),init_orchestration(),init_PipelineDebugger(),init_diversityRerank(),init_regulators(),init_SrsDebugger(),VERBOSE_RESULTS=!0,Pipeline=class extends ContentNavigator{constructor(t,c,u,d){super(),_defineProperty$2(this,`generator`,void 0),_defineProperty$2(this,`filters`,void 0),_defineProperty$2(this,`_cachedOrchestration`,null),_defineProperty$2(this,`strategyHash`,void 0),_defineProperty$2(this,`_tagCache`,new Map),_defineProperty$2(this,`_ephemeralHints`,null),_defineProperty$2(this,`_intakeClock`,null),_defineProperty$2(this,`_intakeClockWrite`,Promise.resolve()),this.generator=t,this.filters=c,this.user=u,this.course=d,d.getCourseConfig().then(t=>{logger.debug(`[pipeline] Crated pipeline for ${t.name}`)}).catch(t=>{logger.error(`[pipeline] Failed to lookup courseCfg: ${t}`)}),logPipelineConfig(t,c),registerPipelineForDebug(this)}setEphemeralHints(t){this._ephemeralHints=t,logger.info(`[Pipeline] Ephemeral hints set: ${JSON.stringify(t)}`)}async getWeightedCards(t){let c=performance.now(),u=await this.buildContext(),d=performance.now(),m=500;logger.debug(`[Pipeline] Fetching 500 candidates from generator '${this.generator.name}'`);let g=await this.generator.getWeightedCards(500,u),b=g.cards,S=performance.now(),C=b.length;this._ephemeralHints=mergeHints2([this._ephemeralHints,g.hints])??null;let w;if(this.generator.generators){let t=new Map;for(let c of b){let u=c.provenance[0];if(u){let d=u.strategyName;t.has(d)||t.set(d,{cards:[]}),t.get(d).cards.push(c)}}w=Array.from(t.entries()).map(([t,c])=>{let u=c.cards.filter(t=>t.reviewID).length;return{name:t,cardCount:c.cards.length,newCount:c.cards.length-u,reviewCount:u,topScore:Math.max(...c.cards.map(t=>t.score),0)}})}logger.debug(`[Pipeline] Generator returned ${C} candidates`),b=await this.hydrateTags(b);let T=performance.now(),E=[...b],D=this._ephemeralHints;if(D?.requireCards?.length){let t=new Set(E.map(t=>t.cardId)),c=D.requireCards.filter(c=>!c.includes(`*`)&&!t.has(c));if(c.length>0){let t=await this.course.getAppliedTagsBatch(c),u=this.course.getCourseID();for(let d of c)E.push({cardId:d,courseId:u,score:1,tags:t.get(d)??[],provenance:[]});logger.info(`[Pipeline] Pre-fetched ${c.length} required card(s) into pool: ${c.join(`, `)}`)}}let O=new Set(b.filter(t=>t.provenance.some(t=>t.strategy===`prescribed`)).map(t=>t.cardId)),xr=[],Sr=new Map(b.map(t=>[t.cardId,t.score])),Cr=new Set;for(let t of this.filters){let c=b.length,d=new Map(b.map(t=>[t.cardId,t.score]));b=await t.transform(b,u);let m=0,g=0,S=0,C=c-b.length,w=t.kind??`gate`;for(let t of b){let c=d.get(t.cardId)??0;t.score>c?m++:t.score<c?(g++,w===`gate`&&Cr.add(t.cardId)):S++}if(xr.push({name:t.name,kind:w,boosted:m,penalized:g,passed:S,removed:C}),O.size>0){let c=new Set(b.map(t=>t.cardId)),u=[...O].filter(t=>!c.has(t)),d=b.filter(t=>O.has(t.cardId)&&t.score===0).map(t=>t.cardId);(u.length>0||d.length>0)&&(logger.info(`[Pipeline] Filter '${t.name}' impact on prescribed cards: `+(u.length>0?`removed=[${u.join(`, `)}] `:``)+(d.length>0?`zeroed=[${d.join(`, `)}]`:``)),u.forEach(t=>O.delete(t)))}logger.debug(`[Pipeline] Filter '${t.name}': ${d.size} \u2192 ${b.length} cards (\u2191${m} \u2193${g} =${S})`)}let wr=b;b=b.filter(t=>t.score>0);let Tr=await this.regulate(b,Sr,Cr),Er=this._ephemeralHints;Er&&(this._ephemeralHints=null,b=this.applyHints(b,Er,E)),b=diversityRerank(b),b.sort((t,c)=>c.score-t.score);let Dr=performance.now(),Or=b.slice(0,t);logger.info(`[Pipeline:timing] total=${(Dr-c).toFixed(0)}ms (context=${(d-c).toFixed(0)} generate=${(S-d).toFixed(0)} hydrate=${(T-S).toFixed(0)} filter=${(Dr-T).toFixed(0)})`);let kr=Or.slice(0,3).map(t=>t.score);logExecutionSummary(this.generator.name,C,this.filters.length,Or.length,kr,xr),logResultCards(Or),logCardProvenance(Or,3);try{let t=await this.course?.getCourseConfig().catch(()=>void 0),c=t?.name,d=buildRunReport(this.course?.getCourseID()||`unknown`,c,this.generator.name,w,C,xr,b,Or,u.userElo,Er??void 0,wr,Tr),m={...this.strategyHash?{strategies:this.strategyHash}:{},...t?.contentVersion?{content:t.contentVersion}:{}};captureRun({...d,...Object.keys(m).length?{versions:m}:{}})}catch(t){logger.debug(`[Pipeline] Failed to capture debug run: ${t}`)}return{cards:Or}}async hydrateTags(t){if(t.length===0)return t;let c=[];for(let u of t)this._tagCache.has(u.cardId)||c.push(u.cardId);if(c.length>0){let t=await this.course.getAppliedTagsBatch(c);for(let[c,u]of t)this._tagCache.set(c,u)}let u=new Map;for(let c of t)u.set(c.cardId,this._tagCache.get(c.cardId)??[]);return logTagHydration(t,u),t.map(t=>({...t,tags:this._tagCache.get(t.cardId)??[]}))}applyHints(t,c,u){let d=t.length;if(c.excludeCards?.length&&(t=t.filter(t=>!c.excludeCards.some(c=>globMatch(t.cardId,c)))),c.excludeTags?.length&&(t=t.filter(t=>!c.excludeTags.some(c=>cardMatchesTagPattern(t,c)))),c.boostTags)for(let[u,d]of Object.entries(c.boostTags))for(let m of t)cardMatchesTagPattern(m,u)&&(m.score*=d,m.provenance.push({strategy:`ephemeralHint`,strategyId:`ephemeral-hint`,strategyName:c._label?`Replan Hint (${c._label})`:`Replan Hint`,action:`boosted`,score:m.score,reason:`boostTag ${u} \xD7${d}`}));if(c.boostCards)for(let[u,d]of Object.entries(c.boostCards))for(let m of t)globMatch(m.cardId,u)&&(m.score*=d,m.provenance.push({strategy:`ephemeralHint`,strategyId:`ephemeral-hint`,strategyName:c._label?`Replan Hint (${c._label})`:`Replan Hint`,action:`boosted`,score:m.score,reason:`boostCard ${u} \xD7${d}`}));let m=new Set(t.map(t=>t.cardId)),g=new Map(t.map(t=>[t.cardId,t])),b=c._label?`Replan Hint (${c._label})`:`Replan Hint`,applyRequirement=(c,u)=>{let d=1/0,S=g.get(c.cardId);S?S.score<d&&(S.score=d,S.provenance.push({strategy:`ephemeralHint`,strategyId:`ephemeral-hint`,strategyName:b,action:`boosted`,score:d,reason:`${u} (upgrade to mandatory score)`})):(t.push({...c,score:d,provenance:[...c.provenance,{strategy:`ephemeralHint`,strategyId:`ephemeral-hint`,strategyName:b,action:`boosted`,score:d,reason:u}]}),m.add(c.cardId),g.set(c.cardId,t[t.length-1]))};if(c.requireCards?.length)for(let t of c.requireCards){for(let c of m)globMatch(c,t)&&applyRequirement(g.get(c),`requireCard ${t}`);for(let c of u)globMatch(c.cardId,t)&&applyRequirement(c,`requireCard ${t}`)}if(c.requireTags?.length)for(let t of c.requireTags){for(let c of m){let u=g.get(c);cardMatchesTagPattern(u,t)&&applyRequirement(u,`requireTag ${t}`)}for(let c of u)cardMatchesTagPattern(c,t)&&applyRequirement(c,`requireTag ${t}`)}return logger.info(`[Pipeline] Hints applied: ${d} \u2192 ${t.length} cards`),t}async regulate(t,c,u){let d=DEFAULT_REGULATOR_CONFIG,m=t.filter(t=>t.reviewID),g=t.filter(t=>!t.reviewID),b=g.filter(t=>!u.has(t.cardId)),S=reviewMassReading(m,c,d.reviewMass);applyReading(m,S),noteReviewPressure(this.course.getCourseID(),{mass:S.urgency,healthyMass:d.reviewMass.healthyMass,rate:d.reviewMass.rate,multiplier:S.multiplier});let C=Date.now(),w=await this.loadIntakeClock(C),T=stepIntakeClock(w,C,b.length);T!==w&&this.saveIntakeClock(T);let E=intakeReading(T,C,{eligibleNew:b.length,newCandidates:g.length},d.intake);return applyReading(b,E),logger.info(`[Pipeline:regulators] review mass ${S.urgency.toFixed(1)} over ${m.length} due \u2192 \xD7${S.multiplier.toFixed(2)}; intake ${E.urgency.toFixed(1)}h, ${b.length}/${g.length} new eligible \u2192 \xD7${E.multiplier.toFixed(2)}`),[S,E]}notePresented(t){t.status!==`new`||t.courseId!==this.course?.getCourseID()||this.saveIntakeClock(resetIntakeClock(Date.now()))}async loadIntakeClock(t){if(this._intakeClock)return this._intakeClock;let c=null;try{c=await this.user.getStrategyState(this.course.getCourseID(),INTAKE_CLOCK_KEY)}catch(t){logger.warn(`[Pipeline:regulators] Could not read the intake clock: ${t}`)}return c?this._intakeClock=c:this.saveIntakeClock(resetIntakeClock(t)),this._intakeClock}saveIntakeClock(t){this._intakeClock=t;let c=this.course.getCourseID();this._intakeClockWrite=this._intakeClockWrite.then(()=>this.user.putStrategyState(c,INTAKE_CLOCK_KEY,t)).catch(t=>logger.warn(`[Pipeline:regulators] Could not save the intake clock: ${t}`))}async buildContext(){let t=1e3,c;try{c=toCourseElo((await this.user.getCourseRegDoc(this.course.getCourseID())).elo),t=c.global.score}catch(t){logger.debug(`[Pipeline] Could not get user ELO, using default: ${t}`)}this._cachedOrchestration||(this._cachedOrchestration=await createOrchestrationContext(this.user,this.course));let u=this._cachedOrchestration;return{user:this.user,course:this.course,userElo:t,...c?{userCourseElo:c}:{},orchestration:u}}getCourseID(){return this.course.getCourseID()}async getOrchestrationContext(){return createOrchestrationContext(this.user,this.course)}getStrategyIds(){let t=[],extractId=t=>t.strategyId?t.strategyId:null,c=extractId(this.generator);c&&t.push(c),this.generator.generators&&Array.isArray(this.generator.generators)&&this.generator.generators.forEach(c=>{let u=extractId(c);u&&t.push(u)});for(let c of this.filters){let u=extractId(c);u&&t.push(u)}return[...new Set(t)]}async getTagEloStatus(t){let c=toCourseElo((await this.user.getCourseRegDoc(this.course.getCourseID())).elo),u={};if(t){let d=Array.isArray(t)?t:[t];for(let t of d){let d=globToRegex(t);for(let[t,m]of Object.entries(c.tags))d.test(t)&&(u[t]={score:m.score,count:m.count})}}else for(let[t,d]of Object.entries(c.tags))u[t]={score:d.score,count:d.count};return u}async forecast(t){let c=t?.threshold??.1,u=t?.unseenOnly??!0,d=this.course.getCourseID(),m=(await this.course.getAllCardIds()).map(t=>({cardId:t,courseId:d,score:1,provenance:[]}));m=await this.hydrateTags(m);let g=m.slice(),b=await this.buildContext();for(let t of this.forecastFilters())m=await t.transform(m,b);if(t?.hints&&(m=this.applyHints(m,t.hints,g)),m=m.filter(t=>t.score>=c),u){let t;try{t=new Set(await this.user.getSeenCards(d))}catch{t=new Set}m=m.filter(c=>!t.has(c.cardId))}return m.sort((t,c)=>c.score-t.score),t?.limit?m.slice(0,t.limit):m}forecastFilters(){return this.filters.filter(t=>!t.liveOnly)}async diagnoseCardSpace(t){let c=t?.threshold??.1,u=performance.now(),d=await this.course.getAllCardIds(),m=d.map(t=>({cardId:t,courseId:this.course.getCourseID(),score:1,provenance:[]}));m=await this.hydrateTags(m);let g=await this.buildContext(),b=[];for(let t of this.forecastFilters()){m=await t.transform(m,g);let u=m.filter(t=>t.score>=c).length;b.push({name:t.name,wellIndicated:u})}let S=m.filter(t=>t.score>=c),C=new Set(S.map(t=>t.cardId)),w;try{let t=this.course.getCourseID(),c=await this.user.getSeenCards(t);w=new Set(c)}catch{w=new Set}let T=S.filter(t=>!w.has(t.cardId)),E=new Map;for(let t of m){let u=t.cardId.split(`-`)[1]||`unknown`;E.has(u)||E.set(u,{total:0,wellIndicated:0,new:0});let d=E.get(u);d.total++,t.score>=c&&(d.wellIndicated++,w.has(t.cardId)||d.new++)}let D=performance.now()-u,O={totalCards:d.length,threshold:c,wellIndicated:C.size,encountered:w.size,wellIndicatedNew:T.length,byType:Object.fromEntries(E),filterBreakdown:b,elapsedMs:Math.round(D)};logger.info(`[Pipeline:diagnose] Card space scan (${O.elapsedMs}ms):`),logger.info(`[Pipeline:diagnose] Total cards: ${O.totalCards}`),logger.info(`[Pipeline:diagnose] Well-indicated (score >= ${c}): ${O.wellIndicated}`),logger.info(`[Pipeline:diagnose] Encountered: ${O.encountered}`),logger.info(`[Pipeline:diagnose] Well-indicated & new: ${O.wellIndicatedNew}`),logger.info(`[Pipeline:diagnose] By type:`);for(let[t,c]of E)logger.info(`[Pipeline:diagnose] ${t}: ${c.wellIndicated}/${c.total} well-indicated, ${c.new} new`);logger.info(`[Pipeline:diagnose] After each filter:`);for(let t of b)logger.info(`[Pipeline:diagnose] ${t.name}: ${t.wellIndicated} well-indicated`);return O}}}}),init_versionStamps=__esm({"src/core/versionStamps.ts"(){"use strict";FRAMEWORK_VERSION=`0.2.35`,DEFAULT_STRATEGY_HASH=`default`}}),defaults_exports={},__export(defaults_exports,{createDefaultEloDistanceStrategy:()=>createDefaultEloDistanceStrategy,createDefaultEloStrategy:()=>createDefaultEloStrategy,createDefaultPipeline:()=>createDefaultPipeline,createDefaultSrsStrategy:()=>createDefaultSrsStrategy}),init_defaults=__esm({"src/core/navigators/defaults.ts"(){"use strict";init_navigators(),init_Pipeline(),init_CompositeGenerator(),init_elo(),init_srs(),init_eloDistance(),init_types_legacy(),init_versionStamps()}}),pipelinePlan_exports={},__export(pipelinePlan_exports,{PIPELINE_STAGES:()=>PIPELINE_STAGES,planPipeline:()=>planPipeline}),init_pipelinePlan=__esm({"src/core/navigators/pipelinePlan.ts"(){"use strict";init_navigators(),init_regulators(),init_defaults(),PIPELINE_STAGES=[{key:`generate`,title:`Generate`,summary:`Each generator proposes candidates (up to 500 in all), scored on what is specific to its source. A card proposed by several generators keeps their mean score, raised 10% per extra generator.`},{key:`filter`,title:`Filter`,summary:`Each filter multiplies candidate scores, in the order shown. A gate says a card is not ready yet; a signal expresses preference. Gates usually penalize rather than remove, so a gated card stays in the pool at a low score.`},{key:`drop-zero`,title:`Drop zero scores`,summary:`Candidates whose score reached 0 leave the pool.`},{key:`regulate`,title:`Regulate`,summary:`Balances reviews against new cards. Review mass: the due reviews weighed by their filtered scores; above a healthy level, every review is lifted. Intake: hours since a new card was last presented; new cards no gate penalized are lifted, and the clock stops while there are none.`},{key:`hints`,title:`Apply hints`,summary:`The session's hints (from the app: an intro's follow-up, a difficulty boost) exclude, boost, or require cards. Required cards skip the filters entirely.`},{key:`diversity`,title:`Diversity re-rank`,summary:`Demotes candidates that repeat a distinctive tag already ranked above them, so one concept or answer cannot take the whole head of the queue. Sees this run only, not what the session already served.`},{key:`select`,title:`Select`,summary:`Highest scores first, up to the run's limit. The session mixes them into its supply queue.`}]}}),PipelineAssembler_exports={},__export(PipelineAssembler_exports,{PipelineAssembler:()=>PipelineAssembler}),init_PipelineAssembler=__esm({"src/core/navigators/PipelineAssembler.ts"(){"use strict";init_navigators(),init_WeightedFilter(),init_Pipeline(),init_logger(),init_CompositeGenerator(),init_pipelinePlan(),init_versionStamps(),PipelineAssembler=class{async assemble(t){let{strategies:c,user:u,course:d}=t,m=[];if(c.length===0)return{pipeline:null,generatorStrategies:[],filterStrategies:[],warnings:m};let g=planPipeline(c,d.getCourseID());m.push(...g.warnings);for(let t of[...g.generators,...g.filters])t.origin===`assembler-default`&&logger.debug(`[PipelineAssembler] No ${t.implementingClass} ${t.role} configured, adding default`);let b=g.generators.map(t=>t.strategy),S=g.filters.map(t=>t.strategy);if(b.length===0)return m.push(`No generator strategy found`),{pipeline:null,generatorStrategies:[],filterStrategies:[],warnings:m};let C;b.length===1?(C=await ContentNavigator.create(u,d,b[0]),logger.debug(`[PipelineAssembler] Using single generator: ${b[0].name}`)):(logger.debug(`[PipelineAssembler] Using CompositeGenerator for ${b.length} generators: ${b.map(t=>t.name).join(`, `)}`),C=await CompositeGenerator.fromStrategies(u,d,b));let w=[];for(let t of S)try{let c=await ContentNavigator.create(u,d,t);if(`transform`in c&&typeof c.transform==`function`){let u=c;t.learnable&&(u=new WeightedFilter(u,t.learnable,t.staticWeight,t._id)),w.push(u),logger.debug(`[PipelineAssembler] Added filter: ${t.name}`)}else m.push(`Filter '${t.name}' does not implement CardFilter.transform(), skipping`)}catch(c){m.push(`Failed to instantiate filter '${t.name}': ${c}`)}let T=new Pipeline(C,w,u,d);return T.strategyHash=strategyHash(c),logger.debug(`[PipelineAssembler] Assembled pipeline with ${b.length} generator(s) and ${w.length} filter(s)`),{pipeline:T,generatorStrategies:b,filterStrategies:S,warnings:m}}}}}),init_3=__esm({'import("./**/*") in src/core/navigators/index.ts'(){globImport=__glob({"./Pipeline.ts":()=>Promise.resolve().then(()=>(init_Pipeline(),Pipeline_exports)),"./PipelineAssembler.ts":()=>Promise.resolve().then(()=>(init_PipelineAssembler(),PipelineAssembler_exports)),"./PipelineDebugger.ts":()=>Promise.resolve().then(()=>(init_PipelineDebugger(),PipelineDebugger_exports)),"./SrsDebugger.ts":()=>Promise.resolve().then(()=>(init_SrsDebugger(),SrsDebugger_exports)),"./StrategyPressureDebugger.ts":()=>Promise.resolve().then(()=>(init_StrategyPressureDebugger(),StrategyPressureDebugger_exports)),"./defaults.ts":()=>Promise.resolve().then(()=>(init_defaults(),defaults_exports)),"./diversityRerank.ts":()=>Promise.resolve().then(()=>(init_diversityRerank(),diversityRerank_exports)),"./filters/WeightedFilter.ts":()=>Promise.resolve().then(()=>(init_WeightedFilter(),WeightedFilter_exports)),"./filters/eloDistance.ts":()=>Promise.resolve().then(()=>(init_eloDistance(),eloDistance_exports)),"./filters/hierarchyDefinition.ts":()=>Promise.resolve().then(()=>(init_hierarchyDefinition(),hierarchyDefinition_exports)),"./filters/index.ts":()=>Promise.resolve().then(()=>(init_filters(),filters_exports)),"./filters/inferredPreferenceStub.ts":()=>Promise.resolve().then(()=>(init_inferredPreferenceStub(),inferredPreferenceStub_exports)),"./filters/interferenceMitigator.ts":()=>Promise.resolve().then(()=>(init_interferenceMitigator(),interferenceMitigator_exports)),"./filters/relativePriority.ts":()=>Promise.resolve().then(()=>(init_relativePriority(),relativePriority_exports)),"./filters/types.ts":()=>Promise.resolve().then(()=>(init_types2(),types_exports2)),"./filters/userGoalStub.ts":()=>Promise.resolve().then(()=>(init_userGoalStub(),userGoalStub_exports)),"./filters/userTagPreference.ts":()=>Promise.resolve().then(()=>(init_userTagPreference(),userTagPreference_exports)),"./generators/CompositeGenerator.ts":()=>Promise.resolve().then(()=>(init_CompositeGenerator(),CompositeGenerator_exports)),"./generators/elo.ts":()=>Promise.resolve().then(()=>(init_elo(),elo_exports)),"./generators/index.ts":()=>Promise.resolve().then(()=>(init_generators(),generators_exports)),"./generators/prescribed.ts":()=>Promise.resolve().then(()=>(init_prescribed(),prescribed_exports)),"./generators/srs.ts":()=>Promise.resolve().then(()=>(init_srs(),srs_exports)),"./generators/types.ts":()=>Promise.resolve().then(()=>(init_types(),types_exports)),"./index.ts":()=>Promise.resolve().then(()=>(init_navigators(),navigators_exports)),"./pipelinePlan.ts":()=>Promise.resolve().then(()=>(init_pipelinePlan(),pipelinePlan_exports)),"./regulators.ts":()=>Promise.resolve().then(()=>(init_regulators(),regulators_exports))})}}),navigators_exports={},__export(navigators_exports,{ContentNavigator:()=>ContentNavigator,DIVERSITY_FLOOR:()=>DIVERSITY_FLOOR,DIVERSITY_STRENGTH:()=>DIVERSITY_STRENGTH,NavigatorRole:()=>NavigatorRole,NavigatorRoles:()=>NavigatorRoles,Navigators:()=>Navigators,captureStrategyPressure:()=>captureStrategyPressure,clearSrsBacklogDebug:()=>clearSrsBacklogDebug,clearStrategyPressureDebug:()=>clearStrategyPressureDebug,diversityRerank:()=>diversityRerank,drainCapturedRuns:()=>drainCapturedRuns,getActivePipeline:()=>getActivePipeline,getCardOrigin:()=>getCardOrigin,getRegisteredFilterKind:()=>getRegisteredFilterKind,getRegisteredNavigator:()=>getRegisteredNavigator,getRegisteredNavigatorNames:()=>getRegisteredNavigatorNames,getRegisteredNavigatorRole:()=>getRegisteredNavigatorRole,getRunsForSession:()=>getRunsForSession,getSrsBacklogDebug:()=>getSrsBacklogDebug,getStrategyPressureDebug:()=>getStrategyPressureDebug,hasRegisteredNavigator:()=>hasRegisteredNavigator,initializeNavigatorRegistry:()=>initializeNavigatorRegistry,isFilter:()=>isFilter,isGenerator:()=>isGenerator,mountPipelineDebugger:()=>mountPipelineDebugger,pipelineDebugAPI:()=>pipelineDebugAPI,registerNavigator:()=>registerNavigator,setDebugSessionId:()=>setDebugSessionId}),init_navigators=__esm({"src/core/navigators/index.ts"(){"use strict";init_diversityRerank(),init_PipelineDebugger(),init_SrsDebugger(),init_StrategyPressureDebugger(),init_logger(),init_(),init_2(),init_3(),navigatorRegistry=new Map,Navigators=(t=>(t.ELO=`elo`,t.SRS=`srs`,t.PRESCRIBED=`prescribed`,t.HIERARCHY=`hierarchyDefinition`,t.INTERFERENCE=`interferenceMitigator`,t.RELATIVE_PRIORITY=`relativePriority`,t.USER_TAG_PREFERENCE=`userTagPreference`,t.ELO_DISTANCE=`eloDistance`,t))(Navigators||{}),NavigatorRole=(t=>(t.GENERATOR=`generator`,t.FILTER=`filter`,t))(NavigatorRole||{}),NavigatorRoles={elo:`generator`,srs:`generator`,prescribed:`generator`,hierarchyDefinition:`filter`,interferenceMitigator:`filter`,relativePriority:`filter`,userTagPreference:`filter`,eloDistance:`filter`},ContentNavigator=class{constructor(t,c,u){_defineProperty$2(this,`user`,void 0),_defineProperty$2(this,`course`,void 0),_defineProperty$2(this,`strategyName`,void 0),_defineProperty$2(this,`strategyId`,void 0),_defineProperty$2(this,`learnable`,void 0),_defineProperty$2(this,`staticWeight`,void 0),this.user=t,this.course=c,u&&(this.strategyName=u.name,this.strategyId=u._id,this.learnable=u.learnable,this.staticWeight=u.staticWeight)}get strategyKey(){return this.constructor.name}async getStrategyState(){if(!this.user||!this.course)throw Error(`Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`);return this.user.getStrategyState(this.course.getCourseID(),this.strategyKey)}async putStrategyState(t){if(!this.user||!this.course)throw Error(`Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`);return this.user.putStrategyState(this.course.getCourseID(),this.strategyKey,t)}static async create(t,c,u){let d=u.implementingClass,m=getRegisteredNavigator(d);if(m)return logger.debug(`[ContentNavigator.create] Using registered navigator: ${d}`),new m(t,c,u);logger.debug(`[ContentNavigator.create] Navigator not in registry, attempting dynamic import: ${d}`);let g;for(let t of[`.ts`,`.js`,``]){try{if(g=(await globImport_generators(`./generators/${d}${t}`)).default,g)break}catch(c){logger.debug(`Failed to load generator ${d}${t}:`,c)}try{if(g=(await globImport_filters(`./filters/${d}${t}`)).default,g)break}catch(c){logger.debug(`Failed to load filter ${d}${t}:`,c)}try{if(g=(await globImport(`./${d}${t}`)).default,g)break}catch(c){logger.debug(`Failed to load legacy ${d}${t}:`,c)}if(g)break}if(!g)throw Error(`Could not load navigator implementation for: ${d}`);return new g(t,c,u)}async getWeightedCards(t){throw Error(`${this.constructor.name} must implement getWeightedCards(). `)}setEphemeralHints(t){}}}}),init_courseDB=__esm({"src/impl/couch/courseDB.ts"(){"use strict";init_couch(),init_updateQueue(),init_types_legacy(),init_logger(),init_clientCache(),init_courseAPI(),init_courseLookupDB(),init_navigators(),init_PipelineAssembler(),init_defaults(),CoursesDB=class{constructor(t){_defineProperty$2(this,`_courseIDs`,void 0),t&&t.length>0?this._courseIDs=t:this._courseIDs=void 0}async getCourseList(){let t=await CourseLookup.allCourseWare();return logger.debug(`AllCourses: ${t.map(t=>t.name+`, `+t._id+`
|
|
354
354
|
`)}`),this._courseIDs&&(t=t.filter(t=>this._courseIDs.includes(t._id))),logger.debug(`AllCourses.filtered: ${t.map(t=>t.name+`, `+t._id+`
|
|
355
355
|
`)}`),(await Promise.all(t.map(async t=>{try{let c=await getCredentialledCourseConfig(t._id);return logger.debug(`Found cfg: ${JSON.stringify(c)}`),c}catch(c){logger.warn(`Error fetching cfg for course ${t.name}, ${t._id}: ${c}`);return}}))).filter(t=>!!t)}async getCourseConfig(t){if(this._courseIDs&&this._courseIDs.length&&!this._courseIDs.includes(t))throw Error(`Course ${t} not in course list`);let c=await getCredentialledCourseConfig(t);if(c===void 0)throw Error(`Error fetching cfg for course ${t}`);return c}async disambiguateCourse(t,c){await CourseLookup.updateDisambiguator(t,c)}},CourseDB=class{constructor(t,c,u){_defineProperty$2(this,`db`,void 0),_defineProperty$2(this,`remoteDB`,void 0),_defineProperty$2(this,`id`,void 0),_defineProperty$2(this,`_getCurrentUser`,void 0),_defineProperty$2(this,`updateQueue`,void 0),_defineProperty$2(this,`_pendingHints`,null),_defineProperty$2(this,`_eloPoolCache`,null),_defineProperty$2(this,`_eloPoolTtlMs`,300*1e3),_defineProperty$2(this,`_cachedNavigator`,null),_defineProperty$2(this,`_navigatorTtlMs`,300*1e3),this.id=t;let d=getCourseDB2(this.id);this.remoteDB=d,this.db=u??d,this._getCurrentUser=c,this.updateQueue=new UpdateQueue(this.remoteDB,this.remoteDB)}getCourseID(){return this.id}async getCourseInfo(){return{cardCount:(await this.db.find({selector:{docType:`CARD`},limit:1e3})).docs.length,registeredUsers:0}}async getInexperiencedCards(t=2){return(await this.db.query(`cardsByInexperience`,{limit:t})).rows.map(t=>({courseId:this.id,cardId:t.id,count:t.key,elo:t.value}))}async getCardsByEloLimits(t={low:0,high:-(2**53-1),limit:25,page:0}){return(await this.db.query(`elo`,{startkey:t.low,endkey:t.high,limit:t.limit,skip:t.limit*t.page})).rows.map(t=>`${this.id}-${t.id}-${t.key}`)}async getCardEloData(t){let c=await this.db.allDocs({keys:t,include_docs:!0}),u=[];return c.rows.forEach(t=>{isSuccessRow(t)?t.doc&&t.doc.elo?u.push(toCourseElo(t.doc.elo)):(logger.warn(`no elo data for card: `+t.id),u.push(blankCourseElo())):(logger.warn(`no elo data for card: `+JSON.stringify(t)),u.push(blankCourseElo()))}),u}async getELOBounds(){let[t,c]=await Promise.all([(await this.db.query(`elo`,{startkey:0,limit:1,include_docs:!1})).rows[0].key,(await this.db.query(`elo`,{limit:1,descending:!0,startkey:1e5})).rows[0].key]);return{low:t,high:c}}async removeCard(t){let c=await this.remoteDB.get(t);if(!c.docType||c.docType!==`CARD`)throw Error(`failed to remove ${t} from course ${this.id}. id does not point to a card`);try{let c=await this.getAppliedTags(t);(await Promise.allSettled(c.rows.map(async c=>{let u=c.id;await this.removeTagFromCard(t,u)}))).forEach((u,d)=>{if(u.status===`rejected`){let m=c.rows[d].id;logger.error(`Failed to remove card ${t} from tag ${m}: ${u.reason}`)}})}catch(c){logger.error(`Error removing card ${t} from tags: ${c}`)}return this.remoteDB.remove(c)}async getCardDisplayableDataIDs(t){logger.debug(t.join(`, `));let c=await this.db.allDocs({keys:t,include_docs:!0}),u={};return c.rows.forEach(t=>{isSuccessRow(t)&&(u[t.id]=t.doc.id_displayable_data)}),u}async getCardsByELO(t,c){t=parseInt(t);let u=c||25,d=await this.db.query(`elo`,{limit:Math.ceil(u/2),startkey:t,descending:!0}),m=u-d.rows.length,g=await this.db.query(`elo`,{limit:m,startkey:t+1}),b=d.rows;b=b.concat(g.rows);let S=b.sort((c,u)=>{let d=Math.abs(c.key-t)-Math.abs(u.key-t);return d===0?Math.random()-.5:d}).map(t=>({courseID:this.id,cardID:t.id,elo:t.key})),C=`below:
|
|
356
356
|
${d.rows.map(t=>` ${t.id}-${t.key}
|