@easbot/memory 0.3.32 → 0.3.37

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 (35) hide show
  1. package/README.en.md +116 -1
  2. package/README.md +103 -8
  3. package/dist/assets/txt/src/plugin/tool/memory.txt +231 -0
  4. package/dist/chunks/{cache-IGJVAUPS.cjs → cache-IS6GEN55.cjs} +1 -1
  5. package/dist/chunks/{chunk-6H5PTRZL.cjs → chunk-4G4FSAFY.cjs} +1 -1
  6. package/dist/chunks/{chunk-7C2J2PDC.cjs → chunk-IP7VEKQY.cjs} +2 -2
  7. package/dist/chunks/{chunk-DYD3SEPC.cjs → chunk-ISYAE6B7.cjs} +5 -5
  8. package/dist/chunks/{chunk-YAF6HMAE.cjs → chunk-QAEIHJOF.cjs} +8 -8
  9. package/dist/chunks/cli-handler-USK4CPAU.cjs +1 -0
  10. package/dist/chunks/{config-KFPQDFJR.cjs → config-5OTOQBQN.cjs} +1 -1
  11. package/dist/chunks/{consolidate-KZAYROKJ.cjs → consolidate-IKQVVWIQ.cjs} +1 -1
  12. package/dist/chunks/doctor-N6HHFR6Y.cjs +1 -0
  13. package/dist/chunks/{extract-BS6HOLXU.cjs → extract-7DQ6OV34.cjs} +1 -1
  14. package/dist/chunks/{forget-Q6UN6GSW.cjs → forget-4KGLTQ5Q.cjs} +1 -1
  15. package/dist/chunks/{graph-4KBXGMOL.cjs → graph-OG23VZZM.cjs} +1 -1
  16. package/dist/chunks/{init-EBA3ZGC6.cjs → init-UQTPANNI.cjs} +1 -1
  17. package/dist/chunks/{interfaces-TGSOKRFI.cjs → interfaces-LDOE5ZTS.cjs} +1 -1
  18. package/dist/chunks/{llm-TQXCNG4J.cjs → llm-JSVYSX5Y.cjs} +1 -1
  19. package/dist/chunks/{mcp-PH3CLOYP.cjs → mcp-ONIMP7FB.cjs} +1 -1
  20. package/dist/chunks/{recall-SBUTMJPU.cjs → recall-KZRYTTWA.cjs} +1 -1
  21. package/dist/chunks/{remember-FXMXYHLK.cjs → remember-GLOJH457.cjs} +1 -1
  22. package/dist/chunks/{status-H4UKSZAH.cjs → status-POX2GWSQ.cjs} +1 -1
  23. package/dist/chunks/stdio-server-W52CMVJO.cjs +1 -0
  24. package/dist/chunks/{sync-FTZT6MWJ.cjs → sync-I423W5G7.cjs} +1 -1
  25. package/dist/cli.cjs +1 -1
  26. package/dist/index.cjs +28 -1
  27. package/dist/index.d.cts +121 -1
  28. package/dist/index.d.ts +121 -1
  29. package/dist/index.mjs +28 -1
  30. package/package.json +14 -11
  31. package/dist/chunks/cli-handler-IXFJAQFB.cjs +0 -1
  32. package/dist/chunks/doctor-OAWL5FMH.cjs +0 -1
  33. package/dist/chunks/stdio-server-CWA2HGXA.cjs +0 -1
  34. /package/dist/assets/txt/{assets → src/assets}/jieba_dict.txt +0 -0
  35. /package/dist/chunks/{chunk-KFESJR3T.cjs → chunk-R32346OA.cjs} +0 -0
package/README.en.md CHANGED
@@ -6,7 +6,7 @@ Long-term memory library for the EASBOT ecosystem, providing per-agent fact stor
6
6
 
7
7
  ## Version
8
8
 
9
- v0.3.32
9
+ v0.3.37
10
10
  ## Features (v0.4.0)
11
11
 
12
12
  - **9 op unified entry** — `recall / remember / forget / extract / consolidate / graph_query / status / doctor / init`; MCP / CLI / Agent Tool share the same `executeOp(name, args, ctx)`.
@@ -187,6 +187,115 @@ import type {
187
187
  } from '@easbot/memory/hooks';
188
188
  ```
189
189
 
190
+ ### plugin (plugin / hook / tool)
191
+
192
+ `@easbot/memory` ships an installable plugin following the `@easbot/plugin` contract:
193
+ 3 lifecycle hooks and 1 `memory` tool. The implementation lives in `src/plugin/`, and
194
+ every symbol is **imported from the package root** (no subpath exports).
195
+
196
+ ```typescript
197
+ import {
198
+ MemoryPlugin,
199
+ MEMORY_PLUGIN_MANIFEST,
200
+ MEMORY_HOOK_EVENTS,
201
+ MemoryPluginHook,
202
+ createMemoryHookMatchers,
203
+ MemoryTool,
204
+ } from '@easbot/memory';
205
+ ```
206
+
207
+ | Export | Description |
208
+ | ------------------------------------- | ------------------------------------------------------------------------------------------- |
209
+ | `MemoryPlugin` / `default` / `Plugin` | Plugin entry, returns `Promise<PluginDefinition>` |
210
+ | `MEMORY_PLUGIN_MANIFEST` | Manifest mirroring `plugin.json` (`name` / `version` / `entry` / `capabilities`) |
211
+ | `MEMORY_HOOK_EVENTS` | 3 dotted events: `context.build.before` / `session.compacting` / `tool.failure` |
212
+ | `MemoryPluginHook` | `HookInfo` shape (host built-in registration path) |
213
+ | `createMemoryHookMatchers()` | `HookMatcher[]` shape (plugin registration path) |
214
+ | `MemoryTool` | `ToolDefinition`: flat `args` map (`operation` + per-op params), `execute` returns a string |
215
+ | `MEMORY_TOOL_OPS` | 7 ops: `recall` / `remember` / `update` / `forget` / `extract` / `graph_query` / `status` |
216
+ | `MEMORY_TOOL_ARGS` | Flat parameter schema, field-by-field aligned with the host built-in memory tool |
217
+
218
+ #### Tool parameter contract (aligned with the host built-in tool)
219
+
220
+ The plugin tool `args` match the host built-in `packages/agent/src/tool/memory.ts`
221
+ field by field: `operation` selects the op, and the remaining flat parameters are
222
+ shared across ops (the host `packages/agent/src/plugin/plugin.ts` enforces
223
+ `z.object(args)`, so a discriminated union is not available).
224
+
225
+ | Op | Effective parameters |
226
+ | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
227
+ | `recall` | `query` (required) / `limit` (default 10, max 100) / `category` / `minImportance` / `maxEdgesPerNode` / `includeGraph` / `includeShared` |
228
+ | `remember` | `content` (required) / `category` / `importance` (1-10) / `tags` |
229
+ | `update` | `factId` (required) plus at least one of `content` / `category` / `importance` / `tags` |
230
+ | `forget` | `factId` (required) / `dryRun` / `force` |
231
+ | `extract` | `lastN` (default 10) / `fromMessageId` |
232
+ | `graph_query` | `query` or `nodeId` (one required) / `maxDepth` (default 2, max 5) / `maxNodes` (default 100, max 500) / `maxEdgesPerNode` |
233
+ | `status` | no extra parameters |
234
+
235
+ Op-specific required fields, ranges and mutual exclusions are validated a second
236
+ time inside the plugin (`parseOperationParams`); validation failures return a
237
+ structured error instead of throwing.
238
+
239
+ #### Distribution artifact generation
240
+
241
+ The distribution artifacts under `plugins/memory/` (`plugin.json` / `package.json` /
242
+ `index.mjs`) and this plugin's entry in `plugins/.easbot-plugin/marketplace.json`
243
+ **MUST be generated by the script, MUST NOT be edited by hand**:
244
+
245
+ ```bash
246
+ # Generate / refresh the distribution artifacts
247
+ pnpm plugin:generate
248
+
249
+ # Verify the artifacts are up to date (CI guard, exits 1 when stale)
250
+ pnpm plugin:check
251
+ ```
252
+
253
+ Data sources and outputs of `scripts/generate-plugin-distribution.ts`:
254
+
255
+ | Input | Output |
256
+ | ---------------------------------------------------- | ---------------------------------------------------------- |
257
+ | `version` in `package.json` | version fields in `plugin.json` / `package.json` |
258
+ | `MEMORY_PLUGIN_MANIFEST` in `src/plugin/manifest.ts` | name / description / entry / capabilities in `plugin.json` |
259
+ | allow-listed exports in `src/plugin/index.ts` | re-export identifier in `index.mjs` |
260
+ | `hook/` and `tool/` directories under `src/plugin/` | capabilities validation (exits 1 when undeclared) |
261
+
262
+ The package version is the single source of truth: when
263
+ `MEMORY_PLUGIN_VERSION` in `src/plugin/manifest.ts` diverges, the script syncs it
264
+ to the package version (in `--check` mode it only reports the divergence).
265
+ The script is idempotent — nothing is written when the artifacts already match.
266
+
267
+ #### Installation and runtime loading
268
+
269
+ The distribution directory lives in the repository-root distribution area
270
+ `plugins/memory/` (`{plugin.json,package.json,index.mjs}`); the marketplace
271
+ manifest is the single repo-wide one at `plugins/.easbot-plugin/marketplace.json`.
272
+ `index.mjs` only re-exports the package root, therefore you MUST build
273
+ `@easbot/memory` before using it.
274
+
275
+ ```bash
276
+ pnpm --filter @easbot/memory build
277
+
278
+ # Register the local marketplace (path is the repository-root distribution area)
279
+ easbot plugins marketplace add ./plugins
280
+
281
+ # Install the memory plugin (non-interactive requires an explicit scope)
282
+ easbot plugins install -m plugins -p memory --project -y --json
283
+
284
+ # Inspect runtime registration: hooks=4 / tools=1
285
+ easbot plugins list --json
286
+ easbot plugins info memory --json
287
+ ```
288
+
289
+ `install` copies `memory/` into `<scope>/plugins/memory/` and writes
290
+ `marketplace:<marketId>|memory` into `config.plugin`; at runtime the specifier is
291
+ resolved to the installed `plugin.json.entry`, then imported and registered
292
+ (hooks + tool). `disable memory` removes the config entry so the plugin is no
293
+ longer loaded, `enable memory` appends it back.
294
+
295
+ > Constraints: only `.mjs` / `.js` / `.cjs` artifacts are loaded — never `.ts`
296
+ > sources; no network access and no cloning. `plugin.json.entry` must start with
297
+ > `./` and must not contain `..` segments.
298
+
190
299
  ## CLI / MCP dual entry (v0.4 stage 4)
191
300
 
192
301
  ### Standalone CLI (`easbot-memory`)
@@ -474,6 +583,12 @@ pnpm type-check
474
583
 
475
584
  # Lint (biome 2.x)
476
585
  pnpm biome-lint
586
+
587
+ # Generate the plugin distribution artifacts (plugins/memory + marketplace manifest)
588
+ pnpm plugin:generate
589
+
590
+ # Verify the plugin distribution artifacts are up to date
591
+ pnpm plugin:check
477
592
  ```
