dsh-git-push 2.9.1 → 2.9.4

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.
@@ -0,0 +1,57 @@
1
+ /**
2
+ * 仓库级检查:逐文件扫描实现过多(`kind: multi-file-scanners`)
3
+ *
4
+ * 【判据】同一函数体内**同时**出现 `readdir` 与 `stat` ⇒ 一个「逐文件取属性」的扫描实现。
5
+ * 全仓这类实现数 > `min_occurrences`(规则字段,默认 3)⇒ 报 **一条** notice:
6
+ * 「同一职责是否被各处独立实现了一遍」交人工判断(不是「你有 N 个 bug」✗)。
7
+ *
8
+ * 【为什么只报一处】这是**整个仓库**的属性(与 duplicate-code 同性质)。逐文件报会在 N 个
9
+ * 文件上产出 N 条同义提示,把真实问题淹掉 ⇒ 只在代表文件上报一次,其余实现列进 message ✓
10
+ * (代表文件 = 路径字典序最小者,由 orchestrate 的 pickRepoLevelAnchorFile 决定语义)。
11
+ *
12
+ * 【口径单一】判据实现只在 `lib/ast/fs-hotspots.js` 一份 —— 独立 CLI
13
+ * `scripts/scan-fs-hotspots.mjs` 用的是同一个函数,不存在「规则一套、脚本一套」的漂移 ✗
14
+ *
15
+ * @param {Array<{path:string,text:string}>} fileTexts 全仓代码文件文本
16
+ * @param {Array} rules 该 kind 下的规则(取第一条;阈值读 min_occurrences / extra.minOccurrences)
17
+ * @returns {Array} findings
18
+ */
19
+ import { scanFsHotspots } from '../ast/fs-hotspots.js';
20
+
21
+ export function checkMultiFileScanners(fileTexts = [], rules = null) {
22
+ const findings = [];
23
+ if (!Array.isArray(fileTexts) || fileTexts.length < 2) return findings; // 单文件谈不上「多实现」
24
+ const rule = Array.isArray(rules) && rules.length ? rules[0] : null;
25
+ if (!rule) return findings;
26
+
27
+ const threshold = Number(rule?.extra?.minOccurrences ?? rule?.minOccurrences ?? 3) || 3;
28
+ const severity = 'notice'; // 恒 notice:这是启发式提示(不同用途的扫描器是合法的)⇒ 只提示不警告
29
+
30
+ let agg;
31
+ try {
32
+ agg = scanFsHotspots(fileTexts);
33
+ } catch {
34
+ return findings; // 单个异常不影响整轮审计
35
+ }
36
+ const scanners = agg.scanners || [];
37
+ if (scanners.length <= threshold) return findings;
38
+
39
+ // 代表文件 = 路径字典序最小者(与 repo-level 语义一致,保证同一仓库每次报同一处)
40
+ const sorted = [...scanners].sort((a, b) => String(a.file).localeCompare(String(b.file)));
41
+ const first = sorted[0];
42
+ const rest = sorted.slice(1);
43
+ const list = rest.map((s) => `${s.file}::${s.fn}()`).join('、');
44
+ findings.push({
45
+ rule: rule.id,
46
+ severity,
47
+ file: first.file,
48
+ line: first.line,
49
+ message: `仓库内「同一函数里既 readdir 又 stat」的逐文件扫描实现共 ${scanners.length} 个`
50
+ + `(阈值 ${threshold}):${first.file}::${first.fn}()`
51
+ + (list ? ` 等 —— 其余:${list}` : '')
52
+ + '。提示:同一职责被各处独立实现时,合并成一层遍历/索引可省掉重复 readdir 与重复 stat'
53
+ + '(不同用途的扫描器属正常,需人工判断)',
54
+ dimensions: rule?.dimensions,
55
+ });
56
+ return findings;
57
+ }
@@ -43,4 +43,5 @@ export { checkMagicNumberSmart } from './magic-number.js';
43
43
  export { checkFileHealth } from './file-health.js';
44
44
  export { checkDataflow } from './dataflow.js';
45
45
  export { checkDuplicateCode } from './dup-code.js';
46
+ export { checkMultiFileScanners } from './fs-scanner.js';
46
47
  export { checkDuplicateConst, findConstDefs } from './dup-const.js';
@@ -38,15 +38,19 @@ export function pickExemptHint(rule) {
38
38
  }
39
39
  if (hit(residue.residueRules)) return 'dsh-skip-residue(行尾=本行)';
40
40
  if (hit(style.styleRules)) return 'dsh-skip-style(文件头=整文件)';
41
- // 三套清单都没命中 = 该规则当前没有可用豁免标记,保守沿用原提示(不新增误导)
42
- return 'dsh-skip-residue(行尾=本行)';
41
+ // 三套清单都没命中:**不能**再沿用一个写了不生效的标记 ✗(2026-10-17「措辞无效」的根因之一:
42
+ // 这里原样返回 dsh-skip-residue,而 residue 只管 debugger/todo/console/io-risk 等窄集合,
43
+ // 其余 regex 规则(vague-function-name / timeout-on-external-api …)写了完全不生效)。
44
+ // 改为按注册表反查:真能豁免给出真标记,否则如实留空(由 finding 出口统一校正兜底)。
45
+ const truth = exemptHintForFinding({ kind: kind || 'regex', rule: id });
46
+ return truth ? `${truth.marker}(${truth.hint})` : '';
43
47
  }
44
48
 
45
49
  import { makeFinding } from '../audit/index.js';
46
50
  import { safeRe } from '../rule/compilers.js';
47
51
  import { capSeverity } from './common.js';
