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,94 @@
1
+ /**
2
+ * 健康分的纯逻辑(tools/lib/health-core.mjs,2026-10-27)。
3
+ *
4
+ * 为什么抽出来:`tools/health.mjs` 是个 CLI——它在模块顶层就 spawn 子进程跑 lint/smells/audit,
5
+ * 一 import 就会执行。这种文件**没法被测试**,而本仓已经因为"工具自己没被测"翻过三次车
6
+ * (合成参数假绿、比率分母被操纵、关键词匹配测不出改写采入)。
7
+ * 所以判定逻辑全部搬到这里,CLI 只做"取数 → 调这里 → 打印"。
8
+ *
9
+ * 三个导出都是纯函数:不碰 fs、不 spawn、同输入必同输出。
10
+ */
11
+
12
+ import { reachClosure } from './reach.mjs'
13
+
14
+ /**
15
+ * 房规问题按层分栏。
16
+ *
17
+ * 为什么分层:全仓 54 条房规问题全在 `hooks/`(已封存不维护)。把封存代码的债务算进
18
+ * 当前健康分,与 `dsh-code-check` 的 0/100 是同一个病——**扣分项与"当前该修的"不对齐**。
19
+ * 计分只认 src/ 活跃层,其余单列(不藏,只是不计分)。
20
+ */
21
+ export function splitLintByLayer(findings) {
22
+ const out = { src: [], tools: [], tests: [], hooks: [] }
23
+ for (const f of findings) {
24
+ const rel = String(f.file || '').replace(/\\/g, '/')
25
+ if (/^packages\/core\/src\//.test(rel)) out.src.push(f)
26
+ else if (/^packages\/core\/tests\//.test(rel)) out.tests.push(f)
27
+ else if (/^packages\/core\/hooks\//.test(rel)) out.hooks.push(f)
28
+ else out.tools.push(f)
29
+ }
30
+ return out
31
+ }
32
+
33
+ /**
34
+ * 可达性分类:src 模块分成三档。
35
+ *
36
+ * active 从测试可达 → 正常
37
+ * frozenOnly 只从 hooks/(已封存)可达 → 不扣分,单列
38
+ * orphan 两组种子都到不了 → 确定没人用,扣分
39
+ *
40
+ * 为什么要区分 frozenOnly(2026-10-27):`core/approval.mjs` 的四个导出只被
41
+ * `hooks/guard.mjs` 引,原生侧已由 `adapters/dsh/eligibility-gate.mjs` 替代。
42
+ * 它不是"缺测试",是**只服务封存路径**——给不维护的代码补测试是浪费。
43
+ * 这与"已封存代码的债务不算当前债务"是同一条原则。
44
+ *
45
+ * `depsOf(file)` 由调用方注入(CLI 传 fs 实现,测试传假 Map)。这样这个函数不碰磁盘。
46
+ *
47
+ * @param {{ srcFiles: string[], testSeeds: string[], frozenSeeds: string[], depsOf: (f: string) => string[] }} p
48
+ */
49
+ export function classifyReach({ srcFiles, testSeeds, frozenSeeds, depsOf }) {
50
+ const srcSet = new Set(srcFiles)
51
+
52
+ const closure = (seeds) => reachClosure(srcSet, seeds, depsOf)
53
+
54
+ const byTests = closure(testSeeds)
55
+ const byFrozen = closure(frozenSeeds)
56
+ const notTested = srcFiles.filter((f) => !byTests.has(f))
57
+ return {
58
+ total: srcFiles.length,
59
+ active: srcFiles.length - notTested.length,
60
+ frozenOnly: notTested.filter((f) => byFrozen.has(f)).sort(),
61
+ orphan: notTested.filter((f) => !byFrozen.has(f)).sort(),
62
+ }
63
+ }
64
+
65
+ /**
66
+ * 加权总分。**不做四舍五入以外的任何平滑**,也不封顶——
67
+ * 每维扣分由调用方自己封顶(扣满 70 为止),总分直接加权求和。
68
+ * 分数难看是故意的:上一轮 brooks-lint 每维封顶 3 条,91 分读起来像"只差 9 分"。
69
+ *
70
+ * @param {{ score: number, weight: number }[]} dims
71
+ */
72
+ export function weightedScore(dims) {
73
+ const w = dims.reduce((s, d) => s + d.weight, 0)
74
+ if (Math.abs(w - 1) > 1e-9) throw new Error(`维度权重之和应为 1,实际 ${w}`)
75
+ return Math.round(dims.reduce((s, d) => s + d.score * d.weight, 0))
76
+ }
77
+
78
+ /**
79
+ * 单维得分:100 起扣,**扣到 70 为止**,所以保底 30 分、不归零。
80
+ *
81
+ * 为什么保底不归零:归零会抹掉"这一维已经烂到什么程度"的信息——
82
+ * `dsh-code-check` 打 0/100 之后,没人再关心它到底是 66 条还是 681 条。
83
+ * 保底 30 让"继续变坏"仍有可见的位移,也让总分不被单维拖死。
84
+ *
85
+ * 拆成两个函数是因为「口径」维的罚分是混合的(未交代 ×10 + 重复行 ×5),
86
+ * 不能表达成"条数 × 单一罚分"。`cappedScore` 收总罚分,`dimensionScore` 是它的简写。
87
+ */
88
+ export function cappedScore(totalPenalty) {
89
+ return 100 - Math.min(70, totalPenalty)
90
+ }
91
+
92
+ export function dimensionScore(hits, penaltyPerHit) {
93
+ return cappedScore(hits * penaltyPerHit)
94
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * import 图(tools/lib/import-graph.mjs,2026-10-27)。
3
+ *
4
+ * 为什么抽出来:`tools/health.mjs`(算可达性)与 `tools/mutate.mjs`(选测试文件)
5
+ * 需要**同一张图**。同一段逻辑写两遍必然分叉——本仓已经栽过一次:`stripLiterals`
6
+ * 各写一份,smells 那份漏了正则字面量,把 398 行的函数抹成 0。
7
+ *
8
+ * 三种引用形态都必须认,否则"没引用"就是假阴性:
9
+ * ① `import x from './a.mjs'`
10
+ * ② `await import('./a.mjs')`
11
+ * ③ `fileURLToPath(new URL('../src/a.mjs', import.meta.url))` ← 跑 CLI 的测试只拼路径,不 import
12
+ *
13
+ * 这里**刻意不用** `stripLiterals`:它会把字符串内容抹成空格,而 import 的路径就在字符串里。
14
+ * 去字面量是给"查运算符"用的,不是给"查路径"用的。
15
+ */
16
+
17
+ import { readFileSync, readdirSync, statSync } from 'node:fs'
18
+ import { join, dirname, resolve, relative } from 'node:path'
19
+ import { reachClosure } from './reach.mjs'
20
+
21
+ const IMPORT_RE =
22
+ /(?:^|\n)\s*(?:import|export)\b[^\n]*?from\s*['"]([^'"]+)['"]|import\s*\(\s*['"]([^'"]+)['"]\s*\)|new\s+URL\s*\(\s*['"]([^'"]+)['"]\s*,\s*import\.meta\.url\s*\)/g
23
+
24
+ export function walk(dir, out = []) {
25
+ let entries
26
+ try {
27
+ entries = readdirSync(dir)
28
+ } catch {
29
+ return out
30
+ }
31
+ for (const e of entries) {
32
+ const p = join(dir, e)
33
+ let st
34
+ try {
35
+ st = statSync(p)
36
+ } catch {
37
+ continue
38
+ }
39
+ if (st.isDirectory()) walk(p, out)
40
+ else if (/\.(mjs|cjs|js)$/.test(e)) out.push(p)
41
+ }
42
+ return out
43
+ }
44
+
45
+ /** 把 `./x.mjs` 这类相对说明符解析成绝对路径(补后缀、试 index)。非相对返回 null。 */
46
+ export function resolveSpec(fromFile, spec) {
47
+ if (!spec || !spec.startsWith('.')) return null
48
+ const base = resolve(dirname(fromFile), spec)
49
+ for (const cand of [base, `${base}.mjs`, `${base}.js`, join(base, 'index.mjs'), join(base, 'index.js')]) {
50
+ try {
51
+ if (statSync(cand).isFile()) return cand
52
+ } catch {
53
+ /* 试下一个候选 */
54
+ }
55
+ }
56
+ return null
57
+ }
58
+
59
+ /**
60
+ * 建图。
61
+ *
62
+ * @param {string} repoRoot
63
+ * @returns {{
64
+ * srcDir: string, srcFiles: string[], testFiles: string[], frozenFiles: string[],
65
+ * depsOf: (f: string) => string[],
66
+ * reachFrom: (seeds: string[]) => Set<string>,
67
+ * reachingTests: (srcFile: string) => string[],
68
+ * }}
69
+ */
70
+ export function buildImportGraph(repoRoot) {
71
+ const srcDir = join(repoRoot, 'packages/core/src')
72
+ const srcFiles = walk(srcDir)
73
+ const srcSet = new Set(srcFiles)
74
+ const testFiles = walk(join(repoRoot, 'packages/core/tests')).filter((f) => f.endsWith('.test.mjs'))
75
+ const frozenFiles = walk(join(repoRoot, 'packages/core/hooks'))
76
+
77
+ const cache = new Map()
78
+ const depsOf = (file) => {
79
+ if (cache.has(file)) return cache.get(file)
80
+ let text = ''
81
+ try {
82
+ text = readFileSync(file, 'utf8')
83
+ } catch {
84
+ /* 读不到就当无边 */
85
+ }
86
+ const out = []
87
+ for (const m of text.matchAll(IMPORT_RE)) {
88
+ const r = resolveSpec(file, m[1] || m[2] || m[3])
89
+ if (r && srcSet.has(r)) out.push(r)
90
+ }
91
+ cache.set(file, out)
92
+ return out
93
+ }
94
+
95
+ const reachFrom = (seeds) => reachClosure(srcSet, seeds, depsOf)
96
+
97
+ // 反向索引:src 模块 ← 触达它的测试文件。变异测试靠这个选测试,不必跑全量。
98
+ let reverse = null
99
+ const reachingTests = (srcFile) => {
100
+ if (!reverse) {
101
+ reverse = new Map()
102
+ for (const t of testFiles) {
103
+ for (const s of reachFrom([t])) {
104
+ if (!reverse.has(s)) reverse.set(s, [])
105
+ reverse.get(s).push(t)
106
+ }
107
+ }
108
+ }
109
+ return reverse.get(srcFile) || []
110
+ }
111
+
112
+ return { srcDir, srcFiles, testFiles, frozenFiles, depsOf, reachFrom, reachingTests }
113
+ }
114
+
115
+ /** 相对 `src/` 的展示路径(报告里用绝对路径没法读)。 */
116
+ export function relToSrc(srcDir, file) {
117
+ return relative(srcDir, file).replace(/\\/g, '/')
118
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * 索引工具的公共 IO(2026-10-31)
3
+ *
4
+ * `library-index.mjs` 与 `knowledge.mjs` 的 `--check` 分支逐行相同——
5
+ * smells 当场报「重复 9 行」,重复块从 41 涨到 43,顶破棘轮。
6
+ *
7
+ * 两个索引工具的差异只有三样:产物路径、索引字段名、条目唯一键。
8
+ * 其余(读旧索引、比对、报漂移、写盘)全一样,抽到这里。
9
+ *
10
+ * 唯一键由调用方给:`library-index` 用 `id|file|chars`,
11
+ * `knowledge` 用 `ns:id:path:chars`——后者多一个命名空间,
12
+ * 因为源文件与积木的编号撞车(都是 B001)。
13
+ */
14
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
15
+
16
+ /** 集合比对。keyOf 决定什么算「同一条」——改一个字就必须变。 */
17
+ export function diffKeys(expected, actual, keyOf, field) {
18
+ const a = new Set((expected[field] || []).map(keyOf))
19
+ const b = new Set((actual[field] || []).map(keyOf))
20
+ return {
21
+ missing: [...a].filter((k) => !b.has(k)),
22
+ extra: [...b].filter((k) => !a.has(k)),
23
+ }
24
+ }
25
+
26
+ /**
27
+ * 写盘或比对,二选一。返回 `{ code, message, detail? }`,调用方负责打印与退出。
28
+ * `code` 就是进程退出码:0 干净 / 1 漂移或缺基线 / 2 无数据(调用方自己判)。
29
+ */
30
+ export function emit({ out, index, check, keyOf, field, label, summary }) {
31
+ if (!check) {
32
+ writeFileSync(out, JSON.stringify({ generated: new Date().toISOString(), ...index }, null, 2) + '\n')
33
+ return { code: 0, message: summary }
34
+ }
35
+ if (!existsSync(out)) {
36
+ return { code: 1, message: `${label} 不存在,先跑一次不带 --check 的` }
37
+ }
38
+ const { missing, extra } = diffKeys(index, JSON.parse(readFileSync(out, 'utf8')), keyOf, field)
39
+ if (missing.length || extra.length) {
40
+ return {
41
+ code: 1,
42
+ message: `漂移:磁盘侧新增 ${missing.length} 条、索引侧多余 ${extra.length} 条`,
43
+ detail: [...missing, ...extra].slice(0, 10),
44
+ }
45
+ }
46
+ return { code: 0, message: `零漂移,${(index[field] || []).length} 条` }
47
+ }
48
+
49
+ /**
50
+ * 索引工具的整个 main 骨架:建 → 空判 → 写/比 → 打印 → 退出。
51
+ *
52
+ * 上一步只抽了 `emit`,两个 `main` 仍逐行相同(smells 报重复 17 行,比抽之前更长)。
53
+ * 说明「只抽中间一段」不够——**重复的是骨架,不是某一段**。
54
+ *
55
+ * `summary` 收函数而不是字符串:调用方要按自己的字段算(块数/条数/字数)。
56
+ */
57
+ export function runIndexTool({ argv, build, field, out, label, keyOf, empty, summary, prefix }) {
58
+ const index = build()
59
+ if (!(index[field] || []).length) {
60
+ console.error(`${prefix} ${empty}`)
61
+ process.exit(2)
62
+ }
63
+ const r = emit({ out, index, check: argv.includes('--check'), keyOf, field, label, summary: summary(index) })
64
+ if (r.code) {
65
+ console.error(`${prefix} ${r.message}`)
66
+ for (const k of r.detail || []) console.error(` ${k}`)
67
+ process.exit(r.code)
68
+ }
69
+ console.log(`${prefix} ${r.message}`)
70
+ }
@@ -0,0 +1,32 @@
1
+ // 用系统默认程序打开一个文件(2026-11-08)
2
+ //
3
+ // 为什么单独一个文件:`brain.mjs`(模板版)与 `brain-cosmic.mjs`(本地皮层版)
4
+ // 都要「生成完顺手打开」。同一个三行分支抄两遍,下一次改平台适配就会只改一处——
5
+ // 重复块是这么长出来的,不是一开始就想抄。
6
+ //
7
+ // 用 detached + unref:启动器是 GUI 进程,不该把 CLI 挂着等它退出。
8
+ // 打不开不抛错:headless / 无关联程序的环境里这是常态,不是故障;
9
+ // 调用方在输出里已经给了绝对路径,兜底靠那一行。
10
+
11
+ import { spawn } from "node:child_process";
12
+
13
+ /**
14
+ * @param {string} file 绝对路径
15
+ * @returns {boolean} 是否成功发起(不代表对方一定打开)
16
+ */
17
+ export function openInBrowser(file) {
18
+ const [cmd, args] =
19
+ process.platform === "win32"
20
+ ? ["cmd", ["/c", "start", "", file]]
21
+ : process.platform === "darwin"
22
+ ? ["open", [file]]
23
+ : ["xdg-open", [file]];
24
+ try {
25
+ const p = spawn(cmd, args, { detached: true, stdio: "ignore", windowsHide: true });
26
+ p.on("error", () => {});
27
+ p.unref();
28
+ return true;
29
+ } catch {
30
+ return false;
31
+ }
32
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * 费用对比与面板对账(2026-10-29 从 prefix-drift.mjs 抽出,纯搬运)。
3
+ *
4
+ * 口径两条,别混:
5
+ * - est4(字符/4):只是估算,用来比较"改前 vs 改后"的相对差;
6
+ * - 面板实测(panel-runs.json):真实 token 与命中率,`collect-panel.mjs` 产出,带 session id。
7
+ * 能按 sid 匹配到本地会话时,用 `实测/est4` 给出校准系数,避免把估算当账单。
8
+ */
9
+ import { basename, dirname } from 'node:path'
10
+ import { readFileSync } from 'node:fs'
11
+ import { decodeSession, textOfMessage, walkSessionFiles } from './sessionDump.mjs'
12
+ import { calcCost } from '../../src/peak-cost.mjs'
13
+
14
+ /**
15
+ * 费用对比:改前 vs 改后。
16
+ *
17
+ * 机制前提(实测):宿主 `systemPromptUpdate: "in-history"`——系统提示一变,就**追加一条完整的
18
+ * system 消息**(约 10,280 字),此后每一步都背着它。所以 FG 抖 480 字,代价是 21 倍放大的整份提示。
19
+ */
20
+ export function runCost({ sessionsDir, limit = 8 } = {}) {
21
+ const TOK = (chars) => Math.round(chars / 4)
22
+ const rows = []
23
+ for (const cand of walkSessionFiles(sessionsDir)
24
+ .filter((x) => x.size < 3 * 1024 * 1024)
25
+ .slice(0, limit)) {
26
+ let lines
27
+ try {
28
+ lines = decodeSession(cand.f)
29
+ } catch {
30
+ continue
31
+ }
32
+ const steps = []
33
+ let cur = null
34
+ let prefixChars = 0
35
+ for (const l of lines) {
36
+ if (l.type === 'request/header') {
37
+ const hd = (l.data && (l.data.header || l.data)) || {}
38
+ if (Array.isArray(hd.tools)) prefixChars += JSON.stringify(hd.tools).length
39
+ continue
40
+ }
41
+ if (l.type === 'step/start') {
42
+ cur = { msgs: 0, sysChars: 0, sysCount: 0 }
43
+ steps.push(cur)
44
+ continue
45
+ }
46
+ if (!cur) continue
47
+ if (l.type === 'system/message') {
48
+ const t = textOfMessage(l)
49
+ cur.sysChars += t.length
50
+ cur.sysCount += 1
51
+ prefixChars += t.length
52
+ } else if (l.type === 'user/message' || l.type === 'assistant/message' || l.type === 'tool/result') {
53
+ cur.msgs += textOfMessage(l).length
54
+ }
55
+ }
56
+ if (steps.length < 5) continue
57
+ const sysSteps = []
58
+ for (let i = 0; i < steps.length; i += 1) if (steps[i].sysCount > 0) sysSteps.push(i)
59
+ let cum = 0
60
+ let totalChars = 0
61
+ for (const s of steps) {
62
+ cum += s.msgs
63
+ totalChars += prefixChars + cum
64
+ }
65
+ const sysChars = steps[sysSteps[0]].sysChars
66
+ const appends = Math.max(0, sysSteps.length - 1)
67
+ const carried = appends ? steps.length - sysSteps[1] : 0
68
+ const totalTok = TOK(totalChars)
69
+ const extraTok = TOK(sysChars * appends * carried)
70
+ const missTok = TOK(sysChars * appends)
71
+ const before = calcCost('deepseek-flash', { input: missTok, cacheRead: extraTok - missTok, output: 0 }, false)
72
+ const afterTok = totalTok - extraTok
73
+ const after = calcCost('deepseek-flash', { input: 0, cacheRead: afterTok, output: 0 }, false)
74
+ if (before === null || after === null) continue
75
+ rows.push({
76
+ sid: basename(dirname(cand.f)).replace('session-', '').slice(0, 8),
77
+ steps: steps.length,
78
+ appends,
79
+ totalTok,
80
+ extraTok,
81
+ before,
82
+ after,
83
+ beforeTotal: before + after,
84
+ afterTotal: after,
85
+ })
86
+ }
87
+ return rows
88
+ }
89
+
90
+ /**
91
+ * 面板实测对账:把 `panel-runs.json`(带 sid 的真实 token)按前 8 位 sid 匹配到本次扫描的会话,
92
+ * 给每行补 `real = {total, cacheRead, uncached, output, hit, factor}`。
93
+ * `factor = 实测/est4`:<1 表示 est4 高估,>1 表示低估。
94
+ *
95
+ * 2026-10-30 修两处:
96
+ * ① `hit` 原先用 `cacheRead / total`,而 total = uncached + cacheRead + **output**——
97
+ * output 不是缓存对象,把它算进命中率的分母会让命中率系统性偏低,
98
+ * 且与 `collect-panel.mjs` 的 `hitRate`(cacheRead/(cacheRead+uncached))同名不同值。
99
+ * 现统一用**输入**作分母。
100
+ * ② 返回体补诊断字段(panelRows / panelLatest / rowsScanned / error),
101
+ * 让"一条都没匹配上"能说清是**面板没数据**、**日期不相交**还是**读不了**——
102
+ * 原实现只说"无可匹配",读的人分不清是缺数据还是功能坏了。
103
+ */
104
+ export function attachPanel(rows, panelFile) {
105
+ let panel = []
106
+ let error = null
107
+ try {
108
+ panel = JSON.parse(readFileSync(panelFile, 'utf8'))
109
+ } catch (e) {
110
+ error = (e && e.message) || String(e)
111
+ panel = []
112
+ }
113
+ const list = Array.isArray(panel) ? panel : []
114
+ const bySid = new Map(rows.map((r) => [r.sid, r]))
115
+ let matched = 0
116
+ for (const p of list) {
117
+ const r = bySid.get(String((p && p.sid) || '').slice(0, 8))
118
+ if (!r) continue
119
+ matched += 1
120
+ const total = Number(p.total) || 0
121
+ const cacheRead = Number(p.cacheRead) || 0
122
+ const uncached = Number(p.uncached) || 0
123
+ const inputTok = cacheRead + uncached
124
+ r.real = {
125
+ total,
126
+ cacheRead,
127
+ uncached,
128
+ output: Number(p.output) || 0,
129
+ // 分母只算输入:output 不是缓存对象。
130
+ hit: inputTok ? cacheRead / inputTok : null,
131
+ factor: r.totalTok ? total / r.totalTok : null,
132
+ }
133
+ }
134
+ const dates = list.map((p) => String((p && p.at) || '')).filter(Boolean).sort()
135
+ return {
136
+ panelFile,
137
+ matched,
138
+ panelRows: list.length,
139
+ panelLatest: dates.length ? dates[dates.length - 1] : null,
140
+ rowsScanned: rows.length,
141
+ error,
142
+ }
143
+ }
@@ -0,0 +1,174 @@
1
+ import { existsSync, readFileSync } from 'node:fs'
2
+ import { execFileSync } from 'node:child_process'
3
+ import { join } from 'node:path'
4
+
5
+ /**
6
+ * 存量棘轮台账(3.3 B,2026-10-30)
7
+ *
8
+ * ## 为什么需要
9
+ *
10
+ * 棘轮(`smells.mjs` 的 BUDGET / DUP_BUDGET)只能**防涨**,不能**催还**。
11
+ * 实测:存量长期停在 8 / 41,闸门天天绿,债务一分没还。
12
+ * 「顶格」其实是**最严**的状态(没有余量),所以问题不在阈值松,而在**没有还款义务**。
13
+ *
14
+ * 本模块把「降」从口号变成可校验的事实:台账里每个版本记一次实际值,发版时必须
15
+ * 严格小于上一版本。想发版,就得先还一条债。
16
+ *
17
+ * ## 四条规则
18
+ *
19
+ * ① 实测 ≤ 本版记账值 —— 防反弹(台账写完又被改坏)
20
+ * ② 本版总和 < 上一版总和 —— 每版至少还 1 条
21
+ * ③ 首版免 ② —— 总得有个起点
22
+ * ④ 自上次记账起 ≥10 次提交仍未降 —— 还款期限(2026-10-30 人类要求:
23
+ * 「每 N 次提交必须降 1」。按版本记账的问题是:版本可以很久不发,
24
+ * 于是 8/8 能一直挂着不动。改成按提交数催,才管得住「不发版就不还债」)
25
+ *
26
+ * ## 为什么不塞进 smells.mjs
27
+ *
28
+ * 那个文件 380 行,上限 400。台账逻辑加进去会把闸门自己顶成一条新的结构异味。
29
+ * 判据:**闸门不能自己触发自己的告警**。
30
+ */
31
+
32
+ /** 还款期限:自上次记账 commit 起,多少提交内必须还 1 条 */
33
+ export const COMMITS_PER_PAYBACK = 10
34
+
35
+ /**
36
+ * 自某 commit 起的提交数。取不到就返回 null(浅克隆 / 非 git 仓库 / 无该 sha)。
37
+ * 返回 null 时规则④跳过——**缺数据允许粗判,但必须在输出里写明**,不能假装查过。
38
+ */
39
+ function commitsSince(repo, sha) {
40
+ if (!sha) return null
41
+ try {
42
+ const out = execFileSync('git', ['rev-list', '--count', `${sha}..HEAD`], {
43
+ cwd: repo,
44
+ encoding: 'utf8',
45
+ stdio: ['ignore', 'pipe', 'ignore'],
46
+ })
47
+ const n = Number(out.trim())
48
+ return Number.isFinite(n) ? n : null
49
+ } catch {
50
+ return null
51
+ }
52
+ }
53
+
54
+ /**
55
+ * 校验台账。
56
+ *
57
+ * @param {object} ledger 台账 JSON(`history` 数组,每项 {version, smells, duplicates})
58
+ * @param {string} version 当前版本号(取 package.json)
59
+ * @param {{smells: number, duplicates: number}} actual 本次实测值
60
+ * @returns {{findings: Array<{rule: string, detail: string}>, entry: object|null, total: number|null}}
61
+ */
62
+ export function checkRatchet(ledger, version, actual, opts = {}) {
63
+ const findings = []
64
+ const history = Array.isArray(ledger?.history) ? ledger.history : []
65
+ const idx = history.findIndex((h) => h && h.version === version)
66
+
67
+ if (idx < 0) {
68
+ findings.push({
69
+ rule: 'no-ledger-entry',
70
+ detail: `台账里没有 ${version} 的记账行——发版前先补一行(照实测值填)`,
71
+ })
72
+ return { findings, entry: null, total: null }
73
+ }
74
+
75
+ const cur = history[idx]
76
+ const total = (cur.smells || 0) + (cur.duplicates || 0)
77
+
78
+ // ① 防反弹:台账写下的数字,实测不得超过
79
+ if (actual.smells > (cur.smells || 0)) {
80
+ findings.push({
81
+ rule: 'ratchet-rebound',
82
+ detail: `结构异味 ${actual.smells} > 本版记账 ${cur.smells}`,
83
+ })
84
+ }
85
+ if (actual.duplicates > (cur.duplicates || 0)) {
86
+ findings.push({
87
+ rule: 'ratchet-rebound',
88
+ detail: `重复块 ${actual.duplicates} > 本版记账 ${cur.duplicates}`,
89
+ })
90
+ }
91
+
92
+ // ② 还款义务:必须严格小于上一版
93
+ let prevTotal = null
94
+ if (idx > 0) {
95
+ const prev = history[idx - 1]
96
+ prevTotal = (prev.smells || 0) + (prev.duplicates || 0)
97
+ if (!(total < prevTotal)) {
98
+ findings.push({
99
+ rule: 'ratchet-not-lowered',
100
+ detail: `${version} 总和 ${total} 未小于 ${prev.version} 的 ${prevTotal}——每版至少还 1 条债`,
101
+ })
102
+ }
103
+ }
104
+
105
+ // ④ 还款期限:不发新版也要还债。只看「当前版本还没降」这一种情形——
106
+ // 已经降过的(② 满足)不该再被催。
107
+ //
108
+ // 2026-10-31 修:原先写的是 `idx === 0 || total >= prevTotal`,首版(idx===0)恒为 stalled,
109
+ // 于是「实测 29 < 记账 41、已经还了 12 条」照样被催债。注释里那句「已经降过的不该再被催」
110
+ // 代码根本没实现——**判据与它自己声明的语义断线**,正是本轮一直在修的那个病。
111
+ // 改为先看「实测是否低于本版记账值」,降过就不催;没降才按上一版比。
112
+ const n = opts.commitsSinceLast
113
+ if (typeof n === 'number' && n >= COMMITS_PER_PAYBACK) {
114
+ // 「降」看的是**实测**,不是台账。第一版这里写成了 `total < booked`——而 total 就是
115
+ // cur 的和、booked 也是 cur 的和,两边同一个数,恒为 false:判据又一次和自己的语义断线。
116
+ const booked = (cur.smells || 0) + (cur.duplicates || 0)
117
+ const lowered = (actual.smells || 0) + (actual.duplicates || 0) < booked
118
+ const stalled = !lowered && (idx === 0 || total >= prevTotal)
119
+ if (stalled) {
120
+ findings.push({
121
+ rule: 'ratchet-overdue',
122
+ detail: `自上次记账(${cur.commit || '未记 commit'})起已 ${n} 次提交,总和仍为 ${total}——超过 ${COMMITS_PER_PAYBACK} 次必须还 1 条`,
123
+ })
124
+ }
125
+ }
126
+
127
+ return { findings, entry: cur, total, commitsSinceLast: typeof n === 'number' ? n : null }
128
+ }
129
+
130
+ /** 还款期限的展示文案。放在这里而不是 smells.mjs——那文件 396 行,上限 400,加 4 行就自己超限。 */
131
+ export function paybackNote(check) {
132
+ if (check.commitsKnown === false) return '(提交数取不到,只能粗判)'
133
+ const n = check.commitsSinceLast
134
+ return typeof n === 'number' ? `(距上次记账 ${n}/${COMMITS_PER_PAYBACK} 次提交)` : ''
135
+ }
136
+
137
+ /**
138
+ * 读台账并校验,全程容错。
139
+ *
140
+ * 必须容错的理由:`FG_REPO_ROOT` 可以指向夹具仓库(测试就这么造),那里既没有
141
+ * `package.json` 也没有台账。**闸门不能因为台账缺失就崩掉**——崩掉等于这条检查消失,
142
+ * 而且是静默消失(子进程空输出,上层只看到"断言失败")。
143
+ *
144
+ * @param {string} repo 仓库根
145
+ * @param {{smells: number, duplicates: number}} actual
146
+ * @returns {{findings: Array, entry: object|null, total: number|null, version?: string, skipped?: string}}
147
+ */
148
+ export function loadRatchet(repo, actual) {
149
+ const pkgPath = join(repo, 'package.json')
150
+ const ledgerPath = join(repo, 'packages/core/docs/RATCHET.json')
151
+ if (!existsSync(pkgPath)) return { findings: [], entry: null, total: null, skipped: '无 package.json(夹具仓库)' }
152
+ if (!existsSync(ledgerPath)) {
153
+ return { findings: [{ rule: 'no-ledger', detail: '台账 RATCHET.json 缺失' }], entry: null, total: null }
154
+ }
155
+ try {
156
+ const version = JSON.parse(readFileSync(pkgPath, 'utf8')).version
157
+ const ledger = JSON.parse(readFileSync(ledgerPath, 'utf8'))
158
+ const history = Array.isArray(ledger.history) ? ledger.history : []
159
+ const last = history.length ? history[history.length - 1] : null
160
+ const n = commitsSince(repo, last && last.commit)
161
+ return {
162
+ ...checkRatchet(ledger, version, actual, { commitsSinceLast: n }),
163
+ version,
164
+ // 取不到提交数时明说「只能粗判」——假装精确比承认不确定更糟
165
+ commitsKnown: n !== null,
166
+ }
167
+ } catch (error) {
168
+ return {
169
+ findings: [{ rule: 'ledger-unreadable', detail: String(error && error.message) }],
170
+ entry: null,
171
+ total: null,
172
+ }
173
+ }
174
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * 可达闭包(tools/lib/reach.mjs,2026-11-02)。
3
+ *
4
+ * 为什么抽出来:同一段 BFS 在 `health-core.mjs` 与 `import-graph.mjs` 各有一份,
5
+ * 逐字相同 12 行。`smells` 的重复块棘轮正是盯这个——两份实现必然分叉,
6
+ * 本仓已经栽过一次(`stripLiterals` 各写一份,其中一份漏了正则字面量)。
7
+ *
8
+ * 语义只有一句话:从若干**种子**出发,沿依赖边反向(`depsOf` 给出的方向)走,
9
+ * 只收集落在 `srcSet` 里的文件。种子自己不算——种子是测试文件,我们问的是"它够到哪些源码"。
10
+ *
11
+ * @param {Set<string>} srcSet 允许被收集的集合(源码文件)
12
+ * @param {string[]} seeds 起点(测试文件或其它入口)
13
+ * @param {(f: string) => string[]} depsOf 依赖展开
14
+ * @returns {Set<string>}
15
+ */
16
+ export function reachClosure(srcSet, seeds, depsOf) {
17
+ const reached = new Set()
18
+ const queue = []
19
+ const push = (f) => {
20
+ if (srcSet.has(f) && !reached.has(f)) {
21
+ reached.add(f)
22
+ queue.push(f)
23
+ }
24
+ }
25
+ for (const s of seeds) for (const d of depsOf(s)) push(d)
26
+ while (queue.length) for (const d of depsOf(queue.pop())) push(d)
27
+ return reached
28
+ }