import{execFileSync as Z}from"child_process";import{existsSync as Y,mkdirSync as P}from"fs";import{join as _,basename as ue}from"path";import{randomBytes as de}from"crypto";import{pathToFileURL as M}from"url";import{createRequire as z}from"module";var F=".zibby/memory",X="dolt",G={encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:15e3},U="mem0",L=new Map,b=new Map,w=!1,ye=z(import.meta.url),I=()=>de(8).toString("hex"),E=()=>new Date().toISOString(),pe=[`CREATE TABLE IF NOT EXISTS chat_memory (
    id            VARCHAR(64)  PRIMARY KEY,
    memory_key    VARCHAR(160),
    category      VARCHAR(32)  NOT NULL,
    content       TEXT         NOT NULL,
    source        VARCHAR(64),
    ticket_key    VARCHAR(32),
    session_id    VARCHAR(64),
    tier          VARCHAR(16)  DEFAULT 'mid',
    relevance     FLOAT        DEFAULT 1.0,
    created_at    VARCHAR(32)  NOT NULL
  )`,`CREATE TABLE IF NOT EXISTS chat_tasks (
    id            VARCHAR(64)  PRIMARY KEY,
    ticket_key    VARCHAR(32),
    type          VARCHAR(32)  NOT NULL,
    title         VARCHAR(512) NOT NULL,
    status        VARCHAR(32)  NOT NULL DEFAULT 'pending',
    spec_path     VARCHAR(512),
    session_id    VARCHAR(64),
    result_summary TEXT,
    created_at    VARCHAR(32)  NOT NULL,
    finished_at   VARCHAR(32)
  )`,`CREATE TABLE IF NOT EXISTS chat_sessions (
    session_id    VARCHAR(64)  PRIMARY KEY,
    summary       TEXT         NOT NULL,
    tickets       TEXT,
    tasks_run     INT          DEFAULT 0,
    tasks_passed  INT          DEFAULT 0,
    tasks_failed  INT          DEFAULT 0,
    key_facts     TEXT,
    created_at    VARCHAR(32)  NOT NULL
  )`],H=new Set;function f(t,e){return Z(X,e,{...G,cwd:t})}function h(t,e){try{let r=f(t,["sql","-q",e,"-r","json"]);return JSON.parse(r.trim()).rows||[]}catch{return[]}}function g(t,e){f(t,["sql","-q",e])}function N(t){if(H.has(t))return!0;if(!Y(_(t,".dolt"))){if(!fe())return!1;P(t,{recursive:!0}),f(t,["init","--name","Zibby Chat Memory","--email","chat@zibby.app"])}let e=`${pe.join(`;
`)};`;g(t,e);try{g(t,"ALTER TABLE chat_memory ADD COLUMN tier VARCHAR(16) DEFAULT 'mid'")}catch{}try{g(t,"ALTER TABLE chat_memory ADD COLUMN memory_key VARCHAR(160)")}catch{}return H.add(t),!0}function Oe(){H.clear()}function De(t){return J(t)}function Le(t){return te(t)}function Be(t,e){return x(t,e)}function Fe(t,e){return ne(t,e)}function fe(){try{return Z(X,["version"],{...G,timeout:5e3}),!0}catch{return!1}}function c(t){return t==null?"NULL":`'${String(t).replace(/'/g,"''")}'`}function K(t){return String(t||"").toLowerCase().replace(/[“”]/g,'"').replace(/[‘’]/g,"'").replace(/[\s_-]+/g," ").replace(/[^\w\s"']/g,"").replace(/\s+/g," ").trim()}function A(t){return t==="long"?3:t==="mid"?2:t==="short"?1:0}function q(t,e){let r=["short","mid","long"].includes(t)?t:"mid";return new Set(["fact","decision","preference","credential","url","workaround"]).has(String(e||"").toLowerCase())&&r==="short"?"mid":r}function Q(t){let e=new Map;for(let r of t||[]){let s=K(r.content),n=r.memory_key?`key:${r.memory_key}`:s?`norm:${s}`:"";if(!n)continue;let i=e.get(n);if(!i){e.set(n,r);continue}let o=A(i.tier),m=A(r.tier);if(m>o){e.set(n,r);continue}m===o&&Number(r.relevance||0)>Number(i.relevance||0)&&e.set(n,r)}return[...e.values()]}function C(t,e){let r=String(t??"");return r.length<=e?r:e<=1?r.slice(0,e):`${r.slice(0,e-1)}\u2026`}function v(t,e){let r={recentSessions:Array.isArray(t?.recentSessions)?t.recentSessions:[],topMemories:Array.isArray(t?.topMemories)?t.topMemories:[],taskStats:Array.isArray(t?.taskStats)?t.taskStats:[],ticketFilter:t?.ticketFilter||null,backend:e||String(t?.backend||U),error:t?.error||null};return r.backend==="mem0"?{...r,recentSessions:[],taskStats:[]}:r}function W(t){let e=[];if(t.recentSessions?.length>0){e.push("Recent sessions:");for(let r of t.recentSessions.slice(0,3))r?.summary?.trim()&&e.push(`- ${C(r.summary,150)}${r.tickets?` [${r.tickets}]`:""}`)}if(t.topMemories?.length>0){e.push("Known facts:");for(let r of t.topMemories.slice(0,10)){let s=r.tier==="long"?"\u2605":"\xB7";e.push(`${s} [${r.category}] ${C(r.content,120)}`)}}return e.length===0?"":`## Memory Context
${e.join(`
`)}`}function $(t){return{backend:t.backend,recentSessions:t.recentSessions.slice(0,3).map(e=>({summary:C(String(e?.summary||""),160),tickets:e?.tickets||null,created_at:e?.created_at||null})),topMemories:t.topMemories.slice(0,8).map(e=>({category:e?.category||null,tier:e?.tier||null,content:C(String(e?.content||""),140),source:e?.source||null})),taskStats:t.taskStats,error:t.error||null}}async function ge(t,e){let r=String(process.env.ZIBBY_MEMORY_BACKEND||"").trim().toLowerCase();if(r==="mem0"||r==="dolt")return r;let s=String(e?.options?.memoryBackend||e?.options?.config?.memory?.backend||"").trim().toLowerCase();if(s==="mem0"||s==="dolt")return s;if(b.has(t))return b.get(t);try{let n=_(t,".zibby.config.mjs");if(Y(n)){let i=await import(M(n).href),o=String(i?.default?.memory?.backend||"").trim().toLowerCase();if(o==="mem0"||o==="dolt")return b.set(t,o),o}}catch{}return b.set(t,U),U}function ee(t){let e=String(process.env.ZIBBY_MEMORY_USER_ID||"").trim();return e||`workspace:${ue(t||process.cwd())}`}var _e="mem0";function J(t){let e=_(t,F,_e);return{dir:e,vectorDbPath:_(e,"vectors.db"),historyDbPath:_(e,"history.db")}}function te(t){let e=String(process.env.ZIBBY_MEM0_OPENAI_BASE_URL||"").trim();if(!e)return null;let r=String(process.env.ZIBBY_MEM0_API_KEY||process.env.ZIBBY_USER_TOKEN||process.env.OPENAI_API_KEY||"").trim(),s=String(process.env.ZIBBY_MEM0_LLM_MODEL||"gpt-4.1-mini").trim(),n=String(process.env.ZIBBY_MEM0_EMBEDDER_MODEL||"text-embedding-3-small").trim(),i=Number(process.env.ZIBBY_MEM0_EMBEDDING_DIMS||1536),{vectorDbPath:o,historyDbPath:m}=J(t||process.cwd());return{llm:{provider:"openai",config:{model:s,baseURL:e,...r?{apiKey:r}:{}}},embedder:{provider:"openai",config:{model:n,embeddingDims:i,baseURL:e,...r?{apiKey:r}:{}}},vectorStore:{provider:"memory",config:{dimension:i,dbPath:o}},historyDbPath:m}}async function re(t){let e=t||process.cwd();if(L.has(e))return L.get(e);let r;try{let m=z(M(_(e,"package.json")).href).resolve("mem0ai/oss");r=await import(M(m).href)}catch{try{let o=ye.resolve("mem0ai/oss");r=await import(M(o).href)}catch(o){throw new Error(`Cannot find package 'mem0ai' for workspace "${e}". Install in that project: npm install mem0ai. (${o.message})`,{cause:o})}}let s=r?.Memory;if(!s)throw new Error("mem0ai/oss does not export Memory");let n=te(e);if(n)try{P(J(e).dir,{recursive:!0})}catch{}let i=n?new s(n):new s;return L.set(e,i),i}function j(t,e="mid"){return(Array.isArray(t)?t:Array.isArray(t?.results)?t.results:[]).map(s=>({id:s?.id||I(),memory_key:s?.metadata?.memoryKey||s?.metadata?.memory_key||null,category:s?.metadata?.category||"fact",content:s?.memory||s?.content||"",source:s?.metadata?.source||"mem0",ticket_key:s?.metadata?.ticketKey||s?.metadata?.ticket_key||null,tier:q(s?.metadata?.tier||e,s?.metadata?.category||"fact"),relevance:Number(s?.score??s?.metadata?.relevance??.8),created_at:s?.created_at||s?.metadata?.created_at||E()})).filter(s=>String(s.content||"").trim().length>0)}var T={id:"dolt",store:(t,e)=>se(t,e),recall:(t,e)=>Re(t,e),brief:(t,e)=>Ae(t,e),endSession:(t,e)=>ie(t,e),logTask:(t,e)=>ce(t,e),taskHistory:(t,e)=>ae(t,e)},ke={id:"mem0",store:(t,e,r)=>Ee(t,e,r),recall:(t,e,r)=>oe(t,e,r),brief:(t,e,r)=>Te(t,e,r),endSession:(t,e)=>ie(t,e),logTask:(t,e)=>ce(t,e),taskHistory:(t,e)=>ae(t,e)},he={dolt:T,mem0:ke};async function x(t,e){let r=await ge(t,e);return he[r]||T}var Ue={id:"chat-memory",description:"Persistent chat memory and task history (Dolt-backed)",envKeys:[],promptFragment:`## Chat Memory (persistent)
You have persistent memory across sessions. Use it to avoid losing context:
- **memory_store**: Save important facts, decisions, or context. Anything worth remembering.
- **memory_recall**: Search your memory by keyword or category. Use this at the START of conversations to recall relevant context.
- **memory_brief**: Get a compact summary of recent sessions and key facts. Load this when starting a new task to understand history.
- **memory_end_session**: Call when a task is complete. Summarizes what happened for future recall.
- **task_log**: Record a completed task (test run, analysis, etc.) for history.
- **task_history**: Query past tasks by ticket, status, or type.

### When to use memory
- At the START of a conversation: call memory_recall or memory_brief to load relevant context
- When you learn something important: call memory_store (e.g. "SCRUM-123 login page is at /auth/login")
- When a task finishes: call task_log to record it
- When the user's request is complete: call memory_end_session

### Categories for memory_store
fact, decision, context, insight, credential, url, error, workaround`,resolve(){return null},async buildPromptContext(t,e={}){let r=t?.options?.workspace||process.cwd(),s=_(r,F),n=await x(r,t),i=n.id;if(i==="dolt"&&!N(s)){let o="Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation";return{backend:i,brief:v({backend:i,error:o},i),promptContext:"",debugPreview:$(v({backend:i,error:o},i)),error:o}}try{let o=await n.brief(e,s,r),m=JSON.parse(o||"{}"),l=v({...m,backend:i},i);return{backend:i,brief:l,promptContext:W(l),debugPreview:$(l),error:l.error||null}}catch(o){if(i==="mem0"&&n!==T&&N(s)){if(!w){w=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${o?.message||o}); degrading to dolt for this run
`)}catch{}}try{let a=await T.brief(e,s,r),u=JSON.parse(a||"{}"),d=v({...u,backend:"dolt"},"dolt");return{backend:"dolt",brief:d,promptContext:W(d),debugPreview:$(d),error:d.error||null,degradedFrom:"mem0"}}catch{}}let m=String(o?.message||o),l=v({backend:i,error:m},i);return{backend:i,brief:l,promptContext:"",debugPreview:$(l),error:m}}},async handleToolCall(t,e,r){let s=r?.options?.workspace||process.cwd(),n=_(s,F),i=await x(s,r),o=i.id;if((o==="dolt"||["memory_end_session","task_log","task_history"].includes(t))&&!N(n))return JSON.stringify({error:"Dolt not available. Install: brew install dolt (macOS) or see https://docs.dolthub.com/introduction/installation"});let l=a=>{switch(t){case"memory_store":return a.store(e,n,s);case"memory_recall":return a.recall(e,n,s);case"memory_brief":return a.brief(e,n,s);case"memory_end_session":return a.endSession(e,n,s);case"task_log":return a.logTask(e,n,s);case"task_history":return a.taskHistory(e,n,s);default:return JSON.stringify({error:`Unknown tool: ${t}`})}};try{return await l(i)}catch(a){if(o==="mem0"&&i!==T){if(N(n)){if(!w){w=!0;try{process.stderr.write(`[chat-memory] mem0 backend unavailable (${a.message}); degrading to dolt for this run
`)}catch{}}try{return await l(T)}catch(u){return JSON.stringify({error:u.message,backend:"dolt",degradedFrom:"mem0"})}}return JSON.stringify({error:`mem0 unavailable (${a.message}); dolt fallback also unavailable`,backend:"mem0"})}return JSON.stringify({error:a.message})}},tools:[{name:"memory_store",description:"Save a fact, decision, or context to persistent memory. Survives across sessions.",input_schema:{type:"object",properties:{memoryKey:{type:"string",description:"Stable semantic identity key (e.g. user.jira.default_board)"},content:{type:"string",description:"The information to remember"},category:{type:"string",enum:["fact","decision","context","insight","preference","credential","url","error","workaround"],description:"Category of memory"},tier:{type:"string",enum:["short","mid","long"],description:"Memory tier: short (session/24h), mid (days/weeks), long (permanent)"},source:{type:"string",description:'Where this info came from (e.g. "jira", "github", "user", "test_run")'},ticketKey:{type:"string",description:"Related ticket key (optional)"},infer:{type:"boolean",description:"true = LLM distills/dedupes facts (costs tokens); false = store raw, embed-only, free",default:!1}},required:["content","category"]}},{name:"memory_recall",description:"Search persistent memory by keyword, category, ticket, or tier. Returns matching facts and context.",input_schema:{type:"object",properties:{query:{type:"string",description:"Search text (matches content)"},category:{type:"string",description:"Filter by category"},ticketKey:{type:"string",description:"Filter by ticket key"},tier:{type:"string",enum:["short","mid","long"],description:"Filter by memory tier"},limit:{type:"number",description:"Max results (default: 20)"}}}},{name:"memory_brief",description:"Get a compact briefing: recent session summaries + top relevant facts. Call at the start of a conversation.",input_schema:{type:"object",properties:{ticketKey:{type:"string",description:"Focus briefing on a specific ticket (optional)"}}}},{name:"memory_end_session",description:"End the current session and save a summary for future recall. Call when a task is complete.",input_schema:{type:"object",properties:{summary:{type:"string",description:"What happened in this session (1-3 sentences)"},tickets:{type:"string",description:"Comma-separated ticket keys covered"},tasksRun:{type:"number",description:"Number of tasks/tests run"},tasksPassed:{type:"number",description:"Number passed"},tasksFailed:{type:"number",description:"Number failed"},keyFacts:{type:"string",description:"Key facts worth remembering from this session (semicolon-separated)"}},required:["summary"]}},{name:"task_log",description:"Record a completed task (test run, analysis, generation) to persistent history.",input_schema:{type:"object",properties:{title:{type:"string",description:"Task description"},type:{type:"string",enum:["test_run","generate","analysis","research","other"],description:"Task type"},status:{type:"string",enum:["passed","failed","cancelled","error"],description:"Outcome"},ticketKey:{type:"string",description:"Related ticket key"},specPath:{type:"string",description:"Spec file path (if test run)"},resultSummary:{type:"string",description:"Brief result description"}},required:["title","type","status"]}},{name:"task_history",description:"Query past tasks by ticket, status, or type. See what was done before.",input_schema:{type:"object",properties:{ticketKey:{type:"string",description:"Filter by ticket key"},type:{type:"string",description:"Filter by task type"},status:{type:"string",description:"Filter by status"},limit:{type:"number",description:"Max results (default: 20)"}}}}]};function se(t,e){let{content:r,category:s,source:n,ticketKey:i,tier:o,memoryKey:m}=t;if(!r||!s)return JSON.stringify({error:"content and category are required"});let l=K(r);if(!l)return JSON.stringify({error:"content is empty after normalization"});let a=q(o,s),u=a==="long"?1:a==="mid"?.8:.5,d=String(m||"").trim().slice(0,160);if(d){let k=h(e,`SELECT id, tier, relevance
      FROM chat_memory
      WHERE memory_key = ${c(d)}
      ORDER BY created_at DESC
      LIMIT 1`)[0];if(k){let R=String(k.tier||"mid"),D=Number(k.relevance||0),V=A(a)>A(R)?a:R,le=Math.max(u,D);g(e,`UPDATE chat_memory
        SET content = ${c(r)},
            category = ${c(s)},
            source = ${c(n)},
            ticket_key = ${c(i)},
            tier = ${c(V)},
            relevance = ${le},
            created_at = ${c(E())}
        WHERE id = ${c(k.id)}`);try{f(e,["add","."]),f(e,["commit","-m",`memory upsert: ${s} \u2014 ${String(r).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:k.id,category:s,tier:V,memoryKey:d,upserted:!0})}}let p=h(e,`SELECT id, content, tier, relevance
     FROM chat_memory
     WHERE category = ${c(s)}
     ORDER BY created_at DESC
     LIMIT 200`).find(S=>K(S.content)===l);if(p){let S=String(p.tier||"mid"),k=Number(p.relevance||0),R=A(a)>A(S),D=u>k;if(R||D){g(e,`UPDATE chat_memory
        SET tier = ${c(R?a:S)},
            relevance = ${Math.max(u,k)}
        WHERE id = ${c(p.id)}`);try{f(e,["add","."]),f(e,["commit","-m",`memory promote: ${s} \u2014 ${String(r).slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:p.id,category:s,tier:R?a:S,deduped:!0,promoted:!0})}return JSON.stringify({ok:!0,id:p.id,category:s,tier:S,deduped:!0,promoted:!1})}let O=I(),me=process.env.ZIBBY_CHAT_SESSION_ID||null;g(e,`INSERT INTO chat_memory (id, memory_key, category, content, source, ticket_key, session_id, tier, relevance, created_at)
     VALUES (${c(O)}, ${c(d||null)}, ${c(s)}, ${c(r)}, ${c(n)}, ${c(i)}, ${c(me)}, ${c(a)}, ${u}, ${c(E())})`);try{f(e,["add","."]),f(e,["commit","-m",`memory: ${s} \u2014 ${r.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:O,category:s,tier:a,memoryKey:d||null,stored:r.slice(0,100)})}function Se(t){let e=String(t||"").trim().toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"}var B=new Map;async function ne(t,e){if(typeof t=="boolean")return t;if(process.env.ZIBBY_MEM0_INFER!=null&&String(process.env.ZIBBY_MEM0_INFER).trim()!=="")return Se(process.env.ZIBBY_MEM0_INFER);let r=e||process.cwd();if(B.has(r))return B.get(r);let s=!1;try{let n=_(r,".zibby.config.mjs");Y(n)&&(s=(await import(M(n).href))?.default?.memory?.infer===!0)}catch{}return B.set(r,s),s}async function Ee(t,e,r){let{content:s,category:n,source:i,ticketKey:o,tier:m,memoryKey:l,infer:a}=t;if(!s||!n)return JSON.stringify({error:"content and category are required"});try{let u=await re(r),d=ee(r),y=q(m,n),p=await ne(a,r);return await u.add([{role:"user",content:String(s)}],{userId:d,infer:p,metadata:{memoryKey:l||null,category:n,tier:y,source:i||"zibby-chat",ticketKey:o||null,created_at:E()}}),JSON.stringify({ok:!0,backend:"mem0",userId:d,category:n,tier:y,infer:p,memoryKey:l||null,stored:String(s).slice(0,100)})}catch(u){throw new Error(`mem0 store failed: ${u.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:u})}}function Re(t,e){let{query:r,category:s,ticketKey:n,tier:i,limit:o=20}=t,m=[];r&&m.push(`content LIKE ${c(`%${r}%`)}`),s&&m.push(`category = ${c(s)}`),n&&m.push(`ticket_key = ${c(n)}`),i&&m.push(`tier = ${c(i)}`);let a=`SELECT id, memory_key, category, content, source, ticket_key, tier, relevance, created_at
               FROM chat_memory ${m.length>0?`WHERE ${m.join(" AND ")}`:""}
               ORDER BY relevance DESC, created_at DESC
               LIMIT ${o}`,u=h(e,a);return JSON.stringify({total:u.length,memories:u})}async function oe(t,e,r){let{query:s,category:n,ticketKey:i,tier:o,limit:m=20}=t;try{let l=await re(r),a=ee(r),u=[];if(s&&String(s).trim()){let d=await l.search(String(s),{filters:{user_id:a},topK:m});u=j(d)}else{let d=await l.getAll({filters:{user_id:a},topK:Math.max(m,50)});u=j(d)}return n&&(u=u.filter(d=>d.category===n)),i&&(u=u.filter(d=>d.ticket_key===i)),o&&(u=u.filter(d=>d.tier===o)),u=u.slice(0,m),JSON.stringify({total:u.length,memories:u,backend:"mem0"})}catch(l){throw new Error(`mem0 recall failed: ${l.message}. If mem0 is not installed, run: npm install mem0ai`,{cause:l})}}function Ae(t,e){let{ticketKey:r}=t;Me(e);let n=h(e,`SELECT session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, created_at
                       FROM chat_sessions ORDER BY created_at DESC LIMIT 5`),i=r?`AND ticket_key = ${c(r)}`:"",o=h(e,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
     WHERE tier = 'long' ${i} ORDER BY relevance DESC, created_at DESC LIMIT 10`),m=h(e,`SELECT memory_key, category, content, source, tier, relevance, created_at FROM chat_memory
     WHERE tier = 'mid' ${i} ORDER BY relevance DESC, created_at DESC LIMIT 8`),a=h(e,`SELECT type, status, COUNT(*) as cnt FROM chat_tasks
                    GROUP BY type, status ORDER BY cnt DESC LIMIT 10`),u=Q([...o,...m]);return JSON.stringify({recentSessions:n,topMemories:u,taskStats:a,ticketFilter:r||null})}async function Te(t,e,r){let{ticketKey:s}=t,n=await oe({limit:80},e,r),i=JSON.parse(n||"{}"),o=Array.isArray(i.memories)?i.memories:[];s&&(o=o.filter(y=>y.ticket_key===s));let m=y=>{let p=Date.parse(String(y?.created_at||""))||0;return Number(y?.relevance||0)*1e12+p},l=(y,p)=>m(p)-m(y),a=o.filter(y=>y.tier==="long").sort(l).slice(0,10),u=o.filter(y=>y.tier==="mid").sort(l).slice(0,8),d=Q([...a,...u]);return JSON.stringify({recentSessions:[],topMemories:d,taskStats:[],ticketFilter:s||null,backend:"mem0"})}function ie(t,e){let{summary:r,tickets:s,tasksRun:n=0,tasksPassed:i=0,tasksFailed:o=0,keyFacts:m}=t;if(!r)return JSON.stringify({error:"summary is required"});let l=process.env.ZIBBY_CHAT_SESSION_ID||`session_${I()}`;if(g(e,`INSERT INTO chat_sessions (session_id, summary, tickets, tasks_run, tasks_passed, tasks_failed, key_facts, created_at)
     VALUES (${c(l)}, ${c(r)}, ${c(s)}, ${n}, ${i}, ${o}, ${c(m)}, ${c(E())})`),m)for(let a of m.split(";").map(u=>u.trim()).filter(Boolean))se({content:a,category:"fact",source:"session_summary",tier:"mid"},e);ve(e);try{f(e,["add","."]),f(e,["commit","-m",`session end: ${r.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,sessionId:l,summary:r.slice(0,200)})}function ce(t,e){let{title:r,type:s,status:n,ticketKey:i,specPath:o,resultSummary:m}=t;if(!r||!s||!n)return JSON.stringify({error:"title, type, and status are required"});let l=I(),a=process.env.ZIBBY_CHAT_SESSION_ID||null;g(e,`INSERT INTO chat_tasks (id, ticket_key, type, title, status, spec_path, session_id, result_summary, created_at, finished_at)
     VALUES (${c(l)}, ${c(i)}, ${c(s)}, ${c(r)}, ${c(n)}, ${c(o)}, ${c(a)}, ${c(m)}, ${c(E())}, ${c(E())})`);try{f(e,["add","."]),f(e,["commit","-m",`task: ${n} \u2014 ${r.slice(0,60)}`])}catch{}return JSON.stringify({ok:!0,id:l,title:r,type:s,status:n})}function ae(t,e){let{ticketKey:r,type:s,status:n,limit:i=20}=t,o=[];r&&o.push(`ticket_key = ${c(r)}`),s&&o.push(`type = ${c(s)}`),n&&o.push(`status = ${c(n)}`);let l=`SELECT id, ticket_key, type, title, status, spec_path, result_summary, created_at, finished_at
               FROM chat_tasks ${o.length>0?`WHERE ${o.join(" AND ")}`:""}
               ORDER BY created_at DESC LIMIT ${i}`,a=h(e,l);return JSON.stringify({total:a.length,tasks:a})}function ve(t){try{g(t,"UPDATE chat_memory SET relevance = relevance * 0.98 WHERE tier = 'long' AND relevance > 0.5"),g(t,"UPDATE chat_memory SET relevance = relevance * 0.90 WHERE tier = 'mid' AND relevance > 0.1"),g(t,"UPDATE chat_memory SET relevance = relevance * 0.70 WHERE tier = 'short' AND relevance > 0.05"),g(t,"DELETE FROM chat_memory WHERE relevance < 0.05")}catch{}}function Me(t){try{let e=new Date(Date.now()-864e5).toISOString();g(t,`DELETE FROM chat_memory WHERE tier = 'short' AND created_at < ${c(e)}`)}catch{}}export{De as _mem0DbPaths,Oe as _resetInitCache,Le as _resolveMem0Config,Fe as _resolveMem0Infer,Be as _resolveMemoryAdapter,Ue as chatMemorySkill};
