@easbot/memory 0.3.23 → 0.3.25
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 +43 -30
- package/README.md +61 -37
- package/dist/chunks/chunk-4YADRVIU.mjs +1 -0
- package/dist/chunks/chunk-DW3CJUBO.cjs +1 -0
- package/dist/chunks/{chunk-PJGILQSZ.mjs → chunk-FY4ILCIM.mjs} +5 -6
- package/dist/chunks/chunk-HY2LFKG7.cjs +67 -0
- package/dist/chunks/chunk-I5YSX4DQ.mjs +64 -0
- package/dist/chunks/{chunk-EK34SXJ7.cjs → chunk-LYBUZDJK.cjs} +5 -6
- package/dist/chunks/chunk-P45OBSAC.cjs +64 -0
- package/dist/chunks/chunk-X7P7ZFZF.mjs +67 -0
- package/dist/chunks/cli-handler-ETHJPZPG.mjs +1 -0
- package/dist/chunks/cli-handler-PG4IBTY2.cjs +1 -0
- package/dist/chunks/consolidate-7GFUFPLX.cjs +2 -0
- package/dist/chunks/consolidate-BGMXJUQX.mjs +2 -0
- package/dist/chunks/doctor-C2FWFUDO.mjs +1 -0
- package/dist/chunks/doctor-SCXUJRSG.cjs +1 -0
- package/dist/chunks/extract-O4IOL6BZ.cjs +2 -0
- package/dist/chunks/extract-RBBSVK2S.mjs +2 -0
- package/dist/chunks/forget-JTACRG7Y.mjs +3 -0
- package/dist/chunks/forget-M4I6GVWI.cjs +3 -0
- package/dist/chunks/graph-AOMDJ6YA.cjs +3 -0
- package/dist/chunks/graph-VBVVRV6V.mjs +3 -0
- package/dist/chunks/init-2SBK7ZWO.mjs +1 -0
- package/dist/chunks/init-VTPJR56L.cjs +1 -0
- package/dist/chunks/{mcp-ES7O3UKN.cjs → mcp-VIOHPDO5.cjs} +1 -1
- package/dist/chunks/{mcp-OAUOA4PI.mjs → mcp-ZQCLVZIR.mjs} +1 -1
- package/dist/chunks/recall-JSTQDGGZ.cjs +2 -0
- package/dist/chunks/recall-UQSG6ECA.mjs +2 -0
- package/dist/chunks/remember-GVQJ5G7Z.mjs +2 -0
- package/dist/chunks/remember-Z4UJJN62.cjs +2 -0
- package/dist/chunks/status-DH33MQZV.cjs +1 -0
- package/dist/chunks/status-VZ5EBAOY.mjs +1 -0
- package/dist/chunks/stdio-server-JC53PUET.mjs +1 -0
- package/dist/chunks/{stdio-server-IMJF7HB6.cjs → stdio-server-OUZAN4IM.cjs} +1 -1
- package/dist/chunks/sync-6I2ZJUH6.cjs +2 -0
- package/dist/chunks/sync-UT4D32ML.mjs +2 -0
- package/dist/cli.cjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/index.cjs +4 -4
- package/dist/index.d.cts +12 -4
- package/dist/index.d.ts +12 -4
- package/dist/index.mjs +4 -4
- package/package.json +9 -9
- package/dist/chunks/chunk-2TBNGTSA.mjs +0 -65
- package/dist/chunks/chunk-3EDNN7MP.mjs +0 -1
- package/dist/chunks/chunk-5YDI4K2F.cjs +0 -65
- package/dist/chunks/chunk-K4K3YR6R.mjs +0 -66
- package/dist/chunks/chunk-MENFLGGM.cjs +0 -66
- package/dist/chunks/chunk-OU5TQHJE.cjs +0 -1
- package/dist/chunks/cli-handler-7HISH37M.cjs +0 -1
- package/dist/chunks/cli-handler-WOX5EG34.mjs +0 -1
- package/dist/chunks/consolidate-JBTOQWUX.mjs +0 -2
- package/dist/chunks/consolidate-JGLVNSDT.cjs +0 -2
- package/dist/chunks/doctor-C7RIJGYC.cjs +0 -1
- package/dist/chunks/doctor-DLQO7QMW.mjs +0 -1
- package/dist/chunks/extract-4ZGVF2DQ.cjs +0 -2
- package/dist/chunks/extract-WH4DU4NQ.mjs +0 -2
- package/dist/chunks/forget-CRDWG4XE.mjs +0 -3
- package/dist/chunks/forget-PARGCUIH.cjs +0 -3
- package/dist/chunks/graph-NJJLGDZI.cjs +0 -3
- package/dist/chunks/graph-T66JXDLU.mjs +0 -3
- package/dist/chunks/init-2ZTVBJ6N.mjs +0 -1
- package/dist/chunks/init-EEWFFF4Y.cjs +0 -1
- package/dist/chunks/recall-LCKRI4TB.cjs +0 -2
- package/dist/chunks/recall-VMW7Y55X.mjs +0 -2
- package/dist/chunks/remember-OZOQ76IA.cjs +0 -2
- package/dist/chunks/remember-ZVTM3IP4.mjs +0 -2
- package/dist/chunks/status-6R335JGR.cjs +0 -1
- package/dist/chunks/status-LHXMB3ZY.mjs +0 -1
- package/dist/chunks/stdio-server-SONZIWC4.mjs +0 -1
- package/dist/chunks/sync-7VBREDVM.cjs +0 -2
- package/dist/chunks/sync-KWHUII26.mjs +0 -2
package/README.en.md
CHANGED
|
@@ -109,17 +109,17 @@ const md = await renderOperationMarkdown('recall', recallResult, { toolName: 'me
|
|
|
109
109
|
|
|
110
110
|
## 9 op manifest
|
|
111
111
|
|
|
112
|
-
| op
|
|
113
|
-
|
|
114
|
-
| `recall`
|
|
115
|
-
| `remember`
|
|
116
|
-
| `forget`
|
|
117
|
-
| `extract`
|
|
118
|
-
| `consolidate` | ✅
|
|
119
|
-
| `graph_query` | ❌ (scope=both → ✅) | ⚠️ optional, defaults to `'default'`
|
|
120
|
-
| `status`
|
|
121
|
-
| `doctor`
|
|
122
|
-
| `init`
|
|
112
|
+
| op | trusted local only | agentId | purpose |
|
|
113
|
+
| ------------- | -------------------- | ----------------------------------------- | ------------------------------------------------------------- |
|
|
114
|
+
| `recall` | ❌ | ✅ required | Hybrid search (FTS + vector + graph) |
|
|
115
|
+
| `remember` | ❌ | ✅ required | Persist a self-memory fact |
|
|
116
|
+
| `forget` | ❌ | ✅ required | Delete by factId / category / time window (supports `dryRun`) |
|
|
117
|
+
| `extract` | ❌ | ✅ required | Aggregate facts / KG nodes for a sessionId |
|
|
118
|
+
| `consolidate` | ✅ | ✅ required | dedup → archive pipeline |
|
|
119
|
+
| `graph_query` | ❌ (scope=both → ✅) | ⚠️ optional, defaults to `'default'` | KG nodes / edges / BFS neighbors |
|
|
120
|
+
| `status` | ❌ | ⚠️ optional, defaults to global aggregate | System status snapshot |
|
|
121
|
+
| `doctor` | ✅ | ⚠️ optional, defaults to whole-DB scan | Data integrity checks (supports `repair`) |
|
|
122
|
+
| `init` | ✅ | ⚠️ optional, defaults to `'default'` | Initialize workspace (supports `force`) |
|
|
123
123
|
|
|
124
124
|
**P0-A reversal note** (since v0.4.1):
|
|
125
125
|
|
|
@@ -163,20 +163,32 @@ import type { PreCompactHook, SessionStartHook, SessionEndHook, PostToolFailureH
|
|
|
163
163
|
|
|
164
164
|
```bash
|
|
165
165
|
# Installed via package.json bin: easbot-memory
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
easbot-memory
|
|
171
|
-
easbot-memory
|
|
172
|
-
easbot-memory
|
|
173
|
-
easbot-memory
|
|
174
|
-
easbot-memory
|
|
166
|
+
# 2026-09-25: agentId is injected via ctx (no --agent flag)
|
|
167
|
+
# - agent CLI (@easbot/agent): from protocol.json
|
|
168
|
+
# - standalone CLI: from .easbot/protocol.json
|
|
169
|
+
# - fallback: 'default'
|
|
170
|
+
easbot-memory init --workspace-dir <dir>
|
|
171
|
+
easbot-memory status [--json]
|
|
172
|
+
easbot-memory doctor [--repair]
|
|
173
|
+
easbot-memory recall --query <q> [--limit <n>] [--json]
|
|
174
|
+
easbot-memory remember --content <text> --category <c> --importance <1-10>
|
|
175
|
+
easbot-memory forget [--fact-id <id>] [--dry-run]
|
|
176
|
+
easbot-memory extract --session <sessionId> [--last-n <n>]
|
|
177
|
+
easbot-memory consolidate [--window-days <n>]
|
|
178
|
+
easbot-memory graph [--query <q>] [--node-id <id>]
|
|
175
179
|
easbot-memory config [--json]
|
|
176
180
|
easbot-memory mcp
|
|
177
181
|
```
|
|
178
182
|
|
|
179
|
-
> Since v0.
|
|
183
|
+
> Since v0.5.1 (2026-09-25 feedback): every op's `agentId` flows through **ctx injection** (no `--agent` flag parsing):
|
|
184
|
+
>
|
|
185
|
+
> - agent CLI (`@easbot/agent`): bridge handler reads `metadata.agentId` from `ContextEngine.getProtocolMetadata()` → `deps.agentId`
|
|
186
|
+
> - standalone CLI (`easbot-memory`): cli.ts reads `metadata.agentId` from `.easbot/protocol.json` → `deps.agentId`
|
|
187
|
+
> - agent tool (memory MCP / agent tool): `buildMemoryCtx` reads `ctx.protocolMetadata?.agentId` → opCtx.agentId
|
|
188
|
+
> - MCP stdio-server: host agent injects `ctxConfig.agentId` at server start → ctx.agentId
|
|
189
|
+
> - all absent → CLI falls back to `'default'` (display only; does not affect service filtering)
|
|
190
|
+
>
|
|
191
|
+
> `status` always returns a **global stats view** (no per-host-agent divergence); `agent_id` is exposed via `extras['agent_id']` as a display-only environment attribute.
|
|
180
192
|
|
|
181
193
|
## Status / Doctor Unified Output Format (Decision 0073 / CLI Spec v1.4)
|
|
182
194
|
|
|
@@ -242,14 +254,14 @@ $ easbot memory doctor
|
|
|
242
254
|
|
|
243
255
|
### Key Fields
|
|
244
256
|
|
|
245
|
-
| Field
|
|
246
|
-
|
|
247
|
-
| `LLM.initialized`
|
|
248
|
-
| `LLM.capabilities`
|
|
249
|
-
| `Vector enabled`
|
|
250
|
-
| `Embedding dims`
|
|
251
|
-
| `embedding_dims_consistency` | Doctor check #9: compares meta / probe / config dimensions for consistency
|
|
252
|
-
| `factsByCategory`
|
|
257
|
+
| Field | Description |
|
|
258
|
+
| ---------------------------- | ---------------------------------------------------------------------------------------------------------- |
|
|
259
|
+
| `LLM.initialized` | Whether LLM is initialized (valid config + reachable) |
|
|
260
|
+
| `LLM.capabilities` | Three capabilities: `embedding` / `graphLlm` / `rerankLlm`, each shows model name or ✗ |
|
|
261
|
+
| `Vector enabled` | Whether vector index is enabled |
|
|
262
|
+
| `Embedding dims` | **Probed** embedding dimension (not just from config), probed at status end and written back to meta table |
|
|
263
|
+
| `embedding_dims_consistency` | Doctor check #9: compares meta / probe / config dimensions for consistency |
|
|
264
|
+
| `factsByCategory` | Memory unique: fact counts by category (shown in Counts section) |
|
|
253
265
|
|
|
254
266
|
### JSON Output (`--json`)
|
|
255
267
|
|
|
@@ -307,6 +319,7 @@ const tools = MemoryStdioServer.getToolNames();
|
|
|
307
319
|
```
|
|
308
320
|
|
|
309
321
|
**9 tool manifest** (1:1 with `OP_REGISTRY`):
|
|
322
|
+
|
|
310
323
|
- `memory_recall` / `memory_remember` / `memory_forget` / `memory_extract` / `memory_consolidate` / `memory_graph_query` / `memory_status` / `memory_doctor` / `memory_init`
|
|
311
324
|
|
|
312
325
|
### handleMemoryCli delegation
|
|
@@ -315,7 +328,7 @@ const tools = MemoryStdioServer.getToolNames();
|
|
|
315
328
|
import { handleMemoryCli, setGlobalAdapter, setInstanceAdapter } from '@easbot/memory';
|
|
316
329
|
|
|
317
330
|
// 1. Inject adapters (cli path / agent path)
|
|
318
|
-
setGlobalAdapter({ Path: {
|
|
331
|
+
setGlobalAdapter({ Path: {/* ... */} });
|
|
319
332
|
setInstanceAdapter({ directory: process.cwd(), worktree: process.cwd() });
|
|
320
333
|
|
|
321
334
|
// 2. Delegate to unified handler
|
package/README.md
CHANGED
|
@@ -86,18 +86,29 @@ await executeOp(
|
|
|
86
86
|
|
|
87
87
|
### KG scope 三档
|
|
88
88
|
|
|
89
|
+
> **2026-09-23 PR-2 同步**:graph_query v0.5 schema 已简化(与 note.graph_query 对齐):
|
|
90
|
+
>
|
|
91
|
+
> - **agent tool 主路径**只接受 `nodeId`(numeric)+ 可选 `maxEdgesPerNode`(默认 20 / 上限 100)
|
|
92
|
+
> - `query / nodeId / type / depth / maxNodes / scope / relation / maxEdgesPerNode` 8 字段走 CLI `easbot memory graph query`
|
|
93
|
+
> - `depth / maxNodes` service 端硬编码(depth=2 / maxNodes=100),agent tool 不暴露
|
|
94
|
+
> - `scope / type / relation` 走 CLI(精细过滤)
|
|
95
|
+
> - agent tool 的 `maxEdgesPerNode` 修复:service zod schema `graphQueryParamsSchema` 在 PR-2 加上该字段声明(之前漏写导致 .strict() 拒字段 → recall/graph_query 在 agent context 失败)
|
|
96
|
+
|
|
89
97
|
```typescript
|
|
90
|
-
//
|
|
91
|
-
await executeOp('graph_query', {
|
|
98
|
+
// agent tool 主路径(v0.5+):按 numeric nodeId 查邻居
|
|
99
|
+
await executeOp('graph_query', { nodeId: 12, maxEdgesPerNode: 20 }, { agentId: 'agent-1', isTrustedLocal: true });
|
|
100
|
+
|
|
101
|
+
// CLI 路径(v0.4.1+,保留兼容):name 模糊匹配 + scope/type/relation 过滤
|
|
102
|
+
await executeOp('graph_query', { query: 'TS', scope: 'agent_only', type: 'class', depth: 2 }, { agentId: 'agent-1', isTrustedLocal: true });
|
|
92
103
|
|
|
93
104
|
// 只看共享节点
|
|
94
|
-
await executeOp('graph_query', {
|
|
105
|
+
await executeOp('graph_query', { query: 'TS', scope: 'shared_only' }, { agentId: 'agent-1', isTrustedLocal: true });
|
|
95
106
|
|
|
96
107
|
// 本 Agent + 共享(trusted local only;MCP 入口会拒绝)
|
|
97
|
-
await executeOp('graph_query', {
|
|
108
|
+
await executeOp('graph_query', { query: 'TS', scope: 'both' }, { agentId: 'agent-1', isTrustedLocal: true });
|
|
98
109
|
|
|
99
110
|
// v0.4.1+:不传 agentId → fallback 'default',全局 KG 视图(trusted local only)
|
|
100
|
-
await executeOp('graph_query', {
|
|
111
|
+
await executeOp('graph_query', { query: 'TS', scope: 'both' }, { isTrustedLocal: true });
|
|
101
112
|
```
|
|
102
113
|
|
|
103
114
|
### Markdown 渲染
|
|
@@ -109,18 +120,18 @@ const md = await renderOperationMarkdown('recall', recallResult, { toolName: 'me
|
|
|
109
120
|
|
|
110
121
|
## 9 op 清单
|
|
111
122
|
|
|
112
|
-
| op
|
|
113
|
-
|
|
114
|
-
| `recall`
|
|
115
|
-
| `remember`
|
|
116
|
-
| `forget`
|
|
117
|
-
| `extract`
|
|
118
|
-
| `consolidate` | ✅
|
|
119
|
-
| `sync`
|
|
120
|
-
| `graph_query` | ❌ (scope=both 时 ✅) | ⚠️ optional,缺省 `'default'` | KG 节点 / 边 / 邻居查询
|
|
121
|
-
| `status`
|
|
122
|
-
| `doctor`
|
|
123
|
-
| `init`
|
|
123
|
+
| op | trusted local only | agentId | 用途 |
|
|
124
|
+
| ------------- | --------------------- | ----------------------------- | ------------------------------------------------------------- |
|
|
125
|
+
| `recall` | ❌ | ✅ 必填 | 混合搜索(FTS + vector + graph) |
|
|
126
|
+
| `remember` | ❌ | ✅ 必填 | 持久化一条 self-memory fact |
|
|
127
|
+
| `forget` | ❌ | ✅ 必填 | 按 factId / category / 时间窗删除(支持 `dryRun`) |
|
|
128
|
+
| `extract` | ❌ | ✅ 必填 | 从 session 抽取 facts |
|
|
129
|
+
| `consolidate` | ✅ | ✅ 必填 | 整理 / 去重 / 摘要 |
|
|
130
|
+
| `sync` | ✅ | ✅ 必填 | db → .md 兜底生成(幂等)+ active/ 过期文件归档(默认 30 天) |
|
|
131
|
+
| `graph_query` | ❌ (scope=both 时 ✅) | ⚠️ optional,缺省 `'default'` | KG 节点 / 边 / 邻居查询 |
|
|
132
|
+
| `status` | ❌ | ⚠️ optional,缺省全局聚合 | 系统状态快照 |
|
|
133
|
+
| `doctor` | ✅ | ⚠️ optional,缺省全库扫描 | 数据完整性检查(支持 `repair`) |
|
|
134
|
+
| `init` | ✅ | ⚠️ optional,缺省 `'default'` | 初始化 workspace(支持 `force`) |
|
|
124
135
|
|
|
125
136
|
**P0-A 反转说明**(v0.4.1 起):
|
|
126
137
|
|
|
@@ -162,16 +173,20 @@ import type { PreCompactHook, SessionStartHook, SessionEndHook, PostToolFailureH
|
|
|
162
173
|
|
|
163
174
|
```bash
|
|
164
175
|
# 安装后即可用(package.json bin: easbot-memory)
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
easbot-memory
|
|
170
|
-
easbot-memory
|
|
171
|
-
easbot-memory
|
|
172
|
-
easbot-memory
|
|
173
|
-
easbot-memory
|
|
174
|
-
easbot-memory
|
|
176
|
+
# 2026-09-25 老侯反馈:所有 op 的 agentId 走 ctx 上下文(不再用 --agent flag)
|
|
177
|
+
# - agent CLI(@easbot/agent):从 protocol.json 注入
|
|
178
|
+
# - standalone CLI:从 .easbot/protocol.json 注入
|
|
179
|
+
# - 都没有 → 兜底 'default'
|
|
180
|
+
easbot-memory init --workspace-dir <dir>
|
|
181
|
+
easbot-memory status [--json]
|
|
182
|
+
easbot-memory doctor [--repair]
|
|
183
|
+
easbot-memory recall --query <q> [--limit <n>] [--json]
|
|
184
|
+
easbot-memory remember --content <text> --category <c> --importance <1-10>
|
|
185
|
+
easbot-memory forget [--fact-id <id>] [--dry-run]
|
|
186
|
+
easbot-memory extract --session <sessionId> [--last-n <n>]
|
|
187
|
+
easbot-memory consolidate [--window-days <n>]
|
|
188
|
+
easbot-memory sync [--window-days <n>] [--dry-run] [--json]
|
|
189
|
+
easbot-memory graph [--query <q>] [--node-id <id>]
|
|
175
190
|
easbot-memory config [--json]
|
|
176
191
|
easbot-memory mcp
|
|
177
192
|
```
|
|
@@ -240,14 +255,14 @@ $ easbot memory doctor
|
|
|
240
255
|
|
|
241
256
|
### 关键字段说明
|
|
242
257
|
|
|
243
|
-
| 字段
|
|
244
|
-
|
|
245
|
-
| `LLM.initialized`
|
|
246
|
-
| `LLM.capabilities`
|
|
247
|
-
| `Vector enabled`
|
|
248
|
-
| `Embedding dims`
|
|
249
|
-
| `embedding_dims_consistency` | doctor 第 9 项检查:对比 meta / probe / config 三方维度是否一致
|
|
250
|
-
| `factsByCategory`
|
|
258
|
+
| 字段 | 说明 |
|
|
259
|
+
| ---------------------------- | ----------------------------------------------------------------------- |
|
|
260
|
+
| `LLM.initialized` | LLM 是否已初始化(配置有效且可达) |
|
|
261
|
+
| `LLM.capabilities` | 三大能力:`embedding` / `graphLlm` / `rerankLlm`,各显示模型名或 ✗ |
|
|
262
|
+
| `Vector enabled` | 向量索引是否启用 |
|
|
263
|
+
| `Embedding dims` | **实测** embedding 维度(非仅读 config),status 末尾探测并回填 meta 表 |
|
|
264
|
+
| `embedding_dims_consistency` | doctor 第 9 项检查:对比 meta / probe / config 三方维度是否一致 |
|
|
265
|
+
| `factsByCategory` | memory 独有:按 category 统计的 fact 数量(Counts 段展示) |
|
|
251
266
|
|
|
252
267
|
### JSON 输出(`--json`)
|
|
253
268
|
|
|
@@ -277,7 +292,15 @@ $ easbot memory status --json
|
|
|
277
292
|
|
|
278
293
|
兼容 [CLI 输出规范 v1.4](file:///e:/work/apps/eas/easbot/docs/spec/cli-output-spec.md) / [决策 0040](file:///e:/work/apps/eas/easbot/docs/decisions/0040-cli-output-unified-json.md)。
|
|
279
294
|
|
|
280
|
-
> v0.
|
|
295
|
+
> v0.5.1 起(2026-09-25 老侯反馈):所有 op 的 `agentId` 统一走 **ctx 上下文注入**(不再从 `--agent` flag 解析):
|
|
296
|
+
>
|
|
297
|
+
> - agent CLI(`@easbot/agent`):bridge handler 从 `ContextEngine.getProtocolMetadata()` 读 `metadata.agentId` → `deps.agentId`
|
|
298
|
+
> - standalone CLI(`easbot-memory`):cli.ts 从 `.easbot/protocol.json` 读 `metadata.agentId` → `deps.agentId`
|
|
299
|
+
> - agent tool(memory MCP/agent tool):`buildMemoryCtx` 从 `ctx.protocolMetadata?.agentId` 拿 → opCtx.agentId
|
|
300
|
+
> - MCP stdio-server:host agent 启动时注入 `ctxConfig.agentId` → ctx.agentId
|
|
301
|
+
> - 都没有 → CLI 兜底 `'default'`(仅作显示,不影响 service 过滤逻辑)
|
|
302
|
+
>
|
|
303
|
+
> `status` 命令永远走**全局统计视图**(不因 host agent 不同而分叉数字);agentId 仅作为 extras 环境属性 `extras['agent_id']` 显示。
|
|
281
304
|
|
|
282
305
|
### Agent 委派模式(v0.4 stage 4 T-M017a)
|
|
283
306
|
|
|
@@ -307,6 +330,7 @@ const tools = MemoryStdioServer.getToolNames();
|
|
|
307
330
|
```
|
|
308
331
|
|
|
309
332
|
**10 tool 清单**(与 `OP_REGISTRY` 一一对应):
|
|
333
|
+
|
|
310
334
|
- `memory_recall` / `memory_remember` / `memory_forget` / `memory_extract` / `memory_consolidate` / `memory_sync` / `memory_graph_query` / `memory_status` / `memory_doctor` / `memory_init`
|
|
311
335
|
|
|
312
336
|
### handleMemoryCli 委派范式
|
|
@@ -315,7 +339,7 @@ const tools = MemoryStdioServer.getToolNames();
|
|
|
315
339
|
import { handleMemoryCli, setGlobalAdapter, setInstanceAdapter } from '@easbot/memory';
|
|
316
340
|
|
|
317
341
|
// 1. 注入 adapter(cli 路径 / agent 路径)
|
|
318
|
-
setGlobalAdapter({ Path: {
|
|
342
|
+
setGlobalAdapter({ Path: {/* ... */} });
|
|
319
343
|
setInstanceAdapter({ directory: process.cwd(), worktree: process.cwd() });
|
|
320
344
|
|
|
321
345
|
// 2. 委派给统一 handler
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {f}from'./chunk-WDVDYZ25.mjs';import {Log}from'@easbot/utils';import {renderLines,printHuman,emitJsonOk,formatKnowledgeDoctor,formatKnowledgeStatus,formatKnowledgeInit,emitJsonError}from'@easbot/terminal';var b=Log.create({service:"memory-cli"}),S=[{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(p,t){let e=S.filter(s=>s.group===p);return renderLines({title:t,flat:e.map(s=>`$ easbot-memory ${s.name.padEnd(14)} ${s.description}`)})}function v(){let p=[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(p);}function j(){v(),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 C(p){try{let{bootstrapLlm:t}=await import('@easbot/llm'),{Llm:e}=await import('./llm-UHTBU2HA.mjs');await t({target:e,cwd:p,subConfigPath:".easbot/memory.json",embedding:!0,graph:!0});}catch(t){b.warn("bootstrapLlm failed; Llm-related features will be disabled",{error:t instanceof Error?t.message:String(t)});}}async function P(p,t){let[e,...s]=p,c=t?.cwd??process.cwd(),d=t?.agentId??"default";if(!e)return j(),{code:0,handled:true,command:null};await C(c);try{switch(e){case "init":{let{parseInitOptions:n,runInit:a}=await import('./init-2SBK7ZWO.mjs'),r=n(s);if(r.help)return console.log("Usage: easbot-memory init [dir] [--force] [--json]"),{code:0,handled:!0,command:e};let o=r.workspaceDir?.trim()??c,i=await a({...r,ctxWorkspaceDir:o,agentId:d});if(r.json)emitJsonOk(i,{command:e});else {let u=i;printHuman([formatKnowledgeInit({packageName:"memory",configPath:u.configPath??u.dbPath,backend:"better-sqlite3",schemaVersion:u.schemaVersion,extras:{dbPath:u.dbPath,migrationsApplied:u.migrationsApplied,tablesCreated:u.tablesCreated,durationMs:`${u.durationMs}ms`}})],{title:"init memory workspace",boxed:!0});}return {code:0,handled:!0,command:e}}case "recall":{let{parseRecallOptions:n,runRecall:a,formatRecallText:r}=await import('./recall-UQSG6ECA.mjs'),o=n(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 i=await a({...o,workspaceDir:c,agentId:d});return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:`recall (agentId=${d??"default"})`}),{code:0,handled:!0,command:e}}case "remember":{let{parseRememberOptions:n,runRemember:a,formatRememberText:r}=await import('./remember-GVQJ5G7Z.mjs'),o=n(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 i=await a({...o,workspaceDir:c,agentId:d});return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:"remember (persist fact)"}),{code:0,handled:!0,command:e}}case "forget":{let{parseForgetOptions:n,runForget:a,formatForgetText:r}=await import('./forget-JTACRG7Y.mjs'),o=n(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 i=await a({...o,workspaceDir:c,agentId:d});return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:"forget (delete facts)"}),{code:0,handled:!0,command:e}}case "extract":{let{parseExtractOptions:n,runExtract:a,formatExtractText:r}=await import('./extract-RBBSVK2S.mjs'),o=n(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 i=await a({...o,workspaceDir:c,agentId:d});return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:"extract (from session)"}),{code:0,handled:!0,command:e}}case "consolidate":{let{parseConsolidateOptions:n,runConsolidate:a,formatConsolidateText:r}=await import('./consolidate-BGMXJUQX.mjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory consolidate [--window-days <n>] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:"consolidate (pipeline)"}),{code:0,handled:!0,command:e}}case "sync":{let{parseSyncOptions:n,runSync:a,formatSyncText:r}=await import('./sync-UT4D32ML.mjs'),o=n(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 i=await a({...o,workspaceDir:c,agentId:d});return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:"sync (db \u2192 .md + archive)"}),{code:0,handled:!0,command:e}}case "graph":{let{parseGraphOptions:n,runGraph:a,formatGraphText:r}=await import('./graph-VBVVRV6V.mjs'),o=n(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 i=await a({...o,workspaceDir:c,agentId:d});return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:"graph_query"}),{code:0,handled:!0,command:e}}case "status":{let{parseStatusOptions:n,runStatus:a}=await import('./status-VZ5EBAOY.mjs'),r=n(s);if(r.help)return console.log("Usage: easbot-memory status [--json]"),{code:0,handled:!0,command:e};let o=await a({...r,workspaceDir:c,agentId:d});return r.json?emitJsonOk(o,{command:e}):printHuman([formatKnowledgeStatus(K(o))],{title:"memory status",boxed:!0}),{code:0,handled:!0,command:e}}case "doctor":{let{parseDoctorOptions:n,runDoctor:a}=await import('./doctor-C2FWFUDO.mjs'),r=n(s);if(r.help)return console.log("Usage: easbot-memory doctor [--repair] [--json]"),{code:0,handled:!0,command:e};let o=await a({...r,workspaceDir:c});return r.json?emitJsonOk(o,{command:e}):printHuman([formatKnowledgeDoctor(M(o))],{title:"memory doctor",boxed:!0}),{code:0,handled:!0,command:e}}case "config":{let{parseConfigOptions:n,runConfig:a,formatConfigText:r}=await import('./config-2SQJYVTO.mjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory config [--json]"),{code:0,handled:!0,command:e};let i=a(o);return o.json?emitJsonOk(i,{command:e}):printHuman([r(i)],{title:"memory config"}),{code:0,handled:!0,command:e}}case "mcp":{let{parseMcpOptions:n,runMcp:a}=await import('./mcp-ZQCLVZIR.mjs'),r=n(s);if(r.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(r);return r.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 console.error(`Unknown command: ${e}`),console.error("Run `easbot-memory --help` for available commands."),{code:2,handled:!1,command:null}}}catch(n){let a=n instanceof Error?n.message:String(n);b.error("memory CLI command failed",{command:e,error:a,stack:n instanceof Error?n.stack:void 0});let r=t?.cwd??f().worktree;return console.error(`[memory] ${r} :: ${e} failed: ${a}`),emitJsonError(e,a),{code:1,handled:true,command:e}}}function K(p){let t=p;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[c,d]of Object.entries(s))typeof d=="number"&&d>0&&(e[`facts/${c}`]=d);}if(t.meta&&typeof t.meta=="object")for(let[s,c]of Object.entries(t.meta))e[`meta/${s}`]=c===void 0?"\u2205":c;return Object.keys(e).length>0?e:void 0})()}}function M(p){let t=p,e=Array.isArray(t.checks)?t.checks:[],s=t.integrityStats,c=t.backendAvailable,d=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(n=>({code:typeof n.code=="string"?n.code:"",severity:n.severity??"info",name:typeof n.name=="string"?n.name:"",message:typeof n.message=="string"?n.message:"",durationMs:typeof n.durationMs=="number"?n.durationMs:void 0,details:n.details})),dbStats:d,backendAvailable:c}}export{S as a,v as b,j as c,P as d,M as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkCPRDIUQ4_cjs=require('./chunk-CPRDIUQ4.cjs'),utils=require('@easbot/utils'),terminal=require('@easbot/terminal');var b=utils.Log.create({service:"memory-cli"}),S=[{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(p,t){let e=S.filter(s=>s.group===p);return terminal.renderLines({title:t,flat:e.map(s=>`$ easbot-memory ${s.name.padEnd(14)} ${s.description}`)})}function v(){let p=[terminal.renderLines({title:"easbot-memory \xB7 Memory & Knowledge Module for EASBot",flat:["Usage: easbot-memory <command> [options]"]}),"",g("lifecycle","Commands (lifecycle):"),"",g("memory","Commands (memory):"),"",g("session","Commands (session):"),"",g("graph","Commands (graph query):"),"",g("external","External:")];terminal.printHuman(p);}function j(){v(),terminal.printHuman(["",terminal.renderLines({title:"Global flags & invocation",flat:["--cwd <dir> --config <path> --log-level <L> --print-logs --debug","Standalone CLI: easbot-memory <command>","Agent CLI: easbot memory <command>"]})]);}async function C(p){try{let{bootstrapLlm:t}=await import('@easbot/llm'),{Llm:e}=await import('./llm-7LQGYSUE.cjs');await t({target:e,cwd:p,subConfigPath:".easbot/memory.json",embedding:!0,graph:!0});}catch(t){b.warn("bootstrapLlm failed; Llm-related features will be disabled",{error:t instanceof Error?t.message:String(t)});}}async function A(p,t){let[e,...s]=p,c=t?.cwd??process.cwd(),d=t?.agentId??"default";if(!e)return j(),{code:0,handled:true,command:null};await C(c);try{switch(e){case "init":{let{parseInitOptions:n,runInit:a}=await import('./init-VTPJR56L.cjs'),r=n(s);if(r.help)return console.log("Usage: easbot-memory init [dir] [--force] [--json]"),{code:0,handled:!0,command:e};let o=r.workspaceDir?.trim()??c,i=await a({...r,ctxWorkspaceDir:o,agentId:d});if(r.json)terminal.emitJsonOk(i,{command:e});else {let u=i;terminal.printHuman([terminal.formatKnowledgeInit({packageName:"memory",configPath:u.configPath??u.dbPath,backend:"better-sqlite3",schemaVersion:u.schemaVersion,extras:{dbPath:u.dbPath,migrationsApplied:u.migrationsApplied,tablesCreated:u.tablesCreated,durationMs:`${u.durationMs}ms`}})],{title:"init memory workspace",boxed:!0});}return {code:0,handled:!0,command:e}}case "recall":{let{parseRecallOptions:n,runRecall:a,formatRecallText:r}=await import('./recall-JSTQDGGZ.cjs'),o=n(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 i=await a({...o,workspaceDir:c,agentId:d});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:`recall (agentId=${d??"default"})`}),{code:0,handled:!0,command:e}}case "remember":{let{parseRememberOptions:n,runRemember:a,formatRememberText:r}=await import('./remember-Z4UJJN62.cjs'),o=n(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 i=await a({...o,workspaceDir:c,agentId:d});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:"remember (persist fact)"}),{code:0,handled:!0,command:e}}case "forget":{let{parseForgetOptions:n,runForget:a,formatForgetText:r}=await import('./forget-M4I6GVWI.cjs'),o=n(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 i=await a({...o,workspaceDir:c,agentId:d});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:"forget (delete facts)"}),{code:0,handled:!0,command:e}}case "extract":{let{parseExtractOptions:n,runExtract:a,formatExtractText:r}=await import('./extract-O4IOL6BZ.cjs'),o=n(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 i=await a({...o,workspaceDir:c,agentId:d});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:"extract (from session)"}),{code:0,handled:!0,command:e}}case "consolidate":{let{parseConsolidateOptions:n,runConsolidate:a,formatConsolidateText:r}=await import('./consolidate-7GFUFPLX.cjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory consolidate [--window-days <n>] [--json]"),{code:0,handled:!0,command:e};let i=await a({...o,workspaceDir:c,agentId:d});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:"consolidate (pipeline)"}),{code:0,handled:!0,command:e}}case "sync":{let{parseSyncOptions:n,runSync:a,formatSyncText:r}=await import('./sync-6I2ZJUH6.cjs'),o=n(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 i=await a({...o,workspaceDir:c,agentId:d});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:"sync (db \u2192 .md + archive)"}),{code:0,handled:!0,command:e}}case "graph":{let{parseGraphOptions:n,runGraph:a,formatGraphText:r}=await import('./graph-AOMDJ6YA.cjs'),o=n(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 i=await a({...o,workspaceDir:c,agentId:d});return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:"graph_query"}),{code:0,handled:!0,command:e}}case "status":{let{parseStatusOptions:n,runStatus:a}=await import('./status-DH33MQZV.cjs'),r=n(s);if(r.help)return console.log("Usage: easbot-memory status [--json]"),{code:0,handled:!0,command:e};let o=await a({...r,workspaceDir:c,agentId:d});return r.json?terminal.emitJsonOk(o,{command:e}):terminal.printHuman([terminal.formatKnowledgeStatus(K(o))],{title:"memory status",boxed:!0}),{code:0,handled:!0,command:e}}case "doctor":{let{parseDoctorOptions:n,runDoctor:a}=await import('./doctor-SCXUJRSG.cjs'),r=n(s);if(r.help)return console.log("Usage: easbot-memory doctor [--repair] [--json]"),{code:0,handled:!0,command:e};let o=await a({...r,workspaceDir:c});return r.json?terminal.emitJsonOk(o,{command:e}):terminal.printHuman([terminal.formatKnowledgeDoctor(M(o))],{title:"memory doctor",boxed:!0}),{code:0,handled:!0,command:e}}case "config":{let{parseConfigOptions:n,runConfig:a,formatConfigText:r}=await import('./config-I2I6U4XM.cjs'),o=n(s);if(o.help)return console.log("Usage: easbot-memory config [--json]"),{code:0,handled:!0,command:e};let i=a(o);return o.json?terminal.emitJsonOk(i,{command:e}):terminal.printHuman([r(i)],{title:"memory config"}),{code:0,handled:!0,command:e}}case "mcp":{let{parseMcpOptions:n,runMcp:a}=await import('./mcp-VIOHPDO5.cjs'),r=n(s);if(r.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(r);return r.json?terminal.emitJsonOk(o,{command:e}):terminal.printHuman([`memory mcp started (tools: ${o.tools.length})`],{title:"memory mcp server"}),{code:0,handled:!0,command:e}}default:return console.error(`Unknown command: ${e}`),console.error("Run `easbot-memory --help` for available commands."),{code:2,handled:!1,command:null}}}catch(n){let a=n instanceof Error?n.message:String(n);b.error("memory CLI command failed",{command:e,error:a,stack:n instanceof Error?n.stack:void 0});let r=t?.cwd??chunkCPRDIUQ4_cjs.f().worktree;return console.error(`[memory] ${r} :: ${e} failed: ${a}`),terminal.emitJsonError(e,a),{code:1,handled:true,command:e}}}function K(p){let t=p;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[c,d]of Object.entries(s))typeof d=="number"&&d>0&&(e[`facts/${c}`]=d);}if(t.meta&&typeof t.meta=="object")for(let[s,c]of Object.entries(t.meta))e[`meta/${s}`]=c===void 0?"\u2205":c;return Object.keys(e).length>0?e:void 0})()}}function M(p){let t=p,e=Array.isArray(t.checks)?t.checks:[],s=t.integrityStats,c=t.backendAvailable,d=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(n=>({code:typeof n.code=="string"?n.code:"",severity:n.severity??"info",name:typeof n.name=="string"?n.name:"",message:typeof n.message=="string"?n.message:"",durationMs:typeof n.durationMs=="number"?n.durationMs:void 0,details:n.details})),dbStats:d,backendAvailable:c}}exports.a=S;exports.b=v;exports.c=j;exports.d=A;exports.e=M;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Filesystem}from'@easbot/utils';import {createSyncSqliteConnection}from'@easbot/database';var c=Log.create({service:"memory-schema-migrations"}),m=1,
|
|
1
|
+
import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Filesystem}from'@easbot/utils';import {createSyncSqliteConnection}from'@easbot/database';var c=Log.create({service:"memory-schema-migrations"}),m=1,f=[{id:1,description:"v1 baseline: memory_facts / memory_vectors / embedding_cache / memory_facts_fts / nodes / edges / meta\uFF08\u4E0E v0.3.x createTables \u8F93\u51FA\u5BF9\u9F50\uFF0C\u8001 db \u8DD1\u8BE5\u8FC1\u79FB\u4E0D\u7834\u574F\u73B0\u6709\u8868\uFF09",up:[`CREATE TABLE IF NOT EXISTS memory_facts (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
agent_id TEXT NOT NULL,
|
|
4
4
|
session_id TEXT,
|
|
@@ -32,12 +32,11 @@ import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Filesystem}from'@easbot/utils';
|
|
|
32
32
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
33
33
|
name TEXT NOT NULL,
|
|
34
34
|
type TEXT NOT NULL,
|
|
35
|
-
owner_agent_id TEXT,
|
|
36
35
|
properties TEXT,
|
|
37
36
|
embedding BLOB,
|
|
38
37
|
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
39
38
|
updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
40
|
-
)`,"CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name)","CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type)","CREATE INDEX IF NOT EXISTS
|
|
39
|
+
)`,"CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name)","CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type)","CREATE INDEX IF NOT EXISTS idx_nodes_embedding ON nodes(embedding) WHERE embedding IS NOT NULL","CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_name_type ON nodes(name, type)",`CREATE TABLE IF NOT EXISTS fact_nodes (
|
|
41
40
|
fact_id TEXT NOT NULL,
|
|
42
41
|
node_id INTEGER NOT NULL,
|
|
43
42
|
source TEXT NOT NULL DEFAULT 'kg_extract',
|
|
@@ -58,10 +57,10 @@ import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Filesystem}from'@easbot/utils';
|
|
|
58
57
|
)`,"CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)","CREATE INDEX IF NOT EXISTS idx_edges_relation ON edges(relation)","CREATE UNIQUE INDEX IF NOT EXISTS idx_edges_unique ON edges(source, target, relation)",`CREATE TABLE IF NOT EXISTS meta (
|
|
59
58
|
key TEXT PRIMARY KEY,
|
|
60
59
|
value TEXT
|
|
61
|
-
)`,"ALTER TABLE nodes ADD COLUMN embedding BLOB","CREATE INDEX IF NOT EXISTS idx_nodes_embedding ON nodes(embedding) WHERE embedding IS NOT NULL"]}];function
|
|
60
|
+
)`,"ALTER TABLE nodes ADD COLUMN embedding BLOB","CREATE INDEX IF NOT EXISTS idx_nodes_embedding ON nodes(embedding) WHERE embedding IS NOT NULL"]}];function g(n,e=m,r={}){n.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
62
61
|
id INTEGER PRIMARY KEY,
|
|
63
62
|
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
64
|
-
)`);let t=n.prepare("SELECT id FROM schema_migrations").all(),s=new Set(t.map(i=>i.id)),a={applied:[],pending:[],errors:[],currentVersion:t.length===0?0:Math.max(...t.map(i=>i.id)),targetVersion:e};for(let i of
|
|
63
|
+
)`);let t=n.prepare("SELECT id FROM schema_migrations").all(),s=new Set(t.map(i=>i.id)),a={applied:[],pending:[],errors:[],currentVersion:t.length===0?0:Math.max(...t.map(i=>i.id)),targetVersion:e};for(let i of f){if(i.id>e)break;if(s.has(i.id)){a.pending.push(i.id);continue}if(r.dryRun){a.applied.push(i.id);continue}try{I(n,i.up),n.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(i.id),s.add(i.id),a.applied.push(i.id),c.info("migration applied",{id:i.id,description:i.description});}catch(o){let d=o instanceof Error?o.message:String(o),T=i.up[0]??"";a.errors.push({migrationId:i.id,sql:T,error:d}),c.warn("migration step failed",{id:i.id,error:d,sqlCount:i.up.length});}}return a}function I(n,e){for(let r of e)try{n.exec(r);}catch(t){let s=t instanceof Error?t.message:String(t);if(O(s)){c.debug("migration: column already exists, skipping",{sql:r.slice(0,80)});continue}throw t}}function O(n){return /duplicate column name/i.test(n)}function u(n){try{let e=n.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(r=>r.id))}catch{return 0}}var N=Log.create({service:"memory-database"}),_=class{constructor(e){a(this,"db",null);a(this,"storagePath");a(this,"backend","better-sqlite3");a(this,"initialized",false);a(this,"initPromise",null);this.storagePath=e===":memory:"?e:Filesystem.normalize(e);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize();try{await this.initPromise,this.initialized=!0;}catch(e){try{this.db&&this.db.close();}catch{}throw this.db=null,this.initPromise=null,e}}}async doInitialize(){try{let e=this.openConnection();e.initialize(),this.db=e,this.applyPragmas(),this.runAllMigrations();}catch(e){let r=e instanceof Error?e.message:String(e);throw N.error("Database initialization failed",{error:r}),e}}openConnection(){return createSyncSqliteConnection({path:this.storagePath,backend:this.backend,walMode:true,foreignKeys:true,busyTimeoutMs:5e3})}applyPragmas(){if(this.db)try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("foreign_keys = ON");}catch(e){N.warn("Failed to apply memory PRAGMAs",{error:String(e)});}}runAllMigrations(){if(!this.db)throw new Error("Database not initialized");let e=g(this.db,m);if(e.errors.length>0){let r=e.errors.map(t=>`migration ${t.migrationId}: ${t.error}`).join("; ");throw new Error(`Some migrations failed: ${r}`)}}query(e,r){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let t=this.db.prepare(e);return r?t.all(...r):t.all()}catch(t){throw new Error(`Query failed: ${t.message}`)}}agentFilter(e){return typeof e=="string"&&e.trim().length>0?{where:"WHERE agent_id = ?",params:[e.trim()]}:{where:"",params:[]}}run(e,r){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");try{let t=this.db.prepare(e),s=r?t.run(...r):t.run();return {lastID:Number(s.lastInsertRowid),changes:s.changes}}catch(t){throw new Error(`Write failed: ${t.message}`)}}transaction(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db.transaction(e)()}prepare(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db.prepare(e)}exec(e){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");this.db.exec(e);}getDb(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return this.db}getPath(){return this.storagePath}getSchemaVersion(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");return u(this.db)}close(){if(this.db){try{this.db.close();}catch(e){N.warn("Failed to close memory database",{error:String(e)});}this.db=null,this.initialized=false,this.initPromise=null;}}healthCheck(){try{return this.db?(this.db.exec("SELECT 1"),!0):!1}catch{return false}}checkIntegrity(){if(!this.db)throw new Error("Database not initialized. Call initialize() first.");let e=p=>this.db.prepare(p).get().c,r={memory_facts:e("SELECT COUNT(*) as c FROM memory_facts"),memory_vectors:e("SELECT COUNT(*) as c FROM memory_vectors"),embedding_cache:e("SELECT COUNT(*) as c FROM embedding_cache"),memory_facts_fts:e("SELECT COUNT(*) as c FROM memory_facts_fts"),nodes:e("SELECT COUNT(*) as c FROM nodes"),edges:e("SELECT COUNT(*) as c FROM edges"),fact_nodes:e("SELECT COUNT(*) as c FROM fact_nodes"),meta:e("SELECT COUNT(*) as c FROM meta"),schema_migrations:e("SELECT COUNT(*) as c FROM schema_migrations")},t=[],s=e(`
|
|
65
64
|
SELECT COUNT(*) as c FROM fact_nodes fn
|
|
66
65
|
LEFT JOIN nodes n ON n.id = fn.node_id
|
|
67
66
|
WHERE n.id IS NULL
|
|
@@ -75,4 +74,4 @@ import {a}from'./chunk-HQBRVVXS.mjs';import {Log,Filesystem}from'@easbot/utils';
|
|
|
75
74
|
EXCEPT
|
|
76
75
|
SELECT id FROM memory_facts
|
|
77
76
|
)
|
|
78
|
-
`);d>0&&t.push({severity:"warn",message:`FTS out of sync (orphan entries): ${d}`});let T=e("SELECT COUNT(*) as c FROM (SELECT id, COUNT(*) as c FROM memory_facts GROUP BY id HAVING c > 1)");T>0&&t.push({severity:"error",message:`duplicate fact ids: ${T}`});let
|
|
77
|
+
`);d>0&&t.push({severity:"warn",message:`FTS out of sync (orphan entries): ${d}`});let T=e("SELECT COUNT(*) as c FROM (SELECT id, COUNT(*) as c FROM memory_facts GROUP BY id HAVING c > 1)");T>0&&t.push({severity:"error",message:`duplicate fact ids: ${T}`});let l=e("SELECT COUNT(*) as c FROM memory_facts WHERE content IS NULL OR content = ''");return l>0&&t.push({severity:"error",message:`memory_facts with null/empty content: ${l}`}),{issues:t,stats:r}}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,r){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,r);}};export{m as a,f as b,g as c,u as d,_ as e};
|