focus-guard 3.5.2 → 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 (99) hide show
  1. package/README.md +15 -3
  2. package/README.zh-CN.md +13 -3
  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 +60 -16
  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 -5
  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 +19 -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/collect-panel.mjs +3 -24
  49. package/tools/dead-export.mjs +2 -17
  50. package/tools/docs-book.mjs +234 -0
  51. package/tools/docs-drift.mjs +165 -0
  52. package/tools/docs-lint.mjs +24 -0
  53. package/tools/gate-audit.mjs +3 -24
  54. package/tools/handoff.mjs +3 -1
  55. package/tools/install-check.mjs +107 -9
  56. package/tools/layering-audit.mjs +7 -1
  57. package/tools/legacy-audit.mjs +83 -0
  58. package/tools/lib/case-tool.mjs +8 -2
  59. package/tools/lib/docs-ack.mjs +95 -0
  60. package/tools/lib/docs-core.mjs +38 -22
  61. package/tools/lib/docs-files.mjs +73 -0
  62. package/tools/lib/docs-status.mjs +143 -0
  63. package/tools/lib/idioms.mjs +149 -0
  64. package/tools/lib/import-graph.mjs +8 -3
  65. package/tools/lib/legacy-core.mjs +178 -0
  66. package/tools/lib/markdown.mjs +202 -0
  67. package/tools/lib/modules-doc.mjs +96 -0
  68. package/tools/lib/modules-list.mjs +382 -0
  69. package/tools/lib/modules.mjs +312 -0
  70. package/tools/lib/prefix-cost.mjs +5 -3
  71. package/tools/library-book.mjs +7 -92
  72. package/tools/lint.mjs +5 -0
  73. package/tools/memory-audit.mjs +32 -6
  74. package/tools/memory-recall-eval.mjs +408 -0
  75. package/tools/module-audit.mjs +2 -17
  76. package/tools/modules-audit.mjs +108 -0
  77. package/tools/panel-baseline.mjs +172 -0
  78. package/tools/prefix-audit.mjs +10 -2
  79. package/tools/prefix-drift.mjs +9 -4
  80. package/tools/registry-check.mjs +194 -0
  81. package/tools/release.mjs +374 -0
  82. package/tools/version.mjs +12 -8
  83. package/docs/AB-PROMPTS.md +0 -123
  84. package/docs/AB-SESSION.md +0 -161
  85. package/docs/BENCH-BASELINE.json +0 -95
  86. package/docs/BRAIN-VIZ.md +0 -94
  87. package/docs/GATE-INPUTS.json +0 -10
  88. package/docs/HANDOFF-2026-10-27.md +0 -736
  89. package/docs/HOOK-ORDERING.md +0 -139
  90. package/docs/LEGISLATION-LAW.md +0 -104
  91. package/docs/MCP-4.0-PLAN.md +0 -184
  92. package/docs/MEMORY-4.5-PLAN.md +0 -415
  93. package/docs/PROFILE-TUNING.md +0 -147
  94. package/docs/RATCHET.json +0 -80
  95. package/docs/TOOL-SCHEMA.json +0 -6
  96. package/docs/VERSION-PLAN.md +0 -604
  97. package/docs/architecture-map.mermaid +0 -186
  98. package/docs/deepseek-pricing-audit.md +0 -65
  99. package/src/dsh/guard/superpowers.mjs +0 -70
