@easbot/memory 0.3.14 → 0.3.17

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 +296 -38
  2. package/README.md +292 -37
  3. package/dist/chunks/chunk-BSKFK4RC.mjs +1 -0
  4. package/dist/chunks/chunk-CPRDIUQ4.cjs +1 -0
  5. package/dist/chunks/chunk-DFWC6WII.mjs +53 -0
  6. package/dist/chunks/chunk-DXU5WPK3.cjs +42 -0
  7. package/dist/chunks/chunk-EECBJNZI.mjs +59 -0
  8. package/dist/chunks/chunk-FMEXQ5YE.cjs +59 -0
  9. package/dist/chunks/chunk-HQBRVVXS.mjs +1 -0
  10. package/dist/chunks/chunk-HSK27DQ7.cjs +1 -0
  11. package/dist/chunks/chunk-I6XVFDN2.mjs +42 -0
  12. package/dist/chunks/chunk-MWRDF6VN.mjs +1 -0
  13. package/dist/chunks/chunk-NVGACA7W.cjs +1 -0
  14. package/dist/chunks/chunk-OIUUTVLL.cjs +53 -0
  15. package/dist/chunks/chunk-QF5S5MG7.mjs +0 -0
  16. package/dist/chunks/chunk-QNDG7BTB.cjs +1 -0
  17. package/dist/chunks/chunk-RSJ2KT6X.cjs +1 -0
  18. package/dist/chunks/chunk-TPSRK4M3.mjs +1 -0
  19. package/dist/chunks/chunk-URADAZYW.cjs +1 -0
  20. package/dist/chunks/chunk-WDVDYZ25.mjs +1 -0
  21. package/dist/chunks/cli-handler-6VTKYXXM.mjs +1 -0
  22. package/dist/chunks/cli-handler-HNPA3STD.cjs +1 -0
  23. package/dist/chunks/config-2SQJYVTO.mjs +1 -0
  24. package/dist/chunks/config-RPPQ73HK.cjs +1 -0
  25. package/dist/chunks/consolidate-6P7LUPPL.cjs +2 -0
  26. package/dist/chunks/consolidate-NYH4IKJK.mjs +2 -0
  27. package/dist/chunks/doctor-IJJ5UYGT.cjs +2 -0
  28. package/dist/chunks/doctor-MZSZGVRL.mjs +2 -0
  29. package/dist/chunks/extract-6B7OD3VK.mjs +2 -0
  30. package/dist/chunks/extract-ERTOHQV6.cjs +2 -0
  31. package/dist/chunks/forget-A4UJI3LE.mjs +3 -0
  32. package/dist/chunks/forget-KLFM5SBQ.cjs +3 -0
  33. package/dist/chunks/graph-P5ZHB4ZM.cjs +3 -0
  34. package/dist/chunks/graph-XZ46LEO7.mjs +3 -0
  35. package/dist/chunks/init-CCOSHE3F.cjs +3 -0
  36. package/dist/chunks/init-WEPU32KF.mjs +3 -0
  37. package/dist/chunks/interfaces-LPJU4KS3.mjs +1 -0
  38. package/dist/chunks/interfaces-XWE45ENK.cjs +1 -0
  39. package/dist/chunks/mcp-BOD4ZOZS.mjs +1 -0
  40. package/dist/chunks/mcp-BXVXTUJK.cjs +1 -0
  41. package/dist/chunks/recall-BV4Z7HUJ.mjs +2 -0
  42. package/dist/chunks/recall-FEINUJKO.cjs +2 -0
  43. package/dist/chunks/remember-ESVRA73C.mjs +2 -0
  44. package/dist/chunks/remember-YNSY2JJB.cjs +2 -0
  45. package/dist/chunks/status-KVM7I6YC.cjs +2 -0
  46. package/dist/chunks/status-QQZS3ZCN.mjs +2 -0
  47. package/dist/chunks/stdio-server-MQKTUGNG.cjs +1 -0
  48. package/dist/chunks/stdio-server-ZLMSUTC5.mjs +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 +403 -170
  55. package/dist/index.d.ts +403 -170
  56. package/dist/index.mjs +6 -146
  57. package/package.json +21 -14
package/README.md CHANGED
@@ -2,15 +2,17 @@
2
2
 
3
3
  [English](./README.en.md) | 中文
4
4
 
5
- EASBOT 生态系统的记忆管理库,提供智能化的记忆索引、搜索和管理功能。
5
+ EASBOT 生态系统的长期记忆管理库(v0.4.0)。提供分层记忆、KG scope 三档隔离、9 op 统一调度、混合搜索与可观测治理。
6
6
 
7
- ## 特性
7
+ ## 特性(v0.4.0)
8
8
 
9
- - **混合搜索**:支持向量搜索、全文搜索(FTS)和图搜索的混合检索
10
- - **中英文分词**:基于 jieba-wasm 实现高质量中英文分词
11
- - **增量索引**:支持增量更新,自动检测文件变化
12
- - **多源支持**:支持 memory 和 sessions 两种记忆源
13
- - **XDG 规范**:数据库默认存储在 XDG 数据目录
9
+ - **9 op 统一入口**:`recall / remember / forget / extract / consolidate / graph_query / status / doctor / init`,MCP / CLI / Agent Tool 三端共享。
10
+ - **KG scope 三档隔离**:每个节点带 `owner_agent_id`;`scope ∈ {agent_only, shared_only, both}`;MCP 默认 `agent_only`,trusted local 可 `both`。`graph_query` / `status` / `doctor` / `init` 的 `agentId` 为 **optional**,缺省 fallback `'default'`(ADR 0068 P0-A 反转)。
11
+ - **分层记忆**:短期 / 可写自记忆 / 历史长期记忆三层,**混合搜索**(FTS + 向量 + 图)。
12
+ - **可观测性**:9 op 全部走 `Log.create({ service })` 英文结构化日志;`status` / `doctor` 提供离线诊断。
13
+ - **i18n**:`zh-CN` / `en-US` 双 locale;`@easbot/memory` API 日志保持英文,文案走 `t()`。
14
+ - **可移植**:纯 TS 6.x;依赖 `better-sqlite3`(transitive via `@easbot/database`)+ `@easbot/database`(sync facade)+ `@easbot/types` / `@easbot/utils`(决策 0036 统一封装,禁止直接 require better-sqlite3 / @modelcontextprotocol/sdk)。
15
+ - **三包统一后台支撑**(决策 0036 / 0049 / 0051 / 0052):database 走 `@easbot/database` `createSyncSqliteConnection`;MCP 走 `@easbot/mcp` `ToolRegistry` + `createAndStartStdioServer`;CLI 输出走 `@easbot/terminal` `printHuman` + `emitJsonOk` + `COMMANDS_HELP` 单一数据源。
14
16
 
15
17
  ## 安装
16
18
 
@@ -20,52 +22,273 @@ pnpm add @easbot/memory
20
22
 
21
23
  ## 使用示例
22
24
 
