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
@@ -1,173 +0,0 @@
1
- /**
2
- * 审计结果 API 聚合层
3
- *
4
- * 为 `/api/git-push/audit` 端点提供「请求时自定义聚合」:
5
- * · 维度:rule(警告类型)/ file(文件名)/ severity / slot(规则包)
6
- * · 过滤:severity 白名单(逗号分隔)
7
- * · 条数:top 截断(每组最多列前 N 条,0=全部)
8
- * · 明细:withFindings=true 时附完整 findings
9
- *
10
- * 纯函数设计:findings 进、聚合出,不碰 I/O,便于单测。
11
- * 与 auditFull/auditWithScope 解耦——本层只消费它们的返回。
12
- */
13
- import { buildRuleSlotMap } from '../audit/slot.js';
14
- import { isBlockerFinding } from '../audit/index.js';
15
- import { MAX_MSG_PREVIEW } from './constants.js';
16
- import { probeRepoOwnership } from './repo-ownership.js';
17
-
18
- /** 支持的聚合维度(非法值回落 rule)。 */
19
- export const GROUP_BY_KEYS = ['rule', 'file', 'severity', 'slot'];
20
- // 豁免类型前缀(exemptHint 形态 dsh-skip-<type>(范围)——统计按类型分组)
21
- const EXEMPT_TYPE_RE = /dsh-skip-([a-z-]+)/; // 无 /g:exec 有 lastIndex 状态(多次调用错位)
22
-
23
- /**
24
- * 豁免类型统计(每次审计后输出「本次被豁免的类型与数量」——
25
- * 审计透明性:dsh-skip-quality/residue/sensitive/size 各豁免多少条)。
26
- * @param {Array} findings audit findings(含 exemptHint)
27
- * @returns {{ types: Record<string, number>, total: number }}
28
- */
29
- export function exemptStatsOf(findings = []) {
30
- const types = {};
31
- let total = 0;
32
- // 「已确认豁免」(.auditignore 的「路径 : 规则」):与上面的「可选豁免标记」分开统计——
33
- // 前者是**已经生效**的豁免(不扣分),后者只是「可以写哪个标记」,混在一起会让人误判。
34
- const applied = {};
35
- let appliedTotal = 0;
36
- for (const f of findings) {
37
- if (f?.exempted) {
38
- appliedTotal += 1;
39
- const key = String(f.rule || '(未知规则)');
40
- applied[key] = (applied[key] || 0) + 1;
41
- continue;
42
- }
43
- const hint = String(f?.exemptHint || '');
44
- if (!hint) continue;
45
- total += 1;
46
- const matched = EXEMPT_TYPE_RE.exec(hint);
47
- if (matched) {
48
- const t = matched[1];
49
- types[t] = (types[t] || 0) + 1;
50
- } else {
51
- types.other = (types.other || 0) + 1;
52
- }
53
- }
54
- return { types, total, applied, appliedTotal };
55
- }
56
-
57
- /** finding 对象聚合键提取(slot 维度用 ruleSlotMap 把 rule id 归到规则包)。 */
58
- function groupKeyOf(finding, groupBy, ruleSlotMap) {
59
- if (groupBy === 'file') return String(finding.file || '(未知文件)');
60
- if (groupBy === 'severity') return String(finding.severity || 'notice');
61
- if (groupBy === 'slot') return ruleSlotMap.get(finding.rule) || '未归类';
62
- return String(finding.rule || '(未知规则)');
63
- }
64
-
65
- /**
66
- * 解析 severity 过滤参数:「warning,blocker」→ ['warning','blocker'];
67
- * 空/非法 → null(不过滤)。
68
- */
69
- export function parseSeverityFilter(raw) {
70
- if (!raw) return null;
71
- const list = String(raw).split(',').map((s) => s.trim().toLowerCase()).filter(Boolean);
72
- return list.length ? [...new Set(list)] : null;
73
- }
74
-
75
- /**
76
- * 按指定维度聚合 findings。
77
- * @param {Array} findings audit findings(含 rule/severity/file)
78
- * @param {object} opts { groupBy='rule', severityFilter=null, top=0, ruleSlotMap=Map }
79
- * @returns {{groups: Array<{key, count, sample?: object}>, total: number, filtered: number}}
80
- * groups 按 count 降序;severity 过滤后 filtered=通过过滤的条数。
81
- */
82
- export function aggregateFindings(findings = [], opts = {}) {
83
- const groupBy = GROUP_BY_KEYS.includes(opts.groupBy) ? opts.groupBy : 'rule';
84
- const top = Number(opts.top) > 0 ? Math.floor(Number(opts.top)) : 0;
85
- const severityFilter = parseSeverityFilter(opts.severityFilter);
86
- const ruleSlotMap = opts.ruleSlotMap instanceof Map ? opts.ruleSlotMap : new Map();
87
-
88
- const buckets = new Map();
89
- let filtered = 0;
90
- for (const f of findings) {
91
- if (severityFilter && !severityFilter.includes(String(f.severity || 'notice').toLowerCase())) continue;
92
- filtered++;
93
- const key = groupKeyOf(f, groupBy, ruleSlotMap);
94
- if (!buckets.has(key)) buckets.set(key, { key, count: 0, sample: null });
95
- const b = buckets.get(key);
96
- b.count++;
97
- if (!b.sample) b.sample = { rule: f.rule, severity: f.severity, file: f.file, line: f.line, message: f.message };
98
- }
99
-
100
- let groups = [...buckets.values()].sort((a, b2) => b2.count - a.count || String(a.key).localeCompare(String(b2.key)));
101
- if (top > 0) groups = groups.slice(0, top);
102
- return { groups, total: findings.length, filtered };
103
- }
104
-
105
- /**
106
- * 执行审计并聚合(HTTP 端点用)。
107
- * @param {string} repo 仓库根
108
- * @param {object} params { scope='full', groupBy='rule', severity='', top=0, withFindings=false, rulesetDir='', maxScanFiles=0, slots, disabledSlots, includeIgnored=false, weights={} }
109
- * @param {object} cfg 插件配置(auditRuleOrder / auditDisabledSlots)
110
- */
111
- export async function runAuditApi(repo, params = {}, cfg = {}) {
112
- const { auditFull, auditWithScope } = await import('../audit/index.js');
113
- const { scoreQuality } = await import('../score/index.js');
114
- const scope = params.scope === 'diff' ? 'diff' : 'full';
115
- const auditOpts = {
116
- ownership: probeRepoOwnership(repo), // 隐私规则只对自有仓库生效(审计层只消费该字符串)
117
- scope,
118
- rulesetDir: params.rulesetDir || '',
119
- maxScanFiles: params.maxScanFiles ?? cfg.maxScanFiles ?? 0,
120
- slots: undefined, // auditRuleOrder 是「加载顺序」不是白名单 ✗(详见 lib/commit-push.js 注释;禁用槽位用 auditDisabledSlots ✓)
121
- disabledSlots: Array.isArray(cfg.auditDisabledSlots) ? cfg.auditDisabledSlots : [],
122
- includeIgnored: params.includeIgnored === true,
123
- };
124
- const auditResult = scope === 'diff'
125
- ? await auditWithScope(repo, auditOpts)
126
- : await auditFull(repo, auditOpts);
127
-
128
- const { summarize } = await import('../audit/index.js');
129
- const summary = summarize(auditResult.findings);
130
- const quality = scoreQuality(auditResult.findings, params.weights || {}, { files: auditResult.files, dimFileCounts: auditResult.dimFileCounts, dimRuleCounts: auditResult.dimRuleCounts });
131
- // slot 归属映射(groupBy=slot 用):与 auditFiles 同源加载规则构建映射——
132
- // 审计返回不带 compiled,这里按相同 slots/disabledSlots 重新编译一次。
133
- let ruleSlotMap = new Map();
134
- if (params.groupBy === 'slot') {
135
- try {
136
- const { loadRuleFiles } = await import('../rule/loader.js');
137
- const { compileAllRules } = await import('../rule/registry.js');
138
- const loaded = loadRuleFiles(auditOpts.slots, { dir: auditOpts.rulesetDir, disabledSlots: auditOpts.disabledSlots });
139
- ruleSlotMap = buildRuleSlotMap(compileAllRules(loaded.merged.rules, { errors: [] }));
140
- } catch { /* slot 映射构建失败退化为空 Map(该维度归「未归类」) */ }
141
- }
142
-
143
- const agg = aggregateFindings(auditResult.findings, {
144
- groupBy: params.groupBy,
145
- severityFilter: params.severity,
146
- top: params.top,
147
- ruleSlotMap,
148
- });
149
-
150
- const out = {
151
- ok: true,
152
- repo,
153
- scope: auditResult.scope || scope,
154
- files: auditResult.files,
155
- summary,
156
- quality: quality.emptyResult ? null : { score: quality.score, level: quality.level },
157
- groups: agg.groups,
158
- total: agg.total,
159
- filtered: agg.filtered,
160
- // 豁免类型统计(本次被豁免的类型与数量)+ 可用聚合类型(groupBy 维度)+
161
- // 拦截列表(blocker findings 直接输出——被拦文件/规则,不用再查明细)
162
- exemptStats: exemptStatsOf(auditResult.findings),
163
- groupByTypes: GROUP_BY_KEYS,
164
- blocked: auditResult.findings
165
- // 统一口径:error 也属拦截级(与 summarize 一致)——此前只筛 'blocker',
166
- // 导致「summary.blocker(10) vs 枚举(7)」差额(差的正是 3 条 error 级)✗
167
- .filter(isBlockerFinding)
168
- .map((f) => ({ file: f.file, line: f.line, rule: f.rule, message: String(f.message || '').slice(0, MAX_MSG_PREVIEW) })),
169
- };
170
- if (params.withFindings === true) out.findings = auditResult.findings;
171
- if (params.withYaml === true) out.yaml = auditResult.yaml;
172
- return out;
173
- }
@@ -1,150 +0,0 @@
1
- /**
2
- * HTTP 处理器 · 审计侧(规则包 / 审计结果聚合 / 规则启停 / 豁免提示)
3
- *
4
- * 为什么单独成文件:审计侧 HTTP 面要与 git 侧**物理分家**(对应 `/api/git-audit/*` 前缀)——
5
- * 否则「审计将来能整体抠走」只是路由上的说法,代码层仍混在 meta.js 里。
6
- * 本文件只放审计专属 handler 与它们的辅助函数(ruleSlotStats / listRuleSlots)。
7
- *
8
- * 路由映射(见 lib/app/http-handlers.js):
9
- * /api/git-audit/{rule-slots,rule-detail,audit,toggle-rule,exempt-hint}
10
- * 旧 /api/git-push/{同 5 条} 保留一版转发(响应带 Deprecation 头)。
11
- */
12
- import { discoverRuleSlots, loadYamlRuleFile, resolveSlotOrder, setSlotDisabled, RULE_YAML_DIR } from '../../rule/loader.js';
13
- import { getLastSlotHitStats } from '../slot-stats.js';
14
- import { getDefaultScanRoot } from '../scan-root.js';
15
- import { exemptHintForFinding, exemptMarkerCovers, EXEMPT_MARKERS } from '../../exempt/index.js';
16
-
17
- /**
18
- * 由规则包 yml 解析结果算该槽位的规则条数统计。
19
- *
20
- * 为什么单独成函数:这段(rules 过滤 + private_files 计数 + pass 推导)原先内联在
21
- * listRuleSlots 的循环里,与「槽位元数据组装」混在一起,把该函数圈复杂度推到 15
22
- * (阈值 10,自审 max-cyclomatic-complexity)——拆开后统计口径可单独阅读与复用。
23
- * 清单驱动槽位(private)用 private_files 条目数计(它们不在 rules 数组里)。
24
- */
25
- function ruleSlotStats(r) {
26
- const rules = Array.isArray(r.data.rules) ? r.data.rules : [];
27
- const listed = Array.isArray(r.data.private_files) ? r.data.private_files.length : 0;
28
- const total = rules.length + listed;
29
- const blocker = rules.filter((x) => x && (x.severity === 'blocker' || x.severity === 'error')).length + listed;
30
- const warning = rules.filter((x) => x && x.severity === 'warning').length;
31
- return { blocker, warning, pass: Math.max(0, total - blocker - warning), total, source: 'rules' };
32
- }
33
-
34
- /** 规则包清单(按规则条数统计;hitStats 参数保留兼容但不再参与计算)。 */
35
- export function listRuleSlots(order, disabledSlots = [], hitStats = null) {
36
- const discovered = discoverRuleSlots(RULE_YAML_DIR);
37
- const slotMeta = {};
38
- for (const slot of discovered) {
39
- const r = loadYamlRuleFile(slot, RULE_YAML_DIR);
40
- if (r.ok && r.data?.metadata) {
41
- slotMeta[slot] = {
42
- name: r.data.metadata.name || slot,
43
- description: r.data.metadata.description || '',
44
- author: r.data.metadata.author || '',
45
- stats: ruleSlotStats(r),
46
- disabled: r.data.disabled === true || disabledSlots.includes(slot),
47
- };
48
- } else {
49
- slotMeta[slot] = { name: slot, description: '', author: '', stats: { blocker: 0, warning: 0, pass: 0, total: 0, source: 'rules' }, disabled: disabledSlots.includes(slot) };
50
- }
51
- }
52
- const eff = resolveSlotOrder(order && order.length ? order : undefined, { dir: RULE_YAML_DIR });
53
- return { discovered, order: eff, meta: slotMeta, forced: ['private'] };
54
- }
55
-
56
- /** GET /api/git-push/rule-slots —— 规则包按包规则条数统计。 */
57
- export function handleRuleSlots(ctx) {
58
- const { cfg } = ctx;
59
- return { status: 200, body: { ok: true, slots: listRuleSlots(cfg.auditRuleOrder, Array.isArray(cfg.auditDisabledSlots) ? cfg.auditDisabledSlots : [], getLastSlotHitStats()) } };
60
- }
61
-
62
- /** GET /api/git-push/rule-detail —— 单个规则包的规则明细 + severity 统计。 */
63
- export function handleRuleDetail(ctx) {
64
- const { query } = ctx;
65
- const slot = String(query.slot || '');
66
- if (!slot) return { status: 400, body: { ok: false, code: 'SLOT_REQUIRED', error: '缺少规则包名 slot' } };
67
- const r = loadYamlRuleFile(slot, RULE_YAML_DIR);
68
- if (!r.ok) return { status: 404, body: { ok: false, code: 'SLOT_NOT_FOUND', error: r.error } };
69
- const rules = Array.isArray(r.data?.rules) ? r.data.rules : [];
70
- const detail = rules.map((rule) => ({
71
- id: rule.id || '',
72
- name: rule.name || rule.id || '',
73
- category: rule.category || '',
74
- severity: rule.severity || 'notice',
75
- description: rule.description || '',
76
- author: rule.author || r.data.metadata?.author || '',
77
- }));
78
- const count = (sev) => detail.filter((x) => x.severity === sev).length;
79
- const stats = {
80
- blocker: count('blocker') + count('error'),
81
- warning: count('warning'),
82
- pass: rules.length - count('blocker') - count('error') - count('warning'),
83
- total: rules.length,
84
- };
85
- return { status: 200, body: { ok: true, slot, meta: { name: r.data?.metadata?.name || slot, description: r.data?.metadata?.description || '', author: r.data?.metadata?.author || '' }, stats, rules: detail } };
86
- }
87
-
88
- /** POST/GET /api/git-push/audit —— 审计结果 API(请求时聚合)。 */
89
- export async function handleAudit(ctx) {
90
- const { query, body, env, cfg } = ctx;
91
- const { runAuditApi } = await import('../audit-api.js');
92
- const params = { ...query, ...body };
93
- const repo = String(params.repo || '').trim()
94
- || getDefaultScanRoot(env, { defaultScanRoot: String(cfg.defaultScanRoot || '') });
95
- if (!repo) return { status: 400, body: { ok: false, code: 'REPO_REQUIRED', error: '缺 repo 参数且无法推断默认扫描根' } };
96
- try {
97
- const r = await runAuditApi(repo, params, cfg);
98
- return { status: 200, body: r };
99
- } catch (e) {
100
- return { status: 500, body: { ok: false, code: 'AUDIT_FAIL', error: `审计失败: ${e?.message || e}` } };
101
- }
102
- }
103
-
104
- /** POST /api/git-push/toggle-rule —— 启用/禁用规则包(改 yml disabled)。 */
105
- export function handleToggleRule(ctx) {
106
- const { body } = ctx;
107
- const slot = String(body.slot || '');
108
- const want = body.disabled === true;
109
- if (!slot) return { status: 400, body: { ok: false, code: 'SLOT_REQUIRED', error: '缺少规则包名 slot' } };
110
- const r = setSlotDisabled(slot, want);
111
- if (!r.ok) return { status: 400, body: { ok: false, code: 'SLOT_TOGGLE_FAIL', error: r.error || '切换失败' } };
112
- return { status: 200, body: { ok: true, slot, disabled: r.disabled, message: want ? '已禁用' : '已启用' } };
113
- }
114
-
115
- /**
116
- * GET /api/git-push/exempt-hint —— 豁免标记查询(只读)。
117
- *
118
- * 入参 query:rule(规则名,如 maintainability/max-complexity)、kind(可选 finding kind)。
119
- * 出参:{ ok, rule, kind, marker, hint, lineLevel, candidates }。
120
- *
121
- * 为什么要有这个端点:豁免标记注册表(EXEMPT_MARKERS)是**单一真源**,外部工具(如
122
- * dsh-useful-tools 的 exempt 工具)需要「该写哪个标记」时来查,而不是复制一份注册表
123
- * ——复制必然漂移(历史上「提示与实际行为不符」的 24 种组合就是这么来的)。
124
- */
125
- export function handleExemptHint(ctx) {
126
- const rule = String(ctx.query?.rule || '').trim();
127
- const kind = String(ctx.query?.kind || '').trim();
128
- const finding = { rule, kind };
129
- const hit = exemptHintForFinding(finding);
130
- const meta = hit ? EXEMPT_MARKERS[hit.marker] : null;
131
- const candidates = Object.entries(EXEMPT_MARKERS).map(([marker, m]) => ({
132
- marker,
133
- lineLevel: m.lineLevel === true,
134
- dimensions: m.dimensions || [],
135
- hint: m.hint || '',
136
- covers: Boolean(rule || kind) && exemptMarkerCovers(marker, finding),
137
- }));
138
- return {
139
- status: 200,
140
- body: {
141
- ok: true,
142
- rule,
143
- kind,
144
- marker: hit ? hit.marker : null,
145
- hint: hit ? hit.hint : '无任何标记可豁免该 finding(应改代码,或走 .auditignore / 豁免槽位)',
146
- lineLevel: meta ? meta.lineLevel === true : false,
147
- candidates,
148
- },
149
- };
150
- }
@@ -1,25 +0,0 @@
1
- /**
2
- * 宿主文档漂移检查器的接线模块(审计包边界,2026-10-13)。
3
- *
4
- * 边界规则:`lib/audit/**` 与 `lib/core/**` 不得 import 仓库脚本(`scripts/**`)——
5
- * 「目录树漂移 / 函数列表漂移」这两个检查器属于**宿主侧**能力,由宿主在加载时注入给审计(见
6
- * lib/audit/orchestrate.js 的 setHostDocChecks)。
7
- *
8
- * 用法:宿主入口加一行 `import '<相对路径>/host-doc-checks.js';` 即完成接线(本模块导入即安装,幂等)。
9
- * 当前三处宿主入口:lib/app/tool-call.js(插件工具调用)、lib/commit-push.js(提交门禁)、cli.mjs(独立 CLI)。
10
- * 未接线的环境(例如别人只依赖审计子路径):审计自动跳过这两类漂移 finding,其余检查不受影响。
11
- */
12
- import { checkDrift, findMarkedHostMd } from '../../scripts/doc-tree.mjs';
13
- import { checkFuncDrift } from '../../scripts/doc-func.mjs';
14
- import { setHostDocChecks } from '../audit/orchestrate.js';
15
-
16
- /** 本宿主提供的检查器集合(供测试直接比对)。 */
17
- export const HOST_DOC_CHECKS = { checkDrift, findMarkedHostMd, checkFuncDrift };
18
-
19
- /** 显式接线(默认已由模块导入自动执行;单独调用用于测试或自定义注入)。 */
20
- export function installHostDocChecks(checks = HOST_DOC_CHECKS) {
21
- setHostDocChecks(checks);
22
- return true;
23
- }
24
-
25
- installHostDocChecks();
@@ -1,42 +0,0 @@
1
- /**
2
- * 插件入口层 · 配置 schema(审计侧)
3
- *
4
- * 为什么单独成文件(2026-11-08 UI 与审计解耦 · 文件隔离阶段):
5
- * 审计与 git 侧计划重构成两个独立项目,本阶段先把**文件边界**划清——
6
- * 审计相关设置键集中在本文件,git / 发布侧的键留在 `schema.js`。
7
- * 行为完全不变:`schema.js` 用 `...auditConfigShape(Schema)` 展开合并,
8
- * 产出的仍是同一个 Config 对象(同一批键、同一批默认值)。
9
- *
10
- * 边界判据:键的语义属于「静态检查 / 规则 / 评分 / 措辞」即归审计侧;
11
- * 属于「扫描仓库 / 克隆 / 推送 / 凭据 / 注入」留在 schema.js。
12
- * `injectRequirements` 归审计侧:它是「提交前审计」的子开关(注入开发者要求清单)。
13
- */
14
-
15
- /** 全量审计文件数上限默认值(0=不限)。 */
16
- const DEFAULT_MAX_SCAN_FILES = 3000;
17
-
18
- /**
19
- * 审计侧配置键形状。
20
- * @param {object} Schema schemastery(或 makeFallbackSchema 兜底实现)
21
- * @returns {object} 键名 → schema 字段
22
- */
23
- export function auditConfigShape(Schema) {
24
- return {
25
- auditEnabled: Schema.boolean().default(false).description('提交前审计(默认关)'),
26
- // 提交前审计的子开关:开启后在系统提示词注入「开发者特殊要求」清单全文,AI 常驻可见、
27
- // 不必等门禁拦截才去读清单(省一次失败的工具往返)。auditEnabled 关闭时本项不生效。
28
- maxScanFiles: Schema.number().default(DEFAULT_MAX_SCAN_FILES).description('全量审计文件数上限(0=不限);超限按变动文件优先截断,防止弱机扫大仓卡死'),
29
- injectRequirements: Schema.boolean().default(false).description('注入开发者要求清单到系统提示词(可直接勾选;父开关「提交前审计」关闭时置灰且不注入,勾选保留;默认关)'),
30
- auditScanScope: Schema.string().default('diff').description('diff | full'),
31
- auditRuleOrder: Schema.array(Schema.string()).default([]).description('规则槽位加载顺序(后加载覆盖先加载;空=默认偏好顺序;private 恒末尾强制)'),
32
- auditDisabledSlots: Schema.array(Schema.string()).default([]).description('UI 禁用的规则槽位(设置页单击切换;nodejs/private 安全红线不可禁用)'),
33
- weightOverrides: Schema.string().default('').description('权重覆盖 JSON(如 {"安全性":100},空=默认权重表)'),
34
- linkCheckEnabled: Schema.boolean().default(false).description('链接检查(默认关,需网络)'),
35
- commentWordingEnabled: Schema.boolean().default(true).description('提交信息措辞检查'),
36
- commentWordingCustom: Schema.string().default('').description('自定义措辞规则'),
37
- commentWordingRulesFile: Schema.string().default('').description('措辞规则文件路径'),
38
- commentWordingRulesUrl: Schema.string().default('').description('措辞规则 URL'),
39
- auditRuleWeights: Schema.dict(Schema.any()).default({}).description('规则权重({ blacklist: { pattern: weight } })'),
40
- qualityWeights: Schema.dict(Schema.number()).default({}).description('质量维度权重覆盖({ 维度名: weight })'),
41
- };
42
- }
@@ -1,69 +0,0 @@
1
- /**
2
- * 「拼接产物作用域检查」的**共享执行器**(工具 / 独立脚本 / 审计规则共用一份判定)。
3
- *
4
- * 为什么要有这一层:同一件事有三个入口(`scope_check` 工具、`scripts/check-js-scope.mjs`、
5
- * 审计规则 kind=scope-collision),执行流程一旦各写一份就会漂移。这里只做
6
- * 「找契约 → 逐文件分析 → 汇总」,真正的判定在 `lib/ast/scope-collisions.js`,
7
- * 「按文件所属项目取契约」在 `lib/audit/scope-policy.js`(中立模块,审计侧也用它)。
8
- *
9
- * 契约适用口径(与审计侧**故意不同**,各有各的输入面):
10
- * · 本执行器:目标文件是调用方**显式点名**的 ⇒ 视为产物;项目给了 `files` 清单
11
- * 且不含该文件时仍不套契约(典型场景:分片源码不是产物,套前缀会把局部变量
12
- * 全判成缺前缀)。
13
- * · 审计侧(lib/checks/scope-collision.js):那是**全仓扫描**,必须严格按
14
- * `files` 清单命中,否则每个 js 文件都会被套上前缀契约。
15
- */
16
- import { existsSync, readFileSync } from 'node:fs';
17
- import { resolve } from 'node:path';
18
-
19
- import { analyzeScopeCollisions } from '../ast/scope-collisions.js';
20
- import { POLICY_SOURCE, readProjectScopePolicy } from '../audit/scope-policy.js';
21
-
22
- export { POLICY_SOURCE };
23
-
24
- /**
25
- * 找出某个文件所属项目的契约配置(兼容旧名,实现在中立模块)。
26
- * @param {string} file 目标文件绝对路径
27
- */
28
- export function policyForFile(file) {
29
- return readProjectScopePolicy(file);
30
- }
31
-
32
- /**
33
- * 逐文件跑检查。
34
- * @param {{files:string[], prefix?:string, allowlist?:string[], topLevelMustBeEmpty?:boolean}} o
35
- * prefix/allowlist/topLevelMustBeEmpty 显式给出时覆盖项目配置(顶层零声明需显式 true/false)。
36
- * @returns {{ok:boolean, reports:Array<object>, policySources:string[]}}
37
- */
38
- export function runScopeCheck({ files = [], prefix = '', allowlist = [], topLevelMustBeEmpty } = {}) {
39
- const reports = [];
40
- const policySources = new Set();
41
- for (const raw of files) {
42
- const file = resolve(raw);
43
- const own = readProjectScopePolicy(file);
44
- // 项目没给 files 清单时,点名文件即产物;给了清单就只认清单内的文件
45
- const contractApplies = own.declared && (own.files.length === 0 || own.isDeclaredArtifact);
46
- const explicit = [];
47
- if (prefix) explicit.push('prefix');
48
- if (Array.isArray(allowlist) && allowlist.length) explicit.push('allowlist');
49
- if (typeof topLevelMustBeEmpty === 'boolean') explicit.push('topLevel');
50
- const policy = {
51
- prefix: prefix || (contractApplies ? own.prefix : ''),
52
- allowlist: Array.isArray(allowlist) && allowlist.length ? allowlist : (contractApplies ? own.allowlist : []),
53
- topLevelMustBeEmpty: typeof topLevelMustBeEmpty === 'boolean'
54
- ? topLevelMustBeEmpty
55
- : (contractApplies && own.topLevelMustBeEmpty),
56
- };
57
- const source = explicit.length
58
- ? `${POLICY_SOURCE.CLI}(${explicit.join('/')})`
59
- : `${own.source}${own.configPath ? `:${own.configPath}` : ''}`;
60
- policySources.add(source);
61
- if (!existsSync(file)) {
62
- reports.push({ file, ok: false, missing: true, violations: [`文件不存在:${file}`], declarations: [], duplicates: [] });
63
- continue;
64
- }
65
- const result = analyzeScopeCollisions(readFileSync(file, 'utf8'), policy);
66
- reports.push({ file, ...result, policy });
67
- }
68
- return { ok: reports.every((r) => r.ok), reports, policySources: [...policySources] };
69
- }
package/lib/ast/brace.js DELETED
@@ -1,120 +0,0 @@
1
- /**
2
- * AST 实现层 · 括号与区间工具
3
- *
4
- * 职责:括号配对、区间包含判定。供复杂度/嵌套/函数行数检查复用,
5
- * 让「某个 token 属于哪个函数体」这类判断只在一处实现。
6
- */
7
-
8
- // 从 function 关键字向后找函数体 '{' 的最大 token 跨度:与 control-flow.js 共用同一来源
9
- // (lib/ast/consts.js)——两处必须永远相等(自审 duplicate-constant 报的真重复)
10
- import { FN_BODY_LOOKAHEAD } from './consts.js';
11
-
12
- /** 括号平衡扫描:从 startIdx 的 '{' 找匹配 '}',返回 [openIdx, closeIdx] 或 null。 */
13
- export function matchBrace(tokens, openIdx) {
14
- let depth = 0;
15
- for (let i = openIdx; i < tokens.length; i++) {
16
- const t = tokens[i];
17
- if (t.type !== 'punct') continue;
18
- if (t.value === '{') depth++;
19
- else if (t.value === '}') {
20
- depth--;
21
- if (depth === 0) return [openIdx, i];
22
- }
23
- }
24
- return null;
25
- }
26
-
27
- /** 前向圆括号配对:从 startIdx 的 '(' 找匹配 ')',返回其下标;不匹配返回 -1。 */
28
- export function matchParenForward(tokens, startIdx) {
29
- let depth = 0;
30
- for (let i = startIdx; i < tokens.length; i++) {
31
- const t = tokens[i];
32
- if (t.type !== 'punct') continue;
33
- if (t.value === '(') depth++;
34
- else if (t.value === ')') {
35
- depth--;
36
- if (depth === 0) return i;
37
- }
38
- }
39
- return -1;
40
- }
41
-
42
- /**
43
- * 从 closeIdx 处 closePunct 向右→左配对,返回 openPunct 下标;不匹配返回 -1。
44
- * 抽公共:原 matchingOpen({})/ matchingBracketBack([])/ matchingParenBack(())
45
- * + isBlockParen 的配对循环是同一逻辑四处复制,统一为本函数(dup-code 规则命中案例)。
46
- * @param {Array} tokens token 流
47
- * @param {number} closeIdx 右括号下标
48
- * @param {string} openPunct 左括号字符('{' / '[' / '(')
49
- * @param {string} closePunct 右括号字符('}' / ']' / ')')
50
- * @returns {number} 配对左括号下标;无配对返回 -1
51
- */
52
- export function matchPairBack(tokens, closeIdx, openPunct, closePunct) {
53
- let level = 0;
54
- for (let j = closeIdx; j >= 0; j--) {
55
- const tj = tokens[j];
56
- if (tj.type !== 'punct') continue;
57
- if (tj.value === closePunct) level++;
58
- else if (tj.value === openPunct) { level--; if (level === 0) return j; }
59
- }
60
- return -1;
61
- }
62
-
63
- /**
64
- * 判断 `)` 是否属于控制流/函数签名的参数表尾(即其后 `{` 是块语句)。
65
- * 从 `)` 向前做括号配对找起始 `(`,再看 `(` 前一个 token:
66
- * if/for/while/switch/catch/function/标识符(函数声明/表达式/方法名) → 是块语句头。
67
- * @param {Array} tokens token 流
68
- * @param {object} closeTok `)` token
69
- * @returns {boolean}
70
- */
71
- export function isBlockParen(tokens, closeTok) {
72
- const closeIdx = tokens.indexOf(closeTok);
73
- const openIdx = matchPairBack(tokens, closeIdx, '(', ')');
74
- if (openIdx === -1) return false;
75
- for (let j = openIdx - 1; j >= 0; j--) {
76
- const tj = tokens[j];
77
- if (tj.type === 'ws' || tj.type === 'comment') continue;
78
- if (tj.type === 'ident') return true; // if (…) / myFunc (…) / function f (…)
79
- // `)` `]` `.` 等 → 调用表达式(如 foo.bar(…)),其后 `{` 多半是对象实参 → 不计
80
- return false;
81
- }
82
- return false;
83
- }
84
-
85
- /** 找与 closeIdx 处 `}` 配对的 `{` 下标(无配对返回 -1)。 */
86
- export function matchingOpen(tokens, closeIdx) {
87
- return matchPairBack(tokens, closeIdx, '{', '}');
88
- }
89
-
90
- /**
91
- * 检查圈复杂度(max-complexity kind,AST 级)。
92
- * 复杂度 = 1 + 分支关键字数(if/for/while/case/catch/&&/||/?/??)。
93
- * @param {string} text 文件全文
94
- * @param {object} [opts] { warn=10, block=20 }
95
- * @returns {Array<{line:number, name:string, complexity:number, level:string}>}
96
- */
97
- /**
98
- * 收集 [from, to) 区间内所有「嵌套 function 体」的 token 区间。
99
- * 供圈复杂度计算排除内层贡献(内层由外层循环单独评估)。
100
- *
101
- * @param {Array} tokens token 流
102
- * @param {number} from 起始下标(含)
103
- * @param {number} to 结束下标(不含)
104
- * @returns {Array<[number, number]>} 各内层函数体的 [openBraceIdx, closeBraceIdx]
105
- */
106
- export function collectInnerFnRanges(tokens, from, to) {
107
- const ranges = [];
108
- for (let i = from; i < to; i++) {
109
- const t = tokens[i];
110
- if (!(t.type === 'ident' && t.value === 'function')) continue;
111
- let openIdx = -1;
112
- for (let j = i + 1; j < Math.min(to, i + FN_BODY_LOOKAHEAD); j++) {
113
- if (tokens[j].type === 'punct' && tokens[j].value === '{') { openIdx = j; break; }
114
- }
115
- if (openIdx === -1) continue;
116
- const r = matchBrace(tokens, openIdx);
117
- if (r) ranges.push(r);
118
- }
119
- return ranges;
120
- }