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.
@@ -0,0 +1,419 @@
1
+ /**
2
+ * Index-page compiler: keep `index.md` a routing table instead of a summary dump.
3
+ *
4
+ * The index is injected into every session in full, so its size is a hard
5
+ * context cost — yet the discipline ("one line per page, a short summary") lived
6
+ * only in prose. Measured on a real store, 85% of its lines had drifted into
7
+ * half-paragraph status reports. This module makes the discipline mechanical:
8
+ *
9
+ * - a summary is **declared** by the page (`summary:` in frontmatter): the
10
+ * compiler never invents prose, which is why a rewrite cannot lower quality;
11
+ * **declared** by the page (`summary:` in frontmatter) — the compiler never
12
+ * invents prose, so a rewrite can never lower the summary's quality;
13
+ * - lines are *rewritten in place*: sections, ordering and the funnel list stay
14
+ * exactly as the agent left them, so an automated pass can never reorder the
15
+ * user's mental map of their own memory;
16
+ * - pages the index has never mentioned are only **reported**, never inserted —
17
+ * which section and which order a new page belongs to is editorial judgement,
18
+ * and that stays with the agent and the user.
19
+ *
20
+ * Everything is derived and dry-run first: `planIndex` never writes, and the CLI
21
+ * requires an explicit `--write`.
22
+ *
23
+ * Depends only on `node:*` builtins plus {@link ./insights.js}.
24
+ *
25
+ * @module dsh-plugin-memory/index-page
26
+ */
27
+
28
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
29
+ import { join } from 'node:path'
30
+ import { collectInsights, parseFrontmatter } from './insights.js'
31
+
32
+ /** Cap for the link label. A routing line is scanned, not read: a
33
+ * page's full title (often a whole clause) belongs in the page, not here. */
34
+ export const INDEX_LABEL_MAX = 32
35
+
36
+ /** Hard cap for one routing line (link + label + summary + salience). */
37
+ export const INDEX_LINE_MAX = 132
38
+ /** Nominal cap for the summary text; long labels shrink it further. */
39
+ export const INDEX_SUMMARY_MAX = 48
40
+
41
+ const LINE_RE = /^(\s*-\s+)\[([^\]]*)\]\(([^)]+)\)\s*(.*)$/
42
+ const HEADING_RE = /^##\s+(.*)$/
43
+
44
+ /** Strip the markdown scaffolding that would only add noise to a one-liner. */
45
+ function stripMarkup(text) {
46
+ return text
47
+ .replace(/`([^`]*)`/g, '$1')
48
+ .replace(/\*\*([^*]*)\*\*/g, '$1')
49
+ .replace(/\*([^*]*)\*/g, '$1')
50
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
51
+ .replace(/^\s*[-*+]\s+/, '')
52
+ .replace(/^\s*>\s?/, '')
53
+ .trim()
54
+ }
55
+
56
+ /**
57
+ * The first real sentence of a page body (skips headings, quotes and blanks).
58
+ * Exported for previews and tooling only — the index compiler does **not** use
59
+ * it, because derived prose measured worse than a declared summary.
60
+ */
61
+ export function firstSentence(text) {
62
+ const body = String(text ?? '').replace(/^---[\s\S]*?\n---\n?/, '')
63
+ for (const rawLine of body.split('\n')) {
64
+ const line = rawLine.trim()
65
+ if (line.length === 0 || line.startsWith('#') || line.startsWith('>')) continue
66
+ const clean = stripMarkup(line)
67
+ if (clean.length === 0) continue
68
+ const end = clean.search(/[。!?!?.](?:\s|$)/)
69
+ return (end >= 0 ? clean.slice(0, end + 1) : clean).trim()
70
+ }
71
+ return ''
72
+ }
73
+
74
+ /** Clamp to `max` characters, appending an ellipsis when it had to cut. */
75
+ export function clampSummary(text, max = INDEX_SUMMARY_MAX) {
76
+ const flat = String(text ?? '').replace(/\s+/g, ' ').trim()
77
+ if (flat.length <= max) return flat
78
+ const head = flat.slice(0, Math.max(1, max - 1))
79
+ // Prefer a natural break (sentence end, then clause) over a hard cut.
80
+ const boundary = Math.max(head.lastIndexOf('。'), head.lastIndexOf(';'), head.lastIndexOf(','))
81
+ if (boundary >= Math.floor(head.length / 2)) return head.slice(0, boundary + 1)
82
+ return `${head.trimEnd()}…`
83
+ }
84
+
85
+ /**
86
+ * Clamp a link label. Labels come from the page title, which is often a full
87
+ * clause ("macOS 下 dsh web 开机自启(LaunchAgent)+ 本机网络/安装坑"); the index
88
+ * needs the gist, the page keeps the full wording.
89
+ * @param {string} title
90
+ * @param {number} [max]
91
+ * @returns {string}
92
+ */
93
+ export function clampLabel(title, max = INDEX_LABEL_MAX) {
94
+ const flat = String(title ?? '').replace(/\s+/g, ' ').trim()
95
+ if (flat.length <= max) return flat
96
+
97
+ // A label is a road sign, so cut it somewhere meaningful rather than mid-word.
98
+ // CJK titles usually carry a parenthetical or a colon separator that marks a
99
+ // natural short form: "决策:社区上架主线选 awesome-dsh-plugin(喂给 dsh-market)"
100
+ // is better served by "决策:社区上架主线选 awesome-dsh-plugin" than by a
101
+ // character-count slice.
102
+ const head = flat.slice(0, max)
103
+ const separators = [':', ':', '(', '(', ' —— ', ' — ', ' - ']
104
+ let best = -1
105
+ for (const separator of separators) {
106
+ const at = head.lastIndexOf(separator)
107
+ if (at > best) best = at
108
+ }
109
+ if (best > Math.floor(max / 3)) return `${head.slice(0, best).trimEnd()}…`
110
+
111
+ // Otherwise prefer a word boundary for latin text ("dsh-plugin-superpowers
112
+ // 插件(obra…" → "dsh-plugin-superpowers…").
113
+ const boundary = head.search(/\s(?=\S*$)/)
114
+ if (boundary > Math.floor(max / 3)) return `${head.slice(0, boundary).trimEnd()}…`
115
+
116
+ return `${head.trimEnd()}…`
117
+ }
118
+
119
+ /**
120
+ * How much room a summary has on one line, given its label. A long label must
121
+ * not push the line past {@link INDEX_LINE_MAX}, so the summary yields first.
122
+ * @param {string} target store-relative page path
123
+ * @param {string} title link label (clamped internally)
124
+ * @param {number} [lineMax]
125
+ * @returns {number} character budget for the summary
126
+ */
127
+ export function summaryBudget(target, title, lineMax = INDEX_LINE_MAX) {
128
+ // Rendered markup around the words: "- [" + "](" + ") — " + " `salience:N`".
129
+ const MARKUP_CHARS = 24
130
+ const overhead = MARKUP_CHARS + clampLabel(title).length + String(target ?? '').length
131
+ return Math.max(16, Math.min(INDEX_SUMMARY_MAX, lineMax - overhead))
132
+ }
133
+
134
+ /**
135
+ * The summary a page declares about itself. **Declaration only** — the first
136
+ * sentence of the body is deliberately not used as a fallback: measured against
137
+ * a real store, derived prose summarised "the setup" instead of the point
138
+ * (a preferences page became "confirm the time first", not "code changes are
139
+ * not committed"), which is worse than no summary at all. An undeclared page
140
+ * contributes its title and nothing else.
141
+ * @param {Record<string, string>} frontmatter parsed frontmatter
142
+ * @returns {string} clamped summary, or '' when the page declares none
143
+ */
144
+ export function declaredSummary(frontmatter = {}, max = INDEX_SUMMARY_MAX) {
145
+ const value = frontmatter.summary
146
+ if (typeof value !== 'string' || value.trim().length === 0) return ''
147
+ return clampSummary(value, max)
148
+ }
149
+
150
+ /** Render one routing line exactly the way the compiler would. */
151
+ export function renderIndexLine({ target, title, salience, summary }) {
152
+ const label = clampLabel(title) || String(target ?? '')
153
+ const badge = salience === undefined ? '' : ` \`salience:${salience}\``
154
+ const text = summary && summary.length > 0 ? ` — ${summary}` : ''
155
+ return `- [${label}](${target})${text}${badge}`
156
+ }
157
+
158
+ /** Parse an index file into its funnel (title + intro) and its sections. */
159
+ export function parseIndexPage(text) {
160
+ const lines = String(text ?? '').split('\n')
161
+ let title = ''
162
+ const intro = []
163
+ const sections = []
164
+ let current
165
+
166
+ // Flat indexes exist: entries before the first `##` still have to parse, so
167
+ // they land in an implicit section instead of being mistaken for funnel prose.
168
+ const ensureSection = () => {
169
+ if (current === undefined) current = { heading: '', name: '', intro: [], items: [] }
170
+ if (sections.length === 0) sections.push(current)
171
+ else if (sections[sections.length - 1] !== current) sections.push(current)
172
+ return current
173
+ }
174
+
175
+ for (const line of lines) {
176
+ const heading = HEADING_RE.exec(line)
177
+ if (heading !== null) {
178
+ current = { heading: line, name: heading[1].trim(), intro: [], items: [] }
179
+ sections.push(current)
180
+ continue
181
+ }
182
+ const item = LINE_RE.exec(line)
183
+ if (item !== null) {
184
+ ensureSection().items.push({ label: item[2], target: item[3], rest: item[4].trim(), raw: line })
185
+ continue
186
+ }
187
+ if (current === undefined) {
188
+ if (title === '' && line.startsWith('# ')) {
189
+ title = line
190
+ continue
191
+ }
192
+ // Once the title is known, everything up to the first section is funnel
193
+ // prose and is preserved verbatim (blank lines included).
194
+ if (title !== '') intro.push(line)
195
+ continue
196
+ }
197
+ if (line.trim().length > 0 || current.items.length === 0) current.intro.push(line)
198
+ }
199
+ return { title, intro, sections }
200
+ }
201
+
202
+ /** Every page the index currently mentions, in file order. */
203
+ export function indexTargets(parsed) {
204
+ const targets = new Set()
205
+ for (const section of parsed.sections) {
206
+ for (const item of section.items) targets.add(item.target)
207
+ }
208
+ return targets
209
+ }
210
+
211
+ /** Compare content, not spacing: a whitespace-only re-render is not a change. */
212
+ const normalise = (value) => value.replace(/\s+/g, ' ').trim()
213
+
214
+ /**
215
+ * Compare the index against the store without touching anything.
216
+ *
217
+ * @param {string} memoryDir absolute path of the memory store
218
+ * @returns {{
219
+ * parsed: object,
220
+ * lines: Array<{ target: string, section: string, current: string, next: string,
221
+ * summary: string, title: string, salience?: number,
222
+ * source: 'declared'|'derived', changed: boolean }>,
223
+ * stale: number,
224
+ * missing: string[],
225
+ * removed: string[],
226
+ * }}
227
+ */
228
+ export function planIndex(memoryDir) {
229
+ const indexPath = join(memoryDir, 'index.md')
230
+ const text = existsSync(indexPath) ? readFileSync(indexPath, 'utf8') : ''
231
+ const parsed = parseIndexPage(text)
232
+ const insights = collectInsights(memoryDir)
233
+ const pageByPath = new Map((insights.pages ?? []).map((page) => [page.path, page]))
234
+ const targets = indexTargets(parsed)
235
+
236
+ const lines = []
237
+ let stale = 0
238
+ for (const section of parsed.sections) {
239
+ for (const item of section.items) {
240
+ const page = pageByPath.get(item.target)
241
+ // Root meta files (SOUL.md / MEMORY.md / log.md …) are not "pages": they
242
+ // have no frontmatter and are not derived, so they are never rewritten.
243
+ if (page === undefined) continue
244
+ let pageText = ''
245
+ try {
246
+ pageText = readFileSync(join(memoryDir, item.target), 'utf8')
247
+ } catch {
248
+ continue
249
+ }
250
+ const fm = parseFrontmatter(pageText)
251
+ const summary = declaredSummary(fm, summaryBudget(item.target, page.title))
252
+ const declared = summary.length > 0
253
+ const declaredChars = typeof fm.summary === 'string' ? fm.summary.trim().length : 0
254
+ const next = renderIndexLine({
255
+ target: item.target,
256
+ title: page.title,
257
+ salience: page.salience,
258
+ summary,
259
+ })
260
+ const changed = normalise(next) !== normalise(item.raw)
261
+ if (changed) stale += 1
262
+ lines.push({
263
+ target: item.target,
264
+ section: section.name,
265
+ current: item.raw,
266
+ next,
267
+ summary,
268
+ declaredChars,
269
+ title: page.title,
270
+ salience: page.salience,
271
+ source: declared ? 'declared' : 'derived',
272
+ changed,
273
+ })
274
+ }
275
+ }
276
+
277
+ // Only *derived pages* are candidates for the missing/removed reports: a root
278
+ // meta file listed in the index (SOUL.md …) is neither an orphan nor a page.
279
+ const listed = new Set(lines.map((line) => line.target))
280
+ const missing = [...pageByPath.keys()].filter((path) => !listed.has(path)).sort()
281
+ const removed = [...targets]
282
+ .filter((path) => !existsSync(join(memoryDir, path)))
283
+ .sort()
284
+ return { parsed, lines, stale, missing, removed }
285
+ }
286
+
287
+ /**
288
+ * Rewrite the lines the plan marked stale. Sections, ordering and any content
289
+ * the plan did not touch are preserved byte-for-byte; nothing is added or
290
+ * deleted, so the blast radius is exactly the lines reported by `--check`.
291
+ *
292
+ * @param {string} memoryDir absolute path of the memory store
293
+ * @param {{ parsed: object, lines: Array<object> }} plan from {@link planIndex}
294
+ * @returns {{ written: number, bytesBefore: number, bytesAfter: number }}
295
+ */
296
+ export function applyIndex(memoryDir, plan) {
297
+ const indexPath = join(memoryDir, 'index.md')
298
+ const before = existsSync(indexPath) ? readFileSync(indexPath, 'utf8') : ''
299
+ const replacement = new Map()
300
+ for (const line of plan.lines) {
301
+ if (line.changed) replacement.set(normalise(line.current), line.next)
302
+ }
303
+ let written = 0
304
+ const out = before.split('\n').map((raw) => {
305
+ const next = replacement.get(normalise(raw))
306
+ if (next === undefined) return raw
307
+ written += 1
308
+ return next
309
+ }).join('\n')
310
+ if (written > 0) writeFileSync(indexPath, out, 'utf8')
311
+ return { written, bytesBefore: before.length, bytesAfter: out.length }
312
+ }
313
+
314
+ /**
315
+ * One-shot migration: copy a summary that already lives in an index line back
316
+ * into the page's frontmatter, so the index and the declaration can never drift
317
+ * again. Pages that already declare `summary:` are left alone.
318
+ *
319
+ * @param {string} memoryDir absolute path of the memory store
320
+ * @param {{ lines: Array<{ target: string, summary: string, current: string }> }} plan
321
+ * @returns {{ synced: string[], skipped: string[] }}
322
+ */
323
+ export function syncDeclaredSummaries(memoryDir, plan) {
324
+ const synced = []
325
+ const skipped = []
326
+ for (const line of plan.lines) {
327
+ // Prefer an explicit "— summary" tail; fall back to nothing (never invent).
328
+ const tail = /\s+[—–-]\s+(.+?)(?:\s+`salience:[^`]*`)?\s*$/.exec(line.current)
329
+ const summary = (tail ? tail[1] : '').trim()
330
+ if (summary.length === 0) {
331
+ skipped.push(line.target)
332
+ continue
333
+ }
334
+ const abs = join(memoryDir, line.target)
335
+ let text = ''
336
+ try {
337
+ text = readFileSync(abs, 'utf8')
338
+ } catch {
339
+ skipped.push(line.target)
340
+ continue
341
+ }
342
+ if (/^summary:/m.test(text)) {
343
+ skipped.push(line.target)
344
+ continue
345
+ }
346
+ const end = text.indexOf('\n---', 3)
347
+ if (!text.startsWith('---') || end < 0) {
348
+ skipped.push(line.target)
349
+ continue
350
+ }
351
+ const next = `${text.slice(0, end)}\nsummary: ${clampSummary(summary)}${text.slice(end)}`
352
+ try {
353
+ writeFileSync(abs, next, 'utf8')
354
+ synced.push(line.target)
355
+ } catch {
356
+ skipped.push(line.target)
357
+ }
358
+ }
359
+ return { synced, skipped }
360
+ }
361
+
362
+ /**
363
+ * Issues the index has, for `lint` and `index --check`. Kept in one place so
364
+ * the CLI, the lint command and the dashboard cannot disagree.
365
+ *
366
+ * @param {string} memoryDir absolute path of the memory store
367
+ * @param {{ includeNoSummary?: boolean }} [options] `no-summary` is advisory, so
368
+ * `lint` opts out (it stays a quality nudge, not a failure)
369
+ * @returns {Array<{ kind: string, target?: string, detail: string }>}
370
+ */
371
+ export function indexIssues(memoryDir, options = {}) {
372
+ const plan = planIndex(memoryDir)
373
+ const issues = []
374
+ for (const line of plan.lines) {
375
+ // Scope: what is wrong with the *index*. "This line no longer matches its
376
+ // page" is `index --check`'s job (a rewrite fixes it), so lint stays free of
377
+ // duplicate reporting.
378
+ if (line.current.length > INDEX_LINE_MAX) {
379
+ issues.push({
380
+ kind: 'line-too-long',
381
+ target: line.target,
382
+ detail: `index 行 ${line.current.length} 字符(上限 ${INDEX_LINE_MAX}):${line.target}`,
383
+ })
384
+ } else if (line.declaredChars > INDEX_SUMMARY_MAX) {
385
+ // The header cap: rewrite will clamp it, so say so instead of silently
386
+ // trimming the author's words on the next `--write`.
387
+ issues.push({
388
+ kind: 'summary-too-long',
389
+ target: line.target,
390
+ detail: `summary 声明 ${line.declaredChars} 字(上限 ${INDEX_SUMMARY_MAX}):${line.target}`,
391
+ })
392
+ }
393
+ }
394
+ for (const path of plan.missing) {
395
+ issues.push({
396
+ kind: 'missing',
397
+ target: path,
398
+ detail: `页面未收录进 index(分节与顺序需人工决定):${path}`,
399
+ })
400
+ }
401
+ for (const path of plan.removed) {
402
+ issues.push({
403
+ kind: 'removed',
404
+ target: path,
405
+ detail: `index 指向已不存在的页(是否删行需人工确认):${path}`,
406
+ })
407
+ }
408
+ if (options.includeNoSummary === false) return issues
409
+ for (const line of plan.lines) {
410
+ if (line.summary.length === 0) {
411
+ issues.push({
412
+ kind: 'no-summary',
413
+ target: line.target,
414
+ detail: `页面未声明 summary(index 只有标题;补 frontmatter \`summary:\` 后会自动同步):${line.target}`,
415
+ })
416
+ }
417
+ }
418
+ return issues
419
+ }
package/lib/index.js CHANGED
@@ -26,6 +26,17 @@
26
26
  * a hard-coded namespace allowlist, so a plugin namespace is never
