@easbot/memory 0.3.37 → 0.3.40

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 (45) hide show
  1. package/README.en.md +126 -81
  2. package/README.md +52 -36
  3. package/dist/assets/txt/src/plugin/tool/memory.txt +1 -1
  4. package/dist/chunks/{chunk-ISYAE6B7.cjs → chunk-4CMSRWL3.cjs} +12 -12
  5. package/dist/chunks/{chunk-QAEIHJOF.cjs → chunk-77ERAHDK.cjs} +16 -16
  6. package/dist/chunks/{chunk-4G4FSAFY.cjs → chunk-BHGAFQCX.cjs} +1 -1
  7. package/dist/chunks/{chunk-FZ3RTYIJ.mjs → chunk-LM6WT4CO.mjs} +11 -11
  8. package/dist/chunks/{chunk-AEAMQDNV.mjs → chunk-LQ4OZPZI.mjs} +16 -16
  9. package/dist/chunks/{chunk-YUWHNHAY.mjs → chunk-NBPDJQIR.mjs} +1 -1
  10. package/dist/chunks/cli-handler-EA6B2IET.mjs +1 -0
  11. package/dist/chunks/cli-handler-F67HXX57.cjs +1 -0
  12. package/dist/chunks/{consolidate-OOAMW7XW.mjs → consolidate-I5KIRN4Q.mjs} +1 -1
  13. package/dist/chunks/{consolidate-IKQVVWIQ.cjs → consolidate-V5B7US3A.cjs} +1 -1
  14. package/dist/chunks/{doctor-ZGHICE2Q.mjs → doctor-GYFZEOFU.mjs} +1 -1
  15. package/dist/chunks/{doctor-N6HHFR6Y.cjs → doctor-WB5IFSAX.cjs} +1 -1
  16. package/dist/chunks/{extract-7DQ6OV34.cjs → extract-NKDG4CRZ.cjs} +1 -1
  17. package/dist/chunks/{extract-AJY2ETKE.mjs → extract-PRZC6J42.mjs} +1 -1
  18. package/dist/chunks/{forget-4KGLTQ5Q.cjs → forget-HMP73OMP.cjs} +1 -1
  19. package/dist/chunks/{forget-NIBBY6FG.mjs → forget-ZETWU236.mjs} +1 -1
  20. package/dist/chunks/{graph-OG23VZZM.cjs → graph-RPU4LN35.cjs} +1 -1
  21. package/dist/chunks/{graph-4K56ZAVL.mjs → graph-XCIX6M4X.mjs} +1 -1
  22. package/dist/chunks/{init-HWR4SD6N.mjs → init-65BD6AXC.mjs} +1 -1
  23. package/dist/chunks/{init-UQTPANNI.cjs → init-EB7XE4QK.cjs} +1 -1
  24. package/dist/chunks/{mcp-ONIMP7FB.cjs → mcp-EPQG2OIZ.cjs} +1 -1
  25. package/dist/chunks/{mcp-ZWZYH52C.mjs → mcp-KUQ55KNY.mjs} +1 -1
  26. package/dist/chunks/{recall-BRXHJPR4.mjs → recall-ARCQ5XUX.mjs} +1 -1
  27. package/dist/chunks/{recall-KZRYTTWA.cjs → recall-SEYESB2W.cjs} +1 -1
  28. package/dist/chunks/{remember-GLOJH457.cjs → remember-22SZ6PPM.cjs} +1 -1
  29. package/dist/chunks/{remember-3XSYCWKK.mjs → remember-KAVRIPMH.mjs} +1 -1
  30. package/dist/chunks/{status-POX2GWSQ.cjs → status-6724XOPA.cjs} +1 -1
  31. package/dist/chunks/{status-SW5BUHJ3.mjs → status-SKORJWEX.mjs} +1 -1
  32. package/dist/chunks/stdio-server-5HTVIDF7.mjs +1 -0
  33. package/dist/chunks/{stdio-server-W52CMVJO.cjs → stdio-server-AHIGDFUH.cjs} +1 -1
  34. package/dist/chunks/{sync-I423W5G7.cjs → sync-RNULQHQD.cjs} +1 -1
  35. package/dist/chunks/{sync-EE4ZD3WB.mjs → sync-UVNIQMEQ.mjs} +1 -1
  36. package/dist/cli.cjs +1 -1
  37. package/dist/cli.mjs +1 -1
  38. package/dist/index.cjs +35 -25
  39. package/dist/index.d.cts +134 -50
  40. package/dist/index.d.ts +134 -50
  41. package/dist/index.mjs +35 -25
  42. package/package.json +11 -11
  43. package/dist/chunks/cli-handler-JHSDGJHK.mjs +0 -1
  44. package/dist/chunks/cli-handler-USK4CPAU.cjs +0 -1
  45. package/dist/chunks/stdio-server-3A3H4YJ7.mjs +0 -1
package/README.en.md CHANGED
@@ -2,17 +2,17 @@
2
2
 
3
3
  [中文](./README.md) | English
4
4
 
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.
5
+ Long-term memory library for the EASBOT ecosystem (v0.4.0). Provides layered memory, three-tier KG scope isolation, a unified 10-op dispatch, hybrid search and observable governance.
6
6
 
7
7
  ## Version
8
8
 
9
- v0.3.37
9
+ v0.3.40
10
10
  ## Features (v0.4.0)
