dsh-git-push 2.20.19 → 3.0.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 (196) hide show
  1. package/README.md +3 -2
  2. package/cli-tool.mjs +2 -4
  3. package/cli.mjs +7 -1
  4. package/lib/app/apply.js +4 -4
  5. package/lib/app/command-registry.js +22 -17
  6. package/lib/app/handlers/meta.js +2 -2
  7. package/lib/app/handlers/preprocess.js +107 -0
  8. package/lib/app/handlers/repo-actions.js +2 -2
  9. package/lib/app/http-handlers.js +13 -42
  10. package/lib/app/index.js +2 -1
  11. package/lib/app/inject-text.js +3 -3
  12. package/lib/app/preprocess-client.js +136 -0
  13. package/lib/app/repo-ownership.js +1 -1
  14. package/lib/app/schema.js +3 -3
  15. package/lib/app/severity.js +14 -0
  16. package/lib/app/slash-commands.js +5 -164
  17. package/lib/app/tool-call.js +73 -144
  18. package/lib/cli/commands-preprocess.mjs +74 -0
  19. package/lib/cli/commands-tool.mjs +3 -2
  20. package/lib/cli/commands-vcs.mjs +4 -4
  21. package/lib/cli/shared.mjs +35 -9
  22. package/lib/commit-push/pre-commit-engine.js +57 -10
  23. package/lib/commit-push.js +71 -27
  24. package/lib/{exempt/index.js → git/exempt-markers.js} +8 -1
  25. package/lib/git/ignore.js +1 -1
  26. package/lib/git/repos.js +2 -2
  27. package/lib/git/sensitive.js +1 -1
  28. package/lib/npm/publish.js +20 -5
  29. package/lib/plugin/auto-push.js +2 -2
  30. package/lib/preprocess/providers.js +191 -0
  31. package/lib/self/index.js +1 -1
  32. package/lib/skip-dirs.js +14 -55
  33. package/package.json +29 -37
  34. package/scripts/build-client.mjs +2 -0
  35. package/scripts/check.mjs +4 -2
  36. package/scripts/local-registry.mjs +2 -1
  37. package/cli-audit.mjs +0 -141
  38. package/lib/app/audit-api.js +0 -173
  39. package/lib/app/handlers/audit.js +0 -150
  40. package/lib/app/host-doc-checks.js +0 -25
  41. package/lib/app/scope-check.js +0 -69
  42. package/lib/ast/brace.js +0 -120
  43. package/lib/ast/callgraph.js +0 -135
  44. package/lib/ast/code-lines.js +0 -175
  45. package/lib/ast/consts.js +0 -12
  46. package/lib/ast/control-flow.js +0 -470
  47. package/lib/ast/credential.js +0 -315
  48. package/lib/ast/dataflow.js +0 -391
  49. package/lib/ast/dup-code.js +0 -165
  50. package/lib/ast/fs-hotspots.js +0 -154
  51. package/lib/ast/index.js +0 -38
  52. package/lib/ast/io-risk-const.js +0 -95
  53. package/lib/ast/io-risk-fn.js +0 -208
  54. package/lib/ast/io-risk-loop.js +0 -308
  55. package/lib/ast/io-risk.js +0 -314
  56. package/lib/ast/lang.js +0 -156
  57. package/lib/ast/line-count.js +0 -52
  58. package/lib/ast/magic-number.js +0 -272
  59. package/lib/ast/naming.js +0 -292
  60. package/lib/ast/perf.js +0 -488
  61. package/lib/ast/scope-collisions.js +0 -228
  62. package/lib/ast/scope.js +0 -241
  63. package/lib/ast/shell.js +0 -131
  64. package/lib/ast/size.js +0 -448
  65. package/lib/ast/symbol-index.js +0 -399
  66. package/lib/ast/tokenizer.js +0 -421
  67. package/lib/ast/treesitter.js +0 -413
  68. package/lib/audit/analysis-coverage.js +0 -98
  69. package/lib/audit/audit-file.js +0 -205
  70. package/lib/audit/auditignore-rules.js +0 -148
  71. package/lib/audit/checks.js +0 -17
  72. package/lib/audit/client-entry.js +0 -93
  73. package/lib/audit/collector.js +0 -610
  74. package/lib/audit/ext-runner.js +0 -80
  75. package/lib/audit/file-context.js +0 -391
  76. package/lib/audit/finding.js +0 -101
  77. package/lib/audit/gitignore-match.js +0 -113
  78. package/lib/audit/glob.js +0 -63
  79. package/lib/audit/history-report.js +0 -100
  80. package/lib/audit/history.js +0 -126
  81. package/lib/audit/ignore-blind.js +0 -102
  82. package/lib/audit/index.js +0 -33
  83. package/lib/audit/orchestrate.js +0 -672
  84. package/lib/audit/public.js +0 -24
  85. package/lib/audit/repo-level.js +0 -30
  86. package/lib/audit/report-yaml.js +0 -90
  87. package/lib/audit/scope-policy.js +0 -110
  88. package/lib/audit/slot.js +0 -66
  89. package/lib/audit-rules/audit-rules-comment.yml +0 -199
  90. package/lib/audit-rules/audit-rules-cpp.yml +0 -114
  91. package/lib/audit-rules/audit-rules-csharp.yml +0 -82
  92. package/lib/audit-rules/audit-rules-docs.yml +0 -32
  93. package/lib/audit-rules/audit-rules-dsh.yml +0 -177
  94. package/lib/audit-rules/audit-rules-filehealth.yml +0 -42
  95. package/lib/audit-rules/audit-rules-folder.yml +0 -99
  96. package/lib/audit-rules/audit-rules-frontend.yml +0 -335
  97. package/lib/audit-rules/audit-rules-go.yml +0 -103
  98. package/lib/audit-rules/audit-rules-i18n.yml +0 -45
  99. package/lib/audit-rules/audit-rules-java.yml +0 -105
  100. package/lib/audit-rules/audit-rules-nodejs.yml +0 -662
  101. package/lib/audit-rules/audit-rules-npm.yml +0 -187
  102. package/lib/audit-rules/audit-rules-paths.yml +0 -98
  103. package/lib/audit-rules/audit-rules-performance.yml +0 -245
  104. package/lib/audit-rules/audit-rules-php.yml +0 -101
  105. package/lib/audit-rules/audit-rules-private.yml +0 -24
  106. package/lib/audit-rules/audit-rules-python.yml +0 -106
  107. package/lib/audit-rules/audit-rules-robustness.yml +0 -31
  108. package/lib/audit-rules/audit-rules-rust.yml +0 -109
  109. package/lib/audit-rules/audit-rules-structure.yml +0 -158
  110. package/lib/audit-rules/audit-rules-swift.yml +0 -99
  111. package/lib/audit-rules/audit-rules-template.yml +0 -108
  112. package/lib/audit-ui-sdk/contract.js +0 -117
  113. package/lib/audit-ui-sdk/index.js +0 -17
  114. package/lib/checks/button-bind.js +0 -347
  115. package/lib/checks/common.js +0 -170
  116. package/lib/checks/credential-file.js +0 -43
  117. package/lib/checks/dataflow.js +0 -40
  118. package/lib/checks/dispatch.js +0 -117
  119. package/lib/checks/dup-code.js +0 -69
  120. package/lib/checks/dup-const.js +0 -232
  121. package/lib/checks/file-health.js +0 -150
  122. package/lib/checks/filter.js +0 -137
  123. package/lib/checks/folder.js +0 -173
  124. package/lib/checks/fs-scanner.js +0 -57
  125. package/lib/checks/hardcoded-path.js +0 -98
  126. package/lib/checks/index.js +0 -49
  127. package/lib/checks/io.js +0 -66
  128. package/lib/checks/magic-number.js +0 -42
  129. package/lib/checks/npm-json.js +0 -273
  130. package/lib/checks/private.js +0 -64
  131. package/lib/checks/regex.js +0 -298
  132. package/lib/checks/scope-collision.js +0 -68
  133. package/lib/checks/semantic.js +0 -134
  134. package/lib/checks/structural.js +0 -281
  135. package/lib/cli/commands-audit.mjs +0 -142
  136. package/lib/cli/commands-doc.mjs +0 -127
  137. package/lib/client-parts/audit/audit.js +0 -301
  138. package/lib/exempt/tool.js +0 -198
  139. package/lib/git/module-splitter.js +0 -47
  140. package/lib/link-check/index.js +0 -187
  141. package/lib/lint-adapter/detect.js +0 -161
  142. package/lib/lint-adapter/index.js +0 -50
  143. package/lib/lint-adapter/runner.js +0 -133
  144. package/lib/preprocess/audit.js +0 -98
  145. package/lib/preprocess/index.js +0 -78
  146. package/lib/rule/compilers/credential.js +0 -62
  147. package/lib/rule/compilers/dataflow.js +0 -38
  148. package/lib/rule/compilers/file-health.js +0 -75
  149. package/lib/rule/compilers/frontend.js +0 -86
  150. package/lib/rule/compilers/func.js +0 -35
  151. package/lib/rule/compilers/helpers.js +0 -71
  152. package/lib/rule/compilers/index.js +0 -29
  153. package/lib/rule/compilers/link-semantic.js +0 -45
  154. package/lib/rule/compilers/list-kinds.js +0 -12
  155. package/lib/rule/compilers/numeric-kinds.js +0 -73
  156. package/lib/rule/compilers/regex.js +0 -78
  157. package/lib/rule/compilers/structure.js +0 -107
  158. package/lib/rule/compilers.js +0 -17
  159. package/lib/rule/homoglyph.js +0 -45
  160. package/lib/rule/loader.js +0 -274
  161. package/lib/rule/registry.js +0 -122
  162. package/lib/rule/scope.js +0 -67
  163. package/lib/score/docs-score.js +0 -166
  164. package/lib/score/index.js +0 -234
  165. package/scripts/__pycache__/module-splitter.cpython-38.pyc +0 -0
  166. package/scripts/audit-ext/_example-readme-present.mjs +0 -34
  167. package/scripts/audit-ext/dsh-inject-declarations.mjs +0 -209
  168. package/scripts/audit-ext/variable-min-length.mjs +0 -102
  169. package/scripts/audit-gate.mjs +0 -235
  170. package/scripts/audit-runner.mjs +0 -35
  171. package/scripts/audit-runtime-check.mjs +0 -129
  172. package/scripts/browser-page-probe.mjs +0 -271
  173. package/scripts/check-js-scope.mjs +0 -87
  174. package/scripts/clean-date-comments.py +0 -102
  175. package/scripts/cpu-sample.mjs +0 -188
  176. package/scripts/doc-drift.mjs +0 -200
  177. package/scripts/hot-path-probe-cjs.cjs +0 -71
  178. package/scripts/hot-path-probe-fs-shim.mjs +0 -28
  179. package/scripts/hot-path-probe-fsp-shim.mjs +0 -31
  180. package/scripts/hot-path-probe.mjs +0 -153
  181. package/scripts/module-splitter.py +0 -800
  182. package/scripts/picker-repro.mjs +0 -115
  183. package/scripts/platform-scan.mjs +0 -168
  184. package/scripts/probe-recheck.mjs +0 -47
  185. package/scripts/rename-locator.mjs +0 -97
  186. package/scripts/rule-switch.mjs +0 -97
  187. package/scripts/rules-solo-audit.mjs +0 -173
  188. package/scripts/scan-file-io.mjs +0 -717
  189. package/scripts/scan-fs-hotspots.mjs +0 -107
  190. package/scripts/symbol-index.mjs +0 -85
  191. package/scripts/verify-prestep.mjs +0 -100
  192. package/skills/dev/audit-rule-authoring.md +0 -58
  193. package/skills/guide/guide-audit.md +0 -270
  194. /package/lib/{audit → app}/ownership.js +0 -0
  195. /package/lib/app/{schema-audit.js → schema-preprocess.js} +0 -0
  196. /package/lib/{audit-defaults.js → git/defaults.js} +0 -0
