memory-forge 0.1.8 → 0.2.0

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.md CHANGED
@@ -1,93 +1,76 @@
1
1
  # MemoryForge
2
2
 
3
- > AI Agent 持久记忆引擎。8 MCP 工具 + 5 个自动化引擎。Free 层本地运行,Pro Shelby 去中心化云同步。
3
+ > Persistent memory engine for AI agents. 8 MCP tools + 5 auto-engines. Free tier runs locally, Pro tier adds Shelby decentralized cloud sync.
4
4
 
5
- ## 安装
5
+ ## Install
6
6
 
7
7
  ```bash
8
8
  npx memory-forge setup
9
9
  ```
10
10
 
11
- 自动配置 Claude Code hooksSessionStart / Stop / PreCompact),导入已有规则为记忆。
11
+ Auto-configures Claude Code hooks (SessionStart / Stop / PreCompact) and imports existing rules as memories.
12
12
 
13
- Free 层零依赖外部服务。Pro 层需 `SHELBY_API_KEY` 启用 Shelby 云同步。
13
+ Free tier has no external service dependencies. Pro tier requires a `SHELBY_API_KEY` for Shelby cloud sync.
14
14
 
15
- ## 核心能力
15
+ ## Core Capabilities
16
16
 
17
- **8 MCP 工具(Agent 直接调用):**
17
+ **8 MCP Tools (invoked by agent directly):**
18
18
 
19
- | 工具 | 说明 |
19
+ | Tool | Description |
20
20
  |---|---|
21
- | `memory_store` | 存储记忆,自动向量化 + 命名 + 去重合并 |
22
- | `memory_search` | 语义检索(向量 + 关键词双模式) |
23
- | `memory_recall` | ID 精确获取 |
24
- | `memory_list` | 列出记忆,支持分类 / 标签过滤 |
25
- | `memory_forget` | 删除记忆(本地 + Shelby 同步) |
26
- | `memory_context` | 加载当前会话上下文 |
27
- | `memory_export` | 导出 JSON Markdown |
28
- | `memory_share` | 打包记忆供队友导入 |
29
-
30
- **5 个自动化引擎(用户无感知):**
31
-
32
- | 引擎 | 说明 |
21
+ | `memory_store` | Store memories with auto-embedding, naming, and dedup merge |
22
+ | `memory_search` | Semantic search (vector + keyword dual-mode) |
23
+ | `memory_recall` | Exact recall by memory ID |
24
+ | `memory_list` | List memories with category/tag filtering |
25
+ | `memory_forget` | Delete a memory (local + Shelby tombstone) |
26
+ | `memory_context` | Load current session context |
27
+ | `memory_export` | Export as JSON or Markdown |
28
+ | `memory_share` | Package a memory for teammate import |
29
+
30
+ **5 Auto-Engines (zero user awareness):**
31
+
32
+ | Engine | Description |
33
33
  |---|---|
34
- | autoName | 从内容自动提取记忆名称 |
35
- | autoMerge | 检测 >80% 重叠自动合并 |
36
- | autoPriority | 基于访问频率 + 时效计算优先级(Ebbinghaus 遗忘曲线) |
37
- | autoDecay | 90 天未访问自动归档 |
38
- | autoCapture | 会话结束自动更新优先级 + 清理过期;PreCompact 提醒 Agent 保存关键信息 |
34
+ | autoName | Extract name from content automatically |
35
+ | autoMerge | Detect >80% overlap and merge duplicates |
36
+ | autoPriority | Priority scoring via access frequency + recency (Ebbinghaus curve) |
37
+ | autoDecay | Auto-archive at 90 days of inactivity |
38
+ | autoCapture | Session-end priority recalc + PreCompact save reminders |
39
39
 
40
- ## 定价
40
+ ## Pricing
41
41
 
42
- | 方案 | 说明 |
42
+ | Tier | Description |
43
43
  |---|---|
44
- | **Free** | 8 工具,本地存储,无限制记忆 |
45
- | **Pro** | + Shelby 去中心化云同步,多设备 |
44
+ | **Free** | 8 tools, local storage, unlimited memories |
45
+ | **Pro** | + Shelby decentralized cloud sync, cross-device |
46
46
 
47
- Pro 当前在测试网阶段。
47
+ Pro is currently on Shelbynet testnet.
48
48
 
49
- ## 技术栈
49
+ ## Tech Stack
50
50
 
51
- - **MCP 协议**: `@modelcontextprotocol/sdk` (stdio transport)
52
- - **嵌入模型**: Transformers.js / Xenova all-MiniLM-L6-v223MB,本地运行,失败自动降级关键词搜索)
53
- - **云存储 (Pro)**: `@shelby-protocol/sdk` (Shelbynet / Aptos)
54
- - **运行时**: Node.js 18+, TypeScript
51
+ - **MCP Protocol**: `@modelcontextprotocol/sdk` (stdio transport)
52
+ - **Embeddings**: Transformers.js / Xenova all-MiniLM-L6-v2 (23MB, local, auto-fallback to keyword)
53
+ - **Cloud (Pro)**: `@shelby-protocol/sdk` (Shelbynet / Aptos)
54
+ - **Runtime**: Node.js 18+, TypeScript
55
55
 
