@easbot/memory 0.3.21 → 0.3.23

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 (59) hide show
  1. package/README.en.md +2 -2
  2. package/README.md +4 -4
  3. package/dist/chunks/chunk-2TBNGTSA.mjs +65 -0
  4. package/dist/chunks/{chunk-TIZCWDJ7.mjs → chunk-3EDNN7MP.mjs} +1 -1
  5. package/dist/chunks/chunk-5YDI4K2F.cjs +65 -0
  6. package/dist/chunks/{chunk-EGWJG65Q.cjs → chunk-EK34SXJ7.cjs} +24 -17
  7. package/dist/chunks/{chunk-N5YRDTEH.mjs → chunk-K4K3YR6R.mjs} +35 -29
  8. package/dist/chunks/{chunk-S6S35LDL.cjs → chunk-MENFLGGM.cjs} +36 -30
  9. package/dist/chunks/{chunk-AYGZUNFR.cjs → chunk-OU5TQHJE.cjs} +1 -1
  10. package/dist/chunks/{chunk-JDPZ5U53.mjs → chunk-PJGILQSZ.mjs} +24 -17
  11. package/dist/chunks/cli-handler-7HISH37M.cjs +1 -0
  12. package/dist/chunks/cli-handler-WOX5EG34.mjs +1 -0
  13. package/dist/chunks/{config-RPPQ73HK.cjs → config-I2I6U4XM.cjs} +1 -1
  14. package/dist/chunks/consolidate-JBTOQWUX.mjs +2 -0
  15. package/dist/chunks/{consolidate-G4YJV756.cjs → consolidate-JGLVNSDT.cjs} +1 -1
  16. package/dist/chunks/doctor-C7RIJGYC.cjs +1 -0
  17. package/dist/chunks/{doctor-GKMREWZN.mjs → doctor-DLQO7QMW.mjs} +1 -1
  18. package/dist/chunks/{extract-YKDPZ7GA.cjs → extract-4ZGVF2DQ.cjs} +1 -1
  19. package/dist/chunks/extract-WH4DU4NQ.mjs +2 -0
  20. package/dist/chunks/{forget-VQB5DUJ3.mjs → forget-CRDWG4XE.mjs} +1 -1
  21. package/dist/chunks/{forget-GNIJL2DU.cjs → forget-PARGCUIH.cjs} +1 -1
  22. package/dist/chunks/{graph-GTYUNUJE.cjs → graph-NJJLGDZI.cjs} +1 -1
  23. package/dist/chunks/{graph-4W63TU2D.mjs → graph-T66JXDLU.mjs} +1 -1
  24. package/dist/chunks/init-2ZTVBJ6N.mjs +1 -0
  25. package/dist/chunks/{init-DGMGRNCG.cjs → init-EEWFFF4Y.cjs} +1 -1
  26. package/dist/chunks/{interfaces-XWE45ENK.cjs → interfaces-Q5OGU5EK.cjs} +1 -1
  27. package/dist/chunks/{llm-RMPVWEVP.cjs → llm-7LQGYSUE.cjs} +1 -1
  28. package/dist/chunks/{mcp-EHUKGJRB.cjs → mcp-ES7O3UKN.cjs} +1 -1
  29. package/dist/chunks/{mcp-QQBHEZFY.mjs → mcp-OAUOA4PI.mjs} +1 -1
  30. package/dist/chunks/{recall-ZENMAOMJ.cjs → recall-LCKRI4TB.cjs} +1 -1
  31. package/dist/chunks/recall-VMW7Y55X.mjs +2 -0
  32. package/dist/chunks/{remember-3ZY66RJQ.cjs → remember-OZOQ76IA.cjs} +1 -1
  33. package/dist/chunks/{remember-P3G7WWYB.mjs → remember-ZVTM3IP4.mjs} +1 -1
  34. package/dist/chunks/status-6R335JGR.cjs +1 -0
  35. package/dist/chunks/{status-JYI52QKB.mjs → status-LHXMB3ZY.mjs} +1 -1
  36. package/dist/chunks/stdio-server-IMJF7HB6.cjs +1 -0
  37. package/dist/chunks/stdio-server-SONZIWC4.mjs +1 -0
  38. package/dist/chunks/{sync-64JINCSC.cjs → sync-7VBREDVM.cjs} +1 -1
  39. package/dist/chunks/{sync-ZPRCA4MO.mjs → sync-KWHUII26.mjs} +1 -1
  40. package/dist/cli.cjs +1 -1
  41. package/dist/cli.mjs +1 -1
  42. package/dist/index.cjs +4 -4
  43. package/dist/index.d.cts +24 -1
  44. package/dist/index.d.ts +24 -1
  45. package/dist/index.mjs +4 -4
  46. package/package.json +11 -11
  47. package/dist/chunks/chunk-UF2Y2Q4L.mjs +0 -50
  48. package/dist/chunks/chunk-Z5E4HBGK.cjs +0 -50
  49. package/dist/chunks/cli-handler-2IPBL45N.cjs +0 -1
  50. package/dist/chunks/cli-handler-5YNHYDSM.mjs +0 -1
  51. package/dist/chunks/consolidate-MSPLH3T6.mjs +0 -2
  52. package/dist/chunks/doctor-YTUQCHFJ.cjs +0 -1
  53. package/dist/chunks/extract-3C4QFS7E.mjs +0 -2
  54. package/dist/chunks/init-G2WTR477.mjs +0 -1
  55. package/dist/chunks/recall-SGA2DITO.mjs +0 -2
  56. package/dist/chunks/status-UEKBJVCI.cjs +0 -1
  57. package/dist/chunks/stdio-server-2PWTBTDJ.mjs +0 -1
  58. package/dist/chunks/stdio-server-JL4XNUHH.cjs +0 -1
  59. /package/dist/chunks/{chunk-NVGACA7W.cjs → chunk-M2YU5LAI.cjs} +0 -0
