@easbot/memory 0.3.24 → 0.3.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.en.md +43 -30
  2. package/README.md +46 -32
  3. package/dist/chunks/chunk-4YADRVIU.mjs +1 -0
  4. package/dist/chunks/chunk-DW3CJUBO.cjs +1 -0
  5. package/dist/chunks/chunk-HY2LFKG7.cjs +67 -0
  6. package/dist/chunks/chunk-I5YSX4DQ.mjs +64 -0
  7. package/dist/chunks/chunk-P45OBSAC.cjs +64 -0
  8. package/dist/chunks/chunk-X7P7ZFZF.mjs +67 -0
  9. package/dist/chunks/cli-handler-ETHJPZPG.mjs +1 -0
  10. package/dist/chunks/cli-handler-PG4IBTY2.cjs +1 -0
  11. package/dist/chunks/consolidate-7GFUFPLX.cjs +2 -0
  12. package/dist/chunks/consolidate-BGMXJUQX.mjs +2 -0
  13. package/dist/chunks/{doctor-RNI5F6GO.mjs → doctor-C2FWFUDO.mjs} +1 -1
  14. package/dist/chunks/{doctor-SJY3K3DV.cjs → doctor-SCXUJRSG.cjs} +1 -1
  15. package/dist/chunks/extract-O4IOL6BZ.cjs +2 -0
  16. package/dist/chunks/extract-RBBSVK2S.mjs +2 -0
  17. package/dist/chunks/forget-JTACRG7Y.mjs +3 -0
  18. package/dist/chunks/forget-M4I6GVWI.cjs +3 -0
  19. package/dist/chunks/graph-AOMDJ6YA.cjs +3 -0
  20. package/dist/chunks/graph-VBVVRV6V.mjs +3 -0
  21. package/dist/chunks/init-2SBK7ZWO.mjs +1 -0
  22. package/dist/chunks/init-VTPJR56L.cjs +1 -0
  23. package/dist/chunks/{mcp-PRR2RYOP.cjs → mcp-VIOHPDO5.cjs} +1 -1
  24. package/dist/chunks/{mcp-RMLMXPZ7.mjs → mcp-ZQCLVZIR.mjs} +1 -1
  25. package/dist/chunks/recall-JSTQDGGZ.cjs +2 -0
  26. package/dist/chunks/recall-UQSG6ECA.mjs +2 -0
  27. package/dist/chunks/remember-GVQJ5G7Z.mjs +2 -0
  28. package/dist/chunks/remember-Z4UJJN62.cjs +2 -0
  29. package/dist/chunks/status-DH33MQZV.cjs +1 -0
  30. package/dist/chunks/status-VZ5EBAOY.mjs +1 -0
  31. package/dist/chunks/stdio-server-JC53PUET.mjs +1 -0
  32. package/dist/chunks/{stdio-server-SXDIW3RQ.cjs → stdio-server-OUZAN4IM.cjs} +1 -1
  33. package/dist/chunks/sync-6I2ZJUH6.cjs +2 -0
  34. package/dist/chunks/sync-UT4D32ML.mjs +2 -0
  35. package/dist/cli.cjs +1 -1
  36. package/dist/cli.mjs +1 -1
  37. package/dist/index.cjs +3 -3
  38. package/dist/index.d.cts +5 -2
  39. package/dist/index.d.ts +5 -2
  40. package/dist/index.mjs +1 -1
  41. package/package.json +9 -9
  42. package/dist/chunks/chunk-46Y7MLBE.cjs +0 -1
  43. package/dist/chunks/chunk-5VZKEZI4.cjs +0 -67
  44. package/dist/chunks/chunk-C3Z455VR.mjs +0 -67
  45. package/dist/chunks/chunk-GL5U3MRI.mjs +0 -64
  46. package/dist/chunks/chunk-MPGIP3IF.cjs +0 -64
  47. package/dist/chunks/chunk-PGJB2U24.mjs +0 -1
  48. package/dist/chunks/cli-handler-KTFW5CCH.mjs +0 -1
  49. package/dist/chunks/cli-handler-Y43WWXOO.cjs +0 -1
  50. package/dist/chunks/consolidate-VGPUQRPU.mjs +0 -2
  51. package/dist/chunks/consolidate-X52RRH2C.cjs +0 -2
  52. package/dist/chunks/extract-ANENWMHZ.mjs +0 -2
  53. package/dist/chunks/extract-L2V2RMDQ.cjs +0 -2
  54. package/dist/chunks/forget-QNG6GELC.mjs +0 -3
  55. package/dist/chunks/forget-SSGVAE5Y.cjs +0 -3
  56. package/dist/chunks/graph-KNLZRAPI.mjs +0 -3
  57. package/dist/chunks/graph-WIKKSBLC.cjs +0 -3
  58. package/dist/chunks/init-2UNKNWR5.mjs +0 -1
  59. package/dist/chunks/init-UNDHFDAC.cjs +0 -1
  60. package/dist/chunks/recall-7TPMD7ZE.mjs +0 -2
  61. package/dist/chunks/recall-M2EWX25U.cjs +0 -2
  62. package/dist/chunks/remember-BXVUUY5M.cjs +0 -2
  63. package/dist/chunks/remember-H5CYMLG5.mjs +0 -2
  64. package/dist/chunks/status-A2JC6NFH.cjs +0 -1
  65. package/dist/chunks/status-MJFDNSPW.mjs +0 -1
  66. package/dist/chunks/stdio-server-43QC3XIS.mjs +0 -1
  67. package/dist/chunks/sync-3RWIZYR6.cjs +0 -2
  68. package/dist/chunks/sync-GPRNZLZA.mjs +0 -2
