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/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,13 +83,24 @@
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'
80
101
  import { RecallNudge } from './recall-nudge.js'
81
102
  import { AutoCommitter } from './autocommit.js'
103
+ import { ActivityTracker } from './activity-tracker.js'
82
104
  import {
83
105
  MEMORY_SKILL_NAME,
84
106
  MEMORY_SKILL_DESCRIPTION,
@@ -91,6 +113,12 @@ export const name = 'memory'
91
113
  /** HTTP route serving the user-facing config to the browser Settings panel. */
92
114
  export const CONFIG_ROUTE_PATH = '/api/memory/config'
93
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
+
94
122
  export const inject = ['systemPrompt', 'skills', 'agents']
95
123
 
96
124
  /** Schemastery schema applied to the plugin config before startup. */
@@ -98,11 +126,19 @@ export const Config = z.object({
98
126
  enabled: z.boolean().default(true),
99
127
  memoryDir: z.string().default('~/.memory'),
100
128
  bootFiles: z.array(z.string()).default(['SOUL.md', 'MEMORY.md', 'index.md']),
101
- 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)]),
102
134
  autoInject: z.boolean().default(true),
103
135
  registerSkill: z.boolean().default(true),
104
136
  scaffold: z.boolean().default(true),
105
137
  configFile: z.union([z.string(), z.const(undefined)]),
138
+ // Gate 1: don't inject until the session's first real user message.
139
+ deferUntilUserSpeaks: z.boolean().default(true),
140
+ // Gate 2: only the currently active session (most recent user message) injects.
141
+ activeSessionOnly: z.boolean().default(true),
106
142
  // Digest guard: inject a synthetic reminder when the agent sits idle and
107
143
  // the store has not been written for a while, so the end-of-session
108
144
  // digest cannot be silently skipped.
@@ -144,8 +180,9 @@ export function resolveMemoryDir(dir) {
144
180
  * @returns {() => void} disposer
145
181
  */
146
182
  export function apply(ctx, config = {}) {
147
- const bootMaxChars = Math.max(512, Number(config.bootMaxChars) || 6000)
148
- 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
149
186
  const scaffoldEnabled = config.scaffold !== false
150
187
 
151
188
  // Single user-facing config source: composition defaults + memory.json.
@@ -156,6 +193,8 @@ export function apply(ctx, config = {}) {
156
193
  memoryDir: config.memoryDir ?? '~/.memory',
157
194
  autoInject: config.autoInject !== false,
158
195
  registerSkill: config.registerSkill !== false,
196
+ deferUntilUserSpeaks: config.deferUntilUserSpeaks !== false,
197
+ activeSessionOnly: config.activeSessionOnly !== false,
159
198
  recallEnabled: config.recallEnabled !== false,
160
199
  recallIntervalMinMinutes: config.recallIntervalMinMinutes ?? 30,
161
200
  recallIntervalMaxMinutes: config.recallIntervalMaxMinutes ?? 240,
@@ -163,6 +202,11 @@ export function apply(ctx, config = {}) {
163
202
  },
164
203
  })
165
204
 
205
+ // Per-agent activity tracker: the single source of truth for both gates.
206
+ // Created before `rebuild()` so the boot block's `text` closure can consult
207
+ // it, and shared with the digest guard + recall nudge so they never disagree.
208
+ const tracker = new ActivityTracker({ agents: ctx.agents, logger: ctx.logger })
209
+
166
210
  let bootDispose
167
211
  let skillDispose
168
212
  let scaffoldedDir
@@ -231,7 +275,14 @@ export function apply(ctx, config = {}) {
231
275
  bootDispose = ctx.systemPrompt.context({
232
276
  name: 'memory-boot',
233
277
  order: -200,
234
- text: () => renderBootBlock(memoryDir, { bootFiles, bootMaxChars }),
278
+ text: (context) => {
279
+ // Per-agent gate: no agent context (e.g. a global preview) injects
280
+ // unconditionally; an agent injects only once it has spoken and is
281
+ // the active session.
282
+ const agent = context?.agent
283
+ if (agent && !tracker.shouldInject(agent.id, store.get())) return ''
284
+ return renderBootBlock(memoryDir, { bootFiles, bootMaxChars, bootFileBudgets })
285
+ },
235
286
  })
236
287
  } else {
237
288
  disposeBoot()
@@ -259,6 +310,59 @@ export function apply(ctx, config = {}) {
259
310
 
260
311
  rebuild()
261
312
 
313
+ // Activity tracker: attach to every live ROOT agent so the two gates
314
+ // (has-user-spoken + active-session) see real user messages as they land.
315
+ ctx.effect(() => {
316
+ const stopCreated = ctx.on('agent/created', ({ agent }) => {
317
+ if (!ctx.agents.roots().includes(agent)) return
318
+ agent.ctx.effect(() => {
319
+ tracker.attach(agent)
320
+ return () => {
321
+ tracker.detach(agent.id)
322
+ }
323
+ })
324
+ })
325
+ return () => stopCreated()
326
+ }, 'memory.activity-tracker()')
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
+
262
366
  // Digest guard: one per live ROOT agent, so a skipped end-of-session
263
367
  // digest is caught mechanically instead of relying on the agent's
264
368
  // self-discipline. Independent of dsh-plugin-heartbeat — the nudge is
@@ -275,10 +379,13 @@ export function apply(ctx, config = {}) {
275
379
  afterMinutes: config.digestNudgeAfterMinutes,
276
380
  cooldownMinutes: config.digestNudgeCooldownMinutes,
277
381
  maxPerSession: config.digestNudgeMaxPerSession,
382
+ deferUntilUserSpeaks: resolved.deferUntilUserSpeaks,
383
+ activeSessionOnly: resolved.activeSessionOnly,
278
384
  }
279
385
  },
280
386
  getMemoryDir: () => currentMemoryDir,
281
387
  agents: ctx.agents,
388
+ tracker,
282
389
  logger: ctx.logger,
283
390
  })
