@easbot/memory 0.3.22 → 0.3.24

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 (56) hide show
  1. package/README.en.md +2 -2
  2. package/README.md +19 -9
  3. package/dist/chunks/{chunk-ECTHWVFQ.cjs → chunk-46Y7MLBE.cjs} +1 -1
  4. package/dist/chunks/chunk-5VZKEZI4.cjs +67 -0
  5. package/dist/chunks/chunk-C3Z455VR.mjs +67 -0
  6. package/dist/chunks/{chunk-PJGILQSZ.mjs → chunk-FY4ILCIM.mjs} +5 -6
  7. package/dist/chunks/chunk-GL5U3MRI.mjs +64 -0
  8. package/dist/chunks/{chunk-EK34SXJ7.cjs → chunk-LYBUZDJK.cjs} +5 -6
  9. package/dist/chunks/chunk-MPGIP3IF.cjs +64 -0
  10. package/dist/chunks/{chunk-5DCNLEAC.mjs → chunk-PGJB2U24.mjs} +1 -1
  11. package/dist/chunks/cli-handler-KTFW5CCH.mjs +1 -0
  12. package/dist/chunks/cli-handler-Y43WWXOO.cjs +1 -0
  13. package/dist/chunks/consolidate-VGPUQRPU.mjs +2 -0
  14. package/dist/chunks/{consolidate-GQ5KCVWW.cjs → consolidate-X52RRH2C.cjs} +1 -1
  15. package/dist/chunks/doctor-RNI5F6GO.mjs +1 -0
  16. package/dist/chunks/doctor-SJY3K3DV.cjs +1 -0
  17. package/dist/chunks/{extract-LUBUHISD.mjs → extract-ANENWMHZ.mjs} +1 -1
  18. package/dist/chunks/{extract-HBIYSJRI.cjs → extract-L2V2RMDQ.cjs} +1 -1
  19. package/dist/chunks/{forget-MSXKORPW.mjs → forget-QNG6GELC.mjs} +1 -1
  20. package/dist/chunks/{forget-C7DNK4TJ.cjs → forget-SSGVAE5Y.cjs} +1 -1
  21. package/dist/chunks/graph-KNLZRAPI.mjs +3 -0
  22. package/dist/chunks/graph-WIKKSBLC.cjs +3 -0
  23. package/dist/chunks/{init-GVYXEMZ3.mjs → init-2UNKNWR5.mjs} +1 -1
  24. package/dist/chunks/{init-AL4IZIBJ.cjs → init-UNDHFDAC.cjs} +1 -1
  25. package/dist/chunks/{mcp-NAE5FPNQ.cjs → mcp-PRR2RYOP.cjs} +1 -1
  26. package/dist/chunks/{mcp-OZFKMFEM.mjs → mcp-RMLMXPZ7.mjs} +1 -1
  27. package/dist/chunks/recall-7TPMD7ZE.mjs +2 -0
  28. package/dist/chunks/{recall-V7XEE6MG.cjs → recall-M2EWX25U.cjs} +1 -1
  29. package/dist/chunks/{remember-5H5A6O5I.cjs → remember-BXVUUY5M.cjs} +1 -1
  30. package/dist/chunks/{remember-XBPCHY4Q.mjs → remember-H5CYMLG5.mjs} +1 -1
  31. package/dist/chunks/{status-ZX25EAH7.cjs → status-A2JC6NFH.cjs} +1 -1
  32. package/dist/chunks/{status-SKO36F6J.mjs → status-MJFDNSPW.mjs} +1 -1
  33. package/dist/chunks/stdio-server-43QC3XIS.mjs +1 -0
  34. package/dist/chunks/{stdio-server-NHPVPW5A.cjs → stdio-server-SXDIW3RQ.cjs} +1 -1
  35. package/dist/chunks/{sync-3L57TMXR.cjs → sync-3RWIZYR6.cjs} +1 -1
  36. package/dist/chunks/{sync-L5XS442K.mjs → sync-GPRNZLZA.mjs} +1 -1
  37. package/dist/cli.cjs +1 -1
  38. package/dist/cli.mjs +1 -1
  39. package/dist/index.cjs +4 -4
  40. package/dist/index.d.cts +7 -2
  41. package/dist/index.d.ts +7 -2
  42. package/dist/index.mjs +4 -4
  43. package/package.json +10 -10
  44. package/dist/chunks/chunk-WDGBZHIS.mjs +0 -66
  45. package/dist/chunks/chunk-YAKGP77O.cjs +0 -65
  46. package/dist/chunks/chunk-YYCHHBMU.cjs +0 -66
  47. package/dist/chunks/chunk-ZIFDM4GO.mjs +0 -65
  48. package/dist/chunks/cli-handler-T3G2REK3.mjs +0 -1
  49. package/dist/chunks/cli-handler-YQEIJ6L2.cjs +0 -1
  50. package/dist/chunks/consolidate-FWRCKNBO.mjs +0 -2
  51. package/dist/chunks/doctor-SYBFGZAM.cjs +0 -1
  52. package/dist/chunks/doctor-Z4MRWUSA.mjs +0 -1
  53. package/dist/chunks/graph-HKBJTVVV.mjs +0 -3
  54. package/dist/chunks/graph-ONZARVEF.cjs +0 -3
  55. package/dist/chunks/recall-W4WBZG5W.mjs +0 -2
  56. package/dist/chunks/stdio-server-EORG6GVP.mjs +0 -1
