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","./BiCEaioG2.js","./CG84LPq-.js","./2PQNgpBd.js","./DsanjglN.js","./BmWTAsFW.js","./B5XQZRTz.js","./CVwAhlPZ.js","./BVC3q6GM.js","./B8PRMiR2.js","./BDDiPmhF.js","./BYJC6_MM.js","./Cx_-1PHK2.js","./B_DA9RKE2.js","./DOPTvi6T.js","./CvaH7m0y.js","./O2P-f9sv.js","./BQ9wXJVQ2.js","./OnYyYdSr2.js","./BzYt7rkb.js","./BYXFvmSx.js"])))=>i.map(i=>d[i]);
import{n as e,t}from"./DsQIgu-4.js";import{t as n}from"./CvFbqtf9.js";function r(e,t){let n=e??`static`;return n===`stdp`||t===`stdp`?`stdp`:t===`hebbian`&&n===`static`?`hebbian`:n}function i(e,t,n=Date.now()){if(!e||e<=0||!t)return null;let r=Math.tanh(e/10),i=(n-new Date(t).getTime())/(1440*60*1e3),a=r*Math.exp(-i/30);return Math.max(0,Math.min(1,a))}e();var a=30,o=1440*60*1e3,s=5e4,c=5e4,l=1e4,u=2e4,d=1800*1e3,f=720*60*1e3,p=3e4,m=7200*1e3,h=.05,g=.06,_=1.5,v=0,y=1;function b(e){return e<=p?u:e<=m?d:f}function x(e,t,n,r,i,a=1){try{let o=new Date(Date.now()-a*60*60*1e3).toISOString().replace(`T`,` `).slice(0,19);return e.prepare(`SELECT 1 FROM brain_plasticity_events
       WHERE source_node = ? AND target_node = ? AND kind = ?
         AND session_id = ?
         AND timestamp > ?
       LIMIT 1`).get(t,n,r,i,o)!==void 0}catch{return!1}}function S(e,t=2,n=null){try{let r=e,i=n===null?r.prepare(`SELECT MAX(timestamp) as last_time FROM brain_plasticity_events`).get()?.last_time??null:r.prepare(`SELECT MAX(timestamp) as last_time FROM brain_plasticity_events
             WHERE session_id = ?`).get(n)?.last_time??null,a;return a=i===null?n===null?r.prepare(`SELECT COUNT(*) as cnt FROM brain_retrieval_log`).get()?.cnt??0:r.prepare(`SELECT COUNT(*) as cnt FROM brain_retrieval_log
             WHERE session_id = ?`).get(n)?.cnt??0:n===null?r.prepare(`SELECT COUNT(*) as cnt FROM brain_retrieval_log
             WHERE created_at > ?`).get(i)?.cnt??0:r.prepare(`SELECT COUNT(*) as cnt FROM brain_retrieval_log
             WHERE session_id = ? AND created_at > ?`).get(n,i)?.cnt??0,a>=t}catch{return!0}}async function C(e,n=null,r=2){let{getBrainDb:i,getBrainNativeDb:a}=await t(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 o=a();if(!o)return!0;let s=S(o,r,n);if(!s){let e=(()=>{try{let e=o,t=n===null?e.prepare(`SELECT MAX(timestamp) as last_time FROM brain_plasticity_events`).get()?.last_time??null:e.prepare(`SELECT MAX(timestamp) as last_time FROM brain_plasticity_events WHERE session_id = ?`).get(n)?.last_time??null;return t===null?(n===null?e.prepare(`SELECT COUNT(*) as cnt FROM brain_retrieval_log`).get():e.prepare(`SELECT COUNT(*) as cnt FROM brain_retrieval_log WHERE session_id = ?`).get(n))?.cnt??0:(n===null?e.prepare(`SELECT COUNT(*) as cnt FROM brain_retrieval_log WHERE created_at > ?`).get(t):e.prepare(`SELECT COUNT(*) as cnt FROM brain_retrieval_log WHERE session_id = ? AND created_at > ?`).get(n,t))?.cnt??0}catch{return 0}})();console.warn(`[plasticity] Minimum-pair gate: skipped STDP Step 9b (${e} retrievals, need >=${r})`)}return s}var w=null;async function T(e,t){for(;w;)try{await w}catch{}let n=E(e,t);w=n.catch(()=>void 0);try{return await n}finally{w=null}}async function E(e,s){let c=a,l=o;typeof s==`number`?(console.warn(`[brain-stdp] Deprecated: passing sessionWindowMs as a number. Use StdpPlasticityOptions { lookbackDays, pairingWindowMs } instead. (T679)`),l=s):s!==void 0&&(c=s.lookbackDays??a,l=s.pairingWindowMs??o);let{getBrainDb:u,getBrainNativeDb:d}=await t(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 u(e);let f=d(),p={ltpEvents:0,ltdEvents:0,edgesCreated:0,pairsExamined:0,rewardModulatedEvents:0};if(!f)return p;try{f.prepare(`SELECT 1 FROM brain_retrieval_log LIMIT 1`).get()}catch{return p}try{f.prepare(`SELECT 1 FROM brain_plasticity_events LIMIT 1`).get()}catch{return p}let m=Date.now(),S=m-c*24*60*60*1e3,C=new Date(S).toISOString().replace(`T`,` `).slice(0,19),w=new Date(m).toISOString().replace(`T`,` `).slice(0,19),T=[];try{T=n(f.prepare(`SELECT id, entry_ids, created_at, retrieval_order, delta_ms, session_id, reward_signal
         FROM brain_retrieval_log
         WHERE created_at >= ?
         ORDER BY created_at ASC, id ASC
         LIMIT 2000`),C)}catch{return p}if(T.length===0)return p;let E=[],D=0;for(let e of T){let t;try{t=JSON.parse(e.entry_ids)}catch{continue}if(!Array.isArray(t))continue;let n=new Date(e.created_at.replace(` `,`T`)+`Z`).getTime();for(let r of t){if(typeof r!=`string`||r.length===0)continue;let t=r.includes(`:`)?r:`observation:${r}`;E.push({entryId:t,rowId:e.id,retrievedAt:n,order:e.retrieval_order??D,sessionId:e.session_id??null,rewardSignal:e.reward_signal??null}),D++}}if(E.length<2)return p;E.sort((e,t)=>e.retrievedAt-t.retrievedAt||e.order-t.order);let O=new Map;for(let e of E){let t=e.sessionId??`null`,n=O.get(t);n===void 0?O.set(t,[e]):n.push(e)}let k=Array.from(O.entries()).sort(([,e],[,t])=>(e[0]?.retrievedAt??0)-(t[0]?.retrievedAt??0)),A=[];for(let e=0;e<k.length;e++){let[,t]=k[e];A.push(...t)}let j=new Map,M=new Map;for(let[,e]of k)for(let t=0;t<e.length;t++){let n=e[t];j.set(n,t),M.set(n.sessionId??`null`,e.length)}let N=f.prepare(`SELECT weight, reinforcement_count, last_reinforced_at, plasticity_class, depression_count, last_depressed_at
     FROM brain_page_edges
     WHERE from_id = ? AND to_id = ? AND edge_type = 'co_retrieved'`),P=f.prepare(`UPDATE brain_page_edges
     SET weight = MAX(?, MIN(?, weight + ?)),
         reinforcement_count = reinforcement_count + 1,
         last_reinforced_at = ?,
         plasticity_class = ?,
         stability_score = ?
     WHERE from_id = ? AND to_id = ? AND edge_type = 'co_retrieved'`),F=f.prepare(`UPDATE brain_page_edges
     SET weight = MAX(?, MIN(?, weight + ?)),
         depression_count = depression_count + 1,
         last_depressed_at = ?,
         plasticity_class = ?,
         stability_score = ?
     WHERE from_id = ? AND to_id = ? AND edge_type = 'co_retrieved'`),I=f.prepare(`INSERT OR IGNORE INTO brain_page_edges
       (from_id, to_id, edge_type, weight, provenance, reinforcement_count, last_reinforced_at, plasticity_class, stability_score, created_at)
     VALUES (?, ?, 'co_retrieved', ?, 'plasticity:stdp-ltp', 1, ?, 'stdp', ?, ?)`),L=f.prepare(`INSERT INTO brain_plasticity_events
       (source_node, target_node, delta_w, kind, timestamp,
        session_id, retrieval_log_id, weight_before, weight_after, delta_t_ms)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),R=null;try{f.prepare(`SELECT 1 FROM brain_weight_history LIMIT 1`).get(),R=f.prepare(`INSERT INTO brain_weight_history
         (edge_from_id, edge_to_id, edge_type, weight_before, weight_after,
          delta_weight, event_kind, source_plasticity_event_id, retrieval_log_id,
          reward_signal, changed_at)
       VALUES (?, ?, 'co_retrieved', ?, ?, ?, ?, ?, ?, ?, ?)`)}catch{}for(let e=0;e<A.length;e++){let t=A[e],n=t.sessionId??`null`,a=M.get(n)??1,o=(j.get(t)??0)>=a-50;for(let a=e+1;a<A.length;a++){let e=A[a],s=e.retrievedAt-t.retrievedAt;if(s>l)break;if(t.entryId===e.entryId||n!==(e.sessionId??`null`)&&!o)continue;p.pairsExamined++;let c=b(s),u=h*Math.exp(-s/c);if(u<1e-6)continue;let d=t.sessionId??null,S=t.rewardSignal??null,C=!1;if(S!==null&&(u=Math.min(u*(1+S),2*h),u=Math.max(u,0),C=!0),u<1e-6){C&&p.rewardModulatedEvents++;continue}let T=N.get(t.entryId,e.entryId),E=null;try{if(T!==void 0){let n=T.weight,a=Math.max(v,Math.min(y,n+u)),o=r(T.plasticity_class,`stdp`),c=i((T.reinforcement_count??0)+1,w,m);if(P.run(v,y,u,w,o,c,t.entryId,e.entryId),x(f,t.entryId,e.entryId,`ltp`,d,1)){p.ltpEvents++,C&&p.rewardModulatedEvents++;continue}let l=L.run(t.entryId,e.entryId,u,`ltp`,w,d,t.rowId,n,a,s);E=l.lastInsertRowid==null?null:Number(l.lastInsertRowid),R&&R.run(t.entryId,e.entryId,n,a,u,`ltp`,E,t.rowId,S,w)}else{let n=u*_,r=Math.min(y,Math.min(h*_,n)),a=i(1,w,m);I.run(t.entryId,e.entryId,r,w,a,w),p.edgesCreated++;let o=L.run(t.entryId,e.entryId,r,`ltp`,w,d,t.rowId,null,r,s);E=o.lastInsertRowid==null?null:Number(o.lastInsertRowid),R&&R.run(t.entryId,e.entryId,null,r,r,`ltp`,E,t.rowId,S,w)}p.ltpEvents++,C&&p.rewardModulatedEvents++}catch{}let D=-(g*Math.exp(-s/c)),O=!1;S!==null&&(D=Math.max(D*(1-S),-2*g),O=!0);let k=N.get(e.entryId,t.entryId);if(k!==void 0&&Math.abs(D)>=1e-6)try{let n=k.weight,a=Math.max(v,Math.min(y,n+D)),o=r(k.plasticity_class,`stdp`),c=i(k.reinforcement_count,k.last_reinforced_at,m);if(F.run(v,y,D,w,o,c,e.entryId,t.entryId),x(f,e.entryId,t.entryId,`ltd`,d,1)){p.ltdEvents++,O&&p.rewardModulatedEvents++;continue}let l=L.run(e.entryId,t.entryId,D,`ltd`,w,d,e.rowId,n,a,s),u=l.lastInsertRowid==null?null:Number(l.lastInsertRowid);R&&R.run(e.entryId,t.entryId,n,a,D,`ltd`,u,e.rowId,S,w),p.ltdEvents++,O&&p.rewardModulatedEvents++}catch{}}}return p}async function D(e,n,r=30){let i={rowsLabeled:0,rowsSkipped:0};if(!n||n.startsWith(`ses_backfill_`))return i;let a=[];try{let{getDb:i}=await t(async()=>{let{getDb:e}=await import(`./BiCEaioG2.js`);return{getDb:e}},__vite__mapDeps([21,22,2,3,23,24,8,7,9,5,4,12,13,14,10,11,15,25,6,16,17,26,19,27,28,29,30,31,1,18,20,32,33,34,35,36,37,38]),import.meta.url),o=await i(e),{tasks:s}=await t(async()=>{let{tasks:e}=await import(`./BzYt7rkb.js`);return{tasks:e}},__vite__mapDeps([39,12,2,13,14,5,35,7,8,19,27,34,20,36]),import.meta.url),{and:c,eq:l,inArray:u,gte:d,or:f,isNotNull:p}=await t(async()=>{let{and:e,eq:t,inArray:n,gte:r,or:i,isNotNull:a}=await import(`./BYXFvmSx.js`);return{and:e,eq:t,inArray:n,gte:r,or:i,isNotNull:a}},__vite__mapDeps([40,24,8]),import.meta.url),m=new Date(Date.now()-r*24*60*60*1e3).toISOString().replace(`T`,` `).slice(0,19);a=(await o.select({id:s.id,status:s.status,verificationJson:s.verificationJson,completedAt:s.completedAt,cancelledAt:s.cancelledAt}).from(s).where(c(l(s.sessionId,n),u(s.status,[`done`,`cancelled`]),f(c(p(s.completedAt),d(s.completedAt,m)),c(p(s.cancelledAt),d(s.cancelledAt,m))))).all()).map(e=>({id:e.id,status:e.status,verificationJson:e.verificationJson??null,completedAt:e.completedAt??null,cancelledAt:e.cancelledAt??null}))}catch{return i}if(a.length===0)return i;let o=null;function s(e){if(e.status===`cancelled`)return-.5;let t=!1;if(e.verificationJson)try{t=JSON.parse(e.verificationJson).passed===!0}catch{}return t?1:.5}for(let e of a){let t=s(e);(o===null||t>o)&&(o=t)}if(o===null)return i;try{let{getBrainDb:r,getBrainNativeDb:c}=await t(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 l=c();if(!l)return i;try{l.prepare(`SELECT 1 FROM brain_retrieval_log LIMIT 1`).get()}catch{return i}let u=l.prepare(`UPDATE brain_retrieval_log
         SET reward_signal = ?
         WHERE session_id = ?
           AND reward_signal IS NULL`).run(o,n),d=typeof u.changes==`number`?u.changes:0;i.rowsLabeled=d,i.rowsSkipped=l.prepare(`SELECT COUNT(*) AS cnt FROM brain_retrieval_log
         WHERE session_id = ? AND reward_signal IS NOT NULL`).get(n)?.cnt??0;let f=!1;try{l.prepare(`SELECT 1 FROM brain_modulators LIMIT 1`).get(),f=!0}catch{}if(f&&d>0){let e=l.prepare(`INSERT INTO brain_modulators
           (modulator_type, valence, magnitude, source_event_id, session_id, description)
         VALUES (?, ?, 1.0, ?, ?, ?)`);for(let t of a){let r=s(t),i,a;t.status===`cancelled`?(i=`task_cancelled`,a=`Task ${t.id} cancelled`):r>=1?(i=`task_verified`,a=`Task ${t.id} completed and verified`):(i=`task_completed`,a=`Task ${t.id} completed (unverified)`);try{e.run(i,r,t.id,n,a)}catch{}}}}catch{}return i}async function O(e,r){let i=r?.decayRatePerDay??.02,a=r?.gracePeriodDays??7,o=r?.pruneThreshold??.05,s={edgesDecayed:0,edgesPruned:0},{getBrainDb:c,getBrainNativeDb:l}=await t(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 c(e);let u=l();if(!u)return s;try{u.prepare(`SELECT 1 FROM brain_page_edges LIMIT 1`).get()}catch{return s}let d=new Date().toISOString().replace(`T`,` `).slice(0,19),f=!1;try{u.prepare(`SELECT 1 FROM brain_weight_history LIMIT 1`).get(),f=!0}catch{}let p=[];try{p=n(u.prepare(`SELECT from_id, to_id, edge_type, weight, plasticity_class, last_reinforced_at
         FROM brain_page_edges
         WHERE plasticity_class IN ('hebbian', 'stdp')
           AND last_reinforced_at IS NOT NULL
           AND (julianday('now') - julianday(last_reinforced_at)) > ?`),a)}catch{return s}if(p.length===0)return s;let m=u.prepare(`UPDATE brain_page_edges
     SET weight = ?
     WHERE from_id = ? AND to_id = ? AND edge_type = ?`),h=u.prepare(`DELETE FROM brain_page_edges
     WHERE from_id = ? AND to_id = ? AND edge_type = ?`),g=null;if(f)try{g=u.prepare(`INSERT INTO brain_weight_history
           (edge_from_id, edge_to_id, edge_type, weight_before, weight_after,
            delta_weight, event_kind, changed_at)
         VALUES (?, ?, ?, ?, 0.0, ?, 'prune', ?)`)}catch{}let _=Date.now();for(let e of p)try{let t=(_-new Date(e.last_reinforced_at.replace(` `,`T`)+`Z`).getTime())/(1440*60*1e3),n=Math.max(0,t-a),r=e.weight*(1-i)**n;if(r<o){if(h.run(e.from_id,e.to_id,e.edge_type),s.edgesPruned++,g){let t=-e.weight;try{g.run(e.from_id,e.to_id,e.edge_type,e.weight,t,d)}catch{}}}else m.run(r,e.from_id,e.to_id,e.edge_type),s.edgesDecayed++}catch{}return s}async function k(e,n){let r={plasticityEventsDeleted:0,weightHistoryDeleted:0,skipped:!1},i;if(n?.retentionDays!==void 0)i=n.retentionDays;else{let e={}.CLEO_BRAIN_HISTORY_RETENTION_DAYS;if(e!==void 0&&e!==``){let t=Number.parseInt(e,10);i=Number.isFinite(t)&&t>=0?t:30}else i=30}if(i===0)return r.skipped=!0,r;let a=n?.plasticityEventsRowCap??5e4,o=n?.weightHistoryRowCap??5e4,{getBrainDb:s,getBrainNativeDb:c}=await t(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 l=c();if(!l)return r;let u=Date.now()-i*24*60*60*1e3,d=new Date(u).toISOString().replace(`T`,` `).slice(0,19);try{l.prepare(`SELECT 1 FROM brain_plasticity_events LIMIT 1`).get();let e=l.prepare(`DELETE FROM brain_plasticity_events WHERE timestamp < ?`).run(d).changes;r.plasticityEventsDeleted+=Number(e??0)}catch{}try{l.prepare(`SELECT 1 FROM brain_weight_history LIMIT 1`).get();let e=l.prepare(`DELETE FROM brain_weight_history WHERE changed_at < ?`).run(d).changes;r.weightHistoryDeleted+=Number(e??0)}catch{}try{let e=l.prepare(`SELECT COUNT(*) AS cnt FROM brain_plasticity_events`).get(),t=Number(e?.cnt??0);if(t>a){let e=t-a,n=l.prepare(`DELETE FROM brain_plasticity_events
         WHERE id IN (
           SELECT id FROM brain_plasticity_events
           ORDER BY timestamp ASC, id ASC
           LIMIT ?
         )`).run(e);r.plasticityEventsDeleted+=Number(n.changes??0)}}catch{}try{let e=l.prepare(`SELECT COUNT(*) AS cnt FROM brain_weight_history`).get(),t=Number(e?.cnt??0);if(t>o){let e=t-o,n=l.prepare(`DELETE FROM brain_weight_history
         WHERE id IN (
           SELECT id FROM brain_weight_history
           ORDER BY changed_at ASC, id ASC
           LIMIT ?
         )`).run(e);r.weightHistoryDeleted+=Number(n.changes??0)}}catch{}return r.plasticityEventsDeleted+r.weightHistoryDeleted>=1e4&&console.info(`[pruneStaleHistory] Pruned ${r.plasticityEventsDeleted} plasticity_events + ${r.weightHistoryDeleted} weight_history rows (retention=${i}d). Consider running 'cleo doctor --vacuum' to reclaim disk space.`),r}export{T as a,k as c,O as i,C as l,c as n,D as o,l as r,b as s,s as t};