dsh-git-push 2.20.19 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (239) hide show
  1. package/README.md +76 -47
  2. package/cli-tool.mjs +2 -4
  3. package/cli.mjs +11 -4
  4. package/lib/app/apply.js +15 -13
  5. package/lib/app/command-registry.js +26 -19
  6. package/lib/app/handlers/http-constants.js +8 -0
  7. package/lib/app/handlers/meta.js +2 -2
  8. package/lib/app/handlers/preprocess.js +104 -0
  9. package/lib/app/handlers/repo-actions.js +2 -3
  10. package/lib/app/handlers/repos.js +137 -10
  11. package/lib/app/handlers/settings.js +34 -15
  12. package/lib/app/http-handlers.js +13 -42
  13. package/lib/app/index.js +3 -2
  14. package/lib/app/inject-text.js +6 -21
  15. package/lib/app/preprocess-client.js +136 -0
  16. package/lib/app/repo-ownership.js +1 -1
  17. package/lib/app/schema.js +20 -10
  18. package/lib/app/settings-bridge.js +60 -8
  19. package/lib/app/severity.js +14 -0
  20. package/lib/app/slash-commands.js +5 -164
  21. package/lib/app/tool-call.js +96 -163
  22. package/lib/cli/commands-preprocess.mjs +74 -0
  23. package/lib/cli/commands-tool.mjs +3 -2
  24. package/lib/cli/commands-vcs.mjs +39 -5
  25. package/lib/cli/shared.mjs +36 -10
  26. package/lib/client/index.js +11 -16
  27. package/lib/client-parts/git/account.js +21 -12
  28. package/lib/client-parts/git/actions.js +23 -77
  29. package/lib/client-parts/git/apply.js +8 -2
  30. package/lib/client-parts/git/browser.js +1 -1
  31. package/lib/client-parts/git/const.js +33 -1
  32. package/lib/client-parts/git/controller.js +175 -176
  33. package/lib/client-parts/git/icons.js +1 -1
  34. package/lib/client-parts/git/loader.js +1 -1
  35. package/lib/client-parts/git/npm.js +56 -37
  36. package/lib/client-parts/git/page.js +53 -1
  37. package/lib/client-parts/git/repo.js +8 -1
  38. package/lib/client-parts/git/settings.js +13 -1
  39. package/lib/client-parts/git/state.js +237 -0
  40. package/lib/client-parts/git/utils.js +1 -1
  41. package/lib/client.js +631 -312
  42. package/lib/commit-push/pre-commit-engine.js +629 -30
  43. package/lib/commit-push.js +127 -67
  44. package/lib/context/index.js +7 -5
  45. package/lib/core/config.js +1 -27
  46. package/lib/core/exec.js +2 -11
  47. package/lib/{exempt/index.js → git/exempt-markers.js} +8 -1
  48. package/lib/git/identity-rewrite.js +1 -1
  49. package/lib/git/ignore.js +1 -1
  50. package/lib/git/index.js +1 -1
  51. package/lib/git/push.js +2 -17
  52. package/lib/git/repo-index.js +8 -3
  53. package/lib/git/repos.js +2 -2
  54. package/lib/git/sensitive.js +1 -1
  55. package/lib/npm/install.js +1 -1
  56. package/lib/npm/publish.js +20 -5
  57. package/lib/npm/registry.js +2 -2
  58. package/lib/plugin/auto-push.js +5 -8
  59. package/lib/preprocess/providers.js +195 -0
  60. package/lib/self/index.js +1 -1
  61. package/lib/skip-dirs.js +14 -55
  62. package/package.json +31 -42
  63. package/skills/dev/dsh-git-push.md +9 -9
  64. package/skills/guide/guide-commit-push.md +11 -13
  65. package/skills/workflow/README.md +0 -1
  66. package/skills/workflow/task-completion-report.md +2 -2
  67. package/.auditignore +0 -30
  68. package/.gitignore +0 -43
  69. package/cli-audit.mjs +0 -141
  70. package/lib/BUGFIX-NOTES-2026-09-14.md +0 -278
  71. package/lib/app/audit-api.js +0 -173
  72. package/lib/app/handlers/audit.js +0 -150
  73. package/lib/app/host-doc-checks.js +0 -25
  74. package/lib/app/schema-audit.js +0 -42
  75. package/lib/app/scope-check.js +0 -69
  76. package/lib/ast/brace.js +0 -120
  77. package/lib/ast/callgraph.js +0 -135
  78. package/lib/ast/code-lines.js +0 -175
  79. package/lib/ast/consts.js +0 -12
  80. package/lib/ast/control-flow.js +0 -470
  81. package/lib/ast/credential.js +0 -315
  82. package/lib/ast/dataflow.js +0 -391
  83. package/lib/ast/dup-code.js +0 -165
  84. package/lib/ast/fs-hotspots.js +0 -154
  85. package/lib/ast/index.js +0 -38
  86. package/lib/ast/io-risk-const.js +0 -95
  87. package/lib/ast/io-risk-fn.js +0 -208
  88. package/lib/ast/io-risk-loop.js +0 -308
  89. package/lib/ast/io-risk.js +0 -314
  90. package/lib/ast/lang.js +0 -156
  91. package/lib/ast/line-count.js +0 -52
  92. package/lib/ast/magic-number.js +0 -272
  93. package/lib/ast/naming.js +0 -292
  94. package/lib/ast/perf.js +0 -488
  95. package/lib/ast/scope-collisions.js +0 -228
  96. package/lib/ast/scope.js +0 -241
  97. package/lib/ast/shell.js +0 -131
  98. package/lib/ast/size.js +0 -448
  99. package/lib/ast/symbol-index.js +0 -399
  100. package/lib/ast/tokenizer.js +0 -421
  101. package/lib/ast/treesitter.js +0 -413
  102. package/lib/audit/analysis-coverage.js +0 -98
  103. package/lib/audit/audit-file.js +0 -205
  104. package/lib/audit/auditignore-rules.js +0 -148
  105. package/lib/audit/checks.js +0 -17
  106. package/lib/audit/client-entry.js +0 -93
  107. package/lib/audit/collector.js +0 -610
  108. package/lib/audit/ext-runner.js +0 -80
  109. package/lib/audit/file-context.js +0 -391
  110. package/lib/audit/finding.js +0 -101
  111. package/lib/audit/gitignore-match.js +0 -113
  112. package/lib/audit/glob.js +0 -63
  113. package/lib/audit/history-report.js +0 -100
  114. package/lib/audit/history.js +0 -126
  115. package/lib/audit/ignore-blind.js +0 -102
  116. package/lib/audit/index.js +0 -33
  117. package/lib/audit/orchestrate.js +0 -672
  118. package/lib/audit/public.js +0 -24
  119. package/lib/audit/repo-level.js +0 -30
  120. package/lib/audit/report-yaml.js +0 -90
  121. package/lib/audit/scope-policy.js +0 -110
  122. package/lib/audit/slot.js +0 -66
  123. package/lib/audit-rules/audit-rules-comment.yml +0 -199
  124. package/lib/audit-rules/audit-rules-cpp.yml +0 -114
  125. package/lib/audit-rules/audit-rules-csharp.yml +0 -82
  126. package/lib/audit-rules/audit-rules-docs.yml +0 -32
  127. package/lib/audit-rules/audit-rules-dsh.yml +0 -177
  128. package/lib/audit-rules/audit-rules-filehealth.yml +0 -42
  129. package/lib/audit-rules/audit-rules-folder.yml +0 -99
  130. package/lib/audit-rules/audit-rules-frontend.yml +0 -335
  131. package/lib/audit-rules/audit-rules-go.yml +0 -103
  132. package/lib/audit-rules/audit-rules-i18n.yml +0 -45
  133. package/lib/audit-rules/audit-rules-java.yml +0 -105
  134. package/lib/audit-rules/audit-rules-nodejs.yml +0 -662
  135. package/lib/audit-rules/audit-rules-npm.yml +0 -187
  136. package/lib/audit-rules/audit-rules-paths.yml +0 -98
  137. package/lib/audit-rules/audit-rules-performance.yml +0 -245
  138. package/lib/audit-rules/audit-rules-php.yml +0 -101
  139. package/lib/audit-rules/audit-rules-private.yml +0 -24
  140. package/lib/audit-rules/audit-rules-python.yml +0 -106
  141. package/lib/audit-rules/audit-rules-robustness.yml +0 -31
  142. package/lib/audit-rules/audit-rules-rust.yml +0 -109
  143. package/lib/audit-rules/audit-rules-structure.yml +0 -158
  144. package/lib/audit-rules/audit-rules-swift.yml +0 -99
  145. package/lib/audit-rules/audit-rules-template.yml +0 -108
  146. package/lib/audit-ui-sdk/contract.js +0 -117
  147. package/lib/audit-ui-sdk/index.js +0 -17
  148. package/lib/checks/button-bind.js +0 -347
  149. package/lib/checks/common.js +0 -170
  150. package/lib/checks/credential-file.js +0 -43
  151. package/lib/checks/dataflow.js +0 -40
  152. package/lib/checks/dispatch.js +0 -117
  153. package/lib/checks/dup-code.js +0 -69
  154. package/lib/checks/dup-const.js +0 -232
  155. package/lib/checks/file-health.js +0 -150
  156. package/lib/checks/filter.js +0 -137
  157. package/lib/checks/folder.js +0 -173
  158. package/lib/checks/fs-scanner.js +0 -57
  159. package/lib/checks/hardcoded-path.js +0 -98
  160. package/lib/checks/index.js +0 -49
  161. package/lib/checks/io.js +0 -66
  162. package/lib/checks/magic-number.js +0 -42
  163. package/lib/checks/npm-json.js +0 -273
  164. package/lib/checks/private.js +0 -64
  165. package/lib/checks/regex.js +0 -298
  166. package/lib/checks/scope-collision.js +0 -68
  167. package/lib/checks/semantic.js +0 -134
  168. package/lib/checks/structural.js +0 -281
  169. package/lib/cli/commands-audit.mjs +0 -142
  170. package/lib/cli/commands-doc.mjs +0 -127
  171. package/lib/client-parts/audit/audit.js +0 -301
  172. package/lib/exempt/tool.js +0 -198
  173. package/lib/git/module-splitter.js +0 -47
  174. package/lib/link-check/index.js +0 -187
  175. package/lib/lint-adapter/detect.js +0 -161
  176. package/lib/lint-adapter/index.js +0 -50
  177. package/lib/lint-adapter/runner.js +0 -133
  178. package/lib/preprocess/audit.js +0 -98
  179. package/lib/preprocess/index.js +0 -78
  180. package/lib/rule/compilers/credential.js +0 -62
  181. package/lib/rule/compilers/dataflow.js +0 -38
  182. package/lib/rule/compilers/file-health.js +0 -75
  183. package/lib/rule/compilers/frontend.js +0 -86
  184. package/lib/rule/compilers/func.js +0 -35
  185. package/lib/rule/compilers/helpers.js +0 -71
  186. package/lib/rule/compilers/index.js +0 -29
  187. package/lib/rule/compilers/link-semantic.js +0 -45
  188. package/lib/rule/compilers/list-kinds.js +0 -12
  189. package/lib/rule/compilers/numeric-kinds.js +0 -73
  190. package/lib/rule/compilers/regex.js +0 -78
  191. package/lib/rule/compilers/structure.js +0 -107
  192. package/lib/rule/compilers.js +0 -17
  193. package/lib/rule/homoglyph.js +0 -45
  194. package/lib/rule/loader.js +0 -274
  195. package/lib/rule/registry.js +0 -122
  196. package/lib/rule/scope.js +0 -67
  197. package/lib/score/docs-score.js +0 -166
  198. package/lib/score/index.js +0 -234
  199. package/lib/user-requirements.json +0 -15
  200. package/scripts/__pycache__/module-splitter.cpython-38.pyc +0 -0
  201. package/scripts/audit-ext/_example-readme-present.mjs +0 -34
  202. package/scripts/audit-ext/dsh-inject-declarations.mjs +0 -209
  203. package/scripts/audit-ext/variable-min-length.mjs +0 -102
  204. package/scripts/audit-gate.mjs +0 -235
  205. package/scripts/audit-runner.mjs +0 -35
  206. package/scripts/audit-runtime-check.mjs +0 -129
  207. package/scripts/browser-page-probe.mjs +0 -271
  208. package/scripts/build-client.mjs +0 -131
  209. package/scripts/bump-version.mjs +0 -178
  210. package/scripts/check-js-scope.mjs +0 -87
  211. package/scripts/check.mjs +0 -203
  212. package/scripts/clean-date-comments.py +0 -102
  213. package/scripts/cpu-sample.mjs +0 -188
  214. package/scripts/doc-drift.mjs +0 -200
  215. package/scripts/doc-func.mjs +0 -212
  216. package/scripts/doc-tree.mjs +0 -458
  217. package/scripts/doc-version.mjs +0 -149
  218. package/scripts/hot-path-probe-cjs.cjs +0 -71
  219. package/scripts/hot-path-probe-fs-shim.mjs +0 -28
  220. package/scripts/hot-path-probe-fsp-shim.mjs +0 -31
  221. package/scripts/hot-path-probe.mjs +0 -153
  222. package/scripts/local-registry.mjs +0 -37
  223. package/scripts/module-splitter.py +0 -800
  224. package/scripts/picker-repro.mjs +0 -115
  225. package/scripts/platform-scan.mjs +0 -168
  226. package/scripts/probe-recheck.mjs +0 -47
  227. package/scripts/rename-locator.mjs +0 -97
  228. package/scripts/rule-switch.mjs +0 -97
  229. package/scripts/rules-solo-audit.mjs +0 -173
  230. package/scripts/scan-file-io.mjs +0 -717
  231. package/scripts/scan-fs-hotspots.mjs +0 -107
  232. package/scripts/scan-version.mjs +0 -125
  233. package/scripts/symbol-index.mjs +0 -85
  234. package/scripts/verify-prestep.mjs +0 -100
  235. package/scripts/version-source.mjs +0 -173
  236. package/skills/dev/audit-rule-authoring.md +0 -58
  237. package/skills/guide/guide-audit.md +0 -270
  238. /package/lib/{audit → app}/ownership.js +0 -0
  239. /package/lib/{audit-defaults.js → git/defaults.js} +0 -0
