dsh-git-push 2.13.3 → 2.14.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.
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
  );
@@ -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
  // 先为「所有已加载槽位」建条目:未命中的槽位也要出现在结果里
@@ -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;
@@ -17,6 +17,8 @@
17
17
  */
18
18
 
19
19
  /** 默认镜像前缀:克隆等**只读**访问默认走 gh-proxy.com(可用环境变量覆盖或关闭)。 */
20
+ import { pickMirror, readSeed } from './mirror-store.js';
21
+
20
22
  export const DEFAULT_MIRROR_PREFIX = 'https://gh-proxy.com/';
21
23
  /** 显式关闭镜像的取值(环境变量设为其中之一即走直连)。 */
22
24
  const MIRROR_OFF = new Set(['off', 'none', 'no', 'false', '0', '-']);
@@ -28,10 +30,18 @@ const MIRROR_OFF = new Set(['off', 'none', 'no', 'false', '0', '-']);
28
30
  * 注意:默认开启**只影响只读请求** —— 写操作与带 token 的请求由 withMirror 的双闸门拦住。
29
31
  */
30
32
  export function mirrorPrefix() {
31
- const raw = String(process.env.DSH_GIT_MIRROR_PREFIX ?? '').trim();
32
- if (MIRROR_OFF.has(raw.toLowerCase())) return '';
33
- const use = raw || DEFAULT_MIRROR_PREFIX;
34
- return use.endsWith('/') ? use : use + '/';
33
+ // 选择逻辑收敛到 mirror-store(候选清单 + 健康度学习):
34
+ // ① DSH_GIT_MIRROR_PREFIX 显式给值 → 钉死该镜像;设为 off/none/... → 关闭;
35
+ // ② 否则取候选清单里第一个未停用的(出厂顺序 ghfast → ghproxy.net → gh-proxy);
36
+ // ③ 全部停用 → 直连。
37
+ // 旧实现硬编码 DEFAULT_MIRROR_PREFIX:单点坏掉(实测对某文件返回截断缓存)就无退路。
38
+ const picked = pickMirror();
39
+ if (picked) return picked;
40
+ // 空返回有两种含义:显式关闭 / 候选全部停用 —— 两者都走直连。
41
+ // 仅当出厂清单读不到(部署异常)时退回历史默认,避免「清单丢了就静默不加速」。
42
+ if (MIRROR_OFF.has(String(process.env.DSH_GIT_MIRROR_PREFIX ?? '').trim().toLowerCase())) return '';
43
+ if (!readSeed().length) return DEFAULT_MIRROR_PREFIX;
44
+ return '';
35
45
  }
36
46
 
37
47
  const MIRRORABLE = ['https://github.com/', 'https://raw.githubusercontent.com/', 'https://codeload.github.com/'];