@@ -0,0 +1,67 @@
1
+ import {e,a as a$2}from'./chunk-FY4ILCIM.mjs';import {j}from'./chunk-WDVDYZ25.mjs';import {a as a$1}from'./chunk-6CQMBEIQ.mjs';import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Locale,formatLocalISO}from'@easbot/utils';import {z}from'zod';import {randomBytes,createHash}from'crypto';import {GraphProvider,probeEmbeddingDims,syncMeta}from'@easbot/llm';import K from'fs/promises';import ue from'path';import {writeFileSync}from'fs';import {createRequire}from'module';import {EMBEDDING_DIMS_CONSISTENCY_CHECK,DEFAULT_SEARCH_CONFIG}from'@easbot/types';var ye=Log.create({service:"memory.graph-store"}),ee=class{constructor(e){a(this,"db");this.db=e;}async upsertNode(e,a,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,a);if(i)return this.db.prepare("UPDATE nodes SET properties = ?, updatedAt = ? WHERE id = ?").run(s,c,i.id),i.id;let l=this.db.prepare("INSERT INTO nodes (name, type, properties, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?)").run(e,a,s,c,c);return Number(l.lastInsertRowid)}async deleteNode(e){this.db.prepare("DELETE FROM nodes WHERE id = ?").run(e);}async upsertEdge(e,a,r,o){let c=this.db.prepare("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)").run(e,a,r,JSON.stringify(o??{}),Date.now());return Number(c.lastInsertRowid)}async queryNodes(e={}){let a="SELECT id, name, type, properties, 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)),o.length>0&&(a+=` WHERE ${o.join(" AND ")}`),a+=" ORDER BY id",e.limit&&(a+=" LIMIT ?",r.push(e.limit)),ye.debug("queryNodes",{sql:a,params:r,filter:e});let c=this.db.prepare(a).all(...r);return ye.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}))}async queryEdges(e={}){let a="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 g=e.sourceOrTarget.map(S=>typeof S=="string"?parseInt(S,10):S).filter(S=>!Number.isNaN(S));o.push(`(e.source IN (${g.map(()=>"?").join(", ")}) OR e.target IN (${g.map(()=>"?").join(", ")}))`),r.push(...g,...g);}e.relation&&(o.push("e.relation = ?"),r.push(e.relation)),o.length>0&&(a+=` WHERE ${o.join(" AND ")}`),a+=" ORDER BY e.id",e.limit&&(a+=" LIMIT ?",r.push(e.limit)),ye.debug("queryEdges",{sql:a,params:r,filter:e});let c=this.db.prepare(a).all(...r);ye.debug("queryEdges result",{count:c.length});let s=[...new Set(c.map(g=>g.target))],i=s.length>0?await this.queryNodes({ids:s,limit:s.length}):[],l=new Map(i.map(g=>[g.id,g]));return c.map(g=>{let S={id:g.id,source:g.source,target:g.target,relation:g.relation,properties:g.properties?JSON.parse(g.properties):void 0,createdAt:g.createdAt},f=l.get(g.target);return f&&(S.targetNode=f),S})}async queryNeighbors(e,a=1,r){let o=r?.maxEdgesPerNode??50,c=new Map,s=[e];for(let i=0;i<=a&&s.length>0;i++){let l=await this.queryNodes({ids:s,limit:s.length}),g=await this.queryEdges({sourceOrTarget:s,limit:o*s.length}),S=new Map;for(let y of g){if(s.includes(y.source)){let h=S.get(y.source)??[];h.push(y),S.set(y.source,h);}if(s.includes(y.target)){let h=S.get(y.target)??[];h.push(y),S.set(y.target,h);}}let f=[];for(let y of l){if(c.has(y.id))continue;let h=(S.get(y.id)??[]).slice(0,o);if(c.set(y.id,{...y,edges:h}),i<a)for(let R of h){let v=R.source===y.id?R.target:R.source;!c.has(v)&&!f.includes(v)&&f.push(v);}}s=f;}return [...c.values()]}};var I=class extends Error{constructor(a$1,r,o){super(a$1);a(this,"code",r);a(this,"details",o);this.name="ServiceError";}},ie=class extends I{constructor(e,a=[]){super(`Memory not found: ${e}`,"NOT_FOUND",{memoryId:e,candidates:a});}};var he=class extends I{constructor(){super("ctx.agentId is required for memory service (ADR 0055 per-agent isolation)","AGENT_ID_REQUIRED");}},be=class extends I{constructor(e,a){super(`Trust denied for operation "${e}": ${a}`,"TRUST_DENIED",{operation:e,reason:a});}},ce=class extends I{constructor(e,a){super(`Memory ${e} has ${a} references (force=false)`,"HAS_REFERENCES",{memoryId:e,referenceCount:a});}},de=class extends I{constructor(e){super(`dryRun mode: ${e} memories matched but not deleted`,"DRY_RUN_NO_DELETE",{matchedCount:e});}},me=class extends I{constructor(e,a){super(`Matched ${e} memories exceeds maxDelete=${a}`,"MAX_DELETE_EXCEEDED",{matched:e,maxDelete:a});}};function H(t){if(typeof t.agentId!="string"||t.agentId.trim().length===0)throw new he}function Q(t,e){if(t.remote!==false)throw new be(e,"requires trusted local caller (CLI / agent tool / MCP with remote=false)")}function te(t){if(!t.dbPath||t.dbPath.trim().length===0)throw new I("service ctx.dbPath is required (MemoryKnowledgeConfigWithModels.database.path)","INTERNAL")}var re=Log.create({service:"memory.service.recall"});async function tt(t,e$1){let a=Date.now();if(H(t),te(t),!e$1.query||e$1.query.trim().length===0)throw new I("recall requires non-empty `query`","CONTENT_REQUIRED");let r=e$1.includeShared?"both":"agent_only";e$1.includeGraph&&void 0,re.debug("recall invoked",{agentId:t.agentId,query:e$1.query,category:e$1.category,maxResults:e$1.maxResults,includeGraph:e$1.includeGraph,scope:r});let o=e$1.maxResults??10,c=e$1.minScore??0,s=[],i=new e(t.dbPath);try{await i.initialize();let l=a$1.isInitialized()&&a$1.capabilities().embedding===!0,g=await St(i,t.agentId,e$1.query,{category:e$1.category,minImportance:e$1.minImportance,fromTime:e$1.fromTime,toTime:e$1.toTime,limit:o,minScore:c,hasEmbedding:l}),S;if(e$1.includeGraph&&g.length>0)try{let y=new ee(i.getDb()),h=e$1.depth??1,R=g.flatMap(E=>(E.nodes??[]).map(M=>M.id)).slice(0,5),v=new Set,b=new Map,C=e$1.maxEdgesPerNode??10;for(let E of R){let M=await y.queryNeighbors(E,h,{agentId:t.agentId,scope:r,maxEdgesPerNode:C});for(let u of M)v.add(u.id),b.set(u.id,u.edges??[]);}let w=v.size>0?i.query(`SELECT id, name, type FROM nodes WHERE id IN (${Array.from(v).map(()=>"?").join(",")})`,Array.from(v)):[],T=Array.from(b.values()).flat();S={nodes:w.map(E=>({id:E.id,name:E.name,type:E.type,createdAt:"",updatedAt:""})),edges:T};}catch(y){let h=y instanceof Error?y.message:String(y);re.warn("recall: KG neighbor query failed",{error:h}),s.push(`kg_neighbor_query_failed: ${h}`),S={nodes:[],edges:[]};}let f=Date.now()-a;return {hits:g,total:g.length,truncated:g.length>=o,durationMs:f,graph:S,...s.length>0?{warnings:s}:{}}}catch(l){throw l instanceof I?l:new I(`recall failed: ${l instanceof Error?l.message:String(l)}`,"INTERNAL",{cause:l instanceof Error?l.message:String(l)})}finally{i.close();}}async function St(t,e,a,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 a$1.embedText(a);}catch(p){re.warn("recall: query embedding failed, falling back to FTS-only",{error:p instanceof Error?p.message:String(p)}),i=null;}let l=Math.max(r.limit*100,1e3),[g,S]=await Promise.all([i?Mt(t,i,s,c,l):Promise.resolve([]),_t(t,a,s,c,r.limit)]),f=i?.7:0,y=i?.3:1,h=f+y,R=f/h,v=y/h,b=new Map;for(let p of g)b.set(p.id,p.score*R);for(let p of S)b.set(p.id,(b.get(p.id)??0)+p.score*v);let C=Array.from(b.entries()).sort((p,D)=>D[1]-p[1]).map(([p])=>p).slice(0,r.limit);if(C.length===0)return [];let w=C.map(()=>"?").join(","),T=t.query(`SELECT
2
+ mf.id,
3
+ mf.category,
4
+ mf.importance,
5
+ mf.agent_id as agentId,
6
+ mf.content as content,
7
+ SUBSTR(mf.content, 1, 200) as snippet,
8
+ mf.created_at as createdAt,
9
+ mf.updated_at as updatedAt,
10
+ mf.source,
11
+ mf.file_path as filePath,
12
+ mf.tags,
13
+ mf.session_id as sessionId,
14
+ mf.msg_id as msgId,
15
+ mf.parent_msg_id as parentMsgId
16
+ FROM memory_facts mf
17
+ WHERE mf.id IN (${w})`,C),E=It(t,T.map(p=>p.id)),M=Date.now();return T.map(p=>{let D=b.get(p.id)??0,L=(M-new Date(p.createdAt).getTime())/864e5,P=Math.exp(-0.05*L),j=(p.importance-1)/9,z=.4*D+.3*P+.3*j,J;if(p.tags)try{let d=JSON.parse(p.tags);Array.isArray(d)&&(J=d.filter(m=>typeof m=="string"));}catch{}return {memoryId:p.id,category:p.category,importance:p.importance,agentId:p.agentId,content:p.content,snippet:p.snippet,score:z,createdAt:p.createdAt,updatedAt:p.updatedAt,source:p.source,filePath:p.filePath??void 0,tags:J,sessionId:p.sessionId??void 0,msgId:p.msgId??void 0,parentMsgId:p.parentMsgId??void 0,nodes:E.get(p.id)??[]}}).filter(p=>p.score>=r.minScore).sort((p,D)=>D.score-p.score)}function It(t,e){let a=new Map;if(e.length===0)return a;try{let r=e.map(()=>"?").join(","),o=t.query(`SELECT fn.fact_id as fact_id, n.id, n.name, n.type
18
+ FROM fact_nodes fn
19
+ JOIN nodes n ON fn.node_id = n.id
20
+ WHERE fn.fact_id IN (${r})
21
+ ORDER BY fn.fact_id, fn.score DESC, n.id`,e);for(let c of o){let s=a.get(c.fact_id);s||(s=[],a.set(c.fact_id,s)),s.push({id:c.id,name:c.name,type:c.type});}}catch(r){re.warn("recall: loadFactNodes failed (KG associations unavailable for this recall)",{error:r instanceof Error?r.message:String(r)});}return a}function Mt(t,e,a,r,o){try{return t.query(`SELECT mf.id, mv.embedding
22
+ FROM memory_facts mf
23
+ JOIN memory_vectors mv ON mf.id = mv.fact_id
24
+ WHERE ${a}
25
+ LIMIT ?`,[...r,o]).map(s=>{let i=new Float32Array(s.embedding.buffer,s.embedding.byteOffset,s.embedding.byteLength/4);return {id:s.id,score:vt(e,i)}}).sort((s,i)=>i.score-s.score)}catch(c){if(c instanceof I)throw c;return re.warn("vector search failed, falling back to FTS-only",{error:c instanceof Error?c.message:String(c)}),[]}}function _t(t,e,a,r,o){try{let c=t.query(`SELECT mf.id as id, bm25(memory_facts_fts) as score
26
+ FROM memory_facts_fts fts
27
+ JOIN memory_facts mf ON mf.id = fts.fact_id
28
+ WHERE ${a} AND memory_facts_fts MATCH ?
29
+ ORDER BY score DESC
30
+ LIMIT ?`,[...r,Dt(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 I)throw c;return re.warn("FTS search failed, returning empty result",{err:c instanceof Error?c.message:String(c)}),[]}}function vt(t,e){if(t.length!==e.length||t.length===0)return 0;let a=0,r=0,o=0;for(let s=0;s<t.length;s++){let i=t[s]??0,l=e[s]??0;a+=i*l,r+=i*i,o+=l*l;}let c=Math.sqrt(r)*Math.sqrt(o);return c===0?0:Math.max(0,a/c)}function Dt(t){return t.trim().split(/\s+/).filter(e=>e.length>0).map(e=>`"${e.replace(/"/g,'""')}"`).join(" ")}var we=z.object({query:z.string().min(1).max(2e3),category:z.string().optional(),minImportance:z.number().min(1).max(10).optional(),fromTime:z.string().datetime().optional(),toTime:z.string().datetime().optional(),maxResults:z.number().int().min(1).max(100).optional(),minScore:z.number().min(0).max(1).optional(),includeGraph:z.boolean().optional(),depth:z.number().int().min(1).max(5).optional(),includeShared:z.boolean().optional(),maxEdgesPerNode:z.number().int().min(1).max(100).optional()}).strict();z.object({hits:z.array(z.unknown()),total:z.number(),truncated:z.boolean(),durationMs:z.number(),graph:z.object({nodes:z.array(z.unknown()),edges:z.array(z.unknown())}).optional()});var Re=z.object({content:z.string().min(1).max(1e4),category:z.string().min(1),importance:z.number().int().min(1).max(10).optional(),tags:z.array(z.string()).optional(),sessionId:z.string().optional(),msgId:z.string().optional(),parentMsgId:z.string().optional(),skipDedup:z.boolean().optional(),extractGraph:z.boolean().optional()}).strict();z.object({fact:z.object({id:z.string(),agentId:z.string(),content:z.string(),category:z.string(),importance:z.number(),createdAt:z.string(),updatedAt:z.string()}),filePath:z.string(),deduplicated:z.boolean(),nodeIds:z.array(z.number()).optional()});var Se=z.object({factId:z.string().min(1).describe("Target fact id (must belong to ctx.agentId)"),content:z.string().min(1).max(1e4).optional().describe("New content (triggers embedding rewrite + FTS reindex)"),category:z.string().min(1).optional().describe("New category (one of MemoryCategory enum)"),importance:z.number().int().min(1).max(10).optional().describe("New importance 1-10"),tags:z.array(z.string()).optional().describe("New tags array (empty array clears tags)")}).strict().refine(t=>t.content!==void 0||t.category!==void 0||t.importance!==void 0||t.tags!==void 0,{message:"at least one of `content`, `category`, `importance`, `tags` is required"});z.object({fact:z.object({id:z.string(),agentId:z.string(),content:z.string(),category:z.string(),importance:z.number(),createdAt:z.string(),updatedAt:z.string()}),contentChanged:z.boolean(),fieldsUpdated:z.array(z.string()),durationMs:z.number()});var Ie=z.object({factId:z.string().optional(),category:z.string().optional(),fromTime:z.string().datetime().optional(),toTime:z.string().datetime().optional(),maxDelete:z.number().int().min(1).max(1e4).optional(),dryRun:z.boolean().optional(),force:z.boolean().optional()}).strict().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"});z.object({deletedCount:z.number(),deletedIds:z.array(z.string()),dryRun:z.boolean(),truncatedCount:z.number()});var Me=z.object({sessionId:z.string().min(1),lastN:z.number().int().min(1).max(500).optional(),fromMessageId:z.string().optional(),writeToDisk:z.boolean().optional()}).strict();z.object({extractedCount:z.number(),factIds:z.array(z.string()),entities:z.array(z.object({id:z.number(),name:z.string(),type:z.string()})),relations:z.array(z.object({source:z.string(),target:z.string(),relation:z.string()})),messageRange:z.object({fromMessageId:z.string(),toMessageId:z.string()}),durationMs:z.number()});var _e=z.object({windowDays:z.number().int().min(1).max(365).optional(),dryRun:z.boolean().optional(),fromTime:z.string().datetime().optional()}).strict();z.object({totalFacts:z.number(),dedupedCount:z.number(),compressedCount:z.number(),archivedCount:z.number(),skippedCount:z.number(),durationMs:z.number()});var ve=z.object({query:z.string().min(1).optional(),nodeId:z.number().int().positive().optional(),type:z.string().optional(),depth:z.number().int().min(1).max(5).optional(),maxNodes:z.number().int().min(1).max(500).optional(),scope:z.enum(["agent_only","shared_only","both"]).optional(),relation:z.string().optional(),agentId:z.string().optional(),maxEdgesPerNode:z.number().int().min(1).max(100).optional()}).strict();z.object({root:z.unknown().nullable(),nodes:z.array(z.unknown()),edges:z.array(z.unknown()),truncated:z.boolean(),totalNodes:z.number(),totalEdges:z.number(),scope:z.enum(["agent_only","shared_only","both"]),durationMs:z.number()});var De=z.object({agentId:z.string().optional()}).passthrough().optional();z.object({dbPath:z.string(),workspaceDir:z.string(),factsCount:z.number(),nodesCount:z.number(),edgesCount:z.number(),factsByCategory:z.record(z.string(),z.number()),ftsAvailable:z.boolean(),vectorEnabled:z.boolean(),kgScopeEnabled:z.boolean(),healthy:z.boolean(),meta:z.record(z.string(),z.string())});var Ce=z.object({repair:z.boolean().optional(),agentId:z.string().optional()}).passthrough().optional();z.object({healthy:z.boolean(),checks:z.array(z.object({name:z.string(),passed:z.boolean(),message:z.string(),details:z.record(z.string(),z.unknown()).optional()}))});var Ne=z.object({workspaceDir:z.string().optional(),dbPath:z.string().optional(),archiveDays:z.number().int().min(1).max(3650).optional(),force:z.boolean().optional()}).strict();z.object({initialized:z.boolean(),dbPath:z.string(),workspaceDir:z.string(),tablesCreated:z.number(),migrationsApplied:z.number(),durationMs:z.number()});var Oe=z.object({windowDays:z.number().int().min(1).max(3650).optional(),dryRun:z.boolean().optional()}).passthrough();z.object({generatedCount:z.number(),skippedCount:z.number(),failedGenerateCount:z.number(),archivedCount:z.number(),failedArchivePaths:z.array(z.string()),archiveThreshold:z.string(),archivedRecords:z.array(z.object({source:z.string(),target:z.string(),firstCreatedAt:z.string(),firstFactId:z.string()})),windowDays:z.number(),dryRun:z.boolean(),durationMs:z.number()});var le=Log.create({service:"memory.fact-file-sync"}),Ot=".easbot/memory/active";function ge(t,e){let a=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"),l=String(c.getDate()).padStart(2,"0"),g=`${s}-${i}-${l}`;return `${a}/${Ot}/${r}/${g}.md`}function rt(t){let e=t.tags&&t.tags.length>0?t.tags:[],a=t.importance??5,r=t.source??"session_self_write",o=t.createdAt?formatLocalISO(new Date(t.createdAt)):formatLocalISO(new Date),c=t.updatedAt?formatLocalISO(new Date(t.updatedAt)):o,s=["---",`id: ${t.id}`,`agent_id: ${t.agentId}`,`category: ${t.category}`,`importance: ${a}`,`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}`),s.push("---"),`${s.join(`
31
+ `)}
32
+ ${t.content.trim()}`}function ne(t,e){let a=t.replace(/\\/g,"/"),r=e.replace(/\\/g,"/").replace(/\/+$/,"");return a.startsWith(`${r}/`)?a.slice(r.length+1):a}async function Tt(t,e){let a=ge(t,e),r=ne(a,e);try{let o=rt(t);await K.mkdir(ue.dirname(a),{recursive:!0});let c="";try{c=await K.readFile(a,"utf-8");}catch(i){if(i.code!=="ENOENT")throw i}let s=c.length>0&&!c.endsWith(`
33
+ `)?`
34
+ `:"";return await K.writeFile(a,`${c}${s}${o}
35
+ `,"utf-8"),le.debug("Fact file synced (append)",{id:t.id,relPath:r}),{ok:!0,absPath:a,relPath:r}}catch(o){let c=o instanceof Error?o.message:String(o);return le.warn("Failed to write fact file (best-effort, non-blocking)",{id:t.id,absPath:a,error:c}),{ok:false,absPath:a,relPath:r,error:c}}}async function Pt(t,e){let a;t.filePath?a=`${e.replace(/\\/g,"/").replace(/\/+$/,"")}/${t.filePath.replace(/^\/+/,"")}`:a=ge({id:t.id,category:t.category,createdAt:t.createdAt,updatedAt:t.createdAt},e);let r=ne(a,e);try{return await K.unlink(a),le.debug("Fact file deleted",{id:t.id,relPath:r}),{ok:!0,absPath:a,relPath:r}}catch(o){if(o.code==="ENOENT")return le.debug("Fact file not found (already deleted)",{id:t.id,relPath:r}),{ok:true,absPath:a,relPath:r};let s=o instanceof Error?o.message:String(o);return le.warn("Failed to delete fact file (best-effort, non-blocking)",{id:t.id,absPath:a,error:s}),{ok:false,absPath:a,relPath:r,error:s}}}var oe={resolvePath:ge,renderMarkdown:rt,toRelPath:ne,write:Tt,delete:Pt};var ae=Log.create({service:"memory.service.remember"});async function nt(t,e$1){if(H(t),te(t),!e$1.content||e$1.content.trim().length===0)throw new I("remember requires non-empty `content`","CONTENT_REQUIRED");if(!e$1.category)throw new I("remember requires `category`","CATEGORY_REQUIRED");ae.debug("remember invoked",{agentId:t.agentId,category:e$1.category,importance:e$1.importance??5,contentLength:e$1.content.length,skipDedup:e$1.skipDedup,extractGraph:e$1.extractGraph??true});let a=new e(t.dbPath);try{await a.initialize();let r=new Date().toISOString(),o=Lt(),c=e$1.importance??5,s={entities:[],relations:[]},l=e$1.extractGraph!==!1&&a$1.isInitialized()&&a$1.capabilities().graphLlm?a$1.getGraphLlm():void 0;if(l)try{s=await $t(l,e$1.content);}catch(E){ae.warn("LLM KG extraction failed (continuing without KG)",{agentId:t.agentId,error:E instanceof Error?E.message:String(E)});}let g=a$1.isInitialized()&&a$1.capabilities().embedding===!0,S=g?await qt(a.getDb(),e$1.content):null,f=S?S.length:null,y=s.entities,h=s.relations,R=[],v=0,b=[];if(a.transaction(()=>{let E=new Map;for(let u of y){let p=a.query("SELECT id FROM nodes WHERE name = ? AND type = ? LIMIT 1",[u.name,u.type])[0];if(p){E.set(u.name,p.id);continue}let D=null;try{let j=Ae(u.name),z=a.query("SELECT embedding FROM embedding_cache WHERE content_hash = ?",[j])[0];z?.embedding&&(D=z.embedding);}catch{}let P=a.run("INSERT INTO nodes (name, type, properties, embedding, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)",[u.name,u.type,JSON.stringify({source:"llm_extracted",...u.properties??{}}),D,r,r]).lastID;P>0&&(E.set(u.name,P),D===null&&b.push({name:u.name,nodeId:P}));}for(let u of h){let p=E.get(u.source),D=E.get(u.target);!p||!D||p===D||a.run("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)",[p,D,u.relation,JSON.stringify({}),r]);}a.run(`INSERT INTO memory_facts
36
+ (id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance,
37
+ source, tags, file_path, created_at, updated_at)
38
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[o,t.agentId,e$1.sessionId??null,e$1.msgId??null,e$1.parentMsgId??null,e$1.content,e$1.category,c,"session_self_write",e$1.tags?JSON.stringify(e$1.tags):null,null,r,r]);let M=Array.from(E.values());if(M.length>0)try{for(let u of M)a.run("INSERT OR IGNORE INTO fact_nodes (fact_id, node_id, source, score, createdAt) VALUES (?, ?, ?, ?, ?)",[o,u,"kg_extract",1,r]);}catch(u){ae.warn("fact_nodes write failed (non-fatal)",{factId:o,nodeCount:M.length,error:u instanceof Error?u.message:String(u)});}if(S&&f){let u=Pe(S);a.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[o,u]),v=1,a.query("SELECT value FROM meta WHERE key = ?",["vectorDims"])[0]||a.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["vectorDims",String(f)]);}a.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[o]),a.run("INSERT INTO memory_facts_fts (fact_id, agent_id, content, tags) VALUES (?, ?, ?, ?)",[o,t.agentId,e$1.content,e$1.tags?e$1.tags.join(" "):""]),R.push(...Array.from(E.values()));}),b.length>0&&a$1.isInitialized()&&a$1.capabilities().embedding)try{let E=b.map(p=>p.name),M=await a$1.embedMany(E),u=new Date().toISOString();for(let p=0;p<b.length;p++){let D=b[p],L=M[p];if(!D||!L||L.length===0)continue;let P=Pe(new Float32Array(L));a.run("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)",[Ae(D.name),P]),a.run("UPDATE nodes SET embedding = ?, updatedAt = ? WHERE id = ?",[P,u,D.nodeId]);}}catch(E){ae.warn("memory entity name batch embed failed (non-fatal)",{pendingCount:b.length,error:E instanceof Error?E.message:String(E)});}ae.info("Memory stored",{id:o,category:e$1.category,agentId:t.agentId,nodeCount:R.length,vectorsWritten:v,vectorDims:f??0,embeddingMode:g?"enabled":"fts_only",entitiesExtracted:y.length,relationsExtracted:h.length});let C={id:o,agentId:t.agentId,sessionId:e$1.sessionId,msgId:e$1.msgId,parentMsgId:e$1.parentMsgId,content:e$1.content,category:e$1.category,importance:c,source:"session_self_write",tags:e$1.tags,nodeIds:R.length>0?R:void 0,filePath:void 0,createdAt:r,updatedAt:r},w="",T=await oe.write(C,t.workspaceDir);if(T.ok){w=T.relPath,C.filePath=T.relPath;try{a.run("UPDATE memory_facts SET file_path = ? WHERE id = ?",[T.relPath,o]);}catch(E){ae.warn("Failed to update file_path column after sync",{id:o,error:E instanceof Error?E.message:String(E)});}}return {fact:C,filePath:w,deduplicated:!1,nodeIds:R,vectorsWritten:v,vectorDims:f??0,entitiesExtracted:y.length,relationsExtracted:h.length}}catch(r){throw r instanceof I?r:new I(`remember failed: ${r instanceof Error?r.message:String(r)}`,"INTERNAL",{cause:r instanceof Error?r.message:String(r)})}finally{a.close();}}function Lt(){let t=Date.now(),e=randomBytes(3).toString("hex");return `mem_${t}_${e}`}function Pe(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}function Ae(t){return createHash("sha256").update(t).digest("hex")}async function qt(t,e){let a=Ae(e),r=t.prepare("SELECT embedding FROM embedding_cache WHERE content_hash = ?").get(a);if(r?.embedding)return new Float32Array(r.embedding.buffer,r.embedding.byteOffset,r.embedding.byteLength/4);let o=await a$1.embedText(e);if(!o||o.length===0)return null;let c=Pe(o);return t.prepare("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)").run(a,c),o}async function $t(t,e){let a=await GraphProvider.generateGraph({chunks:[e],model:t,includeRules:false});return {entities:a.entities,relations:a.relations}}var ke=Log.create({service:"memory.service.update"});function Wt(t){if(t.content===void 0&&t.category===void 0&&t.importance===void 0&&t.tags===void 0)throw new I("update requires at least one of: `content`, `category`, `importance`, `tags`","CONTENT_REQUIRED");if(t.content!==void 0&&t.content.trim().length===0)throw new I("update: `content` cannot be empty (use `forget` to delete)","CONTENT_REQUIRED");if(t.importance!==void 0&&(t.importance<1||t.importance>10))throw new I(`update: \`importance\` must be 1-10, got ${t.importance}`,"IMPORTANCE_REQUIRED")}async function ot(t,e$1){let a=Date.now();H(t),te(t),Wt(e$1),ke.debug("update invoked",{agentId:t.agentId,factId:e$1.factId,fields:{content:e$1.content!==void 0,category:e$1.category!==void 0,importance:e$1.importance!==void 0,tags:e$1.tags!==void 0}});let r=e$1.content!==void 0,o=r&&a$1.isInitialized()&&a$1.capabilities().embedding===true,c=null;if(o&&e$1.content)try{c=await a$1.embedText(e$1.content);}catch(i){ke.warn("update: embedding rewrite failed (continuing without vector update)",{factId:e$1.factId,error:i instanceof Error?i.message:String(i)});}let s=new e(t.dbPath);try{await s.initialize();let i=new Date().toISOString(),l=[];s.transaction(()=>{let y=s.query("SELECT id, content, category, importance, tags FROM memory_facts WHERE id = ? AND agent_id = ?",[e$1.factId,t.agentId])[0];if(!y)throw new ie(e$1.factId);let h=["updated_at = ?"],R=[i];if(e$1.content!==void 0&&e$1.content!==y.content&&(h.push("content = ?"),R.push(e$1.content),l.push("content")),e$1.category!==void 0&&e$1.category!==y.category&&(h.push("category = ?"),R.push(e$1.category),l.push("category")),e$1.importance!==void 0&&e$1.importance!==y.importance&&(h.push("importance = ?"),R.push(e$1.importance),l.push("importance")),e$1.tags!==void 0){let v=e$1.tags.length>0?JSON.stringify(e$1.tags):null;v!==y.tags&&(h.push("tags = ?"),R.push(v),l.push("tags"));}if(l.length>0&&s.run(`UPDATE memory_facts SET ${h.join(", ")} WHERE id = ? AND agent_id = ?`,[...R,e$1.factId,t.agentId]),l.includes("content")||l.includes("tags")){let v=e$1.content??y.content,b=l.includes("tags")?e$1.tags&&e$1.tags.length>0?JSON.stringify(e$1.tags):null:y.tags,C=b?(()=>{try{let w=JSON.parse(b);return Array.isArray(w)?w.filter(T=>typeof T=="string"):[]}catch{return []}})():[];s.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[e$1.factId]),s.run("INSERT INTO memory_facts_fts (fact_id, agent_id, content, tags) VALUES (?, ?, ?, ?)",[e$1.factId,t.agentId,v,C.join(" ")]);}if(l.includes("content")&&c){let v=Gt(c);s.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[e$1.factId,v]);try{let b=jt(e$1.content);s.run("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)",[b,v]);}catch{}}}),(l.includes("content")||l.includes("tags"))&&s.run("INSERT INTO memory_facts_fts(memory_facts_fts) VALUES('optimize')");let g=s.query("SELECT id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance, source, tags, file_path, created_at, updated_at FROM memory_facts WHERE id = ? AND agent_id = ?",[e$1.factId,t.agentId])[0];if(!g)throw new I(`update: failed to read back updated fact ${e$1.factId}`,"INTERNAL");let S;if(g.tags)try{let y=JSON.parse(g.tags);Array.isArray(y)&&(S=y.filter(h=>typeof h=="string"));}catch{}let f={id:g.id,agentId:g.agent_id,sessionId:g.session_id??void 0,msgId:g.msg_id??void 0,parentMsgId:g.parent_msg_id??void 0,content:g.content,category:g.category,importance:g.importance,source:g.source,tags:S,filePath:g.file_path??void 0,createdAt:g.created_at,updatedAt:g.updated_at};return ke.info("Memory updated",{agentId:t.agentId,factId:e$1.factId,fieldsUpdated:l,contentChanged:r,durationMs:Date.now()-a}),{fact:f,contentChanged:r,fieldsUpdated:l,durationMs:Date.now()-a}}catch(i){throw i instanceof I?i:new I(`update failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}function Gt(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}function jt(t){return createHash("sha256").update(t).digest("hex")}var xe=Log.create({service:"memory.service.forget"}),zt=1e3;function Qt(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 I("CONTENT_REQUIRED: forget requires one of: `factId`, `category`, or `fromTime`/`toTime`","CONTENT_REQUIRED");if(e.length>1)throw new I(`mutually exclusive: forget requires exactly one of factId/category/timeRange, got [${e.join(", ")}]`,"CONTENT_REQUIRED");return e[0]}function Kt(t,e,a){let r=[a];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 Vt(t,e,a,r){return t.query(`SELECT id FROM memory_facts WHERE ${e} LIMIT ?`,[...a,r+1]).map(c=>c.id)}function Jt(t,e,a,r){if(a.length===0)return 0;let o=a.map(()=>"?").join(",");return t.query(`SELECT COUNT(DISTINCT fn.fact_id) as count
39
+ FROM fact_nodes fn
40
+ JOIN memory_facts mf ON fn.fact_id = mf.id
41
+ WHERE mf.agent_id = ? AND fn.fact_id != ? AND fn.node_id IN (${o})`,[r,e,...a])[0]?.count??0}function Yt(t,e,a){let r,o,c="";return t.transaction(()=>{let s=t.query("SELECT content, file_path, category, created_at FROM memory_facts WHERE id = ? AND agent_id = ?",[e,a])[0],l=t.query("SELECT node_id FROM fact_nodes WHERE fact_id = ?",[e]).map(g=>g.node_id).filter(g=>typeof g=="number");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,a]),l.length>0){let g=l.map(()=>"?").join(",");t.run(`DELETE FROM nodes WHERE id IN (${g}) AND NOT EXISTS (
42
+ SELECT 1 FROM fact_nodes fn WHERE fn.node_id = nodes.id
43
+ )`,l);}}),t.run("INSERT INTO memory_facts_fts(memory_facts_fts) VALUES('optimize')"),{filePath:r,category:o,createdAt:c}}async function at(t,e$1){H(t),Q(t,"forget");let a=Qt(e$1),r=e$1.maxDelete??zt,o=e$1.dryRun??false,c=e$1.force??false;xe.debug("forget invoked",{agentId:t.agentId,mode:a,maxDelete:r,dryRun:o,force:c});let s=new e(t.dbPath);try{await s.initialize();let{where:i,args:l}=Kt(a,e$1,t.agentId),g=Vt(s,i,l,r),S=g.length>r;if(S&&!c)throw new me(g.length,r);let f=S?g.slice(0,r):g;if(o)throw new de(f.length);let y=[],h=[];for(let R of f){if(!c){let T=s.query("SELECT node_id FROM fact_nodes WHERE fact_id = ? AND node_id IS NOT NULL",[R]).map(M=>M.node_id).filter(M=>typeof M=="number"),E=Jt(s,R,T,t.agentId);if(E>0)throw new ce(R,E)}let{filePath:v,category:b,createdAt:C}=Yt(s,R,t.agentId);v&&b&&h.push({id:R,filePath:v,category:b,createdAt:C}),y.push(R);}xe.info("forget complete",{agentId:t.agentId,mode:a,deletedCount:y.length,force:c,dryRun:o});for(let{id:R,filePath:v,category:b,createdAt:C}of h)await oe.delete({id:R,filePath:v,category:b,createdAt:C},t.workspaceDir).catch(w=>{xe.warn("Fact file delete failed (best-effort)",{id:R,filePath:v,error:w instanceof Error?w.message:String(w)});});return {deletedCount:y.length,deletedIds:y,dryRun:o,truncatedCount:S?g.length-r:0}}catch(i){throw i instanceof I?i:new I(`forget failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var st=Log.create({service:"memory.service.extract"}),Zt=50,Fe=500;async function it(t,e$1){if(H(t),!e$1.sessionId||e$1.sessionId.trim().length===0)throw new I("extract requires non-empty `sessionId`","SESSION_ID_REQUIRED");let a=e$1.lastN??Zt;if(a>Fe)throw new I(`extract lastN=${a} exceeds max=${Fe}`,"CONTENT_REQUIRED",{lastN:a,maxLastN:Fe});let r=e$1.sessionId,o=e$1.fromMessageId;st.debug("extract invoked",{agentId:t.agentId,sessionId:r,lastN:a,fromMessageId:o,writeToDisk:e$1.writeToDisk??true});let c=Date.now(),s=new e(t.dbPath);try{await s.initialize();let i=s.query(`SELECT id, content, category, importance, 1.0 as score, created_at
44
+ FROM memory_facts
45
+ WHERE agent_id = ? AND session_id = ?
46
+ ORDER BY created_at ASC
47
+ LIMIT ?`,[t.agentId,r,a]),l=o?i.filter(b=>b.id>o):i,g=l.map(b=>b.id),S=g.length>0?s.query(`SELECT node_id FROM fact_nodes WHERE fact_id IN (${g.map(()=>"?").join(",")})`,g):[],f=new Set;for(let b of S)typeof b.node_id=="number"&&b.node_id>0&&f.add(b.node_id);let y=Array.from(f),h=[],R=[];if(y.length>0){let b=y.map(()=>"?").join(","),C=s.query(`SELECT id, name, type FROM nodes WHERE id IN (${b})`,y),w=new Map;for(let M of C)w.set(M.id,M.name);h=C.map(M=>({id:M.id,name:M.name,type:M.type}));let T=s.query(`SELECT source, target, relation FROM edges WHERE source IN (${b}) OR target IN (${b})`,[...y,...y]),E=new Set;R=[];for(let M of T){let u=w.get(M.source),p=w.get(M.target);if(!u||!p)continue;let D=`${u}\0${M.relation}\0${p}`;E.has(D)||(E.add(D),R.push({source:u,target:p,relation:M.relation}));}}let v=Date.now()-c;return st.info("extract complete",{agentId:t.agentId,sessionId:r,factCount:l.length,nodeCount:h.length,relationCount:R.length,durationMs:v}),{extractedCount:l.length,factIds:l.map(b=>b.id),entities:h,relations:R,messageRange:{fromMessageId:l[0]?.id??"",toMessageId:l[l.length-1]?.id??""},durationMs:v}}catch(i){throw i instanceof I?i:new I(`extract failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var $e=Log.create({service:"memory.service.consolidate"}),tr=30;async function rr(t){let{createHash:e}=await import('crypto');return e("sha256").update(t).digest("hex")}async function ct(t,e$1={}){let a=Date.now();H(t),Q(t,"consolidate");let r=e$1.windowDays??tr,o=e$1.dryRun??false,c=e$1.fromTime;$e.debug("consolidate invoked",{agentId:t.agentId,windowDays:r,dryRun:o,fromTime:c});let s=new e(t.dbPath);try{await s.initialize();let i=s.query(`SELECT id, content, category, importance, created_at FROM memory_facts
48
+ WHERE agent_id = ?${c?" AND created_at >= ?":""}
49
+ ORDER BY created_at DESC`,c?[t.agentId,c]:[t.agentId]),l=new Map;for(let C of i){let w=await rr(C.content);l.has(w)||l.set(w,[]),l.get(w)?.push(C);}let g=0,S=[];for(let[,C]of l){if(C.length<=1)continue;let w=[...C].sort((M,u)=>M.importance!==u.importance?u.importance-M.importance:u.created_at.localeCompare(M.created_at)),T=w[0];if(!T)continue;let E=w.slice(1).map(M=>M.id);g+=E.length,S.push({keep:T,removeIds:E});}let f=new Date(Date.now()-r*24*60*60*1e3).toISOString(),y=s.query(`SELECT id, content, category, importance, created_at FROM memory_facts
50
+ WHERE agent_id = ? AND created_at < ?
51
+ ORDER BY created_at ASC`,[t.agentId,f]),h=0;if(o)h=0;else {let C=ue.join(t.workspaceDir,"archive");await K.mkdir(C,{recursive:!0});for(let{removeIds:w}of S)w.length!==0&&s.transaction(()=>{for(let T of w)s.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[T,t.agentId]);});for(let w of y){let T=w.created_at.slice(0,7),E=ue.join(C,T,w.category);await K.mkdir(E,{recursive:!0});let M=ue.join(E,`${w.id}.md`);try{await K.writeFile(M,[`# ${w.id}`,"",`category: ${w.category}`,`importance: ${w.importance}`,`createdAt: ${w.created_at}`,"",w.content,""].join(`
52
+ `),"utf-8"),s.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[w.id,t.agentId]),h++;}catch(u){$e.warn("consolidate: archive write failed",{factId:w.id,error:u instanceof Error?u.message:String(u)});}}}let R=i.length,v=0,b=0;return $e.info("consolidate complete",{agentId:t.agentId,totalFacts:R,dedupedCount:g,compressedCount:v,archivedCount:h,skippedCount:b,dryRun:o,durationMs:Date.now()-a}),{totalFacts:R,dedupedCount:g,compressedCount:v,archivedCount:h,skippedCount:b,durationMs:Date.now()-a}}catch(i){throw i instanceof I?i:new I(`consolidate failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var G=Log.create({service:"memory.service.sync"}),ar=30,sr=".easbot/memory/active",dt=".easbot/memory/archive";function ir(t,e){let r=t.query("SELECT node_id FROM fact_nodes WHERE fact_id = ?",[e.id]).map(o=>o.node_id).filter(o=>typeof o=="number");return {id:e.id,agentId:e.agent_id,sessionId:e.session_id??void 0,msgId:e.msg_id??void 0,parentMsgId:e.parent_msg_id??void 0,content:e.content,category:e.category,importance:e.importance,source:e.source,tags:e.tags?JSON.parse(e.tags):void 0,nodeIds:r.length>0?r:void 0,filePath:e.file_path??void 0,createdAt:e.created_at,updatedAt:e.updated_at}}async function cr(t,e){let a=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,
53
+ source, tags, file_path, created_at, updated_at
54
+ FROM memory_facts ${c}
55
+ ORDER BY created_at ASC`,s);for(let l of i){let g=ir(t,l);if(l.file_path?.startsWith(`${dt}/`)){r++;continue}let S=ge(g,e.workspaceDir);try{await K.access(S),r++;continue}catch(y){let h=y;if(h.code!=="ENOENT"){G.warn("sync generate: fs.access failed (non-ENOENT)",{factId:g.id,absPath:S,error:h.message}),o++;continue}}let f=await oe.write(g,e.workspaceDir);f.ok?a++:(o++,G.warn("sync generate: factFileSync.write failed",{factId:g.id,absPath:S,error:f.error}));}return G.debug("sync stage A complete",{agentId:e.agentId,generatedCount:a,skippedCount:r,failedGenerateCount:o}),{generatedCount:a,skippedCount:r,failedGenerateCount:o}}async function dr(t,e,a,r){let o=a*24*60*60*1e3,c=Date.now(),s=formatLocalISO(new Date(c-o)),i=[],l=[],g=ue.join(e.workspaceDir,sr),S=await mr(g);G.debug("sync stage B: scan active dir",{activeDir:g,fileCount:S.length,windowDays:a,threshold:s,dryRun:r});for(let f of S){let y=await lr(f);if(!y){G.warn("sync stage B: skip unparseable file",{absPath:f});continue}let{firstCreatedAt:h,firstFactId:R}=y,v=new Date(h).getTime();if(Number.isNaN(v)){G.warn("sync stage B: skip invalid createdAt",{absPath:f,firstCreatedAt:h});continue}if(c-v<=o)continue;let b=gr(f);if(!b){G.warn("sync stage B: cannot infer category from path",{absPath:f});continue}let C=h.slice(0,7),w=ue.join(e.workspaceDir,dt,C,b),T=ue.basename(f),E=ue.join(w,T);if(r){i.push({source:f,target:E,firstCreatedAt:h,firstFactId:R});continue}try{await K.mkdir(w,{recursive:!0});try{await K.rename(f,E);}catch(p){let D=p;G.warn("sync stage B: fs.rename failed, falling back to copy+unlink",{absPath:f,targetPath:E,error:D.message}),await K.copyFile(f,E),await K.unlink(f);}let M=ne(f,e.workspaceDir),u=ne(E,e.workspaceDir);t.run(`UPDATE memory_facts SET file_path = ?
56
+ WHERE agent_id = ? AND file_path = ?`,[u,e.agentId??"",M]),i.push({source:f,target:E,firstCreatedAt:h,firstFactId:R});}catch(M){let u=M instanceof Error?M.message:String(M);G.warn("sync stage B: archive failed",{absPath:f,targetPath:E,error:u}),l.push(f);}}return G.debug("sync stage B complete",{agentId:e.agentId,archivedCount:i.length,failedArchiveCount:l.length,dryRun:r}),{archivedCount:i.length,archiveThreshold:s,archivedRecords:i,failedArchivePaths:l}}async function mr(t){let e=[];try{await mt(t,e);}catch(a){let r=a;if(r.code==="ENOENT")return e;throw G.warn("sync: listActiveMdFiles failed",{activeDir:t,error:r.message}),new I(`sync: listActiveMdFiles failed: ${r.message}`,"INTERNAL",{cause:r.message})}return e}async function mt(t,e){let a=await K.readdir(t,{withFileTypes:true});for(let r of a){let o=ue.join(t,r.name);r.isDirectory()?await mt(o,e):r.isFile()&&r.name.endsWith(".md")&&e.push(o);}}async function lr(t){let e;try{e=await K.readFile(t,"utf-8");}catch(s){if(s.code==="ENOENT")return null;throw s}if(!e.startsWith(`---
57
+ `))return null;let a=e.indexOf(`
58
+ ---
59
+ `,4);if(a===-1)return null;let r=e.slice(4,a),o,c;for(let s of r.split(`
60
+ `)){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 gr(t){let e=t.replace(/\\/g,"/").split("/"),a=e.findIndex(c=>c==="active");if(a===-1)return null;let r=e.slice(a+1);return r.length!==2||!r[1].endsWith(".md")?null:r[0]??null}async function lt(t,e$1={}){let a=Date.now();H(t),Q(t,"sync");let r=e$1.windowDays??t.config?.archiveDays??ar,o=e$1.dryRun??false;G.info("sync invoked",{agentId:t.agentId,windowDays:r,dryRun:o,workspaceDir:t.workspaceDir});let c=new e(t.dbPath);try{await c.initialize();let s=await cr(c,t),i=await dr(c,t,r,o),l={generatedCount:s.generatedCount,skippedCount:s.skippedCount,failedGenerateCount:s.failedGenerateCount,archivedCount:i.archivedCount,failedArchivePaths:i.failedArchivePaths,archiveThreshold:i.archiveThreshold,archivedRecords:i.archivedRecords,windowDays:r,dryRun:o,durationMs:Date.now()-a};if(G.info("sync complete",{agentId:t.agentId,...l}),l.failedArchivePaths.length>0)throw new I(`sync: ${l.failedArchivePaths.length} archive(s) failed: ${l.failedArchivePaths.join(", ")}`,"INGEST_FAILED",{failedArchivePaths:l.failedArchivePaths,archivedCount:l.archivedCount});return l}catch(s){throw s instanceof I?s:new I(`sync failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{c.close();}}var gt=Log.create({service:"memory.service.graph-query"});async function ut(t,e$1){let a=Date.now(),r=(t.agentId??"").trim()||"default",o=e$1.scope??"agent_only",c=typeof e$1.nodeId=="number"&&e$1.nodeId>0,s=typeof e$1.query=="string"&&e$1.query.trim().length>0;if(!c&&!s)throw new I("CONTENT_REQUIRED: graphQuery requires either `nodeId` (numeric) or `query` (name fragment for CLI)","CONTENT_REQUIRED");let i=2,l=100,g=e$1.maxEdgesPerNode??10,S=e$1.type,f=e$1.relation;gt.debug("graphQuery invoked",{agentId:r,nodeId:e$1.nodeId,query:e$1.query,type:S,depth:i,maxNodes:l,scope:o,remote:t.remote});let y=new e(t.dbPath);try{await y.initialize();let h=new ee(y.getDb()),R=null;if(c)R=(await h.queryNodes({ids:[e$1.nodeId],agentId:r,scope:o}))[0]??null;else {let u=e$1.query,p=u.includes("*")||u.includes("%")?u:`%${u}%`,D=await h.queryNodes({name:p,...S?{type:S}:{},agentId:r,scope:o,limit:l});R=(u.includes("*")||u.includes("%")?D:D.filter(P=>P.name.toLowerCase().includes(u.toLowerCase())))[0]??null;}if(!R)return {root:null,nodes:[],edges:[],truncated:!1,totalNodes:0,totalEdges:0,scope:o,durationMs:Date.now()-a};let v=await h.queryNeighbors(R.id,i,{agentId:r,scope:o,maxEdgesPerNode:g}),b=new Map;b.set(R.id,R);for(let u of v)b.set(u.id,{id:u.id,name:u.name,type:u.type,createdAt:u.createdAt,updatedAt:u.updatedAt});let C=[];for(let u of v)if(u.edges)for(let p of u.edges)f&&p.relation!==f||C.push(p);let w=Array.from(new Map(C.map(u=>[u.id,u])).values());for(let u of w){if(!b.has(u.source)){let p=await h.queryNodes({ids:[u.source],agentId:r,scope:o});p[0]&&b.set(p[0].id,p[0]);}if(!b.has(u.target)){let p=await h.queryNodes({ids:[u.target],agentId:r,scope:o});p[0]&&b.set(p[0].id,p[0]);}}let T=Array.from(b.values()),E=T.length>l,M=E?T.slice(0,l):T;return gt.info("graphQuery complete",{agentId:r,rootId:R.id,nodeCount:M.length,edgeCount:w.length,truncated:E,durationMs:Date.now()-a}),{root:R,nodes:M,edges:w,truncated:E,totalNodes:T.length,totalEdges:w.length,scope:o,durationMs:Date.now()-a}}catch(h){throw h instanceof I?h:new I(`graphQuery failed: ${h instanceof Error?h.message:String(h)}`,"INTERNAL",{cause:h instanceof Error?h.message:String(h)})}finally{y.close();}}var B=Log.create({service:"memory.service.init"});function He(t){return ue.join(t,".easbot","memory.json")}async function yr(t){try{let{Config:e}=await import('@easbot/llm'),a=await e.get(),r=o=>typeof o=="string"&&o.length>0?o:void 0;return {embeddingModel:r(a.embedding_model),graphModel:r(a.graph_model)}}catch{return {}}}function hr(t,e={}){let a={version:1,schema_version:a$2,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};writeFileSync(t,JSON.stringify(a,null,2),"utf-8");}async function ft(t,e$1={}){let a=Date.now();Q(t,"init");let r=e$1.workspaceDir??t.workspaceDir,o=e$1.dbPath??t.dbPath;if(!r||r.trim().length===0)throw new I("init requires non-empty `workspaceDir` (ctx.workspaceDir or params.workspaceDir)","CONTENT_REQUIRED");if(!o||o.trim().length===0)throw new I("init requires non-empty `dbPath` (ctx.dbPath or params.dbPath)","CONTENT_REQUIRED");let c=t.agentId?.trim()??"",s=e$1.force??false;B.debug("init invoked",{agentId:c,workspaceDir:r,dbPath:o,force:s});let i=He(r);if(!s)try{if(await K.stat(i).then(()=>!0).catch(()=>!1))return B.info("init: idempotent skip (memory.json exists, no --force)",{workspaceDir:r,configPath:i}),{initialized:!1,dbPath:o,configPath:i,configCreated:!1,schemaVersion:a$2,workspaceDir:r,tablesCreated:0,migrationsApplied:0,durationMs:0}}catch{}try{await K.mkdir(ue.dirname(o),{recursive:!0}),await K.mkdir(ue.join(r,".easbot","memory","active"),{recursive:!0}),await K.mkdir(ue.join(r,"archive"),{recursive:!0}),await K.mkdir(ue.join(r,".easbot"),{recursive:!0});}catch(f){throw new I(`init: failed to create directories: ${f instanceof Error?f.message:String(f)}`,"INTERNAL",{cause:f instanceof Error?f.message:String(f)})}if(s)for(let f of [o,`${o}-wal`,`${o}-shm`])try{await K.rm(f,{force:!0});}catch(y){B.warn("init: force rm failed (may not exist)",{path:f,error:y instanceof Error?y.message:String(y)});}let l=await yr(),g=false;try{!await K.stat(i).then(()=>!0).catch(()=>!1)||s?(hr(i,{embeddingModel:l.embeddingModel,graphModel:l.graphModel,archiveDays:t.config?.archiveDays,shortTermMaxRounds:t.config?.shortTermMaxRounds}),g=!0,B.info("init: memory.json written",{configPath:i,force:s,configCreated:g})):B.debug("init: memory.json already exists, skipping write",{configPath:i});}catch(f){B.warn("init: memory.json write failed (non-fatal)",{configPath:i,error:f instanceof Error?f.message:String(f)});}let S=new e(o);try{let f=await K.stat(o).then(()=>!0).catch(()=>!1);await S.initialize();let y=new Date().toISOString(),h=[["version","1.0.0"],["schemaVersion",String(a$2)],["createdAt",y],["defaultAgentId",c]];for(let[b,C]of h)try{S.run("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)",[b,C]);}catch(w){B.warn("init: meta insert failed",{key:b,error:w instanceof Error?w.message:String(w)});}let R=0;try{R=S.prepare("SELECT COUNT(*) as n FROM sqlite_master WHERE type IN ('table', 'index', 'trigger', 'view')").get()?.n??0;}catch(b){B.warn("init: tablesCreated count failed",{error:b instanceof Error?b.message:String(b)});}let v=0;try{v=S.prepare("SELECT id FROM schema_migrations").all().length;}catch(b){B.warn("init: migrationsApplied count failed",{error:b instanceof Error?b.message:String(b)});}return B.info("init complete",{agentId:c,workspaceDir:r,dbPath:o,configPath:i,configCreated:g,schemaVersion:a$2,durationMs:Date.now()-a}),{initialized:!0,dbPath:o,configPath:i,configCreated:g,schemaVersion:a$2,workspaceDir:r,tablesCreated:R,migrationsApplied:v,durationMs:Date.now()-a}}catch(f){throw new I(`init failed: ${f instanceof Error?f.message:String(f)}`,"INTERNAL",{cause:f instanceof Error?f.message:String(f)})}finally{S.close();}}var pe=Log.create({service:"memory.service.status"}),Rr=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"],Sr={};async function pt(t,e$1={},a=Sr){let r=t.agentId&&t.agentId.trim().length>0?t.agentId:void 0;if(pe.debug("status invoked",{agentId:r??"<global>"}),!t.dbPath||t.dbPath.length===0)throw new I("`ctx.dbPath` is required","INTERNAL");let o={initialized:false,capabilities:{embedding:false,graphLlm:false}},c={},s={},i=0,l=0,g=0,S,f,y,h=false,R,v="uninitialized",b=false,C=false,w=false,T,E=Rr.reduce((D,L)=>(D[L]=0,D),{}),M=new e(t.dbPath);try{await M.initialize(),i=M.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,l=M.query("SELECT COUNT(*) as c FROM nodes",[])[0]?.c??0,g=M.query("SELECT COUNT(*) as c FROM edges")[0]?.c??0;let j=M.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 _ of j){let O=_.category;O in E&&(E[O]=_.c);}c.facts=i,c.nodes=l,c.edges=g;try{C=M.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]).length>0;}catch(_){pe.debug("status: fts probe failed",{error:_ instanceof Error?_.message:String(_)});}h=!!t.config?.embeddingLlm,b=!1,w=M.healthCheck();try{let _=M.query("SELECT key, value FROM meta");for(let O of _)s[O.key]=O.value;}catch(_){pe.debug("status: meta read failed",{error:_ instanceof Error?_.message:String(_)});}let z=s.schema_version,J=s.extraction_version,d=s.lastSyncAt??s.lastSync,m=s.embeddingDims;S=z&&Number.parseInt(z,10)||void 0,f=J&&Number.parseInt(J,10)||void 0,y=d,R=m&&Number.parseInt(m,10)||void 0,i>0&&(s.index_state==="failed"?v="failed":y?h&&!R?v="partial":v="complete":v="stale");try{T=M.query("SELECT value FROM meta WHERE key = ?",["backend"])[0]?.value??"better-sqlite3";}catch{T="better-sqlite3";}}catch(D){if(D instanceof I)throw D;pe.warn("status: db phase failed; returning partial result",{dbPath:t.dbPath,error:D instanceof Error?D.message:String(D)}),T="unknown",w=false;}finally{M.close();}if(!a.skipLlm&&a$1.isInitialized()){let L=a$1.capabilities();o.initialized=true,o.capabilities={embedding:L.embedding===true,graphLlm:L.graphLlm===true},o.embeddingModel=o.capabilities.embedding?"configured":void 0,o.graphModel=o.capabilities.graphLlm?"configured":void 0;}if(!a.skipEmbeddingProbe&&!a.skipLlm&&o.initialized&&o.capabilities.embedding)try{let D=a$1.getEmbeddingLlm?.();if(D){let L=await probeEmbeddingDims(D,{timeoutMs:5e3});if(typeof L=="number"){R=L,s.embeddingDims=String(L);try{let P=new e(t.dbPath);try{await P.initialize();let j=P.getDb();syncMeta(j,[["embeddingDims",String(L)]]);}finally{P.close();}}catch{}}}}catch{}let u;return w?v==="uninitialized"&&(u="Run `easbot memory remember <content>` to add the first fact."):u="Run `easbot memory init` to initialize the database.",w&&(v??"uninitialized")==="failed"&&(w=false),pe.info("status complete",{dbPath:t.dbPath,agentId:r??"<global>",factsCount:i,nodesCount:l,edgesCount:g,healthy:w}),{package:"memory",agentId:r,dbPath:t.dbPath,configPath:He(t.workspaceDir),configExists:true,schemaVersion:S,extractionVersion:f,lastSyncAt:y,indexState:v,vectorEnabled:h,embeddingDims:R,llm:o,backend:T,counts:c,meta:s,recommendation:u,healthy:w,factsByCategory:E,kgScopeEnabled:b,factsCount:i,nodesCount:l,edgesCount:g,ftsAvailable:C}}var Dr=Log.create({service:"memory.service.doctor"}),We=100*1024*1024,yt=100*1024*1024,Cr={};function N(t,e,a,r,o){return {code:t.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),severity:e,name:t,message:a,details:o,durationMs:r,passed:e!=="error"}}async function ht(t,e$1={},a=Cr){if(Dr.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,l=Date.now();try{s=new e(t.dbPath),await s.initialize(),i=!0;let d=s.healthCheck(),m=N("database",d?"ok":"error",d?"database connected and writable":"database unhealthy",Date.now()-l,{dbPath:t.dbPath});r.push(m),o.push({name:m.name,passed:m.severity!=="error",message:m.message,details:m.details,severity:m.severity});}catch(d){let m=N("database","error",`database connection failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-l,{dbPath:t.dbPath});r.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}let g=Date.now();if(i&&s)try{let d=s.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]),m=d.length>0,_=N("fts",m?"ok":"warn",m?"FTS5 index available":"FTS5 index not found",Date.now()-g,m?{table:d[0]?.name}:void 0);r.push(_),o.push({name:_.name,passed:_.severity!=="error",message:_.message,details:_.details,severity:_.severity});}catch(d){let m=N("fts","error",`fts probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-g);r.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.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 S=Date.now(),f=!!t.config?.embeddingLlm,y=N("vector","ok",f?"embedding model available":"no embedding model configured (FTS-only mode, recall still functional)",Date.now()-S,{mode:f?"hybrid":"fts_only",model:f?"configured":"missing"});r.push(y),o.push({name:y.name,passed:true,message:y.message,details:y.details,severity:"ok"});let h=Date.now();if(i&&s)try{let d=["memory_facts","nodes","edges","meta"],m=s.query("SELECT name FROM sqlite_master WHERE type = ?",["table"]),_=new Set(m.map($=>$.name)),O=d.filter($=>!_.has($)),A=N("schema",O.length===0?"ok":"error",O.length===0?`schema complete (${d.length} tables)`:`missing tables: ${O.join(", ")}`,Date.now()-h,{required:d,existing:Array.from(_)});r.push(A),o.push({name:A.name,passed:A.severity!=="error",message:A.message,details:A.details,severity:A.severity});}catch(d){let m=N("schema","error",`schema probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-h);r.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.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 R=Date.now();try{let d=`${t.dbPath}-wal`,m=`${t.dbPath}-shm`,_=0,O=0;try{_=(await K.stat(d)).size;}catch{_=0;}try{O=(await K.stat(m)).size;}catch{O=0;}let A=_+O,$=A<=yt,U=N("lock",$?"ok":"warn",$?`no lock contention (wal+shm ${(A/1024).toFixed(1)} KB)`:`WAL/SHM files unusually large (${(A/1024/1024).toFixed(1)} MB > ${(yt/1024/1024).toFixed(0)} MB threshold)`,Date.now()-R,{walBytes:_,shmBytes:O});r.push(U),o.push({name:U.name,passed:U.severity!=="error",message:U.message,details:U.details,severity:U.severity});}catch(d){let m=N("lock","error",`lock probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-R);r.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}let v=Date.now();try{let d=ue.dirname(t.dbPath),m=await K.statfs(d),_=typeof m.bsize=="bigint"?Number(m.bsize)*m.bavail:m.bsize*m.bavail,O=_>=We,A=N("disk_space",O?"ok":"error",O?`sufficient disk space (${(_/1024/1024).toFixed(1)} MB available)`:`low disk space (${(_/1024/1024).toFixed(1)} MB < ${(We/1024/1024).toFixed(0)} MB threshold)`,Date.now()-v,{availableBytes:_,threshold:We});r.push(A),o.push({name:A.name,passed:A.severity!=="error",message:A.message,details:A.details,severity:A.severity});}catch(d){let m=N("disk_space","error",`disk_space probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-v);r.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}let b=Date.now();if(i&&s)try{let d=s.agentFilter(t.agentId),_=s.query(`SELECT COUNT(*) as c FROM memory_facts ${d.where}`,d.params)[0]?.c??0;if(_===0){let O=N("fact_node_consistency","info","no facts in db \u2014 nothing to check",Date.now()-b);r.push(O),o.push({name:O.name,passed:!0,message:O.message,severity:"info"});}else {let A=s.query(`SELECT COUNT(DISTINCT fn.fact_id) as c
61
+ FROM fact_nodes fn
62
+ INNER JOIN memory_facts mf ON mf.id = fn.fact_id
63
+ ${d.where}`,d.params)[0]?.c??0,$=_>0?A/_*100:0,U=$>=50?"ok":$>=30?"info":"warn",W=$>=50?`${$.toFixed(1)}% facts linked to KG nodes`:$>=30?`${$.toFixed(1)}% facts linked to KG nodes \u2014 run \`easbot memory remember\` to improve`:`${$.toFixed(1)}% facts linked to KG nodes \u2014 KG extraction may be disabled`,X=N("fact_node_consistency",U,W,Date.now()-b,{facts:_,linked:A,pct:$});r.push(X),o.push({name:X.name,passed:X.severity!=="error",message:X.message,details:X.details,severity:X.severity});}}catch(d){let m=N("fact_node_consistency","warn",`fact_node_consistency probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-b);r.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"warn"});}else {let d=N("fact_node_consistency","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let C=Date.now();if(i&&s)try{let m=s.query("SELECT COUNT(*) as c FROM nodes",[])[0]?.c??0;if(m===0){let _=N("node_embedding_coverage","info","no nodes in KG \u2014 nothing to check",Date.now()-C);r.push(_),o.push({name:_.name,passed:!0,message:_.message,severity:"info"});}else {let O=s.query("SELECT COUNT(*) as c FROM nodes WHERE embedding IS NOT NULL",[])[0]?.c??0,A=m>0?O/m*100:0,$=A>=50?"ok":A>=30?"info":"warn",U=A>=50?`${A.toFixed(1)}% nodes have embedding (${O}/${m})`:A>=30?`${A.toFixed(1)}% nodes have embedding (${O}/${m}) \u2014 GraphRAG entity vector partial`:`${A.toFixed(1)}% nodes have embedding (${O}/${m}) \u2014 GraphRAG entity vector disabled`,W=N("node_embedding_coverage",$,U,Date.now()-C,{total:m,withEmbedding:O,pct:A});r.push(W),o.push({name:W.name,passed:W.severity!=="error",message:W.message,details:W.details,severity:W.severity});}}catch(d){let m=N("node_embedding_coverage","warn",`node_embedding_coverage probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-C);r.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"warn"});}else {let d=N("node_embedding_coverage","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let w=Date.now();if(i&&s)try{let m=s.query(`SELECT fn.fact_id, fn.node_id
64
+ FROM fact_nodes fn
65
+ LEFT JOIN nodes n ON fn.node_id = n.id
66
+ WHERE n.id IS NULL
67
+ LIMIT 100`).map(O=>`${O.fact_id}->${O.node_id}`),_=N("orphan",m.length===0?"ok":"warn",m.length===0?"no orphan KG references (fact_nodes all resolved)":`${m.length} orphan fact_nodes references: ${m.slice(0,5).join(", ")}${m.length>5?", ...":""}`,Date.now()-w,{count:m.length});r.push(_),o.push({name:_.name,passed:_.severity!=="error",message:_.message,details:_.details,severity:_.severity});}catch(d){let m=N("orphan","warn",`orphan probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-w);r.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.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 T=Date.now(),E={"better-sqlite3":false,"node:sqlite":false,"@tursodatabase/database":false};try{let d=createRequire(import.meta.url);try{d.resolve("better-sqlite3"),E["better-sqlite3"]=!0;}catch{}E["node:sqlite"]=typeof process.versions.sqlite=="string";try{d.resolve("@tursodatabase/database"),E["@tursodatabase/database"]=!0;}catch{}}catch{}let M=E["better-sqlite3"]||E["node:sqlite"],u=N("backend",M?"ok":"error",M?`SQLite backend available (better-sqlite3: ${E["better-sqlite3"]}, node:sqlite: ${E["node:sqlite"]})`:"no SQLite backend available (install better-sqlite3 or use Node 22.5+)",Date.now()-T,E);r.push(u),o.push({name:u.name,passed:u.severity!=="error",message:u.message,details:u.details,severity:u.severity});let p=Date.now();if(i&&s)try{let d=s.query("SELECT COUNT(*) as c FROM embedding_cache")[0],m=s.agentFilter(t.agentId),_=s.query(`SELECT COUNT(*) as c FROM memory_facts ${m.where}`,m.params)[0],O=d?.c??0,A=_?.c??0,$=Math.max(0,O-A),U=$>0,W=N("embedding_cache_unused","info",U?`by design: ${$} 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()-p,{cacheCount:O,factsCount:A,unused:$,policy:"global_content_hash_dedup"});r.push(W),o.push({name:W.name,passed:!U,message:W.message,details:W.details,severity:"info"});}catch(d){let m=N("embedding_cache_unused","info",`embedding_cache_unused probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-p);r.push(m),o.push({name:m.name,passed:true,message:m.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 D=Date.now(),L;if(i&&s)try{let d=s.query("SELECT value FROM meta WHERE key = ?",["embeddingDims"]);L=d[0]?.value&&Number.parseInt(d[0].value,10)||void 0;}catch{}let P;if(a.skipLlm||!a$1.isInitialized()||!a$1.capabilities().embedding)P=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","llm not initialized; probe skipped",Date.now()-D);else if(a.skipEmbeddingProbe)P=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe skipped (--skip-embedding-probe)",Date.now()-D);else try{let d=a$1.getEmbeddingLlm?.();if(!d)P=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","embedding llm not exposed; probe skipped",Date.now()-D);else {let m=await probeEmbeddingDims(d,{timeoutMs:5e3});typeof m!="number"?P=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe failed (network / model error)",Date.now()-D):L===void 0?P=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe=${m}, meta missing \u2014 next status will sync`,Date.now()-D):m!==L?P=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"warn",`probe=${m}, meta=${L} \u2014 mismatch`,Date.now()-D,{probe:m,meta:L}):P=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"ok",`probe=${m}, meta=${L} \u2014 consistent`,Date.now()-D);}}catch(d){P=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe threw: ${d instanceof Error?d.message:String(d)}`,Date.now()-D);}r.push({...P,details:P.details??void 0,passed:P.severity!=="error"}),o.push({name:P.name,passed:P.severity!=="error",message:P.message,details:P.details??void 0,severity:P.severity});let j;if(i&&s){let d=Date.now();try{let{issues:m,stats:_}=s.checkIntegrity();j=_;for(let O of m)r.push(N("integrity_stats",O.severity,O.message,0,{source:"database.checkIntegrity"}));}catch(m){r.push(N("integrity_stats","warn",`db integrity check failed: ${m instanceof Error?m.message:String(m)}`,Date.now()-d));}}let z=!r.some(d=>d.severity==="error");s&&s.close();let J=Date.now()-c;return {healthy:z,checks:r,legacyChecks:o,durationMs:J,integrityStats:j,backendAvailable:E}}var Ge={name:"recall",scope:"read",schema:we,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 r=we.parse(t);if(!e.agentId?.trim())throw new Error("recall: agentId is required");return tt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var je={name:"remember",scope:"write",schema:Re,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 r=Re.parse(t);if(!e.agentId?.trim())throw new Error("remember: agentId is required");return nt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var Be={name:"update",scope:"write",schema:Se,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Update an existing memory fact (atomic; preserves factId + KG associations).",readOnlyHint:false,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=Se.parse(t);if(!e.agentId?.trim())throw new Error("update: agentId is required");return ot({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var ze={name:"forget",scope:"write",schema:Ie,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 r=Ie.parse(t);if(!e.agentId?.trim())throw new Error("forget: agentId is required");return at({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var Qe={name:"extract",scope:"write",schema:Me,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 r=Me.parse(t);if(!e.agentId?.trim())throw new Error("extract: agentId is required");return it({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var Ke={name:"consolidate",scope:"admin",schema:_e,annotations:{localOnly:true,requiresAgentId:true,defaultDescription:"Run consolidation pipeline: dedup \u2192 archive.",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let r=_e.parse(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 ct({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},r)}};var Ve={name:"sync",scope:"admin",schema:Oe,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 r=Oe.parse(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 lt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},r)}};var Je={name:"graph_query",scope:"read",schema:ve,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"BFS KG neighbor walk from nodeId (default depth=2, maxNodes=100, maxEdgesPerNode=10/100); CLI may also use name fragment via `query`.",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=ve.parse(t),o=e.agentId?.trim()||"default";return ut({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:o},r)}};var Ye={name:"status",scope:"read",schema:De,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 r=De.parse(t??{})??{}??{};return pt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var Xe={name:"doctor",scope:"admin",schema:Ce,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 r=Ce.parse(t??{})??{}??{};if(!e.isTrustedLocal)throw new Error("doctor: only trusted local process can invoke this op");return ht({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},r)}};var Ze={name:"init",scope:"admin",schema:Ne,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 r=Ne.parse(t??{})??{}??{};return ft({workspaceDir:r.workspaceDir??e.workspaceDir??"",rootDir:r.workspaceDir??e.workspaceDir??"",dbPath:r.dbPath??e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId??""},r)}};var bt={[Ge.name]:Ge,[je.name]:je,[Be.name]:Be,[ze.name]:ze,[Qe.name]:Qe,[Ke.name]:Ke,[Ve.name]:Ve,[Je.name]:Je,[Ye.name]:Ye,[Xe.name]:Xe,[Ze.name]:Ze},Nr=Object.values(bt);function Or(t,e,a){if(t.annotations.localOnly&&!e.isTrustedLocal)throw new Error(`MEMORY:executeOp: op "${a}" 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 "${a}" requires agentId`);e.agentId=r;}}async function Qa(t,e,a){let r=bt[t];if(!r)throw new Error(`executeOp: unknown op "${t}"; available: ${Nr.map(c=>c.name).join(", ")}`);return Or(r,a,t),await r.handler(e,a)}function Ar(t){let e=t.dbPath??"";return {workspaceDir:t.workspaceDir??"",database:{path:e},embeddingLlm:a$1.getEmbeddingLlm(),graphLlm:a$1.getGraphLlm(),search:DEFAULT_SEARCH_CONFIG,indexer:{batchSize:20,ignorePatterns:[],incremental:true},archiveDays:30,shortTermMaxRounds:20}}function rs(t,e,a={}){let r=j(e),o=Locale.resolveLocaleLang(a.locale);return {agentId:t,dbPath:r,workspaceDir:e,rootDir:e,config:Ar({dbPath:r,workspaceDir:e}),isTrustedLocal:true,locale:o,remote:false,...a}}export{Ar as A,rs as B,ee as a,tt as b,we as c,Re as d,Se as e,Ie as f,Me as g,_e as h,ve as i,De as j,Ce as k,Ne as l,Oe as m,nt as n,ot as o,at as p,it as q,ct as r,lt as s,ut as t,ft as u,pt as v,ht as w,bt as x,Nr as y,Qa as z};
@@ -1,4 +1,4 @@
1
- import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Filesystem}from'@easbot/utils';import {createSyncSqliteConnection}from'@easbot/database';var c=Log.create({service:"memory-schema-migrations"}),m=1,R=[{id:1,description:"v1 baseline: memory_facts / memory_vectors / embedding_cache / memory_facts_fts / nodes / edges / meta\uFF08\u4E0E v0.3.x createTables \u8F93\u51FA\u5BF9\u9F50\uFF0C\u8001 db \u8DD1\u8BE5\u8FC1\u79FB\u4E0D\u7834\u574F\u73B0\u6709\u8868\uFF09",up:[`CREATE TABLE IF NOT EXISTS memory_facts (
1
+ import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Filesystem}from'@easbot/utils';import {createSyncSqliteConnection}from'@easbot/database';var c=Log.create({service:"memory-schema-migrations"}),m=1,f=[{id:1,description:"v1 baseline: memory_facts / memory_vectors / embedding_cache / memory_facts_fts / nodes / edges / meta\uFF08\u4E0E v0.3.x createTables \u8F93\u51FA\u5BF9\u9F50\uFF0C\u8001 db \u8DD1\u8BE5\u8FC1\u79FB\u4E0D\u7834\u574F\u73B0\u6709\u8868\uFF09",up:[`CREATE TABLE IF NOT EXISTS memory_facts (
2
2
  id TEXT PRIMARY KEY,
3
3
  agent_id TEXT NOT NULL,
4
4
  session_id TEXT,
@@ -32,12 +32,11 @@ import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Filesystem}from'@easbot/utils';
32
32
  id INTEGER PRIMARY KEY AUTOINCREMENT,
33
33
  name TEXT NOT NULL,
34
34
  type TEXT NOT NULL,
35
- owner_agent_id TEXT,
36
35
  properties TEXT,
37
36
  embedding BLOB,
38
37
  createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
39
38
  updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP
40
- )`,"CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name)","CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type)","CREATE INDEX IF NOT EXISTS idx_nodes_owner_agent_id ON nodes(owner_agent_id)","CREATE INDEX IF NOT EXISTS idx_nodes_embedding ON nodes(embedding) WHERE embedding IS NOT NULL","CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_name_type ON nodes(name, type)",`CREATE TABLE IF NOT EXISTS fact_nodes (
39
+ )`,"CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name)","CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type)","CREATE INDEX IF NOT EXISTS idx_nodes_embedding ON nodes(embedding) WHERE embedding IS NOT NULL","CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_name_type ON nodes(name, type)",`CREATE TABLE IF NOT EXISTS fact_nodes (
41
40
  fact_id TEXT NOT NULL,
42
41
  node_id INTEGER NOT NULL,
43
42
  source TEXT NOT NULL DEFAULT 'kg_extract',
@@ -58,10 +57,10 @@ import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Filesystem}from'@easbot/utils';
58
57
  )`,"CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)","CREATE INDEX IF NOT EXISTS idx_edges_relation ON edges(relation)","CREATE UNIQUE INDEX IF NOT EXISTS idx_edges_unique ON edges(source, target, relation)",`CREATE TABLE IF NOT EXISTS meta (
59
58
  key TEXT PRIMARY KEY,
60
59
  value TEXT
61
- )`,"ALTER TABLE nodes ADD COLUMN embedding BLOB","CREATE INDEX IF NOT EXISTS idx_nodes_embedding ON nodes(embedding) WHERE embedding IS NOT NULL"]}];function l(n,e=m,r={}){n.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
60
+ )`,"ALTER TABLE nodes ADD COLUMN embedding BLOB","CREATE INDEX IF NOT EXISTS idx_nodes_embedding ON nodes(embedding) WHERE embedding IS NOT NULL"]}];function g(n,e=m,r={}){n.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
62
61
  id INTEGER PRIMARY KEY,
63
62
  applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
64
- )`);let t=n.prepare("SELECT id FROM schema_migrations").all(),s=new Set(t.map(i=>i.id)),a={applied:[],pending:[],errors:[],currentVersion:t.length===0?0:Math.max(...t.map(i=>i.id)),targetVersion:e};for(let i of R){if(i.id>e)break;if(s.has(i.id)){a.pending.push(i.id);continue}if(r.dryRun){a.applied.push(i.id);continue}try{f(n,i.up),n.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(i.id),s.add(i.id),a.applied.push(i.id),c.info("migration applied",{id:i.id,description:i.description});}catch(o){let d=o instanceof Error?o.message:String(o),T=i.up[0]??"";a.errors.push({migrationId:i.id,sql:T,error:d}),c.warn("migration step failed",{id:i.id,error:d,sqlCount:i.up.length});}}return a}function f(n,e){for(let r of e)try{n.exec(r);}catch(t){let s=t instanceof Error?t.message:String(t);if(O(s)){c.debug("migration: column already exists, skipping",{sql:r.slice(0,80)});continue}throw t}}function O(n){return /duplicate column name/i.test(n)}function _(n){try{let e=n.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(r=>r.id))}catch{return 0}}var N=Log.create({service:"memory-database"}),u=class{constructor(e){a(this,"db",null);a(this,"storagePath");a(this,"backend","better-sqlite3");a(this,"initialized",false);a(this,"initPromise",null);this.storagePath=e===":memory:"?e:Filesystem.normalize(e);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize();try{await this.initPromise,this.initialized=!0;}catch(e){try{this.db&&this.db.close();}catch{}throw this.db=null,this.initPromise=null,e}}}async doInitialize(){try{let e=this.openConnection();e.initialize(),this.db=e,this.applyPragmas(),this.runAllMigrations();}catch(e){let r=e instanceof Error?e.message:String(e);throw N.error("Database initialization failed",{error:r}),e}}openConnection(){return createSyncSqliteConnection({path:this.storagePath,backend:this.backend,walMode:true,foreignKeys:true,busyTimeoutMs:5e3})}applyPragmas(){if(this.db)try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("foreign_keys = ON");}catch(e){N.warn("Failed to apply memory PRAGMAs",{error:String(e)});}}runAllMigrations(){if(!this.db)throw new Error("Database not initialized");let e=l(this.db,m);if(e.errors.length>0){let r=e.errors.map(t=>`migration ${t.migrationId}: ${t.error}`).join("; ");throw new Error(`Some migrations failed: ${r}`)}}query(e,r){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let t=this.db.prepare(e);return r?t.all(...r):t.all()}catch(t){throw new Error(`Query failed: ${t.message}`)}}agentFilter(e){return typeof e=="string"&&e.trim().length>0?{where:"WHERE agent_id = ?",params:[e.trim()]}:{where:"",params:[]}}run(e,r){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let t=this.db.prepare(e),s=r?t.run(...r):t.run();return {lastID:Number(s.lastInsertRowid),changes:s.changes}}catch(t){throw new Error(`Write failed: ${t.message}`)}}transaction(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db.transaction(e)()}prepare(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db.prepare(e)}exec(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");this.db.exec(e);}getDb(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db}getPath(){return this.storagePath}getSchemaVersion(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return _(this.db)}close(){if(this.db){try{this.db.close();}catch(e){N.warn("Failed to close memory database",{error:String(e)});}this.db=null,this.initialized=false,this.initPromise=null;}}healthCheck(){try{return this.db?(this.db.exec("SELECT 1"),!0):!1}catch{return false}}checkIntegrity(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");let e=S=>this.db.prepare(S).get().c,r={memory_facts:e("SELECT COUNT(*) as c FROM memory_facts"),memory_vectors:e("SELECT COUNT(*) as c FROM memory_vectors"),embedding_cache:e("SELECT COUNT(*) as c FROM embedding_cache"),memory_facts_fts:e("SELECT COUNT(*) as c FROM memory_facts_fts"),nodes:e("SELECT COUNT(*) as c FROM nodes"),edges:e("SELECT COUNT(*) as c FROM edges"),fact_nodes:e("SELECT COUNT(*) as c FROM fact_nodes"),meta:e("SELECT COUNT(*) as c FROM meta"),schema_migrations:e("SELECT COUNT(*) as c FROM schema_migrations")},t=[],s=e(`
63
+ )`);let t=n.prepare("SELECT id FROM schema_migrations").all(),s=new Set(t.map(i=>i.id)),a={applied:[],pending:[],errors:[],currentVersion:t.length===0?0:Math.max(...t.map(i=>i.id)),targetVersion:e};for(let i of f){if(i.id>e)break;if(s.has(i.id)){a.pending.push(i.id);continue}if(r.dryRun){a.applied.push(i.id);continue}try{I(n,i.up),n.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(i.id),s.add(i.id),a.applied.push(i.id),c.info("migration applied",{id:i.id,description:i.description});}catch(o){let d=o instanceof Error?o.message:String(o),T=i.up[0]??"";a.errors.push({migrationId:i.id,sql:T,error:d}),c.warn("migration step failed",{id:i.id,error:d,sqlCount:i.up.length});}}return a}function I(n,e){for(let r of e)try{n.exec(r);}catch(t){let s=t instanceof Error?t.message:String(t);if(O(s)){c.debug("migration: column already exists, skipping",{sql:r.slice(0,80)});continue}throw t}}function O(n){return /duplicate column name/i.test(n)}function u(n){try{let e=n.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(r=>r.id))}catch{return 0}}var N=Log.create({service:"memory-database"}),_=class{constructor(e){a(this,"db",null);a(this,"storagePath");a(this,"backend","better-sqlite3");a(this,"initialized",false);a(this,"initPromise",null);this.storagePath=e===":memory:"?e:Filesystem.normalize(e);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize();try{await this.initPromise,this.initialized=!0;}catch(e){try{this.db&&this.db.close();}catch{}throw this.db=null,this.initPromise=null,e}}}async doInitialize(){try{let e=this.openConnection();e.initialize(),this.db=e,this.applyPragmas(),this.runAllMigrations();}catch(e){let r=e instanceof Error?e.message:String(e);throw N.error("Database initialization failed",{error:r}),e}}openConnection(){return createSyncSqliteConnection({path:this.storagePath,backend:this.backend,walMode:true,foreignKeys:true,busyTimeoutMs:5e3})}applyPragmas(){if(this.db)try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("foreign_keys = ON");}catch(e){N.warn("Failed to apply memory PRAGMAs",{error:String(e)});}}runAllMigrations(){if(!this.db)throw new Error("Database not initialized");let e=g(this.db,m);if(e.errors.length>0){let r=e.errors.map(t=>`migration ${t.migrationId}: ${t.error}`).join("; ");throw new Error(`Some migrations failed: ${r}`)}}query(e,r){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let t=this.db.prepare(e);return r?t.all(...r):t.all()}catch(t){throw new Error(`Query failed: ${t.message}`)}}agentFilter(e){return typeof e=="string"&&e.trim().length>0?{where:"WHERE agent_id = ?",params:[e.trim()]}:{where:"",params:[]}}run(e,r){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let t=this.db.prepare(e),s=r?t.run(...r):t.run();return {lastID:Number(s.lastInsertRowid),changes:s.changes}}catch(t){throw new Error(`Write failed: ${t.message}`)}}transaction(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db.transaction(e)()}prepare(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db.prepare(e)}exec(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");this.db.exec(e);}getDb(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db}getPath(){return this.storagePath}getSchemaVersion(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return u(this.db)}close(){if(this.db){try{this.db.close();}catch(e){N.warn("Failed to close memory database",{error:String(e)});}this.db=null,this.initialized=false,this.initPromise=null;}}healthCheck(){try{return this.db?(this.db.exec("SELECT 1"),!0):!1}catch{return false}}checkIntegrity(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");let e=p=>this.db.prepare(p).get().c,r={memory_facts:e("SELECT COUNT(*) as c FROM memory_facts"),memory_vectors:e("SELECT COUNT(*) as c FROM memory_vectors"),embedding_cache:e("SELECT COUNT(*) as c FROM embedding_cache"),memory_facts_fts:e("SELECT COUNT(*) as c FROM memory_facts_fts"),nodes:e("SELECT COUNT(*) as c FROM nodes"),edges:e("SELECT COUNT(*) as c FROM edges"),fact_nodes:e("SELECT COUNT(*) as c FROM fact_nodes"),meta:e("SELECT COUNT(*) as c FROM meta"),schema_migrations:e("SELECT COUNT(*) as c FROM schema_migrations")},t=[],s=e(`
65
64
  SELECT COUNT(*) as c FROM fact_nodes fn
66
65
  LEFT JOIN nodes n ON n.id = fn.node_id
67
66
  WHERE n.id IS NULL
@@ -75,4 +74,4 @@ import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Filesystem}from'@easbot/utils';
75
74
  EXCEPT
76
75
  SELECT id FROM memory_facts
77
76
  )
78
- `);d>0&&t.push({severity:"warn",message:`FTS out of sync (orphan entries): ${d}`});let T=e("SELECT COUNT(*) as c FROM (SELECT id, COUNT(*) as c FROM memory_facts GROUP BY id HAVING c > 1)");T>0&&t.push({severity:"error",message:`duplicate fact ids: ${T}`});let g=e("SELECT COUNT(*) as c FROM memory_facts WHERE content IS NULL OR content = ''");return g>0&&t.push({severity:"error",message:`memory_facts with null/empty content: ${g}`}),{issues:t,stats:r}}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,r){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,r);}};export{m as a,R as b,l as c,_ as d,u as e};
77
+ `);d>0&&t.push({severity:"warn",message:`FTS out of sync (orphan entries): ${d}`});let T=e("SELECT COUNT(*) as c FROM (SELECT id, COUNT(*) as c FROM memory_facts GROUP BY id HAVING c > 1)");T>0&&t.push({severity:"error",message:`duplicate fact ids: ${T}`});let l=e("SELECT COUNT(*) as c FROM memory_facts WHERE content IS NULL OR content = ''");return l>0&&t.push({severity:"error",message:`memory_facts with null/empty content: ${l}`}),{issues:t,stats:r}}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,r){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,r);}};export{m as a,f as b,g as c,u as d,_ as e};
@@ -0,0 +1,64 @@
1
+ import {x as x$1,z,l,k,j,i,m,h,g,f as f$1,e,d,c,A as A$1}from'./chunk-C3Z455VR.mjs';import {extendKnownErrorCodes,ToolRegistry,createAndStartStdioServer,formatFailClosed}from'@easbot/mcp';import {Log,Locale,TruncateContent}from'@easbot/utils';var ae=Log.create({service:"memory-format-truncate"}),Z="**`";var V=24e3,ee=25e3;async function y(e,n={}){let r=n.softLimit??V,s=n.hardCeiling??ee,o=n.toolName??"memory",c=n.writeToDisk!==false;if(e.length<=r)return {content:e,truncated:false};let i=e.slice(0,s),t=i.lastIndexOf(`
2
+ ${Z}`),a=i.lastIndexOf(`
3
+ `),u;t>s*.5?u=t:a>0?u=a:u=-1;let d=u>0?i.slice(0,u):i,g=d+"\n\n... (output truncated to budget; the source above is complete and verbatim \u2014 treat it as already Read. For any area not covered, make ANOTHER `<tool>` targeting those names \u2014 do NOT Read these files.)";if(!c)return {content:g,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-d.length}/${e.length} characters truncated ...`};try{let p=await TruncateContent.truncate(e,{maxChars:d.length,direction:"head",label:`${o}-output`});return p.truncated?{content:g,truncated:!0,outputPath:p.outputPath,hint:TruncateContent.formatHint(p),info:`... ${p.removedLength}/${p.originalLength} characters truncated ...`}:{content:g,truncated:!0,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-d.length}/${e.length} characters truncated ...`}}catch(p){return ae.warn("TruncateContent.truncate failed, returning without disk hint",{error:p instanceof Error?p.message:String(p)}),{content:g,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-d.length}/${e.length} characters truncated ...`}}}function f(e,n={}){let r=n.softLimit??V,s=n.hardCeiling??ee;if(e.length<=r)return {content:e,truncated:false};let o=e.slice(0,s),c=o.lastIndexOf(`
4
+ ${Z}`),i=o.lastIndexOf(`
5
+ `),t;c>s*.5?t=c:i>0?t=i:t=-1;let a=t>0?o.slice(0,t):o;return {content:a+`
6
+
7
+ ... (output truncated; tail dropped at section boundary)`,truncated:true,outputPath:"",hint:"",info:`... ${e.length-a.length}/${e.length} characters truncated ...`}}function se(e,n){if(!e||e.length===0)return null;let r=e.filter(o=>n.has(o.path));return r.length===0?null:`\u26A0\uFE0F Index may be stale for: ${r.map(o=>`${o.path} (edited pending)`).join(", ")}
8
+
9
+ `}function b(e,n,r={}){return (te[e]??te.default).replace(/<(\w+)>/g,(o,c)=>c==="tool"?n:r[c]??`<${c}>`)}var te={recall:"If you need more facts, make ANOTHER `<tool>` query with a different scope / interval.\nIf you have enough context, proceed with the current task. Do NOT call `<tool>` again for the same query.",remember:"Memory persisted. To recall it later, use `<tool>` with the same query.\nDo NOT call `<tool>` again to verify \u2014 the fact is already in the database.",forget:"Memory deleted. To verify, run `<tool>` with the same filter (no results expected).\nIf you deleted too much, the data is gone (no auto-restore).",graph_query:"If you need to explore further, make ANOTHER `<tool>` from a different start node or depth.\nOtherwise, the graph is complete for this scope.",status:"Status snapshot. To inspect a specific fact, use `<tool>` (recall) with its id.\nOtherwise, this is a complete read.",consolidate:"Consolidation done. To inspect the new facts, use `<tool>` with the same agentId.\nIf you want to undo, archives are in <archive_dir>.",doctor:"Doctor report. To fix a failing check, run with `repair=true`.\nRe-run after fix to confirm.",default:"If you need more, make ANOTHER `<tool>` with refined parameters.\nOtherwise, this is a complete read."};function ie(e){let n=Array.isArray(e.edges)?e.edges.length:0;return ` - node #${e.id}: ${e.name} (${e.type}) [edges: ${n}]`}function ne(e,n,r,s){let o=e.tags&&e.tags.length>0?`
10
+ - tags: ${e.tags.join(", ")}`:"",c=e.sessionId?`
11
+ - session: ${e.sessionId}`:"",i=e.msgId?`
12
+ - msg: ${e.msgId}`:"",t=typeof n=="number"?`
13
+ - score: ${n.toFixed(3)}${r?` (${r})`:""}`:"",a=e.truncated?" [truncated]":"",u="";if(s&&s.length>0){let d=s.map(ie);u=`
14
+ - linked KG nodes (${s.length}) \u2014 use \`graph_query(nodeId=<id>)\` for full relation graph:
15
+ ${d.join(`
16
+ `)}`;}return [`### \`${e.id}\`${a}`,` - agentId: ${e.agentId}`,` - category: ${e.category}`,` - importance: ${e.importance}`,` - createdAt: ${e.createdAt}`,` - updatedAt: ${e.updatedAt}`,` - source: ${e.source}${t}${o}${c}${i}${u}`,"",e.content,""].join(`
17
+ `)}async function v(e,n){let r=n.toolName??"memory_recall",s=`**\`memory_recall:${n.query.slice(0,40).replace(/[^a-zA-Z0-9_]/g,"_")}\`**`,o=se(n.pendingFiles,new Set),i=[`Found ${e.total} fact(s) for query "${n.query}" (agentId=${n.agentId}, scope=${n.scope}):`,"",o??"",s].join(`
18
+ `),t=new Map;for(let m of e.hits){let g=m.fact.category;t.has(g)||t.set(g,[]),t.get(g).push(m);}let a=Array.from(t.entries()).map(([m,g])=>{let p=`**\`category:${m}\`**`,D=g.map(w=>ne(w.fact,w.score,w.source,w.nodes)).join(`
19
+ `);return `${p}
20
+
21
+ ${D}`}).join(`
22
+ `),u=e.warnings&&e.warnings.length>0?`
23
+
24
+ \u26A0\uFE0F warnings:
25
+ ${e.warnings.map(m=>` - ${m}`).join(`
26
+ `)}
27
+ `:"",d=`${i}
28
+
29
+ ${a}${u}
30
+
31
+ ${b("recall",r)}`;return n.sync?f(d,{}).content:(await y(d,{toolName:r,writeToDisk:n.writeToDisk})).content}async function N(e,n={}){let r=n.toolName??"memory_remember",s=`**\`memory_remember:${e.fact.id}\`**`,o=ne(e.fact),c=e.nodeIds??[],i=c.length>0?`
32
+ - linked KG nodes: ${c.join(", ")}
33
+ `:"",t=`${s}
34
+
35
+ ${o}${i}
36
+
37
+ ${b("remember",r)}`;return n.sync?f(t,{}).content:(await y(t,{toolName:r,writeToDisk:n.writeToDisk})).content}async function _(e,n={}){let r=n.toolName??"memory_forget",s="**`memory_forget:result`**",o=e.dryRun?"**DRY RUN** \u2014 no facts were actually deleted. Run again without dryRun to execute.":`Deleted ${e.deletedCount} fact(s).`,c=e.truncatedCount>0?` (truncated: ${e.truncatedCount} more, re-run with narrower filter)`:"",i=[s,"",o+c,"",e.deletedIds.length>0?`deleted ids:
38
+ ${e.deletedIds.map(t=>` - ${t}`).join(`
39
+ `)}`:"(no ids to show)","",b("forget",r)].join(`
40
+ `);return n.sync?f(i,{}).content:(await y(i,{toolName:r,writeToDisk:n.writeToDisk})).content}async function A(e,n={}){let r=n.toolName??"memory_graph_query",s=`**\`memory_graph_query:scope=${e.scope}\`**`,o=e.nodes.map(t=>` - node #${t.id}: ${t.name} (${t.type})${t.ownerAgentId?` [owner=${t.ownerAgentId}]`:" [shared]"}`).join(`
41
+ `),c=e.edges.map(t=>` - edge #${t.id}: ${t.source} --${t.relation}--> ${t.target}`).join(`
42
+ `),i=[s,"",`nodes (${e.nodes.length}${e.truncated?` / total ${e.totalNodes}`:""}):`,o||" (none)","",`edges (${e.edges.length}${e.truncated?` / total ${e.totalEdges}`:""}):`,c||" (none)","",b("graph_query",r)].join(`
43
+ `);return n.sync?f(i,{}).content:(await y(i,{toolName:r,writeToDisk:n.writeToDisk})).content}async function M(e,n={}){let r=n.toolName??"memory_status",c=["**`memory_status`**","",`dbPath: ${e.dbPath}`,`workspaceDir: ${e.workspaceDir}`,`factsCount: ${e.factsCount}`,`nodesCount: ${e.nodesCount} (KG nodes)`,`edgesCount: ${e.edgesCount} (KG edges)`,`ftsAvailable: ${e.ftsAvailable?"yes":"no"}`,`vectorEnabled: ${e.vectorEnabled?"yes":"no"}`,`kgScopeEnabled: ${e.kgScopeEnabled?"yes":"no"}`,`healthy: ${e.healthy?"yes":"no"}`,"","factsByCategory:",...Object.entries(e.factsByCategory).map(([i,t])=>` - ${i}: ${t}`),"","meta:",...Object.entries(e.meta).map(([i,t])=>` - ${i}: ${t}`),"",b("status",r)].join(`
44
+ `);return n.sync?f(c,{}).content:(await y(c,{toolName:r,writeToDisk:n.writeToDisk})).content}async function O(e,n={}){let r=n.toolName??"memory_consolidate",o=["**`memory_consolidate:result`**","",`total facts scanned: ${e.totalFacts}`,`deduped (merged): ${e.dedupedCount}`,`compressed: ${e.compressedCount}`,`archived to archive/: ${e.archivedCount}`,`skipped (no change): ${e.skippedCount}`,`duration: ${e.durationMs}ms`,"",b("consolidate",r)].join(`
45
+ `);return n.sync?f(o,{}).content:(await y(o,{toolName:r,writeToDisk:n.writeToDisk})).content}var x=20;async function P(e,n={}){let r=n.toolName??"memory_sync",o=[`**\`memory_sync:${e.dryRun?"DRY_RUN":"OK"}\`**`,"",`windowDays: ${e.windowDays} (threshold: ${e.archiveThreshold})`,"","## Stage A (db \u2192 .md)",`- generated: ${e.generatedCount}`,`- skipped (idempotent): ${e.skippedCount}`,`- failed (best-effort): ${e.failedGenerateCount}`,"","## Stage B (active/ \u2192 archive/)",`- ${e.dryRun?"would archive":"archived"}: ${e.archivedCount}`];if(e.archivedRecords.length>0){o.push("","### Archived records:");let i=e.archivedRecords.slice(0,x);for(let t of i)o.push(`- ${t.firstFactId} (${t.firstCreatedAt})`),o.push(` - source: \`${t.source}\``),o.push(` - target: \`${t.target}\``);e.archivedRecords.length>x&&o.push(`... and ${e.archivedRecords.length-x} more (use --json for full list)`);}o.push("",`duration: ${e.durationMs}ms`,"",b("sync",r));let c=o.join(`
46
+ `);return n.sync?f(c,{}).content:(await y(c,{toolName:r,writeToDisk:n.writeToDisk})).content}async function L(e,n={}){let r=n.toolName??"memory_doctor",s=`**\`memory_doctor:${e.healthy?"OK":"ISSUES"}\`**`,o=t=>t?"\u2705":"\u274C",c=e.checks.map(t=>`${o(t.passed)} ${t.name}: ${t.message}`).join(`
47
+ `),i=[s,"",c,"",b("doctor",r)].join(`
48
+ `);return n.sync?f(i,{}).content:(await y(i,{toolName:r,writeToDisk:n.writeToDisk})).content}async function $(e,n,r={}){let s=n,o=typeof s.kind=="string";switch((o?s:{kind:e}).kind){case "recall":{let i=o?{hits:s.hits,total:s.totalCount??s.total??0,truncated:s.truncated??false}:n;return v(i,{...r,query:s.query??r.query??"",agentId:s.agentId??r.agentId??"",scope:s.scope??r.scope??"agent_only"})}case "remember":{let i=o?{fact:s.fact,nodeIds:s.nodeIds}:n;return N(i,r)}case "forget":return _(o?s:n,r);case "graph_query":return A(o?s:n,r);case "status":return M(o?s:n,r);case "consolidate":return O(o?s:n,r);case "sync":return P(o?s:n,r);case "doctor":return L(o?s:n,r);default:throw new Error(`renderOperationMarkdown: unsupported op "${e}"`)}}var E=Log.create({service:"memory-mcp-stdio"});function Re(e){let n=new Map,r=e.isRemote??true,s=!r;function o(t){let a=Locale.resolveLocaleLang();return {agentId:t.agentId??e.agentId,isTrustedLocal:t.isTrustedLocal??s,remote:r,locale:a,dbPath:e.dbPath,workspaceDir:e.workspaceDir,rootDir:e.workspaceDir,config:A$1({agentId:e.agentId,dbPath:e.dbPath})}}function c(t,a){return {content:[{type:"text",text:t}],isError:a}}function i(t){return formatFailClosed(t,s)}return n.set("recall",async t=>{try{let a=t,u=o({agentId:a.agentId}),d=await z("recall",t,u);return {content:[{type:"text",text:await $("recall",d,{toolName:"memory_recall",query:a.query,agentId:a.agentId??e.agentId,scope:a.scope??"agent_only"})}]}}catch(a){return c(i(a),true)}}),n.set("remember",async t=>{try{let u=o({agentId:t.agentId}),d=await z("remember",t,u);return {content:[{type:"text",text:await $("remember",d,{toolName:"memory_remember"})}]}}catch(a){return c(i(a),true)}}),n.set("update",async t=>{try{let u=o({agentId:t.agentId}),d=await z("update",t,u),m=d.fieldsUpdated.length>0?d.fieldsUpdated.join(", "):"(no-op)",g=d.contentChanged?" (embedding rewritten)":"";return {content:[{type:"text",text:`Memory updated.
49
+ id: ${d.fact.id}
50
+ category: ${d.fact.category}
51
+ importance: ${d.fact.importance}
52
+ fields updated: ${m}${g}
53
+ updated_at: ${d.fact.updatedAt}
54
+ `}]}}catch(a){return c(i(a),true)}}),n.set("forget",async t=>{try{let u=o({agentId:t.agentId}),d=await z("forget",t,u);return {content:[{type:"text",text:await $("forget",d,{toolName:"memory_forget"})}]}}catch(a){return c(i(a),true)}}),n.set("extract",async t=>{try{let u=o({agentId:t.agentId}),m=await z("extract",t,u);return {content:[{type:"text",text:`Extract completed.
55
+ sessionId: ${t.sessionId??"(unknown)"}
56
+ extractedCount: ${m.extractedCount}
57
+ factIds: ${m.factIds.length>0?m.factIds.join(", "):"(none)"}
58
+ messageRange: ${m.messageRange.fromMessageId} -> ${m.messageRange.toMessageId}
59
+ `}]}}catch(a){return c(i(a),true)}}),n.set("consolidate",async t=>{try{let u=o({agentId:t.agentId,isTrustedLocal:!0}),d=await z("consolidate",t,u);return {content:[{type:"text",text:await $("consolidate",d,{toolName:"memory_consolidate"})}]}}catch(a){return c(i(a),true)}}),n.set("sync",async t=>{try{let u=t.agentId?.trim();if(!u)return c(i(new Error("memory_sync: agentId is required (sync requires agentId, see ADR 0069)")),!0);let d=o({agentId:u,isTrustedLocal:!0}),m=await z("sync",t,d);return {content:[{type:"text",text:await $("sync",m,{toolName:"memory_sync"})}]}}catch(a){return c(i(a),true)}}),n.set("graph_query",async t=>{try{let a=t,u=o({agentId:a.agentId}),d=await z("graph_query",t,u);return {content:[{type:"text",text:await $("graph_query",d,{toolName:"memory_graph_query",scope:a.scope??"agent_only"})}]}}catch(a){return c(i(a),true)}}),n.set("status",async t=>{try{let u=o({agentId:(t??{}).agentId}),d=await z("status",t,u);return {content:[{type:"text",text:await $("status",d,{toolName:"memory_status"})}]}}catch(a){return c(i(a),true)}}),n.set("doctor",async t=>{try{let u=o({agentId:(t??{}).agentId,isTrustedLocal:!0}),d=await z("doctor",t,u);return {content:[{type:"text",text:await $("doctor",d,{toolName:"memory_doctor"})}]}}catch(a){return c(i(a),true)}}),n.set("init",async t=>{try{let a=o({isTrustedLocal:!0}),d=await z("init",t,a);return {content:[{type:"text",text:`Init complete.
60
+ dbPath: ${d.dbPath}
61
+ tablesCreated: ${d.tablesCreated}
62
+ migrationsApplied: ${d.migrationsApplied}
63
+ durationMs: ${d.durationMs}
64
+ `}]}}catch(a){return c(i(a),true)}}),n}var Ce={recall:c,remember:d,update:e,forget:f$1,extract:g,consolidate:h,sync:m,graph_query:i,status:j,doctor:k,init:l};function Te(e,n){let r=x$1[e],s={title:r?.annotations?.defaultDescription??e,readOnlyHint:r?.annotations?.readOnlyHint??false,destructiveHint:r?.annotations?.destructiveHint??false,idempotentHint:r?.annotations?.idempotentHint??true,openWorldHint:false},o=Ce[e];return {name:e,description:r?.annotations?.defaultDescription??`memory op: ${e}`,inputSchema:o??{type:"object",properties:{},required:[],additionalProperties:false},annotations:s,handler:n}}var re;(r=>{async function e(s,o){let{getMemoryDbPath:c,getInstance:i}=await import('./interfaces-LPJU4KS3.mjs'),a=o!==null&&typeof o=="object"&&"agentId"in o&&"dbPath"in o?o:{agentId:process.env.EASBOT_AGENT_ID??"default",dbPath:c(),workspaceDir:i().worktree,isRemote:false};extendKnownErrorCodes(["AGENT_ID_REQUIRED","SESSION_ID_REQUIRED","CATEGORY_REQUIRED","IMPORTANCE_REQUIRED","TIMERANGE_REQUIRED","DRY_RUN_NO_DELETE"]);let u=new ToolRegistry,d=Re(a),m=Object.keys(x$1);for(let l of m){let I=d.get(l);if(!I)throw new Error(`MemoryStdioServer.start: missing handler for tool "${l}"`);u.register(Te(l,I));}E.info("starting memory MCP stdio server",{id:s.id,name:s.name,toolCount:m.length,isRemote:a.isRemote??true});let g=await createAndStartStdioServer(s,u),p=null,D=new Promise(l=>{p=l;}),w=l=>{E.info("received signal, stopping MCP server",{signal:l}),p?.();},k=()=>w("SIGINT"),S=()=>w("SIGTERM"),F=(l,I)=>process.listeners(l).includes(I);F("SIGINT",k)||process.on("SIGINT",k),F("SIGTERM",S)||process.on("SIGTERM",S);try{await D;}finally{try{process.off("SIGINT",k),process.off("SIGTERM",S);}catch(l){E.warn("failed to remove signal handlers",{error:l instanceof Error?l.message:String(l)});}try{await g.stop();}catch(l){E.warn("server.stop failed during cleanup",{error:l instanceof Error?l.message:String(l)});}}return {id:s.id,name:s.name,version:s.version,tools:m}}r.start=e;function n(){return Object.keys(x$1)}r.getToolNames=n;})(re||(re={}));export{$ as a,re as b};
@@ -1,4 +1,4 @@
1
- 'use strict';var chunkM2YU5LAI_cjs=require('./chunk-M2YU5LAI.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database');var c=utils.Log.create({service:"memory-schema-migrations"}),m=1,I=[{id:1,description:"v1 baseline: memory_facts / memory_vectors / embedding_cache / memory_facts_fts / nodes / edges / meta\uFF08\u4E0E v0.3.x createTables \u8F93\u51FA\u5BF9\u9F50\uFF0C\u8001 db \u8DD1\u8BE5\u8FC1\u79FB\u4E0D\u7834\u574F\u73B0\u6709\u8868\uFF09",up:[`CREATE TABLE IF NOT EXISTS memory_facts (
1
+ 'use strict';var chunkM2YU5LAI_cjs=require('./chunk-M2YU5LAI.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database');var c=utils.Log.create({service:"memory-schema-migrations"}),m=1,R=[{id:1,description:"v1 baseline: memory_facts / memory_vectors / embedding_cache / memory_facts_fts / nodes / edges / meta\uFF08\u4E0E v0.3.x createTables \u8F93\u51FA\u5BF9\u9F50\uFF0C\u8001 db \u8DD1\u8BE5\u8FC1\u79FB\u4E0D\u7834\u574F\u73B0\u6709\u8868\uFF09",up:[`CREATE TABLE IF NOT EXISTS memory_facts (
2
2
  id TEXT PRIMARY KEY,
3
3
  agent_id TEXT NOT NULL,
4
4
  session_id TEXT,
@@ -32,12 +32,11 @@
32
32
  id INTEGER PRIMARY KEY AUTOINCREMENT,
33
33
  name TEXT NOT NULL,
34
34
  type TEXT NOT NULL,
35
- owner_agent_id TEXT,
36
35
  properties TEXT,
37
36
  embedding BLOB,
38
37
  createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
39
38
  updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP
40
- )`,"CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name)","CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type)","CREATE INDEX IF NOT EXISTS idx_nodes_owner_agent_id ON nodes(owner_agent_id)","CREATE INDEX IF NOT EXISTS idx_nodes_embedding ON nodes(embedding) WHERE embedding IS NOT NULL","CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_name_type ON nodes(name, type)",`CREATE TABLE IF NOT EXISTS fact_nodes (
39
+ )`,"CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name)","CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type)","CREATE INDEX IF NOT EXISTS idx_nodes_embedding ON nodes(embedding) WHERE embedding IS NOT NULL","CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_name_type ON nodes(name, type)",`CREATE TABLE IF NOT EXISTS fact_nodes (
41
40
  fact_id TEXT NOT NULL,
42
41
  node_id INTEGER NOT NULL,
43
42
  source TEXT NOT NULL DEFAULT 'kg_extract',
@@ -58,10 +57,10 @@
58
57
  )`,"CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)","CREATE INDEX IF NOT EXISTS idx_edges_relation ON edges(relation)","CREATE UNIQUE INDEX IF NOT EXISTS idx_edges_unique ON edges(source, target, relation)",`CREATE TABLE IF NOT EXISTS meta (
59
58
  key TEXT PRIMARY KEY,
60
59
  value TEXT
61
- )`,"ALTER TABLE nodes ADD COLUMN embedding BLOB","CREATE INDEX IF NOT EXISTS idx_nodes_embedding ON nodes(embedding) WHERE embedding IS NOT NULL"]}];function l(n,e=m,r={}){n.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
60
+ )`,"ALTER TABLE nodes ADD COLUMN embedding BLOB","CREATE INDEX IF NOT EXISTS idx_nodes_embedding ON nodes(embedding) WHERE embedding IS NOT NULL"]}];function g(n,e=m,r={}){n.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
62
61
  id INTEGER PRIMARY KEY,
63
62
  applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
64
- )`);let t=n.prepare("SELECT id FROM schema_migrations").all(),s=new Set(t.map(i=>i.id)),a={applied:[],pending:[],errors:[],currentVersion:t.length===0?0:Math.max(...t.map(i=>i.id)),targetVersion:e};for(let i of I){if(i.id>e)break;if(s.has(i.id)){a.pending.push(i.id);continue}if(r.dryRun){a.applied.push(i.id);continue}try{R(n,i.up),n.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(i.id),s.add(i.id),a.applied.push(i.id),c.info("migration applied",{id:i.id,description:i.description});}catch(o){let d=o instanceof Error?o.message:String(o),T=i.up[0]??"";a.errors.push({migrationId:i.id,sql:T,error:d}),c.warn("migration step failed",{id:i.id,error:d,sqlCount:i.up.length});}}return a}function R(n,e){for(let r of e)try{n.exec(r);}catch(t){let s=t instanceof Error?t.message:String(t);if(f(s)){c.debug("migration: column already exists, skipping",{sql:r.slice(0,80)});continue}throw t}}function f(n){return /duplicate column name/i.test(n)}function _(n){try{let e=n.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(r=>r.id))}catch{return 0}}var N=utils.Log.create({service:"memory-database"}),u=class{constructor(e){chunkM2YU5LAI_cjs.a(this,"db",null);chunkM2YU5LAI_cjs.a(this,"storagePath");chunkM2YU5LAI_cjs.a(this,"backend","better-sqlite3");chunkM2YU5LAI_cjs.a(this,"initialized",false);chunkM2YU5LAI_cjs.a(this,"initPromise",null);this.storagePath=e===":memory:"?e:utils.Filesystem.normalize(e);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize();try{await this.initPromise,this.initialized=!0;}catch(e){try{this.db&&this.db.close();}catch{}throw this.db=null,this.initPromise=null,e}}}async doInitialize(){try{let e=this.openConnection();e.initialize(),this.db=e,this.applyPragmas(),this.runAllMigrations();}catch(e){let r=e instanceof Error?e.message:String(e);throw N.error("Database initialization failed",{error:r}),e}}openConnection(){return database.createSyncSqliteConnection({path:this.storagePath,backend:this.backend,walMode:true,foreignKeys:true,busyTimeoutMs:5e3})}applyPragmas(){if(this.db)try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("foreign_keys = ON");}catch(e){N.warn("Failed to apply memory PRAGMAs",{error:String(e)});}}runAllMigrations(){if(!this.db)throw new Error("Database not initialized");let e=l(this.db,m);if(e.errors.length>0){let r=e.errors.map(t=>`migration ${t.migrationId}: ${t.error}`).join("; ");throw new Error(`Some migrations failed: ${r}`)}}query(e,r){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let t=this.db.prepare(e);return r?t.all(...r):t.all()}catch(t){throw new Error(`Query failed: ${t.message}`)}}agentFilter(e){return typeof e=="string"&&e.trim().length>0?{where:"WHERE agent_id = ?",params:[e.trim()]}:{where:"",params:[]}}run(e,r){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let t=this.db.prepare(e),s=r?t.run(...r):t.run();return {lastID:Number(s.lastInsertRowid),changes:s.changes}}catch(t){throw new Error(`Write failed: ${t.message}`)}}transaction(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db.transaction(e)()}prepare(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db.prepare(e)}exec(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");this.db.exec(e);}getDb(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db}getPath(){return this.storagePath}getSchemaVersion(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return _(this.db)}close(){if(this.db){try{this.db.close();}catch(e){N.warn("Failed to close memory database",{error:String(e)});}this.db=null,this.initialized=false,this.initPromise=null;}}healthCheck(){try{return this.db?(this.db.exec("SELECT 1"),!0):!1}catch{return false}}checkIntegrity(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");let e=S=>this.db.prepare(S).get().c,r={memory_facts:e("SELECT COUNT(*) as c FROM memory_facts"),memory_vectors:e("SELECT COUNT(*) as c FROM memory_vectors"),embedding_cache:e("SELECT COUNT(*) as c FROM embedding_cache"),memory_facts_fts:e("SELECT COUNT(*) as c FROM memory_facts_fts"),nodes:e("SELECT COUNT(*) as c FROM nodes"),edges:e("SELECT COUNT(*) as c FROM edges"),fact_nodes:e("SELECT COUNT(*) as c FROM fact_nodes"),meta:e("SELECT COUNT(*) as c FROM meta"),schema_migrations:e("SELECT COUNT(*) as c FROM schema_migrations")},t=[],s=e(`
63
+ )`);let t=n.prepare("SELECT id FROM schema_migrations").all(),s=new Set(t.map(i=>i.id)),a={applied:[],pending:[],errors:[],currentVersion:t.length===0?0:Math.max(...t.map(i=>i.id)),targetVersion:e};for(let i of R){if(i.id>e)break;if(s.has(i.id)){a.pending.push(i.id);continue}if(r.dryRun){a.applied.push(i.id);continue}try{f(n,i.up),n.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(i.id),s.add(i.id),a.applied.push(i.id),c.info("migration applied",{id:i.id,description:i.description});}catch(o){let d=o instanceof Error?o.message:String(o),T=i.up[0]??"";a.errors.push({migrationId:i.id,sql:T,error:d}),c.warn("migration step failed",{id:i.id,error:d,sqlCount:i.up.length});}}return a}function f(n,e){for(let r of e)try{n.exec(r);}catch(t){let s=t instanceof Error?t.message:String(t);if(I(s)){c.debug("migration: column already exists, skipping",{sql:r.slice(0,80)});continue}throw t}}function I(n){return /duplicate column name/i.test(n)}function u(n){try{let e=n.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(r=>r.id))}catch{return 0}}var N=utils.Log.create({service:"memory-database"}),_=class{constructor(e){chunkM2YU5LAI_cjs.a(this,"db",null);chunkM2YU5LAI_cjs.a(this,"storagePath");chunkM2YU5LAI_cjs.a(this,"backend","better-sqlite3");chunkM2YU5LAI_cjs.a(this,"initialized",false);chunkM2YU5LAI_cjs.a(this,"initPromise",null);this.storagePath=e===":memory:"?e:utils.Filesystem.normalize(e);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize();try{await this.initPromise,this.initialized=!0;}catch(e){try{this.db&&this.db.close();}catch{}throw this.db=null,this.initPromise=null,e}}}async doInitialize(){try{let e=this.openConnection();e.initialize(),this.db=e,this.applyPragmas(),this.runAllMigrations();}catch(e){let r=e instanceof Error?e.message:String(e);throw N.error("Database initialization failed",{error:r}),e}}openConnection(){return database.createSyncSqliteConnection({path:this.storagePath,backend:this.backend,walMode:true,foreignKeys:true,busyTimeoutMs:5e3})}applyPragmas(){if(this.db)try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("foreign_keys = ON");}catch(e){N.warn("Failed to apply memory PRAGMAs",{error:String(e)});}}runAllMigrations(){if(!this.db)throw new Error("Database not initialized");let e=g(this.db,m);if(e.errors.length>0){let r=e.errors.map(t=>`migration ${t.migrationId}: ${t.error}`).join("; ");throw new Error(`Some migrations failed: ${r}`)}}query(e,r){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let t=this.db.prepare(e);return r?t.all(...r):t.all()}catch(t){throw new Error(`Query failed: ${t.message}`)}}agentFilter(e){return typeof e=="string"&&e.trim().length>0?{where:"WHERE agent_id = ?",params:[e.trim()]}:{where:"",params:[]}}run(e,r){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let t=this.db.prepare(e),s=r?t.run(...r):t.run();return {lastID:Number(s.lastInsertRowid),changes:s.changes}}catch(t){throw new Error(`Write failed: ${t.message}`)}}transaction(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db.transaction(e)()}prepare(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db.prepare(e)}exec(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");this.db.exec(e);}getDb(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db}getPath(){return this.storagePath}getSchemaVersion(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return u(this.db)}close(){if(this.db){try{this.db.close();}catch(e){N.warn("Failed to close memory database",{error:String(e)});}this.db=null,this.initialized=false,this.initPromise=null;}}healthCheck(){try{return this.db?(this.db.exec("SELECT 1"),!0):!1}catch{return false}}checkIntegrity(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");let e=p=>this.db.prepare(p).get().c,r={memory_facts:e("SELECT COUNT(*) as c FROM memory_facts"),memory_vectors:e("SELECT COUNT(*) as c FROM memory_vectors"),embedding_cache:e("SELECT COUNT(*) as c FROM embedding_cache"),memory_facts_fts:e("SELECT COUNT(*) as c FROM memory_facts_fts"),nodes:e("SELECT COUNT(*) as c FROM nodes"),edges:e("SELECT COUNT(*) as c FROM edges"),fact_nodes:e("SELECT COUNT(*) as c FROM fact_nodes"),meta:e("SELECT COUNT(*) as c FROM meta"),schema_migrations:e("SELECT COUNT(*) as c FROM schema_migrations")},t=[],s=e(`
65
64
  SELECT COUNT(*) as c FROM fact_nodes fn
