@easbot/memory 0.3.32 → 0.3.36

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 (36) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +50 -8
  3. package/dist/assets/txt/src/plugin/tool/description.txt +12 -0
  4. package/dist/assets/txt/src/plugin/tool/memory.txt +231 -0
  5. package/dist/chunks/{cache-IGJVAUPS.cjs → cache-IS6GEN55.cjs} +1 -1
  6. package/dist/chunks/{chunk-6H5PTRZL.cjs → chunk-4G4FSAFY.cjs} +1 -1
  7. package/dist/chunks/{chunk-7C2J2PDC.cjs → chunk-IP7VEKQY.cjs} +2 -2
  8. package/dist/chunks/{chunk-DYD3SEPC.cjs → chunk-ISYAE6B7.cjs} +5 -5
  9. package/dist/chunks/{chunk-YAF6HMAE.cjs → chunk-QAEIHJOF.cjs} +8 -8
  10. package/dist/chunks/cli-handler-USK4CPAU.cjs +1 -0
  11. package/dist/chunks/{config-KFPQDFJR.cjs → config-5OTOQBQN.cjs} +1 -1
  12. package/dist/chunks/{consolidate-KZAYROKJ.cjs → consolidate-IKQVVWIQ.cjs} +1 -1
  13. package/dist/chunks/doctor-N6HHFR6Y.cjs +1 -0
  14. package/dist/chunks/{extract-BS6HOLXU.cjs → extract-7DQ6OV34.cjs} +1 -1
  15. package/dist/chunks/{forget-Q6UN6GSW.cjs → forget-4KGLTQ5Q.cjs} +1 -1
  16. package/dist/chunks/{graph-4KBXGMOL.cjs → graph-OG23VZZM.cjs} +1 -1
  17. package/dist/chunks/{init-EBA3ZGC6.cjs → init-UQTPANNI.cjs} +1 -1
  18. package/dist/chunks/{interfaces-TGSOKRFI.cjs → interfaces-LDOE5ZTS.cjs} +1 -1
  19. package/dist/chunks/{llm-TQXCNG4J.cjs → llm-JSVYSX5Y.cjs} +1 -1
  20. package/dist/chunks/{mcp-PH3CLOYP.cjs → mcp-ONIMP7FB.cjs} +1 -1
  21. package/dist/chunks/{recall-SBUTMJPU.cjs → recall-KZRYTTWA.cjs} +1 -1
  22. package/dist/chunks/{remember-FXMXYHLK.cjs → remember-GLOJH457.cjs} +1 -1
  23. package/dist/chunks/{status-H4UKSZAH.cjs → status-POX2GWSQ.cjs} +1 -1
  24. package/dist/chunks/stdio-server-W52CMVJO.cjs +1 -0
  25. package/dist/chunks/{sync-FTZT6MWJ.cjs → sync-I423W5G7.cjs} +1 -1
  26. package/dist/cli.cjs +1 -1
  27. package/dist/index.cjs +8 -1
  28. package/dist/index.d.cts +41 -2
  29. package/dist/index.d.ts +41 -2
  30. package/dist/index.mjs +8 -1
  31. package/package.json +12 -11
  32. package/dist/chunks/cli-handler-IXFJAQFB.cjs +0 -1
  33. package/dist/chunks/doctor-OAWL5FMH.cjs +0 -1
  34. package/dist/chunks/stdio-server-CWA2HGXA.cjs +0 -1
  35. /package/dist/assets/txt/{assets → src/assets}/jieba_dict.txt +0 -0
  36. /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.36
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)`.
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.36
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,59 @@ 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 = { op, params }`,`execute` 返回字符串 |
227
+
228
+ #### 安装与运行时加载
229
+
230
+ 分发目录 `packages/memory/plugin/` 含 `.easbot-plugin/marketplace.json` 与
231
+ `memory/{plugin.json,package.json,index.mjs}`。`index.mjs` 只做包根 re-export,
232
+ 因此使用前 MUST 先构建 `@easbot/memory`。
233
+
234
+ ```bash
235
+ pnpm --filter @easbot/memory build
236
+
237
+ # 注册本地 marketplace(路径为分发目录)
238
+ easbot plugins marketplace add ./packages/memory/plugin
239
+
240
+ # 安装 memory 插件(非交互必须显式给出 scope)
241
+ easbot plugins install -m plugin -p memory --project -y --json
242
+
243
+ # 查看运行时注册结果:hooks=4 / tools=1
244
+ easbot plugins list --json
245
+ easbot plugins info memory --json
212
246
  ```
