dsh-plugin-memory 0.7.0 → 0.8.1

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 CHANGED
@@ -2,6 +2,37 @@
2
2
 
3
3
  所有记录跟随 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/) 风格;版本号与 `package.json` 保持一致。
4
4
 
5
+ ## [0.8.1] - 2026-09-28
6
+
7
+ ### Fixed(DSH session format v4 兼容)
8
+
9
+ - **修复注入消息被 v4 拒绝导致的运行失败**:`recall-nudge` 与 `digest-guard` 生成的消息 source 从 `{ kind: 'plugin', plugin: 'memory' }` 改为 **`{ kind: 'plugin:memory' }`**。
10
+ - **症状**:`SessionFormatError: format v4 message requires a producer-owned source kind`。它被 `dsh-agent-loop` 当作非 LLM 错误包成 `{ message, code: 'UNKNOWN' }`,界面上显示为 `... source kind UNKNOWN`——**`UNKNOWN` 是错误码,不是 kind 值**。
11
+ - **原因**:session format **v4**(官方 DeepSeek Harness **0.1.7+**)的原生准入 `source()` 明确拒绝 `kind === "plugin"` 这一 v3 时代的 wrapper,要求 producer-owned kind;第三方插件的形态是 `plugin:<name>`(`producerKind()` 的兜底分支)。
12
+ - **兼容性门槛(重要)**:v4 校验与 v3 的 `SOURCE_KINDS` 白名单**互斥**——v3 白名单里只有 `plugin`,没有 `plugin:memory`,所以**无法同时兼容两版**。**本版起要求 DSH session format v4(官方 0.1.7+)**;旧版 DSH 请停留在 0.8.0。
13
+ - **历史 session 不受影响**:v3→v4 迁移的 `rewritePluginSource()` 会自动把旧 wrapper 转换成新格式,只有**新注入**的消息需要改。
14
+
15
+ ### Tests
16
+
17
+ - `test/recall-nudge.test.mjs` / `test/digest-guard.test.mjs` 的 source 断言改为 `deepEqual(source, { kind: 'plugin:memory' })`——顺带卡住「不得再带 `plugin` 字段」。
18
+ - 先写测试并确认其失败(`actual: {kind:'plugin',plugin:'memory'}` vs `expected: {kind:'plugin:memory'}`)后才改实现。
19
+ - 单测 **32/32 通过**。全量 151 项中 3 项失败(`insights-route` / `page-access` / `plugin-metadata`)为既有的 `@deepseek-ai/schemastery` 依赖缺失,已用 `git stash` 基线对比确认**与本次改动无关**。
20
+
21
+ ## [0.8.0] - 2026-09-24
22
+
23
+ ### Added(checkup 报告 + 注入瘦身 + 日志修复)
24
+
25
+ - **`dsh-memory checkup [--boot=N]`**(新增 `lib/checkup.js`):把 lint / status / insights / graph 四个读者合成一份报告——体量、新鲜度条形图、连接度、四项一致性检查,末尾是**按优先级排序的行动清单**。设计动机:四个数字是诊断,"最该做的三件事"才是产品。有活干时退出码非 0。`lonely` 的判据是"除 index 行外没有任何关系"(索引是目录,不算关系)。
26
+ - **补链建议分级 strong/weak**:默认只报告有内容信号的建议(共享主题 tag / 标题词),"仅同类型或同桶标签"降级为 weak,需显式请求才返回——否则每个 skill 页都会"应该"连到每个 skill 页。
27
+ - **boot 注入瘦身 23%**(9240 → 7118 字符 ≈ 6160 → 4745 token):`MEMORY.md` 3464 → 1415 字符(与按需加载的 `memory` 技能重叠的 9 个主题交给技能,本文件只留库自己的 schema);动态条数 5 → 3;索引标签按语义截断而非数到第 N 个字符。
28
+ - **修复 `log.md` 读错端**:`renderBootBlock` 用 `readCapped` 取文件**头**,而 log 是 append-only —— 100 KB 的日志意味着每次会话注入的都是**最旧**的 5 条动态。新增 `readTailCapped()` 从尾部按字符读取。影响所有已发布版本。
29
+
30
+ ### Added(互链机制 + 补链建议)
31
+
32
+ - **互链升级为默认动作**(`skills/memory.md` / `lib/scaffold.js` / `lib/digest-guard.js`):remember 流程、MEMORY 模板工作流、digest 收尾指令三处都要求「给这次碰过的页面各补 1–3 条相关页链接」。动机是实测数据:一个真实记忆库 29 页里只有 1 条真互链,而图谱、跨页综合、探索全都建立在这层关系上——`index.md` 只是目录。
33
+ - **`dsh-memory query`**:结构化检索——先按 frontmatter 过滤(`--tag` / `--type` / `--salience` / `--hot` / `--stale`,可组合),再在结果集内匹配正文关键词。原来的 `search` 只能逐行 `includes`,而 agent 的真实需求通常是"所有带 #memory-plugin 的决策",不是"含某个词的行"。数据层是新增的 `listPagesWithMeta()`(与看板共用"什么算一页"的口径)。
34
+ - **`dsh-memory graph [--suggest]`**(新增 `suggestLinks()` + 路由 `?suggest=1`):报告关系构成与孤立页;`--suggest` 对「只有索引入口」的页面给出「该引用谁」,按共享主题 tag(3 分)、标题词重合(2 分)、共享桶标签(1 分)、同类型(1 分)打分并输出理由。规则刻意保守:**同类型 + 桶标签本身不足以构成建议**(否则每个 skill 页都"应该"连到每个 skill 页);完全无标签的页面降级为弱建议但会说明理由。只报告、不写入。
35
+
5
36
  ## [0.7.0] - 2026-09-23
6
37
 
7
38
  ### Added(boot 预算按文件分配 + last_access 自动戳记 + 记忆健康看板)
package/README.md CHANGED
@@ -25,7 +25,10 @@
25
25
  - **git 自动提交**:记忆库变更静默 `autoCommitQuietSeconds` 后自动 `git add -A && git commit`(无 `.git` 则跳过)——历史可回滚不再依赖 agent 记得 commit。
26
26
  - **设置面板**:在 DSH 设置页提供「记忆 Memory」区块——总开关、记忆目录、开机注入、技能注册、主动追忆(开关 + 随机间隔范围 + 每会话次数)均可热改,立即生效,无需重启。
27
27
  - **index 自动整理(声明式编译)**:索引行不再手写。页面在 frontmatter 里声明 `summary:`,`dsh-memory index --write` 把行重写为它的投影(标签 ≤32 / 摘要 ≤48 / 整行 ≤132 字符),**只改行内容,分节与顺序逐字节保留**,且幂等。`index --check` 给机器判定(有漂移退出码非 0),`index --sync-frontmatter` 把已写在 index 里的摘要回填进页面(老库一次性迁移)。digest 提醒会在索引漂移时附一句提示,agent 顺手就能修。