56
- ## 项目结构
56
+ ## Docs
57
57
 
58
- ```
59
- agentvault/
60
- ├── README.md
61
- ├── package.json
62
- ├── server.json # MCP Registry manifest
63
- ├── Dockerfile
64
- ├── smithery.yaml
65
- ├── tsconfig.json
66
- └── src/
67
- ├── index.ts # MCP Server 入口 + CLI 路由
68
- ├── store.ts # MemoryStore: LRU 缓存 + 向量/关键词搜索
69
- ├── embedding.ts # Transformers.js 嵌入引擎
70
- ├── setup.ts # 一键安装流程
71
- ├── pro.ts # Pro 激活 + Shelby 云同步
72
- ├── auto/
73
- │ └── index.ts # 5 个自动化引擎
74
- ├── storage/
75
- │ ├── local.ts # 本地 Markdown 存储
76
- │ └── shelby.ts # Shelby 云存储
77
- ├── hooks/
78
- │ └── install.ts # Claude Code hooks 配置
79
- └── migrate/
80
- └── import.ts # 规则导入 + 去重
81
- ```
58
+ | Document | Content |
59
+ |---|---|
60
+ | [TECHNICAL.md](TECHNICAL.md) | API reference, data model, architecture, security |
61
+ | [TUTORIAL.md](TUTORIAL.md) | Install guide, daily use, Pro setup, troubleshooting |
62
+ | [SPEC.md](SPEC.md) | Product specification and roadmap |
63
+ | [ARCHITECTURE.md](ARCHITECTURE.md) | System architecture and data flow |
64
+ | [MARKET.md](MARKET.md) | Competitive analysis |
82
65
 
83
- ## 安全
66
+ ## Security
84
67
 
