dsh-plugin-memory 0.6.0 → 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.
@@ -0,0 +1,263 @@
1
+ /**
2
+ * Memory insights: the data layer behind the "memory health" dashboard.
3
+ *
4
+ * Everything here is derived from what the store already contains — frontmatter,
5
+ * `last_access` stamps, `index.md` routing entries and `log.md` headlines — so
6
+ * the dashboard never needs a second source of truth and cannot disagree with
7
+ * `dsh-memory lint` / `status`. Read-only: building insights never writes a byte.
8
+ *
9
+ * Depends only on `node:*` builtins plus {@link ./pages.js}, so the standalone
10
+ * CLI can reuse it without the plugin's peer dependencies.
11
+ *
12
+ * @module dsh-plugin-memory/insights
13
+ */
14
+
15
+ import { existsSync, readFileSync, statSync } from 'node:fs'
16
+ import { basename, join } from 'node:path'
17
+ import { listPagePaths, readLastAccess, today } from './pages.js'
18
+
19
+ /** Type buckets shown on the dashboard, in display order. */
20
+ export const KNOWN_TYPES = ['identity', 'user', 'user-preference', 'project', 'skill', 'decision', 'concept', 'fact']
21
+
22
+ const TYPE_LABELS = {
23
+ identity: '自我',
24
+ user: '关于你',
25
+ 'user-preference': '偏好',
26
+ project: '项目',
27
+ skill: '程序性',
28
+ decision: '决策',
29
+ concept: '概念',
30
+ fact: '事实',
31
+ unknown: '未标注',
32
+ }
33
+
34
+ const FRESHNESS_BUCKETS = [
35
+ { key: 'today', label: '今天', maxDays: 0 },
36
+ { key: 'week', label: '≤7 天', maxDays: 7 },
37
+ { key: 'month', label: '≤30 天', maxDays: 30 },
38
+ { key: 'quarter', label: '≤90 天', maxDays: 90 },
39
+ { key: 'stale', label: '>90 天', maxDays: Infinity },
40
+ ]
41
+
42
+ /** Parse the frontmatter block into a flat key -> string map. */
43
+ export function parseFrontmatter(text) {
44
+ if (!text.startsWith('---')) return {}
45
+ const end = text.indexOf('\n---', 3)
46
+ if (end < 0) return {}
47
+ const fm = {}
48
+ for (const line of text.slice(3, end).split('\n')) {
49
+ const m = /^([A-Za-z_][\w-]*)\s*:\s*(.*)$/.exec(line)
50
+ if (m) fm[m[1]] = m[2].trim()
51
+ }
52
+ return fm
53
+ }
54
+
55
+ /** Whole-day distance between two `YYYY-MM-DD` stamps, or undefined. */
56
+ function daysBetween(from, to) {
57
+ const a = Date.parse(`${from}T00:00:00`)
58
+ const b = Date.parse(`${to}T00:00:00`)
59
+ if (Number.isNaN(a) || Number.isNaN(b)) return undefined
60
+ return Math.floor((b - a) / 86400000)
61
+ }
62
+
63
+ /** Read one page's frontmatter + size into a row for the dashboard. */
64
+ function readPage(memoryDir, rel) {
65
+ const abs = join(memoryDir, rel)
66
+ let text = ''
67
+ let bytes = 0
68
+ let mtimeMs = 0
69
+ try {
70
+ text = readFileSync(abs, 'utf8')
71
+ const stat = statSync(abs)
72
+ bytes = stat.size
73
+ mtimeMs = stat.mtimeMs
74
+ } catch {
75
+ return undefined
76
+ }
77
+ const fm = parseFrontmatter(text)
78
+ const salience = Number(fm.salience)
79
+ const lastAccess = readLastAccess(text)
80
+ return {
81
+ path: rel,
82
+ title: fm.title || basename(rel, '.md'),
83
+ type: fm.type || 'unknown',
84
+ typeLabel: TYPE_LABELS[fm.type] ?? fm.type ?? TYPE_LABELS.unknown,
85
+ salience: [1, 2, 3].includes(salience) ? salience : undefined,
86
+ lastAccess,
87
+ daysSinceAccess: lastAccess ? daysBetween(lastAccess, today()) : undefined,
88
+ bytes,
89
+ chars: text.length,
90
+ mtimeMs,
91
+ }
92
+ }
93
+
94
+ /** Index entries are the `- [label](path.md)` lines; everything else is prose. */
95
+ function parseIndexEntries(memoryDir) {
96
+ const path = join(memoryDir, 'index.md')
97
+ if (!existsSync(path)) return []
98
+ let text = ''
99
+ try {
100
+ text = readFileSync(path, 'utf8')
101
+ } catch {
102
+ return []
103
+ }
104
+ const entries = []
105
+ for (const match of text.matchAll(/^\s*-\s+\[[^\]]*\]\(([^)]+\.md)\)/gm)) {
106
+ const target = match[1]
107
+ if (/^https?:/.test(target)) continue
108
+ entries.push({ target, exists: existsSync(join(memoryDir, target)) })
109
+ }
110
+ return entries
111
+ }
112
+
113
+ /**
114
+ * Build the dashboard payload. Never throws on a missing or empty store — a
115
+ * fresh install yields a zeroed overview rather than an error.
116
+ *
117
+ * @param {string} memoryDir absolute path of the memory store
118
+ * @returns {object} JSON-serializable insights
119
+ */
120
+ export function collectInsights(memoryDir) {
121
+ const paths = listPagePaths(memoryDir)
122
+ const pages = paths.map((rel) => readPage(memoryDir, rel)).filter(Boolean)
123
+ const indexEntries = parseIndexEntries(memoryDir)
124
+ const indexPath = join(memoryDir, 'index.md')
125
+
126
+ // Freshness distribution: a page with no stamp at all is "never".
127
+ const buckets = FRESHNESS_BUCKETS.map((b) => ({ key: b.key, label: b.label, count: 0 }))
128
+ let never = 0
129
+ for (const page of pages) {
130
+ if (page.daysSinceAccess === undefined) {
131
+ never += 1
132
+ continue
133
+ }
134
+ const bucket = FRESHNESS_BUCKETS.find((b) => page.daysSinceAccess <= b.maxDays) ?? FRESHNESS_BUCKETS.at(-1)
135
+ buckets.find((b) => b.key === bucket.key).count += 1
136
+ }
137
+
138
+ const byType = new Map()
139
+ const bySalience = new Map()
140
+ for (const page of pages) {
141
+ byType.set(page.type, (byType.get(page.type) ?? 0) + 1)
142
+ if (page.salience !== undefined) bySalience.set(page.salience, (bySalience.get(page.salience) ?? 0) + 1)
143
+ }
144
+
145
+ const stalePages = pages
146
+ .filter((p) => p.daysSinceAccess === undefined || p.daysSinceAccess > 90)
147
+ .sort((a, b) => (b.daysSinceAccess ?? Infinity) - (a.daysSinceAccess ?? Infinity))
148
+ .slice(0, 8)
149
+ .map((p) => ({ path: p.path, title: p.title, salience: p.salience, daysSinceAccess: p.daysSinceAccess ?? null }))
150
+
151
+ // Checks mirror `dsh-memory lint` so the panel and the CLI cannot disagree.
152
+ const unstamped = pages.filter((p) => !p.lastAccess).length
153
+ const missingSalience = pages.filter((p) => p.salience === undefined).length
154
+ const missingType = pages.filter((p) => p.type === 'unknown').length
155
+ const missingLink = indexEntries.filter((e) => !e.exists)
156
+ const indexedTargets = new Set(indexEntries.filter((e) => e.exists).map((e) => e.target.replace(/^\.\//, '')))
157
+ const orphans = paths.filter((rel) => !indexedTargets.has(rel))
158
+ const staleCount = pages.filter((p) => p.daysSinceAccess !== undefined && p.daysSinceAccess > 90).length
159
+
160
+ const atRisk = staleCount + never
161
+ const checks = [
162
+ {
163
+ id: 'index',
164
+ ok: missingLink.length === 0,
165
+ label: 'index 链接完整',
166
+ detail: missingLink.length === 0 ? `${indexEntries.length} 条路由全部有效` : `${missingLink.length} 条指向不存在的页`,
167
+ },
168
+ {
169
+ id: 'orphans',
170
+ ok: orphans.length === 0,
171
+ label: '无孤儿页',
172
+ detail: orphans.length === 0 ? '每页都在 index 里' : `${orphans.length} 页未收录:${orphans.slice(0, 3).join('、')}${orphans.length > 3 ? '…' : ''}`,
173
+ },
174
+ {
175
+ id: 'frontmatter',
176
+ ok: missingSalience === 0 && missingType === 0,
177
+ label: 'frontmatter 完整',
178
+ detail: missingSalience === 0 && missingType === 0
179
+ ? 'title/type/salience 齐全'
180
+ : `缺 salience ${missingSalience} 页 / 缺 type ${missingType} 页`,
181
+ },
182
+ {
183
+ id: 'freshness',
184
+ ok: atRisk === 0,
185
+ label: '访问新鲜度',
186
+ detail: atRisk === 0 ? '没有超过 90 天未访问的页' : `${atRisk} 页陈旧或从未戳记`,
187
+ },
188
+ ]
189
+
190
+ const totalPages = pages.length
191
+ const score = totalPages === 0
192
+ ? 100
193
+ : Math.max(0, 100 - Math.round(
194
+ (orphans.length * 15 + missingSalience * 8 + missingType * 5 + atRisk * 10 + missingLink.length * 15)
195
+ / totalPages,
196
+ ))
197
+
198
+ const totalBytes = pages.reduce((sum, p) => sum + p.bytes, 0)
199
+ const indexBytes = existsSync(indexPath) ? statSync(indexPath).size : 0
200
+ const logSize = (() => {
201
+ try {
202
+ return statSync(join(memoryDir, 'log.md')).size
203
+ } catch {
204
+ return 0
205
+ }
206
+ })()
207
+ const newest = pages.reduce((max, p) => Math.max(max, p.mtimeMs), 0)
208
+ const recent = readRecentLog(memoryDir, 5)
209
+
210
+ return {
211
+ generatedAt: new Date().toISOString(),
212
+ store: memoryDir,
213
+ overview: {
214
+ pages: totalPages,
215
+ // Character count, not bytes/3: a CJK page is ~3 bytes per character, so a
216
+ // byte-based estimate overshoots Chinese stores by roughly 3x.
217
+ chars: pages.reduce((sum, p) => sum + p.chars, 0),
218
+ bytes: totalBytes,
219
+ indexEntries: indexEntries.length,
220
+ indexBytes,
221
+ logBytes: logSize,
222
+ lastWrite: newest > 0 ? new Date(newest).toISOString() : null,
223
+ neverAccessed: never,
224
+ },
225
+ byType: [...byType.entries()]
226
+ .map(([type, count]) => ({ type, label: TYPE_LABELS[type] ?? type, count }))
227
+ .sort((a, b) => b.count - a.count),
228
+ pages: pages.map((p) => ({
229
+ path: p.path,
230
+ title: p.title,
231
+ type: p.type,
232
+ salience: p.salience,
233
+ lastAccess: p.lastAccess,
234
+ })),
235
+ bySalience: [1, 2, 3].map((level) => ({ level, count: bySalience.get(level) ?? 0 })),
236
+ freshness: { buckets, never },
237
+ stalePages,
238
+ recent,
239
+ health: { score, checks },
240
+ }
241
+ }
242
+
243
+ /**
244
+ * The most recent `count` `log.md` headlines, newest last (same parser shape
245
+ * the recall nudge uses, so the dashboard never invents activity).
246
+ * @param {string} memoryDir absolute path of the memory store
247
+ * @param {number} count max entries
248
+ */
249
+ export function readRecentLog(memoryDir, count = 5) {
250
+ const path = join(memoryDir, 'log.md')
251
+ if (!existsSync(path)) return []
252
+ let text = ''
253
+ try {
254
+ text = readFileSync(path, 'utf8')
255
+ } catch {
256
+ return []
257
+ }
258
+ const entries = []
259
+ for (const line of text.split('\n')) {
260
+ if (line.startsWith('## [')) entries.push(line.slice(3).trim())
261
+ }
262
+ return entries.slice(-count).reverse()
263
+ }
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/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\` | 内容目录 | 每页一行:链接 + 摘要 + 元数据(类别、salience、最近访问) |
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
- > 内容目录:每个记忆页一行 —— 链接 + 摘要 + 元数据。**每次 remember 都要同步更新本文件。**
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
- ## [YYYY-MM-DD] install | dsh-plugin-memory 初始化
199
+ _(还没有动态。第一条真实条目由首次 digest 追加,格式如下:)_
194
200
 
195
- - 记忆库脚手架已创建;等待铸魂对话(BOOTSTRAP.md)完成灵魂定义与身份确认。
201
+ > ## [YYYY-MM-DD] install | dsh-plugin-memory 初始化
196
202
  `
197
203
 
198
204
  export const BOOTSTRAP_TEMPLATE = `---
@@ -8,7 +8,6 @@ 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
12
  export const inject: ['systemPrompt', 'skills', 'agents']
14
13
 
@@ -20,8 +19,16 @@ 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 `6000`. */
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
27
34
  /** Don't inject anything until the session's first real user message. Default `true`. */
@@ -64,6 +71,9 @@ export const Config: import('@deepseek-ai/schemastery').default<MemoryConfig>
64
71
  /** HTTP route serving the user-facing config to the Settings panel. */
65
72
  export const CONFIG_ROUTE_PATH: '/api/memory/config'
66
73
 
74
+ /** Read-only HTTP route serving the memory-health dashboard payload. */
75
+ export const INSIGHTS_ROUTE_PATH: '/api/memory/insights'
76
+
67
77
  /** User-editable settings (composition config is the base layer). */
68
78
  export interface MemorySettings {
69
79
  enabled?: boolean
@@ -114,9 +124,55 @@ export default plugin
114
124
  /** Render the boot memory block injected at session start. */
115
125
  export function renderBootBlock(
116
126
  memoryDir: string,
117
- options?: { bootFiles?: string[]; bootMaxChars?: number },
127
+ options?: {
128
+ bootFiles?: string[]
129
+ bootMaxChars?: number
130
+ bootFileBudgets?: Record<string, number>
131
+ },
118
132
  ): string
119
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
+
120
176
  /** Create the memory-store layout if missing. Returns created paths. */
121
177
  export function ensureMemoryScaffold(memoryDir: string): string[]
122
178
 
@@ -134,3 +190,42 @@ export class ActivityTracker {
134
190
  shouldInject(id: string, config?: { deferUntilUserSpeaks?: boolean; activeSessionOnly?: boolean }): boolean
135
191
  dispose(): void
136
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.6.0",
4
+ "version": "0.7.0",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",