@easbot/memory 0.3.24 → 0.3.25

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 (68) hide show
  1. package/README.en.md +43 -30
  2. package/README.md +46 -32
  3. package/dist/chunks/chunk-4YADRVIU.mjs +1 -0
  4. package/dist/chunks/chunk-DW3CJUBO.cjs +1 -0
  5. package/dist/chunks/chunk-HY2LFKG7.cjs +67 -0
  6. package/dist/chunks/chunk-I5YSX4DQ.mjs +64 -0
  7. package/dist/chunks/chunk-P45OBSAC.cjs +64 -0
  8. package/dist/chunks/chunk-X7P7ZFZF.mjs +67 -0
  9. package/dist/chunks/cli-handler-ETHJPZPG.mjs +1 -0
  10. package/dist/chunks/cli-handler-PG4IBTY2.cjs +1 -0
  11. package/dist/chunks/consolidate-7GFUFPLX.cjs +2 -0
  12. package/dist/chunks/consolidate-BGMXJUQX.mjs +2 -0
  13. package/dist/chunks/{doctor-RNI5F6GO.mjs → doctor-C2FWFUDO.mjs} +1 -1
  14. package/dist/chunks/{doctor-SJY3K3DV.cjs → doctor-SCXUJRSG.cjs} +1 -1
  15. package/dist/chunks/extract-O4IOL6BZ.cjs +2 -0
  16. package/dist/chunks/extract-RBBSVK2S.mjs +2 -0
  17. package/dist/chunks/forget-JTACRG7Y.mjs +3 -0
  18. package/dist/chunks/forget-M4I6GVWI.cjs +3 -0
  19. package/dist/chunks/graph-AOMDJ6YA.cjs +3 -0
  20. package/dist/chunks/graph-VBVVRV6V.mjs +3 -0
  21. package/dist/chunks/init-2SBK7ZWO.mjs +1 -0
  22. package/dist/chunks/init-VTPJR56L.cjs +1 -0
  23. package/dist/chunks/{mcp-PRR2RYOP.cjs → mcp-VIOHPDO5.cjs} +1 -1
  24. package/dist/chunks/{mcp-RMLMXPZ7.mjs → mcp-ZQCLVZIR.mjs} +1 -1
  25. package/dist/chunks/recall-JSTQDGGZ.cjs +2 -0
  26. package/dist/chunks/recall-UQSG6ECA.mjs +2 -0
  27. package/dist/chunks/remember-GVQJ5G7Z.mjs +2 -0
  28. package/dist/chunks/remember-Z4UJJN62.cjs +2 -0
  29. package/dist/chunks/status-DH33MQZV.cjs +1 -0
  30. package/dist/chunks/status-VZ5EBAOY.mjs +1 -0
  31. package/dist/chunks/stdio-server-JC53PUET.mjs +1 -0
  32. package/dist/chunks/{stdio-server-SXDIW3RQ.cjs → stdio-server-OUZAN4IM.cjs} +1 -1
  33. package/dist/chunks/sync-6I2ZJUH6.cjs +2 -0
  34. package/dist/chunks/sync-UT4D32ML.mjs +2 -0
  35. package/dist/cli.cjs +1 -1
  36. package/dist/cli.mjs +1 -1
  37. package/dist/index.cjs +3 -3
  38. package/dist/index.d.cts +5 -2
  39. package/dist/index.d.ts +5 -2
  40. package/dist/index.mjs +1 -1
  41. package/package.json +9 -9
  42. package/dist/chunks/chunk-46Y7MLBE.cjs +0 -1
  43. package/dist/chunks/chunk-5VZKEZI4.cjs +0 -67
  44. package/dist/chunks/chunk-C3Z455VR.mjs +0 -67
  45. package/dist/chunks/chunk-GL5U3MRI.mjs +0 -64
  46. package/dist/chunks/chunk-MPGIP3IF.cjs +0 -64
  47. package/dist/chunks/chunk-PGJB2U24.mjs +0 -1
  48. package/dist/chunks/cli-handler-KTFW5CCH.mjs +0 -1
  49. package/dist/chunks/cli-handler-Y43WWXOO.cjs +0 -1
  50. package/dist/chunks/consolidate-VGPUQRPU.mjs +0 -2
  51. package/dist/chunks/consolidate-X52RRH2C.cjs +0 -2
  52. package/dist/chunks/extract-ANENWMHZ.mjs +0 -2
  53. package/dist/chunks/extract-L2V2RMDQ.cjs +0 -2
  54. package/dist/chunks/forget-QNG6GELC.mjs +0 -3
  55. package/dist/chunks/forget-SSGVAE5Y.cjs +0 -3
  56. package/dist/chunks/graph-KNLZRAPI.mjs +0 -3
  57. package/dist/chunks/graph-WIKKSBLC.cjs +0 -3
  58. package/dist/chunks/init-2UNKNWR5.mjs +0 -1
  59. package/dist/chunks/init-UNDHFDAC.cjs +0 -1
  60. package/dist/chunks/recall-7TPMD7ZE.mjs +0 -2
  61. package/dist/chunks/recall-M2EWX25U.cjs +0 -2
  62. package/dist/chunks/remember-BXVUUY5M.cjs +0 -2
  63. package/dist/chunks/remember-H5CYMLG5.mjs +0 -2
  64. package/dist/chunks/status-A2JC6NFH.cjs +0 -1
  65. package/dist/chunks/status-MJFDNSPW.mjs +0 -1
  66. package/dist/chunks/stdio-server-43QC3XIS.mjs +0 -1
  67. package/dist/chunks/sync-3RWIZYR6.cjs +0 -2
  68. package/dist/chunks/sync-GPRNZLZA.mjs +0 -2
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunk4GSXSIV5_cjs=require('./chunk-4GSXSIV5.cjs');require('./chunk-WQB4D6DZ.cjs');var chunkHY2LFKG7_cjs=require('./chunk-HY2LFKG7.cjs');require('./chunk-LYBUZDJK.cjs'),require('./chunk-CPRDIUQ4.cjs'),require('./chunk-J5XF2W4Z.cjs'),require('./chunk-M2YU5LAI.cjs');async function u(r){if(!r.content?.trim())throw new Error("remember: --content is required");if(!r.category?.trim())throw new Error("remember: --category is required");if(r.importance===void 0)throw new Error("remember: --importance is required (1-10)");let e=r.agentId?.trim();if(!e)throw new Error("remember: agentId is required (ctx environment; agent CLI / standalone CLI must inject)");let n=r.workspaceDir??process.cwd();return chunkHY2LFKG7_cjs.z("remember",{content:r.content,category:r.category,importance:r.importance,tags:r.tags,sessionId:r.sessionId},chunkHY2LFKG7_cjs.B(e,n))}function p(r){let e=r,n=[chunk4GSXSIV5_cjs.b("remember",{},"Memory persisted:"),chunk4GSXSIV5_cjs.c("remember",{id:e.fact.id,category:e.fact.category,importance:String(e.fact.importance??5)}," - id={{id}} category={{category}} importance={{importance}}"),` - createdAt: ${e.fact.createdAt}`];return e.deduplicated&&n.push(" - (deduplicated; no new fact inserted)"),n.join(`
2
+ `)}function l(r){let e={};for(let n=0;n<r.length;n++){let i=r[n];if(i===void 0)continue;let t=r[n+1];i==="--agent"&&t!==void 0?n++:i==="--content"&&t!==void 0?(e.content=t,n++):i==="--category"&&t!==void 0?(e.category=t,n++):i==="--importance"&&t!==void 0?(e.importance=Number(t),n++):i==="--tag"&&t!==void 0?(e.tags=[...e.tags??[],t],n++):i==="--session"&&t!==void 0?(e.sessionId=t,n++):i==="--json"?e.json=true:(i==="--help"||i==="-h")&&(e.help=true);}return e}exports.formatRememberText=p;exports.parseRememberOptions=l;exports.runRemember=u;
@@ -0,0 +1 @@
1
+ 'use strict';var chunkHY2LFKG7_cjs=require('./chunk-HY2LFKG7.cjs');require('./chunk-LYBUZDJK.cjs'),require('./chunk-CPRDIUQ4.cjs'),require('./chunk-J5XF2W4Z.cjs'),require('./chunk-M2YU5LAI.cjs');async function c(t){let e=t.workspaceDir??process.cwd(),n=t.agentId?.trim()??"default";return chunkHY2LFKG7_cjs.z("status",{},chunkHY2LFKG7_cjs.B(n,e))}function f(t){return ""}function l(t){let e={};for(let n=0;n<t.length;n++){let o=t[n];if(o===void 0)continue;t[n+1];o==="--agent"?n++:o==="--json"?e.json=true:(o==="--help"||o==="-h")&&(e.help=true);}return e}exports.formatStatusText=f;exports.parseStatusOptions=l;exports.runStatus=c;
@@ -0,0 +1 @@
1
+ import {z,B}from'./chunk-X7P7ZFZF.mjs';import'./chunk-FY4ILCIM.mjs';import'./chunk-WDVDYZ25.mjs';import'./chunk-6CQMBEIQ.mjs';import'./chunk-HQBRVVXS.mjs';async function f(t){let e=t.workspaceDir??process.cwd(),n=t.agentId?.trim()??"default";return z("status",{},B(n,e))}function l(t){return ""}function d(t){let e={};for(let n=0;n<t.length;n++){let o=t[n];if(o===void 0)continue;t[n+1];o==="--agent"?n++:o==="--json"?e.json=true:(o==="--help"||o==="-h")&&(e.help=true);}return e}export{l as formatStatusText,d as parseStatusOptions,f as runStatus};
@@ -0,0 +1 @@
1
+ export{b as MemoryStdioServer}from'./chunk-I5YSX4DQ.mjs';import'./chunk-X7P7ZFZF.mjs';import'./chunk-FY4ILCIM.mjs';import'./chunk-WDVDYZ25.mjs';import'./chunk-6CQMBEIQ.mjs';import'./chunk-HQBRVVXS.mjs';
@@ -1 +1 @@
1
- 'use strict';var chunkMPGIP3IF_cjs=require('./chunk-MPGIP3IF.cjs');require('./chunk-5VZKEZI4.cjs'),require('./chunk-LYBUZDJK.cjs'),require('./chunk-CPRDIUQ4.cjs'),require('./chunk-J5XF2W4Z.cjs'),require('./chunk-M2YU5LAI.cjs');Object.defineProperty(exports,"MemoryStdioServer",{enumerable:true,get:function(){return chunkMPGIP3IF_cjs.b}});
1
+ 'use strict';var chunkP45OBSAC_cjs=require('./chunk-P45OBSAC.cjs');require('./chunk-HY2LFKG7.cjs'),require('./chunk-LYBUZDJK.cjs'),require('./chunk-CPRDIUQ4.cjs'),require('./chunk-J5XF2W4Z.cjs'),require('./chunk-M2YU5LAI.cjs');Object.defineProperty(exports,"MemoryStdioServer",{enumerable:true,get:function(){return chunkP45OBSAC_cjs.b}});
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunk4GSXSIV5_cjs=require('./chunk-4GSXSIV5.cjs');require('./chunk-WQB4D6DZ.cjs');var chunkHY2LFKG7_cjs=require('./chunk-HY2LFKG7.cjs');require('./chunk-LYBUZDJK.cjs'),require('./chunk-CPRDIUQ4.cjs'),require('./chunk-J5XF2W4Z.cjs'),require('./chunk-M2YU5LAI.cjs');async function l(e){let n=e.agentId?.trim();if(!n)throw new Error("sync: agentId is required (ctx environment; agent CLI / standalone CLI must inject)");let r=e.workspaceDir??process.cwd();return chunkHY2LFKG7_cjs.z("sync",{windowDays:e.windowDays,dryRun:e.dryRun??false},chunkHY2LFKG7_cjs.B(n,r))}function m(e){let n=e;return [chunk4GSXSIV5_cjs.b("sync",{windowDays:String(n.windowDays),dryRun:String(n.dryRun)},"sync complete (windowDays={{windowDays}}, dryRun={{dryRun}}):"),chunk4GSXSIV5_cjs.c("sync",{generatedCount:String(n.generatedCount),skippedCount:String(n.skippedCount),failedGenerateCount:String(n.failedGenerateCount),archivedCount:String(n.archivedCount),archiveThreshold:n.archiveThreshold}," - generated: {{generatedCount}}, skipped: {{skippedCount}}, failed: {{failedGenerateCount}}, archived: {{archivedCount}} (threshold: {{archiveThreshold}})"),` - duration: ${n.durationMs}ms`].join(`
2
+ `)}function f(e){let n={};for(let r=0;r<e.length;r++){let t=e[r];if(t===void 0)continue;let i=e[r+1];if(t==="--agent")r++;else if(t==="--window-days"){let o=Number(i);if(Number.isNaN(o)||o<1||o>3650)throw new Error(`--window-days must be an integer in [1, 3650], got: ${i??"(empty)"}`);n.windowDays=o,r++;}else t==="--dry-run"?n.dryRun=true:t==="--json"?n.json=true:(t==="--help"||t==="-h")&&(n.help=true);}return n}exports.formatSyncText=m;exports.parseSyncOptions=f;exports.runSync=l;
@@ -0,0 +1,2 @@
1
+ import {b,c}from'./chunk-QYBWHFOX.mjs';import'./chunk-SWYQLQ7Z.mjs';import {z,B}from'./chunk-X7P7ZFZF.mjs';import'./chunk-FY4ILCIM.mjs';import'./chunk-WDVDYZ25.mjs';import'./chunk-6CQMBEIQ.mjs';import'./chunk-HQBRVVXS.mjs';async function m(e){let n=e.agentId?.trim();if(!n)throw new Error("sync: agentId is required (ctx environment; agent CLI / standalone CLI must inject)");let r=e.workspaceDir??process.cwd();return z("sync",{windowDays:e.windowDays,dryRun:e.dryRun??false},B(n,r))}function f(e){let n=e;return [b("sync",{windowDays:String(n.windowDays),dryRun:String(n.dryRun)},"sync complete (windowDays={{windowDays}}, dryRun={{dryRun}}):"),c("sync",{generatedCount:String(n.generatedCount),skippedCount:String(n.skippedCount),failedGenerateCount:String(n.failedGenerateCount),archivedCount:String(n.archivedCount),archiveThreshold:n.archiveThreshold}," - generated: {{generatedCount}}, skipped: {{skippedCount}}, failed: {{failedGenerateCount}}, archived: {{archivedCount}} (threshold: {{archiveThreshold}})"),` - duration: ${n.durationMs}ms`].join(`
2
+ `)}function h(e){let n={};for(let r=0;r<e.length;r++){let t=e[r];if(t===void 0)continue;let i=e[r+1];if(t==="--agent")r++;else if(t==="--window-days"){let o=Number(i);if(Number.isNaN(o)||o<1||o>3650)throw new Error(`--window-days must be an integer in [1, 3650], got: ${i??"(empty)"}`);n.windowDays=o,r++;}else t==="--dry-run"?n.dryRun=true:t==="--json"?n.json=true:(t==="--help"||t==="-h")&&(n.help=true);}return n}export{f as formatSyncText,h as parseSyncOptions,m as runSync};
package/dist/cli.cjs CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';var chunkM2YU5LAI_cjs=require('./chunks/chunk-M2YU5LAI.cjs'),fs=require('fs'),path=require('path'),url=require('url'),terminal=require('@easbot/terminal');var E=path.dirname(url.fileURLToPath(chunkM2YU5LAI_cjs.b));function A(){try{let t=path.join(E,"..","package.json");return JSON.parse(fs.readFileSync(t,"utf-8")).version??"0.0.0"}catch{return "0.0.0"}}var f=new Set(["DEBUG","INFO","WARN","ERROR"]);function N(t){let n={logLevel:"INFO",printLogs:false,debug:false};for(let i=0;i<t.length;i++){let e=t[i];if(e)if(e==="--cwd"&&i+1<t.length){let o=t[i+1];o&&!o.startsWith("-")&&(n.cwd=o,i++);}else if(e.startsWith("--cwd="))n.cwd=e.slice(6);else if(e==="--config"&&i+1<t.length){let o=t[i+1];o&&!o.startsWith("-")&&(n.configPath=o,i++);}else if(e.startsWith("--config="))n.configPath=e.slice(9);else if(e==="--log-level"&&i+1<t.length){let o=t[i+1];if(o&&!o.startsWith("-")){let r=o.toUpperCase();f.has(r)&&(n.logLevel=r,i++);}}else if(e.startsWith("--log-level=")){let o=e.slice(12).toUpperCase();f.has(o)&&(n.logLevel=o);}else e==="--print-logs"?n.printLogs=true:e==="--debug"&&(n.debug=true);}return n}async function R(){let t=process.argv.slice(2),n=A(),{loadEnv:i}=await import('@easbot/utils');i(),process.env.EASBOT_LANG||(process.env.EASBOT_LANG="en-US");let e=N(t),{Log:o}=await import('@easbot/utils'),{getXdgData:r}=await import('./chunks/interfaces-Q5OGU5EK.cjs'),h=path.join(r(),"memory","log");if(await o.init({logDir:h,print:e.printLogs,dev:e.debug||false,level:e.logLevel}),t.length===0){let{renderBanner:l}=await import('./chunks/cli-handler-Y43WWXOO.cjs');l();return}if(t[0]==="--help"||t[0]==="-h"){let{renderHelp:l}=await import('./chunks/cli-handler-Y43WWXOO.cjs');l();return}if(t[0]==="--version"||t[0]==="-v"){terminal.printHuman([terminal.formatInfo(n)]);return}let a=e.cwd??process.cwd(),{handleMemoryCli:m}=await import('./chunks/cli-handler-Y43WWXOO.cjs'),{setInstanceAdapter:u}=await import('./chunks/interfaces-Q5OGU5EK.cjs');u({directory:a,worktree:a});let{Llm:w}=await import('./chunks/llm-7LQGYSUE.cjs'),{bootstrapLlm:L,setAdapterRegistry:b}=await import('@easbot/llm'),{getGlobal:s,getInstance:c}=await import('./chunks/interfaces-Q5OGU5EK.cjs');b({config:void 0,instance:{getDirectory:()=>c().directory,getWorktree:()=>c().worktree},global:{home:s().Path.home,data:s().Path.data,cache:s().Path.cache,config:s().Path.config,state:s().Path.state,log:s().Path.log,bin:s().Path.bin},installation:{getVersion:()=>n,getChannel:()=>"local",getUserAgent:()=>`easbot-memory/${n}`}}),await L({target:w,cwd:a,subConfigPath:".easbot/memory.json",embedding:true,graph:true});let g=await m(t,{version:n,cwd:a});g.code!==0&&(process.exitCode=g.code);}R().catch(t=>{console.error(t),process.exitCode=1;}).finally(async()=>{try{let{Log:t}=await import('@easbot/utils');await t.close();}catch{}process.exit(process.exitCode??0);});
2
+ 'use strict';var chunkM2YU5LAI_cjs=require('./chunks/chunk-M2YU5LAI.cjs'),fs=require('fs'),path=require('path'),url=require('url'),terminal=require('@easbot/terminal');require('@easbot/utils');var R=path.dirname(url.fileURLToPath(chunkM2YU5LAI_cjs.b));function S(){try{let t=path.join(R,"..","package.json");return JSON.parse(fs.readFileSync(t,"utf-8")).version??"0.0.0"}catch{return "0.0.0"}}var h=new Set(["DEBUG","INFO","WARN","ERROR"]);function D(t){let n={logLevel:"INFO",printLogs:false,debug:false};for(let s=0;s<t.length;s++){let e=t[s];if(e)if(e==="--cwd"&&s+1<t.length){let o=t[s+1];o&&!o.startsWith("-")&&(n.cwd=o,s++);}else if(e.startsWith("--cwd="))n.cwd=e.slice(6);else if(e==="--config"&&s+1<t.length){let o=t[s+1];o&&!o.startsWith("-")&&(n.configPath=o,s++);}else if(e.startsWith("--config="))n.configPath=e.slice(9);else if(e==="--log-level"&&s+1<t.length){let o=t[s+1];if(o&&!o.startsWith("-")){let l=o.toUpperCase();h.has(l)&&(n.logLevel=l,s++);}}else if(e.startsWith("--log-level=")){let o=e.slice(12).toUpperCase();h.has(o)&&(n.logLevel=o);}else e==="--print-logs"?n.printLogs=true:e==="--debug"&&(n.debug=true);}return n}async function W(){let t=process.argv.slice(2),n=S(),{loadEnv:s}=await import('@easbot/utils');s(),process.env.EASBOT_LANG||(process.env.EASBOT_LANG="en-US");let e=D(t),{Log:o}=await import('@easbot/utils'),{getXdgData:l}=await import('./chunks/interfaces-Q5OGU5EK.cjs'),w=path.join(l(),"memory","log");if(await o.init({logDir:w,print:e.printLogs,dev:e.debug||false,level:e.logLevel}),t.length===0){let{renderBanner:i}=await import('./chunks/cli-handler-PG4IBTY2.cjs');i();return}if(t[0]==="--help"||t[0]==="-h"){let{renderHelp:i}=await import('./chunks/cli-handler-PG4IBTY2.cjs');i();return}if(t[0]==="--version"||t[0]==="-v"){terminal.printHuman([terminal.formatInfo(n)]);return}let a=e.cwd??process.cwd(),{handleMemoryCli:L}=await import('./chunks/cli-handler-PG4IBTY2.cjs'),{setInstanceAdapter:b}=await import('./chunks/interfaces-Q5OGU5EK.cjs');b({directory:a,worktree:a});let{Llm:v}=await import('./chunks/llm-7LQGYSUE.cjs'),{bootstrapLlm:y,setAdapterRegistry:O}=await import('@easbot/llm'),{getGlobal:r,getInstance:g}=await import('./chunks/interfaces-Q5OGU5EK.cjs');O({config:void 0,instance:{getDirectory:()=>g().directory,getWorktree:()=>g().worktree},global:{home:r().Path.home,data:r().Path.data,cache:r().Path.cache,config:r().Path.config,state:r().Path.state,log:r().Path.log,bin:r().Path.bin},installation:{getVersion:()=>n,getChannel:()=>"local",getUserAgent:()=>`easbot-memory/${n}`}}),await y({target:v,cwd:a,subConfigPath:".easbot/memory.json",embedding:true,graph:true});let p=o.create({service:"memory-cli-standalone"}),c;try{let{readFileSync:i}=await import('fs'),{join:I}=await import('path'),f=I(a,".easbot","protocol.json"),P=i(f,"utf-8");c=JSON.parse(P)?.metadata?.agentId?.trim()||void 0,p.debug("standalone CLI: resolved hostAgentId from protocol.json",{hostAgentId:c,protocolPath:f});}catch(i){p.debug("standalone CLI: read protocol.json failed; hostAgentId stays undefined",{cwd:a,error:i instanceof Error?i.message:String(i)});}let d=await L(t,{version:n,cwd:a,agentId:c});d.code!==0&&(process.exitCode=d.code);}W().catch(t=>{console.error(t),process.exitCode=1;}).finally(async()=>{try{let{Log:t}=await import('@easbot/utils');await t.close();}catch{}process.exit(process.exitCode??0);});
package/dist/cli.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import {readFileSync}from'fs';import {dirname,join}from'path';import {fileURLToPath}from'url';import {printHuman,formatInfo}from'@easbot/terminal';var G=dirname(fileURLToPath(import.meta.url));function E(){try{let t=join(G,"..","package.json");return JSON.parse(readFileSync(t,"utf-8")).version??"0.0.0"}catch{return "0.0.0"}}var p=new Set(["DEBUG","INFO","WARN","ERROR"]);function A(t){let n={logLevel:"INFO",printLogs:false,debug:false};for(let i=0;i<t.length;i++){let e=t[i];if(e)if(e==="--cwd"&&i+1<t.length){let o=t[i+1];o&&!o.startsWith("-")&&(n.cwd=o,i++);}else if(e.startsWith("--cwd="))n.cwd=e.slice(6);else if(e==="--config"&&i+1<t.length){let o=t[i+1];o&&!o.startsWith("-")&&(n.configPath=o,i++);}else if(e.startsWith("--config="))n.configPath=e.slice(9);else if(e==="--log-level"&&i+1<t.length){let o=t[i+1];if(o&&!o.startsWith("-")){let r=o.toUpperCase();p.has(r)&&(n.logLevel=r,i++);}}else if(e.startsWith("--log-level=")){let o=e.slice(12).toUpperCase();p.has(o)&&(n.logLevel=o);}else e==="--print-logs"?n.printLogs=true:e==="--debug"&&(n.debug=true);}return n}async function N(){let t=process.argv.slice(2),n=E(),{loadEnv:i}=await import('@easbot/utils');i(),process.env.EASBOT_LANG||(process.env.EASBOT_LANG="en-US");let e=A(t),{Log:o}=await import('@easbot/utils'),{getXdgData:r}=await import('./chunks/interfaces-LPJU4KS3.mjs'),d=join(r(),"memory","log");if(await o.init({logDir:d,print:e.printLogs,dev:e.debug||false,level:e.logLevel}),t.length===0){let{renderBanner:l}=await import('./chunks/cli-handler-KTFW5CCH.mjs');l();return}if(t[0]==="--help"||t[0]==="-h"){let{renderHelp:l}=await import('./chunks/cli-handler-KTFW5CCH.mjs');l();return}if(t[0]==="--version"||t[0]==="-v"){printHuman([formatInfo(n)]);return}let a=e.cwd??process.cwd(),{handleMemoryCli:m}=await import('./chunks/cli-handler-KTFW5CCH.mjs'),{setInstanceAdapter:h}=await import('./chunks/interfaces-LPJU4KS3.mjs');h({directory:a,worktree:a});let{Llm:u}=await import('./chunks/llm-UHTBU2HA.mjs'),{bootstrapLlm:w,setAdapterRegistry:L}=await import('@easbot/llm'),{getGlobal:s,getInstance:c}=await import('./chunks/interfaces-LPJU4KS3.mjs');L({config:void 0,instance:{getDirectory:()=>c().directory,getWorktree:()=>c().worktree},global:{home:s().Path.home,data:s().Path.data,cache:s().Path.cache,config:s().Path.config,state:s().Path.state,log:s().Path.log,bin:s().Path.bin},installation:{getVersion:()=>n,getChannel:()=>"local",getUserAgent:()=>`easbot-memory/${n}`}}),await w({target:u,cwd:a,subConfigPath:".easbot/memory.json",embedding:true,graph:true});let g=await m(t,{version:n,cwd:a});g.code!==0&&(process.exitCode=g.code);}N().catch(t=>{console.error(t),process.exitCode=1;}).finally(async()=>{try{let{Log:t}=await import('@easbot/utils');await t.close();}catch{}process.exit(process.exitCode??0);});
2
+ import {readFileSync}from'fs';import {dirname,join}from'path';import {fileURLToPath}from'url';import {printHuman,formatInfo}from'@easbot/terminal';import'@easbot/utils';var C=dirname(fileURLToPath(import.meta.url));function R(){try{let t=join(C,"..","package.json");return JSON.parse(readFileSync(t,"utf-8")).version??"0.0.0"}catch{return "0.0.0"}}var m=new Set(["DEBUG","INFO","WARN","ERROR"]);function S(t){let n={logLevel:"INFO",printLogs:false,debug:false};for(let s=0;s<t.length;s++){let e=t[s];if(e)if(e==="--cwd"&&s+1<t.length){let o=t[s+1];o&&!o.startsWith("-")&&(n.cwd=o,s++);}else if(e.startsWith("--cwd="))n.cwd=e.slice(6);else if(e==="--config"&&s+1<t.length){let o=t[s+1];o&&!o.startsWith("-")&&(n.configPath=o,s++);}else if(e.startsWith("--config="))n.configPath=e.slice(9);else if(e==="--log-level"&&s+1<t.length){let o=t[s+1];if(o&&!o.startsWith("-")){let l=o.toUpperCase();m.has(l)&&(n.logLevel=l,s++);}}else if(e.startsWith("--log-level=")){let o=e.slice(12).toUpperCase();m.has(o)&&(n.logLevel=o);}else e==="--print-logs"?n.printLogs=true:e==="--debug"&&(n.debug=true);}return n}async function D(){let t=process.argv.slice(2),n=R(),{loadEnv:s}=await import('@easbot/utils');s(),process.env.EASBOT_LANG||(process.env.EASBOT_LANG="en-US");let e=S(t),{Log:o}=await import('@easbot/utils'),{getXdgData:l}=await import('./chunks/interfaces-LPJU4KS3.mjs'),u=join(l(),"memory","log");if(await o.init({logDir:u,print:e.printLogs,dev:e.debug||false,level:e.logLevel}),t.length===0){let{renderBanner:i}=await import('./chunks/cli-handler-ETHJPZPG.mjs');i();return}if(t[0]==="--help"||t[0]==="-h"){let{renderHelp:i}=await import('./chunks/cli-handler-ETHJPZPG.mjs');i();return}if(t[0]==="--version"||t[0]==="-v"){printHuman([formatInfo(n)]);return}let a=e.cwd??process.cwd(),{handleMemoryCli:w}=await import('./chunks/cli-handler-ETHJPZPG.mjs'),{setInstanceAdapter:L}=await import('./chunks/interfaces-LPJU4KS3.mjs');L({directory:a,worktree:a});let{Llm:b}=await import('./chunks/llm-UHTBU2HA.mjs'),{bootstrapLlm:v,setAdapterRegistry:y}=await import('@easbot/llm'),{getGlobal:r,getInstance:g}=await import('./chunks/interfaces-LPJU4KS3.mjs');y({config:void 0,instance:{getDirectory:()=>g().directory,getWorktree:()=>g().worktree},global:{home:r().Path.home,data:r().Path.data,cache:r().Path.cache,config:r().Path.config,state:r().Path.state,log:r().Path.log,bin:r().Path.bin},installation:{getVersion:()=>n,getChannel:()=>"local",getUserAgent:()=>`easbot-memory/${n}`}}),await v({target:b,cwd:a,subConfigPath:".easbot/memory.json",embedding:true,graph:true});let p=o.create({service:"memory-cli-standalone"}),c;try{let{readFileSync:i}=await import('fs'),{join:O}=await import('path'),f=O(a,".easbot","protocol.json"),I=i(f,"utf-8");c=JSON.parse(I)?.metadata?.agentId?.trim()||void 0,p.debug("standalone CLI: resolved hostAgentId from protocol.json",{hostAgentId:c,protocolPath:f});}catch(i){p.debug("standalone CLI: read protocol.json failed; hostAgentId stays undefined",{cwd:a,error:i instanceof Error?i.message:String(i)});}let d=await w(t,{version:n,cwd:a,agentId:c});d.code!==0&&(process.exitCode=d.code);}D().catch(t=>{console.error(t),process.exitCode=1;}).finally(async()=>{try{let{Log:t}=await import('@easbot/utils');await t.close();}catch{}process.exit(process.exitCode??0);});
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
- 'use strict';require('./chunks/chunk-URADAZYW.cjs');var chunk46Y7MLBE_cjs=require('./chunks/chunk-46Y7MLBE.cjs'),chunkMPGIP3IF_cjs=require('./chunks/chunk-MPGIP3IF.cjs'),chunk5VZKEZI4_cjs=require('./chunks/chunk-5VZKEZI4.cjs'),chunkLYBUZDJK_cjs=require('./chunks/chunk-LYBUZDJK.cjs'),chunkCPRDIUQ4_cjs=require('./chunks/chunk-CPRDIUQ4.cjs'),chunkJ5XF2W4Z_cjs=require('./chunks/chunk-J5XF2W4Z.cjs'),chunkM2YU5LAI_cjs=require('./chunks/chunk-M2YU5LAI.cjs'),types=require('@easbot/types'),d=require('jieba-wasm'),utils=require('@easbot/utils'),crypto=require('crypto');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var d__namespace=/*#__PURE__*/_interopNamespace(d);var Ae=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"],p=class extends Error{constructor(o,t,n){super(o,{cause:n});chunkM2YU5LAI_cjs.a(this,"code",t);chunkM2YU5LAI_cjs.a(this,"cause",n);this.name="MemoryError";}},N=class extends p{constructor(r,o){super(r,"MEMORY_VALIDATION_ERROR",o),this.name="MemoryValidationError";}},D=class extends p{constructor(r){super(`Memory not found: ${r}`,"MEMORY_NOT_FOUND"),this.name="MemoryNotFoundError";}},T=class extends p{constructor(r){super(r,"MEMORY_PERMISSION_ERROR"),this.name="MemoryPermissionError";}},v=class extends p{constructor(r,o){super(r,"MEMORY_DATABASE_ERROR",o),this.name="MemoryDatabaseError";}},F=class extends p{constructor(r,o){super(r,"MEMORY_FILE_ERROR",o),this.name="MemoryFileError";}},L=class extends p{constructor(r,o){super(r,"MEMORY_SEARCH_ERROR",o),this.name="MemorySearchError";}},$=class extends p{constructor(r,o){super(r,"MEMORY_EMBEDDING_ERROR",o),this.name="MemoryEmbeddingError";}},ue=(a=>(a.VALIDATION_ERROR="MEMORY_VALIDATION_ERROR",a.NOT_FOUND="MEMORY_NOT_FOUND",a.PERMISSION_ERROR="MEMORY_PERMISSION_ERROR",a.DATABASE_ERROR="MEMORY_DATABASE_ERROR",a.FILE_ERROR="MEMORY_FILE_ERROR",a.SEARCH_ERROR="MEMORY_SEARCH_ERROR",a.EMBEDDING_ERROR="MEMORY_EMBEDDING_ERROR",a))(ue||{});var s=utils.Log.create({service:"memory.tokenizer"}),l=false,Re=utils.loadTextFile("./assets/jieba_dict.txt",chunkM2YU5LAI_cjs.b);async function Le(e){if(!l)try{s.debug("Initializing jieba tokenizer");let r=Re();if(d__namespace.with_dict(r),s.debug("Built-in dictionary loaded"),e?.dictPath&&e.dictPath.length>0)for(let o of e.dictPath)await ke(o);l=!0,s.debug("Jieba tokenizer initialized successfully");}catch(r){s.error("Failed to initialize jieba tokenizer",{error:String(r)}),s.warn("Using fallback tokenization (space-based)");}}async function ke(e){if(!l)throw new Error("Tokenizer not initialized");try{let r=await utils.Filesystem.readText(e);s.debug("Loading custom dictionary",{dictPath:e}),d__namespace.with_dict(r),s.debug("Custom dictionary loaded successfully",{dictPath:e});}catch(r){s.warn("Failed to load custom dictionary",{dictPath:e,error:String(r)});}}function xe(e){if(!l)return e.split(/\s+/).filter(Boolean);try{return d__namespace.cut(e)}catch(r){return s.warn("Tokenization failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean)}}function He(e){if(!l)return e.split(/\s+/).filter(Boolean);try{return d__namespace.cut_for_search(e)}catch(r){return s.warn("Tokenization for search failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean)}}function $e(e,r,o){if(l)try{d__namespace.add_word(e,r,o),s.debug("Word added to dictionary",{word:e,freq:r,tag:o});}catch(t){s.warn("Failed to add word",{word:e,error:String(t)});}}function je(){return l}async function ze(){l=false,s.debug("Tokenizer closed");}function Ye(e){if(!l)return e.split(/\s+/).filter(Boolean).join(" ");try{return xe(e).join(" ")}catch(r){return s.warn("Tokenization failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function Be(e){if(!l)return e.split(/\s+/).filter(Boolean).join(" ");try{return He(e).join(" ")}catch(r){return s.warn("Tokenization for search failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function m(e){let r=chunkCPRDIUQ4_cjs.f().worktree,o=chunkCPRDIUQ4_cjs.j(r);return {agentId:e,isTrustedLocal:true,remote:false,locale:"en-US",dbPath:o,workspaceDir:r,rootDir:r,config:chunk5VZKEZI4_cjs.A({agentId:e,dbPath:o,workspaceDir:r})}}var j=async e=>{if(!e.agentId?.trim())return {ok:false,error:"session-start: agentId is required in ctx"};let r=e.extras?.topK??5,o=e.extras?.query??"";try{let t=await chunk5VZKEZI4_cjs.z("recall",{query:o,maxResults:r},m(e.agentId));if(t.hits.length===0)return {ok:!0,injected:"",logLine:"session-start: no facts found for agent; skipping context injection"};let n=t.hits.map(y=>`- [${y.category}/imp=${y.importance}] ${y.snippet.slice(0,200)}`);return {ok:!0,injected:`[memory:session-start recall top-${t.hits.length}]
1
+ 'use strict';require('./chunks/chunk-URADAZYW.cjs');var chunkDW3CJUBO_cjs=require('./chunks/chunk-DW3CJUBO.cjs'),chunkP45OBSAC_cjs=require('./chunks/chunk-P45OBSAC.cjs'),chunkHY2LFKG7_cjs=require('./chunks/chunk-HY2LFKG7.cjs'),chunkLYBUZDJK_cjs=require('./chunks/chunk-LYBUZDJK.cjs'),chunkCPRDIUQ4_cjs=require('./chunks/chunk-CPRDIUQ4.cjs'),chunkJ5XF2W4Z_cjs=require('./chunks/chunk-J5XF2W4Z.cjs'),chunkM2YU5LAI_cjs=require('./chunks/chunk-M2YU5LAI.cjs'),types=require('@easbot/types'),d=require('jieba-wasm'),utils=require('@easbot/utils'),crypto=require('crypto');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var d__namespace=/*#__PURE__*/_interopNamespace(d);var Ae=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"],p=class extends Error{constructor(o,t,n){super(o,{cause:n});chunkM2YU5LAI_cjs.a(this,"code",t);chunkM2YU5LAI_cjs.a(this,"cause",n);this.name="MemoryError";}},N=class extends p{constructor(r,o){super(r,"MEMORY_VALIDATION_ERROR",o),this.name="MemoryValidationError";}},D=class extends p{constructor(r){super(`Memory not found: ${r}`,"MEMORY_NOT_FOUND"),this.name="MemoryNotFoundError";}},T=class extends p{constructor(r){super(r,"MEMORY_PERMISSION_ERROR"),this.name="MemoryPermissionError";}},v=class extends p{constructor(r,o){super(r,"MEMORY_DATABASE_ERROR",o),this.name="MemoryDatabaseError";}},F=class extends p{constructor(r,o){super(r,"MEMORY_FILE_ERROR",o),this.name="MemoryFileError";}},L=class extends p{constructor(r,o){super(r,"MEMORY_SEARCH_ERROR",o),this.name="MemorySearchError";}},$=class extends p{constructor(r,o){super(r,"MEMORY_EMBEDDING_ERROR",o),this.name="MemoryEmbeddingError";}},ue=(a=>(a.VALIDATION_ERROR="MEMORY_VALIDATION_ERROR",a.NOT_FOUND="MEMORY_NOT_FOUND",a.PERMISSION_ERROR="MEMORY_PERMISSION_ERROR",a.DATABASE_ERROR="MEMORY_DATABASE_ERROR",a.FILE_ERROR="MEMORY_FILE_ERROR",a.SEARCH_ERROR="MEMORY_SEARCH_ERROR",a.EMBEDDING_ERROR="MEMORY_EMBEDDING_ERROR",a))(ue||{});var s=utils.Log.create({service:"memory.tokenizer"}),l=false,Re=utils.loadTextFile("./assets/jieba_dict.txt",chunkM2YU5LAI_cjs.b);async function Le(e){if(!l)try{s.debug("Initializing jieba tokenizer");let r=Re();if(d__namespace.with_dict(r),s.debug("Built-in dictionary loaded"),e?.dictPath&&e.dictPath.length>0)for(let o of e.dictPath)await ke(o);l=!0,s.debug("Jieba tokenizer initialized successfully");}catch(r){s.error("Failed to initialize jieba tokenizer",{error:String(r)}),s.warn("Using fallback tokenization (space-based)");}}async function ke(e){if(!l)throw new Error("Tokenizer not initialized");try{let r=await utils.Filesystem.readText(e);s.debug("Loading custom dictionary",{dictPath:e}),d__namespace.with_dict(r),s.debug("Custom dictionary loaded successfully",{dictPath:e});}catch(r){s.warn("Failed to load custom dictionary",{dictPath:e,error:String(r)});}}function xe(e){if(!l)return e.split(/\s+/).filter(Boolean);try{return d__namespace.cut(e)}catch(r){return s.warn("Tokenization failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean)}}function He(e){if(!l)return e.split(/\s+/).filter(Boolean);try{return d__namespace.cut_for_search(e)}catch(r){return s.warn("Tokenization for search failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean)}}function $e(e,r,o){if(l)try{d__namespace.add_word(e,r,o),s.debug("Word added to dictionary",{word:e,freq:r,tag:o});}catch(t){s.warn("Failed to add word",{word:e,error:String(t)});}}function je(){return l}async function ze(){l=false,s.debug("Tokenizer closed");}function Ye(e){if(!l)return e.split(/\s+/).filter(Boolean).join(" ");try{return xe(e).join(" ")}catch(r){return s.warn("Tokenization failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function Be(e){if(!l)return e.split(/\s+/).filter(Boolean).join(" ");try{return He(e).join(" ")}catch(r){return s.warn("Tokenization for search failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function m(e){let r=chunkCPRDIUQ4_cjs.f().worktree,o=chunkCPRDIUQ4_cjs.j(r);return {agentId:e,isTrustedLocal:true,remote:false,locale:"en-US",dbPath:o,workspaceDir:r,rootDir:r,config:chunkHY2LFKG7_cjs.A({agentId:e,dbPath:o,workspaceDir:r})}}var j=async e=>{if(!e.agentId?.trim())return {ok:false,error:"session-start: agentId is required in ctx"};let r=e.extras?.topK??5,o=e.extras?.query??"";try{let t=await chunkHY2LFKG7_cjs.z("recall",{query:o,maxResults:r},m(e.agentId));if(t.hits.length===0)return {ok:!0,injected:"",logLine:"session-start: no facts found for agent; skipping context injection"};let n=t.hits.map(y=>`- [${y.category}/imp=${y.importance}] ${y.snippet.slice(0,200)}`);return {ok:!0,injected:`[memory:session-start recall top-${t.hits.length}]
2
2
  ${n.join(`
3
- `)}`,logLine:`session-start: injected ${t.hits.length} facts into context (agent=${e.agentId})`}}catch(t){return {ok:false,error:t instanceof Error?t.message:String(t)}}};var he=3600*1e3,z=async e=>{if(!e.agentId?.trim())return {ok:false,error:"session-end: agentId is required in ctx"};let r=typeof e.extras?.lookbackMs=="number"&&e.extras.lookbackMs>0?e.extras.lookbackMs:he,o=e.extras?.fromTime??new Date(Date.now()-r).toISOString();try{let t=await chunk5VZKEZI4_cjs.z("consolidate",{fromTime:o},m(e.agentId));return {ok:!0,logLine:`session-end: lookback=${r}ms, total=${t.totalFacts}, deduped=${t.dedupedCount}, archived=${t.archivedCount}, skipped=${t.skippedCount}`}}catch(t){return {ok:false,error:t instanceof Error?t.message:String(t)}}};var Y=async e=>{if(!e.agentId?.trim())return {ok:false,error:"pre-compact: agentId is required in ctx"};let o=(e.contextPreview??e.messagePreview??"").slice(0,200).replace(/\s+/g," ").trim(),t=e.extras?.topK??3;if(!o)return {ok:true,injected:"",logLine:"pre-compact: empty contextPreview; skipping recall injection"};try{let n=await chunk5VZKEZI4_cjs.z("recall",{query:o,maxResults:t,minImportance:5},m(e.agentId));if(n.hits.length===0)return {ok:!0,injected:"",logLine:`pre-compact: no facts matched query for agent=${e.agentId}`};let H=n.hits.map(a=>`- [${a.category}/imp=${a.importance}] ${a.snippet.slice(0,150)}`);return {ok:!0,injected:`[memory:pre-compact recall top-${n.hits.length} (imp>=5)]
3
+ `)}`,logLine:`session-start: injected ${t.hits.length} facts into context (agent=${e.agentId})`}}catch(t){return {ok:false,error:t instanceof Error?t.message:String(t)}}};var he=3600*1e3,z=async e=>{if(!e.agentId?.trim())return {ok:false,error:"session-end: agentId is required in ctx"};let r=typeof e.extras?.lookbackMs=="number"&&e.extras.lookbackMs>0?e.extras.lookbackMs:he,o=e.extras?.fromTime??new Date(Date.now()-r).toISOString();try{let t=await chunkHY2LFKG7_cjs.z("consolidate",{fromTime:o},m(e.agentId));return {ok:!0,logLine:`session-end: lookback=${r}ms, total=${t.totalFacts}, deduped=${t.dedupedCount}, archived=${t.archivedCount}, skipped=${t.skippedCount}`}}catch(t){return {ok:false,error:t instanceof Error?t.message:String(t)}}};var Y=async e=>{if(!e.agentId?.trim())return {ok:false,error:"pre-compact: agentId is required in ctx"};let o=(e.contextPreview??e.messagePreview??"").slice(0,200).replace(/\s+/g," ").trim(),t=e.extras?.topK??3;if(!o)return {ok:true,injected:"",logLine:"pre-compact: empty contextPreview; skipping recall injection"};try{let n=await chunkHY2LFKG7_cjs.z("recall",{query:o,maxResults:t,minImportance:5},m(e.agentId));if(n.hits.length===0)return {ok:!0,injected:"",logLine:`pre-compact: no facts matched query for agent=${e.agentId}`};let H=n.hits.map(a=>`- [${a.category}/imp=${a.importance}] ${a.snippet.slice(0,150)}`);return {ok:!0,injected:`[memory:pre-compact recall top-${n.hits.length} (imp>=5)]
4
4
  ${H.join(`
5
5
  `)}`,logLine:`pre-compact: injected ${n.hits.length} facts before compaction`}}catch(n){return {ok:false,error:n instanceof Error?n.message:String(n)}}};var B=async e=>{if(!e.agentId?.trim())return {ok:false,error:"post-tool-failure: agentId is required in ctx"};if(!e.toolName?.trim()||!e.error?.trim())return {ok:false,error:"post-tool-failure: toolName and error are required in ctx"};let r=crypto.createHash("sha256").update(`${e.toolName}:${e.error}`).digest("hex").slice(0,8),o=e.messagePreview?e.messagePreview.slice(0,200).replace(/\s+/g," ").trim():"",t=[`[error_pattern] tool=${e.toolName}`,`[error] ${e.error}`,o?`[preview] ${o}`:"",`[errHash] ${r}`].filter(Boolean).join(`
6
- `);try{return {ok:!0,logLine:`post-tool-failure: wrote error_pattern fact ${(await chunk5VZKEZI4_cjs.z("remember",{content:t,category:"error_pattern",importance:6,tags:["post-tool-failure",`tool:${e.toolName}`,`err:${r}`],sessionId:e.sessionId,msgId:e.extras?.msgId},m(e.agentId))).fact.id} (tool=${e.toolName}, errHash=${r})`}}catch(n){return {ok:false,error:n instanceof Error?n.message:String(n)}}};var u=utils.Log.create({service:"memory.hooks"}),g=new Map;function f(e,r){let o={name:e,handler:r,registeredAt:new Date().toISOString()},t=g.get(e);g.set(e,o),t?u.info("Hook overwritten",{name:e,prevRegisteredAt:t.registeredAt,newRegisteredAt:o.registeredAt}):u.info("Hook registered",{name:e,registeredAt:o.registeredAt});}function Ie(e){return g.delete(e)}function Me(){return Array.from(g.values()).map(e=>({name:e.name,handler:e.handler,registeredAt:e.registeredAt}))}function _e(){f("session-start",j),f("session-end",z),f("pre-compact",Y),f("post-tool-failure",B);}function Se(){g.clear(),u.debug("All hooks cleared");}async function Oe(e,r){let o=g.get(e);if(!o)return u.debug("dispatchHook: no handler registered; noop",{name:e}),{ok:true,logLine:`hook ${e} not registered; noop`};try{let t=await o.handler(r);return t.ok?t.logLine&&u.debug("dispatchHook: ok",{name:e,logLine:t.logLine}):u.warn("dispatchHook: handler returned failure",{name:e,agentId:r.agentId,error:t.error}),t}catch(t){let n=t instanceof Error?t.message:String(t);return u.warn("dispatchHook: handler threw, caught and converted to failure result",{name:e,agentId:r.agentId,error:n}),{ok:false,error:n}}}Object.defineProperty(exports,"COMMANDS_HELP",{enumerable:true,get:function(){return chunk46Y7MLBE_cjs.a}});Object.defineProperty(exports,"handleMemoryCli",{enumerable:true,get:function(){return chunk46Y7MLBE_cjs.d}});Object.defineProperty(exports,"renderBanner",{enumerable:true,get:function(){return chunk46Y7MLBE_cjs.b}});Object.defineProperty(exports,"renderHelp",{enumerable:true,get:function(){return chunk46Y7MLBE_cjs.c}});Object.defineProperty(exports,"MemoryStdioServer",{enumerable:true,get:function(){return chunkMPGIP3IF_cjs.b}});Object.defineProperty(exports,"renderOperationMarkdown",{enumerable:true,get:function(){return chunkMPGIP3IF_cjs.a}});Object.defineProperty(exports,"ALL_OPS",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.y}});Object.defineProperty(exports,"GraphStore",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.a}});Object.defineProperty(exports,"OP_REGISTRY",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.x}});Object.defineProperty(exports,"consolidate",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.r}});Object.defineProperty(exports,"doctor",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.w}});Object.defineProperty(exports,"executeOp",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.z}});Object.defineProperty(exports,"extract",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.q}});Object.defineProperty(exports,"forget",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.p}});Object.defineProperty(exports,"graphQuery",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.t}});Object.defineProperty(exports,"init",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.u}});Object.defineProperty(exports,"recall",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.b}});Object.defineProperty(exports,"remember",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.n}});Object.defineProperty(exports,"status",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.v}});Object.defineProperty(exports,"sync",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.s}});Object.defineProperty(exports,"update",{enumerable:true,get:function(){return chunk5VZKEZI4_cjs.o}});Object.defineProperty(exports,"LATEST_SCHEMA_VERSION",{enumerable:true,get:function(){return chunkLYBUZDJK_cjs.a}});Object.defineProperty(exports,"MIGRATIONS",{enumerable:true,get:function(){return chunkLYBUZDJK_cjs.b}});Object.defineProperty(exports,"MemoryDatabaseManager",{enumerable:true,get:function(){return chunkLYBUZDJK_cjs.e}});Object.defineProperty(exports,"readCurrentSchemaVersion",{enumerable:true,get:function(){return chunkLYBUZDJK_cjs.d}});Object.defineProperty(exports,"runMigrations",{enumerable:true,get:function(){return chunkLYBUZDJK_cjs.c}});Object.defineProperty(exports,"getGlobal",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.c}});Object.defineProperty(exports,"getHomeDir",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.g}});Object.defineProperty(exports,"getInstance",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.f}});Object.defineProperty(exports,"getMemoryDbPath",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.j}});Object.defineProperty(exports,"getMemoryDir",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.i}});Object.defineProperty(exports,"getXdgData",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.h}});Object.defineProperty(exports,"resetGlobalAdapter",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.b}});Object.defineProperty(exports,"resetInstanceAdapter",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.e}});Object.defineProperty(exports,"setGlobalAdapter",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.a}});Object.defineProperty(exports,"setInstanceAdapter",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.d}});Object.defineProperty(exports,"Llm",{enumerable:true,get:function(){return chunkJ5XF2W4Z_cjs.a}});Object.defineProperty(exports,"GRAPH_ENTITY_TYPE_DEFINITIONS",{enumerable:true,get:function(){return types.GRAPH_ENTITY_TYPE_DEFINITIONS}});Object.defineProperty(exports,"GRAPH_RELATION_TYPE_DEFINITIONS",{enumerable:true,get:function(){return types.GRAPH_RELATION_TYPE_DEFINITIONS}});exports.MEMORY_CATEGORIES=Ae;exports.MemoryDatabaseError=v;exports.MemoryEmbeddingError=$;exports.MemoryError=p;exports.MemoryErrorCode=ue;exports.MemoryFileError=F;exports.MemoryNotFoundError=D;exports.MemoryPermissionError=T;exports.MemorySearchError=L;exports.MemoryValidationError=N;exports.addWord=$e;exports.clearAllHooks=Se;exports.closeTokenizer=ze;exports.dispatchHook=Oe;exports.initTokenizer=Le;exports.isInitialized=je;exports.listHooks=Me;exports.loadCustomDict=ke;exports.registerAllDefaultHooks=_e;exports.registerHook=f;exports.toFtsTokens=Ye;exports.toFtsTokensForSearch=Be;exports.tokenize=xe;exports.tokenizeForSearch=He;exports.unregisterHook=Ie;
6
+ `);try{return {ok:!0,logLine:`post-tool-failure: wrote error_pattern fact ${(await chunkHY2LFKG7_cjs.z("remember",{content:t,category:"error_pattern",importance:6,tags:["post-tool-failure",`tool:${e.toolName}`,`err:${r}`],sessionId:e.sessionId,msgId:e.extras?.msgId},m(e.agentId))).fact.id} (tool=${e.toolName}, errHash=${r})`}}catch(n){return {ok:false,error:n instanceof Error?n.message:String(n)}}};var u=utils.Log.create({service:"memory.hooks"}),g=new Map;function f(e,r){let o={name:e,handler:r,registeredAt:new Date().toISOString()},t=g.get(e);g.set(e,o),t?u.info("Hook overwritten",{name:e,prevRegisteredAt:t.registeredAt,newRegisteredAt:o.registeredAt}):u.info("Hook registered",{name:e,registeredAt:o.registeredAt});}function Ie(e){return g.delete(e)}function Me(){return Array.from(g.values()).map(e=>({name:e.name,handler:e.handler,registeredAt:e.registeredAt}))}function _e(){f("session-start",j),f("session-end",z),f("pre-compact",Y),f("post-tool-failure",B);}function Se(){g.clear(),u.debug("All hooks cleared");}async function Oe(e,r){let o=g.get(e);if(!o)return u.debug("dispatchHook: no handler registered; noop",{name:e}),{ok:true,logLine:`hook ${e} not registered; noop`};try{let t=await o.handler(r);return t.ok?t.logLine&&u.debug("dispatchHook: ok",{name:e,logLine:t.logLine}):u.warn("dispatchHook: handler returned failure",{name:e,agentId:r.agentId,error:t.error}),t}catch(t){let n=t instanceof Error?t.message:String(t);return u.warn("dispatchHook: handler threw, caught and converted to failure result",{name:e,agentId:r.agentId,error:n}),{ok:false,error:n}}}Object.defineProperty(exports,"COMMANDS_HELP",{enumerable:true,get:function(){return chunkDW3CJUBO_cjs.a}});Object.defineProperty(exports,"handleMemoryCli",{enumerable:true,get:function(){return chunkDW3CJUBO_cjs.d}});Object.defineProperty(exports,"renderBanner",{enumerable:true,get:function(){return chunkDW3CJUBO_cjs.b}});Object.defineProperty(exports,"renderHelp",{enumerable:true,get:function(){return chunkDW3CJUBO_cjs.c}});Object.defineProperty(exports,"MemoryStdioServer",{enumerable:true,get:function(){return chunkP45OBSAC_cjs.b}});Object.defineProperty(exports,"renderOperationMarkdown",{enumerable:true,get:function(){return chunkP45OBSAC_cjs.a}});Object.defineProperty(exports,"ALL_OPS",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.y}});Object.defineProperty(exports,"GraphStore",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.a}});Object.defineProperty(exports,"OP_REGISTRY",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.x}});Object.defineProperty(exports,"consolidate",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.r}});Object.defineProperty(exports,"doctor",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.w}});Object.defineProperty(exports,"executeOp",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.z}});Object.defineProperty(exports,"extract",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.q}});Object.defineProperty(exports,"forget",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.p}});Object.defineProperty(exports,"graphQuery",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.t}});Object.defineProperty(exports,"init",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.u}});Object.defineProperty(exports,"recall",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.b}});Object.defineProperty(exports,"remember",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.n}});Object.defineProperty(exports,"status",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.v}});Object.defineProperty(exports,"sync",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.s}});Object.defineProperty(exports,"update",{enumerable:true,get:function(){return chunkHY2LFKG7_cjs.o}});Object.defineProperty(exports,"LATEST_SCHEMA_VERSION",{enumerable:true,get:function(){return chunkLYBUZDJK_cjs.a}});Object.defineProperty(exports,"MIGRATIONS",{enumerable:true,get:function(){return chunkLYBUZDJK_cjs.b}});Object.defineProperty(exports,"MemoryDatabaseManager",{enumerable:true,get:function(){return chunkLYBUZDJK_cjs.e}});Object.defineProperty(exports,"readCurrentSchemaVersion",{enumerable:true,get:function(){return chunkLYBUZDJK_cjs.d}});Object.defineProperty(exports,"runMigrations",{enumerable:true,get:function(){return chunkLYBUZDJK_cjs.c}});Object.defineProperty(exports,"getGlobal",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.c}});Object.defineProperty(exports,"getHomeDir",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.g}});Object.defineProperty(exports,"getInstance",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.f}});Object.defineProperty(exports,"getMemoryDbPath",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.j}});Object.defineProperty(exports,"getMemoryDir",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.i}});Object.defineProperty(exports,"getXdgData",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.h}});Object.defineProperty(exports,"resetGlobalAdapter",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.b}});Object.defineProperty(exports,"resetInstanceAdapter",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.e}});Object.defineProperty(exports,"setGlobalAdapter",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.a}});Object.defineProperty(exports,"setInstanceAdapter",{enumerable:true,get:function(){return chunkCPRDIUQ4_cjs.d}});Object.defineProperty(exports,"Llm",{enumerable:true,get:function(){return chunkJ5XF2W4Z_cjs.a}});Object.defineProperty(exports,"GRAPH_ENTITY_TYPE_DEFINITIONS",{enumerable:true,get:function(){return types.GRAPH_ENTITY_TYPE_DEFINITIONS}});Object.defineProperty(exports,"GRAPH_RELATION_TYPE_DEFINITIONS",{enumerable:true,get:function(){return types.GRAPH_RELATION_TYPE_DEFINITIONS}});exports.MEMORY_CATEGORIES=Ae;exports.MemoryDatabaseError=v;exports.MemoryEmbeddingError=$;exports.MemoryError=p;exports.MemoryErrorCode=ue;exports.MemoryFileError=F;exports.MemoryNotFoundError=D;exports.MemoryPermissionError=T;exports.MemorySearchError=L;exports.MemoryValidationError=N;exports.addWord=$e;exports.clearAllHooks=Se;exports.closeTokenizer=ze;exports.dispatchHook=Oe;exports.initTokenizer=Le;exports.isInitialized=je;exports.listHooks=Me;exports.loadCustomDict=ke;exports.registerAllDefaultHooks=_e;exports.registerHook=f;exports.toFtsTokens=Ye;exports.toFtsTokensForSearch=Be;exports.tokenize=xe;exports.tokenizeForSearch=He;exports.unregisterHook=Ie;
package/dist/index.d.cts CHANGED
@@ -209,7 +209,7 @@ interface RecallParams {
209
209
  maxResults?: number;
210
210
  minScore?: number;
211
211
  includeGraph?: boolean;
212
- depth?: number;
212
+ maxDepth?: number;
213
213
  maxEdgesPerNode?: number;
214
214
  includeShared?: boolean;
215
215
  }
@@ -315,7 +315,7 @@ interface GraphQueryParams {
315
315
  nodeId?: number;
316
316
  query?: string;
317
317
  type?: string;
318
- depth?: number;
318
+ maxDepth?: number;
319
319
  maxNodes?: number;
320
320
  maxEdgesPerNode?: number;
321
321
  scope?: KGScope;
@@ -338,6 +338,8 @@ interface StatusResult extends MemoryStatus {
338
338
  edgesCount: number;
339
339
  factsByCategory: Record<MemoryCategory, number>;
340
340
  ftsAvailable: boolean;
341
+ dbExists: boolean;
342
+ integrityStats?: Record<string, number>;
341
343
  }
342
344
  type DoctorParams = {};
343
345
  interface DoctorResult extends KnowledgeDoctorResult {
@@ -498,6 +500,7 @@ interface MemoryCliDeps {
498
500
  version: string;
499
501
  cwd?: string;
500
502
  locale?: string;
503
+ agentId?: string;
501
504
  }
502
505
  interface MemoryCliResult {
503
506
  code: number;
package/dist/index.d.ts CHANGED
@@ -209,7 +209,7 @@ interface RecallParams {
209
209
  maxResults?: number;
210
210
  minScore?: number;
211
211
  includeGraph?: boolean;
212
- depth?: number;
212
+ maxDepth?: number;
213
213
  maxEdgesPerNode?: number;
214
214
  includeShared?: boolean;
215
215
  }
@@ -315,7 +315,7 @@ interface GraphQueryParams {
315
315
  nodeId?: number;
316
316
  query?: string;
317
317
  type?: string;
318
- depth?: number;
318
+ maxDepth?: number;
319
319
  maxNodes?: number;
320
320
  maxEdgesPerNode?: number;
321
321
  scope?: KGScope;
@@ -338,6 +338,8 @@ interface StatusResult extends MemoryStatus {
338
338
  edgesCount: number;
339
339
  factsByCategory: Record<MemoryCategory, number>;
340
340
  ftsAvailable: boolean;
341
+ dbExists: boolean;
342
+ integrityStats?: Record<string, number>;
341
343
  }
342
344
  type DoctorParams = {};
343
345
  interface DoctorResult extends KnowledgeDoctorResult {
@@ -498,6 +500,7 @@ interface MemoryCliDeps {
498
500
  version: string;
499
501
  cwd?: string;
500
502
  locale?: string;
503
+ agentId?: string;
501
504
  }
502
505
  interface MemoryCliResult {
503
506
  code: number;
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import'./chunks/chunk-QF5S5MG7.mjs';export{a as COMMANDS_HELP,d as handleMemoryCli,b as renderBanner,c as renderHelp}from'./chunks/chunk-PGJB2U24.mjs';export{b as MemoryStdioServer,a as renderOperationMarkdown}from'./chunks/chunk-GL5U3MRI.mjs';import {z as z$1,A}from'./chunks/chunk-C3Z455VR.mjs';export{y as ALL_OPS,a as GraphStore,x as OP_REGISTRY,r as consolidate,w as doctor,z as executeOp,q as extract,p as forget,t as graphQuery,u as init,b as recall,n as remember,v as status,s as sync,o as update}from'./chunks/chunk-C3Z455VR.mjs';export{a as LATEST_SCHEMA_VERSION,b as MIGRATIONS,e as MemoryDatabaseManager,d as readCurrentSchemaVersion,c as runMigrations}from'./chunks/chunk-FY4ILCIM.mjs';import {f as f$1,j as j$1}from'./chunks/chunk-WDVDYZ25.mjs';export{c as getGlobal,g as getHomeDir,f as getInstance,j as getMemoryDbPath,i as getMemoryDir,h as getXdgData,b as resetGlobalAdapter,e as resetInstanceAdapter,a as setGlobalAdapter,d as setInstanceAdapter}from'./chunks/chunk-WDVDYZ25.mjs';export{a as Llm}from'./chunks/chunk-6CQMBEIQ.mjs';import {a}from'./chunks/chunk-HQBRVVXS.mjs';export{GRAPH_ENTITY_TYPE_DEFINITIONS,GRAPH_RELATION_TYPE_DEFINITIONS}from'@easbot/types';import*as m from'jieba-wasm';import {Log,loadTextFile,Filesystem}from'@easbot/utils';import {createHash}from'crypto';var we=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"],d=class extends Error{constructor(o,t,n){super(o,{cause:n});a(this,"code",t);a(this,"cause",n);this.name="MemoryError";}},D=class extends d{constructor(r,o){super(r,"MEMORY_VALIDATION_ERROR",o),this.name="MemoryValidationError";}},T=class extends d{constructor(r){super(`Memory not found: ${r}`,"MEMORY_NOT_FOUND"),this.name="MemoryNotFoundError";}},v=class extends d{constructor(r){super(r,"MEMORY_PERMISSION_ERROR"),this.name="MemoryPermissionError";}},F=class extends d{constructor(r,o){super(r,"MEMORY_DATABASE_ERROR",o),this.name="MemoryDatabaseError";}},L=class extends d{constructor(r,o){super(r,"MEMORY_FILE_ERROR",o),this.name="MemoryFileError";}},$=class extends d{constructor(r,o){super(r,"MEMORY_SEARCH_ERROR",o),this.name="MemorySearchError";}},j=class extends d{constructor(r,o){super(r,"MEMORY_EMBEDDING_ERROR",o),this.name="MemoryEmbeddingError";}},ge=(i=>(i.VALIDATION_ERROR="MEMORY_VALIDATION_ERROR",i.NOT_FOUND="MEMORY_NOT_FOUND",i.PERMISSION_ERROR="MEMORY_PERMISSION_ERROR",i.DATABASE_ERROR="MEMORY_DATABASE_ERROR",i.FILE_ERROR="MEMORY_FILE_ERROR",i.SEARCH_ERROR="MEMORY_SEARCH_ERROR",i.EMBEDDING_ERROR="MEMORY_EMBEDDING_ERROR",i))(ge||{});var s=Log.create({service:"memory.tokenizer"}),c=false,ke=loadTextFile("./assets/jieba_dict.txt",import.meta.url);async function $e(e){if(!c)try{s.debug("Initializing jieba tokenizer");let r=ke();if(m.with_dict(r),s.debug("Built-in dictionary loaded"),e?.dictPath&&e.dictPath.length>0)for(let o of e.dictPath)await xe(o);c=!0,s.debug("Jieba tokenizer initialized successfully");}catch(r){s.error("Failed to initialize jieba tokenizer",{error:String(r)}),s.warn("Using fallback tokenization (space-based)");}}async function xe(e){if(!c)throw new Error("Tokenizer not initialized");try{let r=await Filesystem.readText(e);s.debug("Loading custom dictionary",{dictPath:e}),m.with_dict(r),s.debug("Custom dictionary loaded successfully",{dictPath:e});}catch(r){s.warn("Failed to load custom dictionary",{dictPath:e,error:String(r)});}}function He(e){if(!c)return e.split(/\s+/).filter(Boolean);try{return m.cut(e)}catch(r){return s.warn("Tokenization failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean)}}function he(e){if(!c)return e.split(/\s+/).filter(Boolean);try{return m.cut_for_search(e)}catch(r){return s.warn("Tokenization for search failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean)}}function je(e,r,o){if(c)try{m.add_word(e,r,o),s.debug("Word added to dictionary",{word:e,freq:r,tag:o});}catch(t){s.warn("Failed to add word",{word:e,error:String(t)});}}function ze(){return c}async function Ye(){c=false,s.debug("Tokenizer closed");}function Be(e){if(!c)return e.split(/\s+/).filter(Boolean).join(" ");try{return He(e).join(" ")}catch(r){return s.warn("Tokenization failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function Ge(e){if(!c)return e.split(/\s+/).filter(Boolean).join(" ");try{return he(e).join(" ")}catch(r){return s.warn("Tokenization for search failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function u(e){let r=f$1().worktree,o=j$1(r);return {agentId:e,isTrustedLocal:true,remote:false,locale:"en-US",dbPath:o,workspaceDir:r,rootDir:r,config:A({agentId:e,dbPath:o,workspaceDir:r})}}var z=async e=>{if(!e.agentId?.trim())return {ok:false,error:"session-start: agentId is required in ctx"};let r=e.extras?.topK??5,o=e.extras?.query??"";try{let t=await z$1("recall",{query:o,maxResults:r},u(e.agentId));if(t.hits.length===0)return {ok:!0,injected:"",logLine:"session-start: no facts found for agent; skipping context injection"};let n=t.hits.map(R=>`- [${R.category}/imp=${R.importance}] ${R.snippet.slice(0,200)}`);return {ok:!0,injected:`[memory:session-start recall top-${t.hits.length}]
1
+ import'./chunks/chunk-QF5S5MG7.mjs';export{a as COMMANDS_HELP,d as handleMemoryCli,b as renderBanner,c as renderHelp}from'./chunks/chunk-4YADRVIU.mjs';export{b as MemoryStdioServer,a as renderOperationMarkdown}from'./chunks/chunk-I5YSX4DQ.mjs';import {z as z$1,A}from'./chunks/chunk-X7P7ZFZF.mjs';export{y as ALL_OPS,a as GraphStore,x as OP_REGISTRY,r as consolidate,w as doctor,z as executeOp,q as extract,p as forget,t as graphQuery,u as init,b as recall,n as remember,v as status,s as sync,o as update}from'./chunks/chunk-X7P7ZFZF.mjs';export{a as LATEST_SCHEMA_VERSION,b as MIGRATIONS,e as MemoryDatabaseManager,d as readCurrentSchemaVersion,c as runMigrations}from'./chunks/chunk-FY4ILCIM.mjs';import {f as f$1,j as j$1}from'./chunks/chunk-WDVDYZ25.mjs';export{c as getGlobal,g as getHomeDir,f as getInstance,j as getMemoryDbPath,i as getMemoryDir,h as getXdgData,b as resetGlobalAdapter,e as resetInstanceAdapter,a as setGlobalAdapter,d as setInstanceAdapter}from'./chunks/chunk-WDVDYZ25.mjs';export{a as Llm}from'./chunks/chunk-6CQMBEIQ.mjs';import {a}from'./chunks/chunk-HQBRVVXS.mjs';export{GRAPH_ENTITY_TYPE_DEFINITIONS,GRAPH_RELATION_TYPE_DEFINITIONS}from'@easbot/types';import*as m from'jieba-wasm';import {Log,loadTextFile,Filesystem}from'@easbot/utils';import {createHash}from'crypto';var we=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"],d=class extends Error{constructor(o,t,n){super(o,{cause:n});a(this,"code",t);a(this,"cause",n);this.name="MemoryError";}},D=class extends d{constructor(r,o){super(r,"MEMORY_VALIDATION_ERROR",o),this.name="MemoryValidationError";}},T=class extends d{constructor(r){super(`Memory not found: ${r}`,"MEMORY_NOT_FOUND"),this.name="MemoryNotFoundError";}},v=class extends d{constructor(r){super(r,"MEMORY_PERMISSION_ERROR"),this.name="MemoryPermissionError";}},F=class extends d{constructor(r,o){super(r,"MEMORY_DATABASE_ERROR",o),this.name="MemoryDatabaseError";}},L=class extends d{constructor(r,o){super(r,"MEMORY_FILE_ERROR",o),this.name="MemoryFileError";}},$=class extends d{constructor(r,o){super(r,"MEMORY_SEARCH_ERROR",o),this.name="MemorySearchError";}},j=class extends d{constructor(r,o){super(r,"MEMORY_EMBEDDING_ERROR",o),this.name="MemoryEmbeddingError";}},ge=(i=>(i.VALIDATION_ERROR="MEMORY_VALIDATION_ERROR",i.NOT_FOUND="MEMORY_NOT_FOUND",i.PERMISSION_ERROR="MEMORY_PERMISSION_ERROR",i.DATABASE_ERROR="MEMORY_DATABASE_ERROR",i.FILE_ERROR="MEMORY_FILE_ERROR",i.SEARCH_ERROR="MEMORY_SEARCH_ERROR",i.EMBEDDING_ERROR="MEMORY_EMBEDDING_ERROR",i))(ge||{});var s=Log.create({service:"memory.tokenizer"}),c=false,ke=loadTextFile("./assets/jieba_dict.txt",import.meta.url);async function $e(e){if(!c)try{s.debug("Initializing jieba tokenizer");let r=ke();if(m.with_dict(r),s.debug("Built-in dictionary loaded"),e?.dictPath&&e.dictPath.length>0)for(let o of e.dictPath)await xe(o);c=!0,s.debug("Jieba tokenizer initialized successfully");}catch(r){s.error("Failed to initialize jieba tokenizer",{error:String(r)}),s.warn("Using fallback tokenization (space-based)");}}async function xe(e){if(!c)throw new Error("Tokenizer not initialized");try{let r=await Filesystem.readText(e);s.debug("Loading custom dictionary",{dictPath:e}),m.with_dict(r),s.debug("Custom dictionary loaded successfully",{dictPath:e});}catch(r){s.warn("Failed to load custom dictionary",{dictPath:e,error:String(r)});}}function He(e){if(!c)return e.split(/\s+/).filter(Boolean);try{return m.cut(e)}catch(r){return s.warn("Tokenization failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean)}}function he(e){if(!c)return e.split(/\s+/).filter(Boolean);try{return m.cut_for_search(e)}catch(r){return s.warn("Tokenization for search failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean)}}function je(e,r,o){if(c)try{m.add_word(e,r,o),s.debug("Word added to dictionary",{word:e,freq:r,tag:o});}catch(t){s.warn("Failed to add word",{word:e,error:String(t)});}}function ze(){return c}async function Ye(){c=false,s.debug("Tokenizer closed");}function Be(e){if(!c)return e.split(/\s+/).filter(Boolean).join(" ");try{return He(e).join(" ")}catch(r){return s.warn("Tokenization failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function Ge(e){if(!c)return e.split(/\s+/).filter(Boolean).join(" ");try{return he(e).join(" ")}catch(r){return s.warn("Tokenization for search failed, using fallback",{error:String(r)}),e.split(/\s+/).filter(Boolean).join(" ")}}function u(e){let r=f$1().worktree,o=j$1(r);return {agentId:e,isTrustedLocal:true,remote:false,locale:"en-US",dbPath:o,workspaceDir:r,rootDir:r,config:A({agentId:e,dbPath:o,workspaceDir:r})}}var z=async e=>{if(!e.agentId?.trim())return {ok:false,error:"session-start: agentId is required in ctx"};let r=e.extras?.topK??5,o=e.extras?.query??"";try{let t=await z$1("recall",{query:o,maxResults:r},u(e.agentId));if(t.hits.length===0)return {ok:!0,injected:"",logLine:"session-start: no facts found for agent; skipping context injection"};let n=t.hits.map(R=>`- [${R.category}/imp=${R.importance}] ${R.snippet.slice(0,200)}`);return {ok:!0,injected:`[memory:session-start recall top-${t.hits.length}]
2
2
  ${n.join(`
3
3
  `)}`,logLine:`session-start: injected ${t.hits.length} facts into context (agent=${e.agentId})`}}catch(t){return {ok:false,error:t instanceof Error?t.message:String(t)}}};var Ee=3600*1e3,Y=async e=>{if(!e.agentId?.trim())return {ok:false,error:"session-end: agentId is required in ctx"};let r=typeof e.extras?.lookbackMs=="number"&&e.extras.lookbackMs>0?e.extras.lookbackMs:Ee,o=e.extras?.fromTime??new Date(Date.now()-r).toISOString();try{let t=await z$1("consolidate",{fromTime:o},u(e.agentId));return {ok:!0,logLine:`session-end: lookback=${r}ms, total=${t.totalFacts}, deduped=${t.dedupedCount}, archived=${t.archivedCount}, skipped=${t.skippedCount}`}}catch(t){return {ok:false,error:t instanceof Error?t.message:String(t)}}};var B=async e=>{if(!e.agentId?.trim())return {ok:false,error:"pre-compact: agentId is required in ctx"};let o=(e.contextPreview??e.messagePreview??"").slice(0,200).replace(/\s+/g," ").trim(),t=e.extras?.topK??3;if(!o)return {ok:true,injected:"",logLine:"pre-compact: empty contextPreview; skipping recall injection"};try{let n=await z$1("recall",{query:o,maxResults:t,minImportance:5},u(e.agentId));if(n.hits.length===0)return {ok:!0,injected:"",logLine:`pre-compact: no facts matched query for agent=${e.agentId}`};let h=n.hits.map(i=>`- [${i.category}/imp=${i.importance}] ${i.snippet.slice(0,150)}`);return {ok:!0,injected:`[memory:pre-compact recall top-${n.hits.length} (imp>=5)]
4
4
  ${h.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easbot/memory",
3
- "version": "0.3.24",
3
+ "version": "0.3.25",
4
4
  "description": "Memory management library for EASBOT ecosystem - 智能记忆管理库,支持混合搜索、中英文分词、增量索引",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -54,14 +54,14 @@
54
54
  "better-sqlite3": "^13.0.3",
55
55
  "jieba-wasm": "^2.4.0",
56
56
  "xdg-basedir": "^5.1.0",
57
- "@easbot/database": "0.3.24",
58
- "@easbot/mcp": "0.3.24",
59
- "@easbot/terminal": "0.3.24",
60
- "@easbot/types": "0.3.24",
61
- "@easbot/utils": "0.3.24",
62
- "@easbot/local-model-sdk": "0.3.24",
63
- "@easbot/llm": "0.3.24",
64
- "@easbot/ollama-sdk": "0.3.24"
57
+ "@easbot/database": "0.3.25",
58
+ "@easbot/mcp": "0.3.25",
59
+ "@easbot/terminal": "0.3.25",
60
+ "@easbot/types": "0.3.25",
61
+ "@easbot/utils": "0.3.25",
62
+ "@easbot/local-model-sdk": "0.3.25",
63
+ "@easbot/llm": "0.3.25",
64
+ "@easbot/ollama-sdk": "0.3.25"
65
65
  },
66
66
  "devDependencies": {
67
67
  "@types/node": "^25.9.5",
@@ -1 +0,0 @@
1
- 'use strict';var chunkCPRDIUQ4_cjs=require('./chunk-CPRDIUQ4.cjs'),utils=require('@easbot/utils'),terminal=require('@easbot/terminal');var y=utils.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 terminal.renderLines({title:t,flat:e.map(i=>`$ easbot-memory ${i.name.padEnd(14)} ${i.description}`)})}function v(){let m=[terminal.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:")];terminal.printHuman(m);}function C(){v(),terminal.printHuman(["",terminal.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-7LQGYSUE.cjs');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,...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-UNDHFDAC.cjs'),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)terminal.emitJsonOk(a,{command:e});else {let p=a;terminal.printHuman([terminal.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-M2EWX25U.cjs'),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?terminal.emitJsonOk(a,{command:e}):terminal.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-BXVUUY5M.cjs'),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?terminal.emitJsonOk(a,{command:e}):terminal.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-SSGVAE5Y.cjs'),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?terminal.emitJsonOk(a,{command:e}):terminal.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-L2V2RMDQ.cjs'),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?terminal.emitJsonOk(a,{command:e}):terminal.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-X52RRH2C.cjs'),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?terminal.emitJsonOk(a,{command:e}):terminal.printHuman([s(a)],{title:"consolidate (pipeline)"}),{code:0,handled:!0,command:e}}case "sync":{let{parseSyncOptions:r,runSync:n,formatSyncText:s}=await import('./sync-3RWIZYR6.cjs'),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?terminal.emitJsonOk(a,{command:e}):terminal.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-WIKKSBLC.cjs'),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?terminal.emitJsonOk(a,{command:e}):terminal.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-A2JC6NFH.cjs'),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?terminal.emitJsonOk(o,{command:e}):terminal.printHuman([terminal.formatKnowledgeStatus(K(o))],{title:"memory status",boxed:!0}),{code:0,handled:!0,command:e}}case "doctor":{let{parseDoctorOptions:r,runDoctor:n}=await import('./doctor-SJY3K3DV.cjs'),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?terminal.emitJsonOk(o,{command:e}):terminal.printHuman([terminal.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-I2I6U4XM.cjs'),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?terminal.emitJsonOk(a,{command:e}):terminal.printHuman([s(a)],{title:"memory config"}),{code:0,handled:!0,command:e}}case "mcp":{let{parseMcpOptions:r,runMcp:n}=await import('./mcp-PRR2RYOP.cjs'),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?terminal.emitJsonOk(o,{command:e}):terminal.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??chunkCPRDIUQ4_cjs.f().worktree;return console.error(`[memory] ${s} :: ${e} failed: ${n}`),terminal.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}}exports.a=S;exports.b=v;exports.c=C;exports.d=A;exports.e=j;
@@ -1,67 +0,0 @@
1
- 'use strict';var chunkLYBUZDJK_cjs=require('./chunk-LYBUZDJK.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'),ge=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 ge__default=/*#__PURE__*/_interopDefault(ge);var pe=utils.Log.create({service:"memory.graph-store"}),Z=class{constructor(e){chunkM2YU5LAI_cjs.a(this,"db");this.db=e;}async upsertNode(e,a,r,o){let c=Date.now(),s=JSON.stringify(r??{}),i=this.db.prepare("SELECT id FROM nodes WHERE name = ? AND type = ? LIMIT 1").get(e,a);if(i)return this.db.prepare("UPDATE nodes SET properties = ?, updatedAt = ? WHERE id = ?").run(s,c,i.id),i.id;let l=this.db.prepare("INSERT INTO nodes (name, type, properties, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?)").run(e,a,s,c,c);return Number(l.lastInsertRowid)}async deleteNode(e){this.db.prepare("DELETE FROM nodes WHERE id = ?").run(e);}async upsertEdge(e,a,r,o){let c=this.db.prepare("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)").run(e,a,r,JSON.stringify(o??{}),Date.now());return Number(c.lastInsertRowid)}async queryNodes(e={}){let a="SELECT id, name, type, properties, createdAt, updatedAt FROM nodes",r=[],o=[];if(e.ids&&e.ids.length>0){let s=e.ids.map(i=>typeof i=="string"?parseInt(i,10):i).filter(i=>!Number.isNaN(i));o.push(`id IN (${s.map(()=>"?").join(", ")})`),r.push(...s);}e.name&&(o.push("name LIKE ?"),r.push(`%${e.name}%`)),e.type&&(o.push("type = ?"),r.push(e.type)),o.length>0&&(a+=` WHERE ${o.join(" AND ")}`),a+=" ORDER BY id",e.limit&&(a+=" LIMIT ?",r.push(e.limit)),pe.debug("queryNodes",{sql:a,params:r,filter:e});let c=this.db.prepare(a).all(...r);return pe.debug("queryNodes result",{count:c.length}),c.map(s=>({id:s.id,name:s.name,type:s.type,properties:s.properties?JSON.parse(s.properties):void 0,createdAt:s.createdAt,updatedAt:s.updatedAt}))}async queryEdges(e={}){let a="SELECT e.id, e.source, e.target, e.relation, e.properties, e.createdAt FROM edges e",r=[],o=[];if(e.ids&&e.ids.length>0&&(o.push(`e.id IN (${e.ids.map(()=>"?").join(", ")})`),r.push(...e.ids)),e.source!==void 0&&(o.push("e.source = ?"),r.push(e.source)),e.target!==void 0&&(o.push("e.target = ?"),r.push(e.target)),e.sourceOrTarget&&e.sourceOrTarget.length>0){let g=e.sourceOrTarget.map(S=>typeof S=="string"?parseInt(S,10):S).filter(S=>!Number.isNaN(S));o.push(`(e.source IN (${g.map(()=>"?").join(", ")}) OR e.target IN (${g.map(()=>"?").join(", ")}))`),r.push(...g,...g);}e.relation&&(o.push("e.relation = ?"),r.push(e.relation)),o.length>0&&(a+=` WHERE ${o.join(" AND ")}`),a+=" ORDER BY e.id",e.limit&&(a+=" LIMIT ?",r.push(e.limit)),pe.debug("queryEdges",{sql:a,params:r,filter:e});let c=this.db.prepare(a).all(...r);pe.debug("queryEdges result",{count:c.length});let s=[...new Set(c.map(g=>g.target))],i=s.length>0?await this.queryNodes({ids:s,limit:s.length}):[],l=new Map(i.map(g=>[g.id,g]));return c.map(g=>{let S={id:g.id,source:g.source,target:g.target,relation:g.relation,properties:g.properties?JSON.parse(g.properties):void 0,createdAt:g.createdAt},f=l.get(g.target);return f&&(S.targetNode=f),S})}async queryNeighbors(e,a=1,r){let o=r?.maxEdgesPerNode??50,c=new Map,s=[e];for(let i=0;i<=a&&s.length>0;i++){let l=await this.queryNodes({ids:s,limit:s.length}),g=await this.queryEdges({sourceOrTarget:s,limit:o*s.length}),S=new Map;for(let y of g){if(s.includes(y.source)){let h=S.get(y.source)??[];h.push(y),S.set(y.source,h);}if(s.includes(y.target)){let h=S.get(y.target)??[];h.push(y),S.set(y.target,h);}}let f=[];for(let y of l){if(c.has(y.id))continue;let h=(S.get(y.id)??[]).slice(0,o);if(c.set(y.id,{...y,edges:h}),i<a)for(let R of h){let v=R.source===y.id?R.target:R.source;!c.has(v)&&!f.includes(v)&&f.push(v);}}s=f;}return [...c.values()]}};var I=class extends Error{constructor(a,r,o){super(a);chunkM2YU5LAI_cjs.a(this,"code",r);chunkM2YU5LAI_cjs.a(this,"details",o);this.name="ServiceError";}},se=class extends I{constructor(e,a=[]){super(`Memory not found: ${e}`,"NOT_FOUND",{memoryId:e,candidates:a});}};var ye=class extends I{constructor(){super("ctx.agentId is required for memory service (ADR 0055 per-agent isolation)","AGENT_ID_REQUIRED");}},he=class extends I{constructor(e,a){super(`Trust denied for operation "${e}": ${a}`,"TRUST_DENIED",{operation:e,reason:a});}},ie=class extends I{constructor(e,a){super(`Memory ${e} has ${a} references (force=false)`,"HAS_REFERENCES",{memoryId:e,referenceCount:a});}},ce=class extends I{constructor(e){super(`dryRun mode: ${e} memories matched but not deleted`,"DRY_RUN_NO_DELETE",{matchedCount:e});}},de=class extends I{constructor(e,a){super(`Matched ${e} memories exceeds maxDelete=${a}`,"MAX_DELETE_EXCEEDED",{matched:e,maxDelete:a});}};function $(t){if(typeof t.agentId!="string"||t.agentId.trim().length===0)throw new ye}function z(t,e){if(t.remote!==false)throw new he(e,"requires trusted local caller (CLI / agent tool / MCP with remote=false)")}function ee(t){if(!t.dbPath||t.dbPath.trim().length===0)throw new I("service ctx.dbPath is required (MemoryKnowledgeConfigWithModels.database.path)","INTERNAL")}var te=utils.Log.create({service:"memory.service.recall"});async function et(t,e){let a=Date.now();if($(t),ee(t),!e.query||e.query.trim().length===0)throw new I("recall requires non-empty `query`","CONTENT_REQUIRED");let r=e.includeShared?"both":"agent_only";e.includeGraph&&void 0,te.debug("recall invoked",{agentId:t.agentId,query:e.query,category:e.category,maxResults:e.maxResults,includeGraph:e.includeGraph,scope:r});let o=e.maxResults??10,c=e.minScore??0,s=[],i=new chunkLYBUZDJK_cjs.e(t.dbPath);try{await i.initialize();let l=chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().embedding===!0,g=await Rt(i,t.agentId,e.query,{category:e.category,minImportance:e.minImportance,fromTime:e.fromTime,toTime:e.toTime,limit:o,minScore:c,hasEmbedding:l}),S;if(e.includeGraph&&g.length>0)try{let y=new Z(i.getDb()),h=e.depth??1,R=g.flatMap(E=>(E.nodes??[]).map(M=>M.id)).slice(0,5),v=new Set,b=new Map,C=e.maxEdgesPerNode??10;for(let E of R){let M=await y.queryNeighbors(E,h,{agentId:t.agentId,scope:r,maxEdgesPerNode:C});for(let u of M)v.add(u.id),b.set(u.id,u.edges??[]);}let w=v.size>0?i.query(`SELECT id, name, type FROM nodes WHERE id IN (${Array.from(v).map(()=>"?").join(",")})`,Array.from(v)):[],T=Array.from(b.values()).flat();S={nodes:w.map(E=>({id:E.id,name:E.name,type:E.type,createdAt:"",updatedAt:""})),edges:T};}catch(y){let h=y instanceof Error?y.message:String(y);te.warn("recall: KG neighbor query failed",{error:h}),s.push(`kg_neighbor_query_failed: ${h}`),S={nodes:[],edges:[]};}let f=Date.now()-a;return {hits:g,total:g.length,truncated:g.length>=o,durationMs:f,graph:S,...s.length>0?{warnings:s}:{}}}catch(l){throw l instanceof I?l:new I(`recall failed: ${l instanceof Error?l.message:String(l)}`,"INTERNAL",{cause:l instanceof Error?l.message:String(l)})}finally{i.close();}}async function Rt(t,e,a,r){let o=["mf.agent_id = ?"],c=[e];r.category&&(o.push("mf.category = ?"),c.push(r.category)),r.minImportance!==void 0&&(o.push("mf.importance >= ?"),c.push(r.minImportance)),r.fromTime&&(o.push("mf.created_at >= ?"),c.push(r.fromTime)),r.toTime&&(o.push("mf.created_at <= ?"),c.push(r.toTime));let s=o.join(" AND "),i=null;if(r.hasEmbedding)try{i=await chunkJ5XF2W4Z_cjs.a.embedText(a);}catch(p){te.warn("recall: query embedding failed, falling back to FTS-only",{error:p instanceof Error?p.message:String(p)}),i=null;}let l=Math.max(r.limit*100,1e3),[g,S]=await Promise.all([i?It(t,i,s,c,l):Promise.resolve([]),Mt(t,a,s,c,r.limit)]),f=i?.7:0,y=i?.3:1,h=f+y,R=f/h,v=y/h,b=new Map;for(let p of g)b.set(p.id,p.score*R);for(let p of S)b.set(p.id,(b.get(p.id)??0)+p.score*v);let C=Array.from(b.entries()).sort((p,D)=>D[1]-p[1]).map(([p])=>p).slice(0,r.limit);if(C.length===0)return [];let w=C.map(()=>"?").join(","),T=t.query(`SELECT
2
- mf.id,
3
- mf.category,
4
- mf.importance,
5
- mf.agent_id as agentId,
6
- mf.content as content,
7
- SUBSTR(mf.content, 1, 200) as snippet,
8
- mf.created_at as createdAt,
9
- mf.updated_at as updatedAt,
10
- mf.source,
11
- mf.file_path as filePath,
12
- mf.tags,
13
- mf.session_id as sessionId,
14
- mf.msg_id as msgId,
15
- mf.parent_msg_id as parentMsgId
16
- FROM memory_facts mf
17
- WHERE mf.id IN (${w})`,C),E=St(t,T.map(p=>p.id)),M=Date.now();return T.map(p=>{let D=b.get(p.id)??0,F=(M-new Date(p.createdAt).getTime())/864e5,P=Math.exp(-0.05*F),G=(p.importance-1)/9,B=.4*D+.3*P+.3*G,V;if(p.tags)try{let d=JSON.parse(p.tags);Array.isArray(d)&&(V=d.filter(m=>typeof m=="string"));}catch{}return {memoryId:p.id,category:p.category,importance:p.importance,agentId:p.agentId,content:p.content,snippet:p.snippet,score:B,createdAt:p.createdAt,updatedAt:p.updatedAt,source:p.source,filePath:p.filePath??void 0,tags:V,sessionId:p.sessionId??void 0,msgId:p.msgId??void 0,parentMsgId:p.parentMsgId??void 0,nodes:E.get(p.id)??[]}}).filter(p=>p.score>=r.minScore).sort((p,D)=>D.score-p.score)}function St(t,e){let a=new Map;if(e.length===0)return a;try{let r=e.map(()=>"?").join(","),o=t.query(`SELECT fn.fact_id as fact_id, n.id, n.name, n.type
18
- FROM fact_nodes fn
19
- JOIN nodes n ON fn.node_id = n.id
20
- WHERE fn.fact_id IN (${r})
21
- ORDER BY fn.fact_id, fn.score DESC, n.id`,e);for(let c of o){let s=a.get(c.fact_id);s||(s=[],a.set(c.fact_id,s)),s.push({id:c.id,name:c.name,type:c.type});}}catch(r){te.warn("recall: loadFactNodes failed (KG associations unavailable for this recall)",{error:r instanceof Error?r.message:String(r)});}return a}function It(t,e,a,r,o){try{return t.query(`SELECT mf.id, mv.embedding
22
- FROM memory_facts mf
23
- JOIN memory_vectors mv ON mf.id = mv.fact_id
24
- WHERE ${a}
25
- LIMIT ?`,[...r,o]).map(s=>{let i=new Float32Array(s.embedding.buffer,s.embedding.byteOffset,s.embedding.byteLength/4);return {id:s.id,score:_t(e,i)}}).sort((s,i)=>i.score-s.score)}catch(c){if(c instanceof I)throw c;return te.warn("vector search failed, falling back to FTS-only",{error:c instanceof Error?c.message:String(c)}),[]}}function Mt(t,e,a,r,o){try{let c=t.query(`SELECT mf.id as id, bm25(memory_facts_fts) as score
26
- FROM memory_facts_fts fts
27
- JOIN memory_facts mf ON mf.id = fts.fact_id
28
- WHERE ${a} AND memory_facts_fts MATCH ?
29
- ORDER BY score DESC
30
- LIMIT ?`,[...r,vt(e),o]);if(c.length===0)return [];let s=Math.max(...c.map(i=>Math.abs(i.score)),1);return c.map(i=>({id:i.id,score:1-Math.abs(i.score)/s})).filter(i=>i.score>=0)}catch(c){if(c instanceof I)throw c;return te.warn("FTS search failed, returning empty result",{err:c instanceof Error?c.message:String(c)}),[]}}function _t(t,e){if(t.length!==e.length||t.length===0)return 0;let a=0,r=0,o=0;for(let s=0;s<t.length;s++){let i=t[s]??0,l=e[s]??0;a+=i*l,r+=i*i,o+=l*l;}let c=Math.sqrt(r)*Math.sqrt(o);return c===0?0:Math.max(0,a/c)}function vt(t){return t.trim().split(/\s+/).filter(e=>e.length>0).map(e=>`"${e.replace(/"/g,'""')}"`).join(" ")}var Ee=zod.z.object({query:zod.z.string().min(1).max(2e3),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(),minScore:zod.z.number().min(0).max(1).optional(),includeGraph:zod.z.boolean().optional(),depth:zod.z.number().int().min(1).max(5).optional(),includeShared:zod.z.boolean().optional(),maxEdgesPerNode:zod.z.number().int().min(1).max(100).optional()}).strict();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 we=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(),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(),extractGraph:zod.z.boolean().optional()}).strict();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 Re=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)")}).strict().refine(t=>t.content!==void 0||t.category!==void 0||t.importance!==void 0||t.tags!==void 0,{message:"at least one of `content`, `category`, `importance`, `tags` is required"});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 Se=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(),dryRun:zod.z.boolean().optional(),force:zod.z.boolean().optional()}).strict().refine(t=>t.factId!==void 0&&t.factId.length>0||t.category!==void 0&&t.category.length>0||t.fromTime!==void 0||t.toTime!==void 0,{message:"one of `factId`, `category`, `fromTime`, or `toTime` is required"});zod.z.object({deletedCount:zod.z.number(),deletedIds:zod.z.array(zod.z.string()),dryRun:zod.z.boolean(),truncatedCount:zod.z.number()});var Ie=zod.z.object({sessionId:zod.z.string().min(1),lastN:zod.z.number().int().min(1).max(500).optional(),fromMessageId:zod.z.string().optional(),writeToDisk:zod.z.boolean().optional()}).strict();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 Me=zod.z.object({windowDays:zod.z.number().int().min(1).max(365).optional(),dryRun:zod.z.boolean().optional(),fromTime:zod.z.string().datetime().optional()}).strict();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 _e=zod.z.object({query:zod.z.string().min(1).optional(),nodeId:zod.z.number().int().positive().optional(),type:zod.z.string().optional(),depth:zod.z.number().int().min(1).max(5).optional(),maxNodes:zod.z.number().int().min(1).max(500).optional(),scope:zod.z.enum(["agent_only","shared_only","both"]).optional(),relation:zod.z.string().optional(),agentId:zod.z.string().optional(),maxEdgesPerNode:zod.z.number().int().min(1).max(100).optional()}).strict();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 ve=zod.z.object({agentId:zod.z.string().optional()}).passthrough().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 De=zod.z.object({repair:zod.z.boolean().optional(),agentId:zod.z.string().optional()}).passthrough().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 Ce=zod.z.object({workspaceDir:zod.z.string().optional(),dbPath:zod.z.string().optional(),archiveDays:zod.z.number().int().min(1).max(3650).optional(),force:zod.z.boolean().optional()}).strict();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 Ne=zod.z.object({windowDays:zod.z.number().int().min(1).max(3650).optional(),dryRun:zod.z.boolean().optional()}).passthrough();zod.z.object({generatedCount:zod.z.number(),skippedCount:zod.z.number(),failedGenerateCount:zod.z.number(),archivedCount:zod.z.number(),failedArchivePaths:zod.z.array(zod.z.string()),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 me=utils.Log.create({service:"memory.fact-file-sync"}),Nt=".easbot/memory/active";function le(t,e){let a=e.replace(/\\/g,"/").replace(/\/+$/,""),r=t.category||"uncategorized",o=t.createdAt?new Date(t.createdAt).getTime():Date.now(),c=Number.isNaN(o)?new Date:new Date(o),s=c.getFullYear(),i=String(c.getMonth()+1).padStart(2,"0"),l=String(c.getDate()).padStart(2,"0"),g=`${s}-${i}-${l}`;return `${a}/${Nt}/${r}/${g}.md`}function tt(t){let e=t.tags&&t.tags.length>0?t.tags:[],a=t.importance??5,r=t.source??"session_self_write",o=t.createdAt?utils.formatLocalISO(new Date(t.createdAt)):utils.formatLocalISO(new Date),c=t.updatedAt?utils.formatLocalISO(new Date(t.updatedAt)):o,s=["---",`id: ${t.id}`,`agent_id: ${t.agentId}`,`category: ${t.category}`,`importance: ${a}`,`created_at: ${o}`,`updated_at: ${c}`,`source: ${r}`,e.length>0?`tags: [${e.join(", ")}]`:"tags: []"];return t.sessionId&&s.push(`session_id: ${t.sessionId}`),t.msgId&&s.push(`msg_id: ${t.msgId}`),t.parentMsgId&&s.push(`parent_msg_id: ${t.parentMsgId}`),s.push("---"),`${s.join(`
31
- `)}
32
- ${t.content.trim()}`}function re(t,e){let a=t.replace(/\\/g,"/"),r=e.replace(/\\/g,"/").replace(/\/+$/,"");return a.startsWith(`${r}/`)?a.slice(r.length+1):a}async function Ot(t,e){let a=le(t,e),r=re(a,e);try{let o=tt(t);await Q__default.default.mkdir(ge__default.default.dirname(a),{recursive:!0});let c="";try{c=await Q__default.default.readFile(a,"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(a,`${c}${s}${o}
35
- `,"utf-8"),me.debug("Fact file synced (append)",{id:t.id,relPath:r}),{ok:!0,absPath:a,relPath:r}}catch(o){let c=o instanceof Error?o.message:String(o);return me.warn("Failed to write fact file (best-effort, non-blocking)",{id:t.id,absPath:a,error:c}),{ok:false,absPath:a,relPath:r,error:c}}}async function Tt(t,e){let a;t.filePath?a=`${e.replace(/\\/g,"/").replace(/\/+$/,"")}/${t.filePath.replace(/^\/+/,"")}`:a=le({id:t.id,category:t.category,createdAt:t.createdAt,updatedAt:t.createdAt},e);let r=re(a,e);try{return await Q__default.default.unlink(a),me.debug("Fact file deleted",{id:t.id,relPath:r}),{ok:!0,absPath:a,relPath:r}}catch(o){if(o.code==="ENOENT")return me.debug("Fact file not found (already deleted)",{id:t.id,relPath:r}),{ok:true,absPath:a,relPath:r};let s=o instanceof Error?o.message:String(o);return me.warn("Failed to delete fact file (best-effort, non-blocking)",{id:t.id,absPath:a,error:s}),{ok:false,absPath:a,relPath:r,error:s}}}var ne={resolvePath:le,renderMarkdown:tt,toRelPath:re,write:Ot,delete:Tt};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 I("remember requires non-empty `content`","CONTENT_REQUIRED");if(!e.category)throw new I("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 a=new chunkLYBUZDJK_cjs.e(t.dbPath);try{await a.initialize();let r=new Date().toISOString(),o=Ft(),c=e.importance??5,s={entities:[],relations:[]},l=e.extractGraph!==!1&&chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().graphLlm?chunkJ5XF2W4Z_cjs.a.getGraphLlm():void 0;if(l)try{s=await qt(l,e.content);}catch(E){oe.warn("LLM KG extraction failed (continuing without KG)",{agentId:t.agentId,error:E instanceof Error?E.message:String(E)});}let g=chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().embedding===!0,S=g?await Lt(a.getDb(),e.content):null,f=S?S.length:null,y=s.entities,h=s.relations,R=[],v=0,b=[];if(a.transaction(()=>{let E=new Map;for(let u of y){let p=a.query("SELECT id FROM nodes WHERE name = ? AND type = ? LIMIT 1",[u.name,u.type])[0];if(p){E.set(u.name,p.id);continue}let D=null;try{let G=Pe(u.name),B=a.query("SELECT embedding FROM embedding_cache WHERE content_hash = ?",[G])[0];B?.embedding&&(D=B.embedding);}catch{}let P=a.run("INSERT INTO nodes (name, type, properties, embedding, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)",[u.name,u.type,JSON.stringify({source:"llm_extracted",...u.properties??{}}),D,r,r]).lastID;P>0&&(E.set(u.name,P),D===null&&b.push({name:u.name,nodeId:P}));}for(let u of h){let p=E.get(u.source),D=E.get(u.target);!p||!D||p===D||a.run("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)",[p,D,u.relation,JSON.stringify({}),r]);}a.run(`INSERT INTO memory_facts
36
- (id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance,
37
- source, tags, file_path, created_at, updated_at)
38
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[o,t.agentId,e.sessionId??null,e.msgId??null,e.parentMsgId??null,e.content,e.category,c,"session_self_write",e.tags?JSON.stringify(e.tags):null,null,r,r]);let M=Array.from(E.values());if(M.length>0)try{for(let u of M)a.run("INSERT OR IGNORE INTO fact_nodes (fact_id, node_id, source, score, createdAt) VALUES (?, ?, ?, ?, ?)",[o,u,"kg_extract",1,r]);}catch(u){oe.warn("fact_nodes write failed (non-fatal)",{factId:o,nodeCount:M.length,error:u instanceof Error?u.message:String(u)});}if(S&&f){let u=Te(S);a.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[o,u]),v=1,a.query("SELECT value FROM meta WHERE key = ?",["vectorDims"])[0]||a.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["vectorDims",String(f)]);}a.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[o]),a.run("INSERT INTO memory_facts_fts (fact_id, agent_id, content, tags) VALUES (?, ?, ?, ?)",[o,t.agentId,e.content,e.tags?e.tags.join(" "):""]),R.push(...Array.from(E.values()));}),b.length>0&&chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().embedding)try{let E=b.map(p=>p.name),M=await chunkJ5XF2W4Z_cjs.a.embedMany(E),u=new Date().toISOString();for(let p=0;p<b.length;p++){let D=b[p],F=M[p];if(!D||!F||F.length===0)continue;let P=Te(new Float32Array(F));a.run("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)",[Pe(D.name),P]),a.run("UPDATE nodes SET embedding = ?, updatedAt = ? WHERE id = ?",[P,u,D.nodeId]);}}catch(E){oe.warn("memory entity name batch embed failed (non-fatal)",{pendingCount:b.length,error:E instanceof Error?E.message:String(E)});}oe.info("Memory stored",{id:o,category:e.category,agentId:t.agentId,nodeCount:R.length,vectorsWritten:v,vectorDims:f??0,embeddingMode:g?"enabled":"fts_only",entitiesExtracted:y.length,relationsExtracted:h.length});let C={id:o,agentId:t.agentId,sessionId:e.sessionId,msgId:e.msgId,parentMsgId:e.parentMsgId,content:e.content,category:e.category,importance:c,source:"session_self_write",tags:e.tags,nodeIds:R.length>0?R:void 0,filePath:void 0,createdAt:r,updatedAt:r},w="",T=await ne.write(C,t.workspaceDir);if(T.ok){w=T.relPath,C.filePath=T.relPath;try{a.run("UPDATE memory_facts SET file_path = ? WHERE id = ?",[T.relPath,o]);}catch(E){oe.warn("Failed to update file_path column after sync",{id:o,error:E instanceof Error?E.message:String(E)});}}return {fact:C,filePath:w,deduplicated:!1,nodeIds:R,vectorsWritten:v,vectorDims:f??0,entitiesExtracted:y.length,relationsExtracted:h.length}}catch(r){throw r instanceof I?r:new I(`remember failed: ${r instanceof Error?r.message:String(r)}`,"INTERNAL",{cause:r instanceof Error?r.message:String(r)})}finally{a.close();}}function Ft(){let t=Date.now(),e=crypto.randomBytes(3).toString("hex");return `mem_${t}_${e}`}function Te(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}function Pe(t){return crypto.createHash("sha256").update(t).digest("hex")}async function Lt(t,e){let a=Pe(e),r=t.prepare("SELECT embedding FROM embedding_cache WHERE content_hash = ?").get(a);if(r?.embedding)return new Float32Array(r.embedding.buffer,r.embedding.byteOffset,r.embedding.byteLength/4);let o=await chunkJ5XF2W4Z_cjs.a.embedText(e);if(!o||o.length===0)return null;let c=Te(o);return t.prepare("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)").run(a,c),o}async function qt(t,e){let a=await llm.GraphProvider.generateGraph({chunks:[e],model:t,includeRules:false});return {entities:a.entities,relations:a.relations}}var Ae=utils.Log.create({service:"memory.service.update"});function Ut(t){if(t.content===void 0&&t.category===void 0&&t.importance===void 0&&t.tags===void 0)throw new I("update requires at least one of: `content`, `category`, `importance`, `tags`","CONTENT_REQUIRED");if(t.content!==void 0&&t.content.trim().length===0)throw new I("update: `content` cannot be empty (use `forget` to delete)","CONTENT_REQUIRED");if(t.importance!==void 0&&(t.importance<1||t.importance>10))throw new I(`update: \`importance\` must be 1-10, got ${t.importance}`,"IMPORTANCE_REQUIRED")}async function nt(t,e){let a=Date.now();$(t),ee(t),Ut(e),Ae.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 r=e.content!==void 0,o=r&&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){Ae.warn("update: embedding rewrite failed (continuing without vector update)",{factId:e.factId,error:i instanceof Error?i.message:String(i)});}let s=new chunkLYBUZDJK_cjs.e(t.dbPath);try{await s.initialize();let i=new Date().toISOString(),l=[];s.transaction(()=>{let y=s.query("SELECT id, content, category, importance, tags FROM memory_facts WHERE id = ? AND agent_id = ?",[e.factId,t.agentId])[0];if(!y)throw new se(e.factId);let h=["updated_at = ?"],R=[i];if(e.content!==void 0&&e.content!==y.content&&(h.push("content = ?"),R.push(e.content),l.push("content")),e.category!==void 0&&e.category!==y.category&&(h.push("category = ?"),R.push(e.category),l.push("category")),e.importance!==void 0&&e.importance!==y.importance&&(h.push("importance = ?"),R.push(e.importance),l.push("importance")),e.tags!==void 0){let v=e.tags.length>0?JSON.stringify(e.tags):null;v!==y.tags&&(h.push("tags = ?"),R.push(v),l.push("tags"));}if(l.length>0&&s.run(`UPDATE memory_facts SET ${h.join(", ")} WHERE id = ? AND agent_id = ?`,[...R,e.factId,t.agentId]),l.includes("content")||l.includes("tags")){let v=e.content??y.content,b=l.includes("tags")?e.tags&&e.tags.length>0?JSON.stringify(e.tags):null:y.tags,C=b?(()=>{try{let w=JSON.parse(b);return Array.isArray(w)?w.filter(T=>typeof T=="string"):[]}catch{return []}})():[];s.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[e.factId]),s.run("INSERT INTO memory_facts_fts (fact_id, agent_id, content, tags) VALUES (?, ?, ?, ?)",[e.factId,t.agentId,v,C.join(" ")]);}if(l.includes("content")&&c){let v=Wt(c);s.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[e.factId,v]);try{let b=Gt(e.content);s.run("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)",[b,v]);}catch{}}}),(l.includes("content")||l.includes("tags"))&&s.run("INSERT INTO memory_facts_fts(memory_facts_fts) VALUES('optimize')");let g=s.query("SELECT id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance, source, tags, file_path, created_at, updated_at FROM memory_facts WHERE id = ? AND agent_id = ?",[e.factId,t.agentId])[0];if(!g)throw new I(`update: failed to read back updated fact ${e.factId}`,"INTERNAL");let S;if(g.tags)try{let y=JSON.parse(g.tags);Array.isArray(y)&&(S=y.filter(h=>typeof h=="string"));}catch{}let f={id:g.id,agentId:g.agent_id,sessionId:g.session_id??void 0,msgId:g.msg_id??void 0,parentMsgId:g.parent_msg_id??void 0,content:g.content,category:g.category,importance:g.importance,source:g.source,tags:S,filePath:g.file_path??void 0,createdAt:g.created_at,updatedAt:g.updated_at};return Ae.info("Memory updated",{agentId:t.agentId,factId:e.factId,fieldsUpdated:l,contentChanged:r,durationMs:Date.now()-a}),{fact:f,contentChanged:r,fieldsUpdated:l,durationMs:Date.now()-a}}catch(i){throw i instanceof I?i:new I(`update failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}function Wt(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}function Gt(t){return crypto.createHash("sha256").update(t).digest("hex")}var ke=utils.Log.create({service:"memory.service.forget"}),Bt=1e3;function zt(t){let e=[];if(t.factId&&t.factId.trim().length>0&&e.push("factId"),t.category&&t.category.trim().length>0&&e.push("category"),(t.fromTime||t.toTime)&&e.push("timeRange"),e.length===0)throw new I("CONTENT_REQUIRED: forget requires one of: `factId`, `category`, or `fromTime`/`toTime`","CONTENT_REQUIRED");if(e.length>1)throw new I(`mutually exclusive: forget requires exactly one of factId/category/timeRange, got [${e.join(", ")}]`,"CONTENT_REQUIRED");return e[0]}function Qt(t,e,a){let r=[a];switch(t){case "factId":return {where:"agent_id = ? AND id = ?",args:[...r,e.factId]};case "category":return {where:"agent_id = ? AND category = ?",args:[...r,e.category]};case "timeRange":{let o=["agent_id = ?"];return e.fromTime&&(o.push("created_at >= ?"),r.push(e.fromTime)),e.toTime&&(o.push("created_at <= ?"),r.push(e.toTime)),{where:o.join(" AND "),args:r}}}}function Kt(t,e,a,r){return t.query(`SELECT id FROM memory_facts WHERE ${e} LIMIT ?`,[...a,r+1]).map(c=>c.id)}function Vt(t,e,a,r){if(a.length===0)return 0;let o=a.map(()=>"?").join(",");return t.query(`SELECT COUNT(DISTINCT fn.fact_id) as count
39
- FROM fact_nodes fn
40
- JOIN memory_facts mf ON fn.fact_id = mf.id
41
- WHERE mf.agent_id = ? AND fn.fact_id != ? AND fn.node_id IN (${o})`,[r,e,...a])[0]?.count??0}function Jt(t,e,a){let r,o,c="";return t.transaction(()=>{let s=t.query("SELECT content, file_path, category, created_at FROM memory_facts WHERE id = ? AND agent_id = ?",[e,a])[0],l=t.query("SELECT node_id FROM fact_nodes WHERE fact_id = ?",[e]).map(g=>g.node_id).filter(g=>typeof g=="number");if(r=s?.file_path??void 0,o=s?.category,c=s?.created_at??"",t.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[e]),t.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[e,a]),l.length>0){let g=l.map(()=>"?").join(",");t.run(`DELETE FROM nodes WHERE id IN (${g}) AND NOT EXISTS (
42
- SELECT 1 FROM fact_nodes fn WHERE fn.node_id = nodes.id
43
- )`,l);}}),t.run("INSERT INTO memory_facts_fts(memory_facts_fts) VALUES('optimize')"),{filePath:r,category:o,createdAt:c}}async function ot(t,e){$(t),z(t,"forget");let a=zt(e),r=e.maxDelete??Bt,o=e.dryRun??false,c=e.force??false;ke.debug("forget invoked",{agentId:t.agentId,mode:a,maxDelete:r,dryRun:o,force:c});let s=new chunkLYBUZDJK_cjs.e(t.dbPath);try{await s.initialize();let{where:i,args:l}=Qt(a,e,t.agentId),g=Kt(s,i,l,r),S=g.length>r;if(S&&!c)throw new de(g.length,r);let f=S?g.slice(0,r):g;if(o)throw new ce(f.length);let y=[],h=[];for(let R of f){if(!c){let T=s.query("SELECT node_id FROM fact_nodes WHERE fact_id = ? AND node_id IS NOT NULL",[R]).map(M=>M.node_id).filter(M=>typeof M=="number"),E=Vt(s,R,T,t.agentId);if(E>0)throw new ie(R,E)}let{filePath:v,category:b,createdAt:C}=Jt(s,R,t.agentId);v&&b&&h.push({id:R,filePath:v,category:b,createdAt:C}),y.push(R);}ke.info("forget complete",{agentId:t.agentId,mode:a,deletedCount:y.length,force:c,dryRun:o});for(let{id:R,filePath:v,category:b,createdAt:C}of h)await ne.delete({id:R,filePath:v,category:b,createdAt:C},t.workspaceDir).catch(w=>{ke.warn("Fact file delete failed (best-effort)",{id:R,filePath:v,error:w instanceof Error?w.message:String(w)});});return {deletedCount:y.length,deletedIds:y,dryRun:o,truncatedCount:S?g.length-r:0}}catch(i){throw i instanceof I?i:new I(`forget failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var at=utils.Log.create({service:"memory.service.extract"}),Xt=50,xe=500;async function st(t,e){if($(t),!e.sessionId||e.sessionId.trim().length===0)throw new I("extract requires non-empty `sessionId`","SESSION_ID_REQUIRED");let a=e.lastN??Xt;if(a>xe)throw new I(`extract lastN=${a} exceeds max=${xe}`,"CONTENT_REQUIRED",{lastN:a,maxLastN:xe});let r=e.sessionId,o=e.fromMessageId;at.debug("extract invoked",{agentId:t.agentId,sessionId:r,lastN:a,fromMessageId:o,writeToDisk:e.writeToDisk??true});let c=Date.now(),s=new chunkLYBUZDJK_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,r,a]),l=o?i.filter(b=>b.id>o):i,g=l.map(b=>b.id),S=g.length>0?s.query(`SELECT node_id FROM fact_nodes WHERE fact_id IN (${g.map(()=>"?").join(",")})`,g):[],f=new Set;for(let b of S)typeof b.node_id=="number"&&b.node_id>0&&f.add(b.node_id);let y=Array.from(f),h=[],R=[];if(y.length>0){let b=y.map(()=>"?").join(","),C=s.query(`SELECT id, name, type FROM nodes WHERE id IN (${b})`,y),w=new Map;for(let M of C)w.set(M.id,M.name);h=C.map(M=>({id:M.id,name:M.name,type:M.type}));let T=s.query(`SELECT source, target, relation FROM edges WHERE source IN (${b}) OR target IN (${b})`,[...y,...y]),E=new Set;R=[];for(let M of T){let u=w.get(M.source),p=w.get(M.target);if(!u||!p)continue;let D=`${u}\0${M.relation}\0${p}`;E.has(D)||(E.add(D),R.push({source:u,target:p,relation:M.relation}));}}let v=Date.now()-c;return at.info("extract complete",{agentId:t.agentId,sessionId:r,factCount:l.length,nodeCount:h.length,relationCount:R.length,durationMs:v}),{extractedCount:l.length,factIds:l.map(b=>b.id),entities:h,relations:R,messageRange:{fromMessageId:l[0]?.id??"",toMessageId:l[l.length-1]?.id??""},durationMs:v}}catch(i){throw i instanceof I?i:new I(`extract failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var qe=utils.Log.create({service:"memory.service.consolidate"}),er=30;async function tr(t){let{createHash:e}=await import('crypto');return e("sha256").update(t).digest("hex")}async function it(t,e={}){let a=Date.now();$(t),z(t,"consolidate");let r=e.windowDays??er,o=e.dryRun??false,c=e.fromTime;qe.debug("consolidate invoked",{agentId:t.agentId,windowDays:r,dryRun:o,fromTime:c});let s=new chunkLYBUZDJK_cjs.e(t.dbPath);try{await s.initialize();let i=s.query(`SELECT id, content, category, importance, created_at FROM memory_facts
48
- WHERE agent_id = ?${c?" AND created_at >= ?":""}
49
- ORDER BY created_at DESC`,c?[t.agentId,c]:[t.agentId]),l=new Map;for(let C of i){let w=await tr(C.content);l.has(w)||l.set(w,[]),l.get(w)?.push(C);}let g=0,S=[];for(let[,C]of l){if(C.length<=1)continue;let w=[...C].sort((M,u)=>M.importance!==u.importance?u.importance-M.importance:u.created_at.localeCompare(M.created_at)),T=w[0];if(!T)continue;let E=w.slice(1).map(M=>M.id);g+=E.length,S.push({keep:T,removeIds:E});}let f=new Date(Date.now()-r*24*60*60*1e3).toISOString(),y=s.query(`SELECT id, content, category, importance, created_at FROM memory_facts
50
- WHERE agent_id = ? AND created_at < ?
51
- ORDER BY created_at ASC`,[t.agentId,f]),h=0;if(o)h=0;else {let C=ge__default.default.join(t.workspaceDir,"archive");await Q__default.default.mkdir(C,{recursive:!0});for(let{removeIds:w}of S)w.length!==0&&s.transaction(()=>{for(let T of w)s.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[T,t.agentId]);});for(let w of y){let T=w.created_at.slice(0,7),E=ge__default.default.join(C,T,w.category);await Q__default.default.mkdir(E,{recursive:!0});let M=ge__default.default.join(E,`${w.id}.md`);try{await Q__default.default.writeFile(M,[`# ${w.id}`,"",`category: ${w.category}`,`importance: ${w.importance}`,`createdAt: ${w.created_at}`,"",w.content,""].join(`
52
- `),"utf-8"),s.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[w.id,t.agentId]),h++;}catch(u){qe.warn("consolidate: archive write failed",{factId:w.id,error:u instanceof Error?u.message:String(u)});}}}let R=i.length,v=0,b=0;return qe.info("consolidate complete",{agentId:t.agentId,totalFacts:R,dedupedCount:g,compressedCount:v,archivedCount:h,skippedCount:b,dryRun:o,durationMs:Date.now()-a}),{totalFacts:R,dedupedCount:g,compressedCount:v,archivedCount:h,skippedCount:b,durationMs:Date.now()-a}}catch(i){throw i instanceof I?i:new I(`consolidate failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var W=utils.Log.create({service:"memory.service.sync"}),or=30,ar=".easbot/memory/active",ct=".easbot/memory/archive";function sr(t,e){let r=t.query("SELECT node_id FROM fact_nodes WHERE fact_id = ?",[e.id]).map(o=>o.node_id).filter(o=>typeof o=="number");return {id:e.id,agentId:e.agent_id,sessionId:e.session_id??void 0,msgId:e.msg_id??void 0,parentMsgId:e.parent_msg_id??void 0,content:e.content,category:e.category,importance:e.importance,source:e.source,tags:e.tags?JSON.parse(e.tags):void 0,nodeIds:r.length>0?r:void 0,filePath:e.file_path??void 0,createdAt:e.created_at,updatedAt:e.updated_at}}async function ir(t,e){let a=0,r=0,o=0,{where:c,params:s}=t.agentFilter(e.agentId),i=t.query(`SELECT id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance,
53
- source, tags, file_path, created_at, updated_at
54
- FROM memory_facts ${c}
55
- ORDER BY created_at ASC`,s);for(let l of i){let g=sr(t,l);if(l.file_path?.startsWith(`${ct}/`)){r++;continue}let S=le(g,e.workspaceDir);try{await Q__default.default.access(S),r++;continue}catch(y){let h=y;if(h.code!=="ENOENT"){W.warn("sync generate: fs.access failed (non-ENOENT)",{factId:g.id,absPath:S,error:h.message}),o++;continue}}let f=await ne.write(g,e.workspaceDir);f.ok?a++:(o++,W.warn("sync generate: factFileSync.write failed",{factId:g.id,absPath:S,error:f.error}));}return W.debug("sync stage A complete",{agentId:e.agentId,generatedCount:a,skippedCount:r,failedGenerateCount:o}),{generatedCount:a,skippedCount:r,failedGenerateCount:o}}async function cr(t,e,a,r){let o=a*24*60*60*1e3,c=Date.now(),s=utils.formatLocalISO(new Date(c-o)),i=[],l=[],g=ge__default.default.join(e.workspaceDir,ar),S=await dr(g);W.debug("sync stage B: scan active dir",{activeDir:g,fileCount:S.length,windowDays:a,threshold:s,dryRun:r});for(let f of S){let y=await mr(f);if(!y){W.warn("sync stage B: skip unparseable file",{absPath:f});continue}let{firstCreatedAt:h,firstFactId:R}=y,v=new Date(h).getTime();if(Number.isNaN(v)){W.warn("sync stage B: skip invalid createdAt",{absPath:f,firstCreatedAt:h});continue}if(c-v<=o)continue;let b=lr(f);if(!b){W.warn("sync stage B: cannot infer category from path",{absPath:f});continue}let C=h.slice(0,7),w=ge__default.default.join(e.workspaceDir,ct,C,b),T=ge__default.default.basename(f),E=ge__default.default.join(w,T);if(r){i.push({source:f,target:E,firstCreatedAt:h,firstFactId:R});continue}try{await Q__default.default.mkdir(w,{recursive:!0});try{await Q__default.default.rename(f,E);}catch(p){let D=p;W.warn("sync stage B: fs.rename failed, falling back to copy+unlink",{absPath:f,targetPath:E,error:D.message}),await Q__default.default.copyFile(f,E),await Q__default.default.unlink(f);}let M=re(f,e.workspaceDir),u=re(E,e.workspaceDir);t.run(`UPDATE memory_facts SET file_path = ?
56
- WHERE agent_id = ? AND file_path = ?`,[u,e.agentId??"",M]),i.push({source:f,target:E,firstCreatedAt:h,firstFactId:R});}catch(M){let u=M instanceof Error?M.message:String(M);W.warn("sync stage B: archive failed",{absPath:f,targetPath:E,error:u}),l.push(f);}}return W.debug("sync stage B complete",{agentId:e.agentId,archivedCount:i.length,failedArchiveCount:l.length,dryRun:r}),{archivedCount:i.length,archiveThreshold:s,archivedRecords:i,failedArchivePaths:l}}async function dr(t){let e=[];try{await dt(t,e);}catch(a){let r=a;if(r.code==="ENOENT")return e;throw W.warn("sync: listActiveMdFiles failed",{activeDir:t,error:r.message}),new I(`sync: listActiveMdFiles failed: ${r.message}`,"INTERNAL",{cause:r.message})}return e}async function dt(t,e){let a=await Q__default.default.readdir(t,{withFileTypes:true});for(let r of a){let o=ge__default.default.join(t,r.name);r.isDirectory()?await dt(o,e):r.isFile()&&r.name.endsWith(".md")&&e.push(o);}}async function mr(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(`---
57
- `))return null;let a=e.indexOf(`
58
- ---
59
- `,4);if(a===-1)return null;let r=e.slice(4,a),o,c;for(let s of r.split(`
60
- `)){let i=s.trim();if(i.startsWith("created_at:")?o=i.slice(11).trim().replace(/^["']|["']$/g,""):i.startsWith("id:")&&(c=i.slice(3).trim().replace(/^["']|["']$/g,"")),o&&c)break}return !o||!c?null:{firstCreatedAt:o,firstFactId:c}}function lr(t){let e=t.replace(/\\/g,"/").split("/"),a=e.findIndex(c=>c==="active");if(a===-1)return null;let r=e.slice(a+1);return r.length!==2||!r[1].endsWith(".md")?null:r[0]??null}async function mt(t,e={}){let a=Date.now();$(t),z(t,"sync");let r=e.windowDays??t.config?.archiveDays??or,o=e.dryRun??false;W.info("sync invoked",{agentId:t.agentId,windowDays:r,dryRun:o,workspaceDir:t.workspaceDir});let c=new chunkLYBUZDJK_cjs.e(t.dbPath);try{await c.initialize();let s=await ir(c,t),i=await cr(c,t,r,o),l={generatedCount:s.generatedCount,skippedCount:s.skippedCount,failedGenerateCount:s.failedGenerateCount,archivedCount:i.archivedCount,failedArchivePaths:i.failedArchivePaths,archiveThreshold:i.archiveThreshold,archivedRecords:i.archivedRecords,windowDays:r,dryRun:o,durationMs:Date.now()-a};if(W.info("sync complete",{agentId:t.agentId,...l}),l.failedArchivePaths.length>0)throw new I(`sync: ${l.failedArchivePaths.length} archive(s) failed: ${l.failedArchivePaths.join(", ")}`,"INGEST_FAILED",{failedArchivePaths:l.failedArchivePaths,archivedCount:l.archivedCount});return l}catch(s){throw s instanceof I?s:new I(`sync failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{c.close();}}var lt=utils.Log.create({service:"memory.service.graph-query"});async function gt(t,e){let a=Date.now(),r=(t.agentId??"").trim()||"default",o=e.scope??"agent_only",c=typeof e.nodeId=="number"&&e.nodeId>0,s=typeof e.query=="string"&&e.query.trim().length>0;if(!c&&!s)throw new I("CONTENT_REQUIRED: graphQuery requires either `nodeId` (numeric) or `query` (name fragment for CLI)","CONTENT_REQUIRED");let i=2,l=100,g=e.maxEdgesPerNode??10,S=e.type,f=e.relation;lt.debug("graphQuery invoked",{agentId:r,nodeId:e.nodeId,query:e.query,type:S,depth:i,maxNodes:l,scope:o,remote:t.remote});let y=new chunkLYBUZDJK_cjs.e(t.dbPath);try{await y.initialize();let h=new Z(y.getDb()),R=null;if(c)R=(await h.queryNodes({ids:[e.nodeId],agentId:r,scope:o}))[0]??null;else {let u=e.query,p=u.includes("*")||u.includes("%")?u:`%${u}%`,D=await h.queryNodes({name:p,...S?{type:S}:{},agentId:r,scope:o,limit:l});R=(u.includes("*")||u.includes("%")?D:D.filter(P=>P.name.toLowerCase().includes(u.toLowerCase())))[0]??null;}if(!R)return {root:null,nodes:[],edges:[],truncated:!1,totalNodes:0,totalEdges:0,scope:o,durationMs:Date.now()-a};let v=await h.queryNeighbors(R.id,i,{agentId:r,scope:o,maxEdgesPerNode:g}),b=new Map;b.set(R.id,R);for(let u of v)b.set(u.id,{id:u.id,name:u.name,type:u.type,createdAt:u.createdAt,updatedAt:u.updatedAt});let C=[];for(let u of v)if(u.edges)for(let p of u.edges)f&&p.relation!==f||C.push(p);let w=Array.from(new Map(C.map(u=>[u.id,u])).values());for(let u of w){if(!b.has(u.source)){let p=await h.queryNodes({ids:[u.source],agentId:r,scope:o});p[0]&&b.set(p[0].id,p[0]);}if(!b.has(u.target)){let p=await h.queryNodes({ids:[u.target],agentId:r,scope:o});p[0]&&b.set(p[0].id,p[0]);}}let T=Array.from(b.values()),E=T.length>l,M=E?T.slice(0,l):T;return lt.info("graphQuery complete",{agentId:r,rootId:R.id,nodeCount:M.length,edgeCount:w.length,truncated:E,durationMs:Date.now()-a}),{root:R,nodes:M,edges:w,truncated:E,totalNodes:T.length,totalEdges:w.length,scope:o,durationMs:Date.now()-a}}catch(h){throw h instanceof I?h:new I(`graphQuery failed: ${h instanceof Error?h.message:String(h)}`,"INTERNAL",{cause:h instanceof Error?h.message:String(h)})}finally{y.close();}}var j=utils.Log.create({service:"memory.service.init"});function $e(t){return ge__default.default.join(t,".easbot","memory.json")}async function pr(t){try{let{Config:e}=await import('@easbot/llm'),a=await e.get(),r=o=>typeof o=="string"&&o.length>0?o:void 0;return {embeddingModel:r(a.embedding_model),graphModel:r(a.graph_model)}}catch{return {}}}function yr(t,e={}){let a={version:1,schema_version:chunkLYBUZDJK_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(a,null,2),"utf-8");}async function ut(t,e={}){let a=Date.now();z(t,"init");let r=e.workspaceDir??t.workspaceDir,o=e.dbPath??t.dbPath;if(!r||r.trim().length===0)throw new I("init requires non-empty `workspaceDir` (ctx.workspaceDir or params.workspaceDir)","CONTENT_REQUIRED");if(!o||o.trim().length===0)throw new I("init requires non-empty `dbPath` (ctx.dbPath or params.dbPath)","CONTENT_REQUIRED");let c=t.agentId?.trim()??"",s=e.force??false;j.debug("init invoked",{agentId:c,workspaceDir:r,dbPath:o,force:s});let i=$e(r);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:r,configPath:i}),{initialized:!1,dbPath:o,configPath:i,configCreated:!1,schemaVersion:chunkLYBUZDJK_cjs.a,workspaceDir:r,tablesCreated:0,migrationsApplied:0,durationMs:0}}catch{}try{await Q__default.default.mkdir(ge__default.default.dirname(o),{recursive:!0}),await Q__default.default.mkdir(ge__default.default.join(r,".easbot","memory","active"),{recursive:!0}),await Q__default.default.mkdir(ge__default.default.join(r,"archive"),{recursive:!0}),await Q__default.default.mkdir(ge__default.default.join(r,".easbot"),{recursive:!0});}catch(f){throw new I(`init: failed to create directories: ${f instanceof Error?f.message:String(f)}`,"INTERNAL",{cause:f instanceof Error?f.message:String(f)})}if(s)for(let f of [o,`${o}-wal`,`${o}-shm`])try{await Q__default.default.rm(f,{force:!0});}catch(y){j.warn("init: force rm failed (may not exist)",{path:f,error:y instanceof Error?y.message:String(y)});}let l=await pr(),g=false;try{!await Q__default.default.stat(i).then(()=>!0).catch(()=>!1)||s?(yr(i,{embeddingModel:l.embeddingModel,graphModel:l.graphModel,archiveDays:t.config?.archiveDays,shortTermMaxRounds:t.config?.shortTermMaxRounds}),g=!0,j.info("init: memory.json written",{configPath:i,force:s,configCreated:g})):j.debug("init: memory.json already exists, skipping write",{configPath:i});}catch(f){j.warn("init: memory.json write failed (non-fatal)",{configPath:i,error:f instanceof Error?f.message:String(f)});}let S=new chunkLYBUZDJK_cjs.e(o);try{let f=await Q__default.default.stat(o).then(()=>!0).catch(()=>!1);await S.initialize();let y=new Date().toISOString(),h=[["version","1.0.0"],["schemaVersion",String(chunkLYBUZDJK_cjs.a)],["createdAt",y],["defaultAgentId",c]];for(let[b,C]of h)try{S.run("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)",[b,C]);}catch(w){j.warn("init: meta insert failed",{key:b,error:w instanceof Error?w.message:String(w)});}let R=0;try{R=S.prepare("SELECT COUNT(*) as n FROM sqlite_master WHERE type IN ('table', 'index', 'trigger', 'view')").get()?.n??0;}catch(b){j.warn("init: tablesCreated count failed",{error:b instanceof Error?b.message:String(b)});}let v=0;try{v=S.prepare("SELECT id FROM schema_migrations").all().length;}catch(b){j.warn("init: migrationsApplied count failed",{error:b instanceof Error?b.message:String(b)});}return j.info("init complete",{agentId:c,workspaceDir:r,dbPath:o,configPath:i,configCreated:g,schemaVersion:chunkLYBUZDJK_cjs.a,durationMs:Date.now()-a}),{initialized:!0,dbPath:o,configPath:i,configCreated:g,schemaVersion:chunkLYBUZDJK_cjs.a,workspaceDir:r,tablesCreated:R,migrationsApplied:v,durationMs:Date.now()-a}}catch(f){throw new I(`init failed: ${f instanceof Error?f.message:String(f)}`,"INTERNAL",{cause:f instanceof Error?f.message:String(f)})}finally{S.close();}}var fe=utils.Log.create({service:"memory.service.status"}),wr=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"],Rr={};async function ft(t,e={},a=Rr){let r=t.agentId&&t.agentId.trim().length>0?t.agentId:void 0;if(fe.debug("status invoked",{agentId:r??"<global>"}),!t.dbPath||t.dbPath.length===0)throw new I("`ctx.dbPath` is required","INTERNAL");let o={initialized:false,capabilities:{embedding:false,graphLlm:false}},c={},s={},i=0,l=0,g=0,S,f,y,h=false,R,v="uninitialized",b=false,C=false,w=false,T,E=wr.reduce((D,F)=>(D[F]=0,D),{}),M=new chunkLYBUZDJK_cjs.e(t.dbPath);try{await M.initialize(),i=M.query(r!==void 0?"SELECT COUNT(*) as c FROM memory_facts WHERE agent_id = ?":"SELECT COUNT(*) as c FROM memory_facts WHERE agent_id IS NOT NULL",r!==void 0?[r]:[])[0]?.c??0,l=M.query("SELECT COUNT(*) as c FROM nodes",[])[0]?.c??0,g=M.query("SELECT COUNT(*) as c FROM edges")[0]?.c??0;let G=M.query(r!==void 0?"SELECT category, COUNT(*) as c FROM memory_facts WHERE agent_id = ? GROUP BY category":"SELECT category, COUNT(*) as c FROM memory_facts WHERE agent_id IS NOT NULL GROUP BY category",r!==void 0?[r]:[]);for(let _ of G){let O=_.category;O in E&&(E[O]=_.c);}c.facts=i,c.nodes=l,c.edges=g;try{C=M.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]).length>0;}catch(_){fe.debug("status: fts probe failed",{error:_ instanceof Error?_.message:String(_)});}h=!!t.config?.embeddingLlm,b=!1,w=M.healthCheck();try{let _=M.query("SELECT key, value FROM meta");for(let O of _)s[O.key]=O.value;}catch(_){fe.debug("status: meta read failed",{error:_ instanceof Error?_.message:String(_)});}let B=s.schema_version,V=s.extraction_version,d=s.lastSyncAt??s.lastSync,m=s.embeddingDims;S=B&&Number.parseInt(B,10)||void 0,f=V&&Number.parseInt(V,10)||void 0,y=d,R=m&&Number.parseInt(m,10)||void 0,i>0&&(s.index_state==="failed"?v="failed":y?h&&!R?v="partial":v="complete":v="stale");try{T=M.query("SELECT value FROM meta WHERE key = ?",["backend"])[0]?.value??"better-sqlite3";}catch{T="better-sqlite3";}}catch(D){if(D instanceof I)throw D;fe.warn("status: db phase failed; returning partial result",{dbPath:t.dbPath,error:D instanceof Error?D.message:String(D)}),T="unknown",w=false;}finally{M.close();}if(!a.skipLlm&&chunkJ5XF2W4Z_cjs.a.isInitialized()){let F=chunkJ5XF2W4Z_cjs.a.capabilities();o.initialized=true,o.capabilities={embedding:F.embedding===true,graphLlm:F.graphLlm===true},o.embeddingModel=o.capabilities.embedding?"configured":void 0,o.graphModel=o.capabilities.graphLlm?"configured":void 0;}if(!a.skipEmbeddingProbe&&!a.skipLlm&&o.initialized&&o.capabilities.embedding)try{let D=chunkJ5XF2W4Z_cjs.a.getEmbeddingLlm?.();if(D){let F=await llm.probeEmbeddingDims(D,{timeoutMs:5e3});if(typeof F=="number"){R=F,s.embeddingDims=String(F);try{let P=new chunkLYBUZDJK_cjs.e(t.dbPath);try{await P.initialize();let G=P.getDb();llm.syncMeta(G,[["embeddingDims",String(F)]]);}finally{P.close();}}catch{}}}}catch{}let u;return w?v==="uninitialized"&&(u="Run `easbot memory remember <content>` to add the first fact."):u="Run `easbot memory init` to initialize the database.",w&&(v??"uninitialized")==="failed"&&(w=false),fe.info("status complete",{dbPath:t.dbPath,agentId:r??"<global>",factsCount:i,nodesCount:l,edgesCount:g,healthy:w}),{package:"memory",agentId:r,dbPath:t.dbPath,configPath:$e(t.workspaceDir),configExists:true,schemaVersion:S,extractionVersion:f,lastSyncAt:y,indexState:v,vectorEnabled:h,embeddingDims:R,llm:o,backend:T,counts:c,meta:s,recommendation:u,healthy:w,factsByCategory:E,kgScopeEnabled:b,factsCount:i,nodesCount:l,edgesCount:g,ftsAvailable:C}}var vr=utils.Log.create({service:"memory.service.doctor"}),Ue=100*1024*1024,pt=100*1024*1024,Dr={};function N(t,e,a,r,o){return {code:t.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),severity:e,name:t,message:a,details:o,durationMs:r,passed:e!=="error"}}async function yt(t,e={},a=Dr){if(vr.debug("doctor invoked",{agentId:t.agentId}),!t.dbPath||t.dbPath.length===0)throw new Error("`ctx.dbPath` is required");let r=[],o=[],c=Date.now(),s=null,i=false,l=Date.now();try{s=new chunkLYBUZDJK_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()-l,{dbPath:t.dbPath});r.push(m),o.push({name:m.name,passed:m.severity!=="error",message:m.message,details:m.details,severity:m.severity});}catch(d){let m=N("database","error",`database connection failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-l,{dbPath:t.dbPath});r.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}let g=Date.now();if(i&&s)try{let d=s.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]),m=d.length>0,_=N("fts",m?"ok":"warn",m?"FTS5 index available":"FTS5 index not found",Date.now()-g,m?{table:d[0]?.name}:void 0);r.push(_),o.push({name:_.name,passed:_.severity!=="error",message:_.message,details:_.details,severity:_.severity});}catch(d){let m=N("fts","error",`fts probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-g);r.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}else {let d=N("fts","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let S=Date.now(),f=!!t.config?.embeddingLlm,y=N("vector","ok",f?"embedding model available":"no embedding model configured (FTS-only mode, recall still functional)",Date.now()-S,{mode:f?"hybrid":"fts_only",model:f?"configured":"missing"});r.push(y),o.push({name:y.name,passed:true,message:y.message,details:y.details,severity:"ok"});let h=Date.now();if(i&&s)try{let d=["memory_facts","nodes","edges","meta"],m=s.query("SELECT name FROM sqlite_master WHERE type = ?",["table"]),_=new Set(m.map(q=>q.name)),O=d.filter(q=>!_.has(q)),A=N("schema",O.length===0?"ok":"error",O.length===0?`schema complete (${d.length} tables)`:`missing tables: ${O.join(", ")}`,Date.now()-h,{required:d,existing:Array.from(_)});r.push(A),o.push({name:A.name,passed:A.severity!=="error",message:A.message,details:A.details,severity:A.severity});}catch(d){let m=N("schema","error",`schema probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-h);r.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}else {let d=N("schema","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let R=Date.now();try{let d=`${t.dbPath}-wal`,m=`${t.dbPath}-shm`,_=0,O=0;try{_=(await Q__default.default.stat(d)).size;}catch{_=0;}try{O=(await Q__default.default.stat(m)).size;}catch{O=0;}let A=_+O,q=A<=pt,H=N("lock",q?"ok":"warn",q?`no lock contention (wal+shm ${(A/1024).toFixed(1)} KB)`:`WAL/SHM files unusually large (${(A/1024/1024).toFixed(1)} MB > ${(pt/1024/1024).toFixed(0)} MB threshold)`,Date.now()-R,{walBytes:_,shmBytes:O});r.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()-R);r.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}let v=Date.now();try{let d=ge__default.default.dirname(t.dbPath),m=await Q__default.default.statfs(d),_=typeof m.bsize=="bigint"?Number(m.bsize)*m.bavail:m.bsize*m.bavail,O=_>=Ue,A=N("disk_space",O?"ok":"error",O?`sufficient disk space (${(_/1024/1024).toFixed(1)} MB available)`:`low disk space (${(_/1024/1024).toFixed(1)} MB < ${(Ue/1024/1024).toFixed(0)} MB threshold)`,Date.now()-v,{availableBytes:_,threshold:Ue});r.push(A),o.push({name:A.name,passed:A.severity!=="error",message:A.message,details:A.details,severity:A.severity});}catch(d){let m=N("disk_space","error",`disk_space probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-v);r.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}let b=Date.now();if(i&&s)try{let d=s.agentFilter(t.agentId),_=s.query(`SELECT COUNT(*) as c FROM memory_facts ${d.where}`,d.params)[0]?.c??0;if(_===0){let O=N("fact_node_consistency","info","no facts in db \u2014 nothing to check",Date.now()-b);r.push(O),o.push({name:O.name,passed:!0,message:O.message,severity:"info"});}else {let A=s.query(`SELECT COUNT(DISTINCT fn.fact_id) as c
61
- FROM fact_nodes fn
62
- INNER JOIN memory_facts mf ON mf.id = fn.fact_id
63
- ${d.where}`,d.params)[0]?.c??0,q=_>0?A/_*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()-b,{facts:_,linked:A,pct:q});r.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()-b);r.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"warn"});}else {let d=N("fact_node_consistency","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let C=Date.now();if(i&&s)try{let m=s.query("SELECT COUNT(*) as c FROM nodes",[])[0]?.c??0;if(m===0){let _=N("node_embedding_coverage","info","no nodes in KG \u2014 nothing to check",Date.now()-C);r.push(_),o.push({name:_.name,passed:!0,message:_.message,severity:"info"});}else {let O=s.query("SELECT COUNT(*) as c FROM nodes WHERE embedding IS NOT NULL",[])[0]?.c??0,A=m>0?O/m*100:0,q=A>=50?"ok":A>=30?"info":"warn",H=A>=50?`${A.toFixed(1)}% nodes have embedding (${O}/${m})`:A>=30?`${A.toFixed(1)}% nodes have embedding (${O}/${m}) \u2014 GraphRAG entity vector partial`:`${A.toFixed(1)}% nodes have embedding (${O}/${m}) \u2014 GraphRAG entity vector disabled`,U=N("node_embedding_coverage",q,H,Date.now()-C,{total:m,withEmbedding:O,pct:A});r.push(U),o.push({name:U.name,passed:U.severity!=="error",message:U.message,details:U.details,severity:U.severity});}}catch(d){let m=N("node_embedding_coverage","warn",`node_embedding_coverage probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-C);r.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"warn"});}else {let d=N("node_embedding_coverage","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let w=Date.now();if(i&&s)try{let m=s.query(`SELECT fn.fact_id, fn.node_id
64
- FROM fact_nodes fn
65
- LEFT JOIN nodes n ON fn.node_id = n.id
66
- WHERE n.id IS NULL
67
- LIMIT 100`).map(O=>`${O.fact_id}->${O.node_id}`),_=N("orphan",m.length===0?"ok":"warn",m.length===0?"no orphan KG references (fact_nodes all resolved)":`${m.length} orphan fact_nodes references: ${m.slice(0,5).join(", ")}${m.length>5?", ...":""}`,Date.now()-w,{count:m.length});r.push(_),o.push({name:_.name,passed:_.severity!=="error",message:_.message,details:_.details,severity:_.severity});}catch(d){let m=N("orphan","warn",`orphan probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-w);r.push(m),o.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"warn"});}else {let d=N("orphan","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let T=Date.now(),E={"better-sqlite3":false,"node:sqlite":false,"@tursodatabase/database":false};try{let d=module$1.createRequire(chunkM2YU5LAI_cjs.b);try{d.resolve("better-sqlite3"),E["better-sqlite3"]=!0;}catch{}E["node:sqlite"]=typeof process.versions.sqlite=="string";try{d.resolve("@tursodatabase/database"),E["@tursodatabase/database"]=!0;}catch{}}catch{}let M=E["better-sqlite3"]||E["node:sqlite"],u=N("backend",M?"ok":"error",M?`SQLite backend available (better-sqlite3: ${E["better-sqlite3"]}, node:sqlite: ${E["node:sqlite"]})`:"no SQLite backend available (install better-sqlite3 or use Node 22.5+)",Date.now()-T,E);r.push(u),o.push({name:u.name,passed:u.severity!=="error",message:u.message,details:u.details,severity:u.severity});let p=Date.now();if(i&&s)try{let d=s.query("SELECT COUNT(*) as c FROM embedding_cache")[0],m=s.agentFilter(t.agentId),_=s.query(`SELECT COUNT(*) as c FROM memory_facts ${m.where}`,m.params)[0],O=d?.c??0,A=_?.c??0,q=Math.max(0,O-A),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()-p,{cacheCount:O,factsCount:A,unused:q,policy:"global_content_hash_dedup"});r.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()-p);r.push(m),o.push({name:m.name,passed:true,message:m.message,severity:"info"});}else {let d=N("embedding_cache_unused","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let D=Date.now(),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 P;if(a.skipLlm||!chunkJ5XF2W4Z_cjs.a.isInitialized()||!chunkJ5XF2W4Z_cjs.a.capabilities().embedding)P=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","llm not initialized; probe skipped",Date.now()-D);else if(a.skipEmbeddingProbe)P=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe skipped (--skip-embedding-probe)",Date.now()-D);else try{let d=chunkJ5XF2W4Z_cjs.a.getEmbeddingLlm?.();if(!d)P=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","embedding llm not exposed; probe skipped",Date.now()-D);else {let m=await llm.probeEmbeddingDims(d,{timeoutMs:5e3});typeof m!="number"?P=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe failed (network / model error)",Date.now()-D):F===void 0?P=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe=${m}, meta missing \u2014 next status will sync`,Date.now()-D):m!==F?P=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"warn",`probe=${m}, meta=${F} \u2014 mismatch`,Date.now()-D,{probe:m,meta:F}):P=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"ok",`probe=${m}, meta=${F} \u2014 consistent`,Date.now()-D);}}catch(d){P=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe threw: ${d instanceof Error?d.message:String(d)}`,Date.now()-D);}r.push({...P,details:P.details??void 0,passed:P.severity!=="error"}),o.push({name:P.name,passed:P.severity!=="error",message:P.message,details:P.details??void 0,severity:P.severity});let G;if(i&&s){let d=Date.now();try{let{issues:m,stats:_}=s.checkIntegrity();G=_;for(let O of m)r.push(N("integrity_stats",O.severity,O.message,0,{source:"database.checkIntegrity"}));}catch(m){r.push(N("integrity_stats","warn",`db integrity check failed: ${m instanceof Error?m.message:String(m)}`,Date.now()-d));}}let B=!r.some(d=>d.severity==="error");s&&s.close();let V=Date.now()-c;return {healthy:B,checks:r,legacyChecks:o,durationMs:V,integrityStats:G,backendAvailable:E}}var We={name:"recall",scope:"read",schema:Ee,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=Ee.parse(t);if(!e.agentId?.trim())throw new Error("recall: agentId is required");return et({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 Ge={name:"remember",scope:"write",schema:we,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=we.parse(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 je={name:"update",scope:"write",schema:Re,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=Re.parse(t);if(!e.agentId?.trim())throw new Error("update: agentId is required");return nt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var Be={name:"forget",scope:"write",schema:Se,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=Se.parse(t);if(!e.agentId?.trim())throw new Error("forget: agentId is required");return ot({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var ze={name:"extract",scope:"write",schema:Ie,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=Ie.parse(t);if(!e.agentId?.trim())throw new Error("extract: 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 Qe={name:"consolidate",scope:"admin",schema:Me,annotations:{localOnly:true,requiresAgentId:true,defaultDescription:"Run consolidation pipeline: dedup \u2192 archive.",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let r=Me.parse(t);if(!e.isTrustedLocal)throw new Error("consolidate: only trusted local process can invoke this op");if(!e.agentId?.trim())throw new Error("consolidate: agentId is required");return it({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},r)}};var Ke={name:"sync",scope:"admin",schema:Ne,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=Ne.parse(t);if(!e.isTrustedLocal)throw new Error("sync: only trusted local process can invoke this op");if(!e.agentId?.trim())throw new Error("sync: agentId is required");return mt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},r)}};var Ve={name:"graph_query",scope:"read",schema:_e,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"BFS KG neighbor walk from nodeId (default depth=2, maxNodes=100, maxEdgesPerNode=10/100); CLI may also use name fragment via `query`.",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=_e.parse(t),o=e.agentId?.trim()||"default";return gt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:o},r)}};var Je={name:"status",scope:"read",schema:ve,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=ve.parse(t??{})??{}??{};return ft({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 Ye={name:"doctor",scope:"admin",schema:De,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=De.parse(t??{})??{}??{};if(!e.isTrustedLocal)throw new Error("doctor: only trusted local process can invoke this op");return yt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},r)}};var Xe={name:"init",scope:"admin",schema:Ce,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=Ce.parse(t??{})??{}??{};return ut({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 ht={[We.name]:We,[Ge.name]:Ge,[je.name]:je,[Be.name]:Be,[ze.name]:ze,[Qe.name]:Qe,[Ke.name]:Ke,[Ve.name]:Ve,[Je.name]:Je,[Ye.name]:Ye,[Xe.name]:Xe},Cr=Object.values(ht);function Nr(t,e,a){if(t.annotations.localOnly&&!e.isTrustedLocal)throw new Error(`MEMORY:executeOp: op "${a}" is localOnly; non-trusted caller rejected`);if(t.annotations.requiresAgentId){let r=e.agentId?.trim()??"";if(r.length===0)throw new Error(`MEMORY:executeOp: op "${a}" requires agentId`);e.agentId=r;}}async function za(t,e,a){let r=ht[t];if(!r)throw new Error(`executeOp: unknown op "${t}"; available: ${Cr.map(c=>c.name).join(", ")}`);return Nr(r,a,t),await r.handler(e,a)}function Pr(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 ts(t,e,a={}){let r=chunkCPRDIUQ4_cjs.j(e),o=utils.Locale.resolveLocaleLang(a.locale);return {agentId:t,dbPath:r,workspaceDir:e,rootDir:e,config:Pr({dbPath:r,workspaceDir:e}),isTrustedLocal:true,locale:o,remote:false,...a}}exports.A=Pr;exports.B=ts;exports.a=Z;exports.b=et;exports.c=Ee;exports.d=we;exports.e=Re;exports.f=Se;exports.g=Ie;exports.h=Me;exports.i=_e;exports.j=ve;exports.k=De;exports.l=Ce;exports.m=Ne;exports.n=rt;exports.o=nt;exports.p=ot;exports.q=st;exports.r=it;exports.s=mt;exports.t=gt;exports.u=ut;exports.v=ft;exports.w=yt;exports.x=ht;exports.y=Cr;exports.z=za;