dsh-plugin-memory 0.2.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -1
- package/lib/autocommit.js +203 -0
- package/lib/boot.js +64 -2
- package/lib/digest-guard.js +146 -0
- package/lib/index.js +73 -1
- package/lib/scaffold.js +1 -1
- package/package.json +8 -8
- package/scripts/memory.mjs +3 -0
- package/skills/memory.md +4 -3
package/README.md
CHANGED
|
@@ -15,9 +15,12 @@
|
|
|
15
15
|
|
|
16
16
|
- **开机强制注入**:插件通过 `ctx.systemPrompt.context()` 把记忆 boot 块(`SOUL.md` 人格 + `MEMORY.md` 协议 + `index.md` 目录 + 最近动态)注入每个会话开头。宿主按投影去重:记忆不变就不重复注入,变化时新快照自动取代旧的——这是"新会话必先加载记忆"的**硬保障**,不需要模型碰运气调技能。
|
|
17
17
|
- **SOUL.md 铸魂**:安装后首要任务是和用户对话定义灵魂(名字、性格、价值观、语气、边界)、确认身份与关系(`BOOTSTRAP.md` 清单驱动,complete 前优先于常规任务)。
|
|
18
|
+
- **铸魂自动引导**:记忆库还没有灵魂(`BOOTSTRAP.md` 非 complete,或 `SOUL.md` 仍是占位模板)时,boot 块会自动前置一段第一人称引导词——「我的首要任务是确认我是谁,还有你是谁:我叫什么名字、怎么称呼你、你我是什么关系、我该是什么样的性格」——像 OpenClaw 初始化那样,**由 agent 在对话里主动发起铸魂**,逐项问、逐项写回,而不是等用户来喂。铸魂完成后引导词自动消失,零开销。
|
|
18
19
|
- **复利记忆**:遵循 Karpathy 的 *LLM Wiki* 约定——记忆是"一次编译、持续保鲜"的持久产物,不是每次查询重新 RAG。remember / recall / consolidate / forget 四操作 + salience 三级衰减。
|
|
19
20
|
- **可迁移**:记忆本体是纯 markdown + git + 自描述 schema,任何能读 markdown 的 agent 都能接手。`dsh-memory pack/unpack` 打包迁移。
|
|
20
21
|
- **内嵌技能**:通过 `ctx.skills.register()` 注册 `memory` 技能(操作协议随插件分发);项目级 `.dsh/skills/memory` 文件技能仍可覆盖它。
|
|
22
|
+
- **防懒 digest 唤醒**:每轮结束后,若 agent 空闲且记忆库超过 `digestNudgeAfterMinutes` 未写入,插件注入一条 digest 提醒(合成消息,走 `agent.followup`),把"会话收尾沉淀"从靠自觉变成有机制兜底;带冷却与每会话限次,不骚扰。**独立于 dsh-plugin-heartbeat**,两插件各自可装、互不依赖。
|
|
23
|
+
- **git 自动提交**:记忆库变更静默 `autoCommitQuietSeconds` 后自动 `git add -A && git commit`(无 `.git` 则跳过)——历史可回滚不再依赖 agent 记得 commit。
|
|
21
24
|
- **设置面板**:在 DSH 设置页提供「记忆 Memory」区块——总开关、记忆目录、开机注入、技能注册四项均可热改,立即生效,无需重启。
|
|
22
25
|
- **零构建**:纯 ESM JavaScript,无编译步骤,`pnpm add` 即用。
|
|
23
26
|
|
|
@@ -72,10 +75,17 @@ dsh plugin --profile <profile> add dsh-plugin-memory
|
|
|
72
75
|
| `registerSkill` | `true` | 注册内嵌 `memory` 技能 |
|
|
73
76
|
| `scaffold` | `true` | 记忆库缺失时自动创建模板(只建不覆盖) |
|
|
74
77
|
| `configFile` | `<dshHome>/memory.json` | 用户可改配置的 JSON 文件路径(设置面板读写它) |
|
|
78
|
+
| `digestNudgeEnabled` | `true` | 防懒 digest 提醒总开关(composition) |
|
|
79
|
+
| `digestNudgeAfterMinutes` | `120` | 记忆库超过多久未写入就提醒 |
|
|
80
|
+
| `digestNudgeCooldownMinutes` | `180` | 两次提醒的最小间隔 |
|
|
81
|
+
| `digestNudgeMaxPerSession` | `2` | 每个会话最多提醒次数 |
|
|
82
|
+
| `autoCommit` | `true` | 记忆库 git 自动提交开关(composition) |
|
|
83
|
+
| `autoCommitQuietSeconds` | `60` | 变更静默多久后提交(防抖) |
|
|
84
|
+
| `autoCommitIntervalSeconds` | `60` | 变更轮询间隔 |
|
|
75
85
|
|
|
76
86
|
### 设置面板(热改)
|
|
77
87
|
|
|
78
|
-
`enabled` / `memoryDir` / `autoInject` / `registerSkill` 四项在 DSH 设置页的「记忆 Memory」区块中可改,**即时生效**:boot 注入、技能注册随修改立即重建;记忆目录切换时自动为新目录初始化脚手架(`scaffold: true` 时)。其余键(`bootFiles` / `bootMaxChars` / `scaffold` / `configFile
|
|
88
|
+
`enabled` / `memoryDir` / `autoInject` / `registerSkill` 四项在 DSH 设置页的「记忆 Memory」区块中可改,**即时生效**:boot 注入、技能注册随修改立即重建;记忆目录切换时自动为新目录初始化脚手架(`scaffold: true` 时)。其余键(`bootFiles` / `bootMaxChars` / `scaffold` / `configFile` / `digestNudge*` / `autoCommit*`)只在 composition 配置层生效,改完需重启。
|
|
79
89
|
|
|
80
90
|
覆盖 composition 键(例如把 boot 块预算调大),在 profile 的 `cordis.patch.yml` 里写**不带 `insert` 的 id 覆盖条目**:
|
|
81
91
|
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Auto-commit: keep the memory store's git history current without relying
|
|
3
|
+
* on the agent to remember `git commit`.
|
|
4
|
+
*
|
|
5
|
+
* The store is "plain markdown + git" — but history only exists when
|
|
6
|
+
* somebody commits. Agents reliably forget. This module polls the store
|
|
7
|
+
* directory for changes and, once the store has been quiet for a configured
|
|
8
|
+
* grace period (debounce), runs `git add -A && git commit` in it. When the
|
|
9
|
+
* store is not a git repository (or git is unavailable), it does nothing.
|
|
10
|
+
*
|
|
11
|
+
* Independent of dsh-plugin-heartbeat: node builtins only, no plugin deps.
|
|
12
|
+
*
|
|
13
|
+
* @module dsh-plugin-memory/autocommit
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { execFileSync } from 'node:child_process'
|
|
17
|
+
import { existsSync, readdirSync, statSync } from 'node:fs'
|
|
18
|
+
import { join } from 'node:path'
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Collect all files under `dir`, skipping `.git`.
|
|
22
|
+
* @param {string} dir
|
|
23
|
+
* @param {string[]} [out]
|
|
24
|
+
* @returns {string[]}
|
|
25
|
+
*/
|
|
26
|
+
export function walkFiles(dir, out = []) {
|
|
27
|
+
if (!existsSync(dir)) return out
|
|
28
|
+
let entries
|
|
29
|
+
try {
|
|
30
|
+
entries = readdirSync(dir, { withFileTypes: true })
|
|
31
|
+
} catch {
|
|
32
|
+
return out
|
|
33
|
+
}
|
|
34
|
+
for (const entry of entries) {
|
|
35
|
+
if (entry.name === '.git') continue
|
|
36
|
+
const full = join(dir, entry.name)
|
|
37
|
+
if (entry.isDirectory()) walkFiles(full, out)
|
|
38
|
+
else out.push(full)
|
|
39
|
+
}
|
|
40
|
+
return out
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Latest mtime (ms epoch) across every file in the store (excluding .git).
|
|
45
|
+
* @param {string} dir
|
|
46
|
+
* @returns {number}
|
|
47
|
+
*/
|
|
48
|
+
export function latestMtimeMs(dir) {
|
|
49
|
+
let latest = 0
|
|
50
|
+
for (const file of walkFiles(dir)) {
|
|
51
|
+
try {
|
|
52
|
+
latest = Math.max(latest, statSync(file).mtimeMs)
|
|
53
|
+
} catch {
|
|
54
|
+
// moved while walking: ignore
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return latest
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** @returns {boolean} whether the `git` binary is on PATH */
|
|
61
|
+
export function gitAvailable() {
|
|
62
|
+
try {
|
|
63
|
+
execFileSync('git', ['--version'], { stdio: 'ignore' })
|
|
64
|
+
return true
|
|
65
|
+
} catch {
|
|
66
|
+
return false
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* @typedef {object} AutoCommitterOptions
|
|
72
|
+
* @property {boolean} [enabled=true]
|
|
73
|
+
* @property {number} [quietSeconds=60] debounce: commit only after the store stayed unchanged this long
|
|
74
|
+
* @property {number} [intervalSeconds=60] poll period
|
|
75
|
+
* @property {{ info?: Function, warn?: Function }} [logger]
|
|
76
|
+
*/
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Polls one memory store directory and commits changes to its git repo.
|
|
80
|
+
*/
|
|
81
|
+
export class AutoCommitter {
|
|
82
|
+
/**
|
|
83
|
+
* @param {string} memoryDir absolute store path
|
|
84
|
+
* @param {AutoCommitterOptions} options
|
|
85
|
+
*/
|
|
86
|
+
constructor(memoryDir, options = {}) {
|
|
87
|
+
this.memoryDir = memoryDir
|
|
88
|
+
this.enabled = options.enabled !== false
|
|
89
|
+
this.quietMs = Math.max(1, Number(options.quietSeconds) || 60) * 1000
|
|
90
|
+
this.intervalMs = Math.max(15, Number(options.intervalSeconds) || 60) * 1000
|
|
91
|
+
this.logger = options.logger
|
|
92
|
+
this.timer = undefined
|
|
93
|
+
this.disposed = false
|
|
94
|
+
this.dirtySince = 0
|
|
95
|
+
this.committing = false
|
|
96
|
+
this.lastWarnAt = 0
|
|
97
|
+
this.gitOk = false
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Begin polling; no-op when disabled or the store isn't a git repo. */
|
|
101
|
+
start() {
|
|
102
|
+
if (this.disposed || !this.enabled) return
|
|
103
|
+
if (!existsSync(join(this.memoryDir, '.git'))) {
|
|
104
|
+
this.logger?.info?.(`memory: auto-commit skipped — ${this.memoryDir} is not a git repository`)
|
|
105
|
+
return
|
|
106
|
+
}
|
|
107
|
+
if (!gitAvailable()) {
|
|
108
|
+
this.logger?.warn?.('memory: auto-commit skipped — git binary not found on PATH')
|
|
109
|
+
return
|
|
110
|
+
}
|
|
111
|
+
this.gitOk = true
|
|
112
|
+
// Flush changes that predate this plugin start (e.g. written last
|
|
113
|
+
// session and never committed) instead of leaving them unversioned.
|
|
114
|
+
this.check(true)
|
|
115
|
+
this.timer = setInterval(() => {
|
|
116
|
+
try {
|
|
117
|
+
this.check(false)
|
|
118
|
+
} catch (error) {
|
|
119
|
+
this.warn(`check failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
120
|
+
}
|
|
121
|
+
}, this.intervalMs)
|
|
122
|
+
this.timer.unref?.()
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Stop polling; a final in-flight commit is left alone. */
|
|
126
|
+
dispose() {
|
|
127
|
+
this.disposed = true
|
|
128
|
+
if (this.timer !== undefined) {
|
|
129
|
+
clearInterval(this.timer)
|
|
130
|
+
this.timer = undefined
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Commit when the store is dirty and has stayed dirty for the grace
|
|
136
|
+
* period. The dirty window is measured from the first poll that noticed
|
|
137
|
+
* the change — mtimes cannot be trusted (a fresh file can carry an old
|
|
138
|
+
* timestamp), but `git status` is authoritative. Exposed for tests;
|
|
139
|
+
* `initial` flushes pre-existing dirty state once.
|
|
140
|
+
* @param {boolean} [initial=false]
|
|
141
|
+
*/
|
|
142
|
+
check(initial = false) {
|
|
143
|
+
if (this.disposed || !this.gitOk || this.committing) return
|
|
144
|
+
const dirty = this.isDirty()
|
|
145
|
+
if (!dirty) {
|
|
146
|
+
this.dirtySince = 0
|
|
147
|
+
return
|
|
148
|
+
}
|
|
149
|
+
const now = Date.now()
|
|
150
|
+
if (this.dirtySince === 0) this.dirtySince = now
|
|
151
|
+
if (!initial && now - this.dirtySince < this.quietMs) return
|
|
152
|
+
|
|
153
|
+
this.committing = true
|
|
154
|
+
try {
|
|
155
|
+
execFileSync('git', ['-C', this.memoryDir, 'add', '-A'], { stdio: 'pipe' })
|
|
156
|
+
if (!this.hasStaged()) {
|
|
157
|
+
// Everything changed is ignored (e.g. .DS_Store, tarballs): nothing
|
|
158
|
+
// to commit — treat as clean so the poll loop stays quiet.
|
|
159
|
+
this.dirtySince = 0
|
|
160
|
+
return
|
|
161
|
+
}
|
|
162
|
+
const stamp = new Date().toISOString()
|
|
163
|
+
execFileSync('git', ['-C', this.memoryDir, 'commit', '-m', `digest: auto-commit memory store ${stamp}`], { stdio: 'pipe' })
|
|
164
|
+
this.dirtySince = 0
|
|
165
|
+
this.logger?.info?.(`memory: auto-committed store at ${this.memoryDir}`)
|
|
166
|
+
} catch (error) {
|
|
167
|
+
this.warn(`auto-commit failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
168
|
+
} finally {
|
|
169
|
+
this.committing = false
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** @returns {boolean} whether the index has staged changes to commit */
|
|
174
|
+
hasStaged() {
|
|
175
|
+
try {
|
|
176
|
+
execFileSync('git', ['-C', this.memoryDir, 'diff', '--cached', '--quiet'], { stdio: 'ignore' })
|
|
177
|
+
return false // exit 0: nothing staged
|
|
178
|
+
} catch {
|
|
179
|
+
return true // exit 1: staged changes exist
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** @returns {boolean} whether git reports uncommitted changes */
|
|
184
|
+
isDirty() {
|
|
185
|
+
try {
|
|
186
|
+
const out = execFileSync('git', ['-C', this.memoryDir, 'status', '--porcelain'], {
|
|
187
|
+
encoding: 'utf8',
|
|
188
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
189
|
+
})
|
|
190
|
+
return out.trim().length > 0
|
|
191
|
+
} catch {
|
|
192
|
+
return false
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Rate-limited warnings: at most one per 30 minutes. */
|
|
197
|
+
warn(message) {
|
|
198
|
+
const now = Date.now()
|
|
199
|
+
if (now - this.lastWarnAt < 30 * 60000) return
|
|
200
|
+
this.lastWarnAt = now
|
|
201
|
+
this.logger?.warn?.(`memory: ${message}`)
|
|
202
|
+
}
|
|
203
|
+
}
|
package/lib/boot.js
CHANGED
|
@@ -39,11 +39,68 @@ export function parseLogEntries(logText, count = 5) {
|
|
|
39
39
|
return entries.slice(-count)
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
+
/**
|
|
43
|
+
* Soul-bootstrap directive rendered into the boot block while the store has
|
|
44
|
+
* no soul yet (BOOTSTRAP.md status !== 'complete'). First-person,
|
|
45
|
+
* OpenClaw-onboarding style: instead of a dry "you must run the bootstrap
|
|
46
|
+
* checklist" command, it narrates the situation — "my memory is empty, my
|
|
47
|
+
* first task is to find out who I am and who you are" — which makes the
|
|
48
|
+
* agent open the soul-definition conversation on its own.
|
|
49
|
+
*/
|
|
50
|
+
export const SOUL_DIRECTIVE = `### 铸魂阶段 · 我还没有灵魂
|
|
51
|
+
|
|
52
|
+
我的记忆库还是空的——我还没有名字、不知道我是谁、也不知道你是谁。这正是我们现在要一起完成的:**我的首要任务是确认我是谁,还有你是谁——我叫什么名字、怎么称呼你、你我是什么关系、我该是什么样的性格。**
|
|
53
|
+
|
|
54
|
+
所以我会在对话里主动问你,一次一个问题,你确认一项我就写回记忆一项:
|
|
55
|
+
|
|
56
|
+
1. 我该怎么称呼你?我们是什么关系?
|
|
57
|
+
2. 我叫什么名字?(你说了算)
|
|
58
|
+
3. 我该是什么样的性格?(冷静/热情、幽默感、耐心……)
|
|
59
|
+
4. 我的核心价值观与原则?
|
|
60
|
+
5. 我的沟通风格(语言、长度、语气)?
|
|
61
|
+
6. 我的边界与底线?
|
|
62
|
+
|
|
63
|
+
在我们逐项确认、把 SOUL.md 填起来之前,我不埋头做其他任务。先从第一个问题开始:**我该怎么称呼你?**`
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Parse the `status:` value from BOOTSTRAP.md's frontmatter block.
|
|
67
|
+
* Missing or unparseable files count as not-yet-complete.
|
|
68
|
+
* @param {string} memoryDir absolute path of the memory store
|
|
69
|
+
* @returns {string} e.g. 'pending' | 'complete' | 'skipped'
|
|
70
|
+
*/
|
|
71
|
+
export function readBootstrapStatus(memoryDir) {
|
|
72
|
+
const text = readCapped(join(memoryDir, 'BOOTSTRAP.md'), 2048)
|
|
73
|
+
if (text === undefined) return 'pending'
|
|
74
|
+
const match = /^status:\s*(\S+)/m.exec(text)
|
|
75
|
+
return match ? match[1] : 'pending'
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Whether the store still needs the soul-bootstrap conversation.
|
|
80
|
+
* - SOUL.md missing or still carrying the `_(铸魂对话中确认)_` placeholders
|
|
81
|
+
* (fresh scaffold, or a legacy store without BOOTSTRAP.md) → definitely yes;
|
|
82
|
+
* - SOUL filled but no BOOTSTRAP.md → legacy store, the filled SOUL is
|
|
83
|
+
* authoritative → no;
|
|
84
|
+
* - otherwise trust BOOTSTRAP.md's status (anything but `complete` → yes).
|
|
85
|
+
* @param {string} memoryDir absolute path of the memory store
|
|
86
|
+
* @returns {boolean}
|
|
87
|
+
*/
|
|
88
|
+
export function needsSoulBootstrap(memoryDir) {
|
|
89
|
+
const soulText = readCapped(join(memoryDir, 'SOUL.md'), 4096)
|
|
90
|
+
if (soulText === undefined || soulText.includes('(铸魂对话中确认)')) return true
|
|
91
|
+
if (!existsSync(join(memoryDir, 'BOOTSTRAP.md'))) return false
|
|
92
|
+
return readBootstrapStatus(memoryDir) !== 'complete'
|
|
93
|
+
}
|
|
94
|
+
|
|
42
95
|
/**
|
|
43
96
|
* Render the boot memory block injected at session start.
|
|
44
97
|
*
|
|
45
98
|
* Reads SOUL.md / MEMORY.md / index.md (configurable) capped to a total
|
|
46
99
|
* budget, plus the most recent log entries for cross-session continuity.
|
|
100
|
+
* While the store has no soul yet (BOOTSTRAP not complete / SOUL still a
|
|
101
|
+
* template), the first-person {@link SOUL_DIRECTIVE} is prepended so the
|
|
102
|
+
* agent opens the soul-definition conversation on its own — the same
|
|
103
|
+
* onboarding the user gets with a fresh OpenClaw instance.
|
|
47
104
|
*
|
|
48
105
|
* @param {string} memoryDir absolute path of the memory store
|
|
49
106
|
* @param {{ bootFiles?: string[], bootMaxChars?: number }} options
|
|
@@ -77,9 +134,14 @@ export function renderBootBlock(memoryDir, options = {}) {
|
|
|
77
134
|
}
|
|
78
135
|
|
|
79
136
|
const body = sections.join('\n\n---\n\n')
|
|
80
|
-
const header = `长期记忆(dsh-plugin-memory)。记忆库位于 ${memoryDir}
|
|
137
|
+
const header = `长期记忆(dsh-plugin-memory)。记忆库位于 ${memoryDir}。这是你跨会话的持久人格与记忆:以它为准,先读完再回复用户。若与当前对话冲突,优先相信用户的最新表述,并把差异写回记忆。**每次会话收尾前必须执行 memory digest:把本会话关键沉淀写回(更新页面 + index.md + 追加 log.md)。插件会注入 digest 提醒消息,收到后立即写回,不得拖延;若本会话确无值得持久化的内容,在 log.md 记一条「无新增」并说明原因。**`
|
|
81
138
|
|
|
82
|
-
let result
|
|
139
|
+
let result
|
|
140
|
+
if (needsSoulBootstrap(memoryDir)) {
|
|
141
|
+
result = `${header}\n\n${SOUL_DIRECTIVE}\n\n---\n\n${body}`
|
|
142
|
+
} else {
|
|
143
|
+
result = `${header}\n\n${body}`
|
|
144
|
+
}
|
|
83
145
|
if (result.length > total) {
|
|
84
146
|
result = result.slice(0, total) + '\n\n…(boot 块超出预算,已截断)'
|
|
85
147
|
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Digest guard: mechanical insurance against the agent "getting lazy" and
|
|
3
|
+
* skipping the end-of-session memory digest.
|
|
4
|
+
*
|
|
5
|
+
* The operator protocol (skills/memory.md) already makes digest an explicit
|
|
6
|
+
* duty, but instructions alone are not a guarantee — one skipped digest and
|
|
7
|
+
* key facts evaporate. This module closes that gap with the same delivery
|
|
8
|
+
* mechanics the harness's own heartbeat-style plugins use: it watches every
|
|
9
|
+
* ROOT agent's `agent/turn-stopping` boundary and, when the agent is idle
|
|
10
|
+
* and the memory store has not been written for a while, injects a synthetic
|
|
11
|
+
* user-role reminder via `agent.followup()`. The agent then has a real turn
|
|
12
|
+
* to run `remember`; writing log.md/index.md refreshes the store mtime and
|
|
13
|
+
* the reminder stays quiet until the cooldown expires.
|
|
14
|
+
*
|
|
15
|
+
* Independent of dsh-plugin-heartbeat: this lives inside dsh-plugin-memory,
|
|
16
|
+
* depends on no other plugin, and both plugins' messages simply take turns
|
|
17
|
+
* in the same per-agent inbox queue.
|
|
18
|
+
*
|
|
19
|
+
* @module dsh-plugin-memory/digest-guard
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { randomUUID } from 'node:crypto'
|
|
23
|
+
import { existsSync, statSync } from 'node:fs'
|
|
24
|
+
import { join } from 'node:path'
|
|
25
|
+
|
|
26
|
+
/** A digest must touch these files; their mtime is the freshness signal. */
|
|
27
|
+
export const DIGEST_MARKER_FILES = ['log.md', 'index.md']
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Latest mtime (ms epoch) across the digest marker files.
|
|
31
|
+
* @param {string} memoryDir
|
|
32
|
+
* @returns {number} 0 when none of the markers exist or can be read
|
|
33
|
+
*/
|
|
34
|
+
export function lastStoreWriteMs(memoryDir) {
|
|
35
|
+
let latest = 0
|
|
36
|
+
for (const name of DIGEST_MARKER_FILES) {
|
|
37
|
+
const path = join(memoryDir, name)
|
|
38
|
+
if (!existsSync(path)) continue
|
|
39
|
+
try {
|
|
40
|
+
latest = Math.max(latest, statSync(path).mtimeMs)
|
|
41
|
+
} catch {
|
|
42
|
+
// unreadable marker: treat as missing
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return latest
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Build the nudge message in the exact shape `dsh-agent-loop` expects for
|
|
50
|
+
* `followup()` (role 'user', content array, plugin source).
|
|
51
|
+
* @param {number} staleMinutes how long the store has been unwritten
|
|
52
|
+
* @returns {{ id: string, role: 'user', content: [{type:'text', text:string}], source: {kind:'plugin', plugin:string} }}
|
|
53
|
+
*/
|
|
54
|
+
export function buildDigestNudgeMessage(staleMinutes) {
|
|
55
|
+
return {
|
|
56
|
+
id: `memory-digest-${randomUUID()}`,
|
|
57
|
+
role: 'user',
|
|
58
|
+
content: [{
|
|
59
|
+
type: 'text',
|
|
60
|
+
text: [
|
|
61
|
+
`【记忆 digest 提醒】距上次记忆写入已超过 ${staleMinutes} 分钟。`,
|
|
62
|
+
'请现在执行 remember 沉淀:把本次会话值得持久化的关键事实、偏好、决策写回记忆库(更新对应页面与 index.md,并追加 log.md 条目)。',
|
|
63
|
+
'若本会话确实没有值得持久化的内容,也在 log.md 记一条「## [日期] digest | 无新增」并说明原因——这同样会解除提醒。',
|
|
64
|
+
'完成后继续手头的事即可,不要开启新任务。',
|
|
65
|
+
].join('\n'),
|
|
66
|
+
}],
|
|
67
|
+
source: { kind: 'plugin', plugin: 'memory' },
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* @typedef {object} DigestGuardOptions
|
|
73
|
+
* @property {() => { enabled: boolean, afterMinutes: number, cooldownMinutes: number, maxPerSession: number }} readConfig
|
|
74
|
+
* @property {() => string} getMemoryDir resolve the current store dir on every check
|
|
75
|
+
* @property {unknown} [agents] optional live-agent registry for liveness checks
|
|
76
|
+
* @property {{ info?: Function, warn?: Function }} [logger]
|
|
77
|
+
*/
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* One guard per live ROOT agent, lifecycle-hooked to the agent's context.
|
|
81
|
+
*/
|
|
82
|
+
export class DigestGuard {
|
|
83
|
+
/**
|
|
84
|
+
* @param {object} agent live root agent (ReactLoopAgent shape: ctx, status, inbox, followup)
|
|
85
|
+
* @param {DigestGuardOptions} options
|
|
86
|
+
*/
|
|
87
|
+
constructor(agent, options) {
|
|
88
|
+
this.agent = agent
|
|
89
|
+
this.readConfig = options.readConfig
|
|
90
|
+
this.getMemoryDir = options.getMemoryDir
|
|
91
|
+
this.agents = options.agents
|
|
92
|
+
this.logger = options.logger
|
|
93
|
+
this.disposed = false
|
|
94
|
+
this.stopTurnStopping = undefined
|
|
95
|
+
this.nudges = 0
|
|
96
|
+
this.lastNudgeAt = 0
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Subscribe to the agent's turn boundary. */
|
|
100
|
+
start() {
|
|
101
|
+
if (this.disposed) return
|
|
102
|
+
this.stopTurnStopping = this.agent.ctx.on?.('agent/turn-stopping', () => {
|
|
103
|
+
try {
|
|
104
|
+
this.onTurnStopped()
|
|
105
|
+
} catch (error) {
|
|
106
|
+
this.logger?.warn?.(`memory: digest check failed for agent "${this.agent.id}": ${error instanceof Error ? error.message : String(error)}`)
|
|
107
|
+
}
|
|
108
|
+
})
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Cancel subscriptions; the guard stops observing. */
|
|
112
|
+
dispose() {
|
|
113
|
+
this.disposed = true
|
|
114
|
+
this.stopTurnStopping?.()
|
|
115
|
+
this.stopTurnStopping = undefined
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Evaluate whether a digest reminder is due right now. */
|
|
119
|
+
onTurnStopped() {
|
|
120
|
+
if (this.disposed) return
|
|
121
|
+
if (this.agents && this.agents.get(this.agent.id) !== this.agent) {
|
|
122
|
+
this.dispose()
|
|
123
|
+
return
|
|
124
|
+
}
|
|
125
|
+
const config = this.readConfig()
|
|
126
|
+
if (!config.enabled) return
|
|
127
|
+
if (this.nudges >= Math.max(1, Number(config.maxPerSession ?? 2))) return
|
|
128
|
+
if (this.agent.status !== 'idle') return
|
|
129
|
+
const inbox = this.agent.inbox
|
|
130
|
+
if (inbox && Array.isArray(inbox.nextStep) && inbox.nextStep.length > 0) return
|
|
131
|
+
|
|
132
|
+
const now = Date.now()
|
|
133
|
+
const cooldownMs = Math.max(0, Number(config.cooldownMinutes ?? 180)) * 60000
|
|
134
|
+
if (now - this.lastNudgeAt < cooldownMs) return
|
|
135
|
+
|
|
136
|
+
const afterMs = Math.max(1, Number(config.afterMinutes ?? 120)) * 60000
|
|
137
|
+
const lastWrite = lastStoreWriteMs(this.getMemoryDir())
|
|
138
|
+
if (now - lastWrite < afterMs) return
|
|
139
|
+
|
|
140
|
+
const staleMinutes = Math.max(1, Math.round((now - lastWrite) / 60000))
|
|
141
|
+
this.agent.followup(buildDigestNudgeMessage(staleMinutes))
|
|
142
|
+
this.lastNudgeAt = now
|
|
143
|
+
this.nudges += 1
|
|
144
|
+
this.logger?.info?.(`memory: digest nudge #${this.nudges} for agent "${this.agent.id}" (store idle ${staleMinutes}min)`)
|
|
145
|
+
}
|
|
146
|
+
}
|
package/lib/index.js
CHANGED
|
@@ -76,6 +76,8 @@ import { renderBootBlock } from './boot.js'
|
|
|
76
76
|
import { ensureMemoryScaffold } from './scaffold.js'
|
|
77
77
|
import { MemoryConfigStore } from './config-store.js'
|
|
78
78
|
import { SettingsSchema } from './schema.js'
|
|
79
|
+
import { DigestGuard } from './digest-guard.js'
|
|
80
|
+
import { AutoCommitter } from './autocommit.js'
|
|
79
81
|
import {
|
|
80
82
|
MEMORY_SKILL_NAME,
|
|
81
83
|
MEMORY_SKILL_DESCRIPTION,
|
|
@@ -88,7 +90,7 @@ export const name = 'memory'
|
|
|
88
90
|
/** HTTP route serving the user-facing config to the browser Settings panel. */
|
|
89
91
|
export const CONFIG_ROUTE_PATH = '/api/memory/config'
|
|
90
92
|
|
|
91
|
-
export const inject = ['systemPrompt', 'skills']
|
|
93
|
+
export const inject = ['systemPrompt', 'skills', 'agents']
|
|
92
94
|
|
|
93
95
|
/** Schemastery schema applied to the plugin config before startup. */
|
|
94
96
|
export const Config = z.object({
|
|
@@ -100,6 +102,17 @@ export const Config = z.object({
|
|
|
100
102
|
registerSkill: z.boolean().default(true),
|
|
101
103
|
scaffold: z.boolean().default(true),
|
|
102
104
|
configFile: z.union([z.string(), z.const(undefined)]),
|
|
105
|
+
// Digest guard: inject a synthetic reminder when the agent sits idle and
|
|
106
|
+
// the store has not been written for a while, so the end-of-session
|
|
107
|
+
// digest cannot be silently skipped.
|
|
108
|
+
digestNudgeEnabled: z.boolean().default(true),
|
|
109
|
+
digestNudgeAfterMinutes: z.number().default(120),
|
|
110
|
+
digestNudgeCooldownMinutes: z.number().default(180),
|
|
111
|
+
digestNudgeMaxPerSession: z.number().default(2),
|
|
112
|
+
// Auto-commit: keep the store's git history current after a quiet period.
|
|
113
|
+
autoCommit: z.boolean().default(true),
|
|
114
|
+
autoCommitQuietSeconds: z.number().default(60),
|
|
115
|
+
autoCommitIntervalSeconds: z.number().default(60),
|
|
103
116
|
})
|
|
104
117
|
|
|
105
118
|
/**
|
|
@@ -139,6 +152,8 @@ export function apply(ctx, config = {}) {
|
|
|
139
152
|
let bootDispose
|
|
140
153
|
let skillDispose
|
|
141
154
|
let scaffoldedDir
|
|
155
|
+
let committer
|
|
156
|
+
let currentMemoryDir = resolveMemoryDir(store.get().memoryDir)
|
|
142
157
|
|
|
143
158
|
const disposeBoot = () => {
|
|
144
159
|
if (bootDispose !== undefined) {
|
|
@@ -154,6 +169,13 @@ export function apply(ctx, config = {}) {
|
|
|
154
169
|
}
|
|
155
170
|
}
|
|
156
171
|
|
|
172
|
+
const disposeCommitter = () => {
|
|
173
|
+
if (committer !== undefined) {
|
|
174
|
+
committer.dispose()
|
|
175
|
+
committer = undefined
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
157
179
|
/**
|
|
158
180
|
* Bring boot injection, skill registration and the scaffold in line with
|
|
159
181
|
* the current resolved config. Called once at startup and on every
|
|
@@ -174,6 +196,22 @@ export function apply(ctx, config = {}) {
|
|
|
174
196
|
}
|
|
175
197
|
}
|
|
176
198
|
|
|
199
|
+
// Auto-commit follows the store dir: create on first build, restart
|
|
200
|
+
// when the dir changes. (The first rebuild must create it too — the
|
|
201
|
+
// dir only "changes" on a later config edit.)
|
|
202
|
+
if (committer === undefined || memoryDir !== currentMemoryDir) {
|
|
203
|
+
currentMemoryDir = memoryDir
|
|
204
|
+
disposeCommitter()
|
|
205
|
+
if (resolved.enabled && config.autoCommit !== false) {
|
|
206
|
+
committer = new AutoCommitter(memoryDir, {
|
|
207
|
+
quietSeconds: config.autoCommitQuietSeconds,
|
|
208
|
+
intervalSeconds: config.autoCommitIntervalSeconds,
|
|
209
|
+
logger: ctx.logger,
|
|
210
|
+
})
|
|
211
|
+
committer.start()
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
177
215
|
if (wantBoot) {
|
|
178
216
|
disposeBoot()
|
|
179
217
|
bootDispose = ctx.systemPrompt.context({
|
|
@@ -207,6 +245,39 @@ export function apply(ctx, config = {}) {
|
|
|
207
245
|
|
|
208
246
|
rebuild()
|
|
209
247
|
|
|
248
|
+
// Digest guard: one per live ROOT agent, so a skipped end-of-session
|
|
249
|
+
// digest is caught mechanically instead of relying on the agent's
|
|
250
|
+
// self-discipline. Independent of dsh-plugin-heartbeat — the nudge is
|
|
251
|
+
// a plugin-source followup, queued behind whatever else the agent does.
|
|
252
|
+
if (config.digestNudgeEnabled !== false) {
|
|
253
|
+
ctx.effect(() => {
|
|
254
|
+
const stopCreated = ctx.on('agent/created', ({ agent }) => {
|
|
255
|
+
if (!ctx.agents.roots().includes(agent)) return
|
|
256
|
+
const guard = new DigestGuard(agent, {
|
|
257
|
+
readConfig: () => {
|
|
258
|
+
const resolved = store.get()
|
|
259
|
+
return {
|
|
260
|
+
enabled: resolved.enabled,
|
|
261
|
+
afterMinutes: config.digestNudgeAfterMinutes,
|
|
262
|
+
cooldownMinutes: config.digestNudgeCooldownMinutes,
|
|
263
|
+
maxPerSession: config.digestNudgeMaxPerSession,
|
|
264
|
+
}
|
|
265
|
+
},
|
|
266
|
+
getMemoryDir: () => currentMemoryDir,
|
|
267
|
+
agents: ctx.agents,
|
|
268
|
+
logger: ctx.logger,
|
|
269
|
+
})
|
|
270
|
+
agent.ctx.effect(() => {
|
|
271
|
+
guard.start()
|
|
272
|
+
return () => {
|
|
273
|
+
guard.dispose()
|
|
274
|
+
}
|
|
275
|
+
})
|
|
276
|
+
})
|
|
277
|
+
return () => stopCreated()
|
|
278
|
+
}, 'memory.digest-guard()')
|
|
279
|
+
}
|
|
280
|
+
|
|
210
281
|
// Settings-panel hot edits: any store change re-applies the config.
|
|
211
282
|
ctx.effect(() => {
|
|
212
283
|
const unwatch = store.watch(() => rebuild())
|
|
@@ -259,6 +330,7 @@ export function apply(ctx, config = {}) {
|
|
|
259
330
|
return () => {
|
|
260
331
|
disposeBoot()
|
|
261
332
|
disposeSkill()
|
|
333
|
+
disposeCommitter()
|
|
262
334
|
}
|
|
263
335
|
}
|
|
264
336
|
|
package/lib/scaffold.js
CHANGED
|
@@ -143,7 +143,7 @@ sources: [] # 指向 raw/ 或外部
|
|
|
143
143
|
## 规则(硬约束)
|
|
144
144
|
|
|
145
145
|
1. 启动必读 \`SOUL.md\` + \`MEMORY.md\` + \`index.md\`(本插件已自动注入)。
|
|
146
|
-
2.
|
|
146
|
+
2. **会话收尾前必须做 digest 沉淀**(写回页面 + index.md + 追加 log.md),否则记忆不更新;插件注入的 digest 提醒消息必须立即执行,确无内容时在 log.md 记「无新增」解除提醒。
|
|
147
147
|
3. \`raw/\` 只读,绝不修改。
|
|
148
148
|
4. 删除前优先归档;显式遗忘立即执行。
|
|
149
149
|
5. 冲突以本文件为准。
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-plugin-memory",
|
|
3
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.
|
|
4
|
+
"version": "0.4.0",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "lib/index.js",
|
|
@@ -37,6 +37,11 @@
|
|
|
37
37
|
"README.md",
|
|
38
38
|
"LICENSE"
|
|
39
39
|
],
|
|
40
|
+
"scripts": {
|
|
41
|
+
"test": "node scripts/memory.mjs --self-test",
|
|
42
|
+
"test:plugin": "node --test",
|
|
43
|
+
"lint:memory": "node scripts/memory.mjs lint"
|
|
44
|
+
},
|
|
40
45
|
"engines": {
|
|
41
46
|
"node": ">=18"
|
|
42
47
|
},
|
|
@@ -64,10 +69,5 @@
|
|
|
64
69
|
"bugs": {
|
|
65
70
|
"url": "https://github.com/LittleBlackTong/dsh-plugin-memory/issues"
|
|
66
71
|
},
|
|
67
|
-
"homepage": "https://github.com/LittleBlackTong/dsh-plugin-memory#readme"
|
|
68
|
-
|
|
69
|
-
"test": "node scripts/memory.mjs --self-test",
|
|
70
|
-
"test:plugin": "node --test test/plugin-metadata.test.mjs",
|
|
71
|
-
"lint:memory": "node scripts/memory.mjs lint"
|
|
72
|
-
}
|
|
73
|
-
}
|
|
72
|
+
"homepage": "https://github.com/LittleBlackTong/dsh-plugin-memory#readme"
|
|
73
|
+
}
|
package/scripts/memory.mjs
CHANGED
|
@@ -124,11 +124,14 @@ function cmdStatus(store) {
|
|
|
124
124
|
byType[t] = (byType[t] || 0) + 1
|
|
125
125
|
}
|
|
126
126
|
const last = walk(store).map((f) => statSync(f).mtimeMs).sort((a, b) => b - a)[0]
|
|
127
|
+
const logPath = join(store, 'log.md')
|
|
128
|
+
const logMtime = existsSync(logPath) ? statSync(logPath).mtimeMs : 0
|
|
127
129
|
console.log(`store: ${store}`)
|
|
128
130
|
console.log(`pages: ${ps.length}`)
|
|
129
131
|
console.log(`total page bytes: ${bytes}`)
|
|
130
132
|
console.log(`by type: ${JSON.stringify(byType)}`)
|
|
131
133
|
console.log(`last modified: ${last ? new Date(last).toISOString() : 'n/a'}`)
|
|
134
|
+
console.log(`last log write: ${logMtime ? `${new Date(logMtime).toISOString()} (${Math.round((Date.now() - logMtime) / 60000)} min ago)` : 'n/a'}`)
|
|
132
135
|
}
|
|
133
136
|
|
|
134
137
|
function manifestFor(storePath) {
|
package/skills/memory.md
CHANGED
|
@@ -9,8 +9,9 @@
|
|
|
9
9
|
插件会在会话开始时自动注入 boot 块(SOUL + MEMORY + index 摘要 + 最近动态)。你应当:
|
|
10
10
|
|
|
11
11
|
1. 先读 boot 块恢复「我是谁」与「我记住了什么」;
|
|
12
|
-
2. 检查
|
|
13
|
-
3.
|
|
12
|
+
2. 检查 boot 块是否含「铸魂阶段」引导词:记忆库还没有灵魂时,插件会在 boot 块前置一段第一人称引导词(「我的首要任务是确认我是谁,还有你是谁——我叫什么名字、怎么称呼你、你我是什么关系、我该是什么样的性格」+ 六步清单)——**照引导词主动发起铸魂对话**,一次问一项,逐项确认后立即写回 `SOUL.md` / `user/profile.md` / `BOOTSTRAP.md`;
|
|
13
|
+
3. 若 boot 块没有引导词、但 `BOOTSTRAP.md` 的 `status` 不是 `complete`,铸魂对话**同样是首要任务**——与用户逐项讨论定义灵魂(名字、性格、价值观、语气、边界)、确认用户身份与关系,写回对应文件,完成前不埋头做其他任务;
|
|
14
|
+
4. 按需 drill 进具体页面(先查 `index.md` 再读页)。
|
|
14
15
|
|
|
15
16
|
## 四个操作
|
|
16
17
|
|
|
@@ -23,7 +24,7 @@
|
|
|
23
24
|
|
|
24
25
|
- 只记**跨会话仍然有价值**的内容:关于用户的稳定事实、偏好、决策与理由、项目背景、学到的工具坑与工作流。不记一次性闲聊、不记能从当前对话直接看到的临时状态。
|
|
25
26
|
- 与用户偏好/语气相关的修正,优先写入 `SOUL.md`(经用户确认)或 `user/preferences.md`。
|
|
26
|
-
-
|
|
27
|
+
- **digest 是强制义务,不是可选项**:每次会话收尾前,把本会话的关键沉淀写回(页面 + `index.md` + `log.md`),否则「长期记忆」只是空话。当收到插件注入的 digest 提醒(一条 `source.kind === 'plugin'` 的合成消息)时**立即执行**,不得以「等会儿」拖延;若本会话确无值得持久化的内容,在 `log.md` 记一条「## [日期] digest | 无新增」并说明原因——这同样会解除提醒。
|
|
27
28
|
|
|
28
29
|
## 迁移与导出
|
|
29
30
|
|