const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./DfVstSkc.js","./BSkUUZJr2.js","./DrKWWDpL.js","./kwfd020K.js","./DIQmuJJZ.js","./D7w7HllH.js","./DB5ifLM-.js","./DYP3EJMY.js","./CxlOpib82.js","./BDDiPmhF.js","./BYJC6_MM.js","./CX8DOZuw2.js","./DsQIgu-4.js","./DOqzs8kl2.js","./BlapV1mo.js","./bG-fsHMS.js","./DTkg6Mnx.js","./DeO5NWhN.js","./DgZn9uJn.js","./CbGRcr-D.js","./CudpqN6Z.js","./Czb-RtcG.js","./C0nwgWmB.js","./D-eE9s2f.js","./CWxOfblT.js","./DlZwu-Y7.js","./Cgka69ys2.js","./IobYPI5p.js","./D84sFRHU.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{a as i}from"./bG-fsHMS.js";import{t as a}from"./CvFbqtf9.js";import{t as o}from"./BnD013za.js";import{t as s}from"./L5YNUO99.js";import{n as c}from"./Cz47RMnI.js";var l=e(r(),1);t();var u=`consolidation`,d=.85,f=7,p=.4,m=3,h=1024,g=`sleep-consolidation`;async function _(e){try{let{loadConfig:t}=await n(async()=>{let{loadConfig:e}=await import(`./DfVstSkc.js`);return{loadConfig:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]),import.meta.url);return{enabled:(await t(e)).brain?.sleepConsolidation?.enabled!==!1}}catch{return{enabled:!0}}}async function v(e,t,n){return(await s(u,t,n,{projectRoot:e,maxTokens:h,signal:AbortSignal.timeout(3e4)}))?.content??null}async function y(e,t,n){if(t===void 0)return e;let r=[{role:`user`,content:e}],i=Math.ceil(e.length/4);if(!t.shouldCompress(i,1e5))return e;try{let i=(await t.compress(r,n)).compressedMessages.find(e=>e.role===`assistant`);return i&&typeof i.content==`string`?i.content:e}catch{return e}}function b(e){try{let t=e.replace(/^```(?:json)?\s*/m,``).replace(/\s*```\s*$/m,``).trim();return JSON.parse(t)}catch{return null}}function x(e,t){if(!e||!t||e.length===0||e.length!==t.length)return 0;let n=Math.floor(e.length/4);if(n===0)return 0;let r=0,i=0,a=0;for(let o=0;o<n;o++){let n=e.readFloatLE(o*4),s=t.readFloatLE(o*4);r+=n*s,i+=n*n,a+=s*s}let o=Math.sqrt(i)*Math.sqrt(a);return o===0?0:r/o}async function S(e){let{getBrainDb:t}=await n(async()=>{let{getBrainDb:e}=await import(`./BlapV1mo.js`);return{getBrainDb:e}},__vite__mapDeps([14,15,2,12,16,7,17,18,19,20,11,13,4,5,6,8,21,22,23,24,25]),import.meta.url);await t(e);let r=i();if(!r)return{merged:0,llmDecisions:0};let o=0,s=0,c=new Date().toISOString().replace(`T`,` `).slice(0,19),l;try{l=a(r.prepare(`
        SELECT id, title, narrative, quality_score, citation_count, memory_tier, created_at, embedding
        FROM brain_observations
        WHERE embedding IS NOT NULL
          AND invalid_at IS NULL
          AND memory_tier = 'short'
        ORDER BY quality_score DESC
        LIMIT 200
      `))}catch{return{merged:0,llmDecisions:0}}if(l.length<2)return{merged:0,llmDecisions:0};let u=[];for(let e=0;e<l.length;e++)for(let t=e+1;t<l.length;t++){let n=x(l[e].embedding,l[t].embedding);n>=d&&u.push({a:l[e],b:l[t],similarity:n})}if(u.length===0)return{merged:0,llmDecisions:0};let f=u.slice(0,10),p=f.map(({a:e,b:t,similarity:n},r)=>({pair:r,similarity:Math.round(n*100)/100,a:{id:e.id,text:`${e.title??``} ${e.narrative??``}`.trim().slice(0,120)},b:{id:t.id,text:`${t.title??``} ${t.narrative??``}`.trim().slice(0,120)}})),m=`Memory entry pairs to evaluate:\n${JSON.stringify(p,null,2)}`,h=[],g=await v(e,`You are a memory deduplication assistant. Given pairs of nearly-identical memory entries evaluate whether they should be merged. For each pair output: {"pair":N,"merge":true/false,"keep":"<id>"}. Output a JSON array only, no prose. Merge when content is substantially the same; keep when content is distinct.`,m);if(g){let e=b(g);Array.isArray(e)&&(h=e,s=h.filter(e=>e.merge).length)}let _=new Set;for(let e=0;e<f.length;e++){let{a:t,b:n}=f[e];if(_.has(t.id)||_.has(n.id))continue;let i=h.find(t=>t.pair===e);if(!(!i||i.merge))continue;let a,s;i?.keep===t.id||i?.keep===n.id?(a=i.keep,s=a===t.id?n.id:t.id):(a=(t.quality_score??.5)>=(n.quality_score??.5)?t.id:n.id,s=a===t.id?n.id:t.id);let l=t.id===a?t:n,u=t.id===s?t:n,d=(l.citation_count??0)+(u.citation_count??0);try{r.prepare(`UPDATE brain_observations SET invalid_at = ?, updated_at = ? WHERE id = ?`).run(c,c,s),d>(l.citation_count??0)&&r.prepare(`UPDATE brain_observations SET citation_count = ?, updated_at = ? WHERE id = ?`).run(d,c,a),o++,_.add(t.id),_.add(n.id)}catch{}}return{merged:o,llmDecisions:s}}async function C(e){let{getBrainDb:t}=await n(async()=>{let{getBrainDb:e}=await import(`./BlapV1mo.js`);return{getBrainDb:e}},__vite__mapDeps([14,15,2,12,16,7,17,18,19,20,11,13,4,5,6,8,21,22,23,24,25]),import.meta.url);await t(e);let r=i();if(!r)return{pruned:0,preserved:0};let o=new Date(Date.now()-f*24*60*60*1e3).toISOString().replace(`T`,` `).slice(0,19),s=new Date().toISOString().replace(`T`,` `).slice(0,19),c;try{c=a(r.prepare(`
        SELECT id, title, narrative, quality_score, citation_count, memory_tier, created_at, embedding
        FROM brain_observations
        WHERE memory_tier = 'short'
          AND invalid_at IS NULL
          AND quality_score IS NOT NULL
          AND quality_score < ?
          AND created_at < ?
        ORDER BY quality_score ASC
        LIMIT 50
      `),p,o)}catch{return{pruned:0,preserved:0}}if(c.length===0)return{pruned:0,preserved:0};let l=c.slice(0,20).map(e=>({id:e.id,age_days:Math.round((Date.now()-new Date(e.created_at??0).getTime())/(1440*60*1e3)),quality:Math.round((e.quality_score??0)*100)/100,citations:e.citation_count,text:`${e.title??``} ${e.narrative??``}`.trim().slice(0,100)})),u=`Candidate entries for eviction:\n${JSON.stringify(l,null,2)}`,d=new Set,m=await v(e,`You are a memory curator. Given a list of low-quality, stale memory entries, decide which ones are worth preserving (i.e. contain unique, non-redundant information that would be hard to reconstruct). Return a JSON array of IDs to preserve: {"preserve":["id1","id2",...]}. Only preserve entries with genuinely unique information. When in doubt, allow eviction.`,u);if(m){let e=b(m);e&&Array.isArray(e.preserve)&&(d=new Set(e.preserve))}let h=0,g=0;for(let e of c)if(d.has(e.id))try{r.prepare(`UPDATE brain_observations SET quality_score = 0.5, updated_at = ? WHERE id = ?`).run(s,e.id),g++}catch{}else try{r.prepare(`UPDATE brain_observations SET invalid_at = ?, updated_at = ? WHERE id = ?`).run(s,s,e.id),h++}catch{}return{pruned:h,preserved:g}}async function w(e,t){let{getBrainDb:r}=await n(async()=>{let{getBrainDb:e}=await import(`./BlapV1mo.js`);return{getBrainDb:e}},__vite__mapDeps([14,15,2,12,16,7,17,18,19,20,11,13,4,5,6,8,21,22,23,24,25]),import.meta.url);await r(e);let o=i();if(!o)return{synthesized:0,patternsGenerated:0};let s;try{s=a(o.prepare(`
        SELECT id, insight, confidence, citation_count, source, memory_tier
        FROM brain_learnings
        WHERE citation_count >= ?
          AND invalid_at IS NULL
        ORDER BY citation_count DESC, confidence DESC
        LIMIT 10
      `),m)}catch{return{synthesized:0,patternsGenerated:0}}if(s.length===0)return{synthesized:0,patternsGenerated:0};let l;try{l=a(o.prepare(`
        SELECT id, pattern, context, impact, frequency, memory_tier
        FROM brain_patterns
        WHERE source_type = ?
          AND invalid_at IS NULL
        ORDER BY frequency DESC
        LIMIT 5
      `),g)}catch{l=[]}let u=l.map(e=>e.pattern.slice(0,80)).join(`; `),d=s.map(e=>({id:e.id,insight:e.insight.slice(0,200),citations:e.citation_count,confidence:Math.round(e.confidence*100)/100})),f=await v(e,`You are a knowledge synthesizer. Given frequently-cited learnings, extract 1-3 higher-order patterns that capture the essence of what has been repeatedly confirmed. Each pattern should be actionable and generalizable. Return JSON: {"patterns":[{"pattern":"...","context":"...","impact":"high|medium|low"}]}. Skip patterns already captured in the existing list. Output JSON only, no prose.`,await y(`Frequently-cited learnings to synthesize:\n${JSON.stringify(d,null,2)}\n\nAlready captured patterns (do not duplicate): ${u||`none`}`,t,`learning synthesis`));if(!f)return{synthesized:s.length,patternsGenerated:0};let p=b(f);if(!p||!Array.isArray(p.patterns))return{synthesized:s.length,patternsGenerated:0};let h=0;for(let t of p.patterns)if(t.pattern?.trim())try{let n=t.impact===`high`||t.impact===`medium`||t.impact===`low`?t.impact:`medium`;await c(e,{type:`optimization`,pattern:t.pattern.slice(0,500),context:(t.context??``).slice(0,500),impact:n,source:g}),h++}catch{}return{synthesized:s.length,patternsGenerated:h}}async function T(e,t){let{getBrainDb:r}=await n(async()=>{let{getBrainDb:e}=await import(`./BlapV1mo.js`);return{getBrainDb:e}},__vite__mapDeps([14,15,2,12,16,7,17,18,19,20,11,13,4,5,6,8,21,22,23,24,25]),import.meta.url);await r(e);let s=i();if(!s)return{clustersProcessed:0,insightsStored:0};let c=new Date(Date.now()-336*60*60*1e3).toISOString().replace(`T`,` `).slice(0,19),u;try{u=a(s.prepare(`
        SELECT id,
               COALESCE(title, '') || ' ' || COALESCE(narrative, '') AS text
        FROM brain_observations
        WHERE created_at >= ?
          AND invalid_at IS NULL
          AND (source_type IS NULL OR source_type NOT IN (?, 'observer-compressed'))
        ORDER BY quality_score DESC
        LIMIT 60
      `),c,g)}catch{return{clustersProcessed:0,insightsStored:0}}if(u.length<5)return{clustersProcessed:0,insightsStored:0};let d=new Set([`this`,`that`,`with`,`from`,`have`,`been`,`will`,`when`,`then`,`they`,`were`,`also`,`into`,`over`,`some`,`more`,`very`,`just`,`each`,`both`]);function f(e){let t=e.toLowerCase().replace(/[^a-z0-9\s]/g,` `).split(/\s+/).filter(e=>e.length>=4&&!d.has(e));return new Set(t)}let p=u.map(e=>({id:e.id,text:e.text,tokens:f(e.text)})),m=[];for(let e of p){let t=!1;for(let n of m){let r=p.find(e=>e.id===n.memberIds[0]);if(!r)continue;let i=0;for(let t of e.tokens)r.tokens.has(t)&&i++;if(i>=3){n.memberIds.push(e.id),n.texts.push(e.text.slice(0,120)),t=!0;break}}!t&&m.length<5&&m.push({memberIds:[e.id],texts:[e.text.slice(0,120)]})}let h=m.filter(e=>e.memberIds.length>=3);if(h.length===0)return{clustersProcessed:0,insightsStored:0};let _=h.map((e,t)=>({cluster:t,entries:e.texts.slice(0,5)})),x=await v(e,`You are a cross-domain insight extractor. Given clusters of related memory entries, identify one cross-cutting insight per cluster that would not be obvious from any single entry. Return JSON: {"insights":[{"cluster":N,"insight":"...","confidence":0.0-1.0}]}. Only include high-value insights (confidence >= 0.7). Output JSON only, no prose.`,await y(`Memory clusters to analyse:\n${JSON.stringify(_,null,2)}`,t,`insight extraction`));if(!x)return{clustersProcessed:h.length,insightsStored:0};let S=b(x);if(!S||!Array.isArray(S.insights))return{clustersProcessed:h.length,insightsStored:0};let C=0,w=new Date().toISOString().replace(`T`,` `).slice(0,19);for(let t of S.insights){if(!t.insight?.trim())continue;let n=Math.max(0,Math.min(1,t.confidence??.7));if(!(n<.7))try{await o(e,{insight:t.insight.slice(0,500),source:g,confidence:n,actionable:!0,application:`Cross-cutting insight synthesized from clustered observations`}),C++}catch{}}if(C>0)try{let e=`O-${(0,l.randomBytes)(4).toString(`hex`)}`;s.prepare(`
          INSERT INTO brain_observations
            (id, type, title, narrative, source_type, quality_score, memory_tier, created_at)
          VALUES (?, 'change', ?, ?, ?, 0.6, 'short', ?)
        `).run(e,`[sleep-consolidation] Insight generation run`,`Generated ${C} cross-cutting insights from ${h.length} clusters.`,g,w)}catch{}return{clustersProcessed:h.length,insightsStored:C}}async function E(e,t){let n={ran:!1,mergeDuplicates:{merged:0,llmDecisions:0},pruneStale:{pruned:0,preserved:0},strengthenPatterns:{synthesized:0,patternsGenerated:0},generateInsights:{clustersProcessed:0,insightsStored:0}},r;try{r=await _(e)}catch{r={enabled:!0}}if(!r.enabled)return n;let i={ran:!0,mergeDuplicates:{merged:0,llmDecisions:0},pruneStale:{pruned:0,preserved:0},strengthenPatterns:{synthesized:0,patternsGenerated:0},generateInsights:{clustersProcessed:0,insightsStored:0}};try{i.mergeDuplicates=await S(e)}catch(e){console.warn(`[sleep-consolidation] Step 1 (merge duplicates) failed:`,e)}try{i.pruneStale=await C(e)}catch(e){console.warn(`[sleep-consolidation] Step 2 (prune stale) failed:`,e)}try{i.strengthenPatterns=await w(e,t)}catch(e){console.warn(`[sleep-consolidation] Step 3 (strengthen patterns) failed:`,e)}try{i.generateInsights=await T(e,t)}catch(e){console.warn(`[sleep-consolidation] Step 4 (generate insights) failed:`,e)}try{i.dreamerUpgrade=await D(e)}catch(e){console.warn(`[sleep-consolidation] Wave 6 dreamer upgrade failed:`,e)}return i}async function D(e){let t={surprisalScored:0,treeNodesWritten:0,treeObsAssigned:0,specialistsCreated:0,specialistsRan:0,specialistsSkipped:0},[{computeSurprisalBatch:r},{buildSurprisalTree:i},{dispatchSpecialists:a}]=await Promise.all([n(()=>import(`./Cgka69ys2.js`),__vite__mapDeps([26,15,2,12,16,7,17,18,19,20,11,13,4,5,6,8,21,22,23,24,25]),import.meta.url),n(()=>import(`./IobYPI5p.js`),__vite__mapDeps([27,15,2,12,16,7,17,18,19,20,11,13,4,5,6,8,21,22,23,24,25]),import.meta.url),n(()=>import(`./D84sFRHU.js`),__vite__mapDeps([28,2,12,15,16,7,17,18,19,20,11,13,4,5,6,8,21,22,23,24,25]),import.meta.url)]),{getBrainNativeDb:o}=await n(async()=>{let{getBrainNativeDb:e}=await import(`./BlapV1mo.js`);return{getBrainNativeDb:e}},__vite__mapDeps([14,15,2,12,16,7,17,18,19,20,11,13,4,5,6,8,21,22,23,24,25]),import.meta.url),s=o();if(!s)return console.warn(`[dreamer-upgrade] No database available; skipping all steps.`),t;let c=s.prepare(`SELECT o.id, o.type, o.title, o.narrative, o.project, o.peer_id,
              o.source_session_id, e.embedding, o.created_at
       FROM brain_observations o
       LEFT JOIN brain_embeddings e ON e.id = o.id
       WHERE o.level IS NULL OR o.level = 'explicit'
       ORDER BY o.created_at DESC
       LIMIT 100`).all();if(c.length===0)return t;let l=r(c.map(e=>{let t=null;if(e.embedding instanceof Uint8Array||Buffer.isBuffer(e.embedding)){let n=e.embedding;t=Array.from(new Float32Array(n.buffer,n.byteOffset,n.byteLength/4))}return{id:e.id,embedding:t}}),{db:s});t.surprisalScored=l.length;let u=c.filter(e=>e.embedding instanceof Uint8Array||Buffer.isBuffer(e.embedding)).map(e=>{let t=e.embedding;return{id:e.id,embedding:Array.from(new Float32Array(t.buffer,t.byteOffset,t.byteLength/4))}});if(u.length>=2){let e=i(u,{db:s});t.treeNodesWritten=e.nodesWritten,t.treeObsAssigned=e.obsAssigned}let d=await a(c.map(e=>({id:e.id,type:String(e.type??``),title:e.title==null?null:String(e.title),narrative:e.narrative==null?null:String(e.narrative),project:e.project==null?null:String(e.project),peerId:String(e.peer_id??`global`),sourceSessionId:e.source_session_id==null?null:String(e.source_session_id)})),l,{db:s});return t.specialistsCreated=d.totalCreated,t.specialistsRan=d.specialists.filter(e=>!e.skipped).length,t.specialistsSkipped=d.totalSkipped,t}export{E as runSleepConsolidation};