const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./DtwiAqOL.js","./H8RQGUV9.js","./DsanjglN.js","./CbGRcr-D.js","./BVDTFQLg.js","./DIQmuJJZ.js","./DrKWWDpL.js","./D7w7HllH.js","./DB5ifLM-.js","./DYP3EJMY.js","./Cx_-1PHK2.js","./2PQNgpBd.js","./DgZn9uJn.js","./CudpqN6Z.js","./DTkg6Mnx.js","./CX8DOZuw2.js","./DsQIgu-4.js","./DOqzs8kl2.js","./CxlOpib82.js","./DeO5NWhN.js","./Czb-RtcG.js","./C0nwgWmB.js","./B_DA9RKE2.js","./DsuOXCFF2.js","./BlapV1mo.js","./bG-fsHMS.js","./D-eE9s2f.js","./CWxOfblT.js","./DlZwu-Y7.js","./DOhdLuUP.js","./C5cNeu21.js","./Ouh6Dj2I2.js","./DE1jbOEi.js","./DVQI6VOy.js","./D3qVY-Cc2.js","./QQHxtsJv2.js","./VsmLQChN.js","./CG84LPq-.js","./BmWTAsFW.js","./B5XQZRTz.js","./CVwAhlPZ.js","./BVC3q6GM.js","./B8PRMiR2.js","./BDDiPmhF.js","./BYJC6_MM.js","./DOPTvi6T.js","./CvaH7m0y.js","./O2P-f9sv.js","./BQ9wXJVQ2.js","./OnYyYdSr2.js","./CGVD7EpU.js"])))=>i.map(i=>d[i]);
import{n as e,t}from"./DsQIgu-4.js";import{t as n}from"./DHbhVvym2.js";import{n as r}from"./Dn7LRnjg2.js";import{t as i}from"./CvFbqtf9.js";import"./Y-eU8Aa32.js";import{t as a}from"./C0bVU7gr2.js";import{a as o,n as s}from"./DmLgVuva2.js";e();var c=4e3,l={cold:!0,warm:!0,hot:!0},u=.2,d=.3;function f(e){return Math.ceil(e.length/4)}async function p(e,n){let{listUserProfile:r}=await t(async()=>{let{listUserProfile:e}=await import(`./DtwiAqOL.js`);return{listUserProfile:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]),import.meta.url),{getSigil:i}=await t(async()=>{let{getSigil:e}=await import(`./DsuOXCFF2.js`);return{getSigil:e}},__vite__mapDeps([23,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]),import.meta.url),[a,o]=await Promise.all([r(n,{minConfidence:.5}),i(n,e).catch(()=>null)]);return{userProfile:a,peerInstructions:o?.systemPromptFragment??``,sigilCard:o}}async function m(e,n){let{getBrainNativeDb:r}=await t(async()=>{let{getBrainNativeDb:e}=await import(`./BlapV1mo.js`);return{getBrainNativeDb:e}},__vite__mapDeps([24,25,6,16,14,9,19,12,3,13,15,17,5,7,8,18,20,21,26,27,28]),import.meta.url),i=r();if(!i)return{peerLearnings:[],peerPatterns:[],decisions:[]};let a=e!==`global`,o=[];try{o=a?i.prepare(`SELECT id, insight, created_at, provenance_class FROM brain_learnings
             WHERE (peer_id = ? OR peer_id = 'global')
             ORDER BY created_at DESC LIMIT 10`).all(e):i.prepare(`SELECT id, insight, created_at, provenance_class FROM brain_learnings
             WHERE peer_id = 'global'
             ORDER BY created_at DESC LIMIT 10`).all()}catch{try{o=i.prepare(`SELECT id, insight, created_at FROM brain_learnings ORDER BY created_at DESC LIMIT 10`).all()}catch{o=[]}}let s=[];try{s=a?i.prepare(`SELECT id, pattern, extracted_at, provenance_class FROM brain_patterns
           WHERE (peer_id = ? OR peer_id = 'global')
           ORDER BY extracted_at DESC LIMIT 10`).all(e):i.prepare(`SELECT id, pattern, extracted_at, provenance_class FROM brain_patterns
           WHERE peer_id = 'global'
           ORDER BY extracted_at DESC LIMIT 10`).all()}catch{try{s=i.prepare(`SELECT id, pattern, extracted_at FROM brain_patterns ORDER BY extracted_at DESC LIMIT 10`).all()}catch{s=[]}}let c=[];try{c=a?i.prepare(`SELECT id, decision, created_at, provenance_class FROM brain_decisions
           WHERE (peer_id = ? OR peer_id = 'global')
           ORDER BY created_at DESC LIMIT 10`).all(e):i.prepare(`SELECT id, decision, created_at, provenance_class FROM brain_decisions
           WHERE peer_id = 'global'
           ORDER BY created_at DESC LIMIT 10`).all()}catch{try{c=i.prepare(`SELECT id, decision, created_at FROM brain_decisions ORDER BY created_at DESC LIMIT 10`).all()}catch{c=[]}}return{peerLearnings:o.map(e=>({id:e.id,insight:e.insight,createdAt:e.created_at,provenanceClass:e.provenance_class??`unswept-pre-T1151`})),peerPatterns:s.map(e=>({id:e.id,pattern:e.pattern,extractedAt:e.extracted_at,provenanceClass:e.provenance_class??`unswept-pre-T1151`})),decisions:c.map(e=>({id:e.id,decision:e.decision,createdAt:e.created_at,provenanceClass:e.provenance_class??`unswept-pre-T1151`}))}}async function h(e,n){let{getSessionNarrative:r}=await t(async()=>{let{getSessionNarrative:e}=await import(`./DOhdLuUP.js`);return{getSessionNarrative:e}},__vite__mapDeps([29,30,31,16,6,25,14,9,19,12,3,13,15,17,5,7,8,18,20,21,26,27,28]),import.meta.url),i=``;try{let{getBrainDb:a}=await t(async()=>{let{getBrainDb:e}=await import(`./BlapV1mo.js`);return{getBrainDb:e}},__vite__mapDeps([24,25,6,16,14,9,19,12,3,13,15,17,5,7,8,18,20,21,26,27,28]),import.meta.url);await a(n),i=(await r(e))?.narrative??``}catch{}let{getBrainNativeDb:a}=await t(async()=>{let{getBrainNativeDb:e}=await import(`./BlapV1mo.js`);return{getBrainNativeDb:e}},__vite__mapDeps([24,25,6,16,14,9,19,12,3,13,15,17,5,7,8,18,20,21,26,27,28]),import.meta.url),o=a(),s=[];if(o)try{s=o.prepare(`SELECT id, title, narrative, created_at, provenance_class
           FROM brain_observations
           WHERE source_session_id = ?
           ORDER BY created_at DESC, id DESC LIMIT 10`).all(e).map(e=>({id:e.id,title:e.title,narrative:e.narrative??``,createdAt:e.created_at,provenanceClass:e.provenance_class??`unswept-pre-T1151`}))}catch{s=[]}let c=[];try{let{getTaskAccessor:e}=await t(async()=>{let{getTaskAccessor:e}=await import(`./DE1jbOEi.js`);return{getTaskAccessor:e}},__vite__mapDeps([32,33,16,6]),import.meta.url),{tasks:r}=await(await e(n)).queryTasks({status:[`active`,`in_progress`],limit:10});c=r.map(e=>({id:e.id,title:e.title,status:e.status}))}catch{c=[]}return{sessionNarrative:i,recentObservations:s,activeTasks:c}}async function g(e,n){let{peerId:r,sessionId:i,query:a,passMask:o=l,tokenBudget:s=c}=e,g={...l,...o},_=Math.floor(s*u),v=Math.floor(s*d),[y,b,x]=await Promise.all([g.cold?(async()=>{try{let{getNexusDb:e}=await t(async()=>{let{getNexusDb:e}=await import(`./D3qVY-Cc2.js`);return{getNexusDb:e}},__vite__mapDeps([34,10,6,11,2,3,12,13,9,14,15,16,17,5,7,8,18,19,20,21,22]),import.meta.url);return await p(r,await e())}catch{return{userProfile:[],peerInstructions:``,sigilCard:null}}})():Promise.resolve({userProfile:[],peerInstructions:``,sigilCard:null}),g.warm?(async()=>{try{let{getBrainDb:e}=await t(async()=>{let{getBrainDb:e}=await import(`./BlapV1mo.js`);return{getBrainDb:e}},__vite__mapDeps([24,25,6,16,14,9,19,12,3,13,15,17,5,7,8,18,20,21,26,27,28]),import.meta.url);return await e(n),await m(r,a)}catch{return{peerLearnings:[],peerPatterns:[],decisions:[]}}})():Promise.resolve({peerLearnings:[],peerPatterns:[],decisions:[]}),g.hot?h(i,n):Promise.resolve({sessionNarrative:``,recentObservations:[],activeTasks:[]})]),S=`unswept-pre-T1151`,C=b.peerLearnings.filter(e=>e.provenanceClass===S),w=b.peerLearnings.filter(e=>e.provenanceClass!==S),T=b.peerPatterns.filter(e=>e.provenanceClass===S),E=b.peerPatterns.filter(e=>e.provenanceClass!==S),D=b.decisions.filter(e=>e.provenanceClass===S),O=b.decisions.filter(e=>e.provenanceClass!==S),k=x.recentObservations.filter(e=>e.provenanceClass===S),A=x.recentObservations.filter(e=>e.provenanceClass!==S),j=C.length+T.length+D.length+k.length;j>0&&console.warn(`[buildRetrievalBundle] M6 refusal gate: refused ${j} entries with provenanceClass='unswept-pre-T1151'. Run T1147 W7 sweep (.132) to promote entries to 'swept-clean'. Bundle may be empty until sweep completes.`);let M={peerLearnings:w,peerPatterns:E,decisions:O},N=A,P=0;for(let e of y.userProfile)P+=f(`${e.traitKey}:${e.traitValue}`);P+=f(y.peerInstructions);let F=0;for(let e of M.peerLearnings)F+=f(e.insight);for(let e of M.peerPatterns)F+=f(e.pattern);for(let e of M.decisions)F+=f(e.decision);let I=f(x.sessionNarrative);for(let e of N)I+=f(e.narrative||e.title);for(let e of x.activeTasks)I+=f(`${e.id} ${e.title}`);let L=N,R=x.activeTasks;if(P+F+I>s){let e=s-P-F,t=Math.max(0,Math.min(v,e)),n=f(x.sessionNarrative);L=[];for(let e of N){let r=f(e.narrative||e.title);n+r<=t&&(L.push(e),n+=r)}R=[];for(let e of x.activeTasks){let r=f(`${e.id} ${e.title}`);n+r<=t&&(R.push(e),n+=r)}I=n}let z=y.userProfile;if(P>_){let e=f(y.peerInstructions);z=[];for(let t of y.userProfile){let n=f(`${t.traitKey}:${t.traitValue}`);e+n<=_&&(z.push(t),e+=n)}P=e}let B=P+F+I;return{cold:{userProfile:z,peerInstructions:y.peerInstructions,sigilCard:y.sigilCard??null},warm:{peerLearnings:M.peerLearnings,peerPatterns:M.peerPatterns,decisions:M.decisions},hot:{sessionNarrative:x.sessionNarrative,recentObservations:L,activeTasks:R},tokenCounts:{cold:P,warm:F,hot:I,total:B}}}e();async function _(e){try{let{resolveCurrentSessionId:n}=await t(async()=>{let{resolveCurrentSessionId:e}=await import(`./QQHxtsJv2.js`);return{resolveCurrentSessionId:e}},__vite__mapDeps([35,36,6,2,3,37,16,11,12,13,9,14,5,7,8,15,17,18,38,19,20,21,39,27,40,41,42,43,44,25,26,28,10,22,45,46,47,48,49,50]),import.meta.url);return await n(e)??void 0}catch{return}}e();async function v(e,n){if(n.length===0)return;let{getBrainDb:r,getBrainNativeDb:i}=await t(async()=>{let{getBrainDb:e,getBrainNativeDb:t}=await import(`./BlapV1mo.js`);return{getBrainDb:e,getBrainNativeDb:t}},__vite__mapDeps([24,25,6,16,14,9,19,12,3,13,15,17,5,7,8,18,20,21,26,27,28]),import.meta.url);await r(e);let a=i();if(!a)return;let o=new Date().toISOString().replace(`T`,` `).slice(0,19);for(let e of n){let t;t=e.startsWith(`D-`)||/^D\d/.test(e)?`brain_decisions`:e.startsWith(`P-`)||/^P\d/.test(e)?`brain_patterns`:e.startsWith(`L-`)||/^L\d/.test(e)?`brain_learnings`:`brain_observations`;try{a.prepare(`UPDATE ${t} SET citation_count = citation_count + 1, updated_at = ? WHERE id = ?`).run(o,e)}catch{}}}e();async function y(e,n,r,i,a,o){if(r.length===0)return;let{getBrainDb:s,getBrainNativeDb:c}=await t(async()=>{let{getBrainDb:e,getBrainNativeDb:t}=await import(`./BlapV1mo.js`);return{getBrainDb:e,getBrainNativeDb:t}},__vite__mapDeps([24,25,6,16,14,9,19,12,3,13,15,17,5,7,8,18,20,21,26,27,28]),import.meta.url);await s(e);let l=c();if(l){try{l.prepare(`CREATE TABLE IF NOT EXISTS brain_retrieval_log (id INTEGER PRIMARY KEY AUTOINCREMENT,query TEXT NOT NULL,entry_ids TEXT NOT NULL,entry_count INTEGER NOT NULL,source TEXT NOT NULL,tokens_used INTEGER,session_id TEXT,created_at TEXT NOT NULL DEFAULT (datetime('now')))`).run()}catch{return}try{l.prepare(`INSERT INTO brain_retrieval_log (query, entry_ids, entry_count, source, tokens_used, session_id) VALUES (?, ?, ?, ?, ?, ?)`).run(n,JSON.stringify(r),r.length,i,a??null,o??null)}catch{}}}e();function b(e){return e.startsWith(`D-`)||/^D\d/.test(e)?`decision`:e.startsWith(`P-`)||/^P\d/.test(e)?`pattern`:e.startsWith(`L-`)||/^L\d/.test(e)?`learning`:e.startsWith(`O-`)||e.startsWith(`O`)||e.startsWith(`CM-`)?`observation`:null}async function x(e,n){let{anchor:a,depthBefore:o=3,depthAfter:s=3}=n,{getBrainDb:c,getBrainNativeDb:l}=await t(async()=>{let{getBrainDb:e,getBrainNativeDb:t}=await import(`./BlapV1mo.js`);return{getBrainDb:e,getBrainNativeDb:t}},__vite__mapDeps([24,25,6,16,14,9,19,12,3,13,15,17,5,7,8,18,20,21,26,27,28]),import.meta.url);await c(e);let u=l();if(!u)return{anchor:null,before:[],after:[]};let d=b(a);if(!d)return{anchor:null,before:[],after:[]};let f=await r(e),p=null,m=null;switch(d){case`decision`:{let e=await f.getDecision(a);e&&(p=e,m=e.createdAt);break}case`pattern`:{let e=await f.getPattern(a);e&&(p=e,m=e.extractedAt);break}case`learning`:{let e=await f.getLearning(a);e&&(p=e,m=e.createdAt);break}case`observation`:{let e=await f.getObservation(a);e&&(p=e,m=e.createdAt);break}}if(!p||!m)return{anchor:null,before:[],after:[]};let h=i(u.prepare(`
    SELECT id, 'decision' AS type, created_at AS date FROM brain_decisions WHERE created_at < ? AND id != ?
    UNION ALL
    SELECT id, 'pattern' AS type, extracted_at AS date FROM brain_patterns WHERE extracted_at < ? AND id != ?
    UNION ALL
    SELECT id, 'learning' AS type, created_at AS date FROM brain_learnings WHERE created_at < ? AND id != ?
    UNION ALL
    SELECT id, 'observation' AS type, created_at AS date FROM brain_observations WHERE created_at < ? AND id != ?
    ORDER BY date DESC
    LIMIT ?
  `),m,a,m,a,m,a,m,a,o),g=i(u.prepare(`
    SELECT id, 'decision' AS type, created_at AS date FROM brain_decisions WHERE created_at > ? AND id != ?
    UNION ALL
    SELECT id, 'pattern' AS type, extracted_at AS date FROM brain_patterns WHERE extracted_at > ? AND id != ?
    UNION ALL
    SELECT id, 'learning' AS type, created_at AS date FROM brain_learnings WHERE created_at > ? AND id != ?
    UNION ALL
    SELECT id, 'observation' AS type, created_at AS date FROM brain_observations WHERE created_at > ? AND id != ?
    ORDER BY date ASC
    LIMIT ?
  `),m,a,m,a,m,a,m,a,s);return{anchor:{id:a,type:d,data:p},before:h.map(e=>({id:e.id,type:e.type,date:e.date})),after:g.map(e=>({id:e.id,type:e.type,date:e.date}))}}async function S(e,t){let{ids:n}=t;if(!n||n.length===0)return{results:[],notFound:[],tokensEstimated:0};let i=await r(e),a=[],o=[],s=[],c=[],l=[];for(let e of n)switch(b(e)){case`decision`:a.push(e);break;case`pattern`:o.push(e);break;case`learning`:s.push(e);break;case`observation`:c.push(e);break;default:l.push(e)}let u=[],d=[...l];for(let e of a){let t=await i.getDecision(e);t?u.push({id:e,type:`decision`,data:t}):d.push(e)}for(let e of o){let t=await i.getPattern(e);t?u.push({id:e,type:`pattern`,data:t}):d.push(e)}for(let e of s){let t=await i.getLearning(e);t?u.push({id:e,type:`learning`,data:t}):d.push(e)}for(let e of c){let t=await i.getObservation(e);t?u.push({id:e,type:`observation`,data:t}):d.push(e)}if(u.length>0){let t=u.map(e=>e.id);setImmediate(()=>{v(e,t).catch(()=>{}),_(e).then(n=>y(e,t.join(`,`),t,`fetch`,u.length*500,n)).catch(()=>{})})}return{results:u,notFound:d,tokensEstimated:u.length*500}}e();async function C(e,r){let{query:i,limit:a,tables:c,dateStart:l,dateEnd:u,agent:d,useRRF:f=!0,peerId:p,includeGlobal:m,mode:h,since:g}=r;if(!i?.trim())return{results:[],total:0,tokensEstimated:0};let b=a??10,x=d!=null;if(h===`recency`&&!x){let{getBrainDb:r,getBrainNativeDb:i}=await t(async()=>{let{getBrainDb:e,getBrainNativeDb:t}=await import(`./BlapV1mo.js`);return{getBrainDb:e,getBrainNativeDb:t}},__vite__mapDeps([24,25,6,16,14,9,19,12,3,13,15,17,5,7,8,18,20,21,26,27,28]),import.meta.url);await r(e);let a=i();if(!a)return{results:[],total:0,tokensEstimated:0};let o=c&&c.length>0?c:[`observations`,`learnings`,`patterns`,`decisions`],s=g?` AND created_at >= '${g}'`:``,d=l?` AND created_at >= '${l}'`:``,f=u?` AND created_at <= '${u}'`:``,p=b*2,m=[];for(let e of o){let t;t=e===`observations`?`SELECT id, title, created_at FROM brain_observations WHERE 1=1${s}${d}${f} ORDER BY created_at DESC LIMIT ${p}`:e===`learnings`?`SELECT id, insight AS title, created_at FROM brain_learnings WHERE 1=1${s}${d}${f} ORDER BY created_at DESC LIMIT ${p}`:e===`patterns`?`SELECT id, pattern AS title, extracted_at AS created_at FROM brain_patterns WHERE 1=1${g?` AND extracted_at >= '${g}'`:``}${l?` AND extracted_at >= '${l}'`:``}${u?` AND extracted_at <= '${u}'`:``} ORDER BY extracted_at DESC LIMIT ${p}`:`SELECT id, decision AS title, created_at FROM brain_decisions WHERE 1=1${s}${d}${f} ORDER BY created_at DESC LIMIT ${p}`;try{let n=a.prepare(t).all();for(let t of n)m.push({id:t.id,type:e.replace(/s$/,``),title:(t.title??``).slice(0,80),date:t.created_at??``,relevance:0})}catch{}}m.sort((e,t)=>t.date>e.date?1:t.date<e.date?-1:0);let h=m.slice(0,b);for(let e of h)e._next=n(e.id);return{results:h,total:h.length,tokensEstimated:h.length*50}}if(f&&!x&&h!==`lexical`||h===`hybrid`&&!x){let[t,r]=await Promise.all([o(e,i,{limit:b*3,tables:c,peerId:p,includeGlobal:m}).catch(()=>({decisions:[],patterns:[],learnings:[],observations:[]})),s(i,e,{limit:b*2})]),a=new Map;for(let e of t.decisions){let t=e;a.set(e.id,(e.createdAt??t.created_at)||``)}for(let e of t.patterns){let t=e;a.set(e.id,(e.extractedAt??t.extracted_at)||``)}for(let e of t.learnings){let t=e;a.set(e.id,(e.createdAt??t.created_at)||``)}for(let e of t.observations){let t=e;a.set(e.id,(e.createdAt??t.created_at)||``)}let d={decision:`decisions`,pattern:`patterns`,learning:`learnings`,observation:`observations`},f=r.map(e=>e.ftsRank??void 0).filter(e=>e!==void 0),h=f.length>0?Math.max(...f):0,x=r.map(e=>e.score),S=x.length>0?Math.min(...x):0,C=(x.length>0?Math.max(...x):0)-S,w=r.map(e=>{let t=e.ftsRank===void 0?0:1-(h>0?e.ftsRank/h:0),n=e.score,r=C>0?(e.score-S)/C:e.score;return{id:e.id,type:e.type,title:e.title.slice(0,80),date:a.get(e.id)??``,relevance:r,rrfScore:n,bm25Score:t}}).filter(e=>a.has(e.id));c&&c.length>0&&(w=w.filter(e=>c.includes(d[e.type]))),g&&(w=w.filter(e=>!e.date||e.date>=g)),l&&(w=w.filter(e=>!e.date||e.date>=l)),u&&(w=w.filter(e=>!e.date||e.date<=u)),w=w.slice(0,b);for(let e of w)e._next=n(e.id);if(w.length>0){let t=w.map(e=>e.id);setImmediate(()=>{v(e,t).catch(()=>{}),_(e).then(n=>y(e,i,t,`find-rrf`,w.length*50,n)).catch(()=>{})})}return{results:w,total:w.length,tokensEstimated:w.length*50}}let S=await o(e,i,{limit:b,tables:x?[`observations`]:c,peerId:p,includeGlobal:m}),C=[];if(!x){for(let e of S.decisions){let t=e;C.push({id:e.id,type:`decision`,title:e.decision.slice(0,80),date:(e.createdAt??t.created_at)||``})}for(let e of S.patterns){let t=e;C.push({id:e.id,type:`pattern`,title:e.pattern.slice(0,80),date:(e.extractedAt??t.extracted_at)||``})}for(let e of S.learnings){let t=e;C.push({id:e.id,type:`learning`,title:e.insight.slice(0,80),date:(e.createdAt??t.created_at)||``})}}for(let e of S.observations){let t=e;x&&(e.agent??t.agent??null)!==d||C.push({id:e.id,type:`observation`,title:e.title.slice(0,80),date:(e.createdAt??t.created_at)||``})}g&&(C=C.filter(e=>e.date>=g)),l&&(C=C.filter(e=>e.date>=l)),u&&(C=C.filter(e=>e.date<=u));for(let e of C)e._next=n(e.id);if(C.length>0){let t=C.map(e=>e.id);setImmediate(()=>{v(e,t).catch(()=>{}),_(e).then(n=>y(e,i,t,`find`,C.length*50,n)).catch(()=>{})})}return{results:C,total:C.length,tokensEstimated:C.length*50}}var w=500;async function T(e,t,n=w,r){if(!t?.trim())return{entries:[],tokensUsed:0,tokensRemaining:n,excluded:0};let[i,s,c]=await Promise.all([o(e,t,{limit:30}).catch(()=>({decisions:[],patterns:[],learnings:[],observations:[]})),a(t,e,20).catch(()=>[]),Promise.resolve([])]),l=new Map,u=.5;for(let e of i.decisions){let t=e,n=e.id,r=(e.memoryTier??t.memory_tier)||void 0,i=(e.memoryType??t.memory_type)||void 0,a=(e.updatedAt??t.updated_at)||void 0;l.set(n,{id:n,type:`decision`,title:e.decision.slice(0,120),text:`${e.decision} — ${e.rationale}`,ftsScore:u,vecScore:0,graphScore:0,qualityScore:e.qualityScore??.5,memoryTier:r,memoryType:i,updatedAt:a})}for(let e of i.patterns){let t=e,n=e.id,r=(e.memoryTier??t.memory_tier)||void 0,i=(e.memoryType??t.memory_type)||void 0,a=(e.updatedAt??t.updated_at)||void 0;l.set(n,{id:n,type:`pattern`,title:e.pattern.slice(0,120),text:`${e.pattern} — ${e.context}`,ftsScore:u,vecScore:0,graphScore:0,qualityScore:e.qualityScore??.5,memoryTier:r,memoryType:i,updatedAt:a})}for(let e of i.learnings){let t=e,n=e.id,r=(e.memoryTier??t.memory_tier)||void 0,i=(e.memoryType??t.memory_type)||void 0,a=(e.updatedAt??t.updated_at)||void 0;l.set(n,{id:n,type:`learning`,title:e.insight.slice(0,120),text:`${e.insight} (source: ${e.source})`,ftsScore:u,vecScore:0,graphScore:0,qualityScore:e.qualityScore??.5,memoryTier:r,memoryType:i,updatedAt:a})}for(let e of i.observations){let t=e,n=e.id,r=(e.memoryTier??t.memory_tier)||void 0,i=(e.memoryType??t.memory_type)||void 0,a=(e.updatedAt??t.updated_at)||void 0;l.set(n,{id:n,type:`observation`,title:e.title.slice(0,120),text:e.narrative??e.title,ftsScore:u,vecScore:0,graphScore:0,qualityScore:e.qualityScore??.5,memoryTier:r,memoryType:i,updatedAt:a})}for(let e of s){let t=Math.max(0,1-e.distance),n=l.get(e.id);n?n.vecScore=t:l.set(e.id,{id:e.id,type:e.type,title:e.title.slice(0,120),text:e.text,ftsScore:0,vecScore:t,graphScore:0,qualityScore:.5,memoryTier:void 0,memoryType:void 0})}for(let e of c){let t=l.get(e.id);t&&(t.graphScore=e.graphScore)}let d=new Date(Date.now()-10080*60*1e3).toISOString().replace(`T`,` `).slice(0,19),f=Array.from(l.values()).map(e=>{let t=e.ftsScore*.5+e.vecScore*.4+e.graphScore*.1;return t*=e.qualityScore,e.updatedAt&&e.updatedAt>=d&&(t+=.05),(e.memoryType===`procedural`||e.type===`pattern`)&&(t+=.1),{...e,score:t}});if(r?.types&&r.types.length>0){let e=new Set(r.types);f=f.filter(t=>t.memoryType?e.has(t.memoryType):!0)}if(r?.tiers&&r.tiers.length>0){let e=new Set(r.tiers);f=f.filter(t=>t.memoryTier?e.has(t.memoryTier):!0)}f.sort((e,t)=>{let n=+(e.memoryType===`procedural`||e.type===`pattern`),r=+(t.memoryType===`procedural`||t.type===`pattern`);return n===r?t.score-e.score:r-n});let p=f.slice(0,50),m=e=>e.memoryType===`procedural`||e.type===`pattern`?0:e.memoryType===`semantic`||e.type===`decision`||e.type===`learning`?1:2,h=[...p].sort((e,t)=>{let n=m(e)-m(t);return n===0?t.score-e.score:n}),g=[],_=0,y=0;for(let e of h){let t=Math.ceil(e.text.length/4);if(_+t>n){y++;continue}g.push({id:e.id,type:e.type,title:e.title,text:e.text,score:e.score,tokensEstimated:t,memoryTier:e.memoryTier,memoryType:e.memoryType}),_+=t}if(g.length>0){let t=g.map(e=>e.id);setImmediate(()=>{v(e,t).catch(()=>{})})}return{entries:g,tokensUsed:_,tokensRemaining:n-_,excluded:y}}export{x as a,m as c,b as i,h as l,C as n,g as o,S as r,p as s,T as t};