dsh-plugin-memory 0.4.0 → 0.5.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
@@ -20,8 +20,9 @@
20
20
  - **可迁移**:记忆本体是纯 markdown + git + 自描述 schema,任何能读 markdown 的 agent 都能接手。`dsh-memory pack/unpack` 打包迁移。
21
21
  - **内嵌技能**:通过 `ctx.skills.register()` 注册 `memory` 技能(操作协议随插件分发);项目级 `.dsh/skills/memory` 文件技能仍可覆盖它。
22
22
  - **防懒 digest 唤醒**:每轮结束后,若 agent 空闲且记忆库超过 `digestNudgeAfterMinutes` 未写入,插件注入一条 digest 提醒(合成消息,走 `agent.followup`),把"会话收尾沉淀"从靠自觉变成有机制兜底;带冷却与每会话限次,不骚扰。**独立于 dsh-plugin-heartbeat**,两插件各自可装、互不依赖。
23
+ - **主动追忆(拟人化)**:对话空下来时,插件会以第一人称主动提起一件**真实记得**的、关于用户或你们之间的事(偏好、往事、未了的决定、最近的进展),把记忆从"只写回"变成"也用起来"——像老友自然想起那样,而非报状态。间隔在最短/最长之间**随机取值**(不固定节奏),配合每会话限次,不骚扰、不编造、不硬聊;纯对话行为,不写记忆库。**同样独立于 heartbeat**。
23
24
  - **git 自动提交**:记忆库变更静默 `autoCommitQuietSeconds` 后自动 `git add -A && git commit`(无 `.git` 则跳过)——历史可回滚不再依赖 agent 记得 commit。
24
- - **设置面板**:在 DSH 设置页提供「记忆 Memory」区块——总开关、记忆目录、开机注入、技能注册四项均可热改,立即生效,无需重启。
25
+ - **设置面板**:在 DSH 设置页提供「记忆 Memory」区块——总开关、记忆目录、开机注入、技能注册、主动追忆(开关 + 随机间隔范围 + 每会话次数)均可热改,立即生效,无需重启。
25
26
  - **零构建**:纯 ESM JavaScript,无编译步骤,`pnpm add` 即用。
26
27
 
27
28
  ## 架构
@@ -32,6 +33,8 @@
32
33
  dsh-plugin-memory(本插件)
33
34
  ├── lib/index.js # Cordis 入口:boot 注入 + 运行时技能注册 + settings 热改
34
35
  ├── lib/boot.js # boot 块渲染(SOUL/MEMORY/index + 最近 log,限额截断)
36
+ ├── lib/digest-guard.js # 防懒 digest 唤醒(空闲 + 记忆库久未写 → followup 提醒)
37
+ ├── lib/recall-nudge.js # 主动追忆(空闲 → 第一人称提起一件真实往事,纯对话不写库)
35
38
  ├── lib/scaffold.js # 记忆库脚手架(模板只建不覆盖)
36
39
  ├── lib/client.js # 客户端半:设置面板「记忆 Memory」区块
37
40
  ├── skills/memory.md # 内嵌技能的操作协议正文
@@ -59,7 +62,7 @@ dsh plugin --profile <profile> add dsh-plugin-memory
59
62
  > ⚠️ **不要**再往 profile 的 `cordis.patch.yml` 里手写 `- insert: {id: dsh-memory, ...}`:
60
63
  > 那会与 bundle manifest 的自动挂载产生两条同名 entry,整个 profile 会以
61
64
  > `duplicate loader entry id "dsh-memory"` 启动失败(2026-08-18 实机事故)。
62
- > 运行期配置(enabled / memoryDir / autoInject / registerSkill)改走
65
+ > 运行期配置(enabled / memoryDir / autoInject / registerSkill / recallEnabled)改走
63
66
  > `<dshHome>/memory.json`(设置面板热改);composition 配置见下表。
64
67
  > 如需覆盖某个 composition 键,用**不带 insert 的 id 覆盖条目**(见配置一节)。
65
68
 
@@ -79,13 +82,17 @@ dsh plugin --profile <profile> add dsh-plugin-memory
79
82
  | `digestNudgeAfterMinutes` | `120` | 记忆库超过多久未写入就提醒 |
80
83
  | `digestNudgeCooldownMinutes` | `180` | 两次提醒的最小间隔 |