@@ -0,0 +1,74 @@
1
+ /**
2
+ * CLI 命令 · 预处理域(从「所有在位 provider 的声明」里找能力并转发)。
3
+ *
4
+ * 为什么不是写死 `audit`:预处理是通用机制,审计只是第一个实现。
5
+ * 本命令只做三件事:① 问 providers 层「谁声明了这个 action」 ② 找不到就说清有哪些可用
6
+ * ③ 找到就 spawn 那个 provider 的 CLI 并把退出码原样透传(脚本可判定失败)。
7
+ *
8
+ * HTTP 侧(/api/preprocess/<action>)用的是同一个查找函数(findActionProvider / findEndpointProvider),
9
+ * 所以 CLI 与 HTTP 的能力面天然一致,不会一边有、一边没有。
10
+ */
11
+ import { spawn } from 'node:child_process';
12
+
13
+ import { findActionProvider, listDeclaredCapabilities, resolveProvider } from '../preprocess/providers.js';
14
+
15
+ /**
16
+ * 列出当前可用的预处理能力(供 help / 报错提示)。
17
+ * @returns {Promise<string>} 多行文本
18
+ */
19
+ export async function describePreprocessCapabilities() {
20
+ const caps = await listDeclaredCapabilities();
21
+ const lines = [];
22
+ if (caps.actions.length === 0) {
23
+ lines.push('当前没有任何在位 provider 声明 action(预处理扩展未安装)');
24
+ } else {
25
+ lines.push('可用预处理动作:');
26
+ for (const action of caps.actions) {
27
+ const params = Array.isArray(action.params) ? action.params.length : 0;
28
+ lines.push(` ${action.action} [${action.provider}] ${params} 个参数 ${action.desc || ''}`.trimEnd());
29
+ }
30
+ }
31
+ for (const miss of caps.missing) {
32
+ lines.push(` · ${miss.provider.id} 不可用:${miss.reason}`);
33
+ }
34
+ return lines.join('\n');
35
+ }
36
+
37
+ /**
38
+ * 执行一次预处理转发。
39
+ * @param {string[]} positional 命令名之后的参数:第一个是 action,其余原样转发
40
+ * @returns {Promise<number>} 退出码(0 成功 / 1 被拦 / 2 参数或执行错误)
41
+ */
42
+ export async function cmdPreprocess(positional = []) {
43
+ const [action, ...forwardArgs] = positional;
44
+ if (!action) {
45
+ console.error(await describePreprocessCapabilities());
46
+ console.error('\n用法:preprocess <action> [参数…]');
47
+ return 2;
48
+ }
49
+ const hit = await findActionProvider(action);
50
+ if (!hit) {
51
+ const caps = await listDeclaredCapabilities();
52
+ const known = caps.actions.map((item) => item.action);
53
+ console.error(`没有 provider 声明动作「${action}」${known.length ? `(可用:${known.join(' / ')})` : '(当前没有任何 provider 在位)'}`);
54
+ console.error(await describePreprocessCapabilities());
55
+ return 2;
56
+ }
57
+ const resolved = resolveProvider(hit.provider.id);
58
+ if (!resolved.ok) {
59
+ console.error(resolved.error);
60
+ return 2;
61
+ }
62
+ // 转发:provider 自己的 CLI 认得同样的 action 名(声明与实现同名,避免映射表漂移)
63
+ const child = spawn(process.execPath, [resolved.path, action, ...forwardArgs], { stdio: 'inherit' });
64
+ return await new Promise((resolvePromise) => {
65
+ child.on('error', (error) => {
66
+ console.error(`启动预处理实现失败:${error?.message || error}`);
67
+ resolvePromise(2);
68
+ });
69
+ child.on('close', (code, signal) => {
70
+ if (signal) { console.error(`预处理实现被信号中断:${signal}`); resolvePromise(2); return; }
71
+ resolvePromise(typeof code === 'number' ? code : 2);
72
+ });
73
+ });
74
+ }
@@ -13,9 +13,10 @@ import { readFileSync } from 'node:fs';
13
13
  import { CLI_ENTRIES, allCommands, parseEntrySourceMeta, readEntrySource } from './shared.mjs';
