@easbot/memory 0.3.14 → 0.3.17

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 (57) hide show
  1. package/README.en.md +296 -38
  2. package/README.md +292 -37
  3. package/dist/chunks/chunk-BSKFK4RC.mjs +1 -0
  4. package/dist/chunks/chunk-CPRDIUQ4.cjs +1 -0
  5. package/dist/chunks/chunk-DFWC6WII.mjs +53 -0
  6. package/dist/chunks/chunk-DXU5WPK3.cjs +42 -0
  7. package/dist/chunks/chunk-EECBJNZI.mjs +59 -0
  8. package/dist/chunks/chunk-FMEXQ5YE.cjs +59 -0
  9. package/dist/chunks/chunk-HQBRVVXS.mjs +1 -0
  10. package/dist/chunks/chunk-HSK27DQ7.cjs +1 -0
  11. package/dist/chunks/chunk-I6XVFDN2.mjs +42 -0
  12. package/dist/chunks/chunk-MWRDF6VN.mjs +1 -0
  13. package/dist/chunks/chunk-NVGACA7W.cjs +1 -0
  14. package/dist/chunks/chunk-OIUUTVLL.cjs +53 -0
  15. package/dist/chunks/chunk-QF5S5MG7.mjs +0 -0
  16. package/dist/chunks/chunk-QNDG7BTB.cjs +1 -0
  17. package/dist/chunks/chunk-RSJ2KT6X.cjs +1 -0
  18. package/dist/chunks/chunk-TPSRK4M3.mjs +1 -0
  19. package/dist/chunks/chunk-URADAZYW.cjs +1 -0
  20. package/dist/chunks/chunk-WDVDYZ25.mjs +1 -0
  21. package/dist/chunks/cli-handler-6VTKYXXM.mjs +1 -0
  22. package/dist/chunks/cli-handler-HNPA3STD.cjs +1 -0
  23. package/dist/chunks/config-2SQJYVTO.mjs +1 -0
  24. package/dist/chunks/config-RPPQ73HK.cjs +1 -0
  25. package/dist/chunks/consolidate-6P7LUPPL.cjs +2 -0
  26. package/dist/chunks/consolidate-NYH4IKJK.mjs +2 -0
  27. package/dist/chunks/doctor-IJJ5UYGT.cjs +2 -0
  28. package/dist/chunks/doctor-MZSZGVRL.mjs +2 -0
  29. package/dist/chunks/extract-6B7OD3VK.mjs +2 -0
  30. package/dist/chunks/extract-ERTOHQV6.cjs +2 -0
  31. package/dist/chunks/forget-A4UJI3LE.mjs +3 -0
  32. package/dist/chunks/forget-KLFM5SBQ.cjs +3 -0
  33. package/dist/chunks/graph-P5ZHB4ZM.cjs +3 -0
  34. package/dist/chunks/graph-XZ46LEO7.mjs +3 -0
  35. package/dist/chunks/init-CCOSHE3F.cjs +3 -0
  36. package/dist/chunks/init-WEPU32KF.mjs +3 -0
  37. package/dist/chunks/interfaces-LPJU4KS3.mjs +1 -0
  38. package/dist/chunks/interfaces-XWE45ENK.cjs +1 -0
  39. package/dist/chunks/mcp-BOD4ZOZS.mjs +1 -0
  40. package/dist/chunks/mcp-BXVXTUJK.cjs +1 -0
  41. package/dist/chunks/recall-BV4Z7HUJ.mjs +2 -0
  42. package/dist/chunks/recall-FEINUJKO.cjs +2 -0
  43. package/dist/chunks/remember-ESVRA73C.mjs +2 -0
  44. package/dist/chunks/remember-YNSY2JJB.cjs +2 -0
  45. package/dist/chunks/status-KVM7I6YC.cjs +2 -0
  46. package/dist/chunks/status-QQZS3ZCN.mjs +2 -0
  47. package/dist/chunks/stdio-server-MQKTUGNG.cjs +1 -0
  48. package/dist/chunks/stdio-server-ZLMSUTC5.mjs +1 -0
  49. package/dist/cli.cjs +2 -0
  50. package/dist/cli.d.cts +1 -0
  51. package/dist/cli.d.ts +1 -0
  52. package/dist/cli.mjs +2 -0
  53. package/dist/index.cjs +6 -146
  54. package/dist/index.d.cts +403 -170
  55. package/dist/index.d.ts +403 -170
  56. package/dist/index.mjs +6 -146
  57. package/package.json +21 -14
