focus-guard 3.5.1 → 3.5.3

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.
Files changed (102) hide show
  1. package/README.md +17 -5
  2. package/README.zh-CN.md +15 -5
  3. package/assets/NOTICE.md +2 -0
  4. package/docs/ARCH-MAP.md +33 -20
  5. package/docs/BENCH.md +21 -12
  6. package/docs/RELEASE-POLICY.md +84 -19
  7. package/docs/RULES.md +75 -55
  8. package/docs/THREAT-MODEL.md +1 -1
  9. package/docs/WRITING-STYLE.md +1 -1
  10. package/package.json +11 -6
  11. package/skills/focus-plan/SKILL.md +77 -0
  12. package/skills/focus-rules/SKILL.md +267 -0
  13. package/skills/focus-thinking/SKILL.md +8 -255
  14. package/src/adapters/dsh/eligibility-gate.mjs +43 -23
  15. package/src/adapters/dsh/session.mjs +22 -0
  16. package/src/core/approvals.mjs +10 -4
  17. package/src/core/audit-writer.mjs +5 -2
  18. package/src/core/checkEligibility.mjs +190 -129
  19. package/src/core/constants.mjs +1 -1
  20. package/src/core/decisionEngine.mjs +16 -13
  21. package/src/core/env.mjs +18 -0
  22. package/src/core/patterns.mjs +3 -1
  23. package/src/core/prefixStability.mjs +27 -3
  24. package/src/core/session.mjs +23 -0
  25. package/src/dsh/audit.mjs +21 -7
  26. package/src/dsh/bridgeCheck.mjs +81 -0
  27. package/src/dsh/compactionWatch/announce.mjs +2 -1
  28. package/src/dsh/compactionWatch.mjs +2 -1
  29. package/src/dsh/guard/authz.mjs +2 -2
  30. package/src/dsh/guard/retryGuard.mjs +96 -0
  31. package/src/dsh/guard/risk.mjs +61 -16
  32. package/src/dsh/guard/runtime.mjs +30 -5
  33. package/src/dsh/guard/tooling.mjs +5 -9
  34. package/src/dsh/guard/writing-gate.mjs +117 -0
  35. package/src/dsh/index.js +4 -7
  36. package/src/dsh/pipeline.mjs +66 -5
  37. package/src/dsh/preGuard.mjs +11 -2
  38. package/src/dsh/repeatGuard.mjs +5 -4
  39. package/src/dsh/seams/session-start.mjs +49 -10
  40. package/src/dsh/seams/shared.mjs +8 -5
  41. package/src/dsh/search-hints.mjs +15 -1
  42. package/src/dsh/sessionScope.mjs +11 -11
  43. package/src/dsh/stopGuard.mjs +2 -7
  44. package/src/dsh/tools.mjs +39 -1
  45. package/src/dsh/traceMeta.mjs +5 -11
  46. package/src/memory/index.mjs +4 -4
  47. package/src/memory/workspace.mjs +41 -19
  48. package/tools/capture-fixtures.mjs +3 -24
  49. package/tools/collect-panel.mjs +3 -24
  50. package/tools/dead-export.mjs +2 -17
  51. package/tools/docs-book.mjs +234 -0
  52. package/tools/docs-drift.mjs +165 -0
  53. package/tools/docs-lint.mjs +24 -0
  54. package/tools/first-run-sweep.mjs +13 -2
  55. package/tools/gate-audit.mjs +3 -24
  56. package/tools/handoff.mjs +3 -1
  57. package/tools/install-check.mjs +294 -0
  58. package/tools/layering-audit.mjs +7 -1
  59. package/tools/legacy-audit.mjs +83 -0
  60. package/tools/lib/case-tool.mjs +8 -2
  61. package/tools/lib/docs-ack.mjs +95 -0
  62. package/tools/lib/docs-core.mjs +38 -22
  63. package/tools/lib/docs-files.mjs +73 -0
  64. package/tools/lib/docs-status.mjs +143 -0
  65. package/tools/lib/idioms.mjs +149 -0
  66. package/tools/lib/import-graph.mjs +8 -3
  67. package/tools/lib/legacy-core.mjs +178 -0
  68. package/tools/lib/markdown.mjs +202 -0
  69. package/tools/lib/modules-doc.mjs +96 -0
  70. package/tools/lib/modules-list.mjs +382 -0
  71. package/tools/lib/modules.mjs +312 -0
  72. package/tools/lib/prefix-cost.mjs +5 -3
  73. package/tools/library-book.mjs +7 -92
  74. package/tools/lint.mjs +5 -0
  75. package/tools/memory-audit.mjs +32 -6
  76. package/tools/memory-recall-eval.mjs +408 -0
  77. package/tools/module-audit.mjs +2 -17
  78. package/tools/modules-audit.mjs +108 -0
  79. package/tools/panel-baseline.mjs +172 -0
  80. package/tools/prefix-audit.mjs +10 -2
  81. package/tools/prefix-drift.mjs +9 -4
  82. package/tools/registry-check.mjs +194 -0
  83. package/tools/release.mjs +374 -0
  84. package/tools/schema-fingerprint.mjs +3 -24
  85. package/tools/version.mjs +12 -8
  86. package/docs/AB-PROMPTS.md +0 -123
  87. package/docs/AB-SESSION.md +0 -161
  88. package/docs/BENCH-BASELINE.json +0 -95
  89. package/docs/BRAIN-VIZ.md +0 -94
  90. package/docs/GATE-INPUTS.json +0 -10
  91. package/docs/HANDOFF-2026-10-27.md +0 -736
  92. package/docs/HOOK-ORDERING.md +0 -139
  93. package/docs/LEGISLATION-LAW.md +0 -104
  94. package/docs/MCP-4.0-PLAN.md +0 -184
  95. package/docs/MEMORY-4.5-PLAN.md +0 -415
  96. package/docs/PROFILE-TUNING.md +0 -147
  97. package/docs/RATCHET.json +0 -72
  98. package/docs/TOOL-SCHEMA.json +0 -6
  99. package/docs/VERSION-PLAN.md +0 -604
  100. package/docs/architecture-map.mermaid +0 -186
  101. package/docs/deepseek-pricing-audit.md +0 -65
  102. package/src/dsh/guard/superpowers.mjs +0 -70
