@vue-skuilder/standalone-ui 0.2.31 → 0.2.33

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.
@@ -309,7 +309,8 @@ Please double-check your map/reduce function.`),guardedConsole(`error`,c,u)}}fun
309
309
  Generator: ${t.name}
310
310
  Filters:${u}`)}function logTagHydration(t,c){let u=Array.from(c.values()).reduce((t,c)=>t+c.length,0),d=Array.from(c.values()).filter(t=>t.length>0).length;logger.debug(`[Pipeline] Tag hydration: ${t.length} cards, ${d} have tags (${u} total tags) - single batch query`)}function logExecutionSummary(t,c,u,d,m,g){let b=m.length>0?m.map(t=>t.toFixed(2)).join(`, `):`none`,S=``;g.length>0&&(S=`
311
311
  Filter impact: ${g.map(t=>{let c=[];return t.boosted>0&&c.push(`+${t.boosted}`),t.penalized>0&&c.push(`-${t.penalized}`),t.passed>0&&c.push(`=${t.passed}`),`${t.name}: ${c.join(`/`)}`}).join(`, `)}`),logger.info(`[Pipeline] Execution: ${t} produced ${c} \u2192 ${u} filters \u2192 ${d} results (top scores: ${b})`+S+`
312
- 💡 Inspect: window.skuilder.pipeline`)}function logResultCards(t){if(!(!VERBOSE_RESULTS||t.length===0)){logger.info(`[Pipeline] Results (${t.length} cards):`);for(let c=0;c<t.length;c++){let u=t[c],d=u.tags?.slice(0,3).join(`, `)||``,m=u.provenance.filter(t=>t.strategy===`hierarchyDefinition`||t.strategy===`priorityDefinition`||t.strategy===`interferenceFilter`||t.strategy===`letterGating`||t.strategy===`ephemeralHint`||t.strategy===`diversityRerank`).map(t=>{let c=t.action===`boosted`?`↑`:t.action===`penalized`?`↓`:`=`;return`${t.strategyName}${c}${t.score.toFixed(2)}`}).join(` | `);logger.info(`[Pipeline] ${String(c+1).padStart(2)}. ${u.score.toFixed(4)} ${u.cardId} [${d}]${m?` {${m}}`:``}`)}}}function logCardProvenance(t,c=3){let u=t.slice(0,c);logger.debug(`[Pipeline] Provenance for top ${u.length} cards:`);for(let t of u){logger.debug(`[Pipeline] ${t.cardId} (final score: ${t.score.toFixed(3)}):`);for(let c of t.provenance){let t=c.score.toFixed(3),u=c.action.padEnd(9);logger.debug(`[Pipeline] ${u} ${t} - ${c.strategyName}: ${c.reason}`)}}}function createDefaultEloStrategy(t){return{_id:`NAVIGATION_STRATEGY-ELO-default`,docType:`NAVIGATION_STRATEGY`,name:`ELO (default)`,description:`Default ELO-based navigation strategy for new cards`,implementingClass:`elo`,course:t,serializedData:``}}function createDefaultSrsStrategy(t){return{_id:`NAVIGATION_STRATEGY-SRS-default`,docType:`NAVIGATION_STRATEGY`,name:`SRS (default)`,description:`Default SRS-based navigation strategy for reviews`,implementingClass:`srs`,course:t,serializedData:``}}function createDefaultEloDistanceStrategy(t){return{_id:`NAVIGATION_STRATEGY-eloDistance-default`,docType:`NAVIGATION_STRATEGY`,name:`ELO Distance (default)`,description:`Scales every candidate, new or review, by its distance from the learner's ELO`,implementingClass:`eloDistance`,course:t,serializedData:JSON.stringify(DEFAULT_ELO_DISTANCE_CONFIG)}}function createDefaultPipeline(t,c){let u=c.getCourseID(),d=new ELONavigator(t,c,createDefaultEloStrategy(u)),m=new SRSNavigator(t,c,createDefaultSrsStrategy(u)),g=new CompositeGenerator([d,m]),b=new EloDistanceFilter(t,c,createDefaultEloDistanceStrategy(u));return new Pipeline(g,[b],t,c)}function planned(t,c,u){let d=c===`filter`?getRegisteredFilterKind(t.implementingClass):void 0;return{role:c,origin:u,name:t.name,implementingClass:t.implementingClass,strategy:t,...d?{kind:d}:{}}}function planPipeline(t,c){if(t.length===0)return{kind:`default`,generators:[planned(createDefaultEloStrategy(c),`generator`,`default-pipeline`),planned(createDefaultSrsStrategy(c),`generator`,`default-pipeline`)],filters:[planned(createDefaultEloDistanceStrategy(c),`filter`,`default-pipeline`)],skipped:[],warnings:[],notes:[],regulators:DEFAULT_REGULATOR_CONFIG};let u=[],d=[],m=[],g=[];for(let c of t)isGenerator(c.implementingClass)?u.push(planned(c,`generator`,`strategy-doc`)):isFilter(c.implementingClass)?d.push(planned(c,`filter`,`strategy-doc`)):(m.push({strategy:c,reason:`not a registered generator or filter`}),g.push(`Unknown strategy type '${c.implementingClass}', skipping: ${c.name}`));let b=new Set(u.map(t=>t.implementingClass));b.has(createDefaultEloStrategy(c).implementingClass)||u.push(planned(createDefaultEloStrategy(c),`generator`,`assembler-default`)),b.has(createDefaultSrsStrategy(c).implementingClass)||u.push(planned(createDefaultSrsStrategy(c),`generator`,`assembler-default`));let S=createDefaultEloDistanceStrategy(c);return d.some(t=>t.implementingClass===S.implementingClass)||d.push(planned(S,`filter`,`assembler-default`)),d.sort((t,c)=>t.name.localeCompare(c.name)),{kind:`assembled`,generators:u,filters:d,skipped:m,warnings:g,notes:[],regulators:DEFAULT_REGULATOR_CONFIG}}function registerNavigator(t,c,u){navigatorRegistry.set(t,{constructor:c,role:u}),logger.debug(`[NavigatorRegistry] Registered: ${t}${u?` (${u})`:``}`)}function getRegisteredNavigator(t){return navigatorRegistry.get(t)?.constructor}function hasRegisteredNavigator(t){return navigatorRegistry.has(t)}function getRegisteredNavigatorRole(t){return navigatorRegistry.get(t)?.role}function getRegisteredFilterKind(t){return navigatorRegistry.get(t)?.constructor?.kind}function getRegisteredNavigatorNames(){return Array.from(navigatorRegistry.keys())}async function initializeNavigatorRegistry(){logger.debug(`[NavigatorRegistry] Initializing built-in navigators...`);let[t,c]=await Promise.all([Promise.resolve().then(()=>(init_elo(),elo_exports)),Promise.resolve().then(()=>(init_srs(),srs_exports))]),u=await Promise.resolve().then(()=>(init_prescribed(),prescribed_exports));registerNavigator(`elo`,t.default),registerNavigator(`srs`,c.default),registerNavigator(`prescribed`,u.default);let[d,m,g,b,S]=await Promise.all([Promise.resolve().then(()=>(init_hierarchyDefinition(),hierarchyDefinition_exports)),Promise.resolve().then(()=>(init_interferenceMitigator(),interferenceMitigator_exports)),Promise.resolve().then(()=>(init_relativePriority(),relativePriority_exports)),Promise.resolve().then(()=>(init_userTagPreference(),userTagPreference_exports)),Promise.resolve().then(()=>(init_eloDistance(),eloDistance_exports))]);registerNavigator(`hierarchyDefinition`,d.default),registerNavigator(`interferenceMitigator`,m.default),registerNavigator(`relativePriority`,g.default),registerNavigator(`userTagPreference`,b.default),registerNavigator(`eloDistance`,S.default),logger.debug(`[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(`, `)}`)}function getCardOrigin(t){if(t.provenance.length===0)throw Error(`Card has no provenance - cannot determine origin`);let c=t.provenance[0].reason.toLowerCase();return c.includes(`failed`)?`failed`:c.includes(`review`)?`review`:`new`}function isGenerator(t){return NavigatorRoles[t]===`generator`?!0:getRegisteredNavigatorRole(t)===`generator`}function isFilter(t){return NavigatorRoles[t]===`filter`?!0:getRegisteredNavigatorRole(t)===`filter`}function randIntWeightedTowardZero(t){return Math.floor(Math.random()*Math.random()*Math.random()*t)}async function getCourseTagStubs(t){logger.debug(`Getting tag stubs for course: ${t}`);let c=await filterAllDocsByPrefix(getCourseDB2(t),`TAG`.valueOf()+`-`);return c.rows.forEach(t=>{logger.debug(` Tag stub for doc: ${t.id}`)}),c}async function createTag(t,c,u){logger.debug(`Creating tag: ${c}...`);let d=getTagID(c);return await getCourseDB2(t).put({course:t,docType:`TAG`,name:c,snippet:``,taggedCards:[],wiki:``,author:u,_id:d})}async function updateTag(t){let c=await getTag(t.course,t.name);return await getCourseDB2(t.course).put({...t,_rev:c._rev})}async function getTag(t,c){let u=getTagID(c);return getCourseDB2(t).get(u)}async function removeTagFromCard(t,c,u){u=getTagID(u);let d=getCourseDB2(t),m=await d.get(u);return m.taggedCards=m.taggedCards.filter(t=>c!==t),d.put(m)}async function getAppliedTags(t,c){return await getCourseDB2(t).query(`getTags`,{startkey:c,endkey:c})}async function updateCredentialledCourseConfig(t,c){logger.debug(`Updating course config:
312
+ 💡 Inspect: window.skuilder.pipeline`)}function logResultCards(t){if(!(!VERBOSE_RESULTS||t.length===0)){logger.info(`[Pipeline] Results (${t.length} cards):`);for(let c=0;c<t.length;c++){let u=t[c],d=u.tags?.slice(0,3).join(`, `)||``,m=u.provenance.filter(t=>t.strategy===`hierarchyDefinition`||t.strategy===`priorityDefinition`||t.strategy===`interferenceFilter`||t.strategy===`letterGating`||t.strategy===`ephemeralHint`||t.strategy===`diversityRerank`).map(t=>{let c=t.action===`boosted`?`↑`:t.action===`penalized`?`↓`:`=`;return`${t.strategyName}${c}${t.score.toFixed(2)}`}).join(` | `);logger.info(`[Pipeline] ${String(c+1).padStart(2)}. ${u.score.toFixed(4)} ${u.cardId} [${d}]${m?` {${m}}`:``}`)}}}function logCardProvenance(t,c=3){let u=t.slice(0,c);logger.debug(`[Pipeline] Provenance for top ${u.length} cards:`);for(let t of u){logger.debug(`[Pipeline] ${t.cardId} (final score: ${t.score.toFixed(3)}):`);for(let c of t.provenance){let t=c.score.toFixed(3),u=c.action.padEnd(9);logger.debug(`[Pipeline] ${u} ${t} - ${c.strategyName}: ${c.reason}`)}}}function setAppVersion(t){hostAppVersion=t}function sessionVersions(){return{framework:FRAMEWORK_VERSION,...hostAppVersion?{app:hostAppVersion}:{}}}function stableStringify(t){return Array.isArray(t)?`[${t.map(stableStringify).join(`,`)}]`:t&&typeof t==`object`?`{${Object.entries(t).filter(([,t])=>t!==void 0).sort(([t],[c])=>t<c?-1:t>c?1:0).map(([t,c])=>`${JSON.stringify(t)}:${stableStringify(c)}`).join(`,`)}}`:JSON.stringify(t)}function strategyHash(t){if(t.length===0)return DEFAULT_STRATEGY_HASH;let c=t.map(t=>{let{_rev:c,...u}=t;return stableStringify(u)}).sort().join(`
313
+ `),u=2166136261;for(let t=0;t<c.length;t++)u^=c.charCodeAt(t),u=Math.imul(u,16777619);return(u>>>0).toString(16).padStart(8,`0`)}function createDefaultEloStrategy(t){return{_id:`NAVIGATION_STRATEGY-ELO-default`,docType:`NAVIGATION_STRATEGY`,name:`ELO (default)`,description:`Default ELO-based navigation strategy for new cards`,implementingClass:`elo`,course:t,serializedData:``}}function createDefaultSrsStrategy(t){return{_id:`NAVIGATION_STRATEGY-SRS-default`,docType:`NAVIGATION_STRATEGY`,name:`SRS (default)`,description:`Default SRS-based navigation strategy for reviews`,implementingClass:`srs`,course:t,serializedData:``}}function createDefaultEloDistanceStrategy(t){return{_id:`NAVIGATION_STRATEGY-eloDistance-default`,docType:`NAVIGATION_STRATEGY`,name:`ELO Distance (default)`,description:`Scales every candidate, new or review, by its distance from the learner's ELO`,implementingClass:`eloDistance`,course:t,serializedData:JSON.stringify(DEFAULT_ELO_DISTANCE_CONFIG)}}function createDefaultPipeline(t,c){let u=c.getCourseID(),d=new ELONavigator(t,c,createDefaultEloStrategy(u)),m=new SRSNavigator(t,c,createDefaultSrsStrategy(u)),g=new CompositeGenerator([d,m]),b=new EloDistanceFilter(t,c,createDefaultEloDistanceStrategy(u)),S=new Pipeline(g,[b],t,c);return S.strategyHash=DEFAULT_STRATEGY_HASH,S}function planned(t,c,u){let d=c===`filter`?getRegisteredFilterKind(t.implementingClass):void 0;return{role:c,origin:u,name:t.name,implementingClass:t.implementingClass,strategy:t,...d?{kind:d}:{}}}function planPipeline(t,c){if(t.length===0)return{kind:`default`,generators:[planned(createDefaultEloStrategy(c),`generator`,`default-pipeline`),planned(createDefaultSrsStrategy(c),`generator`,`default-pipeline`)],filters:[planned(createDefaultEloDistanceStrategy(c),`filter`,`default-pipeline`)],skipped:[],warnings:[],notes:[],regulators:DEFAULT_REGULATOR_CONFIG};let u=[],d=[],m=[],g=[];for(let c of t)isGenerator(c.implementingClass)?u.push(planned(c,`generator`,`strategy-doc`)):isFilter(c.implementingClass)?d.push(planned(c,`filter`,`strategy-doc`)):(m.push({strategy:c,reason:`not a registered generator or filter`}),g.push(`Unknown strategy type '${c.implementingClass}', skipping: ${c.name}`));let b=new Set(u.map(t=>t.implementingClass));b.has(createDefaultEloStrategy(c).implementingClass)||u.push(planned(createDefaultEloStrategy(c),`generator`,`assembler-default`)),b.has(createDefaultSrsStrategy(c).implementingClass)||u.push(planned(createDefaultSrsStrategy(c),`generator`,`assembler-default`));let S=createDefaultEloDistanceStrategy(c);return d.some(t=>t.implementingClass===S.implementingClass)||d.push(planned(S,`filter`,`assembler-default`)),d.sort((t,c)=>t.name.localeCompare(c.name)),{kind:`assembled`,generators:u,filters:d,skipped:m,warnings:g,notes:[],regulators:DEFAULT_REGULATOR_CONFIG}}function registerNavigator(t,c,u){navigatorRegistry.set(t,{constructor:c,role:u}),logger.debug(`[NavigatorRegistry] Registered: ${t}${u?` (${u})`:``}`)}function getRegisteredNavigator(t){return navigatorRegistry.get(t)?.constructor}function hasRegisteredNavigator(t){return navigatorRegistry.has(t)}function getRegisteredNavigatorRole(t){return navigatorRegistry.get(t)?.role}function getRegisteredFilterKind(t){return navigatorRegistry.get(t)?.constructor?.kind}function getRegisteredNavigatorNames(){return Array.from(navigatorRegistry.keys())}async function initializeNavigatorRegistry(){logger.debug(`[NavigatorRegistry] Initializing built-in navigators...`);let[t,c]=await Promise.all([Promise.resolve().then(()=>(init_elo(),elo_exports)),Promise.resolve().then(()=>(init_srs(),srs_exports))]),u=await Promise.resolve().then(()=>(init_prescribed(),prescribed_exports));registerNavigator(`elo`,t.default),registerNavigator(`srs`,c.default),registerNavigator(`prescribed`,u.default);let[d,m,g,b,S]=await Promise.all([Promise.resolve().then(()=>(init_hierarchyDefinition(),hierarchyDefinition_exports)),Promise.resolve().then(()=>(init_interferenceMitigator(),interferenceMitigator_exports)),Promise.resolve().then(()=>(init_relativePriority(),relativePriority_exports)),Promise.resolve().then(()=>(init_userTagPreference(),userTagPreference_exports)),Promise.resolve().then(()=>(init_eloDistance(),eloDistance_exports))]);registerNavigator(`hierarchyDefinition`,d.default),registerNavigator(`interferenceMitigator`,m.default),registerNavigator(`relativePriority`,g.default),registerNavigator(`userTagPreference`,b.default),registerNavigator(`eloDistance`,S.default),logger.debug(`[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(`, `)}`)}function getCardOrigin(t){if(t.provenance.length===0)throw Error(`Card has no provenance - cannot determine origin`);let c=t.provenance[0].reason.toLowerCase();return c.includes(`failed`)?`failed`:c.includes(`review`)?`review`:`new`}function isGenerator(t){return NavigatorRoles[t]===`generator`?!0:getRegisteredNavigatorRole(t)===`generator`}function isFilter(t){return NavigatorRoles[t]===`filter`?!0:getRegisteredNavigatorRole(t)===`filter`}function randIntWeightedTowardZero(t){return Math.floor(Math.random()*Math.random()*Math.random()*t)}async function getCourseTagStubs(t){logger.debug(`Getting tag stubs for course: ${t}`);let c=await filterAllDocsByPrefix(getCourseDB2(t),`TAG`.valueOf()+`-`);return c.rows.forEach(t=>{logger.debug(` Tag stub for doc: ${t.id}`)}),c}async function createTag(t,c,u){logger.debug(`Creating tag: ${c}...`);let d=getTagID(c);return await getCourseDB2(t).put({course:t,docType:`TAG`,name:c,snippet:``,taggedCards:[],wiki:``,author:u,_id:d})}async function updateTag(t){let c=await getTag(t.course,t.name);return await getCourseDB2(t.course).put({...t,_rev:c._rev})}async function getTag(t,c){let u=getTagID(c);return getCourseDB2(t).get(u)}async function removeTagFromCard(t,c,u){u=getTagID(u);let d=getCourseDB2(t),m=await d.get(u);return m.taggedCards=m.taggedCards.filter(t=>c!==t),d.put(m)}async function getAppliedTags(t,c){return await getCourseDB2(t).query(`getTags`,{startkey:c,endkey:c})}async function updateCredentialledCourseConfig(t,c){logger.debug(`Updating course config:
313
314
 
314
315
  ${JSON.stringify(c)}
315
316
  `);let u=getCourseDB2(t),d=await getCredentialledCourseConfig(t);return await u.put({...c,_rev:d._rev})}function isSuccessRow(t){return`doc`in t&&t.doc!==null&&t.doc!==void 0}async function getCurrentSession(){try{if(ENV.COUCHDB_SERVER_URL===NOT_SET||ENV.COUCHDB_SERVER_PROTOCOL===NOT_SET)throw Error(`CouchDB server configuration not properly initialized. Protocol: "${ENV.COUCHDB_SERVER_PROTOCOL}", URL: "${ENV.COUCHDB_SERVER_URL}"`);let t=ENV.COUCHDB_SERVER_URL.endsWith(`/`)?ENV.COUCHDB_SERVER_URL.slice(0,-1):ENV.COUCHDB_SERVER_URL,c=`${ENV.COUCHDB_SERVER_PROTOCOL}://${t}/_session`;logger.debug(`Attempting session check at: ${c}`);let u=await(0,import_browser_ponyfill.default)(c,{method:`GET`,credentials:`include`});if(!u.ok)throw Error(`Session check failed: ${u.status}`);return await u.json()}catch(t){let c=ENV.COUCHDB_SERVER_URL.endsWith(`/`)?ENV.COUCHDB_SERVER_URL.slice(0,-1):ENV.COUCHDB_SERVER_URL,u=`${ENV.COUCHDB_SERVER_PROTOCOL}://${c}/_session`;throw logger.error(`Session check error attempting to connect to: ${u} - ${t}`),Error(`Session check failed connecting to ${u}: ${t}`)}}async function getLoggedInUsername(){let t=await getCurrentSession();if(t.userCtx.name&&t.userCtx.name!==``)return t.userCtx.name;throw Error(`No logged in user`)}function createPouchDBConfig(){return ENV.COUCHDB_USERNAME&&ENV.COUCHDB_PASSWORD&&typeof window>`u`?{fetch(t,c={}){let u=btoa(`${ENV.COUCHDB_USERNAME}:${ENV.COUCHDB_PASSWORD}`),d=new Headers(c.headers||{});d.set(`Authorization`,`Basic ${u}`);let m={...c,headers:d};return pouchdb_setup_default.fetch(t,m)}}:pouchDBincludeCredentialsConfig}function getCourseDB2(t){return new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+`coursedb-`+t,createPouchDBConfig())}function filterAllDocsByPrefix(t,c,u){let d={startkey:c,endkey:c+`￰`,include_docs:!0};return u&&Object.assign(d,u),t.allDocs(d)}function getStartAndEndKeys(t){return{startkey:t,endkey:t+`￰`}}function newInterval(t,c){return areQuestionRecords(c)?newQuestionInterval(t,c):1e5}function newQuestionInterval(t,c){let u=c.records,d=u[u.length-1],m=lastSuccessfulInterval(u);if(m>c.bestInterval&&(c.bestInterval=m,t.update(c._id,{bestInterval:m}).catch(t=>{logger.warn(`[SpacedRepetition] Failed to update bestInterval for ${c._id}: ${t?.message??t}`)})),d.isCorrect){let t=d.performance,u=isTaggedPerformance(t)?t._global:t,g=Math.min(1,Math.max(0,u));logger.debug(`Demontrated skill: ${g}`);let b=m*(.75+g);if(c.lapses=getLapses(c.records),c.streak=getStreak(c.records),c.lapses&&c.streak&&c.bestInterval&&(c.lapses>=0||c.streak>=0)){let t=(c.lapses*b+c.streak*c.bestInterval)/(c.lapses+c.streak);return logger.debug(`Weighted average interval calculation:
@@ -320,11 +321,11 @@ ${t}`)}function headerHtml(){let t=Date.now()<copyFlashUntil;return`<div style="
320
321
  Presentation sequence (first 20):`);let t=c.presentations.slice(0,20).map((t,c)=>`${c+1}. ${t.courseName||t.courseId.slice(0,8)} (${t.origin})`).join(`
321
322
  `);logger.info(t)}let m=0,g=1,b=c.presentations[0]?.courseId;for(let t=1;t<c.presentations.length;t++)c.presentations[t].courseId===b?(g++,m=Math.max(m,g)):(b=c.presentations[t].courseId,g=1);m>3&&(logger.info(`
322
323
  \u26A0\uFE0F Detected clustering: max ${m} cards from same course in a row`),logger.info(`This suggests cards are sorted by score rather than round-robin by course.`)),console.groupEnd()}function mountSessionDebugger(){if(typeof window>`u`)return;let t=window;t.skuilder=t.skuilder||{},t.skuilder.session=sessionDebugAPI}function sig4(t){return Number(t.toPrecision(4))}function toRunCard(t){return{cardId:t.cardId,origin:t.origin,...t.generator?{generator:t.generator}:{},...t.required?{required:t.required}:{},score:Number.isFinite(t.finalScore)?sig4(t.finalScore):null,selected:t.selected}}function toRunCardTrail(t){return{...toRunCard(t),trail:t.provenance.filter(t=>t.action!==`passed`).map(t=>({strategyName:t.strategyName,action:t.action,score:sig4(t.score),reason:t.reason}))}}function persistedReading(t){return{...t,urgency:sig4(t.urgency),multiplier:sig4(t.multiplier),inputs:Object.fromEntries(Object.entries(t.inputs).map(([t,c])=>[t,sig4(c)]))}}function persistedRunCards(t){let c=t.cards.filter(t=>t.selected),u=t.cards.filter(t=>!t.selected).slice(0,PERSISTED_RUNNERS_UP);return[...c,...u].map(toRunCard)}function persistedUnselectedNew(t){return{...t.nextInLine?{nextInLine:toRunCardTrail(t.nextInLine)}:{},...t.topGenerated?{topGenerated:toRunCardTrail(t.topGenerated)}:{}}}function makeScheduledCardId(t){return DocTypePrefixes.SCHEDULED_CARD+hooks.utc(t).format(REVIEW_TIME_FORMAT2)}function hexEncode(t){let c,u=``;for(let d=0;d<t.length;d++)c=t.charCodeAt(d).toString(16),u+=(`000`+c).slice(3);return u}function filterAllDocsByPrefix2(t,c,u){let d={startkey:c,endkey:c+`￰`,include_docs:!0};return u&&Object.assign(d,u),t.allDocs(d)}function getStartAndEndKeys2(t){return{startkey:t,endkey:t+`￰`}}function updateGuestAccountExpirationDate(t){let c=hooks.utc().add(2,`months`).toISOString(),u=`GuestAccountExpirationDate`;t.get(u).then(d=>t.put({_id:u,_rev:d._rev,date:c})).catch(()=>t.put({_id:u,date:c}))}function getLocalUserDB(t){let c=`userdb-${t}`;return typeof window>`u`?new pouchdb_setup_default(getDbPath(c),{}):new pouchdb_setup_default(c,{})}function scheduleCardReviewLocal(t,c){let u=hooks.utc();logger.info(`Scheduling for review in: ${c.time.diff(u,`h`)/24} days`),t.put({_id:makeScheduledCardId(c.time),cardId:c.card_id,reviewTime:c.time.toISOString(),courseId:c.course_id,scheduledAt:u.toISOString(),scheduledFor:c.scheduledFor,schedulingAgentId:c.schedulingAgentId})}async function removeScheduledCardReviewLocal(t,c){let u=await t.get(c);t.remove(u).then(t=>{t.ok&&log3(`Removed Review Doc: ${c}`)}).catch(t=>{log3(`Failed to remove Review Doc: ${c},
323
- ${JSON.stringify(t)}`)})}function withTimeout(t,c,u){let d;return Promise.race([t,new Promise((t,m)=>{d=setTimeout(()=>m(Error(`${u} timed out after ${c}ms`)),c)})]).finally(()=>{d!==void 0&&clearTimeout(d)})}function accomodateGuest(){if(logger.log(`[funnel] accomodateGuest() called`),typeof localStorage>`u`)return logger.log(`[funnel] localStorage not available (Node.js environment), returning default guest`),{username:GuestUsername+`nodejs-test`,firstVisit:!0};let t=`sk-guest-uuid`,c,u=localStorage.getItem(t);if(logger.log(`[funnel] Checking localStorage for key:`,t),logger.log(`[funnel] Existing UUID value:`,u),logger.log(`[funnel] existingUUID !== null:`,u!==null),u!==null)c=!1,logger.log(`[funnel] Returning guest ${u} "logging in".`);else{c=!0,logger.log(`[funnel] No existing UUID, generating new one...`);let u=generateUUID();logger.log(`[funnel] Generated UUID:`,u),logger.log(`[funnel] UUID length:`,u.length);try{localStorage.setItem(t,u),logger.log(`[funnel] Successfully stored UUID in localStorage`);let c=localStorage.getItem(t);logger.log(`[funnel] Verification read from localStorage:`,c)}catch(t){logger.error(`[funnel] ERROR storing UUID:`,t)}logger.log(`[funnel] Accommodating a new guest with account: ${u}`)}let d=localStorage.getItem(t),m=GuestUsername+d;return logger.log(`[funnel] Final UUID from localStorage:`,d),logger.log(`[funnel] GuestUsername constant:`,GuestUsername),logger.log(`[funnel] Final username to return:`,m),{username:m,firstVisit:c};function generateUUID(){if(logger.log(`[funnel] Inside generateUUID()`),typeof crypto<`u`&&typeof crypto.randomUUID==`function`){let t=crypto.randomUUID();return logger.log(`[funnel] Generated UUID using crypto.randomUUID():`,t),t}if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`){let t=new Uint8Array(16);crypto.getRandomValues(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128;let c=[Array.from(t.slice(0,4)).map(t=>t.toString(16).padStart(2,`0`)).join(``),Array.from(t.slice(4,6)).map(t=>t.toString(16).padStart(2,`0`)).join(``),Array.from(t.slice(6,8)).map(t=>t.toString(16).padStart(2,`0`)).join(``),Array.from(t.slice(8,10)).map(t=>t.toString(16).padStart(2,`0`)).join(``),Array.from(t.slice(10,16)).map(t=>t.toString(16).padStart(2,`0`)).join(``)].join(`-`);return logger.log(`[funnel] Generated UUID using crypto.getRandomValues():`,c),c}logger.warn(`[funnel] crypto API not available, using timestamp-based UUID (NOT SECURE)`);let t=new Date().getTime();typeof performance<`u`&&typeof performance.now==`function`&&(t+=performance.now());let c=`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,c=>{let u=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(c===`x`?u:u&3|8).toString(16)});return logger.log(`[funnel] Generated UUID (fallback):`,c),c}}async function getOrCreateClassroomRegistrationsDoc(t){let c;try{c=await getLocalUserDB(t).get(userClassroomsDoc)}catch(u){let d=u;if(d.status===404)await getLocalUserDB(t).put({_id:userClassroomsDoc,registrations:[]}),c=await getOrCreateClassroomRegistrationsDoc(t);else{let t={name:d.name,status:d.status,message:d.message,reason:d.reason,error:d.error};throw logger.error(`Database error in getOrCreateClassroomRegistrationsDoc (standalone function):`,t),Error(`Database error accessing classroom registrations: ${d.message||d.name||`Unknown error`} (status: ${d.status})`)}}return c}async function getOrCreateCourseRegistrationsDoc(t){let c;try{c=await getLocalUserDB(t).get(userCoursesDoc)}catch(u){if(u.status===404)await getLocalUserDB(t).put({_id:userCoursesDoc,courses:[],studyWeight:{}}),c=await getOrCreateCourseRegistrationsDoc(t);else throw Error(`Unexpected error ${JSON.stringify(u)} in getOrCreateCourseRegistrationDoc...`)}return c}async function updateUserElo(t,c,u){let d=await getOrCreateCourseRegistrationsDoc(t),m=d.courses.find(t=>t.courseID===c);return m.elo=u,getLocalUserDB(t).put(d)}async function registerUserForClassroom(t,c,u){return log4(`Registering user: ${t} in course: ${c}`),getOrCreateClassroomRegistrationsDoc(t).then(d=>{let m={classID:c,registeredAs:u};return d.registrations.filter(t=>t.classID===m.classID&&t.registeredAs===m.registeredAs).length===0?d.registrations.push(m):log4(`User ${t} is already registered for class ${c}`),getLocalUserDB(t).put(d)})}async function dropUserFromClassroom(t,c){return getOrCreateClassroomRegistrationsDoc(t).then(u=>{let d=-1;for(let t=0;t<u.registrations.length;t++)u.registrations[t].classID===c&&(d=t);return d!==-1&&u.registrations.splice(d,1),getLocalUserDB(t).put(u)})}async function getUserClassrooms(t){return getOrCreateClassroomRegistrationsDoc(t)}async function initializeDataLayer(t){if(dataLayerInstance)return logger.warn(`Data layer already initialized. Returning existing instance.`),dataLayerInstance;if(await initializeNavigatorRegistry(),t.options.localStoragePrefix&&(ENV.LOCAL_STORAGE_PREFIX=t.options.localStoragePrefix),t.type===`couch`){if(!t.options.COUCHDB_SERVER_URL||!t.options.COUCHDB_SERVER_PROTOCOL)throw Error(`Missing CouchDB server URL or protocol`);if(ENV.COUCHDB_SERVER_PROTOCOL=t.options.COUCHDB_SERVER_PROTOCOL,ENV.COUCHDB_SERVER_URL=t.options.COUCHDB_SERVER_URL,ENV.COUCHDB_USERNAME=t.options.COUCHDB_USERNAME,ENV.COUCHDB_PASSWORD=t.options.COUCHDB_PASSWORD,t.options.courseSync){let{CourseSyncService:c}=await Promise.resolve().then(()=>(init_CourseSyncService(),CourseSyncService_exports));c.getInstance().configure(t.options.courseSync)}if(t.options.COUCHDB_PASSWORD&&t.options.COUCHDB_USERNAME&&typeof window<`u`){let{CouchDBSyncStrategy:c}=await Promise.resolve().then(()=>(init_CouchDBSyncStrategy(),CouchDBSyncStrategy_exports)),u=new c,d=await(await BaseUser.instance(u,t.options.COUCHDB_USERNAME)).login(t.options.COUCHDB_USERNAME,t.options.COUCHDB_PASSWORD);d.ok?logger.info(`Successfully authenticated as ${t.options.COUCHDB_USERNAME}`):logger.warn(`Authentication failed: ${d.error}`)}let{CouchDataLayerProvider:c}=await Promise.resolve().then(()=>(init_PouchDataLayerProvider(),PouchDataLayerProvider_exports));dataLayerInstance=new c(t.options.COURSE_IDS)}else if(t.type===`static`){let{StaticDataLayerProvider:c}=await Promise.resolve().then(()=>(init_StaticDataLayerProvider(),StaticDataLayerProvider_exports));dataLayerInstance=new c(t.options)}else throw Error(`Unknown data layer type: ${t.type}`);return await dataLayerInstance.initialize(),dataLayerInstance}function getDataLayer(){if(!dataLayerInstance)throw Error(`Data layer not initialized. Call initializeDataLayer first.`);return dataLayerInstance}async function _resetDataLayer(){dataLayerInstance&&await dataLayerInstance.teardown(),dataLayerInstance=null}function isReview(t){return t.status===`review`||t.status===`failed-review`||`reviewID`in t}async function getStudySource(t,c){return t.type===`classroom`?await StudentClassroomDB.factory(t.id,c):hasActiveFilter(t.tagFilter)?new TagFilteredContentSource(t.id,t.tagFilter,c):getDataLayer().getCourseDB(t.id)}function buildStrategyStateId(t,c){return`STRATEGY_STATE::${t}::${c}`}async function importParsedCards(t,c,u){let d=[];for(let m of t)try{let t=await processCard(m,c,u);d.push(t)}catch(t){logger.error(`Error processing card:`,t);let c=m.markdown;m.tags&&m.tags.length>0&&(c+=`
324
+ ${JSON.stringify(t)}`)})}function withTimeout(t,c,u){let d;return Promise.race([t,new Promise((t,m)=>{d=setTimeout(()=>m(Error(`${u} timed out after ${c}ms`)),c)})]).finally(()=>{d!==void 0&&clearTimeout(d)})}function accomodateGuest(){if(logger.log(`[funnel] accomodateGuest() called`),typeof localStorage>`u`)return logger.log(`[funnel] localStorage not available (Node.js environment), returning default guest`),{username:GuestUsername+`nodejs-test`,firstVisit:!0};let t=`sk-guest-uuid`,c,u=localStorage.getItem(t);if(logger.log(`[funnel] Checking localStorage for key:`,t),logger.log(`[funnel] Existing UUID value:`,u),logger.log(`[funnel] existingUUID !== null:`,u!==null),u!==null)c=!1,logger.log(`[funnel] Returning guest ${u} "logging in".`);else{c=!0,logger.log(`[funnel] No existing UUID, generating new one...`);let u=generateUUID();logger.log(`[funnel] Generated UUID:`,u),logger.log(`[funnel] UUID length:`,u.length);try{localStorage.setItem(t,u),logger.log(`[funnel] Successfully stored UUID in localStorage`);let c=localStorage.getItem(t);logger.log(`[funnel] Verification read from localStorage:`,c)}catch(t){logger.error(`[funnel] ERROR storing UUID:`,t)}logger.log(`[funnel] Accommodating a new guest with account: ${u}`)}let d=localStorage.getItem(t),m=GuestUsername+d;return logger.log(`[funnel] Final UUID from localStorage:`,d),logger.log(`[funnel] GuestUsername constant:`,GuestUsername),logger.log(`[funnel] Final username to return:`,m),{username:m,firstVisit:c};function generateUUID(){if(logger.log(`[funnel] Inside generateUUID()`),typeof crypto<`u`&&typeof crypto.randomUUID==`function`){let t=crypto.randomUUID();return logger.log(`[funnel] Generated UUID using crypto.randomUUID():`,t),t}if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`){let t=new Uint8Array(16);crypto.getRandomValues(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128;let c=[Array.from(t.slice(0,4)).map(t=>t.toString(16).padStart(2,`0`)).join(``),Array.from(t.slice(4,6)).map(t=>t.toString(16).padStart(2,`0`)).join(``),Array.from(t.slice(6,8)).map(t=>t.toString(16).padStart(2,`0`)).join(``),Array.from(t.slice(8,10)).map(t=>t.toString(16).padStart(2,`0`)).join(``),Array.from(t.slice(10,16)).map(t=>t.toString(16).padStart(2,`0`)).join(``)].join(`-`);return logger.log(`[funnel] Generated UUID using crypto.getRandomValues():`,c),c}logger.warn(`[funnel] crypto API not available, using timestamp-based UUID (NOT SECURE)`);let t=new Date().getTime();typeof performance<`u`&&typeof performance.now==`function`&&(t+=performance.now());let c=`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,c=>{let u=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(c===`x`?u:u&3|8).toString(16)});return logger.log(`[funnel] Generated UUID (fallback):`,c),c}}async function getOrCreateClassroomRegistrationsDoc(t){let c;try{c=await getLocalUserDB(t).get(userClassroomsDoc)}catch(u){let d=u;if(d.status===404)await getLocalUserDB(t).put({_id:userClassroomsDoc,registrations:[]}),c=await getOrCreateClassroomRegistrationsDoc(t);else{let t={name:d.name,status:d.status,message:d.message,reason:d.reason,error:d.error};throw logger.error(`Database error in getOrCreateClassroomRegistrationsDoc (standalone function):`,t),Error(`Database error accessing classroom registrations: ${d.message||d.name||`Unknown error`} (status: ${d.status})`)}}return c}async function getOrCreateCourseRegistrationsDoc(t){let c;try{c=await getLocalUserDB(t).get(userCoursesDoc)}catch(u){if(u.status===404)await getLocalUserDB(t).put({_id:userCoursesDoc,courses:[],studyWeight:{}}),c=await getOrCreateCourseRegistrationsDoc(t);else throw Error(`Unexpected error ${JSON.stringify(u)} in getOrCreateCourseRegistrationDoc...`)}return c}async function updateUserElo(t,c,u){let d=await getOrCreateCourseRegistrationsDoc(t),m=d.courses.find(t=>t.courseID===c);return m.elo=u,getLocalUserDB(t).put(d)}async function registerUserForClassroom(t,c,u){return log4(`Registering user: ${t} in course: ${c}`),getOrCreateClassroomRegistrationsDoc(t).then(d=>{let m={classID:c,registeredAs:u};return d.registrations.filter(t=>t.classID===m.classID&&t.registeredAs===m.registeredAs).length===0?d.registrations.push(m):log4(`User ${t} is already registered for class ${c}`),getLocalUserDB(t).put(d)})}async function dropUserFromClassroom(t,c){return getOrCreateClassroomRegistrationsDoc(t).then(u=>{let d=-1;for(let t=0;t<u.registrations.length;t++)u.registrations[t].classID===c&&(d=t);return d!==-1&&u.registrations.splice(d,1),getLocalUserDB(t).put(u)})}async function getUserClassrooms(t){return getOrCreateClassroomRegistrationsDoc(t)}async function initializeDataLayer(t){if(dataLayerInstance)return logger.warn(`Data layer already initialized. Returning existing instance.`),dataLayerInstance;if(await initializeNavigatorRegistry(),t.options.localStoragePrefix&&(ENV.LOCAL_STORAGE_PREFIX=t.options.localStoragePrefix),t.options.appVersion&&setAppVersion(t.options.appVersion),t.type===`couch`){if(!t.options.COUCHDB_SERVER_URL||!t.options.COUCHDB_SERVER_PROTOCOL)throw Error(`Missing CouchDB server URL or protocol`);if(ENV.COUCHDB_SERVER_PROTOCOL=t.options.COUCHDB_SERVER_PROTOCOL,ENV.COUCHDB_SERVER_URL=t.options.COUCHDB_SERVER_URL,ENV.COUCHDB_USERNAME=t.options.COUCHDB_USERNAME,ENV.COUCHDB_PASSWORD=t.options.COUCHDB_PASSWORD,t.options.courseSync){let{CourseSyncService:c}=await Promise.resolve().then(()=>(init_CourseSyncService(),CourseSyncService_exports));c.getInstance().configure(t.options.courseSync)}if(t.options.COUCHDB_PASSWORD&&t.options.COUCHDB_USERNAME&&typeof window<`u`){let{CouchDBSyncStrategy:c}=await Promise.resolve().then(()=>(init_CouchDBSyncStrategy(),CouchDBSyncStrategy_exports)),u=new c,d=await(await BaseUser.instance(u,t.options.COUCHDB_USERNAME)).login(t.options.COUCHDB_USERNAME,t.options.COUCHDB_PASSWORD);d.ok?logger.info(`Successfully authenticated as ${t.options.COUCHDB_USERNAME}`):logger.warn(`Authentication failed: ${d.error}`)}let{CouchDataLayerProvider:c}=await Promise.resolve().then(()=>(init_PouchDataLayerProvider(),PouchDataLayerProvider_exports));dataLayerInstance=new c(t.options.COURSE_IDS)}else if(t.type===`static`){let{StaticDataLayerProvider:c}=await Promise.resolve().then(()=>(init_StaticDataLayerProvider(),StaticDataLayerProvider_exports));dataLayerInstance=new c(t.options)}else throw Error(`Unknown data layer type: ${t.type}`);return await dataLayerInstance.initialize(),dataLayerInstance}function getDataLayer(){if(!dataLayerInstance)throw Error(`Data layer not initialized. Call initializeDataLayer first.`);return dataLayerInstance}async function _resetDataLayer(){dataLayerInstance&&await dataLayerInstance.teardown(),dataLayerInstance=null}function isReview(t){return t.status===`review`||t.status===`failed-review`||`reviewID`in t}async function getStudySource(t,c){return t.type===`classroom`?await StudentClassroomDB.factory(t.id,c):hasActiveFilter(t.tagFilter)?new TagFilteredContentSource(t.id,t.tagFilter,c):getDataLayer().getCourseDB(t.id)}function buildStrategyStateId(t,c){return`STRATEGY_STATE::${t}::${c}`}async function importParsedCards(t,c,u){let d=[];for(let m of t)try{let t=await processCard(m,c,u);d.push(t)}catch(t){logger.error(`Error processing card:`,t);let c=m.markdown;m.tags&&m.tags.length>0&&(c+=`
324
325
  tags: ${m.tags.join(`, `)}`),m.elo!==void 0&&(c+=`
325
326
  elo: ${m.elo}`),d.push({originalText:c,status:`error`,message:`Error processing card: ${t instanceof Error?t.message:`Unknown error`}`})}return d}async function processCard(t,c,u){let{markdown:d,tags:m,elo:g}=t,b=d;m.length>0&&(b+=`
326
327
  tags: ${m.join(`, `)}`),g!==void 0&&(b+=`
327
- elo: ${g}`);let S={Input:d,Uploads:[]},C={};for(let t of m)C[t]={score:g||0,count:1};try{let t=await c.addNote(u.courseCode,u.dataShape,S,u.userName,m,void 0,g?{global:{score:g,count:1},tags:C,misc:{}}:void 0);return t.status===Status.ok?{originalText:b,status:`success`,message:`Card added successfully.`,cardId:t.id?t.id:`(unknown)`}:{originalText:b,status:`error`,message:t.message||`Failed to add card to database. Unknown error.`}}catch(t){return logger.error(`Error adding note:`,t),{originalText:b,status:`error`,message:`Error adding card: ${t instanceof Error?t.message:`Unknown error`}`}}}function validateProcessorConfig(t){return t.dataShape?t.courseCode?t.userName?{isValid:!0}:{isValid:!1,errorMessage:`No user name provided for card processing`}:{isValid:!1,errorMessage:`No course code provided for card processing`}:{isValid:!1,errorMessage:`No data shape provided for card processing`}}function getUserDB(){try{return getDataLayer().getUserDB()}catch{return logger.info(`[UserDB Debug] Data layer not initialized yet.`),null}}function getRawDB(){let t=getUserDB();return t?t.localDB||(logger.info(`[UserDB Debug] Unable to access raw database instance.`),null):null}function formatTimestamp(t){return new Date(t).toLocaleString()}function mountUserDBDebugger(){if(typeof window>`u`)return;let t=window;t.skuilder=t.skuilder||{},t.skuilder.userdb=userDBDebugAPI}function isDataShapeRegistered(t,c){let u=NameSpacer.getDataShapeString({dataShape:t.name,course:t.course});return c.dataShapes.find(t=>t.name===u)!==void 0}function isDataShapeSchemaAvailable(t,c){let u=NameSpacer.getDataShapeString({dataShape:t.name,course:t.course}),d=c.dataShapes.find(t=>t.name===u);return d!==void 0&&d.serializedZodSchema!==void 0}function isQuestionTypeRegistered(t,c){let u=NameSpacer.getQuestionString({course:t.course,questionType:t.name});return c.questionTypes.some(t=>t.name===u)}function processCustomQuestionsData(t){let c=[],u=[],d=t.courses.map(t=>t.name);return t.questionClasses.forEach(m=>{let g=d.length>0?d[0]:t.meta.packageName;m.dataShapes&&Array.isArray(m.dataShapes)&&m.dataShapes.forEach(t=>{c.push({name:t.name,course:g,dataShape:t})}),u.push({name:m.name,course:g,questionClass:m,dataShapes:m.dataShapes||[],views:m.views||[]})}),{dataShapes:c,questions:u}}function registerDataShape(t,c){let u=NameSpacer.getDataShapeString({dataShape:t.name,course:t.course}),d;try{d=toZodJSON(t.dataShape)}catch(t){logger.warn(`Failed to generate schema for ${u}:`,t),d=void 0}let m=c.dataShapes.findIndex(t=>t.name===u);if(m!==-1){let g=c.dataShapes[m];return g.serializedZodSchema===d?(logger.info(`DataShape '${t.name}' from '${t.course}' already registered with identical schema`),!1):(g.serializedZodSchema?logger.info(`DataShape '${t.name}' from '${t.course}' schema has changed, updating...`):logger.info(`DataShape '${t.name}' from '${t.course}' already registered, but with no schema. Adding schema to existing entry`),c.dataShapes[m]={name:u,questionTypes:g.questionTypes,serializedZodSchema:d},logger.info(`Updated DataShape: ${u}`),!0)}return c.dataShapes.push({name:u,questionTypes:[],serializedZodSchema:d}),logger.info(`Registered DataShape: ${u}`),!0}function registerQuestionType(t,c){if(isQuestionTypeRegistered(t,c))return logger.info(`QuestionType '${t.name}' from '${t.course}' already registered`),!1;let u=NameSpacer.getQuestionString({course:t.course,questionType:t.name}),d=t.views.map(t=>t.name?t.name:`unnamedComponent`),m=t.dataShapes.map(c=>NameSpacer.getDataShapeString({course:t.course,dataShape:c.name}));return c.questionTypes.push({name:u,viewList:d,dataShapeList:m}),t.dataShapes.forEach(d=>{let m=NameSpacer.getDataShapeString({course:t.course,dataShape:d.name});for(let t of c.dataShapes)t.name===m&&t.questionTypes.push(u)}),logger.info(`Registered QuestionType: ${u}`),!0}function removeDataShape(t,c){let u=c.dataShapes.findIndex(c=>c.name===t);return u===-1?(logger.info(`DataShape '${t}' not found in course config`),!1):(c.dataShapes.splice(u,1),c.questionTypes.forEach(c=>{let u=c.dataShapeList.indexOf(t);u!==-1&&c.dataShapeList.splice(u,1)}),logger.info(`Removed DataShape: ${t}`),!0)}function removeQuestionType(t,c){let u=c.questionTypes.findIndex(c=>c.name===t);return u===-1?(logger.info(`QuestionType '${t}' not found in course config`),!1):(c.questionTypes.splice(u,1),c.dataShapes.forEach(c=>{let u=c.questionTypes.indexOf(t);u!==-1&&c.questionTypes.splice(u,1)}),logger.info(`Removed QuestionType: ${t}`),!0)}async function removeCustomQuestionTypes(t,c,u,d){try{logger.info(`Beginning custom question removal`),logger.info(`Removing ${t.length} data shapes and ${c.length} question types`);let m=0;for(let t of c)removeQuestionType(t,u)&&m++;for(let c of t)removeDataShape(c,u)&&m++;logger.info(`Updating course configuration...`);let g=await d.updateCourseConfig(u);if(!g.ok)throw Error(`Failed to update course config: ${JSON.stringify(g)}`);return logger.info(`Custom question removal complete: ${m} items removed`),{success:!0,removedCount:m}}catch(t){let c=t instanceof Error?t.message:String(t);return logger.error(`Custom question removal failed: ${c}`),{success:!1,removedCount:0,errorMessage:c}}}async function registerSeedData(t,c,u){if(t.questionClass.seedData&&Array.isArray(t.questionClass.seedData)){logger.info(`Registering seed data for question: ${t.name}`);try{let d=t.questionClass.seedData.filter(()=>t.dataShapes.length>0).map(d=>c.addNote(t.course,t.dataShapes[0],d,u,[]));await Promise.all(d),logger.info(`Seed data registered for question: ${t.name}`)}catch(c){logger.warn(`Failed to register seed data for question '${t.name}': ${c instanceof Error?c.message:String(c)}`)}}}async function registerBlanksCard(t,c,u,d,m){try{logger.info(`Registering BlanksCard data shapes and question type...`);let g=0,b=`default`;for(let t of c)registerDataShape({name:t.name,course:b,dataShape:t},u)&&g++;let S={name:t.name,course:b,questionClass:{name:t.name,dataShapes:c,views:t.views||[]},dataShapes:c,views:t.views||[]};registerQuestionType(S,u)&&g++,logger.info(`Updating course configuration with BlanksCard...`);let C=await d.updateCourseConfig(u);if(!C.ok)throw Error(`Failed to update course config: ${JSON.stringify(C)}`);return m&&await registerSeedData(S,d,m),logger.info(`BlanksCard registration complete: ${g} items registered`),{success:!0}}catch(t){let c=t instanceof Error?t.message:String(t);return logger.error(`BlanksCard registration failed: ${c}`),{success:!1,errorMessage:c}}}async function registerCustomQuestionTypes(t,c,u,d){try{logger.info(`Beginning custom question registration`),logger.info(`Processing ${t.questionClasses.length} question classes`);let{dataShapes:m,questions:g}=processCustomQuestionsData(t);logger.info(`Found ${m.length} data shapes and ${g.length} questions`);let b=0;logger.info(`Registering data shapes...`);for(let t of m)registerDataShape(t,c)&&b++;logger.info(`Registering question types...`);for(let t of g)registerQuestionType(t,c)&&b++;logger.info(`Updating course configuration...`);let S=await u.updateCourseConfig(c);if(!S.ok)throw Error(`Failed to update course config: ${JSON.stringify(S)}`);if(d){logger.info(`Registering seed data...`);for(let t of g)await registerSeedData(t,u,d)}return logger.info(`Custom question registration complete: ${b} items registered`),{success:!0,registeredCount:b}}catch(t){let c=t instanceof Error?t.message:String(t);return logger.error(`Custom question registration failed: ${c}`),{success:!1,registeredCount:0,errorMessage:c}}}var import_browser_ponyfill,import_browser_ponyfill$1,import_browser,import___vite_browser_external,import___vite_browser_external$1,import___vite_browser_external$2,__defProp,__getOwnPropNames,__glob,__esm,__export,init_adminDB,init_classroomDB,init_SyncStrategy,isDevelopment,logger,init_logger,GuestUsername,log,DocType,DocTypePrefixes,init_types_legacy,init_util,pouchdb_setup_default,init_pouchdb_setup,Loggable,init_Loggable,UpdateQueue,init_updateQueue,CLIENT_CACHE,init_clientCache,AlreadyTaggedErr,init_courseAPI,courseLookupDBTitle,CourseLookup,init_courseLookupDB,diversityRerank_exports,DIVERSITY_STRENGTH,DIVERSITY_FLOOR,STRATEGY,STRATEGY_ID,STRATEGY_NAME,init_diversityRerank,PipelineDebugger_exports,_activePipeline,MAX_RUNS,runHistory,_currentSessionId,_pendingRuns,DISCARDED_KEEP_TOP,_uiContainer,_selectedRunIndex,_cardSearchQuery,pipelineDebugAPI,init_PipelineDebugger,SrsDebugger_exports,snapshots,init_SrsDebugger,StrategyPressureDebugger_exports,snapshots2,init_StrategyPressureDebugger,CompositeGenerator_exports,AggregationMode,DEFAULT_AGGREGATION_MODE,FREQUENCY_BOOST_FACTOR,CompositeGenerator,init_CompositeGenerator,elo_exports,ELONavigator,init_elo,generators_exports,init_generators,prescribed_exports,DEFAULT_FRESHNESS_WINDOW,DEFAULT_MAX_DIRECT_PER_RUN,DEFAULT_MAX_SUPPORT_PER_RUN,DEFAULT_HIERARCHY_DEPTH,DEFAULT_MIN_COUNT,DEFAULT_PRACTICE_MIN_COUNT,DEFAULT_MAX_PRACTICE_PER_RUN,BASE_TARGET_SCORE,BASE_SUPPORT_SCORE,DISCOVERED_SUPPORT_SCORE,BASE_PRACTICE_SCORE,PRACTICE_BASE_MULT,MAX_PRACTICE_MULTIPLIER,PRACTICE_STALENESS_BUMP_PER_DAY,MAX_TARGET_MULTIPLIER,MAX_SUPPORT_MULTIPLIER,PRESCRIBED_DEBUG_VERSION,PrescribedCardsGenerator,init_prescribed,regulators_exports,DEFAULT_REGULATOR_CONFIG,INTAKE_CLOCK_KEY,REGULATOR_LABEL,init_regulators,srs_exports,SRSNavigator,init_srs,types_exports,init_types,globImport_generators,init_,DEFAULT_LEARNABLE_WEIGHT,init_contentNavigationStrategy,WeightedFilter_exports,WeightedFilter,init_WeightedFilter,eloDistance_exports,DEFAULT_ELO_DISTANCE_CONFIG,TAG_CONFIDENCE_HALF,DEFAULT_CARD_ELO,MULTI_DIM_ELO_KEY,multiDimElo,EloDistanceFilter,init_eloDistance,hierarchyDefinition_exports,DEFAULT_MIN_COUNT2,HierarchyDefinitionNavigator,init_hierarchyDefinition,userTagPreference_exports,UserTagPreferenceFilter,init_userTagPreference,filters_exports,init_filters,inferredPreferenceStub_exports,INFERRED_PREFERENCE_NAVIGATOR_STUB,init_inferredPreferenceStub,interferenceMitigator_exports,DEFAULT_MIN_COUNT3,DEFAULT_MIN_ELAPSED_DAYS,DEFAULT_INTERFERENCE_DECAY,InterferenceMitigatorNavigator,init_interferenceMitigator,relativePriority_exports,DEFAULT_PRIORITY,DEFAULT_PRIORITY_INFLUENCE,DEFAULT_COMBINE_MODE,RelativePriorityNavigator,init_relativePriority,types_exports2,init_types2,userGoalStub_exports,USER_GOAL_NAVIGATOR_STUB,init_userGoalStub,globImport_filters,init_2,init_gradient,MIN_OBSERVATIONS_FOR_UPDATE,LEARNING_RATE,MAX_WEIGHT_DELTA,MIN_R_SQUARED_FOR_GRADIENT,FLAT_GRADIENT_THRESHOLD,MAX_HISTORY_LENGTH,init_learning,init_signal,init_recording,MIN_SPREAD,MAX_SPREAD,MIN_WEIGHT,MAX_WEIGHT,init_orchestration,Pipeline_exports,VERBOSE_RESULTS,Pipeline,init_Pipeline,defaults_exports,init_defaults,pipelinePlan_exports,PIPELINE_STAGES,init_pipelinePlan,PipelineAssembler_exports,PipelineAssembler,init_PipelineAssembler,globImport,init_3,navigators_exports,navigatorRegistry,Navigators,NavigatorRole,NavigatorRoles,ContentNavigator,init_navigators,CoursesDB,CourseDB,init_courseDB,classroomLookupDBTitle,CLASSROOM_CONFIG,ClassroomDBBase,StudentClassroomDB,TeacherClassroomDB,ClassroomLookupDB,init_classroomDB2,AdminDB,init_adminDB2,CourseSyncService_exports,DEFAULT_REPLICATION,CourseSyncService,init_CourseSyncService,init_auth,CouchDBSyncStrategy_exports,log2,CouchDBSyncStrategy,init_CouchDBSyncStrategy,isBrowser,GUEST_LOCAL_DB,localUserDB,pouchDBincludeCredentialsConfig,REVIEW_TIME_FORMAT,init_couch,duration,init_SpacedRepetition,SrsService,init_SrsService,init_tagRecent,EloService,init_EloService,ResponseProcessor,init_ResponseProcessor,CardHydrationService,init_CardHydrationService,ItemQueue,init_ItemQueue,init_studySession,init_types3,CouchDBToStaticPacker,init_CouchDBToStaticPacker,init_packer,DEFAULT_MIGRATION_OPTIONS,init_types4,FileSystemError,init_FileSystemAdapter,nodeFS,init_validation,nodeFS2,nodePath,StaticToCouchDBMigrator,init_StaticToCouchDBMigrator,init_migrator,init_dataDirectory,init_util2,QuotaRoundRobinMixer,init_SourceMixer,MAX_RUNS2,runHistory2,mixerDebugAPI,init_MixerDebugger,activeController,OVERLAY_ID,POLL_MS,INLINE_THRESHOLD,SPINNER_FRAMES,spinnerFrame,overlayEl,pollHandle,lastSnapshot,copyFlashUntil,minified,expanded,init_SessionOverlay,activeSession,sessionHistory,MAX_HISTORY,sessionDebugAPI,init_SessionDebugger,PERSISTED_RUNNERS_UP,SessionController,init_SessionController,TagFilteredContentSource,init_TagFilteredContentSource,init_study,REVIEW_TIME_FORMAT2,log3,init_userDBHelpers,UsrCrsData,init_user_course_relDB,log4,HYDRATION_TIMEOUT_MS,BaseUser,userCoursesDoc,userClassroomsDoc,init_BaseUserDB,init_common,PouchDataLayerProvider_exports,CouchDataLayerProvider,init_PouchDataLayerProvider,pathUtils,nodeFS3,StaticDataUnpacker,init_StaticDataUnpacker,StaticCourseDB,init_courseDB2,StaticCoursesDB,init_coursesDB,NoOpSyncStrategy,init_NoOpSyncStrategy,StaticDataLayerProvider_exports,StaticDataLayerProvider,init_StaticDataLayerProvider,NOT_SET,ENV,dataLayerInstance,init_factory,init_contentSource,init_courseDB3,init_dataLayerProvider,init_userDB,init_interfaces,init_user,init_strategyState,init_userOutcome,HYDRATION_MARKER_ID,init_hydration,init_cardProcessor,init_types5,init_bulkImport,userDBDebugAPI,init_UserDBDebugger,init_core,init_dist=__esmMin((()=>{init_defineProperty(),init_index_browser_es$5(),init_index_browser_es(),init_index_es(),init_dist$1(),init_esm_browser(),init_moment(),import_browser_ponyfill=__toESM$2(require_browser_ponyfill(),1),import_browser_ponyfill$1=__toESM$2(require_browser_ponyfill(),1),import_browser=__toESM$2(require_browser(),1),import___vite_browser_external=__toESM$2(require___vite_browser_external(),1),import___vite_browser_external$1=__toESM$2(require___vite_browser_external(),1),import___vite_browser_external$2=__toESM$2(require___vite_browser_external(),1),__defProp=Object.defineProperty,__getOwnPropNames=Object.getOwnPropertyNames,__glob=t=>c=>{var u=t[c];if(u)return u();throw Error(`Module not found in bundle: `+c)},__esm=(t,c)=>function __init(){return t&&(c=(0,t[__getOwnPropNames(t)[0]])(t=0)),c},__export=(t,c)=>{for(var u in c)__defProp(t,u,{get:c[u],enumerable:!0})},init_adminDB=__esm({"src/core/interfaces/adminDB.ts"(){"use strict";}}),init_classroomDB=__esm({"src/core/interfaces/classroomDB.ts"(){"use strict";}}),init_SyncStrategy=__esm({"src/impl/common/SyncStrategy.ts"(){"use strict";}}),init_logger=__esm({"src/util/logger.ts"(){"use strict";isDevelopment=typeof process<`u`&&process.env.NODE_ENV===`development`,logger={debug:(t,...c)=>{isDevelopment&&console.debug(`[DB:DEBUG] ${t}`,...c)},info:(t,...c)=>{console.info(`[DB:INFO] ${t}`,...c)},warn:(t,...c)=>{console.warn(`[DB:WARN] ${t}`,...c)},error:(t,...c)=>{console.error(`[DB:ERROR] ${t}`,...c)},log:(t,...c)=>{isDevelopment&&console.log(`[DB:LOG] ${t}`,...c)}}}}),init_types_legacy=__esm({"src/core/types/types-legacy.ts"(){"use strict";init_logger(),GuestUsername=`sk-guest-`,log=t=>{logger.log(t)},DocType=(t=>(t.DISPLAYABLE_DATA=`DISPLAYABLE_DATA`,t.CARD=`CARD`,t.DATASHAPE=`DATASHAPE`,t.QUESTIONTYPE=`QUESTION`,t.VIEW=`VIEW`,t.PEDAGOGY=`PEDAGOGY`,t.CARDRECORD=`CARDRECORD`,t.SCHEDULED_CARD=`SCHEDULED_CARD`,t.TAG=`TAG`,t.NAVIGATION_STRATEGY=`NAVIGATION_STRATEGY`,t.STRATEGY_STATE=`STRATEGY_STATE`,t.USER_OUTCOME=`USER_OUTCOME`,t.STRATEGY_LEARNING_STATE=`STRATEGY_LEARNING_STATE`,t.STUDY_SESSION=`STUDY_SESSION`,t))(DocType||{}),DocTypePrefixes={CARD:`c`,DISPLAYABLE_DATA:`dd`,TAG:`TAG`,CARDRECORD:`cardH`,SCHEDULED_CARD:`card_review_`,DATASHAPE:`DATASHAPE`,QUESTION:`QUESTION`,VIEW:`VIEW`,PEDAGOGY:`PEDAGOGY`,NAVIGATION_STRATEGY:`NAVIGATION_STRATEGY`,STRATEGY_STATE:`STRATEGY_STATE`,USER_OUTCOME:`USER_OUTCOME`,STRATEGY_LEARNING_STATE:`STRATEGY_LEARNING_STATE`,STUDY_SESSION:`SESSION`}}}),init_util=__esm({"src/core/util/index.ts"(){"use strict";init_types_legacy()}}),init_pouchdb_setup=__esm({"src/impl/couch/pouchdb-setup.ts"(){"use strict";PouchDB.plugin(plugin$1),PouchDB.plugin(plugin),PouchDB.debug!==void 0&&PouchDB.debug.disable(),PouchDB.defaults({}),pouchdb_setup_default=PouchDB}}),init_Loggable=__esm({"src/util/Loggable.ts"(){"use strict";Loggable=class{log(...t){console.log(`LOG-${this._className}@${new Date}:`,...t)}error(...t){console.error(`ERROR-${this._className}@${new Date}:`,...t)}}}}),init_updateQueue=__esm({"src/impl/couch/updateQueue.ts"(){"use strict";init_Loggable(),init_logger(),UpdateQueue=class extends Loggable{update(t,c){return logger.debug(`Update requested on doc: ${t}`),this.pendingUpdates[t]?this.pendingUpdates[t].push(c):this.pendingUpdates[t]=[c],this.applyUpdates(t)}constructor(t,c){super(),_defineProperty$2(this,`_className`,`UpdateQueue`),_defineProperty$2(this,`pendingUpdates`,{}),_defineProperty$2(this,`inprogressUpdates`,{}),_defineProperty$2(this,`readDB`,void 0),_defineProperty$2(this,`writeDB`,void 0),this.readDB=t,this.writeDB=c||t,logger.debug(`UpdateQ initialized...`),this.readDB.info().then(t=>{logger.debug(`db info: ${JSON.stringify(t)}`)})}async applyUpdates(t){if(logger.debug(`Applying updates on doc: ${t}`),this.inprogressUpdates[t]){for(;this.inprogressUpdates[t];)await new Promise(t=>setTimeout(t,Math.random()*50));return this.applyUpdates(t)}else if(this.pendingUpdates[t]&&this.pendingUpdates[t].length>0){this.inprogressUpdates[t]=!0;let c=5;for(let c=0;c<5;c++)try{let c={...await this.readDB.get(t)},u=[...this.pendingUpdates[t]];for(let t of u)c=typeof t==`function`?{...c,...t(c)}:{...c,...t};if(await this.writeDB.put(c),this.pendingUpdates[t].splice(0,u.length),this.pendingUpdates[t].length===0)this.inprogressUpdates[t]=!1,delete this.inprogressUpdates[t];else return this.applyUpdates(t);return c}catch(u){if(u.name===`conflict`&&c<4)logger.warn(`Conflict on update for doc ${t}, retry #${c+1}`),await new Promise(t=>setTimeout(t,50*Math.random()));else if(u.name===`not_found`&&c===0)throw logger.warn(`Update failed for ${t} - does not exist. Throwing to caller.`),delete this.inprogressUpdates[t],u;else throw delete this.inprogressUpdates[t],this.pendingUpdates[t]&&delete this.pendingUpdates[t],logger.error(`Error on attemped update (retry ${c}): ${JSON.stringify(u)}`),u}throw Error(`UpdateQueue failed for doc ${t} after 5 retries.`)}else throw Error(`Empty Updates Queue Triggered`)}}}}),init_clientCache=__esm({"src/impl/couch/clientCache.ts"(){"use strict";CLIENT_CACHE={}}}),init_courseAPI=__esm({"src/impl/couch/courseAPI.ts"(){"use strict";init_pouchdb_setup(),init_couch(),init_factory(),init_courseDB(),init_types_legacy(),init_common(),init_logger(),AlreadyTaggedErr=class extends Error{constructor(t){super(t),this.name=`AlreadyTaggedErr`}}}}),init_courseLookupDB=__esm({"src/impl/couch/courseLookupDB.ts"(){"use strict";var t;init_pouchdb_setup(),init_factory(),init_logger(),courseLookupDBTitle=`coursedb-lookup`,logger.debug(`COURSELOOKUP FILE RUNNING`),CourseLookup=(t=class _CourseLookup{static get _db(){if(this._dbInstance)return this._dbInstance;if(ENV.COUCHDB_SERVER_URL===`NOT_SET`||!ENV.COUCHDB_SERVER_URL)throw Error(`CourseLookup.db: COUCHDB_SERVER_URL is not set. Ensure initializeDataLayer has been called with valid configuration.`);if(ENV.COUCHDB_SERVER_PROTOCOL===`NOT_SET`||!ENV.COUCHDB_SERVER_PROTOCOL)throw Error(`CourseLookup.db: COUCHDB_SERVER_PROTOCOL is not set. Ensure initializeDataLayer has been called with valid configuration.`);let t=`${ENV.COUCHDB_SERVER_PROTOCOL}://${ENV.COUCHDB_SERVER_URL}/${courseLookupDBTitle}`,c={};ENV.COUCHDB_USERNAME&&ENV.COUCHDB_PASSWORD?(c.auth={username:ENV.COUCHDB_USERNAME,password:ENV.COUCHDB_PASSWORD},logger.info(`CourseLookup: Connecting to ${t} with authentication.`)):logger.info(`CourseLookup: Connecting to ${t} without authentication.`);try{return this._dbInstance=new pouchdb_setup_default(t,c),logger.info(`CourseLookup: Database instance created for ${courseLookupDBTitle}.`),this._dbInstance}catch(c){throw logger.error(`CourseLookup: Failed to create PouchDB instance for ${t}`,c),this._dbInstance=null,Error(`CourseLookup: Failed to initialize database connection: ${c instanceof Error?c.message:String(c)}`)}}static async add(t){return(await _CourseLookup._db.post({name:t})).id}static async addWithId(t,c,u){let d={_id:t,name:c};u&&(d.disambiguator=u),await _CourseLookup._db.put(d)}static async delete(t){let c=await _CourseLookup._db.get(t);return await _CourseLookup._db.remove(c)}static async allCourseWare(){return(await _CourseLookup._db.allDocs({include_docs:!0})).rows.map(t=>t.doc)}static async updateDisambiguator(t,c){let u=await _CourseLookup._db.get(t);return u.disambiguator=c,await _CourseLookup._db.put(u)}static async isCourse(t){try{return await _CourseLookup._db.get(t),!0}catch(t){return logger.info(`Courselookup failed:`,t),!1}}},_defineProperty$2(t,`_dbInstance`,null),t)}}),diversityRerank_exports={},__export(diversityRerank_exports,{DIVERSITY_FLOOR:()=>DIVERSITY_FLOOR,DIVERSITY_STRENGTH:()=>DIVERSITY_STRENGTH,diversityRerank:()=>diversityRerank}),init_diversityRerank=__esm({"src/core/navigators/diversityRerank.ts"(){"use strict";DIVERSITY_STRENGTH=.6,DIVERSITY_FLOOR=.3,STRATEGY=`diversityRerank`,STRATEGY_ID=`DIVERSITY_RERANK`,STRATEGY_NAME=`Diversity Re-rank`}}),PipelineDebugger_exports={},__export(PipelineDebugger_exports,{buildRunReport:()=>buildRunReport,captureRun:()=>captureRun,clearRunHistory:()=>clearRunHistory,drainCapturedRuns:()=>drainCapturedRuns,getActivePipeline:()=>getActivePipeline,getRunsForSession:()=>getRunsForSession,mountPipelineDebugger:()=>mountPipelineDebugger,pipelineDebugAPI:()=>pipelineDebugAPI,registerPipelineForDebug:()=>registerPipelineForDebug,setDebugSessionId:()=>setDebugSessionId}),init_PipelineDebugger=__esm({"src/core/navigators/PipelineDebugger.ts"(){"use strict";init_navigators(),init_logger(),_activePipeline=null,MAX_RUNS=10,runHistory=[],_pendingRuns=[],DISCARDED_KEEP_TOP=25,_uiContainer=null,_selectedRunIndex=null,_cardSearchQuery=``,pipelineDebugAPI={get runs(){return[...runHistory]},showRun(t=0){if(runHistory.length===0){logger.info(`[Pipeline Debug] No runs captured yet.`);return}let c;if(typeof t==`number`){if(c=runHistory[t],!c){logger.info(`[Pipeline Debug] No run found at index ${t}. History length: ${runHistory.length}`);return}}else if(c=runHistory.find(c=>c.runId.endsWith(t)),!c){logger.info(`[Pipeline Debug] No run found matching ID '${t}'.`);return}printRunSummary(c)},showLastRun(){this.showRun(0)},showCard(t){for(let c of runHistory){let u=c.cards.find(c=>c.cardId===t);if(u){console.group(`\u{1F3B4} Card: ${t}`),logger.info(`Course: ${u.courseId}`),logger.info(`Origin: ${u.origin}`),logger.info(`Card ELO: ${u.cardElo??`unknown`} | User ELO: ${c.userElo??`unknown`}`),logger.info(`Final score: ${u.finalScore.toFixed(3)}`),logger.info(`Selected: ${u.selected?`Yes ✅`:`No ❌`}`),u.tags&&u.tags.length>0&&logger.info(`Tags (${u.tags.length}): ${u.tags.join(`, `)}`),logger.info(`Provenance:`),logger.info(formatProvenance(u.provenance)),console.groupEnd();return}}let c=runHistory.filter(t=>t.discardedTail&&t.discardedTail.count>0);c.length>0?logger.info(`[Pipeline Debug] Card '${t}' not found in retained cards. ${c.length} run(s) have discarded tails that were not retained \u2014 the card may have been a low-score candidate. See run.discardedTail for ranges.`):logger.info(`[Pipeline Debug] Card '${t}' not found in recent runs.`)},explainReviews(){if(runHistory.length===0){logger.info(`[Pipeline Debug] No runs captured yet.`);return}console.group(`📋 Review Selection Analysis`);for(let t of runHistory){console.group(`Run: ${t.courseId} @ ${t.timestamp.toLocaleTimeString()}`);let c=t.cards.filter(t=>t.origin===`review`),u=c.filter(t=>t.selected);if(c.length===0)logger.info(`❌ No reviews were generated. Check SRS logs for why.`);else if(u.length===0){logger.info(`\u26A0\uFE0F ${c.length} reviews generated but none selected.`),logger.info(`Possible reasons:`);let u=Math.max(...t.cards.filter(t=>t.origin===`new`&&t.selected).map(t=>t.finalScore),0),d=Math.max(...c.map(t=>t.finalScore),0);d<u&&logger.info(` - New cards scored higher (top new: ${u.toFixed(2)}, top review: ${d.toFixed(2)})`);let m=c.sort((t,c)=>c.finalScore-t.finalScore)[0];m&&(logger.info(` - Top review score: ${m.finalScore.toFixed(3)}`),logger.info(` - Its provenance:`),logger.info(formatProvenance(m.provenance)))}else{logger.info(`\u2705 ${u.length}/${c.length} reviews selected.`),logger.info(`Top selected review:`);let t=u.sort((t,c)=>c.finalScore-t.finalScore)[0];logger.info(formatProvenance(t.provenance))}console.groupEnd()}console.groupEnd()},showPrescribed(t){if(runHistory.length===0){logger.info(`[Pipeline Debug] No runs captured yet.`);return}let c=runHistory[0],u=c.cards.filter(t=>t.provenance.some(t=>t.strategy===`prescribed`));if(console.group(`\u{1F9ED} Prescribed Debug (${c.courseId})`),u.length===0){logger.info(`No prescribed-generated cards were present in the most recent run.`),console.groupEnd();return}let d=u.map(t=>{let c=t.provenance.find(t=>t.strategy===`prescribed`)?.reason??``,u=c.match(/group=([^;]+)/)?.[1]??`unknown`,d=c.match(/mode=([^;]+)/)?.[1]??`unknown`,m=c.match(/blocked=([^;]+)/)?.[1]??`unknown`,g=c.match(/blockedTargets=([^;]+)/)?.[1]??`none`,b=c.match(/supportCard=([^;]+)/)?.[1]??`none`,S=c.match(/supportTags=([^;]+)/)?.[1]??`none`,C=c.match(/multiplier=([^;]+)/)?.[1]??`unknown`;return{group:u,mode:d,supportSource:d===`discovered-support`?`discovered`:d===`support`?`authored`:`n/a`,cardId:t.cardId,selected:t.selected?`yes`:`no`,finalScore:t.finalScore.toFixed(3),blocked:m,blockedTargets:g,supportCard:b,supportTags:S,multiplier:C}}).filter(c=>!t||c.group===t).sort((t,c)=>Number(c.finalScore)-Number(t.finalScore));if(d.length===0){logger.info(`[Pipeline Debug] No prescribed cards matched group '${t}' in the most recent run.`),console.groupEnd();return}console.table(d);let m=d.filter(t=>t.selected===`yes`),g=new Set,b=new Set,S=new Set,C=new Set;for(let t of d)t.blockedTargets&&t.blockedTargets!==`none`&&t.blockedTargets.split(`|`).filter(Boolean).forEach(t=>g.add(t)),t.supportTags&&t.supportTags!==`none`&&t.supportTags.split(`|`).filter(Boolean).forEach(t=>b.add(t)),t.supportCard&&t.supportCard!==`none`&&(t.supportSource===`discovered`?C.add(t.supportCard):t.supportSource===`authored`&&S.add(t.supportCard));logger.info(`Prescribed cards in run: ${d.length}`),logger.info(`Selected prescribed cards: ${m.length}`),logger.info(`Blocked prescribed targets referenced: ${g.size>0?[...g].join(`, `):`none`}`),logger.info(`Resolved support tags referenced: ${b.size>0?[...b].join(`, `):`none`}`),logger.info(`Authored support cards emitted: ${S.size>0?[...S].join(`, `):`none`}`),logger.info(`Discovered support cards emitted: ${C.size>0?[...C].join(`, `):`none`}`),console.groupEnd()},listRuns(){if(runHistory.length===0){logger.info(`[Pipeline Debug] No runs captured yet.`);return}console.table(runHistory.map(t=>({id:t.runId.slice(-8),time:t.timestamp.toLocaleTimeString(),course:t.courseName||t.courseId.slice(0,8),generated:t.generatedCount,selected:t.finalCount,new:t.newSelected,reviews:t.reviewsSelected})))},export(){let t=JSON.stringify(runHistory,null,2);return logger.info(`[Pipeline Debug] Run history exported. Copy the returned string or use:`),logger.info(` copy(window.skuilder.pipeline.export())`),t},clear(){runHistory.length=0,logger.info(`[Pipeline Debug] Run history cleared.`)},showRegistry(){let t=getRegisteredNavigatorNames();if(t.length===0){logger.info(`[Pipeline Debug] Navigator registry is empty.`);return}console.group(`📦 Navigator Registry`),console.table(t.map(t=>{let c=getRegisteredNavigatorRole(t),u=NavigatorRoles[t];return{name:t,role:u||c||`⚠️ NONE`,source:u?`built-in`:c?`consumer`:`unclassified`,isGenerator:isGenerator(t),isFilter:isFilter(t)}})),console.groupEnd()},showStrategies(){if(this.showRegistry(),runHistory.length===0){logger.info(`[Pipeline Debug] No pipeline runs captured yet — cannot show strategy doc mapping.`);return}let t=runHistory[0];if(console.group(`🔌 Pipeline Strategy Mapping (last run)`),logger.info(`Generator: ${t.generatorName}`),t.generators&&t.generators.length>0)for(let c of t.generators)logger.info(` \u{1F4E5} ${c.name}: ${c.cardCount} cards (${c.newCount} new, ${c.reviewCount} reviews)`);if(t.filters.length>0){logger.info(`Filters:`);for(let c of t.filters)logger.info(` \u{1F538} ${c.name}: \u2191${c.boosted} \u2193${c.penalized} =${c.passed} \u2715${c.removed}`)}else logger.info(`Filters: (none)`);console.groupEnd()},async diagnoseCardSpace(t){return _activePipeline?_activePipeline.diagnoseCardSpace({threshold:t}):(logger.info(`[Pipeline Debug] No active pipeline. Run a session first.`),null)},async showTagElo(t){if(!_activePipeline){logger.info(`[Pipeline Debug] No active pipeline. Run a session first.`);return}let c=await _activePipeline.getTagEloStatus(t),u=Object.entries(c).sort(([t],[c])=>t.localeCompare(c));if(u.length===0){logger.info(`[Pipeline Debug] No tag ELO data found${t?` for pattern: ${t}`:``}.`);return}console.table(Object.fromEntries(u.map(([t,c])=>[t,{score:Math.round(c.score),count:c.count}])))},ui(){if(_uiContainer){document.body.removeChild(_uiContainer),_uiContainer=null;return}_uiContainer=document.createElement(`div`),_uiContainer.id=`sk-pipeline-debugger`,document.body.appendChild(_uiContainer),_selectedRunIndex===null&&runHistory.length>0&&(_selectedRunIndex=0),renderUI()},_selectRun(t){_selectedRunIndex=t,renderUI()},_setSearch(t){_cardSearchQuery=t,renderUI()},_copyConfig(t,c){let u=runHistory.find(c=>c.runId===t);if(!u)return;let d={runId:u.runId,timestamp:u.timestamp.toISOString(),courseId:u.courseId,courseName:u.courseName,hints:u.hints??null};copyTextToClipboard(JSON.stringify(d,null,2),c)},_copyResults(t,c){let u=runHistory.find(c=>c.runId===t);if(!u)return;let d=u.cards.filter(t=>t.selected).sort((t,c)=>c.finalScore-t.finalScore).map(t=>({cardId:t.cardId,generator:t.generator,origin:t.origin,score:Number(t.finalScore.toFixed(3)),topReason:t.provenance[0]?.reason??``})),m={runId:u.runId,label:u.hints?._label??null,finalCount:u.finalCount,newSelected:u.newSelected,reviewsSelected:u.reviewsSelected,selected:d};copyTextToClipboard(JSON.stringify(m,null,2),c)},help(){logger.info(`
328
+ elo: ${g}`);let S={Input:d,Uploads:[]},C={};for(let t of m)C[t]={score:g||0,count:1};try{let t=await c.addNote(u.courseCode,u.dataShape,S,u.userName,m,void 0,g?{global:{score:g,count:1},tags:C,misc:{}}:void 0);return t.status===Status.ok?{originalText:b,status:`success`,message:`Card added successfully.`,cardId:t.id?t.id:`(unknown)`}:{originalText:b,status:`error`,message:t.message||`Failed to add card to database. Unknown error.`}}catch(t){return logger.error(`Error adding note:`,t),{originalText:b,status:`error`,message:`Error adding card: ${t instanceof Error?t.message:`Unknown error`}`}}}function validateProcessorConfig(t){return t.dataShape?t.courseCode?t.userName?{isValid:!0}:{isValid:!1,errorMessage:`No user name provided for card processing`}:{isValid:!1,errorMessage:`No course code provided for card processing`}:{isValid:!1,errorMessage:`No data shape provided for card processing`}}function getUserDB(){try{return getDataLayer().getUserDB()}catch{return logger.info(`[UserDB Debug] Data layer not initialized yet.`),null}}function getRawDB(){let t=getUserDB();return t?t.localDB||(logger.info(`[UserDB Debug] Unable to access raw database instance.`),null):null}function formatTimestamp(t){return new Date(t).toLocaleString()}function mountUserDBDebugger(){if(typeof window>`u`)return;let t=window;t.skuilder=t.skuilder||{},t.skuilder.userdb=userDBDebugAPI}function isDataShapeRegistered(t,c){let u=NameSpacer.getDataShapeString({dataShape:t.name,course:t.course});return c.dataShapes.find(t=>t.name===u)!==void 0}function isDataShapeSchemaAvailable(t,c){let u=NameSpacer.getDataShapeString({dataShape:t.name,course:t.course}),d=c.dataShapes.find(t=>t.name===u);return d!==void 0&&d.serializedZodSchema!==void 0}function isQuestionTypeRegistered(t,c){let u=NameSpacer.getQuestionString({course:t.course,questionType:t.name});return c.questionTypes.some(t=>t.name===u)}function processCustomQuestionsData(t){let c=[],u=[],d=t.courses.map(t=>t.name);return t.questionClasses.forEach(m=>{let g=d.length>0?d[0]:t.meta.packageName;m.dataShapes&&Array.isArray(m.dataShapes)&&m.dataShapes.forEach(t=>{c.push({name:t.name,course:g,dataShape:t})}),u.push({name:m.name,course:g,questionClass:m,dataShapes:m.dataShapes||[],views:m.views||[]})}),{dataShapes:c,questions:u}}function registerDataShape(t,c){let u=NameSpacer.getDataShapeString({dataShape:t.name,course:t.course}),d;try{d=toZodJSON(t.dataShape)}catch(t){logger.warn(`Failed to generate schema for ${u}:`,t),d=void 0}let m=c.dataShapes.findIndex(t=>t.name===u);if(m!==-1){let g=c.dataShapes[m];return g.serializedZodSchema===d?(logger.info(`DataShape '${t.name}' from '${t.course}' already registered with identical schema`),!1):(g.serializedZodSchema?logger.info(`DataShape '${t.name}' from '${t.course}' schema has changed, updating...`):logger.info(`DataShape '${t.name}' from '${t.course}' already registered, but with no schema. Adding schema to existing entry`),c.dataShapes[m]={name:u,questionTypes:g.questionTypes,serializedZodSchema:d},logger.info(`Updated DataShape: ${u}`),!0)}return c.dataShapes.push({name:u,questionTypes:[],serializedZodSchema:d}),logger.info(`Registered DataShape: ${u}`),!0}function registerQuestionType(t,c){if(isQuestionTypeRegistered(t,c))return logger.info(`QuestionType '${t.name}' from '${t.course}' already registered`),!1;let u=NameSpacer.getQuestionString({course:t.course,questionType:t.name}),d=t.views.map(t=>t.name?t.name:`unnamedComponent`),m=t.dataShapes.map(c=>NameSpacer.getDataShapeString({course:t.course,dataShape:c.name}));return c.questionTypes.push({name:u,viewList:d,dataShapeList:m}),t.dataShapes.forEach(d=>{let m=NameSpacer.getDataShapeString({course:t.course,dataShape:d.name});for(let t of c.dataShapes)t.name===m&&t.questionTypes.push(u)}),logger.info(`Registered QuestionType: ${u}`),!0}function removeDataShape(t,c){let u=c.dataShapes.findIndex(c=>c.name===t);return u===-1?(logger.info(`DataShape '${t}' not found in course config`),!1):(c.dataShapes.splice(u,1),c.questionTypes.forEach(c=>{let u=c.dataShapeList.indexOf(t);u!==-1&&c.dataShapeList.splice(u,1)}),logger.info(`Removed DataShape: ${t}`),!0)}function removeQuestionType(t,c){let u=c.questionTypes.findIndex(c=>c.name===t);return u===-1?(logger.info(`QuestionType '${t}' not found in course config`),!1):(c.questionTypes.splice(u,1),c.dataShapes.forEach(c=>{let u=c.questionTypes.indexOf(t);u!==-1&&c.questionTypes.splice(u,1)}),logger.info(`Removed QuestionType: ${t}`),!0)}async function removeCustomQuestionTypes(t,c,u,d){try{logger.info(`Beginning custom question removal`),logger.info(`Removing ${t.length} data shapes and ${c.length} question types`);let m=0;for(let t of c)removeQuestionType(t,u)&&m++;for(let c of t)removeDataShape(c,u)&&m++;logger.info(`Updating course configuration...`);let g=await d.updateCourseConfig(u);if(!g.ok)throw Error(`Failed to update course config: ${JSON.stringify(g)}`);return logger.info(`Custom question removal complete: ${m} items removed`),{success:!0,removedCount:m}}catch(t){let c=t instanceof Error?t.message:String(t);return logger.error(`Custom question removal failed: ${c}`),{success:!1,removedCount:0,errorMessage:c}}}async function registerSeedData(t,c,u){if(t.questionClass.seedData&&Array.isArray(t.questionClass.seedData)){logger.info(`Registering seed data for question: ${t.name}`);try{let d=t.questionClass.seedData.filter(()=>t.dataShapes.length>0).map(d=>c.addNote(t.course,t.dataShapes[0],d,u,[]));await Promise.all(d),logger.info(`Seed data registered for question: ${t.name}`)}catch(c){logger.warn(`Failed to register seed data for question '${t.name}': ${c instanceof Error?c.message:String(c)}`)}}}async function registerBlanksCard(t,c,u,d,m){try{logger.info(`Registering BlanksCard data shapes and question type...`);let g=0,b=`default`;for(let t of c)registerDataShape({name:t.name,course:b,dataShape:t},u)&&g++;let S={name:t.name,course:b,questionClass:{name:t.name,dataShapes:c,views:t.views||[]},dataShapes:c,views:t.views||[]};registerQuestionType(S,u)&&g++,logger.info(`Updating course configuration with BlanksCard...`);let C=await d.updateCourseConfig(u);if(!C.ok)throw Error(`Failed to update course config: ${JSON.stringify(C)}`);return m&&await registerSeedData(S,d,m),logger.info(`BlanksCard registration complete: ${g} items registered`),{success:!0}}catch(t){let c=t instanceof Error?t.message:String(t);return logger.error(`BlanksCard registration failed: ${c}`),{success:!1,errorMessage:c}}}async function registerCustomQuestionTypes(t,c,u,d){try{logger.info(`Beginning custom question registration`),logger.info(`Processing ${t.questionClasses.length} question classes`);let{dataShapes:m,questions:g}=processCustomQuestionsData(t);logger.info(`Found ${m.length} data shapes and ${g.length} questions`);let b=0;logger.info(`Registering data shapes...`);for(let t of m)registerDataShape(t,c)&&b++;logger.info(`Registering question types...`);for(let t of g)registerQuestionType(t,c)&&b++;logger.info(`Updating course configuration...`);let S=await u.updateCourseConfig(c);if(!S.ok)throw Error(`Failed to update course config: ${JSON.stringify(S)}`);if(d){logger.info(`Registering seed data...`);for(let t of g)await registerSeedData(t,u,d)}return logger.info(`Custom question registration complete: ${b} items registered`),{success:!0,registeredCount:b}}catch(t){let c=t instanceof Error?t.message:String(t);return logger.error(`Custom question registration failed: ${c}`),{success:!1,registeredCount:0,errorMessage:c}}}var import_browser_ponyfill,import_browser_ponyfill$1,import_browser,import___vite_browser_external,import___vite_browser_external$1,import___vite_browser_external$2,__defProp,__getOwnPropNames,__glob,__esm,__export,init_adminDB,init_classroomDB,init_SyncStrategy,isDevelopment,logger,init_logger,GuestUsername,log,DocType,DocTypePrefixes,init_types_legacy,init_util,pouchdb_setup_default,init_pouchdb_setup,Loggable,init_Loggable,UpdateQueue,init_updateQueue,CLIENT_CACHE,init_clientCache,AlreadyTaggedErr,init_courseAPI,courseLookupDBTitle,CourseLookup,init_courseLookupDB,diversityRerank_exports,DIVERSITY_STRENGTH,DIVERSITY_FLOOR,STRATEGY,STRATEGY_ID,STRATEGY_NAME,init_diversityRerank,PipelineDebugger_exports,_activePipeline,MAX_RUNS,runHistory,_currentSessionId,_pendingRuns,DISCARDED_KEEP_TOP,_uiContainer,_selectedRunIndex,_cardSearchQuery,pipelineDebugAPI,init_PipelineDebugger,SrsDebugger_exports,snapshots,init_SrsDebugger,StrategyPressureDebugger_exports,snapshots2,init_StrategyPressureDebugger,CompositeGenerator_exports,AggregationMode,DEFAULT_AGGREGATION_MODE,FREQUENCY_BOOST_FACTOR,CompositeGenerator,init_CompositeGenerator,elo_exports,ELONavigator,init_elo,generators_exports,init_generators,prescribed_exports,DEFAULT_FRESHNESS_WINDOW,DEFAULT_MAX_DIRECT_PER_RUN,DEFAULT_MAX_SUPPORT_PER_RUN,DEFAULT_HIERARCHY_DEPTH,DEFAULT_MIN_COUNT,DEFAULT_PRACTICE_MIN_COUNT,DEFAULT_MAX_PRACTICE_PER_RUN,BASE_TARGET_SCORE,BASE_SUPPORT_SCORE,DISCOVERED_SUPPORT_SCORE,BASE_PRACTICE_SCORE,PRACTICE_BASE_MULT,MAX_PRACTICE_MULTIPLIER,PRACTICE_STALENESS_BUMP_PER_DAY,MAX_TARGET_MULTIPLIER,MAX_SUPPORT_MULTIPLIER,PRESCRIBED_DEBUG_VERSION,PrescribedCardsGenerator,init_prescribed,regulators_exports,DEFAULT_REGULATOR_CONFIG,INTAKE_CLOCK_KEY,REGULATOR_LABEL,init_regulators,srs_exports,SRSNavigator,init_srs,types_exports,init_types,globImport_generators,init_,DEFAULT_LEARNABLE_WEIGHT,init_contentNavigationStrategy,WeightedFilter_exports,WeightedFilter,init_WeightedFilter,eloDistance_exports,DEFAULT_ELO_DISTANCE_CONFIG,TAG_CONFIDENCE_HALF,DEFAULT_CARD_ELO,MULTI_DIM_ELO_KEY,multiDimElo,EloDistanceFilter,init_eloDistance,hierarchyDefinition_exports,DEFAULT_MIN_COUNT2,HierarchyDefinitionNavigator,init_hierarchyDefinition,userTagPreference_exports,UserTagPreferenceFilter,init_userTagPreference,filters_exports,init_filters,inferredPreferenceStub_exports,INFERRED_PREFERENCE_NAVIGATOR_STUB,init_inferredPreferenceStub,interferenceMitigator_exports,DEFAULT_MIN_COUNT3,DEFAULT_MIN_ELAPSED_DAYS,DEFAULT_INTERFERENCE_DECAY,InterferenceMitigatorNavigator,init_interferenceMitigator,relativePriority_exports,DEFAULT_PRIORITY,DEFAULT_PRIORITY_INFLUENCE,DEFAULT_COMBINE_MODE,RelativePriorityNavigator,init_relativePriority,types_exports2,init_types2,userGoalStub_exports,USER_GOAL_NAVIGATOR_STUB,init_userGoalStub,globImport_filters,init_2,init_gradient,MIN_OBSERVATIONS_FOR_UPDATE,LEARNING_RATE,MAX_WEIGHT_DELTA,MIN_R_SQUARED_FOR_GRADIENT,FLAT_GRADIENT_THRESHOLD,MAX_HISTORY_LENGTH,init_learning,init_signal,init_recording,MIN_SPREAD,MAX_SPREAD,MIN_WEIGHT,MAX_WEIGHT,init_orchestration,Pipeline_exports,VERBOSE_RESULTS,Pipeline,init_Pipeline,FRAMEWORK_VERSION,hostAppVersion,DEFAULT_STRATEGY_HASH,init_versionStamps,defaults_exports,init_defaults,pipelinePlan_exports,PIPELINE_STAGES,init_pipelinePlan,PipelineAssembler_exports,PipelineAssembler,init_PipelineAssembler,globImport,init_3,navigators_exports,navigatorRegistry,Navigators,NavigatorRole,NavigatorRoles,ContentNavigator,init_navigators,CoursesDB,CourseDB,init_courseDB,classroomLookupDBTitle,CLASSROOM_CONFIG,ClassroomDBBase,StudentClassroomDB,TeacherClassroomDB,ClassroomLookupDB,init_classroomDB2,AdminDB,init_adminDB2,CourseSyncService_exports,DEFAULT_REPLICATION,CourseSyncService,init_CourseSyncService,init_auth,CouchDBSyncStrategy_exports,log2,CouchDBSyncStrategy,init_CouchDBSyncStrategy,isBrowser,GUEST_LOCAL_DB,localUserDB,pouchDBincludeCredentialsConfig,REVIEW_TIME_FORMAT,init_couch,duration,init_SpacedRepetition,SrsService,init_SrsService,init_tagRecent,EloService,init_EloService,ResponseProcessor,init_ResponseProcessor,CardHydrationService,init_CardHydrationService,ItemQueue,init_ItemQueue,init_studySession,init_types3,CouchDBToStaticPacker,init_CouchDBToStaticPacker,init_packer,DEFAULT_MIGRATION_OPTIONS,init_types4,FileSystemError,init_FileSystemAdapter,nodeFS,init_validation,nodeFS2,nodePath,StaticToCouchDBMigrator,init_StaticToCouchDBMigrator,init_migrator,init_dataDirectory,init_util2,QuotaRoundRobinMixer,init_SourceMixer,MAX_RUNS2,runHistory2,mixerDebugAPI,init_MixerDebugger,activeController,OVERLAY_ID,POLL_MS,INLINE_THRESHOLD,SPINNER_FRAMES,spinnerFrame,overlayEl,pollHandle,lastSnapshot,copyFlashUntil,minified,expanded,init_SessionOverlay,activeSession,sessionHistory,MAX_HISTORY,sessionDebugAPI,init_SessionDebugger,PERSISTED_RUNNERS_UP,SessionController,init_SessionController,TagFilteredContentSource,init_TagFilteredContentSource,init_study,REVIEW_TIME_FORMAT2,log3,init_userDBHelpers,UsrCrsData,init_user_course_relDB,log4,HYDRATION_TIMEOUT_MS,BaseUser,userCoursesDoc,userClassroomsDoc,init_BaseUserDB,init_common,PouchDataLayerProvider_exports,CouchDataLayerProvider,init_PouchDataLayerProvider,pathUtils,nodeFS3,StaticDataUnpacker,init_StaticDataUnpacker,StaticCourseDB,init_courseDB2,StaticCoursesDB,init_coursesDB,NoOpSyncStrategy,init_NoOpSyncStrategy,StaticDataLayerProvider_exports,StaticDataLayerProvider,init_StaticDataLayerProvider,NOT_SET,ENV,dataLayerInstance,init_factory,init_contentSource,init_courseDB3,init_dataLayerProvider,init_userDB,init_interfaces,init_user,init_strategyState,init_userOutcome,HYDRATION_MARKER_ID,init_hydration,init_cardProcessor,init_types5,init_bulkImport,userDBDebugAPI,init_UserDBDebugger,init_core,init_dist=__esmMin((()=>{init_defineProperty(),init_index_browser_es$5(),init_index_browser_es(),init_index_es(),init_dist$1(),init_esm_browser(),init_moment(),import_browser_ponyfill=__toESM$2(require_browser_ponyfill(),1),import_browser_ponyfill$1=__toESM$2(require_browser_ponyfill(),1),import_browser=__toESM$2(require_browser(),1),import___vite_browser_external=__toESM$2(require___vite_browser_external(),1),import___vite_browser_external$1=__toESM$2(require___vite_browser_external(),1),import___vite_browser_external$2=__toESM$2(require___vite_browser_external(),1),__defProp=Object.defineProperty,__getOwnPropNames=Object.getOwnPropertyNames,__glob=t=>c=>{var u=t[c];if(u)return u();throw Error(`Module not found in bundle: `+c)},__esm=(t,c)=>function __init(){return t&&(c=(0,t[__getOwnPropNames(t)[0]])(t=0)),c},__export=(t,c)=>{for(var u in c)__defProp(t,u,{get:c[u],enumerable:!0})},init_adminDB=__esm({"src/core/interfaces/adminDB.ts"(){"use strict";}}),init_classroomDB=__esm({"src/core/interfaces/classroomDB.ts"(){"use strict";}}),init_SyncStrategy=__esm({"src/impl/common/SyncStrategy.ts"(){"use strict";}}),init_logger=__esm({"src/util/logger.ts"(){"use strict";isDevelopment=typeof process<`u`&&process.env.NODE_ENV===`development`,logger={debug:(t,...c)=>{isDevelopment&&console.debug(`[DB:DEBUG] ${t}`,...c)},info:(t,...c)=>{console.info(`[DB:INFO] ${t}`,...c)},warn:(t,...c)=>{console.warn(`[DB:WARN] ${t}`,...c)},error:(t,...c)=>{console.error(`[DB:ERROR] ${t}`,...c)},log:(t,...c)=>{isDevelopment&&console.log(`[DB:LOG] ${t}`,...c)}}}}),init_types_legacy=__esm({"src/core/types/types-legacy.ts"(){"use strict";init_logger(),GuestUsername=`sk-guest-`,log=t=>{logger.log(t)},DocType=(t=>(t.DISPLAYABLE_DATA=`DISPLAYABLE_DATA`,t.CARD=`CARD`,t.DATASHAPE=`DATASHAPE`,t.QUESTIONTYPE=`QUESTION`,t.VIEW=`VIEW`,t.PEDAGOGY=`PEDAGOGY`,t.CARDRECORD=`CARDRECORD`,t.SCHEDULED_CARD=`SCHEDULED_CARD`,t.TAG=`TAG`,t.NAVIGATION_STRATEGY=`NAVIGATION_STRATEGY`,t.STRATEGY_STATE=`STRATEGY_STATE`,t.USER_OUTCOME=`USER_OUTCOME`,t.STRATEGY_LEARNING_STATE=`STRATEGY_LEARNING_STATE`,t.STUDY_SESSION=`STUDY_SESSION`,t))(DocType||{}),DocTypePrefixes={CARD:`c`,DISPLAYABLE_DATA:`dd`,TAG:`TAG`,CARDRECORD:`cardH`,SCHEDULED_CARD:`card_review_`,DATASHAPE:`DATASHAPE`,QUESTION:`QUESTION`,VIEW:`VIEW`,PEDAGOGY:`PEDAGOGY`,NAVIGATION_STRATEGY:`NAVIGATION_STRATEGY`,STRATEGY_STATE:`STRATEGY_STATE`,USER_OUTCOME:`USER_OUTCOME`,STRATEGY_LEARNING_STATE:`STRATEGY_LEARNING_STATE`,STUDY_SESSION:`SESSION`}}}),init_util=__esm({"src/core/util/index.ts"(){"use strict";init_types_legacy()}}),init_pouchdb_setup=__esm({"src/impl/couch/pouchdb-setup.ts"(){"use strict";PouchDB.plugin(plugin$1),PouchDB.plugin(plugin),PouchDB.debug!==void 0&&PouchDB.debug.disable(),PouchDB.defaults({}),pouchdb_setup_default=PouchDB}}),init_Loggable=__esm({"src/util/Loggable.ts"(){"use strict";Loggable=class{log(...t){console.log(`LOG-${this._className}@${new Date}:`,...t)}error(...t){console.error(`ERROR-${this._className}@${new Date}:`,...t)}}}}),init_updateQueue=__esm({"src/impl/couch/updateQueue.ts"(){"use strict";init_Loggable(),init_logger(),UpdateQueue=class extends Loggable{update(t,c){return logger.debug(`Update requested on doc: ${t}`),this.pendingUpdates[t]?this.pendingUpdates[t].push(c):this.pendingUpdates[t]=[c],this.applyUpdates(t)}constructor(t,c){super(),_defineProperty$2(this,`_className`,`UpdateQueue`),_defineProperty$2(this,`pendingUpdates`,{}),_defineProperty$2(this,`inprogressUpdates`,{}),_defineProperty$2(this,`readDB`,void 0),_defineProperty$2(this,`writeDB`,void 0),this.readDB=t,this.writeDB=c||t,logger.debug(`UpdateQ initialized...`),this.readDB.info().then(t=>{logger.debug(`db info: ${JSON.stringify(t)}`)})}async applyUpdates(t){if(logger.debug(`Applying updates on doc: ${t}`),this.inprogressUpdates[t]){for(;this.inprogressUpdates[t];)await new Promise(t=>setTimeout(t,Math.random()*50));return this.applyUpdates(t)}else if(this.pendingUpdates[t]&&this.pendingUpdates[t].length>0){this.inprogressUpdates[t]=!0;let c=5;for(let c=0;c<5;c++)try{let c={...await this.readDB.get(t)},u=[...this.pendingUpdates[t]];for(let t of u)c=typeof t==`function`?{...c,...t(c)}:{...c,...t};if(await this.writeDB.put(c),this.pendingUpdates[t].splice(0,u.length),this.pendingUpdates[t].length===0)this.inprogressUpdates[t]=!1,delete this.inprogressUpdates[t];else return this.applyUpdates(t);return c}catch(u){if(u.name===`conflict`&&c<4)logger.warn(`Conflict on update for doc ${t}, retry #${c+1}`),await new Promise(t=>setTimeout(t,50*Math.random()));else if(u.name===`not_found`&&c===0)throw logger.warn(`Update failed for ${t} - does not exist. Throwing to caller.`),delete this.inprogressUpdates[t],u;else throw delete this.inprogressUpdates[t],this.pendingUpdates[t]&&delete this.pendingUpdates[t],logger.error(`Error on attemped update (retry ${c}): ${JSON.stringify(u)}`),u}throw Error(`UpdateQueue failed for doc ${t} after 5 retries.`)}else throw Error(`Empty Updates Queue Triggered`)}}}}),init_clientCache=__esm({"src/impl/couch/clientCache.ts"(){"use strict";CLIENT_CACHE={}}}),init_courseAPI=__esm({"src/impl/couch/courseAPI.ts"(){"use strict";init_pouchdb_setup(),init_couch(),init_factory(),init_courseDB(),init_types_legacy(),init_common(),init_logger(),AlreadyTaggedErr=class extends Error{constructor(t){super(t),this.name=`AlreadyTaggedErr`}}}}),init_courseLookupDB=__esm({"src/impl/couch/courseLookupDB.ts"(){"use strict";var t;init_pouchdb_setup(),init_factory(),init_logger(),courseLookupDBTitle=`coursedb-lookup`,logger.debug(`COURSELOOKUP FILE RUNNING`),CourseLookup=(t=class _CourseLookup{static get _db(){if(this._dbInstance)return this._dbInstance;if(ENV.COUCHDB_SERVER_URL===`NOT_SET`||!ENV.COUCHDB_SERVER_URL)throw Error(`CourseLookup.db: COUCHDB_SERVER_URL is not set. Ensure initializeDataLayer has been called with valid configuration.`);if(ENV.COUCHDB_SERVER_PROTOCOL===`NOT_SET`||!ENV.COUCHDB_SERVER_PROTOCOL)throw Error(`CourseLookup.db: COUCHDB_SERVER_PROTOCOL is not set. Ensure initializeDataLayer has been called with valid configuration.`);let t=`${ENV.COUCHDB_SERVER_PROTOCOL}://${ENV.COUCHDB_SERVER_URL}/${courseLookupDBTitle}`,c={};ENV.COUCHDB_USERNAME&&ENV.COUCHDB_PASSWORD?(c.auth={username:ENV.COUCHDB_USERNAME,password:ENV.COUCHDB_PASSWORD},logger.info(`CourseLookup: Connecting to ${t} with authentication.`)):logger.info(`CourseLookup: Connecting to ${t} without authentication.`);try{return this._dbInstance=new pouchdb_setup_default(t,c),logger.info(`CourseLookup: Database instance created for ${courseLookupDBTitle}.`),this._dbInstance}catch(c){throw logger.error(`CourseLookup: Failed to create PouchDB instance for ${t}`,c),this._dbInstance=null,Error(`CourseLookup: Failed to initialize database connection: ${c instanceof Error?c.message:String(c)}`)}}static async add(t){return(await _CourseLookup._db.post({name:t})).id}static async addWithId(t,c,u){let d={_id:t,name:c};u&&(d.disambiguator=u),await _CourseLookup._db.put(d)}static async delete(t){let c=await _CourseLookup._db.get(t);return await _CourseLookup._db.remove(c)}static async allCourseWare(){return(await _CourseLookup._db.allDocs({include_docs:!0})).rows.map(t=>t.doc)}static async updateDisambiguator(t,c){let u=await _CourseLookup._db.get(t);return u.disambiguator=c,await _CourseLookup._db.put(u)}static async isCourse(t){try{return await _CourseLookup._db.get(t),!0}catch(t){return logger.info(`Courselookup failed:`,t),!1}}},_defineProperty$2(t,`_dbInstance`,null),t)}}),diversityRerank_exports={},__export(diversityRerank_exports,{DIVERSITY_FLOOR:()=>DIVERSITY_FLOOR,DIVERSITY_STRENGTH:()=>DIVERSITY_STRENGTH,diversityRerank:()=>diversityRerank}),init_diversityRerank=__esm({"src/core/navigators/diversityRerank.ts"(){"use strict";DIVERSITY_STRENGTH=.6,DIVERSITY_FLOOR=.3,STRATEGY=`diversityRerank`,STRATEGY_ID=`DIVERSITY_RERANK`,STRATEGY_NAME=`Diversity Re-rank`}}),PipelineDebugger_exports={},__export(PipelineDebugger_exports,{buildRunReport:()=>buildRunReport,captureRun:()=>captureRun,clearRunHistory:()=>clearRunHistory,drainCapturedRuns:()=>drainCapturedRuns,getActivePipeline:()=>getActivePipeline,getRunsForSession:()=>getRunsForSession,mountPipelineDebugger:()=>mountPipelineDebugger,pipelineDebugAPI:()=>pipelineDebugAPI,registerPipelineForDebug:()=>registerPipelineForDebug,setDebugSessionId:()=>setDebugSessionId}),init_PipelineDebugger=__esm({"src/core/navigators/PipelineDebugger.ts"(){"use strict";init_navigators(),init_logger(),_activePipeline=null,MAX_RUNS=10,runHistory=[],_pendingRuns=[],DISCARDED_KEEP_TOP=25,_uiContainer=null,_selectedRunIndex=null,_cardSearchQuery=``,pipelineDebugAPI={get runs(){return[...runHistory]},showRun(t=0){if(runHistory.length===0){logger.info(`[Pipeline Debug] No runs captured yet.`);return}let c;if(typeof t==`number`){if(c=runHistory[t],!c){logger.info(`[Pipeline Debug] No run found at index ${t}. History length: ${runHistory.length}`);return}}else if(c=runHistory.find(c=>c.runId.endsWith(t)),!c){logger.info(`[Pipeline Debug] No run found matching ID '${t}'.`);return}printRunSummary(c)},showLastRun(){this.showRun(0)},showCard(t){for(let c of runHistory){let u=c.cards.find(c=>c.cardId===t);if(u){console.group(`\u{1F3B4} Card: ${t}`),logger.info(`Course: ${u.courseId}`),logger.info(`Origin: ${u.origin}`),logger.info(`Card ELO: ${u.cardElo??`unknown`} | User ELO: ${c.userElo??`unknown`}`),logger.info(`Final score: ${u.finalScore.toFixed(3)}`),logger.info(`Selected: ${u.selected?`Yes ✅`:`No ❌`}`),u.tags&&u.tags.length>0&&logger.info(`Tags (${u.tags.length}): ${u.tags.join(`, `)}`),logger.info(`Provenance:`),logger.info(formatProvenance(u.provenance)),console.groupEnd();return}}let c=runHistory.filter(t=>t.discardedTail&&t.discardedTail.count>0);c.length>0?logger.info(`[Pipeline Debug] Card '${t}' not found in retained cards. ${c.length} run(s) have discarded tails that were not retained \u2014 the card may have been a low-score candidate. See run.discardedTail for ranges.`):logger.info(`[Pipeline Debug] Card '${t}' not found in recent runs.`)},explainReviews(){if(runHistory.length===0){logger.info(`[Pipeline Debug] No runs captured yet.`);return}console.group(`📋 Review Selection Analysis`);for(let t of runHistory){console.group(`Run: ${t.courseId} @ ${t.timestamp.toLocaleTimeString()}`);let c=t.cards.filter(t=>t.origin===`review`),u=c.filter(t=>t.selected);if(c.length===0)logger.info(`❌ No reviews were generated. Check SRS logs for why.`);else if(u.length===0){logger.info(`\u26A0\uFE0F ${c.length} reviews generated but none selected.`),logger.info(`Possible reasons:`);let u=Math.max(...t.cards.filter(t=>t.origin===`new`&&t.selected).map(t=>t.finalScore),0),d=Math.max(...c.map(t=>t.finalScore),0);d<u&&logger.info(` - New cards scored higher (top new: ${u.toFixed(2)}, top review: ${d.toFixed(2)})`);let m=c.sort((t,c)=>c.finalScore-t.finalScore)[0];m&&(logger.info(` - Top review score: ${m.finalScore.toFixed(3)}`),logger.info(` - Its provenance:`),logger.info(formatProvenance(m.provenance)))}else{logger.info(`\u2705 ${u.length}/${c.length} reviews selected.`),logger.info(`Top selected review:`);let t=u.sort((t,c)=>c.finalScore-t.finalScore)[0];logger.info(formatProvenance(t.provenance))}console.groupEnd()}console.groupEnd()},showPrescribed(t){if(runHistory.length===0){logger.info(`[Pipeline Debug] No runs captured yet.`);return}let c=runHistory[0],u=c.cards.filter(t=>t.provenance.some(t=>t.strategy===`prescribed`));if(console.group(`\u{1F9ED} Prescribed Debug (${c.courseId})`),u.length===0){logger.info(`No prescribed-generated cards were present in the most recent run.`),console.groupEnd();return}let d=u.map(t=>{let c=t.provenance.find(t=>t.strategy===`prescribed`)?.reason??``,u=c.match(/group=([^;]+)/)?.[1]??`unknown`,d=c.match(/mode=([^;]+)/)?.[1]??`unknown`,m=c.match(/blocked=([^;]+)/)?.[1]??`unknown`,g=c.match(/blockedTargets=([^;]+)/)?.[1]??`none`,b=c.match(/supportCard=([^;]+)/)?.[1]??`none`,S=c.match(/supportTags=([^;]+)/)?.[1]??`none`,C=c.match(/multiplier=([^;]+)/)?.[1]??`unknown`;return{group:u,mode:d,supportSource:d===`discovered-support`?`discovered`:d===`support`?`authored`:`n/a`,cardId:t.cardId,selected:t.selected?`yes`:`no`,finalScore:t.finalScore.toFixed(3),blocked:m,blockedTargets:g,supportCard:b,supportTags:S,multiplier:C}}).filter(c=>!t||c.group===t).sort((t,c)=>Number(c.finalScore)-Number(t.finalScore));if(d.length===0){logger.info(`[Pipeline Debug] No prescribed cards matched group '${t}' in the most recent run.`),console.groupEnd();return}console.table(d);let m=d.filter(t=>t.selected===`yes`),g=new Set,b=new Set,S=new Set,C=new Set;for(let t of d)t.blockedTargets&&t.blockedTargets!==`none`&&t.blockedTargets.split(`|`).filter(Boolean).forEach(t=>g.add(t)),t.supportTags&&t.supportTags!==`none`&&t.supportTags.split(`|`).filter(Boolean).forEach(t=>b.add(t)),t.supportCard&&t.supportCard!==`none`&&(t.supportSource===`discovered`?C.add(t.supportCard):t.supportSource===`authored`&&S.add(t.supportCard));logger.info(`Prescribed cards in run: ${d.length}`),logger.info(`Selected prescribed cards: ${m.length}`),logger.info(`Blocked prescribed targets referenced: ${g.size>0?[...g].join(`, `):`none`}`),logger.info(`Resolved support tags referenced: ${b.size>0?[...b].join(`, `):`none`}`),logger.info(`Authored support cards emitted: ${S.size>0?[...S].join(`, `):`none`}`),logger.info(`Discovered support cards emitted: ${C.size>0?[...C].join(`, `):`none`}`),console.groupEnd()},listRuns(){if(runHistory.length===0){logger.info(`[Pipeline Debug] No runs captured yet.`);return}console.table(runHistory.map(t=>({id:t.runId.slice(-8),time:t.timestamp.toLocaleTimeString(),course:t.courseName||t.courseId.slice(0,8),generated:t.generatedCount,selected:t.finalCount,new:t.newSelected,reviews:t.reviewsSelected})))},export(){let t=JSON.stringify(runHistory,null,2);return logger.info(`[Pipeline Debug] Run history exported. Copy the returned string or use:`),logger.info(` copy(window.skuilder.pipeline.export())`),t},clear(){runHistory.length=0,logger.info(`[Pipeline Debug] Run history cleared.`)},showRegistry(){let t=getRegisteredNavigatorNames();if(t.length===0){logger.info(`[Pipeline Debug] Navigator registry is empty.`);return}console.group(`📦 Navigator Registry`),console.table(t.map(t=>{let c=getRegisteredNavigatorRole(t),u=NavigatorRoles[t];return{name:t,role:u||c||`⚠️ NONE`,source:u?`built-in`:c?`consumer`:`unclassified`,isGenerator:isGenerator(t),isFilter:isFilter(t)}})),console.groupEnd()},showStrategies(){if(this.showRegistry(),runHistory.length===0){logger.info(`[Pipeline Debug] No pipeline runs captured yet — cannot show strategy doc mapping.`);return}let t=runHistory[0];if(console.group(`🔌 Pipeline Strategy Mapping (last run)`),logger.info(`Generator: ${t.generatorName}`),t.generators&&t.generators.length>0)for(let c of t.generators)logger.info(` \u{1F4E5} ${c.name}: ${c.cardCount} cards (${c.newCount} new, ${c.reviewCount} reviews)`);if(t.filters.length>0){logger.info(`Filters:`);for(let c of t.filters)logger.info(` \u{1F538} ${c.name}: \u2191${c.boosted} \u2193${c.penalized} =${c.passed} \u2715${c.removed}`)}else logger.info(`Filters: (none)`);console.groupEnd()},async diagnoseCardSpace(t){return _activePipeline?_activePipeline.diagnoseCardSpace({threshold:t}):(logger.info(`[Pipeline Debug] No active pipeline. Run a session first.`),null)},async showTagElo(t){if(!_activePipeline){logger.info(`[Pipeline Debug] No active pipeline. Run a session first.`);return}let c=await _activePipeline.getTagEloStatus(t),u=Object.entries(c).sort(([t],[c])=>t.localeCompare(c));if(u.length===0){logger.info(`[Pipeline Debug] No tag ELO data found${t?` for pattern: ${t}`:``}.`);return}console.table(Object.fromEntries(u.map(([t,c])=>[t,{score:Math.round(c.score),count:c.count}])))},ui(){if(_uiContainer){document.body.removeChild(_uiContainer),_uiContainer=null;return}_uiContainer=document.createElement(`div`),_uiContainer.id=`sk-pipeline-debugger`,document.body.appendChild(_uiContainer),_selectedRunIndex===null&&runHistory.length>0&&(_selectedRunIndex=0),renderUI()},_selectRun(t){_selectedRunIndex=t,renderUI()},_setSearch(t){_cardSearchQuery=t,renderUI()},_copyConfig(t,c){let u=runHistory.find(c=>c.runId===t);if(!u)return;let d={runId:u.runId,timestamp:u.timestamp.toISOString(),courseId:u.courseId,courseName:u.courseName,hints:u.hints??null};copyTextToClipboard(JSON.stringify(d,null,2),c)},_copyResults(t,c){let u=runHistory.find(c=>c.runId===t);if(!u)return;let d=u.cards.filter(t=>t.selected).sort((t,c)=>c.finalScore-t.finalScore).map(t=>({cardId:t.cardId,generator:t.generator,origin:t.origin,score:Number(t.finalScore.toFixed(3)),topReason:t.provenance[0]?.reason??``})),m={runId:u.runId,label:u.hints?._label??null,finalCount:u.finalCount,newSelected:u.newSelected,reviewsSelected:u.reviewsSelected,selected:d};copyTextToClipboard(JSON.stringify(m,null,2),c)},help(){logger.info(`
328
329
  🔧 Pipeline Debug API
329
330
 
330
331
  Commands:
@@ -349,7 +350,7 @@ Example:
349
350
  window.skuilder.pipeline.showLastRun()
350
351
  window.skuilder.pipeline.showRun(1)
351
352
  await window.skuilder.pipeline.diagnoseCardSpace()
352
- `)}},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,`_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().then(t=>t.name).catch(()=>void 0);captureRun(buildRunReport(this.course?.getCourseID()||`unknown`,t,this.generator.name,w,C,xr,b,Or,u.userElo,Er??void 0,wr,Tr))}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}}}}),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()}}),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(),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 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.33`,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
354
  `)}`),this._courseIDs&&(t=t.filter(t=>this._courseIDs.includes(t._id))),logger.debug(`AllCourses.filtered: ${t.map(t=>t.name+`, `+t._id+`
354
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:
355
356
  ${d.rows.map(t=>` ${t.id}-${t.key}
@@ -362,17 +363,17 @@ ${g.rows.map(t=>` ${t.id}-${t.key}
362
363
  `+C),S}async getCourseConfig(){let t=await getCredentialledCourseConfig(this.id);if(t)return t;throw Error(`Course config not found for course ID: ${this.id}`)}async updateCourseConfig(t){logger.debug(`Updating: ${JSON.stringify(t)}`);try{return await updateCredentialledCourseConfig(this.id,t)}catch(t){throw logger.error(`Error updating course config in course DB: ${t}`),t}}async updateCardElo(t,c){if(!c)throw Error(`Cannot update card elo with null or undefined value for card ID: ${t}`);try{return{ok:!0,id:t,rev:(await this.updateQueue.update(t,t=>(logger.debug(`Replacing ${JSON.stringify(t.elo)} with ${JSON.stringify(c)}`),t.elo=c,t)))._rev}}catch(c){throw logger.error(`Failed to update card elo for card ID: ${t}`,c),Error(`Failed to update card elo for card ID: ${t}`)}}async getAppliedTags(t){let c=await getAppliedTags(this.id,t);if(c)return c;throw Error(`Failed to find tags for card ${this.id}-${t}`)}async getAppliedTagsBatch(t){if(t.length===0)return new Map;let c=await this.db.query(`getTags`,{keys:t,include_docs:!1}),u=new Map;for(let c of t)u.set(c,[]);for(let t of c.rows){let c=t.key,d=t.value?.name;d&&u.has(c)&&u.get(c).push(d)}return u}async getAllCardIds(){let t=`${DocTypePrefixes.CARD}-`;return(await this.db.allDocs({startkey:t,endkey:`${t}\uFFF0`,include_docs:!1})).rows.map(t=>t.id)}async addTagToCard(t,c,u){return await addTagToCard(this.id,t,c,(await this._getCurrentUser()).getUsername(),u)}async removeTagFromCard(t,c){return await removeTagFromCard(this.id,t,c)}async createTag(t,c){return await createTag(this.id,t,c)}async getTag(t){return await getTag(this.id,t)}async updateTag(t){if(t.course!==this.id)throw Error(`Tag ${JSON.stringify(t)} does not belong to course ${this.id}`);return await updateTag(t)}async getCourseTagStubs(){return getCourseTagStubs(this.id)}async addNote(t,c,u,d,m,g,b=blankCourseElo()){try{let S=await addNote55(this.id,t,c,u,d,m,g,b);return S.ok?S.cardCreationFailed?(logger.warn(`[courseDB.addNote] Note added but card creation failed: ${S.cardCreationError}`),{status:Status.error,message:`Note was added but no cards were created: ${S.cardCreationError}`,id:S.id}):{status:Status.ok,message:``,id:S.id}:{status:Status.error,message:`Unexpected error adding note`}}catch(t){let c=t;return logger.error(`[addNote] error ${c.name}
363
364
  reason: ${c.reason}
364
365
  message: ${c.message}`),{status:Status.error,message:`Error adding note to course. ${t.reason||c.message}`}}}async getCourseDoc(t,c){return await this.db.get(t,c??{})}async getCourseDocs(t,c={}){return await this.db.allDocs({...c,keys:t})}getNavigationStrategy(t){if(logger.debug(`[courseDB] Getting navigation strategy: ${t}`),t==``){let t={_id:`NAVIGATION_STRATEGY-ELO`,docType:`NAVIGATION_STRATEGY`,name:`ELO`,description:`ELO-based navigation strategy for ordering content by difficulty`,implementingClass:`elo`,course:this.id,serializedData:``};return Promise.resolve(t)}else return this.db.get(t)}async getAllNavigationStrategies(){let t=DocTypePrefixes.NAVIGATION_STRATEGY;return(await this.db.allDocs({startkey:t,endkey:`${t}\uFFF0`,include_docs:!0})).rows.map(t=>t.doc)}async addNavigationStrategy(t){return logger.debug(`[courseDB] Adding navigation strategy: ${t._id}`),this.invalidateNavigatorCache(),this.remoteDB.put(t).then(()=>{})}updateNavigationStrategy(t,c){return logger.debug(`[courseDB] Updating navigation strategy: ${t}`),logger.debug(JSON.stringify(c)),Promise.resolve()}async createNavigator(t){try{let c=await this.getAllNavigationStrategies();if(c.length===0)return logger.debug(`[courseDB] No strategy documents found, using default Pipeline(Composite(ELO, SRS), [eloDistanceFilter])`),createDefaultPipeline(t,this);let{pipeline:u,generatorStrategies:d,filterStrategies:m,warnings:g}=await new PipelineAssembler().assemble({strategies:c,user:t,course:this});for(let t of g)logger.warn(`[PipelineAssembler] ${t}`);return u?(logger.debug(`[courseDB] Using assembled pipeline with ${d.length} generator(s) and ${m.length} filter(s)`),u):(logger.debug(`[courseDB] Pipeline assembly failed, using default pipeline`),createDefaultPipeline(t,this))}catch(t){let c=t instanceof Error?`${t.message}
365
- ${t.stack}`:JSON.stringify(t);throw logger.error(`[courseDB] Error creating navigator: ${c}`),t}}setEphemeralHints(t){this._pendingHints=t}notePresented(t){t.status===`new`&&this._getCurrentUser().then(t=>this._getCachedNavigator(t)).then(({navigator:c})=>c.notePresented?.(t)).catch(t=>logger.warn(`[courseDB] Could not note a presentation: ${t}`))}async getWeightedCards(t){let c=await this._getCurrentUser();try{let{navigator:u}=await this._getCachedNavigator(c);return this._pendingHints&&(u.setEphemeralHints(this._pendingHints),this._pendingHints=null),await u.getWeightedCards(t)}catch(t){throw logger.error(`[courseDB] Error getting weighted cards: ${t}`),t}}async _getCachedNavigator(t){let c=t.getUsername(),u=Date.now();if(this._cachedNavigator&&this._cachedNavigator.userId===c&&u-this._cachedNavigator.builtAt<this._navigatorTtlMs)return{navigator:this._cachedNavigator.navigator,cacheStatus:`hit`};let d=await this.createNavigator(t);return this._cachedNavigator={navigator:d,userId:c,builtAt:u},{navigator:d,cacheStatus:`miss`}}invalidateNavigatorCache(){this._cachedNavigator=null}async getCardsCenteredAtELO(t={limit:99,elo:`user`},c){let u;if(t.elo===`user`){let t=await this._getCurrentUser();u=-1;try{u=EloToNumber((await t.getCourseRegistrationsDoc()).courses.find(t=>t.courseID===this.id).elo)}catch{u=1e3}}else if(t.elo===`random`){let t=await GET_CACHED(`elo-bounds-${this.id}`,()=>this.getELOBounds());u=Math.round(t.low+Math.random()*(t.high-t.low))}else u=t.elo;let d=Math.max(2e3,t.limit*4),m=Date.now(),g=`hit`;if(!this._eloPoolCache||m-this._eloPoolCache.fetchedAt>this._eloPoolTtlMs){let t=await this.getCardsByELO(u,d);t.length>0&&(this._eloPoolCache={rows:t,fetchedAt:m}),g=`miss`}let rankAgainstCurrentElo=()=>{let t=this._eloPoolCache?.rows??[];return(c?t.filter(t=>c(t)):t).map(t=>({...t})).sort((t,c)=>Math.abs((t.elo??u)-u)-Math.abs((c.elo??u)-u))},b=rankAgainstCurrentElo();if(b.length<t.limit&&(g===`hit`||!this._eloPoolCache)){let t=await this.getCardsByELO(u,d);t.length>0&&(this._eloPoolCache={rows:t,fetchedAt:m}),b=rankAgainstCurrentElo(),g=`refresh`}let S=[];for(;S.length<t.limit&&b.length>0;){let t=randIntWeightedTowardZero(b.length),c=b.splice(t,1)[0];S.push(c)}return S.map(t=>({courseID:this.id,cardID:t.cardID,contentSourceType:`course`,contentSourceID:this.id,elo:t.elo,status:`new`}))}async searchCards(t){logger.log(`[CourseDB ${this.id}] Searching for: "${t}"`);let c;try{c=await this.db.find({selector:{docType:`DISPLAYABLE_DATA`,"data.0.data":{$regex:`.*${t}.*`}}}),logger.log(`[CourseDB ${this.id}] Regex search on data[0].data successful`)}catch(u){logger.log(`[CourseDB ${this.id}] Regex search failed, falling back to manual search:`,u);let d=await this.db.find({selector:{docType:`DISPLAYABLE_DATA`}});logger.log(`[CourseDB ${this.id}] Retrieved ${d.docs.length} documents for manual filtering`),c={docs:d.docs.filter(c=>{let u=JSON.stringify(c).toLowerCase().includes(t.toLowerCase());return u&&logger.log(`[CourseDB ${this.id}] Manual match found in document: ${c._id}`),u})}}if(logger.log(`[CourseDB ${this.id}] Found ${c.docs.length} displayable data documents`),c.docs.length===0){let t=await this.db.find({selector:{docType:`DISPLAYABLE_DATA`},limit:5});logger.log(`[CourseDB ${this.id}] Sample displayable data:`,t.docs.map(t=>({id:t._id,docType:t.docType,dataStructure:t.data?Object.keys(t.data):`no data field`,dataContent:t.data,fullDoc:t})))}let u=[];for(let t of c.docs){let c=await this.db.find({selector:{docType:`CARD`,id_displayable_data:{$in:[t._id]}}});logger.log(`[CourseDB ${this.id}] Displayable data ${t._id} linked to ${c.docs.length} cards`),u.push(...c.docs)}return logger.log(`[CourseDB ${this.id}] Total cards found: ${u.length}`),u}async find(t){return this.db.find(t)}}}}),init_classroomDB2=__esm({"src/impl/couch/classroomDB.ts"(){"use strict";init_factory(),init_logger(),init_pouchdb_setup(),init_couch(),init_courseDB(),classroomLookupDBTitle=`classdb-lookup`,CLASSROOM_CONFIG=`ClassroomConfig`,ClassroomDBBase=class{constructor(){_defineProperty$2(this,`_id`,void 0),_defineProperty$2(this,`_db`,void 0),_defineProperty$2(this,`_cfg`,void 0),_defineProperty$2(this,`_initComplete`,!1),_defineProperty$2(this,`_content_prefix`,`content`)}get _content_searchkeys(){return getStartAndEndKeys(this._content_prefix)}async getAssignedContent(){return logger.info(`Getting assigned content...`),(await this._db.allDocs({startkey:this._content_prefix,endkey:this._content_prefix+`￰`,include_docs:!0})).rows.map(t=>t.doc)}getContentId(t){return t.type===`tag`?`${this._content_prefix}-${t.courseID}-${t.tagID}`:`${this._content_prefix}-${t.courseID}`}get ready(){return this._initComplete}getConfig(){return this._cfg}},StudentClassroomDB=class _StudentClassroomDB extends ClassroomDBBase{constructor(t,c){super(),_defineProperty$2(this,`userMessages`,void 0),_defineProperty$2(this,`_user`,void 0),this._id=t,this._user=c}async init(){let t=`classdb-student-${this._id}`;this._db=new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+t,createPouchDBConfig());try{this._cfg=await this._db.get(CLASSROOM_CONFIG),this.userMessages=this._db.changes({since:`now`,live:!0,include_docs:!0}),this._initComplete=!0;return}catch(t){throw Error(`Error in StudentClassroomDB constructor: ${JSON.stringify(t)}`)}}static async factory(t,c){let u=new _StudentClassroomDB(t,c);return await u.init(),u}setChangeFcn(t){this.userMessages.on(`change`,t)}async getWeightedCards(t){let c=[],u=(await this._user.getPendingReviews()).filter(t=>t.scheduledFor===`classroom`&&t.schedulingAgentId===this._id);for(let t of u)c.push({cardId:t.cardId,courseId:t.courseId,score:1,reviewID:t._id,provenance:[{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`generated`,score:1,reason:`Classroom scheduled review`}]});let d=await this._user.getActiveCards(),m=new Set(d.map(t=>t.cardID)),g=hooks.utc(),b=(await this.getAssignedContent()).filter(t=>g.isAfter(hooks.utc(t.activeOn,REVIEW_TIME_FORMAT)));logger.info(`[StudentClassroomDB] Due content: ${JSON.stringify(b)}`);for(let u of b)if(u.type===`course`){let{cards:d}=await new CourseDB(u.courseID,async()=>this._user).getWeightedCards(t);for(let t of d)m.has(t.cardId)||c.push({...t,provenance:[...t.provenance,{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`passed`,score:t.score,reason:`Assigned via classroom from course ${u.courseID}`}]})}else if(u.type===`tag`){let t=await getTag(u.courseID,u.tagID);for(let d of t.taggedCards)m.has(d)||c.push({cardId:d,courseId:u.courseID,score:1,provenance:[{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`generated`,score:1,reason:`Classroom assigned tag: ${u.tagID}, new card`}]})}else u.type===`card`&&(m.has(u.cardID)||c.push({cardId:u.cardID,courseId:u.courseID,score:1,provenance:[{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`generated`,score:1,reason:`Classroom assigned card, new card`}]}));return logger.info(`[StudentClassroomDB] New cards from classroom ${this._cfg.name}: ${c.length} total (reviews + new)`),{cards:c.sort((t,c)=>c.score-t.score).slice(0,t)}}},TeacherClassroomDB=class _TeacherClassroomDB extends ClassroomDBBase{constructor(t){super(),_defineProperty$2(this,`_stuDb`,void 0),this._id=t}async init(){let t=`classdb-teacher-${this._id}`,c=`classdb-student-${this._id}`;this._db=new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+t,createPouchDBConfig()),this._stuDb=new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+c,createPouchDBConfig());try{return this._db.get(CLASSROOM_CONFIG).then(t=>{this._cfg=t,this._initComplete=!0}).then(()=>{})}catch(t){throw Error(`Error in TeacherClassroomDB constructor: ${JSON.stringify(t)}`)}}static async factory(t){let c=new _TeacherClassroomDB(t);return await c.init(),c}async removeContent(t){let c=this.getContentId(t);try{let t=await this._db.get(c);await this._db.remove(t),this._db.replicate.to(this._stuDb,{doc_ids:[c]})}catch(t){logger.error(`Failed to remove content:`,c,t)}}async assignContent(t){let c,u=this.getContentId(t);return c=t.type===`tag`?await this._db.put({courseID:t.courseID,tagID:t.tagID,type:`tag`,_id:u,assignedBy:t.assignedBy,assignedOn:hooks.utc(),activeOn:t.activeOn||hooks.utc()}):await this._db.put({courseID:t.courseID,type:`course`,_id:u,assignedBy:t.assignedBy,assignedOn:hooks.utc(),activeOn:t.activeOn||hooks.utc()}),c.ok?(this._db.replicate.to(this._stuDb,{doc_ids:[u]}),!0):!1}},ClassroomLookupDB=()=>new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+classroomLookupDBTitle,{skip_setup:!0})}}),init_adminDB2=__esm({"src/impl/couch/adminDB.ts"(){"use strict";init_pouchdb_setup(),init_factory(),init_couch(),init_classroomDB2(),init_courseLookupDB(),init_logger(),AdminDB=class{constructor(){_defineProperty$2(this,`usersDB`,void 0),this.usersDB=new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+`_users`,createPouchDBConfig())}async getUsers(){return(await this.usersDB.allDocs({include_docs:!0,...getStartAndEndKeys(`org.couchdb.user:`)})).rows.map(t=>t.doc)}async getCourses(){let t=await CourseLookup.allCourseWare();return await Promise.all(t.map(t=>getCredentialledCourseConfig(t._id)))}async removeCourse(t){let c=await CourseLookup.delete(t),u=await getCredentialledCourseConfig(t);u.deleted=!0;let d=await updateCredentialledCourseConfig(t,u);return{ok:c.ok&&d.ok,id:c.id,rev:c.rev}}async getClassrooms(){let t=(await ClassroomLookupDB().allDocs({include_docs:!0})).rows.map(t=>t.doc.uuid);logger.debug(t.join(`, `));let c=[];for(let u=0;u<t.length;u++)try{let d=await TeacherClassroomDB.factory(t[u]);c.push(d)}catch(c){let d=c;d.error&&d.error===`not_found`&&logger.warn(`db ${t[u]} not found`)}return c.map(t=>({...t.getConfig(),_id:t._id}))}}}}),CourseSyncService_exports={},__export(CourseSyncService_exports,{CourseSyncService:()=>CourseSyncService}),init_CourseSyncService=__esm({"src/impl/couch/CourseSyncService.ts"(){"use strict";var t;init_pouchdb_setup(),init_couch(),init_logger(),DEFAULT_REPLICATION={batchSize:1e3,batchesLimit:5},CourseSyncService=(t=class _CourseSyncService{constructor(){_defineProperty$2(this,`entries`,new Map),_defineProperty$2(this,`replicationOptions`,DEFAULT_REPLICATION)}static getInstance(){return _CourseSyncService.instance||(_CourseSyncService.instance=new _CourseSyncService),_CourseSyncService.instance}configure(t){t.replication&&(this.replicationOptions={...DEFAULT_REPLICATION,...t.replication},logger.info(`[CourseSyncService] Replication configured: batch_size=${this.replicationOptions.batchSize}, batches_limit=${this.replicationOptions.batchesLimit}`))}static resetInstance(){if(_CourseSyncService.instance){for(let[,t]of _CourseSyncService.instance.entries)t.localDB&&t.localDB.close().catch(()=>{});_CourseSyncService.instance.entries.clear()}_CourseSyncService.instance=null}async ensureSynced(t,c){let u=this.entries.get(t);if(u?.status.state===`ready`&&u.localDB){if(!await this.isLocalEpochStale(t,u.localDB))return;logger.info(`[CourseSyncService] Remote DB epoch changed for course ${t} \u2014 destroying stale local replica`);try{await u.localDB.destroy()}catch{}u.localDB=null,u.readyPromise=null}if(u?.status.state===`disabled`)return;if(u?.readyPromise)return u.readyPromise;let d={localDB:null,status:{state:`not-started`},readyPromise:null};return this.entries.set(t,d),d.readyPromise=this.performSync(t,d,c),d.readyPromise}getLocalDB(t){let c=this.entries.get(t);return c?.status.state===`ready`&&c.localDB?c.localDB:null}isReady(t){return this.entries.get(t)?.status.state===`ready`}getStatus(t){return this.entries.get(t)?.status??{state:`not-started`}}async performSync(t,c,u){try{if(!u&&(c.status={state:`checking-config`},!await this.checkLocalSyncEnabled(t))){c.status={state:`disabled`},c.readyPromise=null,logger.debug(`[CourseSyncService] Local sync disabled for course ${t}`);return}c.status={state:`syncing`};let d=this.localDBName(t),m=new pouchdb_setup_default(d);await this.isLocalEpochStale(t,m)&&(logger.info(`[CourseSyncService] Stale local DB detected for course ${t} \u2014 destroying before sync`),await m.destroy(),m=new pouchdb_setup_default(d)),c.localDB=m;let g=this.getRemoteDB(t),b=Date.now();logger.info(`[CourseSyncService] Starting one-shot replication for course ${t} (batch_size=${this.replicationOptions.batchSize}, batches_limit=${this.replicationOptions.batchesLimit})`);let S=await this.replicate(g,m),C=Date.now()-b;logger.info(`[CourseSyncService] Replication complete for course ${t}: ${S.docs_written} docs in ${C}ms`),c.status={state:`warming-views`};let w=Date.now();await this.warmViewIndices(m);let T=Date.now()-w;logger.info(`[CourseSyncService] View indices warmed for course ${t} in ${T}ms`),c.status={state:`ready`,docsReplicated:S.docs_written,syncTimeMs:C,viewWarmTimeMs:T}}catch(u){let d=u instanceof Error?u.message:String(u);if(logger.error(`[CourseSyncService] Sync failed for course ${t}: ${d}`),c.status={state:`error`,error:d},c.readyPromise=null,c.localDB){try{await c.localDB.destroy()}catch{}c.localDB=null}}}async checkLocalSyncEnabled(t){try{return(await this.getRemoteDB(t).get(`CourseConfig`)).localSync?.enabled===!0}catch(c){return logger.warn(`[CourseSyncService] Could not read CourseConfig for ${t}, assuming local sync disabled: ${c}`),!1}}replicate(t,c){return new Promise((u,d)=>{pouchdb_setup_default.replicate(t,c,{batch_size:this.replicationOptions.batchSize,batches_limit:this.replicationOptions.batchesLimit}).on(`complete`,t=>{u(t)}).on(`error`,t=>{d(t)})})}async warmViewIndices(t){for(let c of[`elo`,`getTags`])try{await t.query(c,{limit:1}),logger.debug(`[CourseSyncService] Warmed view index: ${c}`)}catch(t){logger.debug(`[CourseSyncService] Could not warm view ${c}: ${t}`)}}async isLocalEpochStale(t,c){try{let u=await this.getRemoteDB(t).get(`db-epoch`),d=null;try{d=await c.get(`db-epoch`)}catch{return!0}return u.epoch!==d.epoch}catch{return!1}}getRemoteDB(t){return getCourseDB2(t)}localDBName(t){return`coursedb-local-${t}`}},_defineProperty$2(t,`instance`,null),t)}}),init_auth=__esm({"src/impl/couch/auth.ts"(){"use strict";init_factory(),init_logger()}}),CouchDBSyncStrategy_exports={},__export(CouchDBSyncStrategy_exports,{CouchDBSyncStrategy:()=>CouchDBSyncStrategy}),init_CouchDBSyncStrategy=__esm({"src/impl/couch/CouchDBSyncStrategy.ts"(){"use strict";init_factory(),init_types_legacy(),init_logger(),init_common(),init_pouchdb_setup(),init_couch(),init_auth(),log2=t=>{logger.info(t)},CouchDBSyncStrategy=class{constructor(){_defineProperty$2(this,`syncHandle`,void 0),_defineProperty$2(this,`hydrationHandle`,void 0)}setupRemoteDB(t){return t===GuestUsername||t.startsWith(GuestUsername)?getLocalUserDB(t):this.getUserDB(t)}getWriteDB(t){return t===GuestUsername||t.startsWith(GuestUsername)?getLocalUserDB(t):this.getUserDB(t)}async hydrate(t,c){let u=(await t.info()).doc_count===0,d=pouchdb_setup_default.replicate(c,t,u?{selector:{_deleted:{$exists:!1}}}:{});this.hydrationHandle=d;try{let t=await d;return{docsWritten:t.docs_written,lastSeq:u?t.last_seq:void 0}}finally{this.hydrationHandle=void 0}}startSync(t,c,u){t.name!==c.name&&(this.syncHandle=pouchdb_setup_default.sync(t,c,{live:!0,retry:!0,...u===void 0?{}:{pull:{since:u}}}))}stopSync(){if(this.hydrationHandle){try{this.hydrationHandle.cancel()}catch(t){logger.warn(`Failed to cancel hydration pull (continuing anyway): ${t}`)}this.hydrationHandle=void 0}if(this.syncHandle){try{this.syncHandle.cancel()}catch(t){logger.warn(`Failed to cancel user sync (continuing anyway): ${t}`)}this.syncHandle=void 0}}canCreateAccount(){return!0}canAuthenticate(){return!0}async createAccount(t,c){let u=await this.getCurrentUsername(),d=u.startsWith(GuestUsername);d&&logger.info(`Creating account for funnel user ${u} -> ${t}`);try{let m=await this.getRemoteCouchRootDB().signUp(t,c);if(m.ok){log2(`CREATEACCOUNT: Successfully created account for ${t}`);try{let t=await this.getRemoteCouchRootDB().logOut();log2(`CREATEACCOUNT: logged out: ${t.ok}`)}catch{}let m=await this.getRemoteCouchRootDB().logIn(t,c);if(log2(`CREATEACCOUNT: logged in as new user: ${m.ok}`),m.ok){if(d){logger.info(`Migrating data from funnel account ${u} to ${t}`);let c=await this.migrateFunnelData(u,t);c.success||logger.warn(`Migration failed: ${c.error}`)}return{status:Status.ok,error:void 0}}else return{status:Status.error,error:`Failed to log in after account creation`}}else return logger.warn(`Signup not OK: ${JSON.stringify(m)}`),{status:Status.error,error:`Account creation failed`}}catch(t){return t.reason===`Document update conflict.`?{status:Status.error,error:`This username is taken!`}:(logger.error(`Error on signup: ${JSON.stringify(t)}`),{status:Status.error,error:t.message||`Unknown error during account creation`})}}async authenticate(t,c){try{return(await this.getRemoteCouchRootDB().logIn(t,c)).ok?(log2(`Successfully logged in as ${t}`),{ok:!0}):(log2(`Login failed for ${t}`),{ok:!1,error:`Invalid username or password`})}catch(c){return logger.error(`Authentication error for ${t}:`,c),{ok:!1,error:c.message||`Authentication failed`}}}async adoptSession(t){let c;try{c=await getLoggedInUsername()}catch{return{ok:!1,error:`No session to adopt`}}if(t?.startsWith(GuestUsername)){logger.info(`Migrating data from funnel account ${t} to ${c}`);let u=await this.migrateFunnelData(t,c);u.success||logger.warn(`Migration failed: ${u.error}`)}return{ok:!0,username:c}}async logout(){try{let t=await this.getRemoteCouchRootDB().logOut();return{ok:t.ok,error:t.ok?void 0:`Logout failed`}}catch(t){return logger.error(`Logout error:`,t),{ok:!1,error:t.message||`Logout failed`}}}async getCurrentUsername(){logger.log(`[funnel] CouchDBSyncStrategy.getCurrentUsername() called`);try{let t=await getLoggedInUsername();return logger.log(`[funnel] getLoggedInUsername() returned:`,t),t}catch(t){logger.log(`[funnel] getLoggedInUsername() failed, calling accomodateGuest()`),logger.log(`[funnel] Error was:`,t);let c=accomodateGuest();return logger.log(`[funnel] accomodateGuest() returned:`,c),c.username}}async migrateFunnelData(t,c){try{logger.info(`Starting data migration from ${t} to ${c}`);let u=getLocalUserDB(t),d=getLocalUserDB(c),m=await u.allDocs({include_docs:!0});logger.info(`Found ${m.rows.length} documents in funnel account`);let g=m.rows.filter(t=>!t.id.startsWith(`_design/`)).map(t=>({...t.doc,_rev:void 0}));g.length>0?(await d.bulkDocs(g),logger.info(`Successfully migrated ${g.length} documents from ${t} to ${c}`)):logger.info(`No documents to migrate from funnel account`);try{await u.destroy(),logger.info(`Destroyed consumed guest DB for ${t}`)}catch(c){logger.warn(`Failed to destroy consumed guest DB for ${t} (non-fatal): ${c instanceof Error?c.message:String(c)}`)}return{success:!0}}catch(t){return logger.error(`Migration failed:`,t),{success:!1,error:t instanceof Error?t.message:`Unknown error`}}}getRemoteCouchRootDB(){let t=ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+`skuilder`;try{return new pouchdb_setup_default(t,{skip_setup:!0})}catch(t){throw logger.error(`Failed to initialize remote CouchDB connection:`,t),Error(`Failed to initialize CouchDB: ${JSON.stringify(t)}`)}}getUserDB(t){let c=!1,u=`userdb-${hexEncode(t)}`;return log2(`Fetching user database: ${u} (${t})`),new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+u,createPouchDBConfig())}}}}),init_couch=__esm({"src/impl/couch/index.ts"(){"use strict";init_factory(),init_types_legacy(),init_logger(),init_pouchdb_setup(),init_contentSource(),init_adminDB2(),init_classroomDB2(),init_courseAPI(),init_courseDB(),init_CourseSyncService(),init_CouchDBSyncStrategy(),isBrowser=typeof window<`u`,isBrowser&&(window.process=import_browser.default),GUEST_LOCAL_DB=`userdb-${GuestUsername}`,new pouchdb_setup_default(GUEST_LOCAL_DB),pouchDBincludeCredentialsConfig={fetch(t,c){return c.credentials=`include`,pouchdb_setup_default.fetch(t,c)}},REVIEW_TIME_FORMAT=`YYYY-MM-DD--kk:mm:ss-SSS`}}),init_SpacedRepetition=__esm({"src/study/SpacedRepetition.ts"(){"use strict";init_util(),init_logger(),duration=hooks.duration}}),init_SrsService=__esm({"src/study/services/SrsService.ts"(){"use strict";init_couch(),init_SpacedRepetition(),init_logger(),SrsService=class{constructor(t){_defineProperty$2(this,`user`,void 0),this.user=t}removeReview(t){logger.info(`[SrsService] Removing orphaned scheduled review: ${t}`),this.user.removeScheduledCardReview(t)}async scheduleReview(t,c){let u=newInterval(this.user,t),d=hooks.utc().add(u,`seconds`);isReview(c)&&(logger.info(`[SrsService] Removing previously scheduled review for: ${c.cardID}`),this.user.removeScheduledCardReview(c.reviewID)),this.user.scheduleCardReview({user:this.user.getUsername(),course_id:t.courseID,card_id:t.cardID,time:d,scheduledFor:c.contentSourceType,schedulingAgentId:c.contentSourceID})}}}}),init_tagRecent=__esm({"src/study/services/tagRecent.ts"(){"use strict";}}),init_EloService=__esm({"src/study/services/EloService.ts"(){"use strict";init_logger(),init_tagRecent(),EloService=class{constructor(t,c){_defineProperty$2(this,`dataLayer`,void 0),_defineProperty$2(this,`user`,void 0),this.dataLayer=t,this.user=c}async updateUserAndCardElo(t,c,u,d,m,g){g&&logger.warn(`k value interpretation not currently implemented`);let b=this.dataLayer.getCourseDB(m.card.course_id),S=d.courses.find(t=>t.courseID===c);if(!S)return logger.error(`[EloService] No registration for course ${c} on user's registration doc \u2014 skipping ELO update for card ${u}. (Is the user registered for this course?)`),null;let C=toCourseElo(S.elo),w=(await b.getCardEloData([m.card.card_id]))[0];if(w&&C){let d=C.global.score,m=w.global.score,g=Object.keys(w.tags),T={};for(let t of g)T[t]=C.tags[t]?.score??C.global.score;let E=adjustCourseScores(C,w,t);S.elo=E.userElo;let D={};for(let c of g){let u=isCountOnlyTag(c);D[c]={before:T[c],after:u?T[c]:E.userElo.tags[c].score,score:u?null:t}}let O={cardId:u,at:new Date().toISOString(),userScore:t,global:{before:d,after:E.userElo.global.score},card:{before:m,after:E.cardElo.global.score},...g.length?{tags:D}:{}},xr=await Promise.allSettled([this.user.updateUserElo(c,E.userElo),b.updateCardElo(u,E.cardElo)]),Sr=xr[0].status===`fulfilled`,Cr=xr[1].status===`fulfilled`;if(Sr&&Cr){let t=xr[0].value,c=xr[1].value;t.ok&&c&&c.ok&&logger.info(`[EloService] Updated ELOS:
366
- User: ${JSON.stringify(E.userElo)})
367
- Card: ${JSON.stringify(E.cardElo)})
366
+ ${t.stack}`:JSON.stringify(t);throw logger.error(`[courseDB] Error creating navigator: ${c}`),t}}setEphemeralHints(t){this._pendingHints=t}notePresented(t){t.status===`new`&&this._getCurrentUser().then(t=>this._getCachedNavigator(t)).then(({navigator:c})=>c.notePresented?.(t)).catch(t=>logger.warn(`[courseDB] Could not note a presentation: ${t}`))}async getWeightedCards(t){let c=await this._getCurrentUser();try{let{navigator:u}=await this._getCachedNavigator(c);return this._pendingHints&&(u.setEphemeralHints(this._pendingHints),this._pendingHints=null),await u.getWeightedCards(t)}catch(t){throw logger.error(`[courseDB] Error getting weighted cards: ${t}`),t}}async _getCachedNavigator(t){let c=t.getUsername(),u=Date.now();if(this._cachedNavigator&&this._cachedNavigator.userId===c&&u-this._cachedNavigator.builtAt<this._navigatorTtlMs)return{navigator:this._cachedNavigator.navigator,cacheStatus:`hit`};let d=await this.createNavigator(t);return this._cachedNavigator={navigator:d,userId:c,builtAt:u},{navigator:d,cacheStatus:`miss`}}invalidateNavigatorCache(){this._cachedNavigator=null}async getCardsCenteredAtELO(t={limit:99,elo:`user`},c){let u;if(t.elo===`user`){let t=await this._getCurrentUser();u=-1;try{u=EloToNumber((await t.getCourseRegistrationsDoc()).courses.find(t=>t.courseID===this.id).elo)}catch{u=1e3}}else if(t.elo===`random`){let t=await GET_CACHED(`elo-bounds-${this.id}`,()=>this.getELOBounds());u=Math.round(t.low+Math.random()*(t.high-t.low))}else u=t.elo;let d=Math.max(2e3,t.limit*4),m=Date.now(),g=`hit`;if(!this._eloPoolCache||m-this._eloPoolCache.fetchedAt>this._eloPoolTtlMs){let t=await this.getCardsByELO(u,d);t.length>0&&(this._eloPoolCache={rows:t,fetchedAt:m}),g=`miss`}let rankAgainstCurrentElo=()=>{let t=this._eloPoolCache?.rows??[];return(c?t.filter(t=>c(t)):t).map(t=>({...t})).sort((t,c)=>Math.abs((t.elo??u)-u)-Math.abs((c.elo??u)-u))},b=rankAgainstCurrentElo();if(b.length<t.limit&&(g===`hit`||!this._eloPoolCache)){let t=await this.getCardsByELO(u,d);t.length>0&&(this._eloPoolCache={rows:t,fetchedAt:m}),b=rankAgainstCurrentElo(),g=`refresh`}let S=[];for(;S.length<t.limit&&b.length>0;){let t=randIntWeightedTowardZero(b.length),c=b.splice(t,1)[0];S.push(c)}return S.map(t=>({courseID:this.id,cardID:t.cardID,contentSourceType:`course`,contentSourceID:this.id,elo:t.elo,status:`new`}))}async searchCards(t){logger.log(`[CourseDB ${this.id}] Searching for: "${t}"`);let c;try{c=await this.db.find({selector:{docType:`DISPLAYABLE_DATA`,"data.0.data":{$regex:`.*${t}.*`}}}),logger.log(`[CourseDB ${this.id}] Regex search on data[0].data successful`)}catch(u){logger.log(`[CourseDB ${this.id}] Regex search failed, falling back to manual search:`,u);let d=await this.db.find({selector:{docType:`DISPLAYABLE_DATA`}});logger.log(`[CourseDB ${this.id}] Retrieved ${d.docs.length} documents for manual filtering`),c={docs:d.docs.filter(c=>{let u=JSON.stringify(c).toLowerCase().includes(t.toLowerCase());return u&&logger.log(`[CourseDB ${this.id}] Manual match found in document: ${c._id}`),u})}}if(logger.log(`[CourseDB ${this.id}] Found ${c.docs.length} displayable data documents`),c.docs.length===0){let t=await this.db.find({selector:{docType:`DISPLAYABLE_DATA`},limit:5});logger.log(`[CourseDB ${this.id}] Sample displayable data:`,t.docs.map(t=>({id:t._id,docType:t.docType,dataStructure:t.data?Object.keys(t.data):`no data field`,dataContent:t.data,fullDoc:t})))}let u=[];for(let t of c.docs){let c=await this.db.find({selector:{docType:`CARD`,id_displayable_data:{$in:[t._id]}}});logger.log(`[CourseDB ${this.id}] Displayable data ${t._id} linked to ${c.docs.length} cards`),u.push(...c.docs)}return logger.log(`[CourseDB ${this.id}] Total cards found: ${u.length}`),u}async find(t){return this.db.find(t)}}}}),init_classroomDB2=__esm({"src/impl/couch/classroomDB.ts"(){"use strict";init_factory(),init_logger(),init_pouchdb_setup(),init_couch(),init_courseDB(),classroomLookupDBTitle=`classdb-lookup`,CLASSROOM_CONFIG=`ClassroomConfig`,ClassroomDBBase=class{constructor(){_defineProperty$2(this,`_id`,void 0),_defineProperty$2(this,`_db`,void 0),_defineProperty$2(this,`_cfg`,void 0),_defineProperty$2(this,`_initComplete`,!1),_defineProperty$2(this,`_content_prefix`,`content`)}get _content_searchkeys(){return getStartAndEndKeys(this._content_prefix)}async getAssignedContent(){return logger.info(`Getting assigned content...`),(await this._db.allDocs({startkey:this._content_prefix,endkey:this._content_prefix+`￰`,include_docs:!0})).rows.map(t=>t.doc)}getContentId(t){return t.type===`tag`?`${this._content_prefix}-${t.courseID}-${t.tagID}`:`${this._content_prefix}-${t.courseID}`}get ready(){return this._initComplete}getConfig(){return this._cfg}},StudentClassroomDB=class _StudentClassroomDB extends ClassroomDBBase{constructor(t,c){super(),_defineProperty$2(this,`userMessages`,void 0),_defineProperty$2(this,`_user`,void 0),this._id=t,this._user=c}async init(){let t=`classdb-student-${this._id}`;this._db=new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+t,createPouchDBConfig());try{this._cfg=await this._db.get(CLASSROOM_CONFIG),this.userMessages=this._db.changes({since:`now`,live:!0,include_docs:!0}),this._initComplete=!0;return}catch(t){throw Error(`Error in StudentClassroomDB constructor: ${JSON.stringify(t)}`)}}static async factory(t,c){let u=new _StudentClassroomDB(t,c);return await u.init(),u}setChangeFcn(t){this.userMessages.on(`change`,t)}async getWeightedCards(t){let c=[],u=(await this._user.getPendingReviews()).filter(t=>t.scheduledFor===`classroom`&&t.schedulingAgentId===this._id);for(let t of u)c.push({cardId:t.cardId,courseId:t.courseId,score:1,reviewID:t._id,provenance:[{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`generated`,score:1,reason:`Classroom scheduled review`}]});let d=await this._user.getActiveCards(),m=new Set(d.map(t=>t.cardID)),g=hooks.utc(),b=(await this.getAssignedContent()).filter(t=>g.isAfter(hooks.utc(t.activeOn,REVIEW_TIME_FORMAT)));logger.info(`[StudentClassroomDB] Due content: ${JSON.stringify(b)}`);for(let u of b)if(u.type===`course`){let{cards:d}=await new CourseDB(u.courseID,async()=>this._user).getWeightedCards(t);for(let t of d)m.has(t.cardId)||c.push({...t,provenance:[...t.provenance,{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`passed`,score:t.score,reason:`Assigned via classroom from course ${u.courseID}`}]})}else if(u.type===`tag`){let t=await getTag(u.courseID,u.tagID);for(let d of t.taggedCards)m.has(d)||c.push({cardId:d,courseId:u.courseID,score:1,provenance:[{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`generated`,score:1,reason:`Classroom assigned tag: ${u.tagID}, new card`}]})}else u.type===`card`&&(m.has(u.cardID)||c.push({cardId:u.cardID,courseId:u.courseID,score:1,provenance:[{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`generated`,score:1,reason:`Classroom assigned card, new card`}]}));return logger.info(`[StudentClassroomDB] New cards from classroom ${this._cfg.name}: ${c.length} total (reviews + new)`),{cards:c.sort((t,c)=>c.score-t.score).slice(0,t)}}},TeacherClassroomDB=class _TeacherClassroomDB extends ClassroomDBBase{constructor(t){super(),_defineProperty$2(this,`_stuDb`,void 0),this._id=t}async init(){let t=`classdb-teacher-${this._id}`,c=`classdb-student-${this._id}`;this._db=new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+t,createPouchDBConfig()),this._stuDb=new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+c,createPouchDBConfig());try{return this._db.get(CLASSROOM_CONFIG).then(t=>{this._cfg=t,this._initComplete=!0}).then(()=>{})}catch(t){throw Error(`Error in TeacherClassroomDB constructor: ${JSON.stringify(t)}`)}}static async factory(t){let c=new _TeacherClassroomDB(t);return await c.init(),c}async removeContent(t){let c=this.getContentId(t);try{let t=await this._db.get(c);await this._db.remove(t),this._db.replicate.to(this._stuDb,{doc_ids:[c]})}catch(t){logger.error(`Failed to remove content:`,c,t)}}async assignContent(t){let c,u=this.getContentId(t);return c=t.type===`tag`?await this._db.put({courseID:t.courseID,tagID:t.tagID,type:`tag`,_id:u,assignedBy:t.assignedBy,assignedOn:hooks.utc(),activeOn:t.activeOn||hooks.utc()}):await this._db.put({courseID:t.courseID,type:`course`,_id:u,assignedBy:t.assignedBy,assignedOn:hooks.utc(),activeOn:t.activeOn||hooks.utc()}),c.ok?(this._db.replicate.to(this._stuDb,{doc_ids:[u]}),!0):!1}},ClassroomLookupDB=()=>new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+classroomLookupDBTitle,{skip_setup:!0})}}),init_adminDB2=__esm({"src/impl/couch/adminDB.ts"(){"use strict";init_pouchdb_setup(),init_factory(),init_couch(),init_classroomDB2(),init_courseLookupDB(),init_logger(),AdminDB=class{constructor(){_defineProperty$2(this,`usersDB`,void 0),this.usersDB=new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+`_users`,createPouchDBConfig())}async getUsers(){return(await this.usersDB.allDocs({include_docs:!0,...getStartAndEndKeys(`org.couchdb.user:`)})).rows.map(t=>t.doc)}async getCourses(){let t=await CourseLookup.allCourseWare();return await Promise.all(t.map(t=>getCredentialledCourseConfig(t._id)))}async removeCourse(t){let c=await CourseLookup.delete(t),u=await getCredentialledCourseConfig(t);u.deleted=!0;let d=await updateCredentialledCourseConfig(t,u);return{ok:c.ok&&d.ok,id:c.id,rev:c.rev}}async getClassrooms(){let t=(await ClassroomLookupDB().allDocs({include_docs:!0})).rows.map(t=>t.doc.uuid);logger.debug(t.join(`, `));let c=[];for(let u=0;u<t.length;u++)try{let d=await TeacherClassroomDB.factory(t[u]);c.push(d)}catch(c){let d=c;d.error&&d.error===`not_found`&&logger.warn(`db ${t[u]} not found`)}return c.map(t=>({...t.getConfig(),_id:t._id}))}}}}),CourseSyncService_exports={},__export(CourseSyncService_exports,{CourseSyncService:()=>CourseSyncService}),init_CourseSyncService=__esm({"src/impl/couch/CourseSyncService.ts"(){"use strict";var t;init_pouchdb_setup(),init_couch(),init_logger(),DEFAULT_REPLICATION={batchSize:1e3,batchesLimit:5},CourseSyncService=(t=class _CourseSyncService{constructor(){_defineProperty$2(this,`entries`,new Map),_defineProperty$2(this,`replicationOptions`,DEFAULT_REPLICATION)}static getInstance(){return _CourseSyncService.instance||(_CourseSyncService.instance=new _CourseSyncService),_CourseSyncService.instance}configure(t){t.replication&&(this.replicationOptions={...DEFAULT_REPLICATION,...t.replication},logger.info(`[CourseSyncService] Replication configured: batch_size=${this.replicationOptions.batchSize}, batches_limit=${this.replicationOptions.batchesLimit}`))}static resetInstance(){if(_CourseSyncService.instance){for(let[,t]of _CourseSyncService.instance.entries)t.localDB&&t.localDB.close().catch(()=>{});_CourseSyncService.instance.entries.clear()}_CourseSyncService.instance=null}async ensureSynced(t,c){let u=this.entries.get(t);if(u?.status.state===`ready`&&u.localDB){if(!await this.isLocalEpochStale(t,u.localDB))return;logger.info(`[CourseSyncService] Remote DB epoch changed for course ${t} \u2014 destroying stale local replica`);try{await u.localDB.destroy()}catch{}u.localDB=null,u.readyPromise=null}if(u?.status.state===`disabled`)return;if(u?.readyPromise)return u.readyPromise;let d={localDB:null,status:{state:`not-started`},readyPromise:null};return this.entries.set(t,d),d.readyPromise=this.performSync(t,d,c),d.readyPromise}getLocalDB(t){let c=this.entries.get(t);return c?.status.state===`ready`&&c.localDB?c.localDB:null}isReady(t){return this.entries.get(t)?.status.state===`ready`}getStatus(t){return this.entries.get(t)?.status??{state:`not-started`}}async performSync(t,c,u){try{if(!u&&(c.status={state:`checking-config`},!await this.checkLocalSyncEnabled(t))){c.status={state:`disabled`},c.readyPromise=null,logger.debug(`[CourseSyncService] Local sync disabled for course ${t}`);return}c.status={state:`syncing`};let d=this.localDBName(t),m=new pouchdb_setup_default(d);await this.isLocalEpochStale(t,m)&&(logger.info(`[CourseSyncService] Stale local DB detected for course ${t} \u2014 destroying before sync`),await m.destroy(),m=new pouchdb_setup_default(d)),c.localDB=m;let g=this.getRemoteDB(t),b=Date.now();logger.info(`[CourseSyncService] Starting one-shot replication for course ${t} (batch_size=${this.replicationOptions.batchSize}, batches_limit=${this.replicationOptions.batchesLimit})`);let S=await this.replicate(g,m),C=Date.now()-b;logger.info(`[CourseSyncService] Replication complete for course ${t}: ${S.docs_written} docs in ${C}ms`),c.status={state:`warming-views`};let w=Date.now();await this.warmViewIndices(m);let T=Date.now()-w;logger.info(`[CourseSyncService] View indices warmed for course ${t} in ${T}ms`),c.status={state:`ready`,docsReplicated:S.docs_written,syncTimeMs:C,viewWarmTimeMs:T}}catch(u){let d=u instanceof Error?u.message:String(u);if(logger.error(`[CourseSyncService] Sync failed for course ${t}: ${d}`),c.status={state:`error`,error:d},c.readyPromise=null,c.localDB){try{await c.localDB.destroy()}catch{}c.localDB=null}}}async checkLocalSyncEnabled(t){try{return(await this.getRemoteDB(t).get(`CourseConfig`)).localSync?.enabled===!0}catch(c){return logger.warn(`[CourseSyncService] Could not read CourseConfig for ${t}, assuming local sync disabled: ${c}`),!1}}replicate(t,c){return new Promise((u,d)=>{pouchdb_setup_default.replicate(t,c,{batch_size:this.replicationOptions.batchSize,batches_limit:this.replicationOptions.batchesLimit}).on(`complete`,t=>{u(t)}).on(`error`,t=>{d(t)})})}async warmViewIndices(t){for(let c of[`elo`,`getTags`])try{await t.query(c,{limit:1}),logger.debug(`[CourseSyncService] Warmed view index: ${c}`)}catch(t){logger.debug(`[CourseSyncService] Could not warm view ${c}: ${t}`)}}async isLocalEpochStale(t,c){try{let u=await this.getRemoteDB(t).get(`db-epoch`),d=null;try{d=await c.get(`db-epoch`)}catch{return!0}return u.epoch!==d.epoch}catch{return!1}}getRemoteDB(t){return getCourseDB2(t)}localDBName(t){return`coursedb-local-${t}`}},_defineProperty$2(t,`instance`,null),t)}}),init_auth=__esm({"src/impl/couch/auth.ts"(){"use strict";init_factory(),init_logger()}}),CouchDBSyncStrategy_exports={},__export(CouchDBSyncStrategy_exports,{CouchDBSyncStrategy:()=>CouchDBSyncStrategy}),init_CouchDBSyncStrategy=__esm({"src/impl/couch/CouchDBSyncStrategy.ts"(){"use strict";init_factory(),init_types_legacy(),init_logger(),init_common(),init_pouchdb_setup(),init_couch(),init_auth(),log2=t=>{logger.info(t)},CouchDBSyncStrategy=class{constructor(){_defineProperty$2(this,`syncHandle`,void 0),_defineProperty$2(this,`hydrationHandle`,void 0)}setupRemoteDB(t){return t===GuestUsername||t.startsWith(GuestUsername)?getLocalUserDB(t):this.getUserDB(t)}getWriteDB(t){return t===GuestUsername||t.startsWith(GuestUsername)?getLocalUserDB(t):this.getUserDB(t)}async hydrate(t,c){let u=(await t.info()).doc_count===0,d=pouchdb_setup_default.replicate(c,t,u?{selector:{_deleted:{$exists:!1}}}:{});this.hydrationHandle=d;try{let t=await d;return{docsWritten:t.docs_written,lastSeq:u?t.last_seq:void 0}}finally{this.hydrationHandle=void 0}}startSync(t,c,u){t.name!==c.name&&(this.syncHandle=pouchdb_setup_default.sync(t,c,{live:!0,retry:!0,...u===void 0?{}:{pull:{since:u}}}))}stopSync(){if(this.hydrationHandle){try{this.hydrationHandle.cancel()}catch(t){logger.warn(`Failed to cancel hydration pull (continuing anyway): ${t}`)}this.hydrationHandle=void 0}if(this.syncHandle){try{this.syncHandle.cancel()}catch(t){logger.warn(`Failed to cancel user sync (continuing anyway): ${t}`)}this.syncHandle=void 0}}canCreateAccount(){return!0}canAuthenticate(){return!0}async createAccount(t,c){let u=await this.getCurrentUsername(),d=u.startsWith(GuestUsername);d&&logger.info(`Creating account for funnel user ${u} -> ${t}`);try{let m=await this.getRemoteCouchRootDB().signUp(t,c);if(m.ok){log2(`CREATEACCOUNT: Successfully created account for ${t}`);try{let t=await this.getRemoteCouchRootDB().logOut();log2(`CREATEACCOUNT: logged out: ${t.ok}`)}catch{}let m=await this.getRemoteCouchRootDB().logIn(t,c);if(log2(`CREATEACCOUNT: logged in as new user: ${m.ok}`),m.ok){if(d){logger.info(`Migrating data from funnel account ${u} to ${t}`);let c=await this.migrateFunnelData(u,t);c.success||logger.warn(`Migration failed: ${c.error}`)}return{status:Status.ok,error:void 0}}else return{status:Status.error,error:`Failed to log in after account creation`}}else return logger.warn(`Signup not OK: ${JSON.stringify(m)}`),{status:Status.error,error:`Account creation failed`}}catch(t){return t.reason===`Document update conflict.`?{status:Status.error,error:`This username is taken!`}:(logger.error(`Error on signup: ${JSON.stringify(t)}`),{status:Status.error,error:t.message||`Unknown error during account creation`})}}async authenticate(t,c){try{return(await this.getRemoteCouchRootDB().logIn(t,c)).ok?(log2(`Successfully logged in as ${t}`),{ok:!0}):(log2(`Login failed for ${t}`),{ok:!1,error:`Invalid username or password`})}catch(c){return logger.error(`Authentication error for ${t}:`,c),{ok:!1,error:c.message||`Authentication failed`}}}async adoptSession(t){let c;try{c=await getLoggedInUsername()}catch{return{ok:!1,error:`No session to adopt`}}if(t?.startsWith(GuestUsername)){logger.info(`Migrating data from funnel account ${t} to ${c}`);let u=await this.migrateFunnelData(t,c);u.success||logger.warn(`Migration failed: ${u.error}`)}return{ok:!0,username:c}}async logout(){try{let t=await this.getRemoteCouchRootDB().logOut();return{ok:t.ok,error:t.ok?void 0:`Logout failed`}}catch(t){return logger.error(`Logout error:`,t),{ok:!1,error:t.message||`Logout failed`}}}async getCurrentUsername(){logger.log(`[funnel] CouchDBSyncStrategy.getCurrentUsername() called`);try{let t=await getLoggedInUsername();return logger.log(`[funnel] getLoggedInUsername() returned:`,t),t}catch(t){logger.log(`[funnel] getLoggedInUsername() failed, calling accomodateGuest()`),logger.log(`[funnel] Error was:`,t);let c=accomodateGuest();return logger.log(`[funnel] accomodateGuest() returned:`,c),c.username}}async migrateFunnelData(t,c){try{logger.info(`Starting data migration from ${t} to ${c}`);let u=getLocalUserDB(t),d=getLocalUserDB(c),m=await u.allDocs({include_docs:!0});logger.info(`Found ${m.rows.length} documents in funnel account`);let g=m.rows.filter(t=>!t.id.startsWith(`_design/`)).map(t=>({...t.doc,_rev:void 0}));g.length>0?(await d.bulkDocs(g),logger.info(`Successfully migrated ${g.length} documents from ${t} to ${c}`)):logger.info(`No documents to migrate from funnel account`);try{await u.destroy(),logger.info(`Destroyed consumed guest DB for ${t}`)}catch(c){logger.warn(`Failed to destroy consumed guest DB for ${t} (non-fatal): ${c instanceof Error?c.message:String(c)}`)}return{success:!0}}catch(t){return logger.error(`Migration failed:`,t),{success:!1,error:t instanceof Error?t.message:`Unknown error`}}}getRemoteCouchRootDB(){let t=ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+`skuilder`;try{return new pouchdb_setup_default(t,{skip_setup:!0})}catch(t){throw logger.error(`Failed to initialize remote CouchDB connection:`,t),Error(`Failed to initialize CouchDB: ${JSON.stringify(t)}`)}}getUserDB(t){let c=!1,u=`userdb-${hexEncode(t)}`;return log2(`Fetching user database: ${u} (${t})`),new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+u,createPouchDBConfig())}}}}),init_couch=__esm({"src/impl/couch/index.ts"(){"use strict";init_factory(),init_types_legacy(),init_logger(),init_pouchdb_setup(),init_contentSource(),init_adminDB2(),init_classroomDB2(),init_courseAPI(),init_courseDB(),init_CourseSyncService(),init_CouchDBSyncStrategy(),isBrowser=typeof window<`u`,isBrowser&&(window.process=import_browser.default),GUEST_LOCAL_DB=`userdb-${GuestUsername}`,new pouchdb_setup_default(GUEST_LOCAL_DB),pouchDBincludeCredentialsConfig={fetch(t,c){return c.credentials=`include`,pouchdb_setup_default.fetch(t,c)}},REVIEW_TIME_FORMAT=`YYYY-MM-DD--kk:mm:ss-SSS`}}),init_SpacedRepetition=__esm({"src/study/SpacedRepetition.ts"(){"use strict";init_util(),init_logger(),duration=hooks.duration}}),init_SrsService=__esm({"src/study/services/SrsService.ts"(){"use strict";init_couch(),init_SpacedRepetition(),init_logger(),SrsService=class{constructor(t){_defineProperty$2(this,`user`,void 0),this.user=t}removeReview(t){logger.info(`[SrsService] Removing orphaned scheduled review: ${t}`),this.user.removeScheduledCardReview(t)}async scheduleReview(t,c){let u=newInterval(this.user,t),d=hooks.utc().add(u,`seconds`);isReview(c)&&(logger.info(`[SrsService] Removing previously scheduled review for: ${c.cardID}`),this.user.removeScheduledCardReview(c.reviewID)),this.user.scheduleCardReview({user:this.user.getUsername(),course_id:t.courseID,card_id:t.cardID,time:d,scheduledFor:c.contentSourceType,schedulingAgentId:c.contentSourceID})}}}}),init_tagRecent=__esm({"src/study/services/tagRecent.ts"(){"use strict";}}),init_EloService=__esm({"src/study/services/EloService.ts"(){"use strict";init_logger(),init_tagRecent(),EloService=class{constructor(t,c){_defineProperty$2(this,`dataLayer`,void 0),_defineProperty$2(this,`user`,void 0),_defineProperty$2(this,`qaPatterns`,new Map),this.dataLayer=t,this.user=c}async isQaUser(t){let c=t.getCourseID(),u=this.qaPatterns.get(c);return u||(u=t.getCourseConfig().then(t=>t.qaUsernamePattern?new RegExp(t.qaUsernamePattern,`i`):null).catch(t=>(logger.warn(`[EloService] No QA username pattern for ${c}: ${t}`),null)),this.qaPatterns.set(c,u)),(await u)?.test(this.user.getUsername())??!1}async updateUserAndCardElo(t,c,u,d,m,g){g&&logger.warn(`k value interpretation not currently implemented`);let b=this.dataLayer.getCourseDB(m.card.course_id),S=d.courses.find(t=>t.courseID===c);if(!S)return logger.error(`[EloService] No registration for course ${c} on user's registration doc \u2014 skipping ELO update for card ${u}. (Is the user registered for this course?)`),null;let C=toCourseElo(S.elo),w=(await b.getCardEloData([m.card.card_id]))[0];if(w&&C){let d=!await this.isQaUser(b),m=C.global.score,g=w.global.score,T=Object.keys(w.tags),E={};for(let t of T)E[t]=C.tags[t]?.score??C.global.score;let D=adjustCourseScores(C,w,t);S.elo=D.userElo;let O={};for(let c of T){let u=isCountOnlyTag(c);O[c]={before:E[c],after:u?E[c]:D.userElo.tags[c].score,score:u?null:t}}let xr={cardId:u,at:new Date().toISOString(),userScore:t,global:{before:m,after:D.userElo.global.score},card:{before:g,after:d?D.cardElo.global.score:g},...T.length?{tags:O}:{}};d||logger.info(`[EloService] QA account: card ELO for ${u} not written`);let Sr=await Promise.allSettled([this.user.updateUserElo(c,D.userElo),d?b.updateCardElo(u,D.cardElo):Promise.resolve(null)]),Cr=Sr[0].status===`fulfilled`,wr=Sr[1].status===`fulfilled`;if(Cr&&wr){let t=Sr[0].value,c=Sr[1].value;t.ok&&c&&c.ok&&logger.info(`[EloService] Updated ELOS:
367
+ User: ${JSON.stringify(D.userElo)})
368
+ Card: ${JSON.stringify(D.cardElo)})
368
369
  `)}else logger.warn(`[EloService] Partial ELO update:
369
- User ELO update: ${Sr?`SUCCESS`:`FAILED`}
370
- Card ELO update: ${Cr?`SUCCESS`:`FAILED`}`),!Sr&&xr[0].status===`rejected`&&logger.error(`[EloService] User ELO update error:`,xr[0].reason),!Cr&&xr[1].status===`rejected`&&logger.error(`[EloService] Card ELO update error:`,xr[1].reason);return O}return null}async updateUserAndCardEloPerTag(t,c,u,d,m){let g=this.dataLayer.getCourseDB(m.card.course_id),b=d.courses.find(t=>t.courseID===c);if(!b)return logger.error(`[EloService] No registration for course ${c} on user's registration doc \u2014 skipping per-tag ELO update for card ${u}. (Is the user registered for this course?)`),null;let S=toCourseElo(b.elo),[C,w]=await Promise.all([g.getCardEloData([m.card.card_id]),g.getAppliedTagsBatch([u])]),T=C[0],E=w.get(u)??[],D=withCountOnlyRoles(t,u),O={...D},xr=t._global;for(let t of E)t in O||(O[t]=isCountOnlyTag(t)?null:xr);if(T&&S){let t=S.global.score,d=T.global.score,C=Object.keys(O).filter(t=>t!==`_global`),w={};for(let t of C)w[t]=S.tags[t]?.score??S.global.score;let E=adjustCourseScoresPerTag(S,T,O),Sr=new Date().toISOString(),Cr=recordTagPresentations(E.userElo,D,m.records,u,Sr);Cr.length&&logger.info(`[EloService] recent-presentation entries for ${u}: [${Cr.join(`, `)}]`),b.elo=E.userElo;let wr={};for(let t of C){let c=O[t],u=c===null?w[t]:E.userElo.tags[t]?.score??w[t];wr[t]={before:w[t],after:u,score:c}}let Tr={cardId:u,at:Sr,userScore:xr,global:{before:t,after:E.userElo.global.score},card:{before:d,after:E.cardElo.global.score},...C.length?{tags:wr}:{}},Er=await Promise.allSettled([this.user.updateUserElo(c,E.userElo),g.updateCardElo(u,E.cardElo)]),Dr=Er[0].status===`fulfilled`,Or=Er[1].status===`fulfilled`;if(Dr&&Or){let t=Er[0].value,c=Er[1].value;if(t.ok&&c&&c.ok){let t=Object.keys(O).length-1;logger.info(`[EloService] Updated ELOS (per-tag, ${t} tags):
371
- User: ${JSON.stringify(E.userElo)})
372
- Card: ${JSON.stringify(E.cardElo)})
370
+ User ELO update: ${Cr?`SUCCESS`:`FAILED`}
371
+ Card ELO update: ${wr?`SUCCESS`:`FAILED`}`),!Cr&&Sr[0].status===`rejected`&&logger.error(`[EloService] User ELO update error:`,Sr[0].reason),!wr&&Sr[1].status===`rejected`&&logger.error(`[EloService] Card ELO update error:`,Sr[1].reason);return xr}return null}async updateUserAndCardEloPerTag(t,c,u,d,m){let g=this.dataLayer.getCourseDB(m.card.course_id),b=d.courses.find(t=>t.courseID===c);if(!b)return logger.error(`[EloService] No registration for course ${c} on user's registration doc \u2014 skipping per-tag ELO update for card ${u}. (Is the user registered for this course?)`),null;let S=toCourseElo(b.elo),[C,w]=await Promise.all([g.getCardEloData([m.card.card_id]),g.getAppliedTagsBatch([u])]),T=C[0],E=w.get(u)??[],D=withCountOnlyRoles(t,u),O={...D},xr=t._global;for(let t of E)t in O||(O[t]=isCountOnlyTag(t)?null:xr);if(T&&S){let t=!await this.isQaUser(g),d=S.global.score,C=T.global.score,w=Object.keys(O).filter(t=>t!==`_global`),E={};for(let t of w)E[t]=S.tags[t]?.score??S.global.score;let Sr=adjustCourseScoresPerTag(S,T,O),Cr=new Date().toISOString(),wr=recordTagPresentations(Sr.userElo,D,m.records,u,Cr);wr.length&&logger.info(`[EloService] recent-presentation entries for ${u}: [${wr.join(`, `)}]`),b.elo=Sr.userElo;let Tr={};for(let t of w){let c=O[t],u=c===null?E[t]:Sr.userElo.tags[t]?.score??E[t];Tr[t]={before:E[t],after:u,score:c}}let Er={cardId:u,at:Cr,userScore:xr,global:{before:d,after:Sr.userElo.global.score},card:{before:C,after:t?Sr.cardElo.global.score:C},...w.length?{tags:Tr}:{}};t||logger.info(`[EloService] QA account: card ELO for ${u} not written`);let Dr=await Promise.allSettled([this.user.updateUserElo(c,Sr.userElo),t?g.updateCardElo(u,Sr.cardElo):Promise.resolve(null)]),Or=Dr[0].status===`fulfilled`,kr=Dr[1].status===`fulfilled`;if(Or&&kr){let t=Dr[0].value,c=Dr[1].value;if(t.ok&&c&&c.ok){let t=Object.keys(O).length-1;logger.info(`[EloService] Updated ELOS (per-tag, ${t} tags):
372
+ User: ${JSON.stringify(Sr.userElo)})
373
+ Card: ${JSON.stringify(Sr.cardElo)})
373
374
  `)}}else logger.warn(`[EloService] Partial ELO update (per-tag):
374
- User ELO update: ${Dr?`SUCCESS`:`FAILED`}
375
- Card ELO update: ${Or?`SUCCESS`:`FAILED`}`),!Dr&&Er[0].status===`rejected`&&logger.error(`[EloService] User ELO update error:`,Er[0].reason),!Or&&Er[1].status===`rejected`&&logger.error(`[EloService] Card ELO update error:`,Er[1].reason);return Tr}return null}}}}),init_ResponseProcessor=__esm({"src/study/services/ResponseProcessor.ts"(){"use strict";init_core(),init_logger(),ResponseProcessor=class{constructor(t,c,u){_defineProperty$2(this,`srsService`,void 0),_defineProperty$2(this,`eloService`,void 0),_defineProperty$2(this,`onEloEvent`,void 0),this.srsService=t,this.eloService=c,this.onEloEvent=u}logEloFailure(t,c){return u=>logger.error(`[ResponseProcessor] ELO update failed (${t}) for ${c}:`,u)}trackElo(t,c,u){t.then(t=>{t&&this.onEloEvent?.(t)}).catch(this.logEloFailure(c,u))}parsePerformance(t){return typeof t==`number`?{globalScore:t,taggedPerformance:null}:isTaggedPerformance(t)?{globalScore:t._global,taggedPerformance:t}:(logger.warn(`[ResponseProcessor] Unexpected performance structure, using neutral score`,{performance:t}),{globalScore:.5,taggedPerformance:null})}async processResponse(t,c,u,d,m,g,b,S,C,w){if(!isQuestionRecord(t))return{nextCardAction:`dismiss-success`,shouldLoadNextCard:!0,isCorrect:!0,shouldClearFeedbackShadow:!0};try{let T=await c,E;return E=t.isCorrect?this.processCorrectResponse(t,T,u,d,m,g,b,C,w):this.processIncorrectResponse(t,T,d,m,g,b,S,C,w),t.deferAdvance&&E.shouldLoadNextCard&&(logger.info(`[ResponseProcessor] deferAdvance requested — suppressing navigation, action stashed:`,{nextCardAction:E.nextCardAction}),E={...E,shouldLoadNextCard:!1,deferred:!0}),E}catch(t){throw logger.error(`[ResponseProcessor] Failed to load card history`,{e:t,cardId:b}),t}}processCorrectResponse(t,c,u,d,m,g,b,S,C){if(t.priorAttemps===0){m.card.tags.includes(`srs:skip`)||this.srsService.scheduleReview(c,u);let{globalScore:S,taggedPerformance:C}=this.parsePerformance(t.performance);if(C){let u=Object.keys(C).filter(t=>t!==`_global`),S=u.filter(t=>C[t]===null),w=u.filter(t=>C[t]!==null);logger.info(`[FirstContactElo] correct first-attempt per-tag ELO update for ${b} (historyLen=${c.records.length}, priorAttemps=${t.priorAttemps}): scored=[${w.join(`, `)}] count-only=[${S.join(`, `)}]`),this.trackElo(this.eloService.updateUserAndCardEloPerTag(C,g,b,d,m),`correct per-tag`,b)}else{let u=.5+S/2;if(c.records.length===1)this.trackElo(this.eloService.updateUserAndCardElo(u,g,b,d,m),`correct`,b);else{let t=Math.ceil(32/c.records.length);this.trackElo(this.eloService.updateUserAndCardElo(u,g,b,d,m,t),`correct repeat-view`,b)}logger.info(`[FirstContactElo] correct first-attempt ELO update (score=${u.toFixed(3)}) for ${b} (historyLen=${c.records.length}, priorAttemps=${t.priorAttemps})`)}return{nextCardAction:`dismiss-success`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:S,shouldClearFeedbackShadow:!0}}else{let c=C>=S;logger.info(`[ResponseProcessor] Processed correct response (retry attempt - no scheduling/ELO); sessionViews=${C}/${S} -> ${c?`dismiss-success`:`marked-failed`}`);let{globalScore:u}=this.parsePerformance(t.performance);return{nextCardAction:c?`dismiss-success`:`marked-failed`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:u,shouldClearFeedbackShadow:!0}}}processIncorrectResponse(t,c,u,d,m,g,b,S,C){let{taggedPerformance:w}=this.parsePerformance(t.performance),T=!1;return t.priorAttemps===0?(w?(this.trackElo(this.eloService.updateUserAndCardEloPerTag(w,m,g,u,d),`incorrect per-tag`,g),logger.info(`[FirstContactElo] incorrect first-attempt per-tag ELO update for ${g} (historyLen=${c.records.length}, priorAttemps=${t.priorAttemps}, tags=${Object.keys(w).length-1})`)):(this.trackElo(this.eloService.updateUserAndCardElo(0,m,g,u,d),`incorrect`,g),logger.info(`[FirstContactElo] incorrect first-attempt ELO update (score=0) for ${g} (historyLen=${c.records.length}, priorAttemps=${t.priorAttemps})`)),T=!0):logger.info(`[FirstContactElo] incorrect retry \u2014 no ELO update for ${g} (historyLen=${c.records.length}, priorAttemps=${t.priorAttemps})`),d.records.length>=b?C>=S?(T?logger.info(`[FirstContactElo] dismiss-failed \u2014 ELO already updated this response, skipping double penalty for ${g}`):(w?this.trackElo(this.eloService.updateUserAndCardEloPerTag(w,m,g,u,d),`dismiss-failed per-tag`,g):this.trackElo(this.eloService.updateUserAndCardElo(0,m,g,u,d),`dismiss-failed`,g),logger.info(`[FirstContactElo] dismiss-failed final ELO penalty for ${g} (historyLen=${c.records.length}, sessionViews=${C})`)),{nextCardAction:`dismiss-failed`,shouldLoadNextCard:!0,isCorrect:!1,shouldClearFeedbackShadow:!0}):{nextCardAction:`marked-failed`,shouldLoadNextCard:!0,isCorrect:!1,shouldClearFeedbackShadow:!0}:{nextCardAction:`none`,shouldLoadNextCard:!1,isCorrect:!1,shouldClearFeedbackShadow:!0}}}}}),init_CardHydrationService=__esm({"src/study/services/CardHydrationService.ts"(){"use strict";init_logger(),CardHydrationService=class{constructor(t,c,u){_defineProperty$2(this,`hydratedCards`,new Map),_defineProperty$2(this,`hydrationInFlight`,new Set),_defineProperty$2(this,`hydrationInProgress`,!1),this.getViewComponent=t,this.getCourseDB=c,this.getItemsToHydrate=u}getHydratedCard(t){return this.hydratedCards.get(t)??null}hasHydratedCard(t){return this.hydratedCards.has(t)}removeCard(t){this.hydratedCards.delete(t)}async ensureHydratedCards(){this.fillHydratedCards()}async waitForCard(t){if(this.hydratedCards.has(t))return this.hydratedCards.get(t);this.hydrationInProgress||this.fillHydratedCards();let c=1e4,u=25,d=0;for(;d<1e4;){if(this.hydratedCards.has(t))return this.hydratedCards.get(t);if(!this.hydrationInFlight.has(t)&&!this.hydrationInProgress)break;await new Promise(t=>setTimeout(t,25)),d+=25}return this.hydratedCards.get(t)??null}get hydratedCount(){return this.hydratedCards.size}getHydratedCardIds(){return Array.from(this.hydratedCards.keys())}async fillHydratedCards(){if(!this.hydrationInProgress){this.hydrationInProgress=!0;try{let t=this.getItemsToHydrate();for(let c of t)if(!(this.hydratedCards.has(c.cardID)||this.hydrationInFlight.has(c.cardID)))try{await this.hydrateCard(c)}catch(t){logger.error(`[CardHydrationService] Error hydrating card ${c.cardID}:`,t)}}finally{this.hydrationInProgress=!1}}}async hydrateCard(t){if(!(this.hydratedCards.has(t.cardID)||this.hydrationInFlight.has(t.cardID))){this.hydrationInFlight.add(t.cardID);try{let c=this.getCourseDB(t.courseID),[u,d]=await Promise.all([c.getCourseDoc(t.cardID),c.getAppliedTagsBatch([t.cardID])]);isCourseElo(u.elo)||(u.elo=toCourseElo(u.elo));let m=this.getViewComponent(u.id_view),g=await Promise.all(u.id_displayable_data.map(t=>c.getCourseDoc(t,{attachments:!0,binary:!0}))),b=[];g.forEach(t=>{t.data.forEach(t=>{b.push(...parseAudioURIs(t.data))})});let S=[...new Set(b)];S.length>0&&(logger.debug(`[CardHydrationService] Prefetching ${S.length} audio files for card ${t.cardID}`),await Promise.allSettled(S.map(prefetchAudio)));let C=g.map(displayableDataToViewData).reverse();this.hydratedCards.set(t.cardID,{item:{...t,elo:toCourseElo(u.elo).global.score},view:m,data:C,tags:d.get(t.cardID)??[]}),logger.debug(`[CardHydrationService] Hydrated card ${t.cardID}`)}finally{this.hydrationInFlight.delete(t.cardID)}}}}}}),init_ItemQueue=__esm({"src/study/ItemQueue.ts"(){"use strict";ItemQueue=class{constructor(){_defineProperty$2(this,`q`,[]),_defineProperty$2(this,`seenCardIds`,[]),_defineProperty$2(this,`_dequeueCount`,0)}get dequeueCount(){return this._dequeueCount}add(t,c){this.seenCardIds.find(t=>t===c)||(this.seenCardIds.push(c),this.q.push(t))}addAll(t,c){t.forEach(t=>this.add(t,c(t)))}get length(){return this.q.length}peek(t){return this.q[t]}dequeue(t){if(this.q.length!==0){this._dequeueCount++;let c=this.q.splice(0,1)[0];if(t){let u=t(c),d=this.seenCardIds.indexOf(u);d>-1&&this.seenCardIds.splice(d,1)}return c}else return null}replaceAll(t,c){this.q=[],this.seenCardIds=[];for(let u of t){let t=c(u);this.seenCardIds.includes(t)||(this.seenCardIds.push(t),this.q.push(u))}}mergeToFront(t,c,u){let d=0,m=[];for(let g of t){let t=c(g);if(!this.seenCardIds.includes(t))this.seenCardIds.push(t),m.push(g),d++;else if(u?.has(t)){let u=this.q.findIndex(u=>c(u)===t);u>=0&&m.push(...this.q.splice(u,1))}}return this.q.unshift(...m),d}get toString(){return`${typeof this.q[0]}:
375
+ User ELO update: ${Or?`SUCCESS`:`FAILED`}
376
+ Card ELO update: ${kr?`SUCCESS`:`FAILED`}`),!Or&&Dr[0].status===`rejected`&&logger.error(`[EloService] User ELO update error:`,Dr[0].reason),!kr&&Dr[1].status===`rejected`&&logger.error(`[EloService] Card ELO update error:`,Dr[1].reason);return Er}return null}}}}),init_ResponseProcessor=__esm({"src/study/services/ResponseProcessor.ts"(){"use strict";init_core(),init_logger(),ResponseProcessor=class{constructor(t,c,u){_defineProperty$2(this,`srsService`,void 0),_defineProperty$2(this,`eloService`,void 0),_defineProperty$2(this,`onEloEvent`,void 0),this.srsService=t,this.eloService=c,this.onEloEvent=u}logEloFailure(t,c){return u=>logger.error(`[ResponseProcessor] ELO update failed (${t}) for ${c}:`,u)}trackElo(t,c,u){t.then(t=>{t&&this.onEloEvent?.(t)}).catch(this.logEloFailure(c,u))}parsePerformance(t){return typeof t==`number`?{globalScore:t,taggedPerformance:null}:isTaggedPerformance(t)?{globalScore:t._global,taggedPerformance:t}:(logger.warn(`[ResponseProcessor] Unexpected performance structure, using neutral score`,{performance:t}),{globalScore:.5,taggedPerformance:null})}async processResponse(t,c,u,d,m,g,b,S,C,w){if(!isQuestionRecord(t))return{nextCardAction:`dismiss-success`,shouldLoadNextCard:!0,isCorrect:!0,shouldClearFeedbackShadow:!0};try{let T=await c,E;return E=t.isCorrect?this.processCorrectResponse(t,T,u,d,m,g,b,C,w):this.processIncorrectResponse(t,T,d,m,g,b,S,C,w),t.deferAdvance&&E.shouldLoadNextCard&&(logger.info(`[ResponseProcessor] deferAdvance requested — suppressing navigation, action stashed:`,{nextCardAction:E.nextCardAction}),E={...E,shouldLoadNextCard:!1,deferred:!0}),E}catch(t){throw logger.error(`[ResponseProcessor] Failed to load card history`,{e:t,cardId:b}),t}}processCorrectResponse(t,c,u,d,m,g,b,S,C){if(t.priorAttemps===0){m.card.tags.includes(`srs:skip`)||this.srsService.scheduleReview(c,u);let{globalScore:S,taggedPerformance:C}=this.parsePerformance(t.performance);if(C){let u=Object.keys(C).filter(t=>t!==`_global`),S=u.filter(t=>C[t]===null),w=u.filter(t=>C[t]!==null);logger.info(`[FirstContactElo] correct first-attempt per-tag ELO update for ${b} (historyLen=${c.records.length}, priorAttemps=${t.priorAttemps}): scored=[${w.join(`, `)}] count-only=[${S.join(`, `)}]`),this.trackElo(this.eloService.updateUserAndCardEloPerTag(C,g,b,d,m),`correct per-tag`,b)}else{let u=.5+S/2;if(c.records.length===1)this.trackElo(this.eloService.updateUserAndCardElo(u,g,b,d,m),`correct`,b);else{let t=Math.ceil(32/c.records.length);this.trackElo(this.eloService.updateUserAndCardElo(u,g,b,d,m,t),`correct repeat-view`,b)}logger.info(`[FirstContactElo] correct first-attempt ELO update (score=${u.toFixed(3)}) for ${b} (historyLen=${c.records.length}, priorAttemps=${t.priorAttemps})`)}return{nextCardAction:`dismiss-success`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:S,shouldClearFeedbackShadow:!0}}else{let c=C>=S;logger.info(`[ResponseProcessor] Processed correct response (retry attempt - no scheduling/ELO); sessionViews=${C}/${S} -> ${c?`dismiss-success`:`marked-failed`}`);let{globalScore:u}=this.parsePerformance(t.performance);return{nextCardAction:c?`dismiss-success`:`marked-failed`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:u,shouldClearFeedbackShadow:!0}}}processIncorrectResponse(t,c,u,d,m,g,b,S,C){let{taggedPerformance:w}=this.parsePerformance(t.performance),T=!1;return t.priorAttemps===0?(w?(this.trackElo(this.eloService.updateUserAndCardEloPerTag(w,m,g,u,d),`incorrect per-tag`,g),logger.info(`[FirstContactElo] incorrect first-attempt per-tag ELO update for ${g} (historyLen=${c.records.length}, priorAttemps=${t.priorAttemps}, tags=${Object.keys(w).length-1})`)):(this.trackElo(this.eloService.updateUserAndCardElo(0,m,g,u,d),`incorrect`,g),logger.info(`[FirstContactElo] incorrect first-attempt ELO update (score=0) for ${g} (historyLen=${c.records.length}, priorAttemps=${t.priorAttemps})`)),T=!0):logger.info(`[FirstContactElo] incorrect retry \u2014 no ELO update for ${g} (historyLen=${c.records.length}, priorAttemps=${t.priorAttemps})`),d.records.length>=b?C>=S?(T?logger.info(`[FirstContactElo] dismiss-failed \u2014 ELO already updated this response, skipping double penalty for ${g}`):(w?this.trackElo(this.eloService.updateUserAndCardEloPerTag(w,m,g,u,d),`dismiss-failed per-tag`,g):this.trackElo(this.eloService.updateUserAndCardElo(0,m,g,u,d),`dismiss-failed`,g),logger.info(`[FirstContactElo] dismiss-failed final ELO penalty for ${g} (historyLen=${c.records.length}, sessionViews=${C})`)),{nextCardAction:`dismiss-failed`,shouldLoadNextCard:!0,isCorrect:!1,shouldClearFeedbackShadow:!0}):{nextCardAction:`marked-failed`,shouldLoadNextCard:!0,isCorrect:!1,shouldClearFeedbackShadow:!0}:{nextCardAction:`none`,shouldLoadNextCard:!1,isCorrect:!1,shouldClearFeedbackShadow:!0}}}}}),init_CardHydrationService=__esm({"src/study/services/CardHydrationService.ts"(){"use strict";init_logger(),CardHydrationService=class{constructor(t,c,u){_defineProperty$2(this,`hydratedCards`,new Map),_defineProperty$2(this,`hydrationInFlight`,new Set),_defineProperty$2(this,`hydrationInProgress`,!1),this.getViewComponent=t,this.getCourseDB=c,this.getItemsToHydrate=u}getHydratedCard(t){return this.hydratedCards.get(t)??null}hasHydratedCard(t){return this.hydratedCards.has(t)}removeCard(t){this.hydratedCards.delete(t)}async ensureHydratedCards(){this.fillHydratedCards()}async waitForCard(t){if(this.hydratedCards.has(t))return this.hydratedCards.get(t);this.hydrationInProgress||this.fillHydratedCards();let c=1e4,u=25,d=0;for(;d<1e4;){if(this.hydratedCards.has(t))return this.hydratedCards.get(t);if(!this.hydrationInFlight.has(t)&&!this.hydrationInProgress)break;await new Promise(t=>setTimeout(t,25)),d+=25}return this.hydratedCards.get(t)??null}get hydratedCount(){return this.hydratedCards.size}getHydratedCardIds(){return Array.from(this.hydratedCards.keys())}async fillHydratedCards(){if(!this.hydrationInProgress){this.hydrationInProgress=!0;try{let t=this.getItemsToHydrate();for(let c of t)if(!(this.hydratedCards.has(c.cardID)||this.hydrationInFlight.has(c.cardID)))try{await this.hydrateCard(c)}catch(t){logger.error(`[CardHydrationService] Error hydrating card ${c.cardID}:`,t)}}finally{this.hydrationInProgress=!1}}}async hydrateCard(t){if(!(this.hydratedCards.has(t.cardID)||this.hydrationInFlight.has(t.cardID))){this.hydrationInFlight.add(t.cardID);try{let c=this.getCourseDB(t.courseID),[u,d]=await Promise.all([c.getCourseDoc(t.cardID),c.getAppliedTagsBatch([t.cardID])]);isCourseElo(u.elo)||(u.elo=toCourseElo(u.elo));let m=this.getViewComponent(u.id_view),g=await Promise.all(u.id_displayable_data.map(t=>c.getCourseDoc(t,{attachments:!0,binary:!0}))),b=[];g.forEach(t=>{t.data.forEach(t=>{b.push(...parseAudioURIs(t.data))})});let S=[...new Set(b)];S.length>0&&(logger.debug(`[CardHydrationService] Prefetching ${S.length} audio files for card ${t.cardID}`),await Promise.allSettled(S.map(prefetchAudio)));let C=g.map(displayableDataToViewData).reverse();this.hydratedCards.set(t.cardID,{item:{...t,elo:toCourseElo(u.elo).global.score},view:m,data:C,tags:d.get(t.cardID)??[]}),logger.debug(`[CardHydrationService] Hydrated card ${t.cardID}`)}finally{this.hydrationInFlight.delete(t.cardID)}}}}}}),init_ItemQueue=__esm({"src/study/ItemQueue.ts"(){"use strict";ItemQueue=class{constructor(){_defineProperty$2(this,`q`,[]),_defineProperty$2(this,`seenCardIds`,[]),_defineProperty$2(this,`_dequeueCount`,0)}get dequeueCount(){return this._dequeueCount}add(t,c){this.seenCardIds.find(t=>t===c)||(this.seenCardIds.push(c),this.q.push(t))}addAll(t,c){t.forEach(t=>this.add(t,c(t)))}get length(){return this.q.length}peek(t){return this.q[t]}dequeue(t){if(this.q.length!==0){this._dequeueCount++;let c=this.q.splice(0,1)[0];if(t){let u=t(c),d=this.seenCardIds.indexOf(u);d>-1&&this.seenCardIds.splice(d,1)}return c}else return null}replaceAll(t,c){this.q=[],this.seenCardIds=[];for(let u of t){let t=c(u);this.seenCardIds.includes(t)||(this.seenCardIds.push(t),this.q.push(u))}}mergeToFront(t,c,u){let d=0,m=[];for(let g of t){let t=c(g);if(!this.seenCardIds.includes(t))this.seenCardIds.push(t),m.push(g),d++;else if(u?.has(t)){let u=this.q.findIndex(u=>c(u)===t);u>=0&&m.push(...this.q.splice(u,1))}}return this.q.unshift(...m),d}get toString(){return`${typeof this.q[0]}:
376
377
  `+this.q.map(t=>` ${t.courseID}+${t.cardID}: ${t.status}`).join(`
377
378
  `)}}}}),init_studySession=__esm({"src/core/types/studySession.ts"(){"use strict";init_types_legacy()}}),init_types3=__esm({"src/util/packer/types.ts"(){"use strict";}}),init_CouchDBToStaticPacker=__esm({"src/util/packer/CouchDBToStaticPacker.ts"(){"use strict";init_types_legacy(),init_logger(),CouchDBToStaticPacker=class{constructor(t={}){_defineProperty$2(this,`config`,void 0),_defineProperty$2(this,`sourceDB`,null),this.config={chunkSize:1e3,includeAttachments:!0,...t}}async packCourse(t,c){logger.info(`Starting static pack for course: ${c}`),this.sourceDB=t;let u={version:`1.0.0`,courseId:c,courseName:``,courseConfig:null,lastUpdated:new Date().toISOString(),documentCount:0,chunks:[],indices:[],designDocs:[]},d=await this.extractCourseConfig(t);u.courseName=d.name,u.courseConfig=d,u.designDocs=await this.extractDesignDocs(t);let m=await this.extractDocumentsByType(t),g=new Map;this.config.includeAttachments&&await this.extractAllAttachments(m,g);let b=new Map;for(let[t,c]of Object.entries(m)){let d=this.createChunks(c,t);u.chunks.push(...d),u.documentCount+=c.length,this.prepareChunkData(d,c,b)}let S=new Map;return u.indices=await this.buildIndices(m,u.designDocs,S),{manifest:u,chunks:b,indices:S,attachments:g}}async packCourseToFiles(t,c,u,d){logger.info(`Packing course ${c} to files in ${u}`);let m=await this.packCourse(t,c),g=await this.writePackedDataToFiles(m,u,d);return{manifest:m.manifest,filesWritten:g,attachmentsFound:m.attachments?m.attachments.size:0}}async writePackedDataToFiles(t,c,u){let d=0;await u.ensureDir(c);let m=u.joinPath(c,`manifest.json`);await u.writeJson(m,t.manifest,{spaces:2}),d++,logger.info(`Wrote manifest: ${m}`);let g=u.joinPath(c,`chunks`),b=u.joinPath(c,`indices`);await u.ensureDir(g),await u.ensureDir(b);for(let[c,m]of t.chunks){let t=u.joinPath(g,`${c}.json`);await u.writeJson(t,m),d++}logger.info(`Wrote ${t.chunks.size} chunk files`);for(let[c,m]of t.indices){let t=u.joinPath(b,`${c}.json`);await u.writeJson(t,m,{spaces:2}),d++}if(logger.info(`Wrote ${t.indices.size} index files`),t.attachments&&t.attachments.size>0){for(let[m,g]of t.attachments){let t=u.joinPath(c,m),b=u.dirname(t);await u.ensureDir(b),await u.writeFile(t,g.buffer),d++}logger.info(`Wrote ${t.attachments.size} attachment files`)}return d}async extractCourseConfig(t){try{return await t.get(`CourseConfig`)}catch(t){throw logger.error(`Failed to extract course config:`,t),Error(`Course config not found`)}}async extractDesignDocs(t){return(await t.allDocs({startkey:`_design/`,endkey:`_design/￰`,include_docs:!0})).rows.map(t=>({_id:t.id,views:t.doc.views||{}}))}async extractDocumentsByType(t){let c=await t.allDocs({include_docs:!0}),u={};for(let t of c.rows){if(t.id.startsWith(`_`))continue;let c=t.doc;c.docType&&(u[c.docType]||(u[c.docType]=[]),u[c.docType].push(c))}return u}createChunks(t,c){let u=[],d=t.sort((t,c)=>t._id.localeCompare(c._id));for(let t=0;t<d.length;t+=this.config.chunkSize){let m=d.slice(t,t+this.config.chunkSize),g=`${c}-${String(Math.floor(t/this.config.chunkSize)).padStart(4,`0`)}`;u.push({id:g,docType:c,startKey:m[0]._id,endKey:m[m.length-1]._id,documentCount:m.length,path:`chunks/${g}.json`})}return u}prepareChunkData(t,c,u){let d=c.sort((t,c)=>t._id.localeCompare(c._id));for(let c of t){let t=d.filter(t=>t._id>=c.startKey&&t._id<=c.endKey).map(t=>{let c={...t};return delete c._rev,this.config.includeAttachments&&c._attachments?c._attachments=this.transformAttachmentStubs(c._attachments,c._id):this.config.includeAttachments||delete c._attachments,c});u.set(c.id,t)}}async buildIndices(t,c,u){let d=[];if(t.CARD){let c=await this.buildEloIndex(t.CARD,u);d.push(c)}if(t.TAG){let c=await this.buildTagIndex(t.TAG,u);d.push(c)}for(let t of c)for(let[c,m]of Object.entries(t.views))if(m.map){logger.info(`Processing view: ${t._id}/${c}`);let m=await this.buildViewIndex(c,t,u);m?(d.push(m),logger.info(`Successfully built index: ${m.name}`)):logger.warn(`Skipped view index: ${t._id}/${c}`)}return d}async buildEloIndex(t,c){let u=[];for(let c of t)c.elo?.global?.score&&u.push({elo:c.elo.global.score,cardId:c._id});u.sort((t,c)=>t.elo-c.elo);let d={},m=50;for(let t of u){let c=Math.floor(t.elo/50)*50;d[c]||(d[c]=[]),d[c].push(t.cardId)}return c.set(`elo`,{sorted:u,buckets:d,stats:{min:u[0]?.elo||0,max:u[u.length-1]?.elo||0,count:u.length}}),{name:`elo`,type:`btree`,path:`indices/elo.json`}}async buildTagIndex(t,c){let u={};for(let c of t)u[c.name]={cardIds:c.taggedCards,snippet:c.snippet,count:c.taggedCards.length};let d={};for(let c of t)for(let t of c.taggedCards)d[t]||(d[t]=[]),d[t].push(c.name);return c.set(`tags`,{byTag:u,byCard:d}),{name:`tags`,type:`hash`,path:`indices/tags.json`}}async buildViewIndex(t,c,u){if(!this.sourceDB)return logger.error(`Source database not available for view querying`),null;try{let d=`${c._id.replace(`_design/`,``)}/${t}`;logger.info(`Querying CouchDB view: ${d}`);let m=await this.sourceDB.query(d,{include_docs:!1});if(!m.rows||m.rows.length===0)return logger.warn(`View ${d} returned no results`),null;logger.info(`Successfully queried view ${d}: ${m.rows.length} results`);let g=this.formatViewResults(t,m.rows,c),b=`view-${c._id.replace(`_design/`,``)}-${t}`;return u.set(b,g),{name:b,type:`view`,path:`indices/${b}.json`}}catch(u){return logger.error(`Failed to query view ${c._id}/${t}:`,u),null}}formatViewResults(t,c,u){let d={type:`couchdb-view`,viewName:t,designDoc:u._id,results:c,metadata:{resultCount:c.length,generatedAt:new Date().toISOString()}};switch(t){case`elo`:return this.formatEloViewIndex(c,d);case`getTags`:return this.formatTagsViewIndex(c,d);case`cardsByInexperience`:return this.formatInexperienceViewIndex(c,d);default:return this.formatGenericViewIndex(c,d)}}formatEloViewIndex(t,c){let u=t.sort((t,c)=>typeof t.key==`number`&&typeof c.key==`number`?t.key-c.key:0);return{...c,sorted:u,stats:{min:u[0]?.key||0,max:u[u.length-1]?.key||0,count:u.length}}}formatTagsViewIndex(t,c){let u={};for(let c of t){let t=c.key;typeof t==`string`&&(u[t]||(u[t]=[]),u[t].push(c.id))}return{...c,byTag:u,tagCount:Object.keys(u).length}}formatInexperienceViewIndex(t,c){let u=t.sort((t,c)=>typeof t.key==`number`&&typeof c.key==`number`?t.key-c.key:0);return{...c,sorted:u,stats:{minInexperience:u[0]?.key||0,maxInexperience:u[u.length-1]?.key||0,count:u.length}}}formatGenericViewIndex(t,c){return{...c}}async extractAllAttachments(t,c){logger.info(`Extracting attachments...`);let u=[];for(let c of Object.values(t))u.push(...c);let d=u.filter(t=>t._attachments&&Object.keys(t._attachments).length>0);if(d.length===0){logger.info(`No attachments found`);return}logger.info(`Found ${d.length} documents with attachments`);let m=d.map(t=>this.extractDocumentAttachments(t,c));await Promise.all(m),logger.info(`Extracted ${c.size} attachment files`)}async extractDocumentAttachments(t,c){if(!t._attachments||!this.sourceDB)return;let u=t._id;for(let[d,m]of Object.entries(t._attachments))try{let t=await this.sourceDB.getAttachment(u,d),g;if(t instanceof ArrayBuffer)g=Buffer.from(t);else if(Buffer.isBuffer(t))g=t;else{let c=t;g=Buffer.from(await c.arrayBuffer())}let b=`${d}${this.getFileExtension(m.content_type)}`,S=`attachments/${u}/${b}`;c.set(S,{docId:u,attachmentName:d,filename:b,path:S,contentType:m.content_type,length:m.length||g.length,digest:m.digest,buffer:g}),logger.debug(`Extracted attachment: ${S}`)}catch(t){throw logger.error(`Failed to extract attachment ${u}/${d}:`,t),Error(`Failed to extract attachment ${u}/${d}: ${t}`)}}transformAttachmentStubs(t,c){let u={};for(let[d,m]of Object.entries(t))u[d]={path:`attachments/${c}/${`${d}${this.getFileExtension(m.content_type)}`}`,content_type:m.content_type,length:m.length,digest:m.digest,stub:!1};return u}getFileExtension(t){return{"image/jpeg":`.jpg`,"image/jpg":`.jpg`,"image/png":`.png`,"image/gif":`.gif`,"image/webp":`.webp`,"audio/mpeg":`.mp3`,"audio/mp3":`.mp3`,"audio/wav":`.wav`,"audio/ogg":`.ogg`,"video/mp4":`.mp4`,"video/webm":`.webm`,"application/pdf":`.pdf`,"text/plain":`.txt`,"application/json":`.json`}[t]||``}}}}),init_packer=__esm({"src/util/packer/index.ts"(){"use strict";init_types3(),init_CouchDBToStaticPacker()}}),init_types4=__esm({"src/util/migrator/types.ts"(){"use strict";DEFAULT_MIGRATION_OPTIONS={chunkBatchSize:100,validateRoundTrip:!1,cleanupOnFailure:!0,timeout:3e5}}}),init_FileSystemAdapter=__esm({"src/util/migrator/FileSystemAdapter.ts"(){"use strict";FileSystemError=class extends Error{constructor(t,c,u,d){super(t),this.operation=c,this.filePath=u,this.cause=d,this.name=`FileSystemError`}}}}),init_validation=__esm({"src/util/migrator/validation.ts"(){"use strict";init_logger(),init_FileSystemAdapter(),nodeFS=null;try{typeof window>`u`&&typeof process<`u`&&process.versions?.node&&(nodeFS=eval(`require`)(`fs`),nodeFS.promises=nodeFS.promises||eval(`require`)(`fs`).promises)}catch{}}}),init_StaticToCouchDBMigrator=__esm({"src/util/migrator/StaticToCouchDBMigrator.ts"(){"use strict";init_logger(),init_types4(),init_validation(),init_FileSystemAdapter(),nodeFS2=null,nodePath=null;try{typeof window>`u`&&typeof process<`u`&&process.versions?.node&&(nodeFS2=eval(`require`)(`fs`),nodePath=eval(`require`)(`path`),nodeFS2.promises=nodeFS2.promises||eval(`require`)(`fs`).promises)}catch{}StaticToCouchDBMigrator=class{constructor(t={},c){_defineProperty$2(this,`options`,void 0),_defineProperty$2(this,`progressCallback`,void 0),_defineProperty$2(this,`fs`,void 0),this.options={...DEFAULT_MIGRATION_OPTIONS,...t},this.fs=c}setProgressCallback(t){this.progressCallback=t}async migrateCourse(t,c){let u=Date.now(),d={success:!1,documentsRestored:0,attachmentsRestored:0,designDocsRestored:0,courseConfigRestored:0,errors:[],warnings:[],migrationTime:0};try{logger.info(`Starting migration from ${t} to CouchDB`),this.reportProgress(`manifest`,0,1,`Validating static course...`);let m=await validateStaticCourse(t,this.fs);if(!m.valid)throw d.errors.push(...m.errors),Error(`Static course validation failed: ${m.errors.join(`, `)}`);d.warnings.push(...m.warnings),this.reportProgress(`manifest`,1,1,`Loading course manifest...`);let g=await this.loadManifest(t);logger.info(`Loaded manifest for course: ${g.courseId} (${g.courseName})`),this.reportProgress(`design_docs`,0,g.designDocs.length,`Restoring design documents...`);let b=await this.restoreDesignDocuments(g.designDocs,c);d.designDocsRestored=b.restored,d.errors.push(...b.errors),d.warnings.push(...b.warnings),this.reportProgress(`course_config`,0,1,`Restoring CourseConfig document...`);let S=await this.restoreCourseConfig(g,c);d.courseConfigRestored=S.restored,d.errors.push(...S.errors),d.warnings.push(...S.warnings),this.reportProgress(`course_config`,1,1,`CourseConfig document restored`);let C=this.calculateExpectedCounts(g);this.reportProgress(`documents`,0,g.documentCount,`Aggregating documents from chunks...`);let w=await this.aggregateDocuments(t,g),T=w.filter(t=>t._id!==`CourseConfig`);w.length!==T.length&&d.warnings.push(`Filtered out ${w.length-T.length} CourseConfig document(s) from chunks to prevent conflicts`),this.reportProgress(`documents`,T.length,g.documentCount,`Uploading documents to CouchDB...`);let E=await this.uploadDocuments(T,c);d.documentsRestored=E.restored,d.errors.push(...E.errors),d.warnings.push(...E.warnings);let D=w.filter(t=>t._attachments&&Object.keys(t._attachments).length>0);this.reportProgress(`attachments`,0,D.length,`Uploading attachments...`);let O=await this.uploadAttachments(t,D,c);if(d.attachmentsRestored=O.restored,d.errors.push(...O.errors),d.warnings.push(...O.warnings),this.options.validateRoundTrip){this.reportProgress(`validation`,0,1,`Validating migration...`);let t=await validateMigration(c,C,g);t.valid||(d.warnings.push(`Migration validation found issues`),t.issues.forEach(t=>{t.type===`error`?d.errors.push(`Validation: ${t.message}`):d.warnings.push(`Validation: ${t.message}`)})),this.reportProgress(`validation`,1,1,`Migration validation completed`)}d.success=d.errors.length===0,d.migrationTime=Date.now()-u,logger.info(`Migration completed in ${d.migrationTime}ms`),logger.info(`Documents restored: ${d.documentsRestored}`),logger.info(`Attachments restored: ${d.attachmentsRestored}`),logger.info(`Design docs restored: ${d.designDocsRestored}`),logger.info(`CourseConfig restored: ${d.courseConfigRestored}`),d.errors.length>0&&logger.error(`Migration completed with ${d.errors.length} errors`),d.warnings.length>0&&logger.warn(`Migration completed with ${d.warnings.length} warnings`)}catch(t){d.success=!1,d.migrationTime=Date.now()-u;let m=t instanceof Error?t.message:String(t);if(d.errors.push(`Migration failed: ${m}`),logger.error(`Migration failed:`,t),this.options.cleanupOnFailure)try{await this.cleanupFailedMigration(c)}catch(t){logger.error(`Failed to cleanup after migration failure:`,t),d.warnings.push(`Failed to cleanup after migration failure`)}}return d}async loadManifest(t){try{let c,u;if(this.fs)u=this.fs.joinPath(t,`manifest.json`),c=await this.fs.readFile(u);else if(u=nodeFS2&&nodePath?nodePath.join(t,`manifest.json`):`${t}/manifest.json`,nodeFS2&&this.isLocalPath(t))c=await nodeFS2.promises.readFile(u,`utf8`);else{let t=await fetch(u);if(!t.ok)throw Error(`Failed to fetch manifest: ${t.status} ${t.statusText}`);c=await t.text()}let d=JSON.parse(c);if(!d.version||!d.courseId||!d.chunks)throw Error(`Invalid manifest structure`);return d}catch(t){let c=t instanceof FileSystemError?t.message:`Failed to load manifest: ${t instanceof Error?t.message:String(t)}`;throw Error(c)}}async restoreDesignDocuments(t,c){let u={restored:0,errors:[],warnings:[]};for(let d=0;d<t.length;d++){let m=t[d];this.reportProgress(`design_docs`,d,t.length,`Restoring ${m._id}...`);try{let t;try{t=await c.get(m._id)}catch{}let d={_id:m._id,views:m.views};t?(d._rev=t._rev,logger.debug(`Updating existing design document: ${m._id}`)):logger.debug(`Creating new design document: ${m._id}`),await c.put(d),u.restored++}catch(t){let c=`Failed to restore design document ${m._id}: ${t instanceof Error?t.message:String(t)}`;u.errors.push(c),logger.error(c)}}return this.reportProgress(`design_docs`,t.length,t.length,`Restored ${u.restored} design documents`),u}async aggregateDocuments(t,c){let u=[],d=new Map;for(let m=0;m<c.chunks.length;m++){let g=c.chunks[m];this.reportProgress(`documents`,u.length,c.documentCount,`Loading chunk ${g.id}...`);try{let c=await this.loadChunk(t,g);for(let t of c){if(!t._id){logger.warn(`Document without _id found in chunk ${g.id}, skipping`);continue}d.has(t._id)&&logger.warn(`Duplicate document ID found: ${t._id}, using latest version`),d.set(t._id,t)}}catch(t){throw Error(`Failed to load chunk ${g.id}: ${t instanceof Error?t.message:String(t)}`)}}return u.push(...d.values()),logger.info(`Aggregated ${u.length} unique documents from ${c.chunks.length} chunks`),u}async loadChunk(t,c){try{let u,d;if(this.fs)d=this.fs.joinPath(t,c.path),u=await this.fs.readFile(d);else if(d=nodeFS2&&nodePath?nodePath.join(t,c.path):`${t}/${c.path}`,nodeFS2&&this.isLocalPath(t))u=await nodeFS2.promises.readFile(d,`utf8`);else{let t=await fetch(d);if(!t.ok)throw Error(`Failed to fetch chunk: ${t.status} ${t.statusText}`);u=await t.text()}let m=JSON.parse(u);if(!Array.isArray(m))throw Error(`Chunk file does not contain an array of documents`);return m}catch(t){let c=t instanceof FileSystemError?t.message:`Failed to load chunk: ${t instanceof Error?t.message:String(t)}`;throw Error(c)}}async uploadDocuments(t,c){let u={restored:0,errors:[],warnings:[]},d=this.options.chunkBatchSize;for(let m=0;m<t.length;m+=d){let g=t.slice(m,m+d);this.reportProgress(`documents`,m,t.length,`Uploading batch ${Math.floor(m/d)+1}...`);try{let t=g.map(t=>{let c={...t};return delete c._rev,delete c._attachments,c}),d=await c.bulkDocs(t);for(let t=0;t<d.length;t++){let c=d[t],m=g[t];if(`error`in c){let t=`Failed to upload document ${m._id}: ${c.error} - ${c.reason}`;u.errors.push(t),logger.error(t)}else u.restored++}}catch(t){let c;c=t instanceof Error||t&&typeof t==`object`&&`message`in t?`Failed to upload document batch starting at index ${m}: ${t.message}`:`Failed to upload document batch starting at index ${m}: ${JSON.stringify(t)}`,u.errors.push(c),logger.error(c)}}return this.reportProgress(`documents`,t.length,t.length,`Uploaded ${u.restored} documents`),u}async uploadAttachments(t,c,u){let d={restored:0,errors:[],warnings:[]},m=0;for(let g of c)if(this.reportProgress(`attachments`,m,c.length,`Processing attachments for ${g._id}...`),m++,g._attachments)for(let[c,m]of Object.entries(g._attachments))try{let b=await this.uploadSingleAttachment(t,g._id,c,m,u);b.success?d.restored++:d.errors.push(b.error||`Unknown attachment upload error`)}catch(t){let u=`Failed to upload attachment ${g._id}/${c}: ${t instanceof Error?t.message:String(t)}`;d.errors.push(u),logger.error(u)}return this.reportProgress(`attachments`,c.length,c.length,`Uploaded ${d.restored} attachments`),d}async uploadSingleAttachment(t,c,u,d,m){let g={success:!1,attachmentName:u,docId:c};try{if(!d.path)return g.error=`Attachment metadata missing file path`,g;let b,S;if(this.fs)S=this.fs.joinPath(t,d.path),b=await this.fs.readBinary(S);else if(S=nodeFS2&&nodePath?nodePath.join(t,d.path):`${t}/${d.path}`,nodeFS2&&this.isLocalPath(t))b=await nodeFS2.promises.readFile(S);else{let t=await fetch(S);if(!t.ok)return g.error=`Failed to fetch attachment: ${t.status} ${t.statusText}`,g;b=await t.arrayBuffer()}let C=await m.get(c);await m.putAttachment(c,u,C._rev,b,d.content_type),g.success=!0}catch(t){g.error=t instanceof Error?t.message:String(t)}return g}async restoreCourseConfig(t,c){let u={restored:0,errors:[],warnings:[]};try{if(!t.courseConfig)return u.warnings.push(`No courseConfig found in manifest, skipping CourseConfig document creation`),u;let d={_id:`CourseConfig`,...t.courseConfig,courseID:t.courseId};delete d._rev,await c.put(d),u.restored=1,logger.info(`CourseConfig document created for course: ${t.courseId}`)}catch(t){let c=t instanceof Error?t.message:JSON.stringify(t);u.errors.push(`Failed to restore CourseConfig: ${c}`),logger.error(`CourseConfig restoration failed:`,t)}return u}calculateExpectedCounts(t){let c={};for(let u of t.chunks)c[u.docType]=(c[u.docType]||0)+u.documentCount;return t.designDocs.length>0&&(c._design=t.designDocs.length),c}async cleanupFailedMigration(t){logger.info(`Cleaning up failed migration...`);try{let c=(await t.allDocs()).rows.map(t=>({_id:t.id,_rev:t.value.rev,_deleted:!0}));c.length>0&&(await t.bulkDocs(c),logger.info(`Cleaned up ${c.length} documents from failed migration`))}catch(t){throw logger.error(`Failed to cleanup documents:`,t),t}}reportProgress(t,c,u,d){this.progressCallback&&this.progressCallback({phase:t,current:c,total:u,message:d})}isLocalPath(t){return!t.startsWith(`http://`)&&!t.startsWith(`https://`)}}}}),init_migrator=__esm({"src/util/migrator/index.ts"(){"use strict";init_StaticToCouchDBMigrator(),init_validation(),init_FileSystemAdapter()}}),init_dataDirectory=__esm({"src/util/dataDirectory.ts"(){"use strict";init_logger(),init_factory()}}),init_util2=__esm({"src/util/index.ts"(){"use strict";init_Loggable(),init_packer(),init_migrator(),init_dataDirectory()}}),init_SourceMixer=__esm({"src/study/SourceMixer.ts"(){"use strict";QuotaRoundRobinMixer=class{mix(t,c){if(t.length===0)return[];let u=Math.ceil(c/t.length),d=t.map(t=>[...t.weighted].sort((t,c)=>c.score-t.score).slice(0,u));for(let t=d.length-1;t>0;t--){let c=Math.floor(Math.random()*(t+1));[d[t],d[c]]=[d[c],d[t]]}let m=[],g=0,b=Array(d.length).fill(0);for(;m.length<c&&g<d.length;){g=0;for(let t=0;t<d.length&&!(m.length>=c);t++)b[t]<d[t].length?(m.push(d[t][b[t]]),b[t]++):g++}return m}}}}),init_MixerDebugger=__esm({"src/study/MixerDebugger.ts"(){"use strict";init_logger(),init_navigators(),MAX_RUNS2=10,runHistory2=[],mixerDebugAPI={get runs(){return[...runHistory2]},showRun(t=0){if(runHistory2.length===0){logger.info(`[Mixer Debug] No runs captured yet.`);return}let c;if(typeof t==`number`){if(c=runHistory2[t],!c){logger.info(`[Mixer Debug] No run found at index ${t}. History length: ${runHistory2.length}`);return}}else if(c=runHistory2.find(c=>c.runId.endsWith(t)),!c){logger.info(`[Mixer Debug] No run found matching ID '${t}'.`);return}printMixerSummary(c)},showLastMix(){this.showRun(0)},explainSourceBalance(){if(runHistory2.length===0){logger.info(`[Mixer Debug] No runs captured yet.`);return}let t=runHistory2[0];console.group(`⚖️ Source Balance Analysis`),logger.info(`Mixer: ${t.mixerType}`),logger.info(`Requested limit: ${t.requestedLimit}`),t.quotaPerSource&&logger.info(`Quota per source: ${t.quotaPerSource}`),console.group(`Input Distribution:`);for(let c of t.sourceSummaries){let t=c.sourceName||c.sourceId;logger.info(`${t}:`),logger.info(` Provided: ${c.totalCards} cards (${c.reviewCount} reviews, ${c.newCount} new)`),logger.info(` Score range: [${c.scoreRange[0].toFixed(2)}, ${c.scoreRange[1].toFixed(2)}]`)}console.groupEnd(),console.group(`Selection Results:`);for(let c of t.sourceBreakdowns){let t=c.sourceName||c.sourceId;logger.info(`${t}:`),logger.info(` Selected: ${c.totalSelected}/${c.reviewsProvided+c.newProvided} (${c.selectionRate.toFixed(1)}%)`),logger.info(` Reviews: ${c.reviewsSelected}/${c.reviewsProvided}`),logger.info(` New: ${c.newSelected}/${c.newProvided}`),c.reviewsProvided>0&&c.reviewsSelected===0&&logger.info(` ⚠️ Had reviews but none selected!`),c.totalSelected===0&&c.reviewsProvided+c.newProvided>0&&logger.info(` ⚠️ Had cards but none selected!`)}console.groupEnd();let c=t.sourceBreakdowns.map(t=>t.selectionRate),u=c.reduce((t,c)=>t+c,0)/c.length,d=Math.max(...c.map(t=>Math.abs(t-u)));d>20&&(logger.info(`
378
379
  \u26A0\uFE0F Significant imbalance detected (max deviation: ${d.toFixed(1)}%)`),logger.info(`Possible causes:`),logger.info(` - Score range differences between sources`),logger.info(` - One source has much better quality cards`),logger.info(` - Different card availability (reviews vs new)`)),console.groupEnd()},compareScores(){if(runHistory2.length===0){logger.info(`[Mixer Debug] No runs captured yet.`);return}let t=runHistory2[0];console.group(`📊 Score Distribution Comparison`),console.table(t.sourceSummaries.map(t=>({source:t.sourceName||t.sourceId,cards:t.totalCards,min:t.bottomScore.toFixed(3),max:t.topScore.toFixed(3),avg:t.avgScore.toFixed(3),range:(t.topScore-t.bottomScore).toFixed(3)})));let c=t.sourceSummaries.map(t=>t.topScore-t.bottomScore),u=t.sourceSummaries.map(t=>t.avgScore),d=Math.max(...c)-Math.min(...c),m=Math.max(...u)-Math.min(...u);(d>.3||m>.2)&&(logger.info(`
@@ -415,12 +416,12 @@ Example:
415
416
  window.skuilder.session.showHistory()
416
417
  window.skuilder.session.showInterleaving()
417
418
  window.skuilder.session.showQueue()
418
- `)}},mountSessionDebugger()}}),init_SessionController=__esm({"src/study/SessionController.ts"(){"use strict";var t;init_SrsService(),init_EloService(),init_ResponseProcessor(),init_CardHydrationService(),init_ItemQueue(),init_couch(),init_core(),init_types_legacy(),init_studySession(),init_recording(),init_util2(),init_navigators(),init_Pipeline(),init_SourceMixer(),init_MixerDebugger(),init_SessionDebugger(),init_SessionOverlay(),init_logger(),PERSISTED_RUNNERS_UP=5,SessionController=(t=class _SessionController extends Loggable{set sessionRecord(t){this._sessionRecord=t}get secondsRemaining(){return this._secondsRemaining}get hasCardGuarantee(){return this._minCardsGuarantee>0}get report(){let t=this.supplyQ.dequeueCount;return`${t} supply ${t===1?`card`:`cards`} drawn`}get detailedReport(){return this.supplyQ.toString+`
419
+ `)}},mountSessionDebugger()}}),init_SessionController=__esm({"src/study/SessionController.ts"(){"use strict";var t;init_SrsService(),init_EloService(),init_ResponseProcessor(),init_CardHydrationService(),init_ItemQueue(),init_couch(),init_core(),init_types_legacy(),init_studySession(),init_recording(),init_util2(),init_navigators(),init_Pipeline(),init_versionStamps(),init_SourceMixer(),init_MixerDebugger(),init_SessionDebugger(),init_SessionOverlay(),init_logger(),PERSISTED_RUNNERS_UP=5,SessionController=(t=class _SessionController extends Loggable{set sessionRecord(t){this._sessionRecord=t}get secondsRemaining(){return this._secondsRemaining}get hasCardGuarantee(){return this._minCardsGuarantee>0}get report(){let t=this.supplyQ.dequeueCount;return`${t} supply ${t===1?`card`:`cards`} drawn`}get detailedReport(){return this.supplyQ.toString+`
419
420
  `+this.failedQ.toString}constructor(t,c,u,d,m,g){super(),_defineProperty$2(this,`_className`,`SessionController`),_defineProperty$2(this,`services`,void 0),_defineProperty$2(this,`srsService`,void 0),_defineProperty$2(this,`eloService`,void 0),_defineProperty$2(this,`hydrationService`,void 0),_defineProperty$2(this,`mixer`,void 0),_defineProperty$2(this,`dataLayer`,void 0),_defineProperty$2(this,`courseNameCache`,new Map),_defineProperty$2(this,`_defaultBatchLimit`,20),_defineProperty$2(this,`sources`,void 0),_defineProperty$2(this,`_sessionRecord`,[]),_defineProperty$2(this,`_currentCard`,null),_defineProperty$2(this,`supplyQ`,new ItemQueue),_defineProperty$2(this,`failedQ`,new ItemQueue),_defineProperty$2(this,`_supplyDrawsSinceFailed`,0),_defineProperty$2(this,`_replanPromise`,null),_defineProperty$2(this,`_activeReplanLabel`,null),_defineProperty$2(this,`_wellIndicatedRemaining`,0),_defineProperty$2(this,`_suppressQualityReplan`,!1),_defineProperty$2(this,`_minCardsGuarantee`,0),_defineProperty$2(this,`_sessionHints`,null),_defineProperty$2(this,`_servedCardIds`,new Set),_defineProperty$2(this,`_outcomeObservers`,[]),_defineProperty$2(this,`_sessionControls`,null),_defineProperty$2(this,`sessionId`,void 0),_defineProperty$2(this,`_courseId`,void 0),_defineProperty$2(this,`_stateSnapshotProvider`,void 0),_defineProperty$2(this,`_sessionDoc`,null),_defineProperty$2(this,`_openDocPromise`,null),_defineProperty$2(this,`_runLog`,[]),_defineProperty$2(this,`_eloLog`,[]),_defineProperty$2(this,`_sessionClosed`,!1),_defineProperty$2(this,`startTime`,void 0),_defineProperty$2(this,`endTime`,void 0),_defineProperty$2(this,`_secondsRemaining`,void 0),_defineProperty$2(this,`_intervalHandle`,void 0),this.sessionId=newSessionId(),setDebugSessionId(this.sessionId),this.dataLayer=u,this.mixer=m||new QuotaRoundRobinMixer,this.srsService=new SrsService(u.getUserDB()),this.eloService=new EloService(u,u.getUserDB()),this.hydrationService=new CardHydrationService(d,t=>u.getCourseDB(t),()=>this._getItemsToHydrate()),this.services={response:new ResponseProcessor(this.srsService,this.eloService,t=>this._recordEloEvent(t))},this.sources=t,this.startTime=new Date,this._secondsRemaining=c,this.endTime=new Date(this.startTime.valueOf()+1e3*this._secondsRemaining),g?.defaultBatchLimit!==void 0&&(this._defaultBatchLimit=g.defaultBatchLimit),g?.outcomeObservers?.length&&(this._outcomeObservers=[...g.outcomeObservers]),this._courseId=g?.courseId,this._stateSnapshotProvider=g?.stateSnapshotProvider,this.log(`Session constructed:
420
421
  sessionId: ${this.sessionId}
421
422
  startTime: ${this.startTime}
422
423
  endTime: ${this.endTime}
423
- defaultBatchLimit: ${this._defaultBatchLimit}`),registerActiveController(this)}tick(){this._secondsRemaining=Math.floor((this.endTime.valueOf()-Date.now())/1e3),this._secondsRemaining<=0&&clearInterval(this._intervalHandle)}estimateCleanupTime(){let t=0;for(let c=0;c<this.failedQ.length;c++){let u=this.failedQ.peek(c),d=this._sessionRecord.find(t=>t.item.cardID===u.cardID),m=0;if(d){for(let t=0;t<d.records.length;t++)m+=d.records[t].timeSpent;m/=d.records.length,t+=m}}let c=t/1e3;return this.log(`Failed card cleanup estimate: ${Math.round(c)}`),c}async prepareSession(){if(this.sources.some(t=>typeof t.getWeightedCards!=`function`))throw Error(`[SessionController] All content sources must implement getWeightedCards().`);clearStaleSessionDebugState();let t=await this.getWeightedContent();this._recordRuns(`bootstrap`),this._wellIndicatedRemaining=t,t>=0&&t<_SessionController.MIN_WELL_INDICATED&&this.log(`[Init] Only ${t}/${_SessionController.MIN_WELL_INDICATED} well-indicated cards in initial load`),await this.hydrationService.ensureHydratedCards(),startSessionTracking(this.sessionId,this.supplyQ.length,this.failedQ.length),this._openDocPromise=this._openSessionDoc(),this._intervalHandle=setInterval(()=>{this.tick()},1e3)}_recordRuns(t,c){for(let u of drainCapturedRuns()){if(this._runLog.length>=_SessionController.MAX_LOGGED_RUNS)break;this._runLog.push({runId:u.runId,at:u.timestamp.toISOString(),label:t,...c?{mode:c}:{},generatedCount:u.generatedCount,finalCount:u.finalCount,reviewsSelected:u.reviewsSelected,newSelected:u.newSelected,...typeof u.userElo==`number`?{userElo:u.userElo}:{},...u.generators?{generators:u.generators}:{},...u.filters?{filters:u.filters}:{},...u.hints?{hints:u.hints}:{},...u.discardedTail?{discardedTail:u.discardedTail}:{},cards:persistedRunCards(u),...u.unselectedNew?{unselectedNew:persistedUnselectedNew(u.unselectedNew)}:{},...u.regulators?{regulators:u.regulators.map(persistedReading)}:{}})}}async _captureState(t){if(!this._stateSnapshotProvider)return;let c=3e3;try{return await Promise.race([Promise.resolve(this._stateSnapshotProvider(t)),new Promise(t=>setTimeout(()=>t(void 0),3e3))])}catch(c){this.log(`[Session] state snapshot (${t}) failed: ${c}`);return}}async _openSessionDoc(){if(this._courseId)try{let t=this.dataLayer.getUserDB(),c={_id:makeStudySessionId(this._courseId,t.getUsername(),this.sessionId),docType:`STUDY_SESSION`,sessionId:this.sessionId,courseId:this._courseId,userId:t.getUsername(),startTime:this.startTime.toISOString(),status:`open`,plannedSeconds:Math.round((this.endTime.valueOf()-this.startTime.valueOf())/1e3),config:{defaultBatchLimit:this._defaultBatchLimit,sourceCount:this.sources.length,initHints:this._sessionHints},initialQueues:{supplyQ:this.supplyQ.length,failedQ:this.failedQ.length},runs:[...this._runLog],stateAtStart:await this._captureState(`start`)};this._sessionDoc=c,await t.putStudySession(c),this.log(`[Session] Opened session record ${c._id}`)}catch(t){logger.warn(`[SessionController] Failed to open session record: ${t}`)}}async requestReplan(t){let c=this.normalizeReplanOptions(t),u=this._replanHasIntent(c);if(this._replanPromise){if(!u)return this.log(`Replan already in progress, coalescing unhinted auto-replan`),this._replanPromise;let t=c.label?` [${c.label}]`:``;this.log(`Replan in progress; queueing hint-bearing replan${t} behind in-flight run`);let d=this._replanPromise.catch(()=>void 0).then(()=>this._runReplan(c)),m=d.finally(()=>{this._replanPromise===m&&(this._replanPromise=null,this._activeReplanLabel=null)});return this._replanPromise=m,d}let d=this._runReplan(c),m=d.finally(()=>{this._replanPromise===m&&(this._replanPromise=null,this._activeReplanLabel=null)});this._replanPromise=m,await d}_replanHasIntent(t){return!!(t.limit!==void 0||t.minFollowUpCards!==void 0||t.mode&&t.mode!==`replace`||t.hints&&Object.keys(t.hints).length>0||t.sessionHints!==void 0||t.mergeSessionHints!==void 0)}async _runReplan(t){this._activeReplanLabel=t.label??`(auto)`,t.hints||(t.hints={});let c=t.hints,u=new Set(c.excludeCards??[]);this._currentCard?.item.cardID&&u.add(this._currentCard.item.cardID);for(let t of this._sessionRecord)u.add(t.card.card_id);this.supplyQ.length>0&&u.add(this.supplyQ.peek(0).cardID),c.excludeCards=[...u],t.sessionHints!==void 0&&(this._sessionHints=t.sessionHints,this.log(`[Replan] Session hints ${t.sessionHints?`set`:`cleared`}: ${JSON.stringify(t.sessionHints)}`)),t.mergeSessionHints!==void 0&&(this._sessionHints=mergeHints2([this._sessionHints,t.mergeSessionHints])??null,this.log(`[Replan] Session hints merged: ${JSON.stringify(this._sessionHints)}`)),this._applyHintsToSources(t.hints,t.label);let d=t.label?` [${t.label}]`:``;this.log(`Mid-session replan requested${d} (limit: ${t.limit??`default`}, mode: ${t.mode??`replace`}${t.hints?`, with hints`:``})`),t.minFollowUpCards!==void 0&&t.minFollowUpCards>0&&(this._minCardsGuarantee=Math.max(this._minCardsGuarantee,t.minFollowUpCards),this.log(`[Replan] Card guarantee set to ${this._minCardsGuarantee}`)),await this._executeReplan(t)}setSessionHints(t){this._sessionHints=t,this.log(`Session hints ${t?`set`:`cleared`}: ${JSON.stringify(t)}`)}getSessionHints(){return this._sessionHints}getDebugSnapshot(){let describe=t=>{let c=[];for(let u=0;u<t.length;u++){let d=t.peek(u);c.push({cardID:d.cardID,status:d.status,origin:isReview(d)?`review`:`new`,score:d.score})}return{length:t.length,dequeueCount:t.dequeueCount,cards:c}},t=this._sessionRecord.map(t=>{let c=t.records[t.records.length-1];return{cardID:t.item.cardID,status:t.item.status,attempts:t.records.length,correct:c&&isQuestionRecord(c)?c.isCorrect:null,timeSpentMs:t.records.reduce((t,c)=>t+c.timeSpent,0)}});return{sessionId:this.sessionId,secondsRemaining:this.secondsRemaining,hasCardGuarantee:this.hasCardGuarantee,minCardsGuarantee:this._minCardsGuarantee,wellIndicatedRemaining:this._wellIndicatedRemaining,currentCard:this._currentCard?.item.cardID??null,sessionHints:this._sessionHints,replanActive:this._replanPromise!==null,replanLabel:this._activeReplanLabel,supplyQ:describe(this.supplyQ),failedQ:describe(this.failedQ),reviewBacklog:getSrsBacklogDebug(),strategyPressure:getStrategyPressureDebug(),drawnCards:t}}mergeSessionHints(t){this._sessionHints=mergeHints2([this._sessionHints,t])??null,this.log(`Session hints merged: ${JSON.stringify(this._sessionHints)}`)}_applyHintsToSources(t,c){let u=t&&c?{...t,_label:c}:t,d=mergeHints2([this._sessionHints,u]);if(d)for(let t of this.sources)t.setEphemeralHints?.(d)}_getSessionControls(){return this._sessionControls||(this._sessionControls={getSessionHints:()=>this.getSessionHints(),setSessionHints:t=>this.setSessionHints(t),mergeSessionHints:t=>this.mergeSessionHints(t),requestReplan:t=>this.requestReplan(t)}),this._sessionControls}_recordEloEvent(t){this._eloLog.length>=_SessionController.MAX_LOGGED_ELO_EVENTS||this._eloLog.push(t)}async _notifyOutcomeObservers(t,c,u){if(this._outcomeObservers.length===0||!isQuestionRecord(t))return;let d={record:t,card:c.card,result:u},m=this._getSessionControls();for(let t of this._outcomeObservers)try{await t(d,m)}catch(t){this.error(`[OutcomeObserver] observer threw; ignoring`,t)}}async _replanUncoalesced(t){let c=this._runReplan(t),u=c.finally(()=>{this._replanPromise===u&&(this._replanPromise=null,this._activeReplanLabel=null)});this._replanPromise=u,await c}normalizeReplanOptions(t){if(!t)return{};let c=[`hints`,`sessionHints`,`limit`,`mode`,`label`,`minFollowUpCards`];return Object.keys(t).some(t=>c.includes(t))?t:{hints:t}}async _executeReplan(t={}){let c=t.limit,u=t.mode??`replace`,d=await this.getWeightedContent({replan:!0,additive:u===`merge`,limit:c});this._recordRuns(t.label??`(auto)`,u),this._wellIndicatedRemaining=d,c!==void 0&&c<this._defaultBatchLimit?(this._suppressQualityReplan=!0,this.log(`[Replan] Burst mode (limit=${c}): suppressing quality-based auto-replan`)):this._suppressQualityReplan=!1,d>=0&&d<_SessionController.MIN_WELL_INDICATED&&this.log(`[Replan] Only ${d}/${_SessionController.MIN_WELL_INDICATED} well-indicated cards after replan`),await this.hydrationService.ensureHydratedCards();let m=t.label?` [${t.label}]`:``;this.log(`Replan complete${m}: supplyQ now has ${this.supplyQ.length} cards (mode=${u})`),snapshotQueues(this.supplyQ.length,this.failedQ.length)}addTime(t){this.endTime=new Date(this.endTime.valueOf()+1e3*t)}get failedCount(){return this.failedQ.length}toString(){return`Session: ${this.supplyQ.length} supply, ${this.failedQ.length} failed`}reportString(){return`${this.supplyQ.dequeueCount} supply, ${this.failedQ.dequeueCount} failed`}getDebugInfo(){let t=this.sources.some(t=>typeof t.getWeightedCards==`function`),extractQueueItems=(t,c=10)=>{let u=[];for(let d=0;d<Math.min(t.length,c);d++){let c=t.peek(d);u.push({courseID:c.courseID||`unknown`,cardID:c.cardID||`unknown`,status:c.status||`unknown`,score:c.score})}return u};return{api:{mode:t?`weighted`:`legacy`,description:t?`Using getWeightedCards() API with scored candidates`:`ERROR: getWeightedCards() not a function.`},supplyQueue:{length:this.supplyQ.length,dequeueCount:this.supplyQ.dequeueCount,items:extractQueueItems(this.supplyQ)},failedQueue:{length:this.failedQ.length,dequeueCount:this.failedQ.dequeueCount,items:extractQueueItems(this.failedQ)},hydratedCache:{count:this.hydrationService.hydratedCount,cardIds:this.hydrationService.getHydratedCardIds()},replan:{inProgress:this._replanPromise!==null,suppressQualityReplan:this._suppressQualityReplan,defaultBatchLimit:this._defaultBatchLimit,minCardsGuarantee:this._minCardsGuarantee}}}async getWeightedContent(t){let c=t?.replan??!1,u=t?.additive??!1,d=t?.limit??this._defaultBatchLimit,m=d;c||this._applyHintsToSources();let g=[];for(let t=0;t<this.sources.length;t++){let u=this.sources[t];try{let c=(await u.getWeightedCards(m)).cards;g.push({sourceIndex:t,weighted:c})}catch(u){if(this.error(`Failed to get content from source ${t}:`,u),this.sources.length===1&&!c)throw Error(`Cannot start session: failed to load content from source ${t}`)}}if(g.length===0){if(c)return this.log(`Replan: no content from any source, keeping existing supplyQ`),-1;throw Error(`Cannot start session: failed to load content from all ${this.sources.length} source(s). Check logs for details.`)}let b=this.mixer.mix(g,m*this.sources.length),S=g.map(t=>t.weighted[0]?.courseId||`source-${t.sourceIndex}`);await Promise.all(S.map(async t=>{if(!this.courseNameCache.has(t))try{let c=await this.dataLayer.getCoursesDB().getCourseConfig(t);this.courseNameCache.set(t,c.name)}catch{}}));let C=S.map(t=>this.courseNameCache.get(t)),w=this.mixer instanceof QuotaRoundRobinMixer?Math.ceil(m*this.sources.length/g.length):void 0;captureMixerRun(this.mixer.constructor.name,g,S,C,m*this.sources.length,w,b);let T=b.filter(t=>!this._servedCardIds.has(t.cardId)),E=T.filter(t=>t.score===1/0),D=T.filter(t=>t.score!==1/0),O=[...E,...D.slice(0,Math.max(0,d-E.length))],xr=new Set(E.map(t=>t.cardId)),Sr=O.filter(t=>t.score>=_SessionController.WELL_INDICATED_SCORE).length,Cr=c?`Replan content:
424
+ defaultBatchLimit: ${this._defaultBatchLimit}`),registerActiveController(this)}tick(){this._secondsRemaining=Math.floor((this.endTime.valueOf()-Date.now())/1e3),this._secondsRemaining<=0&&clearInterval(this._intervalHandle)}estimateCleanupTime(){let t=0;for(let c=0;c<this.failedQ.length;c++){let u=this.failedQ.peek(c),d=this._sessionRecord.find(t=>t.item.cardID===u.cardID),m=0;if(d){for(let t=0;t<d.records.length;t++)m+=d.records[t].timeSpent;m/=d.records.length,t+=m}}let c=t/1e3;return this.log(`Failed card cleanup estimate: ${Math.round(c)}`),c}async prepareSession(){if(this.sources.some(t=>typeof t.getWeightedCards!=`function`))throw Error(`[SessionController] All content sources must implement getWeightedCards().`);clearStaleSessionDebugState();let t=await this.getWeightedContent();this._recordRuns(`bootstrap`),this._wellIndicatedRemaining=t,t>=0&&t<_SessionController.MIN_WELL_INDICATED&&this.log(`[Init] Only ${t}/${_SessionController.MIN_WELL_INDICATED} well-indicated cards in initial load`),await this.hydrationService.ensureHydratedCards(),startSessionTracking(this.sessionId,this.supplyQ.length,this.failedQ.length),this._openDocPromise=this._openSessionDoc(),this._intervalHandle=setInterval(()=>{this.tick()},1e3)}_recordRuns(t,c){for(let u of drainCapturedRuns()){if(this._runLog.length>=_SessionController.MAX_LOGGED_RUNS)break;this._runLog.push({runId:u.runId,at:u.timestamp.toISOString(),label:t,...c?{mode:c}:{},generatedCount:u.generatedCount,finalCount:u.finalCount,reviewsSelected:u.reviewsSelected,newSelected:u.newSelected,...typeof u.userElo==`number`?{userElo:u.userElo}:{},...u.generators?{generators:u.generators}:{},...u.filters?{filters:u.filters}:{},...u.hints?{hints:u.hints}:{},...u.discardedTail?{discardedTail:u.discardedTail}:{},cards:persistedRunCards(u),...u.unselectedNew?{unselectedNew:persistedUnselectedNew(u.unselectedNew)}:{},...u.regulators?{regulators:u.regulators.map(persistedReading)}:{},...u.versions?{versions:u.versions}:{}})}}async _captureState(t){if(!this._stateSnapshotProvider)return;let c=3e3;try{return await Promise.race([Promise.resolve(this._stateSnapshotProvider(t)),new Promise(t=>setTimeout(()=>t(void 0),3e3))])}catch(c){this.log(`[Session] state snapshot (${t}) failed: ${c}`);return}}async _openSessionDoc(){if(this._courseId)try{let t=this.dataLayer.getUserDB(),c={_id:makeStudySessionId(this._courseId,t.getUsername(),this.sessionId),docType:`STUDY_SESSION`,sessionId:this.sessionId,courseId:this._courseId,userId:t.getUsername(),startTime:this.startTime.toISOString(),status:`open`,plannedSeconds:Math.round((this.endTime.valueOf()-this.startTime.valueOf())/1e3),config:{defaultBatchLimit:this._defaultBatchLimit,sourceCount:this.sources.length,initHints:this._sessionHints},versions:sessionVersions(),initialQueues:{supplyQ:this.supplyQ.length,failedQ:this.failedQ.length},runs:[...this._runLog],stateAtStart:await this._captureState(`start`)};this._sessionDoc=c,await t.putStudySession(c),this.log(`[Session] Opened session record ${c._id}`)}catch(t){logger.warn(`[SessionController] Failed to open session record: ${t}`)}}async requestReplan(t){let c=this.normalizeReplanOptions(t),u=this._replanHasIntent(c);if(this._replanPromise){if(!u)return this.log(`Replan already in progress, coalescing unhinted auto-replan`),this._replanPromise;let t=c.label?` [${c.label}]`:``;this.log(`Replan in progress; queueing hint-bearing replan${t} behind in-flight run`);let d=this._replanPromise.catch(()=>void 0).then(()=>this._runReplan(c)),m=d.finally(()=>{this._replanPromise===m&&(this._replanPromise=null,this._activeReplanLabel=null)});return this._replanPromise=m,d}let d=this._runReplan(c),m=d.finally(()=>{this._replanPromise===m&&(this._replanPromise=null,this._activeReplanLabel=null)});this._replanPromise=m,await d}_replanHasIntent(t){return!!(t.limit!==void 0||t.minFollowUpCards!==void 0||t.mode&&t.mode!==`replace`||t.hints&&Object.keys(t.hints).length>0||t.sessionHints!==void 0||t.mergeSessionHints!==void 0)}async _runReplan(t){this._activeReplanLabel=t.label??`(auto)`,t.hints||(t.hints={});let c=t.hints,u=new Set(c.excludeCards??[]);this._currentCard?.item.cardID&&u.add(this._currentCard.item.cardID);for(let t of this._sessionRecord)u.add(t.card.card_id);this.supplyQ.length>0&&u.add(this.supplyQ.peek(0).cardID),c.excludeCards=[...u],t.sessionHints!==void 0&&(this._sessionHints=t.sessionHints,this.log(`[Replan] Session hints ${t.sessionHints?`set`:`cleared`}: ${JSON.stringify(t.sessionHints)}`)),t.mergeSessionHints!==void 0&&(this._sessionHints=mergeHints2([this._sessionHints,t.mergeSessionHints])??null,this.log(`[Replan] Session hints merged: ${JSON.stringify(this._sessionHints)}`)),this._applyHintsToSources(t.hints,t.label);let d=t.label?` [${t.label}]`:``;this.log(`Mid-session replan requested${d} (limit: ${t.limit??`default`}, mode: ${t.mode??`replace`}${t.hints?`, with hints`:``})`),t.minFollowUpCards!==void 0&&t.minFollowUpCards>0&&(this._minCardsGuarantee=Math.max(this._minCardsGuarantee,t.minFollowUpCards),this.log(`[Replan] Card guarantee set to ${this._minCardsGuarantee}`)),await this._executeReplan(t)}setSessionHints(t){this._sessionHints=t,this.log(`Session hints ${t?`set`:`cleared`}: ${JSON.stringify(t)}`)}getSessionHints(){return this._sessionHints}getDebugSnapshot(){let describe=t=>{let c=[];for(let u=0;u<t.length;u++){let d=t.peek(u);c.push({cardID:d.cardID,status:d.status,origin:isReview(d)?`review`:`new`,score:d.score})}return{length:t.length,dequeueCount:t.dequeueCount,cards:c}},t=this._sessionRecord.map(t=>{let c=t.records[t.records.length-1];return{cardID:t.item.cardID,status:t.item.status,attempts:t.records.length,correct:c&&isQuestionRecord(c)?c.isCorrect:null,timeSpentMs:t.records.reduce((t,c)=>t+c.timeSpent,0)}});return{sessionId:this.sessionId,secondsRemaining:this.secondsRemaining,hasCardGuarantee:this.hasCardGuarantee,minCardsGuarantee:this._minCardsGuarantee,wellIndicatedRemaining:this._wellIndicatedRemaining,currentCard:this._currentCard?.item.cardID??null,sessionHints:this._sessionHints,replanActive:this._replanPromise!==null,replanLabel:this._activeReplanLabel,supplyQ:describe(this.supplyQ),failedQ:describe(this.failedQ),reviewBacklog:getSrsBacklogDebug(),strategyPressure:getStrategyPressureDebug(),drawnCards:t}}mergeSessionHints(t){this._sessionHints=mergeHints2([this._sessionHints,t])??null,this.log(`Session hints merged: ${JSON.stringify(this._sessionHints)}`)}_applyHintsToSources(t,c){let u=t&&c?{...t,_label:c}:t,d=mergeHints2([this._sessionHints,u]);if(d)for(let t of this.sources)t.setEphemeralHints?.(d)}_getSessionControls(){return this._sessionControls||(this._sessionControls={getSessionHints:()=>this.getSessionHints(),setSessionHints:t=>this.setSessionHints(t),mergeSessionHints:t=>this.mergeSessionHints(t),requestReplan:t=>this.requestReplan(t)}),this._sessionControls}_recordEloEvent(t){this._eloLog.length>=_SessionController.MAX_LOGGED_ELO_EVENTS||this._eloLog.push(t)}async _notifyOutcomeObservers(t,c,u){if(this._outcomeObservers.length===0||!isQuestionRecord(t))return;let d={record:t,card:c.card,result:u},m=this._getSessionControls();for(let t of this._outcomeObservers)try{await t(d,m)}catch(t){this.error(`[OutcomeObserver] observer threw; ignoring`,t)}}async _replanUncoalesced(t){let c=this._runReplan(t),u=c.finally(()=>{this._replanPromise===u&&(this._replanPromise=null,this._activeReplanLabel=null)});this._replanPromise=u,await c}normalizeReplanOptions(t){if(!t)return{};let c=[`hints`,`sessionHints`,`limit`,`mode`,`label`,`minFollowUpCards`];return Object.keys(t).some(t=>c.includes(t))?t:{hints:t}}async _executeReplan(t={}){let c=t.limit,u=t.mode??`replace`,d=await this.getWeightedContent({replan:!0,additive:u===`merge`,limit:c});this._recordRuns(t.label??`(auto)`,u),this._wellIndicatedRemaining=d,c!==void 0&&c<this._defaultBatchLimit?(this._suppressQualityReplan=!0,this.log(`[Replan] Burst mode (limit=${c}): suppressing quality-based auto-replan`)):this._suppressQualityReplan=!1,d>=0&&d<_SessionController.MIN_WELL_INDICATED&&this.log(`[Replan] Only ${d}/${_SessionController.MIN_WELL_INDICATED} well-indicated cards after replan`),await this.hydrationService.ensureHydratedCards();let m=t.label?` [${t.label}]`:``;this.log(`Replan complete${m}: supplyQ now has ${this.supplyQ.length} cards (mode=${u})`),snapshotQueues(this.supplyQ.length,this.failedQ.length)}addTime(t){this.endTime=new Date(this.endTime.valueOf()+1e3*t)}get failedCount(){return this.failedQ.length}toString(){return`Session: ${this.supplyQ.length} supply, ${this.failedQ.length} failed`}reportString(){return`${this.supplyQ.dequeueCount} supply, ${this.failedQ.dequeueCount} failed`}getDebugInfo(){let t=this.sources.some(t=>typeof t.getWeightedCards==`function`),extractQueueItems=(t,c=10)=>{let u=[];for(let d=0;d<Math.min(t.length,c);d++){let c=t.peek(d);u.push({courseID:c.courseID||`unknown`,cardID:c.cardID||`unknown`,status:c.status||`unknown`,score:c.score})}return u};return{api:{mode:t?`weighted`:`legacy`,description:t?`Using getWeightedCards() API with scored candidates`:`ERROR: getWeightedCards() not a function.`},supplyQueue:{length:this.supplyQ.length,dequeueCount:this.supplyQ.dequeueCount,items:extractQueueItems(this.supplyQ)},failedQueue:{length:this.failedQ.length,dequeueCount:this.failedQ.dequeueCount,items:extractQueueItems(this.failedQ)},hydratedCache:{count:this.hydrationService.hydratedCount,cardIds:this.hydrationService.getHydratedCardIds()},replan:{inProgress:this._replanPromise!==null,suppressQualityReplan:this._suppressQualityReplan,defaultBatchLimit:this._defaultBatchLimit,minCardsGuarantee:this._minCardsGuarantee}}}async getWeightedContent(t){let c=t?.replan??!1,u=t?.additive??!1,d=t?.limit??this._defaultBatchLimit,m=d;c||this._applyHintsToSources();let g=[];for(let t=0;t<this.sources.length;t++){let u=this.sources[t];try{let c=(await u.getWeightedCards(m)).cards;g.push({sourceIndex:t,weighted:c})}catch(u){if(this.error(`Failed to get content from source ${t}:`,u),this.sources.length===1&&!c)throw Error(`Cannot start session: failed to load content from source ${t}`)}}if(g.length===0){if(c)return this.log(`Replan: no content from any source, keeping existing supplyQ`),-1;throw Error(`Cannot start session: failed to load content from all ${this.sources.length} source(s). Check logs for details.`)}let b=this.mixer.mix(g,m*this.sources.length),S=g.map(t=>t.weighted[0]?.courseId||`source-${t.sourceIndex}`);await Promise.all(S.map(async t=>{if(!this.courseNameCache.has(t))try{let c=await this.dataLayer.getCoursesDB().getCourseConfig(t);this.courseNameCache.set(t,c.name)}catch{}}));let C=S.map(t=>this.courseNameCache.get(t)),w=this.mixer instanceof QuotaRoundRobinMixer?Math.ceil(m*this.sources.length/g.length):void 0;captureMixerRun(this.mixer.constructor.name,g,S,C,m*this.sources.length,w,b);let T=b.filter(t=>!this._servedCardIds.has(t.cardId)),E=T.filter(t=>t.score===1/0),D=T.filter(t=>t.score!==1/0),O=[...E,...D.slice(0,Math.max(0,d-E.length))],xr=new Set(E.map(t=>t.cardId)),Sr=O.filter(t=>t.score>=_SessionController.WELL_INDICATED_SCORE).length,Cr=c?`Replan content:
424
425
  `:`Mixed content session created with:
425
426
  `,wr=O.map(t=>{let c=getCardOrigin(t),u=Number.isFinite(t.score)?t.score.toFixed(2):`+INF`;return Cr+=`${c===`review`?`Review`:`New`}: ${t.courseId}::${t.cardId} (score: ${u})
426
427
  `,this._buildSupplyItem(t,c)});if(u){let t=this.supplyQ.mergeToFront(wr,t=>t.cardID,xr);Cr+=`Additive merge: ${t} cards added to front of supplyQ
@@ -435,7 +436,7 @@ Currently logged-in as ${this._username}.`);let u=await this.syncStrategy.create
435
436
  if (doc._id && doc._id.indexOf('card_review') === 0 && doc.courseId && doc.cardId) {
436
437
  emit(doc._id, doc.courseId + '-' + doc.cardId);
437
438
  }
438
- }`}}}]),t),userCoursesDoc=`CourseRegistrations`,userClassroomsDoc=`ClassroomRegistrations`}}),init_common=__esm({"src/impl/common/index.ts"(){"use strict";init_SyncStrategy(),init_BaseUserDB(),init_userDBHelpers()}}),PouchDataLayerProvider_exports={},__export(PouchDataLayerProvider_exports,{CouchDataLayerProvider:()=>CouchDataLayerProvider}),init_PouchDataLayerProvider=__esm({"src/impl/couch/PouchDataLayerProvider.ts"(){"use strict";init_logger(),init_dataDirectory(),init_adminDB2(),init_classroomDB2(),init_courseDB(),init_CourseSyncService(),init_common(),init_CouchDBSyncStrategy(),CouchDataLayerProvider=class{constructor(t){_defineProperty$2(this,`initialized`,!1),_defineProperty$2(this,`userDB`,void 0),_defineProperty$2(this,`currentUsername`,``),_defineProperty$2(this,`_courseIDs`,[]),t&&(this._courseIDs=t)}async initialize(){if(!this.initialized){if(typeof process<`u`&&process.versions!=null&&process.versions.node!=null){logger.info(`CouchDataLayerProvider: Running in Node.js environment, creating guest UserDB for testing.`),await initializeDataDirectory();let t=new CouchDBSyncStrategy;this.userDB=await BaseUser.instance(t)}else{let t=new CouchDBSyncStrategy;this.userDB=await BaseUser.instance(t),this.currentUsername=this.userDB.getUsername(),logger.debug(`Current username: ${this.currentUsername}`)}this.initialized=!0}}async teardown(){this.initialized=!1}getUserDB(){return this.userDB}getCourseDB(t){let c=CourseSyncService.getInstance().getLocalDB(t);return new CourseDB(t,async()=>this.getUserDB(),c??void 0)}async ensureCourseSynced(t,c){return CourseSyncService.getInstance().ensureSynced(t,c)}getCoursesDB(){return new CoursesDB(this._courseIDs)}async getClassroomDB(t,c){return c===`student`?await StudentClassroomDB.factory(t,this.getUserDB()):await TeacherClassroomDB.factory(t)}getAdminDB(){return new AdminDB}isReadOnly(){return!1}}}}),init_StaticDataUnpacker=__esm({"src/impl/static/StaticDataUnpacker.ts"(){"use strict";init_logger(),init_core(),pathUtils={isAbsolute:t=>!!(/^[a-zA-Z]:[\\/]/.test(t)||/^\\\\/.test(t)||t.startsWith(`/`))},nodeFS3=null;try{typeof window>`u`&&typeof process<`u`&&process.versions?.node&&(nodeFS3=eval(`require`)(`fs`))}catch{}StaticDataUnpacker=class{constructor(t,c){_defineProperty$2(this,`manifest`,void 0),_defineProperty$2(this,`basePath`,void 0),_defineProperty$2(this,`documentCache`,new Map),_defineProperty$2(this,`chunkCache`,new Map),_defineProperty$2(this,`indexCache`,new Map),this.manifest=t,this.basePath=c}async getDocument(t){if(this.documentCache.has(t)){let c=this.documentCache.get(t);return await this.hydrateAttachments(c)}let c=await this.findChunkForDocument(t);if(!c)throw logger.error(`Document ${t} not found in any chunk. Available chunks:`,this.manifest.chunks.map(t=>`${t.id} (${t.docType}): ${t.startKey} - ${t.endKey}`)),Error(`Document ${t} not found in any chunk`);if(await this.loadChunk(c.id),this.documentCache.has(t)){let c=this.documentCache.get(t);return await this.hydrateAttachments(c)}throw logger.error(`Document ${t} not found in chunk ${c.id}`),Error(`Document ${t} not found in chunk ${c.id}`)}async getAllDocumentsByPrefix(t){let c=this.manifest.chunks.filter(c=>{let u=t+`￰`;return c.startKey<=u&&c.endKey>=t});if(c.length===0)return logger.debug(`[StaticDataUnpacker] No chunks found for prefix: ${t}`),[];await Promise.all(c.map(t=>this.loadChunk(t.id)));let u=[];for(let[c,d]of this.documentCache.entries())c.startsWith(t)&&u.push(await this.hydrateAttachments(d));return logger.debug(`[StaticDataUnpacker] Found ${u.length} documents with prefix: ${t}`),u}async queryByElo(t,c=25){let u=await this.loadIndex(`elo`);if(!u||!u.sorted)return logger.warn(`ELO index not found or malformed, returning empty results`),[];let d=u.sorted,m=0,g=0,b=d.length-1;for(;g<=b;){let c=Math.floor((g+b)/2);d[c].elo<t?g=c+1:b=c-1}m=g;let S=[],C=Math.floor(c/2);for(let t=Math.max(0,m-C);t<m&&S.length<c;t++)S.push(d[t].cardId);for(let t=m;t<d.length&&S.length<c;t++)S.push(d[t].cardId);return S}async getTagsIndex(){try{return await this.loadIndex(`tags`)}catch{return{byCard:{},byTag:{}}}}getDocTypeFromId(t){for(let c in DocTypePrefixes){let u=DocTypePrefixes[c];if(t.startsWith(`${u}-`))return c}}async findChunkForDocument(t){let c=this.getDocTypeFromId(t);if(c){let u=this.manifest.chunks.filter(t=>t.docType===c);for(let c of u)if(t>=c.startKey&&t<=c.endKey&&await this.verifyDocumentInChunk(t,c))return c}else{for(let c of this.manifest.chunks)if(t>=c.startKey&&t<=c.endKey&&await this.verifyDocumentInChunk(t,c))return c;let c=this.manifest.chunks.filter(t=>t.docType!==`CARD`&&t.docType!==`DISPLAYABLE_DATA`&&t.docType!==`TAG`);for(let u of c)if(t>=u.startKey&&t<=u.endKey&&await this.verifyDocumentInChunk(t,u))return u;return}}async verifyDocumentInChunk(t,c){try{return await this.loadChunk(c.id),this.documentCache.has(t)}catch{return!1}}async loadChunk(t){if(this.chunkCache.has(t))return;let c=this.manifest.chunks.find(c=>c.id===t);if(!c)throw Error(`Chunk ${t} not found in manifest`);try{let u=`${this.basePath}/${c.path}`;logger.debug(`Loading chunk from ${u}`);let d;if(this.isLocalPath(u)&&nodeFS3){let t=await nodeFS3.promises.readFile(u,`utf8`);d=JSON.parse(t)}else{let c=await fetch(u);if(!c.ok)throw Error(`Failed to fetch chunk ${t}: ${c.status} ${c.statusText}`);d=await c.json()}this.chunkCache.set(t,d);for(let t of d)t._id&&this.documentCache.set(t._id,t);logger.debug(`Loaded ${d.length} documents from chunk ${t}`)}catch(c){throw logger.error(`Failed to load chunk ${t}:`,c),c}}async loadIndex(t){if(this.indexCache.has(t))return this.indexCache.get(t);let c=this.manifest.indices.find(c=>c.name===t);if(!c)throw Error(`Index ${t} not found in manifest`);try{let u=`${this.basePath}/${c.path}`;logger.debug(`Loading index from ${u}`);let d;if(this.isLocalPath(u)&&nodeFS3){let t=await nodeFS3.promises.readFile(u,`utf8`);d=JSON.parse(t)}else{let c=await fetch(u);if(!c.ok)throw Error(`Failed to fetch index ${t}: ${c.status} ${c.statusText}`);d=await c.json()}return this.indexCache.set(t,d),logger.debug(`Loaded index ${t}`),d}catch(c){throw logger.error(`Failed to load index ${t}:`,c),c}}async getRawDocument(t){if(this.documentCache.has(t))return this.documentCache.get(t);let c=await this.findChunkForDocument(t);if(!c)throw logger.error(`Document ${t} not found in any chunk. Available chunks:`,this.manifest.chunks.map(t=>`${t.id} (${t.docType}): ${t.startKey} - ${t.endKey}`)),Error(`Document ${t} not found in any chunk`);if(await this.loadChunk(c.id),this.documentCache.has(t))return this.documentCache.get(t);throw logger.error(`Document ${t} not found in chunk ${c.id}`),Error(`Document ${t} not found in chunk ${c.id}`)}getAttachmentUrl(t,c){return`${this.basePath}/attachments/${t}/${c}`}async getAttachmentPath(t,c){try{let u=await this.getRawDocument(t);if(u._attachments&&u._attachments[c]){let t=u._attachments[c];if(t.path)return`${this.basePath}/${t.path}`}return null}catch{return null}}async getAttachmentBlob(t,c){let u=await this.getAttachmentPath(t,c);if(!u)return null;try{if(this.isLocalPath(u)&&nodeFS3)return await nodeFS3.promises.readFile(u);{let d=await fetch(u);if(!d.ok)throw Error(`Failed to fetch attachment ${t}/${c}: ${d.status} ${d.statusText}`);return await d.blob()}}catch(u){return logger.error(`Failed to load attachment ${t}/${c}:`,u),null}}async hydrateAttachments(t){let c=t;if(!c._attachments)return t;let u=JSON.parse(JSON.stringify(t));for(let[t,d]of Object.entries(c._attachments)){let m=d;if(m.path)try{let d=await this.getAttachmentBlob(c._id,t);d?typeof window<`u`&&window.URL?u._attachments[t]={...m,data:d,stub:!1}:u._attachments[t]={...m,buffer:d}:logger.warn(`[hydrateAttachments] getAttachmentBlob returned null for ${c._id}/${t}. Skipping hydration for this attachment.`)}catch(u){logger.warn(`[hydrateAttachments] Failed to hydrate attachment ${c._id}/${t}:`,u)}else logger.debug(`[hydrateAttachments] Attachment ${t} for doc ${c._id} has no path. Skipping blob conversion.`)}return u}clearCaches(){this.documentCache.clear(),this.chunkCache.clear(),this.indexCache.clear()}getCacheStats(){return{documents:this.documentCache.size,chunks:this.chunkCache.size,indices:this.indexCache.size}}isLocalPath(t){return!t.startsWith(`http://`)&&!t.startsWith(`https://`)&&(pathUtils.isAbsolute(t)||t.startsWith(`./`)||t.startsWith(`../`))}}}}),init_courseDB2=__esm({"src/impl/static/courseDB.ts"(){"use strict";init_types_legacy(),init_logger(),init_defaults(),init_PipelineAssembler(),StaticCourseDB=class{constructor(t,c,u,d){_defineProperty$2(this,`_pendingHints`,null),this.courseId=t,this.unpacker=c,this.userDB=u,this.manifest=d}getCourseID(){return this.courseId}async getCourseConfig(){if(this.manifest.courseConfig!=null)return this.manifest.courseConfig;throw Error(`Course config not found for course ${this.courseId}`)}async updateCourseConfig(t){throw Error(`Cannot update course config in static mode`)}async getCourseInfo(){return{cardCount:this.manifest.chunks.filter(t=>t.docType===`CARD`).reduce((t,c)=>t+c.documentCount,0),registeredUsers:0}}async getCourseDoc(t,c){return this.unpacker.getDocument(t)}async getCourseDocs(t,c){let u=await Promise.all(t.map(async t=>{try{return{id:t,key:t,value:{rev:`1-static`},doc:await this.unpacker.getDocument(t)}}catch{return{key:t,error:`not_found`}}}));return{total_rows:t.length,offset:0,rows:u}}async getCardsByELO(t,c){return(await this.unpacker.queryByElo(t,c||25)).map(t=>{let[c,u,d]=t.split(`-`);return{courseID:c,cardID:u,elo:d?parseInt(d):void 0}})}async getCardEloData(t){return await Promise.all(t.map(async t=>{try{return(await this.unpacker.getDocument(t)).elo||{global:{score:1e3,count:0},tags:{},misc:{}}}catch{return{global:{score:1e3,count:0},tags:{},misc:{}}}}))}async updateCardElo(t,c){return{ok:!0,id:t,rev:`1-static`}}async getCardsCenteredAtELO(t,c){let u=typeof t.elo==`number`?t.elo:1e3;if(t.elo===`user`)try{let t=(await this.userDB.getCourseRegistrationsDoc()).courses.find(t=>t.courseID===this.courseId);t&&typeof t.elo==`object`&&(u=t.elo.global.score)}catch{u=1e3}else t.elo===`random`&&(u=800+Math.random()*400);let d=(await this.unpacker.queryByElo(u,t.limit*2)).map(t=>({cardID:t,courseID:this.courseId}));return c&&(d=d.filter(c)),d.slice(0,t.limit).map(t=>({status:`new`,cardID:t.cardID,contentSourceType:`course`,contentSourceID:this.courseId,courseID:this.courseId}))}async getAppliedTags(t){try{let c=await this.unpacker.getTagsIndex(),u=c.byCard[t]||[],d=await Promise.all(u.map(async u=>{let d=`TAG-${u}`;try{let c=await this.unpacker.getDocument(d);return{id:d,key:t,value:{name:c.name,snippet:c.snippet,count:c.taggedCards?.length||0}}}catch(m){if(m&&m.status===404)logger.warn(`Tag document not found for ${u}, creating stub`);else throw logger.error(`Error getting tag document for ${u}:`,m),m;return{id:d,key:t,value:{name:u,snippet:`Tag: ${u}`,count:c.byTag[u]?.length||0}}}}));return{total_rows:d.length,offset:0,rows:d}}catch(c){return logger.error(`Error getting applied tags for card ${t}:`,c),{total_rows:0,offset:0,rows:[]}}}async getAppliedTagsBatch(t){let c=await this.unpacker.getTagsIndex(),u=new Map;for(let d of t)u.set(d,c.byCard[d]||[]);return u}async getAllCardIds(){let t=await this.unpacker.getTagsIndex();return Object.keys(t.byCard)}async addTagToCard(t,c){throw Error(`Cannot modify tags in static mode`)}async removeTagFromCard(t,c){throw Error(`Cannot modify tags in static mode`)}async createTag(t){throw Error(`Cannot create tags in static mode`)}async getTag(t){return this.unpacker.getDocument(`TAG-${t}`)}async updateTag(t){throw Error(`Cannot update tags in static mode`)}async getCourseTagStubs(){try{let t=await this.unpacker.getTagsIndex();if(!t||!t.byTag)return logger.warn(`Tags index not found or empty`),{total_rows:0,offset:0,rows:[]};let c=Object.keys(t.byTag),u=await Promise.all(c.map(async c=>{let u=t.byTag[c]||[],d=`TAG-${c}`;try{return{id:d,key:d,value:{rev:`1-static`},doc:await this.unpacker.getDocument(d)}}catch(t){if(t&&t.status===404)return logger.warn(`Tag document not found for ${c}, creating stub`),{id:d,key:d,value:{rev:`1-static`},doc:{_id:d,_rev:`1-static`,course:this.courseId,docType:`TAG`,name:c,snippet:`Tag: ${c}`,wiki:``,taggedCards:u,author:`system`}};throw logger.error(`Error getting tag document for ${c}:`,t),t}}));return{total_rows:u.length,offset:0,rows:u}}catch(t){return logger.error(`Failed to get course tag stubs:`,t),{total_rows:0,offset:0,rows:[]}}}async addNote(t,c,u,d,m,g,b){return{status:Status.error,message:`Cannot add notes in static mode`}}async removeCard(t){throw Error(`Cannot remove cards in static mode`)}async getInexperiencedCards(){return[]}async getNavigationStrategy(t){try{return await this.unpacker.getDocument(t)}catch(c){throw logger.error(`[static/courseDB] Strategy ${t} not found: ${c}`),c}}async getAllNavigationStrategies(){let t=DocTypePrefixes.NAVIGATION_STRATEGY;try{return await this.unpacker.getAllDocumentsByPrefix(t)}catch(t){return logger.warn(`[static/courseDB] Error loading navigation strategies: ${t}`),[]}}async addNavigationStrategy(t){throw Error(`Cannot add navigation strategies in static mode`)}async updateNavigationStrategy(t,c){throw Error(`Cannot update navigation strategies in static mode`)}async createNavigator(t){try{let c=await this.getAllNavigationStrategies();if(c.length===0)return logger.debug(`[static/courseDB] No strategy documents found, using default Pipeline(Composite(ELO, SRS), [eloDistanceFilter])`),createDefaultPipeline(t,this);let{pipeline:u,generatorStrategies:d,filterStrategies:m,warnings:g}=await new PipelineAssembler().assemble({strategies:c,user:t,course:this});for(let t of g)logger.warn(`[PipelineAssembler] ${t}`);return u?(logger.debug(`[static/courseDB] Using assembled pipeline with ${d.length} generator(s) and ${m.length} filter(s)`),u):(logger.debug(`[static/courseDB] Pipeline assembly failed, using default pipeline`),createDefaultPipeline(t,this))}catch(t){throw logger.error(`[static/courseDB] Error creating navigator: ${t}`),t}}setEphemeralHints(t){this._pendingHints=t}notePresented(t){t.status===`new`&&this.createNavigator(this.userDB).then(c=>c.notePresented?.(t)).catch(t=>logger.warn(`[static/courseDB] Could not note a presentation: ${t}`))}async getWeightedCards(t){try{let c=await this.createNavigator(this.userDB);return this._pendingHints&&(c.setEphemeralHints(this._pendingHints),this._pendingHints=null),c.getWeightedCards(t)}catch(t){throw logger.error(`[static/courseDB] Error getting weighted cards: ${t}`),t}}getAttachmentUrl(t,c){return this.unpacker.getAttachmentUrl(t,c)}async getAttachmentBlob(t,c){return this.unpacker.getAttachmentBlob(t,c)}async searchCards(t){return[]}async find(t){return{docs:[],warning:`Find operations not supported in static mode`}}}}}),init_coursesDB=__esm({"src/impl/static/coursesDB.ts"(){"use strict";init_logger(),StaticCoursesDB=class{constructor(t,c){this.manifests=t,this.dependencyNameToCourseId=c}async getCourseConfig(t){let c=this.manifests[t];if(!c&&this.dependencyNameToCourseId){let u=this.dependencyNameToCourseId.get(t);u&&(c=this.manifests[u])}if(!c)throw logger.warn(`Course manifest for ${t} not found`),Error(`Course ${t} not found`);if(c.courseConfig)return c.courseConfig;throw logger.warn(`Course config not found in manifest for course ${t}`),Error(`Course config not found for course ${t}`)}async getCourseList(){return Object.keys(this.manifests).map(t=>({courseID:t,name:this.manifests[t].courseName}))}async disambiguateCourse(t,c){logger.warn(`Cannot disambiguate courses in static mode`)}}}}),init_NoOpSyncStrategy=__esm({"src/impl/static/NoOpSyncStrategy.ts"(){"use strict";init_common(),NoOpSyncStrategy=class{constructor(){_defineProperty$2(this,`currentUsername`,accomodateGuest().username)}setupRemoteDB(t){return getLocalUserDB(t)}getWriteDB(t){return getLocalUserDB(t)}startSync(t,c){}stopSync(){}canCreateAccount(){return!1}canAuthenticate(){return!1}async createAccount(t,c){throw Error(`Account creation not supported in static mode. Use local account switching instead.`)}async authenticate(t,c){throw Error(`Remote authentication not supported in static mode. Use local account switching instead.`)}async logout(){return this.currentUsername=accomodateGuest().username,{ok:!0}}async getCurrentUsername(){return this.currentUsername}setCurrentUsername(t){this.currentUsername=t}}}}),StaticDataLayerProvider_exports={},__export(StaticDataLayerProvider_exports,{StaticDataLayerProvider:()=>StaticDataLayerProvider}),init_StaticDataLayerProvider=__esm({"src/impl/static/StaticDataLayerProvider.ts"(){"use strict";init_logger(),init_StaticDataUnpacker(),init_courseDB2(),init_coursesDB(),init_common(),init_NoOpSyncStrategy(),StaticDataLayerProvider=class{constructor(t){_defineProperty$2(this,`config`,void 0),_defineProperty$2(this,`initialized`,!1),_defineProperty$2(this,`courseUnpackers`,new Map),_defineProperty$2(this,`manifests`,{}),_defineProperty$2(this,`dependencyNameToCourseId`,new Map),this.config={localStoragePrefix:t.localStoragePrefix||`skuilder-static`,rootManifest:t.rootManifest||{dependencies:{}},rootManifestUrl:t.rootManifestUrl||`/`}}async resolveCourseDependencies(){logger.info(`[StaticDataLayerProvider] Starting course dependency resolution...`);let t=this.config.rootManifest;for(let[c,u]of Object.entries(t.dependencies||{}))try{logger.debug(`[StaticDataLayerProvider] Resolving dependency: ${c} from ${u}`);let t=new URL(u,this.config.rootManifestUrl).href,d=await fetch(t);if(!d.ok)throw Error(`Failed to fetch course manifest for ${c}`);let m=await d.json();if(m.content&&m.content.manifest){let u=new URL(`.`,t).href,d=new URL(m.content.manifest,t).href,g=await fetch(d);if(!g.ok)throw Error(`Failed to fetch final content manifest for ${c} at ${d}`);let b=await g.json(),S=b.courseId||b.courseConfig?.courseID;if(!S)throw Error(`Course manifest for ${c} missing courseId`);this.manifests[S]=b;let C=new StaticDataUnpacker(b,u);this.courseUnpackers.set(S,C),this.dependencyNameToCourseId.set(c,S),logger.info(`[StaticDataLayerProvider] Successfully resolved and prepared course: ${c} (courseId: ${S})`)}}catch(t){logger.error(`[StaticDataLayerProvider] Failed to resolve dependency ${c}:`,t)}logger.info(`[StaticDataLayerProvider] Course dependency resolution complete.`)}async initialize(){this.initialized||(logger.info(`Initializing static data layer provider`),await this.resolveCourseDependencies(),this.initialized=!0)}async teardown(){this.courseUnpackers.clear(),this.initialized=!1}getUserDB(){let t=new NoOpSyncStrategy;return BaseUser.Dummy(t)}getCourseDB(t){let c=this.courseUnpackers.get(t),u=t;if(!c){let d=this.dependencyNameToCourseId.get(t);d&&(c=this.courseUnpackers.get(d),u=d)}if(!c)throw Error(`Course ${t} not found or failed to initialize in static data layer.`);let d=this.manifests[u];return new StaticCourseDB(u,c,this.getUserDB(),d)}getCoursesDB(){return new StaticCoursesDB(this.manifests,this.dependencyNameToCourseId)}async getClassroomDB(t,c){throw Error(`Classrooms not supported in static mode`)}getAdminDB(){throw Error(`Admin functions not supported in static mode`)}isReadOnly(){return!0}}}}),init_factory=__esm({"src/factory.ts"(){"use strict";init_common(),init_logger(),init_navigators(),NOT_SET=`NOT_SET`,ENV={COUCHDB_SERVER_PROTOCOL:NOT_SET,COUCHDB_SERVER_URL:NOT_SET,LOCAL_STORAGE_PREFIX:``},dataLayerInstance=null}}),init_contentSource=__esm({"src/core/interfaces/contentSource.ts"(){"use strict";init_factory(),init_classroomDB2(),init_TagFilteredContentSource()}}),init_courseDB3=__esm({"src/core/interfaces/courseDB.ts"(){"use strict";}}),init_dataLayerProvider=__esm({"src/core/interfaces/dataLayerProvider.ts"(){"use strict";}}),init_userDB=__esm({"src/core/interfaces/userDB.ts"(){"use strict";}}),init_interfaces=__esm({"src/core/interfaces/index.ts"(){"use strict";init_adminDB(),init_classroomDB(),init_contentSource(),init_courseDB3(),init_dataLayerProvider(),init_userDB()}}),init_user=__esm({"src/core/types/user.ts"(){"use strict";}}),init_strategyState=__esm({"src/core/types/strategyState.ts"(){"use strict";}}),init_userOutcome=__esm({"src/core/types/userOutcome.ts"(){"use strict";}}),init_hydration=__esm({"src/core/types/hydration.ts"(){"use strict";HYDRATION_MARKER_ID=`_local/hydration`}}),init_cardProcessor=__esm({"src/core/bulkImport/cardProcessor.ts"(){"use strict";init_logger()}}),init_types5=__esm({"src/core/bulkImport/types.ts"(){"use strict";}}),init_bulkImport=__esm({"src/core/bulkImport/index.ts"(){"use strict";init_cardProcessor(),init_types5()}}),init_UserDBDebugger=__esm({"src/core/UserDBDebugger.ts"(){"use strict";init_logger(),init_factory(),init_types_legacy(),init_userDBHelpers(),userDBDebugAPI={showUser(){let t=getUserDB();t&&(console.group(`👤 User Information`),logger.info(`Username: ${t.getUsername()}`),logger.info(`Logged in: ${t.isLoggedIn()?`Yes ✅`:`No (Guest) ❌`}`),t.getConfig().then(t=>{logger.info(`Configuration:`),logger.info(JSON.stringify(t,null,2))}).catch(t=>{logger.info(`Error loading config: ${t.message}`)}).finally(()=>{console.groupEnd()}))},async showScheduledReviews(t){let c=getUserDB();if(!c){logger.info(`[UserDB Debug] Data layer not available`);return}logger.info(`[UserDB Debug] Fetching pending reviews${t?` for course: ${t}`:``}...`);try{let u=await c.getPendingReviews(t);if(logger.info(`[UserDB Debug] Got ${u.length} reviews`),console.group(`\u{1F4C5} Scheduled Reviews${t?` (${t})`:``}`),logger.info(`Total: ${u.length}`),u.length>0){let t=new Map;for(let c of u)t.has(c.courseId)||t.set(c.courseId,[]),t.get(c.courseId).push(c);for(let[c,u]of t){console.group(`Course: ${c} (${u.length} reviews)`);let t=u.sort((t,c)=>{let u=typeof t.reviewTime==`string`?t.reviewTime:t.reviewTime.toISOString(),d=typeof c.reviewTime==`string`?c.reviewTime:c.reviewTime.toISOString();return new Date(u).getTime()-new Date(d).getTime()});for(let c of t.slice(0,10)){let t=typeof c.reviewTime==`string`?c.reviewTime:c.reviewTime.toISOString();logger.info(` ${c.cardId.slice(0,12)}... @ ${formatTimestamp(t)} [${c.scheduledFor}/${c.schedulingAgentId}]`)}t.length>10&&logger.info(` ... and ${t.length-10} more`),console.groupEnd()}}console.groupEnd()}catch(t){logger.info(`Error loading scheduled reviews: ${t.message}`)}},async showCourseRegistrations(){let t=getUserDB();if(t)try{let c=await t.getActiveCourses();console.group(`📚 Course Registrations`),logger.info(`Total: ${c.length}`),c.length>0&&console.table(c.map(t=>({courseId:t.courseID,status:t.status||`active`,elo:typeof t.elo==`number`?t.elo.toFixed(0):t.elo?.global?.score?.toFixed(0)||`N/A`}))),console.groupEnd()}catch(t){logger.info(`Error loading course registrations: ${t.message}`)}},async showCardHistory(t){let c=getRawDB();if(c)try{let u=(await filterAllDocsByPrefix2(c,DocTypePrefixes.CARDRECORD)).rows.filter(c=>c.doc&&c.doc.cardID===t).map(t=>t.doc);if(console.group(`\u{1F3B4} Card History: ${t}`),logger.info(`Total interactions: ${u.length}`),u.length>0){let t=u.sort((t,c)=>new Date(c.timestamp).getTime()-new Date(t.timestamp).getTime());console.table(t.slice(0,20).map(t=>({time:formatTimestamp(t.timestamp),outcome:t.outcome||`N/A`,duration:t.duration?`${(t.duration/1e3).toFixed(1)}s`:`N/A`,courseId:t.courseId}))),t.length>20&&logger.info(`... and ${t.length-20} more interactions`)}console.groupEnd()}catch(t){logger.info(`Error loading card history: ${t.message}`)}},async queryByType(t,c=50){let u=getRawDB();if(u)try{let d=DocTypePrefixes[DocType[t]];if(!d){logger.info(`Unknown document type: ${t}`);return}let m=await filterAllDocsByPrefix2(u,d);if(console.group(`\u{1F4C4} Documents: ${t}`),logger.info(`Total: ${m.rows.length}`),logger.info(`Prefix: ${d}`),m.rows.length>0){logger.info(`Sample documents:`);let t=m.rows.slice(0,Math.min(c,m.rows.length));for(let c of t)logger.info(`
439
+ }`}}}]),t),userCoursesDoc=`CourseRegistrations`,userClassroomsDoc=`ClassroomRegistrations`}}),init_common=__esm({"src/impl/common/index.ts"(){"use strict";init_SyncStrategy(),init_BaseUserDB(),init_userDBHelpers()}}),PouchDataLayerProvider_exports={},__export(PouchDataLayerProvider_exports,{CouchDataLayerProvider:()=>CouchDataLayerProvider}),init_PouchDataLayerProvider=__esm({"src/impl/couch/PouchDataLayerProvider.ts"(){"use strict";init_logger(),init_dataDirectory(),init_adminDB2(),init_classroomDB2(),init_courseDB(),init_CourseSyncService(),init_common(),init_CouchDBSyncStrategy(),CouchDataLayerProvider=class{constructor(t){_defineProperty$2(this,`initialized`,!1),_defineProperty$2(this,`userDB`,void 0),_defineProperty$2(this,`currentUsername`,``),_defineProperty$2(this,`_courseIDs`,[]),t&&(this._courseIDs=t)}async initialize(){if(!this.initialized){if(typeof process<`u`&&process.versions!=null&&process.versions.node!=null){logger.info(`CouchDataLayerProvider: Running in Node.js environment, creating guest UserDB for testing.`),await initializeDataDirectory();let t=new CouchDBSyncStrategy;this.userDB=await BaseUser.instance(t)}else{let t=new CouchDBSyncStrategy;this.userDB=await BaseUser.instance(t),this.currentUsername=this.userDB.getUsername(),logger.debug(`Current username: ${this.currentUsername}`)}this.initialized=!0}}async teardown(){this.initialized=!1}getUserDB(){return this.userDB}getCourseDB(t){let c=CourseSyncService.getInstance().getLocalDB(t);return new CourseDB(t,async()=>this.getUserDB(),c??void 0)}async ensureCourseSynced(t,c){return CourseSyncService.getInstance().ensureSynced(t,c)}getCoursesDB(){return new CoursesDB(this._courseIDs)}async getClassroomDB(t,c){return c===`student`?await StudentClassroomDB.factory(t,this.getUserDB()):await TeacherClassroomDB.factory(t)}getAdminDB(){return new AdminDB}isReadOnly(){return!1}}}}),init_StaticDataUnpacker=__esm({"src/impl/static/StaticDataUnpacker.ts"(){"use strict";init_logger(),init_core(),pathUtils={isAbsolute:t=>!!(/^[a-zA-Z]:[\\/]/.test(t)||/^\\\\/.test(t)||t.startsWith(`/`))},nodeFS3=null;try{typeof window>`u`&&typeof process<`u`&&process.versions?.node&&(nodeFS3=eval(`require`)(`fs`))}catch{}StaticDataUnpacker=class{constructor(t,c){_defineProperty$2(this,`manifest`,void 0),_defineProperty$2(this,`basePath`,void 0),_defineProperty$2(this,`documentCache`,new Map),_defineProperty$2(this,`chunkCache`,new Map),_defineProperty$2(this,`indexCache`,new Map),this.manifest=t,this.basePath=c}async getDocument(t){if(this.documentCache.has(t)){let c=this.documentCache.get(t);return await this.hydrateAttachments(c)}let c=await this.findChunkForDocument(t);if(!c)throw logger.error(`Document ${t} not found in any chunk. Available chunks:`,this.manifest.chunks.map(t=>`${t.id} (${t.docType}): ${t.startKey} - ${t.endKey}`)),Error(`Document ${t} not found in any chunk`);if(await this.loadChunk(c.id),this.documentCache.has(t)){let c=this.documentCache.get(t);return await this.hydrateAttachments(c)}throw logger.error(`Document ${t} not found in chunk ${c.id}`),Error(`Document ${t} not found in chunk ${c.id}`)}async getAllDocumentsByPrefix(t){let c=this.manifest.chunks.filter(c=>{let u=t+`￰`;return c.startKey<=u&&c.endKey>=t});if(c.length===0)return logger.debug(`[StaticDataUnpacker] No chunks found for prefix: ${t}`),[];await Promise.all(c.map(t=>this.loadChunk(t.id)));let u=[];for(let[c,d]of this.documentCache.entries())c.startsWith(t)&&u.push(await this.hydrateAttachments(d));return logger.debug(`[StaticDataUnpacker] Found ${u.length} documents with prefix: ${t}`),u}async queryByElo(t,c=25){let u=await this.loadIndex(`elo`);if(!u||!u.sorted)return logger.warn(`ELO index not found or malformed, returning empty results`),[];let d=u.sorted,m=0,g=0,b=d.length-1;for(;g<=b;){let c=Math.floor((g+b)/2);d[c].elo<t?g=c+1:b=c-1}m=g;let S=[],C=Math.floor(c/2);for(let t=Math.max(0,m-C);t<m&&S.length<c;t++)S.push(d[t].cardId);for(let t=m;t<d.length&&S.length<c;t++)S.push(d[t].cardId);return S}async getTagsIndex(){try{return await this.loadIndex(`tags`)}catch{return{byCard:{},byTag:{}}}}getDocTypeFromId(t){for(let c in DocTypePrefixes){let u=DocTypePrefixes[c];if(t.startsWith(`${u}-`))return c}}async findChunkForDocument(t){let c=this.getDocTypeFromId(t);if(c){let u=this.manifest.chunks.filter(t=>t.docType===c);for(let c of u)if(t>=c.startKey&&t<=c.endKey&&await this.verifyDocumentInChunk(t,c))return c}else{for(let c of this.manifest.chunks)if(t>=c.startKey&&t<=c.endKey&&await this.verifyDocumentInChunk(t,c))return c;let c=this.manifest.chunks.filter(t=>t.docType!==`CARD`&&t.docType!==`DISPLAYABLE_DATA`&&t.docType!==`TAG`);for(let u of c)if(t>=u.startKey&&t<=u.endKey&&await this.verifyDocumentInChunk(t,u))return u;return}}async verifyDocumentInChunk(t,c){try{return await this.loadChunk(c.id),this.documentCache.has(t)}catch{return!1}}async loadChunk(t){if(this.chunkCache.has(t))return;let c=this.manifest.chunks.find(c=>c.id===t);if(!c)throw Error(`Chunk ${t} not found in manifest`);try{let u=`${this.basePath}/${c.path}`;logger.debug(`Loading chunk from ${u}`);let d;if(this.isLocalPath(u)&&nodeFS3){let t=await nodeFS3.promises.readFile(u,`utf8`);d=JSON.parse(t)}else{let c=await fetch(u);if(!c.ok)throw Error(`Failed to fetch chunk ${t}: ${c.status} ${c.statusText}`);d=await c.json()}this.chunkCache.set(t,d);for(let t of d)t._id&&this.documentCache.set(t._id,t);logger.debug(`Loaded ${d.length} documents from chunk ${t}`)}catch(c){throw logger.error(`Failed to load chunk ${t}:`,c),c}}async loadIndex(t){if(this.indexCache.has(t))return this.indexCache.get(t);let c=this.manifest.indices.find(c=>c.name===t);if(!c)throw Error(`Index ${t} not found in manifest`);try{let u=`${this.basePath}/${c.path}`;logger.debug(`Loading index from ${u}`);let d;if(this.isLocalPath(u)&&nodeFS3){let t=await nodeFS3.promises.readFile(u,`utf8`);d=JSON.parse(t)}else{let c=await fetch(u);if(!c.ok)throw Error(`Failed to fetch index ${t}: ${c.status} ${c.statusText}`);d=await c.json()}return this.indexCache.set(t,d),logger.debug(`Loaded index ${t}`),d}catch(c){throw logger.error(`Failed to load index ${t}:`,c),c}}async getRawDocument(t){if(this.documentCache.has(t))return this.documentCache.get(t);let c=await this.findChunkForDocument(t);if(!c)throw logger.error(`Document ${t} not found in any chunk. Available chunks:`,this.manifest.chunks.map(t=>`${t.id} (${t.docType}): ${t.startKey} - ${t.endKey}`)),Error(`Document ${t} not found in any chunk`);if(await this.loadChunk(c.id),this.documentCache.has(t))return this.documentCache.get(t);throw logger.error(`Document ${t} not found in chunk ${c.id}`),Error(`Document ${t} not found in chunk ${c.id}`)}getAttachmentUrl(t,c){return`${this.basePath}/attachments/${t}/${c}`}async getAttachmentPath(t,c){try{let u=await this.getRawDocument(t);if(u._attachments&&u._attachments[c]){let t=u._attachments[c];if(t.path)return`${this.basePath}/${t.path}`}return null}catch{return null}}async getAttachmentBlob(t,c){let u=await this.getAttachmentPath(t,c);if(!u)return null;try{if(this.isLocalPath(u)&&nodeFS3)return await nodeFS3.promises.readFile(u);{let d=await fetch(u);if(!d.ok)throw Error(`Failed to fetch attachment ${t}/${c}: ${d.status} ${d.statusText}`);return await d.blob()}}catch(u){return logger.error(`Failed to load attachment ${t}/${c}:`,u),null}}async hydrateAttachments(t){let c=t;if(!c._attachments)return t;let u=JSON.parse(JSON.stringify(t));for(let[t,d]of Object.entries(c._attachments)){let m=d;if(m.path)try{let d=await this.getAttachmentBlob(c._id,t);d?typeof window<`u`&&window.URL?u._attachments[t]={...m,data:d,stub:!1}:u._attachments[t]={...m,buffer:d}:logger.warn(`[hydrateAttachments] getAttachmentBlob returned null for ${c._id}/${t}. Skipping hydration for this attachment.`)}catch(u){logger.warn(`[hydrateAttachments] Failed to hydrate attachment ${c._id}/${t}:`,u)}else logger.debug(`[hydrateAttachments] Attachment ${t} for doc ${c._id} has no path. Skipping blob conversion.`)}return u}clearCaches(){this.documentCache.clear(),this.chunkCache.clear(),this.indexCache.clear()}getCacheStats(){return{documents:this.documentCache.size,chunks:this.chunkCache.size,indices:this.indexCache.size}}isLocalPath(t){return!t.startsWith(`http://`)&&!t.startsWith(`https://`)&&(pathUtils.isAbsolute(t)||t.startsWith(`./`)||t.startsWith(`../`))}}}}),init_courseDB2=__esm({"src/impl/static/courseDB.ts"(){"use strict";init_types_legacy(),init_logger(),init_defaults(),init_PipelineAssembler(),StaticCourseDB=class{constructor(t,c,u,d){_defineProperty$2(this,`_pendingHints`,null),this.courseId=t,this.unpacker=c,this.userDB=u,this.manifest=d}getCourseID(){return this.courseId}async getCourseConfig(){if(this.manifest.courseConfig!=null)return this.manifest.courseConfig;throw Error(`Course config not found for course ${this.courseId}`)}async updateCourseConfig(t){throw Error(`Cannot update course config in static mode`)}async getCourseInfo(){return{cardCount:this.manifest.chunks.filter(t=>t.docType===`CARD`).reduce((t,c)=>t+c.documentCount,0),registeredUsers:0}}async getCourseDoc(t,c){return this.unpacker.getDocument(t)}async getCourseDocs(t,c){let u=await Promise.all(t.map(async t=>{try{return{id:t,key:t,value:{rev:`1-static`},doc:await this.unpacker.getDocument(t)}}catch{return{key:t,error:`not_found`}}}));return{total_rows:t.length,offset:0,rows:u}}async getCardsByELO(t,c){return(await this.unpacker.queryByElo(t,c||25)).map(t=>{let[c,u,d]=t.split(`-`);return{courseID:c,cardID:u,elo:d?parseInt(d):void 0}})}async getCardEloData(t){return await Promise.all(t.map(async t=>{try{return(await this.unpacker.getDocument(t)).elo||{global:{score:1e3,count:0},tags:{},misc:{}}}catch{return{global:{score:1e3,count:0},tags:{},misc:{}}}}))}async updateCardElo(t,c){return{ok:!0,id:t,rev:`1-static`}}async getCardsCenteredAtELO(t,c){let u=typeof t.elo==`number`?t.elo:1e3;if(t.elo===`user`)try{let t=(await this.userDB.getCourseRegistrationsDoc()).courses.find(t=>t.courseID===this.courseId);t&&typeof t.elo==`object`&&(u=t.elo.global.score)}catch{u=1e3}else t.elo===`random`&&(u=800+Math.random()*400);let d=(await this.unpacker.queryByElo(u,t.limit*2)).map(t=>({cardID:t,courseID:this.courseId}));return c&&(d=d.filter(c)),d.slice(0,t.limit).map(t=>({status:`new`,cardID:t.cardID,contentSourceType:`course`,contentSourceID:this.courseId,courseID:this.courseId}))}async getAppliedTags(t){try{let c=await this.unpacker.getTagsIndex(),u=c.byCard[t]||[],d=await Promise.all(u.map(async u=>{let d=`TAG-${u}`;try{let c=await this.unpacker.getDocument(d);return{id:d,key:t,value:{name:c.name,snippet:c.snippet,count:c.taggedCards?.length||0}}}catch(m){if(m&&m.status===404)logger.warn(`Tag document not found for ${u}, creating stub`);else throw logger.error(`Error getting tag document for ${u}:`,m),m;return{id:d,key:t,value:{name:u,snippet:`Tag: ${u}`,count:c.byTag[u]?.length||0}}}}));return{total_rows:d.length,offset:0,rows:d}}catch(c){return logger.error(`Error getting applied tags for card ${t}:`,c),{total_rows:0,offset:0,rows:[]}}}async getAppliedTagsBatch(t){let c=await this.unpacker.getTagsIndex(),u=new Map;for(let d of t)u.set(d,c.byCard[d]||[]);return u}async getAllCardIds(){let t=await this.unpacker.getTagsIndex();return Object.keys(t.byCard)}async addTagToCard(t,c){throw Error(`Cannot modify tags in static mode`)}async removeTagFromCard(t,c){throw Error(`Cannot modify tags in static mode`)}async createTag(t){throw Error(`Cannot create tags in static mode`)}async getTag(t){return this.unpacker.getDocument(`TAG-${t}`)}async updateTag(t){throw Error(`Cannot update tags in static mode`)}async getCourseTagStubs(){try{let t=await this.unpacker.getTagsIndex();if(!t||!t.byTag)return logger.warn(`Tags index not found or empty`),{total_rows:0,offset:0,rows:[]};let c=Object.keys(t.byTag),u=await Promise.all(c.map(async c=>{let u=t.byTag[c]||[],d=`TAG-${c}`;try{return{id:d,key:d,value:{rev:`1-static`},doc:await this.unpacker.getDocument(d)}}catch(t){if(t&&t.status===404)return logger.warn(`Tag document not found for ${c}, creating stub`),{id:d,key:d,value:{rev:`1-static`},doc:{_id:d,_rev:`1-static`,course:this.courseId,docType:`TAG`,name:c,snippet:`Tag: ${c}`,wiki:``,taggedCards:u,author:`system`}};throw logger.error(`Error getting tag document for ${c}:`,t),t}}));return{total_rows:u.length,offset:0,rows:u}}catch(t){return logger.error(`Failed to get course tag stubs:`,t),{total_rows:0,offset:0,rows:[]}}}async addNote(t,c,u,d,m,g,b){return{status:Status.error,message:`Cannot add notes in static mode`}}async removeCard(t){throw Error(`Cannot remove cards in static mode`)}async getInexperiencedCards(){return[]}async getNavigationStrategy(t){try{return await this.unpacker.getDocument(t)}catch(c){throw logger.error(`[static/courseDB] Strategy ${t} not found: ${c}`),c}}async getAllNavigationStrategies(){let t=DocTypePrefixes.NAVIGATION_STRATEGY;try{return await this.unpacker.getAllDocumentsByPrefix(t)}catch(t){return logger.warn(`[static/courseDB] Error loading navigation strategies: ${t}`),[]}}async addNavigationStrategy(t){throw Error(`Cannot add navigation strategies in static mode`)}async updateNavigationStrategy(t,c){throw Error(`Cannot update navigation strategies in static mode`)}async createNavigator(t){try{let c=await this.getAllNavigationStrategies();if(c.length===0)return logger.debug(`[static/courseDB] No strategy documents found, using default Pipeline(Composite(ELO, SRS), [eloDistanceFilter])`),createDefaultPipeline(t,this);let{pipeline:u,generatorStrategies:d,filterStrategies:m,warnings:g}=await new PipelineAssembler().assemble({strategies:c,user:t,course:this});for(let t of g)logger.warn(`[PipelineAssembler] ${t}`);return u?(logger.debug(`[static/courseDB] Using assembled pipeline with ${d.length} generator(s) and ${m.length} filter(s)`),u):(logger.debug(`[static/courseDB] Pipeline assembly failed, using default pipeline`),createDefaultPipeline(t,this))}catch(t){throw logger.error(`[static/courseDB] Error creating navigator: ${t}`),t}}setEphemeralHints(t){this._pendingHints=t}notePresented(t){t.status===`new`&&this.createNavigator(this.userDB).then(c=>c.notePresented?.(t)).catch(t=>logger.warn(`[static/courseDB] Could not note a presentation: ${t}`))}async getWeightedCards(t){try{let c=await this.createNavigator(this.userDB);return this._pendingHints&&(c.setEphemeralHints(this._pendingHints),this._pendingHints=null),c.getWeightedCards(t)}catch(t){throw logger.error(`[static/courseDB] Error getting weighted cards: ${t}`),t}}getAttachmentUrl(t,c){return this.unpacker.getAttachmentUrl(t,c)}async getAttachmentBlob(t,c){return this.unpacker.getAttachmentBlob(t,c)}async searchCards(t){return[]}async find(t){return{docs:[],warning:`Find operations not supported in static mode`}}}}}),init_coursesDB=__esm({"src/impl/static/coursesDB.ts"(){"use strict";init_logger(),StaticCoursesDB=class{constructor(t,c){this.manifests=t,this.dependencyNameToCourseId=c}async getCourseConfig(t){let c=this.manifests[t];if(!c&&this.dependencyNameToCourseId){let u=this.dependencyNameToCourseId.get(t);u&&(c=this.manifests[u])}if(!c)throw logger.warn(`Course manifest for ${t} not found`),Error(`Course ${t} not found`);if(c.courseConfig)return c.courseConfig;throw logger.warn(`Course config not found in manifest for course ${t}`),Error(`Course config not found for course ${t}`)}async getCourseList(){return Object.keys(this.manifests).map(t=>({courseID:t,name:this.manifests[t].courseName}))}async disambiguateCourse(t,c){logger.warn(`Cannot disambiguate courses in static mode`)}}}}),init_NoOpSyncStrategy=__esm({"src/impl/static/NoOpSyncStrategy.ts"(){"use strict";init_common(),NoOpSyncStrategy=class{constructor(){_defineProperty$2(this,`currentUsername`,accomodateGuest().username)}setupRemoteDB(t){return getLocalUserDB(t)}getWriteDB(t){return getLocalUserDB(t)}startSync(t,c){}stopSync(){}canCreateAccount(){return!1}canAuthenticate(){return!1}async createAccount(t,c){throw Error(`Account creation not supported in static mode. Use local account switching instead.`)}async authenticate(t,c){throw Error(`Remote authentication not supported in static mode. Use local account switching instead.`)}async logout(){return this.currentUsername=accomodateGuest().username,{ok:!0}}async getCurrentUsername(){return this.currentUsername}setCurrentUsername(t){this.currentUsername=t}}}}),StaticDataLayerProvider_exports={},__export(StaticDataLayerProvider_exports,{StaticDataLayerProvider:()=>StaticDataLayerProvider}),init_StaticDataLayerProvider=__esm({"src/impl/static/StaticDataLayerProvider.ts"(){"use strict";init_logger(),init_StaticDataUnpacker(),init_courseDB2(),init_coursesDB(),init_common(),init_NoOpSyncStrategy(),StaticDataLayerProvider=class{constructor(t){_defineProperty$2(this,`config`,void 0),_defineProperty$2(this,`initialized`,!1),_defineProperty$2(this,`courseUnpackers`,new Map),_defineProperty$2(this,`manifests`,{}),_defineProperty$2(this,`dependencyNameToCourseId`,new Map),this.config={localStoragePrefix:t.localStoragePrefix||`skuilder-static`,rootManifest:t.rootManifest||{dependencies:{}},rootManifestUrl:t.rootManifestUrl||`/`}}async resolveCourseDependencies(){logger.info(`[StaticDataLayerProvider] Starting course dependency resolution...`);let t=this.config.rootManifest;for(let[c,u]of Object.entries(t.dependencies||{}))try{logger.debug(`[StaticDataLayerProvider] Resolving dependency: ${c} from ${u}`);let t=new URL(u,this.config.rootManifestUrl).href,d=await fetch(t);if(!d.ok)throw Error(`Failed to fetch course manifest for ${c}`);let m=await d.json();if(m.content&&m.content.manifest){let u=new URL(`.`,t).href,d=new URL(m.content.manifest,t).href,g=await fetch(d);if(!g.ok)throw Error(`Failed to fetch final content manifest for ${c} at ${d}`);let b=await g.json(),S=b.courseId||b.courseConfig?.courseID;if(!S)throw Error(`Course manifest for ${c} missing courseId`);this.manifests[S]=b;let C=new StaticDataUnpacker(b,u);this.courseUnpackers.set(S,C),this.dependencyNameToCourseId.set(c,S),logger.info(`[StaticDataLayerProvider] Successfully resolved and prepared course: ${c} (courseId: ${S})`)}}catch(t){logger.error(`[StaticDataLayerProvider] Failed to resolve dependency ${c}:`,t)}logger.info(`[StaticDataLayerProvider] Course dependency resolution complete.`)}async initialize(){this.initialized||(logger.info(`Initializing static data layer provider`),await this.resolveCourseDependencies(),this.initialized=!0)}async teardown(){this.courseUnpackers.clear(),this.initialized=!1}getUserDB(){let t=new NoOpSyncStrategy;return BaseUser.Dummy(t)}getCourseDB(t){let c=this.courseUnpackers.get(t),u=t;if(!c){let d=this.dependencyNameToCourseId.get(t);d&&(c=this.courseUnpackers.get(d),u=d)}if(!c)throw Error(`Course ${t} not found or failed to initialize in static data layer.`);let d=this.manifests[u];return new StaticCourseDB(u,c,this.getUserDB(),d)}getCoursesDB(){return new StaticCoursesDB(this.manifests,this.dependencyNameToCourseId)}async getClassroomDB(t,c){throw Error(`Classrooms not supported in static mode`)}getAdminDB(){throw Error(`Admin functions not supported in static mode`)}isReadOnly(){return!0}}}}),init_factory=__esm({"src/factory.ts"(){"use strict";init_common(),init_logger(),init_navigators(),init_versionStamps(),NOT_SET=`NOT_SET`,ENV={COUCHDB_SERVER_PROTOCOL:NOT_SET,COUCHDB_SERVER_URL:NOT_SET,LOCAL_STORAGE_PREFIX:``},dataLayerInstance=null}}),init_contentSource=__esm({"src/core/interfaces/contentSource.ts"(){"use strict";init_factory(),init_classroomDB2(),init_TagFilteredContentSource()}}),init_courseDB3=__esm({"src/core/interfaces/courseDB.ts"(){"use strict";}}),init_dataLayerProvider=__esm({"src/core/interfaces/dataLayerProvider.ts"(){"use strict";}}),init_userDB=__esm({"src/core/interfaces/userDB.ts"(){"use strict";}}),init_interfaces=__esm({"src/core/interfaces/index.ts"(){"use strict";init_adminDB(),init_classroomDB(),init_contentSource(),init_courseDB3(),init_dataLayerProvider(),init_userDB()}}),init_user=__esm({"src/core/types/user.ts"(){"use strict";}}),init_strategyState=__esm({"src/core/types/strategyState.ts"(){"use strict";}}),init_userOutcome=__esm({"src/core/types/userOutcome.ts"(){"use strict";}}),init_hydration=__esm({"src/core/types/hydration.ts"(){"use strict";HYDRATION_MARKER_ID=`_local/hydration`}}),init_cardProcessor=__esm({"src/core/bulkImport/cardProcessor.ts"(){"use strict";init_logger()}}),init_types5=__esm({"src/core/bulkImport/types.ts"(){"use strict";}}),init_bulkImport=__esm({"src/core/bulkImport/index.ts"(){"use strict";init_cardProcessor(),init_types5()}}),init_UserDBDebugger=__esm({"src/core/UserDBDebugger.ts"(){"use strict";init_logger(),init_factory(),init_types_legacy(),init_userDBHelpers(),userDBDebugAPI={showUser(){let t=getUserDB();t&&(console.group(`👤 User Information`),logger.info(`Username: ${t.getUsername()}`),logger.info(`Logged in: ${t.isLoggedIn()?`Yes ✅`:`No (Guest) ❌`}`),t.getConfig().then(t=>{logger.info(`Configuration:`),logger.info(JSON.stringify(t,null,2))}).catch(t=>{logger.info(`Error loading config: ${t.message}`)}).finally(()=>{console.groupEnd()}))},async showScheduledReviews(t){let c=getUserDB();if(!c){logger.info(`[UserDB Debug] Data layer not available`);return}logger.info(`[UserDB Debug] Fetching pending reviews${t?` for course: ${t}`:``}...`);try{let u=await c.getPendingReviews(t);if(logger.info(`[UserDB Debug] Got ${u.length} reviews`),console.group(`\u{1F4C5} Scheduled Reviews${t?` (${t})`:``}`),logger.info(`Total: ${u.length}`),u.length>0){let t=new Map;for(let c of u)t.has(c.courseId)||t.set(c.courseId,[]),t.get(c.courseId).push(c);for(let[c,u]of t){console.group(`Course: ${c} (${u.length} reviews)`);let t=u.sort((t,c)=>{let u=typeof t.reviewTime==`string`?t.reviewTime:t.reviewTime.toISOString(),d=typeof c.reviewTime==`string`?c.reviewTime:c.reviewTime.toISOString();return new Date(u).getTime()-new Date(d).getTime()});for(let c of t.slice(0,10)){let t=typeof c.reviewTime==`string`?c.reviewTime:c.reviewTime.toISOString();logger.info(` ${c.cardId.slice(0,12)}... @ ${formatTimestamp(t)} [${c.scheduledFor}/${c.schedulingAgentId}]`)}t.length>10&&logger.info(` ... and ${t.length-10} more`),console.groupEnd()}}console.groupEnd()}catch(t){logger.info(`Error loading scheduled reviews: ${t.message}`)}},async showCourseRegistrations(){let t=getUserDB();if(t)try{let c=await t.getActiveCourses();console.group(`📚 Course Registrations`),logger.info(`Total: ${c.length}`),c.length>0&&console.table(c.map(t=>({courseId:t.courseID,status:t.status||`active`,elo:typeof t.elo==`number`?t.elo.toFixed(0):t.elo?.global?.score?.toFixed(0)||`N/A`}))),console.groupEnd()}catch(t){logger.info(`Error loading course registrations: ${t.message}`)}},async showCardHistory(t){let c=getRawDB();if(c)try{let u=(await filterAllDocsByPrefix2(c,DocTypePrefixes.CARDRECORD)).rows.filter(c=>c.doc&&c.doc.cardID===t).map(t=>t.doc);if(console.group(`\u{1F3B4} Card History: ${t}`),logger.info(`Total interactions: ${u.length}`),u.length>0){let t=u.sort((t,c)=>new Date(c.timestamp).getTime()-new Date(t.timestamp).getTime());console.table(t.slice(0,20).map(t=>({time:formatTimestamp(t.timestamp),outcome:t.outcome||`N/A`,duration:t.duration?`${(t.duration/1e3).toFixed(1)}s`:`N/A`,courseId:t.courseId}))),t.length>20&&logger.info(`... and ${t.length-20} more interactions`)}console.groupEnd()}catch(t){logger.info(`Error loading card history: ${t.message}`)}},async queryByType(t,c=50){let u=getRawDB();if(u)try{let d=DocTypePrefixes[DocType[t]];if(!d){logger.info(`Unknown document type: ${t}`);return}let m=await filterAllDocsByPrefix2(u,d);if(console.group(`\u{1F4C4} Documents: ${t}`),logger.info(`Total: ${m.rows.length}`),logger.info(`Prefix: ${d}`),m.rows.length>0){logger.info(`Sample documents:`);let t=m.rows.slice(0,Math.min(c,m.rows.length));for(let c of t)logger.info(`
439
440
  ${c.id}:`),logger.info(JSON.stringify(c.doc,null,2));m.rows.length>c&&logger.info(`
440
441
  ... and ${m.rows.length-c} more documents`)}console.groupEnd()}catch(t){logger.info(`Error querying documents: ${t.message}`)}},async dbInfo(){let t=getRawDB();if(t)try{let c=await t.info();console.group(`ℹ️ Database Information`),logger.info(`Database name: ${c.db_name}`),logger.info(`Total documents: ${c.doc_count}`),logger.info(`Update sequence: ${c.update_seq}`),`disk_size`in c&&logger.info(`Disk size: ${(c.disk_size||0)/1024/1024} MB`),logger.info(`
441
442
  Document counts by type:`);let u=await t.allDocs({include_docs:!1}),d=new Map;for(let t of u.rows){let c=`other`;for(let[u,d]of Object.entries(DocTypePrefixes))if(t.id.startsWith(d)){c=u;break}d.set(c,(d.get(c)||0)+1)}console.table(Array.from(d.entries()).sort((t,c)=>c[1]-t[1]).map(([t,c])=>({type:t,count:c}))),console.groupEnd()}catch(t){logger.info(`Error getting database info: ${t.message}`)}},listDocTypes(){console.group(`📋 Available Document Types`),logger.info(`Use with queryByType(type):`);for(let[t,c]of Object.entries(DocTypePrefixes))logger.info(` ${t.padEnd(30)} \u2192 prefix: "${c}"`);console.groupEnd()},async export(t=!1){let c=getRawDB(),u=getUserDB();if(!c||!u)return`{}`;try{let d={username:u.getUsername(),loggedIn:u.isLoggedIn(),timestamp:new Date().toISOString()};if(t){let t=await c.allDocs({include_docs:!0});d.documents=t.rows.map(t=>({id:t.id,doc:t.doc})),d.totalDocs=t.rows.length}else{let t=await c.allDocs({include_docs:!1});d.totalDocs=t.rows.length;let u=new Map;for(let c of t.rows){let t=`other`;for(let[u,d]of Object.entries(DocTypePrefixes))if(c.id.startsWith(d)){t=u;break}u.set(t,(u.get(t)||0)+1)}d.docCounts=Object.fromEntries(u)}let m=JSON.stringify(d,null,2);return logger.info(`[UserDB Debug] Database info exported. Copy the returned string or use:`),logger.info(` copy(window.skuilder.userdb.export())`),t||logger.info(` For full content export: window.skuilder.userdb.export(true)`),m}catch(t){return logger.info(`Error exporting database: ${t.message}`),`{}`}},async raw(t){let c=getRawDB();if(c)try{let u=await t(c);logger.info(`[UserDB Debug] Query result:`),logger.info(u)}catch(t){logger.info(`[UserDB Debug] Query error: ${t.message}`)}},help(){logger.info(`