dsh-plugin-memory 0.5.2 → 0.7.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 +47 -0
- package/README.md +51 -12
- package/cordis.patch.yml +3 -2
- package/lib/activity-tracker.js +115 -0
- package/lib/boot.js +101 -7
- package/lib/client.js +665 -2
- package/lib/config-store.js +7 -1
- package/lib/digest-guard.js +44 -4
- package/lib/graph-drag.js +100 -0
- package/lib/graph-layout.js +137 -0
- package/lib/graph-view.js +98 -0
- package/lib/graph.js +249 -0
- package/lib/index-page.js +399 -0
- package/lib/index.js +171 -7
- package/lib/insights.js +263 -0
- package/lib/pages.js +197 -0
- package/lib/recall-nudge.js +14 -1
- package/lib/scaffold.js +11 -5
- package/lib/schema.js +4 -0
- package/lib/types/index.d.ts +121 -5
- package/package.json +1 -1
- package/scripts/memory.mjs +123 -7
- package/skills/memory.md +4 -4
package/lib/pages.js
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Page-reference bookkeeping: which memory pages a session actually loaded,
|
|
3
|
+
* and how to mark them as accessed.
|
|
4
|
+
*
|
|
5
|
+
* The salience/decay rules in `MEMORY.md` only work if `last_access` moves.
|
|
6
|
+
* Historically that field was honor-system: the template shipped it, the rules
|
|
7
|
+
* referenced it, and nothing ever wrote it — so every page aged in place and
|
|
8
|
+
* the decay table stayed fiction. This module closes that loop mechanically:
|
|
9
|
+
* whatever the boot block actually hands the model counts as an access, and
|
|
10
|
+
* its `last_access` is stamped once per session.
|
|
11
|
+
*
|
|
12
|
+
* Everything here is date-granular (a page is touched at most once per day)
|
|
13
|
+
* and conservative: pages without frontmatter are left alone rather than
|
|
14
|
+
* rewritten, and a missing store is simply a no-op.
|
|
15
|
+
*
|
|
16
|
+
* Depends only on `node:*` builtins so the standalone CLI can reuse it.
|
|
17
|
+
*
|
|
18
|
+
* @module dsh-plugin-memory/pages
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
|
|
22
|
+
import { join, relative, sep } from 'node:path'
|
|
23
|
+
|
|
24
|
+
/** Category directories a memory page may live under. */
|
|
25
|
+
export const PAGE_DIRS = [
|
|
26
|
+
'identity',
|
|
27
|
+
'user',
|
|
28
|
+
'skills',
|
|
29
|
+
'decisions',
|
|
30
|
+
'projects',
|
|
31
|
+
'concepts',
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
/** Today's date as `YYYY-MM-DD` (local time, matching the frontmatter convention). */
|
|
35
|
+
export function today() {
|
|
36
|
+
const now = new Date()
|
|
37
|
+
const pad = (n) => String(n).padStart(2, '0')
|
|
38
|
+
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Walk a store and return every markdown page path relative to the store root
|
|
43
|
+
* (meta files at the root are excluded — they are not "pages").
|
|
44
|
+
*
|
|
45
|
+
* @param {string} memoryDir absolute path of the memory store
|
|
46
|
+
* @param {string[]} [dirs] directories to walk (defaults to {@link PAGE_DIRS})
|
|
47
|
+
* @returns {string[]} store-relative paths using `/` separators
|
|
48
|
+
*/
|
|
49
|
+
export function listPagePaths(memoryDir, dirs = PAGE_DIRS) {
|
|
50
|
+
const out = []
|
|
51
|
+
const walk = (dir) => {
|
|
52
|
+
if (!existsSync(dir)) return
|
|
53
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
54
|
+
if (entry.name === '.git' || entry.name.startsWith('.')) continue
|
|
55
|
+
const path = join(dir, entry.name)
|
|
56
|
+
if (entry.isDirectory()) walk(path)
|
|
57
|
+
else if (entry.name.endsWith('.md')) out.push(relative(memoryDir, path).split(sep).join('/'))
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
for (const dir of dirs) walk(join(memoryDir, dir))
|
|
61
|
+
return out
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Extract the memory pages a rendered boot block refers to.
|
|
66
|
+
*
|
|
67
|
+
* Only references that (a) look like a store-relative markdown path and
|
|
68
|
+
* (b) resolve to a real file are returned, so prose like `SOUL.md` or a
|
|
69
|
+
* placeholder `xxx.md` never becomes a phantom access. Paths are matched in
|
|
70
|
+
* the three forms the boot block actually produces: bare
|
|
71
|
+
* (`user/profile.md`), backticked (`` `decisions/foo.md` ``) and linked
|
|
72
|
+
* (`[x](user/profile.md)`).
|
|
73
|
+
*
|
|
74
|
+
* @param {string} text the rendered boot block
|
|
75
|
+
* @param {string} memoryDir absolute path of the memory store
|
|
76
|
+
* @param {string[]} [dirs] directories a page may live under
|
|
77
|
+
* @returns {string[]} de-duplicated store-relative page paths, in first-seen order
|
|
78
|
+
*/
|
|
79
|
+
export function extractReferencedPages(text, memoryDir, dirs = PAGE_DIRS) {
|
|
80
|
+
if (typeof text !== 'string' || text.length === 0) return []
|
|
81
|
+
const known = new Set(listPagePaths(memoryDir, dirs))
|
|
82
|
+
if (known.size === 0) return []
|
|
83
|
+
const pattern = /([A-Za-z0-9_-]+(?:\/[A-Za-z0-9_.-]+)*\.md)\b/g
|
|
84
|
+
const seen = new Set()
|
|
85
|
+
const found = []
|
|
86
|
+
for (const match of text.matchAll(pattern)) {
|
|
87
|
+
const candidate = match[1]
|
|
88
|
+
if (!known.has(candidate) || seen.has(candidate)) continue
|
|
89
|
+
seen.add(candidate)
|
|
90
|
+
found.push(candidate)
|
|
91
|
+
}
|
|
92
|
+
return found
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Rewrite one page's `last_access` to `date` when it actually differs.
|
|
97
|
+
* Keeps every other byte of the file intact.
|
|
98
|
+
*
|
|
99
|
+
* @param {string} filePath absolute path of the page
|
|
100
|
+
* @param {string} [date] `YYYY-MM-DD` (defaults to today)
|
|
101
|
+
* @returns {boolean} true when the file was rewritten
|
|
102
|
+
*/
|
|
103
|
+
export function touchPageFile(filePath, date = today()) {
|
|
104
|
+
if (!existsSync(filePath)) return false
|
|
105
|
+
let text
|
|
106
|
+
try {
|
|
107
|
+
text = readFileSync(filePath, 'utf8')
|
|
108
|
+
} catch {
|
|
109
|
+
return false
|
|
110
|
+
}
|
|
111
|
+
const match = /^last_access:.*$/m.exec(text)
|
|
112
|
+
// No `last_access` line: leave the page alone rather than inventing
|
|
113
|
+
// frontmatter the author did not write.
|
|
114
|
+
if (match === null) return false
|
|
115
|
+
if (match[0] === `last_access: ${date}`) return false
|
|
116
|
+
const next = text.slice(0, match.index) + `last_access: ${date}` + text.slice(match.index + match[0].length)
|
|
117
|
+
try {
|
|
118
|
+
writeFileSync(filePath, next, 'utf8')
|
|
119
|
+
} catch {
|
|
120
|
+
return false
|
|
121
|
+
}
|
|
122
|
+
return true
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Stamp `last_access` on the given store-relative pages.
|
|
127
|
+
*
|
|
128
|
+
* @param {string} memoryDir absolute path of the memory store
|
|
129
|
+
* @param {string[]} paths store-relative page paths
|
|
130
|
+
* @param {{ date?: string, dirs?: string[] }} [options]
|
|
131
|
+
* @returns {string[]} the relative paths that were actually rewritten
|
|
132
|
+
*/
|
|
133
|
+
export function touchPages(memoryDir, paths, options = {}) {
|
|
134
|
+
const date = options.date ?? today()
|
|
135
|
+
const allowed = new Set(listPagePaths(memoryDir, options.dirs ?? PAGE_DIRS))
|
|
136
|
+
const touched = []
|
|
137
|
+
for (const path of Array.isArray(paths) ? paths : []) {
|
|
138
|
+
if (typeof path !== 'string' || !allowed.has(path)) continue
|
|
139
|
+
if (touchPageFile(join(memoryDir, path), date)) touched.push(path)
|
|
140
|
+
}
|
|
141
|
+
return touched
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Parse `last_access` out of page text (frontmatter only, by convention the
|
|
146
|
+
* first such line). Returns `undefined` when absent.
|
|
147
|
+
* @param {string} text page content
|
|
148
|
+
* @returns {string | undefined}
|
|
149
|
+
*/
|
|
150
|
+
export function readLastAccess(text) {
|
|
151
|
+
const match = /^last_access:\s*(\S+)/m.exec(text ?? '')
|
|
152
|
+
return match ? match[1] : undefined
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Store-wide access summary, used by the CLI `status` command: how many pages
|
|
157
|
+
* are stale (older than `staleDays`, or never stamped), and the oldest stamp.
|
|
158
|
+
*
|
|
159
|
+
* @param {string} memoryDir absolute path of the memory store
|
|
160
|
+
* @param {{ staleDays?: number, now?: Date }} [options]
|
|
161
|
+
* @returns {{ total: number, missing: number, stale: string[], oldest?: { path: string, lastAccess: string } }}
|
|
162
|
+
*/
|
|
163
|
+
export function accessSummary(memoryDir, options = {}) {
|
|
164
|
+
const staleDays = Math.max(1, Number(options.staleDays ?? 90))
|
|
165
|
+
const now = options.now ?? new Date()
|
|
166
|
+
const cutoff = now.getTime() - staleDays * 86400000
|
|
167
|
+
const paths = listPagePaths(memoryDir)
|
|
168
|
+
let missing = 0
|
|
169
|
+
let oldest
|
|
170
|
+
const stale = []
|
|
171
|
+
for (const path of paths) {
|
|
172
|
+
const abs = join(memoryDir, path)
|
|
173
|
+
const lastAccess = readLastAccess(readFileSync(abs, 'utf8'))
|
|
174
|
+
if (!lastAccess) {
|
|
175
|
+
missing += 1
|
|
176
|
+
stale.push(path)
|
|
177
|
+
continue
|
|
178
|
+
}
|
|
179
|
+
const at = Date.parse(`${lastAccess}T00:00:00`)
|
|
180
|
+
if (Number.isNaN(at)) {
|
|
181
|
+
stale.push(path)
|
|
182
|
+
continue
|
|
183
|
+
}
|
|
184
|
+
if (at < cutoff) stale.push(path)
|
|
185
|
+
if (oldest === undefined || at < Date.parse(`${oldest.lastAccess}T00:00:00`)) oldest = { path, lastAccess }
|
|
186
|
+
}
|
|
187
|
+
return { total: paths.length, missing, stale, oldest }
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** @returns {number} mtime (ms) of a path, 0 when it does not exist */
|
|
191
|
+
export function mtimeOf(path) {
|
|
192
|
+
try {
|
|
193
|
+
return statSync(path).mtimeMs
|
|
194
|
+
} catch {
|
|
195
|
+
return 0
|
|
196
|
+
}
|
|
197
|
+
}
|
package/lib/recall-nudge.js
CHANGED
|
@@ -98,9 +98,10 @@ export function buildRecallNudgeMessage(candidates) {
|
|
|
98
98
|
|
|
99
99
|
/**
|
|
100
100
|
* @typedef {object} RecallNudgeOptions
|
|
101
|
-
* @property {() => { enabled: boolean, minMinutes: number, maxMinutes: number, maxPerSession: number }} readConfig
|
|
101
|
+
* @property {() => { enabled: boolean, minMinutes: number, maxMinutes: number, maxPerSession: number, deferUntilUserSpeaks?: boolean, activeSessionOnly?: boolean }} readConfig
|
|
102
102
|
* @property {() => string} getMemoryDir resolve the current store dir on every check
|
|
103
103
|
* @property {unknown} [agents] optional live-agent registry for liveness checks
|
|
104
|
+
* @property {import('./activity-tracker.js').ActivityTracker} [tracker] gate source: has-user-spoken + active-session
|
|
104
105
|
* @property {{ info?: Function, warn?: Function }} [logger]
|
|
105
106
|
*/
|
|
106
107
|
|
|
@@ -119,12 +120,15 @@ export class RecallNudge {
|
|
|
119
120
|
this.readConfig = options.readConfig
|
|
120
121
|
this.getMemoryDir = options.getMemoryDir
|
|
121
122
|
this.agents = options.agents
|
|
123
|
+
this.tracker = options.tracker
|
|
122
124
|
this.logger = options.logger
|
|
123
125
|
this.pollIntervalMs = options.pollIntervalMs ?? POLL_INTERVAL_MS
|
|
124
126
|
this.disposed = false
|
|
125
127
|
this.stopTurnStopping = undefined
|
|
126
128
|
this.timer = undefined
|
|
127
129
|
this.recalls = 0
|
|
130
|
+
// 0 = "not armed yet": the first eligible idle moment arms the interval so
|
|
131
|
+
// the first recall never fires instantly after the user's first turn.
|
|
128
132
|
this.nextRecallAt = 0
|
|
129
133
|
}
|
|
130
134
|
|
|
@@ -173,12 +177,21 @@ export class RecallNudge {
|
|
|
173
177
|
}
|
|
174
178
|
const config = this.readConfig()
|
|
175
179
|
if (!config.enabled) return
|
|
180
|
+
// Both gates: don't recall before the user has spoken, and only for the
|
|
181
|
+
// currently active session (most recent user message).
|
|
182
|
+
if (this.tracker && !this.tracker.shouldInject(this.agent.id, config)) return
|
|
176
183
|
if (this.recalls >= Math.max(1, Number(config.maxPerSession ?? 3))) return
|
|
177
184
|
if (this.agent.status !== 'idle') return
|
|
178
185
|
const inbox = this.agent.inbox
|
|
179
186
|
if (inbox && Array.isArray(inbox.nextStep) && inbox.nextStep.length > 0) return
|
|
180
187
|
|
|
181
188
|
const now = Date.now()
|
|
189
|
+
if (this.nextRecallAt === 0) {
|
|
190
|
+
// First eligible idle moment: arm the interval from here instead of
|
|
191
|
+
// firing instantly (the pre-gate bug). Returns so the next check honors it.
|
|
192
|
+
this.nextRecallAt = now + randomIntervalMs(config.minMinutes, config.maxMinutes)
|
|
193
|
+
return
|
|
194
|
+
}
|
|
182
195
|
if (now < this.nextRecallAt) return
|
|
183
196
|
|
|
184
197
|
const candidates = listRecallCandidates(this.getMemoryDir(), 3)
|
package/lib/scaffold.js
CHANGED
|
@@ -81,7 +81,7 @@ export const MEMORY_TEMPLATE = `# MEMORY — 记忆库 schema 与维护协议
|
|
|
81
81
|
| \`SOUL.md\` | 人格(用户主导) | 我是谁、性格、价值观、沟通风格、与用户的关系、边界 |
|
|
82
82
|
| \`BOOTSTRAP.md\` | 铸魂清单 | 安装后灵魂定义/身份确认的进度;complete 前优先于常规任务 |
|
|
83
83
|
| \`MEMORY.md\` | schema(本文件) | 目录、分级、衰减、遗忘、迁移、工作流 |
|
|
84
|
-
| \`index.md\` | 内容目录 |
|
|
84
|
+
| \`index.md\` | 内容目录 | **路由表**:每页一行 —— 链接 + 一句话摘要(≤ 80 字)+ \`salience\` 标记。长内容留在页面里 |
|
|
85
85
|
| \`log.md\` | 时间线 | append-only,每条 \`## [YYYY-MM-DD] <kind> \\| <title>\`,可 grep 解析 |
|
|
86
86
|
| \`identity/\` | 自我 | agent 的持久自我认知、能力边界、工作方式 |
|
|
87
87
|
| \`user/\` | 关于用户 | profile(稳定事实)、preferences(偏好/风格) |
|
|
@@ -134,6 +134,9 @@ sources: [] # 指向 raw/ 或外部
|
|
|
134
134
|
|
|
135
135
|
- 页面用**相对 markdown 链接**互相引用。
|
|
136
136
|
- 新信息与旧声明矛盾时:改旧页、在新页标注、\`log.md\` 记变更。
|
|
137
|
+
- \`last_access\` 由插件**自动维护**:会话启动时把 boot 块实际引用的页面戳为当天,也可用 \`dsh-memory touch <pages...>\` 手动补记。写页时保持该字段存在即可,不必逐日手改。
|
|
138
|
+
- \`index.md\` 是**路由表**:一行一页、一句话摘要,不写状态流水。它会被完整注入会话,膨胀的代价是挤掉其他记忆——一行写不下,就说明该拆页或该把细节移进正文。
|
|
139
|
+
- 每个页面用 frontmatter \`summary:\` 声明一句话摘要(≤ 100 字)——index 行由它派生,\`dsh-memory index --write\` 负责同步,\`--sync-frontmatter\` 可把已写在 index 里的摘要回填到页面。
|
|
137
140
|
|
|
138
141
|
## 迁移协议
|
|
139
142
|
|
|
@@ -151,8 +154,11 @@ sources: [] # 指向 raw/ 或外部
|
|
|
151
154
|
|
|
152
155
|
export const INDEX_TEMPLATE = `# Memory Index
|
|
153
156
|
|
|
154
|
-
>
|
|
155
|
-
>
|
|
157
|
+
> 内容目录 / 路由表:**每页一行** —— 链接 + 一句话摘要(≤ 80 字)+ \`salience\` 标记。**每次 remember 都要同步更新本文件。**
|
|
158
|
+
> 查询时先读本文件定位,再钻具体页。这是**路由表而不是摘要表**:细节留在页面里,index 只负责让人知道「有这一页、值不值得点进去」。
|
|
159
|
+
|
|
160
|
+
> 长度自律:一行一句话。写不下就说明该拆页,或该把细节放进页面正文——不要把状态、进度、复述塞进 index。
|
|
161
|
+
> **摘要来源**:index 行由页面的 frontmatter \`summary:\` 派生(\`dsh-memory index --write\` 自动重写),不要在这里手写散文——手写的会漂移。
|
|
156
162
|
|
|
157
163
|
## 元记忆
|
|
158
164
|
|
|
@@ -190,9 +196,9 @@ export const LOG_TEMPLATE = `# Memory Log
|
|
|
190
196
|
|
|
191
197
|
> append-only 时间线。每条:\`## [YYYY-MM-DD] <kind> | <title>\`,可 \`grep '^## \\[' log.md\` 解析。
|
|
192
198
|
|
|
193
|
-
|
|
199
|
+
_(还没有动态。第一条真实条目由首次 digest 追加,格式如下:)_
|
|
194
200
|
|
|
195
|
-
-
|
|
201
|
+
> ## [YYYY-MM-DD] install | dsh-plugin-memory 初始化
|
|
196
202
|
`
|
|
197
203
|
|
|
198
204
|
export const BOOTSTRAP_TEMPLATE = `---
|
package/lib/schema.js
CHANGED
|
@@ -15,6 +15,10 @@ export const SettingsSchema = z.object({
|
|
|
15
15
|
memoryDir: z.string().default('~/.memory'),
|
|
16
16
|
autoInject: z.boolean().default(true),
|
|
17
17
|
registerSkill: z.boolean().default(true),
|
|
18
|
+
// Gate 1: don't inject anything until the session's first real user message.
|
|
19
|
+
deferUntilUserSpeaks: z.boolean().default(true),
|
|
20
|
+
// Gate 2: only the currently active session (most recent user message) injects.
|
|
21
|
+
activeSessionOnly: z.boolean().default(true),
|
|
18
22
|
recallEnabled: z.boolean().default(true),
|
|
19
23
|
recallIntervalMinMinutes: z.number().default(30),
|
|
20
24
|
recallIntervalMaxMinutes: z.number().default(240),
|
package/lib/types/index.d.ts
CHANGED
|
@@ -8,9 +8,8 @@ import type { Context } from '@deepseek-ai/cordis'
|
|
|
8
8
|
|
|
9
9
|
/** Plugin entry name. */
|
|
10
10
|
export const name: 'memory'
|
|
11
|
-
|
|
12
11
|
/** Services required by the plugin. */
|
|
13
|
-
export const inject: ['systemPrompt', 'skills']
|
|
12
|
+
export const inject: ['systemPrompt', 'skills', 'agents']
|
|
14
13
|
|
|
15
14
|
/** User-facing plugin configuration (all fields optional). */
|
|
16
15
|
export interface MemoryConfig {
|
|
@@ -20,10 +19,22 @@ export interface MemoryConfig {
|
|
|
20
19
|
memoryDir?: string
|
|
21
20
|
/** Files injected at session start. Default `['SOUL.md', 'MEMORY.md', 'index.md']`. */
|
|
22
21
|
bootFiles?: string[]
|
|
23
|
-
/** Total character budget of the boot block. Default `
|
|
22
|
+
/** Total character budget of the boot block. Default `12000`. */
|
|
24
23
|
bootMaxChars?: number
|
|
24
|
+
/**
|
|
25
|
+
* Explicit per-file character caps for the boot block (composition-time
|
|
26
|
+
* only). Files without a cap share what is left, with `index.md` taking its
|
|
27
|
+
* share first so the routing table is never starved.
|
|
28
|
+
*/
|
|
29
|
+
bootFileBudgets?: Record<string, number>
|
|
30
|
+
/** Stamp `last_access` on the pages a session actually loaded. Default `true`. */
|
|
31
|
+
trackPageAccess?: boolean
|
|
25
32
|
/** Inject the boot block at session start. Default `true`. */
|
|
26
33
|
autoInject?: boolean
|
|
34
|
+
/** Don't inject anything until the session's first real user message. Default `true`. */
|
|
35
|
+
deferUntilUserSpeaks?: boolean
|
|
36
|
+
/** Only inject for the currently active session (most recent user message). Default `true`. */
|
|
37
|
+
activeSessionOnly?: boolean
|
|
27
38
|
/** Register the embedded `memory` skill. Default `true`. */
|
|
28
39
|
registerSkill?: boolean
|
|
29
40
|
/** Create the store layout and templates when missing. Default `true`. */
|
|
@@ -60,11 +71,16 @@ export const Config: import('@deepseek-ai/schemastery').default<MemoryConfig>
|
|
|
60
71
|
/** HTTP route serving the user-facing config to the Settings panel. */
|
|
61
72
|
export const CONFIG_ROUTE_PATH: '/api/memory/config'
|
|
62
73
|
|
|
74
|
+
/** Read-only HTTP route serving the memory-health dashboard payload. */
|
|
75
|
+
export const INSIGHTS_ROUTE_PATH: '/api/memory/insights'
|
|
76
|
+
|
|
63
77
|
/** User-editable settings (composition config is the base layer). */
|
|
64
78
|
export interface MemorySettings {
|
|
65
79
|
enabled?: boolean
|
|
66
80
|
memoryDir?: string
|
|
67
81
|
autoInject?: boolean
|
|
82
|
+
deferUntilUserSpeaks?: boolean
|
|
83
|
+
activeSessionOnly?: boolean
|
|
68
84
|
registerSkill?: boolean
|
|
69
85
|
recallEnabled?: boolean
|
|
70
86
|
recallIntervalMinMinutes?: number
|
|
@@ -94,7 +110,7 @@ export function resolveMemoryDir(dir: string): string
|
|
|
94
110
|
export interface MemoryPlugin {
|
|
95
111
|
(ctx: Context, config?: MemoryConfig): () => void
|
|
96
112
|
readonly name: 'memory'
|
|
97
|
-
readonly inject: ['systemPrompt', 'skills']
|
|
113
|
+
readonly inject: ['systemPrompt', 'skills', 'agents']
|
|
98
114
|
readonly Config: import('@deepseek-ai/schemastery').default<MemoryConfig>
|
|
99
115
|
}
|
|
100
116
|
|
|
@@ -108,8 +124,108 @@ export default plugin
|
|
|
108
124
|
/** Render the boot memory block injected at session start. */
|
|
109
125
|
export function renderBootBlock(
|
|
110
126
|
memoryDir: string,
|
|
111
|
-
options?: {
|
|
127
|
+
options?: {
|
|
128
|
+
bootFiles?: string[]
|
|
129
|
+
bootMaxChars?: number
|
|
130
|
+
bootFileBudgets?: Record<string, number>
|
|
131
|
+
},
|
|
112
132
|
): string
|
|
113
133
|
|
|
134
|
+
/** Files injected at session start when the config does not override them. */
|
|
135
|
+
export const DEFAULT_BOOT_FILES: string[]
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Split the boot budget across the injected files: explicit per-file caps
|
|
139
|
+
* first, then `index.md`'s share, then an even split, each clamped to the
|
|
140
|
+
* file's real size.
|
|
141
|
+
*/
|
|
142
|
+
export function allocateBootBudget(
|
|
143
|
+
memoryDir: string,
|
|
144
|
+
options?: {
|
|
145
|
+
files?: string[]
|
|
146
|
+
total?: number
|
|
147
|
+
perFile?: Record<string, number>
|
|
148
|
+
},
|
|
149
|
+
): Map<string, number>
|
|
150
|
+
|
|
151
|
+
/** Walk a store and return every page path relative to its root. */
|
|
152
|
+
export function listPagePaths(memoryDir: string, dirs?: string[]): string[]
|
|
153
|
+
|
|
154
|
+
/** Extract the real, store-relative pages a rendered boot block refers to. */
|
|
155
|
+
export function extractReferencedPages(text: string, memoryDir: string, dirs?: string[]): string[]
|
|
156
|
+
|
|
157
|
+
/** Stamp `last_access` (`YYYY-MM-DD`, today by default) on the given pages. */
|
|
158
|
+
export function touchPages(
|
|
159
|
+
memoryDir: string,
|
|
160
|
+
paths: string[],
|
|
161
|
+
options?: { date?: string; dirs?: string[] },
|
|
162
|
+
): string[]
|
|
163
|
+
|
|
164
|
+
/** Rewrite one page's `last_access` when it differs. Returns true when written. */
|
|
165
|
+
export function touchPageFile(filePath: string, date?: string): boolean
|
|
166
|
+
|
|
167
|
+
/** Today as `YYYY-MM-DD` (local time). */
|
|
168
|
+
export function today(): string
|
|
169
|
+
|
|
170
|
+
/** Store-wide `last_access` summary used by `dsh-memory status`. */
|
|
171
|
+
export function accessSummary(
|
|
172
|
+
memoryDir: string,
|
|
173
|
+
options?: { staleDays?: number; now?: Date },
|
|
174
|
+
): { total: number; missing: number; stale: string[]; oldest?: { path: string; lastAccess: string } }
|
|
175
|
+
|
|
114
176
|
/** Create the memory-store layout if missing. Returns created paths. */
|
|
115
177
|
export function ensureMemoryScaffold(memoryDir: string): string[]
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Per-agent activity tracker behind the two polite-injection gates
|
|
181
|
+
* (`deferUntilUserSpeaks` + `activeSessionOnly`).
|
|
182
|
+
*/
|
|
183
|
+
export class ActivityTracker {
|
|
184
|
+
constructor(options?: { agents?: unknown; logger?: unknown })
|
|
185
|
+
attach(agent: unknown): void
|
|
186
|
+
noteUserMessage(id: string): void
|
|
187
|
+
detach(id: string): void
|
|
188
|
+
hasUserSpoken(id: string): boolean
|
|
189
|
+
isActive(id: string): boolean
|
|
190
|
+
shouldInject(id: string, config?: { deferUntilUserSpeaks?: boolean; activeSessionOnly?: boolean }): boolean
|
|
191
|
+
dispose(): void
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Memory-health dashboard payload (read-only, computed per request). */
|
|
195
|
+
export interface MemoryInsights {
|
|
196
|
+
generatedAt: string
|
|
197
|
+
store: string
|
|
198
|
+
overview: {
|
|
199
|
+
pages: number
|
|
200
|
+
chars: number
|
|
201
|
+
bytes: number
|
|
202
|
+
indexEntries: number
|
|
203
|
+
indexBytes: number
|
|
204
|
+
logBytes: number
|
|
205
|
+
lastWrite: string | null
|
|
206
|
+
neverAccessed: number
|
|
207
|
+
}
|
|
208
|
+
byType: Array<{ type: string, label: string, count: number }>
|
|
209
|
+
bySalience: Array<{ level: 1 | 2 | 3, count: number }>
|
|
210
|
+
freshness: {
|
|
211
|
+
buckets: Array<{ key: string, label: string, count: number }>
|
|
212
|
+
never: number
|
|
213
|
+
}
|
|
214
|
+
stalePages: Array<{
|
|
215
|
+
path: string
|
|
216
|
+
title: string
|
|
217
|
+
salience?: number
|
|
218
|
+
daysSinceAccess: number | null
|
|
219
|
+
}>
|
|
220
|
+
recent: string[]
|
|
221
|
+
health: {
|
|
222
|
+
score: number
|
|
223
|
+
checks: Array<{ id: string, ok: boolean, label: string, detail: string }>
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Build the dashboard payload from the store on disk (never writes). */
|
|
228
|
+
export function collectInsights(memoryDir: string): MemoryInsights
|
|
229
|
+
|
|
230
|
+
/** Newest-first `log.md` headlines for the dashboard. */
|
|
231
|
+
export function readRecentLog(memoryDir: string, count?: number): 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.7.0",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "lib/index.js",
|
package/scripts/memory.mjs
CHANGED
|
@@ -4,9 +4,12 @@
|
|
|
4
4
|
*
|
|
5
5
|
* Usage:
|
|
6
6
|
* dsh-memory init [dir] # create the store scaffold (default $MEMORY_DIR or ~/.memory)
|
|
7
|
-
* dsh-memory search <query>
|
|
7
|
+
* dsh-memory search <query> [--touch] # full-text search; --touch stamps last_access on the hits
|
|
8
|
+
* dsh-memory touch [pages...] # stamp last_access (all pages when none given)
|
|
9
|
+
* dsh-memory index [--check|--write|--sync-frontmatter]
|
|
10
|
+
* # index routing table: drift / rewrite / import summaries
|
|
8
11
|
* dsh-memory lint # integrity check (index vs files, orphans, log format)
|
|
9
|
-
* dsh-memory status # health summary (page counts, sizes, last modified)
|
|
12
|
+
* dsh-memory status # health summary (page counts, sizes, staleness, last modified)
|
|
10
13
|
* dsh-memory pack [out.tar.gz] # export a portable archive + manifest
|
|
11
14
|
* dsh-memory unpack <archive> [--force] # restore from an archive
|
|
12
15
|
* dsh-memory --self-test # run a temp-dir round-trip test (npm test)
|
|
@@ -22,6 +25,8 @@ import { execFileSync } from 'node:child_process'
|
|
|
22
25
|
import { tmpdir, homedir } from 'node:os'
|
|
23
26
|
import { createHash } from 'node:crypto'
|
|
24
27
|
import { ensureMemoryScaffold } from '../lib/scaffold.js'
|
|
28
|
+
import { touchPages, accessSummary, today } from '../lib/pages.js'
|
|
29
|
+
import { planIndex, applyIndex, indexIssues, syncDeclaredSummaries, INDEX_LINE_MAX } from '../lib/index-page.js'
|
|
25
30
|
|
|
26
31
|
const META = new Set(['SOUL.md', 'MEMORY.md', 'BOOTSTRAP.md', 'index.md', 'log.md'])
|
|
27
32
|
|
|
@@ -74,17 +79,110 @@ function cmdInit(store, args) {
|
|
|
74
79
|
: `store already present: ${store} (nothing created; existing files never overwritten)`)
|
|
75
80
|
}
|
|
76
81
|
|
|
77
|
-
function cmdSearch(store, query) {
|
|
82
|
+
function cmdSearch(store, query, touch = false) {
|
|
78
83
|
if (!query) fail('search needs a query')
|
|
79
84
|
const q = query.toLowerCase()
|
|
80
85
|
const hits = []
|
|
86
|
+
const hitPages = []
|
|
81
87
|
for (const f of walk(store).filter((x) => x.endsWith('.md'))) {
|
|
82
88
|
const text = readFileSync(f, 'utf8')
|
|
83
89
|
for (const [i, line] of text.split('\n').entries()) {
|
|
84
|
-
if (line.toLowerCase().includes(q))
|
|
90
|
+
if (line.toLowerCase().includes(q)) {
|
|
91
|
+
hits.push(`${relative(store, f)}:${i + 1}: ${line.trim().slice(0, 200)}`)
|
|
92
|
+
const rel = relative(store, f)
|
|
93
|
+
if (!META.has(basename(rel)) && !hitPages.includes(rel)) hitPages.push(rel)
|
|
94
|
+
}
|
|
85
95
|
}
|
|
86
96
|
}
|
|
87
97
|
console.log(hits.length ? hits.join('\n') : `no matches for "${query}"`)
|
|
98
|
+
if (touch && hitPages.length > 0) {
|
|
99
|
+
const stamped = touchPages(store, hitPages)
|
|
100
|
+
console.log(`— last_access ${today()} stamped on ${stamped.length} page(s)`)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Stamp `last_access` on pages. With no arguments, touch every page — the
|
|
106
|
+
* "I just read through the store" case; with arguments, only the named ones.
|
|
107
|
+
*/
|
|
108
|
+
function cmdTouch(store, args) {
|
|
109
|
+
const all = pages(store)
|
|
110
|
+
const requested = args.filter((a) => !a.startsWith('-'))
|
|
111
|
+
const targets = requested.length > 0 ? requested : all
|
|
112
|
+
const unknown = requested.filter((p) => !all.includes(p))
|
|
113
|
+
const stamped = touchPages(store, targets)
|
|
114
|
+
console.log(`stamped last_access ${today()} on ${stamped.length}/${targets.length} page(s)`)
|
|
115
|
+
if (unknown.length > 0) console.log(`skipped (not a page): ${unknown.join(', ')}`)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Index compiler: report drift (default / `--check`) or rewrite the stale lines
|
|
120
|
+
* (`--write`). Only existing entry lines are rewritten — sections, order and
|
|
121
|
+
* unmentioned pages are left for the agent to decide.
|
|
122
|
+
*/
|
|
123
|
+
function cmdIndex(store, args) {
|
|
124
|
+
const plan = planIndex(store)
|
|
125
|
+
const write = args.includes('--write')
|
|
126
|
+
const check = args.includes('--check')
|
|
127
|
+
const sync = args.includes('--sync-frontmatter') || args.includes('--sync')
|
|
128
|
+
const overlong = plan.lines.filter((l) => l.current.length > INDEX_LINE_MAX).length
|
|
129
|
+
const stale = plan.lines.filter((l) => l.changed)
|
|
130
|
+
const noSummary = plan.lines.filter((l) => l.summary.length === 0)
|
|
131
|
+
|
|
132
|
+
if (sync) {
|
|
133
|
+
// One-shot migration: whatever summary already lives in the index moves into
|
|
134
|
+
// the page's frontmatter, after which the index is pure projection.
|
|
135
|
+
const result = syncDeclaredSummaries(store, plan)
|
|
136
|
+
console.log(`index: synced ${result.synced.length} summary declaration(s) into frontmatter`
|
|
137
|
+
+ (result.skipped.length > 0 ? `, skipped ${result.skipped.length}` : ''))
|
|
138
|
+
for (const path of result.skipped.slice(0, 5)) console.log(` · skipped (no index summary to import): ${path}`)
|
|
139
|
+
return
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
if (write) {
|
|
143
|
+
const result = applyIndex(store, plan)
|
|
144
|
+
console.log(`index: rewrote ${result.written}/${plan.lines.length} line(s) `
|
|
145
|
+
+ `(${result.bytesBefore} → ${result.bytesAfter} bytes)`)
|
|
146
|
+
if (plan.missing.length > 0) {
|
|
147
|
+
console.log(`index: ${plan.missing.length} page(s) not listed — add them by hand (section + order are editorial):`)
|
|
148
|
+
for (const path of plan.missing) console.log(` + ${path}`)
|
|
149
|
+
}
|
|
150
|
+
if (plan.removed.length > 0) {
|
|
151
|
+
console.log(`index: ${plan.removed.length} stale link(s) — decide whether to delete the line: ${plan.removed.join(', ')}`)
|
|
152
|
+
}
|
|
153
|
+
if (noSummary.length > 0) {
|
|
154
|
+
console.log(`index: ${noSummary.length} page(s) declare no summary — the line shows the title only; `
|
|
155
|
+
+ 'add `summary:` to the page frontmatter and re-run')
|
|
156
|
+
}
|
|
157
|
+
return
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (check) {
|
|
161
|
+
console.log(`index: ${stale.length} stale / ${overlong} over-cap / ${noSummary.length} undeclared-summary `
|
|
162
|
+
+ `of ${plan.lines.length} line(s)`)
|
|
163
|
+
for (const line of plan.lines) console.log(` ${line.changed ? '~' : '·'} ${line.target}`)
|
|
164
|
+
for (const path of plan.missing) console.log(` + missing from index: ${path}`)
|
|
165
|
+
for (const path of plan.removed) console.log(` - stale link: ${path}`)
|
|
166
|
+
if (stale.length > 0 || plan.missing.length > 0 || plan.removed.length > 0) process.exit(1)
|
|
167
|
+
return
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
if (stale.length > 0) {
|
|
171
|
+
console.log(`index: ${stale.length} of ${plan.lines.length} line(s) need a rewrite`
|
|
172
|
+
+ (overlong > 0 ? `, ${overlong} over the ${INDEX_LINE_MAX}-char cap` : ''))
|
|
173
|
+
for (const line of stale.slice(0, 10)) console.log(` ~ ${line.target}`)
|
|
174
|
+
if (stale.length > 10) console.log(` … ${stale.length - 10} more`)
|
|
175
|
+
console.log('run `dsh-memory index --write` to rewrite them (sections and order are preserved)')
|
|
176
|
+
} else if (plan.lines.length > 0) {
|
|
177
|
+
console.log(`index: ${plan.lines.length} line(s) in sync with their pages`)
|
|
178
|
+
}
|
|
179
|
+
if (noSummary.length > 0) {
|
|
180
|
+
console.log(`index: ${noSummary.length} page(s) declare no summary (line shows title only): `
|
|
181
|
+
+ noSummary.slice(0, 5).map((l) => l.target).join(', ') + (noSummary.length > 5 ? ' …' : ''))
|
|
182
|
+
console.log(' hint: `dsh-memory index --sync-frontmatter` imports the summary already written in index.md')
|
|
183
|
+
}
|
|
184
|
+
for (const path of plan.missing) console.log(` + missing from index (add by hand): ${path}`)
|
|
185
|
+
for (const path of plan.removed) console.log(` - stale link (decide by hand): ${path}`)
|
|
88
186
|
}
|
|
89
187
|
|
|
90
188
|
function cmdLint(store) {
|
|
@@ -108,8 +206,17 @@ function cmdLint(store) {
|
|
|
108
206
|
problems.push(`${p}: salience must be 1|2|3, got "${fm.salience}"`)
|
|
109
207
|
}
|
|
110
208
|
}
|
|
209
|
+
// Routing-table discipline: a line that has drifted from its page, or grown
|
|
210
|
+
// past the cap, is a lint failure — not a style preference. The index is
|
|
211
|
+
// injected whole, so an overgrown line costs every session context.
|
|
212
|
+
for (const issue of indexIssues(store, { includeNoSummary: false })) {
|
|
213
|
+
if (issue.kind === 'missing' || issue.kind === 'removed') continue // already reported above
|
|
214
|
+
problems.push(issue.detail)
|
|
215
|
+
}
|
|
111
216
|
const log = readFileSync(join(store, 'log.md'), 'utf8')
|
|
112
|
-
|
|
217
|
+
// Quoted example lines (`> ## [...]`) are documentation, not entries.
|
|
218
|
+
const badLines = log.split('\n')
|
|
219
|
+
.filter((l) => l.startsWith('## ') && !/^## \[\d{4}-\d{2}-\d{2}\] /.test(l))
|
|
113
220
|
for (const l of badLines) problems.push(`log.md malformed entry: ${l}`)
|
|
114
221
|
console.log(problems.length ? problems.join('\n') : `ok — ${ps.length} pages, no problems found`)
|
|
115
222
|
process.exit(problems.length ? 1 : 0)
|
|
@@ -132,6 +239,10 @@ function cmdStatus(store) {
|
|
|
132
239
|
console.log(`by type: ${JSON.stringify(byType)}`)
|
|
133
240
|
console.log(`last modified: ${last ? new Date(last).toISOString() : 'n/a'}`)
|
|
134
241
|
console.log(`last log write: ${logMtime ? `${new Date(logMtime).toISOString()} (${Math.round((Date.now() - logMtime) / 60000)} min ago)` : 'n/a'}`)
|
|
242
|
+
const access = accessSummary(store)
|
|
243
|
+
const oldest = access.oldest ? `${access.oldest.lastAccess} (${access.oldest.path})` : 'n/a'
|
|
244
|
+
console.log(`stale pages (>90d or unstamped): ${access.stale.length}/${access.total}${access.missing > 0 ? ` (${access.missing} missing last_access)` : ''}`)
|
|
245
|
+
console.log(`oldest last_access: ${oldest}`)
|
|
135
246
|
}
|
|
136
247
|
|
|
137
248
|
function manifestFor(storePath) {
|
|
@@ -231,7 +342,10 @@ if (args[0] === '--self-test') {
|
|
|
231
342
|
} else {
|
|
232
343
|
const help = `dsh-memory — long-term memory CLI
|
|
233
344
|
init [dir] create the store scaffold
|
|
234
|
-
search <query>
|
|
345
|
+
search <query> [--touch] full-text search (--touch stamps last_access on hits)
|
|
346
|
+
touch [pages...] stamp last_access (all pages when none given)
|
|
347
|
+
index [--check|--write|--sync-frontmatter]
|
|
348
|
+
index routing table: report drift / rewrite / import summaries
|
|
235
349
|
lint integrity check
|
|
236
350
|
status health summary
|
|
237
351
|
pack [out.tar.gz] export portable archive + manifest
|
|
@@ -239,7 +353,9 @@ if (args[0] === '--self-test') {
|
|
|
239
353
|
Store: $MEMORY_DIR or ./.memory or ~/.memory (current: ${store})`
|
|
240
354
|
switch (args[0]) {
|
|
241
355
|
case 'init': cmdInit(store, args.slice(1)); break
|
|
242
|
-
case 'search': cmdSearch(store, args[1]); break
|
|
356
|
+
case 'search': cmdSearch(store, args[1], args.includes('--touch')); break
|
|
357
|
+
case 'touch': cmdTouch(store, args.slice(1)); break
|
|
358
|
+
case 'index': cmdIndex(store, args.slice(1)); break
|
|
243
359
|
case 'lint': cmdLint(store); break
|
|
244
360
|
case 'status': cmdStatus(store); break
|
|
245
361
|
case 'pack': cmdPack(store, args[1]); break
|