81
84
  | `digestNudgeMaxPerSession` | `2` | 每个会话最多提醒次数 |
85
+ | `recallEnabled` | `true` | 主动追忆总开关(面板可热改) |
86
+ | `recallIntervalMinMinutes` | `30` | 随机间隔下限(分钟,面板可热改) |
87
+ | `recallIntervalMaxMinutes` | `240` | 随机间隔上限(分钟,面板可热改) |
88
+ | `recallMaxPerSession` | `3` | 每个会话最多追忆次数(面板可热改) |
82
89
  | `autoCommit` | `true` | 记忆库 git 自动提交开关(composition) |
83
90
  | `autoCommitQuietSeconds` | `60` | 变更静默多久后提交(防抖) |
84
91
  | `autoCommitIntervalSeconds` | `60` | 变更轮询间隔 |
85
92
 
86
93
  ### 设置面板(热改)
87
94
 
88
- `enabled` / `memoryDir` / `autoInject` / `registerSkill` 四项在 DSH 设置页的「记忆 Memory」区块中可改,**即时生效**:boot 注入、技能注册随修改立即重建;记忆目录切换时自动为新目录初始化脚手架(`scaffold: true` 时)。其余键(`bootFiles` / `bootMaxChars` / `scaffold` / `configFile` / `digestNudge*` / `autoCommit*`)只在 composition 配置层生效,改完需重启。
95
+ `enabled` / `memoryDir` / `autoInject` / `registerSkill` / `recallEnabled` / `recallIntervalMinMinutes` / `recallIntervalMaxMinutes` / `recallMaxPerSession` 八项在 DSH 设置页的「记忆 Memory」区块中可改,**即时生效**:boot 注入、技能注册、主动追忆(含随机间隔与次数)随修改立即生效;记忆目录切换时自动为新目录初始化脚手架(`scaffold: true` 时)。其余键(`bootFiles` / `bootMaxChars` / `scaffold` / `configFile` / `digestNudge*` / `autoCommit*`)只在 composition 配置层生效,改完需重启。
89
96
 
90
97
  覆盖 composition 键(例如把 boot 块预算调大),在 profile 的 `cordis.patch.yml` 里写**不带 `insert` 的 id 覆盖条目**:
91
98
 
package/lib/client.js CHANGED
@@ -119,6 +119,31 @@ window.__ModuleLoader__.load({
119
119
  })
120
120
  }
121
121
 
122
+ /** 数字输入:草稿态编辑,blur / Enter 才写回(分钟/次数)。 */
123
+ function NumberInput({ value, disabled, onCommit, placeholder }) {
124
+ const [draft, setDraft] = React.useState(undefined)
125
+ const shown = draft !== undefined ? draft : (value ?? '')
126
+ const commit = () => {
127
+ if (draft === undefined) return
128
+ const parsed = Number(draft)
129
+ if (Number.isFinite(parsed) && parsed !== value) onCommit(parsed)
130
+ setDraft(undefined)
131
+ }
132
+ return React.createElement('input', {
133
+ type: 'number',
134
+ placeholder,
135
+ disabled,
136
+ value: shown,
137
+ onChange: (event) => setDraft(event.target.value),
138
+ onBlur: commit,
139
+ onKeyDown: (event) => {
140
+ if (event.key === 'Enter') commit()
141
+ if (event.key === 'Escape') setDraft(undefined)
142
+ },
143
+ style: { ...inputStyle, width: '120px' },
144
+ })
145
+ }
146
+
122
147
  function MemoryForm() {
123
148
  const [config, setConfig] = React.useState(undefined)
124
149
  const [status, setStatus] = React.useState('loading')
@@ -219,6 +244,50 @@ window.__ModuleLoader__.load({
219
244
  onChange: (next) => apply({ registerSkill: next }),
220
245
  }),
221
246
  ),
