focus-guard 3.0.7 → 3.4.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.
Files changed (161) hide show
  1. package/LICENSE +683 -21
  2. package/NOTICE +25 -0
  3. package/README.md +14 -9
  4. package/README.zh-CN.md +12 -9
  5. package/docs/AB-PROMPTS.md +123 -0
  6. package/docs/AB-SESSION.md +161 -0
  7. package/docs/ARCH-MAP.md +148 -0
  8. package/docs/BENCH-BASELINE.json +95 -0
  9. package/docs/BENCH.md +323 -0
  10. package/docs/GATE-INPUTS.json +10 -0
  11. package/docs/HANDOFF-2026-10-27.md +736 -0
  12. package/docs/HOOK-ORDERING.md +139 -0
  13. package/docs/LEGISLATION-LAW.md +4 -2
  14. package/docs/MCP-4.0-PLAN.md +184 -0
  15. package/docs/MEMORY-4.5-PLAN.md +415 -0
  16. package/docs/PROFILE-TUNING.md +147 -0
  17. package/docs/RATCHET.json +48 -0
  18. package/docs/RELEASE-POLICY.md +163 -0
  19. package/docs/RULES.md +95 -14
  20. package/docs/THREAT-MODEL.md +68 -0
  21. package/docs/TOOL-SCHEMA.json +6 -0
  22. package/docs/VERSION-PLAN.md +532 -0
  23. package/docs/WRITING-STYLE.md +109 -0
  24. package/docs/architecture-map.mermaid +186 -0
  25. package/docs/deepseek-pricing-audit.md +2 -0
  26. package/hooks/guard.mjs +92 -56
  27. package/package.json +34 -5
  28. package/skills/focus-thinking/SKILL.md +9 -7
  29. package/src/adapters/dsh/eligibility-gate.mjs +446 -23
  30. package/src/adapters/dsh/tool-kinds.mjs +81 -0
  31. package/src/core/approval.mjs +2 -8
  32. package/src/core/approvals.mjs +208 -0
  33. package/src/core/audit-writer.mjs +297 -0
  34. package/src/core/audit.mjs +46 -16
  35. package/src/core/backup.mjs +37 -11
  36. package/src/core/checkEligibility.mjs +7 -4
  37. package/src/core/constants.mjs +67 -22
  38. package/src/core/decisionEngine.mjs +12 -0
  39. package/src/core/env.mjs +147 -19
  40. package/src/core/grants.mjs +54 -13
  41. package/src/core/kpi.mjs +16 -0
  42. package/src/core/outputGate.mjs +77 -0
  43. package/src/core/patterns.mjs +129 -0
  44. package/src/core/prefixStability.mjs +143 -0
  45. package/src/core/profileLoader.mjs +40 -5
  46. package/src/core/progressPolicy.mjs +65 -0
  47. package/src/core/redlines.mjs +49 -5
  48. package/src/core/risk.mjs +94 -15
  49. package/src/core/schemaDrift.mjs +125 -0
  50. package/src/core/sessionScratch.mjs +147 -0
  51. package/src/core/stageGraph.mjs +104 -0
  52. package/src/core/staleCleanup.mjs +153 -0
  53. package/src/core/state.mjs +215 -81
  54. package/src/core/stopPolicy.mjs +97 -0
  55. package/src/core/tempPath.mjs +23 -0
  56. package/src/dsh/audit.mjs +168 -118
  57. package/src/dsh/compactionWatch/announce.mjs +117 -0
  58. package/src/dsh/compactionWatch.mjs +68 -153
  59. package/src/dsh/guard/authz.mjs +97 -0
  60. package/src/dsh/guard/evidence.mjs +308 -0
  61. package/src/dsh/guard/hardCheck.mjs +85 -0
  62. package/src/dsh/guard/redline.mjs +62 -0
  63. package/src/dsh/guard/risk.mjs +196 -0
  64. package/src/dsh/guard/runtime.mjs +162 -0
  65. package/src/dsh/guard/superpowers.mjs +70 -0
  66. package/src/dsh/guard/tooling.mjs +177 -0
  67. package/src/dsh/guard/volume.mjs +181 -0
  68. package/src/dsh/guard/wholeFile.mjs +109 -0
  69. package/src/dsh/heartbeat.mjs +76 -13
  70. package/src/dsh/hookOrder.mjs +101 -0
  71. package/src/dsh/index.js +247 -15
  72. package/src/dsh/pipeline.mjs +77 -854
  73. package/src/dsh/policy-audit.mjs +84 -0
  74. package/src/dsh/postProgress.mjs +400 -274
  75. package/src/dsh/preGuard.mjs +249 -228
  76. package/src/dsh/repeatGuard.mjs +98 -0
  77. package/src/dsh/seams/pre-step.mjs +186 -0
  78. package/src/dsh/seams/prompt-rules.mjs +59 -0
  79. package/src/dsh/seams/session-start.mjs +297 -0
  80. package/src/dsh/seams/shared.mjs +109 -0
  81. package/src/dsh/seams.mjs +95 -408
  82. package/src/dsh/search-hints.mjs +136 -0
  83. package/src/dsh/sessionScope.mjs +28 -0
  84. package/src/dsh/status.mjs +7 -0
  85. package/src/dsh/stopGuard.mjs +225 -164
  86. package/src/dsh/testRuntime.mjs +62 -0
  87. package/src/dsh/toolKindAudit.mjs +66 -0
  88. package/src/dsh/tools.mjs +81 -5
  89. package/src/dsh/traceMeta.mjs +125 -0
  90. package/src/dsh/value-gate.mjs +93 -0
  91. package/src/dsh/workspace.mjs +3 -143
  92. package/src/memory/index.mjs +15 -0
  93. package/src/memory/tags.mjs +30 -0
  94. package/src/memory/workspace.mjs +283 -0
  95. package/src/peak-cost.mjs +1 -1
  96. package/src/profiles/deepseek-flash.mjs +7 -1
  97. package/src/profiles/deepseek-pro.mjs +6 -1
  98. package/src/profiles/default.mjs +6 -1
  99. package/src/profiles/glm.mjs +6 -1
  100. package/src/profiles/gpt-astra.mjs +6 -1
  101. package/tools/bench-ab.mjs +240 -0
  102. package/tools/bench-cost.mjs +176 -0
  103. package/tools/brain-cosmic.mjs +43 -0
  104. package/tools/brain-view.html +853 -0
  105. package/tools/brain.mjs +317 -0
  106. package/tools/capture-fixtures.mjs +182 -0
  107. package/tools/case-audit.mjs +114 -0
  108. package/tools/collect-panel.mjs +218 -0
  109. package/tools/dead-export.mjs +60 -0
  110. package/tools/docs-lint.mjs +82 -0
  111. package/tools/env-fingerprint.mjs +126 -33
  112. package/tools/first-run-sweep.mjs +123 -0
  113. package/tools/focusguard.mjs +155 -0
  114. package/tools/gate-audit.mjs +140 -0
  115. package/tools/gate-inputs.mjs +115 -0
  116. package/tools/handoff.mjs +56 -0
  117. package/tools/health.mjs +182 -0
  118. package/tools/knowledge.mjs +118 -0
  119. package/tools/layering-audit.mjs +105 -0
  120. package/tools/lib/book-style.mjs +136 -0
  121. package/tools/lib/brain-core.mjs +342 -0
  122. package/tools/lib/brain-docs.mjs +293 -0
  123. package/tools/lib/brain-regions.mjs +169 -0
  124. package/tools/lib/brain-relate.mjs +235 -0
  125. package/tools/lib/brain-text.mjs +121 -0
  126. package/tools/lib/case-tool.mjs +186 -0
  127. package/tools/lib/docs-core.mjs +392 -0
  128. package/tools/lib/docs-version.mjs +66 -0
  129. package/tools/lib/envMap.mjs +31 -0
  130. package/tools/lib/health-core.mjs +94 -0
  131. package/tools/lib/import-graph.mjs +118 -0
  132. package/tools/lib/index-io.mjs +70 -0
  133. package/tools/lib/open.mjs +32 -0
  134. package/tools/lib/prefix-cost.mjs +143 -0
  135. package/tools/lib/ratchet.mjs +174 -0
  136. package/tools/lib/reach.mjs +28 -0
  137. package/tools/lib/sessionDump.mjs +80 -0
  138. package/tools/lib/source-text.mjs +112 -0
  139. package/tools/library-book.mjs +313 -0
  140. package/tools/library-build.mjs +50 -12
  141. package/tools/library-index.mjs +91 -0
  142. package/tools/lint.mjs +282 -0
  143. package/tools/log-audit.mjs +108 -0
  144. package/tools/manifest-sync.mjs +111 -0
  145. package/tools/memory-audit.mjs +67 -0
  146. package/tools/module-audit.mjs +56 -0
  147. package/tools/mutate.mjs +316 -0
  148. package/tools/prefix-audit.mjs +122 -0
  149. package/tools/prefix-drift.mjs +325 -0
  150. package/tools/privacy-guard.mjs +352 -0
  151. package/tools/quality-audit.mjs +166 -0
  152. package/tools/schema-fingerprint.mjs +191 -0
  153. package/{src/dsh → tools}/selftest.mjs +75 -22
  154. package/tools/smells.mjs +398 -0
  155. package/tools/verify-case-paths.mjs +93 -0
  156. package/tools/version.mjs +191 -0
  157. package/docs/MASTER-PLAN-2.0.0.md +0 -133
  158. package/docs/MASTER-PLAN-3.0.0.md +0 -76
  159. package/src/adapters/dsh/fg-appeal-tool.mjs +0 -47
  160. package/src/adapters/dsh/fg-apply-tool.mjs +0 -68
  161. /package/{src/adapters/dsh → hooks}/protocol.mjs +0 -0