27
27
  * remotely writable (see `lib/config-store.js`).
28
28
  *
29
+ * 5. **Memory health dashboard.** A read-only `GET /api/memory/insights`
30
+ * route serves the payload behind the panel's health card (page counts,
31
+ * freshness distribution, lint-parity checks, stale candidates, recent
32
+ * activity). It is computed per request from the store on disk — never
33
+ * cached, never written.
34
+ *
35
+ * 6. **Memory graph.** A read-only `GET /api/memory/graph` route serves the
36
+ * relationships the store encodes but `index.md` never shows: explicit
37
+ * page-to-page links plus edges derived from shared frontmatter tags (and,
38
+ * optionally, same-type grouping). Rendered as an SVG in the panel.
39
+ *
29
40
  * The memory store itself is plain markdown + git — the plugin never owns
30
41
  * the format, only the workflows around it.
31
42
  *
@@ -36,7 +47,7 @@
36
47
  * | `enabled` | `true` | master switch: stops boot injection AND skill registration |
37
48
  * | `memoryDir` | `~/.memory` | absolute memory-store path (`~` expanded) |
38
49
  * | `bootFiles` | `[SOUL.md, MEMORY.md, index.md]` | files injected at boot |
39
- * | `bootMaxChars` | `6000` | total character budget of the boot block |
50
+ * | `bootMaxChars` | `12000` | total character budget of the boot block |
40
51
  * | `autoInject` | `true` | inject the boot block at session start |
