dsh-plugin-memory 0.10.1 → 0.12.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.
@@ -26,6 +26,13 @@ import { randomUUID } from 'node:crypto'
26
26
  import { existsSync, readFileSync } from 'node:fs'
27
27
  import { join } from 'node:path'
28
28
  import { parseLogEntries } from './boot.js'
29
+ import {
30
+ GROWTH_STATE_FILENAME,
31
+ collectGrowth,
32
+ growthRecapDue,
33
+ renderGrowthRecap,
34
+ writeGrowthState,
35
+ } from './growth.js'
29
36
 
30
37
  /** Poll cadence while the agent sits idle (ms). Short enough to feel prompt, long enough to stay cheap. */
31
38
  const POLL_INTERVAL_MS = 30000
@@ -102,9 +109,34 @@ export function buildRecallNudgeMessage(candidates) {
102
109
  }
103
110
  }
104
111
 
112
+ /**
113
+ * Build the growth-recap followup: the weekly "what I kept this week" line,
114
+ * delivered on the same channel as a recall and in the same message shape.
115
+ * @param {string} recap first-person recap text from renderGrowthRecap()
116
+ * @returns {{ id: string, role: 'user', content: [{type:'text', text:string}], source: {kind:'plugin:memory'} }}
117
+ */
118
+ export function buildGrowthRecapNudgeMessage(recap) {
119
+ const text = typeof recap === 'string' ? recap.trim() : ''
120
+ return {
121
+ id: `memory-growth-${randomUUID()}`,
122
+ role: 'user',
123
+ content: [{
124
+ type: 'text',
125
+ text: [
126
+ '【小蓝成长回顾】距离上次回顾有一阵子了。下面是我这周真实记住的事(第一人称,最多五句):',
127
+ text,
128
+ '用自然口语说给阿周听,别念成汇报、别加戏,也不要编造这里没写的事;说完继续手头的事即可。',
129
+ ].filter(Boolean).join('\n'),
130
+ }],
131
+ source: { kind: 'plugin:memory' },
132
+ }
133
+ }
134
+
105
135
  /**
106
136
  * @typedef {object} RecallNudgeOptions
107
- * @property {() => { enabled: boolean, minMinutes: number, maxMinutes: number, maxPerSession: number, deferUntilUserSpeaks?: boolean, activeSessionOnly?: boolean }} readConfig
137
+ * @property {() => { enabled: boolean, minMinutes: number, maxMinutes: number, maxPerSession: number, deferUntilUserSpeaks?: boolean, activeSessionOnly?: boolean, proactiveCooldownSeconds?: number }} readConfig
138
+ * @property {() => { enabled: boolean, intervalDays: number, language?: 'zh'|'en' }} [readGrowthConfig] weekly-recap config; omitted = no recap
139
+ * @property {(options: { now: number, cooldownSeconds: number }) => { ok: boolean, deferredBy?: string }} [claimLock] shared proactive lock (see proactive-lock.js)
108
140
  * @property {() => string} getMemoryDir resolve the current store dir on every check
109
141
  * @property {unknown} [agents] optional live-agent registry for liveness checks
110
142
  * @property {import('./activity-tracker.js').ActivityTracker} [tracker] gate source: has-user-spoken + active-session
@@ -128,6 +160,8 @@ export class RecallNudge {
128
160
  this.agents = options.agents
129
161
  this.tracker = options.tracker
130
162
  this.logger = options.logger
163
+ this.claimLock = options.claimLock
164
+ this.readGrowthConfig = options.readGrowthConfig
131
165
  this.pollIntervalMs = options.pollIntervalMs ?? POLL_INTERVAL_MS
132
166
  this.disposed = false
133
167
  this.stopTurnStopping = undefined
@@ -200,12 +234,99 @@ export class RecallNudge {
200
234
  }
201
235
  if (now < this.nextRecallAt) return
202
236
 
237
+ // Growth recap first: when the week is due it replaces this recall, but it
238
+ // shares the same cadence, per-session cap and arbitration lock.
239
+ const growth = this.planGrowth(now)
240
+ if (growth !== undefined) {
241
+ const claim = this.claimProactive(now, config)
242
+ if (!claim.ok) {
243
+ this.logger?.info?.(`memory: growth recap deferred for agent "${this.agent.id}" (${claim.deferredBy} holds the lock)`)
244
+ return // next trigger retries; the cadence is not consumed
245
+ }
246
+ try {
247
+ writeGrowthState(growth.statePath, now)
248
+ } catch (error) {
249
+ // Losing the timestamp only means the recap may repeat; it must not
250
+ // eat the message the user was about to see.
251
+ this.logger?.warn?.(`memory: growth recap state write failed: ${error instanceof Error ? error.message : String(error)}`)
252
+ }
253
+ this.agent.followup(growth.message)
254
+ this.nextRecallAt = now + randomIntervalMs(config.minMinutes, config.maxMinutes)
255
+ this.recalls += 1
256
+ this.logger?.info?.(`memory: growth recap #${this.recalls} for agent "${this.agent.id}"`)
257
+ return
258
+ }
259
+
203
260
  const candidates = listRecallCandidates(this.getMemoryDir(), 3)
204
261
  if (candidates.length === 0) return
205
262
 
263
+ const claim = this.claimProactive(now, config)
264
+ if (!claim.ok) {
265
+ this.logger?.info?.(`memory: recall deferred for agent "${this.agent.id}" (${claim.deferredBy} holds the lock)`)
266
+ return // next trigger retries; the cadence is not consumed
267
+ }
268
+
206
269
  this.agent.followup(buildRecallNudgeMessage(candidates))
207
270
  this.nextRecallAt = now + randomIntervalMs(config.minMinutes, config.maxMinutes)
208
271
  this.recalls += 1
209
272
  this.logger?.info?.(`memory: recall nudge #${this.recalls} for agent "${this.agent.id}"`)
210
273
  }
274
+
275
+ /**
276
+ * Ask the shared proactive lock for permission to speak. A missing lock
277
+ * (no other proactive plugin installed) or a broken/unwritable lock file
278
+ * never blocks the message: arbitration is best-effort, not a gate.
279
+ * @param {number} now epoch ms
280
+ * @param {{ proactiveCooldownSeconds?: number }} config
281
+ * @returns {{ ok: boolean, deferredBy?: string }}
282
+ */
283
+ claimProactive(now, config) {
284
+ if (typeof this.claimLock !== 'function') return { ok: true }
285
+ try {
286
+ const result = this.claimLock({
287
+ now,
288
+ cooldownSeconds: Math.max(0, Number(config.proactiveCooldownSeconds ?? 180)),
289
+ })
290
+ return result ?? { ok: true }
291
+ } catch (error) {
292
+ this.logger?.warn?.(`memory: proactive lock failed: ${error instanceof Error ? error.message : String(error)}`)
293
+ return { ok: true }
294
+ }
295
+ }
296
+
297
+ /**
298
+ * Plan a weekly growth recap, or undefined when it is not due / has nothing
299
+ * to say. Reads only the store; never throws (a broken recap must fall
300
+ * through to the normal recall path).
301
+ * @param {number} now epoch ms
302
+ * @returns {{ message: object, statePath: string } | undefined}
303
+ */
304
+ planGrowth(now) {
305
+ if (typeof this.readGrowthConfig !== 'function') return undefined
306
+ let growthConfig
307
+ try {
308
+ growthConfig = this.readGrowthConfig()
309
+ } catch (error) {
310
+ this.logger?.warn?.(`memory: growth config unavailable: ${error instanceof Error ? error.message : String(error)}`)
311
+ return undefined
312
+ }
313
+ if (!growthConfig || growthConfig.enabled !== true) return undefined
314
+ try {
315
+ const storeDir = this.getMemoryDir()
316
+ const intervalDays = Math.max(1, Number(growthConfig.intervalDays ?? 7))
317
+ const statePath = join(storeDir, GROWTH_STATE_FILENAME)
318
+ if (!growthRecapDue({ statePath, intervalDays, now })) return undefined
319
+ const growth = collectGrowth({ storeDir, sinceDays: intervalDays, max: 5, now })
320
+ if (growth.entries.length === 0 && growth.pagesChanged === 0) return undefined
321
+ const recap = renderGrowthRecap({
322
+ ...growth,
323
+ language: growthConfig.language === 'en' ? 'en' : 'zh',
324
+ })
325
+ if (recap.length === 0) return undefined
326
+ return { statePath, message: buildGrowthRecapNudgeMessage(recap) }
327
+ } catch (error) {
328
+ this.logger?.warn?.(`memory: growth recap skipped: ${error instanceof Error ? error.message : String(error)}`)
329
+ return undefined
330
+ }
331
+ }
211
332
  }
