dsh-git-push 0.0.0-stage → 2.8.6

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 (279) hide show
  1. package/.auditignore +30 -0
  2. package/.gitignore +39 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1486 -2
  5. package/cli.mjs +360 -0
  6. package/cordis.patch.yml +14 -0
  7. package/lib/ARCHITECTURE.md +34 -0
  8. package/lib/BUGFIX-NOTES-2026-09-14.md +278 -0
  9. package/lib/app/apply.js +275 -0
  10. package/lib/app/audit-api.js +158 -0
  11. package/lib/app/command-registry.js +266 -0
  12. package/lib/app/constants.js +16 -0
  13. package/lib/app/handlers/account.js +166 -0
  14. package/lib/app/handlers/clone.js +168 -0
  15. package/lib/app/handlers/http-constants.js +9 -0
  16. package/lib/app/handlers/identity-rewrite.js +94 -0
  17. package/lib/app/handlers/meta.js +175 -0
  18. package/lib/app/handlers/npm.js +169 -0
  19. package/lib/app/handlers/repo-actions.js +143 -0
  20. package/lib/app/handlers/repos.js +231 -0
  21. package/lib/app/handlers/settings.js +62 -0
  22. package/lib/app/host-doc-checks.js +25 -0
  23. package/lib/app/http-handlers.js +131 -0
  24. package/lib/app/index.js +30 -0
  25. package/lib/app/inject-text.js +192 -0
  26. package/lib/app/scan-root.js +23 -0
  27. package/lib/app/schema.js +150 -0
  28. package/lib/app/settings-bridge.js +167 -0
  29. package/lib/app/slash-commands.js +395 -0
  30. package/lib/app/slot-stats.js +35 -0
  31. package/lib/app/tool-call.js +672 -0
  32. package/lib/app/tools.js +34 -0
  33. package/lib/ast/brace.js +105 -0
  34. package/lib/ast/callgraph.js +135 -0
  35. package/lib/ast/code-lines.js +114 -0
  36. package/lib/ast/consts.js +12 -0
  37. package/lib/ast/control-flow.js +461 -0
  38. package/lib/ast/credential.js +199 -0
  39. package/lib/ast/dataflow.js +274 -0
  40. package/lib/ast/dup-code.js +165 -0
  41. package/lib/ast/index.js +36 -0
  42. package/lib/ast/io-risk-const.js +95 -0
  43. package/lib/ast/io-risk-fn.js +208 -0
  44. package/lib/ast/io-risk-loop.js +308 -0
  45. package/lib/ast/io-risk.js +314 -0
  46. package/lib/ast/lang.js +156 -0
  47. package/lib/ast/line-count.js +52 -0
  48. package/lib/ast/magic-number.js +272 -0
  49. package/lib/ast/naming.js +284 -0
  50. package/lib/ast/perf.js +472 -0
  51. package/lib/ast/scope.js +241 -0
  52. package/lib/ast/shell.js +131 -0
  53. package/lib/ast/size.js +378 -0
  54. package/lib/ast/symbol-index.js +399 -0
  55. package/lib/ast/tokenizer.js +341 -0
  56. package/lib/audit/analysis-coverage.js +98 -0
  57. package/lib/audit/audit-file.js +182 -0
  58. package/lib/audit/checks.js +17 -0
  59. package/lib/audit/client-entry.js +93 -0
  60. package/lib/audit/collector.js +477 -0
  61. package/lib/audit/ext-runner.js +80 -0
  62. package/lib/audit/file-context.js +138 -0
  63. package/lib/audit/finding.js +50 -0
  64. package/lib/audit/gitignore-match.js +113 -0
  65. package/lib/audit/glob.js +63 -0
  66. package/lib/audit/history-report.js +100 -0
  67. package/lib/audit/history.js +126 -0
  68. package/lib/audit/ignore-blind.js +101 -0
  69. package/lib/audit/index.js +33 -0
  70. package/lib/audit/orchestrate.js +476 -0
  71. package/lib/audit/public.js +24 -0
  72. package/lib/audit/repo-level.js +30 -0
  73. package/lib/audit/report-yaml.js +86 -0
  74. package/lib/audit/slot.js +65 -0
  75. package/lib/audit-defaults.js +18 -0
  76. package/lib/audit-rules/audit-rules-comment.yml +247 -0
  77. package/lib/audit-rules/audit-rules-cpp.yml +22 -0
  78. package/lib/audit-rules/audit-rules-docs.yml +32 -0
  79. package/lib/audit-rules/audit-rules-dsh.yml +162 -0
  80. package/lib/audit-rules/audit-rules-filehealth.yml +42 -0
  81. package/lib/audit-rules/audit-rules-folder.yml +99 -0
  82. package/lib/audit-rules/audit-rules-frontend.yml +335 -0
  83. package/lib/audit-rules/audit-rules-go.yml +22 -0
  84. package/lib/audit-rules/audit-rules-i18n.yml +45 -0
  85. package/lib/audit-rules/audit-rules-java.yml +105 -0
  86. package/lib/audit-rules/audit-rules-nodejs.yml +647 -0
  87. package/lib/audit-rules/audit-rules-npm.yml +187 -0
  88. package/lib/audit-rules/audit-rules-paths.yml +92 -0
  89. package/lib/audit-rules/audit-rules-performance.yml +215 -0
  90. package/lib/audit-rules/audit-rules-php.yml +22 -0
  91. package/lib/audit-rules/audit-rules-private.yml +24 -0
  92. package/lib/audit-rules/audit-rules-python.yml +106 -0
  93. package/lib/audit-rules/audit-rules-robustness.yml +27 -0
  94. package/lib/audit-rules/audit-rules-rust.yml +22 -0
  95. package/lib/audit-rules/audit-rules-structure.yml +159 -0
  96. package/lib/audit-rules/audit-rules-swift.yml +22 -0
  97. package/lib/audit-rules/audit-rules-template.yml +108 -0
  98. package/lib/checks/button-bind.js +276 -0
  99. package/lib/checks/common.js +170 -0
  100. package/lib/checks/credential-file.js +43 -0
  101. package/lib/checks/dataflow.js +40 -0
  102. package/lib/checks/dispatch.js +112 -0
  103. package/lib/checks/dup-code.js +69 -0
  104. package/lib/checks/dup-const.js +232 -0
  105. package/lib/checks/file-health.js +150 -0
  106. package/lib/checks/filter.js +137 -0
  107. package/lib/checks/folder.js +173 -0
  108. package/lib/checks/hardcoded-path.js +98 -0
  109. package/lib/checks/index.js +46 -0
  110. package/lib/checks/io.js +66 -0
  111. package/lib/checks/magic-number.js +42 -0
  112. package/lib/checks/npm-json.js +273 -0
  113. package/lib/checks/private.js +63 -0
  114. package/lib/checks/regex.js +256 -0
  115. package/lib/checks/semantic.js +134 -0
  116. package/lib/checks/structural.js +274 -0
  117. package/lib/cli/commands-account.mjs +107 -0
  118. package/lib/cli/commands-audit.mjs +144 -0
  119. package/lib/cli/commands-doc.mjs +127 -0
  120. package/lib/cli/commands-vcs.mjs +175 -0
  121. package/lib/client/index.js +162 -0
  122. package/lib/client-parts/00-loader.js +33 -0
  123. package/lib/client-parts/01-const.js +207 -0
  124. package/lib/client-parts/02-utils.js +62 -0
  125. package/lib/client-parts/03-icons.js +12 -0
  126. package/lib/client-parts/10-account.js +83 -0
  127. package/lib/client-parts/11-browser.js +95 -0
  128. package/lib/client-parts/20-repo.js +374 -0
  129. package/lib/client-parts/21-audit.js +301 -0
  130. package/lib/client-parts/22-settings.js +146 -0
  131. package/lib/client-parts/23-npm.js +383 -0
  132. package/lib/client-parts/30-page.js +56 -0
  133. package/lib/client-parts/40-controller.js +1092 -0
  134. package/lib/client-parts/41-actions.js +279 -0
  135. package/lib/client-parts/99-apply.js +72 -0
  136. package/lib/client.js +3195 -0
  137. package/lib/commit-push.js +148 -0
  138. package/lib/context/index.js +363 -0
  139. package/lib/core/atomic-json.js +98 -0
  140. package/lib/core/config.js +40 -0
  141. package/lib/core/credentials.js +274 -0
  142. package/lib/core/endpoints.js +109 -0
  143. package/lib/core/exec.js +162 -0
  144. package/lib/exempt/index.js +292 -0
  145. package/lib/fs/edit-after-read.js +103 -0
  146. package/lib/fsx.js +87 -0
  147. package/lib/git/account-status.js +140 -0
  148. package/lib/git/account.js +233 -0
  149. package/lib/git/api.js +136 -0
  150. package/lib/git/atomic-json.js +6 -0
  151. package/lib/git/browse.js +38 -0
  152. package/lib/git/clone-download.js +397 -0
  153. package/lib/git/clone-history-mode.js +143 -0
  154. package/lib/git/clone-history.js +175 -0
  155. package/lib/git/clone-jobs.js +250 -0
  156. package/lib/git/clone-replay-io.js +172 -0
  157. package/lib/git/clone-replay.js +275 -0
  158. package/lib/git/clone.js +445 -0
  159. package/lib/git/cloud.js +46 -0
  160. package/lib/git/commit-message.js +141 -0
  161. package/lib/git/config.js +6 -0
  162. package/lib/git/cred-env.js +88 -0
  163. package/lib/git/credentials.js +6 -0
  164. package/lib/git/endpoints.js +6 -0
  165. package/lib/git/exec.js +6 -0
  166. package/lib/git/identity-rewrite.js +297 -0
  167. package/lib/git/identity.js +150 -0
  168. package/lib/git/ignore.js +69 -0
  169. package/lib/git/index.js +41 -0
  170. package/lib/git/module-splitter.js +47 -0
  171. package/lib/git/post-push.js +101 -0
  172. package/lib/git/push-diagnose.js +142 -0
  173. package/lib/git/push.js +476 -0
  174. package/lib/git/remote-resolve.js +146 -0
  175. package/lib/git/remote.js +128 -0
  176. package/lib/git/repo-index.js +512 -0
  177. package/lib/git/repos.js +235 -0
  178. package/lib/git/scan-runner.js +159 -0
  179. package/lib/git/sensitive.js +134 -0
  180. package/lib/git/transport.js +430 -0
  181. package/lib/git/visibility.js +35 -0
  182. package/lib/git/wrapped-git.js +68 -0
  183. package/lib/http/index.js +170 -0
  184. package/lib/index.js +24 -0
  185. package/lib/link-check/index.js +187 -0
  186. package/lib/npm/account.js +64 -0
  187. package/lib/npm/install.js +211 -0
  188. package/lib/npm/npmrc.js +56 -0
  189. package/lib/npm/publish.js +171 -0
  190. package/lib/npm/registry.js +168 -0
  191. package/lib/plugin/auto-detect.js +92 -0
  192. package/lib/plugin/auto-push.js +154 -0
  193. package/lib/plugin/index.js +250 -0
  194. package/lib/readme-templates/readme.yml +38 -0
  195. package/lib/rule/compilers/credential.js +62 -0
  196. package/lib/rule/compilers/dataflow.js +38 -0
  197. package/lib/rule/compilers/file-health.js +75 -0
  198. package/lib/rule/compilers/frontend.js +86 -0
  199. package/lib/rule/compilers/func.js +35 -0
  200. package/lib/rule/compilers/helpers.js +71 -0
  201. package/lib/rule/compilers/index.js +29 -0
  202. package/lib/rule/compilers/link-semantic.js +45 -0
  203. package/lib/rule/compilers/list-kinds.js +12 -0
  204. package/lib/rule/compilers/numeric-kinds.js +66 -0
  205. package/lib/rule/compilers/regex.js +78 -0
  206. package/lib/rule/compilers/structure.js +80 -0
  207. package/lib/rule/compilers.js +17 -0
  208. package/lib/rule/homoglyph.js +45 -0
  209. package/lib/rule/loader.js +270 -0
  210. package/lib/rule/registry.js +115 -0
  211. package/lib/rule/scope.js +67 -0
  212. package/lib/score/docs-score.js +166 -0
  213. package/lib/score/index.js +140 -0
  214. package/lib/self/index.js +196 -0
  215. package/lib/skip-dirs.js +64 -0
  216. package/lib/tool-probes.json +50 -0
  217. package/lib/user-requirements.json +14 -0
  218. package/lib/vendor/js-yaml/LICENSE +21 -0
  219. package/lib/vendor/js-yaml/js-yaml.mjs +3073 -0
  220. package/package.json +95 -4
  221. package/scripts/__pycache__/module-splitter.cpython-38.pyc +0 -0
  222. package/scripts/audit-ext/_example-readme-present.mjs +34 -0
  223. package/scripts/audit-ext/variable-min-length.mjs +102 -0
  224. package/scripts/audit-runner.mjs +35 -0
  225. package/scripts/audit-runtime-check.mjs +129 -0
  226. package/scripts/browser-page-probe.mjs +271 -0
  227. package/scripts/build-client.mjs +119 -0
  228. package/scripts/check.mjs +88 -0
  229. package/scripts/clean-date-comments.py +102 -0
  230. package/scripts/cpu-sample.mjs +188 -0
  231. package/scripts/doc-drift.mjs +200 -0
  232. package/scripts/doc-func.mjs +212 -0
  233. package/scripts/doc-tree.mjs +456 -0
  234. package/scripts/doc-version.mjs +220 -0
  235. package/scripts/frontend-preview-check.mjs +124 -0
  236. package/scripts/hot-path-probe-cjs.cjs +71 -0
  237. package/scripts/hot-path-probe-fs-shim.mjs +28 -0
  238. package/scripts/hot-path-probe-fsp-shim.mjs +31 -0
  239. package/scripts/hot-path-probe.mjs +153 -0
  240. package/scripts/module-splitter.py +800 -0
  241. package/scripts/platform-scan.mjs +168 -0
  242. package/scripts/preview-gen.mjs +489 -0
  243. package/scripts/preview-local-runner.mjs +55 -0
  244. package/scripts/preview-server-direct.mjs +116 -0
  245. package/scripts/preview-server.mjs +305 -0
  246. package/scripts/preview-slot-data.mjs +123 -0
  247. package/scripts/probe-recheck.mjs +47 -0
  248. package/scripts/readme-gen.mjs +268 -0
  249. package/scripts/rename-locator.mjs +97 -0
  250. package/scripts/rule-switch.mjs +97 -0
  251. package/scripts/rules-solo-audit.mjs +173 -0
  252. package/scripts/scan-file-io.mjs +713 -0
  253. package/scripts/scan-hardcoded-paths.mjs +125 -0
  254. package/scripts/scan-repos.mjs +167 -0
  255. package/scripts/scan-version.mjs +122 -0
  256. package/scripts/scrub-user-wording.mjs +420 -0
  257. package/scripts/symbol-index.mjs +85 -0
  258. package/scripts/sync-plugin-install.mjs +223 -0
  259. package/scripts/sync-plugin.mjs +279 -0
  260. package/scripts/verify-prestep.mjs +100 -0
  261. package/skills/dev/audit-rule-authoring.md +58 -0
  262. package/skills/dev/dsh-git-push.md +323 -0
  263. package/skills/dev/git-push-live-fix.md +45 -0
  264. package/skills/dsh-repo-index.md +35 -0
  265. package/skills/guide/guide-audit.md +167 -0
  266. package/skills/guide/guide-cli-scripts.md +104 -0
  267. package/skills/guide/guide-clone-repos.md +173 -0
  268. package/skills/guide/guide-commit-push.md +156 -0
  269. package/skills/guide/guide-inject-ui.md +166 -0
  270. package/skills/guide/guide-slash-completion.md +118 -0
  271. package/skills/workflow/README.md +21 -0
  272. package/skills/workflow/git-commit-discipline.md +68 -0
  273. package/skills/workflow/git-project-startup.md +85 -0
  274. package/skills/workflow/git-rebuild-process.md +57 -0
  275. package/skills/workflow/github-operations.md +91 -0
  276. package/skills/workflow/readme-sync-git-md.md +28 -0
  277. package/skills/workflow/task-completion-report.md +73 -0
  278. package/skills/workflow/tool-json-add-ask.md +35 -0
  279. package/skills/workflow/versioning-rule.md +211 -0