@@ -5,31 +5,54 @@
5
5
  // 进程契约**:跑一条命令、看退出码、解析一行 JSON。这样 Python / Go / Rust 写的引擎
6
6
  // 只要满足契约就能顶替,git 侧一行不用改。
7
7
  //
8
- // 契约(完整定义见 scripts/audit-gate.mjs 头部与 docs/ 下的「提交前预处理与审计引擎解耦方案」):
8
+ // 契约(完整定义见预处理实现 CLI 头部与 docs/ 下的「提交前预处理与审计引擎解耦方案」):
9
9
  // stdout : 一行 JSON { ok, scope, summary, quality, findings, files }
10
10
  // 退出码 : 0 = 无 blocker / 1 = 有 blocker / 2 = 执行失败
11
11
  // 超时 : 达到 timeoutMs 一律按「执行失败」处理
12
12
  //
13
13
  // 退出码 1 **不等于**「本次提交被拦」:示例目录豁免、临时豁免、私有库豁免都属于 git 侧判定
14
14
  // (依赖仓库语义 / 调用方参数 / GitHub 网络),引擎不知道也不该知道。所以本层只把
15
- // 「引擎说有 blocker」如实映射成 blocked 标志,**最终拦截判定仍由 runAudit 用自己的豁免规则做**。
15
+ // 「引擎说有 blocker」如实映射成 blocked 标志,**最终拦截判定仍由 runPreprocess 用豁免规则做**。
16
16
  //
17
17
  // 失败一律 fail-closed(拒绝提交):引擎崩了 / 超时 / 退出码非 0/1 / stdout 解析不了,
18
18
  // 都不能当成「审计通过」放行 —— 那是把红线交给「恰好没跑起来」。
19
19
 
20
20
  import { spawn } from 'node:child_process';
21
+ import { createHash } from 'node:crypto';
22
+ import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
23
+ import { tmpdir } from 'node:os';
24
+ import { join as joinPath } from 'node:path';
21
25
  import { existsSync, accessSync, constants as fsConstants } from 'node:fs';
22
26
  import { delimiter, isAbsolute, join, resolve } from 'node:path';