28
+ - **互链成为默认动作**:`index.md` 是目录(谁存在),页间互链才是**关系**(谁和谁有关)——实测一个真实记忆库里 29 页只有 1 条真互链,而图谱与跨页综合全都建立在这层关系上。现在三处一起推:`skills/memory.md` 的 remember 流程、`MEMORY.md` 模板的工作流、以及 digest 提醒的收尾指令,都明确要求"给这次碰过的页面各补 1–3 条相关页链接"。
29
+ - **补链建议**:`dsh-memory graph --suggest` 列出「只有索引入口、没有任何内容关系」的页面该引用谁——按共享主题 tag、标题词、同类型打分,并说明理由(`共享 #dsh` / `标题词 dsh` / `同类型`)。只报告不写入:是否连、怎么连由 agent 决定。`GET /api/memory/graph?suggest=1` 同源。
28
30
  - **记忆图谱**:设置页里一张只读关系图 —— 不只是 `index.md` 那种"索引连着所有页"的星形,而是把页面**已经编码但没人画出来**的关系画出来:**索引路由**(`index.md` 指向每一页——这是全库最大的边集,43 条;先前版本跳过了元文件,导致 index 在图上孤立无援)、页间显式 markdown 链接(含相对路径解析)、共享 frontmatter tag(通用容器 tag 如 `project`/`skill` 会被忽略,稠密 tag 走锚点链而非全连接)。坐标由服务端 `lib/graph-layout.js` 一次性算好(确定性、无随机、无依赖),客户端只负责画 SVG。**可交互**:滚轮缩放(以光标为中心,缩放范围 0.4×–2.5×,非 passive 监听所以不会连带滚动设置页)、拖空白处平移、`重置视图` 回到全图;按住节点即可拖走,直接邻居按距离轻微跟随,松手后带缓动滑回原布局——拖动期间暂停过渡做到 1:1 跟手,用 O(邻居数) 的局部松弛而不是逐帧全量力导向(后者在几百页时会卡)。悬停高亮邻里,首次渲染从中心绽开(尊重 `prefers-reduced-motion`)。图谱**每 25 秒自动刷新**(面板开着时记忆变更会自己出现,副标题显示「更新于 HH:MM:SS」);取数失败保留上一张图而不是清空。视图数学(`zoomAt`/`panBy`/`toGraphPoint`)在 `lib/graph-view.js` 里是纯函数并有测试——缩放中心不漂移这件事必须被钉住。`GET /api/memory/graph`(只读、实时,`?types=1` 追加同类型弱边)。三类边在图上可区分:页间互链=实线蓝、索引路由=灰色虚线、共享 tag=细线。
31
+ - **`dsh-memory checkup`**:把四个读者(lint 的完整性、status 的计数、看板的体量与新鲜度、graph 的关系)合成**一份带优先级的报告** —— 体量、新鲜度条形图、连接度、一致性检查,最后给出"最该做的 N 件事"。四个数字是诊断,"做这三件事"才是产品。有活干时退出码非 0,可被脚本消费。`--boot=N` 用于按你的 boot 预算计算索引占比。
29
32
  - **记忆健康看板**:同一区块下方是一张**只读**看板——记忆页数 / index 路由数 / 记忆字数、访问新鲜度条形图(今天 / ≤7 / ≤30 / ≤90 / >90 天)、四项体检结论(index 链接、孤儿页、frontmatter、新鲜度)与健康分、陈旧页候选、最近 5 条动态。数据来自新增的 `GET /api/memory/insights`(每次请求实时统计,不缓存),体检口径与 `dsh-memory lint` 同源,所以看板与 CLI 不会互相打脸。
30
33
  - **零构建**:纯 ESM JavaScript,无编译步骤,`pnpm add` 即用。
31
34
 
@@ -66,6 +69,16 @@ dsh plugin --profile <profile> add dsh-plugin-memory
66
69
 
67
70
  重启 profile(DSH Desktop 重启应用)后生效。
68
71
 
72
+ > 📌 **版本要求:DSH session format v4(官方 DeepSeek Harness 0.1.7+)**
73
+ >
74
+ > 注入消息的 source 使用 producer-owned kind `plugin:memory`。v4 的原生准入明确拒绝 v3 时代的
75
+ > `{ kind: 'plugin', plugin: 'memory' }` wrapper,报
76
+ > `format v4 message requires a producer-owned source kind`(该错误被包成 `code: "UNKNOWN"`,
77
+ > 所以在界面上会显示成 `... source kind UNKNOWN`——`UNKNOWN` 是错误码,不是 kind 值)。
78
+ >
79
+ > v4 与 v3 的白名单**互斥**(v3 只认 `plugin`),因此无法同时兼容两版。
80
+ > **0.8.0 及更早版本在 v4 上会触发该错误**;旧版 DSH 请停留在 0.8.0。
81
+
69
82
  > ⚠️ **不要**再往 profile 的 `cordis.patch.yml` 里手写 `- insert: {id: dsh-memory, ...}`:
70
83
  > 那会与 bundle manifest 的自动挂载产生两条同名 entry,整个 profile 会以
71
84
  > `duplicate loader entry id "dsh-memory"` 启动失败(2026-08-18 实机事故)。
@@ -159,6 +172,10 @@ dsh plugin --profile <profile> add dsh-plugin-memory
159
172
  dsh-memory init [dir] # 创建记忆库脚手架
160
173
  dsh-memory search <query> [--touch] # 全文检索(--touch 给命中页戳 last_access)
161
174
  dsh-memory touch [pages...] # 手动戳 last_access(不带参数 = 全部页面)
175
+ dsh-memory graph --suggest # 关系报告 + 「这页该连谁」建议(只报告)
176
+ dsh-memory query --type decision --tag dsh --hot --stale [关键词]
177
+ # 结构化检索:先按 frontmatter 过滤,再匹配正文
178
+ dsh-memory checkup [--boot=N] # 一份报告:体量/新鲜度/连接度/一致性 + 优先级行动清单
162
179
  dsh-memory lint # 完整性体检
163
180
  dsh-memory status # 健康概览(含陈旧页统计)
164
181
  dsh-memory pack [out.tar.gz] # 打包导出(含 manifest)
package/lib/boot.js CHANGED
@@ -17,6 +17,11 @@ import { join } from 'node:path'
17
17
  /** Files injected at session start when the config does not override them. */
18
18
  export const DEFAULT_BOOT_FILES = ['SOUL.md', 'MEMORY.md', 'index.md']
19
19
 
20
+ /** Recent-activity headlines carried in the boot block. Three is enough to
21
+ * orient a session; five cost ~90 characters more per request for no extra
22
+ * signal, and this block is injected on every request. */
23
+ export const RECENT_LOG_COUNT = 3
24
+
20
25
  /** Read a file and cap it at `maxChars`, noting truncation when applied. */