247
+ React.createElement('div', { style: rowStyle },
248
+ React.createElement('div', null,
249
+ React.createElement('div', { style: labelStyle }, '主动追忆'),
250
+ React.createElement('div', { style: subStyle }, '对话空闲时,以第一人称主动提起一件关于你的往事(拟人化),可随时关闭'),
251
+ ),
252
+ React.createElement(Toggle, {
253
+ checked: value.recallEnabled !== false,
254
+ disabled,
255
+ onChange: (next) => apply({ recallEnabled: next }),
256
+ }),
257
+ ),
258
+ React.createElement('div', { style: rowStyle },
259
+ React.createElement('div', null,
260
+ React.createElement('div', { style: labelStyle }, '追忆间隔(分钟)'),
261
+ React.createElement('div', { style: subStyle }, '每次随机在最短 ~ 最长之间取一个间隔,避免固定节奏'),
262
+ ),
263
+ React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: '8px' } },
264
+ React.createElement(NumberInput, {
265
+ value: value.recallIntervalMinMinutes,
266
+ disabled,
267
+ placeholder: '30',
268
+ onCommit: (next) => apply({ recallIntervalMinMinutes: next }),
269
+ }),
270
+ React.createElement('span', { style: { color: 'var(--dsw-alias-label-secondary, #999)' } }, '~'),
271
+ React.createElement(NumberInput, {
272
+ value: value.recallIntervalMaxMinutes,
273
+ disabled,
274
+ placeholder: '240',
275
+ onCommit: (next) => apply({ recallIntervalMaxMinutes: next }),
276
+ }),
277
+ ),
278
+ ),
279
+ React.createElement('div', { style: rowStyle },
280
+ React.createElement('div', null,
281
+ React.createElement('div', { style: labelStyle }, '每会话追忆次数'),
282
+ React.createElement('div', { style: subStyle }, '一个会话内最多主动追忆几次,避免打扰'),
283
+ ),
284
+ React.createElement(NumberInput, {
285
+ value: value.recallMaxPerSession,
286
+ disabled,
287
+ placeholder: '3',
288
+ onCommit: (next) => apply({ recallMaxPerSession: next }),
289
+ }),
290
+ ),
222
291
  error !== undefined ? React.createElement('div', { style: errorStyle }, '保存失败:', error) : null,