23
27
  import { fileURLToPath } from 'node:url';
24
28
 
25
29
  import { readSettings } from '../app/settings-bridge.js';
30
+ // 工作树快照用(阶段改动的差集比对;只读 git status,不做任何写操作)
31
+ import { gitRaw } from '../git/index.js';
26
32
  // 超时默认值取单一来源:schema 默认值与运行期兜底必须是同一个数字(见 lib/app/constants.js)
27
33
  import { PRE_COMMIT_TIMEOUT_MS_DEFAULT } from '../app/constants.js';
28
34
 
29
35
  export { PRE_COMMIT_TIMEOUT_MS_DEFAULT };
30
36
 
37
+ /** 阶段回执里「命中拦截的文件清单」最多列几个:只是给个线索,完整清单在 audit.blocked 里。 */
38
+ const BLOCKED_FILES_PREVIEW_MAX = 20;
39
+
31
40
  /** 内置轻量入口(相对插件根)。配置留空时用它。 */
32
- export const AUDIT_GATE_SCRIPT_REL = join('scripts', 'audit-gate.mjs');
41
+
42
+
43
+ /**
44
+ * 审计实现所属包名(拆包后审计实现在 `audit-sluice`)。
45
+ * 为什么单独一个常量:入口解析、错误提示、将来 npm 依赖安装后的路径都引用它,避免多处手写字符串。
46
+ */
47
+
48
+ /** 预处理实现的 CLI 入口(相对包根)。 */
49
+ export const PREPROCESS_CLI_REL = 'cli.mjs';
50
+
51
+ // 注意:这里不再写死具体实现的包名——包名属于 provider 定义(lib/preprocess/providers.js),
52
+ // 通用层只通过 provider 抽象拿它。将来换/加 provider 不需要改本文件。
53
+ import { resolveGateProvider, resolveProvider, listProviderManifests, getProviderDefinition, DEFAULT_PROVIDER_ID } from '../preprocess/providers.js';
54
+
55
+ export { resolveGateProvider };
33
56
 
34
57
  /** 错误信息里保留的 stderr 尾部字符数:够定位(栈尾通常在最后),又不至于把上下文刷爆。 */
35
58
  export const STDERR_TAIL_CHARS = 2000;
@@ -37,7 +60,7 @@ export const STDERR_TAIL_CHARS = 2000;
37
60
  /** stdout 收集上限(64MB):findings 全量在大仓可达数 MB,超这个量级说明契约跑偏,宁可报错。 */
38
61
  export const STDOUT_MAX_BYTES = 64 * 1024 * 1024;
39
62
 
40
- /** 契约退出码(与 scripts/audit-gate.mjs 的 EXIT_* 常量对应)。 */
63
+ /** 契约退出码(与预处理实现 CLI 的 EXIT_* 常量对应)。 */
41
64
  export const ENGINE_EXIT_OK = 0;
42
65
  export const ENGINE_EXIT_BLOCKED = 1;
43
66
  export const ENGINE_EXIT_FAILED = 2;
@@ -75,19 +98,152 @@ export function resolvePreCommitConfig(cfg = {}) {
75
98
  ? raw.args.map((rawArg) => String(rawArg)).filter((rawArg) => rawArg !== '')
76
99
  : [];
77
100
  // 内置默认只在「command 与 args 都没配」时生效:
78
- // · command 空 + args 空 → node + 插件自带 scripts/audit-gate.mjs
101
+ // · command 空 + args 空 → node + 预处理实现 CLI
79
102
  // · command 空 + args 有值 → node + 配置里给的引擎脚本(args 里相对路径按插件根解析)
80
103
  // · command 有值 + args 空 → 那是一个独立可执行文件(Go/Rust 单二进制就是这种形态,
81
104
  // 此时**不能**塞我们自己的脚本路径进去)
82
- const args = (!command && configuredArgs.length === 0)
83
- ? [join(pluginRootDir(), AUDIT_GATE_SCRIPT_REL)]
84
- : configuredArgs;
105
+ // 缺省引擎 = 预处理实现的 CLI;显式配置 command/args 时以配置为准(换引擎只改配置)。
106
+ let args = configuredArgs;
107
+ if (!command && configuredArgs.length === 0) {
108
+ const entry = resolveGateProvider();
109
+ // 解析失败也把"期望的路径"放进 args:真正的失败在 spawn 前由 runPreCommitEngine 报出,
110
+ // 错误信息里带上具体查过哪些路径(否则用户只看到"命令不存在",不知道该怎么办)。
111
+ args = entry.ok ? [entry.path] : [join(pluginRootDir(), '..', getProviderDefinition(DEFAULT_PROVIDER_ID).packageName, PREPROCESS_CLI_REL)];
112
+ }
85
113
  const rawTimeout = Number(raw?.timeoutMs);
86
114
  // 超时必须是正有限数:0 / 负数 / NaN 一律退回默认(0 表示「立刻超时」会让门禁永远失败)
87
115
  const timeoutMs = Number.isFinite(rawTimeout) && rawTimeout > 0 ? Math.floor(rawTimeout) : PRE_COMMIT_TIMEOUT_MS_DEFAULT;
88
116
  return { command, args, timeoutMs, source };
89
117
  }
90
118
 