@@ -0,0 +1,18 @@
1
+ {
2
+ "version": 1,
3
+ "note": "GitHub 只读镜像候选清单。mirror 必须以 / 结尾(withMirror 做纯前缀拼接)。顺序即优先级:靠前的先用。运行期会把 failures/disabled/lastOkAt/lastError 学习结果写到配置目录的 mirror-state.json,本文件保持为「出厂清单」不被回写污染。降权是自动的:某镜像连续 3 次数据校验失败(声明总长不符 / blob sha 不符)即停用,一次成功清零。",
4
+ "candidates": [
5
+ {
6
+ "mirror": "https://gh-proxy.com/",
7
+ "note": "历史默认镜像,实测吞吐最好(2026-10-03:codeload 21KB/s → 12MB/s)。2026-10-30 观测到它对个别大文件返回截断缓存(total=590454 而真实 8059635)——属**单文件缓存**问题而非镜像整体失效,故保持首选;真出问题时由下载器的 total/sha 校验自动累计失败并降权到后续候选。"
8
+ },
9
+ {
10
+ "mirror": "https://ghfast.top/",
11
+ "note": "备用。实测对同一文件返回正确总长(content-range /8059635)且支持 Range 续传"
12
+ },
13
+ {
14
+ "mirror": "https://ghproxy.net/",
15
+ "note": "备用。实测同样返回正确总长、支持 Range"
16
+ }
17
+ ]
18
+ }
@@ -0,0 +1,243 @@
1
+ /**
2
+ * 镜像候选清单与「按健康度选镜像」(模仿 dsh-useful-tools 的 github-mirror 设计)。
3
+ *
4
+ * 为什么需要候选清单:单一镜像被写死(旧实现硬编码 gh-proxy.com)时,一旦该镜像
5
+ * **返回坏数据**——实测它对一个 8MB 文件给过 total=590454 的截断缓存——整条克隆链路
6
+ * 都会卡在同一处。写死单点没有退路,而「换一个镜像」是唯一能立刻绕开的手段。
7
+ *
8
+ * 与 useful-tools 那套的分工(避免重复建设):
9
+ * · useful-tools 的候选清单作用于 **git 层**(`url.<镜像>.insteadOf` 重写);
10
+ * · 本模块作用于**插件自己的 HTTP 只读通道**(raw / codeload / api 的 GET),
11
+ * 由 lib/core/endpoints.js 的 withMirror() 拼接前缀。两者各自收口、互不干扰。
12
+ *
13
+ * 清单分两层,刻意分开:
14
+ * · **出厂清单** `mirror-candidates.json`(随仓库入库):只写「有哪些镜像、优先级」,
15
+ * 运行期的失败计数不回写它 —— 否则部署副本被 sync 覆盖、仓库被学习结果弄脏;
16
+ * · **学习状态** `<配置目录>/mirror-state.json`:每个镜像的 failures / disabled /
17
+ * lastOkAt / lastError。运行期只写这份。
18
+ *
19
+ * 选择策略(mirrorPrefix 每次调用都走这里):
20
+ * 1. 环境变量 `DSH_GIT_MIRROR_PREFIX` 显式给值 → 用它(人工钉死,最高优先);
21
+ * 设为 off/none/no/false/0/- → 关闭镜像;
22
+ * 2. 否则取**未停用**且按清单顺序的第一个镜像;
23
+ * 3. 全部停用 → 返回空串(走直连)——宁可不加速,也不用一个已知会返回坏数据的源。
24
+ *
25
+ * 失败累计:连续失败达 MAX_FAILURES(3) 次置 disabled;一次成功清零。
26
+ * 停用不是永久的:`probe` 成功即恢复(见 probeAll)。
27
+ */
28
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
29
+ import { dirname, join } from 'node:path';
30
+ import { fileURLToPath } from 'node:url';
31
+
32
+ const HERE = dirname(fileURLToPath(import.meta.url));
33
+ /** raw 基址(用于探测;与 endpoints.js 的 GH_RAW 同值,此处内联以保持单向依赖、避免循环 import)。 */
34
+ const PROBE_RAW_BASE = 'https://raw.githubusercontent.com';
35
+ /**
36
+ * 进程内缓存:下载是热路径(7374 个文件 ⇒ 每文件都问一次「用哪个镜像」),
37
+ * 每次读两个 JSON 在 CIFS 上会显著拖慢。缓存选择结果与学习状态,写状态时同步刷新。
38
+ * TTL 只影响「别的进程改了状态本进程多久能看到」,5s 足够(本进程的写入立即生效)。
39
+ */
40
+ const CACHE_TTL_MS = 5000;
41
+ let pickCache = { key: '', value: '', at: 0 };
42
+ let stateCache = { key: '', value: null, at: 0 };
43
+ /** 出厂清单位置(随仓库入库,只读种子)。 */
44
+ export const SEED_PATH = join(HERE, 'mirror-candidates.json');
45
+ /** 连续失败多少次停用(可在状态文件里手改单条 disabled 覆盖)。 */
46
+ export const MAX_FAILURES = 3;
47
+ /** 显式关闭镜像的取值。 */
48
+ const MIRROR_OFF = new Set(['off', 'none', 'no', 'false', '0', '-']);
49
+
50
+ /** 归一化前缀:去空白、强制以 / 结尾(withMirror 是纯字符串拼接,缺斜杠会拼出坏 URL)。 */
51
+ export function normalizeMirror(raw) {
52
+ const text = String(raw ?? '').trim();
53
+ if (!text) return '';
54
+ return text.endsWith('/') ? text : `${text}/`;
55
+ }
56
+
57
+ /**
58
+ * 学习状态文件位置。默认在配置目录(与凭据同处),可被
59
+ * `DSH_GIT_MIRROR_STATE` 覆盖——测试据此指向临时文件,不污染真实状态。
60
+ */
61
+ export function statePath({ configDir = '' } = {}) {
62
+ const override = String(process.env.DSH_GIT_MIRROR_STATE || '').trim();
63
+ if (override) return override;
64
+ const dir = configDir || (process.env.DSH_HOME ? join(process.env.DSH_HOME, 'git-push') : '');
65
+ return dir ? join(dir, 'mirror-state.json') : '';
66
+ }
67
+
68
+ /** 读出出厂清单。文件缺失/损坏 → 空清单(调用方回退直连,不崩)。 */
69
+ export function readSeed(path = SEED_PATH) {
70
+ try {
71
+ const raw = JSON.parse(readFileSync(path, 'utf8'));
72
+ const list = Array.isArray(raw?.candidates) ? raw.candidates : [];
73
+ return list
74
+ .map((it) => ({ mirror: normalizeMirror(it?.mirror), note: it?.note || '' }))
75
+ .filter((it) => it.mirror);
76
+ } catch { return []; }
77
+ }
78
+
79
+ /** 读学习状态(mirror → {failures, disabled, lastOkAt, lastError})。缺失/损坏 → 空表。 */
80
+ export function readState(path = statePath()) {
81
+ if (!path) return {};
82
+ try {
83
+ if (!existsSync(path)) return {};
84
+ const raw = JSON.parse(readFileSync(path, 'utf8'));
85
+ const mirrors = raw && typeof raw.mirrors === 'object' && raw.mirrors ? raw.mirrors : {};
86
+ const out = {};
87
+ for (const [k, v] of Object.entries(mirrors)) {
88
+ const key = normalizeMirror(k);
89
+ if (!key) continue;
90
+ out[key] = {
91
+ failures: Math.max(0, Math.trunc(Number(v?.failures) || 0)),
92
+ disabled: v?.disabled === true,
93
+ lastOkAt: v?.lastOkAt ?? null,
94
+ lastError: v?.lastError ?? null,
95
+ };
96
+ }
97
+ return out;
98
+ } catch { return {}; }
99
+ }
100
+
101
+ /** 原子写学习状态(失败静默:状态是加速用的元数据,写不进去不影响下载主流程)。 */
102
+ export function writeState(state, path = statePath()) {
103
+ if (!path) return { ok: false, error: '状态路径不可用' };
104
+ try {
105
+ mkdirSync(dirname(path), { recursive: true });
106
+ const tmp = `${path}.tmp-${process.pid}`;
107
+ writeFileSync(tmp, `${JSON.stringify({ version: 1, note: '镜像健康度学习结果(运行期自动维护,可手改 disabled 立即生效)', mirrors: state }, null, 2)}\n`, 'utf8');
108
+ renameSync(tmp, path);
109
+ return { ok: true, path };
110
+ } catch (e) { return { ok: false, error: String((e?.message) || e) }; }
111
+ }
112
+
113
+ /**
114
+ * 合并出厂清单与学习状态,产出按优先级排序的候选视图。
115
+ * @returns {Array<{mirror:string, note:string, failures:number, disabled:boolean, lastOkAt:string|null, lastError:string|null}>}
116
+ */
117
+ export function listCandidates({ seedPath = SEED_PATH, stateFile = statePath() } = {}) {
118
+ const state = readState(stateFile);
119
+ return readSeed(seedPath).map((it) => {
120
+ const st = state[it.mirror] || {};
121
+ return {
122
+ mirror: it.mirror,
123
+ note: it.note,
124
+ failures: st.failures || 0,
125
+ // 状态里的 disabled 可以与清单叠加:手工把状态文件改成 disabled:true 也能立刻停用
126
+ disabled: st.disabled === true,
127
+ lastOkAt: st.lastOkAt ?? null,
128
+ lastError: st.lastError ?? null,
129
+ };
130
+ });
131
+ }
132
+
133
+ /** 当前应使用的镜像前缀(含环境变量优先级与关闭语义)。空串 = 直连。 */
134
+ export function pickMirror({ seedPath, stateFile } = {}) {
135
+ const raw = String(process.env.DSH_GIT_MIRROR_PREFIX ?? '').trim();
136
+ if (raw && MIRROR_OFF.has(raw.toLowerCase())) return ''; // 显式关闭
137
+ if (raw) return normalizeMirror(raw); // 显式钉死
138
+ const key = `${seedPath || SEED_PATH}|${stateFile || statePath()}`;
139
+ const now = Date.now();
140
+ if (pickCache.key === key && now - pickCache.at < CACHE_TTL_MS) return pickCache.value;
141
+ const usable = listCandidates({ seedPath, stateFile }).find((it) => !it.disabled);
142
+ const value = usable ? usable.mirror : '';
143
+ pickCache = { key, value, at: now };
144
+ return value;
145
+ }
146
+
147
+ /** 清空进程内缓存(测试与状态变更后强制重读)。 */
148
+ export function invalidateMirrorCache() {
149
+ pickCache = { key: '', value: '', at: 0 };
150
+ stateCache = { key: '', value: null, at: 0 };
151
+ }
152
+
153
+ /**
154
+ * 记录一次实际使用的成败(由下载器在「数据校验通过/失败」后调用)。
155
+ *
156
+ * 为什么以**数据校验**而不是 HTTP 状态为判据:坏镜像的表现是 HTTP 200/206 一切正常、
157
+ * 但内容被截断或陈旧 —— 只有 total/sha 校验才能识别。故调用点放在 clone-download。
158
+ * @param {string} mirror 实际使用的镜像前缀
159
+ * @param {{ok:boolean, error?:string, stateFile?:string}} o
160
+ * @returns {{ok:boolean, state?:object, disabled?:boolean}}
161
+ */
162
+ export function recordOutcome(mirror, { ok, error = '', stateFile = statePath() } = {}) {
163
+ const key = normalizeMirror(mirror);
164
+ if (!key) return { ok: false };
165
+ const cacheKey = stateFile || statePath();
166
+ const now = Date.now();
167
+ const state = (stateCache.key === cacheKey && stateCache.value && now - stateCache.at < CACHE_TTL_MS)
168
+ ? stateCache.value
169
+ : readState(stateFile);
170
+ const cur = state[key] || { failures: 0, disabled: false, lastOkAt: null, lastError: null };
171
+ const at = new Date().toISOString();
172
+ const next = ok
173
+ ? { failures: 0, disabled: false, lastOkAt: at, lastError: null }
174
+ : {
175
+ failures: cur.failures + 1,
176
+ disabled: cur.failures + 1 >= MAX_FAILURES,
177
+ lastOkAt: cur.lastOkAt ?? null,
178
+ lastError: String(error || '数据校验失败').slice(0, 300),
179
+ };
180
+ state[key] = next;
181
+ // 无变化不写盘:成功且此前无失败记录(下载主流程的常见情形)时直接返回,
182
+ // 否则 7374 个文件会触发 7374 次状态写盘,在 CIFS 上是纯浪费。
183
+ if (ok && cur.failures === 0 && cur.disabled !== true) {
184
+ // 状态无实质变化(累计失败仍是 0、未停用)⇒ 不写盘、也不清选择缓存:
185
+ // 下载主流程每个文件都会走到这里,清缓存会让「选镜像」重新读两份 JSON。
186
+ stateCache = { key: cacheKey, value: state, at: now };
187
+ return { ok: true, state: next, disabled: false };
188
+ }
189
+ const written = writeState(state, stateFile);
190
+ stateCache = { key: cacheKey, value: state, at: now };
191
+ pickCache = { key: '', value: '', at: 0 }; // 状态变了,下一次选择重新计算
192
+ return { ok: written.ok, state: next, disabled: next.disabled === true };
193
+ }
194
+
195
+ /**
196
+ * 主动探测候选(HTTP HEAD 一个必存在的公开文件;带 Range 校验返回的总长是否与声明一致)。
197
+ *
198
+ * 为什么不只判 HTTP 状态:坏镜像恰恰是「状态正常、内容不对」。这里用 Range 请求读回
199
+ * `content-range` 的 total 与 `content-length` 交叉验证,能识别出「声明长度异常」的缓存。
200
+ * @param {{mirror?:string, stateFile?:string, fetchImpl?:Function, timeoutMs?:number,
201
+ * probeUrl?:string, expectedBytes?:number}} o
202
+ * expectedBytes:已知文件字节数;给了就严格校验,不给只判「有响应且非 0 长」。
203
+ */
204
+ export async function probeMirror({
205
+ mirror, stateFile = statePath(), fetchImpl = globalThis.fetch, timeoutMs = 8000,
206
+ probeUrl = `${PROBE_RAW_BASE}/octocat/Hello-World/main/README`, expectedBytes = 0,
207
+ } = {}) {
208
+ const prefix = normalizeMirror(mirror);
209
+ if (!prefix) return { ok: false, error: '镜像前缀为空', mirror: '' };
210
+ const url = prefix + probeUrl;
211
+ const ctrl = new AbortController();
212
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
213
+ try {
214
+ const r = await fetchImpl(url, { method: 'GET', headers: { 'User-Agent': 'dsh-git-push', Range: 'bytes=0-1023' }, signal: ctrl.signal });
215
+ if (!r.ok && r.status !== 206) return { ok: false, mirror: prefix, error: `HTTP ${r.status}` };
216
+ const len = Number(r.headers?.get?.('content-length')) || 0;
217
+ const cr = String(r.headers?.get?.('content-range') || '');
218
+ const total = Number(/\/(\d+)\s*$/.exec(cr)?.[1]) || 0;
219
+ // 声明总长与已知字节数不符 = 该源缓存坏了(这次事故的典型形态),直接判不健康
220
+ if (expectedBytes > 0 && total > 0 && total !== expectedBytes) {
221
+ return { ok: false, mirror: prefix, error: `声明总长 ${total} ≠ 期望 ${expectedBytes}`, total };
222
+ }
223
+ if (!len && !total) return { ok: false, mirror: prefix, error: '响应无长度信息' };
224
+ return { ok: true, mirror: prefix, total: total || null, len };
225
+ } catch (e) {
226
+ return { ok: false, mirror: prefix, error: String((e?.message) || e) };
227
+ } finally { clearTimeout(timer); }
228
+ }
229
+
230
+ /**
231
+ * 探测全部候选并把结果写回学习状态(成功清零并恢复,失败累计)。
232
+ * @returns {Promise<Array<{mirror:string, ok:boolean, error?:string}>>}
233
+ */
234
+ export async function probeAll({ seedPath, stateFile = statePath(), fetchImpl, timeoutMs, expectedBytes } = {}) {
235
+ const list = listCandidates({ seedPath, stateFile });
236
+ const results = [];
237
+ for (const c of list) {
238
+ const r = await probeMirror({ mirror: c.mirror, stateFile, fetchImpl, timeoutMs, expectedBytes });
239
+ recordOutcome(c.mirror, { ok: r.ok, error: r.error, stateFile });
240
+ results.push({ mirror: c.mirror, ok: r.ok, error: r.error });
241
+ }
242
+ return results;
243
+ }
@@ -27,7 +27,8 @@ import { mkdir, rename, unlink, chmod, symlink, rm, readdir, rmdir, access } fro
27
27
  import { dirname, join } from 'node:path';
