@easbot/memory 0.3.36 → 0.3.39
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.
- package/README.en.md +207 -49
- package/README.md +86 -18
- package/dist/chunks/{chunk-YUWHNHAY.mjs → chunk-7RA6RQGC.mjs} +1 -1
- package/dist/chunks/{chunk-FZ3RTYIJ.mjs → chunk-HTBMVZF7.mjs} +11 -11
- package/dist/chunks/{chunk-AEAMQDNV.mjs → chunk-IPUFIEKC.mjs} +6 -6
- package/dist/chunks/{chunk-QAEIHJOF.cjs → chunk-KWSPFECY.cjs} +5 -5
- package/dist/chunks/{chunk-4G4FSAFY.cjs → chunk-SAGLLJTU.cjs} +1 -1
- package/dist/chunks/{chunk-ISYAE6B7.cjs → chunk-SEKBFDEC.cjs} +12 -12
- package/dist/chunks/cli-handler-HUTXCEXM.cjs +1 -0
- package/dist/chunks/cli-handler-TUILJT7W.mjs +1 -0
- package/dist/chunks/{consolidate-OOAMW7XW.mjs → consolidate-JMXYI3NF.mjs} +1 -1
- package/dist/chunks/{consolidate-IKQVVWIQ.cjs → consolidate-TYCVXZFF.cjs} +1 -1
- package/dist/chunks/{doctor-ZGHICE2Q.mjs → doctor-3W3MVUZF.mjs} +1 -1
- package/dist/chunks/{doctor-N6HHFR6Y.cjs → doctor-GRS3CZWD.cjs} +1 -1
- package/dist/chunks/{extract-7DQ6OV34.cjs → extract-IKAJ3GHK.cjs} +1 -1
- package/dist/chunks/{extract-AJY2ETKE.mjs → extract-XT6HBENH.mjs} +1 -1
- package/dist/chunks/{forget-NIBBY6FG.mjs → forget-2OAYPXCB.mjs} +1 -1
- package/dist/chunks/{forget-4KGLTQ5Q.cjs → forget-GXJPG4P4.cjs} +1 -1
- package/dist/chunks/{graph-4K56ZAVL.mjs → graph-2AL2R3KO.mjs} +1 -1
- package/dist/chunks/{graph-OG23VZZM.cjs → graph-LJYAUA3C.cjs} +1 -1
- package/dist/chunks/{init-HWR4SD6N.mjs → init-M5CEJUEY.mjs} +1 -1
- package/dist/chunks/{init-UQTPANNI.cjs → init-OFCTBJGM.cjs} +1 -1
- package/dist/chunks/{mcp-ONIMP7FB.cjs → mcp-OKBJHIXH.cjs} +1 -1
- package/dist/chunks/{mcp-ZWZYH52C.mjs → mcp-OWOAIP2Z.mjs} +1 -1
- package/dist/chunks/{recall-KZRYTTWA.cjs → recall-K3DU2S23.cjs} +1 -1
- package/dist/chunks/{recall-BRXHJPR4.mjs → recall-ZEDO4S5I.mjs} +1 -1
- package/dist/chunks/{remember-GLOJH457.cjs → remember-FR7JL2ZC.cjs} +1 -1
- package/dist/chunks/{remember-3XSYCWKK.mjs → remember-TEAHLG4E.mjs} +1 -1
- package/dist/chunks/{status-SW5BUHJ3.mjs → status-BGRJ224S.mjs} +1 -1
- package/dist/chunks/{status-POX2GWSQ.cjs → status-KLQSENQX.cjs} +1 -1
- package/dist/chunks/stdio-server-EEWPIACW.mjs +1 -0
- package/dist/chunks/{stdio-server-W52CMVJO.cjs → stdio-server-ME6A6STR.cjs} +1 -1
- package/dist/chunks/{sync-EE4ZD3WB.mjs → sync-2D3E4DPE.mjs} +1 -1
- package/dist/chunks/{sync-I423W5G7.cjs → sync-QZCZXNNN.cjs} +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/index.cjs +38 -8
- package/dist/index.d.cts +179 -16
- package/dist/index.d.ts +179 -16
- package/dist/index.mjs +38 -8
- package/package.json +13 -11
- package/dist/assets/txt/src/plugin/tool/description.txt +0 -12
- package/dist/chunks/cli-handler-JHSDGJHK.mjs +0 -1
- package/dist/chunks/cli-handler-USK4CPAU.cjs +0 -1
- 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
|
|
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.
|
|
9
|
+
v0.3.39
|
|
10
10
|
## Features (v0.4.0)
|
|
11
11
|
|
|
12
|
-
- **
|
|
13
|
-
- **
|
|
14
|
-
- **Layered memory** — short-term / writable self-memory / long-term history; hybrid search (FTS + vector + graph).
|
|
15
|
-
- **Observability** —
|
|
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
|
-
###
|
|
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 only `nodeId` (numeric) + optional `maxEdgesPerNode` (default 20 / max 100)
|
|
95
|
+
> - The 8 fields `query / nodeId / type / depth / maxNodes / scope / relation / maxEdgesPerNode` go through the CLI `easbot memory graph query`
|
|
96
|
+
> - `depth / maxNodes` are hardcoded in the service (depth=2 / maxNodes=100) and not exposed by the agent tool
|
|
97
|
+
> - `scope / type / relation` go 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
|
-
//
|
|
101
|
+
// Agent tool main path (v0.5+): query neighbors by numeric nodeId
|
|
102
|
+
await executeOp(
|
|
103
|
+
'graph_query',
|
|
104
|
+
{ nodeId: 12, maxEdgesPerNode: 20 },
|
|
105
|
+
{ agentId: 'agent-1', isTrustedLocal: true },
|
|
106
|
+
);
|
|
107
|
+
|
|
108
|
+
// CLI path (v0.4.1+, kept for compatibility): name fuzzy match + scope/type/relation filters
|
|
94
109
|
await executeOp(
|
|
95
110
|
'graph_query',
|
|
96
|
-
{
|
|
111
|
+
{ query: 'TS', scope: 'agent_only', type: 'class', depth: 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
|
-
{
|
|
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
|
-
{
|
|
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', {
|
|
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
|
-
##
|
|
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 |
|
|
133
|
-
| `consolidate` | ✅ | ✅ required | dedup
|
|
134
|
-
| `
|
|
135
|
-
| `
|
|
136
|
-
| `
|
|
137
|
-
| `
|
|
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
|
-
|
|
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 (
|
|
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 (
|
|
201
|
+
### operations (10 op registry + executeOp)
|
|
168
202
|
|
|
169
203
|
```typescript
|
|
170
204
|
import { executeOp, OP_REGISTRY, ALL_OPS } from '@easbot/memory/operations';
|
|
@@ -176,17 +210,133 @@ import { executeOp, OP_REGISTRY, ALL_OPS } from '@easbot/memory/operations';
|
|
|
176
210
|
import { renderOperationMarkdown } from '@easbot/memory/format/render';
|
|
177
211
|
```
|
|
178
212
|
|
|
179
|
-
###
|
|
213
|
+
### plugin (plugin / hook / tool)
|
|
214
|
+
|
|
215
|
+
`@easbot/memory` ships an installable plugin following the `@easbot/plugin` contract:
|
|
216
|
+
4 lifecycle hooks and 1 `memory` tool. The implementation lives in `src/plugin/`, and
|
|
217
|
+
every symbol is **imported from the package root** (no subpath exports).
|
|
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).
|
|
180
231
|
|
|
181
232
|
```typescript
|
|
182
|
-
import
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
233
|
+
import {
|
|
234
|
+
MemoryPlugin,
|
|
235
|
+
MEMORY_PLUGIN_MANIFEST,
|
|
236
|
+
MEMORY_HOOK_EVENTS,
|
|
237
|
+
MEMORY_FRAGMENT_MAX_TOKENS,
|
|
238
|
+
MemoryPluginHook,
|
|
239
|
+
createMemoryHookMatchers,
|
|
240
|
+
MemoryTool,
|
|
241
|
+
} from '@easbot/memory';
|
|
188
242
|
```
|
|
189
243
|
|
|
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 |
|
|
255
|
+
|
|
256
|
+
#### Tool parameter contract (aligned with the host built-in tool)
|
|
257
|
+
|
|
258
|
+
The plugin tool `args` match the host built-in `packages/agent/src/tool/memory.ts`
|
|
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) / `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` | `query` (required, node name fragment) / `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.
|
|
279
|
+
|
|
280
|
+
#### Distribution artifact generation
|
|
281
|
+
|
|
282
|
+
The distribution artifacts under `plugins/memory/` (`plugin.json` / `package.json` /
|
|
283
|
+
`index.mjs`) and this plugin's entry in `plugins/.easbot-plugin/marketplace.json`
|
|
284
|
+
**MUST be generated by the script, MUST NOT be edited by hand**:
|
|
285
|
+
|
|
286
|
+
```bash
|
|
287
|
+
# Generate / refresh the distribution artifacts
|
|
288
|
+
pnpm plugin:generate
|
|
289
|
+
|
|
290
|
+
# Verify the artifacts are up to date (CI guard, exits 1 when stale)
|
|
291
|
+
pnpm plugin:check
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
Data sources and outputs of `scripts/generate-plugin-distribution.ts`:
|
|
295
|
+
|
|
296
|
+
| Input | Output |
|
|
297
|
+
| ---------------------------------------------------- | ---------------------------------------------------------- |
|
|
298
|
+
| `version` in `package.json` | version fields in `plugin.json` / `package.json` |
|
|
299
|
+
| `MEMORY_PLUGIN_MANIFEST` in `src/plugin/manifest.ts` | name / description / entry / capabilities in `plugin.json` |
|
|
300
|
+
| allow-listed exports in `src/plugin/index.ts` | re-export identifier in `index.mjs` |
|
|
301
|
+
| `hook/` and `tool/` directories under `src/plugin/` | capabilities validation (exits 1 when undeclared) |
|
|
302
|
+
|
|
303
|
+
The package version is the single source of truth: when
|
|
304
|
+
`MEMORY_PLUGIN_VERSION` in `src/plugin/manifest.ts` diverges, the script syncs it
|
|
305
|
+
to the package version (in `--check` mode it only reports the divergence).
|
|
306
|
+
The script is idempotent — nothing is written when the artifacts already match.
|
|
307
|
+
|
|
308
|
+
#### Installation and runtime loading
|
|
309
|
+
|
|
310
|
+
The distribution directory lives in the repository-root distribution area
|
|
311
|
+
`plugins/memory/` (`{plugin.json,package.json,index.mjs}`); the marketplace
|
|
312
|
+
manifest is the single repo-wide one at `plugins/.easbot-plugin/marketplace.json`.
|
|
313
|
+
`index.mjs` only re-exports the package root, therefore you MUST build
|
|
314
|
+
`@easbot/memory` before using it.
|
|
315
|
+
|
|
316
|
+
```bash
|
|
317
|
+
pnpm --filter @easbot/memory build
|
|
318
|
+
|
|
319
|
+
# Register the local marketplace (path is the repository-root distribution area)
|
|
320
|
+
easbot plugins marketplace add ./plugins
|
|
321
|
+
|
|
322
|
+
# Install the memory plugin (non-interactive requires an explicit scope)
|
|
323
|
+
easbot plugins install -m plugins -p memory --project -y --json
|
|
324
|
+
|
|
325
|
+
# Inspect runtime registration: hooks=4 / tools=1
|
|
326
|
+
easbot plugins list --json
|
|
327
|
+
easbot plugins info memory --json
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
`install` copies `memory/` into `<scope>/plugins/memory/` and writes
|
|
331
|
+
`marketplace:<marketId>|memory` into `config.plugin`; at runtime the specifier is
|
|
332
|
+
resolved to the installed `plugin.json.entry`, then imported and registered
|
|
333
|
+
(hooks + tool). `disable memory` removes the config entry so the plugin is no
|
|
334
|
+
longer loaded, `enable memory` appends it back.
|
|
335
|
+
|
|
336
|
+
> Constraints: only `.mjs` / `.js` / `.cjs` artifacts are loaded — never `.ts`
|
|
337
|
+
> sources; no network access and no cloning. `plugin.json.entry` must start with
|
|
338
|
+
> `./` and must not contain `..` segments.
|
|
339
|
+
|
|
190
340
|
## CLI / MCP dual entry (v0.4 stage 4)
|
|
191
341
|
|
|
192
342
|
### Standalone CLI (`easbot-memory`)
|
|
@@ -205,6 +355,7 @@ easbot-memory remember --content <text> --category <c> --importance <1-10>
|
|
|
205
355
|
easbot-memory forget [--fact-id <id>] [--dry-run]
|
|
206
356
|
easbot-memory extract --session <sessionId> [--last-n <n>]
|
|
207
357
|
easbot-memory consolidate [--window-days <n>]
|
|
358
|
+
easbot-memory sync [--window-days <n>] [--dry-run] [--json]
|
|
208
359
|
easbot-memory graph [--query <q>] [--node-id <id>]
|
|
209
360
|
easbot-memory config [--json]
|
|
210
361
|
easbot-memory mcp
|
|
@@ -335,22 +486,22 @@ easbot memory mcp # starts MCP stdio server
|
|
|
335
486
|
```typescript
|
|
336
487
|
import { MemoryStdioServer } from '@easbot/memory';
|
|
337
488
|
|
|
338
|
-
// Start
|
|
339
|
-
// v0.4.0: start signature simplified — no `
|
|
489
|
+
// Start the 10-tool MCP stdio server (callable by Cline / Claude Code / Continue)
|
|
490
|
+
// v0.4.0: start signature simplified — no `memorySystem` param needed (handlers dispatch via executeOp)
|
|
340
491
|
await MemoryStdioServer.start({
|
|
341
492
|
name: 'easbot-memory',
|
|
342
493
|
version: '0.4.0',
|
|
343
494
|
description: 'EASBot memory MCP server',
|
|
344
495
|
});
|
|
345
496
|
|
|
346
|
-
// List
|
|
497
|
+
// List the 10 tool names (ADR 0069 +1 sync)
|
|
347
498
|
const tools = MemoryStdioServer.getToolNames();
|
|
348
|
-
// ['memory_recall', 'memory_remember', 'memory_forget',
|
|
499
|
+
// ['memory_recall', 'memory_remember', 'memory_forget', 'memory_extract', 'memory_consolidate', 'memory_sync', 'memory_graph_query', 'memory_status', 'memory_doctor', 'memory_init']
|
|
349
500
|
```
|
|
350
501
|
|
|
351
|
-
**
|
|
502
|
+
**10 tool manifest** (1:1 with `OP_REGISTRY`):
|
|
352
503
|
|
|
353
|
-
- `memory_recall` / `memory_remember` / `memory_forget` / `memory_extract` / `memory_consolidate` / `memory_graph_query` / `memory_status` / `memory_doctor` / `memory_init`
|
|
504
|
+
- `memory_recall` / `memory_remember` / `memory_forget` / `memory_extract` / `memory_consolidate` / `memory_sync` / `memory_graph_query` / `memory_status` / `memory_doctor` / `memory_init`
|
|
354
505
|
|
|
355
506
|
### handleMemoryCli delegation
|
|
356
507
|
|
|
@@ -378,16 +529,17 @@ After `remember` commits the db transaction, it **best-effort** renders the fact
|
|
|
378
529
|
- Future integration: `note` tool may watch memory .md changes for cross-reference updates
|
|
379
530
|
- Resilience: file IO failure **never blocks** db writes (consistent with v0.3)
|
|
380
531
|
|
|
381
|
-
### Path schema
|
|
532
|
+
### Path schema (v0.5.1+ feedback fix)
|
|
382
533
|
|
|
383
534
|
```
|
|
384
|
-
{workspaceDir}/.easbot/
|
|
535
|
+
{workspaceDir}/.easbot/memory/active/{category}/{YYYY-MM-DD}.md
|
|
385
536
|
```
|
|
386
537
|
|
|
387
538
|
- One directory per **category** (`task_context` / `workflow` / `user_preference` / ...)
|
|
388
|
-
- One
|
|
389
|
-
- File name = `
|
|
539
|
+
- One file per **createdAt local date** (one file per day, append mode, shared by multiple facts)
|
|
540
|
+
- File name = `{YYYY-MM-DD}.md` (no longer contains fact.id)
|
|
390
541
|
- `memory_facts.file_path` stores a **workspaceDir-relative POSIX path**
|
|
542
|
+
- Archive path (ADR 0069 sync): `{workspaceDir}/.easbot/memory/archive/{YYYY-MM}/{category}/{YYYY-MM-DD}.md` (flat structure)
|
|
391
543
|
|
|
392
544
|
### Markdown template
|
|
393
545
|
|
|
@@ -445,16 +597,16 @@ Default storage: `$XDG_DATA_HOME/easbot/memory.db`
|
|
|
445
597
|
|
|
446
598
|
## Decisions and migration
|
|
447
599
|
|
|
600
|
+
- 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`
|
|
448
601
|
- 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`
|
|
449
602
|
- ADR 0060 (v0.5+ fact → .md sync restoration): `docs/decisions/0060-memory-fact-file-sync-restore.md`
|
|
450
|
-
- ADR 0055 / 0056 / 0057 (v0.4 decisions): `docs/decisions/00NN-*.md`
|
|
451
|
-
-
|
|
452
|
-
- Migration script: `pnpm migrate:v04` (BC-01 ~ BC-12 dry-run + apply)
|
|
603
|
+
- ADR 0055 / 0056 / 0057 (v0.4 decisions): `.easbot/protocol.json` and `docs/decisions/00NN-*.md`
|
|
604
|
+
- Migration scripts: `scripts/migrate/{scan,apply,review}.ts` + `scripts/db-backup.ts` (v0.3 → v0.4 `owner_agent_id` column + default scope = agent_only)
|
|
453
605
|
- CI guards (v0.4 stage 5 three-package unified backend support):
|
|
454
606
|
- `scripts/check-database-facade.sh` (forbid directly requiring `better-sqlite3` / `node:sqlite` / `createRequire`)
|
|
455
607
|
- `scripts/check-mcp-facade.sh` (forbid directly importing `@modelcontextprotocol/sdk`)
|
|
456
608
|
- `scripts/check-terminal-facade.sh` (CLI output goes through `@easbot/terminal` + `COMMANDS_HELP` single source of truth)
|
|
457
|
-
- `scripts/check-cmd-i18n-coverage.sh` (zh-CN /
|
|
609
|
+
- `scripts/check-cmd-i18n-coverage.sh` (zh-CN / en-US dual-locale consistency + switch-case routing validation)
|
|
458
610
|
- L-M13 / L-M14 / L-M15 lessons: `.easbot/knowledge/tasks/memory-v04-refactor/findings.md`
|
|
459
611
|
|
|
460
612
|
## Development
|
|
@@ -474,6 +626,12 @@ pnpm type-check
|
|
|
474
626
|
|
|
475
627
|
# Lint (biome 2.x)
|
|
476
628
|
pnpm biome-lint
|
|
629
|
+
|
|
630
|
+
# Generate the plugin distribution artifacts (plugins/memory + marketplace manifest)
|
|
631
|
+
pnpm plugin:generate
|
|
632
|
+
|
|
633
|
+
# Verify the plugin distribution artifacts are up to date
|
|
634
|
+
pnpm plugin:check
|
|
477
635
|
```
|
|
478
636
|
|
|
479
637
|
## License
|
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ EASBOT 生态系统的长期记忆管理库(v0.4.0)。提供分层记忆、K
|
|
|
6
6
|
|
|
7
7
|
## 版本
|
|
8
8
|
|
|
9
|
-
v0.3.
|
|
9
|
+
v0.3.39
|
|
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
|
-
###
|
|
28
|
+
### 10 op 入口
|
|
29
29
|
|
|
30
30
|
```typescript
|
|
31
31
|
import { executeOp } from '@easbot/memory';
|
|
@@ -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
|
-
##
|
|
140
|
+
## 10 op 清单
|
|
141
141
|
|
|
142
142
|
| op | trusted local only | agentId | 用途 |
|
|
143
143
|
| ------------- | --------------------- | ----------------------------- | ------------------------------------------------------------- |
|
|
@@ -202,43 +202,105 @@ import { renderOperationMarkdown } from '@easbot/memory/format/render';
|
|
|
202
202
|
|
|
203
203
|
### 插件(plugin / hook / tool)
|
|
204
204
|
|
|
205
|
-
`@easbot/memory` 按 `@easbot/plugin` 契约提供可安装插件:
|
|
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` |
|
|
224
|
-
| `
|
|
225
|
-
| `
|
|
226
|
-
| `
|
|
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 工具逐字段对齐) |
|
|
241
|
+
|
|
242
|
+
#### 工具参数契约(对齐宿主内置工具)
|
|
243
|
+
|
|
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,闭区间)/ `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` | `query`(必填,节点名片段)/ `maxDepth`(默认 2)/ `maxNodes`(默认 100)/ `maxEdgesPerNode`(默认 10)/ `relation` / `type` |
|
|
259
|
+
| `status` | 无额外参数 |
|
|
260
|
+
|
|
261
|
+
工具返回值统一为 `ToolResult`(`{ output, title, metadata }`):`output` 回传模型,
|
|
262
|
+
`title` / `metadata` 供宿主 UI 与统计消费。
|
|
263
|
+
|
|
264
|
+
#### 分发产物自动生成
|
|
265
|
+
|
|
266
|
+
`plugins/memory/` 下的分发产物(`plugin.json` / `package.json` / `index.mjs`)与
|
|
267
|
+
`plugins/.easbot-plugin/marketplace.json` 中的本插件条目 **MUST 由脚本生成,MUST NOT 手改**:
|
|
268
|
+
|
|
269
|
+
```bash
|
|
270
|
+
# 生成 / 更新分发产物
|
|
271
|
+
pnpm plugin:generate
|
|
272
|
+
|
|
273
|
+
# 只校验产物是否最新(CI 用,过期则 exit 1)
|
|
274
|
+
pnpm plugin:check
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
脚本 `scripts/generate-plugin-distribution.ts` 的数据来源与产物:
|
|
278
|
+
|
|
279
|
+
| 输入 | 产物 |
|
|
280
|
+
| ---------------------------------------------------- | ---------------------------------------------------------- |
|
|
281
|
+
| `package.json` 的 `version` | `plugin.json` / `package.json` 的版本 |
|
|
282
|
+
| `src/plugin/manifest.ts` 的 `MEMORY_PLUGIN_MANIFEST` | `plugin.json` 的 name / description / entry / capabilities |
|
|
283
|
+
| `src/plugin/index.ts` 的白名单导出 | `index.mjs` 的 re-export 标识符 |
|
|
284
|
+
| `src/plugin/` 下的 `hook/` `tool/` 目录 | capabilities 能力校验(缺声明即报错退出) |
|
|
285
|
+
|
|
286
|
+
版本真值源是 `package.json`;`src/plugin/manifest.ts` 的 `MEMORY_PLUGIN_VERSION`
|
|
287
|
+
与之不一致时脚本会自动同步(`--check` 模式只报错不改文件)。
|
|
288
|
+
脚本幂等:产物内容与磁盘一致时不写盘。
|
|
227
289
|
|
|
228
290
|
#### 安装与运行时加载
|
|
229
291
|
|
|
230
|
-
|
|
231
|
-
`
|
|
232
|
-
|
|
292
|
+
分发目录位于仓根统一分发区 `plugins/memory/`(`{plugin.json,package.json,index.mjs}`),
|
|
293
|
+
marketplace 清单为仓内唯一一份 `plugins/.easbot-plugin/marketplace.json`。
|
|
294
|
+
`index.mjs` 只做包根 re-export,因此使用前 MUST 先构建 `@easbot/memory`。
|
|
233
295
|
|
|
234
296
|
```bash
|
|
235
297
|
pnpm --filter @easbot/memory build
|
|
236
298
|
|
|
237
|
-
# 注册本地 marketplace
|
|
238
|
-
easbot plugins marketplace add ./
|
|
299
|
+
# 注册本地 marketplace(路径为仓根统一分发区)
|
|
300
|
+
easbot plugins marketplace add ./plugins
|
|
239
301
|
|
|
240
302
|
# 安装 memory 插件(非交互必须显式给出 scope)
|
|
241
|
-
easbot plugins install -m
|
|
303
|
+
easbot plugins install -m plugins -p memory --project -y --json
|
|
242
304
|
|
|
243
305
|
# 查看运行时注册结果:hooks=4 / tools=1
|
|
244
306
|
easbot plugins list --json
|
|
@@ -542,6 +604,12 @@ pnpm type-check
|
|
|
542
604
|
|
|
543
605
|
# lint(biome 2.x)
|
|
544
606
|
pnpm biome-lint
|
|
607
|
+
|
|
608
|
+
# 生成插件分发产物(plugins/memory + marketplace 清单)
|
|
609
|
+
pnpm plugin:generate
|
|
610
|
+
|
|
611
|
+
# 校验插件分发产物是否最新
|
|
612
|
+
pnpm plugin:check
|
|
545
613
|
```
|
|
546
614
|
|
|
547
615
|
## 许可证
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {f}from'./chunk-HX3TV7FD.mjs';import {Log,errorMeta}from'@easbot/utils';import {renderLines,printHuman,emitJsonError,emitJsonOk,formatKnowledgeDoctor,formatKnowledgeStatus,formatKnowledgeInit}from'@easbot/terminal';var w=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 renderLines({title:t,flat:e.map(s=>`$ easbot-memory ${s.name.padEnd(14)} ${s.description}`)})}function j(){let l=[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:")];printHuman(l);}function C(){j(),printHuman(["",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-BRSMYENV.mjs'),{MemoryCache:t}=await import('./cache-U5YYUDWO.mjs'),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:errorMeta(l)});}}async function U(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-HWR4SD6N.mjs'),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)emitJsonOk(o,{command:e});else {let r=o;printHuman([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-BRXHJPR4.mjs'),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?emitJsonOk(r,{command:e}):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-3XSYCWKK.mjs'),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?emitJsonOk(r,{command:e}):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-NIBBY6FG.mjs'),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?emitJsonOk(r,{command:e}):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-AJY2ETKE.mjs'),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?emitJsonOk(r,{command:e}):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-OOAMW7XW.mjs'),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?emitJsonOk(r,{command:e}):printHuman([n(r)],{title:"consolidate (pipeline)"}),{code:0,handled:!0,command:e}}case "sync":{let{parseSyncOptions:i,runSync:a,formatSyncText:n}=await import('./sync-EE4ZD3WB.mjs'),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?emitJsonOk(r,{command:e}):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-4K56ZAVL.mjs'),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?emitJsonOk(r,{command:e}):printHuman([n(r)],{title:"graph_query"}),{code:0,handled:!0,command:e}}case "status":{let{parseStatusOptions:i,runStatus:a}=await import('./status-SW5BUHJ3.mjs'),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?emitJsonOk(o,{command:e}):printHuman([formatKnowledgeStatus(K(o))],{title:"memory status",boxed:!0}),{code:0,handled:!0,command:e}}case "doctor":{let{parseDoctorOptions:i,runDoctor:a}=await import('./doctor-ZGHICE2Q.mjs'),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?emitJsonOk(o,{command:e}):printHuman([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-5P7O45FH.mjs'),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?emitJsonOk(r,{command:e}):printHuman([n(r)],{title:"memory config"}),{code:0,handled:!0,command:e}}case "mcp":{let{parseMcpOptions:i,runMcp:a}=await import('./mcp-ZWZYH52C.mjs'),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?emitJsonOk(o,{command:e}):printHuman([`memory mcp started (tools: ${o.tools.length})`],{title:"memory mcp server"}),{code:0,handled:!0,command:e}}default:return m?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=errorMeta(i);w.error("memory CLI command failed",{command:e,error:a});let n=t?.cwd??f().worktree;return m?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}}export{v as a,j as b,C as c,U as d,R as e};
|
|
1
|
+
import {f}from'./chunk-HX3TV7FD.mjs';import {Log,errorMeta}from'@easbot/utils';import {renderLines,printHuman,emitJsonError,emitJsonOk,formatKnowledgeDoctor,formatKnowledgeStatus,formatKnowledgeInit}from'@easbot/terminal';var w=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 renderLines({title:t,flat:e.map(s=>`$ easbot-memory ${s.name.padEnd(14)} ${s.description}`)})}function j(){let l=[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:")];printHuman(l);}function C(){j(),printHuman(["",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-BRSMYENV.mjs'),{MemoryCache:t}=await import('./cache-U5YYUDWO.mjs'),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:errorMeta(l)});}}async function U(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-M5CEJUEY.mjs'),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)emitJsonOk(o,{command:e});else {let r=o;printHuman([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-ZEDO4S5I.mjs'),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?emitJsonOk(r,{command:e}):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-TEAHLG4E.mjs'),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?emitJsonOk(r,{command:e}):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-2OAYPXCB.mjs'),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?emitJsonOk(r,{command:e}):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-XT6HBENH.mjs'),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?emitJsonOk(r,{command:e}):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-JMXYI3NF.mjs'),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?emitJsonOk(r,{command:e}):printHuman([n(r)],{title:"consolidate (pipeline)"}),{code:0,handled:!0,command:e}}case "sync":{let{parseSyncOptions:i,runSync:a,formatSyncText:n}=await import('./sync-2D3E4DPE.mjs'),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?emitJsonOk(r,{command:e}):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-2AL2R3KO.mjs'),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?emitJsonOk(r,{command:e}):printHuman([n(r)],{title:"graph_query"}),{code:0,handled:!0,command:e}}case "status":{let{parseStatusOptions:i,runStatus:a}=await import('./status-BGRJ224S.mjs'),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?emitJsonOk(o,{command:e}):printHuman([formatKnowledgeStatus(K(o))],{title:"memory status",boxed:!0}),{code:0,handled:!0,command:e}}case "doctor":{let{parseDoctorOptions:i,runDoctor:a}=await import('./doctor-3W3MVUZF.mjs'),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?emitJsonOk(o,{command:e}):printHuman([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-5P7O45FH.mjs'),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?emitJsonOk(r,{command:e}):printHuman([n(r)],{title:"memory config"}),{code:0,handled:!0,command:e}}case "mcp":{let{parseMcpOptions:i,runMcp:a}=await import('./mcp-OWOAIP2Z.mjs'),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?emitJsonOk(o,{command:e}):printHuman([`memory mcp started (tools: ${o.tools.length})`],{title:"memory mcp server"}),{code:0,handled:!0,command:e}}default:return m?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=errorMeta(i);w.error("memory CLI command failed",{command:e,error:a});let n=t?.cwd??f().worktree;return m?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}}export{v as a,j as b,C as c,U as d,R as e};
|