284
391
  agent.ctx.effect(() => {
@@ -307,10 +414,13 @@ export function apply(ctx, config = {}) {
307
414
  minMinutes: resolved.recallIntervalMinMinutes,
308
415
  maxMinutes: resolved.recallIntervalMaxMinutes,
309
416
  maxPerSession: resolved.recallMaxPerSession,
417
+ deferUntilUserSpeaks: resolved.deferUntilUserSpeaks,
418
+ activeSessionOnly: resolved.activeSessionOnly,
310
419
  }
311
420
  },
312
421
  getMemoryDir: () => currentMemoryDir,
313
422
  agents: ctx.agents,
423
+ tracker,
314
424
  logger: ctx.logger,
315
425
  })
316
426
  agent.ctx.effect(() => {
@@ -371,12 +481,63 @@ export function apply(ctx, config = {}) {
371
481
  })
372
482
  webCtx.effect(() => disposeRoute, 'memory.config-route()')
373
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 graph = buildMemoryGraph(currentMemoryDir, { includeTypeEdges })
524
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
525
+ res.end(JSON.stringify(graph))
526
+ } catch (error) {
527
+ res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' })
528
+ res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }))
529
+ }
530
+ },
531
+ })
532
+ webCtx.effect(() => disposeGraphRoute, 'memory.graph-route()')
533
+ ctx.logger?.info(`memory: graph route at ${GRAPH_ROUTE_PATH}`)
374
534
  })
375
535
 
376
536
  return () => {
377
537
  disposeBoot()
378
538
  disposeSkill()
379
539
  disposeCommitter()
540
+ tracker.dispose()
380
541
  }
381
542
  }
382
543
 
@@ -392,4 +553,7 @@ Object.defineProperties(apply, {
392
553
 
393
554
  export default apply
394
555
 
395
- export { renderBootBlock, ensureMemoryScaffold, SettingsSchema, MemoryConfigStore }
556
+ export { renderBootBlock, ensureMemoryScaffold, SettingsSchema, MemoryConfigStore, ActivityTracker }
557
+ export { touchPages, touchPageFile, extractReferencedPages, listPagePaths, accessSummary, today }
558
+ export { collectInsights, readRecentLog } from './insights.js'
559
+ export { buildMemoryGraph, EDGE_KINDS } from './graph.js'
@@ -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
+ }