@easbot/memory 0.3.16 → 0.3.19

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 (98) hide show
  1. package/README.en.md +200 -19
  2. package/README.md +210 -25
  3. package/dist/chunks/chunk-4GSXSIV5.cjs +1 -0
  4. package/dist/chunks/chunk-5Q6SIVSP.cjs +50 -0
  5. package/dist/chunks/chunk-6CQMBEIQ.mjs +1 -0
  6. package/dist/chunks/chunk-746FKSL5.mjs +50 -0
  7. package/dist/chunks/chunk-ARA4LMAI.mjs +1 -0
  8. package/dist/chunks/chunk-CN6WBJLX.mjs +60 -0
  9. package/dist/chunks/chunk-CPRDIUQ4.cjs +1 -0
  10. package/dist/chunks/chunk-EGWJG65Q.cjs +71 -0
  11. package/dist/chunks/chunk-HQBRVVXS.mjs +1 -0
  12. package/dist/chunks/chunk-J5XF2W4Z.cjs +1 -0
  13. package/dist/chunks/chunk-JDPZ5U53.mjs +71 -0
  14. package/dist/chunks/chunk-NVGACA7W.cjs +1 -0
  15. package/dist/chunks/chunk-QHPGDNEG.cjs +1 -0
  16. package/dist/chunks/{chunk-FNT7WEHL.mjs → chunk-QYBWHFOX.mjs} +1 -1
  17. package/dist/chunks/chunk-SWYQLQ7Z.mjs +1 -0
  18. package/dist/chunks/{chunk-YHOJKRHE.mjs → chunk-WDVDYZ25.mjs} +1 -1
  19. package/dist/chunks/chunk-WQB4D6DZ.cjs +1 -0
  20. package/dist/chunks/chunk-X66LENNV.cjs +60 -0
  21. package/dist/chunks/cli-handler-CN4Q7BCY.mjs +1 -0
  22. package/dist/chunks/cli-handler-IRPYADZF.cjs +1 -0
  23. package/dist/chunks/{config-M2KZYVRZ.mjs → config-2SQJYVTO.mjs} +1 -1
  24. package/dist/chunks/{config-BFJFRX2C.cjs → config-RPPQ73HK.cjs} +1 -1
  25. package/dist/chunks/consolidate-PUOAAQN3.cjs +2 -0
  26. package/dist/chunks/consolidate-UEYNLKQN.mjs +2 -0
  27. package/dist/chunks/doctor-KPAZWVVZ.mjs +1 -0
  28. package/dist/chunks/doctor-U4HOSXGW.cjs +1 -0
  29. package/dist/chunks/extract-7FFIDVG3.cjs +2 -0
  30. package/dist/chunks/extract-EOZJMLTP.mjs +2 -0
  31. package/dist/chunks/forget-5AXV3GHW.mjs +3 -0
  32. package/dist/chunks/forget-GBMYCUPJ.cjs +3 -0
  33. package/dist/chunks/graph-KOJYJTA4.cjs +3 -0
  34. package/dist/chunks/graph-Y6AYRFCN.mjs +3 -0
  35. package/dist/chunks/init-B24TNUSD.cjs +1 -0
  36. package/dist/chunks/init-HGEBZTJW.mjs +1 -0
  37. package/dist/chunks/{interfaces-VBO3Z6QF.mjs → interfaces-LPJU4KS3.mjs} +1 -1
  38. package/dist/chunks/interfaces-XWE45ENK.cjs +1 -0
  39. package/dist/chunks/llm-RMPVWEVP.cjs +1 -0
  40. package/dist/chunks/llm-UHTBU2HA.mjs +1 -0
  41. package/dist/chunks/mcp-BMAB3TT7.mjs +1 -0
  42. package/dist/chunks/mcp-BS6XHEBR.cjs +1 -0
  43. package/dist/chunks/recall-LKETADTB.cjs +2 -0
  44. package/dist/chunks/recall-UPGGKBNX.mjs +2 -0
  45. package/dist/chunks/remember-KCQN2UWN.mjs +2 -0
  46. package/dist/chunks/remember-VZF4O7ZF.cjs +2 -0
  47. package/dist/chunks/status-2BFVXY5J.cjs +1 -0
  48. package/dist/chunks/status-HGN2YLKJ.mjs +1 -0
  49. package/dist/chunks/stdio-server-GABA2MLR.cjs +1 -0
  50. package/dist/chunks/stdio-server-JPMLMEWY.mjs +1 -0
  51. package/dist/chunks/sync-7Y2DEDDW.mjs +2 -0
  52. package/dist/chunks/sync-W5A2O5TS.cjs +2 -0
  53. package/dist/cli.cjs +1 -1
  54. package/dist/cli.mjs +1 -1
  55. package/dist/index.cjs +4 -4
  56. package/dist/index.d.cts +119 -21
  57. package/dist/index.d.ts +119 -21
  58. package/dist/index.mjs +4 -4
  59. package/package.json +10 -9
  60. package/dist/chunks/chunk-3HTZTI7U.cjs +0 -1
  61. package/dist/chunks/chunk-5W4K5UKV.mjs +0 -53
  62. package/dist/chunks/chunk-7XEOH55R.cjs +0 -1
  63. package/dist/chunks/chunk-BWPPLYIF.cjs +0 -1
  64. package/dist/chunks/chunk-FEMOFIOS.mjs +0 -1
  65. package/dist/chunks/chunk-I5YWAJHW.cjs +0 -32
  66. package/dist/chunks/chunk-JGXW3E73.mjs +0 -59
  67. package/dist/chunks/chunk-MQ72K25M.cjs +0 -59
  68. package/dist/chunks/chunk-NJVXQ7TV.cjs +0 -1
  69. package/dist/chunks/chunk-OWLFPNZG.cjs +0 -1
  70. package/dist/chunks/chunk-PWLSQFYA.mjs +0 -32
  71. package/dist/chunks/chunk-Q2MKNRER.cjs +0 -53
  72. package/dist/chunks/chunk-WQGSYA5D.mjs +0 -1
  73. package/dist/chunks/chunk-Z3NQERNT.mjs +0 -1
  74. package/dist/chunks/cli-handler-57MKQCNO.cjs +0 -1
  75. package/dist/chunks/cli-handler-WW3I2YV4.mjs +0 -1
  76. package/dist/chunks/consolidate-YQ3H643L.cjs +0 -2
  77. package/dist/chunks/consolidate-ZCFRYIWV.mjs +0 -2
  78. package/dist/chunks/doctor-GVSMK4HL.cjs +0 -2
  79. package/dist/chunks/doctor-SPJ64FW3.mjs +0 -2
  80. package/dist/chunks/extract-5VSCY754.mjs +0 -2
  81. package/dist/chunks/extract-E54PPHMQ.cjs +0 -2
  82. package/dist/chunks/forget-AALO5DL5.mjs +0 -3
  83. package/dist/chunks/forget-GEAEUNRH.cjs +0 -3
  84. package/dist/chunks/graph-HSYCZI7R.mjs +0 -3
  85. package/dist/chunks/graph-QEGKUROQ.cjs +0 -3
  86. package/dist/chunks/init-2GZLH6RB.cjs +0 -2
  87. package/dist/chunks/init-U7XRD4MW.mjs +0 -2
  88. package/dist/chunks/interfaces-KNVKCV3Q.cjs +0 -1
  89. package/dist/chunks/mcp-WE7TV32J.cjs +0 -1
  90. package/dist/chunks/mcp-XPTJOCQA.mjs +0 -1
  91. package/dist/chunks/recall-JI2NYDLH.cjs +0 -2
  92. package/dist/chunks/recall-M6SAHHZX.mjs +0 -2
  93. package/dist/chunks/remember-FR5QGXFT.mjs +0 -2
  94. package/dist/chunks/remember-X33PMYA5.cjs +0 -2
  95. package/dist/chunks/status-6XW6Q3TT.mjs +0 -2
  96. package/dist/chunks/status-CPB6XZNU.cjs +0 -2
  97. package/dist/chunks/stdio-server-5LE3HFKN.mjs +0 -1
  98. package/dist/chunks/stdio-server-6PUOFDLR.cjs +0 -1
