dsh-novel-fade 0.6.0 → 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/CHANGELOG.md ADDED
@@ -0,0 +1,34 @@
1
+ # Changelog
2
+
3
+ ## 0.7.0 — 2026-11-20 · 可核对的记忆
4
+
5
+ ### 新增
6
+
7
+ - **写后收据**:`memo_digest` 返回 `receipt`(`revision` / `artifactId` / `hash` / `cardIds`),随同一次原子写落进 `memory.chapters[N].receipt`;`memo_forget` / `memo_forget restore` 返回 `receipt.revision` 并把 `id` 写进审计。
8
+ - **服务回查**:`novelFade.getStatus` 新增 `lastDigestChapter` / `lastDigestReceipt` / `revisionDrift`;`lastDigest` 改为按 `digestedAt` 取时间最新的一条,不再按最大章号。
9
+ - **简报来源**:`buildBrief` / `getBrief` 返回 `sources`(实际进入简报的 cardIds / chapters / threadIds、L0 总数与漏装数、beatStatus、canonCount、overBudget);模型工具输出仍是 markdown,不增加上下文。
10
+ - **章末体检**:新增 `lib/health.js` 纯函数,14 个检查项(缺章、缺场景单、L0 无锚句、L0 过多、线索到期、legacy 线索、原文缺失/变化、锚句找不到、高光未确认、旧账无收据、版本漂移、简报超预算等);`memo_state` 返回 `health`,右栏总览新增「本章体检」。
11
+ - **原文定位**:`memo_source` / `sourceSlice` 返回 `offset` / `endOffset` / `excerptStart` / `sha256` / `stale`;`locateInSource` 支持跨行、空格与大小写;卡片「回查原句」会高亮,原文改过明确标 stale。
12
+ - **记忆版本**:右栏头部显示 `vN`,footer 显示 `记忆 vN · 快照 …`;`library.json` 的 `contentRevision` 改用 `meta.revision`。
13
+
14
+ ### 修复
15
+
16
+ - `getStatus.cards` 只统计 active 卡(不再把 superseded 算进去)。
17
+ - 曲线不再先截最新 300 张卡:500 章的书保留全段采样。
18
+ - 切书后原文请求携带 `book`,不再读到第一本书的正文;远端对显式传入的未知书返回 `book-not-found`。
19
+ - 简报在 L0 超过 12 张时明确写出「另有 N 张未列入」,并给出 `overBudget`,不再静默漏装或超预算。
20
+ - 旧账本(无 `meta.revision`)读取仍按 `audit.length` 兜底且不写盘;0.7 写入记录 `meta.revisionAt` 检查点,0.6 降级写入后读为 `revisionDrift:true`,不按审计条数伪造 revision。
21
+
22
+ ### 兼容
23
+
24
+ - `memory.json` 仍为 `schemaVersion: 3`;新增字段全部可选,旧账本可直接读。
25
+ - 七个工具名、`/memo` 开关、右栏 tab kind、数据目录、服务 key 全部不变。
26
+ - 0.6 读 0.7 的账本:`receipt` / `revisionAt` 被忽略,不影响渲染。
27
+ - 0.7 读 0.6 的账本:缺 `receipt` 的章在体检里显示 `NO_RECEIPT`(info),不阻断。
28
+
29
+ ### 测试
30
+
31
+ - `npm test`:72 → 100;新增收据、简报来源、体检、定位、客户端契约、面板版本/曲线、library 修复等用例。
32
+ - `npm run check` 全过(含 `check-surface`)。
33
+
34
+ > 0.7.1 计划:记忆时间线、简报工作台、人物记忆视图、pin/unpin(另见系列方案)。
package/README.md CHANGED
@@ -69,18 +69,24 @@ dsh plugin --profile web add github:DrizzleGig/dsh-novel-fade
69
69
  memo_digest(dir, book, chapter, path="正文/第12章.md", cards=[...], sheet={...})