@@ -21,21 +21,15 @@
21
21
  * 落盘:回合结束时由 `recordFuseWaste()` 写一行 `action:"fuse-waste"`(**只在真熔断过的回合**写,不是每步一行)。
22
22
  */
23
23
  import { appendAudit, buildAuditRow, setTraceMetaProvider } from '../core/audit-writer.mjs'
24
+ import { sidOf as sidOfAny, UNKNOWN_SESSION } from './sessionScope.mjs'
24
25
 
25
26
  /** sid → { turn, step, fuseTurn, fuseStep } */
26
27
  const sessions = new Map()
27
28
 
28
- /** 会话键:接受 agent 对象或 session id 字符串。 */
29
+ /** 会话键:接受 agent 对象或 session id 字符串(口径统一走 `sessionScope.sidOf`)。 */
29
30
  function keyOf(agentOrSession) {
30
- if (typeof agentOrSession === 'string') return agentOrSession || 'dsh-native'
31
- const agent = agentOrSession
32
- return (
33
- (agent &&
34
- ((agent.session && agent.session.header && agent.session.header.id) ||
35
- agent.sessionId ||
36
- agent.id)) ||
37
- 'dsh-native'
38
- )
31
+ if (typeof agentOrSession === 'string') return agentOrSession || UNKNOWN_SESSION
32
+ return sidOfAny(agentOrSession)
39
33
  }
40
34
 
41
35
  /**
@@ -69,7 +63,7 @@ export function currentPosition(agentOrSession) {
69
63
  * 在写入器这一处识别比逐个改调用点更不容易漏。
70
64
  */
