@easbot/memory 0.3.20 → 0.3.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/chunks/{chunk-TIZCWDJ7.mjs → chunk-5DCNLEAC.mjs} +1 -1
  2. package/dist/chunks/{chunk-AYGZUNFR.cjs → chunk-ECTHWVFQ.cjs} +1 -1
  3. package/dist/chunks/{chunk-EGWJG65Q.cjs → chunk-EK34SXJ7.cjs} +24 -17
  4. package/dist/chunks/{chunk-JDPZ5U53.mjs → chunk-PJGILQSZ.mjs} +24 -17
  5. package/dist/chunks/{chunk-N5YRDTEH.mjs → chunk-WDGBZHIS.mjs} +33 -27
  6. package/dist/chunks/chunk-YAKGP77O.cjs +65 -0
  7. package/dist/chunks/{chunk-S6S35LDL.cjs → chunk-YYCHHBMU.cjs} +36 -30
  8. package/dist/chunks/chunk-ZIFDM4GO.mjs +65 -0
  9. package/dist/chunks/cli-handler-T3G2REK3.mjs +1 -0
  10. package/dist/chunks/cli-handler-YQEIJ6L2.cjs +1 -0
  11. package/dist/chunks/{config-RPPQ73HK.cjs → config-I2I6U4XM.cjs} +1 -1
  12. package/dist/chunks/consolidate-FWRCKNBO.mjs +2 -0
  13. package/dist/chunks/{consolidate-G4YJV756.cjs → consolidate-GQ5KCVWW.cjs} +1 -1
  14. package/dist/chunks/doctor-SYBFGZAM.cjs +1 -0
  15. package/dist/chunks/{doctor-GKMREWZN.mjs → doctor-Z4MRWUSA.mjs} +1 -1
  16. package/dist/chunks/{extract-YKDPZ7GA.cjs → extract-HBIYSJRI.cjs} +1 -1
  17. package/dist/chunks/extract-LUBUHISD.mjs +2 -0
  18. package/dist/chunks/{forget-GNIJL2DU.cjs → forget-C7DNK4TJ.cjs} +1 -1
  19. package/dist/chunks/{forget-VQB5DUJ3.mjs → forget-MSXKORPW.mjs} +1 -1
  20. package/dist/chunks/{graph-4W63TU2D.mjs → graph-HKBJTVVV.mjs} +1 -1
  21. package/dist/chunks/{graph-GTYUNUJE.cjs → graph-ONZARVEF.cjs} +1 -1
  22. package/dist/chunks/{init-DGMGRNCG.cjs → init-AL4IZIBJ.cjs} +1 -1
  23. package/dist/chunks/init-GVYXEMZ3.mjs +1 -0
  24. package/dist/chunks/{interfaces-XWE45ENK.cjs → interfaces-Q5OGU5EK.cjs} +1 -1
  25. package/dist/chunks/{llm-RMPVWEVP.cjs → llm-7LQGYSUE.cjs} +1 -1
  26. package/dist/chunks/{mcp-EHUKGJRB.cjs → mcp-NAE5FPNQ.cjs} +1 -1
  27. package/dist/chunks/{mcp-QQBHEZFY.mjs → mcp-OZFKMFEM.mjs} +1 -1
  28. package/dist/chunks/{recall-ZENMAOMJ.cjs → recall-V7XEE6MG.cjs} +1 -1
  29. package/dist/chunks/recall-W4WBZG5W.mjs +2 -0
  30. package/dist/chunks/{remember-3ZY66RJQ.cjs → remember-5H5A6O5I.cjs} +1 -1
  31. package/dist/chunks/{remember-P3G7WWYB.mjs → remember-XBPCHY4Q.mjs} +1 -1
  32. package/dist/chunks/{status-JYI52QKB.mjs → status-SKO36F6J.mjs} +1 -1
  33. package/dist/chunks/status-ZX25EAH7.cjs +1 -0
  34. package/dist/chunks/stdio-server-EORG6GVP.mjs +1 -0
  35. package/dist/chunks/stdio-server-NHPVPW5A.cjs +1 -0
  36. package/dist/chunks/{sync-64JINCSC.cjs → sync-3L57TMXR.cjs} +1 -1
  37. package/dist/chunks/{sync-ZPRCA4MO.mjs → sync-L5XS442K.mjs} +1 -1
  38. package/dist/cli.cjs +1 -1
  39. package/dist/cli.mjs +1 -1
  40. package/dist/index.cjs +4 -4
  41. package/dist/index.d.cts +24 -1
  42. package/dist/index.d.ts +24 -1
  43. package/dist/index.mjs +4 -4
  44. package/package.json +10 -10
  45. package/dist/chunks/chunk-UF2Y2Q4L.mjs +0 -50
  46. package/dist/chunks/chunk-Z5E4HBGK.cjs +0 -50
  47. package/dist/chunks/cli-handler-2IPBL45N.cjs +0 -1
  48. package/dist/chunks/cli-handler-5YNHYDSM.mjs +0 -1
  49. package/dist/chunks/consolidate-MSPLH3T6.mjs +0 -2
  50. package/dist/chunks/doctor-YTUQCHFJ.cjs +0 -1
  51. package/dist/chunks/extract-3C4QFS7E.mjs +0 -2
  52. package/dist/chunks/init-G2WTR477.mjs +0 -1
  53. package/dist/chunks/recall-SGA2DITO.mjs +0 -2
  54. package/dist/chunks/status-UEKBJVCI.cjs +0 -1
  55. package/dist/chunks/stdio-server-2PWTBTDJ.mjs +0 -1
  56. package/dist/chunks/stdio-server-JL4XNUHH.cjs +0 -1
  57. /package/dist/chunks/{chunk-NVGACA7W.cjs → chunk-M2YU5LAI.cjs} +0 -0
