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.
- package/CHANGELOG.md +30 -0
- package/README.md +21 -1
- package/README.zh.md +22 -4
- package/lib/boot.js +22 -3
- package/lib/client.js +495 -78
- 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/insights.js +17 -3
- package/lib/proactive-lock.js +122 -0
- package/lib/recall-nudge.js +122 -1
- package/lib/schema.js +10 -0
- package/lib/settings-nav-icon.js +17 -4
- package/lib/tone.js +86 -0
- package/lib/types/index.d.ts +44 -0
- package/package.json +1 -1
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'
|
package/lib/insights.js
CHANGED
|
@@ -158,18 +158,24 @@ export function collectInsights(memoryDir) {
|
|
|
158
158
|
const staleCount = pages.filter((p) => p.daysSinceAccess !== undefined && p.daysSinceAccess > 90).length
|
|
159
159
|
|
|
160
160
|
const atRisk = staleCount + never
|
|
161
|
+
// `label` / `detail` stay the Chinese strings the CLI and older clients read.
|
|
162
|
+
// `data` is an additive, locale-neutral copy of the same numbers so a client
|
|
163
|
+
// can render the sentence in its own language (see lib/client.js). Never drop
|
|
164
|
+
// the string fields: `dsh-memory checkup` and pre-0.11 panels depend on them.
|
|
161
165
|
const checks = [
|
|
162
166
|
{
|
|
163
167
|
id: 'index',
|
|
164
168
|
ok: missingLink.length === 0,
|
|
165
169
|
label: 'index 链接完整',
|
|
166
170
|
detail: missingLink.length === 0 ? `${indexEntries.length} 条路由全部有效` : `${missingLink.length} 条指向不存在的页`,
|
|
171
|
+
data: { routes: indexEntries.length, missing: missingLink.length },
|
|
167
172
|
},
|
|
168
173
|
{
|
|
169
174
|
id: 'orphans',
|
|
170
175
|
ok: orphans.length === 0,
|
|
171
176
|
label: '无孤儿页',
|
|
172
177
|
detail: orphans.length === 0 ? '每页都在 index 里' : `${orphans.length} 页未收录:${orphans.slice(0, 3).join('、')}${orphans.length > 3 ? '…' : ''}`,
|
|
178
|
+
data: { count: orphans.length, sample: orphans.slice(0, 3) },
|
|
173
179
|
},
|
|
174
180
|
{
|
|
175
181
|
id: 'frontmatter',
|
|
@@ -178,12 +184,14 @@ export function collectInsights(memoryDir) {
|
|
|
178
184
|
detail: missingSalience === 0 && missingType === 0
|
|
179
185
|
? 'title/type/salience 齐全'
|
|
180
186
|
: `缺 salience ${missingSalience} 页 / 缺 type ${missingType} 页`,
|
|
187
|
+
data: { missingSalience, missingType },
|
|
181
188
|
},
|
|
182
189
|
{
|
|
183
190
|
id: 'freshness',
|
|
184
191
|
ok: atRisk === 0,
|
|
185
192
|
label: '访问新鲜度',
|
|
186
193
|
detail: atRisk === 0 ? '没有超过 90 天未访问的页' : `${atRisk} 页陈旧或从未戳记`,
|
|
194
|
+
data: { atRisk },
|
|
187
195
|
},
|
|
188
196
|
]
|
|
189
197
|
|
|
@@ -217,6 +225,11 @@ export function collectInsights(memoryDir) {
|
|
|
217
225
|
})()
|
|
218
226
|
const newest = pages.reduce((max, p) => Math.max(max, p.mtimeMs), 0)
|
|
219
227
|
const recent = readRecentLog(memoryDir, 5)
|
|
228
|
+
// Type distribution, locale-neutral: `type` is the machine key a client
|
|
229
|
+
// translates, `label` stays the Chinese display string for CLI consumers.
|
|
230
|
+
const typeCounts = [...byType.entries()]
|
|
231
|
+
.map(([type, count]) => ({ type, label: TYPE_LABELS[type] ?? type, count }))
|
|
232
|
+
.sort((a, b) => b.count - a.count)
|
|
220
233
|
|
|
221
234
|
return {
|
|
222
235
|
generatedAt: new Date().toISOString(),
|
|
@@ -234,9 +247,10 @@ export function collectInsights(memoryDir) {
|
|
|
234
247
|
lastWrite: newest > 0 ? new Date(newest).toISOString() : null,
|
|
235
248
|
neverAccessed: never,
|
|
236
249
|
},
|
|
237
|
-
byType:
|
|
238
|
-
|
|
239
|
-
|
|
250
|
+
byType: typeCounts.map((row) => ({ ...row })),
|
|
251
|
+
// Additive alias of `byType` (same rows, same order), documented so a
|
|
252
|
+
// locale-aware client can read `typeCounts` without guessing field names.
|
|
253
|
+
typeCounts,
|
|
240
254
|
pages: pages.map((p) => ({
|
|
241
255
|
path: p.path,
|
|
242
256
|
title: p.title,
|
|
@@ -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
|
+
}
|