package/README.en.md CHANGED
@@ -2,15 +2,17 @@
2
2
 
3
3
  [中文](./README.md) | English
4
4
 
5
- Memory management library for the EASBOT ecosystem, providing intelligent memory indexing, search, and management capabilities.
5
+ Long-term memory library for the EASBOT ecosystem, providing per-agent fact storage, hybrid search, KG scope filtering, and a 9-op unified execution interface.
6
6
 
7
- ## Features
7
+ ## Features (v0.4.0)
8
8
 
9
- - **Hybrid Search**: Combines vector search, full-text search (FTS), and graph search
10
- - **Chinese/English Tokenization**: High-quality tokenization via jieba-wasm
11
- - **Incremental Indexing**: Supports incremental updates with automatic file change detection
12
- - **Multi-source Support**: Supports both memory and sessions memory sources
13
- - **XDG Compliance**: Database stored in XDG data directory by default
9
+ - **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)`.
10
+ - **Per-agent isolation + KG scope filtering** — each KG node carries `owner_agent_id`; scope ∈ `{agent_only, shared_only, both}`; MCP defaults to `agent_only`, trusted local may use `both`. `agentId` is **optional** for `graph_query` / `status` / `doctor` / `init` (defaults to `'default'`, see ADR 0068 P0-A reversal).
11
+ - **Layered memory** — short-term / writable self-memory / long-term history; hybrid search (FTS + vector + graph).
12
+ - **Observability** — 9 op fully routed through `Log.create({ service })` English structured logs; `status` / `doctor` provide offline diagnostics.
13
+ - **i18n** — `zh-CN` / `en-US` locales; `@easbot/memory` API logs stay English, copy goes through `t()`.
14
+ - **Portable** — pure TS 6.x; depends on `better-sqlite3` (transitive via `@easbot/database`) + `@easbot/database` (sync facade) + `@easbot/types` / `@easbot/utils` (decision 0036 unified facade; do not directly require `better-sqlite3` / `@modelcontextprotocol/sdk`).
15
+ - **Three-package unified backend support** (decision 0036 / 0049 / 0051 / 0052): database goes through `@easbot/database` `createSyncSqliteConnection`; MCP goes through `@easbot/mcp` `ToolRegistry` + `createAndStartStdioServer`; CLI output goes through `@easbot/terminal` `printHuman` + `emitJsonOk` + `COMMANDS_HELP` single source of truth.
14
16
 
15
17
  ## Installation
16
18
 
@@ -20,53 +22,276 @@ pnpm add @easbot/memory
20
22
 
21
23
  ## Usage
22
24
 
25
+ ### 9 op entry
26
+
27
+ ```typescript
28
+ import { executeOp } from '@easbot/memory';
29
+
30
+ // v0.4.0 simplification: no more `createMemorySystem` + `setOpSystem` main class;
31
+ // all ops go through `executeOp(name, args, ctx)` (agentId injected via ctx).
32
+
33
+ // 1. recall
34
+ const recall = await executeOp<{ hits: unknown[] }>(
35
+ 'recall',
36
+ {
37
+ // No more agentId at args top-level — goes through ctx.agentId
38
+ query: 'user preference',
39
+ limit: 10,
40
+ scope: 'agent_only',
41
+ // dbPath / workspaceDir go through ctx or service config; can be omitted
42
+ dbPath: '/path/to/memory.db',
43
+ workspaceDir: '/path/to/workspace',
44
+ rootDir: '/path/to/workspace',
45
+ locale: 'en-US',
46
+ remote: false,
47
+ },
48
+ {
49
+ agentId: 'agent-1',
50
+ isTrustedLocal: true,
51
+ },
52
+ );
53
+
54
+ // 2. remember
55
+ const saved = await executeOp<{ id: string }>(
56
+ 'remember',
57
+ {
58
+ content: '老侯 prefers TypeScript',
59
+ category: 'user_preference',
60
+ importance: 9,
61
+ dbPath: '/path/to/memory.db',
62
+ workspaceDir: '/path/to/workspace',
63
+ rootDir: '/path/to/workspace',
64
+ locale: 'en-US',
65
+ remote: false,
66
+ },
67
+ { agentId: 'agent-1', isTrustedLocal: true },
68
+ );
69
+
70
+ // 3. forget (delete by category)
71
+ await executeOp(
72
+ 'forget',
73
+ {
74
+ category: 'user_preference',
75
+ maxDelete: 1000,
76
+ dryRun: false,
77
+ dbPath: '/path/to/memory.db',
78
+ workspaceDir: '/path/to/workspace',
79
+ rootDir: '/path/to/workspace',
80
+ locale: 'en-US',
81
+ remote: false,
82
+ },
83
+ { agentId: 'agent-1', isTrustedLocal: true },
84
+ );
85
+ ```
86
+
87
+ ### KG scope three tiers
88
+
89
+ ```typescript
90
+ // Only this Agent's nodes (default; MCP entry enforces)
91
+ await executeOp('graph_query', { agentId: 'agent-1', kind: 'nodes', scope: 'agent_only' }, { agentId: 'agent-1', isTrustedLocal: true });
92
+
93
+ // Only shared nodes
94
+ await executeOp('graph_query', { agentId: 'agent-1', kind: 'nodes', scope: 'shared_only' }, { agentId: 'agent-1', isTrustedLocal: true });
95
+
96
+ // This Agent + shared (trusted local only; MCP entry rejects)
97
+ await executeOp('graph_query', { agentId: 'agent-1', kind: 'nodes', scope: 'both' }, { agentId: 'agent-1', isTrustedLocal: true });
98
+
99
+ // v0.4.1+: omitting agentId → fallback 'default', global KG view (trusted local only)
100
+ await executeOp('graph_query', { kind: 'nodes', scope: 'both' }, { isTrustedLocal: true });
101
+ ```
102
+
103
+ ### Markdown render
104
+
105
+ ```typescript
106
+ import { renderOperationMarkdown } from '@easbot/memory';
107
+ const md = await renderOperationMarkdown('recall', recallResult, { toolName: 'memory_recall' });
108
+ ```
109
+
110
+ ## 9 op manifest
111
+
112
+ | op | trusted local only | agentId | purpose |
113
+ |---|---|---|---|
114
+ | `recall` | ❌ | ✅ required | Hybrid search (FTS + vector + graph) |
115
+ | `remember` | ❌ | ✅ required | Persist a self-memory fact |
116
+ | `forget` | ❌ | ✅ required | Delete by factId / category / time window (supports `dryRun`) |
117
+ | `extract` | ❌ | ✅ required | Aggregate facts / KG nodes for a sessionId |
118
+ | `consolidate` | ✅ | ✅ required | dedup → archive pipeline |
119
+ | `graph_query` | ❌ (scope=both → ✅) | ⚠️ optional, defaults to `'default'` | KG nodes / edges / BFS neighbors |
120
+ | `status` | ❌ | ⚠️ optional, defaults to global aggregate | System status snapshot |
121
+ | `doctor` | ✅ | ⚠️ optional, defaults to whole-DB scan | Data integrity checks (supports `repair`) |
122
+ | `init` | ✅ | ⚠️ optional, defaults to `'default'` | Initialize workspace (supports `force`) |
123
+
124
+ **P0-A reversal note** (since v0.4.1):
125
+
126
+ Four ops — `graph_query` / `status` / `doctor` / `init` — have made `agentId` **optional**; missing values fall back to the fixed sentinel `'default'` instead of throwing. This reverses the earlier "agent scope required" semantics captured in ADR 0055 / 0056 / 0057, and is meant to let CLI / status / one-shot diagnostic calls run without an explicit agent context.
127
+
128
+ - `graph_query` without agentId → global KG view (`scope` still chosen by caller; trusted local defaults to `'both'`)
129
+ - `status` without agentId → cross-agent aggregate stats (no longer single-agent view)
130
+ - `doctor` / `init` without agentId → default agent = `'default'`, aligned with status / graph_query semantics
131
+
132
+ **Local-only operations** (`consolidate`, `doctor`, `init`) reject non-trusted callers; remote / multi-tenant contexts must not invoke them.
133
+
134
+ ## API categories
135
+
136
+ ### services (9 op business layer)
137
+
23
138
  ```typescript