11
11
 
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)`.
13
- - **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).
14
- - **Layered memory** — short-term / writable self-memory / long-term history; hybrid search (FTS + vector + graph).
15
- - **Observability** — 9 op fully routed through `Log.create({ service })` English structured logs; `status` / `doctor` provide offline diagnostics.
12
+ - **10 op unified entry** (ADR 0069 +1 `sync`) — `recall / remember / forget / extract / consolidate / sync / graph_query / status / doctor / init`; MCP / CLI / Agent Tool share the same `executeOp(name, args, ctx)`.
13
+ - **Three-tier KG scope isolation** — each 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`, falling back to `'default'` (ADR 0068 P0-A reversal).
14
+ - **Layered memory** — short-term / writable self-memory / long-term history; **hybrid search** (FTS + vector + graph).
15
+ - **Observability** — all 10 ops route through `Log.create({ service })` English structured logs; `status` / `doctor` provide offline diagnostics.
16
16
  - **i18n** — `zh-CN` / `en-US` locales; `@easbot/memory` API logs stay English, copy goes through `t()`.
17
17
  - **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`).
18
18
  - **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.
@@ -25,7 +25,7 @@ pnpm add @easbot/memory
25
25
 
26
26
  ## Usage
27
27
 
28
- ### 9 op entry
28
+ ### 10 op entry
29
29
 
30
30
  ```typescript
31
31
  import { executeOp } from '@easbot/memory';