package/lib/schema.js CHANGED
@@ -23,4 +23,14 @@ export const SettingsSchema = z.object({
23
23
  recallIntervalMinMinutes: z.number().default(30),
24
24
  recallIntervalMaxMinutes: z.number().default(240),
25
25
  recallMaxPerSession: z.number().default(3),
26
+ // 0.12.0: shared proactive-speech arbitration with dsh-plugin-heartbeat.
27
+ // 180s default; 0 turns arbitration off (each plugin speaks freely).
28
+ proactiveCooldownSeconds: z.number().default(180),
29
+ // 0.12.0: tone drift — how to shift register by context. The intensity
30
+ // select is the only knob; `off` ships a pure engineering voice.
31
+ toneGuideEnabled: z.boolean().default(true),
32
+ toneIntensity: z.union([z.const('low'), z.const('medium'), z.const('off')]).default('low'),
33
+ // 0.12.0: weekly growth recap delivered on the recall channel.
34
+ growthRecapEnabled: z.boolean().default(true),
35
+ growthRecapIntervalDays: z.number().default(7),
26
36
  })
@@ -22,12 +22,25 @@ export const NAV_ROW_SELECTOR = '[role="dialog"] nav button'
22
22
  export const NAV_ICON_ATTR = 'data-dsh-memory-nav-icon'
