dsh-git-push 2.13.4 → 2.14.1

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.
package/.auditignore CHANGED
@@ -7,8 +7,10 @@
7
7
 
8
8
  # 评分参数表:DEFAULT_WEIGHTS / DIMENSION_K 的数字是「维度名 → 参数」映射值,
9
9
  # 键名已表意,拆成 WEIGHT_X = 15 这类常量反而割裂表格、降低可读性;
10
- # 权重另由侧边栏配置项可调,不是散落魔数。故整文件豁免质量类规则。
11
- lib/score/index.js
10
+ # 权重另由侧边栏配置项可调,不是散落魔数。
11
+ # 2026-11-01 起改用**细粒度豁免**(路径 : 规则):只免魔数与冗长函数这两类
12
+ # 「表格本身固有」的命中,其余规则照常审——整文件豁免会让可读性/健壮性问题一起消失。
13
+ lib/score/index.js : readability/magic-number-smart, maintainability/max-function-length # 维度权重参数表,键名已表意
12
14
 
13
15
  # 侧边栏设置 UI(lib/client.js,package.json 的 "./client" 入口):**不再整文件豁免**。
14
16
  # 改为**规则声明降级**:audit-rules-nodejs.yml 的 readability/max-file-length 声明
@@ -29,7 +29,17 @@ const EXEMPT_TYPE_RE = /dsh-skip-([a-z-]+)/; // 无 /g:exec 有 lastIndex 状
29
29
  export function exemptStatsOf(findings = []) {
30
30
  const types = {};
31
31
  let total = 0;
32
+ // 「已确认豁免」(.auditignore 的「路径 : 规则」):与上面的「可选豁免标记」分开统计——
33
+ // 前者是**已经生效**的豁免(不扣分),后者只是「可以写哪个标记」,混在一起会让人误判。
34
+ const applied = {};
35
+ let appliedTotal = 0;
32
36
  for (const f of findings) {
37
+ if (f?.exempted) {
38
+ appliedTotal += 1;
39
+ const key = String(f.rule || '(未知规则)');
40
+ applied[key] = (applied[key] || 0) + 1;
41
+ continue;
42
+ }
33
43
  const hint = String(f?.exemptHint || '');
34
44
  if (!hint) continue;
35
45
  total += 1;
@@ -41,7 +51,7 @@ export function exemptStatsOf(findings = []) {
41
51
  types.other = (types.other || 0) + 1;
42
52
  }
43
53
  }
44
- return { types, total };
54
+ return { types, total, applied, appliedTotal };
45
55
  }
46
56
 
47
57
  /** finding 对象聚合键提取(slot 维度用 ruleSlotMap 把 rule id 归到规则包)。 */
