dsh-plugin-memory 0.6.0 → 0.8.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 +46 -0
- package/README.md +53 -12
- package/lib/boot.js +133 -8
- package/lib/checkup.js +235 -0
- package/lib/client.js +643 -2
- package/lib/digest-guard.js +43 -3
- 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 +395 -0
- package/lib/index-page.js +419 -0
- package/lib/index.js +130 -6
- package/lib/insights.js +275 -0
- package/lib/pages.js +238 -0
- package/lib/scaffold.js +14 -6
- package/lib/types/index.d.ts +98 -3
- package/package.json +1 -1
- package/scripts/memory.mjs +244 -7
- package/skills/memory.md +4 -4
package/lib/insights.js
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
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
|
+
// Characters, not bytes: every budget in this plugin is expressed in
|
|
201
|
+
// characters (bootMaxChars), and a CJK page is ~3 bytes per character, so
|
|
202
|
+
// comparing bytes against a character budget overstates by ~2x.
|
|
203
|
+
let indexChars = 0
|
|
204
|
+
if (existsSync(indexPath)) {
|
|
205
|
+
try {
|
|
206
|
+
indexChars = readFileSync(indexPath, 'utf8').length
|
|
207
|
+
} catch {
|
|
208
|
+
indexChars = indexBytes
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
const logSize = (() => {
|
|
212
|
+
try {
|
|
213
|
+
return statSync(join(memoryDir, 'log.md')).size
|
|
214
|
+
} catch {
|
|
215
|
+
return 0
|
|
216
|
+
}
|
|
217
|
+
})()
|
|
218
|
+
const newest = pages.reduce((max, p) => Math.max(max, p.mtimeMs), 0)
|
|
219
|
+
const recent = readRecentLog(memoryDir, 5)
|
|
220
|
+
|
|
221
|
+
return {
|
|
222
|
+
generatedAt: new Date().toISOString(),
|
|
223
|
+
store: memoryDir,
|
|
224
|
+
overview: {
|
|
225
|
+
pages: totalPages,
|
|
226
|
+
// Character count, not bytes/3: a CJK page is ~3 bytes per character, so a
|
|
227
|
+
// byte-based estimate overshoots Chinese stores by roughly 3x.
|
|
228
|
+
chars: pages.reduce((sum, p) => sum + p.chars, 0),
|
|
229
|
+
bytes: totalBytes,
|
|
230
|
+
indexEntries: indexEntries.length,
|
|
231
|
+
indexBytes,
|
|
232
|
+
indexChars,
|
|
233
|
+
logBytes: logSize,
|
|
234
|
+
lastWrite: newest > 0 ? new Date(newest).toISOString() : null,
|
|
235
|
+
neverAccessed: never,
|
|
236
|
+
},
|
|
237
|
+
byType: [...byType.entries()]
|
|
238
|
+
.map(([type, count]) => ({ type, label: TYPE_LABELS[type] ?? type, count }))
|
|
239
|
+
.sort((a, b) => b.count - a.count),
|
|
240
|
+
pages: pages.map((p) => ({
|
|
241
|
+
path: p.path,
|
|
242
|
+
title: p.title,
|
|
243
|
+
type: p.type,
|
|
244
|
+
salience: p.salience,
|
|
245
|
+
lastAccess: p.lastAccess,
|
|
246
|
+
})),
|
|
247
|
+
bySalience: [1, 2, 3].map((level) => ({ level, count: bySalience.get(level) ?? 0 })),
|
|
248
|
+
freshness: { buckets, never },
|
|
249
|
+
stalePages,
|
|
250
|
+
recent,
|
|
251
|
+
health: { score, checks },
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* The most recent `count` `log.md` headlines, newest last (same parser shape
|
|
257
|
+
* the recall nudge uses, so the dashboard never invents activity).
|
|
258
|
+
* @param {string} memoryDir absolute path of the memory store
|
|
259
|
+
* @param {number} count max entries
|
|
260
|
+
*/
|
|
261
|
+
export function readRecentLog(memoryDir, count = 5) {
|
|
262
|
+
const path = join(memoryDir, 'log.md')
|
|
263
|
+
if (!existsSync(path)) return []
|
|
264
|
+
let text = ''
|
|
265
|
+
try {
|
|
266
|
+
text = readFileSync(path, 'utf8')
|
|
267
|
+
} catch {
|
|
268
|
+
return []
|
|
269
|
+
}
|
|
270
|
+
const entries = []
|
|
271
|
+
for (const line of text.split('\n')) {
|
|
272
|
+
if (line.startsWith('## [')) entries.push(line.slice(3).trim())
|
|
273
|
+
}
|
|
274
|
+
return entries.slice(-count).reverse()
|
|
275
|
+
}
|
package/lib/pages.js
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
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
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Every page with the metadata the query command filters on.
|
|
201
|
+
*
|
|
202
|
+
* A thin wrapper over {@link listPagePaths}: callers that only need metadata
|
|
203
|
+
* should not re-implement the frontmatter walk, and this keeps the CLI and the
|
|
204
|
+
* dashboard agreeing on what counts as a page.
|
|
205
|
+
*
|
|
206
|
+
* @param {string} memoryDir absolute path of the memory store
|
|
207
|
+
* @returns {Array<{ path: string, title: string, type: string, salience?: number, tags: string[], lastAccess?: string }>}
|
|
208
|
+
*/
|
|
209
|
+
export function listPagesWithMeta(memoryDir) {
|
|
210
|
+
const out = []
|
|
211
|
+
for (const rel of listPagePaths(memoryDir)) {
|
|
212
|
+
let text = ''
|
|
213
|
+
try {
|
|
214
|
+
text = readFileSync(join(memoryDir, rel), 'utf8')
|
|
215
|
+
} catch {
|
|
216
|
+
continue
|
|
217
|
+
}
|
|
218
|
+
const end = text.startsWith('---') ? text.indexOf('\n---', 3) : -1
|
|
219
|
+
const fm = {}
|
|
220
|
+
if (end > 0) {
|
|
221
|
+
for (const line of text.slice(3, end).split('\n')) {
|
|
222
|
+
const m = /^([A-Za-z_][\w-]*)\s*:\s*(.*)$/.exec(line)
|
|
223
|
+
if (m) fm[m[1]] = m[2].trim()
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
const salience = Number(fm.salience)
|
|
227
|
+
const tagMatch = /^\[(.*)\]$/.exec(fm.tags ?? '')
|
|
228
|
+
out.push({
|
|
229
|
+
path: rel,
|
|
230
|
+
title: fm.title || rel.split('/').pop().replace(/\.md$/, ''),
|
|
231
|
+
type: fm.type || 'unknown',
|
|
232
|
+
salience: [1, 2, 3].includes(salience) ? salience : undefined,
|
|
233
|
+
tags: tagMatch ? tagMatch[1].split(',').map((t) => t.trim()).filter(Boolean) : [],
|
|
234
|
+
lastAccess: fm.last_access,
|
|
235
|
+
})
|
|
236
|
+
}
|
|
237
|
+
return out
|
|
238
|
+
}
|
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(偏好/风格) |
|
|
@@ -106,7 +106,9 @@ export const MEMORY_TEMPLATE = `# MEMORY — 记忆库 schema 与维护协议
|
|
|
106
106
|
## 工作流
|
|
107
107
|
|
|
108
108
|
### remember(记)
|
|
109
|
-
读源 → 提取关键事实 → 新建/更新相关页 →
|
|
109
|
+
读源 → 提取关键事实 → 新建/更新相关页 → **补 1–3 条「相关页面」互链(相对路径)** → 标注矛盾 → 更新 \`index.md\` → 追加 \`log.md\`。一次 ingest 常 touch 多页。
|
|
110
|
+
|
|
111
|
+
> 互链不是装饰:\`index.md\` 是目录(谁存在),页间链接是**关系**(谁和谁有关)。图谱、跨页综合、未来的检索都建立在这层关系上——写页时顺手补两三行,比事后补一个功能有用。
|
|
110
112
|
|
|
111
113
|
### recall(忆)
|
|
112
114
|
先读 \`index.md\` 定位,再钻页综合;好的答案可回写为新页(让探索复利累积)。
|
|
@@ -134,6 +136,9 @@ sources: [] # 指向 raw/ 或外部
|
|
|
134
136
|
|
|
135
137
|
- 页面用**相对 markdown 链接**互相引用。
|
|
136
138
|
- 新信息与旧声明矛盾时:改旧页、在新页标注、\`log.md\` 记变更。
|
|
139
|
+
- \`last_access\` 由插件**自动维护**:会话启动时把 boot 块实际引用的页面戳为当天,也可用 \`dsh-memory touch <pages...>\` 手动补记。写页时保持该字段存在即可,不必逐日手改。
|
|
140
|
+
- \`index.md\` 是**路由表**:一行一页、一句话摘要,不写状态流水。它会被完整注入会话,膨胀的代价是挤掉其他记忆——一行写不下,就说明该拆页或该把细节移进正文。
|
|
141
|
+
- 每个页面用 frontmatter \`summary:\` 声明一句话摘要(≤ 100 字)——index 行由它派生,\`dsh-memory index --write\` 负责同步,\`--sync-frontmatter\` 可把已写在 index 里的摘要回填到页面。
|
|
137
142
|
|
|
138
143
|
## 迁移协议
|
|
139
144
|
|
|
@@ -151,8 +156,11 @@ sources: [] # 指向 raw/ 或外部
|
|
|
151
156
|
|
|
152
157
|
export const INDEX_TEMPLATE = `# Memory Index
|
|
153
158
|
|
|
154
|
-
>
|
|
155
|
-
>
|
|
159
|
+
> 内容目录 / 路由表:**每页一行** —— 链接 + 一句话摘要(≤ 80 字)+ \`salience\` 标记。**每次 remember 都要同步更新本文件。**
|
|
160
|
+
> 查询时先读本文件定位,再钻具体页。这是**路由表而不是摘要表**:细节留在页面里,index 只负责让人知道「有这一页、值不值得点进去」。
|
|
161
|
+
|
|
162
|
+
> 长度自律:一行一句话。写不下就说明该拆页,或该把细节放进页面正文——不要把状态、进度、复述塞进 index。
|
|
163
|
+
> **摘要来源**:index 行由页面的 frontmatter \`summary:\` 派生(\`dsh-memory index --write\` 自动重写),不要在这里手写散文——手写的会漂移。
|
|
156
164
|
|
|
157
165
|
## 元记忆
|
|
158
166
|
|
|
@@ -190,9 +198,9 @@ export const LOG_TEMPLATE = `# Memory Log
|
|
|
190
198
|
|
|
191
199
|
> append-only 时间线。每条:\`## [YYYY-MM-DD] <kind> | <title>\`,可 \`grep '^## \\[' log.md\` 解析。
|
|
192
200
|
|
|
193
|
-
|
|
201
|
+
_(还没有动态。第一条真实条目由首次 digest 追加,格式如下:)_
|
|
194
202
|
|
|
195
|
-
-
|
|
203
|
+
> ## [YYYY-MM-DD] install | dsh-plugin-memory 初始化
|
|
196
204
|
`
|
|
197
205
|
|
|
198
206
|
export const BOOTSTRAP_TEMPLATE = `---
|