const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./BlapV1mo.js","./bG-fsHMS.js","./DrKWWDpL.js","./DsQIgu-4.js","./DTkg6Mnx.js","./DYP3EJMY.js","./DeO5NWhN.js","./DgZn9uJn.js","./CbGRcr-D.js","./CudpqN6Z.js","./CX8DOZuw2.js","./DOqzs8kl2.js","./DIQmuJJZ.js","./D7w7HllH.js","./DB5ifLM-.js","./CxlOpib82.js","./Czb-RtcG.js","./C0nwgWmB.js","./D-eE9s2f.js","./CWxOfblT.js","./DlZwu-Y7.js","./CN3sIbmT2.js","./CLr_XgCb2.js","./CvFbqtf9.js","./BMB7x0Pe.js","./B1GXAVRr.js","./BVC3q6GM.js","./B8PRMiR2.js","./CVwAhlPZ.js","./Cx_-1PHK2.js","./2PQNgpBd.js","./DsanjglN.js","./B_DA9RKE2.js","./D33dA--e.js","./yMgjaRvh2.js","./BjcV1PlZ.js","./BTn_GkPS.js","./BOogSHps2.js","./D_sriNfV2.js","./X_DUeLZp2.js","./DmLgVuva2.js","./C0bVU7gr2.js","./Ouh6Dj2I2.js","./Dn7LRnjg2.js","./-TjUTcZv2.js","./Y-eU8Aa32.js","./Dg_1c8FK2.js","./CG84LPq-.js","./BmWTAsFW.js","./B5XQZRTz.js","./BDDiPmhF.js","./BYJC6_MM.js","./DOPTvi6T.js","./CvaH7m0y.js","./O2P-f9sv.js","./BQ9wXJVQ2.js","./OnYyYdSr2.js","./ImGf_A8f.js","./DHbhVvym2.js","./0fbKjx7U2.js","./C2F4p_R3.js","./L5YNUO99.js","./6qfzuuhO.js","./Od6vz3AQ.js","./CMdgFTSd.js","./C7FdbtRT.js","./BPr73Pj8.js","./COfTZUNn.js","./D2jkj_HI.js","./CzgNarYu.js","./Blw0ugqW2.js","./CiotqGya.js","./CBuincfO.js","./CvWN0JfP.js","./NC6fXeo_.js","./DXsj0Ygw.js","./DO4myGf_.js","./ByMOJ7vP.js","./DoOTPDI-.js","./DiIbXgam.js","./BSkUUZJr2.js","./kwfd020K.js","./BMGkukPk.js","./b2R8Ad-3.js","./BnD013za.js","./2yUiEINB.js","./Cz47RMnI.js","./vDOh_fWF.js","./DFB29SWc.js","./B0j8dF6c.js","./CDYojaIH.js"])))=>i.map(i=>d[i]);
import{s as e}from"./DrKWWDpL.js";import{n as t,t as n}from"./DsQIgu-4.js";import{t as r}from"./DYP3EJMY.js";import{t as i}from"./DTkg6Mnx.js";import{n as a}from"./Dn7LRnjg2.js";import{t as o}from"./CvFbqtf9.js";import{t as s}from"./ByGkWwzP2.js";var c=e(r(),1);t();var l=new Set(`the.a.an.is.are.was.were.be.been.being.have.has.had.do.does.did.will.would.could.should.may.might.shall.can.need.dare.ought.used.to.of.in.for.on.with.at.by.from.as.into.through.during.before.after.above.below.between.out.off.over.under.again.further.then.once.and.but.or.nor.not.so.yet.both.either.neither.each.every.all.any.few.more.most.other.some.such.no.only.own.same.than.too.very.just.because.until.while.about.against.this.that.these.those.it.its`.split(`.`));function u(e){let t=e.toLowerCase().replace(/[^a-z0-9\s-]/g,``).split(/\s+/),n=new Set;for(let e of t)e.length>=4&&!l.has(e)&&n.add(e);return n}function d(e,t){if(e.size===0||t.size===0)return 0;let n=0;for(let r of e)t.has(r)&&n++;let r=e.size+t.size-n;return r>0?n/r:0}async function f(e,t){let r=t?.olderThanDays??90,i=t?.minClusterSize??3,{getBrainDb:s,getBrainNativeDb:l}=await n(async()=>{let{getBrainDb:e,getBrainNativeDb:t}=await import(`./BlapV1mo.js`);return{getBrainDb:e,getBrainNativeDb:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]),import.meta.url);await s(e);let f=l();if(!f)return{grouped:0,merged:0,archived:0};let p=new Date(Date.now()-r*24*60*60*1e3).toISOString().replace(`T`,` `).slice(0,19),m=o(f.prepare(`
    SELECT id, type, title, narrative, project, created_at
    FROM brain_observations
    WHERE created_at < ?
      AND narrative NOT LIKE '[ARCHIVED]%'
    ORDER BY created_at DESC
  `),p);if(m.length<i)return{grouped:0,merged:0,archived:0};let h=m.map(e=>({...e,keywords:u(`${e.title} ${e.narrative??``}`),clustered:!1})),g=[];for(let e=0;e<h.length;e++){if(h[e].clustered)continue;let t=[h[e]];h[e].clustered=!0;for(let n=e+1;n<h.length;n++)h[n].clustered||h[e].type===h[n].type&&d(h[e].keywords,h[n].keywords)>=.3&&(t.push(h[n]),h[n].clustered=!0);t.length>=i&&g.push(t)}let _=0,v=0,y=0,b=await a(e),x=new Date().toISOString().replace(`T`,` `).slice(0,19);for(let e of g){_+=e.length;let t=e.map(e=>e.title).join(`; `),n=`Consolidated: ${e[0].type} observations (${e.length} entries)`,r=`Merged from ${e.length} observations: ${t.slice(0,500)}`,i=(0,c.createHash)(`sha256`).update(n+r).digest(`hex`).slice(0,16),a=`O-${Date.now().toString(36)}`;await b.addObservation({id:a,type:e[0].type,title:n,narrative:r,contentHash:i,project:e[0].project??null,sourceType:`agent`,createdAt:x}),v++;for(let t of e)f.prepare(`
        UPDATE brain_observations
        SET narrative = '[ARCHIVED] ' || COALESCE(narrative, ''),
            updated_at = ?
        WHERE id = ?
      `).run(x,t.id),y++}return{grouped:_,merged:v,archived:y}}async function p(e){let{getBrainDb:t,getBrainNativeDb:r}=await n(async()=>{let{getBrainDb:e,getBrainNativeDb:t}=await import(`./BlapV1mo.js`);return{getBrainDb:e,getBrainNativeDb:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]),import.meta.url);await t(e);let i=r();if(!i)return{promoted:[],evicted:[]};let a=[],s=[],c=new Date().toISOString().replace(`T`,` `).slice(0,19),l=new Date(Date.now()-1440*60*1e3).toISOString().replace(`T`,` `).slice(0,19),u=new Date(Date.now()-10080*60*1e3).toISOString().replace(`T`,` `).slice(0,19),d=new Date(Date.now()-10080*60*1e3).toISOString().replace(`T`,` `).slice(0,19);for(let{table:e,dateCol:t}of[{table:`brain_observations`,dateCol:`created_at`},{table:`brain_learnings`,dateCol:`created_at`},{table:`brain_patterns`,dateCol:`extracted_at`},{table:`brain_decisions`,dateCol:`created_at`}]){let n=[];try{n=o(i.prepare(`
          SELECT id, citation_count, quality_score, verified
          FROM ${e}
          WHERE memory_tier = 'short'
            AND invalid_at IS NULL
            AND ${t} < ?
            AND (
              citation_count >= 3
              OR quality_score >= 0.7
              OR verified = 1
            )
        `),l)}catch{continue}for(let t of n)try{let n;n=t.citation_count>=3?`citationCount=${t.citation_count} >= 3, age > 24h`:(t.quality_score??0)>=.7?`qualityScore=${t.quality_score?.toFixed(2)} >= 0.70, age > 24h`:`verified=true, age > 24h`,i.prepare(`UPDATE ${e} SET memory_tier = 'medium', updated_at = ?, tier_promoted_at = ?, tier_promotion_reason = ? WHERE id = ?`).run(c,c,n,t.id),a.push({id:t.id,table:e,fromTier:`short`,toTier:`medium`,reason:n})}catch{}let r=[];try{r=o(i.prepare(`
          SELECT id, citation_count, quality_score, verified
          FROM ${e}
          WHERE memory_tier = 'medium'
            AND invalid_at IS NULL
            AND ${t} < ?
            AND (citation_count >= 5 OR verified = 1)
        `),u)}catch{continue}for(let t of r)try{let n=t.citation_count>=5?`citationCount=${t.citation_count} >= 5, age > 7d`:`verified=true, age > 7d`;i.prepare(`UPDATE ${e} SET memory_tier = 'long', updated_at = ?, tier_promoted_at = ?, tier_promotion_reason = ? WHERE id = ?`).run(c,c,n,t.id),a.push({id:t.id,table:e,fromTier:`medium`,toTier:`long`,reason:n})}catch{}let f=[];try{f=o(i.prepare(`
          SELECT id, quality_score
          FROM ${e}
          WHERE memory_tier = 'short'
            AND invalid_at IS NULL
            AND ${t} < ?
            AND (verified = 0 OR verified IS NULL)
            AND (quality_score IS NULL OR quality_score < 0.5)
        `),d)}catch{continue}for(let t of f)try{i.prepare(`UPDATE ${e} SET invalid_at = ?, updated_at = ? WHERE id = ?`).run(c,c,t.id),s.push({id:t.id,table:e,tier:`short`,reason:`age > 7d, unverified, qualityScore=${t.quality_score?.toFixed(2)??`null`} < 0.5`})}catch{}}return{promoted:a,evicted:s}}async function m(e,t,r=`session_end`){let a=Date.now(),o={deduplicated:0,qualityRecomputed:0,tierPromotions:{promoted:[],evicted:[]},contradictions:0,softEvicted:0,edgesStrengthened:0,nexusEdgesStrengthened:0,summariesGenerated:0};try{o.deduplicated=await g(e)}catch(e){console.warn(`[consolidation] Step 1 deduplication failed:`,e)}try{o.qualityRecomputed=await _(e)}catch(e){console.warn(`[consolidation] Step 2 quality recompute failed:`,e)}try{o.tierPromotions=await p(e)}catch(e){console.warn(`[consolidation] Step 3 tier promotion failed:`,e)}try{o.autoExtractPromotion=await h(e)}catch(e){console.warn(`[consolidation] Step 3b promotion fulfillment failed:`,e)}try{let{detectContradictions:t}=await n(async()=>{let{detectContradictions:e}=await import(`./CN3sIbmT2.js`);return{detectContradictions:e}},__vite__mapDeps([21,22,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,23]),import.meta.url);o.contradictions=(await t(e)).length}catch(e){console.warn(`[consolidation] Step 4 contradiction detection failed:`,e)}try{let{dedupePatterns:t}=await n(async()=>{let{dedupePatterns:e}=await import(`./CN3sIbmT2.js`);return{dedupePatterns:e}},__vite__mapDeps([21,22,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,23]),import.meta.url);o.patternDeduped=await t(e)}catch(e){console.warn(`[consolidation] Step 4b pattern dedup failed:`,e)}try{o.softEvicted=await v(e)}catch(e){console.warn(`[consolidation] Step 5 soft eviction failed:`,e)}try{o.edgesStrengthened=await b(e)}catch(e){console.warn(`[consolidation] Step 6 edge strengthening failed:`,e)}try{let{extractNexusPairsFromRetrievalLog:t,strengthenNexusCoAccess:r}=await n(async()=>{let{extractNexusPairsFromRetrievalLog:e,strengthenNexusCoAccess:t}=await import(`./BMB7x0Pe.js`);return{extractNexusPairsFromRetrievalLog:e,strengthenNexusCoAccess:t}},__vite__mapDeps([24,3,2,23]),import.meta.url),i=await t(e);i.length>0?o.nexusEdgesStrengthened=(await r(i)).strengthened:o.nexusEdgesStrengthened=0}catch(e){console.warn(`[consolidation] Step 6b nexus plasticity failed:`,e),o.nexusEdgesStrengthened=0}try{let{applyPlasticityDecay:e}=await n(async()=>{let{applyPlasticityDecay:e}=await import(`./BMB7x0Pe.js`);return{applyPlasticityDecay:e}},__vite__mapDeps([24,3,2,23]),import.meta.url);o.nexusEdgesDecayed=(await e()).updated}catch(e){console.warn(`[consolidation] Step 6c plasticity decay failed:`,e)}try{o.summariesGenerated=(await f(e,{olderThanDays:30,minClusterSize:5})).merged}catch(e){console.warn(`[consolidation] Step 7 summary generation failed:`,e)}try{let{autoLinkMemories:t}=await n(async()=>{let{autoLinkMemories:e}=await import(`./B1GXAVRr.js`);return{autoLinkMemories:e}},__vite__mapDeps([25,2,26,6,3,7,8,9,5,4,10,11,12,13,14,15,16,17,27,19,28,1,18,20,29,30,31,32,23]),import.meta.url);o.graphLinksCreated=(await t(e)).linked}catch(e){console.warn(`[consolidation] Step 8 graph memory bridge failed:`,e)}try{let{backfillRewardSignals:r}=await n(async()=>{let{backfillRewardSignals:e}=await import(`./D33dA--e.js`);return{backfillRewardSignals:e}},__vite__mapDeps([33,34,3,2,23]),import.meta.url);o.rewardBackfilled=await r(e,t??null)}catch(e){console.warn(`[consolidation] Step 9a reward backfill failed:`,e)}try{let{correlateOutcomes:t}=await n(async()=>{let{correlateOutcomes:e}=await import(`./BjcV1PlZ.js`);return{correlateOutcomes:e}},__vite__mapDeps([35,36,3,2,23]),import.meta.url),r=await t(e);o.outcomeCorrelation={boosted:r.boosted,penalized:r.penalized,flaggedForPruning:r.flaggedForPruning}}catch(e){console.warn(`[consolidation] Step 9a.5 outcome correlation failed:`,e)}try{let{applyStdpPlasticity:r,shouldRunPlasticity:i}=await n(async()=>{let{applyStdpPlasticity:e,shouldRunPlasticity:t}=await import(`./D33dA--e.js`);return{applyStdpPlasticity:e,shouldRunPlasticity:t}},__vite__mapDeps([33,34,3,2,23]),import.meta.url);await i(e,t??null,2)?o.stdpPlasticity=await r(e):o.stdpPlasticity={ltpEvents:0,ltdEvents:0,edgesCreated:0,pairsExamined:0}}catch(e){console.warn(`[consolidation] Step 9b STDP plasticity failed:`,e)}try{let{applyHomeostaticDecay:t}=await n(async()=>{let{applyHomeostaticDecay:e}=await import(`./D33dA--e.js`);return{applyHomeostaticDecay:e}},__vite__mapDeps([33,34,3,2,23]),import.meta.url);o.homeostaticDecay=await t(e)}catch(e){console.warn(`[consolidation] Step 9c homeostatic decay failed:`,e)}try{let{pruneStaleHistory:t}=await n(async()=>{let{pruneStaleHistory:e}=await import(`./D33dA--e.js`);return{pruneStaleHistory:e}},__vite__mapDeps([33,34,3,2,23]),import.meta.url);o.historyRetention=await t(e)}catch(e){console.warn(`[consolidation] Step 9d history retention failed:`,e)}try{let{runPruneSweep:t}=await n(async()=>{let{runPruneSweep:e}=await import(`./BOogSHps2.js`);return{runPruneSweep:e}},__vite__mapDeps([37,38,2,3,4,5,39,40,41,42,43,31,8,1,6,7,9,10,11,12,13,14,15,16,17,18,19,20,23,44,45,46,47,30,48,49,28,26,27,50,51,29,32,52,53,54,55,56,57,58]),import.meta.url),r=await t(e);o.pruneSweep={deleted:r.deleted,wouldDelete:r.wouldDelete,dryRun:r.dryRun}}catch(e){console.warn(`[consolidation] Step 9f prune sweep failed:`,e)}try{let{consolidateAttention:t}=await n(async()=>{let{consolidateAttention:e}=await import(`./0fbKjx7U2.js`);return{consolidateAttention:e}},__vite__mapDeps([59,3,2,4,5,43,31,8,1,6,7,9,10,11,12,13,14,15,16,17,18,19,20]),import.meta.url),r=await t(e);o.attentionConsolidation={reviewed:r.reviewed,promoted:r.promoted,kept:r.kept,discarded:r.discarded}}catch(e){i(`consolidation`).warn({err:e},`Step 9g attention consolidation failed`)}try{let{getBrainDb:i,getBrainNativeDb:s}=await n(async()=>{let{getBrainDb:e,getBrainNativeDb:t}=await import(`./BlapV1mo.js`);return{getBrainDb:e,getBrainNativeDb:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]),import.meta.url);await i(e);let c=s();if(c){let e=!1;try{c.prepare(`SELECT 1 FROM brain_consolidation_events LIMIT 1`).get(),e=!0}catch{}if(e){let e=Date.now()-a,n=JSON.stringify(o);c.prepare(`INSERT INTO brain_consolidation_events
               (trigger, session_id, step_results_json, duration_ms, succeeded)
             VALUES (?, ?, ?, ?, 1)`).run(r,t??null,n,e)}}}catch(e){console.warn(`[consolidation] Step 9e consolidation event log failed:`,e)}try{let{runSleepConsolidation:t}=await n(async()=>{let{runSleepConsolidation:e}=await import(`./C2F4p_R3.js`);return{runSleepConsolidation:e}},__vite__mapDeps([60,2,3,61,62,63,64,65,66,67,68,69,70,71,72,4,5,13,14,73,74,75,76,11,77,51,10,12,15,78,79,80,81,50,82,83,84,46,1,6,7,8,9,16,17,18,19,20,44,85,23,43,31,86]),import.meta.url),r=await t(e);o.sleepConsolidation={ran:r.ran,merged:r.mergeDuplicates.merged,pruned:r.pruneStale.pruned,patternsGenerated:r.strengthenPatterns.patternsGenerated,insightsStored:r.generateInsights.insightsStored},r.ran?o.summariesGenerated+=r.strengthenPatterns.patternsGenerated+r.generateInsights.insightsStored:console.warn(`[consolidation] Step 10 sleep consolidation skipped (disabled or no LLM)`)}catch(e){console.warn(`[consolidation] Step 10 sleep consolidation failed:`,e)}return o}async function h(e){let t={invocations:0,candidates:0,promoted:0,rejected:{already_fulfilled:0,store_error:0,no_narrative:0,dedup_hash:0,other:0}},{getBrainDb:r,getBrainNativeDb:i}=await n(async()=>{let{getBrainDb:e,getBrainNativeDb:t}=await import(`./BlapV1mo.js`);return{getBrainDb:e,getBrainNativeDb:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]),import.meta.url);await r(e);let a=i();if(!a)return t;try{a.prepare(`SELECT 1 FROM brain_promotion_log LIMIT 1`).get()}catch{return t}let s=[];try{s=o(a.prepare(`
        SELECT id, observation_id, to_tier, score, fulfilled_at
        FROM brain_promotion_log
        WHERE fulfilled_at IS NULL
          AND decided_by = 'composite-scorer'
        ORDER BY score DESC
        LIMIT 200
      `))}catch{return t}if(t.invocations=s.length,s.length===0)return t;let c=s.map(e=>e.observation_id),l=c.map(()=>`?`).join(`, `),u=new Map;try{let e=o(a.prepare(`SELECT id, type, title, narrative, created_at, citation_count
         FROM brain_observations
         WHERE id IN (${l}) AND invalid_at IS NULL`),...c);for(let t of e)u.set(t.id,t)}catch{return t}let d=new Date().toISOString().replace(`T`,` `).slice(0,19),{checkHashDedup:f}=await n(async()=>{let{checkHashDedup:e}=await import(`./vDOh_fWF.js`);return{checkHashDedup:e}},__vite__mapDeps([87,88,2,3,42,41,43,31,8,1,4,5,6,7,9,10,11,12,13,14,15,16,17,18,19,20,23,46]),import.meta.url);for(let r of s){let i=u.get(r.observation_id);if(!i){t.rejected.other++;continue}let o=i.narrative??i.title;if(!o?.trim()){t.rejected.no_narrative++;try{a.prepare(`UPDATE brain_promotion_log SET fulfilled_at = ?, fulfillment_note = 'no-narrative' WHERE id = ?`).run(d,r.id)}catch{}continue}if(t.candidates++,(await f(e,o,r.to_tier===`pattern`?`brain_patterns`:`brain_learnings`)).matched){t.rejected.dedup_hash++;try{a.prepare(`UPDATE brain_promotion_log SET fulfilled_at = ?, fulfillment_note = 'dedup-hash' WHERE id = ?`).run(d,r.id)}catch{}continue}try{if(r.to_tier===`pattern`){let{storePattern:t}=await n(async()=>{let{storePattern:e}=await import(`./B0j8dF6c.js`);return{storePattern:e}},__vite__mapDeps([89,86,2,3,46,4,5,1,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,44,85,23,43,31]),import.meta.url);await t(e,{type:`workflow`,pattern:o,context:i.title,_skipGate:!0})}else{let{storeLearning:t}=await n(async()=>{let{storeLearning:e}=await import(`./CDYojaIH.js`);return{storeLearning:e}},__vite__mapDeps([90,84,2,3,46,4,5,1,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,44,85,23,43,31]),import.meta.url);await t(e,{insight:o,source:`promotion-log:${r.id}`,confidence:Math.min(r.score,1),actionable:i.type===`bugfix`||i.type===`discovery`,_skipGate:!0})}t.promoted++;try{a.prepare(`UPDATE brain_promotion_log SET fulfilled_at = ?, fulfillment_note = 'stored' WHERE id = ?`).run(d,r.id)}catch{}}catch{t.rejected.store_error++}}return t}async function g(e){let{getBrainDb:t,getBrainNativeDb:r}=await n(async()=>{let{getBrainDb:e,getBrainNativeDb:t}=await import(`./BlapV1mo.js`);return{getBrainDb:e,getBrainNativeDb:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]),import.meta.url);await t(e);let i=r();if(!i)return 0;let a=0,s=new Date().toISOString().replace(`T`,` `).slice(0,19),c=o(i.prepare(`
      SELECT content_hash, COUNT(*) as cnt
      FROM brain_observations
      WHERE content_hash IS NOT NULL
        AND invalid_at IS NULL
      GROUP BY content_hash
      HAVING cnt > 1
    `));for(let e of c){let t=o(i.prepare(`
        SELECT id, quality_score, citation_count
        FROM brain_observations
        WHERE content_hash = ?
          AND invalid_at IS NULL
        ORDER BY quality_score DESC, citation_count DESC
      `),e.content_hash);if(t.length<2)continue;let[n,...r]=t;if(!n)continue;let c=n.citation_count;for(let e of r)c+=e.citation_count,i.prepare(`UPDATE brain_observations SET invalid_at = ?, updated_at = ? WHERE id = ?`).run(s,s,e.id),a++;c!==n.citation_count&&i.prepare(`UPDATE brain_observations SET citation_count = ?, updated_at = ? WHERE id = ?`).run(c,s,n.id)}return a}async function _(e){let{getBrainDb:t,getBrainNativeDb:r}=await n(async()=>{let{getBrainDb:e,getBrainNativeDb:t}=await import(`./BlapV1mo.js`);return{getBrainDb:e,getBrainNativeDb:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]),import.meta.url);await t(e);let i=r();if(!i)return 0;let a=0,o=new Date().toISOString().replace(`T`,` `).slice(0,19);try{let e=i.prepare(`
      UPDATE brain_observations
      SET quality_score = MIN(1.0, COALESCE(quality_score, 0.5) + MIN(0.15, citation_count * 0.01)),
          updated_at = ?
      WHERE citation_count > 0
        AND invalid_at IS NULL
    `).run(o);a+=typeof e.changes==`number`?e.changes:0}catch{}try{let e=i.prepare(`
      UPDATE brain_learnings
      SET quality_score = MIN(1.0, COALESCE(quality_score, 0.5) + MIN(0.15, citation_count * 0.01)),
          updated_at = ?
      WHERE citation_count > 0
        AND invalid_at IS NULL
    `).run(o);a+=typeof e.changes==`number`?e.changes:0}catch{}return a}async function v(e){let{getBrainDb:t,getBrainNativeDb:r}=await n(async()=>{let{getBrainDb:e,getBrainNativeDb:t}=await import(`./BlapV1mo.js`);return{getBrainDb:e,getBrainNativeDb:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]),import.meta.url);await t(e);let i=r();if(!i)return 0;let a=0,o=new Date().toISOString().replace(`T`,` `).slice(0,19),s=new Date(Date.now()-720*60*60*1e3).toISOString().replace(`T`,` `).slice(0,19);for(let{table:e,dateCol:t}of[{table:`brain_observations`,dateCol:`created_at`},{table:`brain_learnings`,dateCol:`created_at`},{table:`brain_patterns`,dateCol:`extracted_at`},{table:`brain_decisions`,dateCol:`created_at`}])try{let n=i.prepare(`
        UPDATE ${e}
        SET invalid_at = ?, updated_at = ?
        WHERE memory_tier = 'medium'
          AND invalid_at IS NULL
          AND quality_score IS NOT NULL
          AND quality_score < 0.30
          AND ${t} < ?
      `).run(o,o,s);a+=typeof n.changes==`number`?n.changes:0}catch{}return a}function y(e){let t=e.trim();if(t.startsWith(`[`))try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}return t.split(`,`).map(e=>e.trim()).filter(Boolean)}async function b(e){let{getBrainDb:t,getBrainNativeDb:r}=await n(async()=>{let{getBrainDb:e,getBrainNativeDb:t}=await import(`./BlapV1mo.js`);return{getBrainDb:e,getBrainNativeDb:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]),import.meta.url);await t(e);let i=r();if(!i)return 0;try{i.prepare(`SELECT 1 FROM brain_retrieval_log LIMIT 1`).get()}catch{return 0}let a=new Date(Date.now()-720*60*60*1e3).toISOString().replace(`T`,` `).slice(0,19),c=new Date().toISOString().replace(`T`,` `).slice(0,19),l=[];try{l=o(i.prepare(`SELECT entry_ids, query FROM brain_retrieval_log WHERE created_at >= ? LIMIT 1000`),a)}catch{return 0}let u=new Map;for(let e of l){let t=y(e.entry_ids);if(!(t.length<2))for(let n=0;n<t.length;n++)for(let r=n+1;r<t.length;r++){let i=t[n],a=t[r],o=i<a?`${i}|${a}`:`${a}|${i}`,s=u.get(o)??new Set;s.add(e.query),u.set(o,s)}}let d=0;for(let[e,t]of u){if(t.size<3)continue;let[n,r]=e.split(`|`);if(!n||!r)continue;let a=`observation:${n}`,o=`observation:${r}`;try{let e=i.prepare(`
        UPDATE brain_page_edges
        SET weight = MIN(1.0, weight + 0.1),
            plasticity_class = 'hebbian'
        WHERE from_id = ? AND to_id = ? AND edge_type = ?
      `).run(a,o,s.CO_RETRIEVED);(typeof e.changes==`number`?e.changes:0)===0&&i.prepare(`
            INSERT OR IGNORE INTO brain_page_edges
              (from_id, to_id, edge_type, weight, provenance, plasticity_class, created_at)
            VALUES (?, ?, ?, 0.3, 'consolidation:co-retrieval', 'hebbian', ?)
          `).run(a,o,s.CO_RETRIEVED,c),d++}catch{}}return d}export{p as i,h as n,m as r,f as t};