@easbot/memory 0.3.17 → 0.3.20

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-6CQMBEIQ.mjs +1 -0
  5. package/dist/chunks/chunk-AYGZUNFR.cjs +1 -0
  6. package/dist/chunks/{chunk-OIUUTVLL.cjs → chunk-EGWJG65Q.cjs} +22 -4
  7. package/dist/chunks/chunk-J5XF2W4Z.cjs +1 -0
  8. package/dist/chunks/chunk-JDPZ5U53.mjs +71 -0
  9. package/dist/chunks/chunk-N5YRDTEH.mjs +60 -0
  10. package/dist/chunks/{chunk-MWRDF6VN.mjs → chunk-QYBWHFOX.mjs} +1 -1
  11. package/dist/chunks/chunk-S6S35LDL.cjs +60 -0
  12. package/dist/chunks/chunk-SWYQLQ7Z.mjs +1 -0
  13. package/dist/chunks/chunk-TIZCWDJ7.mjs +1 -0
  14. package/dist/chunks/chunk-UF2Y2Q4L.mjs +50 -0
  15. package/dist/chunks/chunk-WQB4D6DZ.cjs +1 -0
  16. package/dist/chunks/chunk-Z5E4HBGK.cjs +50 -0
  17. package/dist/chunks/cli-handler-2IPBL45N.cjs +1 -0
  18. package/dist/chunks/cli-handler-5YNHYDSM.mjs +1 -0
  19. package/dist/chunks/consolidate-G4YJV756.cjs +2 -0
  20. package/dist/chunks/consolidate-MSPLH3T6.mjs +2 -0
  21. package/dist/chunks/doctor-GKMREWZN.mjs +1 -0
  22. package/dist/chunks/doctor-YTUQCHFJ.cjs +1 -0
  23. package/dist/chunks/extract-3C4QFS7E.mjs +2 -0
  24. package/dist/chunks/extract-YKDPZ7GA.cjs +2 -0
  25. package/dist/chunks/forget-GNIJL2DU.cjs +3 -0
  26. package/dist/chunks/{forget-A4UJI3LE.mjs → forget-VQB5DUJ3.mjs} +1 -1
  27. package/dist/chunks/{graph-XZ46LEO7.mjs → graph-4W63TU2D.mjs} +1 -1
  28. package/dist/chunks/graph-GTYUNUJE.cjs +3 -0
  29. package/dist/chunks/init-DGMGRNCG.cjs +1 -0
  30. package/dist/chunks/init-G2WTR477.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-BXVXTUJK.cjs → mcp-EHUKGJRB.cjs} +1 -1
  34. package/dist/chunks/{mcp-BOD4ZOZS.mjs → mcp-QQBHEZFY.mjs} +1 -1
  35. package/dist/chunks/recall-SGA2DITO.mjs +2 -0
  36. package/dist/chunks/recall-ZENMAOMJ.cjs +2 -0
  37. package/dist/chunks/remember-3ZY66RJQ.cjs +2 -0
  38. package/dist/chunks/remember-P3G7WWYB.mjs +2 -0
  39. package/dist/chunks/status-JYI52QKB.mjs +1 -0
  40. package/dist/chunks/status-UEKBJVCI.cjs +1 -0
  41. package/dist/chunks/stdio-server-2PWTBTDJ.mjs +1 -0
  42. package/dist/chunks/stdio-server-JL4XNUHH.cjs +1 -0
  43. package/dist/chunks/sync-64JINCSC.cjs +2 -0
  44. package/dist/chunks/sync-ZPRCA4MO.mjs +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 @@
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};
@@ -0,0 +1 @@
1
+ 'use strict';var chunkCPRDIUQ4_cjs=require('./chunk-CPRDIUQ4.cjs'),utils=require('@easbot/utils'),terminal=require('@easbot/terminal');var y=utils.Log.create({service:"memory-cli"}),S=[{i18nKey:"cli.cmd.init.description",name:"init",description:"Initialize memory workspace (.easbot/memory.db)",group:"lifecycle"},{i18nKey:"cli.cmd.status.description",name:"status",description:"Show memory state / db stats / facts by category",group:"lifecycle"},{i18nKey:"cli.cmd.doctor.description",name:"doctor",description:"Run health checks (backend, FTS, schema, lock)",group:"lifecycle"},{i18nKey:"cli.cmd.recall.description",name:"recall",description:"Hybrid search (FTS + vector) over memory facts",group:"memory"},{i18nKey:"cli.cmd.remember.description",name:"remember",description:"Persist a new memory fact (with dedup + KG extraction)",group:"memory"},{i18nKey:"cli.cmd.forget.description",name:"forget",description:"Delete memory facts (factId / category / timeRange / dryRun)",group:"memory"},{i18nKey:"cli.cmd.sync.description",name:"sync",description:"Sync facts to .md files (idempotent) and archive expired active files (default 30 days)",group:"memory"},{i18nKey:"cli.cmd.extract.description",name:"extract",description:"Extract facts from a session (sessionId + lastN)",group:"session"},{i18nKey:"cli.cmd.consolidate.description",name:"consolidate",description:"Run consolidation pipeline (extract \u2192 dedup \u2192 archive)",group:"session"},{i18nKey:"cli.cmd.graph.description",name:"graph",description:"KG query (nodes / edges / neighbors with scope \u4E09\u6863)",group:"graph"},{i18nKey:"cli.cmd.config.description",name:"config",description:"Show / validate memory configuration (dry-read)",group:"external"},{i18nKey:"cli.cmd.mcp.description",name:"mcp",description:"Start stdio MCP server (exposes 10 memory tools)",group:"external"}];function u(m,t){let e=S.filter(a=>a.group===m);return terminal.renderLines({title:t,flat:e.map(a=>`$ easbot-memory ${a.name.padEnd(14)} ${a.description}`)})}function v(){let m=[terminal.renderLines({title:"easbot-memory \xB7 Memory & Knowledge Module for EASBot",flat:["Usage: easbot-memory <command> [options]"]}),"",u("lifecycle","Commands (lifecycle):"),"",u("memory","Commands (memory):"),"",u("session","Commands (session):"),"",u("graph","Commands (graph query):"),"",u("external","External:")];terminal.printHuman(m);}function C(){v(),terminal.printHuman(["",terminal.renderLines({title:"Global flags & invocation",flat:["--cwd <dir> --config <path> --log-level <L> --print-logs --debug","Standalone CLI: easbot-memory <command>","Agent CLI: easbot memory <command>"]})]);}async function j(m){try{let{bootstrapLlm:t}=await import('@easbot/llm'),{Llm:e}=await import('./llm-RMPVWEVP.cjs');await t({target:e,cwd:m,subConfigPath:".easbot/memory.json",embedding:!0,graph:!0});}catch(t){y.warn("bootstrapLlm failed; Llm-related features will be disabled",{error:t instanceof Error?t.message:String(t)});}}async function E(m,t){let[e,...a]=m,c=t?.cwd??process.cwd();if(!e)return C(),{code:0,handled:true,command:null};await j(c);try{switch(e){case "init":{let{parseInitOptions:r,runInit:n}=await import('./init-DGMGRNCG.cjs'),s=r(a);if(s.help)return console.log("Usage: easbot-memory init [dir] [--agent <id>] [--force] [--json]"),{code:0,handled:!0,command:e};let o=s.workspaceDir?.trim()??c,i=await n({...s,ctxWorkspaceDir:o});if(s.json)terminal.emitJsonOk(i,{command:e});else {let p=i;terminal.printHuman([terminal.formatKnowledgeInit({packageName:"memory",configPath:p.configPath??p.dbPath,backend:"better-sqlite3",schemaVersion:p.schemaVersion,extras:{dbPath:p.dbPath,migrationsApplied:p.migrationsApplied,tablesCreated:p.tablesCreated,durationMs:`${p.durationMs}ms`}})],{title:"init memory workspace",boxed:!0});}return {code:0,handled:!0,command:e}}case "recall":{let{parseRecallOptions:r,runRecall:n,formatRecallText:s}=await import('./recall-ZENMAOMJ.cjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory recall --query <q> [--agent <id>] [--limit <n>] [--category <c>] [--min-importance <n>] [--json]"),{code:0,handled:!0,command:e};let i=await n({...o,workspaceDir:c});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([s(i)],{title:`recall (agentId=${o.agentId??"default"})`}),{code:0,handled:!0,command:e}}case "remember":{let{parseRememberOptions:r,runRemember:n,formatRememberText:s}=await import('./remember-3ZY66RJQ.cjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory remember --content <text> --category <c> --importance <1-10> [--agent <id>] [--tag <t>] [--session <s>] [--json]"),{code:0,handled:!0,command:e};let i=await n({...o,workspaceDir:c});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([s(i)],{title:"remember (persist fact)"}),{code:0,handled:!0,command:e}}case "forget":{let{parseForgetOptions:r,runForget:n,formatForgetText:s}=await import('./forget-GNIJL2DU.cjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory forget [--agent <id>] (--fact-id <id> | --category <c> | --from <ISO> --to <ISO>) [--max-delete <n>] [--dry-run] [--json]"),{code:0,handled:!0,command:e};let i=await n({...o,workspaceDir:c});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([s(i)],{title:"forget (delete facts)"}),{code:0,handled:!0,command:e}}case "extract":{let{parseExtractOptions:r,runExtract:n,formatExtractText:s}=await import('./extract-YKDPZ7GA.cjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory extract --session <sessionId> [--agent <id>] [--last-n <n>] [--from-msg <id>] [--json]"),{code:0,handled:!0,command:e};let i=await n({...o,workspaceDir:c});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([s(i)],{title:"extract (from session)"}),{code:0,handled:!0,command:e}}case "consolidate":{let{parseConsolidateOptions:r,runConsolidate:n,formatConsolidateText:s}=await import('./consolidate-G4YJV756.cjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory consolidate [--agent <id>] [--window-days <n>] [--json]"),{code:0,handled:!0,command:e};let i=await n({...o,workspaceDir:c});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([s(i)],{title:"consolidate (pipeline)"}),{code:0,handled:!0,command:e}}case "sync":{let{parseSyncOptions:r,runSync:n,formatSyncText:s}=await import('./sync-64JINCSC.cjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory sync [--agent <id>] [--window-days <n>] [--dry-run] [--json]"),console.log("Two-stage pipeline: (A) db \u2192 .md (idempotent skip on existing), (B) archive active/ files older than windowDays."),{code:0,handled:!0,command:e};let i=await n({...o,workspaceDir:c});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([s(i)],{title:"sync (db \u2192 .md + archive)"}),{code:0,handled:!0,command:e}}case "graph":{let{parseGraphOptions:r,runGraph:n,formatGraphText:s}=await import('./graph-GTYUNUJE.cjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory graph [--agent <id>] --kind <nodes|edges|neighbors> [--query <q>] [--start-node <id>] [--depth <n>] [--max-nodes <n>] [--scope <agent_only|shared_only|both>] [--json]"),{code:0,handled:!0,command:e};let i=await n({...o,workspaceDir:c});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([s(i)],{title:`graph_query (scope=${o.scope??"agent_only"})`}),{code:0,handled:!0,command:e}}case "status":{let{parseStatusOptions:r,runStatus:n}=await import('./status-UEKBJVCI.cjs'),s=r(a);if(s.help)return console.log("Usage: easbot-memory status [--agent <id>] [--json]"),{code:0,handled:!0,command:e};let o=await n({...s,workspaceDir:c});return s.json?terminal.emitJsonOk(o,{command:e}):terminal.printHuman([terminal.formatKnowledgeStatus(I(o))],{title:"memory status",boxed:!0}),{code:0,handled:!0,command:e}}case "doctor":{let{parseDoctorOptions:r,runDoctor:n}=await import('./doctor-YTUQCHFJ.cjs'),s=r(a);if(s.help)return console.log("Usage: easbot-memory doctor [--repair] [--json]"),{code:0,handled:!0,command:e};let o=await n({...s,workspaceDir:c});return s.json?terminal.emitJsonOk(o,{command:e}):terminal.printHuman([terminal.formatKnowledgeDoctor(K(o))],{title:"memory doctor",boxed:!0}),{code:0,handled:!0,command:e}}case "config":{let{parseConfigOptions:r,runConfig:n,formatConfigText:s}=await import('./config-RPPQ73HK.cjs'),o=r(a);if(o.help)return console.log("Usage: easbot-memory config [--json]"),{code:0,handled:!0,command:e};let i=n(o);return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([s(i)],{title:"memory config"}),{code:0,handled:!0,command:e}}case "mcp":{let{parseMcpOptions:r,runMcp:n}=await import('./mcp-EHUKGJRB.cjs'),s=r(a);if(s.help)return console.log("Usage: easbot-memory mcp [start]"),console.log("Start a stdio MCP server exposing 10 memory tools:"),console.log(" recall / remember / forget / extract / consolidate"),console.log(" graph_query / status / doctor / init / sync"),{code:0,handled:!0,command:e};let o=await n(s);return s.json?terminal.emitJsonOk(o,{command:e}):terminal.printHuman([`memory mcp started (tools: ${o.tools.length})`],{title:"memory mcp server"}),{code:0,handled:!0,command:e}}default:return console.error(`Unknown command: ${e}`),console.error("Run `easbot-memory --help` for available commands."),{code:2,handled:!1,command:null}}}catch(r){let n=r instanceof Error?r.message:String(r);y.error("memory CLI command failed",{command:e,error:n,stack:r instanceof Error?r.stack:void 0});let s=t?.cwd??chunkCPRDIUQ4_cjs.f().worktree;return console.error(`[memory] ${s} :: ${e} failed: ${n}`),terminal.emitJsonError(e,n),{code:1,handled:true,command:e}}}function I(m){let t=m;return {packageName:"memory",rootDir:t.workspaceDir??"",configPath:t.configPath??"",configExists:true,dbPath:t.dbPath??"",dbExists:true,dbSize:typeof t.dbSize=="number"?t.dbSize:void 0,indexState:t.indexState,schemaVersion:typeof t.schemaVersion=="number"?t.schemaVersion:void 0,extractionVersion:typeof t.extractionVersion=="number"?t.extractionVersion:void 0,lastSyncAt:t.lastSyncAt,vectorEnabled:typeof t.vectorEnabled=="boolean"?t.vectorEnabled:void 0,embeddingDims:typeof t.embeddingDims=="number"?t.embeddingDims:void 0,llm:t.llm??{initialized:false,capabilities:{}},backend:t.backend,counts:t.counts??{},healthy:typeof t.healthy=="boolean"?t.healthy:true,recommendation:t.recommendation,extras:(()=>{let e={};if(typeof t.agentId=="string"&&(e.agent_id=t.agentId),typeof t.ftsAvailable=="boolean"&&(e.fts_available=t.ftsAvailable?"yes":"no"),typeof t.kgScopeEnabled=="boolean"&&(e.kg_scope_enabled=t.kgScopeEnabled?"yes":"no"),t.factsByCategory&&typeof t.factsByCategory=="object"){let a=t.factsByCategory;for(let[c,r]of Object.entries(a))typeof r=="number"&&r>0&&(e[`facts/${c}`]=r);}return Object.keys(e).length>0?e:void 0})()}}function K(m){let t=m,e=Array.isArray(t.checks)?t.checks:[],a=t.integrityStats,c=t.backendAvailable,r=a?{nodes:a.nodes??0,edges:a.edges??0,file_hashes:0,fts:a.memory_facts_fts??0,node_embeddings:a.memory_vectors??0,embedding_cache:a.embedding_cache??0,parse_errors:0,unresolved_refs:0,name_segment_vocab:0,project_metadata:0,meta:a.meta??0}:void 0;return {packageName:"memory",healthy:typeof t.healthy=="boolean"?t.healthy:false,durationMs:typeof t.durationMs=="number"?t.durationMs:0,checks:e.map(n=>({code:typeof n.code=="string"?n.code:"",severity:n.severity??"info",name:typeof n.name=="string"?n.name:"",message:typeof n.message=="string"?n.message:"",durationMs:typeof n.durationMs=="number"?n.durationMs:void 0,details:n.details})),dbStats:r,backendAvailable:c}}exports.a=S;exports.b=v;exports.c=C;exports.d=E;
@@ -1,4 +1,4 @@
1
- 'use strict';var chunkNVGACA7W_cjs=require('./chunk-NVGACA7W.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database');var d=utils.Log.create({service:"memory-schema-migrations"}),T=2,I=[{id:1,description:"v1 baseline: memory_facts / memory_vectors / embedding_cache / memory_facts_fts / nodes / edges / meta\uFF08\u4E0E v0.3.x createTables \u8F93\u51FA\u5BF9\u9F50\uFF0C\u8001 db \u8DD1\u8BE5\u8FC1\u79FB\u4E0D\u7834\u574F\u73B0\u6709\u8868\uFF09",up:[`CREATE TABLE IF NOT EXISTS memory_facts (
1
+ 'use strict';var chunkNVGACA7W_cjs=require('./chunk-NVGACA7W.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database');var T=utils.Log.create({service:"memory-schema-migrations"}),m=1,f=[{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
2
  id TEXT PRIMARY KEY,
3
3
  agent_id TEXT NOT NULL,
4
4
  session_id TEXT,
@@ -32,10 +32,11 @@
32
32
  id INTEGER PRIMARY KEY AUTOINCREMENT,
33
33
  name TEXT NOT NULL,
34
34
  type TEXT NOT NULL,
35
+ owner_agent_id TEXT,
35
36
  properties TEXT,
36
37
  createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
37
38
  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
+ )`,"CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name)","CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type)","CREATE INDEX IF NOT EXISTS idx_nodes_owner_agent_id ON nodes(owner_agent_id)","CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_name_type ON nodes(name, type)",`CREATE TABLE IF NOT EXISTS edges (
39
40
  id INTEGER PRIMARY KEY AUTOINCREMENT,
40
41
  source INTEGER NOT NULL,
41
42
  target INTEGER NOT NULL,
@@ -47,7 +48,24 @@
47
48
  )`,"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
49
  key TEXT PRIMARY KEY,
49
50
  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
+ )`]}];function p(n,e=m,t={}){n.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
51
52
  id INTEGER PRIMARY KEY,
52
53
  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 I){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{S(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 S(n,e){for(let r of e)try{n.exec(r);}catch(i){let a=i instanceof Error?i.message:String(i);if(_(a)){d.debug("migration: column already exists, skipping",{sql:r.slice(0,80)});continue}throw i}}function _(n){return /duplicate column name/i.test(n)}function g(n){try{let e=n.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(r=>r.id))}catch{return 0}}var c=utils.Log.create({service:"memory-database"}),p=class{constructor(e){chunkNVGACA7W_cjs.a(this,"db",null);chunkNVGACA7W_cjs.a(this,"storagePath");chunkNVGACA7W_cjs.a(this,"backend","better-sqlite3");chunkNVGACA7W_cjs.a(this,"initialized",false);chunkNVGACA7W_cjs.a(this,"initPromise",null);this.storagePath=e===":memory:"?e:utils.Filesystem.normalize(e);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize();try{await this.initPromise,this.initialized=!0;}catch(e){try{this.db&&this.db.close();}catch{}throw this.db=null,this.initPromise=null,e}}}async doInitialize(){try{let e=this.openConnection();e.initialize(),this.db=e,this.applyPragmas(),this.runAllMigrations();}catch(e){let r=e instanceof Error?e.message:String(e);throw c.error("Database initialization failed",{error:r}),e}}openConnection(){return database.createSyncSqliteConnection({path:this.storagePath,backend:this.backend,walMode:true,foreignKeys:true,busyTimeoutMs:5e3})}applyPragmas(){if(this.db)try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("foreign_keys = ON");}catch(e){c.warn("Failed to apply memory PRAGMAs",{error:String(e)});}}runAllMigrations(){if(!this.db)throw new Error("Database not initialized");let e=m(this.db,T);if(e.errors.length>0){let 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);}};exports.a=T;exports.b=I;exports.c=m;exports.d=g;exports.e=p;
54
+ )`);let r=n.prepare("SELECT id FROM schema_migrations").all(),s=new Set(r.map(i=>i.id)),a={applied:[],pending:[],errors:[],currentVersion:r.length===0?0:Math.max(...r.map(i=>i.id)),targetVersion:e};for(let i of f){if(i.id>e)break;if(s.has(i.id)){a.pending.push(i.id);continue}if(t.dryRun){a.applied.push(i.id);continue}try{R(n,i.up),n.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(i.id),s.add(i.id),a.applied.push(i.id),T.info("migration applied",{id:i.id,description:i.description});}catch(o){let d=o instanceof Error?o.message:String(o),c=i.up[0]??"";a.errors.push({migrationId:i.id,sql:c,error:d}),T.warn("migration step failed",{id:i.id,error:d,sqlCount:i.up.length});}}return a}function R(n,e){for(let t of e)try{n.exec(t);}catch(r){let s=r instanceof Error?r.message:String(r);if(C(s)){T.debug("migration: column already exists, skipping",{sql:t.slice(0,80)});continue}throw r}}function C(n){return /duplicate column name/i.test(n)}function u(n){try{let e=n.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(t=>t.id))}catch{return 0}}var l=utils.Log.create({service:"memory-database"}),h=class{constructor(e){chunkNVGACA7W_cjs.a(this,"db",null);chunkNVGACA7W_cjs.a(this,"storagePath");chunkNVGACA7W_cjs.a(this,"backend","better-sqlite3");chunkNVGACA7W_cjs.a(this,"initialized",false);chunkNVGACA7W_cjs.a(this,"initPromise",null);this.storagePath=e===":memory:"?e:utils.Filesystem.normalize(e);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize();try{await this.initPromise,this.initialized=!0;}catch(e){try{this.db&&this.db.close();}catch{}throw this.db=null,this.initPromise=null,e}}}async doInitialize(){try{let e=this.openConnection();e.initialize(),this.db=e,this.applyPragmas(),this.runAllMigrations();}catch(e){let t=e instanceof Error?e.message:String(e);throw l.error("Database initialization failed",{error:t}),e}}openConnection(){return database.createSyncSqliteConnection({path:this.storagePath,backend:this.backend,walMode:true,foreignKeys:true,busyTimeoutMs:5e3})}applyPragmas(){if(this.db)try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("foreign_keys = ON");}catch(e){l.warn("Failed to apply memory PRAGMAs",{error:String(e)});}}runAllMigrations(){if(!this.db)throw new Error("Database not initialized");let e=p(this.db,m);if(e.errors.length>0){let t=e.errors.map(r=>`migration ${r.migrationId}: ${r.error}`).join("; ");throw new Error(`Some migrations failed: ${t}`)}}query(e,t){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let r=this.db.prepare(e);return t?r.all(...t):r.all()}catch(r){throw new Error(`Query failed: ${r.message}`)}}agentFilter(e){return typeof e=="string"&&e.trim().length>0?{where:"WHERE agent_id = ?",params:[e.trim()]}:{where:"",params:[]}}run(e,t){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let r=this.db.prepare(e),s=t?r.run(...t):r.run();return {lastID:Number(s.lastInsertRowid),changes:s.changes}}catch(r){throw new Error(`Write failed: ${r.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 u(this.db)}close(){if(this.db){try{this.db.close();}catch(e){l.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}}checkIntegrity(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");let e=N=>this.db.prepare(N).get().c,t={memory_facts:e("SELECT COUNT(*) as c FROM memory_facts"),memory_vectors:e("SELECT COUNT(*) as c FROM memory_vectors"),embedding_cache:e("SELECT COUNT(*) as c FROM embedding_cache"),memory_facts_fts:e("SELECT COUNT(*) as c FROM memory_facts_fts"),nodes:e("SELECT COUNT(*) as c FROM nodes"),edges:e("SELECT COUNT(*) as c FROM edges"),meta:e("SELECT COUNT(*) as c FROM meta"),schema_migrations:e("SELECT COUNT(*) as c FROM schema_migrations")},r=[],s=e(`
55
+ SELECT COUNT(*) as c FROM (
56
+ SELECT mf.id, JSON_EACH.value AS node_id
57
+ FROM memory_facts mf, JSON_EACH(mf.node_ids)
58
+ WHERE mf.node_ids IS NOT NULL
59
+ ) LEFT JOIN nodes n ON n.id = CAST(node_id AS INTEGER)
60
+ WHERE n.id IS NULL
61
+ `);s>0&&r.push({severity:"error",message:`orphan node references (fact.nodeIds): ${s}`});let a=e(`
62
+ SELECT COUNT(*) as c FROM edges e WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.source)
63
+ `);a>0&&r.push({severity:"error",message:`orphan edges (source): ${a}`});let i=e(`
64
+ SELECT COUNT(*) as c FROM edges e WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.target)
65
+ `);i>0&&r.push({severity:"error",message:`orphan edges (target): ${i}`});let o=e("SELECT COUNT(*) as c FROM edges WHERE source = target");o>0&&r.push({severity:"warn",message:`self-loop edges: ${o}`});let d=e(`
66
+ SELECT COUNT(*) as c FROM (
67
+ SELECT fact_id FROM memory_facts_fts
68
+ EXCEPT
69
+ SELECT id FROM memory_facts
70
+ )
71
+ `);d>0&&r.push({severity:"warn",message:`FTS out of sync (orphan entries): ${d}`});let c=e("SELECT COUNT(*) as c FROM (SELECT id, COUNT(*) as c FROM memory_facts GROUP BY id HAVING c > 1)");c>0&&r.push({severity:"error",message:`duplicate fact ids: ${c}`});let g=e("SELECT COUNT(*) as c FROM memory_facts WHERE content IS NULL OR content = ''");return g>0&&r.push({severity:"error",message:`memory_facts with null/empty content: ${g}`}),{issues:r,stats:t}}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}};exports.a=m;exports.b=f;exports.c=p;exports.d=u;exports.e=h;
@@ -0,0 +1 @@
1
+ 'use strict';var ai=require('ai'),utils=require('@easbot/utils');exports.a=void 0;(a=>{let s=utils.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 ai.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 ai.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;})(exports.a||(exports.a={}));var P=exports.a;exports.b=P;
@@ -0,0 +1,71 @@
1
+ import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Filesystem}from'@easbot/utils';import {createSyncSqliteConnection}from'@easbot/database';var T=Log.create({service:"memory-schema-migrations"}),m=1,R=[{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
+ owner_agent_id TEXT,
36
+ properties TEXT,
37
+ createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
38
+ updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP
39
+ )`,"CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name)","CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type)","CREATE INDEX IF NOT EXISTS idx_nodes_owner_agent_id ON nodes(owner_agent_id)","CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_name_type ON nodes(name, type)",`CREATE TABLE IF NOT EXISTS edges (
40
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
41
+ source INTEGER NOT NULL,
42
+ target INTEGER NOT NULL,
43
+ relation TEXT NOT NULL,
44
+ properties TEXT,
45
+ createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
46
+ FOREIGN KEY (source) REFERENCES nodes(id) ON DELETE CASCADE,
47
+ FOREIGN KEY (target) REFERENCES nodes(id) ON DELETE CASCADE
48
+ )`,"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 (
49
+ key TEXT PRIMARY KEY,
50
+ value TEXT
51
+ )`]}];function p(n,e=m,t={}){n.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
52
+ id INTEGER PRIMARY KEY,
53
+ applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
54
+ )`);let r=n.prepare("SELECT id FROM schema_migrations").all(),s=new Set(r.map(i=>i.id)),a={applied:[],pending:[],errors:[],currentVersion:r.length===0?0:Math.max(...r.map(i=>i.id)),targetVersion:e};for(let i of R){if(i.id>e)break;if(s.has(i.id)){a.pending.push(i.id);continue}if(t.dryRun){a.applied.push(i.id);continue}try{C(n,i.up),n.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(i.id),s.add(i.id),a.applied.push(i.id),T.info("migration applied",{id:i.id,description:i.description});}catch(o){let d=o instanceof Error?o.message:String(o),c=i.up[0]??"";a.errors.push({migrationId:i.id,sql:c,error:d}),T.warn("migration step failed",{id:i.id,error:d,sqlCount:i.up.length});}}return a}function C(n,e){for(let t of e)try{n.exec(t);}catch(r){let s=r instanceof Error?r.message:String(r);if(I(s)){T.debug("migration: column already exists, skipping",{sql:t.slice(0,80)});continue}throw r}}function I(n){return /duplicate column name/i.test(n)}function u(n){try{let e=n.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(t=>t.id))}catch{return 0}}var l=Log.create({service:"memory-database"}),h=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 t=e instanceof Error?e.message:String(e);throw l.error("Database initialization failed",{error:t}),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){l.warn("Failed to apply memory PRAGMAs",{error:String(e)});}}runAllMigrations(){if(!this.db)throw new Error("Database not initialized");let e=p(this.db,m);if(e.errors.length>0){let t=e.errors.map(r=>`migration ${r.migrationId}: ${r.error}`).join("; ");throw new Error(`Some migrations failed: ${t}`)}}query(e,t){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let r=this.db.prepare(e);return t?r.all(...t):r.all()}catch(r){throw new Error(`Query failed: ${r.message}`)}}agentFilter(e){return typeof e=="string"&&e.trim().length>0?{where:"WHERE agent_id = ?",params:[e.trim()]}:{where:"",params:[]}}run(e,t){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let r=this.db.prepare(e),s=t?r.run(...t):r.run();return {lastID:Number(s.lastInsertRowid),changes:s.changes}}catch(r){throw new Error(`Write failed: ${r.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 u(this.db)}close(){if(this.db){try{this.db.close();}catch(e){l.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}}checkIntegrity(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");let e=N=>this.db.prepare(N).get().c,t={memory_facts:e("SELECT COUNT(*) as c FROM memory_facts"),memory_vectors:e("SELECT COUNT(*) as c FROM memory_vectors"),embedding_cache:e("SELECT COUNT(*) as c FROM embedding_cache"),memory_facts_fts:e("SELECT COUNT(*) as c FROM memory_facts_fts"),nodes:e("SELECT COUNT(*) as c FROM nodes"),edges:e("SELECT COUNT(*) as c FROM edges"),meta:e("SELECT COUNT(*) as c FROM meta"),schema_migrations:e("SELECT COUNT(*) as c FROM schema_migrations")},r=[],s=e(`
55
+ SELECT COUNT(*) as c FROM (
56
+ SELECT mf.id, JSON_EACH.value AS node_id
57
+ FROM memory_facts mf, JSON_EACH(mf.node_ids)
58
+ WHERE mf.node_ids IS NOT NULL
59
+ ) LEFT JOIN nodes n ON n.id = CAST(node_id AS INTEGER)
60
+ WHERE n.id IS NULL
61
+ `);s>0&&r.push({severity:"error",message:`orphan node references (fact.nodeIds): ${s}`});let a=e(`
62
+ SELECT COUNT(*) as c FROM edges e WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.source)
63
+ `);a>0&&r.push({severity:"error",message:`orphan edges (source): ${a}`});let i=e(`
64
+ SELECT COUNT(*) as c FROM edges e WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.target)
65
+ `);i>0&&r.push({severity:"error",message:`orphan edges (target): ${i}`});let o=e("SELECT COUNT(*) as c FROM edges WHERE source = target");o>0&&r.push({severity:"warn",message:`self-loop edges: ${o}`});let d=e(`
66
+ SELECT COUNT(*) as c FROM (
67
+ SELECT fact_id FROM memory_facts_fts
68
+ EXCEPT
69
+ SELECT id FROM memory_facts
70
+ )
71
+ `);d>0&&r.push({severity:"warn",message:`FTS out of sync (orphan entries): ${d}`});let c=e("SELECT COUNT(*) as c FROM (SELECT id, COUNT(*) as c FROM memory_facts GROUP BY id HAVING c > 1)");c>0&&r.push({severity:"error",message:`duplicate fact ids: ${c}`});let g=e("SELECT COUNT(*) as c FROM memory_facts WHERE content IS NULL OR content = ''");return g>0&&r.push({severity:"error",message:`memory_facts with null/empty content: ${g}`}),{issues:r,stats:t}}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}};export{m as a,R as b,p as c,u as d,h as e};
@@ -0,0 +1,60 @@
1
+ import {t,v as v$1,i,h,j,g,f as f$1,e,d,c,w as w$1}from'./chunk-UF2Y2Q4L.mjs';import {ToolRegistry,createAndStartStdioServer,formatFailClosed}from'@easbot/mcp';import {Log,Locale,TruncateContent}from'@easbot/utils';var te=Log.create({service:"memory-format-truncate"}),Q="**`";var z=24e3,J=25e3;async function f(e,n={}){let r=n.softLimit??z,s=n.hardCeiling??J,o=n.toolName??"memory",c=n.writeToDisk!==false;if(e.length<=r)return {content:e,truncated:false};let i=e.slice(0,s),t=i.lastIndexOf(`
2
+ ${Q}`),a=i.lastIndexOf(`
3
+ `),u;t>s*.5?u=t:a>0?u=a:u=-1;let d=u>0?i.slice(0,u):i,l=d+"\n\n... (output truncated to budget; the source above is complete and verbatim \u2014 treat it as already Read. For any area not covered, make ANOTHER `<tool>` targeting those names \u2014 do NOT Read these files.)";if(!c)return {content:l,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-d.length}/${e.length} characters truncated ...`};try{let g=await TruncateContent.truncate(e,{maxChars:d.length,direction:"head",label:`${o}-output`});return g.truncated?{content:l,truncated:!0,outputPath:g.outputPath,hint:TruncateContent.formatHint(g),info:`... ${g.removedLength}/${g.originalLength} characters truncated ...`}:{content:l,truncated:!0,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-d.length}/${e.length} characters truncated ...`}}catch(g){return te.warn("TruncateContent.truncate failed, returning without disk hint",{error:g instanceof Error?g.message:String(g)}),{content:l,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-d.length}/${e.length} characters truncated ...`}}}function $(e,n={}){let r=n.softLimit??z,s=n.hardCeiling??J;if(e.length<=r)return {content:e,truncated:false};let o=e.slice(0,s),c=o.lastIndexOf(`
4
+ ${Q}`),i=o.lastIndexOf(`
5
+ `),t;c>s*.5?t=c:i>0?t=i:t=-1;let a=t>0?o.slice(0,t):o;return {content:a+`
6
+
7
+ ... (output truncated; tail dropped at section boundary)`,truncated:true,outputPath:"",hint:"",info:`... ${e.length-a.length}/${e.length} characters truncated ...`}}function ne(e,n){if(!e||e.length===0)return null;let r=e.filter(o=>n.has(o.path));return r.length===0?null:`\u26A0\uFE0F Index may be stale for: ${r.map(o=>`${o.path} (edited pending)`).join(", ")}
8
+
9
+ `}function I(e,n,r={}){return (X[e]??X.default).replace(/<(\w+)>/g,(o,c)=>c==="tool"?n:r[c]??`<${c}>`)}var X={recall:"If you need more facts, make ANOTHER `<tool>` query with a different scope / interval.\nIf you have enough context, proceed with the current task. Do NOT call `<tool>` again for the same query.",remember:"Memory persisted. To recall it later, use `<tool>` with the same query.\nDo NOT call `<tool>` again to verify \u2014 the fact is already in the database.",forget:"Memory deleted. To verify, run `<tool>` with the same filter (no results expected).\nIf you deleted too much, the data is gone (no auto-restore).",graph_query:"If you need to explore further, make ANOTHER `<tool>` from a different start node or depth.\nOtherwise, the graph is complete for this scope.",status:"Status snapshot. To inspect a specific fact, use `<tool>` (recall) with its id.\nOtherwise, this is a complete read.",consolidate:"Consolidation done. To inspect the new facts, use `<tool>` with the same agentId.\nIf you want to undo, archives are in <archive_dir>.",doctor:"Doctor report. To fix a failing check, run with `repair=true`.\nRe-run after fix to confirm.",default:"If you need more, make ANOTHER `<tool>` with refined parameters.\nOtherwise, this is a complete read."};function Z(e,n,r,s){let o=e.tags&&e.tags.length>0?`
10
+ - tags: ${e.tags.join(", ")}`:"",c=e.sessionId?`
11
+ - session: ${e.sessionId}`:"",i=e.msgId?`
12
+ - msg: ${e.msgId}`:"",t=typeof n=="number"?`
13
+ - score: ${n.toFixed(3)}${r?` (${r})`:""}`:"",a=e.truncated?" [truncated]":"",u="";if(s&&s.length>0){let d=[];for(let m of s){let l=[];if(m.edges&&m.edges.length>0)for(let y of m.edges){let b=y.direction??(y.source===m.id?"out":"in"),R=y.targetNode?.name??String(y.target),C=y.targetNode?.type??"node";l.push(` --[${b}] ${y.relation}--> ${R} (${C})`);}let g=l.length>0?l.join(`
14
+ `):" (no relations)";d.push(` - Node: ${m.name} (${m.type})
15
+ ${g}`);}u=`
16
+ - linked KG nodes (${s.length}):
17
+ ${d.join(`
18
+ `)}`;}return [`### \`${e.id}\`${a}`,` - agentId: ${e.agentId}`,` - category: ${e.category}`,` - importance: ${e.importance}`,` - createdAt: ${e.createdAt}`,` - updatedAt: ${e.updatedAt}`,` - source: ${e.source}${t}${o}${c}${i}${u}`,"",e.content,""].join(`
19
+ `)}async function v(e,n){let r=n.toolName??"memory_recall",s=`**\`memory_recall:${n.query.slice(0,40).replace(/[^a-zA-Z0-9_]/g,"_")}\`**`,o=ne(n.pendingFiles,new Set),i=[`Found ${e.total} fact(s) for query "${n.query}" (agentId=${n.agentId}, scope=${n.scope}):`,"",o??"",s].join(`
20
+ `),t=new Map;for(let m of e.hits){let l=m.fact.category;t.has(l)||t.set(l,[]),t.get(l).push(m);}let a=Array.from(t.entries()).map(([m,l])=>{let g=`**\`category:${m}\`**`,y=l.map(b=>Z(b.fact,b.score,b.source,b.nodes)).join(`
21
+ `);return `${g}
22
+
23
+ ${y}`}).join(`
24
+ `),u=e.warnings&&e.warnings.length>0?`
25
+
26
+ \u26A0\uFE0F warnings:
27
+ ${e.warnings.map(m=>` - ${m}`).join(`
28
+ `)}
29
+ `:"",d=`${i}
30
+
31
+ ${a}${u}
32
+
33
+ ${I("recall",r)}`;return n.sync?$(d,{}).content:(await f(d,{toolName:r,writeToDisk:n.writeToDisk})).content}async function x(e,n={}){let r=n.toolName??"memory_remember",s=`**\`memory_remember:${e.fact.id}\`**`,o=Z(e.fact),c=e.nodeIds??[],i=c.length>0?`
34
+ - linked KG nodes: ${c.join(", ")}
35
+ `:"",t=`${s}
36
+
37
+ ${o}${i}
38
+
39
+ ${I("remember",r)}`;return n.sync?$(t,{}).content:(await f(t,{toolName:r,writeToDisk:n.writeToDisk})).content}async function N(e,n={}){let r=n.toolName??"memory_forget",s="**`memory_forget:result`**",o=e.dryRun?"**DRY RUN** \u2014 no facts were actually deleted. Run again without dryRun to execute.":`Deleted ${e.deletedCount} fact(s).`,c=e.truncatedCount>0?` (truncated: ${e.truncatedCount} more, re-run with narrower filter)`:"",i=[s,"",o+c,"",e.deletedIds.length>0?`deleted ids:
40
+ ${e.deletedIds.map(t=>` - ${t}`).join(`
41
+ `)}`:"(no ids to show)","",I("forget",r)].join(`
42
+ `);return n.sync?$(i,{}).content:(await f(i,{toolName:r,writeToDisk:n.writeToDisk})).content}async function M(e,n={}){let r=n.toolName??"memory_graph_query",s=`**\`memory_graph_query:scope=${e.scope}\`**`,o=e.nodes.map(t=>` - node #${t.id}: ${t.name} (${t.type})${t.ownerAgentId?` [owner=${t.ownerAgentId}]`:" [shared]"}`).join(`
43
+ `),c=e.edges.map(t=>` - edge #${t.id}: ${t.source} --${t.relation}--> ${t.target}`).join(`
44
+ `),i=[s,"",`nodes (${e.nodes.length}${e.truncated?` / total ${e.totalNodes}`:""}):`,o||" (none)","",`edges (${e.edges.length}${e.truncated?` / total ${e.totalEdges}`:""}):`,c||" (none)","",I("graph_query",r)].join(`
45
+ `);return n.sync?$(i,{}).content:(await f(i,{toolName:r,writeToDisk:n.writeToDisk})).content}async function A(e,n={}){let r=n.toolName??"memory_status",c=["**`memory_status`**","",`dbPath: ${e.dbPath}`,`workspaceDir: ${e.workspaceDir}`,`factsCount: ${e.factsCount}`,`nodesCount: ${e.nodesCount} (KG nodes)`,`edgesCount: ${e.edgesCount} (KG edges)`,`ftsAvailable: ${e.ftsAvailable?"yes":"no"}`,`vectorEnabled: ${e.vectorEnabled?"yes":"no"}`,`kgScopeEnabled: ${e.kgScopeEnabled?"yes":"no"}`,`healthy: ${e.healthy?"yes":"no"}`,"","factsByCategory:",...Object.entries(e.factsByCategory).map(([i,t])=>` - ${i}: ${t}`),"","meta:",...Object.entries(e.meta).map(([i,t])=>` - ${i}: ${t}`),"",I("status",r)].join(`
46
+ `);return n.sync?$(c,{}).content:(await f(c,{toolName:r,writeToDisk:n.writeToDisk})).content}async function _(e,n={}){let r=n.toolName??"memory_consolidate",o=["**`memory_consolidate:result`**","",`total facts scanned: ${e.totalFacts}`,`deduped (merged): ${e.dedupedCount}`,`compressed: ${e.compressedCount}`,`archived to archive/: ${e.archivedCount}`,`skipped (no change): ${e.skippedCount}`,`duration: ${e.durationMs}ms`,"",I("consolidate",r)].join(`
47
+ `);return n.sync?$(o,{}).content:(await f(o,{toolName:r,writeToDisk:n.writeToDisk})).content}var S=20;async function O(e,n={}){let r=n.toolName??"memory_sync",o=[`**\`memory_sync:${e.dryRun?"DRY_RUN":"OK"}\`**`,"",`windowDays: ${e.windowDays} (threshold: ${e.archiveThreshold})`,"","## Stage A (db \u2192 .md)",`- generated: ${e.generatedCount}`,`- skipped (idempotent): ${e.skippedCount}`,`- failed (best-effort): ${e.failedGenerateCount}`,"","## Stage B (active/ \u2192 archive/)",`- ${e.dryRun?"would archive":"archived"}: ${e.archivedCount}`];if(e.archivedRecords.length>0){o.push("","### Archived records:");let i=e.archivedRecords.slice(0,S);for(let t of i)o.push(`- ${t.firstFactId} (${t.firstCreatedAt})`),o.push(` - source: \`${t.source}\``),o.push(` - target: \`${t.target}\``);e.archivedRecords.length>S&&o.push(`... and ${e.archivedRecords.length-S} more (use --json for full list)`);}o.push("",`duration: ${e.durationMs}ms`,"",I("sync",r));let c=o.join(`
48
+ `);return n.sync?$(c,{}).content:(await f(c,{toolName:r,writeToDisk:n.writeToDisk})).content}async function P(e,n={}){let r=n.toolName??"memory_doctor",s=`**\`memory_doctor:${e.healthy?"OK":"ISSUES"}\`**`,o=t=>t?"\u2705":"\u274C",c=e.checks.map(t=>`${o(t.passed)} ${t.name}: ${t.message}`).join(`
49
+ `),i=[s,"",c,"",I("doctor",r)].join(`
50
+ `);return n.sync?$(i,{}).content:(await f(i,{toolName:r,writeToDisk:n.writeToDisk})).content}async function w(e,n,r={}){let s=n,o=typeof s.kind=="string";switch((o?s:{kind:e}).kind){case "recall":{let i=o?{hits:s.hits,total:s.totalCount??s.total??0,truncated:s.truncated??false}:n;return v(i,{...r,query:s.query??r.query??"",agentId:s.agentId??r.agentId??"",scope:s.scope??r.scope??"agent_only"})}case "remember":{let i=o?{fact:s.fact,nodeIds:s.nodeIds}:n;return x(i,r)}case "forget":return N(o?s:n,r);case "graph_query":return M(o?s:n,r);case "status":return A(o?s:n,r);case "consolidate":return _(o?s:n,r);case "sync":return O(o?s:n,r);case "doctor":return P(o?s:n,r);default:throw new Error(`renderOperationMarkdown: unsupported op "${e}"`)}}var E=Log.create({service:"memory-mcp-stdio"});function ye(e){let n=new Map,r=e.isRemote??true,s=!r;function o(t){let a=Locale.resolveLocaleLang();return {agentId:t.agentId??e.agentId,isTrustedLocal:t.isTrustedLocal??s,remote:r,locale:a,dbPath:e.dbPath,workspaceDir:e.workspaceDir,rootDir:e.workspaceDir,config:w$1({agentId:e.agentId,dbPath:e.dbPath})}}function c(t,a){return {content:[{type:"text",text:t}],isError:a}}function i(t){return formatFailClosed(t,s)}return n.set("recall",async t=>{try{let a=t,u=o({agentId:a.agentId}),d=await v$1("recall",t,u);return {content:[{type:"text",text:await w("recall",d,{toolName:"memory_recall",query:a.query,agentId:a.agentId??e.agentId,scope:a.scope??"agent_only"})}]}}catch(a){return c(i(a),true)}}),n.set("remember",async t=>{try{let u=o({agentId:t.agentId}),d=await v$1("remember",t,u);return {content:[{type:"text",text:await w("remember",d,{toolName:"memory_remember"})}]}}catch(a){return c(i(a),true)}}),n.set("forget",async t=>{try{let u=o({agentId:t.agentId}),d=await v$1("forget",t,u);return {content:[{type:"text",text:await w("forget",d,{toolName:"memory_forget"})}]}}catch(a){return c(i(a),true)}}),n.set("extract",async t=>{try{let u=o({agentId:t.agentId}),m=await v$1("extract",t,u);return {content:[{type:"text",text:`Extract completed.
51
+ sessionId: ${t.sessionId??"(unknown)"}
52
+ extractedCount: ${m.extractedCount}
53
+ factIds: ${m.factIds.length>0?m.factIds.join(", "):"(none)"}
54
+ messageRange: ${m.messageRange.fromMessageId} -> ${m.messageRange.toMessageId}
55
+ `}]}}catch(a){return c(i(a),true)}}),n.set("consolidate",async t=>{try{let u=o({agentId:t.agentId,isTrustedLocal:!0}),d=await v$1("consolidate",t,u);return {content:[{type:"text",text:await w("consolidate",d,{toolName:"memory_consolidate"})}]}}catch(a){return c(i(a),true)}}),n.set("sync",async t=>{try{let u=t.agentId?.trim();if(!u)return c(i(new Error("memory_sync: agentId is required (sync requires agentId, see ADR 0069)")),!0);let d=o({agentId:u,isTrustedLocal:!0}),m=await v$1("sync",t,d);return {content:[{type:"text",text:await w("sync",m,{toolName:"memory_sync"})}]}}catch(a){return c(i(a),true)}}),n.set("graph_query",async t=>{try{let a=t,u=o({agentId:a.agentId}),d=await v$1("graph_query",t,u);return {content:[{type:"text",text:await w("graph_query",d,{toolName:"memory_graph_query",scope:a.scope??"agent_only"})}]}}catch(a){return c(i(a),true)}}),n.set("status",async t=>{try{let u=o({agentId:(t??{}).agentId}),d=await v$1("status",t,u);return {content:[{type:"text",text:await w("status",d,{toolName:"memory_status"})}]}}catch(a){return c(i(a),true)}}),n.set("doctor",async t=>{try{let u=o({agentId:(t??{}).agentId,isTrustedLocal:!0}),d=await v$1("doctor",t,u);return {content:[{type:"text",text:await w("doctor",d,{toolName:"memory_doctor"})}]}}catch(a){return c(i(a),true)}}),n.set("init",async t=>{try{let a=o({isTrustedLocal:!0}),d=await v$1("init",t,a);return {content:[{type:"text",text:`Init complete.
56
+ dbPath: ${d.dbPath}
57
+ tablesCreated: ${d.tablesCreated}
58
+ migrationsApplied: ${d.migrationsApplied}
59
+ durationMs: ${d.durationMs}
60
+ `}]}}catch(a){return c(i(a),true)}}),n}var fe={recall:c,remember:d,forget:e,extract:f$1,consolidate:g,sync:j,graph_query:h,init:i};function $e(e,n){let r=t[e],s={title:r?.annotations?.defaultDescription??e,readOnlyHint:r?.annotations?.readOnlyHint??false,destructiveHint:r?.annotations?.destructiveHint??false,idempotentHint:r?.annotations?.idempotentHint??true,openWorldHint:false},o=fe[e];return {name:e,description:r?.annotations?.defaultDescription??`memory op: ${e}`,inputSchema:o??{type:"object",properties:{},required:[]},annotations:s,handler:n}}var V;(r=>{async function e(s,o){let{getMemoryDbPath:c,getInstance:i}=await import('./interfaces-LPJU4KS3.mjs'),a=o!==null&&typeof o=="object"&&"agentId"in o&&"dbPath"in o?o:{agentId:process.env.EASBOT_AGENT_ID??"default",dbPath:c(),workspaceDir:i().worktree,isRemote:false},u=new ToolRegistry,d=ye(a),m=Object.keys(t);for(let p of m){let L=d.get(p);if(!L)throw new Error(`MemoryStdioServer.start: missing handler for tool "${p}"`);u.register($e(p,L));}E.info("starting memory MCP stdio server",{id:s.id,name:s.name,toolCount:m.length,isRemote:a.isRemote??true});let l=await createAndStartStdioServer(s,u),g=null,y=new Promise(p=>{g=p;}),b=p=>{E.info("received signal, stopping MCP server",{signal:p}),g?.();},R=()=>b("SIGINT"),C=()=>b("SIGTERM");process.on("SIGINT",R),process.on("SIGTERM",C);try{await y;}finally{try{process.off("SIGINT",R),process.off("SIGTERM",C);}catch(p){E.warn("failed to remove signal handlers",{error:p instanceof Error?p.message:String(p)});}try{await l.stop();}catch(p){E.warn("server.stop failed during cleanup",{error:p instanceof Error?p.message:String(p)});}}return {id:s.id,name:s.name,version:s.version,tools:m}}r.start=e;function n(){return Object.keys(t)}r.getToolNames=n;})(V||(V={}));export{w as a,V as b};
@@ -1 +1 @@
1
- import {a}from'./chunk-BSKFK4RC.mjs';function s(r,t){return a(`memory.${r}.empty`,{fallback:t})}function g(r,t,m){return a(`memory.${r}.summary`,{vars:t,fallback:m})}function u(r,t,m){return a(`memory.${r}.item`,{vars:t,fallback:m})}export{s as a,g as b,u as c};
1
+ import {a}from'./chunk-SWYQLQ7Z.mjs';function s(r,t){return a(`memory.${r}.empty`,{fallback:t})}function g(r,t,m){return a(`memory.${r}.summary`,{vars:t,fallback:m})}function u(r,t,m){return a(`memory.${r}.item`,{vars:t,fallback:m})}export{s as a,g as b,u as c};