@easbot/memory 0.3.17 → 0.3.19

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 (81) hide show
  1. package/README.en.md +101 -0
  2. package/README.md +116 -11
  3. package/dist/chunks/chunk-4GSXSIV5.cjs +1 -0
  4. package/dist/chunks/chunk-5Q6SIVSP.cjs +50 -0
  5. package/dist/chunks/chunk-6CQMBEIQ.mjs +1 -0
  6. package/dist/chunks/chunk-746FKSL5.mjs +50 -0
  7. package/dist/chunks/chunk-ARA4LMAI.mjs +1 -0
  8. package/dist/chunks/chunk-CN6WBJLX.mjs +60 -0
  9. package/dist/chunks/{chunk-OIUUTVLL.cjs → chunk-EGWJG65Q.cjs} +22 -4
  10. package/dist/chunks/chunk-J5XF2W4Z.cjs +1 -0
  11. package/dist/chunks/chunk-JDPZ5U53.mjs +71 -0
  12. package/dist/chunks/chunk-QHPGDNEG.cjs +1 -0
  13. package/dist/chunks/{chunk-MWRDF6VN.mjs → chunk-QYBWHFOX.mjs} +1 -1
  14. package/dist/chunks/chunk-SWYQLQ7Z.mjs +1 -0
  15. package/dist/chunks/chunk-WQB4D6DZ.cjs +1 -0
  16. package/dist/chunks/chunk-X66LENNV.cjs +60 -0
  17. package/dist/chunks/cli-handler-CN4Q7BCY.mjs +1 -0
  18. package/dist/chunks/cli-handler-IRPYADZF.cjs +1 -0
  19. package/dist/chunks/consolidate-PUOAAQN3.cjs +2 -0
  20. package/dist/chunks/consolidate-UEYNLKQN.mjs +2 -0
  21. package/dist/chunks/doctor-KPAZWVVZ.mjs +1 -0
  22. package/dist/chunks/doctor-U4HOSXGW.cjs +1 -0
  23. package/dist/chunks/extract-7FFIDVG3.cjs +2 -0
  24. package/dist/chunks/extract-EOZJMLTP.mjs +2 -0
  25. package/dist/chunks/{forget-A4UJI3LE.mjs → forget-5AXV3GHW.mjs} +1 -1
  26. package/dist/chunks/forget-GBMYCUPJ.cjs +3 -0
  27. package/dist/chunks/graph-KOJYJTA4.cjs +3 -0
  28. package/dist/chunks/{graph-XZ46LEO7.mjs → graph-Y6AYRFCN.mjs} +1 -1
  29. package/dist/chunks/init-B24TNUSD.cjs +1 -0
  30. package/dist/chunks/init-HGEBZTJW.mjs +1 -0
  31. package/dist/chunks/llm-RMPVWEVP.cjs +1 -0
  32. package/dist/chunks/llm-UHTBU2HA.mjs +1 -0
  33. package/dist/chunks/{mcp-BOD4ZOZS.mjs → mcp-BMAB3TT7.mjs} +1 -1
  34. package/dist/chunks/{mcp-BXVXTUJK.cjs → mcp-BS6XHEBR.cjs} +1 -1
  35. package/dist/chunks/recall-LKETADTB.cjs +2 -0
  36. package/dist/chunks/recall-UPGGKBNX.mjs +2 -0
  37. package/dist/chunks/remember-KCQN2UWN.mjs +2 -0
  38. package/dist/chunks/remember-VZF4O7ZF.cjs +2 -0
  39. package/dist/chunks/status-2BFVXY5J.cjs +1 -0
  40. package/dist/chunks/status-HGN2YLKJ.mjs +1 -0
  41. package/dist/chunks/stdio-server-GABA2MLR.cjs +1 -0
  42. package/dist/chunks/stdio-server-JPMLMEWY.mjs +1 -0
  43. package/dist/chunks/sync-7Y2DEDDW.mjs +2 -0
  44. package/dist/chunks/sync-W5A2O5TS.cjs +2 -0
  45. package/dist/cli.cjs +1 -1
  46. package/dist/cli.mjs +1 -1
  47. package/dist/index.cjs +4 -4
  48. package/dist/index.d.cts +87 -38
  49. package/dist/index.d.ts +87 -38
  50. package/dist/index.mjs +4 -4
  51. package/package.json +9 -8
  52. package/dist/chunks/chunk-BSKFK4RC.mjs +0 -1
  53. package/dist/chunks/chunk-DFWC6WII.mjs +0 -53
  54. package/dist/chunks/chunk-DXU5WPK3.cjs +0 -42
  55. package/dist/chunks/chunk-EECBJNZI.mjs +0 -59
  56. package/dist/chunks/chunk-FMEXQ5YE.cjs +0 -59
  57. package/dist/chunks/chunk-HSK27DQ7.cjs +0 -1
  58. package/dist/chunks/chunk-I6XVFDN2.mjs +0 -42
  59. package/dist/chunks/chunk-QNDG7BTB.cjs +0 -1
  60. package/dist/chunks/chunk-RSJ2KT6X.cjs +0 -1
  61. package/dist/chunks/chunk-TPSRK4M3.mjs +0 -1
  62. package/dist/chunks/cli-handler-6VTKYXXM.mjs +0 -1
  63. package/dist/chunks/cli-handler-HNPA3STD.cjs +0 -1
  64. package/dist/chunks/consolidate-6P7LUPPL.cjs +0 -2
  65. package/dist/chunks/consolidate-NYH4IKJK.mjs +0 -2
  66. package/dist/chunks/doctor-IJJ5UYGT.cjs +0 -2
  67. package/dist/chunks/doctor-MZSZGVRL.mjs +0 -2
  68. package/dist/chunks/extract-6B7OD3VK.mjs +0 -2
  69. package/dist/chunks/extract-ERTOHQV6.cjs +0 -2
  70. package/dist/chunks/forget-KLFM5SBQ.cjs +0 -3
  71. package/dist/chunks/graph-P5ZHB4ZM.cjs +0 -3
  72. package/dist/chunks/init-CCOSHE3F.cjs +0 -3
  73. package/dist/chunks/init-WEPU32KF.mjs +0 -3
  74. package/dist/chunks/recall-BV4Z7HUJ.mjs +0 -2
  75. package/dist/chunks/recall-FEINUJKO.cjs +0 -2
  76. package/dist/chunks/remember-ESVRA73C.mjs +0 -2
  77. package/dist/chunks/remember-YNSY2JJB.cjs +0 -2
  78. package/dist/chunks/status-KVM7I6YC.cjs +0 -2
  79. package/dist/chunks/status-QQZS3ZCN.mjs +0 -2
  80. package/dist/chunks/stdio-server-MQKTUGNG.cjs +0 -1
  81. package/dist/chunks/stdio-server-ZLMSUTC5.mjs +0 -1
package/README.en.md CHANGED
@@ -178,6 +178,107 @@ easbot-memory mcp
178
178
 
179
179
  > Since v0.4.1: `--agent` is **optional** for `init` / `status` / `doctor` / `graph` (defaults to `'default'`), letting CLI / one-shot diagnostic calls run without an agent context. The remaining 5 ops (`recall` / `remember` / `forget` / `extract` / `consolidate`) still require an explicit `--agent`; missing values return a non-zero exit code.
180
180
 