25
+ ### 9 op 入口
26
+
27
+ ```typescript
28
+ import { executeOp } from '@easbot/memory';
29
+
30
+ // v0.4.0 简化:不再有 `createMemorySystem` + `setOpSystem` 主类;
31
+ // 全部 op 走 `executeOp(name, args, ctx)` 统一入口(agentId 走 ctx 注入)。
32
+
33
+ // 1. recall
34
+ const recall = await executeOp<{ hits: unknown[] }>(
35
+ 'recall',
36
+ {
37
+ // 不再传 agentId 到 args 顶层 —— 走 ctx.agentId
38
+ query: 'user preference',
39
+ limit: 10,
40
+ scope: 'agent_only',
41
+ // dbPath / workspaceDir 走 ctx 或 service 配置;可省略
42
+ dbPath: '/path/to/memory.db',
43
+ workspaceDir: '/path/to/workspace',
44
+ rootDir: '/path/to/workspace',
45
+ locale: 'en-US',
46
+ remote: false,
47
+ },
48
+ {
49
+ agentId: 'agent-1',
50
+ isTrustedLocal: true,
51
+ },
52
+ );
53
+
54
+ // 2. remember
55
+ const saved = await executeOp<{ id: string }>(
56
+ 'remember',
57
+ {
58
+ content: '老侯 prefers TypeScript',
59
+ category: 'user_preference',
60
+ importance: 9,
61
+ dbPath: '/path/to/memory.db',
62
+ workspaceDir: '/path/to/workspace',
63
+ rootDir: '/path/to/workspace',
64
+ locale: 'en-US',
65
+ remote: false,
66
+ },
67
+ { agentId: 'agent-1', isTrustedLocal: true },
68
+ );
69
+
70
+ // 3. forget(按 category 全删)
71
+ await executeOp(
72
+ 'forget',
73
+ {
74
+ category: 'user_preference',
75
+ maxDelete: 1000,
76
+ dryRun: false,
77
+ dbPath: '/path/to/memory.db',
78
+ workspaceDir: '/path/to/workspace',
79
+ rootDir: '/path/to/workspace',
80
+ locale: 'en-US',
81
+ remote: false,
82
+ },
83
+ { agentId: 'agent-1', isTrustedLocal: true },
84
+ );
85
+ ```
86
+
87
+ ### KG scope 三档
88
+
89
+ ```typescript
90
+ // 只看本 Agent 节点(默认;MCP 入口强制)
91
+ await executeOp('graph_query', { agentId: 'agent-1', kind: 'nodes', scope: 'agent_only' }, { agentId: 'agent-1', isTrustedLocal: true });
92
+
93
+ // 只看共享节点
94
+ await executeOp('graph_query', { agentId: 'agent-1', kind: 'nodes', scope: 'shared_only' }, { agentId: 'agent-1', isTrustedLocal: true });
95
+
96
+ // 本 Agent + 共享(trusted local only;MCP 入口会拒绝)
97
+ await executeOp('graph_query', { agentId: 'agent-1', kind: 'nodes', scope: 'both' }, { agentId: 'agent-1', isTrustedLocal: true });
98
+
99
+ // v0.4.1+:不传 agentId → fallback 'default',全局 KG 视图(trusted local only)
100
+ await executeOp('graph_query', { kind: 'nodes', scope: 'both' }, { isTrustedLocal: true });
101
+ ```
102
+
103
+ ### Markdown 渲染
104
+
105
+ ```typescript
106
+ import { renderOperationMarkdown } from '@easbot/memory';
107
+ const md = await renderOperationMarkdown('recall', recallResult, { toolName: 'memory_recall' });
108
+ ```
109
+
110
+ ## 9 op 清单
111
+
112
+ | op | trusted local only | agentId | 用途 |
113
+ |---|---|---|---|
114
+ | `recall` | ❌ | ✅ 必填 | 混合搜索(FTS + vector + graph) |
115
+ | `remember` | ❌ | ✅ 必填 | 持久化一条 self-memory fact |
116
+ | `forget` | ❌ | ✅ 必填 | 按 factId / category / 时间窗删除(支持 `dryRun`) |
117
+ | `extract` | ❌ | ✅ 必填 | 从 session 抽取 facts |
118
+ | `consolidate` | ✅ | ✅ 必填 | 整理 / 去重 / 摘要 |
119
+ | `graph_query` | ❌ (scope=both 时 ✅) | ⚠️ optional,缺省 `'default'` | KG 节点 / 边 / 邻居查询 |
120
+ | `status` | ❌ | ⚠️ optional,缺省全局聚合 | 系统状态快照 |
121
+ | `doctor` | ✅ | ⚠️ optional,缺省全库扫描 | 数据完整性检查(支持 `repair`) |
122
+ | `init` | ✅ | ⚠️ optional,缺省 `'default'` | 初始化 workspace(支持 `force`) |
123
+
124
+ **P0-A 反转说明**(v0.4.1 起):
125
+
126
+ `graph_query` / `status` / `doctor` / `init` 四个 op 的 `agentId` 改为 **optional**,缺省时 fallback 到固定值 `'default'`,不再因缺失 agentId 抛错。这条决策与 ADR 0055 / 0056 / 0057 中"agent scope 必填"的早期语义相反,目的是让 CLI / 状态查询 / 一次性诊断场景可以无 agent 上下文运行。
127
+
128
+ - `graph_query` 不传 agentId → 全局 KG 视图(`scope` 仍由调用方决定,trusted local 默认 `'both'`)
129
+ - `status` 不传 agentId → 跨 agent 聚合统计(不再是单一 agent 视图)
130
+ - `doctor` / `init` 不传 agentId → 全局默认 agent = `'default'`,与 status / graph_query 口径一致
131
+
132
+ ## API 分类
133
+
134
+ ### services(9 op 业务层)
135
+
136
+ ```typescript
137
+ import { recall, remember, forget } from '@easbot/memory/services';
138
+ ```
139
+
140
+ ### operations(9 op 注册表 + executeOp)
141
+
142
+ ```typescript
143
+ import { executeOp, OP_REGISTRY, ALL_OPS } from '@easbot/memory/operations';
144
+ ```
145
+
146
+ ### format(schema + markdown + text + truncate + render)
147
+
148
+ ```typescript
149
+ import { renderOperationMarkdown } from '@easbot/memory/format/render';
150
+ ```
151
+
152
+ ### hooks(4 hook 类型)
153
+
154
+ ```typescript
155
+ import type { PreCompactHook, SessionStartHook, SessionEndHook, PostToolFailureHook } from '@easbot/memory/hooks';
156
+ ```
157
+
158
+ ## CLI / MCP 双入口(v0.4 stage 4 落地)
159
+
160
+ ### 独立 CLI(`easbot-memory`)
161
+
162
+ ```bash
163
+ # 安装后即可用(package.json bin: easbot-memory)
164
+ easbot-memory init --workspace-dir <dir> [--agent <id>]
165
+ easbot-memory status [--agent <id>] [--json]
166
+ easbot-memory doctor [--repair] [--agent <id>]
167
+ easbot-memory recall --query <q> --agent <id> [--limit <n>] [--json]
168
+ easbot-memory remember --content <text> --category <c> --importance <1-10> --agent <id>
169
+ easbot-memory forget --agent <id> [--fact-id <id>] [--dry-run]
170
+ easbot-memory extract --session <sessionId> [--last-n <n>] --agent <id>
171
+ easbot-memory consolidate --agent <id> [--window-days <n>]
172
+ easbot-memory graph --kind <nodes|edges|neighbors> [--query <q>] [--agent <id>]
173
+ easbot-memory config [--json]
174
+ easbot-memory mcp
175
+ ```
176
+
177
+ > v0.4.1 起:`init` / `status` / `doctor` / `graph` 的 `--agent` 为可选,缺省时 fallback 到 `'default'`(CLI / 一次性诊断场景无需 agent 上下文);其余 5 op(`recall` / `remember` / `forget` / `extract` / `consolidate`)仍要求显式 `--agent`,缺失时返回非 0 退出码。
178
+
179
+ ### Agent 委派模式(v0.4 stage 4 T-M017a)
180
+
181
+ ```bash
182
+ # @easbot/agent 的 memory 子命令直接委派 handleMemoryCli(决策 0049)
183
+ easbot memory recall --query "user preference"
184
+ easbot memory remember --content "老侯 prefers TypeScript"
185
+ easbot memory mcp # 启动 MCP stdio server
186
+ ```
187
+
188
+ ### MCP stdio server(v0.4 stage 4 T-M013abc)
189
+
23
190
  ```typescript
24
- import { MemoryIndexManager } from '@easbot/memory';
191
+ import { MemoryStdioServer } from '@easbot/memory';
25
192
 
26
- // 获取记忆管理器实例
27
- const manager = await MemoryIndexManager.get({
28
- workspaceDir: '/path/to/workspace',
193
+ // 启动 9 tool 的 MCP stdio server(Cline / Claude Code / Continue 可调用)
194
+ // v0.4.0:start 签名简化(不需要 `memorySystem` 参数,handler 走 executeOp 调度 services)
195
+ await MemoryStdioServer.start({
196
+ name: 'easbot-memory',
197
+ version: '0.4.0',
198
+ description: 'EASBot memory MCP server',
29
199
  });
30
200
 
31
- // 搜索记忆
32
- const results = await manager.search('机器学习', {
33
- maxResults: 10,
34
- minScore: 0.5,
201
+ // 列出 9 个 tool 名
202
+ const tools = MemoryStdioServer.getToolNames();
203
+ // ['memory_recall', 'memory_remember', 'memory_forget', ...]
204
+ ```
205
+
206
+ **9 tool 清单**(与 `OP_REGISTRY` 一一对应):
207
+ - `memory_recall` / `memory_remember` / `memory_forget` / `memory_extract` / `memory_consolidate` / `memory_graph_query` / `memory_status` / `memory_doctor` / `memory_init`
208
+
209
+ ### handleMemoryCli 委派范式
210
+
211
+ ```typescript
212
+ import { handleMemoryCli, setGlobalAdapter, setInstanceAdapter } from '@easbot/memory';
213
+
214
+ // 1. 注入 adapter(cli 路径 / agent 路径)
215
+ setGlobalAdapter({ Path: { /* ... */ } });
216
+ setInstanceAdapter({ directory: process.cwd(), worktree: process.cwd() });
217
+
218
+ // 2. 委派给统一 handler
219
+ const result = await handleMemoryCli(['recall', '--query', 'test'], {
220
+ version: '0.4.0',
221
+ cwd: process.cwd(),
35
222
  });
36
223
 
37
- // 索引文件
38
- await manager.indexFile('/path/to/file.md');
224
+ if (result.code !== 0) process.exit(result.code);
39
225
  ```
40
226
 
41
- ## API
227
+ ## fact → .md 文档同步(v0.5+ ADR 0060)
42
228
 
43
- ### MemoryIndexManager
229
+ `remember` op 在事务提交后会**best-effort**地将 fact 渲染为 Markdown 文件,便于:
44
230
 
45
- | 方法 | 说明 |
46
- |------|------|
47
- | `get(params)` | 获取或创建管理器实例 |
48
- | `search(query, options)` | 混合搜索 |
49
- | `indexFile(filePath)` | 索引单个文件 |
50
- | `indexDirectory(dirPath)` | 索引目录 |
51
- | `getStatus()` | 获取状态信息 |
231
+ - debug:开发者直接看磁盘上的「人类可读副本」
232
+ - 二次开发:未来 `note` 工具可通过 file watcher 检测 memory .md 变化触发 cross-reference 更新
233
+ - 灾备:file 失败**不阻塞** db 写入(与 v0.3 行为一致)
52
234
 
53
- ## 开发
235
+ ### 路径格式
54
236
 
