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","./yX3I--Np.js","./DiIbXgam.js","./DTkg6Mnx.js","./BMGkukPk.js","./DoOTPDI-.js","./DO4myGf_.js","./ByMOJ7vP.js","./BlapV1mo.js","./bG-fsHMS.js","./DeO5NWhN.js","./DgZn9uJn.js","./CbGRcr-D.js","./CudpqN6Z.js","./Czb-RtcG.js","./C0nwgWmB.js","./D-eE9s2f.js","./CWxOfblT.js","./DlZwu-Y7.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{a}from"./bG-fsHMS.js";import{t as o}from"./Dg_1c8FK2.js";import{t as s}from"./BnD013za.js";import{t as c}from"./L5YNUO99.js";import{n as l}from"./Cz47RMnI.js";var u=e(r(),1);t();var d=i(`observer-reflector`),f=`consolidation`,p=1024,m=10,h=30,g=`observer-compressed`,_=`reflector-synthesized`;async function v(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),r=(await t(e)).brain?.observer;return{enabled:r?.enabled!==!1,threshold:typeof r?.threshold==`number`?r.threshold:m}}catch{return{enabled:!0,threshold:m}}}async function y(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?.reflector?.enabled!==!1}}catch{return{enabled:!0}}}async function b(e,t,n){let r={}.CLEO_OBSERVER_MODEL,i=r!==void 0&&r.length>0?r:void 0;return(await c(f,t,n,{projectRoot:e,maxTokens:p,...i===void 0?{}:{modelOverride:i}}))?.content??null}function x(e){try{let t=e.replace(/^```(?:json)?\s*/m,``).replace(/\s*```\s*$/m,``).trim();return JSON.parse(t)}catch{return null}}function S(e,t){let n=a();if(!n)return[];try{if(e){let r=n.prepare(`
          SELECT id, type, title, narrative, created_at, source_session_id
          FROM brain_observations
          WHERE source_session_id = ?
            AND (source_type IS NULL OR source_type != ?)
            AND invalid_at IS NULL
          ORDER BY created_at DESC
          LIMIT ?
        `).all(e,g,t);if(r.length>=2)return r}let r=new Date(Date.now()-1440*60*1e3).toISOString().replace(`T`,` `).slice(0,19);return n.prepare(`
        SELECT id, type, title, narrative, created_at, source_session_id
        FROM brain_observations
        WHERE created_at >= ?
          AND (source_type IS NULL OR source_type != ?)
          AND invalid_at IS NULL
        ORDER BY created_at DESC
        LIMIT ?
      `).all(r,g,t)}catch{return[]}}function C(e){let t=a();if(!t)return 0;try{if(e){let n=t.prepare(`
          SELECT COUNT(*) as cnt
          FROM brain_observations
          WHERE source_session_id = ?
            AND (source_type IS NULL OR source_type != ?)
            AND invalid_at IS NULL
        `).get(e,g);if(n&&n.cnt>0)return n.cnt}let n=new Date(Date.now()-1440*60*1e3).toISOString().replace(`T`,` `).slice(0,19);return t.prepare(`
        SELECT COUNT(*) as cnt
        FROM brain_observations
        WHERE created_at >= ?
          AND (source_type IS NULL OR source_type != ?)
          AND invalid_at IS NULL
      `).get(n,g)?.cnt??0}catch{return 0}}function w(e,t,n){let r=a();if(!r)return null;try{let i=`O-${(0,u.randomBytes)(4).toString(`hex`)}`,a=new Date().toISOString().replace(`T`,` `).slice(0,19),s=`[Observer p${t.priority}] ${t.observation.slice(0,80)}`,c=`${t.observation} (compressed from: ${t.source_ids.join(`, `)})`;r.prepare(`
        INSERT INTO brain_observations
          (id, type, title, narrative, source_type, source_session_id, quality_score,
           memory_tier, created_at)
        VALUES (?, 'change', ?, ?, ?, ?, ?, 'short', ?)
      `).run(i,s,c,g,n??null,Math.max(.6,1-(t.priority-1)*.1),a);for(let n of t.source_ids)o(e,`observation:${i}`,`observation:${n}`,`supersedes`,.9,`observer-reflector`).catch(()=>void 0);return i}catch(e){let t=e instanceof Error?e.message:String(e);return d.warn(`Failed to store observer note: ${t}`),null}}function T(e){if(e.length===0)return;let t=a();if(!t)return;let n=new Date().toISOString().replace(`T`,` `).slice(0,19);try{for(let r=0;r<e.length;r+=100){let i=e.slice(r,r+100),a=i.map(()=>`?`).join(`,`);t.prepare(`UPDATE brain_observations
           SET invalid_at = ?, updated_at = ?
           WHERE id IN (${a}) AND invalid_at IS NULL`).run(n,n,...i)}}catch{}}var E=`You are compressing AI coding session activity into dense observation notes.
Input: recent observations and tool outputs from a CLEO agent coding session.
Output: 3-5 dated, prioritized observation notes (each ≤300 chars).
Focus on: state changes, decisions, errors, completed work.
Drop: verbose tool output, repetition, transient state.
Format: JSON array of objects with keys:
  - date: ISO date string (YYYY-MM-DD)
  - priority: integer 1-5 (1=architectural decision, 2=implementation choice, 3=constraint/bug, 4=routine action, 5=noise)
  - observation: string ≤300 chars — capture DECISION+RATIONALE not the discussion
  - source_ids: array of original observation IDs that this note compresses

Rules:
- For tool calls: capture the outcome, not the invocation
- For file reads: capture what was LEARNED, not what was read
- For errors: capture the ROOT CAUSE, not the stack trace
- Prefer priority 1-2 items; include priority 4-5 only if significant count
- ONLY return valid JSON array, no markdown fences or extra text`;async function D(e,t,r){let i={ran:!1,stored:0,compressedIds:[],notes:[]},{resolveCredentials:a}=await n(async()=>{let{resolveCredentials:e}=await import(`./yX3I--Np.js`);return{resolveCredentials:e}},__vite__mapDeps([14,15,2,13,7,16,4,5,6,1,3,8,9,10,11,12,17,18,19,20]),import.meta.url);if(!a(`anthropic`).apiKey)return i;let o=await v(e);if(!o.enabled)return i;try{let{getBrainDb:t}=await n(async()=>{let{getBrainDb:e}=await import(`./BlapV1mo.js`);return{getBrainDb:e}},__vite__mapDeps([21,22,2,12,16,7,23,24,25,26,11,13,4,5,6,8,27,28,29,30,31]),import.meta.url);await t(e)}catch{return i}let s=r?.thresholdOverride??o.threshold;if(C(t)<s)return i;let c=S(t,h);if(c.length<2)return i;let l=c.map(e=>`[${e.id}] ${e.created_at??`unknown`}: ${e.title??``} — ${(e.narrative??``).slice(0,200)}`).join(`
`),u=await b(e,E,`Recent observations to compress (${c.length} entries):\n\n${l}`);if(!u)return i;let f=x(u);if(!f||!Array.isArray(f)||f.length===0)return d.warn(`Observer: failed to parse LLM response as ObserverNote[]`),i;let p=0,m=[];for(let n of f)typeof n.observation!=`string`||!n.observation||!Array.isArray(n.source_ids)||w(e,n,t)!==null&&(p++,m.push(...n.source_ids));return{ran:!0,stored:p,compressedIds:[...new Set(m)],notes:f}}var O=`You are restructuring accumulated observations from a coding agent session into durable knowledge.
Input: observation notes from the session (both raw and observer-compressed).
Output: extracted patterns + learnings.

Rules:
- Combine related observations into single insights
- Identify cross-cutting patterns (3+ similar events)
- Drop observations superseded by later ones (list their IDs in "superseded")
- Preserve ALL architectural decisions and their rationale
- Preserve ALL discovered constraints and bugs with root causes
- Add cross-cutting insights that emerge from the full picture

Format: JSON object with keys:
  - patterns: array of { pattern: string (≤300 chars), context: string (≤150 chars) }
  - learnings: array of { insight: string (≤300 chars), confidence: number 0.0-1.0 }
  - superseded: array of observation IDs (strings) that are now redundant

ONLY return valid JSON, no markdown fences or extra text.
Maximum 5 patterns, 5 learnings. Quality over quantity.`;async function k(e,t){let r={ran:!1,patternsStored:0,learningsStored:0,supersededIds:[]},{resolveCredentials:i}=await n(async()=>{let{resolveCredentials:e}=await import(`./yX3I--Np.js`);return{resolveCredentials:e}},__vite__mapDeps([14,15,2,13,7,16,4,5,6,1,3,8,9,10,11,12,17,18,19,20]),import.meta.url);if(!i(`anthropic`).apiKey||!(await y(e)).enabled)return r;try{let{getBrainDb:t}=await n(async()=>{let{getBrainDb:e}=await import(`./BlapV1mo.js`);return{getBrainDb:e}},__vite__mapDeps([21,22,2,12,16,7,23,24,25,26,11,13,4,5,6,8,27,28,29,30,31]),import.meta.url);await t(e)}catch{return r}let c=a();if(!c)return r;let u=[];try{let e=new Date(Date.now()-2880*60*1e3).toISOString().replace(`T`,` `).slice(0,19);t&&(u=c.prepare(`
          SELECT id, type, title, narrative, created_at, source_type
          FROM brain_observations
          WHERE source_session_id = ?
            AND invalid_at IS NULL
          ORDER BY created_at DESC
          LIMIT 50
        `).all(t)),u.length<3&&(u=c.prepare(`
          SELECT id, type, title, narrative, created_at, source_type
          FROM brain_observations
          WHERE created_at >= ?
            AND invalid_at IS NULL
          ORDER BY created_at DESC
          LIMIT 50
        `).all(e))}catch{return r}if(u.length<3)return r;let f=u.map(e=>`[${e.id}] (${e.source_type??`raw`}): ${e.title??``} — ${(e.narrative??``).slice(0,200)}`).join(`
`),p=await b(e,O,`Session observations to synthesize (${u.length} entries):\n\n${f}`);if(!p)return r;let m=x(p);if(!m||typeof m!=`object`)return d.warn(`Reflector: failed to parse LLM response`),r;let h=0,g=0,v=[];if(Array.isArray(m.patterns)){for(let t of m.patterns)if(!(typeof t.pattern!=`string`||!t.pattern))try{let n=await l(e,{type:`workflow`,pattern:t.pattern.slice(0,500),context:(t.context??``).slice(0,200),source:_});v.push(`pattern:${n.id}`),h++}catch{}}if(Array.isArray(m.learnings))for(let t of m.learnings){if(typeof t.insight!=`string`||!t.insight)continue;let n=typeof t.confidence==`number`?Math.max(.1,Math.min(1,t.confidence)):.7;try{let r=await s(e,{insight:t.insight.slice(0,500),source:_,confidence:n,actionable:n>=.7});v.push(`learning:${r.id}`),g++}catch{}}let S=Array.isArray(m.superseded)?m.superseded.filter(e=>typeof e==`string`):[];if(T(S),v.length>0&&S.length>0)for(let t of v)for(let n of S)o(e,t,`observation:${n}`,`supersedes`,1,`reflector-synthesized:session-end-reflection`).catch(()=>{});return{ran:!0,patternsStored:h,learningsStored:g,supersededIds:S}}export{k as n,D as t};