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,314 @@
1
+ /**
2
+ * dsh-git-push — I/O 风险分级(AST 层,)
3
+ *
4
+ * 职责:找出文件里的全部 fs 调用(同步 + 异步),判定每个调用的上下文
5
+ * (异步路径 / 循环内 / 请求处理路径 / 启动路径)与操作类别(读 / 写 / 删 / 改名),
6
+ * 据此给出四级风险,供审计 findings 与 scripts/scan-file-io.mjs 共用。
7
+ *
8
+ * 分层约定(README「正则初筛 → AST 精筛」):本文件属 `lib/ast/` 实现层,
9
+ * 只把判定结果交出去;调用方(lib/checks/)只做「转 finding / 转报表」。
10
+ *
11
+ * 四级风险(写类操作加权一档;循环内 I/O 改多维分级,不再一刀切 high):
12
+ * high —— 异步路径中的同步 I/O;或循环内「同步阻塞 + 边界不可控」落在请求路径;
13
+ * 或请求路径上循环内逐个 await(响应时间线性增长)
14
+ * medium —— 请求处理路径上的 I/O;循环内同步 I/O(阻塞事件循环,边界不可控但非关键路径)
15
+ * low —— 启动路径上的同步 I/O(模块顶层 / apply() 等一次性初始化);
16
+ * 循环内异步串行 await(只慢不阻塞);固定小数组循环内的 I/O;
17
+ * 循环内异步 I/O 已 Promise.all 并行
18
+ * safe —— 异步 + 无循环 + 非关键路径
19
+ *
20
+ * 模块划分(原单文件按职责拆分,对外出口不变):
21
+ * io-risk-const.js —— 常量与档位工具
22
+ * io-risk-fn.js —— 函数边界识别与 token 配对
23
+ * io-risk-loop.js —— 循环判定
24
+ * 本文件 —— 判定与评分,并再导出上述模块的公共符号
25
+ */
26
+ import { tokenize } from './tokenizer.js';
27
+ import {
28
+ LOOP_KEYWORDS, LOOP_METHODS, RISK_BADGE, RISK_LABEL,
29
+ SYNC_FS_FNS, ASYNC_FS_FNS, KIND_BY_FN, REQUEST_PATTERNS, LEVELS, raise, META_FS_FNS,
30
+ } from './io-risk-const.js';
31
+ import { buildCallGraph, isInRequestPath } from './callgraph.js';
32
+ import { collectRanges } from './io-risk-loop.js';
33
+ import { enclosingLoop } from './io-risk-fn.js';
34
+ import { isSmallFixedLoop } from './io-risk-loop.js';
35
+
36
+
37
+ /**
38
+ * 扫描文件内全部 fs 调用并分级。
39
+ *
40
+ * @param {string} text 文件全文
41
+ * @returns {Array<{
42
+ * line:number, call:string, via:string, type:'sync'|'async', kind:'read'|'write'|'delete'|'rename',
43
+ * inAsync:boolean, inLoop:boolean, inRequest:boolean, inStartup:boolean,
44
+ * risk:'high'|'medium'|'low'|'safe', reason:string
45
+ * }>}
46
+ */
47
+ /** 模块顶层/初始化的判定常量(魔数具名化,说明取值理由)。 */
48
+
49
+ /**
50
+ * 判断 token 位置是否是一个真实的 fs 调用。
51
+ * 三个条件:① 标识符是已知 fs 函数名 ② 后一个 token 是 '('(调用形态)
52
+ * ③ 同步/异步归类。拆自 judgeIoTokend(原函数圈复杂度 12,超阈值 10)。
53
+ * @returns {{token: object, isSync: boolean}|null}
54
+ */
55
+ function classifyIoCall(tokens, idx) {
56
+ const t = tokens[idx];
57
+ if (t.type !== 'ident') return null;
58
+ const isSync = SYNC_FS_FNS.has(t.value);
59
+ const isAsync = !isSync && ASYNC_FS_FNS.has(t.value);
60
+ if (!isSync && !isAsync) return null;
61
+ // 必须是调用形态:名字后紧跟 '('(允许 fs.promises.readFile 的点号形态)
62
+ const next = tokens[idx + 1];
63
+ if (!next || next.type !== 'punct' || next.value !== '(') return null;
64
+ return { token: t, isSync };
65
+ }
66
+
67
+ /**
68
+ * 判定单条 I/O token 的上下文与风险等级。
69
+ * 从 scanIoRiskAst 抽出(原函数圈复杂度 27 / 嵌套 4,超阈值),
70
+ * 使主循环只负责遍历与筛形,判定逻辑可独立测试。
71
+ *
72
+ * @param {object} ctx { tokens, lines, idx, asyncFns, loops, within, enclosingFnText }
73
+ * @returns {object|null} 命中项;非 I/O 调用返回 null
74
+ */
75
+ function judgeIoTokend(ctx) {
76
+ const { tokens, lines, idx, asyncFns, loops, within, enclosingFnText, enclosingFnName, promiseAllRanges, callGraph } = ctx;
77
+ const callKind = classifyIoCall(tokens, idx);
78
+ if (!callKind) return null;
79
+ const { token: t, isSync } = callKind;
80
+
81
+ const line = t.line;
82
+ const inAsync = within(asyncFns, line);
83
+ const loopHit = enclosingLoop(loops, line);
84
+ // 迭代器表达式内的 I/O 只执行一次(进入循环前),不算「循环内」:
85
+ // `for (const line of readFileSync(f).split('\n'))` —— readFileSync 在头部括号内。
86
+ // 同行代码无法靠行号区分,故按 token 下标判定。
87
+ const inLoopHead = Boolean(loopHit && loopHit[3] && idx > loopHit[3][0] && idx < loopHit[3][1]);
88
+ const inLoop = Boolean(loopHit) && !inLoopHead;
89
+ // 只遍历固定小字面量数组的循环:I/O 次数确定且极少,不按「逐次阻塞放大耗时」计
90
+ const inSmallFixedLoop = Boolean(loopHit && loopHit[2]);
91
+ // Promise.all(...) 表达式内的 I/O = 并行执行(不串行放大),
92
+ // 循环内逐次 await 才是串行放大;并行形态降级为可接受
93
+ const inParallelAll = Boolean(promiseAllRanges && promiseAllRanges.some(([s, e]) => idx > s && idx < e));
94
+ // P3:请求路径判定升级——函数体内 HTTP 特征(detectRequestContext)
95
+ // 或「被请求路径函数调用」(调用链 isInRequestPath)——修「请求处理调用的公共函数漏报」
96
+ const inRequest = detectRequestContext(lines, enclosingFnText(line))
97
+ || (callGraph && enclosingFnName(line) ? isInRequestPath(enclosingFnName(line), callGraph) : false);
98
+ const inStartup = !inAsync && !inLoop && !inRequest;
99
+ const type = isSync ? 'sync' : 'async';
100
+ const kind = META_FS_FNS.has(t.value) ? 'meta' : (KIND_BY_FN[t.value] || 'read'); // 元数据/查询/幂等目录操作独立档
101
+
102
+ const { risk, reason } = gradeRisk({ isSync, inAsync, inLoop, inSmallFixedLoop, inRequest, inParallelAll, kind });
103
+ return { line, call: t.value, via: '', type, kind, inAsync, inLoop, inRequest, inStartup, risk, reason };
104
+ }
105
+
106
+ /** 请求路径判定:所在函数体内出现 HTTP 特征即算(文本回溯,回溯上限见常量)。 */
107
+ function detectRequestContext(lines, fnRange) {
108
+ if (!fnRange) return false;
109
+ const from = Math.max(0, fnRange[0] - 1);
110
+ const body = lines.slice(from, fnRange[1]).join('\n');
111
+ return REQUEST_PATTERNS.some((re) => re.test(body));
112
+ }
113
+
114
+ /**
115
+ * 四级判定:上下文 + 操作类别。
116
+ * 基础档由上下文决定,写/删/改名再按「数据不可逆」加权一档。
117
+ * 循环内 I/O 多维分级(不再一刀切 high):
118
+ * 风险不取决于「在不在循环里」,而取决于「循环次数可不可控 + I/O 同不同步 +
119
+ * 在不在请求路径上」——三者同时满足才是真正高风险;只满足一个或两个降级为提醒。
120
+ * 同步阻塞 + 边界不可控:medium(非关键路径)/ high(请求路径)
121
+ * 异步串行 await:low(只慢不阻塞)/ high(请求路径,响应时间线性增长)
122
+ * 异步并行(Promise.all):low(可接受)
123
+ * @returns {{risk: string, reason: string}}
124
+ */
125
+ function gradeRisk({ isSync, inAsync, inLoop, inSmallFixedLoop, inRequest, inParallelAll, kind }) {
126
+ let risk = 'safe';
127
+ let reason = '异步 + 无循环 + 非关键路径';
128
+ // 「会重复执行」= 循环内(逐次执行)或请求路径(每次请求执行一次)。
129
+ // 只有这类上下文才存在「反复 + 不可逆」的叠加;异步路径的同步 I/O 本身已是最高档,
130
+ // 且它的风险来自「阻塞事件循环」而非重复,不参与加权。
131
+ const repeated = (inLoop && !inSmallFixedLoop) || inRequest;
132
+ if (isSync && inAsync) { risk = 'high'; reason = '异步路径中的同步 I/O(阻塞事件循环)'; }
133
+ else if (inLoop && inSmallFixedLoop) { risk = 'low'; reason = '固定小数组循环内的 I/O(次数确定且极少,开销可忽略)'; }
134
+ else if (inLoop && isSync) {
135
+ // 循环内同步 I/O(边界不可控,已排除 smallFixed):阻塞事件循环;
136
+ // 落在请求路径再升一档(不可控 + 同步 + 关键路径三条件齐)
137
+ risk = inRequest ? 'high' : 'medium';
138
+ reason = inRequest
139
+ ? '请求路径上循环内同步 I/O(阻塞事件循环 + 次数不可控,逐次放大)'
140
+ : '循环内同步 I/O(阻塞事件循环;边界不可控时逐次放大耗时)';
141
+ }
142
+ else if (inLoop && inParallelAll) { risk = 'low'; reason = '循环内异步 I/O 已 Promise.all 并行(不串行放大)'; }
143
+ else if (inLoop && inRequest) { risk = 'high'; reason = '请求处理路径上循环内逐个 await I/O(响应时间线性增长)'; }
144
+ else if (inLoop) { risk = 'low'; reason = '循环内异步 I/O(串行 await 只慢不阻塞事件循环)'; }
145
+ // (io-risk 优化,对照诊断「97% 误报」):请求路径上的**元数据/查询/幂等目录操作**
146
+ // (existsSync/statSync/readdirSync/mkdir(recursive)/rmdir…)单文件微秒级、不搬运数据内容,
147
+ // 不构成请求路径阻塞 → 降 low(不再按「请求路径 I/O」一律 medium)。
148
+ // 注意:循环内的 meta 已被上方循环分级接管(循环内逐次 stat 累积按循环规则判),不受本档豁免。
149
+ else if (inRequest && kind === 'meta') { risk = 'low'; reason = '请求处理路径上的元数据/查询/幂等目录操作(单文件微秒级,无数据内容搬运)'; }
150
+ else if (inRequest) { risk = 'medium'; reason = '请求处理路径上的 I/O'; }
151
+ else if (isSync) { risk = 'low'; reason = '启动路径上的同步 I/O(一次性初始化)'; }
152
+
153
+ // 写/删加权一档(数据不可逆)——**仅当该次 I/O 会重复执行时**。
154
+ // 加权要表达的是「反复执行 + 不可逆」的叠加风险:循环内逐次写盘、请求路径并发写。
155
+ // 启动路径的一次性落盘(含 `.tmp` + rename 的标准原子写)执行一次即结束,
156
+ // 不存在重复放大;对它加权会把这套**正确做法**报成「中风险」,
157
+ // 实测 25 条 atomic-json/account-status/scan-repos 等原子写全被误升档。
158
+ // rename 同卷改名 = 元数据级(非数据内容搬运,DELETE 移 .trash 等)→ 不再参与加权。
159
+ if (repeated && (kind === 'write' || kind === 'delete')) {
160
+ const raised = raise(risk, 1);
161
+ if (raised !== risk) { reason += `;${kind} 类操作加权`; risk = raised; }
162
+ }
163
+ return { risk, reason };
164
+ }
165
+
166
+ /** 从 openIdx(应为 `(`)起配对最近的闭合括号,返回闭括号 token 下标(无配对返回 -1)。 */
167
+ function findMatchingClose(tokens, openIdx) {
168
+ let depth = 0;
169
+ for (let j = openIdx; j < tokens.length; j++) {
170
+ if (tokens[j].type === 'punct' && tokens[j].value === '(') depth++;
171
+ else if (tokens[j].type === 'punct' && tokens[j].value === ')') {
172
+ depth--;
173
+ if (depth === 0) return j;
174
+ }
175
+ }
176
+ return -1;
177
+ }
178
+
179
+ /**
180
+ * Promise.all(...) 表达式的 token 区间。
181
+ * 循环内 I/O 若落在 Promise.all 参数里 = 并行执行(不串行放大)→ 降级可接受。
182
+ * 判定依据:`Promise` `.` `all` `(` 四连 token,配对其括号区间 [开, 闭]。
183
+ * @param {Array} tokens tokenize 产物
184
+ * @returns {Array<[number, number]>} token 下标区间(含开闭括号)
185
+ */
186
+ function findPromiseAllRanges(tokens) {
187
+ const ranges = [];
188
+ for (let i = 0; i < tokens.length - 3; i++) {
189
+ const a = tokens[i], b = tokens[i + 1], c = tokens[i + 2], d = tokens[i + 3];
190
+ const isPromiseAll = a.type === 'ident' && a.value === 'Promise'
191
+ && b.type === 'punct' && b.value === '.'
192
+ && c.type === 'ident' && c.value === 'all'
193
+ && d.type === 'punct' && d.value === '(';
194
+ if (!isPromiseAll) continue;
195
+ const close = findMatchingClose(tokens, i + 3);
196
+ if (close > i + 3) ranges.push([i + 3, close]);
197
+ }
198
+ return ranges;
199
+ }
200
+
201
+ /**
202
+ * 扫描源码里的文件 I/O,按上下文与操作类别给出四级风险。
203
+ * @param {string} text 源码全文
204
+ * @returns {Array<object>} 命中项数组(见文件头字段说明)
205
+ */
206
+ export function scanIoRiskAst(text = '') {
207
+ const src = String(text);
208
+ const tokens = tokenize(src);
209
+ const { asyncFns, allFns, loops } = collectRanges(tokens);
210
+ const callGraph = buildCallGraph(src); // P3:单文件调用链——被请求路径函数调用的函数也判请求路径(修漏报)
211
+ const promiseAllRanges = findPromiseAllRanges(tokens);
212
+ const lines = src.split('\n');
213
+ const out = [];
214
+
215
+ const within = (ranges, line) => ranges.some(([s, e]) => line >= s && line <= e);
216
+ /**
217
+ * 取最近函数体范围(含区间嵌套时取最内层,用于请求路径特征匹配)。
218
+ * 必须用 allFns(含同步函数/箭头函数/方法简写)—— 请求路径判定看的是
219
+ * 「这段函数体里有没有 HTTP 特征」,与函数是否 async 无关。
220
+ * 早先误用 asyncFns,导致同步 handler(`function h(req,res){ res.end() }`)
221
+ * 识别不到请求上下文,其中的 I/O 被降格成「启动路径一次性」→ 低估风险。
222
+ */
223
+ const enclosingFnText = (line) => {
224
+ let best = null;
225
+ for (const [s, e] of allFns) if (line >= s && line <= e) best = [s, e];
226
+ return best;
227
+ };
228
+
229
+ const fnNameAt = (line) => {
230
+ let best = null;
231
+ for (const [sf, ef] of allFns) if (line >= sf && line <= ef) { best = [sf, ef]; break; }
232
+ if (!best) return '';
233
+ const head = src.split('\n')[best[0] - 1] || '';
234
+ const match = head.match(/(?:function\s+)?([A-Za-z_$][\w$]*)\s*(?:=\s*)?(?:\(|=>)/);
235
+ return match ? match[1] : '';
236
+ };
237
+ const ctx = { tokens, lines, asyncFns, loops, within, enclosingFnText, enclosingFnName: fnNameAt, promiseAllRanges, callGraph };
238
+ for (let i = 0; i < tokens.length; i++) {
239
+ const hit = judgeIoTokend({ ...ctx, idx: i });
240
+ if (!hit) continue;
241
+ out.push(hit);
242
+ i += 1;
243
+ }
244
+ return out;
245
+ }
246
+
247
+ /**
248
+ * 统计 I/O 分布(供报表与审计摘要用)。
249
+ * @param {Array} hits scanIoRiskAst 的结果
250
+ * @returns {{total:number, sync:number, async:number, syncRatio:number, byRisk:object, byKind:object, byFile:Array}}
251
+ */
252
+ export function summarizeIoRisk(hits = []) {
253
+ const list = Array.isArray(hits) ? hits : [];
254
+ const sync = list.filter((h) => h.type === 'sync').length;
255
+ const byRisk = { high: 0, medium: 0, low: 0, safe: 0 };
256
+ const byKind = { read: 0, write: 0, delete: 0, rename: 0 };
257
+ const fileMap = new Map();
258
+ for (const hit of list) {
259
+ byRisk[hit.risk] = (byRisk[hit.risk] || 0) + 1;
260
+ byKind[hit.kind] = (byKind[hit.kind] || 0) + 1;
261
+ if (hit.file) fileMap.set(hit.file, (fileMap.get(hit.file) || 0) + 1);
262
+ }
263
+ const byFile = [...fileMap.entries()]
264
+ .map(([file, count]) => ({ file, count }))
265
+ .sort((a, b) => b.count - a.count || a.file.localeCompare(b.file));
266
+ return {
267
+ total: list.length,
268
+ sync,
269
+ async: list.length - sync,
270
+ syncRatio: list.length ? sync / list.length : 0,
271
+ byRisk, byKind, byFile,
272
+ };
273
+ }
274
+
275
+ /**
276
+ * 生成改造优先级清单:按风险级别排序(同级内写/删优先、同步优先)。
277
+ * @param {Array} hits 每条需带 file 字段
278
+ * @returns {Array} 排序后的清单(含 rank 序号)
279
+ */
280
+ export function rankIoFixList(hits = []) {
281
+ const list = Array.isArray(hits) ? hits : [];
282
+ const sorted = [...list].sort(compareFixPriority);
283
+ return sorted.map((hit, idx) => ({ ...hit, rank: idx + 1 }));
284
+ }
285
+
286
+ /**
287
+ * 改造优先级排序:风险 > 写类 > 同步 > 文件 > 行号。
288
+ * 从 rankIoFixList 的比较器抽出(原为内联多级比较,变量名过短且难读)。
289
+ * @returns {number} 负数 = a 优先
290
+ */
291
+ function compareFixPriority(a, b) {
292
+ const byRisk = LEVELS.indexOf(b.risk) - LEVELS.indexOf(a.risk);
293
+ if (byRisk) return byRisk;
294
+ const byKind = isWriteLike(b.kind) - isWriteLike(a.kind);
295
+ if (byKind) return byKind;
296
+ const byType = isSync(b.type) - isSync(a.type);
297
+ if (byType) return byType;
298
+ const byFile = String(a.file || '').localeCompare(String(b.file || ''));
299
+ if (byFile) return byFile;
300
+ return (a.line || 0) - (b.line || 0);
301
+ }
302
+
303
+ /** 写/删/改名优先于读(数据不可逆,改造收益更高)。 */
304
+ function isWriteLike(kind) {
305
+ return kind === 'read' ? 0 : 1;
306
+ }
307
+
308
+ /** 同步调用优先于异步(阻塞事件循环,收益直接)。 */
309
+ function isSync(type) {
310
+ return type === 'sync' ? 1 : 0;
311
+ }
312
+
313
+ // ── 对外出口:保持与原单文件一致,调用方无需改动 ──
314
+ export { RISK_BADGE, RISK_LABEL };
@@ -0,0 +1,156 @@
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
+ };
@@ -0,0 +1,52 @@
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
+ }