41
52
  * | `registerSkill` | `true` | register the embedded `memory` skill |
42
53
  * | `scaffold` | `true` | create the store layout + templates when missing |
@@ -72,8 +83,18 @@
72
83
  import { homedir } from 'node:os'
73
84
  import { join, resolve } from 'node:path'
74
85
  import z from '@deepseek-ai/schemastery'
75
- import { renderBootBlock } from './boot.js'
86
+ import { renderBootBlock, DEFAULT_BOOT_FILES } from './boot.js'
87
+ import {
88
+ accessSummary,
89
+ extractReferencedPages,
90
+ listPagePaths,
91
+ today,
92
+ touchPageFile,
93
+ touchPages,
94
+ } from './pages.js'
76
95
  import { ensureMemoryScaffold } from './scaffold.js'
96
+ import { collectInsights } from './insights.js'
97
+ import { buildMemoryGraph } from './graph.js'
77
98
  import { MemoryConfigStore } from './config-store.js'
78
99
  import { SettingsSchema } from './schema.js'
79
100
  import { DigestGuard } from './digest-guard.js'
@@ -92,6 +113,12 @@ export const name = 'memory'
92
113
  /** HTTP route serving the user-facing config to the browser Settings panel. */
93
114
  export const CONFIG_ROUTE_PATH = '/api/memory/config'