14
14
 
15
15
  /** 入口文件清单(bin → 源文件)。自检逐个核对。 */
16
+ // 审计 CLI 已随审计能力独立成包(audit-sluice),本插件只剩 git / tool 两侧,
17
+ // 故自检不再遍历 audit 入口(文件已不存在)。
16
18
  export const ENTRY_FILES = [
17
19
  { cliName: 'git-sluice', file: 'cli.mjs' },
18
- { cliName: 'audit-sluice', file: 'cli-audit.mjs' },
19
20
  { cliName: 'tool-sluice', file: 'cli-tool.mjs' },
20
21
  ];
21
22
 
@@ -87,7 +88,7 @@ export function cmdSelfCheck() {
87
88
  // 一次性并入(不在循环里逐条 push:既少一层循环,也让「失败清单来自一处」更好读)
88
89
  failures.push(...entryFailures);
89
90
  for (const failure of entryFailures) console.error(` ✗ ${failure}`);
90
- if (!entryFailures.length) console.log(` ✓ 命令覆盖:三入口共 ${allCommands().length} 个命令都有用法行`);
91
+ if (!entryFailures.length) console.log(` ✓ 命令覆盖:各入口共 ${allCommands().length} 个命令都有用法行`);
91
92
  process.exitCode = failures.length > 0 ? 1 : 0;
92
93
  return failures.length > 0 ? 1 : 0;
93
94
  }
@@ -13,8 +13,8 @@ import { scanRepos } from '../git/repos.js';
13
13
  import { updateRepoIndex } from '../git/repo-index.js';
14
14
  import { runWrappedGit } from '../git/wrapped-git.js';
15
15
  import { commitWithAudit } from '../commit-push.js';
16
- import { checkLinks, sumLinkPenalty } from '../link-check/index.js';
17
- import { collectTextFiles, readText } from '../audit/collector.js';
16
+
17
+ import * as auditClient from '../app/preprocess-client.js';
18
18
  import { cloneViaApi, previewClone } from '../git/clone.js';
19
19
  import { DEFAULT_MAX_FILE_MB } from '../git/clone-download.js';
20
20
  import { resolveToken } from '../git/credentials.js';