@@ -0,0 +1,182 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 工具链健康分(tools/health.mjs,2026-10-27)——内置化第三件,零依赖。
4
+ *
5
+ * 定位:**聚合器**,不重复实现任何扫描。四个维度各自来自已有工具:
6
+ * 房规 ← tools/lint.mjs
7
+ * 结构 ← tools/smells.mjs
8
+ * 测试 ← 静态分析:哪些 src 模块没有被任何测试引用
9
+ * 口径 ← tools/quality-audit.mjs
10
+ *
11
+ * 为什么自己算分:
12
+ * 上一轮用 `brooks-lint` 出健康分,91/100。分数本身没问题,但**它的扣分项是按它自己的
13
+ * 十三条风险模型算的**,与本仓关心的四件事(房规/结构/测试/口径)不完全对齐;而且它
14
+ * 每维封顶 3 条,91 分读起来像"只差 9 分",实际未封顶的问题是 66 条死 import + 398 行函数。
15
+ * 本工具的分**不做封顶**,扣满为止——分数难看是故意的。
16
+ *
17
+ * 计分口径(2026-10-27 修):**只算 src/ 活跃层**。
18
+ * 首版把全部 66 条房规问题按 −1/条 扣,扣到 34 分,可其中 54 条在 `hooks/guard.mjs`
19
+ * 与 `hooks/protocol.mjs`——那是已封存不维护的代码。**已封存代码的债务不是当前债务**,
20
+ * 把它算进健康分与 `dsh-code-check` 的 0/100 是同一个病:扣分项与"当前该修的"不对齐。
21
+ * 所以:src/ 计分,tools/+tests/+hooks/ 单列(不藏,只是不计分),输出里逐栏写明。
22
+ *
23
+ * 评分规则(确定性:同输入必同分):
24
+ * 房规 = 100 − min(70, src 层问题数 × 1)
25
+ * 结构 = 100 − min(70, 源文件异味数 × 3)
26
+ * 测试 = 100 − min(70, 无测试的 src 模块数 × 4)
27
+ * 口径 = 100 − min(70, 未交代×10 + 清单重复×5)
28
+ * 总分 = 加权(结构 0.30 / 房规 0.25 / 测试 0.25 / 口径 0.20),四舍五入
29
+ *
30
+ * 用法:
31
+ * node packages/core/tools/health.mjs # 明细 + 总分
32
+ * node packages/core/tools/health.mjs --brief # 一行
33
+ * node packages/core/tools/health.mjs --json
34
+ * node packages/core/tools/health.mjs --strict # 低于债务上限 exit 1
35
+ *
36
+ * 关于 `--strict`(2026-10-27):原为"低于 80 分 exit 1",但当前 79 分且短期上不去
37
+ * (结构维被 1243 行文件压着),那条闸门一开就红——与 lint/smells 同一个坑。
38
+ * 改成棘轮:BUDGET 记当前分,只许升不许降。本工具**不进 check 链**:它的四个维度
39
+ * 各自已被 lint/smells/quality-audit 单独把守,聚合分再加一道只会产生更模糊的信号。
40
+ */
41
+
42
+ import { spawnSync } from 'node:child_process'
43
+ import { join, dirname, resolve } from 'node:path'
44
+ import { fileURLToPath } from 'node:url'
45
+ // 判定逻辑在 lib/(纯函数、可测)。本文件只做"取数 → 调 → 打印"。
46
+ import { splitLintByLayer, classifyReach, weightedScore, dimensionScore, cappedScore } from './lib/health-core.mjs'
47
+ import { buildImportGraph, walk, relToSrc } from './lib/import-graph.mjs'
48
+
49
+ const HERE = dirname(fileURLToPath(import.meta.url))
50
+ const REPO = resolve(HERE, '../../..')
51
+
52
+ const argv = process.argv.slice(2)
53
+ const BRIEF = argv.includes('--brief')
54
+ const AS_JSON = argv.includes('--json')
55
+ const STRICT = argv.includes('--strict')
56
+
57
+ /** 债务上限(棘轮):总分不许低于此值。只许升不许降。2026-10-27:79 → 93。 */
58
+ const BUDGET = 93
59
+
60
+ const runJson = (tool) => {
61
+ const r = spawnSync('node', [join(HERE, tool), '--json'], { cwd: REPO, encoding: 'utf8' })
62
+ try {
63
+ return JSON.parse(r.stdout)
64
+ } catch {
65
+ throw new Error(`${tool} 的 JSON 输出无法解析(exit ${r.status}):${(r.stderr || '').slice(0, 200)}`)
66
+ }
67
+ }
68
+
69
+ /**
70
+ * 取数:从测试与封存层出发,各求一次 src 内部的可达闭包。
71
+ *
72
+ * 判定逻辑在 `lib/health-core.mjs` 的 `classifyReach`(纯函数、可测);
73
+ * 读文件与解析 import 在 `lib/import-graph.mjs`(与 mutate.mjs 共用同一张图)。
74
+ * 这里只做粘合。
75
+ */
76
+ function coverage() {
77
+ const g = buildImportGraph(REPO)
78
+ const r = classifyReach({
79
+ srcFiles: g.srcFiles,
80
+ testSeeds: walk(join(REPO, 'packages/core/tests')),
81
+ frozenSeeds: g.frozenFiles,
82
+ depsOf: g.depsOf,
83
+ })
84
+ const rel = (f) => relToSrc(g.srcDir, f)
85
+ return { total: r.total, active: r.active, frozenOnly: r.frozenOnly.map(rel), orphan: r.orphan.map(rel) }
86
+ }
87
+
88
+ const lint = runJson('lint.mjs')
89
+ const smells = runJson('smells.mjs')
90
+ const audit = runJson('quality-audit.mjs')
91
+ const cov = coverage()
92
+
93
+ // 房规按层分栏:只有 src/ 活跃层计分(见头注释「计分口径」)
94
+ const lintLayer = splitLintByLayer(lint.findings)
95
+
96
+ const DIMS = [
97
+ {
98
+ key: '房规',
99
+ weight: 0.25,
100
+ hits: lintLayer.src.length,
101
+ score: dimensionScore(lintLayer.src.length, 1),
102
+ top: lintLayer.src.length
103
+ ? `${Object.entries(
104
+ lintLayer.src.reduce((a, f) => ({ ...a, [f.rule]: (a[f.rule] || 0) + 1 }), {}),
105
+ ).sort((a, b) => b[1] - a[1])[0][0]} 为主(${lintLayer.src.length} 条)`
106
+ : 'Clean(src 层 0 条)',
107
+ },
108
+ {
109
+ key: '结构',
110
+ weight: 0.3,
111
+ hits: smells.srcFindings.length,
112
+ score: dimensionScore(smells.srcFindings.length, 3),
113
+ top: smells.srcFindings.length
114
+ ? smells.srcFindings.slice().sort((a, b) => b.value - a.value)[0].detail
115
+ : 'Clean',
116
+ },
117
+ {
118
+ key: '测试',
119
+ weight: 0.25,
120
+ hits: cov.orphan.length,
121
+ score: dimensionScore(cov.orphan.length, 4),
122
+ top: cov.orphan.length
123
+ ? `${cov.orphan.length}/${cov.total} 个 src 模块测试与封存层都不可达`
124
+ : `Clean(${cov.active}/${cov.total} 可达;${cov.frozenOnly.length} 个仅封存层可达)`,
125
+ },
126
+ {
127
+ key: '口径',
128
+ weight: 0.2,
129
+ hits: audit.holes.length + audit.dupInList.length,
130
+ score: cappedScore(audit.holes.length * 10 + audit.dupInList.length * 5),
131
+ top: audit.holes.length || audit.dupInList.length ? `未交代 ${audit.holes.length} / 清单重复 ${audit.dupInList.length}` : 'Clean',
132
+ },
133
+ ]
134
+
135
+ const composite = weightedScore(DIMS)
136
+
137
+ if (AS_JSON) {
138
+ console.log(
139
+ JSON.stringify(
140
+ {
141
+ composite,
142
+ dimensions: DIMS,
143
+ lintByLayer: {
144
+ src: lintLayer.src.length,
145
+ tools: lintLayer.tools.length,
146
+ tests: lintLayer.tests.length,
147
+ hooks: lintLayer.hooks.length,
148
+ },
149
+ untested: { active: cov.active, frozenOnly: cov.frozenOnly, orphan: cov.orphan },
150
+ },
151
+ null,
152
+ 2,
153
+ ),
154
+ )
155
+ } else if (BRIEF) {
156
+ const parts = DIMS.map((d) => `${d.key} ${d.score}`).join(' / ')
157
+ const side = lintLayer.tools.length + lintLayer.tests.length + lintLayer.hooks.length
158
+ console.log(`工具链健康分:${composite}/100(${parts};层外房规 ${side} 条不计分)`)
159
+ } else {
160
+ console.log(`工具链健康分:${composite}/100\n`)
161
+ console.log('维度\t权重\t得分\t首要问题')
162
+ for (const d of DIMS) console.log(`${d.key}\t${d.weight}\t${d.score}\t${d.top}`)
163
+ console.log('\n扣分不封顶(每维扣满 70 为止),分数难看是故意的:')
164
+ console.log(` 房规 ${lintLayer.src.length} 条(每条 −1)`)
165
+ console.log(` 结构 ${smells.srcFindings.length} 条(每条 −3)`)
166
+ console.log(` 测试 ${cov.orphan.length} 个模块双不可达(每个 −4)`)
167
+ console.log(` 口径 未交代 ${audit.holes.length} 条(每条 −10)+ 清单重复 ${audit.dupInList.length} 条(每条 −5)`)
168
+ console.log('\n计分口径 = 仅 src/ 活跃层。层外房规单列、不计分:')
169
+ console.log(` tools/ ${lintLayer.tools.length} 条`)
170
+ console.log(` tests/ ${lintLayer.tests.length} 条`)
171
+ console.log(` hooks/ ${lintLayer.hooks.length} 条(已封存,不维护)`)
172
+ console.log(`\nsrc 模块可达性:${cov.active}/${cov.total} 从测试可达`)
173
+ if (cov.frozenOnly.length) {
174
+ console.log(` ${cov.frozenOnly.length} 个仅封存层可达(不扣分,单列):`)
175
+ for (const f of cov.frozenOnly) console.log(` ${f}`)
176
+ }
177
+ if (cov.orphan.length) {
178
+ console.log(` ${cov.orphan.length} 个双不可达(扣分):`)
179
+ for (const f of cov.orphan) console.log(` ${f}`)
180
+ }
181
+ }
182
+ process.exit(STRICT && composite < BUDGET ? 1 : 0)
@@ -0,0 +1,118 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 【私有工具】知识库统一索引(2026-10-31,M2)
4
+ *
5
+ * 产物落 `.ai/output/`——私有面,不入库、不随 npm 分发。
6
+ *
7
+ * ## 为什么有 namespace
8
+ *
9
+ * 源文件是 `B001-主题-1-防幻觉-…`(106 份),积木是 `B001-s-级-改改措辞就能进-rules-…`(28 块)。
10
+ * **同一个 B001 指两个文件。** 统一索引里必须带 `ns`(src / note / block),
11
+ * 唯一键是 `ns:id`——`src:B001` 与 `block:B001` 是两条,不是一条。
12
+ *
13
+ * ## 为什么不接进 check 链
14
+ *
15
+ * 归档是冻结快照。索引它,`--check` 永远零漂移——一条永远绿的闸门,
16
+ * 跟 schema:verify 空转 8 天是同一个形状(2026-10-29 抓到的病)。
17
+ * 所以 `--check` 只作为「快照没被手改」的取证工具,**不进 npm run check**。
18
+ *
19
+ * ## 四个源(2026-10-31 按归档 README 纠正)
20
+ *
21
+ * src docs/vault-notes/ 外部原文(8 份,**唯一可信源**)
22
+ * note .ai/notes/ 自研笔记(12 份,含 prompts-mining/ 子目录)
23
+ * block .ai/output/library/ 当前派生积木(28 块)
24
+ * hist .ai/archive/library/<日期>/ 历史派生积木(106 份)
25
+ *
26
+ * 第一版把 `hist` 当成 `src` 索引,是错的——`.ai/archive/library/2026-10-08/`
27
+ * 的 README 第一句就是「这是历史归档,不是工作区」,那 105 份是 `library-build`
28
+ * 当年切出来的派生视图,`source:` 多已指向不存在的路径。真正的原文在
29
+ * `docs/vault-notes/`。**索引历史可以,但必须标成 hist,不能混进 src。**
30
+ *
31
+ * ## 用法
32
+ *
33
+ * node tools/knowledge.mjs 重建 knowledge.json
34
+ * node tools/knowledge.mjs --check 只比对,不写;漂移则退 1
35
+ */
36
+ import { existsSync, readFileSync, readdirSync } from 'node:fs'
37
+ import { join } from 'node:path'
38
+ import { parseBlock } from './library-index.mjs'
39
+ import { diffKeys, runIndexTool } from './lib/index-io.mjs'
40
+
41
+ const OUT = '.ai/output/knowledge.json'
42
+ const SOURCES = [
43
+ { ns: 'src', dir: 'docs/vault-notes', test: /\.md$/ },
44
+ { ns: 'note', dir: '.ai/notes', test: /\.md$/ },
45
+ { ns: 'block', dir: '.ai/output/library', test: /^B\d{3}-.+\.md$/ },
46
+ { ns: 'hist', dir: '.ai/archive/library', test: /\.md$/ },
47
+ ]
48
+
49
+ /** 递归列出相对路径(正斜杠)。目录不存在返回空数组,不抛。 */
50
+ function walk(dir, test, prefix = '') {
51
+ if (!existsSync(dir)) return []
52
+ const out = []
53
+ for (const d of readdirSync(join(dir, prefix), { withFileTypes: true })) {
54
+ const rel = prefix ? `${prefix}/${d.name}` : d.name
55
+ if (d.isDirectory()) out.push(...walk(dir, test, rel))
56
+ else if (test.test(d.name)) out.push(rel)
57
+ }
58
+ return out.sort()
59
+ }
60
+
61
+ /** 单个文件 → 索引项。block 走 library-index 的 parseBlock,不另写一套解析。 */
62
+ export function entryOf(ns, dir, rel) {
63
+ const abs = join(dir, rel)
64
+ const chars = readFileSync(abs, 'utf8').length
65
+ const name = rel.split('/').pop()
66
+ if (ns === 'block') {
67
+ const b = parseBlock(name, chars)
68
+ return b ? { ns, ...b, path: abs } : null
69
+ }
70
+ const stem = rel.replace(/\.md$/, '')
71
+ const numbered = /^B(\d{3})-(.+)$/.exec(name.replace(/\.md$/, ''))
72
+ return {
73
+ ns,
74
+ id: numbered ? `B${numbered[1]}` : stem,
75
+ topic: numbered ? numbered[2] : stem,
76
+ path: abs,
77
+ chars,
78
+ }
79
+ }
80
+
81
+ /** 扫三个源,出统一索引。不写盘。 */
82
+ export function buildKnowledge() {
83
+ const entries = []
84
+ const sources = []
85
+ for (const { ns, dir, test } of SOURCES) {
86
+ const files = walk(dir, test)
87
+ const got = files.map((rel) => entryOf(ns, dir, rel)).filter(Boolean)
88
+ entries.push(...got)
89
+ sources.push({ ns, dir, count: got.length })
90
+ }
91
+ return { sources, entries }
92
+ }
93
+
94
+ /** 零漂移判据:ns:id:path:chars 四元组全等。改一个字都算。 */
95
+ const KEY = (e) => `${e.ns}:${e.id}:${e.path}:${e.chars}`
96
+ export function diffKnowledge(expected, actual) {
97
+ return diffKeys(expected, actual, KEY, 'entries')
98
+ }
99
+
100
+ function main() {
101
+ runIndexTool({
102
+ argv: process.argv.slice(2),
103
+ build: buildKnowledge,
104
+ field: 'entries',
105
+ out: OUT,
106
+ label: 'knowledge.json',
107
+ keyOf: KEY,
108
+ prefix: '[knowledge]',
109
+ empty: '三个源都没扫到文件,先确认 .ai/ 下有没有资料',
110
+ summary: (i) => {
111
+ const byNs = i.sources.map((s) => `${s.ns} ${s.count}`).join(' / ')
112
+ const chars = i.entries.reduce((n, e) => n + e.chars, 0)
113
+ return `${i.entries.length} 条(${byNs})/ ${chars} 字 → ${OUT}`
114
+ },
115
+ })
116
+ }
117
+
118
+ if (process.argv[1] && process.argv[1].endsWith('knowledge.mjs')) main()
@@ -0,0 +1,105 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 分层泄漏审计(2026-10-22)
4
+ *
5
+ * 方向纪律(`tests/layering.test.mjs` 已锁 import 方向):
6
+ * core(母版,与宿主无关) → adapter(各宿主映射) → seam(DSH 挂接/组装根)
7
+ * 但 import 方向对了,**内容**仍可能越界:母版里写死某个宿主的工具名/事件名/环境变量,
8
+ * 等于让母版替宿主代言 —— 换宿主就要改母版。
9
+ *
10
+ * 本工具只读扫描,输出三类问题:
11
+ * A 母版(src/core, hooks/)出现宿主专属标识
12
+ * B 适配层(src/adapters)出现别的宿主
13
+ * C 宿主缝(src/dsh)直接引用 ZCode 母版实现
14
+ *
15
+ * 用法:node packages/core/tools/layering-audit.mjs [--json] [--strict]
16
+ * --strict:发现问题即 exit 1(供 CI 用)
17
+ */
18
+
19
+ import { readdirSync, readFileSync, statSync } from 'node:fs'
20
+ import { dirname, join, relative } from 'node:path'
21
+ import { fileURLToPath } from 'node:url'
22
+
23
+ const HERE = dirname(fileURLToPath(import.meta.url))
24
+ const CORE = join(HERE, '..')
25
+ const ROOT = join(CORE, 'src')
26
+ const argv = process.argv.slice(2)
27
+
28
+ // 宿主专属标识:出现在母版里就是泄漏
29
+ const HOST_MARKS = {
30
+ dsh: /\b(?:dsh-native|ctx\.tools|agent\.session|tools\/pre-execute|session\/event|FG_PTC_\w+|FG_MUTATION_UNMAPPED|focus-guard-native)\b/,
31
+ zcode: /\b(?:ZCODE_\w+|CLAUDE_\w+|installed_plugins\.json|hookSpecificOutput)\b/,
32
+ }
33
+ // 宿主**工具**名(母版不该知道宿主方言)。shell 名(pwsh/powershell/bash)不算:
34
+ // 红线匹配的是"命令文本里的 shell",与宿主无关。
35
+ const TOOL_NAMES = /\b(?:Bash|Write|Edit|MultiEdit|Read|Grep|Glob|run_code)(?![\w-])/
36
+ // 白名单:规则文本(SESSION_RULES)里提到 Grep/head_limit 属面向模型的表述。
37
+ const ALLOW = {
38
+ toolNames: ['src/core/constants.mjs'],
39
+ }
40
+
41
+ function walk(dir, out = []) {
42
+ for (const e of readdirSync(dir)) {
43
+ const p = join(dir, e)
44
+ const st = statSync(p)
45
+ if (st.isDirectory()) walk(p, out)
46
+ else if (e.endsWith('.mjs') || e.endsWith('.js')) out.push(p)
47
+ }
48
+ return out
49
+ }
50
+
51
+ const files = walk(ROOT)
52
+ const findings = []
53
+
54
+ for (const f of files) {
55
+ const rel = relative(CORE, f).replace(/\\/g, '/')
56
+ const src = readFileSync(f, 'utf8')
57
+ const lines = src.split('\n')
58
+ const inCore = rel.startsWith('src/core/')
59
+ const inHooks = rel.startsWith('hooks/')
60
+ const inAdapter = rel.startsWith('src/adapters/')
61
+ const inDsh = rel.startsWith('src/dsh/')
62
+
63
+ lines.forEach((line, i) => {
64
+ const at = `${rel}:${i + 1}`
65
+ // A:母版出现宿主标识
66
+ if (inCore || inHooks) {
67
+ for (const [host, re] of Object.entries(HOST_MARKS)) {
68
+ if (re.test(line) && !/^\s*(\*|\/\/)/.test(line)) {
69
+ findings.push({ kind: `A 母版出现 ${host} 专属标识`, at, text: line.trim().slice(0, 100) })
70
+ }
71
+ }
72
+ if (TOOL_NAMES.test(line) && !ALLOW.toolNames.includes(rel) && !/^\s*(\*|\/\/)/.test(line)) {
73
+ findings.push({ kind: 'A 母版出现宿主工具名', at, text: line.trim().slice(0, 100) })
74
+ }
75
+ }
76
+ // B:适配层写死**别的**宿主(`src/adapters/dsh/` 出现 dsh 标识是本职,不算泄漏)
77
+ if (inAdapter) {
78
+ const own = (rel.match(/src\/adapters\/([^/]+)\//) || [])[1] || ''
79
+ for (const [host, re] of Object.entries(HOST_MARKS)) {
80
+ if (own === host) continue
81
+ if (re.test(line) && !/^\s*(\*|\/\/)/.test(line)) {
82
+ findings.push({ kind: `B ${own || '?'} 适配层出现 ${host} 标识`, at, text: line.trim().slice(0, 100) })
83
+ }
84
+ }
85
+ }
86
+ // C:宿主缝直接 import ZCode 母版实现
87
+ if (inDsh && /from\s+['"][^'"]*hooks\/[^'"]*['"]/.test(line)) {
88
+ findings.push({ kind: 'C 宿主缝直接引用 ZCode 母版代码', at, text: line.trim().slice(0, 100) })
89
+ }
90
+ })
91
+ }
92
+
93
+ const byKind = findings.reduce((acc, f) => ((acc[f.kind] = (acc[f.kind] || 0) + 1), acc), {})
94
+
95
+ if (argv.includes('--json')) {
96
+ console.log(JSON.stringify({ total: findings.length, byKind, findings }, null, 2))
97
+ } else {
98
+ console.log(`扫描 ${files.length} 个文件,发现 ${findings.length} 处分层泄漏`)
99
+ for (const [k, n] of Object.entries(byKind).sort((a, b) => b[1] - a[1])) console.log(` ${k}: ${n}`)
100
+ for (const f of findings.slice(0, 40)) console.log(` ${f.at}\n [${f.kind}] ${f.text}`)
101
+ if (findings.length > 40) console.log(` …(共 ${findings.length} 条,--json 看全部)`)
102
+ }
103
+
104
+ if (argv.includes('--strict') && findings.length > 0) process.exit(1)
105
+ process.exit(0)
@@ -0,0 +1,136 @@
1
+ /**
2
+ * 【私有工具的一部分】只服务 library-book.mjs(私有面成书),不进公开产品面。
3
+ *
4
+ * 资料书的版式(2026-10-30)
5
+ *
6
+ * 为什么单独一个文件:这是**排版**,不是取数也不是渲染。混在 library-book.mjs 里会把
7
+ * 那个文件顶过 400 行上限(结构异味闸门),而版式本身又确实有一百多行。
8
+ *
9
+ * 设计取舍:
10
+ * · 正文用衬线(Noto Serif / 思源宋 / 宋体),界面用无衬线——书是拿来读的,
11
+ * 长段中文用宋体更接近纸书;目录、出处、按钮这些"零件"用黑体,界限分明。
12
+ * · 行长 38em ≈ 38 个汉字,比网页默认窄。中文一行超过 45 字,眼睛回行会丢行。
13
+ * · 三种文字颜色各司其职:正文 --ink、说明 --ink2、标注 --dim。不要多,多了就花。
14
+ * · 认笔记自己的三层体例(条目名 .h / 动作行 .act / 出处行 .ref)。不认的话,
15
+ * 每条都摊成四段同样大小的字,读起来一片平——这就是"生硬"的来源。
16
+ * · 深色模式跟随系统,不另设开关:书是长时间看的,跟随系统才不用每次手动切。
17
+ *
18
+ * 这个字符串里没有反引号也没有 `${`,可以安全内嵌进 library-book 的模板。
19
+ */
20
+ export const BOOK_CSS = `
21
+ :root{
22
+ --side:320px;
23
+ --paper:#fcfaf6;--panel:#f5f1e8;--ink:#221f1c;--ink2:#4b443b;--dim:#8b8378;
24
+ --line:#e7e0d2;--accent:#9a6a3c;--soft:#f1e7d7;
25
+ --sans:ui-sans-serif,-apple-system,"Segoe UI","Microsoft YaHei",system-ui,sans-serif;
26
+ --serif:"Noto Serif SC","Source Han Serif SC","Songti SC",SimSun,Georgia,serif;
27
+ --mono:ui-monospace,Consolas,"Courier New",monospace;
28
+ }
29
+ @media(prefers-color-scheme:dark){
30
+ :root{--paper:#1c1a17;--panel:#161411;--ink:#eae4d9;--ink2:#c2bab0;--dim:#9a9186;
31
+ --line:#312c25;--accent:#cc9b6b;--soft:#282219}
32
+ }
33
+ *{box-sizing:border-box}
34
+ html,body{margin:0;height:100%}
35
+ body{display:grid;grid-template-columns:var(--side) 1fr;background:var(--panel);color:var(--ink);
36
+ font:17px/1.9 var(--serif);-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility}
37
+ ::selection{background:var(--soft);color:var(--ink)}
38
+
39
+ /* 左侧目录:书脊 */
40
+ aside{height:100vh;overflow:auto;border-right:1px solid var(--line);
41
+ padding:32px 0 48px;font-family:var(--sans);
42
+ scrollbar-width:thin;scrollbar-color:var(--line) transparent}
43
+ aside::-webkit-scrollbar{width:8px}
44
+ aside::-webkit-scrollbar-thumb{background:var(--line);border-radius:8px}
45
+ aside::-webkit-scrollbar-track{background:transparent}
46
+ .brand{padding:0 26px 22px}
47
+ .kicker{font-size:10.5px;letter-spacing:.3em;color:var(--accent);
48
+ text-transform:uppercase;margin-bottom:10px}
49
+ .brand h1{font-family:var(--serif);font-size:21px;line-height:1.4;margin:0 0 10px;font-weight:700}
50
+ .brand .meta{font-size:12px;color:var(--dim);line-height:1.7}
51
+ .search{padding:0 20px 4px}
52
+ #q{width:100%;padding:9px 12px;border:1px solid var(--line);border-radius:8px;
53
+ background:var(--paper);color:var(--ink);font-family:var(--sans);font-size:13px}
54
+ #q::placeholder{color:var(--dim)}
55
+ #q:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 3px var(--soft)}
56
+ .grp{font-size:10.5px;color:var(--dim);margin:22px 26px 8px;letter-spacing:.18em;
57
+ font-weight:600;display:flex;align-items:center;gap:10px}
58
+ .grp::after{content:"";flex:1;height:1px;background:var(--line)}
59
+ .item{display:flex;gap:10px;align-items:baseline;padding:9px 26px 9px 23px;
60
+ color:var(--ink2);text-decoration:none;font-size:13.5px;line-height:1.5;cursor:pointer;
61
+ border-left:3px solid transparent;transition:background .12s,color .12s}
62
+ .item:hover{background:var(--paper);color:var(--ink)}
63
+ .item.on{background:var(--soft);border-left-color:var(--accent);color:var(--ink);font-weight:600}
64
+ .item .n{flex:none;width:1.7em;text-align:right;color:var(--dim);
65
+ font:500 11px/1.7 var(--mono);font-variant-numeric:tabular-nums}
66
+ .item.on .n{color:var(--accent)}
67
+ /* 长标题最多两行,否则目录会被一条超长条目撑得参差不齐 */
68
+ .item .t{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;
69
+ overflow:hidden;text-overflow:ellipsis}
70
+ .aside-foot{margin:26px 26px 0;padding-top:16px;border-top:1px solid var(--line);
71
+ font-size:11.5px;color:var(--dim);line-height:1.8}
72
+
73
+ /* 右侧正文:书页 */
74
+ main{height:100vh;overflow:auto;scroll-behavior:smooth;background:var(--paper);position:relative}
75
+ #bar{position:fixed;top:0;left:var(--side);right:0;height:2px;z-index:20;pointer-events:none}
76
+ #bar i{display:block;height:100%;width:0;background:var(--accent);opacity:.5;
77
+ transition:width .12s linear}
78
+ .wrap{max-width:38em;margin:0 auto;padding:78px 46px 180px}
79
+ article+article{margin-top:78px;padding-top:64px;border-top:1px solid var(--line)}
80
+ .ch{margin-bottom:30px}
81
+ .ch .no{font:600 11px/1 var(--mono);letter-spacing:.24em;color:var(--accent);margin-bottom:14px}
82
+ .ch h2{font-family:var(--sans);font-size:27px;line-height:1.35;margin:0 0 14px;
83
+ font-weight:700;color:var(--ink)}
84
+ .ch .src{font-family:var(--sans);font-size:12px;color:var(--dim);line-height:1.7;
85
+ word-break:break-all}
86
+ .body{text-align:justify;text-justify:inter-ideograph}
87
+ .body p{margin:0 0 .95em}
88
+ /* 三层体例:条目名 / 动作行 / 出处行。间距刻意不同,让一条一条能分开 */
89
+ .body p.h{font-family:var(--sans);font-size:15.5px;line-height:1.6;font-weight:700;
90
+ margin:2em 0 .6em;color:var(--ink)}
91
+ .body p.act{margin:.1em 0 .35em;padding-left:1.2em;text-indent:-1.2em;color:var(--ink2)}
92
+ .body p.ref{margin:.3em 0 1.9em;font-family:var(--sans);font-size:12px;color:var(--dim);
93
+ letter-spacing:.01em;text-align:left}
94
+ .body h3{font-family:var(--sans);font-size:19px;line-height:1.5;margin:2.1em 0 .8em;
95
+ font-weight:700;color:var(--ink)}
96
+ .body h4{font-family:var(--sans);font-size:16px;line-height:1.5;margin:1.7em 0 .6em;
97
+ font-weight:600;color:var(--ink2)}
98
+ .body ul,.body ol{margin:0 0 1.15em;padding-left:1.5em}
99
+ .body li{margin:.34em 0}
100
+ .body li::marker{color:var(--accent)}
101
+ .body strong{font-weight:700;color:var(--ink)}
102
+ .body blockquote{margin:1.3em 0;padding:14px 18px;background:var(--soft);border-radius:10px;
103
+ border-left:3px solid var(--accent);color:var(--ink2);font-size:.93em;line-height:1.8;
104
+ text-align:left}
105
+ .body blockquote p{margin:0 0 .4em}
106
+ .body blockquote p:last-child{margin:0}
107
+ .body hr{border:0;width:52%;margin:2.4em auto;border-top:1px solid var(--line)}
108
+ code{font-family:var(--mono);font-size:.86em;background:var(--soft);color:var(--ink2);
109
+ padding:.12em .42em;border-radius:5px}
110
+ details summary{list-style:none;display:inline-flex;align-items:center;gap:9px;cursor:pointer;
111
+ font-family:var(--sans);font-size:12.5px;color:var(--accent);background:var(--soft);
112
+ border:1px solid var(--line);border-radius:999px;padding:7px 16px;margin-bottom:22px;
113
+ transition:background .12s}
114
+ details summary:hover{background:var(--panel)}
115
+ details summary::-webkit-details-marker{display:none}
116
+ details summary::before{content:"展开";font-size:11px;letter-spacing:.1em;opacity:.75}
117
+ details[open] summary::before{content:"收起"}
118
+
119
+ /* 窄屏:目录收起,正文占满(手机上侧栏没地方放) */
120
+ @media(max-width:900px){
121
+ :root{--side:0px}
122
+ body{grid-template-columns:1fr}
123
+ aside{display:none}
124
+ #bar{left:0}
125
+ .wrap{padding:44px 22px 120px}
126
+ .ch h2{font-size:23px}
127
+ }
128
+ /* 打印:书本来就该能打印。目录与进度条去掉,每章另起一页 */
129
+ @media print{
130
+ aside,#bar,#q{display:none}
131
+ body{display:block;background:#fff}
132
+ main{height:auto;overflow:visible}
133
+ .wrap{max-width:none;padding:0}
134
+ article+article{page-break-before:always;border-top:0}
135
+ }
136
+ `