24
- import { MemoryIndexManager } from '@easbot/memory';
139
+ import { recall, remember, forget, extract, consolidate, graphQuery, status, doctor, init } from '@easbot/memory/services';
140
+ ```
141
+
142
+ ### operations (9 op registry + executeOp)
143
+
144
+ ```typescript
145
+ import { executeOp, OP_REGISTRY, ALL_OPS } from '@easbot/memory/operations';
146
+ ```
147
+
148
+ ### format (schema + markdown + text + truncate + render)
149
+
150
+ ```typescript
151
+ import { renderOperationMarkdown } from '@easbot/memory/format/render';
152
+ ```
153
+
154
+ ### hooks (4 hook types)
155
+
156
+ ```typescript
157
+ import type { PreCompactHook, SessionStartHook, SessionEndHook, PostToolFailureHook } from '@easbot/memory/hooks';
158
+ ```
159
+
160
+ ## CLI / MCP dual entry (v0.4 stage 4)
161
+
162
+ ### Standalone CLI (`easbot-memory`)
163
+
164
+ ```bash
165
+ # Installed via package.json bin: easbot-memory
166
+ easbot-memory init --workspace-dir <dir> [--agent <id>]
167
+ easbot-memory status [--agent <id>] [--json]
168
+ easbot-memory doctor [--repair] [--agent <id>]
169
+ easbot-memory recall --query <q> --agent <id> [--limit <n>] [--json]
170
+ easbot-memory remember --content <text> --category <c> --importance <1-10> --agent <id>
171
+ easbot-memory forget --agent <id> [--fact-id <id>] [--dry-run]
172
+ easbot-memory extract --session <sessionId> [--last-n <n>] --agent <id>
173
+ easbot-memory consolidate --agent <id> [--window-days <n>]
174
+ easbot-memory graph --kind <nodes|edges|neighbors> [--query <q>] [--agent <id>]
175
+ easbot-memory config [--json]
176
+ easbot-memory mcp
177
+ ```
178
+
179
+ > Since v0.4.1: `--agent` is **optional** for `init` / `status` / `doctor` / `graph` (defaults to `'default'`), letting CLI / one-shot diagnostic calls run without an agent context. The remaining 5 ops (`recall` / `remember` / `forget` / `extract` / `consolidate`) still require an explicit `--agent`; missing values return a non-zero exit code.
180
+
181
+ ### Agent delegation (v0.4 stage 4)
182
+
183
+ ```bash
184
+ # @easbot/agent memory subcommand delegates to @easbot/memory's cli-handler
185
+ easbot memory recall --query "user preference"
186
+ easbot memory remember --content "..." --category user_preference --importance 8
187
+ easbot memory mcp # starts MCP stdio server
188
+ ```
25
189
 
26
- // Get memory manager instance
27
- const manager = await MemoryIndexManager.get({
28
- workspaceDir: '/path/to/workspace',
190
+ ### MCP stdio server (v0.4 stage 4)
191
+
192
+ ```typescript
193
+ import { MemoryStdioServer } from '@easbot/memory';
194
+
195
+ // Start 9 tool MCP stdio server (callable by Cline / Claude Code / Continue)
196
+ // v0.4.0: start signature simplified — no `system` param needed (handlers dispatch via executeOp)
197
+ await MemoryStdioServer.start({
198
+ name: 'easbot-memory',
199
+ version: '0.4.0',
200
+ description: 'EASBot memory MCP server',
29
201
  });
