dsh-git-push 2.18.2 → 2.20.11

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 (43) hide show
  1. package/.gitignore +4 -0
  2. package/README.md +3 -0
  3. package/cli.mjs +16 -3
  4. package/lib/ARCHITECTURE.md +3 -0
  5. package/lib/app/audit-api.js +1 -1
  6. package/lib/app/command-registry.js +13 -1
  7. package/lib/app/inject-text.js +1 -0
  8. package/lib/app/scope-check.js +69 -0
  9. package/lib/app/tool-call.js +49 -2
  10. package/lib/ast/credential.js +130 -14
  11. package/lib/ast/dataflow.js +127 -10
  12. package/lib/ast/index.js +2 -0
  13. package/lib/ast/naming.js +9 -1
  14. package/lib/ast/scope-collisions.js +228 -0
  15. package/lib/ast/treesitter.js +142 -1
  16. package/lib/audit/history.js +1 -1
  17. package/lib/audit/orchestrate.js +93 -6
  18. package/lib/audit/scope-policy.js +110 -0
  19. package/lib/audit-rules/audit-rules-dsh.yml +16 -1
  20. package/lib/audit-rules/audit-rules-nodejs.yml +21 -6
  21. package/lib/checks/common.js +4 -4
  22. package/lib/checks/dispatch.js +5 -0
  23. package/lib/checks/index.js +2 -0
  24. package/lib/checks/regex.js +2 -2
  25. package/lib/checks/scope-collision.js +68 -0
  26. package/lib/cli/commands-audit.mjs +1 -1
  27. package/lib/commit-push.js +6 -1
  28. package/lib/exempt/index.js +5 -2
  29. package/lib/git/ignore.js +6 -4
  30. package/lib/git/init-compat.js +83 -4
  31. package/lib/git/push.js +25 -2
  32. package/lib/git/sensitive.js +30 -1
  33. package/lib/lint-adapter/detect.js +161 -0
  34. package/lib/lint-adapter/index.js +50 -0
  35. package/lib/lint-adapter/runner.js +133 -0
  36. package/lib/rule/compilers/structure.js +24 -0
  37. package/lib/score/index.js +36 -4
  38. package/lib/self/index.js +1 -1
  39. package/package.json +20 -1
  40. package/scripts/bump-version.mjs +20 -5
  41. package/scripts/check-js-scope.mjs +87 -0
  42. package/scripts/check.mjs +39 -1
  43. package/skills/dev/dsh-git-push.md +8 -2
