dsh-git-push 2.20.18 → 3.0.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 (198) hide show
  1. package/README.md +3 -2
  2. package/cli-tool.mjs +2 -4
  3. package/cli.mjs +36 -2
  4. package/lib/app/apply.js +9 -9
  5. package/lib/app/command-registry.js +44 -20
  6. package/lib/app/handlers/meta.js +7 -142
  7. package/lib/app/handlers/npm.js +18 -1
  8. package/lib/app/handlers/preprocess.js +107 -0
  9. package/lib/app/handlers/repo-actions.js +2 -2
  10. package/lib/app/http-handlers.js +25 -12
  11. package/lib/app/index.js +2 -1
  12. package/lib/app/inject-text.js +3 -2
  13. package/lib/app/preprocess-client.js +136 -0
  14. package/lib/app/repo-ownership.js +1 -1
  15. package/lib/app/schema.js +3 -3
  16. package/lib/app/severity.js +14 -0
  17. package/lib/app/slash-commands.js +5 -164
  18. package/lib/app/tool-call.js +75 -140
  19. package/lib/app/tools.js +13 -6
  20. package/lib/cli/commands-preprocess.mjs +74 -0
  21. package/lib/cli/commands-tool.mjs +3 -2
  22. package/lib/cli/commands-vcs.mjs +4 -4
  23. package/lib/cli/shared.mjs +42 -13
  24. package/lib/client-parts/git/controller.js +2 -2
  25. package/lib/client.js +2 -2
  26. package/lib/commit-push/pre-commit-engine.js +57 -10
  27. package/lib/commit-push.js +125 -36
  28. package/lib/{exempt/index.js → git/exempt-markers.js} +8 -1
  29. package/lib/git/ignore.js +1 -1
  30. package/lib/git/repos.js +2 -2
  31. package/lib/git/sensitive.js +1 -1
  32. package/lib/npm/publish.js +20 -5
  33. package/lib/plugin/auto-push.js +2 -2
  34. package/lib/preprocess/providers.js +191 -0
  35. package/lib/self/index.js +1 -1
  36. package/lib/skip-dirs.js +14 -55
  37. package/package.json +29 -37
  38. package/scripts/build-client.mjs +2 -0
  39. package/scripts/check.mjs +4 -2
  40. package/scripts/local-registry.mjs +2 -1
  41. package/skills/dev/dsh-git-push.md +5 -0
  42. package/cli-audit.mjs +0 -141
  43. package/lib/app/audit-api.js +0 -173
  44. package/lib/app/host-doc-checks.js +0 -25
  45. package/lib/app/scope-check.js +0 -69
  46. package/lib/ast/brace.js +0 -120
  47. package/lib/ast/callgraph.js +0 -135
  48. package/lib/ast/code-lines.js +0 -175
  49. package/lib/ast/consts.js +0 -12
  50. package/lib/ast/control-flow.js +0 -470
  51. package/lib/ast/credential.js +0 -315
  52. package/lib/ast/dataflow.js +0 -391
  53. package/lib/ast/dup-code.js +0 -165
  54. package/lib/ast/fs-hotspots.js +0 -154
  55. package/lib/ast/index.js +0 -38
  56. package/lib/ast/io-risk-const.js +0 -95
  57. package/lib/ast/io-risk-fn.js +0 -208
  58. package/lib/ast/io-risk-loop.js +0 -308
  59. package/lib/ast/io-risk.js +0 -314
  60. package/lib/ast/lang.js +0 -156
  61. package/lib/ast/line-count.js +0 -52
  62. package/lib/ast/magic-number.js +0 -272
  63. package/lib/ast/naming.js +0 -292
  64. package/lib/ast/perf.js +0 -488
  65. package/lib/ast/scope-collisions.js +0 -228
  66. package/lib/ast/scope.js +0 -241
  67. package/lib/ast/shell.js +0 -131
  68. package/lib/ast/size.js +0 -448
  69. package/lib/ast/symbol-index.js +0 -399
  70. package/lib/ast/tokenizer.js +0 -421
  71. package/lib/ast/treesitter.js +0 -413
  72. package/lib/audit/analysis-coverage.js +0 -98
  73. package/lib/audit/audit-file.js +0 -205
  74. package/lib/audit/auditignore-rules.js +0 -148
  75. package/lib/audit/checks.js +0 -17
  76. package/lib/audit/client-entry.js +0 -93
  77. package/lib/audit/collector.js +0 -610
  78. package/lib/audit/ext-runner.js +0 -80
  79. package/lib/audit/file-context.js +0 -391
  80. package/lib/audit/finding.js +0 -101
  81. package/lib/audit/gitignore-match.js +0 -113
  82. package/lib/audit/glob.js +0 -63
  83. package/lib/audit/history-report.js +0 -100
  84. package/lib/audit/history.js +0 -126
  85. package/lib/audit/ignore-blind.js +0 -102
  86. package/lib/audit/index.js +0 -33
  87. package/lib/audit/orchestrate.js +0 -672
  88. package/lib/audit/public.js +0 -24
  89. package/lib/audit/repo-level.js +0 -30
  90. package/lib/audit/report-yaml.js +0 -90
  91. package/lib/audit/scope-policy.js +0 -110
  92. package/lib/audit/slot.js +0 -66
  93. package/lib/audit-rules/audit-rules-comment.yml +0 -199
  94. package/lib/audit-rules/audit-rules-cpp.yml +0 -114
  95. package/lib/audit-rules/audit-rules-csharp.yml +0 -82
  96. package/lib/audit-rules/audit-rules-docs.yml +0 -32
  97. package/lib/audit-rules/audit-rules-dsh.yml +0 -177
  98. package/lib/audit-rules/audit-rules-filehealth.yml +0 -42
  99. package/lib/audit-rules/audit-rules-folder.yml +0 -99
  100. package/lib/audit-rules/audit-rules-frontend.yml +0 -335
  101. package/lib/audit-rules/audit-rules-go.yml +0 -103
  102. package/lib/audit-rules/audit-rules-i18n.yml +0 -45
  103. package/lib/audit-rules/audit-rules-java.yml +0 -105
  104. package/lib/audit-rules/audit-rules-nodejs.yml +0 -662
  105. package/lib/audit-rules/audit-rules-npm.yml +0 -187
  106. package/lib/audit-rules/audit-rules-paths.yml +0 -98
  107. package/lib/audit-rules/audit-rules-performance.yml +0 -245
  108. package/lib/audit-rules/audit-rules-php.yml +0 -101
  109. package/lib/audit-rules/audit-rules-private.yml +0 -24
  110. package/lib/audit-rules/audit-rules-python.yml +0 -106
  111. package/lib/audit-rules/audit-rules-robustness.yml +0 -31
  112. package/lib/audit-rules/audit-rules-rust.yml +0 -109
  113. package/lib/audit-rules/audit-rules-structure.yml +0 -158
  114. package/lib/audit-rules/audit-rules-swift.yml +0 -99
  115. package/lib/audit-rules/audit-rules-template.yml +0 -108
  116. package/lib/audit-ui-sdk/contract.js +0 -117
  117. package/lib/audit-ui-sdk/index.js +0 -17
  118. package/lib/checks/button-bind.js +0 -347
  119. package/lib/checks/common.js +0 -170
  120. package/lib/checks/credential-file.js +0 -43
  121. package/lib/checks/dataflow.js +0 -40
  122. package/lib/checks/dispatch.js +0 -117
  123. package/lib/checks/dup-code.js +0 -69
  124. package/lib/checks/dup-const.js +0 -232
  125. package/lib/checks/file-health.js +0 -150
  126. package/lib/checks/filter.js +0 -137
  127. package/lib/checks/folder.js +0 -173
  128. package/lib/checks/fs-scanner.js +0 -57
  129. package/lib/checks/hardcoded-path.js +0 -98
  130. package/lib/checks/index.js +0 -49
  131. package/lib/checks/io.js +0 -66
  132. package/lib/checks/magic-number.js +0 -42
  133. package/lib/checks/npm-json.js +0 -273
  134. package/lib/checks/private.js +0 -64
  135. package/lib/checks/regex.js +0 -298
  136. package/lib/checks/scope-collision.js +0 -68
  137. package/lib/checks/semantic.js +0 -134
  138. package/lib/checks/structural.js +0 -281
  139. package/lib/cli/commands-audit.mjs +0 -142
  140. package/lib/cli/commands-doc.mjs +0 -127
  141. package/lib/client-parts/audit/audit.js +0 -301
  142. package/lib/exempt/tool.js +0 -198
  143. package/lib/git/module-splitter.js +0 -47
  144. package/lib/link-check/index.js +0 -187
  145. package/lib/lint-adapter/detect.js +0 -161
  146. package/lib/lint-adapter/index.js +0 -50
  147. package/lib/lint-adapter/runner.js +0 -133
  148. package/lib/rule/compilers/credential.js +0 -62
  149. package/lib/rule/compilers/dataflow.js +0 -38
  150. package/lib/rule/compilers/file-health.js +0 -75
  151. package/lib/rule/compilers/frontend.js +0 -86
  152. package/lib/rule/compilers/func.js +0 -35
  153. package/lib/rule/compilers/helpers.js +0 -71
  154. package/lib/rule/compilers/index.js +0 -29
  155. package/lib/rule/compilers/link-semantic.js +0 -45
  156. package/lib/rule/compilers/list-kinds.js +0 -12
  157. package/lib/rule/compilers/numeric-kinds.js +0 -73
  158. package/lib/rule/compilers/regex.js +0 -78
  159. package/lib/rule/compilers/structure.js +0 -107
  160. package/lib/rule/compilers.js +0 -17
  161. package/lib/rule/homoglyph.js +0 -45
  162. package/lib/rule/loader.js +0 -274
  163. package/lib/rule/registry.js +0 -122
  164. package/lib/rule/scope.js +0 -67
  165. package/lib/score/docs-score.js +0 -166
  166. package/lib/score/index.js +0 -234
  167. package/scripts/__pycache__/module-splitter.cpython-38.pyc +0 -0
  168. package/scripts/audit-ext/_example-readme-present.mjs +0 -34
  169. package/scripts/audit-ext/dsh-inject-declarations.mjs +0 -209
  170. package/scripts/audit-ext/variable-min-length.mjs +0 -102
  171. package/scripts/audit-gate.mjs +0 -235
  172. package/scripts/audit-runner.mjs +0 -35
  173. package/scripts/audit-runtime-check.mjs +0 -129
  174. package/scripts/browser-page-probe.mjs +0 -271
  175. package/scripts/check-js-scope.mjs +0 -87
  176. package/scripts/clean-date-comments.py +0 -102
  177. package/scripts/cpu-sample.mjs +0 -188
  178. package/scripts/doc-drift.mjs +0 -200
  179. package/scripts/hot-path-probe-cjs.cjs +0 -71
  180. package/scripts/hot-path-probe-fs-shim.mjs +0 -28
  181. package/scripts/hot-path-probe-fsp-shim.mjs +0 -31
  182. package/scripts/hot-path-probe.mjs +0 -153
  183. package/scripts/module-splitter.py +0 -800
  184. package/scripts/picker-repro.mjs +0 -115
  185. package/scripts/platform-scan.mjs +0 -168
  186. package/scripts/probe-recheck.mjs +0 -47
  187. package/scripts/rename-locator.mjs +0 -97
  188. package/scripts/rule-switch.mjs +0 -97
  189. package/scripts/rules-solo-audit.mjs +0 -173
  190. package/scripts/scan-file-io.mjs +0 -717
  191. package/scripts/scan-fs-hotspots.mjs +0 -107
  192. package/scripts/symbol-index.mjs +0 -85
  193. package/scripts/verify-prestep.mjs +0 -100
  194. package/skills/dev/audit-rule-authoring.md +0 -58
  195. package/skills/guide/guide-audit.md +0 -270
  196. /package/lib/{audit → app}/ownership.js +0 -0
  197. /package/lib/app/{schema-audit.js → schema-preprocess.js} +0 -0
  198. /package/lib/{audit-defaults.js → git/defaults.js} +0 -0