48
52
  // 豁免提示按规则名前缀选关键词——分类清单复用豁免注册表(单一来源,避免两处各写一份清单)
49
- import { EXEMPT_MARKERS } from '../exempt/index.js';
53
+ import { EXEMPT_MARKERS, exemptHintForFinding } from '../exempt/index.js';
50
54
  import { credentialValueLines, placeholderCredentialLines, shortFuncNameLines, smallFileReadLines, consoleLogJsonLines, loopFullCollectionLines, repeatIdenticalCallLines, loopNoFallbackReturnLines, loopFullRewriteCallLines, nestedLinearScanLines, longSyncLoopLines, smartHitLines, shellCdDynamicLines, writeIntoGitignoredLines, ioRiskLines, ioRiskDetail } from './common.js';
51
55
 
52
56
  /** 检查文本是否符合 regex 型规则(regex / secret / credential-ref)。
@@ -83,8 +83,11 @@ export function saveWorkspacePaths(paths, { by = 'ai' } = {}) {
83
83
  /**
84
84
  * 生成注入用的「AI 自设工作区」文本块(无自设时返回 '')。
85
85
  *
86
- * 措辞要点:① 明确这是 **AI 自己登记的**(不是宿主探测 ⇒ 不准确就是自己写错了)
87
- * ② 给出修改入口(同一个 API),让下一轮的自己知道怎么改 ✓
86
+ * 措辞要点(缺一不可):
87
+ * ① 明确这是 **AI 自己维护**的位置清单(不是宿主探测)——**维护责任在 AI**:
88
+ * 工作区挪了/改名了/开始处理另一个目录,AI 自己要更新,否则下一轮看到的还是旧清单 ✗
89
+ * ② 给出修改入口(同一个 API)与读回方式,让下一轮的自己知道怎么改 ✓
90
+ * ③ 说明优先级:高于会话 cwd(会话 header 本身可能是陈旧路径)
88
91
  * @param {string} [sep] 行分隔符(默认换行)
89
92
  * @returns {string} 多行文本;无自设 ⇒ ''
90
93
  */
@@ -93,8 +96,13 @@ export function workspacePathsInjectionText(sep = '\n') {
93
96
  if (!paths.length) return '';
94
97
  const L = [`【AI 自设工作区(${paths.length} 个 · 由 ${updatedBy || 'ai'} 于 ${String(updatedAt).slice(0, 16) || '未知时间'} 登记)】`];
95
98
  paths.forEach((p, i) => L.push(`- ${i + 1}. ${p}`));
96
- L.push('(这是**你自己**登记的清单,优先级高于会话 cwd;要增删改用 API:'
97
- + "git_api({path:'workspace-paths', method:'POST', body:'{\"paths\":[\"<绝对路径>\", …]}'})"
98
- + ',GET 同路径可读回当前值)');
99
+ L.push('⚠️ 这是**由你(AI)自己维护**的工作区位置清单——不是宿主探测出来的:'
100
+ + '工作区被移动/改名、或你开始处理另一个目录时,**你要主动更新它**,'
101
+ + '否则下一轮你看到的仍是这份旧清单(下方会话 cwd 可能本身就是陈旧路径 ✗)。');
102
+ L.push('维护方式(同一端点按方法分发):'
103
+ + "改/加/删 —— git_api({path:'workspace-paths', method:'POST', body:'{\"paths\":[\"<绝对路径>\", …]}'})"
104
+ + '(可选 "mode":"add"|"remove";{"clear":true} 清空);'
105
+ + "读回 —— git_api({path:'workspace-paths'})"
106
+ + '。只收绝对路径、必须存在且是目录,上限 20 条。');
99
107
  return L.join(sep);
100
108
  }