package/README.en.md CHANGED
@@ -109,17 +109,17 @@ const md = await renderOperationMarkdown('recall', recallResult, { toolName: 'me
109
109
 
110
110
  ## 9 op manifest
111
111
 
112
- | op | trusted local only | agentId | purpose |
113
- |---|---|---|---|
114
- | `recall` | ❌ | ✅ required | Hybrid search (FTS + vector + graph) |
115
- | `remember` | ❌ | ✅ required | Persist a self-memory fact |
116
- | `forget` | ❌ | ✅ required | Delete by factId / category / time window (supports `dryRun`) |
117
- | `extract` | ❌ | ✅ required | Aggregate facts / KG nodes for a sessionId |
118
- | `consolidate` | ✅ | ✅ required | dedup → archive pipeline |
119
- | `graph_query` | ❌ (scope=both → ✅) | ⚠️ optional, defaults to `'default'` | KG nodes / edges / BFS neighbors |
120
- | `status` | ❌ | ⚠️ optional, defaults to global aggregate | System status snapshot |
121
- | `doctor` | ✅ | ⚠️ optional, defaults to whole-DB scan | Data integrity checks (supports `repair`) |
122
- | `init` | ✅ | ⚠️ optional, defaults to `'default'` | Initialize workspace (supports `force`) |
112
+ | op | trusted local only | agentId | purpose |
113
+ | ------------- | -------------------- | ----------------------------------------- | ------------------------------------------------------------- |
114
+ | `recall` | ❌ | ✅ required | Hybrid search (FTS + vector + graph) |
115
+ | `remember` | ❌ | ✅ required | Persist a self-memory fact |
116
+ | `forget` | ❌ | ✅ required | Delete by factId / category / time window (supports `dryRun`) |
117
+ | `extract` | ❌ | ✅ required | Aggregate facts / KG nodes for a sessionId |
118
+ | `consolidate` | ✅ | ✅ required | dedup → archive pipeline |
119
+ | `graph_query` | ❌ (scope=both → ✅) | ⚠️ optional, defaults to `'default'` | KG nodes / edges / BFS neighbors |
120
+ | `status` | ❌ | ⚠️ optional, defaults to global aggregate | System status snapshot |
121
+ | `doctor` | ✅ | ⚠️ optional, defaults to whole-DB scan | Data integrity checks (supports `repair`) |
122
+ | `init` | ✅ | ⚠️ optional, defaults to `'default'` | Initialize workspace (supports `force`) |
123
123
 
124
124
  **P0-A reversal note** (since v0.4.1):
125
125
 
@@ -163,20 +163,32 @@ import type { PreCompactHook, SessionStartHook, SessionEndHook, PostToolFailureH
163
163
 
164
164
  ```bash
165
165
  # Installed via package.json bin: easbot-memory
166
- easbot-memory init --workspace-dir <dir> [--agent <id>]
167
- easbot-memory status [--agent <id>] [--json]
168
- easbot-memory doctor [--repair] [--agent <id>]
169
- easbot-memory recall --query <q> --agent <id> [--limit <n>] [--json]
170
- easbot-memory remember --content <text> --category <c> --importance <1-10> --agent <id>
171
- easbot-memory forget --agent <id> [--fact-id <id>] [--dry-run]
172
- easbot-memory extract --session <sessionId> [--last-n <n>] --agent <id>
173
- easbot-memory consolidate --agent <id> [--window-days <n>]
174
- easbot-memory graph --kind <nodes|edges|neighbors> [--query <q>] [--agent <id>]
166
+ # 2026-09-25: agentId is injected via ctx (no --agent flag)
167
+ # - agent CLI (@easbot/agent): from protocol.json
168
+ # - standalone CLI: from .easbot/protocol.json
169
+ # - fallback: 'default'
170
+ easbot-memory init --workspace-dir <dir>
171
+ easbot-memory status [--json]
172
+ easbot-memory doctor [--repair]
173
+ easbot-memory recall --query <q> [--limit <n>] [--json]
174
+ easbot-memory remember --content <text> --category <c> --importance <1-10>
175
+ easbot-memory forget [--fact-id <id>] [--dry-run]
176
+ easbot-memory extract --session <sessionId> [--last-n <n>]
177
+ easbot-memory consolidate [--window-days <n>]
178
+ easbot-memory graph [--query <q>] [--node-id <id>]
175
179
  easbot-memory config [--json]
176
180
  easbot-memory mcp
177
181
  ```
178
182
 
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.
183
+ > Since v0.5.1 (2026-09-25 feedback): every op's `agentId` flows through **ctx injection** (no `--agent` flag parsing):
184
+ >
185
+ > - agent CLI (`@easbot/agent`): bridge handler reads `metadata.agentId` from `ContextEngine.getProtocolMetadata()` → `deps.agentId`
186
+ > - standalone CLI (`easbot-memory`): cli.ts reads `metadata.agentId` from `.easbot/protocol.json` → `deps.agentId`
187
+ > - agent tool (memory MCP / agent tool): `buildMemoryCtx` reads `ctx.protocolMetadata?.agentId` → opCtx.agentId
188
+ > - MCP stdio-server: host agent injects `ctxConfig.agentId` at server start → ctx.agentId
189
+ > - all absent → CLI falls back to `'default'` (display only; does not affect service filtering)
190
+ >
191
+ > `status` always returns a **global stats view** (no per-host-agent divergence); `agent_id` is exposed via `extras['agent_id']` as a display-only environment attribute.
180
192
 
181
193
  ## Status / Doctor Unified Output Format (Decision 0073 / CLI Spec v1.4)
182
194
 
@@ -242,14 +254,14 @@ $ easbot memory doctor
242
254
 
243
255
  ### Key Fields
244
256
 
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) |
257
+ | Field | Description |
258
+ | ---------------------------- | ---------------------------------------------------------------------------------------------------------- |
259
+ | `LLM.initialized` | Whether LLM is initialized (valid config + reachable) |
260
+ | `LLM.capabilities` | Three capabilities: `embedding` / `graphLlm` / `rerankLlm`, each shows model name or ✗ |
261
+ | `Vector enabled` | Whether vector index is enabled |
262
+ | `Embedding dims` | **Probed** embedding dimension (not just from config), probed at status end and written back to meta table |
263
+ | `embedding_dims_consistency` | Doctor check #9: compares meta / probe / config dimensions for consistency |
264
+ | `factsByCategory` | Memory unique: fact counts by category (shown in Counts section) |
253
265
 
254
266
  ### JSON Output (`--json`)
255
267
 
@@ -307,6 +319,7 @@ const tools = MemoryStdioServer.getToolNames();
307
319
  ```
308
320
 
309
321
  **9 tool manifest** (1:1 with `OP_REGISTRY`):
322
+
310
323
  - `memory_recall` / `memory_remember` / `memory_forget` / `memory_extract` / `memory_consolidate` / `memory_graph_query` / `memory_status` / `memory_doctor` / `memory_init`
311
324
 
312
325
  ### handleMemoryCli delegation
@@ -315,7 +328,7 @@ const tools = MemoryStdioServer.getToolNames();
315
328
  import { handleMemoryCli, setGlobalAdapter, setInstanceAdapter } from '@easbot/memory';
316
329
 
317
330
  // 1. Inject adapters (cli path / agent path)
318
- setGlobalAdapter({ Path: { /* ... */ } });
331
+ setGlobalAdapter({ Path: {/* ... */} });
319
332
  setInstanceAdapter({ directory: process.cwd(), worktree: process.cwd() });
320
333
 
321
334
  // 2. Delegate to unified handler
package/README.md CHANGED
@@ -87,6 +87,7 @@ await executeOp(
87
87
  ### KG scope 三档
88
88
 
89
89
  > **2026-09-23 PR-2 同步**:graph_query v0.5 schema 已简化(与 note.graph_query 对齐):
90
+ >
90
91
  > - **agent tool 主路径**只接受 `nodeId`(numeric)+ 可选 `maxEdgesPerNode`(默认 20 / 上限 100)
91
92
  > - `query / nodeId / type / depth / maxNodes / scope / relation / maxEdgesPerNode` 8 字段走 CLI `easbot memory graph query`
92
93
  > - `depth / maxNodes` service 端硬编码(depth=2 / maxNodes=100),agent tool 不暴露
@@ -119,18 +120,18 @@ const md = await renderOperationMarkdown('recall', recallResult, { toolName: 'me
119
120
 
120
121
  ## 9 op 清单
121
122
 
122
- | op | trusted local only | agentId | 用途 |
123
- |---|---|---|---|
124
- | `recall` | ❌ | ✅ 必填 | 混合搜索(FTS + vector + graph) |
125
- | `remember` | ❌ | ✅ 必填 | 持久化一条 self-memory fact |
126
- | `forget` | ❌ | ✅ 必填 | 按 factId / category / 时间窗删除(支持 `dryRun`) |
127
- | `extract` | ❌ | ✅ 必填 | 从 session 抽取 facts |
128
- | `consolidate` | ✅ | ✅ 必填 | 整理 / 去重 / 摘要 |
129
- | `sync` | ✅ | ✅ 必填 | db → .md 兜底生成(幂等)+ active/ 过期文件归档(默认 30 天) |
130
- | `graph_query` | ❌ (scope=both 时 ✅) | ⚠️ optional,缺省 `'default'` | KG 节点 / 边 / 邻居查询 |
131
- | `status` | ❌ | ⚠️ optional,缺省全局聚合 | 系统状态快照 |
132
- | `doctor` | ✅ | ⚠️ optional,缺省全库扫描 | 数据完整性检查(支持 `repair`) |
133
- | `init` | ✅ | ⚠️ optional,缺省 `'default'` | 初始化 workspace(支持 `force`) |
123
+ | op | trusted local only | agentId | 用途 |
124
+ | ------------- | --------------------- | ----------------------------- | ------------------------------------------------------------- |
125
+ | `recall` | ❌ | ✅ 必填 | 混合搜索(FTS + vector + graph) |
126
+ | `remember` | ❌ | ✅ 必填 | 持久化一条 self-memory fact |
127
+ | `forget` | ❌ | ✅ 必填 | 按 factId / category / 时间窗删除(支持 `dryRun`) |
128
+ | `extract` | ❌ | ✅ 必填 | 从 session 抽取 facts |
129
+ | `consolidate` | ✅ | ✅ 必填 | 整理 / 去重 / 摘要 |
130
+ | `sync` | ✅ | ✅ 必填 | db → .md 兜底生成(幂等)+ active/ 过期文件归档(默认 30 天) |
131
+ | `graph_query` | ❌ (scope=both 时 ✅) | ⚠️ optional,缺省 `'default'` | KG 节点 / 边 / 邻居查询 |
132
+ | `status` | ❌ | ⚠️ optional,缺省全局聚合 | 系统状态快照 |
133
+ | `doctor` | ✅ | ⚠️ optional,缺省全库扫描 | 数据完整性检查(支持 `repair`) |
134
+ | `init` | ✅ | ⚠️ optional,缺省 `'default'` | 初始化 workspace(支持 `force`) |
134
135
 
135
136
  **P0-A 反转说明**(v0.4.1 起):
136
137
 
@@ -172,16 +173,20 @@ import type { PreCompactHook, SessionStartHook, SessionEndHook, PostToolFailureH
172
173
 
173
174
  ```bash
174
175
  # 安装后即可用(package.json bin: easbot-memory)
175
- easbot-memory init --workspace-dir <dir> [--agent <id>]
176
- easbot-memory status [--agent <id>] [--json]
177
- easbot-memory doctor [--repair] [--agent <id>]
178
- easbot-memory recall --query <q> --agent <id> [--limit <n>] [--json]
179
- easbot-memory remember --content <text> --category <c> --importance <1-10> --agent <id>
180
- easbot-memory forget --agent <id> [--fact-id <id>] [--dry-run]
181
- easbot-memory extract --session <sessionId> [--last-n <n>] --agent <id>
182
- easbot-memory consolidate --agent <id> [--window-days <n>]
183
- easbot-memory sync --agent <id> [--window-days <n>] [--dry-run] [--json]
184
- easbot-memory graph --kind <nodes|edges|neighbors> [--query <q>] [--agent <id>]
176
+ # 2026-09-25 老侯反馈:所有 op 的 agentId 走 ctx 上下文(不再用 --agent flag)
177
+ # - agent CLI(@easbot/agent):从 protocol.json 注入
178
+ # - standalone CLI:从 .easbot/protocol.json 注入
179
+ # - 都没有 → 兜底 'default'
180
+ easbot-memory init --workspace-dir <dir>
181
+ easbot-memory status [--json]
182
+ easbot-memory doctor [--repair]
183
+ easbot-memory recall --query <q> [--limit <n>] [--json]
184
+ easbot-memory remember --content <text> --category <c> --importance <1-10>
185
+ easbot-memory forget [--fact-id <id>] [--dry-run]
186
+ easbot-memory extract --session <sessionId> [--last-n <n>]
187
+ easbot-memory consolidate [--window-days <n>]
188
+ easbot-memory sync [--window-days <n>] [--dry-run] [--json]
189
+ easbot-memory graph [--query <q>] [--node-id <id>]
185
190
  easbot-memory config [--json]
186
191
  easbot-memory mcp
187
192
  ```
@@ -250,14 +255,14 @@ $ easbot memory doctor
250
255
 
251
256
  ### 关键字段说明
252
257
 
253
- | 字段 | 说明 |
254
- |------|------|
255
- | `LLM.initialized` | LLM 是否已初始化(配置有效且可达) |
256
- | `LLM.capabilities` | 三大能力:`embedding` / `graphLlm` / `rerankLlm`,各显示模型名或 ✗ |
257
- | `Vector enabled` | 向量索引是否启用 |
258
- | `Embedding dims` | **实测** embedding 维度(非仅读 config),status 末尾探测并回填 meta 表 |
259
- | `embedding_dims_consistency` | doctor 第 9 项检查:对比 meta / probe / config 三方维度是否一致 |
260
- | `factsByCategory` | memory 独有:按 category 统计的 fact 数量(Counts 段展示) |
258
+ | 字段 | 说明 |
259
+ | ---------------------------- | ----------------------------------------------------------------------- |
260
+ | `LLM.initialized` | LLM 是否已初始化(配置有效且可达) |
261
+ | `LLM.capabilities` | 三大能力:`embedding` / `graphLlm` / `rerankLlm`,各显示模型名或 ✗ |
262
+ | `Vector enabled` | 向量索引是否启用 |
263
+ | `Embedding dims` | **实测** embedding 维度(非仅读 config),status 末尾探测并回填 meta 表 |
264
+ | `embedding_dims_consistency` | doctor 第 9 项检查:对比 meta / probe / config 三方维度是否一致 |
265
+ | `factsByCategory` | memory 独有:按 category 统计的 fact 数量(Counts 段展示) |
261
266
 
262
267
  ### JSON 输出(`--json`)
263
268
 
@@ -287,7 +292,15 @@ $ easbot memory status --json
287
292
 
288
293
  兼容 [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)。
289
294
 
290
- > v0.4.1 起:`init` / `status` / `doctor` / `graph` 的 `--agent` 为可选,缺省时 fallback 到 `'default'`(CLI / 一次性诊断场景无需 agent 上下文);其余 6 op(`recall` / `remember` / `forget` / `extract` / `consolidate` / `sync`)仍要求显式 `--agent`,缺失时返回非 0 退出码。
295
+ > v0.5.1 起(2026-09-25 老侯反馈):所有 op 的 `agentId` 统一走 **ctx 上下文注入**(不再从 `--agent` flag 解析):
296
+ >
297
+ > - agent CLI(`@easbot/agent`):bridge handler 从 `ContextEngine.getProtocolMetadata()` 读 `metadata.agentId` → `deps.agentId`
298
+ > - standalone CLI(`easbot-memory`):cli.ts 从 `.easbot/protocol.json` 读 `metadata.agentId` → `deps.agentId`
299
+ > - agent tool(memory MCP/agent tool):`buildMemoryCtx` 从 `ctx.protocolMetadata?.agentId` 拿 → opCtx.agentId
300
+ > - MCP stdio-server:host agent 启动时注入 `ctxConfig.agentId` → ctx.agentId
301
+ > - 都没有 → CLI 兜底 `'default'`(仅作显示,不影响 service 过滤逻辑)
302
+ >
303
+ > `status` 命令永远走**全局统计视图**(不因 host agent 不同而分叉数字);agentId 仅作为 extras 环境属性 `extras['agent_id']` 显示。
291
304
 
292
305
  ### Agent 委派模式(v0.4 stage 4 T-M017a)
293
306
 
@@ -317,6 +330,7 @@ const tools = MemoryStdioServer.getToolNames();
317
330
  ```
318
331
 
319
332
  **10 tool 清单**(与 `OP_REGISTRY` 一一对应):
333
+
320
334
  - `memory_recall` / `memory_remember` / `memory_forget` / `memory_extract` / `memory_consolidate` / `memory_sync` / `memory_graph_query` / `memory_status` / `memory_doctor` / `memory_init`
321
335
 
322
336
  ### handleMemoryCli 委派范式
@@ -325,7 +339,7 @@ const tools = MemoryStdioServer.getToolNames();
325
339
  import { handleMemoryCli, setGlobalAdapter, setInstanceAdapter } from '@easbot/memory';
326
340
 
327
341
  // 1. 注入 adapter(cli 路径 / agent 路径)
328
- setGlobalAdapter({ Path: { /* ... */ } });
342
+ setGlobalAdapter({ Path: {/* ... */} });
329
343
  setInstanceAdapter({ directory: process.cwd(), worktree: process.cwd() });
330
344
 
331
345
  // 2. 委派给统一 handler
@@ -0,0 +1 @@
1
+ import {f}from'./chunk-WDVDYZ25.mjs';import {Log}from'@easbot/utils';import {renderLines,printHuman,emitJsonOk,formatKnowledgeDoctor,formatKnowledgeStatus,formatKnowledgeInit,emitJsonError}from'@easbot/terminal';var b=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 g(p,t){let e=S.filter(s=>s.group===p);return renderLines({title:t,flat:e.map(s=>`$ easbot-memory ${s.name.padEnd(14)} ${s.description}`)})}function v(){let p=[renderLines({title:"easbot-memory \xB7 Memory & Knowledge Module for EASBot",flat:["Usage: easbot-memory <command> [options]"]}),"",g("lifecycle","Commands (lifecycle):"),"",g("memory","Commands (memory):"),"",g("session","Commands (session):"),"",g("graph","Commands (graph query):"),"",g("external","External:")];printHuman(p);}function j(){v(),printHuman(["",renderLines({title:"Global flags & invocation",flat:["--cwd <dir> --config <path> --log-level <L> --print-logs --debug","Standalone CLI: easbot-memory <command>","Agent CLI: easbot memory <command>"]})]);}async function C(p){try{let{bootstrapLlm:t}=await import('@easbot/llm'),{Llm:e}=await import('./llm-UHTBU2HA.mjs');await t({target:e,cwd:p,subConfigPath:".easbot/memory.json",embedding:!0,graph:!0});}catch(t){b.warn("bootstrapLlm failed; Llm-related features will be disabled",{error:t instanceof Error?t.message:String(t)});}}async function P(p,t){let[e,...s]=p,c=t?.cwd??process.cwd(),d=t?.agentId??"default";if(!e)return j(),{code:0,handled:true,command:null};await C(c);try{switch(e){case "init":{let{parseInitOptions:n,runInit:a}=await import('./init-2SBK7ZWO.mjs'),r=n(s);if(r.help)return console.log("Usage: easbot-memory init [dir] [--force] [--json]"),{code:0,handled:!0,command:e};let o=r.workspaceDir?.trim()??c,i=await a({...r,ctxWorkspaceDir:o,agentId:d});if(r.json)emitJsonOk(i,{command:e});else {let u=i;printHuman([formatKnowledgeInit({packageName:"memory",configPath:u.configPath??u.dbPath,backend:"better-sqlite3",schemaVersion:u.schemaVersion,extras:{dbPath:u.dbPath,migrationsApplied:u.migrationsApplied,tablesCreated:u.tablesCreated,durationMs:`${u.durationMs}ms`}})],{title:"init memory workspace",boxed:!0});}return {code:0,handled:!0,command:e}}case "recall":{let{parseRecallOptions:n,runRecall:a,formatRecallText:r}=await import('./recall-UQSG6ECA.mjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory recall --query <q> [--limit <n>] [--category <c>] [--min-importance <n>] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:`recall (agentId=${d??"default"})`}),{code:0,handled:!0,command:e}}case "remember":{let{parseRememberOptions:n,runRemember:a,formatRememberText:r}=await import('./remember-GVQJ5G7Z.mjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory remember --content <text> --category <c> --importance <1-10> [--tag <t>] [--session <s>] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:"remember (persist fact)"}),{code:0,handled:!0,command:e}}case "forget":{let{parseForgetOptions:n,runForget:a,formatForgetText:r}=await import('./forget-JTACRG7Y.mjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory forget (--fact-id <id> | --category <c> | --from <ISO> --to <ISO>) [--max-delete <n>] [--dry-run] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:"forget (delete facts)"}),{code:0,handled:!0,command:e}}case "extract":{let{parseExtractOptions:n,runExtract:a,formatExtractText:r}=await import('./extract-RBBSVK2S.mjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory extract --session <sessionId> [--last-n <n>] [--from-msg <id>] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:"extract (from session)"}),{code:0,handled:!0,command:e}}case "consolidate":{let{parseConsolidateOptions:n,runConsolidate:a,formatConsolidateText:r}=await import('./consolidate-BGMXJUQX.mjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory consolidate [--window-days <n>] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:"consolidate (pipeline)"}),{code:0,handled:!0,command:e}}case "sync":{let{parseSyncOptions:n,runSync:a,formatSyncText:r}=await import('./sync-UT4D32ML.mjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory sync [--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 a({...o,workspaceDir:c,agentId:d});return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:"sync (db \u2192 .md + archive)"}),{code:0,handled:!0,command:e}}case "graph":{let{parseGraphOptions:n,runGraph:a,formatGraphText:r}=await import('./graph-VBVVRV6V.mjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory graph [--query <q>] [--node-id <id>] [--max-depth <n>] [--max-nodes <n>] [--max-edges-per-node <n>] [--json]\n (note: `--depth` is an alias for `--max-depth`; old `--kind` / `--start-node` / `--scope` flags removed since service schema is strict)"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:"graph_query"}),{code:0,handled:!0,command:e}}case "status":{let{parseStatusOptions:n,runStatus:a}=await import('./status-VZ5EBAOY.mjs'),r=n(s);if(r.help)return console.log("Usage: easbot-memory status [--json]"),{code:0,handled:!0,command:e};let o=await a({...r,workspaceDir:c,agentId:d});return r.json?emitJsonOk(o,{command:e}):printHuman([formatKnowledgeStatus(K(o))],{title:"memory status",boxed:!0}),{code:0,handled:!0,command:e}}case "doctor":{let{parseDoctorOptions:n,runDoctor:a}=await import('./doctor-C2FWFUDO.mjs'),r=n(s);if(r.help)return console.log("Usage: easbot-memory doctor [--repair] [--json]"),{code:0,handled:!0,command:e};let o=await a({...r,workspaceDir:c});return r.json?emitJsonOk(o,{command:e}):printHuman([formatKnowledgeDoctor(M(o))],{title:"memory doctor",boxed:!0}),{code:0,handled:!0,command:e}}case "config":{let{parseConfigOptions:n,runConfig:a,formatConfigText:r}=await import('./config-2SQJYVTO.mjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory config [--json]"),{code:0,handled:!0,command:e};let i=a(o);return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:"memory config"}),{code:0,handled:!0,command:e}}case "mcp":{let{parseMcpOptions:n,runMcp:a}=await import('./mcp-ZQCLVZIR.mjs'),r=n(s);if(r.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 a(r);return r.json?emitJsonOk(o,{command:e}):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(n){let a=n instanceof Error?n.message:String(n);b.error("memory CLI command failed",{command:e,error:a,stack:n instanceof Error?n.stack:void 0});let r=t?.cwd??f().worktree;return console.error(`[memory] ${r} :: ${e} failed: ${a}`),emitJsonError(e,a),{code:1,handled:true,command:e}}}function K(p){let t=p;return {packageName:"memory",rootDir:t.workspaceDir??"",configPath:t.configPath??"",configExists:typeof t.configExists=="boolean"?t.configExists:true,dbPath:t.dbPath??"",dbExists:typeof t.dbExists=="boolean"?t.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,healthy:typeof t.healthy=="boolean"?t.healthy:true,recommendation:t.recommendation,dbStats:(()=>{let e=t.dbStats;if(e&&typeof e=="object"&&Object.keys(e).length>0)return {...e};let s=t.integrityStats;if(s&&typeof s=="object"&&Object.keys(s).length>0)return {...s}})(),extras:(()=>{let e={};if(typeof t.agentId=="string"&&(e.agent_id=t.agentId),typeof t.ftsAvailable=="boolean"&&(e.fts_available=t.ftsAvailable?"yes":"no"),t.factsByCategory&&typeof t.factsByCategory=="object"){let s=t.factsByCategory;for(let[c,d]of Object.entries(s))typeof d=="number"&&d>0&&(e[`facts/${c}`]=d);}if(t.meta&&typeof t.meta=="object")for(let[s,c]of Object.entries(t.meta))e[`meta/${s}`]=c===void 0?"\u2205":c;return Object.keys(e).length>0?e:void 0})()}}function M(p){let t=p,e=Array.isArray(t.checks)?t.checks:[],s=t.integrityStats,c=t.backendAvailable,d=s?{...s}: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:d,backendAvailable:c}}export{S as a,v as b,j as c,P as d,M as e};
@@ -0,0 +1 @@
1
+ 'use strict';var chunkCPRDIUQ4_cjs=require('./chunk-CPRDIUQ4.cjs'),utils=require('@easbot/utils'),terminal=require('@easbot/terminal');var b=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 g(p,t){let e=S.filter(s=>s.group===p);return terminal.renderLines({title:t,flat:e.map(s=>`$ easbot-memory ${s.name.padEnd(14)} ${s.description}`)})}function v(){let p=[terminal.renderLines({title:"easbot-memory \xB7 Memory & Knowledge Module for EASBot",flat:["Usage: easbot-memory <command> [options]"]}),"",g("lifecycle","Commands (lifecycle):"),"",g("memory","Commands (memory):"),"",g("session","Commands (session):"),"",g("graph","Commands (graph query):"),"",g("external","External:")];terminal.printHuman(p);}function j(){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 C(p){try{let{bootstrapLlm:t}=await import('@easbot/llm'),{Llm:e}=await import('./llm-7LQGYSUE.cjs');await t({target:e,cwd:p,subConfigPath:".easbot/memory.json",embedding:!0,graph:!0});}catch(t){b.warn("bootstrapLlm failed; Llm-related features will be disabled",{error:t instanceof Error?t.message:String(t)});}}async function A(p,t){let[e,...s]=p,c=t?.cwd??process.cwd(),d=t?.agentId??"default";if(!e)return j(),{code:0,handled:true,command:null};await C(c);try{switch(e){case "init":{let{parseInitOptions:n,runInit:a}=await import('./init-VTPJR56L.cjs'),r=n(s);if(r.help)return console.log("Usage: easbot-memory init [dir] [--force] [--json]"),{code:0,handled:!0,command:e};let o=r.workspaceDir?.trim()??c,i=await a({...r,ctxWorkspaceDir:o,agentId:d});if(r.json)terminal.emitJsonOk(i,{command:e});else {let u=i;terminal.printHuman([terminal.formatKnowledgeInit({packageName:"memory",configPath:u.configPath??u.dbPath,backend:"better-sqlite3",schemaVersion:u.schemaVersion,extras:{dbPath:u.dbPath,migrationsApplied:u.migrationsApplied,tablesCreated:u.tablesCreated,durationMs:`${u.durationMs}ms`}})],{title:"init memory workspace",boxed:!0});}return {code:0,handled:!0,command:e}}case "recall":{let{parseRecallOptions:n,runRecall:a,formatRecallText:r}=await import('./recall-JSTQDGGZ.cjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory recall --query <q> [--limit <n>] [--category <c>] [--min-importance <n>] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:`recall (agentId=${d??"default"})`}),{code:0,handled:!0,command:e}}case "remember":{let{parseRememberOptions:n,runRemember:a,formatRememberText:r}=await import('./remember-Z4UJJN62.cjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory remember --content <text> --category <c> --importance <1-10> [--tag <t>] [--session <s>] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:"remember (persist fact)"}),{code:0,handled:!0,command:e}}case "forget":{let{parseForgetOptions:n,runForget:a,formatForgetText:r}=await import('./forget-M4I6GVWI.cjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory forget (--fact-id <id> | --category <c> | --from <ISO> --to <ISO>) [--max-delete <n>] [--dry-run] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:"forget (delete facts)"}),{code:0,handled:!0,command:e}}case "extract":{let{parseExtractOptions:n,runExtract:a,formatExtractText:r}=await import('./extract-O4IOL6BZ.cjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory extract --session <sessionId> [--last-n <n>] [--from-msg <id>] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:"extract (from session)"}),{code:0,handled:!0,command:e}}case "consolidate":{let{parseConsolidateOptions:n,runConsolidate:a,formatConsolidateText:r}=await import('./consolidate-7GFUFPLX.cjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory consolidate [--window-days <n>] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:"consolidate (pipeline)"}),{code:0,handled:!0,command:e}}case "sync":{let{parseSyncOptions:n,runSync:a,formatSyncText:r}=await import('./sync-6I2ZJUH6.cjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory sync [--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 a({...o,workspaceDir:c,agentId:d});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:"sync (db \u2192 .md + archive)"}),{code:0,handled:!0,command:e}}case "graph":{let{parseGraphOptions:n,runGraph:a,formatGraphText:r}=await import('./graph-AOMDJ6YA.cjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory graph [--query <q>] [--node-id <id>] [--max-depth <n>] [--max-nodes <n>] [--max-edges-per-node <n>] [--json]\n (note: `--depth` is an alias for `--max-depth`; old `--kind` / `--start-node` / `--scope` flags removed since service schema is strict)"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:"graph_query"}),{code:0,handled:!0,command:e}}case "status":{let{parseStatusOptions:n,runStatus:a}=await import('./status-DH33MQZV.cjs'),r=n(s);if(r.help)return console.log("Usage: easbot-memory status [--json]"),{code:0,handled:!0,command:e};let o=await a({...r,workspaceDir:c,agentId:d});return r.json?terminal.emitJsonOk(o,{command:e}):terminal.printHuman([terminal.formatKnowledgeStatus(K(o))],{title:"memory status",boxed:!0}),{code:0,handled:!0,command:e}}case "doctor":{let{parseDoctorOptions:n,runDoctor:a}=await import('./doctor-SCXUJRSG.cjs'),r=n(s);if(r.help)return console.log("Usage: easbot-memory doctor [--repair] [--json]"),{code:0,handled:!0,command:e};let o=await a({...r,workspaceDir:c});return r.json?terminal.emitJsonOk(o,{command:e}):terminal.printHuman([terminal.formatKnowledgeDoctor(M(o))],{title:"memory doctor",boxed:!0}),{code:0,handled:!0,command:e}}case "config":{let{parseConfigOptions:n,runConfig:a,formatConfigText:r}=await import('./config-I2I6U4XM.cjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory config [--json]"),{code:0,handled:!0,command:e};let i=a(o);return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:"memory config"}),{code:0,handled:!0,command:e}}case "mcp":{let{parseMcpOptions:n,runMcp:a}=await import('./mcp-VIOHPDO5.cjs'),r=n(s);if(r.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 a(r);return r.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(n){let a=n instanceof Error?n.message:String(n);b.error("memory CLI command failed",{command:e,error:a,stack:n instanceof Error?n.stack:void 0});let r=t?.cwd??chunkCPRDIUQ4_cjs.f().worktree;return console.error(`[memory] ${r} :: ${e} failed: ${a}`),terminal.emitJsonError(e,a),{code:1,handled:true,command:e}}}function K(p){let t=p;return {packageName:"memory",rootDir:t.workspaceDir??"",configPath:t.configPath??"",configExists:typeof t.configExists=="boolean"?t.configExists:true,dbPath:t.dbPath??"",dbExists:typeof t.dbExists=="boolean"?t.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,healthy:typeof t.healthy=="boolean"?t.healthy:true,recommendation:t.recommendation,dbStats:(()=>{let e=t.dbStats;if(e&&typeof e=="object"&&Object.keys(e).length>0)return {...e};let s=t.integrityStats;if(s&&typeof s=="object"&&Object.keys(s).length>0)return {...s}})(),extras:(()=>{let e={};if(typeof t.agentId=="string"&&(e.agent_id=t.agentId),typeof t.ftsAvailable=="boolean"&&(e.fts_available=t.ftsAvailable?"yes":"no"),t.factsByCategory&&typeof t.factsByCategory=="object"){let s=t.factsByCategory;for(let[c,d]of Object.entries(s))typeof d=="number"&&d>0&&(e[`facts/${c}`]=d);}if(t.meta&&typeof t.meta=="object")for(let[s,c]of Object.entries(t.meta))e[`meta/${s}`]=c===void 0?"\u2205":c;return Object.keys(e).length>0?e:void 0})()}}function M(p){let t=p,e=Array.isArray(t.checks)?t.checks:[],s=t.integrityStats,c=t.backendAvailable,d=s?{...s}: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:d,backendAvailable:c}}exports.a=S;exports.b=v;exports.c=j;exports.d=A;exports.e=M;
@@ -0,0 +1,67 @@
1
+ 'use strict';var chunkLYBUZDJK_cjs=require('./chunk-LYBUZDJK.cjs'),chunkCPRDIUQ4_cjs=require('./chunk-CPRDIUQ4.cjs'),chunkJ5XF2W4Z_cjs=require('./chunk-J5XF2W4Z.cjs'),chunkM2YU5LAI_cjs=require('./chunk-M2YU5LAI.cjs'),utils=require('@easbot/utils'),zod=require('zod'),crypto=require('crypto'),llm=require('@easbot/llm'),Q=require('fs/promises'),ue=require('path'),fs=require('fs'),module$1=require('module'),types=require('@easbot/types');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Q__default=/*#__PURE__*/_interopDefault(Q);var ue__default=/*#__PURE__*/_interopDefault(ue);var pe=utils.Log.create({service:"memory.graph-store"}),Z=class{constructor(e){chunkM2YU5LAI_cjs.a(this,"db");this.db=e;}async upsertNode(e,a,r,n){let c=Date.now(),s=JSON.stringify(r??{}),i=this.db.prepare("SELECT id FROM nodes WHERE name = ? AND type = ? LIMIT 1").get(e,a);if(i)return this.db.prepare("UPDATE nodes SET properties = ?, updatedAt = ? WHERE id = ?").run(s,c,i.id),i.id;let u=this.db.prepare("INSERT INTO nodes (name, type, properties, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?)").run(e,a,s,c,c);return Number(u.lastInsertRowid)}async deleteNode(e){this.db.prepare("DELETE FROM nodes WHERE id = ?").run(e);}async upsertEdge(e,a,r,n){let c=this.db.prepare("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)").run(e,a,r,JSON.stringify(n??{}),Date.now());return Number(c.lastInsertRowid)}async queryNodes(e={}){let a="SELECT id, name, type, properties, createdAt, updatedAt FROM nodes",r=[],n=[];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));n.push(`id IN (${s.map(()=>"?").join(", ")})`),r.push(...s);}e.name&&(n.push("name LIKE ?"),r.push(`%${e.name}%`)),e.type&&(n.push("type = ?"),r.push(e.type)),n.length>0&&(a+=` WHERE ${n.join(" AND ")}`),a+=" ORDER BY id",e.limit&&(a+=" LIMIT ?",r.push(e.limit)),pe.debug("queryNodes",{sql:a,params:r,filter:e});let c=this.db.prepare(a).all(...r);return pe.debug("queryNodes result",{count:c.length}),c.map(s=>({id:s.id,name:s.name,type:s.type,properties:s.properties?JSON.parse(s.properties):void 0,createdAt:s.createdAt,updatedAt:s.updatedAt}))}async queryEdges(e={}){let a="SELECT e.id, e.source, e.target, e.relation, e.properties, e.createdAt FROM edges e",r=[],n=[];if(e.ids&&e.ids.length>0&&(n.push(`e.id IN (${e.ids.map(()=>"?").join(", ")})`),r.push(...e.ids)),e.source!==void 0&&(n.push("e.source = ?"),r.push(e.source)),e.target!==void 0&&(n.push("e.target = ?"),r.push(e.target)),e.sourceOrTarget&&e.sourceOrTarget.length>0){let g=e.sourceOrTarget.map(S=>typeof S=="string"?parseInt(S,10):S).filter(S=>!Number.isNaN(S));n.push(`(e.source IN (${g.map(()=>"?").join(", ")}) OR e.target IN (${g.map(()=>"?").join(", ")}))`),r.push(...g,...g);}e.relation&&(n.push("e.relation = ?"),r.push(e.relation)),n.length>0&&(a+=` WHERE ${n.join(" AND ")}`),a+=" ORDER BY e.id",e.limit&&(a+=" LIMIT ?",r.push(e.limit)),pe.debug("queryEdges",{sql:a,params:r,filter:e});let c=this.db.prepare(a).all(...r);pe.debug("queryEdges result",{count:c.length});let s=[...new Set(c.map(g=>g.target))],i=s.length>0?await this.queryNodes({ids:s,limit:s.length}):[],u=new Map(i.map(g=>[g.id,g]));return c.map(g=>{let S={id:g.id,source:g.source,target:g.target,relation:g.relation,properties:g.properties?JSON.parse(g.properties):void 0,createdAt:g.createdAt},f=u.get(g.target);return f&&(S.targetNode=f),S})}async queryNeighbors(e,a=1,r){let n=r?.maxEdgesPerNode??50,c=new Map,s=[e];for(let i=0;i<=a&&s.length>0;i++){let u=await this.queryNodes({ids:s,limit:s.length}),g=await this.queryEdges({sourceOrTarget:s,limit:n*s.length}),S=new Map;for(let p of g){if(s.includes(p.source)){let E=S.get(p.source)??[];E.push(p),S.set(p.source,E);}if(s.includes(p.target)){let E=S.get(p.target)??[];E.push(p),S.set(p.target,E);}}let f=[];for(let p of u){if(c.has(p.id))continue;let E=(S.get(p.id)??[]).slice(0,n);if(c.set(p.id,{...p,edges:E}),i<a)for(let h of E){let _=h.source===p.id?h.target:h.source;!c.has(_)&&!f.includes(_)&&f.push(_);}}s=f;}return [...c.values()]}};var R=class extends Error{constructor(a,r,n){super(a);chunkM2YU5LAI_cjs.a(this,"code",r);chunkM2YU5LAI_cjs.a(this,"details",n);this.name="ServiceError";}},ie=class extends R{constructor(e,a=[]){super(`Memory not found: ${e}`,"NOT_FOUND",{memoryId:e,candidates:a});}};var ye=class extends R{constructor(){super("ctx.agentId is required for memory service (ADR 0055 per-agent isolation)","AGENT_ID_REQUIRED");}},he=class extends R{constructor(e,a){super(`Trust denied for operation "${e}": ${a}`,"TRUST_DENIED",{operation:e,reason:a});}},ce=class extends R{constructor(e,a){super(`Memory ${e} has ${a} references (force=false)`,"HAS_REFERENCES",{memoryId:e,referenceCount:a});}},de=class extends R{constructor(e){super(`dryRun mode: ${e} memories matched but not deleted`,"DRY_RUN_NO_DELETE",{matchedCount:e});}},me=class extends R{constructor(e,a){super(`Matched ${e} memories exceeds maxDelete=${a}`,"MAX_DELETE_EXCEEDED",{matched:e,maxDelete:a});}};function $(t){if(typeof t.agentId!="string"||t.agentId.trim().length===0)throw new ye}function B(t,e){if(t.remote!==false)throw new he(e,"requires trusted local caller (CLI / agent tool / MCP with remote=false)")}function ee(t){if(!t.dbPath||t.dbPath.trim().length===0)throw new R("service ctx.dbPath is required (MemoryKnowledgeConfigWithModels.database.path)","INTERNAL")}var te=utils.Log.create({service:"memory.service.recall"});async function tt(t,e){let a=Date.now();if($(t),ee(t),!e.query||e.query.trim().length===0)throw new R("recall requires non-empty `query`","CONTENT_REQUIRED");let r=e.includeShared?"both":"agent_only";e.includeGraph&&void 0,te.debug("recall invoked",{agentId:t.agentId,query:e.query,category:e.category,maxResults:e.maxResults,includeGraph:e.includeGraph,scope:r});let n=e.maxResults??10,c=e.minScore??0,s=[],i=new chunkLYBUZDJK_cjs.e(t.dbPath);try{await i.initialize();let u=chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().embedding===!0,g=await St(i,t.agentId,e.query,{category:e.category,minImportance:e.minImportance,fromTime:e.fromTime,toTime:e.toTime,limit:n,minScore:c,hasEmbedding:u}),S;if(e.includeGraph&&g.length>0)try{let p=new Z(i.getDb()),E=e.maxDepth??1,h=g.flatMap(b=>(b.nodes??[]).map(v=>v.id)).slice(0,5),_=new Set,y=new Map,C=e.maxEdgesPerNode??10;for(let b of h){let v=await p.queryNeighbors(b,E,{agentId:t.agentId,scope:r,maxEdgesPerNode:C});for(let I of v)_.add(I.id),y.set(I.id,I.edges??[]);}let M=_.size>0?i.query(`SELECT id, name, type FROM nodes WHERE id IN (${Array.from(_).map(()=>"?").join(",")})`,Array.from(_)):[],N=Array.from(y.values()).flat();S={nodes:M.map(b=>({id:b.id,name:b.name,type:b.type,createdAt:"",updatedAt:""})),edges:N};}catch(p){let E=p instanceof Error?p.message:String(p);te.warn("recall: KG neighbor query failed",{error:E}),s.push(`kg_neighbor_query_failed: ${E}`),S={nodes:[],edges:[]};}let f=Date.now()-a;return {hits:g,total:g.length,truncated:g.length>=n,durationMs:f,graph:S,...s.length>0?{warnings:s}:{}}}catch(u){throw u instanceof R?u:new R(`recall failed: ${u instanceof Error?u.message:String(u)}`,"INTERNAL",{cause:u instanceof Error?u.message:String(u)})}finally{i.close();}}async function St(t,e,a,r){let n=["mf.agent_id = ?"],c=[e];r.category&&(n.push("mf.category = ?"),c.push(r.category)),r.minImportance!==void 0&&(n.push("mf.importance >= ?"),c.push(r.minImportance)),r.fromTime&&(n.push("mf.created_at >= ?"),c.push(r.fromTime)),r.toTime&&(n.push("mf.created_at <= ?"),c.push(r.toTime));let s=n.join(" AND "),i=null;if(r.hasEmbedding)try{i=await chunkJ5XF2W4Z_cjs.a.embedText(a);}catch(l){te.warn("recall: query embedding failed, falling back to FTS-only",{error:l instanceof Error?l.message:String(l)}),i=null;}let u=Math.max(r.limit*100,1e3),[g,S]=await Promise.all([i?Mt(t,i,s,c,u):Promise.resolve([]),_t(t,a,s,c,r.limit)]),f=i?.7:0,p=i?.3:1,E=f+p,h=f/E,_=p/E,y=new Map;for(let l of g)y.set(l.id,l.score*h);for(let l of S)y.set(l.id,(y.get(l.id)??0)+l.score*_);let C=Array.from(y.entries()).sort((l,w)=>w[1]-l[1]).map(([l])=>l).slice(0,r.limit);if(C.length===0)return [];let M=C.map(()=>"?").join(","),N=t.query(`SELECT
2
+ mf.id,
3
+ mf.category,
4
+ mf.importance,
5
+ mf.agent_id as agentId,
6
+ mf.content as content,
7
+ SUBSTR(mf.content, 1, 200) as snippet,
8
+ mf.created_at as createdAt,
9
+ mf.updated_at as updatedAt,
10
+ mf.source,
11
+ mf.file_path as filePath,
12
+ mf.tags,
13
+ mf.session_id as sessionId,
14
+ mf.msg_id as msgId,
15
+ mf.parent_msg_id as parentMsgId
16
+ FROM memory_facts mf
17
+ WHERE mf.id IN (${M})`,C),b=It(t,N.map(l=>l.id)),v=Date.now();return N.map(l=>{let w=y.get(l.id)??0,P=(v-new Date(l.createdAt).getTime())/864e5,k=Math.exp(-0.05*P),G=(l.importance-1)/9,z=.4*w+.3*k+.3*G,V;if(l.tags)try{let d=JSON.parse(l.tags);Array.isArray(d)&&(V=d.filter(m=>typeof m=="string"));}catch{}return {memoryId:l.id,category:l.category,importance:l.importance,agentId:l.agentId,content:l.content,snippet:l.snippet,score:z,createdAt:l.createdAt,updatedAt:l.updatedAt,source:l.source,filePath:l.filePath??void 0,tags:V,sessionId:l.sessionId??void 0,msgId:l.msgId??void 0,parentMsgId:l.parentMsgId??void 0,nodes:b.get(l.id)??[]}}).filter(l=>l.score>=r.minScore).sort((l,w)=>w.score-l.score)}function It(t,e){let a=new Map;if(e.length===0)return a;try{let r=e.map(()=>"?").join(","),n=t.query(`SELECT fn.fact_id as fact_id, n.id, n.name, n.type
18
+ FROM fact_nodes fn
19
+ JOIN nodes n ON fn.node_id = n.id
20
+ WHERE fn.fact_id IN (${r})
21
+ ORDER BY fn.fact_id, fn.score DESC, n.id`,e);for(let c of n){let s=a.get(c.fact_id);s||(s=[],a.set(c.fact_id,s)),s.push({id:c.id,name:c.name,type:c.type});}}catch(r){te.warn("recall: loadFactNodes failed (KG associations unavailable for this recall)",{error:r instanceof Error?r.message:String(r)});}return a}function Mt(t,e,a,r,n){try{return t.query(`SELECT mf.id, mv.embedding
22
+ FROM memory_facts mf
23
+ JOIN memory_vectors mv ON mf.id = mv.fact_id
24
+ WHERE ${a}
25
+ LIMIT ?`,[...r,n]).map(s=>{let i=new Float32Array(s.embedding.buffer,s.embedding.byteOffset,s.embedding.byteLength/4);return {id:s.id,score:Dt(e,i)}}).sort((s,i)=>i.score-s.score)}catch(c){if(c instanceof R)throw c;return te.warn("vector search failed, falling back to FTS-only",{error:c instanceof Error?c.message:String(c)}),[]}}function _t(t,e,a,r,n){try{let c=t.query(`SELECT mf.id as id, bm25(memory_facts_fts) as score
26
+ FROM memory_facts_fts fts
27
+ JOIN memory_facts mf ON mf.id = fts.fact_id
28
+ WHERE ${a} AND memory_facts_fts MATCH ?
29
+ ORDER BY score DESC
30
+ LIMIT ?`,[...r,vt(e),n]);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 R)throw c;return te.warn("FTS search failed, returning empty result",{err:c instanceof Error?c.message:String(c)}),[]}}function Dt(t,e){if(t.length!==e.length||t.length===0)return 0;let a=0,r=0,n=0;for(let s=0;s<t.length;s++){let i=t[s]??0,u=e[s]??0;a+=i*u,r+=i*i,n+=u*u;}let c=Math.sqrt(r)*Math.sqrt(n);return c===0?0:Math.max(0,a/c)}function vt(t){return t.trim().split(/\s+/).filter(e=>e.length>0).map(e=>`"${e.replace(/"/g,'""')}"`).join(" ")}var we=zod.z.object({query:zod.z.string().min(1).max(2e3),category:zod.z.string().optional(),minImportance:zod.z.number().min(1).max(10).optional(),fromTime:zod.z.string().datetime().optional(),toTime:zod.z.string().datetime().optional(),maxResults:zod.z.number().int().min(1).max(100).optional(),minScore:zod.z.number().min(0).max(1).optional(),includeGraph:zod.z.boolean().optional(),maxDepth:zod.z.number().int().min(1).max(5).optional(),includeShared:zod.z.boolean().optional(),maxEdgesPerNode:zod.z.number().int().min(1).max(100).optional()}).strict();zod.z.object({hits:zod.z.array(zod.z.unknown()),total:zod.z.number(),truncated:zod.z.boolean(),durationMs:zod.z.number(),graph:zod.z.object({nodes:zod.z.array(zod.z.unknown()),edges:zod.z.array(zod.z.unknown())}).optional()});var Re=zod.z.object({content:zod.z.string().min(1).max(1e4),category:zod.z.string().min(1),importance:zod.z.number().int().min(1).max(10).optional(),tags:zod.z.array(zod.z.string()).optional(),sessionId:zod.z.string().optional(),msgId:zod.z.string().optional(),parentMsgId:zod.z.string().optional(),skipDedup:zod.z.boolean().optional(),extractGraph:zod.z.boolean().optional()}).strict();zod.z.object({fact:zod.z.object({id:zod.z.string(),agentId:zod.z.string(),content:zod.z.string(),category:zod.z.string(),importance:zod.z.number(),createdAt:zod.z.string(),updatedAt:zod.z.string()}),filePath:zod.z.string(),deduplicated:zod.z.boolean(),nodeIds:zod.z.array(zod.z.number()).optional()});var Se=zod.z.object({factId:zod.z.string().min(1).describe("Target fact id (must belong to ctx.agentId)"),content:zod.z.string().min(1).max(1e4).optional().describe("New content (triggers embedding rewrite + FTS reindex)"),category:zod.z.string().min(1).optional().describe("New category (one of MemoryCategory enum)"),importance:zod.z.number().int().min(1).max(10).optional().describe("New importance 1-10"),tags:zod.z.array(zod.z.string()).optional().describe("New tags array (empty array clears tags)")}).strict().refine(t=>t.content!==void 0||t.category!==void 0||t.importance!==void 0||t.tags!==void 0,{message:"at least one of `content`, `category`, `importance`, `tags` is required"});zod.z.object({fact:zod.z.object({id:zod.z.string(),agentId:zod.z.string(),content:zod.z.string(),category:zod.z.string(),importance:zod.z.number(),createdAt:zod.z.string(),updatedAt:zod.z.string()}),contentChanged:zod.z.boolean(),fieldsUpdated:zod.z.array(zod.z.string()),durationMs:zod.z.number()});var Ie=zod.z.object({factId:zod.z.string().optional(),category:zod.z.string().optional(),fromTime:zod.z.string().datetime().optional(),toTime:zod.z.string().datetime().optional(),maxDelete:zod.z.number().int().min(1).max(1e4).optional(),dryRun:zod.z.boolean().optional(),force:zod.z.boolean().optional()}).strict().refine(t=>t.factId!==void 0&&t.factId.length>0||t.category!==void 0&&t.category.length>0||t.fromTime!==void 0||t.toTime!==void 0,{message:"one of `factId`, `category`, `fromTime`, or `toTime` is required"});zod.z.object({deletedCount:zod.z.number(),deletedIds:zod.z.array(zod.z.string()),dryRun:zod.z.boolean(),truncatedCount:zod.z.number()});var Me=zod.z.object({sessionId:zod.z.string().min(1),lastN:zod.z.number().int().min(1).max(500).optional(),fromMessageId:zod.z.string().optional(),writeToDisk:zod.z.boolean().optional()}).strict();zod.z.object({extractedCount:zod.z.number(),factIds:zod.z.array(zod.z.string()),entities:zod.z.array(zod.z.object({id:zod.z.number(),name:zod.z.string(),type:zod.z.string()})),relations:zod.z.array(zod.z.object({source:zod.z.string(),target:zod.z.string(),relation:zod.z.string()})),messageRange:zod.z.object({fromMessageId:zod.z.string(),toMessageId:zod.z.string()}),durationMs:zod.z.number()});var _e=zod.z.object({windowDays:zod.z.number().int().min(1).max(365).optional(),dryRun:zod.z.boolean().optional(),fromTime:zod.z.string().datetime().optional()}).strict();zod.z.object({totalFacts:zod.z.number(),dedupedCount:zod.z.number(),compressedCount:zod.z.number(),archivedCount:zod.z.number(),skippedCount:zod.z.number(),durationMs:zod.z.number()});var De=zod.z.object({query:zod.z.string().min(1).optional(),nodeId:zod.z.number().int().positive().optional(),type:zod.z.string().optional(),maxDepth:zod.z.number().int().min(1).max(5).optional(),maxNodes:zod.z.number().int().min(1).max(500).optional(),scope:zod.z.enum(["agent_only","shared_only","both"]).optional(),relation:zod.z.string().optional(),maxEdgesPerNode:zod.z.number().int().min(1).max(100).optional()}).strict();zod.z.object({root:zod.z.unknown().nullable(),nodes:zod.z.array(zod.z.unknown()),edges:zod.z.array(zod.z.unknown()),truncated:zod.z.boolean(),totalNodes:zod.z.number(),totalEdges:zod.z.number(),scope:zod.z.enum(["agent_only","shared_only","both"]),durationMs:zod.z.number()});var ve=zod.z.object({agentId:zod.z.string().optional()}).passthrough().optional();zod.z.object({dbPath:zod.z.string(),workspaceDir:zod.z.string(),factsCount:zod.z.number(),nodesCount:zod.z.number(),edgesCount:zod.z.number(),factsByCategory:zod.z.record(zod.z.string(),zod.z.number()),ftsAvailable:zod.z.boolean(),vectorEnabled:zod.z.boolean(),healthy:zod.z.boolean(),meta:zod.z.record(zod.z.string(),zod.z.string())});var Ce=zod.z.object({repair:zod.z.boolean().optional(),agentId:zod.z.string().optional()}).passthrough().optional();zod.z.object({healthy:zod.z.boolean(),checks:zod.z.array(zod.z.object({name:zod.z.string(),passed:zod.z.boolean(),message:zod.z.string(),details:zod.z.record(zod.z.string(),zod.z.unknown()).optional()}))});var Ne=zod.z.object({workspaceDir:zod.z.string().optional(),dbPath:zod.z.string().optional(),archiveDays:zod.z.number().int().min(1).max(3650).optional(),force:zod.z.boolean().optional()}).strict();zod.z.object({initialized:zod.z.boolean(),dbPath:zod.z.string(),workspaceDir:zod.z.string(),tablesCreated:zod.z.number(),migrationsApplied:zod.z.number(),durationMs:zod.z.number()});var Oe=zod.z.object({windowDays:zod.z.number().int().min(1).max(3650).optional(),dryRun:zod.z.boolean().optional()}).passthrough();zod.z.object({generatedCount:zod.z.number(),skippedCount:zod.z.number(),failedGenerateCount:zod.z.number(),archivedCount:zod.z.number(),failedArchivePaths:zod.z.array(zod.z.string()),archiveThreshold:zod.z.string(),archivedRecords:zod.z.array(zod.z.object({source:zod.z.string(),target:zod.z.string(),firstCreatedAt:zod.z.string(),firstFactId:zod.z.string()})),windowDays:zod.z.number(),dryRun:zod.z.boolean(),durationMs:zod.z.number()});var le=utils.Log.create({service:"memory.fact-file-sync"}),Ot=".easbot/memory/active";function ge(t,e){let a=e.replace(/\\/g,"/").replace(/\/+$/,""),r=t.category||"uncategorized",n=t.createdAt?new Date(t.createdAt).getTime():Date.now(),c=Number.isNaN(n)?new Date:new Date(n),s=c.getFullYear(),i=String(c.getMonth()+1).padStart(2,"0"),u=String(c.getDate()).padStart(2,"0"),g=`${s}-${i}-${u}`;return `${a}/${Ot}/${r}/${g}.md`}function rt(t){let e=t.tags&&t.tags.length>0?t.tags:[],a=t.importance??5,r=t.source??"session_self_write",n=t.createdAt?utils.formatLocalISO(new Date(t.createdAt)):utils.formatLocalISO(new Date),c=t.updatedAt?utils.formatLocalISO(new Date(t.updatedAt)):n,s=["---",`id: ${t.id}`,`agent_id: ${t.agentId}`,`category: ${t.category}`,`importance: ${a}`,`created_at: ${n}`,`updated_at: ${c}`,`source: ${r}`,e.length>0?`tags: [${e.join(", ")}]`:"tags: []"];return t.sessionId&&s.push(`session_id: ${t.sessionId}`),t.msgId&&s.push(`msg_id: ${t.msgId}`),t.parentMsgId&&s.push(`parent_msg_id: ${t.parentMsgId}`),s.push("---"),`${s.join(`
31
+ `)}
32
+ ${t.content.trim()}`}function re(t,e){let a=t.replace(/\\/g,"/"),r=e.replace(/\\/g,"/").replace(/\/+$/,"");return a.startsWith(`${r}/`)?a.slice(r.length+1):a}async function Tt(t,e){let a=ge(t,e),r=re(a,e);try{let n=rt(t);await Q__default.default.mkdir(ue__default.default.dirname(a),{recursive:!0});let c="";try{c=await Q__default.default.readFile(a,"utf-8");}catch(i){if(i.code!=="ENOENT")throw i}let s=c.length>0&&!c.endsWith(`
33
+ `)?`
34
+ `:"";return await Q__default.default.writeFile(a,`${c}${s}${n}
35
+ `,"utf-8"),le.debug("Fact file synced (append)",{id:t.id,relPath:r}),{ok:!0,absPath:a,relPath:r}}catch(n){let c=n instanceof Error?n.message:String(n);return le.warn("Failed to write fact file (best-effort, non-blocking)",{id:t.id,absPath:a,error:c}),{ok:false,absPath:a,relPath:r,error:c}}}async function Pt(t,e){let a;t.filePath?a=`${e.replace(/\\/g,"/").replace(/\/+$/,"")}/${t.filePath.replace(/^\/+/,"")}`:a=ge({id:t.id,category:t.category,createdAt:t.createdAt,updatedAt:t.createdAt},e);let r=re(a,e);try{return await Q__default.default.unlink(a),le.debug("Fact file deleted",{id:t.id,relPath:r}),{ok:!0,absPath:a,relPath:r}}catch(n){if(n.code==="ENOENT")return le.debug("Fact file not found (already deleted)",{id:t.id,relPath:r}),{ok:true,absPath:a,relPath:r};let s=n instanceof Error?n.message:String(n);return le.warn("Failed to delete fact file (best-effort, non-blocking)",{id:t.id,absPath:a,error:s}),{ok:false,absPath:a,relPath:r,error:s}}}var ne={resolvePath:ge,renderMarkdown:rt,toRelPath:re,write:Tt,delete:Pt};var oe=utils.Log.create({service:"memory.service.remember"});async function nt(t,e){if($(t),ee(t),!e.content||e.content.trim().length===0)throw new R("remember requires non-empty `content`","CONTENT_REQUIRED");if(!e.category)throw new R("remember requires `category`","CATEGORY_REQUIRED");oe.debug("remember invoked",{agentId:t.agentId,category:e.category,importance:e.importance??5,contentLength:e.content.length,skipDedup:e.skipDedup,extractGraph:e.extractGraph??true});let a=new chunkLYBUZDJK_cjs.e(t.dbPath);try{await a.initialize();let r=new Date().toISOString(),n=Lt(),c=e.importance??5,s={entities:[],relations:[]},u=e.extractGraph!==!1&&chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().graphLlm?chunkJ5XF2W4Z_cjs.a.getGraphLlm():void 0;if(u)try{s=await $t(u,e.content);}catch(b){oe.warn("LLM KG extraction failed (continuing without KG)",{agentId:t.agentId,error:b instanceof Error?b.message:String(b)});}let g=chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().embedding===!0,S=g?await qt(a.getDb(),e.content):null,f=S?S.length:null,p=s.entities,E=s.relations,h=[],_=0,y=[];if(a.transaction(()=>{let b=new Map;for(let I of p){let l=a.query("SELECT id FROM nodes WHERE name = ? AND type = ? LIMIT 1",[I.name,I.type])[0];if(l){b.set(I.name,l.id);continue}let w=null;try{let G=Ae(I.name),z=a.query("SELECT embedding FROM embedding_cache WHERE content_hash = ?",[G])[0];z?.embedding&&(w=z.embedding);}catch{}let k=a.run("INSERT INTO nodes (name, type, properties, embedding, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)",[I.name,I.type,JSON.stringify({source:"llm_extracted",...I.properties??{}}),w,r,r]).lastID;k>0&&(b.set(I.name,k),w===null&&y.push({name:I.name,nodeId:k}));}for(let I of E){let l=b.get(I.source),w=b.get(I.target);!l||!w||l===w||a.run("INSERT OR REPLACE INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)",[l,w,I.relation,JSON.stringify({}),r]);}a.run(`INSERT INTO memory_facts
36
+ (id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance,
37
+ source, tags, file_path, created_at, updated_at)
38
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n,t.agentId,e.sessionId??null,e.msgId??null,e.parentMsgId??null,e.content,e.category,c,"session_self_write",e.tags?JSON.stringify(e.tags):null,null,r,r]);let v=Array.from(b.values());if(v.length>0)try{for(let I of v)a.run("INSERT OR IGNORE INTO fact_nodes (fact_id, node_id, source, score, createdAt) VALUES (?, ?, ?, ?, ?)",[n,I,"kg_extract",1,r]);}catch(I){oe.warn("fact_nodes write failed (non-fatal)",{factId:n,nodeCount:v.length,error:I instanceof Error?I.message:String(I)});}if(S&&f){let I=Pe(S);a.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[n,I]),_=1,a.query("SELECT value FROM meta WHERE key = ?",["vectorDims"])[0]||a.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["vectorDims",String(f)]);}a.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[n]),a.run("INSERT INTO memory_facts_fts (fact_id, agent_id, content, tags) VALUES (?, ?, ?, ?)",[n,t.agentId,e.content,e.tags?e.tags.join(" "):""]),h.push(...Array.from(b.values()));}),y.length>0&&chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().embedding)try{let b=y.map(l=>l.name),v=await chunkJ5XF2W4Z_cjs.a.embedMany(b),I=new Date().toISOString();for(let l=0;l<y.length;l++){let w=y[l],P=v[l];if(!w||!P||P.length===0)continue;let k=Pe(new Float32Array(P));a.run("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)",[Ae(w.name),k]),a.run("UPDATE nodes SET embedding = ?, updatedAt = ? WHERE id = ?",[k,I,w.nodeId]);}}catch(b){oe.warn("memory entity name batch embed failed (non-fatal)",{pendingCount:y.length,error:b instanceof Error?b.message:String(b)});}oe.info("Memory stored",{id:n,category:e.category,agentId:t.agentId,nodeCount:h.length,vectorsWritten:_,vectorDims:f??0,embeddingMode:g?"enabled":"fts_only",entitiesExtracted:p.length,relationsExtracted:E.length});let C={id:n,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:h.length>0?h:void 0,filePath:void 0,createdAt:r,updatedAt:r},M="",N=await ne.write(C,t.workspaceDir);if(N.ok){M=N.relPath,C.filePath=N.relPath;try{a.run("UPDATE memory_facts SET file_path = ? WHERE id = ?",[N.relPath,n]);}catch(b){oe.warn("Failed to update file_path column after sync",{id:n,error:b instanceof Error?b.message:String(b)});}}return {fact:C,filePath:M,deduplicated:!1,nodeIds:h,vectorsWritten:_,vectorDims:f??0,entitiesExtracted:p.length,relationsExtracted:E.length}}catch(r){throw r instanceof R?r:new R(`remember failed: ${r instanceof Error?r.message:String(r)}`,"INTERNAL",{cause:r instanceof Error?r.message:String(r)})}finally{a.close();}}function Lt(){let t=Date.now(),e=crypto.randomBytes(3).toString("hex");return `mem_${t}_${e}`}function Pe(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}function Ae(t){return crypto.createHash("sha256").update(t).digest("hex")}async function qt(t,e){let a=Ae(e),r=t.prepare("SELECT embedding FROM embedding_cache WHERE content_hash = ?").get(a);if(r?.embedding)return new Float32Array(r.embedding.buffer,r.embedding.byteOffset,r.embedding.byteLength/4);let n=await chunkJ5XF2W4Z_cjs.a.embedText(e);if(!n||n.length===0)return null;let c=Pe(n);return t.prepare("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)").run(a,c),n}async function $t(t,e){let a=await llm.GraphProvider.generateGraph({chunks:[e],model:t,includeRules:false});return {entities:a.entities,relations:a.relations}}var ke=utils.Log.create({service:"memory.service.update"});function Wt(t){if(t.content===void 0&&t.category===void 0&&t.importance===void 0&&t.tags===void 0)throw new R("update requires at least one of: `content`, `category`, `importance`, `tags`","CONTENT_REQUIRED");if(t.content!==void 0&&t.content.trim().length===0)throw new R("update: `content` cannot be empty (use `forget` to delete)","CONTENT_REQUIRED");if(t.importance!==void 0&&(t.importance<1||t.importance>10))throw new R(`update: \`importance\` must be 1-10, got ${t.importance}`,"IMPORTANCE_REQUIRED")}async function ot(t,e){let a=Date.now();$(t),ee(t),Wt(e),ke.debug("update invoked",{agentId:t.agentId,factId:e.factId,fields:{content:e.content!==void 0,category:e.category!==void 0,importance:e.importance!==void 0,tags:e.tags!==void 0}});let r=e.content!==void 0,n=r&&chunkJ5XF2W4Z_cjs.a.isInitialized()&&chunkJ5XF2W4Z_cjs.a.capabilities().embedding===true,c=null;if(n&&e.content)try{c=await chunkJ5XF2W4Z_cjs.a.embedText(e.content);}catch(i){ke.warn("update: embedding rewrite failed (continuing without vector update)",{factId:e.factId,error:i instanceof Error?i.message:String(i)});}let s=new chunkLYBUZDJK_cjs.e(t.dbPath);try{await s.initialize();let i=new Date().toISOString(),u=[];s.transaction(()=>{let p=s.query("SELECT id, content, category, importance, tags FROM memory_facts WHERE id = ? AND agent_id = ?",[e.factId,t.agentId])[0];if(!p)throw new ie(e.factId);let E=["updated_at = ?"],h=[i];if(e.content!==void 0&&e.content!==p.content&&(E.push("content = ?"),h.push(e.content),u.push("content")),e.category!==void 0&&e.category!==p.category&&(E.push("category = ?"),h.push(e.category),u.push("category")),e.importance!==void 0&&e.importance!==p.importance&&(E.push("importance = ?"),h.push(e.importance),u.push("importance")),e.tags!==void 0){let _=e.tags.length>0?JSON.stringify(e.tags):null;_!==p.tags&&(E.push("tags = ?"),h.push(_),u.push("tags"));}if(u.length>0&&s.run(`UPDATE memory_facts SET ${E.join(", ")} WHERE id = ? AND agent_id = ?`,[...h,e.factId,t.agentId]),u.includes("content")||u.includes("tags")){let _=e.content??p.content,y=u.includes("tags")?e.tags&&e.tags.length>0?JSON.stringify(e.tags):null:p.tags,C=y?(()=>{try{let M=JSON.parse(y);return Array.isArray(M)?M.filter(N=>typeof N=="string"):[]}catch{return []}})():[];s.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[e.factId]),s.run("INSERT INTO memory_facts_fts (fact_id, agent_id, content, tags) VALUES (?, ?, ?, ?)",[e.factId,t.agentId,_,C.join(" ")]);}if(u.includes("content")&&c){let _=Gt(c);s.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[e.factId,_]);try{let y=jt(e.content);s.run("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)",[y,_]);}catch{}}}),(u.includes("content")||u.includes("tags"))&&s.run("INSERT INTO memory_facts_fts(memory_facts_fts) VALUES('optimize')");let g=s.query("SELECT id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance, source, tags, file_path, created_at, updated_at FROM memory_facts WHERE id = ? AND agent_id = ?",[e.factId,t.agentId])[0];if(!g)throw new R(`update: failed to read back updated fact ${e.factId}`,"INTERNAL");let S;if(g.tags)try{let p=JSON.parse(g.tags);Array.isArray(p)&&(S=p.filter(E=>typeof E=="string"));}catch{}let f={id:g.id,agentId:g.agent_id,sessionId:g.session_id??void 0,msgId:g.msg_id??void 0,parentMsgId:g.parent_msg_id??void 0,content:g.content,category:g.category,importance:g.importance,source:g.source,tags:S,filePath:g.file_path??void 0,createdAt:g.created_at,updatedAt:g.updated_at};return ke.info("Memory updated",{agentId:t.agentId,factId:e.factId,fieldsUpdated:u,contentChanged:r,durationMs:Date.now()-a}),{fact:f,contentChanged:r,fieldsUpdated:u,durationMs:Date.now()-a}}catch(i){throw i instanceof R?i:new R(`update failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}function Gt(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}function jt(t){return crypto.createHash("sha256").update(t).digest("hex")}var xe=utils.Log.create({service:"memory.service.forget"}),Bt=1e3;function Qt(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 R("CONTENT_REQUIRED: forget requires one of: `factId`, `category`, or `fromTime`/`toTime`","CONTENT_REQUIRED");if(e.length>1)throw new R(`mutually exclusive: forget requires exactly one of factId/category/timeRange, got [${e.join(", ")}]`,"CONTENT_REQUIRED");return e[0]}function Kt(t,e,a){let r=[a];switch(t){case "factId":return {where:"agent_id = ? AND id = ?",args:[...r,e.factId]};case "category":return {where:"agent_id = ? AND category = ?",args:[...r,e.category]};case "timeRange":{let n=["agent_id = ?"];return e.fromTime&&(n.push("created_at >= ?"),r.push(e.fromTime)),e.toTime&&(n.push("created_at <= ?"),r.push(e.toTime)),{where:n.join(" AND "),args:r}}}}function Vt(t,e,a,r){return t.query(`SELECT id FROM memory_facts WHERE ${e} LIMIT ?`,[...a,r+1]).map(c=>c.id)}function Jt(t,e,a,r){if(a.length===0)return 0;let n=a.map(()=>"?").join(",");return t.query(`SELECT COUNT(DISTINCT fn.fact_id) as count
39
+ FROM fact_nodes fn
40
+ JOIN memory_facts mf ON fn.fact_id = mf.id
41
+ WHERE mf.agent_id = ? AND fn.fact_id != ? AND fn.node_id IN (${n})`,[r,e,...a])[0]?.count??0}function Yt(t,e,a){let r,n,c="";return t.transaction(()=>{let s=t.query("SELECT content, file_path, category, created_at FROM memory_facts WHERE id = ? AND agent_id = ?",[e,a])[0],u=t.query("SELECT node_id FROM fact_nodes WHERE fact_id = ?",[e]).map(g=>g.node_id).filter(g=>typeof g=="number");if(r=s?.file_path??void 0,n=s?.category,c=s?.created_at??"",t.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[e]),t.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[e,a]),u.length>0){let g=u.map(()=>"?").join(",");t.run(`DELETE FROM nodes WHERE id IN (${g}) AND NOT EXISTS (
42
+ SELECT 1 FROM fact_nodes fn WHERE fn.node_id = nodes.id
43
+ )`,u);}}),t.run("INSERT INTO memory_facts_fts(memory_facts_fts) VALUES('optimize')"),{filePath:r,category:n,createdAt:c}}async function at(t,e){$(t),B(t,"forget");let a=Qt(e),r=e.maxDelete??Bt,n=e.dryRun??false,c=e.force??false;xe.debug("forget invoked",{agentId:t.agentId,mode:a,maxDelete:r,dryRun:n,force:c});let s=new chunkLYBUZDJK_cjs.e(t.dbPath);try{await s.initialize();let{where:i,args:u}=Kt(a,e,t.agentId),g=Vt(s,i,u,r),S=g.length>r;if(S&&!c)throw new me(g.length,r);let f=S?g.slice(0,r):g;if(n)throw new de(f.length);let p=[],E=[];for(let h of f){if(!c){let N=s.query("SELECT node_id FROM fact_nodes WHERE fact_id = ? AND node_id IS NOT NULL",[h]).map(v=>v.node_id).filter(v=>typeof v=="number"),b=Jt(s,h,N,t.agentId);if(b>0)throw new ce(h,b)}let{filePath:_,category:y,createdAt:C}=Yt(s,h,t.agentId);_&&y&&E.push({id:h,filePath:_,category:y,createdAt:C}),p.push(h);}xe.info("forget complete",{agentId:t.agentId,mode:a,deletedCount:p.length,force:c,dryRun:n});for(let{id:h,filePath:_,category:y,createdAt:C}of E)await ne.delete({id:h,filePath:_,category:y,createdAt:C},t.workspaceDir).catch(M=>{xe.warn("Fact file delete failed (best-effort)",{id:h,filePath:_,error:M instanceof Error?M.message:String(M)});});return {deletedCount:p.length,deletedIds:p,dryRun:n,truncatedCount:S?g.length-r:0}}catch(i){throw i instanceof R?i:new R(`forget failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var st=utils.Log.create({service:"memory.service.extract"}),Zt=50,Fe=500;async function it(t,e){if($(t),!e.sessionId||e.sessionId.trim().length===0)throw new R("extract requires non-empty `sessionId`","SESSION_ID_REQUIRED");let a=e.lastN??Zt;if(a>Fe)throw new R(`extract lastN=${a} exceeds max=${Fe}`,"CONTENT_REQUIRED",{lastN:a,maxLastN:Fe});let r=e.sessionId,n=e.fromMessageId;st.debug("extract invoked",{agentId:t.agentId,sessionId:r,lastN:a,fromMessageId:n,writeToDisk:e.writeToDisk??true});let c=Date.now(),s=new chunkLYBUZDJK_cjs.e(t.dbPath);try{await s.initialize();let i=s.query(`SELECT id, content, category, importance, 1.0 as score, created_at
44
+ FROM memory_facts
45
+ WHERE agent_id = ? AND session_id = ?
46
+ ORDER BY created_at ASC
47
+ LIMIT ?`,[t.agentId,r,a]),u=n?i.filter(y=>y.id>n):i,g=u.map(y=>y.id),S=g.length>0?s.query(`SELECT node_id FROM fact_nodes WHERE fact_id IN (${g.map(()=>"?").join(",")})`,g):[],f=new Set;for(let y of S)typeof y.node_id=="number"&&y.node_id>0&&f.add(y.node_id);let p=Array.from(f),E=[],h=[];if(p.length>0){let y=p.map(()=>"?").join(","),C=s.query(`SELECT id, name, type FROM nodes WHERE id IN (${y})`,p),M=new Map;for(let v of C)M.set(v.id,v.name);E=C.map(v=>({id:v.id,name:v.name,type:v.type}));let N=s.query(`SELECT source, target, relation FROM edges WHERE source IN (${y}) OR target IN (${y})`,[...p,...p]),b=new Set;h=[];for(let v of N){let I=M.get(v.source),l=M.get(v.target);if(!I||!l)continue;let w=`${I}\0${v.relation}\0${l}`;b.has(w)||(b.add(w),h.push({source:I,target:l,relation:v.relation}));}}let _=Date.now()-c;return st.info("extract complete",{agentId:t.agentId,sessionId:r,factCount:u.length,nodeCount:E.length,relationCount:h.length,durationMs:_}),{extractedCount:u.length,factIds:u.map(y=>y.id),entities:E,relations:h,messageRange:{fromMessageId:u[0]?.id??"",toMessageId:u[u.length-1]?.id??""},durationMs:_}}catch(i){throw i instanceof R?i:new R(`extract failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var $e=utils.Log.create({service:"memory.service.consolidate"}),tr=30;async function rr(t){let{createHash:e}=await import('crypto');return e("sha256").update(t).digest("hex")}async function ct(t,e={}){let a=Date.now();$(t),B(t,"consolidate");let r=e.windowDays??tr,n=e.dryRun??false,c=e.fromTime;$e.debug("consolidate invoked",{agentId:t.agentId,windowDays:r,dryRun:n,fromTime:c});let s=new chunkLYBUZDJK_cjs.e(t.dbPath);try{await s.initialize();let i=s.query(`SELECT id, content, category, importance, created_at FROM memory_facts
48
+ WHERE agent_id = ?${c?" AND created_at >= ?":""}
49
+ ORDER BY created_at DESC`,c?[t.agentId,c]:[t.agentId]),u=new Map;for(let C of i){let M=await rr(C.content);u.has(M)||u.set(M,[]),u.get(M)?.push(C);}let g=0,S=[];for(let[,C]of u){if(C.length<=1)continue;let M=[...C].sort((v,I)=>v.importance!==I.importance?I.importance-v.importance:I.created_at.localeCompare(v.created_at)),N=M[0];if(!N)continue;let b=M.slice(1).map(v=>v.id);g+=b.length,S.push({keep:N,removeIds:b});}let f=new Date(Date.now()-r*24*60*60*1e3).toISOString(),p=s.query(`SELECT id, content, category, importance, created_at FROM memory_facts
50
+ WHERE agent_id = ? AND created_at < ?
51
+ ORDER BY created_at ASC`,[t.agentId,f]),E=0;if(n)E=0;else {let C=ue__default.default.join(t.workspaceDir,"archive");await Q__default.default.mkdir(C,{recursive:!0});for(let{removeIds:M}of S)M.length!==0&&s.transaction(()=>{for(let N of M)s.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[N,t.agentId]);});for(let M of p){let N=M.created_at.slice(0,7),b=ue__default.default.join(C,N,M.category);await Q__default.default.mkdir(b,{recursive:!0});let v=ue__default.default.join(b,`${M.id}.md`);try{await Q__default.default.writeFile(v,[`# ${M.id}`,"",`category: ${M.category}`,`importance: ${M.importance}`,`createdAt: ${M.created_at}`,"",M.content,""].join(`
52
+ `),"utf-8"),s.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[M.id,t.agentId]),E++;}catch(I){$e.warn("consolidate: archive write failed",{factId:M.id,error:I instanceof Error?I.message:String(I)});}}}let h=i.length,_=0,y=0;return $e.info("consolidate complete",{agentId:t.agentId,totalFacts:h,dedupedCount:g,compressedCount:_,archivedCount:E,skippedCount:y,dryRun:n,durationMs:Date.now()-a}),{totalFacts:h,dedupedCount:g,compressedCount:_,archivedCount:E,skippedCount:y,durationMs:Date.now()-a}}catch(i){throw i instanceof R?i:new R(`consolidate failed: ${i instanceof Error?i.message:String(i)}`,"INTERNAL",{cause:i instanceof Error?i.message:String(i)})}finally{s.close();}}var W=utils.Log.create({service:"memory.service.sync"}),ar=30,sr=".easbot/memory/active",dt=".easbot/memory/archive";function ir(t,e){let r=t.query("SELECT node_id FROM fact_nodes WHERE fact_id = ?",[e.id]).map(n=>n.node_id).filter(n=>typeof n=="number");return {id:e.id,agentId:e.agent_id,sessionId:e.session_id??void 0,msgId:e.msg_id??void 0,parentMsgId:e.parent_msg_id??void 0,content:e.content,category:e.category,importance:e.importance,source:e.source,tags:e.tags?JSON.parse(e.tags):void 0,nodeIds:r.length>0?r:void 0,filePath:e.file_path??void 0,createdAt:e.created_at,updatedAt:e.updated_at}}async function cr(t,e){let a=0,r=0,n=0,{where:c,params:s}=t.agentFilter(e.agentId),i=t.query(`SELECT id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance,
53
+ source, tags, file_path, created_at, updated_at
54
+ FROM memory_facts ${c}
55
+ ORDER BY created_at ASC`,s);for(let u of i){let g=ir(t,u);if(u.file_path?.startsWith(`${dt}/`)){r++;continue}let S=ge(g,e.workspaceDir);try{await Q__default.default.access(S),r++;continue}catch(p){let E=p;if(E.code!=="ENOENT"){W.warn("sync generate: fs.access failed (non-ENOENT)",{factId:g.id,absPath:S,error:E.message}),n++;continue}}let f=await ne.write(g,e.workspaceDir);f.ok?a++:(n++,W.warn("sync generate: factFileSync.write failed",{factId:g.id,absPath:S,error:f.error}));}return W.debug("sync stage A complete",{agentId:e.agentId,generatedCount:a,skippedCount:r,failedGenerateCount:n}),{generatedCount:a,skippedCount:r,failedGenerateCount:n}}async function dr(t,e,a,r){let n=a*24*60*60*1e3,c=Date.now(),s=utils.formatLocalISO(new Date(c-n)),i=[],u=[],g=ue__default.default.join(e.workspaceDir,sr),S=await mr(g);W.debug("sync stage B: scan active dir",{activeDir:g,fileCount:S.length,windowDays:a,threshold:s,dryRun:r});for(let f of S){let p=await lr(f);if(!p){W.warn("sync stage B: skip unparseable file",{absPath:f});continue}let{firstCreatedAt:E,firstFactId:h}=p,_=new Date(E).getTime();if(Number.isNaN(_)){W.warn("sync stage B: skip invalid createdAt",{absPath:f,firstCreatedAt:E});continue}if(c-_<=n)continue;let y=gr(f);if(!y){W.warn("sync stage B: cannot infer category from path",{absPath:f});continue}let C=E.slice(0,7),M=ue__default.default.join(e.workspaceDir,dt,C,y),N=ue__default.default.basename(f),b=ue__default.default.join(M,N);if(r){i.push({source:f,target:b,firstCreatedAt:E,firstFactId:h});continue}try{await Q__default.default.mkdir(M,{recursive:!0});try{await Q__default.default.rename(f,b);}catch(l){let w=l;W.warn("sync stage B: fs.rename failed, falling back to copy+unlink",{absPath:f,targetPath:b,error:w.message}),await Q__default.default.copyFile(f,b),await Q__default.default.unlink(f);}let v=re(f,e.workspaceDir),I=re(b,e.workspaceDir);t.run(`UPDATE memory_facts SET file_path = ?
56
+ WHERE agent_id = ? AND file_path = ?`,[I,e.agentId??"",v]),i.push({source:f,target:b,firstCreatedAt:E,firstFactId:h});}catch(v){let I=v instanceof Error?v.message:String(v);W.warn("sync stage B: archive failed",{absPath:f,targetPath:b,error:I}),u.push(f);}}return W.debug("sync stage B complete",{agentId:e.agentId,archivedCount:i.length,failedArchiveCount:u.length,dryRun:r}),{archivedCount:i.length,archiveThreshold:s,archivedRecords:i,failedArchivePaths:u}}async function mr(t){let e=[];try{await mt(t,e);}catch(a){let r=a;if(r.code==="ENOENT")return e;throw W.warn("sync: listActiveMdFiles failed",{activeDir:t,error:r.message}),new R(`sync: listActiveMdFiles failed: ${r.message}`,"INTERNAL",{cause:r.message})}return e}async function mt(t,e){let a=await Q__default.default.readdir(t,{withFileTypes:true});for(let r of a){let n=ue__default.default.join(t,r.name);r.isDirectory()?await mt(n,e):r.isFile()&&r.name.endsWith(".md")&&e.push(n);}}async function lr(t){let e;try{e=await Q__default.default.readFile(t,"utf-8");}catch(s){if(s.code==="ENOENT")return null;throw s}if(!e.startsWith(`---
57
+ `))return null;let a=e.indexOf(`
58
+ ---
59
+ `,4);if(a===-1)return null;let r=e.slice(4,a),n,c;for(let s of r.split(`
60
+ `)){let i=s.trim();if(i.startsWith("created_at:")?n=i.slice(11).trim().replace(/^["']|["']$/g,""):i.startsWith("id:")&&(c=i.slice(3).trim().replace(/^["']|["']$/g,"")),n&&c)break}return !n||!c?null:{firstCreatedAt:n,firstFactId:c}}function gr(t){let e=t.replace(/\\/g,"/").split("/"),a=e.findIndex(c=>c==="active");if(a===-1)return null;let r=e.slice(a+1);return r.length!==2||!r[1].endsWith(".md")?null:r[0]??null}async function lt(t,e={}){let a=Date.now();$(t),B(t,"sync");let r=e.windowDays??t.config?.archiveDays??ar,n=e.dryRun??false;W.info("sync invoked",{agentId:t.agentId,windowDays:r,dryRun:n,workspaceDir:t.workspaceDir});let c=new chunkLYBUZDJK_cjs.e(t.dbPath);try{await c.initialize();let s=await cr(c,t),i=await dr(c,t,r,n),u={generatedCount:s.generatedCount,skippedCount:s.skippedCount,failedGenerateCount:s.failedGenerateCount,archivedCount:i.archivedCount,failedArchivePaths:i.failedArchivePaths,archiveThreshold:i.archiveThreshold,archivedRecords:i.archivedRecords,windowDays:r,dryRun:n,durationMs:Date.now()-a};if(W.info("sync complete",{agentId:t.agentId,...u}),u.failedArchivePaths.length>0)throw new R(`sync: ${u.failedArchivePaths.length} archive(s) failed: ${u.failedArchivePaths.join(", ")}`,"INGEST_FAILED",{failedArchivePaths:u.failedArchivePaths,archivedCount:u.archivedCount});return u}catch(s){throw s instanceof R?s:new R(`sync failed: ${s instanceof Error?s.message:String(s)}`,"INTERNAL",{cause:s instanceof Error?s.message:String(s)})}finally{c.close();}}var gt=utils.Log.create({service:"memory.service.graph-query"});async function ut(t,e){let a=Date.now(),r=(t.agentId??"").trim()||"default",n=e.scope??"agent_only",c=typeof e.nodeId=="number"&&e.nodeId>0,s=typeof e.query=="string"&&e.query.trim().length>0;if(!c&&!s)throw new R("CONTENT_REQUIRED: graphQuery requires either `nodeId` (numeric) or `query` (name fragment for CLI)","CONTENT_REQUIRED");let i=n==="both"||n==="shared_only"?3:1,u=e.maxDepth??i,g=e.maxNodes??100,S=e.maxEdgesPerNode??10,f=e.type,p=e.relation;gt.debug("graphQuery invoked",{agentId:r,nodeId:e.nodeId,query:e.query,type:f,maxDepth:u,maxNodes:g,scope:n,remote:t.remote});let E=new chunkLYBUZDJK_cjs.e(t.dbPath);try{await E.initialize();let h=new Z(E.getDb()),_=null;if(c)_=(await h.queryNodes({ids:[e.nodeId],agentId:r,scope:n}))[0]??null;else {let l=e.query,w=l.includes("*")||l.includes("%")?l:`%${l}%`,P=await h.queryNodes({name:w,...f?{type:f}:{},agentId:r,scope:n,limit:g});_=(l.includes("*")||l.includes("%")?P:P.filter(G=>G.name.toLowerCase().includes(l.toLowerCase())))[0]??null;}if(!_)return {root:null,nodes:[],edges:[],truncated:!1,totalNodes:0,totalEdges:0,scope:n,durationMs:Date.now()-a};let y=await h.queryNeighbors(_.id,u,{agentId:r,scope:n,maxEdgesPerNode:S}),C=new Map;C.set(_.id,_);for(let l of y)C.set(l.id,{id:l.id,name:l.name,type:l.type,createdAt:l.createdAt,updatedAt:l.updatedAt});let M=[];for(let l of y)if(l.edges)for(let w of l.edges)p&&w.relation!==p||M.push(w);let N=Array.from(new Map(M.map(l=>[l.id,l])).values());for(let l of N){if(!C.has(l.source)){let w=await h.queryNodes({ids:[l.source],agentId:r,scope:n});w[0]&&C.set(w[0].id,w[0]);}if(!C.has(l.target)){let w=await h.queryNodes({ids:[l.target],agentId:r,scope:n});w[0]&&C.set(w[0].id,w[0]);}}let b=Array.from(C.values()),v=b.length>g,I=v?b.slice(0,g):b;return gt.info("graphQuery complete",{agentId:r,rootId:_.id,nodeCount:I.length,edgeCount:N.length,truncated:v,durationMs:Date.now()-a}),{root:_,nodes:I,edges:N,truncated:v,totalNodes:b.length,totalEdges:N.length,scope:n,durationMs:Date.now()-a}}catch(h){throw h instanceof R?h:new R(`graphQuery failed: ${h instanceof Error?h.message:String(h)}`,"INTERNAL",{cause:h instanceof Error?h.message:String(h)})}finally{E.close();}}var j=utils.Log.create({service:"memory.service.init"});function Ee(t){return ue__default.default.join(t,".easbot","memory.json")}async function yr(t){try{let{Config:e}=await import('@easbot/llm'),a=await e.get(),r=n=>typeof n=="string"&&n.length>0?n:void 0;return {embeddingModel:r(a.embedding_model),graphModel:r(a.graph_model)}}catch{return {}}}function hr(t,e={}){let a={version:1,schema_version:chunkLYBUZDJK_cjs.a,backend:"better-sqlite3",created_at:new Date().toISOString(),embedding_model:e.embeddingModel??null,graph_model:e.graphModel??null,entity_extraction_prompt:e.entityExtractionPrompt??null,relation_extraction_prompt:e.relationExtractionPrompt??null,archiveDays:e.archiveDays??30,shortTermMaxRounds:e.shortTermMaxRounds??20};fs.writeFileSync(t,JSON.stringify(a,null,2),"utf-8");}async function ft(t,e={}){let a=Date.now();B(t,"init");let r=e.workspaceDir??t.workspaceDir,n=e.dbPath??t.dbPath;if(!r||r.trim().length===0)throw new R("init requires non-empty `workspaceDir` (ctx.workspaceDir or params.workspaceDir)","CONTENT_REQUIRED");if(!n||n.trim().length===0)throw new R("init requires non-empty `dbPath` (ctx.dbPath or params.dbPath)","CONTENT_REQUIRED");let c=t.agentId?.trim()??"",s=e.force??false;j.debug("init invoked",{agentId:c,workspaceDir:r,dbPath:n,force:s});let i=Ee(r);if(!s)try{if(await Q__default.default.stat(i).then(()=>!0).catch(()=>!1))return j.info("init: idempotent skip (memory.json exists, no --force)",{workspaceDir:r,configPath:i}),{initialized:!1,dbPath:n,configPath:i,configCreated:!1,schemaVersion:chunkLYBUZDJK_cjs.a,workspaceDir:r,tablesCreated:0,migrationsApplied:0,durationMs:0}}catch{}try{await Q__default.default.mkdir(ue__default.default.dirname(n),{recursive:!0}),await Q__default.default.mkdir(ue__default.default.join(r,".easbot","memory","active"),{recursive:!0}),await Q__default.default.mkdir(ue__default.default.join(r,"archive"),{recursive:!0}),await Q__default.default.mkdir(ue__default.default.join(r,".easbot"),{recursive:!0});}catch(f){throw new R(`init: failed to create directories: ${f instanceof Error?f.message:String(f)}`,"INTERNAL",{cause:f instanceof Error?f.message:String(f)})}if(s)for(let f of [n,`${n}-wal`,`${n}-shm`])try{await Q__default.default.rm(f,{force:!0});}catch(p){j.warn("init: force rm failed (may not exist)",{path:f,error:p instanceof Error?p.message:String(p)});}let u=await yr(),g=false;try{!await Q__default.default.stat(i).then(()=>!0).catch(()=>!1)||s?(hr(i,{embeddingModel:u.embeddingModel,graphModel:u.graphModel,archiveDays:t.config?.archiveDays,shortTermMaxRounds:t.config?.shortTermMaxRounds}),g=!0,j.info("init: memory.json written",{configPath:i,force:s,configCreated:g})):j.debug("init: memory.json already exists, skipping write",{configPath:i});}catch(f){j.warn("init: memory.json write failed (non-fatal)",{configPath:i,error:f instanceof Error?f.message:String(f)});}let S=new chunkLYBUZDJK_cjs.e(n);try{let f=await Q__default.default.stat(n).then(()=>!0).catch(()=>!1);await S.initialize();let p=new Date().toISOString(),E=[["version","1.0.0"],["schemaVersion",String(chunkLYBUZDJK_cjs.a)],["createdAt",p],["defaultAgentId",c]];for(let[y,C]of E)try{S.run("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)",[y,C]);}catch(M){j.warn("init: meta insert failed",{key:y,error:M instanceof Error?M.message:String(M)});}let h=0;try{h=S.prepare("SELECT COUNT(*) as n FROM sqlite_master WHERE type IN ('table', 'index', 'trigger', 'view')").get()?.n??0;}catch(y){j.warn("init: tablesCreated count failed",{error:y instanceof Error?y.message:String(y)});}let _=0;try{_=S.prepare("SELECT id FROM schema_migrations").all().length;}catch(y){j.warn("init: migrationsApplied count failed",{error:y instanceof Error?y.message:String(y)});}return j.info("init complete",{agentId:c,workspaceDir:r,dbPath:n,configPath:i,configCreated:g,schemaVersion:chunkLYBUZDJK_cjs.a,durationMs:Date.now()-a}),{initialized:!0,dbPath:n,configPath:i,configCreated:g,schemaVersion:chunkLYBUZDJK_cjs.a,workspaceDir:r,tablesCreated:h,migrationsApplied:_,durationMs:Date.now()-a}}catch(f){throw new R(`init failed: ${f instanceof Error?f.message:String(f)}`,"INTERNAL",{cause:f instanceof Error?f.message:String(f)})}finally{S.close();}}var ae=utils.Log.create({service:"memory.service.status"}),Rr=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"],Sr={};async function pt(t,e={},a=Sr){let r=t.agentId&&t.agentId.trim().length>0?t.agentId:void 0;if(ae.debug("status invoked",{agentId:r??"<global>"}),!t.dbPath||t.dbPath.length===0)throw new R("`ctx.dbPath` is required","INTERNAL");let n={initialized:false,capabilities:{embedding:false,graphLlm:false}},c={},s=0,i=0,u=0,g,S,f,p=false,E,h="uninitialized",_=false,y=false,C,M=Rr.reduce((w,P)=>(w[P]=0,w),{}),N=new chunkLYBUZDJK_cjs.e(t.dbPath);try{await N.initialize(),s=N.query("SELECT COUNT(*) as c FROM memory_facts WHERE agent_id IS NOT NULL",[])[0]?.c??0,i=N.query("SELECT COUNT(*) as c FROM nodes",[])[0]?.c??0,u=N.query("SELECT COUNT(*) as c FROM edges")[0]?.c??0;let G=N.query("SELECT category, COUNT(*) as c FROM memory_facts WHERE agent_id IS NOT NULL GROUP BY category",[]);for(let D of G){let T=D.category;T in M&&(M[T]=D.c);}try{_=N.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]).length>0;}catch(D){ae.debug("status: fts probe failed",{error:D instanceof Error?D.message:String(D)});}y=N.healthCheck();try{let D=N.query("SELECT key, value FROM meta");for(let T of D)c[T.key]=T.value;}catch(D){ae.debug("status: meta read failed",{error:D instanceof Error?D.message:String(D)});}let z=c.schema_version,V=c.extraction_version,d=c.lastSyncAt??c.lastSync,m=c.embeddingDims;g=z&&Number.parseInt(z,10)||void 0,S=V&&Number.parseInt(V,10)||void 0,f=d,E=m&&Number.parseInt(m,10)||void 0,p=E!==void 0||c.vector_enabled==="true"||n.capabilities.embedding===!0,s>0&&(c.index_state==="failed"?h="failed":f?p&&!E?h="partial":h="complete":h="stale");try{C=N.query("SELECT value FROM meta WHERE key = ?",["backend"])[0]?.value??"better-sqlite3";}catch{C="better-sqlite3";}}catch(w){if(w instanceof R)throw w;ae.warn("status: db phase failed; returning partial result",{dbPath:t.dbPath,error:w instanceof Error?w.message:String(w)}),C="unknown",y=false;}finally{N.close();}let b,v;if(fs.existsSync(t.dbPath)){try{let{statSync:P}=await import('fs');v=P(t.dbPath).size;}catch{}let w=null;try{w=new chunkLYBUZDJK_cjs.e(t.dbPath),await w.initialize();let{stats:P}=w.checkIntegrity();b=P;}catch(P){ae.debug("status: checkIntegrity failed; dbStats segment omitted",{dbPath:t.dbPath,error:P instanceof Error?P.message:String(P)});}finally{w&&w.close();}}if(!a.skipLlm&&chunkJ5XF2W4Z_cjs.a.isInitialized()){let P=chunkJ5XF2W4Z_cjs.a.capabilities();n.initialized=true,n.capabilities={embedding:P.embedding===true,graphLlm:P.graphLlm===true},n.embeddingModel=n.capabilities.embedding?"configured":void 0,n.graphModel=n.capabilities.graphLlm?"configured":void 0;}if(!a.skipEmbeddingProbe&&!a.skipLlm&&n.initialized&&n.capabilities.embedding)try{let w=chunkJ5XF2W4Z_cjs.a.getEmbeddingLlm?.();if(w){let P=await llm.probeEmbeddingDims(w,{timeoutMs:5e3});if(typeof P=="number"){E=P,c.embeddingDims=String(P);try{let k=new chunkLYBUZDJK_cjs.e(t.dbPath);try{await k.initialize();let G=k.getDb();llm.syncMeta(G,[["embeddingDims",String(P)]]);}finally{k.close();}}catch{}}}}catch{}let I=h??"uninitialized",l;return y?h==="uninitialized"?l="Run `easbot memory remember <content>` to add the first fact.":I==="stale"&&(l="Index is stale (factsCount > 0 \u4F46\u7F3A lastSyncAt) \u2014 run `easbot memory sync` to refresh file snapshots."):l="Run `easbot memory init` to initialize the database.",y&&I==="failed"&&(y=false),ae.info("status complete",{dbPath:t.dbPath,agentId:r??"<global>",factsCount:s,nodesCount:i,edgesCount:u,healthy:y}),{package:"memory",workspaceDir:t.workspaceDir,agentId:r,dbPath:t.dbPath,dbSize:v,configPath:Ee(t.workspaceDir),configExists:fs.existsSync(Ee(t.workspaceDir)),dbStats:b,schemaVersion:g,extractionVersion:S,lastSyncAt:f,indexState:h,vectorEnabled:p,embeddingDims:E,llm:n,backend:C,meta:c,recommendation:l,healthy:y,factsByCategory:M,dbExists:fs.existsSync(t.dbPath),factsCount:s,nodesCount:i,edgesCount:u,ftsAvailable:_,integrityStats:b}}var vr=utils.Log.create({service:"memory.service.doctor"}),We=100*1024*1024,yt=100*1024*1024,Cr={};function O(t,e,a,r,n){return {code:t.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),severity:e,name:t,message:a,details:n,durationMs:r,passed:e!=="error"}}async function ht(t,e={},a=Cr){if(vr.debug("doctor invoked",{agentId:t.agentId}),!t.dbPath||t.dbPath.length===0)throw new Error("`ctx.dbPath` is required");let r=[],n=[],c=Date.now(),s=null,i=false,u=Date.now();try{s=new chunkLYBUZDJK_cjs.e(t.dbPath),await s.initialize(),i=!0;let d=s.healthCheck(),m=O("database",d?"ok":"error",d?"database connected and writable":"database unhealthy",Date.now()-u,{dbPath:t.dbPath});r.push(m),n.push({name:m.name,passed:m.severity!=="error",message:m.message,details:m.details,severity:m.severity});}catch(d){let m=O("database","error",`database connection failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-u,{dbPath:t.dbPath});r.push(m),n.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}let g=Date.now();if(i&&s)try{let d=s.query("SELECT name FROM sqlite_master WHERE type = ? AND name = ?",["table","memory_facts_fts"]),m=d.length>0,D=O("fts",m?"ok":"warn",m?"FTS5 index available":"FTS5 index not found",Date.now()-g,m?{table:d[0]?.name}:void 0);r.push(D),n.push({name:D.name,passed:D.severity!=="error",message:D.message,details:D.details,severity:D.severity});}catch(d){let m=O("fts","error",`fts probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-g);r.push(m),n.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}else {let d=O("fts","info","skipped (db not initialized)",0);r.push(d),n.push({name:d.name,passed:true,message:d.message,severity:"info"});}let S=Date.now(),f=!!t.config?.embeddingLlm,p=O("vector","ok",f?"embedding model available":"no embedding model configured (FTS-only mode, recall still functional)",Date.now()-S,{mode:f?"hybrid":"fts_only",model:f?"configured":"missing"});r.push(p),n.push({name:p.name,passed:true,message:p.message,details:p.details,severity:"ok"});let E=Date.now();if(i&&s)try{let d=["memory_facts","nodes","edges","meta"],m=s.query("SELECT name FROM sqlite_master WHERE type = ?",["table"]),D=new Set(m.map(q=>q.name)),T=d.filter(q=>!D.has(q)),A=O("schema",T.length===0?"ok":"error",T.length===0?`schema complete (${d.length} tables)`:`missing tables: ${T.join(", ")}`,Date.now()-E,{required:d,existing:Array.from(D)});r.push(A),n.push({name:A.name,passed:A.severity!=="error",message:A.message,details:A.details,severity:A.severity});}catch(d){let m=O("schema","error",`schema probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-E);r.push(m),n.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}else {let d=O("schema","info","skipped (db not initialized)",0);r.push(d),n.push({name:d.name,passed:true,message:d.message,severity:"info"});}let h=Date.now();try{let d=`${t.dbPath}-wal`,m=`${t.dbPath}-shm`,D=0,T=0;try{D=(await Q__default.default.stat(d)).size;}catch{D=0;}try{T=(await Q__default.default.stat(m)).size;}catch{T=0;}let A=D+T,q=A<=yt,H=O("lock",q?"ok":"warn",q?`no lock contention (wal+shm ${(A/1024).toFixed(1)} KB)`:`WAL/SHM files unusually large (${(A/1024/1024).toFixed(1)} MB > ${(yt/1024/1024).toFixed(0)} MB threshold)`,Date.now()-h,{walBytes:D,shmBytes:T});r.push(H),n.push({name:H.name,passed:H.severity!=="error",message:H.message,details:H.details,severity:H.severity});}catch(d){let m=O("lock","error",`lock probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-h);r.push(m),n.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}let _=Date.now();try{let d=ue__default.default.dirname(t.dbPath),m=await Q__default.default.statfs(d),D=typeof m.bsize=="bigint"?Number(m.bsize)*m.bavail:m.bsize*m.bavail,T=D>=We,A=O("disk_space",T?"ok":"error",T?`sufficient disk space (${(D/1024/1024).toFixed(1)} MB available)`:`low disk space (${(D/1024/1024).toFixed(1)} MB < ${(We/1024/1024).toFixed(0)} MB threshold)`,Date.now()-_,{availableBytes:D,threshold:We});r.push(A),n.push({name:A.name,passed:A.severity!=="error",message:A.message,details:A.details,severity:A.severity});}catch(d){let m=O("disk_space","error",`disk_space probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-_);r.push(m),n.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"error"});}let y=Date.now();if(i&&s)try{let d=s.agentFilter(t.agentId),D=s.query(`SELECT COUNT(*) as c FROM memory_facts ${d.where}`,d.params)[0]?.c??0;if(D===0){let T=O("fact_node_consistency","info","no facts in db \u2014 nothing to check",Date.now()-y);r.push(T),n.push({name:T.name,passed:!0,message:T.message,severity:"info"});}else {let A=s.query(`SELECT COUNT(DISTINCT fn.fact_id) as c
61
+ FROM fact_nodes fn
62
+ INNER JOIN memory_facts mf ON mf.id = fn.fact_id
63
+ ${d.where}`,d.params)[0]?.c??0,q=D>0?A/D*100:0,H=q>=50?"ok":q>=30?"info":"warn",U=q>=50?`${q.toFixed(1)}% facts linked to KG nodes`:q>=30?`${q.toFixed(1)}% facts linked to KG nodes \u2014 run \`easbot memory remember\` to improve`:`${q.toFixed(1)}% facts linked to KG nodes \u2014 KG extraction may be disabled`,Y=O("fact_node_consistency",H,U,Date.now()-y,{facts:D,linked:A,pct:q});r.push(Y),n.push({name:Y.name,passed:Y.severity!=="error",message:Y.message,details:Y.details,severity:Y.severity});}}catch(d){let m=O("fact_node_consistency","warn",`fact_node_consistency probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-y);r.push(m),n.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"warn"});}else {let d=O("fact_node_consistency","info","skipped (db not initialized)",0);r.push(d),n.push({name:d.name,passed:true,message:d.message,severity:"info"});}let C=Date.now();if(i&&s)try{let m=s.query("SELECT COUNT(*) as c FROM nodes",[])[0]?.c??0;if(m===0){let D=O("node_embedding_coverage","info","no nodes in KG \u2014 nothing to check",Date.now()-C);r.push(D),n.push({name:D.name,passed:!0,message:D.message,severity:"info"});}else {let T=s.query("SELECT COUNT(*) as c FROM nodes WHERE embedding IS NOT NULL",[])[0]?.c??0,A=m>0?T/m*100:0,q=A>=50?"ok":A>=30?"info":"warn",H=A>=50?`${A.toFixed(1)}% nodes have embedding (${T}/${m})`:A>=30?`${A.toFixed(1)}% nodes have embedding (${T}/${m}) \u2014 GraphRAG entity vector partial`:`${A.toFixed(1)}% nodes have embedding (${T}/${m}) \u2014 GraphRAG entity vector disabled`,U=O("node_embedding_coverage",q,H,Date.now()-C,{total:m,withEmbedding:T,pct:A});r.push(U),n.push({name:U.name,passed:U.severity!=="error",message:U.message,details:U.details,severity:U.severity});}}catch(d){let m=O("node_embedding_coverage","warn",`node_embedding_coverage probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-C);r.push(m),n.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"warn"});}else {let d=O("node_embedding_coverage","info","skipped (db not initialized)",0);r.push(d),n.push({name:d.name,passed:true,message:d.message,severity:"info"});}let M=Date.now();if(i&&s)try{let m=s.query(`SELECT fn.fact_id, fn.node_id
64
+ FROM fact_nodes fn
65
+ LEFT JOIN nodes n ON fn.node_id = n.id
66
+ WHERE n.id IS NULL
67
+ LIMIT 100`).map(T=>`${T.fact_id}->${T.node_id}`),D=O("orphan",m.length===0?"ok":"warn",m.length===0?"no orphan KG references (fact_nodes all resolved)":`${m.length} orphan fact_nodes references: ${m.slice(0,5).join(", ")}${m.length>5?", ...":""}`,Date.now()-M,{count:m.length});r.push(D),n.push({name:D.name,passed:D.severity!=="error",message:D.message,details:D.details,severity:D.severity});}catch(d){let m=O("orphan","warn",`orphan probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-M);r.push(m),n.push({name:m.name,passed:false,message:m.message,details:m.details,severity:"warn"});}else {let d=O("orphan","info","skipped (db not initialized)",0);r.push(d),n.push({name:d.name,passed:true,message:d.message,severity:"info"});}let N=Date.now(),b={"better-sqlite3":false,"node:sqlite":false,"@tursodatabase/database":false};try{let d=module$1.createRequire(chunkM2YU5LAI_cjs.b);try{d.resolve("better-sqlite3"),b["better-sqlite3"]=!0;}catch{}b["node:sqlite"]=typeof process.versions.sqlite=="string";try{d.resolve("@tursodatabase/database"),b["@tursodatabase/database"]=!0;}catch{}}catch{}let v=b["better-sqlite3"]||b["node:sqlite"],I=O("backend",v?"ok":"error",v?`SQLite backend available (better-sqlite3: ${b["better-sqlite3"]}, node:sqlite: ${b["node:sqlite"]})`:"no SQLite backend available (install better-sqlite3 or use Node 22.5+)",Date.now()-N,b);r.push(I),n.push({name:I.name,passed:I.severity!=="error",message:I.message,details:I.details,severity:I.severity});let l=Date.now();if(i&&s)try{let d=s.query("SELECT COUNT(*) as c FROM embedding_cache")[0],m=s.agentFilter(t.agentId),D=s.query(`SELECT COUNT(*) as c FROM memory_facts ${m.where}`,m.params)[0],T=d?.c??0,A=D?.c??0,q=Math.max(0,T-A),H=q>0,U=O("embedding_cache_unused","info",H?`by design: ${q} embedding_cache rows remain after fact deletion (cache is global content-hash dedup; forget intentionally doesn't cascade clear cache to preserve same-content hit rate)`:"embedding_cache in sync with memory_facts (no unused rows)",Date.now()-l,{cacheCount:T,factsCount:A,unused:q,policy:"global_content_hash_dedup"});r.push(U),n.push({name:U.name,passed:!H,message:U.message,details:U.details,severity:"info"});}catch(d){let m=O("embedding_cache_unused","info",`embedding_cache_unused probe failed: ${d instanceof Error?d.message:String(d)}`,Date.now()-l);r.push(m),n.push({name:m.name,passed:true,message:m.message,severity:"info"});}else {let d=O("embedding_cache_unused","info","skipped (db not initialized)",0);r.push(d),n.push({name:d.name,passed:true,message:d.message,severity:"info"});}let w=Date.now(),P;if(i&&s)try{let d=s.query("SELECT value FROM meta WHERE key = ?",["embeddingDims"]);P=d[0]?.value&&Number.parseInt(d[0].value,10)||void 0;}catch{}let k;if(a.skipLlm||!chunkJ5XF2W4Z_cjs.a.isInitialized()||!chunkJ5XF2W4Z_cjs.a.capabilities().embedding)k=O(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","llm not initialized; probe skipped",Date.now()-w);else if(a.skipEmbeddingProbe)k=O(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe skipped (--skip-embedding-probe)",Date.now()-w);else try{let d=chunkJ5XF2W4Z_cjs.a.getEmbeddingLlm?.();if(!d)k=O(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","embedding llm not exposed; probe skipped",Date.now()-w);else {let m=await llm.probeEmbeddingDims(d,{timeoutMs:5e3});typeof m!="number"?k=O(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe failed (network / model error)",Date.now()-w):P===void 0?k=O(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe=${m}, meta missing \u2014 next status will sync`,Date.now()-w):m!==P?k=O(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"warn",`probe=${m}, meta=${P} \u2014 mismatch`,Date.now()-w,{probe:m,meta:P}):k=O(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"ok",`probe=${m}, meta=${P} \u2014 consistent`,Date.now()-w);}}catch(d){k=O(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe threw: ${d instanceof Error?d.message:String(d)}`,Date.now()-w);}r.push({...k,details:k.details??void 0,passed:k.severity!=="error"}),n.push({name:k.name,passed:k.severity!=="error",message:k.message,details:k.details??void 0,severity:k.severity});let G;if(i&&s){let d=Date.now();try{let{issues:m,stats:D}=s.checkIntegrity();G=D;for(let T of m)r.push(O("integrity_stats",T.severity,T.message,0,{source:"database.checkIntegrity"}));}catch(m){r.push(O("integrity_stats","warn",`db integrity check failed: ${m instanceof Error?m.message:String(m)}`,Date.now()-d));}}let z=!r.some(d=>d.severity==="error");s&&s.close();let V=Date.now()-c;return {healthy:z,checks:r,legacyChecks:n,durationMs:V,integrityStats:G,backendAvailable:b}}var Ge={name:"recall",scope:"read",schema:we,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Query memory via hybrid search (FTS + vector); returns ranked facts.",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=we.parse(t);if(!e.agentId?.trim())throw new Error("recall: agentId is required");return tt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var je={name:"remember",scope:"write",schema:Re,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Persist a new self-memory fact; auto-extract entities into KG.",readOnlyHint:false,destructiveHint:false,idempotentHint:false},handler:async(t,e)=>{let r=Re.parse(t);if(!e.agentId?.trim())throw new Error("remember: agentId is required");return nt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var ze={name:"update",scope:"write",schema:Se,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Update an existing memory fact (atomic; preserves factId + KG associations).",readOnlyHint:false,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=Se.parse(t);if(!e.agentId?.trim())throw new Error("update: agentId is required");return ot({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var Be={name:"forget",scope:"write",schema:Ie,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Delete memory facts by id / category / time range; supports dryRun.",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let r=Ie.parse(t);if(!e.agentId?.trim())throw new Error("forget: agentId is required");return at({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var Qe={name:"extract",scope:"write",schema:Me,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"Extract facts from a session (server-side pulls messages by lastN).",readOnlyHint:false,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=Me.parse(t);if(!e.agentId?.trim())throw new Error("extract: agentId is required");return it({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var Ke={name:"consolidate",scope:"admin",schema:_e,annotations:{localOnly:true,requiresAgentId:true,defaultDescription:"Run consolidation pipeline: dedup \u2192 archive.",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let r=_e.parse(t);if(!e.isTrustedLocal)throw new Error("consolidate: only trusted local process can invoke this op");if(!e.agentId?.trim())throw new Error("consolidate: agentId is required");return ct({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},r)}};var Ve={name:"sync",scope:"admin",schema:Oe,annotations:{localOnly:true,requiresAgentId:true,defaultDescription:"Sync memory facts to .md files (idempotent skip on existing) and archive expired active files (default 30 days)",readOnlyHint:false,destructiveHint:true,idempotentHint:true},handler:async(t,e)=>{let r=Oe.parse(t);if(!e.isTrustedLocal)throw new Error("sync: only trusted local process can invoke this op");if(!e.agentId?.trim())throw new Error("sync: agentId is required");return lt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},r)}};var Je={name:"graph_query",scope:"read",schema:De,annotations:{localOnly:false,requiresAgentId:true,defaultDescription:"BFS KG neighbor walk from nodeId (default depth=2, maxNodes=100, maxEdgesPerNode=10/100); CLI may also use name fragment via `query`.",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=De.parse(t),n=e.agentId?.trim()||"default";return ut({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:n},r)}};var Ye={name:"status",scope:"read",schema:ve,annotations:{localOnly:false,requiresAgentId:false,defaultDescription:"Memory system status (factsCount / nodesCount / edgesCount / fts / vector).",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=ve.parse(t??{})??{}??{};return pt({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:e.remote??false,config:e.config,agentId:e.agentId},r)}};var Xe={name:"doctor",scope:"admin",schema:Ce,annotations:{localOnly:true,requiresAgentId:false,defaultDescription:"Run 7 health checks (database / fts / vector / schema / lock / disk_space / orphan).",readOnlyHint:true,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{let r=Ce.parse(t??{})??{}??{};if(!e.isTrustedLocal)throw new Error("doctor: only trusted local process can invoke this op");return ht({workspaceDir:e.workspaceDir??"",rootDir:e.workspaceDir??"",dbPath:e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId},r)}};var Ze={name:"init",scope:"admin",schema:Ne,annotations:{localOnly:true,requiresAgentId:false,defaultDescription:"Initialize memory workspace (dirs + db schema + meta).",readOnlyHint:false,destructiveHint:false,idempotentHint:true},handler:async(t,e)=>{if(!e.isTrustedLocal)throw new Error("init: only trusted local process can invoke this op");let r=Ne.parse(t??{})??{}??{};return ft({workspaceDir:r.workspaceDir??e.workspaceDir??"",rootDir:r.workspaceDir??e.workspaceDir??"",dbPath:r.dbPath??e.dbPath??"",locale:e.locale??"en-US",remote:false,config:e.config,agentId:e.agentId??""},r)}};var bt={[Ge.name]:Ge,[je.name]:je,[ze.name]:ze,[Be.name]:Be,[Qe.name]:Qe,[Ke.name]:Ke,[Ve.name]:Ve,[Je.name]:Je,[Ye.name]:Ye,[Xe.name]:Xe,[Ze.name]:Ze},Nr=Object.values(bt);function Or(t,e,a){if(t.annotations.localOnly&&!e.isTrustedLocal)throw new Error(`MEMORY:executeOp: op "${a}" is localOnly; non-trusted caller rejected`);if(t.annotations.requiresAgentId){let r=e.agentId?.trim()??"";if(r.length===0)throw new Error(`MEMORY:executeOp: op "${a}" requires agentId`);e.agentId=r;}}async function Ka(t,e,a){let r=bt[t];if(!r)throw new Error(`executeOp: unknown op "${t}"; available: ${Nr.map(c=>c.name).join(", ")}`);return Or(r,a,t),await r.handler(e,a)}function Ar(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 ns(t,e,a={}){let r=chunkCPRDIUQ4_cjs.j(e),n=utils.Locale.resolveLocaleLang(a.locale);return {agentId:t,dbPath:r,workspaceDir:e,rootDir:e,config:Ar({dbPath:r,workspaceDir:e}),isTrustedLocal:true,locale:n,remote:false,...a}}exports.A=Ar;exports.B=ns;exports.a=Z;exports.b=tt;exports.c=we;exports.d=Re;exports.e=Se;exports.f=Ie;exports.g=Me;exports.h=_e;exports.i=De;exports.j=ve;exports.k=Ce;exports.l=Ne;exports.m=Oe;exports.n=nt;exports.o=ot;exports.p=at;exports.q=it;exports.r=ct;exports.s=lt;exports.t=ut;exports.u=ft;exports.v=pt;exports.w=ht;exports.x=bt;exports.y=Nr;exports.z=Ka;