@easbot/memory 0.3.13 → 0.3.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.en.md +216 -38
  2. package/README.md +213 -38
  3. package/dist/chunks/chunk-3HTZTI7U.cjs +1 -0
  4. package/dist/chunks/chunk-5W4K5UKV.mjs +53 -0
  5. package/dist/chunks/chunk-7XEOH55R.cjs +1 -0
  6. package/dist/chunks/chunk-BWPPLYIF.cjs +1 -0
  7. package/dist/chunks/chunk-FEMOFIOS.mjs +1 -0
  8. package/dist/chunks/chunk-FNT7WEHL.mjs +1 -0
  9. package/dist/chunks/chunk-I5YWAJHW.cjs +32 -0
  10. package/dist/chunks/chunk-JGXW3E73.mjs +59 -0
  11. package/dist/chunks/chunk-MQ72K25M.cjs +59 -0
  12. package/dist/chunks/chunk-NJVXQ7TV.cjs +1 -0
  13. package/dist/chunks/chunk-OWLFPNZG.cjs +1 -0
  14. package/dist/chunks/chunk-PWLSQFYA.mjs +32 -0
  15. package/dist/chunks/chunk-Q2MKNRER.cjs +53 -0
  16. package/dist/chunks/chunk-QF5S5MG7.mjs +0 -0
  17. package/dist/chunks/chunk-URADAZYW.cjs +1 -0
  18. package/dist/chunks/chunk-WQGSYA5D.mjs +1 -0
  19. package/dist/chunks/chunk-YHOJKRHE.mjs +1 -0
  20. package/dist/chunks/chunk-Z3NQERNT.mjs +1 -0
  21. package/dist/chunks/cli-handler-57MKQCNO.cjs +1 -0
  22. package/dist/chunks/cli-handler-WW3I2YV4.mjs +1 -0
  23. package/dist/chunks/config-BFJFRX2C.cjs +1 -0
  24. package/dist/chunks/config-M2KZYVRZ.mjs +1 -0
  25. package/dist/chunks/consolidate-YQ3H643L.cjs +2 -0
  26. package/dist/chunks/consolidate-ZCFRYIWV.mjs +2 -0
  27. package/dist/chunks/doctor-GVSMK4HL.cjs +2 -0
  28. package/dist/chunks/doctor-SPJ64FW3.mjs +2 -0
  29. package/dist/chunks/extract-5VSCY754.mjs +2 -0
  30. package/dist/chunks/extract-E54PPHMQ.cjs +2 -0
  31. package/dist/chunks/forget-AALO5DL5.mjs +3 -0
  32. package/dist/chunks/forget-GEAEUNRH.cjs +3 -0
  33. package/dist/chunks/graph-HSYCZI7R.mjs +3 -0
  34. package/dist/chunks/graph-QEGKUROQ.cjs +3 -0
  35. package/dist/chunks/init-2GZLH6RB.cjs +2 -0
  36. package/dist/chunks/init-U7XRD4MW.mjs +2 -0
  37. package/dist/chunks/interfaces-KNVKCV3Q.cjs +1 -0
  38. package/dist/chunks/interfaces-VBO3Z6QF.mjs +1 -0
  39. package/dist/chunks/mcp-WE7TV32J.cjs +1 -0
  40. package/dist/chunks/mcp-XPTJOCQA.mjs +1 -0
  41. package/dist/chunks/recall-JI2NYDLH.cjs +2 -0
  42. package/dist/chunks/recall-M6SAHHZX.mjs +2 -0
  43. package/dist/chunks/remember-FR5QGXFT.mjs +2 -0
  44. package/dist/chunks/remember-X33PMYA5.cjs +2 -0
  45. package/dist/chunks/status-6XW6Q3TT.mjs +2 -0
  46. package/dist/chunks/status-CPB6XZNU.cjs +2 -0
  47. package/dist/chunks/stdio-server-5LE3HFKN.mjs +1 -0
  48. package/dist/chunks/stdio-server-6PUOFDLR.cjs +1 -0
  49. package/dist/cli.cjs +2 -0
  50. package/dist/cli.d.cts +1 -0
  51. package/dist/cli.d.ts +1 -0
  52. package/dist/cli.mjs +2 -0
  53. package/dist/index.cjs +6 -146
  54. package/dist/index.d.cts +354 -170
  55. package/dist/index.d.ts +354 -170
  56. package/dist/index.mjs +6 -146
  57. package/package.json +21 -14