@@ -123,10 +123,10 @@ export async function cmdCommit(root, flags) {
123
123
 
124
124
  /** 子命令:link-check — 检查文本文件的链接有效性(只 warning,不拦提交)。 */
125
125
  export async function cmdLinkCheck(root = '.') {
126
- const files = (await collectTextFiles(root, { depth: 5 })).filter((f) => /\.(md|markdown|txt)$/i.test(f.path));
126
+ const files = (await await (await auditClient.hostApi()).collectTextFiles(root, { depth: 5 })).filter((f) => /\.(md|markdown|txt)$/i.test(f.path));
127
127
  const all = [];
128
128
  for (const f of files) {
129
- const findings = await checkLinks({ file: f.path, text: readText(f.full) });
129
+ const findings = await checkLinks({ file: f.path, text: await (await auditClient.hostApi()).readText(f.full) });
130
130
  if (findings.length) all.push(...findings);
131
131
  }
132
132
  console.log(`链接检查 ${root}(${files.length} 个文档)`);
@@ -22,14 +22,14 @@ import { defaultConfig } from '../client/index.js';
22
22
 
23
23
  /** 三个入口的名字(也是 bin 名)。 */
24
24
  export const CLI_GIT = 'git-sluice';
25
- export const CLI_AUDIT = 'audit-sluice';
26
25
  export const CLI_TOOL = 'tool-sluice';
27
26
 
28
27
  /**
29
- * 三入口的切割线(唯一真相)。
28
+ * CLI 切割线(唯一真相):审计 CLI 已随审计实现独立成包(audit-sluice)
29
+ * ——宿主不再提供审计入口,故这里只有 git / tool 两侧。
30
30
  * commands:该 CLI 独占的命令名(含注册表驱动与 COMMANDS 表两种来源);
31
31
  * fallback:未知命令的处置——只有 git 侧把未知命令透传给 git(`git-sluice status` = `git status`),
32
- * 另外两侧遇到未知命令必须报错(审计/工具 CLI 不该悄悄执行 git 命令)。
32
+ * tool 侧遇到未知命令必须报错(不该悄悄执行 git 命令)。
33
33
  */
34
34
  export const CLI_ENTRIES = {
35
35
  [CLI_GIT]: {
@@ -39,20 +39,33 @@ export const CLI_ENTRIES = {
39
39
  'scan', 'commit', 'clone', 'clone-preview', 'remote-create', 'rename', 'set-visibility',
40
40
  'identity-rewrite', 'account-check', 'cred-env', 'gen-ssh-key', 'git', 'api', 'repos', 'index',
41
41
  'npm-publish', 'unpublish',
42
+ // 通用预处理入口:从所有在位 provider 的声明里找 action 并转发(审计只是其中之一)
43
+ 'preprocess',
42
44
  ],
43
45
  },
44
- [CLI_AUDIT]: {
45
- intro: 'dsh-git-push 审计侧 CLI(审计/规则/评分/静态检查;脱离 DSH 运行)',
46
- fallback: 'error',
47
- commands: ['audit', 'ruleset', 'file-io', 'link-check', 'scope-check', 'functions', 'tree-doc'],
48
- },
49
46
  [CLI_TOOL]: {
50
47
  intro: 'dsh-git-push 工具链 CLI(拆分/模板/自检;不含 git 与审计命令)',
51
48
  fallback: 'error',
52
- commands: ['module-splitter', 'yaml-template', 'readme-template', 'self-check'],
49
+ commands: ['yaml-template', 'readme-template', 'self-check'],
53
50
  },
54
51
  };
55
52
 
53
+ /**
54
+ * 已随能力迁出宿主的命令 → 现在该去哪个包敲。
55
+ *
56
+ * 为什么单独列:审计 CLI 独立成包后,这些命令名在宿主侧「既不属于 git 也不属于 tool」,
57
+ * 若落进「未知命令」分支,git 侧会把 `audit` 当 git 子命令透传出去(跑出莫名其妙的 git 报错)。
58
+ * 明确告诉用户「已迁到哪个包 + 怎么敲」,才是可行动的提示。
59
+ */
60
+ export const MIGRATED_COMMANDS = Object.freeze({
61
+ audit: 'audit-sluice',
62
+ manifest: 'audit-sluice',
63
+ io_scan: 'audit-sluice',
64
+ link_check: 'audit-sluice',
65
+ scope_check: 'audit-sluice',
66
+ exempt_hint: 'audit-sluice',
67
+ });
68
+
56
69
  /** 命令 → 所属 CLI(未登记返回空串)。 */
57
70
  export function commandOwner(command) {
58
71
  const name = String(command || '');
@@ -277,6 +290,17 @@ export function resolveDispatch({ cliName = CLI_GIT, argv = [], commands = new M
277
290
  if (!command || command === 'help' || command === '--help' || command === '-h') return { kind: 'help' };
278
291
  if (command === 'version' || command === '-v' || command === '--version') return { kind: 'version' };
279
292
  const owner = commandOwner(command);
293
+ // ⓪ 已迁出宿主的命令:说清「去了哪个包 + 怎么敲」,别落进未知命令分支被当 git 子命令透传
294
+ const migratedTo = MIGRATED_COMMANDS[command];
295
+ if (migratedTo) {
296
+ return {
297
+ kind: 'migrated',
298
+ command,
299
+ targetPackage: migratedTo,
300
+ hint: `命令 "${command}" 已随能力迁到独立包 ${migratedTo}(宿主不再内置)。\n`
301
+ + `请改用:git-sluice preprocess ${command} ${rest.join(' ')}(等价:${migratedTo} ${command} …)`.trim(),
302
+ };
303
+ }
280
304
  // ① 跨侧:明确报错并给出可照抄的替代命令(绝不静默转发)
281
305
  if (owner && owner !== cliName) {
282
306
  return { kind: 'cross', command, targetCli: owner, hint: buildCrossCliHint({ command, argvRest: rest, fromCli: cliName }) };
@@ -351,6 +375,8 @@ export async function runCli({
351
375
  if (plan.kind === 'help') { console.log(typeof helpText === 'function' ? helpText() : helpText); return; }
352
376
  if (plan.kind === 'version') { printVersion(cliName); return; }
353
377
  if (plan.kind === 'cross') { console.error(plan.hint); process.exitCode = 1; return 1; }
378
+ // 命令已随能力迁出宿主(如审计侧 → audit-sluice 包):给可照抄的提示,不当未知命令
379
+ if (plan.kind === 'migrated') { console.error(plan.hint); process.exitCode = 1; return 1; }
354
380
  if (plan.kind === 'unknown') { console.error(plan.error); process.exitCode = 1; return 1; }
355
381
  if (plan.kind === 'command') return await plan.handler(argv.slice(1));
356
382
  if (plan.kind === 'registry') {
@@ -5,7 +5,7 @@
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 一律按「执行失败」处理
@@ -29,7 +29,21 @@ import { PRE_COMMIT_TIMEOUT_MS_DEFAULT } from '../app/constants.js';
29
29
  export { PRE_COMMIT_TIMEOUT_MS_DEFAULT };
30
30
 
31
31
  /** 内置轻量入口(相对插件根)。配置留空时用它。 */
32
- export const AUDIT_GATE_SCRIPT_REL = join('scripts', 'audit-gate.mjs');
32
+
33
+
34
+ /**
35
+ * 审计实现所属包名(拆包后审计实现在 `audit-sluice`)。
36
+ * 为什么单独一个常量:入口解析、错误提示、将来 npm 依赖安装后的路径都引用它,避免多处手写字符串。
37
+ */
38
+
39
+ /** 预处理实现的 CLI 入口(相对包根)。 */
40
+ export const PREPROCESS_CLI_REL = 'cli.mjs';
41
+
42
+ // 注意:这里不再写死具体实现的包名——包名属于 provider 定义(lib/preprocess/providers.js),
43
+ // 通用层只通过 provider 抽象拿它。将来换/加 provider 不需要改本文件。
44
+ import { resolveGateProvider, getProviderDefinition, DEFAULT_PROVIDER_ID } from '../preprocess/providers.js';
45
+
46
+ export { resolveGateProvider };
33
47
 
34
48
  /** 错误信息里保留的 stderr 尾部字符数:够定位(栈尾通常在最后),又不至于把上下文刷爆。 */
35
49
  export const STDERR_TAIL_CHARS = 2000;
@@ -37,7 +51,7 @@ export const STDERR_TAIL_CHARS = 2000;
37
51
  /** stdout 收集上限(64MB):findings 全量在大仓可达数 MB,超这个量级说明契约跑偏,宁可报错。 */
38
52
  export const STDOUT_MAX_BYTES = 64 * 1024 * 1024;
39
53
 
40
- /** 契约退出码(与 scripts/audit-gate.mjs 的 EXIT_* 常量对应)。 */
54
+ /** 契约退出码(与预处理实现 CLI 的 EXIT_* 常量对应)。 */
41
55
  export const ENGINE_EXIT_OK = 0;
42
56
  export const ENGINE_EXIT_BLOCKED = 1;
43
57
  export const ENGINE_EXIT_FAILED = 2;
@@ -75,13 +89,22 @@ export function resolvePreCommitConfig(cfg = {}) {
75
89
  ? raw.args.map((rawArg) => String(rawArg)).filter((rawArg) => rawArg !== '')
76
90
  : [];
77
91
  // 内置默认只在「command 与 args 都没配」时生效:
78
- // · command 空 + args 空 → node + 插件自带 scripts/audit-gate.mjs
92
+ // · command 空 + args 空 → node + 预处理实现 CLI
79
93
  // · command 空 + args 有值 → node + 配置里给的引擎脚本(args 里相对路径按插件根解析)
80
94
  // · command 有值 + args 空 → 那是一个独立可执行文件(Go/Rust 单二进制就是这种形态,
81
95
  // 此时**不能**塞我们自己的脚本路径进去)
82
- const args = (!command && configuredArgs.length === 0)
83
- ? [join(pluginRootDir(), AUDIT_GATE_SCRIPT_REL)]
84
- : configuredArgs;
96
+ // 缺省引擎 = 预处理实现 CLI(拆包后审计实现归 audit-sluice);
97
+ // 显式配置 command/args 时仍以配置为准(回滚与自定义引擎都走这条)。
98
+ let args = configuredArgs;
99
+ if (!command && configuredArgs.length === 0) {
100
+ const entry = resolveGateProvider();
101
+ // 解析失败也把"期望的路径"放进 args:真正的失败在 spawn 前由 runPreCommitEngine 报出,
102
+ // 错误信息里带上具体查过哪些路径(否则用户只看到"命令不存在",不知道该怎么办)。
103
+ args = entry.ok ? [entry.path] : [join(pluginRootDir(), '..', getProviderDefinition(DEFAULT_PROVIDER_ID).packageName, PREPROCESS_CLI_REL)];
104
+ }
105
+ // 是否仍是「内置旧引擎」(显式指回 plugins 自带 预处理实现 CLI 的回滚路径):
106
+ // 旧引擎不认 --visibility/--exempt-paths,也不会返回 blocked —— 传了会直接 exit 2。
107
+ // 两条路径都保留可用,才能做到「切调用但可回滚」。
85
108
  const rawTimeout = Number(raw?.timeoutMs);
86
109
  // 超时必须是正有限数:0 / 负数 / NaN 一律退回默认(0 表示「立刻超时」会让门禁永远失败)
87
110
  const timeoutMs = Number.isFinite(rawTimeout) && rawTimeout > 0 ? Math.floor(rawTimeout) : PRE_COMMIT_TIMEOUT_MS_DEFAULT;
@@ -212,7 +235,8 @@ function toSlotCsv(slots) {
212
235
  * @returns {string[]}
213
236
  */
214
237
  export function buildEngineArgs({
215
- args = [], repoPath = '', scope = 'diff', rulesetDir = '', weights = {}, maxScanFiles, slots = [], disabledSlots = [], blockersOnly = false,
238
+ args = [], repoPath = '', scope = 'diff', rulesetDir = '', weights = {}, maxScanFiles, slots = [], disabledSlots = [],
239
+ blockersOnly = false, visibility = '', exemptPaths = [], exemptReason = '',
216
240
  } = {}) {
217
241
  const argv = [...resolveEngineArgs(args)];
218
242
  argv.push('--repo', String(repoPath || '.'));
@@ -226,6 +250,15 @@ export function buildEngineArgs({
226
250
  if (whiteListCsv) argv.push('--slots', whiteListCsv);
227
251
  const blackListCsv = toSlotCsv(disabledSlots);
228
252
  if (blackListCsv) argv.push('--disabled-slots', blackListCsv);
253
+ // 新参数只传给「新引擎」(预处理实现):内置旧引擎不认这些 flag,传了会直接 exit 2。
254
+ // 可见性:只有明确知道时才传(unknown 是引擎缺省,传了也一样);
255
+ // 私有库豁免由预处理实现自己判(它是权威),gitpush 只负责探测后把结论传过去。
256
+ if (visibility === 'private' || visibility === 'public') argv.push('--visibility', visibility);
257
+ // 临时豁免:**参数名映射** —— 工具参数叫 auditExemptPaths/auditExemptReason,
258
+ // 预处理实现 CLI 叫 --exempt-paths/--exempt-reason(独立包不需要 audit- 前缀)。
259
+ const exemptCsv = toSlotCsv(exemptPaths);
260
+ if (exemptCsv) argv.push('--exempt-paths', exemptCsv);
261
+ if (exemptReason) argv.push('--exempt-reason', String(exemptReason));
229
262
  if (blockersOnly) argv.push('--blockers-only');
230
263
  argv.push('--json');
231
264
  return argv;
@@ -352,13 +385,27 @@ function runEngineProcess({ command, args, timeoutMs }) {
352
385
  */
353
386
  export async function runPreCommitEngine({
354
387
  repoPath = '.', scope = 'diff', rulesetDir = '', weights = {}, maxScanFiles, slots = [], disabledSlots = [],
355
- blockersOnly = false, cfg = {}, timeoutMs,
388
+ blockersOnly = false, cfg = {}, timeoutMs, visibility = '', exemptPaths = [], exemptReason = '',
356
389
  } = {}) {
357
390
  const spec = resolvePreCommitConfig(cfg);
391
+ // 预处理实现是**可热插拔的扩展能力**:不在位时不该拦住提交,而应当「跳过审计并明确标注」。
392
+ // 这正是解耦的目标——拔掉扩展,主流程照常;插上扩展,能力自动回来。
393
+ // 注意:这里返回的是「跳过」而不是「静默通过」,调用方能拿到 preprocessSkipped 与原因。
394
+ if (!spec.command && spec.args.length === 1 && !existsSync(spec.args[0])) {
395
+ const entry = resolveGateProvider();
396
+ return {
397
+ ok: true,
398
+ audit: null,
399
+ preprocessSkipped: 'package-not-found',
400
+ skipReason: entry.ok ? '预处理实现不可用' : entry.error,
401
+ engine: { command: '', args: [], exitCode: null, timedOut: false },
402
+ };
403
+ }
358
404
  const resolved = resolveEngineCommand(spec.command);
405
+ // 显式配置的引擎命令不可用 ⇒ 这是配置错误(不是「扩展不在位」),仍然 fail-closed
359
406
  if (!resolved.ok) return failClosed(`提交前预处理失败:${resolved.error}(未执行任何 git 操作;修复 preCommit.command 后重试)`);
360
407
  const command = resolved.command;
361
- const args = buildEngineArgs({ args: spec.args, repoPath, scope, rulesetDir, weights, maxScanFiles, slots, disabledSlots, blockersOnly });
408
+ const args = buildEngineArgs({ args: spec.args, repoPath, scope, rulesetDir, weights, maxScanFiles, slots, disabledSlots, blockersOnly, visibility, exemptPaths, exemptReason });
362
409
  const commandLine = formatCommandLine(command, args);
363
410
  const effectiveTimeout = Number.isFinite(Number(timeoutMs)) && Number(timeoutMs) > 0
364
411
  ? Math.floor(Number(timeoutMs))
@@ -11,20 +11,19 @@
11
11
  // 审计的结果文案改由「预处理能力」渲染(lib/preprocess/):git 侧只留兜底逻辑与中性默认文案。
12
12
  // 为什么 git 侧不再自己生成这份指引:那是**审计措辞**(查询用哪个 API、明细去哪看),
13
13
  // 属于审计预处理自己的语义,搬进 lib/preprocess/audit.js 的 renderResult 里。
14
- import { renderPreprocessResult } from './preprocess/index.js';
14
+ import * as auditClient from './app/preprocess-client.js';
15
15
 
16
16
  // 审计内核(auditWithScope / scoreQuality)不再在本文件直接 import —— 提交门禁改为
17
17
  // 调「可配置的审计引擎子进程」(lib/commit-push/pre-commit-engine.js),这是解耦点:
18
18
  // 换引擎(含换语言重写)只改配置,git 侧零改动。
19
- // ⚠️ 文档漂移检查器的接线也随之搬进引擎入口(scripts/audit-gate.mjs 里 import 一次);
19
+ // ⚠️ 文档漂移检查器的接线也随之搬进引擎入口(审计包 CLI 里 import 一次);
20
20
  // 宿主自己的工具/HTTP 侧仍由 lib/app/tool-call.js 接线,不依赖本文件。
21
21
  import { runPreCommitEngine } from './commit-push/pre-commit-engine.js';
22
22
  import { commitAndPush } from './git/index.js';
23
23
  import { defaultConfig } from './client/index.js';
24
- import { MAX_MSG_PREVIEW } from './app/constants.js';
25
- import { isSampleExemptDir } from './exempt/index.js';
26
24
  import { resolveRepoVisibility } from './git/index.js';
27
25
 
26
+
28
27
  /**
29
28
  * 预处理渲染的**兜底文案**(刻意留在 git 侧)。
30
29
  *
@@ -61,7 +60,15 @@ export function defaultPreprocessRender(ctx = {}) {
61
60
  * (README「④ 私有库豁免」);缺省按 origin 探测,探测失败按 unknown(保守拦截)。
62
61
  * 显式传入可免网络探测(测试/已知场景)。
63
62
  */
64
- export async function runAudit({ repoPath = '', audit, rulesetDir, slots, cfg: extCfg, visibility: extVisibility, exemptPaths = [], exemptReason = '' } = {}) {
63
+ export async function runAudit({
64
+ repoPath = '', audit, rulesetDir, slots, cfg: extCfg, visibility: extVisibility,
65
+ auditExemptPaths = [], auditExemptReason = '',
66
+ ...unknownKeys // 未知参数一律报错:
67
+ }) { // 参数名与工具参数(auditExemptPaths 等)曾不一致,
68
+ const unknown = Object.keys(unknownKeys); // 传错名过去是**静默无效且不报错**(实测踩到),
69
+ if (unknown.length) { // 这个校验把它变成立刻可见的错误。
70
+ throw new Error(`runAudit 收到未知参数:${unknown.join(', ')}(可用:repoPath/audit/rulesetDir/slots/cfg/visibility/auditExemptPaths/auditExemptReason)`);
71
+ }
65
72
  const cfg = extCfg || defaultConfig();
66
73
  const doAudit = audit ?? cfg.auditEnabled;
67
74
  if (!doAudit) return { ok: true, audit: null };
@@ -91,11 +98,28 @@ export async function runAudit({ repoPath = '', audit, rulesetDir, slots, cfg: e
91
98
  maxScanFiles: cfg.maxScanFiles,
92
99
  slots: slotOrder,
93
100
  disabledSlots: Array.isArray(cfg.auditDisabledSlots) ? cfg.auditDisabledSlots : [],
101
+ // 可见性:显式传入时直接给引擎;未传则留空(引擎按 unknown 保守处理,gitpush 稍后按需探测)
102
+ visibility: extVisibility,
103
+ // 临时豁免:**参数名映射**(工具参数 auditExemptPaths → 审计包 --exempt-paths)
104
+ exemptPaths: Array.isArray(auditExemptPaths) ? auditExemptPaths : [],
105
+ exemptReason: auditExemptReason || '',
94
106
  cfg,
95
107
  });
96
108
  // 引擎不可用(崩/超时/退出码 2/输出不合契约)一律 fail-closed:拒绝提交并给出可诊断原因。
97
109
  // 绝不在这里「当作没有 blocker 放行」——那等于把红线交给「恰好没跑起来」。
110
+ // 例外:预处理实现不在位(preprocessSkipped)——那是「扩展没插」,不是「引擎坏了」。
111
+ // 按热插拔语义放行主流程,但必须把「本次未做预处理」透出给调用方(不静默)。
112
+ // 字段名刻意用 preprocess* 而不是 audit*:预处理是通用机制,审计只是它的一个实现。
98
113
  if (!engineRes.ok) return { ok: false, blocked: false, error: engineRes.error, audit: null };
114
+ if (engineRes.preprocessSkipped) {
115
+ return {
116
+ ok: true,
117
+ blocked: false,
118
+ audit: null,
119
+ preprocessSkipped: engineRes.preprocessSkipped,
120
+ skipReason: engineRes.skipReason || '',
121
+ };
122
+ }
99
123
  const engineAudit = engineRes.audit || {};
100
124
  const findings = Array.isArray(engineAudit.findings) ? engineAudit.findings : [];
101
125
  const auditOut = {
@@ -109,27 +133,47 @@ export async function runAudit({ repoPath = '', audit, rulesetDir, slots, cfg: e
109
133
  blocked: engineRes.engine?.exitCode === 1,
110
134
  },
111
135
  };
112
- // 本次提交的按文件临时豁免(auditExemptPaths):列入的文件 finding 一律不参与拦截判定(含 blocker),
113
- // 仅本次有效、不落盘、不改 .auditignore;评分仍用全量 findings(豁免不影响打分基数)。
114
- // 语义按需求方定稿:豁免即豁免,不设「只允许 warning/notice」的限制,也不按规则类别过滤。
115
- const exemptSet = new Set((Array.isArray(exemptPaths) ? exemptPaths : [])
116
- .map((p) => String(p || '').replace(/\\/g, '/').replace(/^\.\//, '').trim())
117
- .filter(Boolean));
118
- const isExemptFile = (f) => exemptSet.size > 0 && exemptSet.has(String(f.file || '').replace(/\\/g, '/').replace(/^\.\//, ''));
119
- const exemptFindings = exemptSet.size ? findings.filter((f) => isExemptFile(f)) : [];
120
- // 只算非示例目录的 blocker(示例目录内的 blocker 是规则演示,不拦真实提交)
121
- const blocked = findings.filter((f) => f.severity === 'blocker' && !isSampleExemptDir(repoPath || '.', f.file) && !isExemptFile(f));
122
- auditOut.blocked = blocked.map((f) => ({ file: f.file, line: f.line, rule: f.rule, message: (f.message || '').slice(0, MAX_MSG_PREVIEW) }));
123
- if (exemptSet.size) {
124
- // 回显(记录而非判断):本次豁免了哪些文件、命中哪些规则、共几条 finding
125
- auditOut.exempt = {
126
- files: [...exemptSet],
127
- count: exemptFindings.length,
128
- rules: [...new Set(exemptFindings.map((f) => f.rule).filter(Boolean))],
129
- ...(exemptReason ? { reason: String(exemptReason) } : {}),
130
- // note 由预处理渲染填(见下方 renderPreprocessResult);这里不写死措辞
131
- };
136
+ // ── 拦截结论:**直接用审计包的**(拆包后它才是权威)──
137
+ // 豁免四类(代码标记 / 测试夹具 / 示例目录 / 临时豁免)加私有库降级都在包内完成,
138
+ // gitpush 这层不再重复实现一遍 —— 两份实现并存时最危险的是「某一天两边算得不一样」,
139
+ // 而那时门禁到底拦不拦取决于走了哪条分支,几乎无法排查。
140
+ // 拦截结论**只认审计包的**:宿主不再有第二套豁免/拦截实现(回滚路径已随旧引擎删除)
141
+ auditOut.blocked = Array.isArray(engineAudit.blocked) ? engineAudit.blocked : [];
142
+ // 示例目录豁免条数(summary.blocker 与 blocked 的差值来源之一),原样透传供排查
143
+ if (Number.isFinite(Number(engineAudit.sampleExemptCount))) auditOut.sampleExemptCount = Number(engineAudit.sampleExemptCount);
144
+ // exempt 回显:新引擎(审计包)自己给;回滚路径(内置旧引擎)这里保底构造,
145
+ // 语义与切包前一致(记录而非判断:豁免了哪些文件、命中哪些规则、共几条 finding)。
146
+ if (engineAudit.exempt) {
147
+ auditOut.exempt = engineAudit.exempt;
148
+ } else {
149
+ const exemptSet = new Set((Array.isArray(auditExemptPaths) ? auditExemptPaths : [])
150
+ .map((value) => String(value || '').replace(/\\/g, '/').replace(/^\.\//, '').trim())
151
+ .filter(Boolean));
152
+ if (exemptSet.size) {
153
+ const isExemptFile = (finding) => exemptSet.has(String(finding.file || '').replace(/\\/g, '/').replace(/^\.\//, ''));
154
+ const exemptFindings = findings.filter(isExemptFile);
155
+ auditOut.exempt = {
156
+ files: [...exemptSet],
157
+ count: exemptFindings.length,
158
+ rules: [...new Set(exemptFindings.map((finding) => finding.rule).filter(Boolean))],
159
+ ...(auditExemptReason ? { reason: String(auditExemptReason) } : {}),
160
+ };
161
+ }
132
162
  }
163
+ if (engineAudit.privateExempt) {
164
+ auditOut.privateExempt = engineAudit.privateExempt;
165
+ // 私有库时审计包把结论归零(blocked: [],理由见批 B 契约);但**对外形态保持旧样**:
166
+ // `audit.blocked` 历来是「报告用的原始清单」(audit-api / code_audit / 报告都读它),
167
+ // 归零会让这些消费方以为「这个私有库一条问题都没有」,丢掉「本来有几条会拦」的可观测性。
168
+ // 拦截结论由 `ok` / `blocked` 布尔表达(私有库恒 false/true),清单只作报告。
169
+ if (!Array.isArray(engineAudit.blocked) || engineAudit.blocked.length === 0) {
170
+ // 私有库时包把 blocked 归零,但报告形态仍给原始清单(租户侧读取 audit.blocked 展示)
171
+ auditOut.blocked = findings.filter((f) => f.severity === 'blocker' || f.severity === 'error')
172
+ .map((f) => ({ file: f.file, line: f.line, rule: f.rule, message: String(f.message || '').slice(0, 80) }));
173
+ }
174
+ }
175
+ const blocked = auditOut.blocked;
176
+
133
177
  // ── 结果文案:交给「可用预处理」渲染,git 侧只保留兜底 ──
134
178
  // 数据契约(ctx):repoPath + audit{summary,quality,findings,scope,files} + blocked + exempt
135
179
  // 兜底:预处理不可用 / 没实现 renderResult / 渲染抛错 时用中性默认(defaultRenderResult),
@@ -147,11 +191,11 @@ export async function runAudit({ repoPath = '', audit, rulesetDir, slots, cfg: e
147
191
  ...(auditOut.exempt ? { exempt: auditOut.exempt } : {}),
148
192
  };
149
193
  const fallbackRender = defaultPreprocessRender(renderCtx);
150
- const rendered = renderPreprocessResult(renderCtx, cfg);
194
+ const rendered = await (async () => { try { const api = await auditClient.hostApi(); return api.renderAuditResult(renderCtx, cfg); } catch { return undefined; } })();
151
195
  auditOut.apiGuide = rendered?.apiGuide ?? fallbackRender.apiGuide;
152
196
  if (auditOut.exempt) auditOut.exempt.note = rendered?.notes?.exempt ?? fallbackRender.notes.exempt;
153
197
 
154
- if (blocked.length > 0) {
198
+ if (blocked.length > 0 && !auditOut.privateExempt) {
155
199
  // 【修复】私有库豁免(README「④ 私有库豁免」):远端可见性 = private → 审计只报告不拦截。
156
200
  // 修复背景:私有库被拦的回归——
157
201
  // 此前拦截判定只看「示例目录」、没有可见性分级,
@@ -1,4 +1,11 @@
1
- // dsh-skip-residue: 豁免注册表元数据含 debugger/console 关键词声明(规则定义,非真实残留)
1
+ /**
2
+ * 豁免标记与目录判定的**宿主侧快照**(权威定义在审计包 lib/exempt/index.js)。
3
+ *
4
+ * 为什么需要快照:git 侧的 .gitignore 与敏感文件扫描在**同步**路径上要判「某标记能否豁免该 finding」
5
+ * 以及「该目录是否示例/测试夹具」,而审计包只能异步加载。整文件复制而非零散搬运——
6
+ * 零散搬运漏一个私有辅助函数就会在运行时炸(本文件第一版就因为漏了缓存辅助而报错)。
7
+ * 由 test/git/test-exempt-markers-parity.mjs 对拍:包与快照行为分叉即红。
8
+ */
2
9
  import { join, resolve, dirname, sep } from 'node:path';
3
10
  import { statSync } from 'node:fs';
4
11
  /**
package/lib/git/ignore.js CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  import { existsSync, readFileSync, writeFileSync } from 'node:fs';
8
8
  import { join } from 'node:path';
9
- import { isSampleExemptDir } from '../exempt/index.js';
9
+ import { isSampleExemptDir } from './exempt-markers.js';
10
10
  import { scanSensitiveFiles } from './sensitive.js';
11
11
 
12
12
  /**
package/lib/git/repos.js CHANGED
@@ -11,8 +11,8 @@ import { runGit, runGitAsync } from './exec.js';
11
11
 
12
12
  /* ───────── 仓库扫描常量 ───────── */
13
13
  const LS_IGNORED_TIMEOUT_MS = 15_000; // git ls-files --ignored 超时
14
- // 扫描下钻深度默认值:与 lib/plugin/auto-push.js 共用同一来源(lib/audit-defaults.js)
15
- import { DEFAULT_SCAN_DEPTH } from '../audit-defaults.js';
14
+ // 扫描下钻深度默认值:与 lib/plugin/auto-push.js 共用同一来源(lib/git/defaults.js)
15
+ import { DEFAULT_SCAN_DEPTH } from './defaults.js';
16
16
 
17
17
  /**
18
18
  * 扫描目录下的 git 仓库(1.0.0 接线:git_scan 工具用)。
@@ -8,7 +8,7 @@
8
8
 
9
9
  import { readFile, readdir, stat } from 'node:fs/promises';
10
10
  import { join } from 'node:path';
11
- import { isTestExemptDir } from '../exempt/index.js';
11
+ import { isTestExemptDir } from './exempt-markers.js';
12
12
  import { getSkipSet } from '../skip-dirs.js';
13
13
 
14
14
  /* ───────────────────────── 敏感文件自动 .gitignore ───────────────────────── */
@@ -7,12 +7,13 @@
7
7
  * ③ 真发前先体检:`private:true` 拦截、同名版本占用检测、`npm pack --dry-run` 文件清单。
8
8
  * 凭据:一律 `--userconfig` 指向插件物化的 0600 npmrc(不碰用户全局 ~/.npmrc、token 不进仓库)。
9
9
  */
10
- import { appendFileSync, existsSync, readFileSync, statSync } from 'node:fs';
10
+ import { appendFileSync, existsSync, mkdtempSync, readFileSync, statSync, writeFileSync } from 'node:fs';
11
+ import { tmpdir } from 'node:os';
11
12
  import { join } from 'node:path';
12
13
 
13
14
  import { credentialsDir, readNpmToken } from '../core/credentials.js';
14
15
  import { DEFAULT_REGISTRY, NPM_TIMEOUT_MS, normalizeRegistry, runNpm } from './registry.js';
15
- import { npmArgs, writeNpmrc } from './npmrc.js';
16
+ import { npmArgs, npmrcText, writeNpmrc } from './npmrc.js';
16
17
  import { smokeTestPackage, entrySpecsOf, isBrowserEntry, classifyPackageForm } from './smoke.js';
17
18
  import { runLocalPreview } from './local-registry.js';
18
19
 
@@ -109,7 +110,14 @@ export function parsePackOutput(text = '', { maxCandidates = 200 } = {}) {
109
110
  export function packDryRun({ dir, registry = DEFAULT_REGISTRY, workspaceRoot = '', token = '', timeoutMs = PUBLISH_TIMEOUT_MS } = {}) {
110
111
  try {
111
112
  const merged = { ...process.env };
112
- const rc = writeNpmrc({ workspaceRoot, registry, token });
113
+ // **不能写真实凭据目录的 npmrc**:writeNpmrc 写的是 credentialsDir 下的**持久**文件,
114
+ // 而本函数只是「预演」——用预演覆盖真实 npmrc 会把用户的真 token 冲掉。
115
+ // 实测事故:本地彩排跑完后 npmrc 变成临时 token(11 字符)⇒ 之后所有 npm 命令 401。
116
+ // 预演只需要一份**临时** npmrc,写到临时目录、用完即弃。
117
+ const tempDir = mkdtempSync(join(tmpdir(), 'dshgp-pack-'));
118
+ const tempRc = join(tempDir, '.npmrc');
119
+ writeFileSync(tempRc, npmrcText({ registry, token }), { mode: 0o600 });
120
+ const rc = { ok: true, file: tempRc };
113
121
  if (!rc.ok) return { ok: false, error: rc.error || 'npmrc 写入失败' };
114
122
  // cwd 必须显式给:npm pack 以「工作目录」为目标包,继承宿主 cwd 会去错目录
115
123
  // (实测:宿主 cwd 无 package.json ⇒ ENOENT;有 ⇒ 打包整棵树 ⇒ ENOBUFS)
@@ -184,8 +192,15 @@ export async function publishPackage({
184
192
  // 体检①:private:true 会被 npm 拒绝(提前给结论,省一次网络)
185
193
  if (info.private) return { ok: false, blocked: 'private-true', name: info.name, version: info.version, error: 'package.json 标了 private:true ⇒ npm publish 会被拒绝(去掉该字段或改用私有 registry)' };
186
194
  // 体检②:同名版本是否已存在
187
- const pub = await fetchPublishedVersions({ name: info.name, registry: reg, timeoutMs: NPM_TIMEOUT_MS });
188
- const versionTaken = pub.ok && pub.versions.includes(info.version);
195
+ // **网络边界**:这一步是 GET 真实上游 registry(只读,不写入)。
196
+ // localPreview=true 时**跳过**——本地 registry 是空的,「版本占用」无从判断也无意义;
197
+ // 跳过之后整条链路(publish → install → 加载)全程不碰公网。
198
+ let versionTaken = false;
199
+ let pub = { ok: false, versions: [] };
200
+ if (!localPreview) {
201
+ pub = await fetchPublishedVersions({ name: info.name, registry: reg, timeoutMs: NPM_TIMEOUT_MS });
202
+ versionTaken = pub.ok && pub.versions.includes(info.version);
203
+ }
189
204
  if (versionTaken) {
190
205
  return { ok: false, blocked: 'version-taken', name: info.name, version: info.version, versions: pub.versions, error: `${info.name}@${info.version} 已存在于 registry ⇒ 先升版本号再发` };
191
206
  }
@@ -25,8 +25,8 @@ import { runGit } from '../git/exec.js';
25
25
 
26
26
  /* ───────── 自动推送常量 ───────── */
27
27
  const AUTO_PUSH_SETTLE_MS = 800; // 回合结束后等收尾落盘的防抖时长
28
- // 扫描仓库下钻深度默认值:与 lib/git/repos.js 共用同一来源(lib/audit-defaults.js)
29
- import { DEFAULT_SCAN_DEPTH } from '../audit-defaults.js';
28
+ // 扫描仓库下钻深度默认值:与 lib/git/repos.js 共用同一来源(lib/git/defaults.js)
29
+ import { DEFAULT_SCAN_DEPTH } from '../git/defaults.js';
30
30
 
31
31
  /** 触发面开关(默认全关——保守:自动推送与审计都不默认开,需用户经 UI 显式开启)。 */
32
32