@@ -14,7 +14,10 @@ import { statSync } from 'node:fs';
14
14
  export const EXEMPT_MARKERS = {
15
15
  'dsh-skip-sensitive': {
16
16
  dimensions: ['安全性'],
17
- blocked: ['[FUNC]', 'credential-file', 'credential-ref', 'path-regex', 'regex'], // path-regex 含私钥路径类;regex 是宽声明(安全类按 rule 名细分)
17
+ // 2026-10-17 补 'semantic':security/* 的语义类 finding(如 security/no-path-traversal)
18
+ // 此前既不在 sensitive.blocked、又被 quality 的安全排除挡掉 ⇒ 任何标记都豁免不了 ✗
19
+ // (自证第 24 种)。细分词表同时作用于 semantic(见 markerCovers)。
20
+ blocked: ['[FUNC]', 'credential-file', 'credential-ref', 'path-regex', 'regex', 'semantic'], // path-regex 含私钥路径类;regex 是宽声明(安全类按 rule 名细分)
18
21
  // regex 宽声明:security/* 规则带 pattern 字段编译成 regex kind,
19
22
  // 需按 rule 名细分(含 security/credential/secret/password/hardcoded 等安全词才算敏感类)
20
23
  sensitiveRules: ['security', 'credential', 'credref', 'credfile', 'secret', 'password', 'hardcoded'],
@@ -66,8 +69,17 @@ export const EXEMPT_MARKERS = {
66
69
  // comment-density / file-health:这两类 finding 一直提示 dsh-skip-quality,
67
70
  // 但它们的 kind 也不在任何标记的 blocked 里(同 blacklist/magic-number-smart 一类 bug:
68
71
  // 提示写了不生效)⇒ 一并补进本条(注释密度与文件健康度都属「质量评分」语义)。
72
+ // 2026-10-17 补齐(起因:「有人反应文件头豁免措辞无效」⇒ 全量自证查出 24 种组合
73
+ // **按 finding 提示写了文件头标记仍照报** ✗)。两类缺口:
74
+ // ① semantic / dataflow / duplicate-const / repeated-string —— 此前**没有任何标记**
75
+ // 能豁免这些 kind,而规则自身却提示用 dsh-skip-quality ⇒ 写了不生效;
76
+ // ② regex —— 兜底覆盖**非安全类**的 regex finding(安全类由 excludeRules 排除,
77
+ // 仍必须写 dsh-skip-sensitive,避免用质量标记顺手静默掉安全问题 ✗)。
69
78
  blocked: ['func-lines', 'empty-catch', 'sync-fs', 'magic-number-smart', 'blacklist',
70
- 'comment-density', 'file-health'],
79
+ 'comment-density', 'file-health',
80
+ 'semantic', 'dataflow', 'duplicate-const', 'repeated-string', 'regex'],
81
+ // regex 兜底时**排除**安全类规则名(这些必须走 dsh-skip-sensitive,不能靠质量标记吞掉)
82
+ excludeRules: ['security', 'credential', 'credref', 'credfile', 'secret', 'password', 'hardcoded'],
71
83
  lineLevel: false,
72
84
  hint: '文件头=整文件免质量评分(func-lines/empty-catch/sync-fs/magic-number-smart/blacklist 措辞/comment-density/file-health)',
73
85
  },
@@ -84,7 +96,11 @@ export const EXEMPT_MARKERS = {
84
96
  },
85
97
  'dsh-skip-style': {
86
98
  dimensions: ['可读性'],
87
- blocked: ['regex', 'min-occurrences'], // 需按 rule 前缀细分(style-* 数值风格规则);min-occurrences 是 lib/audit/orchestrate.js 分体文档提示用的非 regex kind
99
+ // 需按 rule 前缀细分(style-* 数值风格规则);min-occurrences 是 lib/audit/orchestrate.js 分体文档提示用的非 regex kind。
100
+ // 2026-10-17 补 min-length / max-lines / max-complexity / max-depth / repeated-string 这些**直接 kind**:
101
+ // styleRules 里本来就列了它们(文档表也写「style-* 数值风格(min-length/max-lines/max-complexity/max-depth)→ 只能文件头」),
102
+ // 但 blocked 只列了 'min-occurrences' ⇒ kind=min-length 等 finding 提示 dsh-skip-quality 时**无任何标记可豁免** ✗(自证抓到)。
103
+ blocked: ['regex', 'min-occurrences', 'min-length', 'max-lines', 'max-complexity', 'max-depth', 'repeated-string'],
88
104
  styleRules: ['min-length', 'max-lines', 'max-complexity', 'max-depth', 'min-occurrences', 'repeated-string'],
89
105
  lineLevel: false,
90
106
  hint: '文件头=整文件免全部 styleRules',
@@ -136,11 +152,62 @@ export function isCategoryExempt(finding = {}) {
136
152
  return false;
137
153
  }
138
154
 
155
+ /**
156
+ * 单个标记是否覆盖该 kind/rule —— **唯一判定口径**(exemptForFinding 与反查提示共用)。
157
+ *
158
+ * 为什么抽出来:此前「判定是否豁免」与「生成 exemptHint」两处各写一套口径 ⇒
159
+ * 提示的标记与实际能否豁免会不一致(2026-10-17 全量自证实测 24 种组合:
160
+ * 用户按 finding 提示写了文件头标记仍然照报,即「措辞无效」✗)。
161
+ */
162
+ function markerCovers(meta, kind, rule) {
163
+ if (!meta || !Array.isArray(meta.blocked) || !meta.blocked.includes(kind)) return false;
164
+ const r = String(rule || '').toLowerCase();
165
+ const has = (a) => Array.isArray(a) && a.length > 0;
166
+ // 残留/风格/国际化:只对 regex 宽声明做「规则名细分」
167
+ if (kind === 'regex') {
168
+ if (has(meta.residueRules)) return meta.residueRules.some((w) => r.includes(w));
169
+ if (has(meta.styleRules)) return meta.styleRules.some((w) => r.includes(w));
170
+ if (has(meta.i18nRules)) return meta.i18nRules.some((w) => r.includes(w));
171
+ }
172
+ // 安全类细分:regex 与 semantic 两类**宽 kind** 都要按词表判;
173
+ // ⚠️ 不可推广到 path-regex / [FUNC] / credential-* —— 那些是**直接 kind 命中**,
174
+ // 不受规则名词表约束(原语义;扩展 semantic 时曾误伤 path-private-key-location ⇒ 回归)。
175
+ if ((kind === 'regex' || kind === 'semantic') && has(meta.sensitiveRules)) {
176
+ return meta.sensitiveRules.some((w) => r.includes(w));
177
+ }
178
+ // 质量兜底对 regex 的覆盖:排除安全类(安全 finding 不许被质量标记吞掉 ✗)
179
+ if (kind === 'regex' && has(meta.excludeRules)) return !meta.excludeRules.some((w) => r.includes(w));
180
+ return true;
181
+ }
182
+
183
+ /** 指定标记是否覆盖该 finding(供提示校正判断「原提示是否仍然有效」)。 */
184
+ export function exemptMarkerCovers(marker, finding = {}) {
185
+ return markerCovers(EXEMPT_MARKERS[marker], finding.kind || '', finding.rule || '');
186
+ }
187
+
188
+ /**
189
+ * 反查「真能豁免该 finding 的标记」——按与 exemptForFinding **同一口径**判定。
190
+ * 优先级:先非 dsh-skip-quality(专用标记更贴切),最后才是质量类兜底。
191
+ * @param {object} finding 需含 kind/rule
192
+ * @returns {{marker:string, hint:string}|null} 无可豁免标记时返回 null(调用方应如实提示)
193
+ */
194
+ export function exemptHintForFinding(finding = {}) {
195
+ const kind = finding.kind || '';
196
+ const rule = finding.rule || '';
197
+ const pinned = ['dsh-skip-quality'];
198
+ const order = [...Object.keys(EXEMPT_MARKERS).filter((m) => !pinned.includes(m)), ...pinned];
199
+ for (const marker of order) {
200
+ const meta = EXEMPT_MARKERS[marker];
201
+ if (markerCovers(meta, kind, rule)) return { marker, hint: meta.hint };
202
+ }
203
+ return null;
204
+ }
205
+
139
206
  /**
140
207
  * 判定单个 finding 是否被豁免。
141
208
  * 整文件豁免(文件头前 3 行含标记)→ 该 finding 的 kind 命中 blocked 即豁免;
142
209
  * 行级豁免(finding.line 所在行含标记,且标记支持 lineLevel)→ 豁免。
143
- * residue/style 走 rule 前缀细分(blocked=['regex'] + 规则名含 debugger/todo/console / style-*)。
210
+ * residue/style/i18n/sensitive 走 rule 前缀细分(口径统一在 markerCovers)。
144
211
  * @param {object} finding 统一问题对象
145
212
  * @param {string} text 文件全文(用于取文件头与行)
146
213
  * @returns {boolean} true=豁免(应丢弃该 finding)
@@ -152,28 +219,7 @@ export function exemptForFinding(finding, text = '') { // dsh-skip-complexity:
152
219
  const kind = finding.kind || '';
153
220
  const rule = finding.rule || '';
154
221
  for (const [marker, meta] of Object.entries(EXEMPT_MARKERS)) {
155
- const blockedHit = meta.blocked.includes(kind);
156
- // residue/style:blocked 里的 'regex' 是**宽声明**,需按 rule 前缀细分;
157
- // 但细分支必须只在 kind === 'regex' 时生效——否则 blocked 里直接列的非 regex kind
158
- // (如 style 的 'min-occurrences',orchestrate.js 的分体文档提示用它做 kind)
159
- // 会被 rule 名细分误杀:规则名不含 styleRules 词 ⇒ 写了标记也不豁免(实测复现)。
160
- // sensitive/i18n 两个分支本就带 kind === 'regex' 前置,这里补齐一致。
161
- let kindHit = blockedHit;
162
- if (kind === 'regex' && blockedHit && meta.residueRules && meta.residueRules.length) {
163
- kindHit = meta.residueRules.some((r) => rule.toLowerCase().includes(r));
164
- }
165
-
166
- if (kind === 'regex' && blockedHit && meta.styleRules && meta.styleRules.length) {
167
- kindHit = meta.styleRules.some((r) => rule.toLowerCase().includes(r));
168
- }
169
- if (kind === 'regex' && meta.i18nRules && meta.i18nRules.length) {
170
- kindHit = meta.i18nRules.some((r) => rule.toLowerCase().includes(r));
171
- }
172
- // sensitive 细分只在 regex 宽声明时生效(直接 kind 命中如 [FUNC]/credential-*/path-regex 不受 rule 名约束)
173
- if (kind === 'regex' && meta.sensitiveRules && meta.sensitiveRules.length) {
174
- kindHit = meta.sensitiveRules.some((r) => rule.toLowerCase().includes(r));
175
- }
176
- if (!kindHit) continue;
222
+ if (!markerCovers(meta, kind, rule)) continue;
177
223
  // 整文件豁免(文件头前 3 行)
178
224
  if (hasHeaderExempt(lines.slice(0, 3).join('\n'), marker)) return true;
179
225
  // 行级豁免(支持 lineLevel 且本行含标记)
@@ -53,6 +53,7 @@ export function editAfterRead({
53
53
  old: oldArg,
54
54
  new: newArg,
55
55
  all: allArg,
56
+ allowDuplicate: allowDupArg,
56
57
  file_path: filePathAlias,
57
58
  old_string: oldStringAlias,
58
59
  new_string: newStringAlias,
@@ -67,6 +68,7 @@ export function editAfterRead({
67
68
  const old = oldArg ?? oldStringAlias;
68
69
  const next = newArg ?? newStringAlias;
69
70
  const all = (allArg ?? replaceAllAlias) === true;
71
+ const allowDuplicate = allowDupArg === true;
70
72
  const fail = (reason) => ({ ok: false, path, replaced: 0, bytesBefore: 0, bytesAfter: 0, reason });
71
73
  if (!path) return fail('缺少 path(或 file_path)');
72
74
  if (!old) return fail('缺少 old(要被替换的字面文本;或 old_string)');
@@ -94,10 +96,47 @@ export function editAfterRead({
94
96
  }
95
97
 
96
98
  const out = all ? text.split(old).join(next) : text.replace(old, next);
99
+
100
+ // ── 写前防呆(两道,专治"文档被写重"):实测事故 2026-10-16,一份 17.7KB 文档被改成
101
+ // ~2 倍体积、`## 一`/`## 二` 各出现两次 —— 形态是「old 只是个小锚点,而 new 里带了**整份文档**」。
102
+ // 复现结论:工具本身不会写重(new 含 old、同一 old 连调两次都不重 ✗)⇒ 重复来自参数形态;
103
+ // 所以这里把该形态**拦在写盘之前**,而不是写坏文件再让人去 git checkout 恢复 ✓
104
+ // ① 产物里若**包含整份原文**(text)⇒ new 必定把原文整份带上了 ⇒ 拒绝(正常编辑/追加都不会满足)
105
+ // ② 产物里 old 出现多次 ⇒ 同样是"原文被带上"的另一种形态 ⇒ 拒绝
106
+ // 两道都可显式 allowDuplicate:true 放行(确实要保留重复时)
107
+ if (!allowDuplicate) {
108
+ if (out.includes(text)) {
109
+ return fail('拒绝写入:替换后的内容**完整包含原文件**(new 里很可能把整份原文又带上了)'
110
+ + '—— 这会把文档写成两份。请让 new 只描述「被替换那一段替换后长什么样」;'
111
+ + '确实要保留整份原文请显式传 allowDuplicate: true');
112
+ }
113
+ const dup = countOccurrences(out, old);
114
+ if (dup > 1) {
115
+ return fail(`拒绝写入:替换后,被替换的原文会**出现 ${dup} 次**(new 里很可能把 old 整份又带上了)`
116
+ + '—— 这会把文档写重。请把 new 只写成「替换后的样子」;确实需要重复请显式传 allowDuplicate: true');
117
+ }
118
+ }
119
+
97
120
  try {
98
121
  writeFile(path, out, 'utf8');
99
122
  } catch (e) {
100
123
  return fail(`写入失败:${(e && e.message) || e}`);
101
124
  }
125
+
126
+ // ── 写后自检 + 自动回滚(只在用默认真实读写时做;注入的读函数按测试约定可能返回定值 ✗)
127
+ // 回读校验两条不变量:① 长度与预期一致 ② old 不再出现多次(除非 allowDuplicate)
128
+ // 任一不满足 ⇒ 用内存里那份原文**回滚** ✓(原文就在手上,无需备份文件)⇒ 最坏情况也只是「没改成」
129
+ if (readFile === readFileSync) {
130
+ try {
131
+ const back = String(readFile(path, 'utf8'));
132
+ const badLen = back.length !== out.length;
133
+ const badDup = !allowDuplicate && countOccurrences(back, old) > 1;
134
+ if (badLen || badDup) {
135
+ writeFile(path, text, 'utf8');
136
+ return fail(`写后自检未通过(${badLen ? '长度不符' : ''}${badLen && badDup ? ' + ' : ''}${badDup ? '原文重复出现' : ''}),`
137
+ + '已**回滚**为读到的原内容;请检查参数(很可能是 new 里带了整份文档)后重试');
138
+ }
139
+ } catch { /* 回读失败不阻断:写入已完成,交由调用方核对 */ }
140
+ }
102
141
  return { ok: true, path, replaced: all ? hits : 1, bytesBefore: text.length, bytesAfter: out.length };
103
142
  }
@@ -28,6 +28,13 @@ const numericKinds = [
28
28
  }), [DIMENSIONS.可维护性]],
29
29
  // 同名常量跨文件重复定义(DRY)——kind=duplicate-const,由 lib/checks/dup-const.js 消费
30
30
  ['duplicate-const', (r) => r?.kind === 'duplicate-const', (r) => ({}), [DIMENSIONS.可维护性]],
31
+ // 逐文件扫描实现过多(仓库级;2026-10-16 由 bench-template 的 scan-fs-hotspots 交接)——
32
+ // kind=multi-file-scanners,由 lib/checks/fs-scanner.js 消费;min_occurrences=阈值(默认 3)。
33
+ // ⚠️ 必须在这里登记:registry.js 对带 kind 的规则会查 RULE_COMPILERS,查不到就
34
+ // **静默丢弃**(报「未知规则类型 kind=…」)——实测本规则一开始就是这么消失的 ✗
35
+ ['multi-file-scanners', (r) => r?.kind === 'multi-file-scanners', (r) => ({
36
+ minOccurrences: Number(r.min_occurrences) || 3,
37
+ }), [DIMENSIONS.性能 || DIMENSIONS.可维护性]],
31
38
  // 注释冗余密度(用户规则反馈①)——显式 kind 或 id 含 comment-density,
32
39
  // threshold 字段承载密度阈值(0~1,默认 0.4 由检查器兜底)
33
40
  ['comment-density', (r) => r?.kind === 'comment-density' || /comment-density/i.test(String(r?.id || '')), (r) => ({
package/lib/self/index.js CHANGED
@@ -9,7 +9,7 @@
9
9
  */
10
10
 
11
11
 
12
- export const VERSION = '2.9.1'; // 2.9.1:AI 自设工作区路径(数组 + API,注入优先显示)+ 修 handleHttp 丢弃 JSON 字符串 body(工具/CLI 的 POST body 全丢)+ 副本漂移检查补「文件清单」。历史:2.9.0:审计接入 tree-sitter(语法树优先、token 级回退;assets/tree-sitter 钉 web-tree-sitter@0.25.10)。历史:2.8.9:审计精筛升级为**列级**(astConfirmSpan 按规则 opt-in)。历史:2.8.5:修 runNpm 不传 cwd —— npm pack/publish 会跑在**宿主进程的 cwd**(本机是 DSH 安装目录 /volume1/@appstore/DeepSeekHarness-NAS)而不是目标包目录。
12
+ export const VERSION = '2.9.4'; // 2.9.4:修「文件头豁免提示的标记写了不生效」——判定口径抽成唯一函数(exemptForFinding 与反查提示共用)+ 补齐注册表缺口(quality 增加 semantic/dataflow/duplicate-const/repeated-string 与非安全类 regex 兜底、style 补 min-length/max-lines/max-complexity/max-depth、sensitive 补 semantic)+ 所有 finding 产出后统一校正提示为「真能豁免的标记」;自证:写了不生效的组合 24 → 0。历史:2.9.3:FS 热点扫描并入审计(判据②扩到函数体 + 仓库级 multi-file-scanners + 独立 CLI)。
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.9.1",
3
+ "version": "2.9.4",
4
4
 
5
5
  "description": "DSH git 自动提交推送插件——统一函数入口架构(规则/审计/git/自身/侧边栏/评分/豁免/上下文/HTTP/测试十大总入口)",
6
6
  "type": "module",
@@ -1,10 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * dsh-git-push — 版本列表文档生成器(doc-version:版本表由 git log 权威生成,聚合入表防手写版本记录漂移)
3
+ * dsh-git-push — 版本列表文档生成器(doc-version:版本表由**文件**权威生成,防手写版本记录漂移)
4
4
  * dsh-skip-i18n: 用户可见文案硬编码为产品设计
5
5
  *
6
6
  * 分体式文档三兄弟之一(doc-tree 文件树 / doc-func 函数列表 / doc-version 版本列表)。
7
- * 从 git log 聚合提交标题里的 X.Y.Z 版本号,生成版本记录表 markdown,
7
+ * 版本表数据源 = `docs/releases.json`(每版一行说明)+ 版本真源文件(package.json 等)
8
+ * + `version-metrics.json`(可选量化记录);**不读 git log**(2026-10-16 改,原因见
9
+ * readme-gen.mjs 的 buildReadmeVersionTable 注释)。
8
10
  * 写入宿主 md(README 有 dshgp-version 标记块用 README,否则 docs/ 带块 md)。
9
11
  * 复用 readme-gen.mjs 的 buildReadmeVersionTable(版本聚合逻辑单一事实源)。
10
12
  *
@@ -17,7 +19,7 @@ import { readFileSync, writeFileSync, existsSync } from 'node:fs';
17
19
  import { join, resolve, relative, basename, dirname } from 'node:path';
18
20
  import { fileURLToPath } from 'node:url';
19
21
  import { findMarkedHostMd } from './doc-tree.mjs';
20
- import { buildReadmeVersionTable } from './readme-gen.mjs';
22
+ import { buildReadmeVersionTable, detectVersionSource, projectVersionOf, readReleases, VERSION_SOURCES } from './readme-gen.mjs';
21
23
 
22
24
  const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
23
25
  const MARKER = 'dshgp-version';
@@ -25,99 +27,26 @@ const MARK_START = `<!-- ${MARKER}:start -->`;
25
27
  const MARK_END = `<!-- ${MARKER}:end -->`;
26
28
 
27
29
  /**
28
- * 版本表「最新行」的来源:
29
- * · npm 项目(项目根有 package.json)默认取 package.json.version —— 它才是版本号权威源
30
- * (scan-version 门禁也正是比对 package.json),因此发版流程无需「先提交再生成再 amend」;
31
- * · 其余项目退回 git log 聚合(老项目行为不变)。
32
- * @param {string} root 项目根
33
- * @param {string} [explicit] 'package.json' | 'git-log'(显式覆盖,留空则自动识别)
30
+ * 版本源探测与读取**已迁到 scripts/readme-gen.mjs**(版本表生成与版本源同源,避免两处各写一份)。
31
+ * 这里只做再导出,保持旧调用方的 import 路径不变。
32
+ *
33
+ * ⚠️ 2026-10-16 起:版本表**不再读 git log**(`detectVersionSource` 不再回退 'git-log')——
34
+ * 表内容由 `docs/releases.json` + 版本真源文件生成,普通提交不再动表、也不再逼人「为门禁升版本」。
34
35
  */
35
- /* 旧的 resolveVersionSource 已删除:它只判断"有没有 package.json",
36
- 已被下方 detectVersionSource/projectVersionOf 版本取代(非 npm 项目需按类型识别)。 */
37
-
38
- /** 读项目 package.json 的 version;读不到返回空串(不抛错,退回 git log 行)。 */
39
- /** 支持的项目类型 → 版本文件(数组顺序即探测优先级)。
40
- * ⚠️ 为什么需要这个表:只判断"有没有 package.json"会把非 npm 项目误判为 git-log 聚合
41
- * (用户指出:package.json 只是 **npm 项目的默认源**,工具应能识别项目类型自动切换)。 */
42
- const VERSION_SOURCES = [
43
- { id: 'package.json', file: 'package.json', read: (t) => JSON.parse(t).version },
44
- { id: 'pyproject.toml', file: 'pyproject.toml', read: (t) => (t.match(/^\s*version\s*=\s*["']([^"']+)["']/m) || [])[1] },
45
- { id: 'Cargo.toml', file: 'Cargo.toml', read: (t) => (t.match(/^\s*version\s*=\s*["']([^"']+)["']/m) || [])[1] },
46
- { id: 'composer.json', file: 'composer.json', read: (t) => JSON.parse(t).version },
47
- { id: 'setup.cfg', file: 'setup.cfg', read: (t) => (t.match(/^\s*version\s*=\s*([^\s#]+)/m) || [])[1] },
48
- ];
49
-
50
- /** 按项目类型探测版本源;都不匹配则回退 git-log 聚合(老项目行为不变)。 */
51
- export function detectVersionSource(root) {
52
- for (const s of VERSION_SOURCES) {
53
- if (existsSync(join(root, s.file))) return s.id;
54
- }
55
- return 'git-log';
56
- }
57
-
58
- /** 版本源解析:显式指定优先;否则按项目类型自动识别。 */
59
- export function resolveVersionSource(root, explicit = '') {
60
- if (explicit) return explicit;
61
- return detectVersionSource(root);
62
- }
63
-
64
- /** 按已识别/指定的版本源读取版本号;读不到返回空串(不抛错,退回 git log 行)。 */
65
- export function projectVersionOf(root, source = '') {
66
- const src = source || detectVersionSource(root);
67
- const def = VERSION_SOURCES.find((s) => s.id === src);
68
- if (!def) return '';
69
- try {
70
- const v = def.read(readFileSync(join(root, def.file), 'utf8'));
71
- return v ? String(v).trim() : '';
72
- } catch {
73
- return '';
74
- }
75
- }
36
+ // 本地再导出(`export … from` 不产生本地绑定 ⇒ 必须先 import 再导出)
37
+ export { VERSION_SOURCES, detectVersionSource, projectVersionOf, readReleases };
76
38
 
77
39
  /** 兼容旧调用:等价于"按项目类型识别后取版本号"。 */
78
40
  export function packageVersionOf(root) {
79
41
  return projectVersionOf(root, detectVersionSource(root));
80
42
  }
81
43
 
82
- /** 生成版本列表 markdown(宿主块内容)。 */
83
- export function buildVersionListText(root, { versionSource = '' } = {}) {
44
+ /** 生成版本列表 markdown(宿主块内容)——**纯文件驱动,不读 git log**。
45
+ * 行内容来自 buildReadmeVersionTable(docs/releases.json + 版本真源 + version-metrics.json)。 */
46
+ export function buildVersionListText(root, _opts = {}) {
84
47
  const rows = buildReadmeVersionTable(root);
85
- const source = resolveVersionSource(root, versionSource);
86
- const pkg = source !== 'git-log' ? projectVersionOf(root, source) : '';
87
- // 只改**最新数据行**的版本号(rows[0]=表头、rows[1]=分隔行 ⇒ 数据从 rows[2] 起);
88
- // 日期与标题仍来自该行原本的 git 提交 —— 历史行完全不动。
89
- if (pkg && rows.length > 2) {
90
- const m = rows[2].match(/\d+\.\d+\.\d+/);
91
- if (m && m[0] !== pkg) rows[2] = rows[2].replace(m[0], pkg);
92
- } else if (pkg) {
93
- // 版本真源是 package.json:**git log 读不到时也必须出表**(此前这里产 0 行 ⇒ 整张表被写空)。
94
- // 提交历史不可读时,至少以 package.json 的版本号生成一条数据行,绝不产出空表。
95
- rows.push(`| ${pkg} | 版本号来自 package.json(提交历史不可读,内容待补) |`);
96
- }
97
- // ── 发布说明源(docs/releases.json):拆掉「最新行只能来自 git log」这个环 ──
98
- // 历史行的标题/日期仍来自 git log(无需维护);**当前版本**的标题可由本文件提供 ⇒
99
- // `apply`/`check` 在提交前就能产出与提交后**完全一致**的表,发版不再需要「先提交再生成再 amend」。
100
- // 取值优先级:本文件的当前版本标题 > git log 里同名版本行 > git log 最新行(版本号按 package.json 覆盖)。
101
- const releaseTitle = (() => {
102
- try {
103
- const p = join(root, 'docs', 'releases.json');
104
- if (!existsSync(p)) return '';
105
- const j = JSON.parse(readFileSync(p, 'utf8'));
106
- const v = j && typeof j === 'object' ? j[pkg] : '';
107
- return typeof v === 'string' ? v.trim() : '';
108
- } catch {
109
- return ''; // 文件缺失/非法 JSON:静默退回纯 git log 行为(不因辅助源报错而阻断发版)
110
- }
111
- })();
112
- if (pkg && releaseTitle) {
113
- if (rows.length > 2) {
114
- const cells = rows[2].split('|').map((s) => s.trim());
115
- if (cells[1] === pkg) rows[2] = `| ${pkg} | ${releaseTitle} |`; // 版本已在 git log:只换标题
116
- else rows.splice(2, 0, `| ${pkg} | ${releaseTitle} |`); // git log 尚无该版本:插入为最新行
117
- } else {
118
- rows.push(`| ${pkg} | ${releaseTitle} |`); // 提交历史不可读:至少出这一行
119
- }
120
- }
48
+ const source = detectVersionSource(root) || '(无版本源文件)';
49
+ const pkg = projectVersionOf(root);
121
50
  return { text: `## 版本列表\n\n${rows.join('\n')}\n`, rows: rows.length - 2, source, packageVersion: pkg };
122
51
  }
123
52
 
@@ -157,8 +86,8 @@ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.ur
157
86
  // 版本来源可显式指定(package.json | git-log);不传则按项目类型自动识别(有 package.json 即 npm 项目)
158
87
  const srcIdx = args.indexOf('--version-source');
159
88
  const versionSource = srcIdx !== -1 && args[srcIdx + 1] ? String(args[srcIdx + 1]) : '';
160
- if (versionSource && versionSource !== 'package.json' && versionSource !== 'git-log') {
161
- console.log(`❌ --version-source 只接受 package.json 或 git-log,收到:${versionSource}`);
89
+ if (versionSource && versionSource !== 'package.json') {
90
+ console.log(`❌ --version-source 只接受 package.json(版本表已改为文件驱动,不再支持 git-log),收到:${versionSource}`);
162
91
  process.exit(1);
163
92
  }
164
93
  const host = findMarkedHostMd(root, MARKER);
@@ -195,31 +195,81 @@ export function readVersionMetrics(repoPath) {
195
195
  } catch { return {}; }
196
196
  }
197
197
 
198
+ /** 支持的项目类型 → 版本文件(数组顺序即探测优先级)。
199
+ * 2026-10-16 从 doc-version.mjs 迁来(版本源逻辑与版本表生成同源,避免两处各写一份)。 */
200
+ export const VERSION_SOURCES = [
201
+ { id: 'package.json', file: 'package.json', read: (t) => JSON.parse(t).version },
202
+ { id: 'pyproject.toml', file: 'pyproject.toml', read: (t) => (t.match(/^\s*version\s*=\s*["']([^"']+)["']/m) || [])[1] },
203
+ { id: 'Cargo.toml', file: 'Cargo.toml', read: (t) => (t.match(/^\s*version\s*=\s*["']([^"']+)["']/m) || [])[1] },
204
+ { id: 'composer.json', file: 'composer.json', read: (t) => JSON.parse(t).version },
205
+ { id: 'setup.cfg', file: 'setup.cfg', read: (t) => (t.match(/^\s*version\s*=\s*([^\s#]+)/m) || [])[1] },
206
+ ];
207
+
208
+ /** 按项目类型探测版本源;都不匹配返回 ''(**不再回退 git log** —— 见 buildReadmeVersionTable 说明)。 */
209
+ export function detectVersionSource(root) {
210
+ for (const s of VERSION_SOURCES) {
211
+ if (existsSync(join(root, s.file))) return s.id;
212
+ }
213
+ return '';
214
+ }
215
+
216
+ /** 按已识别/指定的版本源读取版本号;读不到返回空串(不抛错)。 */
217
+ export function projectVersionOf(root, source = '') {
218
+ const src = source || detectVersionSource(root);
219
+ const def = VERSION_SOURCES.find((s) => s.id === src);
220
+ if (!def) return '';
221
+ try {
222
+ const v = def.read(readFileSync(join(root, def.file), 'utf8'));
223
+ return v ? String(v).trim() : '';
224
+ } catch {
225
+ return '';
226
+ }
227
+ }
228
+
229
+ /** 读可选的「版本发布说明」文件(`<repo>/docs/releases.json`)——版本表行内容的真源。 */
230
+ export function readReleases(repoPath) {
231
+ try {
232
+ const p = join(repoPath, 'docs', 'releases.json');
233
+ if (!existsSync(p)) return {};
234
+ const data = JSON.parse(readFileSync(p, 'utf8'));
235
+ return data && typeof data === 'object' && !Array.isArray(data) ? data : {};
236
+ } catch { return {}; }
237
+ }
238
+
239
+ /**
240
+ * 版本记录表 markdown(**全部来自文件,不读 git log**)。
241
+ *
242
+ * 数据源:
243
+ * · `docs/releases.json` —— 每个版本一行的说明(历史行真源)
244
+ * · 版本真源文件(package.json / pyproject.toml / Cargo.toml / composer.json / setup.cfg)
245
+ * —— 当前版本号(releases.json 未登记时也保证有这一行)
246
+ * · `version-metrics.json` —— 可选量化记录,拼到该行内容最前
247
+ *
248
+ * 为什么改成文件驱动(2026-10-16):此前行内容取自 **git log 提交标题** ⇒
249
+ * · 任何不带版本号的普通提交都会改动「最新行」的内容/条数 ⇒ 版本表门禁报漂移 ✗
250
+ * · 门禁一旦红了,就只好「为门禁升版本」——把版本号变成讨好门禁的产物 ✗(本末倒置)
251
+ * 改为文件驱动后:**普通提交完全不动版本表**;发版只改 `docs/releases.json` 一行 ✓。
252
+ *
253
+ * `listVersionCommits` 仍保留导出(旧调用方/测试可用),但本函数不再调用它。
254
+ */
198
255
  export function buildReadmeVersionTable(repoPath) {
199
- const groups = listVersionCommits(repoPath);
256
+ const releases = readReleases(repoPath);
200
257
  const metrics = readVersionMetrics(repoPath);
258
+ const current = projectVersionOf(repoPath);
201
259
  const lines = ['| 版本 | 内容 |', '|------|------|'];
202
- if (groups.length) {
203
- const by = new Map();
204
- for (const g of groups) {
205
- // 每个识别到的 X.Y.Z 独立成行(不把 patch>0 归并到 x.y.0):
206
- // 归并会让 1.0.1~1.0.4 的内容并进 1.0.0 行,且 doc-version check 对
207
- // 真实逐版本记录(如 dsh-session-migrate)报漂移。
208
- const key = g.versionStr;
209
- if (!by.has(key)) by.set(key, []);
210
- by.get(key).push(scrubConvWording(g.label.replace(/^\S+\s*/, '')));
211
- }
212
- const keys = [...by.keys()].sort((a, b) => {
213
- const [am, ai, ap] = a.split('.').map(Number);
214
- const [bm, bi, bp] = b.split('.').map(Number);
215
- return (bm - am) || (bi - ai) || (bp - ap);
216
- });
217
- for (const k of keys) {
218
- const body = by.get(k).filter(Boolean).join(';');
219
- // 有量化记录就拼到最前(一眼看出这版改善了什么),没有则保持原样
220
- const metric = metrics[k] ? `${metrics[k]}——${body}` : body;
221
- lines.push(`| ${k} | ${metric} |`);
222
- }
260
+ const keys = new Set(Object.keys(releases));
261
+ if (current) keys.add(current);
262
+ const ordered = [...keys].sort((a, b) => {
263
+ const [am, ai, ap] = a.split('.').map(Number);
264
+ const [bm, bi, bp] = b.split('.').map(Number);
265
+ return (bm - am) || (bi - ai) || (bp - ap);
266
+ });
267
+ for (const k of ordered) {
268
+ const raw = releases[k] || (k === current ? '(本版说明待补:docs/releases.json 未登记)' : '');
269
+ const body = scrubConvWording(String(raw));
270
+ if (!body) continue;
271
+ const metric = metrics[k] ? `${metrics[k]}——${body}` : body;
272
+ lines.push(`| ${k} | ${metric} |`);
223
273
  }
224
274
  return lines;
225
275
  }