85
- - Free 层全本地,零网络请求(除首次模型下载 23MB
86
- - Pro 层记忆上传至 Shelby 链上存储,每条有 Aptos 交易证明
87
- - API key 通过环境变量注入,不存储密钥明文
88
- - 支持 GDPR 被遗忘权(`memory_forget` 删除本地 + 链上 tombstone
68
+ - Free tier is fully local — zero network requests (except one-time 23MB model download)
69
+ - Pro tier uploads to Shelby blockchain storage with Aptos transaction proofs
70
+ - API key via environment variable; secrets never stored in plaintext
71
+ - GDPR right-to-erasure via `memory_forget` (local + on-chain tombstone)
89
72
 
90
- ## 测试
73
+ ## Tests
91
74
 
92
75
  ```bash
93
76
  npm test # 48 tests, 100% pass
package/TECHNICAL.md ADDED
@@ -0,0 +1,527 @@
1
+ # MemoryForge — Technical Documentation
2
+
3
+ > Version 0.1.9 | 8 MCP Tools + 5 Auto-Engines | Free (local) + Pro (Shelby cloud)
4
+
5
+ ## Table of Contents
6
+
7
+ 1. [System Architecture](#system-architecture)
8
+ 2. [Data Model](#data-model)
9
+ 3. [MCP Tool API Reference](#mcp-tool-api-reference)
10
+ 4. [Auto-Engines](#auto-engines)
11
+ 5. [Hook System](#hook-system)
12
+ 6. [Storage Layer](#storage-layer)
13
+ 7. [Embedding Engine](#embedding-engine)
14
+ 8. [Security Model](#security-model)
15
+ 9. [Pro Tier (Shelby Cloud)](#pro-tier-shelby-cloud)
16
+ 10. [Error Handling & Degradation](#error-handling--degradation)
17
+
18
+ ---
19
+
20
+ ## System Architecture
21
+
22
+ ```
23
+ ┌─────────────────────────────────────┐
24
+ │ AI Agent (Claude Code / Cursor) │ MCP stdio protocol
25
+ ├─────────────────────────────────────┤
26
+ │ CLI Router (index.ts) │
27
+ │ setup / pro / hook / MCP Server │
28
+ ├─────────────────────────────────────┤
29
+ │ 8 MCP Tools │
30
+ │ store / search / recall / list │
31
+ │ forget / context / export / share │
32
+ ├──────────────┬──────────────────────┤
33
+ │ Free Tier │ Pro Tier │
34
+ │ MemoryStore │ ShelbyNodeClient │
35
+ │ local .md │ upload/download/list │
36
+ ├──────────────┴──────────────────────┤
37
+ │ 5 Auto-Engines │
38
+ │ name → merge → priority → decay │
39
+ │ → contextSummary │
40
+ ├─────────────────────────────────────┤
41
+ │ Embedding Engine │
42
+ │ Transformers.js / MiniLM-L6-v2 │
43
+ │ 384-dim vectors, cosine similarity │
44
+ │ fallback: keyword matching │
45
+ └─────────────────────────────────────┘
46
+ ```
47
+
48
+ ### Source File Structure
49
+
50
+ ```
51
+ agentvault/src/
52
+ ├── index.ts # Entry: CLI routing + MCP Server
53
+ ├── store.ts # MemoryStore: in-memory index + search
54
+ ├── embedding.ts # Transformers.js lazy-load engine
55
+ ├── setup.ts # One-command install flow
56
+ ├── pro.ts # Pro activation + bidirectional sync
57
+ ├── auto/index.ts # 5 auto-engines
58
+ ├── storage/
59
+ │ ├── local.ts # Markdown file read/write
60
+ │ └── shelby.ts # Shelby cloud API wrapper
61
+ ├── hooks/install.ts # Claude Code hooks configuration
62
+ └── migrate/import.ts # Rule import + dedup
63
+ ```
64
+
65
+ ---
66
+
67
+ ## Data Model
68
+
69
+ ### Memory Interface
70
+
71
+ ```typescript
72
+ interface Memory {
73
+ id: string; // UUID v4
74
+ name: string; // Human-readable name (autoName, max 40 chars)
75
+ content: string; // Raw content
76
+ category: string; // user-preference | project-context | decision-log | code-pattern
77
+ tags: string[]; // Tag list
78
+ priority: number; // 1–10, dynamically adjusted by autoPriority
79
+ vector: number[]; // 384-dim embedding vector
80
+ created_at: string; // ISO-8601 creation timestamp
81
+ access_count: number; // Touch count
82
+ last_accessed: string | null; // Last access timestamp
83
+ }
84
+ ```
85
+
86
+ ### Local Storage Format
87
+
88
+ Path: `~/.memory-forge/memories/{id}.md`
89
+
90
+ ```markdown
91
+ # Memory Name
92
+ > category: user-preference
93
+ > tags: coding-style, javascript
94
+ > priority: 8
95
+ > created: 2026-06-26T10:00:00.000Z
96
+ > access_count: 5
97
+ > last_accessed: 2026-06-26T12:00:00.000Z
98
+
99
+ User prefers camelCase naming, single quotes, and 2-space indent.
100
+ ```
101
+
102
+ ### MemoryStore Index
103
+
104
+ - `Map<string, Memory>` primary store
105
+ - `Map<string, Float32Array>` vector cache
106
+ - LRU eviction: 5,000 entry cap, evicts lowest `access_count × priority`
107
+ - Dedup: Jaccard similarity > 0.8 triggers auto-merge
108
+
109
+ ---
110
+
111
+ ## MCP Tool API Reference
112
+
113
+ All tools are invoked via the MCP stdio protocol. The agent receives them automatically — no manual invocation required.
114
+
115
+ ### memory_store
116
+
117
+ Store a memory. Auto-embeds, names, and dedup-merges.
118
+
119
+ ```typescript
120
+ // Input
121
+ {
122
+ content: string; // required, min 1 char
123
+ category?: string; // "general" | "user-preference" | "project-context" | "decision-log" | "code-pattern"
124
+ tags?: string[]; // default: []
125
+ priority?: number; // 1–10, default: 5
126
+ }
127
+
128
+ // Output (success)
129
+ {
130
+ success: true;
131
+ merged?: boolean; // true if merged with existing (>80% overlap)
132
+ memory_id: string;
133
+ name: string;
134
+ preview: string; // first 200 chars
135
+ }
136
+ ```
137
+
138
+ **Internal pipeline:**
139
+ 1. `embed(content)` → 384-dim vector (null on failure)
140
+ 2. `autoName(content)` → extract name from content
141
+ 3. `autoMerge(store, memory)` → check existing, merge if Jaccard > 0.8
142
+ 4. `saveMemory(memory)` → write local Markdown
143
+ 5. `store.add(memory)` → update LRU cache
144
+ 6. Pro: `uploadMemory(memory)` → Shelby cloud (async, fire-and-forget)
145
+
146
+ ### memory_search
147
+
148
+ Semantic memory search. Vector-first, auto-fallback to keyword.
149
+
150
+ ```typescript
151
+ // Input
152
+ {
153
+ query: string; // required, natural language
154
+ limit?: number; // 1–20, default: 5
155
+ min_similarity?: number; // 0–1, default: 0.6
156
+ category?: string; // filter by category
157
+ tags?: string[]; // filter by tags (OR match)
158
+ }
159
+
160
+ // Output
161
+ {
162
+ query: string;
163
+ count: number;
164
+ results: [{
165
+ memory_id: string;
166
+ name: string;
167
+ similarity: number; // cosine similarity (0 if keyword fallback)
168
+ content: string;
169
+ _method: "vector" | "keyword";
170
+ }];
171
+ hint: string | null; // "No relevant memories found." if empty
172
+ }
173
+ ```
174
+
175
+ **Scoring formula (vector mode):**
176
+ ```
177
+ score = cosineSimilarity(queryVec, memoryVec)
178
+ × (priority / 5)
179
+ × (1 + min(access_count, 10) × 0.05)
180
+ ```
181
+
182
+ **Scoring formula (keyword mode):**
183
+ ```
184
+ score = (contentHits × 2 + nameHits × 3) + priority
185
+ ```
186
+
187
+ ### memory_recall
188
+
189
+ Exact retrieval by memory ID.
190
+
191
+ ```typescript
192
+ // Input
193
+ { memory_id: string }
194
+
195
+ // Output (success)
196
+ {
197
+ memory_id, name, content, category, tags,
198
+ priority, created_at, access_count
199
+ }
200
+
201
+ // Output (not found)
202
+ { error: "Not found", memory_id }
203
+ ```
204
+
205
+ ### memory_list
206
+
207
+ List memories with pagination and filtering.
208
+
209
+ ```typescript
210
+ // Input
211
+ {
212
+ category?: string; // filter
213
+ tags?: string[]; // filter (OR match)
214
+ limit?: number; // 1–100, default: 20
215
+ offset?: number; // default: 0
216
+ }
217
+
218
+ // Output
219
+ {
220
+ total: number; // total memory count
221
+ count: number; // current page count
222
+ memories: [{
223
+ memory_id, name, category,
224
+ tags, priority,
225
+ preview: string; // first 100 chars
226
+ }];
227
+ }
228
+ ```
229
+
230
+ ### memory_forget
231
+
232
+ Delete a memory (local file + in-memory cache).
233
+
234
+ ```typescript
235
+ // Input
236
+ { memory_id: string }
237
+
238
+ // Output
239
+ {
240
+ success: boolean;
241
+ memory_id: string;
242
+ action: "deleted" | "not_found";
243
+ }
244
+ ```
245
+
246
+ ### memory_context
247
+
248
+ Load current session context — returns top recently-accessed, high-priority memory summaries.
249
+
250
+ ```typescript
251
+ // Input
252
+ { limit?: number; // 1–20, default: 5 }
253
+
254
+ // Output
255
+ {
256
+ context_loaded: true;
257
+ memory_count: number;
258
+ context: string; // format: "- [name] preview..."
259
+ }
260
+ ```
261
+
262
+ **Sort order:** `access_count` DESC, ties broken by `priority` DESC.
263
+
264
+ ### memory_export
265
+
266
+ Export memories as JSON or Markdown.
267
+
268
+ ```typescript
269
+ // Input
270
+ {
271
+ memory_ids?: string[]; // omit to export all
272
+ format?: "json" | "markdown"; // default: "json"
273
+ }
274
+
275
+ // Output (JSON)
276
+ {
277
+ exported_at: string;
278
+ version: "memory-forge-1.0";
279
+ count: number;
280
+ memories: [{ id, name, content, category, tags, priority, created_at }];
281
+ }
282
+
283
+ // Output (Markdown)
284
+ # Memory Name
285
+ > category: x | tags: a, b | priority: 7
286
+ ...
287
+ ---
288
+ ```
289
+
290
+ ### memory_share
291
+
292
+ Package a single memory for import by teammates.
293
+
294
+ ```typescript
295
+ // Input
296
+ {
297
+ memory_id: string;
298
+ recipient?: string;
299
+ note?: string;
300
+ }
301
+
302
+ // Output
303
+ {
304
+ type: "memory-forge-share";
305
+ version: "1.0";
306
+ shared_at: string;
307
+ recipient: string | null;
308
+ note: string | null;
309
+ memory: { name, content, category, tags };
310
+ import_instruction: "Use memory_store with this content to import.";
311
+ }
312
+ ```
313
+
314
+ ---
315
+
316
+ ## Auto-Engines
317
+
318
+ All engines are located in `src/auto/index.ts`.
319
+
320
+ ### autoName
321
+
322
+ Extracts a human-readable name from content.
323
+
324
+ ```
325
+ Algorithm:
326
+ 1. Strip code blocks (```...```)
327
+ 2. Take first 40 chars
328
+ 3. Replace newlines with spaces
329
+ 4. Empty content → "memory"
330
+ ```
331
+
332
+ ### autoMerge
333
+
334
+ Detects and merges duplicate memories.
335
+
336
+ ```
337
+ Algorithm:
338
+ 1. Jaccard similarity: |setA ∩ setB| / min(|setA|, |setB|)
339
+ 2. Minimum word length: 3 chars
340
+ 3. Threshold: > 0.8 → merge
341
+ 4. Recompute embedding vector after merge
342
+ ```
343
+
344
+ ### autoPriority
345
+
346
+ Computes priority score (1–10) based on the Ebbinghaus forgetting curve.
347
+
348
+ ```
349
+ Formula:
350
+ freqWeight = min(access_count, 50) / 50
351
+ recencyWeight = 1 - (daysSinceLastAccess / 90) // clamp 0–1
352
+ ageWeight = 1 - min(ageDays, 365) / 365
353
+
354
+ priority = 1 + 9 × (freqWeight × 0.4 + recencyWeight × 0.4 + ageWeight × 0.2)
355
+ ```
356
+
357
+ ### autoDecay
358
+
359
+ Determines whether a memory should be archived.
360
+
361
+ ```
362
+ | Days | Decay Value | Status |
363
+ |----------|-------------|-------------------|
364
+ | ≤1 | 1.0 | Active |
365
+ | ≤7 | 0.8 | Recent |
366
+ | ≤30 | 0.5 | Decaying |
367
+ | ≤90 | 0.2 | Weak |
368
+ | >90 | 0 | Archived (deleted) |
369
+ ```
370
+
371
+ ### generateContextSummary
372
+
373
+ Generates a context summary for agent injection.
374
+
375
+ ```
376
+ Algorithm:
377
+ 1. Sort all memories by access_count DESC, priority DESC
378
+ 2. Truncate to top-N
379
+ 3. Truncate each to 150 chars
380
+ 4. Format: "- [name] content..."
381
+ ```
382
+
383
+ ---
384
+
385
+ ## Hook System
386
+
387
+ Configuration location: `~/.claude/settings.json`
388
+
389
+ ```json
390
+ {
391
+ "hooks": {
392
+ "SessionStart": [{
393
+ "hooks": [{"type": "command", "command": "memory-forge hook session-start"}]
394
+ }],
395
+ "Stop": [{
396
+ "hooks": [{"type": "command", "command": "memory-forge hook stop"}]
397
+ }],
398
+ "PreCompact": [{
399
+ "hooks": [{"type": "command", "command": "memory-forge hook pre-compact"}]
400
+ }]
401
+ }
402
+ }
403
+ ```
404
+
405
+ ### Lifecycle
406
+
407
+ ```
408
+ SessionStart → Load top-5 memories → Inject into agent context (stdout)
409
+
410
+ Agent works → Calls memory_store / memory_search / etc.
411
+
412
+ PreCompact → Load top-8 memories + inject save instruction → Agent auto-saves
413
+
414
+ Stop → autoPriority recalc + autoDecay check + archive expired
415
+
416
+ (next) SessionStart → Memories preserved ✅
417
+ ```
418
+
419
+ ### Key Design Decision
420
+
421
+ **Why PreCompact instead of Stop for auto-capture?**
422
+
423
+ The Stop hook only fires on graceful exit. `kill`, closing the terminal window, or crashes will skip it. PreCompact always fires when the context window approaches its limit — the process is still alive and the agent can execute the save instruction.
424
+
425
+ ---
426
+
427
+ ## Storage Layer
428
+
429
+ ### Free Tier (Local Markdown)
430
+
431
+ - Path: `~/.memory-forge/memories/{id}.md`
432
+ - Format: YAML-like frontmatter + Markdown body
433
+ - Encoding: UTF-8
434
+ - Permissions: user filesystem control
435
+ - Network: zero
436
+
437
+ ### Pro Tier (Shelby Cloud)
438
+
439
+ - SDK: `@shelby-protocol/sdk` ^0.3.1 (optionalDependency)
440
+ - Network: Shelbynet testnet
441
+ - Auth: API Key + Ed25519 on-chain account
442
+ - Blob format: `memories/{id}.json` (JSON)
443
+ - Expiry: 365 days
444
+ - Data flow: bidirectional sync (↓↑ on session start, ↑ on memory_store)
445
+
446
+ **Pro data flow:**
447
+ ```
448
+ SessionStart:
449
+ syncAll():
450
+ ↓ listBlobs() → fetch remote memory list
451
+ ↓ downloadMemory() → download anything not local (30s timeout)
452
+ ↑ uploadMemory() → upload local-only memories
453
+ → Bidirectional sync complete
454
+
455
+ memory_store:
456
+ saveMemory() → local
457
+ uploadMemory() → Shelby (fire-and-forget, failure is non-blocking)
458
+ ```
459
+
460
+ ---
461
+
462
+ ## Embedding Engine
463
+
464
+ ### Tech Stack
465
+
466
+ - Library: `@huggingface/transformers` ^3.0.0
467
+ - Model: Xenova/all-MiniLM-L6-v2
468
+ - Size: ~23MB (one-time download, cached thereafter)
469
+ - Dimensions: 384
470
+ - Pooling: mean pooling + L2 normalization
471
+
472
+ ### Degradation Strategy
473
+
474
+ ```
475
+ Load model
476
+ → Success: cosine similarity search
477
+ → Failure: keyword matching (Jaccard)
478
+ + 5-minute auto-retry
479
+ + sleep(300s) to prevent request storms
480
+ ```
481
+
482
+ ### Performance
483
+
484
+ - First load: 3–10s (depends on network; 23MB download)
485
+ - Subsequent inference: < 100ms
486
+ - Keyword fallback: < 10ms
487
+ - Model caching: Transformers.js built-in cache
488
+
489
+ ---
490
+
491
+ ## Security Model
492
+
493
+ ### Free Tier
494
+
495
+ - All data in `~/.memory-forge/` directory
496
+ - Zero ongoing network requests
497
+ - Only network: one-time model download (HuggingFace CDN, 23MB)
498
+ - Model download failure → keyword fallback, zero functionality loss
499
+
500
+ ### Pro Tier
501
+
502
+ - API Key: `SHELBY_API_KEY` environment variable only — never written to disk
503
+ - Private Key: `~/.memory-forge/pro.json`, Ed25519 format
504
+ - Transport: HTTPS (Shelbynet API)
505
+ - On-chain: each memory → Aptos blob upload transaction
506
+ - Deletion: tombstone blob (marks deletion; chain is immutable)
507
+
508
+ ### Memory Permissions
509
+
510
+ - Filesystem permissions = memory permissions (Free)
511
+ - On-chain account signature = memory permissions (Pro)
512
+ - No built-in auth layer (agent is already authenticated by Claude Code)
513
+
514
+ ---
515
+
516
+ ## Error Handling & Degradation
517
+
518
+ | Scenario | Behavior | Impact |
519
+ |----------|----------|--------|
520
+ | Embedding model download fails | Keyword search, 5min retry | Lower search precision, functional |
521
+ | Embedding model inference fails | Return null, keyword fallback | Single query degraded |
522
+ | Shelby upload fails | console.error, non-blocking | Pro sync delayed, local intact |
523
+ | Shelby download timeout | 30s timeout, return null | That memory skipped, others OK |
524
+ | Shelby on-chain gas insufficient | Upload fails + error message | Pro unavailable, Free intact |
525
+ | parseMemoryFile corrupt | Skip file, return null | Corrupt file ignored |
526
+ | Disk write fails | Silent failure | Memory lost (extremely rare) |
527
+ | LRU at 5,000 limit | Evict lowest access_count × priority | Old memories evicted from cache, disk preserved |
package/TUTORIAL.md ADDED
@@ -0,0 +1,349 @@
1
+ # MemoryForge — Tutorial
2
+
3
+ > One command. Zero config. Your AI agent now has persistent memory.
4
+
5
+ ## Table of Contents
6
+
7
+ 1. [Quick Start](#quick-start)
8
+ 2. [How It Works](#how-it-works)
9
+ 3. [Daily Use](#daily-use)
10
+ 4. [Pro Tier (Cloud Sync)](#pro-tier-cloud-sync)
11
+ 5. [Managing Memories](#managing-memories)
12
+ 6. [Best Practices](#best-practices)
13
+ 7. [Troubleshooting](#troubleshooting)
14
+ 8. [Uninstall](#uninstall)
15
+
16
+ ---
17
+
18
+ ## Quick Start
19
+
20
+ ### Install
21
+
22
+ ```bash
23
+ npx memory-forge setup
24
+ ```
25
+
26
+ This single command:
27
+ - Installs Claude Code hooks (SessionStart / Stop / PreCompact)
28
+ - Auto-imports existing rules (CLAUDE.md / .cursor/rules / .gitconfig)
29
+ - Preloads the embedding model (23MB, one-time, offline thereafter)
30
+ - Globally installs the `memory-forge` command
31
+
32
+ **Supported platforms:** Claude Code (all platforms), Cursor (via MCP), Windsurf, VS Code.
33
+
34
+ ### Verify
35
+
36
+ Restart Claude Code. You should see:
37
+
38
+ ```
39
+ - [Git User Info] Git user email: xxx
40
+ - [Claude Code Rules] For independent parallel tasks...
41
+ ```
42
+
43
+ This means the SessionStart hook is active and the agent has loaded your memories.
44
+
45
+ ---
46
+
47
+ ## How It Works
48
+
49
+ ### Automated Memory Lifecycle
50
+
51
+ ```
52
+ You open Claude Code
53
+ → Agent auto-loads your preferences and project context
54
+
55
+ You work...
56
+ → Agent automatically remembers your coding style, technical decisions, project preferences
57
+
58
+ Context window nearly full (PreCompact)
59
+ → Agent auto-saves critical information to the memory store
60
+ → Even if you force-close the terminal, memories survive
61
+
62
+ You close Claude Code (Stop)
63
+ → Auto-update memory priorities (frequently-used memories get higher weight)
64
+ → Auto-archive memories unused for 90+ days
65
+
66
+ Next session
67
+ → Agent remembers everything ✅
68
+ ```
69
+
70
+ ### You Do Nothing
71
+
72
+ The agent automatically:
73
+ - **Stores**: you mention preferences, decisions, lessons → agent calls `memory_store`
74
+ - **Searches**: needs to recall something → agent calls `memory_search`
75
+ - **Maintains**: priority adjustment, expiry cleanup → fully automatic
76
+
77
+ ---
78
+
79
+ ## Daily Use
80
+
81
+ ### Basic Interaction
82
+
83
+ ```
84
+ You: "I prefer camelCase naming, single quotes, 2-space indent"
85
+
86
+ Agent auto-calls memory_store → memory saved ✅
87
+ Next time you write code, the agent follows your preferences automatically.
88
+
89
+ ---
90
+
91
+ You: "How did we fix that token refresh bug?"
92
+
93
+ Agent calls memory_search → finds relevant memory
94
+ "On June 15, you fixed auth.ts — the token expiry check was using < instead of <="
95
+
96
+ ---
97
+
98
+ You: "Help me refactor the auth module"
99
+
100
+ Agent calls memory_context → loads context
101
+ "Got it. Based on prior records, this project uses React 19 + JWT + refresh token pattern. Start from auth.ts?"
102
+ ```
103
+
104
+ ### Explicit Commands
105
+
106
+ You can also tell the agent explicitly:
107
+
108
+ ```
109
+ "Store a memory: production database uses PostgreSQL 16, connection string in .env.production"
110
+ "Search for memories about deployment"
111
+ "List all my memories"
112
+ "Export all memories as Markdown"
113
+ "Forget the memory with ID xxx"
114
+ ```
115
+
116
+ ---
117
+
118
+ ## Pro Tier (Cloud Sync)
119
+
120
+ ### When You Need Pro
121
+
122
+ - You use multiple computers and want cross-device memory sync
123
+ - You're worried about disk failure losing your memories
124
+ - You want shared project memories with teammates
125
+
126
+ ### Activating Pro
127
+
128
+ ```bash
129
+ # 1. Get an API Key
130
+ # Visit https://docs.shelby.xyz/sdks/typescript/acquire-api-keys
131
+
132
+ # 2. Activate Pro
133
+ SHELBY_API_KEY="your-api-key" memory-forge pro
134
+
135
+ # 3. First time: fund your account with APT + ShelbyUSD (testnet faucet)
136
+ # The address will be printed. Go to the faucet:
137
+ # APT: https://docs.shelby.xyz/apis/faucet/aptos
138
+ # ShelbyUSD: https://docs.shelby.xyz/apis/faucet/shelbyusd
139
+
140
+ # 4. After claiming tokens, sync again
141
+ SHELBY_API_KEY="your-api-key" memory-forge pro
142
+ ```
143
+
144
+ ### Cross-Device Sync
145
+
146
+ ```
147
+ Device A: Activate Pro → work → memories auto-upload
148
+ Device B: Set SHELBY_API_KEY env var → install → memories auto-download
149
+ → Agent on device B remembers everything ✅
150
+ ```
151
+
152
+ ### Environment Variable
153
+
154
+ Add to your shell config for permanent setup:
155
+
156
+ ```bash
157
+ # ~/.bashrc or ~/.zshrc
158
+ export SHELBY_API_KEY="your-api-key"
159
+ ```
160
+
161
+ The agent will auto-sync on every session start.
162
+
163
+ ---
164
+
165
+ ## Managing Memories
166
+
167
+ ### Viewing Memories
168
+
169
+ ```bash
170
+ # List memory files
171
+ ls ~/.memory-forge/memories/
172
+
173
+ # Read a specific memory
174
+ cat ~/.memory-forge/memories/{id}.md
175
+ ```
176
+
177
+ Memory files are human-readable Markdown. You can edit them directly.
178
+
179
+ ### Exporting
180
+
181
+ ```
182
+ # Via agent
183
+ "Export all memories as JSON"
184
+ "Export auth-related memories as Markdown"
185
+ ```
186
+
187
+ ### Backup
188
+
189
+ ```bash
190
+ # Local backup (Free tier)
191
+ cp -r ~/.memory-forge/memories/ ~/backup/
192
+
193
+ # Pro tier auto-backs up to Shelby cloud
194
+ ```
195
+
196
+ ### Cleanup
197
+
198
+ ```bash
199
+ # Delete all local memories
200
+ rm -rf ~/.memory-forge/memories/*.md
201
+
202
+ # Delete a single memory
203
+ rm ~/.memory-forge/memories/{id}.md
204
+
205
+ # Reset Pro account
206
+ rm ~/.memory-forge/pro.json
207
+ ```
208
+
209
+ ---
210
+
211
+ ## Best Practices
212
+
213
+ ### What's Worth Remembering
214
+
215
+ | Worth It | Not Worth It |
216
+ |----------|--------------|
217
+ | Coding style preferences | One-off debug sessions |
218
+ | Project architecture decisions | Temporary experimental code |
219
+ | Team conventions | Outdated configuration |
220
+ | Frequently-used commands and workflows | Pure factual knowledge |
221
+ | Lessons learned and solutions found | One-time tasks |
222
+
223
+ ### Memory Quality
224
+
225
+ ```
226
+ ✅ Good: "Project uses PostgreSQL 16 + Prisma ORM, connection pool limit 20"
227
+ ❌ Bad: "database is pg"
228
+
229
+ ✅ Good: "User prefers camelCase, single quotes, 2-space indent, React 19 + TypeScript strict"
230
+ ❌ Bad: "uses camelCase"
231
+
232
+ ✅ Good: "6/26 — decided to cache tokens in Redis because DB queries were >500ms"
233
+ ❌ Bad: "added Redis"
234
+ ```
235
+
236
+ ### Periodic Maintenance
237
+
238
+ Do a memory cleanup once a month:
239
+
240
+ ```
241
+ "Review all my memories and flag anything outdated or no longer needed"
242
+ "Forget memories related to projects I no longer work on"
243
+ ```
244
+
245
+ ---
246
+
247
+ ## Troubleshooting
248
+
249
+ ### Hooks Not Working
250
+
251
+ **Symptom:** Opening Claude Code shows no memory loading.
252
+
253
+ ```bash
254
+ # 1. Check hook configuration
255
+ memory-forge hook session-start
256
+
257
+ # 2. Reinstall hooks
258
+ memory-forge setup
259
+
260
+ # 3. Verify settings.json
261
+ cat ~/.claude/settings.json | grep memory-forge
262
+
263
+ # 4. Restart Claude Code
264
+ ```
265
+
266
+ ### Stop Hook Error
267
+
268
+ **Symptom:** "Stop hook error" on session close.
269
+
270
+ ```bash
271
+ # Confirm global install
272
+ npm ls -g memory-forge
273
+
274
+ # If not latest
275
+ npm i -g memory-forge@latest
276
+
277
+ # Check hook command format
278
+ # settings.json should have "memory-forge hook stop", not "npx memory-forge hook stop"
279
+ ```
280
+
281
+ ### Inaccurate Search Results
282
+
283
+ **Symptom:** `memory_search` returns irrelevant results.
284
+
285
+ ```bash
286
+ # Check if embedding model downloaded successfully
287
+ # If you see "[MemoryForge] Falling back to keyword matching"
288
+ # → Model download failed; keyword mode is active
289
+
290
+ # Solution: wait 5 minutes for auto-retry, or trigger a retry manually
291
+ # Model size is 23MB — ensure network is working
292
+ ```
293
+
294
+ ### Pro Sync Fails
295
+
296
+ **Symptom:** "Shelby upload failed: INSUFFICIENT_BALANCE_FOR_TRANSACTION_FEE"
297
+
298
+ ```bash
299
+ # Check account balance
300
+ # Visit the faucet to claim APT + ShelbyUSD
301
+ # Then re-run pro
302
+
303
+ SHELBY_API_KEY="your-key" memory-forge pro
304
+ ```
305
+
306
+ ### Duplicate Memories
307
+
308
+ **Symptom:** `memory_list` shows repeated similar memories.
309
+
310
+ ```bash
311
+ # 0.1.6+ has a root-cause fix. If you still see duplicates:
312
+ # 1. Upgrade to latest
313
+ npm i -g memory-forge@latest
314
+ memory-forge setup
315
+
316
+ # 2. Manual cleanup
317
+ # Delete duplicate .md files in ~/.memory-forge/memories/
318
+ ```
319
+
320
+ ### Full Reset
321
+
322
+ ```bash
323
+ # 1. Delete memories
324
+ rm -rf ~/.memory-forge/memories/*.md
325
+
326
+ # 2. Delete Pro account (optional)
327
+ rm -f ~/.memory-forge/pro.json
328
+
329
+ # 3. Clear hooks
330
+ # Edit ~/.claude/settings.json, remove all entries containing "memory-forge"
331
+
332
+ # 4. Reinstall
333
+ memory-forge setup
334
+ ```
335
+
336
+ ---
337
+
338
+ ## Uninstall
339
+
340
+ ```bash
341
+ # Remove all local data
342
+ rm -rf ~/.memory-forge/
343
+
344
+ # Edit ~/.claude/settings.json
345
+ # Remove all hook entries containing "memory-forge"
346
+
347
+ # Uninstall global command
348
+ npm uninstall -g memory-forge
349
+ ```
package/dist/index.js CHANGED
@@ -95,7 +95,7 @@ function startMcpServer() {
95
95
  store.add(m);
96
96
  }
97
97
  preload();
98
- const server = new McpServer({ name: "memory-forge", version: "0.1.7" });
98
+ const server = new McpServer({ name: "memory-forge", version: "0.2.0" });
99
99
  // ── memory_store ──────────────────────────────────────────
100
100
  server.registerTool("memory_store", {
101
101
  title: "存储记忆",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "memory-forge",
3
- "version": "0.1.8",
3
+ "version": "0.2.0",
4
4
  "description": "Forge persistent memories for your AI agent. 8 MCP tools + 5 auto-engines. Powered by Shelby decentralized cloud.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -33,6 +33,8 @@
33
33
  "files": [
34
34
  "dist/",
35
35
  "README.md",
36
+ "TECHNICAL.md",
37
+ "TUTORIAL.md",
36
38
  "LICENSE"
37
39
  ],
38
40
  "scripts": {