21
26
  export function readCapped(path, maxChars) {
22
27
  if (!existsSync(path)) return undefined
@@ -32,6 +37,31 @@ export function readCapped(path, maxChars) {
32
37
  return head + marker
33
38
  }
34
39
 
40
+ /**
41
+ * Read the **last** `maxChars` characters of a file.
42
+ *
43
+ * `readCapped` takes the head, which is right for schema files and wrong for
44
+ * append-only logs: on a 100 KB `log.md` the head is the oldest entries, so the
45
+ * "recent activity" section was quietly showing the *first* five entries the
46
+ * store ever had. Anything that reads a growing timeline from the end needs
47
+ * this instead.
48
+ *
49
+ * @param {string} path
50
+ * @param {number} maxChars
51
+ * @returns {string | undefined}
52
+ */
53
+ export function readTailCapped(path, maxChars) {
54
+ if (!existsSync(path)) return undefined
55
+ try {
56
+ const text = readFileSync(path, 'utf8')
57
+ if (text.length <= maxChars) return text
58
+ // Slice by characters, not bytes: a Chinese entry is ~3 bytes per character.
59
+ return text.slice(text.length - maxChars)
60
+ } catch {
61
+ return undefined
62
+ }
63
+ }
64
+
35
65
  /** Extract the most recent `count` log entries (lines starting with `## [`). */
36
66
  export function parseLogEntries(logText, count = 5) {
37
67
  if (!logText) return []
@@ -219,9 +249,10 @@ export function renderBootBlock(memoryDir, options = {}) {
219
249
 
220
250
  if (sections.length === 0) return ''
221
251
 
252
+ // Read the tail: log.md is append-only, so the head is ancient history.
222
253
  const logPath = join(memoryDir, 'log.md')
223
254
  const logEntries = existsSync(logPath)
224
- ? parseLogEntries(readCapped(logPath, 4096) ?? '', 5)
255
+ ? parseLogEntries(readTailCapped(logPath, 4096) ?? '', RECENT_LOG_COUNT)
225
256
  : []
226
257
  if (logEntries.length > 0) {
227
258
  sections.push(`### 最近动态(log.md 末尾 ${logEntries.length} 条)\n\n${logEntries.map((e) => `- ${e}`).join('\n')}`)
package/lib/checkup.js ADDED
@@ -0,0 +1,235 @@
1
+ /**
2
+ * `dsh-memory checkup`: one report that says what to do next.
3
+ *
4
+ * The plugin grew four readers over time — `lint` (integrity), `status`
5
+ * (counts), the dashboard payload (freshness, connections) and `graph`
6
+ * (relationships) — and a user staring at all four still has to work out which
7
+ * problem matters. This module assembles them into one graded report with a
8
+ * short, ordered action list, because "here are four numbers" is a diagnostic
9
+ * and "do these three things" is a product.
10
+ *
11
+ * Read-only: every value is derived from the store on disk, nothing is written
12
+ * and nothing is inferred that the other readers would disagree with.
13
+ *
14
+ * @module dsh-plugin-memory/checkup
15
+ */
16
+
17
+ import { existsSync, statSync } from 'node:fs'
18
+ import { join } from 'node:path'
19
+ import { accessSummary, listPagesWithMeta, today } from './pages.js'
20
+ import { collectInsights } from './insights.js'
21
+ import { planIndex, INDEX_LINE_MAX, INDEX_SUMMARY_MAX } from './index-page.js'
22
+ import { buildMemoryGraph, suggestLinks } from './graph.js'
23
+
24
+ /** Days without access before a page counts as stale. */
25
+ export const STALE_DAYS = 90
26
+ /** Share of the boot budget the index may take before it is called out. */
27
+ export const INDEX_SHARE_WARN = 0.4
28
+
29
+ const daysBetween = (from, to) => {
30
+ const a = Date.parse(`${from}T00:00:00`)
31
+ const b = Date.parse(`${to}T00:00:00`)
32
+ if (Number.isNaN(a) || Number.isNaN(b)) return undefined
33
+ return Math.floor((b - a) / 86400000)
34
+ }
35
+
36
+ const bar = (count, total, width = 20) => {
37
+ if (total <= 0) return ''
38
+ const filled = Math.max(0, Math.min(width, Math.round((count / total) * width)))
39
+ return '█'.repeat(filled) + '░'.repeat(width - filled)
40
+ }
41
+
42
+ /**
43
+ * Build the checkup report.
44
+ *
45
+ * @param {string} memoryDir absolute path of the memory store
46
+ * @param {{ bootMaxChars?: number, staleDays?: number, indexShareWarn?: number, today?: string }} [options]
47
+ * @returns {{
48
+ * store: string, generatedAt: string,
49
+ * size: { pages: number, chars: number, indexChars: number, indexShare: number, bootMaxChars: number },
50
+ * freshness: { buckets: Array<{ label: string, count: number, bar: string }>, never: number, stale: number },
51
+ * links: { pageLinks: number, tagEdges: number, indexLinks: number, isolated: string[], lonely: number, suggestions: number },
52
+ * integrity: { checks: Array<{ label: string, ok: boolean, detail: string }> },
53
+ * actions: string[],
54
+ * }}
55
+ */
56
+ export function runCheckup(memoryDir, options = {}) {
57
+ const bootMaxChars = options.bootMaxChars ?? 12000
58
+ const staleDays = options.staleDays ?? STALE_DAYS
59
+ const indexShareWarn = options.indexShareWarn ?? INDEX_SHARE_WARN
60
+ const now = options.today ?? today()
61
+
62
+ const pages = listPagesWithMeta(memoryDir)
63
+ const insights = collectInsights(memoryDir)
64
+ const graph = buildMemoryGraph(memoryDir)
65
+ // Findings first (shared topic), then everything else as a fallback: a page
66
+ // with no real relationship must be *counted* as lonely whether or not the
67
+ // heuristic can suggest anyone for it. The previous version derived the count
68
+ // from the suggestion list, so the loneliest pages — the ones with nothing to
69
+ // match on — silently disappeared from the report.
70
+ const findings = suggestLinks(graph)
71
+ const suggestions = suggestLinks(graph, { strengths: ['strong', 'weak'] })
72
+ const access = accessSummary(memoryDir, { staleDays })
73
+
74
+ // ---- 体量 ----
75
+ const indexChars = insights.overview.indexChars ?? insights.overview.indexBytes
76
+ const indexShare = bootMaxChars > 0 ? indexChars / bootMaxChars : 0
77
+
78
+ // ---- 新鲜度 ----
79
+ const buckets = [
80
+ { label: '≤7 天', count: 0 },
81
+ { label: '≤30 天', count: 0 },
82
+ { label: '≤90 天', count: 0 },
83
+ { label: '>90 天', count: 0 },
84
+ ]
85
+ let never = 0
86
+ for (const page of pages) {
87
+ if (page.lastAccess === undefined) {
88
+ never += 1
89
+ continue
90
+ }
91
+ const days = daysBetween(page.lastAccess, now)
92
+ if (days === undefined) { never += 1; continue }
93
+ if (days <= 7) buckets[0].count += 1
94
+ else if (days <= 30) buckets[1].count += 1
95
+ else if (days <= 90) buckets[2].count += 1
96
+ else buckets[3].count += 1
97
+ }
98
+ for (const bucket of buckets) bucket.bar = bar(bucket.count, pages.length)
99
+
100
+ // ---- 连接度 ----
101
+ // An index row is not a relationship: `index.md` links every page by design,
102
+ // so counting it as "connected" would report that nothing needs linking.
103
+ // `lonely` therefore means "connected to nothing except its index row" —
104
+ // which is exactly the set `graph --suggest` can help with.
105
+ const linked = new Set()
106
+ for (const edge of graph.edges) {
107
+ if (edge.kind === 'index') continue
108
+ linked.add(edge.source)
109
+ linked.add(edge.target)
110
+ }
111
+ const lonely = graph.nodes
112
+ .filter((node) => node.kind === 'page' && !linked.has(node.id))
113
+ .map((node) => node.id)
114
+
115
+ // ---- 一致性 ----
116
+ const plan = planIndex(memoryDir)
117
+ const staleLines = plan.lines.filter((line) => line.changed)
118
+ const overCap = plan.lines.filter((line) => line.current.length > INDEX_LINE_MAX)
119
+ const overSummary = plan.lines.filter((line) => line.declaredChars > INDEX_SUMMARY_MAX)
120
+ const missingFrontmatter = pages.filter((page) => page.salience === undefined || page.type === 'unknown')
121
+ const missingSummaryPages = pages.filter((page) => {
122
+ const line = plan.lines.find((entry) => entry.target === page.path)
123
+ return line !== undefined && line.summary.length === 0
124
+ })
125
+ const checks = [
126
+ { label: 'index 链接完整', ok: insights.health.checks.find((c) => c.id === 'index')?.ok ?? true, detail: insights.health.checks.find((c) => c.id === 'index')?.detail ?? '' },
127
+ { label: '无孤儿页', ok: insights.health.checks.find((c) => c.id === 'orphans')?.ok ?? true, detail: insights.health.checks.find((c) => c.id === 'orphans')?.detail ?? '' },
128
+ { label: 'frontmatter 完整', ok: missingFrontmatter.length === 0, detail: missingFrontmatter.length === 0 ? 'title/type/salience 齐全' : `${missingFrontmatter.length} 页缺 type 或 salience` },
129
+ {
130
+ label: 'index 与页面同步',
131
+ ok: staleLines.length === 0,
132
+ detail: staleLines.length === 0 ? '每行都与页面一致' : `${staleLines.length} 行漂移(index --write 可修)`,
133
+ },
134
+ ]
135
+
136
+ // ---- 下一步建议(按"修了最有感"排序)----
137
+ const actions = []
138
+ if (staleLines.length > 0) {
139
+ actions.push(`index 有 ${staleLines.length} 行与页面不一致 → \`dsh-memory index --write\``)
140
+ }
141
+ if (overSummary.length > 0 || overCap.length > 0) {
142
+ actions.push(`${overSummary.length} 个 summary 声明超 ${INDEX_SUMMARY_MAX} 字、${overCap.length} 行超 ${INDEX_LINE_MAX} 字符 → 精简声明或缩短标题`)
143
+ }
144
+ if (lonely.length > 0) {
145
+ actions.push(`${lonely.length} 页只有索引入口、没有内容关系 → \`dsh-memory graph --suggest\``)
146
+ }
147
+ if (missingFrontmatter.length > 0) {
148
+ actions.push(`${missingFrontmatter.length} 页缺 type/salience → 补 frontmatter(lint 会报)`)
149
+ }
150
+ if (missingSummaryPages.length > 0) {
151
+ actions.push(`${missingSummaryPages.length} 页只显示标题(未声明 summary)→ 给页面加 \`summary:\``)
152
+ }
153
+ if (access.stale.length > 0) {
154
+ actions.push(`${access.stale.length} 页超过 ${staleDays} 天未访问 → 整理或归档(优先归档)`)
155
+ }
156
+ if (indexShare > indexShareWarn) {
157
+ actions.push(`index 已占 boot 预算 ${Math.round(indexShare * 100)}% → 精简摘要或拆页,否则会挤掉人格记忆`)
158
+ }
159
+
160
+ return {
161
+ store: memoryDir,
162
+ generatedAt: new Date().toISOString(),
163
+ size: {
164
+ pages: pages.length,
165
+ chars: insights.overview.chars,
166
+ indexChars,
167
+ indexShare,
168
+ bootMaxChars,
169
+ },
170
+ freshness: { buckets, never, stale: access.stale.length },
171
+ links: {
172
+ pageLinks: graph.stats.links,
173
+ tagEdges: graph.stats.tagEdges,
174
+ indexLinks: graph.stats.indexLinks,
175
+ isolated: graph.stats.isolated,
176
+ lonely: lonely.length,
177
+ suggestions: findings.reduce((sum, entry) => sum + entry.candidates.length, 0),
178
+ },
179
+ integrity: { checks },
180
+ actions,
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Render the report for a terminal.
186
+ *
187
+ * @param {ReturnType<typeof runCheckup>} report
188
+ * @param {{ color?: boolean }} [options]
189
+ * @returns {string}
190
+ */
191
+ export function formatCheckup(report, options = {}) {
192
+ const color = options.color === true
193
+ const pct = Math.round(report.size.indexShare * 100)
194
+ const lines = []
195
+ lines.push(`记忆库体检 · ${report.generatedAt.slice(0, 10)}`)
196
+ lines.push('')
197
+ lines.push(`体量 ${report.size.pages} 页 · ${report.size.chars.toLocaleString()} 字符 · `
198
+ + `索引 ${report.size.indexChars.toLocaleString()} 字符(占 boot 预算 ${pct}%)`)
199
+ lines.push('新鲜度')
200
+ for (const bucket of report.freshness.buckets) {
201
+ lines.push(` ${bucket.label.padEnd(7)} ${bucket.bar} ${bucket.count}`)
202
+ }
203
+ if (report.freshness.never > 0) lines.push(` ${'从未戳记'.padEnd(6)} ${report.freshness.never}`)
204
+ lines.push(`连接度 ${report.links.pageLinks} 条页间互链 · ${report.links.tagEdges} 条共享 tag · `
205
+ + `${report.links.indexLinks} 条索引路由`)
206
+ if (report.links.lonely > 0) {
207
+ lines.push(` ${report.links.lonely} 页只有索引入口(${report.links.suggestions} 条候选可参考)`)
208
+ }
209
+ lines.push('一致性')
210
+ for (const check of report.integrity.checks) {
211
+ const mark = check.ok ? '✓' : '!'
212
+ const tint = color && !check.ok ? '\u001b[33m' : ''
213
+ const reset = color && !check.ok ? '\u001b[0m' : ''
214
+ lines.push(` ${tint}${mark} ${check.label} · ${check.detail}${reset}`)
215
+ }
216
+ lines.push('')
217
+ if (report.actions.length === 0) {
218
+ lines.push('没有需要处理的问题 —— 记忆库是健康的。')
219
+ } else {
220
+ lines.push(`最该做的 ${report.actions.length} 件事:`)
221
+ report.actions.forEach((action, index) => lines.push(` ${index + 1}. ${action}`))
222
+ }
223
+ return lines.join('\n')
224
+ }
225
+
226
+ /** `true` when the report contains something worth acting on. */
227
+ export function hasWork(report) {
228
+ return report.actions.length > 0
229
+ }
230
+
231
+ /** Kept for callers that want the raw file size without the full report. */
232
+ export function indexBytes(memoryDir) {
233
+ const path = join(memoryDir, 'index.md')
234
+ return existsSync(path) ? statSync(path).size : 0
235
+ }
@@ -78,9 +78,10 @@ export function lastStoreWriteMs(memoryDir) {
78
78
  * @param {number} staleMinutes how long the store has been unwritten
79
79
  * @param {{ indexHint?: string }} [options] optional routing-table drift line,
80
80
  * rendered on its own so the message stays a checklist, not a paragraph
81
- * @returns {{ id: string, role: 'user', content: [{type:'text', text:string}], source: {kind:'plugin', plugin:string} }}
81
+ * @returns {{ id: string, role: 'user', content: [{type:'text', text:string}], source: {kind:'plugin:memory'} }}
82
82
  */
83
83
  export function buildDigestNudgeMessage(staleMinutes, options = {}) {
84
+ const hint = typeof options.hint === 'string' ? options.hint.trim() : ''
84
85
  const indexHint = typeof options.indexHint === 'string' ? options.indexHint.trim() : ''
85
86
  return {
86
87
  id: `memory-digest-${randomUUID()}`,
@@ -90,12 +91,19 @@ export function buildDigestNudgeMessage(staleMinutes, options = {}) {
90
91
  text: [
91
92
  `【记忆 digest 提醒】距上次记忆写入已超过 ${staleMinutes} 分钟。`,
92
93
  '请现在执行 remember 沉淀:把本次会话值得持久化的关键事实、偏好、决策写回记忆库(更新对应页面与 index.md,并追加 log.md 条目)。',
94
+ // Cross-links are content quality, and nothing else in the system
95
+ // produces them: the graph and every future recall depend on them.
96
+ '顺手给这次碰过的页面各补 1–3 条相关页链接(例:`见 [某页](../decisions/x.md)`)——页面之间的引用是图谱和探索的骨架,不写它就不会存在。',
93
97
  '若本会话确实没有值得持久化的内容,也在 log.md 记一条「## [日期] digest | 无新增」并说明原因——这同样会解除提醒。',
98
+ ...(hint.length > 0 ? [hint] : []),
94
99
  ...(indexHint.length > 0 ? [indexHint] : []),
95
100
  '完成后继续手头的事即可,不要开启新任务。',
96
101
  ].join('\n'),
97
102
  }],
98
- source: { kind: 'plugin', plugin: 'memory' },
103
+ // Session format v4 admits only a producer-owned kind. The retired
104
+ // {kind:'plugin', plugin:'memory'} wrapper is rejected at adoption
105
+ // ("format v4 message requires a producer-owned source kind").
106
+ source: { kind: 'plugin:memory' },
99
107
  }
100
108
  }
101
109
 
package/lib/graph.js CHANGED
@@ -38,6 +38,18 @@ const STOP_TAGS = new Set([
38
38
  'concept', 'concepts', 'user', 'identity', 'fact',
39
39
  ])
40
40
 
41
+ /**
42
+ * Words that name a *bucket* rather than a topic. They are still evidence of
43
+ * shared intent (a page tagged `#skill` is a skill record), just weak evidence:
44
+ * alone they should not draw an edge, together or beside a topic tag they make
45
+ * a reasonable suggestion. `STOP_TAGS` above is the stronger form — pure type
46
+ * words that carry no intent at all.
47
+ */
48
+ const WEAK_TAGS = new Set([
49
+ 'skill', 'skills', 'project', 'projects', 'decision', 'decisions',
50
+ 'concept', 'concepts', 'fact', 'user', 'identity', 'meta',
51
+ ])
52
+
41
53
 
42
54
  /** Stable-ish id for a node: the store-relative path. */
43
55
  const nodeId = (path) => path.replace(/^\.\//, '')
@@ -231,12 +243,24 @@ export function buildMemoryGraph(memoryDir, options = {}) {
231
243
  }
232
244
  node.r = Math.round(radius(node.id) * 10) / 10 + (node.hub ? 4 : 0)
233
245
  node.color = typeColor(node.type)
246
+ // Effective tags exclude container words (skill/project/user…): two pages
247
+ // "sharing" a type word are not related, they are just the same kind.
248
+ node.tagSet = new Set(node.tags.filter((tag) => !stopTags.has(tag)))
249
+ node.weakTags = new Set(node.tags.filter((tag) => WEAK_TAGS.has(tag)))
234
250
  }
235
251
 
252
+ // Suggested links: inference, not fact. Only meaningful for pages that have
253
+ // no real relationship yet — a page already connected by a tag or an explicit
254
+ // link does not need to be told who its neighbours are.
255
+ const suggestions = options.includeSuggestions
256
+ ? suggestLinks({ nodes, edges })
257
+ : []
258
+
236
259
  const isolated = nodes.filter((node) => node.degree === 0 && node.kind === 'page').map((node) => node.id)
237
260
  return {
238
261
  nodes,
239
262
  edges,
263
+ suggestions,
240
264
  stats: {
241
265
  pages: nodes.filter((node) => node.kind === 'page').length,
242
266
  links,
@@ -247,3 +271,125 @@ export function buildMemoryGraph(memoryDir, options = {}) {
247
271
  },
248
272
  }
249
273
  }
274
+
275
+ /**
276
+ * Pages that have no real relationship, and who they should probably link to.
277
+ *
278
+ * A page whose only edge is its `index.md` row is connected in the routing
279
+ * sense and alone in the knowledge sense. This scores candidates by shared
280
+ * tags, same type and title overlap, and returns a short, explainable list —
281
+ * the point is to answer "who should this page cite?", which is the one thing
282
+ * the graph cannot infer from links that do not exist yet.
283
+ *
284
+ * Pure inference: nothing is written, and the caller decides whether to act.
285
+ *
286
+ * @param {{ nodes: Array<object>, edges: Array<object> }} graph from {@link buildMemoryGraph}
287
+ * @param {{ limit?: number, minScore?: number }} [options]
288
+ * @returns {Array<{ page: string, title: string, degree: number, candidates: Array<{ target: string, title: string, score: number, sharedTags: string[], sameType: boolean }> }>}
289
+ */
290
+ export function suggestLinks({ nodes, edges }, options = {}) {
291
+ const limit = Math.max(1, options.limit ?? 3)
292
+ const minScore = options.minScore ?? 3
293
+ // Default to findings only: a shared topic tag or title word.
294
+ const strengths = options.strengths ?? ['strong']
295
+ const pages = (nodes ?? []).filter((node) => node.kind === 'page')
296
+ const byId = new Map(pages.map((node) => [node.id, node]))
297
+
298
+ // Real relationships only: index rows do not count as knowing each other.
299
+ const realNeighbours = new Map()
300
+ for (const edge of edges ?? []) {
301
+ if (edge.kind === 'index') continue
302
+ if (!realNeighbours.has(edge.source)) realNeighbours.set(edge.source, new Set())
303
+ if (!realNeighbours.has(edge.target)) realNeighbours.set(edge.target, new Set())
304
+ realNeighbours.get(edge.source).add(edge.target)
305
+ realNeighbours.get(edge.target).add(edge.source)
306
+ }
307
+
308
+ const lonely = pages
309
+ .filter((node) => (realNeighbours.get(node.id)?.size ?? 0) === 0)
310
+ .sort((a, b) => (b.degree ?? 0) - (a.degree ?? 0))
311
+
312
+ const out = []
313
+ for (const page of lonely) {
314
+ const mine = page.tagSet ?? new Set(page.tags ?? [])
315
+ const myWords = new Set(
316
+ String(page.label).toLowerCase().split(/[^a-z0-9\u4e00-\u9fff]+/).filter((w) => w.length > 2),
317
+ )
318
+ const scored = []
319
+ for (const other of pages) {
320
+ if (other.id === page.id) continue
321
+ const theirs = other.tagSet ?? new Set(other.tags ?? [])
322
+ const sharedTags = [...mine].filter((tag) => theirs.has(tag))
323
+ const weakTags = [...(page.weakTags ?? [])].filter((tag) => (other.weakTags ?? new Set()).has(tag))
324
+ const sameType = page.type !== 'unknown' && page.type === other.type
325
+ const otherWords = String(other.label).toLowerCase().split(/[^a-z0-9\u4e00-\u9fff]+/).filter((w) => w.length > 2)
326
+ const sharedWords = otherWords.filter((w) => myWords.has(w))
327
+ // Weights: a shared topic tag is worth 3, a shared title word 2, a shared
328
+ // bucket tag 1, being the same kind of page 1. Crucially the last two
329
+ // cannot justify a suggestion by themselves — otherwise every skill page
330
+ // "should" link to every other skill page, which is noise, not signal.
331
+ const content = sharedTags.length * 3 + sharedWords.length * 2
332
+ // A page with no effective tags of its own has no topic to overlap on —
333
+ // and it is exactly the page most in need of a suggestion. For those,
334
+ // fall back to the weakest signals (same kind, shared title word) and let
335
+ // the explanation say so instead of staying silent.
336
+ // Two different kinds of "nothing to match on":
337
+ // - no tags at all: the page is genuinely unlabelled, so the weakest
338
+ // signal (being the same kind of page) is all we can offer — advice is
339
+ // still more useful than silence;
340
+ // - only bucket tags (`#skill`): the author did label it, they just did
341
+ // not say with what. Suggesting every other skill page would be noise,
342
+ // so this case still requires a shared title word or topic tag.
343
+ const hasContent = sharedTags.length > 0 || sharedWords.length > 0
344
+ const hasWeak = weakTags.length > 0
345
+ const sameKindOnly = sameType && !hasContent && !hasWeak
346
+ // A shared bucket tag is not a topic, but two pages of the same kind
347
+ // *and* the same bucket ("both are skill records") are still worth
348
+ // linking — that is how a `skills/` set becomes navigable. Without any
349
+ // tags at all we fall back to same-kind alone, remembering the store
350
+ // rarely has more than one distinct type per folder.
351
+ const unlabelled = mine.size === 0 && (page.weakTags?.size ?? 0) === 0 && (page.tags?.length ?? 0) === 0
352
+ const score = content + weakTags.length + (sameType ? 1 : 0)
353
+ const qualifies = hasContent
354
+ ? score >= minScore
355
+ : (hasWeak && sameType) || sameKindOnly || unlabelled
356
+ ? score >= minScore - 2
357
+ : false
358
+ if (qualifies) {
359
+ // Strength, not just score: a suggestion backed by a shared topic is
360
+ // worth writing into the page; "you are both skill pages" is a maybe.
361
+ // The CLI/dashboard filter on this so weak inferences never masquerade
362
+ // as findings.
363
+ const strength = hasContent ? 'strong' : 'weak'
364
+ scored.push({ other, score, sharedTags: [...sharedTags, ...weakTags], sameType, sharedWords, strength })
365
+ }
366
+ }
367
+ scored.sort((a, b) => b.score - a.score || String(a.other.id).localeCompare(String(b.other.id)))
368
+ out.push({
369
+ page: page.id,
370
+ title: page.label,
371
+ degree: page.degree ?? 0,
372
+ candidates: scored.slice(0, limit).map((entry) => ({
373
+ target: entry.other.id,
374
+ title: entry.other.label,
375
+ score: entry.score,
376
+ sharedTags: entry.sharedTags,
377
+ sharedWords: entry.sharedWords,
378
+ sameType: entry.sameType,
379
+ strength: entry.strength,
380
+ // Human-readable reason, so the CLI and the panel never guess.
381
+ reason: [
382
+ entry.sharedTags.length > 0 ? `共享 #${entry.sharedTags.join(' #')}` : '',
383
+ entry.sharedWords.length > 0 ? `标题词 ${entry.sharedWords.join('/')}` : '',
384
+ entry.sharedTags.length === 0 && entry.sharedWords.length === 0 && entry.sameType ? '同类型' : '',
385
+ ].filter(Boolean).join(' · ') || '弱信号',
386
+ })),
387
+ })
388
+ }
389
+ return out
390
+ .map((entry) => ({
391
+ ...entry,
392
+ candidates: entry.candidates.filter((candidate) => strengths.includes(candidate.strength)),
393
+ }))
394
+ .filter((entry) => entry.candidates.length > 0)
395
+ }
package/lib/index-page.js CHANGED
@@ -93,7 +93,27 @@ export function clampSummary(text, max = INDEX_SUMMARY_MAX) {
93
93
  export function clampLabel(title, max = INDEX_LABEL_MAX) {
94
94
  const flat = String(title ?? '').replace(/\s+/g, ' ').trim()
95
95
  if (flat.length <= max) return flat
96
- return `${flat.slice(0, Math.max(1, max - 1)).trimEnd()}…`
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()}…`
97
117
  }
98
118
 
99
119
  /**
package/lib/index.js CHANGED
@@ -520,7 +520,8 @@ export function apply(ctx, config = {}) {
520
520
  }
521
521
  const url = new URL(req.url ?? '/', 'http://localhost')
522
522
  const includeTypeEdges = url.searchParams.get('types') === '1'
523
- const graph = buildMemoryGraph(currentMemoryDir, { includeTypeEdges })
523
+ const includeSuggestions = url.searchParams.get('suggest') === '1'
524
+ const graph = buildMemoryGraph(currentMemoryDir, { includeTypeEdges, includeSuggestions })
524
525
  res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
525
526
  res.end(JSON.stringify(graph))
526
527
  } catch (error) {
package/lib/insights.js CHANGED
@@ -197,6 +197,17 @@ export function collectInsights(memoryDir) {
197
197
 
198
198
  const totalBytes = pages.reduce((sum, p) => sum + p.bytes, 0)
199
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
+ }
200
211
  const logSize = (() => {
201
212
  try {
202
213
  return statSync(join(memoryDir, 'log.md')).size
@@ -218,6 +229,7 @@ export function collectInsights(memoryDir) {
218
229
  bytes: totalBytes,
219
230
  indexEntries: indexEntries.length,
220
231
  indexBytes,
232
+ indexChars,
221
233
  logBytes: logSize,
222
234
  lastWrite: newest > 0 ? new Date(newest).toISOString() : null,
223
235
  neverAccessed: never,
package/lib/pages.js CHANGED
@@ -195,3 +195,44 @@ export function mtimeOf(path) {
195
195
  return 0
196
196
  }
197
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
+ }
@@ -69,7 +69,7 @@ export function listRecallCandidates(memoryDir, count = 3) {
69
69
  * not a command: first-person, Small-Blue voice, explicitly bounded by
70
70
  * "only what's really in memory, never invent, don't repeat yourself".
71
71
  * @param {string[]} candidates optional seed headlines
72
- * @returns {{ id: string, role: 'user', content: [{type:'text', text:string}], source: {kind:'plugin', plugin:string} }}
72
+ * @returns {{ id: string, role: 'user', content: [{type:'text', text:string}], source: {kind:'plugin:memory'} }}
73
73
  */
74
74
  export function buildRecallNudgeMessage(candidates) {
75
75
  const list = Array.isArray(candidates)
@@ -92,7 +92,10 @@ export function buildRecallNudgeMessage(candidates) {
92
92
  seed,
93
93
  ].filter(Boolean).join('\n'),
94
94
  }],
95
- source: { kind: 'plugin', plugin: 'memory' },
95
+ // Session format v4 admits only a producer-owned kind. The retired
96
+ // {kind:'plugin', plugin:'memory'} wrapper is rejected at adoption
97
+ // ("format v4 message requires a producer-owned source kind").
98
+ source: { kind: 'plugin:memory' },
96
99
  }
97
100
  }
98
101
 
package/lib/scaffold.js CHANGED
@@ -106,7 +106,9 @@ export const MEMORY_TEMPLATE = `# MEMORY — 记忆库 schema 与维护协议
106
106
  ## 工作流
107
107
 
108
108
  ### remember(记)
109
- 读源 → 提取关键事实 → 新建/更新相关页 → 补交叉引用 → 标注矛盾 → 更新 \`index.md\` → 追加 \`log.md\`。一次 ingest 常 touch 多页。
109
+ 读源 → 提取关键事实 → 新建/更新相关页 → **补 1–3 条「相关页面」互链(相对路径)** → 标注矛盾 → 更新 \`index.md\` → 追加 \`log.md\`。一次 ingest 常 touch 多页。
110
+
111
+ > 互链不是装饰:\`index.md\` 是目录(谁存在),页间链接是**关系**(谁和谁有关)。图谱、跨页综合、未来的检索都建立在这层关系上——写页时顺手补两三行,比事后补一个功能有用。
110
112
 
111
113
  ### recall(忆)
112
114
  先读 \`index.md\` 定位,再钻页综合;好的答案可回写为新页(让探索复利累积)。
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.7.0",
4
+ "version": "0.8.1",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",
@@ -6,6 +6,8 @@
6
6
  * dsh-memory init [dir] # create the store scaffold (default $MEMORY_DIR or ~/.memory)
7
7
  * dsh-memory search <query> [--touch] # full-text search; --touch stamps last_access on the hits
8
8
  * dsh-memory touch [pages...] # stamp last_access (all pages when none given)
9
+ * dsh-memory graph [--suggest] # relationship report / citation suggestions
10
+ * dsh-memory checkup [--boot=N] # one health report with prioritised actions
9
11
  * dsh-memory index [--check|--write|--sync-frontmatter]
10
12
  * # index routing table: drift / rewrite / import summaries
11
13
  * dsh-memory lint # integrity check (index vs files, orphans, log format)
@@ -25,8 +27,10 @@ import { execFileSync } from 'node:child_process'
25
27
  import { tmpdir, homedir } from 'node:os'
26
28
  import { createHash } from 'node:crypto'
27
29
  import { ensureMemoryScaffold } from '../lib/scaffold.js'
28
- import { touchPages, accessSummary, today } from '../lib/pages.js'
30
+ import { touchPages, accessSummary, today, listPagesWithMeta } from '../lib/pages.js'
29
31
  import { planIndex, applyIndex, indexIssues, syncDeclaredSummaries, INDEX_LINE_MAX } from '../lib/index-page.js'
32
+ import { buildMemoryGraph, suggestLinks } from '../lib/graph.js'
33
+ import { runCheckup, formatCheckup, hasWork } from '../lib/checkup.js'
30
34
 
31
35
  const META = new Set(['SOUL.md', 'MEMORY.md', 'BOOTSTRAP.md', 'index.md', 'log.md'])
32
36
 
@@ -222,6 +226,116 @@ function cmdLint(store) {
222
226
  process.exit(problems.length ? 1 : 0)
223
227
  }
224
228
 
229
+ /**
230
+ * Relationship report: what the graph looks like, and (with `--suggest`) who
231
+ * each under-connected page should probably cite. Suggestion only — the write
232
+ * stays with the agent, per the project's "no automatic rewrites" rule.
233
+ */
234
+ function cmdGraph(store, args) {
235
+ const graph = buildMemoryGraph(store, { includeSuggestions: args.includes('--suggest') })
236
+ const { stats } = graph
237
+ console.log(`graph: ${stats.pages} 页 · ${stats.links} 条页间互链 · ${stats.tagEdges} 条共享 tag · ${stats.indexLinks} 条索引路由`)
238
+ if (stats.isolated.length > 0) {
239
+ console.log(`孤立页(连索引之外没有任何关系):${stats.isolated.length} 个`)
240
+ for (const path of stats.isolated) console.log(` · ${path}`)
241
+ }
242
+ if (!args.includes('--suggest')) {
243
+ console.log('用 `dsh-memory graph --suggest` 查看"这页该连谁"的建议(只报告,不写入)')
244
+ return
245
+ }
246
+ const suggestions = graph.suggestions ?? []
247
+ if (suggestions.length === 0) {
248
+ console.log('没有需要补链的页面 —— 每页都已经有内容层面的关系了')
249
+ return
250
+ }
251
+ console.log('')
252
+ console.log('补链建议(只提示,请自己确认后写进页面):')
253
+ for (const entry of suggestions) {
254
+ console.log(` ${entry.page}`)
255
+ for (const candidate of entry.candidates) {
256
+ console.log(` → ${candidate.target} [${candidate.reason}]`)
257
+ }
258
+ }
259
+ console.log('')
260
+ console.log('写进页面示例:在正文里加 `见 [某页](../path.md)`,图谱与探索都会用到这条边。')
261
+ }
262
+
263
+ /**
264
+ * Structured search.
265
+ *
266
+ * Keyword recall alone cannot answer "every decision tagged #memory-plugin",
267
+ * which is what an agent usually means; this filters on frontmatter first and
268
+ * only then matches text, so the result set is what was actually asked for.
269
+ */
270
+ function cmdQuery(store, args) {
271
+ const filters = { tags: [], type: undefined, salience: undefined, stale: false, hot: false }
272
+ const words = []
273
+ for (let i = 0; i < args.length; i += 1) {
274
+ const arg = args[i]
275
+ if (arg === '--tag' && args[i + 1] !== undefined) filters.tags.push(String(args[i += 1]).replace(/^#/, ''))
276
+ else if (arg === '--type' && args[i + 1] !== undefined) filters.type = args[i += 1]
277
+ else if (arg === '--salience' && args[i + 1] !== undefined) filters.salience = Number(args[i += 1])
278
+ else if (arg === '--stale') filters.stale = true
279
+ else if (arg === '--hot') filters.hot = true
280
+ else if (!arg.startsWith('--')) words.push(arg)
281
+ }
282
+
283
+ const all = listPagesWithMeta(store)
284
+ let matched = all
285
+ if (filters.tags.length > 0) matched = matched.filter((p) => filters.tags.every((t) => p.tags.includes(t)))
286
+ if (filters.type !== undefined) matched = matched.filter((p) => p.type === filters.type)
287
+ if (Number.isFinite(filters.salience)) matched = matched.filter((p) => p.salience === filters.salience)
288
+ if (filters.hot) matched = matched.filter((p) => p.salience === 1)
289
+ if (filters.stale) matched = matched.filter((p) => p.daysSinceAccess === undefined || p.daysSinceAccess > 90)
290
+
291
+ const shown = []
292
+ if (filters.tags.length > 0) shown.push(`#${filters.tags.join(' #')}`)
293
+ if (filters.type !== undefined) shown.push(`type=${filters.type}`)
294
+ if (Number.isFinite(filters.salience)) shown.push(`salience=${filters.salience}`)
295
+ if (filters.hot) shown.push('hot')
296
+ if (filters.stale) shown.push('stale')
297
+ const suffix = shown.length > 0 ? ` (${shown.join(' ')})` : ''
298
+
299
+ if (words.length === 0) {
300
+ console.log(`query: ${matched.length}/${all.length} pages${suffix}`)
301
+ for (const page of matched) {
302
+ console.log(` [s${page.salience ?? '?'}] ${page.path} — ${page.title}`)
303
+ }
304
+ return
305
+ }
306
+
307
+ const needle = words.join(' ').toLowerCase()
308
+ const inScope = new Set(matched.map((p) => p.path))
309
+ const hits = []
310
+ const hitPages = new Set()
311
+ for (const rel of pages(store)) {
312
+ if (!inScope.has(rel)) continue
313
+ const text = readFileSync(join(store, rel), 'utf8')
314
+ for (const [index, line] of text.split('\n').entries()) {
315
+ if (line.toLowerCase().includes(needle)) {
316
+ hits.push(`${rel}:${index + 1}: ${line.trim().slice(0, 160)}`)
317
+ hitPages.add(rel)
318
+ }
319
+ }
320
+ }
321
+ console.log(`query "${words.join(' ')}"${suffix}: ${hitPages.size} page(s) matched`)
322
+ console.log(hits.length > 0 ? hits.join('\n') : ' no matches')
323
+ }
324
+
325
+ /**
326
+ * One report that says what to do next: the four readers (lint / status /
327
+ * insights / graph) each answer a question, but a user still has to work out
328
+ * which problem matters. Exit code is non-zero when there is work, so a cron
329
+ * or a human can both consume it.
330
+ */
331
+ function cmdCheckup(store, args) {
332
+ const bootMaxChars = Number(args.find((a) => a.startsWith('--boot='))?.slice(7)) || 12000
333
+ const report = runCheckup(store, { bootMaxChars })
334
+ const color = !args.includes('--no-color')
335
+ console.log(formatCheckup(report, { color }))
336
+ process.exit(hasWork(report) ? 1 : 0)
337
+ }
338
+
225
339
  function cmdStatus(store) {
226
340
  const ps = pages(store)
227
341
  const bytes = ps.map((p) => statSync(join(store, p)).size).reduce((a, b) => a + b, 0)
@@ -344,6 +458,10 @@ if (args[0] === '--self-test') {
344
458
  init [dir] create the store scaffold
345
459
  search <query> [--touch] full-text search (--touch stamps last_access on hits)
346
460
  touch [pages...] stamp last_access (all pages when none given)
461
+ graph [--suggest] relationship report / "who should this page cite"
462
+ checkup [--boot=N] one health report with a prioritised action list
463
+ query [--tag x] [--type t] [--salience n] [--hot|--stale] [words]
464
+ structured search: frontmatter filters, then text
347
465
  index [--check|--write|--sync-frontmatter]
348
466
  index routing table: report drift / rewrite / import summaries
349
467
  lint integrity check
@@ -355,6 +473,9 @@ Store: $MEMORY_DIR or ./.memory or ~/.memory (current: ${store})`
355
473
  case 'init': cmdInit(store, args.slice(1)); break
356
474
  case 'search': cmdSearch(store, args[1], args.includes('--touch')); break
357
475
  case 'touch': cmdTouch(store, args.slice(1)); break
476
+ case 'graph': cmdGraph(store, args.slice(1)); break
477
+ case 'checkup': cmdCheckup(store, args.slice(1)); break
478
+ case 'query': cmdQuery(store, args.slice(1)); break
358
479
  case 'index': cmdIndex(store, args.slice(1)); break
359
480
  case 'lint': cmdLint(store); break
360
481
  case 'status': cmdStatus(store); break
package/skills/memory.md CHANGED
@@ -15,7 +15,7 @@
15
15
 
16
16
  ## 四个操作
17
17
 
18
- - **remember(记)**:会话中或收尾时,把值得持久化的内容蒸馏成/更新为页面,并同步更新 `index.md`、追加 `log.md`。一条事实可能 touch 多个页(例:一次决策同时更新 `decisions/`、`user/`、`projects/`)。维护 `index.md` 时守**路由表纪律**:一行一页、链接 + 一句话摘要(≤ 80 字)+ `salience`,不写状态流水——index 会被完整注入会话,它膨胀的代价是挤掉别的记忆;一行写不下就说明该拆页或该把细节移进正文。
18
+ - **remember(记)**:会话中或收尾时,把值得持久化的内容蒸馏成/更新为页面,并同步更新 `index.md`、追加 `log.md`。一条事实可能 touch 多个页(例:一次决策同时更新 `decisions/`、`user/`、`projects/`)。**每个新页/改动页补 1–3 条「相关页面」互链**(相对路径,例:`见 [内存面板决策](../decisions/settings-wire-allowlist-bypass.md)`)——互链是记忆网络唯一的骨架,`index.md` 只是目录;不写互链,页面之间就永远没有关系,图谱和探索都只能靠 tag 猜。维护 `index.md` 时守**路由表纪律**:一行一页、链接 + 一句话摘要(≤ 80 字)+ `salience`,不写状态流水——index 会被完整注入会话,它膨胀的代价是挤掉别的记忆;一行写不下就说明该拆页或该把细节移进正文。
19
19
  - **recall(忆)**:先查 `index.md`,再钻具体页;必要时用 `dsh-memory search <关键词>`;读完一批页可用 `dsh-memory touch <pages...>` 补记访问。
20
20
  - **consolidate(整理)**:定期 `dsh-memory lint`——查矛盾、过时声明、孤儿页、缺交叉引用、该归档的冷页;合并重复页;`dsh-memory status` 看陈旧页(>90 天未访问)分布。\n- **index 同步**:index 行**由页面的 frontmatter `summary:` 派生**,不要手写 index 散文。写完页面后:先 `dsh-memory index` 看漂移,再 `dsh-memory index --write` 重写(只改行内容,分节与顺序不动);`--check` 供机器判定(有漂移则退出码非 0);老库可用 `--sync-frontmatter` 把已经写在 index 里的摘要回填进页面。缺 `summary:` 的页面只显示标题——补上它。
21
21
  - **forget(忘)**:显式遗忘(用户要求删除/修正)+ 自动衰减(按 salience 与 last_access,冷页归档或删除,见 `MEMORY.md`)。`last_access` 由插件自动维护(boot 把实际注入的页面戳为当天),你不需要逐日手改,但写页时要保留该字段。