@@ -15,6 +15,7 @@ import { decorateTestExemptHint, makeFinding, summarize, normalizeExemptHints, C
15
15
  import { pickRepoLevelAnchorFile, repoLevelSemanticRuleIds } from './repo-level.js';
16
16
  import { checkDocsScore } from '../score/docs-score.js';
17
17
  import { runAuditExt } from './ext-runner.js';
18
+ import { runLintAdapters } from '../lint-adapter/index.js';
18
19
  import { buildRuleSlotMap, countRulesBySlot, slotStatsFromFindings } from './slot.js';
19
20
  import { findingsToYaml } from './report-yaml.js';
20
21
  /**
@@ -119,7 +120,21 @@ function appendIgnoreBlindSpot(findings, repoPath, scanned) {
119
120
  *
120
121
  * @returns {Promise<null|((line:number, col:number)=>boolean|null)>}
121
122
  */
123
+ /**
124
+ * 「有树走树」精筛 kind 清单(方向 E2):这些 astConfirmKind 的检查器在拿到语法树时
125
+ * 会走树语义路径(优于 token 近似),因此**只要规则集里有它们就预解析建树**——
126
+ * 不再局限于 astConfirmSpan(此前 .py 文件因槽位无 astConfirmSpan 规则而从不建树,
127
+ * 凭据精筛永远吃 token 级,是「有树不走树」的根因之一)。
128
+ * 新增成员必须同时在检查器里实现「无树回退」(D5),不得让审计因缺语法而失效。
129
+ */
130
+ const TREE_FIRST_KINDS = new Set(['credential-value', 'short-func-name']);
131
+
122
132
  async function buildTreeConfirmer(relPath, text, grouped) {
133
+ // 返回值语义(供 treeUsage 统计「有树不走树」是否复发):
134
+ // { confirm: fn, state: 'parsed' } ⇒ 语法可用且树真建立、并被消费
135
+ // { confirm: null, state: 'not-needed' } ⇒ 本文件规则集不需要树(省一次解析,正常)
136
+ // { confirm: null, state: 'no-grammar' } ⇒ 需要树但语言无语法(回退 token 级)
137
+ // { confirm: null, state: 'parse-failed' }⇒ 有语法却没建树(资产缺失/超预算/语法错误)——**最该警惕的一档**
123
138
  try {
124
139
  // ⚠️ 取**扩展名**(不是整条路径)——grammarForExt 收的是扩展名 ✓
125
140
  // 按 basename 的最后一个点取:避免 `docs/.vitepress/theme/index.ts` 这类**带点目录**踩坑 ✗
@@ -127,17 +142,18 @@ async function buildTreeConfirmer(relPath, text, grouped) {
127
142
  const base = String(relPath || '').split(/[\\/]/).pop();
128
143
  const ext = base.includes('.') ? base.slice(base.lastIndexOf('.') + 1) : '';
129
144
  const grammar = grammarForExt(ext);
130
- if (!grammar) return null;
145
+ if (!grammar) return { confirm: null, state: 'no-grammar' };
131
146
  let need = false;
132
147
  for (const rules of Object.values(grouped || {})) {
133
148
  if (!Array.isArray(rules)) continue;
134
- if (rules.some((r) => r?.astConfirmSpan === true)) { need = true; break; }
149
+ if (rules.some((r) => r?.astConfirmSpan === true || TREE_FIRST_KINDS.has(String(r?.astConfirmKind || '')))) { need = true; break; }
135
150
  }
136
- if (!need) return null;
151
+ if (!need) return { confirm: null, state: 'not-needed' };
137
152
  const tree = await parseText(text, grammar);
138
- return tree ? makeSyncConfirmer(tree) : null;
153
+ const confirm = tree ? makeSyncConfirmer(tree) : null;
154
+ return confirm ? { confirm, state: 'parsed' } : { confirm: null, state: 'parse-failed' };
139
155
  } catch {
140
- return null;
156
+ return { confirm: null, state: 'parse-failed' };
141
157
  }
142
158
  }
143
159
 
@@ -196,6 +212,31 @@ export function computeDimFileCounts(grouped, normFiles) {
196
212
  return counts;
197
213
  }
198
214
 
215
+ /**
216
+ * 每维度**绑定的生效规则数**(dim → 至少一条规则声明了该维度)。
217
+ *
218
+ * 用途:评分层据此把「零规则维度」权重记 0——本次生效规则集里一条规则都没绑定的维度,
219
+ * 对本仓库**没有检测能力**,不该按「无命中=满分」进总分(实测外部仓库五维齐满分抬到 85/A,
220
+ * 而人工核实出 6 个真问题)。
221
+ * 口径是**生效规则集**(grouped,已按仓库语言/槽位/豁免过滤),不是全量规则表:
222
+ * 纯 Python 仓库没有 C# 专属规则属正常,不该因此把可维护性记 0。
223
+ * 同维度多规则只计 1 次(要的是「有没有检测能力」,不是规则条数)。
224
+ * @returns {{[dim]: number}}
225
+ */
226
+ export function computeDimRuleCounts(grouped) {
227
+ const counts = {};
228
+ const seen = new Set();
229
+ for (const rules of Object.values(grouped || {})) {
230
+ if (!Array.isArray(rules)) continue;
231
+ for (const r of rules) {
232
+ if (!r || !r.id || seen.has(r.id)) continue;
233
+ seen.add(r.id);
234
+ for (const d of r.dimensions || []) counts[d] = (counts[d] || 0) + 1;
235
+ }
236
+ }
237
+ return counts;
238
+ }
239
+
199
240
  async function auditFiles(repoPath, files, opts = {}) {
200
241
  // 归一化:full 收集项用 path,changed 用 rel → 统一取 path
201
242
  const normFiles = files.map((f) => ({ path: f.path ?? f.rel, full: f.full, status: f.status }));
@@ -254,6 +295,8 @@ async function auditFiles(repoPath, files, opts = {}) {
254
295
  }
255
296
  // 动态权重分母(维度可作用文件数,见 computeDimFileCounts)——在所有规则过滤完成后统计
256
297
  const dimFileCounts = computeDimFileCounts(grouped, normFiles);
298
+ // 维度检测能力(生效规则集口径):评分层据此对零绑定维度记 0 权重
299
+ const dimRuleCounts = computeDimRuleCounts(grouped);
257
300
  const findings = [];
258
301
  if (opts.truncated) {
259
302
  findings.push(makeFinding({
@@ -271,13 +314,18 @@ async function auditFiles(repoPath, files, opts = {}) {
271
314
  const repoLevelRules = repoLevelSemanticRuleIds(grouped);
272
315
  const repoLevelAnchor = pickRepoLevelAnchorFile(normFiles);
273
316
  const fileTexts = []; // 跨文件重复检测用(全部代码文件文本)
317
+ // 语法树使用状态统计(方向 E3 防再哑门禁):随审计结果一起返回,
318
+ // 让「规则声明要吃树、却没吃到树」不再静默——parse-failed/no-grammar 数量在报告里可见。
319
+ const treeUsage = { parsed: 0, notNeeded: 0, noGrammar: 0, parseFailed: 0, byState: null };
320
+ const STATE_KEY = { parsed: 'parsed', 'not-needed': 'notNeeded', 'no-grammar': 'noGrammar', 'parse-failed': 'parseFailed' };
274
321
  for (const f of normFiles) {
275
322
  const text = readText(f.full);
276
323
  fileTexts.push({ path: f.path, text });
277
324
  const skipRepoLevel = repoLevelRules.size > 0 && f.path !== repoLevelAnchor;
278
325
  // tree-sitter 预解析(异步):有语法 + 本文件规则集确实要 astConfirmSpan 才解析;
279
326
  // 拿不到语法树 ⇒ treeConfirm 为 null ⇒ 检查器回退 token 级判定 ✓
280
- const treeConfirm = await buildTreeConfirmer(f.path, text, grouped);
327
+ const { confirm: treeConfirm, state: treeState } = await buildTreeConfirmer(f.path, text, grouped);
328
+ treeUsage[STATE_KEY[treeState] || 'parsed'] = (treeUsage[STATE_KEY[treeState] || 'parsed'] || 0) + 1;
281
329
  findings.push(...auditFile({ file: f.path, relPath: f.path, text, grouped }, {
282
330
  level: opts.auditLevel, repoHasJsYamlImport, repoPath,
283
331
  repoLevelRules: skipRepoLevel ? repoLevelRules : null,
@@ -345,6 +393,22 @@ async function auditFiles(repoPath, files, opts = {}) {
345
393
  try {
346
394
  findings.push(...(await runAuditExt(repoPath, { dir: opts.auditExtDir, log: opts.log })));
347
395
  } catch (e) { log?.warn?.(`审计扩展执行失败:${e?.message || e}`); }
396
+ // 外部 linter 委托层(方向 A):被审项目自带官方 linter(如 ruff——配置存在且 tools/·PATH 有可执行)时,
397
+ // 委托其 JSON 输出并入 findings。两条硬约束:①**只进评分与报告、绝不进拦截**(severity 恒封顶 warning,
398
+ // 见 lib/lint-adapter/runner.js,别人的规则集不裁决本仓能否提交);②探不到/跑不动/超时/坏输出**一律降级空**
399
+ // (D5,交回自研规则)。仅 full 范围委托:外部 linter 是全仓扫描器,diff 语义不符且拖慢提交门禁(与 analysisCoverage 同口径)。
400
+ // 必须放在 normalizeExemptHints 之前——外部 finding 同样要过豁免提示可信化。
401
+ // ⚠️ `opts.linters` 是**测试注入口**(可指定任意可执行路径),**不得接进 API/CLI**:
402
+ // lib/app/tool-call.js 的 buildAuditOpts 是字段白名单,外部 args 到不了这里;
403
+ // 一旦把它接进去,等于开「让审计引擎执行调用方指定二进制」的后门,改动时务必保持这条路封闭。
404
+ let linted = [];
405
+ if ((opts.scope || 'full') === 'full' && opts.lintAdapters !== false) {
406
+ try {
407
+ const la = await runLintAdapters(repoPath, { linters: opts.linters, log: opts.log });
408
+ findings.push(...la.findings);
409
+ linted = la.linted;
410
+ } catch (e) { log?.warn?.(`外部 linter 委托失败:${e?.message || e}`); }
411
+ }
348
412
  // 豁免提示可信化(2026-10-17)—— **必须放在所有 finding 追加完之后**:
349
413
  // 此前放在文件循环附近,后面还有 tree-doc/func-doc/split-docs/ignore/ext 五处追加 ⇒
350
414
  // 那些 finding 绕过校正,自证里仍能看到「提示 dsh-skip-quality 却没有标记能豁免」✗。
@@ -370,7 +434,30 @@ async function auditFiles(repoPath, files, opts = {}) {
370
434
  ok: true, scope: opts.scope || 'full', repo: repoPath, findings, summary: summarize(findings), slotStats, files: normFiles.length,
371
435
  docsScore,
372
436
  dimFileCounts,
437
+ dimRuleCounts,
438
+ // 外部 linter 委托状态(方向 A 防静默空转):本次委托了哪些 linter、各产出多少、降级原因。
439
+ // 项目自带 ruff 却长期 linted=[] ⇒ 报告里看得见(与 treeUsage 同一思路:用没用上外部权威源不靠猜)。
440
+ linted,
373
441
  analysisCoverage,
442
+ // 语法树消费状态(E3):needTree=规则声明要吃树的文件数,hasGrammar=其中有语法映射的,
443
+ // parsed=真建树数。parseFailed>0 或 coverage<1 ⇒ 语法资产/预算问题导致静默回退,报告里看得见。
444
+ treeUsage: (() => {
445
+ // needTree=规则声明要吃树的文件数;hasGrammar=其中语言有语法映射的;
446
+ // parseFailed=**有语法却没建出树**(资产缺失/超预算/语法错误)——防再哑核心指标。
447
+ // coverage=hasGrammar 里真建树比例;语法资产完好时应恒为 1。
448
+ const needTree = treeUsage.parsed + treeUsage.noGrammar + treeUsage.parseFailed;
449
+ const hasGrammar = treeUsage.parsed + treeUsage.parseFailed;
450
+ return {
451
+ needTree,
452
+ hasGrammar,
453
+ parsed: treeUsage.parsed,
454
+ tokenFallback: treeUsage.noGrammar + treeUsage.parseFailed,
455
+ noGrammar: treeUsage.noGrammar,
456
+ parseFailed: treeUsage.parseFailed,
457
+ notNeeded: treeUsage.notNeeded,
458
+ coverage: hasGrammar > 0 ? treeUsage.parsed / hasGrammar : null,
459
+ };
460
+ })(),
374
461
  // 层级聚合 YAML(summary → 拦截级别 → 目录 → 文件 → 规则明细)
375
462
  yaml: findingsToYaml(findings),
376
463
  };
@@ -0,0 +1,110 @@
1
+ /**
2
+ * 拼接产物作用域契约的**读取层**(中立模块:工具/独立脚本/审计检查三方共用一份判定)。
3
+ *
4
+ * 为什么单独成模块:同一件事有三个入口(`scope_check` 工具、`scripts/check-js-scope.mjs`、
5
+ * 审计规则 kind=scope-collision),「按文件所属项目取契约」的判定一旦各写一份就会漂移。
6
+ * 放在 lib/app/ 会被 lib/checks/ 反向依赖(现有链路是 app → audit → checks,
7
+ * checks → app 会成环);与 lib/audit/client-entry.js 同款处理:共用逻辑下沉中立模块,
8
+ * 依赖方向保持单向(checks → audit/scope-policy 是叶子模块,无回指)。
9
+ *
10
+ * 核心约定:`dshgp_` 前缀与「顶层零声明」都是**各项目自己的契约**,不是通用规范。
11
+ * 拿本项目的约定去要求别人的文件,会刷出一屏「缺少 dshgp_ 前缀」,把真正的同帧重名淹掉。
12
+ * ① 调用方显式给定 prefix/allowlist → 以显式值为准(调用方明确要求);
13
+ * ② 否则从文件所在目录向上找最近的 package.json,读其 `dshScopeCheck`;
14
+ * ③ 都没有 → 前缀留空、不要求顶层零声明,**只查同帧重名**(唯一通用项)。
15
+ */
16
+
17
+ import { existsSync, readFileSync } from 'node:fs';
18
+ import { dirname, join, relative, resolve } from 'node:path';
19
+
20
+ /** 策略来源(输出头自证:避免「继承了本仓默认值」被误读成对方的约定)。 */
21
+ export const POLICY_SOURCE = {
22
+ CLI: '命令行',
23
+ PROJECT: '项目 package.json',
24
+ BUILTIN: '内置默认(只查同帧重名)',
25
+ };
26
+
27
+ /** 路径归一化:去掉前导 `./`、反斜杠统一成 `/`(声明值与相对路径两边都用它比)。 */
28
+ function normRelPath(value) {
29
+ return String(value || '').replace(/\\/g, '/').replace(/^\.\//, '');
30
+ }
31
+
32
+ /**
33
+ * 目录 → 最近的 package.json 路径缓存('' = 一路到根都没有)。
34
+ *
35
+ * 为什么需要:审计逐文件调用本模块,全仓 400+ 个 js 就要做 400+ 次「向上找 package.json」;
36
+ * 在 CIFS/HFS 挂载上 stat 单次约 2.8ms,实测这一项 1.2s(占比虽小但纯浪费)。
37
+ * TTL 取 1s:一次审计内连续调用几乎全命中,而两次审计之间(≥1s)必然重新读,
38
+ * 不会把「刚改了 dshScopeCheck 又立刻审计」读成旧值。
39
+ */
40
+ const DIR_LOOKUP_TTL_MS = 1000;
41
+ const dirLookupCache = new Map(); // dir → { at, configPath }
42
+
43
+ /** 向上找最近的 package.json(带 1s 缓存)。 */
44
+ function findConfigPath(startDir, now) {
45
+ const cached = dirLookupCache.get(startDir);
46
+ if (cached && now - cached.at < DIR_LOOKUP_TTL_MS) return cached.configPath;
47
+ let found = '';
48
+ let dir = startDir;
49
+ for (;;) {
50
+ const candidate = join(dir, 'package.json');
51
+ if (existsSync(candidate)) { found = candidate; break; }
52
+ const parent = dirname(dir);
53
+ if (parent === dir) break; // 到根了还没找到 ⇒ 无声明
54
+ dir = parent;
55
+ }
56
+ dirLookupCache.set(startDir, { at: now, configPath: found });
57
+ return found;
58
+ }
59
+
60
+ /**
61
+ * 读某个文件所属项目的作用域契约。
62
+ *
63
+ * @param {string} file 目标文件路径(绝对路径最稳;相对路径按进程 cwd 解析)
64
+ * @returns {{
65
+ * declared: boolean, 是否找到了显式声明(决定「契约类检查」跑不跑)
66
+ * isDeclaredArtifact: boolean, 当前文件是否在该项目声明的 files 清单里
67
+ * prefix: string, allowlist: string[], topLevelMustBeEmpty: boolean,
68
+ * files: string[], configPath: string, relFromConfig: string, source: string
69
+ * }}
70
+ * `isDeclaredArtifact` 必须为 true 才允许套用 prefix / 顶层零声明:`files` 清单就是
71
+ * 「哪些文件是拼接产物」的声明——不在清单里的文件(如分片源码)套用前缀会把
72
+ * 片段里的局部变量全部误判成缺前缀。
73
+ */
74
+ export function readProjectScopePolicy(file = '') {
75
+ const target = resolve(file);
76
+ const builtin = {
77
+ declared: false,
78
+ isDeclaredArtifact: false,
79
+ prefix: '',
80
+ allowlist: [],
81
+ topLevelMustBeEmpty: false,
82
+ files: [],
83
+ configPath: '',
84
+ relFromConfig: '',
85
+ source: POLICY_SOURCE.BUILTIN,
86
+ };
87
+ const configPath = findConfigPath(dirname(target), Date.now());
88
+ if (!configPath) return builtin; // 一路到根都没有 package.json ⇒ 按「无声明」处理
89
+ let own;
90
+ try {
91
+ own = JSON.parse(readFileSync(configPath, 'utf8'))?.dshScopeCheck;
92
+ } catch {
93
+ return builtin; // package.json 损坏 → 按「无声明」处理,不抛给调用方
94
+ }
95
+ if (!own || typeof own !== 'object') return builtin; // 找到所属项目但没声明 ⇒ 不套别人的规范
96
+ const files = Array.isArray(own.files) ? own.files.map(String) : [];
97
+ const configDir = dirname(configPath);
98
+ const relFromConfig = normRelPath(relative(configDir, target));
99
+ return {
100
+ declared: true,
101
+ isDeclaredArtifact: files.some((rel) => normRelPath(rel) === relFromConfig),
102
+ prefix: String(own.prefix || ''),
103
+ allowlist: Array.isArray(own.allowlist) ? own.allowlist.map(String) : [],
104
+ topLevelMustBeEmpty: own.topLevelMustBeEmpty === true,
105
+ files,
106
+ configPath,
107
+ relFromConfig,
108
+ source: POLICY_SOURCE.PROJECT,
109
+ };
110
+ }
@@ -159,4 +159,19 @@ rules:
159
159
  patterns:
160
160
  - "\\b(addRoute|addHandler|registerRoute|useRoute)\\s*\\|\\|"
161
161
  fixable: true
162
- mitigation: "按官方真实 API 写(webServer.register({ kind:'prefix', path, handler }));接线失败必须 return false 并告警,不得静默吞掉"
162
+ mitigation: "按官方真实 API 写(webServer.register({ kind:'prefix', path, handler }));接线失败必须 return false 并告警,不得静默吞掉"
163
+ # ── ⑦ 分片拼接作用域(多段 JS 拼成单文件产物时 var/function 同名静默覆盖)──
164
+ # 为什么不用 patterns:这是**跨声明**的语义判定(同名次数 + 真实作用域帧),
165
+ # 单行正则做不到;由 kind=scope-collision 的编译器 + lib/ast/scope-collisions.js 执行。
166
+ # 契约来源:前缀 / 顶层零声明 / 产物文件清单一律取自**被审项目自己**的 package.json
167
+ # (dshScopeCheck,读在 lib/audit/scope-policy.js)——规则包跨仓库共享,
168
+ # 把 dshgp_ 写在这里会让所有被审项目都收到「缺少 dshgp_ 前缀」这类无关告警。
169
+ - id: dsh/scope-collision
170
+ kind: "scope-collision"
171
+ name: "分片拼接作用域撞名(var/function 静默覆盖)"
172
+ category: "structure"
173
+ severity: "error"
174
+ description: "多段 JS 拼进同一作用域(分片拼 factory / 多个 <script> 引入 / cat a.js b.js > bundle.js)时,同一函数帧内 function/const/let/class 同名会让后者顶掉前者或让整份产物 SyntaxError,且运行期可能毫无报错线索;判定按真实作用域帧,两个不同函数里的同名局部变量不算撞名。顶层声明与裸名在拼接场景还会与其它脚本撞名(该两项只有项目自己在 package.json 声明 dshScopeCheck 时才查)。"
175
+ exts: ["js", "mjs", "cjs"]
176
+ fixable: false
177
+ mitigation: "① 同帧重名必须改名(function/const/let/class 是真缺陷,纯 var 重复至少应合并);② 拼接产物保持文件顶层零声明;③ 共享作用域内的声明加项目约定的前缀,并把该约定写进项目 package.json 的 dshScopeCheck(files/prefix/allowlist/topLevelMustBeEmpty)"
@@ -63,7 +63,14 @@ rules:
63
63
  category: "readability"
64
64
  severity: "warning"
65
65
  description: "函数名 ≤2 字符是缩写(如 gU),无法从名字猜出含义"
66
- pattern: "\\bfunction\\s+[a-zA-Z_$][a-zA-Z0-9_$]{0,1}\\s*\\("
66
+ patterns:
67
+ - "\\bfunction\\s+[a-zA-Z_$][a-zA-Z0-9_$]{0,1}\\s*\\("
68
+ # 方法定义行(class A { gh() {} } / const o = { ef() {} })不含 function 关键字,
69
+ # 第一条 pattern 结构上不可能命中它们 ⇒ 候选行都进不来,树化后照样漏报(实测踩过:
70
+ # allow 精筛前必须先过初筛)。这里只做**粗筛**(行首短标识符 + 左括号),
71
+ # 是否真是「定义」由 short-func-name 精筛(语法树 method_definition 节点)判定——
72
+ # 因此 ` ab(1);` 这类调用行虽进候选,也不会被报。
73
+ - "^\\s*[a-zA-Z_$][a-zA-Z0-9_$]{0,1}\\s*\\("
67
74
  # 2026-09-13 误报修复(正则初筛 → AST 精筛):i18n 领域标准缩写(tr/t/L 等翻译、
68
75
  # 字典函数名)长度 ≤2 但含义公认,纯正则命中即报会把它们当「无法猜出含义」报掉。
69
76
  # astConfirmKind: short-func-name → token 级判定(checkShortFunctionNameAst):
@@ -348,12 +355,20 @@ rules:
348
355
  # · 引号内内容收紧为 `[^'"\s]{8,}`——真实凭据较长,短占位/空串不参与初筛
349
356
  # (AST 精筛仍按 isMeaningfulCredentialValue 判占位符,双层不矛盾)。
350
357
  astConfirmKind: credential-value
358
+ # 初筛在 `=`/`:` 与引号之间允许 ≤2 字符的**字符串前缀**(Python b"…"/rb'…'、f"…"):
359
+ # 原写法 `=\s*['\"]` 在 `SECRET_KEY = b"…"` 上因夹着 b 直接断链,bytes 真凭据
360
+ # 连候选行都进不来(外部仓库实测漏报)。放宽只影响初筛覆盖面,是否真报仍由
361
+ # credential-value 精筛(树/ token)判语义与值形状决定,不会新增误报形态。
362
+ # 凭据词后允许词尾段(`(?![A-Za-z])\\w*`):`SECRET_KEY =` / `API_KEY_ID =` 这类
363
+ # 下划线复合标识符此前因「凭据词后不直接接等号」而漏出候选(外部仓库实测
364
+ # APP_UPDATE_TOKEN_SECRET = b"…" 整行不报);`(?![A-Za-z])` 保证 tokenizer /
365
+ # cookieMonster 这类「凭据词只是单词前缀」的情况仍不进候选。
351
366
  patterns:
352
- - "(?<![?&/])password\\s*[=:]+\\s*['\"][^'\"\\s]{8,}['\"]"
353
- - "(?<![?&/])secret\\s*[=:]+\\s*['\"][^'\"\\s]{8,}['\"]"
354
- - "(?<![?&/])api[_-]?key\\s*[=:]+\\s*['\"][^'\"\\s]{8,}['\"]"
355
- - "(?<![?&/])token\\s*[=:]+\\s*['\"][^'\"\\s]{8,}['\"]"
356
- - "(?<![?&/])cookie\\s*[=:]+\\s*['\"][^'\"\\s]{8,}['\"]"
367
+ - "(?<![?&/])password(?![A-Za-z])\\w*\\s*[=:]+\\s*[a-zA-Z]{0,2}\\s*['\"][^'\"\\s]{8,}['\"]"
368
+ - "(?<![?&/])secret(?![A-Za-z])\\w*\\s*[=:]+\\s*[a-zA-Z]{0,2}\\s*['\"][^'\"\\s]{8,}['\"]"
369
+ - "(?<![?&/])api[_-]?key(?![A-Za-z])\\w*\\s*[=:]+\\s*[a-zA-Z]{0,2}\\s*['\"][^'\"\\s]{8,}['\"]"
370
+ - "(?<![?&/])token(?![A-Za-z])\\w*\\s*[=:]+\\s*[a-zA-Z]{0,2}\\s*['\"][^'\"\\s]{8,}['\"]"
371
+ - "(?<![?&/])cookie(?![A-Za-z])\\w*\\s*[=:]+\\s*[a-zA-Z]{0,2}\\s*['\"][^'\"\\s]{8,}['\"]"
357
372
  # 2026-09-13 误报修复:正则把「凭据字段引用/API 名/字符串字面量」误判为「凭据值硬编码」。
358
373
  # 白名单行豁免——命中以下任一模子的行不报:
359
374
  # · GM_cookie(油猴 GM_cookie API 名,非硬编码值)
@@ -102,8 +102,8 @@ export function consoleLogJsonLines(text) {
102
102
  * @param {string} text 文件全文
103
103
  * @returns {Set<number>} 允许报的行号集合
104
104
  */
105
- export function shortFuncNameLines(text) {
106
- return new Set(checkShortFunctionNameAst(String(text || '')).map((h) => h.line));
105
+ export function shortFuncNameLines(text, tree) {
106
+ return new Set(checkShortFunctionNameAst(String(text || ''), { tree: tree || null }).map((h) => h.line));
107
107
  }
108
108
 
109
109
  /**
@@ -119,8 +119,8 @@ export function placeholderCredentialLines(text, file) {
119
119
  return checkPlaceholderCredentialAst(text, file);
120
120
  }
121
121
 
122
- export function credentialValueLines(text) {
123
- return checkCredentialRefAst(String(text || ''));
122
+ export function credentialValueLines(text, tree) {
123
+ return checkCredentialRefAst(String(text || ''), tree);
124
124
  }
125
125
 
126
126
  /**
@@ -24,6 +24,7 @@ import { checkPrivateFiles } from './private.js';
24
24
  import { checkButtonBindings } from './button-bind.js';
25
25
  import { checkMagicNumberSmart } from './magic-number.js';
26
26
  import { checkDataflow } from './dataflow.js';
27
+ import { checkScopeCollision } from './scope-collision.js';
27
28
  import { checkFileHealth } from './file-health.js';
28
29
  import { filterRulesByExt, filterRulesByPath, filterRulesByFileText } from './filter.js';
29
30
  import { resolveDshClientEntries, resolveDshClientFragments } from '../audit/client-entry.js';
@@ -103,6 +104,10 @@ export function runChecks({ file, relPath, text, grouped }, opts = {}) {
103
104
  // 三层审计 L2——数据流检查(kind=dataflow,如 clear-then-access 同函数清空后访问)
104
105
  // L1 已在 filterRulesByFileText 初筛:file_patterns 未命中的文件这里 grouped 已空,空规则短路
105
106
  if (!quick && grouped['dataflow']) findings = findings.concat(checkDataflow({ file, text, rules: grouped['dataflow'] }));
107
+ // 拼接产物作用域撞名(多段 JS 拼进同一作用域):判定在 lib/ast/scope-collisions.js,
108
+ // 契约由被审项目自己的 package.json 决定(lib/audit/scope-policy.js)——
109
+ // 规则 yml 跨仓库共享,故 yml 只声明「查不查」,不写任何项目的前缀约定。
110
+ if (!quick && grouped['scope-collision']) findings = findings.concat(checkScopeCollision({ file, text, rules: grouped['scope-collision'] }));
106
111
  findings = findings.concat(checkEmptyCatch({ file, text }));
107
112
  // I/O 风险分级 —— 经「正则初筛 → AST 精筛」产出(robustness/io-risk
108
113
  // 规则 + astConfirmKind: io-risk),不在此独立调用检查器:两条路径会为同一处 I/O
@@ -14,6 +14,7 @@
14
14
  * regex.js 正则类规则(含 astConfirm 精筛消费)
15
15
  * structural.js 结构类(函数长度/复杂度/嵌套/文件行数/同步 fs/空 catch)
16
16
  * semantic.js 语义类(yml 声明的语义检查、patch insert)
17
+ * scope-collision.js 拼接产物作用域撞名(多段 JS 共用同一作用域)
17
18
  * npm-json.js package.json 规范
18
19
  * folder.js 目录级检查
19
20
  * credential-file.js 凭据文件
@@ -42,6 +43,7 @@ export { checkButtonBindings } from './button-bind.js';
42
43
  export { checkMagicNumberSmart } from './magic-number.js';
43
44
  export { checkFileHealth } from './file-health.js';
44
45
  export { checkDataflow } from './dataflow.js';
46
+ export { checkScopeCollision } from './scope-collision.js';
45
47
  export { checkDuplicateCode } from './dup-code.js';
46
48
  export { checkMultiFileScanners } from './fs-scanner.js';
47
49
  export { checkDuplicateConst, findConstDefs } from './dup-const.js';
@@ -109,8 +109,8 @@ export function checkRegexRules({ file, text, rules, source = '新增行', repoP
109
109
  if (rule.astConfirmKind === 'small-file-read') kindFilter = { mode: 'deny', lines: smallFileReadLines(text) };
110
110
  // CLI console.log(JSON.stringify(大对象)) 一次性输出行豁免(memory-bomb json-stringify-large)
111
111
  else if (rule.astConfirmKind === 'console-log-json') kindFilter = { mode: 'deny', lines: consoleLogJsonLines(text) };
112
- else if (rule.astConfirmKind === 'short-func-name') kindFilter = { mode: 'allow', lines: shortFuncNameLines(text) };
113
- else if (rule.astConfirmKind === 'credential-value') kindFilter = { mode: 'allow', lines: credentialValueLines(text) };
112
+ else if (rule.astConfirmKind === 'short-func-name') kindFilter = { mode: 'allow', lines: shortFuncNameLines(text, treeConfirm?.tree || null) };
113
+ else if (rule.astConfirmKind === 'credential-value') kindFilter = { mode: 'allow', lines: credentialValueLines(text, treeConfirm?.tree || null) };
114
114
  // 前缀型密钥串(ghp_/sk-/AKIA)的占位符精筛:命中行是「演示值/占位文案」时豁免
115
115
  else if (rule.astConfirmKind === 'placeholder-credential') kindFilter = { mode: 'deny', lines: placeholderCredentialLines(text, file) };
116
116
  // shell 健壮性精筛(folder/cd-to-maybe-missing:cd 到动态路径且无兜底)
@@ -0,0 +1,68 @@
1
+ /**
2
+ * 检查层 · 拼接产物作用域撞名(kind = scope-collision)
3
+ *
4
+ * 判定在 `lib/ast/scope-collisions.js`(token 级、按真实作用域帧),契约在
5
+ * `lib/audit/scope-policy.js`(按**被审项目自己**的 package.json 取)。
6
+ *
7
+ * 两类命中,严重度口径**故意不同**:
8
+ * ① 同帧重名(任何 js 文件都查)——分两档,避免把合法写法拦成 blocker:
9
+ * · 两次都是 var:同一声明的重复写入(后一次等价赋值),运行时无害 → warning;
10
+ * · 含 function / class / const / let:后声明真的顶掉前者,或拼接后整份产物
11
+ * 直接 SyntaxError → 跟随规则声明(yml `severity: error` ⇒ blocker 拦截提交)。
12
+ * ② 前缀 / 顶层零声明(**只对项目自己声明的产物文件**生效)——契约类问题,
13
+ * 一律 capSeverity 到 warning:绝不因为别人的风格约定拦下提交。
14
+ *
15
+ * 为什么契约必须以「项目自己声明」为准:规则包是**跨仓库共享**的(同一份 yml 审计所有仓库)。
16
+ * 把 dshgp_ 写进 yml,会给所有被审项目刷出「缺少 dshgp_ 前缀」,
17
+ * 把真正的同帧重名淹掉。项目没声明 dshScopeCheck ⇒ 这里只做通用项(同帧重名)。
18
+ *
19
+ * 豁免:空 rules 短路(规则被 exts/exclude_paths/file_patterns 过滤空时,
20
+ * 防止读 rule.severity 抛错——与 structural.js 各检查器同款守卫)。
21
+ */
22
+
23
+ import { makeFinding } from '../audit/index.js';
24
+ import { readProjectScopePolicy } from '../audit/scope-policy.js';
25
+ import { analyzeScopeCollisions } from '../ast/index.js';
26
+ import { HINT_QUALITY, capSeverity } from './common.js';
27
+
28
+ /**
29
+ * @param {object} ctx { file(绝对路径), relPath, text, rules }
30
+ * @returns {Array} findings
31
+ */
32
+ export function checkScopeCollision({ file, text, rules }) {
33
+ const findings = [];
34
+ const rule = (rules || [])[0];
35
+ if (!rule) return findings;
36
+
37
+ const project = readProjectScopePolicy(file);
38
+ // 全仓扫描口径:必须严格命中项目声明的 files 清单,不能「没清单就都算产物」
39
+ const enforceContract = project.declared && project.isDeclaredArtifact;
40
+ const result = analyzeScopeCollisions(String(text || ''), {
41
+ prefix: enforceContract ? project.prefix : '',
42
+ allowlist: enforceContract ? project.allowlist : [],
43
+ topLevelMustBeEmpty: enforceContract ? project.topLevelMustBeEmpty : false,
44
+ });
45
+
46
+ const ruleId = rule.id || 'dsh/scope-collision';
47
+ const dimensions = rule.dimensions || ['健壮性'];
48
+ const base = { file, rule: ruleId, kind: 'scope-collision', dimensions, exemptHint: HINT_QUALITY, scoreImpact: 1 };
49
+ // 契约类(前缀 / 顶层零声明)与「纯 var 重声明」最高只到 warning
50
+ const softSeverity = capSeverity(rule.severity || 'warning', 'warning');
51
+ // ① 同帧重名:严重度按**命中性质**分档,避免把合法写法拦成 blocker
52
+ // · 两次都是 var ⇒ 同一声明的重复写入(后一次等价赋值),运行时无害 → warning
53
+ // · 含 function / class / const / let ⇒ 后声明真的顶掉前者,或拼接后整份产物
54
+ // 直接 SyntaxError(命名冲突)→ 按规则声明的严重度(error ⇒ blocker)
55
+ const hardSeverity = rule.level === 'blocker' ? 'blocker' : capSeverity(rule.severity || 'warning', 'warning');
56
+ for (const hit of result.duplicates) {
57
+ const varOnly = Array.isArray(hit.keywords) && hit.keywords.every((kw) => kw === 'var');
58
+ findings.push(makeFinding({ ...base, line: hit.line, severity: varOnly ? softSeverity : hardSeverity, message: hit.message }));
59
+ }
60
+ // ② 契约类(项目自选):恒为 warning
61
+ for (const hit of result.topLevel) {
62
+ findings.push(makeFinding({ ...base, line: hit.line, severity: softSeverity, message: hit.message }));
63
+ }
64
+ for (const hit of result.missingPrefix) {
65
+ findings.push(makeFinding({ ...base, line: hit.line, severity: softSeverity, message: hit.message }));
66
+ }
67
+ return findings;
68
+ }
@@ -101,7 +101,7 @@ async function runStandardAudit(root, flags) {
101
101
  opts.ownership = probeRepoOwnership(root); // 与插件工具同参:隐私规则只对自有仓库生效
102
102
  const weights = pluginEqualWeights(cfg, flags);
103
103
  const auditResult = full ? await auditFull(root, opts) : await auditWithScope(root, opts);
104
- const quality = scoreQuality(auditResult.findings, weights, { files: auditResult.files, dimFileCounts: auditResult.dimFileCounts });
104
+ const quality = scoreQuality(auditResult.findings, weights, { files: auditResult.files, dimFileCounts: auditResult.dimFileCounts, dimRuleCounts: auditResult.dimRuleCounts });
105
105
  if (flags.json) {
106
106
  console.log(JSON.stringify({ ok: true, repo: root, scope: auditResult.scope, summary: auditResult.summary, quality, findings: auditResult.findings, files: auditResult.files, analysisCoverage: auditResult.analysisCoverage || null, yaml: auditResult.yaml }, null, 2));
107
107
  return;
@@ -54,7 +54,12 @@ export async function runAudit({ repoPath = '', audit, rulesetDir, slots, cfg: e
54
54
  if (typeof cfg.weightOverrides === 'string' && cfg.weightOverrides.trim()) {
55
55
  try { auditWeights = JSON.parse(cfg.weightOverrides) || {}; } catch { /* 非法 JSON 回退默认 */ }
56
56
  }
57
- const auditOut = { summary: auditRes.summary, quality: scoreQuality(auditRes.findings, auditWeights, { files: auditRes.files }) };
57
+ const auditOut = {
58
+ summary: auditRes.summary,
59
+ quality: scoreQuality(auditRes.findings, auditWeights, {
60
+ files: auditRes.files, dimFileCounts: auditRes.dimFileCounts, dimRuleCounts: auditRes.dimRuleCounts,
61
+ }),
62
+ };
58
63
  // 审计输出改为「级别数量 + 评分 + API 查询用法」——审计明细由聚合 API
59
64
  // (/api/git-push/audit)查询,不再内联 findings 全文;blocked 摘要保留(拦截必需)。
60
65
  auditOut.apiGuide = buildAuditApiGuide(repoPath, { scope: auditRes.scope, summary: auditRes.summary, quality: auditOut.quality });
@@ -80,13 +80,16 @@ export const EXEMPT_MARKERS = {
80
80
  // ⇒ 用户按提示写文件头标记**完全不生效**,且找不到别的标记可用(同一类「提示写了
81
81
  // 不生效」缺陷)。按钮绑定判定是启发式的(事件委托/封装函数/原生 label 触发都可能
82
82
  // 合法),必须留一条可豁免路径。
83
+ // 2026-11-05 补齐:scope-collision(拼接产物作用域撞名)此前同样不在任何标记的 blocked 里。
84
+ // 前缀/顶层零声明这类**项目自选契约定**若不可豁免,接入方只能改 yml 或关槽位;
85
+ // 而同帧重名属真缺陷,豁免时用文件头标记显式承担即可(与其它质量类一致)。
83
86
  blocked: ['func-lines', 'empty-catch', 'sync-fs', 'magic-number-smart', 'blacklist',
84
- 'comment-density', 'file-health', 'button-bind',
87
+ 'comment-density', 'file-health', 'button-bind', 'scope-collision',
85
88
  'semantic', 'dataflow', 'duplicate-const', 'repeated-string', 'regex'],
86
89
  // regex 兜底时**排除**安全类规则名(这些必须走 dsh-skip-sensitive,不能靠质量标记吞掉)
87
90
  excludeRules: ['security', 'credential', 'credref', 'credfile', 'secret', 'password', 'hardcoded'],
88
91
  lineLevel: false,
89
- hint: '文件头=整文件免质量评分(func-lines/empty-catch/sync-fs/magic-number-smart/blacklist 措辞/comment-density/file-health/button-bind 按钮绑定)',
92
+ hint: '文件头=整文件免质量评分(func-lines/empty-catch/sync-fs/magic-number-smart/blacklist 措辞/comment-density/file-health/button-bind 按钮绑定/scope-collision 作用域撞名)',
90
93
  },
91
94
  'dsh-skip-residue': {
92
95
  dimensions: ['可读性', '可维护性'],
package/lib/git/ignore.js CHANGED
@@ -18,7 +18,7 @@ export const DEFAULT_IGNORE_PATTERNS = ['node_modules/', 'node_modules.orig/'];
18
18
 
19
19
  /**
20
20
  * 把基线忽略项 + 自定义忽略追加进 .gitignore(幂等:已存在行不重复写)。
21
- * 敏感文件扫描只报告(files),不写入 .gitignore、不解除跟踪(用户指令)。
21
+ * 敏感文件扫描只报告(files),不写入 .gitignore、不解除跟踪。
22
22
  * @param {string} repoPath 仓库根
23
23
  * @param {{customIgnorePatterns?: string|string[]}} [opts]
24
24
  * customIgnorePatterns:逗号/换行分隔的 gitignore pattern 或字符串数组(用户自定义忽略)
@@ -26,8 +26,10 @@ export const DEFAULT_IGNORE_PATTERNS = ['node_modules/', 'node_modules.orig/'];
26
26
  * added 追加总行数 / files 敏感文件路径(只报告)/ baseline 基线补入数 / custom 自定义补入数 /
27
27
  * tracked 恒空(不再解除跟踪)/ unstaged 恒空
28
28
  */
29
- export async function ensureGitignore(repoPath, { customIgnorePatterns = '' } = {}) {
30
- const files = await scanSensitiveFiles(repoPath);
29
+ export async function ensureGitignore(repoPath, { customIgnorePatterns = '', onlyPaths = null, scanSensitive = true } = {}) {
30
+ // onlyPaths:只扫本次将提交的文件(提交路径传入;缺省=全仓,兼容其它调用方)
31
+ // scanSensitive:与审计同一开关——审计关闭时不扫(不再是无条件的特权步骤)
32
+ const files = scanSensitive ? await scanSensitiveFiles(repoPath, { onlyPaths }) : [];
31
33
  const giPath = join(repoPath, '.gitignore');
32
34
  let existing = '';
33
35
  try { existing = existsSync(giPath) ? readFileSync(giPath, 'utf8') : ''; } catch { /* 忽略 */ }
@@ -46,7 +48,7 @@ export async function ensureGitignore(repoPath, { customIgnorePatterns = '' } =
46
48
  added++;
47
49
  }
48
50
  // 2) 扫描出的敏感文件(内容级 + 文件名黑名单)——只报告不动作:不动 .gitignore、不解除跟踪
49
- //(用户指令:扫描到敏感文件不改动 git 忽略配置,由仓库方自行决定处理)
51
+ //(扫描到敏感文件不改动 git 忽略配置,由仓库方自行决定处理)
50
52
  for (const hit of files) {
51
53
  const rel = hit.path;
52
54
  if (isSampleExemptDir(repoPath, rel)) { sampleExempted++; continue; }