@easbot/memory 0.3.29 → 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 (101) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +70 -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-IS6GEN55.cjs +1 -0
  6. package/dist/chunks/cache-U5YYUDWO.mjs +1 -0
  7. package/dist/chunks/chunk-4G4FSAFY.cjs +1 -0
  8. package/dist/chunks/chunk-AEAMQDNV.mjs +67 -0
  9. package/dist/chunks/chunk-EKSLNNMF.cjs +1 -0
  10. package/dist/chunks/{chunk-NWY7CUSL.mjs → chunk-FZ3RTYIJ.mjs} +3 -3
  11. package/dist/chunks/chunk-GCVKM3RJ.cjs +1 -0
  12. package/dist/chunks/chunk-HH7EA2UE.mjs +1 -0
  13. package/dist/chunks/chunk-HX3TV7FD.mjs +1 -0
  14. package/dist/chunks/chunk-IP7VEKQY.cjs +77 -0
  15. package/dist/chunks/{chunk-DVZOWMF5.cjs → chunk-ISYAE6B7.cjs} +5 -5
  16. package/dist/chunks/chunk-NHRRIJFK.cjs +1 -0
  17. package/dist/chunks/chunk-QAEIHJOF.cjs +67 -0
  18. package/dist/chunks/chunk-R32346OA.cjs +1 -0
  19. package/dist/chunks/chunk-S4DPVKMV.mjs +1 -0
  20. package/dist/chunks/chunk-SE3F5YQE.mjs +1 -0
  21. package/dist/chunks/chunk-YJLHS7JB.mjs +77 -0
  22. package/dist/chunks/chunk-YUWHNHAY.mjs +1 -0
  23. package/dist/chunks/cli-handler-JHSDGJHK.mjs +1 -0
  24. package/dist/chunks/cli-handler-USK4CPAU.cjs +1 -0
  25. package/dist/chunks/{config-I2I6U4XM.cjs → config-5OTOQBQN.cjs} +1 -1
  26. package/dist/chunks/{config-2SQJYVTO.mjs → config-5P7O45FH.mjs} +1 -1
  27. package/dist/chunks/consolidate-IKQVVWIQ.cjs +2 -0
  28. package/dist/chunks/consolidate-OOAMW7XW.mjs +2 -0
  29. package/dist/chunks/doctor-N6HHFR6Y.cjs +1 -0
  30. package/dist/chunks/doctor-ZGHICE2Q.mjs +1 -0
  31. package/dist/chunks/extract-7DQ6OV34.cjs +2 -0
  32. package/dist/chunks/extract-AJY2ETKE.mjs +2 -0
  33. package/dist/chunks/forget-4KGLTQ5Q.cjs +3 -0
  34. package/dist/chunks/{forget-PQLRSYOJ.mjs → forget-NIBBY6FG.mjs} +1 -1
  35. package/dist/chunks/{graph-P6LEEEVA.mjs → graph-4K56ZAVL.mjs} +1 -1
  36. package/dist/chunks/graph-OG23VZZM.cjs +3 -0
  37. package/dist/chunks/init-HWR4SD6N.mjs +1 -0
  38. package/dist/chunks/init-UQTPANNI.cjs +1 -0
  39. package/dist/chunks/interfaces-LDOE5ZTS.cjs +1 -0
  40. package/dist/chunks/{interfaces-7TJ645HL.mjs → interfaces-OFM2XGSG.mjs} +1 -1
  41. package/dist/chunks/llm-BRSMYENV.mjs +1 -0
  42. package/dist/chunks/llm-JSVYSX5Y.cjs +1 -0
  43. package/dist/chunks/mcp-ONIMP7FB.cjs +1 -0
  44. package/dist/chunks/mcp-ZWZYH52C.mjs +1 -0
  45. package/dist/chunks/recall-BRXHJPR4.mjs +2 -0
  46. package/dist/chunks/recall-KZRYTTWA.cjs +2 -0
  47. package/dist/chunks/remember-3XSYCWKK.mjs +2 -0
  48. package/dist/chunks/remember-GLOJH457.cjs +2 -0
  49. package/dist/chunks/status-POX2GWSQ.cjs +1 -0
  50. package/dist/chunks/status-SW5BUHJ3.mjs +1 -0
  51. package/dist/chunks/stdio-server-3A3H4YJ7.mjs +1 -0
  52. package/dist/chunks/stdio-server-W52CMVJO.cjs +1 -0
  53. package/dist/chunks/sync-EE4ZD3WB.mjs +2 -0
  54. package/dist/chunks/sync-I423W5G7.cjs +2 -0
  55. package/dist/cli.cjs +1 -1
  56. package/dist/cli.mjs +1 -1
  57. package/dist/index.cjs +7 -5
  58. package/dist/index.d.cts +59 -75
  59. package/dist/index.d.ts +59 -75
  60. package/dist/index.mjs +7 -5
  61. package/package.json +12 -12
  62. package/dist/chunks/chunk-3EENVVWK.cjs +0 -67
  63. package/dist/chunks/chunk-BYNUWUL2.cjs +0 -77
  64. package/dist/chunks/chunk-CIXJXCID.mjs +0 -1
  65. package/dist/chunks/chunk-CVS25NBK.mjs +0 -77
  66. package/dist/chunks/chunk-DWGCQLSH.mjs +0 -1
  67. package/dist/chunks/chunk-GHJLFUKH.cjs +0 -1
  68. package/dist/chunks/chunk-HQBRVVXS.mjs +0 -1
  69. package/dist/chunks/chunk-I5SOBIRK.cjs +0 -1
  70. package/dist/chunks/chunk-M2YU5LAI.cjs +0 -1
  71. package/dist/chunks/chunk-OOBYBPIN.mjs +0 -67
  72. package/dist/chunks/chunk-QJTEXVXX.mjs +0 -1
  73. package/dist/chunks/chunk-ZDTPURG4.cjs +0 -1
  74. package/dist/chunks/cli-handler-7KD65K5T.mjs +0 -1
  75. package/dist/chunks/cli-handler-L2HSWA2P.cjs +0 -1
  76. package/dist/chunks/consolidate-ANQFG7QD.mjs +0 -2
  77. package/dist/chunks/consolidate-GJPX4H7R.cjs +0 -2
  78. package/dist/chunks/doctor-4L2KSJXV.cjs +0 -1
  79. package/dist/chunks/doctor-CDS2OUAA.mjs +0 -1
  80. package/dist/chunks/extract-3MLEFVJV.cjs +0 -2
  81. package/dist/chunks/extract-V4BIBFW7.mjs +0 -2
  82. package/dist/chunks/forget-FG7ZFJL7.cjs +0 -3
  83. package/dist/chunks/graph-34HVP7TP.cjs +0 -3
  84. package/dist/chunks/init-7SHKOGVZ.cjs +0 -1
  85. package/dist/chunks/init-TTINBBT4.mjs +0 -1
  86. package/dist/chunks/interfaces-BGC3V4WU.cjs +0 -1
  87. package/dist/chunks/llm-RSSNHF6T.cjs +0 -1
  88. package/dist/chunks/llm-XHWMIOUN.mjs +0 -1
  89. package/dist/chunks/mcp-7TMDANN6.cjs +0 -1
  90. package/dist/chunks/mcp-YNGRYILA.mjs +0 -1
  91. package/dist/chunks/recall-JIH4PAR5.mjs +0 -2
  92. package/dist/chunks/recall-TA4YPWD2.cjs +0 -2
  93. package/dist/chunks/remember-5JAWVMYX.cjs +0 -2
  94. package/dist/chunks/remember-KY4HDAE4.mjs +0 -2
  95. package/dist/chunks/status-QZ27UQJG.mjs +0 -1
  96. package/dist/chunks/status-YGRSKKZZ.cjs +0 -1
  97. package/dist/chunks/stdio-server-KEBLOUB2.cjs +0 -1
  98. package/dist/chunks/stdio-server-RTY5WYTU.mjs +0 -1
  99. package/dist/chunks/sync-D44EAJLK.mjs +0 -2
  100. package/dist/chunks/sync-SJI7PENR.cjs +0 -2
  101. /package/dist/assets/txt/{assets → src/assets}/jieba_dict.txt +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.29
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.29
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 三端共享。
@@ -160,6 +160,26 @@ const md = await renderOperationMarkdown('recall', recallResult, { toolName: 'me
160
160
  - `status` 不传 agentId → 跨 agent 聚合统计(不再是单一 agent 视图)
161
161
  - `doctor` / `init` 不传 agentId → 全局默认 agent = `'default'`,与 status / graph_query 口径一致
162
162
 
163
+ ### `recall` 的 `snippet` 裁剪(2026-10-13)
164
+
165
+ `snippet` 是给预览用的**裁剪副本**,完整正文见 `hit.content`(决策 0086 v2)。历史上 `SUBSTR(mf.content, 1, 200)` 把长度写死在 SQL 字面量里;现统一到 `@easbot/database` 的真值源,并**收回为内部参数**:
166
+
167
+ | 层 | 归属 | 默认值 | 语义 |
168
+ | --------------- | -------------------------------------- | ------------------------------- | -------------------------------------------------------- |
169
+ | service 层 | 内部(`RecallParams.snippetMaxChars`) | `2000`(=`SQL_TEXT_LIMIT_MAX`) | **防御上限** —— 防单条 fact 撑爆结果集 |
170
+ | op schema | **不暴露** | — | LLM 不该决定服务端裁剪多长,`.strict()` 会直接拒掉该字段 |
171
+ | format / 渲染层 | 各 renderer 自行 `slice` | 场景决定 | **展示决策** —— 终端 / CLI 预览通常远小于上限 |
172
+
173
+ ```typescript
174
+ // 服务内部 / 程序化调用可以传(仍会被 clamp)
175
+ await recall(ctx, { query: '...', maxResults: 10, snippetMaxChars: 800 });
176
+
177
+ // LLM / MCP / agent tool 传入则直接报错(schema 外字段)
178
+ await executeOp('recall', { query: '...', snippetMaxChars: 800 }, ctx); // ❌ throws
179
+ ```
180
+
181
+ **约束**:无论传什么都会过 `resolveSqlTextLimit` 收敛到 `[1, SQL_TEXT_LIMIT_MAX]` —— **无法绕过防御**。默认值从硬编码 200 提升到 2000:200 字符在中文语境仅 ≈ 133 token,信息量不足以支撑摘要(摘要链路见 `@easbot/llm` 的 `SummaryProvider`)。
182
+
163
183
  ## API 分类
164
184
 
165
185
  ### services(9 op 业务层)
@@ -180,17 +200,59 @@ import { executeOp, OP_REGISTRY, ALL_OPS } from '@easbot/memory/operations';
180
200
  import { renderOperationMarkdown } from '@easbot/memory/format/render';
181
201
  ```
182
202
 
183
- ### hooks(4 hook 类型)
203
+ ### 插件(plugin / hook / tool)
204
+
205
+ `@easbot/memory` 按 `@easbot/plugin` 契约提供可安装插件:3 个生命周期 hook 与 1 个 `memory` 工具。
206
+ 实现位于 `src/plugin/`,所有符号**统一从包根入口导入**(不提供 subpath 导出)。
184
207
 
185
208
  ```typescript
186
- import type {
187
- PreCompactHook,
188
- SessionStartHook,
189
- SessionEndHook,
190
- PostToolFailureHook,
191
- } 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
192
246
  ```
193
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
+
194
256
  ## CLI / MCP 双入口(v0.4 stage 4 落地)
195
257
 
196
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.
@@ -0,0 +1 @@
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}});
@@ -0,0 +1 @@
1
+ export{c as MEMORY_JSON_REL_PATH,d as MemoryCache}from'./chunk-SE3F5YQE.mjs';import'./chunk-HX3TV7FD.mjs';import'./chunk-S4DPVKMV.mjs';
@@ -0,0 +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-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;