478
593
 
479
594
  ## License
package/README.md CHANGED
@@ -6,7 +6,7 @@ EASBOT 生态系统的长期记忆管理库(v0.4.0)。提供分层记忆、K
6
6
 
7
7
  ## 版本
8
8
 
9
- v0.3.32
9
+ v0.3.37
10
10
  ## 特性(v0.4.0)
11
11
 
12
12
  - **10 op 统一入口**(ADR 0069 +1 sync):`recall / remember / forget / extract / consolidate / sync / graph_query / status / doctor / init`,MCP / CLI / Agent Tool 三端共享。
@@ -200,17 +200,106 @@ import { executeOp, OP_REGISTRY, ALL_OPS } from '@easbot/memory/operations';
200
200
  import { renderOperationMarkdown } from '@easbot/memory/format/render';
201
201
  ```
202
202
 
203
- ### hooks(4 hook 类型)
203
+ ### 插件(plugin / hook / tool)
204
+
205
+ `@easbot/memory` 按 `@easbot/plugin` 契约提供可安装插件:3 个生命周期 hook 与 1 个 `memory` 工具。
206
+ 实现位于 `src/plugin/`,所有符号**统一从包根入口导入**(不提供 subpath 导出)。
204
207
 
205
208
  ```typescript
206
- import type {
207
- PreCompactHook,
208
- SessionStartHook,
209
- SessionEndHook,
210
- PostToolFailureHook,
211
- } from '@easbot/memory/hooks';
209
+ import {
210
+ MemoryPlugin,
211
+ MEMORY_PLUGIN_MANIFEST,
212
+ MEMORY_HOOK_EVENTS,
213
+ MemoryPluginHook,
214
+ createMemoryHookMatchers,
215
+ MemoryTool,
216
+ } from '@easbot/memory';
217
+ ```
218
+
219
+ | 导出 | 说明 |
220
+ | ------------------------------------- | ------------------------------------------------------------------------------------------- |
221
+ | `MemoryPlugin` / `default` / `Plugin` | 插件入口,返回 `Promise<PluginDefinition>` |
222
+ | `MEMORY_PLUGIN_MANIFEST` | `plugin.json` 对应的清单(`name` / `version` / `entry` / `capabilities`) |
223
+ | `MEMORY_HOOK_EVENTS` | 3 个点分事件:`context.build.before` / `session.compacting` / `tool.failure` |
224
+ | `MemoryPluginHook` | `HookInfo` 形态(宿主内置注册路径) |
225
+ | `createMemoryHookMatchers()` | `HookMatcher[]` 形态(插件注册路径) |
226
+ | `MemoryTool` | `ToolDefinition`:`args` 为扁平 map(`operation` + 各 op 参数),`execute` 返回字符串 |
227
+ | `MEMORY_TOOL_OPS` | 7 个 op:`recall` / `remember` / `update` / `forget` / `extract` / `graph_query` / `status` |
228
+ | `MEMORY_TOOL_ARGS` | 扁平参数 schema(与宿主内置 memory 工具逐字段对齐) |
229
+
230
+ #### 工具参数契约(对齐宿主内置工具)
231
+
232
+ 插件工具的 `args` 与宿主内置 `packages/agent/src/tool/memory.ts` **逐字段一致**:
233
+ `operation` 决定本次调用的 op,其余参数按 op 语义共享(扁平 map,宿主
234
+ `packages/agent/src/plugin/plugin.ts` 会强制 `z.object(args)`,不支持判别联合)。
235
+
236
+ | op | 生效参数 |
237
+ | ------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
238
+ | `recall` | `query`(必填)/ `limit`(默认 10,上限 100)/ `category` / `minImportance` / `maxEdgesPerNode` / `includeGraph` / `includeShared` |
239
+ | `remember` | `content`(必填)/ `category` / `importance`(1-10)/ `tags` |
240
+ | `update` | `factId`(必填)+ `content` / `category` / `importance` / `tags`(至少一项) |
241
+ | `forget` | `factId`(必填)/ `dryRun` / `force` |
242
+ | `extract` | `lastN`(默认 10)/ `fromMessageId` |
243
+ | `graph_query` | `query` 或 `nodeId`(二者其一必填)/ `maxDepth`(默认 2,上限 5)/ `maxNodes`(默认 100,上限 500)/ `maxEdgesPerNode` |
244
+ | `status` | 无额外参数 |
245
+
246
+ op 专属的必填 / 取值范围 / 互斥约束由插件侧做**二次校验**(`parseOperationParams`),
247
+ 校验失败返回结构化错误而非抛异常。
248
+
249
+ #### 分发产物自动生成
250
+
251
+ `plugins/memory/` 下的分发产物(`plugin.json` / `package.json` / `index.mjs`)与
252
+ `plugins/.easbot-plugin/marketplace.json` 中的本插件条目 **MUST 由脚本生成,MUST NOT 手改**:
253
+
254
+ ```bash
255
+ # 生成 / 更新分发产物
256
+ pnpm plugin:generate
257
+
258
+ # 只校验产物是否最新(CI 用,过期则 exit 1)
259
+ pnpm plugin:check
212
260
  ```
213
261
 
262
+ 脚本 `scripts/generate-plugin-distribution.ts` 的数据来源与产物:
263
+
264
+ | 输入 | 产物 |
265
+ | ---------------------------------------------------- | ---------------------------------------------------------- |
266
+ | `package.json` 的 `version` | `plugin.json` / `package.json` 的版本 |
267
+ | `src/plugin/manifest.ts` 的 `MEMORY_PLUGIN_MANIFEST` | `plugin.json` 的 name / description / entry / capabilities |
268
+ | `src/plugin/index.ts` 的白名单导出 | `index.mjs` 的 re-export 标识符 |
269
+ | `src/plugin/` 下的 `hook/` `tool/` 目录 | capabilities 能力校验(缺声明即报错退出) |
270
+
271
+ 版本真值源是 `package.json`;`src/plugin/manifest.ts` 的 `MEMORY_PLUGIN_VERSION`
272
+ 与之不一致时脚本会自动同步(`--check` 模式只报错不改文件)。
273
+ 脚本幂等:产物内容与磁盘一致时不写盘。
274
+
275
+ #### 安装与运行时加载
276
+
277
+ 分发目录位于仓根统一分发区 `plugins/memory/`(`{plugin.json,package.json,index.mjs}`),
278
+ marketplace 清单为仓内唯一一份 `plugins/.easbot-plugin/marketplace.json`。
279
+ `index.mjs` 只做包根 re-export,因此使用前 MUST 先构建 `@easbot/memory`。
280
+
281
+ ```bash
282
+ pnpm --filter @easbot/memory build
283
+
284
+ # 注册本地 marketplace(路径为仓根统一分发区)
285
+ easbot plugins marketplace add ./plugins
286
+
287
+ # 安装 memory 插件(非交互必须显式给出 scope)
288
+ easbot plugins install -m plugins -p memory --project -y --json
289
+
290
+ # 查看运行时注册结果:hooks=4 / tools=1
291
+ easbot plugins list --json
292
+ easbot plugins info memory --json
293
+ ```
294
+
295
+ `install` 会把 `memory/` 复制到 `<scope>/plugins/memory/`,并写入
296
+ `config.plugin` 的 `marketplace:<marketId>|memory`;运行时把该 specifier
297
+ 解析为已安装目录的 `plugin.json.entry`,再 `import()` 并注册 hook 与 tool。
298
+ `disable memory` 删除配置项后不再加载,`enable memory` 追加回来。
299
+
300
+ > 约束:运行时只加载 `.mjs` / `.js` / `.cjs` 产物,不加载 `.ts` 源码、不联网、不 clone。
301
+ > `plugin.json.entry` 必须以 `./` 开头且不含 `..` 段。
302
+
214
303
  ## CLI / MCP 双入口(v0.4 stage 4 落地)
215
304
 
216
305
  ### 独立 CLI(`easbot-memory`)
@@ -500,6 +589,12 @@ pnpm type-check
500
589
 
501
590
  # lint(biome 2.x)
502
591
  pnpm biome-lint
592
+
593
+ # 生成插件分发产物(plugins/memory + marketplace 清单)
594
+ pnpm plugin:generate
595
+
596
+ # 校验插件分发产物是否最新
597
+ pnpm plugin:check
503
598
  ```