28
28
  import { pipeline } from 'node:stream/promises';
29
29
  import { Readable } from 'node:stream';
30
- import { blobApiUrl, contentsApiUrl, rawFileUrl } from './endpoints.js';
30
+ import { blobApiUrl, contentsApiUrl, rawFileUrl, mirrorPrefix, GH_RAW } from './endpoints.js';
31
+ import { listCandidates, normalizeMirror, recordOutcome } from '../core/mirror-store.js';
31
32
 
32
33
  /* ───────── clone 下载器常量 ───────── */
33
34
  const RETRY_BASE_DELAY_MS = 120; // 失败重试基础延迟(第 i 次重试等待 120×(i+1)ms,线性退避)
@@ -312,6 +313,30 @@ export async function removeDirForce(dir, attempts = 3) {
312
313
  try { await access(dir); return false; } catch { return true; } // 不存在即视为成功
313
314
  }
314
315
 
316
+ /**
317
+ * 本次请求走的是哪个镜像(未走镜像返回空串)。
318
+ *
319
+ * 用途:只有**真正经镜像**的请求才该影响镜像健康度;api.github.com 直连通道
320
+ * (不走镜像)成功或失败都与镜像无关,不能记到它头上。
321
+ */
322
+ function mirrorOf(url) {
323
+ try {
324
+ const mp = mirrorPrefix();
325
+ return mp && String(url).startsWith(mp) ? mp : '';
326
+ } catch { return ''; }
327
+ }
328
+
329
+ /**
330
+ * 把一次实际使用的成败记到镜像健康度上(数据校验才是判据:坏镜像表现为
331
+ * HTTP 正常但内容截断/陈旧,只有 total/sha 校验能识别)。
332
+ * 记录失败不影响本次下载结果——它只影响「下次优先选谁」。
333
+ */
334
+ function noteMirror(url, ok, error) {
335
+ const mp = mirrorOf(url);
336
+ if (!mp) return;
337
+ try { recordOutcome(mp, { ok, error }); } catch { /* 健康度是加速用的元数据,失败不打断下载 */ }
338
+ }
339
+
315
340
  /** 从响应头提取「该源声明的文件总长」:206 用 content-range 的 /total,200 用 content-length。0=无从判断。 */