package/README.en.md CHANGED
@@ -7,7 +7,7 @@ Long-term memory library for the EASBOT ecosystem, providing per-agent fact stor
7
7
  ## Features (v0.4.0)
8
8
 
9
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`.
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
11
  - **Layered memory** — short-term / writable self-memory / long-term history; hybrid search (FTS + vector + graph).
12
12
  - **Observability** — 9 op fully routed through `Log.create({ service })` English structured logs; `status` / `doctor` provide offline diagnostics.
13
13
  - **i18n** — `zh-CN` / `en-US` locales; `@easbot/memory` API logs stay English, copy goes through `t()`.
@@ -95,6 +95,9 @@ await executeOp('graph_query', { agentId: 'agent-1', kind: 'nodes', scope: 'shar
95
95
 
96
96
  // This Agent + shared (trusted local only; MCP entry rejects)
97
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 });
98
101
  ```
99
102
 
100
103
  ### Markdown render
@@ -106,17 +109,25 @@ const md = await renderOperationMarkdown('recall', recallResult, { toolName: 'me
106
109
 
107
110
  ## 9 op manifest
108
111
 
109
- | op | trusted local only | requires agentId | purpose |
112
+ | op | trusted local only | agentId | purpose |
110
113
  |---|---|---|---|
111
- | `recall` | ❌ | ✅ | Hybrid search (FTS + vector + graph) |
112
- | `remember` | ❌ | ✅ | Persist a self-memory fact |
113
- | `forget` | ❌ | ✅ | Delete by factId / category / time window (supports `dryRun`) |
114
- | `extract` | ❌ | ✅ | Aggregate facts / KG nodes for a sessionId |
115
- | `consolidate` | ✅ | ✅ | dedup → archive pipeline |
116
- | `graph_query` | ❌ (scope=both → ✅) | ✅ | KG nodes / edges / BFS neighbors |
117
- | `status` | ❌ | ⚠️ optional | System status snapshot |
118
- | `doctor` | ✅ | ⚠️ optional | Data integrity checks (supports `repair`) |
119
- | `init` | ✅ | ⚠️ optional | Initialize workspace (supports `force`) |
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
120
131
 
121
132
  **Local-only operations** (`consolidate`, `doctor`, `init`) reject non-trusted callers; remote / multi-tenant contexts must not invoke them.
122
133
 
@@ -152,19 +163,122 @@ import type { PreCompactHook, SessionStartHook, SessionEndHook, PostToolFailureH
152
163
 
153
164
  ```bash
154
165
  # Installed via package.json bin: easbot-memory
155
- easbot-memory init --workspace-dir <dir>
166
+ easbot-memory init --workspace-dir <dir> [--agent <id>]
156
167
  easbot-memory status [--agent <id>] [--json]
157
- easbot-memory doctor [--repair]
158
- easbot-memory recall --query <q> [--agent <id>] [--limit <n>] [--json]
159
- easbot-memory remember --content <text> --category <c> --importance <1-10>
160
- easbot-memory forget [--agent <id>] [--fact-id <id>] [--dry-run]
161
- easbot-memory extract --session <sessionId> [--last-n <n>]
162
- easbot-memory consolidate [--agent <id>] [--window-days <n>]
163
- easbot-memory graph --kind <nodes|edges|neighbors> [--query <q>]>]
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>]
164
175
  easbot-memory config [--json]
165
176
  easbot-memory mcp
166
177
  ```
167
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
+ ## Status / Doctor Unified Output Format (Decision 0073 / CLI Spec v1.4)
182
+
183
+ `memory status` / `memory doctor` share the same rendering as `codebase` / `note` via `@easbot/terminal`'s `formatKnowledgeStatus` / `formatKnowledgeDoctor`, ensuring consistent visual and field structure across all three packages.
184
+
185
+ ### Status Output Example
186
+
187
+ ```bash
188
+ $ easbot memory status
189
+ ─ memory status ───────────────────────────────────────────────────
190
+ Root directory E:/work/my-project
191
+ Config ✓ E:/work/my-project/.easbot/memory.json
192
+ DB ✓ E:/work/my-project/.easbot/db/memory.db (5242880 bytes)
193
+ Index state ready
194
+ Schema version 1
195
+ Extraction version 1
196
+ Backend better-sqlite3
197
+ Last sync 2026-08-31T14:23:11.000Z
198
+ Vector enabled ✓
199
+ Embedding dims 1536
200
+ LLM:
201
+ Initialized ✓
202
+ Provider openai
203
+ Capabilities:
204
+ Embedding ✓ text-embedding-3-small
205
+ Graph LLM ✓ gpt-4o-mini
206
+ Rerank LLM ✗
207
+ Counts:
208
+ facts 256
209
+ agent_only 180
210
+ shared_only 42
211
+ both 34
212
+ Healthy ✓
213
+ ```
214
+
215
+ ### Doctor Output Example
216
+
217
+ ```bash
218
+ $ easbot memory doctor
219
+ ─ memory doctor ───────────────────────────────────────────────────
220
+ Healthy ✓
221
+ Duration 98 ms
222
+ Backend availability:
223
+ - better-sqlite3 ✓
224
+ - node:sqlite ✗
225
+ - @tursodatabase/database ✗
226
+ DB stats:
227
+ page_count 320
228
+ page_size 4096
229
+ freelist_count 0
230
+ Checks 10 total (0 error, 0 warn, 1 info, 9 ok)
231
+ [ok] ✓ database: database file exists and accessible (12 ms)
232
+ [ok] ✓ fts: FTS5 available (8 ms)
233
+ [ok] ✓ vector: vector index usable (23 ms)
234
+ [ok] ✓ schema: schema version matches (2 ms)
235
+ [ok] ✓ lock: no lock contention (1 ms)
236
+ [ok] ✓ disk_space: sufficient (156 MB free) (3 ms)
237
+ [ok] ✓ orphan: no orphan records (18 ms)
238
+ [info] ℹ llm: LLM reachable (ping 42 ms) (42 ms)
239
+ [ok] ✓ embedding_cache_unused: no unused embedding cache entries (5 ms)
240
+ [ok] ✓ embedding_dims_consistency: meta=1536 probe=1536 config=1536 (35 ms)
241
+ ```
242
+
243
+ ### Key Fields
244
+
245
+ | Field | Description |
246
+ |-------|-------------|
247
+ | `LLM.initialized` | Whether LLM is initialized (valid config + reachable) |
248
+ | `LLM.capabilities` | Three capabilities: `embedding` / `graphLlm` / `rerankLlm`, each shows model name or ✗ |
249
+ | `Vector enabled` | Whether vector index is enabled |
250
+ | `Embedding dims` | **Probed** embedding dimension (not just from config), probed at status end and written back to meta table |
251
+ | `embedding_dims_consistency` | Doctor check #9: compares meta / probe / config dimensions for consistency |
252
+ | `factsByCategory` | Memory unique: fact counts by category (shown in Counts section) |
253
+
254
+ ### JSON Output (`--json`)
255
+
256
+ ```bash
257
+ $ easbot memory status --json
258
+ {
259
+ "ok": true,
260
+ "data": {
261
+ "rootDir": "E:/work/my-project",
262
+ "configExists": true,
263
+ "dbExists": true,
264
+ "indexState": "ready",
265
+ "schemaVersion": 1,
266
+ "llm": {
267
+ "initialized": true,
268
+ "capabilities": { "embedding": true, "graphLlm": true, "rerankLlm": false },
269
+ "embeddingModel": "text-embedding-3-small",
270
+ "graphModel": "gpt-4o-mini",
271
+ "providerId": "openai"
272
+ },
273
+ "counts": { "facts": 256, "agent_only": 180, "shared_only": 42, "both": 34 },
274
+ "healthy": true
275
+ },
276
+ "meta": { "scope": "all" }
277
+ }
278
+ ```
279
+
280
+ Compatible with [CLI Output Spec v1.4](file:///e:/work/apps/eas/easbot/docs/spec/cli-output-spec.md) / [Decision 0040](file:///e:/work/apps/eas/easbot/docs/decisions/0040-cli-output-unified-json.md).
281
+
168
282
  ### Agent delegation (v0.4 stage 4)
169
283
 
170
284
  ```bash
@@ -213,6 +327,71 @@ const result = await handleMemoryCli(['recall', '--query', 'test'], {
213
327
  if (result.code !== 0) process.exit(result.code);
214
328
  ```
215
329
 
330
+ ## fact → .md document sync (v0.5+ ADR 0060)
331
+
332
+ After `remember` commits the db transaction, it **best-effort** renders the fact into a Markdown file. Benefits:
333
+
334
+ - Debug: developers can read the human-readable copy on disk
335
+ - Future integration: `note` tool may watch memory .md changes for cross-reference updates
336
+ - Resilience: file IO failure **never blocks** db writes (consistent with v0.3)
337
+
338
+ ### Path schema
339
+
340
+ ```
341
+ {workspaceDir}/.easbot/knowledge/memory/{category}/{YYYY-MM}/mem_{id}.md
342
+ ```
343
+
344
+ - One directory per **category** (`task_context` / `workflow` / `user_preference` / ...)
345
+ - One directory per **createdAt month** (avoid packing too many files per month)
346
+ - File name = `fact.id` (globally unique)
347
+ - `memory_facts.file_path` stores a **workspaceDir-relative POSIX path**
348
+
349
+ ### Markdown template
350
+
351
+ ```markdown
352
+ ---
353
+ id: mem_xxx
354
+ agent_id: easbot-xxx
355
+ category: task_context
356
+ importance: 7
357
+ created_at: 2026-08-22T22:00:00Z
358
+ updated_at: 2026-08-22T22:00:00Z
359
+ tags: [tag1, tag2]
360
+ ---
361
+
362
+ # fact content (one line)
363
+
364
+ **category**: task_context | **importance**: 7/10 | **source**: session_self_write
365
+ ```
366
+
367
+ ### Programmatic usage (advanced)
368
+
369
+ Most callers should use `executeOp('remember' / 'forget')` directly. For advanced scenarios (batch migration / custom path strategy):
370
+
371
+ ```typescript
372
+ import { factFileSync } from '@easbot/memory/services';
373
+
374
+ // 1. Compute path without writing
375
+ const absPath = factFileSync.resolvePath(fact, '/path/to/workspace');
376
+
377
+ // 2. Render Markdown string without writing
378
+ const md = factFileSync.renderMarkdown(fact);
379
+
380
+ // 3. Write (best-effort; failure returns ok=false + log.warn, never throws)
381
+ const { ok, relPath, absPath } = await factFileSync.write(fact, '/path/to/workspace');
382
+
383
+ // 4. Delete (by fact.filePath; missing file → ok=true, idempotent)
384
+ const { ok, absPath } = await factFileSync.delete(fact, '/path/to/workspace');
385
+ ```
386
+
387
+ ### Policies and limits
388
+
389
+ - **best-effort**: write/delete failures → `log.warn` + return `ok=false`; **never throws**, **never blocks** main flow
390
+ - **Single-process assumption**: no cross-process file lock (consistent with v0.3)
391
+ - **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)
392
+
393
+ See `docs/decisions/0060-memory-fact-file-sync-restore.md`.
394
+
216
395
  ## Database location
217
396
 
218
397
  Default storage: `$XDG_DATA_HOME/easbot/memory.db`
@@ -223,6 +402,8 @@ Default storage: `$XDG_DATA_HOME/easbot/memory.db`
223
402
 
224
403
  ## Decisions and migration
225
404
 
405
+ - 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`
406
+ - ADR 0060 (v0.5+ fact → .md sync restoration): `docs/decisions/0060-memory-fact-file-sync-restore.md`
226
407
  - ADR 0055 / 0056 / 0057 (v0.4 decisions): `docs/decisions/00NN-*.md`
227
408
  - v0.4 cleanup log: `.easbot/knowledge/tasks/memory-v04-refactor/`
228
409
  - Migration script: `pnpm migrate:v04` (BC-01 ~ BC-12 dry-run + apply)
package/README.md CHANGED
@@ -6,10 +6,10 @@ EASBOT 生态系统的长期记忆管理库(v0.4.0)。提供分层记忆、K
6
6
 
7
7
  ## 特性(v0.4.0)
8
8
 
9
- - **9 op 统一入口**:`recall / remember / forget / extract / consolidate / graph_query / status / doctor / init`,MCP / CLI / Agent Tool 三端共享。
10
- - **KG scope 三档隔离**:每个节点带 `owner_agent_id`;`scope ∈ {agent_only, shared_only, both}`;MCP 默认 `agent_only`,trusted local 可 `both`。
9
+ - **10 op 统一入口**(ADR 0069 +1 sync):`recall / remember / forget / extract / consolidate / sync / graph_query / status / doctor / init`,MCP / CLI / Agent Tool 三端共享。
10
+ - **KG scope 三档隔离**:每个节点带 `owner_agent_id`;`scope ∈ {agent_only, shared_only, both}`;MCP 默认 `agent_only`,trusted local 可 `both`。`graph_query` / `status` / `doctor` / `init` 的 `agentId` 为 **optional**,缺省 fallback `'default'`(ADR 0068 P0-A 反转)。
11
11
  - **分层记忆**:短期 / 可写自记忆 / 历史长期记忆三层,**混合搜索**(FTS + 向量 + 图)。
12
- - **可观测性**:9 op 全部走 `Log.create({ service })` 英文结构化日志;`status` / `doctor` 提供离线诊断。
12
+ - **可观测性**:10 op 全部走 `Log.create({ service })` 英文结构化日志;`status` / `doctor` 提供离线诊断。
13
13
  - **i18n**:`zh-CN` / `en-US` 双 locale;`@easbot/memory` API 日志保持英文,文案走 `t()`。
14
14
  - **可移植**:纯 TS 6.x;依赖 `better-sqlite3`(transitive via `@easbot/database`)+ `@easbot/database`(sync facade)+ `@easbot/types` / `@easbot/utils`(决策 0036 统一封装,禁止直接 require better-sqlite3 / @modelcontextprotocol/sdk)。
15
15
  - **三包统一后台支撑**(决策 0036 / 0049 / 0051 / 0052):database 走 `@easbot/database` `createSyncSqliteConnection`;MCP 走 `@easbot/mcp` `ToolRegistry` + `createAndStartStdioServer`;CLI 输出走 `@easbot/terminal` `printHuman` + `emitJsonOk` + `COMMANDS_HELP` 单一数据源。
@@ -95,6 +95,9 @@ await executeOp('graph_query', { agentId: 'agent-1', kind: 'nodes', scope: 'shar
95
95
 
96
96
  // 本 Agent + 共享(trusted local only;MCP 入口会拒绝)
97
97
  await executeOp('graph_query', { agentId: 'agent-1', kind: 'nodes', scope: 'both' }, { agentId: 'agent-1', isTrustedLocal: true });
98
+
99
+ // v0.4.1+:不传 agentId → fallback 'default',全局 KG 视图(trusted local only)
100
+ await executeOp('graph_query', { kind: 'nodes', scope: 'both' }, { isTrustedLocal: true });
98
101
  ```
99
102
 
100
103
  ### Markdown 渲染
@@ -106,17 +109,26 @@ const md = await renderOperationMarkdown('recall', recallResult, { toolName: 'me
106
109
 
107
110
  ## 9 op 清单
108
111
 
109
- | op | trusted local only | requires agentId | 用途 |
112
+ | op | trusted local only | agentId | 用途 |
110
113
  |---|---|---|---|
111
- | `recall` | ❌ | ✅ | 混合搜索(FTS + vector + graph) |
112
- | `remember` | ❌ | ✅ | 持久化一条 self-memory fact |
113
- | `forget` | ❌ | ✅ | 按 factId / category / 时间窗删除(支持 `dryRun`) |
114
- | `extract` | ❌ | ✅ | 从 session 抽取 facts |
115
- | `consolidate` | ✅ | ✅ | 整理 / 去重 / 摘要 |
116
- | `graph_query` | ❌ (scope=both 时 ✅) | ✅ | KG 节点 / 边 / 邻居查询 |
117
- | `status` | ❌ | ⚠️ optional | 系统状态快照 |
118
- | `doctor` | ✅ | ⚠️ optional | 数据完整性检查(支持 `repair`) |
119
- | `init` | ✅ | ⚠️ optional | 初始化 workspace(支持 `force`) |
114
+ | `recall` | ❌ | ✅ 必填 | 混合搜索(FTS + vector + graph) |
115
+ | `remember` | ❌ | ✅ 必填 | 持久化一条 self-memory fact |
116
+ | `forget` | ❌ | ✅ 必填 | 按 factId / category / 时间窗删除(支持 `dryRun`) |
117
+ | `extract` | ❌ | ✅ 必填 | 从 session 抽取 facts |
118
+ | `consolidate` | ✅ | ✅ 必填 | 整理 / 去重 / 摘要 |
119
+ | `sync` | ✅ | ✅ 必填 | db → .md 兜底生成(幂等)+ active/ 过期文件归档(默认 30 天) |
120
+ | `graph_query` | ❌ (scope=both 时 ✅) | ⚠️ optional,缺省 `'default'` | KG 节点 / 边 / 邻居查询 |
121
+ | `status` | ❌ | ⚠️ optional,缺省全局聚合 | 系统状态快照 |
122
+ | `doctor` | ✅ | ⚠️ optional,缺省全库扫描 | 数据完整性检查(支持 `repair`) |
123
+ | `init` | ✅ | ⚠️ optional,缺省 `'default'` | 初始化 workspace(支持 `force`) |
124
+
125
+ **P0-A 反转说明**(v0.4.1 起):
126
+
127
+ `graph_query` / `status` / `doctor` / `init` 四个 op 的 `agentId` 改为 **optional**,缺省时 fallback 到固定值 `'default'`,不再因缺失 agentId 抛错。这条决策与 ADR 0055 / 0056 / 0057 中"agent scope 必填"的早期语义相反,目的是让 CLI / 状态查询 / 一次性诊断场景可以无 agent 上下文运行。
128
+
129
+ - `graph_query` 不传 agentId → 全局 KG 视图(`scope` 仍由调用方决定,trusted local 默认 `'both'`)
130
+ - `status` 不传 agentId → 跨 agent 聚合统计(不再是单一 agent 视图)
131
+ - `doctor` / `init` 不传 agentId → 全局默认 agent = `'default'`,与 status / graph_query 口径一致
120
132
 
121
133
  ## API 分类
122
134
 
@@ -150,19 +162,123 @@ import type { PreCompactHook, SessionStartHook, SessionEndHook, PostToolFailureH
150
162
 
151
163
  ```bash
152
164
  # 安装后即可用(package.json bin: easbot-memory)
153
- easbot-memory init --workspace-dir <dir>
165
+ easbot-memory init --workspace-dir <dir> [--agent <id>]
154
166
  easbot-memory status [--agent <id>] [--json]
155
- easbot-memory doctor [--repair]
156
- easbot-memory recall --query <q> [--agent <id>] [--limit <n>] [--json]
157
- easbot-memory remember --content <text> --category <c> --importance <1-10>
158
- easbot-memory forget [--agent <id>] [--fact-id <id>] [--dry-run]
159
- easbot-memory extract --session <sessionId> [--last-n <n>]
160
- easbot-memory consolidate [--agent <id>] [--window-days <n>]
161
- easbot-memory graph --kind <nodes|edges|neighbors> [--query <q>]
167
+ easbot-memory doctor [--repair] [--agent <id>]
168
+ easbot-memory recall --query <q> --agent <id> [--limit <n>] [--json]
169
+ easbot-memory remember --content <text> --category <c> --importance <1-10> --agent <id>
170
+ easbot-memory forget --agent <id> [--fact-id <id>] [--dry-run]
171
+ easbot-memory extract --session <sessionId> [--last-n <n>] --agent <id>
172
+ easbot-memory consolidate --agent <id> [--window-days <n>]
173
+ easbot-memory sync --agent <id> [--window-days <n>] [--dry-run] [--json]
174
+ easbot-memory graph --kind <nodes|edges|neighbors> [--query <q>] [--agent <id>]
162
175
  easbot-memory config [--json]
163
176
  easbot-memory mcp
164
177
  ```
165
178
 
179
+ ## Status / Doctor 统一输出格式(决策 0073 / CLI 规范 v1.4)
180
+
181
+ `memory status` / `memory doctor` 与 `codebase` / `note` 三包统一走 `@easbot/terminal` 的 `formatKnowledgeStatus` / `formatKnowledgeDoctor` 渲染,视觉与字段结构完全一致。
182
+
183
+ ### status 输出示例
184
+
185
+ ```bash
186
+ $ easbot memory status
187
+ ─ memory status ───────────────────────────────────────────────────
188
+ Root directory E:/work/my-project
189
+ Config ✓ E:/work/my-project/.easbot/memory.json
190
+ DB ✓ E:/work/my-project/.easbot/db/memory.db (5242880 bytes)
191
+ Index state ready
192
+ Schema version 1
193
+ Extraction version 1
194
+ Backend better-sqlite3
195
+ Last sync 2026-08-31T14:23:11.000Z
196
+ Vector enabled ✓
197
+ Embedding dims 1536
198
+ LLM:
199
+ Initialized ✓
200
+ Provider openai
201
+ Capabilities:
202
+ Embedding ✓ text-embedding-3-small
203
+ Graph LLM ✓ gpt-4o-mini
204
+ Rerank LLM ✗
205
+ Counts:
206
+ facts 256
207
+ agent_only 180
208
+ shared_only 42
209
+ both 34
210
+ Healthy ✓
211
+ ```
212
+
213
+ ### doctor 输出示例
214
+
215
+ ```bash
216
+ $ easbot memory doctor
217
+ ─ memory doctor ───────────────────────────────────────────────────
218
+ Healthy ✓
219
+ Duration 98 ms
220
+ Backend availability:
221
+ - better-sqlite3 ✓
222
+ - node:sqlite ✗
223
+ - @tursodatabase/database ✗
224
+ DB stats:
225
+ page_count 320
226
+ page_size 4096
227
+ freelist_count 0
228
+ Checks 10 total (0 error, 0 warn, 1 info, 9 ok)
229
+ [ok] ✓ database: database file exists and accessible (12 ms)
230
+ [ok] ✓ fts: FTS5 available (8 ms)
231
+ [ok] ✓ vector: vector index usable (23 ms)
232
+ [ok] ✓ schema: schema version matches (2 ms)
233
+ [ok] ✓ lock: no lock contention (1 ms)
234
+ [ok] ✓ disk_space: sufficient (156 MB free) (3 ms)
235
+ [ok] ✓ orphan: no orphan records (18 ms)
236
+ [info] ℹ llm: LLM reachable (ping 42 ms) (42 ms)
237
+ [ok] ✓ embedding_cache_unused: no unused embedding cache entries (5 ms)
238
+ [ok] ✓ embedding_dims_consistency: meta=1536 probe=1536 config=1536 (35 ms)
239
+ ```
240
+
241
+ ### 关键字段说明
242
+
243
+ | 字段 | 说明 |
244
+ |------|------|
245
+ | `LLM.initialized` | LLM 是否已初始化(配置有效且可达) |
246
+ | `LLM.capabilities` | 三大能力:`embedding` / `graphLlm` / `rerankLlm`,各显示模型名或 ✗ |
247
+ | `Vector enabled` | 向量索引是否启用 |
248
+ | `Embedding dims` | **实测** embedding 维度(非仅读 config),status 末尾探测并回填 meta 表 |
249
+ | `embedding_dims_consistency` | doctor 第 9 项检查:对比 meta / probe / config 三方维度是否一致 |
250
+ | `factsByCategory` | memory 独有:按 category 统计的 fact 数量(Counts 段展示) |
251
+
252
+ ### JSON 输出(`--json`)
253
+
254
+ ```bash
255
+ $ easbot memory status --json
256
+ {
257
+ "ok": true,
258
+ "data": {
259
+ "rootDir": "E:/work/my-project",
260
+ "configExists": true,
261
+ "dbExists": true,
262
+ "indexState": "ready",
263
+ "schemaVersion": 1,
264
+ "llm": {
265
+ "initialized": true,
266
+ "capabilities": { "embedding": true, "graphLlm": true, "rerankLlm": false },
267
+ "embeddingModel": "text-embedding-3-small",
268
+ "graphModel": "gpt-4o-mini",
269
+ "providerId": "openai"
270
+ },
271
+ "counts": { "facts": 256, "agent_only": 180, "shared_only": 42, "both": 34 },
272
+ "healthy": true
273
+ },
274
+ "meta": { "scope": "all" }
275
+ }
276
+ ```
277
+
278
+ 兼容 [CLI 输出规范 v1.4](file:///e:/work/apps/eas/easbot/docs/spec/cli-output-spec.md) / [决策 0040](file:///e:/work/apps/eas/easbot/docs/decisions/0040-cli-output-unified-json.md)。
279
+
280
+ > v0.4.1 起:`init` / `status` / `doctor` / `graph` 的 `--agent` 为可选,缺省时 fallback 到 `'default'`(CLI / 一次性诊断场景无需 agent 上下文);其余 6 op(`recall` / `remember` / `forget` / `extract` / `consolidate` / `sync`)仍要求显式 `--agent`,缺失时返回非 0 退出码。
281
+
166
282
  ### Agent 委派模式(v0.4 stage 4 T-M017a)
167
283
 
168
284
  ```bash
@@ -185,13 +301,13 @@ await MemoryStdioServer.start({
185
301
  description: 'EASBot memory MCP server',
186
302
  });
187
303
 
188
- // 列出 9 个 tool 名
304
+ // 列出 10 个 tool 名(ADR 0069 +1 sync)
189
305
  const tools = MemoryStdioServer.getToolNames();
190
- // ['memory_recall', 'memory_remember', 'memory_forget', ...]
306
+ // ['memory_recall', 'memory_remember', 'memory_forget', 'memory_extract', 'memory_consolidate', 'memory_sync', 'memory_graph_query', 'memory_status', 'memory_doctor', 'memory_init']
191
307
  ```
192
308
 
193
- **9 tool 清单**(与 `OP_REGISTRY` 一一对应):
194
- - `memory_recall` / `memory_remember` / `memory_forget` / `memory_extract` / `memory_consolidate` / `memory_graph_query` / `memory_status` / `memory_doctor` / `memory_init`
309
+ **10 tool 清单**(与 `OP_REGISTRY` 一一对应):
310
+ - `memory_recall` / `memory_remember` / `memory_forget` / `memory_extract` / `memory_consolidate` / `memory_sync` / `memory_graph_query` / `memory_status` / `memory_doctor` / `memory_init`
195
311
 
196
312
  ### handleMemoryCli 委派范式
197
313
 
@@ -211,6 +327,72 @@ const result = await handleMemoryCli(['recall', '--query', 'test'], {
211
327
  if (result.code !== 0) process.exit(result.code);
212
328
  ```
213
329
 
330
+ ## fact → .md 文档同步(v0.5+ ADR 0060)
331
+
332
+ `remember` op 在事务提交后会**best-effort**地将 fact 渲染为 Markdown 文件,便于:
333
+
334
+ - debug:开发者直接看磁盘上的「人类可读副本」
335
+ - 二次开发:未来 `note` 工具可通过 file watcher 检测 memory .md 变化触发 cross-reference 更新
336
+ - 灾备:file 失败**不阻塞** db 写入(与 v0.3 行为一致)
337
+
338
+ ### 路径格式(v0.5.1+ 老侯 2026-08-23 反馈修正)
339
+
340
+ ```
341
+ {workspaceDir}/.easbot/memory/active/{category}/{YYYY-MM-DD}.md
342
+ ```
343
+
344
+ - 按 **category** 分目录(`task_context` / `workflow` / `user_preference` / ...)
345
+ - 按 **createdAt 本地日期**分文件(一日一文件,append 模式,多 fact 共享)
346
+ - 文件名 = `{YYYY-MM-DD}.md`(不再含 fact.id)
347
+ - `memory_facts.file_path` 列存**相对 workspaceDir 的 POSIX 路径**
348
+ - 归档路径(ADR 0069 sync):`{workspaceDir}/.easbot/memory/archive/{YYYY-MM}/{category}/{YYYY-MM-DD}.md`(扁平结构)
349
+
350
+ ### Markdown 模板
351
+
352
+ ```markdown
353
+ ---
354
+ id: mem_xxx
355
+ agent_id: easbot-xxx
356
+ category: task_context
357
+ importance: 7
358
+ created_at: 2026-08-22T22:00:00Z
359
+ updated_at: 2026-08-22T22:00:00Z
360
+ tags: [tag1, tag2]
361
+ ---
362
+
363
+ # fact 内容(一行一个)
364
+
365
+ **category**: task_context | **importance**: 7/10 | **source**: session_self_write
366
+ ```
367
+
368
+ ### 编程式调用(高级)
369
+
370
+ 大多数场景不需要直接调 —— 走 `executeOp('remember' / 'forget')` 即可。需要精细控制时(如批量迁移 / 自定义路径策略):
371
+
372
+ ```typescript
373
+ import { factFileSync } from '@easbot/memory/services';
374
+
375
+ // 1. 计算路径(不写文件)
376
+ const absPath = factFileSync.resolvePath(fact, '/path/to/workspace');
377
+
378
+ // 2. 渲染 Markdown 字符串(不写文件)
379
+ const md = factFileSync.renderMarkdown(fact);
380
+
381
+ // 3. 写文件(best-effort;失败返回 ok=false + log.warn)
382
+ const { ok, relPath, absPath } = await factFileSync.write(fact, '/path/to/workspace');
383
+
384
+ // 4. 删文件(按 fact.filePath;不存在返回 ok=true,idempotent)
385
+ const { ok, absPath } = await factFileSync.delete(fact, '/path/to/workspace');
386
+ ```
387
+
388
+ ### 策略与限制
389
+
390
+ - **best-effort**:写/删文件失败 → log.warn + 返回 `ok=false`,**不抛错,不阻塞**主流程
391
+ - **单进程假设**:未实现跨进程文件锁(与 v0.3 一致)
392
+ - **不做 stale orphan 清理**:forget 删 db 后删文件;如 db 删成功文件删失败 → 留 stale .md(doctor 第 9 项「orphan file 检测」后续增强)
393
+
394
+ 详见 `docs/decisions/0060-memory-fact-file-sync-restore.md`。
395
+
214
396
  ## 数据库位置
215
397
 
216
398
  默认存储位置:`$XDG_DATA_HOME/easbot/memory.db`
@@ -221,6 +403,9 @@ if (result.code !== 0) process.exit(result.code);
221
403
 
222
404
  ## 决策与迁移
223
405
 
406
+ - ADR 0069(v0.5+ memory sync op:两阶段流水线 —— db → .md 兜底生成(幂等)+ active/ 过期归档):`docs/decisions/0069-memory-sync-op.md`
407
+ - ADR 0068(v0.4.1 P0-A 反转:graph_query / status / doctor / init 的 agentId 改为 optional,缺省 fallback `'default'`):`docs/decisions/0068-p0a-agent-id-optional.md`
408
+ - ADR 0060(v0.5+ fact → .md 同步恢复):`docs/decisions/0060-memory-fact-file-sync-restore.md`
224
409
  - ADR 0055 / 0056 / 0057(v0.4 决策):`.easbot/protocol.json` 与 `docs/decisions/00NN-*.md`
225
410
  - 迁移脚本:`scripts/migrate/{scan,apply,review}.ts` + `scripts/db-backup.ts`(v0.3 → v0.4 `owner_agent_id` 列添加 + 默认 scope = agent_only)
226
411
  - CI guard(v0.4 stage 5 三包统一后台支撑):
@@ -0,0 +1 @@
1
+ 'use strict';var chunkWQB4D6DZ_cjs=require('./chunk-WQB4D6DZ.cjs');function o(r,t){return chunkWQB4D6DZ_cjs.a(`memory.${r}.empty`,{fallback:t})}function s(r,t,m){return chunkWQB4D6DZ_cjs.a(`memory.${r}.summary`,{vars:t,fallback:m})}function g(r,t,m){return chunkWQB4D6DZ_cjs.a(`memory.${r}.item`,{vars:t,fallback:m})}exports.a=o;exports.b=s;exports.c=g;