pi-ate-memory 1.0.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.en.md +232 -0
- package/README.md +234 -0
- package/index.ts +198 -0
- package/lib/conflict-detect.ts +38 -0
- package/lib/memory-hook.ts +37 -0
- package/lib/memory-inject.ts +72 -0
- package/lib/memory-parser.ts +95 -0
- package/lib/types.ts +32 -0
- package/lib/writer.ts +69 -0
- package/memory-prompt.md +11 -0
- package/package.json +60 -0
- package/prompts/update-description.md +29 -0
- package/tsconfig.json +10 -0
package/README.en.md
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
[中文文档](README.md) | English
|
|
2
|
+
|
|
3
|
+
# pi-memory
|
|
4
|
+
|
|
5
|
+
Persistent cross-session memory for [pi](https://github.com/earendil-works/pi-coding-agent).
|
|
6
|
+
|
|
7
|
+
Every AI agent conversation starts from scratch — it doesn't remember what was discussed yesterday, what pitfalls were hit, or what decisions were made. pi-memory solves this using the filesystem: it lets the agent maintain a knowledge base automatically, and loads it into every new session without manual intervention.
|
|
8
|
+
|
|
9
|
+
## How It Works
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
New session starts
|
|
13
|
+
└─► MEMORY.md index is automatically injected into system prompt
|
|
14
|
+
│
|
|
15
|
+
▼
|
|
16
|
+
Agent needs to recall → calls memory_index to check existing entries
|
|
17
|
+
Agent learns something new → calls memory_update to write it down
|
|
18
|
+
└─► Index is rebuilt automatically, visible in next session
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
**Core mechanisms**:
|
|
22
|
+
- **Files as memory**: Each Markdown file is an independent knowledge record
|
|
23
|
+
- **Auto-indexing**: The `MEMORY.md` index is rebuilt after every write, automatically injected into the next session
|
|
24
|
+
- **Conflict detection**: Before writing, checks for existing files with the same topic or ≥3 overlapping keywords to prevent fragmentation
|
|
25
|
+
- **Two-tier storage**: Global memory (cross-project knowledge) + Project memory (architectural decisions, pitfalls)
|
|
26
|
+
|
|
27
|
+
## Installation
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pi install git:github.com/catlain/pi-memory
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Restart pi and you're good to go. No additional configuration needed.
|
|
34
|
+
|
|
35
|
+
> **Prerequisite**: [pi](https://github.com/earendil-works/pi-coding-agent) must be installed.
|
|
36
|
+
|
|
37
|
+
## Provided Tools
|
|
38
|
+
|
|
39
|
+
### `memory_index` — View Memory Inventory
|
|
40
|
+
|
|
41
|
+
Scans the memory directories and returns a structured index table.
|
|
42
|
+
|
|
43
|
+
**Parameters**:
|
|
44
|
+
| Parameter | Type | Required | Description |
|
|
45
|
+
|-----------|------|----------|-------------|
|
|
46
|
+
| scope | `"all"` / `"L1"` / `"L2"` | No | Scan scope, defaults to `all` |
|
|
47
|
+
|
|
48
|
+
**When the agent should use this**:
|
|
49
|
+
- To browse existing memory contents
|
|
50
|
+
- To check whether a topic already has a memory file before writing
|
|
51
|
+
- To decide whether to create a new file or merge into an existing one
|
|
52
|
+
|
|
53
|
+
**Example output**:
|
|
54
|
+
```
|
|
55
|
+
# Memory Index
|
|
56
|
+
|
|
57
|
+
## L1 — ~/.pi/agent/memory
|
|
58
|
+
|
|
59
|
+
| topic | keywords | lines | description |
|
|
60
|
+
|-------|----------|-------|-------------|
|
|
61
|
+
| coding_standards | coding, git, lint, format | 45 | Coding standards and file formatting rules |
|
|
62
|
+
| debug_anti_pattern | uvicorn, cache, code loading | 32 | Common debugging pitfalls |
|
|
63
|
+
|
|
64
|
+
## L2 — /project/.pi/memory
|
|
65
|
+
|
|
66
|
+
| topic | keywords | lines | description |
|
|
67
|
+
|-------|----------|-------|-------------|
|
|
68
|
+
| data_model | DuckDB, factor, incremental | 28 | Factor data storage design |
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### `memory_update` — Write/Update Memory
|
|
72
|
+
|
|
73
|
+
Writes a Markdown file and rebuilds the index. Includes a full safety check chain.
|
|
74
|
+
|
|
75
|
+
**Parameters**:
|
|
76
|
+
| Parameter | Type | Required | Description |
|
|
77
|
+
|-----------|------|----------|-------------|
|
|
78
|
+
| fileName | string | Yes | File name, format `topic--kw1,kw2,kw3.md` |
|
|
79
|
+
| content | string | Yes | Full memory file content (Markdown) |
|
|
80
|
+
| scope | `"L1"` / `"L2"` | No | Target scope, defaults to `L2` |
|
|
81
|
+
|
|
82
|
+
**Safety checks** (executed in order; any failure rejects the write):
|
|
83
|
+
1. ✏️ File name does not contain path separators (prevents path traversal)
|
|
84
|
+
2. 📏 Content ≤ 50KB
|
|
85
|
+
3. 📏 Content ≤ 200 lines
|
|
86
|
+
4. 📁 Total memory files ≤ 40 (hard limit)
|
|
87
|
+
5. 🔍 No existing file with same topic or ≥3 overlapping keywords (conflict detection)
|
|
88
|
+
|
|
89
|
+
**Agent write workflow** (guided by the tool description):
|
|
90
|
+
```
|
|
91
|
+
1. Call memory_index to inspect existing files
|
|
92
|
+
2. Decide: create new? overwrite? merge?
|
|
93
|
+
3. Confirm the file name format is correct
|
|
94
|
+
4. Call memory_update to write
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
**Handling conflicts** (the tool returns the list of conflicting files):
|
|
98
|
+
- **Merge**: Read all conflicting files → consolidate into one → overwrite with an existing file name → delete the rest
|
|
99
|
+
- **Replace**: New content fully supersedes old conclusions → write using the conflicting file's name
|
|
100
|
+
- **Confirm unrelated**: Adjust the topic or keywords so overlap < 3, then retry
|
|
101
|
+
|
|
102
|
+
## File Format
|
|
103
|
+
|
|
104
|
+
### File Naming
|
|
105
|
+
|
|
106
|
+
```
|
|
107
|
+
topic--kw1,kw2,kw3,kw4,kw5.md
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
| Part | Description | Example |
|
|
111
|
+
|------|-------------|---------|
|
|
112
|
+
| topic | Short English identifier representing the memory topic | `coding_standards` |
|
|
113
|
+
| kw1~kw5 | Up to 5 keywords, comma-separated | `coding,git,lint,format` |
|
|
114
|
+
|
|
115
|
+
**Examples**:
|
|
116
|
+
- `debug_anti_pattern--uvicorn,cache,code-loading,misdiagnosis.md`
|
|
117
|
+
- `data_model--DuckDB,factor,incremental.md`
|
|
118
|
+
- `coding_standards--coding,git,lint,format,Karpathy.md`
|
|
119
|
+
|
|
120
|
+
### File Content
|
|
121
|
+
|
|
122
|
+
Markdown format, with the title describing the topic:
|
|
123
|
+
|
|
124
|
+
```markdown
|
|
125
|
+
# Coding Standards & File Formatting
|
|
126
|
+
|
|
127
|
+
Keywords: coding git lint format
|
|
128
|
+
|
|
129
|
+
## Core Rules
|
|
130
|
+
- One PR per concern
|
|
131
|
+
- Must lint before commit
|
|
132
|
+
- ...
|
|
133
|
+
|
|
134
|
+
## Pitfalls
|
|
135
|
+
- ...
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
### Index File
|
|
139
|
+
|
|
140
|
+
`MEMORY.md` is maintained automatically by the tool — no manual editing needed. Format:
|
|
141
|
+
|
|
142
|
+
```markdown
|
|
143
|
+
# Memory Index
|
|
144
|
+
|
|
145
|
+
> Auto-generated — lists all memory files and their keyword summaries
|
|
146
|
+
|
|
147
|
+
## Files (3)
|
|
148
|
+
|
|
149
|
+
| # | File | Keywords |
|
|
150
|
+
|---|------|----------|
|
|
151
|
+
| 1 | coding_standards | coding, git, lint |
|
|
152
|
+
| 2 | debug_anti_pattern | uvicorn, cache |
|
|
153
|
+
|
|
154
|
+
- [coding_standards](coding_standards--coding,git,lint.md)
|
|
155
|
+
- [debug_anti_pattern](debug_anti_pattern--uvicorn,cache.md)
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## Two-Tier Storage
|
|
159
|
+
|
|
160
|
+
| Tier | Path | Purpose | Example |
|
|
161
|
+
|------|------|---------|---------|
|
|
162
|
+
| **L1 Global** | `~/.pi/agent/memory/` | Cross-project general knowledge | Toolchain config, coding discipline, general pitfalls |
|
|
163
|
+
| **L2 Project** | `<project>/.pi/memory/` | Project-specific knowledge | Architecture decisions, data models, project conventions |
|
|
164
|
+
|
|
165
|
+
- L1 is visible in all projects
|
|
166
|
+
- L2 is visible only under its project directory
|
|
167
|
+
- Each tier's index is maintained independently
|
|
168
|
+
|
|
169
|
+
## Automatic Injection
|
|
170
|
+
|
|
171
|
+
On every new session start, the `before_agent_start` hook automatically injects the `MEMORY.md` index into the system prompt. Once the agent sees the index, it can use the `read` tool to load specific memory files.
|
|
172
|
+
|
|
173
|
+
Injection limits:
|
|
174
|
+
- Max 200 lines
|
|
175
|
+
- Max 25KB
|
|
176
|
+
- Truncated automatically with a warning when exceeded
|
|
177
|
+
|
|
178
|
+
## Limits
|
|
179
|
+
|
|
180
|
+
| Limit | Value | Description |
|
|
181
|
+
|-------|-------|-------------|
|
|
182
|
+
| Max lines per file | 200 | Write rejected beyond this; split required |
|
|
183
|
+
| Max size per file | 50 KB | Write rejected beyond this |
|
|
184
|
+
| Hard limit on total files | 40 | Write rejected beyond this; cleanup/merge required |
|
|
185
|
+
| Soft limit on total files | 25 | Warning issued beyond this |
|
|
186
|
+
| Max keywords | 5 | At most 5 keywords per file |
|
|
187
|
+
| Conflict detection threshold | 3 overlapping keywords | Same topic or ≥3 keyword overlap triggers conflict |
|
|
188
|
+
|
|
189
|
+
## Best Practices
|
|
190
|
+
|
|
191
|
+
### ✅ Worth Remembering
|
|
192
|
+
- Pitfalls you've hit and how you fixed them
|
|
193
|
+
- Architecture decisions and the reasoning behind them
|
|
194
|
+
- Project-specific conventions and rules
|
|
195
|
+
- Toolchain configuration experience
|
|
196
|
+
- Debugging misconceptions and anti-patterns
|
|
197
|
+
|
|
198
|
+
### ❌ Not Worth Remembering
|
|
199
|
+
- Transient info (current bug state, tasks in progress)
|
|
200
|
+
- Information that can be read directly from source code
|
|
201
|
+
- Frequently changing info (version numbers, specific line numbers)
|
|
202
|
+
|
|
203
|
+
### 🧹 Regular Cleanup
|
|
204
|
+
- When memory exceeds 25 files, proactively merge related topics
|
|
205
|
+
- When new files supersede outdated conclusions, delete the old ones
|
|
206
|
+
- Split files exceeding 200 lines by subtopic
|
|
207
|
+
|
|
208
|
+
## Architecture
|
|
209
|
+
|
|
210
|
+
```
|
|
211
|
+
extensions/memory/
|
|
212
|
+
├── index.ts # Entry point: registers tools + before_agent_start hook
|
|
213
|
+
├── memory-prompt.md # Injected instructions (tells the AI how to use memory)
|
|
214
|
+
├── lib/
|
|
215
|
+
│ ├── types.ts # Constants (directory paths, limit thresholds)
|
|
216
|
+
│ ├── memory-hook.ts # before_agent_start hook registration
|
|
217
|
+
│ ├── memory-inject.ts # Reads MEMORY.md → generates injection text
|
|
218
|
+
│ ├── writer.ts # File writing + index rebuild
|
|
219
|
+
│ └── conflict-detect.ts # Same-topic / keyword-overlap detection
|
|
220
|
+
├── prompts/
|
|
221
|
+
│ └── update-description.md # Full description for the memory_update tool (with write workflow)
|
|
222
|
+
└── package.json
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
**Dependencies**:
|
|
226
|
+
- `@pi-atelier/shared-utils` — `scanMemoryDir`, `parseFileName` (file name parsing and directory scanning)
|
|
227
|
+
- `@earendil-works/pi-coding-agent` — ExtensionAPI
|
|
228
|
+
- No other dependencies
|
|
229
|
+
|
|
230
|
+
## License
|
|
231
|
+
|
|
232
|
+
MIT
|
package/README.md
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
> 📖 **[pi-atelier 实战指南](https://catlain.github.io/pi-atelier/)** — 从零教会你使用 pi-atelier 扩展生态,包含完整示例和最佳实践。
|
|
2
|
+
|
|
3
|
+
[English](README.en.md) | 程序中文文档
|
|
4
|
+
|
|
5
|
+
# pi-memory
|
|
6
|
+
|
|
7
|
+
为 [pi](https://github.com/earendil-works/pi-coding-agent) 提供跨会话持久记忆。
|
|
8
|
+
|
|
9
|
+
AI agent 的每次对话都是全新开始——不记得昨天讨论了什么、踩过哪些坑、做过什么决策。pi-memory 用文件系统解决这个问题:让 agent 自动维护一个知识库,每次新会话自动加载。
|
|
10
|
+
|
|
11
|
+
## 工作原理
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
新会话启动
|
|
15
|
+
└─► 自动注入 MEMORY.md 索引到 system prompt
|
|
16
|
+
│
|
|
17
|
+
▼
|
|
18
|
+
Agent 需要记忆 → 调用 memory_index 查看已有
|
|
19
|
+
Agent 学到新东西 → 调用 memory_update 写入
|
|
20
|
+
└─► 自动重建索引,下次会话可见
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
**核心机制**:
|
|
24
|
+
- **文件即记忆**:每个 Markdown 文件是一条独立的知识记录
|
|
25
|
+
- **自动索引**:每次写入后自动重建 `MEMORY.md` 索引,下次会话自动注入
|
|
26
|
+
- **冲突检测**:写入时自动检查同主题/高关键词重叠的已有文件,防止碎片化
|
|
27
|
+
- **两级存储**:全局记忆(跨项目通用知识)+ 项目记忆(架构决策、踩坑记录)
|
|
28
|
+
|
|
29
|
+
## 安装
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pi install git:github.com/catlain/pi-memory
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
重启 pi 即可使用。无需额外配置。
|
|
36
|
+
|
|
37
|
+
> **前提**:已安装 [pi](https://github.com/earendil-works/pi-coding-agent)。
|
|
38
|
+
|
|
39
|
+
## 提供的工具
|
|
40
|
+
|
|
41
|
+
### `memory_index` — 查看记忆清单
|
|
42
|
+
|
|
43
|
+
扫描记忆目录,返回结构化索引表格。
|
|
44
|
+
|
|
45
|
+
**参数**:
|
|
46
|
+
| 参数 | 类型 | 必填 | 说明 |
|
|
47
|
+
|------|------|------|------|
|
|
48
|
+
| scope | `"all"` / `"L1"` / `"L2"` | 否 | 扫描范围,默认 `all` |
|
|
49
|
+
|
|
50
|
+
**Agent 什么时候用**:
|
|
51
|
+
- 想了解已有记忆内容
|
|
52
|
+
- 写入前检查是否已存在相关记忆
|
|
53
|
+
- 决定是否需要新建或合并
|
|
54
|
+
|
|
55
|
+
**输出示例**:
|
|
56
|
+
```
|
|
57
|
+
# 记忆文件索引
|
|
58
|
+
|
|
59
|
+
## L1 — ~/.pi/agent/memory
|
|
60
|
+
|
|
61
|
+
| topic | keywords | 行数 | 描述 |
|
|
62
|
+
|-------|----------|------|------|
|
|
63
|
+
| coding_standards | 编码, git, lint, 格式 | 45 | 编码规范和文件格式要求 |
|
|
64
|
+
| debug_anti_pattern | uvicorn, 缓存, 代码加载 | 32 | 常见调试误区 |
|
|
65
|
+
|
|
66
|
+
## L2 — /project/.pi/memory
|
|
67
|
+
|
|
68
|
+
| topic | keywords | 行数 | 描述 |
|
|
69
|
+
|-------|----------|------|------|
|
|
70
|
+
| 数据模型 | DuckDB, 因子, 增量 | 28 | 因子数据存储方案 |
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### `memory_update` — 写入/更新记忆
|
|
74
|
+
|
|
75
|
+
写入 Markdown 文件并自动重建索引。包含完整的安全检查链。
|
|
76
|
+
|
|
77
|
+
**参数**:
|
|
78
|
+
| 参数 | 类型 | 必填 | 说明 |
|
|
79
|
+
|------|------|------|------|
|
|
80
|
+
| fileName | string | 是 | 文件名,格式 `topic--kw1,kw2,kw3.md` |
|
|
81
|
+
| content | string | 是 | 完整的记忆文件内容(Markdown) |
|
|
82
|
+
| scope | `"L1"` / `"L2"` | 否 | 目标作用域,默认 `L2` |
|
|
83
|
+
|
|
84
|
+
**安全检查**(按顺序执行,任一失败则拒绝写入):
|
|
85
|
+
1. ✏️ 文件名不含路径分隔符(防路径遍历)
|
|
86
|
+
2. 📏 内容 ≤ 50KB
|
|
87
|
+
3. 📏 内容 ≤ 200 行
|
|
88
|
+
4. 📁 记忆文件总数 ≤ 40(硬限制)
|
|
89
|
+
5. 🔍 无同主题或 ≥3 关键词重叠的已有文件(冲突检测)
|
|
90
|
+
|
|
91
|
+
**Agent 写入流程**(工具描述中已引导):
|
|
92
|
+
```
|
|
93
|
+
1. 调 memory_index 查看已有文件
|
|
94
|
+
2. 判断:新建?覆盖?合并?
|
|
95
|
+
3. 确认文件名格式正确
|
|
96
|
+
4. 调 memory_update 写入
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
**冲突时的处理方法**(工具会返回具体冲突文件列表):
|
|
100
|
+
- **合并**:读取所有冲突文件 → 整合为一份 → 用已有文件名覆盖 → 删除其余
|
|
101
|
+
- **取代**:新内容完全覆盖旧结论 → 用冲突文件的文件名写入
|
|
102
|
+
- **确认不相关**:调整 topic 或关键词使重叠 < 3,再重试
|
|
103
|
+
|
|
104
|
+
## 文件格式
|
|
105
|
+
|
|
106
|
+
### 文件命名
|
|
107
|
+
|
|
108
|
+
```
|
|
109
|
+
topic--kw1,kw2,kw3,kw4,kw5.md
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
| 部分 | 说明 | 示例 |
|
|
113
|
+
|------|------|------|
|
|
114
|
+
| topic | 英文短标识,代表记忆主题 | `coding_standards` |
|
|
115
|
+
| kw1~kw5 | 最多 5 个关键词,逗号分隔 | `编码,git,lint,格式` |
|
|
116
|
+
|
|
117
|
+
**示例**:
|
|
118
|
+
- `debug_anti_pattern--uvicorn,缓存,代码加载,误判.md`
|
|
119
|
+
- `数据模型--DuckDB,因子,增量.md`
|
|
120
|
+
- `coding_standards--编码,git,lint,格式,Karpathy.md`
|
|
121
|
+
|
|
122
|
+
### 文件内容
|
|
123
|
+
|
|
124
|
+
Markdown 格式,标题即主题描述:
|
|
125
|
+
|
|
126
|
+
```markdown
|
|
127
|
+
# 编码规范与文件格式
|
|
128
|
+
|
|
129
|
+
关键词: 编码 git lint 格式
|
|
130
|
+
|
|
131
|
+
## 核心规则
|
|
132
|
+
- 每个 PR 只做一件事
|
|
133
|
+
- 提交前必须 lint
|
|
134
|
+
- ...
|
|
135
|
+
|
|
136
|
+
## 踩坑记录
|
|
137
|
+
- ...
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
### 索引文件
|
|
141
|
+
|
|
142
|
+
`MEMORY.md` 由工具自动维护,不需要手动编辑。格式:
|
|
143
|
+
|
|
144
|
+
```markdown
|
|
145
|
+
# Memory Index
|
|
146
|
+
|
|
147
|
+
> 自动生成 — 列出所有记忆文件及其关键词摘要
|
|
148
|
+
|
|
149
|
+
## 文件清单 (3)
|
|
150
|
+
|
|
151
|
+
| # | 文件 | 关键词 |
|
|
152
|
+
|---|------|--------|
|
|
153
|
+
| 1 | coding_standards | 编码, git, lint |
|
|
154
|
+
| 2 | debug_anti_pattern | uvicorn, 缓存 |
|
|
155
|
+
|
|
156
|
+
- [coding_standards](coding_standards--编码,git,lint.md)
|
|
157
|
+
- [debug_anti_pattern](debug_anti_pattern--uvicorn,缓存.md)
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
## 两级存储
|
|
161
|
+
|
|
162
|
+
| 级别 | 路径 | 用途 | 示例 |
|
|
163
|
+
|------|------|------|------|
|
|
164
|
+
| **L1 全局** | `~/.pi/agent/memory/` | 跨项目通用知识 | 工具链配置、编码纪律、通用踩坑 |
|
|
165
|
+
| **L2 项目** | `<project>/.pi/memory/` | 项目特定知识 | 架构决策、数据模型、项目约定 |
|
|
166
|
+
|
|
167
|
+
- L1 在所有项目中可见
|
|
168
|
+
- L2 只在对应项目目录下可见
|
|
169
|
+
- 两级的索引独立维护
|
|
170
|
+
|
|
171
|
+
## 自动注入
|
|
172
|
+
|
|
173
|
+
每次新会话启动时,`before_agent_start` hook 会自动将 `MEMORY.md` 索引注入到 system prompt 中。Agent 看到索引后,可以用 `read` 工具读取具体文件内容。
|
|
174
|
+
|
|
175
|
+
注入有限制:
|
|
176
|
+
- 最大 200 行
|
|
177
|
+
- 最大 25KB
|
|
178
|
+
- 超出时自动截断并提示
|
|
179
|
+
|
|
180
|
+
## 限制
|
|
181
|
+
|
|
182
|
+
| 限制 | 值 | 说明 |
|
|
183
|
+
|------|---|------|
|
|
184
|
+
| 单文件行数上限 | 200 行 | 超出拒绝写入,需拆分 |
|
|
185
|
+
| 单文件大小上限 | 50 KB | 超出拒绝写入 |
|
|
186
|
+
| 文件总数硬限制 | 40 个 | 超出拒绝写入,需清理合并 |
|
|
187
|
+
| 文件总数软限制 | 25 个 | 超出发出警告 |
|
|
188
|
+
| 关键词上限 | 5 个 | 每个文件最多 5 个关键词 |
|
|
189
|
+
| 冲突检测阈值 | 3 个关键词重叠 | 同 topic 或 ≥3 关键词重叠触发冲突 |
|
|
190
|
+
|
|
191
|
+
## 最佳实践
|
|
192
|
+
|
|
193
|
+
### ✅ 应该记住的
|
|
194
|
+
- 踩过的坑和解决方案
|
|
195
|
+
- 架构决策和原因
|
|
196
|
+
- 项目特有的约定和规则
|
|
197
|
+
- 工具链配置经验
|
|
198
|
+
- 调试误区和反模式
|
|
199
|
+
|
|
200
|
+
### ❌ 不应该记住的
|
|
201
|
+
- 临时信息(当前 bug 状态、正在处理的任务)
|
|
202
|
+
- 可以从代码中直接读取的信息
|
|
203
|
+
- 频繁变化的信息(版本号、具体行数)
|
|
204
|
+
|
|
205
|
+
### 🧹 定期清理
|
|
206
|
+
- 记忆超过 25 个时,主动合并相关主题
|
|
207
|
+
- 过时结论被新文件取代时,删除旧文件
|
|
208
|
+
- 超过 200 行的文件按子主题拆分
|
|
209
|
+
|
|
210
|
+
## 架构
|
|
211
|
+
|
|
212
|
+
```
|
|
213
|
+
extensions/memory/
|
|
214
|
+
├── index.ts # 入口:注册工具 + before_agent_start hook
|
|
215
|
+
├── memory-prompt.md # 注入说明文本(告诉 AI 怎么用记忆)
|
|
216
|
+
├── lib/
|
|
217
|
+
│ ├── types.ts # 常量(目录路径、限制阈值)
|
|
218
|
+
│ ├── memory-hook.ts # before_agent_start hook 注册
|
|
219
|
+
│ ├── memory-inject.ts # 读取 MEMORY.md → 生成注入文本
|
|
220
|
+
│ ├── writer.ts # 文件写入 + 索引重建
|
|
221
|
+
│ └── conflict-detect.ts # 同主题/关键词重叠检测
|
|
222
|
+
├── prompts/
|
|
223
|
+
│ └── update-description.md # memory_update 工具的完整描述(含写入流程)
|
|
224
|
+
└── package.json
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
**依赖**:
|
|
228
|
+
- `@pi-atelier/shared-utils` — `scanMemoryDir`、`parseFileName`(文件名解析和目录扫描)
|
|
229
|
+
- `@earendil-works/pi-coding-agent` — ExtensionAPI
|
|
230
|
+
- 无其他依赖
|
|
231
|
+
|
|
232
|
+
## 许可证
|
|
233
|
+
|
|
234
|
+
MIT
|
package/index.ts
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memory Tools — 记忆索引查询 + 写入
|
|
3
|
+
*
|
|
4
|
+
* 提供两个工具供 AI 主动调用:
|
|
5
|
+
* - memory_index: 扫描记忆目录,返回结构化清单(从文件名解析 topic + keywords)
|
|
6
|
+
* - memory_update: 写文件 + 更新 MEMORY.md 索引(去重由 AI 判断)
|
|
7
|
+
*
|
|
8
|
+
* 记忆架构:
|
|
9
|
+
* L1 ~/.pi/agent/MEMORY.md + memory/*.md ← 跨项目通用
|
|
10
|
+
* L2 {project}/.pi/memory/MEMORY.md + *.md ← 项目主题
|
|
11
|
+
*
|
|
12
|
+
* 文件名格式:topic--kw1,kw2,kw3,kw4,kw5.md
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
16
|
+
import { Type } from "@sinclair/typebox";
|
|
17
|
+
import * as fs from "node:fs";
|
|
18
|
+
import * as path from "node:path";
|
|
19
|
+
import { AGENT_DIR, MAX_FILE_LINES, HARD_FILE_LIMIT, SOFT_FILE_LIMIT, HINT_FILE_LIMIT } from "./lib/types";
|
|
20
|
+
import { scanMemoryDir, parseFileName, type MemoryEntry } from "./lib/memory-parser";
|
|
21
|
+
import { rebuildIndex } from "./lib/writer";
|
|
22
|
+
import { registerMemoryHook } from "./lib/memory-hook";
|
|
23
|
+
import { detectConflicts } from "./lib/conflict-detect";
|
|
24
|
+
|
|
25
|
+
export default function memoryToolsExtension(pi: ExtensionAPI) {
|
|
26
|
+
|
|
27
|
+
// ── before_agent_start: 注入记忆说明 + 索引到 systemPrompt ──
|
|
28
|
+
registerMemoryHook(pi);
|
|
29
|
+
|
|
30
|
+
// ── memory_index: 查询记忆清单 ──────────────────────
|
|
31
|
+
pi.registerTool({
|
|
32
|
+
name: "memory_index",
|
|
33
|
+
label: "Memory Index",
|
|
34
|
+
description: [
|
|
35
|
+
"扫描并返回所有记忆文件的索引清单(L1 全局 + L2 项目)。",
|
|
36
|
+
"从文件名解析 topic 和关键词,返回结构化表格。",
|
|
37
|
+
"用于:了解已有记忆、判断重复、决定是否新建文件。",
|
|
38
|
+
].join("\n"),
|
|
39
|
+
parameters: Type.Object({
|
|
40
|
+
scope: Type.Optional(Type.Union([
|
|
41
|
+
Type.Literal("all"),
|
|
42
|
+
Type.Literal("L1"),
|
|
43
|
+
Type.Literal("L2"),
|
|
44
|
+
], { description: "扫描范围:all=全部,L1=全局,L2=项目。默认 all。", default: "all" })),
|
|
45
|
+
}),
|
|
46
|
+
async execute(toolCallId, params: { scope?: "all" | "L1" | "L2" }, signal, onUpdate, ctx) {
|
|
47
|
+
const cwd = (ctx as any).cwd || process.cwd();
|
|
48
|
+
const l1Dir = path.join(AGENT_DIR, "memory");
|
|
49
|
+
const l2Dir = path.join(cwd, ".pi", "memory");
|
|
50
|
+
const entries: MemoryEntry[] = [];
|
|
51
|
+
|
|
52
|
+
if ((params.scope || "all") !== "L2") {
|
|
53
|
+
entries.push(...scanMemoryDir(l1Dir, "L1"));
|
|
54
|
+
// 顺便重建索引,修复手动删文件后的不一致
|
|
55
|
+
const l1IndexPath = path.join(AGENT_DIR, "MEMORY.md");
|
|
56
|
+
if (fs.existsSync(l1Dir)) rebuildIndex(l1Dir, l1IndexPath, "L1");
|
|
57
|
+
}
|
|
58
|
+
if ((params.scope || "all") !== "L1") {
|
|
59
|
+
entries.push(...scanMemoryDir(l2Dir, "L2"));
|
|
60
|
+
// 顺便重建索引,修复手动删文件后的不一致
|
|
61
|
+
const l2IndexPath = path.join(cwd, ".pi", "memory", "MEMORY.md");
|
|
62
|
+
if (fs.existsSync(l2Dir)) rebuildIndex(l2Dir, l2IndexPath, "L2");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (entries.length === 0) {
|
|
66
|
+
return { content: [{ type: "text", text: "未找到任何记忆文件。" }], details: {} };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
entries.sort((a, b) => {
|
|
70
|
+
if (a.scope !== b.scope) return a.scope === "L1" ? -1 : 1;
|
|
71
|
+
return a.name.localeCompare(b.name);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
const lines: string[] = ["# 记忆文件索引\n"];
|
|
75
|
+
let currentScope = "";
|
|
76
|
+
for (const e of entries) {
|
|
77
|
+
if (e.scope !== currentScope) {
|
|
78
|
+
currentScope = e.scope;
|
|
79
|
+
const scopeDir = e.scope === "L1" ? l1Dir : l2Dir;
|
|
80
|
+
lines.push(`\n## ${e.scope} — ${scopeDir}\n`);
|
|
81
|
+
lines.push("| topic | keywords | 行数 | 描述 |");
|
|
82
|
+
lines.push("|-------|----------|------|------|");
|
|
83
|
+
}
|
|
84
|
+
const topic = e.topic || e.name;
|
|
85
|
+
const kws = e.keywords.join(", ") || "";
|
|
86
|
+
const lineWarning = e.lines > MAX_FILE_LINES ? " ⚠️" : "";
|
|
87
|
+
lines.push(`| ${topic} | ${kws} | ${e.lines}${lineWarning} | ${e.description} |`);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return { content: [{ type: "text", text: lines.join("\n") }], details: {} };
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
// ── memory_update: 写文件 + 更新索引 ─────────────────
|
|
95
|
+
// AI 负责:看 memory_index → 判断重复 → 决定文件名 → 调用本工具
|
|
96
|
+
pi.registerTool({
|
|
97
|
+
name: "memory_update",
|
|
98
|
+
label: "Memory Update",
|
|
99
|
+
description: fs.readFileSync(
|
|
100
|
+
path.join(__dirname, "prompts", "update-description.md"), "utf-8"
|
|
101
|
+
).trim(),
|
|
102
|
+
parameters: Type.Object({
|
|
103
|
+
fileName: Type.String({ description: "目标文件名,格式 topic--kw1,kw2,kw3.md" }),
|
|
104
|
+
content: Type.String({ description: "完整的记忆文件内容(markdown)" }),
|
|
105
|
+
scope: Type.Optional(Type.Union([
|
|
106
|
+
Type.Literal("L1"),
|
|
107
|
+
Type.Literal("L2"),
|
|
108
|
+
], { description: "目标作用域。默认 L2。", default: "L2" })),
|
|
109
|
+
}),
|
|
110
|
+
async execute(toolCallId, params: { fileName: string; content: string; scope?: "L1" | "L2" }, signal, onUpdate, ctx) {
|
|
111
|
+
const cwd = (ctx as any).cwd || process.cwd();
|
|
112
|
+
const effectiveScope: "L1" | "L2" = params.scope === "L1" ? "L1" : "L2";
|
|
113
|
+
const targetDir = effectiveScope === "L1"
|
|
114
|
+
? path.join(AGENT_DIR, "memory")
|
|
115
|
+
: path.join(cwd, ".pi", "memory");
|
|
116
|
+
const indexPath = effectiveScope === "L1"
|
|
117
|
+
? path.join(AGENT_DIR, "MEMORY.md")
|
|
118
|
+
: path.join(cwd, ".pi", "memory", "MEMORY.md");
|
|
119
|
+
|
|
120
|
+
fs.mkdirSync(targetDir, { recursive: true });
|
|
121
|
+
|
|
122
|
+
// 安全检查:只允许 .md 文件,不允许路径遍历
|
|
123
|
+
const fileName = params.fileName.replace(/\.md$/, "") + ".md";
|
|
124
|
+
if (fileName.includes("/") || fileName.includes("\\")) {
|
|
125
|
+
return { content: [{ type: "text", text: "❌ 文件名不允许包含路径分隔符" }], details: {} };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const filePath = path.join(targetDir, fileName);
|
|
129
|
+
const parsed = parseFileName(fileName);
|
|
130
|
+
const isOverwrite = fs.existsSync(filePath);
|
|
131
|
+
const contentBytes = Buffer.byteLength(params.content, "utf-8");
|
|
132
|
+
const MAX_CONTENT_BYTES = 50_000; // 50KB
|
|
133
|
+
if (contentBytes > MAX_CONTENT_BYTES) {
|
|
134
|
+
return { content: [{ type: "text", text: `❌ 内容 ${(contentBytes / 1024).toFixed(1)}KB 超过 ${MAX_CONTENT_BYTES / 1000}KB 限制` }], details: {} };
|
|
135
|
+
}
|
|
136
|
+
const contentLines = params.content.split("\n").length;
|
|
137
|
+
|
|
138
|
+
// 行数硬限制
|
|
139
|
+
if (contentLines > MAX_FILE_LINES) {
|
|
140
|
+
return { content: [{ type: "text", text: `❌ 内容 ${contentLines} 行,超过 ${MAX_FILE_LINES} 行硬限制,请精简或拆分后重试` }], details: {} };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// 记忆总数硬限制 — 先检查再写
|
|
144
|
+
const totalFiles = fs.existsSync(targetDir)
|
|
145
|
+
? fs.readdirSync(targetDir).filter(f => f.endsWith(".md") && f !== "MEMORY.md").length
|
|
146
|
+
: 0;
|
|
147
|
+
// 覆盖已有文件不增加总数,不算超标
|
|
148
|
+
const effectiveTotal = isOverwrite ? totalFiles : totalFiles + 1;
|
|
149
|
+
if (effectiveTotal > HARD_FILE_LIMIT) {
|
|
150
|
+
return {
|
|
151
|
+
content: [{ type: "text", text: `❌ ${effectiveScope} 记忆文件已达 ${totalFiles} 个(硬限制 ${HARD_FILE_LIMIT}),拒绝写入。请先用 memory_index 查看,合并/删除后重试。` }],
|
|
152
|
+
details: {},
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// 写入前检测冲突:同 topic 或高关键词重叠 → 硬拒绝
|
|
157
|
+
if (fs.existsSync(targetDir)) {
|
|
158
|
+
const conflicts = detectConflicts(targetDir, fileName, parsed);
|
|
159
|
+
if (conflicts.length > 0) {
|
|
160
|
+
const conflictList = conflicts.map(c => ` - ${c.name} (${c.reason})`).join("\n");
|
|
161
|
+
return {
|
|
162
|
+
content: [{ type: "text", text: [
|
|
163
|
+
`❌ 检测到相关记忆,拒绝写入。请先处理冲突:`,
|
|
164
|
+
``,
|
|
165
|
+
conflictList,
|
|
166
|
+
``,
|
|
167
|
+
`处理方法(按优先级):`,
|
|
168
|
+
`1. 合并:内容互补 → 读取所有冲突文件 → 整合为一份 → 用 memory_update 覆盖其中一个的文件名 → 删除其余文件`,
|
|
169
|
+
`2. 取代:新内容完全覆盖旧结论 → 改用冲突文件的文件名写入(覆盖),不要新建`,
|
|
170
|
+
`3. 确认不相关 → 在 fileName 中调整 topic 或关键词使重叠 < 3,再重试`,
|
|
171
|
+
``,
|
|
172
|
+
`⚠️ 不允许无视此提示。必须处理冲突后才能写入。`,
|
|
173
|
+
].join("\n") }],
|
|
174
|
+
details: {},
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// 所有检查通过,写入文件
|
|
180
|
+
fs.writeFileSync(filePath, params.content, "utf-8");
|
|
181
|
+
// 全量重建索引,保证索引 === 磁盘
|
|
182
|
+
rebuildIndex(targetDir, indexPath, effectiveScope);
|
|
183
|
+
|
|
184
|
+
// 成功消息
|
|
185
|
+
const action = isOverwrite ? "覆盖" : "新建";
|
|
186
|
+
const totalWarning = totalFiles > SOFT_FILE_LIMIT
|
|
187
|
+
? `\n⚠️ ${effectiveScope} 记忆文件 ${totalFiles} 个,接近 ${HARD_FILE_LIMIT} 硬限制,请尽快清理合并`
|
|
188
|
+
: totalFiles > HINT_FILE_LIMIT
|
|
189
|
+
? `\n💡 ${effectiveScope} 记忆文件 ${totalFiles} 个,注意控制数量`
|
|
190
|
+
: "";
|
|
191
|
+
|
|
192
|
+
return {
|
|
193
|
+
content: [{ type: "text", text: `✅ ${action}: ${fileName} (${contentLines} 行)${totalWarning}` }],
|
|
194
|
+
details: {},
|
|
195
|
+
};
|
|
196
|
+
},
|
|
197
|
+
});
|
|
198
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memory 冲突检测 — 同目录中 topic 或关键词重叠检查
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import * as fs from "node:fs";
|
|
6
|
+
import * as path from "node:path";
|
|
7
|
+
import { parseFileName } from "./memory-parser";
|
|
8
|
+
|
|
9
|
+
/** 检测同目录中与目标文件存在 topic 或关键词重叠的文件 */
|
|
10
|
+
export function detectConflicts(
|
|
11
|
+
dir: string,
|
|
12
|
+
newFileName: string,
|
|
13
|
+
newParsed: ReturnType<typeof parseFileName>,
|
|
14
|
+
): Array<{ name: string; reason: string }> {
|
|
15
|
+
const results: Array<{ name: string; reason: string }> = [];
|
|
16
|
+
const newKeywords = new Set(newParsed.keywords);
|
|
17
|
+
const newTopic = newParsed.topic;
|
|
18
|
+
|
|
19
|
+
for (const f of fs.readdirSync(dir)) {
|
|
20
|
+
if (!f.endsWith(".md") || f === "MEMORY.md" || f === newFileName) continue;
|
|
21
|
+
const existing = parseFileName(f);
|
|
22
|
+
if (!existing) continue;
|
|
23
|
+
|
|
24
|
+
// 同 topic → 冲突
|
|
25
|
+
if (existing.topic === newTopic) {
|
|
26
|
+
const lines = fs.readFileSync(path.join(dir, f), "utf-8").split("\n").length;
|
|
27
|
+
results.push({ name: f, reason: `同topic, ${lines}行` });
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
// 关键词重叠 ≥ 3 → 冲突
|
|
31
|
+
const overlap = existing.keywords.filter((k: string) => newKeywords.has(k)).length;
|
|
32
|
+
if (overlap >= 3) {
|
|
33
|
+
const lines = fs.readFileSync(path.join(dir, f), "utf-8").split("\n").length;
|
|
34
|
+
results.push({ name: f, reason: `${overlap}关键词重叠, ${lines}行` });
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return results;
|
|
38
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memory 注入 — before_agent_start hook 注册
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import * as fs from "node:fs";
|
|
6
|
+
import * as path from "node:path";
|
|
7
|
+
import type { ExtensionAPI, BeforeAgentStartEvent, BeforeAgentStartEventResult } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import { resolveMemoryInjection } from "./memory-inject";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 注册 before_agent_start hook:
|
|
12
|
+
* 1. 注入 memory-prompt.md 说明文本
|
|
13
|
+
* 2. 注入 L1/L2 MEMORY.md 索引内容
|
|
14
|
+
*/
|
|
15
|
+
export function registerMemoryHook(pi: ExtensionAPI): void {
|
|
16
|
+
const memoryPromptPath = path.join(__dirname, "..", "memory-prompt.md");
|
|
17
|
+
let memoryPrompt = "";
|
|
18
|
+
try {
|
|
19
|
+
if (fs.existsSync(memoryPromptPath)) {
|
|
20
|
+
memoryPrompt = fs.readFileSync(memoryPromptPath, "utf-8").trim();
|
|
21
|
+
}
|
|
22
|
+
} catch { // 文件不存在或权限异常 → 跳过注入
|
|
23
|
+
/* ignore */
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
if (!memoryPrompt) return;
|
|
27
|
+
|
|
28
|
+
pi.on("before_agent_start", async (event: BeforeAgentStartEvent): Promise<BeforeAgentStartEventResult> => {
|
|
29
|
+
const cwd = event.systemPromptOptions?.cwd || process.cwd();
|
|
30
|
+
const injection = resolveMemoryInjection(cwd);
|
|
31
|
+
const parts = [memoryPrompt];
|
|
32
|
+
if (injection) parts.push(injection);
|
|
33
|
+
return {
|
|
34
|
+
systemPrompt: event.systemPrompt + "\n\n" + parts.join("\n\n"),
|
|
35
|
+
};
|
|
36
|
+
});
|
|
37
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memory 注入 — 读取 MEMORY.md 索引并拼接为 systemPrompt 注入文本
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import * as fs from "node:fs";
|
|
6
|
+
import * as path from "node:path";
|
|
7
|
+
import { AGENT_DIR } from "./types";
|
|
8
|
+
|
|
9
|
+
// ── 注入截断常量 ─────────────────────────────────────────
|
|
10
|
+
|
|
11
|
+
/** 注入索引的最大行数 */
|
|
12
|
+
const MAX_MEMORY_LINES = 200;
|
|
13
|
+
|
|
14
|
+
/** 注入索引的最大字节数 */
|
|
15
|
+
const MAX_MEMORY_BYTES = 25_000;
|
|
16
|
+
|
|
17
|
+
// ── 工具函数 ─────────────────────────────────────────────
|
|
18
|
+
|
|
19
|
+
/** 读取文件,成功返回 trim 内容,否则空字符串 */
|
|
20
|
+
export function readMemoryFile(filePath: string): string {
|
|
21
|
+
try {
|
|
22
|
+
if (fs.existsSync(filePath)) return fs.readFileSync(filePath, "utf-8").trim();
|
|
23
|
+
} catch { // 文件不存在或权限异常 → 降级为空字符串
|
|
24
|
+
}
|
|
25
|
+
return "";
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** 截断超长记忆索引 */
|
|
29
|
+
export function truncateMemory(raw: string): string {
|
|
30
|
+
const lines = raw.split("\n");
|
|
31
|
+
let truncated =
|
|
32
|
+
lines.length > MAX_MEMORY_LINES
|
|
33
|
+
? lines.slice(0, MAX_MEMORY_LINES).join("\n")
|
|
34
|
+
: raw;
|
|
35
|
+
if (truncated.length > MAX_MEMORY_BYTES) {
|
|
36
|
+
const cutAt = truncated.lastIndexOf("\n", MAX_MEMORY_BYTES);
|
|
37
|
+
truncated = truncated.slice(0, cutAt > 0 ? cutAt : MAX_MEMORY_BYTES);
|
|
38
|
+
}
|
|
39
|
+
if (truncated.length < raw.length) {
|
|
40
|
+
truncated += "\n\n> ⚠️ MEMORY.md 索引已截断。";
|
|
41
|
+
}
|
|
42
|
+
return truncated;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 拼接记忆注入文本。
|
|
47
|
+
* @returns 完整的注入文本,或 null(无记忆时)
|
|
48
|
+
*/
|
|
49
|
+
export function buildMemoryPrompt(
|
|
50
|
+
globalMemory: string,
|
|
51
|
+
projectMemory: string,
|
|
52
|
+
): string | null {
|
|
53
|
+
const entries: string[] = [];
|
|
54
|
+
if (globalMemory) entries.push(globalMemory);
|
|
55
|
+
if (projectMemory) entries.push(projectMemory);
|
|
56
|
+
if (entries.length === 0) return null;
|
|
57
|
+
return "## 记忆\n\n" + entries.join("\n\n");
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 读取 L1/L2 的 MEMORY.md 索引,返回注入文本。
|
|
62
|
+
* 供 before_agent_start hook 调用。
|
|
63
|
+
*/
|
|
64
|
+
export function resolveMemoryInjection(cwd: string): string | null {
|
|
65
|
+
const l1Path = path.join(AGENT_DIR, "MEMORY.md");
|
|
66
|
+
const l2Path = path.join(cwd, ".pi", "memory", "MEMORY.md");
|
|
67
|
+
|
|
68
|
+
const globalMemory = readMemoryFile(l1Path);
|
|
69
|
+
const projectMemory = truncateMemory(readMemoryFile(l2Path));
|
|
70
|
+
|
|
71
|
+
return buildMemoryPrompt(globalMemory, projectMemory);
|
|
72
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memory Parser — 共享的记忆文件名解析与目录扫描
|
|
3
|
+
*
|
|
4
|
+
* 文件名格式:topic--kw1,kw2,kw3,kw4,kw5.md
|
|
5
|
+
* -- 分隔 topic 和关键词
|
|
6
|
+
* , 分隔关键词
|
|
7
|
+
*
|
|
8
|
+
* 被 memory 扩展和 smart-context 扩展共同使用。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import * as fs from "node:fs";
|
|
12
|
+
import * as path from "node:path";
|
|
13
|
+
|
|
14
|
+
// ── 类型定义 ─────────────────────────────────────────────
|
|
15
|
+
|
|
16
|
+
export interface MemoryEntry {
|
|
17
|
+
name: string;
|
|
18
|
+
file: string;
|
|
19
|
+
description: string;
|
|
20
|
+
lines: number;
|
|
21
|
+
scope: "L1" | "L2";
|
|
22
|
+
topic: string;
|
|
23
|
+
keywords: string[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// ── 文件名解析 ───────────────────────────────────────────
|
|
27
|
+
|
|
28
|
+
/** 从文件名解析 topic 和 keywords
|
|
29
|
+
*
|
|
30
|
+
* 格式:topic--kw1,kw2,kw3.md
|
|
31
|
+
* 无 -- 时 topic = basename(兼容旧格式)
|
|
32
|
+
*/
|
|
33
|
+
export function parseFileName(fileName: string): { topic: string; keywords: string[] } {
|
|
34
|
+
if (fileName == null) return { topic: "", keywords: [] };
|
|
35
|
+
const base = fileName.replace(/\.md$/, "");
|
|
36
|
+
const idx = base.indexOf("--");
|
|
37
|
+
if (idx === -1) {
|
|
38
|
+
return { topic: base, keywords: [] };
|
|
39
|
+
}
|
|
40
|
+
const topic = base.substring(0, idx);
|
|
41
|
+
const kwStr = base.substring(idx + 2);
|
|
42
|
+
const keywords = kwStr ? kwStr.split(",") : [];
|
|
43
|
+
return { topic, keywords };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 生成文件名:topic--kw1,kw2,...md */
|
|
47
|
+
export function buildFileName(topic: string, keywords: string[]): string {
|
|
48
|
+
const kwPart = keywords.length > 0 ? keywords.join(",") : "";
|
|
49
|
+
const base = kwPart ? `${topic}--${kwPart}` : topic;
|
|
50
|
+
return `${base}.md`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// ── 目录扫描 ─────────────────────────────────────────────
|
|
54
|
+
|
|
55
|
+
/** 扫描目录下的记忆文件,从文件名解析 topic + keywords */
|
|
56
|
+
export function scanMemoryDir(dir: string, scope: "L1" | "L2"): MemoryEntry[] {
|
|
57
|
+
const entries: MemoryEntry[] = [];
|
|
58
|
+
if (!fs.existsSync(dir)) return entries;
|
|
59
|
+
|
|
60
|
+
const files = fs.readdirSync(dir)
|
|
61
|
+
.filter(f => f.endsWith(".md") && f !== "MEMORY.md")
|
|
62
|
+
.sort();
|
|
63
|
+
|
|
64
|
+
for (const file of files) {
|
|
65
|
+
const filePath = path.join(dir, file);
|
|
66
|
+
try {
|
|
67
|
+
const content = fs.readFileSync(filePath, "utf-8");
|
|
68
|
+
const lines = content.split("\n").length;
|
|
69
|
+
const titleLine = content.split("\n").find(l => l.startsWith("# "));
|
|
70
|
+
const description = titleLine?.replace(/^#\s+/, "") || "";
|
|
71
|
+
const parsed = parseFileName(file);
|
|
72
|
+
entries.push({
|
|
73
|
+
name: file.replace(".md", ""),
|
|
74
|
+
file,
|
|
75
|
+
description,
|
|
76
|
+
lines,
|
|
77
|
+
scope,
|
|
78
|
+
topic: parsed.topic,
|
|
79
|
+
keywords: parsed.keywords,
|
|
80
|
+
});
|
|
81
|
+
} catch { // 文件读取失败 → 用降级信息填充
|
|
82
|
+
entries.push({
|
|
83
|
+
name: file.replace(".md", ""),
|
|
84
|
+
file,
|
|
85
|
+
description: "(读取失败)",
|
|
86
|
+
lines: 0,
|
|
87
|
+
scope,
|
|
88
|
+
topic: parseFileName(file).topic,
|
|
89
|
+
keywords: parseFileName(file).keywords,
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return entries;
|
|
95
|
+
}
|
package/lib/types.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memory Tools — 公共类型与常量
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import * as path from "node:path";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
|
|
8
|
+
export interface MemoryEntry {
|
|
9
|
+
name: string;
|
|
10
|
+
file: string;
|
|
11
|
+
description: string;
|
|
12
|
+
lines: number;
|
|
13
|
+
scope: "L1" | "L2";
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** L1 全局目录 */
|
|
17
|
+
export const AGENT_DIR = path.join(homedir(), ".pi/agent");
|
|
18
|
+
|
|
19
|
+
/** 记忆文件行数上限 */
|
|
20
|
+
export const MAX_FILE_LINES = 200;
|
|
21
|
+
|
|
22
|
+
/** 记忆文件合并后行数上限 */
|
|
23
|
+
export const MAX_MERGED_LINES = MAX_FILE_LINES * 2;
|
|
24
|
+
|
|
25
|
+
/** 记忆文件总数硬限制(超过拒绝写入) */
|
|
26
|
+
export const HARD_FILE_LIMIT = 40;
|
|
27
|
+
|
|
28
|
+
/** 记忆文件总数软限制(超过发出警告) */
|
|
29
|
+
export const SOFT_FILE_LIMIT = 25;
|
|
30
|
+
|
|
31
|
+
/** 记忆文件总数提示阈值 */
|
|
32
|
+
export const HINT_FILE_LIMIT = 20;
|
package/lib/writer.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memory Tools — 文件写入与索引重建
|
|
3
|
+
*
|
|
4
|
+
* 索引(MEMORY.md)以磁盘文件为唯一真相源。
|
|
5
|
+
* 每次 write 后全量重建索引,保证索引与磁盘始终一致。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import * as fs from "node:fs";
|
|
9
|
+
import * as path from "node:path";
|
|
10
|
+
import { scanMemoryDir } from "./memory-parser";
|
|
11
|
+
import { MAX_FILE_LINES } from "./types";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* 全量重建 MEMORY.md 索引
|
|
15
|
+
*
|
|
16
|
+
* 扫描 targetDir 下所有 .md 文件(排除 MEMORY.md 自身),
|
|
17
|
+
* 生成 表格 + 链接区,覆盖写入 indexPath。
|
|
18
|
+
*
|
|
19
|
+
* 这是保证「索引 === 磁盘」的唯一函数。
|
|
20
|
+
*/
|
|
21
|
+
export function rebuildIndex(targetDir: string, indexPath: string, scope: "L1" | "L2"): void {
|
|
22
|
+
const entries = scanMemoryDir(targetDir, scope);
|
|
23
|
+
|
|
24
|
+
if (entries.length === 0) {
|
|
25
|
+
// 没有记忆文件时,写一个空索引(或删除索引)
|
|
26
|
+
if (fs.existsSync(indexPath)) {
|
|
27
|
+
fs.writeFileSync(indexPath, "", "utf-8");
|
|
28
|
+
}
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const lines: string[] = [
|
|
33
|
+
"# Memory Index",
|
|
34
|
+
"",
|
|
35
|
+
"> 自动生成 — 列出所有记忆文件及其关键词摘要",
|
|
36
|
+
"",
|
|
37
|
+
`## 文件清单 (${entries.length})`,
|
|
38
|
+
"",
|
|
39
|
+
"| # | 文件 | 关键词 |",
|
|
40
|
+
"|---|------|--------|",
|
|
41
|
+
];
|
|
42
|
+
|
|
43
|
+
for (let i = 0; i < entries.length; i++) {
|
|
44
|
+
const e = entries[i];
|
|
45
|
+
const kws = e.keywords.join(", ") || "";
|
|
46
|
+
lines.push(`| ${i + 1} | ${e.topic} | ${kws} |`);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
lines.push("");
|
|
50
|
+
|
|
51
|
+
for (const e of entries) {
|
|
52
|
+
lines.push(`- [${e.topic}](${e.file})`);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
lines.push(""); // trailing newline
|
|
56
|
+
|
|
57
|
+
fs.mkdirSync(path.dirname(indexPath), { recursive: true });
|
|
58
|
+
fs.writeFileSync(indexPath, lines.join("\n"), "utf-8");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 检查文件行数是否超限,返回警告或 null */
|
|
62
|
+
export function checkLineCount(filePath: string): string | null {
|
|
63
|
+
if (!fs.existsSync(filePath)) return null;
|
|
64
|
+
const lines = fs.readFileSync(filePath, "utf-8").split("\n").length;
|
|
65
|
+
if (lines > MAX_FILE_LINES) {
|
|
66
|
+
return `⚠️ ${filePath} 超过 ${MAX_FILE_LINES} 行(当前 ${lines} 行),请拆分`;
|
|
67
|
+
}
|
|
68
|
+
return null;
|
|
69
|
+
}
|
package/memory-prompt.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Memory
|
|
2
|
+
|
|
3
|
+
你有基于文件的持久记忆。会话间保留,每轮自动加载索引到上下文。
|
|
4
|
+
|
|
5
|
+
两个记忆目录:
|
|
6
|
+
- **全局** `~/.pi/agent/memory/` — 跨项目通用(工具链、pi 基础设施、编码纪律)
|
|
7
|
+
- **项目** `.pi/memory/` — 项目级(架构决策、策略结论、踩坑记录)
|
|
8
|
+
|
|
9
|
+
需要具体记忆内容时:`read .pi/memory/{文件名}`(项目)或 `read ~/.pi/agent/memory/{文件名}`(全局)。
|
|
10
|
+
|
|
11
|
+
记忆可能过期,引用函数/路径前先验证是否还存在。
|
package/package.json
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "pi-ate-memory",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "File-based persistent memory for AI coding agents",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"pi-package"
|
|
7
|
+
],
|
|
8
|
+
"type": "commonjs",
|
|
9
|
+
"main": "index.ts",
|
|
10
|
+
"types": "index.ts",
|
|
11
|
+
"scripts": {
|
|
12
|
+
"test": "vitest run",
|
|
13
|
+
"typecheck": "tsc --noEemit"
|
|
14
|
+
},
|
|
15
|
+
"peerDependencies": {
|
|
16
|
+
"@earendil-works/pi-coding-agent": ">=1.0.0"
|
|
17
|
+
},
|
|
18
|
+
"peerDependenciesMeta": {
|
|
19
|
+
"@earendil-works/pi-coding-agent": {
|
|
20
|
+
"optional": true
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"@sinclair/typebox": "^0.34.49",
|
|
25
|
+
"@types/node": "^25.6.2",
|
|
26
|
+
"@vitest/coverage-v8": "^3.2.4",
|
|
27
|
+
"typescript": "^6.0.3",
|
|
28
|
+
"vitest": "^3.0.0"
|
|
29
|
+
},
|
|
30
|
+
"pi": {
|
|
31
|
+
"extensions": [
|
|
32
|
+
"."
|
|
33
|
+
],
|
|
34
|
+
"skills": [
|
|
35
|
+
"skills"
|
|
36
|
+
],
|
|
37
|
+
"prompts": [
|
|
38
|
+
"prompts"
|
|
39
|
+
]
|
|
40
|
+
},
|
|
41
|
+
"files": [
|
|
42
|
+
"index.ts",
|
|
43
|
+
"lib/",
|
|
44
|
+
"prompts/",
|
|
45
|
+
"memory-prompt.md",
|
|
46
|
+
"README.md",
|
|
47
|
+
"README.en.md",
|
|
48
|
+
"tsconfig.json",
|
|
49
|
+
"package.json"
|
|
50
|
+
],
|
|
51
|
+
"homepage": "https://catlain.github.io/pi-atelier/",
|
|
52
|
+
"repository": {
|
|
53
|
+
"type": "git",
|
|
54
|
+
"url": "git+ssh://git@github.com:catlain/pi-memory.git"
|
|
55
|
+
},
|
|
56
|
+
"bugs": {
|
|
57
|
+
"url": "https://github.com/catlain/pi-memory/issues"
|
|
58
|
+
},
|
|
59
|
+
"license": "MIT"
|
|
60
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
记忆写入:写文件 + 更新 MEMORY.md 索引,一步完成。
|
|
2
|
+
|
|
3
|
+
⚠️ 写入前必做检查(按顺序):
|
|
4
|
+
1. 先调 memory_index 查看已有文件,判断是否重复或应合并
|
|
5
|
+
2. 发现同主题/高重叠的已有记忆 → 先合并/覆盖旧文件,再调用本工具
|
|
6
|
+
3. 确认文件名符合格式规范(见下方)
|
|
7
|
+
|
|
8
|
+
文件名格式:topic--kw1,kw2,kw3,kw4,kw5.md
|
|
9
|
+
- topic:英文短标识,代表记忆主题
|
|
10
|
+
- kw1~kw5:最多 5 个关键词,用逗号分隔
|
|
11
|
+
- 例:guard_agent_end--guard,agent_end,git,提交,记忆更新.md
|
|
12
|
+
|
|
13
|
+
规范:
|
|
14
|
+
1. 每个文件 1 个 topic,关键词最多 5 个
|
|
15
|
+
2. 单文件上限 200 行,超过需拆分(工具会拒绝写入)
|
|
16
|
+
3. 标题第二行写 关键词:`kw1` `kw2` ...
|
|
17
|
+
|
|
18
|
+
重复/冗余处理指引:
|
|
19
|
+
- 同主题多文件(topic 相同或关键词 3+ 重叠)→ 合并为单文件
|
|
20
|
+
- 旧结论已被新结论取代 → 用新内容覆盖旧文件(同名),不要新建
|
|
21
|
+
- 不确定是否重复 → 先 memory_index 确认,不要盲目新建
|
|
22
|
+
- 记忆文件总数超过 25 个时 → 主动考虑合并/归档,减少碎片化
|
|
23
|
+
- 记忆文件总数超过 40 个时 → 工具拒绝写入,必须先清理
|
|
24
|
+
|
|
25
|
+
清理操作步骤(记忆文件过多时执行):
|
|
26
|
+
A. 同主题合并:read 所有同 topic/高关键词重叠的文件 → 整合为一份 → memory_update 覆盖 → 删除旧文件
|
|
27
|
+
B. 废弃归档:过时结论被新文件取代 → 删除旧文件,更新 MEMORY.md 索引
|
|
28
|
+
C. 超长拆分:>200 行的文件按子主题拆分为多文件,每文件独立 topic
|
|
29
|
+
D. 索引同步:清理后用 read 验证 MEMORY.md 条目与实际文件一致
|