316
341
  function totalFromResponse(resp) {
317
342
  try {
@@ -357,7 +382,22 @@ async function fetchToFile({ owner, repo, branch, relPath, token, out, partPath,
357
382
  // 需要续传(have > 0)或 api 失败时退 raw(能断点续,接受其并发不稳)。
358
383
  const useRawFirst = have > 0;
359
384
  const apiUrl = contentsApiUrl(owner, repo, encoded, encodedBranch);
360
- const rawUrl = rawFileUrl(owner, repo, encodedBranch, encoded); // raw 走镜像
385
+ const rawUrl = rawFileUrl(owner, repo, encodedBranch, encoded); // raw 走当前选中的镜像
386
+ // 直连 raw(不经镜像):镜像全部不可用时仍是可用通道
387
+ const rawDirect = `${GH_RAW}/${owner}/${repo}/${encodedBranch}/${encoded}`;
388
+ // **同一文件的救援链**:当前镜像之外的其它候选镜像也要试。
389
+ // 为什么必须这样:候选清单原先只影响「选谁」,而单个文件一旦撞上某个镜像的坏缓存
390
+ // (实测某镜像对该文件只有 590454 字节的截断版本),链里只剩 api 全量重下——
391
+ // 续传能力就白费了。把全部可用镜像都放进链里,才能真的「换一个镜像接着续」。
392
+ const altMirrors = (() => {
393
+ try {
394
+ return listCandidates()
395
+ .filter((it) => !it.disabled)
396
+ .map((it) => normalizeMirror(it.mirror))
397
+ .filter((m) => m && rawUrl !== m && !String(rawUrl).startsWith(m))
398
+ .map((m) => `${m}${rawDirect}`);
399
+ } catch { return []; }
400
+ })();
361
401
  const mkHeaders = (raw, withRange) => {
362
402
  const headers = { 'User-Agent': 'dsh-git-push' };
363
403
  if (token) headers.Authorization = `Bearer ${token}`;
@@ -366,7 +406,13 @@ async function fetchToFile({ owner, repo, branch, relPath, token, out, partPath,
366
406
  if (withRange && have > 0) headers.Range = `bytes=${have}-`;
367
407
  return headers;
368
408
  };
369
- const urls = useRawFirst ? [[rawUrl, true], [apiUrl, false]] : [[apiUrl, false], [rawUrl, true]];
409
+ const mirrorChain = [rawUrl, ...altMirrors].filter((u, i, a) => u && a.indexOf(u) === i).map((u) => [u, true]);
410
+ // 续传优先(have>0):镜像链在前(唯一支持 Range),api 全量兜底;
411
+ // 起步(have=0):api 稳、优先,镜像链随后。直连 raw 仅在**没有任何镜像**时补位。
412
+ const urls = useRawFirst
413
+ ? [...mirrorChain, [apiUrl, false]]
414
+ : [[apiUrl, false], ...mirrorChain];
415
+ if (!mirrorChain.length) urls.push([rawDirect, true]);
370
416
 
371
417
  // 依次尝试候选通道,首个成功即用;全失败则回报最后一条的成因
372
418
  let resp = null;
@@ -397,6 +443,7 @@ async function fetchToFile({ owner, repo, branch, relPath, token, out, partPath,
397
443
  const declaredTotal = totalFromResponse(resp);
398
444
  if (declaredTotal > 0 && declaredTotal !== size) {
399
445
  try { await resp.body?.cancel?.(); } catch { /* 无所谓 */ }
446
+ noteMirror(urls[respIdx]?.[0], false, `声明总长 ${declaredTotal} ≠ 仓库记录 ${size}(疑似截断缓存)`);
400
447
  lastErr = { status: resp.status, reason: `通道数据异常(声明总长 ${declaredTotal} ≠ 仓库记录 ${size},疑似代理截断缓存),弃用该源` };
401
448
  let rescued = false;
402
449
  for (let ci = 0; ci < urls.length; ci++) {
@@ -440,7 +487,7 @@ async function fetchToFile({ owner, repo, branch, relPath, token, out, partPath,
440
487
  if (expectSha && size > 0) {
441
488
  const { createHash } = await import('node:crypto');
442
489
  hasher = createHash('sha1');
443
- hasher.update(`blob ${size}\u0000`, 'latin1'); // git object header( 按 latin1 保持单字节)
490
+ hasher.update(`blob ${size}\u0000`, 'latin1'); // git object header(\u0000 按 latin1 保持单字节)
444
491
  if (appending && have > 0) {
445
492
  try { hasher.update(readFileSync(partPath)); } catch { hasher = null; }
446
493
  }
@@ -462,10 +509,13 @@ async function fetchToFile({ owner, repo, branch, relPath, token, out, partPath,
462
509
  const got = hasher.digest('hex');
463
510
  if (got !== String(expectSha)) {
464
511
  try { await unlink(partPath); } catch { /* 忽略 */ }
512
+ // 内容与 tree 记录的 sha 不符:坏镜像 / 脏前缀都会这样。同样计入镜像健康度。
513
+ noteMirror(urls[respIdx]?.[0], false, `blob sha 不符(实得 ${got.slice(0, 10)}…)`);
465
514
  return { ok: false, status: resp.status, reason: `内容校验不符(blob sha 期望 ${String(expectSha).slice(0, 10)}…,实得 ${got.slice(0, 10)}…),已废弃分片以便下轮干净重下` };
466
515
  }
467
516
  }
468
517
  await rename(partPath, out);
518
+ noteMirror(urls[respIdx]?.[0], true); // 校验全过 ⇒ 该镜像这次是健康的
469
519
  return { ok: true };
470
520
  } catch (e) {
471
521
  return { ok: false, status: 0, reason: `写入失败: ${e?.message || e}` };
@@ -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.3'; // 2.13.3:修大仓库克隆「死在同一文件每轮从 0 重来」(实测根因:gh-proxy.com 对某 8MB 文件返回total=590454 的**截断缓存**,带 Range 续传每轮「已到该源 total 无法增长」→ 长度校验永远失败、脏分片留着越拼越歪)。clone-download 三重防御:①响应声明总量校验(206 取 content-range 的 /total、200 取 content-length,与仓库记录 size 不符 ⇒ cancel 响应、不写分片、换候选通道 rescue);②git blob sha 增量校验(流式 update,header 按 latin1 单字节 \0;长度对但内容错——镜像旧缓存——也当场废弃分片,下轮从 0 走 api 直连自愈);③失败保留分片语义不变。新增 test-clone-mirror-truncation 4 例(含真实 git hash 自洽桩);顺带修既有测试两处桩缺陷(两个文件同 sha 撞分片名、预置分片没落在实际 sha 上)。历史:2.13.2 动态权重维度分母。2.13.1 流式 fetch 停摆判据。
12
+ export const VERSION = '2.14.0'; // 2.14.0:.auditignore 支持**细粒度豁免**(路径 : 规则),并可把豁免做成「已确认豁免」可见通道;另有注释内命中治理。历史:2.13.4 镜像候选清单与分批测试。
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.3",
3
+ "version": "2.14.0",
4
4
  "description": "DSH git 自动提交推送插件——统一函数入口架构(规则/审计/git/自身/侧边栏/评分/豁免/上下文/HTTP/测试十大总入口)",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",