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,56 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 模块体检(2026-10-25)
4
+ * 输出:每个模块的行数/导出符号/TODO/空 catch/console 调用;测试覆盖线索。
5
+ * 只读,不改代码。
6
+ */
7
+ import { readdirSync, readFileSync, statSync } from 'node:fs'
8
+ import { dirname, join, relative } from 'node:path'
9
+ import { fileURLToPath } from 'node:url'
10
+
11
+ const HERE = dirname(fileURLToPath(import.meta.url))
12
+ const CORE = join(HERE, '..')
13
+ const ROOTS = ['src/core', 'src/adapters/dsh', 'src/dsh', 'hooks', 'tools', 'tests']
14
+
15
+ function walk(dir, out = []) {
16
+ let entries = []
17
+ try {
18
+ entries = readdirSync(dir)
19
+ } catch {
20
+ return out
21
+ }
22
+ for (const e of entries) {
23
+ const p = join(dir, e)
24
+ const st = statSync(p)
25
+ if (st.isDirectory()) walk(p, out)
26
+ else if (/\.(mjs|js)$/.test(e)) out.push(p)
27
+ }
28
+ return out
29
+ }
30
+
31
+ const files = ROOTS.flatMap((r) => walk(join(CORE, r)))
32
+ const rows = []
33
+ for (const f of files) {
34
+ const rel = relative(CORE, f).replace(/\\/g, '/')
35
+ const src = readFileSync(f, 'utf8')
36
+ const lines = src.split('\n').length
37
+ const exports = [...src.matchAll(/export\s+(?:async\s+)?(?:function|const|let|class)\s+([A-Za-z_$][\w$]*)/g)].map((m) => m[1])
38
+ const todos = (src.match(/TODO|FIXME|XXX|HACK/g) || []).length
39
+ const emptyCatch = (src.match(/catch\s*(?:\([^)]*\))?\s*\{\s*(?:\/\*[^*]*\*\/)?\s*\}/g) || []).length
40
+ const consoleCalls = (src.match(/console\.(log|warn|error|info)\(/g) || []).length
41
+ rows.push({ rel, lines, exports: exports.length, todos, emptyCatch, consoleCalls })
42
+ }
43
+
44
+ rows.sort((a, b) => b.lines - a.lines)
45
+ console.log('模块'.padEnd(46) + '行'.padStart(6) + '导出'.padStart(5) + 'TODO'.padStart(6) + '空catch'.padStart(8) + 'console'.padStart(8))
46
+ for (const r of rows) {
47
+ console.log(
48
+ r.rel.padEnd(42) +
49
+ String(r.lines).padStart(6) +
50
+ String(r.exports).padStart(5) +
51
+ String(r.todos).padStart(6) +
52
+ String(r.emptyCatch).padStart(8) +
53
+ String(r.consoleCalls).padStart(8),
54
+ )
55
+ }
56
+ console.log(`\n合计 ${rows.length} 个文件,${rows.reduce((a, r) => a + r.lines, 0)} 行`)
@@ -0,0 +1,316 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 抽样变异测试(tools/mutate.mjs,2026-10-27)——内置化第四件,零依赖。
4
+ *
5
+ * 为什么自己写:
6
+ * `quality:mutate` 走 `npx --yes --package @stryker-mutator/...`,是"零依赖"剩下的最后一环。
7
+ * 但直接自研完整变异引擎是不划算的:历史上手写版 9 个变异体跑了 5 分钟,Stryker 单文件
8
+ * 6 秒跑 51 个变异体,**手写版完败**。败因不是变异算法,是**测试选择**——手写版每个
9
+ * 变异体都跑全量测试,Stryker 用覆盖率只跑相关的。
10
+ *
11
+ * 所以本工具的设计只有一条核心:**用 import 图选测试**。
12
+ * `lib/import-graph.mjs` 已经能算出"哪些测试文件触达某个 src 模块"(health.mjs 也在用),
13
+ * 变异一个模块时只跑那几个文件,而不是全量 498 条。
14
+ *
15
+ * 与 Stryker 的差距(**必须看清,别当等价物**):
16
+ * ① 变异算子只有 6 类(见 OPERATORS)。**不做**语句删除、返回值替换、
17
+ * 数字/字符串字面量替换、数组/对象字面量替换——那些需要 AST。
18
+ * ② 测试选择粒度是**文件**,不是语句级覆盖率。一个模块若被慢文件触达(如
19
+ * `acceptance.test.mjs` 单文件 29s),本工具会明显变慢,故设 `--max` 与慢文件告警。
20
+ * ③ 结果可复现(同输入同变异体同顺序),但不追求与 Stryker 分数可比。
21
+ * ④ **存活里混着等价变异体**(改了行为不变)。工具不区分,得人工判读。
22
+ * 结论:**它是"有没有断言"的抽样探针,不是"变异覆盖率"的完整度量。**
23
+ * 要完整度量仍用 `npm run quality:mutate`(Stryker,需联网拉包)。
24
+ *
25
+ * 分数可信度的两道闸(都是被假数字逼出来的):
26
+ * · 变异**前**跑两次基线:只要一次红就拒绝变异(偶发失败会被算成"杀死")。
27
+ * · 变异**后**再跑一次基线:红了就把结果标 `不可信`,不把假分数报出去。
28
+ * 实测见过首次跑 `toolName` 报 2/2 全杀、复跑 0/2 全存活——前一次的"杀死"来自
29
+ * 某次测试的残留状态偶发失败。**没有事后复验,这种假数字会直接进报告。**
30
+ *
31
+ * 安全设计(重点):
32
+ * **真实源码永不被改动。** 先把 `packages/` 复制到临时目录,所有变异在副本里做,
33
+ * 跑完删副本。首版考虑过"原地变异 + finally 还原",被否——进程被强杀就留下脏源码,
34
+ * 而这个仓的源码是安全闸门本体,脏了比跑不完严重得多。
35
+ *
36
+ * 用法:
37
+ * node packages/core/tools/mutate.mjs dsh/toolName.mjs # 变异一个模块
38
+ * node packages/core/tools/mutate.mjs core/approval.mjs --list # 只列变异体,不跑
39
+ * node packages/core/tools/mutate.mjs dsh/postProgress.mjs --max 30
40
+ * node packages/core/tools/mutate.mjs dsh/postProgress.mjs --json
41
+ *
42
+ * 退出码:默认恒 0(只报不改);`--strict` 时存活率超 `--max-survive`(默认 40%)才 exit 1。
43
+ */
44
+
45
+ import { spawnSync } from 'node:child_process'
46
+ import { readFileSync, writeFileSync, cpSync, rmSync, mkdtempSync } from 'node:fs'
47
+ import { join, dirname, resolve, basename } from 'node:path'
48
+ import { tmpdir } from 'node:os'
49
+ import { fileURLToPath } from 'node:url'
50
+ import { stripLiterals } from './lib/source-text.mjs'
51
+ import { buildImportGraph } from './lib/import-graph.mjs'
52
+
53
+ const HERE = dirname(fileURLToPath(import.meta.url))
54
+ // 仓库根可覆盖:端到端测试要跑**受控夹具**,不能跑在真实仓库的测试上——
55
+ // 真实测试有偶发失败,会让"变异得分"时高时低,测试跟着抖。
56
+ // 与 lint/smells 同一思路:**测试必须能把被测对象指到别处**。
57
+ const REPO = process.env.FG_REPO_ROOT ? resolve(process.env.FG_REPO_ROOT) : resolve(HERE, '../../..')
58
+
59
+ const argv = process.argv.slice(2)
60
+ const AS_JSON = argv.includes('--json')
61
+ const LIST_ONLY = argv.includes('--list')
62
+ const STRICT = argv.includes('--strict')
63
+ const numArg = (flag, dflt) => {
64
+ const i = argv.indexOf(flag)
65
+ return i >= 0 && argv[i + 1] ? Number(argv[i + 1]) : dflt
66
+ }
67
+ const MAX = numArg('--max', Infinity)
68
+ const MAX_SURVIVE = numArg('--max-survive', 40)
69
+ const PER_MUTANT_TIMEOUT = numArg('--timeout', 60000)
70
+
71
+ /**
72
+ * 变异算子。每个算子:正则 + 替换规则。
73
+ *
74
+ * 全部作用在 `stripLiterals` 之后的文本上——否则 `'== 分布 =='` 这种字符串里的运算符
75
+ * 会被当成代码变异,跑出来的"存活"全是假的。去字面量保留长度与换行,
76
+ * 所以 `plain` 里的下标可以直接映射回原文件(下面有长度断言兜底)。
77
+ */
78
+ const OPERATORS = [
79
+ { id: 'comparison', re: /(?<![<>=!])(<=|>=|<|>)(?![=<>])/g, flip: { '<': '<=', '<=': '<', '>': '>=', '>=': '>' } },
80
+ { id: 'equality', re: /(?<![=!<>])(===|!==)(?!=)/g, flip: { '===': '!==', '!==': '===' } },
81
+ { id: 'boolean', re: /(?<![\w$.])(&&|\|\|)(?![\w$])/g, flip: { '&&': '||', '||': '&&' } },
82
+ { id: 'literal-bool', re: /(?<![\w$.])(true|false)(?![\w$])/g, flip: { true: 'false', false: 'true' } },
83
+ { id: 'nullish', re: /(?<![\w$.])\?\?(?![\w$])/g, flip: { '??': '||' } },
84
+ // 去掉一个 `!`:`if (!reason)` → `if (reason)`。闸门类代码里这条最能暴露"没人断言"。
85
+ // 捕获组不能省:`m[1]` 取的是 token,没有捕获组时是 undefined,整条算子会**静默失效**
86
+ // (这个 bug 是 `mutate.test.mjs` 抓出来的——自己写的算子也会犯"看起来跑了"的错)。
87
+ { id: 'negation', re: /(?<![!=<>])(!)(?!=)/g, flip: { '!': '' } },
88
+ ]
89
+
90
+ /** 生成变异体:{ op, index, token, replacement, line } */
91
+ export function generateMutants(src) {
92
+ const plain = stripLiterals(src)
93
+ if (plain.length !== src.length) {
94
+ throw new Error(`stripLiterals 改变了长度(${src.length} → ${plain.length}),下标无法映射,拒绝变异`)
95
+ }
96
+ const lineStarts = [0]
97
+ for (let i = 0; i < src.length; i += 1) if (src[i] === '\n') lineStarts.push(i + 1)
98
+ const lineOf = (idx) => {
99
+ let lo = 0
100
+ let hi = lineStarts.length - 1
101
+ while (lo < hi) {
102
+ const mid = (lo + hi + 1) >> 1
103
+ if (lineStarts[mid] <= idx) lo = mid
104
+ else hi = mid - 1
105
+ }
106
+ return lo + 1
107
+ }
108
+
109
+ const out = []
110
+ for (const op of OPERATORS) {
111
+ for (const m of plain.matchAll(op.re)) {
112
+ const token = m[1]
113
+ const replacement = op.flip[token]
114
+ if (replacement === undefined) continue
115
+ out.push({ op: op.id, index: m.index, token, replacement, line: lineOf(m.index) })
116
+ }
117
+ }
118
+ return out.sort((a, b) => a.index - b.index)
119
+ }
120
+
121
+ /** 把第 i 个变异体应用到源码上,返回新源码。 */
122
+ export function applyMutant(src, mutant) {
123
+ return src.slice(0, mutant.index) + mutant.replacement + src.slice(mutant.index + mutant.token.length)
124
+ }
125
+
126
+ function runTests(cwd, testFiles) {
127
+ const env = {
128
+ ...process.env,
129
+ // 隔离:子进程不许继承宿主的工作区根,否则变异跑出来的审计会写脏真实 AUDIT.log
130
+ // (`npm run eval` 上踩过:单跑一次写脏 62 行)。
131
+ ZCODE_PROJECT_DIR: '',
132
+ CLAUDE_PROJECT_DIR: '',
133
+ FG_PROJECT_DIR: '',
134
+ FG_SHELL: '',
135
+ FG_AUDIT_FILE: join(cwd, '.focus-guard', 'mutate-audit.log'),
136
+ }
137
+ // **必须删掉 NODE_TEST_CONTEXT(2026-10-27 实测)。**
138
+ // 这个变量在 `node --test` 里会被设成 `child-v8`,子进程继承后 `node --test` 会**恒 exit 0**,
139
+ // 哪怕测试明确失败。后果:从任何测试里调本工具,所有变异体都被判"存活",得分是假的。
140
+ // 这是端到端用例抓出来的——同一夹具在测试里跑出 2/2 存活、在终端里跑出 1 杀 1 活。
141
+ // 判据:**跑测试的子进程,环境必须和终端一致**,否则测的不是被测对象。
142
+ delete env.NODE_TEST_CONTEXT
143
+
144
+ const r = spawnSync('node', ['--test', ...testFiles], {
145
+ cwd,
146
+ encoding: 'utf8',
147
+ timeout: PER_MUTANT_TIMEOUT,
148
+ env,
149
+ })
150
+ return { ok: r.status === 0, timedOut: r.error?.code === 'ETIMEDOUT', out: `${r.stdout || ''}${r.stderr || ''}` }
151
+ }
152
+
153
+ // ───────────────────────────── 主流程 ─────────────────────────────
154
+ //
155
+ // 整段由 `isMain` 守卫。原因:不这样做的话,测试文件一
156
+ // `import { generateMutants }` 就会执行 CLI 并 `exit(2)`,纯函数根本测不到。
157
+ // `health.mjs` 上踩过同一个坑(当时是把逻辑抽到 lib/ 解决的,这里逻辑本身就少,
158
+ // 加守卫就够)。判据:**凡是要被测试 import 的 CLI,必须有主模块判定。**
159
+ //
160
+ // 拆成 5 个小函数是**被自己的 smells 工具逼的**:首版一个 `main()` 148 行,
161
+ // 直接撞上阈值 80,把结构维从 28 条推到 29 条。棘轮的规矩是只许降不许升,
162
+ // 所以拆代码,不是调上限。
163
+
164
+ /** 解析目标模块,算变异计划。 */
165
+ function planTargets(targets) {
166
+ const g = buildImportGraph(REPO)
167
+ const plans = targets.map((t) => {
168
+ const abs = resolve(g.srcDir, t)
169
+ try {
170
+ readFileSync(abs)
171
+ } catch {
172
+ console.error(`找不到模块:${t}(相对 packages/core/src)`)
173
+ process.exit(2)
174
+ }
175
+ const src = readFileSync(abs, 'utf8')
176
+ const all = generateMutants(src)
177
+ const selected = Number.isFinite(MAX) ? all.slice(0, MAX) : all
178
+ return { abs, name: basename(abs), src, all, mutants: selected, tests: g.reachingTests(abs) }
179
+ })
180
+ return { g, plans }
181
+ }
182
+
183
+ /** `--list`:只报计划,不复制、不跑测试。 */
184
+ function listPlans(plans) {
185
+ for (const p of plans) {
186
+ const byOp = {}
187
+ for (const m of p.all) byOp[m.op] = (byOp[m.op] || 0) + 1
188
+ console.log(`${p.name}:${p.all.length} 个变异体 ${JSON.stringify(byOp)};触达测试 ${p.tests.length} 个`)
189
+ for (const m of p.mutants.slice(0, 20)) {
190
+ const before = p.src.split('\n')[m.line - 1].trim()
191
+ console.log(` L${m.line} [${m.op}] ${m.token} → ${m.replacement || '(删)'} ${before.slice(0, 70)}`)
192
+ }
193
+ if (p.mutants.length > 20) console.log(` …另有 ${p.mutants.length - 20} 个`)
194
+ }
195
+ }
196
+
197
+ /**
198
+ * 跑一个模块:基线校验 → 逐个变异 → 事后复验。
199
+ * 返回 { ...统计, survivors?, skipped?, unreliable? }。
200
+ */
201
+ function runModule(work, g, p) {
202
+ const targetInCopy = join(work, 'packages/core/src', p.abs.slice(g.srcDir.length + 1))
203
+ const testsInCopy = p.tests.map((t) => join(work, t.slice(REPO.length + 1)))
204
+ const base = { name: p.name, total: p.mutants.length, generated: p.all.length, tests: p.tests.length }
205
+
206
+ if (!p.mutants.length) return { ...base, skipped: '该模块没有可变异算子(纯常量表或纯声明)' }
207
+ if (!p.tests.length) {
208
+ return { ...base, skipped: '没有任何测试文件触达该模块,变异体全存活,测了也没意义' }
209
+ }
210
+
211
+ // 基线:不变异先跑一次。**基线本身是红的就不能变异**——否则"杀死"是假的。
212
+ //
213
+ // 重试一次是因为实测发现本仓有**状态相关的偶发失败**(`preGuard.test.mjs`
214
+ // 的"异常一律不阻塞"偶发红,连跑 6 次又全绿)。重试只用来**判定基线是否可信**,
215
+ // 不用来"重试到绿"——两次里只要有一次红就判基线不可信并跳过。
216
+ const b1 = runTests(work, testsInCopy)
217
+ const b2 = b1.ok ? b1 : runTests(work, testsInCopy)
218
+ if (!b1.ok || !b2.ok) {
219
+ const flaky = b1.ok !== b2.ok
220
+ return {
221
+ ...base,
222
+ skipped: `${flaky ? '基线不稳定(一次红一次绿)' : '基线测试未通过'},拒绝变异。偶发失败会被算成"杀死",变异得分不可信:${b2.out.slice(-300)}`,
223
+ }
224
+ }
225
+
226
+ let killed = 0
227
+ let timedOut = 0
228
+ const survivors = []
229
+ for (const m of p.mutants) {
230
+ writeFileSync(targetInCopy, applyMutant(p.src, m))
231
+ const r = runTests(work, testsInCopy)
232
+ writeFileSync(targetInCopy, p.src) // 立刻还原,下一个变异体基于原码
233
+ if (r.timedOut) {
234
+ timedOut += 1
235
+ killed += 1 // 超时按杀死算(测试没能通过)
236
+ } else if (r.ok) {
237
+ survivors.push({ line: m.line, op: m.op, token: m.token, replacement: m.replacement })
238
+ } else {
239
+ killed += 1
240
+ }
241
+ }
242
+ const out = { ...base, killed, timedOut, survivors, score: Math.round((killed / p.mutants.length) * 1000) / 10 }
243
+
244
+ // 事后校验(2026-10-27 补):循环跑完、源码已还原,再跑一次基线。
245
+ //
246
+ // 为什么必须有这一步:实测见过"杀死数虚高"——循环中某次测试因**残留状态**偶发失败,
247
+ // 被算成"这个变异体被杀了",而实际上它压根没被杀。首次跑 toolName 得到 2/2 全杀,
248
+ // 复跑变成 0/2 全存活,就是这种情况。基线只在循环前检查**抓不住循环中的污染**。
249
+ writeFileSync(targetInCopy, p.src)
250
+ if (!runTests(work, testsInCopy).ok) {
251
+ out.unreliable = '变异循环结束后基线变红(测试有状态泄漏或偶发失败),杀死数可能虚高,本次结果不可信'
252
+ }
253
+ return out
254
+ }
255
+
256
+ /** 输出与退出码。 */
257
+ function report(results) {
258
+ const alive = results.reduce((s, r) => s + (r.survivors ? r.survivors.length : 0), 0)
259
+ const ran = results.reduce((s, r) => s + (r.killed || 0) + (r.survivors ? r.survivors.length : 0), 0)
260
+
261
+ if (AS_JSON) {
262
+ console.log(JSON.stringify({ results, alive, ran }, null, 2))
263
+ } else {
264
+ for (const r of results) {
265
+ console.log(`\n${r.name}:生成 ${r.generated} 个变异体,本次跑 ${r.total} 个,触达测试 ${r.tests} 个`)
266
+ if (r.skipped) {
267
+ console.log(` 跳过:${r.skipped}`)
268
+ continue
269
+ }
270
+ console.log(` 杀死 ${r.killed}(其中超时 ${r.timedOut})/ 存活 ${r.survivors.length} 变异得分 ${r.score}%`)
271
+ if (r.unreliable) console.log(` ⚠ ${r.unreliable}`)
272
+ for (const s of r.survivors) console.log(` 存活 L${s.line} [${s.op}] ${s.token} → ${s.replacement || '(删)'}`)
273
+ }
274
+ console.log('\n读法(重要):存活分两种——「真缺口」(该分支没断言)与「等价变异体」(改了行为不变)。')
275
+ console.log('本工具不区分这两者,得人工判读。所以得分**不可与 Stryker 的覆盖率分数直接比**。')
276
+ console.log('算子只有 6 类(无语句删除/返回值替换/字面量替换),测试选择粒度是文件不是覆盖率。')
277
+ }
278
+ return STRICT && ran > 0 && (alive / ran) * 100 > MAX_SURVIVE ? 1 : 0
279
+ }
280
+
281
+ function main() {
282
+ const targets = argv.filter(
283
+ (a, i) => !a.startsWith('--') && !/^\d+$/.test(a) && !['--max', '--max-survive', '--timeout'].includes(argv[i - 1]),
284
+ )
285
+ if (!targets.length) {
286
+ console.error('用法:node packages/core/tools/mutate.mjs <src 相对路径...> [--list] [--max n] [--json] [--strict]')
287
+ console.error(' 例:node packages/core/tools/mutate.mjs dsh/toolName.mjs')
288
+ process.exit(2)
289
+ }
290
+
291
+ const { g, plans } = planTargets(targets)
292
+ if (LIST_ONLY) {
293
+ listPlans(plans)
294
+ process.exit(0)
295
+ }
296
+
297
+ // 复制到临时目录:真实源码永不被改
298
+ const work = mkdtempSync(join(tmpdir(), 'fg-mutate-'))
299
+ cpSync(join(REPO, 'packages'), join(work, 'packages'), { recursive: true })
300
+ try {
301
+ cpSync(join(REPO, 'package.json'), join(work, 'package.json'))
302
+ } catch {
303
+ /* package.json 不是必需 */
304
+ }
305
+
306
+ const results = []
307
+ try {
308
+ for (const p of plans) results.push(runModule(work, g, p))
309
+ } finally {
310
+ rmSync(work, { recursive: true, force: true })
311
+ }
312
+ process.exit(report(results))
313
+ }
314
+
315
+ const isMain = process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)
316
+ if (isMain) main()
@@ -0,0 +1,122 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 前缀构成审计(2026-10-22)
4
+ *
5
+ * 目的:回答"每请求固定前缀花在哪、能砍哪"。缓存命中率已 ~98%,成本 ≈ 请求数 × 前缀,
6
+ * 所以真正的杠杆是**前缀里那些每轮都付的东西**:工具 schema / 技能目录 / 系统提示 / 注入块。
7
+ *
8
+ * 口径:字符数 → est4(chars/4),**不是账单**;真实 token 只在宿主面板。
9
+ *
10
+ * 用法:node packages/core/tools/prefix-audit.mjs [--sid <前缀>] [--json]
11
+ */
12
+
13
+ import { basename, dirname } from 'node:path'
14
+ import { decodeSession, walkSessionFiles } from './lib/sessionDump.mjs'
15
+
16
+ const SESSIONS = process.env.FG_SESSIONS_DIR || 'E:/DSH/.dsh/sessions'
17
+ const argv = process.argv.slice(2)
18
+ const SID = argv.includes('--sid') ? argv[argv.indexOf('--sid') + 1] : null
19
+ const AS_JSON = argv.includes('--json')
20
+
21
+ const files = walkSessionFiles(SESSIONS).filter((x) => x.size < 3 * 1024 * 1024)
22
+ // 选会话:默认取"最近且真的带 tools + 有若干步"的那个(子代理/空会话会干扰)。
23
+ let pick = null
24
+ let lines = null
25
+ for (const cand of (SID ? files.filter((x) => x.f.includes(SID)) : files.slice(0, 20))) {
26
+ let ls
27
+ try {
28
+ ls = decodeSession(cand.f)
29
+ } catch {
30
+ continue
31
+ }
32
+ const hd = ls.find((l) => l.type === 'request/header')
33
+ const hh = hd && hd.data ? hd.data.header || hd.data : null
34
+ const nTools = (hh && hh.tools && hh.tools.length) || 0
35
+ const nSteps = ls.filter((l) => l.type === 'step/start').length
36
+ if (nTools > 0 && (SID || nSteps >= 5)) {
37
+ pick = cand
38
+ lines = ls
39
+ break
40
+ }
41
+ }
42
+ if (!pick) {
43
+ console.log('找不到带工具表的会话', SID || '(最近 20 个)')
44
+ process.exit(0)
45
+ }
46
+
47
+ const header = lines.find((l) => l.type === 'request/header')
48
+ const h = header && header.data ? header.data.header || header.data : null
49
+ const tools = (h && h.tools) || []
50
+
51
+ let toolsChars = 0
52
+ const perTool = []
53
+ for (const t of tools) {
54
+ const n = JSON.stringify(t).length
55
+ toolsChars += n
56
+ perTool.push({ name: t.name, chars: n })
57
+ }
58
+ perTool.sort((a, b) => b.chars - a.chars)
59
+
60
+ // 系统/开发者/用户消息里的固定内容
61
+ const sysMsgs = lines.filter((l) => l.type === 'system/message')
62
+ const devMsgs = lines.filter((l) => l.type === 'developer/message')
63
+ const firstUser = lines.find((l) => l.type === 'user/message')
64
+ const textOf = (l) => JSON.stringify((l.data && l.data.content) || l.data || '').length
65
+
66
+ const sysChars = sysMsgs.reduce((a, l) => a + textOf(l), 0)
67
+ const devChars = devMsgs.reduce((a, l) => a + textOf(l), 0)
68
+ const firstUserText = firstUser ? JSON.stringify(firstUser.data.content || '') : ''
69
+
70
+ // 技能目录(<available_skills> 块)在首个 user/message 的 system-reminder 里
71
+ function blockLen(src, start, end) {
72
+ const i = src.indexOf(start)
73
+ if (i < 0) return 0
74
+ const j = src.indexOf(end, i)
75
+ return j > i ? j - i + end.length : 0
76
+ }
77
+ const skillsChars = blockLen(firstUserText, '<available_skills>', '</available_skills>')
78
+ // 锚点用两版注入块的公共前缀 `<focus-guard `:2026-10-24 前的完整版开头是
79
+ // `focus-guard AI履职执法模型v3.0`,之后的精简版是 `focus-guard v3.0`。旧锚点只认前者,
80
+ // 精简版上线后 indexOf 恒 -1 → 本行恒报 0(读起来像"没成本")。历史会话仍要能测,故取公共前缀。
81
+ const fgRulesChars = blockLen(firstUserText, '<focus-guard ', 'docs/RULES.md')
82
+ const fgWsChars = blockLen(firstUserText, '[FG-WORKSPACE]', '决策:') || 0
83
+ const costChars = blockLen(firstUserText, '【成本】', '【成本】') || 20
84
+
85
+ const steps = lines.filter((l) => l.type === 'step/start').length
86
+ const totalFixed = toolsChars + sysChars + devChars + skillsChars
87
+
88
+ const rows = [
89
+ { item: '工具 schema(' + tools.length + ' 个)', chars: toolsChars },
90
+ { item: '系统提示 system/message(' + sysMsgs.length + ' 条)', chars: sysChars },
91
+ { item: '开发者消息 developer/message(' + devMsgs.length + ' 条)', chars: devChars },
92
+ { item: '技能目录 <available_skills>', chars: skillsChars },
93
+ { item: 'FG 执法规则注入', chars: fgRulesChars },
94
+ { item: 'FG 卷宗注入', chars: fgWsChars },
95
+ { item: '成本行', chars: costChars },
96
+ ]
97
+ rows.sort((a, b) => b.chars - a.chars)
98
+
99
+ const report = {
100
+ session: basename(dirname(pick.f)).replace('session-', '').slice(0, 8),
101
+ steps,
102
+ tools: tools.length,
103
+ totalFixedChars: totalFixed,
104
+ totalFixedTok: Math.round(totalFixed / 4),
105
+ rows: rows.map((r) => ({ ...r, tok: Math.round(r.chars / 4), share: +(r.chars / totalFixed * 100).toFixed(1) })),
106
+ topTools: perTool.slice(0, 10).map((t) => ({ ...t, tok: Math.round(t.chars / 4) })),
107
+ }
108
+
109
+ if (AS_JSON) {
110
+ console.log(JSON.stringify(report, null, 2))
111
+ process.exit(0)
112
+ }
113
+
114
+ console.log(`会话 ${report.session} · ${report.steps} 步 · 工具 ${report.tools} 个`)
115
+ console.log(`固定前缀合计 ${report.totalFixedChars} 字符 ≈ ${report.totalFixedTok} tok(est4)\n`)
116
+ console.log('项目'.padEnd(34) + '字符'.padStart(10) + 'tok'.padStart(9) + '占比'.padStart(8))
117
+ for (const r of report.rows) {
118
+ console.log(`${r.item.padEnd(30)}${String(r.chars).padStart(10)}${String(r.tok).padStart(9)}${(r.share + '%').padStart(8)}`)
119
+ }
120
+ console.log('\n最大的 10 个工具:')
121
+ for (const t of report.topTools) console.log(` ${String(t.tok).padStart(6)} tok ${t.name}`)
122
+ console.log(`\n每步成本下限 ≈ 前缀 ${report.totalFixedTok} tok × 缓存价 $0.003/1M = $${(report.totalFixedTok * 0.003 / 1e6).toFixed(8)}`)