@@ -1,50 +0,0 @@
1
- 'use strict';var chunkEGWJG65Q_cjs=require('./chunk-EGWJG65Q.cjs'),chunkCPRDIUQ4_cjs=require('./chunk-CPRDIUQ4.cjs'),chunkJ5XF2W4Z_cjs=require('./chunk-J5XF2W4Z.cjs'),chunkNVGACA7W_cjs=require('./chunk-NVGACA7W.cjs'),utils=require('@easbot/utils'),zod=require('zod'),crypto=require('crypto'),llm=require('@easbot/llm'),G=require('fs/promises'),ce=require('path'),fs=require('fs'),module$1=require('module'),types=require('@easbot/types');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var G__default=/*#__PURE__*/_interopDefault(G);var ce__default=/*#__PURE__*/_interopDefault(ce);var me=utils.Log.create({service:"memory.graph-store"}),J=class{constructor(e){chunkNVGACA7W_cjs.a(this,"db");this.db=e;}async upsertNode(e,n,r,o){let c=Date.now(),s=JSON.stringify(r??{}),i=this.db.prepare("SELECT id FROM nodes WHERE name = ? AND type = ? LIMIT 1").get(e,n);if(i)return this.db.prepare("UPDATE nodes SET properties = ?, updatedAt = ? WHERE id = ?").run(s,c,i.id),i.id;let p=this.db.prepare("INSERT INTO nodes (name, type, properties, owner_agent_id, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)").run(e,n,s,o??null,c,c);return Number(p.lastInsertRowid)}async deleteNode(e){this.db.prepare("DELETE FROM nodes WHERE id = ?").run(e);}async upsertEdge(e,n,r,o){let c=this.db.prepare("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)").run(e,n,r,JSON.stringify(o??{}),Date.now());return Number(c.lastInsertRowid)}async queryNodes(e={}){let n="SELECT id, name, type, properties, owner_agent_id, createdAt, updatedAt FROM nodes",r=[],o=[];if(e.ids&&e.ids.length>0){let s=e.ids.map(i=>typeof i=="string"?parseInt(i,10):i).filter(i=>!Number.isNaN(i));o.push(`id IN (${s.map(()=>"?").join(", ")})`),r.push(...s);}e.name&&(o.push("name LIKE ?"),r.push(`%${e.name}%`)),e.type&&(o.push("type = ?"),r.push(e.type)),ut(o,r,e.agentId,e.scope??"agent_only"),o.length>0&&(n+=` WHERE ${o.join(" AND ")}`),n+=" ORDER BY id",e.limit&&(n+=" LIMIT ?",r.push(e.limit)),me.debug("queryNodes",{sql:n,params:r,filter:e});let c=this.db.prepare(n).all(...r);return me.debug("queryNodes result",{count:c.length}),c.map(s=>({id:s.id,name:s.name,type:s.type,properties:s.properties?JSON.parse(s.properties):void 0,createdAt:s.createdAt,updatedAt:s.updatedAt,ownerAgentId:s.owner_agent_id}))}async queryEdges(e={}){let n="SELECT e.id, e.source, e.target, e.relation, e.properties, e.createdAt FROM edges e",r=[],o=[];if(e.ids&&e.ids.length>0&&(o.push(`e.id IN (${e.ids.map(()=>"?").join(", ")})`),r.push(...e.ids)),e.source!==void 0&&(o.push("e.source = ?"),r.push(e.source)),e.target!==void 0&&(o.push("e.target = ?"),r.push(e.target)),e.sourceOrTarget&&e.sourceOrTarget.length>0){let f=e.sourceOrTarget.map(m=>typeof m=="string"?parseInt(m,10):m).filter(m=>!Number.isNaN(m));o.push(`(e.source IN (${f.map(()=>"?").join(", ")}) OR e.target IN (${f.map(()=>"?").join(", ")}))`),r.push(...f,...f);}e.relation&&(o.push("e.relation = ?"),r.push(e.relation)),o.length>0&&(n+=` WHERE ${o.join(" AND ")}`),n+=" ORDER BY e.id",e.limit&&(n+=" LIMIT ?",r.push(e.limit)),me.debug("queryEdges",{sql:n,params:r,filter:e});let c=this.db.prepare(n).all(...r);me.debug("queryEdges result",{count:c.length});let s=[...new Set(c.map(f=>f.target))],i=s.length>0?await this.queryNodes({ids:s,limit:s.length}):[],p=new Map(i.map(f=>[f.id,f]));return c.map(f=>{let m={id:f.id,source:f.source,target:f.target,relation:f.relation,properties:f.properties?JSON.parse(f.properties):void 0,createdAt:f.createdAt},u=p.get(f.target);return u&&(m.targetNode=u),m})}async queryNeighbors(e,n=1,r){let o=r?.agentId,c=r?.scope??"agent_only",s=new Set,i=[{id:e,level:0}],p=[],f=r?.maxEdgesPerNode??50;for(;i.length>0;){let m=i.shift();if(!m)break;if(s.has(m.id)||m.level>n)continue;s.add(m.id);let I=(await this.queryNodes({ids:[m.id],limit:1,agentId:o,scope:c}))[0];if(!I)continue;let v=await this.queryEdges({sourceOrTarget:[m.id],limit:f}),S=o?await lt(this,v,o,c):v;if(p.push({...I,edges:S}),m.level<n)for(let w of S){let h=w.source===m.id?w.target:w.source;s.has(h)||i.push({id:h,level:m.level+1});}}return p}};async function lt(t,e,n,r){if(e.length===0)return e;let o=new Set;for(let i of e)o.add(i.source),o.add(i.target);let c=await t.queryNodes({ids:Array.from(o),agentId:n,scope:r,limit:o.size}),s=new Set(c.map(i=>i.id));return e.filter(i=>s.has(i.source)&&s.has(i.target))}function ut(t,e,n,r){if(n)switch(r){case "agent_only":t.push("owner_agent_id = ?"),e.push(n);break;case "shared_only":t.push("owner_agent_id IS NULL");break;case "both":t.push("(owner_agent_id = ? OR owner_agent_id IS NULL)"),e.push(n);break}}var M=class extends Error{constructor(n,r,o){super(n);chunkNVGACA7W_cjs.a(this,"code",r);chunkNVGACA7W_cjs.a(this,"details",o);this.name="ServiceError";}};var le=class extends M{constructor(){super("ctx.agentId is required for memory service (ADR 0055 per-agent isolation)","AGENT_ID_REQUIRED");}},te=class extends M{constructor(e,n){super(`Trust denied for operation "${e}": ${n}`,"TRUST_DENIED",{operation:e,reason:n});}},re=class extends M{constructor(e,n){super(`Memory ${e} has ${n} references (force=false)`,"HAS_REFERENCES",{memoryId:e,referenceCount:n});}},ne=class extends M{constructor(e){super(`dryRun mode: ${e} memories matched but not deleted`,"DRY_RUN_NO_DELETE",{matchedCount:e});}},oe=class extends M{constructor(e,n){super(`Matched ${e} memories exceeds maxDelete=${n}`,"MAX_DELETE_EXCEEDED",{matched:e,maxDelete:n});}};function H(t){if(typeof t.agentId!="string"||t.agentId.trim().length===0)throw new le}function j(t,e){if(t.remote!==false)throw new te(e,"requires trusted local caller (CLI / agent tool / MCP with remote=false)")}function ue(t,e,n){if(e!=="agent_only"&&t.remote!==false)throw new te(n,`scope="${e}" requires trusted local caller (cross-agent access denied)`)}function ge(t){if(!t.dbPath||t.dbPath.trim().length===0)throw new M("service ctx.dbPath is required (MemoryKnowledgeConfigWithModels.database.path)","INTERNAL")}var ae=utils.Log.create({service:"memory.service.recall"});async function Fe(t,e){let n=Date.now();if(H(t),ge(t),!e.query||e.query.trim().length===0)throw new M("recall requires non-empty `query`","CONTENT_REQUIRED");let r=e.includeShared?"both":"agent_only";e.includeGraph&&ue(t,r,"recall"),ae.debug("recall invoked",{agentId:t.agentId,query:e.query,category:e.category,maxResults:e.maxResults,includeGraph:e.includeGraph,scope:r});let o=e.maxResults??10,c=e.minScore??0,s=[],i=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await i.initialize();let p=chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().embedding===!0,f=await pt(i,t.agentId,e.query,{category:e.category,minImportance:e.minImportance,fromTime:e.fromTime,toTime:e.toTime,limit:o,minScore:c,hasEmbedding:p}),m;if(e.includeGraph&&f.length>0)try{let I=new J(i.getDb()),v=e.depth??1,S=f.flatMap(y=>(y.nodes??[]).map(E=>E.id)).slice(0,5),w=new Set,h=new Map;for(let y of S){let E=await I.queryNeighbors(y,v,{agentId:t.agentId,scope:r,maxEdgesPerNode:10});for(let _ of E)w.add(_.id),h.set(_.id,_.edges??[]);}let b=w.size>0?i.query(`SELECT id, name, type FROM nodes WHERE id IN (${Array.from(w).map(()=>"?").join(",")})`,Array.from(w)):[],R=Array.from(h.values()).flat();m={nodes:b.map(y=>({id:y.id,name:y.name,type:y.type,createdAt:"",updatedAt:""})),edges:R};}catch(I){let v=I instanceof Error?I.message:String(I);ae.warn("recall: KG neighbor query failed",{error:v}),s.push(`kg_neighbor_query_failed: ${v}`),m={nodes:[],edges:[]};}let u=Date.now()-n;return {hits:f,total:f.length,truncated:f.length>=o,durationMs:u,graph:m,...s.length>0?{warnings:s}:{}}}catch(p){throw p instanceof M?p:new M(`recall failed: ${p instanceof Error?p.message:String(p)}`,"INTERNAL",{cause:p instanceof Error?p.message:String(p)})}finally{i.close();}}async function pt(t,e,n,r){let o=["mf.agent_id = ?"],c=[e];r.category&&(o.push("mf.category = ?"),c.push(r.category)),r.minImportance!==void 0&&(o.push("mf.importance >= ?"),c.push(r.minImportance)),r.fromTime&&(o.push("mf.created_at >= ?"),c.push(r.fromTime)),r.toTime&&(o.push("mf.created_at <= ?"),c.push(r.toTime));let s=o.join(" AND "),i=null;if(r.hasEmbedding)try{i=await chunkJ5XF2W4Z_cjs.a.embedText(n);}catch(g){ae.warn("recall: query embedding failed, falling back to FTS-only",{error:g instanceof Error?g.message:String(g)}),i=null;}let p=Math.max(r.limit*100,1e3),[f,m]=await Promise.all([i?ft(t,i,s,c,p):Promise.resolve([]),yt(t,n,s,c,r.limit)]),u=i?.7:0,I=i?.3:1,v=u+I,S=u/v,w=I/v,h=new Map;for(let g of f)h.set(g.id,g.score*S);for(let g of m)h.set(g.id,(h.get(g.id)??0)+g.score*w);let b=Array.from(h.entries()).sort((g,k)=>k[1]-g[1]).map(([g])=>g).slice(0,r.limit);if(b.length===0)return [];let R=b.map(()=>"?").join(","),y=t.query(`SELECT
2
- mf.id,
3
- mf.category,
4
- mf.importance,
5
- mf.agent_id as agentId,
6
- SUBSTR(mf.content, 1, 200) as snippet,
7
- mf.created_at as createdAt,
8
- mf.source,
9
- mf.file_path as filePath,
10
- mf.node_ids as nodeIds
11
- FROM memory_facts mf
12
- WHERE mf.id IN (${R})`,b),E=Date.now();return y.map(g=>{let k=h.get(g.id)??0,O=(E-new Date(g.createdAt).getTime())/864e5,F=Math.exp(-0.05*O),W=(g.importance-1)/9,B=.4*k+.3*F+.3*W;return {memoryId:g.id,category:g.category,importance:g.importance,agentId:g.agentId,snippet:g.snippet,score:B,createdAt:g.createdAt,source:g.source,filePath:g.filePath??void 0,nodes:void 0}}).filter(g=>g.score>=r.minScore).sort((g,k)=>k.score-g.score)}function ft(t,e,n,r,o){try{return t.query(`SELECT mf.id, mv.embedding
13
- FROM memory_facts mf
14
- JOIN memory_vectors mv ON mf.id = mv.fact_id
15
- WHERE ${n}
16
- LIMIT ?`,[...r,o]).map(s=>{let i=new Float32Array(s.embedding.buffer,s.embedding.byteOffset,s.embedding.byteLength/4);return {id:s.id,score:ht(e,i)}}).sort((s,i)=>i.score-s.score)}catch(c){if(c instanceof M)throw c;return ae.warn("vector search failed, falling back to FTS-only",{error:c instanceof Error?c.message:String(c)}),[]}}function yt(t,e,n,r,o){try{let c=t.query(`SELECT mf.id as id, bm25(memory_facts_fts) as score
17
- FROM memory_facts_fts fts
18
- JOIN memory_facts mf ON mf.id = fts.fact_id
19
- WHERE ${n} AND memory_facts_fts MATCH ?
20
- ORDER BY score DESC
21
- LIMIT ?`,[...r,bt(e),o]);if(c.length===0)return [];let s=Math.max(...c.map(i=>Math.abs(i.score)),1);return c.map(i=>({id:i.id,score:1-Math.abs(i.score)/s})).filter(i=>i.score>=0)}catch(c){if(c instanceof M)throw c;return ae.warn("FTS search failed, returning empty result",{err:c instanceof Error?c.message:String(c)}),[]}}function ht(t,e){if(t.length!==e.length||t.length===0)return 0;let n=0,r=0,o=0;for(let s=0;s<t.length;s++){let i=t[s]??0,p=e[s]??0;n+=i*p,r+=i*i,o+=p*p;}let c=Math.sqrt(r)*Math.sqrt(o);return c===0?0:Math.max(0,n/c)}function bt(t){return t.trim().split(/\s+/).filter(e=>e.length>0).map(e=>`"${e.replace(/"/g,'""')}"`).join(" ")}var qe=zod.z.object({query:zod.z.string().min(1).max(500),category:zod.z.string().optional(),minImportance:zod.z.number().min(1).max(10).optional(),fromTime:zod.z.string().datetime().optional(),toTime:zod.z.string().datetime().optional(),maxResults:zod.z.number().int().min(1).max(100).optional().default(10),minScore:zod.z.number().min(0).max(1).optional(),includeGraph:zod.z.boolean().optional().default(false),depth:zod.z.number().int().min(1).max(5).optional().default(1),includeShared:zod.z.boolean().optional().default(false)});zod.z.object({hits:zod.z.array(zod.z.unknown()),total:zod.z.number(),truncated:zod.z.boolean(),durationMs:zod.z.number(),graph:zod.z.object({nodes:zod.z.array(zod.z.unknown()),edges:zod.z.array(zod.z.unknown())}).optional()});var $e=zod.z.object({content:zod.z.string().min(1).max(1e4),category:zod.z.string().min(1),importance:zod.z.number().int().min(1).max(10).optional().default(5),tags:zod.z.array(zod.z.string()).optional(),sessionId:zod.z.string().optional(),msgId:zod.z.string().optional(),parentMsgId:zod.z.string().optional(),skipDedup:zod.z.boolean().optional().default(false),extractGraph:zod.z.boolean().optional().default(true)});zod.z.object({fact:zod.z.object({id:zod.z.string(),agentId:zod.z.string(),content:zod.z.string(),category:zod.z.string(),importance:zod.z.number(),createdAt:zod.z.string(),updatedAt:zod.z.string()}),filePath:zod.z.string(),deduplicated:zod.z.boolean(),nodeIds:zod.z.array(zod.z.number()).optional()});var He=zod.z.object({factId:zod.z.string().optional(),category:zod.z.string().optional(),fromTime:zod.z.string().datetime().optional(),toTime:zod.z.string().datetime().optional(),maxDelete:zod.z.number().int().min(1).max(1e4).optional().default(1e3),dryRun:zod.z.boolean().optional().default(false),force:zod.z.boolean().optional().default(false)}).refine(t=>t.factId!==void 0&&t.factId.length>0||t.category!==void 0&&t.category.length>0||t.fromTime!==void 0||t.toTime!==void 0,{message:"one of `factId`, `category`, `fromTime`, or `toTime` is required"});zod.z.object({deletedCount:zod.z.number(),deletedIds:zod.z.array(zod.z.string()),dryRun:zod.z.boolean(),truncatedCount:zod.z.number()});var Ue=zod.z.object({sessionId:zod.z.string().min(1),lastN:zod.z.number().int().min(1).max(500).optional().default(50),fromMessageId:zod.z.string().optional(),writeToDisk:zod.z.boolean().optional().default(true)});zod.z.object({extractedCount:zod.z.number(),factIds:zod.z.array(zod.z.string()),entities:zod.z.array(zod.z.object({id:zod.z.number(),name:zod.z.string(),type:zod.z.string()})),relations:zod.z.array(zod.z.object({source:zod.z.string(),target:zod.z.string(),relation:zod.z.string()})),messageRange:zod.z.object({fromMessageId:zod.z.string(),toMessageId:zod.z.string()}),durationMs:zod.z.number()});var We=zod.z.object({windowDays:zod.z.number().int().min(1).max(365).optional().default(30),dryRun:zod.z.boolean().optional().default(false)});zod.z.object({totalFacts:zod.z.number(),dedupedCount:zod.z.number(),compressedCount:zod.z.number(),archivedCount:zod.z.number(),skippedCount:zod.z.number(),durationMs:zod.z.number()});var je=zod.z.object({query:zod.z.string().min(1),type:zod.z.string().optional(),depth:zod.z.number().int().min(1).max(5).optional().default(2),maxNodes:zod.z.number().int().min(1).max(500).optional().default(100),scope:zod.z.enum(["agent_only","shared_only","both"]).optional().default("agent_only"),relation:zod.z.string().optional()});zod.z.object({root:zod.z.unknown().nullable(),nodes:zod.z.array(zod.z.unknown()),edges:zod.z.array(zod.z.unknown()),truncated:zod.z.boolean(),totalNodes:zod.z.number(),totalEdges:zod.z.number(),scope:zod.z.enum(["agent_only","shared_only","both"]),durationMs:zod.z.number()});var Ge=zod.z.object({}).optional();zod.z.object({dbPath:zod.z.string(),workspaceDir:zod.z.string(),factsCount:zod.z.number(),nodesCount:zod.z.number(),edgesCount:zod.z.number(),factsByCategory:zod.z.record(zod.z.string(),zod.z.number()),ftsAvailable:zod.z.boolean(),vectorEnabled:zod.z.boolean(),kgScopeEnabled:zod.z.boolean(),healthy:zod.z.boolean(),meta:zod.z.record(zod.z.string(),zod.z.string())});var ze=zod.z.object({}).optional();zod.z.object({healthy:zod.z.boolean(),checks:zod.z.array(zod.z.object({name:zod.z.string(),passed:zod.z.boolean(),message:zod.z.string(),details:zod.z.record(zod.z.string(),zod.z.unknown()).optional()}))});var Be=zod.z.object({workspaceDir:zod.z.string().optional(),dbPath:zod.z.string().optional(),archiveDays:zod.z.number().int().min(1).max(3650).optional().default(30),force:zod.z.boolean().optional().default(false)});zod.z.object({initialized:zod.z.boolean(),dbPath:zod.z.string(),workspaceDir:zod.z.string(),tablesCreated:zod.z.number(),migrationsApplied:zod.z.number(),durationMs:zod.z.number()});var Qe=zod.z.object({windowDays:zod.z.number().int().min(1).max(3650).optional(),dryRun:zod.z.boolean().optional().default(false)});zod.z.object({generatedCount:zod.z.number(),skippedCount:zod.z.number(),failedGenerateCount:zod.z.number(),archivedCount:zod.z.number(),archiveThreshold:zod.z.string(),archivedRecords:zod.z.array(zod.z.object({source:zod.z.string(),target:zod.z.string(),firstCreatedAt:zod.z.string(),firstFactId:zod.z.string()})),windowDays:zod.z.number(),dryRun:zod.z.boolean(),durationMs:zod.z.number()});var se=utils.Log.create({service:"memory.fact-file-sync"}),Rt=".easbot/memory/active";function ie(t,e){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),r=t.category||"uncategorized",o=t.createdAt?new Date(t.createdAt).getTime():Date.now(),c=Number.isNaN(o)?new Date:new Date(o),s=c.getFullYear(),i=String(c.getMonth()+1).padStart(2,"0"),p=String(c.getDate()).padStart(2,"0"),f=`${s}-${i}-${p}`;return `${n}/${Rt}/${r}/${f}.md`}function Ke(t){let e=t.tags&&t.tags.length>0?t.tags:[],n=t.importance??5,r=t.source??"session_self_write",o=t.createdAt?utils.formatLocalISO(new Date(t.createdAt)):utils.formatLocalISO(new Date),c=t.updatedAt?utils.formatLocalISO(new Date(t.updatedAt)):o,s=["---",`id: ${t.id}`,`agent_id: ${t.agentId}`,`category: ${t.category}`,`importance: ${n}`,`created_at: ${o}`,`updated_at: ${c}`,`source: ${r}`,e.length>0?`tags: [${e.join(", ")}]`:"tags: []"];return t.sessionId&&s.push(`session_id: ${t.sessionId}`),t.msgId&&s.push(`msg_id: ${t.msgId}`),t.parentMsgId&&s.push(`parent_msg_id: ${t.parentMsgId}`),t.nodeIds&&t.nodeIds.length>0&&s.push(`node_ids: [${t.nodeIds.join(", ")}]`),s.push("---"),`${s.join(`
22
- `)}
23
- ${t.content.trim()}`}function V(t,e){let n=t.replace(/\\/g,"/"),r=e.replace(/\\/g,"/").replace(/\/+$/,"");return n.startsWith(`${r}/`)?n.slice(r.length+1):n}async function St(t,e){let n=ie(t,e),r=V(n,e);try{let o=Ke(t);await G__default.default.mkdir(ce__default.default.dirname(n),{recursive:!0});let c="";try{c=await G__default.default.readFile(n,"utf-8");}catch(i){if(i.code!=="ENOENT")throw i}let s=c.length>0&&!c.endsWith(`
24
- `)?`
25
- `:"";return await G__default.default.writeFile(n,`${c}${s}${o}
26
- `,"utf-8"),se.debug("Fact file synced (append)",{id:t.id,relPath:r}),{ok:!0,absPath:n,relPath:r}}catch(o){let c=o instanceof Error?o.message:String(o);return se.warn("Failed to write fact file (best-effort, non-blocking)",{id:t.id,absPath:n,error:c}),{ok:false,absPath:n,relPath:r,error:c}}}async function It(t,e){let n;t.filePath?n=`${e.replace(/\\/g,"/").replace(/\/+$/,"")}/${t.filePath.replace(/^\/+/,"")}`:n=ie({id:t.id,category:t.category,createdAt:t.createdAt,updatedAt:t.createdAt},e);let r=V(n,e);try{return await G__default.default.unlink(n),se.debug("Fact file deleted",{id:t.id,relPath:r}),{ok:!0,absPath:n,relPath:r}}catch(o){if(o.code==="ENOENT")return se.debug("Fact file not found (already deleted)",{id:t.id,relPath:r}),{ok:true,absPath:n,relPath:r};let s=o instanceof Error?o.message:String(o);return se.warn("Failed to delete fact file (best-effort, non-blocking)",{id:t.id,absPath:n,error:s}),{ok:false,absPath:n,relPath:r,error:s}}}var Y={resolvePath:ie,renderMarkdown:Ke,toRelPath:V,write:St,delete:It};var fe=utils.Log.create({service:"memory.service.remember"});async function Je(t,e){if(H(t),ge(t),!e.content||e.content.trim().length===0)throw new M("remember requires non-empty `content`","CONTENT_REQUIRED");if(!e.category)throw new M("remember requires `category`","CATEGORY_REQUIRED");fe.debug("remember invoked",{agentId:t.agentId,category:e.category,importance:e.importance??5,contentLength:e.content.length,skipDedup:e.skipDedup,extractGraph:e.extractGraph??true});let n=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await n.initialize();let r=new Date().toISOString(),o=Ct(),c=e.importance??5,s={entities:[],relations:[]},p=e.extractGraph!==!1&&chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().graphLlm?chunkJ5XF2W4Z_cjs.a.getGraphLlm():void 0;if(p)try{s=await Tt(p,e.content);}catch(y){fe.warn("LLM KG extraction failed (continuing without KG)",{agentId:t.agentId,error:y instanceof Error?y.message:String(y)});}let f=chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().embedding===!0,m=f?await Nt(n.getDb(),e.content):null,u=m?m.length:null,I=s.entities,v=s.relations,S=[],w=0;n.transaction(()=>{let y=new Map;for(let E of I){let _=n.query("SELECT id FROM nodes WHERE name = ? AND type = ? AND owner_agent_id = ? LIMIT 1",[E.name,E.type,t.agentId])[0];if(_){y.set(E.name,_.id);continue}let g=n.run("INSERT INTO nodes (name, type, properties, owner_agent_id, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)",[E.name,E.type,JSON.stringify({source:"llm_extracted",...E.properties??{}}),t.agentId,r,r]);g.lastID>0&&y.set(E.name,g.lastID);}for(let E of v){let _=y.get(E.source),g=y.get(E.target);!_||!g||_===g||n.run("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)",[_,g,E.relation,JSON.stringify({}),r]);}if(n.run(`INSERT INTO memory_facts
27
- (id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance,
28
- source, tags, node_ids, file_path, created_at, updated_at)
29
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[o,t.agentId,e.sessionId??null,e.msgId??null,e.parentMsgId??null,e.content,e.category,c,"session_self_write",e.tags?JSON.stringify(e.tags):null,JSON.stringify(Array.from(y.values())),null,r,r]),m&&u){let E=Ve(m);n.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[o,E]),w=1,n.query("SELECT value FROM meta WHERE key = ?",["vectorDims"])[0]||n.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["vectorDims",String(u)]);}n.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[o]),n.run("INSERT INTO memory_facts_fts (fact_id, agent_id, content, tags) VALUES (?, ?, ?, ?)",[o,t.agentId,e.content,e.tags?e.tags.join(" "):""]),S.push(...Array.from(y.values()));}),fe.info("Memory stored",{id:o,category:e.category,agentId:t.agentId,nodeCount:S.length,vectorsWritten:w,vectorDims:u??0,embeddingMode:f?"enabled":"fts_only",entitiesExtracted:I.length,relationsExtracted:v.length});let h={id:o,agentId:t.agentId,sessionId:e.sessionId,msgId:e.msgId,parentMsgId:e.parentMsgId,content:e.content,category:e.category,importance:c,source:"session_self_write",tags:e.tags,nodeIds:S.length>0?S:void 0,filePath:void 0,createdAt:r,updatedAt:r},b="",R=await Y.write(h,t.workspaceDir);if(R.ok){b=R.relPath,h.filePath=R.relPath;try{n.run("UPDATE memory_facts SET file_path = ? WHERE id = ?",[R.relPath,o]);}catch(y){fe.warn("Failed to update file_path column after sync",{id:o,error:y instanceof Error?y.message:String(y)});}}return {fact:h,filePath:b,deduplicated:!1,nodeIds:S,vectorsWritten:w,vectorDims:u??0,entitiesExtracted:I.length,relationsExtracted:v.length}}catch(r){throw r instanceof M?r:new M(`remember failed: ${r instanceof Error?r.message:String(r)}`,"INTERNAL",{cause:r instanceof Error?r.message:String(r)})}finally{n.close();}}function Ct(){let t=Date.now(),e=crypto.randomBytes(3).toString("hex");return `mem_${t}_${e}`}function Ve(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}function Ot(t){return crypto.createHash("sha256").update(t).digest("hex")}async function Nt(t,e){let n=Ot(e),r=t.prepare("SELECT embedding FROM embedding_cache WHERE content_hash = ?").get(n);if(r?.embedding)return new Float32Array(r.embedding.buffer,r.embedding.byteOffset,r.embedding.byteLength/4);let o=await chunkJ5XF2W4Z_cjs.a.embedText(e);if(!o||o.length===0)return null;let c=Ve(o);return t.prepare("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)").run(n,c),o}async function Tt(t,e){let n=await llm.GraphProvider.generateGraph({chunks:[e],model:t,includeRules:false});return {entities:n.entities,relations:n.relations}}var he=utils.Log.create({service:"memory.service.forget"}),kt=1e3;function At(t){let e=[];if(t.factId&&t.factId.trim().length>0&&e.push("factId"),t.category&&t.category.trim().length>0&&e.push("category"),(t.fromTime||t.toTime)&&e.push("timeRange"),e.length===0)throw new M("CONTENT_REQUIRED: forget requires one of: `factId`, `category`, or `fromTime`/`toTime`","CONTENT_REQUIRED");if(e.length>1)throw new M(`mutually exclusive: forget requires exactly one of factId/category/timeRange, got [${e.join(", ")}]`,"CONTENT_REQUIRED");return e[0]}function xt(t,e,n){let r=[n];switch(t){case "factId":return {where:"agent_id = ? AND id = ?",args:[...r,e.factId]};case "category":return {where:"agent_id = ? AND category = ?",args:[...r,e.category]};case "timeRange":{let o=["agent_id = ?"];return e.fromTime&&(o.push("created_at >= ?"),r.push(e.fromTime)),e.toTime&&(o.push("created_at <= ?"),r.push(e.toTime)),{where:o.join(" AND "),args:r}}}}function Lt(t,e,n,r){return t.query(`SELECT id, node_ids FROM memory_facts WHERE ${e} LIMIT ?`,[...n,r+1]).map(c=>c.id)}function Ft(t,e,n,r){if(n.length===0)return 0;let o=n.map(()=>"?").join(",");return t.query(`SELECT COUNT(*) as count FROM memory_facts WHERE agent_id = ? AND id != ? AND node_ids IS NOT NULL AND EXISTS (
30
- SELECT 1 FROM json_each(node_ids) AS je WHERE je.value IN (${o})
31
- )`,[r,e,...n])[0]?.count??0}function qt(t,e,n){let r,o,c="";return t.transaction(()=>{let s=t.query("SELECT node_ids, content, file_path, category, created_at FROM memory_facts WHERE id = ? AND agent_id = ?",[e,n])[0],i=[];if(s?.node_ids)try{i=JSON.parse(s.node_ids),Array.isArray(i)||(i=[]);}catch{i=[];}if(r=s?.file_path??void 0,o=s?.category,c=s?.created_at??"",t.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[e]),t.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[e,n]),i.length>0){let p=i.map(()=>"?").join(",");t.run(`DELETE FROM nodes WHERE id IN (${p}) AND NOT EXISTS (
32
- SELECT 1 FROM memory_facts WHERE node_ids IS NOT NULL AND EXISTS (
33
- SELECT 1 FROM json_each(node_ids) AS je WHERE je.value = nodes.id
34
- )
35
- )`,i);}}),{filePath:r,category:o,createdAt:c}}async function Ye(t,e){H(t),j(t,"forget");let n=At(e),r=e.maxDelete??kt,o=e.dryRun??false,c=e.force??false;he.debug("forget invoked",{agentId:t.agentId,mode:n,maxDelete:r,dryRun:o,force:c});let s=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await s.initialize();let{where:i,args:p}=xt(n,e,t.agentId),f=Lt(s,i,p,r),m=f.length>r;if(m&&!c)throw new oe(f.length,r);let u=m?f.slice(0,r):f;if(o)throw new ne(u.length);let I=[],v=[];for(let S of u){if(!c){let R=s.query("SELECT node_ids FROM memory_facts WHERE id = ? AND agent_id = ?",[S,t.agentId])[0],y=R?.node_ids?(()=>{try{let _=JSON.parse(R.node_ids);if(Array.isArray(_))return _.filter(g=>typeof g=="number")}catch{}return []})():[],E=Ft(s,S,y,t.agentId);if(E>0)throw new re(S,E)}let{filePath:w,category:h,createdAt:b}=qt(s,S,t.agentId);w&&h&&v.push({id:S,filePath:w,category:h,createdAt:b}),I.push(S);}he.info("forget complete",{agentId:t.agentId,mode:n,deletedCount:I.length,force:c,dryRun:o});for(let{id:S,filePath:w,category:h,createdAt:b}of v)await Y.delete({id:S,filePath:w,category:h,createdAt:b},t.workspaceDir).catch(R=>{he.warn("Fact file delete failed (best-effort)",{id:S,filePath:w,error:R instanceof Error?R.message:String(R)});});return {deletedCount:I.length,deletedIds:I,dryRun:o,truncatedCount:m?f.length-r:0}}catch(i){throw i instanceof M?i:new M(`forget failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var be=utils.Log.create({service:"memory.service.extract"}),Ht=50,Ee=500;async function Xe(t,e){if(H(t),!e.sessionId||e.sessionId.trim().length===0)throw new M("extract requires non-empty `sessionId`","SESSION_ID_REQUIRED");let n=e.lastN??Ht;if(n>Ee)throw new M(`extract lastN=${n} exceeds max=${Ee}`,"CONTENT_REQUIRED",{lastN:n,maxLastN:Ee});let r=e.sessionId,o=e.fromMessageId;be.debug("extract invoked",{agentId:t.agentId,sessionId:r,lastN:n,fromMessageId:o,writeToDisk:e.writeToDisk??true});let c=Date.now(),s=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await s.initialize();let i=s.query(`SELECT id, content, category, importance, 1.0 as score, created_at, node_ids
36
- FROM memory_facts
37
- WHERE agent_id = ? AND session_id = ?
38
- ORDER BY created_at ASC
39
- LIMIT ?`,[t.agentId,r,n]),p=o?i.filter(S=>S.id>o):i,f=new Set;for(let S of p)if(S.node_ids)try{let w=JSON.parse(S.node_ids);if(Array.isArray(w))for(let h of w)typeof h=="number"&&h>0&&f.add(h);}catch(w){be.warn("extract: invalid node_ids JSON",{factId:S.id,error:w instanceof Error?w.message:String(w)});}let m=Array.from(f),u=[],I=[];if(m.length>0){let S=m.map(()=>"?").join(","),w=s.query(`SELECT id, name, type FROM nodes WHERE id IN (${S})`,m),h=new Map;for(let y of w)h.set(y.id,y.name);u=w.map(y=>({id:y.id,name:y.name,type:y.type}));let b=s.query(`SELECT source, target, relation FROM edges WHERE source IN (${S}) OR target IN (${S})`,[...m,...m]),R=new Set;I=[];for(let y of b){let E=h.get(y.source),_=h.get(y.target);if(!E||!_)continue;let g=`${E}\0${y.relation}\0${_}`;R.has(g)||(R.add(g),I.push({source:E,target:_,relation:y.relation}));}}let v=Date.now()-c;return be.info("extract complete",{agentId:t.agentId,sessionId:r,factCount:p.length,nodeCount:u.length,relationCount:I.length,durationMs:v}),{extractedCount:p.length,factIds:p.map(S=>S.id),entities:u,relations:I,messageRange:{fromMessageId:p[0]?.id??"",toMessageId:p[p.length-1]?.id??""},durationMs:v}}catch(i){throw i instanceof M?i:new M(`extract failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var Se=utils.Log.create({service:"memory.service.consolidate"}),Wt=30;async function jt(t){let{createHash:e}=await import('crypto');return e("sha256").update(t).digest("hex")}async function Ze(t,e={}){let n=Date.now();H(t),j(t,"consolidate");let r=e.windowDays??Wt,o=e.dryRun??false;Se.debug("consolidate invoked",{agentId:t.agentId,windowDays:r,dryRun:o});let c=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await c.initialize();let s=c.query("SELECT id, content, category, importance, created_at FROM memory_facts WHERE agent_id = ? ORDER BY created_at DESC",[t.agentId]),i=new Map;for(let h of s){let b=await jt(h.content);i.has(b)||i.set(b,[]),i.get(b)?.push(h);}let p=0,f=[];for(let[,h]of i){if(h.length<=1)continue;let b=[...h].sort((E,_)=>E.importance!==_.importance?_.importance-E.importance:_.created_at.localeCompare(E.created_at)),R=b[0];if(!R)continue;let y=b.slice(1).map(E=>E.id);p+=y.length,f.push({keep:R,removeIds:y});}let m=new Date(Date.now()-r*24*60*60*1e3).toISOString(),u=c.query(`SELECT id, content, category, importance, created_at FROM memory_facts
40
- WHERE agent_id = ? AND created_at < ?
41
- ORDER BY created_at ASC`,[t.agentId,m]),I=0,v=0;if(o)I=0,v=p;else {let h=ce__default.default.join(t.workspaceDir,"archive");await G__default.default.mkdir(h,{recursive:!0});for(let{removeIds:b}of f){if(b.length===0)continue;let R=b.map(()=>"?").join(",");c.transaction(()=>{for(let y of b)c.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[y,t.agentId]);}),v+=b.length;}for(let b of u){let R=b.created_at.slice(0,7),y=ce__default.default.join(h,R,b.category);await G__default.default.mkdir(y,{recursive:!0});let E=ce__default.default.join(y,`${b.id}.md`);try{await G__default.default.writeFile(E,[`# ${b.id}`,"",`category: ${b.category}`,`importance: ${b.importance}`,`createdAt: ${b.created_at}`,"",b.content,""].join(`
42
- `),"utf-8"),c.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[b.id,t.agentId]),I++;}catch(_){Se.warn("consolidate: archive write failed",{factId:b.id,error:_ instanceof Error?_.message:String(_)});}}}let S=s.length,w=0;return Se.info("consolidate complete",{agentId:t.agentId,totalFacts:S,dedupedCount:p,compressedCount:w,archivedCount:I,skippedCount:v,dryRun:o,durationMs:Date.now()-n}),{totalFacts:S,dedupedCount:p,compressedCount:w,archivedCount:I,skippedCount:v,durationMs:Date.now()-n}}catch(s){throw s instanceof M?s:new M(`consolidate failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{c.close();}}var $=utils.Log.create({service:"memory.service.sync"}),Bt=30,Qt=".easbot/memory/active",et=".easbot/memory/archive";function Kt(t){return {id:t.id,agentId:t.agent_id,sessionId:t.session_id??void 0,msgId:t.msg_id??void 0,parentMsgId:t.parent_msg_id??void 0,content:t.content,category:t.category,importance:t.importance,source:t.source,tags:t.tags?JSON.parse(t.tags):void 0,nodeIds:t.node_ids?JSON.parse(t.node_ids):void 0,filePath:t.file_path??void 0,createdAt:t.created_at,updatedAt:t.updated_at}}async function Jt(t,e){let n=0,r=0,o=0,{where:c,params:s}=t.agentFilter(e.agentId),i=t.query(`SELECT id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance,
43
- source, tags, node_ids, file_path, created_at, updated_at
44
- FROM memory_facts ${c}
45
- ORDER BY created_at ASC`,s);for(let p of i){let f=Kt(p);if(p.file_path?.startsWith(`${et}/`)){r++;continue}let m=ie(f,e.workspaceDir);try{await G__default.default.access(m),r++;continue}catch(I){let v=I;if(v.code!=="ENOENT"){$.warn("sync generate: fs.access failed (non-ENOENT)",{factId:f.id,absPath:m,error:v.message}),o++;continue}}let u=await Y.write(f,e.workspaceDir);u.ok?n++:(o++,$.warn("sync generate: factFileSync.write failed",{factId:f.id,absPath:m,error:u.error}));}return $.debug("sync stage A complete",{agentId:e.agentId,generatedCount:n,skippedCount:r,failedGenerateCount:o}),{generatedCount:n,skippedCount:r,failedGenerateCount:o}}async function Vt(t,e,n,r){let o=n*24*60*60*1e3,c=Date.now(),s=utils.formatLocalISO(new Date(c-o)),i=[],p=ce__default.default.join(e.workspaceDir,Qt),f=await Yt(p);$.debug("sync stage B: scan active dir",{activeDir:p,fileCount:f.length,windowDays:n,threshold:s,dryRun:r});for(let m of f){let u=await Xt(m);if(!u){$.warn("sync stage B: skip unparseable file",{absPath:m});continue}let{firstCreatedAt:I,firstFactId:v}=u,S=new Date(I).getTime();if(Number.isNaN(S)){$.warn("sync stage B: skip invalid createdAt",{absPath:m,firstCreatedAt:I});continue}if(c-S<=o)continue;let w=Zt(m);if(!w){$.warn("sync stage B: cannot infer category from path",{absPath:m});continue}let h=I.slice(0,7),b=ce__default.default.join(e.workspaceDir,et,h,w),R=ce__default.default.basename(m),y=ce__default.default.join(b,R);if(r){i.push({source:m,target:y,firstCreatedAt:I,firstFactId:v});continue}try{await G__default.default.mkdir(b,{recursive:!0});try{await G__default.default.rename(m,y);}catch(g){let k=g;$.warn("sync stage B: fs.rename failed, falling back to copy+unlink",{absPath:m,targetPath:y,error:k.message}),await G__default.default.copyFile(m,y),await G__default.default.unlink(m);}let E=V(m,e.workspaceDir),_=V(y,e.workspaceDir);t.run(`UPDATE memory_facts SET file_path = ?
46
- WHERE agent_id = ? AND file_path = ?`,[_,e.agentId??"",E]),i.push({source:m,target:y,firstCreatedAt:I,firstFactId:v});}catch(E){$.warn("sync stage B: archive failed",{absPath:m,targetPath:y,error:E instanceof Error?E.message:String(E)});}}return $.debug("sync stage B complete",{agentId:e.agentId,archivedCount:i.length,dryRun:r}),{archivedCount:i.length,archiveThreshold:s,archivedRecords:i}}async function Yt(t){let e=[];try{await tt(t,e);}catch(n){let r=n;if(r.code==="ENOENT")return e;throw $.warn("sync: listActiveMdFiles failed",{activeDir:t,error:r.message}),new M(`sync: listActiveMdFiles failed: ${r.message}`,"INTERNAL",{cause:r.message})}return e}async function tt(t,e){let n=await G__default.default.readdir(t,{withFileTypes:true});for(let r of n){let o=ce__default.default.join(t,r.name);r.isDirectory()?await tt(o,e):r.isFile()&&r.name.endsWith(".md")&&e.push(o);}}async function Xt(t){let e;try{e=await G__default.default.readFile(t,"utf-8");}catch(s){if(s.code==="ENOENT")return null;throw s}if(!e.startsWith(`---
47
- `))return null;let n=e.indexOf(`
48
- ---
49
- `,4);if(n===-1)return null;let r=e.slice(4,n),o,c;for(let s of r.split(`
50
- `)){let i=s.trim();if(i.startsWith("created_at:")?o=i.slice(11).trim().replace(/^["']|["']$/g,""):i.startsWith("id:")&&(c=i.slice(3).trim().replace(/^["']|["']$/g,"")),o&&c)break}return !o||!c?null:{firstCreatedAt:o,firstFactId:c}}function Zt(t){let e=t.replace(/\\/g,"/").split("/"),n=e.findIndex(c=>c==="active");if(n===-1)return null;let r=e.slice(n+1);return r.length!==2||!r[1].endsWith(".md")?null:r[0]??null}async function rt(t,e={}){let n=Date.now();H(t),j(t,"sync");let r=e.windowDays??t.config?.archiveDays??Bt,o=e.dryRun??false;$.info("sync invoked",{agentId:t.agentId,windowDays:r,dryRun:o,workspaceDir:t.workspaceDir});let c=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await c.initialize();let s=await Jt(c,t),i=await Vt(c,t,r,o),p={generatedCount:s.generatedCount,skippedCount:s.skippedCount,failedGenerateCount:s.failedGenerateCount,archivedCount:i.archivedCount,archiveThreshold:i.archiveThreshold,archivedRecords:i.archivedRecords,windowDays:r,dryRun:o,durationMs:Date.now()-n};return $.info("sync complete",{agentId:t.agentId,...p}),p}catch(s){throw s instanceof M?s:new M(`sync failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{c.close();}}var nt=utils.Log.create({service:"memory.service.graph-query"});async function ot(t,e){let n=Date.now(),r=(t.agentId??"").trim()||"default",o=e.scope??"agent_only";if(!e.query||e.query.trim().length===0)throw new M("CONTENT_REQUIRED: graphQuery requires non-empty `query`","CONTENT_REQUIRED");ue(t,o,"graph_query");let c=e.depth??2,s=e.maxNodes??100,i=e.query,p=e.type,f=e.relation;nt.debug("graphQuery invoked",{agentId:r,query:i,type:p,depth:c,maxNodes:s,scope:o,remote:t.remote});let m=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await m.initialize();let u=new J(m.getDb()),I=i.includes("*")||i.includes("%")?i:`%${i}%`,v=await u.queryNodes({name:I,...p?{type:p}:{},agentId:r,scope:o,limit:s}),w=(i.includes("*")||i.includes("%")?v:v.filter(g=>g.name.toLowerCase().includes(i.toLowerCase())))[0]??null;if(!w)return {root:null,nodes:[],edges:[],truncated:!1,totalNodes:0,totalEdges:0,scope:o,durationMs:Date.now()-n};let h=await u.queryNeighbors(w.id,c,{agentId:r,scope:o,maxEdgesPerNode:20}),b=new Map;b.set(w.id,w);for(let g of h)b.set(g.id,{id:g.id,name:g.name,type:g.type,createdAt:g.createdAt,updatedAt:g.updatedAt});let R=[];for(let g of h)if(g.edges)for(let k of g.edges)f&&k.relation!==f||R.push(k);for(let g of R){if(!b.has(g.source)){let k=await u.queryNodes({ids:[g.source],agentId:r,scope:o});k[0]&&b.set(k[0].id,k[0]);}if(!b.has(g.target)){let k=await u.queryNodes({ids:[g.target],agentId:r,scope:o});k[0]&&b.set(k[0].id,k[0]);}}let y=Array.from(b.values()),E=y.length>s,_=E?y.slice(0,s):y;return nt.info("graphQuery complete",{agentId:r,rootId:w.id,nodeCount:_.length,edgeCount:R.length,truncated:E,durationMs:Date.now()-n}),{root:w,nodes:_,edges:R,truncated:E,totalNodes:y.length,totalEdges:R.length,scope:o,durationMs:Date.now()-n}}catch(u){throw u instanceof M?u:new M(`graphQuery failed: ${u instanceof Error?u.message:String(u)}`,"INTERNAL",{cause:u instanceof Error?u.message:String(u)})}finally{m.close();}}var U=utils.Log.create({service:"memory.service.init"});function Ie(t){return ce__default.default.join(t,".easbot","memory.json")}async function nr(t){try{let{Config:e}=await import('@easbot/llm'),n=await e.get(),r=o=>typeof o=="string"&&o.length>0?o:void 0;return {embeddingModel:r(n.embedding_model),graphModel:r(n.graph_model)}}catch{return {}}}function or(t,e={}){let n={version:1,schema_version:chunkEGWJG65Q_cjs.a,backend:"better-sqlite3",created_at:new Date().toISOString(),embedding_model:e.embeddingModel??null,graph_model:e.graphModel??null,entity_extraction_prompt:e.entityExtractionPrompt??null,relation_extraction_prompt:e.relationExtractionPrompt??null,archiveDays:e.archiveDays??30,shortTermMaxRounds:e.shortTermMaxRounds??20};fs.writeFileSync(t,JSON.stringify(n,null,2),"utf-8");}async function at(t,e={}){let n=Date.now();j(t,"init");let r=e.workspaceDir??t.workspaceDir,o=e.dbPath??t.dbPath;if(!r||r.trim().length===0)throw new M("init requires non-empty `workspaceDir` (ctx.workspaceDir or params.workspaceDir)","CONTENT_REQUIRED");if(!o||o.trim().length===0)throw new M("init requires non-empty `dbPath` (ctx.dbPath or params.dbPath)","CONTENT_REQUIRED");let c=t.agentId?.trim()??"",s=e.force??false;U.debug("init invoked",{agentId:c,workspaceDir:r,dbPath:o,force:s});let i=Ie(r);if(!s)try{if(await G__default.default.stat(i).then(()=>!0).catch(()=>!1))return U.info("init: idempotent skip (memory.json exists, no --force)",{workspaceDir:r,configPath:i}),{initialized:!1,dbPath:o,configPath:i,configCreated:!1,schemaVersion:chunkEGWJG65Q_cjs.a,workspaceDir:r,tablesCreated:0,migrationsApplied:0,durationMs:0}}catch{}try{await G__default.default.mkdir(ce__default.default.dirname(o),{recursive:!0}),await G__default.default.mkdir(ce__default.default.join(r,".easbot","memory","active"),{recursive:!0}),await G__default.default.mkdir(ce__default.default.join(r,"archive"),{recursive:!0}),await G__default.default.mkdir(ce__default.default.join(r,".easbot"),{recursive:!0});}catch(u){throw new M(`init: failed to create directories: ${u instanceof Error?u.message:String(u)}`,"INTERNAL",{cause:u instanceof Error?u.message:String(u)})}if(s)try{await G__default.default.rm(o,{force:!0});}catch(u){U.warn("init: force rm db failed (may not exist)",{dbPath:o,error:u instanceof Error?u.message:String(u)});}let p=await nr(),f=false;try{!await G__default.default.stat(i).then(()=>!0).catch(()=>!1)||s?(or(i,{embeddingModel:p.embeddingModel,graphModel:p.graphModel,archiveDays:t.config?.archiveDays,shortTermMaxRounds:t.config?.shortTermMaxRounds}),f=!0,U.info("init: memory.json written",{configPath:i,force:s,configCreated:f})):U.debug("init: memory.json already exists, skipping write",{configPath:i});}catch(u){U.warn("init: memory.json write failed (non-fatal)",{configPath:i,error:u instanceof Error?u.message:String(u)});}let m=new chunkEGWJG65Q_cjs.e(o);try{let u=await G__default.default.stat(o).then(()=>!0).catch(()=>!1);await m.initialize();let I=new Date().toISOString(),v=[["version","1.0.0"],["schemaVersion",String(chunkEGWJG65Q_cjs.a)],["createdAt",I],["defaultAgentId",c]];for(let[h,b]of v)try{m.run("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)",[h,b]);}catch(R){U.warn("init: meta insert failed",{key:h,error:R instanceof Error?R.message:String(R)});}let S=0;try{S=m.prepare("SELECT COUNT(*) as n FROM sqlite_master WHERE type IN ('table', 'index', 'trigger', 'view')").get()?.n??0;}catch(h){U.warn("init: tablesCreated count failed",{error:h instanceof Error?h.message:String(h)});}let w=0;try{w=m.prepare("SELECT id FROM schema_migrations").all().length;}catch(h){U.warn("init: migrationsApplied count failed",{error:h instanceof Error?h.message:String(h)});}return U.info("init complete",{agentId:c,workspaceDir:r,dbPath:o,configPath:i,configCreated:f,schemaVersion:chunkEGWJG65Q_cjs.a,durationMs:Date.now()-n}),{initialized:!0,dbPath:o,configPath:i,configCreated:f,schemaVersion:chunkEGWJG65Q_cjs.a,workspaceDir:r,tablesCreated:S,migrationsApplied:w,durationMs:Date.now()-n}}catch(u){throw new M(`init failed: ${u instanceof Error?u.message:String(u)}`,"INTERNAL",{cause:u instanceof Error?u.message:String(u)})}finally{m.close();}}var X=utils.Log.create({service:"memory.service.status"}),cr=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"],dr={};async function st(t,e={},n=dr){let r=t.agentId&&t.agentId.trim().length>0?t.agentId:void 0;if(X.debug("status invoked",{agentId:r??"<global>"}),!t.dbPath||t.dbPath.length===0)throw new M("`ctx.dbPath` is required","INTERNAL");let o={initialized:false,capabilities:{embedding:false,graphLlm:false}},c={},s={},i=0,p=0,f=0,m,u,I,v=false,S,w="uninitialized",h=false,b=false,R=false,y,E=cr.reduce((O,F)=>(O[F]=0,O),{}),_=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await _.initialize(),i=_.query(r!==void 0?"SELECT COUNT(*) as c FROM memory_facts WHERE agent_id = ?":"SELECT COUNT(*) as c FROM memory_facts WHERE agent_id IS NOT NULL",r!==void 0?[r]:[])[0]?.c??0,p=_.query(r!==void 0?"SELECT COUNT(*) AS c FROM nodes WHERE owner_agent_id = ? OR owner_agent_id IS NULL":"SELECT COUNT(*) AS c FROM nodes",r!==void 0?[r]:[])[0]?.c??0,f=_.query("SELECT COUNT(*) as c FROM edges")[0]?.c??0;let B=_.query(r!==void 0?"SELECT category, COUNT(*) as c FROM memory_facts WHERE agent_id = ? GROUP BY category":"SELECT category, COUNT(*) as c FROM memory_facts WHERE agent_id IS NOT NULL GROUP BY category",r!==void 0?[r]:[]);for(let D of B){let L=D.category;L in E&&(E[L]=D.c);}c.facts=i,c.nodes=p,c.edges=f;try{b=_.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]).length>0;}catch(D){X.debug("status: fts probe failed",{error:D instanceof Error?D.message:String(D)});}v=!!t.config?.embeddingLlm;try{h=_.query("SELECT name FROM pragma_table_info('nodes') WHERE name = ?",["owner_agent_id"]).length>0;}catch(D){X.debug("status: kg scope probe failed",{error:D instanceof Error?D.message:String(D)});}R=_.healthCheck();try{let D=_.query("SELECT key, value FROM meta");for(let L of D)s[L.key]=L.value;}catch(D){X.debug("status: meta read failed",{error:D instanceof Error?D.message:String(D)});}let d=s.schema_version,l=s.extraction_version,C=s.lastSyncAt??s.lastSync,P=s.embeddingDims;m=d&&Number.parseInt(d,10)||void 0,u=l&&Number.parseInt(l,10)||void 0,I=C,S=P&&Number.parseInt(P,10)||void 0,i>0&&(w="complete");try{y=_.query("SELECT value FROM meta WHERE key = ?",["backend"])[0]?.value??"better-sqlite3";}catch{y="better-sqlite3";}}catch(O){if(O instanceof M)throw O;X.warn("status: db phase failed; returning partial result",{dbPath:t.dbPath,error:O instanceof Error?O.message:String(O)}),y="unknown",R=false;}finally{_.close();}if(!n.skipLlm&&chunkJ5XF2W4Z_cjs.a.isInitialized()){let F=chunkJ5XF2W4Z_cjs.a.capabilities();o.initialized=true,o.capabilities={embedding:F.embedding===true,graphLlm:F.graphLlm===true},o.embeddingModel=o.capabilities.embedding?"configured":void 0,o.graphModel=o.capabilities.graphLlm?"configured":void 0;}if(!n.skipEmbeddingProbe&&!n.skipLlm&&o.initialized&&o.capabilities.embedding)try{let O=chunkJ5XF2W4Z_cjs.a.getEmbeddingLlm?.();if(O){let F=await llm.probeEmbeddingDims(O,{timeoutMs:5e3});if(typeof F=="number"){S=F,s.embeddingDims=String(F);try{let W=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await W.initialize();let B=W.getDb();llm.syncMeta(B,[["embeddingDims",String(F)]]);}finally{W.close();}}catch{}}}}catch{}let g;return R?w==="uninitialized"&&(g="Run `easbot memory remember <content>` to add the first fact."):g="Run `easbot memory init` to initialize the database.",R&&(w??"uninitialized")==="failed"&&(R=false),X.info("status complete",{dbPath:t.dbPath,agentId:r??"<global>",factsCount:i,nodesCount:p,edgesCount:f,healthy:R}),{package:"memory",agentId:r,dbPath:t.dbPath,configPath:Ie(t.workspaceDir),configExists:true,schemaVersion:m,extractionVersion:u,lastSyncAt:I,indexState:w,vectorEnabled:v,embeddingDims:S,llm:o,backend:y,counts:c,meta:s,recommendation:g,healthy:R,factsByCategory:E,kgScopeEnabled:h,factsCount:i,nodesCount:p,edgesCount:f,ftsAvailable:b}}var pr=utils.Log.create({service:"memory.service.doctor"}),_e=100*1024*1024,it=100*1024*1024,fr={};function N(t,e,n,r,o){return {code:t.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),severity:e,name:t,message:n,details:o,durationMs:r,passed:e!=="error"}}async function ct(t,e={},n=fr){if(pr.debug("doctor invoked",{agentId:t.agentId}),!t.dbPath||t.dbPath.length===0)throw new Error("`ctx.dbPath` is required");let r=[],o=[],c=Date.now(),s=null,i=false,p=Date.now();try{s=new chunkEGWJG65Q_cjs.e(t.dbPath),await s.initialize(),i=!0;let d=s.healthCheck(),l=N("database",d?"ok":"error",d?"database connected and writable":"database unhealthy",Date.now()-p,{dbPath:t.dbPath});r.push(l),o.push({name:l.name,passed:l.severity!=="error",message:l.message,details:l.details,severity:l.severity});}catch(d){let l=N("database","error",`database connection failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-p,{dbPath:t.dbPath});r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"error"});}let f=Date.now();if(i&&s)try{let d=s.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]),l=d.length>0,C=N("fts",l?"ok":"warn",l?"FTS5 index available":"FTS5 index not found",Date.now()-f,l?{table:d[0]?.name}:void 0);r.push(C),o.push({name:C.name,passed:C.severity!=="error",message:C.message,details:C.details,severity:C.severity});}catch(d){let l=N("fts","error",`fts probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-f);r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"error"});}else {let d=N("fts","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let m=Date.now(),u=!!t.config?.embeddingLlm,I=N("vector","ok",u?"embedding model available":"no embedding model configured (FTS-only mode, recall still functional)",Date.now()-m,{mode:u?"hybrid":"fts_only",model:u?"configured":"missing"});r.push(I),o.push({name:I.name,passed:true,message:I.message,details:I.details,severity:"ok"});let v=Date.now();if(i&&s)try{let d=["memory_facts","nodes","edges","meta"],l=s.query("SELECT name FROM sqlite_master WHERE type = ?",["table"]),C=new Set(l.map(L=>L.name)),P=d.filter(L=>!C.has(L)),D=N("schema",P.length===0?"ok":"error",P.length===0?`schema complete (${d.length} tables)`:`missing tables: ${P.join(", ")}`,Date.now()-v,{required:d,existing:Array.from(C)});r.push(D),o.push({name:D.name,passed:D.severity!=="error",message:D.message,details:D.details,severity:D.severity});}catch(d){let l=N("schema","error",`schema probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-v);r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"error"});}else {let d=N("schema","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let S=Date.now();try{let d=`${t.dbPath}-wal`,l=`${t.dbPath}-shm`,C=0,P=0;try{C=(await G__default.default.stat(d)).size;}catch{C=0;}try{P=(await G__default.default.stat(l)).size;}catch{P=0;}let D=C+P,L=D<=it,q=N("lock",L?"ok":"warn",L?`no lock contention (wal+shm ${(D/1024).toFixed(1)} KB)`:`WAL/SHM files unusually large (${(D/1024/1024).toFixed(1)} MB > ${(it/1024/1024).toFixed(0)} MB threshold)`,Date.now()-S,{walBytes:C,shmBytes:P});r.push(q),o.push({name:q.name,passed:q.severity!=="error",message:q.message,details:q.details,severity:q.severity});}catch(d){let l=N("lock","error",`lock probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-S);r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"error"});}let w=Date.now();try{let d=ce__default.default.dirname(t.dbPath),l=await G__default.default.statfs(d),C=typeof l.bsize=="bigint"?Number(l.bsize)*l.bavail:l.bsize*l.bavail,P=C>=_e,D=N("disk_space",P?"ok":"error",P?`sufficient disk space (${(C/1024/1024).toFixed(1)} MB available)`:`low disk space (${(C/1024/1024).toFixed(1)} MB < ${(_e/1024/1024).toFixed(0)} MB threshold)`,Date.now()-w,{availableBytes:C,threshold:_e});r.push(D),o.push({name:D.name,passed:D.severity!=="error",message:D.message,details:D.details,severity:D.severity});}catch(d){let l=N("disk_space","error",`disk_space probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-w);r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"error"});}let h=Date.now();if(i&&s)try{let d=s.agentFilter(t.agentId),l=s.query(`SELECT id, node_ids FROM memory_facts ${d.where} ${d.where?"AND":"WHERE"} node_ids IS NOT NULL`,d.params),C=[];for(let D of l)try{let L=JSON.parse(D.node_ids);if(!Array.isArray(L))continue;for(let q of L){if(typeof q!="number")continue;if((s.query("SELECT COUNT(*) as c FROM nodes WHERE id = ?",[q])[0]?.c??0)===0){C.push(`${D.id}->${q}`);break}}}catch{}let P=N("orphan",C.length===0?"ok":"warn",C.length===0?"no orphan KG references":`${C.length} orphan references: ${C.slice(0,5).join(", ")}${C.length>5?", ...":""}`,Date.now()-h,{count:C.length});r.push(P),o.push({name:P.name,passed:P.severity!=="error",message:P.message,details:P.details,severity:P.severity});}catch(d){let l=N("orphan","warn",`orphan probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-h);r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"warn"});}else {let d=N("orphan","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let b=Date.now(),R={"better-sqlite3":false,"node:sqlite":false,"@tursodatabase/database":false};try{let d=module$1.createRequire(chunkNVGACA7W_cjs.b);try{d.resolve("better-sqlite3"),R["better-sqlite3"]=!0;}catch{}R["node:sqlite"]=typeof process.versions.sqlite=="string";try{d.resolve("@tursodatabase/database"),R["@tursodatabase/database"]=!0;}catch{}}catch{}let y=R["better-sqlite3"]||R["node:sqlite"],E=N("backend",y?"ok":"error",y?`SQLite backend available (better-sqlite3: ${R["better-sqlite3"]}, node:sqlite: ${R["node:sqlite"]})`:"no SQLite backend available (install better-sqlite3 or use Node 22.5+)",Date.now()-b,R);r.push(E),o.push({name:E.name,passed:E.severity!=="error",message:E.message,details:E.details,severity:E.severity});let _=Date.now();if(i&&s)try{let d=s.query("SELECT COUNT(*) as c FROM embedding_cache")[0],l=s.agentFilter(t.agentId),C=s.query(`SELECT COUNT(*) as c FROM memory_facts ${l.where}`,l.params)[0],P=d?.c??0,D=C?.c??0,L=Math.max(0,P-D),q=L>0,Z=N("embedding_cache_unused","info",q?`by design: ${L} embedding_cache rows remain after fact deletion (cache is global content-hash dedup; forget intentionally doesn't cascade clear cache to preserve same-content hit rate)`:"embedding_cache in sync with memory_facts (no unused rows)",Date.now()-_,{cacheCount:P,factsCount:D,unused:L,policy:"global_content_hash_dedup"});r.push(Z),o.push({name:Z.name,passed:!q,message:Z.message,details:Z.details,severity:"info"});}catch(d){let l=N("embedding_cache_unused","info",`embedding_cache_unused probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-_);r.push(l),o.push({name:l.name,passed:true,message:l.message,severity:"info"});}else {let d=N("embedding_cache_unused","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let g=Date.now(),k;if(i&&s)try{let d=s.query("SELECT value FROM meta WHERE key = ?",["embeddingDims"]);k=d[0]?.value&&Number.parseInt(d[0].value,10)||void 0;}catch{}let O;if(n.skipLlm||!chunkJ5XF2W4Z_cjs.a.isInitialized()||!chunkJ5XF2W4Z_cjs.a.capabilities().embedding)O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","llm not initialized; probe skipped",Date.now()-g);else if(n.skipEmbeddingProbe)O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe skipped (--skip-embedding-probe)",Date.now()-g);else try{let d=chunkJ5XF2W4Z_cjs.a.getEmbeddingLlm?.();if(!d)O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","embedding llm not exposed; probe skipped",Date.now()-g);else {let l=await llm.probeEmbeddingDims(d,{timeoutMs:5e3});typeof l!="number"?O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe failed (network / model error)",Date.now()-g):k===void 0?O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe=${l}, meta missing \u2014 next status will sync`,Date.now()-g):l!==k?O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"warn",`probe=${l}, meta=${k} \u2014 mismatch`,Date.now()-g,{probe:l,meta:k}):O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"ok",`probe=${l}, meta=${k} \u2014 consistent`,Date.now()-g);}}catch(d){O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe threw: ${d instanceof Error?d.message:String(d)}`,Date.now()-g);}r.push({...O,details:O.details??void 0,passed:O.severity!=="error"}),o.push({name:O.name,passed:O.severity!=="error",message:O.message,details:O.details??void 0,severity:O.severity});let F;if(i&&s){let d=Date.now();try{let{issues:l,stats:C}=s.checkIntegrity();F=C;for(let P of l)r.push(N("integrity_stats",P.severity,P.message,0,{source:"database.checkIntegrity"}));}catch(l){r.push(N("integrity_stats","warn",`db integrity check failed: ${l instanceof Error?l.message:String(l)}`,Date.now()-d));}}let W=!r.some(d=>d.severity==="error");s&&s.close();let B=Date.now()-c;return {healthy:W,checks:r,legacyChecks:o,durationMs:B,integrityStats:F,backendAvailable:R}}var De={name:"recall",scope:"read",schema:qe,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Query memory via hybrid search (FTS + vector); returns ranked facts.",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("recall: agentId is required");return Fe({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var ve={name:"remember",scope:"write",schema:$e,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Persist a new self-memory fact; auto-extract entities into KG.",readOnlyHint:false,destructiveHint:false,idempotentHint:false},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("remember: agentId is required");return Je({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var Ce={name:"forget",scope:"write",schema:He,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Delete memory facts by id / category / time range; supports dryRun.",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("forget: agentId is required");return Ye({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var Oe={name:"extract",scope:"write",schema:Ue,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Extract facts from a session (server-side pulls messages by lastN).",readOnlyHint:false,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("extract: agentId is required");return Xe({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var Ne={name:"consolidate",scope:"admin",schema:We,annotations:{localOnly:true,requiresAgentId:true,defaultDescription:"Run consolidation pipeline: dedup \u2192 archive.",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.isTrustedLocal)throw new Error("consolidate: only trusted local process can invoke this op");if(!e.agentId?.trim())throw new Error("consolidate: agentId is required");return Ze({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},n)}};var Te={name:"sync",scope:"admin",schema:Qe,annotations:{localOnly:true,requiresAgentId:true,defaultDescription:"Sync memory facts to .md files (idempotent skip on existing) and archive expired active files (default 30 days)",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.isTrustedLocal)throw new Error("sync: only trusted local process can invoke this op");if(!e.agentId?.trim())throw new Error("sync: agentId is required");return rt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},n)}};var Pe={name:"graph_query",scope:"read",schema:je,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Query KG nodes / edges / neighbors with scope filtering.",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t,r=e.agentId?.trim()||"default";return ot({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:r},n)}};var ke={name:"status",scope:"read",schema:Ge,annotations:{localOnly:false,requiresAgentId:false,defaultDescription:"Memory system status (factsCount / nodesCount / edgesCount / fts / vector).",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t??{};return st({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var Ae={name:"doctor",scope:"admin",schema:ze,annotations:{localOnly:true,requiresAgentId:false,defaultDescription:"Run 7 health checks (database / fts / vector / schema / lock / disk_space / orphan).",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t??{};if(!e.isTrustedLocal)throw new Error("doctor: only trusted local process can invoke this op");return ct({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},n)}};var xe={name:"init",scope:"admin",schema:Be,annotations:{localOnly:true,requiresAgentId:false,defaultDescription:"Initialize memory workspace (dirs + db schema + meta).",readOnlyHint:false,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{if(!e.isTrustedLocal)throw new Error("init: only trusted local process can invoke this op");let n=t??{};return at({workspaceDir:n.workspaceDir??e.workspaceDir??"",rootDir:n.workspaceDir??e.workspaceDir??"",dbPath:n.dbPath??e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId??""},n)}};var dt={[De.name]:De,[ve.name]:ve,[Ce.name]:Ce,[Oe.name]:Oe,[Ne.name]:Ne,[Te.name]:Te,[Pe.name]:Pe,[ke.name]:ke,[Ae.name]:Ae,[xe.name]:xe},yr=Object.values(dt);function hr(t,e,n){if(t.annotations.localOnly&&!e.isTrustedLocal)throw new Error(`MEMORY:executeOp: op "${n}" is localOnly; non-trusted caller rejected`);if(t.annotations.requiresAgentId){let r=e.agentId?.trim()??"";if(r.length===0)throw new Error(`MEMORY:executeOp: op "${n}" requires agentId`);e.agentId=r;}}async function Ra(t,e,n){let r=dt[t];if(!r)throw new Error(`executeOp: unknown op "${t}"; available: ${yr.map(c=>c.name).join(", ")}`);return hr(r,n,t),await r.handler(e,n)}function wr(t){let e=t.dbPath??"";return {workspaceDir:t.workspaceDir??"",database:{path:e},embeddingLlm:chunkJ5XF2W4Z_cjs.a.getEmbeddingLlm(),graphLlm:chunkJ5XF2W4Z_cjs.a.getGraphLlm(),search:types.DEFAULT_SEARCH_CONFIG,indexer:{batchSize:20,ignorePatterns:[],incremental:true},archiveDays:30,shortTermMaxRounds:20}}function Na(t,e,n={}){let r=chunkCPRDIUQ4_cjs.j(e),o=utils.Locale.resolveLocaleLang(n.locale);return {agentId:t,dbPath:r,workspaceDir:e,rootDir:e,config:wr({dbPath:r,workspaceDir:e}),isTrustedLocal:true,locale:o,remote:false,...n}}exports.a=J;exports.b=Fe;exports.c=qe;exports.d=$e;exports.e=He;exports.f=Ue;exports.g=We;exports.h=je;exports.i=Be;exports.j=Qe;exports.k=Je;exports.l=Ye;exports.m=Xe;exports.n=Ze;exports.o=rt;exports.p=ot;exports.q=at;exports.r=st;exports.s=ct;exports.t=dt;exports.u=yr;exports.v=Ra;exports.w=wr;exports.x=Na;
@@ -1 +0,0 @@
1
- 'use strict';var chunkAYGZUNFR_cjs=require('./chunk-AYGZUNFR.cjs');require('./chunk-CPRDIUQ4.cjs'),require('./chunk-NVGACA7W.cjs');Object.defineProperty(exports,"COMMANDS_HELP",{enumerable:true,get:function(){return chunkAYGZUNFR_cjs.a}});Object.defineProperty(exports,"handleMemoryCli",{enumerable:true,get:function(){return chunkAYGZUNFR_cjs.d}});Object.defineProperty(exports,"renderBanner",{enumerable:true,get:function(){return chunkAYGZUNFR_cjs.b}});Object.defineProperty(exports,"renderHelp",{enumerable:true,get:function(){return chunkAYGZUNFR_cjs.c}});
@@ -1 +0,0 @@
1
- export{a as COMMANDS_HELP,d as handleMemoryCli,b as renderBanner,c as renderHelp}from'./chunk-TIZCWDJ7.mjs';import'./chunk-WDVDYZ25.mjs';import'./chunk-HQBRVVXS.mjs';
@@ -1,2 +0,0 @@
1
- import {b,c}from'./chunk-QYBWHFOX.mjs';import'./chunk-SWYQLQ7Z.mjs';import {v,x}from'./chunk-UF2Y2Q4L.mjs';import'./chunk-JDPZ5U53.mjs';import'./chunk-WDVDYZ25.mjs';import'./chunk-6CQMBEIQ.mjs';import'./chunk-HQBRVVXS.mjs';async function C(t){let n=t.agentId?.trim()||"default",o=t.workspaceDir??process.cwd();return v("consolidate",{windowDays:t.windowDays??30,dryRun:false},x(n,o))}function f(t){let n=t;return [b("consolidate",{},"Consolidation complete ({{totalFacts}} total / deduped {{dedupedCount}} / archived {{archivedCount}}):"),c("consolidate",{totalFacts:String(n.totalFacts),dedupedCount:String(n.dedupedCount),archivedCount:String(n.archivedCount)}," - total: {{totalFacts}}, deduped: {{dedupedCount}}, archived: {{archivedCount}}"),` - skipped: ${n.skippedCount}, duration: ${n.durationMs}ms`].join(`
2
- `)}function w(t){let n={};for(let o=0;o<t.length;o++){let e=t[o];if(e===void 0)continue;let i=t[o+1];e==="--agent"?(n.agentId=i,o++):e==="--window-days"?(n.windowDays=Number(i),o++):e==="--json"?n.json=true:(e==="--help"||e==="-h")&&(n.help=true);}return n}export{f as formatConsolidateText,w as parseConsolidateOptions,C as runConsolidate};
@@ -1 +0,0 @@
1
- 'use strict';var chunkZ5E4HBGK_cjs=require('./chunk-Z5E4HBGK.cjs');require('./chunk-EGWJG65Q.cjs'),require('./chunk-CPRDIUQ4.cjs'),require('./chunk-J5XF2W4Z.cjs'),require('./chunk-NVGACA7W.cjs');async function a(o){let r=o.agentId,t=o.workspaceDir??process.cwd();return chunkZ5E4HBGK_cjs.v("doctor",{repair:o.repair??false},chunkZ5E4HBGK_cjs.x(r,t))}function u(o){return ""}function f(o){let r={};for(let t=0;t<o.length;t++){let e=o[t];e!==void 0&&(e==="--repair"?r.repair=true:e==="--json"?r.json=true:(e==="--help"||e==="-h")&&(r.help=true));}return r}exports.formatDoctorText=u;exports.parseDoctorOptions=f;exports.runDoctor=a;
@@ -1,2 +0,0 @@
1
- import {b,c}from'./chunk-QYBWHFOX.mjs';import'./chunk-SWYQLQ7Z.mjs';import {v,x as x$1}from'./chunk-UF2Y2Q4L.mjs';import'./chunk-JDPZ5U53.mjs';import'./chunk-WDVDYZ25.mjs';import'./chunk-6CQMBEIQ.mjs';import'./chunk-HQBRVVXS.mjs';async function m(r){if(!r.sessionId?.trim())throw new Error("extract: --session is required");let e=r.agentId?.trim()||"default",t=r.workspaceDir??process.cwd();return v("extract",{sessionId:r.sessionId,lastN:r.lastN??10,fromMessageId:r.fromMessageId},x$1(e,t))}function p(r){let e=r,t=[b("extract",{extractedCount:e.extractedCount},"Extracted {{extractedCount}} fact(s) from {{fromMessageId}}..{{toMessageId}}")];for(let s of e.factIds)t.push(c("extract",{id:s}," - {{id}}"));if(e.entities&&e.entities.length>0){t.push(""),t.push("entities:");for(let s of e.entities)t.push(` - ${s.name} (${s.type})`);}if(e.relations&&e.relations.length>0){t.push(""),t.push("relations:");for(let s of e.relations)t.push(` - ${s.source} --${s.relation}--> ${s.target}`);}return t.join(`
2
- `)}function x(r){let e={};for(let t=0;t<r.length;t++){let s=r[t];if(s===void 0)continue;let n=r[t+1];s==="--agent"?(e.agentId=n,t++):s==="--session"?(e.sessionId=n,t++):s==="--last-n"?(e.lastN=Number(n),t++):s==="--from-msg"?(e.fromMessageId=n,t++):s==="--json"?e.json=true:(s==="--help"||s==="-h")&&(e.help=true);}return e}export{p as formatExtractText,x as parseExtractOptions,m as runExtract};
@@ -1 +0,0 @@
1
- import {v,x as x$1}from'./chunk-UF2Y2Q4L.mjs';import'./chunk-JDPZ5U53.mjs';import {j}from'./chunk-WDVDYZ25.mjs';import'./chunk-6CQMBEIQ.mjs';import'./chunk-HQBRVVXS.mjs';async function m(t){let e=t.workspaceDir?.trim()||t.ctxWorkspaceDir?.trim()||process.cwd(),i=t.agentId??"",n=t.ctxWorkspaceDir?.trim()||e;return v("init",{workspaceDir:e,dbPath:j(n),force:t.force??false},x$1(i,n))}function x(t){let e={},i=[];for(let n=0;n<t.length;n++){let r=t[n];if(r===void 0)continue;let p=t[n+1];r==="--agent"?(e.agentId=p,n++):r==="--force"?e.force=true:r==="--json"?e.json=true:r==="--help"||r==="-h"?e.help=true:r.startsWith("-")||i.push(r);}return e.workspaceDir=i[0],e}export{x as parseInitOptions,m as runInit};
@@ -1,2 +0,0 @@
1
- import {a}from'./chunk-SWYQLQ7Z.mjs';import {v,x}from'./chunk-UF2Y2Q4L.mjs';import'./chunk-JDPZ5U53.mjs';import'./chunk-WDVDYZ25.mjs';import'./chunk-6CQMBEIQ.mjs';import'./chunk-HQBRVVXS.mjs';async function f(n){if(!n.query?.trim())throw new Error("recall: --query is required");let e=n.agentId?.trim()||"default",t=n.workspaceDir??process.cwd();return v("recall",{query:n.query,maxResults:n.limit??10,category:n.category,minImportance:n.minImportance},x(e,t))}function g(n){let e=n;if(e.total===0)return a("memory.recall.empty",{fallback:"(no facts)"});let t=[a("memory.recall.summary",{vars:{total:e.total},fallback:`Found ${e.total} fact(s):`})];for(let r of e.hits)t.push(a("memory.recall.item",{vars:{id:r.memoryId,category:r.category,importance:String(r.importance),score:r.score.toFixed(3),content:r.snippet},fallback:" - {{id}} [{{category}}/imp={{importance}}/score={{score}}] {{content}}"}));return t.join(`
2
- `)}function y(n){let e={};for(let t=0;t<n.length;t++){let r=n[t];if(r===void 0)continue;let o=n[t+1];r==="--agent"?(e.agentId=o,t++):r==="--query"?(e.query=o,t++):r==="--limit"?(e.limit=Number(o),t++):r==="--category"?(e.category=o,t++):r==="--min-importance"?(e.minImportance=Number(o),t++):r==="--json"?e.json=true:(r==="--help"||r==="-h")&&(e.help=true);}return e}export{g as formatRecallText,y as parseRecallOptions,f as runRecall};
@@ -1 +0,0 @@
1
- 'use strict';var chunkZ5E4HBGK_cjs=require('./chunk-Z5E4HBGK.cjs');require('./chunk-EGWJG65Q.cjs'),require('./chunk-CPRDIUQ4.cjs'),require('./chunk-J5XF2W4Z.cjs'),require('./chunk-NVGACA7W.cjs');async function c(t){let n=t.agentId,e=t.workspaceDir??process.cwd();return chunkZ5E4HBGK_cjs.v("status",{agentId:n},chunkZ5E4HBGK_cjs.x(n,e))}function f(t){return ""}function l(t){let n={};for(let e=0;e<t.length;e++){let o=t[e];if(o===void 0)continue;let i=t[e+1];o==="--agent"?(n.agentId=i,e++):o==="--json"?n.json=true:(o==="--help"||o==="-h")&&(n.help=true);}return n}exports.formatStatusText=f;exports.parseStatusOptions=l;exports.runStatus=c;
@@ -1 +0,0 @@
1
- export{b as MemoryStdioServer}from'./chunk-N5YRDTEH.mjs';import'./chunk-UF2Y2Q4L.mjs';import'./chunk-JDPZ5U53.mjs';import'./chunk-WDVDYZ25.mjs';import'./chunk-6CQMBEIQ.mjs';import'./chunk-HQBRVVXS.mjs';
@@ -1 +0,0 @@
1
- 'use strict';var chunkS6S35LDL_cjs=require('./chunk-S6S35LDL.cjs');require('./chunk-Z5E4HBGK.cjs'),require('./chunk-EGWJG65Q.cjs'),require('./chunk-CPRDIUQ4.cjs'),require('./chunk-J5XF2W4Z.cjs'),require('./chunk-NVGACA7W.cjs');Object.defineProperty(exports,"MemoryStdioServer",{enumerable:true,get:function(){return chunkS6S35LDL_cjs.b}});