119
+ /**
120
+ * 旧版开关键名(历史配置里这个键就是「提交前检查开不开」)。
121
+ * 单独提常量是为了让「还在兼容什么」一目了然,也便于将来彻底删除时 grep 到唯一出处。
122
+ */
123
+ const LEGACY_ENABLED_KEY = 'auditEnabled';
124
+
125
+ /**
126
+ * 合法失败语义(provider 声明或用户配置只允许这三个值;其余一律当"没声明"处理)。
127
+ * @type {ReadonlyArray<string>}
128
+ */
129
+ export const STAGE_ON_FAIL = Object.freeze(['block', 'warn', 'skip']);
130
+
131
+ /**
132
+ * 解析「有序阶段链」配置。
133
+ *
134
+ * 两种形态,语义严格区分(向后兼容是硬要求):
135
+ * · `preCommit.stages` 为空/未配 ⇒ `mode:'legacy'`:**完全走原来的单命令路径**
136
+ * (`command`/`args`,缺省就是门禁 provider 的 CLI),行为与升级前逐字段一致
137
+ * · 非空 ⇒ `mode:'chain'`:按数组顺序逐阶段执行,每阶段独立超时与失败语义
138
+ *
139
+ * onFail 的解析**不看 provider 名字**(写死"audit 拦截 / format 警告"就是把具体实现
140
+ * 固化进宿主,正是要清掉的耦合):用户配置 > provider manifest 的 defaultOnFail > 'block'。
141
+ * 其中 manifest 那一步需要异步读包,放在执行阶段做(见 resolveStageOnFail)。
142
+ *
143
+ * @param {object} [cfg] 运行期配置
144
+ * @returns {{mode: 'legacy'|'chain', stages: Array<{provider: string, onFail: string, timeoutMs: number}>}}
145
+ */
146
+ export function resolveStages(cfg = {}, paramStages = null) {
147
+ const block = (cfg && typeof cfg.preCommit === 'object' && cfg.preCommit) || {};
148
+ // 优先级:调用参数 > 配置 stages > (由调用方按 command/default 处理)
149
+ const fromParam = Array.isArray(paramStages) && paramStages.length ? paramStages : null;
150
+ const raw = fromParam || (Array.isArray(block.stages) ? block.stages : []);
151
+ const source = fromParam ? 'param' : 'config';
152
+ const stages = raw
153
+ .map((stage, index) => normalizeStageItem(stage, index))
154
+ .filter(Boolean);
155
+ if (!stages.length) return { mode: 'legacy', stages: [], source: 'config' };
156
+ return { mode: 'chain', stages: stages, source: source };
157
+ }
158
+
159
+ /**
160
+ * 归一化单个阶段条目(两种合法形态 + 明确报错)。
161
+ *
162
+ * A. `{ provider }` —— 走 provider 注册表解析(已有通道)
163
+ * B. `{ command, args? }` —— 跑任意脚本(**不要求**对方声明是"我们的扩展")
164
+ *
165
+ * 非法时抛错(`StageConfigError`):参数写错要在跑任何 git 操作之前就失败,
166
+ * 不能等到 spawn 才发现——那会把"配置写错"表现成"提交时莫名报错"。
167
+ * @param {object} stage 原始条目
168
+ * @param {number} index 序号(错误信息里用)
169
+ * @returns {object}
170
+ */
171
+ function normalizeStageItem(stage, index) {
172
+ const declaredStage = (stage && typeof stage === 'object') ? stage : null;
173
+ if (!declaredStage) throw new StageConfigError(`预处理阶段第 ${index + 1} 项不是对象`);
174
+ const provider = String(declaredStage.provider || '').trim();
175
+ const command = String(declaredStage.command || '').trim();
176
+ if (provider && command) throw new StageConfigError(`预处理阶段第 ${index + 1} 项同时给了 provider 和 command(只能二选一)`);
177
+ if (!provider && !command) throw new StageConfigError(`预处理阶段第 ${index + 1} 项既没有 provider 也没有 command`);
178
+ const onFailRaw = String(declaredStage.onFail || '').trim();
179
+ const timeoutMs = Number(declaredStage.timeoutMs);
180
+ const base = {
181
+ index: index,
182
+ // 空串 = 交给 provider 声明(provider 形态)/ 直接兜底 block(command 形态)
183
+ onFail: STAGE_ON_FAIL.includes(onFailRaw) ? onFailRaw : '',
184
+ timeoutMs: Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.floor(timeoutMs) : 0,
185
+ };
186
+ if (provider) return { ...base, kind: 'provider', provider: provider };
187
+ const args = Array.isArray(declaredStage.args) ? declaredStage.args.map((a) => String(a)) : [];
188
+ return { ...base, kind: 'command', command: command, args: args };
189
+ }
190
+
191
+ /** 阶段配置错误(与"引擎跑失败"区分开:那是执行错误,这是配置错误)。 */
192
+ export class StageConfigError extends Error {
193
+ constructor(message) {
194
+ super(message);
195
+ this.name = 'StageConfigError';
196
+ }
197
+ }
198
+
199
+ /**
200
+ * 定某阶段的失败语义:用户配置 > provider manifest 的 defaultOnFail > 'block'。
201
+ *
202
+ * 为什么默认是 block:没声明就等于没承诺"失败也没关系"——放行一个跑失败的阶段,
203
+ * 等于把"恰好没跑起来"当成"通过"(与门禁 fail-closed 同一原则)。
204
+ * 想让格式化失败只警告的实现方,在自己的 manifest 里写 `defaultOnFail: 'warn'` 即可。
205
+ * @param {{onFail: string}} stage resolveStages 的条目
206
+ * @param {object|null} manifest provider 的 preprocessManifest(可为 null)
207
+ * @returns {'block'|'warn'|'skip'}
208
+ */
209
+ export function resolveStageOnFail(stage, manifest) {
210
+ const fromUser = stage && STAGE_ON_FAIL.includes(stage.onFail) ? stage.onFail : '';
211
+ if (fromUser) return fromUser;
212
+ const fromManifest = manifest && STAGE_ON_FAIL.includes(manifest.defaultOnFail) ? manifest.defaultOnFail : '';
213
+ if (fromManifest) return fromManifest;
214
+ return 'block';
215
+ }
216
+
217
+ /**
218
+ * 判断「提交前预处理要不要跑」(`preCommit.enabled`)。
219
+ *
220
+ * 判定顺序(**先看用户实际写下的配置,再看运行期默认值**):
221
+ * ① `config.json` 里的 `preCommit.enabled`(用户显式配过)
222
+ * ② `config.json` 里的旧版开关键(LEGACY_ENABLED_KEY):直接忽略等于让「本来开着的门禁
223
+ * 悄悄关掉」,这是最难发现的一类行为变化;读回时把来源标出来,用户能看到「本次沿用旧键」
224
+ * ③ 运行期 cfg 的 `preCommit.enabled`(schema 默认值 / 调用方显式传入)
225
+ * ④ 关
226
+ * 为什么 ①② 在 ③ 之前:schema 有默认值,运行期 cfg 里**永远**有 `preCommit.enabled:false`,
227
+ * 若先看 cfg 就永远读不到用户写下的真值(旧键也就永远失效)。
228
+ * @param {object} [cfg] 运行期配置
229
+ * @returns {{enabled: boolean, source: 'config.json'|'legacy'|'cfg'|'default'}}
230
+ */
231
+ export function resolvePreCommitEnabled(cfg = {}) {
232
+ let fileSettings = null;
233
+ try {
234
+ fileSettings = readSettings({});
235
+ } catch {
236
+ // 配置读不到(无 DSH_HOME / 坏 JSON)→ 当作没配,不让读盘失败影响提交
237
+ fileSettings = null;
238
+ }
239
+ const fileBlock = fileSettings && typeof fileSettings.preCommit === 'object' ? fileSettings.preCommit : null;
240
+ if (typeof fileBlock?.enabled === 'boolean') return { enabled: fileBlock.enabled, source: 'config.json' };
241
+ const legacyEnabled = fileSettings?.[LEGACY_ENABLED_KEY];
242
+ if (typeof legacyEnabled === 'boolean') return { enabled: legacyEnabled, source: 'legacy' };
243
+ if (typeof cfg?.preCommit?.enabled === 'boolean') return { enabled: cfg.preCommit.enabled, source: 'cfg' };
244
+ return { enabled: false, source: 'default' };
245
+ }
246
+
91
247
  /**
92
248
  * 取 preCommit 配置块(两档来源 + 来源标记)。
93
249
  * @param {object} cfg
@@ -208,24 +364,32 @@ function toSlotCsv(slots) {
208
364
  /**
209
365
  * 组装传给引擎的完整参数表(**由本模块统一追加,调用方不拼**)。
210
366
  * 排序固定:先配置里的 args,再契约参数 —— 契约参数在最后,任何引擎都能靠「尾部固定段」解析。
367
+ *
368
+ * 参数只有两类,**界线不能含糊**(宿主/实现分家后的核心约定):
369
+ * ① **调用上下文**(宿主才知道的):repo / 仓库可见性 / 本次临时豁免 / findings 粒度
370
+ * —— 这些是「这一次提交的事实」,不是配置,必须由宿主传给引擎;
371
+ * ② **实现自己的配置**(怎么审):扫描范围 / 权重 / 规则槽位 / 文件数上限
372
+ * —— 属预处理实现自己的 config.json,宿主**不传**(传了等于宿主继续替它做配置决策,
373
+ * 两包就还是耦合的)。命令行 `--scope` 等只用于「显式覆盖」,由调用方在需要时给。
211
374
  * @param {object} p
212
375
  * @returns {string[]}
213
376
  */