23
23
 
24
24
  /**
25
- * 本区块的 label。
25
+ * 本区块的 label(按 DSH 语言解析)。
26
26
  *
27
- * 它同时是**显示文案**和**认领时的匹配键**——两者必须是同一个字符串,
28
- * 否则语言切换后行与标记会对不上。
27
+ * 中文「记忆」/ 英文 `Memory`。它同时是**显示文案**和**认领时的匹配键**——
28
+ * 两者必须来自同一个解析函数,否则语言切换后行与标记会对不上。
29
29
  */
30
- export const MEMORY_SECTION_LABEL = 'Memory'
30
+ export const MEMORY_SECTION_LABELS = Object.freeze({ zh: '记忆', en: 'Memory' })
31
+
32
+ /**
33
+ * 取本区块在指定语言下的 label。
34
+ *
35
+ * 纯函数:未知 / 缺失语言回退中文(DSH 的默认语言)。设置侧栏标记与测试共用
36
+ * 这一个函数,保证显示文案与认领键永远一致。
37
+ *
38
+ * @param {string | null | undefined} language `ctx.locale.getSnapshot().active`。
39
+ * @returns {string} 该语言下的区块 label。
40
+ */
41
+ export function sectionLabel(language) {
42
+ return MEMORY_SECTION_LABELS[language === 'en' ? 'en' : 'zh']
43
+ }
31
44
 