223
292
  React.createElement('div', { style: { padding: '14px 16px', fontSize: '12px', lineHeight: '18px', color: 'var(--dsw-alias-label-secondary, #888)' } },
224
293
  `当前:${value.enabled === false ? '已停用' : `记忆库位于 ${value.memoryDir ?? '(未配置)'}`}。修改即时生效。`,
@@ -23,7 +23,7 @@ export function defaultConfigPath() {
23
23
  return join(process.env.DSH_HOME || join(homedir(), '.dsh'), MEMORY_CONFIG_FILENAME)
24
24
  }
25
25
 
26
- const FIELDS = ['enabled', 'memoryDir', 'autoInject', 'registerSkill']
26
+ const FIELDS = ['enabled', 'memoryDir', 'autoInject', 'registerSkill', 'recallEnabled', 'recallIntervalMinMinutes', 'recallIntervalMaxMinutes', 'recallMaxPerSession']
27
27
 
28
28
  function pickFields(input) {
29
29
  const picked = {}
@@ -39,12 +39,13 @@ function pickFields(input) {
39
39
  * @property {string} memoryDir
40
40
  * @property {boolean} autoInject
41
41
  * @property {boolean} registerSkill
42
+ * @property {boolean} recallEnabled
42
43
  */
43
44
 
44
45
  /**
45
46
  * @param {object} options
46
47
  * @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
+ * @param {object} [options.base] composition defaults ({enabled, memoryDir, autoInject, registerSkill, recallEnabled})
48
49
  */
49
50
  export class MemoryConfigStore {
50
51
  constructor(options = {}) {
@@ -56,6 +57,10 @@ export class MemoryConfigStore {
56
57
  : '~/.memory',
57
58
  autoInject: options.base?.autoInject !== false,
58
59
  registerSkill: options.base?.registerSkill !== false,
60
+ recallEnabled: options.base?.recallEnabled !== false,
61
+ recallIntervalMinMinutes: options.base?.recallIntervalMinMinutes ?? 30,
62
+ recallIntervalMaxMinutes: options.base?.recallIntervalMaxMinutes ?? 240,
63
+ recallMaxPerSession: options.base?.recallMaxPerSession ?? 3,
59
64
  }
60
65
  this.config = { ...this.base }
61
66
  this.watchers = new Set()
@@ -81,6 +86,10 @@ export class MemoryConfigStore {
81
86
  memoryDir: resolved.memoryDir,
82
87
  autoInject: resolved.autoInject,
83
88
  registerSkill: resolved.registerSkill,
89
+ recallEnabled: resolved.recallEnabled,
90
+ recallIntervalMinMinutes: resolved.recallIntervalMinMinutes,
91
+ recallIntervalMaxMinutes: resolved.recallIntervalMaxMinutes,
92
+ recallMaxPerSession: resolved.recallMaxPerSession,
84
93
  }
85
94
  } catch {
86
95
  // schema validation failed: keep last good config
@@ -114,6 +123,10 @@ export class MemoryConfigStore {
114
123
  memoryDir: next.memoryDir,
115
124
  autoInject: next.autoInject,
116
125
  registerSkill: next.registerSkill,
126
+ recallEnabled: next.recallEnabled,
127
+ recallIntervalMinMinutes: next.recallIntervalMinMinutes,
128
+ recallIntervalMaxMinutes: next.recallIntervalMaxMinutes,
129
+ recallMaxPerSession: next.recallMaxPerSession,
117
130
  }
118
131
  this.persist()
119
132
  for (const watcher of this.watchers) {
package/lib/index.js CHANGED
@@ -77,6 +77,7 @@ import { ensureMemoryScaffold } from './scaffold.js'
77
77
  import { MemoryConfigStore } from './config-store.js'
78
78
  import { SettingsSchema } from './schema.js'
79
79
  import { DigestGuard } from './digest-guard.js'
80
+ import { RecallNudge } from './recall-nudge.js'
80
81
  import { AutoCommitter } from './autocommit.js'
81
82
  import {
82
83
  MEMORY_SKILL_NAME,
@@ -109,6 +110,15 @@ export const Config = z.object({
109
110
  digestNudgeAfterMinutes: z.number().default(120),
110
111
  digestNudgeCooldownMinutes: z.number().default(180),
111
112
  digestNudgeMaxPerSession: z.number().default(2),
113
+ // Recall nudge: when the agent sits idle, invite it to surface a real
114
+ // memory about the user in a first-person voice (the "persona" half —
115
+ // conversational only, never mutates the store). The interval is a random
116
+ // draw inside [minMinutes, maxMinutes] each time, so recalls never feel
117
+ // metronomic.
118
+ recallEnabled: z.boolean().default(true),
119
+ recallIntervalMinMinutes: z.number().default(30),
120
+ recallIntervalMaxMinutes: z.number().default(240),
121
+ recallMaxPerSession: z.number().default(3),
112
122
  // Auto-commit: keep the store's git history current after a quiet period.
113
123
  autoCommit: z.boolean().default(true),
114
124
  autoCommitQuietSeconds: z.number().default(60),
@@ -146,6 +156,10 @@ export function apply(ctx, config = {}) {
146
156
  memoryDir: config.memoryDir ?? '~/.memory',
147
157
  autoInject: config.autoInject !== false,
148
158
  registerSkill: config.registerSkill !== false,
159
+ recallEnabled: config.recallEnabled !== false,
160
+ recallIntervalMinMinutes: config.recallIntervalMinMinutes ?? 30,
161
+ recallIntervalMaxMinutes: config.recallIntervalMaxMinutes ?? 240,
162
+ recallMaxPerSession: config.recallMaxPerSession ?? 3,
149
163
  },
150
164
  })
151
165
 
@@ -278,6 +292,38 @@ export function apply(ctx, config = {}) {
278
292
  }, 'memory.digest-guard()')
279
293
  }
280
294
 
295
+ // Recall nudge: one per live ROOT agent, on the same idle boundary as the
296
+ // digest guard but on a cadence (interval + per-session cap) instead of
297
+ // store staleness. Conversational only — it never writes the store.
298
+ if (config.recallEnabled !== false) {
299
+ ctx.effect(() => {
300
+ const stopCreated = ctx.on('agent/created', ({ agent }) => {
301
+ if (!ctx.agents.roots().includes(agent)) return
302
+ const nudge = new RecallNudge(agent, {
303
+ readConfig: () => {
304
+ const resolved = store.get()
305
+ return {
306
+ enabled: resolved.enabled && resolved.recallEnabled !== false,
307
+ minMinutes: resolved.recallIntervalMinMinutes,
308
+ maxMinutes: resolved.recallIntervalMaxMinutes,
309
+ maxPerSession: resolved.recallMaxPerSession,
310
+ }
311
+ },
312
+ getMemoryDir: () => currentMemoryDir,
313
+ agents: ctx.agents,
314
+ logger: ctx.logger,
315
+ })
316
+ agent.ctx.effect(() => {
317
+ nudge.start()
318
+ return () => {
319
+ nudge.dispose()
320
+ }
321
+ })
322
+ })
323
+ return () => stopCreated()
324
+ }, 'memory.recall-nudge()')
325
+ }
326
+
281
327
  // Settings-panel hot edits: any store change re-applies the config.
282
328
  ctx.effect(() => {
283
329
  const unwatch = store.watch(() => rebuild())
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Recall nudge: the "persona" half of dsh-plugin-memory.
3
+ *
4
+ * DigestGuard makes sure the agent WRITES memory back; this module makes it
5
+ * USE memory like a long-term companion would — when a conversation lulls,
6
+ * it invites the agent to surface one real, remembered fact about the user
7
+ * in a first-person voice ("I remember / last time we…"), instead of a dry
8
+ * status line. The delivery mechanics mirror DigestGuard (watch every ROOT
9
+ * agent's `agent/turn-stopping` boundary, inject a synthetic followup only
10
+ * while the agent is idle and no next-turn step is queued), but the trigger
11
+ * is a *cadence*, not store staleness: at most `maxPerSession` recalls per
12
+ * session, spaced by at least `intervalMinutes`.
13
+ *
14
+ * The nudge never invents material — it only hands the agent a few real
15
+ * `log.md` headlines as a seed and tells it to pick one it actually
16
+ * remembers. No store write happens here, so the recall is conversational
17
+ * only and never mutates the memory library.
18
+ *
19
+ * Independent of dsh-plugin-heartbeat: lives inside dsh-plugin-memory,
20
+ * depends on no other plugin, and queues behind the same per-agent inbox.
21
+ *
22
+ * @module dsh-plugin-memory/recall-nudge
23
+ */
24
+
25
+ import { randomUUID } from 'node:crypto'
26
+ import { existsSync, readFileSync } from 'node:fs'
27
+ import { join } from 'node:path'
28
+ import { parseLogEntries } from './boot.js'
29
+
30
+ /** Poll cadence while the agent sits idle (ms). Short enough to feel prompt, long enough to stay cheap. */
31
+ const POLL_INTERVAL_MS = 30000
32
+
33
+ /**
34
+ * Draw a random interval in [minMinutes, maxMinutes] minutes (ms).
35
+ * The spread makes recalls feel human rather than metronomic.
36
+ * @param {number} minMinutes lower bound in minutes
37
+ * @param {number} maxMinutes upper bound in minutes
38
+ * @returns {number} milliseconds
39
+ */
40
+ export function randomIntervalMs(minMinutes, maxMinutes) {
41
+ const min = Math.max(0, Number(minMinutes ?? 30))
42
+ const max = Math.max(min, Number(maxMinutes ?? min))
43
+ return (min + Math.random() * (max - min)) * 60000
44
+ }
45
+
46
+ /**
47
+ * Seed candidates for a recall: the most recent log.md headlines, which are
48
+ * the closest thing to "what we've been through lately". Empty when the
49
+ * store has no log yet — in that case there is nothing to recall and the
50
+ * nudge stays quiet.
51
+ * @param {string} memoryDir absolute path of the memory store
52
+ * @param {number} count max candidates to surface (default 3)
53
+ * @returns {string[]}
54
+ */
55
+ export function listRecallCandidates(memoryDir, count = 3) {
56
+ const logPath = join(memoryDir, 'log.md')
57
+ if (!existsSync(logPath)) return []
58
+ try {
59
+ const text = readFileSync(logPath, 'utf8')
60
+ return parseLogEntries(text, count)
61
+ } catch {
62
+ return []
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Build the recall message in the same followup shape DigestGuard uses
68
+ * (role 'user', content array, plugin source). The text is an invitation,
69
+ * not a command: first-person, Small-Blue voice, explicitly bounded by
70
+ * "only what's really in memory, never invent, don't repeat yourself".
71
+ * @param {string[]} candidates optional seed headlines
72
+ * @returns {{ id: string, role: 'user', content: [{type:'text', text:string}], source: {kind:'plugin', plugin:string} }}
73
+ */
74
+ export function buildRecallNudgeMessage(candidates) {
75
+ const list = Array.isArray(candidates)
76
+ ? candidates.filter((c) => typeof c === 'string' && c.trim().length > 0)
77
+ : []
78
+ const seed = list.length > 0
79
+ ? `\n可作引子(挑一件自然提起即可,不必全用):\n${list.map((c) => `- ${c}`).join('\n')}`
80
+ : ''
81
+ return {
82
+ id: `memory-recall-${randomUUID()}`,
83
+ role: 'user',
84
+ content: [{
85
+ type: 'text',
86
+ text: [
87
+ '【小蓝主动追忆】对话空了下来,是自然提起往事的好时机。请以「小蓝」的口吻(外松内紧、先结论后细节),主动对阿周提起一件你记得的、关于他或你们之间的事——偏好、往事、未了的决定、最近的进展都行,像老友自然想起来那样,别端着。',
88
+ '- 只提记忆里真实存在的,绝不编造;',
89
+ '- 用第一人称(我记得 / 上次我们…),别用「据记忆库记录」这种机器腔;',
90
+ '- 换着说,别重复最近提过的;一句到三句即可,别写成任务汇报;',
91
+ '- 若话题正不合适,就只回一句日常状态带过,不硬聊。',
92
+ seed,
93
+ ].filter(Boolean).join('\n'),
94
+ }],
95
+ source: { kind: 'plugin', plugin: 'memory' },
96
+ }
97
+ }
98
+
99
+ /**
100
+ * @typedef {object} RecallNudgeOptions
101
+ * @property {() => { enabled: boolean, minMinutes: number, maxMinutes: number, maxPerSession: number }} readConfig
102
+ * @property {() => string} getMemoryDir resolve the current store dir on every check
103
+ * @property {unknown} [agents] optional live-agent registry for liveness checks
104
+ * @property {{ info?: Function, warn?: Function }} [logger]
105
+ */
106
+
107
+ /**
108
+ * One recall-nudge per live ROOT agent, lifecycle-hooked to the agent's
109
+ * context — same pattern as DigestGuard so the two never share state but
110
+ * both fire only on a real idle boundary.
111
+ */
112
+ export class RecallNudge {
113
+ /**
114
+ * @param {object} agent live root agent (ReactLoopAgent shape: ctx, status, inbox, followup)
115
+ * @param {RecallNudgeOptions} options
116
+ */
117
+ constructor(agent, options) {
118
+ this.agent = agent
119
+ this.readConfig = options.readConfig
120
+ this.getMemoryDir = options.getMemoryDir
121
+ this.agents = options.agents
122
+ this.logger = options.logger
123
+ this.pollIntervalMs = options.pollIntervalMs ?? POLL_INTERVAL_MS
124
+ this.disposed = false
125
+ this.stopTurnStopping = undefined
126
+ this.timer = undefined
127
+ this.recalls = 0
128
+ this.nextRecallAt = 0
129
+ }
130
+
131
+ /** Subscribe to the turn boundary AND poll while the agent sits idle. */
132
+ start() {
133
+ if (this.disposed) return
134
+ this.stopTurnStopping = this.agent.ctx.on?.('agent/turn-stopping', () => {
135
+ this.safeCheck()
136
+ })
137
+ // A turn boundary only fires when a turn ends; a fully idle agent never
138
+ // produces one, so we also poll on a short interval. This is what makes
139
+ // recall proactive (heartbeat-style) rather than turn-reactive.
140
+ this.timer = setInterval(() => {
141
+ this.safeCheck()
142
+ }, this.pollIntervalMs)
143
+ if (typeof this.timer.unref === 'function') this.timer.unref()
144
+ }
145
+
146
+ /** Shared guard wrapper so both triggers stay exception-safe. */
147
+ safeCheck() {
148
+ if (this.disposed) return
149
+ try {
150
+ this.onTurnStopped()
151
+ } catch (error) {
152
+ this.logger?.warn?.(`memory: recall check failed for agent "${this.agent.id}": ${error instanceof Error ? error.message : String(error)}`)
153
+ }
154
+ }
155
+
156
+ /** Cancel subscriptions and the poll timer; the nudge stops observing. */
157
+ dispose() {
158
+ this.disposed = true
159
+ this.stopTurnStopping?.()
160
+ this.stopTurnStopping = undefined
161
+ if (this.timer !== undefined) {
162
+ clearInterval(this.timer)
163
+ this.timer = undefined
164
+ }
165
+ }
166
+
167
+ /** Evaluate whether a recall is due right now. */
168
+ onTurnStopped() {
169
+ if (this.disposed) return
170
+ if (this.agents && this.agents.get(this.agent.id) !== this.agent) {
171
+ this.dispose()
172
+ return
173
+ }
174
+ const config = this.readConfig()
175
+ if (!config.enabled) return
176
+ if (this.recalls >= Math.max(1, Number(config.maxPerSession ?? 3))) return
177
+ if (this.agent.status !== 'idle') return
178
+ const inbox = this.agent.inbox
179
+ if (inbox && Array.isArray(inbox.nextStep) && inbox.nextStep.length > 0) return
180
+
181
+ const now = Date.now()
182
+ if (now < this.nextRecallAt) return
183
+
184
+ const candidates = listRecallCandidates(this.getMemoryDir(), 3)
185
+ if (candidates.length === 0) return
186
+
187
+ this.agent.followup(buildRecallNudgeMessage(candidates))
188
+ this.nextRecallAt = now + randomIntervalMs(config.minMinutes, config.maxMinutes)
189
+ this.recalls += 1
190
+ this.logger?.info?.(`memory: recall nudge #${this.recalls} for agent "${this.agent.id}"`)
191
+ }
192
+ }
package/lib/schema.js CHANGED
@@ -15,4 +15,8 @@ export const SettingsSchema = z.object({
15
15
  memoryDir: z.string().default('~/.memory'),
16
16
  autoInject: z.boolean().default(true),
17
17
  registerSkill: z.boolean().default(true),
18
+ recallEnabled: z.boolean().default(true),
19
+ recallIntervalMinMinutes: z.number().default(30),
20
+ recallIntervalMaxMinutes: z.number().default(240),
21
+ recallMaxPerSession: z.number().default(3),
18
22
  })
@@ -30,6 +30,28 @@ export interface MemoryConfig {
30
30
  scaffold?: boolean
31
31
  /** Absolute user-facing config-file path. Default `<dshHome>/memory.json`. */
32
32
  configFile?: string
33
+ /** Digest guard: inject a reminder when the store goes unwritten too long. Default `true`. */
34
+ digestNudgeEnabled?: boolean
35
+ /** Minutes of store inactivity before a digest reminder. Default `120`. */
36
+ digestNudgeAfterMinutes?: number
37
+ /** Minimum minutes between digest reminders. Default `180`. */
38
+ digestNudgeCooldownMinutes?: number
39
+ /** Max digest reminders per session. Default `2`. */
40
+ digestNudgeMaxPerSession?: number
41
+ /** Recall nudge: idle-time first-person recall of a real memory. Default `true`. */
42
+ recallEnabled?: boolean
43
+ /** Lower bound (minutes) of the random recall interval. Default `30`. */
44
+ recallIntervalMinMinutes?: number
45
+ /** Upper bound (minutes) of the random recall interval. Default `240`. */
46
+ recallIntervalMaxMinutes?: number
47
+ /** Max recall nudges per session. Default `3`. */
48
+ recallMaxPerSession?: number
49
+ /** Auto-commit the store's git history after a quiet period. Default `true`. */
50
+ autoCommit?: boolean
51
+ /** Seconds of quiet before an auto-commit. Default `60`. */
52
+ autoCommitQuietSeconds?: number
53
+ /** Poll interval (seconds) for the auto-committer. Default `60`. */
54
+ autoCommitIntervalSeconds?: number
33
55
  }
34
56
 
35
57
  /** Schemastery schema for {@link MemoryConfig}. */
@@ -44,6 +66,10 @@ export interface MemorySettings {
44
66
  memoryDir?: string
45
67
  autoInject?: boolean
46
68
  registerSkill?: boolean
69
+ recallEnabled?: boolean
70
+ recallIntervalMinMinutes?: number
71
+ recallIntervalMaxMinutes?: number
72
+ recallMaxPerSession?: number
47
73
  }
48
74
 
49
75
  /** Schemastery schema for {@link MemorySettings}. */
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.0",
4
+ "version": "0.5.0",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",