dsh-plugin-memory 0.6.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +46 -0
- package/README.md +53 -12
- package/lib/boot.js +133 -8
- package/lib/checkup.js +235 -0
- package/lib/client.js +643 -2
- package/lib/digest-guard.js +43 -3
- package/lib/graph-drag.js +100 -0
- package/lib/graph-layout.js +137 -0
- package/lib/graph-view.js +98 -0
- package/lib/graph.js +395 -0
- package/lib/index-page.js +419 -0
- package/lib/index.js +130 -6
- package/lib/insights.js +275 -0
- package/lib/pages.js +238 -0
- package/lib/scaffold.js +14 -6
- package/lib/types/index.d.ts +98 -3
- package/package.json +1 -1
- package/scripts/memory.mjs +244 -7
- package/skills/memory.md +4 -4
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,52 @@
|
|
|
2
2
|
|
|
3
3
|
所有记录跟随 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/) 风格;版本号与 `package.json` 保持一致。
|
|
4
4
|
|
|
5
|
+
## [0.8.0] - 2026-09-24
|
|
6
|
+
|
|
7
|
+
### Added(checkup 报告 + 注入瘦身 + 日志修复)
|
|
8
|
+
|
|
9
|
+
- **`dsh-memory checkup [--boot=N]`**(新增 `lib/checkup.js`):把 lint / status / insights / graph 四个读者合成一份报告——体量、新鲜度条形图、连接度、四项一致性检查,末尾是**按优先级排序的行动清单**。设计动机:四个数字是诊断,"最该做的三件事"才是产品。有活干时退出码非 0。`lonely` 的判据是"除 index 行外没有任何关系"(索引是目录,不算关系)。
|
|
10
|
+
- **补链建议分级 strong/weak**:默认只报告有内容信号的建议(共享主题 tag / 标题词),"仅同类型或同桶标签"降级为 weak,需显式请求才返回——否则每个 skill 页都会"应该"连到每个 skill 页。
|
|
11
|
+
- **boot 注入瘦身 23%**(9240 → 7118 字符 ≈ 6160 → 4745 token):`MEMORY.md` 3464 → 1415 字符(与按需加载的 `memory` 技能重叠的 9 个主题交给技能,本文件只留库自己的 schema);动态条数 5 → 3;索引标签按语义截断而非数到第 N 个字符。
|
|
12
|
+
- **修复 `log.md` 读错端**:`renderBootBlock` 用 `readCapped` 取文件**头**,而 log 是 append-only —— 100 KB 的日志意味着每次会话注入的都是**最旧**的 5 条动态。新增 `readTailCapped()` 从尾部按字符读取。影响所有已发布版本。
|
|
13
|
+
|
|
14
|
+
### Added(互链机制 + 补链建议)
|
|
15
|
+
|
|
16
|
+
- **互链升级为默认动作**(`skills/memory.md` / `lib/scaffold.js` / `lib/digest-guard.js`):remember 流程、MEMORY 模板工作流、digest 收尾指令三处都要求「给这次碰过的页面各补 1–3 条相关页链接」。动机是实测数据:一个真实记忆库 29 页里只有 1 条真互链,而图谱、跨页综合、探索全都建立在这层关系上——`index.md` 只是目录。
|
|
17
|
+
- **`dsh-memory query`**:结构化检索——先按 frontmatter 过滤(`--tag` / `--type` / `--salience` / `--hot` / `--stale`,可组合),再在结果集内匹配正文关键词。原来的 `search` 只能逐行 `includes`,而 agent 的真实需求通常是"所有带 #memory-plugin 的决策",不是"含某个词的行"。数据层是新增的 `listPagesWithMeta()`(与看板共用"什么算一页"的口径)。
|
|
18
|
+
- **`dsh-memory graph [--suggest]`**(新增 `suggestLinks()` + 路由 `?suggest=1`):报告关系构成与孤立页;`--suggest` 对「只有索引入口」的页面给出「该引用谁」,按共享主题 tag(3 分)、标题词重合(2 分)、共享桶标签(1 分)、同类型(1 分)打分并输出理由。规则刻意保守:**同类型 + 桶标签本身不足以构成建议**(否则每个 skill 页都"应该"连到每个 skill 页);完全无标签的页面降级为弱建议但会说明理由。只报告、不写入。
|
|
19
|
+
|
|
20
|
+
## [0.7.0] - 2026-09-23
|
|
21
|
+
|
|
22
|
+
### Added(boot 预算按文件分配 + last_access 自动戳记 + 记忆健康看板)
|
|
23
|
+
|
|
24
|
+
- **boot 预算不再平摊**(`lib/boot.js`):旧规则是 `总预算 / 文件数` 平均分给每个文件,于是 `index.md` 一长大,**它的尾部就先被截掉**——agent 连「有这一页」都看不到,更谈不上 drill 进去。现在按文件分配:显式配额(新增 `bootFileBudgets`)→ 其余文件均分且以实际大小封顶 → 余额补回「仍有内容未注入」的文件(`index.md` 优先,其余按体积降序,单个文件最多补到均分额度的两倍)。每个文件都小于均分额度时,结果与旧规则逐字节一致。`bootMaxChars` 默认值同时从 `6000` 提到 `12000`——6000 全量塞不下「人格 + schema + 目录」,默认值偏小正是它被截断的原因之一。
|
|
25
|
+
- **`last_access` 自动戳记**(新增 `lib/pages.js`):`MEMORY.md` 的衰减规则依赖 `last_access`,但它一直是个没人写的字段——模板里有、规则里提到、代码里没有,所以每个页面都原地变老、衰减表形同虚设。现在会话收到第一条真实用户消息时,插件把 boot 块**实际注入到的页面**(boot 文件 + `index.md` 引用到的分类页)戳成当天:每会话一次、按天幂等、只改 `last_access` 一行、无 frontmatter 的页面不碰、`trackPageAccess: false` 可关。
|
|
26
|
+
- **CLI**:新增 `dsh-memory touch [pages...]`(不带参数 = 全部页面),`search` 新增 `--touch`;`status` 增加陈旧页统计(>90 天未访问 / 缺 `last_access`)与最老戳记。
|
|
27
|
+
- **`index.md` 定位为路由表**:脚手架模板、嵌入式 `memory` 技能与 `MEMORY.md` 模板同步写入「一行一页、摘要 ≤ 80 字、不写状态流水」的纪律——它会被完整注入,膨胀的代价是挤掉人格与其他记忆。
|
|
28
|
+
- **记忆健康看板**(新增 `lib/insights.js` + `lib/client.js` 看板卡片 + `GET /api/memory/insights`):设置页「记忆 Memory」区块下方新增**只读**看板——记忆页 / index 路由 / 记忆字数、健康分(孤儿页、缺 frontmatter、陈旧页、失效链接加权)、访问新鲜度条形图(今天 / ≤7 / ≤30 / ≤90 / >90 天 / 从未戳记)、四项体检结论、陈旧页候选、最近 5 条动态。数据每次请求实时统计,**不缓存、不落盘、不写记忆库**;体检口径与 `dsh-memory lint` 同源,二者不会互相打脸;字数按**字符**而非字节计(中文按字节会虚高约 3 倍)。
|
|
29
|
+
|
|
30
|
+
- **index 声明式编译**(新增 `lib/index-page.js` + CLI `dsh-memory index [--check|--write|--sync-frontmatter]`):索引纪律原来只在文档里,实测 85% 的行超标(中位 191 字符、最长 2000+)。现在索引行是**页面 `summary:` 的投影**——编译器绝不自己编话(曾实现"从首句推导摘要",实测把铺垫当要点,已删除该路径)。重写只改行内容、保留分节与顺序、幂等;根元文件永不重写;无 `##` 的扁平索引也能解析。`lint` 增加超长行 / 未声明 summary 检查,与 `index --check` 分工不重复。
|
|
31
|
+
- **digest 提醒附带索引漂移**:会话空闲触发 digest 提醒时,插件顺带跑一次索引检查,把「N 行与页面不一致 / N 个新页未收录 / N 个链接失效」写进提醒正文,`dsh-memory index --write` 即可修复。只在真要提醒时才扫描,不增加空闲开销。
|
|
32
|
+
|
|
33
|
+
- **记忆图谱**(新增 `lib/graph.js` + `lib/graph-layout.js` + `GET /api/memory/graph` + 面板 SVG 卡片):从 markdown 渲染的图是**星形**(index 连所有页,页间几乎不互链——实测 29 页只有 1 条页间链接),它说明"索引列了所有页",不说明"哪些记忆属于一起"。本功能补上页面已经编码、却没人画出来的关系:显式页间链接(解析相对路径,如 `../skills/x.md`)、共享 tag(忽略 `project`/`skill` 这类通用容器 tag;同一 tag 的稠密组走锚点链而不是全连接)。布局在服务端算一次(`layoutGraph`,确定性、无随机、无依赖),客户端只画;`?types=1` 可追加同类型弱边。
|
|
34
|
+
- **图谱交互**(新增 `lib/graph-drag.js`):可拖动节点——按住即 1:1 跟手(拖动期间暂停 CSS 过渡),直接邻居按距离轻微跟随,松手后带缓动滑回原布局;首次渲染从中心绽开;尊重 `prefers-reduced-motion`。拖动数学是**纯函数模块**(`applyDrag` / `releasePositions` / `clampToBox` / `neighbourLean`),因为浏览器半无法 import 本地模块,客户端内联一份 12 行等价实现,并由测试断言两者行为一致。**客户端半首次有了测试**:用 Node `vm` 加载 `client.js`(只注入 `react` stub),真跑 `GraphView` 的元素树,断言"每节点一组、每边一线、边端点跟随实时位置、空图渲染 null"。
|
|
35
|
+
|
|
36
|
+
- **图谱缩放与平移 + 自动刷新**(新增 `lib/graph-view.js`):滚轮以光标为中心缩放(0.4×–2.5×,监听器非 passive,否则设置页会跟着滚)、拖空白处平移、`重置视图`;节点拖动在缩放后依然落在光标下(屏幕→图坐标转换走同一份数学)。图谱每 25 秒轮询一次,记忆变更在面板开着时自己出现(副标题显示更新时间),失败时保留上一张图。视图数学是纯函数模块(`zoomAt`/`panBy`/`toGraphPoint`/`isZoomed`),客户端内联等价实现并由测试断言一致——**该测试当场抓到两份实现的分歧**:客户端写死 `w/4`、模块写 `w×0.4`,最紧视口差 84px。
|
|
37
|
+
|
|
38
|
+
### Fixed
|
|
39
|
+
|
|
40
|
+
- **图谱把 `index.md` 画成了孤岛**:链接遍历只处理"记忆页",整段跳过了元文件——而 `index.md` 恰恰是全库最大的边集(33 条链接到每一页)。结果是在图上 index 度数为 0,看起来跟谁都没关系(阿周实机截图发现)。现在每个节点都参与链接解析,且索引路由是**独立的边类型**(`index`,灰色虚线、权重更低),所以它既是背景总线、又不会把页面之间的真实关系淹没。修复后:index 度数 0 → **32**,孤立页 6 → **0**。
|
|
41
|
+
|
|
42
|
+
- **图谱悬停高亮从未生效**:悬停样式是 `g:not(.lit)`,但没有任何代码给 `<g>` 加过 `lit` 类 —— 悬停会变暗**所有**节点,包括被悬停那个。现在按邻居关系给组加类。
|
|
43
|
+
- **图谱拖动的指针捕获可能抛错**:`setPointerCapture` 在合成事件/边界情况下会抛,一旦抛出整个拖动就死掉。现在包了 try/catch —— 捕获只是优化,丢掉它拖动依然成立(坐标本身已被画布夹取)。
|
|
44
|
+
- **`clampToBox` 把无穷大当成 NaN**:`±Infinity` 是合法方向(应夹到边界),只有 `NaN` 才该回退。修正并补测试。
|
|
45
|
+
- **`lint` 在刚 `init` 的记忆库上误报**:脚手架 `log.md` 模板里的占位行 `## [YYYY-MM-DD] install | ...` 会被自己的 lint 规则判为「malformed entry」。占位行改为引用块(`> ## [...]`),lint 只认真正的 `## ` 行。
|
|
46
|
+
|
|
47
|
+
### Tests
|
|
48
|
+
|
|
49
|
+
- 87/87 全过(新增 `boot-budget` / `pages` / `page-access` / `cli` / `insights` / `insights-route` 六套:预算分配与截断行为、引用提取与戳记语义、插件端「首条用户消息 → 戳记」链路与 `trackPageAccess: false`、CLI 新建库自检与帮助文本、看板数据层(分布/新鲜度/体检/只读性)、看板路由(GET 200 / POST 405 / 跟随 memoryDir 热改))。
|
|
50
|
+
|
|
5
51
|
## [0.6.0] - 2026-09-09
|
|
6
52
|
|
|
7
53
|
### Added(两道礼貌闸门:提问后才注入 + 只注入激活会话)
|
package/README.md
CHANGED
|
@@ -13,7 +13,8 @@
|
|
|
13
13
|
|
|
14
14
|
## 特性
|
|
15
15
|
|
|
16
|
-
-
|
|
16
|
+
- **开机强制注入(带路由表保护)**:插件通过 `ctx.systemPrompt.context()` 把记忆 boot 块(`SOUL.md` 人格 + `MEMORY.md` 协议 + `index.md` 目录 + 最近动态)注入会话上下文。宿主按投影去重:记忆不变就不重复注入,变化时新快照自动取代旧的——这是"新会话必先加载记忆"的**硬保障**,不需要模型碰运气调技能。总预算是 `bootMaxChars`,**按文件分配**:每个文件先拿一份均分(受实际大小封顶),剩余额度优先给 `index.md`、再给尚有内容未注入的文件——所以记忆库长大时,目录的尾部不会先被截掉(详见「boot 预算分配」)。默认还带**两道礼貌闸门**:`deferUntilUserSpeaks`(用户开口后才注入)与 `activeSessionOnly`(只注入当前激活会话),见「配置」。
|
|
17
|
+
- **last_access 自动戳记**:`MEMORY.md` 的 salience 衰减规则依赖 `last_access`,而它以前纯粹靠自觉——模板里有字段、规则里提到它,但没有任何代码去写它,于是每个页面都原地变老、衰减表形同虚设。现在会话收到第一条真实用户消息时,插件会把 boot 块**实际注入过的页面**(`SOUL.md` / `MEMORY.md` / `index.md` + 目录里被引用到的页)戳成当天,每会话一次、按天幂等,只改 `last_access` 一行;`dsh-memory touch <pages...>` 可手动补记,`trackPageAccess: false` 可关闭。
|
|
17
18
|
- **SOUL.md 铸魂**:安装后首要任务是和用户对话定义灵魂(名字、性格、价值观、语气、边界)、确认身份与关系(`BOOTSTRAP.md` 清单驱动,complete 前优先于常规任务)。
|
|
18
19
|
- **铸魂自动引导**:记忆库还没有灵魂(`BOOTSTRAP.md` 非 complete,或 `SOUL.md` 仍是占位模板)时,boot 块会自动前置一段第一人称引导词——「我的首要任务是确认我是谁,还有你是谁:我叫什么名字、怎么称呼你、你我是什么关系、我该是什么样的性格」——像 OpenClaw 初始化那样,**由 agent 在对话里主动发起铸魂**,逐项问、逐项写回,而不是等用户来喂。铸魂完成后引导词自动消失,零开销。
|
|
19
20
|
- **复利记忆**:遵循 Karpathy 的 *LLM Wiki* 约定——记忆是"一次编译、持续保鲜"的持久产物,不是每次查询重新 RAG。remember / recall / consolidate / forget 四操作 + salience 三级衰减。
|
|
@@ -23,6 +24,12 @@
|
|
|
23
24
|
- **主动追忆(拟人化)**:对话空下来时,插件会以第一人称主动提起一件**真实记得**的、关于用户或你们之间的事(偏好、往事、未了的决定、最近的进展),把记忆从"只写回"变成"也用起来"——像老友自然想起那样,而非报状态。间隔在最短/最长之间**随机取值**(不固定节奏),配合每会话限次,不骚扰、不编造、不硬聊;纯对话行为,不写记忆库。**同样独立于 heartbeat**。
|
|
24
25
|
- **git 自动提交**:记忆库变更静默 `autoCommitQuietSeconds` 后自动 `git add -A && git commit`(无 `.git` 则跳过)——历史可回滚不再依赖 agent 记得 commit。
|
|
25
26
|
- **设置面板**:在 DSH 设置页提供「记忆 Memory」区块——总开关、记忆目录、开机注入、技能注册、主动追忆(开关 + 随机间隔范围 + 每会话次数)均可热改,立即生效,无需重启。
|
|
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` 同源。
|
|
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 预算计算索引占比。
|
|
32
|
+
- **记忆健康看板**:同一区块下方是一张**只读**看板——记忆页数 / index 路由数 / 记忆字数、访问新鲜度条形图(今天 / ≤7 / ≤30 / ≤90 / >90 天)、四项体检结论(index 链接、孤儿页、frontmatter、新鲜度)与健康分、陈旧页候选、最近 5 条动态。数据来自新增的 `GET /api/memory/insights`(每次请求实时统计,不缓存),体检口径与 `dsh-memory lint` 同源,所以看板与 CLI 不会互相打脸。
|
|
26
33
|
- **零构建**:纯 ESM JavaScript,无编译步骤,`pnpm add` 即用。
|
|
27
34
|
|
|
28
35
|
## 架构
|
|
@@ -32,14 +39,16 @@
|
|
|
32
39
|
```
|
|
33
40
|
dsh-plugin-memory(本插件)
|
|
34
41
|
├── lib/index.js # Cordis 入口:boot 注入 + 运行时技能注册 + settings 热改
|
|
35
|
-
├── lib/boot.js # boot 块渲染(SOUL/MEMORY/index + 最近 log
|
|
42
|
+
├── lib/boot.js # boot 块渲染(SOUL/MEMORY/index + 最近 log,按文件分配预算)
|
|
43
|
+
├── lib/pages.js # 页面访问记账:extractReferencedPages / touchPages(last_access)
|
|
44
|
+
├── lib/insights.js # 记忆健康看板的数据层(页数/分布/新鲜度/体检,只读)
|
|
36
45
|
├── lib/activity-tracker.js # 两道礼貌闸门:用户是否开口 + 当前激活会话
|
|
37
46
|
├── lib/digest-guard.js # 防懒 digest 唤醒(空闲 + 记忆库久未写 → followup 提醒)
|
|
38
47
|
├── lib/recall-nudge.js # 主动追忆(空闲 → 第一人称提起一件真实往事,纯对话不写库)
|
|
39
48
|
├── lib/scaffold.js # 记忆库脚手架(模板只建不覆盖)
|
|
40
|
-
├── lib/client.js # 客户端半:设置面板「记忆 Memory」区块
|
|
49
|
+
├── lib/client.js # 客户端半:设置面板「记忆 Memory」区块 + 记忆健康看板
|
|
41
50
|
├── skills/memory.md # 内嵌技能的操作协议正文
|
|
42
|
-
└── scripts/memory.mjs # CLI:init/search/lint/status/pack/unpack
|
|
51
|
+
└── scripts/memory.mjs # CLI:init/search/touch/lint/status/pack/unpack
|
|
43
52
|
|
|
44
53
|
记忆库(用户数据,默认 ~/.memory)
|
|
45
54
|
├── SOUL.md # 人格与灵魂(用户主导)
|
|
@@ -74,7 +83,9 @@ dsh plugin --profile <profile> add dsh-plugin-memory
|
|
|
74
83
|
| `enabled` | `true` | 总开关:关闭后不注入 boot 块、不注册 `memory` 技能 |
|
|
75
84
|
| `memoryDir` | `~/.memory` | 记忆库绝对路径(`~` 自动展开) |
|
|
76
85
|
| `bootFiles` | `[SOUL.md, MEMORY.md, index.md]` | 开机注入的文件 |
|
|
77
|
-
| `bootMaxChars` | `
|
|
86
|
+
| `bootMaxChars` | `12000` | boot 块总字符预算(防止占用过多上下文);按文件分配见下文 |
|
|
87
|
+
| `bootFileBudgets` | — | 逐文件字符上限,例如 `{ index.md: 3500 }`;未列出的文件分剩余额度(composition 层,改完需重启) |
|
|
88
|
+
| `trackPageAccess` | `true` | 会话首条用户消息时,把 boot 块实际注入的页面戳 `last_access`(关闭后衰减表需手动维护) |
|
|
78
89
|
| `autoInject` | `true` | 会话开始时注入 boot 块 |
|
|
79
90
|
| `deferUntilUserSpeaks` | `true` | 用户发出第一条真实消息后才注入(boot 块 / 追忆 / digest 提醒都遵守);面板可热改 |
|
|
80
91
|
| `activeSessionOnly` | `true` | 只对「当前激活会话」(最近收到用户消息的会话)注入,后台会话不打扰;面板可热改 |
|
|
@@ -95,10 +106,35 @@ dsh plugin --profile <profile> add dsh-plugin-memory
|
|
|
95
106
|
|
|
96
107
|
### 设置面板(热改)
|
|
97
108
|
|
|
98
|
-
`enabled` / `memoryDir` / `autoInject` / `deferUntilUserSpeaks` / `activeSessionOnly` / `registerSkill` / `recallEnabled` / `recallIntervalMinMinutes` / `recallIntervalMaxMinutes` / `recallMaxPerSession` 十项在 DSH 设置页的「记忆 Memory」区块中可改,**即时生效**:boot 注入、两道礼貌闸门、技能注册、主动追忆(含随机间隔与次数)随修改立即生效;记忆目录切换时自动为新目录初始化脚手架(`scaffold: true` 时)。其余键(`bootFiles` / `bootMaxChars` / `scaffold` / `configFile` / `digestNudge*` / `autoCommit*`)只在 composition 配置层生效,改完需重启。
|
|
109
|
+
`enabled` / `memoryDir` / `autoInject` / `deferUntilUserSpeaks` / `activeSessionOnly` / `registerSkill` / `recallEnabled` / `recallIntervalMinMinutes` / `recallIntervalMaxMinutes` / `recallMaxPerSession` 十项在 DSH 设置页的「记忆 Memory」区块中可改,**即时生效**:boot 注入、两道礼貌闸门、技能注册、主动追忆(含随机间隔与次数)随修改立即生效;记忆目录切换时自动为新目录初始化脚手架(`scaffold: true` 时)。其余键(`bootFiles` / `bootMaxChars` / `bootFileBudgets` / `trackPageAccess` / `scaffold` / `configFile` / `digestNudge*` / `autoCommit*`)只在 composition 配置层生效,改完需重启。
|
|
110
|
+
|
|
111
|
+
### boot 预算分配(为什么 index 不会先被截掉)
|
|
112
|
+
|
|
113
|
+
`bootMaxChars` 是总预算,按文件分配而不是简单平摊:
|
|
114
|
+
|
|
115
|
+
1. 有 `bootFileBudgets` 条目的文件先拿自己的额度;
|
|
116
|
+
2. 其余文件各拿一份均分额度,**以文件实际大小封顶**——短文件把用不完的额度退回池子;
|
|
117
|
+
3. 池子再补给「还有内容没注入」的文件(每个最多补到均分额度的两倍):**`index.md` 优先**,其余按体积降序——所以截断落在哪个文件上由体积决定,而不是由 `bootFiles` 的书写顺序决定。
|
|
118
|
+
|
|
119
|
+
当每个文件都小于均分额度时,结果与旧的平摊规则逐字节相同;只有记忆库长大后才会不同。这也意味着:**`index.md` 是路由表,别把它写成摘要表**——它会被完整注入,膨胀的代价是挤掉人格与其他记忆。
|
|
99
120
|
|
|
100
121
|
> **「当前激活会话」怎么判?** DSH 宿主侧没有「浏览器当前聚焦的会话」信号(激活会话是前端概念)。插件用**最近一次收到真实用户消息的 live root agent**作为激活会话的代理:你在哪个会话里说话,哪个会话就激活;切到别处但不发消息时,宿主感知不到「切换」这个动作(这是代理的已知边界)。若日后需要精确到「展开/聚焦」级别,需补一小段客户端 focus 上报。
|
|
101
122
|
|
|
123
|
+
### 记忆健康看板
|
|
124
|
+
|
|
125
|
+
设置页「记忆 Memory」区块下方是一张**只读**看板,数据来自 `GET /api/memory/insights`:
|
|
126
|
+
|
|
127
|
+
| 展示 | 含义 |
|
|
128
|
+
|---|---|
|
|
129
|
+
| 记忆页 / index 路由 / 记忆字数 | 记忆库规模(字数按字符计,中文不会按字节虚高 3 倍) |
|
|
130
|
+
| 健康分(0–100) | 由孤儿页、缺 `salience`/`type`、陈旧页、失效 index 链接加权得出 |
|
|
131
|
+
| 访问新鲜度条形图 | 今天 / ≤7 / ≤30 / ≤90 / >90 天 / 从未戳记(驱动自 `last_access` 自动戳记) |
|
|
132
|
+
| 四项体检 | index 链接完整、无孤儿页、frontmatter 完整、访问新鲜度——口径与 `dsh-memory lint` 同源 |
|
|
133
|
+
| 陈旧页候选 | 超过 90 天或从未戳记的页面,按陈旧度排序(前 8) |
|
|
134
|
+
| 最近动态 | `log.md` 最新 5 条标题 |
|
|
135
|
+
|
|
136
|
+
看板是**实时**的:每次打开设置页(或改完任一配置项后)重新拉取,不落盘、不缓存、不写记忆库。头less 部署没有 `webServer` 时该路由与看板都不存在,其余功能不受影响。
|
|
137
|
+
|
|
102
138
|
覆盖 composition 键(例如把 boot 块预算调大),在 profile 的 `cordis.patch.yml` 里写**不带 `insert` 的 id 覆盖条目**:
|
|
103
139
|
|
|
104
140
|
```yaml
|
|
@@ -115,18 +151,23 @@ dsh plugin --profile <profile> add dsh-plugin-memory
|
|
|
115
151
|
|
|
116
152
|
## 四个操作
|
|
117
153
|
|
|
118
|
-
- **remember(记)**:把值得持久化的内容蒸馏成页面,同步更新 `index.md`、追加 `log.md`。
|
|
119
|
-
- **recall(忆)**:会话开始读 boot 块;查询时先查 `index.md` 再钻页;必要时 `dsh-memory search
|
|
120
|
-
- **consolidate(整理)**:`dsh-memory lint`
|
|
121
|
-
- **forget(忘)**:显式遗忘立即执行;自动衰减按 salience + last_access
|
|
154
|
+
- **remember(记)**:把值得持久化的内容蒸馏成页面,同步更新 `index.md`、追加 `log.md`。维护 index 时守路由表纪律:一行一页、一句话摘要(≤ 80 字)+ `salience`。
|
|
155
|
+
- **recall(忆)**:会话开始读 boot 块;查询时先查 `index.md` 再钻页;必要时 `dsh-memory search <关键词>`。
|
|
156
|
+
- **consolidate(整理)**:`dsh-memory lint` 查矛盾、孤儿页、该归档的冷页;`dsh-memory status` 看陈旧页分布。
|
|
157
|
+
- **forget(忘)**:显式遗忘立即执行;自动衰减按 salience + last_access(冷页优先归档)。`last_access` 由插件自动维护,无需手改。
|
|
122
158
|
|
|
123
159
|
## CLI
|
|
124
160
|
|
|
125
161
|
```sh
|
|
126
162
|
dsh-memory init [dir] # 创建记忆库脚手架
|
|
127
|
-
dsh-memory search <query>
|
|
163
|
+
dsh-memory search <query> [--touch] # 全文检索(--touch 给命中页戳 last_access)
|
|
164
|
+
dsh-memory touch [pages...] # 手动戳 last_access(不带参数 = 全部页面)
|
|
165
|
+
dsh-memory graph --suggest # 关系报告 + 「这页该连谁」建议(只报告)
|
|
166
|
+
dsh-memory query --type decision --tag dsh --hot --stale [关键词]
|
|
167
|
+
# 结构化检索:先按 frontmatter 过滤,再匹配正文
|
|
168
|
+
dsh-memory checkup [--boot=N] # 一份报告:体量/新鲜度/连接度/一致性 + 优先级行动清单
|
|
128
169
|
dsh-memory lint # 完整性体检
|
|
129
|
-
dsh-memory status #
|
|
170
|
+
dsh-memory status # 健康概览(含陈旧页统计)
|
|
130
171
|
dsh-memory pack [out.tar.gz] # 打包导出(含 manifest)
|
|
131
172
|
dsh-memory unpack <archive> [--force] # 从归档恢复
|
|
132
173
|
```
|
package/lib/boot.js
CHANGED
|
@@ -11,9 +11,17 @@
|
|
|
11
11
|
* @module dsh-plugin-memory/boot
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
|
-
import { existsSync, readFileSync } from 'node:fs'
|
|
14
|
+
import { existsSync, readFileSync, statSync } from 'node:fs'
|
|
15
15
|
import { join } from 'node:path'
|
|
16
16
|
|
|
17
|
+
/** Files injected at session start when the config does not override them. */
|
|
18
|
+
export const DEFAULT_BOOT_FILES = ['SOUL.md', 'MEMORY.md', 'index.md']
|
|
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
|
+
|
|
17
25
|
/** Read a file and cap it at `maxChars`, noting truncation when applied. */
|
|
18
26
|
export function readCapped(path, maxChars) {
|
|
19
27
|
if (!existsSync(path)) return undefined
|
|
@@ -29,6 +37,31 @@ export function readCapped(path, maxChars) {
|
|
|
29
37
|
return head + marker
|
|
30
38
|
}
|
|
31
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
|
+
|
|
32
65
|
/** Extract the most recent `count` log entries (lines starting with `## [`). */
|
|
33
66
|
export function parseLogEntries(logText, count = 5) {
|
|
34
67
|
if (!logText) return []
|
|
@@ -39,6 +72,92 @@ export function parseLogEntries(logText, count = 5) {
|
|
|
39
72
|
return entries.slice(-count)
|
|
40
73
|
}
|
|
41
74
|
|
|
75
|
+
/**
|
|
76
|
+
* Split the boot budget across the injected files.
|
|
77
|
+
*
|
|
78
|
+
* The flat "total / fileCount" rule that shipped originally is what let a
|
|
79
|
+
* growing `index.md` silently fall off the end of the boot block: every file
|
|
80
|
+
* got 1/N, so the directory lost its tail exactly as the store grew — and an
|
|
81
|
+
* agent cannot drill into a page whose index line it never saw.
|
|
82
|
+
*
|
|
83
|
+
* The rule here:
|
|
84
|
+
*
|
|
85
|
+
* 1. each file gets its configured budget, if it has one;
|
|
86
|
+
* 2. every other file gets an even share — clamped to its real size, so a
|
|
87
|
+
* short file hands its unused remainder back to the pool;
|
|
88
|
+
* 3. the pool is handed to whichever files still have unsent content (up to
|
|
89
|
+
* twice the even share each): `index.md` first, then by size, so
|
|
90
|
+
* truncation lands on bulky files no matter their order in `bootFiles`.
|
|
91
|
+
*
|
|
92
|
+
* While every file fits inside its even share this is byte-for-byte the old
|
|
93
|
+
* behaviour; it only starts to differ once the store outgrows its share.
|
|
94
|
+
*
|
|
95
|
+
* @param {string} memoryDir absolute path of the memory store
|
|
96
|
+
* @param {{ files?: string[], total?: number, perFile?: Record<string, number> }} [options]
|
|
97
|
+
* @returns {Map<string, number>} file -> character cap
|
|
98
|
+
*/
|
|
99
|
+
export function allocateBootBudget(memoryDir, options = {}) {
|
|
100
|
+
const files = (options.files ?? []).filter((f) => typeof f === 'string' && f.length > 0)
|
|
101
|
+
const total = Math.max(512, Number(options.total) || 6000)
|
|
102
|
+
const sizeOf = (fileName) => {
|
|
103
|
+
try {
|
|
104
|
+
return statSync(join(memoryDir, fileName)).size
|
|
105
|
+
} catch {
|
|
106
|
+
return 0
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const caps = new Map(files.map((f) => [f, 0]))
|
|
111
|
+
const explicit = options.perFile ?? {}
|
|
112
|
+
const isExplicit = (file) => Number.isFinite(Number(explicit[file])) && Number(explicit[file]) > 0
|
|
113
|
+
let pool = total
|
|
114
|
+
|
|
115
|
+
// 1. explicit per-file budgets (composition layer only)
|
|
116
|
+
for (const file of files) {
|
|
117
|
+
if (!isExplicit(file)) continue
|
|
118
|
+
const cap = Math.min(Number(explicit[file]), pool)
|
|
119
|
+
caps.set(file, cap)
|
|
120
|
+
pool -= cap
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// 2. an even share for the rest, clamped to real size (index first only so
|
|
124
|
+
// an exactly-even pool is never split awkwardly by ordering)
|
|
125
|
+
const flexible = files.filter((f) => !isExplicit(f))
|
|
126
|
+
if (flexible.length > 0 && pool > 0) {
|
|
127
|
+
const share = Math.floor(pool / flexible.length)
|
|
128
|
+
const order = [
|
|
129
|
+
...flexible.filter((f) => f === 'index.md'),
|
|
130
|
+
...flexible.filter((f) => f !== 'index.md'),
|
|
131
|
+
]
|
|
132
|
+
for (const file of order) {
|
|
133
|
+
const cap = Math.min(share, sizeOf(file))
|
|
134
|
+
caps.set(file, cap)
|
|
135
|
+
pool -= cap
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// 3. the remainder goes to files that still have content left unsent. Each
|
|
140
|
+
// may grow to at most twice the even share, so the pool funds whatever is
|
|
141
|
+
// actually long without letting one file swallow the whole block; index
|
|
142
|
+
// still comes first because its tail is what an agent navigates by.
|
|
143
|
+
const ceiling = Math.max(1, Math.floor((total / Math.max(1, flexible.length)) * 2))
|
|
144
|
+
const wanting = () => flexible
|
|
145
|
+
.filter((f) => sizeOf(f) > caps.get(f) && caps.get(f) < ceiling)
|
|
146
|
+
.sort((a, b) => {
|
|
147
|
+
if (a === 'index.md') return -1
|
|
148
|
+
if (b === 'index.md') return 1
|
|
149
|
+
return sizeOf(b) - sizeOf(a)
|
|
150
|
+
})
|
|
151
|
+
for (let file = wanting()[0]; file !== undefined && pool > 0; file = wanting()[0]) {
|
|
152
|
+
const cap = Math.min(pool, sizeOf(file) - caps.get(file), ceiling - caps.get(file))
|
|
153
|
+
if (cap <= 0) break
|
|
154
|
+
caps.set(file, caps.get(file) + cap)
|
|
155
|
+
pool -= cap
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
return caps
|
|
159
|
+
}
|
|
160
|
+
|
|
42
161
|
/**
|
|
43
162
|
* Soul-bootstrap directive rendered into the boot block while the store has
|
|
44
163
|
* no soul yet (BOOTSTRAP.md status !== 'complete'). First-person,
|
|
@@ -97,37 +216,43 @@ export function needsSoulBootstrap(memoryDir) {
|
|
|
97
216
|
*
|
|
98
217
|
* Reads SOUL.md / MEMORY.md / index.md (configurable) capped to a total
|
|
99
218
|
* budget, plus the most recent log entries for cross-session continuity.
|
|
219
|
+
* The budget is split by {@link allocateBootBudget}, which protects the
|
|
220
|
+
* `index.md` routing table from being starved as the store grows.
|
|
100
221
|
* While the store has no soul yet (BOOTSTRAP not complete / SOUL still a
|
|
101
222
|
* template), the first-person {@link SOUL_DIRECTIVE} is prepended so the
|
|
102
223
|
* agent opens the soul-definition conversation on its own — the same
|
|
103
224
|
* onboarding the user gets with a fresh OpenClaw instance.
|
|
104
225
|
*
|
|
105
226
|
* @param {string} memoryDir absolute path of the memory store
|
|
106
|
-
* @param {{ bootFiles?: string[], bootMaxChars?: number }} options
|
|
227
|
+
* @param {{ bootFiles?: string[], bootMaxChars?: number, bootFileBudgets?: Record<string, number> }} options
|
|
107
228
|
* @returns {string} the model-facing boot block; '' when the store is empty
|
|
108
229
|
*/
|
|
109
230
|
export function renderBootBlock(memoryDir, options = {}) {
|
|
110
231
|
const bootFiles = options.bootFiles && options.bootFiles.length > 0
|
|
111
232
|
? options.bootFiles
|
|
112
|
-
:
|
|
233
|
+
: DEFAULT_BOOT_FILES
|
|
113
234
|
const total = Math.max(512, options.bootMaxChars ?? 6000)
|
|
114
|
-
const
|
|
235
|
+
const caps = allocateBootBudget(memoryDir, {
|
|
236
|
+
files: bootFiles,
|
|
237
|
+
total,
|
|
238
|
+
perFile: options.bootFileBudgets,
|
|
239
|
+
})
|
|
115
240
|
|
|
116
241
|
const sections = []
|
|
117
|
-
let injected = 0
|
|
118
242
|
for (const fileName of bootFiles) {
|
|
119
243
|
const path = join(memoryDir, fileName)
|
|
120
|
-
const
|
|
244
|
+
const cap = caps.get(fileName) ?? 0
|
|
245
|
+
const text = cap > 0 ? readCapped(path, cap) : undefined
|
|
121
246
|
if (text === undefined || text.trim() === '') continue
|
|
122
247
|
sections.push(`### ${fileName}\n\n${text}`)
|
|
123
|
-
injected += Math.min(text.length, perFile)
|
|
124
248
|
}
|
|
125
249
|
|
|
126
250
|
if (sections.length === 0) return ''
|
|
127
251
|
|
|
252
|
+
// Read the tail: log.md is append-only, so the head is ancient history.
|
|
128
253
|
const logPath = join(memoryDir, 'log.md')
|
|
129
254
|
const logEntries = existsSync(logPath)
|
|
130
|
-
? parseLogEntries(
|
|
255
|
+
? parseLogEntries(readTailCapped(logPath, 4096) ?? '', RECENT_LOG_COUNT)
|
|
131
256
|
: []
|
|
132
257
|
if (logEntries.length > 0) {
|
|
133
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
|
+
}
|