@@ -89,30 +89,45 @@ await executeOp(
89
89
 
90
90
  ### KG scope three tiers
91
91
 
92
+ > **2026-09-23 PR-2 sync**: the `graph_query` v0.5 schema was simplified (aligned with `note.graph_query`):
93
+ >
94
+ > - The **agent tool main path** accepts a positive-integer `nodeId` (numeric strings included), plus optional `maxDepth` / `maxNodes` / `maxEdgesPerNode` / `relation` / `type`
95
+ > - Name-fragment `query` matching is retained only for the CLI `easbot memory graph query`; it is not exposed by the agent tool
96
+ > - `maxDepth` (default 2) / `maxNodes` (default 100) / `maxEdgesPerNode` (default 10, max 100) control the BFS budget
97
+ > - `scope` goes through the CLI (fine-grained filtering)
98
+ > - Agent tool `maxEdgesPerNode` fix: the service zod schema `graphQueryParamsSchema` declared this field in PR-2 (its earlier absence caused `.strict()` to reject it → recall/graph_query failures in agent context)
99
+
92
100
  ```typescript
93
- // Only this Agent's nodes (default; MCP entry enforces)
101
+ // Agent tool main path (v0.5+): query neighbors by numeric nodeId
94
102
  await executeOp(
95
103
  'graph_query',
96
- { agentId: 'agent-1', kind: 'nodes', scope: 'agent_only' },
104
+ { nodeId: 12, maxDepth: 2, maxNodes: 100, maxEdgesPerNode: 10 },
105
+ { agentId: 'agent-1', isTrustedLocal: true },
106
+ );
107
+
108
+ // CLI path (v0.4.1+, kept for compatibility): name fuzzy match + scope/type/relation filters
109
+ await executeOp(
110
+ 'graph_query',
111
+ { query: 'TS', scope: 'agent_only', type: 'class', maxDepth: 2 },
97
112
  { agentId: 'agent-1', isTrustedLocal: true },
98
113
  );
99
114
 
100
115
  // Only shared nodes
101
116
  await executeOp(
102
117
  'graph_query',
103
- { agentId: 'agent-1', kind: 'nodes', scope: 'shared_only' },
118
+ { query: 'TS', scope: 'shared_only' },
104
119
  { agentId: 'agent-1', isTrustedLocal: true },
105
120
  );
106
121
 
107
122
  // This Agent + shared (trusted local only; MCP entry rejects)
108
123
  await executeOp(
109
124
  'graph_query',
110
- { agentId: 'agent-1', kind: 'nodes', scope: 'both' },
125
+ { query: 'TS', scope: 'both' },
111
126
  { agentId: 'agent-1', isTrustedLocal: true },
112
127
  );
113
128
 
114
129
  // v0.4.1+: omitting agentId → fallback 'default', global KG view (trusted local only)
115
- await executeOp('graph_query', { kind: 'nodes', scope: 'both' }, { isTrustedLocal: true });
130
+ await executeOp('graph_query', { query: 'TS', scope: 'both' }, { isTrustedLocal: true });
116
131
  ```
117
132
 
118
133
  ### Markdown render
@@ -122,19 +137,20 @@ import { renderOperationMarkdown } from '@easbot/memory';
122
137
  const md = await renderOperationMarkdown('recall', recallResult, { toolName: 'memory_recall' });
123
138
  ```
124
139
 
125
- ## 9 op manifest
126
-
127
- | op | trusted local only | agentId | purpose |
128
- | ------------- | -------------------- | ----------------------------------------- | ------------------------------------------------------------- |
129
- | `recall` | ❌ | ✅ required | Hybrid search (FTS + vector + graph) |
130
- | `remember` | ❌ | ✅ required | Persist a self-memory fact |
131
- | `forget` | ❌ | ✅ required | Delete by factId / category / time window (supports `dryRun`) |
132
- | `extract` | ❌ | ✅ required | Aggregate facts / KG nodes for a sessionId |
133
- | `consolidate` | ✅ | ✅ required | dedup → archive pipeline |
134
- | `graph_query` | ❌ (scope=both → ✅) | ⚠️ optional, defaults to `'default'` | KG nodes / edges / BFS neighbors |
135
- | `status` | ❌ | ⚠️ optional, defaults to global aggregate | System status snapshot |
136
- | `doctor` | ✅ | ⚠️ optional, defaults to whole-DB scan | Data integrity checks (supports `repair`) |
137
- | `init` | ✅ | ⚠️ optional, defaults to `'default'` | Initialize workspace (supports `force`) |
140
+ ## 10 op manifest
141
+
142
+ | op | trusted local only | agentId | purpose |
143
+ | ------------- | -------------------- | ----------------------------------------- | ----------------------------------------------------------------------------- |
144
+ | `recall` | ❌ | ✅ required | Hybrid search (FTS + vector + graph) |
145
+ | `remember` | ❌ | ✅ required | Persist a self-memory fact |
146
+ | `forget` | ❌ | ✅ required | Delete by factId / category / time window (supports `dryRun`) |
147
+ | `extract` | ❌ | ✅ required | Extract facts from a session |
148
+ | `consolidate` | ✅ | ✅ required | Consolidate / dedup / summarize |
149
+ | `sync` | ✅ | ✅ required | db → .md fallback generation (idempotent) + active/ stale-file archival (30d) |
150
+ | `graph_query` | ❌ (scope=both → ✅) | ⚠️ optional, defaults to `'default'` | KG nodes / edges / neighbors queries |
151
+ | `status` | ❌ | ⚠️ optional, defaults to global aggregate | System status snapshot |
152
+ | `doctor` | ✅ | ⚠️ optional, defaults to whole-DB scan | Data integrity checks (supports `repair`) |
153
+ | `init` | ✅ | ⚠️ optional, defaults to `'default'` | Initialize workspace (supports `force`) |
138
154
 
139
155
  **P0-A reversal note** (since v0.4.1):
140
156
 
@@ -144,11 +160,29 @@ Four ops — `graph_query` / `status` / `doctor` / `init` — have made `agentId
144
160
  - `status` without agentId → cross-agent aggregate stats (no longer single-agent view)
145
161
  - `doctor` / `init` without agentId → default agent = `'default'`, aligned with status / graph_query semantics
146
162
 
147
- **Local-only operations** (`consolidate`, `doctor`, `init`) reject non-trusted callers; remote / multi-tenant contexts must not invoke them.
163
+ ### `recall` snippet truncation (2026-10-13)
164
+
165
+ `snippet` is a **truncated copy** for preview only; the full body lives in `hit.content` (decision 0086 v2). Historically `SUBSTR(mf.content, 1, 200)` hardcoded the length in the SQL literal; it is now unified under `@easbot/database`'s source of truth and **pulled back to an internal parameter**:
166
+
167
+ | Layer | Owner | Default | Semantics |
168
+ | ------------------- | ----------------------------------------- | ------------------------------- | ------------------------------------------------------------------------------------ |
169
+ | service layer | internal (`RecallParams.snippetMaxChars`) | `2000` (= `SQL_TEXT_LIMIT_MAX`) | **Defense cap** — keeps a single fact from bloating the result set |
170
+ | op schema | **not exposed** | — | LLMs should not decide server-side truncation length; `.strict()` rejects this field |
171
+ | format/render layer | each renderer applies its own `slice` | scenario-specific | **Display decision** — terminal / CLI previews are usually far shorter than the cap |
172
+
173
+ ```typescript
174
+ // Service-internal / programmatic calls may pass it (still clamped)
175
+ await recall(ctx, { query: '...', maxResults: 10, snippetMaxChars: 800 });
176
+
177
+ // LLM / MCP / agent tool passing it fails immediately (unknown field)
178
+ await executeOp('recall', { query: '...', snippetMaxChars: 800 }, ctx); // ❌ throws
179
+ ```
180
+
181
+ **Constraint**: whatever is passed goes through `resolveSqlTextLimit` and is clamped to `[1, SQL_TEXT_LIMIT_MAX]` — **the defense cannot be bypassed**. The default was raised from the hardcoded 200 to 2000: 200 chars is only ≈ 133 tokens in Chinese, not enough information to support a summary (see `@easbot/llm`'s `SummaryProvider` for the summary chain).
148
182
 
149
183
  ## API categories
150
184
 
151
- ### services (9 op business layer)
185
+ ### services (10 op business layer)
152
186
 
153
187
  ```typescript
154
188
  import {
@@ -164,7 +198,7 @@ import {
164
198
  } from '@easbot/memory/services';
165
199
  ```
166
200
 
167
- ### operations (9 op registry + executeOp)
201
+ ### operations (10 op registry + executeOp)
168
202
 
169
203
  ```typescript
170
204
  import { executeOp, OP_REGISTRY, ALL_OPS } from '@easbot/memory/operations';
@@ -176,65 +210,74 @@ import { executeOp, OP_REGISTRY, ALL_OPS } from '@easbot/memory/operations';
176
210
  import { renderOperationMarkdown } from '@easbot/memory/format/render';
177
211
  ```
178
212
 
179
- ### hooks (4 hook types)
180
-
181
- ```typescript
182
- import type {
183
- PreCompactHook,
184
- SessionStartHook,
185
- SessionEndHook,
186
- PostToolFailureHook,
187
- } from '@easbot/memory/hooks';
188
- ```
189
-
190
213
  ### plugin (plugin / hook / tool)
191
214
 
192
215
  `@easbot/memory` ships an installable plugin following the `@easbot/plugin` contract:
193
- 3 lifecycle hooks and 1 `memory` tool. The implementation lives in `src/plugin/`, and
216
+ 4 lifecycle hooks and 1 `memory` tool. The implementation lives in `src/plugin/`, and
194
217
  every symbol is **imported from the package root** (no subpath exports).
195
218
 
219
+ > **Distribution form (2026-11-18 decision)**: the memory plugin does **not** go into the host's `INTERNAL_PLUGINS`;
220
+ > it is installed via marketplace — all 4 hooks (context recall / pre-compaction cleanup /
221
+ > tool-failure fallback / end-of-loop extraction) plus 1 `memory` tool are fully effective.
222
+ > The tool carries its own `isEnabled` (`MemoryCache.exists()` — based solely on L2 config presence);
223
+ > the host only forwards it, and no agent-side module config decides availability any more.
224
+ > Uninstalling the plugin disables memory.
225
+
226
+ > **Session-level events (ADR 0159)**: memory does **not** register `session.start` / `session.end`
227
+ > handlers — session records do not persist the agent identity (`protocolMetadata.agentId` only
228
+ > exists in the LLM-layer `ToolContext`), so those events cannot provide the `agentId` memory needs;
229
+ > registering them would create dangling handlers that never do anything. Session-level memory
230
+ > extraction stays on `loop.end` (end of one conversation turn).
231
+
196
232
  ```typescript
197
233
  import {
198
234
  MemoryPlugin,
199
235
  MEMORY_PLUGIN_MANIFEST,
200
236
  MEMORY_HOOK_EVENTS,
237
+ MEMORY_FRAGMENT_MAX_TOKENS,
201
238
  MemoryPluginHook,
202
239
  createMemoryHookMatchers,
203
240
  MemoryTool,
204
241
  } from '@easbot/memory';
205
242
  ```
206
243
 
207
- | Export | Description |
208
- | ------------------------------------- | ------------------------------------------------------------------------------------------- |
209
- | `MemoryPlugin` / `default` / `Plugin` | Plugin entry, returns `Promise<PluginDefinition>` |
210
- | `MEMORY_PLUGIN_MANIFEST` | Manifest mirroring `plugin.json` (`name` / `version` / `entry` / `capabilities`) |
211
- | `MEMORY_HOOK_EVENTS` | 3 dotted events: `context.build.before` / `session.compacting` / `tool.failure` |
212
- | `MemoryPluginHook` | `HookInfo` shape (host built-in registration path) |
213
- | `createMemoryHookMatchers()` | `HookMatcher[]` shape (plugin registration path) |
214
- | `MemoryTool` | `ToolDefinition`: flat `args` map (`operation` + per-op params), `execute` returns a string |
215
- | `MEMORY_TOOL_OPS` | 7 ops: `recall` / `remember` / `update` / `forget` / `extract` / `graph_query` / `status` |
216
- | `MEMORY_TOOL_ARGS` | Flat parameter schema, field-by-field aligned with the host built-in memory tool |
244
+ | Export | Description |
245
+ | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
246
+ | `MemoryPlugin` / `default` / `Plugin` | Plugin entry, returns `Promise<PluginDefinition>` |
247
+ | `MEMORY_PLUGIN_MANIFEST` | Manifest mirroring `plugin.json` (`name` / `version` / `entry` / `capabilities`) |
248
+ | `MEMORY_HOOK_EVENTS` | 4 dotted events: `context.collect` / `session.compacting` / `tool.failure` / `loop.end` (the latter carries long-term memory extraction) |
249
+ | `MEMORY_FRAGMENT_MAX_TOKENS` | **Absolute** cap (`1200` tokens) for the whole rendered fragment — content is rendered in full, then truncated by `TruncateContent` with the full text saved to disk (agent can read it back) |
250
+ | `MemoryPluginHook` | `HookInfo` shape (for hosts that prefer the built-in hook registration path) |
251
+ | `createMemoryHookMatchers()` | `HookMatcher[]` shape (plugin registration path) |
252
+ | `MemoryTool` | `ToolDefinition`: `args` is a **discriminated union** (7 op branches keyed by `operation`), `execute` returns a `ToolResult` (`{ output, title, metadata }`) |
253
+ | `MEMORY_TOOL_OPS` | 7 ops: `recall` / `remember` / `update` / `forget` / `extract` / `graph_query` / `status` |
254
+ | `MEMORY_TOOL_ARGS` | Full parameter schema (`z.discriminatedUnion('operation', [...])`), field-by-field aligned with the host built-in memory tool |
217
255
 
218
256
  #### Tool parameter contract (aligned with the host built-in tool)
219
257
 
220
258
  The plugin tool `args` match the host built-in `packages/agent/src/tool/memory.ts`
221
- field by field: `operation` selects the op, and the remaining flat parameters are
222
- shared across ops (the host `packages/agent/src/plugin/plugin.ts` enforces
223
- `z.object(args)`, so a discriminated union is not available).
224
-
225
- | Op | Effective parameters |
226
- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
227
- | `recall` | `query` (required) / `limit` (default 10, max 100) / `category` / `minImportance` / `maxEdgesPerNode` / `includeGraph` / `includeShared` |
228
- | `remember` | `content` (required) / `category` / `importance` (1-10) / `tags` |
229
- | `update` | `factId` (required) plus at least one of `content` / `category` / `importance` / `tags` |
230
- | `forget` | `factId` (required) / `dryRun` / `force` |
231
- | `extract` | `lastN` (default 10) / `fromMessageId` |
232
- | `graph_query` | `query` or `nodeId` (one required) / `maxDepth` (default 2, max 5) / `maxNodes` (default 100, max 500) / `maxEdgesPerNode` |
233
- | `status` | no extra parameters |
234
-
235
- Op-specific required fields, ranges and mutual exclusions are validated a second
236
- time inside the plugin (`parseOperationParams`); validation failures return a
237
- structured error instead of throwing.
259
+ field by field, and now share its **shape** as well: a discriminated union
260
+ `z.discriminatedUnion('operation', [...])` with one branch per op. Each branch
261
+ declares only that op's parameters and is `.strict()` (undeclared fields are
262
+ rejected). The host (`packages/agent/src/plugin/plugin.ts`) forwards a **full zod
263
+ schema as-is** (it is no longer flattened into a shape map), so per-op required
264
+ fields, ranges and cross-field rules are expressed by the schema itself — no
265
+ secondary validation inside the plugin is needed.
266
+
267
+ | Op | Effective parameters |
268
+ | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
269
+ | `recall` | `query` (required) / `limit` (default 10) / `category` / `minImportance` (1-10, inclusive) / `minScore` (0-1) / `maxEdgesPerNode` (default 10, 1-100) / `includeGraph` / `includeShared` |
270
+ | `remember` | `content` (required) / `category` (required) / `importance` (required, 1-10) / `tags` |
271
+ | `update` | `factId` (required) plus at least one of `content` / `category` / `importance` / `tags` |
272
+ | `forget` | `factId` (required) / `dryRun` (default false) / `force` (default false) |
273
+ | `extract` | `lastN` (default 10) / `fromMessageId` |
274
+ | `graph_query` | `nodeId` (required, positive integer) / `maxDepth` (default 2) / `maxNodes` (default 100) / `maxEdgesPerNode` (default 10) / `relation` / `type` |
275
+ | `status` | no extra parameters |
276
+
277
+ Tool return values are uniformly `ToolResult` (`{ output, title, metadata }`): `output` goes back
278
+ to the model, while `title` / `metadata` are consumed by the host UI and statistics. For `remember`,
279
+ embedding is an optional enhancement: adapter, model, or network failures fall back to FTS-only
280
+ without blocking fact persistence or recall.
238
281
 
239
282
  #### Distribution artifact generation
240
283
 
@@ -314,6 +357,7 @@ easbot-memory remember --content <text> --category <c> --importance <1-10>
314
357
  easbot-memory forget [--fact-id <id>] [--dry-run]
315
358
  easbot-memory extract --session <sessionId> [--last-n <n>]
316
359
  easbot-memory consolidate [--window-days <n>]
360
+ easbot-memory sync [--window-days <n>] [--dry-run] [--json]
317
361
  easbot-memory graph [--query <q>] [--node-id <id>]
318
362
  easbot-memory config [--json]
319
363
  easbot-memory mcp
@@ -444,22 +488,22 @@ easbot memory mcp # starts MCP stdio server
444
488
  ```typescript
445
489
  import { MemoryStdioServer } from '@easbot/memory';
446
490
 
447
- // Start 9 tool MCP stdio server (callable by Cline / Claude Code / Continue)
448
- // v0.4.0: start signature simplified — no `system` param needed (handlers dispatch via executeOp)
491
+ // Start the 10-tool MCP stdio server (callable by Cline / Claude Code / Continue)
492
+ // v0.4.0: start signature simplified — no `memorySystem` param needed (handlers dispatch via executeOp)
449
493
  await MemoryStdioServer.start({
450
494
  name: 'easbot-memory',
451
495
  version: '0.4.0',
452
496
  description: 'EASBot memory MCP server',
453
497
  });
454
498
 
455
- // List 9 tool names
499
+ // List the 10 tool names (ADR 0069 +1 sync)
456
500
  const tools = MemoryStdioServer.getToolNames();
457
- // ['memory_recall', 'memory_remember', 'memory_forget', ...]
501
+ // ['memory_recall', 'memory_remember', 'memory_forget', 'memory_extract', 'memory_consolidate', 'memory_sync', 'memory_graph_query', 'memory_status', 'memory_doctor', 'memory_init']
458
502
  ```
459
503
 
460
- **9 tool manifest** (1:1 with `OP_REGISTRY`):
504
+ **10 tool manifest** (1:1 with `OP_REGISTRY`):
461
505
 
462
- - `memory_recall` / `memory_remember` / `memory_forget` / `memory_extract` / `memory_consolidate` / `memory_graph_query` / `memory_status` / `memory_doctor` / `memory_init`
506
+ - `memory_recall` / `memory_remember` / `memory_forget` / `memory_extract` / `memory_consolidate` / `memory_sync` / `memory_graph_query` / `memory_status` / `memory_doctor` / `memory_init`
463
507
 
464
508
  ### handleMemoryCli delegation
465
509
 
@@ -487,16 +531,17 @@ After `remember` commits the db transaction, it **best-effort** renders the fact
487
531
  - Future integration: `note` tool may watch memory .md changes for cross-reference updates
488
532
  - Resilience: file IO failure **never blocks** db writes (consistent with v0.3)
489
533
 
490
- ### Path schema
534
+ ### Path schema (v0.5.1+ feedback fix)
491
535
 
492
536
  ```
493
- {workspaceDir}/.easbot/knowledge/memory/{category}/{YYYY-MM}/mem_{id}.md
537
+ {workspaceDir}/.easbot/memory/active/{category}/{YYYY-MM-DD}.md
494
538
  ```
495
539
 
496
540
  - One directory per **category** (`task_context` / `workflow` / `user_preference` / ...)
497
- - One directory per **createdAt month** (avoid packing too many files per month)
498
- - File name = `fact.id` (globally unique)
541
+ - One file per **createdAt local date** (one file per day, append mode, shared by multiple facts)
542
+ - File name = `{YYYY-MM-DD}.md` (no longer contains fact.id)
499
543
  - `memory_facts.file_path` stores a **workspaceDir-relative POSIX path**
544
+ - Archive path (ADR 0069 sync): `{workspaceDir}/.easbot/memory/archive/{YYYY-MM}/{category}/{YYYY-MM-DD}.md` (flat structure)
500
545
 
501
546
  ### Markdown template
502
547
 
@@ -554,16 +599,16 @@ Default storage: `$XDG_DATA_HOME/easbot/memory.db`
554
599
 
555
600
  ## Decisions and migration
556
601
 
602
+ - ADR 0069 (v0.5+ memory sync op: two-stage pipeline — idempotent db → .md fallback generation + active/ stale archival): `docs/decisions/0069-memory-sync-op.md`
557
603
  - 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`
558
604
  - ADR 0060 (v0.5+ fact → .md sync restoration): `docs/decisions/0060-memory-fact-file-sync-restore.md`
559
- - ADR 0055 / 0056 / 0057 (v0.4 decisions): `docs/decisions/00NN-*.md`
560
- - v0.4 cleanup log: `.easbot/knowledge/tasks/memory-v04-refactor/`
561
- - Migration script: `pnpm migrate:v04` (BC-01 ~ BC-12 dry-run + apply)
605
+ - ADR 0055 / 0056 / 0057 (v0.4 decisions): `.easbot/protocol.json` and `docs/decisions/00NN-*.md`
606
+ - Migration scripts: `scripts/migrate/{scan,apply,review}.ts` + `scripts/db-backup.ts` (v0.3 → v0.4 `owner_agent_id` column + default scope = agent_only)
562
607
  - CI guards (v0.4 stage 5 three-package unified backend support):
563
608
  - `scripts/check-database-facade.sh` (forbid directly requiring `better-sqlite3` / `node:sqlite` / `createRequire`)
564
609
  - `scripts/check-mcp-facade.sh` (forbid directly importing `@modelcontextprotocol/sdk`)
565
610
  - `scripts/check-terminal-facade.sh` (CLI output goes through `@easbot/terminal` + `COMMANDS_HELP` single source of truth)
566
- - `scripts/check-cmd-i18n-coverage.sh` (zh-CN / / en-US dual-locale consistency + switch-case routing validation)
611
+ - `scripts/check-cmd-i18n-coverage.sh` (zh-CN / en-US dual-locale consistency + switch-case routing validation)
567
612
  - L-M13 / L-M14 / L-M15 lessons: `.easbot/knowledge/tasks/memory-v04-refactor/findings.md`
568
613
 
569
614
  ## Development
package/README.md CHANGED
@@ -6,7 +6,7 @@ EASBOT 生态系统的长期记忆管理库(v0.4.0)。提供分层记忆、K
6
6
 
7
7
  ## 版本
8
8
 
9
- v0.3.37
9
+ v0.3.40
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 三端共享。
@@ -25,7 +25,7 @@ pnpm add @easbot/memory
25
25
 
26
26
  ## 使用示例
27
27
 
28
- ### 9 op 入口
28
+ ### 10 op 入口
29
29
 
30
30
  ```typescript
31
31
  import { executeOp } from '@easbot/memory';
@@ -91,24 +91,24 @@ await executeOp(
91
91
 
92
92
  > **2026-09-23 PR-2 同步**:graph_query v0.5 schema 已简化(与 note.graph_query 对齐):
93
93
  >
94
- > - **agent tool 主路径**只接受 `nodeId`(numeric)+ 可选 `maxEdgesPerNode`(默认 20 / 上限 100)
95
- > - `query / nodeId / type / depth / maxNodes / scope / relation / maxEdgesPerNode` 8 字段走 CLI `easbot memory graph query`
96
- > - `depth / maxNodes` service 端硬编码(depth=2 / maxNodes=100),agent tool 不暴露
97
- > - `scope / type / relation` 走 CLI(精细过滤)
94
+ > - **agent tool 主路径**只接受 `nodeId`(正整数,支持数字字符串),并可传 `maxDepth` / `maxNodes` / `maxEdgesPerNode` / `relation` / `type`
95
+ > - `query` 节点名模糊匹配仅保留给 CLI `easbot memory graph query`,agent tool 不暴露
96
+ > - `maxDepth`(默认 2)/ `maxNodes`(默认 100)/ `maxEdgesPerNode`(默认 10,上限 100)控制 BFS 预算
97
+ > - `scope` 走 CLI(精细过滤)
98
98
  > - agent tool 的 `maxEdgesPerNode` 修复:service zod schema `graphQueryParamsSchema` 在 PR-2 加上该字段声明(之前漏写导致 .strict() 拒字段 → recall/graph_query 在 agent context 失败)
99
99
 
100
100
  ```typescript
101
101
  // agent tool 主路径(v0.5+):按 numeric nodeId 查邻居
102
102
  await executeOp(
103
103
  'graph_query',
104
- { nodeId: 12, maxEdgesPerNode: 20 },
104
+ { nodeId: 12, maxDepth: 2, maxNodes: 100, maxEdgesPerNode: 10 },
105
105
  { agentId: 'agent-1', isTrustedLocal: true },
106
106
  );
107
107
 
108
108
  // CLI 路径(v0.4.1+,保留兼容):name 模糊匹配 + scope/type/relation 过滤
109
109
  await executeOp(
110
110
  'graph_query',
111
- { query: 'TS', scope: 'agent_only', type: 'class', depth: 2 },
111
+ { query: 'TS', scope: 'agent_only', type: 'class', maxDepth: 2 },
112
112
  { agentId: 'agent-1', isTrustedLocal: true },
113
113
  );
114
114
 
@@ -137,7 +137,7 @@ import { renderOperationMarkdown } from '@easbot/memory';
137
137
  const md = await renderOperationMarkdown('recall', recallResult, { toolName: 'memory_recall' });
138
138
  ```
139
139
 
140
- ## 9 op 清单
140
+ ## 10 op 清单
141
141
 
142
142
  | op | trusted local only | agentId | 用途 |
143
143
  | ------------- | --------------------- | ----------------------------- | ------------------------------------------------------------- |
@@ -202,49 +202,65 @@ import { renderOperationMarkdown } from '@easbot/memory/format/render';
202
202
 
203
203
  ### 插件(plugin / hook / tool)
204
204
 
205
- `@easbot/memory` 按 `@easbot/plugin` 契约提供可安装插件:3 个生命周期 hook 与 1 个 `memory` 工具。
205
+ `@easbot/memory` 按 `@easbot/plugin` 契约提供可安装插件:4 个生命周期 hook 与 1 个 `memory` 工具。
206
206
  实现位于 `src/plugin/`,所有符号**统一从包根入口导入**(不提供 subpath 导出)。
207
207
 
208
+ > **分发形态(2026-11-18 决策)**:memory 插件**不进宿主 `INTERNAL_PLUGINS`**,走 marketplace 安装 ——
209
+ > 4 个 hook(上下文召回 / 压缩前整理 / 工具失败兜底 / 一轮对话结束提炼)+ 1 个 `memory` 工具全量生效。
210
+ > 工具自带 `isEnabled`(`MemoryCache.exists()` —— 只看 L2 配置是否存在),宿主仅透传,
211
+ > 不再由 agent 侧模块配置决定;卸载插件即关闭记忆能力。
212
+
213
+ > **会话级事件的取舍(ADR 0159)**:memory **不**注册 `session.start` / `session.end` handler ——
214
+ > 会话记录不持久化 agent 身份(`protocolMetadata.agentId` 只存在于 LLM 层 `ToolContext`),
215
+ > 这两个事件拿不到 memory 所需的 `agentId`,注册即为悬空 handler(运行时恒定空跑)。
216
+ > 会话级的记忆固化继续由 `loop.end`(一轮对话结束)承担。
217
+
208
218
  ```typescript
209
219
  import {
210
220
  MemoryPlugin,
211
221
  MEMORY_PLUGIN_MANIFEST,
212
222
  MEMORY_HOOK_EVENTS,
223
+ MEMORY_FRAGMENT_MAX_TOKENS,
213
224
  MemoryPluginHook,
214
225
  createMemoryHookMatchers,
215
226
  MemoryTool,
216
227
  } from '@easbot/memory';
217
228
  ```
218
229
 
219
- | 导出 | 说明 |
220
- | ------------------------------------- | ------------------------------------------------------------------------------------------- |
221
- | `MemoryPlugin` / `default` / `Plugin` | 插件入口,返回 `Promise<PluginDefinition>` |
222
- | `MEMORY_PLUGIN_MANIFEST` | `plugin.json` 对应的清单(`name` / `version` / `entry` / `capabilities`) |
223
- | `MEMORY_HOOK_EVENTS` | 3 个点分事件:`context.build.before` / `session.compacting` / `tool.failure` |
224
- | `MemoryPluginHook` | `HookInfo` 形态(宿主内置注册路径) |
225
- | `createMemoryHookMatchers()` | `HookMatcher[]` 形态(插件注册路径) |
226
- | `MemoryTool` | `ToolDefinition`:`args` 为扁平 map(`operation` + 各 op 参数),`execute` 返回字符串 |
227
- | `MEMORY_TOOL_OPS` | 7 个 op:`recall` / `remember` / `update` / `forget` / `extract` / `graph_query` / `status` |
228
- | `MEMORY_TOOL_ARGS` | 扁平参数 schema(与宿主内置 memory 工具逐字段对齐) |
230
+ | 导出 | 说明 |
231
+ | ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
232
+ | `MemoryPlugin` / `default` / `Plugin` | 插件入口,返回 `Promise<PluginDefinition>` |
233
+ | `MEMORY_PLUGIN_MANIFEST` | `plugin.json` 对应的清单(`name` / `version` / `entry` / `capabilities`) |
234
+ | `MEMORY_HOOK_EVENTS` | 4 个点分事件:`context.collect` / `session.compacting` / `tool.failure` / `loop.end`(`loop.end` 承载长期记忆提炼) |
235
+ | `MEMORY_FRAGMENT_MAX_TOKENS` | memory 片段整体渲染的绝对上限(`1200` token)—— 全量渲染后交 `TruncateContent` 整体截断,超限完整内容落盘(agent 可读回) |
236
+ | `MemoryPluginHook` | `HookInfo` 形态(供偏好 builtin hook 注册路径的宿主使用) |
237
+ | `createMemoryHookMatchers()` | `HookMatcher[]` 形态(插件注册路径) |
238
+ | `MemoryTool` | `ToolDefinition`:`args` 为 **discriminated union**(按 `operation` 判别 7 个 op 分支),`execute` 返回 `ToolResult`(`{ output, title, metadata }`) |
239
+ | `MEMORY_TOOL_OPS` | 7 个 op:`recall` / `remember` / `update` / `forget` / `extract` / `graph_query` / `status` |
240
+ | `MEMORY_TOOL_ARGS` | 完整参数 schema(`z.discriminatedUnion('operation', [...])`,与宿主内置 memory 工具逐字段对齐) |
229
241
 
230
242
  #### 工具参数契约(对齐宿主内置工具)
231
243
 
232
- 插件工具的 `args` 与宿主内置 `packages/agent/src/tool/memory.ts` **逐字段一致**:
233
- `operation` 决定本次调用的 op,其余参数按 op 语义共享(扁平 map,宿主
234
- `packages/agent/src/plugin/plugin.ts` 会强制 `z.object(args)`,不支持判别联合)。
235
-
236
- | op | 生效参数 |
237
- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
238
- | `recall` | `query`(必填)/ `limit`(默认 10,上限 100)/ `category` / `minImportance` / `maxEdgesPerNode` / `includeGraph` / `includeShared` |
239
- | `remember` | `content`(必填)/ `category` / `importance`(1-10)/ `tags` |
240
- | `update` | `factId`(必填)+ `content` / `category` / `importance` / `tags`(至少一项) |
241
- | `forget` | `factId`(必填)/ `dryRun` / `force` |
242
- | `extract` | `lastN`(默认 10)/ `fromMessageId` |
243
- | `graph_query` | `query` 或 `nodeId`(二者其一必填)/ `maxDepth`(默认 2,上限 5)/ `maxNodes`(默认 100,上限 500)/ `maxEdgesPerNode` |
244
- | `status` | 无额外参数 |
245
-
246
- op 专属的必填 / 取值范围 / 互斥约束由插件侧做**二次校验**(`parseOperationParams`),
247
- 校验失败返回结构化错误而非抛异常。
244
+ 插件工具的 `args` 与宿主内置 `packages/agent/src/tool/memory.ts` **逐字段一致**,
245
+ 且**形态同为判别联合**:`z.discriminatedUnion('operation', [...])`,每个 op 一个分支,
246
+ 分支内只声明该 op 的参数(`.strict()` 拒绝未声明字段)。宿主
247
+ `packages/agent/src/plugin/plugin.ts` 对**完整 zod schema 原样下发**(不再压平成扁平
248
+ shape map),因此 per-op 的必填 / 取值范围 / 跨字段约束**由 schema 直接表达**,
249
+ 无需插件侧二次校验。
250
+
251
+ | op | 生效参数 |
252
+ | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
253
+ | `recall` | `query`(必填)/ `limit`(默认 10)/ `category` / `minImportance`(1-10,闭区间)/ `minScore`(0-1)/ `maxEdgesPerNode`(默认 10,1-100)/ `includeGraph` / `includeShared` |
254
+ | `remember` | `content`(必填)/ `category`(必填)/ `importance`(必填,1-10)/ `tags` |
255
+ | `update` | `factId`(必填)+ `content` / `category` / `importance` / `tags`(至少一项) |
256
+ | `forget` | `factId`(必填)/ `dryRun` / `force` |
257
+ | `extract` | `lastN`(默认 10)/ `fromMessageId` |
258
+ | `graph_query` | `nodeId`(必填,正整数)/ `maxDepth`(默认 2)/ `maxNodes`(默认 100)/ `maxEdgesPerNode`(默认 10)/ `relation` / `type` |
259
+ | `status` | 无额外参数 |
260
+
261
+ 工具返回值统一为 `ToolResult`(`{ output, title, metadata }`):`output` 回传模型,
262
+ `title` / `metadata` 供宿主 UI 与统计消费。`remember` 的 embedding 是可选增强:
263
+ 适配器、模型或网络失败时自动降级为 FTS-only,不阻断事实写入与召回。
248
264
 
249
265
  #### 分发产物自动生成
250
266
 
@@ -19,7 +19,7 @@ agentId via params**.
19
19
  | `update` | Update an existing fact (atomic) | no | `factId` + at least one of `content` / `category` / `importance` / `tags` |
20
20
  | `forget` | Delete one fact by `factId` | no | Single-fact delete only |
21
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 |
22
+ | `graph_query` | KG BFS neighbor expansion | no | `nodeId` from a recall hit or prior graph result; use `recall` for fact search |
23
23
  | `status` | Counts / fts / vector / schema | no | Diagnostic summary |
24
24
 
25
25
  **Workspace init is automatic**: if the memory db does not yet exist when you call any op,