70
70
  ```
71
71
 
72
- `quote` / `ending` / `keyLines` 必须**逐字**来自正文,否则拒收——模型不能凭空补细节。同一章重做要传 `replace: true`,旧卡会被标成 superseded。
72
+ `quote` / `ending` / `keyLines` 必须**逐字**来自正文,否则拒收——模型不能凭空补细节。同一章重做要传 `replace: true`,旧卡会被标成 superseded。返回的 `receipt` 是这一章的落账凭据:`revision`(写后版本)、`artifactId`(`digest:ch12:v2`)、`hash`(正文 sha256)、`cardIds`。
73
73
 
74
74
  ### 5. 看右侧栏
75
75
 
76
- 会话头点「长篇记忆」,右栏出现四个分段:
76
+ 会话头点「长篇记忆」,右栏出现四个分段(0.7.0 的总览里多了「本章体检」和记忆版本 `vN`):
77
77
 
78
78
  | 分段 | 看什么 |
79
79
  |---|---|
80
- | 总览 | 这一章能省多少 token、最近人物与事件、原文贮存状态、生成本章简报 |
81
- | 卡片 | 事件 / 章节 / 人物 / 地点,搜索、按章筛选、"只看已褪" |
82
- | 曲线 | 可及性 × 章节,标出 0.55 的"要翻旧账"线 |
83
- | 原文 | 章节索引 + 按需取片段(≤4000 字) |
80
+ | 总览 | 记忆预算、**本章体检**(缺 digest / L0 无锚句 / 线索到期 / 原文未存)、最近人物与事件、原文贮存状态、生成本章简报 |
81
+ | 卡片 | 事件 / 章节 / 人物 / 地点,搜索、按章筛选、"只看已褪";卡详情可**回查原句并高亮** |
82
+ | 曲线 | 可及性 × 章节,标出 0.55 的"要翻旧账"线;500 章不再只显示末段 |
83
+ | 原文 | 章节索引 + 按需取片段(≤4000 字),显示偏移与 sha 校验;原文改过会标 stale |
84
+
85
+ ## 0.7.0 的三个新能力
86
+
87
+ - **写后可核对**:`memo_digest` / `memo_forget` 返回 `receipt`(revision / artifactId / hash);服务 `novelFade.getStatus` 能回查最近一次 digest 的收据,编排器不再只能信"模型说写完了"。
88
+ - **章末体检**:总览里的「本章体检」把问题分成确定 / 待确认 / 提醒三级,指出哪章缺 digest、哪张 L0 没有逐字锚句、哪条线索过期、哪章原文没存;只读,不自动改记忆。
89
+ - **原文定位**:从卡片的锚句回到原文,返回精确 offset 并高亮;原文与索引的 sha256 对不上时明确标"原文已变化",不静默跳到相似位置。
84
90
 
85
91
  ## 它解决什么
86
92
 
@@ -100,20 +106,20 @@ memo_digest(dir, book, chapter, path="正文/第12章.md", cards=[...], sheet={.
100
106
 
101
107
  | 工具 | 用途 |
102
108
  |---|---|
103
- | `memo_digest` | 写完一章后沉淀事件卡 + 场景卡,并默认把本章正文存进原文贮存;没给 cards 只预览 |
104
- | `memo_brief` | 写下一章前取简报;默认 1400 字,handoff 2200 字;L0 独立成段且不被裁 |
109
+ | `memo_digest` | 写完一章后沉淀事件卡 + 场景卡,并默认把本章正文存进原文贮存;没给 cards 只预览;返回 `receipt`(revision/artifactId/hash) |
110
+ | `memo_brief` | 写下一章前取简报;默认 1400 字,handoff 2200 字;L0 独立成段且不被裁;装了 beat 时 `sources` 给编排器,不进模型上下文 |
105
111
  | `memo_recall` | 按人物 / 地点 / 关键词翻记忆;`deep: true` 才读原文并标记"这是原文" |
106
- | `memo_forget` | 作者主权:软删除 / 恢复,必须写 reason;L0 默认拒删,`force: true` 才删并写审计 |
107
- | `memo_state` | 全书记忆体检:缺 digest 的章、三维分布、L0 分布、beat 状态、预算估算 |
112
+ | `memo_forget` | 作者主权:软删除 / 恢复,必须写 reason;L0 默认拒删,`force: true` 才删并写审计;返回 `receipt.revision` |
113
+ | `memo_state` | 全书记忆体检:缺 digest 的章、三维分布、L0 分布、beat 状态、预算估算,以及结构化 `health` |
108
114
  | `memo_ingest` | 给**旧章**补原文储备(新章由 digest 自动存);不写卡、不调模型 |
109
- | `memo_source` | 按需读原文贮存里的一小段(≤4000 字),只有卡答不上来、要核对原句时才用 |
115
+ | `memo_source` | 按需读原文贮存里的一小段(≤4000 字),只有卡答不上来、要核对原句时才用;返回 offset / sha256 / stale |
110
116
 
111
117
  ## 侧栏四段
112
118
 
113
- - **总览**:左上是记忆预算(原文 token → 记忆 token、少读百分比、累计少读),右上三个迷你统计(人物 / 事件 / 已褪);下面是最新人物、时间轴事件、原文贮存状态和「生成本章简报」。
114
- - **卡片**:搜索 + 事件 / 章节 / 人物 / 地点 / 已褪筛选;点卡原地出详情(三维、因→果、锚句、回查原句),点章节行出**章节档案**(场景 / 关键动作 / 关键句 / 结尾 / 未闭合线索)。
115
- - **曲线**:人物 / 事件 / 章节三条口径,可及性随章衰减,0.55 以下是"细节要翻旧账"区。
116
- - **原文**:只列索引和每章"有几条卡已褪",不加载正文;搜索或点章才取片段。
119
+ - **总览**:左上是记忆预算(原文 token → 记忆 token、少读百分比、累计少读),右上三个迷你统计(人物 / 事件 / 已褪);下面是**本章体检**、最新人物、时间轴事件、原文贮存状态和「生成本章简报」;头部显示记忆版本 `vN`。
120
+ - **卡片**:搜索 + 事件 / 章节 / 人物 / 地点 / 已褪筛选;点卡原地出详情(三维、因→果、锚句、回查原句),点章节行出**章节档案**(场景 / 关键动作 / 关键句 / 结尾 / 未闭合线索);回查原句会定位并高亮,原文改过会标 stale。
121
+ - **曲线**:人物 / 事件 / 章节三条口径,可及性随章衰减,0.55 以下是"细节要翻旧账"区;500 章也保留全段采样。
122
+ - **原文**:只列索引和每章"有几条卡已褪",不加载正文;搜索或点章才取片段,并显示偏移与 sha 校验状态。
117
123
 
118
124
  ## 原文贮存:只存不用
119
125
 
@@ -148,15 +154,15 @@ memo_digest(dir, book, chapter, path="正文/第12章.md", cards=[...], sheet={.
148
154
  | 插件列表名 | 褪色 |
149
155
  | 面板名 | 长篇记忆 |
150
156
  | 包名 | `dsh-novel-fade` |
151
- | 版本 | v0.6.0 |
157
+ | 版本 | v0.7.0 |
152
158
  | 运行环境 | Node.js ≥ 20 |
153
159
  | 外部依赖 | 零依赖(右栏只用 DSH 官方 `sidebarRight*`,不依赖第三方侧栏插件) |
154
160
  | 工具 | 七个 `memo_*` |
155
- | 右栏 RPC | `panel` / `curve` / `chapter` / `sourceIndex` / `sourceSlice` / `brief` / `status` / `setMode`(全部按 `sessionId` 寻址) |
161
+ | 右栏 RPC | `panel` / `curve` / `chapter` / `sourceIndex` / `sourceSlice` / `brief` / `status` / `setMode`(全部按 `sessionId` 寻址;`sourceSlice` 返回 offset/sha/stale) |
156
162
  | 数据目录 | `<工作区>/.dsh-novel-fade/<book>/`(书库索引在 `<DSH_HOME>/dsh-novel-fade/library.json`) |
157
163
  | 记忆分层 | L0 硬契约 / L1 事件 / L2 近期上下文 / L3 归档 |
158
164
  | 衰减 | `accessibility` 随章衰减;0.55 是 precise 的分界;L0 不衰减 |
159
- | 测试 | `npm test` 51/51 |
165
+ | 测试 | `npm test` 100/100 |
160
166
  | 默认状态 | 关闭(`/memo on` 启用) |
161
167
  | 许可 | MIT |
162
168
 
@@ -196,6 +202,8 @@ memo_digest(dir, book, chapter, path="正文/第12章.md", cards=[...], sheet={.
196
202
 
197
203
  ## 更多文档
198
204
 
205
+ - [契约与能力声明(v0.7.0)](https://github.com/DrizzleGig/dsh-novel-fade/blob/main/docs/contract.md)
206
+ - [CHANGELOG](https://github.com/DrizzleGig/dsh-novel-fade/blob/main/CHANGELOG.md)
199
207
  - [设计与开发方案(v0.6 侧栏重制)](https://github.com/DrizzleGig/dsh-novel-fade/blob/main/docs/dsh-novel-fade-v0.6-侧栏重制-设计与开发方案.md)
200
208
  - [侧栏证据(槽位实测)](https://github.com/DrizzleGig/dsh-novel-fade/blob/main/docs/evidence/2026-11-16-侧栏证据.md)
201
209
  - [效果图(设计稿)](https://github.com/DrizzleGig/dsh-novel-fade/blob/main/docs/mockups/panel-v06.png)
package/client.js CHANGED
@@ -378,7 +378,62 @@ window.__ModuleLoader__.load({
378
378
  /* ════════════════════════════════════════════════════════════════════════
379
379
  * 5. Overview
380
380
  * ════════════════════════════════════════════════════════════════════════ */
381
- function Overview({ snapshot, mode, onToggleMode, onGo, onBrief, brief, onFaded }) {
381
+ function HealthCard({ health, onAction }) {
382
+ const [expanded, setExpanded] = React.useState(false)
383
+ const all = Array.isArray(health.issues) ? health.issues : []
384
+ const issues = expanded ? all : all.slice(0, 3)
385
+ const counts = health.counts ?? {}
386
+ const total = (counts.block ?? 0) + (counts.warn ?? 0) + (counts.info ?? 0)
387
+ const tone = counts.block ? T.danger : counts.warn ? T.warn : T.ok
388
+ const label = total
389
+ ? (counts.block || counts.warn ? `本章体检 · ${total} 项待处理` : `本章体检 · ${total} 条提醒`)
390
+ : '本章体检 · 通过'
391
+ return h('div', {
392
+ className: 'fade-card',
393
+ style: { marginTop: 10, borderLeft: `3px solid ${tone}`, paddingLeft: 10 },
394
+ },
395
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 7 } },
396
+ h('span', { style: { width: 7, height: 7, borderRadius: '50%', background: tone, flex: 'none' } }),
397
+ h('span', { style: { fontSize: 12, fontWeight: 600 } }, label),
398
+ h('span', { className: 'fade-grow' }),
399
+ h('span', { className: 'fade-t2' }, `第 ${health.chapter} 章`)),
400
+ issues.length
401
+ ? h('div', { style: { marginTop: 2 } }, issues.map((issue) => h('button', {
402
+ key: issue.id,
403
+ type: 'button',
404
+ className: 'fade-row',
405
+ style: { padding: '7px 0', textAlign: 'left', alignItems: 'flex-start' },
406
+ onClick: () => onAction?.(issue.action),
407
+ },
408
+ h('span', {
409
+ style: {
410
+ width: 3, alignSelf: 'stretch', flex: 'none', borderRadius: 2, marginTop: 2,
411
+ background: issue.severity === 'block' ? T.danger : issue.severity === 'warn' ? T.warn : T.muted,
412
+ },
413
+ }),
414
+ h('div', { className: 'fade-grow' },
415
+ h('div', { style: { fontSize: 11.5, lineHeight: 1.4, whiteSpace: 'normal' } }, issue.title),
416
+ h('div', { className: 'fade-t2', style: { whiteSpace: 'normal', marginTop: 2 } }, issue.detail),
417
+ issue.action?.label
418
+ ? h('span', { style: { color: T.brand, fontSize: 10, fontFamily: T.mono } }, `${issue.action.label} →`)
419
+ : null))))
420
+ : h('div', { className: 'fade-t2', style: { marginTop: 4 } }, '这一章没有发现需要处理的问题。'),
421
+ health.passed?.length
422
+ ? h('div', { className: 'fade-t2', style: { marginTop: 6 } },
423
+ `检查通过 ${health.passed.length} 项:${health.passed.map((item) => item.label).join('、')}`)
424
+ : null,
425
+ all.length > 3
426
+ ? h('button', {
427
+ type: 'button', className: 'fade-chip', style: { marginTop: 6 },
428
+ onClick: () => setExpanded((value) => !value),
429
+ }, expanded ? '收起' : `展开全部 ${all.length} 项`)
430
+ : null,
431
+ h('div', { className: 'fade-t2', style: { marginTop: 5, display: 'flex', justifyContent: 'space-between' } },
432
+ h('span', null, '只读,不自动修改记忆'),
433
+ h('span', null, health.summary ?? '')))
434
+ }
435
+
436
+ function Overview({ snapshot, mode, onToggleMode, onGo, onBrief, brief, onFaded, onHealthAction }) {
382
437
  const overview = snapshot.overview ?? {}
383
438
  const savings = overview.savings ?? {}
384
439
  const decay = overview.decay ?? {}
@@ -450,6 +505,8 @@ window.__ModuleLoader__.load({
450
505
  `另有 ${decay.recalled} 条已经要翻旧账;L0 硬契约 ${decay.hardKept} 条永不褪色。`)
451
506
  : null,
452
507
 
508
+ snapshot.health ? h(HealthCard, { health: snapshot.health, onAction: onHealthAction }) : null,
509
+
453
510
  h('div', { className: 'fade-sec' }, h('h3', null, '最近人物'), h('span', null, '按出场章')),
454
511
  people.length
455
512
  ? h('div', { className: 'fade-list' }, people.slice(0, 5).map((person) => h('button', {
@@ -859,7 +916,28 @@ window.__ModuleLoader__.load({
859
916
  /* ════════════════════════════════════════════════════════════════════════
860
917
  * 8. Source
861
918
  * ════════════════════════════════════════════════════════════════════════ */
862
- function SourceSection({ index, remote, sessionId, inline, fadedChapters }) {
919
+ function SourceExcerpt({ result }) {
920
+ const text = result?.text ?? ''
921
+ if (!text) return h('pre', { className: 'fade-pre' }, '(空)')
922
+ const offset = Number.isInteger(result.offset) ? result.offset : null
923
+ const end = Number.isInteger(result.endOffset) ? result.endOffset : null
924
+ const base = Number.isInteger(result.excerptStart) ? result.excerptStart : 0
925
+ if (offset == null || end == null) return h('pre', { className: 'fade-pre' }, text)
926
+ const start = offset - base
927
+ const stop = end - base
928
+ if (start < 0 || stop <= start || stop > text.length) return h('pre', { className: 'fade-pre' }, text)
929
+ return h('pre', { className: 'fade-pre' },
930
+ text.slice(0, start),
931
+ h('mark', {
932
+ style: {
933
+ background: 'rgba(125,149,251,.28)', color: 'inherit',
934
+ borderRadius: 2, padding: '0 1px',
935
+ },
936
+ }, text.slice(start, stop)),
937
+ text.slice(stop))
938
+ }
939
+
940
+ function SourceSection({ index, remote, sessionId, inline, fadedChapters, book }) {
863
941
  const [term, setTerm] = React.useState(inline?.query ?? '')
864
942
  const [result, setResult] = React.useState(null)
865
943
  const [busy, setBusy] = React.useState(false)
@@ -878,6 +956,7 @@ window.__ModuleLoader__.load({
878
956
  setError(null)
879
957
  try {
880
958
  const value = unwrap(await remote.sourceSlice(sessionId, {
959
+ ...(book ? { book } : {}),
881
960
  chapter: targetChapter,
882
961
  ...(String(targetTerm || '').trim() ? { query: String(targetTerm).trim() } : { from: 0, len: 2000 }),
883
962
  }))
@@ -953,11 +1032,15 @@ window.__ModuleLoader__.load({
953
1032
  result
954
1033
  ? h('div', { style: { marginTop: 8 } },
955
1034
  h('div', { className: 'fade-t2' }, result.ok
956
- ? `第 ${result.chapter} 章 · 偏移 ${result.offset}${result.truncated ? ' · 已截断' : ''}${result.note ? ` · ${result.note}` : ''}`
1035
+ ? `第 ${result.chapter} 章 · 偏移 ${result.offset}${result.endOffset != null ? `–${result.endOffset}` : ''}${result.truncated ? ' · 已截断' : ''}${result.stale === true ? ' · 原文已变化' : result.stale === false ? ' · sha 校验通过' : ''}${result.note ? ` · ${result.note}` : ''}`
957
1036
  : '没取到'),
958
1037
  result.ok
959
- ? h('pre', { className: 'fade-pre' }, result.text || '(空)')
960
- : h('div', { className: 'fade-err', style: { marginTop: 6 } }, result.message ?? result.code ?? '取不到'))
1038
+ ? h(SourceExcerpt, { result })
1039
+ : h('div', { className: 'fade-err', style: { marginTop: 6 } }, result.message ?? result.code ?? '取不到'),
1040
+ result.ok && result.stale === true
1041
+ ? h('div', { className: 'fade-err', style: { marginTop: 6 } },
1042
+ '原文已变化:旧偏移可能不再准确;建议重新 digest 这一章,或重新 memo_ingest。')
1043
+ : null)
961
1044
  : null)
962
1045
  }
963
1046
 
@@ -1115,6 +1198,18 @@ window.__ModuleLoader__.load({
1115
1198
  setSection('source')
1116
1199
  }
1117
1200
 
1201
+ const healthAction = (action) => {
1202
+ if (!action) return
1203
+ if (action.kind === 'brief') {
1204
+ setSection('overview')
1205
+ return
1206
+ }
1207
+ setSection('cards')
1208
+ setKind('events')
1209
+ if (Number.isInteger(action.chapter) && action.chapter > 0) setChapterFilter(action.chapter)
1210
+ if (action.kind === 'card' && action.cardId) setSelected(action.cardId)
1211
+ }
1212
+
1118
1213
  const clearFilter = () => {
1119
1214
  setQuery('')
1120
1215
  setDebounced('')
@@ -1140,6 +1235,13 @@ window.__ModuleLoader__.load({
1140
1235
  onClick: toggleMode,
1141
1236
  title: '切换 /memo on | off',
1142
1237
  }, mode ? '开' : '关'),
1238
+ snapshot?.revision != null
1239
+ ? h('span', {
1240
+ className: 'fade-chip',
1241
+ style: { height: 18, fontSize: 9.5, color: T.muted },
1242
+ title: '记忆版本',
1243
+ }, `v${snapshot.revision}`)
1244
+ : null,
1143
1245
  h('div', { className: 'fade-grow' }),
1144
1246
  h('button', {
1145
1247
  type: 'button', className: 'fade-chip', onClick: () => { clearFilter(); panel.reload() },
@@ -1177,6 +1279,7 @@ window.__ModuleLoader__.load({
1177
1279
  body = h(Overview, {
1178
1280
  snapshot, mode, onToggleMode: toggleMode, onGo: go, onBrief: generateBrief, brief,
1179
1281
  onFaded: () => { setFadedOnly(true); setKind('events'); setSection('cards') },
1282
+ onHealthAction: healthAction,
1180
1283
  })
1181
1284
  } else if (section === 'cards') {
1182
1285
  body = h(CardsSection, {
@@ -1216,6 +1319,7 @@ window.__ModuleLoader__.load({
1216
1319
  body = h(SourceSection, {
1217
1320
  index: sourceIndex, remote, sessionId, inline: sourceCursor,
1218
1321
  fadedChapters: (snapshot.chapters ?? []).filter((row) => row.faded > 0),
1322
+ book: bookPicked ?? snapshot?.book ?? null,
1219
1323
  })
1220
1324
  }
1221
1325
 
@@ -1228,7 +1332,9 @@ window.__ModuleLoader__.load({
1228
1332
  }, label))),
1229
1333
  h('div', { className: 'fade-body' }, body),
1230
1334
  h('div', { className: 'fade-foot' },
1231
- h('span', null, snapshot?.generatedAt ? `快照 ${new Date(snapshot.generatedAt).toLocaleTimeString('zh-CN', { hour12: false })}` : '未加载'),
1335
+ h('span', null, snapshot?.revision != null
1336
+ ? `记忆 v${snapshot.revision} · 快照 ${snapshot.generatedAt ? new Date(snapshot.generatedAt).toLocaleTimeString('zh-CN', { hour12: false }) : '未加载'}`
1337
+ : (snapshot?.generatedAt ? `快照 ${new Date(snapshot.generatedAt).toLocaleTimeString('zh-CN', { hour12: false })}` : '未加载')),
1232
1338
  h('span', null, `${(snapshot?.warnings ?? []).length} 条提示`)))
1233
1339
  }
1234
1340
 
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * dsh-novel-fade — 有损记忆 / 小说记忆插件(v0.6.0)
2
+ * dsh-novel-fade — 有损记忆 / 小说记忆插件(v0.7.0)
3
3
  *
4
4
  * 独立运行:不 import beat,不调用 beat 工具。
5
5
  * 装了 dsh-novel-beat 时,只读 <dir>/.dsh-novel-beat/<book>/book.json 做增强。
@@ -8,6 +8,9 @@
8
8
  */
9
9
  import { toolDefinitions } from './lib/tools.js'
10
10
  import { getSessionMode, setSessionMode } from './lib/store.js'
11
+ import { createFadeService } from './lib/service.js'
12
+
13
+ const VERSION = '0.7.0'
11
14
 
12
15
  export const inject = ['tools', 'commands', 'workingDirectory', 'agents']
13
16
 
@@ -27,9 +30,9 @@ const SKILL = {
27
30
  '',
28
31
  '0. 所有 `memo_*` 的 `dir` 必须传**工作区根目录**,不要传 `正文/`、`章节目录/`。传了章节目录时工具会自动上移,但不要依赖它。',
29
32
  '1. 写下一章前:调用 `memo_brief`,先拿简报再动笔。',
30
- '2. 写完一章后:**立即**调用 `memo_digest`,把本章正文路径和事件卡提交;通常 3–7 张,L0 硬契约多时不受此限(最多 24)。只把正文写进编辑器不算沉淀。',
33
+ '2. 写完一章后:**立即**调用 `memo_digest`,把本章正文路径和事件卡提交;通常 3–7 张,L0 硬契约多时不受此限(最多 24)。只把正文写进编辑器不算沉淀。返回的 `receipt`(revision / artifactId / hash)是这一章落账的凭据,不要丢;重做同章传 `replace:true`。',
31
34
  '3. 用户只让你改正文、或你是在“作家助手”里手写:保存/复制正文后,仍要执行第 2 步;不能因为没经过 `novel_write_chapter` 就跳过。',
32
- '4. 下一章开写前 `memo_state` 检查:缺 digest 的章、未确认高光、到期 thread 先处理。',
35
+ '4. 下一章开写前 `memo_state` 检查:缺 digest 的章、未确认高光、到期 thread 先处理;`health` 里的 block/warn 优先看。',
33
36
  '',
34
37
  '## 七个工具',
35
38
  '',
@@ -37,9 +40,9 @@ const SKILL = {
37
40
  '- `memo_digest(dir, book, chapter, text|path, cards, sheet)`:写完一章后沉淀。quote/ending/keyLines 必须逐字来自正文;没给 cards 只预览。默认顺手把本章正文存进「原文贮存」(只存不用;要关传 `source:false`)。',
38
41
  '- `memo_recall(dir, book, chapter, query|entity|place)`:需要精确细节时翻记忆;`deep:true` 才读原文。',
39
42
  '- `memo_forget(dir, book, ids|query, reason, confirm, force)`:作者主权,软删除;先预览再确认。L0 硬契约默认拒删,只有作者明确要求并传 `force:true` 才能删,且写审计。',
40
- '- `memo_state(dir, book, chapter)`:记忆体检;含 L0/L1/L2/L3 分布与未解决硬契约。',
43
+ '- `memo_state(dir, book, chapter)`:记忆体检;含 L0/L1/L2/L3 分布、未解决硬契约,以及结构化 `health`(L0_OVERLOAD / THREAD_OVERDUE / SOURCE_MISSING / REVISION_DRIFT 等)。',
41
44
  '- `memo_ingest(dir, book, chapter, text|path)`:给**旧章**补原文储备(digest 已自动存新章);不写记忆卡、不调用模型。',
42
- '- `memo_source(dir, book, chapter, query|from|len)`:卡被褪掉、要核对原句时才读一小段(≤4000 字)。',
45
+ '- `memo_source(dir, book, chapter, query|from|len)`:卡被褪掉、要核对原句时才读一小段(≤4000 字);返回 offset/sha256/stale,原文改过会明确标记,不要假装定位准确。',
43
46
  '',
44
47
  '## 四层记忆',
45
48
  '',
@@ -79,6 +82,10 @@ function sessionKey(context) {
79
82
  const TOOL_NAMES = toolDefinitions().map((definition) => definition.name)
80
83
 
81
84
  export async function apply(ctx) {
85
+ const service = createFadeService({ version: VERSION })
86
+ if (typeof ctx.provide === 'function') {
87
+ ctx.effect(() => ctx.provide('novelFade', service))
88
+ }
82
89
  const commands = ctx.get('commands')
83
90
  const workingDirectory = ctx.get('workingDirectory')
84
91
  const agents = ctx.get('agents')
package/lib/brief.js CHANGED
@@ -78,9 +78,12 @@ function canonSection(memory, beat, chapter, cast) {
78
78
  const context = beatContext(beat, chapter, cast)
79
79
  if (context.status !== 'linked') {
80
80
  return {
81
+ id: 'canon',
81
82
  title: '不会记错(账本)',
82
83
  content: `- ${beatStatusLabel(context.status)}。下面只是记忆,不是事实;记忆与作者说法冲突时,以作者为准。`,
83
84
  budget: 120,
85
+ canonCount: 0,
86
+ chapters: [],
84
87
  }
85
88
  }
86
89
  const lines = ['- 已接 beat 账本(只读);记忆与账本冲突时以账本为准。']
@@ -92,7 +95,14 @@ function canonSection(memory, beat, chapter, cast) {
92
95
  lines.push(`- ${late}义务:${obligation.text}${Number.isInteger(obligation.dueChapter) ? `(第 ${obligation.dueChapter} 章前)` : ''}`)
93
96
  }
94
97
  if (lines.length === 0) lines.push('- beat 账本已接,本章没有需要先摆出来的 canon/义务。')
95
- return { title: '不会记错(账本)', content: lines.join('\n'), budget: LIMITS.canon }
98
+ return {
99
+ id: 'canon',
100
+ title: '不会记错(账本)',
101
+ content: lines.join('\n'),
102
+ budget: LIMITS.canon,
103
+ canonCount: context.canon.length,
104
+ chapters: context.canon.map((entry) => entry.chapter).filter(Number.isInteger),
105
+ }
96
106
  }
97
107
 
98
108
  export function buildBrief({ memory, beat, chapter, scene = null, mode = 'chapter', budget } = {}) {
@@ -120,21 +130,26 @@ export function buildBrief({ memory, beat, chapter, scene = null, mode = 'chapte
120
130
  if (!stateLines.includes(line)) stateLines.push(line)
121
131
  }
122
132
 
123
- const hardCards = cards
124
- .filter((card) => card.layer === 'L0' || card.contract?.protected)
125
- .slice(0, 12)
133
+ const hardCards = cards.filter((card) => card.layer === 'L0' || card.contract?.protected)
134
+ const hardShown = hardCards.slice(0, 12)
135
+ const omittedHardCards = Math.max(0, hardCards.length - hardShown.length)
136
+ const canon = canonSection(memory, beat, chapter, cast)
126
137
  const sections = [
127
- { ...canonSection(memory, beat, chapter, cast), protected: true },
138
+ { ...canon, protected: true },
128
139
  ]
129
- if (hardCards.length) {
140
+ if (hardShown.length) {
141
+ const omittedLine = omittedHardCards
142
+ ? `\n- 另有 ${omittedHardCards} 张 L0 未列入本节(共 ${hardCards.length} 张);写前按在场人物 memo_recall。`
143
+ : ''
130
144
  sections.push({
145
+ id: 'hard',
131
146
  title: '必须记住(硬契约)',
132
- content: hardCards.map(hardLine).join('\n'),
147
+ content: `${hardShown.map(hardLine).join('\n')}${omittedLine}`,
133
148
  budget: 360,
134
149
  protected: true,
135
150
  })
136
151
  }
137
- sections.push({ title: '接得上', content: stateLines.join('\n'), budget: handoff ? 760 : 420 })
152
+ sections.push({ id: 'state', title: '接得上', content: stateLines.join('\n'), budget: handoff ? 760 : 420 })
138
153
 
139
154
  if (candidates.length) {
140
155
  const lines = candidates.map((candidate) => {
@@ -148,32 +163,33 @@ export function buildBrief({ memory, beat, chapter, scene = null, mode = 'chapte
148
163
  }
149
164
  return `- [翻旧账] ${candidate.thread.text}`
150
165
  })
151
- sections.push({ title: '接得上(这次要翻的旧账)', content: lines.join('\n'), budget: 220 })
166
+ sections.push({ id: 'old', title: '接得上(这次要翻的旧账)', content: lines.join('\n'), budget: 220 })
152
167
  }
153
168
 
154
169
  sections.push({
170
+ id: 'precise',
155
171
  title: '记得清楚',
156
172
  content: precise.length ? precise.map(cardLine).join('\n') : '- 本章没有高保真细节;需要精确内容先 memo_recall。',
157
173
  budget: handoff ? 360 : 300,
158
174
  })
159
175
  sections.push({
176
+ id: 'faded',
160
177
  title: '只剩印象',
161
178
  content: faded.length ? faded.map(cardLine).join('\n') : '- 没有需要刻意模糊的旧印象。',
162
179
  budget: handoff ? 160 : 120,
163
180
  })
164
181
 
165
- const threadLines = []
166
- for (const thread of threads) {
167
- if (thread.authority === 'fade-note' || thread.legacyNote) continue
168
- threadLines.push(threadLine(thread))
169
- }
182
+ const sourcedThreads = threads.filter((thread) => thread.authority !== 'fade-note' && !thread.legacyNote)
183
+ const threadLines = sourcedThreads.map(threadLine)
170
184
  sections.push({
185
+ id: 'threads',
171
186
  title: '未完成义务与伏笔',
172
187
  content: threadLines.length ? threadLines.join('\n') : '- 没有 fade 侧的未完成线索;beat 义务见账本段。',
173
188
  budget: handoff ? 300 : 220,
174
189
  })
175
190
 
176
191
  sections.push({
192
+ id: 'causal',
177
193
  title: '关键因果',
178
194
  content: causal.length
179
195
  ? causal.map((card) => `- ${card.cause ? `${card.cause} → ` : ''}${card.topic}${card.effect ? ` → ${card.effect}` : ''}`).join('\n')
@@ -190,18 +206,34 @@ export function buildBrief({ memory, beat, chapter, scene = null, mode = 'chapte
190
206
  if (cast.length) hook.push(`- 在场:${cast.join('、')}`)
191
207
  if (scene?.props?.length) hook.push(`- 道具:${scene.props.slice(0, 5).join('、')}`)
192
208
  sections.push({
209
+ id: 'scene',
193
210
  title: '场景接点',
194
211
  content: hook.length ? hook.join('\n') : '- 没给场景;只按当前章开写,不要虚构“上次”。',
195
212
  budget: handoff ? 180 : 140,
196
213
  })
197
214
 
198
215
  sections.push({
216
+ id: 'rules',
199
217
  title: '写作约束',
200
218
  content: '- 记忆与账本冲突时,以账本为准。\n- 标「只剩印象」的项只写大意/情绪,不补人名、数字、对白。\n- 需要精确细节先 memo_recall;仍没有就问作者,不要编。',
201
219
  budget: 100,
202
220
  })
203
221
 
204
- const markdown = renderSections(chapter, sections, requested, handoff)
222
+ const rendered = renderSections(chapter, sections, requested, handoff)
223
+ const markdown = rendered.markdown
224
+ const included = new Set(rendered.includedIds)
225
+ const includeCards = (id, list) => (included.has(id) ? list : [])
226
+ const sourcedCards = [
227
+ ...includeCards('hard', hardShown),
228
+ ...includeCards('precise', precise),
229
+ ...includeCards('faded', faded),
230
+ ...includeCards('causal', causal),
231
+ ...includeCards('state', bridgeCards),
232
+ ]
233
+ const chapterSet = new Set(sourcedCards.map((card) => card.chapter).filter(Number.isInteger))
234
+ if (included.has('state') && sheet) chapterSet.add(chapter - 1)
235
+ if (included.has('canon')) for (const value of canon.chapters) chapterSet.add(value)
236
+ const overBudget = [...markdown].length > requested
205
237
  return {
206
238
  markdown,
207
239
  chars: [...markdown].length,
@@ -209,6 +241,17 @@ export function buildBrief({ memory, beat, chapter, scene = null, mode = 'chapte
209
241
  budget: requested,
210
242
  mode: handoff ? 'handoff' : 'chapter',
211
243
  beatStatus: beat?.status ?? 'absent',
244
+ sources: {
245
+ cardIds: [...new Set(sourcedCards.map((card) => card.id))],
246
+ chapters: [...chapterSet].filter(Number.isInteger).sort((a, b) => a - b),
247
+ threadIds: included.has('threads') ? sourcedThreads.map((thread) => thread.id) : [],
248
+ hardCardCount: hardCards.length,
249
+ shownHardCards: hardShown.length,
250
+ omittedHardCards,
251
+ beatStatus: beat?.status ?? 'absent',
252
+ canonCount: canon.canonCount ?? 0,
253
+ overBudget,
254
+ },
212
255
  stats: {
213
256
  cards: cards.length,
214
257
  hardCards: hardCards.length,
@@ -216,24 +259,30 @@ export function buildBrief({ memory, beat, chapter, scene = null, mode = 'chapte
216
259
  faded: faded.length,
217
260
  candidates: candidates.length,
218
261
  sections: sections.length,
262
+ omittedHardCards,
263
+ overBudget,
219
264
  },
220
265
  }
221
266
  }
222
267
 
223
268
  function renderSections(chapter, sections, budget, handoff) {
224
269
  const head = `# 褪色简报|第 ${chapter} 章${handoff ? '(交接)' : ''}\n`