30
202
 
31
- // Search memories
32
- const results = await manager.search('machine learning', {
33
- maxResults: 10,
34
- minScore: 0.5,
203
+ // List 9 tool names
204
+ const tools = MemoryStdioServer.getToolNames();
205
+ // ['memory_recall', 'memory_remember', 'memory_forget', ...]
206
+ ```
207
+
208
+ **9 tool manifest** (1:1 with `OP_REGISTRY`):
209
+ - `memory_recall` / `memory_remember` / `memory_forget` / `memory_extract` / `memory_consolidate` / `memory_graph_query` / `memory_status` / `memory_doctor` / `memory_init`
210
+
211
+ ### handleMemoryCli delegation
212
+
213
+ ```typescript
214
+ import { handleMemoryCli, setGlobalAdapter, setInstanceAdapter } from '@easbot/memory';
215
+
216
+ // 1. Inject adapters (cli path / agent path)
217
+ setGlobalAdapter({ Path: { /* ... */ } });
218
+ setInstanceAdapter({ directory: process.cwd(), worktree: process.cwd() });
219
+
220
+ // 2. Delegate to unified handler
221
+ const result = await handleMemoryCli(['recall', '--query', 'test'], {
222
+ version: '0.4.0',
223
+ cwd: process.cwd(),
35
224
  });
36
225
 
37
- // Index a file
38
- await manager.indexFile('/path/to/file.md');
226
+ if (result.code !== 0) process.exit(result.code);
39
227
  ```
40
228
 
41
- ## API
229
+ ## fact → .md document sync (v0.5+ ADR 0060)
42
230
 
43
- ### MemoryIndexManager
231
+ After `remember` commits the db transaction, it **best-effort** renders the fact into a Markdown file. Benefits:
44
232
 
45
- | Method | Description |
46
- |--------|-------------|
47
- | `get(params)` | Get or create manager instance |
48
- | `search(query, options)` | Hybrid search |
49
- | `indexFile(filePath)` | Index a single file |
50
- | `indexDirectory(dirPath)` | Index a directory |
51
- | `getStatus()` | Get status information |
233
+ - Debug: developers can read the human-readable copy on disk
234
+ - Future integration: `note` tool may watch memory .md changes for cross-reference updates
235
+ - Resilience: file IO failure **never blocks** db writes (consistent with v0.3)
52
236
 
53
- ## Development
237
+ ### Path schema
54
238
 
55
- ```bash
56
- # Install dependencies
57
- pnpm install
239
+ ```
240
+ {workspaceDir}/.easbot/knowledge/memory/{category}/{YYYY-MM}/mem_{id}.md
241
+ ```
58
242
 
59
- # Build
60
- pnpm build
243
+ - One directory per **category** (`task_context` / `workflow` / `user_preference` / ...)
244
+ - One directory per **createdAt month** (avoid packing too many files per month)
245
+ - File name = `fact.id` (globally unique)
246
+ - `memory_facts.file_path` stores a **workspaceDir-relative POSIX path**
61
247
 
62
- # Test
63
- pnpm test
248
+ ### Markdown template
64
249
 
65
- # Type check
66
- pnpm type-check
250
+ ```markdown
251
+ ---
252
+ id: mem_xxx
253
+ agent_id: easbot-xxx
254
+ category: task_context
255
+ importance: 7
256
+ created_at: 2026-08-22T22:00:00Z
257
+ updated_at: 2026-08-22T22:00:00Z
258
+ tags: [tag1, tag2]
259
+ ---
260
+
261
+ # fact content (one line)
262
+
263
+ **category**: task_context | **importance**: 7/10 | **source**: session_self_write
67
264
  ```
68
265
 
69
- ## Database Location
266
+ ### Programmatic usage (advanced)
267
+
268
+ Most callers should use `executeOp('remember' / 'forget')` directly. For advanced scenarios (batch migration / custom path strategy):
269
+
270
+ ```typescript
271
+ import { factFileSync } from '@easbot/memory/services';
272
+
273
+ // 1. Compute path without writing
274
+ const absPath = factFileSync.resolvePath(fact, '/path/to/workspace');
275
+
276
+ // 2. Render Markdown string without writing
277
+ const md = factFileSync.renderMarkdown(fact);
278
+
279
+ // 3. Write (best-effort; failure returns ok=false + log.warn, never throws)
280
+ const { ok, relPath, absPath } = await factFileSync.write(fact, '/path/to/workspace');
281
+
282
+ // 4. Delete (by fact.filePath; missing file → ok=true, idempotent)
283
+ const { ok, absPath } = await factFileSync.delete(fact, '/path/to/workspace');
284
+ ```
285
+
286
+ ### Policies and limits
287
+
288
+ - **best-effort**: write/delete failures → `log.warn` + return `ok=false`; **never throws**, **never blocks** main flow
289
+ - **Single-process assumption**: no cross-process file lock (consistent with v0.3)
290
+ - **No stale orphan cleanup**: if db delete succeeds but file delete fails → stale .md remains (doctor check #9 "orphan file detection" is a future enhancement)
291
+
292
+ See `docs/decisions/0060-memory-fact-file-sync-restore.md`.
293
+
294
+ ## Database location
70
295
 
71
296
  Default storage: `$XDG_DATA_HOME/easbot/memory.db`
72
297
 
@@ -74,6 +299,39 @@ Default storage: `$XDG_DATA_HOME/easbot/memory.db`
74
299
  - macOS: `~/Library/Application Support/easbot/memory.db`
75
300
  - Windows: `%APPDATA%/easbot/memory.db`
76
301
 
302
+ ## Decisions and migration
303
+
304
+ - ADR 0068 (v0.4.1 P0-A reversal: agentId becomes optional for `graph_query` / `status` / `doctor` / `init`, defaulting to `'default'`): `docs/decisions/0068-p0a-agent-id-optional.md`
305
+ - ADR 0060 (v0.5+ fact → .md sync restoration): `docs/decisions/0060-memory-fact-file-sync-restore.md`
306
+ - ADR 0055 / 0056 / 0057 (v0.4 decisions): `docs/decisions/00NN-*.md`
307
+ - v0.4 cleanup log: `.easbot/knowledge/tasks/memory-v04-refactor/`
308
+ - Migration script: `pnpm migrate:v04` (BC-01 ~ BC-12 dry-run + apply)
309
+ - CI guards (v0.4 stage 5 three-package unified backend support):
310
+ - `scripts/check-database-facade.sh` (forbid directly requiring `better-sqlite3` / `node:sqlite` / `createRequire`)
311
+ - `scripts/check-mcp-facade.sh` (forbid directly importing `@modelcontextprotocol/sdk`)
312
+ - `scripts/check-terminal-facade.sh` (CLI output goes through `@easbot/terminal` + `COMMANDS_HELP` single source of truth)
313
+ - `scripts/check-cmd-i18n-coverage.sh` (zh-CN / / en-US dual-locale consistency + switch-case routing validation)
314
+ - L-M13 / L-M14 / L-M15 lessons: `.easbot/knowledge/tasks/memory-v04-refactor/findings.md`
315
+
316
+ ## Development
317
+
318
+ ```bash
319
+ # Install
320
+ pnpm install
321
+
322
+ # Build
323
+ pnpm build
324
+
325
+ # Test (vitest 4)
326
+ pnpm test:run
327
+
328
+ # Type check
329
+ pnpm type-check
330
+
331
+ # Lint (biome 2.x)
332
+ pnpm biome-lint
333
+ ```
334
+
77
335
  ## License
78
336
 
79
- MIT
337
+ MIT