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,113 +0,0 @@
1
- /**
2
- * dsh-git-push gitignore 语法匹配器(非 git 目录兜底,)
3
- *
4
- * 为什么需要:`.auditignore` 原先只走 `git check-ignore`,因此**仅在 git 仓库内生效**——
5
- * 非 git 目录(解压的源码包、临时导出目录、未 init 的工程)下 `.auditignore` 被完全忽略,
6
- * 实测同一个 `*.sh` 规则在 `git init` 前后行为相反。本模块提供纯 JS 兜底,
7
- * 使 `.auditignore` 在无 git 时同样生效。
8
- *
9
- * 语义对齐 git(用真 git 建立基准后逐条对齐,见 test/test-gitignore-match.mjs):
10
- * - `*.sh` 匹配**任意层级**(不是只根目录)——gitignore 的 `*` 不跨 `/`,
11
- * 但无 `/` 的模式整体可匹配任意深度,故 `*.sh` = 任意层级的 .sh
12
- * - `/ + *.sh` 仅根目录(前导 `/` 锚定)
13
- * - `sub/*.sh` 含 `/` 的模式从仓库根锚定,`*` 不跨 `/`
14
- * - `** + / + *.sh` 任意层级(显式递归)
15
- * - `gen/` 目录规则:匹配该目录**及其下全部内容**
16
- * - `!xxx` 取反(白名单恢复),**后出现的规则覆盖先出现的**
17
- *
18
- * 与 git 的已知差异(有意为之,够用即可):
19
- * - 不处理嵌套 `.gitignore`(只处理传入的单份规则文本)
20
- * - `**` 的极端位置组合不保证与 git 逐字节一致
21
- * 这些差异只影响「非 git 兜底」路径;git 仓库仍走 `git check-ignore`,语义 100% 一致。
22
- */
23
- import { globToRegex } from './glob.js';
24
-
25
- /**
26
- * 解析 gitignore 文本为规则数组。
27
- *
28
- * 逐行处理:去尾随空白、跳过空行与 `#` 注释、识别 `!` 取反与前导 `/` 锚定、
29
- * 识别尾随 `/` 的目录规则。
30
- * @param {string} text gitignore 格式文本
31
- * @returns {Array<{negated:boolean, dirOnly:boolean, anchored:boolean, pattern:string, re:RegExp|null}>}
32
- */
33
- export function parseGitignore(text) {
34
- const rules = [];
35
- for (const raw of String(text || '').split('\n')) {
36
- let line = raw.replace(/\s+$/, '');
37
- if (!line || line.startsWith('#')) continue;
38
- let negated = false;
39
- if (line.startsWith('!')) { negated = true; line = line.slice(1); }
40
- if (!line) continue;
41
- let dirOnly = false;
42
- if (line.endsWith('/')) { dirOnly = true; line = line.replace(/\/+$/, ''); }
43
- if (!line) continue;
44
- let anchored = false;
45
- if (line.startsWith('/')) { anchored = true; line = line.replace(/^\/+/, ''); }
46
- // 含 `/` 的模式在 gitignore 中天然从根锚定
47
- if (line.includes('/')) anchored = true;
48
- if (!line) continue;
49
- rules.push({ negated, dirOnly, anchored, pattern: line, re: compilePattern(line, anchored) });
50
- }
51
- return rules;
52
- }
53
-
54
- /**
55
- * 把单条 pattern 编译为匹配「仓库相对路径」的正则。
56
- *
57
- * 无 `/` 的模式(anchored=false)编译为「任意层级」:任意目录前缀 + pattern,
58
- * 这正是 gitignore 里 `*.sh` 能命中 `deep/a/b/x.sh` 的原因。
59
- * @param {string} pattern 已剥离 `!`、前导 `/`、尾随 `/` 的模式
60
- * @param {boolean} anchored 是否从根锚定
61
- * @returns {RegExp|null}
62
- */
63
- function compilePattern(pattern, anchored) {
64
- const body = globToRegex(pattern, false);
65
- if (!body) return null;
66
- try {
67
- return new RegExp(anchored ? `^${body.source}$` : `^(?:.*/)?${body.source}$`);
68
- } catch {
69
- return null;
70
- }
71
- }
72
-
73
- /**
74
- * 判断相对路径是否被规则集忽略。
75
- *
76
- * 语义要点:
77
- * - 规则**顺序敏感**:后出现的规则覆盖先出现的(`!` 恢复同样受顺序影响)
78
- * - 目录规则(`gen/`)命中该目录本身**及其全部子路径**
79
- * - 传入的路径统一用 `/` 分隔的仓库相对路径
80
- * @param {Array} rules parseGitignore 的结果
81
- * @param {string} relPath `/` 分隔的相对路径
82
- * @param {boolean} [isDir] 该路径是否为目录(当前仅用于语义自解释,判定不区分)
83
- * @returns {boolean} true = 被忽略
84
- */
85
- export function isIgnoredByRules(rules, relPath, isDir = false) {
86
- const p = String(relPath || '').replace(/\\/g, '/').replace(/^\.\//, '').replace(/^\/+/, '');
87
- if (!p) return false;
88
- let ignored = false;
89
- for (const r of rules) {
90
- if (!r.re) continue;
91
- let hit = r.re.test(p);
92
- // 目录规则:还命中其下所有后代(gen/ → gen/a/b.js)
93
- if (!hit && r.dirOnly) {
94
- const segs = p.split('/');
95
- for (let i = 1; i < segs.length; i += 1) {
96
- if (r.re.test(segs.slice(0, i).join('/'))) { hit = true; break; }
97
- }
98
- }
99
- if (hit) ignored = !r.negated;
100
- }
101
- return ignored;
102
- }
103
-
104
- /**
105
- * 一次性判断:给定 gitignore 文本与相对路径,是否被忽略。
106
- * @param {string} text gitignore 格式文本
107
- * @param {string} relPath `/` 分隔的相对路径
108
- * @param {boolean} [isDir]
109
- * @returns {boolean}
110
- */
111
- export function isIgnored(text, relPath, isDir = false) {
112
- return isIgnoredByRules(parseGitignore(text), relPath, isDir);
113
- }
package/lib/audit/glob.js DELETED
@@ -1,63 +0,0 @@
1
- /**
2
- * dsh-git-push glob → RegExp 转换(1.0.4,private-files 匹配用)
3
- *
4
- * 支持子集:`**`(任意层级)、`*`(单层任意)、`?`(单字符)、
5
- * `{a,b}`(任选一,可含通配)、`[abc]`(字符类)、`\`(转义)。
6
- * 语义对齐 gitignore:「** + / + id_ed25519」匹配任意深度;`*.key` 匹配任意层级的 .key。
7
- * 不依赖 minimatch(零依赖铁律),实现 ≤40 行,可单测。
8
- */
9
- export function globToRegex(glob, anchored = true) {
10
- if (typeof glob !== 'string' || !glob) return null;
11
- let out = '';
12
- let i = 0;
13
- const s = glob;
14
- while (i < s.length) {
15
- const ch = s[i];
16
- if (ch === '*') {
17
- // ** 跨层级(含零级);* 单层级内任意
18
- if (s[i + 1] === '*') {
19
- while (s[i + 1] === '*') i++; // 吸收连续星:i 停最后一个 *
20
- if (s[i + 1] === '/') { out += '(?:.*/)?'; i += 2; } // i 跳至 '/' 后
21
- else { out += '.*'; i++; }
22
- } else {
23
- out += '[^/]*';
24
- i++;
25
- }
26
- } else if (ch === '?') {
27
- out += '[^/]';
28
- i++;
29
- } else if (ch === '{') {
30
- // {a,b} → (?:a|b),最省实现:找配对 }
31
- const end = s.indexOf('}', i);
32
- if (end === -1) { out += '\\{'; i++; continue; }
33
- const inner = s.slice(i + 1, end).split(',').filter(Boolean);
34
- const parts = inner.map((p) => { const r = globToRegex(p, false); return r ? r.source : ''; }).filter(Boolean);
35
- if (parts.length) out += `(?:${parts.join('|')})`;
36
- i = end + 1;
37
- } else if (ch === '[') {
38
- const end = s.indexOf(']', i);
39
- if (end === -1) { out += '\\['; i++; continue; }
40
- let cls = s.slice(i + 1, end).replace(/\\/g, '\\\\');
41
- if (cls.startsWith('!')) cls = '^' + cls.slice(1);
42
- out += `[${cls}]`;
43
- i = end + 1;
44
- } else if ('.+()^$|'.includes(ch)) {
45
- out += `\\${ch}`;
46
- i++;
47
- } else {
48
- out += ch;
49
- i++;
50
- }
51
- }
52
- try {
53
- return new RegExp(anchored ? `^${out}$` : out);
54
- } catch {
55
- return null; // 非法 glob → 调用方跳过
56
- }
57
- }
58
-
59
- /** 一行 glob 是否触及当前路径(供批量匹配)。 */
60
- export function globMatch(glob, path) {
61
- const re = globToRegex(glob);
62
- return !!re && re.test(String(path));
63
- }
@@ -1,100 +0,0 @@
1
- /**
2
- * audit --history 历史提交审计:落盘模块(1.7.0)。
3
- *
4
- * 职责:
5
- * · resolveReportDir —— 保存位置解析(--out 缺省 = git 根 audit-history/ 子目录)
6
- * · writeCommitReport —— 每个提交一份审计清单(<short>-<时间>.json 完整 + .md 可读版)
7
- * · writeHistoryIndex —— SUMMARY.json 全部提交汇总(快速浏览)
8
- * 原子写复用 atomic-json(.tmp + rename),中断/崩溃不出现半文件。
9
- */
10
- import { join } from 'node:path';
11
- import { mkdirSync } from 'node:fs';
12
- import { writeJsonAtomic, writeTextAtomic } from '../core/atomic-json.js';
13
-
14
- /* ───────── 历史审计报告常量 ───────── */
15
- const TIMESTAMP_MAX_LEN = 19; // ISO 时间戳(YYYY-MM-DDTHH:mm:ss)截断长度
16
-
17
- /** 报告保存位置:--out 缺省 = <git根>/audit-history(需求「缺省就是 git 根目录存所有提交的分析」)。 */
18
- export function resolveReportDir(repoPath, outDir = '') {
19
- return String(outDir || '').trim() || join(String(repoPath || '.'), 'audit-history');
20
- }
21
-
22
- /** 可读 Markdown 清单(报告 .md 版;文件/规则/消息结构化展示)。 */
23
- function renderMarkdown(entry = {}) {
24
- const lines = [];
25
- lines.push(`# 审计报告 · ${entry.short} ${entry.subject || ''}`);
26
- lines.push('');
27
- lines.push(`- 提交:${entry.sha}`);
28
- lines.push(`- 作者:${entry.author || ''}|时间:${entry.date || ''}`);
29
- lines.push(`- 文件数:${entry.fileCount ?? 0}`);
30
- const quality = entry.quality || {};
31
- lines.push(`- 质量:${quality.emptyResult ? (quality.emptyReason || '未评分') : `${quality.score}/100(${quality.level || ''})`}`);
32
- const summary = entry.summary || {};
33
- lines.push(`- summary:blocker ${summary.blocker ?? 0} / warning ${summary.warning ?? 0} / notice ${summary.notice ?? 0}(total ${summary.total ?? 0})`);
34
- // 文档加分制(0 分起、上限 10)——结构信号 + 交叉验证
35
- const docsScore = entry.docsScore;
36
- if (docsScore && Array.isArray(docsScore.items)) {
37
- const total = docsScore.items.filter((i) => i.hit).reduce((a, i) => a + (Number(i.score) || 0), 0);
38
- lines.push(`- 文档加分:命中 ${docsScore.hits?.length ?? 0}/${docsScore.items.length}(+${total.toFixed(1)}/10)`);
39
- if (Array.isArray(docsScore.review) && docsScore.review.length) lines.push(`- 建议人工复核:${docsScore.review.join(';')}`);
40
- }
41
- const findings = entry.findings || [];
42
- if (!findings.length) {
43
- lines.push('');
44
- lines.push('(无 findings)');
45
- return lines.join('\n') + '\n';
46
- }
47
- lines.push('');
48
- lines.push('## findings');
49
- for (const f of findings) {
50
- lines.push(`- [${f.severity}] ${f.rule} ${f.file}:${f.line} — ${String(f.message || '').slice(0, 160)}`);
51
- }
52
- return lines.join('\n') + '\n';
53
- }
54
-
55
- /**
56
- * 写单个提交的报告(json 完整 + md 可读),返回落盘路径。
57
- * @param {string} dir 保存目录(resolveReportDir 的结果)
58
- * @param {object} entry { sha, short, date, author, subject, summary, quality, findings, fileCount }
59
- * @returns {{json: string, md: string, base: string}}
60
- */
61
- export function writeCommitReport(dir, entry = {}) {
62
- mkdirSync(dir, { recursive: true });
63
- const ts = String(entry.date || new Date().toISOString()).replace(/[:.]/g, '-').slice(0, TIMESTAMP_MAX_LEN);
64
- const base = `${entry.short || 'unknown'}-${ts}`;
65
- const jsonPath = join(dir, base + '.json');
66
- const mdPath = join(dir, base + '.md');
67
- writeJsonAtomic(jsonPath, entry, { pretty: true });
68
- writeTextAtomic(mdPath, renderMarkdown(entry));
69
- return { json: jsonPath, md: mdPath, base };
70
- }
71
-
72
- /**
73
- * 写全部提交汇总(SUMMARY.json)。
74
- * @param {string} dir 保存目录
75
- * @param {object} meta { repoPath, since, until, total, processed, entries: [{sha,short,date,subject,summary,quality}] }
76
- */
77
- export function writeHistoryIndex(dir, meta = {}) {
78
- mkdirSync(dir, { recursive: true });
79
- const agg = { blocker: 0, warning: 0, notice: 0, total: 0 };
80
- for (const e of meta.entries || []) {
81
- const s = e.summary || {};
82
- agg.blocker += s.blocker || 0;
83
- agg.warning += s.warning || 0;
84
- agg.notice += s.notice || 0;
85
- agg.total += s.total || 0;
86
- }
87
- writeJsonAtomic(join(dir, 'SUMMARY.json'), {
88
- generatedAt: new Date().toISOString(),
89
- repoPath: meta.repoPath || '',
90
- range: { since: meta.since || '', until: meta.until || '' },
91
- total: meta.total ?? 0,
92
- processed: meta.processed ?? 0,
93
- aggregate: agg,
94
- commits: (meta.entries || []).map((e) => ({
95
- sha: e.sha, short: e.short, date: e.date, author: e.author, subject: e.subject,
96
- summary: e.summary || {}, quality: e.quality || {},
97
- })),
98
- }, { pretty: true });
99
- return join(dir, 'SUMMARY.json');
100
- }
@@ -1,126 +0,0 @@
1
- /**
2
- * audit --history 历史提交审计:遍历 + 快照审计核心(1.7.0)。
3
- *
4
- * 语义(需求):
5
- * · **只看历史提交**——不审当前工作区/diff;遍历 git log 指定范围(起始~结束,皆缺省=全部历史、含两端)
6
- * · 每个提交用 `git archive` 解出**代码快照**到临时目录,跑 `auditFull` 全量审计
7
- * (审计规则与当前工作区同一套——不新增第二套审计逻辑)
8
- * · **按提交后台串行**:runHistoryAudit 逐个提交顺序执行(非并发),每提交落盘一份审计清单
9
- *
10
- * git 命令经 runGit/gitRaw(带 DSH_GIT_ENFORCE_PASS 的插件包装器);archive 二进制走 gitRaw Buffer。
11
- */
12
- import { execFileSync } from 'node:child_process';
13
- import { mkdtempSync, rmSync, writeFileSync, existsSync } from 'node:fs';
14
- import { tmpdir } from 'node:os';
15
- import { join } from 'node:path';
16
- import { runGit, gitRaw } from '../core/exec.js';
17
- import { auditFull } from './orchestrate.js';
18
- import { scoreQuality } from '../score/index.js';
19
- import { resolveReportDir, writeCommitReport, writeHistoryIndex } from './history-report.js';
20
-
21
- /* ───────── 历史审计常量 ───────── */
22
- const SHA_SHORT_LEN = 7; // 短 sha 截断长度
23
- const SUBJECT_MAX_LEN = 80; // 提交标题截断长度
24
-
25
- /**
26
- * 列出历史提交(范围含两端)。
27
- * @param {string} repoPath git 仓库路径
28
- * @param {{since?: string, until?: string}} [range] since/until 为空 = 全历史(到 HEAD)
29
- * @returns {Array<{sha,short,subject,author,date}>} 旧→新顺序(git log --reverse)
30
- */
31
- export function listHistoryCommits(repoPath, { since = '', until = '' } = {}) {
32
- const sinceTrim = String(since || '').trim();
33
- const untilTrim = String(until || '').trim();
34
- // 范围:since^..until(含 since 与 until 两端);both 空 = 全历史
35
- const range = untilTrim || 'HEAD';
36
- // range 是提交范围参数,不能放 `--` 之后(`--` 后 git 当路径 → 空结果)
37
- const res = runGit(['log', '--format=%H%x1f%h%x1f%an%x1f%aI%x1f%s', '--reverse', range], { cwd: repoPath });
38
- if (!res.ok) return { error: `读取提交历史失败: ${res.stderr || 'git log 出错'}` };
39
- const out = [];
40
- for (const line of String(res.stdout || '').split('\n')) {
41
- if (!line.trim()) continue;
42
- const [sha, short, author, date, ...subjectParts] = line.split('\x1f');
43
- out.push({ sha, short: short || sha.slice(0, SHA_SHORT_LEN), author: author || '', date: date || '', subject: (subjectParts.join('\x1f') || '').slice(0, SUBJECT_MAX_LEN) });
44
- }
45
- if (sinceTrim) {
46
- // since 语义「从此提交开始(含)」,不用 `since^..until` 范围(根提交无父会 ambiguous);
47
- // 取 until 全部历史后截断到 since 出现处
48
- const idx = out.findIndex((c) => c.sha === sinceTrim || c.short === sinceTrim || c.sha.startsWith(sinceTrim));
49
- if (idx === -1) return { error: `起始提交不存在: ${sinceTrim}` };
50
- return out.slice(idx);
51
- }
52
- return out;
53
- }
54
-
55
- /**
56
- * 对单个历史提交做「快照全量审计」:git archive 解临时目录 → auditFull → 评分 → 清理。
57
- * @param {string} repoPath git 仓库
58
- * @param {object} commit listHistoryCommits 单条
59
- * @param {object} [opts] auditFull 的 opts(rulesetDir/maxScanFiles/slots/disabledSlots/includeIgnored…)
60
- * @param {object} [weights] scoreQuality 权重覆盖
61
- * @returns {Promise<{summary, quality, findings, fileCount}>}
62
- */
63
- export async function auditHistoryCommit(repoPath, commit, opts = {}, weights = {}) {
64
- const tmpDir = mkdtempSync(join(tmpdir(), 'dshgp-hist-'));
65
- const tarPath = join(tmpDir, 'snapshot.tar');
66
- try {
67
- // git archive <sha> → Buffer(二进制,不用 runGit 的 utf8 通道)
68
- const arch = gitRaw(['archive', commit.sha], { cwd: repoPath });
69
- if (arch.error || arch.status !== 0) {
70
- return { error: `git archive ${commit.short} 失败: ${String(arch.error || arch.stderr).slice(0, 200)}` };
71
- }
72
- writeFileSync(tarPath, arch.stdout);
73
- execFileSync('tar', ['-x', '-C', tmpDir, '-f', tarPath], { stdio: 'ignore' });
74
- const historyAudit = await auditFull(tmpDir, opts);
75
- const quality = scoreQuality(historyAudit.findings || [], weights, { files: historyAudit.files, docsScore: historyAudit.docsScore, dimFileCounts: historyAudit.dimFileCounts, dimRuleCounts: historyAudit.dimRuleCounts });
76
- return {
77
- summary: historyAudit.summary || {},
78
- quality,
79
- findings: historyAudit.findings || [],
80
- docsScore: historyAudit.docsScore,
81
- fileCount: historyAudit.files ?? 0,
82
- };
83
- } finally {
84
- rmSync(tmpDir, { recursive: true, force: true });
85
- }
86
- }
87
-
88
- /**
89
- * 串行执行历史审计:逐提交审计 + 落盘 + 进度回调 + 汇总;signal.aborted 时停(已落盘保留)。
90
- * @param {string} repoPath git 仓库
91
- * @param {object} [opts] { since, until, outDir, auditOpts, weights, signal, onCommit }
92
- * @returns {Promise<{ok:boolean, reportDir, total, processed, aborted?, summary, entries, error?}>}
93
- */
94
- export async function runHistoryAudit(repoPath, { since = '', until = '', outDir = '', auditOpts = {}, weights = {}, signal, onCommit } = {}) {
95
- const commits = listHistoryCommits(repoPath, { since, until });
96
- if (Array.isArray(commits) === false || commits.error) {
97
- return { ok: false, error: commits.error || '读取提交历史失败' };
98
- }
99
- if (!commits.length) return { ok: false, error: '没有可审计的历史提交(空仓库?)' };
100
- const dir = resolveReportDir(repoPath, outDir);
101
- const entries = [];
102
- let aborted = false;
103
- for (let i = 0; i < commits.length; i += 1) {
104
- if (signal && signal.aborted) { aborted = true; break; }
105
- const commit = commits[i];
106
- const res = await auditHistoryCommit(repoPath, commit, auditOpts, weights);
107
- if (res.error) {
108
- entries.push({ ...commit, error: res.error, summary: {}, quality: {}, findings: [] });
109
- } else {
110
- const entry = { ...commit, ...res };
111
- entries.push(entry);
112
- writeCommitReport(dir, entry);
113
- }
114
- onCommit?.({ index: i + 1, total: commits.length, short: commit.short, ok: !res.error, error: res.error });
115
- }
116
- writeHistoryIndex(dir, { repoPath, since, until, total: commits.length, processed: entries.filter((e) => !e.error).length, entries });
117
- return {
118
- ok: true,
119
- reportDir: dir,
120
- total: commits.length,
121
- processed: entries.length,
122
- failed: entries.filter((e) => e.error).length,
123
- aborted,
124
- entries: entries.map((e) => ({ sha: e.sha, short: e.short, subject: e.subject, ok: !e.error, error: e.error, summary: e.summary, quality: e.quality })),
125
- };
126
- }
@@ -1,102 +0,0 @@
1
- /**
2
- * 审计「静默失明」检测。
3
- *
4
- * 为什么需要:审计的文件收集走 `git check-ignore`,而该判定会采信
5
- * `.git/info/exclude`——这是 git 的**本地私有排除**层,不随仓库分发,却
6
- * 优先级等同于 .gitignore。实测一个被写成单行 `*` 的 `.git/info/exclude`
7
- * 能让整仓文件被判定为「已忽略」:审计只收集到 5 个文件(其余 21 个全跳过),
8
- * 而**不报错、不告警、退出码正常**——调用方看到的是「这个仓库很干净」。
9
- *
10
- * 这比误报危险得多:误报会被人发现并纠正,静默失明不会。且该文件属于本机
11
- * 配置,CI/他人机器上不存在——同一份代码在不同机器上审计结论不同。
12
- *
13
- * 判据(两者取或,均可独立触发):
14
- * ① 静态:`.git/info/exclude` 含「全仓通配」条目(`*` / `/*` / `**` / `**​/*`)
15
- * ② 行为:git 跟踪的文件里,被判定为忽略的比例 ≥ 90% 且数量 ≥ 20
16
- * (正常仓库的 info/exclude 只排除少量本地产物;接近全量说明配置异常)
17
- *
18
- * 只报 warning 不阻断:仓库可能真的有意排除本机文件,交由人确认。
19
- */
20
- import { existsSync, readFileSync } from 'node:fs';
21
- import { join, isAbsolute } from 'node:path';
22
- import { spawnSync } from 'node:child_process';
23
- import { GIT_GLOBAL_ARGS } from '../core/exec.js';
24
-
25
- /* ───────── 静默失明检测常量 ───────── */
26
- const GIT_PROBE_TIMEOUT_MS = 5000; // git rev-parse 探测超时
27
- const GIT_LS_TIMEOUT_MS = 20_000; // git ls-files / check-ignore 超时
28
- const TRACKED_MIN = 20; // 行为判据:跟踪文件数下限
29
- const IGNORE_RATIO_THRESHOLD = 0.9; // 行为判据:被忽略比例阈值
30
-
31
- /** 判定为「全仓通配」的模式(这些会让整仓不可见)。 */
32
- const BROAD_PATTERNS = new Set(['*', '/*', '**', '**/*', '.']);
33
-
34
- /**
35
- * 取仓库的 `.git/info/exclude` 绝对路径(兼容 .git 为文件的工作树/submodule)。
36
- * @param {string} root 仓库根
37
- * @returns {string} 路径(可能不存在)
38
- */
39
- function excludePathOf(root) {
40
- const r = spawnSync('git', [...GIT_GLOBAL_ARGS, '-C', root, 'rev-parse', '--git-dir'], {
41
- encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: GIT_PROBE_TIMEOUT_MS,
42
- });
43
- if (r.status !== 0) return '';
44
- let gitDir = String(r.stdout || '').trim();
45
- if (!gitDir) return '';
46
- if (!isAbsolute(gitDir)) gitDir = join(root, gitDir);
47
- return join(gitDir, 'info', 'exclude');
48
- }
49
-
50
- /**
51
- * 检测审计是否可能因本地 git 排除配置而静默失明。
52
- * @param {string} root 仓库根目录
53
- * @returns {{broad: string[], ignoreRatio: number, tracked: number}|null} null = 非 git 或无异常
54
- */
55
- export function detectIgnoreBlindSpot(root) {
56
- const probe = spawnSync('git', [...GIT_GLOBAL_ARGS, '-C', root, 'rev-parse', '--is-inside-work-tree'], {
57
- encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: GIT_PROBE_TIMEOUT_MS,
58
- });
59
- if (probe.status !== 0 || String(probe.stdout || '').trim() !== 'true') return null;
60
-
61
- // ① 静态判据:info/exclude 里的全仓通配
62
- const broad = [];
63
- try {
64
- const p = excludePathOf(root);
65
- if (p && existsSync(p)) {
66
- for (const raw of readFileSync(p, 'utf8').split('\n')) {
67
- const line = raw.trim();
68
- if (!line || line.startsWith('#')) continue;
69
- if (BROAD_PATTERNS.has(line)) broad.push(line);
70
- }
71
- }
72
- } catch { /* 读不到则跳过静态判据,行为判据仍生效 */ }
73
-
74
- // ② 行为判据:被忽略的跟踪文件占比
75
- let tracked = 0;
76
- let ignored = 0;
77
- try {
78
- const ls = spawnSync('git', [...GIT_GLOBAL_ARGS, '-C', root, 'ls-files'], {
79
- encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: GIT_LS_TIMEOUT_MS,
80
- });
81
- if (ls.status === 0) {
82
- const files = String(ls.stdout || '').split('\n').filter(Boolean);
83
- tracked = files.length;
84
- if (tracked) {
85
- // 必须带 --no-index:对**已跟踪**文件,check-ignore 默认不报(它们按定义不被忽略),
86
- // 而我们要问的正是「这些文件在审计收集时会不会被跳过」。实测不带该参数时
87
- // 被 `*` 污染的仓库仍返回 0 条,行为判据形同失效。
88
- const ci = spawnSync('git', [...GIT_GLOBAL_ARGS, '-C', root, 'check-ignore', '--stdin', '--no-index'], {
89
- input: files.join('\n'), encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], timeout: GIT_LS_TIMEOUT_MS,
90
- });
91
- if (ci.status === 0 || ci.status === 1) {
92
- ignored = String(ci.stdout || '').split('\n').filter(Boolean).length;
93
- }
94
- }
95
- }
96
- } catch { /* 判据不可用则按未命中处理 */ }
97
-
98
- const ignoreRatio = tracked ? ignored / tracked : 0;
99
- const ratioHit = tracked >= TRACKED_MIN && ignoreRatio >= IGNORE_RATIO_THRESHOLD;
100
- if (!broad.length && !ratioHit) return null;
101
- return { broad, ignoreRatio, tracked };
102
- }
@@ -1,33 +0,0 @@
1
- /**
2
- * 审计层 · 统一出口
3
- *
4
- * 本目录是「审计编排层」:采集文件(collector/glob)→ 逐文件跑检查(audit-file)
5
- * → 豁免过滤(lib/exempt/)→ 汇总(finding/slot)→ 按范围编排(orchestrate)。
6
- *
7
- * 分层位置(四层审计架构最上层):
8
- * lib/audit-rules/*.yml 规则内容(阈值/严重度/豁免清单)
9
- * lib/rule/* 规则加载与编译
10
- * lib/ast/* · lib/checks/* token 级实现与检查包装
11
- * lib/audit/* 采集与编排(本目录)
12
- *
13
- * 模块划分:
14
- * finding.js finding 构造、豁免提示装饰、汇总统计、代码扩展名表
15
- * slot.js 规则槽位统计(槽位命中数、槽位映射、按槽位计数)
16
- * repo-level.js 仓库级语义规则的锚点文件选择(全仓只报一次的那类规则)
17
- * file-context.js 文件上下文判定辅助(同函数内 mkdir、外部调用超时、js/yaml import、版本号在路径中)
18
- * audit-file.js 单文件审计(读文件 → 跑检查 → 豁免过滤)
19
- * orchestrate.js 编排入口:全量审计 / 变动审计 / 作用域审计 / 扫描上限截断
20
- *
21
- * 注意本文件底部的副作用 import:lib/rule/compilers.js 靠 import 触发规则编译器注册,
22
- * 删掉它会让审计拿到空编译器表(不报错,但检查项全不出)。
23
- */
24
-
25
- import '../rule/compilers.js'; // 副作用:注册 13 种编译函数
26
-
27
- export { makeFinding, decorateTestExemptHint, normalizeExemptHints, isBlockerFinding, summarize, CODE_EXTS } from './finding.js';
28
- export { slotStatsFromFindings, buildRuleSlotMap, countRulesBySlot } from './slot.js';
29
- export { repoLevelSemanticRuleIds, pickRepoLevelAnchorFile } from './repo-level.js';
30
- export { hasMkdirInSameFunction, hasForeignWriteTarget, hasExternalCallTimeout, detectRepoJsYamlImport, isVersionInPathContext } from './file-context.js';
31
- export { auditFile } from './audit-file.js';
32
- export { capScanFiles, auditFull, auditChanged, auditWithScope } from './orchestrate.js';
33
- export { findingsToYaml } from './report-yaml.js';