504
599
 
505
600
  ## 许可证
@@ -0,0 +1,231 @@
1
+ Persistent memory system with **7 operations** (`recall` / `remember` / `update` / `forget` / `extract` / `graph_query` / `status`) for long-term knowledge across sessions.
2
+
3
+ > The `@easbot/memory` package exposes 11 ops in total; this tool only surfaces 7.
4
+ > `doctor` / `init` are one-shot CLI bootstrap / diagnostics actions.
5
+ > `consolidate` / `sync` are trusted-local long-running batch jobs.
6
+ > Use the CLI for those: `easbot memory {init,status,doctor,consolidate,sync}`.
7
+
8
+ ## Operations
9
+
10
+ Single tool with a discriminated `operation` parameter. Pick **exactly one** operation
11
+ per call. All operations go through `@easbot/memory.executeOp` with `agentId`
12
+ resolved from `ctx.protocolMetadata?.agentId ?? ctx.agent` — **LLM cannot override
13
+ agentId via params**.
14
+
15
+ | operation | purpose | local-only | notes |
16
+ |-----------------|--------------------------------------|-----------|----------------------------------------|
17
+ | `recall` | Hybrid search (FTS + vector) | no | Filters: `category` + inclusive `minImportance` ≥ |
18
+ | `remember` | Persist a new self-memory fact | no | Auto-extracts entities into KG |
19
+ | `update` | Update an existing fact (atomic) | no | `factId` + at least one of `content` / `category` / `importance` / `tags` |
20
+ | `forget` | Delete one fact by `factId` | no | Single-fact delete only |
21
+ | `extract` | Aggregate facts / KG nodes for current session | no | Read-only; `sessionId` from ctx |
22
+ | `graph_query` | KG BFS neighbor expansion | no | `query` is a node-name fragment (NOT natural-language); use `recall` for fact search |
23
+ | `status` | Counts / fts / vector / schema | no | Diagnostic summary |
24
+
25
+ **Workspace init is automatic**: if the memory db does not yet exist when you call any op,
26
+ the tool auto-initializes. If init fails, you will see a friendly error pointing to
27
+ `easbot memory init` (a one-time manual fallback — you do NOT need to call init yourself
28
+ in the normal flow).
29
+
30
+ **`agentId` / `sessionId` / `msgId` are not tool parameters.** They come from ctx
31
+ automatically. Do not attempt to pass them.
32
+
33
+ ## Trust Boundary
34
+
35
+ These fields are **ctx-injected only**; the zod schema rejects any attempt to pass them:
36
+
37
+ - **`agentId`** — from `ctx.protocolMetadata?.agentId ?? ctx.agent`.
38
+ - **`sessionId`** (extract op) — from `ctx.sessionId`.
39
+ - **`workspaceDir`** — from `ctx.workspaceDir ?? Instance.worktree`.
40
+
41
+ For agent-management, cross-session queries, or trust-boundary expansion, use the CLI:
42
+
43
+ ```bash
44
+ easbot memory init # one-time bootstrap
45
+ easbot memory status # full diagnostic
46
+ easbot memory doctor --repair # integrity check + repair
47
+ easbot memory consolidate # dedup → archive
48
+ easbot memory forget --category X # range delete (audit + confirm)
49
+ ```
50
+
51
+ ## When to Use
52
+
53
+ Use `remember` proactively for facts worth retaining — preferences, decisions, technical
54
+ facts, error patterns, workflows, exploration findings, skill creation experience, and
55
+ recurring task context.
56
+
57
+ Use `recall` at session/task start and before suggesting approaches — verify a fact exists
58
+ before re-`remember`ing (avoid duplicates), restore context, check existing decisions.
59
+
60
+ Use `update` (not `forget + remember`) to revise an existing fact — it keeps `factId`,
61
+ KG / FTS / vector associations in sync.
62
+
63
+ Use `forget` to remove a specific fact by `factId` (single delete only). Range / batch
64
+ delete is intentionally not exposed here; use the CLI for that.
65
+
66
+ Use `extract` to aggregate facts (and KG entities) already captured for the current
67
+ session via `ctx.sessionId`. It does NOT run new extraction.
68
+
69
+ Use `graph_query` to traverse entity relationships — supply a `nodeId` (the
70
+ KG node id to start BFS from); the service then performs BFS neighbor expansion
71
+ (`maxEdgesPerNode=10`, `maxDepth=2`, `maxNodes=100` defaults). Pass `relation` and/or `type`
72
+ to filter the BFS results without going through the CLI. For broader scope (shared nodes
73
+ across agents), use the CLI `easbot memory graph query`. Use `status` for diagnostics.
74
+
75
+ ## recall parameters
76
+
77
+ - `query` — required text query (FTS5 tokenization + optional vector hybrid scoring when
78
+ embedding is configured; falls back to FTS-only if vector unavailable).
79
+ - `limit` — max results to return (default 10, max 100).
80
+ - `category` — exact-match filter on `MemoryCategory` enum. Omitted → no category filter.
81
+ - `minImportance` — **inclusive `≥`** filter on the 1-10 importance scale
82
+ (SQL `WHERE importance >= ?`). Range `[1, 10]` (validated by zod refine). Omitted → no
83
+ importance filter (returns facts of any importance). `minImportance: 5` keeps
84
+ importance `5`; for strictly `> 5`, pass `6`.
85
+ - `minScore` — minimum relevance score filter (default 0; range `[0, 1]`). Pass `0` to disable filtering.
86
+ - `maxEdgesPerNode` — cap on edges returned **per KG neighbor node** when `includeGraph=true`
87
+ (default **10**; range `[1, 100]`).
88
+ - `includeGraph` — include KG neighbor subgraph alongside hits (default `false`).
89
+ Pass `true` when you actually need BFS neighbors in `recall` output (e.g. you're about to
90
+ answer a "how is X connected to Y" question). Otherwise the LLM has to make a second
91
+ `graph_query` call, which is one extra round-trip.
92
+ - `includeShared` — include shared KG nodes from other agents (default `false`). Requires
93
+ trusted-local. Off by default to keep recall strictly per-agent.
94
+
95
+ ## remember parameters
96
+
97
+ - `content` (required) — the fact body.
98
+ - `category` (required) — `MemoryCategory` enum value (pick the most specific).
99
+ - `importance` (required) — integer in `[1, 10]` (accepts number or numeric string). Service validates range.
100
+ - `tags` (string[], optional) — e.g. `["pnpm","npm"]`. Stored verbatim; whitespace trimmed; empty strings filtered.
101
+
102
+ ## update parameters
103
+
104
+ - `factId` **(required)** — ID of an existing fact (e.g. from `recall` results).
105
+ - At least one of `content` / `category` / `importance` / `tags`. `content` change
106
+ rewrites the embedding and reindexes FTS automatically.
107
+
108
+ ## recall results (cross-op contract)
109
+
110
+ Each `recall` hit includes a `nodes` array (`[{ id, name, type, edges: N }, ...]`) with the KG node
111
+ IDs that the fact is associated with. These **numeric `id`s** are useful for follow-up
112
+ `graph_query(nodeId=<id>)` calls.
113
+
114
+ **Markdown rendering is intentionally concise**:
115
+ each KG node appears as one line — `node #<id>: <name> (<type>) [edges: <count>]` —
116
+ with a hint `use \`graph_query(nodeId=<id>)\` for full relation graph`. Edges are **not**
117
+ expanded inline to keep `recall` output bounded; pass `nodeId` back into `graph_query`
118
+ to fetch the relation graph.
119
+
120
+ ## graph_query parameters
121
+
122
+ - `nodeId` **(required, positive integer)** — KG node id to start BFS from. Get it from
123
+ a `recall` hit's `nodes[i].id` or from prior `graph_query` results. Accepts both `42`
124
+ and `"42"`. Non-numeric strings like `"n_42"` are rejected by zod.
125
+ - `maxEdgesPerNode` — cap on edges returned **per BFS neighbor node** (default **10**;
126
+ range `[1, 100]`).
127
+ - `maxDepth` — BFS depth for neighbor expansion (default **2**; service range `[1, 5]`).
128
+ - `maxNodes` — cap on total nodes returned after BFS (default **100**; service max 500).
129
+ - `relation` — edge relation filter (single-value exact match, e.g. `"uses"`).
130
+ **Differs from `note.graph_query`'s `relationTypes: string[]`** (array IN match) — the
131
+ memory service does exact equality on a single string, so for multi-relation filtering
132
+ call `graph_query` once per relation.
133
+ - `type` — node type filter for the root node (e.g. `"decision"`); only affects the
134
+ CLI `query`-name path. The `nodeId` path bypasses this filter.
135
+
136
+ > Backward-compat note: the service also accepts a `query` (string) parameter for the
137
+ > CLI fallback path — name-fragment match against `nodes.name`. Agent tool path always
138
+ > uses `nodeId`. For CLI mode use `easbot memory graph query <name-fragment>`.
139
+
140
+ ## forget parameters
141
+
142
+ - `factId` **(required)** — ID of an existing fact to delete.
143
+ - `dryRun` — `true` returns match count without deleting (always throws
144
+ `DRY_RUN_NO_DELETE` to confirm matched count). **Use `dryRun: true` first** to
145
+ check whether the fact is KG-referenced before deciding whether to pass `force`.
146
+ - `force` — `true` skips the KG reference guard and deletes anyway
147
+ (default `false`). Required when the fact is referenced by other facts (which
148
+ happens for almost every fact created via `remember` — KG extraction creates
149
+ edges automatically). **Two-step flow** for a KG-referenced fact:
150
+ 1. `forget(factId=X, dryRun=true)` → confirm matched count
151
+ 2. `forget(factId=X, force=true)` → actually delete
152
+
153
+ ## Anti-patterns
154
+
155
+ - **Do NOT use `forget + remember` to update a fact** — it loses `factId`, breaks KG/FTS
156
+ associations, and `forget` has no importance-threshold guard. Use `update`.
157
+ - **Do NOT pass `category` / `fromTime` / `toTime` to `forget`** — only `factId` is
158
+ accepted. For range delete use `easbot memory forget --category X`.
159
+ - **Do NOT pass `force=true` blindly** — first call `forget(factId=X, dryRun=true)` to
160
+ confirm the matched count, then call `forget(factId=X, force=true)` to actually
161
+ delete. The two-step flow protects against accidental deletion of KG-referenced facts.
162
+ - **Do NOT pass unknown keys** — the schema is strict and rejects unrecognized keys
163
+ (e.g. `startNodeId`, `dir`).
164
+ - **Do NOT omit `minImportance` when you want only "important" facts** — default recall
165
+ returns facts of any importance including low-importance ephemeral entries. Pass
166
+ `minImportance: 7` (or higher) for long-term critical knowledge; `3` for session notes;
167
+ omit only for full inventory.
168
+ - **Do NOT recall speculatively on every message** — if there is no plausible match, skip.
169
+ - **Do NOT pass `agentId` / `sessionId` / `msgId`** — they are ctx-injected and the zod
170
+ schema rejects them.
171
+ - **Do NOT retry the tool blindly on init failure** — there is likely a permissions /
172
+ disk issue. Tell the user to run `easbot memory init`.
173
+
174
+ ## After This Tool Runs
175
+
176
+ - **`remember` succeeded** → do NOT call `recall` to "verify"; the fact is already persisted.
177
+ - **`recall` returned results** → if you need more, make ANOTHER `recall` with refined query;
178
+ if you have enough context, proceed.
179
+ - **`update` succeeded** → factId stable; KG / FTS / vector associations refreshed.
180
+ - **`forget` succeeded** → data is gone (no auto-restore); verify with `recall` if needed.
181
+ - **`status`** → snapshot is complete; no need to re-call unless something changed.
182
+ - **Auto-init failed** → tell the user: "memory db could not be created; run `easbot memory init` and retry."
183
+
184
+ ## Categories (pick the most specific)
185
+
186
+ `user_preference` · `technical_fact` · `decision` · `workflow` · `error_pattern` ·
187
+ `exploration_finding` · `experience_summary` · `tool_usage` · `skill_creation` ·
188
+ `task_context` · `relationship` · `reminder` · `test` · `other`
189
+
190
+ ## Importance Scale
191
+
192
+ - **9–10** — Critical, affects all future work (core architecture, strong user constraints)
193
+ - **7–8** — High, frequently relevant (preferences, key decisions)
194
+ - **5–6** — Medium, occasionally useful (task context, one-off fixes)
195
+ - **1–4** — Low, minor details, rarely needed
196
+
197
+ When in doubt, store it. A memory that turns out to be unnecessary costs little.
198
+ A missing memory that causes repeated mistakes costs much more.
199
+
200
+ ## Examples
201
+
202
+ ```
203
+ # User says they prefer pnpm
204
+ memory(operation="remember", content="User prefers pnpm over npm for this project",
205
+ category="user_preference", importance=8, tags="pnpm,npm,package-manager")
206
+
207
+ # Recall user prefs at session start
208
+ memory(operation="recall", query="user preferences", minImportance=7)
209
+
210
+ # Update an existing fact (preserves factId)
211
+ memory(operation="update", factId=42, importance=9)
212
+
213
+ # Delete a confirmed-outdated fact (two-step flow for KG-referenced fact)
214
+ memory(operation="forget", factId=42, dryRun=true) # → matched count
215
+ memory(operation="forget", factId=42, force=true) # → actually delete
216
+
217
+ # Traverse KG neighbors from a node
218
+ memory(operation="graph_query", nodeId=42) # → root + BFS neighbors
219
+
220
+ # Filter graph_query by relation type (memory single-value exact match)
221
+ memory(operation="graph_query", nodeId=42, relation="uses") # → only "uses" edges
222
+
223
+ # Diagnostic snapshot
224
+ memory(operation="status")
225
+ ```
226
+
227
+ ## Proactive Usage Pattern
228
+
229
+ **At session start**: recall relevant context before diving in.
230
+ **During work**: remember discoveries, decisions, and corrections as they happen — don't batch them to the end.
231
+ **At session end**: store any important outcomes or learnings that aren't already saved.
@@ -1 +1 @@
1
- 'use strict';var chunkNHRRIJFK_cjs=require('./chunk-NHRRIJFK.cjs');require('./chunk-GCVKM3RJ.cjs'),require('./chunk-KFESJR3T.cjs');Object.defineProperty(exports,"MEMORY_JSON_REL_PATH",{enumerable:true,get:function(){return chunkNHRRIJFK_cjs.c}});Object.defineProperty(exports,"MemoryCache",{enumerable:true,get:function(){return chunkNHRRIJFK_cjs.d}});
1
+ 'use strict';var chunkNHRRIJFK_cjs=require('./chunk-NHRRIJFK.cjs');require('./chunk-GCVKM3RJ.cjs'),require('./chunk-R32346OA.cjs');Object.defineProperty(exports,"MEMORY_JSON_REL_PATH",{enumerable:true,get:function(){return chunkNHRRIJFK_cjs.c}});Object.defineProperty(exports,"MemoryCache",{enumerable:true,get:function(){return chunkNHRRIJFK_cjs.d}});
@@ -1 +1 @@
1
- 'use strict';var chunkGCVKM3RJ_cjs=require('./chunk-GCVKM3RJ.cjs'),utils=require('@easbot/utils'),terminal=require('@easbot/terminal');var w=utils.Log.create({service:"memory.cli"}),v=[{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(l,t){let e=v.filter(s=>s.group===l);return terminal.renderLines({title:t,flat:e.map(s=>`$ easbot-memory ${s.name.padEnd(14)} ${s.description}`)})}function j(){let l=[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(l);}function C(){j(),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 M(){try{let{Llm:l}=await import('./llm-TQXCNG4J.cjs'),{MemoryCache:t}=await import('./cache-IGJVAUPS.cjs'),e=await t.getMemoryJson();l.init({models:{embedding:e?.embedding_model??void 0,graph:e?.graph_model??void 0}});}catch(l){w.warn("Llm init failed; Llm-related features will be disabled",{error:utils.errorMeta(l)});}}async function P(l,t){let [e,...s]=l;t?.cwd??process.cwd();let c=t?.agentId??"default";if(!e)return C(),{code:0,handled:true,command:null};await M();let m=s.includes("--json");try{switch(e){case "init":{let{parseInitOptions:i,runInit:a}=await import('./init-EBA3ZGC6.cjs'),n=i(s);if(n.help)return console.log("Usage: easbot-memory init [--force] [--json]"),{code:0,handled:!0,command:e};let o=await a({...n,agentId:c});if(n.json)terminal.emitJsonOk(o,{command:e});else {let r=o;terminal.printHuman([terminal.formatKnowledgeInit({packageName:"memory",configPath:r.configPath??r.dbPath,backend:"better-sqlite3",schemaVersion:r.schemaVersion,extras:{dbPath:r.dbPath,migrationsApplied:r.migrationsApplied,tablesCreated:r.tablesCreated,durationMs:`${r.durationMs}ms`}})],{title:"init memory workspace",boxed:!0});}return {code:0,handled:!0,command:e}}case "recall":{let{parseRecallOptions:i,runRecall:a,formatRecallText:n}=await import('./recall-SBUTMJPU.cjs'),o=i(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 r=await a({...o,agentId:c});return o.json?terminal.emitJsonOk(r,{command:e}):terminal.printHuman([n(r)],{title:`recall (agentId=${c??"default"})`}),{code:0,handled:!0,command:e}}case "remember":{let{parseRememberOptions:i,runRemember:a,formatRememberText:n}=await import('./remember-FXMXYHLK.cjs'),o=i(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 r=await a({...o,agentId:c});return o.json?terminal.emitJsonOk(r,{command:e}):terminal.printHuman([n(r)],{title:"remember (persist fact)"}),{code:0,handled:!0,command:e}}case "forget":{let{parseForgetOptions:i,runForget:a,formatForgetText:n}=await import('./forget-Q6UN6GSW.cjs'),o=i(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 r=await a({...o,agentId:c});return o.json?terminal.emitJsonOk(r,{command:e}):terminal.printHuman([n(r)],{title:"forget (delete facts)"}),{code:0,handled:!0,command:e}}case "extract":{let{parseExtractOptions:i,runExtract:a,formatExtractText:n}=await import('./extract-BS6HOLXU.cjs'),o=i(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 r=await a({...o,agentId:c});return o.json?terminal.emitJsonOk(r,{command:e}):terminal.printHuman([n(r)],{title:"extract (from session)"}),{code:0,handled:!0,command:e}}case "consolidate":{let{parseConsolidateOptions:i,runConsolidate:a,formatConsolidateText:n}=await import('./consolidate-KZAYROKJ.cjs'),o=i(s);if(o.help)return console.log("Usage: easbot-memory consolidate [--window-days <n>] [--json]"),{code:0,handled:!0,command:e};let r=await a({...o,agentId:c});return o.json?terminal.emitJsonOk(r,{command:e}):terminal.printHuman([n(r)],{title:"consolidate (pipeline)"}),{code:0,handled:!0,command:e}}case "sync":{let{parseSyncOptions:i,runSync:a,formatSyncText:n}=await import('./sync-FTZT6MWJ.cjs'),o=i(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 r=await a({...o,agentId:c});return o.json?terminal.emitJsonOk(r,{command:e}):terminal.printHuman([n(r)],{title:"sync (db \u2192 .md + archive)"}),{code:0,handled:!0,command:e}}case "graph":{let{parseGraphOptions:i,runGraph:a,formatGraphText:n}=await import('./graph-4KBXGMOL.cjs'),o=i(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 r=await a({...o,agentId:c});return o.json?terminal.emitJsonOk(r,{command:e}):terminal.printHuman([n(r)],{title:"graph_query"}),{code:0,handled:!0,command:e}}case "status":{let{parseStatusOptions:i,runStatus:a}=await import('./status-H4UKSZAH.cjs'),n=i(s);if(n.help)return console.log("Usage: easbot-memory status [--json]"),{code:0,handled:!0,command:e};let o=await a({...n,agentId:c});return n.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:i,runDoctor:a}=await import('./doctor-OAWL5FMH.cjs'),n=i(s);if(n.help)return console.log("Usage: easbot-memory doctor [--repair] [--json]"),{code:0,handled:!0,command:e};let o=await a({...n});return n.json?terminal.emitJsonOk(o,{command:e}):terminal.printHuman([terminal.formatKnowledgeDoctor(R(o))],{title:"memory doctor",boxed:!0}),{code:0,handled:!0,command:e}}case "config":{let{parseConfigOptions:i,runConfig:a,formatConfigText:n}=await import('./config-KFPQDFJR.cjs'),o=i(s);if(o.help)return console.log("Usage: easbot-memory config [--json]"),{code:0,handled:!0,command:e};let r=a(o);return o.json?terminal.emitJsonOk(r,{command:e}):terminal.printHuman([n(r)],{title:"memory config"}),{code:0,handled:!0,command:e}}case "mcp":{let{parseMcpOptions:i,runMcp:a}=await import('./mcp-PH3CLOYP.cjs'),n=i(s);if(n.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(n);return n.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 m?terminal.emitJsonError(e??"__unknown__",`Unknown command: ${e}`):(console.error(`Unknown command: ${e}`),console.error("Run `easbot-memory --help` for available commands.")),{code:2,handled:!1,command:null}}}catch(i){let a=utils.errorMeta(i);w.error("memory CLI command failed",{command:e,error:a});let n=t?.cwd??chunkGCVKM3RJ_cjs.f().worktree;return m?terminal.emitJsonError(e??"__unknown__",a.message):console.error(`[memory] ${n} :: ${e} failed: ${a.message}`),{code:1,handled:true,command:e}}}function K(l){let t=l;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[u,c]of Object.entries(s))typeof c=="number"&&c>0&&(e[`facts/${u}`]=c);}if(t.meta&&typeof t.meta=="object")for(let[s,u]of Object.entries(t.meta))e[`meta/${s}`]=u===void 0?"\u2205":u;return Object.keys(e).length>0?e:void 0})()}}function R(l){let t=l,e=Array.isArray(t.checks)?t.checks:[],s=t.integrityStats,u=t.backendAvailable,c=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(m=>({code:typeof m.code=="string"?m.code:"",severity:m.severity??"info",name:typeof m.name=="string"?m.name:"",message:typeof m.message=="string"?m.message:"",durationMs:typeof m.durationMs=="number"?m.durationMs:void 0,details:m.details})),dbStats:c,backendAvailable:u}}exports.a=v;exports.b=j;exports.c=C;exports.d=P;exports.e=R;
1
+ 'use strict';var chunkGCVKM3RJ_cjs=require('./chunk-GCVKM3RJ.cjs'),utils=require('@easbot/utils'),terminal=require('@easbot/terminal');var w=utils.Log.create({service:"memory.cli"}),v=[{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(l,t){let e=v.filter(s=>s.group===l);return terminal.renderLines({title:t,flat:e.map(s=>`$ easbot-memory ${s.name.padEnd(14)} ${s.description}`)})}function j(){let l=[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(l);}function C(){j(),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 M(){try{let{Llm:l}=await import('./llm-JSVYSX5Y.cjs'),{MemoryCache:t}=await import('./cache-IS6GEN55.cjs'),e=await t.getMemoryJson();l.init({models:{embedding:e?.embedding_model??void 0,graph:e?.graph_model??void 0}});}catch(l){w.warn("Llm init failed; Llm-related features will be disabled",{error:utils.errorMeta(l)});}}async function P(l,t){let [e,...s]=l;t?.cwd??process.cwd();let c=t?.agentId??"default";if(!e)return C(),{code:0,handled:true,command:null};await M();let m=s.includes("--json");try{switch(e){case "init":{let{parseInitOptions:i,runInit:a}=await import('./init-UQTPANNI.cjs'),n=i(s);if(n.help)return console.log("Usage: easbot-memory init [--force] [--json]"),{code:0,handled:!0,command:e};let o=await a({...n,agentId:c});if(n.json)terminal.emitJsonOk(o,{command:e});else {let r=o;terminal.printHuman([terminal.formatKnowledgeInit({packageName:"memory",configPath:r.configPath??r.dbPath,backend:"better-sqlite3",schemaVersion:r.schemaVersion,extras:{dbPath:r.dbPath,migrationsApplied:r.migrationsApplied,tablesCreated:r.tablesCreated,durationMs:`${r.durationMs}ms`}})],{title:"init memory workspace",boxed:!0});}return {code:0,handled:!0,command:e}}case "recall":{let{parseRecallOptions:i,runRecall:a,formatRecallText:n}=await import('./recall-KZRYTTWA.cjs'),o=i(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 r=await a({...o,agentId:c});return o.json?terminal.emitJsonOk(r,{command:e}):terminal.printHuman([n(r)],{title:`recall (agentId=${c??"default"})`}),{code:0,handled:!0,command:e}}case "remember":{let{parseRememberOptions:i,runRemember:a,formatRememberText:n}=await import('./remember-GLOJH457.cjs'),o=i(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 r=await a({...o,agentId:c});return o.json?terminal.emitJsonOk(r,{command:e}):terminal.printHuman([n(r)],{title:"remember (persist fact)"}),{code:0,handled:!0,command:e}}case "forget":{let{parseForgetOptions:i,runForget:a,formatForgetText:n}=await import('./forget-4KGLTQ5Q.cjs'),o=i(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 r=await a({...o,agentId:c});return o.json?terminal.emitJsonOk(r,{command:e}):terminal.printHuman([n(r)],{title:"forget (delete facts)"}),{code:0,handled:!0,command:e}}case "extract":{let{parseExtractOptions:i,runExtract:a,formatExtractText:n}=await import('./extract-7DQ6OV34.cjs'),o=i(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 r=await a({...o,agentId:c});return o.json?terminal.emitJsonOk(r,{command:e}):terminal.printHuman([n(r)],{title:"extract (from session)"}),{code:0,handled:!0,command:e}}case "consolidate":{let{parseConsolidateOptions:i,runConsolidate:a,formatConsolidateText:n}=await import('./consolidate-IKQVVWIQ.cjs'),o=i(s);if(o.help)return console.log("Usage: easbot-memory consolidate [--window-days <n>] [--json]"),{code:0,handled:!0,command:e};let r=await a({...o,agentId:c});return o.json?terminal.emitJsonOk(r,{command:e}):terminal.printHuman([n(r)],{title:"consolidate (pipeline)"}),{code:0,handled:!0,command:e}}case "sync":{let{parseSyncOptions:i,runSync:a,formatSyncText:n}=await import('./sync-I423W5G7.cjs'),o=i(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 r=await a({...o,agentId:c});return o.json?terminal.emitJsonOk(r,{command:e}):terminal.printHuman([n(r)],{title:"sync (db \u2192 .md + archive)"}),{code:0,handled:!0,command:e}}case "graph":{let{parseGraphOptions:i,runGraph:a,formatGraphText:n}=await import('./graph-OG23VZZM.cjs'),o=i(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 r=await a({...o,agentId:c});return o.json?terminal.emitJsonOk(r,{command:e}):terminal.printHuman([n(r)],{title:"graph_query"}),{code:0,handled:!0,command:e}}case "status":{let{parseStatusOptions:i,runStatus:a}=await import('./status-POX2GWSQ.cjs'),n=i(s);if(n.help)return console.log("Usage: easbot-memory status [--json]"),{code:0,handled:!0,command:e};let o=await a({...n,agentId:c});return n.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:i,runDoctor:a}=await import('./doctor-N6HHFR6Y.cjs'),n=i(s);if(n.help)return console.log("Usage: easbot-memory doctor [--repair] [--json]"),{code:0,handled:!0,command:e};let o=await a({...n});return n.json?terminal.emitJsonOk(o,{command:e}):terminal.printHuman([terminal.formatKnowledgeDoctor(R(o))],{title:"memory doctor",boxed:!0}),{code:0,handled:!0,command:e}}case "config":{let{parseConfigOptions:i,runConfig:a,formatConfigText:n}=await import('./config-5OTOQBQN.cjs'),o=i(s);if(o.help)return console.log("Usage: easbot-memory config [--json]"),{code:0,handled:!0,command:e};let r=a(o);return o.json?terminal.emitJsonOk(r,{command:e}):terminal.printHuman([n(r)],{title:"memory config"}),{code:0,handled:!0,command:e}}case "mcp":{let{parseMcpOptions:i,runMcp:a}=await import('./mcp-ONIMP7FB.cjs'),n=i(s);if(n.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(n);return n.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 m?terminal.emitJsonError(e??"__unknown__",`Unknown command: ${e}`):(console.error(`Unknown command: ${e}`),console.error("Run `easbot-memory --help` for available commands.")),{code:2,handled:!1,command:null}}}catch(i){let a=utils.errorMeta(i);w.error("memory CLI command failed",{command:e,error:a});let n=t?.cwd??chunkGCVKM3RJ_cjs.f().worktree;return m?terminal.emitJsonError(e??"__unknown__",a.message):console.error(`[memory] ${n} :: ${e} failed: ${a.message}`),{code:1,handled:true,command:e}}}function K(l){let t=l;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[u,c]of Object.entries(s))typeof c=="number"&&c>0&&(e[`facts/${u}`]=c);}if(t.meta&&typeof t.meta=="object")for(let[s,u]of Object.entries(t.meta))e[`meta/${s}`]=u===void 0?"\u2205":u;return Object.keys(e).length>0?e:void 0})()}}function R(l){let t=l,e=Array.isArray(t.checks)?t.checks:[],s=t.integrityStats,u=t.backendAvailable,c=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(m=>({code:typeof m.code=="string"?m.code:"",severity:m.severity??"info",name:typeof m.name=="string"?m.name:"",message:typeof m.message=="string"?m.message:"",durationMs:typeof m.durationMs=="number"?m.durationMs:void 0,details:m.details})),dbStats:c,backendAvailable:u}}exports.a=v;exports.b=j;exports.c=C;exports.d=P;exports.e=R;
@@ -1,4 +1,4 @@
1
- 'use strict';var chunkAVECFV5K_cjs=require('./chunk-AVECFV5K.cjs'),chunkKFESJR3T_cjs=require('./chunk-KFESJR3T.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database');var l=utils.Log.create({service:"memory.database.migrations"}),g=1,O=[{id:1,description:"v1 baseline: memory_facts / memory_vectors / embedding_cache / memory_facts_fts / nodes / edges / meta\uFF08\u4E0E v0.3.x createTables \u8F93\u51FA\u5BF9\u9F50\uFF0C\u8001 db \u8DD1\u8BE5\u8FC1\u79FB\u4E0D\u7834\u574F\u73B0\u6709\u8868\uFF09",up:[`CREATE TABLE IF NOT EXISTS memory_facts (
1
+ 'use strict';var chunkAVECFV5K_cjs=require('./chunk-AVECFV5K.cjs'),chunkR32346OA_cjs=require('./chunk-R32346OA.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database');var l=utils.Log.create({service:"memory.database.migrations"}),g=1,O=[{id:1,description:"v1 baseline: memory_facts / memory_vectors / embedding_cache / memory_facts_fts / nodes / edges / meta\uFF08\u4E0E v0.3.x createTables \u8F93\u51FA\u5BF9\u9F50\uFF0C\u8001 db \u8DD1\u8BE5\u8FC1\u79FB\u4E0D\u7834\u574F\u73B0\u6709\u8868\uFF09",up:[`CREATE TABLE IF NOT EXISTS memory_facts (
2
2
  id TEXT PRIMARY KEY,
3
3
  agent_id TEXT NOT NULL,
4
4
  session_id TEXT,
@@ -60,7 +60,7 @@
60
60
  )`,"ALTER TABLE nodes ADD COLUMN embedding BLOB","CREATE INDEX IF NOT EXISTS idx_nodes_embedding ON nodes(embedding) WHERE embedding IS NOT NULL"]}];function p(s,e=g,i={}){s.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
61
61
  id INTEGER PRIMARY KEY,
62
62
  applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
63
- )`);let t=s.prepare("SELECT id FROM schema_migrations").all(),n=new Set(t.map(r=>r.id)),o={applied:[],pending:[],errors:[],currentVersion:t.length===0?0:Math.max(...t.map(r=>r.id)),targetVersion:e};for(let r of O){if(r.id>e)break;if(n.has(r.id)){o.pending.push(r.id);continue}if(i.dryRun){o.applied.push(r.id);continue}try{C(s,r.up),s.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(r.id),n.add(r.id),o.applied.push(r.id),l.debug("migration applied",{id:r.id,description:r.description});}catch(c){let d=utils.errorMeta(c),m=r.up[0]??"";o.errors.push({migrationId:r.id,sql:m,error:d.message}),l.warn("migration step failed",{id:r.id,error:d,sqlCount:r.up.length});}}return o}function C(s,e){for(let i of e)try{s.exec(i);}catch(t){let n=utils.errorMeta(t).message;if(b(n)){l.debug("migration: column already exists, skipping",{sql:i.slice(0,80)});continue}throw t}}function b(s){return /duplicate column name/i.test(s)}function _(s){try{let e=s.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(i=>i.id))}catch{return 0}}var N=utils.Log.create({service:"memory.database"}),I=class{constructor(e){chunkKFESJR3T_cjs.a(this,"db",null);chunkKFESJR3T_cjs.a(this,"storagePath");chunkKFESJR3T_cjs.a(this,"backend","better-sqlite3");chunkKFESJR3T_cjs.a(this,"initialized",false);chunkKFESJR3T_cjs.a(this,"initPromise",null);this.storagePath=e===":memory:"?e:utils.Filesystem.normalize(e);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize();try{await this.initPromise,this.initialized=!0;}catch(e){try{this.db&&this.db.close();}catch{}throw this.db=null,this.initPromise=null,e}}}async doInitialize(){try{let e=this.openConnection();e.initialize(),this.db=e,this.applyPragmas(),this.runAllMigrations();}catch(e){throw N.error("Database initialization failed",{error:utils.errorMeta(e)}),e}}openConnection(){return database.createSyncSqliteConnection({path:this.storagePath,backend:this.backend,walMode:true,foreignKeys:true,busyTimeoutMs:5e3})}applyPragmas(){if(this.db)try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("foreign_keys = ON");}catch(e){N.warn("Failed to apply memory PRAGMAs",{error:utils.errorMeta(e)});}}runAllMigrations(){if(!this.db)throw new chunkAVECFV5K_cjs.a.DatabaseNotInitializedError({message:"Database not initialized",method:"runAllMigrations"});let e=p(this.db,g);if(e.errors.length>0){let i=e.errors.map(t=>`migration ${t.migrationId}: ${t.error}`).join("; ");throw new chunkAVECFV5K_cjs.a.MigrationFailedError({message:`Some migrations failed: ${i}`,errSummary:i})}}query(e,i){if(!this.db)throw new chunkAVECFV5K_cjs.a.DatabaseNotInitializedError({message:"Database not initialized. Call initialize() first.",method:"query"});try{let t=this.db.prepare(e);return i?t.all(...i):t.all()}catch(t){throw new chunkAVECFV5K_cjs.a.DatabaseOperationFailedError({message:`Query failed: ${utils.errorMeta(t).message}`,operation:"query"},{cause:t})}}agentFilter(e){return typeof e=="string"&&e.trim().length>0?{where:"WHERE agent_id = ?",params:[e.trim()]}:{where:"",params:[]}}run(e,i){if(!this.db)throw new chunkAVECFV5K_cjs.a.DatabaseNotInitializedError({message:"Database not initialized. Call initialize() first.",method:"run"});try{let t=this.db.prepare(e),n=i?t.run(...i):t.run();return {lastID:Number(n.lastInsertRowid),changes:n.changes}}catch(t){throw new chunkAVECFV5K_cjs.a.DatabaseOperationFailedError({message:`Write failed: ${utils.errorMeta(t).message}`,operation:"write"},{cause:t})}}transaction(e){if(!this.db)throw new chunkAVECFV5K_cjs.a.DatabaseNotInitializedError({message:"Database not initialized. Call initialize() first.",method:"transaction"});return this.db.transaction(e)()}prepare(e){if(!this.db)throw new chunkAVECFV5K_cjs.a.DatabaseNotInitializedError({message:"Database not initialized. Call initialize() first.",method:"prepare"});return this.db.prepare(e)}exec(e){if(!this.db)throw new chunkAVECFV5K_cjs.a.DatabaseNotInitializedError({message:"Database not initialized. Call initialize() first.",method:"exec"});this.db.exec(e);}getDb(){if(!this.db)throw new chunkAVECFV5K_cjs.a.DatabaseNotInitializedError({message:"Database not initialized. Call initialize() first.",method:"getDb"});return this.db}getPath(){return this.storagePath}getSchemaVersion(){if(!this.db)throw new chunkAVECFV5K_cjs.a.DatabaseNotInitializedError({message:"Database not initialized. Call initialize() first.",method:"getSchemaVersion"});return _(this.db)}close(){if(this.db){try{this.db.close();}catch(e){N.warn("Failed to close memory database",{error:utils.errorMeta(e)});}this.db=null,this.initialized=false,this.initPromise=null;}}healthCheck(){try{return this.db?(this.db.exec("SELECT 1"),!0):!1}catch{return false}}checkIntegrity(){if(!this.db)throw new chunkAVECFV5K_cjs.a.DatabaseNotInitializedError({message:"Database not initialized. Call initialize() first.",method:"checkIntegrity"});let e=S=>this.db.prepare(S).get().c,i={memory_facts:e("SELECT COUNT(*) as c FROM memory_facts"),memory_vectors:e("SELECT COUNT(*) as c FROM memory_vectors"),embedding_cache:e("SELECT COUNT(*) as c FROM embedding_cache"),memory_facts_fts:e("SELECT COUNT(*) as c FROM memory_facts_fts"),nodes:e("SELECT COUNT(*) as c FROM nodes"),edges:e("SELECT COUNT(*) as c FROM edges"),fact_nodes:e("SELECT COUNT(*) as c FROM fact_nodes"),meta:e("SELECT COUNT(*) as c FROM meta"),schema_migrations:e("SELECT COUNT(*) as c FROM schema_migrations")},t=[],n=e(`
63
+ )`);let t=s.prepare("SELECT id FROM schema_migrations").all(),n=new Set(t.map(r=>r.id)),o={applied:[],pending:[],errors:[],currentVersion:t.length===0?0:Math.max(...t.map(r=>r.id)),targetVersion:e};for(let r of O){if(r.id>e)break;if(n.has(r.id)){o.pending.push(r.id);continue}if(i.dryRun){o.applied.push(r.id);continue}try{C(s,r.up),s.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(r.id),n.add(r.id),o.applied.push(r.id),l.debug("migration applied",{id:r.id,description:r.description});}catch(c){let d=utils.errorMeta(c),m=r.up[0]??"";o.errors.push({migrationId:r.id,sql:m,error:d.message}),l.warn("migration step failed",{id:r.id,error:d,sqlCount:r.up.length});}}return o}function C(s,e){for(let i of e)try{s.exec(i);}catch(t){let n=utils.errorMeta(t).message;if(b(n)){l.debug("migration: column already exists, skipping",{sql:i.slice(0,80)});continue}throw t}}function b(s){return /duplicate column name/i.test(s)}function _(s){try{let e=s.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(i=>i.id))}catch{return 0}}var N=utils.Log.create({service:"memory.database"}),I=class{constructor(e){chunkR32346OA_cjs.a(this,"db",null);chunkR32346OA_cjs.a(this,"storagePath");chunkR32346OA_cjs.a(this,"backend","better-sqlite3");chunkR32346OA_cjs.a(this,"initialized",false);chunkR32346OA_cjs.a(this,"initPromise",null);this.storagePath=e===":memory:"?e:utils.Filesystem.normalize(e);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize();try{await this.initPromise,this.initialized=!0;}catch(e){try{this.db&&this.db.close();}catch{}throw this.db=null,this.initPromise=null,e}}}async doInitialize(){try{let e=this.openConnection();e.initialize(),this.db=e,this.applyPragmas(),this.runAllMigrations();}catch(e){throw N.error("Database initialization failed",{error:utils.errorMeta(e)}),e}}openConnection(){return database.createSyncSqliteConnection({path:this.storagePath,backend:this.backend,walMode:true,foreignKeys:true,busyTimeoutMs:5e3})}applyPragmas(){if(this.db)try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("foreign_keys = ON");}catch(e){N.warn("Failed to apply memory PRAGMAs",{error:utils.errorMeta(e)});}}runAllMigrations(){if(!this.db)throw new chunkAVECFV5K_cjs.a.DatabaseNotInitializedError({message:"Database not initialized",method:"runAllMigrations"});let e=p(this.db,g);if(e.errors.length>0){let i=e.errors.map(t=>`migration ${t.migrationId}: ${t.error}`).join("; ");throw new chunkAVECFV5K_cjs.a.MigrationFailedError({message:`Some migrations failed: ${i}`,errSummary:i})}}query(e,i){if(!this.db)throw new chunkAVECFV5K_cjs.a.DatabaseNotInitializedError({message:"Database not initialized. Call initialize() first.",method:"query"});try{let t=this.db.prepare(e);return i?t.all(...i):t.all()}catch(t){throw new chunkAVECFV5K_cjs.a.DatabaseOperationFailedError({message:`Query failed: ${utils.errorMeta(t).message}`,operation:"query"},{cause:t})}}agentFilter(e){return typeof e=="string"&&e.trim().length>0?{where:"WHERE agent_id = ?",params:[e.trim()]}:{where:"",params:[]}}run(e,i){if(!this.db)throw new chunkAVECFV5K_cjs.a.DatabaseNotInitializedError({message:"Database not initialized. Call initialize() first.",method:"run"});try{let t=this.db.prepare(e),n=i?t.run(...i):t.run();return {lastID:Number(n.lastInsertRowid),changes:n.changes}}catch(t){throw new chunkAVECFV5K_cjs.a.DatabaseOperationFailedError({message:`Write failed: ${utils.errorMeta(t).message}`,operation:"write"},{cause:t})}}transaction(e){if(!this.db)throw new chunkAVECFV5K_cjs.a.DatabaseNotInitializedError({message:"Database not initialized. Call initialize() first.",method:"transaction"});return this.db.transaction(e)()}prepare(e){if(!this.db)throw new chunkAVECFV5K_cjs.a.DatabaseNotInitializedError({message:"Database not initialized. Call initialize() first.",method:"prepare"});return this.db.prepare(e)}exec(e){if(!this.db)throw new chunkAVECFV5K_cjs.a.DatabaseNotInitializedError({message:"Database not initialized. Call initialize() first.",method:"exec"});this.db.exec(e);}getDb(){if(!this.db)throw new chunkAVECFV5K_cjs.a.DatabaseNotInitializedError({message:"Database not initialized. Call initialize() first.",method:"getDb"});return this.db}getPath(){return this.storagePath}getSchemaVersion(){if(!this.db)throw new chunkAVECFV5K_cjs.a.DatabaseNotInitializedError({message:"Database not initialized. Call initialize() first.",method:"getSchemaVersion"});return _(this.db)}close(){if(this.db){try{this.db.close();}catch(e){N.warn("Failed to close memory database",{error:utils.errorMeta(e)});}this.db=null,this.initialized=false,this.initPromise=null;}}healthCheck(){try{return this.db?(this.db.exec("SELECT 1"),!0):!1}catch{return false}}checkIntegrity(){if(!this.db)throw new chunkAVECFV5K_cjs.a.DatabaseNotInitializedError({message:"Database not initialized. Call initialize() first.",method:"checkIntegrity"});let e=S=>this.db.prepare(S).get().c,i={memory_facts:e("SELECT COUNT(*) as c FROM memory_facts"),memory_vectors:e("SELECT COUNT(*) as c FROM memory_vectors"),embedding_cache:e("SELECT COUNT(*) as c FROM embedding_cache"),memory_facts_fts:e("SELECT COUNT(*) as c FROM memory_facts_fts"),nodes:e("SELECT COUNT(*) as c FROM nodes"),edges:e("SELECT COUNT(*) as c FROM edges"),fact_nodes:e("SELECT COUNT(*) as c FROM fact_nodes"),meta:e("SELECT COUNT(*) as c FROM meta"),schema_migrations:e("SELECT COUNT(*) as c FROM schema_migrations")},t=[],n=e(`
64
64
  SELECT COUNT(*) as c FROM fact_nodes fn
65
65
  LEFT JOIN nodes n ON n.id = fn.node_id
66
66
  WHERE n.id IS NULL