181
+ ## Status / Doctor Unified Output Format (Decision 0073 / CLI Spec v1.4)
182
+
183
+ `memory status` / `memory doctor` share the same rendering as `codebase` / `note` via `@easbot/terminal`'s `formatKnowledgeStatus` / `formatKnowledgeDoctor`, ensuring consistent visual and field structure across all three packages.
184
+
185
+ ### Status Output Example
186
+
187
+ ```bash
188
+ $ easbot memory status
189
+ ─ memory status ───────────────────────────────────────────────────
190
+ Root directory E:/work/my-project
191
+ Config ✓ E:/work/my-project/.easbot/memory.json
192
+ DB ✓ E:/work/my-project/.easbot/db/memory.db (5242880 bytes)
193
+ Index state ready
194
+ Schema version 1
195
+ Extraction version 1
196
+ Backend better-sqlite3
197
+ Last sync 2026-08-31T14:23:11.000Z
198
+ Vector enabled ✓
199
+ Embedding dims 1536
200
+ LLM:
201
+ Initialized ✓
202
+ Provider openai
203
+ Capabilities:
204
+ Embedding ✓ text-embedding-3-small
205
+ Graph LLM ✓ gpt-4o-mini
206
+ Rerank LLM ✗
207
+ Counts:
208
+ facts 256
209
+ agent_only 180
210
+ shared_only 42
211
+ both 34
212
+ Healthy ✓
213
+ ```
214
+
215
+ ### Doctor Output Example
216
+
217
+ ```bash
218
+ $ easbot memory doctor
219
+ ─ memory doctor ───────────────────────────────────────────────────
220
+ Healthy ✓
221
+ Duration 98 ms
222
+ Backend availability:
223
+ - better-sqlite3 ✓
224
+ - node:sqlite ✗
225
+ - @tursodatabase/database ✗
226
+ DB stats:
227
+ page_count 320
228
+ page_size 4096
229
+ freelist_count 0
230
+ Checks 10 total (0 error, 0 warn, 1 info, 9 ok)
231
+ [ok] ✓ database: database file exists and accessible (12 ms)
232
+ [ok] ✓ fts: FTS5 available (8 ms)
233
+ [ok] ✓ vector: vector index usable (23 ms)
234
+ [ok] ✓ schema: schema version matches (2 ms)
235
+ [ok] ✓ lock: no lock contention (1 ms)
236
+ [ok] ✓ disk_space: sufficient (156 MB free) (3 ms)
237
+ [ok] ✓ orphan: no orphan records (18 ms)
238
+ [info] ℹ llm: LLM reachable (ping 42 ms) (42 ms)
239
+ [ok] ✓ embedding_cache_unused: no unused embedding cache entries (5 ms)
240
+ [ok] ✓ embedding_dims_consistency: meta=1536 probe=1536 config=1536 (35 ms)
241
+ ```
242
+
243
+ ### Key Fields
244
+
245
+ | Field | Description |
246
+ |-------|-------------|
247
+ | `LLM.initialized` | Whether LLM is initialized (valid config + reachable) |
248
+ | `LLM.capabilities` | Three capabilities: `embedding` / `graphLlm` / `rerankLlm`, each shows model name or ✗ |
249
+ | `Vector enabled` | Whether vector index is enabled |
250
+ | `Embedding dims` | **Probed** embedding dimension (not just from config), probed at status end and written back to meta table |
251
+ | `embedding_dims_consistency` | Doctor check #9: compares meta / probe / config dimensions for consistency |
252
+ | `factsByCategory` | Memory unique: fact counts by category (shown in Counts section) |
253
+
254
+ ### JSON Output (`--json`)
255
+
256
+ ```bash
257
+ $ easbot memory status --json
258
+ {
259
+ "ok": true,
260
+ "data": {
261
+ "rootDir": "E:/work/my-project",
262
+ "configExists": true,
263
+ "dbExists": true,
264
+ "indexState": "ready",
265
+ "schemaVersion": 1,
266
+ "llm": {
267
+ "initialized": true,
268
+ "capabilities": { "embedding": true, "graphLlm": true, "rerankLlm": false },
269
+ "embeddingModel": "text-embedding-3-small",
270
+ "graphModel": "gpt-4o-mini",
271
+ "providerId": "openai"
272
+ },
273
+ "counts": { "facts": 256, "agent_only": 180, "shared_only": 42, "both": 34 },
274
+ "healthy": true
275
+ },
276
+ "meta": { "scope": "all" }
277
+ }
278
+ ```
279
+
280
+ Compatible with [CLI Output Spec v1.4](file:///e:/work/apps/eas/easbot/docs/spec/cli-output-spec.md) / [Decision 0040](file:///e:/work/apps/eas/easbot/docs/decisions/0040-cli-output-unified-json.md).
281
+
181
282
  ### Agent delegation (v0.4 stage 4)
182
283
 
183
284
  ```bash
package/README.md CHANGED
@@ -6,10 +6,10 @@ EASBOT 生态系统的长期记忆管理库(v0.4.0)。提供分层记忆、K
6
6
 
7
7
  ## 特性(v0.4.0)
8
8
 
9
- - **9 op 统一入口**:`recall / remember / forget / extract / consolidate / graph_query / status / doctor / init`,MCP / CLI / Agent Tool 三端共享。
9
+ - **10 op 统一入口**(ADR 0069 +1 sync):`recall / remember / forget / extract / consolidate / sync / graph_query / status / doctor / init`,MCP / CLI / Agent Tool 三端共享。
10
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
11
  - **分层记忆**:短期 / 可写自记忆 / 历史长期记忆三层,**混合搜索**(FTS + 向量 + 图)。
12
- - **可观测性**:9 op 全部走 `Log.create({ service })` 英文结构化日志;`status` / `doctor` 提供离线诊断。
12
+ - **可观测性**:10 op 全部走 `Log.create({ service })` 英文结构化日志;`status` / `doctor` 提供离线诊断。
13
13
  - **i18n**:`zh-CN` / `en-US` 双 locale;`@easbot/memory` API 日志保持英文,文案走 `t()`。
14
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
15
  - **三包统一后台支撑**(决策 0036 / 0049 / 0051 / 0052):database 走 `@easbot/database` `createSyncSqliteConnection`;MCP 走 `@easbot/mcp` `ToolRegistry` + `createAndStartStdioServer`;CLI 输出走 `@easbot/terminal` `printHuman` + `emitJsonOk` + `COMMANDS_HELP` 单一数据源。
@@ -116,6 +116,7 @@ const md = await renderOperationMarkdown('recall', recallResult, { toolName: 'me
116
116
  | `forget` | ❌ | ✅ 必填 | 按 factId / category / 时间窗删除(支持 `dryRun`) |
117
117
  | `extract` | ❌ | ✅ 必填 | 从 session 抽取 facts |
118
118
  | `consolidate` | ✅ | ✅ 必填 | 整理 / 去重 / 摘要 |
119
+ | `sync` | ✅ | ✅ 必填 | db → .md 兜底生成(幂等)+ active/ 过期文件归档(默认 30 天) |
119
120
  | `graph_query` | ❌ (scope=both 时 ✅) | ⚠️ optional,缺省 `'default'` | KG 节点 / 边 / 邻居查询 |
120
121
  | `status` | ❌ | ⚠️ optional,缺省全局聚合 | 系统状态快照 |
121
122
  | `doctor` | ✅ | ⚠️ optional,缺省全库扫描 | 数据完整性检查(支持 `repair`) |
@@ -169,12 +170,114 @@ easbot-memory remember --content <text> --category <c> --importance <1-10> --age
169
170
  easbot-memory forget --agent <id> [--fact-id <id>] [--dry-run]
170
171
  easbot-memory extract --session <sessionId> [--last-n <n>] --agent <id>
171
172
  easbot-memory consolidate --agent <id> [--window-days <n>]
173
+ easbot-memory sync --agent <id> [--window-days <n>] [--dry-run] [--json]
172
174
  easbot-memory graph --kind <nodes|edges|neighbors> [--query <q>] [--agent <id>]
173
175
  easbot-memory config [--json]
174
176
  easbot-memory mcp
175
177
  ```
176
178
 
177
- > v0.4.1 起:`init` / `status` / `doctor` / `graph` 的 `--agent` 为可选,缺省时 fallback 到 `'default'`(CLI / 一次性诊断场景无需 agent 上下文);其余 5 op(`recall` / `remember` / `forget` / `extract` / `consolidate`)仍要求显式 `--agent`,缺失时返回非 0 退出码。
179
+ ## Status / Doctor 统一输出格式(决策 0073 / CLI 规范 v1.4)
180
+
181
+ `memory status` / `memory doctor` 与 `codebase` / `note` 三包统一走 `@easbot/terminal` 的 `formatKnowledgeStatus` / `formatKnowledgeDoctor` 渲染,视觉与字段结构完全一致。
182
+
183
+ ### status 输出示例
184
+
185
+ ```bash
186
+ $ easbot memory status
187
+ ─ memory status ───────────────────────────────────────────────────
188
+ Root directory E:/work/my-project
189
+ Config ✓ E:/work/my-project/.easbot/memory.json
190
+ DB ✓ E:/work/my-project/.easbot/db/memory.db (5242880 bytes)
191
+ Index state ready
192
+ Schema version 1
193
+ Extraction version 1
194
+ Backend better-sqlite3
195
+ Last sync 2026-08-31T14:23:11.000Z
196
+ Vector enabled ✓
197
+ Embedding dims 1536
198
+ LLM:
199
+ Initialized ✓
200
+ Provider openai
201
+ Capabilities:
202
+ Embedding ✓ text-embedding-3-small
203
+ Graph LLM ✓ gpt-4o-mini
204
+ Rerank LLM ✗
205
+ Counts:
206
+ facts 256
207
+ agent_only 180
208
+ shared_only 42
209
+ both 34
210
+ Healthy ✓
211
+ ```
212
+
213
+ ### doctor 输出示例
214
+
215
+ ```bash
216
+ $ easbot memory doctor
217
+ ─ memory doctor ───────────────────────────────────────────────────
218
+ Healthy ✓
219
+ Duration 98 ms
220
+ Backend availability:
221
+ - better-sqlite3 ✓
222
+ - node:sqlite ✗
223
+ - @tursodatabase/database ✗
224
+ DB stats:
225
+ page_count 320
226
+ page_size 4096
227
+ freelist_count 0
228
+ Checks 10 total (0 error, 0 warn, 1 info, 9 ok)
229
+ [ok] ✓ database: database file exists and accessible (12 ms)
230
+ [ok] ✓ fts: FTS5 available (8 ms)
231
+ [ok] ✓ vector: vector index usable (23 ms)
232
+ [ok] ✓ schema: schema version matches (2 ms)
233
+ [ok] ✓ lock: no lock contention (1 ms)
234
+ [ok] ✓ disk_space: sufficient (156 MB free) (3 ms)
235
+ [ok] ✓ orphan: no orphan records (18 ms)
236
+ [info] ℹ llm: LLM reachable (ping 42 ms) (42 ms)
237
+ [ok] ✓ embedding_cache_unused: no unused embedding cache entries (5 ms)
238
+ [ok] ✓ embedding_dims_consistency: meta=1536 probe=1536 config=1536 (35 ms)
239
+ ```
240
+
241
+ ### 关键字段说明
242
+
243
+ | 字段 | 说明 |
244
+ |------|------|
245
+ | `LLM.initialized` | LLM 是否已初始化(配置有效且可达) |
246
+ | `LLM.capabilities` | 三大能力:`embedding` / `graphLlm` / `rerankLlm`,各显示模型名或 ✗ |
247
+ | `Vector enabled` | 向量索引是否启用 |
248
+ | `Embedding dims` | **实测** embedding 维度(非仅读 config),status 末尾探测并回填 meta 表 |
249
+ | `embedding_dims_consistency` | doctor 第 9 项检查:对比 meta / probe / config 三方维度是否一致 |
250
+ | `factsByCategory` | memory 独有:按 category 统计的 fact 数量(Counts 段展示) |
251
+
252
+ ### JSON 输出(`--json`)
253
+
254
+ ```bash
255
+ $ easbot memory status --json
256
+ {
257
+ "ok": true,
258
+ "data": {
259
+ "rootDir": "E:/work/my-project",
260
+ "configExists": true,
261
+ "dbExists": true,
262
+ "indexState": "ready",
263
+ "schemaVersion": 1,
264
+ "llm": {
265
+ "initialized": true,
266
+ "capabilities": { "embedding": true, "graphLlm": true, "rerankLlm": false },
267
+ "embeddingModel": "text-embedding-3-small",
268
+ "graphModel": "gpt-4o-mini",
269
+ "providerId": "openai"
270
+ },
271
+ "counts": { "facts": 256, "agent_only": 180, "shared_only": 42, "both": 34 },
272
+ "healthy": true
273
+ },
274
+ "meta": { "scope": "all" }
275
+ }
276
+ ```
277
+
278
+ 兼容 [CLI 输出规范 v1.4](file:///e:/work/apps/eas/easbot/docs/spec/cli-output-spec.md) / [决策 0040](file:///e:/work/apps/eas/easbot/docs/decisions/0040-cli-output-unified-json.md)。
279
+
280
+ > v0.4.1 起:`init` / `status` / `doctor` / `graph` 的 `--agent` 为可选,缺省时 fallback 到 `'default'`(CLI / 一次性诊断场景无需 agent 上下文);其余 6 op(`recall` / `remember` / `forget` / `extract` / `consolidate` / `sync`)仍要求显式 `--agent`,缺失时返回非 0 退出码。
178
281
 
179
282
  ### Agent 委派模式(v0.4 stage 4 T-M017a)
180
283
 
@@ -198,13 +301,13 @@ await MemoryStdioServer.start({
198
301
  description: 'EASBot memory MCP server',
199
302
  });
200
303
 
201
- // 列出 9 个 tool 名
304
+ // 列出 10 个 tool 名(ADR 0069 +1 sync)
202
305
  const tools = MemoryStdioServer.getToolNames();
203
- // ['memory_recall', 'memory_remember', 'memory_forget', ...]
306
+ // ['memory_recall', 'memory_remember', 'memory_forget', 'memory_extract', 'memory_consolidate', 'memory_sync', 'memory_graph_query', 'memory_status', 'memory_doctor', 'memory_init']
204
307
  ```
205
308
 
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`
309
+ **10 tool 清单**(与 `OP_REGISTRY` 一一对应):
310
+ - `memory_recall` / `memory_remember` / `memory_forget` / `memory_extract` / `memory_consolidate` / `memory_sync` / `memory_graph_query` / `memory_status` / `memory_doctor` / `memory_init`
208
311
 
209
312
  ### handleMemoryCli 委派范式
210
313
 
@@ -232,16 +335,17 @@ if (result.code !== 0) process.exit(result.code);
232
335
  - 二次开发:未来 `note` 工具可通过 file watcher 检测 memory .md 变化触发 cross-reference 更新
233
336
  - 灾备:file 失败**不阻塞** db 写入(与 v0.3 行为一致)
234
337
 
235
- ### 路径格式
338
+ ### 路径格式(v0.5.1+ 老侯 2026-08-23 反馈修正)
236
339
 
237
340
  ```
238
- {workspaceDir}/.easbot/knowledge/memory/{category}/{YYYY-MM}/mem_{id}.md
341
+ {workspaceDir}/.easbot/memory/active/{category}/{YYYY-MM-DD}.md
239
342
  ```
240
343
 
241
344
  - 按 **category** 分目录(`task_context` / `workflow` / `user_preference` / ...)
242
- - 按 **createdAt 月份**分目录(避免单月文件过多)
243
- - 文件名 = `fact.id`(全局唯一)
345
+ - 按 **createdAt 本地日期**分文件(一日一文件,append 模式,多 fact 共享)
346
+ - 文件名 = `{YYYY-MM-DD}.md`(不再含 fact.id)
244
347
  - `memory_facts.file_path` 列存**相对 workspaceDir 的 POSIX 路径**
348
+ - 归档路径(ADR 0069 sync):`{workspaceDir}/.easbot/memory/archive/{YYYY-MM}/{category}/{YYYY-MM-DD}.md`(扁平结构)
245
349
 
246
350
  ### Markdown 模板
247
351
 
@@ -299,6 +403,7 @@ const { ok, absPath } = await factFileSync.delete(fact, '/path/to/workspace');
299
403
 
300
404
  ## 决策与迁移
301
405
 
406
+ - ADR 0069(v0.5+ memory sync op:两阶段流水线 —— db → .md 兜底生成(幂等)+ active/ 过期归档):`docs/decisions/0069-memory-sync-op.md`
302
407
  - 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
408
  - ADR 0060(v0.5+ fact → .md 同步恢复):`docs/decisions/0060-memory-fact-file-sync-restore.md`
304
409
  - ADR 0055 / 0056 / 0057(v0.4 决策):`.easbot/protocol.json` 与 `docs/decisions/00NN-*.md`
@@ -0,0 +1 @@
1
+ 'use strict';var chunkWQB4D6DZ_cjs=require('./chunk-WQB4D6DZ.cjs');function o(r,t){return chunkWQB4D6DZ_cjs.a(`memory.${r}.empty`,{fallback:t})}function s(r,t,m){return chunkWQB4D6DZ_cjs.a(`memory.${r}.summary`,{vars:t,fallback:m})}function g(r,t,m){return chunkWQB4D6DZ_cjs.a(`memory.${r}.item`,{vars:t,fallback:m})}exports.a=o;exports.b=s;exports.c=g;
@@ -0,0 +1,50 @@
1
+ 'use strict';var chunkEGWJG65Q_cjs=require('./chunk-EGWJG65Q.cjs'),chunkCPRDIUQ4_cjs=require('./chunk-CPRDIUQ4.cjs'),chunkJ5XF2W4Z_cjs=require('./chunk-J5XF2W4Z.cjs'),chunkNVGACA7W_cjs=require('./chunk-NVGACA7W.cjs'),utils=require('@easbot/utils'),zod=require('zod'),crypto=require('crypto'),llm=require('@easbot/llm'),G=require('fs/promises'),ce=require('path'),fs=require('fs'),module$1=require('module'),types=require('@easbot/types');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var G__default=/*#__PURE__*/_interopDefault(G);var ce__default=/*#__PURE__*/_interopDefault(ce);var me=utils.Log.create({service:"memory.graph-store"}),J=class{constructor(e){chunkNVGACA7W_cjs.a(this,"db");this.db=e;}async upsertNode(e,n,r,o){let c=Date.now(),s=JSON.stringify(r??{}),i=this.db.prepare("SELECT id FROM nodes WHERE name = ? AND type = ? LIMIT 1").get(e,n);if(i)return this.db.prepare("UPDATE nodes SET properties = ?, updatedAt = ? WHERE id = ?").run(s,c,i.id),i.id;let p=this.db.prepare("INSERT INTO nodes (name, type, properties, owner_agent_id, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)").run(e,n,s,o??null,c,c);return Number(p.lastInsertRowid)}async deleteNode(e){this.db.prepare("DELETE FROM nodes WHERE id = ?").run(e);}async upsertEdge(e,n,r,o){let c=this.db.prepare("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)").run(e,n,r,JSON.stringify(o??{}),Date.now());return Number(c.lastInsertRowid)}async queryNodes(e={}){let n="SELECT id, name, type, properties, owner_agent_id, createdAt, updatedAt FROM nodes",r=[],o=[];if(e.ids&&e.ids.length>0){let s=e.ids.map(i=>typeof i=="string"?parseInt(i,10):i).filter(i=>!Number.isNaN(i));o.push(`id IN (${s.map(()=>"?").join(", ")})`),r.push(...s);}e.name&&(o.push("name LIKE ?"),r.push(`%${e.name}%`)),e.type&&(o.push("type = ?"),r.push(e.type)),ut(o,r,e.agentId,e.scope??"agent_only"),o.length>0&&(n+=` WHERE ${o.join(" AND ")}`),n+=" ORDER BY id",e.limit&&(n+=" LIMIT ?",r.push(e.limit)),me.debug("queryNodes",{sql:n,params:r,filter:e});let c=this.db.prepare(n).all(...r);return me.debug("queryNodes result",{count:c.length}),c.map(s=>({id:s.id,name:s.name,type:s.type,properties:s.properties?JSON.parse(s.properties):void 0,createdAt:s.createdAt,updatedAt:s.updatedAt,ownerAgentId:s.owner_agent_id}))}async queryEdges(e={}){let n="SELECT e.id, e.source, e.target, e.relation, e.properties, e.createdAt FROM edges e",r=[],o=[];if(e.ids&&e.ids.length>0&&(o.push(`e.id IN (${e.ids.map(()=>"?").join(", ")})`),r.push(...e.ids)),e.source!==void 0&&(o.push("e.source = ?"),r.push(e.source)),e.target!==void 0&&(o.push("e.target = ?"),r.push(e.target)),e.sourceOrTarget&&e.sourceOrTarget.length>0){let f=e.sourceOrTarget.map(m=>typeof m=="string"?parseInt(m,10):m).filter(m=>!Number.isNaN(m));o.push(`(e.source IN (${f.map(()=>"?").join(", ")}) OR e.target IN (${f.map(()=>"?").join(", ")}))`),r.push(...f,...f);}e.relation&&(o.push("e.relation = ?"),r.push(e.relation)),o.length>0&&(n+=` WHERE ${o.join(" AND ")}`),n+=" ORDER BY e.id",e.limit&&(n+=" LIMIT ?",r.push(e.limit)),me.debug("queryEdges",{sql:n,params:r,filter:e});let c=this.db.prepare(n).all(...r);me.debug("queryEdges result",{count:c.length});let s=[...new Set(c.map(f=>f.target))],i=s.length>0?await this.queryNodes({ids:s,limit:s.length}):[],p=new Map(i.map(f=>[f.id,f]));return c.map(f=>{let m={id:f.id,source:f.source,target:f.target,relation:f.relation,properties:f.properties?JSON.parse(f.properties):void 0,createdAt:f.createdAt},u=p.get(f.target);return u&&(m.targetNode=u),m})}async queryNeighbors(e,n=1,r){let o=r?.agentId,c=r?.scope??"agent_only",s=new Set,i=[{id:e,level:0}],p=[],f=r?.maxEdgesPerNode??50;for(;i.length>0;){let m=i.shift();if(!m)break;if(s.has(m.id)||m.level>n)continue;s.add(m.id);let I=(await this.queryNodes({ids:[m.id],limit:1,agentId:o,scope:c}))[0];if(!I)continue;let v=await this.queryEdges({sourceOrTarget:[m.id],limit:f}),S=o?await lt(this,v,o,c):v;if(p.push({...I,edges:S}),m.level<n)for(let w of S){let h=w.source===m.id?w.target:w.source;s.has(h)||i.push({id:h,level:m.level+1});}}return p}};async function lt(t,e,n,r){if(e.length===0)return e;let o=new Set;for(let i of e)o.add(i.source),o.add(i.target);let c=await t.queryNodes({ids:Array.from(o),agentId:n,scope:r,limit:o.size}),s=new Set(c.map(i=>i.id));return e.filter(i=>s.has(i.source)&&s.has(i.target))}function ut(t,e,n,r){if(n)switch(r){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 M=class extends Error{constructor(n,r,o){super(n);chunkNVGACA7W_cjs.a(this,"code",r);chunkNVGACA7W_cjs.a(this,"details",o);this.name="ServiceError";}};var le=class extends M{constructor(){super("ctx.agentId is required for memory service (ADR 0055 per-agent isolation)","AGENT_ID_REQUIRED");}},te=class extends M{constructor(e,n){super(`Trust denied for operation "${e}": ${n}`,"TRUST_DENIED",{operation:e,reason:n});}},re=class extends M{constructor(e,n){super(`Memory ${e} has ${n} references (force=false)`,"HAS_REFERENCES",{memoryId:e,referenceCount:n});}},ne=class extends M{constructor(e){super(`dryRun mode: ${e} memories matched but not deleted`,"DRY_RUN_NO_DELETE",{matchedCount:e});}},oe=class extends M{constructor(e,n){super(`Matched ${e} memories exceeds maxDelete=${n}`,"MAX_DELETE_EXCEEDED",{matched:e,maxDelete:n});}};function H(t){if(typeof t.agentId!="string"||t.agentId.trim().length===0)throw new le}function j(t,e){if(t.remote!==false)throw new te(e,"requires trusted local caller (CLI / agent tool / MCP with remote=false)")}function ue(t,e,n){if(e!=="agent_only"&&t.remote!==false)throw new te(n,`scope="${e}" requires trusted local caller (cross-agent access denied)`)}function ge(t){if(!t.dbPath||t.dbPath.trim().length===0)throw new M("service ctx.dbPath is required (MemoryKnowledgeConfigWithModels.database.path)","INTERNAL")}var ae=utils.Log.create({service:"memory.service.recall"});async function Fe(t,e){let n=Date.now();if(H(t),ge(t),!e.query||e.query.trim().length===0)throw new M("recall requires non-empty `query`","CONTENT_REQUIRED");let r=e.includeShared?"both":"agent_only";e.includeGraph&&ue(t,r,"recall"),ae.debug("recall invoked",{agentId:t.agentId,query:e.query,category:e.category,maxResults:e.maxResults,includeGraph:e.includeGraph,scope:r});let o=e.maxResults??10,c=e.minScore??0,s=[],i=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await i.initialize();let p=chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().embedding===!0,f=await pt(i,t.agentId,e.query,{category:e.category,minImportance:e.minImportance,fromTime:e.fromTime,toTime:e.toTime,limit:o,minScore:c,hasEmbedding:p}),m;if(e.includeGraph&&f.length>0)try{let I=new J(i.getDb()),v=e.depth??1,S=f.flatMap(y=>(y.nodes??[]).map(E=>E.id)).slice(0,5),w=new Set,h=new Map;for(let y of S){let E=await I.queryNeighbors(y,v,{agentId:t.agentId,scope:r,maxEdgesPerNode:10});for(let _ of E)w.add(_.id),h.set(_.id,_.edges??[]);}let b=w.size>0?i.query(`SELECT id, name, type FROM nodes WHERE id IN (${Array.from(w).map(()=>"?").join(",")})`,Array.from(w)):[],R=Array.from(h.values()).flat();m={nodes:b.map(y=>({id:y.id,name:y.name,type:y.type,createdAt:"",updatedAt:""})),edges:R};}catch(I){let v=I instanceof Error?I.message:String(I);ae.warn("recall: KG neighbor query failed",{error:v}),s.push(`kg_neighbor_query_failed: ${v}`),m={nodes:[],edges:[]};}let u=Date.now()-n;return {hits:f,total:f.length,truncated:f.length>=o,durationMs:u,graph:m,...s.length>0?{warnings:s}:{}}}catch(p){throw p instanceof M?p:new M(`recall failed: ${p instanceof Error?p.message:String(p)}`,"INTERNAL",{cause:p instanceof Error?p.message:String(p)})}finally{i.close();}}async function pt(t,e,n,r){let o=["mf.agent_id = ?"],c=[e];r.category&&(o.push("mf.category = ?"),c.push(r.category)),r.minImportance!==void 0&&(o.push("mf.importance >= ?"),c.push(r.minImportance)),r.fromTime&&(o.push("mf.created_at >= ?"),c.push(r.fromTime)),r.toTime&&(o.push("mf.created_at <= ?"),c.push(r.toTime));let s=o.join(" AND "),i=null;if(r.hasEmbedding)try{i=await chunkJ5XF2W4Z_cjs.a.embedText(n);}catch(g){ae.warn("recall: query embedding failed, falling back to FTS-only",{error:g instanceof Error?g.message:String(g)}),i=null;}let p=Math.max(r.limit*100,1e3),[f,m]=await Promise.all([i?ft(t,i,s,c,p):Promise.resolve([]),yt(t,n,s,c,r.limit)]),u=i?.7:0,I=i?.3:1,v=u+I,S=u/v,w=I/v,h=new Map;for(let g of f)h.set(g.id,g.score*S);for(let g of m)h.set(g.id,(h.get(g.id)??0)+g.score*w);let b=Array.from(h.entries()).sort((g,k)=>k[1]-g[1]).map(([g])=>g).slice(0,r.limit);if(b.length===0)return [];let R=b.map(()=>"?").join(","),y=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 (${R})`,b),E=Date.now();return y.map(g=>{let k=h.get(g.id)??0,O=(E-new Date(g.createdAt).getTime())/864e5,F=Math.exp(-0.05*O),W=(g.importance-1)/9,B=.4*k+.3*F+.3*W;return {memoryId:g.id,category:g.category,importance:g.importance,agentId:g.agentId,snippet:g.snippet,score:B,createdAt:g.createdAt,source:g.source,filePath:g.filePath??void 0,nodes:void 0}}).filter(g=>g.score>=r.minScore).sort((g,k)=>k.score-g.score)}function ft(t,e,n,r,o){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 ${n}
16
+ LIMIT ?`,[...r,o]).map(s=>{let i=new Float32Array(s.embedding.buffer,s.embedding.byteOffset,s.embedding.byteLength/4);return {id:s.id,score:ht(e,i)}}).sort((s,i)=>i.score-s.score)}catch(c){if(c instanceof M)throw c;return ae.warn("vector search failed, falling back to FTS-only",{error:c instanceof Error?c.message:String(c)}),[]}}function yt(t,e,n,r,o){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 ${n} AND memory_facts_fts MATCH ?
20
+ ORDER BY score DESC
21
+ LIMIT ?`,[...r,bt(e),o]);if(c.length===0)return [];let s=Math.max(...c.map(i=>Math.abs(i.score)),1);return c.map(i=>({id:i.id,score:1-Math.abs(i.score)/s})).filter(i=>i.score>=0)}catch(c){if(c instanceof M)throw c;return ae.warn("FTS search failed, returning empty result",{err:c instanceof Error?c.message:String(c)}),[]}}function ht(t,e){if(t.length!==e.length||t.length===0)return 0;let n=0,r=0,o=0;for(let s=0;s<t.length;s++){let i=t[s]??0,p=e[s]??0;n+=i*p,r+=i*i,o+=p*p;}let c=Math.sqrt(r)*Math.sqrt(o);return c===0?0:Math.max(0,n/c)}function bt(t){return t.trim().split(/\s+/).filter(e=>e.length>0).map(e=>`"${e.replace(/"/g,'""')}"`).join(" ")}var qe=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 $e=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 He=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 Ue=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 We=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 je=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 Ge=zod.z.object({}).optional();zod.z.object({dbPath:zod.z.string(),workspaceDir:zod.z.string(),factsCount:zod.z.number(),nodesCount:zod.z.number(),edgesCount:zod.z.number(),factsByCategory:zod.z.record(zod.z.string(),zod.z.number()),ftsAvailable:zod.z.boolean(),vectorEnabled:zod.z.boolean(),kgScopeEnabled:zod.z.boolean(),healthy:zod.z.boolean(),meta:zod.z.record(zod.z.string(),zod.z.string())});var ze=zod.z.object({}).optional();zod.z.object({healthy:zod.z.boolean(),checks:zod.z.array(zod.z.object({name:zod.z.string(),passed:zod.z.boolean(),message:zod.z.string(),details:zod.z.record(zod.z.string(),zod.z.unknown()).optional()}))});var Be=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 Qe=zod.z.object({windowDays:zod.z.number().int().min(1).max(3650).optional(),dryRun:zod.z.boolean().optional().default(false)});zod.z.object({generatedCount:zod.z.number(),skippedCount:zod.z.number(),failedGenerateCount:zod.z.number(),archivedCount:zod.z.number(),archiveThreshold:zod.z.string(),archivedRecords:zod.z.array(zod.z.object({source:zod.z.string(),target:zod.z.string(),firstCreatedAt:zod.z.string(),firstFactId:zod.z.string()})),windowDays:zod.z.number(),dryRun:zod.z.boolean(),durationMs:zod.z.number()});var se=utils.Log.create({service:"memory.fact-file-sync"}),Rt=".easbot/memory/active";function ie(t,e){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),r=t.category||"uncategorized",o=t.createdAt?new Date(t.createdAt).getTime():Date.now(),c=Number.isNaN(o)?new Date:new Date(o),s=c.getFullYear(),i=String(c.getMonth()+1).padStart(2,"0"),p=String(c.getDate()).padStart(2,"0"),f=`${s}-${i}-${p}`;return `${n}/${Rt}/${r}/${f}.md`}function Ke(t){let e=t.tags&&t.tags.length>0?t.tags:[],n=t.importance??5,r=t.source??"session_self_write",o=t.createdAt?utils.formatLocalISO(new Date(t.createdAt)):utils.formatLocalISO(new Date),c=t.updatedAt?utils.formatLocalISO(new Date(t.updatedAt)):o,s=["---",`id: ${t.id}`,`agent_id: ${t.agentId}`,`category: ${t.category}`,`importance: ${n}`,`created_at: ${o}`,`updated_at: ${c}`,`source: ${r}`,e.length>0?`tags: [${e.join(", ")}]`:"tags: []"];return t.sessionId&&s.push(`session_id: ${t.sessionId}`),t.msgId&&s.push(`msg_id: ${t.msgId}`),t.parentMsgId&&s.push(`parent_msg_id: ${t.parentMsgId}`),t.nodeIds&&t.nodeIds.length>0&&s.push(`node_ids: [${t.nodeIds.join(", ")}]`),s.push("---"),`${s.join(`
22
+ `)}
23
+ ${t.content.trim()}`}function V(t,e){let n=t.replace(/\\/g,"/"),r=e.replace(/\\/g,"/").replace(/\/+$/,"");return n.startsWith(`${r}/`)?n.slice(r.length+1):n}async function St(t,e){let n=ie(t,e),r=V(n,e);try{let o=Ke(t);await G__default.default.mkdir(ce__default.default.dirname(n),{recursive:!0});let c="";try{c=await G__default.default.readFile(n,"utf-8");}catch(i){if(i.code!=="ENOENT")throw i}let s=c.length>0&&!c.endsWith(`
24
+ `)?`
25
+ `:"";return await G__default.default.writeFile(n,`${c}${s}${o}
26
+ `,"utf-8"),se.debug("Fact file synced (append)",{id:t.id,relPath:r}),{ok:!0,absPath:n,relPath:r}}catch(o){let c=o instanceof Error?o.message:String(o);return se.warn("Failed to write fact file (best-effort, non-blocking)",{id:t.id,absPath:n,error:c}),{ok:false,absPath:n,relPath:r,error:c}}}async function It(t,e){let n;t.filePath?n=`${e.replace(/\\/g,"/").replace(/\/+$/,"")}/${t.filePath.replace(/^\/+/,"")}`:n=ie({id:t.id,category:t.category,createdAt:t.createdAt,updatedAt:t.createdAt},e);let r=V(n,e);try{return await G__default.default.unlink(n),se.debug("Fact file deleted",{id:t.id,relPath:r}),{ok:!0,absPath:n,relPath:r}}catch(o){if(o.code==="ENOENT")return se.debug("Fact file not found (already deleted)",{id:t.id,relPath:r}),{ok:true,absPath:n,relPath:r};let s=o instanceof Error?o.message:String(o);return se.warn("Failed to delete fact file (best-effort, non-blocking)",{id:t.id,absPath:n,error:s}),{ok:false,absPath:n,relPath:r,error:s}}}var Y={resolvePath:ie,renderMarkdown:Ke,toRelPath:V,write:St,delete:It};var fe=utils.Log.create({service:"memory.service.remember"});async function Je(t,e){if(H(t),ge(t),!e.content||e.content.trim().length===0)throw new M("remember requires non-empty `content`","CONTENT_REQUIRED");if(!e.category)throw new M("remember requires `category`","CATEGORY_REQUIRED");fe.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 chunkEGWJG65Q_cjs.e(t.dbPath);try{await n.initialize();let r=new Date().toISOString(),o=Ct(),c=e.importance??5,s={entities:[],relations:[]},p=e.extractGraph!==!1&&chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().graphLlm?chunkJ5XF2W4Z_cjs.a.getGraphLlm():void 0;if(p)try{s=await Tt(p,e.content);}catch(y){fe.warn("LLM KG extraction failed (continuing without KG)",{agentId:t.agentId,error:y instanceof Error?y.message:String(y)});}let f=chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().embedding===!0,m=f?await Nt(n.getDb(),e.content):null,u=m?m.length:null,I=s.entities,v=s.relations,S=[],w=0;n.transaction(()=>{let y=new Map;for(let E of I){let _=n.query("SELECT id FROM nodes WHERE name = ? AND type = ? AND owner_agent_id = ? LIMIT 1",[E.name,E.type,t.agentId])[0];if(_){y.set(E.name,_.id);continue}let g=n.run("INSERT INTO nodes (name, type, properties, owner_agent_id, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)",[E.name,E.type,JSON.stringify({source:"llm_extracted",...E.properties??{}}),t.agentId,r,r]);g.lastID>0&&y.set(E.name,g.lastID);}for(let E of v){let _=y.get(E.source),g=y.get(E.target);!_||!g||_===g||n.run("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)",[_,g,E.relation,JSON.stringify({}),r]);}if(n.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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[o,t.agentId,e.sessionId??null,e.msgId??null,e.parentMsgId??null,e.content,e.category,c,"session_self_write",e.tags?JSON.stringify(e.tags):null,JSON.stringify(Array.from(y.values())),null,r,r]),m&&u){let E=Ve(m);n.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[o,E]),w=1,n.query("SELECT value FROM meta WHERE key = ?",["vectorDims"])[0]||n.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["vectorDims",String(u)]);}n.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[o]),n.run("INSERT INTO memory_facts_fts (fact_id, agent_id, content, tags) VALUES (?, ?, ?, ?)",[o,t.agentId,e.content,e.tags?e.tags.join(" "):""]),S.push(...Array.from(y.values()));}),fe.info("Memory stored",{id:o,category:e.category,agentId:t.agentId,nodeCount:S.length,vectorsWritten:w,vectorDims:u??0,embeddingMode:f?"enabled":"fts_only",entitiesExtracted:I.length,relationsExtracted:v.length});let h={id:o,agentId:t.agentId,sessionId:e.sessionId,msgId:e.msgId,parentMsgId:e.parentMsgId,content:e.content,category:e.category,importance:c,source:"session_self_write",tags:e.tags,nodeIds:S.length>0?S:void 0,filePath:void 0,createdAt:r,updatedAt:r},b="",R=await Y.write(h,t.workspaceDir);if(R.ok){b=R.relPath,h.filePath=R.relPath;try{n.run("UPDATE memory_facts SET file_path = ? WHERE id = ?",[R.relPath,o]);}catch(y){fe.warn("Failed to update file_path column after sync",{id:o,error:y instanceof Error?y.message:String(y)});}}return {fact:h,filePath:b,deduplicated:!1,nodeIds:S,vectorsWritten:w,vectorDims:u??0,entitiesExtracted:I.length,relationsExtracted:v.length}}catch(r){throw r instanceof M?r:new M(`remember failed: ${r instanceof Error?r.message:String(r)}`,"INTERNAL",{cause:r instanceof Error?r.message:String(r)})}finally{n.close();}}function Ct(){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 Ot(t){return crypto.createHash("sha256").update(t).digest("hex")}async function Nt(t,e){let n=Ot(e),r=t.prepare("SELECT embedding FROM embedding_cache WHERE content_hash = ?").get(n);if(r?.embedding)return new Float32Array(r.embedding.buffer,r.embedding.byteOffset,r.embedding.byteLength/4);let o=await chunkJ5XF2W4Z_cjs.a.embedText(e);if(!o||o.length===0)return null;let c=Ve(o);return t.prepare("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)").run(n,c),o}async function Tt(t,e){let n=await llm.GraphProvider.generateGraph({chunks:[e],model:t,includeRules:false});return {entities:n.entities,relations:n.relations}}var he=utils.Log.create({service:"memory.service.forget"}),kt=1e3;function At(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 M("CONTENT_REQUIRED: forget requires one of: `factId`, `category`, or `fromTime`/`toTime`","CONTENT_REQUIRED");if(e.length>1)throw new M(`mutually exclusive: forget requires exactly one of factId/category/timeRange, got [${e.join(", ")}]`,"CONTENT_REQUIRED");return e[0]}function xt(t,e,n){let r=[n];switch(t){case "factId":return {where:"agent_id = ? AND id = ?",args:[...r,e.factId]};case "category":return {where:"agent_id = ? AND category = ?",args:[...r,e.category]};case "timeRange":{let o=["agent_id = ?"];return e.fromTime&&(o.push("created_at >= ?"),r.push(e.fromTime)),e.toTime&&(o.push("created_at <= ?"),r.push(e.toTime)),{where:o.join(" AND "),args:r}}}}function Lt(t,e,n,r){return t.query(`SELECT id, node_ids FROM memory_facts WHERE ${e} LIMIT ?`,[...n,r+1]).map(c=>c.id)}function Ft(t,e,n,r){if(n.length===0)return 0;let o=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 (
30
+ SELECT 1 FROM json_each(node_ids) AS je WHERE je.value IN (${o})
31
+ )`,[r,e,...n])[0]?.count??0}function qt(t,e,n){let r,o,c="";return t.transaction(()=>{let s=t.query("SELECT node_ids, content, file_path, category, created_at FROM memory_facts WHERE id = ? AND agent_id = ?",[e,n])[0],i=[];if(s?.node_ids)try{i=JSON.parse(s.node_ids),Array.isArray(i)||(i=[]);}catch{i=[];}if(r=s?.file_path??void 0,o=s?.category,c=s?.created_at??"",t.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[e]),t.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[e,n]),i.length>0){let p=i.map(()=>"?").join(",");t.run(`DELETE FROM nodes WHERE id IN (${p}) 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
+ )`,i);}}),{filePath:r,category:o,createdAt:c}}async function Ye(t,e){H(t),j(t,"forget");let n=At(e),r=e.maxDelete??kt,o=e.dryRun??false,c=e.force??false;he.debug("forget invoked",{agentId:t.agentId,mode:n,maxDelete:r,dryRun:o,force:c});let s=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await s.initialize();let{where:i,args:p}=xt(n,e,t.agentId),f=Lt(s,i,p,r),m=f.length>r;if(m&&!c)throw new oe(f.length,r);let u=m?f.slice(0,r):f;if(o)throw new ne(u.length);let I=[],v=[];for(let S of u){if(!c){let R=s.query("SELECT node_ids FROM memory_facts WHERE id = ? AND agent_id = ?",[S,t.agentId])[0],y=R?.node_ids?(()=>{try{let _=JSON.parse(R.node_ids);if(Array.isArray(_))return _.filter(g=>typeof g=="number")}catch{}return []})():[],E=Ft(s,S,y,t.agentId);if(E>0)throw new re(S,E)}let{filePath:w,category:h,createdAt:b}=qt(s,S,t.agentId);w&&h&&v.push({id:S,filePath:w,category:h,createdAt:b}),I.push(S);}he.info("forget complete",{agentId:t.agentId,mode:n,deletedCount:I.length,force:c,dryRun:o});for(let{id:S,filePath:w,category:h,createdAt:b}of v)await Y.delete({id:S,filePath:w,category:h,createdAt:b},t.workspaceDir).catch(R=>{he.warn("Fact file delete failed (best-effort)",{id:S,filePath:w,error:R instanceof Error?R.message:String(R)});});return {deletedCount:I.length,deletedIds:I,dryRun:o,truncatedCount:m?f.length-r:0}}catch(i){throw i instanceof M?i:new M(`forget failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var be=utils.Log.create({service:"memory.service.extract"}),Ht=50,Ee=500;async function Xe(t,e){if(H(t),!e.sessionId||e.sessionId.trim().length===0)throw new M("extract requires non-empty `sessionId`","SESSION_ID_REQUIRED");let n=e.lastN??Ht;if(n>Ee)throw new M(`extract lastN=${n} exceeds max=${Ee}`,"CONTENT_REQUIRED",{lastN:n,maxLastN:Ee});let r=e.sessionId,o=e.fromMessageId;be.debug("extract invoked",{agentId:t.agentId,sessionId:r,lastN:n,fromMessageId:o,writeToDisk:e.writeToDisk??true});let c=Date.now(),s=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await s.initialize();let i=s.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,r,n]),p=o?i.filter(S=>S.id>o):i,f=new Set;for(let S of p)if(S.node_ids)try{let w=JSON.parse(S.node_ids);if(Array.isArray(w))for(let h of w)typeof h=="number"&&h>0&&f.add(h);}catch(w){be.warn("extract: invalid node_ids JSON",{factId:S.id,error:w instanceof Error?w.message:String(w)});}let m=Array.from(f),u=[],I=[];if(m.length>0){let S=m.map(()=>"?").join(","),w=s.query(`SELECT id, name, type FROM nodes WHERE id IN (${S})`,m),h=new Map;for(let y of w)h.set(y.id,y.name);u=w.map(y=>({id:y.id,name:y.name,type:y.type}));let b=s.query(`SELECT source, target, relation FROM edges WHERE source IN (${S}) OR target IN (${S})`,[...m,...m]),R=new Set;I=[];for(let y of b){let E=h.get(y.source),_=h.get(y.target);if(!E||!_)continue;let g=`${E}\0${y.relation}\0${_}`;R.has(g)||(R.add(g),I.push({source:E,target:_,relation:y.relation}));}}let v=Date.now()-c;return be.info("extract complete",{agentId:t.agentId,sessionId:r,factCount:p.length,nodeCount:u.length,relationCount:I.length,durationMs:v}),{extractedCount:p.length,factIds:p.map(S=>S.id),entities:u,relations:I,messageRange:{fromMessageId:p[0]?.id??"",toMessageId:p[p.length-1]?.id??""},durationMs:v}}catch(i){throw i instanceof M?i:new M(`extract failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var Se=utils.Log.create({service:"memory.service.consolidate"}),Wt=30;async function jt(t){let{createHash:e}=await import('crypto');return e("sha256").update(t).digest("hex")}async function Ze(t,e={}){let n=Date.now();H(t),j(t,"consolidate");let r=e.windowDays??Wt,o=e.dryRun??false;Se.debug("consolidate invoked",{agentId:t.agentId,windowDays:r,dryRun:o});let c=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await c.initialize();let s=c.query("SELECT id, content, category, importance, created_at FROM memory_facts WHERE agent_id = ? ORDER BY created_at DESC",[t.agentId]),i=new Map;for(let h of s){let b=await jt(h.content);i.has(b)||i.set(b,[]),i.get(b)?.push(h);}let p=0,f=[];for(let[,h]of i){if(h.length<=1)continue;let b=[...h].sort((E,_)=>E.importance!==_.importance?_.importance-E.importance:_.created_at.localeCompare(E.created_at)),R=b[0];if(!R)continue;let y=b.slice(1).map(E=>E.id);p+=y.length,f.push({keep:R,removeIds:y});}let m=new Date(Date.now()-r*24*60*60*1e3).toISOString(),u=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,m]),I=0,v=0;if(o)I=0,v=p;else {let h=ce__default.default.join(t.workspaceDir,"archive");await G__default.default.mkdir(h,{recursive:!0});for(let{removeIds:b}of f){if(b.length===0)continue;let R=b.map(()=>"?").join(",");c.transaction(()=>{for(let y of b)c.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[y,t.agentId]);}),v+=b.length;}for(let b of u){let R=b.created_at.slice(0,7),y=ce__default.default.join(h,R,b.category);await G__default.default.mkdir(y,{recursive:!0});let E=ce__default.default.join(y,`${b.id}.md`);try{await G__default.default.writeFile(E,[`# ${b.id}`,"",`category: ${b.category}`,`importance: ${b.importance}`,`createdAt: ${b.created_at}`,"",b.content,""].join(`
42
+ `),"utf-8"),c.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[b.id,t.agentId]),I++;}catch(_){Se.warn("consolidate: archive write failed",{factId:b.id,error:_ instanceof Error?_.message:String(_)});}}}let S=s.length,w=0;return Se.info("consolidate complete",{agentId:t.agentId,totalFacts:S,dedupedCount:p,compressedCount:w,archivedCount:I,skippedCount:v,dryRun:o,durationMs:Date.now()-n}),{totalFacts:S,dedupedCount:p,compressedCount:w,archivedCount:I,skippedCount:v,durationMs:Date.now()-n}}catch(s){throw s instanceof M?s:new M(`consolidate failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{c.close();}}var $=utils.Log.create({service:"memory.service.sync"}),Bt=30,Qt=".easbot/memory/active",et=".easbot/memory/archive";function Kt(t){return {id:t.id,agentId:t.agent_id,sessionId:t.session_id??void 0,msgId:t.msg_id??void 0,parentMsgId:t.parent_msg_id??void 0,content:t.content,category:t.category,importance:t.importance,source:t.source,tags:t.tags?JSON.parse(t.tags):void 0,nodeIds:t.node_ids?JSON.parse(t.node_ids):void 0,filePath:t.file_path??void 0,createdAt:t.created_at,updatedAt:t.updated_at}}async function Jt(t,e){let n=0,r=0,o=0,{where:c,params:s}=t.agentFilter(e.agentId),i=t.query(`SELECT id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance,
43
+ source, tags, node_ids, file_path, created_at, updated_at
44
+ FROM memory_facts ${c}
45
+ ORDER BY created_at ASC`,s);for(let p of i){let f=Kt(p);if(p.file_path?.startsWith(`${et}/`)){r++;continue}let m=ie(f,e.workspaceDir);try{await G__default.default.access(m),r++;continue}catch(I){let v=I;if(v.code!=="ENOENT"){$.warn("sync generate: fs.access failed (non-ENOENT)",{factId:f.id,absPath:m,error:v.message}),o++;continue}}let u=await Y.write(f,e.workspaceDir);u.ok?n++:(o++,$.warn("sync generate: factFileSync.write failed",{factId:f.id,absPath:m,error:u.error}));}return $.debug("sync stage A complete",{agentId:e.agentId,generatedCount:n,skippedCount:r,failedGenerateCount:o}),{generatedCount:n,skippedCount:r,failedGenerateCount:o}}async function Vt(t,e,n,r){let o=n*24*60*60*1e3,c=Date.now(),s=utils.formatLocalISO(new Date(c-o)),i=[],p=ce__default.default.join(e.workspaceDir,Qt),f=await Yt(p);$.debug("sync stage B: scan active dir",{activeDir:p,fileCount:f.length,windowDays:n,threshold:s,dryRun:r});for(let m of f){let u=await Xt(m);if(!u){$.warn("sync stage B: skip unparseable file",{absPath:m});continue}let{firstCreatedAt:I,firstFactId:v}=u,S=new Date(I).getTime();if(Number.isNaN(S)){$.warn("sync stage B: skip invalid createdAt",{absPath:m,firstCreatedAt:I});continue}if(c-S<=o)continue;let w=Zt(m);if(!w){$.warn("sync stage B: cannot infer category from path",{absPath:m});continue}let h=I.slice(0,7),b=ce__default.default.join(e.workspaceDir,et,h,w),R=ce__default.default.basename(m),y=ce__default.default.join(b,R);if(r){i.push({source:m,target:y,firstCreatedAt:I,firstFactId:v});continue}try{await G__default.default.mkdir(b,{recursive:!0});try{await G__default.default.rename(m,y);}catch(g){let k=g;$.warn("sync stage B: fs.rename failed, falling back to copy+unlink",{absPath:m,targetPath:y,error:k.message}),await G__default.default.copyFile(m,y),await G__default.default.unlink(m);}let E=V(m,e.workspaceDir),_=V(y,e.workspaceDir);t.run(`UPDATE memory_facts SET file_path = ?
46
+ WHERE agent_id = ? AND file_path = ?`,[_,e.agentId??"",E]),i.push({source:m,target:y,firstCreatedAt:I,firstFactId:v});}catch(E){$.warn("sync stage B: archive failed",{absPath:m,targetPath:y,error:E instanceof Error?E.message:String(E)});}}return $.debug("sync stage B complete",{agentId:e.agentId,archivedCount:i.length,dryRun:r}),{archivedCount:i.length,archiveThreshold:s,archivedRecords:i}}async function Yt(t){let e=[];try{await tt(t,e);}catch(n){let r=n;if(r.code==="ENOENT")return e;throw $.warn("sync: listActiveMdFiles failed",{activeDir:t,error:r.message}),new M(`sync: listActiveMdFiles failed: ${r.message}`,"INTERNAL",{cause:r.message})}return e}async function tt(t,e){let n=await G__default.default.readdir(t,{withFileTypes:true});for(let r of n){let o=ce__default.default.join(t,r.name);r.isDirectory()?await tt(o,e):r.isFile()&&r.name.endsWith(".md")&&e.push(o);}}async function Xt(t){let e;try{e=await G__default.default.readFile(t,"utf-8");}catch(s){if(s.code==="ENOENT")return null;throw s}if(!e.startsWith(`---
47
+ `))return null;let n=e.indexOf(`
48
+ ---
49
+ `,4);if(n===-1)return null;let r=e.slice(4,n),o,c;for(let s of r.split(`
50
+ `)){let i=s.trim();if(i.startsWith("created_at:")?o=i.slice(11).trim().replace(/^["']|["']$/g,""):i.startsWith("id:")&&(c=i.slice(3).trim().replace(/^["']|["']$/g,"")),o&&c)break}return !o||!c?null:{firstCreatedAt:o,firstFactId:c}}function Zt(t){let e=t.replace(/\\/g,"/").split("/"),n=e.findIndex(c=>c==="active");if(n===-1)return null;let r=e.slice(n+1);return r.length!==2||!r[1].endsWith(".md")?null:r[0]??null}async function rt(t,e={}){let n=Date.now();H(t),j(t,"sync");let r=e.windowDays??t.config?.archiveDays??Bt,o=e.dryRun??false;$.info("sync invoked",{agentId:t.agentId,windowDays:r,dryRun:o,workspaceDir:t.workspaceDir});let c=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await c.initialize();let s=await Jt(c,t),i=await Vt(c,t,r,o),p={generatedCount:s.generatedCount,skippedCount:s.skippedCount,failedGenerateCount:s.failedGenerateCount,archivedCount:i.archivedCount,archiveThreshold:i.archiveThreshold,archivedRecords:i.archivedRecords,windowDays:r,dryRun:o,durationMs:Date.now()-n};return $.info("sync complete",{agentId:t.agentId,...p}),p}catch(s){throw s instanceof M?s:new M(`sync failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{c.close();}}var nt=utils.Log.create({service:"memory.service.graph-query"});async function ot(t,e){let n=Date.now(),r=(t.agentId??"").trim()||"default",o=e.scope??"agent_only";if(!e.query||e.query.trim().length===0)throw new M("CONTENT_REQUIRED: graphQuery requires non-empty `query`","CONTENT_REQUIRED");ue(t,o,"graph_query");let c=e.depth??2,s=e.maxNodes??100,i=e.query,p=e.type,f=e.relation;nt.debug("graphQuery invoked",{agentId:r,query:i,type:p,depth:c,maxNodes:s,scope:o,remote:t.remote});let m=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await m.initialize();let u=new J(m.getDb()),I=i.includes("*")||i.includes("%")?i:`%${i}%`,v=await u.queryNodes({name:I,...p?{type:p}:{},agentId:r,scope:o,limit:s}),w=(i.includes("*")||i.includes("%")?v:v.filter(g=>g.name.toLowerCase().includes(i.toLowerCase())))[0]??null;if(!w)return {root:null,nodes:[],edges:[],truncated:!1,totalNodes:0,totalEdges:0,scope:o,durationMs:Date.now()-n};let h=await u.queryNeighbors(w.id,c,{agentId:r,scope:o,maxEdgesPerNode:20}),b=new Map;b.set(w.id,w);for(let g of h)b.set(g.id,{id:g.id,name:g.name,type:g.type,createdAt:g.createdAt,updatedAt:g.updatedAt});let R=[];for(let g of h)if(g.edges)for(let k of g.edges)f&&k.relation!==f||R.push(k);for(let g of R){if(!b.has(g.source)){let k=await u.queryNodes({ids:[g.source],agentId:r,scope:o});k[0]&&b.set(k[0].id,k[0]);}if(!b.has(g.target)){let k=await u.queryNodes({ids:[g.target],agentId:r,scope:o});k[0]&&b.set(k[0].id,k[0]);}}let y=Array.from(b.values()),E=y.length>s,_=E?y.slice(0,s):y;return nt.info("graphQuery complete",{agentId:r,rootId:w.id,nodeCount:_.length,edgeCount:R.length,truncated:E,durationMs:Date.now()-n}),{root:w,nodes:_,edges:R,truncated:E,totalNodes:y.length,totalEdges:R.length,scope:o,durationMs:Date.now()-n}}catch(u){throw u instanceof M?u:new M(`graphQuery failed: ${u instanceof Error?u.message:String(u)}`,"INTERNAL",{cause:u instanceof Error?u.message:String(u)})}finally{m.close();}}var U=utils.Log.create({service:"memory.service.init"});function Ie(t){return ce__default.default.join(t,".easbot","memory.json")}async function nr(t){try{let{Config:e}=await import('@easbot/llm'),n=await e.get(),r=o=>typeof o=="string"&&o.length>0?o:void 0;return {embeddingModel:r(n.embedding_model),graphModel:r(n.graph_model)}}catch{return {}}}function or(t,e={}){let n={version:1,schema_version:chunkEGWJG65Q_cjs.a,backend:"better-sqlite3",created_at:new Date().toISOString(),embedding_model:e.embeddingModel??null,graph_model:e.graphModel??null,entity_extraction_prompt:e.entityExtractionPrompt??null,relation_extraction_prompt:e.relationExtractionPrompt??null,archiveDays:e.archiveDays??30,shortTermMaxRounds:e.shortTermMaxRounds??20};fs.writeFileSync(t,JSON.stringify(n,null,2),"utf-8");}async function at(t,e={}){let n=Date.now();j(t,"init");let r=e.workspaceDir??t.workspaceDir,o=e.dbPath??t.dbPath;if(!r||r.trim().length===0)throw new M("init requires non-empty `workspaceDir` (ctx.workspaceDir or params.workspaceDir)","CONTENT_REQUIRED");if(!o||o.trim().length===0)throw new M("init requires non-empty `dbPath` (ctx.dbPath or params.dbPath)","CONTENT_REQUIRED");let c=t.agentId?.trim()??"",s=e.force??false;U.debug("init invoked",{agentId:c,workspaceDir:r,dbPath:o,force:s});let i=Ie(r);if(!s)try{if(await G__default.default.stat(i).then(()=>!0).catch(()=>!1))return U.info("init: idempotent skip (memory.json exists, no --force)",{workspaceDir:r,configPath:i}),{initialized:!1,dbPath:o,configPath:i,configCreated:!1,schemaVersion:chunkEGWJG65Q_cjs.a,workspaceDir:r,tablesCreated:0,migrationsApplied:0,durationMs:0}}catch{}try{await G__default.default.mkdir(ce__default.default.dirname(o),{recursive:!0}),await G__default.default.mkdir(ce__default.default.join(r,".easbot","memory","active"),{recursive:!0}),await G__default.default.mkdir(ce__default.default.join(r,"archive"),{recursive:!0}),await G__default.default.mkdir(ce__default.default.join(r,".easbot"),{recursive:!0});}catch(u){throw new M(`init: failed to create directories: ${u instanceof Error?u.message:String(u)}`,"INTERNAL",{cause:u instanceof Error?u.message:String(u)})}if(s)try{await G__default.default.rm(o,{force:!0});}catch(u){U.warn("init: force rm db failed (may not exist)",{dbPath:o,error:u instanceof Error?u.message:String(u)});}let p=await nr(),f=false;try{!await G__default.default.stat(i).then(()=>!0).catch(()=>!1)||s?(or(i,{embeddingModel:p.embeddingModel,graphModel:p.graphModel,archiveDays:t.config?.archiveDays,shortTermMaxRounds:t.config?.shortTermMaxRounds}),f=!0,U.info("init: memory.json written",{configPath:i,force:s,configCreated:f})):U.debug("init: memory.json already exists, skipping write",{configPath:i});}catch(u){U.warn("init: memory.json write failed (non-fatal)",{configPath:i,error:u instanceof Error?u.message:String(u)});}let m=new chunkEGWJG65Q_cjs.e(o);try{let u=await G__default.default.stat(o).then(()=>!0).catch(()=>!1);await m.initialize();let I=new Date().toISOString(),v=[["version","1.0.0"],["schemaVersion",String(chunkEGWJG65Q_cjs.a)],["createdAt",I],["defaultAgentId",c]];for(let[h,b]of v)try{m.run("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)",[h,b]);}catch(R){U.warn("init: meta insert failed",{key:h,error:R instanceof Error?R.message:String(R)});}let S=0;try{S=m.prepare("SELECT COUNT(*) as n FROM sqlite_master WHERE type IN ('table', 'index', 'trigger', 'view')").get()?.n??0;}catch(h){U.warn("init: tablesCreated count failed",{error:h instanceof Error?h.message:String(h)});}let w=0;try{w=m.prepare("SELECT id FROM schema_migrations").all().length;}catch(h){U.warn("init: migrationsApplied count failed",{error:h instanceof Error?h.message:String(h)});}return U.info("init complete",{agentId:c,workspaceDir:r,dbPath:o,configPath:i,configCreated:f,schemaVersion:chunkEGWJG65Q_cjs.a,durationMs:Date.now()-n}),{initialized:!0,dbPath:o,configPath:i,configCreated:f,schemaVersion:chunkEGWJG65Q_cjs.a,workspaceDir:r,tablesCreated:S,migrationsApplied:w,durationMs:Date.now()-n}}catch(u){throw new M(`init failed: ${u instanceof Error?u.message:String(u)}`,"INTERNAL",{cause:u instanceof Error?u.message:String(u)})}finally{m.close();}}var X=utils.Log.create({service:"memory.service.status"}),cr=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"],dr={};async function st(t,e={},n=dr){let r=t.agentId&&t.agentId.trim().length>0?t.agentId:void 0;if(X.debug("status invoked",{agentId:r??"<global>"}),!t.dbPath||t.dbPath.length===0)throw new M("`ctx.dbPath` is required","INTERNAL");let o={initialized:false,capabilities:{embedding:false,graphLlm:false}},c={},s={},i=0,p=0,f=0,m,u,I,v=false,S,w="uninitialized",h=false,b=false,R=false,y,E=cr.reduce((O,F)=>(O[F]=0,O),{}),_=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await _.initialize(),i=_.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,p=_.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,f=_.query("SELECT COUNT(*) as c FROM edges")[0]?.c??0;let B=_.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 D of B){let L=D.category;L in E&&(E[L]=D.c);}c.facts=i,c.nodes=p,c.edges=f;try{b=_.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]).length>0;}catch(D){X.debug("status: fts probe failed",{error:D instanceof Error?D.message:String(D)});}v=!!t.config?.embeddingLlm;try{h=_.query("SELECT name FROM pragma_table_info('nodes') WHERE name = ?",["owner_agent_id"]).length>0;}catch(D){X.debug("status: kg scope probe failed",{error:D instanceof Error?D.message:String(D)});}R=_.healthCheck();try{let D=_.query("SELECT key, value FROM meta");for(let L of D)s[L.key]=L.value;}catch(D){X.debug("status: meta read failed",{error:D instanceof Error?D.message:String(D)});}let d=s.schema_version,l=s.extraction_version,C=s.lastSyncAt??s.lastSync,P=s.embeddingDims;m=d&&Number.parseInt(d,10)||void 0,u=l&&Number.parseInt(l,10)||void 0,I=C,S=P&&Number.parseInt(P,10)||void 0,i>0&&(w="complete");try{y=_.query("SELECT value FROM meta WHERE key = ?",["backend"])[0]?.value??"better-sqlite3";}catch{y="better-sqlite3";}}catch(O){if(O instanceof M)throw O;X.warn("status: db phase failed; returning partial result",{dbPath:t.dbPath,error:O instanceof Error?O.message:String(O)}),y="unknown",R=false;}finally{_.close();}if(!n.skipLlm&&chunkJ5XF2W4Z_cjs.a.isInitialized()){let F=chunkJ5XF2W4Z_cjs.a.capabilities();o.initialized=true,o.capabilities={embedding:F.embedding===true,graphLlm:F.graphLlm===true},o.embeddingModel=o.capabilities.embedding?"configured":void 0,o.graphModel=o.capabilities.graphLlm?"configured":void 0;}if(!n.skipEmbeddingProbe&&!n.skipLlm&&o.initialized&&o.capabilities.embedding)try{let O=chunkJ5XF2W4Z_cjs.a.getEmbeddingLlm?.();if(O){let F=await llm.probeEmbeddingDims(O,{timeoutMs:5e3});if(typeof F=="number"){S=F,s.embeddingDims=String(F);try{let W=new chunkEGWJG65Q_cjs.e(t.dbPath);try{await W.initialize();let B=W.getDb();llm.syncMeta(B,[["embeddingDims",String(F)]]);}finally{W.close();}}catch{}}}}catch{}let g;return R?w==="uninitialized"&&(g="Run `easbot memory remember <content>` to add the first fact."):g="Run `easbot memory init` to initialize the database.",R&&(w??"uninitialized")==="failed"&&(R=false),X.info("status complete",{dbPath:t.dbPath,agentId:r??"<global>",factsCount:i,nodesCount:p,edgesCount:f,healthy:R}),{package:"memory",agentId:r,dbPath:t.dbPath,configPath:Ie(t.workspaceDir),configExists:true,schemaVersion:m,extractionVersion:u,lastSyncAt:I,indexState:w,vectorEnabled:v,embeddingDims:S,llm:o,backend:y,counts:c,meta:s,recommendation:g,healthy:R,factsByCategory:E,kgScopeEnabled:h,factsCount:i,nodesCount:p,edgesCount:f,ftsAvailable:b}}var pr=utils.Log.create({service:"memory.service.doctor"}),_e=100*1024*1024,it=100*1024*1024,fr={};function N(t,e,n,r,o){return {code:t.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),severity:e,name:t,message:n,details:o,durationMs:r,passed:e!=="error"}}async function ct(t,e={},n=fr){if(pr.debug("doctor invoked",{agentId:t.agentId}),!t.dbPath||t.dbPath.length===0)throw new Error("`ctx.dbPath` is required");let r=[],o=[],c=Date.now(),s=null,i=false,p=Date.now();try{s=new chunkEGWJG65Q_cjs.e(t.dbPath),await s.initialize(),i=!0;let d=s.healthCheck(),l=N("database",d?"ok":"error",d?"database connected and writable":"database unhealthy",Date.now()-p,{dbPath:t.dbPath});r.push(l),o.push({name:l.name,passed:l.severity!=="error",message:l.message,details:l.details,severity:l.severity});}catch(d){let l=N("database","error",`database connection failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-p,{dbPath:t.dbPath});r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"error"});}let f=Date.now();if(i&&s)try{let d=s.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]),l=d.length>0,C=N("fts",l?"ok":"warn",l?"FTS5 index available":"FTS5 index not found",Date.now()-f,l?{table:d[0]?.name}:void 0);r.push(C),o.push({name:C.name,passed:C.severity!=="error",message:C.message,details:C.details,severity:C.severity});}catch(d){let l=N("fts","error",`fts probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-f);r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"error"});}else {let d=N("fts","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let m=Date.now(),u=!!t.config?.embeddingLlm,I=N("vector","ok",u?"embedding model available":"no embedding model configured (FTS-only mode, recall still functional)",Date.now()-m,{mode:u?"hybrid":"fts_only",model:u?"configured":"missing"});r.push(I),o.push({name:I.name,passed:true,message:I.message,details:I.details,severity:"ok"});let v=Date.now();if(i&&s)try{let d=["memory_facts","nodes","edges","meta"],l=s.query("SELECT name FROM sqlite_master WHERE type = ?",["table"]),C=new Set(l.map(L=>L.name)),P=d.filter(L=>!C.has(L)),D=N("schema",P.length===0?"ok":"error",P.length===0?`schema complete (${d.length} tables)`:`missing tables: ${P.join(", ")}`,Date.now()-v,{required:d,existing:Array.from(C)});r.push(D),o.push({name:D.name,passed:D.severity!=="error",message:D.message,details:D.details,severity:D.severity});}catch(d){let l=N("schema","error",`schema probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-v);r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"error"});}else {let d=N("schema","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let S=Date.now();try{let d=`${t.dbPath}-wal`,l=`${t.dbPath}-shm`,C=0,P=0;try{C=(await G__default.default.stat(d)).size;}catch{C=0;}try{P=(await G__default.default.stat(l)).size;}catch{P=0;}let D=C+P,L=D<=it,q=N("lock",L?"ok":"warn",L?`no lock contention (wal+shm ${(D/1024).toFixed(1)} KB)`:`WAL/SHM files unusually large (${(D/1024/1024).toFixed(1)} MB > ${(it/1024/1024).toFixed(0)} MB threshold)`,Date.now()-S,{walBytes:C,shmBytes:P});r.push(q),o.push({name:q.name,passed:q.severity!=="error",message:q.message,details:q.details,severity:q.severity});}catch(d){let l=N("lock","error",`lock probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-S);r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"error"});}let w=Date.now();try{let d=ce__default.default.dirname(t.dbPath),l=await G__default.default.statfs(d),C=typeof l.bsize=="bigint"?Number(l.bsize)*l.bavail:l.bsize*l.bavail,P=C>=_e,D=N("disk_space",P?"ok":"error",P?`sufficient disk space (${(C/1024/1024).toFixed(1)} MB available)`:`low disk space (${(C/1024/1024).toFixed(1)} MB < ${(_e/1024/1024).toFixed(0)} MB threshold)`,Date.now()-w,{availableBytes:C,threshold:_e});r.push(D),o.push({name:D.name,passed:D.severity!=="error",message:D.message,details:D.details,severity:D.severity});}catch(d){let l=N("disk_space","error",`disk_space probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-w);r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"error"});}let h=Date.now();if(i&&s)try{let d=s.agentFilter(t.agentId),l=s.query(`SELECT id, node_ids FROM memory_facts ${d.where} ${d.where?"AND":"WHERE"} node_ids IS NOT NULL`,d.params),C=[];for(let D of l)try{let L=JSON.parse(D.node_ids);if(!Array.isArray(L))continue;for(let q of L){if(typeof q!="number")continue;if((s.query("SELECT COUNT(*) as c FROM nodes WHERE id = ?",[q])[0]?.c??0)===0){C.push(`${D.id}->${q}`);break}}}catch{}let P=N("orphan",C.length===0?"ok":"warn",C.length===0?"no orphan KG references":`${C.length} orphan references: ${C.slice(0,5).join(", ")}${C.length>5?", ...":""}`,Date.now()-h,{count:C.length});r.push(P),o.push({name:P.name,passed:P.severity!=="error",message:P.message,details:P.details,severity:P.severity});}catch(d){let l=N("orphan","warn",`orphan probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-h);r.push(l),o.push({name:l.name,passed:false,message:l.message,details:l.details,severity:"warn"});}else {let d=N("orphan","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let b=Date.now(),R={"better-sqlite3":false,"node:sqlite":false,"@tursodatabase/database":false};try{let d=module$1.createRequire(chunkNVGACA7W_cjs.b);try{d.resolve("better-sqlite3"),R["better-sqlite3"]=!0;}catch{}R["node:sqlite"]=typeof process.versions.sqlite=="string";try{d.resolve("@tursodatabase/database"),R["@tursodatabase/database"]=!0;}catch{}}catch{}let y=R["better-sqlite3"]||R["node:sqlite"],E=N("backend",y?"ok":"error",y?`SQLite backend available (better-sqlite3: ${R["better-sqlite3"]}, node:sqlite: ${R["node:sqlite"]})`:"no SQLite backend available (install better-sqlite3 or use Node 22.5+)",Date.now()-b,R);r.push(E),o.push({name:E.name,passed:E.severity!=="error",message:E.message,details:E.details,severity:E.severity});let _=Date.now();if(i&&s)try{let d=s.query("SELECT COUNT(*) as c FROM embedding_cache")[0],l=s.agentFilter(t.agentId),C=s.query(`SELECT COUNT(*) as c FROM memory_facts ${l.where}`,l.params)[0],P=d?.c??0,D=C?.c??0,L=Math.max(0,P-D),q=L>0,Z=N("embedding_cache_unused","info",q?`by design: ${L} embedding_cache rows remain after fact deletion (cache is global content-hash dedup; forget intentionally doesn't cascade clear cache to preserve same-content hit rate)`:"embedding_cache in sync with memory_facts (no unused rows)",Date.now()-_,{cacheCount:P,factsCount:D,unused:L,policy:"global_content_hash_dedup"});r.push(Z),o.push({name:Z.name,passed:!q,message:Z.message,details:Z.details,severity:"info"});}catch(d){let l=N("embedding_cache_unused","info",`embedding_cache_unused probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-_);r.push(l),o.push({name:l.name,passed:true,message:l.message,severity:"info"});}else {let d=N("embedding_cache_unused","info","skipped (db not initialized)",0);r.push(d),o.push({name:d.name,passed:true,message:d.message,severity:"info"});}let g=Date.now(),k;if(i&&s)try{let d=s.query("SELECT value FROM meta WHERE key = ?",["embeddingDims"]);k=d[0]?.value&&Number.parseInt(d[0].value,10)||void 0;}catch{}let O;if(n.skipLlm||!chunkJ5XF2W4Z_cjs.a.isInitialized()||!chunkJ5XF2W4Z_cjs.a.capabilities().embedding)O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","llm not initialized; probe skipped",Date.now()-g);else if(n.skipEmbeddingProbe)O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe skipped (--skip-embedding-probe)",Date.now()-g);else try{let d=chunkJ5XF2W4Z_cjs.a.getEmbeddingLlm?.();if(!d)O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","embedding llm not exposed; probe skipped",Date.now()-g);else {let l=await llm.probeEmbeddingDims(d,{timeoutMs:5e3});typeof l!="number"?O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe failed (network / model error)",Date.now()-g):k===void 0?O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe=${l}, meta missing \u2014 next status will sync`,Date.now()-g):l!==k?O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"warn",`probe=${l}, meta=${k} \u2014 mismatch`,Date.now()-g,{probe:l,meta:k}):O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"ok",`probe=${l}, meta=${k} \u2014 consistent`,Date.now()-g);}}catch(d){O=N(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe threw: ${d instanceof Error?d.message:String(d)}`,Date.now()-g);}r.push({...O,details:O.details??void 0,passed:O.severity!=="error"}),o.push({name:O.name,passed:O.severity!=="error",message:O.message,details:O.details??void 0,severity:O.severity});let F;if(i&&s){let d=Date.now();try{let{issues:l,stats:C}=s.checkIntegrity();F=C;for(let P of l)r.push(N("integrity_stats",P.severity,P.message,0,{source:"database.checkIntegrity"}));}catch(l){r.push(N("integrity_stats","warn",`db integrity check failed: ${l instanceof Error?l.message:String(l)}`,Date.now()-d));}}let W=!r.some(d=>d.severity==="error");s&&s.close();let B=Date.now()-c;return {healthy:W,checks:r,legacyChecks:o,durationMs:B,integrityStats:F,backendAvailable:R}}var De={name:"recall",scope:"read",schema:qe,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 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 ve={name:"remember",scope:"write",schema:$e,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 Je({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var Ce={name:"forget",scope:"write",schema:He,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 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:"extract",scope:"write",schema:Ue,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 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},n)}};var Ne={name:"consolidate",scope:"admin",schema:We,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 Ze({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},n)}};var Te={name:"sync",scope:"admin",schema:Qe,annotations:{localOnly:true,requiresAgentId:true,defaultDescription:"Sync memory facts to .md files (idempotent skip on existing) and archive expired active files (default 30 days)",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let n=t;if(!e.isTrustedLocal)throw new Error("sync: only trusted local process can invoke this op");if(!e.agentId?.trim())throw new Error("sync: agentId is required");return rt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},n)}};var Pe={name:"graph_query",scope:"read",schema:je,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,r=e.agentId?.trim()||"default";return ot({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:r},n)}};var ke={name:"status",scope:"read",schema:Ge,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 n=t??{};return st({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},n)}};var Ae={name:"doctor",scope:"admin",schema:ze,annotations:{localOnly:true,requiresAgentId:false,defaultDescription:"Run 7 health checks (database / fts / vector / schema / lock / disk_space / orphan).",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let n=t??{};if(!e.isTrustedLocal)throw new Error("doctor: only trusted local process can invoke this op");return ct({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},n)}};var xe={name:"init",scope:"admin",schema:Be,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 at({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 dt={[De.name]:De,[ve.name]:ve,[Ce.name]:Ce,[Oe.name]:Oe,[Ne.name]:Ne,[Te.name]:Te,[Pe.name]:Pe,[ke.name]:ke,[Ae.name]:Ae,[xe.name]:xe},yr=Object.values(dt);function hr(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 r=e.agentId?.trim()??"";if(r.length===0)throw new Error(`MEMORY:executeOp: op "${n}" requires agentId`);e.agentId=r;}}async function _a(t,e,n){let r=dt[t];if(!r)throw new Error(`executeOp: unknown op "${t}"; available: ${yr.map(c=>c.name).join(", ")}`);return hr(r,n,t),await r.handler(e,n)}function wr(t){let e=t.dbPath??"";return {workspaceDir:t.workspaceDir??"",database:{path:e},embeddingLlm:chunkJ5XF2W4Z_cjs.a.getEmbeddingLlm(),graphLlm:chunkJ5XF2W4Z_cjs.a.getGraphLlm(),search:types.DEFAULT_SEARCH_CONFIG,indexer:{batchSize:20,ignorePatterns:[],incremental:true},archiveDays:30,shortTermMaxRounds:20}}function Aa(t,e,n={}){let r=chunkCPRDIUQ4_cjs.j(e),o=utils.Locale.resolveLocaleLang(n.locale);return {agentId:t,dbPath:r,workspaceDir:e,rootDir:e,config:wr({dbPath:r,workspaceDir:e}),isTrustedLocal:true,locale:o,remote:false,...n}}exports.a=J;exports.b=Fe;exports.c=qe;exports.d=$e;exports.e=He;exports.f=Ue;exports.g=We;exports.h=je;exports.i=Be;exports.j=Qe;exports.k=Je;exports.l=Ye;exports.m=Xe;exports.n=Ze;exports.o=rt;exports.p=ot;exports.q=at;exports.r=st;exports.s=ct;exports.t=dt;exports.u=yr;exports.v=_a;exports.w=wr;exports.x=Aa;
@@ -0,0 +1 @@
1
+ import {embed,embedMany}from'ai';import {Log}from'@easbot/utils';var m;(a=>{let s=Log.create({service:"memory-llm"}),e=null;function f(n){if(g())return;let r=n;e={models:r.models,options:r.options??{}},s.debug("Llm initialized",{embeddingConfigured:!!r.models.embeddingLlm,graphConfigured:!!r.models.graphLlm});}a.init=f;function g(){return e!==null}a.isInitialized=g;function y(){e=null;}a.reset=y;function x(){return e?{embedding:!!e.models.embeddingLlm,graphLlm:!!e.models.graphLlm}:{embedding:false,graphLlm:false}}a.capabilities=x;function w(){return e?.models.embeddingLlm}a.getEmbeddingLlm=w;function I(){return e?.models.graphLlm}a.getGraphLlm=I;async function u(n){let t=l().models.embeddingLlm;if(!t)throw new Error("embeddingLlm model is not configured.");try{let o=await embed({model:t,value:n});return new Float32Array(o.embedding)}catch(o){let i=t.doEmbed;if(typeof i!="function")throw new Error("embeddingLlm model does not support embedding generation.",{cause:o});let d=(await i({values:[n]}))?.embeddings?.[0];if(!d||!Array.isArray(d))throw new Error("embeddingLlm model returned invalid embedding result.",{cause:o});return new Float32Array(d)}}a.embedText=u;async function b(n){let t=l().models.embeddingLlm;if(!t)throw new Error("embeddingLlm model is not configured.");try{return (await embedMany({model:t,values:n})).embeddings.map(i=>new Float32Array(i))}catch{return ((await t.doEmbed?.({values:n}))?.embeddings??[]).map(i=>new Float32Array(i))}}a.embedTexts=b;let l=()=>{if(!e)throw new Error("Llm is not initialized. Please call Llm.init() first.");return e};a.embed=u,a.embedMany=b;})(m||(m={}));var v=m;export{m as a,v as b};