dsh-plugin-memory 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,6 +18,9 @@
18
18
  - **复利记忆**:遵循 Karpathy 的 *LLM Wiki* 约定——记忆是"一次编译、持续保鲜"的持久产物,不是每次查询重新 RAG。remember / recall / consolidate / forget 四操作 + salience 三级衰减。
19
19
  - **可迁移**:记忆本体是纯 markdown + git + 自描述 schema,任何能读 markdown 的 agent 都能接手。`dsh-memory pack/unpack` 打包迁移。
20
20
  - **内嵌技能**:通过 `ctx.skills.register()` 注册 `memory` 技能(操作协议随插件分发);项目级 `.dsh/skills/memory` 文件技能仍可覆盖它。
21
+ - **防懒 digest 唤醒**:每轮结束后,若 agent 空闲且记忆库超过 `digestNudgeAfterMinutes` 未写入,插件注入一条 digest 提醒(合成消息,走 `agent.followup`),把"会话收尾沉淀"从靠自觉变成有机制兜底;带冷却与每会话限次,不骚扰。**独立于 dsh-plugin-heartbeat**,两插件各自可装、互不依赖。
22
+ - **git 自动提交**:记忆库变更静默 `autoCommitQuietSeconds` 后自动 `git add -A && git commit`(无 `.git` 则跳过)——历史可回滚不再依赖 agent 记得 commit。
23
+ - **设置面板**:在 DSH 设置页提供「记忆 Memory」区块——总开关、记忆目录、开机注入、技能注册四项均可热改,立即生效,无需重启。
21
24
  - **零构建**:纯 ESM JavaScript,无编译步骤,`pnpm add` 即用。
22
25
 
23
26
  ## 架构
@@ -26,9 +29,10 @@
26
29
 
27
30
  ```
28
31
  dsh-plugin-memory(本插件)
29
- ├── lib/index.js # Cordis 入口:boot 注入 + 运行时技能注册
32
+ ├── lib/index.js # Cordis 入口:boot 注入 + 运行时技能注册 + settings 热改
30
33
  ├── lib/boot.js # boot 块渲染(SOUL/MEMORY/index + 最近 log,限额截断)
31
34
  ├── lib/scaffold.js # 记忆库脚手架(模板只建不覆盖)
35
+ ├── lib/client.js # 客户端半:设置面板「记忆 Memory」区块
32
36
  ├── skills/memory.md # 内嵌技能的操作协议正文
33
37
  └── scripts/memory.mjs # CLI:init/search/lint/status/pack/unpack
34
38
 
@@ -44,40 +48,53 @@ dsh-plugin-memory(本插件)
44
48
  ## 安装
45
49
 
46
50
  ```sh