94
115
 
116
+ /** Read-only HTTP route serving the memory-health dashboard payload. */
117
+ export const INSIGHTS_ROUTE_PATH = '/api/memory/insights'
118
+
119
+ /** Read-only HTTP route serving the memory graph (nodes + edges). */
120
+ export const GRAPH_ROUTE_PATH = '/api/memory/graph'
121
+
95
122
  export const inject = ['systemPrompt', 'skills', 'agents']
96
123
 
97
124
  /** Schemastery schema applied to the plugin config before startup. */
@@ -99,7 +126,11 @@ export const Config = z.object({
99
126
  enabled: z.boolean().default(true),
100
127
  memoryDir: z.string().default('~/.memory'),
101
128
  bootFiles: z.array(z.string()).default(['SOUL.md', 'MEMORY.md', 'index.md']),
102
- bootMaxChars: z.number().default(6000),
129
+ bootMaxChars: z.number().default(12000),
130
+ // Explicit per-file caps, composition-time only. Unlisted files share what
131
+ // is left; `index.md` is served first in the redistribution pass, and each
132
+ // file takes at most twice the even share (see allocateBootBudget).
133
+ bootFileBudgets: z.union([z.dict(z.number()), z.const(undefined)]),
103
134
  autoInject: z.boolean().default(true),
104
135
  registerSkill: z.boolean().default(true),
105
136
  scaffold: z.boolean().default(true),
@@ -149,8 +180,9 @@ export function resolveMemoryDir(dir) {
149
180
  * @returns {() => void} disposer
150
181
  */
151
182
  export function apply(ctx, config = {}) {
152
- const bootMaxChars = Math.max(512, Number(config.bootMaxChars) || 6000)
153
- const bootFiles = config.bootFiles ?? ['SOUL.md', 'MEMORY.md', 'index.md']
183
+ const bootMaxChars = Math.max(512, Number(config.bootMaxChars) || 12000)
184
+ const bootFiles = config.bootFiles && config.bootFiles.length > 0 ? config.bootFiles : DEFAULT_BOOT_FILES
185
+ const bootFileBudgets = config.bootFileBudgets
154
186
  const scaffoldEnabled = config.scaffold !== false
155
187
 
156
188
  // Single user-facing config source: composition defaults + memory.json.
@@ -249,7 +281,7 @@ export function apply(ctx, config = {}) {
249
281
  // the active session.
250
282
  const agent = context?.agent
251
283
  if (agent && !tracker.shouldInject(agent.id, store.get())) return ''
252
- return renderBootBlock(memoryDir, { bootFiles, bootMaxChars })
284
+ return renderBootBlock(memoryDir, { bootFiles, bootMaxChars, bootFileBudgets })
253
285
  },
254
286
  })
255
287
  } else {
@@ -293,6 +325,44 @@ export function apply(ctx, config = {}) {
293
325
  return () => stopCreated()
294
326
  }, 'memory.activity-tracker()')
295
327
 
328
+ // Page access bookkeeping: the salience/decay table in MEMORY.md is only
329
+ // real if `last_access` moves — it shipped as an honor-system field that
330
+ // nothing ever wrote, so every page aged in place and the decay rules
331
+ // stayed fiction. Stamp the pages the boot block actually hands the model,
332
+ // on the session's first real user message. Deliberately NOT inside the
333
+ // `text()` callback: prompt building stays synchronous and side-effect
334
+ // free, and nothing is stamped for a session the gates kept silent.
335
+ if (config.trackPageAccess !== false) {
336
+ const stamped = new Set()
337
+ ctx.effect(() => {
338
+ const stopCreated = ctx.on('agent/created', ({ agent }) => {
339
+ if (!ctx.agents.roots().includes(agent)) return
340
+ agent.ctx.effect(() => {
341
+ const stopInserted = ctx.on('agent/inbox/inserted', ({ agent: target, message }) => {
342
+ if (target?.id !== agent.id) return
343
+ if (message?.source?.kind !== 'user') return
344
+ if (stamped.has(agent.id)) return
345
+ if (!tracker.shouldInject(agent.id, store.get())) return
346
+ stamped.add(agent.id)
347
+ try {
348
+ const memoryDir = currentMemoryDir
349
+ const block = renderBootBlock(memoryDir, { bootFiles, bootMaxChars, bootFileBudgets })
350
+ const referenced = extractReferencedPages(block, memoryDir)
351
+ const touched = touchPages(memoryDir, [...bootFiles, ...referenced])
352
+ if (touched.length > 0) {
353
+ ctx.logger?.info?.(`memory: last_access stamped on ${touched.length} page(s)`)
354
+ }
355
+ } catch (error) {
356
+ ctx.logger?.warn?.(`memory: last_access stamp failed: ${error instanceof Error ? error.message : String(error)}`)
357
+ }
358
+ })
359
+ return () => stopInserted?.()
360
+ })
361
+ })
362
+ return () => stopCreated()
363
+ }, 'memory.page-access()')
364
+ }
365
+
296
366
  // Digest guard: one per live ROOT agent, so a skipped end-of-session
297
367
  // digest is caught mechanically instead of relying on the agent's
298
368
  // self-discipline. Independent of dsh-plugin-heartbeat — the nudge is
@@ -411,6 +481,57 @@ export function apply(ctx, config = {}) {
411
481
  })
