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,107 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * dsh-git-push — FS 热点静态扫描(独立 CLI,咨询性,恒退出码 0)
4
- *
5
- * 用法:
6
- * node scripts/scan-fs-hotspots.mjs [root] [--json] [--top N] [--include 子串] [--exclude 子串] [--include-tests]
7
- *
8
- * 判据(六类,与审计规则 performance/multi-file-scanners 同源 ✓):
9
- * ① stat 热点 按 stat 调用点数排序的文件
10
- * ② 重复 stat 同一函数内同一表达式 stat ≥2 次
11
- * ③ 重复 readdir 同一函数内同一表达式 readdir ≥2 次
12
- * ④ 遍历入口 readdir + (自递归 或 已知 walker 名)
13
- * ⑤ 逐文件扫描实现 同一函数内既有 readdir 又有 stat
14
- * ⑥ 汇总 totals
15
- *
16
- * 【为什么不自己再写一遍判据】判据实现只在 lib/ast/fs-hotspots.js 一份 —— 审计规则
17
- * (lib/checks/fs-scanner.js)与 CLI 都用它 ⇒ 不会出现「脚本说 9 个、规则说 7 个」的漂移 ✗
18
- * (2026-10-16 由 bench-template 的 scan-fs-hotspots.mjs 交接而来:规则化 + 复用插件 tokenizer)
19
- * 【退出码恒 0】这是**咨询性报告**,不拦提交(要拦走审计规则 ✓)
20
- * dsh-skip-i18n: 用户可见文案硬编码为产品设计
21
- */
22
- import { readFileSync, readdirSync } from 'node:fs';
23
- import { join, relative, extname } from 'node:path';
24
- import { scanFsHotspots, FS_WALKERS } from '../lib/ast/fs-hotspots.js';
25
-
26
- /** 默认豁免目录(与审计规则口径一致:审计侧由 collector 跳过,这里显式列同一份)。 */
27
- const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'release', '.trash', '.auto-update-tmp', 'cache-index', 'cache-gifs', '__pycache__']);
28
- const TEST_DIRS = new Set(['test', 'tests']);
29
- const EXTS = new Set(['.js', '.mjs', '.cjs']);
30
-
31
- function parseArgs(argv) {
32
- const o = { root: process.cwd(), json: false, top: 10, include: '', exclude: '', includeTests: false };
33
- for (let i = 0; i < argv.length; i += 1) {
34
- const a = argv[i];
35
- if (a === '--json') o.json = true;
36
- else if (a === '--top') o.top = Number(argv[++i]) || 10;
37
- else if (a === '--include') o.include = String(argv[++i] || '');
38
- else if (a === '--exclude') o.exclude = String(argv[++i] || '');
39
- else if (a === '--include-tests') o.includeTests = true;
40
- else if (!a.startsWith('--')) o.root = a;
41
- }
42
- return o;
43
- }
44
-
45
- /** 递归收集待扫文件(跳过 SKIP_DIRS;test/tests 默认跳过,--include-tests 纳入 ✓)。 */
46
- function collectFiles(dir, o, out = []) {
47
- let ents = [];
48
- try {
49
- ents = readdirSync(dir, { withFileTypes: true });
50
- } catch {
51
- return out; // 权限/竞态:跳过该目录,不让整轮失败
52
- }
53
- for (const e of ents) {
54
- const full = join(dir, e.name);
55
- if (e.isDirectory()) {
56
- if (SKIP_DIRS.has(e.name)) continue;
57
- if (!o.includeTests && TEST_DIRS.has(e.name)) continue;
58
- collectFiles(full, o, out);
59
- } else if (EXTS.has(extname(e.name))) {
60
- const rel = relative(o.root, full);
61
- if (o.include && !rel.includes(o.include)) continue;
62
- if (o.exclude && rel.includes(o.exclude)) continue;
63
- out.push(full);
64
- }
65
- }
66
- return out;
67
- }
68
-
69
- const opts = parseArgs(process.argv.slice(2));
70
- const files = collectFiles(opts.root, opts);
71
- const fileTexts = files.map((full) => {
72
- try {
73
- return { path: relative(opts.root, full), text: readFileSync(full, 'utf8') };
74
- } catch {
75
- return { path: relative(opts.root, full), text: '' };
76
- }
77
- });
78
- const agg = scanFsHotspots(fileTexts);
79
-
80
- if (opts.json) {
81
- console.log(JSON.stringify({
82
- root: opts.root,
83
- includeTests: opts.includeTests,
84
- walkerNames: FS_WALKERS,
85
- totals: agg.totals,
86
- hot: agg.hot.slice(0, opts.top),
87
- scanners: agg.scanners,
88
- dupStats: agg.dupStats,
89
- dupReaddirs: agg.dupReaddirs,
90
- walkers: agg.walkers,
91
- }, null, 2));
92
- } else {
93
- const t = agg.totals;
94
- console.log(`FS 热点扫描(${t.files} 文件 · stat ${t.stats} · readdir ${t.readdirs} · 重复 stat ${t.dupStats} · 重复 readdir ${t.dupReaddirs} · 遍历入口 ${t.walkerCalls} · 逐文件扫描实现 ${t.scanners})`);
95
- console.log('\n① stat 热点(按 stat 调用点数):');
96
- for (const h of agg.hot.slice(0, opts.top)) console.log(` ${String(h.stats).padStart(3)} stat / ${String(h.readdirs).padStart(3)} readdir ${h.file}`);
97
- console.log('\n④ 遍历入口(readdir + 自递归/已知 walker):');
98
- if (!agg.walkers.length) console.log(' (无)');
99
- for (const w of agg.walkers) console.log(` ${w.file}:${w.line} ${w.fn}() → ${w.calls}`);
100
- if (agg.dupStats.length || agg.dupReaddirs.length) {
101
- console.log('\n②③ 同函数内重复的 stat/readdir(可合并成一次):');
102
- for (const d of [...agg.dupStats, ...agg.dupReaddirs]) console.log(` ${d.file}:${d.line} ${d.fn}() ${d.expr}`);
103
- }
104
- console.log(`\n⑤ 逐文件扫描实现(readdir+stat 同函数,共 ${agg.scanners.length} 个;> 3 时审计规则 performance/multi-file-scanners 会报 notice):`);
105
- for (const s of agg.scanners) console.log(` ${s.file}:${s.line} ${s.fn}()`);
106
- }
107
- process.exit(0); // 咨询性:恒 0(要拦提交走审计规则 ✓)
@@ -1,125 +0,0 @@
1
- #!/usr/bin/env node
2
- // dsh-skip-i18n: CLI 输出硬编码中文为产品行为(无 i18n 需求)
3
- /**
4
- * scan-version.mjs — 版本一致性校验(自身总入口 0.1.4)
5
- *
6
- * 校验四处版本必须一致:
7
- * 1) lib/self/index.js 的 VERSION(单一事实源)
8
- * 2) package.json 的 version
9
- * 3) cli.mjs HELP 文本里的 v${VERSION}
10
- * 4) 版本列表宿主里的当前版本(适配分体式:优先 docs/CHANGELOG.md
11
- * 的 dshgp-version 标记块;无则回退 README「## 版本列表」章节)
12
- * 任一不一致 → exit 1(版本漂移拦截)。
13
- *
14
- * 用法:
15
- * node scripts/scan-version.mjs # 校验(npm run scan-version)
16
- * node scripts/scan-version.mjs --json # JSON 输出(机器可读)
17
- */
18
- import { readFileSync, existsSync } from 'node:fs';
19
- import { join, dirname } from 'node:path';
20
- import { fileURLToPath } from 'node:url';
21
-
22
- import { VERSION, versionInfo, helpSync } from '../lib/self/index.js';
23
-
24
- const __dirname = dirname(fileURLToPath(import.meta.url));
25
- const ROOT = join(__dirname, '..');
26
- const json = process.argv.includes('--json');
27
-
28
- /**
29
- * 从 README 正文提取版本列表里的当前版本(新增)。
30
- *
31
- * 策略:①先找「(当前)」标记行的版本(最精确:作者显式标注的当前版本)
32
- * ②无标记 → 取「## 版本列表 / ## 版本记录 / ## 更新日志」章节内出现的最高版本
33
- * 返回 { found, version, source };source 说明取值依据(便于排查)。
34
- * @param {string} text README 全文
35
- */
36
- export function readmeVersion(text = '') {
37
- const src = String(text || '');
38
- if (!src) return { found: false, version: '', source: '' };
39
- // ① 显式「当前」标记:| **1.2.3**(当前) | 或 - **1.2.3**(当前)
40
- const cur = /\*{0,2}(\d+\.\d+\.\d+)\*{0,2}\s*[((]\s*当前\s*[))]/.exec(src);
41
- if (cur) return { found: true, version: cur[1], source: '(当前)标记行' };
42
- // ② 版本章节内取最高版本
43
- const heads = ['## 版本列表', '## 版本记录', '## 版本历史', '## 更新日志', '## Changelog'];
44
- let section = '';
45
- for (const head of heads) {
46
- const i = src.indexOf(head);
47
- if (i < 0) continue;
48
- const rest = src.slice(i + head.length);
49
- const next = rest.indexOf('\n## ');
50
- section = next >= 0 ? rest.slice(0, next) : rest;
51
- break;
52
- }
53
- const scope = section || src;
54
- const found = [...scope.matchAll(/\|\s*\*{0,2}(\d+\.\d+\.\d+)\*{0,2}/g)].map((m) => m[1]);
55
- if (!found.length) return { found: false, version: '', source: '' };
56
- const cmp = (a, b) => {
57
- const pa = a.split('.').map(Number);
58
- const pb = b.split('.').map(Number);
59
- for (let i = 0; i < 3; i++) {
60
- if (pa[i] !== pb[i]) return pa[i] - pb[i];
61
- }
62
- return 0;
63
- };
64
- const max = found.reduce((a, b) => (cmp(b, a) > 0 ? b : a));
65
- return { found: true, version: max, source: section ? '版本列表章节最高版本' : '全文表格最高版本' };
66
- }
67
-
68
- function main() {
69
- const errors = [];
70
- // 1) lib/self VERSION(import 已拿) 2) package.json
71
- const pkgPath = join(ROOT, 'package.json');
72
- let pkgJson = '';
73
- try { pkgJson = readFileSync(pkgPath, 'utf8'); } catch (e) { errors.push(`读 package.json 失败: ${e?.message || e}`); }
74
- const vi = versionInfo(pkgJson);
75
- if (!vi.ok) errors.push(vi.error);
76
- // 3) cli.mjs HELP 文本(源码里是 v${VERSION} 模板,运行时渲染为 v<版本>)
77
- // 三个 CLI 入口都必须在 HELP 首行引用 v${VERSION} 模板(入口拆成三个后,只查 cli.mjs 会漏掉另外两个)
78
- for (const entryFile of ['cli.mjs', 'cli-audit.mjs', 'cli-tool.mjs']) {
79
- const entryPath = join(ROOT, entryFile);
80
- let entryText = '';
81
- if (existsSync(entryPath)) {
82
- try { entryText = readFileSync(entryPath, 'utf8'); } catch { /* 忽略 */ }
83
- }
84
- if (!entryText.includes('v${VERSION}')) {
85
- errors.push(`${entryFile} HELP 未引用 v${VERSION} 模板(应在 HELP 首行 <CLI名> v${VERSION})`);
86
- }
87
- }
88
- // 4) 版本列表宿主(适配分体式:优先 docs/CHANGELOG.md 的 dshgp-version
89
- // 标记块——README 不再内嵌版本表,只有链接引用;无标记块回退 README 章节)
90
- // 优先认「(当前)」标记行;无标记则取版本列表章节内最高版本。
91
- const changelogPath = join(ROOT, 'docs', 'CHANGELOG.md');
92
- const readmePath = join(ROOT, 'README.md');
93
- let hostText = '';
94
- let hostLabel = '';
95
- if (existsSync(changelogPath)) {
96
- try {
97
- const cl = readFileSync(changelogPath, 'utf8');
98
- const vs = cl.indexOf('<!-- dshgp-version:start -->');
99
- const ve = cl.indexOf('<!-- dshgp-version:end -->');
100
- if (vs >= 0 && ve > vs) { hostText = cl.slice(vs, ve); hostLabel = 'docs/CHANGELOG.md(dshgp-version 标记块)'; }
101
- } catch { /* 读失败回退 README */ }
102
- }
103
- if (!hostText) {
104
- try { hostText = readFileSync(readmePath, 'utf8'); hostLabel = 'README.md'; }
105
- catch (e) { errors.push(`读版本列表宿主失败: ${e?.message || e}`); }
106
- }
107
- const rv = readmeVersion(hostText);
108
- if (!rv.found) {
109
- errors.push(`${hostLabel} 版本列表未找到版本号(应有「## 版本列表」章节,行形如 | **1.2.3**(当前) | … |)`);
110
- } else if (rv.version !== vi.pkgVersion) {
111
- errors.push(`${hostLabel} 版本列表当前版本 ${rv.version}(${rv.source})与 package.json ${vi.pkgVersion} 不一致——发版后须同步版本记录`);
112
- }
113
- const ok = errors.length === 0;
114
- if (json) {
115
- const report = { ok, selfVersion: VERSION, pkgVersion: vi.pkgVersion, readmeVersion: rv.version || '', readmeSource: rv.source || '', errors };
116
- console.log(JSON.stringify(report, null, 2));
117
- } else {
118
- console.log(`版本一致性 ${ok ? '✅' : '❌'}: lib/self=${VERSION} / package.json=${vi.pkgVersion} / README=${rv.version || '未找到'} / cli HELP 引用 v\${VERSION} 模板`);
119
- for (const e of errors) console.error(` ✗ ${e}`);
120
- if (!ok) console.error('\n修法:改 lib/self/index.js 的 VERSION 与 package.json version 同步(单一事实源在 lib/self)');
121
- }
122
- process.exitCode = ok ? 0 : 1;
123
- }
124
-
125
- main();
@@ -1,85 +0,0 @@
1
- /**
2
- * 跨文件符号索引 CLI —— 把 lib/ast/symbol-index.js 的能力做成可直接跑的命令。
3
- *
4
- * 用途:不用起插件/服务,直接对一个仓库出「符号索引 + 跨文件调用边 + 未使用导出候选 + 覆盖率」。
5
- * 覆盖率 = 连边数 / 可解析调用数(成员调用 `x.y()` 已排除并单独计数),是判断静态分析
6
- * 「到底解析到了多少」的置信度指标——只看命中数会被「其实没解析到」误导。
7
- *
8
- * 用法(在插件仓库根目录执行):
9
- * node scripts/symbol-index.mjs <仓库目录> [--json] [--unused] [--top N] [--ext .js,.mjs]
10
- * 例:
11
- * node scripts/symbol-index.mjs ../dsh-git-push --unused
12
- * node scripts/symbol-index.mjs ../dsh-codegraph --ext .ts --json > /tmp/idx.json
13
- */
14
- import { readFileSync, readdirSync, statSync } from 'node:fs';
15
- import { join, relative, resolve } from 'node:path';
16
-
17
- import { buildSymbolIndex, indexSummary, unusedExportCandidates } from '../lib/ast/symbol-index.js';
18
-
19
- const SKIP_DIRS = new Set(['.git', 'node_modules', '.trash', '.codegraph', 'dist', 'build', '__pycache__', '.archify']);
20
- const DEFAULT_EXTS = ['.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx'];
21
-
22
- /** 递归收集源码文件(相对路径,正斜杠)。 */
23
- function collectFiles(root, exts, dir = root, out = []) {
24
- let entries = [];
25
- try { entries = readdirSync(dir); } catch { return out; }
26
- for (const name of entries) {
27
- if (SKIP_DIRS.has(name)) continue;
28
- const full = join(dir, name);
29
- let st = null;
30
- try { st = statSync(full); } catch { continue; }
31
- if (st.isDirectory()) collectFiles(root, exts, full, out);
32
- else if (exts.some((x) => name.endsWith(x))) out.push(relative(root, full).replace(/\\/g, '/'));
33
- }
34
- return out;
35
- }
36
-
37
- /** 解析命令行参数。 */
38
- function parseArgs(argv) {
39
- const args = { exts: DEFAULT_EXTS, json: false, unused: false, top: 8 };
40
- const positional = [];
41
- for (let i = 0; i < argv.length; i++) {
42
- const a = argv[i];
43
- if (a === '--json') args.json = true;
44
- else if (a === '--unused') args.unused = true;
45
- else if (a === '--top') args.top = Number(argv[++i] || 8);
46
- else if (a === '--ext') args.exts = String(argv[++i] || '').split(',').map((s) => s.trim()).filter(Boolean);
47
- else if (a.startsWith('--')) throw new Error(`未知参数: ${a}`);
48
- else positional.push(a);
49
- }
50
- args.root = positional[0];
51
- return args;
52
- }
53
-
54
- const args = parseArgs(process.argv.slice(2));
55
- if (!args.root) {
56
- console.error('用法: node scripts/symbol-index.mjs <仓库目录> [--json] [--unused] [--top N] [--ext .js,.mjs]');
57
- process.exit(2);
58
- }
59
- const root = resolve(args.root);
60
- const files = collectFiles(root, args.exts);
61
- const index = buildSymbolIndex(files, { readFile: (rel) => readFileSync(join(root, rel), 'utf8') });
62
- const unused = unusedExportCandidates(index);
63
-
64
- if (args.json) {
65
- console.log(JSON.stringify({
66
- root, stats: index.stats, summary: indexSummary(index),
67
- edges: index.edges, unresolved: index.unresolved, unusedExports: unused,
68
- }, null, 2));
69
- } else {
70
- console.log(`仓库: ${root}`);
71
- console.log(indexSummary(index));
72
- console.log(`排除的成员调用: ${index.stats.skippedMemberCalls}(x.y() 这类不经符号索引解析)`);
73
- const byReason = {};
74
- for (const u of index.unresolved) byReason[u.reason] = (byReason[u.reason] || 0) + 1;
75
- console.log(`未解析构成: ${JSON.stringify(byReason)}`);
76
- const top = index.edges.filter((e) => e.via === 'import').slice(0, args.top);
77
- if (top.length) {
78
- console.log(`跨文件调用边(前 ${top.length} 条):`);
79
- for (const e of top) console.log(` ${e.from}:${e.line} → ${e.to}`);
80
- }
81
- if (args.unused) {
82
- console.log(`未使用导出候选(${unused.length} 个,动态访问/外部引用无法静态判定,仅作线索):`);
83
- for (const u of unused.slice(0, args.top * 3)) console.log(` ${u.file}:${u.line} ${u.name}`);
84
- }
85
- }
@@ -1,100 +0,0 @@
1
- /**
2
- * 上下文注入自检脚本(配合 1.5.2 工具探测改上下文注入)
3
- *
4
- * 真实调用 apply() 并触发 agent/pre-step,验证环境信息按上下文注入:
5
- * - 工作区跑:验证接线正确 + 无 DSH 依赖时降级不崩(@deepseek-ai/dsh-llm 解析不到 → 注入跳过)
6
- * - 安装副本跑(profiles/.../node_modules/dsh-git-push):完整验证注入 user 消息
7
- * (工作区目录 + 工具安装路径(实测)+ skill 总入口,source 标记 plugin instructions)
8
- *
9
- * 用法:node scripts/verify-prestep.mjs
10
- * 退出码:0 = 接线与(可注入时)注入全部符合预期;1 = 断言失败
11
- */
12
- import { apply } from '../lib/app/apply.js';
13
- import { setDefineToolOverride } from '../lib/plugin/index.js';
14
-
15
- /** 被验证的宿主事件名(pre-step:上下文注入发生在 agent 回合前)。 */
16
- const PRE_STEP_EVENT = 'agent/pre-step';
17
-
18
- /** 简易断言计数(不引测试框架)。 */
19
- const results = [];
20
- function check(name, ok) { results.push([name, !!ok]); if (!ok) console.log(' ❌', name); }
21
-
22
- // 1) defineTool 喂 mock(工作区无 DSH 依赖;安装副本同样可喂)
23
- setDefineToolOverride((spec) => spec);
24
-
25
- // 2) mock DSH ctx:tools/systemPrompt/webServer 服务 + agent/pre-step 事件捕获
26
- const sections = [];
27
- const events = {};
28
- const registered = [];
29
- const ctx = {
30
- get: (k) => (k === 'log' ? { info: () => {}, warn: (...a) => console.log(' [warn]', ...a) } : undefined),
31
- inject: (keys, fn) => {
32
- if (keys[0] === 'tools') fn({ get: (k) => (k === 'tools' ? { register: (t) => registered.push(t) } : undefined) });
33
- if (keys[0] === 'systemPrompt') fn({ get: (k) => (k === 'systemPrompt' ? { section: (s) => sections.push(s) } : undefined) });
34
- if (keys[0] === 'webServer') fn({ get: (k) => (k === 'webServer' ? { register: () => {} } : undefined) });
35
- },
36
- on: (name, handler) => { events[name] = handler; },
37
- };
38
-
39
- // 3) 真实调用 apply
40
- await apply(ctx, { workspaceRoot: process.cwd() });
41
- setDefineToolOverride(null);
42
-
43
- console.log('== 注册统计 ==');
44
- console.log('systemPrompt sections:', sections.map((s) => s.name).join(', ') || '(空)');
45
- console.log('agent/pre-step 接线:', typeof events[PRE_STEP_EVENT] === 'function' ? '✅ 是' : '❌ 否');
46
- console.log('工具注册数:', registered.length);
47
-
48
- // 环境段不应再注册为 systemPrompt section(迁出)
49
- check('systemPrompt 不含环境段(dsh-git-push-env 已迁出)', !sections.some((s) => s.name === 'dsh-git-push-env'));
50
- check('systemPrompt 保留功能用法段', sections.some((s) => s.name === 'dsh-git-push-usage'));
51
- check('agent/pre-step 已接线', typeof events[PRE_STEP_EVENT] === 'function');
52
- check('工具已注册', registered.length >= 8);
53
-
54
- if (typeof events[PRE_STEP_EVENT] !== 'function') {
55
- console.log('\n❌ 未接线,退出(exit 1)');
56
- process.exit(1);
57
- }
58
-
59
- // 4) 构造「首次 step」decision 并触发 pre-step
60
- const decision = {
61
- kind: 'next',
62
- messages: [{ role: 'user', content: [{ type: 'text', text: '(原有消息)' }] }],
63
- };
64
- const agent = { id: 'verify-agent-1', session: { id: 'verify-session' } };
65
- const first = await events[PRE_STEP_EVENT]({ agent, signal: undefined }, async () => decision);
66
- const count1 = first.messages.length;
67
- const injected = count1 > 1 ? first.messages[count1 - 1] : null;
68
-
69
- console.log('\n== 首次触发 ==');
70
- check('首次触发追加 1 条注入消息', count1 === 2);
71
- if (injected) {
72
- check('注入消息 role=user', injected.role === 'user');
73
- check('注入消息 source 标记(plugin/dsh-git-push/instructions)',
74
- injected.source?.kind === 'plugin' && injected.source?.plugin === 'dsh-git-push' && injected.source?.form === 'instructions');
75
- }
76
-
77
- // 5) 再次触发同一 agent:WeakSet 防重复,不应再追加
78
- const second = await events[PRE_STEP_EVENT]({ agent, signal: undefined }, async () => decision);
79
- check('二次触发不重复注入(回到原 1 条)', second.messages.length === 1);
80
-
81
- // 6) 注入正文内容校验(注入成功时)
82
- if (injected) {
83
- const text = injected.content?.[0]?.text || '';
84
- console.log('\n== 注入上下文正文 ==\n----------------------------------------');
85
- console.log(text);
86
- console.log('----------------------------------------');
87
- check('含工作区根目录', /工作区根目录/.test(text));
88
- check('含当前工作目录 cwd', /当前工作目录 cwd/.test(text));
89
- check('含工具安装路径', /工具:/.test(text));
90
- check('含 git 实测路径', /git=/.test(text));
91
- check('含 skill 总入口', /skills/.test(text));
92
- } else {
93
- console.log('\n(未注入:当前运行环境无 @deepseek-ai/dsh-llm 依赖,属预期降级;')
94
- console.log(' 在安装副本 profiles/.../node_modules/dsh-git-push 下运行可完整验证注入)');
95
- }
96
-
97
- // 7) 汇总
98
- const failed = results.filter(([, ok]) => !ok).length;
99
- console.log(`\n== 结果:${results.length - failed}/${results.length} 通过 ==`);
100
- process.exit(failed ? 1 : 0);
@@ -1,173 +0,0 @@
1
- /**
2
- * 版本源探测与版本表聚合(供 doc-version 门禁生成 CHANGELOG/README 版本表使用)。
3
- *
4
- * 来历:原先与 README 模板渲染混在 scripts/readme-gen.mjs 里;README 生成能力已作废(README 改由
5
- * readme-spec 手工维护、不再按模板渲染),故把**仍在关键路径上**的版本源逻辑单独拆出,
6
- * 模板渲染/TOC/genReadme 一并删除,避免死代码继续挂在门禁脚本的依赖链上。
7
- *
8
- * 纯读取:只读 package.json 等版本文件、docs/releases.json、version-metrics.json,
9
- * 不写盘、不改仓库(写入由 doc-version.mjs 负责)。
10
- */
11
- import { existsSync, readFileSync } from 'node:fs';
12
- import { join } from 'node:path';
13
- import { spawnSync } from 'node:child_process';
14
-
15
- /** runGit 精简单机版(git log 取提交标题,供版本表聚合)。 */
16
- function runGit(args, { cwd = '' } = {}) {
17
- try {
18
- const r = spawnSync('git', args, { encoding: 'utf8', cwd: cwd || undefined, stdio: ['pipe', 'pipe', 'ignore'] });
19
- return { ok: r.status === 0, stdout: r.stdout || '', stderr: r.stderr || '' };
20
- } catch (e) {
21
- return { ok: false, stdout: '', stderr: String(e?.message || e) };
22
- }
23
- }
24
-
25
- /** 渲染 yml 模板({ header, sections })→ markdown 模板文本(占位符原样保留)。 */
26
-
27
- const VERSION_RE = /\bv?(\d+)\.(\d+)\.(\d+)\b/;
28
-
29
- /** 解析版本三元组。 */
30
- export function parseVersion(str) {
31
- const match = String(str).match(VERSION_RE);
32
- if (!match) return null;
33
- return { major: parseInt(match[1], 10), minor: parseInt(match[2], 10), patch: parseInt(match[3], 10) };
34
- }
35
-
36
- const v2s = (v) => `${v.major}.${v.minor}.${v.patch}`;
37
-
38
- /** git log 按版本标题分组(补丁并入主版本)。 */
39
- export function listVersionCommits(repoPath) {
40
- const log = runGit(['log', '--reverse', '--format=%H|%s'], { cwd: repoPath });
41
- if (!log.ok || !log.stdout) return [];
42
- const groups = [];
43
- for (const line of log.stdout.split('\n')) {
44
- const i = line.indexOf('|');
45
- if (i < 0) continue;
46
- const hash = line.slice(0, i);
47
- const msg = line.slice(i + 1);
48
- const v = parseVersion(msg);
49
- // 只渲染标题带版本号的提交;无版本号提交不渲染(不归组、不合成占位行)
50
- if (v) groups.push({ version: v, versionStr: v2s(v), label: msg, isPatch: v.patch > 0 });
51
- }
52
- return groups;
53
- }
54
-
55
- /** 版本记录表 markdown。 */
56
- /**
57
- * 清洗提交标题里的许可类措辞(release-docs-rule:公开文档不写许可类交流内容)。
58
- * 黑名单词用字符类拆分(如 用[户]),避免正则字面量被审计的自举误报命中。
59
- */
60
- export function scrubConvWording(label) {
61
- const user = '[用][户]';
62
- return String(label || '')
63
- // 剔除括号内沟通短语(许可/同意/要求/确认等)
64
- .replace(new RegExp(`[((](?:${user})?(?:许可|同意|要求|确认|授权)[^))]*[))]`, 'g'), '')
65
- // 残留裸短语(扩充:补决策来源类裸短语——此前只清括号内与「同意/要求/许可」,
66
- // 裸的「按用[户]确认删除」会整句留在版本表里,被公开文档规则拦下)
67
- // 本项目惯例:黑名单词在注释与正则里都做字符类拆分(如 用[户]、指[示]),避免注释自举规则误报命中
68
- .replace(new RegExp(`(${user}许可升版)|(${user}许可)|${user}许可升版|${user}同意|${user}要求|按?经?${user}(?:确认|决[定]|指[示]|反馈|指[出]|建议|选择)[,、]?`, 'g'), '')
69
- .replace(new RegExp(`(${user}[^)]*)|\\(${user}[^)]*\\)`, 'g'), '')
70
- .replace(new RegExp(`——bump[\\s\\S]*?(${user}[^)]*)`, 'g'), '')
71
- // 清理遗留的分号/空括号
72
- .replace(/;;+/g, ';').replace(/\(\)/g, '').replace(/;\s*$/, '').replace(/——\s*$/, '')
73
- .trim();
74
- }
75
-
76
- /**
77
- * 读可选的「版本量化记录」(`<repo>/version-metrics.json`)。
78
- *
79
- * 为什么需要:版本表由 git log 聚合,行内容取自提交信息——偏叙述,看不出这版到底改善了多少。
80
- * 本函数允许为某版本补一句**前后对比**(如「误报 16 → 0」),渲染时拼到该行内容最前。
81
- * 数据放独立 json(而不是写死在脚本里):改数字不用改代码,且与版本号一一对应可校验。
82
- *
83
- * @returns {Record<string,string>} 版本号 → 一句话量化(缺文件/格式错时返回空对象,不阻断生成)
84
- */
85
- export function readVersionMetrics(repoPath) {
86
- try {
87
- const p = join(repoPath, 'version-metrics.json');
88
- if (!existsSync(p)) return {};
89
- const data = JSON.parse(readFileSync(p, 'utf8'));
90
- return data && typeof data === 'object' && !Array.isArray(data) ? data : {};
91
- } catch { return {}; }
92
- }
93
-
94
- /** 支持的项目类型 → 版本文件(数组顺序即探测优先级)。
95
- * 2026-10-16 从 doc-version.mjs 迁来(版本源逻辑与版本表生成同源,避免两处各写一份)。 */
96
- export const VERSION_SOURCES = [
97
- { id: 'package.json', file: 'package.json', read: (t) => JSON.parse(t).version },
98
- { id: 'pyproject.toml', file: 'pyproject.toml', read: (t) => (t.match(/^\s*version\s*=\s*["']([^"']+)["']/m) || [])[1] },
99
- { id: 'Cargo.toml', file: 'Cargo.toml', read: (t) => (t.match(/^\s*version\s*=\s*["']([^"']+)["']/m) || [])[1] },
100
- { id: 'composer.json', file: 'composer.json', read: (t) => JSON.parse(t).version },
101
- { id: 'setup.cfg', file: 'setup.cfg', read: (t) => (t.match(/^\s*version\s*=\s*([^\s#]+)/m) || [])[1] },
102
- ];
103
-
104
- /** 按项目类型探测版本源;都不匹配返回 ''(**不再回退 git log** —— 见 buildReadmeVersionTable 说明)。 */
105
- export function detectVersionSource(root) {
106
- for (const s of VERSION_SOURCES) {
107
- if (existsSync(join(root, s.file))) return s.id;
108
- }
109
- return '';
110
- }
111
-
112
- /** 按已识别/指定的版本源读取版本号;读不到返回空串(不抛错)。 */
113
- export function projectVersionOf(root, source = '') {
114
- const src = source || detectVersionSource(root);
115
- const def = VERSION_SOURCES.find((s) => s.id === src);
116
- if (!def) return '';
117
- try {
118
- const v = def.read(readFileSync(join(root, def.file), 'utf8'));
119
- return v ? String(v).trim() : '';
120
- } catch {
121
- return '';
122
- }
123
- }
124
-
125
- /** 读可选的「版本发布说明」文件(`<repo>/docs/releases.json`)——版本表行内容的真源。 */
126
- export function readReleases(repoPath) {
127
- try {
128
- const p = join(repoPath, 'docs', 'releases.json');
129
- if (!existsSync(p)) return {};
130
- const data = JSON.parse(readFileSync(p, 'utf8'));
131
- return data && typeof data === 'object' && !Array.isArray(data) ? data : {};
132
- } catch { return {}; }
133
- }
134
-
135
- /**
136
- * 版本记录表 markdown(**全部来自文件,不读 git log**)。
137
- *
138
- * 数据源:
139
- * · `docs/releases.json` —— 每个版本一行的说明(历史行真源)
140
- * · 版本真源文件(package.json / pyproject.toml / Cargo.toml / composer.json / setup.cfg)
141
- * —— 当前版本号(releases.json 未登记时也保证有这一行)
142
- * · `version-metrics.json` —— 可选量化记录,拼到该行内容最前
143
- *
144
- * 为什么改成文件驱动(2026-10-16):此前行内容取自 **git log 提交标题** ⇒
145
- * · 任何不带版本号的普通提交都会改动「最新行」的内容/条数 ⇒ 版本表门禁报漂移 ✗
146
- * · 门禁一旦红了,就只好「为门禁升版本」——把版本号变成讨好门禁的产物 ✗(本末倒置)
147
- * 改为文件驱动后:**普通提交完全不动版本表**;发版只改 `docs/releases.json` 一行 ✓。
148
- *
149
- * `listVersionCommits` 仍保留导出(旧调用方/测试可用),但本函数不再调用它。
150
- */
151
- export function buildReadmeVersionTable(repoPath) {
152
- const releases = readReleases(repoPath);
153
- const metrics = readVersionMetrics(repoPath);
154
- const current = projectVersionOf(repoPath);
155
- const lines = ['| 版本 | 内容 |', '|------|------|'];
156
- const keys = new Set(Object.keys(releases));
157
- if (current) keys.add(current);
158
- const ordered = [...keys].sort((a, b) => {
159
- const [am, ai, ap] = a.split('.').map(Number);
160
- const [bm, bi, bp] = b.split('.').map(Number);
161
- return (bm - am) || (bi - ai) || (bp - ap);
162
- });
163
- for (const k of ordered) {
164
- const raw = releases[k] || (k === current ? '(本版说明待补:docs/releases.json 未登记)' : '');
165
- const body = scrubConvWording(String(raw));
166
- if (!body) continue;
167
- const metric = metrics[k] ? `${metrics[k]}——${body}` : body;
168
- lines.push(`| ${k} | ${metric} |`);
169
- }
170
- return lines;
171
- }
172
-
173
- /** 生成 README 文本(不落盘)。 */
@@ -1,58 +0,0 @@
1
- ---
2
- name: audit-rule-authoring
3
- description: 给 dsh-git-push 审计引擎新增规则的要点与坑:allow/deny 两种精筛语义、allow 语义下必须自查注释与字符串、判据收窄前先在自己仓库量命中量、用真实样本当回归测试、诚实标注代理特征。处理「新增审计规则」「性能规则」「规则误报太多」「astConfirmKind」类场景时加载。
4
- whenToUse: 给本插件(或同类规则引擎)新增/调整审计规则时;规则误报或漏报排查时。
5
- generatedBy: deepseek-v4-flash(2026-10-08)
6
- ---
7
-
8
- # 审计规则编写要点(dsh-git-push)
9
-
10
- > **先记住我**:任何会话开始前,先读用户档案 `ai-work-archive/skills/remember-me.md`(优先级最高)。
11
- > 本 skill 为**插件相关**,权威位置:插件项目 `skills/dev/`。
12
-
13
- ## 一、规则形态(沿用既有架构,不另造机制)
14
-
15
- | 层 | 文件 | 职责 |
16
- |---|---|---|
17
- 规则声明 | `lib/audit-rules/audit-rules-<槽位>.yml` | id / category / severity / exts / patterns / mitigation |
18
- AST 精筛 | `lib/ast/<模块>.js` | 提供「命中行号集合」的判定函数(如 `loopBodyLines`) |
19
- 引擎派发 | `lib/checks/regex.js` | 按 `rule.astConfirmKind` 取精筛集合 |
20
- 取值出口 | `lib/checks/common.js` | 统一导出精筛集合取值函数(约定:都从这里取) |
21
-
22
- ## 二、两种精筛语义(关键)
23
-
24
- | 语义 | 含义 | 典型用法 |
25
- |---|---|---|
26
- `deny` | 集合内的行**豁免** | 受控小文件读取不算 memory-bomb |
27
- `allow` | **只有**集合内的行才报 | token 级短名、循环体内的命中 |
28
-
29
- ## 三、坑(都踩过)
30
-
31
- 1. **allow 语义会跳过引擎的通用 `codeFilter`** → 注释/字符串里的示例**不会被自动过滤**。
32
- 实测:规则说明注释里写了 `Array.from(x.values())` 示例(恰在 `for` 循环体内),被自己的规则命中。
33
- → 用 `tokenize()` 做 **token 级排除**:同行存在 `comment`/`str`/`tmpl` 且文本包含命中串则不算命中。
34
- 2. **判据先宽后窄必须量化**:第一版规则在我们仓库炸出 **218 处**(`log/push/emit/readFile` 这类
35
- 重复调用是有意为之)→ 收窄到「查询/解析类函数名」后 **4 处**。
36
- → 纪律:**新规则提交前先在自己仓库跑一遍数命中量**,量级不合理先收窄。
37
- 3. **edit 锚点行会被自己吃掉**:把「函数注释头」当锚点替换 → 留下孤儿注释 → `SyntaxError`。
38
- → 凡 edit 后立刻 `node --check`;「在某行前插入」时锚点行必须原样出现在新内容里。
39
- 4. **不要用「同一函数内占比高」证明「某几行是元凶」** → 改完复测才作数(见 `perf-diagnosis-method`)。
40
-
41
- ## 四、测试写法
42
-
43
- - **用真实样本当回归测试**:把外部真实项目里的问题片段(如 `symbol-table.ts` 的循环内物化结构)
44
- 写成 fixture 字符串,断言「必须命中」;再配「循环外/实参不同/注释里」的负样本断言「不报」。
45
- - 端到端再补一条:`checkRegexRules({ file, text, rules: [<规则对象>] })` 断言命中数与规则 id
46
- (规则对象用 `subPatterns: [{ regex, message }]` 形态,`patterns: [{regex}]` 会被引擎当 RegExp 用而报错)。
47
-
48
- ## 五、诚实标注
49
-
50
- 规则是**代理特征**,不是判决器:
51
- - 「循环内全量物化」能静态判 → 可作规则;
52
- - 「入参部分重叠的重复调用」「函数是否真的贵」→ 静态判不出来,只能靠运行时探针;
53
- - 结论里要写清「本规则抓什么、抓不到什么」,避免使用者误以为规则=全知。
54
-
55
- ## 配套
56
-
57
- - `perf-diagnosis-method`(性能定位与等价性验证)、`diagnostic-to-code-rule`(诊断转规则)、
58
- - `code-detailed-comments`(注释写为什么)、`test-design-norms`(测试路径与隔离规范)。