55
- ```bash
56
- # 安装依赖
57
- pnpm install
237
+ ```
238
+ {workspaceDir}/.easbot/knowledge/memory/{category}/{YYYY-MM}/mem_{id}.md
239
+ ```
58
240
 
59
- # 构建
60
- pnpm build
241
+ - 按 **category** 分目录(`task_context` / `workflow` / `user_preference` / ...)
242
+ - 按 **createdAt 月份**分目录(避免单月文件过多)
243
+ - 文件名 = `fact.id`(全局唯一)
244
+ - `memory_facts.file_path` 列存**相对 workspaceDir 的 POSIX 路径**
61
245
 
62
- # 测试
63
- pnpm test
246
+ ### Markdown 模板
64
247
 
65
- # 类型检查
66
- pnpm type-check
248
+ ```markdown
249
+ ---
250
+ id: mem_xxx
251
+ agent_id: easbot-xxx
252
+ category: task_context
253
+ importance: 7
254
+ created_at: 2026-08-22T22:00:00Z
255
+ updated_at: 2026-08-22T22:00:00Z
256
+ tags: [tag1, tag2]
257
+ ---
258
+
259
+ # fact 内容(一行一个)
260
+
261
+ **category**: task_context | **importance**: 7/10 | **source**: session_self_write
67
262
  ```
68
263
 
264
+ ### 编程式调用(高级)
265
+
266
+ 大多数场景不需要直接调 —— 走 `executeOp('remember' / 'forget')` 即可。需要精细控制时(如批量迁移 / 自定义路径策略):
267
+
268
+ ```typescript
269
+ import { factFileSync } from '@easbot/memory/services';
270
+
271
+ // 1. 计算路径(不写文件)
272
+ const absPath = factFileSync.resolvePath(fact, '/path/to/workspace');
273
+
274
+ // 2. 渲染 Markdown 字符串(不写文件)
275
+ const md = factFileSync.renderMarkdown(fact);
276
+
277
+ // 3. 写文件(best-effort;失败返回 ok=false + log.warn)
278
+ const { ok, relPath, absPath } = await factFileSync.write(fact, '/path/to/workspace');
279
+
280
+ // 4. 删文件(按 fact.filePath;不存在返回 ok=true,idempotent)
281
+ const { ok, absPath } = await factFileSync.delete(fact, '/path/to/workspace');
282
+ ```
283
+
284
+ ### 策略与限制
285
+
286
+ - **best-effort**:写/删文件失败 → log.warn + 返回 `ok=false`,**不抛错,不阻塞**主流程
287
+ - **单进程假设**:未实现跨进程文件锁(与 v0.3 一致)
288
+ - **不做 stale orphan 清理**:forget 删 db 后删文件;如 db 删成功文件删失败 → 留 stale .md(doctor 第 9 项「orphan file 检测」后续增强)
289
+
290
+ 详见 `docs/decisions/0060-memory-fact-file-sync-restore.md`。
291
+
69
292
  ## 数据库位置
70
293
 
71
294
  默认存储位置:`$XDG_DATA_HOME/easbot/memory.db`
@@ -74,6 +297,38 @@ pnpm type-check
74
297
  - macOS: `~/Library/Application Support/easbot/memory.db`
75
298
  - Windows: `%APPDATA%/easbot/memory.db`
76
299
 
300
+ ## 决策与迁移
301
+
302
+ - ADR 0068(v0.4.1 P0-A 反转:graph_query / status / doctor / init 的 agentId 改为 optional,缺省 fallback `'default'`):`docs/decisions/0068-p0a-agent-id-optional.md`
303
+ - ADR 0060(v0.5+ fact → .md 同步恢复):`docs/decisions/0060-memory-fact-file-sync-restore.md`
304
+ - ADR 0055 / 0056 / 0057(v0.4 决策):`.easbot/protocol.json` 与 `docs/decisions/00NN-*.md`
305
+ - 迁移脚本:`scripts/migrate/{scan,apply,review}.ts` + `scripts/db-backup.ts`(v0.3 → v0.4 `owner_agent_id` 列添加 + 默认 scope = agent_only)
306
+ - CI guard(v0.4 stage 5 三包统一后台支撑):
307
+ - `scripts/check-database-facade.sh`(禁止直接 require better-sqlite3 / node:sqlite / createRequire)
308
+ - `scripts/check-mcp-facade.sh`(禁止直接 import @modelcontextprotocol/sdk)
309
+ - `scripts/check-terminal-facade.sh`(CLI 输出走 @easbot/terminal + COMMANDS_HELP 单一数据源)
310
+ - `scripts/check-cmd-i18n-coverage.sh`(zh-CN / en-US 双 locale 一致性 + switch-case 路由校验)
311
+ - L-M13 / L-M14 / L-M15 教训沉淀:`.easbot/knowledge/tasks/memory-v04-refactor/findings.md`
312
+
313
+ ## 开发
314
+
315
+ ```bash
316
+ # 安装
317
+ pnpm install
318
+
319
+ # 构建
320
+ pnpm build
321
+
322
+ # 测试(vitest 4)
323
+ pnpm test:run
324
+
325
+ # 类型检查
326
+ pnpm type-check
327
+
328
+ # lint(biome 2.x)
329
+ pnpm biome-lint
330
+ ```
331
+
77
332
  ## 许可证
78
333
 
79
- MIT
334
+ MIT
@@ -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 os=require('os'),path=require('path'),xdgBasedir=require('xdg-basedir');var o=null,n=null;function b(t){o=t;}function f(){o=null;}function a(){if(o)return o;let t=os.homedir();return {Path:{home:t,data:process.env.EASBOT_DATA_PATH?.trim()||path.join(xdgBasedir.xdgData??path.join(t,".local","share"),"easbot"),config:process.env.EASBOT_CONFIG_PATH?.trim()||path.join(t,".config","easbot"),state:process.env.EASBOT_STATE_PATH?.trim()||path.join(xdgBasedir.xdgData??path.join(t,".local","share"),"easbot","state"),cache:process.env.EASBOT_CACHE_PATH?.trim()||path.join(t,".cache","easbot"),log:process.env.EASBOT_LOG_PATH?.trim()||path.join(xdgBasedir.xdgData??path.join(t,".local","share"),"easbot","log"),bin:process.env.EASBOT_BIN_PATH?.trim()||path.join(t,".local","bin")}}}function g(t){n=t;}function A(){n=null;}function I(){if(n)return n;let t=process.cwd();return {directory:t,worktree:t}}function c(){return a().Path.home||os.homedir()}function l(){let t=a().Path.data;return t||(xdgBasedir.xdgData??path.join(c(),".local","share"))}function T(){return path.join(l(),"memory")}function _(t){let i=typeof t=="string"?t:t?.dir??t?.workspaceDir??process.cwd();return path.join(i,".easbot","db","memory.db")}exports.a=b;exports.b=f;exports.c=a;exports.d=g;exports.e=A;exports.f=I;exports.g=c;exports.h=l;exports.i=T;exports.j=_;
@@ -0,0 +1,53 @@
1
+ import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Filesystem}from'@easbot/utils';import {createSyncSqliteConnection}from'@easbot/database';var d=Log.create({service:"memory-schema-migrations"}),T=2,S=[{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,r={}){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(t=>t.id)),s={applied:[],pending:[],errors:[],currentVersion:i.length===0?0:Math.max(...i.map(t=>t.id)),targetVersion:e};for(let t of S){if(t.id>e)break;if(a.has(t.id)){s.pending.push(t.id);continue}if(r.dryRun){s.applied.push(t.id);continue}try{_(n,t.up),n.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(t.id),a.add(t.id),s.applied.push(t.id),d.info("migration applied",{id:t.id,description:t.description});}catch(E){let l=E instanceof Error?E.message:String(E),h=t.up[0]??"";s.errors.push({migrationId:t.id,sql:h,error:l}),d.warn("migration step failed",{id:t.id,error:l,sqlCount:t.up.length});}}return s}function _(n,e){for(let r of e)try{n.exec(r);}catch(i){let a=i instanceof Error?i.message:String(i);if(R(a)){d.debug("migration: column already exists, skipping",{sql:r.slice(0,80)});continue}throw i}}function R(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(r=>r.id))}catch{return 0}}var c=Log.create({service:"memory-database"}),p=class{constructor(e){a(this,"db",null);a(this,"storagePath");a(this,"backend","better-sqlite3");a(this,"initialized",false);a(this,"initPromise",null);this.storagePath=e===":memory:"?e:Filesystem.normalize(e);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize();try{await this.initPromise,this.initialized=!0;}catch(e){try{this.db&&this.db.close();}catch{}throw this.db=null,this.initPromise=null,e}}}async doInitialize(){try{let e=this.openConnection();e.initialize(),this.db=e,this.applyPragmas(),this.runAllMigrations();}catch(e){let r=e instanceof Error?e.message:String(e);throw c.error("Database initialization failed",{error:r}),e}}openConnection(){return createSyncSqliteConnection({path:this.storagePath,backend:this.backend,walMode:true,foreignKeys:true,busyTimeoutMs:5e3})}applyPragmas(){if(this.db)try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("foreign_keys = ON");}catch(e){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 r=e.errors.map(i=>`migration ${i.migrationId}: ${i.error}`).join("; ");throw new Error(`Some migrations failed: ${r}`)}}query(e,r){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let i=this.db.prepare(e);return r?i.all(...r):i.all()}catch(i){throw new Error(`Query failed: ${i.message}`)}}agentFilter(e){return typeof e=="string"&&e.trim().length>0?{where:"WHERE agent_id = ?",params:[e.trim()]}:{where:"",params:[]}}run(e,r){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let i=this.db.prepare(e),a=r?i.run(...r):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,r){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,r);}};export{T as a,S as b,m as c,g as d,p as e};
@@ -0,0 +1,42 @@
1
+ 'use strict';var chunkOIUUTVLL_cjs=require('./chunk-OIUUTVLL.cjs'),chunkCPRDIUQ4_cjs=require('./chunk-CPRDIUQ4.cjs'),chunkNVGACA7W_cjs=require('./chunk-NVGACA7W.cjs'),utils=require('@easbot/utils'),ai=require('ai'),zod=require('zod'),crypto=require('crypto'),types=require('@easbot/types'),P=require('fs/promises'),W=require('path'),fs=require('fs');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var P__default=/*#__PURE__*/_interopDefault(P);var W__default=/*#__PURE__*/_interopDefault(W);var G=utils.Log.create({service:"memory.graph-store"}),v=class{constructor(e){chunkNVGACA7W_cjs.a(this,"db");this.db=e;}async upsertNode(e,r,n,i){let c=Date.now(),o=JSON.stringify(n??{}),s=this.db.prepare("SELECT id FROM nodes WHERE name = ? AND type = ? LIMIT 1").get(e,r);if(s)return this.db.prepare("UPDATE nodes SET properties = ?, updatedAt = ? WHERE id = ?").run(o,c,s.id),s.id;let l=this.db.prepare("INSERT INTO nodes (name, type, properties, owner_agent_id, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)").run(e,r,o,i??null,c,c);return Number(l.lastInsertRowid)}async deleteNode(e){this.db.prepare("DELETE FROM nodes WHERE id = ?").run(e);}async upsertEdge(e,r,n,i){let c=this.db.prepare("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)").run(e,r,n,JSON.stringify(i??{}),Date.now());return Number(c.lastInsertRowid)}async queryNodes(e={}){let r="SELECT id, name, type, properties, owner_agent_id, createdAt, updatedAt FROM nodes",n=[],i=[];if(e.ids&&e.ids.length>0){let o=e.ids.map(s=>typeof s=="string"?parseInt(s,10):s).filter(s=>!Number.isNaN(s));i.push(`id IN (${o.map(()=>"?").join(", ")})`),n.push(...o);}e.name&&(i.push("name LIKE ?"),n.push(`%${e.name}%`)),e.type&&(i.push("type = ?"),n.push(e.type)),Je(i,n,e.agentId,e.scope??"agent_only"),i.length>0&&(r+=` WHERE ${i.join(" AND ")}`),r+=" ORDER BY id",e.limit&&(r+=" LIMIT ?",n.push(e.limit)),G.debug("queryNodes",{sql:r,params:n,filter:e});let c=this.db.prepare(r).all(...n);return G.debug("queryNodes result",{count:c.length}),c.map(o=>({id:o.id,name:o.name,type:o.type,properties:o.properties?JSON.parse(o.properties):void 0,createdAt:o.createdAt,updatedAt:o.updatedAt,ownerAgentId:o.owner_agent_id}))}async queryEdges(e={}){let r="SELECT e.id, e.source, e.target, e.relation, e.properties, e.createdAt FROM edges e",n=[],i=[];if(e.ids&&e.ids.length>0&&(i.push(`e.id IN (${e.ids.map(()=>"?").join(", ")})`),n.push(...e.ids)),e.source!==void 0&&(i.push("e.source = ?"),n.push(e.source)),e.target!==void 0&&(i.push("e.target = ?"),n.push(e.target)),e.sourceOrTarget&&e.sourceOrTarget.length>0){let u=e.sourceOrTarget.map(d=>typeof d=="string"?parseInt(d,10):d).filter(d=>!Number.isNaN(d));i.push(`(e.source IN (${u.map(()=>"?").join(", ")}) OR e.target IN (${u.map(()=>"?").join(", ")}))`),n.push(...u,...u);}e.relation&&(i.push("e.relation = ?"),n.push(e.relation)),i.length>0&&(r+=` WHERE ${i.join(" AND ")}`),r+=" ORDER BY e.id",e.limit&&(r+=" LIMIT ?",n.push(e.limit)),G.debug("queryEdges",{sql:r,params:n,filter:e});let c=this.db.prepare(r).all(...n);G.debug("queryEdges result",{count:c.length});let o=[...new Set(c.map(u=>u.target))],s=o.length>0?await this.queryNodes({ids:o,limit:o.length}):[],l=new Map(s.map(u=>[u.id,u]));return c.map(u=>{let d={id:u.id,source:u.source,target:u.target,relation:u.relation,properties:u.properties?JSON.parse(u.properties):void 0,createdAt:u.createdAt},E=l.get(u.target);return E&&(d.targetNode=E),d})}async queryNeighbors(e,r=1,n){let i=n?.agentId,c=n?.scope??"agent_only",o=new Set,s=[{id:e,level:0}],l=[],u=n?.maxEdgesPerNode??50;for(;s.length>0;){let d=s.shift();if(!d)break;if(o.has(d.id)||d.level>r)continue;o.add(d.id);let R=(await this.queryNodes({ids:[d.id],limit:1,agentId:i,scope:c}))[0];if(!R)continue;let I=await this.queryEdges({sourceOrTarget:[d.id],limit:u}),f=i?await Ke(this,I,i,c):I;if(l.push({...R,edges:f}),d.level<r)for(let h of f){let g=h.source===d.id?h.target:h.source;o.has(g)||s.push({id:g,level:d.level+1});}}return l}};async function Ke(t,e,r,n){if(e.length===0)return e;let i=new Set;for(let s of e)i.add(s.source),i.add(s.target);let c=await t.queryNodes({ids:Array.from(i),agentId:r,scope:n,limit:i.size}),o=new Set(c.map(s=>s.id));return e.filter(s=>o.has(s.source)&&o.has(s.target))}function Je(t,e,r,n){if(r)switch(n){case "agent_only":t.push("owner_agent_id = ?"),e.push(r);break;case "shared_only":t.push("owner_agent_id IS NULL");break;case "both":t.push("(owner_agent_id = ? OR owner_agent_id IS NULL)"),e.push(r);break}}exports.b=void 0;(I=>{let t=utils.Log.create({service:"memory-llm"}),e=null;function r(f){n()||(e={models:f.models,options:f.options??{}},t.debug("Llm initialized",{embeddingConfigured:!!f.models.embeddingLlm,graphConfigured:!!f.models.graphLlm}));}I.init=r;function n(){return e!==null}I.isInitialized=n;function i(){e=null;}I.reset=i;function c(){return e?{embedding:!!e.models.embeddingLlm,graph:!!e.models.graphLlm}:{embedding:false,graph:false}}I.capabilities=c;async function o(f){let g=d().models.embeddingLlm;if(!g)throw new Error("embeddingLlm model is not configured.");try{let m=await ai.embed({model:g,value:f});return new Float32Array(m.embedding)}catch(m){let p=g.doEmbed;if(typeof p!="function")throw new Error("embeddingLlm model does not support embedding generation.",{cause:m});let S=(await p({values:[f]}))?.embeddings?.[0];if(!S||!Array.isArray(S))throw new Error("embeddingLlm model returned invalid embedding result.",{cause:m});return new Float32Array(S)}}I.embedText=o;async function s(f){let g=d().models.embeddingLlm;if(!g)throw new Error("embeddingLlm model is not configured.");try{return (await ai.embedMany({model:g,values:f})).embeddings.map(p=>new Float32Array(p))}catch{return ((await g.doEmbed?.({values:f}))?.embeddings??[]).map(p=>new Float32Array(p))}}I.embedTexts=s;async function l(f,h,g,m={}){if(!d().models.graphLlm)return t.debug("generateGraph skipped: graphLlm not configured"),"";let{maxContentLength:b,maxChunks:S,includeSummary:M,...y}=m,T=utils.buildEntityExtractionPrompt(f,h,g,{maxContentLength:b,maxChunks:S,includeSummary:M});return u(T,y)}I.generateGraph=l;async function u(f,h){let g=d(),m=g.models.graphLlm;if(!m)throw new Error("llm model is not configured.");try{return (await ai.streamText({model:m,prompt:f,maxOutputTokens:h?.maxOutputTokens??g.options.graph?.maxOutputTokens,temperature:h?.temperature??g.options.graph?.temperature})).text}catch{return (await m.doGenerate?.({prompt:[{role:"user",content:[{type:"text",text:f}]}],maxOutputTokens:h?.maxOutputTokens??g.options.graph?.maxOutputTokens}))?.content?.find(b=>b.type==="text")?.text??""}}I.generate=u;let d=()=>{if(!e)throw new Error("Llm is not initialized. Please call Llm.init() first.");return e};I.embed=o,I.embedMany=s;})(exports.b||(exports.b={}));var w=class extends Error{constructor(r,n,i){super(r);chunkNVGACA7W_cjs.a(this,"code",n);chunkNVGACA7W_cjs.a(this,"details",i);this.name="ServiceError";}};var Q=class extends w{constructor(){super("ctx.agentId is required for memory service (ADR 0055 per-agent isolation)","AGENT_ID_REQUIRED");}},k=class extends w{constructor(e,r){super(`Trust denied for operation "${e}": ${r}`,"TRUST_DENIED",{operation:e,reason:r});}},F=class extends w{constructor(e,r){super(`Memory ${e} has ${r} references (force=false)`,"HAS_REFERENCES",{memoryId:e,referenceCount:r});}},H=class extends w{constructor(e){super(`dryRun mode: ${e} memories matched but not deleted`,"DRY_RUN_NO_DELETE",{matchedCount:e});}},q=class extends w{constructor(e,r){super(`Matched ${e} memories exceeds maxDelete=${r}`,"MAX_DELETE_EXCEEDED",{matched:e,maxDelete:r});}};function D(t){if(typeof t.agentId!="string"||t.agentId.trim().length===0)throw new Q}function x(t,e){if(t.remote!==false)throw new k(e,"requires trusted local caller (CLI / agent tool / MCP with remote=false)")}function z(t,e,r){if(e!=="agent_only"&&t.remote!==false)throw new k(r,`scope="${e}" requires trusted local caller (cross-agent access denied)`)}function B(t){if(!t.dbPath||t.dbPath.trim().length===0)throw new w("service ctx.dbPath is required (MemoryKnowledgeConfigWithModels.database.path)","INTERNAL")}var $=utils.Log.create({service:"memory.service.recall"});async function Ee(t,e){let r=Date.now();if(D(t),B(t),!e.query||e.query.trim().length===0)throw new w("recall requires non-empty `query`","CONTENT_REQUIRED");let n=e.includeShared?"both":"agent_only";e.includeGraph&&z(t,n,"recall"),$.debug("recall invoked",{agentId:t.agentId,query:e.query,category:e.category,maxResults:e.maxResults,includeGraph:e.includeGraph,scope:n});let i=e.maxResults??10,c=e.minScore??0,o=[],s=new chunkOIUUTVLL_cjs.e(t.dbPath);try{await s.initialize();let l=exports.b.isInitialized()&&exports.b.capabilities().embedding,u=await rt(s,t.agentId,e.query,{category:e.category,minImportance:e.minImportance,fromTime:e.fromTime,toTime:e.toTime,limit:i,minScore:c,hasEmbedding:l}),d;if(e.includeGraph&&u.length>0)try{let R=new v(s.getDb()),I=e.depth??1,f=u.flatMap(b=>(b.nodes??[]).map(S=>S.id)).slice(0,5),h=new Set,g=new Map;for(let b of f){let S=await R.queryNeighbors(b,I,{agentId:t.agentId,scope:n,maxEdgesPerNode:10});for(let M of S)h.add(M.id),g.set(M.id,M.edges??[]);}let m=h.size>0?s.query(`SELECT id, name, type FROM nodes WHERE id IN (${Array.from(h).map(()=>"?").join(",")})`,Array.from(h)):[],p=Array.from(g.values()).flat();d={nodes:m.map(b=>({id:b.id,name:b.name,type:b.type,createdAt:"",updatedAt:""})),edges:p};}catch(R){let I=R instanceof Error?R.message:String(R);$.warn("recall: KG neighbor query failed",{error:I}),o.push(`kg_neighbor_query_failed: ${I}`),d={nodes:[],edges:[]};}let E=Date.now()-r;return {hits:u,total:u.length,truncated:u.length>=i,durationMs:E,graph:d,...o.length>0?{warnings:o}:{}}}catch(l){throw l instanceof w?l:new w(`recall failed: ${l instanceof Error?l.message:String(l)}`,"INTERNAL",{cause:l instanceof Error?l.message:String(l)})}finally{s.close();}}async function rt(t,e,r,n){let i=["mf.agent_id = ?"],c=[e];n.category&&(i.push("mf.category = ?"),c.push(n.category)),n.minImportance!==void 0&&(i.push("mf.importance >= ?"),c.push(n.minImportance)),n.fromTime&&(i.push("mf.created_at >= ?"),c.push(n.fromTime)),n.toTime&&(i.push("mf.created_at <= ?"),c.push(n.toTime));let o=i.join(" AND "),s=null;if(n.hasEmbedding)try{s=await exports.b.embedText(r);}catch(y){$.warn("recall: query embedding failed, falling back to FTS-only",{error:y instanceof Error?y.message:String(y)}),s=null;}let l=Math.max(n.limit*100,1e3),[u,d]=await Promise.all([s?nt(t,s,o,c,l):Promise.resolve([]),ot(t,r,o,c,n.limit)]),E=s?.7:0,R=s?.3:1,I=E+R,f=E/I,h=R/I,g=new Map;for(let y of u)g.set(y.id,y.score*f);for(let y of d)g.set(y.id,(g.get(y.id)??0)+y.score*h);let m=Array.from(g.entries()).sort((y,T)=>T[1]-y[1]).map(([y])=>y).slice(0,n.limit);if(m.length===0)return [];let p=m.map(()=>"?").join(","),b=t.query(`SELECT
2
+ mf.id,
3
+ mf.category,
4
+ mf.importance,
5
+ mf.agent_id as agentId,
6
+ SUBSTR(mf.content, 1, 200) as snippet,
7
+ mf.created_at as createdAt,
8
+ mf.source,
9
+ mf.file_path as filePath,
10
+ mf.node_ids as nodeIds
11
+ FROM memory_facts mf
12
+ WHERE mf.id IN (${p})`,m),S=Date.now();return b.map(y=>{let T=g.get(y.id)??0,je=(S-new Date(y.createdAt).getTime())/864e5,Ge=Math.exp(-0.05*je),Qe=(y.importance-1)/9,ze=.4*T+.3*Ge+.3*Qe;return {memoryId:y.id,category:y.category,importance:y.importance,agentId:y.agentId,snippet:y.snippet,score:ze,createdAt:y.createdAt,source:y.source,filePath:y.filePath??void 0,nodes:void 0}}).filter(y=>y.score>=n.minScore).sort((y,T)=>T.score-y.score)}function nt(t,e,r,n,i){try{return t.query(`SELECT mf.id, mv.embedding
13
+ FROM memory_facts mf
14
+ JOIN memory_vectors mv ON mf.id = mv.fact_id
15
+ WHERE ${r}
16
+ LIMIT ?`,[...n,i]).map(o=>{let s=new Float32Array(o.embedding.buffer,o.embedding.byteOffset,o.embedding.byteLength/4);return {id:o.id,score:at(e,s)}}).sort((o,s)=>s.score-o.score)}catch(c){if(c instanceof w)throw c;return $.warn("vector search failed, falling back to FTS-only",{error:c instanceof Error?c.message:String(c)}),[]}}function ot(t,e,r,n,i){try{let c=t.query(`SELECT mf.id as id, bm25(memory_facts_fts) as score
17
+ FROM memory_facts_fts fts
18
+ JOIN memory_facts mf ON mf.id = fts.fact_id
19
+ WHERE ${r} AND memory_facts_fts MATCH ?
20
+ ORDER BY score DESC
21
+ LIMIT ?`,[...n,st(e),i]);if(c.length===0)return [];let o=Math.max(...c.map(s=>Math.abs(s.score)),1);return c.map(s=>({id:s.id,score:1-Math.abs(s.score)/o})).filter(s=>s.score>=0)}catch(c){if(c instanceof w)throw c;return $.warn("FTS search failed, returning empty result",{err:c instanceof Error?c.message:String(c)}),[]}}function at(t,e){if(t.length!==e.length||t.length===0)return 0;let r=0,n=0,i=0;for(let o=0;o<t.length;o++){let s=t[o]??0,l=e[o]??0;r+=s*l,n+=s*s,i+=l*l;}let c=Math.sqrt(n)*Math.sqrt(i);return c===0?0:Math.max(0,r/c)}function st(t){return t.trim().split(/\s+/).filter(e=>e.length>0).map(e=>`"${e.replace(/"/g,'""')}"`).join(" ")}var we=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 Re=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 Se=zod.z.object({factId:zod.z.string().optional(),category:zod.z.string().optional(),fromTime:zod.z.string().datetime().optional(),toTime:zod.z.string().datetime().optional(),maxDelete:zod.z.number().int().min(1).max(1e4).optional().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 Ie=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 Me=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 _e=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 Oe=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 Te=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 Ce=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 U=utils.Log.create({service:"memory.fact-file-sync"}),dt=".easbot/memory/active";function X(t,e){let r=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.category||"uncategorized",i=t.createdAt?new Date(t.createdAt).getTime():Date.now(),c=Number.isNaN(i)?new Date:new Date(i),o=c.getFullYear(),s=String(c.getMonth()+1).padStart(2,"0"),l=String(c.getDate()).padStart(2,"0"),u=`${o}-${s}-${l}`;return `${r}/${dt}/${n}/${u}.md`}function De(t){let e=t.tags&&t.tags.length>0?t.tags:[],r=t.importance??5,n=t.source??"session_self_write",i=t.createdAt?utils.formatLocalISO(new Date(t.createdAt)):utils.formatLocalISO(new Date),c=t.updatedAt?utils.formatLocalISO(new Date(t.updatedAt)):i,o=["---",`id: ${t.id}`,`agent_id: ${t.agentId}`,`category: ${t.category}`,`importance: ${r}`,`created_at: ${i}`,`updated_at: ${c}`,`source: ${n}`,e.length>0?`tags: [${e.join(", ")}]`:"tags: []"];return t.sessionId&&o.push(`session_id: ${t.sessionId}`),t.msgId&&o.push(`msg_id: ${t.msgId}`),t.parentMsgId&&o.push(`parent_msg_id: ${t.parentMsgId}`),t.nodeIds&&t.nodeIds.length>0&&o.push(`node_ids: [${t.nodeIds.join(", ")}]`),o.push("---"),`${o.join(`
22
+ `)}
23
+ ${t.content.trim()}`}function Z(t,e){let r=t.replace(/\\/g,"/"),n=e.replace(/\\/g,"/").replace(/\/+$/,"");return r.startsWith(`${n}/`)?r.slice(n.length+1):r}async function mt(t,e){let r=X(t,e),n=Z(r,e);try{let i=De(t);await P__default.default.mkdir(W__default.default.dirname(r),{recursive:!0});let c="";try{c=await P__default.default.readFile(r,"utf-8");}catch(s){if(s.code!=="ENOENT")throw s}let o=c.length>0&&!c.endsWith(`
24
+ `)?`
25
+ `:"";return await P__default.default.writeFile(r,`${c}${o}${i}
26
+ `,"utf-8"),U.debug("Fact file synced (append)",{id:t.id,relPath:n}),{ok:!0,absPath:r,relPath:n}}catch(i){let c=i instanceof Error?i.message:String(i);return U.warn("Failed to write fact file (best-effort, non-blocking)",{id:t.id,absPath:r,error:c}),{ok:false,absPath:r,relPath:n,error:c}}}async function lt(t,e){let r;t.filePath?r=`${e.replace(/\\/g,"/").replace(/\/+$/,"")}/${t.filePath.replace(/^\/+/,"")}`:r=X({id:t.id,category:t.category,createdAt:t.createdAt,updatedAt:t.createdAt},e);let n=Z(r,e);try{return await P__default.default.unlink(r),U.debug("Fact file deleted",{id:t.id,relPath:n}),{ok:!0,absPath:r,relPath:n}}catch(i){if(i.code==="ENOENT")return U.debug("Fact file not found (already deleted)",{id:t.id,relPath:n}),{ok:true,absPath:r,relPath:n};let o=i instanceof Error?i.message:String(i);return U.warn("Failed to delete fact file (best-effort, non-blocking)",{id:t.id,absPath:r,error:o}),{ok:false,absPath:r,relPath:n,error:o}}}var J={resolvePath:X,renderMarkdown:De,toRelPath:Z,write:mt,delete:lt};var N=utils.Log.create({service:"memory.service.remember"});async function Ae(t,e){if(D(t),B(t),!e.content||e.content.trim().length===0)throw new w("remember requires non-empty `content`","CONTENT_REQUIRED");if(!e.category)throw new w("remember requires `category`","CATEGORY_REQUIRED");N.debug("remember invoked",{agentId:t.agentId,category:e.category,importance:e.importance??5,contentLength:e.content.length,skipDedup:e.skipDedup,extractGraph:e.extractGraph??true});let r=new chunkOIUUTVLL_cjs.e(t.dbPath);try{await r.initialize();let n=new Date().toISOString(),i=ht(),c=e.importance??5,o=e.extractGraph!==!1?utils.extractEntitiesByRules(e.content):{entities:[],relations:[]},s=o.entities,l=o.relations;if(e.extractGraph!==!1&&exports.b.isInitialized()&&exports.b.capabilities().graph){let m=t.dbPath,p=t.agentId;exports.b.generateGraph([e.content],types.GRAPH_ENTITY_TYPE_DEFINITIONS,types.GRAPH_RELATION_TYPE_DEFINITIONS).then(b=>{try{let S=utils.parseEntityExtractionResult(b,types.GRAPH_ENTITY_TYPE_DEFINITIONS,types.GRAPH_RELATION_TYPE_DEFINITIONS),M=new chunkOIUUTVLL_cjs.e(m);M.initialize().then(()=>{try{wt(M,p,S.entities,S.relations);}finally{M.close();}}).catch(y=>{N.debug("background LLM extraction db init failed",{agentId:p,error:String(y)});});}catch(S){N.debug("background LLM extraction parse failed",{agentId:p,error:String(S)});}}).catch(b=>{N.warn("background LLM extraction failed",{agentId:p,error:String(b)});});}let u=exports.b.isInitialized()&&exports.b.capabilities().embedding,d=u?await Et(r.getDb(),e.content):null,E=d?d.length:null,R=[],I=0;r.transaction(()=>{let m=new Map;for(let p of s){let b=r.query("SELECT id FROM nodes WHERE name = ? AND type = ? LIMIT 1",[p.name,p.type])[0];if(b){m.set(p.name,b.id);continue}let S=r.run("INSERT INTO nodes (name, type, properties, owner_agent_id, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)",[p.name,p.type,JSON.stringify({source:"rule_extracted"}),t.agentId,n,n]);S.lastID>0&&m.set(p.name,S.lastID);}for(let p of l){let b=m.get(p.source),S=m.get(p.target);!b||!S||r.run("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)",[b,S,p.relation,JSON.stringify({}),n]);}if(r.run(`INSERT INTO memory_facts
27
+ (id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance,
28
+ source, tags, node_ids, file_path, created_at, updated_at)
29
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i,t.agentId,e.sessionId??null,e.msgId??null,e.parentMsgId??null,e.content,e.category,c,"session_self_write",e.tags?JSON.stringify(e.tags):null,JSON.stringify(Array.from(m.values())),null,n,n]),d&&E){let p=ve(d);r.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[i,p]),I=1,r.query("SELECT value FROM meta WHERE key = ?",["vectorDims"])[0]||r.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["vectorDims",String(E)]);}r.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[i]),r.run("INSERT INTO memory_facts_fts (fact_id, agent_id, content, tags) VALUES (?, ?, ?, ?)",[i,t.agentId,e.content,e.tags?e.tags.join(" "):""]),R.push(...Array.from(m.values()));}),N.info("Memory stored",{id:i,category:e.category,agentId:t.agentId,nodeCount:R.length,vectorsWritten:I,vectorDims:E??0,embeddingMode:u?"enabled":"fts_only"});let f={id:i,agentId:t.agentId,sessionId:e.sessionId,msgId:e.msgId,parentMsgId:e.parentMsgId,content:e.content,category:e.category,importance:c,source:"session_self_write",tags:e.tags,nodeIds:R.length>0?R:void 0,filePath:void 0,createdAt:n,updatedAt:n},h="",g=await J.write(f,t.workspaceDir);if(g.ok){h=g.relPath,f.filePath=g.relPath;try{r.run("UPDATE memory_facts SET file_path = ? WHERE id = ?",[g.relPath,i]);}catch(m){N.warn("Failed to update file_path column after sync",{id:i,error:m instanceof Error?m.message:String(m)});}}return {fact:f,filePath:h,deduplicated:!1,nodeIds:R,vectorsWritten:I,vectorDims:E??0}}catch(n){throw n instanceof w?n:new w(`remember failed: ${n instanceof Error?n.message:String(n)}`,"INTERNAL",{cause:n instanceof Error?n.message:String(n)})}finally{r.close();}}function ht(){let t=Date.now(),e=crypto.randomBytes(3).toString("hex");return `mem_${t}_${e}`}function ve(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}function bt(t){return crypto.createHash("sha256").update(t).digest("hex")}async function Et(t,e){let r=bt(e),n=t.prepare("SELECT embedding FROM embedding_cache WHERE content_hash = ?").get(r);if(n?.embedding)return new Float32Array(n.embedding.buffer,n.embedding.byteOffset,n.embedding.byteLength/4);let i=await exports.b.embedText(e);if(!i||i.length===0)return null;let c=ve(i);return t.prepare("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)").run(r,c),i}function wt(t,e,r,n){if(r.length===0&&n.length===0)return;let i=new Date().toISOString(),c=new Map;t.transaction(()=>{for(let o of r){let s=t.query("SELECT id FROM nodes WHERE name = ? AND type = ? AND owner_agent_id = ? LIMIT 1",[o.name,o.type,e])[0];s&&c.set(o.name,s.id);}for(let o of r){if(c.has(o.name))continue;let s=t.run("INSERT INTO nodes (name, type, properties, owner_agent_id, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)",[o.name,o.type,JSON.stringify({source:"llm_extracted",...o.properties??{}}),e,i,i]);s.lastID>0&&c.set(o.name,s.lastID);}for(let o of n){let s=c.get(o.source),l=c.get(o.target);!s||!l||t.run("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)",[s,l,o.relation,JSON.stringify({}),i]);}}),N.debug("LLM extraction merged",{agentId:e,entityCount:r.length,relationCount:n.length,resolvedNodeCount:c.size});}var ee=utils.Log.create({service:"memory.service.forget"}),St=1e3;function It(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 w("CONTENT_REQUIRED: forget requires one of: `factId`, `category`, or `fromTime`/`toTime`","CONTENT_REQUIRED");if(e.length>1)throw new w(`mutually exclusive: forget requires exactly one of factId/category/timeRange, got [${e.join(", ")}]`,"CONTENT_REQUIRED");return e[0]}function Mt(t,e,r){let n=[r];switch(t){case "factId":return {where:"agent_id = ? AND id = ?",args:[...n,e.factId]};case "category":return {where:"agent_id = ? AND category = ?",args:[...n,e.category]};case "timeRange":{let i=["agent_id = ?"];return e.fromTime&&(i.push("created_at >= ?"),n.push(e.fromTime)),e.toTime&&(i.push("created_at <= ?"),n.push(e.toTime)),{where:i.join(" AND "),args:n}}}}function _t(t,e,r,n){return t.query(`SELECT id, node_ids FROM memory_facts WHERE ${e} LIMIT ?`,[...r,n+1]).map(c=>c.id)}function Ot(t,e,r,n){if(r.length===0)return 0;let i=r.map(()=>"?").join(",");return t.query(`SELECT COUNT(*) as count FROM memory_facts WHERE agent_id = ? AND id != ? AND node_ids IS NOT NULL AND EXISTS (
30
+ SELECT 1 FROM json_each(node_ids) AS je WHERE je.value IN (${i})
31
+ )`,[n,e,...r])[0]?.count??0}function Tt(t,e,r){let n,i,c="";return t.transaction(()=>{let o=t.query("SELECT node_ids, content, file_path, category, created_at FROM memory_facts WHERE id = ? AND agent_id = ?",[e,r])[0],s=[];if(o?.node_ids)try{s=JSON.parse(o.node_ids),Array.isArray(s)||(s=[]);}catch{s=[];}if(n=o?.file_path??void 0,i=o?.category,c=o?.created_at??"",t.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[e]),t.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[e,r]),s.length>0){let l=s.map(()=>"?").join(",");t.run(`DELETE FROM nodes WHERE id IN (${l}) AND NOT EXISTS (
32
+ SELECT 1 FROM memory_facts WHERE node_ids IS NOT NULL AND EXISTS (
33
+ SELECT 1 FROM json_each(node_ids) AS je WHERE je.value = nodes.id
34
+ )
35
+ )`,s);}}),{filePath:n,category:i,createdAt:c}}async function xe(t,e){D(t),x(t,"forget");let r=It(e),n=e.maxDelete??St,i=e.dryRun??false,c=e.force??false;ee.debug("forget invoked",{agentId:t.agentId,mode:r,maxDelete:n,dryRun:i,force:c});let o=new chunkOIUUTVLL_cjs.e(t.dbPath);try{await o.initialize();let{where:s,args:l}=Mt(r,e,t.agentId),u=_t(o,s,l,n),d=u.length>n;if(d&&!c)throw new q(u.length,n);let E=d?u.slice(0,n):u;if(i)throw new H(E.length);let R=[],I=[];for(let f of E){if(!c){let p=o.query("SELECT node_ids FROM memory_facts WHERE id = ? AND agent_id = ?",[f,t.agentId])[0],b=p?.node_ids?(()=>{try{let M=JSON.parse(p.node_ids);if(Array.isArray(M))return M.filter(y=>typeof y=="number")}catch{}return []})():[],S=Ot(o,f,b,t.agentId);if(S>0)throw new F(f,S)}let{filePath:h,category:g,createdAt:m}=Tt(o,f,t.agentId);h&&g&&I.push({id:f,filePath:h,category:g,createdAt:m}),R.push(f);}ee.info("forget complete",{agentId:t.agentId,mode:r,deletedCount:R.length,force:c,dryRun:i});for(let{id:f,filePath:h,category:g,createdAt:m}of I)await J.delete({id:f,filePath:h,category:g,createdAt:m},t.workspaceDir).catch(p=>{ee.warn("Fact file delete failed (best-effort)",{id:f,filePath:h,error:p instanceof Error?p.message:String(p)});});return {deletedCount:R.length,deletedIds:R,dryRun:i,truncatedCount:d?u.length-n:0}}catch(s){throw s instanceof w?s:new w(`forget failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{o.close();}}var te=utils.Log.create({service:"memory.service.extract"}),Dt=50,re=500;async function Le(t,e){if(D(t),!e.sessionId||e.sessionId.trim().length===0)throw new w("extract requires non-empty `sessionId`","SESSION_ID_REQUIRED");let r=e.lastN??Dt;if(r>re)throw new w(`extract lastN=${r} exceeds max=${re}`,"CONTENT_REQUIRED",{lastN:r,maxLastN:re});let n=e.sessionId,i=e.fromMessageId;te.debug("extract invoked",{agentId:t.agentId,sessionId:n,lastN:r,fromMessageId:i,writeToDisk:e.writeToDisk??true});let c=Date.now(),o=new chunkOIUUTVLL_cjs.e(t.dbPath);try{await o.initialize();let s=o.query(`SELECT id, content, category, importance, 1.0 as score, created_at, node_ids
36
+ FROM memory_facts
37
+ WHERE agent_id = ? AND session_id = ?
38
+ ORDER BY created_at ASC
39
+ LIMIT ?`,[t.agentId,n,r]),l=i?s.filter(f=>f.id>i):s,u=new Set;for(let f of l)if(f.node_ids)try{let h=JSON.parse(f.node_ids);if(Array.isArray(h))for(let g of h)typeof g=="number"&&g>0&&u.add(g);}catch(h){te.warn("extract: invalid node_ids JSON",{factId:f.id,error:h instanceof Error?h.message:String(h)});}let d=Array.from(u),E=[],R=[];if(d.length>0){let f=d.map(()=>"?").join(","),h=o.query(`SELECT id, name, type FROM nodes WHERE id IN (${f})`,d),g=new Map;for(let b of h)g.set(b.id,b.name);E=h.map(b=>({id:b.id,name:b.name,type:b.type}));let m=o.query(`SELECT source, target, relation FROM edges WHERE source IN (${f}) OR target IN (${f})`,[...d,...d]),p=new Set;R=[];for(let b of m){let S=g.get(b.source),M=g.get(b.target);if(!S||!M)continue;let y=`${S}\0${b.relation}\0${M}`;p.has(y)||(p.add(y),R.push({source:S,target:M,relation:b.relation}));}}let I=Date.now()-c;return te.info("extract complete",{agentId:t.agentId,sessionId:n,factCount:l.length,nodeCount:E.length,relationCount:R.length,durationMs:I}),{extractedCount:l.length,factIds:l.map(f=>f.id),entities:E,relations:R,messageRange:{fromMessageId:l[0]?.id??"",toMessageId:l[l.length-1]?.id??""},durationMs:I}}catch(s){throw s instanceof w?s:new w(`extract failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{o.close();}}var ae=utils.Log.create({service:"memory.service.consolidate"}),Pt=30;async function At(t){let{createHash:e}=await import('crypto');return e("sha256").update(t).digest("hex")}async function ke(t,e={}){let r=Date.now();D(t),x(t,"consolidate");let n=e.windowDays??Pt,i=e.dryRun??false;ae.debug("consolidate invoked",{agentId:t.agentId,windowDays:n,dryRun:i});let c=new chunkOIUUTVLL_cjs.e(t.dbPath);try{await c.initialize();let o=c.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 g of o){let m=await At(g.content);s.has(m)||s.set(m,[]),s.get(m)?.push(g);}let l=0,u=[];for(let[,g]of s){if(g.length<=1)continue;let m=[...g].sort((S,M)=>S.importance!==M.importance?M.importance-S.importance:M.created_at.localeCompare(S.created_at)),p=m[0];if(!p)continue;let b=m.slice(1).map(S=>S.id);l+=b.length,u.push({keep:p,removeIds:b});}let d=new Date(Date.now()-n*24*60*60*1e3).toISOString(),E=c.query(`SELECT id, content, category, importance, created_at FROM memory_facts
40
+ WHERE agent_id = ? AND created_at < ?
41
+ ORDER BY created_at ASC`,[t.agentId,d]),R=0,I=0;if(i)R=0,I=l;else {let g=W__default.default.join(t.workspaceDir,"archive");await P__default.default.mkdir(g,{recursive:!0});for(let{removeIds:m}of u){if(m.length===0)continue;let p=m.map(()=>"?").join(",");c.transaction(()=>{for(let b of m)c.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[b,t.agentId]);}),I+=m.length;}for(let m of E){let p=m.created_at.slice(0,7),b=W__default.default.join(g,p,m.category);await P__default.default.mkdir(b,{recursive:!0});let S=W__default.default.join(b,`${m.id}.md`);try{await P__default.default.writeFile(S,[`# ${m.id}`,"",`category: ${m.category}`,`importance: ${m.importance}`,`createdAt: ${m.created_at}`,"",m.content,""].join(`
42
+ `),"utf-8"),c.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[m.id,t.agentId]),R++;}catch(M){ae.warn("consolidate: archive write failed",{factId:m.id,error:M instanceof Error?M.message:String(M)});}}}let f=o.length,h=0;return ae.info("consolidate complete",{agentId:t.agentId,totalFacts:f,dedupedCount:l,compressedCount:h,archivedCount:R,skippedCount:I,dryRun:i,durationMs:Date.now()-r}),{totalFacts:f,dedupedCount:l,compressedCount:h,archivedCount:R,skippedCount:I,durationMs:Date.now()-r}}catch(o){throw o instanceof w?o:new w(`consolidate failed: ${o instanceof Error?o.message:String(o)}`,"INTERNAL",{cause:o instanceof Error?o.message:String(o)})}finally{c.close();}}var Fe=utils.Log.create({service:"memory.service.graph-query"});async function He(t,e){let r=Date.now(),n=(t.agentId??"").trim()||"default",i=e.scope??"agent_only";if(!e.query||e.query.trim().length===0)throw new w("CONTENT_REQUIRED: graphQuery requires non-empty `query`","CONTENT_REQUIRED");z(t,i,"graph_query");let c=e.depth??2,o=e.maxNodes??100,s=e.query,l=e.type,u=e.relation;Fe.debug("graphQuery invoked",{agentId:n,query:s,type:l,depth:c,maxNodes:o,scope:i,remote:t.remote});let d=new chunkOIUUTVLL_cjs.e(t.dbPath);try{await d.initialize();let E=new v(d.getDb()),R=s.includes("*")||s.includes("%")?s:`%${s}%`,I=await E.queryNodes({name:R,...l?{type:l}:{},agentId:n,scope:i,limit:o}),h=(s.includes("*")||s.includes("%")?I:I.filter(y=>y.name.toLowerCase().includes(s.toLowerCase())))[0]??null;if(!h)return {root:null,nodes:[],edges:[],truncated:!1,totalNodes:0,totalEdges:0,scope:i,durationMs:Date.now()-r};let g=await E.queryNeighbors(h.id,c,{agentId:n,scope:i,maxEdgesPerNode:20}),m=new Map;m.set(h.id,h);for(let y of g)m.set(y.id,{id:y.id,name:y.name,type:y.type,createdAt:y.createdAt,updatedAt:y.updatedAt});let p=[];for(let y of g)if(y.edges)for(let T of y.edges)u&&T.relation!==u||p.push(T);for(let y of p){if(!m.has(y.source)){let T=await E.queryNodes({ids:[y.source],agentId:n,scope:i});T[0]&&m.set(T[0].id,T[0]);}if(!m.has(y.target)){let T=await E.queryNodes({ids:[y.target],agentId:n,scope:i});T[0]&&m.set(T[0].id,T[0]);}}let b=Array.from(m.values()),S=b.length>o,M=S?b.slice(0,o):b;return Fe.info("graphQuery complete",{agentId:n,rootId:h.id,nodeCount:M.length,edgeCount:p.length,truncated:S,durationMs:Date.now()-r}),{root:h,nodes:M,edges:p,truncated:S,totalNodes:b.length,totalEdges:p.length,scope:i,durationMs:Date.now()-r}}catch(E){throw E instanceof w?E:new w(`graphQuery failed: ${E instanceof Error?E.message:String(E)}`,"INTERNAL",{cause:E instanceof Error?E.message:String(E)})}finally{d.close();}}var Y=utils.Log.create({service:"memory.service.status"}),Lt=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"];async function qe(t,e={}){let r=t.agentId&&t.agentId.trim().length>0?t.agentId:void 0;Y.debug("status invoked",{agentId:r??"<global>"});let n=new chunkOIUUTVLL_cjs.e(t.dbPath);try{await n.initialize();let c=n.query(r!==void 0?"SELECT COUNT(*) as c FROM memory_facts WHERE agent_id = ?":"SELECT COUNT(*) as c FROM memory_facts WHERE agent_id IS NOT NULL",r!==void 0?[r]:[])[0]?.c??0,s=n.query(r!==void 0?"SELECT COUNT(*) AS c FROM nodes WHERE owner_agent_id = ? OR owner_agent_id IS NULL":"SELECT COUNT(*) AS c FROM nodes",r!==void 0?[r]:[])[0]?.c??0,u=n.query("SELECT COUNT(*) as c FROM edges")[0]?.c??0,d=Lt.reduce((m,p)=>(m[p]=0,m),{}),E=n.query(r!==void 0?"SELECT category, COUNT(*) as c FROM memory_facts WHERE agent_id = ? GROUP BY category":"SELECT category, COUNT(*) as c FROM memory_facts WHERE agent_id IS NOT NULL GROUP BY category",r!==void 0?[r]:[]);for(let m of E){let p=m.category;p in d&&(d[p]=m.c);}let R=!1;try{R=n.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]).length>0;}catch(m){Y.debug("status: fts probe failed",{error:m instanceof Error?m.message:String(m)});}let I=!!t.config?.embeddingLlm,f=!1;try{f=n.query("SELECT name FROM pragma_table_info('nodes') WHERE name = ?",["owner_agent_id"]).length>0;}catch(m){Y.debug("status: kg scope probe failed",{error:m instanceof Error?m.message:String(m)});}let h=n.healthCheck(),g={};try{let m=n.query("SELECT key, value FROM meta");for(let p of m)g[p.key]=p.value;}catch(m){Y.debug("status: meta read failed",{error:m instanceof Error?m.message:String(m)});}return {dbPath:t.dbPath,workspaceDir:t.workspaceDir,factsCount:c,nodesCount:s,edgesCount:u,factsByCategory:d,ftsAvailable:R,vectorEnabled:I,kgScopeEnabled:f,healthy:h,meta:g}}catch(i){throw i instanceof w?i:new w(`status failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL")}finally{n.close();}}var Ht=utils.Log.create({service:"memory.service.doctor"}),ie=100*1024*1024,ce=100*1024*1024;async function $e(t,e={}){Ht.debug("doctor invoked",{agentId:t.agentId});let r=[],n=null;try{n=new chunkOIUUTVLL_cjs.e(t.dbPath),await n.initialize();let o=n.healthCheck();r.push({name:"database",passed:o,message:o?"database connected and writable":"database unhealthy",details:{dbPath:t.dbPath}});}catch(o){r.push({name:"database",passed:false,message:`database connection failed: ${o instanceof Error?o.message:String(o)}`,details:{dbPath:t.dbPath}});}try{if(!n)throw new Error("db not initialized");let o=n.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]);r.push({name:"fts",passed:o.length>0,message:o.length>0?"FTS5 index available":"FTS5 index not found",details:o.length>0?{table:o[0]?.name}:void 0});}catch(o){r.push({name:"fts",passed:false,message:`fts probe failed: ${o instanceof Error?o.message:String(o)}`});}let i=!!t.config?.embeddingLlm;r.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(!n)throw new Error("db not initialized");let o=["memory_facts","nodes","edges","meta"],s=n.query("SELECT name FROM sqlite_master WHERE type = ?",["table"]),l=new Set(s.map(d=>d.name)),u=o.filter(d=>!l.has(d));r.push({name:"schema",passed:u.length===0,message:u.length===0?`schema complete (${o.length} tables)`:`missing tables: ${u.join(", ")}`,details:{required:o,existing:Array.from(l)}});}catch(o){r.push({name:"schema",passed:false,message:`schema probe failed: ${o instanceof Error?o.message:String(o)}`});}try{let o=`${t.dbPath}-wal`,s=`${t.dbPath}-shm`,l=0,u=0;try{l=(await P__default.default.stat(o)).size;}catch{l=0;}try{u=(await P__default.default.stat(s)).size;}catch{u=0;}let d=l+u;r.push({name:"lock",passed:d<=ce,message:d<=ce?`no lock contention (wal+shm ${(d/1024).toFixed(1)} KB)`:`WAL/SHM files unusually large (${(d/1024/1024).toFixed(1)} MB > ${(ce/1024/1024).toFixed(0)} MB threshold)`,details:{walBytes:l,shmBytes:u}});}catch(o){r.push({name:"lock",passed:false,message:`lock probe failed: ${o instanceof Error?o.message:String(o)}`});}try{let o=W__default.default.dirname(t.dbPath),s=await P__default.default.statfs(o),l=typeof s.bsize=="bigint"?Number(s.bsize)*s.bavail:s.bsize*s.bavail,u=l>=ie;r.push({name:"disk_space",passed:u,message:u?`sufficient disk space (${(l/1024/1024).toFixed(1)} MB available)`:`low disk space (${(l/1024/1024).toFixed(1)} MB < ${(ie/1024/1024).toFixed(0)} MB threshold)`,details:{availableBytes:l,threshold:ie}});}catch(o){r.push({name:"disk_space",passed:false,message:`disk_space probe failed: ${o instanceof Error?o.message:String(o)}`});}try{if(!n)throw new Error("db not initialized");let o=n.agentFilter(t.agentId),s=n.query(`SELECT id, node_ids FROM memory_facts ${o.where} ${o.where?"AND":"WHERE"} node_ids IS NOT NULL`,o.params),l=[];for(let u of s)try{let d=JSON.parse(u.node_ids);if(!Array.isArray(d))continue;for(let E of d){if(typeof E!="number")continue;if((n.query("SELECT COUNT(*) as c FROM nodes WHERE id = ?",[E])[0]?.c??0)===0){l.push(`${u.id}->${E}`);break}}}catch{}r.push({name:"orphan",passed:l.length===0,message:l.length===0?"no orphan KG references":`${l.length} orphan references: ${l.slice(0,5).join(", ")}${l.length>5?", ...":""}`,details:{count:l.length}});}catch(o){r.push({name:"orphan",passed:false,message:`orphan probe failed: ${o instanceof Error?o.message:String(o)}`});}try{if(!n)throw new Error("db not initialized");let o=n.query("SELECT COUNT(*) as c FROM embedding_cache")[0],s=n.agentFilter(t.agentId),l=n.query(`SELECT COUNT(*) as c FROM memory_facts ${s.where}`,s.params)[0],u=o?.c??0,d=l?.c??0,E=Math.max(0,u-d),R=E>0;r.push({name:"embedding_cache_unused",passed:!R,severity:"info",message:R?`by design: ${E} embedding_cache rows remain after fact deletion (cache is global content-hash dedup; forget intentionally doesn't cascade clear cache to preserve same-content hit rate)`:"embedding_cache in sync with memory_facts (no unused rows)",details:{cacheCount:u,factsCount:d,unused:E,policy:"global_content_hash_dedup"}});}catch(o){r.push({name:"embedding_cache_unused",passed:false,message:`embedding_cache_unused probe failed: ${o instanceof Error?o.message:String(o)}`});}let c=r.every(o=>o.severity==="info"?true:o.passed);return n&&n.close(),{healthy:c,checks:r}}var A=utils.Log.create({service:"memory.service.init"});function Ut(t){return W__default.default.join(t,".easbot","memory.json")}function Wt(t,e={}){let r={version:1,schema_version:chunkOIUUTVLL_cjs.a,backend:"better-sqlite3",created_at:new Date().toISOString(),embedding_llm:e.embeddingLlm??null,embedding_batch_size:32,embedding_dimensions:768,graph_llm:e.graphLlm??null,entity_extraction_prompt:e.entityExtractionPrompt??null,relation_extraction_prompt:e.relationExtractionPrompt??null,tokenizer:{dictPath:["./packages/memory/src/assets/jieba_dict.txt"]},archiveDays:e.archiveDays??30,shortTermMaxRounds:e.shortTermMaxRounds??20};fs.writeFileSync(t,JSON.stringify(r,null,2),"utf-8");}async function Ue(t,e={}){let r=Date.now();x(t,"init");let n=e.workspaceDir??t.workspaceDir,i=e.dbPath??t.dbPath;if(!n||n.trim().length===0)throw new w("init requires non-empty `workspaceDir` (ctx.workspaceDir or params.workspaceDir)","CONTENT_REQUIRED");if(!i||i.trim().length===0)throw new w("init requires non-empty `dbPath` (ctx.dbPath or params.dbPath)","CONTENT_REQUIRED");let c=t.agentId?.trim()??"",o=e.force??false;A.debug("init invoked",{agentId:c,workspaceDir:n,dbPath:i,force:o});try{await P__default.default.mkdir(W__default.default.dirname(i),{recursive:!0}),await P__default.default.mkdir(W__default.default.join(n,".easbot","memory","active"),{recursive:!0}),await P__default.default.mkdir(W__default.default.join(n,"archive"),{recursive:!0}),await P__default.default.mkdir(W__default.default.join(n,".easbot"),{recursive:!0});}catch(d){throw new w(`init: failed to create directories: ${d instanceof Error?d.message:String(d)}`,"INTERNAL",{cause:d instanceof Error?d.message:String(d)})}if(o)try{await P__default.default.rm(i,{force:!0});}catch(d){A.warn("init: force rm db failed (may not exist)",{dbPath:i,error:d instanceof Error?d.message:String(d)});}let s=Ut(n),l=false;try{!await P__default.default.stat(s).then(()=>!0).catch(()=>!1)||o?(Wt(s,{embeddingLlm:t.config?.embeddingLlm?String(t.config.embeddingLlm.modelId??""):void 0,graphLlm:t.config?.graphLlm?String(t.config.graphLlm.modelId??""):void 0,archiveDays:t.config?.archiveDays,shortTermMaxRounds:t.config?.shortTermMaxRounds}),l=!0,A.info("init: memory.json written",{configPath:s,force:o,configCreated:l})):A.debug("init: memory.json already exists, skipping write",{configPath:s});}catch(d){A.warn("init: memory.json write failed (non-fatal)",{configPath:s,error:d instanceof Error?d.message:String(d)});}let u=new chunkOIUUTVLL_cjs.e(i);try{let d=await P__default.default.stat(i).then(()=>!0).catch(()=>!1);await u.initialize();let E=new Date().toISOString(),R=[["version","1.0.0"],["schemaVersion",String(chunkOIUUTVLL_cjs.a)],["createdAt",E],["defaultAgentId",c]];for(let[h,g]of R)try{u.run("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)",[h,g]);}catch(m){A.warn("init: meta insert failed",{key:h,error:m instanceof Error?m.message:String(m)});}let I=d?0:12,f=d?0:1;return A.info("init complete",{agentId:c,workspaceDir:n,dbPath:i,configPath:s,configCreated:l,schemaVersion:chunkOIUUTVLL_cjs.a,durationMs:Date.now()-r}),{initialized:!0,dbPath:i,configPath:s,configCreated:l,workspaceDir:n,tablesCreated:I,migrationsApplied:f,durationMs:Date.now()-r}}catch(d){throw new w(`init failed: ${d instanceof Error?d.message:String(d)}`,"INTERNAL",{cause:d instanceof Error?d.message:String(d)})}finally{u.close();}}var de={name:"recall",scope:"read",schema:we,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Query memory via hybrid search (FTS + vector); returns ranked facts.",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=t;if(!e.agentId?.trim())throw new Error("recall: 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},r)}};var me={name:"remember",scope:"write",schema:Re,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Persist a new self-memory fact; auto-extract entities into KG.",readOnlyHint:false,destructiveHint:false,idempotentHint:false},handler:async(t,e)=>{let r=t;if(!e.agentId?.trim())throw new Error("remember: agentId is required");return Ae({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var le={name:"forget",scope:"write",schema:Se,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Delete memory facts by id / category / time range; supports dryRun.",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let r=t;if(!e.agentId?.trim())throw new Error("forget: agentId is required");return xe({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var ue={name:"extract",scope:"write",schema:Ie,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Extract facts from a session (server-side pulls messages by lastN).",readOnlyHint:false,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=t;if(!e.agentId?.trim())throw new Error("extract: agentId is required");return Le({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var ge={name:"consolidate",scope:"admin",schema:Me,annotations:{localOnly:true,requiresAgentId:true,defaultDescription:"Run consolidation pipeline: dedup \u2192 archive.",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let r=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 ke({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},r)}};var pe={name:"graph_query",scope:"read",schema:_e,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Query KG nodes / edges / neighbors with scope filtering.",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=t,n=e.agentId?.trim()||"default";return He({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:n},r)}};var fe={name:"status",scope:"read",schema:Oe,annotations:{localOnly:false,requiresAgentId:false,defaultDescription:"Memory system status (factsCount / nodesCount / edgesCount / fts / vector).",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=t??{};return qe({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var ye={name:"doctor",scope:"admin",schema:Te,annotations:{localOnly:true,requiresAgentId:false,defaultDescription:"Run 7 health checks (database / fts / vector / schema / lock / disk_space / orphan).",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=t??{};if(!e.isTrustedLocal)throw new Error("doctor: only trusted local process can invoke this op");return $e({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},r)}};var he={name:"init",scope:"admin",schema:Ce,annotations:{localOnly:true,requiresAgentId:false,defaultDescription:"Initialize memory workspace (dirs + db schema + meta).",readOnlyHint:false,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{if(!e.isTrustedLocal)throw new Error("init: only trusted local process can invoke this op");let r=t??{};return Ue({workspaceDir:r.workspaceDir??e.workspaceDir??"",rootDir:r.workspaceDir??e.workspaceDir??"",dbPath:r.dbPath??e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId??""},r)}};var We={[de.name]:de,[me.name]:me,[le.name]:le,[ue.name]:ue,[ge.name]:ge,[pe.name]:pe,[fe.name]:fe,[ye.name]:ye,[he.name]:he},jt=Object.values(We);function Gt(t,e,r){if(t.annotations.localOnly&&!e.isTrustedLocal)throw new Error(`MEMORY:executeOp: op "${r}" is localOnly; non-trusted caller rejected`);if(t.annotations.requiresAgentId){let n=e.agentId?.trim()??"";if(n.length===0)throw new Error(`MEMORY:executeOp: op "${r}" requires agentId`);e.agentId=n;}}async function Po(t,e,r){let n=We[t];if(!n)throw new Error(`executeOp: unknown op "${t}"; available: ${jt.map(c=>c.name).join(", ")}`);return Gt(n,r,t),await n.handler(e,r)}function Bt(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 qo(t,e,r={}){let n=chunkCPRDIUQ4_cjs.j(e),i=utils.Locale.resolveLocaleLang(r.locale);return {agentId:t,dbPath:n,workspaceDir:e,rootDir:e,config:Bt({dbPath:n,workspaceDir:e}),isTrustedLocal:true,locale:i,remote:false,...r}}exports.a=v;exports.c=Ee;exports.d=we;exports.e=Re;exports.f=Se;exports.g=Ie;exports.h=Me;exports.i=_e;exports.j=Ce;exports.k=Ae;exports.l=xe;exports.m=Le;exports.n=ke;exports.o=He;exports.p=qe;exports.q=$e;exports.r=Ue;exports.s=We;exports.t=jt;exports.u=Po;exports.v=Bt;exports.w=qo;