412
482
  webCtx.effect(() => disposeRoute, 'memory.config-route()')
413
483
  ctx.logger?.info(`memory: config route at ${CONFIG_ROUTE_PATH} (store ${store.path})`)
484
+
485
+ // Read-only health dashboard payload. Built fresh on every request from the
486
+ // store on disk, so the panel always reflects the newest state and the
487
+ // plugin never caches a stale view of the user's memory.
488
+ const disposeInsightsRoute = webCtx.webServer.register({
489
+ kind: 'exact',
490
+ path: INSIGHTS_ROUTE_PATH,
491
+ handler: async (req, res) => {
492
+ try {
493
+ if (req.method !== 'GET') {
494
+ res.writeHead(405, { 'content-type': 'application/json; charset=utf-8' })
495
+ res.end(JSON.stringify({ error: 'method not allowed' }))
496
+ return
497
+ }
498
+ const insights = collectInsights(currentMemoryDir)
499
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
500
+ res.end(JSON.stringify(insights))
501
+ } catch (error) {
502
+ res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' })
503
+ res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }))
504
+ }
505
+ },
506
+ })
507
+ webCtx.effect(() => disposeInsightsRoute, 'memory.insights-route()')
508
+ ctx.logger?.info(`memory: insights route at ${INSIGHTS_ROUTE_PATH}`)
509
+
510
+ // Read-only memory graph: the relationships `index.md` alone cannot show.
511
+ const disposeGraphRoute = webCtx.webServer.register({
512
+ kind: 'exact',
513
+ path: GRAPH_ROUTE_PATH,
514
+ handler: async (req, res) => {
515
+ try {
516
+ if (req.method !== 'GET') {
517
+ res.writeHead(405, { 'content-type': 'application/json; charset=utf-8' })
518
+ res.end(JSON.stringify({ error: 'method not allowed' }))
519
+ return
520
+ }
521
+ const url = new URL(req.url ?? '/', 'http://localhost')
522
+ const includeTypeEdges = url.searchParams.get('types') === '1'
523
+ const includeSuggestions = url.searchParams.get('suggest') === '1'
524
+ const graph = buildMemoryGraph(currentMemoryDir, { includeTypeEdges, includeSuggestions })
525
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
526
+ res.end(JSON.stringify(graph))
527
+ } catch (error) {
528
+ res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' })
529
+ res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }))
530
+ }
531
+ },
532
+ })
533
+ webCtx.effect(() => disposeGraphRoute, 'memory.graph-route()')
534
+ ctx.logger?.info(`memory: graph route at ${GRAPH_ROUTE_PATH}`)
414
535
  })
415
536
 
416
537
  return () => {
@@ -434,3 +555,6 @@ Object.defineProperties(apply, {
434
555
  export default apply
435
556
 
436
557
  export { renderBootBlock, ensureMemoryScaffold, SettingsSchema, MemoryConfigStore, ActivityTracker }
558
+ export { touchPages, touchPageFile, extractReferencedPages, listPagePaths, accessSummary, today }
559
+ export { collectInsights, readRecentLog } from './insights.js'
560
+ export { buildMemoryGraph, EDGE_KINDS } from './graph.js'