225
- const body = sections
226
- .filter((section) => section.content && section.content.trim())
270
+ const visible = sections.filter((section) => section.content && section.content.trim())
271
+ const body = visible
227
272
  .map((section) => `## ${section.title}\n${section.content}`)
228
273
  .join('\n\n')
229
274
  const full = `${head}\n${body}`
230
- if ([...full].length <= budget) return full
275
+ if ([...full].length <= budget) {
276
+ return { markdown: full, includedIds: visible.map((section) => section.id) }
277
+ }
231
278
  let remaining = budget - [...head].length - 20
232
279
  const compact = []
280
+ const includedIds = []
233
281
  // L0 hard contracts and canon are protected: never clip them to make room.
234
282
  for (const section of sections.filter((item) => item.protected)) {
235
283
  if (!section.content || !section.content.trim()) continue
236
284
  compact.push(`## ${section.title}\n${section.content}`)
285
+ includedIds.push(section.id)
237
286
  remaining -= [...section.title].length + [...section.content].length + 6
238
287
  }
239
288
  for (const section of sections.filter((item) => !item.protected)) {
@@ -243,7 +292,8 @@ function renderSections(chapter, sections, budget, handoff) {
243
292
  if (max <= 8) continue
244
293
  const content = clip(section.content, max)
245
294
  compact.push(`${title}\n${content}`)
295
+ includedIds.push(section.id)
246
296
  remaining -= [...title].length + [...content].length + 4
247
297
  }
248
- return `${head}\n${compact.join('\n\n')}`
298
+ return { markdown: `${head}\n${compact.join('\n\n')}`, includedIds }
249
299
  }