@@ -0,0 +1,272 @@
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
+ }
@@ -0,0 +1,284 @@
1
+ /**
2
+ * AST 实现层 · 命名与读取检查
3
+ *
4
+ * 职责:标识符长度、函数名是否过短(含 i18n 缩写豁免)、受控小文件读取判定。
5
+ */
6
+
7
+ import { tokenize } from './tokenizer.js';
8
+
9
+ /** 声明/控制流关键字(Java「类型 短名」分支须排除的常见语言关键字前缀)——
10
+ * prevT 是这些时不是「类型名」,`短名` 属各语言声明/流程语境而非 Java 变量声明。
11
+ * const/let/var=JS、val=Kotlin、return=流程、function/def/class=声明、import/from=导入、
12
+ * for/in/of=循环头、case=switch、new=构造、throw=抛错。 */
13
+ const DECL_KEYWORDS = new Set([
14
+ 'const', 'let', 'var', 'val', 'return', 'function', 'def', 'class', 'import', 'from',
15
+ 'for', 'in', 'of', 'case', 'new', 'throw', 'while', 'if', 'else', 'switch', 'catch',
16
+ 'typeof', 'void', 'delete', 'yield', 'await', 'extends', 'super', 'this', 'static',
17
+ ]);
18
+
19
+ /**
20
+ * 检查函数/变量命名长度不足(min-length kind,AST 级)。
21
+ * 覆盖:function 声明名的长度、参数名单字母、变量声明名单字母。
22
+ * @param {string} text 文件全文
23
+ * @param {object} [opts] { min=2, allow=['i','j','k','x','y','z','e','_','$','a','b','n','p','s','v','f','t','r','id','ok','db','fs','os','el','cb','err','req','res','ctx','args' } }
24
+ * @returns {Array<{line:number, name:string, type:string}>}
25
+ */
26
+ export function checkNameLengthAst(text = '', { min = 2, allow = [] } = {}) {
27
+ const tokens = tokenize(text);
28
+ const out = [];
29
+ const allowSet = new Set(['i', 'j', 'k', 'x', 'y', 'z', 'e', '_', '$', 'a', 'b', 'n', 'p', 's', 'v', 'f', 't', 'r',
30
+ 'id', 'ok', 'db', 'fs', 'os', 'el', 'cb', 'err', 'req', 'res', 'ctx', 'args', 'key', 'val', 'fn', 'ns', ...allow,
31
+ // i18n/字典领域标准缩写——tr/L 是翻译与字典加载的通用命名(对标
32
+ // react-i18next 的 t、i18n 字典 dict),不是「无法猜出含义」的缩写。
33
+ // 小写 l 与大写 L 同语义(line/字典加载),此前只列了大写 → 同一写法两种待遇(自审实测命中)。
34
+ 'tr', 'L', 'l', 'i18n', 'dict', 'locale']);
35
+ // 窄作用域阈值:短名所在大括号块的行跨度 ≤ 该值时视为「惯用局部别名」不报(见下方声明分支)。
36
+ // 取 8 的依据:实测 dsh-session-conductor 的 20 条业务层命中全部落在 3–6 行的紧邻块内,
37
+ // 而真正难读的是「跨几十行仍在用的短名」——8 行既放行惯用法、又不放过长作用域。
38
+ const SCOPE_LINES = 8;
39
+ for (let i = 0; i < tokens.length; i++) {
40
+ const t = tokens[i];
41
+ // 函数声明:function 后的 ident
42
+ if (t.type === 'ident' && t.value === 'function') {
43
+ const nx = tokens[i + 1];
44
+ if (nx && nx.type === 'ident' && nx.value.length < min && !allowSet.has(nx.value)) {
45
+ out.push({ line: nx.line, name: nx.value, type: 'function' });
46
+ }
47
+ continue;
48
+ }
49
+ // 参数列表内的短名(function f(a, b) / (a, b) => 的形参或调用实参位置)——短函数参数可接受(作用域 P2)
50
+ if (t.type === 'ident' && t.value.length < min && !allowSet.has(t.value)) {
51
+ const prevT = tokens[i - 1];
52
+ const nextT = tokens[i + 1];
53
+ const inParams = prevT && ((prevT.type === 'punct' && (prevT.value === '(' || prevT.value === ',')))
54
+ && nextT && (nextT.type === 'punct' && (nextT.value === ',' || nextT.value === ')'));
55
+ if (inParams) continue;
56
+ }
57
+ // 变量声明:const/let/var 后的 ident
58
+ if (t.type === 'ident' && ['const', 'let', 'var'].includes(t.value)) {
59
+ const nx = tokens[i + 1];
60
+ // 循环迭代变量豁免(for (const d of densityHits) / for (let i in obj) 的
61
+ // 单字母是强语义局部变量——作用域仅循环体、语义由被遍历集合决定,不属「看不懂含义」。
62
+ if (nx && nx.type === 'ident' && nx.value.length < min && !allowSet.has(nx.value)) {
63
+ // token 序列:for (const d of ... —— const 前一 token 是 '(',再前是 'for'
64
+ const prevP = tokens[i - 1];
65
+ const prev2 = tokens[i - 2];
66
+ const inForHead = prevP && prevP.type === 'punct' && prevP.value === '('
67
+ && prev2 && prev2.type === 'ident' && prev2.value === 'for';
68
+ // 作用域分析(新增):短名若只落在**很窄**的作用域里(声明所在大括号块的行跨度
69
+ // ≤ SCOPE_LINES),属惯用局部别名(c=chunk / h=header / m=method / d=data / q=query),
70
+ // 含义由紧邻的上下文决定,不影响可读性 ⇒ 不报;只有跨越大段代码仍用短名才真的难看懂。
71
+ // 实测 dsh-session-conductor 的 20 条业务层命中全部落在 3–6 行的紧邻块内
72
+ // (声明与最后一次使用相距 ≤ 4 行),而它们此前全被报成「应可读命名」。
73
+ // 用**大括号栈**定位声明所在块(而不是「同名最后一次出现」——同文件里可能有另一个
74
+ // 同名的短别名,那样会把它误算成同一作用域、导致该报的不报/该放行的报)。
75
+ let scopeEndLine = nx.line;
76
+ {
77
+ // 向前找声明所在的最内层 '{'(跳过字符串/注释——tokenizer 已把它们单独分类)
78
+ let depth = 0;
79
+ let openIdx = -1;
80
+ for (let k = i - 1; k >= 0; k--) {
81
+ const tk = tokens[k];
82
+ if (tk.type !== 'punct') continue;
83
+ if (tk.value === '}') depth++;
84
+ else if (tk.value === '{') {
85
+ if (depth === 0) { openIdx = k; break; }
86
+ depth--;
87
+ }
88
+ }
89
+ if (openIdx !== -1) {
90
+ // 从该 '{' 向后配对到它的 '}',其行号即作用域结束
91
+ let d2 = 0;
92
+ for (let k = openIdx; k < tokens.length; k++) {
93
+ const tk = tokens[k];
94
+ if (tk.type !== 'punct') continue;
95
+ if (tk.value === '{') d2++;
96
+ else if (tk.value === '}') {
97
+ d2--;
98
+ if (d2 === 0) { scopeEndLine = tk.line; break; }
99
+ }
100
+ }
101
+ }
102
+ }
103
+ const narrowScope = (scopeEndLine - nx.line) <= SCOPE_LINES;
104
+ // 降级而非丢弃(按需求):窄作用域里的短别名**仍要报出来**(聚合结果里能查到位置、
105
+ // 便于人工核对),但带 narrowScope 标记 ⇒ 上游把它降为 notice(不计警告、不影响评分)。
106
+ // 宽作用域仍按 warning 报。
107
+ if (!inForHead) out.push({ line: nx.line, name: nx.value, type: 'variable', narrowScope });
108
+ }
109
+ }
110
+ // ── Python 语法支持(python/variable-min-length 等规则生效)──
111
+ // Python 无 const/let/var/function:函数声明是 `def name(`,变量声明是 `name = 值`。
112
+ // a) def 后的函数名(ident 'def' 下一个非空白 ident 且后跟 '(')
113
+ if (t.type === 'ident' && t.value === 'def') {
114
+ const nx = tokens[i + 1];
115
+ const after = tokens[i + 2];
116
+ if (nx && nx.type === 'ident' && nx.value.length < min && !allowSet.has(nx.value)
117
+ && after && after.type === 'punct' && after.value === '(') {
118
+ out.push({ line: nx.line, name: nx.value, type: 'function' });
119
+ }
120
+ continue;
121
+ }
122
+ // b) `name = ` 变量声明(等号前是短 ident;排除 import/from/def/class/return/
123
+ // for/if/elif/else/while 关键字语境——这些不是「变量声明」;
124
+ // 并排除 const/let/var 前缀——JS 声明已由上方 JS 分支处理,避免二次报)
125
+ if (t.type === 'ident' && t.value.length < min && !allowSet.has(t.value)) {
126
+ const prevT = tokens[i - 1];
127
+ const prev2 = tokens[i - 2];
128
+ const nextT = tokens[i + 1];
129
+ if (nextT && nextT.type === 'punct' && nextT.value === '=') {
130
+ // 排除:import x / from x / return x / for x in / class x / def x / const x =
131
+ // (const/let/var 前缀的 JS 声明由 JS 分支管;这里是 Python 无关键字声明)
132
+ const KW = new Set(['import', 'from', 'return', 'for', 'class', 'def', 'if', 'elif', 'else', 'while', 'in', 'as', 'with', 'lambda', 'del', 'pass', 'not', 'and', 'or', 'global', 'nonlocal', 'yield', 'assert', 'raise', 'is', 'None', 'True', 'False']);
133
+ const prevIsDecl = prevT && prevT.type === 'ident' && ['const', 'let', 'var'].includes(prevT.value);
134
+ const prev2IsDecl = prev2 && prev2.type === 'ident' && ['const', 'let', 'var'].includes(prev2.value);
135
+ if (!KW.has(t.value) && !prevIsDecl && !prev2IsDecl
136
+ && prevT && !(prevT.type === 'punct' && prevT.value === '.')) {
137
+ out.push({ line: t.line, name: t.value, type: 'variable' });
138
+ }
139
+ }
140
+ }
141
+ // ── Java/Kotlin 语法支持(java/variable-min-length 等规则生效)──
142
+ // Java/Kotlin 无 const/let/var/function/def:变量声明是「类型 短名」形态
143
+ // (int x / String s / int[] arr / List<String> list),方法参数、字段、局部变量
144
+ // 都如此。识别:短 ident 后跟 `=` 或 `;` 或 `,` 或 `)`,且前一是「类型段末尾」
145
+ // (ident / `>` 泛型尾 / `]` 数组尾)——即 `类型 短名` 声明形态。
146
+ if (t.type === 'ident' && t.value.length < min && !allowSet.has(t.value)) {
147
+ const prevT = tokens[i - 1];
148
+ const nextT0 = tokens[i + 1];
149
+ const nextT1 = tokens[i + 2];
150
+ // 声明判定:前一是类型段(ident/`>`/`]`),后一可能是 `=`(初始化)、
151
+ // `;`(纯声明)、`,`(多声明/参数)、`)`(参数尾)、`]`(数组长度)
152
+ const prevIsTypeEnd = prevT && (
153
+ prevT.type === 'ident'
154
+ || (prevT.type === 'punct' && (prevT.value === '>' || prevT.value === ']'))
155
+ );
156
+ const nextIsDecl = nextT0 && (
157
+ (nextT0.type === 'punct' && ['=', ';', ',', ')', ']', ':'].includes(nextT0.value))
158
+ || (nextT0.type === 'ident' && nextT1 && nextT1.type === 'punct' && nextT1.value === '=')
159
+ );
160
+ if (prevIsTypeEnd && nextIsDecl && !(prevT.type === 'ident' && prevT.value === 'fun')) {
161
+ // 排除声明/控制流关键字前缀(修复 Java 分支误伤 JS):
162
+ // `const c = 1`(JS)、`val/var x =`(Kotlin)、`return q`、`function`、
163
+ // Python `def`/`import` 后接短名等——prevT 是 ident 但非「类型名」,
164
+ // 前一是这些关键字时是各语言声明/流程语境,不是「类型 短名」声明。
165
+ // 实测误伤:Pawchive test/tools 大量 `const c/h/m = …` 被 Java 分支当
166
+ // Java 变量报短名(内置 min-length 27 条 + ext 部分全为此根因)。
167
+ if (prevT.type === 'ident' && DECL_KEYWORDS.has(prevT.value)) continue;
168
+ out.push({ line: t.line, name: t.value, type: 'variable' });
169
+ }
170
+ }
171
+ // Kotlin 函数声明:fun name( —— name 前的 `fun` 是声明关键字
172
+ if (t.type === 'ident' && t.value === 'fun') {
173
+ const nx = tokens[i + 1];
174
+ const after = tokens[i + 2];
175
+ if (nx && nx.type === 'ident' && nx.value.length < min && !allowSet.has(nx.value)
176
+ && after && after.type === 'punct' && after.value === '(') {
177
+ out.push({ line: nx.line, name: nx.value, type: 'function' });
178
+ }
179
+ continue;
180
+ }
181
+ }
182
+ // 多语言分支可能对同一标识符重复命中(如 Java `int w = 5` 的 w 同时命中
183
+ // 「类型+短名」Java 分支与「短名=」Python 分支)——按行+名+类型去重
184
+ const seen = new Set();
185
+ return out.filter((x) => {
186
+ const k = `${x.line}:${x.name}:${x.type}`;
187
+ if (seen.has(k)) return false;
188
+ seen.add(k);
189
+ return true;
190
+ });
191
+ }
192
+
193
+ /**
194
+ * 检查函数名过短(function-name-too-short kind,AST 级,正则初筛后的精筛)。
195
+ *
196
+ * 与纯正则的差别:正则 `function\s+[A-Za-z_$][\w$]{0,1}\s*\(` 命中即报,会把
197
+ * **i18n 领域标准缩写**(tr = translate、t、L = locale dict)当「无法猜出含义的缩写」
198
+ * 误报。本实现按 token 定位 function 声明后的函数名,长度 ≤ max 且**不在公认缩写
199
+ * 白名单**里才报。
200
+ *
201
+ * @param {string} text 文件全文
202
+ * @param {{max?: number, allow?: string[]}} [opts] max 默认 2;allow 追加白名单
203
+ * @returns {Array<{line:number, name:string}>} 命中列表
204
+ */
205
+ export function checkShortFunctionNameAst(text = '', { max = 2, allow = [] } = {}) {
206
+ const tokens = tokenize(text);
207
+ const out = [];
208
+ // 长度 ≤2 但有公认语义的缩写(不报):i18n 的 tr/t、字典 L、常见工具名
209
+ const ALLOW = new Set(['tr', 't', 'r', 'L', 'i18n', 'db', 'fs', 'os', 'el', 'cb', 'fn', 'ns',
210
+ 'id', 'ok', 'kv', 'ui', 'js', 'ts', 'is', 'to', 'of', 'in', 'no', 'op', 'up', 'un',
211
+ 'i', 'j', 'k', 'x', 'y', 'z', 'e', 'a', 'b', 'n', 'p', 's', 'v', 'f', ...allow]);
212
+ for (let i = 0; i < tokens.length; i++) {
213
+ const t = tokens[i];
214
+ if (!(t.type === 'ident' && t.value === 'function')) continue;
215
+ const nx = tokens[i + 1];
216
+ if (!nx || nx.type !== 'ident') continue;
217
+ if (nx.value.length <= max && !ALLOW.has(nx.value)) out.push({ line: nx.line, name: nx.value });
218
+ }
219
+ return out;
220
+ }
221
+
222
+ /**
223
+ * 判定「全量读入文件」是否属于**受控小文件**读取(memory-bomb 精筛,AST 级)。
224
+ *
225
+ * 规则语义:`fs.readFile` 调用命中即报对「读本地小 JSON 配置/数据」的项目恒定误报。
226
+ * 内存爆炸的真实风险在「读未知大小的大文件」;而读记分数据、标题缓存这类受控小文件
227
+ * (通常紧跟 JSON.parse、或路径变量名含 data/cache/config/locale/store)不构成风险。
228
+ *
229
+ * 判定(满足任一即视为受控小文件读取 → 不报):
230
+ * ① 同一行(或紧邻下一行)出现 JSON.parse —— 读 JSON 数据结构化的标准写法;
231
+ * ② 读取调用前后 6 个 token 内出现小文件语义标识符(data/cache/config/locale/settings/store/state)。
232
+ *
233
+ * @param {string} text 文件全文
234
+ * @returns {Set<number>} 受控小文件读取的行号集合(这些行应从 memory-bomb 命中中剔除)
235
+ */
236
+ export function checkSmallFileReadAst(text = '') {
237
+ const tokens = tokenize(text);
238
+ const out = new Set();
239
+ const SMALL_HINTS = /(data|cache|config|locale|settings|store|state|manifest|package)/i;
240
+ for (let i = 0; i < tokens.length; i++) {
241
+ const t = tokens[i];
242
+ // 找 readFile / readFileSync 调用
243
+ if (!(t.type === 'ident' && /^readFile(Sync)?$/.test(t.value))) continue;
244
+ // 邻近 token 文本(前后各 8 个)作为上下文
245
+ const before = tokens.slice(Math.max(0, i - 8), i).map((x) => x.value).join(' ');
246
+ const after = tokens.slice(i + 1, i + 9).map((x) => x.value).join(' ');
247
+ const ctx = `${before} ${after}`;
248
+ // 行级窗口:读入后常在下一行 JSON.parse(如读取文件后紧跟 migrate(JSON.parse(raw))),
249
+ // token 窗口不够,按源码行扩到 ±3 行。
250
+ const srcLines = String(text).split('\n');
251
+ const lineWindow = srcLines.slice(Math.max(0, t.line - 4), t.line + 3).join(' ');
252
+ // ① 同语句/邻近行里出现 JSON.parse(读 JSON 数据)
253
+ if (/JSON\s*\.\s*parse/.test(ctx) || /JSON\s*\.\s*parse/.test(lineWindow)) { out.add(t.line); continue; }
254
+ // ② 上下文含小文件语义标识符
255
+ if (SMALL_HINTS.test(before) || SMALL_HINTS.test(after) || SMALL_HINTS.test(lineWindow)) { out.add(t.line); continue; }
256
+ // ③ 变量名/参数名为 file/raw 且同语句有 JSON 语义 —— 保守起见不豁免
257
+ }
258
+ return out;
259
+ }
260
+
261
+ /**
262
+ * memory-bomb 的 json-stringify-large 精筛:`console.log(JSON.stringify(大对象))`
263
+ * 是一次性输出模式——CLI `--json` 出口序列化一次立即打印并退出,字符串不会常驻内存,
264
+ * 与「长期运行进程里大对象序列化」的真实风险不同。此类行豁免。
265
+ * @param {string} text 文件全文
266
+ * @returns {Set<number>} 豁免行号集合
267
+ */
268
+ export function checkConsoleLogJsonAst(text = '') {
269
+ const tokens = tokenize(text);
270
+ const out = new Set();
271
+ for (let i = 0; i < tokens.length; i++) {
272
+ const t = tokens[i];
273
+ if (!(t.type === 'ident' && t.value === 'JSON')) continue;
274
+ // JSON 后应跟 .stringify
275
+ const nx = tokens[i + 1];
276
+ if (!nx || nx.type !== 'punct' || nx.value !== '.') continue;
277
+ const nx2 = tokens[i + 2];
278
+ if (!nx2 || nx2.type !== 'ident' || nx2.value !== 'stringify') continue;
279
+ // 行内窗口:JSON.stringify 之前 12 个 token 内是否有 console.log / console.error 输出调用
280
+ const before = tokens.slice(Math.max(0, i - 12), i).map((x) => x.value).join(' ');
281
+ if (/console\s*\.\s*(log|error|warn|info)\s*\(/.test(before)) out.add(t.line);
282
+ }
283
+ return out;
284
+ }