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
@@ -8,7 +8,7 @@ import { join } from 'node:path';
8
8
  import { pushCurrentBranch, resolveToken, githubFetch, setVisibility, refreshAccountStatus, detectRepoVisibility, runGit, parseGithubOwnerRepo } from '../../git/index.js';
9
9
  import { updateRepoIndex } from '../../git/repo-index.js';
10
10
  import { commitWithAudit } from '../../commit-push.js';
11
- import { isBlockerFinding } from '../../audit/index.js';
11
+ import { isBlockerSeverity } from '../severity.js';
12
12
 
13
13
  /* ───────── 仓库动作常量 ───────── */
14
14
  const COMMIT_SHA_MAX_LEN = 40; // commit sha 展示截断长度
@@ -104,7 +104,6 @@ export async function handleRepoCommit(ctx) {
104
104
  message,
105
105
  push: false,
106
106
  audit: true,
107
- requirementsConfirmed: true,
108
107
  pushMethod: cfg.pushMethod || 'ssh',
109
108
  pushGate: false,
110
109
  pushConfirmed: true,
@@ -112,7 +111,7 @@ export async function handleRepoCommit(ctx) {
112
111
  if (!r.ok) {
113
112
  const findings = r.audit?.findings || [];
114
113
  // 统一口径:error 也属拦截级(与 summarize 一致,此前只筛 'blocker' ⇒ 枚举少于 summary)
115
- const blockers = findings.filter(isBlockerFinding).slice(0, 3)
114
+ const blockers = findings.filter(isBlockerSeverity).slice(0, 3)
116
115
  .map((f) => `${f.file}:${f.line} ${f.rule}`);
117
116
  return {
118
117
  status: 200,
@@ -16,11 +16,15 @@ import {
16
16
  } from '../../git/repo-index.js';
17
17
  import { runScan, waitScanDelta } from '../../git/index.js';
18
18
  import { getDefaultScanRoot } from '../scan-root.js';
19
- import { LIST_LIVE_BUDGET_MS, PROBE_CONCURRENCY, SCAN_WAIT_TIMEOUT_MS } from './http-constants.js';
19
+ import { LIST_LIVE_BUDGET_MS, LIST_LIVE_TTL_MS, PROBE_CONCURRENCY, SCAN_WAIT_TIMEOUT_MS } from './http-constants.js';
20
20
 
21
21
  /** GET/POST /api/git-push/repos-local —— 本地仓库列表(读索引 + live 并发探测远端)。 */
22
22
  /** 构建本地仓库列表(读索引 → 本地路径探测 → 标记待 remote live 探测)。 */
23
- function buildLocalList(indexMap, root, deadline) {
23
+ function buildLocalList(indexMap, root, deadline, options) {
24
+ // probeLocal=false ⇒ **不 spawn 任何 git**,本地状态取索引里上次扫描/补查记下的快照。
25
+ // 为什么必须能关:这里每仓要跑 describeRepo + git log(4 次同步 spawn),
26
+ // 27 仓在 CIFS 上实测 ≈100s —— 放进 HTTP 请求就等于"打开列表必超时"。
27
+ const probeLocal = !(options && options.probeLocal === false);
24
28
  return Object.keys(indexMap).map((name) => {
25
29
  const entry = indexMap[name];
26
30
  const local = entry.path || join(root, name);
@@ -38,7 +42,16 @@ function buildLocalList(indexMap, root, deadline) {
38
42
  cloudOnly: !!entry.cloudOnly,
39
43
  branch: '', ahead: null, behind: null, changed: 0, lastCommit: '',
40
44
  };
41
- if (exists) {
45
+ // 索引里上次记下的本地状态(扫描/后台补查写入):请求路径直接用它,零 spawn
46
+ const cachedLocal = (entry.localState && typeof entry.localState === 'object') ? entry.localState : null;
47
+ if (cachedLocal) {
48
+ out.branch = cachedLocal.branch || '';
49
+ out.changed = Number(cachedLocal.changed) || 0;
50
+ out.lastCommit = cachedLocal.lastCommit || '';
51
+ out.localHead = cachedLocal.localHead || cachedLocal.lastCommit || '';
52
+ out.localHeadAt = cachedLocal.localHeadAt || '';
53
+ }
54
+ if (exists && probeLocal) {
42
55
  try {
43
56
  const repoState = describeRepo(local);
44
57
  out.branch = repoState.branch || '';
@@ -133,7 +146,74 @@ async function applyLiveRemote(list, deadline) {
133
146
  return list;
134
147
  }
135
148
 
136
- /** GET/POST /api/git-push/repos-local —— 本地仓库列表(读索引 + live 并发探测远端)。 */
149
+ /**
150
+ * 用索引里**上次补查到的远端状态**填充列表(纯本地计算,不联网)。
151
+ *
152
+ * 为什么要这么做:ahead/behind 只需要一个已知的远端 sha(本地 rev-list 就能算),
153
+ * 不需要再连一次远端。于是"列表请求"的代价 = 读索引 + 每仓一次本地 git,
154
+ * 与仓库数量线性但都是毫秒级;真正的网络探测交给后台。
155
+ *
156
+ * 没补过的仓库保持 liveSkipped=true(= 真未知,前端据此显示"同步中"而不是"0/0")。
157
+ * @param {Array<object>} list buildLocalList 的输出
158
+ * @returns {{liveAt: string, stale: boolean}} liveAt=最新一次远端状态时间
159
+ */
160
+ function mergeCachedRemote(list) {
161
+ let newestAt = 0;
162
+ let unknown = 0;
163
+ for (const row of list) {
164
+ const entry = row.indexed || {};
165
+ if (!row.path || !row.hasRemote) continue;
166
+ if (!entry.remoteHead) { row.liveSkipped = true; unknown += 1; continue; }
167
+ row.remoteHead = entry.remoteHead;
168
+ row.remoteHeadAt = entry.remoteHeadAt || '';
169
+ // ahead/behind 直接用索引里上次比较的结果 —— **不在请求路径 spawn git**
170
+ // (每个 spawn 在 CIFS 上 ≈1s,27 仓就能把 500ms 目标打成 100s)
171
+ if (entry.ahead === null || entry.ahead === undefined || entry.behind === null || entry.behind === undefined) {
172
+ row.ahead = null; row.behind = null; row.synced = false; row.liveSkipped = true;
173
+ } else {
174
+ row.ahead = Number(entry.ahead) || 0;
175
+ row.behind = Number(entry.behind) || 0;
176
+ row.synced = entry.synced === true;
177
+ }
178
+ const at = Date.parse(entry.remoteHeadAt || '');
179
+ if (Number.isFinite(at) && at > newestAt) newestAt = at;
180
+ }
181
+ const liveAt = newestAt ? new Date(newestAt).toISOString() : '';
182
+ const missingLocal = list.filter((r) => r.path && !r.lastCommit).length;
183
+ const tooOld = !newestAt || (Date.now() - newestAt) > LIST_LIVE_TTL_MS;
184
+ return { liveAt: liveAt, stale: tooOld || unknown > 0 || missingLocal > 0 };
185
+ }
186
+
187
+ /** 同一时刻只跑一个后台补查任务(多开页面/连续刷新不叠加探测)。 */
188
+ let liveRefreshRunning = false;
189
+
190
+ /**
191
+ * 后台补查远端状态(不阻塞请求):逐仓探测 → 写回索引 → 下次列表请求就带上了。
192
+ *
193
+ * 为什么放后台:27 仓 × SSH 实测 87s,放在请求里必然把前端 30s 超时打爆。
194
+ * 失败不影响列表:列表继续用上一次的状态,只是 stale 保持为真。
195
+ * @param {Array<object>} list 当前列表(只取有 path+hasRemote 的)
196
+ * @param {object} env 运行环境(workspaceRoot 等)
197
+ * @returns {boolean} 是否真的启动了(已有任务在跑 ⇒ false)
198
+ */
199
+ function scheduleLiveRefresh(list, env) {
200
+ if (liveRefreshRunning) return false;
201
+ const targets = list
202
+ .filter((r) => r.path && (r.hasRemote || !r.lastCommit))
203
+ .map((r) => ({ name: r.name, path: r.path, branch: r.branch || '' }));
204
+ if (!targets.length) return false;
205
+ liveRefreshRunning = true;
206
+ void (async () => {
207
+ try {
208
+ for (const target of targets) await refreshOneTarget(target, env);
209
+ } catch { /* 后台补查失败不影响列表:下一次请求仍会看到 stale 并重试 */ } finally {
210
+ liveRefreshRunning = false;
211
+ }
212
+ })();
213
+ return true;
214
+ }
215
+
216
+ /** GET/POST /api/git-push/repos-local —— 本地仓库列表(**只读索引快照**;远端状态后台补)。 */
137
217
  export async function handleReposLocal(ctx) {
138
218
  const { query, env, cfg } = ctx;
139
219
  const rebuild = query.rebuild === '1' || query.rebuild === 'true';
@@ -148,13 +228,44 @@ export async function handleReposLocal(ctx) {
148
228
  }
149
229
  const indexMap = readRepoIndexMap(env.workspaceRoot);
150
230
  let list = [];
231
+ let liveAt = '';
232
+ let stale = false;
151
233
  if (indexMap) {
152
- const deadline = Date.now() + LIST_LIVE_BUDGET_MS;
153
- list = buildLocalList(indexMap, path, deadline);
154
- await applyLiveRemote(list, deadline);
234
+ if (query.live === '1') {
235
+ // 显式"现在就同步探测"(排障/测试/手动刷新用):沿用原先的预算内并发探测。
236
+ // 默认路径**不走这里** —— 27 仓实测 87s,放在默认请求里必然把前端超时打爆。
237
+ const deadline = Date.now() + LIST_LIVE_BUDGET_MS;
238
+ list = buildLocalList(indexMap, path, deadline);
239
+ await applyLiveRemote(list, deadline);
240
+ stale = false;
241
+ } else {
242
+ // 默认:只读索引快照(不联网),远端状态用上次补查结果,本地即可算 ahead/behind
243
+ list = buildLocalList(indexMap, path, 0, { probeLocal: false });
244
+ const cached = mergeCachedRemote(list);
245
+ liveAt = cached.liveAt;
246
+ stale = cached.stale;
247
+ }
155
248
  if (owner) list = list.filter((r) => (r.indexed?.owner === owner) || !r.indexed?.owner);
249
+ // 远端状态过期/从未补过 ⇒ 交给后台补,请求立刻返回。
250
+ // ⚠️ 必须延到下一个宏任务再启动:补查函数里第一句是**同步** git spawn(runGit 取分支),
251
+ // 直接调会在返回响应前就阻塞住(实测总耗时 3.9s,其中 3.5s 是这句同步 git)。
252
+ if (stale) setTimeout(() => { scheduleLiveRefresh(list, env); }, 0);
156
253
  }
157
- return { status: 200, body: { ok: true, root: path, count: list.length, repos: list, owner: owner || null, indexedAvailable: !!indexMap, indexUpdated: rebuildIndexUpdated === true } };
254
+ return {
255
+ status: 200,
256
+ body: {
257
+ ok: true,
258
+ root: path,
259
+ count: list.length,
260
+ repos: list,
261
+ owner: owner || null,
262
+ indexedAvailable: !!indexMap,
263
+ indexUpdated: rebuildIndexUpdated === true,
264
+ // 远端状态的可见性交给前端:liveAt=上次同步时间,stale=正在后台补
265
+ liveAt: liveAt,
266
+ stale: stale,
267
+ },
268
+ };
158
269
  }
159
270
 
160
271
  export function handleReposLocalScan(ctx) {
@@ -209,8 +320,24 @@ async function refreshOneTarget(t, env) {
209
320
  state.compareOk = false;
210
321
  state.error = live.error || '远端不可达';
211
322
  }
212
- const up = updateRepoIndex({ workspaceRoot: env.workspaceRoot, repoName: name, remoteState: state, mode: 'single' });
213
- return { name, ok: true, remoteState: state, indexUpdated: up.ok, error: up.error };
323
+ // 顺手把**本地状态**一起记进索引:列表请求随后就能零 spawn 地渲染分支/未提交数/最近提交。
324
+ // 不记的话,请求路径只能每仓 describeRepo + git log(CIFS 上每仓 ≈4 次慢 spawn)。
325
+ const localState = (function () {
326
+ try {
327
+ const rs = describeRepo(repoPath);
328
+ const lc = runGit(['log', '-1', '--format=%cI'], { cwd: repoPath });
329
+ return {
330
+ branch: rs.branch || branch || '',
331
+ changed: Number(rs.changed) || 0,
332
+ lastCommit: rs.lastCommit || '',
333
+ localHead: rs.lastCommit || '',
334
+ localHeadAt: lc.ok ? (lc.stdout || '').trim() : '',
335
+ at: new Date().toISOString(),
336
+ };
337
+ } catch { return null; }
338
+ })();
339
+ const up = updateRepoIndex({ workspaceRoot: env.workspaceRoot, repoName: name, remoteState: state, localState: localState, mode: 'single' });
340
+ return { name, ok: true, remoteState: state, localState: localState, indexUpdated: up.ok, error: up.error };
214
341
  } catch (e) {
215
342
  return { name, ok: false, error: String(e?.message || e) };
216
343
  }
@@ -6,37 +6,51 @@
6
6
  * 设置读写走插件私有 config.json(不写公共 settings.yaml,见 settings-bridge.js 说明)。
7
7
  */
8
8
  import { redactConfig } from '../schema.js';
9
- import { readSettings, writeSettingsKey, applySettingsToCfg, appendSettingsLog } from '../settings-bridge.js';
9
+ import { readSettings, writeSettingsKey, writePreCommitEnabled, applySettingsToCfg, appendSettingsLog } from '../settings-bridge.js';
10
10
  import { persistSshPub, persistGithubToken, persistNpmToken } from '../../git/index.js';
11
11
 
12
12
  /** GET /api/git-push/settings-get —— 读插件 config.json 设置快照(token/ssh 掩码)。 */
13
13
  export function handleSettingsGet(ctx) {
14
14
  const { env } = ctx;
15
15
  const snap = readSettings({ workspaceRoot: env.workspaceRoot });
16
- // 同步 apply 后 cfg(settings-set 写盘后内存 cfg 即时更新;读侧也对齐
17
- // ——部分字段如 auditEnabled 在 status/settings-get 都读 cfg,需与内存一致)
18
16
  return { status: 200, body: { ok: true, settings: redactConfig(snap || {}) } };
19
17
  }
20
18
 
21
19
  /** 凭据类设置键:写成功后的回显值必须脱敏(明文只留在 config.json 0600 与凭据文件)。 */
22
20
  const SENSITIVE_SETTING_KEYS = new Set(['githubToken', 'sshPub', 'npmToken']);
23
21
 
22
+ /**
23
+ * 「提交前预处理」总开关的**前端键名**(settings-set 的扁平键)。
24
+ *
25
+ * 为什么需要扁平别名:配置文件里的真身是嵌套的 `preCommit.enabled`(与同块的
26
+ * command/args/timeoutMs 一起构成引擎配置),而 settings-set 的协议是「一个 key 一个 value」。
27
+ * 前端只认这个扁平键,写盘时翻译成嵌套键级合并(见 writePreCommitEnabled),
28
+ * 避免「改开关把同块的引擎路径一起覆盖掉」。
29
+ */
30
+ const PRECOMMIT_ENABLED_KEY = 'preCommitEnabled';
31
+
32
+ /**
33
+ * settings-set 允许写的键(白名单,防越权写入任意字段)。
34
+ *
35
+ * 为什么要显式列全:这条白名单是「前端能改什么」的唯一闸门,少列一个键 = 那个设置
36
+ * 静默存不下来;多列一个键 = 越权面。测试会把它与前端声明逐键比对,改这里必须同步。
37
+ */
38
+ export const ALLOWED_SETTING_KEYS = [
39
+ PRECOMMIT_ENABLED_KEY, 'injectSystemPrompt',
40
+ 'maxCloneFileMB', 'cloneConcurrency',
41
+ 'pushMethod',
42
+ 'githubToken', 'sshPub', 'pushGate',
43
+ 'npmToken', 'npmRegistry',
44
+ 'autoPushEnabled', 'autoPushTriggerText', 'autoPushScope', 'autoPushMessage',
45
+ ];
46
+
24
47
  /** POST /api/git-push/settings-set —— 写单个设置键(白名单防越权)。 */
25
48
  export async function handleSettingsSet(ctx) {
26
49
  const { body, env, cfg } = ctx;
27
50
  const log = ctx.cfg?.log || ctx.log || { warn: () => {} };
28
51
  const key = String(body.key || '');
29
52
  // 白名单:仅允许前端设置卡片声明的键(凭据走这里 + 下方同步 cfg)
30
- const allowedKeys = new Set([
31
- 'auditEnabled', 'injectRequirements', 'injectSystemPrompt', 'auditScanScope',
32
- 'maxScanFiles', 'weightOverrides',
33
- 'maxCloneFileMB', 'cloneConcurrency',
34
- 'pushMethod', 'auditRuleOrder', 'auditDisabledSlots',
35
- 'githubToken', 'sshPub', 'pushGate',
36
- 'npmToken', 'npmRegistry',
37
- 'autoPushEnabled', 'autoPushTriggerText', 'autoPushScope', 'autoPushMessage',
38
- ]);
39
- if (!allowedKeys.has(key)) return { status: 400, body: { ok: false, error: `不支持的设置键: ${key || '(空)'}` } };
53
+ if (!ALLOWED_SETTING_KEYS.includes(key)) return { status: 400, body: { ok: false, error: `不支持的设置键: ${key || '(空)'}` } };
40
54
  // 凭据落插件目录(github-token / *.pub / npmToken 一律 0600,绝不入库)
41
55
  if (key === 'githubToken') {
42
56
  const r = persistGithubToken(body.value, { workspaceRoot: env.workspaceRoot });
@@ -50,14 +64,19 @@ export async function handleSettingsSet(ctx) {
50
64
  const r = persistNpmToken(body.value, { workspaceRoot: env.workspaceRoot });
51
65
  if (!r.ok) return { status: 400, body: { ok: false, error: `npm token 持久化失败: ${r.error || '未知错误'}` } };
52
66
  }
53
- const r = await writeSettingsKey(key, body.value, { workspaceRoot: env.workspaceRoot });
67
+ // 嵌套块走专用写路径(键级合并);其余键仍走通用整键写入
68
+ const r = key === PRECOMMIT_ENABLED_KEY
69
+ ? await writePreCommitEnabled(body.value, { workspaceRoot: env.workspaceRoot })
70
+ : await writeSettingsKey(key, body.value, { workspaceRoot: env.workspaceRoot });
54
71
  appendSettingsLog({ key, value: body.value, via: 'http-settings-set', ok: r.ok, error: r.error }, { workspaceRoot: env.workspaceRoot });
55
72
  if (!r.ok) {
56
73
  return { status: r.code === 'BAD_KEY' ? 400 : 500, body: { ok: false, code: r.code || 'SETTINGS_WRITE', error: r.error } };
57
74
  }
58
75
  // 写盘成功后同步内存 cfg(即时生效;config.json 才是真源)
59
76
  try {
60
- applySettingsToCfg(cfg, { [key]: body.value });
77
+ applySettingsToCfg(cfg, key === PRECOMMIT_ENABLED_KEY
78
+ ? { preCommit: { enabled: body.value } }
79
+ : { [key]: body.value });
61
80
  } catch (e) {
62
81
  log?.warn?.(`settings-set cfg 同步跳过:${e?.message || e}`);
63
82
  }
@@ -11,10 +11,10 @@ import { defaultConfig } from '../client/index.js';
11
11
  import {
12
12
  handleStatus, handleScan, handleBrowse, handleTools, handleToolProbes,
13
13
  } from './handlers/meta.js';
14
- // 审计侧 handler 已独立成文件(与 /api/git-audit 前缀同构):git 侧路由不再 import 审计实现
14
+ // 预处理 handler 已独立成文件(走 /api/preprocess 前缀):git 侧路由不再 import 预处理实现
15
15
  import {
16
16
  listRuleSlots, handleRuleSlots, handleRuleDetail, handleAudit, handleToggleRule, handleExemptHint,
17
- } from './handlers/audit.js';
17
+ } from './handlers/preprocess.js';
18
18
  import {
19
19
  handleReposLocal, handleReposLocalScan, handleReposLocalScanWait, handleReposLocalRefresh, handleReposCloud,
20
20
  } from './handlers/repos.js';
@@ -36,7 +36,7 @@ import {
36
36
  import { handleNpmAccount, handleNpmCheck, handleNpmOwned, handleNpmPackages, handleNpmInstall, handleNpmPublish, handleNpmInstallProgress } from './handlers/npm.js';
37
37
  import { appendHttpRejectLog } from './settings-bridge.js';
38
38
  /** 规则槽位清单对外导出(实现迁至 handlers/meta.js)。 */
39
- export { listRuleSlots } from './handlers/audit.js';
39
+ export { listRuleSlots } from './handlers/preprocess.js';
40
40
 
41
41
  /**
42
42
  * HTTP 适配:DSH webServer 原生 (req, res) ↔ v2 纯函数 handleHttp({status, body})。
@@ -89,35 +89,10 @@ function buildCtx(req, method, env, cfg, query, body, path) {
89
89
  }
90
90
 
91
91
  /** 审计侧 HTTP 前缀(与 git 侧 `/api/git-push` 物理分开;git 侧 25 条路径一个字未改)。 */
92
- export const AUDIT_API_PREFIX = '/api/git-audit';
93
-
94
- /** 旧前缀下的审计路径:保留一版转发,响应带 Deprecation 头(指向新路径)。 */
95
- const DEPRECATED_AUDIT_PATHS = new Map([
96
- ['/api/git-push/audit', `${AUDIT_API_PREFIX}/audit`],
97
- ['/api/git-push/rule-slots', `${AUDIT_API_PREFIX}/rule-slots`],
98
- ['/api/git-push/rule-detail', `${AUDIT_API_PREFIX}/rule-detail`],
99
- ['/api/git-push/toggle-rule', `${AUDIT_API_PREFIX}/toggle-rule`],
100
- ['/api/git-push/exempt-hint', `${AUDIT_API_PREFIX}/exempt-hint`],
101
- ]);
102
-
103
- /**
104
- * 给「旧路径转发」的响应补上废弃标记。
105
- * 为什么用响应头而不是错误:旧路径仍然**能用**(兼容一版),只是要在自动化能看见的地方留痕,
106
- * 将来移除时才有人能拿出「谁还在调」的证据。`Link: rel="successor-version"` 是 RFC 5829 的标准写法。
107
- * @param {object} result handler 返回值 { status, body, headers? }
108
- * @param {string} successorPath 新路径
109
- * @returns {object}
110
- */
111
- function withDeprecation(result, successorPath) {
112
- return {
113
- ...result,
114
- headers: {
115
- ...(result?.headers || {}),
116
- Deprecation: 'true',
117
- Link: `<${successorPath}>; rel="successor-version"`,
118
- },
119
- };
120
- }
92
+ // 通用预处理前缀(审计只是第一个 provider)。
93
+ // 路由形如 /api/preprocess/<action>,action 来自各 provider 的 manifest 声明;
94
+ // 宿主不写死具体实现名,新增 provider 不需要改这里。
95
+ export const PREPROCESS_API_PREFIX = '/api/preprocess';
121
96
 
122
97
  /**
123
98
  * HTTP 端点分发(鉴权前置:Origin/CSRF → 413 → 写确认 → switch 路由)。
@@ -179,18 +154,14 @@ export async function handleHttp(req = {}, env = {}, cfg = defaultConfig()) {
179
154
  case '/api/git-push/tools': return handleTools(ctx);
180
155
  case '/api/git-push/tool-probes': return handleToolProbes(ctx);
181
156
  // ── 审计侧(新前缀):规则包 / 审计结果聚合 / 规则启停 / 豁免提示 ──
182
- case '/api/git-audit/rule-slots': return handleRuleSlots(ctx);
183
- case '/api/git-audit/rule-detail': return handleRuleDetail(ctx);
184
- case '/api/git-audit/audit': return await handleAudit(ctx);
185
- case '/api/git-audit/toggle-rule': return handleToggleRule(ctx);
157
+ case '/api/preprocess/rule-slots': return handleRuleSlots(ctx);
158
+ case '/api/preprocess/rule-detail': return handleRuleDetail(ctx);
159
+ case '/api/preprocess/audit': return await handleAudit(ctx);
160
+ case '/api/preprocess/toggle-rule': return handleToggleRule(ctx);
186
161
  // 豁免标记查询(只读):供外部工具推导「该写哪个 dsh-skip-*」,避免复制标记注册表
187
- case '/api/git-audit/exempt-hint': return handleExemptHint(ctx);
162
+ case '/api/preprocess/exempt-hint': return handleExemptHint(ctx);
188
163
  // ── 旧前缀(兼容一版):转发到同一 handler + Deprecation 头 ──
189
- case '/api/git-push/rule-slots': return withDeprecation(handleRuleSlots(ctx), `${AUDIT_API_PREFIX}/rule-slots`);
190
- case '/api/git-push/rule-detail': return withDeprecation(handleRuleDetail(ctx), `${AUDIT_API_PREFIX}/rule-detail`);
191
- case '/api/git-push/audit': return withDeprecation(await handleAudit(ctx), `${AUDIT_API_PREFIX}/audit`);
192
- case '/api/git-push/toggle-rule': return withDeprecation(handleToggleRule(ctx), `${AUDIT_API_PREFIX}/toggle-rule`);
193
- case '/api/git-push/exempt-hint': return withDeprecation(handleExemptHint(ctx), `${AUDIT_API_PREFIX}/exempt-hint`);
164
+ // 历史调用方(脚本/文档/AI 记忆里的旧地址)不该因为改前缀就 404。
194
165
  case '/api/git-push/account-status': return handleAccountStatus(ctx);
195
166
  case '/api/git-push/npm-account': return await handleNpmAccount(ctx);
196
167
  case '/api/git-push/npm-check': return await handleNpmCheck(ctx);
package/lib/app/index.js CHANGED
@@ -20,11 +20,12 @@ export { Config } from './schema.js';
20
20
  export { MSG_REPO_REQUIRED, name, GIT_PUSH_SETTINGS_NS } from './constants.js';
21
21
  export { setLastSlotHitStats, getLastSlotHitStats, getLastSlotHitMeta } from './slot-stats.js';
22
22
  export { listTools } from './tools.js';
23
- export { README_CHECK_HINT, buildRequirementsInjectionText, formatAuditBlock } from './inject-text.js';
23
+ export { README_CHECK_HINT, buildIdentityInjectionText, formatAuditBlock } from './inject-text.js';
24
24
  export { callTool } from './tool-call.js';
25
25
  export { adaptHttpHandler, listRuleSlots, handleHttp } from './http-handlers.js';
26
26
  export { apply } from './apply.js';
27
- export { parseGitAuditInput, sessionCwdOf, findGitRoot, resolveAuditRepo, runGitAuditCommand, registerSlashCommands } from './slash-commands.js';
27
+ // 审计斜杠命令(/git-audit /git-io-scan /link-check)随审计能力迁出宿主,只剩 git 侧命令
28
+ export { sessionCwdOf, findGitRoot, registerSlashCommands } from './slash-commands.js';
28
29
 
29
30
  import { routeRequest, readJsonBody } from '../http/index.js';
30
31
  export { routeRequest, readJsonBody };
@@ -3,14 +3,13 @@
3
3
  *
4
4
  * FUNCTION_USAGE_HINT(插件功能用法注入——每个工具怎么用 + 凭据由插件托管,见需求:
5
5
  * 「注入系统提示词可以注入插件每个功能怎么用,发现好多不用插件还到处找凭据的」)、
6
- * buildRequirementsInjectionText(开发者要求清单注入,挂审计开关子开关)、
6
+ * buildIdentityInjectionText(身份告知注入,避免 AI 猜错项目归属)、
7
7
  * formatAuditBlock(审计结果块)、README_CHECK_HINT(提交前 README 核对提醒)。
8
8
  * 这些是「写进系统提示词/工具返回」的文本,与业务逻辑分开便于单独校对措辞。
9
9
  */
10
10
 
11
11
  import { networkInterfaces } from 'node:os';
12
12
  import { join } from 'node:path';
13
- import { loadRequirements } from '../git/index.js';
14
13
  import { readAccountStatus } from '../git/account-status.js';
15
14
  import { identityHintText, resolveCommitIdentity } from '../git/identity.js';
16
15
 
@@ -26,8 +25,8 @@ import { identityHintText, resolveCommitIdentity } from '../git/identity.js';
26
25
  export const FUNCTION_USAGE_HINT = [
27
26
  '【dsh-git-push 功能用法】本插件的 git 操作请直接调用下列工具,不要手敲 git/curl 绕过(插件自带审计门禁、凭据管理、推送通道选择);**工作区没有改动 / 没有新提交时也照常调用,不会报错**(详见 git_commit_push 说明),不要因为「怕它报错」而绕开插件:',
28
27
  '· git_scan —— 列工作区(含额外路径)所有 git 仓库:分支/remote/未提交与未推送数/最近活动。找「哪个仓库要提交」先用它。',
29
- '· git_commit_push —— 一键提交并推送(一次调用 = 审计(可关)→ **有改动才** commit → **有可推内容才** push;审计同步拦截,通过后 commit+push 走宿主官方后台 job,立即返回 async:true + jobId,结果完成会自动返回、无需特意查询,可继续干别的)。参数:repo=仓库绝对路径、message=提交信息(必填,但**零改动时不会被用到**)、audit、dryRun、push、force、ignorePatterns;调用前逐条核对开发者特殊要求,达标才传 requirementsConfirmed=true(**只要配置里存在开发者要求清单,任何调用都要带——与有没有改动、是否推送无关**)。如需主动查结果:job_output <jobId>(job_list/job_kill 同理)。',
30
- ' **零改动 = 正常成功路径,不是失败**(可以放心调用):工作区没改动 ⇒ 返回 ok:true + committed:false(job 状态 completed,文案写明「无需提交(正常)」);远端已最新 ⇒ ok:true + pushed:false;而「本地领先远端」的已提交内容**照样会推上去**。所以任何时候都直接用它,不要因为「没东西可提交」改去手敲 git。(**唯一例外**:配置里存在开发者要求清单时,仍要按上文带上 `requirementsConfirmed:true`——那是要求门禁,与「有没有改动」无关。)',
28
+ '· git_commit_push —— 一键提交并推送(一次调用 = 审计(可关)→ **有改动才** commit → **有可推内容才** push;审计同步拦截,通过后 commit+push 走宿主官方后台 job,立即返回 async:true + jobId,结果完成会自动返回、无需特意查询,可继续干别的)。参数:repo=仓库绝对路径、message=提交信息(必填,但**零改动时不会被用到**)、audit、dryRun、push、force、ignorePatterns。如需主动查结果:job_output <jobId>(job_list/job_kill 同理)。',
29
+ ' **零改动 = 正常成功路径,不是失败**(可以放心调用):工作区没改动 ⇒ 返回 ok:true + committed:false(job 状态 completed,文案写明「无需提交(正常)」);远端已最新 ⇒ ok:true + pushed:false;而「本地领先远端」的已提交内容**照样会推上去**。所以任何时候都直接用它,不要因为「没东西可提交」改去手敲 git。',
31
30
  '· code_audit —— 审计仓库(L0 静态检查 + 质量评分):语法/敏感信息/凭据/大文件/文档措辞;scope=full 全量;可传 ruleset 自定规则目录、weights 覆盖权重。',
32
31
  '· git_account_check —— 校验 GitHub 账号与凭据(token 在线校验 + SSH 公钥指纹),返回登录态/用户名/公钥数/套餐。想知道「现在能不能推、以谁的身份」,用它,不要自己去翻 token 文件。',
33
32
  '· git_identity_rewrite —— 提交身份历史改写:把仓库里非规范身份(工具/AI 产生的 agent@dsh.local / eightfs@local / v2-clone@local,以及账号 noreply 的旧变体)统一成登录账号规范身份。默认 dryRun 只报告;真改写要传 dryRun:false(先建备份引用,自检通过才改写),要推远端再加 push:true(force-with-lease,远端动过自动拒绝)。只处理 origin 属于登录账号的仓库。',
@@ -58,7 +57,6 @@ export const README_CHECK_HINT = [
58
57
  * 构造「开发者特殊要求」注入正文(systemPrompt 段,需开启提交前审计 + 本子开关)。
59
58
  *
60
59
  * 价值:清单常驻系统提示词,AI 一次读到即可持续遵守,不必走「提交被门禁拦截 →
61
- * 读拦截信息里的清单 → 带 requirementsConfirmed 重试」的失败往返(每次省一轮工具调用)。
62
60
  * 清单为空/未找到时返回空串(空段不注入)。
63
61
  *
64
62
  * @returns {string} 注入正文;无清单时返回空串
@@ -83,19 +81,6 @@ export function buildIdentityInjectionText() {
83
81
  + '**不要擅自改写历史**;用户要统一历史时走 git_identity_rewrite(默认 dry-run 先预览)。';
84
82
  }
85
83
 
86
- export function buildRequirementsInjectionText() {
87
- const req = loadRequirements();
88
- const identityLine = buildIdentityInjectionText();
89
- // 没有开发者要求清单时也把身份行注入(它是「AI 别猜身份」的唯一告知途径)
90
- if (!req.found || !req.items.length) return identityLine;
91
- const L = [
92
- `【dsh-git-push 开发者要求(${req.user})】调用 git_commit_push / git_remote_create 前逐条核对,全部达标才传 requirementsConfirmed: true:`,
93
- ];
94
- req.items.forEach((it, i) => L.push(`${i + 1}. ${it}`));
95
- L.push('(需要**推送**且未核对时才会被门禁拦截;零改动、或 push=false 只提交时不受影响。清单可用插件配置目录的 requirements.json 外挂覆盖)');
96
- if (identityLine) L.push(identityLine);
97
- return L.join('\n');
98
- }
99
84
 
100
85
  /**
101
86
  * 审计结果格式化为可直接说给用户的总结块(对齐 git_account_check 的 block 模式)。
@@ -106,7 +91,7 @@ export function buildRequirementsInjectionText() {
106
91
 
107
92
  /**
108
93
  * 审计输出公共函数:只输出「级别数量 + 评分 + API 查询用法」——
109
- * 审计结果改由聚合 API 查询(/api/git-audit/audit —— 审计侧独立前缀),不再内联输出审计内容。
94
+ * 审计结果改由聚合 API 查询(/api/preprocess/audit —— 通用预处理前缀),不再内联输出审计内容。
110
95
  * code_audit 工具 / git_commit_push 提交后统一调用,避免各处输出漂移。
111
96
  * @param {string} repo 仓库路径
112
97
  * @param {object} [opts] { scope?: 'full'|'diff', summary?, quality? }
@@ -139,8 +124,8 @@ export function buildAuditApiGuide(repo = '', opts = {}) {
139
124
  const scope = (opts.scope || 'full') === 'full' ? 'full' : 'diff';
140
125
  // 参数自动填充:repo 实际路径(encode)、scope 实际值、groupBy 默认 rule、severity 默认全级别
141
126
  const qs = `repo=${encodeURIComponent(repo || '')}&scope=${scope}&groupBy=${opts.groupBy || 'rule'}`;
142
- // 审计侧已分到独立前缀(/api/git-audit):这里的 URL 是给用户/AI 直接复制去 curl 的,必须同步
143
- const base = `http://${detectHostIp()}:30800/api/git-audit/audit`;
127
+ // 预处理侧走通用前缀(/api/preprocess):这里的 URL 是给用户/AI 直接复制去 curl 的,必须同步
128
+ const base = `http://${detectHostIp()}:30800/api/preprocess/audit`;
144
129
  const L = [];
145
130
  L.push(`审计:${repo || ''}(${scope === 'full' ? '全量' : '变动'})`);
146
131
  L.push(`评分 ${quality.score ?? '?'}/${quality.level ?? '?'} · ${s.blocker ?? 0} 拦截 / ${s.warning ?? 0} 警告 / ${s.notice ?? 0} 提示`);
@@ -0,0 +1,136 @@
1
+ /**
2
+ * 预处理实现客户端(宿主侧唯一入口)
3
+ *
4
+ * 拆包后审计实现住在 `audit-sluice`,宿主**不再自己实现**判定,只负责:解析包位置 →
5
+ * 调它的公开面 → 把结果转给 AI/前端。本文件就是那个「调」的位置:
6
+ * · 包位置解析复用 pre-commit-engine 的同一套规则(env → node_modules → 平级目录),
7
+ * 保证「工具调用」与「提交门禁」永远指向**同一个**包(否则两处行为会分叉);
8
+ * · 用**动态 import**(不是子进程):工具调用要返回结构化对象,进程内调用省掉序列化与启动开销,
9
+ * 且包的公开面(`lib/index.js`)本来就是给 library 形态准备的。
10
+ *
11
+ * 为什么集中在一个文件:宿主里有 5 个工具 + 若干 handler 要用审计能力,
12
+ * 各自 `import(...)` 会让「包路径怎么找」散成 N 处(一处改了漏另一处 ⇒ 有的工具悄悄用旧实现)。
13
+ */
14
+
15
+ import { existsSync } from 'node:fs';
16
+ import { dirname, join, resolve } from 'node:path';
17
+ import { pathToFileURL } from 'node:url';
18
+
19
+ import { resolveGateProvider } from '../commit-push/pre-commit-engine.js';
20
+
21
+ /** 已加载的包模块(进程内单例:包是纯函数集合,重复加载只浪费内存)。 */
22
+ let cachedModule = null;
23
+ let cachedHostApi = null;
24
+ let cachedRoot = '';
25
+
26
+ /**
27
+ * 解析预处理实现根目录(CLI 入口所在目录)。
28
+ * @returns {{ok: true, root: string, source: string} | {ok: false, error: string}}
29
+ */
30
+ export function resolvePreprocessProviderRoot() {
31
+ const entry = resolveGateProvider();
32
+ if (!entry.ok) return entry;
33
+ return { ok: true, root: dirname(entry.path), source: entry.source };
34
+ }
35
+
36
+ /**
37
+ * 取预处理实现模块(懒加载 + 缓存)。
38
+ * 失败时抛出**可诊断**的错误:调用方(工具层)会把它转成 `{ ok:false, error }` 给 AI 看。
39
+ * @returns {Promise<object>}
40
+ */
41
+ export async function loadPreprocessProvider() {
42
+ // 热插拔支持:每次先重新解析入口,只有「解析结果与上次一致」才复用缓存。
43
+ // 为什么要这样:包可能被**换版本**(路径变了)、被**拔掉**(路径失效)、
44
+ // 或在另一个位置重新插上;只认 cachedModule 会让宿主一直用旧实现或继续用已删除的包。
45
+ // resolveGateProvider 只是几次 existsSync,成本可忽略。
46
+ const resolvedRoot = resolvePreprocessProviderRoot();
47
+ if (!resolvedRoot.ok) {
48
+ cachedModule = null;
49
+ cachedRoot = '';
50
+ throw new Error(resolvedRoot.error);
51
+ }
52
+ if (cachedModule && cachedRoot === resolvedRoot.root) return cachedModule;
53
+ const entryFile = join(resolvedRoot.root, 'lib', 'index.js');
54
+ if (!existsSync(entryFile)) {
55
+ cachedModule = null;
56
+ cachedRoot = '';
57
+ throw new Error(`预处理实现缺少公开面 ${entryFile}(包根 ${resolvedRoot.root})——检查 audit-sluice 是否完整`);
58
+ }
59
+ const loaded = await import(pathToFileURL(entryFile).href);
60
+ cachedModule = loaded;
61
+ cachedRoot = resolvedRoot.root;
62
+ return cachedModule;
63
+ }
64
+
65
+ /** 当前已加载的包根(未加载时为空串;供状态/排查展示)。 */
66
+ export function preprocessProviderRoot() {
67
+ return cachedRoot;
68
+ }
69
+
70
+ /** 供测试重置缓存(改 DSH_AUDIT_SLUICE_CLI 后要能重新解析)。 */
71
+ export function resetPreprocessProviderCache() {
72
+ cachedModule = null;
73
+ cachedHostApi = null;
74
+ cachedRoot = '';
75
+ }
76
+
77
+ /**
78
+ * 宿主对接面(规则包/聚合/豁免提示/预处理参数与文案)——从预处理实现 `lib/host-api.js` 取。
79
+ * 包的对接面**只提供已完成的中立能力,不含宿主策略**;宿主策略(job、缓存、路由整形)留在这里。
80
+ * @returns {Promise<object>}
81
+ */
82
+ export async function hostApi() {
83
+ if (cachedHostApi) return cachedHostApi;
84
+ const resolvedRoot = resolvePreprocessProviderRoot();
85
+ if (!resolvedRoot.ok) throw new Error(resolvedRoot.error);
86
+ const entryFile = join(resolvedRoot.root, 'lib', 'capabilities.js');
87
+ if (!existsSync(entryFile)) throw new Error(`预处理实现缺少能力出口 ${entryFile}`);
88
+ cachedHostApi = await import(pathToFileURL(entryFile).href);
89
+ return cachedHostApi;
90
+ }
91
+
92
+ /**
93
+ * 跑审计报告(`code_audit` 工具的实体)。
94
+ * @param {object} options 见 audit-sluice `auditReport`
95
+ * @returns {Promise<object>}
96
+ */
97
+ export async function auditReport(options = {}) {
98
+ const pkg = await loadPreprocessProvider();
99
+ return pkg.auditReport({ ...options, repo: resolve(String(options.repo || '.')) });
100
+ }
101
+
102
+ /** 历史审计(按 commit 区间逐版本审计 + 报告)。 */
103
+ export async function auditHistory(options = {}) {
104
+ const pkg = await loadPreprocessProvider();
105
+ return pkg.auditHistory({ ...options, repo: resolve(String(options.repo || '.')) });
106
+ }
107
+
108
+ /** IO 风险扫描。 */
109
+ export async function ioScan(options = {}) {
110
+ const pkg = await loadPreprocessProvider();
111
+ return pkg.ioScan({ ...options, ...(options.root ? { root: resolve(String(options.root)) } : {}) });
112
+ }
113
+
114
+ /** 链接检查。 */
115
+ export async function linkCheck(options = {}) {
116
+ const pkg = await loadPreprocessProvider();
117
+ return pkg.linkCheck({ ...options, ...(options.path ? { path: resolve(String(options.path)) } : {}) });
118
+ }
119
+
120
+ /** 拼接产物作用域撞名检查。 */
121
+ export async function scopeCheck(options = {}) {
122
+ const pkg = await loadPreprocessProvider();
123
+ return pkg.scopeCheck({ ...options });
124
+ }
125
+
126
+ /** 注释豁免标注(add/remove/list/check)。 */
127
+ export async function exemptAction(options = {}) {
128
+ const pkg = await loadPreprocessProvider();
129
+ return pkg.exemptAction({ ...options });
130
+ }
131
+
132
+ /** 聚合查询维度清单(宿主 HTTP/工具提示共用;从包取,不在宿主里再写一份)。 */
133
+ export async function groupByKeys() {
134
+ const pkg = await loadPreprocessProvider();
135
+ return pkg.GROUP_BY_KEYS;
136
+ }
@@ -17,7 +17,7 @@
17
17
  */
18
18
  import { listRemotes, parseGithubUrl } from '../git/remote-resolve.js';
19
19
  import { readAccountStatus } from '../git/account-status.js';
20
- import { classifyOwnership } from '../audit/ownership.js';
20
+ import { classifyOwnership } from './ownership.js';
21
21
 
22
22
  /** 同一仓库只探一次(remote 与账号快照都是磁盘读,逐文件审计时重复开销明显)。 */
23
23
  const CACHE = new Map();