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,378 @@
1
+ /**
2
+ * AST 实现层 · 规模检查
3
+ *
4
+ * 职责:函数长度、文件长度、重复字符串。
5
+ * 函数长度按括号平衡区间统计函数体内语句密度,单行海量语句也能识别。
6
+ */
7
+
8
+ import { tokenize } from './tokenizer.js';
9
+ import { matchBrace } from './brace.js';
10
+ import { javaKtFuncRanges } from './lang.js';
11
+ import { lineStats } from './line-count.js';
12
+
13
+ /** 函数体行数默认阈值:≥ WARN 报 warning,≥ BLOCK 报 blocker。 */
14
+ const FUNC_LINES_WARN = 50;
15
+ const FUNC_LINES_BLOCK = 100;
16
+ /** 从 `function` 关键字向后搜索函数体 `{` 的 token 窗口(覆盖 name(params ) { 形态)。 */
17
+ const FUNC_BODY_LOOKAHEAD_TOKENS = 20;
18
+ /** 行注释密度默认阈值(0~1——行注释占有效代码行比例,超过提示「注释复述代码」)。 */
19
+ const COMMENT_DENSITY_WARN_DEFAULT = 0.4;
20
+
21
+ /**
22
+ * 列出全文所有函数的**精确行范围**(AST 级,tokenizer 括号配对)。
23
+ *
24
+ * 与 checkFuncLinesAst 共用同一套边界算法,区别是:本函数返回**全部**函数(不只超限的),
25
+ * 供上层在此基础上做「语句密度」等派生判定,避免上层再自建第二套边界识别
26
+ * (历史教训:上层曾用正则找起点 + 自己数花括号,未剥离字面量,把 8 行函数算成 242 行 blocker)。
27
+ * @param {string} text 文件全文
28
+ * @returns {Array<{startLine:number, endLine:number, len:number}>} 按出现顺序
29
+ */
30
+ /** 从 function 标记提取函数名:`function NAME(` 直接取;`const f = function(` 向前找声明名;否则 (匿名)。 */
31
+ function funcNameAt(tokens, i) {
32
+ const nx = tokens[i + 1];
33
+ if (nx && nx.type === 'ident') return nx.value;
34
+ if (nx && nx.type === 'punct' && nx.value === '(') {
35
+ // 向前找 const/let/var NAME =
36
+ for (let k = i - 1; k >= Math.max(0, i - 6); k--) {
37
+ const tk = tokens[k];
38
+ if (tk && tk.type === 'ident' && ['const', 'let', 'var'].includes(tk.value)) {
39
+ const nm = tokens[k + 1];
40
+ if (nm && nm.type === 'ident') return nm.value;
41
+ }
42
+ }
43
+ }
44
+ return '(匿名)';
45
+ }
46
+
47
+ /**
48
+ * Python 函数范围收集(行级缩进法)。
49
+ *
50
+ * Python 无 `function` 关键字与大括号——`def name(...):` + 缩进定义函数体。
51
+ * funcRangesAst 的大括号配对法对 Python 完全失效,这里按行扫描:
52
+ * · `def name(...):` 行 = 函数起点
53
+ * · 函数体 = 后续缩进 > def 行缩进的行,直到缩进回到 def 缩进或更浅(或文件尾)
54
+ * · 行内对象/列表推导不产生缩进块,天然正确
55
+ * 返回 [{startLine, endLine, len, name}],与 funcRangesAst 输出结构一致,
56
+ * 由 funcRangesAst 合并(JS + Python 双语言函数范围)。
57
+ * @param {string} text 文件全文
58
+ * @returns {Array<{startLine:number, endLine:number, len:number, name:string}>}
59
+ */
60
+ export function pythonFuncRanges(text = '') {
61
+ const out = [];
62
+ const lines = String(text).split('\n');
63
+ const DEF_RE = /^(\s*)def\s+([A-Za-z_]\w*)\s*\(/;
64
+ for (let i = 0; i < lines.length; i++) {
65
+ const m = DEF_RE.exec(lines[i]);
66
+ if (!m) continue;
67
+ const defIndent = m[1].length;
68
+ const name = m[2];
69
+ // 找函数体结束:后续首个「非空且缩进 <= defIndent」的行是函数外的行;函数体 = 其间行
70
+ let end = i;
71
+ for (let j = i + 1; j < lines.length; j++) {
72
+ const l = lines[j];
73
+ if (!l.trim()) continue; // 空行属于函数体(不结束)
74
+ const indent = (l.match(/^\s*/) || [''])[0].length;
75
+ // 注释行:`#` 顶格或在任何缩进——不算「函数外」,跳过(注释不打断函数体)
76
+ if (/^\s*#/.test(l)) continue;
77
+ if (indent <= defIndent) break;
78
+ end = j;
79
+ }
80
+ out.push({ startLine: i + 1, endLine: end + 1, len: end - i + 1, name });
81
+ i = end; // 跳过函数体,继续找下一个 def
82
+ }
83
+ return out;
84
+ }
85
+
86
+ /**
87
+ * 最大函数长度(行数,跨语言:JS/Python/Java/Kotlin 统一由 funcRangesAst 提供范围)。
88
+ * 供 file-health / max-lines 的「聚合型 vs 臃肿型」判定:最大函数 > 合规阈值 = 臃肿型
89
+ * (文件大是因为藏着大函数,该罚);全部函数合规(含无函数的数据文件)= 聚合型
90
+ * (文件大只是函数多,可接受不按规模扣分)。
91
+ * 注意:纯 JS 文件的 Java/Python 探测零命中,无额外开销(tokenize 有 LRU 缓存)。
92
+ * @param {string} text 文件全文
93
+ * @returns {number} 最大函数行数(无函数返回 0)
94
+ */
95
+ export function maxFunctionLength(text = '') {
96
+ let max = 0;
97
+ for (const r of funcRangesAst(String(text))) {
98
+ if (r.len > max) max = r.len;
99
+ }
100
+ return max;
101
+ }
102
+
103
+ export function funcRangesAst(text = '') {
104
+ const tokens = tokenize(text);
105
+ const out = [];
106
+ // 合并 Python 函数范围(缩进法)——Python 项目函数长度/复杂度/嵌套
107
+ // 规则依赖它(python/max-function-length 等此前对 py 全失效)。
108
+ for (const r of pythonFuncRanges(text)) out.push(r);
109
+ // Java/Kotlin 方法范围(方法签名 + 括号配对)——语言路由:JS 用 function 关键字、
110
+ // Python 按 def+缩进、Java/Kotlin 无声明关键字,只能靠「方法签名 + 括号配对」判定——
111
+ // Java/Kotlin 无 function 关键字,JS 大括号法零命中 → 由 lang.js 的
112
+ // javaKtFuncRanges 补充(轻量内容探测,纯 JS 项目不受影响)。
113
+ for (const r of javaKtFuncRanges(text)) {
114
+ // 与 JS 分支结果去重(极端混合文件里同名起点的保守处理)
115
+ if (!out.some((o) => o.startLine === r.startLine)) out.push(r);
116
+ }
117
+ for (let i = 0; i < tokens.length; i++) {
118
+ const t = tokens[i];
119
+ if (t.type !== 'ident' || t.value !== 'function') continue;
120
+ let openIdx = -1;
121
+ for (let j = i + 1; j < Math.min(tokens.length, i + FUNC_BODY_LOOKAHEAD_TOKENS); j++) {
122
+ const tj = tokens[j];
123
+ if (tj.type === 'punct' && tj.value === '{') { openIdx = j; break; }
124
+ if (tj.type === 'punct' && tj.value === ';') break;
125
+ }
126
+ if (openIdx === -1) continue;
127
+ const range = matchBrace(tokens, openIdx);
128
+ if (!range) continue;
129
+ const startLine = tokens[openIdx].line;
130
+ const endLine = tokens[range[1]].line;
131
+ out.push({ startLine, endLine, len: endLine - startLine + 1, name: funcNameAt(tokens, i) });
132
+ i = range[1];
133
+ }
134
+ return out;
135
+ }
136
+
137
+ /**
138
+ * 统计指定行范围内的注释行数(多项检查共用:函数长度/文件长度的「非注释部分」口径)。
139
+ * 与 countCommentLines 同思路(comment token 按物理行去重、跨行块注释逐行覆盖),
140
+ * 但限定在 [startLine, endLine] 闭区间内。
141
+ * @param {Array} tokens tokenize 输出
142
+ * @param {number} startLine 起始物理行(含)
143
+ * @param {number} endLine 结束物理行(含)
144
+ * @returns {number} 范围内注释行数
145
+ */
146
+ export function countCommentLinesInRange(tokens, startLine = 1, endLine = Infinity) {
147
+ const commentLines = new Set();
148
+ for (const t of tokens) {
149
+ if (t.type !== 'comment') continue;
150
+ const start = Number(t.line) || 1;
151
+ if (start < startLine || start > endLine) continue;
152
+ commentLines.add(start);
153
+ const newlines = String(t.value || '').match(/\n/g)?.length || 0;
154
+ for (let i = 1; i <= newlines; i++) {
155
+ if (start + i <= endLine) commentLines.add(start + i);
156
+ }
157
+ }
158
+ return commentLines.size;
159
+ }
160
+
161
+ /**
162
+ * 检查单函数超长(AST 级:括号平衡精确统计函数体行数)。
163
+ * 判定按**非注释部分**(codeLen = 总行数 − 范围内注释行),
164
+ * 注释/文档行不占「代码规模」预算;总行数仍随返回供展示。
165
+ * @param {string} text 文件全文
166
+ * @param {{warn?: number, block?: number}} [opts]
167
+ * @returns {Array<{line:number, len:number, codeLen:number, commentLines:number, level:'warning'|'blocker'}>}
168
+ */
169
+ export function checkFuncLinesAst(text = '', { warn = FUNC_LINES_WARN, block = FUNC_LINES_BLOCK } = {}) {
170
+ const tokens = tokenize(text);
171
+ const out = [];
172
+ // 统一走 funcRangesAst(JS 大括号 + Python 缩进双语言函数范围)——
173
+ // 旧内联扫描只认 `function`+`{`,Python def 函数长度规则(python/max-function-length)
174
+ // 对 py 文件全失效。funcRangesAst 已合并 pythonFuncRanges。
175
+ for (const r of funcRangesAst(text)) {
176
+ const startLine = r.startLine;
177
+ const endLine = r.endLine;
178
+ const len = endLine - startLine + 1;
179
+ const commentLines = countCommentLinesInRange(tokens, startLine, endLine);
180
+ const codeLen = Math.max(1, len - commentLines);
181
+ if (codeLen > warn) {
182
+ out.push({ line: startLine, name: r.name || '(匿名)', len, codeLen, commentLines, level: codeLen > block ? 'blocker' : 'warning' });
183
+ }
184
+ }
185
+ return out;
186
+ }
187
+
188
+ /** 语句密度门槛(条/行):低于此值说明语句正常铺开分布,不算「单行海量语句」。 */
189
+ const STMT_DENSITY_MIN = 3;
190
+
191
+ /**
192
+ * 检查「单行/极少行堆叠海量语句」(AST 级,tokenizer 计数)。
193
+ *
194
+ * 为什么独立于行数判定:`function f() { a++; a++; … ×200 }` 挤在**一行**,行数=1 永远
195
+ * 超不过 50 行阈值,只能按**语句密度**(语句数 ÷ 函数体行数)识别。
196
+ *
197
+ * 为什么不与行数判定重复报:两处都基于同一份 AST 函数范围;本函数跳过「已被行数判定报出」
198
+ * 的函数(见 `reportedByLines`),避免同一函数在同一规则下产生两条 finding。
199
+ *
200
+ * 历史(误报):旧实现在 `lib/checks/` 层用正则找起点、自己数花括号、无条件套用
201
+ * 语句总数阈值 → 把 DSH 客户端 bundle 的单入口工厂 `factory: (require) => { … }`(整个
202
+ * 插件体都在这个箭头函数里,横跨上千行、语句数自然过百,密度却不到 1)误报为 blocker。
203
+ * 现加密度门槛,并把全部字符级操作收敛到 AST 层(tokenizer 计数,不经正则)。
204
+ *
205
+ * @param {string} text 文件全文
206
+ * @param {{threshold?: number, blockThreshold?: number, skipLines?: Set<number>}} [opts]
207
+ * skipLines:已被行数判定报出的函数起始行,不再重复报
208
+ * @returns {Array<{line:number, stmtCount:number, bodyLines:number, density:number, level:'warning'|'blocker'}>}
209
+ */
210
+ export function checkFuncDensityAst(text = '', { threshold = FUNC_LINES_WARN, blockThreshold = FUNC_LINES_BLOCK, skipLines = new Set() } = {}) {
211
+ const tokens = tokenize(String(text));
212
+ const out = [];
213
+ for (const r of funcRangesAst(text)) {
214
+ if (skipLines.has(r.startLine)) continue;
215
+ const bodyLines = Math.max(1, r.len);
216
+ // 语句数 = 该函数行范围内的分号 token 数(tokenizer 已剥离字符串/正则/注释内的分号)
217
+ let stmtCount = 0;
218
+ for (const t of tokens) {
219
+ if (t.type !== 'punct' || t.value !== ';') continue;
220
+ if (t.line >= r.startLine && t.line <= r.endLine) stmtCount += 1;
221
+ }
222
+ const density = stmtCount / bodyLines;
223
+ if (stmtCount > threshold && density > STMT_DENSITY_MIN) {
224
+ out.push({
225
+ line: r.startLine, stmtCount, bodyLines, density,
226
+ level: stmtCount > blockThreshold ? 'blocker' : 'warning',
227
+ });
228
+ }
229
+ }
230
+ return out;
231
+ }
232
+
233
+ /**
234
+ * 统计注释行数(注释行单独算):基于 tokenizer 的 comment token,
235
+ * 对跨行块注释按换行拆分后按「物理行号去重」计注释行数。
236
+ * @param {string} text 文件全文
237
+ * @returns {number} 注释行数(0 = 无注释/无法解析)
238
+ */
239
+ export function countCommentLines(text = '') {
240
+ const tokens = tokenize(String(text));
241
+ const commentLines = new Set();
242
+ for (const t of tokens) {
243
+ if (t.type !== 'comment') continue;
244
+ const v = String(t.value || '');
245
+ const start = Number(t.line) || 1;
246
+ commentLines.add(start);
247
+ // 跨行块注释:从起始行起按换行推进,覆盖到的每行都算注释行
248
+ const newlines = v.match(/\n/g)?.length || 0;
249
+ for (let i = 1; i <= newlines; i++) commentLines.add(start + i);
250
+ }
251
+ return commentLines.size;
252
+ }
253
+
254
+ /**
255
+ * 检查文件行数(max-lines kind)。
256
+ * 判定默认按**非注释部分**(codeLines = 总行数 − 注释行数),
257
+ * 注释/文档行不占文件规模预算;总行数/注释行数仍随返回供展示。
258
+ * @param {string} text 文件全文
259
+ * @param {object} [opts] { warn=500, block=1000, excludeComments=true }
260
+ * excludeComments=false 时回退旧口径(按总行数判定)。
261
+ * @returns {{lines:number, codeLines:number, commentLines:number, level:string|null}}
262
+ */
263
+ export function checkFileLines(text = '', { warn = 500, block = 1000, excludeComments = true } = {}) {
264
+ // 行数口径走**单一来源** lib/ast/line-count.js(代码行 = 总行 − 纯注释行 − 空行)——
265
+ // 此前只减注释行、**漏减空行**,同一文件在 file-health 与 max-file-length 两条规则里行数对不上。
266
+ const stats = lineStats(text);
267
+ const lines = stats.total;
268
+ const commentLines = stats.comment;
269
+ const codeLines = excludeComments ? stats.code : lines;
270
+ if (codeLines <= warn) return { lines, codeLines, commentLines, level: null };
271
+ return { lines, codeLines, commentLines, level: codeLines > block ? 'blocker' : 'warning' };
272
+ }
273
+
274
+ /**
275
+ * 注释冗余检测(评审规则①)。
276
+ *
277
+ * 语义:**变量即注释**——语义明确的代码里变量名已表达内容,额外的行注释并不加深
278
+ * 理解;应只保留具有隐性约束、复杂设计、外部契约、非显然决策的块注释,同时减少
279
+ * 行注释。注释应解释「为什么」而非复述「做了什么」。
280
+ *
281
+ * 判据(保守,防误伤合理注释):
282
+ * · 统计**行注释**行数(独立 `//` / `#` 行,非行尾注释)÷ 有效代码行数;
283
+ * · 行注释密度 > 阈值(默认 0.4,即行注释占代码行 40% 以上)→ 提示
284
+ * 「行注释过多,可能复述代码」;
285
+ * · **块注释**(斜杠星号文档注释、Python docstring)不计入——那是设计说明,
286
+ * 评审要求保留;
287
+ * · 连续注释块(≥3 行同属一个逻辑说明)不触发——大段注释往往是设计文档;
288
+ * · 只提示(warning),不拦截。
289
+ *
290
+ * @param {string} text 文件全文
291
+ * @param {{warn?:number}} [opts] warn=行注释密度阈值(0~1)
292
+ * @returns {Array<{line:number, commentLines:number, codeLines:number, ratio:number}>}
293
+ */
294
+ export function checkCommentDensityAst(text = '', { warn = COMMENT_DENSITY_WARN_DEFAULT, minCodeLines = 5 } = {}) {
295
+ const lines = String(text).split('\n');
296
+ let commentLines = 0;
297
+ let codeLines = 0;
298
+ let inBlockComment = false;
299
+ const hits = [];
300
+ for (let i = 0; i < lines.length; i++) {
301
+ const raw = lines[i];
302
+ const line = raw.trim();
303
+ // 跨行块注释(/* ... */ 未闭合)
304
+ if (inBlockComment) {
305
+ if (line.includes('*/')) inBlockComment = false;
306
+ continue; // 块注释不计入行注释密度
307
+ }
308
+ if (line.startsWith('/*')) { if (!line.includes('*/')) inBlockComment = true; continue; }
309
+ // 文档注释 `/** */` 单行、`///` 也算块/文档注释不计(设计说明保留)
310
+ if (/^\/\*\*/.test(line) || /^\/\/\//.test(line)) continue;
311
+ // 行注释(// 或 # 开头;# 排除 shebang)——**行注释无论是否连续都计入**:
312
+ // 修:评审要求是「减少行注释、保留块注释」——连续行注释是
313
+ // 复述代码的高发区(每行注释对应一行简单语句),不是设计说明,count 不豁免。
314
+ if (/^(\/\/|#)/.test(line) && !/^#!/.test(line)) {
315
+ commentLines++;
316
+ } else if (line) {
317
+ // 代码行(非空、非注释)
318
+ codeLines++;
319
+ }
320
+ }
321
+ // 短文件(代码行 < minCodeLines)不判定:文件头说明/简述占比天然高且篇幅小,
322
+ // 「注释复述代码」是长文件信号(行注释随代码量线性堆积时才该提示)。
323
+ if (codeLines < minCodeLines) return [];
324
+ const ratio = commentLines / codeLines;
325
+ if (ratio > warn) {
326
+ hits.push({ line: 1, commentLines, codeLines, ratio });
327
+ }
328
+ return hits;
329
+ }
330
+
331
+ /**
332
+ * 检查重复出现的硬编码字符串/模板串(repeated-string / min-occurrences kind)。
333
+ * 数值字面量(num)不参与统计——版本号/端口/阈值等数字重复属正常,
334
+ * 按「硬编码文本」报会造成大面积噪音(如 README 里的 10/15)。
335
+ * @param {string} text 文件全文
336
+ * @param {object} [opts] { min=3, ignore=['', ' ', '\\n', '-', '/', '0', '1'] }
337
+ * @returns {Array<{line:number, value:string, count:number}>}
338
+ */
339
+ export function checkRepeatedStringsAst(text = '', { min = 3, ignore = [] } = {}) {
340
+ const tokens = tokenize(text);
341
+ // tokenizer 产出的字面量类型名是 str / tmpl / num(非 string/number);
342
+ // 类型名不匹配会让本检查永不命中,故按实际类型名收集;num 刻意排除(见上)
343
+ const LITERAL_TYPES = new Set(['str', 'tmpl']);
344
+ const ignoreSet = new Set(['', ' ', '\n', '-', '/', '0', '1', 'utf8', 'string', 'number', 'boolean', 'object', 'function', ...ignore]);
345
+ const counts = new Map();
346
+ for (const t of tokens) {
347
+ if (!LITERAL_TYPES.has(t.type)) continue;
348
+ // 去掉字面量外层引号('' "" ``),计数与展示都用裸值
349
+ const v = String(t.value).replace(/^(['"`])([\s\S]*)\1$/, '$2');
350
+ if (ignoreSet.has(v) || v.length < 4) continue;
351
+ // ① 纯标识符形状(含下划线):kind 名/分派词(credential-ref、code_audit 等),重复属正常
352
+ if (/^[a-z0-9][a-z0-9_-]{0,19}$/i.test(v)) continue;
353
+ // ①b dotfile 名(.git/.dsh/.env 等):路径/目录域名词汇,重复属正常
354
+ if (/^\.[a-z0-9_-]{1,16}$/i.test(v)) continue;
355
+ // ①c i18n 键/配置键(common.cancel / menu.save_as / zh-CN.foo / api.retry_times /
356
+ // downloader.files_netloc):点分小写链是字典/配置引用键(多处引用同一键是正常
357
+ // 用法,不是「应配置化的硬编码值」——键本身就是配置)。允许 snake_case 段
358
+ // (Python 配置键惯例, 二次修:下划线段 files_netloc 此前漏豁免)。
359
+ // 判据:全小写 + 点分 2~4 段 + 每段 [a-z][a-z0-9_]*(允许下划线)+ 段可含连字符;
360
+ // 排除域名特征——末段是域名后缀(com/net/org/io 等)或含 example/test/localhost
361
+ // 段的是真实业务/URL。`api.scheme`(配置字段名)算配置键豁免。
362
+ if (/^[a-z][a-z0-9_-]*(\.[a-z][a-z0-9_-]*){1,3}$/.test(v)
363
+ && !/\.(com|net|org|io|dev|cn|co|example|test|localhost)$/.test(v)
364
+ && !/(^|\.)(example|test|localhost|your|demo)\./.test(v)) continue;
365
+ // ①d 路由/端点路径(/naming /session /api/foo):路径段是小写词(含连字符),
366
+ // 重复是「多处引用同一路由常量」的正常形态(路由表/链接/匹配共用),非硬编码值。
367
+ // 排除含 `..`/空白/大写的真实路径与查询串(?a=b 是数据不是路由名)。
368
+ if (/^\/[a-z0-9][a-z0-9/_-]*$/.test(v) && !v.includes('..') && !/[\s?]/.test(v)) continue;
369
+ // ② 短期望词(2-4 个汉字):可读性/可维护性/安全性 等维度名,重复属正常
370
+ if (/^[\u4e00-\u9fff]{2,4}$/.test(v)) continue;
371
+ // ③ 无值型特征(不含 ./:\ 空格/CJK)的短串:\n、-c、-q、[FUNC] 属控制串/标志,不报
372
+ // 值型特征 = 含 路径分隔/点/冒号/反斜杠/空白/CJK —— 才像"硬编码值"
373
+ if (!/[\s./:\\\u4e00-\u9fff]/.test(v)) continue;
374
+ if (!counts.has(v)) counts.set(v, { value: v, count: 0, line: t.line });
375
+ counts.get(v).count++;
376
+ }
377
+ return [...counts.values()].filter((x) => x.count >= min);
378
+ }