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,138 @@
1
+ import { readText } from './collector.js';
2
+
3
+ /* ───────── 文件上下文常量 ───────── */
4
+ const MK_DIR_SCOPE_LOOKAHEAD = 20; // 命中行向后查 mkdir 调用的保守跨度
5
+ const FUNC_START_SCAN_BACK = 60; // 向上找函数起点的最大行数
6
+
7
+ /**
8
+ * 写文件前 mkdir 语义豁免:
9
+ * robustness/mkdir-before-write 用纯 regex 匹配 `fs.writeFile(...)` 等写语句,
10
+ * 看不到同函数内先执行的 mkdir/ensureDataDir 调用 → 把「先建目录再写」的
11
+ * 常规安全写法误报成 ENOENT 风险。
12
+ * 判定:命中行向上找最近函数体边界(前一个 `){`/`=>{` 或 `function` 行),
13
+ * 该函数体内(往后至函数闭括号前,保守取命中行前 40 行 + 命中行后 20 行)
14
+ * 若出现 mkdirSync/mkdir(/ensureDataDir 调用则视为已确保目录存在。
15
+ * @param {string[]} lines 文件全部行
16
+ * @param {number} lineIdx 命中行索引(0 基)
17
+ * @returns {boolean} true=同一函数内已建目录(应豁免)
18
+ */
19
+ export function hasMkdirInSameFunction(lines, lineIdx) {
20
+ const MKDIR_RE = /mkdir(Sync)?\s*\(|ensureDataDir\s*\(|recursive:\s*true/;
21
+ const FUNC_START_RE = /(function|=>)\s*\{|\)\s*(async\s*)?\{/;
22
+ // 向上找函数起点(最多 60 行),命中即记下作用域起点
23
+ let scopeStart = 0;
24
+ for (let i = Math.max(0, lineIdx - FUNC_START_SCAN_BACK); i < lineIdx; i++) {
25
+ if (FUNC_START_RE.test(String(lines[i] || ''))) scopeStart = i;
26
+ }
27
+ // 向后找闭括号粗略平衡点(保守取 20 行),期间出现 mkdir 即豁免
28
+ const scopeEnd = Math.min(lines.length, lineIdx + MK_DIR_SCOPE_LOOKAHEAD);
29
+ for (let i = scopeStart; i < scopeEnd; i++) {
30
+ if (i === lineIdx) continue;
31
+ if (MKDIR_RE.test(String(lines[i] || ''))) return true;
32
+ }
33
+ return false;
34
+ }
35
+
36
+ /**
37
+ * 外部 API 调用超时语义豁免:
38
+ * robustness/timeout-on-external-api 规则用纯 regex 匹配 `fetch(`/`axios.(` 等调用,
39
+ * 无法看到同一调用表达式内的超时参数 → 把「已设置 AbortSignal.timeout / AbortController /
40
+ * timeout 选项」的调用误报成无超时。
41
+ * 判定:命中行内联有超时设置(单行调用),或命中行前/后(各最多 12 行、括号未闭合区间)
42
+ * 出现 AbortSignal.timeout / AbortController / timeout: / timeout = 即视为已设超时。
43
+ * 修误报:只往后看会漏「init/options 定义在调用之前」的写法——
44
+ * `const init = { signal: AbortSignal.timeout(MS) }; await fetch(url, init)` 的
45
+ * signal 在 fetch 前 6 行,后看 12 行永远扫不到 → 加前向 12 行扫描。
46
+ * @param {string} line 命中的行文本
47
+ * @param {string[]} lines 文件全部行
48
+ * @param {number} lineIdx 命中行索引(0 基)
49
+ * @returns {boolean} true=调用已设超时(应豁免)
50
+ */
51
+ /** 超时语义特征(行内/区间扫描复用)。 */
52
+ const TIMEOUT_SIGNAL_RE = /AbortSignal\.timeout|AbortController|timeout\s*[:=]/;
53
+
54
+ /**
55
+ * 区间扫描:lines[start, end) 内是否出现超时信号。
56
+ * 从 hasExternalCallTimeout 抽出(前向 12 行扫描),独立成函数降圈复杂度。
57
+ * @param {string[]} lines 文件全部行
58
+ * @param {number} start 起始行索引(含)
59
+ * @param {number} end 结束行索引(不含)
60
+ * @returns {boolean} true=区间内有超时设置
61
+ */
62
+ function hasTimeoutInRange(lines, start, end) {
63
+ for (let i = start; i < end; i++) {
64
+ if (TIMEOUT_SIGNAL_RE.test(String(lines[i] || ''))) return true;
65
+ }
66
+ return false;
67
+ }
68
+
69
+ /** 调用表达式闭合判定(括号深度归零且行尾闭合符号)——从后向扫描循环抽出。 */
70
+ function isCallClosed(s, depth) {
71
+ return depth <= 0 && /\);|},|}\);/.test(s);
72
+ }
73
+
74
+ /**
75
+ * 调用之后(括号未闭合区间,最多 12 行)的超时检测:
76
+ * 跨行对象(fetch(url, { ... }))从下一行算起时首行的 `},` 会把深度归零提前
77
+ * break,漏掉对象尾部的 signal: AbortSignal.timeout 字段——故起始括号深度计入
78
+ * 命中行自身。从 hasExternalCallTimeout 抽出(后向扫描 + 括号深度平衡)。
79
+ * @param {string} line 命中的行文本
80
+ * @param {string[]} lines 文件全部行
81
+ * @param {number} lineIdx 命中行索引(0 基)
82
+ * @returns {boolean} true=调用之后已设超时
83
+ */
84
+ function hasTimeoutAfterCall(line, lines, lineIdx) {
85
+ let depth = (String(line || '').match(/\(/g) || []).length - (String(line || '').match(/\)/g) || []).length;
86
+ const LIMIT = 12;
87
+ for (let i = lineIdx + 1; i < Math.min(lines.length, lineIdx + 1 + LIMIT); i++) {
88
+ const s = String(lines[i] || '');
89
+ depth += (s.match(/\(/g) || []).length - (s.match(/\)/g) || []).length;
90
+ if (TIMEOUT_SIGNAL_RE.test(s)) return true;
91
+ if (isCallClosed(s, depth)) break; // 调用表达式已闭合
92
+ }
93
+ return false;
94
+ }
95
+
96
+ export function hasExternalCallTimeout(line, lines, lineIdx) {
97
+ if (TIMEOUT_SIGNAL_RE.test(line)) return true; // 单行内联超时
98
+ // 前向扫描:init/options 常定义在调用之前(同函数内 signal: AbortSignal.timeout(...))
99
+ if (hasTimeoutInRange(lines, Math.max(0, lineIdx - 12), lineIdx)) return true;
100
+ return hasTimeoutAfterCall(line, lines, lineIdx);
101
+ }
102
+
103
+ /**
104
+ * 全仓 js-yaml 引用检测:扫描所有文本文件的 import/require 语句,
105
+ * 判断仓库是否真的引用了 js-yaml 包。npm/undeclared-js-yaml 规则需要这个
106
+ * 全仓语义证据——零依赖插件(lib 不 import js-yaml)不应被报「未声明 js-yaml 依赖」。
107
+ * @param {Array<{path:string, full:string}>} files 收集的文件清单
108
+ * @returns {boolean} true=全仓存在 js-yaml import/require
109
+ */
110
+ export function detectRepoJsYamlImport(files) {
111
+ const RE = /(?:from\s+['"]js-yaml['"]|require\s*\(\s*['"]js-yaml['"]\s*\)|import\s*\(\s*['"]js-yaml['"]\s*\))/;
112
+ for (const f of files || []) {
113
+ try {
114
+ const t = readText(f.full);
115
+ if (RE.test(t)) return true;
116
+ } catch { /* 读失败跳过(collector 已保证可读) */ }
117
+ }
118
+ return false;
119
+ }
120
+
121
+ /**
122
+ * 版本号「路径/文件名上下文」豁免:
123
+ * version/embedded-major-zero 与 version/readme-zero-title 用 pattern 匹配任意
124
+ * `v0.x.y` 字符串,会误伤「安装路径/文件名里的版本号」——如 README 数据示例
125
+ * `Path('/vol2/.../dsh-v0.1.2-alpha.4/.dsh-home/...')` 里的 dsh-v0.1.2 是
126
+ * DSH runtime 目录名(第三方环境路径),不是本项目版本标记,不应报。
127
+ * 判定:v0.x.y 前一个字符是路径/文件名分隔符(/ - . _ 或字母数字),
128
+ * 且整行含路径分隔符 / → 视为路径上下文,豁免。
129
+ * @param {string} line 命中行文本
130
+ * @returns {boolean} true=版本号处于路径/文件名上下文(应豁免)
131
+ */
132
+ export function isVersionInPathContext(line) {
133
+ const match = /[vV]0\.\d+\.\d+/.exec(String(line || ''));
134
+ if (!match) return false;
135
+ if (!String(line || '').includes('/')) return false; // 无路径分隔符 = 不是路径上下文
136
+ const before = String(line || '')[match.index - 1] || '';
137
+ return /[/\-._A-Za-z0-9]/.test(before);
138
+ }
@@ -0,0 +1,50 @@
1
+ /** 统一问题对象构造器(所有审计检查的出口)。 */
2
+ export function makeFinding({ file, line, rule, kind, severity = 'warning', message, dimensions = [], exemptHint = '', scoreImpact = 0 }) {
3
+ return { file, line, rule, kind, severity, message, dimensions, exemptHint, scoreImpact };
4
+ }
5
+
6
+ /**
7
+ * 扫描智能提示(1.0.8):对 warning/blocker 且文件路径或文件名带 test 特征的 finding,
8
+ * 在 message 末尾附加「测试文件夹可用 .test 空文件豁免」提示(告知而非自动豁免——
9
+ * 是否豁免由用户在对应目录放 0 字节 .test 空文件决定,防逃逸语义与 1.0.6 isTestExemptDir 一致)。
10
+ * test 特征:路径含 `test|tests|__tests__|spec` 目录段,或文件名 `.test.js`/`-spec.js` 等。
11
+ * 重复提示幂等:message 已含「.test」则跳过。
12
+ * @param {Array} findings 统一问题对象数组(原地补 message,返回同一数组)
13
+ */
14
+ export function decorateTestExemptHint(findings = []) {
15
+ const testPathRe = /(^|[/\\])(test|tests|__tests__|spec)[/\\]|\.(test|spec)(\.[a-z]+)?$/i;
16
+ const HINT = '(提示:测试目录/文件可在对应目录放 0 字节 .test 空文件整目录豁免扫描)';
17
+ for (const f of findings) {
18
+ if (!f || !['warning', 'blocker', 'error'].includes(f.severity)) continue;
19
+ const file = String(f.file || '');
20
+ if (!testPathRe.test(file)) continue;
21
+ if (String(f.message || '').includes('.test')) continue;
22
+ f.message = `${f.message || ''}${HINT}`;
23
+ }
24
+ return findings;
25
+ }
26
+
27
+ /**
28
+ * 汇总 findings 统计。
29
+ *
30
+ * 1.1.0 修复:原实现只累加 blocker/warning,但规则 severity 实际有三档
31
+ * (blocker / error / warning)。error 级问题(凭据泄露等)既不进 blocker
32
+ * 也不进 warning,却计入 total → 产生「0 blocker 0 warning 但 total=3」的
33
+ * 矛盾统计,且上层按 blocker 数判断门禁时会**漏放** error 级问题。
34
+ * 现统一语义:error 归入 blocker(拦截级),notice/info 单列,其余为 warning。
35
+ * @param {Array} findings 统一问题对象列表
36
+ * @returns {{blocker:number, warning:number, notice:number, total:number}}
37
+ */
38
+ export function summarize(findings = []) {
39
+ let blocker = 0, warning = 0, notice = 0;
40
+ for (const f of findings) {
41
+ const sev = f.severity || 'warning';
42
+ if (sev === 'blocker' || sev === 'error') blocker++; // error=拦截级(凭据泄露/语法错误等)
43
+ else if (sev === 'notice' || sev === 'info') notice++;
44
+ else warning++;
45
+ }
46
+ return { blocker, warning, notice, total: findings.length };
47
+ }
48
+
49
+ /** 代码文件扩展名(residue/style 类检查只对代码生效,修规则定义/文档自举假阳性)。 */
50
+ export const CODE_EXTS = new Set(['js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', 'py', 'go', 'rs', 'java', 'kt', 'swift', 'php', 'rb', 'sh', 'bash']);
@@ -0,0 +1,113 @@
1
+ /**
2
+ * dsh-git-push gitignore 语法匹配器(非 git 目录兜底,)
3
+ *
4
+ * 为什么需要:`.auditignore` 原先只走 `git check-ignore`,因此**仅在 git 仓库内生效**——
5
+ * 非 git 目录(解压的源码包、临时导出目录、未 init 的工程)下 `.auditignore` 被完全忽略,
6
+ * 实测同一个 `*.sh` 规则在 `git init` 前后行为相反。本模块提供纯 JS 兜底,
7
+ * 使 `.auditignore` 在无 git 时同样生效。
8
+ *
9
+ * 语义对齐 git(用真 git 建立基准后逐条对齐,见 test/test-gitignore-match.mjs):
10
+ * - `*.sh` 匹配**任意层级**(不是只根目录)——gitignore 的 `*` 不跨 `/`,
11
+ * 但无 `/` 的模式整体可匹配任意深度,故 `*.sh` = 任意层级的 .sh
12
+ * - `/ + *.sh` 仅根目录(前导 `/` 锚定)
13
+ * - `sub/*.sh` 含 `/` 的模式从仓库根锚定,`*` 不跨 `/`
14
+ * - `** + / + *.sh` 任意层级(显式递归)
15
+ * - `gen/` 目录规则:匹配该目录**及其下全部内容**
16
+ * - `!xxx` 取反(白名单恢复),**后出现的规则覆盖先出现的**
17
+ *
18
+ * 与 git 的已知差异(有意为之,够用即可):
19
+ * - 不处理嵌套 `.gitignore`(只处理传入的单份规则文本)
20
+ * - `**` 的极端位置组合不保证与 git 逐字节一致
21
+ * 这些差异只影响「非 git 兜底」路径;git 仓库仍走 `git check-ignore`,语义 100% 一致。
22
+ */
23
+ import { globToRegex } from './glob.js';
24
+
25
+ /**
26
+ * 解析 gitignore 文本为规则数组。
27
+ *
28
+ * 逐行处理:去尾随空白、跳过空行与 `#` 注释、识别 `!` 取反与前导 `/` 锚定、
29
+ * 识别尾随 `/` 的目录规则。
30
+ * @param {string} text gitignore 格式文本
31
+ * @returns {Array<{negated:boolean, dirOnly:boolean, anchored:boolean, pattern:string, re:RegExp|null}>}
32
+ */
33
+ export function parseGitignore(text) {
34
+ const rules = [];
35
+ for (const raw of String(text || '').split('\n')) {
36
+ let line = raw.replace(/\s+$/, '');
37
+ if (!line || line.startsWith('#')) continue;
38
+ let negated = false;
39
+ if (line.startsWith('!')) { negated = true; line = line.slice(1); }
40
+ if (!line) continue;
41
+ let dirOnly = false;
42
+ if (line.endsWith('/')) { dirOnly = true; line = line.replace(/\/+$/, ''); }
43
+ if (!line) continue;
44
+ let anchored = false;
45
+ if (line.startsWith('/')) { anchored = true; line = line.replace(/^\/+/, ''); }
46
+ // 含 `/` 的模式在 gitignore 中天然从根锚定
47
+ if (line.includes('/')) anchored = true;
48
+ if (!line) continue;
49
+ rules.push({ negated, dirOnly, anchored, pattern: line, re: compilePattern(line, anchored) });
50
+ }
51
+ return rules;
52
+ }
53
+
54
+ /**
55
+ * 把单条 pattern 编译为匹配「仓库相对路径」的正则。
56
+ *
57
+ * 无 `/` 的模式(anchored=false)编译为「任意层级」:任意目录前缀 + pattern,
58
+ * 这正是 gitignore 里 `*.sh` 能命中 `deep/a/b/x.sh` 的原因。
59
+ * @param {string} pattern 已剥离 `!`、前导 `/`、尾随 `/` 的模式
60
+ * @param {boolean} anchored 是否从根锚定
61
+ * @returns {RegExp|null}
62
+ */
63
+ function compilePattern(pattern, anchored) {
64
+ const body = globToRegex(pattern, false);
65
+ if (!body) return null;
66
+ try {
67
+ return new RegExp(anchored ? `^${body.source}$` : `^(?:.*/)?${body.source}$`);
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
72
+
73
+ /**
74
+ * 判断相对路径是否被规则集忽略。
75
+ *
76
+ * 语义要点:
77
+ * - 规则**顺序敏感**:后出现的规则覆盖先出现的(`!` 恢复同样受顺序影响)
78
+ * - 目录规则(`gen/`)命中该目录本身**及其全部子路径**
79
+ * - 传入的路径统一用 `/` 分隔的仓库相对路径
80
+ * @param {Array} rules parseGitignore 的结果
81
+ * @param {string} relPath `/` 分隔的相对路径
82
+ * @param {boolean} [isDir] 该路径是否为目录(当前仅用于语义自解释,判定不区分)
83
+ * @returns {boolean} true = 被忽略
84
+ */
85
+ export function isIgnoredByRules(rules, relPath, isDir = false) {
86
+ const p = String(relPath || '').replace(/\\/g, '/').replace(/^\.\//, '').replace(/^\/+/, '');
87
+ if (!p) return false;
88
+ let ignored = false;
89
+ for (const r of rules) {
90
+ if (!r.re) continue;
91
+ let hit = r.re.test(p);
92
+ // 目录规则:还命中其下所有后代(gen/ → gen/a/b.js)
93
+ if (!hit && r.dirOnly) {
94
+ const segs = p.split('/');
95
+ for (let i = 1; i < segs.length; i += 1) {
96
+ if (r.re.test(segs.slice(0, i).join('/'))) { hit = true; break; }
97
+ }
98
+ }
99
+ if (hit) ignored = !r.negated;
100
+ }
101
+ return ignored;
102
+ }
103
+
104
+ /**
105
+ * 一次性判断:给定 gitignore 文本与相对路径,是否被忽略。
106
+ * @param {string} text gitignore 格式文本
107
+ * @param {string} relPath `/` 分隔的相对路径
108
+ * @param {boolean} [isDir]
109
+ * @returns {boolean}
110
+ */
111
+ export function isIgnored(text, relPath, isDir = false) {
112
+ return isIgnoredByRules(parseGitignore(text), relPath, isDir);
113
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * dsh-git-push glob → RegExp 转换(1.0.4,private-files 匹配用)
3
+ *
4
+ * 支持子集:`**`(任意层级)、`*`(单层任意)、`?`(单字符)、
5
+ * `{a,b}`(任选一,可含通配)、`[abc]`(字符类)、`\`(转义)。
6
+ * 语义对齐 gitignore:「** + / + id_ed25519」匹配任意深度;`*.key` 匹配任意层级的 .key。
7
+ * 不依赖 minimatch(零依赖铁律),实现 ≤40 行,可单测。
8
+ */
9
+ export function globToRegex(glob, anchored = true) {
10
+ if (typeof glob !== 'string' || !glob) return null;
11
+ let out = '';
12
+ let i = 0;
13
+ const s = glob;
14
+ while (i < s.length) {
15
+ const ch = s[i];
16
+ if (ch === '*') {
17
+ // ** 跨层级(含零级);* 单层级内任意
18
+ if (s[i + 1] === '*') {
19
+ while (s[i + 1] === '*') i++; // 吸收连续星:i 停最后一个 *
20
+ if (s[i + 1] === '/') { out += '(?:.*/)?'; i += 2; } // i 跳至 '/' 后
21
+ else { out += '.*'; i++; }
22
+ } else {
23
+ out += '[^/]*';
24
+ i++;
25
+ }
26
+ } else if (ch === '?') {
27
+ out += '[^/]';
28
+ i++;
29
+ } else if (ch === '{') {
30
+ // {a,b} → (?:a|b),最省实现:找配对 }
31
+ const end = s.indexOf('}', i);
32
+ if (end === -1) { out += '\\{'; i++; continue; }
33
+ const inner = s.slice(i + 1, end).split(',').filter(Boolean);
34
+ const parts = inner.map((p) => { const r = globToRegex(p, false); return r ? r.source : ''; }).filter(Boolean);
35
+ if (parts.length) out += `(?:${parts.join('|')})`;
36
+ i = end + 1;
37
+ } else if (ch === '[') {
38
+ const end = s.indexOf(']', i);
39
+ if (end === -1) { out += '\\['; i++; continue; }
40
+ let cls = s.slice(i + 1, end).replace(/\\/g, '\\\\');
41
+ if (cls.startsWith('!')) cls = '^' + cls.slice(1);
42
+ out += `[${cls}]`;
43
+ i = end + 1;
44
+ } else if ('.+()^$|'.includes(ch)) {
45
+ out += `\\${ch}`;
46
+ i++;
47
+ } else {
48
+ out += ch;
49
+ i++;
50
+ }
51
+ }
52
+ try {
53
+ return new RegExp(anchored ? `^${out}$` : out);
54
+ } catch {
55
+ return null; // 非法 glob → 调用方跳过
56
+ }
57
+ }
58
+
59
+ /** 一行 glob 是否触及当前路径(供批量匹配)。 */
60
+ export function globMatch(glob, path) {
61
+ const re = globToRegex(glob);
62
+ return !!re && re.test(String(path));
63
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * audit --history 历史提交审计:落盘模块(1.7.0)。
3
+ *
4
+ * 职责:
5
+ * · resolveReportDir —— 保存位置解析(--out 缺省 = git 根 audit-history/ 子目录)
6
+ * · writeCommitReport —— 每个提交一份审计清单(<short>-<时间>.json 完整 + .md 可读版)
7
+ * · writeHistoryIndex —— SUMMARY.json 全部提交汇总(快速浏览)
8
+ * 原子写复用 atomic-json(.tmp + rename),中断/崩溃不出现半文件。
9
+ */
10
+ import { join } from 'node:path';
11
+ import { mkdirSync } from 'node:fs';
12
+ import { writeJsonAtomic, writeTextAtomic } from '../core/atomic-json.js';
13
+
14
+ /* ───────── 历史审计报告常量 ───────── */
15
+ const TIMESTAMP_MAX_LEN = 19; // ISO 时间戳(YYYY-MM-DDTHH:mm:ss)截断长度
16
+
17
+ /** 报告保存位置:--out 缺省 = <git根>/audit-history(需求「缺省就是 git 根目录存所有提交的分析」)。 */
18
+ export function resolveReportDir(repoPath, outDir = '') {
19
+ return String(outDir || '').trim() || join(String(repoPath || '.'), 'audit-history');
20
+ }
21
+
22
+ /** 可读 Markdown 清单(报告 .md 版;文件/规则/消息结构化展示)。 */
23
+ function renderMarkdown(entry = {}) {
24
+ const lines = [];
25
+ lines.push(`# 审计报告 · ${entry.short} ${entry.subject || ''}`);
26
+ lines.push('');
27
+ lines.push(`- 提交:${entry.sha}`);
28
+ lines.push(`- 作者:${entry.author || ''}|时间:${entry.date || ''}`);
29
+ lines.push(`- 文件数:${entry.fileCount ?? 0}`);
30
+ const quality = entry.quality || {};
31
+ lines.push(`- 质量:${quality.emptyResult ? (quality.emptyReason || '未评分') : `${quality.score}/100(${quality.level || ''})`}`);
32
+ const summary = entry.summary || {};
33
+ lines.push(`- summary:blocker ${summary.blocker ?? 0} / warning ${summary.warning ?? 0} / notice ${summary.notice ?? 0}(total ${summary.total ?? 0})`);
34
+ // 文档加分制(0 分起、上限 10)——结构信号 + 交叉验证
35
+ const docsScore = entry.docsScore;
36
+ if (docsScore && Array.isArray(docsScore.items)) {
37
+ const total = docsScore.items.filter((i) => i.hit).reduce((a, i) => a + (Number(i.score) || 0), 0);
38
+ lines.push(`- 文档加分:命中 ${docsScore.hits?.length ?? 0}/${docsScore.items.length}(+${total.toFixed(1)}/10)`);
39
+ if (Array.isArray(docsScore.review) && docsScore.review.length) lines.push(`- 建议人工复核:${docsScore.review.join(';')}`);
40
+ }
41
+ const findings = entry.findings || [];
42
+ if (!findings.length) {
43
+ lines.push('');
44
+ lines.push('(无 findings)');
45
+ return lines.join('\n') + '\n';
46
+ }
47
+ lines.push('');
48
+ lines.push('## findings');
49
+ for (const f of findings) {
50
+ lines.push(`- [${f.severity}] ${f.rule} ${f.file}:${f.line} — ${String(f.message || '').slice(0, 160)}`);
51
+ }
52
+ return lines.join('\n') + '\n';
53
+ }
54
+
55
+ /**
56
+ * 写单个提交的报告(json 完整 + md 可读),返回落盘路径。
57
+ * @param {string} dir 保存目录(resolveReportDir 的结果)
58
+ * @param {object} entry { sha, short, date, author, subject, summary, quality, findings, fileCount }
59
+ * @returns {{json: string, md: string, base: string}}
60
+ */
61
+ export function writeCommitReport(dir, entry = {}) {
62
+ mkdirSync(dir, { recursive: true });
63
+ const ts = String(entry.date || new Date().toISOString()).replace(/[:.]/g, '-').slice(0, TIMESTAMP_MAX_LEN);
64
+ const base = `${entry.short || 'unknown'}-${ts}`;
65
+ const jsonPath = join(dir, base + '.json');
66
+ const mdPath = join(dir, base + '.md');
67
+ writeJsonAtomic(jsonPath, entry, { pretty: true });
68
+ writeTextAtomic(mdPath, renderMarkdown(entry));
69
+ return { json: jsonPath, md: mdPath, base };
70
+ }
71
+
72
+ /**
73
+ * 写全部提交汇总(SUMMARY.json)。
74
+ * @param {string} dir 保存目录
75
+ * @param {object} meta { repoPath, since, until, total, processed, entries: [{sha,short,date,subject,summary,quality}] }
76
+ */
77
+ export function writeHistoryIndex(dir, meta = {}) {
78
+ mkdirSync(dir, { recursive: true });
79
+ const agg = { blocker: 0, warning: 0, notice: 0, total: 0 };
80
+ for (const e of meta.entries || []) {
81
+ const s = e.summary || {};
82
+ agg.blocker += s.blocker || 0;
83
+ agg.warning += s.warning || 0;
84
+ agg.notice += s.notice || 0;
85
+ agg.total += s.total || 0;
86
+ }
87
+ writeJsonAtomic(join(dir, 'SUMMARY.json'), {
88
+ generatedAt: new Date().toISOString(),
89
+ repoPath: meta.repoPath || '',
90
+ range: { since: meta.since || '', until: meta.until || '' },
91
+ total: meta.total ?? 0,
92
+ processed: meta.processed ?? 0,
93
+ aggregate: agg,
94
+ commits: (meta.entries || []).map((e) => ({
95
+ sha: e.sha, short: e.short, date: e.date, author: e.author, subject: e.subject,
96
+ summary: e.summary || {}, quality: e.quality || {},
97
+ })),
98
+ }, { pretty: true });
99
+ return join(dir, 'SUMMARY.json');
100
+ }
@@ -0,0 +1,126 @@
1
+ /**
2
+ * audit --history 历史提交审计:遍历 + 快照审计核心(1.7.0)。
3
+ *
4
+ * 语义(需求):
5
+ * · **只看历史提交**——不审当前工作区/diff;遍历 git log 指定范围(起始~结束,皆缺省=全部历史、含两端)
6
+ * · 每个提交用 `git archive` 解出**代码快照**到临时目录,跑 `auditFull` 全量审计
7
+ * (审计规则与当前工作区同一套——不新增第二套审计逻辑)
8
+ * · **按提交后台串行**:runHistoryAudit 逐个提交顺序执行(非并发),每提交落盘一份审计清单
9
+ *
10
+ * git 命令经 runGit/gitRaw(带 DSH_GIT_ENFORCE_PASS 的插件包装器);archive 二进制走 gitRaw Buffer。
11
+ */
12
+ import { execFileSync } from 'node:child_process';
13
+ import { mkdtempSync, rmSync, writeFileSync, existsSync } from 'node:fs';
14
+ import { tmpdir } from 'node:os';
15
+ import { join } from 'node:path';
16
+ import { runGit, gitRaw } from '../core/exec.js';
17
+ import { auditFull } from './orchestrate.js';
18
+ import { scoreQuality } from '../score/index.js';
19
+ import { resolveReportDir, writeCommitReport, writeHistoryIndex } from './history-report.js';
20
+
21
+ /* ───────── 历史审计常量 ───────── */
22
+ const SHA_SHORT_LEN = 7; // 短 sha 截断长度
23
+ const SUBJECT_MAX_LEN = 80; // 提交标题截断长度
24
+
25
+ /**
26
+ * 列出历史提交(范围含两端)。
27
+ * @param {string} repoPath git 仓库路径
28
+ * @param {{since?: string, until?: string}} [range] since/until 为空 = 全历史(到 HEAD)
29
+ * @returns {Array<{sha,short,subject,author,date}>} 旧→新顺序(git log --reverse)
30
+ */
31
+ export function listHistoryCommits(repoPath, { since = '', until = '' } = {}) {
32
+ const sinceTrim = String(since || '').trim();
33
+ const untilTrim = String(until || '').trim();
34
+ // 范围:since^..until(含 since 与 until 两端);both 空 = 全历史
35
+ const range = untilTrim || 'HEAD';
36
+ // range 是提交范围参数,不能放 `--` 之后(`--` 后 git 当路径 → 空结果)
37
+ const res = runGit(['log', '--format=%H%x1f%h%x1f%an%x1f%aI%x1f%s', '--reverse', range], { cwd: repoPath });
38
+ if (!res.ok) return { error: `读取提交历史失败: ${res.stderr || 'git log 出错'}` };
39
+ const out = [];
40
+ for (const line of String(res.stdout || '').split('\n')) {
41
+ if (!line.trim()) continue;
42
+ const [sha, short, author, date, ...subjectParts] = line.split('\x1f');
43
+ out.push({ sha, short: short || sha.slice(0, SHA_SHORT_LEN), author: author || '', date: date || '', subject: (subjectParts.join('\x1f') || '').slice(0, SUBJECT_MAX_LEN) });
44
+ }
45
+ if (sinceTrim) {
46
+ // since 语义「从此提交开始(含)」,不用 `since^..until` 范围(根提交无父会 ambiguous);
47
+ // 取 until 全部历史后截断到 since 出现处
48
+ const idx = out.findIndex((c) => c.sha === sinceTrim || c.short === sinceTrim || c.sha.startsWith(sinceTrim));
49
+ if (idx === -1) return { error: `起始提交不存在: ${sinceTrim}` };
50
+ return out.slice(idx);
51
+ }
52
+ return out;
53
+ }
54
+
55
+ /**
56
+ * 对单个历史提交做「快照全量审计」:git archive 解临时目录 → auditFull → 评分 → 清理。
57
+ * @param {string} repoPath git 仓库
58
+ * @param {object} commit listHistoryCommits 单条
59
+ * @param {object} [opts] auditFull 的 opts(rulesetDir/maxScanFiles/slots/disabledSlots/includeIgnored…)
60
+ * @param {object} [weights] scoreQuality 权重覆盖
61
+ * @returns {Promise<{summary, quality, findings, fileCount}>}
62
+ */
63
+ export async function auditHistoryCommit(repoPath, commit, opts = {}, weights = {}) {
64
+ const tmpDir = mkdtempSync(join(tmpdir(), 'dshgp-hist-'));
65
+ const tarPath = join(tmpDir, 'snapshot.tar');
66
+ try {
67
+ // git archive <sha> → Buffer(二进制,不用 runGit 的 utf8 通道)
68
+ const arch = gitRaw(['archive', commit.sha], { cwd: repoPath });
69
+ if (arch.error || arch.status !== 0) {
70
+ return { error: `git archive ${commit.short} 失败: ${String(arch.error || arch.stderr).slice(0, 200)}` };
71
+ }
72
+ writeFileSync(tarPath, arch.stdout);
73
+ execFileSync('tar', ['-x', '-C', tmpDir, '-f', tarPath], { stdio: 'ignore' });
74
+ const historyAudit = await auditFull(tmpDir, opts);
75
+ const quality = scoreQuality(historyAudit.findings || [], weights, { files: historyAudit.files, docsScore: historyAudit.docsScore });
76
+ return {
77
+ summary: historyAudit.summary || {},
78
+ quality,
79
+ findings: historyAudit.findings || [],
80
+ docsScore: historyAudit.docsScore,
81
+ fileCount: historyAudit.files ?? 0,
82
+ };
83
+ } finally {
84
+ rmSync(tmpDir, { recursive: true, force: true });
85
+ }
86
+ }
87
+
88
+ /**
89
+ * 串行执行历史审计:逐提交审计 + 落盘 + 进度回调 + 汇总;signal.aborted 时停(已落盘保留)。
90
+ * @param {string} repoPath git 仓库
91
+ * @param {object} [opts] { since, until, outDir, auditOpts, weights, signal, onCommit }
92
+ * @returns {Promise<{ok:boolean, reportDir, total, processed, aborted?, summary, entries, error?}>}
93
+ */
94
+ export async function runHistoryAudit(repoPath, { since = '', until = '', outDir = '', auditOpts = {}, weights = {}, signal, onCommit } = {}) {
95
+ const commits = listHistoryCommits(repoPath, { since, until });
96
+ if (Array.isArray(commits) === false || commits.error) {
97
+ return { ok: false, error: commits.error || '读取提交历史失败' };
98
+ }
99
+ if (!commits.length) return { ok: false, error: '没有可审计的历史提交(空仓库?)' };
100
+ const dir = resolveReportDir(repoPath, outDir);
101
+ const entries = [];
102
+ let aborted = false;
103
+ for (let i = 0; i < commits.length; i += 1) {
104
+ if (signal && signal.aborted) { aborted = true; break; }
105
+ const commit = commits[i];
106
+ const res = await auditHistoryCommit(repoPath, commit, auditOpts, weights);
107
+ if (res.error) {
108
+ entries.push({ ...commit, error: res.error, summary: {}, quality: {}, findings: [] });
109
+ } else {
110
+ const entry = { ...commit, ...res };
111
+ entries.push(entry);
112
+ writeCommitReport(dir, entry);
113
+ }
114
+ onCommit?.({ index: i + 1, total: commits.length, short: commit.short, ok: !res.error, error: res.error });
115
+ }
116
+ writeHistoryIndex(dir, { repoPath, since, until, total: commits.length, processed: entries.filter((e) => !e.error).length, entries });
117
+ return {
118
+ ok: true,
119
+ reportDir: dir,
120
+ total: commits.length,
121
+ processed: entries.length,
122
+ failed: entries.filter((e) => e.error).length,
123
+ aborted,
124
+ entries: entries.map((e) => ({ sha: e.sha, short: e.short, subject: e.subject, ok: !e.error, error: e.error, summary: e.summary, quality: e.quality })),
125
+ };
126
+ }