@@ -148,6 +148,12 @@ export function buildAuditApiGuide(repo = '', opts = {}) {
148
148
  L.push(`可选参数(默认已填,按需改 URL 即可):groupBy=${opts.groupBy ? '自定义' : 'rule'}(默认)<可选 rule|file|severity|slot> · severity 过滤(如 &severity=blocker,warning)`);
149
149
  // 审计后提示增加——豁免类型统计 / 聚合类型 / 拦截列表(直接可见,不用查 API)
150
150
  const es = opts.exemptStats;
151
+ // 已确认豁免(.auditignore 的「路径 : 规则」):单列一节,与「未处理问题」明确分开——
152
+ // 这些 finding 不扣分、不计入警告数,但必须可见(否则等于静默消失)。
153
+ if (es && es.appliedTotal > 0) {
154
+ const detail = Object.entries(es.applied || {}).map(([r, n]) => `${r} ${n}`).join(' / ');
155
+ L.push(`已确认豁免 ${es.appliedTotal} 条(.auditignore 细粒度,不扣分):${detail}`);
156
+ }
151
157
  if (es && es.total > 0) {
152
158
  const parts = Object.entries(es.types || {}).map(([t, n]) => `${t} ${n}`).join(' / ');
153
159
  L.push(`豁免:${es.total} 条(${parts})`);
@@ -74,8 +74,13 @@ export function makeCodeSpanFilter(text = '', candidateLines = [], opts = {}) {
74
74
  // 不透明区间只取**单行 token**:跨行 token(三引号/多行块注释)的 col 是续行内位置,
75
75
  // 用它构造区间会算错。跨行场景本就由行级判定覆盖——续行不产 ident/num ⇒ 不算代码行。
76
76
  const opaque = new Map(); // line → [[startCol, endColExclusive), ...]
77
+ // onlyComment:只把**注释**当不透明区间,字符串仍算代码。
78
+ // 为什么需要这一档:paths/凭据类规则的命中本来就写在字符串里(路径字面量),
79
+ // 若把字符串也一并当「非代码」会把这些规则整体废掉(实测 hardcoded-absolute-path 5→0);
80
+ // 而「注释里的示例代码被当真」是纯误报,两者必须分开处理。
81
+ const opaqueTypes = opts.onlyComment ? new Set(['comment']) : new Set(['str', 'tmpl', 'comment']);
77
82
  for (const t of tokenize(text)) {
78
- if (t.type !== 'str' && t.type !== 'tmpl' && t.type !== 'comment') continue;
83
+ if (!opaqueTypes.has(t.type)) continue;
79
84
  const v = String(t.value);
80
85
  if (v.includes('\n')) continue;
81
86
  const col = Number(t.col);
@@ -87,7 +92,11 @@ export function makeCodeSpanFilter(text = '', candidateLines = [], opts = {}) {
87
92
  return {
88
93
  isCode: base.isCode,
89
94
  isCodeHit: (line, col) => {
90
- if (!base.isCode(line)) return false;
95
+ // onlyComment(只判注释)**不走行级判定**:行级判定里编码了「散文体文档只有围栏代码算代码」
96
+ // 的语义,若沿用它,`contact: x@y.com` 这种普通文档行会被判非代码 ⇒ 所有正则规则
97
+ // 在 .md/.txt 上整体失效(实测:隐私规则端到端用例直接转红)。
98
+ // 这里只回答「这一列是否落在注释 token 区间内」,与文件体裁无关。
99
+ if (!opts.onlyComment && !base.isCode(line)) return false;
91
100
  const ranges = opaque.get(line);
92
101
  if (!ranges || !ranges.length) return true;
93
102
  const c = Number(col);
@@ -0,0 +1,148 @@
1
+ /**
2
+ * `.auditignore` 的**细粒度豁免**解析与匹配(文件 : 规则)。
3
+ *
4
+ * 为什么需要这一档:`.auditignore` 原先只有「整文件跳过」一种力度,而实际需求常是
5
+ * 「这个文件的其他规则照审,只免某一类」。典型场景:
6
+ * · 权重/参数表文件(`lib/score/index.js`):数字是「维度名 → 参数」映射值,
7
+ * 键名已表意,拆成常量反而割裂表格 ⇒ 只想免 magic-number,别的照报;
8
+ * · 通用字符串数据表(`plugins/x/lib/common-strings.js`):同理;
9
+ * · 跨文件看门狗:单文件里看不到超时设置(真实设置在宿主侧),静态分析无法识别。
10
+ * 旧做法只能整文件豁免 ⇒ 连带把可读性/健壮性问题一起藏起来,事实消失、不可追溯。
11
+ *
12
+ * 语法(在现有 gitignore 语法之上**追加**一行后缀,旧条目行为完全不变):
13
+ * # 整文件 / 整目录跳过(原有语义)
14
+ * lib/score/index.js
15
+ * .archify/*.html
16
+ *
17
+ * # 细粒度:路径 + " : " + 规则(逗号分隔,支持 slot/* 通配)+ 可选 # 理由
18
+ * lib/score/index.js : readability/magic-number-smart # 权重参数表,键名已表意
19
+ * test/lib/wait-ready.mjs : robustness/*, paths/hardcoded-absolute-path
20
+ *
21
+ * 解析保护(避免与既有写法冲突):冒号后**每一段都必须形如 `slot/rule`**(允许 `*`),
22
+ * 否则整行按文件模式处理。这样 `C:\Users\x`、`https://x/y`、`a:b` 这类既有内容
23
+ * 不会被误判成细粒度规则。
24
+ *
25
+ * 生效方式:细粒度条目不参与「采集阶段跳过」,而是在 finding 产出后**标记**为
26
+ * `exempted: true`(不扣分、不进 warning 计数),并在报告里单列一节列出理由——
27
+ * 既保留可追溯性,也不让「已确认豁免」与「未处理」混在一起。
28
+ */
29
+ import { existsSync, readFileSync } from 'node:fs';
30
+ import { join, relative } from 'node:path';
31
+
32
+ import { isIgnoredByRules, parseGitignore } from './gitignore-match.js';
33
+
34
+ /** 规则段的合法形态:`slot/rule`,允许 `*` 通配(如 `robustness/*`)。 */
35
+ const RULE_SEGMENT_RE = /^[a-z][a-z0-9-]*\/[a-z0-9*][a-z0-9*/-]*$/;
36
+ /** 细粒度分隔符:冒号**两侧各一个空格**。刻意不用裸 `:` —— Windows 盘符与 URL 都含它。 */
37
+ const SEPARATOR = ' : ';
38
+
39
+ /**
40
+ * 把一行拆成「文件模式 + 规则段 + 理由」。
41
+ * @returns {{filePattern:string, rulePatterns:string[], reason:string}|null} 不是细粒度行时返回 null
42
+ */
43
+ export function parseScopedLine(line) {
44
+ const raw = String(line || '');
45
+ if (!raw.trim() || raw.trim().startsWith('#')) return null;
46
+ const at = raw.indexOf(SEPARATOR);
47
+ if (at <= 0) return null;
48
+ // 注意:理由分隔(#)在**规则段内**处理——文件模式里出现 # 是合法 gitignore 字符
49
+ const afterSeparator = raw.slice(at + SEPARATOR.length);
50
+ const hashAt = afterSeparator.indexOf('#');
51
+ const rulePart = (hashAt === -1 ? afterSeparator : afterSeparator.slice(0, hashAt)).trim();
52
+ const reason = hashAt === -1 ? '' : afterSeparator.slice(hashAt + 1).trim();
53
+ const filePattern = raw.slice(0, at).trim();
54
+ if (!filePattern || !rulePart) return null;
55
+ const rulePatterns = rulePart.split(',').map((s) => s.trim()).filter(Boolean);
56
+ if (!rulePatterns.length) return null;
57
+ // 任一段不像规则 id ⇒ 不是细粒度行(防止旧写法被误解析)
58
+ if (!rulePatterns.every((p) => RULE_SEGMENT_RE.test(p))) return null;
59
+ return { filePattern, rulePatterns, reason };
60
+ }
61
+
62
+ /**
63
+ * 把一个 `.auditignore` 文本拆成两部分。
64
+ * @param {string} text 文件原文
65
+ * @returns {{wholeText:string, scoped:Array<{filePattern:string, rulePatterns:string[], reason:string, rules:object[]}>}}
66
+ * wholeText = **去掉细粒度行**后的文本(供采集阶段使用:这些文件不能被整文件跳过)
67
+ */
68
+ export function splitAuditIgnore(text = '') {
69
+ const scoped = [];
70
+ const kept = [];
71
+ for (const line of String(text).split('\n')) {
72
+ const hit = parseScopedLine(line);
73
+ if (!hit) { kept.push(line); continue; }
74
+ let rules = [];
75
+ try { rules = parseGitignore(hit.filePattern); } catch { rules = []; }
76
+ if (!rules.length) { kept.push(line); continue; } // 文件模式解析不出 ⇒ 退回整行(保守)
77
+ scoped.push({ ...hit, rules });
78
+ }
79
+ return { wholeText: kept.join('\n'), scoped };
80
+ }
81
+
82
+ /** 规则模式(可含 `*`)是否命中某条 finding 的规则 id。 */
83
+ export function ruleMatches(pattern, ruleId) {
84
+ const p = String(pattern || '');
85
+ const id = String(ruleId || '');
86
+ if (!p || !id) return false;
87
+ if (!p.includes('*')) return p === id;
88
+ // 只支持 `*`(不引入正则元字符,避免用户写 `[` 造成非法正则)
89
+ const re = new RegExp(`^${p.split('*').map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('.*')}$`);
90
+ return re.test(id);
91
+ }
92
+
93
+ /**
94
+ * 判断某条 finding 是否被细粒度豁免覆盖。
95
+ * @param {Array} scoped splitAuditIgnore 的 scoped 结果
96
+ * @param {string} relPath 相对仓库根的路径(/ 分隔)
97
+ * @param {string} ruleId finding 的 rule
98
+ * @returns {{hit:boolean, reason:string, filePattern:string}}
99
+ */
100
+ export function matchScopedExemption(scoped, relPath, ruleId) {
101
+ const path = String(relPath || '').replace(/\\/g, '/');
102
+ for (const it of Array.isArray(scoped) ? scoped : []) {
103
+ if (!it.rules?.length) continue;
104
+ if (!isIgnoredByRules(it.rules, path, false)) continue;
105
+ if (!it.rulePatterns.some((p) => ruleMatches(p, ruleId))) continue;
106
+ return { hit: true, reason: it.reason || '', filePattern: it.filePattern };
107
+ }
108
+ return { hit: false, reason: '', filePattern: '' };
109
+ }
110
+
111
+ /** 文本里是否存在细粒度条目(采集阶段据此决定要不要换 excludesFile)。 */
112
+ export function hasScopedEntries(text = '') {
113
+ return splitAuditIgnore(text).scoped.length > 0;
114
+ }
115
+
116
+ /**
117
+ * 把细粒度豁免应用到 findings 上:**标记而非丢弃**。
118
+ *
119
+ * 为什么不丢弃:丢弃会让「已确认豁免」与「未处理」在报告里无法区分(这正是要解决的问题)。
120
+ * 标记后计分/汇总跳过它们,但报告能单列一节列出「豁免了哪条、为什么」。
121
+ * @param {Array} findings 统一问题对象(原地修改)
122
+ * @param {string} root 仓库根
123
+ * @returns {{total:number, byRule:Record<string,number>}}
124
+ */
125
+ export function applyScopedExemptions(findings = [], root = '') {
126
+ const byRule = {};
127
+ let total = 0;
128
+ let scoped = [];
129
+ try {
130
+ const p = join(root, '.auditignore');
131
+ if (existsSync(p)) scoped = splitAuditIgnore(readFileSync(p, 'utf8')).scoped;
132
+ } catch { scoped = []; }
133
+ if (!scoped.length) return { total, byRule };
134
+ for (const f of findings) {
135
+ if (f.exempted) continue;
136
+ const raw = String(f.file || '');
137
+ const rel = raw ? (raw.startsWith('/') ? relative(root, raw) : raw).replace(/\\/g, '/') : '';
138
+ if (!rel) continue;
139
+ const hit = matchScopedExemption(scoped, rel, f.rule);
140
+ if (!hit.hit) continue;
141
+ f.exempted = true;
142
+ f.exemptBy = 'auditignore';
143
+ f.exemptReason = hit.reason;
144
+ total += 1;
145
+ byRule[f.rule] = (byRule[f.rule] || 0) + 1;
146
+ }
147
+ return { total, byRule };
148
+ }
@@ -5,13 +5,16 @@
5
5
  * - gitIgnoreRoot 为 git 仓库:git check-ignore --stdin 批量判定(Map 缓存)
6
6
  * - 非 git 目录:全量收集不报错
7
7
  */
8
- import { readdirSync, statSync, existsSync, readFileSync } from 'node:fs';
8
+ import { readdirSync, statSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
9
+ import { tmpdir } from 'node:os';
10
+ import { createHash } from 'node:crypto';
9
11
  import { readdir, stat } from 'node:fs/promises';
10
12
  import { join, relative, extname, sep } from 'node:path';
11
13
  import { execFileSync, spawnSync } from 'node:child_process';
12
14
  import { isTestExemptDir } from '../exempt/index.js';
13
15
  import { SKIP_DIRS as HARDCODED_SKIP, getSkipSet } from '../skip-dirs.js';
14
16
  import { parseGitignore, isIgnoredByRules } from './gitignore-match.js';
17
+ import { splitAuditIgnore } from './auditignore-rules.js';
15
18
  import { GIT_GLOBAL_ARGS } from '../core/exec.js';
16
19
 
17
20
  /** 跳过目录集合 = 硬编码基线(node_modules/.git) ∪ yml 黑名单关键词(加载一次缓存)。 */
@@ -97,6 +100,30 @@ function isGitWorkTree(dir) {
97
100
  return ok;
98
101
  }
99
102
 
103
+ /**
104
+ * `.auditignore` 里出现细粒度条目(`路径 : 规则`)时,采集阶段要用**去掉这些行**的副本
105
+ * 作为 `core.excludesFile` —— 否则文件会被整文件跳过,细粒度豁免就退化成整文件豁免了。
106
+ * 无细粒度条目时直接用原文件(零额外开销,行为与旧版完全一致)。
107
+ * 结果按「根目录 + 文件 mtime/size」缓存:一次审计里 collectTextFiles 会被调用多次。
108
+ */
109
+ const AUDIT_IGNORE_COMPAT_CACHE = new Map();
110
+ function auditIgnoreExcludesFile(root, auditIgnorePath) {
111
+ let text;
112
+ try { text = readFileSync(auditIgnorePath, 'utf8'); } catch { return auditIgnorePath; }
113
+ let splitted;
114
+ try { splitted = splitAuditIgnore(text); } catch { return auditIgnorePath; }
115
+ if (!splitted.scoped.length) return auditIgnorePath;
116
+ const st = (() => { try { return statSync(auditIgnorePath); } catch { return null; } })();
117
+ const stamp = `${st ? st.mtimeMs : 0}:${text.length}`;
118
+ const cached = AUDIT_IGNORE_COMPAT_CACHE.get(root);
119
+ if (cached && cached.stamp === stamp) return cached.path;
120
+ const hash = createHash('sha1').update(`${root}:${stamp}`).digest('hex').slice(0, 16);
121
+ const out = join(tmpdir(), `dsh-auditignore-${hash}.txt`);
122
+ try { writeFileSync(out, splitted.wholeText, 'utf8'); } catch { return auditIgnorePath; }
123
+ AUDIT_IGNORE_COMPAT_CACHE.set(root, { path: out, stamp });
124
+ return out;
125
+ }
126
+
100
127
  /**
101
128
  * 非 git 目录下用纯 JS 匹配 `.auditignore`,产出与 git 路径同构的「被忽略目录集」。
102
129
  *
@@ -125,7 +152,8 @@ function tryLoadAuditIgnoreFallback(root, respectAuditIgnore = true) {
125
152
  if (gitSrc !== null) parts.push(gitSrc);
126
153
  if (respectAuditIgnore) {
127
154
  const auditSrc = readIgnoreFileCached(auditIgnorePath);
128
- if (auditSrc !== null) parts.push(auditSrc);
155
+ // 细粒度条目(路径 : 规则)只豁免指定规则,**不能**让文件整体跳过 ⇒ 采集期剔除这些行
156
+ if (auditSrc !== null) parts.push(splitAuditIgnore(auditSrc).wholeText);
129
157
  }
130
158
  if (!parts.length) return null;
131
159
  let rules;
@@ -204,7 +232,7 @@ function tryLoadGitIgnoreSet(root, respectAuditIgnore = true) {
204
232
  // 审计豁免的语义是「别对它报误报」,不是「它不是代码」;实测把它当排除项会让
205
233
  // adapters/KToolBox-webui.js 这类被豁免的文件整片从架构图里消失。
206
234
  const hasAuditIgnore = respectAuditIgnore && existsSync(auditIgnorePath);
207
- const ignoreExtraArgs = hasAuditIgnore ? ['-c', `core.excludesFile=${auditIgnorePath}`] : [];
235
+ const ignoreExtraArgs = hasAuditIgnore ? ['-c', `core.excludesFile=${auditIgnoreExcludesFile(root, auditIgnorePath)}`] : [];
208
236
  // 修复(大仓库忽略失效):原实现枚举**全部文件**路径喂 check-ignore——大仓
209
237
  // (如 DeepSeekHarness-NAS 9.9 万个文件)输入过大导致 spawnSync 超时被 SIGTERM,status=null
210
238
  // 时仍用**残缺的 stdout** 构造忽略集合 → 忽略集不完整 → 被 .gitignore 忽略的 src/ 等
@@ -428,7 +456,7 @@ export function collectChangedFiles(repoPath) {
428
456
  try {
429
457
  const r = spawnSync(
430
458
  'git',
431
- [...GIT_QUOTEPATH_ARGS, '-C', repoPath, '-c', `core.excludesFile=${auditIgnorePath}`,
459
+ [...GIT_QUOTEPATH_ARGS, '-C', repoPath, '-c', `core.excludesFile=${auditIgnoreExcludesFile(repoPath, auditIgnorePath)}`,
432
460
  'check-ignore', '--stdin', '--no-index'],
433
461
  { input: kept.map((f) => f.rel).join('\n'), encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], timeout: IGNORE_BATCH_TIMEOUT_MS },
434
462
  );
@@ -17,22 +17,90 @@ const FUNC_START_SCAN_BACK = 60; // 向上找函数起点的最大行数
17
17
  * @returns {boolean} true=同一函数内已建目录(应豁免)
18
18
  */
19
19
  export function hasMkdirInSameFunction(lines, lineIdx) {
20
- const MKDIR_RE = /mkdir(Sync)?\s*\(|ensureDataDir\s*\(|recursive:\s*true/;
21
- const FUNC_START_RE = /(function|=>)\s*\{|\)\s*(async\s*)?\{/;
22
- // 向上找函数起点(最多 60 行),命中即记下作用域起点
23
- let scopeStart = 0;
24
- for (let i = Math.max(0, lineIdx - FUNC_START_SCAN_BACK); i < lineIdx; i++) {
25
- if (FUNC_START_RE.test(String(lines[i] || ''))) scopeStart = i;
26
- }
27
- // 向后找闭括号粗略平衡点(保守取 20 行),期间出现 mkdir 即豁免
28
- const scopeEnd = Math.min(lines.length, lineIdx + MK_DIR_SCOPE_LOOKAHEAD);
29
- for (let i = scopeStart; i < scopeEnd; i++) {
20
+ // mkdir 语义家族:字面量之外还要认**常见封装命名**。
21
+ // 实测(2026-11-01 外部会话逐行样本):`ensureDir(path.dirname(file))` 就在写语句**上一行**,
22
+ // 但旧正则只认 `mkdir(Sync)?(` / `ensureDataDir(`,于是把「先建目录再写」报成 ENOENT 风险。
23
+ const MKDIR_CALL_RE = new RegExp(
24
+ '\\b(?:mkdir|mkdirSync|mkdirp|mkdtemp|mkdtempSync|ensure[A-Za-z0-9_]*Dir|ensureDir[A-Za-z0-9_]*)' +
25
+ '\\s*\\(|recursive\\s*:\\s*true',
26
+ );
27
+ const { start, end } = functionScope(lines, lineIdx);
28
+ // ① 同一函数体内出现 mkdir 家族调用
29
+ for (let i = start; i <= end && i < lines.length; i++) {
30
30
  if (i === lineIdx) continue;
31
- if (MKDIR_RE.test(String(lines[i] || ''))) return true;
31
+ if (MKDIR_CALL_RE.test(String(lines[i] || ''))) return true;
32
+ }
33
+ // ② 一层间接:本文件里定义的 helper,其函数体含 mkdir ⇒ 调用它等同已建目录
34
+ // (样本:atomic-json.mjs 的 ensureDir 是**同模块导出**,调用点自然没有 mkdir 字面量)
35
+ for (const name of mkdirHelperNames(lines)) {
36
+ const callRe = new RegExp(`\\b${name}\\s*\\(`);
37
+ for (let i = start; i <= end && i < lines.length; i++) {
38
+ if (i === lineIdx) continue;
39
+ if (callRe.test(String(lines[i] || ''))) return true;
40
+ }
32
41
  }
33
42
  return false;
34
43
  }
35
44
 
45
+ /** 向上找最近的函数起点,再按花括号配平取函数体范围(含跨 70+ 行的远距离 mkdir)。 */
46
+ function functionScope(lines, lineIdx) {
47
+ // 函数起点的四种常见形态都要认(漏一种就会把作用域退化成整文件,
48
+ // 进而把「别的函数里的 mkdir」当成本函数的 ⇒ 真问题被洗掉):
49
+ // export function name(...) { / function name(...) {
50
+ // const name = (...) => { / 方法简写 name(...) {
51
+ // 同时排除 if/for/while/switch/catch 这类不是函数的块。
52
+ const NOT_FUNC_KW = '(?!(?:if|for|while|switch|catch|do|else|try)\\b)';
53
+ const FUNC_START_RE = new RegExp(
54
+ `(?:${NOT_FUNC_KW}(?:export\\s+)?(?:async\\s+)?function\\s+[A-Za-z_$][\\w$]*\\s*\\([^)]*\\)\\s*\\{` +
55
+ `|${NOT_FUNC_KW}(?:export\\s+)?(?:async\\s+)?[A-Za-z_$][\\w$]*\\s*\\([^)]*\\)\\s*\\{` +
56
+ '|=>\\s*\\{)',
57
+ );
58
+ let start = 0;
59
+ for (let i = lineIdx; i >= 0 && i >= lineIdx - 400; i--) {
60
+ if (FUNC_START_RE.test(String(lines[i] || ''))) { start = i; break; }
61
+ }
62
+ let depth = 0;
63
+ let started = false;
64
+ let end = Math.min(lines.length - 1, start + 400);
65
+ for (let i = start; i < lines.length; i++) {
66
+ const text = String(lines[i] || '');
67
+ for (const ch of text) {
68
+ if (ch === '{') { depth += 1; started = true; }
69
+ else if (ch === '}') {
70
+ depth -= 1;
71
+ if (started && depth <= 0) { end = i; break; }
72
+ }
73
+ }
74
+ if (started && depth <= 0) { end = i; break; }
75
+ }
76
+ return { start, end: Math.max(start, end) };
77
+ }
78
+
79
+ /** 收集「函数体里含 mkdir 家族调用」的本文件函数名(一层间接判定用)。 */
80
+ function mkdirHelperNames(lines) {
81
+ const names = new Set();
82
+ const DEF_RES = [
83
+ /(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/g,
84
+ /(?:export\s+)?const\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>/g,
85
+ ];
86
+ const MKDIR_DEF_RE = /\b(?:mkdir|mkdirSync|mkdirp|mkdtemp|mkdtempSync)\s*\(/;
87
+ for (let i = 0; i < lines.length; i++) {
88
+ const text = String(lines[i] || '');
89
+ for (const re of DEF_RES) {
90
+ re.lastIndex = 0;
91
+ const m = re.exec(text);
92
+ if (!m) continue;
93
+ const { end } = functionScope(lines, i);
94
+ let has = false;
95
+ for (let k = i; k <= end && k < lines.length; k++) {
96
+ if (MKDIR_DEF_RE.test(String(lines[k] || ''))) { has = true; break; }
97
+ }
98
+ if (has) names.add(m[1]);
99
+ }
100
+ }
101
+ return names;
102
+ }
103
+
36
104
  /**
37
105
  * 写目标是否「来自调用方」——若是,则目录创建责任不在本函数,mkdir-before-write 应豁免。
38
106
  *
@@ -81,12 +81,13 @@ export function decorateTestExemptHint(findings = []) {
81
81
  export function summarize(findings = []) {
82
82
  let blocker = 0, warning = 0, notice = 0;
83
83
  for (const f of findings) {
84
+ if (f.exempted) continue; // 已确认豁免不计入「拦截/警告/提示」任何一档
84
85
  const sev = f.severity || 'warning';
85
86
  if (isBlockerFinding(f)) blocker++; // error=拦截级(凭据泄露/语法错误等)
86
87
  else if (sev === 'notice' || sev === 'info') notice++;
87
88
  else warning++;
88
89
  }
89
- return { blocker, warning, notice, total: findings.length };
90
+ return { blocker, warning, notice, total: findings.filter((f) => !f.exempted).length };
90
91
  }
91
92
 
92
93
  /** 代码文件扩展名(residue/style 类检查只对代码生效,修规则定义/文档自举假阳性)。 */
@@ -1,4 +1,5 @@
1
1
  import { readFileSync, existsSync } from 'node:fs';
2
+ import { applyScopedExemptions } from './auditignore-rules.js';
2
3
  import { execFileSync } from 'node:child_process';
3
4
  import { join, relative } from 'node:path';
4
5
  import { collectTextFiles, readText, isGitRepo, collectChangedFiles, isTextFile } from './collector.js';
@@ -349,6 +350,9 @@ async function auditFiles(repoPath, files, opts = {}) {
349
350
  // 那些 finding 绕过校正,自证里仍能看到「提示 dsh-skip-quality 却没有标记能豁免」✗。
350
351
  // 统一校正为「真能豁免该 finding」的标记(提示与判定口径分离曾致 24 种组合写了不生效)。
351
352
  normalizeExemptHints(findings);
353
+ // 细粒度豁免(`.auditignore` 的「路径 : 规则」):标记而非丢弃——不扣分但报告可见。
354
+ // 必须在所有 finding 追加完之后(与上面豁免提示校正同理,否则扩展类 finding 逃过判定)。
355
+ try { applyScopedExemptions(findings, repoPath); } catch { /* 豁免解析失败不影响审计主流程 */ }
352
356
  // 按规则包聚合命中数(侧边栏规则包列表的「拦截/警告/通过」= 实际命中数)
353
357
  const slotStats = slotStatsFromFindings(findings, buildRuleSlotMap(compiled), countRulesBySlot(compiled));
354
358
  // 文档加分制(0 分起、上限 10)——结构信号 + 交叉验证,**不进 findings**
package/lib/audit/slot.js CHANGED
@@ -15,6 +15,7 @@
15
15
  * @returns {Record<string, {blocker:number, warning:number, pass:number, total:number}>}
16
16
  */
17
17
  export function slotStatsFromFindings(findings = [], ruleSlotMap = new Map(), slotRuleCount = {}) {
18
+ findings = findings.filter((f) => !f.exempted); // 已确认豁免不计入规则包命中
18
19
  const stats = {};
19
20
  const hitRules = {}; // slot → Set(命中的规则 id)
20
21
  // 先为「所有已加载槽位」建条目:未命中的槽位也要出现在结果里
@@ -13,7 +13,11 @@ rules:
13
13
  name: "写文件前必须确保目录存在"
14
14
  category: "robustness"
15
15
  severity: "warning"
16
- description: "直接 writeFile 而不 mkdir 父目录,会导致 ENOENT 错误"
16
+ description: "本函数体内未见 mkdir/ensureDir 类建目录调用就往目标路径写文件——若目录由自定义辅助函数或调用方准备,请确认后忽略"
17
+ # 措辞刻意**不断言「代码有 bug」**:判定是静态的,认不出的形态(跨文件 helper、动态目录、
18
+ # 由调用方保证的目录)都会落在这里。写成断言式会让人以为代码真错了(外部会话反馈第 3 点)。
19
+ # 同函数体的 mkdir / ensure*Dir / mkdirp / mkdtemp,以及**本文件内**「函数体含 mkdir」的
20
+ # helper 调用,都会被判为已建目录(见 lib/audit/file-context.js 的 hasMkdirInSameFunction)。
17
21
  # 正则初筛 → token 级精筛(makeCodeLineFilter):剔除注释与字符串里的调用示例。
18
22
  # 本规则是纯 regex,此前会把**说明本规则自身的文档**也命中——实测
19
23
  # lib/checks/common.js 的 JSDoc(「会把注释/字符串里的 `fs.writeFile(...)`
@@ -83,6 +83,22 @@ export function checkRegexRules({ file, text, rules, source = '新增行', repoP
83
83
  }
84
84
  }
85
85
  const codeFilter = rule.astConfirm ? makeCodeSpanFilter(text, candidates, { file }) : null;
86
+ // 注释内命中一律丢弃(懒构建:只有真出现命中才 tokenize 一趟)。
87
+ // 背景:规则匹配到**注释里**的示例/说明文字是最常见的纯误报形态
88
+ // (实测:URL 判定谓词的注释里写着 fetch('vfs://…'),被 timeout 规则当成真实外呼)。
89
+ // 只剔注释、不剔字符串:paths/凭据类规则的命中本来就写在字符串字面量里。
90
+ // 注释类规则(comment/*、documentation/*、comment-density、no-date-in-comment 等)不适用。
91
+ const COMMENT_TARGET_RULE = /^(comment|documentation)\/|comment-(density|suspicious)|no-date-in-comment|context-todo/;
92
+ const skipCommentHits = !COMMENT_TARGET_RULE.test(String(rule.id || ''));
93
+ let commentFilter = null;
94
+ const inComment = (line, col) => {
95
+ if (!skipCommentHits) return false;
96
+ // 注意:候选行必须给**全部行**,不能复用本规则的 candidates ——
97
+ // makeCodeLineFilter 的 isCode 只对传入候选行成立,命中行若不在集合里会返回 false,
98
+ // 于是「代码里的真实命中」被当成「注释内」误杀(实测:硬编码密码 blocker 直接消失)。
99
+ if (!commentFilter) commentFilter = makeCodeSpanFilter(text, lines.map((_, k) => k + 1), { file, onlyComment: true });
100
+ return !commentFilter.isCodeHit(line, col);
101
+ };
86
102
  // readability/magic-number(唯一声明 astConfirm: magic-number 的规则)已合并进
87
103
  // magic-number-smart;本分支保留机制(自定义规则包可复用),当前无内置规则消费。
88
104
  const magicSmartLines = rule.astConfirm === 'magic-number' ? smartHitLines(text) : null;
@@ -152,6 +168,8 @@ export function checkRegexRules({ file, text, rules, source = '新增行', repoP
152
168
  // ② 回退 **token 级列级判定**(2.8.9 实现):命中列落在字符串/注释区间内 ⇒ 丢弃
153
169
  // 为什么必须 opt-in、且绝不覆盖 kindFilter(allow):硬编码路径/凭据类规则的命中
154
170
  // 本来就写在字符串里(实测:无条件开启会让 paths/hardcoded-absolute-path 从 5 条掉到 0 条 ✗)
171
+ // 注释内命中:丢弃(见上方 skipCommentHits 说明)
172
+ if (inComment(i + 1, m.index + 1)) continue;
155
173
  if (rule.astConfirmSpan === true && !hasKindAllow) {
156
174
  const verdict = typeof treeConfirm === 'function' ? treeConfirm(i + 1, m.index + 1) : null;
157
175
  if (verdict === false) continue;
@@ -56,6 +56,8 @@ export function countByDimension(findings = []) {
56
56
  // blocker(安全/凭据等硬问题)保持每次计 2——同文件多个凭据 = 多个致命风险,不合并。
57
57
  const seenRule = new Map(); // `${rule}|${dim}` → Set(file);仅 warning/info 参与去重
58
58
  for (const f of findings) {
59
+ // 已确认豁免(.auditignore 的「路径 : 规则」):不参与计分,但保留在报告里可追溯
60
+ if (f.exempted) continue;
59
61
  // scoreImpact: 0 的纯提醒(语义占位提示:npm audit 人工核查 / a11y /
60
62
  // 路径穿越人工确认)不拉低质量分——它们不是「代码质量缺陷」,只是需要人工确认的
61
63
  // 提示项;照常展示但不计入评分维度计数(severity=notice 且声明 0 影响的都不计)。
@@ -90,6 +92,7 @@ export function countByDimension(findings = []) {
90
92
  export function countHitFilesByDimension(findings = []) {
91
93
  const sets = new Map();
92
94
  for (const f of findings) {
95
+ if (f.exempted) continue; // 已确认豁免不参与「命中文件数」口径
93
96
  if (f.scoreImpact === 0) continue;
94
97
  const fileKey = f.file || '__repo__';
95
98
  for (const dim of f.dimensions || []) {
package/lib/self/index.js CHANGED
@@ -9,7 +9,7 @@
9
9
  */
10
10
 
11
11
 
12
- export const VERSION = '2.13.4'; // 2.13.4:镜像改**候选清单 + 健康度学习**(旧实现硬编码单一 gh-proxy.com,单点坏掉无退路——实测它对某 8MB 文件返回 total=590454 的截断缓存)。出厂清单 lib/core/mirror-candidates.json 只写优先级;运行期学习结果(failures/disabled/lastOkAt/lastError)落 <配置目录>/mirror-state.json,不污染入库文件。选择:DSH_GIT_MIRROR_PREFIX 显式值 > 清单首个未停用 > 全部停用则直连。停用判据以**数据校验**为准(声明总长不符 / blob sha 不符),连续 3 次停用、一次成功清零;clone-download 三处埋点(total/sha/成功),热路径加进程内缓存与「无变化不写盘」。另:test/run-tests.mjs 改**分批执行**(默认 40 文件/批,每批独立进程 + 1GB 堆上限),解决全量回归单进程堆只涨不还在 8GB 机器上挤爆内存的问题;新增 --only=<子串> 便于单组调试。历史:2.13.3 克隆死循环修复。2.13.2 动态权重维度分母。
12
+ export const VERSION = '2.14.1'; // 2.14.1:mkdir-before-write 认得出封装与一层间接。旧判定只认 mkdir(Sync)( / ensureDataDir( 字面量,且扫描窗口仅 ±20/60 行——实测对「写语句上一行就是 ensureDir(...),而 ensureDir 函数体里有 mkdirSync」的写法仍报 ENOENT 风险。现改为:识别 mkdir 家族命名(ensure*Dir / mkdirp / mkdtemp)、识别**本文件内**函数体含 mkdir 的 helper 调用(一层间接,不做跨文件)、作用域按花括号配平取**整个外层函数体**(远距离 70+ 行也覆盖),并补全 export function 形态的函数起点识别。措辞同时软化:不再断言「写前未建目录」,改为提示确认。历史:2.14.0 .auditignore 细粒度豁免。
13
13
  // 实测后果:该目录有 package.json ⇒ npm 去打包整棵 DSH 树、输出 2.1MB > spawnSync 默认 maxBuffer 1MB ⇒ ENOBUFS(npm_publish 的体检与真发全部失败);
14
14
  // 该目录没有 package.json 时报 ENOENT。现 publish 的两个调用点显式传 cwd=目标包目录,并给 runNpm 加 16MB maxBuffer。
15
15
  // 2.8.3:文案修正——「零改动 / 无新提交」明确为**正常成功路径**(注入用法、工具描述、README、skill 同批改),并修 job 输出自相矛盾(cleanSkipCommit 路径补 committed:false,不再显示「已提交,未推送」)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-git-push",
3
- "version": "2.13.4",
3
+ "version": "2.14.1",
4
4
  "description": "DSH git 自动提交推送插件——统一函数入口架构(规则/审计/git/自身/侧边栏/评分/豁免/上下文/HTTP/测试十大总入口)",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",