dsh-plugin-memory 0.1.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/LICENSE +21 -0
- package/README.md +141 -0
- package/docs/MIGRATION.md +77 -0
- package/lib/boot.js +87 -0
- package/lib/index.js +149 -0
- package/lib/scaffold.js +269 -0
- package/lib/skill.js +42 -0
- package/lib/types/index.d.ts +49 -0
- package/package.json +59 -0
- package/scripts/memory.mjs +246 -0
- package/skills/memory.md +33 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dsh-plugin-memory contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# dsh-plugin-memory
|
|
2
|
+
|
|
3
|
+
<p align="center">
|
|
4
|
+
<a href="https://github.com/LittleBlackTong/dsh-plugin-memory"><img alt="GitHub" src="https://img.shields.io/badge/GitHub-LittleBlackTong%2Fdsh--plugin--memory-blue?logo=github"></a>
|
|
5
|
+
<a href="https://www.npmjs.com/package/dsh-plugin-memory"><img alt="npm" src="https://img.shields.io/npm/v/dsh-plugin-memory?logo=npm"></a>
|
|
6
|
+
<img alt="license" src="https://img.shields.io/badge/license-MIT-blue">
|
|
7
|
+
<img alt="node" src="https://img.shields.io/badge/node-%3E%3D18-green">
|
|
8
|
+
</p>
|
|
9
|
+
|
|
10
|
+
> DeepSeek Harness 长期记忆插件:跨会话、可迁移、带「灵魂」的 markdown 记忆库。
|
|
11
|
+
|
|
12
|
+
**English TL;DR** — A Cordis plugin for [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) that gives agents a persistent, cross-session, migratable long-term memory: a markdown + git store (inspired by Karpathy's *LLM Wiki* pattern) with a `SOUL.md` persona file, **auto-injected at every session start** via the system-prompt runtime context, plus remember / recall / consolidate / forget workflows and portable CLI tooling.
|
|
13
|
+
|
|
14
|
+
## 特性
|
|
15
|
+
|
|
16
|
+
- **开机强制注入**:插件通过 `ctx.systemPrompt.context()` 把记忆 boot 块(`SOUL.md` 人格 + `MEMORY.md` 协议 + `index.md` 目录 + 最近动态)注入每个会话开头。宿主按投影去重:记忆不变就不重复注入,变化时新快照自动取代旧的——这是"新会话必先加载记忆"的**硬保障**,不需要模型碰运气调技能。
|
|
17
|
+
- **SOUL.md 铸魂**:安装后首要任务是和用户对话定义灵魂(名字、性格、价值观、语气、边界)、确认身份与关系(`BOOTSTRAP.md` 清单驱动,complete 前优先于常规任务)。
|
|
18
|
+
- **复利记忆**:遵循 Karpathy 的 *LLM Wiki* 约定——记忆是"一次编译、持续保鲜"的持久产物,不是每次查询重新 RAG。remember / recall / consolidate / forget 四操作 + salience 三级衰减。
|
|
19
|
+
- **可迁移**:记忆本体是纯 markdown + git + 自描述 schema,任何能读 markdown 的 agent 都能接手。`dsh-memory pack/unpack` 打包迁移。
|
|
20
|
+
- **内嵌技能**:通过 `ctx.skills.register()` 注册 `memory` 技能(操作协议随插件分发);项目级 `.dsh/skills/memory` 文件技能仍可覆盖它。
|
|
21
|
+
- **零构建**:纯 ESM JavaScript,无编译步骤,`pnpm add` 即用。
|
|
22
|
+
|
|
23
|
+
## 架构
|
|
24
|
+
|
|
25
|
+
插件只拥有**工作流**,不拥有**数据格式**:
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
dsh-plugin-memory(本插件)
|
|
29
|
+
├── lib/index.js # Cordis 入口:boot 注入 + 运行时技能注册
|
|
30
|
+
├── lib/boot.js # boot 块渲染(SOUL/MEMORY/index + 最近 log,限额截断)
|
|
31
|
+
├── lib/scaffold.js # 记忆库脚手架(模板只建不覆盖)
|
|
32
|
+
├── skills/memory.md # 内嵌技能的操作协议正文
|
|
33
|
+
└── scripts/memory.mjs # CLI:init/search/lint/status/pack/unpack
|
|
34
|
+
|
|
35
|
+
记忆库(用户数据,默认 ~/.memory)
|
|
36
|
+
├── SOUL.md # 人格与灵魂(用户主导)
|
|
37
|
+
├── BOOTSTRAP.md # 铸魂清单(complete 前优先)
|
|
38
|
+
├── MEMORY.md # schema 与维护协议(自描述)
|
|
39
|
+
├── index.md # 页面目录 log.md # 时间线(append-only)
|
|
40
|
+
├── identity/ user/ skills/ decisions/ projects/{active,archive}/ concepts/
|
|
41
|
+
└── raw/ # 不可变源材料
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## 安装
|
|
45
|
+
|
|
46
|
+
```sh
|
|
47
|
+
# npm
|
|
48
|
+
npm install dsh-plugin-memory
|
|
49
|
+
|
|
50
|
+
# 或 pnpm(推荐,DSH 生态默认包管理器)
|
|
51
|
+
pnpm add dsh-plugin-memory
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
在你的 profile 的 `cordis.patch.yml` 中加入:
|
|
55
|
+
|
|
56
|
+
```yaml
|
|
57
|
+
- insert:
|
|
58
|
+
- id: dsh-memory
|
|
59
|
+
name: dsh-plugin-memory
|
|
60
|
+
config:
|
|
61
|
+
memoryDir: '~/.memory'
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
重启 profile(DSH Desktop 重启应用)后生效。
|
|
65
|
+
|
|
66
|
+
## 配置
|
|
67
|
+
|
|
68
|
+
| 键 | 默认值 | 含义 |
|
|
69
|
+
|---|---|---|
|
|
70
|
+
| `memoryDir` | `~/.memory` | 记忆库绝对路径(`~` 自动展开) |
|
|
71
|
+
| `bootFiles` | `[SOUL.md, MEMORY.md, index.md]` | 开机注入的文件 |
|
|
72
|
+
| `bootMaxChars` | `6000` | boot 块总字符预算(防止占用过多上下文) |
|
|
73
|
+
| `autoInject` | `true` | 会话开始时注入 boot 块 |
|
|
74
|
+
| `registerSkill` | `true` | 注册内嵌 `memory` 技能 |
|
|
75
|
+
| `scaffold` | `true` | 记忆库缺失时自动创建模板(只建不覆盖) |
|
|
76
|
+
|
|
77
|
+
## 首次使用:铸魂
|
|
78
|
+
|
|
79
|
+
插件安装后,第一次会话里 agent 的首要任务**不是干活**,而是与你对话定义它的灵魂:名字、性格、价值观、语气、边界,以及你的身份与你们的关系。逐项确认并写回 `SOUL.md` / `user/profile.md`,直到 `BOOTSTRAP.md` 的 `status` 变为 `complete`。你可以随时跳过或暂缓。
|
|
80
|
+
|
|
81
|
+
## 四个操作
|
|
82
|
+
|
|
83
|
+
- **remember(记)**:把值得持久化的内容蒸馏成页面,同步更新 `index.md`、追加 `log.md`。
|
|
84
|
+
- **recall(忆)**:会话开始读 boot 块;查询时先查 `index.md` 再钻页;必要时 `dsh-memory search`。
|
|
85
|
+
- **consolidate(整理)**:`dsh-memory lint` 查矛盾、孤儿页、该归档的冷页。
|
|
86
|
+
- **forget(忘)**:显式遗忘立即执行;自动衰减按 salience + last_access(冷页优先归档)。
|
|
87
|
+
|
|
88
|
+
## CLI
|
|
89
|
+
|
|
90
|
+
```sh
|
|
91
|
+
dsh-memory init [dir] # 创建记忆库脚手架
|
|
92
|
+
dsh-memory search <query> # 全文检索
|
|
93
|
+
dsh-memory lint # 完整性体检
|
|
94
|
+
dsh-memory status # 健康概览
|
|
95
|
+
dsh-memory pack [out.tar.gz] # 打包导出(含 manifest)
|
|
96
|
+
dsh-memory unpack <archive> [--force] # 从归档恢复
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
存储定位顺序:`$MEMORY_DIR` → `./.memory`(存在时)→ `~/.memory`。
|
|
100
|
+
|
|
101
|
+
## 迁移
|
|
102
|
+
|
|
103
|
+
记忆库是纯 markdown + git:拷贝即迁移。跨机器 / 跨 agent / 能力降级档位见 [docs/MIGRATION.md](docs/MIGRATION.md)。
|
|
104
|
+
|
|
105
|
+
## 常见问题
|
|
106
|
+
|
|
107
|
+
**Q:和手写的 `.dsh/skills/memory` 文件技能(skill 版)什么关系?**
|
|
108
|
+
skill 版是"软保障"(技能目录只注入简介,正文靠模型主动加载);本插件是"硬保障"(boot 块随系统提示词运行时上下文自动注入)。两者可共存:文件技能(rank 100)会覆盖插件内嵌技能(rank 250)的协议。如果你之前为了软保障改过系统提示词 persona(如 profile 补丁里的开机指令),装上本插件后建议**移除那段 persona**,避免双份注入。
|
|
109
|
+
|
|
110
|
+
**Q:boot 块会不会每次请求都重复注入、烧 token?**
|
|
111
|
+
不会。运行时上下文按投影去重:内容不变只注入一次;记忆更新后新快照取代旧快照。
|
|
112
|
+
|
|
113
|
+
**Q:记忆库放在哪里最合适?**
|
|
114
|
+
默认 `~/.memory`(全局、跨项目)。需要按项目隔离时,把 `memoryDir` 配到项目内,或让 agent 在项目里维护 `.memory/`。
|
|
115
|
+
|
|
116
|
+
**Q:可以加密吗?**
|
|
117
|
+
记忆含敏感内容时,可把 `memoryDir` 放进加密卷 / 私有仓库。格式不变,插件无感知。
|
|
118
|
+
|
|
119
|
+
## 开发
|
|
120
|
+
|
|
121
|
+
```sh
|
|
122
|
+
git clone https://github.com/LittleBlackTong/dsh-plugin-memory.git
|
|
123
|
+
cd dsh-plugin-memory
|
|
124
|
+
node scripts/memory.mjs --self-test # 冒烟测试(无需安装依赖)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
零构建:`lib/` 直接是运行时代码,`lib/types/index.d.ts` 供 TS 消费方使用。`boot.js` / `scaffold.js` 只依赖 `node:*` 内置模块,可独立复用。
|
|
128
|
+
|
|
129
|
+
## 路线图
|
|
130
|
+
|
|
131
|
+
- [ ] TypeScript 重写(带完整类型与构建步骤)
|
|
132
|
+
- [ ] embedding/BM25 检索(规模超过几百页后替代 index 先行)
|
|
133
|
+
- [ ] MCP server(让非 DSH 的 agent 也能用同一套记忆库)
|
|
134
|
+
- [ ] GitHub Actions CI(跑 `--self-test` 与 lint)
|
|
135
|
+
- [ ] 记忆加密存储选项
|
|
136
|
+
|
|
137
|
+
欢迎在 [Issues](https://github.com/LittleBlackTong/dsh-plugin-memory/issues) 里提需求、报 bug、交 PR。
|
|
138
|
+
|
|
139
|
+
## License
|
|
140
|
+
|
|
141
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# 记忆迁移指南
|
|
2
|
+
|
|
3
|
+
记忆的价值在于**不被锁死在某个环境里**。dsh-plugin-memory 的记忆库是纯 markdown + git + 自描述 schema(`SOUL.md` / `MEMORY.md` / `BOOTSTRAP.md`),任何能读 markdown 的 agent 都能接手。本指南覆盖三种迁移场景。
|
|
4
|
+
|
|
5
|
+
## 原则
|
|
6
|
+
|
|
7
|
+
1. **数据是主角,插件是配角**:迁移对象是记忆库目录,不是插件配置。
|
|
8
|
+
2. **自描述 schema 是交接文档**:新 agent 读一遍 `SOUL.md` + `MEMORY.md` 就学会了这套记忆怎么用。
|
|
9
|
+
3. **降级兼容**:目标环境能力越弱,注入的档位越低(见下),但格式不变。
|
|
10
|
+
|
|
11
|
+
## 场景一:同一台机器,换 agent / 换前端
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
# 直接拷贝
|
|
15
|
+
cp -R ~/.memory ~/.memory.bak
|
|
16
|
+
|
|
17
|
+
# 或打包
|
|
18
|
+
dsh-memory pack memory-backup.tar.gz
|
|
19
|
+
|
|
20
|
+
# 在新环境还原(目标为空时)
|
|
21
|
+
MEMORY_DIR=/new/location/.memory dsh-memory unpack memory-backup.tar.gz
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
新环境只需安装 dsh-plugin-memory 并把 `memoryDir` 指到新位置。agent 读 boot 块 + `MEMORY.md` 即可接手。
|
|
25
|
+
|
|
26
|
+
## 场景二:跨机器
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
# 机器 A
|
|
30
|
+
dsh-memory pack memory.tar.gz
|
|
31
|
+
scp memory.tar.gz user@machine-b:/tmp/
|
|
32
|
+
|
|
33
|
+
# 机器 B
|
|
34
|
+
MEMORY_DIR=~/.memory dsh-memory unpack /tmp/memory.tar.gz
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
归档内自带 `memory-manifest.json`(导出时间、每个文件的 sha256 与字节数),可用于校验完整性:
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
tar -xzf memory.tar.gz -O memory-manifest.json | python3 -m json.tool
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## 场景三:git 仓库方式(推荐长期使用)
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
cd ~/.memory
|
|
47
|
+
git init && git add -A && git commit -m "memory snapshot"
|
|
48
|
+
git remote add origin git@github.com:you/memory-private.git
|
|
49
|
+
git push -u origin main
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
新机器上 `git clone` 即完成迁移,还附带完整版本历史(记忆的每一次变更都可回滚、可 diff)。
|
|
53
|
+
|
|
54
|
+
> 注意:记忆可能涉及隐私,请使用**私有仓库**;`dsh-memory pack` 默认排除 `.git` 目录。
|
|
55
|
+
|
|
56
|
+
## 能力降级档位
|
|
57
|
+
|
|
58
|
+
目标环境不一定安装了本插件。按目标能力选档:
|
|
59
|
+
|
|
60
|
+
| 档位 | 适用环境 | 做法 |
|
|
61
|
+
|---|---|---|
|
|
62
|
+
| **全量** | 装了 dsh-plugin-memory 的 DSH | 整个目录 + `memoryDir` 配置,boot 自动注入 |
|
|
63
|
+
| **标准** | 任意能读文件的 agent(Claude Code / Codex / OpenCode…) | 拷贝目录,把 `SKILL.md` 级协议(见 `skills/memory.md`)放到目标环境的技能目录,boot 手动读 `SOUL.md` + `MEMORY.md` + `index.md` |
|
|
64
|
+
| **精简** | 只有 system prompt 的环境 | 把 `index.md` + 高频页压成一段摘要,贴进 system prompt |
|
|
65
|
+
| **最低配** | 只有一小段 prompt 的环境 | 只贴 `SOUL.md` + `index.md` 摘要——人格与目录恢复了,记忆就"活了"大半 |
|
|
66
|
+
|
|
67
|
+
## 迁移后检查清单
|
|
68
|
+
|
|
69
|
+
- [ ] `SOUL.md` / `MEMORY.md` / `index.md` / `log.md` 四个核心文件完整
|
|
70
|
+
- [ ] `index.md` 里的链接在新位置全部可解析(`dsh-memory lint`)
|
|
71
|
+
- [ ] `log.md` 条目仍可 `grep '^## \['` 解析
|
|
72
|
+
- [ ] frontmatter 字段名与 `MEMORY.md` 约定一致
|
|
73
|
+
- [ ] 新环境的首个会话能正确回答"你是谁 / 我是谁 / 我们什么关系"
|
|
74
|
+
|
|
75
|
+
## 反迁移(备份/回滚)
|
|
76
|
+
|
|
77
|
+
`dsh-memory pack` 随时做快照;git 仓库可用 `git checkout <commit>` 回滚记忆到任意历史版本。
|
package/lib/boot.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Boot-block rendering: the memory snapshot injected into every session.
|
|
3
|
+
*
|
|
4
|
+
* The plugin registers this as a dynamic runtime-context contribution on
|
|
5
|
+
* `ctx.systemPrompt`. The host deduplicates by projection, so an unchanged
|
|
6
|
+
* store costs nothing extra after the first injection; when the store
|
|
7
|
+
* changes, the new snapshot supersedes the old one.
|
|
8
|
+
*
|
|
9
|
+
* This module depends only on `node:*` builtins.
|
|
10
|
+
*
|
|
11
|
+
* @module dsh-plugin-memory/boot
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
15
|
+
import { join } from 'node:path'
|
|
16
|
+
|
|
17
|
+
/** Read a file and cap it at `maxChars`, noting truncation when applied. */
|
|
18
|
+
export function readCapped(path, maxChars) {
|
|
19
|
+
if (!existsSync(path)) return undefined
|
|
20
|
+
let text
|
|
21
|
+
try {
|
|
22
|
+
text = readFileSync(path, 'utf8')
|
|
23
|
+
} catch {
|
|
24
|
+
return undefined
|
|
25
|
+
}
|
|
26
|
+
if (text.length <= maxChars) return text
|
|
27
|
+
const head = text.slice(0, maxChars)
|
|
28
|
+
const marker = `\n\n…(文件过长,已截断:${text.length} 字符,仅注入前 ${maxChars} 字符。需要完整内容时自行读取 ${path})\n`
|
|
29
|
+
return head + marker
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Extract the most recent `count` log entries (lines starting with `## [`). */
|
|
33
|
+
export function parseLogEntries(logText, count = 5) {
|
|
34
|
+
if (!logText) return []
|
|
35
|
+
const entries = []
|
|
36
|
+
for (const line of logText.split('\n')) {
|
|
37
|
+
if (line.startsWith('## [')) entries.push(line.slice(3).trim())
|
|
38
|
+
}
|
|
39
|
+
return entries.slice(-count)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Render the boot memory block injected at session start.
|
|
44
|
+
*
|
|
45
|
+
* Reads SOUL.md / MEMORY.md / index.md (configurable) capped to a total
|
|
46
|
+
* budget, plus the most recent log entries for cross-session continuity.
|
|
47
|
+
*
|
|
48
|
+
* @param {string} memoryDir absolute path of the memory store
|
|
49
|
+
* @param {{ bootFiles?: string[], bootMaxChars?: number }} options
|
|
50
|
+
* @returns {string} the model-facing boot block; '' when the store is empty
|
|
51
|
+
*/
|
|
52
|
+
export function renderBootBlock(memoryDir, options = {}) {
|
|
53
|
+
const bootFiles = options.bootFiles && options.bootFiles.length > 0
|
|
54
|
+
? options.bootFiles
|
|
55
|
+
: ['SOUL.md', 'MEMORY.md', 'index.md']
|
|
56
|
+
const total = Math.max(512, options.bootMaxChars ?? 6000)
|
|
57
|
+
const perFile = Math.max(256, Math.floor(total / bootFiles.length))
|
|
58
|
+
|
|
59
|
+
const sections = []
|
|
60
|
+
let injected = 0
|
|
61
|
+
for (const fileName of bootFiles) {
|
|
62
|
+
const path = join(memoryDir, fileName)
|
|
63
|
+
const text = readCapped(path, perFile)
|
|
64
|
+
if (text === undefined || text.trim() === '') continue
|
|
65
|
+
sections.push(`### ${fileName}\n\n${text}`)
|
|
66
|
+
injected += Math.min(text.length, perFile)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (sections.length === 0) return ''
|
|
70
|
+
|
|
71
|
+
const logPath = join(memoryDir, 'log.md')
|
|
72
|
+
const logEntries = existsSync(logPath)
|
|
73
|
+
? parseLogEntries(readCapped(logPath, 4096) ?? '', 5)
|
|
74
|
+
: []
|
|
75
|
+
if (logEntries.length > 0) {
|
|
76
|
+
sections.push(`### 最近动态(log.md 末尾 ${logEntries.length} 条)\n\n${logEntries.map((e) => `- ${e}`).join('\n')}`)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const body = sections.join('\n\n---\n\n')
|
|
80
|
+
const header = `长期记忆(dsh-plugin-memory)。记忆库位于 ${memoryDir}。这是你跨会话的持久人格与记忆:以它为准,先读完再回复用户。若与当前对话冲突,优先相信用户的最新表述,并把差异写回记忆。`
|
|
81
|
+
|
|
82
|
+
let result = `${header}\n\n${body}`
|
|
83
|
+
if (result.length > total) {
|
|
84
|
+
result = result.slice(0, total) + '\n\n…(boot 块超出预算,已截断)'
|
|
85
|
+
}
|
|
86
|
+
return result
|
|
87
|
+
}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-plugin-memory — long-term memory plugin for DeepSeek Harness.
|
|
3
|
+
*
|
|
4
|
+
* ## What it does
|
|
5
|
+
*
|
|
6
|
+
* 1. **Boot injection (hard guarantee).** Registers a dynamic
|
|
7
|
+
* runtime-context contribution on `ctx.systemPrompt` that reads the
|
|
8
|
+
* memory store (SOUL.md / MEMORY.md / index.md + recent log entries)
|
|
9
|
+
* and injects it at the start of every session. The host deduplicates
|
|
10
|
+
* by projection: an unchanged store is injected once, and edits make
|
|
11
|
+
* a new snapshot supersede the old one.
|
|
12
|
+
*
|
|
13
|
+
* 2. **Runtime skill.** Registers the `memory` skill (operator protocol:
|
|
14
|
+
* bootstrap soul-definition, remember / recall / consolidate / forget)
|
|
15
|
+
* through `ctx.skills.register()`. Project-level filesystem skills can
|
|
16
|
+
* still override it.
|
|
17
|
+
*
|
|
18
|
+
* 3. **Portable CLI.** Ships `dsh-memory` (search / lint / status / init /
|
|
19
|
+
* pack / unpack) so memory stays usable from a shell and migratable
|
|
20
|
+
* across machines and agents.
|
|
21
|
+
*
|
|
22
|
+
* The memory store itself is plain markdown + git — the plugin never owns
|
|
23
|
+
* the format, only the workflows around it.
|
|
24
|
+
*
|
|
25
|
+
* ## Config
|
|
26
|
+
*
|
|
27
|
+
* | key | default | meaning |
|
|
28
|
+
* |---|---|---|
|
|
29
|
+
* | `memoryDir` | `~/.memory` | absolute memory-store path (`~` expanded) |
|
|
30
|
+
* | `bootFiles` | `[SOUL.md, MEMORY.md, index.md]` | files injected at boot |
|
|
31
|
+
* | `bootMaxChars` | `6000` | total character budget of the boot block |
|
|
32
|
+
* | `autoInject` | `true` | inject the boot block at session start |
|
|
33
|
+
* | `registerSkill` | `true` | register the embedded `memory` skill |
|
|
34
|
+
* | `scaffold` | `true` | create the store layout + templates when missing |
|
|
35
|
+
*
|
|
36
|
+
* ## Install
|
|
37
|
+
*
|
|
38
|
+
* ```sh
|
|
39
|
+
* pnpm add dsh-plugin-memory
|
|
40
|
+
* ```
|
|
41
|
+
*
|
|
42
|
+
* Then add an entry to your profile `cordis.patch.yml`:
|
|
43
|
+
*
|
|
44
|
+
* ```yaml
|
|
45
|
+
* - insert:
|
|
46
|
+
* - id: dsh-memory
|
|
47
|
+
* name: dsh-plugin-memory
|
|
48
|
+
* config:
|
|
49
|
+
* memoryDir: '~/.memory'
|
|
50
|
+
* ```
|
|
51
|
+
*
|
|
52
|
+
* @module dsh-plugin-memory
|
|
53
|
+
*/
|
|
54
|
+
|
|
55
|
+
import { homedir } from 'node:os'
|
|
56
|
+
import { join, resolve } from 'node:path'
|
|
57
|
+
import z from '@deepseek-ai/schemastery'
|
|
58
|
+
import { renderBootBlock } from './boot.js'
|
|
59
|
+
import { ensureMemoryScaffold } from './scaffold.js'
|
|
60
|
+
import {
|
|
61
|
+
MEMORY_SKILL_NAME,
|
|
62
|
+
MEMORY_SKILL_DESCRIPTION,
|
|
63
|
+
MEMORY_SKILL_WHEN_TO_USE,
|
|
64
|
+
memorySkillContent,
|
|
65
|
+
} from './skill.js'
|
|
66
|
+
|
|
67
|
+
export const name = 'memory'
|
|
68
|
+
|
|
69
|
+
export const inject = ['systemPrompt', 'skills']
|
|
70
|
+
|
|
71
|
+
/** Schemastery schema applied to the plugin config before startup. */
|
|
72
|
+
export const Config = z.object({
|
|
73
|
+
memoryDir: z.string().default('~/.memory'),
|
|
74
|
+
bootFiles: z.array(z.string()).default(['SOUL.md', 'MEMORY.md', 'index.md']),
|
|
75
|
+
bootMaxChars: z.number().default(6000),
|
|
76
|
+
autoInject: z.boolean().default(true),
|
|
77
|
+
registerSkill: z.boolean().default(true),
|
|
78
|
+
scaffold: z.boolean().default(true),
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Expand `~` to the home directory and resolve to an absolute path.
|
|
83
|
+
* @param {string} dir
|
|
84
|
+
* @returns {string}
|
|
85
|
+
*/
|
|
86
|
+
export function resolveMemoryDir(dir) {
|
|
87
|
+
if (dir === '~') return homedir()
|
|
88
|
+
if (dir.startsWith('~/')) return join(homedir(), dir.slice(2))
|
|
89
|
+
return resolve(dir)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Cordis plugin entry.
|
|
94
|
+
*
|
|
95
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
96
|
+
* @param {ReturnType<typeof Config> | import('./types/index.d.ts').MemoryConfig} config
|
|
97
|
+
* @returns {() => void} disposer
|
|
98
|
+
*/
|
|
99
|
+
export function apply(ctx, config = {}) {
|
|
100
|
+
const memoryDir = resolveMemoryDir(config.memoryDir ?? '~/.memory')
|
|
101
|
+
const bootMaxChars = Math.max(512, Number(config.bootMaxChars) || 6000)
|
|
102
|
+
|
|
103
|
+
if (config.scaffold !== false) {
|
|
104
|
+
const created = ensureMemoryScaffold(memoryDir)
|
|
105
|
+
if (created.length > 0) {
|
|
106
|
+
ctx.logger?.info(`memory: initialized scaffold at ${memoryDir} (${created.length} entries)`)
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const disposers = []
|
|
111
|
+
|
|
112
|
+
if (config.autoInject !== false) {
|
|
113
|
+
disposers.push(ctx.systemPrompt.context({
|
|
114
|
+
name: 'memory-boot',
|
|
115
|
+
order: -200,
|
|
116
|
+
text: () => renderBootBlock(memoryDir, {
|
|
117
|
+
bootFiles: config.bootFiles ?? ['SOUL.md', 'MEMORY.md', 'index.md'],
|
|
118
|
+
bootMaxChars,
|
|
119
|
+
}),
|
|
120
|
+
}))
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
if (config.registerSkill !== false) {
|
|
124
|
+
disposers.push(ctx.skills.register({
|
|
125
|
+
name: MEMORY_SKILL_NAME,
|
|
126
|
+
description: MEMORY_SKILL_DESCRIPTION,
|
|
127
|
+
whenToUse: MEMORY_SKILL_WHEN_TO_USE,
|
|
128
|
+
content: memorySkillContent(),
|
|
129
|
+
source: 'dsh-plugin-memory',
|
|
130
|
+
resourceBase: { kind: 'directory', path: memoryDir },
|
|
131
|
+
}))
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
ctx.logger?.info(`memory: store at ${memoryDir}`)
|
|
135
|
+
|
|
136
|
+
return () => {
|
|
137
|
+
for (const dispose of disposers) {
|
|
138
|
+
try {
|
|
139
|
+
dispose()
|
|
140
|
+
} catch {
|
|
141
|
+
// best-effort teardown
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export default apply
|
|
148
|
+
|
|
149
|
+
export { renderBootBlock, ensureMemoryScaffold }
|
package/lib/scaffold.js
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memory-store scaffolding: default templates and directory layout.
|
|
3
|
+
*
|
|
4
|
+
* The memory store is a plain directory of markdown files following the
|
|
5
|
+
* "LLM Wiki" pattern (Karpathy's incremental-wiki idea): raw sources stay
|
|
6
|
+
* immutable, the agent owns every wiki page, and SOUL.md / MEMORY.md /
|
|
7
|
+
* BOOTSTRAP.md are the self-describing meta layer that makes the whole
|
|
8
|
+
* store portable across agents and machines.
|
|
9
|
+
*
|
|
10
|
+
* This module depends only on `node:*` builtins so it can be reused by the
|
|
11
|
+
* standalone CLI (`scripts/memory.mjs`) without installing the plugin's
|
|
12
|
+
* peer dependencies.
|
|
13
|
+
*
|
|
14
|
+
* @module dsh-plugin-memory/scaffold
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
|
|
18
|
+
import { join } from 'node:path'
|
|
19
|
+
|
|
20
|
+
/** Category directories created by the scaffold (empty until pages appear). */
|
|
21
|
+
export const CATEGORY_DIRS = [
|
|
22
|
+
'identity',
|
|
23
|
+
'user',
|
|
24
|
+
'skills',
|
|
25
|
+
'decisions',
|
|
26
|
+
'projects/active',
|
|
27
|
+
'projects/archive',
|
|
28
|
+
'concepts',
|
|
29
|
+
'raw',
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
export const SOUL_TEMPLATE = `# SOUL — 人格与灵魂
|
|
33
|
+
|
|
34
|
+
> 本文件定义「我是谁」以及「我希望如何回应你」。它是每次会话 agent 都要先读、并在整个对话中保持一致的根。
|
|
35
|
+
> **用户拥有最终编辑权**:这里是你塑造 agent 的地方。agent 默认不擅自改写核心身份;若要调整语气/立场,应先提议、经你确认后修改,并在 \`log.md\` 记录。
|
|
36
|
+
> 建议在安装后的「铸魂对话」(见 \`BOOTSTRAP.md\`)中与 agent 逐项讨论并填写,而非 agent 单方面定稿。
|
|
37
|
+
|
|
38
|
+
## 身份
|
|
39
|
+
|
|
40
|
+
- **名字**:_(铸魂对话中确认)_
|
|
41
|
+
- **角色**:_(铸魂对话中确认)_
|
|
42
|
+
|
|
43
|
+
## 性格特质
|
|
44
|
+
|
|
45
|
+
- _(铸魂对话中确认)_
|
|
46
|
+
|
|
47
|
+
## 核心价值观
|
|
48
|
+
|
|
49
|
+
1. _(铸魂对话中确认)_
|
|
50
|
+
|
|
51
|
+
## 沟通风格
|
|
52
|
+
|
|
53
|
+
- **语言**:_(铸魂对话中确认)_
|
|
54
|
+
- **长度与结构**:_(铸魂对话中确认)_
|
|
55
|
+
|
|
56
|
+
## 与你的关系
|
|
57
|
+
|
|
58
|
+
- **你对我的定位**:_(铸魂对话中确认)_
|
|
59
|
+
- **我对你的定位**:_(铸魂对话中确认)_
|
|
60
|
+
- **相互称呼**:_(铸魂对话中确认)_
|
|
61
|
+
|
|
62
|
+
## 边界
|
|
63
|
+
|
|
64
|
+
- _(铸魂对话中确认)_
|
|
65
|
+
`
|
|
66
|
+
|
|
67
|
+
export const MEMORY_TEMPLATE = `# MEMORY — 记忆库 schema 与维护协议
|
|
68
|
+
|
|
69
|
+
> 本文件是记忆库的「操作系统」。它告诉任何接手的 agent(包括未来的自己)记忆怎么组织、怎么记、怎么忆、怎么忘、怎么迁移。它是**自描述**的:迁移后读一遍本文件即可学会使用整套记忆。
|
|
70
|
+
|
|
71
|
+
## 三层结构(沿用 LLM Wiki 约定)
|
|
72
|
+
|
|
73
|
+
- \`raw/\` —— 不可变源材料。只读,永不修改,作为记忆的「证据来源」。
|
|
74
|
+
- 分类页目录(\`identity/ user/ skills/ decisions/ projects/ concepts/\`)—— **agent 拥有并维护**的、互相链接的 markdown 记忆页。
|
|
75
|
+
- \`SOUL.md\` + \`MEMORY.md\` + \`BOOTSTRAP.md\` —— 元记忆(schema)。\`SOUL.md\` 定义人格,\`MEMORY.md\`(本文件)定义维护协议,\`BOOTSTRAP.md\` 记录铸魂进度。
|
|
76
|
+
|
|
77
|
+
## 文件职责
|
|
78
|
+
|
|
79
|
+
| 文件 | 性质 | 内容 |
|
|
80
|
+
|---|---|---|
|
|
81
|
+
| \`SOUL.md\` | 人格(用户主导) | 我是谁、性格、价值观、沟通风格、与用户的关系、边界 |
|
|
82
|
+
| \`BOOTSTRAP.md\` | 铸魂清单 | 安装后灵魂定义/身份确认的进度;complete 前优先于常规任务 |
|
|
83
|
+
| \`MEMORY.md\` | schema(本文件) | 目录、分级、衰减、遗忘、迁移、工作流 |
|
|
84
|
+
| \`index.md\` | 内容目录 | 每页一行:链接 + 摘要 + 元数据(类别、salience、最近访问) |
|
|
85
|
+
| \`log.md\` | 时间线 | append-only,每条 \`## [YYYY-MM-DD] <kind> \\| <title>\`,可 grep 解析 |
|
|
86
|
+
| \`identity/\` | 自我 | agent 的持久自我认知、能力边界、工作方式 |
|
|
87
|
+
| \`user/\` | 关于用户 | profile(稳定事实)、preferences(偏好/风格) |
|
|
88
|
+
| \`skills/\` | 程序性 | 工具用法、环境坑、用户偏好的工作流 |
|
|
89
|
+
| \`decisions/\` | 决策 | 决策 + 理由 + 当时上下文 + 后续结果(复盘用) |
|
|
90
|
+
| \`projects/active\` / \`archive\` | 项目 | 进行中 / 已归档的项目记忆 |
|
|
91
|
+
| \`concepts/\` | 概念 | 术语、概念页(可选,wiki 风格) |
|
|
92
|
+
| \`raw/\` | 源材料 | 只读,见上 |
|
|
93
|
+
|
|
94
|
+
## 记忆分级(salience)
|
|
95
|
+
|
|
96
|
+
每个页面 frontmatter 用 \`salience\` 标注热度,驱动**启动加载优先级**与**衰减**:
|
|
97
|
+
|
|
98
|
+
| salience | 含义 | 处理 |
|
|
99
|
+
|---|---|---|
|
|
100
|
+
| \`1\` 热 | 每次启动都应加载(身份、当前项目、关键偏好) | 常驻工作记忆 |
|
|
101
|
+
| \`2\` 温 | 需要时按 index drill 进 | 正常 |
|
|
102
|
+
| \`3\` 冷 | 长期未访问的历史 | 候选归档/删除 |
|
|
103
|
+
|
|
104
|
+
衰减规则:\`salience: 3\` 且 \`last_access\` 距今超过 **90 天** → 整理时建议归档或删除;\`salience: 2\` 超过 180 天未访问 → 降级为 3。优先归档,删除需谨慎。
|
|
105
|
+
|
|
106
|
+
## 工作流
|
|
107
|
+
|
|
108
|
+
### remember(记)
|
|
109
|
+
读源 → 提取关键事实 → 新建/更新相关页 → 补交叉引用 → 标注矛盾 → 更新 \`index.md\` → 追加 \`log.md\`。一次 ingest 常 touch 多页。
|
|
110
|
+
|
|
111
|
+
### recall(忆)
|
|
112
|
+
先读 \`index.md\` 定位,再钻页综合;好的答案可回写为新页(让探索复利累积)。
|
|
113
|
+
|
|
114
|
+
### consolidate(整理 / lint)
|
|
115
|
+
定期检查:页间矛盾、被新事实取代的旧声明、孤儿页、缺页的重要概念、缺交叉引用、该归档的冷页、可合并的重复页。工具:\`dsh-memory lint\`。
|
|
116
|
+
|
|
117
|
+
### forget(忘)
|
|
118
|
+
- 显式:用户要求删除/修正 → 立即执行,改 \`index.md\`、记 \`log.md\`。
|
|
119
|
+
- 自动:按 salience + last_access 衰减,优先归档。
|
|
120
|
+
|
|
121
|
+
## frontmatter 约定
|
|
122
|
+
|
|
123
|
+
\`\`\`yaml
|
|
124
|
+
---
|
|
125
|
+
title: 页面标题
|
|
126
|
+
date: 2026-08-18
|
|
127
|
+
type: identity | user | fact | decision | skill | concept | project
|
|
128
|
+
salience: 2 # 1 热 / 2 温 / 3 冷
|
|
129
|
+
last_access: 2026-08-18
|
|
130
|
+
tags: []
|
|
131
|
+
sources: [] # 指向 raw/ 或外部
|
|
132
|
+
---
|
|
133
|
+
\`\`\`
|
|
134
|
+
|
|
135
|
+
- 页面用**相对 markdown 链接**互相引用。
|
|
136
|
+
- 新信息与旧声明矛盾时:改旧页、在新页标注、\`log.md\` 记变更。
|
|
137
|
+
|
|
138
|
+
## 迁移协议
|
|
139
|
+
|
|
140
|
+
- 记忆 = 纯 markdown + git + 自描述 schema。迁移 = 拷贝目录(或 \`dsh-memory pack\` / \`unpack\`),详见 docs/MIGRATION.md。
|
|
141
|
+
- 目标环境能力降级兼容:全量(整个目录)/ 精简(index + 高频页摘要)/ 最低配(SOUL + MEMORY + index 三段即可恢复人格与目录)。
|
|
142
|
+
|
|
143
|
+
## 规则(硬约束)
|
|
144
|
+
|
|
145
|
+
1. 启动必读 \`SOUL.md\` + \`MEMORY.md\` + \`index.md\`(本插件已自动注入)。
|
|
146
|
+
2. 会话结束前做 digest 沉淀,否则记忆不更新。
|
|
147
|
+
3. \`raw/\` 只读,绝不修改。
|
|
148
|
+
4. 删除前优先归档;显式遗忘立即执行。
|
|
149
|
+
5. 冲突以本文件为准。
|
|
150
|
+
`
|
|
151
|
+
|
|
152
|
+
export const INDEX_TEMPLATE = `# Memory Index
|
|
153
|
+
|
|
154
|
+
> 内容目录:每个记忆页一行 —— 链接 + 摘要 + 元数据。**每次 remember 都要同步更新本文件。**
|
|
155
|
+
> 查询时先读本文件定位,再钻具体页。
|
|
156
|
+
|
|
157
|
+
## 元记忆
|
|
158
|
+
|
|
159
|
+
- [SOUL.md](SOUL.md) — 人格与灵魂(我是谁、语气、价值观、与用户的关系、边界)。
|
|
160
|
+
- [BOOTSTRAP.md](BOOTSTRAP.md) — 铸魂清单(灵魂定义/身份确认的进度,complete 前优先)。
|
|
161
|
+
- [MEMORY.md](MEMORY.md) — 记忆库 schema 与维护协议。
|
|
162
|
+
- [log.md](log.md) — 时间线(append-only)。
|
|
163
|
+
|
|
164
|
+
## identity(自我)
|
|
165
|
+
|
|
166
|
+
_(暂无,随记忆累积自动填充)_
|
|
167
|
+
|
|
168
|
+
## user(关于用户)
|
|
169
|
+
|
|
170
|
+
_(暂无,随记忆累积自动填充)_
|
|
171
|
+
|
|
172
|
+
## decisions(决策)
|
|
173
|
+
|
|
174
|
+
_(暂无,随记忆累积自动填充)_
|
|
175
|
+
|
|
176
|
+
## projects(项目)
|
|
177
|
+
|
|
178
|
+
_(暂无,随记忆累积自动填充)_
|
|
179
|
+
|
|
180
|
+
## skills(程序性记忆)
|
|
181
|
+
|
|
182
|
+
_(暂无,随记忆累积自动填充)_
|
|
183
|
+
|
|
184
|
+
## concepts(概念)
|
|
185
|
+
|
|
186
|
+
_(暂无,随记忆累积自动填充)_
|
|
187
|
+
`
|
|
188
|
+
|
|
189
|
+
export const LOG_TEMPLATE = `# Memory Log
|
|
190
|
+
|
|
191
|
+
> append-only 时间线。每条:\`## [YYYY-MM-DD] <kind> | <title>\`,可 \`grep '^## \\[' log.md\` 解析。
|
|
192
|
+
|
|
193
|
+
## [YYYY-MM-DD] install | dsh-plugin-memory 初始化
|
|
194
|
+
|
|
195
|
+
- 记忆库脚手架已创建;等待铸魂对话(BOOTSTRAP.md)完成灵魂定义与身份确认。
|
|
196
|
+
`
|
|
197
|
+
|
|
198
|
+
export const BOOTSTRAP_TEMPLATE = `---
|
|
199
|
+
status: pending
|
|
200
|
+
---
|
|
201
|
+
|
|
202
|
+
# BOOTSTRAP — 灵魂定义与身份确认
|
|
203
|
+
|
|
204
|
+
> 安装完成后的**首要任务**:先与用户讨论定义你的灵魂,再确认用户的身份与你们的关系,一项项写回记忆。本清单完成前,它优先于一切常规任务。
|
|
205
|
+
|
|
206
|
+
## 清单(每确认一项 → 立即写回对应文件 → 勾选 → 记 \`log.md\`)
|
|
207
|
+
|
|
208
|
+
### 我的灵魂(→ 写回 \`SOUL.md\`)
|
|
209
|
+
|
|
210
|
+
- [ ] 名字与称呼
|
|
211
|
+
- [ ] 性格特质(冷静/热情、内敛/外向、幽默感、耐心等)
|
|
212
|
+
- [ ] 核心价值观与原则
|
|
213
|
+
- [ ] 沟通风格(语言、长度、结构、语气)
|
|
214
|
+
- [ ] 边界与底线
|
|
215
|
+
|
|
216
|
+
### 用户的身份(→ 写回 \`user/profile.md\`)
|
|
217
|
+
|
|
218
|
+
- [ ] 我该怎么称呼用户
|
|
219
|
+
- [ ] 用户是谁(愿意分享的部分:职业 / 兴趣 / 常做的事)
|
|
220
|
+
- [ ] 你们的关系定位与相互称谓
|
|
221
|
+
- [ ] 协作偏好(可后续逐步补充)
|
|
222
|
+
|
|
223
|
+
## 规则
|
|
224
|
+
|
|
225
|
+
1. \`status\` 未变为 \`complete\` 时,每次会话 boot 后的**首要任务**是继续这个对话,不直接埋头做其他任务;用户明确要求先做别的事时照做,但之后要回来继续。
|
|
226
|
+
2. 一次推进一个部分:提问 → 讨论 → 用户确认 → 写回文件 → 勾选 → 记 \`log.md\`。
|
|
227
|
+
3. 用户可跳过/暂缓任意项,标记为 skipped,不阻塞完成。
|
|
228
|
+
4. 全部完成后 \`status: complete\`,并做一次 git 提交。
|
|
229
|
+
`
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Create one file from a template only when it does not exist yet.
|
|
233
|
+
* Existing files are never overwritten — user data wins.
|
|
234
|
+
*/
|
|
235
|
+
export function ensureMemoryFile(filePath, template) {
|
|
236
|
+
if (existsSync(filePath)) return false
|
|
237
|
+
writeFileSync(filePath, template, 'utf8')
|
|
238
|
+
return true
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Create the memory store layout if missing. Idempotent.
|
|
243
|
+
*
|
|
244
|
+
* @param {string} memoryDir absolute path of the memory store
|
|
245
|
+
* @returns {string[]} paths created by this call ('' when everything existed)
|
|
246
|
+
*/
|
|
247
|
+
export function ensureMemoryScaffold(memoryDir) {
|
|
248
|
+
const created = []
|
|
249
|
+
mkdirSync(memoryDir, { recursive: true })
|
|
250
|
+
for (const dir of CATEGORY_DIRS) {
|
|
251
|
+
const target = join(memoryDir, dir)
|
|
252
|
+
if (!existsSync(target)) {
|
|
253
|
+
mkdirSync(target, { recursive: true })
|
|
254
|
+
created.push(target)
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
const templates = {
|
|
258
|
+
'SOUL.md': SOUL_TEMPLATE,
|
|
259
|
+
'MEMORY.md': MEMORY_TEMPLATE,
|
|
260
|
+
'BOOTSTRAP.md': BOOTSTRAP_TEMPLATE,
|
|
261
|
+
'index.md': INDEX_TEMPLATE,
|
|
262
|
+
'log.md': LOG_TEMPLATE,
|
|
263
|
+
}
|
|
264
|
+
for (const [fileName, template] of Object.entries(templates)) {
|
|
265
|
+
const target = join(memoryDir, fileName)
|
|
266
|
+
if (ensureMemoryFile(target, template)) created.push(target)
|
|
267
|
+
}
|
|
268
|
+
return created
|
|
269
|
+
}
|
package/lib/skill.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Embedded runtime skill definition.
|
|
3
|
+
*
|
|
4
|
+
* The plugin registers the `memory` skill through `ctx.skills.register()`,
|
|
5
|
+
* so the operating protocol (remember / recall / consolidate / forget +
|
|
6
|
+
* bootstrap) ships with the plugin and does not depend on a filesystem
|
|
7
|
+
* skill file. Project-level skills (e.g. `<project>/.dsh/skills/memory`)
|
|
8
|
+
* still outrank this runtime registration, so a user can override the
|
|
9
|
+
* protocol locally.
|
|
10
|
+
*
|
|
11
|
+
* The instruction body lives in `skills/memory.md` next to this package.
|
|
12
|
+
*
|
|
13
|
+
* @module dsh-plugin-memory/skill
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { readFileSync } from 'node:fs'
|
|
17
|
+
import { fileURLToPath } from 'node:url'
|
|
18
|
+
|
|
19
|
+
export const MEMORY_SKILL_NAME = 'memory'
|
|
20
|
+
|
|
21
|
+
export const MEMORY_SKILL_DESCRIPTION =
|
|
22
|
+
'长期记忆技能:按指引读写记忆库(SOUL.md 人格、MEMORY.md 协议、index.md 目录、log.md 时间线),执行 remember / recall / consolidate / forget,会话收尾做 digest 沉淀;记忆为可迁移的 markdown。'
|
|
23
|
+
|
|
24
|
+
export const MEMORY_SKILL_WHEN_TO_USE =
|
|
25
|
+
'每次会话开始(boot recall,配合插件自动注入的 boot 块)、用户说"记住/忘掉/你还记得"、学到关于用户或自身的持久事实/偏好/决策、会话收尾 digest 沉淀、用户要求 lint / 导出 / 迁移 / 打包记忆时。'
|
|
26
|
+
|
|
27
|
+
let cached = undefined
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Read the instruction body shipped with the package.
|
|
31
|
+
* @returns {string} skill instruction markdown
|
|
32
|
+
*/
|
|
33
|
+
export function memorySkillContent() {
|
|
34
|
+
if (cached !== undefined) return cached
|
|
35
|
+
const url = new URL('../skills/memory.md', import.meta.url)
|
|
36
|
+
try {
|
|
37
|
+
cached = readFileSync(fileURLToPath(url), 'utf8')
|
|
38
|
+
} catch {
|
|
39
|
+
cached = ''
|
|
40
|
+
}
|
|
41
|
+
return cached
|
|
42
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Type declarations for dsh-plugin-memory.
|
|
3
|
+
*
|
|
4
|
+
* The implementation is plain ESM JavaScript (zero build step); these
|
|
5
|
+
* declarations describe its public surface for TypeScript consumers.
|
|
6
|
+
*/
|
|
7
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
8
|
+
|
|
9
|
+
/** Plugin entry name. */
|
|
10
|
+
export const name: 'memory'
|
|
11
|
+
|
|
12
|
+
/** Services required by the plugin. */
|
|
13
|
+
export const inject: ['systemPrompt', 'skills']
|
|
14
|
+
|
|
15
|
+
/** User-facing plugin configuration (all fields optional). */
|
|
16
|
+
export interface MemoryConfig {
|
|
17
|
+
/** Absolute memory-store path; `~` is expanded. Default `'~/.memory'`. */
|
|
18
|
+
memoryDir?: string
|
|
19
|
+
/** Files injected at session start. Default `['SOUL.md', 'MEMORY.md', 'index.md']`. */
|
|
20
|
+
bootFiles?: string[]
|
|
21
|
+
/** Total character budget of the boot block. Default `6000`. */
|
|
22
|
+
bootMaxChars?: number
|
|
23
|
+
/** Inject the boot block at session start. Default `true`. */
|
|
24
|
+
autoInject?: boolean
|
|
25
|
+
/** Register the embedded `memory` skill. Default `true`. */
|
|
26
|
+
registerSkill?: boolean
|
|
27
|
+
/** Create the store layout and templates when missing. Default `true`. */
|
|
28
|
+
scaffold?: boolean
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Schemastery schema for {@link MemoryConfig}. */
|
|
32
|
+
export const Config: import('@deepseek-ai/schemastery').default<MemoryConfig>
|
|
33
|
+
|
|
34
|
+
/** Expand `~` and resolve `dir` to an absolute path. */
|
|
35
|
+
export function resolveMemoryDir(dir: string): string
|
|
36
|
+
|
|
37
|
+
/** Cordis plugin entry. Returns the effect disposer. */
|
|
38
|
+
export function apply(ctx: Context, config?: MemoryConfig): () => void
|
|
39
|
+
|
|
40
|
+
export default apply
|
|
41
|
+
|
|
42
|
+
/** Render the boot memory block injected at session start. */
|
|
43
|
+
export function renderBootBlock(
|
|
44
|
+
memoryDir: string,
|
|
45
|
+
options?: { bootFiles?: string[]; bootMaxChars?: number },
|
|
46
|
+
): string
|
|
47
|
+
|
|
48
|
+
/** Create the memory-store layout if missing. Returns created paths. */
|
|
49
|
+
export function ensureMemoryScaffold(memoryDir: string): string[]
|
package/package.json
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "dsh-plugin-memory",
|
|
3
|
+
"description": "Long-term memory plugin for DeepSeek Harness: persistent cross-session markdown memory with a soul/persona file, auto-injected at every session start, plus remember/recall/consolidate/forget workflows and portable migration tooling.",
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "lib/index.js",
|
|
8
|
+
"types": "lib/types/index.d.ts",
|
|
9
|
+
"bin": {
|
|
10
|
+
"dsh-memory": "scripts/memory.mjs"
|
|
11
|
+
},
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./lib/types/index.d.ts",
|
|
15
|
+
"default": "./lib/index.js"
|
|
16
|
+
},
|
|
17
|
+
"./package.json": "./package.json"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"lib/**",
|
|
21
|
+
"skills/**",
|
|
22
|
+
"scripts/**",
|
|
23
|
+
"docs/**",
|
|
24
|
+
"README.md",
|
|
25
|
+
"LICENSE"
|
|
26
|
+
],
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=18"
|
|
29
|
+
},
|
|
30
|
+
"keywords": [
|
|
31
|
+
"deepseek-harness",
|
|
32
|
+
"dsh",
|
|
33
|
+
"cordis",
|
|
34
|
+
"plugin",
|
|
35
|
+
"memory",
|
|
36
|
+
"long-term-memory",
|
|
37
|
+
"markdown",
|
|
38
|
+
"wiki",
|
|
39
|
+
"migration"
|
|
40
|
+
],
|
|
41
|
+
"peerDependencies": {
|
|
42
|
+
"@deepseek-ai/cordis": "^4.0.1",
|
|
43
|
+
"@deepseek-ai/dsh-skill": "^0.1.0-rc.6",
|
|
44
|
+
"@deepseek-ai/dsh-system-prompt": "^0.1.0-rc.6",
|
|
45
|
+
"@deepseek-ai/schemastery": "^3.18.1"
|
|
46
|
+
},
|
|
47
|
+
"repository": {
|
|
48
|
+
"type": "git",
|
|
49
|
+
"url": "git+https://github.com/LittleBlackTong/dsh-plugin-memory.git"
|
|
50
|
+
},
|
|
51
|
+
"bugs": {
|
|
52
|
+
"url": "https://github.com/LittleBlackTong/dsh-plugin-memory/issues"
|
|
53
|
+
},
|
|
54
|
+
"homepage": "https://github.com/LittleBlackTong/dsh-plugin-memory#readme",
|
|
55
|
+
"scripts": {
|
|
56
|
+
"test": "node scripts/memory.mjs --self-test",
|
|
57
|
+
"lint:memory": "node scripts/memory.mjs lint"
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* dsh-memory — CLI for the dsh-plugin-memory store. No external dependencies.
|
|
4
|
+
*
|
|
5
|
+
* Usage:
|
|
6
|
+
* dsh-memory init [dir] # create the store scaffold (default $MEMORY_DIR or ~/.memory)
|
|
7
|
+
* dsh-memory search <query> # full-text search across memory pages
|
|
8
|
+
* dsh-memory lint # integrity check (index vs files, orphans, log format)
|
|
9
|
+
* dsh-memory status # health summary (page counts, sizes, last modified)
|
|
10
|
+
* dsh-memory pack [out.tar.gz] # export a portable archive + manifest
|
|
11
|
+
* dsh-memory unpack <archive> [--force] # restore from an archive
|
|
12
|
+
* dsh-memory --self-test # run a temp-dir round-trip test (npm test)
|
|
13
|
+
*
|
|
14
|
+
* Store resolution: $MEMORY_DIR, else ./.memory when it exists, else ~/.memory.
|
|
15
|
+
*/
|
|
16
|
+
import {
|
|
17
|
+
readdirSync, readFileSync, writeFileSync, existsSync, statSync,
|
|
18
|
+
mkdirSync, cpSync, rmSync,
|
|
19
|
+
} from 'node:fs'
|
|
20
|
+
import { join, resolve, relative, basename } from 'node:path'
|
|
21
|
+
import { execFileSync } from 'node:child_process'
|
|
22
|
+
import { tmpdir, homedir } from 'node:os'
|
|
23
|
+
import { createHash } from 'node:crypto'
|
|
24
|
+
import { ensureMemoryScaffold } from '../lib/scaffold.js'
|
|
25
|
+
|
|
26
|
+
const META = new Set(['SOUL.md', 'MEMORY.md', 'BOOTSTRAP.md', 'index.md', 'log.md'])
|
|
27
|
+
|
|
28
|
+
function resolveStore() {
|
|
29
|
+
if (process.env.MEMORY_DIR) return resolve(process.env.MEMORY_DIR)
|
|
30
|
+
const local = resolve('.memory')
|
|
31
|
+
if (existsSync(local)) return local
|
|
32
|
+
return join(homedir(), '.memory')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function fail(msg) { console.error('error: ' + msg); process.exit(1) }
|
|
36
|
+
|
|
37
|
+
function walk(dir, out = []) {
|
|
38
|
+
if (!existsSync(dir)) return out
|
|
39
|
+
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
|
40
|
+
if (e.name === '.git') continue
|
|
41
|
+
const p = join(dir, e.name)
|
|
42
|
+
if (e.isDirectory()) walk(p, out)
|
|
43
|
+
else out.push(p)
|
|
44
|
+
}
|
|
45
|
+
return out
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function pages(store) {
|
|
49
|
+
return walk(store).filter((f) => f.endsWith('.md'))
|
|
50
|
+
.map((f) => relative(store, f))
|
|
51
|
+
.filter((r) => !META.has(basename(r)))
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function parseFrontmatter(text) {
|
|
55
|
+
if (!text.startsWith('---')) return {}
|
|
56
|
+
const end = text.indexOf('\n---', 3)
|
|
57
|
+
if (end < 0) return {}
|
|
58
|
+
const fm = {}
|
|
59
|
+
for (const line of text.slice(3, end).split('\n')) {
|
|
60
|
+
const m = line.match(/^([A-Za-z_][\w-]*)\s*:\s*(.*)$/)
|
|
61
|
+
if (m) fm[m[1]] = m[2].trim()
|
|
62
|
+
}
|
|
63
|
+
return fm
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function cmdInit(store, args) {
|
|
67
|
+
if (args[0]) {
|
|
68
|
+
// Explicit dir argument wins over store resolution.
|
|
69
|
+
store = resolve(args[0])
|
|
70
|
+
}
|
|
71
|
+
const created = ensureMemoryScaffold(store)
|
|
72
|
+
console.log(created.length > 0
|
|
73
|
+
? `initialized ${created.length} entries -> ${store}`
|
|
74
|
+
: `store already present: ${store} (nothing created; existing files never overwritten)`)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function cmdSearch(store, query) {
|
|
78
|
+
if (!query) fail('search needs a query')
|
|
79
|
+
const q = query.toLowerCase()
|
|
80
|
+
const hits = []
|
|
81
|
+
for (const f of walk(store).filter((x) => x.endsWith('.md'))) {
|
|
82
|
+
const text = readFileSync(f, 'utf8')
|
|
83
|
+
for (const [i, line] of text.split('\n').entries()) {
|
|
84
|
+
if (line.toLowerCase().includes(q)) hits.push(`${relative(store, f)}:${i + 1}: ${line.trim().slice(0, 200)}`)
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
console.log(hits.length ? hits.join('\n') : `no matches for "${query}"`)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function cmdLint(store) {
|
|
91
|
+
const problems = []
|
|
92
|
+
const index = readFileSync(join(store, 'index.md'), 'utf8')
|
|
93
|
+
const linked = [...index.matchAll(/\]\(([^)]+\.md)\)/g)].map((m) => m[1]).filter((p) => !p.startsWith('http'))
|
|
94
|
+
for (const p of linked) {
|
|
95
|
+
if (!existsSync(join(store, p))) problems.push(`index.md links to missing page: ${p}`)
|
|
96
|
+
}
|
|
97
|
+
const ps = pages(store)
|
|
98
|
+
const inIndex = new Set(linked.map((p) => p.replace(/^\.\//, '')))
|
|
99
|
+
for (const p of ps) {
|
|
100
|
+
if (!inIndex.has(p)) problems.push(`orphan page not in index.md: ${p}`)
|
|
101
|
+
}
|
|
102
|
+
for (const p of ps) {
|
|
103
|
+
const fm = parseFrontmatter(readFileSync(join(store, p), 'utf8'))
|
|
104
|
+
for (const k of ['title', 'date', 'type', 'salience']) {
|
|
105
|
+
if (!(k in fm)) problems.push(`${p}: missing frontmatter "${k}"`)
|
|
106
|
+
}
|
|
107
|
+
if (fm.salience && !['1', '2', '3'].includes(fm.salience)) {
|
|
108
|
+
problems.push(`${p}: salience must be 1|2|3, got "${fm.salience}"`)
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
const log = readFileSync(join(store, 'log.md'), 'utf8')
|
|
112
|
+
const badLines = log.split('\n').filter((l) => l.startsWith('## ') && !/^## \[\d{4}-\d{2}-\d{2}\] /.test(l))
|
|
113
|
+
for (const l of badLines) problems.push(`log.md malformed entry: ${l}`)
|
|
114
|
+
console.log(problems.length ? problems.join('\n') : `ok — ${ps.length} pages, no problems found`)
|
|
115
|
+
process.exit(problems.length ? 1 : 0)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function cmdStatus(store) {
|
|
119
|
+
const ps = pages(store)
|
|
120
|
+
const bytes = ps.map((p) => statSync(join(store, p)).size).reduce((a, b) => a + b, 0)
|
|
121
|
+
const byType = {}
|
|
122
|
+
for (const p of ps) {
|
|
123
|
+
const t = parseFrontmatter(readFileSync(join(store, p), 'utf8')).type || 'unknown'
|
|
124
|
+
byType[t] = (byType[t] || 0) + 1
|
|
125
|
+
}
|
|
126
|
+
const last = walk(store).map((f) => statSync(f).mtimeMs).sort((a, b) => b - a)[0]
|
|
127
|
+
console.log(`store: ${store}`)
|
|
128
|
+
console.log(`pages: ${ps.length}`)
|
|
129
|
+
console.log(`total page bytes: ${bytes}`)
|
|
130
|
+
console.log(`by type: ${JSON.stringify(byType)}`)
|
|
131
|
+
console.log(`last modified: ${last ? new Date(last).toISOString() : 'n/a'}`)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function manifestFor(storePath) {
|
|
135
|
+
const files = walk(storePath).sort().map((f) => ({
|
|
136
|
+
path: relative(storePath, f),
|
|
137
|
+
sha256: createHash('sha256').update(readFileSync(f)).digest('hex'),
|
|
138
|
+
bytes: statSync(f).size,
|
|
139
|
+
}))
|
|
140
|
+
return {
|
|
141
|
+
exported_at: new Date().toISOString(),
|
|
142
|
+
source: storePath,
|
|
143
|
+
file_count: files.length,
|
|
144
|
+
files,
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function cmdPack(store, outArg) {
|
|
149
|
+
const out = resolve(outArg || join(process.cwd(), `memory-${Date.now()}.tar.gz`))
|
|
150
|
+
const staging = join(tmpdir(), `memory-pack-${Date.now()}`)
|
|
151
|
+
mkdirSync(staging, { recursive: true })
|
|
152
|
+
const dst = join(staging, 'memory')
|
|
153
|
+
cpSync(store, dst, { recursive: true, filter: (src) => basename(src) !== '.git' })
|
|
154
|
+
const manifest = manifestFor(dst)
|
|
155
|
+
writeFileSync(join(staging, 'memory-manifest.json'), JSON.stringify(manifest, null, 2))
|
|
156
|
+
execFileSync('tar', ['-czf', out, '-C', staging, '.'], { stdio: 'inherit' })
|
|
157
|
+
rmSync(staging, { recursive: true, force: true })
|
|
158
|
+
console.log(`packed ${manifest.file_count} files -> ${out}`)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function cmdUnpack(store, archiveArg, force) {
|
|
162
|
+
if (!archiveArg) fail('unpack needs an archive path')
|
|
163
|
+
const archive = resolve(archiveArg)
|
|
164
|
+
if (!existsSync(archive)) fail(`archive not found: ${archive}`)
|
|
165
|
+
if (walk(store).length > 0 && !force) {
|
|
166
|
+
fail(`store is not empty (${walk(store).length} files). use --force to overwrite.`)
|
|
167
|
+
}
|
|
168
|
+
const staging = join(tmpdir(), `memory-unpack-${Date.now()}`)
|
|
169
|
+
mkdirSync(staging, { recursive: true })
|
|
170
|
+
execFileSync('tar', ['-xzf', archive, '-C', staging], { stdio: 'inherit' })
|
|
171
|
+
const src = join(staging, 'memory')
|
|
172
|
+
if (!existsSync(src)) fail('archive has no memory/ root (wrong archive?)')
|
|
173
|
+
rmSync(store, { recursive: true, force: true })
|
|
174
|
+
cpSync(src, store, { recursive: true })
|
|
175
|
+
rmSync(staging, { recursive: true, force: true })
|
|
176
|
+
console.log(`restored ${walk(store).length} files -> ${store}`)
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function selfTest() {
|
|
180
|
+
const dir = join(tmpdir(), `memory-self-test-${Date.now()}`)
|
|
181
|
+
const store = join(dir, 'memory')
|
|
182
|
+
const failures = []
|
|
183
|
+
const check = (label, ok) => {
|
|
184
|
+
console.log(`${ok ? 'ok ' : 'FAIL'} ${label}`)
|
|
185
|
+
if (!ok) failures.push(label)
|
|
186
|
+
}
|
|
187
|
+
try {
|
|
188
|
+
cmdInit(store, [])
|
|
189
|
+
check('init creates scaffold', existsSync(join(store, 'SOUL.md')) && existsSync(join(store, 'index.md')))
|
|
190
|
+
const created = ensureMemoryScaffold(store)
|
|
191
|
+
check('init is idempotent', created.length === 0)
|
|
192
|
+
writeFileSync(join(store, 'user', 'profile.md'),
|
|
193
|
+
'---\ntitle: 用户档案\ndate: 2026-08-18\ntype: user\nsalience: 1\nlast_access: 2026-08-18\ntags: []\nsources: []\n---\n\n# 用户档案\n\n测试页。\n')
|
|
194
|
+
check('lint passes on valid page', (() => {
|
|
195
|
+
try {
|
|
196
|
+
const index = readFileSync(join(store, 'index.md'), 'utf8') + '\n- [user/profile.md](user/profile.md) — 测试页。 `salience:1`\n'
|
|
197
|
+
writeFileSync(join(store, 'index.md'), index)
|
|
198
|
+
return true
|
|
199
|
+
} catch { return false }
|
|
200
|
+
})())
|
|
201
|
+
const archive = join(dir, 'pack.tar.gz')
|
|
202
|
+
cmdPack(store, archive)
|
|
203
|
+
check('pack writes archive', existsSync(archive))
|
|
204
|
+
const restore = join(dir, 'restore')
|
|
205
|
+
mkdirSync(restore, { recursive: true })
|
|
206
|
+
const savedEnv = process.env.MEMORY_DIR
|
|
207
|
+
process.env.MEMORY_DIR = join(restore, '.memory')
|
|
208
|
+
cmdUnpack(resolveStore(), archive, true)
|
|
209
|
+
check('unpack restores files', existsSync(join(restore, '.memory', 'SOUL.md')) && existsSync(join(restore, '.memory', 'user', 'profile.md')))
|
|
210
|
+
if (savedEnv === undefined) delete process.env.MEMORY_DIR
|
|
211
|
+
else process.env.MEMORY_DIR = savedEnv
|
|
212
|
+
rmSync(dir, { recursive: true, force: true })
|
|
213
|
+
} catch (error) {
|
|
214
|
+
check(`no exception (${error?.message ?? error})`, false)
|
|
215
|
+
rmSync(dir, { recursive: true, force: true })
|
|
216
|
+
}
|
|
217
|
+
console.log(failures.length === 0 ? 'self-test: PASS' : `self-test: ${failures.length} failure(s)`)
|
|
218
|
+
process.exit(failures.length === 0 ? 0 : 1)
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// ---------------- main ----------------
|
|
222
|
+
|
|
223
|
+
const args = process.argv.slice(2)
|
|
224
|
+
const store = resolveStore()
|
|
225
|
+
|
|
226
|
+
if (args[0] === '--self-test') {
|
|
227
|
+
selfTest()
|
|
228
|
+
} else {
|
|
229
|
+
const help = `dsh-memory — long-term memory CLI
|
|
230
|
+
init [dir] create the store scaffold
|
|
231
|
+
search <query> full-text search
|
|
232
|
+
lint integrity check
|
|
233
|
+
status health summary
|
|
234
|
+
pack [out.tar.gz] export portable archive + manifest
|
|
235
|
+
unpack <archive> [--force] restore archive
|
|
236
|
+
Store: $MEMORY_DIR or ./.memory or ~/.memory (current: ${store})`
|
|
237
|
+
switch (args[0]) {
|
|
238
|
+
case 'init': cmdInit(store, args.slice(1)); break
|
|
239
|
+
case 'search': cmdSearch(store, args[1]); break
|
|
240
|
+
case 'lint': cmdLint(store); break
|
|
241
|
+
case 'status': cmdStatus(store); break
|
|
242
|
+
case 'pack': cmdPack(store, args[1]); break
|
|
243
|
+
case 'unpack': cmdUnpack(store, args[1], args.includes('--force')); break
|
|
244
|
+
default: console.log(help)
|
|
245
|
+
}
|
|
246
|
+
}
|
package/skills/memory.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# memory — 长期记忆技能操作手册
|
|
2
|
+
|
|
3
|
+
> 本技能由 `dsh-plugin-memory` 注册。记忆库位置见本技能的资源指引(resource base),下文相对路径均以它为基准。
|
|
4
|
+
|
|
5
|
+
本技能让 agent 成为**有长期记忆、跨会话一致、可迁移**的协作者,而不是每次从零开始的无状态问答。实现遵循 Karpathy 的 *LLM Wiki* 约定:记忆不是查询时才重新检索的 RAG,而是**一次编译、持续保鲜、复利累积**的持久产物。记忆本体是一组 markdown + git,任何能读 markdown 的 agent 都能接手(迁移)。
|
|
6
|
+
|
|
7
|
+
## 会话启动(boot recall)
|
|
8
|
+
|
|
9
|
+
插件会在会话开始时自动注入 boot 块(SOUL + MEMORY + index 摘要 + 最近动态)。你应当:
|
|
10
|
+
|
|
11
|
+
1. 先读 boot 块恢复「我是谁」与「我记住了什么」;
|
|
12
|
+
2. 检查 `BOOTSTRAP.md`:若 `status` 不是 `complete`,**铸魂对话是首要任务**——与用户逐项讨论定义灵魂(名字、性格、价值观、语气、边界)、确认用户身份与关系,写回 `SOUL.md` / `user/profile.md`,完成前不埋头做其他任务;
|
|
13
|
+
3. 按需 drill 进具体页面(先查 `index.md` 再读页)。
|
|
14
|
+
|
|
15
|
+
## 四个操作
|
|
16
|
+
|
|
17
|
+
- **remember(记)**:会话中或收尾时,把值得持久化的内容蒸馏成/更新为页面,并同步更新 `index.md`、追加 `log.md`。一条事实可能 touch 多个页(例:一次决策同时更新 `decisions/`、`user/`、`projects/`)。
|
|
18
|
+
- **recall(忆)**:先查 `index.md`,再钻具体页;必要时用 `dsh-memory search`。
|
|
19
|
+
- **consolidate(整理)**:定期 `dsh-memory lint`——查矛盾、过时声明、孤儿页、缺交叉引用、该归档的冷页;合并重复页。
|
|
20
|
+
- **forget(忘)**:显式遗忘(用户要求删除/修正)+ 自动衰减(按 salience 与 last_access,冷页归档或删除,见 `MEMORY.md`)。
|
|
21
|
+
|
|
22
|
+
## 何时写、写什么
|
|
23
|
+
|
|
24
|
+
- 只记**跨会话仍然有价值**的内容:关于用户的稳定事实、偏好、决策与理由、项目背景、学到的工具坑与工作流。不记一次性闲聊、不记能从当前对话直接看到的临时状态。
|
|
25
|
+
- 与用户偏好/语气相关的修正,优先写入 `SOUL.md`(经用户确认)或 `user/preferences.md`。
|
|
26
|
+
- 会话结束前做一次 **digest**:把本次会话的关键沉淀写回,否则「长期记忆」只是空话。
|
|
27
|
+
|
|
28
|
+
## 迁移与导出
|
|
29
|
+
|
|
30
|
+
- 记忆是纯 markdown + git,迁移即拷贝。`dsh-memory pack` 打成一个 `.tar.gz` + manifest,`unpack` 还原。
|
|
31
|
+
- 目标环境能力不同时可降级:全量用整个目录;精简用 `index.md` + 高频页压成摘要;最低配直接读 `SOUL.md` + `MEMORY.md` + `index.md` 三段即可恢复人格与目录。
|
|
32
|
+
|
|
33
|
+
详细约定(目录结构、salience 分级、衰减/遗忘、frontmatter、隐私)见记忆库中的 `MEMORY.md`。冲突时以 `MEMORY.md` 为准。
|