package/lib/ast/lang.js DELETED
@@ -1,156 +0,0 @@
1
- /**
2
- * AST 实现层 · 语言路由
3
- *
4
- * 职责:按源码内容(或扩展名)判定语言,并为各语言提供「函数范围收集器」。
5
- * tokenizer 是 JS 语法假设的通用切词器,对多数花括号系语言(Java/Kotlin/Go/Rust/
6
- * Swift/C/C++/PHP)的「函数体边界」识别却各不同——JS 找 `function` 关键字、Python
7
- * 按 def+缩进、Java/Kotlin 按方法签名。本模块统一这层差异:detectLang 给出语言,
8
- * funcRangesFor 返回该语言的函数范围收集函数(暂无实现的返回 null——槽位就绪,
9
- * 后续补语言规则时零架构改动)。
10
- *
11
- * 语言路由(funcRanges 函数):
12
- * js/ts/tsx/jsx → funcRangesAst 的 JS 分支(大括号法,size.js)
13
- * python → pythonFuncRanges(缩进法,size.js)
14
- * java/kotlin → javaKtFuncRanges(方法签名 + 括号配对,本文件)
15
- * go/rust/swift/cpp/php/rb → null 占位(语言专项规则 yml 已建槽位,范围解析待补)
16
- */
17
- import { matchBrace } from './brace.js';
18
- import { tokenize } from './tokenizer.js';
19
-
20
- /** 方法签名 `(` 配对 `)` 的最大 token 跨度(防遍历到文件尾)。 */
21
- const SIG_CLOSE_LOOKAHEAD = 40;
22
- /** 配对 `)` 后找方法体 `{` 的最大 token 跨度(跳过 throws 子句/注解)。 */
23
- const BODY_OPEN_LOOKAHEAD = 13;
24
-
25
- /** 主流的「方法声明前导关键字/上下文排除集」——这些 ident 紧跟在 `X(` 前时不构成方法声明。 */
26
- const NOT_METHOD_PREV = new Set([
27
- 'return', 'if', 'else', 'for', 'while', 'do', 'switch', 'catch', 'case',
28
- 'new', 'throw', 'import', 'package', 'extends', 'implements', 'super', 'this',
29
- 'class', 'interface', 'enum', 'function', 'const', 'let', 'var', 'def',
30
- 'in', 'of', 'not', 'and', 'or', 'is', 'as', 'assert', 'yield', 'await',
31
- ]);
32
-
33
- /**
34
- * Java/Kotlin 函数(方法)范围收集——token 级方法签名识别 + 括号配对。
35
- *
36
- * 为什么不能复用 JS 分支:Java/Kotlin 方法无 `function` 关键字——
37
- * `public void foo(int x) {` / `private fun bar(): Int {`,JS 分支零命中。
38
- * 识别算法(token 级,天然剥离字符串/注释):
39
- * ① 候选:ident 紧跟 `(`(方法名/构造器名),且该 ident 前一非空白 token:
40
- * - 是 `.` → 方法调用(helper.foo()排除
41
- * - 是 NOT_METHOD_PREV 关键字(return/if/new/class…)→ 排除
42
- * - 是函数体/语句边界(`{` `}` `;` `,` `(` `=` `:` `)`)→ 排除
43
- * - 其它(返回类型/修饰符/泛型尾 `>`/数组尾 `]`/`fun` 关键字)→ 候选
44
- * ② 确认:`(` 括号配对到 `)`,其后 12 token 内出现 `{`(方法体)→ 方法声明;
45
- * `)` 后跟 `;`(调用)/`,`/`)` 等 → 非方法体,排除。
46
- * ——「配对后必须跟 `{`」是区分「方法声明」与「方法调用」的强判据:
47
- * 调用结尾是 `;`/`)`,声明结尾是 `{`(或 throws X {)。
48
- * ③ 方法名:候选 ident 即方法名(构造器=类名,合法函数)。
49
- * 覆盖:Java 方法/构造器/静态块前的方法、Kotlin fun(含返回值 `: Type`、
50
- * 默认参数)。不覆盖:Kotlin 表达式体(fun x() = …)——无 `{}`,一般极短。
51
- * 局部 fun(Kotlin 允许嵌套)与 lambda `{` 的开始由 matchBrace 各自配对,
52
- * 内层独立计数(与 JS 内层函数同语义)。
53
- *
54
- * 返回 [{startLine, endLine, len, name}](与 funcRangesAst 输出结构一致)。
55
- * @param {string} text 文件全文
56
- */
57
- /** 方法名前一非 ws/comment token。 */
58
- function prevNonWsToken(tokens, i) {
59
- for (let j = i - 1; j >= 0; j--) {
60
- const tj = tokens[j];
61
- if (tj.type === 'ws' || tj.type === 'comment') continue;
62
- return tj;
63
- }
64
- return null;
65
- }
66
-
67
- /** 前一 token 是否构成「方法声名前导」——punct 泛型尾/数组尾,ident 非排除关键字。 */
68
- function isMethodCandidate(prev) {
69
- if (!prev) return false;
70
- if (prev.type === 'punct') return prev.value === '>' || prev.value === ']';
71
- if (prev.type === 'ident') return !NOT_METHOD_PREV.has(prev.value);
72
- return false;
73
- }
74
-
75
- /** 从 `(` 起配对 `)`(depth 从 1 起,找到闭合或超出 SIG_CLOSE_LOOKAHEAD 窗口)。 */
76
- function findMatchingParen(tokens, openIdx) {
77
- let depth = 1;
78
- for (let k = openIdx + 1; k < tokens.length && k < openIdx + SIG_CLOSE_LOOKAHEAD; k++) {
79
- const tk = tokens[k];
80
- if (tk.type !== 'punct') continue;
81
- if (tk.value === '(') depth++;
82
- else if (tk.value === ')') { depth--; if (depth === 0) return k; }
83
- }
84
- return -1;
85
- }
86
-
87
- /** 配对 `)` 后找方法体 `{`(BODY_OPEN_LOOKAHEAD 窗口内;遇 `;`/`{`/`)` 提前停)。 */
88
- function findOpenBrace(tokens, closeIdx) {
89
- for (let k = closeIdx + 1; k < Math.min(tokens.length, closeIdx + BODY_OPEN_LOOKAHEAD); k++) {
90
- const tk = tokens[k];
91
- if (tk.type === 'ws' || tk.type === 'comment') continue;
92
- if (tk.type === 'punct') {
93
- if (tk.value === '{') return k;
94
- if (tk.value === ';' || tk.value === '{' || tk.value === ')') return -1;
95
- }
96
- }
97
- return -1;
98
- }
99
-
100
- export function javaKtFuncRanges(text = '') {
101
- const tokens = tokenize(text);
102
- const out = [];
103
- for (let i = 0; i < tokens.length; i++) {
104
- const t = tokens[i];
105
- if (t.type !== 'ident') continue;
106
- const nx = tokens[i + 1];
107
- if (!nx || nx.type !== 'punct' || nx.value !== '(') continue;
108
- // ① 方法名前一 token 过滤(最近的非 ws/comment token)
109
- if (!isMethodCandidate(prevNonWsToken(tokens, i))) continue;
110
- // ② `(` 配对 `)` 后 12 token 内找 `{`
111
- const closeIdx = findMatchingParen(tokens, i + 1);
112
- if (closeIdx === -1) continue;
113
- const openIdx = findOpenBrace(tokens, closeIdx);
114
- if (openIdx === -1) continue;
115
- const range = matchBrace(tokens, openIdx);
116
- if (!range) continue;
117
- const startLine = tokens[openIdx].line;
118
- const endLine = tokens[range[1]].line;
119
- out.push({ startLine, endLine, len: endLine - startLine + 1, name: t.value });
120
- i = range[1]; // 跳过方法体(Java 无嵌套方法;Kotlin 局部 fun 由后续迭代各自评估——不整段跳过外层也能扫到内层,但跳过可避免外层方法重复计数其体内 lambda)
121
- }
122
- return out;
123
- }
124
-
125
- /**
126
- * 内容启发式语言检测(与 pythonDetectDef 同精度级别,用于 AST 层按语言路由)。
127
- * 优先级:python(def + 缩进无大括号)> java/kotlin(方法签名/class 大写/fun)> js。
128
- * @param {string} text 文件全文
129
- * @returns {'python'|'java'|'kotlin'|'js'|'other'}
130
- */
131
- export function detectLang(text = '') {
132
- const s = String(text);
133
- if (/^\s*def\s+[A-Za-z_]\w*\s*\(/m.test(s)) return 'python';
134
- // Kotlin 强信号:fun 关键字(比 class 大写更早判——Kotlin 的 class/interface 声明
135
- // 形态与 Java 相同,先查 fun 避免 Kotlin 文件被 Java 迹象误夺)
136
- if (/^\s*fun\s+[A-Za-z_]\w*\s*\(/m.test(s) || /\bfun\s+[A-Za-z_]\w*\s*\(/m.test(s)) return 'kotlin';
137
- // Java 迹象:行首修饰符/返回类型 + 类/接口/枚举声明(类名惯例大写开头)
138
- if (/^\s*(public|private|protected|static|final|synchronized|abstract|native|default|strictfp)(\s|$)/m.test(s)
139
- || /(^|\n)\s*(public|abstract|final)?\s*(class|interface|enum)\s+[A-Z][A-Za-z0-9_]*/m.test(s)
140
- || /@(Override|Deprecated|SuppressWarnings|Test)\b/.test(s)) return 'java';
141
- return /^\s*(import|require|include|#include|use\s+)/m.test(s) ? 'other' : 'js';
142
- }
143
-
144
- /** 语言 → 函数范围收集器(null = 占位:语言专项规则槽位已建,范围解析待补)。 */
145
- export const LANG_FUNC_RANGES = {
146
- java: javaKtFuncRanges,
147
- kotlin: javaKtFuncRanges,
148
- python: null, // 由 size.js 内联 pythonFuncRanges(避免循环依赖)
149
- js: null, // 由 size.js 内联 funcRangesAst(JS 分支)
150
- go: null,
151
- rust: null,
152
- swift: null,
153
- cpp: null,
154
- php: null,
155
- rb: null,
156
- };
@@ -1,52 +0,0 @@
1
- /**
2
- * 行数口径**单一来源**:代码行 = 总行 − 纯注释行 − 空行。
3
- *
4
- * 【为什么需要单一来源】此前「行数」在多处各算各的:
5
- * `lib/checks/file-health.js` 用「总行 − 纯注释行」(**没减空行** ✗)、
6
- * `lib/ast/size.js` 早年直接用总行 ✗ —— 同一文件在不同规则/报告里
7
- * 给出不同的「行数」,无法对照,也无法作为拆分依据。
8
- *
9
- * 【口径】按**行上有哪些 token** 判定(单趟、无歧义):
10
- * · 有非注释 token(哪怕只有一个 `}`)→ **代码行**(行尾注释不影响 ✓);
11
- * · 只有 comment token → **纯注释行**(含块注释覆盖的每一行 ✓);
12
- * · 都没有(`trim()` 为空)→ **空行**。
13
- * 于是「纯注释行」与「空行」天然不重叠 ✓(块注释内部的空行算注释行 ✓),无需取并集再修正 ✓。
14
- *
15
- * 【不做的事】不判断「有效代码」(只有 `}` 的行仍算代码行 ✓)—— 口径要稳定可预期 ✓,
16
- * 不做语义判断,否则不同人算出的数不一样 ✓。
17
- */
18
-
19
- import { tokenize } from './tokenizer.js';
20
-
21
- /**
22
- * 统计一个文件的行数分布(单趟 token 判定)。
23
- * @param {string} text 文件全文
24
- * @returns {{total:number, comment:number, blank:number, code:number}} 总行 / 纯注释行 / 空行 / 代码行
25
- */
26
- export function lineStats(text) {
27
- const src = String(text || '');
28
- const total = src.split('\n').length;
29
- const codeLines = new Set();
30
- const commentLines = new Set();
31
- for (const t of tokenize(src)) {
32
- const span = String(t.value).split('\n').length - 1;
33
- const bucket = t.type === 'comment' ? commentLines : codeLines;
34
- for (let i = 0; i <= span; i += 1) bucket.add(t.line + i);
35
- }
36
- let code = 0;
37
- let comment = 0;
38
- for (let i = 1; i <= total; i += 1) {
39
- if (codeLines.has(i)) code += 1; // 有代码 → 代码行(行尾注释不影响)
40
- else if (commentLines.has(i)) comment += 1; // 只有注释 → 纯注释行
41
- }
42
- return { total, comment, blank: total - code - comment, code };
43
- }
44
-
45
- /**
46
- * 代码行数(口径见模块头注释)。
47
- * @param {string} text 文件全文
48
- * @returns {number} 代码行
49
- */
50
- export function codeLineCount(text) {
51
- return lineStats(text).code;
52
- }
@@ -1,272 +0,0 @@
1
- /**
2
- * AST 实现层 · 硬编码魔数检查
3
- *
4
- * 职责:token 级识别数字字面量,并豁免版本号/日期/HTTP 状态码/命名常量等合法常量。
5
- * 注释里的版本号、字符串里的 CSS 字号都不是 num token,天然不进入检查。
6
- */
7
-
8
- import { tokenize } from './tokenizer.js';
9
-
10
- /* ───────────────────────── 硬编码魔数检测(token 级,版本号豁免版) ───────────────────────── */
11
-
12
- /** HTTP 常见状态码(魔数豁免清单:status/http 上下文里出现即豁免)。 */
13
- const HTTP_STATUS_CODES = new Set([100, 101, 102, 103, 200, 201, 202, 203, 204, 205, 206, 207, 208, 226,
14
- 300, 301, 302, 303, 304, 305, 307, 308, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410,
15
- 411, 412, 413, 414, 415, 416, 417, 418, 421, 422, 423, 424, 425, 426, 428, 429, 431, 451,
16
- 500, 501, 502, 503, 504]);
17
-
18
- /** 公认合法常量(进制/时间/容量等,无魔数上下文时豁免)。 */
19
- const COMMON_NUM_CONSTANTS = new Set(['0', '1', '-1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '12', '16',
20
- '24', '30', '31', '32', '60', '100', '128', '256', '365', '512', '1000', '1024', '2048', '3600', '4096', '86400', '65535']);
21
-
22
- /** 魔数「命名常量值」判定回跳窗口(向后找等号/属性名「=」的最大 token 跨度)。 */
23
- const CONST_NAME_BACKTRACK = 40;
24
-
25
- const DEFAULT_MAGIC_HINTS = ['timeout', 'retry', 'max', 'min', 'limit', 'size', 'count', 'port',
26
- 'interval', 'delay', 'duration', 'threshold', 'buffer', 'chunk'];
27
-
28
- const DEFAULT_LEGIT_HINTS = ['version', 'date', 'year', 'month', 'day', 'hour', 'minute', 'second', 'http', 'status'];
29
-
30
- /**
31
- * 硬编码魔数检测(token 级,版本号豁免版)。
32
- *
33
- * 为什么是 token 级:逐行正则无法区分「代码里的数字」与「注释/字符串里的数字」——
34
- * 注释里的版本号(`// v1.8.0:数据升级`)、CSS 字号('.x{font-weight:650}')、
35
- * i18n 字典值都会误报。tokenizer 已把注释/字符串/模板串分类成独立 token 类型,
36
- * 只对 num token(真正的数字字面量)判定,从根上消除上述误报,无需任何「跳过行」补丁。
37
- *
38
- * 检测:num token 且形态为 ≥2 位整数 / 小数 / 十六进制(单数字与 0/1 边界天然不参与)。
39
- * 豁免(任一命中即不报):
40
- * · 公认合法常量(0/1/60/100/1000/1024/3600/86400 等),除非处于魔数上下文;
41
- * · legit 上下文(version/date/year/month/day/hour/minute/second/http/status 词邻近);
42
- * · HTTP 状态码 + status/http 上下文;
43
- * · 字符串/注释里的数字(tokenizer 层面即非 num,天然不进入检测)。
44
- * 强制报:邻近 token 命中魔数上下文(timeout/retry/max/min/limit/size/count/port/interval/
45
- * delay/duration/threshold/buffer/chunk),或同一数字文件内出现 ≥ forceCount 次。
46
- *
47
- * @param {string} text 文件全文
48
- * @param {{magicHints?:string[], legitHints?:string[], forceCount?:number}} [opts]
49
- * @returns {Array<{line:number, raw:string, num:string, count:number, magicCtx:boolean}>}
50
- */
51
- export function checkMagicNumberSmartAst(text = '', {
52
- magicHints = DEFAULT_MAGIC_HINTS, legitHints = DEFAULT_LEGIT_HINTS, forceCount = 3,
53
- } = {}) {
54
- const tokens = tokenize(text);
55
- // Python 枚举成员行(class X(Enum) 体内的大写 NAME = 数字)——支持
56
- const pythonEnumLines = collectPythonEnumAssignLines(text);
57
- const hintTest = (hints) => {
58
- const regexes = hints.map((h) => new RegExp(`(^|[^a-z])${h}`, 'i'));
59
- return (ctx) => regexes.some((r) => r.test(ctx));
60
- };
61
- const isMagicCtx = hintTest(magicHints);
62
- const isLegitCtx = hintTest(legitHints);
63
- const hits = [];
64
- const counts = new Map();
65
- for (let i = 0; i < tokens.length; i++) {
66
- const t = tokens[i];
67
- if (t.type !== 'num') continue; // 注释/字符串/tmpl token 天然排除——本检查只认代码里的数字字面量
68
- const raw = String(t.value);
69
- const norm = raw.replace(/_/g, '').replace(/n$/, ''); // 60_000 → 60000、10n → 10
70
- if (!/^(?:0[xX][0-9a-fA-F]+|\d{2,}(?:\.\d+)?|\d+\.\d+)$/.test(norm)) continue; // 单数字不参与
71
- const numeric = /^0[xX]/.test(norm) ? parseInt(norm, 16) : Number(norm);
72
- if (!Number.isFinite(numeric)) continue;
73
- // 上下文 = 邻近 token 文本(前置 6 个看命名,后置 4 个看单位/参数位)
74
- const before = tokens.slice(Math.max(0, i - 6), i).map((x) => x.value).join(' ');
75
- const after = tokens.slice(i + 1, i + 5).map((x) => x.value).join(' ');
76
- const ctx = `${before} ${after}`;
77
- const magicCtx = isMagicCtx(before) || isMagicCtx(ctx);
78
- const legitCtx = isLegitCtx(ctx);
79
- // ── Python 枚举成员豁免(修复 KToolBox 等 Python 项目评估失真)──
80
- // `class Status(IntEnum):` 体内的 `PENDING = 1001` 是枚举成员定义值,
81
- // 不是「散落魔数」——枚举码就是有意设计的标识符。识别:枚举类体内
82
- // 缩进层的大写 `NAME = <数字>` 赋值行。
83
- if (pythonEnumLines.has(t.line)) continue;
84
- // ── 四类豁免(修 scoreboard 误报;规格表:版本号/日期/HTTP 状态码/
85
- // 常见合法常量自动豁免,无上下文裸数字仍报)──
86
- // ① 命名常量定义值:`const NAME = <数字>` / `const NAME = [<数字>, ...]`——
87
- // 数字就是该常量的定义值,报「建议提取为命名常量」自相矛盾
88
- // (PAGE_SIZES = [10, 20, 50]、API_ROW_LIMIT = 200、TTL_MS = 5 * 60_000)。
89
- if (isNamedConstantValue(tokens, i)) continue;
90
- // ② HTTP 状态码:数字 ∈ HTTP_STATUS_CODES 即豁免——sendJson(res, 405, ...) 的 405、
91
- // `status_code == 429` 的 429 都是状态码不是魔数;**不要求 !magicCtx**(
92
- // 变量名带 retry/limit 等魔数关键词(retryable_status)会被 isMagicCtx 误判为
93
- // 「魔数上下文」,但状态码语义本身合法,应先豁免——状态码 > 上下文提示)。
94
- if (HTTP_STATUS_CODES.has(numeric)) continue;
95
- // ④ 配置兜底默认值(Pawchive 核对 8 处误报中的 4 处):
96
- // `Number(env) || 3000` / `process.env.X ?? 10000`——||/?? 右侧是配置缺失时的默认值,
97
- // 不是散落魔数(兜底写法本身说明语义)。
98
- if (tokens[i - 1] && (tokens[i - 1].value === '||' || tokens[i - 1].value === '??')) continue;
99
- // 修(Pawchive):比较阈值——`n < 1048576` / `> 65536`——比较运算符后的数字
100
- // 是界限/阈值语义(比较即声明边界),不是散落魔数
101
- if (tokens[i - 1] && ['<', '>', '<=', '>='].includes(tokens[i - 1].value)) continue;
102
- // 修(Pawchive):超时 API 配置参数——`AbortSignal.timeout(5000)`(超时上限语义;
103
- // 普通 setTimeout(fn, N) 回调用时长是「真魔数上下文」仍报——见 test-magic 魔数上下文用例)
104
- if (/AbortSignal\s*\.\s*timeout\s*\(/.test(before)) continue;
105
- // ⑤ 配置字段/属性赋值默认值(Pawchive 核对:CONFIG.pageSize=50 /
106
- // { pageSize: 50 } 等配置字段):属性名/成员名已说明含义,值即默认值非散落魔数
107
- // (`obj.prop = N` member 赋值 / `{ prop: N }` 对象属性值——CSS 样式属性同形态)。
108
- const prev2 = tokens[i - 2];
109
- const prev3 = tokens[i - 3];
110
- const isPropAssign = Boolean(tokens[i - 1] && tokens[i - 1].value === '=' && prev3 && prev3.value === '.'); // obj.prop = N:= 在 i-1,. 在 i-3
111
- // 对象属性值仅豁免「配置语义属性名」(pageSize/apiTimeoutMs/apiRetryIntervalMs 等——
112
- // Pawchive 核对),普通对象数字({ width: 1400 } 布局/样式属性)照报。
113
- const isObjPropVal = Boolean(tokens[i - 1] && tokens[i - 1].value === ':' && prev2
114
- && /(size|ms|bytes|kb|mb|gb|timeout|interval|retry|limit|port|count|delay|duration|threshold|max|min|buffer|chunk|ttl|backoff|window)$/i.test(String(prev2.value)));
115
- if (isPropAssign || isObjPropVal) continue;
116
- // ③ 函数参数默认值:`(e, max = 120)` —— 参数名 max 已说明含义,默认值不是硬编码
117
- // Python 形态 `timeout: float = 5.0`(含类型注解,:KToolBox
118
- // api/client.py 的 timeout/retry_interval 默认值此前误报)。
119
- if (/[,(]\s*[a-zA-Z_$][\w$]*\s*(:\s*[A-Za-z_$][\w$.\[\]]*\s*)?=\s*$/.test(before)) continue;
120
- // ④ 常见合法常量(1024/3600/86400 等进制、时间、容量单位)即使处于魔数上下文也豁免
121
- // ——8 * 1024 * 1024 是 8MB 的容量表达,1024 是单位不是魔数。
122
- if (COMMON_NUM_CONSTANTS.has(norm)) continue;
123
- // ④b CSS 色值豁免:rgba(255,255,255,.08) / #fff 的 255 是 RGB 通道上限,
124
- // 不是「散落魔数」——前文 token 含 rgba/rgb/color 语义即豁免(0-255 通道值)。
125
- if (!magicCtx && /rgba?\s*\(|color/i.test(before)) continue;
126
- // ④c 日期时间构造豁免:datetime(2024, 1, 1, 0, 0, 0) / date(2026, 9, 1)
127
- // 的年/月/日/时/分/秒参数是日期语义,不是散落魔数(KToolBox 断言用 datetime 构造
128
- // 具体时刻,数字全是时间组成部分)。
129
- if (!magicCtx && /datetime|date\s*\(|time\s*\(/i.test(before)) continue;
130
- // ④d pydantic Field 参数豁免:Field(default=30 * 60, ge=1, le=3600)
131
- // 的 default/ge/le/gt/lt/multiple_of 是字段约束声明,数字是约束值不是魔数。
132
- if (!magicCtx && /field\s*\(|default\s*=|ge\s*=|le\s*=|gt\s*=|lt\s*=|multiple_of\s*=/i.test(before)) continue;
133
- if (!magicCtx && legitCtx) continue;
134
- if (!magicCtx && HTTP_STATUS_CODES.has(numeric) && /status|http/i.test(ctx)) continue;
135
- counts.set(norm, (counts.get(norm) || 0) + 1);
136
- hits.push({ line: t.line, raw, num: norm, magicCtx });
137
- }
138
- // 输出:同一数字只报首次出现的行。
139
- // 修:旧逻辑「count>=forceCount 或 magicCtx 才报」会把「单次出现且无
140
- // 魔数上下文的裸数字」过滤掉——规格表 ❌ 项(const x = 1.2 / if (score > 1.5) /
141
- // const ratio = 1.2)全是这种情况,应报。豁免已在上面四类(命名常量值/HTTP 状态码
142
- // 实参/参数默认值/常见合法常量)处理完,能走到这里的数字就是该报的魔数;
143
- // count 与 magicCtx 仅作 message 信息(forceCount 语义并入 message)。
144
- const out = [];
145
- const reported = new Set();
146
- for (const hit of hits) {
147
- if (reported.has(hit.num)) continue;
148
- reported.add(hit.num);
149
- out.push({ line: hit.line, raw: hit.raw, num: hit.num, count: counts.get(hit.num) || 1, magicCtx: hit.magicCtx });
150
- }
151
- return out;
152
- }
153
-
154
- /** 从数字往回扫描找 `=`(跳过值表达式运算符/数组对象分隔符/属性名)。 */
155
- function scanBackToEquals(tokens, numIdx) {
156
- const SKIP = new Set(['*', '/', '+', '-', '%', '[', ']', ',', '(', ')', '{', '}', ':']);
157
- for (let j = numIdx - 1; j >= Math.max(0, numIdx - CONST_NAME_BACKTRACK); j--) {
158
- const tj = tokens[j];
159
- if (tj.type === 'ws' || tj.type === 'comment') continue;
160
- if (tj.type === 'num' || SKIP.has(tj.value)) continue; // 值表达式/数组对象分隔符
161
- if (tj.value === '=') return j;
162
- if (tj.value === ';') return -1; // 越出语句
163
- if (tj.type === 'ident') {
164
- // 对象字面量属性名({ width: 1400 } 的 width)是常量定义的一部分,
165
- // 往回跳时允许经过——但只在「该 ident 后跟 ':'」时(属性名 ≠ 其他表达式标识符)。
166
- const nextT = tokens[j + 1];
167
- if (nextT && nextT.value === ':') continue; // 属性名:{ width: 1400 } 的 width
168
- return -1;
169
- }
170
- return -1;
171
- }
172
- return -1;
173
- }
174
-
175
- /** `=` 前检查是否为 const/let/var NAME 声明(或 Python 全大写裸赋值)。 */
176
- function checkConstPrefix(tokens, eqIdx) {
177
- let constName = null;
178
- let declKw = null;
179
- for (let j = eqIdx - 1; j >= 0; j--) {
180
- const tj = tokens[j];
181
- if (tj.type === 'ws' || tj.type === 'comment') continue;
182
- if (!constName) { if (tj.type !== 'ident') return false; constName = tj; continue; }
183
- declKw = tj;
184
- break;
185
- }
186
- if (!constName) return false;
187
- // declKw 放宽——Python 无 const/let/var,`API_VERSION = 2023` 是命名常量
188
- // 但 declKw 是行首/其他标识符。放宽:declKw 为 const/let/var → 常规路径;
189
- // 否则(Python 或 JS 裸赋值)仅当 constName **全大写**(PEP8 常量惯例)才豁免——
190
- // 小写裸赋值(x = 42)是普通变量赋值,值 42 仍算魔数(该报)。
191
- const hasDeclKw = declKw && ['const', 'let', 'var'].includes(declKw.value);
192
- const allCaps = /^[A-Z][A-Z0-9_]*$/.test(constName.value);
193
- if (!hasDeclKw && !allCaps) return false;
194
- // 修(Pawchive):`const barW = 18`——const 声明且**表意名**(≥3 字符)即命名常量
195
- // (规则本意「提取为命名常量」——已是 const 声明即达标);单字母(const a = 777)仍报
196
- if (hasDeclKw && declKw.value === 'const' && constName.value.length >= 3) return true;
197
- // 常量名:全大写(PAGE_SIZES/API_ROW_LIMIT/TTL_MS)、常见前缀驼峰(dshgp_FETCH_TIMEOUT_MS、
198
- // DEFAULT_WEIGHTS、MAX_SCAN_FILES、LIST_LIVE_BUDGET_MS——带语义词尾 timeout/limit/size/count/
199
- // ms 等也是命名常量),或含 version/date 等语义。修:此前只认全大写——
200
- // 项目自己的 `dshgp_*` 前缀常量被误报成魔数(建议提取为命名常量,自相矛盾)。
201
- const constNameStr = constName.value;
202
- const semanticTail = /(timeout|retry|max|min|limit|size|count|interval|delay|duration|threshold|buffer|chunk|version|date|year|month|day|hour|minute|second|total|ms|kb|mb|rounds|levels|weight|score|price|ratio|percent|budget|lookahead)/i;
203
- return /^[A-Z][A-Z0-9_]*$/.test(constNameStr)
204
- || /^[a-z]+_[A-Z][A-Z0-9_]*$/.test(constNameStr) // 小写前缀_全大写尾(dshgp_FETCH_TIMEOUT_MS)
205
- || semanticTail.test(constNameStr)
206
- || /version|date|year|month|day|hour|minute|second|total|count|limit|size/i.test(constNameStr);
207
- }
208
-
209
- /**
210
- * 判定数字 token 是否为「命名常量定义值」:向前看是否有 `const/let/var NAME = ` 模式
211
- * (NAME 为大写常量名或含 version/date 语义),数组字面量 [10, 20, 50] 内同样算。
212
- * 规则本意是「把散落的数字提取为命名常量」——数字已经是命名常量的定义值时不报。
213
- * @param {Array} tokens token 流
214
- * @param {number} numIdx 数字 token 下标
215
- * @returns {boolean}
216
- */
217
- function isNamedConstantValue(tokens, numIdx) {
218
- // 从数字往回:先跳过「值表达式」部分——运算符(* / + - %)、其他数字、数组/对象分隔符
219
- // ([ ] , { } :)都属于赋值右侧表达式;然后找 =,= 前一个标识符是常量名,
220
- // 再前一个是 const/let/var。命中 const NAME = <expr> 即视为命名常量定义值。
221
- const eqIdx = scanBackToEquals(tokens, numIdx);
222
- if (eqIdx === -1) return false;
223
- return checkConstPrefix(tokens, eqIdx);
224
- }
225
-
226
- /**
227
- * 收集 Python 枚举成员赋值行。
228
- *
229
- * 为什么需要:Python 无 const/let/var,`class Status(IntEnum):` 体内(乃至普通类体内)
230
- * `PENDING = 1001` 过不了 isNamedConstantValue(它要求 const/let/var 前缀),
231
- * 枚举码被当魔数误报(KToolBox `_enum.py` 的 1001/1002/2001、配置里的版本号
232
- * 2023/2024 全中招)。枚举成员值是有意设计的标识符,不是散落魔数。
233
- *
234
- * 识别规则:
235
- * · **任意类体**内(class X(...): 或 class X:)的 `^<缩进>NAME = <数字>`
236
- * ——NAME 全大写(Python 常量/枚举成员惯例)。二次修:不限于
237
- * Enum/IntEnum 基类——KToolBox `_enum.py` 用**普通类**(`class Error:` 无括号)
238
- * 定义错误码枚举(NetWorkError = 1001),此前只认 Enum 基类导致漏豁免。
239
- * · 缩进 > 类定义缩进(排除 def 方法签名/类外的顶层行)。
240
- * · 收紧面:仅「全大写 NAME = 数字」豁免;类体内小写属性(port = 8080)不豁免
241
- * (仍是散落魔数)。
242
- *
243
- * @param {string} text 文件全文
244
- * @returns {Set<number>} 命中的行号集合(1-based)
245
- */
246
- function collectPythonEnumAssignLines(text) {
247
- const out = new Set();
248
- const lines = String(text).split('\n');
249
- let inEnum = false;
250
- let enumIndent = -1;
251
- // 任意类:class X(...): 或 class X:(基类可省略——Python 枚举常用普通类)
252
- const CLASS_RE = /^(\s*)class\s+[A-Za-z_]\w*(?:\s*\([^)]*\))?\s*:/;
253
- // 类成员赋值:全大写(PENDING)或驼峰(NetWorkError)开头 + = 数字——Python 枚举/
254
- // 常量惯例(二次修:KToolBox `_enum.py` 用驼峰成员 NetWorkError/JsonDecodeError)。
255
- // 收紧面:首字符大写(排除小写属性 port = 8080);数字值(排除字符串成员)。
256
- const MEMBER_RE = /^(\s*)([A-Z][A-Za-z0-9_]*)\s*=\s*\d+(?:\s*#.*)?$/;
257
- for (let i = 0; i < lines.length; i++) {
258
- const line = lines[i];
259
- const cls = CLASS_RE.exec(line);
260
- if (cls) {
261
- inEnum = true;
262
- enumIndent = cls[1].length;
263
- continue;
264
- }
265
- if (!inEnum) continue;
266
- // 缩进回到类定义级或更浅 → 枚举类结束
267
- const indent = (line.match(/^\s*/) || [''])[0].length;
268
- if (line.trim() && indent <= enumIndent) { inEnum = false; continue; }
269
- if (MEMBER_RE.test(line)) out.add(i + 1);
270
- }
271
- return out;
272
- }