213
247
 
248
+ `install` 会把 `memory/` 复制到 `<scope>/plugins/memory/`,并写入
249
+ `config.plugin` 的 `marketplace:<marketId>|memory`;运行时把该 specifier
250
+ 解析为已安装目录的 `plugin.json.entry`,再 `import()` 并注册 hook 与 tool。
251
+ `disable memory` 删除配置项后不再加载,`enable memory` 追加回来。
252
+
253
+ > 约束:运行时只加载 `.mjs` / `.js` / `.cjs` 产物,不加载 `.ts` 源码、不联网、不 clone。
254
+ > `plugin.json.entry` 必须以 `./` 开头且不含 `..` 段。
255
+
214
256
  ## CLI / MCP 双入口(v0.4 stage 4 落地)
215
257
 
216
258
  ### 独立 CLI(`easbot-memory`)
@@ -0,0 +1,12 @@
1
+ WHEN TO USE:
2
+ Use this tool to read or write EASBot long-term memory. Call it when the user asks to remember something, when you need prior facts or error patterns before answering, or when you need the memory subsystem health status.
3
+
4
+ AFTER THIS:
5
+ Review the returned markdown or JSON. For `recall`, use the returned facts as context and cite them when relevant. For `remember` / `update` / `forget`, report the affected fact id. For `status`, report the health summary.
6
+
7
+ NOTES:
8
+ - `op` selects one of: recall, remember, update, forget, extract, graph_query, status.
9
+ - `params` carries the operation arguments as a flat object; see the memory op schemas for field names.
10
+ - Operations run against the current workspace memory database. Write operations require a trusted local caller.
11
+ - `update` / `extract` return JSON text; the other operations return rendered markdown.
12
+ - Failures return a diagnostic string instead of throwing. Keep going with the rest of the task.
@@ -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
@@ -1,4 +1,4 @@
1
- 'use strict';var chunkYAF6HMAE_cjs=require('./chunk-YAF6HMAE.cjs'),chunkAVECFV5K_cjs=require('./chunk-AVECFV5K.cjs'),mcp=require('@easbot/mcp'),utils=require('@easbot/utils');var ie=utils.Log.create({service:"memory.format.truncate"}),X="**`";var Z=24e3,ee=25e3;async function $(e,n={}){let o=n.softLimit??Z,s=n.hardCeiling??ee,r=n.toolName??"memory",c=n.writeToDisk!==false;if(e.length<=o)return {content:e,truncated:false};let d=e.slice(0,s),t=d.lastIndexOf(`
1
+ 'use strict';var chunkQAEIHJOF_cjs=require('./chunk-QAEIHJOF.cjs'),chunkAVECFV5K_cjs=require('./chunk-AVECFV5K.cjs'),mcp=require('@easbot/mcp'),utils=require('@easbot/utils');var ie=utils.Log.create({service:"memory.format.truncate"}),X="**`";var Z=24e3,ee=25e3;async function $(e,n={}){let o=n.softLimit??Z,s=n.hardCeiling??ee,r=n.toolName??"memory",c=n.writeToDisk!==false;if(e.length<=o)return {content:e,truncated:false};let d=e.slice(0,s),t=d.lastIndexOf(`
2
2
  ${X}`),a=d.lastIndexOf(`
3
3
  `),m;t>s*.5?m=t:a>0?m=a:m=-1;let u=m>0?d.slice(0,m):d,i=u+"\n\n... (output truncated to budget; the source above is complete and verbatim \u2014 treat it as already Read. For any area not covered, make ANOTHER `<tool>` targeting those names \u2014 do NOT Read these files.)";if(!c)return {content:i,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-u.length}/${e.length} characters truncated ...`};try{let f=await utils.TruncateContent.truncate(e,{maxChars:u.length,direction:"head",label:`${r}-output`});return f.truncated?{content:i,truncated:!0,outputPath:f.outputPath,hint:utils.TruncateContent.formatHint(f),info:`... ${f.removedLength}/${f.originalLength} characters truncated ...`}:{content:i,truncated:!0,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-u.length}/${e.length} characters truncated ...`}}catch(f){return ie.warn("TruncateContent.truncate failed, returning without disk hint",{error:utils.errorMeta(f)}),{content:i,truncated:true,outputPath:"",hint:"Make another recall / graph_query with narrower scope.",info:`... ${e.length-u.length}/${e.length} characters truncated ...`}}}function w(e,n={}){let o=n.softLimit??Z,s=n.hardCeiling??ee;if(e.length<=o)return {content:e,truncated:false};let r=e.slice(0,s),c=r.lastIndexOf(`
4
4
  ${X}`),d=r.lastIndexOf(`
@@ -45,20 +45,20 @@ ${e.deletedIds.map(t=>` - ${t}`).join(`
45
45
  `);return n.sync?w(r,{}).content:(await $(r,{toolName:o,writeToDisk:n.writeToDisk})).content}var S=20;async function P(e,n={}){let o=n.toolName??"memory_sync",r=[`**\`memory_sync:${e.dryRun?"DRY_RUN":"OK"}\`**`,"",`windowDays: ${e.windowDays} (threshold: ${e.archiveThreshold})`,"","## Stage A (db \u2192 .md)",`- generated: ${e.generatedCount}`,`- skipped (idempotent): ${e.skippedCount}`,`- failed (best-effort): ${e.failedGenerateCount}`,"","## Stage B (active/ \u2192 archive/)",`- ${e.dryRun?"would archive":"archived"}: ${e.archivedCount}`];if(e.archivedRecords.length>0){r.push("","### Archived records:");let d=e.archivedRecords.slice(0,S);for(let t of d)r.push(`- ${t.firstFactId} (${t.firstCreatedAt})`),r.push(` - source: \`${t.source}\``),r.push(` - target: \`${t.target}\``);e.archivedRecords.length>S&&r.push(`... and ${e.archivedRecords.length-S} more (use --json for full list)`);}r.push("",`duration: ${e.durationMs}ms`,"",I("sync",o));let c=r.join(`
46
46
  `);return n.sync?w(c,{}).content:(await $(c,{toolName:o,writeToDisk:n.writeToDisk})).content}async function j(e,n={}){let o=n.toolName??"memory_doctor",s=`**\`memory_doctor:${e.healthy?"OK":"ISSUES"}\`**`,r=t=>t?"\u2705":"\u274C",c=e.checks.map(t=>`${r(t.passed)} ${t.name}: ${t.message}`).join(`
47
47
  `),d=[s,"",c,"",I("doctor",o)].join(`
48
- `);return n.sync?w(d,{}).content:(await $(d,{toolName:o,writeToDisk:n.writeToDisk})).content}async function R(e,n,o={}){let s=n,r=typeof s.kind=="string";switch((r?s:{kind:e}).kind){case "recall":{let d=r?{hits:s.hits,total:s.totalCount??s.total??0,truncated:s.truncated??false}:n;return v(d,{...o,query:s.query??o.query??"",agentId:s.agentId??o.agentId??"",scope:s.scope??o.scope??"agent_only"})}case "remember":{let d=r?{fact:s.fact,nodeIds:s.nodeIds}:n;return M(d,o)}case "forget":return A(r?s:n,o);case "graph_query":return _(r?s:n,o);case "status":return N(r?s:n,o);case "consolidate":return O(r?s:n,o);case "sync":return P(r?s:n,o);case "doctor":return j(r?s:n,o);default:throw new chunkAVECFV5K_cjs.a.UnsupportedOperationError({message:`renderOperationMarkdown: unsupported op "${e}"`,opName:e,renderer:"markdown"})}}var D=utils.Log.create({service:"memory.mcp.stdio"});function Te(e){let n=new Map,o=e.isRemote??true,s=!o;function r(t){let a=utils.Locale.resolveLocaleLang();return {agentId:t.agentId??e.agentId,isTrustedLocal:t.isTrustedLocal??s,remote:o,locale:a,dbPath:e.dbPath,workspaceDir:e.workspaceDir,rootDir:e.workspaceDir,config:chunkYAF6HMAE_cjs.A({agentId:e.agentId,dbPath:e.dbPath})}}function c(t,a){return {content:[{type:"text",text:t}],isError:a}}function d(t){return mcp.formatFailClosed(t,s)}return n.set("recall",async t=>{try{let a=t,m=r({agentId:a.agentId}),u=await chunkYAF6HMAE_cjs.z("recall",t,m);return {content:[{type:"text",text:await R("recall",u,{toolName:"memory_recall",query:a.query,agentId:a.agentId??e.agentId,scope:a.scope??"agent_only"})}]}}catch(a){return c(d(a),true)}}),n.set("remember",async t=>{try{let m=r({agentId:t.agentId}),u=await chunkYAF6HMAE_cjs.z("remember",t,m);return {content:[{type:"text",text:await R("remember",u,{toolName:"memory_remember"})}]}}catch(a){return c(d(a),true)}}),n.set("update",async t=>{try{let m=r({agentId:t.agentId}),u=await chunkYAF6HMAE_cjs.z("update",t,m),l=u.fieldsUpdated.length>0?u.fieldsUpdated.join(", "):"(no-op)",i=u.contentChanged?" (embedding rewritten)":"";return {content:[{type:"text",text:`Memory updated.
48
+ `);return n.sync?w(d,{}).content:(await $(d,{toolName:o,writeToDisk:n.writeToDisk})).content}async function R(e,n,o={}){let s=n,r=typeof s.kind=="string";switch((r?s:{kind:e}).kind){case "recall":{let d=r?{hits:s.hits,total:s.totalCount??s.total??0,truncated:s.truncated??false}:n;return v(d,{...o,query:s.query??o.query??"",agentId:s.agentId??o.agentId??"",scope:s.scope??o.scope??"agent_only"})}case "remember":{let d=r?{fact:s.fact,nodeIds:s.nodeIds}:n;return M(d,o)}case "forget":return A(r?s:n,o);case "graph_query":return _(r?s:n,o);case "status":return N(r?s:n,o);case "consolidate":return O(r?s:n,o);case "sync":return P(r?s:n,o);case "doctor":return j(r?s:n,o);default:throw new chunkAVECFV5K_cjs.a.UnsupportedOperationError({message:`renderOperationMarkdown: unsupported op "${e}"`,opName:e,renderer:"markdown"})}}var D=utils.Log.create({service:"memory.mcp.stdio"});function Te(e){let n=new Map,o=e.isRemote??true,s=!o;function r(t){let a=utils.Locale.resolveLocaleLang();return {agentId:t.agentId??e.agentId,isTrustedLocal:t.isTrustedLocal??s,remote:o,locale:a,dbPath:e.dbPath,workspaceDir:e.workspaceDir,rootDir:e.workspaceDir,config:chunkQAEIHJOF_cjs.A({agentId:e.agentId,dbPath:e.dbPath})}}function c(t,a){return {content:[{type:"text",text:t}],isError:a}}function d(t){return mcp.formatFailClosed(t,s)}return n.set("recall",async t=>{try{let a=t,m=r({agentId:a.agentId}),u=await chunkQAEIHJOF_cjs.z("recall",t,m);return {content:[{type:"text",text:await R("recall",u,{toolName:"memory_recall",query:a.query,agentId:a.agentId??e.agentId,scope:a.scope??"agent_only"})}]}}catch(a){return c(d(a),true)}}),n.set("remember",async t=>{try{let m=r({agentId:t.agentId}),u=await chunkQAEIHJOF_cjs.z("remember",t,m);return {content:[{type:"text",text:await R("remember",u,{toolName:"memory_remember"})}]}}catch(a){return c(d(a),true)}}),n.set("update",async t=>{try{let m=r({agentId:t.agentId}),u=await chunkQAEIHJOF_cjs.z("update",t,m),l=u.fieldsUpdated.length>0?u.fieldsUpdated.join(", "):"(no-op)",i=u.contentChanged?" (embedding rewritten)":"";return {content:[{type:"text",text:`Memory updated.
49
49
  id: ${u.fact.id}
50
50
  category: ${u.fact.category}
51
51
  importance: ${u.fact.importance}
52
52
  fields updated: ${l}${i}
53
53
  updated_at: ${u.fact.updatedAt}
54
- `}]}}catch(a){return c(d(a),true)}}),n.set("forget",async t=>{try{let m=r({agentId:t.agentId}),u=await chunkYAF6HMAE_cjs.z("forget",t,m);return {content:[{type:"text",text:await R("forget",u,{toolName:"memory_forget"})}]}}catch(a){return c(d(a),true)}}),n.set("extract",async t=>{try{let m=r({agentId:t.agentId}),l=await chunkYAF6HMAE_cjs.z("extract",t,m);return {content:[{type:"text",text:`Extract completed.
54
+ `}]}}catch(a){return c(d(a),true)}}),n.set("forget",async t=>{try{let m=r({agentId:t.agentId}),u=await chunkQAEIHJOF_cjs.z("forget",t,m);return {content:[{type:"text",text:await R("forget",u,{toolName:"memory_forget"})}]}}catch(a){return c(d(a),true)}}),n.set("extract",async t=>{try{let m=r({agentId:t.agentId}),l=await chunkQAEIHJOF_cjs.z("extract",t,m);return {content:[{type:"text",text:`Extract completed.
55
55
  sessionId: ${t.sessionId??"(unknown)"}
56
56
  extractedCount: ${l.extractedCount}
57
57
  factIds: ${l.factIds.length>0?l.factIds.join(", "):"(none)"}
58
58
  messageRange: ${l.messageRange.fromMessageId} -> ${l.messageRange.toMessageId}
59
- `}]}}catch(a){return c(d(a),true)}}),n.set("consolidate",async t=>{try{let m=r({agentId:t.agentId,isTrustedLocal:!0}),u=await chunkYAF6HMAE_cjs.z("consolidate",t,m);return {content:[{type:"text",text:await R("consolidate",u,{toolName:"memory_consolidate"})}]}}catch(a){return c(d(a),true)}}),n.set("sync",async t=>{try{let m=t.agentId?.trim();if(!m)return c(d(new Error("memory_sync: agentId is required (sync requires agentId, see ADR 0069)")),!0);let u=r({agentId:m,isTrustedLocal:!0}),l=await chunkYAF6HMAE_cjs.z("sync",t,u);return {content:[{type:"text",text:await R("sync",l,{toolName:"memory_sync"})}]}}catch(a){return c(d(a),true)}}),n.set("graph_query",async t=>{try{let a=t,m=r({agentId:a.agentId}),u=await chunkYAF6HMAE_cjs.z("graph_query",t,m);return {content:[{type:"text",text:await R("graph_query",u,{toolName:"memory_graph_query",scope:a.scope??"agent_only"})}]}}catch(a){return c(d(a),true)}}),n.set("status",async t=>{try{let m=r({agentId:(t??{}).agentId}),u=await chunkYAF6HMAE_cjs.z("status",t,m),{renderKnowledgeStatus:l}=await import('@easbot/terminal'),i=u;return {content:[{type:"text",text:l({packageName:"memory",rootDir:i.workspaceDir??"",configPath:i.configPath??"",configExists:typeof i.configExists=="boolean"?i.configExists:!0,dbPath:i.dbPath??"",dbExists:typeof i.dbExists=="boolean"?i.dbExists:!0,dbSize:typeof i.dbSize=="number"?i.dbSize:void 0,indexState:i.indexState,schemaVersion:typeof i.schemaVersion=="number"?i.schemaVersion:void 0,extractionVersion:typeof i.extractionVersion=="number"?i.extractionVersion:void 0,lastSyncAt:i.lastSyncAt,vectorEnabled:typeof i.vectorEnabled=="boolean"?i.vectorEnabled:!1,embeddingDims:typeof i.embeddingDims=="number"?i.embeddingDims:void 0,llm:i.llm??{initialized:!1,capabilities:{}},backend:i.backend,healthy:typeof i.healthy=="boolean"?i.healthy:!0,recommendation:i.recommendation,dbStats:(()=>{let p=i.dbStats;if(p&&typeof p=="object"&&Object.keys(p).length>0)return {...p};let g=i.integrityStats;if(g&&typeof g=="object"&&Object.keys(g).length>0)return {...g}})(),extras:(()=>{let p={};if(typeof i.agentId=="string"&&(p.agent_id=i.agentId),typeof i.ftsAvailable=="boolean"&&(p.fts_available=i.ftsAvailable?"yes":"no"),i.factsByCategory&&typeof i.factsByCategory=="object")for(let[g,b]of Object.entries(i.factsByCategory))typeof b=="number"&&b>0&&(p[`facts/${g}`]=b);if(i.meta&&typeof i.meta=="object")for(let[g,b]of Object.entries(i.meta))b!==void 0&&(p[`meta/${g}`]=b);return Object.keys(p).length>0?p:void 0})()})}]}}catch(a){return c(d(a),true)}}),n.set("doctor",async t=>{try{let m=r({agentId:(t??{}).agentId,isTrustedLocal:!0}),u=await chunkYAF6HMAE_cjs.z("doctor",t,m);return {content:[{type:"text",text:await R("doctor",u,{toolName:"memory_doctor"})}]}}catch(a){return c(d(a),true)}}),n.set("init",async t=>{try{let a=r({isTrustedLocal:!0}),u=await chunkYAF6HMAE_cjs.z("init",t,a);return {content:[{type:"text",text:`Init complete.
59
+ `}]}}catch(a){return c(d(a),true)}}),n.set("consolidate",async t=>{try{let m=r({agentId:t.agentId,isTrustedLocal:!0}),u=await chunkQAEIHJOF_cjs.z("consolidate",t,m);return {content:[{type:"text",text:await R("consolidate",u,{toolName:"memory_consolidate"})}]}}catch(a){return c(d(a),true)}}),n.set("sync",async t=>{try{let m=t.agentId?.trim();if(!m)return c(d(new Error("memory_sync: agentId is required (sync requires agentId, see ADR 0069)")),!0);let u=r({agentId:m,isTrustedLocal:!0}),l=await chunkQAEIHJOF_cjs.z("sync",t,u);return {content:[{type:"text",text:await R("sync",l,{toolName:"memory_sync"})}]}}catch(a){return c(d(a),true)}}),n.set("graph_query",async t=>{try{let a=t,m=r({agentId:a.agentId}),u=await chunkQAEIHJOF_cjs.z("graph_query",t,m);return {content:[{type:"text",text:await R("graph_query",u,{toolName:"memory_graph_query",scope:a.scope??"agent_only"})}]}}catch(a){return c(d(a),true)}}),n.set("status",async t=>{try{let m=r({agentId:(t??{}).agentId}),u=await chunkQAEIHJOF_cjs.z("status",t,m),{renderKnowledgeStatus:l}=await import('@easbot/terminal'),i=u;return {content:[{type:"text",text:l({packageName:"memory",rootDir:i.workspaceDir??"",configPath:i.configPath??"",configExists:typeof i.configExists=="boolean"?i.configExists:!0,dbPath:i.dbPath??"",dbExists:typeof i.dbExists=="boolean"?i.dbExists:!0,dbSize:typeof i.dbSize=="number"?i.dbSize:void 0,indexState:i.indexState,schemaVersion:typeof i.schemaVersion=="number"?i.schemaVersion:void 0,extractionVersion:typeof i.extractionVersion=="number"?i.extractionVersion:void 0,lastSyncAt:i.lastSyncAt,vectorEnabled:typeof i.vectorEnabled=="boolean"?i.vectorEnabled:!1,embeddingDims:typeof i.embeddingDims=="number"?i.embeddingDims:void 0,llm:i.llm??{initialized:!1,capabilities:{}},backend:i.backend,healthy:typeof i.healthy=="boolean"?i.healthy:!0,recommendation:i.recommendation,dbStats:(()=>{let p=i.dbStats;if(p&&typeof p=="object"&&Object.keys(p).length>0)return {...p};let g=i.integrityStats;if(g&&typeof g=="object"&&Object.keys(g).length>0)return {...g}})(),extras:(()=>{let p={};if(typeof i.agentId=="string"&&(p.agent_id=i.agentId),typeof i.ftsAvailable=="boolean"&&(p.fts_available=i.ftsAvailable?"yes":"no"),i.factsByCategory&&typeof i.factsByCategory=="object")for(let[g,b]of Object.entries(i.factsByCategory))typeof b=="number"&&b>0&&(p[`facts/${g}`]=b);if(i.meta&&typeof i.meta=="object")for(let[g,b]of Object.entries(i.meta))b!==void 0&&(p[`meta/${g}`]=b);return Object.keys(p).length>0?p:void 0})()})}]}}catch(a){return c(d(a),true)}}),n.set("doctor",async t=>{try{let m=r({agentId:(t??{}).agentId,isTrustedLocal:!0}),u=await chunkQAEIHJOF_cjs.z("doctor",t,m);return {content:[{type:"text",text:await R("doctor",u,{toolName:"memory_doctor"})}]}}catch(a){return c(d(a),true)}}),n.set("init",async t=>{try{let a=r({isTrustedLocal:!0}),u=await chunkQAEIHJOF_cjs.z("init",t,a);return {content:[{type:"text",text:`Init complete.
60
60
  dbPath: ${u.dbPath}
61
61
  tablesCreated: ${u.tablesCreated}
62
62
  migrationsApplied: ${u.migrationsApplied}
63
63
  durationMs: ${u.durationMs}
64
- `}]}}catch(a){return c(d(a),true)}}),n}var Ee={recall:chunkYAF6HMAE_cjs.c,remember:chunkYAF6HMAE_cjs.d,update:chunkYAF6HMAE_cjs.e,forget:chunkYAF6HMAE_cjs.f,extract:chunkYAF6HMAE_cjs.g,consolidate:chunkYAF6HMAE_cjs.h,sync:chunkYAF6HMAE_cjs.m,graph_query:chunkYAF6HMAE_cjs.i,status:chunkYAF6HMAE_cjs.j,doctor:chunkYAF6HMAE_cjs.k,init:chunkYAF6HMAE_cjs.l};function xe(e,n){let o=chunkYAF6HMAE_cjs.x[e],s={title:o?.annotations?.defaultDescription??e,readOnlyHint:o?.annotations?.readOnlyHint??false,destructiveHint:o?.annotations?.destructiveHint??false,idempotentHint:o?.annotations?.idempotentHint??true,openWorldHint:false},r=Ee[e];return {name:e,description:o?.annotations?.defaultDescription??`memory op: ${e}`,inputSchema:r??{type:"object",properties:{},required:[],additionalProperties:false},annotations:s,handler:n}}exports.b=void 0;(o=>{async function e(s,r){let{getMemoryDbPath:c,getInstance:d}=await import('./interfaces-TGSOKRFI.cjs'),a=r!==null&&typeof r=="object"&&"agentId"in r&&"dbPath"in r?r:{agentId:process.env.EASBOT_AGENT_ID??"default",dbPath:c(d().worktree),workspaceDir:d().worktree,isRemote:false};mcp.extendKnownErrorCodes(["AGENT_ID_REQUIRED","SESSION_ID_REQUIRED","CATEGORY_REQUIRED","IMPORTANCE_REQUIRED","TIMERANGE_REQUIRED","DRY_RUN_NO_DELETE"]);let m=new mcp.ToolRegistry,u=Te(a),l=Object.keys(chunkYAF6HMAE_cjs.x);for(let y of l){let C=u.get(y);if(!C)throw new chunkAVECFV5K_cjs.a.MissingMcpHandlerError({message:`MemoryStdioServer.start: missing handler for tool "${y}"`,toolName:y});m.register(xe(y,C));}D.info("starting memory MCP stdio server",{id:s.id,name:s.name,toolCount:l.length,isRemote:a.isRemote??true});let i=await mcp.createAndStartStdioServer(s,m),f=null,p=new Promise(y=>{f=y;}),g=y=>{D.info("received signal, stopping MCP server",{signal:y}),f?.();},b=()=>g("SIGINT"),k=()=>g("SIGTERM"),L=(y,C)=>process.listeners(y).includes(C);L("SIGINT",b)||process.on("SIGINT",b),L("SIGTERM",k)||process.on("SIGTERM",k);try{await p;}finally{try{process.off("SIGINT",b),process.off("SIGTERM",k);}catch(y){D.warn("failed to remove signal handlers",{error:utils.errorMeta(y)});}try{await i.stop();}catch(y){D.warn("server.stop failed during cleanup",{error:utils.errorMeta(y)});}}return {id:s.id,name:s.name,version:s.version,tools:l}}o.start=e;function n(){return Object.keys(chunkYAF6HMAE_cjs.x)}o.getToolNames=n;})(exports.b||(exports.b={}));exports.a=R;
64
+ `}]}}catch(a){return c(d(a),true)}}),n}var Ee={recall:chunkQAEIHJOF_cjs.c,remember:chunkQAEIHJOF_cjs.d,update:chunkQAEIHJOF_cjs.e,forget:chunkQAEIHJOF_cjs.f,extract:chunkQAEIHJOF_cjs.g,consolidate:chunkQAEIHJOF_cjs.h,sync:chunkQAEIHJOF_cjs.m,graph_query:chunkQAEIHJOF_cjs.i,status:chunkQAEIHJOF_cjs.j,doctor:chunkQAEIHJOF_cjs.k,init:chunkQAEIHJOF_cjs.l};function xe(e,n){let o=chunkQAEIHJOF_cjs.x[e],s={title:o?.annotations?.defaultDescription??e,readOnlyHint:o?.annotations?.readOnlyHint??false,destructiveHint:o?.annotations?.destructiveHint??false,idempotentHint:o?.annotations?.idempotentHint??true,openWorldHint:false},r=Ee[e];return {name:e,description:o?.annotations?.defaultDescription??`memory op: ${e}`,inputSchema:r??{type:"object",properties:{},required:[],additionalProperties:false},annotations:s,handler:n}}exports.b=void 0;(o=>{async function e(s,r){let{getMemoryDbPath:c,getInstance:d}=await import('./interfaces-LDOE5ZTS.cjs'),a=r!==null&&typeof r=="object"&&"agentId"in r&&"dbPath"in r?r:{agentId:process.env.EASBOT_AGENT_ID??"default",dbPath:c(d().worktree),workspaceDir:d().worktree,isRemote:false};mcp.extendKnownErrorCodes(["AGENT_ID_REQUIRED","SESSION_ID_REQUIRED","CATEGORY_REQUIRED","IMPORTANCE_REQUIRED","TIMERANGE_REQUIRED","DRY_RUN_NO_DELETE"]);let m=new mcp.ToolRegistry,u=Te(a),l=Object.keys(chunkQAEIHJOF_cjs.x);for(let y of l){let C=u.get(y);if(!C)throw new chunkAVECFV5K_cjs.a.MissingMcpHandlerError({message:`MemoryStdioServer.start: missing handler for tool "${y}"`,toolName:y});m.register(xe(y,C));}D.info("starting memory MCP stdio server",{id:s.id,name:s.name,toolCount:l.length,isRemote:a.isRemote??true});let i=await mcp.createAndStartStdioServer(s,m),f=null,p=new Promise(y=>{f=y;}),g=y=>{D.info("received signal, stopping MCP server",{signal:y}),f?.();},b=()=>g("SIGINT"),k=()=>g("SIGTERM"),L=(y,C)=>process.listeners(y).includes(C);L("SIGINT",b)||process.on("SIGINT",b),L("SIGTERM",k)||process.on("SIGTERM",k);try{await p;}finally{try{process.off("SIGINT",b),process.off("SIGTERM",k);}catch(y){D.warn("failed to remove signal handlers",{error:utils.errorMeta(y)});}try{await i.stop();}catch(y){D.warn("server.stop failed during cleanup",{error:utils.errorMeta(y)});}}return {id:s.id,name:s.name,version:s.version,tools:l}}o.start=e;function n(){return Object.keys(chunkQAEIHJOF_cjs.x)}o.getToolNames=n;})(exports.b||(exports.b={}));exports.a=R;