214
377
  export function buildEngineArgs({
215
- args = [], repoPath = '', scope = 'diff', rulesetDir = '', weights = {}, maxScanFiles, slots = [], disabledSlots = [], blockersOnly = false,
378
+ args = [], repoPath = '', rulesetDir = '', blockersOnly = false,
379
+ visibility = '', exemptPaths = [], exemptReason = '',
216
380
  } = {}) {
217
381
  const argv = [...resolveEngineArgs(args)];
218
382
  argv.push('--repo', String(repoPath || '.'));
219
- argv.push('--scope', scope === 'full' ? 'full' : 'diff');
383
+ // 自定规则目录是**调用方显式指定**(工具 ruleset 参数 / API 传参),不是宿主配置,故保留透传。
220
384
  if (rulesetDir) argv.push('--ruleset', String(rulesetDir));
221
- if (weights && typeof weights === 'object' && Object.keys(weights).length) argv.push('--weights', JSON.stringify(weights));
222
- // maxScanFiles 只在拿到有限数时才传:0 有明确含义(不限),所以不能用 truthy 判断
223
- if (Number.isFinite(Number(maxScanFiles))) argv.push('--max-scan-files', String(Number(maxScanFiles)));
224
- // 槽位清单只在「确实有内容」时才传:空数组传成空字符串会被引擎当成一个空槽位名
225
- const whiteListCsv = toSlotCsv(slots);
226
- if (whiteListCsv) argv.push('--slots', whiteListCsv);
227
- const blackListCsv = toSlotCsv(disabledSlots);
228
- if (blackListCsv) argv.push('--disabled-slots', blackListCsv);
385
+ // 可见性:只有明确知道时才传(unknown 是引擎缺省,传了也一样);
386
+ // 私有库豁免由预处理实现自己判(它是权威),gitpush 只负责探测后把结论传过去。
387
+ if (visibility === 'private' || visibility === 'public') argv.push('--visibility', visibility);
388
+ // 临时豁免:**参数名映射** —— 工具参数叫 auditExemptPaths/auditExemptReason,
389
+ // 预处理实现 CLI 叫 --exempt-paths/--exempt-reason(独立包不需要 audit- 前缀)。
390
+ const exemptCsv = toSlotCsv(exemptPaths);
391
+ if (exemptCsv) argv.push('--exempt-paths', exemptCsv);
392
+ if (exemptReason) argv.push('--exempt-reason', String(exemptReason));
229
393
  if (blockersOnly) argv.push('--blockers-only');
230
394
  argv.push('--json');
231
395
  return argv;
@@ -287,7 +451,7 @@ export function parseEngineStdout(stdout) {
287
451
  * @returns {Promise<{ok: true, stdout: string, stderr: string, exitCode: number|null, signal: string|null}
288
452
  * | {ok: false, stage: 'timeout'|'too-large'|'spawn', error: string, stderr: string}>}
289
453
  */
290
- function runEngineProcess({ command, args, timeoutMs }) {
454
+ function runEngineProcess({ command, args, timeoutMs, env }) {
291
455
  return new Promise((settle) => {
292
456
  let stdout = '';
293
457
  let stderr = '';
@@ -306,7 +470,8 @@ function runEngineProcess({ command, args, timeoutMs }) {
306
470
  const killChild = () => { try { child?.kill('SIGKILL'); } catch { /* 进程可能已退出 */ } };
307
471
 
308
472
  try {
309
- child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] });
473
+ // env 是**追加**的:不给就完全继承父进程环境(旧行为不变)
474
+ child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...(env || {}) } });
310
475
  } catch (e) {
311
476
  finish({ ok: false, stage: 'spawn', error: String(e?.message || e), stderr });
312
477
  return;
@@ -340,10 +505,7 @@ function runEngineProcess({ command, args, timeoutMs }) {
340
505
  * 跑提交前预处理引擎。
341
506
  * @param {object} p
342
507
  * repoPath : 仓库绝对路径(相对路径按当前工作目录解析,与旧行为一致)
343
- * scope : 'diff' | 'full'
344
- * rulesetDir: 自定规则目录(透传,不解析——旧行为就是原样传给审计)
345
- * weights : 已解析好的权重覆盖对象(空对象 = 默认权重表)
346
- * maxScanFiles / slots / disabledSlots:来自插件配置的审计选项(不传则用引擎默认值)
508
+ * rulesetDir: 自定规则目录(调用方显式指定,透传不解析)
347
509
  * blockersOnly: findings 只留 blocker
348
510
  * cfg : 运行期配置(读 preCommit)
349
511
  * timeoutMs : 覆盖超时(测试用)
@@ -351,28 +513,51 @@ function runEngineProcess({ command, args, timeoutMs }) {
351
513
  * engine?: {command: string, args: string[], exitCode: number|null, timedOut: boolean}}>}
352
514
  */
353
515
  export async function runPreCommitEngine({
354
- repoPath = '.', scope = 'diff', rulesetDir = '', weights = {}, maxScanFiles, slots = [], disabledSlots = [],
355
- blockersOnly = false, cfg = {}, timeoutMs,
516
+ repoPath = '.', rulesetDir = '', blockersOnly = false,
517
+ cfg = {}, timeoutMs, visibility = '', exemptPaths = [], exemptReason = '',
518
+ env = null,
356
519
  } = {}) {
357
520
  const spec = resolvePreCommitConfig(cfg);
521
+ // 预处理实现是**可热插拔的扩展能力**:不在位时不该拦住提交,而应当「跳过审计并明确标注」。
522
+ // 这正是解耦的目标——拔掉扩展,主流程照常;插上扩展,能力自动回来。
523
+ // 注意:这里返回的是「跳过」而不是「静默通过」,调用方能拿到 preprocessSkipped 与原因。
524
+ // 「不在位」的判据 = **实现包的 CLI 入口文件不存在**,与有没有显式配置 command 无关:
525
+ // 用户完全可能把 preCommit.command 配成 `node` + args 指到包里的 cli.mjs,
526
+ // 此时包被拔掉(optionalDependency 未装)也属「扩展没插」,不该拦提交;
527
+ // 而自定义引擎换成别的脚本名时不会命中这条,仍是 fail-closed(那是配置错,不是缺扩展)。
528
+ const missingProviderEntry = spec.args.find((rawArg) => {
529
+ const text = String(rawArg || '');
530
+ return text.endsWith(PREPROCESS_CLI_REL) && isAbsolute(text) && !existsSync(text);
531
+ });
532
+ if (missingProviderEntry) {
533
+ const entry = resolveGateProvider();
534
+ return {
535
+ ok: true,
536
+ audit: null,
537
+ preprocessSkipped: 'package-not-found',
538
+ skipReason: entry.ok ? '预处理实现不可用' : entry.error,
539
+ engine: { command: '', args: [], exitCode: null, timedOut: false },
540
+ };
541
+ }
358
542
  const resolved = resolveEngineCommand(spec.command);
543
+ // 显式配置的引擎命令不可用 ⇒ 这是配置错误(不是「扩展不在位」),仍然 fail-closed
359
544
  if (!resolved.ok) return failClosed(`提交前预处理失败:${resolved.error}(未执行任何 git 操作;修复 preCommit.command 后重试)`);
360
545
  const command = resolved.command;
361
- const args = buildEngineArgs({ args: spec.args, repoPath, scope, rulesetDir, weights, maxScanFiles, slots, disabledSlots, blockersOnly });
546
+ const args = buildEngineArgs({ args: spec.args, repoPath, rulesetDir, blockersOnly, visibility, exemptPaths, exemptReason });
362
547
  const commandLine = formatCommandLine(command, args);
363
548
  const effectiveTimeout = Number.isFinite(Number(timeoutMs)) && Number(timeoutMs) > 0
364
549
  ? Math.floor(Number(timeoutMs))
365
550
  : spec.timeoutMs;
366
- const run = await runEngineProcess({ command, args, timeoutMs: effectiveTimeout });
551
+ const run = await runEngineProcess({ command, args, timeoutMs: effectiveTimeout, env: env });
367
552
 
368
553
  if (!run.ok) {
369
554
  const label = run.stage === 'timeout' ? '超时' : run.stage === 'too-large' ? '输出超限' : '无法启动';
370
- return failClosed(`提交前预处理失败:引擎${label}(${run.error})\n 命令:${commandLine}\n stderr: ${stderrTail(run.stderr) || '(空)'}\n (未执行任何 git 操作;修复引擎或临时关闭 auditEnabled 后重试)`);
555
+ return failClosed(`提交前预处理失败:引擎${label}(${run.error})\n 命令:${commandLine}\n stderr: ${stderrTail(run.stderr) || '(空)'}\n (未执行任何 git 操作;修复引擎或临时关闭 preCommit.enabled 后重试)`);
371
556
  }
372
557
  const { exitCode, signal, stdout, stderr } = run;
373
558
  if (exitCode !== ENGINE_EXIT_OK && exitCode !== ENGINE_EXIT_BLOCKED) {
374
559
  const codeText = exitCode === null ? `被信号 ${signal || '?'} 终止` : `退出码 ${exitCode}`;
375
- return failClosed(`提交前预处理失败:引擎 ${commandLine} ${codeText}\n stderr: ${stderrTail(stderr) || '(空)'}\n (未执行任何 git 操作;修复引擎或临时关闭 auditEnabled 后重试)`);
560
+ return failClosed(`提交前预处理失败:引擎 ${commandLine} ${codeText}\n stderr: ${stderrTail(stderr) || '(空)'}\n (未执行任何 git 操作;修复引擎或临时关闭 preCommit.enabled 后重试)`);
376
561
  }
377
562
  const parsed = parseEngineStdout(stdout);
378
563
  if (!parsed.ok) {
@@ -386,3 +571,417 @@ export async function runPreCommitEngine({
386
571
  engine: { command, args, exitCode, timedOut: false },
387
572
  };
388
573
  }
574
+
575
+ /**
576
+ * 跑「提交前预处理流水线」——阶段链的入口。
577
+ *
578
+ * 与 `runPreCommitEngine` 的分工:后者是**单次执行**(解析命令 → spawn → 按契约解释结果),
579
+ * 本函数只做「按配置决定跑几个阶段、按什么顺序、失败了怎么办」,不重复实现执行细节。
580
+ *
581
+ * 三种形态:
582
+ * · `preCommit.stages` 未配/空 ⇒ **原样调用 runPreCommitEngine**(回执与升级前逐字段一致)
583
+ * · 只配一个阶段 ⇒ 也走同一条单次执行路径(按该阶段 provider 的 CLI 跑),回执形状不变
584
+ * · 多阶段 ⇒ 按数组顺序逐阶段执行;每阶段独立超时;失败语义见 resolveStageOnFail
585
+ *
586
+ * @param {object} opts 与 runPreCommitEngine 相同的入参(repoPath / visibility / exemptPaths / cfg / …)
587
+ * @returns {Promise<object>} legacy/单阶段:与 runPreCommitEngine 同形状;
588
+ * 多阶段:在它基础上追加 `preprocessStages`(逐阶段回执)等 additive 字段
589
+ */
590
+ export async function runPreCommitPipeline(opts = {}) {
591
+ let plan;
592
+ try {
593
+ plan = resolveStages(opts.cfg, opts.stages);
594
+ } catch (e) {
595
+ // 配置错误要在**跑任何 git 操作之前**就失败(runPreprocess 在 add/commit 之前调用)
596
+ return failClosed(`提交前预处理失败:${e && e.message ? e.message : e}`);
597
+ }
598
+ // ── 兼容路径:没配阶段链 ⇒ 行为与升级前完全一致(不追加任何字段)──
599
+ if (plan.mode === 'legacy') {
600
+ // 单命令 / 单 provider 兜底:回执不变,只补一个来源标识(additive,便于观测本次跑的是谁)
601
+ const legacy = await runPreCommitEngine(opts);
602
+ const block = (opts.cfg && opts.cfg.preCommit) || {};
603
+ const legacySource = (block.command || (Array.isArray(block.args) && block.args.length)) ? 'command' : 'default';
604
+ return { ...legacy, stagesSource: legacySource };
605
+ }
606
+ // ── 配了 stages(哪怕只有一个):一律走链执行 ──
607
+ // 为什么单阶段也走链:这样"改了哪些文件"(preprocessChanges)对单阶段同样可用,
608
+ // 否则「只配了一个格式化 provider」的用户永远看不到改动清单。
609
+ // 代价仅是回执多出 additive 字段(preprocessStages / preprocessChanges),
610
+ // 拦截决策与执行路径完全复用同一实现。
611
+ return runChain(plan.stages, opts, plan.source || 'config');
612
+ }
613
+
614
+ /** 单文件内容指纹(读不到/非普通文件返回空串,不抛)。 */
615
+ function fileFingerprint(absPath) {
616
+ try {
617
+ const st = statSync(absPath);
618
+ if (!st.isFile()) return 'nonfile';
619
+ const buf = readFileSync(absPath);
620
+ return createHash('sha256').update(buf).digest('hex').slice(0, 16);
621
+ } catch { return ''; }
622
+ }
623
+
624
+ /** 工作树快照上限:超过就退化为「只比状态码」,避免大改动拖慢提交。 */
625
+ const STAGE_SNAPSHOT_MAX_FILES = 500;
626
+
627
+ /**
628
+ * 拍一次工作树快照:`git status --porcelain` 列出的每个路径 → `状态码|大小|内容指纹`。
629
+ *
630
+ * 为什么不能只比状态码:格式化器改写一个**本来就已经是 M** 的文件时,status 前后都是 " M",
631
+ * 只看状态码会得出"没改动"的假结论(这正是要防的)。
632
+ * 为什么不只看 mtime:跑两次格式化,第二次内容完全相同时 mtime 仍会变 ⇒ 会把幂等误报成有改动。
633
+ * ⇒ 用**内容指纹**,幂等才是真的幂等。
634
+ * @param {string} repoPath 仓库绝对路径
635
+ * @returns {{ok: boolean, files: Map<string,string>, truncated?: boolean}}
636
+ */
637
+ export function snapshotWorktree(repoPath) {
638
+ // 必须用 gitRaw + -z:runGit 会 trim 输出,而 porcelain 的状态首列**可能就是一个空格**
639
+ // (未暂存修改 = " M")——trim 会把那个空格吃掉,路径整体左移一位,
640
+ // 结果得到 ".js" 这种假路径(本函数第一版就是这么错的,靠"改动清单里没有 a.js"抓到)。
641
+ // -z 分隔的原始字节不受 trim 影响。
642
+ const res = gitRaw(['status', '--porcelain', '-z'], { cwd: repoPath });
643
+ const files = new Map();
644
+ if (res.error || res.status === null) return { ok: false, files: files };
645
+ const entries = res.stdout.toString('utf8').split('\0').filter((entry) => entry.length > 2);
646
+ const truncated = entries.length > STAGE_SNAPSHOT_MAX_FILES;
647
+ for (const line of entries.slice(0, STAGE_SNAPSHOT_MAX_FILES)) {
648
+ // porcelain v1 -z:每项 "XY path"(重命名是 "XY new\0old",旧路径项会被上面的长度过滤挡住)
649
+ const code = line.slice(0, 2);
650
+ let rel = line.slice(3);
651
+ rel = rel.replace(/^"|"$/g, '');
652
+ if (!rel) continue;
653
+ const abs = joinPath(repoPath, rel);
654
+ const size = (() => { try { return String(statSync(abs).size); } catch { return '0'; } })();
655
+ const fp = truncated ? '' : fileFingerprint(abs);
656
+ files.set(rel, code + '|' + size + '|' + fp);
657
+ }
658
+ return { ok: true, files: files, ...(truncated ? { truncated: true } : {}) };
659
+ }
660
+
661
+ /**
662
+ * 两次快照的差集 = 这一阶段到底改了什么。
663
+ *
664
+ * 判定:
665
+ * · 只在 after 里 ⇒ 新增
666
+ * · 只在 before 里 ⇒ 删除(格式化器不会删,但"会改文件"的 provider 可能)
667
+ * · 两边都有但指纹/大小/状态码不同 ⇒ 修改(**这是格式化最常见的形态**)
668
+ * @param {Map<string,string>} before
669
+ * @param {Map<string,string>} after
670
+ * @returns {{added: number, modified: number, deleted: number, files: string[]}}
671
+ */
672
+ export function diffSnapshots(before, after) {
673
+ const added = [];
674
+ const modified = [];
675
+ const deleted = [];
676
+ for (const [rel, sig] of after) {
677
+ if (!before.has(rel)) { added.push(rel); continue; }
678
+ if (before.get(rel) !== sig) modified.push(rel);
679
+ }
680
+ for (const rel of before.keys()) if (!after.has(rel)) deleted.push(rel);
681
+ return {
682
+ added: added.length,
683
+ modified: modified.length,
684
+ deleted: deleted.length,
685
+ files: [...added, ...modified, ...deleted].sort(),
686
+ };
687
+ }
688
+
689
+ /**
690
+ * 顺序执行阶段链。
691
+ *
692
+ * 语义(与配置解耦,宿主不认 provider 名字):
693
+ * · **顺序**:数组顺序即执行顺序,前一个跑完才跑下一个(格式化必须先于审计改完文件)
694
+ * · **每阶段独立超时**:stage.timeoutMs > 0 时覆盖全局超时
695
+ * · **失败语义**:resolveStageOnFail(用户 > provider 声明 > 'block')
696
+ * block ⇒ 立即中断并拒绝提交;warn ⇒ 记警告继续;skip ⇒ 静默跳过继续
697
+ * · **实现不在位**(provider 没装)不算失败 ⇒ 记 `skipped` + 警告,继续下一阶段
698
+ * (与单阶段「拔掉扩展仍能提交」的热插拔语义一致)
699
+ * @param {Array<{provider: string, onFail: string, timeoutMs: number}>} stages
700
+ * @param {object} opts 与 runPreCommitEngine 相同
701
+ * @returns {Promise<object>} 追加 `preprocessStages`(逐阶段回执)与可选 `preprocessWarnings`
702
+ */
703
+ async function runChain(stages, opts = {}, chainSource = 'config') {
704
+ const stageReceipts = [];
705
+ const warnings = [];
706
+ const allChanged = [];
707
+ let lastAudit = null;
708
+ let lastEngine = null;
709
+ let lastSkipped = null;
710
+
711
+ // 一次性取全部在位 provider 的声明(onFail 的默认值来自它;读不到就当没声明)
712
+ let manifestsById = new Map();
713
+ try {
714
+ const listed = await listProviderManifests();
715
+ manifestsById = new Map((listed.manifests || []).map((m) => [m.provider.id, m.manifest]));
716
+ } catch { /* 读不到声明不影响执行:onFail 退回默认 block */ }
717
+
718
+ // 链开始时的「本次改动」:这就是用户马上要提交的那批文件(格式化要处理的正是它们)
719
+ const initialSnap = snapshotWorktree(opts.repoPath || '.');
720
+ const changedSoFar = new Set(initialSnap.ok ? [...initialSnap.files.keys()] : []);
721
+ const envDir = mkdtempSync(joinPath(tmpdir(), 'dsh-preprocess-'));
722
+
723
+ try {
724
+ for (const stage of stages) {
725
+ const startedAt = Date.now();
726
+ // 两种阶段形态:provider(走注册表解析)与 command(跑任意脚本,不要求对方声明)
727
+ const stageLabel = stage.kind === 'provider' ? stage.provider : commandLabelOf(stage.command);
728
+ let providerEntry = null;
729
+ if (stage.kind === 'provider') {
730
+ providerEntry = resolveProvider(stage.provider);
731
+ if (!providerEntry.ok) {
732
+ // 两种"解析失败"必须分开处理,否则会把配置错当成"没装"而静默放行:
733
+ // ① provider 名字不在注册表里 ⇒ 配置写错了 ⇒ fail-closed(打错一个字母就让整道门禁消失,太危险)
734
+ // ② 注册过但入口文件不在 ⇒ 扩展没装 ⇒ 跳过 + 警告,不拦提交(热插拔语义)
735
+ if (!getProviderDefinition(stage.provider)) {
736
+ return failClosed(`提交前预处理失败:阶段配置里的 provider 「${stage.provider}」未注册(已注册:audit 等,见 lib/preprocess/providers.js)`);
737
+ }
738
+ stageReceipts.push({ provider: stageLabel, ok: true, skipped: 'provider-not-found', ms: 0, error: providerEntry.error });
739
+ warnings.push(`${stageLabel}: 未安装/入口不可用,已跳过该阶段`);
740
+ lastSkipped = { preprocessSkipped: 'package-not-found', skipReason: providerEntry.error };
741
+ continue;
742
+ }
743
+ }
744
+ const onFail = resolveStageOnFail(stage, stage.kind === 'provider' ? (manifestsById.get(stage.provider) || null) : null);
745
+ // 改动的可见性:阶段前后各拍一次工作树快照,差集就是它改了哪些文件。
746
+ // 放在宿主而不是要求 provider 上报:任何"会改文件"的实现(格式化/自动修复/锁更新)都通用。
747
+ const beforeSnap = snapshotWorktree(opts.repoPath || '.');
748
+ // 把「本次改动」以**环境变量**的形式交给实现方(想读就读,不读就当没看见 ⇒ 不改变既有契约)。
749
+ // 换行分隔而不是逗号:文件名里可以有逗号,换行几乎不可能。
750
+ // 同时落一份文件路径:文件很多时单个环境变量会撞 128KB 上限。
751
+ const stageEnv = buildStageEnv({
752
+ repoPath: opts.repoPath || '.',
753
+ provider: stage.provider,
754
+ changed: [...changedSoFar],
755
+ envDir: envDir,
756
+ });
757
+ const stageCfg = stage.kind === 'provider'
758
+ ? withStageOverride(opts.cfg, providerEntry.path, stage.timeoutMs)
759
+ : withCommandStage(opts.cfg, stage, {
760
+ repo: opts.repoPath || '.',
761
+ filesFile: stageEnv.listFile,
762
+ filesCount: String(changedSoFar.size),
763
+ stage: String(stageReceipts.length + 1),
764
+ }, stage.timeoutMs);
765
+ const res = await runPreCommitEngine({ ...opts, cfg: stageCfg, env: stageEnv.env });
766
+ const afterSnap = snapshotWorktree(opts.repoPath || '.');
767
+ const changed = (beforeSnap.ok && afterSnap.ok) ? diffSnapshots(beforeSnap.files, afterSnap.files) : null;
768
+ const ms = Date.now() - startedAt;
769
+ const providerSkipped = !!res.preprocessSkipped;
770
+ const hitBlockers = res.ok === true && res.blocked === true;
771
+ const failed = res.ok !== true;
772
+
773
+ stageReceipts.push({
774
+ provider: stageLabel,
775
+ ...(stage.kind === 'command' ? { kind: 'command' } : {}),
776
+ ok: !failed && !hitBlockers,
777
+ onFail: onFail,
778
+ ms: ms,
779
+ ...(providerSkipped ? { skipped: res.preprocessSkipped, reason: res.skipReason || '' } : {}),
780
+ ...(hitBlockers ? { blocked: blockedSummaryOf(res) } : {}),
781
+ ...(failed ? { error: res.error || '执行失败' } : {}),
782
+ // 本阶段改动的文件清单(null = 拍不到快照,例如非 git 目录)
783
+ ...(changed ? { changed: changed } : {}),
784
+ });
785
+ allChanged.push(...((changed && changed.files) || []));
786
+ for (const rel of (changed && changed.files) || []) changedSoFar.add(rel);
787
+ if (res.engine) lastEngine = res.engine;
788
+ if (res.audit) lastAudit = res.audit;
789
+ if (providerSkipped) { lastSkipped = { preprocessSkipped: res.preprocessSkipped, skipReason: res.skipReason || '' }; continue; }
790
+
791
+ if (failed) {
792
+ if (onFail === 'warn') { warnings.push(`${stage.provider}: ${res.error || '执行失败'}(该阶段为 warn,继续)`); continue; }
793
+ if (onFail === 'skip') continue;
794
+ // block:中断整条链,拒绝提交(保留可诊断信息 + 已跑阶段的回执)
795
+ return {
796
+ ...res,
797
+ preprocessStages: stageReceipts,
798
+ preprocessChanges: { total: new Set(allChanged).size, files: [...new Set(allChanged)].sort() },
799
+ ...(warnings.length ? { preprocessWarnings: warnings } : {}),
800
+ };
801
+ }
802
+ if (hitBlockers) {
803
+ if (onFail === 'warn') { warnings.push(`${stage.provider}: 命中拦截项(该阶段为 warn,仅记录)`); continue; }
804
+ if (onFail === 'skip') continue;
805
+ return {
806
+ ok: true,
807
+ blocked: true,
808
+ audit: res.audit || null,
809
+ engine: res.engine || null,
810
+ preprocessStages: stageReceipts,
811
+ preprocessChanges: { total: new Set(allChanged).size, files: [...new Set(allChanged)].sort() },
812
+ ...(warnings.length ? { preprocessWarnings: warnings } : {}),
813
+ };
814
+ }
815
+ }
816
+
817
+ return {
818
+ ok: true,
819
+ blocked: false,
820
+ audit: lastAudit,
821
+ engine: lastEngine,
822
+ ...(lastSkipped && !lastAudit ? lastSkipped : {}),
823
+ preprocessStages: stageReceipts,
824
+ // 汇总:整条链一共改了哪些文件(去重排序;格式化改的文件会被后续 git add 一并提交)
825
+ preprocessChanges: { total: new Set(allChanged).size, files: [...new Set(allChanged)].sort() },
826
+ // 本次链的来源:param(调用参数覆盖)/ config(配置文件)
827
+ stagesSource: chainSource,
828
+ ...(warnings.length ? { preprocessWarnings: warnings } : {}),
829
+ };
830
+ } finally {
831
+ // 临时目录只装「改动文件清单」,链跑完就删(不在 /tmp 里堆垃圾)
832
+ try { rmSync(envDir, { recursive: true, force: true }); } catch { /* 清理失败不影响结果 */ }
833
+ }
834
+ }
835
+
836
+ /**
837
+ * 造「当前阶段」的环境变量(想读就读,不读就当没看见 ⇒ 不改变既有 provider 契约)。
838
+ *
839
+ * 变量(都是**加法**,老实现完全不需要知道它们):
840
+ * PREPROCESS_REPO 当前仓库绝对路径
841
+ * PREPROCESS_CHANGED_FILES 本次改动文件(**换行**分隔;文件名里可以有逗号,换行几乎不可能)
842
+ * PREPROCESS_CHANGED_FILES_COUNT 条数
843
+ * PREPROCESS_CHANGED_FILES_FILE 同一份清单落盘的绝对路径(文件多时单个变量会撞 128KB 上限)
844
+ * PREPROCESS_STAGE_PROVIDER 当前阶段的 provider id
845
+ * @param {{repoPath: string, provider: string, changed: string[], envDir: string}} p
846
+ * @returns {{env: object, listFile: string}}
847
+ */
848
+ export function buildStageEnv({ repoPath = '.', provider = '', changed = [], envDir = '' } = {}) {
849
+ const list = changed.filter(Boolean);
850
+ const text = list.join('\n');
851
+ let listFile = '';
852
+ if (envDir) {
853
+ listFile = joinPath(envDir, 'changed-files.txt');
854
+ try { writeFileSync(listFile, text, 'utf8'); } catch { listFile = ''; }
855
+ }
856
+ const env = {
857
+ PREPROCESS_REPO: String(repoPath || '.'),
858
+ PREPROCESS_CHANGED_FILES: text,
859
+ PREPROCESS_CHANGED_FILES_COUNT: String(list.length),
860
+ ...(listFile ? { PREPROCESS_CHANGED_FILES_FILE: listFile } : {}),
861
+ ...(provider ? { PREPROCESS_STAGE_PROVIDER: String(provider) } : {}),
862
+ };
863
+ return { env: env, listFile: listFile };
864
+ }
865
+
866
+ /**
867
+ * 从单阶段回执里抽出「拦截清单摘要」——阶段回执只报事实(几条、头几条文件),
868
+ * 完整 findings 仍在最终 audit 里,不在这里复制一份(避免两份真相)。
869
+ * @param {object} res runPreCommitEngine 的回执
870
+ * @returns {{count: number, files: string[]}}
871
+ */
872
+ function blockedSummaryOf(res) {
873
+ const audit = (res && res.audit) || {};
874
+ const blocked = Array.isArray(audit.blocked) ? audit.blocked : [];
875
+ return {
876
+ count: blocked.length,
877
+ files: [...new Set(blocked.map((b) => String(b && b.file || '')).filter(Boolean))].slice(0, BLOCKED_FILES_PREVIEW_MAX),
878
+ };
879
+ }
880
+
881
+ /**
882
+ * 造一份「指定 provider 入口」的临时 cfg:让 runPreCommitEngine 走显式 args 分支。
883
+ *
884
+ * 为什么不改 runPreCommitEngine 的签名:它已经支持「command/args 显式指定」,这里只是
885
+ * 把阶段解析结果喂进那条既有通道 —— 单次执行只有一份实现,避免两套 spawn 逻辑漂移。
886
+ * @param {object} cfg 原运行期配置
887
+ * @param {string} cliPath provider 的 CLI 绝对路径
888
+ * @param {number} timeoutMs 该阶段超时(0=沿用全局)
889
+ * @returns {object}
890
+ */
891
+ function withStageOverride(cfg, cliPath, timeoutMs) {
892
+ const base = (cfg && typeof cfg.preCommit === 'object' && cfg.preCommit) || {};
893
+ return {
894
+ ...cfg,
895
+ preCommit: {
896
+ ...base,
897
+ command: '',
898
+ args: [cliPath],
899
+ ...(timeoutMs > 0 ? { timeoutMs: timeoutMs } : {}),
900
+ },
901
+ };
902
+ }
903
+
904
+ /** 阶段标签(command 形态):取可执行文件名,便于回执里认人。 */
905
+ function commandLabelOf(command) {
906
+ const first = splitCommandLine(String(command || ''))[0] || String(command || '');
907
+ return joinPath('.', first).replace(/^\.\//, '') || 'command';
908
+ }
909
+
910
+ /**
911
+ * 按 shell-like 规则切词 —— **不启动真 shell**。
912
+ *
913
+ * 为什么不用 `sh -c`:那等于把配置里的字符串当代码执行(`; rm -rf /` 会被执行)。
914
+ * 这里只做引号/空白切分,任何 `;` `|` `$()` 都原样当作普通参数传下去。
915
+ * 规则:单/双引号成组(引号内空格不切分);反斜杠转义下一个字符;其余按空白切分。
916
+ * @param {string} text 命令行文本
917
+ * @returns {string[]} 词数组(首项通常是可执行文件)
918
+ */
919
+ export function splitCommandLine(text) {
920
+ const out = [];
921
+ let cur = '';
922
+ let quote = '';
923
+ let has = false;
924
+ const src = String(text || '');
925
+ for (let i = 0; i < src.length; i += 1) {
926
+ const ch = src[i];
927
+ if (quote) {
928
+ if (ch === quote) { quote = ''; continue; }
929
+ if (ch === '\\' && quote === '"' && i + 1 < src.length) { cur += src[i + 1]; i += 1; continue; }
930
+ cur += ch;
931
+ continue;
932
+ }
933
+ if (ch === '"' || ch === "'") { quote = ch; has = true; continue; }
934
+ if (ch === '\\' && i + 1 < src.length) { cur += src[i + 1]; i += 1; has = true; continue; }
935
+ if (/\s/.test(ch)) {
936
+ if (has || cur) { out.push(cur); cur = ''; has = false; }
937
+ continue;
938
+ }
939
+ cur += ch;
940
+ has = true;
941
+ }
942
+ if (has || cur) out.push(cur);
943
+ return out;
944
+ }
945
+
946
+ /** 占位符替换:{repo} / {filesFile} / {filesCount} / {stage}(宿主替换,未知占位符原样保留)。 */
947
+ export function substitutePlaceholders(value, ctx = {}) {
948
+ return String(value == null ? '' : value).replace(/\{(repo|filesFile|filesCount|stage)\}/g,
949
+ (whole, key) => (ctx[key] === undefined || ctx[key] === null ? whole : String(ctx[key])));
950
+ }
951
+
952
+ /**
953
+ * 造「command 形态阶段」的临时 cfg。
954
+ *
955
+ * 两种写法都支持:
956
+ * A. `{ command: 'node', args: ['x.mjs', '{filesFile}'] }` —— **不走 shell**,文件名含空格也安全(推荐)
957
+ * B. `{ command: 'node x.mjs --mode staged' }` —— 按 shell-like 切词(不启动真 shell)
958
+ * 占位符在两种写法里都替换({repo} / {filesFile} / {filesCount} / {stage})。
959
+ * @param {object} cfg 原运行期配置
960
+ * @param {{command: string, args: string[]}} stage 阶段条目
961
+ * @param {object} ctx 占位符上下文
962
+ * @param {number} timeoutMs 该阶段超时(0=沿用全局)
963
+ * @returns {object}
964
+ */
965
+ function withCommandStage(cfg, stage, ctx, timeoutMs) {
966
+ const base = (cfg && typeof cfg.preCommit === 'object' && cfg.preCommit) || {};
967
+ const declaredArgs = Array.isArray(stage.args) ? stage.args : [];
968
+ let command = '';
969
+ let args = [];
970
+ if (declaredArgs.length) {
971
+ command = substitutePlaceholders(stage.command, ctx); // A:可执行文件 + 参数数组
972
+ args = declaredArgs.map((a) => substitutePlaceholders(a, ctx));
973
+ } else {
974
+ const words = splitCommandLine(stage.command).map((w) => substitutePlaceholders(w, ctx)); // B:整串切词
975
+ command = words[0] || '';
976
+ args = words.slice(1);
977
+ }
978
+ return {
979
+ ...cfg,
980
+ preCommit: {
981
+ ...base,
982
+ command: command,
983
+ args: args,
984
+ ...(timeoutMs > 0 ? { timeoutMs: timeoutMs } : {}),
985
+ },
986
+ };
987
+ }