71
65
  function traceMetaOf(session, row) {
72
- const key = String(session || 'dsh-native')
66
+ const key = String(session || UNKNOWN_SESSION)
73
67
  const pos = sessions.get(key)
74
68
  if (!pos) return null
75
69
  if (row && row.action === 'stall-fuse' && pos.fuseTurn === null) {
@@ -4,10 +4,10 @@
4
4
  * 分层纪律:本模块不 import 任何 `src/dsh/`;宿主适配层只准 import 这里。
5
5
  * 旧路径 `src/dsh/workspace.mjs` 保留转发,调用方不必改。
6
6
  *
7
- * 注入边界(2026-11-02 人类批示):
8
- * ① 不新开 `focus-guard-memory` 段——记忆只并进已有的 `focus-guard-workspace`,
9
- * 同一 owner、同一尾部位置,避免与宿主记忆插件抢段。
10
- * ② FG 只注入**约束类**内容(决策 / 被否决的命令 / 熔断);
7
+ * 注入边界(2026-11-02 定,2026-11-22 更新):
8
+ * ① 不新开 `focus-guard-memory` 段;原 `focus-guard-workspace` 段自 2026-11-22 起
9
+ * **不再常驻注入**,改为 `fg_workspace` 工具按需拉取(前缀更短、缓存更稳)。
10
+ * ② FG 只记录**约束类**内容(决策 / 被否决的命令 / 熔断);
11
11
  * 用户偏好归 DSH 的 self-improvement,两边不重复写。
12
12
  * ③ 静态知识库与人格档**不进注入**:前者只在 `tools/` 离线落索引,后者待裁决。
13
13
  */
@@ -13,12 +13,34 @@
13
13
  * · 不 cancel、不 reject、不写 surface —— 只读文件、只追加系统提示 section;
14
14
  * · 不伪造 user 消息(DSH 0.2 的 UserMessage 走 runtime context 投影,硬塞会断);
15
15
  * · 写失败只 warn,绝不阻断回合。
16
+ *
17
+ * ⚠ 下架声明:decisions 自动落账与注入**已于 2026-11-26 下架**(功能有缺陷,非重构)。
18
+ *
19
+ * 缺陷:它写的不是决策。`recordWorkspaceTurn` 拿的是 `state.turnPrompt`,剥首行、
20
+ * 限 120 字就存成一条「决策」——存进去的是**问句和训话**,不是结论。
21
+ * 实测本仓 `.focus-guard/workspace.json` 的 10 条里,0 条是决策,4 条是提问/质疑,
22
+ * 最短一条是 `?UI?`(4 字符)。根因是 FG 只看得见 prompt,看不见「选 A 不选 B,因为 C」;
23
+ * 同一个病仓库自己已记过一次:`next_action` 恒为 0(MEMORY-4.5-PLAN §8.1)。
24
+ *
25
+ * 为什么是下架而不是就地修:正确形态需要「谁做决定谁来写结论」的显式入口 +
26
+ * 证据可校验(`[goal]` / `[note]` 标签体系已备好,见 `tags.mjs`),属 MEMORY-4.5 的 A4/C2,
27
+ * 不在 3.5.x 补丁位里。排期见 `VERSION-PLAN.md` §1.9「下架登记」。
28
+ *
29
+ * 下架后的行为:**不写**(`recordWorkspaceTurn` 不再产出 decisions)、
30
+ * **不注入**(`renderWorkspaceSection` 不再输出「决策:」行)。
31
+ * 字段与 `fg case` 读取路径保留,只为存量清理与人工查看;存量原文需人工删
32
+ * (`fg case rm` 或直接删 `.focus-guard/workspace.json`),不自动迁移——
33
+ * 它本来就不是决策,迁移只是给错的东西换个名字。
34
+ *
35
+ * 恢复条件(三条同时满足才可重新接入):显式写入入口存在、条目带 `[goal]`/`[note]` 标签、
36
+ * 有「结论能否被后续证据推翻」的校验。缺一条就是在重演这次的坑。
16
37
  */
17
38
 
18
39
  import { createHash } from 'node:crypto'
19
40
  import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs'
20
41
  import { dirname } from 'node:path'
21
42
  import { fileURLToPath } from 'node:url'
43
+ import { resolveSid } from '../core/session.mjs'
22
44
  import { statePath, loadState } from '../core/state.mjs'
23
45
 
24
46
  /** 默认落点:仓库根 `.focus-guard/workspace.json`(该目录在本地 exclude 里,2026-10-30 起不再写进 .gitignore)。 */
@@ -106,6 +128,11 @@ function clean(list) {
106
128
  * 指令质量筛选(2026-10-22):只留"像一条人类指令"的文本。
107
129
  * 剔掉:多行/表格/代码块粘贴、终端报错、超长转述、子代理回执。
108
130
  * 判据保守——宁可少记,也不要让卷宗变成垃圾桶。
131
+ *
132
+ * @deprecated 2026-11-26 起**无生产调用**(decisions 已下架,见文件头「下架声明」)。
133
+ * 保留原因:`workspace-quality.test.mjs` 仍锁它的行为,且 4.5 若恢复显式写入入口,
134
+ * 这套「什么算一条指令」的判据可复用。**但别把它当作可用的决策抽取器**——
135
+ * 它做的是过滤 prompt,不是从对话里提炼结论;七条规则再多也变不出「选 A 因为 C」。
109
136
  */
110
137
  export function pickDecisionText(raw) {
111
138
  const text = String(raw ?? '').replace(/\r/g, '').trim()
@@ -162,15 +189,11 @@ export function renderWorkspaceSection(record, opts = {}) {
162
189
  const snap = showSnapshot
163
190
  ? `上次会话:${s.sid ? String(s.sid).slice(0, 12) : '-'} · ${s.at || '-'} · 工具调用 ${s.toolCalls ?? '-'} · 被拦 ${s.denies ?? '-'} · KPI ${s.kpi ?? '-'} · 委托 ${s.delegateBudget ?? '-'}`
164
191
  : ''
165
- // 决策行同理,且理由更硬(2026-10-29):它是**历史**,而历史每回合都在长。
166
- // 实测(tools/prefix-drift.mjs)系统段每会话 2 个版本,分歧点恒定落在这一行。
167
- // 代价口径(2026-11-11 更正,与 docs/ARCHITECTURE.md「前缀稳定性」一节对齐):
168
- // 宿主是 `systemPromptUpdate: "in-history"`——系统段变了是往历史里**追加**一条,
169
- // 不改写前缀,所以「后面整段历史按未缓存价重付」**不成立**(前缀照常命中)。
170
- // 真实代价是每变一次多背一份完整系统提示(约 2.5k tok/次),并在历史里堆出多条 system 消息。
171
- // 冻结它仍值得,但收益量级是 0.3% 而不是"整段重付"——别用旧口径给这条加权重。
172
- // 而指令原文本来就在会话消息里,再抄一份既重复又抖。
173
- const showDecisions = opts.sid === undefined || shouldInjectHandoff(record, opts.sid)
192
+ // 「决策:」行已于 2026-11-26 下架(缺陷与恢复条件见文件头「下架声明」)。
193
+ // 这里保留一条历史注记,免得后人又从 `prefix-drift.mjs` 的旧曲线里把结论倒推回去:
194
+ // 它当初是系统段抖动的**唯一**来源(每回合长一条,实测每会话 2 个版本,分歧点恒在这一行),
195
+ // 处置方式曾是「冻结到换会话」——那是在给一个不该存在的数据打补丁。
196
+ // 真正的处置是让它不存在:指令原文本来就在会话消息里,再抄一份既重复又抖。
174
197
  const head = `[FG-WORKSPACE] 本工作区跨会话卷宗(hash=${record.workspace_hash},仅当前路径可见):`
175
198
  /** 组装可见条目:`[done]` / `[note]` 不注入,`[goal]` 剥掉标记。 */
176
199
  const parts = []
@@ -178,7 +201,7 @@ export function renderWorkspaceSection(record, opts = {}) {
178
201
  const shown = (items || []).filter((x) => !isHiddenTag(x)).map((x) => stripTag(x))
179
202
  if (shown.length) parts.push({ label, shown })
180
203
  }
181
- if (showDecisions) push('决策', record.decisions)
204
+ // 注意:**不 push 决策**。存量 workspace.json 里的旧条目也不再注入(2026-11-26 下架)。
182
205
  // 约束(人类否决过的命令)保留实时:它是安全信息、只在真被否决时变,不是每回合的噪音。
183
206
  push('约束', record.constraints)
184
207
  push('下一步', record.next_action)
@@ -244,26 +267,26 @@ export function shouldInjectHandoff(record, sid) {
244
267
  }
245
268
 
246
269
  /**
247
- * 回合结束落账:只记 FG **亲眼看到**的三类事实,不推断、不编造。
248
- * decisions ← 本轮人类指令原文(≤200 字)
270
+ * 回合结束落账:只记 FG **亲眼数得出来**的事实,不推断、不转抄。
249
271
  * constraints← 人类明确否决过的命令(state.rejectedCmds 的键)
250
272
  * next_action← FG 不知道,留空(宁可空,不猜)
273
+ * decisions ← **已下架(2026-11-26),不再写入**。缺陷见文件头「下架声明」:
274
+ * 它抄的是本轮人类指令首行,而指令原文本来就在会话消息里;
275
+ * 抄出来的条目 0 条是决策、多为问句与训话。
251
276
  */
252
277
  export function recordWorkspaceTurn(agent) {
253
278
  const cwd = agent && agent.session && agent.session.header && agent.session.header.cwd
254
279
  if (!cwd) return null
255
- const sid =
256
- (agent && agent.session && agent.session.header && agent.session.header.id) ||
257
- (agent && (agent.sessionId || agent.id)) ||
258
- 'dsh-native'
280
+ // 哨兵用 `dsh-native` 而不是母版的中性值 `unknown`(`audit-writer` 用的是后者):
281
+ // 这里要读的是宿主缝写下的 state 文件,键必须与写方一致,否则读不到。**这是取值不是代言。**
282
+ // 解析链仍走 `core/session.mjs::resolveSid`,不自己拼。
283
+ const sid = resolveSid(agent, 'dsh-native')
259
284
  let state = {}
260
285
  try {
261
286
  state = loadState(statePath(sid)) || {}
262
287
  } catch {
263
288
  state = {}
264
289
  }
265
- const prompt = String(state.turnPromptFull || state.turnPrompt || '').trim()
266
- const decided = pickDecisionText(prompt)
267
290
  const rejected = Object.keys(state.rejectedCmds || {})
268
291
  // 快速交接快照(主图 L4):只存 FG 亲自数得出来的量,不推断"做到哪了"。
269
292
  const snapshot = {
@@ -275,7 +298,6 @@ export function recordWorkspaceTurn(agent) {
275
298
  delegateBudget: Number.isFinite(state.delegateBudget) ? state.delegateBudget : null,
276
299
  }
277
300
  return mergeWorkspace(cwd, {
278
- decisions: decided ? [decided] : [],
279
301
  constraints: rejected.slice(0, MAX_ITEMS),
280
302
  next_action: [],
281
303
  snapshot,
@@ -13,8 +13,8 @@
13
13
  * node packages/core/tools/capture-fixtures.mjs --since 24h # 只取最近 24h
14
14
  */
15
15
 
16
- import { decodeSession as decode } from './lib/sessionDump.mjs'
17
- import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync, rmSync } from 'node:fs'
16
+ import { decodeSession as decode, walkSessionFiles } from './lib/sessionDump.mjs'
17
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'node:fs'
18
18
  import { dirname, join, basename } from 'node:path'
19
19
  import { fileURLToPath } from 'node:url'
20
20
 
@@ -49,27 +49,6 @@ const DENY_RE =
49
49
  const DENY_PREFIX_RE = /^\s*Error[::]/
50
50
  const DENY_ZCODE_RE = /^\s*【拦截】/
51
51
 
52
- function walk(dir, out = []) {
53
- let entries = []
54
- try {
55
- entries = readdirSync(dir)
56
- } catch {
57
- return out
58
- }
59
- for (const e of entries) {
60
- const p = join(dir, e)
61
- let st
62
- try {
63
- st = statSync(p)
64
- } catch {
65
- continue
66
- }
67
- if (st.isDirectory()) walk(p, out)
68
- else if (e === 'session.v4.jsonl.zstd') out.push({ f: p, m: st.mtimeMs, size: st.size })
69
- }
70
- return out
71
- }
72
-
73
52
  /** 截断过长的参数值(content/command 可能上千字),只保留形状。 */
74
53
  function compactArg(value, limit = 160) {
75
54
  if (typeof value === 'string') return value.length > limit ? `${value.slice(0, limit)}…(${value.length})` : value
@@ -82,7 +61,7 @@ function compactArg(value, limit = 160) {
82
61
  return value
83
62
  }
84
63
 
85
- const files = walk(SESSIONS)
64
+ const files = walkSessionFiles(SESSIONS)
86
65
  .filter((x) => x.size < MAX_BYTES)
87
66
  .sort((a, b) => b.m - a.m)
88
67
  .slice(0, LIMIT)
@@ -22,8 +22,8 @@
22
22
  * node packages/core/tools/collect-panel.mjs panel.json --json
23
23
  */
24
24
 
25
- import { decodeSession as decode } from './lib/sessionDump.mjs'
26
- import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
25
+ import { decodeSession as decode, walkSessionFiles } from './lib/sessionDump.mjs'
26
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
27
27
  import { dirname, join } from 'node:path'
28
28
  import { fileURLToPath } from 'node:url'
29
29
 
@@ -49,28 +49,7 @@ function isPeak(at) {
49
49
  // 官方价目是 USD/1M,故按汇率换算后与面板核对;汇率可被 FG_USD_CNY 覆盖(默认 7.1)。
50
50
  const USD_CNY = Number(process.env.FG_USD_CNY || 7.1)
51
51
 
52
- function walk(dir, out = []) {
53
- let entries = []
54
- try {
55
- entries = readdirSync(dir)
56
- } catch {
57
- return out
58
- }
59
- for (const e of entries) {
60
- const p = join(dir, e)
61
- let st
62
- try {
63
- st = statSync(p)
64
- } catch {
65
- continue
66
- }
67
- if (st.isDirectory()) walk(p, out)
68
- else if (e === 'session.v4.jsonl.zstd') out.push(p)
69
- }
70
- return out
71
- }
72
-
73
- const FILES = walk(SESSIONS)
52
+ const FILES = walkSessionFiles(SESSIONS).map((x) => x.f)
74
53
 
75
54
  /** 从会话记录取结构指标:steps / denies / 工具调用 / 时长。 */
76
55
  function structureOf(sidPrefix) {
@@ -3,30 +3,15 @@
3
3
  * 死导出检查(2026-10-25):找出"导出了但没人调用"的符号——模块活着、功能没接上的典型形态。
4
4
  * 只读。排除:tests/ 内的引用不算使用者;同名不同文件的第二个实现会单独列出。
5
5
  */
6
- import { readFileSync, readdirSync, statSync } from 'node:fs'
6
+ import { readFileSync } from 'node:fs'
7
7
  import { dirname, join, relative } from 'node:path'
8
8
  import { fileURLToPath } from 'node:url'
9
+ import { walk } from './lib/import-graph.mjs'
9
10
 
10
11
  const HERE = dirname(fileURLToPath(import.meta.url))
11
12
  const CORE = join(HERE, '..')
12
13
  const ROOTS = ['src', 'hooks', 'tools']
13
14
 
14
- function walk(dir, out = []) {
15
- let entries = []
16
- try {
17
- entries = readdirSync(dir)
18
- } catch {
19
- return out
20
- }
21
- for (const e of entries) {
22
- const p = join(dir, e)
23
- const st = statSync(p)
24
- if (st.isDirectory()) walk(p, out)
25
- else if (/\.(mjs|js)$/.test(e)) out.push(p)
26
- }
27
- return out
28
- }
29
-
30
15
  const files = ROOTS.flatMap((r) => walk(join(CORE, r)))
31
16
  const sources = new Map()
32
17
  for (const f of files) sources.set(f, readFileSync(f, 'utf8'))
@@ -0,0 +1,234 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 全仓文档书(tools/docs-book.mjs,2026-11-19)
4
+ *
5
+ * 把 `listMarkdownFiles` 认到的每一份 `.md` 编成**一本单文件 HTML**:
6
+ * 左侧按状态分组(权威 / 参考 / 台账 / 归档),右侧连续阅读,带搜索与阅读进度。
7
+ *
8
+ * ## 为什么是单文件
9
+ *
10
+ * 双击就开,不起服务器。`file://` 下 `fetch` 本地文件会被 CORS 拦,
11
+ * 所以 40 份正文必须**内嵌**进 HTML——这也是 `library-book.mjs` 早就定下的同一取舍。
12
+ *
13
+ * ## 与 `library-book.mjs` 的分工
14
+ *
15
+ * - `library-book`:读 `.ai/output/library` 的**卡片**,给私有研读资料成书(卡片体例 `.h/.act/.ref`)。
16
+ * - 本脚本:读**仓库里的文档**,按状态分组,给「这份文档落后多少」一个可翻阅的视图。
17
+ * - 渲染器**共用** `lib/markdown.mjs`,版式**共用** `lib/book-style.mjs`。
18
+ * 两个入口、一套实现——不共用的话,两本书对同一段 markdown 会给出不同结果。
19
+ *
20
+ * ## 数据从哪来
21
+ *
22
+ * 状态、适用版本、最后核对一律走 `collectDocStatus`,与 `docs/STATUS.md` **同一份真值**。
23
+ * 本书不另算落后档数:两处各算一遍,迟早算出两个数。
24
+ *
25
+ * 用法:
26
+ * node packages/core/tools/docs-book.mjs # 写 docs/book.html
27
+ * node packages/core/tools/docs-book.mjs --out <file>
28
+ * node packages/core/tools/docs-book.mjs --label 我的书
29
+ */
30
+ import { readFileSync, writeFileSync } from 'node:fs'
31
+ import { dirname, join, relative, resolve } from 'node:path'
32
+ import { fileURLToPath } from 'node:url'
33
+ import { listMarkdownFiles } from './lib/docs-core.mjs'
34
+ import { collectDocStatus, parseStatusHeader } from './lib/docs-status.mjs'
35
+ import { mdToHtml } from './lib/markdown.mjs'
36
+ import { BOOK_CSS } from './lib/book-style.mjs'
37
+
38
+ const HERE = dirname(fileURLToPath(import.meta.url))
39
+ const ROOT = resolve(HERE, '..', '..', '..')
40
+ const argv = process.argv.slice(2)
41
+ const arg = (k, d) => (argv.includes(k) ? argv[argv.indexOf(k) + 1] : d)
42
+ const OUT = resolve(ROOT, arg('--out', 'docs/book.html'))
43
+ const LABEL = arg('--label', 'Focus Guard 文档全集')
44
+
45
+ const { current, rows } = collectDocStatus(ROOT)
46
+ const byRel = new Map(rows.map((r) => [r.rel, r]))
47
+
48
+ /** 去掉首个 H1 与紧随其后的状态块:标题与版本已经在文章头上,正文里再来一遍是重复。 */
49
+ function stripHead(text) {
50
+ const lines = text.split('\n')
51
+ let i = 0
52
+ while (i < lines.length && !lines[i].startsWith('# ')) i += 1
53
+ if (i < lines.length) i += 1
54
+ while (i < lines.length && !lines[i].trim()) i += 1
55
+ return lines.slice(i).join('\n')
56
+ }
57
+
58
+ const GROUP_ORDER = ['权威', '参考', '台账', '归档', '未标']
59
+
60
+ const docs = listMarkdownFiles(ROOT)
61
+ .map((file) => {
62
+ const rel = relative(ROOT, file).split('\\').join('/')
63
+ const text = readFileSync(file, 'utf8')
64
+ // `collectDocStatus` 有意把 `docs/STATUS.md` 自己排除(自引用会让总表行数漂移),
65
+ // 但书里要收它,所以这里单独读一次它自己的状态头,而不是让它显示成「未标」。
66
+ const meta = byRel.get(rel) || parseStatusHeader(text) || {}
67
+ const title = (text.split('\n').find((l) => l.startsWith('# ')) || '').replace(/^#\s*/, '').trim() || rel
68
+ return {
69
+ id: rel,
70
+ title,
71
+ group: meta.status || '未标',
72
+ version: meta.version || '—',
73
+ date: meta.date || '—',
74
+ behind: meta.status === '权威' && typeof meta.behind === 'number' && meta.behind > 0 ? meta.behind : 0,
75
+ chars: text.length,
76
+ html: mdToHtml(stripHead(text), { hShift: 0, cardClasses: false }),
77
+ }
78
+ })
79
+ .sort((a, b) => {
80
+ const ga = GROUP_ORDER.indexOf(a.group)
81
+ const gb = GROUP_ORDER.indexOf(b.group)
82
+ if (ga !== gb) return (ga < 0 ? 9 : ga) - (gb < 0 ? 9 : gb)
83
+ return a.id.localeCompare(b.id)
84
+ })
85
+
86
+ const groups = []
87
+ for (const d of docs) {
88
+ const last = groups[groups.length - 1]
89
+ if (last && last.name === d.group) last.docs.push(d)
90
+ else groups.push({ name: d.group, docs: [d] })
91
+ }
92
+
93
+ const totalChars = docs.reduce((a, d) => a + d.chars, 0)
94
+
95
+ /**
96
+ * 文档书比资料书多出的排版。
97
+ *
98
+ * `BOOK_CSS` 只定义了 `.body h3` / `.body h4`——那是按资料书的卡片层级写的
99
+ * (卡片里最高只到 `###`)。文档的 `##` 会渲染成 `<h2>`,落在这里就没有样式,
100
+ * 退回浏览器默认的 1.5em 粗体,和正文打架。表格与代码块同理:资料书里一个都没有。
101
+ * 所以这一段是**补缺**,不是覆盖:BOOK_CSS 里有的(行宽、纸色、衬线)一概不动。
102
+ */
103
+ const DOCS_CSS = `
104
+ .body h1{font-size:1.42em;line-height:1.3;margin:1.6em 0 .6em}
105
+ .body h2{font-size:1.2em;line-height:1.35;margin:1.7em 0 .5em;padding-bottom:.28em;border-bottom:1px solid var(--line)}
106
+ .body h3{font-size:1.04em;margin:1.3em 0 .4em}
107
+ .body h4{font-size:1em;margin:1.1em 0 .3em}
108
+ .body table{width:100%;border-collapse:collapse;margin:1em 0;font-size:.9em}
109
+ .body th,.body td{border:1px solid var(--line);padding:.42em .6em;text-align:left;vertical-align:top}
110
+ .body th{background:var(--soft);font-weight:600;white-space:nowrap}
111
+ .body pre{background:var(--panel);border:1px solid var(--line);border-radius:6px;padding:.8em 1em;overflow:auto;font-size:.84em;line-height:1.55}
112
+ .body code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.9em}
113
+ .body :not(pre)>code{background:var(--soft);padding:.1em .34em;border-radius:4px;word-break:break-word}
114
+ .body a{color:var(--accent);text-decoration:none;border-bottom:1px solid var(--soft)}
115
+ .body a:hover{border-bottom-color:var(--accent)}
116
+ .body blockquote{border-left:3px solid var(--soft);margin:1em 0;padding:.1em 0 .1em 1em;color:var(--ink2)}
117
+ .body blockquote p{margin:.35em 0}
118
+ .body hr{border:0;border-top:1px solid var(--line);margin:2em 0}
119
+ .body img{max-width:100%}
120
+ .body details>summary{cursor:pointer;color:var(--dim);margin:.6em 0}
121
+ `
122
+
123
+ const HTML = `<!DOCTYPE html>
124
+ <html lang="zh-CN">
125
+ <head>
126
+ <meta charset="utf-8">
127
+ <meta name="viewport" content="width=device-width, initial-scale=1">
128
+ <title>${LABEL}</title>
129
+ <style>${BOOK_CSS}${DOCS_CSS}</style>
130
+ </head>
131
+ <body>
132
+ <aside>
133
+ <div class="brand">
134
+ <div class="kicker">Documents</div>
135
+ <h1>${LABEL}</h1>
136
+ <div class="meta">${docs.length} 份 · ${(totalChars / 10000).toFixed(1)} 万字 · 版本 ${current}</div>
137
+ </div>
138
+ <div class="search"><input id="q" placeholder="搜索文档名或路径" autocomplete="off"></div>
139
+ <nav id="tree"></nav>
140
+ <div class="aside-foot">权威在前,落后的在前<br>滚轮连续读 · 点目录跳章</div>
141
+ </aside>
142
+ <main><div id="bar"><i></i></div><div class="wrap" id="book"></div></main>
143
+ <script>
144
+ const DATA = ${JSON.stringify(groups).replace(/</g, '\\u003c')};
145
+ const esc = (s) => String(s).replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c]);
146
+ const tree = document.getElementById('tree');
147
+ const book = document.getElementById('book');
148
+ const TOTAL = DATA.reduce((a, g) => a + g.docs.length, 0);
149
+ const LONG = 20000;
150
+ let n = 0;
151
+ for (const g of DATA) {
152
+ const h = document.createElement('div');
153
+ h.className = 'grp';
154
+ h.textContent = g.name + ' · ' + g.docs.length;
155
+ tree.appendChild(h);
156
+ for (const d of g.docs) {
157
+ n += 1;
158
+ const a = document.createElement('a');
159
+ a.className = 'item';
160
+ a.dataset.id = d.id;
161
+ a.dataset.title = (d.title + ' ' + d.id).toLowerCase();
162
+ a.innerHTML = '<span class="n">' + String(n).padStart(2, '0') + '</span><span class="t">' + esc(d.title) + '</span>';
163
+ // getElementById 按字面匹配,不要用 CSS.escape:它会把点和斜杠转义,
164
+ // 拼出来的字符串与真实 id 不同,跳转会静默失效(2026-11-19 初版踩过)。
165
+ a.onclick = () => document.getElementById('blk-' + d.id).scrollIntoView({ behavior: 'smooth', block: 'start' });
166
+ tree.appendChild(a);
167
+
168
+ const art = document.createElement('article');
169
+ art.id = 'blk-' + d.id;
170
+ art.innerHTML =
171
+ '<header class="ch">' +
172
+ '<div class="no">' + String(n).padStart(2, '0') + ' / ' + String(TOTAL).padStart(2, '0') + '</div>' +
173
+ '<h2>' + esc(d.title) + '</h2>' +
174
+ '<div class="src">' + esc(d.id) + ' · ' + esc(d.version) + ' · 核对 ' + esc(d.date) +
175
+ (d.behind ? ' · <b>落后 ' + d.behind + ' 档</b>' : '') +
176
+ ' · ' + d.chars + ' 字</div>' +
177
+ '</header>' +
178
+ '<div class="body">' +
179
+ (d.chars > LONG ? '<details><summary>' + d.chars + ' 字,点开</summary>' + d.html + '</details>' : d.html) +
180
+ '</div>';
181
+ book.appendChild(art);
182
+ }
183
+ }
184
+
185
+ // 搜索:只过滤目录项,不动正文——正文一次性全渲染,按需滚动。
186
+ const q = document.getElementById('q');
187
+ q.addEventListener('input', () => {
188
+ const k = q.value.trim().toLowerCase();
189
+ for (const a of document.querySelectorAll('.item')) {
190
+ a.style.display = !k || a.dataset.title.includes(k) ? '' : 'none';
191
+ }
192
+ for (const g of document.querySelectorAll('.grp')) {
193
+ let el = g.nextElementSibling;
194
+ let any = false;
195
+ while (el && el.classList.contains('item')) {
196
+ if (el.style.display !== 'none') any = true;
197
+ el = el.nextElementSibling;
198
+ }
199
+ g.style.display = any ? '' : 'none';
200
+ }
201
+ });
202
+
203
+ // 阅读进度:细线贴顶,只在 main 里滚时变。
204
+ const mainEl = document.querySelector('main');
205
+ const barEl = document.querySelector('#bar i');
206
+ const paint = () => {
207
+ const max = mainEl.scrollHeight - mainEl.clientHeight;
208
+ barEl.style.width = (max > 0 ? (mainEl.scrollTop / max) * 100 : 0) + '%';
209
+ };
210
+ mainEl.addEventListener('scroll', paint, { passive: true });
211
+ window.addEventListener('resize', paint);
212
+ paint();
213
+
214
+ // 目录高亮:IntersectionObserver 比 scroll 事件省。
215
+ const links = new Map([...document.querySelectorAll('.item')].map((a) => [a.dataset.id, a]));
216
+ const io = new IntersectionObserver((entries) => {
217
+ for (const e of entries) {
218
+ if (!e.isIntersecting) continue;
219
+ const id = e.target.id.replace(/^blk-/, '');
220
+ for (const a of links.values()) a.classList.remove('on');
221
+ const a = links.get(id);
222
+ if (a) a.classList.add('on');
223
+ }
224
+ }, { rootMargin: '0px 0px -70% 0px' });
225
+ for (const art of document.querySelectorAll('article')) io.observe(art);
226
+ </script>
227
+ </body>
228
+ </html>
229
+ `
230
+
231
+ writeFileSync(OUT, HTML)
232
+ process.stdout.write(
233
+ `[docs-book] ${relative(ROOT, OUT).split('\\').join('/')}:${docs.length} 份 / ${groups.length} 组 / ${(HTML.length / 1024).toFixed(0)} KB\n`,
234
+ )