@@ -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,
@@ -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
+ )
@@ -0,0 +1,165 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * docs:drift(2026-11-22)
4
+ *
5
+ * 文档漂移扫描器:把「文档里写死的事实」拿代码对一遍,出清单而不是靠人眼。
6
+ * 三类判据(都只认可机器验证的):
7
+ * 1. `npm run <script>`:package.json 的 scripts 里必须存在;
8
+ * 2. 反引号里的仓库相对路径:文件/目录必须存在(占位符与通配符跳过);
9
+ * 3. `FG_*` 环境变量:`packages/core/src` 里必须出现过。
10
+ *
11
+ * 不判:示例里的外部 URL、<占位符>、执行结果、版本号(版本面已由 docs:lint / version.mjs 管)。
12
+ *
13
+ * 用法:
14
+ * node packages/core/tools/docs-drift.mjs # 人读清单
15
+ * node packages/core/tools/docs-drift.mjs --json # 机器读
16
+ * node packages/core/tools/docs-drift.mjs --strict # 有漂移则退出码 1(默认 0,只报告)
17
+ */
18
+ import { readFileSync, existsSync, statSync, readdirSync } from 'node:fs'
19
+ import { dirname, join, resolve, relative } from 'node:path'
20
+ import { fileURLToPath } from 'node:url'
21
+
22
+ const HERE = dirname(fileURLToPath(import.meta.url))
23
+ const ROOT = resolve(HERE, '..', '..', '..')
24
+
25
+ const args = process.argv.slice(2)
26
+ const asJson = args.includes('--json')
27
+ const strict = args.includes('--strict')
28
+
29
+ /** 扫描范围:docs 树 + 入口文档;归档与 vault 笔记不扫(历史材料,改了也不该被当前事实约束)。 */
30
+ function walkDocs(dir, out = []) {
31
+ let entries
32
+ try {
33
+ entries = readdirSync(dir, { withFileTypes: true })
34
+ } catch {
35
+ return out
36
+ }
37
+ for (const e of entries) {
38
+ if (e.name === 'archive' || e.name === 'vault-notes' || e.name === 'node_modules') continue
39
+ const p = join(dir, e.name)
40
+ if (e.isDirectory()) walkDocs(p, out)
41
+ else if (e.name.endsWith('.md')) out.push(p)
42
+ }
43
+ return out
44
+ }
45
+
46
+ const FILES = [
47
+ ...walkDocs(join(ROOT, 'docs')),
48
+ ...walkDocs(join(ROOT, 'packages/core/docs')),
49
+ join(ROOT, 'README.md'),
50
+ join(ROOT, 'INSTALL.md'),
51
+ join(ROOT, 'packages/core/README.md'),
52
+ join(ROOT, 'packages/core/README.zh-CN.md'),
53
+ ].filter((f) => existsSync(f) && !/HANDOFF-/.test(f))
54
+
55
+ const scripts = Object.keys(JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')).scripts || {})
56
+
57
+ /** FG_* 变量名集合:从 src 全量收集(只读,不猜)。 */
58
+ function collectEnvNames() {
59
+ const names = new Set()
60
+ const walk = (dir) => {
61
+ let entries
62
+ try {
63
+ entries = readdirSync(dir, { withFileTypes: true })
64
+ } catch {
65
+ return
66
+ }
67
+ for (const e of entries) {
68
+ if (e.name === 'node_modules') continue
69
+ const p = join(dir, e.name)
70
+ if (e.isDirectory()) walk(p)
71
+ else if (/\.(mjs|js)$/.test(e.name)) {
72
+ const text = readFileSync(p, 'utf8')
73
+ for (const m of text.matchAll(/\bFG_[A-Z0-9_]+\b/g)) names.add(m[0])
74
+ }
75
+ }
76
+ }
77
+ walk(join(ROOT, 'packages/core'))
78
+ return names
79
+ }
80
+ const ENV_NAMES = collectEnvNames()
81
+
82
+ const SKIP_PATH = /\s|<|>|\*|\?|\{|\}|\.\.\.|…|^https?:|^file:|^[A-Za-z]:|^~|^\$|^%|^you$|^\.\.$/
83
+
84
+ /** 运行期产物目录:文档里写它们只在说「会生成到哪」,不该被要求当前就存在。 */
85
+ const RUNTIME_PREFIX = /^(?:\.focus-guard|\.ai|\.stryker-tmp|reports|\.dsh|library|notes|output|archive)\//
86
+
87
+ /** 只认本仓自己的目录前缀;`memory-core/`、`plugins/` 这类是外部项目引用,不归本仓查。 */
88
+ const REPO_PREFIX = /^(?:packages|docs|\.ai|\.githooks|\.github|\.claude-plugin|\.zcode-plugin|src|tests|tools|hooks|skills|presets|assets|scripts)\//
89
+ const PATHISH = /^(?:packages|docs|\.ai|\.githooks|\.github|\.claude-plugin|\.zcode-plugin)\//
90
+ const EXT = /\.(?:md|mjs|js|json|yml|yaml|html|css|txt|sh|ps1|bat)$/
91
+
92
+ const rows = []
93
+ function report(file, line, rule, snippet, detail) {
94
+ rows.push({ file: relative(ROOT, file).replace(/\\/g, '/'), line, rule, snippet, detail })
95
+ }
96
+
97
+ function checkScript(file, line, name) {
98
+ const head = name.split(/\s+/)[0]
99
+ if (!head || head.startsWith('-')) return
100
+ if (scripts.includes(head)) return
101
+ report(file, line, 'npm-script', `npm run ${head}`, `package.json scripts 里没有 ${head}`)
102
+ }
103
+
104
+ function checkPath(file, line, token, lineText = '') {
105
+ const t = token.trim()
106
+ if (!t || SKIP_PATH.test(t)) return
107
+ const bare = t.replace(/[.,;:))】]+$/, '').replace(/^['"]|['"]$/g, '')
108
+ if (!REPO_PREFIX.test(bare) && !PATHISH.test(bare)) return
109
+ if (RUNTIME_PREFIX.test(bare)) return
110
+ if (!EXT.test(bare) && !bare.endsWith('/')) return
111
+ if (bare.includes('*')) return
112
+ // 文档里的路径有三种写法,逐一试:仓库根相对、文档同目录相对、包内相对(packages/core/…)。
113
+ const candidates = [
114
+ join(ROOT, bare),
115
+ resolve(dirname(file), bare),
116
+ resolve(dirname(file), '..', bare),
117
+ join(ROOT, 'packages/core', bare),
118
+ join(ROOT, 'packages/core/src', bare),
119
+ join(ROOT, 'packages/core/src/dsh', bare),
120
+ ]
121
+ for (const c of candidates) {
122
+ try {
123
+ if (existsSync(c) && statSync(c)) return
124
+ } catch {
125
+ /* keep trying */
126
+ }
127
+ }
128
+ // 计划/设计类段落里的路径是「将来要建」,不是当前事实;只报告已建成文档里的死路径。
129
+ if (/计划|待做|未做|目标|将|拟|设计/.test(lineText)) return
130
+ report(file, line, 'repo-path', bare, '文件或目录不存在')
131
+ }
132
+
133
+ function checkEnv(file, line, name) {
134
+ if (ENV_NAMES.has(name)) return
135
+ report(file, line, 'fg-env', name, 'packages/core/src 里没有这个环境变量')
136
+ }
137
+
138
+ for (const file of FILES) {
139
+ const lines = readFileSync(file, 'utf8').split('\n')
140
+ lines.forEach((text, i) => {
141
+ const line = i + 1
142
+ for (const m of text.matchAll(/npm run ([A-Za-z0-9:_-]+)/g)) checkScript(file, line, m[1])
143
+ for (const m of text.matchAll(/\bFG_[A-Z0-9_]+\b/g)) checkEnv(file, line, m[0])
144
+ // 只查反引号包裹的路径;代码块里没有反引号,靠行内格式,避免把命令参数当路径。
145
+ for (const m of text.matchAll(/`([^`\n]+)`/g)) checkPath(file, line, m[1], text)
146
+ })
147
+ }
148
+
149
+ rows.sort((a, b) => (a.file === b.file ? a.line - b.line : a.file < b.file ? -1 : 1))
150
+
151
+ if (asJson) {
152
+ console.log(JSON.stringify({ scanned: FILES.length, issues: rows.length, rows }, null, 2))
153
+ } else {
154
+ console.log(`[docs:drift] 扫描 ${FILES.length} 份文档 → 漂移 ${rows.length} 条`)
155
+ let last = ''
156
+ for (const r of rows) {
157
+ if (r.file !== last) {
158
+ console.log(`\n${r.file}`)
159
+ last = r.file
160
+ }
161
+ console.log(` :${r.line} [${r.rule}] ${r.snippet} — ${r.detail}`)
162
+ }
163
+ if (!rows.length) console.log(' 无漂移。')
164
+ }
165
+ process.exit(strict && rows.length ? 1 : 0)
@@ -6,16 +6,20 @@
6
6
  * node packages/core/tools/docs-lint.mjs --brief # 一行(供 npm run check)
7
7
  * node packages/core/tools/docs-lint.mjs --json # 机器读
8
8
  * node packages/core/tools/docs-lint.mjs --strict # 有问题即 exit 1
9
+ * node packages/core/tools/docs-lint.mjs --sync-status # 重新生成 docs/STATUS.md
9
10
  *
10
11
  * 闸门是棘轮:`BUDGET` 记当前存量(初始 0),只许降不许升。
11
12
  * 这是 3.5「文档重置完成」的前置尺子(D5);README 硬指标、数字单点、状态头分别归 D1/D4/D2。
12
13
  */
14
+ import { writeFileSync } from 'node:fs'
15
+ import { join } from 'node:path'
13
16
  import { fileURLToPath } from 'node:url'
14
17
  import {
15
18
  listMarkdownFiles,
16
19
  checkVersionFace,
17
20
  checkRelativeLinks,
18
21
  checkCodePathRefs,
22
+ checkScriptRefs,
19
23
  checkStatusHeaders,
20
24
  checkIndexCoverage,
21
25
  allDocFiles,
@@ -23,12 +27,16 @@ import {
23
27
  checkCitationStyle,
24
28
  } from './lib/docs-core.mjs'
25
29
  import { checkVersionClaims, checkReadmeVersionFace } from './lib/docs-version.mjs'
30
+ import { checkAckFreshness } from './lib/docs-ack.mjs'
31
+ import { STATUS_DOC, collectDocStatus, renderStatusTable, checkStatusTable } from './lib/docs-status.mjs'
32
+ import { checkModulePaths, checkModuleIds, checkModuleOverlap, checkModuleCoverage } from './lib/modules.mjs'
26
33
 
27
34
  const ROOT = fileURLToPath(new URL('../../../', import.meta.url))
28
35
  const argv = process.argv.slice(2)
29
36
  const AS_JSON = argv.includes('--json')
30
37
  const BRIEF = argv.includes('--brief')
31
38
  const STRICT = argv.includes('--strict')
39
+ const SYNC_STATUS = argv.includes('--sync-status')
32
40
  const BUDGET = 0
33
41
 
34
42
  /**
@@ -41,16 +49,32 @@ const BUDGET = 0
41
49
  const RULE_BUDGET = { 'dead-code-path': 0 }
42
50
 
43
51
  const files = listMarkdownFiles(ROOT)
52
+
53
+ // `--sync-status` 只做生成,不跑判据:生成器不该顺便当闸门,否则"红着生成"会把人搞糊涂。
54
+ if (SYNC_STATUS) {
55
+ const data = collectDocStatus(ROOT, files)
56
+ writeFileSync(join(ROOT, STATUS_DOC), renderStatusTable(data))
57
+ console.log(`已生成 ${STATUS_DOC}:${data.rows.length} 份文档,当前版本 ${data.current}。`)
58
+ process.exit(0)
59
+ }
60
+
44
61
  const findings = [
45
62
  ...checkVersionFace(ROOT),
46
63
  ...checkRelativeLinks(ROOT, files),
47
64
  ...checkCodePathRefs(ROOT, files),
65
+ ...checkScriptRefs(ROOT, files),
48
66
  ...checkStatusHeaders(ROOT),
49
67
  ...checkIndexCoverage(ROOT, allDocFiles(ROOT)),
68
+ ...checkStatusTable(ROOT, files),
69
+ ...checkModulePaths(ROOT),
70
+ ...checkModuleIds(),
71
+ ...checkModuleOverlap(ROOT),
72
+ ...checkModuleCoverage(ROOT),
50
73
  ...checkReadmeMetrics(ROOT),
51
74
  ...checkCitationStyle(ROOT),
52
75
  ...checkVersionClaims(ROOT),
53
76
  ...checkReadmeVersionFace(ROOT),
77
+ ...checkAckFreshness(ROOT, files),
54
78
  ]
55
79
  const byRule = {}
56
80
  for (const f of findings) byRule[f.rule] = (byRule[f.rule] || 0) + 1