@@ -0,0 +1 @@
1
+ 'use strict';var n=Object.defineProperty;var c=(e,t,r)=>t in e?n(e,t,{enumerable:true,configurable:true,writable:true,value:r}):e[t]=r;var m=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var p=(e,t,r)=>c(e,typeof t!="symbol"?t+"":t,r);var o=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,a=o();exports.a=m;exports.b=p;exports.c=a;
@@ -0,0 +1 @@
1
+ import {f}from'./chunk-YHOJKRHE.mjs';import {Log}from'@easbot/utils';import {renderLines,printHuman,emitJsonOk,emitJsonError}from'@easbot/terminal';var h=Log.create({service:"memory-cli"}),w=[{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.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 9 memory tools)",group:"external"}];function m(d,p){let o=w.filter(a=>a.group===d);return renderLines({title:p,flat:o.map(a=>`$ easbot-memory ${a.name.padEnd(14)} ${a.description}`)})}function x(){let d=[renderLines({title:"easbot-memory \xB7 Memory & Knowledge Module for EASBot",flat:["Usage: easbot-memory <command> [options]"]}),"",m("lifecycle","Commands (lifecycle):"),"",m("memory","Commands (memory):"),"",m("session","Commands (session):"),"",m("graph","Commands (graph query):"),"",m("external","External:")];printHuman(d);}function b(){x(),printHuman(["",renderLines({title:"Global flags & invocation",flat:["--cwd <dir> --config <path> --log-level <L> --print-logs --debug","Standalone CLI: easbot-memory <command>","Agent CLI: easbot memory <command>"]})]);}async function K(d,p){let[o,...a]=d,l=p?.cwd??process.cwd();if(!o)return b(),{code:0,handled:true,command:null};try{switch(o){case "init":{let{parseInitOptions:r,runInit:n,formatInitText:s}=await import('./init-U7XRD4MW.mjs'),e=r(a);if(e.help)return console.log("Usage: easbot-memory init --workspace-dir <dir> [--agent <id>] [--force] [--json]"),{code:0,handled:!0,command:o};let t=await n({...e,ctxWorkspaceDir:l});return e.json?emitJsonOk(t,{command:o}):printHuman([s(t)],{title:"init memory workspace"}),{code:0,handled:!0,command:o}}case "recall":{let{parseRecallOptions:r,runRecall:n,formatRecallText:s}=await import('./recall-M6SAHHZX.mjs'),e=r(a);if(e.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:o};let t=await n({...e,workspaceDir:l});return e.json?emitJsonOk(t,{command:o}):printHuman([s(t)],{title:`recall (agentId=${e.agentId??"default"})`}),{code:0,handled:!0,command:o}}case "remember":{let{parseRememberOptions:r,runRemember:n,formatRememberText:s}=await import('./remember-FR5QGXFT.mjs'),e=r(a);if(e.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:o};let t=await n({...e,workspaceDir:l});return e.json?emitJsonOk(t,{command:o}):printHuman([s(t)],{title:"remember (persist fact)"}),{code:0,handled:!0,command:o}}case "forget":{let{parseForgetOptions:r,runForget:n,formatForgetText:s}=await import('./forget-AALO5DL5.mjs'),e=r(a);if(e.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:o};let t=await n({...e,workspaceDir:l});return e.json?emitJsonOk(t,{command:o}):printHuman([s(t)],{title:"forget (delete facts)"}),{code:0,handled:!0,command:o}}case "extract":{let{parseExtractOptions:r,runExtract:n,formatExtractText:s}=await import('./extract-5VSCY754.mjs'),e=r(a);if(e.help)return console.log("Usage: easbot-memory extract --session <sessionId> [--agent <id>] [--last-n <n>] [--from-msg <id>] [--json]"),{code:0,handled:!0,command:o};let t=await n({...e,workspaceDir:l});return e.json?emitJsonOk(t,{command:o}):printHuman([s(t)],{title:"extract (from session)"}),{code:0,handled:!0,command:o}}case "consolidate":{let{parseConsolidateOptions:r,runConsolidate:n,formatConsolidateText:s}=await import('./consolidate-ZCFRYIWV.mjs'),e=r(a);if(e.help)return console.log("Usage: easbot-memory consolidate [--agent <id>] [--window-days <n>] [--json]"),{code:0,handled:!0,command:o};let t=await n({...e,workspaceDir:l});return e.json?emitJsonOk(t,{command:o}):printHuman([s(t)],{title:"consolidate (pipeline)"}),{code:0,handled:!0,command:o}}case "graph":{let{parseGraphOptions:r,runGraph:n,formatGraphText:s}=await import('./graph-HSYCZI7R.mjs'),e=r(a);if(e.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:o};let t=await n({...e,workspaceDir:l});return e.json?emitJsonOk(t,{command:o}):printHuman([s(t)],{title:`graph_query (scope=${e.scope??"agent_only"})`}),{code:0,handled:!0,command:o}}case "status":{let{parseStatusOptions:r,runStatus:n,formatStatusText:s}=await import('./status-6XW6Q3TT.mjs'),e=r(a);if(e.help)return console.log("Usage: easbot-memory status [--agent <id>] [--json]"),{code:0,handled:!0,command:o};let t=await n({...e,workspaceDir:l});return e.json?emitJsonOk(t,{command:o}):printHuman([s(t)],{title:"memory status"}),{code:0,handled:!0,command:o}}case "doctor":{let{parseDoctorOptions:r,runDoctor:n,formatDoctorText:s}=await import('./doctor-SPJ64FW3.mjs'),e=r(a);if(e.help)return console.log("Usage: easbot-memory doctor [--repair] [--json]"),{code:0,handled:!0,command:o};let t=await n({...e,workspaceDir:l});return e.json?emitJsonOk(t,{command:o}):printHuman([s(t)],{title:"doctor"}),{code:0,handled:!0,command:o}}case "config":{let{parseConfigOptions:r,runConfig:n,formatConfigText:s}=await import('./config-M2KZYVRZ.mjs'),e=r(a);if(e.help)return console.log("Usage: easbot-memory config [--json]"),{code:0,handled:!0,command:o};let t=n(e);return e.json?emitJsonOk(t,{command:o}):printHuman([s(t)],{title:"memory config"}),{code:0,handled:!0,command:o}}case "mcp":{let{parseMcpOptions:r,runMcp:n}=await import('./mcp-XPTJOCQA.mjs'),s=r(a);if(s.help)return console.log("Usage: easbot-memory mcp [start]"),console.log("Start a stdio MCP server exposing 9 memory tools:"),console.log(" recall / remember / forget / extract / consolidate"),console.log(" graph_query / status / doctor / init"),{code:0,handled:!0,command:o};let e=await n(s);return s.json?emitJsonOk(e,{command:o}):printHuman([`memory mcp started (tools: ${e.tools.length})`],{title:"memory mcp server"}),{code:0,handled:!0,command:o}}default:return console.error(`Unknown command: ${o}`),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);h.error("memory CLI command failed",{command:o,error:n,stack:r instanceof Error?r.stack:void 0});let s=p?.cwd??f().worktree;return console.error(`[memory] ${s} :: ${o} failed: ${n}`),emitJsonError(o,n),{code:1,handled:true,command:o}}}export{w as a,x as b,b as c,K as d};
@@ -0,0 +1 @@
1
+ import {a}from'./chunk-Z3NQERNT.mjs';function s(r,t){return a(`memory.${r}.empty`,{fallback:t})}function g(r,t,m){return a(`memory.${r}.summary`,{vars:t,fallback:m})}function u(r,t,m){return a(`memory.${r}.item`,{vars:t,fallback:m})}export{s as a,g as b,u as c};
@@ -0,0 +1,32 @@
1
+ 'use strict';var chunkQ2MKNRER_cjs=require('./chunk-Q2MKNRER.cjs'),chunk3HTZTI7U_cjs=require('./chunk-3HTZTI7U.cjs'),chunkBWPPLYIF_cjs=require('./chunk-BWPPLYIF.cjs'),utils=require('@easbot/utils'),crypto=require('crypto'),B=require('path'),x=require('fs/promises'),zod=require('zod'),types=require('@easbot/types');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var B__default=/*#__PURE__*/_interopDefault(B);var x__default=/*#__PURE__*/_interopDefault(x);var L=utils.Log.create({service:"memory.graph-store"}),C=class{constructor(e){chunkBWPPLYIF_cjs.b(this,"db");this.db=e;}async upsertNode(e,n,o,i){let l=Date.now(),a=JSON.stringify(o??{}),s=this.db.prepare("SELECT id FROM nodes WHERE name = ? AND type = ? LIMIT 1").get(e,n);if(s)return this.db.prepare("UPDATE nodes SET properties = ?, updatedAt = ? WHERE id = ?").run(a,l,s.id),s.id;let c=this.db.prepare("INSERT INTO nodes (name, type, properties, owner_agent_id, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)").run(e,n,a,i??null,l,l);return Number(c.lastInsertRowid)}async deleteNode(e){this.db.prepare("DELETE FROM nodes WHERE id = ?").run(e);}async upsertEdge(e,n,o,i){let l=this.db.prepare("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)").run(e,n,o,JSON.stringify(i??{}),Date.now());return Number(l.lastInsertRowid)}async queryNodes(e={}){let n="SELECT id, name, type, properties, owner_agent_id, createdAt, updatedAt FROM nodes",o=[],i=[];if(e.ids&&e.ids.length>0){let a=e.ids.map(s=>typeof s=="string"?parseInt(s,10):s).filter(s=>!Number.isNaN(s));i.push(`id IN (${a.map(()=>"?").join(", ")})`),o.push(...a);}e.name&&(i.push("name LIKE ?"),o.push(`%${e.name}%`)),e.type&&(i.push("type = ?"),o.push(e.type)),ke(i,o,e.agentId,e.scope??"agent_only"),i.length>0&&(n+=` WHERE ${i.join(" AND ")}`),n+=" ORDER BY id",e.limit&&(n+=" LIMIT ?",o.push(e.limit)),L.debug("queryNodes",{sql:n,params:o,filter:e});let l=this.db.prepare(n).all(...o);return L.debug("queryNodes result",{count:l.length}),l.map(a=>({id:a.id,name:a.name,type:a.type,properties:a.properties?JSON.parse(a.properties):void 0,createdAt:a.createdAt,updatedAt:a.updatedAt,ownerAgentId:a.owner_agent_id}))}async queryEdges(e={}){let n="SELECT e.id, e.source, e.target, e.relation, e.properties, e.createdAt FROM edges e",o=[],i=[];if(e.ids&&e.ids.length>0&&(i.push(`e.id IN (${e.ids.map(()=>"?").join(", ")})`),o.push(...e.ids)),e.source!==void 0&&(i.push("e.source = ?"),o.push(e.source)),e.target!==void 0&&(i.push("e.target = ?"),o.push(e.target)),e.sourceOrTarget&&e.sourceOrTarget.length>0){let m=e.sourceOrTarget.map(d=>typeof d=="string"?parseInt(d,10):d).filter(d=>!Number.isNaN(d));i.push(`(e.source IN (${m.map(()=>"?").join(", ")}) OR e.target IN (${m.map(()=>"?").join(", ")}))`),o.push(...m,...m);}e.relation&&(i.push("e.relation = ?"),o.push(e.relation)),i.length>0&&(n+=` WHERE ${i.join(" AND ")}`),n+=" ORDER BY e.id",e.limit&&(n+=" LIMIT ?",o.push(e.limit)),L.debug("queryEdges",{sql:n,params:o,filter:e});let l=this.db.prepare(n).all(...o);L.debug("queryEdges result",{count:l.length});let a=[...new Set(l.map(m=>m.target))],s=a.length>0?await this.queryNodes({ids:a,limit:a.length}):[],c=new Map(s.map(m=>[m.id,m]));return l.map(m=>{let d={id:m.id,source:m.source,target:m.target,relation:m.relation,properties:m.properties?JSON.parse(m.properties):void 0,createdAt:m.createdAt},f=c.get(m.target);return f&&(d.targetNode=f),d})}async queryNeighbors(e,n=1,o){let i=o?.agentId,l=o?.scope??"agent_only",a=new Set,s=[{id:e,level:0}],c=[],m=o?.maxEdgesPerNode??50;for(;s.length>0;){let d=s.shift();if(!d)break;if(a.has(d.id)||d.level>n)continue;a.add(d.id);let h=(await this.queryNodes({ids:[d.id],limit:1,agentId:i,scope:l}))[0];if(!h)continue;let b=await this.queryEdges({sourceOrTarget:[d.id],limit:m}),y=i?await Pe(this,b,i,l):b;if(c.push({...h,edges:y}),d.level<n)for(let E of y){let u=E.source===d.id?E.target:E.source;a.has(u)||s.push({id:u,level:d.level+1});}}return c}};async function Pe(t,e,n,o){if(e.length===0)return e;let i=new Set;for(let s of e)i.add(s.source),i.add(s.target);let l=await t.queryNodes({ids:Array.from(i),agentId:n,scope:o,limit:i.size}),a=new Set(l.map(s=>s.id));return e.filter(s=>a.has(s.source)&&a.has(s.target))}function ke(t,e,n,o){if(n)switch(o){case "agent_only":t.push("owner_agent_id = ?"),e.push(n);break;case "shared_only":t.push("owner_agent_id IS NULL");break;case "both":t.push("(owner_agent_id = ? OR owner_agent_id IS NULL)"),e.push(n);break}}var g=class extends Error{constructor(n,o,i){super(n);chunkBWPPLYIF_cjs.b(this,"code",o);chunkBWPPLYIF_cjs.b(this,"details",i);this.name="ServiceError";}};var q=class extends g{constructor(){super("ctx.agentId is required for memory service (ADR 0055 per-agent isolation)","AGENT_ID_REQUIRED");}},v=class extends g{constructor(e,n){super(`Trust denied for operation "${e}": ${n}`,"TRUST_DENIED",{operation:e,reason:n});}},A=class extends g{constructor(e,n){super(`Memory ${e} has ${n} references (force=false)`,"HAS_REFERENCES",{memoryId:e,referenceCount:n});}},P=class extends g{constructor(e){super(`dryRun mode: ${e} memories matched but not deleted`,"DRY_RUN_NO_DELETE",{matchedCount:e});}},k=class extends g{constructor(e,n){super(`Matched ${e} memories exceeds maxDelete=${n}`,"MAX_DELETE_EXCEEDED",{matched:e,maxDelete:n});}};function D(t){if(typeof t.agentId!="string"||t.agentId.length===0)throw new q}function N(t,e){if(t.remote!==false)throw new v(e,"requires trusted local caller (CLI / agent tool / MCP with remote=false)")}function F(t,e,n){if(e!=="agent_only"&&t.remote!==false)throw new v(n,`scope="${e}" requires trusted local caller (cross-agent access denied)`)}function H(t){if(!t.dbPath||t.dbPath.trim().length===0)throw new g("service ctx.dbPath is required (MemoryKnowledgeConfigWithModels.database.path)","INTERNAL")}var W=utils.Log.create({service:"memory.service.recall"});async function de(t,e){let n=Date.now();if(D(t),H(t),!e.query||e.query.trim().length===0)throw new g("recall requires non-empty `query`","CONTENT_REQUIRED");let o=e.includeShared?"both":"agent_only";e.includeGraph&&F(t,o,"recall"),W.debug("recall invoked",{agentId:t.agentId,query:e.query,category:e.category,maxResults:e.maxResults,includeGraph:e.includeGraph,scope:o});let i=e.maxResults??10,l=e.minScore??0,a=[],s=new chunkQ2MKNRER_cjs.e(t.dbPath);try{await s.initialize();let c=await Le(s,t.agentId,e.query,{category:e.category,minImportance:e.minImportance,fromTime:e.fromTime,toTime:e.toTime,limit:i,minScore:l}),m;if(e.includeGraph&&c.length>0)try{let f=new C(s.getDb()),h=e.depth??1,b=c.flatMap(S=>(S.nodes??[]).map(R=>R.id)).slice(0,5),y=new Set,E=new Map;for(let S of b){let R=await f.queryNeighbors(S,h,{agentId:t.agentId,scope:o,maxEdgesPerNode:10});for(let M of R)y.add(M.id),E.set(M.id,M.edges??[]);}let u=y.size>0?s.query(`SELECT id, name, type FROM nodes WHERE id IN (${Array.from(y).map(()=>"?").join(",")})`,Array.from(y)):[],p=Array.from(E.values()).flat();m={nodes:u.map(S=>({id:S.id,name:S.name,type:S.type,createdAt:"",updatedAt:""})),edges:p};}catch(f){let h=f instanceof Error?f.message:String(f);W.warn("recall: KG neighbor query failed",{error:h}),a.push(`kg_neighbor_query_failed: ${h}`),m={nodes:[],edges:[]};}let d=Date.now()-n;return {hits:c,total:c.length,truncated:c.length>=i,durationMs:d,graph:m,...a.length>0?{warnings:a}:{}}}catch(c){throw c instanceof g?c:new g(`recall failed: ${c instanceof Error?c.message:String(c)}`,"INTERNAL",{cause:c instanceof Error?c.message:String(c)})}finally{s.close();}}function Le(t,e,n,o){let i=["mf.agent_id = ?","fts.memory_facts_fts MATCH ?"],l=[e,qe(n)];o.category&&(i.push("mf.category = ?"),l.push(o.category)),o.minImportance!==void 0&&(i.push("mf.importance >= ?"),l.push(o.minImportance)),o.fromTime&&(i.push("mf.created_at >= ?"),l.push(o.fromTime)),o.toTime&&(i.push("mf.created_at <= ?"),l.push(o.toTime));try{return t.query(`SELECT
2
+ mf.id as memoryId,
3
+ mf.category,
4
+ mf.importance,
5
+ mf.agent_id as agentId,
6
+ SUBSTR(mf.content, 1, 200) as snippet,
7
+ bm25(memory_facts_fts) as score,
8
+ mf.created_at as createdAt,
9
+ mf.source,
10
+ mf.file_path as filePath,
11
+ mf.node_ids as nodeIds
12
+ FROM memory_facts_fts fts
13
+ JOIN memory_facts mf ON mf.id = fts.fact_id
14
+ WHERE ${i.join(" AND ")}
15
+ ORDER BY score DESC
16
+ LIMIT ?`,[...l,o.limit]).map(s=>({memoryId:s.memoryId,category:s.category,importance:s.importance,agentId:s.agentId,snippet:s.snippet,score:Math.abs(s.score),createdAt:s.createdAt,source:s.source,filePath:s.filePath??void 0,nodes:void 0})).filter(s=>s.score>=o.minScore)}catch(a){if(a instanceof g)throw a;return W.warn("FTS search failed, returning empty result",{err:a instanceof Error?a.message:String(a)}),[]}}function qe(t){return t.trim().split(/\s+/).filter(e=>e.length>0).map(e=>`"${e.replace(/"/g,'""')}"`).join(" ")}var me=utils.Log.create({service:"memory.service.remember"});async function ue(t,e){if(D(t),H(t),!e.content||e.content.trim().length===0)throw new g("remember requires non-empty `content`","CONTENT_REQUIRED");if(!e.category)throw new g("remember requires `category`","CATEGORY_REQUIRED");me.debug("remember invoked",{agentId:t.agentId,category:e.category,importance:e.importance??5,contentLength:e.content.length,skipDedup:e.skipDedup,extractGraph:e.extractGraph??true});let n=new chunkQ2MKNRER_cjs.e(t.dbPath);try{await n.initialize();let o=new Date().toISOString(),i=$e(),l=e.importance??5,{entities:a,relations:s}=e.extractGraph!==!1?Ue(e.content):{entities:[],relations:[]},c=[];return n.transaction(()=>{let d=new Map;for(let f of a){let h=n.query("SELECT id FROM nodes WHERE name = ? AND type = ? LIMIT 1",[f.name,f.type])[0];if(h){d.set(f.name,h.id);continue}let b=n.run("INSERT INTO nodes (name, type, properties, owner_agent_id, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)",[f.name,f.type,JSON.stringify({source:"rule_extracted"}),t.agentId,o,o]);b.lastID>0&&d.set(f.name,b.lastID);}for(let f of s){let h=d.get(f.source),b=d.get(f.target);!h||!b||n.run("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)",[h,b,f.relation,JSON.stringify({}),o]);}n.run(`INSERT INTO memory_facts
17
+ (id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance,
18
+ source, tags, node_ids, file_path, created_at, updated_at)
19
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i,t.agentId,e.sessionId??null,e.msgId??null,e.parentMsgId??null,e.content,e.category,l,"session_self_write",e.tags?JSON.stringify(e.tags):null,JSON.stringify(Array.from(d.values())),null,o,o]),n.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[i]),n.run("INSERT INTO memory_facts_fts (fact_id, agent_id, content, tags) VALUES (?, ?, ?, ?)",[i,t.agentId,e.content,e.tags?e.tags.join(" "):""]),c.push(...Array.from(d.values()));}),me.info("Memory stored",{id:i,category:e.category,agentId:t.agentId,nodeCount:c.length}),{fact:{id:i,agentId:t.agentId,sessionId:e.sessionId,msgId:e.msgId,parentMsgId:e.parentMsgId,content:e.content,category:e.category,importance:l,source:"session_self_write",tags:e.tags,nodeIds:c.length>0?c:void 0,filePath:void 0,createdAt:o,updatedAt:o},filePath:"",deduplicated:!1,nodeIds:c}}catch(o){throw o instanceof g?o:new g(`remember failed: ${o instanceof Error?o.message:String(o)}`,"INTERNAL",{cause:o instanceof Error?o.message:String(o)})}finally{n.close();}}function $e(){let t=Date.now(),e=crypto.randomBytes(3).toString("hex");return `mem_${t}_${e}`}function Ue(t){let e=[],n=[],o=new Set,i=new Set,l=/([A-Za-z][\w.-]{1,80})\s+(is_a|part_of|has_attribute|located_in|occurs_in|causes|influences|owned_by|member_of|uses|depends_on|related_to)\s+([A-Za-z][\w.-]{1,80})/g;for(let a of t.matchAll(l)){let s=(a[1]??"").trim(),c=(a[2]??"related_to").trim(),m=(a[3]??"").trim();if(!s||!m||s===m)continue;o.has(s.toLowerCase())||(o.add(s.toLowerCase()),e.push({name:s,type:le(s)})),o.has(m.toLowerCase())||(o.add(m.toLowerCase()),e.push({name:m,type:le(m)}));let d=`${s.toLowerCase()}|${m.toLowerCase()}|${c}`;i.has(d)||(i.add(d),n.push({source:s,target:m,relation:c}));}return {entities:e,relations:n}}function le(t){let e=t.toLowerCase();return /(\.md|\.ts|\.json|readme|doc|spec|guideline)/i.test(t)?"document":/(api|service|system|engine|pipeline|server|db|database|memorysystem|contextengine)/i.test(e)?"process":/(team|group|org|company|inc|ltd|corp)/i.test(e)?"organization":/(task|issue|ticket|todo|action)/i.test(e)?"task":/(file|model|dataset|artifact|resource|tool|sdk|ollama|sqlite|embedding|vector|fts)/i.test(e)||/[A-Z]/.test(t)&&e!==t?"object":"keyword"}var ge=utils.Log.create({service:"memory.service.forget"}),We=1e3;function Ge(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 g("CONTENT_REQUIRED: forget requires one of: `factId`, `category`, or `fromTime`/`toTime`","CONTENT_REQUIRED");if(e.length>1)throw new g(`mutually exclusive: forget requires exactly one of factId/category/timeRange, got [${e.join(", ")}]`,"CONTENT_REQUIRED");return e[0]}function Qe(t,e,n){let o=[n];switch(t){case "factId":return {where:"agent_id = ? AND id = ?",args:[...o,e.factId]};case "category":return {where:"agent_id = ? AND category = ?",args:[...o,e.category]};case "timeRange":{let i=["agent_id = ?"];return e.fromTime&&(i.push("created_at >= ?"),o.push(e.fromTime)),e.toTime&&(i.push("created_at <= ?"),o.push(e.toTime)),{where:i.join(" AND "),args:o}}}}function Be(t,e,n,o){return t.query(`SELECT id, node_ids FROM memory_facts WHERE ${e} LIMIT ?`,[...n,o+1]).map(l=>l.id)}function ze(t,e,n,o){if(n.length===0)return 0;let i=n.map(()=>"?").join(",");return t.query(`SELECT COUNT(*) as count FROM memory_facts WHERE agent_id = ? AND id != ? AND node_ids IS NOT NULL AND EXISTS (
20
+ SELECT 1 FROM json_each(node_ids) AS je WHERE je.value IN (${i})
21
+ )`,[o,e,...n])[0]?.count??0}function Ke(t,e,n){t.transaction(()=>{let o=t.query("SELECT node_ids, content FROM memory_facts WHERE id = ? AND agent_id = ?",[e,n])[0],i=[];if(o?.node_ids)try{i=JSON.parse(o.node_ids),Array.isArray(i)||(i=[]);}catch{i=[];}if(t.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[e]),t.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[e,n]),i.length>0){let l=i.map(()=>"?").join(",");t.run(`DELETE FROM nodes WHERE id IN (${l}) AND NOT EXISTS (
22
+ SELECT 1 FROM memory_facts WHERE node_ids IS NOT NULL AND EXISTS (
23
+ SELECT 1 FROM json_each(node_ids) AS je WHERE je.value = nodes.id
24
+ )
25
+ )`,i);}});}async function pe(t,e){D(t),N(t,"forget");let n=Ge(e),o=e.maxDelete??We,i=e.dryRun??false,l=e.force??false;ge.debug("forget invoked",{agentId:t.agentId,mode:n,maxDelete:o,dryRun:i,force:l});let a=new chunkQ2MKNRER_cjs.e(t.dbPath);try{await a.initialize();let{where:s,args:c}=Qe(n,e,t.agentId),m=Be(a,s,c,o),d=m.length>o;if(d&&!l)throw new k(m.length,o);let f=d?m.slice(0,o):m;if(i)throw new P(f.length);let h=[];for(let b of f){if(!l){let y=a.query("SELECT node_ids FROM memory_facts WHERE id = ? AND agent_id = ?",[b,t.agentId])[0],E=y?.node_ids?(()=>{try{let p=JSON.parse(y.node_ids);if(Array.isArray(p))return p.filter(S=>typeof S=="number")}catch{}return []})():[],u=ze(a,b,E,t.agentId);if(u>0)throw new A(b,u)}Ke(a,b,t.agentId),h.push(b);}return ge.info("forget complete",{agentId:t.agentId,mode:n,deletedCount:h.length,force:l,dryRun:i}),{deletedCount:h.length,deletedIds:h,dryRun:i,truncatedCount:d?m.length-o:0}}catch(s){throw s instanceof g?s:new g(`forget failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{a.close();}}var G=utils.Log.create({service:"memory.service.extract"}),Ye=50,Q=500;async function fe(t,e){if(D(t),!e.sessionId||e.sessionId.trim().length===0)throw new g("extract requires non-empty `sessionId`","SESSION_ID_REQUIRED");let n=e.lastN??Ye;if(n>Q)throw new g(`extract lastN=${n} exceeds max=${Q}`,"CONTENT_REQUIRED",{lastN:n,maxLastN:Q});let o=e.sessionId,i=e.fromMessageId;G.debug("extract invoked",{agentId:t.agentId,sessionId:o,lastN:n,fromMessageId:i,writeToDisk:e.writeToDisk??true});let l=Date.now(),a=new chunkQ2MKNRER_cjs.e(t.dbPath);try{await a.initialize();let s=a.query(`SELECT id, content, category, importance, 1.0 as score, created_at, node_ids
26
+ FROM memory_facts
27
+ WHERE agent_id = ? AND session_id = ?
28
+ ORDER BY created_at ASC
29
+ LIMIT ?`,[t.agentId,o,n]),c=i?s.filter(y=>y.id>i):s,m=new Set;for(let y of c)if(y.node_ids)try{let E=JSON.parse(y.node_ids);if(Array.isArray(E))for(let u of E)typeof u=="number"&&u>0&&m.add(u);}catch(E){G.warn("extract: invalid node_ids JSON",{factId:y.id,error:E instanceof Error?E.message:String(E)});}let d=Array.from(m),f=[],h=[];if(d.length>0){let y=d.map(()=>"?").join(","),E=a.query(`SELECT id, name, type FROM nodes WHERE id IN (${y})`,d),u=new Map;for(let R of E)u.set(R.id,R.name);f=E.map(R=>({id:R.id,name:R.name,type:R.type}));let p=a.query(`SELECT source, target, relation FROM edges WHERE source IN (${y}) OR target IN (${y})`,[...d,...d]),S=new Set;h=[];for(let R of p){let M=u.get(R.source),w=u.get(R.target);if(!M||!w)continue;let O=`${M}\0${R.relation}\0${w}`;S.has(O)||(S.add(O),h.push({source:M,target:w,relation:R.relation}));}}let b=Date.now()-l;return G.info("extract complete",{agentId:t.agentId,sessionId:o,factCount:c.length,nodeCount:f.length,relationCount:h.length,durationMs:b}),{extractedCount:c.length,factIds:c.map(y=>y.id),entities:f,relations:h,messageRange:{fromMessageId:c[0]?.id??"",toMessageId:c[c.length-1]?.id??""},durationMs:b}}catch(s){throw s instanceof g?s:new g(`extract failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{a.close();}}var K=utils.Log.create({service:"memory.service.consolidate"}),Xe=30;async function Ze(t){let{createHash:e}=await import('crypto');return e("sha256").update(t).digest("hex")}async function ye(t,e={}){let n=Date.now();D(t),N(t,"consolidate");let o=e.windowDays??Xe,i=e.dryRun??false;K.debug("consolidate invoked",{agentId:t.agentId,windowDays:o,dryRun:i});let l=new chunkQ2MKNRER_cjs.e(t.dbPath);try{await l.initialize();let a=l.query("SELECT id, content, category, importance, created_at FROM memory_facts WHERE agent_id = ? ORDER BY created_at DESC",[t.agentId]),s=new Map;for(let u of a){let p=await Ze(u.content);s.has(p)||s.set(p,[]),s.get(p)?.push(u);}let c=0,m=[];for(let[,u]of s){if(u.length<=1)continue;let p=[...u].sort((M,w)=>M.importance!==w.importance?w.importance-M.importance:w.created_at.localeCompare(M.created_at)),S=p[0];if(!S)continue;let R=p.slice(1).map(M=>M.id);c+=R.length,m.push({keep:S,removeIds:R});}let d=new Date(Date.now()-o*24*60*60*1e3).toISOString(),f=l.query(`SELECT id, content, category, importance, created_at FROM memory_facts
30
+ WHERE agent_id = ? AND created_at < ?
31
+ ORDER BY created_at ASC`,[t.agentId,d]),h=0,b=0;if(i)h=0,b=c;else {let u=B__default.default.join(t.workspaceDir,"archive");await x__default.default.mkdir(u,{recursive:!0});for(let{removeIds:p}of m){if(p.length===0)continue;let S=p.map(()=>"?").join(",");l.transaction(()=>{for(let R of p)l.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[R,t.agentId]);}),b+=p.length;}for(let p of f){let S=p.created_at.slice(0,7),R=B__default.default.join(u,S,p.category);await x__default.default.mkdir(R,{recursive:!0});let M=B__default.default.join(R,`${p.id}.md`);try{await x__default.default.writeFile(M,[`# ${p.id}`,"",`category: ${p.category}`,`importance: ${p.importance}`,`createdAt: ${p.created_at}`,"",p.content,""].join(`
32
+ `),"utf-8"),l.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[p.id,t.agentId]),h++;}catch(w){K.warn("consolidate: archive write failed",{factId:p.id,error:w instanceof Error?w.message:String(w)});}}}let y=a.length,E=0;return K.info("consolidate complete",{agentId:t.agentId,totalFacts:y,dedupedCount:c,compressedCount:E,archivedCount:h,skippedCount:b,dryRun:i,durationMs:Date.now()-n}),{totalFacts:y,dedupedCount:c,compressedCount:E,archivedCount:h,skippedCount:b,durationMs:Date.now()-n}}catch(a){throw a instanceof g?a:new g(`consolidate failed: ${a instanceof Error?a.message:String(a)}`,"INTERNAL",{cause:a instanceof Error?a.message:String(a)})}finally{l.close();}}var he=utils.Log.create({service:"memory.service.graph-query"});async function be(t,e){let n=Date.now();D(t);let o=e.scope??"agent_only";if(!e.query||e.query.trim().length===0)throw new g("CONTENT_REQUIRED: graphQuery requires non-empty `query`","CONTENT_REQUIRED");F(t,o,"graph_query");let i=e.depth??2,l=e.maxNodes??100,a=e.query,s=e.type,c=e.relation;he.debug("graphQuery invoked",{agentId:t.agentId,query:a,type:s,depth:i,maxNodes:l,scope:o,remote:t.remote});let m=new chunkQ2MKNRER_cjs.e(t.dbPath);try{await m.initialize();let d=new C(m.getDb()),f=a.includes("*")||a.includes("%")?a:`%${a}%`,h=await d.queryNodes({name:f,...s?{type:s}:{},agentId:t.agentId,scope:o,limit:l}),y=(a.includes("*")||a.includes("%")?h:h.filter(w=>w.name.toLowerCase().includes(a.toLowerCase())))[0]??null;if(!y)return {root:null,nodes:[],edges:[],truncated:!1,totalNodes:0,totalEdges:0,scope:o,durationMs:Date.now()-n};let E=await d.queryNeighbors(y.id,i,{agentId:t.agentId,scope:o,maxEdgesPerNode:20}),u=new Map;u.set(y.id,y);for(let w of E)u.set(w.id,{id:w.id,name:w.name,type:w.type,createdAt:w.createdAt,updatedAt:w.updatedAt});let p=[];for(let w of E)if(w.edges)for(let O of w.edges)c&&O.relation!==c||p.push(O);for(let w of p){if(!u.has(w.source)){let O=await d.queryNodes({ids:[w.source],agentId:t.agentId,scope:o});O[0]&&u.set(O[0].id,O[0]);}if(!u.has(w.target)){let O=await d.queryNodes({ids:[w.target],agentId:t.agentId,scope:o});O[0]&&u.set(O[0].id,O[0]);}}let S=Array.from(u.values()),R=S.length>l,M=R?S.slice(0,l):S;return he.info("graphQuery complete",{agentId:t.agentId,rootId:y.id,nodeCount:M.length,edgeCount:p.length,truncated:R,durationMs:Date.now()-n}),{root:y,nodes:M,edges:p,truncated:R,totalNodes:S.length,totalEdges:p.length,scope:o,durationMs:Date.now()-n}}catch(d){throw d instanceof g?d:new g(`graphQuery failed: ${d instanceof Error?d.message:String(d)}`,"INTERNAL",{cause:d instanceof Error?d.message:String(d)})}finally{m.close();}}var $=utils.Log.create({service:"memory.service.status"}),rt=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"];async function Ee(t,e={}){D(t),$.debug("status invoked",{agentId:t.agentId});let n=new chunkQ2MKNRER_cjs.e(t.dbPath);try{await n.initialize();let i=n.query("SELECT COUNT(*) as c FROM memory_facts WHERE agent_id = ?",[t.agentId])[0]?.c??0,a=n.query("SELECT COUNT(*) AS c FROM nodes WHERE owner_agent_id = ? OR owner_agent_id IS NULL",[t.agentId])[0]?.c??0,c=n.query("SELECT COUNT(*) as c FROM edges")[0]?.c??0,m=rt.reduce((u,p)=>(u[p]=0,u),{}),d=n.query("SELECT category, COUNT(*) as c FROM memory_facts WHERE agent_id = ? GROUP BY category",[t.agentId]);for(let u of d){let p=u.category;p in m&&(m[p]=u.c);}let f=!1;try{f=n.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]).length>0;}catch(u){$.debug("status: fts probe failed",{error:u instanceof Error?u.message:String(u)});}let h=!!t.config?.embeddingLlm,b=!1;try{b=n.query("SELECT name FROM pragma_table_info('nodes') WHERE name = ?",["owner_agent_id"]).length>0;}catch(u){$.debug("status: kg scope probe failed",{error:u instanceof Error?u.message:String(u)});}let y=n.healthCheck(),E={};try{let u=n.query("SELECT key, value FROM meta");for(let p of u)E[p.key]=p.value;}catch(u){$.debug("status: meta read failed",{error:u instanceof Error?u.message:String(u)});}return {dbPath:t.dbPath,workspaceDir:t.workspaceDir,factsCount:i,nodesCount:a,edgesCount:c,factsByCategory:m,ftsAvailable:f,vectorEnabled:h,kgScopeEnabled:b,healthy:y,meta:E}}catch(o){throw o instanceof g?o:new g(`status failed: ${o instanceof Error?o.message:String(o)}`,"INTERNAL")}finally{n.close();}}var at=utils.Log.create({service:"memory.service.doctor"}),Y=100*1024*1024,V=100*1024*1024;async function we(t,e={}){D(t),at.debug("doctor invoked",{agentId:t.agentId});let n=[],o=null;try{o=new chunkQ2MKNRER_cjs.e(t.dbPath),await o.initialize();let a=o.healthCheck();n.push({name:"database",passed:a,message:a?"database connected and writable":"database unhealthy",details:{dbPath:t.dbPath}});}catch(a){n.push({name:"database",passed:false,message:`database connection failed: ${a instanceof Error?a.message:String(a)}`,details:{dbPath:t.dbPath}});}try{if(!o)throw new Error("db not initialized");let a=o.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]);n.push({name:"fts",passed:a.length>0,message:a.length>0?"FTS5 index available":"FTS5 index not found",details:a.length>0?{table:a[0]?.name}:void 0});}catch(a){n.push({name:"fts",passed:false,message:`fts probe failed: ${a instanceof Error?a.message:String(a)}`});}let i=!!t.config?.embeddingLlm;n.push({name:"vector",passed:true,message:i?"embedding model available":"no embedding model configured (FTS-only mode, recall still functional)",details:{mode:i?"hybrid":"fts_only",model:t.config?.embeddingLlm?"configured":"missing"}});try{if(!o)throw new Error("db not initialized");let a=["memory_facts","nodes","edges","meta"],s=o.query("SELECT name FROM sqlite_master WHERE type = ?",["table"]),c=new Set(s.map(d=>d.name)),m=a.filter(d=>!c.has(d));n.push({name:"schema",passed:m.length===0,message:m.length===0?`schema complete (${a.length} tables)`:`missing tables: ${m.join(", ")}`,details:{required:a,existing:Array.from(c)}});}catch(a){n.push({name:"schema",passed:false,message:`schema probe failed: ${a instanceof Error?a.message:String(a)}`});}try{let a=`${t.dbPath}-wal`,s=`${t.dbPath}-shm`,c=0,m=0;try{c=(await x__default.default.stat(a)).size;}catch{c=0;}try{m=(await x__default.default.stat(s)).size;}catch{m=0;}let d=c+m;n.push({name:"lock",passed:d<=V,message:d<=V?`no lock contention (wal+shm ${(d/1024).toFixed(1)} KB)`:`WAL/SHM files unusually large (${(d/1024/1024).toFixed(1)} MB > ${(V/1024/1024).toFixed(0)} MB threshold)`,details:{walBytes:c,shmBytes:m}});}catch(a){n.push({name:"lock",passed:false,message:`lock probe failed: ${a instanceof Error?a.message:String(a)}`});}try{let a=B__default.default.dirname(t.dbPath),s=await x__default.default.statfs(a),c=typeof s.bsize=="bigint"?Number(s.bsize)*s.bavail:s.bsize*s.bavail,m=c>=Y;n.push({name:"disk_space",passed:m,message:m?`sufficient disk space (${(c/1024/1024).toFixed(1)} MB available)`:`low disk space (${(c/1024/1024).toFixed(1)} MB < ${(Y/1024/1024).toFixed(0)} MB threshold)`,details:{availableBytes:c,threshold:Y}});}catch(a){n.push({name:"disk_space",passed:false,message:`disk_space probe failed: ${a instanceof Error?a.message:String(a)}`});}try{if(!o)throw new Error("db not initialized");let a=o.query("SELECT id, node_ids FROM memory_facts WHERE agent_id = ? AND node_ids IS NOT NULL",[t.agentId]),s=[];for(let c of a)try{let m=JSON.parse(c.node_ids);if(!Array.isArray(m))continue;for(let d of m){if(typeof d!="number")continue;if((o.query("SELECT COUNT(*) as c FROM nodes WHERE id = ?",[d])[0]?.c??0)===0){s.push(`${c.id}->${d}`);break}}}catch{}n.push({name:"orphan",passed:s.length===0,message:s.length===0?"no orphan KG references":`${s.length} orphan references: ${s.slice(0,5).join(", ")}${s.length>5?", ...":""}`,details:{count:s.length}});}catch(a){n.push({name:"orphan",passed:false,message:`orphan probe failed: ${a instanceof Error?a.message:String(a)}`});}let l=n.every(a=>a.passed);return o&&o.close(),{healthy:l,checks:n}}var U=utils.Log.create({service:"memory.service.init"});async function Re(t,e={}){let n=Date.now();N(t,"init");let o=e.workspaceDir??t.workspaceDir,i=e.dbPath??t.dbPath;if(!o||o.trim().length===0)throw new g("init requires non-empty `workspaceDir` (ctx.workspaceDir or params.workspaceDir)","CONTENT_REQUIRED");if(!i||i.trim().length===0)throw new g("init requires non-empty `dbPath` (ctx.dbPath or params.dbPath)","CONTENT_REQUIRED");let l=t.agentId?.trim()??"",a=e.force??false;U.debug("init invoked",{agentId:l,workspaceDir:o,dbPath:i,force:a});try{await x__default.default.mkdir(B__default.default.dirname(i),{recursive:!0}),await x__default.default.mkdir(B__default.default.join(o,"active"),{recursive:!0}),await x__default.default.mkdir(B__default.default.join(o,"archive"),{recursive:!0});}catch(c){throw new g(`init: failed to create directories: ${c instanceof Error?c.message:String(c)}`,"INTERNAL",{cause:c instanceof Error?c.message:String(c)})}if(a)try{await x__default.default.rm(i,{force:!0});}catch(c){U.warn("init: force rm db failed (may not exist)",{dbPath:i,error:c instanceof Error?c.message:String(c)});}let s=new chunkQ2MKNRER_cjs.e(i);try{let c=await x__default.default.stat(i).then(()=>!0).catch(()=>!1);await s.initialize();let m=new Date().toISOString(),d=[["version","1.0.0"],["schemaVersion",String(chunkQ2MKNRER_cjs.a)],["createdAt",m],["defaultAgentId",l]];for(let[b,y]of d)try{s.run("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)",[b,y]);}catch(E){U.warn("init: meta insert failed",{key:b,error:E instanceof Error?E.message:String(E)});}let f=c?0:12,h=c?0:1;return U.info("init complete",{agentId:l,workspaceDir:o,dbPath:i,schemaVersion:chunkQ2MKNRER_cjs.a,durationMs:Date.now()-n}),{initialized:!0,dbPath:i,workspaceDir:o,tablesCreated:f,migrationsApplied:h,durationMs:Date.now()-n}}catch(c){throw new g(`init failed: ${c instanceof Error?c.message:String(c)}`,"INTERNAL",{cause:c instanceof Error?c.message:String(c)})}finally{s.close();}}var Ie=zod.z.object({query:zod.z.string().min(1).max(500),category:zod.z.string().optional(),minImportance:zod.z.number().min(1).max(10).optional(),fromTime:zod.z.string().datetime().optional(),toTime:zod.z.string().datetime().optional(),maxResults:zod.z.number().int().min(1).max(100).optional().default(10),minScore:zod.z.number().min(0).max(1).optional(),includeGraph:zod.z.boolean().optional().default(false),depth:zod.z.number().int().min(1).max(5).optional().default(1),includeShared:zod.z.boolean().optional().default(false)});zod.z.object({hits:zod.z.array(zod.z.unknown()),total:zod.z.number(),truncated:zod.z.boolean(),durationMs:zod.z.number(),graph:zod.z.object({nodes:zod.z.array(zod.z.unknown()),edges:zod.z.array(zod.z.unknown())}).optional()});var Se=zod.z.object({content:zod.z.string().min(1).max(1e4),category:zod.z.string().min(1),importance:zod.z.number().int().min(1).max(10).optional().default(5),tags:zod.z.array(zod.z.string()).optional(),sessionId:zod.z.string().optional(),msgId:zod.z.string().optional(),parentMsgId:zod.z.string().optional(),skipDedup:zod.z.boolean().optional().default(false),extractGraph:zod.z.boolean().optional().default(true)});zod.z.object({fact:zod.z.object({id:zod.z.string(),agentId:zod.z.string(),content:zod.z.string(),category:zod.z.string(),importance:zod.z.number(),createdAt:zod.z.string(),updatedAt:zod.z.string()}),filePath:zod.z.string(),deduplicated:zod.z.boolean(),nodeIds:zod.z.array(zod.z.number()).optional()});var Me=zod.z.object({factId:zod.z.string().optional(),category:zod.z.string().optional(),fromTime:zod.z.string().datetime().optional(),toTime:zod.z.string().datetime().optional(),maxDelete:zod.z.number().int().min(1).max(1e4).optional().default(1e3),dryRun:zod.z.boolean().optional().default(false),force:zod.z.boolean().optional().default(false)}).refine(t=>t.factId!==void 0&&t.factId.length>0||t.category!==void 0&&t.category.length>0||t.fromTime!==void 0||t.toTime!==void 0,{message:"one of `factId`, `category`, `fromTime`, or `toTime` is required"});zod.z.object({deletedCount:zod.z.number(),deletedIds:zod.z.array(zod.z.string()),dryRun:zod.z.boolean(),truncatedCount:zod.z.number()});var _e=zod.z.object({sessionId:zod.z.string().min(1),lastN:zod.z.number().int().min(1).max(500).optional().default(50),fromMessageId:zod.z.string().optional(),writeToDisk:zod.z.boolean().optional().default(true)});zod.z.object({extractedCount:zod.z.number(),factIds:zod.z.array(zod.z.string()),entities:zod.z.array(zod.z.object({id:zod.z.number(),name:zod.z.string(),type:zod.z.string()})),relations:zod.z.array(zod.z.object({source:zod.z.string(),target:zod.z.string(),relation:zod.z.string()})),messageRange:zod.z.object({fromMessageId:zod.z.string(),toMessageId:zod.z.string()}),durationMs:zod.z.number()});var De=zod.z.object({windowDays:zod.z.number().int().min(1).max(365).optional().default(30),dryRun:zod.z.boolean().optional().default(false)});zod.z.object({totalFacts:zod.z.number(),dedupedCount:zod.z.number(),compressedCount:zod.z.number(),archivedCount:zod.z.number(),skippedCount:zod.z.number(),durationMs:zod.z.number()});var Oe=zod.z.object({query:zod.z.string().min(1),type:zod.z.string().optional(),depth:zod.z.number().int().min(1).max(5).optional().default(2),maxNodes:zod.z.number().int().min(1).max(500).optional().default(100),scope:zod.z.enum(["agent_only","shared_only","both"]).optional().default("agent_only"),relation:zod.z.string().optional()});zod.z.object({root:zod.z.unknown().nullable(),nodes:zod.z.array(zod.z.unknown()),edges:zod.z.array(zod.z.unknown()),truncated:zod.z.boolean(),totalNodes:zod.z.number(),totalEdges:zod.z.number(),scope:zod.z.enum(["agent_only","shared_only","both"]),durationMs:zod.z.number()});var Ce=zod.z.object({}).optional();zod.z.object({dbPath:zod.z.string(),workspaceDir:zod.z.string(),factsCount:zod.z.number(),nodesCount:zod.z.number(),edgesCount:zod.z.number(),factsByCategory:zod.z.record(zod.z.string(),zod.z.number()),ftsAvailable:zod.z.boolean(),vectorEnabled:zod.z.boolean(),kgScopeEnabled:zod.z.boolean(),healthy:zod.z.boolean(),meta:zod.z.record(zod.z.string(),zod.z.string())});var Ne=zod.z.object({}).optional();zod.z.object({healthy:zod.z.boolean(),checks:zod.z.array(zod.z.object({name:zod.z.string(),passed:zod.z.boolean(),message:zod.z.string(),details:zod.z.record(zod.z.string(),zod.z.unknown()).optional()}))});var Te=zod.z.object({workspaceDir:zod.z.string().optional(),dbPath:zod.z.string().optional(),archiveDays:zod.z.number().int().min(1).max(3650).optional().default(30),force:zod.z.boolean().optional().default(false)});zod.z.object({initialized:zod.z.boolean(),dbPath:zod.z.string(),workspaceDir:zod.z.string(),tablesCreated:zod.z.number(),migrationsApplied:zod.z.number(),durationMs:zod.z.number()});var Z={name:"recall",scope:"read",schema:Ie,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Query memory via hybrid search (FTS + vector); returns ranked facts.",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("recall: agentId is required");return de({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var ee={name:"remember",scope:"write",schema:Se,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Persist a new self-memory fact; auto-extract entities into KG.",readOnlyHint:false,destructiveHint:false,idempotentHint:false},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("remember: agentId is required");return ue({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var te={name:"forget",scope:"write",schema:Me,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Delete memory facts by id / category / time range; supports dryRun.",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("forget: agentId is required");return pe({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var re={name:"extract",scope:"write",schema:_e,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Extract facts from a session (server-side pulls messages by lastN).",readOnlyHint:false,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("extract: agentId is required");return fe({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var ne={name:"consolidate",scope:"admin",schema:De,annotations:{localOnly:true,requiresAgentId:true,defaultDescription:"Run consolidation pipeline: dedup \u2192 archive.",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.isTrustedLocal)throw new Error("consolidate: only trusted local process can invoke this op");if(!e.agentId?.trim())throw new Error("consolidate: agentId is required");return ye({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},n)}};var oe={name:"graph_query",scope:"read",schema:Oe,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Query KG nodes / edges / neighbors with scope filtering.",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("graph_query: agentId is required");return be({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var ae={name:"status",scope:"read",schema:Ce,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Memory system status (factsCount / nodesCount / edgesCount / fts / vector).",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t??{};return Ee({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var se={name:"doctor",scope:"admin",schema:Ne,annotations:{localOnly:true,requiresAgentId:true,defaultDescription:"Run 7 health checks (database / fts / vector / schema / lock / disk_space / orphan).",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t??{};if(!e.isTrustedLocal)throw new Error("doctor: only trusted local process can invoke this op");if(!e.agentId?.trim())throw new Error("doctor: agentId is required");return we({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},n)}};var ie={name:"init",scope:"admin",schema:Te,annotations:{localOnly:true,requiresAgentId:false,defaultDescription:"Initialize memory workspace (dirs + db schema + meta).",readOnlyHint:false,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{if(!e.isTrustedLocal)throw new Error("init: only trusted local process can invoke this op");let n=t??{};return Re({workspaceDir:n.workspaceDir??e.workspaceDir??"",rootDir:n.workspaceDir??e.workspaceDir??"",dbPath:n.dbPath??e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId??""},n)}};var ve={[Z.name]:Z,[ee.name]:ee,[te.name]:te,[re.name]:re,[ne.name]:ne,[oe.name]:oe,[ae.name]:ae,[se.name]:se,[ie.name]:ie},it=Object.values(ve);function ct(t,e,n){if(t.annotations.localOnly&&!e.isTrustedLocal)throw new Error(`MEMORY:executeOp: op "${n}" is localOnly; non-trusted caller rejected`);if(t.annotations.requiresAgentId){let o=e.agentId?.trim()??"";if(o.length===0)throw new Error(`MEMORY:executeOp: op "${n}" requires agentId`);e.agentId=o;}}async function Pn(t,e,n){let o=ve[t];if(!o)throw new Error(`executeOp: unknown op "${t}"; available: ${it.map(l=>l.name).join(", ")}`);return ct(o,n,t),await o.handler(e,n)}function lt(t){let e=t.dbPath??"";return {workspaceDir:t.workspaceDir??"",database:{path:e},embeddingLlm:void 0,graphLlm:void 0,search:types.DEFAULT_SEARCH_CONFIG,indexer:{batchSize:20,ignorePatterns:[],incremental:true},archiveDays:30,shortTermMaxRounds:20}}function Un(t,e,n={}){let o=chunk3HTZTI7U_cjs.j(),i=utils.Locale.resolveLocaleLang(n.locale);return {agentId:t,dbPath:o,workspaceDir:e,rootDir:e,config:lt({dbPath:o,workspaceDir:e}),isTrustedLocal:true,locale:i,remote:false,...n}}exports.a=C;exports.b=de;exports.c=ue;exports.d=pe;exports.e=fe;exports.f=ye;exports.g=be;exports.h=Ee;exports.i=we;exports.j=Re;exports.k=ve;exports.l=it;exports.m=Pn;exports.n=lt;exports.o=Un;
@@ -0,0 +1,59 @@
1
+ import {k,m,n}from'./chunk-PWLSQFYA.mjs';import {a}from'./chunk-WQGSYA5D.mjs';import {ToolRegistry,createAndStartStdioServer,formatFailClosed}from'@easbot/mcp';import {Log,TruncateContent}from'@easbot/utils';var K=Log.create({service:"memory-format-truncate"}),P="**`";var j=24e3,q=25e3;async function $(e,n={}){let o=n.softLimit??j,r=n.hardCeiling??q,s=n.toolName??"memory",c=n.writeToDisk!==false;if(e.length<=o)return {content:e,truncated:false};let i=e.slice(0,r),t=i.lastIndexOf(`
2
+ ${P}`),a=i.lastIndexOf(`
3
+ `),d;t>r*.5?d=t:a>0?d=a:d=-1;let u=d>0?i.slice(0,d):i,m=u+"\n\n... (output truncated to budget; the source above is complete and verbatim \u2014 treat it as already Read. For any area not covered, make ANOTHER `<tool>` targeting those names \u2014 do NOT Read these files.)";if(!c)return {content:m,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-u.length}/${e.length} characters truncated ...`};try{let g=await TruncateContent.truncate(e,{maxChars:u.length,direction:"head",label:`${s}-output`});return g.truncated?{content:m,truncated:!0,outputPath:g.outputPath,hint:TruncateContent.formatHint(g),info:`... ${g.removedLength}/${g.originalLength} characters truncated ...`}:{content:m,truncated:!0,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-u.length}/${e.length} characters truncated ...`}}catch(g){return K.warn("TruncateContent.truncate failed, returning without disk hint",{error:g instanceof Error?g.message:String(g)}),{content:m,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-u.length}/${e.length} characters truncated ...`}}}function b(e,n={}){let o=n.softLimit??j,r=n.hardCeiling??q;if(e.length<=o)return {content:e,truncated:false};let s=e.slice(0,r),c=s.lastIndexOf(`
4
+ ${P}`),i=s.lastIndexOf(`
5
+ `),t;c>r*.5?t=c:i>0?t=i:t=-1;let a=t>0?s.slice(0,t):s;return {content:a+`
6
+
7
+ ... (output truncated; tail dropped at section boundary)`,truncated:true,outputPath:"",hint:"",info:`... ${e.length-a.length}/${e.length} characters truncated ...`}}function U(e,n){if(!e||e.length===0)return null;let o=e.filter(s=>n.has(s.path));return o.length===0?null:`\u26A0\uFE0F Index may be stale for: ${o.map(s=>`${s.path} (edited pending)`).join(", ")}
8
+
9
+ `}function I(e,n,o={}){return (G[e]??G.default).replace(/<(\w+)>/g,(s,c)=>c==="tool"?n:o[c]??`<${c}>`)}var G={recall:"If you need more facts, make ANOTHER `<tool>` query with a different scope / interval.\nIf you have enough context, proceed with the current task. Do NOT call `<tool>` again for the same query.",remember:"Memory persisted. To recall it later, use `<tool>` with the same query.\nDo NOT call `<tool>` again to verify \u2014 the fact is already in the database.",forget:"Memory deleted. To verify, run `<tool>` with the same filter (no results expected).\nIf you deleted too much, the data is gone (no auto-restore).",graph_query:"If you need to explore further, make ANOTHER `<tool>` from a different start node or depth.\nOtherwise, the graph is complete for this scope.",status:"Status snapshot. To inspect a specific fact, use `<tool>` (recall) with its id.\nOtherwise, this is a complete read.",consolidate:"Consolidation done. To inspect the new facts, use `<tool>` with the same agentId.\nIf you want to undo, archives are in <archive_dir>.",doctor:"Doctor report. To fix a failing check, run with `repair=true`.\nRe-run after fix to confirm.",default:"If you need more, make ANOTHER `<tool>` with refined parameters.\nOtherwise, this is a complete read."};function H(e,n,o,r){let s=e.tags&&e.tags.length>0?`
10
+ - tags: ${e.tags.join(", ")}`:"",c=e.sessionId?`
11
+ - session: ${e.sessionId}`:"",i=e.msgId?`
12
+ - msg: ${e.msgId}`:"",t=typeof n=="number"?`
13
+ - score: ${n.toFixed(3)}${o?` (${o})`:""}`:"",a=e.truncated?" [truncated]":"",d="";if(r&&r.length>0){let u=[];for(let l of r){let m=[];if(l.edges&&l.edges.length>0)for(let h of l.edges){let f=h.direction??(h.source===l.id?"out":"in"),R=h.targetNode?.name??String(h.target),C=h.targetNode?.type??"node";m.push(` --[${f}] ${h.relation}--> ${R} (${C})`);}let g=m.length>0?m.join(`
14
+ `):" (no relations)";u.push(` - Node: ${l.name} (${l.type})
15
+ ${g}`);}d=`
16
+ - linked KG nodes (${r.length}):
17
+ ${u.join(`
18
+ `)}`;}return [`### \`${e.id}\`${a}`,` - agentId: ${e.agentId}`,` - category: ${e.category}`,` - importance: ${e.importance}`,` - createdAt: ${e.createdAt}`,` - updatedAt: ${e.updatedAt}`,` - source: ${e.source}${t}${s}${c}${i}${d}`,"",e.content,""].join(`
19
+ `)}async function D(e,n){let o=n.toolName??"memory_recall",r=`**\`memory_recall:${n.query.slice(0,40).replace(/[^a-zA-Z0-9_]/g,"_")}\`**`,s=U(n.pendingFiles,new Set),i=[`Found ${e.total} fact(s) for query "${n.query}" (agentId=${n.agentId}, scope=${n.scope}):`,"",s??"",r].join(`
20
+ `),t=new Map;for(let l of e.hits){let m=l.fact.category;t.has(m)||t.set(m,[]),t.get(m).push(l);}let a=Array.from(t.entries()).map(([l,m])=>{let g=`**\`category:${l}\`**`,h=m.map(f=>H(f.fact,f.score,f.source,f.nodes)).join(`
21
+ `);return `${g}
22
+
23
+ ${h}`}).join(`
24
+ `),d=e.warnings&&e.warnings.length>0?`
25
+
26
+ \u26A0\uFE0F warnings:
27
+ ${e.warnings.map(l=>` - ${l}`).join(`
28
+ `)}
29
+ `:"",u=`${i}
30
+
31
+ ${a}${d}
32
+
33
+ ${I("recall",o)}`;return n.sync?b(u,{}).content:(await $(u,{toolName:o,writeToDisk:n.writeToDisk})).content}async function N(e,n={}){let o=n.toolName??"memory_remember",r=`**\`memory_remember:${e.fact.id}\`**`,s=H(e.fact),c=e.nodeIds??[],i=c.length>0?`
34
+ - linked KG nodes: ${c.join(", ")}
35
+ `:"",t=`${r}
36
+
37
+ ${s}${i}
38
+
39
+ ${I("remember",o)}`;return n.sync?b(t,{}).content:(await $(t,{toolName:o,writeToDisk:n.writeToDisk})).content}async function S(e,n={}){let o=n.toolName??"memory_forget",r="**`memory_forget:result`**",s=e.dryRun?"**DRY RUN** \u2014 no facts were actually deleted. Run again without dryRun to execute.":`Deleted ${e.deletedCount} fact(s).`,c=e.truncatedCount>0?` (truncated: ${e.truncatedCount} more, re-run with narrower filter)`:"",i=[r,"",s+c,"",e.deletedIds.length>0?`deleted ids:
40
+ ${e.deletedIds.map(t=>` - ${t}`).join(`
41
+ `)}`:"(no ids to show)","",I("forget",o)].join(`
42
+ `);return n.sync?b(i,{}).content:(await $(i,{toolName:o,writeToDisk:n.writeToDisk})).content}async function M(e,n={}){let o=n.toolName??"memory_graph_query",r=`**\`memory_graph_query:scope=${e.scope}\`**`,s=e.nodes.map(t=>` - node #${t.id}: ${t.name} (${t.type})${t.ownerAgentId?` [owner=${t.ownerAgentId}]`:" [shared]"}`).join(`
43
+ `),c=e.edges.map(t=>` - edge #${t.id}: ${t.source} --${t.relation}--> ${t.target}`).join(`
44
+ `),i=[r,"",`nodes (${e.nodes.length}${e.truncated?` / total ${e.totalNodes}`:""}):`,s||" (none)","",`edges (${e.edges.length}${e.truncated?` / total ${e.totalEdges}`:""}):`,c||" (none)","",I("graph_query",o)].join(`
45
+ `);return n.sync?b(i,{}).content:(await $(i,{toolName:o,writeToDisk:n.writeToDisk})).content}async function v(e,n={}){let o=n.toolName??"memory_status",c=["**`memory_status`**","",`dbPath: ${e.dbPath}`,`workspaceDir: ${e.workspaceDir}`,`factsCount: ${e.factsCount}`,`nodesCount: ${e.nodesCount} (KG nodes)`,`edgesCount: ${e.edgesCount} (KG edges)`,`ftsAvailable: ${e.ftsAvailable?"yes":"no"}`,`vectorEnabled: ${e.vectorEnabled?"yes":"no"}`,`kgScopeEnabled: ${e.kgScopeEnabled?"yes":"no"}`,`healthy: ${e.healthy?"yes":"no"}`,"","factsByCategory:",...Object.entries(e.factsByCategory).map(([i,t])=>` - ${i}: ${t}`),"","meta:",...Object.entries(e.meta).map(([i,t])=>` - ${i}: ${t}`),"",I("status",o)].join(`
46
+ `);return n.sync?b(c,{}).content:(await $(c,{toolName:o,writeToDisk:n.writeToDisk})).content}async function _(e,n={}){let o=n.toolName??"memory_consolidate",s=["**`memory_consolidate:result`**","",`total facts scanned: ${e.totalFacts}`,`deduped (merged): ${e.dedupedCount}`,`compressed: ${e.compressedCount}`,`archived to archive/: ${e.archivedCount}`,`skipped (no change): ${e.skippedCount}`,`duration: ${e.durationMs}ms`,"",I("consolidate",o)].join(`
47
+ `);return n.sync?b(s,{}).content:(await $(s,{toolName:o,writeToDisk:n.writeToDisk})).content}async function A(e,n={}){let o=n.toolName??"memory_doctor",r=`**\`memory_doctor:${e.healthy?"OK":"ISSUES"}\`**`,s=t=>t?"\u2705":"\u274C",c=e.checks.map(t=>`${s(t.passed)} ${t.name}: ${t.message}`).join(`
48
+ `),i=[r,"",c,"",I("doctor",o)].join(`
49
+ `);return n.sync?b(i,{}).content:(await $(i,{toolName:o,writeToDisk:n.writeToDisk})).content}async function w(e,n,o={}){let r=n,s=typeof r.kind=="string";switch((s?r:{kind:e}).kind){case "recall":{let i=s?{hits:r.hits,total:r.totalCount??r.total??0,truncated:r.truncated??false}:n;return D(i,{...o,query:r.query??o.query??"",agentId:r.agentId??o.agentId??"",scope:r.scope??o.scope??"agent_only"})}case "remember":{let i=s?{fact:r.fact,nodeIds:r.nodeIds}:n;return N(i,o)}case "forget":return S(s?r:n,o);case "graph_query":return M(s?r:n,o);case "status":return v(s?r:n,o);case "consolidate":return _(s?r:n,o);case "doctor":return A(s?r:n,o);default:throw new Error(`renderOperationMarkdown: unsupported op "${e}"`)}}var x=Log.create({service:"memory-mcp-stdio"});function se(e){let n$1=new Map,o=e.isRemote??true,r=!o;function s(t){let{Locale:a$1}=a("@easbot/utils"),d=a$1.resolveLocaleLang();return {agentId:t.agentId??e.agentId,isTrustedLocal:t.isTrustedLocal??r,remote:o,locale:d,dbPath:e.dbPath,workspaceDir:e.workspaceDir,rootDir:e.workspaceDir,config:n({agentId:e.agentId,dbPath:e.dbPath})}}function c(t,a){return {content:[{type:"text",text:t}],isError:a}}function i(t){return formatFailClosed(t,r)}return n$1.set("recall",async t=>{try{let a=t,d=s({agentId:a.agentId}),u=await m("recall",t,d);return {content:[{type:"text",text:await w("recall",u,{toolName:"memory_recall",query:a.query,agentId:a.agentId??e.agentId,scope:a.scope??"agent_only"})}]}}catch(a){return c(i(a),true)}}),n$1.set("remember",async t=>{try{let d=s({agentId:t.agentId}),u=await m("remember",t,d);return {content:[{type:"text",text:await w("remember",u,{toolName:"memory_remember"})}]}}catch(a){return c(i(a),true)}}),n$1.set("forget",async t=>{try{let d=s({agentId:t.agentId}),u=await m("forget",t,d);return {content:[{type:"text",text:await w("forget",u,{toolName:"memory_forget"})}]}}catch(a){return c(i(a),true)}}),n$1.set("extract",async t=>{try{let d=s({agentId:t.agentId}),l=await m("extract",t,d);return {content:[{type:"text",text:`Extract completed.
50
+ sessionId: ${t.sessionId??"(unknown)"}
51
+ extractedCount: ${l.extractedCount}
52
+ factIds: ${l.factIds.length>0?l.factIds.join(", "):"(none)"}
53
+ messageRange: ${l.messageRange.fromMessageId} -> ${l.messageRange.toMessageId}
54
+ `}]}}catch(a){return c(i(a),true)}}),n$1.set("consolidate",async t=>{try{let d=s({agentId:t.agentId,isTrustedLocal:!0}),u=await m("consolidate",t,d);return {content:[{type:"text",text:await w("consolidate",u,{toolName:"memory_consolidate"})}]}}catch(a){return c(i(a),true)}}),n$1.set("graph_query",async t=>{try{let a=t,d=s({agentId:a.agentId}),u=await m("graph_query",t,d);return {content:[{type:"text",text:await w("graph_query",u,{toolName:"memory_graph_query",scope:a.scope??"agent_only"})}]}}catch(a){return c(i(a),true)}}),n$1.set("status",async t=>{try{let d=s({agentId:(t??{}).agentId}),u=await m("status",t,d);return {content:[{type:"text",text:await w("status",u,{toolName:"memory_status"})}]}}catch(a){return c(i(a),true)}}),n$1.set("doctor",async t=>{try{let d=s({agentId:(t??{}).agentId,isTrustedLocal:!0}),u=await m("doctor",t,d);return {content:[{type:"text",text:await w("doctor",u,{toolName:"memory_doctor"})}]}}catch(a){return c(i(a),true)}}),n$1.set("init",async t=>{try{let a=s({isTrustedLocal:!0}),u=await m("init",t,a);return {content:[{type:"text",text:`Init complete.
55
+ dbPath: ${u.dbPath}
56
+ tablesCreated: ${u.tablesCreated}
57
+ migrationsApplied: ${u.migrationsApplied}
58
+ durationMs: ${u.durationMs}
59
+ `}]}}catch(a){return c(i(a),true)}}),n$1}function ae(e,n){let o=k[e],r={title:o?.annotations?.defaultDescription??e,readOnlyHint:o?.annotations?.readOnlyHint??false,destructiveHint:o?.annotations?.destructiveHint??false,idempotentHint:o?.annotations?.idempotentHint??true,openWorldHint:false};return {name:e,description:o?.annotations?.defaultDescription??`memory op: ${e}`,inputSchema:{type:"object",properties:{},required:[]},annotations:r,handler:n}}var B;(o=>{async function e(r,s){let{getMemoryDbPath:c,getInstance:i}=await import('./interfaces-VBO3Z6QF.mjs'),a=s!==null&&typeof s=="object"&&"agentId"in s&&"dbPath"in s?s:{agentId:process.env.EASBOT_AGENT_ID??"default",dbPath:c(),workspaceDir:i().worktree,isRemote:false},d=new ToolRegistry,u=se(a),l=Object.keys(k);for(let p of l){let O=u.get(p);if(!O)throw new Error(`MemoryStdioServer.start: missing handler for tool "${p}"`);d.register(ae(p,O));}x.info("starting memory MCP stdio server",{id:r.id,name:r.name,toolCount:l.length,isRemote:a.isRemote??true});let m=await createAndStartStdioServer(r,d),g=null,h=new Promise(p=>{g=p;}),f=p=>{x.info("received signal, stopping MCP server",{signal:p}),g?.();},R=()=>f("SIGINT"),C=()=>f("SIGTERM");process.on("SIGINT",R),process.on("SIGTERM",C);try{await h;}finally{try{process.off("SIGINT",R),process.off("SIGTERM",C);}catch(p){x.warn("failed to remove signal handlers",{error:p instanceof Error?p.message:String(p)});}try{await m.stop();}catch(p){x.warn("server.stop failed during cleanup",{error:p instanceof Error?p.message:String(p)});}}return {id:r.id,name:r.name,version:r.version,tools:l}}o.start=e;function n(){return Object.keys(k)}o.getToolNames=n;})(B||(B={}));export{w as a,B as b};
@@ -0,0 +1,59 @@
1
+ 'use strict';var chunkI5YWAJHW_cjs=require('./chunk-I5YWAJHW.cjs'),chunkBWPPLYIF_cjs=require('./chunk-BWPPLYIF.cjs'),mcp=require('@easbot/mcp'),utils=require('@easbot/utils');var W=utils.Log.create({service:"memory-format-truncate"}),F="**`";var P=24e3,j=25e3;async function $(e,n={}){let o=n.softLimit??P,r=n.hardCeiling??j,s=n.toolName??"memory",c=n.writeToDisk!==false;if(e.length<=o)return {content:e,truncated:false};let i=e.slice(0,r),t=i.lastIndexOf(`
2
+ ${F}`),a=i.lastIndexOf(`
3
+ `),d;t>r*.5?d=t:a>0?d=a:d=-1;let u=d>0?i.slice(0,d):i,m=u+"\n\n... (output truncated to budget; the source above is complete and verbatim \u2014 treat it as already Read. For any area not covered, make ANOTHER `<tool>` targeting those names \u2014 do NOT Read these files.)";if(!c)return {content:m,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-u.length}/${e.length} characters truncated ...`};try{let g=await utils.TruncateContent.truncate(e,{maxChars:u.length,direction:"head",label:`${s}-output`});return g.truncated?{content:m,truncated:!0,outputPath:g.outputPath,hint:utils.TruncateContent.formatHint(g),info:`... ${g.removedLength}/${g.originalLength} characters truncated ...`}:{content:m,truncated:!0,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-u.length}/${e.length} characters truncated ...`}}catch(g){return W.warn("TruncateContent.truncate failed, returning without disk hint",{error:g instanceof Error?g.message:String(g)}),{content:m,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-u.length}/${e.length} characters truncated ...`}}}function b(e,n={}){let o=n.softLimit??P,r=n.hardCeiling??j;if(e.length<=o)return {content:e,truncated:false};let s=e.slice(0,r),c=s.lastIndexOf(`
4
+ ${F}`),i=s.lastIndexOf(`
5
+ `),t;c>r*.5?t=c:i>0?t=i:t=-1;let a=t>0?s.slice(0,t):s;return {content:a+`
6
+
7
+ ... (output truncated; tail dropped at section boundary)`,truncated:true,outputPath:"",hint:"",info:`... ${e.length-a.length}/${e.length} characters truncated ...`}}function K(e,n){if(!e||e.length===0)return null;let o=e.filter(s=>n.has(s.path));return o.length===0?null:`\u26A0\uFE0F Index may be stale for: ${o.map(s=>`${s.path} (edited pending)`).join(", ")}
8
+
9
+ `}function I(e,n,o={}){return (q[e]??q.default).replace(/<(\w+)>/g,(s,c)=>c==="tool"?n:o[c]??`<${c}>`)}var q={recall:"If you need more facts, make ANOTHER `<tool>` query with a different scope / interval.\nIf you have enough context, proceed with the current task. Do NOT call `<tool>` again for the same query.",remember:"Memory persisted. To recall it later, use `<tool>` with the same query.\nDo NOT call `<tool>` again to verify \u2014 the fact is already in the database.",forget:"Memory deleted. To verify, run `<tool>` with the same filter (no results expected).\nIf you deleted too much, the data is gone (no auto-restore).",graph_query:"If you need to explore further, make ANOTHER `<tool>` from a different start node or depth.\nOtherwise, the graph is complete for this scope.",status:"Status snapshot. To inspect a specific fact, use `<tool>` (recall) with its id.\nOtherwise, this is a complete read.",consolidate:"Consolidation done. To inspect the new facts, use `<tool>` with the same agentId.\nIf you want to undo, archives are in <archive_dir>.",doctor:"Doctor report. To fix a failing check, run with `repair=true`.\nRe-run after fix to confirm.",default:"If you need more, make ANOTHER `<tool>` with refined parameters.\nOtherwise, this is a complete read."};function G(e,n,o,r){let s=e.tags&&e.tags.length>0?`
10
+ - tags: ${e.tags.join(", ")}`:"",c=e.sessionId?`
11
+ - session: ${e.sessionId}`:"",i=e.msgId?`
12
+ - msg: ${e.msgId}`:"",t=typeof n=="number"?`
13
+ - score: ${n.toFixed(3)}${o?` (${o})`:""}`:"",a=e.truncated?" [truncated]":"",d="";if(r&&r.length>0){let u=[];for(let l of r){let m=[];if(l.edges&&l.edges.length>0)for(let h of l.edges){let f=h.direction??(h.source===l.id?"out":"in"),R=h.targetNode?.name??String(h.target),C=h.targetNode?.type??"node";m.push(` --[${f}] ${h.relation}--> ${R} (${C})`);}let g=m.length>0?m.join(`
14
+ `):" (no relations)";u.push(` - Node: ${l.name} (${l.type})
15
+ ${g}`);}d=`
16
+ - linked KG nodes (${r.length}):
17
+ ${u.join(`
18
+ `)}`;}return [`### \`${e.id}\`${a}`,` - agentId: ${e.agentId}`,` - category: ${e.category}`,` - importance: ${e.importance}`,` - createdAt: ${e.createdAt}`,` - updatedAt: ${e.updatedAt}`,` - source: ${e.source}${t}${s}${c}${i}${d}`,"",e.content,""].join(`
19
+ `)}async function x(e,n){let o=n.toolName??"memory_recall",r=`**\`memory_recall:${n.query.slice(0,40).replace(/[^a-zA-Z0-9_]/g,"_")}\`**`,s=K(n.pendingFiles,new Set),i=[`Found ${e.total} fact(s) for query "${n.query}" (agentId=${n.agentId}, scope=${n.scope}):`,"",s??"",r].join(`
20
+ `),t=new Map;for(let l of e.hits){let m=l.fact.category;t.has(m)||t.set(m,[]),t.get(m).push(l);}let a=Array.from(t.entries()).map(([l,m])=>{let g=`**\`category:${l}\`**`,h=m.map(f=>G(f.fact,f.score,f.source,f.nodes)).join(`
21
+ `);return `${g}
22
+
23
+ ${h}`}).join(`
24
+ `),d=e.warnings&&e.warnings.length>0?`
25
+
26
+ \u26A0\uFE0F warnings:
27
+ ${e.warnings.map(l=>` - ${l}`).join(`
28
+ `)}
29
+ `:"",u=`${i}
30
+
31
+ ${a}${d}
32
+
33
+ ${I("recall",o)}`;return n.sync?b(u,{}).content:(await $(u,{toolName:o,writeToDisk:n.writeToDisk})).content}async function D(e,n={}){let o=n.toolName??"memory_remember",r=`**\`memory_remember:${e.fact.id}\`**`,s=G(e.fact),c=e.nodeIds??[],i=c.length>0?`
34
+ - linked KG nodes: ${c.join(", ")}
35
+ `:"",t=`${r}
36
+
37
+ ${s}${i}
38
+
39
+ ${I("remember",o)}`;return n.sync?b(t,{}).content:(await $(t,{toolName:o,writeToDisk:n.writeToDisk})).content}async function N(e,n={}){let o=n.toolName??"memory_forget",r="**`memory_forget:result`**",s=e.dryRun?"**DRY RUN** \u2014 no facts were actually deleted. Run again without dryRun to execute.":`Deleted ${e.deletedCount} fact(s).`,c=e.truncatedCount>0?` (truncated: ${e.truncatedCount} more, re-run with narrower filter)`:"",i=[r,"",s+c,"",e.deletedIds.length>0?`deleted ids:
40
+ ${e.deletedIds.map(t=>` - ${t}`).join(`
41
+ `)}`:"(no ids to show)","",I("forget",o)].join(`
42
+ `);return n.sync?b(i,{}).content:(await $(i,{toolName:o,writeToDisk:n.writeToDisk})).content}async function S(e,n={}){let o=n.toolName??"memory_graph_query",r=`**\`memory_graph_query:scope=${e.scope}\`**`,s=e.nodes.map(t=>` - node #${t.id}: ${t.name} (${t.type})${t.ownerAgentId?` [owner=${t.ownerAgentId}]`:" [shared]"}`).join(`
43
+ `),c=e.edges.map(t=>` - edge #${t.id}: ${t.source} --${t.relation}--> ${t.target}`).join(`
44
+ `),i=[r,"",`nodes (${e.nodes.length}${e.truncated?` / total ${e.totalNodes}`:""}):`,s||" (none)","",`edges (${e.edges.length}${e.truncated?` / total ${e.totalEdges}`:""}):`,c||" (none)","",I("graph_query",o)].join(`
45
+ `);return n.sync?b(i,{}).content:(await $(i,{toolName:o,writeToDisk:n.writeToDisk})).content}async function M(e,n={}){let o=n.toolName??"memory_status",c=["**`memory_status`**","",`dbPath: ${e.dbPath}`,`workspaceDir: ${e.workspaceDir}`,`factsCount: ${e.factsCount}`,`nodesCount: ${e.nodesCount} (KG nodes)`,`edgesCount: ${e.edgesCount} (KG edges)`,`ftsAvailable: ${e.ftsAvailable?"yes":"no"}`,`vectorEnabled: ${e.vectorEnabled?"yes":"no"}`,`kgScopeEnabled: ${e.kgScopeEnabled?"yes":"no"}`,`healthy: ${e.healthy?"yes":"no"}`,"","factsByCategory:",...Object.entries(e.factsByCategory).map(([i,t])=>` - ${i}: ${t}`),"","meta:",...Object.entries(e.meta).map(([i,t])=>` - ${i}: ${t}`),"",I("status",o)].join(`
46
+ `);return n.sync?b(c,{}).content:(await $(c,{toolName:o,writeToDisk:n.writeToDisk})).content}async function v(e,n={}){let o=n.toolName??"memory_consolidate",s=["**`memory_consolidate:result`**","",`total facts scanned: ${e.totalFacts}`,`deduped (merged): ${e.dedupedCount}`,`compressed: ${e.compressedCount}`,`archived to archive/: ${e.archivedCount}`,`skipped (no change): ${e.skippedCount}`,`duration: ${e.durationMs}ms`,"",I("consolidate",o)].join(`
47
+ `);return n.sync?b(s,{}).content:(await $(s,{toolName:o,writeToDisk:n.writeToDisk})).content}async function _(e,n={}){let o=n.toolName??"memory_doctor",r=`**\`memory_doctor:${e.healthy?"OK":"ISSUES"}\`**`,s=t=>t?"\u2705":"\u274C",c=e.checks.map(t=>`${s(t.passed)} ${t.name}: ${t.message}`).join(`
48
+ `),i=[r,"",c,"",I("doctor",o)].join(`
49
+ `);return n.sync?b(i,{}).content:(await $(i,{toolName:o,writeToDisk:n.writeToDisk})).content}async function w(e,n,o={}){let r=n,s=typeof r.kind=="string";switch((s?r:{kind:e}).kind){case "recall":{let i=s?{hits:r.hits,total:r.totalCount??r.total??0,truncated:r.truncated??false}:n;return x(i,{...o,query:r.query??o.query??"",agentId:r.agentId??o.agentId??"",scope:r.scope??o.scope??"agent_only"})}case "remember":{let i=s?{fact:r.fact,nodeIds:r.nodeIds}:n;return D(i,o)}case "forget":return N(s?r:n,o);case "graph_query":return S(s?r:n,o);case "status":return M(s?r:n,o);case "consolidate":return v(s?r:n,o);case "doctor":return _(s?r:n,o);default:throw new Error(`renderOperationMarkdown: unsupported op "${e}"`)}}var E=utils.Log.create({service:"memory-mcp-stdio"});function re(e){let n=new Map,o=e.isRemote??true,r=!o;function s(t){let{Locale:a}=chunkBWPPLYIF_cjs.a("@easbot/utils"),d=a.resolveLocaleLang();return {agentId:t.agentId??e.agentId,isTrustedLocal:t.isTrustedLocal??r,remote:o,locale:d,dbPath:e.dbPath,workspaceDir:e.workspaceDir,rootDir:e.workspaceDir,config:chunkI5YWAJHW_cjs.n({agentId:e.agentId,dbPath:e.dbPath})}}function c(t,a){return {content:[{type:"text",text:t}],isError:a}}function i(t){return mcp.formatFailClosed(t,r)}return n.set("recall",async t=>{try{let a=t,d=s({agentId:a.agentId}),u=await chunkI5YWAJHW_cjs.m("recall",t,d);return {content:[{type:"text",text:await w("recall",u,{toolName:"memory_recall",query:a.query,agentId:a.agentId??e.agentId,scope:a.scope??"agent_only"})}]}}catch(a){return c(i(a),true)}}),n.set("remember",async t=>{try{let d=s({agentId:t.agentId}),u=await chunkI5YWAJHW_cjs.m("remember",t,d);return {content:[{type:"text",text:await w("remember",u,{toolName:"memory_remember"})}]}}catch(a){return c(i(a),true)}}),n.set("forget",async t=>{try{let d=s({agentId:t.agentId}),u=await chunkI5YWAJHW_cjs.m("forget",t,d);return {content:[{type:"text",text:await w("forget",u,{toolName:"memory_forget"})}]}}catch(a){return c(i(a),true)}}),n.set("extract",async t=>{try{let d=s({agentId:t.agentId}),l=await chunkI5YWAJHW_cjs.m("extract",t,d);return {content:[{type:"text",text:`Extract completed.
50
+ sessionId: ${t.sessionId??"(unknown)"}
51
+ extractedCount: ${l.extractedCount}
52
+ factIds: ${l.factIds.length>0?l.factIds.join(", "):"(none)"}
53
+ messageRange: ${l.messageRange.fromMessageId} -> ${l.messageRange.toMessageId}
54
+ `}]}}catch(a){return c(i(a),true)}}),n.set("consolidate",async t=>{try{let d=s({agentId:t.agentId,isTrustedLocal:!0}),u=await chunkI5YWAJHW_cjs.m("consolidate",t,d);return {content:[{type:"text",text:await w("consolidate",u,{toolName:"memory_consolidate"})}]}}catch(a){return c(i(a),true)}}),n.set("graph_query",async t=>{try{let a=t,d=s({agentId:a.agentId}),u=await chunkI5YWAJHW_cjs.m("graph_query",t,d);return {content:[{type:"text",text:await w("graph_query",u,{toolName:"memory_graph_query",scope:a.scope??"agent_only"})}]}}catch(a){return c(i(a),true)}}),n.set("status",async t=>{try{let d=s({agentId:(t??{}).agentId}),u=await chunkI5YWAJHW_cjs.m("status",t,d);return {content:[{type:"text",text:await w("status",u,{toolName:"memory_status"})}]}}catch(a){return c(i(a),true)}}),n.set("doctor",async t=>{try{let d=s({agentId:(t??{}).agentId,isTrustedLocal:!0}),u=await chunkI5YWAJHW_cjs.m("doctor",t,d);return {content:[{type:"text",text:await w("doctor",u,{toolName:"memory_doctor"})}]}}catch(a){return c(i(a),true)}}),n.set("init",async t=>{try{let a=s({isTrustedLocal:!0}),u=await chunkI5YWAJHW_cjs.m("init",t,a);return {content:[{type:"text",text:`Init complete.
55
+ dbPath: ${u.dbPath}
56
+ tablesCreated: ${u.tablesCreated}
57
+ migrationsApplied: ${u.migrationsApplied}
58
+ durationMs: ${u.durationMs}
59
+ `}]}}catch(a){return c(i(a),true)}}),n}function se(e,n){let o=chunkI5YWAJHW_cjs.k[e],r={title:o?.annotations?.defaultDescription??e,readOnlyHint:o?.annotations?.readOnlyHint??false,destructiveHint:o?.annotations?.destructiveHint??false,idempotentHint:o?.annotations?.idempotentHint??true,openWorldHint:false};return {name:e,description:o?.annotations?.defaultDescription??`memory op: ${e}`,inputSchema:{type:"object",properties:{},required:[]},annotations:r,handler:n}}exports.b=void 0;(o=>{async function e(r,s){let{getMemoryDbPath:c,getInstance:i}=await import('./interfaces-KNVKCV3Q.cjs'),a=s!==null&&typeof s=="object"&&"agentId"in s&&"dbPath"in s?s:{agentId:process.env.EASBOT_AGENT_ID??"default",dbPath:c(),workspaceDir:i().worktree,isRemote:false},d=new mcp.ToolRegistry,u=re(a),l=Object.keys(chunkI5YWAJHW_cjs.k);for(let p of l){let A=u.get(p);if(!A)throw new Error(`MemoryStdioServer.start: missing handler for tool "${p}"`);d.register(se(p,A));}E.info("starting memory MCP stdio server",{id:r.id,name:r.name,toolCount:l.length,isRemote:a.isRemote??true});let m=await mcp.createAndStartStdioServer(r,d),g=null,h=new Promise(p=>{g=p;}),f=p=>{E.info("received signal, stopping MCP server",{signal:p}),g?.();},R=()=>f("SIGINT"),C=()=>f("SIGTERM");process.on("SIGINT",R),process.on("SIGTERM",C);try{await h;}finally{try{process.off("SIGINT",R),process.off("SIGTERM",C);}catch(p){E.warn("failed to remove signal handlers",{error:p instanceof Error?p.message:String(p)});}try{await m.stop();}catch(p){E.warn("server.stop failed during cleanup",{error:p instanceof Error?p.message:String(p)});}}return {id:r.id,name:r.name,version:r.version,tools:l}}o.start=e;function n(){return Object.keys(chunkI5YWAJHW_cjs.k)}o.getToolNames=n;})(exports.b||(exports.b={}));exports.a=w;
@@ -0,0 +1 @@
1
+ 'use strict';var chunk3HTZTI7U_cjs=require('./chunk-3HTZTI7U.cjs'),utils=require('@easbot/utils'),terminal=require('@easbot/terminal');var h=utils.Log.create({service:"memory-cli"}),w=[{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.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 9 memory tools)",group:"external"}];function m(d,p){let o=w.filter(a=>a.group===d);return terminal.renderLines({title:p,flat:o.map(a=>`$ easbot-memory ${a.name.padEnd(14)} ${a.description}`)})}function x(){let d=[terminal.renderLines({title:"easbot-memory \xB7 Memory & Knowledge Module for EASBot",flat:["Usage: easbot-memory <command> [options]"]}),"",m("lifecycle","Commands (lifecycle):"),"",m("memory","Commands (memory):"),"",m("session","Commands (session):"),"",m("graph","Commands (graph query):"),"",m("external","External:")];terminal.printHuman(d);}function b(){x(),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(d,p){let[o,...a]=d,l=p?.cwd??process.cwd();if(!o)return b(),{code:0,handled:true,command:null};try{switch(o){case "init":{let{parseInitOptions:r,runInit:n,formatInitText:s}=await import('./init-2GZLH6RB.cjs'),e=r(a);if(e.help)return console.log("Usage: easbot-memory init --workspace-dir <dir> [--agent <id>] [--force] [--json]"),{code:0,handled:!0,command:o};let t=await n({...e,ctxWorkspaceDir:l});return e.json?terminal.emitJsonOk(t,{command:o}):terminal.printHuman([s(t)],{title:"init memory workspace"}),{code:0,handled:!0,command:o}}case "recall":{let{parseRecallOptions:r,runRecall:n,formatRecallText:s}=await import('./recall-JI2NYDLH.cjs'),e=r(a);if(e.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:o};let t=await n({...e,workspaceDir:l});return e.json?terminal.emitJsonOk(t,{command:o}):terminal.printHuman([s(t)],{title:`recall (agentId=${e.agentId??"default"})`}),{code:0,handled:!0,command:o}}case "remember":{let{parseRememberOptions:r,runRemember:n,formatRememberText:s}=await import('./remember-X33PMYA5.cjs'),e=r(a);if(e.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:o};let t=await n({...e,workspaceDir:l});return e.json?terminal.emitJsonOk(t,{command:o}):terminal.printHuman([s(t)],{title:"remember (persist fact)"}),{code:0,handled:!0,command:o}}case "forget":{let{parseForgetOptions:r,runForget:n,formatForgetText:s}=await import('./forget-GEAEUNRH.cjs'),e=r(a);if(e.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:o};let t=await n({...e,workspaceDir:l});return e.json?terminal.emitJsonOk(t,{command:o}):terminal.printHuman([s(t)],{title:"forget (delete facts)"}),{code:0,handled:!0,command:o}}case "extract":{let{parseExtractOptions:r,runExtract:n,formatExtractText:s}=await import('./extract-E54PPHMQ.cjs'),e=r(a);if(e.help)return console.log("Usage: easbot-memory extract --session <sessionId> [--agent <id>] [--last-n <n>] [--from-msg <id>] [--json]"),{code:0,handled:!0,command:o};let t=await n({...e,workspaceDir:l});return e.json?terminal.emitJsonOk(t,{command:o}):terminal.printHuman([s(t)],{title:"extract (from session)"}),{code:0,handled:!0,command:o}}case "consolidate":{let{parseConsolidateOptions:r,runConsolidate:n,formatConsolidateText:s}=await import('./consolidate-YQ3H643L.cjs'),e=r(a);if(e.help)return console.log("Usage: easbot-memory consolidate [--agent <id>] [--window-days <n>] [--json]"),{code:0,handled:!0,command:o};let t=await n({...e,workspaceDir:l});return e.json?terminal.emitJsonOk(t,{command:o}):terminal.printHuman([s(t)],{title:"consolidate (pipeline)"}),{code:0,handled:!0,command:o}}case "graph":{let{parseGraphOptions:r,runGraph:n,formatGraphText:s}=await import('./graph-QEGKUROQ.cjs'),e=r(a);if(e.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:o};let t=await n({...e,workspaceDir:l});return e.json?terminal.emitJsonOk(t,{command:o}):terminal.printHuman([s(t)],{title:`graph_query (scope=${e.scope??"agent_only"})`}),{code:0,handled:!0,command:o}}case "status":{let{parseStatusOptions:r,runStatus:n,formatStatusText:s}=await import('./status-CPB6XZNU.cjs'),e=r(a);if(e.help)return console.log("Usage: easbot-memory status [--agent <id>] [--json]"),{code:0,handled:!0,command:o};let t=await n({...e,workspaceDir:l});return e.json?terminal.emitJsonOk(t,{command:o}):terminal.printHuman([s(t)],{title:"memory status"}),{code:0,handled:!0,command:o}}case "doctor":{let{parseDoctorOptions:r,runDoctor:n,formatDoctorText:s}=await import('./doctor-GVSMK4HL.cjs'),e=r(a);if(e.help)return console.log("Usage: easbot-memory doctor [--repair] [--json]"),{code:0,handled:!0,command:o};let t=await n({...e,workspaceDir:l});return e.json?terminal.emitJsonOk(t,{command:o}):terminal.printHuman([s(t)],{title:"doctor"}),{code:0,handled:!0,command:o}}case "config":{let{parseConfigOptions:r,runConfig:n,formatConfigText:s}=await import('./config-BFJFRX2C.cjs'),e=r(a);if(e.help)return console.log("Usage: easbot-memory config [--json]"),{code:0,handled:!0,command:o};let t=n(e);return e.json?terminal.emitJsonOk(t,{command:o}):terminal.printHuman([s(t)],{title:"memory config"}),{code:0,handled:!0,command:o}}case "mcp":{let{parseMcpOptions:r,runMcp:n}=await import('./mcp-WE7TV32J.cjs'),s=r(a);if(s.help)return console.log("Usage: easbot-memory mcp [start]"),console.log("Start a stdio MCP server exposing 9 memory tools:"),console.log(" recall / remember / forget / extract / consolidate"),console.log(" graph_query / status / doctor / init"),{code:0,handled:!0,command:o};let e=await n(s);return s.json?terminal.emitJsonOk(e,{command:o}):terminal.printHuman([`memory mcp started (tools: ${e.tools.length})`],{title:"memory mcp server"}),{code:0,handled:!0,command:o}}default:return console.error(`Unknown command: ${o}`),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);h.error("memory CLI command failed",{command:o,error:n,stack:r instanceof Error?r.stack:void 0});let s=p?.cwd??chunk3HTZTI7U_cjs.f().worktree;return console.error(`[memory] ${s} :: ${o} failed: ${n}`),terminal.emitJsonError(o,n),{code:1,handled:true,command:o}}}exports.a=w;exports.b=x;exports.c=b;exports.d=I;
@@ -0,0 +1 @@
1
+ 'use strict';var chunk7XEOH55R_cjs=require('./chunk-7XEOH55R.cjs');function o(r,t){return chunk7XEOH55R_cjs.a(`memory.${r}.empty`,{fallback:t})}function s(r,t,m){return chunk7XEOH55R_cjs.a(`memory.${r}.summary`,{vars:t,fallback:m})}function g(r,t,m){return chunk7XEOH55R_cjs.a(`memory.${r}.item`,{vars:t,fallback:m})}exports.a=o;exports.b=s;exports.c=g;
@@ -0,0 +1,32 @@
1
+ import {e,a}from'./chunk-5W4K5UKV.mjs';import {j as j$1}from'./chunk-YHOJKRHE.mjs';import {b}from'./chunk-WQGSYA5D.mjs';import {Log,Locale}from'@easbot/utils';import {randomBytes}from'crypto';import z$1 from'path';import L from'fs/promises';import {z}from'zod';import {DEFAULT_SEARCH_CONFIG}from'@easbot/types';var q=Log.create({service:"memory.graph-store"}),N=class{constructor(e){b(this,"db");this.db=e;}async upsertNode(e,n,o,i){let l=Date.now(),a=JSON.stringify(o??{}),s=this.db.prepare("SELECT id FROM nodes WHERE name = ? AND type = ? LIMIT 1").get(e,n);if(s)return this.db.prepare("UPDATE nodes SET properties = ?, updatedAt = ? WHERE id = ?").run(a,l,s.id),s.id;let c=this.db.prepare("INSERT INTO nodes (name, type, properties, owner_agent_id, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)").run(e,n,a,i??null,l,l);return Number(c.lastInsertRowid)}async deleteNode(e){this.db.prepare("DELETE FROM nodes WHERE id = ?").run(e);}async upsertEdge(e,n,o,i){let l=this.db.prepare("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)").run(e,n,o,JSON.stringify(i??{}),Date.now());return Number(l.lastInsertRowid)}async queryNodes(e={}){let n="SELECT id, name, type, properties, owner_agent_id, createdAt, updatedAt FROM nodes",o=[],i=[];if(e.ids&&e.ids.length>0){let a=e.ids.map(s=>typeof s=="string"?parseInt(s,10):s).filter(s=>!Number.isNaN(s));i.push(`id IN (${a.map(()=>"?").join(", ")})`),o.push(...a);}e.name&&(i.push("name LIKE ?"),o.push(`%${e.name}%`)),e.type&&(i.push("type = ?"),o.push(e.type)),xe(i,o,e.agentId,e.scope??"agent_only"),i.length>0&&(n+=` WHERE ${i.join(" AND ")}`),n+=" ORDER BY id",e.limit&&(n+=" LIMIT ?",o.push(e.limit)),q.debug("queryNodes",{sql:n,params:o,filter:e});let l=this.db.prepare(n).all(...o);return q.debug("queryNodes result",{count:l.length}),l.map(a=>({id:a.id,name:a.name,type:a.type,properties:a.properties?JSON.parse(a.properties):void 0,createdAt:a.createdAt,updatedAt:a.updatedAt,ownerAgentId:a.owner_agent_id}))}async queryEdges(e={}){let n="SELECT e.id, e.source, e.target, e.relation, e.properties, e.createdAt FROM edges e",o=[],i=[];if(e.ids&&e.ids.length>0&&(i.push(`e.id IN (${e.ids.map(()=>"?").join(", ")})`),o.push(...e.ids)),e.source!==void 0&&(i.push("e.source = ?"),o.push(e.source)),e.target!==void 0&&(i.push("e.target = ?"),o.push(e.target)),e.sourceOrTarget&&e.sourceOrTarget.length>0){let m=e.sourceOrTarget.map(d=>typeof d=="string"?parseInt(d,10):d).filter(d=>!Number.isNaN(d));i.push(`(e.source IN (${m.map(()=>"?").join(", ")}) OR e.target IN (${m.map(()=>"?").join(", ")}))`),o.push(...m,...m);}e.relation&&(i.push("e.relation = ?"),o.push(e.relation)),i.length>0&&(n+=` WHERE ${i.join(" AND ")}`),n+=" ORDER BY e.id",e.limit&&(n+=" LIMIT ?",o.push(e.limit)),q.debug("queryEdges",{sql:n,params:o,filter:e});let l=this.db.prepare(n).all(...o);q.debug("queryEdges result",{count:l.length});let a=[...new Set(l.map(m=>m.target))],s=a.length>0?await this.queryNodes({ids:a,limit:a.length}):[],c=new Map(s.map(m=>[m.id,m]));return l.map(m=>{let d={id:m.id,source:m.source,target:m.target,relation:m.relation,properties:m.properties?JSON.parse(m.properties):void 0,createdAt:m.createdAt},f=c.get(m.target);return f&&(d.targetNode=f),d})}async queryNeighbors(e,n=1,o){let i=o?.agentId,l=o?.scope??"agent_only",a=new Set,s=[{id:e,level:0}],c=[],m=o?.maxEdgesPerNode??50;for(;s.length>0;){let d=s.shift();if(!d)break;if(a.has(d.id)||d.level>n)continue;a.add(d.id);let h=(await this.queryNodes({ids:[d.id],limit:1,agentId:i,scope:l}))[0];if(!h)continue;let b=await this.queryEdges({sourceOrTarget:[d.id],limit:m}),y=i?await ke(this,b,i,l):b;if(c.push({...h,edges:y}),d.level<n)for(let E of y){let u=E.source===d.id?E.target:E.source;a.has(u)||s.push({id:u,level:d.level+1});}}return c}};async function ke(t,e,n,o){if(e.length===0)return e;let i=new Set;for(let s of e)i.add(s.source),i.add(s.target);let l=await t.queryNodes({ids:Array.from(i),agentId:n,scope:o,limit:i.size}),a=new Set(l.map(s=>s.id));return e.filter(s=>a.has(s.source)&&a.has(s.target))}function xe(t,e,n,o){if(n)switch(o){case "agent_only":t.push("owner_agent_id = ?"),e.push(n);break;case "shared_only":t.push("owner_agent_id IS NULL");break;case "both":t.push("(owner_agent_id = ? OR owner_agent_id IS NULL)"),e.push(n);break}}var g=class extends Error{constructor(n,o,i){super(n);b(this,"code",o);b(this,"details",i);this.name="ServiceError";}};var F=class extends g{constructor(){super("ctx.agentId is required for memory service (ADR 0055 per-agent isolation)","AGENT_ID_REQUIRED");}},A=class extends g{constructor(e,n){super(`Trust denied for operation "${e}": ${n}`,"TRUST_DENIED",{operation:e,reason:n});}},P=class extends g{constructor(e,n){super(`Memory ${e} has ${n} references (force=false)`,"HAS_REFERENCES",{memoryId:e,referenceCount:n});}},k=class extends g{constructor(e){super(`dryRun mode: ${e} memories matched but not deleted`,"DRY_RUN_NO_DELETE",{matchedCount:e});}},x=class extends g{constructor(e,n){super(`Matched ${e} memories exceeds maxDelete=${n}`,"MAX_DELETE_EXCEEDED",{matched:e,maxDelete:n});}};function O(t){if(typeof t.agentId!="string"||t.agentId.length===0)throw new F}function T(t,e){if(t.remote!==false)throw new A(e,"requires trusted local caller (CLI / agent tool / MCP with remote=false)")}function H(t,e,n){if(e!=="agent_only"&&t.remote!==false)throw new A(n,`scope="${e}" requires trusted local caller (cross-agent access denied)`)}function $(t){if(!t.dbPath||t.dbPath.trim().length===0)throw new g("service ctx.dbPath is required (MemoryKnowledgeConfigWithModels.database.path)","INTERNAL")}var G=Log.create({service:"memory.service.recall"});async function me(t,e$1){let n=Date.now();if(O(t),$(t),!e$1.query||e$1.query.trim().length===0)throw new g("recall requires non-empty `query`","CONTENT_REQUIRED");let o=e$1.includeShared?"both":"agent_only";e$1.includeGraph&&H(t,o,"recall"),G.debug("recall invoked",{agentId:t.agentId,query:e$1.query,category:e$1.category,maxResults:e$1.maxResults,includeGraph:e$1.includeGraph,scope:o});let i=e$1.maxResults??10,l=e$1.minScore??0,a=[],s=new e(t.dbPath);try{await s.initialize();let c=await qe(s,t.agentId,e$1.query,{category:e$1.category,minImportance:e$1.minImportance,fromTime:e$1.fromTime,toTime:e$1.toTime,limit:i,minScore:l}),m;if(e$1.includeGraph&&c.length>0)try{let f=new N(s.getDb()),h=e$1.depth??1,b=c.flatMap(M=>(M.nodes??[]).map(R=>R.id)).slice(0,5),y=new Set,E=new Map;for(let M of b){let R=await f.queryNeighbors(M,h,{agentId:t.agentId,scope:o,maxEdgesPerNode:10});for(let _ of R)y.add(_.id),E.set(_.id,_.edges??[]);}let u=y.size>0?s.query(`SELECT id, name, type FROM nodes WHERE id IN (${Array.from(y).map(()=>"?").join(",")})`,Array.from(y)):[],p=Array.from(E.values()).flat();m={nodes:u.map(M=>({id:M.id,name:M.name,type:M.type,createdAt:"",updatedAt:""})),edges:p};}catch(f){let h=f instanceof Error?f.message:String(f);G.warn("recall: KG neighbor query failed",{error:h}),a.push(`kg_neighbor_query_failed: ${h}`),m={nodes:[],edges:[]};}let d=Date.now()-n;return {hits:c,total:c.length,truncated:c.length>=i,durationMs:d,graph:m,...a.length>0?{warnings:a}:{}}}catch(c){throw c instanceof g?c:new g(`recall failed: ${c instanceof Error?c.message:String(c)}`,"INTERNAL",{cause:c instanceof Error?c.message:String(c)})}finally{s.close();}}function qe(t,e,n,o){let i=["mf.agent_id = ?","fts.memory_facts_fts MATCH ?"],l=[e,Fe(n)];o.category&&(i.push("mf.category = ?"),l.push(o.category)),o.minImportance!==void 0&&(i.push("mf.importance >= ?"),l.push(o.minImportance)),o.fromTime&&(i.push("mf.created_at >= ?"),l.push(o.fromTime)),o.toTime&&(i.push("mf.created_at <= ?"),l.push(o.toTime));try{return t.query(`SELECT
2
+ mf.id as memoryId,
3
+ mf.category,
4
+ mf.importance,
5
+ mf.agent_id as agentId,
6
+ SUBSTR(mf.content, 1, 200) as snippet,
7
+ bm25(memory_facts_fts) as score,
8
+ mf.created_at as createdAt,
9
+ mf.source,
10
+ mf.file_path as filePath,
11
+ mf.node_ids as nodeIds
12
+ FROM memory_facts_fts fts
13
+ JOIN memory_facts mf ON mf.id = fts.fact_id
14
+ WHERE ${i.join(" AND ")}
15
+ ORDER BY score DESC
16
+ LIMIT ?`,[...l,o.limit]).map(s=>({memoryId:s.memoryId,category:s.category,importance:s.importance,agentId:s.agentId,snippet:s.snippet,score:Math.abs(s.score),createdAt:s.createdAt,source:s.source,filePath:s.filePath??void 0,nodes:void 0})).filter(s=>s.score>=o.minScore)}catch(a){if(a instanceof g)throw a;return G.warn("FTS search failed, returning empty result",{err:a instanceof Error?a.message:String(a)}),[]}}function Fe(t){return t.trim().split(/\s+/).filter(e=>e.length>0).map(e=>`"${e.replace(/"/g,'""')}"`).join(" ")}var le=Log.create({service:"memory.service.remember"});async function ge(t,e$1){if(O(t),$(t),!e$1.content||e$1.content.trim().length===0)throw new g("remember requires non-empty `content`","CONTENT_REQUIRED");if(!e$1.category)throw new g("remember requires `category`","CATEGORY_REQUIRED");le.debug("remember invoked",{agentId:t.agentId,category:e$1.category,importance:e$1.importance??5,contentLength:e$1.content.length,skipDedup:e$1.skipDedup,extractGraph:e$1.extractGraph??true});let n=new e(t.dbPath);try{await n.initialize();let o=new Date().toISOString(),i=Ue(),l=e$1.importance??5,{entities:a,relations:s}=e$1.extractGraph!==!1?je(e$1.content):{entities:[],relations:[]},c=[];return n.transaction(()=>{let d=new Map;for(let f of a){let h=n.query("SELECT id FROM nodes WHERE name = ? AND type = ? LIMIT 1",[f.name,f.type])[0];if(h){d.set(f.name,h.id);continue}let b=n.run("INSERT INTO nodes (name, type, properties, owner_agent_id, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)",[f.name,f.type,JSON.stringify({source:"rule_extracted"}),t.agentId,o,o]);b.lastID>0&&d.set(f.name,b.lastID);}for(let f of s){let h=d.get(f.source),b=d.get(f.target);!h||!b||n.run("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)",[h,b,f.relation,JSON.stringify({}),o]);}n.run(`INSERT INTO memory_facts
17
+ (id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance,
18
+ source, tags, node_ids, file_path, created_at, updated_at)
19
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i,t.agentId,e$1.sessionId??null,e$1.msgId??null,e$1.parentMsgId??null,e$1.content,e$1.category,l,"session_self_write",e$1.tags?JSON.stringify(e$1.tags):null,JSON.stringify(Array.from(d.values())),null,o,o]),n.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[i]),n.run("INSERT INTO memory_facts_fts (fact_id, agent_id, content, tags) VALUES (?, ?, ?, ?)",[i,t.agentId,e$1.content,e$1.tags?e$1.tags.join(" "):""]),c.push(...Array.from(d.values()));}),le.info("Memory stored",{id:i,category:e$1.category,agentId:t.agentId,nodeCount:c.length}),{fact:{id:i,agentId:t.agentId,sessionId:e$1.sessionId,msgId:e$1.msgId,parentMsgId:e$1.parentMsgId,content:e$1.content,category:e$1.category,importance:l,source:"session_self_write",tags:e$1.tags,nodeIds:c.length>0?c:void 0,filePath:void 0,createdAt:o,updatedAt:o},filePath:"",deduplicated:!1,nodeIds:c}}catch(o){throw o instanceof g?o:new g(`remember failed: ${o instanceof Error?o.message:String(o)}`,"INTERNAL",{cause:o instanceof Error?o.message:String(o)})}finally{n.close();}}function Ue(){let t=Date.now(),e=randomBytes(3).toString("hex");return `mem_${t}_${e}`}function je(t){let e=[],n=[],o=new Set,i=new Set,l=/([A-Za-z][\w.-]{1,80})\s+(is_a|part_of|has_attribute|located_in|occurs_in|causes|influences|owned_by|member_of|uses|depends_on|related_to)\s+([A-Za-z][\w.-]{1,80})/g;for(let a of t.matchAll(l)){let s=(a[1]??"").trim(),c=(a[2]??"related_to").trim(),m=(a[3]??"").trim();if(!s||!m||s===m)continue;o.has(s.toLowerCase())||(o.add(s.toLowerCase()),e.push({name:s,type:ue(s)})),o.has(m.toLowerCase())||(o.add(m.toLowerCase()),e.push({name:m,type:ue(m)}));let d=`${s.toLowerCase()}|${m.toLowerCase()}|${c}`;i.has(d)||(i.add(d),n.push({source:s,target:m,relation:c}));}return {entities:e,relations:n}}function ue(t){let e=t.toLowerCase();return /(\.md|\.ts|\.json|readme|doc|spec|guideline)/i.test(t)?"document":/(api|service|system|engine|pipeline|server|db|database|memorysystem|contextengine)/i.test(e)?"process":/(team|group|org|company|inc|ltd|corp)/i.test(e)?"organization":/(task|issue|ticket|todo|action)/i.test(e)?"task":/(file|model|dataset|artifact|resource|tool|sdk|ollama|sqlite|embedding|vector|fts)/i.test(e)||/[A-Z]/.test(t)&&e!==t?"object":"keyword"}var pe=Log.create({service:"memory.service.forget"}),Ge=1e3;function Qe(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 g("CONTENT_REQUIRED: forget requires one of: `factId`, `category`, or `fromTime`/`toTime`","CONTENT_REQUIRED");if(e.length>1)throw new g(`mutually exclusive: forget requires exactly one of factId/category/timeRange, got [${e.join(", ")}]`,"CONTENT_REQUIRED");return e[0]}function Be(t,e,n){let o=[n];switch(t){case "factId":return {where:"agent_id = ? AND id = ?",args:[...o,e.factId]};case "category":return {where:"agent_id = ? AND category = ?",args:[...o,e.category]};case "timeRange":{let i=["agent_id = ?"];return e.fromTime&&(i.push("created_at >= ?"),o.push(e.fromTime)),e.toTime&&(i.push("created_at <= ?"),o.push(e.toTime)),{where:i.join(" AND "),args:o}}}}function ze(t,e,n,o){return t.query(`SELECT id, node_ids FROM memory_facts WHERE ${e} LIMIT ?`,[...n,o+1]).map(l=>l.id)}function Ke(t,e,n,o){if(n.length===0)return 0;let i=n.map(()=>"?").join(",");return t.query(`SELECT COUNT(*) as count FROM memory_facts WHERE agent_id = ? AND id != ? AND node_ids IS NOT NULL AND EXISTS (
20
+ SELECT 1 FROM json_each(node_ids) AS je WHERE je.value IN (${i})
21
+ )`,[o,e,...n])[0]?.count??0}function Je(t,e,n){t.transaction(()=>{let o=t.query("SELECT node_ids, content FROM memory_facts WHERE id = ? AND agent_id = ?",[e,n])[0],i=[];if(o?.node_ids)try{i=JSON.parse(o.node_ids),Array.isArray(i)||(i=[]);}catch{i=[];}if(t.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[e]),t.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[e,n]),i.length>0){let l=i.map(()=>"?").join(",");t.run(`DELETE FROM nodes WHERE id IN (${l}) AND NOT EXISTS (
22
+ SELECT 1 FROM memory_facts WHERE node_ids IS NOT NULL AND EXISTS (
23
+ SELECT 1 FROM json_each(node_ids) AS je WHERE je.value = nodes.id
24
+ )
25
+ )`,i);}});}async function fe(t,e$1){O(t),T(t,"forget");let n=Qe(e$1),o=e$1.maxDelete??Ge,i=e$1.dryRun??false,l=e$1.force??false;pe.debug("forget invoked",{agentId:t.agentId,mode:n,maxDelete:o,dryRun:i,force:l});let a=new e(t.dbPath);try{await a.initialize();let{where:s,args:c}=Be(n,e$1,t.agentId),m=ze(a,s,c,o),d=m.length>o;if(d&&!l)throw new x(m.length,o);let f=d?m.slice(0,o):m;if(i)throw new k(f.length);let h=[];for(let b of f){if(!l){let y=a.query("SELECT node_ids FROM memory_facts WHERE id = ? AND agent_id = ?",[b,t.agentId])[0],E=y?.node_ids?(()=>{try{let p=JSON.parse(y.node_ids);if(Array.isArray(p))return p.filter(M=>typeof M=="number")}catch{}return []})():[],u=Ke(a,b,E,t.agentId);if(u>0)throw new P(b,u)}Je(a,b,t.agentId),h.push(b);}return pe.info("forget complete",{agentId:t.agentId,mode:n,deletedCount:h.length,force:l,dryRun:i}),{deletedCount:h.length,deletedIds:h,dryRun:i,truncatedCount:d?m.length-o:0}}catch(s){throw s instanceof g?s:new g(`forget failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{a.close();}}var Q=Log.create({service:"memory.service.extract"}),Ve=50,B=500;async function ye(t,e$1){if(O(t),!e$1.sessionId||e$1.sessionId.trim().length===0)throw new g("extract requires non-empty `sessionId`","SESSION_ID_REQUIRED");let n=e$1.lastN??Ve;if(n>B)throw new g(`extract lastN=${n} exceeds max=${B}`,"CONTENT_REQUIRED",{lastN:n,maxLastN:B});let o=e$1.sessionId,i=e$1.fromMessageId;Q.debug("extract invoked",{agentId:t.agentId,sessionId:o,lastN:n,fromMessageId:i,writeToDisk:e$1.writeToDisk??true});let l=Date.now(),a=new e(t.dbPath);try{await a.initialize();let s=a.query(`SELECT id, content, category, importance, 1.0 as score, created_at, node_ids
26
+ FROM memory_facts
27
+ WHERE agent_id = ? AND session_id = ?
28
+ ORDER BY created_at ASC
29
+ LIMIT ?`,[t.agentId,o,n]),c=i?s.filter(y=>y.id>i):s,m=new Set;for(let y of c)if(y.node_ids)try{let E=JSON.parse(y.node_ids);if(Array.isArray(E))for(let u of E)typeof u=="number"&&u>0&&m.add(u);}catch(E){Q.warn("extract: invalid node_ids JSON",{factId:y.id,error:E instanceof Error?E.message:String(E)});}let d=Array.from(m),f=[],h=[];if(d.length>0){let y=d.map(()=>"?").join(","),E=a.query(`SELECT id, name, type FROM nodes WHERE id IN (${y})`,d),u=new Map;for(let R of E)u.set(R.id,R.name);f=E.map(R=>({id:R.id,name:R.name,type:R.type}));let p=a.query(`SELECT source, target, relation FROM edges WHERE source IN (${y}) OR target IN (${y})`,[...d,...d]),M=new Set;h=[];for(let R of p){let _=u.get(R.source),w=u.get(R.target);if(!_||!w)continue;let C=`${_}\0${R.relation}\0${w}`;M.has(C)||(M.add(C),h.push({source:_,target:w,relation:R.relation}));}}let b=Date.now()-l;return Q.info("extract complete",{agentId:t.agentId,sessionId:o,factCount:c.length,nodeCount:f.length,relationCount:h.length,durationMs:b}),{extractedCount:c.length,factIds:c.map(y=>y.id),entities:f,relations:h,messageRange:{fromMessageId:c[0]?.id??"",toMessageId:c[c.length-1]?.id??""},durationMs:b}}catch(s){throw s instanceof g?s:new g(`extract failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{a.close();}}var J=Log.create({service:"memory.service.consolidate"}),Ze=30;async function et(t){let{createHash:e}=await import('crypto');return e("sha256").update(t).digest("hex")}async function he(t,e$1={}){let n=Date.now();O(t),T(t,"consolidate");let o=e$1.windowDays??Ze,i=e$1.dryRun??false;J.debug("consolidate invoked",{agentId:t.agentId,windowDays:o,dryRun:i});let l=new e(t.dbPath);try{await l.initialize();let a=l.query("SELECT id, content, category, importance, created_at FROM memory_facts WHERE agent_id = ? ORDER BY created_at DESC",[t.agentId]),s=new Map;for(let u of a){let p=await et(u.content);s.has(p)||s.set(p,[]),s.get(p)?.push(u);}let c=0,m=[];for(let[,u]of s){if(u.length<=1)continue;let p=[...u].sort((_,w)=>_.importance!==w.importance?w.importance-_.importance:w.created_at.localeCompare(_.created_at)),M=p[0];if(!M)continue;let R=p.slice(1).map(_=>_.id);c+=R.length,m.push({keep:M,removeIds:R});}let d=new Date(Date.now()-o*24*60*60*1e3).toISOString(),f=l.query(`SELECT id, content, category, importance, created_at FROM memory_facts
30
+ WHERE agent_id = ? AND created_at < ?
31
+ ORDER BY created_at ASC`,[t.agentId,d]),h=0,b=0;if(i)h=0,b=c;else {let u=z$1.join(t.workspaceDir,"archive");await L.mkdir(u,{recursive:!0});for(let{removeIds:p}of m){if(p.length===0)continue;let M=p.map(()=>"?").join(",");l.transaction(()=>{for(let R of p)l.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[R,t.agentId]);}),b+=p.length;}for(let p of f){let M=p.created_at.slice(0,7),R=z$1.join(u,M,p.category);await L.mkdir(R,{recursive:!0});let _=z$1.join(R,`${p.id}.md`);try{await L.writeFile(_,[`# ${p.id}`,"",`category: ${p.category}`,`importance: ${p.importance}`,`createdAt: ${p.created_at}`,"",p.content,""].join(`
32
+ `),"utf-8"),l.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[p.id,t.agentId]),h++;}catch(w){J.warn("consolidate: archive write failed",{factId:p.id,error:w instanceof Error?w.message:String(w)});}}}let y=a.length,E=0;return J.info("consolidate complete",{agentId:t.agentId,totalFacts:y,dedupedCount:c,compressedCount:E,archivedCount:h,skippedCount:b,dryRun:i,durationMs:Date.now()-n}),{totalFacts:y,dedupedCount:c,compressedCount:E,archivedCount:h,skippedCount:b,durationMs:Date.now()-n}}catch(a){throw a instanceof g?a:new g(`consolidate failed: ${a instanceof Error?a.message:String(a)}`,"INTERNAL",{cause:a instanceof Error?a.message:String(a)})}finally{l.close();}}var be=Log.create({service:"memory.service.graph-query"});async function Ee(t,e$1){let n=Date.now();O(t);let o=e$1.scope??"agent_only";if(!e$1.query||e$1.query.trim().length===0)throw new g("CONTENT_REQUIRED: graphQuery requires non-empty `query`","CONTENT_REQUIRED");H(t,o,"graph_query");let i=e$1.depth??2,l=e$1.maxNodes??100,a=e$1.query,s=e$1.type,c=e$1.relation;be.debug("graphQuery invoked",{agentId:t.agentId,query:a,type:s,depth:i,maxNodes:l,scope:o,remote:t.remote});let m=new e(t.dbPath);try{await m.initialize();let d=new N(m.getDb()),f=a.includes("*")||a.includes("%")?a:`%${a}%`,h=await d.queryNodes({name:f,...s?{type:s}:{},agentId:t.agentId,scope:o,limit:l}),y=(a.includes("*")||a.includes("%")?h:h.filter(w=>w.name.toLowerCase().includes(a.toLowerCase())))[0]??null;if(!y)return {root:null,nodes:[],edges:[],truncated:!1,totalNodes:0,totalEdges:0,scope:o,durationMs:Date.now()-n};let E=await d.queryNeighbors(y.id,i,{agentId:t.agentId,scope:o,maxEdgesPerNode:20}),u=new Map;u.set(y.id,y);for(let w of E)u.set(w.id,{id:w.id,name:w.name,type:w.type,createdAt:w.createdAt,updatedAt:w.updatedAt});let p=[];for(let w of E)if(w.edges)for(let C of w.edges)c&&C.relation!==c||p.push(C);for(let w of p){if(!u.has(w.source)){let C=await d.queryNodes({ids:[w.source],agentId:t.agentId,scope:o});C[0]&&u.set(C[0].id,C[0]);}if(!u.has(w.target)){let C=await d.queryNodes({ids:[w.target],agentId:t.agentId,scope:o});C[0]&&u.set(C[0].id,C[0]);}}let M=Array.from(u.values()),R=M.length>l,_=R?M.slice(0,l):M;return be.info("graphQuery complete",{agentId:t.agentId,rootId:y.id,nodeCount:_.length,edgeCount:p.length,truncated:R,durationMs:Date.now()-n}),{root:y,nodes:_,edges:p,truncated:R,totalNodes:M.length,totalEdges:p.length,scope:o,durationMs:Date.now()-n}}catch(d){throw d instanceof g?d:new g(`graphQuery failed: ${d instanceof Error?d.message:String(d)}`,"INTERNAL",{cause:d instanceof Error?d.message:String(d)})}finally{m.close();}}var U=Log.create({service:"memory.service.status"}),nt=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"];async function we(t,e$1={}){O(t),U.debug("status invoked",{agentId:t.agentId});let n=new e(t.dbPath);try{await n.initialize();let i=n.query("SELECT COUNT(*) as c FROM memory_facts WHERE agent_id = ?",[t.agentId])[0]?.c??0,a=n.query("SELECT COUNT(*) AS c FROM nodes WHERE owner_agent_id = ? OR owner_agent_id IS NULL",[t.agentId])[0]?.c??0,c=n.query("SELECT COUNT(*) as c FROM edges")[0]?.c??0,m=nt.reduce((u,p)=>(u[p]=0,u),{}),d=n.query("SELECT category, COUNT(*) as c FROM memory_facts WHERE agent_id = ? GROUP BY category",[t.agentId]);for(let u of d){let p=u.category;p in m&&(m[p]=u.c);}let f=!1;try{f=n.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]).length>0;}catch(u){U.debug("status: fts probe failed",{error:u instanceof Error?u.message:String(u)});}let h=!!t.config?.embeddingLlm,b=!1;try{b=n.query("SELECT name FROM pragma_table_info('nodes') WHERE name = ?",["owner_agent_id"]).length>0;}catch(u){U.debug("status: kg scope probe failed",{error:u instanceof Error?u.message:String(u)});}let y=n.healthCheck(),E={};try{let u=n.query("SELECT key, value FROM meta");for(let p of u)E[p.key]=p.value;}catch(u){U.debug("status: meta read failed",{error:u instanceof Error?u.message:String(u)});}return {dbPath:t.dbPath,workspaceDir:t.workspaceDir,factsCount:i,nodesCount:a,edgesCount:c,factsByCategory:m,ftsAvailable:f,vectorEnabled:h,kgScopeEnabled:b,healthy:y,meta:E}}catch(o){throw o instanceof g?o:new g(`status failed: ${o instanceof Error?o.message:String(o)}`,"INTERNAL")}finally{n.close();}}var st=Log.create({service:"memory.service.doctor"}),V=100*1024*1024,X=100*1024*1024;async function Re(t,e$1={}){O(t),st.debug("doctor invoked",{agentId:t.agentId});let n=[],o=null;try{o=new e(t.dbPath),await o.initialize();let a=o.healthCheck();n.push({name:"database",passed:a,message:a?"database connected and writable":"database unhealthy",details:{dbPath:t.dbPath}});}catch(a){n.push({name:"database",passed:false,message:`database connection failed: ${a instanceof Error?a.message:String(a)}`,details:{dbPath:t.dbPath}});}try{if(!o)throw new Error("db not initialized");let a=o.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]);n.push({name:"fts",passed:a.length>0,message:a.length>0?"FTS5 index available":"FTS5 index not found",details:a.length>0?{table:a[0]?.name}:void 0});}catch(a){n.push({name:"fts",passed:false,message:`fts probe failed: ${a instanceof Error?a.message:String(a)}`});}let i=!!t.config?.embeddingLlm;n.push({name:"vector",passed:true,message:i?"embedding model available":"no embedding model configured (FTS-only mode, recall still functional)",details:{mode:i?"hybrid":"fts_only",model:t.config?.embeddingLlm?"configured":"missing"}});try{if(!o)throw new Error("db not initialized");let a=["memory_facts","nodes","edges","meta"],s=o.query("SELECT name FROM sqlite_master WHERE type = ?",["table"]),c=new Set(s.map(d=>d.name)),m=a.filter(d=>!c.has(d));n.push({name:"schema",passed:m.length===0,message:m.length===0?`schema complete (${a.length} tables)`:`missing tables: ${m.join(", ")}`,details:{required:a,existing:Array.from(c)}});}catch(a){n.push({name:"schema",passed:false,message:`schema probe failed: ${a instanceof Error?a.message:String(a)}`});}try{let a=`${t.dbPath}-wal`,s=`${t.dbPath}-shm`,c=0,m=0;try{c=(await L.stat(a)).size;}catch{c=0;}try{m=(await L.stat(s)).size;}catch{m=0;}let d=c+m;n.push({name:"lock",passed:d<=X,message:d<=X?`no lock contention (wal+shm ${(d/1024).toFixed(1)} KB)`:`WAL/SHM files unusually large (${(d/1024/1024).toFixed(1)} MB > ${(X/1024/1024).toFixed(0)} MB threshold)`,details:{walBytes:c,shmBytes:m}});}catch(a){n.push({name:"lock",passed:false,message:`lock probe failed: ${a instanceof Error?a.message:String(a)}`});}try{let a=z$1.dirname(t.dbPath),s=await L.statfs(a),c=typeof s.bsize=="bigint"?Number(s.bsize)*s.bavail:s.bsize*s.bavail,m=c>=V;n.push({name:"disk_space",passed:m,message:m?`sufficient disk space (${(c/1024/1024).toFixed(1)} MB available)`:`low disk space (${(c/1024/1024).toFixed(1)} MB < ${(V/1024/1024).toFixed(0)} MB threshold)`,details:{availableBytes:c,threshold:V}});}catch(a){n.push({name:"disk_space",passed:false,message:`disk_space probe failed: ${a instanceof Error?a.message:String(a)}`});}try{if(!o)throw new Error("db not initialized");let a=o.query("SELECT id, node_ids FROM memory_facts WHERE agent_id = ? AND node_ids IS NOT NULL",[t.agentId]),s=[];for(let c of a)try{let m=JSON.parse(c.node_ids);if(!Array.isArray(m))continue;for(let d of m){if(typeof d!="number")continue;if((o.query("SELECT COUNT(*) as c FROM nodes WHERE id = ?",[d])[0]?.c??0)===0){s.push(`${c.id}->${d}`);break}}}catch{}n.push({name:"orphan",passed:s.length===0,message:s.length===0?"no orphan KG references":`${s.length} orphan references: ${s.slice(0,5).join(", ")}${s.length>5?", ...":""}`,details:{count:s.length}});}catch(a){n.push({name:"orphan",passed:false,message:`orphan probe failed: ${a instanceof Error?a.message:String(a)}`});}let l=n.every(a=>a.passed);return o&&o.close(),{healthy:l,checks:n}}var j=Log.create({service:"memory.service.init"});async function Ie(t,e$1={}){let n=Date.now();T(t,"init");let o=e$1.workspaceDir??t.workspaceDir,i=e$1.dbPath??t.dbPath;if(!o||o.trim().length===0)throw new g("init requires non-empty `workspaceDir` (ctx.workspaceDir or params.workspaceDir)","CONTENT_REQUIRED");if(!i||i.trim().length===0)throw new g("init requires non-empty `dbPath` (ctx.dbPath or params.dbPath)","CONTENT_REQUIRED");let l=t.agentId?.trim()??"",a$1=e$1.force??false;j.debug("init invoked",{agentId:l,workspaceDir:o,dbPath:i,force:a$1});try{await L.mkdir(z$1.dirname(i),{recursive:!0}),await L.mkdir(z$1.join(o,"active"),{recursive:!0}),await L.mkdir(z$1.join(o,"archive"),{recursive:!0});}catch(c){throw new g(`init: failed to create directories: ${c instanceof Error?c.message:String(c)}`,"INTERNAL",{cause:c instanceof Error?c.message:String(c)})}if(a$1)try{await L.rm(i,{force:!0});}catch(c){j.warn("init: force rm db failed (may not exist)",{dbPath:i,error:c instanceof Error?c.message:String(c)});}let s=new e(i);try{let c=await L.stat(i).then(()=>!0).catch(()=>!1);await s.initialize();let m=new Date().toISOString(),d=[["version","1.0.0"],["schemaVersion",String(a)],["createdAt",m],["defaultAgentId",l]];for(let[b,y]of d)try{s.run("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)",[b,y]);}catch(E){j.warn("init: meta insert failed",{key:b,error:E instanceof Error?E.message:String(E)});}let f=c?0:12,h=c?0:1;return j.info("init complete",{agentId:l,workspaceDir:o,dbPath:i,schemaVersion:a,durationMs:Date.now()-n}),{initialized:!0,dbPath:i,workspaceDir:o,tablesCreated:f,migrationsApplied:h,durationMs:Date.now()-n}}catch(c){throw new g(`init failed: ${c instanceof Error?c.message:String(c)}`,"INTERNAL",{cause:c instanceof Error?c.message:String(c)})}finally{s.close();}}var Se=z.object({query:z.string().min(1).max(500),category:z.string().optional(),minImportance:z.number().min(1).max(10).optional(),fromTime:z.string().datetime().optional(),toTime:z.string().datetime().optional(),maxResults:z.number().int().min(1).max(100).optional().default(10),minScore:z.number().min(0).max(1).optional(),includeGraph:z.boolean().optional().default(false),depth:z.number().int().min(1).max(5).optional().default(1),includeShared:z.boolean().optional().default(false)});z.object({hits:z.array(z.unknown()),total:z.number(),truncated:z.boolean(),durationMs:z.number(),graph:z.object({nodes:z.array(z.unknown()),edges:z.array(z.unknown())}).optional()});var Me=z.object({content:z.string().min(1).max(1e4),category:z.string().min(1),importance:z.number().int().min(1).max(10).optional().default(5),tags:z.array(z.string()).optional(),sessionId:z.string().optional(),msgId:z.string().optional(),parentMsgId:z.string().optional(),skipDedup:z.boolean().optional().default(false),extractGraph:z.boolean().optional().default(true)});z.object({fact:z.object({id:z.string(),agentId:z.string(),content:z.string(),category:z.string(),importance:z.number(),createdAt:z.string(),updatedAt:z.string()}),filePath:z.string(),deduplicated:z.boolean(),nodeIds:z.array(z.number()).optional()});var _e=z.object({factId:z.string().optional(),category:z.string().optional(),fromTime:z.string().datetime().optional(),toTime:z.string().datetime().optional(),maxDelete:z.number().int().min(1).max(1e4).optional().default(1e3),dryRun:z.boolean().optional().default(false),force:z.boolean().optional().default(false)}).refine(t=>t.factId!==void 0&&t.factId.length>0||t.category!==void 0&&t.category.length>0||t.fromTime!==void 0||t.toTime!==void 0,{message:"one of `factId`, `category`, `fromTime`, or `toTime` is required"});z.object({deletedCount:z.number(),deletedIds:z.array(z.string()),dryRun:z.boolean(),truncatedCount:z.number()});var De=z.object({sessionId:z.string().min(1),lastN:z.number().int().min(1).max(500).optional().default(50),fromMessageId:z.string().optional(),writeToDisk:z.boolean().optional().default(true)});z.object({extractedCount:z.number(),factIds:z.array(z.string()),entities:z.array(z.object({id:z.number(),name:z.string(),type:z.string()})),relations:z.array(z.object({source:z.string(),target:z.string(),relation:z.string()})),messageRange:z.object({fromMessageId:z.string(),toMessageId:z.string()}),durationMs:z.number()});var Oe=z.object({windowDays:z.number().int().min(1).max(365).optional().default(30),dryRun:z.boolean().optional().default(false)});z.object({totalFacts:z.number(),dedupedCount:z.number(),compressedCount:z.number(),archivedCount:z.number(),skippedCount:z.number(),durationMs:z.number()});var Ce=z.object({query:z.string().min(1),type:z.string().optional(),depth:z.number().int().min(1).max(5).optional().default(2),maxNodes:z.number().int().min(1).max(500).optional().default(100),scope:z.enum(["agent_only","shared_only","both"]).optional().default("agent_only"),relation:z.string().optional()});z.object({root:z.unknown().nullable(),nodes:z.array(z.unknown()),edges:z.array(z.unknown()),truncated:z.boolean(),totalNodes:z.number(),totalEdges:z.number(),scope:z.enum(["agent_only","shared_only","both"]),durationMs:z.number()});var Ne=z.object({}).optional();z.object({dbPath:z.string(),workspaceDir:z.string(),factsCount:z.number(),nodesCount:z.number(),edgesCount:z.number(),factsByCategory:z.record(z.string(),z.number()),ftsAvailable:z.boolean(),vectorEnabled:z.boolean(),kgScopeEnabled:z.boolean(),healthy:z.boolean(),meta:z.record(z.string(),z.string())});var Te=z.object({}).optional();z.object({healthy:z.boolean(),checks:z.array(z.object({name:z.string(),passed:z.boolean(),message:z.string(),details:z.record(z.string(),z.unknown()).optional()}))});var ve=z.object({workspaceDir:z.string().optional(),dbPath:z.string().optional(),archiveDays:z.number().int().min(1).max(3650).optional().default(30),force:z.boolean().optional().default(false)});z.object({initialized:z.boolean(),dbPath:z.string(),workspaceDir:z.string(),tablesCreated:z.number(),migrationsApplied:z.number(),durationMs:z.number()});var ee={name:"recall",scope:"read",schema:Se,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Query memory via hybrid search (FTS + vector); returns ranked facts.",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("recall: agentId is required");return me({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var te={name:"remember",scope:"write",schema:Me,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Persist a new self-memory fact; auto-extract entities into KG.",readOnlyHint:false,destructiveHint:false,idempotentHint:false},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("remember: agentId is required");return ge({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var re={name:"forget",scope:"write",schema:_e,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Delete memory facts by id / category / time range; supports dryRun.",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("forget: agentId is required");return fe({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var ne={name:"extract",scope:"write",schema:De,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Extract facts from a session (server-side pulls messages by lastN).",readOnlyHint:false,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("extract: agentId is required");return ye({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var oe={name:"consolidate",scope:"admin",schema:Oe,annotations:{localOnly:true,requiresAgentId:true,defaultDescription:"Run consolidation pipeline: dedup \u2192 archive.",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.isTrustedLocal)throw new Error("consolidate: only trusted local process can invoke this op");if(!e.agentId?.trim())throw new Error("consolidate: agentId is required");return he({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},n)}};var ae={name:"graph_query",scope:"read",schema:Ce,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Query KG nodes / edges / neighbors with scope filtering.",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.agentId?.trim())throw new Error("graph_query: agentId is required");return Ee({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var se={name:"status",scope:"read",schema:Ne,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Memory system status (factsCount / nodesCount / edgesCount / fts / vector).",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t??{};return we({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var ie={name:"doctor",scope:"admin",schema:Te,annotations:{localOnly:true,requiresAgentId:true,defaultDescription:"Run 7 health checks (database / fts / vector / schema / lock / disk_space / orphan).",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t??{};if(!e.isTrustedLocal)throw new Error("doctor: only trusted local process can invoke this op");if(!e.agentId?.trim())throw new Error("doctor: agentId is required");return Re({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},n)}};var ce={name:"init",scope:"admin",schema:ve,annotations:{localOnly:true,requiresAgentId:false,defaultDescription:"Initialize memory workspace (dirs + db schema + meta).",readOnlyHint:false,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{if(!e.isTrustedLocal)throw new Error("init: only trusted local process can invoke this op");let n=t??{};return Ie({workspaceDir:n.workspaceDir??e.workspaceDir??"",rootDir:n.workspaceDir??e.workspaceDir??"",dbPath:n.dbPath??e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId??""},n)}};var Ae={[ee.name]:ee,[te.name]:te,[re.name]:re,[ne.name]:ne,[oe.name]:oe,[ae.name]:ae,[se.name]:se,[ie.name]:ie,[ce.name]:ce},ct=Object.values(Ae);function dt(t,e,n){if(t.annotations.localOnly&&!e.isTrustedLocal)throw new Error(`MEMORY:executeOp: op "${n}" is localOnly; non-trusted caller rejected`);if(t.annotations.requiresAgentId){let o=e.agentId?.trim()??"";if(o.length===0)throw new Error(`MEMORY:executeOp: op "${n}" requires agentId`);e.agentId=o;}}async function kn(t,e,n){let o=Ae[t];if(!o)throw new Error(`executeOp: unknown op "${t}"; available: ${ct.map(l=>l.name).join(", ")}`);return dt(o,n,t),await o.handler(e,n)}function ut(t){let e=t.dbPath??"";return {workspaceDir:t.workspaceDir??"",database:{path:e},embeddingLlm:void 0,graphLlm:void 0,search:DEFAULT_SEARCH_CONFIG,indexer:{batchSize:20,ignorePatterns:[],incremental:true},archiveDays:30,shortTermMaxRounds:20}}function jn(t,e,n={}){let o=j$1(),i=Locale.resolveLocaleLang(n.locale);return {agentId:t,dbPath:o,workspaceDir:e,rootDir:e,config:ut({dbPath:o,workspaceDir:e}),isTrustedLocal:true,locale:i,remote:false,...n}}export{N as a,me as b,ge as c,fe as d,ye as e,he as f,Ee as g,we as h,Re as i,Ie as j,Ae as k,ct as l,kn as m,ut as n,jn as o};
@@ -0,0 +1,53 @@
1
+ 'use strict';var chunkBWPPLYIF_cjs=require('./chunk-BWPPLYIF.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database');var d=utils.Log.create({service:"memory-schema-migrations"}),T=2,I=[{id:1,description:"v1 baseline: memory_facts / memory_vectors / embedding_cache / memory_facts_fts / nodes / edges / meta\uFF08\u4E0E v0.3.x createTables \u8F93\u51FA\u5BF9\u9F50\uFF0C\u8001 db \u8DD1\u8BE5\u8FC1\u79FB\u4E0D\u7834\u574F\u73B0\u6709\u8868\uFF09",up:[`CREATE TABLE IF NOT EXISTS memory_facts (
2
+ id TEXT PRIMARY KEY,
3
+ agent_id TEXT NOT NULL,
4
+ session_id TEXT,
5
+ msg_id TEXT,
6
+ parent_msg_id TEXT,
7
+ content TEXT NOT NULL,
8
+ category TEXT NOT NULL,
9
+ importance INTEGER NOT NULL CHECK(importance >= 1 AND importance <= 10),
10
+ source TEXT NOT NULL CHECK(source IN ('session_self_write', 'historical')),
11
+ tags TEXT,
12
+ node_ids TEXT,
13
+ file_path TEXT,
14
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
15
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
16
+ UNIQUE(session_id, msg_id)
17
+ )`,"CREATE INDEX IF NOT EXISTS idx_memory_facts_agent_id ON memory_facts(agent_id)","CREATE INDEX IF NOT EXISTS idx_memory_facts_agent_category ON memory_facts(agent_id, category)","CREATE INDEX IF NOT EXISTS idx_memory_facts_agent_importance ON memory_facts(agent_id, importance DESC)","CREATE INDEX IF NOT EXISTS idx_memory_facts_created_at ON memory_facts(created_at)",`CREATE TABLE IF NOT EXISTS memory_vectors (
18
+ fact_id TEXT PRIMARY KEY,
19
+ embedding BLOB NOT NULL,
20
+ FOREIGN KEY (fact_id) REFERENCES memory_facts(id) ON DELETE CASCADE
21
+ )`,`CREATE TABLE IF NOT EXISTS embedding_cache (
22
+ content_hash TEXT PRIMARY KEY,
23
+ embedding BLOB NOT NULL,
24
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
25
+ )`,`CREATE VIRTUAL TABLE IF NOT EXISTS memory_facts_fts USING fts5(
26
+ fact_id UNINDEXED,
27
+ agent_id UNINDEXED,
28
+ content,
29
+ tags,
30
+ tokenize='porter unicode61'
31
+ )`,`CREATE TABLE IF NOT EXISTS nodes (
32
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
33
+ name TEXT NOT NULL,
34
+ type TEXT NOT NULL,
35
+ properties TEXT,
36
+ createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
37
+ updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP
38
+ )`,"CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name)","CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type)","CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_name_type ON nodes(name, type)",`CREATE TABLE IF NOT EXISTS edges (
39
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
40
+ source INTEGER NOT NULL,
41
+ target INTEGER NOT NULL,
42
+ relation TEXT NOT NULL,
43
+ properties TEXT,
44
+ createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
45
+ FOREIGN KEY (source) REFERENCES nodes(id) ON DELETE CASCADE,
46
+ FOREIGN KEY (target) REFERENCES nodes(id) ON DELETE CASCADE
47
+ )`,"CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)","CREATE INDEX IF NOT EXISTS idx_edges_relation ON edges(relation)","CREATE UNIQUE INDEX IF NOT EXISTS idx_edges_unique ON edges(source, target, relation)",`CREATE TABLE IF NOT EXISTS meta (
48
+ key TEXT PRIMARY KEY,
49
+ value TEXT
50
+ )`]},{id:2,description:"v2: \u7ED9 nodes \u8868\u52A0 owner_agent_id \u5217 + \u7D22\u5F15\uFF08ADR 0056 KG scope \u4E09\u6863\uFF0Cper-agent \u9694\u79BB\uFF09",up:["ALTER TABLE nodes ADD COLUMN owner_agent_id TEXT","CREATE INDEX IF NOT EXISTS idx_nodes_owner_agent_id ON nodes(owner_agent_id)"]}];function m(n,e=T,t={}){n.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
51
+ id INTEGER PRIMARY KEY,
52
+ applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
53
+ )`);let i=n.prepare("SELECT id FROM schema_migrations").all(),a=new Set(i.map(r=>r.id)),s={applied:[],pending:[],errors:[],currentVersion:i.length===0?0:Math.max(...i.map(r=>r.id)),targetVersion:e};for(let r of I){if(r.id>e)break;if(a.has(r.id)){s.pending.push(r.id);continue}if(t.dryRun){s.applied.push(r.id);continue}try{S(n,r.up),n.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(r.id),a.add(r.id),s.applied.push(r.id),d.info("migration applied",{id:r.id,description:r.description});}catch(E){let l=E instanceof Error?E.message:String(E),h=r.up[0]??"";s.errors.push({migrationId:r.id,sql:h,error:l}),d.warn("migration step failed",{id:r.id,error:l,sqlCount:r.up.length});}}return s}function S(n,e){for(let t of e)try{n.exec(t);}catch(i){let a=i instanceof Error?i.message:String(i);if(_(a)){d.debug("migration: column already exists, skipping",{sql:t.slice(0,80)});continue}throw i}}function _(n){return /duplicate column name/i.test(n)}function g(n){try{let e=n.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(t=>t.id))}catch{return 0}}var c=utils.Log.create({service:"memory-database"}),p=class{constructor(e){chunkBWPPLYIF_cjs.b(this,"db",null);chunkBWPPLYIF_cjs.b(this,"storagePath");chunkBWPPLYIF_cjs.b(this,"backend","better-sqlite3");chunkBWPPLYIF_cjs.b(this,"initialized",false);chunkBWPPLYIF_cjs.b(this,"initPromise",null);this.storagePath=e===":memory:"?e:utils.Filesystem.normalize(e);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize();try{await this.initPromise,this.initialized=!0;}catch(e){try{this.db&&this.db.close();}catch{}throw this.db=null,this.initPromise=null,e}}}async doInitialize(){try{let e=this.openConnection();e.initialize(),this.db=e,this.applyPragmas(),this.runAllMigrations();}catch(e){let t=e instanceof Error?e.message:String(e);throw c.error("Database initialization failed",{error:t}),e}}openConnection(){return database.createSyncSqliteConnection({path:this.storagePath,backend:this.backend,walMode:true,foreignKeys:true,busyTimeoutMs:5e3})}applyPragmas(){if(this.db)try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("foreign_keys = ON");}catch(e){c.warn("Failed to apply memory PRAGMAs",{error:String(e)});}}runAllMigrations(){if(!this.db)throw new Error("Database not initialized");let e=m(this.db,T);if(e.errors.length>0){let t=e.errors.map(i=>`migration ${i.migrationId}: ${i.error}`).join("; ");throw new Error(`Some migrations failed: ${t}`)}}query(e,t){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let i=this.db.prepare(e);return t?i.all(...t):i.all()}catch(i){throw new Error(`Query failed: ${i.message}`)}}run(e,t){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let i=this.db.prepare(e),a=t?i.run(...t):i.run();return {lastID:Number(a.lastInsertRowid),changes:a.changes}}catch(i){throw new Error(`Write failed: ${i.message}`)}}transaction(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db.transaction(e)()}prepare(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db.prepare(e)}exec(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");this.db.exec(e);}getDb(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db}getPath(){return this.storagePath}getSchemaVersion(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return g(this.db)}close(){if(this.db){try{this.db.close();}catch(e){c.warn("Failed to close memory database",{error:String(e)});}this.db=null,this.initialized=false,this.initPromise=null;}}healthCheck(){try{return this.db?(this.db.exec("SELECT 1"),!0):!1}catch{return false}}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}};exports.a=T;exports.b=I;exports.c=m;exports.d=g;exports.e=p;
File without changes
@@ -0,0 +1 @@
1
+ 'use strict';
@@ -0,0 +1 @@
1
+ var d=Object.defineProperty;var e=(a,b,c)=>b in a?d(a,b,{enumerable:true,configurable:true,writable:true,value:c}):a[b]=c;var f=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var g=(a,b,c)=>e(a,typeof b!="symbol"?b+"":b,c);export{f as a,g as b};
@@ -0,0 +1 @@
1
+ import {homedir}from'os';import {join}from'path';import {xdgData}from'xdg-basedir';var r=null,n=null;function f(t){r=t;}function A(){r=null;}function s(){if(r)return r;let t=homedir();return {Path:{home:t,data:process.env.EASBOT_DATA_PATH?.trim()||join(xdgData??join(t,".local","share"),"easbot"),config:process.env.EASBOT_CONFIG_PATH?.trim()||join(t,".config","easbot"),state:process.env.EASBOT_STATE_PATH?.trim()||join(xdgData??join(t,".local","share"),"easbot","state"),cache:process.env.EASBOT_CACHE_PATH?.trim()||join(t,".cache","easbot"),log:process.env.EASBOT_LOG_PATH?.trim()||join(xdgData??join(t,".local","share"),"easbot","log"),bin:process.env.EASBOT_BIN_PATH?.trim()||join(t,".local","bin")}}}function I(t){n=t;}function g(){n=null;}function T(){if(n)return n;let t=process.cwd();return {directory:t,worktree:t}}function l(){return s().Path.home||homedir()}function c(){let t=s().Path.data;return t||(xdgData??join(l(),".local","share"))}function i(){return join(c(),"memory")}function _(){return join(i(),"memory.db")}export{f as a,A as b,s as c,I as d,g as e,T as f,l as g,c as h,i,_ as j};
@@ -0,0 +1 @@
1
+ var f={languages:[{value:"zh-CN",name:"\u7B80\u4F53\u4E2D\u6587",example:"\u4F60\u597D\uFF0CEASBOT\uFF01",supported:true},{value:"en-US",name:"English (United States)",example:"Hello, EASBOT!",supported:true}]};var L=f.languages,C=L.filter(e=>e.supported).map(e=>e.value),a={defaultLocale:"zh-CN",locales:C},m={},p=(e,t)=>{let r=m[e]||{translation:{}};return m[e]={translation:{...r.translation,...t.translation}},m[e]},u=(e=a.defaultLocale)=>(m[e]||p(e,{translation:{}}),{locale:e,resources:m[e]||{translation:{}}});var S={translation:{"cli.cmd.init.description":"\u521D\u59CB\u5316\u8BB0\u5FC6 workspace\uFF08.easbot/memory.db\uFF09","cli.cmd.recall.description":"\u6DF7\u5408\u641C\u7D22\uFF08FTS + \u5411\u91CF\uFF09\u67E5\u8BE2\u8BB0\u5FC6","cli.cmd.remember.description":"\u5199\u5165\u4E00\u6761\u65B0\u8BB0\u5FC6\uFF08\u81EA\u5E26 dedup + \u77E5\u8BC6\u56FE\u8C31\u62BD\u53D6\uFF09","cli.cmd.forget.description":"\u5220\u9664\u8BB0\u5FC6\uFF08factId / category / \u65F6\u95F4\u7A97 / \u8BD5\u8FD0\u884C\uFF09","cli.cmd.extract.description":"\u4ECE session \u62BD\u53D6 facts\uFF08sessionId + lastN\uFF09","cli.cmd.consolidate.description":"\u8FD0\u884C consolidation \u6D41\u6C34\u7EBF\uFF08extract \u2192 dedup \u2192 archive\uFF09","cli.cmd.graph.description":"\u77E5\u8BC6\u56FE\u8C31\u67E5\u8BE2\uFF08nodes / edges / neighbors\uFF0Cscope \u4E09\u6863\uFF09","cli.cmd.status.description":"\u663E\u793A\u8BB0\u5FC6\u72B6\u6001 / \u6570\u636E\u5E93\u7EDF\u8BA1 / \u5404\u7C7B\u522B\u8BA1\u6570","cli.cmd.doctor.description":"\u8FD0\u884C\u5065\u5EB7\u68C0\u67E5\uFF08\u540E\u7AEF / FTS / schema / \u9501\uFF09","cli.cmd.config.description":"\u67E5\u770B / \u6821\u9A8C\u8BB0\u5FC6\u914D\u7F6E\uFF08dry-read\uFF09","cli.cmd.mcp.description":"\u542F\u52A8 stdio MCP \u670D\u52A1\u5668\uFF08\u66B4\u9732 9 \u4E2A memory \u5DE5\u5177\uFF09","memory.recall.empty":"\uFF08\u65E0\u5339\u914D\u8BB0\u5FC6\uFF09","memory.recall.summary":"\u5171\u5339\u914D {total} \u6761\u8BB0\u5FC6\uFF1A","memory.recall.item":" - {id} [{category}/\u91CD\u8981\u6027={importance}/\u5206\u6570={score}] {content}","memory.forget.empty":"\uFF08\u672A\u547D\u4E2D\u53EF\u5220\u9664\u7684\u8BB0\u5F55\uFF09\uFF09","memory.forget.summary":"\u5220\u9664 {deletedCount} \u6761\u8BB0\u5FC6\uFF08dryRun={dryRun}\uFF09\uFF1A","memory.forget.item":" - {id}","memory.remember.summary":"\u8BB0\u5FC6\u5DF2\u5199\u5165\uFF1A","memory.remember.item":" - id={id} \u7C7B\u522B={category} \u91CD\u8981\u6027={importance}","memory.consolidate.summary":"consolidation \u5B8C\u6210\uFF1A","memory.consolidate.item":" - \u603B\u8BA1 {totalFacts} \u53BB\u91CD {dedupedCount} \u5F52\u6863 {archivedCount}","memory.status.empty":"\uFF08\u6682\u65E0\u6570\u636E\uFF09","memory.status.summary":"\u8BB0\u5FC6\u72B6\u6001\uFF1A","memory.status.item":" - {key}: {value}","memory.doctor.empty":"\uFF08\u65E0\u68C0\u67E5\u9879\uFF09","memory.doctor.summary":"\u5065\u5EB7\u68C0\u67E5\uFF1A{status}","memory.doctor.item":" - {name}: {message}","memory.graph.empty":"\uFF08\u65E0\u8282\u70B9\u547D\u4E2D\uFF09","memory.graph.summary":"\u77E5\u8BC6\u56FE\u8C31\u67E5\u8BE2\uFF08\u5171 {totalNodes} \u8282\u70B9\uFF09\uFF1A","memory.graph.item":" - {id} {name} [{type}]","memory.extract.summary":"\u62BD\u53D6 {extractedCount} \u6761 facts\uFF1A","memory.extract.item":" - {id}","memory.init.summary":"\u521D\u59CB\u5316\u5B8C\u6210\uFF1A","memory.init.item":" - db={dbPath} \u8FC1\u79FB={migrationsApplied} \u8868={tablesCreated}"}},h=S;var v={translation:{"cli.cmd.init.description":"Initialize memory workspace (.easbot/memory.db)","cli.cmd.recall.description":"Hybrid search (FTS + vector) over memory facts","cli.cmd.remember.description":"Persist a new memory fact (with dedup + KG extraction)","cli.cmd.forget.description":"Delete memory facts (factId / category / timeRange / dryRun)","cli.cmd.extract.description":"Extract facts from a session (sessionId + lastN)","cli.cmd.consolidate.description":"Run consolidation pipeline (extract \u2192 dedup \u2192 archive)","cli.cmd.graph.description":"KG query (nodes / edges / neighbors with scope \u4E09\u6863)","cli.cmd.status.description":"Show memory state / db stats / facts by category","cli.cmd.doctor.description":"Run health checks (backend, FTS, schema, lock)","cli.cmd.config.description":"Show / validate memory configuration (dry-read)","cli.cmd.mcp.description":"Start stdio MCP server (exposes 9 memory tools)","memory.recall.empty":"(no matching facts)","memory.recall.summary":"Found {total} fact(s):","memory.recall.item":" - {id} [{category}/imp={importance}/score={score}] {content}","memory.forget.empty":"(no records to delete)","memory.forget.summary":"Deleted {deletedCount} fact(s) (dryRun={dryRun}):","memory.forget.item":" - {id}","memory.remember.summary":"Memory persisted:","memory.remember.item":" - id={id} category={category} importance={importance}","memory.consolidate.summary":"Consolidation complete:","memory.consolidate.item":" - total {totalFacts} deduped {dedupedCount} archived {archivedCount}","memory.status.empty":"(no data)","memory.status.summary":"Memory status:","memory.status.item":" - {key}: {value}","memory.doctor.empty":"(no checks)","memory.doctor.summary":"Health check: {status}","memory.doctor.item":" - {name}: {message}","memory.graph.empty":"(no nodes matched)","memory.graph.summary":"KG query ({totalNodes} node(s)):","memory.graph.item":" - {id} {name} [{type}]","memory.extract.summary":"Extracted {extractedCount} fact(s):","memory.extract.item":" - {id}","memory.init.summary":"Initialization complete:","memory.init.item":" - db={dbPath} migrations={migrationsApplied} tables={tablesCreated}"}},x=v;var w=()=>{u("zh-CN"),u("en-US"),p("zh-CN",h),p("en-US",x);};w();var g=new Map;var y=new Map;var k=e=>{if(y.has(e))return y.get(e);let t=/{{\s*(\w+)\s*}}/g,r=[],o;for(;(o=t.exec(e))!==null;){let n=o[1];n&&!r.includes(n)&&r.push(n);}let i=new RegExp("{{\\s*("+r.join("|")+")\\s*}}","g"),s={keys:r,regex:i};return y.set(e,s),s},R=(e,t)=>{if(!e||typeof e!="string")return "";if(!t||Object.keys(t).length===0)return e;let{regex:r,keys:o}=k(e);return o.length===0||!o.some(s=>s in t)?e:e.replace(r,(s,n)=>{let c=t[n];return c==null?"":String(c)})},I=e=>{if(e&&a.locales.includes(e))return e;let t=process.env.EASBOT_LANG?.trim()||process.env.LANG?.trim();if(t){let r=t.replace(/_/g,"-");if(a.locales.includes(r))return r;let o=r.split("-")[0];if(o==="zh")return "zh-CN";if(o==="en")return "en-US"}return a.defaultLocale},T=e=>{if(!g.has(e)){let{resources:t}=u(e);g.set(e,t);}return g.get(e)},N=(e,t={})=>{let r=I(t.locale),i=T(r)?.translation[e];if(i&&typeof i=="string"){let s=R(i,t.vars);return s!=null?String(s):String(e)}if(r!==a.defaultLocale){let n=T(a.defaultLocale)?.translation[e];if(n&&typeof n=="string"){let c=R(n,t.vars);return c!=null?String(c):String(e)}}return String(t.fallback??e)},B=N;export{B as a};
@@ -0,0 +1 @@
1
+ 'use strict';var chunkNJVXQ7TV_cjs=require('./chunk-NJVXQ7TV.cjs');require('./chunk-3HTZTI7U.cjs'),require('./chunk-BWPPLYIF.cjs');Object.defineProperty(exports,"COMMANDS_HELP",{enumerable:true,get:function(){return chunkNJVXQ7TV_cjs.a}});Object.defineProperty(exports,"handleMemoryCli",{enumerable:true,get:function(){return chunkNJVXQ7TV_cjs.d}});Object.defineProperty(exports,"renderBanner",{enumerable:true,get:function(){return chunkNJVXQ7TV_cjs.b}});Object.defineProperty(exports,"renderHelp",{enumerable:true,get:function(){return chunkNJVXQ7TV_cjs.c}});