32
45
  /**
33
46
  * 标记的绘图元素:一个闭合的大脑半球轮廓 + 三条从脑缘引出的线 + 五个节点
package/lib/tone.js ADDED
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Tone drift: the "how to speak" half of the persona, injected into the boot
3
+ * block after the soul.
4
+ *
5
+ * A soul describes who the agent is; nothing in it tells the agent how to
6
+ * *shift register* when the user is in a hurry, when it is 3 a.m., or when it
7
+ * has to deliver bad news. That gap is what made replies read like a status
8
+ * report at the exact moment a companion would be brief and warm. This module
9
+ * turns the intended behaviour into a small, observable rule set — no mantle
10
+ * adjectives, only "in this context, do that".
11
+ *
12
+ * It also carries the emotional-expression layer: the agent may *express*
13
+ * care about a situation it can observe, and must never *fake* an inner
14
+ * feeling it cannot have. Three occasions only: risk/bad news, milestones,
15
+ * and the first line after a long silence.
16
+ *
17
+ * The output is capped at a dozen lines and charged to the boot budget: this
18
+ * text rides on every request, so it has to earn its characters.
19
+ *
20
+ * This module depends only on `node:*` builtins.
21
+ *
22
+ * @module dsh-plugin-memory/tone
23
+ */
24
+
25
+ /** Maximum lines the injected section may occupy (heading included). */
26
+ export const TONE_GUIDE_MAX_LINES = 12
27
+
28
+ /** Supported intensity levels; anything else degrades to `low`. */
29
+ export const TONE_INTENSITIES = ['low', 'medium', 'off']
30
+
31
+ const ZH_HEADING = '## 语气(按语境微调)'
32
+
33
+ const ZH_RULES = [
34
+ '- 赶工/紧急修复:短句、先结论、零玩笑。',
35
+ '- 深夜(23:00–06:00):更简短、更温和。',
36
+ '- 报错/坏消息:先给事实与修复动作,再谈感受。',
37
+ '- 里程碑/完成:可以轻松一句,然后回到正事。',
38
+ '- 闲聊:默认小蓝口吻(外松内紧),先结论后细节。',
39
+ '- 情绪表达(只表达不假装):只描述观察到的处境与关心,不宣称内心情绪;仅限风险/坏消息、里程碑/完成、超过 3 天没联系后的第一次开口(例:「看你连着加班,有点担心你硬扛」)。',
40
+ ]
41
+
42
+ const ZH_INTENSITY = {
43
+ low: '- 强度 low:只做轻微调味;事实准确性永远优先,不越 SOUL 边界。',
44
+ medium: '- 强度 medium:语气可以更明显(该短则短、该暖则暖),但事实优先,不越 SOUL 边界。',
45
+ }
46
+
47
+ const EN_HEADING = '## Tone (adapt to context)'
48
+
49
+ const EN_RULES = [
50
+ '- Crunch/urgent fix: short sentences, conclusion first, zero jokes.',
51
+ '- Deep night (23:00–06:00): shorter and gentler.',
52
+ '- Errors/bad news: give the facts and the fix before any feelings.',
53
+ '- Milestone/finished: one light line, then back to business.',
54
+ '- Small talk: default Small-Blue voice, conclusion before detail.',
55
+ '- Emotion (express, never fake): describe the observed situation and care, never claim an inner feeling; only for risk/bad news, milestones, and the first line after 3+ days without contact (e.g. "you have been working late — I am a bit worried you are pushing yourself").',
56
+ ]
57
+
58
+ const EN_INTENSITY = {
59
+ low: '- Intensity low: light seasoning only; facts always win, never cross the SOUL boundary.',
60
+ medium: '- Intensity medium: let the tone show more clearly (tender when it matters) while keeping facts first and staying inside the SOUL boundary.',
61
+ }
62
+
63
+ /**
64
+ * Render the tone section for injection into the boot block.
65
+ *
66
+ * `language` is the language of the injected prompt material (the memory
67
+ * plugin ships Chinese boot content; `en` is available for English stores).
68
+ * `intensity: 'off'` returns `''` — the boot block then looks exactly as it
69
+ * did before this feature existed.
70
+ *
71
+ * @param {object} [options]
72
+ * @param {'low'|'medium'|'off'} [options.intensity] default 'low'
73
+ * @param {'zh'|'en'} [options.language] default 'zh'
74
+ * @returns {string} complete section (heading + rules), '' when off
75
+ */
76
+ export function buildToneGuide(options = {}) {
77
+ const intensity = TONE_INTENSITIES.includes(options.intensity) ? options.intensity : 'low'
78
+ if (intensity === 'off') return ''
79
+ const language = options.language === 'en' ? 'en' : 'zh'
80
+ const lines = language === 'en'
81
+ ? [EN_HEADING, '', ...EN_RULES, EN_INTENSITY[intensity]]
82
+ : [ZH_HEADING, '', ...ZH_RULES, ZH_INTENSITY[intensity]]
83
+ // The cap is a contract (see TONE_GUIDE_MAX_LINES / test/tone.test.mjs):
84
+ // trim defensively rather than ever letting the section grow unbounded.
85
+ return lines.slice(0, TONE_GUIDE_MAX_LINES).join('\n')
86
+ }
@@ -57,6 +57,20 @@ export interface MemoryConfig {
57
57
  recallIntervalMaxMinutes?: number
58
58
  /** Max recall nudges per session. Default `3`. */
59
59
  recallMaxPerSession?: number
60
+ /**
61
+ * Shared proactive-speech cooldown (seconds) with dsh-plugin-heartbeat,
62
+ * via `<dshHome>/proactive-cooldown.json`. `0` turns arbitration off.
63
+ * Default `180`.
64
+ */
65
+ proactiveCooldownSeconds?: number
66
+ /** Inject the context-sensitive tone section after SOUL. Default `true`. */
67
+ toneGuideEnabled?: boolean
68
+ /** Tone intensity: `low` (default) / `medium` / `off` (pure engineering voice). */
69
+ toneIntensity?: 'low' | 'medium' | 'off'
70
+ /** Deliver a weekly first-person growth recap on the recall channel. Default `true`. */
71
+ growthRecapEnabled?: boolean
72
+ /** Days between growth recaps. Default `7`. */
73
+ growthRecapIntervalDays?: number
60
74
  /** Auto-commit the store's git history after a quiet period. Default `true`. */
61
75
  autoCommit?: boolean
62
76
  /** Seconds of quiet before an auto-commit. Default `60`. */
@@ -86,6 +100,11 @@ export interface MemorySettings {
86
100
  recallIntervalMinMinutes?: number
87
101
  recallIntervalMaxMinutes?: number
88
102
  recallMaxPerSession?: number
103
+ proactiveCooldownSeconds?: number
104
+ toneGuideEnabled?: boolean
105
+ toneIntensity?: 'low' | 'medium' | 'off'
106
+ growthRecapEnabled?: boolean
107
+ growthRecapIntervalDays?: number
89
108
  }
90
109
 
91
110
  /** Schemastery schema for {@link MemorySettings}. */
@@ -229,3 +248,28 @@ export function collectInsights(memoryDir: string): MemoryInsights
229
248
 
230
249
  /** Newest-first `log.md` headlines for the dashboard. */
231
250
  export function readRecentLog(memoryDir: string, count?: number): string[]
251
+
252
+ /** Render the tone section injected after SOUL ('' when intensity is off). */
253
+ export function buildToneGuide(options?: {
254
+ intensity?: 'low' | 'medium' | 'off'
255
+ language?: 'zh' | 'en'
256
+ }): string
257
+
258
+ /** Shared proactive-speech cooldown values. */
259
+ export const TONE_INTENSITIES: ReadonlyArray<'low' | 'medium' | 'off'>
260
+
261
+ /** Claim the shared proactive-speech lock (see lib/proactive-lock.js). */
262
+ export function claimProactiveLock(options?: {
263
+ path?: string
264
+ speaker?: string
265
+ cooldownSeconds?: number
266
+ now?: number
267
+ }): { ok: true; disabled?: true } | { ok: false; deferredBy: string }
268
+
269
+ /** Read the shared proactive-speech lock, or undefined when missing/corrupt. */
270
+ export function readProactiveLock(path: string):
271
+ | { version: number; speaker: string; at: number }
272
+ | undefined
273
+
274
+ /** Default lock path: `${DSH_HOME||~/.dsh}/proactive-cooldown.json`. */
275
+ export function defaultProactiveCooldownPath(): string
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.10.1",
4
+ "version": "0.12.0",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",