package/README.en.md CHANGED
@@ -55,7 +55,7 @@ const recall = await executeOp<{ hits: unknown[] }>(
55
55
  const saved = await executeOp<{ id: string }>(
56
56
  'remember',
57
57
  {
58
- content: '老侯 prefers TypeScript',
58
+ content: 'prefers TypeScript',
59
59
  category: 'user_preference',
60
60
  importance: 9,
61
61
  dbPath: '/path/to/memory.db',
@@ -435,4 +435,4 @@ pnpm biome-lint
435
435
 
436
436
  ## License
437
437
 
438
- MIT
438
+ MIT
package/README.md CHANGED
@@ -55,7 +55,7 @@ const recall = await executeOp<{ hits: unknown[] }>(
55
55
  const saved = await executeOp<{ id: string }>(
56
56
  'remember',
57
57
  {
58
- content: '老侯 prefers TypeScript',
58
+ content: 'prefers TypeScript',
59
59
  category: 'user_preference',
60
60
  importance: 9,
61
61
  dbPath: '/path/to/memory.db',
@@ -284,7 +284,7 @@ $ easbot memory status --json
284
284
  ```bash
285
285
  # @easbot/agent 的 memory 子命令直接委派 handleMemoryCli(决策 0049)
286
286
  easbot memory recall --query "user preference"
287
- easbot memory remember --content "老侯 prefers TypeScript"
287
+ easbot memory remember --content "prefers TypeScript"
288
288
  easbot memory mcp # 启动 MCP stdio server
289
289
  ```
290
290
 
@@ -335,7 +335,7 @@ if (result.code !== 0) process.exit(result.code);
335
335
  - 二次开发:未来 `note` 工具可通过 file watcher 检测 memory .md 变化触发 cross-reference 更新
336
336
  - 灾备:file 失败**不阻塞** db 写入(与 v0.3 行为一致)
337
337
 
338
- ### 路径格式(v0.5.1+ 老侯 2026-08-23 反馈修正)
338
+ ### 路径格式(v0.5.1+ 反馈修正)
339
339
 
340
340
  ```
341
341
  {workspaceDir}/.easbot/memory/active/{category}/{YYYY-MM-DD}.md
@@ -436,4 +436,4 @@ pnpm biome-lint
436
436
 
437
437
  ## 许可证
438
438
 
439
- MIT
439
+ MIT
@@ -0,0 +1,65 @@
1
+ import {e,a as a$2}from'./chunk-PJGILQSZ.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 pe from'path';import {writeFileSync}from'fs';import {createRequire}from'module';import {EMBEDDING_DIMS_CONSISTENCY_CHECK,DEFAULT_SEARCH_CONFIG}from'@easbot/types';var he=Log.create({service:"memory.graph-store"}),ee=class{constructor(e){a(this,"db");this.db=e;}async upsertNode(e,r,n,o){let c=Date.now(),s=JSON.stringify(n??{}),i=this.db.prepare("SELECT id FROM nodes WHERE name = ? AND type = ? LIMIT 1").get(e,r);if(i)return this.db.prepare("UPDATE nodes SET properties = ?, updatedAt = ? WHERE id = ?").run(s,c,i.id),i.id;let g=this.db.prepare("INSERT INTO nodes (name, type, properties, owner_agent_id, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)").run(e,r,s,o??null,c,c);return Number(g.lastInsertRowid)}async deleteNode(e){this.db.prepare("DELETE FROM nodes WHERE id = ?").run(e);}async upsertEdge(e,r,n,o){let c=this.db.prepare("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)").run(e,r,n,JSON.stringify(o??{}),Date.now());return Number(c.lastInsertRowid)}async queryNodes(e={}){let r="SELECT id, name, type, properties, owner_agent_id, createdAt, updatedAt FROM nodes",n=[],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(", ")})`),n.push(...s);}e.name&&(o.push("name LIKE ?"),n.push(`%${e.name}%`)),e.type&&(o.push("type = ?"),n.push(e.type)),St(o,n,e.agentId,e.scope??"agent_only"),o.length>0&&(r+=` WHERE ${o.join(" AND ")}`),r+=" ORDER BY id",e.limit&&(r+=" LIMIT ?",n.push(e.limit)),he.debug("queryNodes",{sql:r,params:n,filter:e});let c=this.db.prepare(r).all(...n);return he.debug("queryNodes result",{count:c.length}),c.map(s=>({id:s.id,name:s.name,type:s.type,properties:s.properties?JSON.parse(s.properties):void 0,createdAt:s.createdAt,updatedAt:s.updatedAt,ownerAgentId:s.owner_agent_id}))}async queryEdges(e={}){let r="SELECT e.id, e.source, e.target, e.relation, e.properties, e.createdAt FROM edges e",n=[],o=[];if(e.ids&&e.ids.length>0&&(o.push(`e.id IN (${e.ids.map(()=>"?").join(", ")})`),n.push(...e.ids)),e.source!==void 0&&(o.push("e.source = ?"),n.push(e.source)),e.target!==void 0&&(o.push("e.target = ?"),n.push(e.target)),e.sourceOrTarget&&e.sourceOrTarget.length>0){let l=e.sourceOrTarget.map(p=>typeof p=="string"?parseInt(p,10):p).filter(p=>!Number.isNaN(p));o.push(`(e.source IN (${l.map(()=>"?").join(", ")}) OR e.target IN (${l.map(()=>"?").join(", ")}))`),n.push(...l,...l);}e.relation&&(o.push("e.relation = ?"),n.push(e.relation)),o.length>0&&(r+=` WHERE ${o.join(" AND ")}`),r+=" ORDER BY e.id",e.limit&&(r+=" LIMIT ?",n.push(e.limit)),he.debug("queryEdges",{sql:r,params:n,filter:e});let c=this.db.prepare(r).all(...n);he.debug("queryEdges result",{count:c.length});let s=[...new Set(c.map(l=>l.target))],i=s.length>0?await this.queryNodes({ids:s,limit:s.length}):[],g=new Map(i.map(l=>[l.id,l]));return c.map(l=>{let p={id:l.id,source:l.source,target:l.target,relation:l.relation,properties:l.properties?JSON.parse(l.properties):void 0,createdAt:l.createdAt},y=g.get(l.target);return y&&(p.targetNode=y),p})}async queryNeighbors(e,r=1,n){let o=n?.agentId,c=n?.scope??"agent_only",s=new Set,i=[{id:e,level:0}],g=[],l=n?.maxEdgesPerNode??50;for(;i.length>0;){let p=i.shift();if(!p)break;if(s.has(p.id)||p.level>r)continue;s.add(p.id);let h=(await this.queryNodes({ids:[p.id],limit:1,agentId:o,scope:c}))[0];if(!h)continue;let M=await this.queryEdges({sourceOrTarget:[p.id],limit:l}),D=o?await Rt(this,M,o,c):M;if(g.push({...h,edges:D}),p.level<r)for(let I of D){let u=I.source===p.id?I.target:I.source;s.has(u)||i.push({id:u,level:p.level+1});}}return g}};async function Rt(t,e,r,n){if(e.length===0)return e;let o=new Set;for(let i of e)o.add(i.source),o.add(i.target);let c=await t.queryNodes({ids:Array.from(o),agentId:r,scope:n,limit:o.size}),s=new Set(c.map(i=>i.id));return e.filter(i=>s.has(i.source)&&s.has(i.target))}function St(t,e,r,n){if(r)switch(n){case "agent_only":t.push("owner_agent_id = ?"),e.push(r);break;case "shared_only":t.push("owner_agent_id IS NULL");break;case "both":t.push("(owner_agent_id = ? OR owner_agent_id IS NULL)"),e.push(r);break}}var S=class extends Error{constructor(r,n,o){super(r);a(this,"code",n);a(this,"details",o);this.name="ServiceError";}},ce=class extends S{constructor(e,r=[]){super(`Memory not found: ${e}`,"NOT_FOUND",{memoryId:e,candidates:r});}};var be=class extends S{constructor(){super("ctx.agentId is required for memory service (ADR 0055 per-agent isolation)","AGENT_ID_REQUIRED");}},de=class extends S{constructor(e,r){super(`Trust denied for operation "${e}": ${r}`,"TRUST_DENIED",{operation:e,reason:r});}},me=class extends S{constructor(e,r){super(`Memory ${e} has ${r} references (force=false)`,"HAS_REFERENCES",{memoryId:e,referenceCount:r});}},le=class extends S{constructor(e){super(`dryRun mode: ${e} memories matched but not deleted`,"DRY_RUN_NO_DELETE",{matchedCount:e});}},ge=class extends S{constructor(e,r){super(`Matched ${e} memories exceeds maxDelete=${r}`,"MAX_DELETE_EXCEEDED",{matched:e,maxDelete:r});}};function H(t){if(typeof t.agentId!="string"||t.agentId.trim().length===0)throw new be}function Q(t,e){if(t.remote!==false)throw new de(e,"requires trusted local caller (CLI / agent tool / MCP with remote=false)")}function Ee(t,e,r){if(e!=="agent_only"&&t.remote!==false)throw new de(r,`scope="${e}" requires trusted local caller (cross-agent access denied)`)}function te(t){if(!t.dbPath||t.dbPath.trim().length===0)throw new S("service ctx.dbPath is required (MemoryKnowledgeConfigWithModels.database.path)","INTERNAL")}var ne=Log.create({service:"memory.service.recall"});async function Be(t,e$1){let r=Date.now();if(H(t),te(t),!e$1.query||e$1.query.trim().length===0)throw new S("recall requires non-empty `query`","CONTENT_REQUIRED");let n=e$1.includeShared?"both":"agent_only";e$1.includeGraph&&Ee(t,n,"recall"),ne.debug("recall invoked",{agentId:t.agentId,query:e$1.query,category:e$1.category,maxResults:e$1.maxResults,includeGraph:e$1.includeGraph,scope:n});let o=e$1.maxResults??10,c=e$1.minScore??0,s=[],i=new e(t.dbPath);try{await i.initialize();let g=a$1.isInitialized()&&a$1.capabilities().embedding===!0,l=await _t(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:g}),p;if(e$1.includeGraph&&l.length>0)try{let h=new ee(i.getDb()),M=e$1.depth??1,D=l.flatMap(v=>(v.nodes??[]).map(b=>b.id)).slice(0,5),I=new Set,u=new Map;for(let v of D){let b=await h.queryNeighbors(v,M,{agentId:t.agentId,scope:n,maxEdgesPerNode:10});for(let _ of b)I.add(_.id),u.set(_.id,_.edges??[]);}let E=I.size>0?i.query(`SELECT id, name, type FROM nodes WHERE id IN (${Array.from(I).map(()=>"?").join(",")})`,Array.from(I)):[],C=Array.from(u.values()).flat();p={nodes:E.map(v=>({id:v.id,name:v.name,type:v.type,createdAt:"",updatedAt:""})),edges:C};}catch(h){let M=h instanceof Error?h.message:String(h);ne.warn("recall: KG neighbor query failed",{error:M}),s.push(`kg_neighbor_query_failed: ${M}`),p={nodes:[],edges:[]};}let y=Date.now()-r;return {hits:l,total:l.length,truncated:l.length>=o,durationMs:y,graph:p,...s.length>0?{warnings:s}:{}}}catch(g){throw g instanceof S?g:new S(`recall failed: ${g instanceof Error?g.message:String(g)}`,"INTERNAL",{cause:g instanceof Error?g.message:String(g)})}finally{i.close();}}async function _t(t,e,r,n){let o=["mf.agent_id = ?"],c=[e];n.category&&(o.push("mf.category = ?"),c.push(n.category)),n.minImportance!==void 0&&(o.push("mf.importance >= ?"),c.push(n.minImportance)),n.fromTime&&(o.push("mf.created_at >= ?"),c.push(n.fromTime)),n.toTime&&(o.push("mf.created_at <= ?"),c.push(n.toTime));let s=o.join(" AND "),i=null;if(n.hasEmbedding)try{i=await a$1.embedText(r);}catch(f){ne.warn("recall: query embedding failed, falling back to FTS-only",{error:f instanceof Error?f.message:String(f)}),i=null;}let g=Math.max(n.limit*100,1e3),[l,p]=await Promise.all([i?Dt(t,i,s,c,g):Promise.resolve([]),vt(t,r,s,c,n.limit)]),y=i?.7:0,h=i?.3:1,M=y+h,D=y/M,I=h/M,u=new Map;for(let f of l)u.set(f.id,f.score*D);for(let f of p)u.set(f.id,(u.get(f.id)??0)+f.score*I);let E=Array.from(u.entries()).sort((f,O)=>O[1]-f[1]).map(([f])=>f).slice(0,n.limit);if(E.length===0)return [];let C=E.map(()=>"?").join(","),v=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 (${C})`,E),b=Mt(t,v.map(f=>f.id)),_=Date.now();return v.map(f=>{let O=u.get(f.id)??0,F=(_-new Date(f.createdAt).getTime())/864e5,k=Math.exp(-0.05*F),j=(f.importance-1)/9,z=.4*O+.3*k+.3*j,V;if(f.tags)try{let d=JSON.parse(f.tags);Array.isArray(d)&&(V=d.filter(m=>typeof m=="string"));}catch{}return {memoryId:f.id,category:f.category,importance:f.importance,agentId:f.agentId,content:f.content,snippet:f.snippet,score:z,createdAt:f.createdAt,updatedAt:f.updatedAt,source:f.source,filePath:f.filePath??void 0,tags:V,sessionId:f.sessionId??void 0,msgId:f.msgId??void 0,parentMsgId:f.parentMsgId??void 0,nodes:b.get(f.id)??[]}}).filter(f=>f.score>=n.minScore).sort((f,O)=>O.score-f.score)}function Mt(t,e){let r=new Map;if(e.length===0)return r;try{let n=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 (${n})
21
+ ORDER BY fn.fact_id, fn.score DESC, n.id`,e);for(let c of o){let s=r.get(c.fact_id);s||(s=[],r.set(c.fact_id,s)),s.push({id:c.id,name:c.name,type:c.type});}}catch(n){ne.warn("recall: loadFactNodes failed (KG associations unavailable for this recall)",{error:n instanceof Error?n.message:String(n)});}return r}function Dt(t,e,r,n,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 ${r}
25
+ LIMIT ?`,[...n,o]).map(s=>{let i=new Float32Array(s.embedding.buffer,s.embedding.byteOffset,s.embedding.byteLength/4);return {id:s.id,score:Ct(e,i)}}).sort((s,i)=>i.score-s.score)}catch(c){if(c instanceof S)throw c;return ne.warn("vector search failed, falling back to FTS-only",{error:c instanceof Error?c.message:String(c)}),[]}}function vt(t,e,r,n,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 ${r} AND memory_facts_fts MATCH ?
29
+ ORDER BY score DESC
30
+ LIMIT ?`,[...n,Ot(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 S)throw c;return ne.warn("FTS search failed, returning empty result",{err:c instanceof Error?c.message:String(c)}),[]}}function Ct(t,e){if(t.length!==e.length||t.length===0)return 0;let r=0,n=0,o=0;for(let s=0;s<t.length;s++){let i=t[s]??0,g=e[s]??0;r+=i*g,n+=i*i,o+=g*g;}let c=Math.sqrt(n)*Math.sqrt(o);return c===0?0:Math.max(0,r/c)}function Ot(t){return t.trim().split(/\s+/).filter(e=>e.length>0).map(e=>`"${e.replace(/"/g,'""')}"`).join(" ")}var ze=z.object({query:z.string().min(1).max(500),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().default(10),minScore:z.number().min(0).max(1).optional(),includeGraph:z.boolean().optional().default(false),depth:z.number().int().min(1).max(5).optional().default(1),includeShared:z.boolean().optional().default(false)});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 Qe=z.object({content:z.string().min(1).max(1e4),category:z.string().min(1),importance:z.number().int().min(1).max(10).optional().default(5),tags:z.array(z.string()).optional(),sessionId:z.string().optional(),msgId:z.string().optional(),parentMsgId:z.string().optional(),skipDedup:z.boolean().optional().default(false),extractGraph:z.boolean().optional().default(true)});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 Ke=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)")}).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 Je=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().default(1e3),dryRun:z.boolean().optional().default(false),force:z.boolean().optional().default(false)}).refine(t=>t.factId!==void 0&&t.factId.length>0||t.category!==void 0&&t.category.length>0||t.fromTime!==void 0||t.toTime!==void 0,{message:"one of `factId`, `category`, `fromTime`, or `toTime` is required"});z.object({deletedCount:z.number(),deletedIds:z.array(z.string()),dryRun:z.boolean(),truncatedCount:z.number()});var Ve=z.object({sessionId:z.string().min(1),lastN:z.number().int().min(1).max(500).optional().default(50),fromMessageId:z.string().optional(),writeToDisk:z.boolean().optional().default(true)});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 Ye=z.object({windowDays:z.number().int().min(1).max(365).optional().default(30),dryRun:z.boolean().optional().default(false)});z.object({totalFacts:z.number(),dedupedCount:z.number(),compressedCount:z.number(),archivedCount:z.number(),skippedCount:z.number(),durationMs:z.number()});var Xe=z.object({query:z.string().min(1),type:z.string().optional(),depth:z.number().int().min(1).max(5).optional().default(2),maxNodes:z.number().int().min(1).max(500).optional().default(100),scope:z.enum(["agent_only","shared_only","both"]).optional().default("agent_only"),relation:z.string().optional()});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 Ze=z.object({}).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 et=z.object({}).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 tt=z.object({workspaceDir:z.string().optional(),dbPath:z.string().optional(),archiveDays:z.number().int().min(1).max(3650).optional().default(30),force:z.boolean().optional().default(false)});z.object({initialized:z.boolean(),dbPath:z.string(),workspaceDir:z.string(),tablesCreated:z.number(),migrationsApplied:z.number(),durationMs:z.number()});var nt=z.object({windowDays:z.number().int().min(1).max(3650).optional(),dryRun:z.boolean().optional().default(false)});z.object({generatedCount:z.number(),skippedCount:z.number(),failedGenerateCount:z.number(),archivedCount:z.number(),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 ue=Log.create({service:"memory.fact-file-sync"}),Pt=".easbot/memory/active";function fe(t,e){let r=e.replace(/\\/g,"/").replace(/\/+$/,""),n=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"),g=String(c.getDate()).padStart(2,"0"),l=`${s}-${i}-${g}`;return `${r}/${Pt}/${n}/${l}.md`}function rt(t){let e=t.tags&&t.tags.length>0?t.tags:[],r=t.importance??5,n=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: ${r}`,`created_at: ${o}`,`updated_at: ${c}`,`source: ${n}`,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 re(t,e){let r=t.replace(/\\/g,"/"),n=e.replace(/\\/g,"/").replace(/\/+$/,"");return r.startsWith(`${n}/`)?r.slice(n.length+1):r}async function kt(t,e){let r=fe(t,e),n=re(r,e);try{let o=rt(t);await K.mkdir(pe.dirname(r),{recursive:!0});let c="";try{c=await K.readFile(r,"utf-8");}catch(i){if(i.code!=="ENOENT")throw i}let s=c.length>0&&!c.endsWith(`
33
+ `)?`
34
+ `:"";return await K.writeFile(r,`${c}${s}${o}
35
+ `,"utf-8"),ue.debug("Fact file synced (append)",{id:t.id,relPath:n}),{ok:!0,absPath:r,relPath:n}}catch(o){let c=o instanceof Error?o.message:String(o);return ue.warn("Failed to write fact file (best-effort, non-blocking)",{id:t.id,absPath:r,error:c}),{ok:false,absPath:r,relPath:n,error:c}}}async function At(t,e){let r;t.filePath?r=`${e.replace(/\\/g,"/").replace(/\/+$/,"")}/${t.filePath.replace(/^\/+/,"")}`:r=fe({id:t.id,category:t.category,createdAt:t.createdAt,updatedAt:t.createdAt},e);let n=re(r,e);try{return await K.unlink(r),ue.debug("Fact file deleted",{id:t.id,relPath:n}),{ok:!0,absPath:r,relPath:n}}catch(o){if(o.code==="ENOENT")return ue.debug("Fact file not found (already deleted)",{id:t.id,relPath:n}),{ok:true,absPath:r,relPath:n};let s=o instanceof Error?o.message:String(o);return ue.warn("Failed to delete fact file (best-effort, non-blocking)",{id:t.id,absPath:r,error:s}),{ok:false,absPath:r,relPath:n,error:s}}}var oe={resolvePath:fe,renderMarkdown:rt,toRelPath:re,write:kt,delete:At};var ae=Log.create({service:"memory.service.remember"});async function ot(t,e$1){if(H(t),te(t),!e$1.content||e$1.content.trim().length===0)throw new S("remember requires non-empty `content`","CONTENT_REQUIRED");if(!e$1.category)throw new S("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 r=new e(t.dbPath);try{await r.initialize();let n=new Date().toISOString(),o=$t(),c=e$1.importance??5,s={entities:[],relations:[]},g=e$1.extractGraph!==!1&&a$1.isInitialized()&&a$1.capabilities().graphLlm?a$1.getGraphLlm():void 0;if(g)try{s=await Ut(g,e$1.content);}catch(b){ae.warn("LLM KG extraction failed (continuing without KG)",{agentId:t.agentId,error:b instanceof Error?b.message:String(b)});}let l=a$1.isInitialized()&&a$1.capabilities().embedding===!0,p=l?await Ht(r.getDb(),e$1.content):null,y=p?p.length:null,h=s.entities,M=s.relations,D=[],I=0,u=[];if(r.transaction(()=>{let b=new Map;for(let R of h){let f=r.query("SELECT id FROM nodes WHERE name = ? AND type = ? AND owner_agent_id = ? LIMIT 1",[R.name,R.type,t.agentId])[0];if(f){b.set(R.name,f.id);continue}let O=null;try{let j=Ie(R.name),z=r.query("SELECT embedding FROM embedding_cache WHERE content_hash = ?",[j])[0];z?.embedding&&(O=z.embedding);}catch{}let k=r.run("INSERT INTO nodes (name, type, properties, owner_agent_id, embedding, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?, ?)",[R.name,R.type,JSON.stringify({source:"llm_extracted",...R.properties??{}}),t.agentId,O,n,n]).lastID;k>0&&(b.set(R.name,k),O===null&&u.push({name:R.name,nodeId:k}));}for(let R of M){let f=b.get(R.source),O=b.get(R.target);!f||!O||f===O||r.run("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)",[f,O,R.relation,JSON.stringify({}),n]);}r.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,n,n]);let _=Array.from(b.values());if(_.length>0)try{for(let R of _)r.run("INSERT OR IGNORE INTO fact_nodes (fact_id, node_id, source, score, createdAt) VALUES (?, ?, ?, ?, ?)",[o,R,"kg_extract",1,n]);}catch(R){ae.warn("fact_nodes write failed (non-fatal)",{factId:o,nodeCount:_.length,error:R instanceof Error?R.message:String(R)});}if(p&&y){let R=Se(p);r.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[o,R]),I=1,r.query("SELECT value FROM meta WHERE key = ?",["vectorDims"])[0]||r.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["vectorDims",String(y)]);}r.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[o]),r.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(" "):""]),D.push(...Array.from(b.values()));}),u.length>0&&a$1.isInitialized()&&a$1.capabilities().embedding)try{let b=u.map(f=>f.name),_=await a$1.embedMany(b),R=new Date().toISOString();for(let f=0;f<u.length;f++){let O=u[f],F=_[f];if(!O||!F||F.length===0)continue;let k=Se(new Float32Array(F));r.run("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)",[Ie(O.name),k]),r.run("UPDATE nodes SET embedding = ?, updatedAt = ? WHERE id = ?",[k,R,O.nodeId]);}}catch(b){ae.warn("memory entity name batch embed failed (non-fatal)",{pendingCount:u.length,error:b instanceof Error?b.message:String(b)});}ae.info("Memory stored",{id:o,category:e$1.category,agentId:t.agentId,nodeCount:D.length,vectorsWritten:I,vectorDims:y??0,embeddingMode:l?"enabled":"fts_only",entitiesExtracted:h.length,relationsExtracted:M.length});let E={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:D.length>0?D:void 0,filePath:void 0,createdAt:n,updatedAt:n},C="",v=await oe.write(E,t.workspaceDir);if(v.ok){C=v.relPath,E.filePath=v.relPath;try{r.run("UPDATE memory_facts SET file_path = ? WHERE id = ?",[v.relPath,o]);}catch(b){ae.warn("Failed to update file_path column after sync",{id:o,error:b instanceof Error?b.message:String(b)});}}return {fact:E,filePath:C,deduplicated:!1,nodeIds:D,vectorsWritten:I,vectorDims:y??0,entitiesExtracted:h.length,relationsExtracted:M.length}}catch(n){throw n instanceof S?n:new S(`remember failed: ${n instanceof Error?n.message:String(n)}`,"INTERNAL",{cause:n instanceof Error?n.message:String(n)})}finally{r.close();}}function $t(){let t=Date.now(),e=randomBytes(3).toString("hex");return `mem_${t}_${e}`}function Se(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}function Ie(t){return createHash("sha256").update(t).digest("hex")}async function Ht(t,e){let r=Ie(e),n=t.prepare("SELECT embedding FROM embedding_cache WHERE content_hash = ?").get(r);if(n?.embedding)return new Float32Array(n.embedding.buffer,n.embedding.byteOffset,n.embedding.byteLength/4);let o=await a$1.embedText(e);if(!o||o.length===0)return null;let c=Se(o);return t.prepare("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)").run(r,c),o}async function Ut(t,e){let r=await GraphProvider.generateGraph({chunks:[e],model:t,includeRules:false});return {entities:r.entities,relations:r.relations}}var _e=Log.create({service:"memory.service.update"});function jt(t){if(t.content===void 0&&t.category===void 0&&t.importance===void 0&&t.tags===void 0)throw new S("update requires at least one of: `content`, `category`, `importance`, `tags`","CONTENT_REQUIRED");if(t.content!==void 0&&t.content.trim().length===0)throw new S("update: `content` cannot be empty (use `forget` to delete)","CONTENT_REQUIRED");if(t.importance!==void 0&&(t.importance<1||t.importance>10))throw new S(`update: \`importance\` must be 1-10, got ${t.importance}`,"IMPORTANCE_REQUIRED")}async function at(t,e$1){let r=Date.now();H(t),te(t),jt(e$1),_e.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 n=e$1.content!==void 0,o=n&&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){_e.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(),g=[];s.transaction(()=>{let h=s.query("SELECT id, content, category, importance, tags FROM memory_facts WHERE id = ? AND agent_id = ?",[e$1.factId,t.agentId])[0];if(!h)throw new ce(e$1.factId);let M=["updated_at = ?"],D=[i];if(e$1.content!==void 0&&e$1.content!==h.content&&(M.push("content = ?"),D.push(e$1.content),g.push("content")),e$1.category!==void 0&&e$1.category!==h.category&&(M.push("category = ?"),D.push(e$1.category),g.push("category")),e$1.importance!==void 0&&e$1.importance!==h.importance&&(M.push("importance = ?"),D.push(e$1.importance),g.push("importance")),e$1.tags!==void 0){let I=e$1.tags.length>0?JSON.stringify(e$1.tags):null;I!==h.tags&&(M.push("tags = ?"),D.push(I),g.push("tags"));}if(g.length>0&&s.run(`UPDATE memory_facts SET ${M.join(", ")} WHERE id = ? AND agent_id = ?`,[...D,e$1.factId,t.agentId]),g.includes("content")||g.includes("tags")){let I=e$1.content??h.content,u=g.includes("tags")?e$1.tags&&e$1.tags.length>0?JSON.stringify(e$1.tags):null:h.tags,E=u?(()=>{try{let C=JSON.parse(u);return Array.isArray(C)?C.filter(v=>typeof v=="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,I,E.join(" ")]);}if(g.includes("content")&&c){let I=Bt(c);s.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[e$1.factId,I]);try{let u=zt(e$1.content);s.run("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)",[u,I]);}catch{}}});let l=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(!l)throw new S(`update: failed to read back updated fact ${e$1.factId}`,"INTERNAL");let p;if(l.tags)try{let h=JSON.parse(l.tags);Array.isArray(h)&&(p=h.filter(M=>typeof M=="string"));}catch{}let y={id:l.id,agentId:l.agent_id,sessionId:l.session_id??void 0,msgId:l.msg_id??void 0,parentMsgId:l.parent_msg_id??void 0,content:l.content,category:l.category,importance:l.importance,source:l.source,tags:p,filePath:l.file_path??void 0,createdAt:l.created_at,updatedAt:l.updated_at};return _e.info("Memory updated",{agentId:t.agentId,factId:e$1.factId,fieldsUpdated:g,contentChanged:n,durationMs:Date.now()-r}),{fact:y,contentChanged:n,fieldsUpdated:g,durationMs:Date.now()-r}}catch(i){throw i instanceof S?i:new S(`update failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}function Bt(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}function zt(t){return createHash("sha256").update(t).digest("hex")}var Me=Log.create({service:"memory.service.forget"}),Kt=1e3;function Jt(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 S("CONTENT_REQUIRED: forget requires one of: `factId`, `category`, or `fromTime`/`toTime`","CONTENT_REQUIRED");if(e.length>1)throw new S(`mutually exclusive: forget requires exactly one of factId/category/timeRange, got [${e.join(", ")}]`,"CONTENT_REQUIRED");return e[0]}function Vt(t,e,r){let n=[r];switch(t){case "factId":return {where:"agent_id = ? AND id = ?",args:[...n,e.factId]};case "category":return {where:"agent_id = ? AND category = ?",args:[...n,e.category]};case "timeRange":{let o=["agent_id = ?"];return e.fromTime&&(o.push("created_at >= ?"),n.push(e.fromTime)),e.toTime&&(o.push("created_at <= ?"),n.push(e.toTime)),{where:o.join(" AND "),args:n}}}}function Yt(t,e,r,n){return t.query(`SELECT id FROM memory_facts WHERE ${e} LIMIT ?`,[...r,n+1]).map(c=>c.id)}function Xt(t,e,r,n){if(r.length===0)return 0;let o=r.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})`,[n,e,...r])[0]?.count??0}function Zt(t,e,r){let n,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,r])[0],g=t.query("SELECT node_id FROM fact_nodes WHERE fact_id = ?",[e]).map(l=>l.node_id).filter(l=>typeof l=="number");if(n=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,r]),g.length>0){let l=g.map(()=>"?").join(",");t.run(`DELETE FROM nodes WHERE id IN (${l}) AND NOT EXISTS (
42
+ SELECT 1 FROM fact_nodes fn WHERE fn.node_id = nodes.id
43
+ )`,g);}}),{filePath:n,category:o,createdAt:c}}async function st(t,e$1){H(t),Q(t,"forget");let r=Jt(e$1),n=e$1.maxDelete??Kt,o=e$1.dryRun??false,c=e$1.force??false;Me.debug("forget invoked",{agentId:t.agentId,mode:r,maxDelete:n,dryRun:o,force:c});let s=new e(t.dbPath);try{await s.initialize();let{where:i,args:g}=Vt(r,e$1,t.agentId),l=Yt(s,i,g,n),p=l.length>n;if(p&&!c)throw new ge(l.length,n);let y=p?l.slice(0,n):l;if(o)throw new le(y.length);let h=[],M=[];for(let D of y){if(!c){let v=s.query("SELECT node_id FROM fact_nodes WHERE fact_id = ? AND node_id IS NOT NULL",[D]).map(_=>_.node_id).filter(_=>typeof _=="number"),b=Xt(s,D,v,t.agentId);if(b>0)throw new me(D,b)}let{filePath:I,category:u,createdAt:E}=Zt(s,D,t.agentId);I&&u&&M.push({id:D,filePath:I,category:u,createdAt:E}),h.push(D);}Me.info("forget complete",{agentId:t.agentId,mode:r,deletedCount:h.length,force:c,dryRun:o});for(let{id:D,filePath:I,category:u,createdAt:E}of M)await oe.delete({id:D,filePath:I,category:u,createdAt:E},t.workspaceDir).catch(C=>{Me.warn("Fact file delete failed (best-effort)",{id:D,filePath:I,error:C instanceof Error?C.message:String(C)});});return {deletedCount:h.length,deletedIds:h,dryRun:o,truncatedCount:p?l.length-n:0}}catch(i){throw i instanceof S?i:new S(`forget failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var it=Log.create({service:"memory.service.extract"}),tn=50,De=500;async function ct(t,e$1){if(H(t),!e$1.sessionId||e$1.sessionId.trim().length===0)throw new S("extract requires non-empty `sessionId`","SESSION_ID_REQUIRED");let r=e$1.lastN??tn;if(r>De)throw new S(`extract lastN=${r} exceeds max=${De}`,"CONTENT_REQUIRED",{lastN:r,maxLastN:De});let n=e$1.sessionId,o=e$1.fromMessageId;it.debug("extract invoked",{agentId:t.agentId,sessionId:n,lastN:r,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,n,r]),g=o?i.filter(u=>u.id>o):i,l=g.map(u=>u.id),p=l.length>0?s.query(`SELECT node_id FROM fact_nodes WHERE fact_id IN (${l.map(()=>"?").join(",")})`,l):[],y=new Set;for(let u of p)typeof u.node_id=="number"&&u.node_id>0&&y.add(u.node_id);let h=Array.from(y),M=[],D=[];if(h.length>0){let u=h.map(()=>"?").join(","),E=s.query(`SELECT id, name, type FROM nodes WHERE id IN (${u})`,h),C=new Map;for(let _ of E)C.set(_.id,_.name);M=E.map(_=>({id:_.id,name:_.name,type:_.type}));let v=s.query(`SELECT source, target, relation FROM edges WHERE source IN (${u}) OR target IN (${u})`,[...h,...h]),b=new Set;D=[];for(let _ of v){let R=C.get(_.source),f=C.get(_.target);if(!R||!f)continue;let O=`${R}\0${_.relation}\0${f}`;b.has(O)||(b.add(O),D.push({source:R,target:f,relation:_.relation}));}}let I=Date.now()-c;return it.info("extract complete",{agentId:t.agentId,sessionId:n,factCount:g.length,nodeCount:M.length,relationCount:D.length,durationMs:I}),{extractedCount:g.length,factIds:g.map(u=>u.id),entities:M,relations:D,messageRange:{fromMessageId:g[0]?.id??"",toMessageId:g[g.length-1]?.id??""},durationMs:I}}catch(i){throw i instanceof S?i:new S(`extract failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var Oe=Log.create({service:"memory.service.consolidate"}),rn=30;async function on(t){let{createHash:e}=await import('crypto');return e("sha256").update(t).digest("hex")}async function dt(t,e$1={}){let r=Date.now();H(t),Q(t,"consolidate");let n=e$1.windowDays??rn,o=e$1.dryRun??false;Oe.debug("consolidate invoked",{agentId:t.agentId,windowDays:n,dryRun:o});let c=new e(t.dbPath);try{await c.initialize();let s=c.query("SELECT id, content, category, importance, created_at FROM memory_facts WHERE agent_id = ? ORDER BY created_at DESC",[t.agentId]),i=new Map;for(let u of s){let E=await on(u.content);i.has(E)||i.set(E,[]),i.get(E)?.push(u);}let g=0,l=[];for(let[,u]of i){if(u.length<=1)continue;let E=[...u].sort((b,_)=>b.importance!==_.importance?_.importance-b.importance:_.created_at.localeCompare(b.created_at)),C=E[0];if(!C)continue;let v=E.slice(1).map(b=>b.id);g+=v.length,l.push({keep:C,removeIds:v});}let p=new Date(Date.now()-n*24*60*60*1e3).toISOString(),y=c.query(`SELECT id, content, category, importance, created_at FROM memory_facts
48
+ WHERE agent_id = ? AND created_at < ?
49
+ ORDER BY created_at ASC`,[t.agentId,p]),h=0,M=0;if(o)h=0,M=g;else {let u=pe.join(t.workspaceDir,"archive");await K.mkdir(u,{recursive:!0});for(let{removeIds:E}of l){if(E.length===0)continue;let C=E.map(()=>"?").join(",");c.transaction(()=>{for(let v of E)c.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[v,t.agentId]);}),M+=E.length;}for(let E of y){let C=E.created_at.slice(0,7),v=pe.join(u,C,E.category);await K.mkdir(v,{recursive:!0});let b=pe.join(v,`${E.id}.md`);try{await K.writeFile(b,[`# ${E.id}`,"",`category: ${E.category}`,`importance: ${E.importance}`,`createdAt: ${E.created_at}`,"",E.content,""].join(`
50
+ `),"utf-8"),c.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[E.id,t.agentId]),h++;}catch(_){Oe.warn("consolidate: archive write failed",{factId:E.id,error:_ instanceof Error?_.message:String(_)});}}}let D=s.length,I=0;return Oe.info("consolidate complete",{agentId:t.agentId,totalFacts:D,dedupedCount:g,compressedCount:I,archivedCount:h,skippedCount:M,dryRun:o,durationMs:Date.now()-r}),{totalFacts:D,dedupedCount:g,compressedCount:I,archivedCount:h,skippedCount:M,durationMs:Date.now()-r}}catch(s){throw s instanceof S?s:new S(`consolidate failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{c.close();}}var G=Log.create({service:"memory.service.sync"}),cn=30,dn=".easbot/memory/active",mt=".easbot/memory/archive";function mn(t,e){let n=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:n.length>0?n:void 0,filePath:e.file_path??void 0,createdAt:e.created_at,updatedAt:e.updated_at}}async function ln(t,e){let r=0,n=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,
51
+ source, tags, file_path, created_at, updated_at
52
+ FROM memory_facts ${c}
53
+ ORDER BY created_at ASC`,s);for(let g of i){let l=mn(t,g);if(g.file_path?.startsWith(`${mt}/`)){n++;continue}let p=fe(l,e.workspaceDir);try{await K.access(p),n++;continue}catch(h){let M=h;if(M.code!=="ENOENT"){G.warn("sync generate: fs.access failed (non-ENOENT)",{factId:l.id,absPath:p,error:M.message}),o++;continue}}let y=await oe.write(l,e.workspaceDir);y.ok?r++:(o++,G.warn("sync generate: factFileSync.write failed",{factId:l.id,absPath:p,error:y.error}));}return G.debug("sync stage A complete",{agentId:e.agentId,generatedCount:r,skippedCount:n,failedGenerateCount:o}),{generatedCount:r,skippedCount:n,failedGenerateCount:o}}async function gn(t,e,r,n){let o=r*24*60*60*1e3,c=Date.now(),s=formatLocalISO(new Date(c-o)),i=[],g=pe.join(e.workspaceDir,dn),l=await un(g);G.debug("sync stage B: scan active dir",{activeDir:g,fileCount:l.length,windowDays:r,threshold:s,dryRun:n});for(let p of l){let y=await fn(p);if(!y){G.warn("sync stage B: skip unparseable file",{absPath:p});continue}let{firstCreatedAt:h,firstFactId:M}=y,D=new Date(h).getTime();if(Number.isNaN(D)){G.warn("sync stage B: skip invalid createdAt",{absPath:p,firstCreatedAt:h});continue}if(c-D<=o)continue;let I=pn(p);if(!I){G.warn("sync stage B: cannot infer category from path",{absPath:p});continue}let u=h.slice(0,7),E=pe.join(e.workspaceDir,mt,u,I),C=pe.basename(p),v=pe.join(E,C);if(n){i.push({source:p,target:v,firstCreatedAt:h,firstFactId:M});continue}try{await K.mkdir(E,{recursive:!0});try{await K.rename(p,v);}catch(R){let f=R;G.warn("sync stage B: fs.rename failed, falling back to copy+unlink",{absPath:p,targetPath:v,error:f.message}),await K.copyFile(p,v),await K.unlink(p);}let b=re(p,e.workspaceDir),_=re(v,e.workspaceDir);t.run(`UPDATE memory_facts SET file_path = ?
54
+ WHERE agent_id = ? AND file_path = ?`,[_,e.agentId??"",b]),i.push({source:p,target:v,firstCreatedAt:h,firstFactId:M});}catch(b){G.warn("sync stage B: archive failed",{absPath:p,targetPath:v,error:b instanceof Error?b.message:String(b)});}}return G.debug("sync stage B complete",{agentId:e.agentId,archivedCount:i.length,dryRun:n}),{archivedCount:i.length,archiveThreshold:s,archivedRecords:i}}async function un(t){let e=[];try{await lt(t,e);}catch(r){let n=r;if(n.code==="ENOENT")return e;throw G.warn("sync: listActiveMdFiles failed",{activeDir:t,error:n.message}),new S(`sync: listActiveMdFiles failed: ${n.message}`,"INTERNAL",{cause:n.message})}return e}async function lt(t,e){let r=await K.readdir(t,{withFileTypes:true});for(let n of r){let o=pe.join(t,n.name);n.isDirectory()?await lt(o,e):n.isFile()&&n.name.endsWith(".md")&&e.push(o);}}async function fn(t){let e;try{e=await K.readFile(t,"utf-8");}catch(s){if(s.code==="ENOENT")return null;throw s}if(!e.startsWith(`---
55
+ `))return null;let r=e.indexOf(`
56
+ ---
57
+ `,4);if(r===-1)return null;let n=e.slice(4,r),o,c;for(let s of n.split(`
58
+ `)){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 pn(t){let e=t.replace(/\\/g,"/").split("/"),r=e.findIndex(c=>c==="active");if(r===-1)return null;let n=e.slice(r+1);return n.length!==2||!n[1].endsWith(".md")?null:n[0]??null}async function gt(t,e$1={}){let r=Date.now();H(t),Q(t,"sync");let n=e$1.windowDays??t.config?.archiveDays??cn,o=e$1.dryRun??false;G.info("sync invoked",{agentId:t.agentId,windowDays:n,dryRun:o,workspaceDir:t.workspaceDir});let c=new e(t.dbPath);try{await c.initialize();let s=await ln(c,t),i=await gn(c,t,n,o),g={generatedCount:s.generatedCount,skippedCount:s.skippedCount,failedGenerateCount:s.failedGenerateCount,archivedCount:i.archivedCount,archiveThreshold:i.archiveThreshold,archivedRecords:i.archivedRecords,windowDays:n,dryRun:o,durationMs:Date.now()-r};return G.info("sync complete",{agentId:t.agentId,...g}),g}catch(s){throw s instanceof S?s:new S(`sync failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{c.close();}}var ut=Log.create({service:"memory.service.graph-query"});async function ft(t,e$1){let r=Date.now(),n=(t.agentId??"").trim()||"default",o=e$1.scope??"agent_only";if(!e$1.query||e$1.query.trim().length===0)throw new S("CONTENT_REQUIRED: graphQuery requires non-empty `query`","CONTENT_REQUIRED");Ee(t,o,"graph_query");let c=e$1.depth??2,s=e$1.maxNodes??100,i=e$1.query,g=e$1.type,l=e$1.relation;ut.debug("graphQuery invoked",{agentId:n,query:i,type:g,depth:c,maxNodes:s,scope:o,remote:t.remote});let p=new e(t.dbPath);try{await p.initialize();let y=new ee(p.getDb()),h=i.includes("*")||i.includes("%")?i:`%${i}%`,M=await y.queryNodes({name:h,...g?{type:g}:{},agentId:n,scope:o,limit:s}),I=(i.includes("*")||i.includes("%")?M:M.filter(R=>R.name.toLowerCase().includes(i.toLowerCase())))[0]??null;if(!I)return {root:null,nodes:[],edges:[],truncated:!1,totalNodes:0,totalEdges:0,scope:o,durationMs:Date.now()-r};let u=await y.queryNeighbors(I.id,c,{agentId:n,scope:o,maxEdgesPerNode:20}),E=new Map;E.set(I.id,I);for(let R of u)E.set(R.id,{id:R.id,name:R.name,type:R.type,createdAt:R.createdAt,updatedAt:R.updatedAt});let C=[];for(let R of u)if(R.edges)for(let f of R.edges)l&&f.relation!==l||C.push(f);for(let R of C){if(!E.has(R.source)){let f=await y.queryNodes({ids:[R.source],agentId:n,scope:o});f[0]&&E.set(f[0].id,f[0]);}if(!E.has(R.target)){let f=await y.queryNodes({ids:[R.target],agentId:n,scope:o});f[0]&&E.set(f[0].id,f[0]);}}let v=Array.from(E.values()),b=v.length>s,_=b?v.slice(0,s):v;return ut.info("graphQuery complete",{agentId:n,rootId:I.id,nodeCount:_.length,edgeCount:C.length,truncated:b,durationMs:Date.now()-r}),{root:I,nodes:_,edges:C,truncated:b,totalNodes:v.length,totalEdges:C.length,scope:o,durationMs:Date.now()-r}}catch(y){throw y instanceof S?y:new S(`graphQuery failed: ${y instanceof Error?y.message:String(y)}`,"INTERNAL",{cause:y instanceof Error?y.message:String(y)})}finally{p.close();}}var B=Log.create({service:"memory.service.init"});function Ne(t){return pe.join(t,".easbot","memory.json")}async function En(t){try{let{Config:e}=await import('@easbot/llm'),r=await e.get(),n=o=>typeof o=="string"&&o.length>0?o:void 0;return {embeddingModel:n(r.embedding_model),graphModel:n(r.graph_model)}}catch{return {}}}function wn(t,e={}){let r={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(r,null,2),"utf-8");}async function pt(t,e$1={}){let r=Date.now();Q(t,"init");let n=e$1.workspaceDir??t.workspaceDir,o=e$1.dbPath??t.dbPath;if(!n||n.trim().length===0)throw new S("init requires non-empty `workspaceDir` (ctx.workspaceDir or params.workspaceDir)","CONTENT_REQUIRED");if(!o||o.trim().length===0)throw new S("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:n,dbPath:o,force:s});let i=Ne(n);if(!s)try{if(await K.stat(i).then(()=>!0).catch(()=>!1))return B.info("init: idempotent skip (memory.json exists, no --force)",{workspaceDir:n,configPath:i}),{initialized:!1,dbPath:o,configPath:i,configCreated:!1,schemaVersion:a$2,workspaceDir:n,tablesCreated:0,migrationsApplied:0,durationMs:0}}catch{}try{await K.mkdir(pe.dirname(o),{recursive:!0}),await K.mkdir(pe.join(n,".easbot","memory","active"),{recursive:!0}),await K.mkdir(pe.join(n,"archive"),{recursive:!0}),await K.mkdir(pe.join(n,".easbot"),{recursive:!0});}catch(y){throw new S(`init: failed to create directories: ${y instanceof Error?y.message:String(y)}`,"INTERNAL",{cause:y instanceof Error?y.message:String(y)})}if(s)for(let y of [o,`${o}-wal`,`${o}-shm`])try{await K.rm(y,{force:!0});}catch(h){B.warn("init: force rm failed (may not exist)",{path:y,error:h instanceof Error?h.message:String(h)});}let g=await En(),l=false;try{!await K.stat(i).then(()=>!0).catch(()=>!1)||s?(wn(i,{embeddingModel:g.embeddingModel,graphModel:g.graphModel,archiveDays:t.config?.archiveDays,shortTermMaxRounds:t.config?.shortTermMaxRounds}),l=!0,B.info("init: memory.json written",{configPath:i,force:s,configCreated:l})):B.debug("init: memory.json already exists, skipping write",{configPath:i});}catch(y){B.warn("init: memory.json write failed (non-fatal)",{configPath:i,error:y instanceof Error?y.message:String(y)});}let p=new e(o);try{let y=await K.stat(o).then(()=>!0).catch(()=>!1);await p.initialize();let h=new Date().toISOString(),M=[["version","1.0.0"],["schemaVersion",String(a$2)],["createdAt",h],["defaultAgentId",c]];for(let[u,E]of M)try{p.run("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)",[u,E]);}catch(C){B.warn("init: meta insert failed",{key:u,error:C instanceof Error?C.message:String(C)});}let D=0;try{D=p.prepare("SELECT COUNT(*) as n FROM sqlite_master WHERE type IN ('table', 'index', 'trigger', 'view')").get()?.n??0;}catch(u){B.warn("init: tablesCreated count failed",{error:u instanceof Error?u.message:String(u)});}let I=0;try{I=p.prepare("SELECT id FROM schema_migrations").all().length;}catch(u){B.warn("init: migrationsApplied count failed",{error:u instanceof Error?u.message:String(u)});}return B.info("init complete",{agentId:c,workspaceDir:n,dbPath:o,configPath:i,configCreated:l,schemaVersion:a$2,durationMs:Date.now()-r}),{initialized:!0,dbPath:o,configPath:i,configCreated:l,schemaVersion:a$2,workspaceDir:n,tablesCreated:D,migrationsApplied:I,durationMs:Date.now()-r}}catch(y){throw new S(`init failed: ${y instanceof Error?y.message:String(y)}`,"INTERNAL",{cause:y instanceof Error?y.message:String(y)})}finally{p.close();}}var se=Log.create({service:"memory.service.status"}),_n=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"],Mn={};async function yt(t,e$1={},r=Mn){let n=t.agentId&&t.agentId.trim().length>0?t.agentId:void 0;if(se.debug("status invoked",{agentId:n??"<global>"}),!t.dbPath||t.dbPath.length===0)throw new S("`ctx.dbPath` is required","INTERNAL");let o={initialized:false,capabilities:{embedding:false,graphLlm:false}},c={},s={},i=0,g=0,l=0,p,y,h,M=false,D,I="uninitialized",u=false,E=false,C=false,v,b=_n.reduce((O,F)=>(O[F]=0,O),{}),_=new e(t.dbPath);try{await _.initialize(),i=_.query(n!==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",n!==void 0?[n]:[])[0]?.c??0,g=_.query(n!==void 0?"SELECT COUNT(*) AS c FROM nodes WHERE owner_agent_id = ? OR owner_agent_id IS NULL":"SELECT COUNT(*) AS c FROM nodes",n!==void 0?[n]:[])[0]?.c??0,l=_.query("SELECT COUNT(*) as c FROM edges")[0]?.c??0;let j=_.query(n!==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",n!==void 0?[n]:[]);for(let w of j){let T=w.category;T in b&&(b[T]=w.c);}c.facts=i,c.nodes=g,c.edges=l;try{E=_.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]).length>0;}catch(w){se.debug("status: fts probe failed",{error:w instanceof Error?w.message:String(w)});}M=!!t.config?.embeddingLlm;try{u=_.query("SELECT name FROM pragma_table_info('nodes') WHERE name = ?",["owner_agent_id"]).length>0;}catch(w){se.debug("status: kg scope probe failed",{error:w instanceof Error?w.message:String(w)});}C=_.healthCheck();try{let w=_.query("SELECT key, value FROM meta");for(let T of w)s[T.key]=T.value;}catch(w){se.debug("status: meta read failed",{error:w instanceof Error?w.message:String(w)});}let z=s.schema_version,V=s.extraction_version,d=s.lastSyncAt??s.lastSync,m=s.embeddingDims;p=z&&Number.parseInt(z,10)||void 0,y=V&&Number.parseInt(V,10)||void 0,h=d,D=m&&Number.parseInt(m,10)||void 0,i>0&&(I="complete");try{v=_.query("SELECT value FROM meta WHERE key = ?",["backend"])[0]?.value??"better-sqlite3";}catch{v="better-sqlite3";}}catch(O){if(O instanceof S)throw O;se.warn("status: db phase failed; returning partial result",{dbPath:t.dbPath,error:O instanceof Error?O.message:String(O)}),v="unknown",C=false;}finally{_.close();}if(!r.skipLlm&&a$1.isInitialized()){let F=a$1.capabilities();o.initialized=true,o.capabilities={embedding:F.embedding===true,graphLlm:F.graphLlm===true},o.embeddingModel=o.capabilities.embedding?"configured":void 0,o.graphModel=o.capabilities.graphLlm?"configured":void 0;}if(!r.skipEmbeddingProbe&&!r.skipLlm&&o.initialized&&o.capabilities.embedding)try{let O=a$1.getEmbeddingLlm?.();if(O){let F=await probeEmbeddingDims(O,{timeoutMs:5e3});if(typeof F=="number"){D=F,s.embeddingDims=String(F);try{let k=new e(t.dbPath);try{await k.initialize();let j=k.getDb();syncMeta(j,[["embeddingDims",String(F)]]);}finally{k.close();}}catch{}}}}catch{}let R;return C?I==="uninitialized"&&(R="Run `easbot memory remember <content>` to add the first fact."):R="Run `easbot memory init` to initialize the database.",C&&(I??"uninitialized")==="failed"&&(C=false),se.info("status complete",{dbPath:t.dbPath,agentId:n??"<global>",factsCount:i,nodesCount:g,edgesCount:l,healthy:C}),{package:"memory",agentId:n,dbPath:t.dbPath,configPath:Ne(t.workspaceDir),configExists:true,schemaVersion:p,extractionVersion:y,lastSyncAt:h,indexState:I,vectorEnabled:M,embeddingDims:D,llm:o,backend:v,counts:c,meta:s,recommendation:R,healthy:C,factsByCategory:b,kgScopeEnabled:u,factsCount:i,nodesCount:g,edgesCount:l,ftsAvailable:E}}var Nn=Log.create({service:"memory.service.doctor"}),Pe=100*1024*1024,ht=100*1024*1024,Tn={};function N(t,e,r,n,o){return {code:t.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),severity:e,name:t,message:r,details:o,durationMs:n,passed:e!=="error"}}async function bt(t,e$1={},r=Tn){if(Nn.debug("doctor invoked",{agentId:t.agentId}),!t.dbPath||t.dbPath.length===0)throw new Error("`ctx.dbPath` is required");let n=[],o=[],c=Date.now(),s=null,i=false,g=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()-g,{dbPath:t.dbPath});n.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()-g,{dbPath:t.dbPath});n.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}let l=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,w=N("fts",m?"ok":"warn",m?"FTS5 index available":"FTS5 index not found",Date.now()-l,m?{table:d[0]?.name}:void 0);n.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("fts","error",`fts probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-l);n.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);n.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let p=Date.now(),y=!!t.config?.embeddingLlm,h=N("vector","ok",y?"embedding model available":"no embedding model configured (FTS-only mode, recall still functional)",Date.now()-p,{mode:y?"hybrid":"fts_only",model:y?"configured":"missing"});n.push(h),o.push({name:h.name,passed:true,message:h.message,details:h.details,severity:"ok"});let M=Date.now();if(i&&s)try{let d=["memory_facts","nodes","edges","meta"],m=s.query("SELECT name FROM sqlite_master WHERE type = ?",["table"]),w=new Set(m.map($=>$.name)),T=d.filter($=>!w.has($)),P=N("schema",T.length===0?"ok":"error",T.length===0?`schema complete (${d.length} tables)`:`missing tables: ${T.join(", ")}`,Date.now()-M,{required:d,existing:Array.from(w)});n.push(P),o.push({name:P.name,passed:P.severity!=="error",message:P.message,details:P.details,severity:P.severity});}catch(d){let m=N("schema","error",`schema probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-M);n.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);n.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let D=Date.now();try{let d=`${t.dbPath}-wal`,m=`${t.dbPath}-shm`,w=0,T=0;try{w=(await K.stat(d)).size;}catch{w=0;}try{T=(await K.stat(m)).size;}catch{T=0;}let P=w+T,$=P<=ht,U=N("lock",$?"ok":"warn",$?`no lock contention (wal+shm ${(P/1024).toFixed(1)} KB)`:`WAL/SHM files unusually large (${(P/1024/1024).toFixed(1)} MB > ${(ht/1024/1024).toFixed(0)} MB threshold)`,Date.now()-D,{walBytes:w,shmBytes:T});n.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()-D);n.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}let I=Date.now();try{let d=pe.dirname(t.dbPath),m=await K.statfs(d),w=typeof m.bsize=="bigint"?Number(m.bsize)*m.bavail:m.bsize*m.bavail,T=w>=Pe,P=N("disk_space",T?"ok":"error",T?`sufficient disk space (${(w/1024/1024).toFixed(1)} MB available)`:`low disk space (${(w/1024/1024).toFixed(1)} MB < ${(Pe/1024/1024).toFixed(0)} MB threshold)`,Date.now()-I,{availableBytes:w,threshold:Pe});n.push(P),o.push({name:P.name,passed:P.severity!=="error",message:P.message,details:P.details,severity:P.severity});}catch(d){let m=N("disk_space","error",`disk_space probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-I);n.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}let u=Date.now();if(i&&s)try{let d=s.agentFilter(t.agentId),w=s.query(`SELECT COUNT(*) as c FROM memory_facts ${d.where}`,d.params)[0]?.c??0;if(w===0){let T=N("fact_node_consistency","info","no facts in db \u2014 nothing to check",Date.now()-u);n.push(T),o.push({name:T.name,passed:!0,message:T.message,severity:"info"});}else {let P=s.query(`SELECT COUNT(DISTINCT fn.fact_id) as c
59
+ FROM fact_nodes fn
60
+ INNER JOIN memory_facts mf ON mf.id = fn.fact_id
61
+ ${d.where}`,d.params)[0]?.c??0,$=w>0?P/w*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()-u,{facts:w,linked:P,pct:$});n.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()-u);n.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);n.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let E=Date.now();if(i&&s)try{let m=s.query("SELECT COUNT(*) as c FROM nodes"+(t.agentId?" WHERE owner_agent_id = ?":""),t.agentId?[t.agentId]:[])[0]?.c??0;if(m===0){let w=N("node_embedding_coverage","info","no nodes in KG \u2014 nothing to check",Date.now()-E);n.push(w),o.push({name:w.name,passed:!0,message:w.message,severity:"info"});}else {let T=s.query("SELECT COUNT(*) as c FROM nodes WHERE embedding IS NOT NULL"+(t.agentId?" AND owner_agent_id = ?":""),t.agentId?[t.agentId]:[])[0]?.c??0,P=m>0?T/m*100:0,$=P>=50?"ok":P>=30?"info":"warn",U=P>=50?`${P.toFixed(1)}% nodes have embedding (${T}/${m})`:P>=30?`${P.toFixed(1)}% nodes have embedding (${T}/${m}) \u2014 GraphRAG entity vector partial`:`${P.toFixed(1)}% nodes have embedding (${T}/${m}) \u2014 GraphRAG entity vector disabled`,W=N("node_embedding_coverage",$,U,Date.now()-E,{total:m,withEmbedding:T,pct:P});n.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()-E);n.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);n.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 fn.fact_id, fn.node_id
62
+ FROM fact_nodes fn
63
+ LEFT JOIN nodes n ON fn.node_id = n.id
64
+ WHERE n.id IS NULL
65
+ LIMIT 100`).map(T=>`${T.fact_id}->${T.node_id}`),w=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()-C,{count:m.length});n.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("orphan","warn",`orphan probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-C);n.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);n.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let v=Date.now(),b={"better-sqlite3":false,"node:sqlite":false,"@tursodatabase/database":false};try{let d=createRequire(import.meta.url);try{d.resolve("better-sqlite3"),b["better-sqlite3"]=!0;}catch{}b["node:sqlite"]=typeof process.versions.sqlite=="string";try{d.resolve("@tursodatabase/database"),b["@tursodatabase/database"]=!0;}catch{}}catch{}let _=b["better-sqlite3"]||b["node:sqlite"],R=N("backend",_?"ok":"error",_?`SQLite backend available (better-sqlite3: ${b["better-sqlite3"]}, node:sqlite: ${b["node:sqlite"]})`:"no SQLite backend available (install better-sqlite3 or use Node 22.5+)",Date.now()-v,b);n.push(R),o.push({name:R.name,passed:R.severity!=="error",message:R.message,details:R.details,severity:R.severity});let f=Date.now();if(i&&s)try{let d=s.query("SELECT COUNT(*) as c FROM embedding_cache")[0],m=s.agentFilter(t.agentId),w=s.query(`SELECT COUNT(*) as c FROM memory_facts ${m.where}`,m.params)[0],T=d?.c??0,P=w?.c??0,$=Math.max(0,T-P),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()-f,{cacheCount:T,factsCount:P,unused:$,policy:"global_content_hash_dedup"});n.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()-f);n.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);n.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let O=Date.now(),F;if(i&&s)try{let d=s.query("SELECT value FROM meta WHERE key = ?",["embeddingDims"]);F=d[0]?.value&&Number.parseInt(d[0].value,10)||void 0;}catch{}let k;if(r.skipLlm||!a$1.isInitialized()||!a$1.capabilities().embedding)k=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","llm not initialized; probe skipped",Date.now()-O);else if(r.skipEmbeddingProbe)k=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe skipped (--skip-embedding-probe)",Date.now()-O);else try{let d=a$1.getEmbeddingLlm?.();if(!d)k=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","embedding llm not exposed; probe skipped",Date.now()-O);else {let m=await probeEmbeddingDims(d,{timeoutMs:5e3});typeof m!="number"?k=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe failed (network / model error)",Date.now()-O):F===void 0?k=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe=${m}, meta missing \u2014 next status will sync`,Date.now()-O):m!==F?k=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"warn",`probe=${m}, meta=${F} \u2014 mismatch`,Date.now()-O,{probe:m,meta:F}):k=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"ok",`probe=${m}, meta=${F} \u2014 consistent`,Date.now()-O);}}catch(d){k=N(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe threw: ${d instanceof Error?d.message:String(d)}`,Date.now()-O);}n.push({...k,details:k.details??void 0,passed:k.severity!=="error"}),o.push({name:k.name,passed:k.severity!=="error",message:k.message,details:k.details??void 0,severity:k.severity});let j;if(i&&s){let d=Date.now();try{let{issues:m,stats:w}=s.checkIntegrity();j=w;for(let T of m)n.push(N("integrity_stats",T.severity,T.message,0,{source:"database.checkIntegrity"}));}catch(m){n.push(N("integrity_stats","warn",`db integrity check failed: ${m instanceof Error?m.message:String(m)}`,Date.now()-d));}}let z=!n.some(d=>d.severity==="error");s&&s.close();let V=Date.now()-c;return {healthy:z,checks:n,legacyChecks:o,durationMs:V,integrityStats:j,backendAvailable:b}}var ke={name:"recall",scope:"read",schema:ze,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=t;if(!e.agentId?.trim())throw new Error("recall: agentId is required");return Be({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 Ae={name:"remember",scope:"write",schema:Qe,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=t;if(!e.agentId?.trim())throw new Error("remember: 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 xe={name:"update",scope:"write",schema:Ke,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=t;if(!e.agentId?.trim())throw new Error("update: 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 Le={name:"forget",scope:"write",schema:Je,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=t;if(!e.agentId?.trim())throw new Error("forget: agentId is required");return st({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var Fe={name:"extract",scope:"write",schema:Ve,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=t;if(!e.agentId?.trim())throw new Error("extract: agentId is required");return ct({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:"consolidate",scope:"admin",schema:Ye,annotations:{localOnly:true,requiresAgentId:true,defaultDescription:"Run consolidation pipeline: dedup \u2192 archive.",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let r=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 dt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},r)}};var $e={name:"sync",scope:"admin",schema:nt,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=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 gt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},r)}};var He={name:"graph_query",scope:"read",schema:Xe,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Query KG nodes / edges / neighbors with scope filtering.",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=t,n=e.agentId?.trim()||"default";return ft({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:n},r)}};var Ue={name:"status",scope:"read",schema:Ze,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=t??{};return yt({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 We={name:"doctor",scope:"admin",schema:et,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=t??{};if(!e.isTrustedLocal)throw new Error("doctor: only trusted local process can invoke this op");return bt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},r)}};var Ge={name:"init",scope:"admin",schema:tt,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=t??{};return pt({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 Et={[ke.name]:ke,[Ae.name]:Ae,[xe.name]:xe,[Le.name]:Le,[Fe.name]:Fe,[qe.name]:qe,[$e.name]:$e,[He.name]:He,[Ue.name]:Ue,[We.name]:We,[Ge.name]:Ge},Pn=Object.values(Et);function kn(t,e,r){if(t.annotations.localOnly&&!e.isTrustedLocal)throw new Error(`MEMORY:executeOp: op "${r}" is localOnly; non-trusted caller rejected`);if(t.annotations.requiresAgentId){let n=e.agentId?.trim()??"";if(n.length===0)throw new Error(`MEMORY:executeOp: op "${r}" requires agentId`);e.agentId=n;}}async function Ja(t,e,r){let n=Et[t];if(!n)throw new Error(`executeOp: unknown op "${t}"; available: ${Pn.map(c=>c.name).join(", ")}`);return kn(n,r,t),await n.handler(e,r)}function Ln(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 os(t,e,r={}){let n=j(e),o=Locale.resolveLocaleLang(r.locale);return {agentId:t,dbPath:n,workspaceDir:e,rootDir:e,config:Ln({dbPath:n,workspaceDir:e}),isTrustedLocal:true,locale:o,remote:false,...r}}export{ee as a,Be as b,ze as c,Qe as d,Je as e,Ve as f,Ye as g,Xe as h,tt as i,nt as j,ot as k,at as l,st as m,ct as n,dt as o,gt as p,ft as q,pt as r,yt as s,bt as t,Et as u,Pn as v,Ja as w,Ln as x,os as y};
@@ -1 +1 @@
1
- import {f}from'./chunk-WDVDYZ25.mjs';import {Log}from'@easbot/utils';import {renderLines,printHuman,emitJsonOk,formatKnowledgeDoctor,formatKnowledgeStatus,formatKnowledgeInit,emitJsonError}from'@easbot/terminal';var y=Log.create({service:"memory-cli"}),S=[{i18nKey:"cli.cmd.init.description",name:"init",description:"Initialize memory workspace (.easbot/memory.db)",group:"lifecycle"},{i18nKey:"cli.cmd.status.description",name:"status",description:"Show memory state / db stats / facts by category",group:"lifecycle"},{i18nKey:"cli.cmd.doctor.description",name:"doctor",description:"Run health checks (backend, FTS, schema, lock)",group:"lifecycle"},{i18nKey:"cli.cmd.recall.description",name:"recall",description:"Hybrid search (FTS + vector) over memory facts",group:"memory"},{i18nKey:"cli.cmd.remember.description",name:"remember",description:"Persist a new memory fact (with dedup + KG extraction)",group:"memory"},{i18nKey:"cli.cmd.forget.description",name:"forget",description:"Delete memory facts (factId / category / timeRange / dryRun)",group:"memory"},{i18nKey:"cli.cmd.sync.description",name:"sync",description:"Sync facts to .md files (idempotent) and archive expired active files (default 30 days)",group:"memory"},{i18nKey:"cli.cmd.extract.description",name:"extract",description:"Extract facts from a session (sessionId + lastN)",group:"session"},{i18nKey:"cli.cmd.consolidate.description",name:"consolidate",description:"Run consolidation pipeline (extract \u2192 dedup \u2192 archive)",group:"session"},{i18nKey:"cli.cmd.graph.description",name:"graph",description:"KG query (nodes / edges / neighbors with scope \u4E09\u6863)",group:"graph"},{i18nKey:"cli.cmd.config.description",name:"config",description:"Show / validate memory configuration (dry-read)",group:"external"},{i18nKey:"cli.cmd.mcp.description",name:"mcp",description:"Start stdio MCP server (exposes 10 memory tools)",group:"external"}];function u(m,t){let e=S.filter(a=>a.group===m);return renderLines({title:t,flat:e.map(a=>`$ easbot-memory ${a.name.padEnd(14)} ${a.description}`)})}function v(){let m=[renderLines({title:"easbot-memory \xB7 Memory & Knowledge Module for EASBot",flat:["Usage: easbot-memory <command> [options]"]}),"",u("lifecycle","Commands (lifecycle):"),"",u("memory","Commands (memory):"),"",u("session","Commands (session):"),"",u("graph","Commands (graph query):"),"",u("external","External:")];printHuman(m);}function C(){v(),printHuman(["",renderLines({title:"Global flags & invocation",flat:["--cwd <dir> --config <path> --log-level <L> --print-logs --debug","Standalone CLI: easbot-memory <command>","Agent CLI: easbot memory <command>"]})]);}async function j(m){try{let{bootstrapLlm:t}=await import('@easbot/llm'),{Llm:e}=await import('./llm-UHTBU2HA.mjs');await t({target:e,cwd:m,subConfigPath:".easbot/memory.json",embedding:!0,graph:!0});}catch(t){y.warn("bootstrapLlm failed; Llm-related features will be disabled",{error:t instanceof Error?t.message:String(t)});}}async function A(m,t){let[e,...a]=m,c=t?.cwd??process.cwd();if(!e)return C(),{code:0,handled:true,command:null};await j(c);try{switch(e){case "init":{let{parseInitOptions:r,runInit:n}=await import('./init-G2WTR477.mjs'),s=r(a);if(s.help)return console.log("Usage: easbot-memory init [dir] [--agent <id>] [--force] [--json]"),{code:0,handled:!0,command:e};let o=s.workspaceDir?.trim()??c,i=await n({...s,ctxWorkspaceDir:o});if(s.json)emitJsonOk(i,{command:e});else {let p=i;printHuman([formatKnowledgeInit({packageName:"memory",configPath:p.configPath??p.dbPath,backend:"better-sqlite3",schemaVersion:p.schemaVersion,extras:{dbPath:p.dbPath,migrationsApplied:p.migrationsApplied,tablesCreated:p.tablesCreated,durationMs:`${p.durationMs}ms`}})],{title:"init memory workspace",boxed:!0});}return {code:0,handled:!0,command:e}}case "recall":{let{parseRecallOptions:r,runRecall:n,formatRecallText:s}=await import('./recall-SGA2DITO.mjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory recall --query <q> [--agent <id>] [--limit <n>] [--category <c>] [--min-importance <n>] [--json]"),{code:0,handled:!0,command:e};let i=await n({...o,workspaceDir:c});return o.json?emitJsonOk(i,{command:e}):printHuman([s(i)],{title:`recall (agentId=${o.agentId??"default"})`}),{code:0,handled:!0,command:e}}case "remember":{let{parseRememberOptions:r,runRemember:n,formatRememberText:s}=await import('./remember-P3G7WWYB.mjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory remember --content <text> --category <c> --importance <1-10> [--agent <id>] [--tag <t>] [--session <s>] [--json]"),{code:0,handled:!0,command:e};let i=await n({...o,workspaceDir:c});return o.json?emitJsonOk(i,{command:e}):printHuman([s(i)],{title:"remember (persist fact)"}),{code:0,handled:!0,command:e}}case "forget":{let{parseForgetOptions:r,runForget:n,formatForgetText:s}=await import('./forget-VQB5DUJ3.mjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory forget [--agent <id>] (--fact-id <id> | --category <c> | --from <ISO> --to <ISO>) [--max-delete <n>] [--dry-run] [--json]"),{code:0,handled:!0,command:e};let i=await n({...o,workspaceDir:c});return o.json?emitJsonOk(i,{command:e}):printHuman([s(i)],{title:"forget (delete facts)"}),{code:0,handled:!0,command:e}}case "extract":{let{parseExtractOptions:r,runExtract:n,formatExtractText:s}=await import('./extract-3C4QFS7E.mjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory extract --session <sessionId> [--agent <id>] [--last-n <n>] [--from-msg <id>] [--json]"),{code:0,handled:!0,command:e};let i=await n({...o,workspaceDir:c});return o.json?emitJsonOk(i,{command:e}):printHuman([s(i)],{title:"extract (from session)"}),{code:0,handled:!0,command:e}}case "consolidate":{let{parseConsolidateOptions:r,runConsolidate:n,formatConsolidateText:s}=await import('./consolidate-MSPLH3T6.mjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory consolidate [--agent <id>] [--window-days <n>] [--json]"),{code:0,handled:!0,command:e};let i=await n({...o,workspaceDir:c});return o.json?emitJsonOk(i,{command:e}):printHuman([s(i)],{title:"consolidate (pipeline)"}),{code:0,handled:!0,command:e}}case "sync":{let{parseSyncOptions:r,runSync:n,formatSyncText:s}=await import('./sync-ZPRCA4MO.mjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory sync [--agent <id>] [--window-days <n>] [--dry-run] [--json]"),console.log("Two-stage pipeline: (A) db \u2192 .md (idempotent skip on existing), (B) archive active/ files older than windowDays."),{code:0,handled:!0,command:e};let i=await n({...o,workspaceDir:c});return o.json?emitJsonOk(i,{command:e}):printHuman([s(i)],{title:"sync (db \u2192 .md + archive)"}),{code:0,handled:!0,command:e}}case "graph":{let{parseGraphOptions:r,runGraph:n,formatGraphText:s}=await import('./graph-4W63TU2D.mjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory graph [--agent <id>] --kind <nodes|edges|neighbors> [--query <q>] [--start-node <id>] [--depth <n>] [--max-nodes <n>] [--scope <agent_only|shared_only|both>] [--json]"),{code:0,handled:!0,command:e};let i=await n({...o,workspaceDir:c});return o.json?emitJsonOk(i,{command:e}):printHuman([s(i)],{title:`graph_query (scope=${o.scope??"agent_only"})`}),{code:0,handled:!0,command:e}}case "status":{let{parseStatusOptions:r,runStatus:n}=await import('./status-JYI52QKB.mjs'),s=r(a);if(s.help)return console.log("Usage: easbot-memory status [--agent <id>] [--json]"),{code:0,handled:!0,command:e};let o=await n({...s,workspaceDir:c});return s.json?emitJsonOk(o,{command:e}):printHuman([formatKnowledgeStatus(I(o))],{title:"memory status",boxed:!0}),{code:0,handled:!0,command:e}}case "doctor":{let{parseDoctorOptions:r,runDoctor:n}=await import('./doctor-GKMREWZN.mjs'),s=r(a);if(s.help)return console.log("Usage: easbot-memory doctor [--repair] [--json]"),{code:0,handled:!0,command:e};let o=await n({...s,workspaceDir:c});return s.json?emitJsonOk(o,{command:e}):printHuman([formatKnowledgeDoctor(K(o))],{title:"memory doctor",boxed:!0}),{code:0,handled:!0,command:e}}case "config":{let{parseConfigOptions:r,runConfig:n,formatConfigText:s}=await import('./config-2SQJYVTO.mjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory config [--json]"),{code:0,handled:!0,command:e};let i=n(o);return o.json?emitJsonOk(i,{command:e}):printHuman([s(i)],{title:"memory config"}),{code:0,handled:!0,command:e}}case "mcp":{let{parseMcpOptions:r,runMcp:n}=await import('./mcp-QQBHEZFY.mjs'),s=r(a);if(s.help)return console.log("Usage: easbot-memory mcp [start]"),console.log("Start a stdio MCP server exposing 10 memory tools:"),console.log(" recall / remember / forget / extract / consolidate"),console.log(" graph_query / status / doctor / init / sync"),{code:0,handled:!0,command:e};let o=await n(s);return s.json?emitJsonOk(o,{command:e}):printHuman([`memory mcp started (tools: ${o.tools.length})`],{title:"memory mcp server"}),{code:0,handled:!0,command:e}}default:return console.error(`Unknown command: ${e}`),console.error("Run `easbot-memory --help` for available commands."),{code:2,handled:!1,command:null}}}catch(r){let n=r instanceof Error?r.message:String(r);y.error("memory CLI command failed",{command:e,error:n,stack:r instanceof Error?r.stack:void 0});let s=t?.cwd??f().worktree;return console.error(`[memory] ${s} :: ${e} failed: ${n}`),emitJsonError(e,n),{code:1,handled:true,command:e}}}function I(m){let t=m;return {packageName:"memory",rootDir:t.workspaceDir??"",configPath:t.configPath??"",configExists:true,dbPath:t.dbPath??"",dbExists:true,dbSize:typeof t.dbSize=="number"?t.dbSize:void 0,indexState:t.indexState,schemaVersion:typeof t.schemaVersion=="number"?t.schemaVersion:void 0,extractionVersion:typeof t.extractionVersion=="number"?t.extractionVersion:void 0,lastSyncAt:t.lastSyncAt,vectorEnabled:typeof t.vectorEnabled=="boolean"?t.vectorEnabled:void 0,embeddingDims:typeof t.embeddingDims=="number"?t.embeddingDims:void 0,llm:t.llm??{initialized:false,capabilities:{}},backend:t.backend,counts:t.counts??{},healthy:typeof t.healthy=="boolean"?t.healthy:true,recommendation:t.recommendation,extras:(()=>{let e={};if(typeof t.agentId=="string"&&(e.agent_id=t.agentId),typeof t.ftsAvailable=="boolean"&&(e.fts_available=t.ftsAvailable?"yes":"no"),typeof t.kgScopeEnabled=="boolean"&&(e.kg_scope_enabled=t.kgScopeEnabled?"yes":"no"),t.factsByCategory&&typeof t.factsByCategory=="object"){let a=t.factsByCategory;for(let[c,r]of Object.entries(a))typeof r=="number"&&r>0&&(e[`facts/${c}`]=r);}return Object.keys(e).length>0?e:void 0})()}}function K(m){let t=m,e=Array.isArray(t.checks)?t.checks:[],a=t.integrityStats,c=t.backendAvailable,r=a?{nodes:a.nodes??0,edges:a.edges??0,file_hashes:0,fts:a.memory_facts_fts??0,node_embeddings:a.memory_vectors??0,embedding_cache:a.embedding_cache??0,parse_errors:0,unresolved_refs:0,name_segment_vocab:0,project_metadata:0,meta:a.meta??0}:void 0;return {packageName:"memory",healthy:typeof t.healthy=="boolean"?t.healthy:false,durationMs:typeof t.durationMs=="number"?t.durationMs:0,checks:e.map(n=>({code:typeof n.code=="string"?n.code:"",severity:n.severity??"info",name:typeof n.name=="string"?n.name:"",message:typeof n.message=="string"?n.message:"",durationMs:typeof n.durationMs=="number"?n.durationMs:void 0,details:n.details})),dbStats:r,backendAvailable:c}}export{S as a,v as b,C as c,A as d};
1
+ import {f}from'./chunk-WDVDYZ25.mjs';import {Log}from'@easbot/utils';import {renderLines,printHuman,emitJsonOk,formatKnowledgeDoctor,formatKnowledgeStatus,formatKnowledgeInit,emitJsonError}from'@easbot/terminal';var y=Log.create({service:"memory-cli"}),S=[{i18nKey:"cli.cmd.init.description",name:"init",description:"Initialize memory workspace (.easbot/memory.db)",group:"lifecycle"},{i18nKey:"cli.cmd.status.description",name:"status",description:"Show memory state / db stats / facts by category",group:"lifecycle"},{i18nKey:"cli.cmd.doctor.description",name:"doctor",description:"Run health checks (backend, FTS, schema, lock)",group:"lifecycle"},{i18nKey:"cli.cmd.recall.description",name:"recall",description:"Hybrid search (FTS + vector) over memory facts",group:"memory"},{i18nKey:"cli.cmd.remember.description",name:"remember",description:"Persist a new memory fact (with dedup + KG extraction)",group:"memory"},{i18nKey:"cli.cmd.forget.description",name:"forget",description:"Delete memory facts (factId / category / timeRange / dryRun)",group:"memory"},{i18nKey:"cli.cmd.sync.description",name:"sync",description:"Sync facts to .md files (idempotent) and archive expired active files (default 30 days)",group:"memory"},{i18nKey:"cli.cmd.extract.description",name:"extract",description:"Extract facts from a session (sessionId + lastN)",group:"session"},{i18nKey:"cli.cmd.consolidate.description",name:"consolidate",description:"Run consolidation pipeline (extract \u2192 dedup \u2192 archive)",group:"session"},{i18nKey:"cli.cmd.graph.description",name:"graph",description:"KG query (nodes / edges / neighbors with scope \u4E09\u6863)",group:"graph"},{i18nKey:"cli.cmd.config.description",name:"config",description:"Show / validate memory configuration (dry-read)",group:"external"},{i18nKey:"cli.cmd.mcp.description",name:"mcp",description:"Start stdio MCP server (exposes 10 memory tools)",group:"external"}];function u(m,t){let e=S.filter(i=>i.group===m);return renderLines({title:t,flat:e.map(i=>`$ easbot-memory ${i.name.padEnd(14)} ${i.description}`)})}function v(){let m=[renderLines({title:"easbot-memory \xB7 Memory & Knowledge Module for EASBot",flat:["Usage: easbot-memory <command> [options]"]}),"",u("lifecycle","Commands (lifecycle):"),"",u("memory","Commands (memory):"),"",u("session","Commands (session):"),"",u("graph","Commands (graph query):"),"",u("external","External:")];printHuman(m);}function C(){v(),printHuman(["",renderLines({title:"Global flags & invocation",flat:["--cwd <dir> --config <path> --log-level <L> --print-logs --debug","Standalone CLI: easbot-memory <command>","Agent CLI: easbot memory <command>"]})]);}async function I(m){try{let{bootstrapLlm:t}=await import('@easbot/llm'),{Llm:e}=await import('./llm-UHTBU2HA.mjs');await t({target:e,cwd:m,subConfigPath:".easbot/memory.json",embedding:!0,graph:!0});}catch(t){y.warn("bootstrapLlm failed; Llm-related features will be disabled",{error:t instanceof Error?t.message:String(t)});}}async function O(m,t){let[e,...i]=m,c=t?.cwd??process.cwd();if(!e)return C(),{code:0,handled:true,command:null};await I(c);try{switch(e){case "init":{let{parseInitOptions:r,runInit:n}=await import('./init-2ZTVBJ6N.mjs'),s=r(i);if(s.help)return console.log("Usage: easbot-memory init [dir] [--agent <id>] [--force] [--json]"),{code:0,handled:!0,command:e};let o=s.workspaceDir?.trim()??c,a=await n({...s,ctxWorkspaceDir:o});if(s.json)emitJsonOk(a,{command:e});else {let p=a;printHuman([formatKnowledgeInit({packageName:"memory",configPath:p.configPath??p.dbPath,backend:"better-sqlite3",schemaVersion:p.schemaVersion,extras:{dbPath:p.dbPath,migrationsApplied:p.migrationsApplied,tablesCreated:p.tablesCreated,durationMs:`${p.durationMs}ms`}})],{title:"init memory workspace",boxed:!0});}return {code:0,handled:!0,command:e}}case "recall":{let{parseRecallOptions:r,runRecall:n,formatRecallText:s}=await import('./recall-VMW7Y55X.mjs'),o=r(i);if(o.help)return console.log("Usage: easbot-memory recall --query <q> [--agent <id>] [--limit <n>] [--category <c>] [--min-importance <n>] [--json]"),{code:0,handled:!0,command:e};let a=await n({...o,workspaceDir:c});return o.json?emitJsonOk(a,{command:e}):printHuman([s(a)],{title:`recall (agentId=${o.agentId??"default"})`}),{code:0,handled:!0,command:e}}case "remember":{let{parseRememberOptions:r,runRemember:n,formatRememberText:s}=await import('./remember-ZVTM3IP4.mjs'),o=r(i);if(o.help)return console.log("Usage: easbot-memory remember --content <text> --category <c> --importance <1-10> [--agent <id>] [--tag <t>] [--session <s>] [--json]"),{code:0,handled:!0,command:e};let a=await n({...o,workspaceDir:c});return o.json?emitJsonOk(a,{command:e}):printHuman([s(a)],{title:"remember (persist fact)"}),{code:0,handled:!0,command:e}}case "forget":{let{parseForgetOptions:r,runForget:n,formatForgetText:s}=await import('./forget-CRDWG4XE.mjs'),o=r(i);if(o.help)return console.log("Usage: easbot-memory forget [--agent <id>] (--fact-id <id> | --category <c> | --from <ISO> --to <ISO>) [--max-delete <n>] [--dry-run] [--json]"),{code:0,handled:!0,command:e};let a=await n({...o,workspaceDir:c});return o.json?emitJsonOk(a,{command:e}):printHuman([s(a)],{title:"forget (delete facts)"}),{code:0,handled:!0,command:e}}case "extract":{let{parseExtractOptions:r,runExtract:n,formatExtractText:s}=await import('./extract-WH4DU4NQ.mjs'),o=r(i);if(o.help)return console.log("Usage: easbot-memory extract --session <sessionId> [--agent <id>] [--last-n <n>] [--from-msg <id>] [--json]"),{code:0,handled:!0,command:e};let a=await n({...o,workspaceDir:c});return o.json?emitJsonOk(a,{command:e}):printHuman([s(a)],{title:"extract (from session)"}),{code:0,handled:!0,command:e}}case "consolidate":{let{parseConsolidateOptions:r,runConsolidate:n,formatConsolidateText:s}=await import('./consolidate-JBTOQWUX.mjs'),o=r(i);if(o.help)return console.log("Usage: easbot-memory consolidate [--agent <id>] [--window-days <n>] [--json]"),{code:0,handled:!0,command:e};let a=await n({...o,workspaceDir:c});return o.json?emitJsonOk(a,{command:e}):printHuman([s(a)],{title:"consolidate (pipeline)"}),{code:0,handled:!0,command:e}}case "sync":{let{parseSyncOptions:r,runSync:n,formatSyncText:s}=await import('./sync-KWHUII26.mjs'),o=r(i);if(o.help)return console.log("Usage: easbot-memory sync [--agent <id>] [--window-days <n>] [--dry-run] [--json]"),console.log("Two-stage pipeline: (A) db \u2192 .md (idempotent skip on existing), (B) archive active/ files older than windowDays."),{code:0,handled:!0,command:e};let a=await n({...o,workspaceDir:c});return o.json?emitJsonOk(a,{command:e}):printHuman([s(a)],{title:"sync (db \u2192 .md + archive)"}),{code:0,handled:!0,command:e}}case "graph":{let{parseGraphOptions:r,runGraph:n,formatGraphText:s}=await import('./graph-T66JXDLU.mjs'),o=r(i);if(o.help)return console.log("Usage: easbot-memory graph [--agent <id>] --kind <nodes|edges|neighbors> [--query <q>] [--start-node <id>] [--depth <n>] [--max-nodes <n>] [--scope <agent_only|shared_only|both>] [--json]"),{code:0,handled:!0,command:e};let a=await n({...o,workspaceDir:c});return o.json?emitJsonOk(a,{command:e}):printHuman([s(a)],{title:`graph_query (scope=${o.scope??"agent_only"})`}),{code:0,handled:!0,command:e}}case "status":{let{parseStatusOptions:r,runStatus:n}=await import('./status-LHXMB3ZY.mjs'),s=r(i);if(s.help)return console.log("Usage: easbot-memory status [--agent <id>] [--json]"),{code:0,handled:!0,command:e};let o=await n({...s,workspaceDir:c});return s.json?emitJsonOk(o,{command:e}):printHuman([formatKnowledgeStatus(K(o))],{title:"memory status",boxed:!0}),{code:0,handled:!0,command:e}}case "doctor":{let{parseDoctorOptions:r,runDoctor:n}=await import('./doctor-DLQO7QMW.mjs'),s=r(i);if(s.help)return console.log("Usage: easbot-memory doctor [--repair] [--json]"),{code:0,handled:!0,command:e};let o=await n({...s,workspaceDir:c});return s.json?emitJsonOk(o,{command:e}):printHuman([formatKnowledgeDoctor(j(o))],{title:"memory doctor",boxed:!0}),{code:0,handled:!0,command:e}}case "config":{let{parseConfigOptions:r,runConfig:n,formatConfigText:s}=await import('./config-2SQJYVTO.mjs'),o=r(i);if(o.help)return console.log("Usage: easbot-memory config [--json]"),{code:0,handled:!0,command:e};let a=n(o);return o.json?emitJsonOk(a,{command:e}):printHuman([s(a)],{title:"memory config"}),{code:0,handled:!0,command:e}}case "mcp":{let{parseMcpOptions:r,runMcp:n}=await import('./mcp-OAUOA4PI.mjs'),s=r(i);if(s.help)return console.log("Usage: easbot-memory mcp [start]"),console.log("Start a stdio MCP server exposing 10 memory tools:"),console.log(" recall / remember / forget / extract / consolidate"),console.log(" graph_query / status / doctor / init / sync"),{code:0,handled:!0,command:e};let o=await n(s);return s.json?emitJsonOk(o,{command:e}):printHuman([`memory mcp started (tools: ${o.tools.length})`],{title:"memory mcp server"}),{code:0,handled:!0,command:e}}default:return console.error(`Unknown command: ${e}`),console.error("Run `easbot-memory --help` for available commands."),{code:2,handled:!1,command:null}}}catch(r){let n=r instanceof Error?r.message:String(r);y.error("memory CLI command failed",{command:e,error:n,stack:r instanceof Error?r.stack:void 0});let s=t?.cwd??f().worktree;return console.error(`[memory] ${s} :: ${e} failed: ${n}`),emitJsonError(e,n),{code:1,handled:true,command:e}}}function K(m){let t=m;return {packageName:"memory",rootDir:t.workspaceDir??"",configPath:t.configPath??"",configExists:true,dbPath:t.dbPath??"",dbExists:true,dbSize:typeof t.dbSize=="number"?t.dbSize:void 0,indexState:t.indexState,schemaVersion:typeof t.schemaVersion=="number"?t.schemaVersion:void 0,extractionVersion:typeof t.extractionVersion=="number"?t.extractionVersion:void 0,lastSyncAt:t.lastSyncAt,vectorEnabled:typeof t.vectorEnabled=="boolean"?t.vectorEnabled:void 0,embeddingDims:typeof t.embeddingDims=="number"?t.embeddingDims:void 0,llm:t.llm??{initialized:false,capabilities:{}},backend:t.backend,counts:t.counts??{},healthy:typeof t.healthy=="boolean"?t.healthy:true,recommendation:t.recommendation,extras:(()=>{let e={};if(typeof t.agentId=="string"&&(e.agent_id=t.agentId),typeof t.ftsAvailable=="boolean"&&(e.fts_available=t.ftsAvailable?"yes":"no"),typeof t.kgScopeEnabled=="boolean"&&(e.kg_scope_enabled=t.kgScopeEnabled?"yes":"no"),t.factsByCategory&&typeof t.factsByCategory=="object"){let i=t.factsByCategory;for(let[c,r]of Object.entries(i))typeof r=="number"&&r>0&&(e[`facts/${c}`]=r);}return Object.keys(e).length>0?e:void 0})()}}function j(m){let t=m,e=Array.isArray(t.checks)?t.checks:[],i=t.integrityStats,c=t.backendAvailable,r=i?{...i}:void 0;return {packageName:"memory",healthy:typeof t.healthy=="boolean"?t.healthy:false,durationMs:typeof t.durationMs=="number"?t.durationMs:0,checks:e.map(n=>({code:typeof n.code=="string"?n.code:"",severity:n.severity??"info",name:typeof n.name=="string"?n.name:"",message:typeof n.message=="string"?n.message:"",durationMs:typeof n.durationMs=="number"?n.durationMs:void 0,details:n.details})),dbStats:r,backendAvailable:c}}export{S as a,v as b,C as c,O as d,j as e};
@@ -0,0 +1,65 @@
1
+ 'use strict';var chunkEK34SXJ7_cjs=require('./chunk-EK34SXJ7.cjs'),chunkCPRDIUQ4_cjs=require('./chunk-CPRDIUQ4.cjs'),chunkJ5XF2W4Z_cjs=require('./chunk-J5XF2W4Z.cjs'),chunkM2YU5LAI_cjs=require('./chunk-M2YU5LAI.cjs'),utils=require('@easbot/utils'),zod=require('zod'),crypto=require('crypto'),llm=require('@easbot/llm'),Q=require('fs/promises'),fe=require('path'),fs=require('fs'),module$1=require('module'),types=require('@easbot/types');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Q__default=/*#__PURE__*/_interopDefault(Q);var fe__default=/*#__PURE__*/_interopDefault(fe);var ye=utils.Log.create({service:"memory.graph-store"}),Z=class{constructor(e){chunkM2YU5LAI_cjs.a(this,"db");this.db=e;}async upsertNode(e,r,n,o){let c=Date.now(),s=JSON.stringify(n??{}),i=this.db.prepare("SELECT id FROM nodes WHERE name = ? AND type = ? LIMIT 1").get(e,r);if(i)return this.db.prepare("UPDATE nodes SET properties = ?, updatedAt = ? WHERE id = ?").run(s,c,i.id),i.id;let g=this.db.prepare("INSERT INTO nodes (name, type, properties, owner_agent_id, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)").run(e,r,s,o??null,c,c);return Number(g.lastInsertRowid)}async deleteNode(e){this.db.prepare("DELETE FROM nodes WHERE id = ?").run(e);}async upsertEdge(e,r,n,o){let c=this.db.prepare("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)").run(e,r,n,JSON.stringify(o??{}),Date.now());return Number(c.lastInsertRowid)}async queryNodes(e={}){let r="SELECT id, name, type, properties, owner_agent_id, createdAt, updatedAt FROM nodes",n=[],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(", ")})`),n.push(...s);}e.name&&(o.push("name LIKE ?"),n.push(`%${e.name}%`)),e.type&&(o.push("type = ?"),n.push(e.type)),Rt(o,n,e.agentId,e.scope??"agent_only"),o.length>0&&(r+=` WHERE ${o.join(" AND ")}`),r+=" ORDER BY id",e.limit&&(r+=" LIMIT ?",n.push(e.limit)),ye.debug("queryNodes",{sql:r,params:n,filter:e});let c=this.db.prepare(r).all(...n);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,ownerAgentId:s.owner_agent_id}))}async queryEdges(e={}){let r="SELECT e.id, e.source, e.target, e.relation, e.properties, e.createdAt FROM edges e",n=[],o=[];if(e.ids&&e.ids.length>0&&(o.push(`e.id IN (${e.ids.map(()=>"?").join(", ")})`),n.push(...e.ids)),e.source!==void 0&&(o.push("e.source = ?"),n.push(e.source)),e.target!==void 0&&(o.push("e.target = ?"),n.push(e.target)),e.sourceOrTarget&&e.sourceOrTarget.length>0){let l=e.sourceOrTarget.map(p=>typeof p=="string"?parseInt(p,10):p).filter(p=>!Number.isNaN(p));o.push(`(e.source IN (${l.map(()=>"?").join(", ")}) OR e.target IN (${l.map(()=>"?").join(", ")}))`),n.push(...l,...l);}e.relation&&(o.push("e.relation = ?"),n.push(e.relation)),o.length>0&&(r+=` WHERE ${o.join(" AND ")}`),r+=" ORDER BY e.id",e.limit&&(r+=" LIMIT ?",n.push(e.limit)),ye.debug("queryEdges",{sql:r,params:n,filter:e});let c=this.db.prepare(r).all(...n);ye.debug("queryEdges result",{count:c.length});let s=[...new Set(c.map(l=>l.target))],i=s.length>0?await this.queryNodes({ids:s,limit:s.length}):[],g=new Map(i.map(l=>[l.id,l]));return c.map(l=>{let p={id:l.id,source:l.source,target:l.target,relation:l.relation,properties:l.properties?JSON.parse(l.properties):void 0,createdAt:l.createdAt},y=g.get(l.target);return y&&(p.targetNode=y),p})}async queryNeighbors(e,r=1,n){let o=n?.agentId,c=n?.scope??"agent_only",s=new Set,i=[{id:e,level:0}],g=[],l=n?.maxEdgesPerNode??50;for(;i.length>0;){let p=i.shift();if(!p)break;if(s.has(p.id)||p.level>r)continue;s.add(p.id);let h=(await this.queryNodes({ids:[p.id],limit:1,agentId:o,scope:c}))[0];if(!h)continue;let M=await this.queryEdges({sourceOrTarget:[p.id],limit:l}),D=o?await wt(this,M,o,c):M;if(g.push({...h,edges:D}),p.level<r)for(let I of D){let u=I.source===p.id?I.target:I.source;s.has(u)||i.push({id:u,level:p.level+1});}}return g}};async function wt(t,e,r,n){if(e.length===0)return e;let o=new Set;for(let i of e)o.add(i.source),o.add(i.target);let c=await t.queryNodes({ids:Array.from(o),agentId:r,scope:n,limit:o.size}),s=new Set(c.map(i=>i.id));return e.filter(i=>s.has(i.source)&&s.has(i.target))}function Rt(t,e,r,n){if(r)switch(n){case "agent_only":t.push("owner_agent_id = ?"),e.push(r);break;case "shared_only":t.push("owner_agent_id IS NULL");break;case "both":t.push("(owner_agent_id = ? OR owner_agent_id IS NULL)"),e.push(r);break}}var S=class extends Error{constructor(r,n,o){super(r);chunkM2YU5LAI_cjs.a(this,"code",n);chunkM2YU5LAI_cjs.a(this,"details",o);this.name="ServiceError";}},ie=class extends S{constructor(e,r=[]){super(`Memory not found: ${e}`,"NOT_FOUND",{memoryId:e,candidates:r});}};var he=class extends S{constructor(){super("ctx.agentId is required for memory service (ADR 0055 per-agent isolation)","AGENT_ID_REQUIRED");}},ce=class extends S{constructor(e,r){super(`Trust denied for operation "${e}": ${r}`,"TRUST_DENIED",{operation:e,reason:r});}},de=class extends S{constructor(e,r){super(`Memory ${e} has ${r} references (force=false)`,"HAS_REFERENCES",{memoryId:e,referenceCount:r});}},me=class extends S{constructor(e){super(`dryRun mode: ${e} memories matched but not deleted`,"DRY_RUN_NO_DELETE",{matchedCount:e});}},le=class extends S{constructor(e,r){super(`Matched ${e} memories exceeds maxDelete=${r}`,"MAX_DELETE_EXCEEDED",{matched:e,maxDelete:r});}};function $(t){if(typeof t.agentId!="string"||t.agentId.trim().length===0)throw new he}function z(t,e){if(t.remote!==false)throw new ce(e,"requires trusted local caller (CLI / agent tool / MCP with remote=false)")}function be(t,e,r){if(e!=="agent_only"&&t.remote!==false)throw new ce(r,`scope="${e}" requires trusted local caller (cross-agent access denied)`)}function ee(t){if(!t.dbPath||t.dbPath.trim().length===0)throw new S("service ctx.dbPath is required (MemoryKnowledgeConfigWithModels.database.path)","INTERNAL")}var te=utils.Log.create({service:"memory.service.recall"});async function je(t,e){let r=Date.now();if($(t),ee(t),!e.query||e.query.trim().length===0)throw new S("recall requires non-empty `query`","CONTENT_REQUIRED");let n=e.includeShared?"both":"agent_only";e.includeGraph&&be(t,n,"recall"),te.debug("recall invoked",{agentId:t.agentId,query:e.query,category:e.category,maxResults:e.maxResults,includeGraph:e.includeGraph,scope:n});let o=e.maxResults??10,c=e.minScore??0,s=[],i=new chunkEK34SXJ7_cjs.e(t.dbPath);try{await i.initialize();let g=chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().embedding===!0,l=await It(i,t.agentId,e.query,{category:e.category,minImportance:e.minImportance,fromTime:e.fromTime,toTime:e.toTime,limit:o,minScore:c,hasEmbedding:g}),p;if(e.includeGraph&&l.length>0)try{let h=new Z(i.getDb()),M=e.depth??1,D=l.flatMap(v=>(v.nodes??[]).map(b=>b.id)).slice(0,5),I=new Set,u=new Map;for(let v of D){let b=await h.queryNeighbors(v,M,{agentId:t.agentId,scope:n,maxEdgesPerNode:10});for(let _ of b)I.add(_.id),u.set(_.id,_.edges??[]);}let E=I.size>0?i.query(`SELECT id, name, type FROM nodes WHERE id IN (${Array.from(I).map(()=>"?").join(",")})`,Array.from(I)):[],C=Array.from(u.values()).flat();p={nodes:E.map(v=>({id:v.id,name:v.name,type:v.type,createdAt:"",updatedAt:""})),edges:C};}catch(h){let M=h instanceof Error?h.message:String(h);te.warn("recall: KG neighbor query failed",{error:M}),s.push(`kg_neighbor_query_failed: ${M}`),p={nodes:[],edges:[]};}let y=Date.now()-r;return {hits:l,total:l.length,truncated:l.length>=o,durationMs:y,graph:p,...s.length>0?{warnings:s}:{}}}catch(g){throw g instanceof S?g:new S(`recall failed: ${g instanceof Error?g.message:String(g)}`,"INTERNAL",{cause:g instanceof Error?g.message:String(g)})}finally{i.close();}}async function It(t,e,r,n){let o=["mf.agent_id = ?"],c=[e];n.category&&(o.push("mf.category = ?"),c.push(n.category)),n.minImportance!==void 0&&(o.push("mf.importance >= ?"),c.push(n.minImportance)),n.fromTime&&(o.push("mf.created_at >= ?"),c.push(n.fromTime)),n.toTime&&(o.push("mf.created_at <= ?"),c.push(n.toTime));let s=o.join(" AND "),i=null;if(n.hasEmbedding)try{i=await chunkJ5XF2W4Z_cjs.a.embedText(r);}catch(f){te.warn("recall: query embedding failed, falling back to FTS-only",{error:f instanceof Error?f.message:String(f)}),i=null;}let g=Math.max(n.limit*100,1e3),[l,p]=await Promise.all([i?Mt(t,i,s,c,g):Promise.resolve([]),Dt(t,r,s,c,n.limit)]),y=i?.7:0,h=i?.3:1,M=y+h,D=y/M,I=h/M,u=new Map;for(let f of l)u.set(f.id,f.score*D);for(let f of p)u.set(f.id,(u.get(f.id)??0)+f.score*I);let E=Array.from(u.entries()).sort((f,O)=>O[1]-f[1]).map(([f])=>f).slice(0,n.limit);if(E.length===0)return [];let C=E.map(()=>"?").join(","),v=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 (${C})`,E),b=_t(t,v.map(f=>f.id)),_=Date.now();return v.map(f=>{let O=u.get(f.id)??0,L=(_-new Date(f.createdAt).getTime())/864e5,A=Math.exp(-0.05*L),G=(f.importance-1)/9,B=.4*O+.3*A+.3*G,J;if(f.tags)try{let d=JSON.parse(f.tags);Array.isArray(d)&&(J=d.filter(m=>typeof m=="string"));}catch{}return {memoryId:f.id,category:f.category,importance:f.importance,agentId:f.agentId,content:f.content,snippet:f.snippet,score:B,createdAt:f.createdAt,updatedAt:f.updatedAt,source:f.source,filePath:f.filePath??void 0,tags:J,sessionId:f.sessionId??void 0,msgId:f.msgId??void 0,parentMsgId:f.parentMsgId??void 0,nodes:b.get(f.id)??[]}}).filter(f=>f.score>=n.minScore).sort((f,O)=>O.score-f.score)}function _t(t,e){let r=new Map;if(e.length===0)return r;try{let n=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 (${n})
21
+ ORDER BY fn.fact_id, fn.score DESC, n.id`,e);for(let c of o){let s=r.get(c.fact_id);s||(s=[],r.set(c.fact_id,s)),s.push({id:c.id,name:c.name,type:c.type});}}catch(n){te.warn("recall: loadFactNodes failed (KG associations unavailable for this recall)",{error:n instanceof Error?n.message:String(n)});}return r}function Mt(t,e,r,n,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 ${r}
25
+ LIMIT ?`,[...n,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 S)throw c;return te.warn("vector search failed, falling back to FTS-only",{error:c instanceof Error?c.message:String(c)}),[]}}function Dt(t,e,r,n,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 ${r} AND memory_facts_fts MATCH ?
29
+ ORDER BY score DESC
30
+ LIMIT ?`,[...n,Ct(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 S)throw c;return te.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 r=0,n=0,o=0;for(let s=0;s<t.length;s++){let i=t[s]??0,g=e[s]??0;r+=i*g,n+=i*i,o+=g*g;}let c=Math.sqrt(n)*Math.sqrt(o);return c===0?0:Math.max(0,r/c)}function Ct(t){return t.trim().split(/\s+/).filter(e=>e.length>0).map(e=>`"${e.replace(/"/g,'""')}"`).join(" ")}var Be=zod.z.object({query:zod.z.string().min(1).max(500),category:zod.z.string().optional(),minImportance:zod.z.number().min(1).max(10).optional(),fromTime:zod.z.string().datetime().optional(),toTime:zod.z.string().datetime().optional(),maxResults:zod.z.number().int().min(1).max(100).optional().default(10),minScore:zod.z.number().min(0).max(1).optional(),includeGraph:zod.z.boolean().optional().default(false),depth:zod.z.number().int().min(1).max(5).optional().default(1),includeShared:zod.z.boolean().optional().default(false)});zod.z.object({hits:zod.z.array(zod.z.unknown()),total:zod.z.number(),truncated:zod.z.boolean(),durationMs:zod.z.number(),graph:zod.z.object({nodes:zod.z.array(zod.z.unknown()),edges:zod.z.array(zod.z.unknown())}).optional()});var ze=zod.z.object({content:zod.z.string().min(1).max(1e4),category:zod.z.string().min(1),importance:zod.z.number().int().min(1).max(10).optional().default(5),tags:zod.z.array(zod.z.string()).optional(),sessionId:zod.z.string().optional(),msgId:zod.z.string().optional(),parentMsgId:zod.z.string().optional(),skipDedup:zod.z.boolean().optional().default(false),extractGraph:zod.z.boolean().optional().default(true)});zod.z.object({fact:zod.z.object({id:zod.z.string(),agentId:zod.z.string(),content:zod.z.string(),category:zod.z.string(),importance:zod.z.number(),createdAt:zod.z.string(),updatedAt:zod.z.string()}),filePath:zod.z.string(),deduplicated:zod.z.boolean(),nodeIds:zod.z.array(zod.z.number()).optional()});var Qe=zod.z.object({factId:zod.z.string().min(1).describe("Target fact id (must belong to ctx.agentId)"),content:zod.z.string().min(1).max(1e4).optional().describe("New content (triggers embedding rewrite + FTS reindex)"),category:zod.z.string().min(1).optional().describe("New category (one of MemoryCategory enum)"),importance:zod.z.number().int().min(1).max(10).optional().describe("New importance 1-10"),tags:zod.z.array(zod.z.string()).optional().describe("New tags array (empty array clears tags)")}).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"});zod.z.object({fact:zod.z.object({id:zod.z.string(),agentId:zod.z.string(),content:zod.z.string(),category:zod.z.string(),importance:zod.z.number(),createdAt:zod.z.string(),updatedAt:zod.z.string()}),contentChanged:zod.z.boolean(),fieldsUpdated:zod.z.array(zod.z.string()),durationMs:zod.z.number()});var Ke=zod.z.object({factId:zod.z.string().optional(),category:zod.z.string().optional(),fromTime:zod.z.string().datetime().optional(),toTime:zod.z.string().datetime().optional(),maxDelete:zod.z.number().int().min(1).max(1e4).optional().default(1e3),dryRun:zod.z.boolean().optional().default(false),force:zod.z.boolean().optional().default(false)}).refine(t=>t.factId!==void 0&&t.factId.length>0||t.category!==void 0&&t.category.length>0||t.fromTime!==void 0||t.toTime!==void 0,{message:"one of `factId`, `category`, `fromTime`, or `toTime` is required"});zod.z.object({deletedCount:zod.z.number(),deletedIds:zod.z.array(zod.z.string()),dryRun:zod.z.boolean(),truncatedCount:zod.z.number()});var Je=zod.z.object({sessionId:zod.z.string().min(1),lastN:zod.z.number().int().min(1).max(500).optional().default(50),fromMessageId:zod.z.string().optional(),writeToDisk:zod.z.boolean().optional().default(true)});zod.z.object({extractedCount:zod.z.number(),factIds:zod.z.array(zod.z.string()),entities:zod.z.array(zod.z.object({id:zod.z.number(),name:zod.z.string(),type:zod.z.string()})),relations:zod.z.array(zod.z.object({source:zod.z.string(),target:zod.z.string(),relation:zod.z.string()})),messageRange:zod.z.object({fromMessageId:zod.z.string(),toMessageId:zod.z.string()}),durationMs:zod.z.number()});var Ve=zod.z.object({windowDays:zod.z.number().int().min(1).max(365).optional().default(30),dryRun:zod.z.boolean().optional().default(false)});zod.z.object({totalFacts:zod.z.number(),dedupedCount:zod.z.number(),compressedCount:zod.z.number(),archivedCount:zod.z.number(),skippedCount:zod.z.number(),durationMs:zod.z.number()});var Ye=zod.z.object({query:zod.z.string().min(1),type:zod.z.string().optional(),depth:zod.z.number().int().min(1).max(5).optional().default(2),maxNodes:zod.z.number().int().min(1).max(500).optional().default(100),scope:zod.z.enum(["agent_only","shared_only","both"]).optional().default("agent_only"),relation:zod.z.string().optional()});zod.z.object({root:zod.z.unknown().nullable(),nodes:zod.z.array(zod.z.unknown()),edges:zod.z.array(zod.z.unknown()),truncated:zod.z.boolean(),totalNodes:zod.z.number(),totalEdges:zod.z.number(),scope:zod.z.enum(["agent_only","shared_only","both"]),durationMs:zod.z.number()});var Xe=zod.z.object({}).optional();zod.z.object({dbPath:zod.z.string(),workspaceDir:zod.z.string(),factsCount:zod.z.number(),nodesCount:zod.z.number(),edgesCount:zod.z.number(),factsByCategory:zod.z.record(zod.z.string(),zod.z.number()),ftsAvailable:zod.z.boolean(),vectorEnabled:zod.z.boolean(),kgScopeEnabled:zod.z.boolean(),healthy:zod.z.boolean(),meta:zod.z.record(zod.z.string(),zod.z.string())});var Ze=zod.z.object({}).optional();zod.z.object({healthy:zod.z.boolean(),checks:zod.z.array(zod.z.object({name:zod.z.string(),passed:zod.z.boolean(),message:zod.z.string(),details:zod.z.record(zod.z.string(),zod.z.unknown()).optional()}))});var et=zod.z.object({workspaceDir:zod.z.string().optional(),dbPath:zod.z.string().optional(),archiveDays:zod.z.number().int().min(1).max(3650).optional().default(30),force:zod.z.boolean().optional().default(false)});zod.z.object({initialized:zod.z.boolean(),dbPath:zod.z.string(),workspaceDir:zod.z.string(),tablesCreated:zod.z.number(),migrationsApplied:zod.z.number(),durationMs:zod.z.number()});var tt=zod.z.object({windowDays:zod.z.number().int().min(1).max(3650).optional(),dryRun:zod.z.boolean().optional().default(false)});zod.z.object({generatedCount:zod.z.number(),skippedCount:zod.z.number(),failedGenerateCount:zod.z.number(),archivedCount:zod.z.number(),archiveThreshold:zod.z.string(),archivedRecords:zod.z.array(zod.z.object({source:zod.z.string(),target:zod.z.string(),firstCreatedAt:zod.z.string(),firstFactId:zod.z.string()})),windowDays:zod.z.number(),dryRun:zod.z.boolean(),durationMs:zod.z.number()});var ge=utils.Log.create({service:"memory.fact-file-sync"}),Tt=".easbot/memory/active";function ue(t,e){let r=e.replace(/\\/g,"/").replace(/\/+$/,""),n=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"),g=String(c.getDate()).padStart(2,"0"),l=`${s}-${i}-${g}`;return `${r}/${Tt}/${n}/${l}.md`}function nt(t){let e=t.tags&&t.tags.length>0?t.tags:[],r=t.importance??5,n=t.source??"session_self_write",o=t.createdAt?utils.formatLocalISO(new Date(t.createdAt)):utils.formatLocalISO(new Date),c=t.updatedAt?utils.formatLocalISO(new Date(t.updatedAt)):o,s=["---",`id: ${t.id}`,`agent_id: ${t.agentId}`,`category: ${t.category}`,`importance: ${r}`,`created_at: ${o}`,`updated_at: ${c}`,`source: ${n}`,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 r=t.replace(/\\/g,"/"),n=e.replace(/\\/g,"/").replace(/\/+$/,"");return r.startsWith(`${n}/`)?r.slice(n.length+1):r}async function Pt(t,e){let r=ue(t,e),n=ne(r,e);try{let o=nt(t);await Q__default.default.mkdir(fe__default.default.dirname(r),{recursive:!0});let c="";try{c=await Q__default.default.readFile(r,"utf-8");}catch(i){if(i.code!=="ENOENT")throw i}let s=c.length>0&&!c.endsWith(`
33
+ `)?`
34
+ `:"";return await Q__default.default.writeFile(r,`${c}${s}${o}
35
+ `,"utf-8"),ge.debug("Fact file synced (append)",{id:t.id,relPath:n}),{ok:!0,absPath:r,relPath:n}}catch(o){let c=o instanceof Error?o.message:String(o);return ge.warn("Failed to write fact file (best-effort, non-blocking)",{id:t.id,absPath:r,error:c}),{ok:false,absPath:r,relPath:n,error:c}}}async function kt(t,e){let r;t.filePath?r=`${e.replace(/\\/g,"/").replace(/\/+$/,"")}/${t.filePath.replace(/^\/+/,"")}`:r=ue({id:t.id,category:t.category,createdAt:t.createdAt,updatedAt:t.createdAt},e);let n=ne(r,e);try{return await Q__default.default.unlink(r),ge.debug("Fact file deleted",{id:t.id,relPath:n}),{ok:!0,absPath:r,relPath:n}}catch(o){if(o.code==="ENOENT")return ge.debug("Fact file not found (already deleted)",{id:t.id,relPath:n}),{ok:true,absPath:r,relPath:n};let s=o instanceof Error?o.message:String(o);return ge.warn("Failed to delete fact file (best-effort, non-blocking)",{id:t.id,absPath:r,error:s}),{ok:false,absPath:r,relPath:n,error:s}}}var re={resolvePath:ue,renderMarkdown:nt,toRelPath:ne,write:Pt,delete:kt};var oe=utils.Log.create({service:"memory.service.remember"});async function rt(t,e){if($(t),ee(t),!e.content||e.content.trim().length===0)throw new S("remember requires non-empty `content`","CONTENT_REQUIRED");if(!e.category)throw new S("remember requires `category`","CATEGORY_REQUIRED");oe.debug("remember invoked",{agentId:t.agentId,category:e.category,importance:e.importance??5,contentLength:e.content.length,skipDedup:e.skipDedup,extractGraph:e.extractGraph??true});let r=new chunkEK34SXJ7_cjs.e(t.dbPath);try{await r.initialize();let n=new Date().toISOString(),o=qt(),c=e.importance??5,s={entities:[],relations:[]},g=e.extractGraph!==!1&&chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().graphLlm?chunkJ5XF2W4Z_cjs.a.getGraphLlm():void 0;if(g)try{s=await Ht(g,e.content);}catch(b){oe.warn("LLM KG extraction failed (continuing without KG)",{agentId:t.agentId,error:b instanceof Error?b.message:String(b)});}let l=chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().embedding===!0,p=l?await $t(r.getDb(),e.content):null,y=p?p.length:null,h=s.entities,M=s.relations,D=[],I=0,u=[];if(r.transaction(()=>{let b=new Map;for(let R of h){let f=r.query("SELECT id FROM nodes WHERE name = ? AND type = ? AND owner_agent_id = ? LIMIT 1",[R.name,R.type,t.agentId])[0];if(f){b.set(R.name,f.id);continue}let O=null;try{let G=Se(R.name),B=r.query("SELECT embedding FROM embedding_cache WHERE content_hash = ?",[G])[0];B?.embedding&&(O=B.embedding);}catch{}let A=r.run("INSERT INTO nodes (name, type, properties, owner_agent_id, embedding, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?, ?)",[R.name,R.type,JSON.stringify({source:"llm_extracted",...R.properties??{}}),t.agentId,O,n,n]).lastID;A>0&&(b.set(R.name,A),O===null&&u.push({name:R.name,nodeId:A}));}for(let R of M){let f=b.get(R.source),O=b.get(R.target);!f||!O||f===O||r.run("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)",[f,O,R.relation,JSON.stringify({}),n]);}r.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.sessionId??null,e.msgId??null,e.parentMsgId??null,e.content,e.category,c,"session_self_write",e.tags?JSON.stringify(e.tags):null,null,n,n]);let _=Array.from(b.values());if(_.length>0)try{for(let R of _)r.run("INSERT OR IGNORE INTO fact_nodes (fact_id, node_id, source, score, createdAt) VALUES (?, ?, ?, ?, ?)",[o,R,"kg_extract",1,n]);}catch(R){oe.warn("fact_nodes write failed (non-fatal)",{factId:o,nodeCount:_.length,error:R instanceof Error?R.message:String(R)});}if(p&&y){let R=Re(p);r.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[o,R]),I=1,r.query("SELECT value FROM meta WHERE key = ?",["vectorDims"])[0]||r.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["vectorDims",String(y)]);}r.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[o]),r.run("INSERT INTO memory_facts_fts (fact_id, agent_id, content, tags) VALUES (?, ?, ?, ?)",[o,t.agentId,e.content,e.tags?e.tags.join(" "):""]),D.push(...Array.from(b.values()));}),u.length>0&&chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().embedding)try{let b=u.map(f=>f.name),_=await chunkJ5XF2W4Z_cjs.a.embedMany(b),R=new Date().toISOString();for(let f=0;f<u.length;f++){let O=u[f],L=_[f];if(!O||!L||L.length===0)continue;let A=Re(new Float32Array(L));r.run("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)",[Se(O.name),A]),r.run("UPDATE nodes SET embedding = ?, updatedAt = ? WHERE id = ?",[A,R,O.nodeId]);}}catch(b){oe.warn("memory entity name batch embed failed (non-fatal)",{pendingCount:u.length,error:b instanceof Error?b.message:String(b)});}oe.info("Memory stored",{id:o,category:e.category,agentId:t.agentId,nodeCount:D.length,vectorsWritten:I,vectorDims:y??0,embeddingMode:l?"enabled":"fts_only",entitiesExtracted:h.length,relationsExtracted:M.length});let E={id:o,agentId:t.agentId,sessionId:e.sessionId,msgId:e.msgId,parentMsgId:e.parentMsgId,content:e.content,category:e.category,importance:c,source:"session_self_write",tags:e.tags,nodeIds:D.length>0?D:void 0,filePath:void 0,createdAt:n,updatedAt:n},C="",v=await re.write(E,t.workspaceDir);if(v.ok){C=v.relPath,E.filePath=v.relPath;try{r.run("UPDATE memory_facts SET file_path = ? WHERE id = ?",[v.relPath,o]);}catch(b){oe.warn("Failed to update file_path column after sync",{id:o,error:b instanceof Error?b.message:String(b)});}}return {fact:E,filePath:C,deduplicated:!1,nodeIds:D,vectorsWritten:I,vectorDims:y??0,entitiesExtracted:h.length,relationsExtracted:M.length}}catch(n){throw n instanceof S?n:new S(`remember failed: ${n instanceof Error?n.message:String(n)}`,"INTERNAL",{cause:n instanceof Error?n.message:String(n)})}finally{r.close();}}function qt(){let t=Date.now(),e=crypto.randomBytes(3).toString("hex");return `mem_${t}_${e}`}function Re(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}function Se(t){return crypto.createHash("sha256").update(t).digest("hex")}async function $t(t,e){let r=Se(e),n=t.prepare("SELECT embedding FROM embedding_cache WHERE content_hash = ?").get(r);if(n?.embedding)return new Float32Array(n.embedding.buffer,n.embedding.byteOffset,n.embedding.byteLength/4);let o=await chunkJ5XF2W4Z_cjs.a.embedText(e);if(!o||o.length===0)return null;let c=Re(o);return t.prepare("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)").run(r,c),o}async function Ht(t,e){let r=await llm.GraphProvider.generateGraph({chunks:[e],model:t,includeRules:false});return {entities:r.entities,relations:r.relations}}var Ie=utils.Log.create({service:"memory.service.update"});function Gt(t){if(t.content===void 0&&t.category===void 0&&t.importance===void 0&&t.tags===void 0)throw new S("update requires at least one of: `content`, `category`, `importance`, `tags`","CONTENT_REQUIRED");if(t.content!==void 0&&t.content.trim().length===0)throw new S("update: `content` cannot be empty (use `forget` to delete)","CONTENT_REQUIRED");if(t.importance!==void 0&&(t.importance<1||t.importance>10))throw new S(`update: \`importance\` must be 1-10, got ${t.importance}`,"IMPORTANCE_REQUIRED")}async function ot(t,e){let r=Date.now();$(t),ee(t),Gt(e),Ie.debug("update invoked",{agentId:t.agentId,factId:e.factId,fields:{content:e.content!==void 0,category:e.category!==void 0,importance:e.importance!==void 0,tags:e.tags!==void 0}});let n=e.content!==void 0,o=n&&chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().embedding===true,c=null;if(o&&e.content)try{c=await chunkJ5XF2W4Z_cjs.a.embedText(e.content);}catch(i){Ie.warn("update: embedding rewrite failed (continuing without vector update)",{factId:e.factId,error:i instanceof Error?i.message:String(i)});}let s=new chunkEK34SXJ7_cjs.e(t.dbPath);try{await s.initialize();let i=new Date().toISOString(),g=[];s.transaction(()=>{let h=s.query("SELECT id, content, category, importance, tags FROM memory_facts WHERE id = ? AND agent_id = ?",[e.factId,t.agentId])[0];if(!h)throw new ie(e.factId);let M=["updated_at = ?"],D=[i];if(e.content!==void 0&&e.content!==h.content&&(M.push("content = ?"),D.push(e.content),g.push("content")),e.category!==void 0&&e.category!==h.category&&(M.push("category = ?"),D.push(e.category),g.push("category")),e.importance!==void 0&&e.importance!==h.importance&&(M.push("importance = ?"),D.push(e.importance),g.push("importance")),e.tags!==void 0){let I=e.tags.length>0?JSON.stringify(e.tags):null;I!==h.tags&&(M.push("tags = ?"),D.push(I),g.push("tags"));}if(g.length>0&&s.run(`UPDATE memory_facts SET ${M.join(", ")} WHERE id = ? AND agent_id = ?`,[...D,e.factId,t.agentId]),g.includes("content")||g.includes("tags")){let I=e.content??h.content,u=g.includes("tags")?e.tags&&e.tags.length>0?JSON.stringify(e.tags):null:h.tags,E=u?(()=>{try{let C=JSON.parse(u);return Array.isArray(C)?C.filter(v=>typeof v=="string"):[]}catch{return []}})():[];s.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[e.factId]),s.run("INSERT INTO memory_facts_fts (fact_id, agent_id, content, tags) VALUES (?, ?, ?, ?)",[e.factId,t.agentId,I,E.join(" ")]);}if(g.includes("content")&&c){let I=jt(c);s.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[e.factId,I]);try{let u=Bt(e.content);s.run("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)",[u,I]);}catch{}}});let l=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.factId,t.agentId])[0];if(!l)throw new S(`update: failed to read back updated fact ${e.factId}`,"INTERNAL");let p;if(l.tags)try{let h=JSON.parse(l.tags);Array.isArray(h)&&(p=h.filter(M=>typeof M=="string"));}catch{}let y={id:l.id,agentId:l.agent_id,sessionId:l.session_id??void 0,msgId:l.msg_id??void 0,parentMsgId:l.parent_msg_id??void 0,content:l.content,category:l.category,importance:l.importance,source:l.source,tags:p,filePath:l.file_path??void 0,createdAt:l.created_at,updatedAt:l.updated_at};return Ie.info("Memory updated",{agentId:t.agentId,factId:e.factId,fieldsUpdated:g,contentChanged:n,durationMs:Date.now()-r}),{fact:y,contentChanged:n,fieldsUpdated:g,durationMs:Date.now()-r}}catch(i){throw i instanceof S?i:new S(`update failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}function jt(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}function Bt(t){return crypto.createHash("sha256").update(t).digest("hex")}var _e=utils.Log.create({service:"memory.service.forget"}),Qt=1e3;function Kt(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 S("CONTENT_REQUIRED: forget requires one of: `factId`, `category`, or `fromTime`/`toTime`","CONTENT_REQUIRED");if(e.length>1)throw new S(`mutually exclusive: forget requires exactly one of factId/category/timeRange, got [${e.join(", ")}]`,"CONTENT_REQUIRED");return e[0]}function Jt(t,e,r){let n=[r];switch(t){case "factId":return {where:"agent_id = ? AND id = ?",args:[...n,e.factId]};case "category":return {where:"agent_id = ? AND category = ?",args:[...n,e.category]};case "timeRange":{let o=["agent_id = ?"];return e.fromTime&&(o.push("created_at >= ?"),n.push(e.fromTime)),e.toTime&&(o.push("created_at <= ?"),n.push(e.toTime)),{where:o.join(" AND "),args:n}}}}function Vt(t,e,r,n){return t.query(`SELECT id FROM memory_facts WHERE ${e} LIMIT ?`,[...r,n+1]).map(c=>c.id)}function Yt(t,e,r,n){if(r.length===0)return 0;let o=r.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})`,[n,e,...r])[0]?.count??0}function Xt(t,e,r){let n,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,r])[0],g=t.query("SELECT node_id FROM fact_nodes WHERE fact_id = ?",[e]).map(l=>l.node_id).filter(l=>typeof l=="number");if(n=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,r]),g.length>0){let l=g.map(()=>"?").join(",");t.run(`DELETE FROM nodes WHERE id IN (${l}) AND NOT EXISTS (
42
+ SELECT 1 FROM fact_nodes fn WHERE fn.node_id = nodes.id
43
+ )`,g);}}),{filePath:n,category:o,createdAt:c}}async function at(t,e){$(t),z(t,"forget");let r=Kt(e),n=e.maxDelete??Qt,o=e.dryRun??false,c=e.force??false;_e.debug("forget invoked",{agentId:t.agentId,mode:r,maxDelete:n,dryRun:o,force:c});let s=new chunkEK34SXJ7_cjs.e(t.dbPath);try{await s.initialize();let{where:i,args:g}=Jt(r,e,t.agentId),l=Vt(s,i,g,n),p=l.length>n;if(p&&!c)throw new le(l.length,n);let y=p?l.slice(0,n):l;if(o)throw new me(y.length);let h=[],M=[];for(let D of y){if(!c){let v=s.query("SELECT node_id FROM fact_nodes WHERE fact_id = ? AND node_id IS NOT NULL",[D]).map(_=>_.node_id).filter(_=>typeof _=="number"),b=Yt(s,D,v,t.agentId);if(b>0)throw new de(D,b)}let{filePath:I,category:u,createdAt:E}=Xt(s,D,t.agentId);I&&u&&M.push({id:D,filePath:I,category:u,createdAt:E}),h.push(D);}_e.info("forget complete",{agentId:t.agentId,mode:r,deletedCount:h.length,force:c,dryRun:o});for(let{id:D,filePath:I,category:u,createdAt:E}of M)await re.delete({id:D,filePath:I,category:u,createdAt:E},t.workspaceDir).catch(C=>{_e.warn("Fact file delete failed (best-effort)",{id:D,filePath:I,error:C instanceof Error?C.message:String(C)});});return {deletedCount:h.length,deletedIds:h,dryRun:o,truncatedCount:p?l.length-n:0}}catch(i){throw i instanceof S?i:new S(`forget failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var st=utils.Log.create({service:"memory.service.extract"}),en=50,Me=500;async function it(t,e){if($(t),!e.sessionId||e.sessionId.trim().length===0)throw new S("extract requires non-empty `sessionId`","SESSION_ID_REQUIRED");let r=e.lastN??en;if(r>Me)throw new S(`extract lastN=${r} exceeds max=${Me}`,"CONTENT_REQUIRED",{lastN:r,maxLastN:Me});let n=e.sessionId,o=e.fromMessageId;st.debug("extract invoked",{agentId:t.agentId,sessionId:n,lastN:r,fromMessageId:o,writeToDisk:e.writeToDisk??true});let c=Date.now(),s=new chunkEK34SXJ7_cjs.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,n,r]),g=o?i.filter(u=>u.id>o):i,l=g.map(u=>u.id),p=l.length>0?s.query(`SELECT node_id FROM fact_nodes WHERE fact_id IN (${l.map(()=>"?").join(",")})`,l):[],y=new Set;for(let u of p)typeof u.node_id=="number"&&u.node_id>0&&y.add(u.node_id);let h=Array.from(y),M=[],D=[];if(h.length>0){let u=h.map(()=>"?").join(","),E=s.query(`SELECT id, name, type FROM nodes WHERE id IN (${u})`,h),C=new Map;for(let _ of E)C.set(_.id,_.name);M=E.map(_=>({id:_.id,name:_.name,type:_.type}));let v=s.query(`SELECT source, target, relation FROM edges WHERE source IN (${u}) OR target IN (${u})`,[...h,...h]),b=new Set;D=[];for(let _ of v){let R=C.get(_.source),f=C.get(_.target);if(!R||!f)continue;let O=`${R}\0${_.relation}\0${f}`;b.has(O)||(b.add(O),D.push({source:R,target:f,relation:_.relation}));}}let I=Date.now()-c;return st.info("extract complete",{agentId:t.agentId,sessionId:n,factCount:g.length,nodeCount:M.length,relationCount:D.length,durationMs:I}),{extractedCount:g.length,factIds:g.map(u=>u.id),entities:M,relations:D,messageRange:{fromMessageId:g[0]?.id??"",toMessageId:g[g.length-1]?.id??""},durationMs:I}}catch(i){throw i instanceof S?i:new S(`extract failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var Ce=utils.Log.create({service:"memory.service.consolidate"}),nn=30;async function rn(t){let{createHash:e}=await import('crypto');return e("sha256").update(t).digest("hex")}async function ct(t,e={}){let r=Date.now();$(t),z(t,"consolidate");let n=e.windowDays??nn,o=e.dryRun??false;Ce.debug("consolidate invoked",{agentId:t.agentId,windowDays:n,dryRun:o});let c=new chunkEK34SXJ7_cjs.e(t.dbPath);try{await c.initialize();let s=c.query("SELECT id, content, category, importance, created_at FROM memory_facts WHERE agent_id = ? ORDER BY created_at DESC",[t.agentId]),i=new Map;for(let u of s){let E=await rn(u.content);i.has(E)||i.set(E,[]),i.get(E)?.push(u);}let g=0,l=[];for(let[,u]of i){if(u.length<=1)continue;let E=[...u].sort((b,_)=>b.importance!==_.importance?_.importance-b.importance:_.created_at.localeCompare(b.created_at)),C=E[0];if(!C)continue;let v=E.slice(1).map(b=>b.id);g+=v.length,l.push({keep:C,removeIds:v});}let p=new Date(Date.now()-n*24*60*60*1e3).toISOString(),y=c.query(`SELECT id, content, category, importance, created_at FROM memory_facts
48
+ WHERE agent_id = ? AND created_at < ?
49
+ ORDER BY created_at ASC`,[t.agentId,p]),h=0,M=0;if(o)h=0,M=g;else {let u=fe__default.default.join(t.workspaceDir,"archive");await Q__default.default.mkdir(u,{recursive:!0});for(let{removeIds:E}of l){if(E.length===0)continue;let C=E.map(()=>"?").join(",");c.transaction(()=>{for(let v of E)c.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[v,t.agentId]);}),M+=E.length;}for(let E of y){let C=E.created_at.slice(0,7),v=fe__default.default.join(u,C,E.category);await Q__default.default.mkdir(v,{recursive:!0});let b=fe__default.default.join(v,`${E.id}.md`);try{await Q__default.default.writeFile(b,[`# ${E.id}`,"",`category: ${E.category}`,`importance: ${E.importance}`,`createdAt: ${E.created_at}`,"",E.content,""].join(`
50
+ `),"utf-8"),c.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[E.id,t.agentId]),h++;}catch(_){Ce.warn("consolidate: archive write failed",{factId:E.id,error:_ instanceof Error?_.message:String(_)});}}}let D=s.length,I=0;return Ce.info("consolidate complete",{agentId:t.agentId,totalFacts:D,dedupedCount:g,compressedCount:I,archivedCount:h,skippedCount:M,dryRun:o,durationMs:Date.now()-r}),{totalFacts:D,dedupedCount:g,compressedCount:I,archivedCount:h,skippedCount:M,durationMs:Date.now()-r}}catch(s){throw s instanceof S?s:new S(`consolidate failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{c.close();}}var W=utils.Log.create({service:"memory.service.sync"}),sn=30,cn=".easbot/memory/active",dt=".easbot/memory/archive";function dn(t,e){let n=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:n.length>0?n:void 0,filePath:e.file_path??void 0,createdAt:e.created_at,updatedAt:e.updated_at}}async function mn(t,e){let r=0,n=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,
51
+ source, tags, file_path, created_at, updated_at
52
+ FROM memory_facts ${c}
53
+ ORDER BY created_at ASC`,s);for(let g of i){let l=dn(t,g);if(g.file_path?.startsWith(`${dt}/`)){n++;continue}let p=ue(l,e.workspaceDir);try{await Q__default.default.access(p),n++;continue}catch(h){let M=h;if(M.code!=="ENOENT"){W.warn("sync generate: fs.access failed (non-ENOENT)",{factId:l.id,absPath:p,error:M.message}),o++;continue}}let y=await re.write(l,e.workspaceDir);y.ok?r++:(o++,W.warn("sync generate: factFileSync.write failed",{factId:l.id,absPath:p,error:y.error}));}return W.debug("sync stage A complete",{agentId:e.agentId,generatedCount:r,skippedCount:n,failedGenerateCount:o}),{generatedCount:r,skippedCount:n,failedGenerateCount:o}}async function ln(t,e,r,n){let o=r*24*60*60*1e3,c=Date.now(),s=utils.formatLocalISO(new Date(c-o)),i=[],g=fe__default.default.join(e.workspaceDir,cn),l=await gn(g);W.debug("sync stage B: scan active dir",{activeDir:g,fileCount:l.length,windowDays:r,threshold:s,dryRun:n});for(let p of l){let y=await un(p);if(!y){W.warn("sync stage B: skip unparseable file",{absPath:p});continue}let{firstCreatedAt:h,firstFactId:M}=y,D=new Date(h).getTime();if(Number.isNaN(D)){W.warn("sync stage B: skip invalid createdAt",{absPath:p,firstCreatedAt:h});continue}if(c-D<=o)continue;let I=fn(p);if(!I){W.warn("sync stage B: cannot infer category from path",{absPath:p});continue}let u=h.slice(0,7),E=fe__default.default.join(e.workspaceDir,dt,u,I),C=fe__default.default.basename(p),v=fe__default.default.join(E,C);if(n){i.push({source:p,target:v,firstCreatedAt:h,firstFactId:M});continue}try{await Q__default.default.mkdir(E,{recursive:!0});try{await Q__default.default.rename(p,v);}catch(R){let f=R;W.warn("sync stage B: fs.rename failed, falling back to copy+unlink",{absPath:p,targetPath:v,error:f.message}),await Q__default.default.copyFile(p,v),await Q__default.default.unlink(p);}let b=ne(p,e.workspaceDir),_=ne(v,e.workspaceDir);t.run(`UPDATE memory_facts SET file_path = ?
54
+ WHERE agent_id = ? AND file_path = ?`,[_,e.agentId??"",b]),i.push({source:p,target:v,firstCreatedAt:h,firstFactId:M});}catch(b){W.warn("sync stage B: archive failed",{absPath:p,targetPath:v,error:b instanceof Error?b.message:String(b)});}}return W.debug("sync stage B complete",{agentId:e.agentId,archivedCount:i.length,dryRun:n}),{archivedCount:i.length,archiveThreshold:s,archivedRecords:i}}async function gn(t){let e=[];try{await mt(t,e);}catch(r){let n=r;if(n.code==="ENOENT")return e;throw W.warn("sync: listActiveMdFiles failed",{activeDir:t,error:n.message}),new S(`sync: listActiveMdFiles failed: ${n.message}`,"INTERNAL",{cause:n.message})}return e}async function mt(t,e){let r=await Q__default.default.readdir(t,{withFileTypes:true});for(let n of r){let o=fe__default.default.join(t,n.name);n.isDirectory()?await mt(o,e):n.isFile()&&n.name.endsWith(".md")&&e.push(o);}}async function un(t){let e;try{e=await Q__default.default.readFile(t,"utf-8");}catch(s){if(s.code==="ENOENT")return null;throw s}if(!e.startsWith(`---
55
+ `))return null;let r=e.indexOf(`
56
+ ---
57
+ `,4);if(r===-1)return null;let n=e.slice(4,r),o,c;for(let s of n.split(`
58
+ `)){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 fn(t){let e=t.replace(/\\/g,"/").split("/"),r=e.findIndex(c=>c==="active");if(r===-1)return null;let n=e.slice(r+1);return n.length!==2||!n[1].endsWith(".md")?null:n[0]??null}async function lt(t,e={}){let r=Date.now();$(t),z(t,"sync");let n=e.windowDays??t.config?.archiveDays??sn,o=e.dryRun??false;W.info("sync invoked",{agentId:t.agentId,windowDays:n,dryRun:o,workspaceDir:t.workspaceDir});let c=new chunkEK34SXJ7_cjs.e(t.dbPath);try{await c.initialize();let s=await mn(c,t),i=await ln(c,t,n,o),g={generatedCount:s.generatedCount,skippedCount:s.skippedCount,failedGenerateCount:s.failedGenerateCount,archivedCount:i.archivedCount,archiveThreshold:i.archiveThreshold,archivedRecords:i.archivedRecords,windowDays:n,dryRun:o,durationMs:Date.now()-r};return W.info("sync complete",{agentId:t.agentId,...g}),g}catch(s){throw s instanceof S?s:new S(`sync failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{c.close();}}var gt=utils.Log.create({service:"memory.service.graph-query"});async function ut(t,e){let r=Date.now(),n=(t.agentId??"").trim()||"default",o=e.scope??"agent_only";if(!e.query||e.query.trim().length===0)throw new S("CONTENT_REQUIRED: graphQuery requires non-empty `query`","CONTENT_REQUIRED");be(t,o,"graph_query");let c=e.depth??2,s=e.maxNodes??100,i=e.query,g=e.type,l=e.relation;gt.debug("graphQuery invoked",{agentId:n,query:i,type:g,depth:c,maxNodes:s,scope:o,remote:t.remote});let p=new chunkEK34SXJ7_cjs.e(t.dbPath);try{await p.initialize();let y=new Z(p.getDb()),h=i.includes("*")||i.includes("%")?i:`%${i}%`,M=await y.queryNodes({name:h,...g?{type:g}:{},agentId:n,scope:o,limit:s}),I=(i.includes("*")||i.includes("%")?M:M.filter(R=>R.name.toLowerCase().includes(i.toLowerCase())))[0]??null;if(!I)return {root:null,nodes:[],edges:[],truncated:!1,totalNodes:0,totalEdges:0,scope:o,durationMs:Date.now()-r};let u=await y.queryNeighbors(I.id,c,{agentId:n,scope:o,maxEdgesPerNode:20}),E=new Map;E.set(I.id,I);for(let R of u)E.set(R.id,{id:R.id,name:R.name,type:R.type,createdAt:R.createdAt,updatedAt:R.updatedAt});let C=[];for(let R of u)if(R.edges)for(let f of R.edges)l&&f.relation!==l||C.push(f);for(let R of C){if(!E.has(R.source)){let f=await y.queryNodes({ids:[R.source],agentId:n,scope:o});f[0]&&E.set(f[0].id,f[0]);}if(!E.has(R.target)){let f=await y.queryNodes({ids:[R.target],agentId:n,scope:o});f[0]&&E.set(f[0].id,f[0]);}}let v=Array.from(E.values()),b=v.length>s,_=b?v.slice(0,s):v;return gt.info("graphQuery complete",{agentId:n,rootId:I.id,nodeCount:_.length,edgeCount:C.length,truncated:b,durationMs:Date.now()-r}),{root:I,nodes:_,edges:C,truncated:b,totalNodes:v.length,totalEdges:C.length,scope:o,durationMs:Date.now()-r}}catch(y){throw y instanceof S?y:new S(`graphQuery failed: ${y instanceof Error?y.message:String(y)}`,"INTERNAL",{cause:y instanceof Error?y.message:String(y)})}finally{p.close();}}var j=utils.Log.create({service:"memory.service.init"});function Oe(t){return fe__default.default.join(t,".easbot","memory.json")}async function bn(t){try{let{Config:e}=await import('@easbot/llm'),r=await e.get(),n=o=>typeof o=="string"&&o.length>0?o:void 0;return {embeddingModel:n(r.embedding_model),graphModel:n(r.graph_model)}}catch{return {}}}function En(t,e={}){let r={version:1,schema_version:chunkEK34SXJ7_cjs.a,backend:"better-sqlite3",created_at:new Date().toISOString(),embedding_model:e.embeddingModel??null,graph_model:e.graphModel??null,entity_extraction_prompt:e.entityExtractionPrompt??null,relation_extraction_prompt:e.relationExtractionPrompt??null,archiveDays:e.archiveDays??30,shortTermMaxRounds:e.shortTermMaxRounds??20};fs.writeFileSync(t,JSON.stringify(r,null,2),"utf-8");}async function ft(t,e={}){let r=Date.now();z(t,"init");let n=e.workspaceDir??t.workspaceDir,o=e.dbPath??t.dbPath;if(!n||n.trim().length===0)throw new S("init requires non-empty `workspaceDir` (ctx.workspaceDir or params.workspaceDir)","CONTENT_REQUIRED");if(!o||o.trim().length===0)throw new S("init requires non-empty `dbPath` (ctx.dbPath or params.dbPath)","CONTENT_REQUIRED");let c=t.agentId?.trim()??"",s=e.force??false;j.debug("init invoked",{agentId:c,workspaceDir:n,dbPath:o,force:s});let i=Oe(n);if(!s)try{if(await Q__default.default.stat(i).then(()=>!0).catch(()=>!1))return j.info("init: idempotent skip (memory.json exists, no --force)",{workspaceDir:n,configPath:i}),{initialized:!1,dbPath:o,configPath:i,configCreated:!1,schemaVersion:chunkEK34SXJ7_cjs.a,workspaceDir:n,tablesCreated:0,migrationsApplied:0,durationMs:0}}catch{}try{await Q__default.default.mkdir(fe__default.default.dirname(o),{recursive:!0}),await Q__default.default.mkdir(fe__default.default.join(n,".easbot","memory","active"),{recursive:!0}),await Q__default.default.mkdir(fe__default.default.join(n,"archive"),{recursive:!0}),await Q__default.default.mkdir(fe__default.default.join(n,".easbot"),{recursive:!0});}catch(y){throw new S(`init: failed to create directories: ${y instanceof Error?y.message:String(y)}`,"INTERNAL",{cause:y instanceof Error?y.message:String(y)})}if(s)for(let y of [o,`${o}-wal`,`${o}-shm`])try{await Q__default.default.rm(y,{force:!0});}catch(h){j.warn("init: force rm failed (may not exist)",{path:y,error:h instanceof Error?h.message:String(h)});}let g=await bn(),l=false;try{!await Q__default.default.stat(i).then(()=>!0).catch(()=>!1)||s?(En(i,{embeddingModel:g.embeddingModel,graphModel:g.graphModel,archiveDays:t.config?.archiveDays,shortTermMaxRounds:t.config?.shortTermMaxRounds}),l=!0,j.info("init: memory.json written",{configPath:i,force:s,configCreated:l})):j.debug("init: memory.json already exists, skipping write",{configPath:i});}catch(y){j.warn("init: memory.json write failed (non-fatal)",{configPath:i,error:y instanceof Error?y.message:String(y)});}let p=new chunkEK34SXJ7_cjs.e(o);try{let y=await Q__default.default.stat(o).then(()=>!0).catch(()=>!1);await p.initialize();let h=new Date().toISOString(),M=[["version","1.0.0"],["schemaVersion",String(chunkEK34SXJ7_cjs.a)],["createdAt",h],["defaultAgentId",c]];for(let[u,E]of M)try{p.run("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)",[u,E]);}catch(C){j.warn("init: meta insert failed",{key:u,error:C instanceof Error?C.message:String(C)});}let D=0;try{D=p.prepare("SELECT COUNT(*) as n FROM sqlite_master WHERE type IN ('table', 'index', 'trigger', 'view')").get()?.n??0;}catch(u){j.warn("init: tablesCreated count failed",{error:u instanceof Error?u.message:String(u)});}let I=0;try{I=p.prepare("SELECT id FROM schema_migrations").all().length;}catch(u){j.warn("init: migrationsApplied count failed",{error:u instanceof Error?u.message:String(u)});}return j.info("init complete",{agentId:c,workspaceDir:n,dbPath:o,configPath:i,configCreated:l,schemaVersion:chunkEK34SXJ7_cjs.a,durationMs:Date.now()-r}),{initialized:!0,dbPath:o,configPath:i,configCreated:l,schemaVersion:chunkEK34SXJ7_cjs.a,workspaceDir:n,tablesCreated:D,migrationsApplied:I,durationMs:Date.now()-r}}catch(y){throw new S(`init failed: ${y instanceof Error?y.message:String(y)}`,"INTERNAL",{cause:y instanceof Error?y.message:String(y)})}finally{p.close();}}var ae=utils.Log.create({service:"memory.service.status"}),In=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"],_n={};async function pt(t,e={},r=_n){let n=t.agentId&&t.agentId.trim().length>0?t.agentId:void 0;if(ae.debug("status invoked",{agentId:n??"<global>"}),!t.dbPath||t.dbPath.length===0)throw new S("`ctx.dbPath` is required","INTERNAL");let o={initialized:false,capabilities:{embedding:false,graphLlm:false}},c={},s={},i=0,g=0,l=0,p,y,h,M=false,D,I="uninitialized",u=false,E=false,C=false,v,b=In.reduce((O,L)=>(O[L]=0,O),{}),_=new chunkEK34SXJ7_cjs.e(t.dbPath);try{await _.initialize(),i=_.query(n!==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",n!==void 0?[n]:[])[0]?.c??0,g=_.query(n!==void 0?"SELECT COUNT(*) AS c FROM nodes WHERE owner_agent_id = ? OR owner_agent_id IS NULL":"SELECT COUNT(*) AS c FROM nodes",n!==void 0?[n]:[])[0]?.c??0,l=_.query("SELECT COUNT(*) as c FROM edges")[0]?.c??0;let G=_.query(n!==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",n!==void 0?[n]:[]);for(let w of G){let T=w.category;T in b&&(b[T]=w.c);}c.facts=i,c.nodes=g,c.edges=l;try{E=_.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]).length>0;}catch(w){ae.debug("status: fts probe failed",{error:w instanceof Error?w.message:String(w)});}M=!!t.config?.embeddingLlm;try{u=_.query("SELECT name FROM pragma_table_info('nodes') WHERE name = ?",["owner_agent_id"]).length>0;}catch(w){ae.debug("status: kg scope probe failed",{error:w instanceof Error?w.message:String(w)});}C=_.healthCheck();try{let w=_.query("SELECT key, value FROM meta");for(let T of w)s[T.key]=T.value;}catch(w){ae.debug("status: meta read failed",{error:w instanceof Error?w.message:String(w)});}let B=s.schema_version,J=s.extraction_version,d=s.lastSyncAt??s.lastSync,m=s.embeddingDims;p=B&&Number.parseInt(B,10)||void 0,y=J&&Number.parseInt(J,10)||void 0,h=d,D=m&&Number.parseInt(m,10)||void 0,i>0&&(I="complete");try{v=_.query("SELECT value FROM meta WHERE key = ?",["backend"])[0]?.value??"better-sqlite3";}catch{v="better-sqlite3";}}catch(O){if(O instanceof S)throw O;ae.warn("status: db phase failed; returning partial result",{dbPath:t.dbPath,error:O instanceof Error?O.message:String(O)}),v="unknown",C=false;}finally{_.close();}if(!r.skipLlm&&chunkJ5XF2W4Z_cjs.a.isInitialized()){let L=chunkJ5XF2W4Z_cjs.a.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(!r.skipEmbeddingProbe&&!r.skipLlm&&o.initialized&&o.capabilities.embedding)try{let O=chunkJ5XF2W4Z_cjs.a.getEmbeddingLlm?.();if(O){let L=await llm.probeEmbeddingDims(O,{timeoutMs:5e3});if(typeof L=="number"){D=L,s.embeddingDims=String(L);try{let A=new chunkEK34SXJ7_cjs.e(t.dbPath);try{await A.initialize();let G=A.getDb();llm.syncMeta(G,[["embeddingDims",String(L)]]);}finally{A.close();}}catch{}}}}catch{}let R;return C?I==="uninitialized"&&(R="Run `easbot memory remember <content>` to add the first fact."):R="Run `easbot memory init` to initialize the database.",C&&(I??"uninitialized")==="failed"&&(C=false),ae.info("status complete",{dbPath:t.dbPath,agentId:n??"<global>",factsCount:i,nodesCount:g,edgesCount:l,healthy:C}),{package:"memory",agentId:n,dbPath:t.dbPath,configPath:Oe(t.workspaceDir),configExists:true,schemaVersion:p,extractionVersion:y,lastSyncAt:h,indexState:I,vectorEnabled:M,embeddingDims:D,llm:o,backend:v,counts:c,meta:s,recommendation:R,healthy:C,factsByCategory:b,kgScopeEnabled:u,factsCount:i,nodesCount:g,edgesCount:l,ftsAvailable:E}}var On=utils.Log.create({service:"memory.service.doctor"}),Te=100*1024*1024,yt=100*1024*1024,Nn={};function N(t,e,r,n,o){return {code:t.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),severity:e,name:t,message:r,details:o,durationMs:n,passed:e!=="error"}}async function ht(t,e={},r=Nn){if(On.debug("doctor invoked",{agentId:t.agentId}),!t.dbPath||t.dbPath.length===0)throw new Error("`ctx.dbPath` is required");let n=[],o=[],c=Date.now(),s=null,i=false,g=Date.now();try{s=new chunkEK34SXJ7_cjs.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()-g,{dbPath:t.dbPath});n.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()-g,{dbPath:t.dbPath});n.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}let l=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,w=N("fts",m?"ok":"warn",m?"FTS5 index available":"FTS5 index not found",Date.now()-l,m?{table:d[0]?.name}:void 0);n.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("fts","error",`fts probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-l);n.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);n.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let p=Date.now(),y=!!t.config?.embeddingLlm,h=N("vector","ok",y?"embedding model available":"no embedding model configured (FTS-only mode, recall still functional)",Date.now()-p,{mode:y?"hybrid":"fts_only",model:y?"configured":"missing"});n.push(h),o.push({name:h.name,passed:true,message:h.message,details:h.details,severity:"ok"});let M=Date.now();if(i&&s)try{let d=["memory_facts","nodes","edges","meta"],m=s.query("SELECT name FROM sqlite_master WHERE type = ?",["table"]),w=new Set(m.map(q=>q.name)),T=d.filter(q=>!w.has(q)),P=N("schema",T.length===0?"ok":"error",T.length===0?`schema complete (${d.length} tables)`:`missing tables: ${T.join(", ")}`,Date.now()-M,{required:d,existing:Array.from(w)});n.push(P),o.push({name:P.name,passed:P.severity!=="error",message:P.message,details:P.details,severity:P.severity});}catch(d){let m=N("schema","error",`schema probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-M);n.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);n.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let D=Date.now();try{let d=`${t.dbPath}-wal`,m=`${t.dbPath}-shm`,w=0,T=0;try{w=(await Q__default.default.stat(d)).size;}catch{w=0;}try{T=(await Q__default.default.stat(m)).size;}catch{T=0;}let P=w+T,q=P<=yt,H=N("lock",q?"ok":"warn",q?`no lock contention (wal+shm ${(P/1024).toFixed(1)} KB)`:`WAL/SHM files unusually large (${(P/1024/1024).toFixed(1)} MB > ${(yt/1024/1024).toFixed(0)} MB threshold)`,Date.now()-D,{walBytes:w,shmBytes:T});n.push(H),o.push({name:H.name,passed:H.severity!=="error",message:H.message,details:H.details,severity:H.severity});}catch(d){let m=N("lock","error",`lock probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-D);n.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}let I=Date.now();try{let d=fe__default.default.dirname(t.dbPath),m=await Q__default.default.statfs(d),w=typeof m.bsize=="bigint"?Number(m.bsize)*m.bavail:m.bsize*m.bavail,T=w>=Te,P=N("disk_space",T?"ok":"error",T?`sufficient disk space (${(w/1024/1024).toFixed(1)} MB available)`:`low disk space (${(w/1024/1024).toFixed(1)} MB < ${(Te/1024/1024).toFixed(0)} MB threshold)`,Date.now()-I,{availableBytes:w,threshold:Te});n.push(P),o.push({name:P.name,passed:P.severity!=="error",message:P.message,details:P.details,severity:P.severity});}catch(d){let m=N("disk_space","error",`disk_space probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-I);n.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}let u=Date.now();if(i&&s)try{let d=s.agentFilter(t.agentId),w=s.query(`SELECT COUNT(*) as c FROM memory_facts ${d.where}`,d.params)[0]?.c??0;if(w===0){let T=N("fact_node_consistency","info","no facts in db \u2014 nothing to check",Date.now()-u);n.push(T),o.push({name:T.name,passed:!0,message:T.message,severity:"info"});}else {let P=s.query(`SELECT COUNT(DISTINCT fn.fact_id) as c
59
+ FROM fact_nodes fn
60
+ INNER JOIN memory_facts mf ON mf.id = fn.fact_id
61
+ ${d.where}`,d.params)[0]?.c??0,q=w>0?P/w*100:0,H=q>=50?"ok":q>=30?"info":"warn",U=q>=50?`${q.toFixed(1)}% facts linked to KG nodes`:q>=30?`${q.toFixed(1)}% facts linked to KG nodes \u2014 run \`easbot memory remember\` to improve`:`${q.toFixed(1)}% facts linked to KG nodes \u2014 KG extraction may be disabled`,Y=N("fact_node_consistency",H,U,Date.now()-u,{facts:w,linked:P,pct:q});n.push(Y),o.push({name:Y.name,passed:Y.severity!=="error",message:Y.message,details:Y.details,severity:Y.severity});}}catch(d){let m=N("fact_node_consistency","warn",`fact_node_consistency probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-u);n.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);n.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let E=Date.now();if(i&&s)try{let m=s.query("SELECT COUNT(*) as c FROM nodes"+(t.agentId?" WHERE owner_agent_id = ?":""),t.agentId?[t.agentId]:[])[0]?.c??0;if(m===0){let w=N("node_embedding_coverage","info","no nodes in KG \u2014 nothing to check",Date.now()-E);n.push(w),o.push({name:w.name,passed:!0,message:w.message,severity:"info"});}else {let T=s.query("SELECT COUNT(*) as c FROM nodes WHERE embedding IS NOT NULL"+(t.agentId?" AND owner_agent_id = ?":""),t.agentId?[t.agentId]:[])[0]?.c??0,P=m>0?T/m*100:0,q=P>=50?"ok":P>=30?"info":"warn",H=P>=50?`${P.toFixed(1)}% nodes have embedding (${T}/${m})`:P>=30?`${P.toFixed(1)}% nodes have embedding (${T}/${m}) \u2014 GraphRAG entity vector partial`:`${P.toFixed(1)}% nodes have embedding (${T}/${m}) \u2014 GraphRAG entity vector disabled`,U=N("node_embedding_coverage",q,H,Date.now()-E,{total:m,withEmbedding:T,pct:P});n.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("node_embedding_coverage","warn",`node_embedding_coverage probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-E);n.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);n.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 fn.fact_id, fn.node_id
62
+ FROM fact_nodes fn
63
+ LEFT JOIN nodes n ON fn.node_id = n.id
64
+ WHERE n.id IS NULL
65
+ LIMIT 100`).map(T=>`${T.fact_id}->${T.node_id}`),w=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()-C,{count:m.length});n.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("orphan","warn",`orphan probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-C);n.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);n.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let v=Date.now(),b={"better-sqlite3":false,"node:sqlite":false,"@tursodatabase/database":false};try{let d=module$1.createRequire(chunkM2YU5LAI_cjs.b);try{d.resolve("better-sqlite3"),b["better-sqlite3"]=!0;}catch{}b["node:sqlite"]=typeof process.versions.sqlite=="string";try{d.resolve("@tursodatabase/database"),b["@tursodatabase/database"]=!0;}catch{}}catch{}let _=b["better-sqlite3"]||b["node:sqlite"],R=N("backend",_?"ok":"error",_?`SQLite backend available (better-sqlite3: ${b["better-sqlite3"]}, node:sqlite: ${b["node:sqlite"]})`:"no SQLite backend available (install better-sqlite3 or use Node 22.5+)",Date.now()-v,b);n.push(R),o.push({name:R.name,passed:R.severity!=="error",message:R.message,details:R.details,severity:R.severity});let f=Date.now();if(i&&s)try{let d=s.query("SELECT COUNT(*) as c FROM embedding_cache")[0],m=s.agentFilter(t.agentId),w=s.query(`SELECT COUNT(*) as c FROM memory_facts ${m.where}`,m.params)[0],T=d?.c??0,P=w?.c??0,q=Math.max(0,T-P),H=q>0,U=N("embedding_cache_unused","info",H?`by design: ${q} 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()-f,{cacheCount:T,factsCount:P,unused:q,policy:"global_content_hash_dedup"});n.push(U),o.push({name:U.name,passed:!H,message:U.message,details:U.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()-f);n.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);n.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let O=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 A;if(r.skipLlm||!chunkJ5XF2W4Z_cjs.a.isInitialized()||!chunkJ5XF2W4Z_cjs.a.capabilities().embedding)A=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","llm not initialized; probe skipped",Date.now()-O);else if(r.skipEmbeddingProbe)A=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe skipped (--skip-embedding-probe)",Date.now()-O);else try{let d=chunkJ5XF2W4Z_cjs.a.getEmbeddingLlm?.();if(!d)A=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","embedding llm not exposed; probe skipped",Date.now()-O);else {let m=await llm.probeEmbeddingDims(d,{timeoutMs:5e3});typeof m!="number"?A=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe failed (network / model error)",Date.now()-O):L===void 0?A=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe=${m}, meta missing \u2014 next status will sync`,Date.now()-O):m!==L?A=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"warn",`probe=${m}, meta=${L} \u2014 mismatch`,Date.now()-O,{probe:m,meta:L}):A=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"ok",`probe=${m}, meta=${L} \u2014 consistent`,Date.now()-O);}}catch(d){A=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe threw: ${d instanceof Error?d.message:String(d)}`,Date.now()-O);}n.push({...A,details:A.details??void 0,passed:A.severity!=="error"}),o.push({name:A.name,passed:A.severity!=="error",message:A.message,details:A.details??void 0,severity:A.severity});let G;if(i&&s){let d=Date.now();try{let{issues:m,stats:w}=s.checkIntegrity();G=w;for(let T of m)n.push(N("integrity_stats",T.severity,T.message,0,{source:"database.checkIntegrity"}));}catch(m){n.push(N("integrity_stats","warn",`db integrity check failed: ${m instanceof Error?m.message:String(m)}`,Date.now()-d));}}let B=!n.some(d=>d.severity==="error");s&&s.close();let J=Date.now()-c;return {healthy:B,checks:n,legacyChecks:o,durationMs:J,integrityStats:G,backendAvailable:b}}var Pe={name:"recall",scope:"read",schema:Be,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=t;if(!e.agentId?.trim())throw new Error("recall: agentId is required");return je({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var ke={name:"remember",scope:"write",schema:ze,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=t;if(!e.agentId?.trim())throw new Error("remember: agentId is required");return rt({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 Ae={name:"update",scope:"write",schema:Qe,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=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 xe={name:"forget",scope:"write",schema:Ke,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=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 Le={name:"extract",scope:"write",schema:Je,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=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 Fe={name:"consolidate",scope:"admin",schema:Ve,annotations:{localOnly:true,requiresAgentId:true,defaultDescription:"Run consolidation pipeline: dedup \u2192 archive.",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let r=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 qe={name:"sync",scope:"admin",schema:tt,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=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 $e={name:"graph_query",scope:"read",schema:Ye,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Query KG nodes / edges / neighbors with scope filtering.",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=t,n=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:n},r)}};var He={name:"status",scope:"read",schema:Xe,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=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 Ue={name:"doctor",scope:"admin",schema:Ze,annotations:{localOnly:true,requiresAgentId:false,defaultDescription:"Run 7 health checks (database / fts / vector / schema / lock / disk_space / orphan).",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=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 We={name:"init",scope:"admin",schema:et,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=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={[Pe.name]:Pe,[ke.name]:ke,[Ae.name]:Ae,[xe.name]:xe,[Le.name]:Le,[Fe.name]:Fe,[qe.name]:qe,[$e.name]:$e,[He.name]:He,[Ue.name]:Ue,[We.name]:We},Tn=Object.values(bt);function Pn(t,e,r){if(t.annotations.localOnly&&!e.isTrustedLocal)throw new Error(`MEMORY:executeOp: op "${r}" is localOnly; non-trusted caller rejected`);if(t.annotations.requiresAgentId){let n=e.agentId?.trim()??"";if(n.length===0)throw new Error(`MEMORY:executeOp: op "${r}" requires agentId`);e.agentId=n;}}async function Ka(t,e,r){let n=bt[t];if(!n)throw new Error(`executeOp: unknown op "${t}"; available: ${Tn.map(c=>c.name).join(", ")}`);return Pn(n,r,t),await n.handler(e,r)}function xn(t){let e=t.dbPath??"";return {workspaceDir:t.workspaceDir??"",database:{path:e},embeddingLlm:chunkJ5XF2W4Z_cjs.a.getEmbeddingLlm(),graphLlm:chunkJ5XF2W4Z_cjs.a.getGraphLlm(),search:types.DEFAULT_SEARCH_CONFIG,indexer:{batchSize:20,ignorePatterns:[],incremental:true},archiveDays:30,shortTermMaxRounds:20}}function rs(t,e,r={}){let n=chunkCPRDIUQ4_cjs.j(e),o=utils.Locale.resolveLocaleLang(r.locale);return {agentId:t,dbPath:n,workspaceDir:e,rootDir:e,config:xn({dbPath:n,workspaceDir:e}),isTrustedLocal:true,locale:o,remote:false,...r}}exports.a=Z;exports.b=je;exports.c=Be;exports.d=ze;exports.e=Ke;exports.f=Je;exports.g=Ve;exports.h=Ye;exports.i=et;exports.j=tt;exports.k=rt;exports.l=ot;exports.m=at;exports.n=it;exports.o=ct;exports.p=lt;exports.q=ut;exports.r=ft;exports.s=pt;exports.t=ht;exports.u=bt;exports.v=Tn;exports.w=Ka;exports.x=xn;exports.y=rs;