47
- # npm
48
- npm install dsh-plugin-memory
49
-
50
- # 或 pnpm(推荐,DSH 生态默认包管理器)
51
- pnpm add dsh-plugin-memory
51
+ dsh plugin --profile <profile> add dsh-plugin-memory
52
52
  ```
53
53
 
54
- 在你的 profile 的 `cordis.patch.yml` 中加入:
55
-
56
- ```yaml
57
- - insert:
58
- - id: dsh-memory
59
- name: dsh-plugin-memory
60
- inject:
61
- - systemPrompt
62
- - skills
63
- config:
64
- memoryDir: '~/.memory'
65
- ```
54
+ (包内置 `dsh.bundle` manifest,`dsh plugin add` 会把它自动挂进 profile 的 bundles 层;dsh-market 里的一键安装同此通道。)
66
55
 
67
56
  重启 profile(DSH Desktop 重启应用)后生效。
68
57
 
69
- `inject` 两项是必须的:`systemPrompt` 用于注入记忆 boot 块,`skills` 用于注册 `memory` 技能。
58
+ > ⚠️ **不要**再往 profile 的 `cordis.patch.yml` 里手写 `- insert: {id: dsh-memory, ...}`:
59
+ > 那会与 bundle manifest 的自动挂载产生两条同名 entry,整个 profile 会以
60
+ > `duplicate loader entry id "dsh-memory"` 启动失败(2026-08-18 实机事故)。
61
+ > 运行期配置(enabled / memoryDir / autoInject / registerSkill)改走
62
+ > `<dshHome>/memory.json`(设置面板热改);composition 配置见下表。
63
+ > 如需覆盖某个 composition 键,用**不带 insert 的 id 覆盖条目**(见配置一节)。
70
64
 
71
65
  ## 配置
72
66
 
73
67
  | 键 | 默认值 | 含义 |
74
68
  |---|---|---|
69
+ | `enabled` | `true` | 总开关:关闭后不注入 boot 块、不注册 `memory` 技能 |
75
70
  | `memoryDir` | `~/.memory` | 记忆库绝对路径(`~` 自动展开) |
76
71
  | `bootFiles` | `[SOUL.md, MEMORY.md, index.md]` | 开机注入的文件 |
77
72
  | `bootMaxChars` | `6000` | boot 块总字符预算(防止占用过多上下文) |
78
73
  | `autoInject` | `true` | 会话开始时注入 boot 块 |
79
74
  | `registerSkill` | `true` | 注册内嵌 `memory` 技能 |
80
75
  | `scaffold` | `true` | 记忆库缺失时自动创建模板(只建不覆盖) |
76
+ | `configFile` | `<dshHome>/memory.json` | 用户可改配置的 JSON 文件路径(设置面板读写它) |
77
+ | `digestNudgeEnabled` | `true` | 防懒 digest 提醒总开关(composition) |
78
+ | `digestNudgeAfterMinutes` | `120` | 记忆库超过多久未写入就提醒 |
79
+ | `digestNudgeCooldownMinutes` | `180` | 两次提醒的最小间隔 |
80
+ | `digestNudgeMaxPerSession` | `2` | 每个会话最多提醒次数 |
81
+ | `autoCommit` | `true` | 记忆库 git 自动提交开关(composition) |
82
+ | `autoCommitQuietSeconds` | `60` | 变更静默多久后提交(防抖) |
83
+ | `autoCommitIntervalSeconds` | `60` | 变更轮询间隔 |
84
+
85
+ ### 设置面板(热改)
86
+
87
+ `enabled` / `memoryDir` / `autoInject` / `registerSkill` 四项在 DSH 设置页的「记忆 Memory」区块中可改,**即时生效**:boot 注入、技能注册随修改立即重建;记忆目录切换时自动为新目录初始化脚手架(`scaffold: true` 时)。其余键(`bootFiles` / `bootMaxChars` / `scaffold` / `configFile` / `digestNudge*` / `autoCommit*`)只在 composition 配置层生效,改完需重启。
88
+
89
+ 覆盖 composition 键(例如把 boot 块预算调大),在 profile 的 `cordis.patch.yml` 里写**不带 `insert` 的 id 覆盖条目**:
90
+
91
+ ```yaml
92
+ - id: dsh-memory
93
+ config:
94
+ bootMaxChars: 12000
95
+ ```
96
+
97
+ > 实现说明:DSH 的 settings wire 只服务硬编码的命名空间白名单,插件命名空间写不进去,因此本插件走自建通道——配置存 `<dshHome>/memory.json`(schema 校验 + 原子落盘),由插件自注册的 `GET/POST /api/memory/config` 路由服务,客户端区块 fetch 直连。
81
98
 
82
99
  ## 首次使用:铸魂
83
100
 
@@ -0,0 +1,10 @@
1
+ # dsh-plugin-memory bundle layer.
2
+ #
3
+ # Declared via the `dsh.bundle.patch` manifest in package.json, so
4
+ # `dsh plugin add dsh-plugin-memory` (and the dsh-market install flow)
5
+ # mounts this insert automatically. User-level overrides — including the
6
+ # hot-editable `enabled` / `memoryDir` / `autoInject` / `registerSkill` —
7
+ # live in <dshHome>/memory.json, managed by the settings panel.
8
+ - insert:
9
+ - id: dsh-memory
10
+ name: dsh-plugin-memory
@@ -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
@@ -77,7 +77,7 @@ export function renderBootBlock(memoryDir, options = {}) {
77
77
  }
78
78
 
79
79
  const body = sections.join('\n\n---\n\n')
80
- const header = `长期记忆(dsh-plugin-memory)。记忆库位于 ${memoryDir}。这是你跨会话的持久人格与记忆:以它为准,先读完再回复用户。若与当前对话冲突,优先相信用户的最新表述,并把差异写回记忆。`
80
+ const header = `长期记忆(dsh-plugin-memory)。记忆库位于 ${memoryDir}。这是你跨会话的持久人格与记忆:以它为准,先读完再回复用户。若与当前对话冲突,优先相信用户的最新表述,并把差异写回记忆。**每次会话收尾前必须执行 memory digest:把本会话关键沉淀写回(更新页面 + index.md + 追加 log.md)。插件会注入 digest 提醒消息,收到后立即写回,不得拖延;若本会话确无值得持久化的内容,在 log.md 记一条「无新增」并说明原因。**`
81
81
 
82
82
  let result = `${header}\n\n${body}`
83
83
  if (result.length > total) {
package/lib/client.js ADDED
@@ -0,0 +1,242 @@
1
+ /**
2
+ * dsh-plugin-memory 客户端半(零构建):
3
+ * 在设置面板注册「记忆 Memory」区块 —— 总开关 + 记忆目录 + 两个子开关。
4
+ *
5
+ * 数据通道:settings wire 只服务硬编码白名单(memory 不在其中),
6
+ * 因此本区块直连插件自建的 HTTP 路由(/api/memory/config):
7
+ * GET 读配置、POST 部分更新,Host 校验并立即热应用。
8
+ */
9
+ window.__ModuleLoader__.load({
10
+ id: 'dsh-plugin-memory',
11
+ factory: (require) => {
12
+ var module = { exports: {} }
13
+ var exports = module.exports
14
+ let react = require('react')
15
+
16
+ const React = react
17
+ const CONFIG_URL = '/api/memory/config'
18
+
19
+ const rowStyle = {
20
+ display: 'flex',
21
+ alignItems: 'center',
22
+ justifyContent: 'space-between',
23
+ gap: '12px',
24
+ padding: '14px 16px',
25
+ borderBottom: '1px solid var(--dsw-alias-border-l1, rgba(128,128,128,0.2))',
26
+ }
27
+ const labelStyle = { fontSize: '14px', lineHeight: '22px' }
28
+ const subStyle = { fontSize: '12px', lineHeight: '18px', color: 'var(--dsw-alias-label-secondary, #999)' }
29
+ const errorStyle = { padding: '0 16px 8px', fontSize: '12px', lineHeight: '18px', color: 'var(--dsw-alias-state-error-primary, #e5484d)' }
30
+ const inputStyle = {
31
+ width: '240px',
32
+ padding: '6px 8px',
33
+ fontSize: '14px',
34
+ borderRadius: '6px',
35
+ border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.35))',
36
+ background: 'var(--dsw-alias-bg-layer-1, transparent)',
37
+ color: 'var(--dsw-alias-label-primary, inherit)',
38
+ }
39
+
40
+ function Toggle({ checked, disabled, onChange }) {
41
+ return React.createElement('button', {
42
+ type: 'button',
43
+ role: 'switch',
44
+ 'aria-checked': checked,
45
+ disabled,
46
+ onClick: () => onChange(!checked),
47
+ style: {
48
+ position: 'relative',
49
+ width: '40px',
50
+ height: '22px',
51
+ borderRadius: '11px',
52
+ border: 'none',
53
+ cursor: disabled ? 'not-allowed' : 'pointer',
54
+ background: checked ? 'var(--dsw-alias-brand-primary, #4c8bf5)' : 'var(--dsw-alias-label-secondary, #666)',
55
+ opacity: disabled ? 0.5 : 1,
56
+ transition: 'background 0.15s',
57
+ flexShrink: 0,
58
+ },
59
+ }, React.createElement('span', {
60
+ style: {
61
+ position: 'absolute',
62
+ top: '2px',
63
+ left: checked ? '20px' : '2px',
64
+ width: '18px',
65
+ height: '18px',
66
+ borderRadius: '9px',
67
+ background: '#fff',
68
+ transition: 'left 0.15s',
69
+ },
70
+ }))
71
+ }
72
+
73
+ function ErrorText({ message }) {
74
+ return React.createElement('div', { style: { padding: '14px 16px', fontSize: '13px', lineHeight: '20px', color: 'var(--dsw-alias-state-error-primary, #e5484d)' } },
75
+ '记忆设置页加载失败:', message)
76
+ }
77
+
78
+ /** 渲染期兜底:任何异常都以文案形式显示,绝不空白。 */
79
+ class SectionBoundary extends React.Component {
80
+ constructor(props) {
81
+ super(props)
82
+ this.state = { error: undefined }
83
+ }
84
+ static getDerivedStateFromError(error) {
85
+ return { error: error instanceof Error ? error.message : String(error) }
86
+ }
87
+ render() {
88
+ if (this.state.error !== undefined) return React.createElement(ErrorText, { message: this.state.error })
89
+ return this.props.children
90
+ }
91
+ }
92
+
93
+ function MemorySection() {
94
+ return React.createElement(SectionBoundary, null, React.createElement(MemoryForm))
95
+ }
96
+
97
+ /** 目录输入:草稿态编辑,blur / Enter 才写回,避免每次按键触发 Host 重排。 */
98
+ function DirInput({ value, disabled, onCommit }) {
99
+ const [draft, setDraft] = React.useState(undefined)
100
+ const shown = draft !== undefined ? draft : (value ?? '')
101
+ const commit = () => {
102
+ if (draft === undefined) return
103
+ const trimmed = draft.trim()
104
+ if (trimmed.length > 0 && trimmed !== value) onCommit(trimmed)
105
+ setDraft(undefined)
106
+ }
107
+ return React.createElement('input', {
108
+ type: 'text',
109
+ placeholder: '~/.memory',
110
+ disabled,
111
+ value: shown,
112
+ onChange: (event) => setDraft(event.target.value),
113
+ onBlur: commit,
114
+ onKeyDown: (event) => {
115
+ if (event.key === 'Enter') commit()
116
+ if (event.key === 'Escape') setDraft(undefined)
117
+ },
118
+ style: inputStyle,
119
+ })
120
+ }
121
+
122
+ function MemoryForm() {
123
+ const [config, setConfig] = React.useState(undefined)
124
+ const [status, setStatus] = React.useState('loading')
125
+ const [error, setError] = React.useState(undefined)
126
+ const [saving, setSaving] = React.useState(false)
127
+
128
+ React.useEffect(() => {
129
+ let alive = true
130
+ fetch(CONFIG_URL)
131
+ .then(async (response) => {
132
+ if (!response.ok) throw new Error(`GET ${response.status}`)
133
+ return response.json()
134
+ })
135
+ .then((value) => {
136
+ if (!alive) return
137
+ setConfig(value)
138
+ setStatus('ready')
139
+ })
140
+ .catch((err) => {
141
+ if (!alive) return
142
+ setStatus('failed')
143
+ setError(err instanceof Error ? err.message : String(err))
144
+ })
145
+ return () => {
146
+ alive = false
147
+ }
148
+ }, [])
149
+
150
+ const apply = (patch) => {
151
+ setSaving(true)
152
+ setError(undefined)
153
+ fetch(CONFIG_URL, {
154
+ method: 'POST',
155
+ headers: { 'content-type': 'application/json' },
156
+ body: JSON.stringify(patch),
157
+ })
158
+ .then(async (response) => {
159
+ const body = await response.json().catch(() => ({}))
160
+ if (!response.ok) throw new Error(body.error ?? `POST ${response.status}`)
161
+ setConfig(body)
162
+ })
163
+ .catch((err) => {
164
+ setError(err instanceof Error ? err.message : String(err))
165
+ })
166
+ .finally(() => setSaving(false))
167
+ }
168
+
169
+ if (status === 'loading') {
170
+ return React.createElement('div', { style: { padding: '14px 16px', fontSize: '13px', color: 'var(--dsw-alias-label-secondary, #888)' } }, '读取配置中…')
171
+ }
172
+ if (status === 'failed') return React.createElement(ErrorText, { message: error ?? 'unknown' })
173
+
174
+ const value = config ?? {}
175
+ const disabled = saving
176
+
177
+ return React.createElement('div', { style: { padding: '8px 0' } },
178
+ React.createElement('div', { style: rowStyle },
179
+ React.createElement('div', null,
180
+ React.createElement('div', { style: labelStyle }, '启用记忆插件'),
181
+ React.createElement('div', { style: subStyle }, '总开关:关闭后不再注入记忆,也不注册 memory 技能'),
182
+ ),
183
+ React.createElement(Toggle, {
184
+ checked: value.enabled !== false,
185
+ disabled,
186
+ onChange: (next) => apply({ enabled: next }),
187
+ }),
188
+ ),
189
+ React.createElement('div', { style: rowStyle },
190
+ React.createElement('div', null,
191
+ React.createElement('div', { style: labelStyle }, '记忆目录'),
192
+ React.createElement('div', { style: subStyle }, '存放 SOUL/MEMORY/index/log 的路径,支持 ~ 开头;修改后立即切换,目录不存在时自动初始化'),
193
+ ),
194
+ React.createElement(DirInput, {
195
+ value: value.memoryDir,
196
+ disabled,
197
+ onCommit: (next) => apply({ memoryDir: next }),
198
+ }),
199
+ ),
200
+ React.createElement('div', { style: rowStyle },
201
+ React.createElement('div', null,
202
+ React.createElement('div', { style: labelStyle }, '开机注入记忆'),
203
+ React.createElement('div', { style: subStyle }, '每次会话开始把记忆快照注入上下文'),
204
+ ),
205
+ React.createElement(Toggle, {
206
+ checked: value.autoInject !== false,
207
+ disabled,
208
+ onChange: (next) => apply({ autoInject: next }),
209
+ }),
210
+ ),
211
+ React.createElement('div', { style: rowStyle },
212
+ React.createElement('div', null,
213
+ React.createElement('div', { style: labelStyle }, '注册 memory 技能'),
214
+ React.createElement('div', { style: subStyle }, '让 agent 获得 remember / recall / consolidate / forget 操作协议'),
215
+ ),
216
+ React.createElement(Toggle, {
217
+ checked: value.registerSkill !== false,
218
+ disabled,
219
+ onChange: (next) => apply({ registerSkill: next }),
220
+ }),
221
+ ),
222
+ error !== undefined ? React.createElement('div', { style: errorStyle }, '保存失败:', error) : null,
223
+ React.createElement('div', { style: { padding: '14px 16px', fontSize: '12px', lineHeight: '18px', color: 'var(--dsw-alias-label-secondary, #888)' } },
224
+ `当前:${value.enabled === false ? '已停用' : `记忆库位于 ${value.memoryDir ?? '(未配置)'}`}。修改即时生效。`,
225
+ ),
226
+ )
227
+ }
228
+
229
+ function apply(ctx) {
230
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
231
+ name: 'settings.section',
232
+ id: 'memory',
233
+ order: 100,
234
+ label: () => '记忆 Memory',
235
+ }, MemorySection))
236
+ }
237
+
238
+ exports.apply = apply
239
+ exports.inject = ['slots']
240
+ return module.exports
241
+ },
242
+ })
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Memory configuration store: one JSON file as the single user-facing
3
+ * config source, layered over the composition defaults.
4
+ *
5
+ * Why not the `settings` service? The Web settings wire only serves a
6
+ * hard-coded allowlist (`WEB_SETTINGS_NAMESPACES` in dsh-host-apiproxy) and
7
+ * rejects every other namespace with `settings-not-exposed`; a plugin cannot
8
+ * add itself to that list yet. This store keeps the same "base + user layer"
9
+ * semantics with a private JSON file and an in-process watch, and the plugin
10
+ * serves it over its own HTTP route for the browser UI.
11
+ *
12
+ * @module dsh-plugin-memory/config-store
13
+ */
14
+
15
+ import { existsSync, readFileSync, renameSync, writeFileSync, mkdirSync } from 'node:fs'
16
+ import { dirname, join } from 'node:path'
17
+ import { homedir } from 'node:os'
18
+ import { SettingsSchema } from './schema.js'
19
+
20
+ export const MEMORY_CONFIG_FILENAME = 'memory.json'
21
+
22
+ export function defaultConfigPath() {
23
+ return join(process.env.DSH_HOME || join(homedir(), '.dsh'), MEMORY_CONFIG_FILENAME)
24
+ }
25
+
26
+ const FIELDS = ['enabled', 'memoryDir', 'autoInject', 'registerSkill']
27
+
28
+ function pickFields(input) {
29
+ const picked = {}
30
+ for (const key of FIELDS) {
31
+ if (input[key] !== undefined) picked[key] = input[key]
32
+ }
33
+ return picked
34
+ }
35
+
36
+ /**
37
+ * @typedef {object} MemorySettings
38
+ * @property {boolean} enabled
39
+ * @property {string} memoryDir
40
+ * @property {boolean} autoInject
41
+ * @property {boolean} registerSkill
42
+ */
43
+
44
+ /**
45
+ * @param {object} options
46
+ * @param {string} [options.path] absolute config-file path (defaults to `<dshHome>/memory.json`)
47
+ * @param {object} [options.base] composition defaults ({enabled, memoryDir, autoInject, registerSkill})
48
+ */
49
+ export class MemoryConfigStore {
50
+ constructor(options = {}) {
51
+ this.path = options.path ?? defaultConfigPath()
52
+ this.base = {
53
+ enabled: options.base?.enabled !== false,
54
+ memoryDir: typeof options.base?.memoryDir === 'string' && options.base.memoryDir.trim().length > 0
55
+ ? options.base.memoryDir
56
+ : '~/.memory',
57
+ autoInject: options.base?.autoInject !== false,
58
+ registerSkill: options.base?.registerSkill !== false,
59
+ }
60
+ this.config = { ...this.base }
61
+ this.watchers = new Set()
62
+ this.load()
63
+ }
64
+
65
+ /** Read the user file if present; invalid files are ignored, not fatal. */
66
+ load() {
67
+ let raw
68
+ try {
69
+ if (!existsSync(this.path)) return
70
+ raw = JSON.parse(readFileSync(this.path, 'utf8'))
71
+ } catch {
72
+ return // corrupt file: keep last good config
73
+ }
74
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return
75
+ try {
76
+ const picked = pickFields(raw)
77
+ if (picked.memoryDir !== undefined && (typeof picked.memoryDir !== 'string' || picked.memoryDir.trim().length === 0)) return
78
+ const resolved = SettingsSchema({ ...this.base, ...picked })
79
+ this.config = {
80
+ enabled: resolved.enabled,
81
+ memoryDir: resolved.memoryDir,
82
+ autoInject: resolved.autoInject,
83
+ registerSkill: resolved.registerSkill,
84
+ }
85
+ } catch {
86
+ // schema validation failed: keep last good config
87
+ }
88
+ }
89
+
90
+ /** Current effective config (stable reference until the next update). */
91
+ get() {
92
+ return this.config
93
+ }
94
+
95
+ /**
96
+ * Apply a partial update, persist it, and notify watchers.
97
+ * @param {Partial<MemorySettings>} patch
98
+ * @returns {MemorySettings} the new effective config
99
+ * @throws {Error} on invalid fields or values
100
+ */
101
+ update(patch) {
102
+ if (typeof patch !== 'object' || patch === null) throw new Error('config patch must be an object')
103
+ const picked = pickFields(patch)
104
+ if (picked.memoryDir !== undefined && (typeof picked.memoryDir !== 'string' || picked.memoryDir.trim().length === 0)) {
105
+ throw new Error('memoryDir must be a non-empty path string')
106
+ }
107
+ const next = SettingsSchema({
108
+ ...this.base,
109
+ ...this.config,
110
+ ...picked,
111
+ })
112
+ this.config = {
113
+ enabled: next.enabled,
114
+ memoryDir: next.memoryDir,
115
+ autoInject: next.autoInject,
116
+ registerSkill: next.registerSkill,
117
+ }
118
+ this.persist()
119
+ for (const watcher of this.watchers) {
120
+ try {
121
+ watcher(this.config)
122
+ } catch {
123
+ // best-effort notification
124
+ }
125
+ }
126
+ return this.config
127
+ }
128
+
129
+ /** Subscribe to config changes; returns the disposer. */
130
+ watch(callback) {
131
+ this.watchers.add(callback)
132
+ return () => this.watchers.delete(callback)
133
+ }
134
+
135
+ persist() {
136
+ try {
137
+ mkdirSync(dirname(this.path), { recursive: true })
138
+ const tmp = `${this.path}.tmp`
139
+ writeFileSync(tmp, `${JSON.stringify(this.config, null, 2)}\n`)
140
+ renameSync(tmp, this.path)
141
+ } catch (error) {
142
+ // Persistence is best-effort; the in-memory config is already applied.
143
+ // Surface the failure so the route can report it.
144
+ throw new Error(`config persisted in memory but not to disk: ${error instanceof Error ? error.message : String(error)}`)
145
+ }
146
+ }
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
@@ -19,6 +19,13 @@
19
19
  * pack / unpack) so memory stays usable from a shell and migratable
20
20
  * across machines and agents.
21
21
  *
22
+ * 4. **Settings panel.** `enabled` / `memoryDir` / `autoInject` /
23
+ * `registerSkill` are editable in the Settings panel and hot-apply.
24
+ * They live in `<dshHome>/memory.json` and are served to the browser
25
+ * through the plugin's own HTTP route — the settings wire only serves
26
+ * a hard-coded namespace allowlist, so a plugin namespace is never
27
+ * remotely writable (see `lib/config-store.js`).
28
+ *
22
29
  * The memory store itself is plain markdown + git — the plugin never owns
23
30
  * the format, only the workflows around it.
24
31
  *
@@ -26,12 +33,19 @@
26
33
  *
27
34
  * | key | default | meaning |
28
35
  * |---|---|---|
36
+ * | `enabled` | `true` | master switch: stops boot injection AND skill registration |
29
37
  * | `memoryDir` | `~/.memory` | absolute memory-store path (`~` expanded) |
30
38
  * | `bootFiles` | `[SOUL.md, MEMORY.md, index.md]` | files injected at boot |
31
39
  * | `bootMaxChars` | `6000` | total character budget of the boot block |
32
40
  * | `autoInject` | `true` | inject the boot block at session start |
33
41
  * | `registerSkill` | `true` | register the embedded `memory` skill |
34
42
  * | `scaffold` | `true` | create the store layout + templates when missing |
43
+ * | `configFile` | `<dshHome>/memory.json` | user-facing config file (Settings panel) |
44
+ *
45
+ * `enabled`, `memoryDir`, `autoInject` and `registerSkill` are editable in
46
+ * the Settings panel and hot-apply: boot injection, the skill registration
47
+ * and the scaffold react to edits immediately. The other keys are
48
+ * composition-time only.
35
49
  *
36
50
  * ## Install
37
51
  *
@@ -60,6 +74,10 @@ import { join, resolve } from 'node:path'
60
74
  import z from '@deepseek-ai/schemastery'
61
75
  import { renderBootBlock } from './boot.js'
62
76
  import { ensureMemoryScaffold } from './scaffold.js'
77
+ import { MemoryConfigStore } from './config-store.js'
78
+ import { SettingsSchema } from './schema.js'
79
+ import { DigestGuard } from './digest-guard.js'
80
+ import { AutoCommitter } from './autocommit.js'
63
81
  import {
64
82
  MEMORY_SKILL_NAME,
65
83
  MEMORY_SKILL_DESCRIPTION,
@@ -69,16 +87,32 @@ import {
69
87
 
70
88
  export const name = 'memory'
71
89
 
72
- export const inject = ['systemPrompt', 'skills']
90
+ /** HTTP route serving the user-facing config to the browser Settings panel. */
91
+ export const CONFIG_ROUTE_PATH = '/api/memory/config'
92
+
93
+ export const inject = ['systemPrompt', 'skills', 'agents']
73
94
 
74
95
  /** Schemastery schema applied to the plugin config before startup. */
75
96
  export const Config = z.object({
97
+ enabled: z.boolean().default(true),
76
98
  memoryDir: z.string().default('~/.memory'),
77
99
  bootFiles: z.array(z.string()).default(['SOUL.md', 'MEMORY.md', 'index.md']),
78
100
  bootMaxChars: z.number().default(6000),
79
101
  autoInject: z.boolean().default(true),
80
102
  registerSkill: z.boolean().default(true),
81
103
  scaffold: z.boolean().default(true),
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),
82
116
  })
83
117
 
84
118
  /**
@@ -100,50 +134,203 @@ export function resolveMemoryDir(dir) {
100
134
  * @returns {() => void} disposer
101
135
  */
102
136
  export function apply(ctx, config = {}) {
103
- const memoryDir = resolveMemoryDir(config.memoryDir ?? '~/.memory')
104
137
  const bootMaxChars = Math.max(512, Number(config.bootMaxChars) || 6000)
138
+ const bootFiles = config.bootFiles ?? ['SOUL.md', 'MEMORY.md', 'index.md']
139
+ const scaffoldEnabled = config.scaffold !== false
140
+
141
+ // Single user-facing config source: composition defaults + memory.json.
142
+ const store = new MemoryConfigStore({
143
+ path: typeof config.configFile === 'string' && config.configFile.trim().length > 0 ? config.configFile : undefined,
144
+ base: {
145
+ enabled: config.enabled !== false,
146
+ memoryDir: config.memoryDir ?? '~/.memory',
147
+ autoInject: config.autoInject !== false,
148
+ registerSkill: config.registerSkill !== false,
149
+ },
150
+ })
105
151
 
106
- if (config.scaffold !== false) {
107
- const created = ensureMemoryScaffold(memoryDir)
108
- if (created.length > 0) {
109
- ctx.logger?.info(`memory: initialized scaffold at ${memoryDir} (${created.length} entries)`)
152
+ let bootDispose
153
+ let skillDispose
154
+ let scaffoldedDir
155
+ let committer
156
+ let currentMemoryDir = resolveMemoryDir(store.get().memoryDir)
157
+
158
+ const disposeBoot = () => {
159
+ if (bootDispose !== undefined) {
160
+ bootDispose()
161
+ bootDispose = undefined
110
162
  }
111
163
  }
112
164
 
113
- const disposers = []
114
-
115
- if (config.autoInject !== false) {
116
- disposers.push(ctx.systemPrompt.context({
117
- name: 'memory-boot',
118
- order: -200,
119
- text: () => renderBootBlock(memoryDir, {
120
- bootFiles: config.bootFiles ?? ['SOUL.md', 'MEMORY.md', 'index.md'],
121
- bootMaxChars,
122
- }),
123
- }))
165
+ const disposeSkill = () => {
166
+ if (skillDispose !== undefined) {
167
+ skillDispose()
168
+ skillDispose = undefined
169
+ }
124
170
  }
125
171
 
126
- if (config.registerSkill !== false) {
127
- disposers.push(ctx.skills.register({
128
- name: MEMORY_SKILL_NAME,
129
- description: MEMORY_SKILL_DESCRIPTION,
130
- whenToUse: MEMORY_SKILL_WHEN_TO_USE,
131
- content: memorySkillContent(),
132
- source: 'dsh-plugin-memory',
133
- resourceBase: { kind: 'directory', path: memoryDir },
134
- }))
172
+ const disposeCommitter = () => {
173
+ if (committer !== undefined) {
174
+ committer.dispose()
175
+ committer = undefined
176
+ }
135
177
  }
136
178
 
137
- ctx.logger?.info(`memory: store at ${memoryDir}`)
179
+ /**
180
+ * Bring boot injection, skill registration and the scaffold in line with
181
+ * the current resolved config. Called once at startup and on every
182
+ * config-store change; teardown + re-register keeps it correct for both
183
+ * toggle and memory-dir edits.
184
+ */
185
+ const rebuild = () => {
186
+ const resolved = store.get()
187
+ const memoryDir = resolveMemoryDir(resolved.memoryDir)
188
+ const wantBoot = resolved.enabled && resolved.autoInject
189
+ const wantSkill = resolved.enabled && resolved.registerSkill
138
190
 
139
- return () => {
140
- for (const dispose of disposers) {
141
- try {
142
- dispose()
143
- } catch {
144
- // best-effort teardown
191
+ if (resolved.enabled && scaffoldEnabled && memoryDir !== scaffoldedDir) {
192
+ const created = ensureMemoryScaffold(memoryDir)
193
+ scaffoldedDir = memoryDir
194
+ if (created.length > 0) {
195
+ ctx.logger?.info(`memory: initialized scaffold at ${memoryDir} (${created.length} entries)`)
196
+ }
197
+ }
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()
145
212
  }
146
213
  }
214
+
215
+ if (wantBoot) {
216
+ disposeBoot()
217
+ bootDispose = ctx.systemPrompt.context({
218
+ name: 'memory-boot',
219
+ order: -200,
220
+ text: () => renderBootBlock(memoryDir, { bootFiles, bootMaxChars }),
221
+ })
222
+ } else {
223
+ disposeBoot()
224
+ }
225
+
226
+ if (wantSkill) {
227
+ disposeSkill()
228
+ skillDispose = ctx.skills.register({
229
+ name: MEMORY_SKILL_NAME,
230
+ description: MEMORY_SKILL_DESCRIPTION,
231
+ whenToUse: MEMORY_SKILL_WHEN_TO_USE,
232
+ content: memorySkillContent(),
233
+ source: 'dsh-plugin-memory',
234
+ resourceBase: { kind: 'directory', path: memoryDir },
235
+ })
236
+ } else {
237
+ disposeSkill()
238
+ }
239
+
240
+ ctx.logger?.info(
241
+ `memory: ${resolved.enabled ? `enabled, store at ${memoryDir}` : 'disabled'}`
242
+ + ` (boot ${wantBoot ? 'on' : 'off'}, skill ${wantSkill ? 'on' : 'off'})`,
243
+ )
244
+ }
245
+
246
+ rebuild()
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
+
281
+ // Settings-panel hot edits: any store change re-applies the config.
282
+ ctx.effect(() => {
283
+ const unwatch = store.watch(() => rebuild())
284
+ return () => {
285
+ unwatch()
286
+ }
287
+ }, 'memory.config-watch()')
288
+
289
+ // Browser config route (optional: headless deployments have no webServer).
290
+ ctx.inject(['webServer'], (webCtx) => {
291
+ const disposeRoute = webCtx.webServer.register({
292
+ kind: 'exact',
293
+ path: CONFIG_ROUTE_PATH,
294
+ handler: async (req, res) => {
295
+ try {
296
+ if (req.method === 'GET') {
297
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
298
+ res.end(JSON.stringify(store.get()))
299
+ return
300
+ }
301
+ if (req.method === 'POST') {
302
+ const chunks = []
303
+ for await (const chunk of req) chunks.push(chunk)
304
+ const body = Buffer.concat(chunks).toString('utf8')
305
+ let patch
306
+ try {
307
+ patch = JSON.parse(body)
308
+ } catch {
309
+ res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
310
+ res.end(JSON.stringify({ error: 'body must be JSON' }))
311
+ return
312
+ }
313
+ const next = store.update(patch)
314
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
315
+ res.end(JSON.stringify(next))
316
+ return
317
+ }
318
+ res.writeHead(405, { 'content-type': 'application/json; charset=utf-8' })
319
+ res.end(JSON.stringify({ error: 'method not allowed' }))
320
+ } catch (error) {
321
+ res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
322
+ res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }))
323
+ }
324
+ },
325
+ })
326
+ webCtx.effect(() => disposeRoute, 'memory.config-route()')
327
+ ctx.logger?.info(`memory: config route at ${CONFIG_ROUTE_PATH} (store ${store.path})`)
328
+ })
329
+
330
+ return () => {
331
+ disposeBoot()
332
+ disposeSkill()
333
+ disposeCommitter()
147
334
  }
148
335
  }
149
336
 
@@ -159,4 +346,4 @@ Object.defineProperties(apply, {
159
346
 
160
347
  export default apply
161
348
 
162
- export { renderBootBlock, ensureMemoryScaffold }
349
+ export { renderBootBlock, ensureMemoryScaffold, SettingsSchema, MemoryConfigStore }
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. 会话结束前做 digest 沉淀,否则记忆不更新。
146
+ 2. **会话收尾前必须做 digest 沉淀**(写回页面 + index.md + 追加 log.md),否则记忆不更新;插件注入的 digest 提醒消息必须立即执行,确无内容时在 log.md 记「无新增」解除提醒。
147
147
  3. \`raw/\` 只读,绝不修改。
148
148
  4. 删除前优先归档;显式遗忘立即执行。
149
149
  5. 冲突以本文件为准。
package/lib/schema.js ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Shared schemas for dsh-plugin-memory.
3
+ *
4
+ * Split out so the config store can validate without importing the plugin
5
+ * entry (which imports the store).
6
+ *
7
+ * @module dsh-plugin-memory/schema
8
+ */
9
+
10
+ import z from '@deepseek-ai/schemastery'
11
+
12
+ /** The user-facing settings schema: composition config is the base layer. */
13
+ export const SettingsSchema = z.object({
14
+ enabled: z.boolean().default(true),
15
+ memoryDir: z.string().default('~/.memory'),
16
+ autoInject: z.boolean().default(true),
17
+ registerSkill: z.boolean().default(true),
18
+ })
@@ -14,6 +14,8 @@ export const inject: ['systemPrompt', 'skills']
14
14
 
15
15
  /** User-facing plugin configuration (all fields optional). */
16
16
  export interface MemoryConfig {
17
+ /** Master switch: stops boot injection AND skill registration. Default `true`. */
18
+ enabled?: boolean
17
19
  /** Absolute memory-store path; `~` is expanded. Default `'~/.memory'`. */
18
20
  memoryDir?: string
19
21
  /** Files injected at session start. Default `['SOUL.md', 'MEMORY.md', 'index.md']`. */
@@ -26,11 +28,39 @@ export interface MemoryConfig {
26
28
  registerSkill?: boolean
27
29
  /** Create the store layout and templates when missing. Default `true`. */
28
30
  scaffold?: boolean
31
+ /** Absolute user-facing config-file path. Default `<dshHome>/memory.json`. */
32
+ configFile?: string
29
33
  }
30
34
 
31
35
  /** Schemastery schema for {@link MemoryConfig}. */
32
36
  export const Config: import('@deepseek-ai/schemastery').default<MemoryConfig>
33
37
 
38
+ /** HTTP route serving the user-facing config to the Settings panel. */
39
+ export const CONFIG_ROUTE_PATH: '/api/memory/config'
40
+
41
+ /** User-editable settings (composition config is the base layer). */
42
+ export interface MemorySettings {
43
+ enabled?: boolean
44
+ memoryDir?: string
45
+ autoInject?: boolean
46
+ registerSkill?: boolean
47
+ }
48
+
49
+ /** Schemastery schema for {@link MemorySettings}. */
50
+ export const SettingsSchema: import('@deepseek-ai/schemastery').default<MemorySettings>
51
+
52
+ /** JSON config store: base + user layer, atomic persist, in-process watch. */
53
+ export class MemoryConfigStore {
54
+ constructor(options?: { path?: string; base?: MemorySettings })
55
+ readonly path: string
56
+ get(): MemorySettings
57
+ update(patch: Partial<MemorySettings>): MemorySettings
58
+ watch(callback: (config: MemorySettings) => void): () => void
59
+ }
60
+
61
+ /** Default config-file path (`<dshHome>/memory.json`). */
62
+ export function defaultConfigPath(): string
63
+
34
64
  /** Expand `~` and resolve `dir` to an absolute path. */
35
65
  export function resolveMemoryDir(dir: string): string
36
66
 
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.1.1",
4
+ "version": "0.3.0",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",
@@ -14,21 +14,29 @@
14
14
  "types": "./lib/types/index.d.ts",
15
15
  "default": "./lib/index.js"
16
16
  },
17
+ "./client": "./lib/client.js",
17
18
  "./package.json": "./package.json"
18
19
  },
20
+ "dsh": {
21
+ "bundle": {
22
+ "patch": "./cordis.patch.yml"
23
+ },
24
+ "client": {
25
+ "platform": "web",
26
+ "inject": [
27
+ "@deepseek-ai/dsh-client-runtime"
28
+ ]
29
+ }
30
+ },
19
31
  "files": [
20
32
  "lib/**",
21
33
  "skills/**",
22
34
  "scripts/**",
23
35
  "docs/**",
36
+ "cordis.patch.yml",
24
37
  "README.md",
25
38
  "LICENSE"
26
39
  ],
27
- "scripts": {
28
- "test": "node scripts/memory.mjs --self-test",
29
- "test:plugin": "node --test test/plugin-metadata.test.mjs",
30
- "lint:memory": "node scripts/memory.mjs lint"
31
- },
32
40
  "engines": {
33
41
  "node": ">=18"
34
42
  },
@@ -56,5 +64,10 @@
56
64
  "bugs": {
57
65
  "url": "https://github.com/LittleBlackTong/dsh-plugin-memory/issues"
58
66
  },
59
- "homepage": "https://github.com/LittleBlackTong/dsh-plugin-memory#readme"
60
- }
67
+ "homepage": "https://github.com/LittleBlackTong/dsh-plugin-memory#readme",
68
+ "scripts": {
69
+ "test": "node scripts/memory.mjs --self-test",
70
+ "test:plugin": "node --test",
71
+ "lint:memory": "node scripts/memory.mjs lint"
72
+ }
73
+ }
@@ -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
@@ -23,7 +23,7 @@
23
23
 
24
24
  - 只记**跨会话仍然有价值**的内容:关于用户的稳定事实、偏好、决策与理由、项目背景、学到的工具坑与工作流。不记一次性闲聊、不记能从当前对话直接看到的临时状态。
25
25
  - 与用户偏好/语气相关的修正,优先写入 `SOUL.md`(经用户确认)或 `user/preferences.md`。
26
- - 会话结束前做一次 **digest**:把本次会话的关键沉淀写回,否则「长期记忆」只是空话。
26
+ - **digest 是强制义务,不是可选项**:每次会话收尾前,把本会话的关键沉淀写回(页面 + `index.md` + `log.md`),否则「长期记忆」只是空话。当收到插件注入的 digest 提醒(一条 `source.kind === 'plugin'` 的合成消息)时**立即执行**,不得以「等会儿」拖延;若本会话确无值得持久化的内容,在 `log.md` 记一条「## [日期] digest | 无新增」并说明原因——这同样会解除提醒。
27
27
 
28
28
  ## 迁移与导出
29
29