66
65
  LEFT JOIN nodes n ON n.id = fn.node_id
67
66
  WHERE n.id IS NULL
@@ -75,4 +74,4 @@
75
74
  EXCEPT
76
75
  SELECT id FROM memory_facts
77
76
  )
78
- `);d>0&&t.push({severity:"warn",message:`FTS out of sync (orphan entries): ${d}`});let T=e("SELECT COUNT(*) as c FROM (SELECT id, COUNT(*) as c FROM memory_facts GROUP BY id HAVING c > 1)");T>0&&t.push({severity:"error",message:`duplicate fact ids: ${T}`});let g=e("SELECT COUNT(*) as c FROM memory_facts WHERE content IS NULL OR content = ''");return g>0&&t.push({severity:"error",message:`memory_facts with null/empty content: ${g}`}),{issues:t,stats:r}}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,r){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,r);}};exports.a=m;exports.b=I;exports.c=l;exports.d=_;exports.e=u;
77
+ `);d>0&&t.push({severity:"warn",message:`FTS out of sync (orphan entries): ${d}`});let T=e("SELECT COUNT(*) as c FROM (SELECT id, COUNT(*) as c FROM memory_facts GROUP BY id HAVING c > 1)");T>0&&t.push({severity:"error",message:`duplicate fact ids: ${T}`});let l=e("SELECT COUNT(*) as c FROM memory_facts WHERE content IS NULL OR content = ''");return l>0&&t.push({severity:"error",message:`memory_facts with null/empty content: ${l}`}),{issues:t,stats:r}}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,r){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,r);}};exports.a=m;exports.b=R;exports.c=g;exports.d=u;exports.e=_;
@@ -0,0 +1,64 @@
1
+ 'use strict';var chunk5VZKEZI4_cjs=require('./chunk-5VZKEZI4.cjs'),mcp=require('@easbot/mcp'),utils=require('@easbot/utils');var oe=utils.Log.create({service:"memory-format-truncate"}),X="**`";var Z=24e3,V=25e3;async function y(e,n={}){let r=n.softLimit??Z,s=n.hardCeiling??V,o=n.toolName??"memory",c=n.writeToDisk!==false;if(e.length<=r)return {content:e,truncated:false};let i=e.slice(0,s),t=i.lastIndexOf(`
2
+ ${X}`),a=i.lastIndexOf(`
3
+ `),u;t>s*.5?u=t:a>0?u=a:u=-1;let d=u>0?i.slice(0,u):i,g=d+"\n\n... (output truncated to budget; the source above is complete and verbatim \u2014 treat it as already Read. For any area not covered, make ANOTHER `<tool>` targeting those names \u2014 do NOT Read these files.)";if(!c)return {content:g,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-d.length}/${e.length} characters truncated ...`};try{let p=await utils.TruncateContent.truncate(e,{maxChars:d.length,direction:"head",label:`${o}-output`});return p.truncated?{content:g,truncated:!0,outputPath:p.outputPath,hint:utils.TruncateContent.formatHint(p),info:`... ${p.removedLength}/${p.originalLength} characters truncated ...`}:{content:g,truncated:!0,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-d.length}/${e.length} characters truncated ...`}}catch(p){return oe.warn("TruncateContent.truncate failed, returning without disk hint",{error:p instanceof Error?p.message:String(p)}),{content:g,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-d.length}/${e.length} characters truncated ...`}}}function f(e,n={}){let r=n.softLimit??Z,s=n.hardCeiling??V;if(e.length<=r)return {content:e,truncated:false};let o=e.slice(0,s),c=o.lastIndexOf(`
4
+ ${X}`),i=o.lastIndexOf(`
5
+ `),t;c>s*.5?t=c:i>0?t=i:t=-1;let a=t>0?o.slice(0,t):o;return {content:a+`
6
+
7
+ ... (output truncated; tail dropped at section boundary)`,truncated:true,outputPath:"",hint:"",info:`... ${e.length-a.length}/${e.length} characters truncated ...`}}function ae(e,n){if(!e||e.length===0)return null;let r=e.filter(o=>n.has(o.path));return r.length===0?null:`\u26A0\uFE0F Index may be stale for: ${r.map(o=>`${o.path} (edited pending)`).join(", ")}
8
+
9
+ `}function b(e,n,r={}){return (ee[e]??ee.default).replace(/<(\w+)>/g,(o,c)=>c==="tool"?n:r[c]??`<${c}>`)}var ee={recall:"If you need more facts, make ANOTHER `<tool>` query with a different scope / interval.\nIf you have enough context, proceed with the current task. Do NOT call `<tool>` again for the same query.",remember:"Memory persisted. To recall it later, use `<tool>` with the same query.\nDo NOT call `<tool>` again to verify \u2014 the fact is already in the database.",forget:"Memory deleted. To verify, run `<tool>` with the same filter (no results expected).\nIf you deleted too much, the data is gone (no auto-restore).",graph_query:"If you need to explore further, make ANOTHER `<tool>` from a different start node or depth.\nOtherwise, the graph is complete for this scope.",status:"Status snapshot. To inspect a specific fact, use `<tool>` (recall) with its id.\nOtherwise, this is a complete read.",consolidate:"Consolidation done. To inspect the new facts, use `<tool>` with the same agentId.\nIf you want to undo, archives are in <archive_dir>.",doctor:"Doctor report. To fix a failing check, run with `repair=true`.\nRe-run after fix to confirm.",default:"If you need more, make ANOTHER `<tool>` with refined parameters.\nOtherwise, this is a complete read."};function se(e){let n=Array.isArray(e.edges)?e.edges.length:0;return ` - node #${e.id}: ${e.name} (${e.type}) [edges: ${n}]`}function te(e,n,r,s){let o=e.tags&&e.tags.length>0?`
10
+ - tags: ${e.tags.join(", ")}`:"",c=e.sessionId?`
11
+ - session: ${e.sessionId}`:"",i=e.msgId?`
12
+ - msg: ${e.msgId}`:"",t=typeof n=="number"?`
13
+ - score: ${n.toFixed(3)}${r?` (${r})`:""}`:"",a=e.truncated?" [truncated]":"",u="";if(s&&s.length>0){let d=s.map(se);u=`
14
+ - linked KG nodes (${s.length}) \u2014 use \`graph_query(nodeId=<id>)\` for full relation graph:
15
+ ${d.join(`
16
+ `)}`;}return [`### \`${e.id}\`${a}`,` - agentId: ${e.agentId}`,` - category: ${e.category}`,` - importance: ${e.importance}`,` - createdAt: ${e.createdAt}`,` - updatedAt: ${e.updatedAt}`,` - source: ${e.source}${t}${o}${c}${i}${u}`,"",e.content,""].join(`
17
+ `)}async function x(e,n){let r=n.toolName??"memory_recall",s=`**\`memory_recall:${n.query.slice(0,40).replace(/[^a-zA-Z0-9_]/g,"_")}\`**`,o=ae(n.pendingFiles,new Set),i=[`Found ${e.total} fact(s) for query "${n.query}" (agentId=${n.agentId}, scope=${n.scope}):`,"",o??"",s].join(`
18
+ `),t=new Map;for(let m of e.hits){let g=m.fact.category;t.has(g)||t.set(g,[]),t.get(g).push(m);}let a=Array.from(t.entries()).map(([m,g])=>{let p=`**\`category:${m}\`**`,E=g.map(w=>te(w.fact,w.score,w.source,w.nodes)).join(`
19
+ `);return `${p}
20
+
21
+ ${E}`}).join(`
22
+ `),u=e.warnings&&e.warnings.length>0?`
23
+
24
+ \u26A0\uFE0F warnings:
25
+ ${e.warnings.map(m=>` - ${m}`).join(`
26
+ `)}
27
+ `:"",d=`${i}
28
+
29
+ ${a}${u}
30
+
31
+ ${b("recall",r)}`;return n.sync?f(d,{}).content:(await y(d,{toolName:r,writeToDisk:n.writeToDisk})).content}async function v(e,n={}){let r=n.toolName??"memory_remember",s=`**\`memory_remember:${e.fact.id}\`**`,o=te(e.fact),c=e.nodeIds??[],i=c.length>0?`
32
+ - linked KG nodes: ${c.join(", ")}
33
+ `:"",t=`${s}
34
+
35
+ ${o}${i}
36
+
37
+ ${b("remember",r)}`;return n.sync?f(t,{}).content:(await y(t,{toolName:r,writeToDisk:n.writeToDisk})).content}async function N(e,n={}){let r=n.toolName??"memory_forget",s="**`memory_forget:result`**",o=e.dryRun?"**DRY RUN** \u2014 no facts were actually deleted. Run again without dryRun to execute.":`Deleted ${e.deletedCount} fact(s).`,c=e.truncatedCount>0?` (truncated: ${e.truncatedCount} more, re-run with narrower filter)`:"",i=[s,"",o+c,"",e.deletedIds.length>0?`deleted ids:
38
+ ${e.deletedIds.map(t=>` - ${t}`).join(`
39
+ `)}`:"(no ids to show)","",b("forget",r)].join(`
40
+ `);return n.sync?f(i,{}).content:(await y(i,{toolName:r,writeToDisk:n.writeToDisk})).content}async function _(e,n={}){let r=n.toolName??"memory_graph_query",s=`**\`memory_graph_query:scope=${e.scope}\`**`,o=e.nodes.map(t=>` - node #${t.id}: ${t.name} (${t.type})${t.ownerAgentId?` [owner=${t.ownerAgentId}]`:" [shared]"}`).join(`
41
+ `),c=e.edges.map(t=>` - edge #${t.id}: ${t.source} --${t.relation}--> ${t.target}`).join(`
42
+ `),i=[s,"",`nodes (${e.nodes.length}${e.truncated?` / total ${e.totalNodes}`:""}):`,o||" (none)","",`edges (${e.edges.length}${e.truncated?` / total ${e.totalEdges}`:""}):`,c||" (none)","",b("graph_query",r)].join(`
43
+ `);return n.sync?f(i,{}).content:(await y(i,{toolName:r,writeToDisk:n.writeToDisk})).content}async function A(e,n={}){let r=n.toolName??"memory_status",c=["**`memory_status`**","",`dbPath: ${e.dbPath}`,`workspaceDir: ${e.workspaceDir}`,`factsCount: ${e.factsCount}`,`nodesCount: ${e.nodesCount} (KG nodes)`,`edgesCount: ${e.edgesCount} (KG edges)`,`ftsAvailable: ${e.ftsAvailable?"yes":"no"}`,`vectorEnabled: ${e.vectorEnabled?"yes":"no"}`,`kgScopeEnabled: ${e.kgScopeEnabled?"yes":"no"}`,`healthy: ${e.healthy?"yes":"no"}`,"","factsByCategory:",...Object.entries(e.factsByCategory).map(([i,t])=>` - ${i}: ${t}`),"","meta:",...Object.entries(e.meta).map(([i,t])=>` - ${i}: ${t}`),"",b("status",r)].join(`
44
+ `);return n.sync?f(c,{}).content:(await y(c,{toolName:r,writeToDisk:n.writeToDisk})).content}async function M(e,n={}){let r=n.toolName??"memory_consolidate",o=["**`memory_consolidate:result`**","",`total facts scanned: ${e.totalFacts}`,`deduped (merged): ${e.dedupedCount}`,`compressed: ${e.compressedCount}`,`archived to archive/: ${e.archivedCount}`,`skipped (no change): ${e.skippedCount}`,`duration: ${e.durationMs}ms`,"",b("consolidate",r)].join(`
45
+ `);return n.sync?f(o,{}).content:(await y(o,{toolName:r,writeToDisk:n.writeToDisk})).content}var S=20;async function O(e,n={}){let r=n.toolName??"memory_sync",o=[`**\`memory_sync:${e.dryRun?"DRY_RUN":"OK"}\`**`,"",`windowDays: ${e.windowDays} (threshold: ${e.archiveThreshold})`,"","## Stage A (db \u2192 .md)",`- generated: ${e.generatedCount}`,`- skipped (idempotent): ${e.skippedCount}`,`- failed (best-effort): ${e.failedGenerateCount}`,"","## Stage B (active/ \u2192 archive/)",`- ${e.dryRun?"would archive":"archived"}: ${e.archivedCount}`];if(e.archivedRecords.length>0){o.push("","### Archived records:");let i=e.archivedRecords.slice(0,S);for(let t of i)o.push(`- ${t.firstFactId} (${t.firstCreatedAt})`),o.push(` - source: \`${t.source}\``),o.push(` - target: \`${t.target}\``);e.archivedRecords.length>S&&o.push(`... and ${e.archivedRecords.length-S} more (use --json for full list)`);}o.push("",`duration: ${e.durationMs}ms`,"",b("sync",r));let c=o.join(`
46
+ `);return n.sync?f(c,{}).content:(await y(c,{toolName:r,writeToDisk:n.writeToDisk})).content}async function P(e,n={}){let r=n.toolName??"memory_doctor",s=`**\`memory_doctor:${e.healthy?"OK":"ISSUES"}\`**`,o=t=>t?"\u2705":"\u274C",c=e.checks.map(t=>`${o(t.passed)} ${t.name}: ${t.message}`).join(`
47
+ `),i=[s,"",c,"",b("doctor",r)].join(`
48
+ `);return n.sync?f(i,{}).content:(await y(i,{toolName:r,writeToDisk:n.writeToDisk})).content}async function $(e,n,r={}){let s=n,o=typeof s.kind=="string";switch((o?s:{kind:e}).kind){case "recall":{let i=o?{hits:s.hits,total:s.totalCount??s.total??0,truncated:s.truncated??false}:n;return x(i,{...r,query:s.query??r.query??"",agentId:s.agentId??r.agentId??"",scope:s.scope??r.scope??"agent_only"})}case "remember":{let i=o?{fact:s.fact,nodeIds:s.nodeIds}:n;return v(i,r)}case "forget":return N(o?s:n,r);case "graph_query":return _(o?s:n,r);case "status":return A(o?s:n,r);case "consolidate":return M(o?s:n,r);case "sync":return O(o?s:n,r);case "doctor":return P(o?s:n,r);default:throw new Error(`renderOperationMarkdown: unsupported op "${e}"`)}}var T=utils.Log.create({service:"memory-mcp-stdio"});function Ie(e){let n=new Map,r=e.isRemote??true,s=!r;function o(t){let a=utils.Locale.resolveLocaleLang();return {agentId:t.agentId??e.agentId,isTrustedLocal:t.isTrustedLocal??s,remote:r,locale:a,dbPath:e.dbPath,workspaceDir:e.workspaceDir,rootDir:e.workspaceDir,config:chunk5VZKEZI4_cjs.A({agentId:e.agentId,dbPath:e.dbPath})}}function c(t,a){return {content:[{type:"text",text:t}],isError:a}}function i(t){return mcp.formatFailClosed(t,s)}return n.set("recall",async t=>{try{let a=t,u=o({agentId:a.agentId}),d=await chunk5VZKEZI4_cjs.z("recall",t,u);return {content:[{type:"text",text:await $("recall",d,{toolName:"memory_recall",query:a.query,agentId:a.agentId??e.agentId,scope:a.scope??"agent_only"})}]}}catch(a){return c(i(a),true)}}),n.set("remember",async t=>{try{let u=o({agentId:t.agentId}),d=await chunk5VZKEZI4_cjs.z("remember",t,u);return {content:[{type:"text",text:await $("remember",d,{toolName:"memory_remember"})}]}}catch(a){return c(i(a),true)}}),n.set("update",async t=>{try{let u=o({agentId:t.agentId}),d=await chunk5VZKEZI4_cjs.z("update",t,u),m=d.fieldsUpdated.length>0?d.fieldsUpdated.join(", "):"(no-op)",g=d.contentChanged?" (embedding rewritten)":"";return {content:[{type:"text",text:`Memory updated.
49
+ id: ${d.fact.id}
50
+ category: ${d.fact.category}
51
+ importance: ${d.fact.importance}
52
+ fields updated: ${m}${g}
53
+ updated_at: ${d.fact.updatedAt}
54
+ `}]}}catch(a){return c(i(a),true)}}),n.set("forget",async t=>{try{let u=o({agentId:t.agentId}),d=await chunk5VZKEZI4_cjs.z("forget",t,u);return {content:[{type:"text",text:await $("forget",d,{toolName:"memory_forget"})}]}}catch(a){return c(i(a),true)}}),n.set("extract",async t=>{try{let u=o({agentId:t.agentId}),m=await chunk5VZKEZI4_cjs.z("extract",t,u);return {content:[{type:"text",text:`Extract completed.
55
+ sessionId: ${t.sessionId??"(unknown)"}
56
+ extractedCount: ${m.extractedCount}
57
+ factIds: ${m.factIds.length>0?m.factIds.join(", "):"(none)"}
58
+ messageRange: ${m.messageRange.fromMessageId} -> ${m.messageRange.toMessageId}
59
+ `}]}}catch(a){return c(i(a),true)}}),n.set("consolidate",async t=>{try{let u=o({agentId:t.agentId,isTrustedLocal:!0}),d=await chunk5VZKEZI4_cjs.z("consolidate",t,u);return {content:[{type:"text",text:await $("consolidate",d,{toolName:"memory_consolidate"})}]}}catch(a){return c(i(a),true)}}),n.set("sync",async t=>{try{let u=t.agentId?.trim();if(!u)return c(i(new Error("memory_sync: agentId is required (sync requires agentId, see ADR 0069)")),!0);let d=o({agentId:u,isTrustedLocal:!0}),m=await chunk5VZKEZI4_cjs.z("sync",t,d);return {content:[{type:"text",text:await $("sync",m,{toolName:"memory_sync"})}]}}catch(a){return c(i(a),true)}}),n.set("graph_query",async t=>{try{let a=t,u=o({agentId:a.agentId}),d=await chunk5VZKEZI4_cjs.z("graph_query",t,u);return {content:[{type:"text",text:await $("graph_query",d,{toolName:"memory_graph_query",scope:a.scope??"agent_only"})}]}}catch(a){return c(i(a),true)}}),n.set("status",async t=>{try{let u=o({agentId:(t??{}).agentId}),d=await chunk5VZKEZI4_cjs.z("status",t,u);return {content:[{type:"text",text:await $("status",d,{toolName:"memory_status"})}]}}catch(a){return c(i(a),true)}}),n.set("doctor",async t=>{try{let u=o({agentId:(t??{}).agentId,isTrustedLocal:!0}),d=await chunk5VZKEZI4_cjs.z("doctor",t,u);return {content:[{type:"text",text:await $("doctor",d,{toolName:"memory_doctor"})}]}}catch(a){return c(i(a),true)}}),n.set("init",async t=>{try{let a=o({isTrustedLocal:!0}),d=await chunk5VZKEZI4_cjs.z("init",t,a);return {content:[{type:"text",text:`Init complete.
60
+ dbPath: ${d.dbPath}
61
+ tablesCreated: ${d.tablesCreated}
62
+ migrationsApplied: ${d.migrationsApplied}
63
+ durationMs: ${d.durationMs}
64
+ `}]}}catch(a){return c(i(a),true)}}),n}var Re={recall:chunk5VZKEZI4_cjs.c,remember:chunk5VZKEZI4_cjs.d,update:chunk5VZKEZI4_cjs.e,forget:chunk5VZKEZI4_cjs.f,extract:chunk5VZKEZI4_cjs.g,consolidate:chunk5VZKEZI4_cjs.h,sync:chunk5VZKEZI4_cjs.m,graph_query:chunk5VZKEZI4_cjs.i,status:chunk5VZKEZI4_cjs.j,doctor:chunk5VZKEZI4_cjs.k,init:chunk5VZKEZI4_cjs.l};function Ce(e,n){let r=chunk5VZKEZI4_cjs.x[e],s={title:r?.annotations?.defaultDescription??e,readOnlyHint:r?.annotations?.readOnlyHint??false,destructiveHint:r?.annotations?.destructiveHint??false,idempotentHint:r?.annotations?.idempotentHint??true,openWorldHint:false},o=Re[e];return {name:e,description:r?.annotations?.defaultDescription??`memory op: ${e}`,inputSchema:o??{type:"object",properties:{},required:[],additionalProperties:false},annotations:s,handler:n}}exports.b=void 0;(r=>{async function e(s,o){let{getMemoryDbPath:c,getInstance:i}=await import('./interfaces-Q5OGU5EK.cjs'),a=o!==null&&typeof o=="object"&&"agentId"in o&&"dbPath"in o?o:{agentId:process.env.EASBOT_AGENT_ID??"default",dbPath:c(),workspaceDir:i().worktree,isRemote:false};mcp.extendKnownErrorCodes(["AGENT_ID_REQUIRED","SESSION_ID_REQUIRED","CATEGORY_REQUIRED","IMPORTANCE_REQUIRED","TIMERANGE_REQUIRED","DRY_RUN_NO_DELETE"]);let u=new mcp.ToolRegistry,d=Ie(a),m=Object.keys(chunk5VZKEZI4_cjs.x);for(let l of m){let I=d.get(l);if(!I)throw new Error(`MemoryStdioServer.start: missing handler for tool "${l}"`);u.register(Ce(l,I));}T.info("starting memory MCP stdio server",{id:s.id,name:s.name,toolCount:m.length,isRemote:a.isRemote??true});let g=await mcp.createAndStartStdioServer(s,u),p=null,E=new Promise(l=>{p=l;}),w=l=>{T.info("received signal, stopping MCP server",{signal:l}),p?.();},D=()=>w("SIGINT"),k=()=>w("SIGTERM"),L=(l,I)=>process.listeners(l).includes(I);L("SIGINT",D)||process.on("SIGINT",D),L("SIGTERM",k)||process.on("SIGTERM",k);try{await E;}finally{try{process.off("SIGINT",D),process.off("SIGTERM",k);}catch(l){T.warn("failed to remove signal handlers",{error:l instanceof Error?l.message:String(l)});}try{await g.stop();}catch(l){T.warn("server.stop failed during cleanup",{error:l instanceof Error?l.message:String(l)});}}return {id:s.id,name:s.name,version:s.version,tools:m}}r.start=e;function n(){return Object.keys(chunk5VZKEZI4_cjs.x)}r.getToolNames=n;})(exports.b||(exports.b={}));exports.a=$;