dsh-plugin-memory 0.11.0 → 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.
- package/CHANGELOG.md +14 -0
- package/README.md +15 -1
- package/README.zh.md +15 -1
- package/lib/boot.js +22 -3
- package/lib/client.js +67 -0
- package/lib/config-store.js +19 -1
- package/lib/digest-guard.js +35 -1
- package/lib/growth.js +201 -0
- package/lib/index.js +54 -2
- package/lib/proactive-lock.js +122 -0
- package/lib/recall-nudge.js +122 -1
- package/lib/schema.js +10 -0
- package/lib/tone.js +86 -0
- package/lib/types/index.d.ts +44 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,20 @@
|
|
|
2
2
|
|
|
3
3
|
所有记录跟随 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/) 风格;版本号与 `package.json` 保持一致。
|
|
4
4
|
|
|
5
|
+
## [0.12.0] - 2026-10-30
|
|
6
|
+
|
|
7
|
+
### Added(A 仲裁 + B 语气漂移 + C 表达层 + D 每周成长回顾)
|
|
8
|
+
|
|
9
|
+
- **A 发言权仲裁(与 heartbeat 插件共享协议)**:新增 `lib/proactive-lock.js`。所有主动消息(recall / digest / growth 三个通道)投递前先 claim 共享文件 `${DSH_HOME:-~/.dsh}/proactive-cooldown.json`(`{ version: 1, speaker: 'memory' | 'heartbeat', at: <epoch ms> }`,tmp+rename 原子写):若窗口内已有其他 speaker 的 claim,本条让位(日志 `... deferred for agent ... (... holds the lock)`)并**不消耗节奏**——下次触发自动重试;`proactiveCooldownSeconds`(默认 **180**,`0` = 关闭)。双方零 import,各自独立实现同一协议,任一方可单独装/卸。
|
|
10
|
+
- **B 语气漂移(`lib/tone.js`)**:boot 块在 SOUL 之后注入一小段 `## 语气(按语境微调)`(英文 `## Tone (adapt to context)`),共 ≤12 行:赶工/紧急修复短句先结论、深夜(23:00–06:00)更短更温和、报错/坏消息先给事实与修复动作、里程碑/完成可轻松一句、闲聊回默认小蓝口吻。`toneGuideEnabled`(默认 `true`)、`toneIntensity`(`low` / `medium` / `off`,默认 `low`);该段**计入 boot 预算**(先扣掉 tone 段的字符成本,再给文件分预算),不白嫖上下文。
|
|
11
|
+
- **C 表达层(只表达不假装)**:同一段语气规则内置表达边界——只描述**观察到的处境与关心**,不宣称内心情绪(禁「我很… / 我感到…」);仅允许三类场合:风险/坏消息、里程碑/完成、超过 3 天没联系后的第一次开口。原文例:「看你连着加班,有点担心你硬扛」。
|
|
12
|
+
- **D 每周成长回顾(`lib/growth.js`)**:`growthRecapEnabled`(默认 `true`)、`growthRecapIntervalDays`(默认 `7`);走 **recall 通道**(同一节律、同一每会话上限、同一仲裁锁),首人称「这周我记住了什么」;`<store>/.growth-recap.json` 记录上次投递,重启不会重复同一周的回顾;内容只从 `log.md` 标题与页面 mtime 派生——**不新增记账、不编造成长**。
|
|
13
|
+
|
|
14
|
+
### Tests
|
|
15
|
+
|
|
16
|
+
- 新增 `test/tone.test.mjs`、`test/growth.test.mjs`、`test/proactive-lock.test.mjs`;`recall-nudge` / `digest-guard` / `plugin-metadata` 等补仲裁、语气、回顾用例。
|
|
17
|
+
- 全量单测 **242/242 通过**(0.11.0 基线 198,新增 44 条);`node scripts/memory.mjs --self-test` PASS。
|
|
18
|
+
|
|
5
19
|
## [0.11.0] - 2026-10-30
|
|
6
20
|
|
|
7
21
|
### Added(设置面板与侧栏 label 跟随语言:中英双语)
|
package/README.md
CHANGED
|
@@ -51,6 +51,15 @@ After that the loop is simple: the agent writes memories back as you work, and y
|
|
|
51
51
|
- **Memory health dashboard**: below the same section is a **read-only** dashboard — memory pages / index routes / word count, an access-freshness bar chart (today / ≤7 / ≤30 / ≤90 / >90 days), four health verdicts (index links, orphan pages, frontmatter, freshness) with a health score, stale-page candidates, and the 5 most recent log entries. Data comes from the new `GET /api/memory/insights` (computed live per request, never cached), and its criteria share a source with `dsh-memory lint`, so the dashboard and the CLI cannot contradict each other.
|
|
52
52
|
- **Zero build**: plain ESM JavaScript, no compilation step, usable straight after `pnpm add`.
|
|
53
53
|
|
|
54
|
+
## Persona, politeness and growth (v0.12.0)
|
|
55
|
+
|
|
56
|
+
Four small additions turn the memory from "storage with a soul" into a companion that behaves:
|
|
57
|
+
|
|
58
|
+
- **Speech-right arbitration with other proactive plugins (A)**: before sending anything proactive — a recall, a digest reminder or a growth recap — the plugin claims the shared `${DSH_HOME:-~/.dsh}/proactive-cooldown.json` (`{ version: 1, speaker: 'memory' | 'heartbeat', at: <epoch ms> }`, atomic tmp+rename). If another speaker claimed inside `proactiveCooldownSeconds` (default **180**, `0` disables), the message is deferred and **the cadence is not consumed** — the next trigger retries. Neither plugin imports the other; both implement the same protocol independently, so either can be installed, upgraded or removed alone.
|
|
59
|
+
- **Tone drift (B)**: `lib/tone.js` injects a small `## Tone (adapt to context)` section right after SOUL (≤12 lines, **charged to the boot budget** — its character cost is deducted before the per-file allocation): crunch/urgent fix → short sentences, conclusion first, zero jokes; deep night (23:00–06:00) → shorter and gentler; errors/bad news → facts and the fix before any feelings; milestone/finished → one light line, then back to business. `toneGuideEnabled` (default `true`) switches it, `toneIntensity` (`low` / `medium` / `off`, default `low`) sets how visible it is.
|
|
60
|
+
- **Expression, never fake emotion (C)**: the same section draws the line — describe the **observed situation and care**, never claim inner feelings ("I am … / I feel …"); only three occasions are allowed: risk/bad news, milestones/completion, and the first line after 3+ days without contact.
|
|
61
|
+
- **Weekly growth recap (D)**: `growthRecapEnabled` (default `true`) and `growthRecapIntervalDays` (default `7`). It rides the **recall channel** (same cadence, same per-session cap, same arbitration lock) and reads only what the store already proves — recent `log.md` headlines and page mtimes — so there is no invented progress. `<store>/.growth-recap.json` remembers the last delivery, so a restart does not repeat the same week.
|
|
62
|
+
|
|
54
63
|
## Architecture
|
|
55
64
|
|
|
56
65
|
The plugin owns the **workflow**, never the **data format**:
|
|
@@ -121,6 +130,11 @@ Restart the profile (restart the DSH Desktop app) to take effect.
|
|
|
121
130
|
| `recallIntervalMinMinutes` | `30` | Lower bound of the random interval (minutes, hot-editable) |
|
|
122
131
|
| `recallIntervalMaxMinutes` | `240` | Upper bound of the random interval (minutes, hot-editable) |
|
|
123
132
|
| `recallMaxPerSession` | `3` | Maximum recalls per session (hot-editable) |
|
|
133
|
+
| `proactiveCooldownSeconds` | `180` | Shared speech-floor cooldown against other proactive plugins (`0` = off) |
|
|
134
|
+
| `toneGuideEnabled` | `true` | Inject the context-sensitive tone section after SOUL |
|
|
135
|
+
| `toneIntensity` | `low` | `low` / `medium` / `off` (pure engineering voice) |
|
|
136
|
+
| `growthRecapEnabled` | `true` | Weekly growth recap on the recall channel |
|
|
137
|
+
| `growthRecapIntervalDays` | `7` | Days between growth recaps |
|
|
124
138
|
| `autoCommit` | `true` | Git auto-commit switch for the store (composition) |
|
|
125
139
|
| `autoCommitQuietSeconds` | `60` | How long changes must be quiet before committing (debounce) |
|
|
126
140
|
| `autoCommitIntervalSeconds` | `60` | Change polling interval |
|
|
@@ -129,7 +143,7 @@ Restart the profile (restart the DSH Desktop app) to take effect.
|
|
|
129
143
|
|
|
130
144
|
The section is registered as **"Memory"** in the English UI and **「记忆」** in the Chinese UI — it follows DSH's own language setting (see [Language](#language) below).
|
|
131
145
|
|
|
132
|
-
|
|
146
|
+
Fifteen settings are editable in the "Memory" section of the DSH settings page and take effect **immediately**: `enabled` / `memoryDir` / `autoInject` / `deferUntilUserSpeaks` / `activeSessionOnly` / `registerSkill` / `recallEnabled` / `recallIntervalMinMinutes` / `recallIntervalMaxMinutes` / `recallMaxPerSession` / `proactiveCooldownSeconds` / `toneGuideEnabled` / `toneIntensity` / `growthRecapEnabled` / `growthRecapIntervalDays` — boot injection, the two polite gates, skill registration, proactive recall (including its random interval and cap), speech-right arbitration, the tone section and the weekly growth recap all follow the change at once; switching the store directory scaffolds the new one automatically (when `scaffold: true`). The remaining keys (`bootFiles` / `bootMaxChars` / `bootFileBudgets` / `trackPageAccess` / `scaffold` / `configFile` / `digestNudge*` / `autoCommit*`) only apply at the composition layer and need a restart.
|
|
133
147
|
|
|
134
148
|
### Language
|
|
135
149
|
|
package/README.zh.md
CHANGED
|
@@ -51,6 +51,15 @@ dsh plugin --profile <profile> add dsh-plugin-memory
|
|
|
51
51
|
- **记忆健康看板**:同一区块下方是一张**只读**看板——记忆页数 / index 路由数 / 记忆字数、访问新鲜度条形图(今天 / ≤7 / ≤30 / ≤90 / >90 天)、四项体检结论(index 链接、孤儿页、frontmatter、新鲜度)与健康分、陈旧页候选、最近 5 条动态。数据来自新增的 `GET /api/memory/insights`(每次请求实时统计,不缓存),体检口径与 `dsh-memory lint` 同源,所以看板与 CLI 不会互相打脸。
|
|
52
52
|
- **零构建**:纯 ESM JavaScript,无编译步骤,`pnpm add` 即用。
|
|
53
53
|
|
|
54
|
+
## 人格层、礼貌与成长(v0.12.0)
|
|
55
|
+
|
|
56
|
+
四个小增量,把「带灵魂的存储」变成「会处事的伙伴」:
|
|
57
|
+
|
|
58
|
+
- **A 与其他主动插件的发言权仲裁**:任何主动消息——追忆、digest 提醒、成长回顾——发出前先 claim 共享文件 `${DSH_HOME:-~/.dsh}/proactive-cooldown.json`(`{ version: 1, speaker: 'memory' | 'heartbeat', at: <epoch ms> }`,tmp+rename 原子写)。若 `proactiveCooldownSeconds`(默认 **180**,`0` = 关闭)内有其他 speaker 先 claim,本条让位且**不消耗节奏**——下次触发自动重试。两个插件零 import、各自独立实现同一协议,任一方可单独装 / 升 / 卸。
|
|
59
|
+
- **B 语气漂移**:`lib/tone.js` 在 SOUL 之后注入一小段 `## 语气(按语境微调)`(≤12 行,**计入 boot 预算**——先扣掉该段字符成本再按文件分配):赶工/紧急修复 → 短句、先结论、零玩笑;深夜(23:00–06:00)→ 更短更温和;报错/坏消息 → 先给事实与修复动作再谈感受;里程碑/完成 → 轻松一句然后回正事。`toneGuideEnabled`(默认 `true`)开关,`toneIntensity`(`low` / `medium` / `off`,默认 `low`)控制明显程度。
|
|
60
|
+
- **C 表达层(只表达不假装)**:同一段语气规则画出边界——只描述**观察到的处境与关心**,不宣称内心情绪(禁「我很… / 我感到…」);仅允许三类场合:风险/坏消息、里程碑/完成、超过 3 天没联系后的第一次开口。
|
|
61
|
+
- **D 每周成长回顾**:`growthRecapEnabled`(默认 `true`)、`growthRecapIntervalDays`(默认 `7`)。走 **recall 通道**(同一节律、同一每会话上限、同一仲裁锁),内容只从记忆库已经证明的东西派生——最近的 `log.md` 标题与页面 mtime——不编造成长。`<store>/.growth-recap.json` 记录上次投递,重启不会重复同一周的回顾。
|
|
62
|
+
|
|
54
63
|
## 架构
|
|
55
64
|
|
|
56
65
|
插件只拥有**工作流**,不拥有**数据格式**:
|
|
@@ -129,13 +138,18 @@ dsh plugin --profile <profile> add dsh-plugin-memory
|
|
|
129
138
|
| `recallIntervalMinMinutes` | `30` | 随机间隔下限(分钟,面板可热改) |
|
|
130
139
|
| `recallIntervalMaxMinutes` | `240` | 随机间隔上限(分钟,面板可热改) |
|
|
131
140
|
| `recallMaxPerSession` | `3` | 每个会话最多追忆次数(面板可热改) |
|
|
141
|
+
| `proactiveCooldownSeconds` | `180` | 与其他主动插件的共享发言冷却(`0` = 关闭) |
|
|
142
|
+
| `toneGuideEnabled` | `true` | 在 SOUL 之后注入按语境微调的语气段 |
|
|
143
|
+
| `toneIntensity` | `low` | `low` / `medium` / `off`(off = 纯工程师语气) |
|
|
144
|
+
| `growthRecapEnabled` | `true` | 每周成长回顾(走 recall 通道) |
|
|
145
|
+
| `growthRecapIntervalDays` | `7` | 两次成长回顾间隔天数 |
|
|
132
146
|
| `autoCommit` | `true` | 记忆库 git 自动提交开关(composition) |
|
|
133
147
|
| `autoCommitQuietSeconds` | `60` | 变更静默多久后提交(防抖) |
|
|
134
148
|
| `autoCommitIntervalSeconds` | `60` | 变更轮询间隔 |
|
|
135
149
|
|
|
136
150
|
### 设置面板(热改)
|
|
137
151
|
|
|
138
|
-
`enabled` / `memoryDir` / `autoInject` / `deferUntilUserSpeaks` / `activeSessionOnly` / `registerSkill` / `recallEnabled` / `recallIntervalMinMinutes` / `recallIntervalMaxMinutes` / `recallMaxPerSession`
|
|
152
|
+
`enabled` / `memoryDir` / `autoInject` / `deferUntilUserSpeaks` / `activeSessionOnly` / `registerSkill` / `recallEnabled` / `recallIntervalMinMinutes` / `recallIntervalMaxMinutes` / `recallMaxPerSession` / `proactiveCooldownSeconds` / `toneGuideEnabled` / `toneIntensity` / `growthRecapEnabled` / `growthRecapIntervalDays` 十五项在 DSH 设置页的「记忆 / Memory」区块中可改(跟随语言),**即时生效**:boot 注入、两道礼貌闸门、技能注册、主动追忆(含随机间隔与次数)、发言权仲裁、语气段与每周成长回顾随修改立即生效;记忆目录切换时自动为新目录初始化脚手架(`scaffold: true` 时)。其余键(`bootFiles` / `bootMaxChars` / `bootFileBudgets` / `trackPageAccess` / `scaffold` / `configFile` / `digestNudge*` / `autoCommit*`)只在 composition 配置层生效,改完需重启。
|
|
139
153
|
|
|
140
154
|
### 语言 / Language
|
|
141
155
|
|
package/lib/boot.js
CHANGED
|
@@ -22,6 +22,9 @@ export const DEFAULT_BOOT_FILES = ['SOUL.md', 'MEMORY.md', 'index.md']
|
|
|
22
22
|
* signal, and this block is injected on every request. */
|
|
23
23
|
export const RECENT_LOG_COUNT = 3
|
|
24
24
|
|
|
25
|
+
/** Separator joining the boot-block sections. */
|
|
26
|
+
const SECTION_SEPARATOR = '\n\n---\n\n'
|
|
27
|
+
|
|
25
28
|
/** Read a file and cap it at `maxChars`, noting truncation when applied. */
|
|
26
29
|
export function readCapped(path, maxChars) {
|
|
27
30
|
if (!existsSync(path)) return undefined
|
|
@@ -224,7 +227,7 @@ export function needsSoulBootstrap(memoryDir) {
|
|
|
224
227
|
* onboarding the user gets with a fresh OpenClaw instance.
|
|
225
228
|
*
|
|
226
229
|
* @param {string} memoryDir absolute path of the memory store
|
|
227
|
-
* @param {{ bootFiles?: string[], bootMaxChars?: number, bootFileBudgets?: Record<string, number
|
|
230
|
+
* @param {{ bootFiles?: string[], bootMaxChars?: number, bootFileBudgets?: Record<string, number>, toneGuide?: string }} options
|
|
228
231
|
* @returns {string} the model-facing boot block; '' when the store is empty
|
|
229
232
|
*/
|
|
230
233
|
export function renderBootBlock(memoryDir, options = {}) {
|
|
@@ -232,20 +235,36 @@ export function renderBootBlock(memoryDir, options = {}) {
|
|
|
232
235
|
? options.bootFiles
|
|
233
236
|
: DEFAULT_BOOT_FILES
|
|
234
237
|
const total = Math.max(512, options.bootMaxChars ?? 6000)
|
|
238
|
+
// The tone section rides along on every request, so it is charged to the
|
|
239
|
+
// same budget as the store files: without this the persona paragraph would
|
|
240
|
+
// silently push the end of `index.md` out of the block.
|
|
241
|
+
const toneSection = typeof options.toneGuide === 'string' && options.toneGuide.trim().length > 0
|
|
242
|
+
? options.toneGuide.trim()
|
|
243
|
+
: ''
|
|
244
|
+
const toneCost = toneSection.length > 0 ? toneSection.length + SECTION_SEPARATOR.length : 0
|
|
245
|
+
const fileBudget = Math.max(512, total - toneCost)
|
|
235
246
|
const caps = allocateBootBudget(memoryDir, {
|
|
236
247
|
files: bootFiles,
|
|
237
|
-
total,
|
|
248
|
+
total: fileBudget,
|
|
238
249
|
perFile: options.bootFileBudgets,
|
|
239
250
|
})
|
|
240
251
|
|
|
241
252
|
const sections = []
|
|
253
|
+
let toneInjected = false
|
|
242
254
|
for (const fileName of bootFiles) {
|
|
243
255
|
const path = join(memoryDir, fileName)
|
|
244
256
|
const cap = caps.get(fileName) ?? 0
|
|
245
257
|
const text = cap > 0 ? readCapped(path, cap) : undefined
|
|
246
258
|
if (text === undefined || text.trim() === '') continue
|
|
247
259
|
sections.push(`### ${fileName}\n\n${text}`)
|
|
260
|
+
// Personality first, then how to speak: the tone section goes right after
|
|
261
|
+
// the soul file so the rules are read as an extension of the persona.
|
|
262
|
+
if (fileName === 'SOUL.md' && toneSection.length > 0) {
|
|
263
|
+
sections.push(toneSection)
|
|
264
|
+
toneInjected = true
|
|
265
|
+
}
|
|
248
266
|
}
|
|
267
|
+
if (toneSection.length > 0 && !toneInjected) sections.push(toneSection)
|
|
249
268
|
|
|
250
269
|
if (sections.length === 0) return ''
|
|
251
270
|
|
|
@@ -258,7 +277,7 @@ export function renderBootBlock(memoryDir, options = {}) {
|
|
|
258
277
|
sections.push(`### 最近动态(log.md 末尾 ${logEntries.length} 条)\n\n${logEntries.map((e) => `- ${e}`).join('\n')}`)
|
|
259
278
|
}
|
|
260
279
|
|
|
261
|
-
const body = sections.join(
|
|
280
|
+
const body = sections.join(SECTION_SEPARATOR)
|
|
262
281
|
const header = `长期记忆(dsh-plugin-memory)。记忆库位于 ${memoryDir}。这是你跨会话的持久人格与记忆:以它为准,先读完再回复用户。若与当前对话冲突,优先相信用户的最新表述,并把差异写回记忆。**每次会话收尾前必须执行 memory digest:把本会话关键沉淀写回(更新页面 + index.md + 追加 log.md)。插件会注入 digest 提醒消息,收到后立即写回,不得拖延;若本会话确无值得持久化的内容,在 log.md 记一条「无新增」并说明原因。**`
|
|
263
282
|
|
|
264
283
|
let result
|
package/lib/client.js
CHANGED
|
@@ -60,6 +60,15 @@ window.__ModuleLoader__.load({
|
|
|
60
60
|
recallIntervalHint: '每次随机在最短 ~ 最长之间取一个间隔,避免固定节奏',
|
|
61
61
|
recallMaxPerSession: '每会话追忆次数',
|
|
62
62
|
recallMaxPerSessionHint: '一个会话内最多主动追忆几次,避免打扰',
|
|
63
|
+
toneGuide: '语气引导',
|
|
64
|
+
toneGuideHint: '按语境微调说话方式(赶工、深夜、坏消息、里程碑),不改变事实、不越 SOUL 边界',
|
|
65
|
+
toneIntensity: '语气强度',
|
|
66
|
+
toneIntensityHint: 'low 仅调味 / medium 更明显 / off 纯工程口吻;任何档位都以事实优先',
|
|
67
|
+
toneLow: 'low(仅调味)',
|
|
68
|
+
toneMedium: 'medium(更明显)',
|
|
69
|
+
toneOff: 'off(纯工程口吻)',
|
|
70
|
+
growthRecap: '每周成长回顾',
|
|
71
|
+
growthRecapHint: '每周在追忆通道里说一次「这周我记住了什么」(第一人称,最多五句,可随时关闭)',
|
|
63
72
|
minutesPlaceholder: '30',
|
|
64
73
|
maxMinutesPlaceholder: '240',
|
|
65
74
|
maxPerSessionPlaceholder: '3',
|
|
@@ -148,6 +157,15 @@ window.__ModuleLoader__.load({
|
|
|
148
157
|
recallIntervalHint: 'A random interval between min and max each time, so the rhythm never feels fixed',
|
|
149
158
|
recallMaxPerSession: 'Recalls per session',
|
|
150
159
|
recallMaxPerSessionHint: 'Maximum proactive recalls in one session, to stay unobtrusive',
|
|
160
|
+
toneGuide: 'Tone guidance',
|
|
161
|
+
toneGuideHint: 'Shift register by context (crunch, late night, bad news, milestones) without changing facts or crossing the SOUL boundary',
|
|
162
|
+
toneIntensity: 'Tone intensity',
|
|
163
|
+
toneIntensityHint: 'low = light seasoning / medium = more visible / off = pure engineering voice; facts always win',
|
|
164
|
+
toneLow: 'low (light seasoning)',
|
|
165
|
+
toneMedium: 'medium (more visible)',
|
|
166
|
+
toneOff: 'off (pure engineering voice)',
|
|
167
|
+
growthRecap: 'Weekly growth recap',
|
|
168
|
+
growthRecapHint: 'Once a week, on the recall channel, say what I kept this week (first person, at most five sentences; can be turned off)',
|
|
151
169
|
minutesPlaceholder: '30',
|
|
152
170
|
maxMinutesPlaceholder: '240',
|
|
153
171
|
maxPerSessionPlaceholder: '3',
|
|
@@ -625,6 +643,17 @@ window.__ModuleLoader__.load({
|
|
|
625
643
|
})
|
|
626
644
|
}
|
|
627
645
|
|
|
646
|
+
/** 下拉选择:语气强度这类枚举配置,改动立即写回。 */
|
|
647
|
+
function SelectInput({ value, disabled, options, onChange }) {
|
|
648
|
+
return React.createElement('select', {
|
|
649
|
+
disabled,
|
|
650
|
+
value: value ?? '',
|
|
651
|
+
onChange: (event) => onChange(event.target.value),
|
|
652
|
+
style: { ...inputStyle, width: '190px', cursor: 'pointer' },
|
|
653
|
+
}, (options ?? []).map((option) =>
|
|
654
|
+
React.createElement('option', { key: option.value, value: option.value }, option.label)))
|
|
655
|
+
}
|
|
656
|
+
|
|
628
657
|
function MemoryForm(props) {
|
|
629
658
|
const t = useT(props)
|
|
630
659
|
const { onSaved } = props
|
|
@@ -794,6 +823,44 @@ window.__ModuleLoader__.load({
|
|
|
794
823
|
onCommit: (next) => apply({ recallMaxPerSession: next }),
|
|
795
824
|
}),
|
|
796
825
|
),
|
|
826
|
+
React.createElement('div', { style: rowStyle },
|
|
827
|
+
React.createElement('div', null,
|
|
828
|
+
React.createElement('div', { style: labelStyle }, t('toneGuide')),
|
|
829
|
+
React.createElement('div', { style: subStyle }, t('toneGuideHint')),
|
|
830
|
+
),
|
|
831
|
+
React.createElement(Toggle, {
|
|
832
|
+
checked: value.toneGuideEnabled !== false,
|
|
833
|
+
disabled,
|
|
834
|
+
onChange: (next) => apply({ toneGuideEnabled: next }),
|
|
835
|
+
}),
|
|
836
|
+
),
|
|
837
|
+
React.createElement('div', { style: rowStyle },
|
|
838
|
+
React.createElement('div', null,
|
|
839
|
+
React.createElement('div', { style: labelStyle }, t('toneIntensity')),
|
|
840
|
+
React.createElement('div', { style: subStyle }, t('toneIntensityHint')),
|
|
841
|
+
),
|
|
842
|
+
React.createElement(SelectInput, {
|
|
843
|
+
value: value.toneIntensity ?? 'low',
|
|
844
|
+
disabled: disabled || value.toneGuideEnabled === false,
|
|
845
|
+
options: [
|
|
846
|
+
{ value: 'low', label: t('toneLow') },
|
|
847
|
+
{ value: 'medium', label: t('toneMedium') },
|
|
848
|
+
{ value: 'off', label: t('toneOff') },
|
|
849
|
+
],
|
|
850
|
+
onChange: (next) => apply({ toneIntensity: next }),
|
|
851
|
+
}),
|
|
852
|
+
),
|
|
853
|
+
React.createElement('div', { style: rowStyle },
|
|
854
|
+
React.createElement('div', null,
|
|
855
|
+
React.createElement('div', { style: labelStyle }, t('growthRecap')),
|
|
856
|
+
React.createElement('div', { style: subStyle }, t('growthRecapHint')),
|
|
857
|
+
),
|
|
858
|
+
React.createElement(Toggle, {
|
|
859
|
+
checked: value.growthRecapEnabled !== false,
|
|
860
|
+
disabled,
|
|
861
|
+
onChange: (next) => apply({ growthRecapEnabled: next }),
|
|
862
|
+
}),
|
|
863
|
+
),
|
|
797
864
|
error !== undefined ? React.createElement('div', { style: errorStyle }, t('saveFailed'), error) : null,
|
|
798
865
|
React.createElement('div', { style: { padding: '14px 16px', fontSize: '12px', lineHeight: '18px', color: 'var(--dsw-alias-label-secondary, #888)' } },
|
|
799
866
|
value.enabled === false
|
package/lib/config-store.js
CHANGED
|
@@ -23,7 +23,10 @@ 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', 'deferUntilUserSpeaks', 'activeSessionOnly', 'recallEnabled', 'recallIntervalMinMinutes', 'recallIntervalMaxMinutes', 'recallMaxPerSession']
|
|
26
|
+
const FIELDS = ['enabled', 'memoryDir', 'autoInject', 'registerSkill', 'deferUntilUserSpeaks', 'activeSessionOnly', 'recallEnabled', 'recallIntervalMinMinutes', 'recallIntervalMaxMinutes', 'recallMaxPerSession', 'proactiveCooldownSeconds', 'toneGuideEnabled', 'toneIntensity', 'growthRecapEnabled', 'growthRecapIntervalDays']
|
|
27
|
+
|
|
28
|
+
/** Tone intensity values the schema accepts; invalid composition input falls back to low. */
|
|
29
|
+
const TONE_INTENSITIES = ['low', 'medium', 'off']
|
|
27
30
|
|
|
28
31
|
function pickFields(input) {
|
|
29
32
|
const picked = {}
|
|
@@ -63,6 +66,11 @@ export class MemoryConfigStore {
|
|
|
63
66
|
recallIntervalMinMinutes: options.base?.recallIntervalMinMinutes ?? 30,
|
|
64
67
|
recallIntervalMaxMinutes: options.base?.recallIntervalMaxMinutes ?? 240,
|
|
65
68
|
recallMaxPerSession: options.base?.recallMaxPerSession ?? 3,
|
|
69
|
+
proactiveCooldownSeconds: options.base?.proactiveCooldownSeconds ?? 180,
|
|
70
|
+
toneGuideEnabled: options.base?.toneGuideEnabled !== false,
|
|
71
|
+
toneIntensity: TONE_INTENSITIES.includes(options.base?.toneIntensity) ? options.base.toneIntensity : 'low',
|
|
72
|
+
growthRecapEnabled: options.base?.growthRecapEnabled !== false,
|
|
73
|
+
growthRecapIntervalDays: options.base?.growthRecapIntervalDays ?? 7,
|
|
66
74
|
}
|
|
67
75
|
this.config = { ...this.base }
|
|
68
76
|
this.watchers = new Set()
|
|
@@ -94,6 +102,11 @@ export class MemoryConfigStore {
|
|
|
94
102
|
recallIntervalMinMinutes: resolved.recallIntervalMinMinutes,
|
|
95
103
|
recallIntervalMaxMinutes: resolved.recallIntervalMaxMinutes,
|
|
96
104
|
recallMaxPerSession: resolved.recallMaxPerSession,
|
|
105
|
+
proactiveCooldownSeconds: resolved.proactiveCooldownSeconds,
|
|
106
|
+
toneGuideEnabled: resolved.toneGuideEnabled,
|
|
107
|
+
toneIntensity: resolved.toneIntensity,
|
|
108
|
+
growthRecapEnabled: resolved.growthRecapEnabled,
|
|
109
|
+
growthRecapIntervalDays: resolved.growthRecapIntervalDays,
|
|
97
110
|
}
|
|
98
111
|
} catch {
|
|
99
112
|
// schema validation failed: keep last good config
|
|
@@ -133,6 +146,11 @@ export class MemoryConfigStore {
|
|
|
133
146
|
recallIntervalMinMinutes: next.recallIntervalMinMinutes,
|
|
134
147
|
recallIntervalMaxMinutes: next.recallIntervalMaxMinutes,
|
|
135
148
|
recallMaxPerSession: next.recallMaxPerSession,
|
|
149
|
+
proactiveCooldownSeconds: next.proactiveCooldownSeconds,
|
|
150
|
+
toneGuideEnabled: next.toneGuideEnabled,
|
|
151
|
+
toneIntensity: next.toneIntensity,
|
|
152
|
+
growthRecapEnabled: next.growthRecapEnabled,
|
|
153
|
+
growthRecapIntervalDays: next.growthRecapIntervalDays,
|
|
136
154
|
}
|
|
137
155
|
this.persist()
|
|
138
156
|
for (const watcher of this.watchers) {
|
package/lib/digest-guard.js
CHANGED
|
@@ -109,7 +109,8 @@ export function buildDigestNudgeMessage(staleMinutes, options = {}) {
|
|
|
109
109
|
|
|
110
110
|
/**
|
|
111
111
|
* @typedef {object} DigestGuardOptions
|
|
112
|
-
* @property {() => { enabled: boolean, afterMinutes: number, cooldownMinutes: number, maxPerSession: number, deferUntilUserSpeaks?: boolean, activeSessionOnly?: boolean }} readConfig
|
|
112
|
+
* @property {() => { enabled: boolean, afterMinutes: number, cooldownMinutes: number, maxPerSession: number, deferUntilUserSpeaks?: boolean, activeSessionOnly?: boolean, proactiveCooldownSeconds?: number }} readConfig
|
|
113
|
+
* @property {(options: { now: number, cooldownSeconds: number }) => { ok: boolean, deferredBy?: string }} [claimLock] shared proactive lock (see proactive-lock.js)
|
|
113
114
|
* @property {() => string} getMemoryDir resolve the current store dir on every check
|
|
114
115
|
* @property {unknown} [agents] optional live-agent registry for liveness checks
|
|
115
116
|
* @property {import('./activity-tracker.js').ActivityTracker} [tracker] gate source: has-user-spoken + active-session
|
|
@@ -131,6 +132,7 @@ export class DigestGuard {
|
|
|
131
132
|
this.agents = options.agents
|
|
132
133
|
this.tracker = options.tracker
|
|
133
134
|
this.logger = options.logger
|
|
135
|
+
this.claimLock = options.claimLock
|
|
134
136
|
this.disposed = false
|
|
135
137
|
this.stopTurnStopping = undefined
|
|
136
138
|
this.nudges = 0
|
|
@@ -181,6 +183,16 @@ export class DigestGuard {
|
|
|
181
183
|
const lastWrite = lastStoreWriteMs(this.getMemoryDir())
|
|
182
184
|
if (now - lastWrite < afterMs) return
|
|
183
185
|
|
|
186
|
+
// Proactive-speech arbitration: dsh-plugin-heartbeat may have just spoken,
|
|
187
|
+
// and two synthetic followups in one quiet window is exactly the noise the
|
|
188
|
+
// shared cooldown file exists to prevent. Refused = skip this round; the
|
|
189
|
+
// next idle boundary retries and this guard's own cooldown is not consumed.
|
|
190
|
+
const claim = this.claimProactive(now, config)
|
|
191
|
+
if (!claim.ok) {
|
|
192
|
+
this.logger?.info?.(`memory: digest reminder deferred for agent "${this.agent.id}" (${claim.deferredBy} holds the lock)`)
|
|
193
|
+
return
|
|
194
|
+
}
|
|
195
|
+
|
|
184
196
|
const staleMinutes = Math.max(1, Math.round((now - lastWrite) / 60000))
|
|
185
197
|
// Only computed once a reminder is actually being delivered: scanning the
|
|
186
198
|
// store on every idle turn would be pure overhead.
|
|
@@ -191,4 +203,26 @@ export class DigestGuard {
|
|
|
191
203
|
this.logger?.info?.(`memory: digest nudge #${this.nudges} for agent "${this.agent.id}" `
|
|
192
204
|
+ `(store idle ${staleMinutes}min${indexHint.length > 0 ? ', index drift reported' : ''})`)
|
|
193
205
|
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Ask the shared proactive lock for permission to speak. Missing lock (no
|
|
209
|
+
* other proactive plugin) or a broken lock never blocks the reminder:
|
|
210
|
+
* arbitration is best-effort.
|
|
211
|
+
* @param {number} now epoch ms
|
|
212
|
+
* @param {{ proactiveCooldownSeconds?: number }} config
|
|
213
|
+
* @returns {{ ok: boolean, deferredBy?: string }}
|
|
214
|
+
*/
|
|
215
|
+
claimProactive(now, config) {
|
|
216
|
+
if (typeof this.claimLock !== 'function') return { ok: true }
|
|
217
|
+
try {
|
|
218
|
+
const result = this.claimLock({
|
|
219
|
+
now,
|
|
220
|
+
cooldownSeconds: Math.max(0, Number(config.proactiveCooldownSeconds ?? 180)),
|
|
221
|
+
})
|
|
222
|
+
return result ?? { ok: true }
|
|
223
|
+
} catch (error) {
|
|
224
|
+
this.logger?.warn?.(`memory: proactive lock failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
225
|
+
return { ok: true }
|
|
226
|
+
}
|
|
227
|
+
}
|
|
194
228
|
}
|
package/lib/growth.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Growth recap: the "look how far we've come" half of the persona.
|
|
3
|
+
*
|
|
4
|
+
* A long-term companion should occasionally *notice* its own growth instead of
|
|
5
|
+
* only reacting — "this week I kept these things, and touched those pages".
|
|
6
|
+
* Everything here is derived from what the memory store already proves: the
|
|
7
|
+
* recent `log.md` headlines and page mtimes. No new bookkeeping, no invented
|
|
8
|
+
* progress.
|
|
9
|
+
*
|
|
10
|
+
* The recap is delivered on the recall-nudge channel at most once every
|
|
11
|
+
* `growthRecapIntervalDays`; `<store>/.growth-recap.json` records the last
|
|
12
|
+
* delivery so a restart does not repeat the same week.
|
|
13
|
+
*
|
|
14
|
+
* This module depends only on `node:*` builtins plus {@link ./pages.js}.
|
|
15
|
+
*
|
|
16
|
+
* @module dsh-plugin-memory/growth
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
|
|
20
|
+
import { dirname, join } from 'node:path'
|
|
21
|
+
import { listPagePaths } from './pages.js'
|
|
22
|
+
|
|
23
|
+
/** State file recording the last delivered recap (store-relative). */
|
|
24
|
+
export const GROWTH_STATE_FILENAME = '.growth-recap.json'
|
|
25
|
+
|
|
26
|
+
const DAY_MS = 24 * 60 * 60 * 1000
|
|
27
|
+
|
|
28
|
+
/** Start of the local day containing `epochMs`. */
|
|
29
|
+
function dayStart(epochMs) {
|
|
30
|
+
const date = new Date(epochMs)
|
|
31
|
+
date.setHours(0, 0, 0, 0)
|
|
32
|
+
return date.getTime()
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Parse one `log.md` headline: `## [2026-10-30] release | 标题`.
|
|
37
|
+
* @param {string} line
|
|
38
|
+
* @returns {{title: string, date: string, kind: string} | undefined}
|
|
39
|
+
*/
|
|
40
|
+
export function parseGrowthLogEntry(line) {
|
|
41
|
+
const match = /^##\s+\[(\d{4}-\d{2}-\d{2})\]\s*(.*)$/.exec(line)
|
|
42
|
+
if (match === null) return undefined
|
|
43
|
+
const rest = match[2].trim()
|
|
44
|
+
if (rest.length === 0) return undefined
|
|
45
|
+
const pipe = rest.indexOf('|')
|
|
46
|
+
const kind = pipe >= 0 ? (rest.slice(0, pipe).trim() || 'note') : 'note'
|
|
47
|
+
const title = pipe >= 0 ? rest.slice(pipe + 1).trim() : rest
|
|
48
|
+
if (title.length === 0) return undefined
|
|
49
|
+
return { title, date: match[1], kind }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Collect this week's growth from the store.
|
|
54
|
+
*
|
|
55
|
+
* - `entries`: `log.md` headlines dated inside the window, newest first, at
|
|
56
|
+
* most `max`.
|
|
57
|
+
* - `pagesChanged`: memory pages whose mtime falls inside the window.
|
|
58
|
+
* - `newPages`: pages that were also *created* inside the window (birthtime),
|
|
59
|
+
* i.e. genuinely new memories rather than edits to old ones.
|
|
60
|
+
*
|
|
61
|
+
* Never throws: a missing/corrupt store yields an empty recap.
|
|
62
|
+
*
|
|
63
|
+
* @param {object} options
|
|
64
|
+
* @param {string} options.storeDir absolute memory-store path
|
|
65
|
+
* @param {number} [options.sinceDays] window size in days (default 7)
|
|
66
|
+
* @param {number} [options.max] headline cap (default 5)
|
|
67
|
+
* @param {number} [options.now] epoch ms (injectable for tests)
|
|
68
|
+
* @returns {{ entries: Array<{title: string, date: string, kind: string}>, pagesChanged: number, newPages: number }}
|
|
69
|
+
*/
|
|
70
|
+
export function collectGrowth({ storeDir, sinceDays = 7, max = 5, now = Date.now() } = {}) {
|
|
71
|
+
const days = Number.isFinite(Number(sinceDays)) ? Math.max(0, Number(sinceDays)) : 7
|
|
72
|
+
const limit = Number.isFinite(Number(max)) ? Math.max(0, Number(max)) : 5
|
|
73
|
+
const windowStartMs = dayStart(now) - days * DAY_MS
|
|
74
|
+
|
|
75
|
+
// 1. Recent log headlines (the durable proof of what happened).
|
|
76
|
+
const entries = []
|
|
77
|
+
const logPath = join(storeDir, 'log.md')
|
|
78
|
+
if (existsSync(logPath)) {
|
|
79
|
+
try {
|
|
80
|
+
for (const line of readFileSync(logPath, 'utf8').split('\n')) {
|
|
81
|
+
const entry = parseGrowthLogEntry(line)
|
|
82
|
+
if (entry === undefined) continue
|
|
83
|
+
const entryMs = Date.parse(`${entry.date}T00:00:00`)
|
|
84
|
+
if (!Number.isFinite(entryMs) || entryMs < windowStartMs) continue
|
|
85
|
+
entries.push(entry)
|
|
86
|
+
}
|
|
87
|
+
} catch {
|
|
88
|
+
// unreadable log: still report page activity
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
entries.reverse()
|
|
92
|
+
entries.splice(limit)
|
|
93
|
+
|
|
94
|
+
// 2. Page activity from mtimes (birthtime separates new pages from edits).
|
|
95
|
+
let pagesChanged = 0
|
|
96
|
+
let newPages = 0
|
|
97
|
+
try {
|
|
98
|
+
for (const rel of listPagePaths(storeDir)) {
|
|
99
|
+
let stat
|
|
100
|
+
try {
|
|
101
|
+
stat = statSync(join(storeDir, rel))
|
|
102
|
+
} catch {
|
|
103
|
+
continue
|
|
104
|
+
}
|
|
105
|
+
if (stat.mtimeMs < windowStartMs) continue
|
|
106
|
+
pagesChanged += 1
|
|
107
|
+
if (stat.birthtimeMs > 0 && stat.birthtimeMs >= windowStartMs) newPages += 1
|
|
108
|
+
}
|
|
109
|
+
} catch {
|
|
110
|
+
// store vanished mid-scan: keep the log half
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return { entries, pagesChanged, newPages }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Render the first-person recap. At most two sentences (well under the
|
|
118
|
+
* "≤5 sentences" contract), each half omitted when there is nothing to say.
|
|
119
|
+
*
|
|
120
|
+
* @param {object} options
|
|
121
|
+
* @param {Array<{title: string}>} [options.entries]
|
|
122
|
+
* @param {number} [options.pagesChanged]
|
|
123
|
+
* @param {number} [options.newPages]
|
|
124
|
+
* @param {'zh'|'en'} [options.language]
|
|
125
|
+
* @returns {string} recap text, '' when there is no growth to report
|
|
126
|
+
*/
|
|
127
|
+
export function renderGrowthRecap({ entries, pagesChanged = 0, newPages = 0, language = 'zh' } = {}) {
|
|
128
|
+
const titles = (Array.isArray(entries) ? entries : [])
|
|
129
|
+
.filter((entry) => entry && typeof entry.title === 'string' && entry.title.trim().length > 0)
|
|
130
|
+
.slice(0, 5)
|
|
131
|
+
.map((entry) => entry.title.trim())
|
|
132
|
+
const changed = Math.max(0, Number(pagesChanged) || 0)
|
|
133
|
+
const fresh = Math.max(0, Math.min(changed, Number(newPages) || 0))
|
|
134
|
+
const sentences = []
|
|
135
|
+
|
|
136
|
+
if (language === 'en') {
|
|
137
|
+
if (titles.length > 0) {
|
|
138
|
+
sentences.push(`This week I remembered ${titles.length} thing${titles.length === 1 ? '' : 's'}: ${titles.join('; ')}.`)
|
|
139
|
+
}
|
|
140
|
+
if (changed > 0) {
|
|
141
|
+
sentences.push(`I also touched ${changed} memory page${changed === 1 ? '' : 's'}${fresh > 0 ? ` (${fresh} new)` : ''}.`)
|
|
142
|
+
}
|
|
143
|
+
} else {
|
|
144
|
+
if (titles.length > 0) {
|
|
145
|
+
sentences.push(`这周我记住了 ${titles.length} 件:${titles.join(';')}。`)
|
|
146
|
+
}
|
|
147
|
+
if (changed > 0) {
|
|
148
|
+
sentences.push(`另外改了 ${changed} 页记忆${fresh > 0 ? `(其中 ${fresh} 页是新写的)` : ''}。`)
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return sentences.join('')
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Read the last-delivered state; anything unreadable means "never recapped".
|
|
156
|
+
* @param {string} statePath absolute `.growth-recap.json` path
|
|
157
|
+
* @returns {{ version: number, lastAt: number } | undefined}
|
|
158
|
+
*/
|
|
159
|
+
export function readGrowthState(statePath) {
|
|
160
|
+
if (typeof statePath !== 'string' || statePath.length === 0 || !existsSync(statePath)) return undefined
|
|
161
|
+
let raw
|
|
162
|
+
try {
|
|
163
|
+
raw = JSON.parse(readFileSync(statePath, 'utf8'))
|
|
164
|
+
} catch {
|
|
165
|
+
return undefined
|
|
166
|
+
}
|
|
167
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined
|
|
168
|
+
const lastAt = Number(raw.lastAt)
|
|
169
|
+
if (!Number.isFinite(lastAt) || lastAt <= 0) return undefined
|
|
170
|
+
return { version: Number.isFinite(Number(raw.version)) ? Number(raw.version) : 1, lastAt }
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Whether a recap is due now.
|
|
175
|
+
* @param {object} options
|
|
176
|
+
* @param {string} options.statePath absolute state-file path
|
|
177
|
+
* @param {number} [options.intervalDays] default 7
|
|
178
|
+
* @param {number} [options.now]
|
|
179
|
+
* @returns {boolean}
|
|
180
|
+
*/
|
|
181
|
+
export function growthRecapDue({ statePath, intervalDays = 7, now = Date.now() } = {}) {
|
|
182
|
+
const state = readGrowthState(statePath)
|
|
183
|
+
if (state === undefined) return true
|
|
184
|
+
const days = Number.isFinite(Number(intervalDays)) ? Math.max(0, Number(intervalDays)) : 7
|
|
185
|
+
return now - state.lastAt >= days * DAY_MS
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Persist the delivery time atomically.
|
|
190
|
+
* @param {string} statePath absolute state-file path
|
|
191
|
+
* @param {number} [lastAt] epoch ms (default now)
|
|
192
|
+
* @returns {{ version: number, lastAt: number }}
|
|
193
|
+
*/
|
|
194
|
+
export function writeGrowthState(statePath, lastAt = Date.now()) {
|
|
195
|
+
const state = { version: 1, lastAt }
|
|
196
|
+
mkdirSync(dirname(statePath), { recursive: true })
|
|
197
|
+
const tmp = `${statePath}.tmp`
|
|
198
|
+
writeFileSync(tmp, `${JSON.stringify(state)}\n`, 'utf8')
|
|
199
|
+
renameSync(tmp, statePath)
|
|
200
|
+
return state
|
|
201
|
+
}
|
package/lib/index.js
CHANGED
|
@@ -52,6 +52,11 @@
|
|
|
52
52
|
* | `registerSkill` | `true` | register the embedded `memory` skill |
|
|
53
53
|
* | `scaffold` | `true` | create the store layout + templates when missing |
|
|
54
54
|
* | `configFile` | `<dshHome>/memory.json` | user-facing config file (Settings panel) |
|
|
55
|
+
* | `proactiveCooldownSeconds` | `180` | shared proactive-speech lock with heartbeat (0 = off) |
|
|
56
|
+
* | `toneGuideEnabled` | `true` | inject the context-sensitive tone section after SOUL |
|
|
57
|
+
* | `toneIntensity` | `low` | `low` / `medium` / `off` (pure engineering voice) |
|
|
58
|
+
* | `growthRecapEnabled` | `true` | weekly growth recap on the recall channel |
|
|
59
|
+
* | `growthRecapIntervalDays` | `7` | days between growth recaps |
|
|
55
60
|
*
|
|
56
61
|
* `enabled`, `memoryDir`, `autoInject` and `registerSkill` are editable in
|
|
57
62
|
* the Settings panel and hot-apply: boot injection, the skill registration
|
|
@@ -99,6 +104,8 @@ import { MemoryConfigStore } from './config-store.js'
|
|
|
99
104
|
import { SettingsSchema } from './schema.js'
|
|
100
105
|
import { DigestGuard } from './digest-guard.js'
|
|
101
106
|
import { RecallNudge } from './recall-nudge.js'
|
|
107
|
+
import { buildToneGuide } from './tone.js'
|
|
108
|
+
import { claimProactiveLock, defaultProactiveCooldownPath } from './proactive-lock.js'
|
|
102
109
|
import { AutoCommitter } from './autocommit.js'
|
|
103
110
|
import { ActivityTracker } from './activity-tracker.js'
|
|
104
111
|
import {
|
|
@@ -155,6 +162,16 @@ export const Config = z.object({
|
|
|
155
162
|
recallIntervalMinMinutes: z.number().default(30),
|
|
156
163
|
recallIntervalMaxMinutes: z.number().default(240),
|
|
157
164
|
recallMaxPerSession: z.number().default(3),
|
|
165
|
+
// Shared proactive-speech arbitration with dsh-plugin-heartbeat: one JSON
|
|
166
|
+
// file, claimed before any synthetic followup. 180s default; 0 = off.
|
|
167
|
+
proactiveCooldownSeconds: z.number().default(180),
|
|
168
|
+
// Tone drift: inject a bounded "how to shift register by context" section
|
|
169
|
+
// after SOUL. `off` restores the pre-0.12.0 boot block exactly.
|
|
170
|
+
toneGuideEnabled: z.boolean().default(true),
|
|
171
|
+
toneIntensity: z.union([z.const('low'), z.const('medium'), z.const('off')]).default('low'),
|
|
172
|
+
// Weekly growth recap, delivered on the recall channel.
|
|
173
|
+
growthRecapEnabled: z.boolean().default(true),
|
|
174
|
+
growthRecapIntervalDays: z.number().default(7),
|
|
158
175
|
// Auto-commit: keep the store's git history current after a quiet period.
|
|
159
176
|
autoCommit: z.boolean().default(true),
|
|
160
177
|
autoCommitQuietSeconds: z.number().default(60),
|
|
@@ -199,6 +216,11 @@ export function apply(ctx, config = {}) {
|
|
|
199
216
|
recallIntervalMinMinutes: config.recallIntervalMinMinutes ?? 30,
|
|
200
217
|
recallIntervalMaxMinutes: config.recallIntervalMaxMinutes ?? 240,
|
|
201
218
|
recallMaxPerSession: config.recallMaxPerSession ?? 3,
|
|
219
|
+
proactiveCooldownSeconds: config.proactiveCooldownSeconds ?? 180,
|
|
220
|
+
toneGuideEnabled: config.toneGuideEnabled !== false,
|
|
221
|
+
toneIntensity: ['low', 'medium', 'off'].includes(config.toneIntensity) ? config.toneIntensity : 'low',
|
|
222
|
+
growthRecapEnabled: config.growthRecapEnabled !== false,
|
|
223
|
+
growthRecapIntervalDays: config.growthRecapIntervalDays ?? 7,
|
|
202
224
|
},
|
|
203
225
|
})
|
|
204
226
|
|
|
@@ -279,9 +301,16 @@ export function apply(ctx, config = {}) {
|
|
|
279
301
|
// Per-agent gate: no agent context (e.g. a global preview) injects
|
|
280
302
|
// unconditionally; an agent injects only once it has spoken and is
|
|
281
303
|
// the active session.
|
|
304
|
+
const resolved = store.get()
|
|
282
305
|
const agent = context?.agent
|
|
283
|
-
if (agent && !tracker.shouldInject(agent.id,
|
|
284
|
-
|
|
306
|
+
if (agent && !tracker.shouldInject(agent.id, resolved)) return ''
|
|
307
|
+
// Tone drift rides on the boot block (charged to its budget). Read
|
|
308
|
+
// live from the store so the Settings select applies on the next
|
|
309
|
+
// prompt build without a reload.
|
|
310
|
+
const toneGuide = resolved.toneGuideEnabled
|
|
311
|
+
? buildToneGuide({ intensity: resolved.toneIntensity, language: 'zh' })
|
|
312
|
+
: ''
|
|
313
|
+
return renderBootBlock(memoryDir, { bootFiles, bootMaxChars, bootFileBudgets, toneGuide })
|
|
285
314
|
},
|
|
286
315
|
})
|
|
287
316
|
} else {
|
|
@@ -363,6 +392,14 @@ export function apply(ctx, config = {}) {
|
|
|
363
392
|
}, 'memory.page-access()')
|
|
364
393
|
}
|
|
365
394
|
|
|
395
|
+
/** Claim the cross-plugin proactive lock (see lib/proactive-lock.js). */
|
|
396
|
+
const claimSharedProactiveLock = ({ now, cooldownSeconds }) => claimProactiveLock({
|
|
397
|
+
path: defaultProactiveCooldownPath(),
|
|
398
|
+
speaker: 'memory',
|
|
399
|
+
cooldownSeconds,
|
|
400
|
+
now,
|
|
401
|
+
})
|
|
402
|
+
|
|
366
403
|
// Digest guard: one per live ROOT agent, so a skipped end-of-session
|
|
367
404
|
// digest is caught mechanically instead of relying on the agent's
|
|
368
405
|
// self-discipline. Independent of dsh-plugin-heartbeat — the nudge is
|
|
@@ -381,12 +418,14 @@ export function apply(ctx, config = {}) {
|
|
|
381
418
|
maxPerSession: config.digestNudgeMaxPerSession,
|
|
382
419
|
deferUntilUserSpeaks: resolved.deferUntilUserSpeaks,
|
|
383
420
|
activeSessionOnly: resolved.activeSessionOnly,
|
|
421
|
+
proactiveCooldownSeconds: resolved.proactiveCooldownSeconds,
|
|
384
422
|
}
|
|
385
423
|
},
|
|
386
424
|
getMemoryDir: () => currentMemoryDir,
|
|
387
425
|
agents: ctx.agents,
|
|
388
426
|
tracker,
|
|
389
427
|
logger: ctx.logger,
|
|
428
|
+
claimLock: claimSharedProactiveLock,
|
|
390
429
|
})
|
|
391
430
|
agent.ctx.effect(() => {
|
|
392
431
|
guard.start()
|
|
@@ -416,12 +455,22 @@ export function apply(ctx, config = {}) {
|
|
|
416
455
|
maxPerSession: resolved.recallMaxPerSession,
|
|
417
456
|
deferUntilUserSpeaks: resolved.deferUntilUserSpeaks,
|
|
418
457
|
activeSessionOnly: resolved.activeSessionOnly,
|
|
458
|
+
proactiveCooldownSeconds: resolved.proactiveCooldownSeconds,
|
|
459
|
+
}
|
|
460
|
+
},
|
|
461
|
+
readGrowthConfig: () => {
|
|
462
|
+
const resolved = store.get()
|
|
463
|
+
return {
|
|
464
|
+
enabled: resolved.growthRecapEnabled !== false,
|
|
465
|
+
intervalDays: resolved.growthRecapIntervalDays,
|
|
466
|
+
language: 'zh',
|
|
419
467
|
}
|
|
420
468
|
},
|
|
421
469
|
getMemoryDir: () => currentMemoryDir,
|
|
422
470
|
agents: ctx.agents,
|
|
423
471
|
tracker,
|
|
424
472
|
logger: ctx.logger,
|
|
473
|
+
claimLock: claimSharedProactiveLock,
|
|
425
474
|
})
|
|
426
475
|
agent.ctx.effect(() => {
|
|
427
476
|
nudge.start()
|
|
@@ -558,3 +607,6 @@ export { renderBootBlock, ensureMemoryScaffold, SettingsSchema, MemoryConfigStor
|
|
|
558
607
|
export { touchPages, touchPageFile, extractReferencedPages, listPagePaths, accessSummary, today }
|
|
559
608
|
export { collectInsights, readRecentLog } from './insights.js'
|
|
560
609
|
export { buildMemoryGraph, EDGE_KINDS } from './graph.js'
|
|
610
|
+
export { buildToneGuide, TONE_INTENSITIES, TONE_GUIDE_MAX_LINES } from './tone.js'
|
|
611
|
+
export { claimProactiveLock, readProactiveLock, defaultProactiveCooldownPath } from './proactive-lock.js'
|
|
612
|
+
export { collectGrowth, renderGrowthRecap, growthRecapDue } from './growth.js'
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Proactive-speech arbitration: the shared "who may speak right now" lock.
|
|
3
|
+
*
|
|
4
|
+
* Two independent plugins can each decide, on their own timer, that the agent
|
|
5
|
+
* should say something unprompted — dsh-plugin-memory (recall / digest /
|
|
6
|
+
* growth recap) and dsh-plugin-heartbeat. Without arbitration both fire in the
|
|
7
|
+
* same quiet window and the user gets a burst of synthetic followups.
|
|
8
|
+
*
|
|
9
|
+
* They cannot import each other (plugin boundary: zero cross-plugin imports),
|
|
10
|
+
* so the protocol is a single JSON file both implementations understand:
|
|
11
|
+
*
|
|
12
|
+
* ```json
|
|
13
|
+
* { "version": 1, "speaker": "memory" | "heartbeat", "at": 1760000000000 }
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* A speaker may claim only when the file is absent, corrupt, owns the same
|
|
17
|
+
* `speaker` name (its own lock), or the previous claim is older than the
|
|
18
|
+
* cooldown. Writes are atomic (tmp + rename) so a reader never sees a partial
|
|
19
|
+
* document; a corrupt file degrades to "no lock" because a broken cooldown
|
|
20
|
+
* must never silence the plugin forever.
|
|
21
|
+
*
|
|
22
|
+
* This module depends only on `node:*` builtins.
|
|
23
|
+
*
|
|
24
|
+
* @module dsh-plugin-memory/proactive-lock
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
28
|
+
import { homedir } from 'node:os'
|
|
29
|
+
import { dirname, join } from 'node:path'
|
|
30
|
+
|
|
31
|
+
/** File name of the shared arbitration protocol (same on both sides). */
|
|
32
|
+
export const PROACTIVE_COOLDOWN_FILENAME = 'proactive-cooldown.json'
|
|
33
|
+
|
|
34
|
+
/** Protocol version written into the file. */
|
|
35
|
+
export const PROACTIVE_LOCK_VERSION = 1
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The shared cooldown file location: `${DSH_HOME||~/.dsh}/proactive-cooldown.json`.
|
|
39
|
+
* Both plugins resolve it the same way so they meet on the same file.
|
|
40
|
+
* @returns {string} absolute path
|
|
41
|
+
*/
|
|
42
|
+
export function defaultProactiveCooldownPath() {
|
|
43
|
+
return join(process.env.DSH_HOME || join(homedir(), '.dsh'), PROACTIVE_COOLDOWN_FILENAME)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Read the current lock, tolerating every kind of damage.
|
|
48
|
+
*
|
|
49
|
+
* @param {string} path absolute lock-file path
|
|
50
|
+
* @returns {{version: number, speaker: string, at: number} | undefined}
|
|
51
|
+
* the parsed lock, or undefined when missing/corrupt (== no lock)
|
|
52
|
+
*/
|
|
53
|
+
export function readProactiveLock(path) {
|
|
54
|
+
if (typeof path !== 'string' || path.length === 0 || !existsSync(path)) return undefined
|
|
55
|
+
let raw
|
|
56
|
+
try {
|
|
57
|
+
raw = JSON.parse(readFileSync(path, 'utf8'))
|
|
58
|
+
} catch {
|
|
59
|
+
return undefined
|
|
60
|
+
}
|
|
61
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined
|
|
62
|
+
const at = Number(raw.at)
|
|
63
|
+
if (!Number.isFinite(at)) return undefined
|
|
64
|
+
return {
|
|
65
|
+
version: Number.isFinite(Number(raw.version)) ? Number(raw.version) : PROACTIVE_LOCK_VERSION,
|
|
66
|
+
speaker: typeof raw.speaker === 'string' && raw.speaker.length > 0 ? raw.speaker : 'unknown',
|
|
67
|
+
at,
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Try to take the proactive-speech lock.
|
|
73
|
+
*
|
|
74
|
+
* The lock is advisory and single-file: claim right before injecting a
|
|
75
|
+
* followup, and if it is refused, skip this round (the next scheduled trigger
|
|
76
|
+
* tries again). `cooldownSeconds <= 0` turns arbitration off entirely (the
|
|
77
|
+
* config escape hatch) and writes nothing.
|
|
78
|
+
*
|
|
79
|
+
* @param {object} [options]
|
|
80
|
+
* @param {string} [options.path] lock-file path (defaults to the shared path)
|
|
81
|
+
* @param {string} [options.speaker] who is speaking ('memory' here)
|
|
82
|
+
* @param {number} [options.cooldownSeconds] arbitration window; default 180, 0 = off
|
|
83
|
+
* @param {number} [options.now] epoch ms (injectable for tests)
|
|
84
|
+
* @returns {{ ok: true, disabled?: true } | { ok: false, deferredBy: string }}
|
|
85
|
+
*/
|
|
86
|
+
export function claimProactiveLock(options = {}) {
|
|
87
|
+
const path = typeof options.path === 'string' && options.path.length > 0
|
|
88
|
+
? options.path
|
|
89
|
+
: defaultProactiveCooldownPath()
|
|
90
|
+
const speaker = typeof options.speaker === 'string' && options.speaker.length > 0
|
|
91
|
+
? options.speaker
|
|
92
|
+
: 'memory'
|
|
93
|
+
const rawCooldown = Number(options.cooldownSeconds ?? 180)
|
|
94
|
+
const cooldownSeconds = Number.isFinite(rawCooldown) ? Math.max(0, rawCooldown) : 180
|
|
95
|
+
const rawNow = Number(options.now ?? Date.now())
|
|
96
|
+
const now = Number.isFinite(rawNow) ? rawNow : Date.now()
|
|
97
|
+
|
|
98
|
+
// Explicitly disabled: everyone may speak, and we leave the protocol file
|
|
99
|
+
// untouched so the other side's state is not clobbered for nothing.
|
|
100
|
+
if (cooldownSeconds === 0) return { ok: true, disabled: true }
|
|
101
|
+
|
|
102
|
+
const current = readProactiveLock(path)
|
|
103
|
+
if (current !== undefined && current.speaker !== speaker) {
|
|
104
|
+
const cooldownMs = cooldownSeconds * 1000
|
|
105
|
+
if (current.at > now - cooldownMs) {
|
|
106
|
+
return { ok: false, deferredBy: current.speaker }
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const lock = { version: PROACTIVE_LOCK_VERSION, speaker, at: now }
|
|
111
|
+
try {
|
|
112
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
113
|
+
const tmp = `${path}.tmp`
|
|
114
|
+
writeFileSync(tmp, `${JSON.stringify(lock)}\n`, 'utf8')
|
|
115
|
+
renameSync(tmp, path)
|
|
116
|
+
} catch {
|
|
117
|
+
// An unwritable lock file must not break the caller: arbitration is
|
|
118
|
+
// best-effort, the message itself is still worth delivering.
|
|
119
|
+
return { ok: true, disabled: true }
|
|
120
|
+
}
|
|
121
|
+
return { ok: true }
|
|
122
|
+
}
|
package/lib/recall-nudge.js
CHANGED
|
@@ -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
|
})
|
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
|
+
}
|
package/lib/types/index.d.ts
CHANGED
|
@@ -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.
|
|
4
|
+
"version": "0.12.0",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "lib/index.js",
|