package/lib/digest.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // lib/digest.js — turn a chapter into cards + a chapter sheet. The model proposes;
2
2
  // this module validates, computes and writes. It never calls an LLM.
3
3
 
4
+ import { createHash } from 'node:crypto'
4
5
  import {
5
6
  LIMITS,
6
7
  fail,
@@ -129,6 +130,7 @@ export function commitDigest(memory, {
129
130
  povDistortions = [],
130
131
  replace = false,
131
132
  linked = false,
133
+ revision = null,
132
134
  } = {}) {
133
135
  if (typeof text !== 'string' || text.trim().length < 10) fail('no-text', '正文太短,至少 10 字')
134
136
  if (!Array.isArray(cards) || cards.length === 0) fail('no-cards', '至少给 1 张事件卡;没有卡就不要 commit')
@@ -194,6 +196,24 @@ export function commitDigest(memory, {
194
196
  cardIds: normalizedCards.map((card) => card.id),
195
197
  supersededCardIds: existing?.cardIds ?? [],
196
198
  }
199
+ // A receipt is the smallest object that lets another plugin re-read this
200
+ // commit: which artifact, which revision, which text hash, which cards.
201
+ // mutation happens before store.js bumps meta.revision, so the revision is
202
+ // passed in (or predicted for direct calls in tests).
203
+ const nextRevision = Number.isInteger(revision)
204
+ ? revision
205
+ : Math.max(Number(memory.meta?.revision) || 0, memory.audit.length) + 1
206
+ const receipt = {
207
+ kind: 'digest',
208
+ artifactId: `digest:ch${chapter}:v${version}`,
209
+ chapter,
210
+ version,
211
+ revision: nextRevision,
212
+ hash: `sha256:${createHash('sha256').update(text, 'utf8').digest('hex')}`,
213
+ cardIds: [...record.cardIds],
214
+ at: record.digestedAt,
215
+ }
216
+ record.receipt = receipt
197
217
  memory.chapters[String(chapter)] = record
198
218
  memory.cards.push(...normalizedCards)
199
219
  memory.audit.push({
@@ -212,6 +232,7 @@ export function commitDigest(memory, {
212
232
  book,
213
233
  chapter,
214
234
  version,
235
+ revision: nextRevision,
215
236
  path: record.path,
216
237
  chars: record.chars,
217
238
  cards: normalizedCards.length,
@@ -220,6 +241,7 @@ export function commitDigest(memory, {
220
241
  entities: Object.keys(memory.entities).length,
221
242
  places: Object.keys(memory.places).length,
222
243
  stats: record.textStats,
244
+ receipt,
223
245
  retention: layerStats(normalizedCards),
224
246
  quality: digestQuality({
225
247
  cards: normalizedCards,