dsh-git-push 2.9.1 → 2.9.3

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.
@@ -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.3'; // 2.9.3:FS 热点静态扫描并入审计——判据②并入 performance/repeat-identical-call(作用域扩到「循环体 ∪ 同一函数体」+ fs 属性类白名单 + 第三方资产排除);新增仓库级规则 performance/multi-file-scanners(notice/默认开/阈值 3);新增判据单一实现 lib/ast/fs-hotspots.js 与独立 CLI scripts/scan-fs-hotspots.mjs;修抽取器双重计数与新 kind 未登记被静默丢弃。历史:2.9.2:版本表改为文件驱动(不读 git log)+ 5 个占位语言规则包首版真规则。
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.3",
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
  }
@@ -0,0 +1,107 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * dsh-git-push — FS 热点静态扫描(独立 CLI,咨询性,恒退出码 0)
4
+ *
5
+ * 用法:
6
+ * node scripts/scan-fs-hotspots.mjs [root] [--json] [--top N] [--include 子串] [--exclude 子串] [--include-tests]
7
+ *
8
+ * 判据(六类,与审计规则 performance/multi-file-scanners 同源 ✓):
9
+ * ① stat 热点 按 stat 调用点数排序的文件
10
+ * ② 重复 stat 同一函数内同一表达式 stat ≥2 次
11
+ * ③ 重复 readdir 同一函数内同一表达式 readdir ≥2 次
12
+ * ④ 遍历入口 readdir + (自递归 或 已知 walker 名)
13
+ * ⑤ 逐文件扫描实现 同一函数内既有 readdir 又有 stat
14
+ * ⑥ 汇总 totals
15
+ *
16
+ * 【为什么不自己再写一遍判据】判据实现只在 lib/ast/fs-hotspots.js 一份 —— 审计规则
17
+ * (lib/checks/fs-scanner.js)与 CLI 都用它 ⇒ 不会出现「脚本说 9 个、规则说 7 个」的漂移 ✗
18
+ * (2026-10-16 由 bench-template 的 scan-fs-hotspots.mjs 交接而来:规则化 + 复用插件 tokenizer)
19
+ * 【退出码恒 0】这是**咨询性报告**,不拦提交(要拦走审计规则 ✓)
20
+ * dsh-skip-i18n: 用户可见文案硬编码为产品设计
21
+ */
22
+ import { readFileSync, readdirSync } from 'node:fs';
23
+ import { join, relative, extname } from 'node:path';
24
+ import { scanFsHotspots, FS_WALKERS } from '../lib/ast/fs-hotspots.js';
25
+
26
+ /** 默认豁免目录(与审计规则口径一致:审计侧由 collector 跳过,这里显式列同一份)。 */
27
+ const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'release', '.trash', '.auto-update-tmp', 'cache-index', 'cache-gifs', '__pycache__']);
28
+ const TEST_DIRS = new Set(['test', 'tests']);
29
+ const EXTS = new Set(['.js', '.mjs', '.cjs']);
30
+
31
+ function parseArgs(argv) {
32
+ const o = { root: process.cwd(), json: false, top: 10, include: '', exclude: '', includeTests: false };
33
+ for (let i = 0; i < argv.length; i += 1) {
34
+ const a = argv[i];
35
+ if (a === '--json') o.json = true;
36
+ else if (a === '--top') o.top = Number(argv[++i]) || 10;
37
+ else if (a === '--include') o.include = String(argv[++i] || '');
38
+ else if (a === '--exclude') o.exclude = String(argv[++i] || '');
39
+ else if (a === '--include-tests') o.includeTests = true;
40
+ else if (!a.startsWith('--')) o.root = a;
41
+ }
42
+ return o;
43
+ }
44
+
45
+ /** 递归收集待扫文件(跳过 SKIP_DIRS;test/tests 默认跳过,--include-tests 纳入 ✓)。 */
46
+ function collectFiles(dir, o, out = []) {
47
+ let ents = [];
48
+ try {
49
+ ents = readdirSync(dir, { withFileTypes: true });
50
+ } catch {
51
+ return out; // 权限/竞态:跳过该目录,不让整轮失败
52
+ }
53
+ for (const e of ents) {
54
+ const full = join(dir, e.name);
55
+ if (e.isDirectory()) {
56
+ if (SKIP_DIRS.has(e.name)) continue;
57
+ if (!o.includeTests && TEST_DIRS.has(e.name)) continue;
58
+ collectFiles(full, o, out);
59
+ } else if (EXTS.has(extname(e.name))) {
60
+ const rel = relative(o.root, full);
61
+ if (o.include && !rel.includes(o.include)) continue;
62
+ if (o.exclude && rel.includes(o.exclude)) continue;
63
+ out.push(full);
64
+ }
65
+ }
66
+ return out;
67
+ }
68
+
69
+ const opts = parseArgs(process.argv.slice(2));
70
+ const files = collectFiles(opts.root, opts);
71
+ const fileTexts = files.map((full) => {
72
+ try {
73
+ return { path: relative(opts.root, full), text: readFileSync(full, 'utf8') };
74
+ } catch {
75
+ return { path: relative(opts.root, full), text: '' };
76
+ }
77
+ });
78
+ const agg = scanFsHotspots(fileTexts);
79
+
80
+ if (opts.json) {
81
+ console.log(JSON.stringify({
82
+ root: opts.root,
83
+ includeTests: opts.includeTests,
84
+ walkerNames: FS_WALKERS,
85
+ totals: agg.totals,
86
+ hot: agg.hot.slice(0, opts.top),
87
+ scanners: agg.scanners,
88
+ dupStats: agg.dupStats,
89
+ dupReaddirs: agg.dupReaddirs,
90
+ walkers: agg.walkers,
91
+ }, null, 2));
92
+ } else {
93
+ const t = agg.totals;
94
+ console.log(`FS 热点扫描(${t.files} 文件 · stat ${t.stats} · readdir ${t.readdirs} · 重复 stat ${t.dupStats} · 重复 readdir ${t.dupReaddirs} · 遍历入口 ${t.walkerCalls} · 逐文件扫描实现 ${t.scanners})`);
95
+ console.log('\n① stat 热点(按 stat 调用点数):');
96
+ for (const h of agg.hot.slice(0, opts.top)) console.log(` ${String(h.stats).padStart(3)} stat / ${String(h.readdirs).padStart(3)} readdir ${h.file}`);
97
+ console.log('\n④ 遍历入口(readdir + 自递归/已知 walker):');
98
+ if (!agg.walkers.length) console.log(' (无)');
99
+ for (const w of agg.walkers) console.log(` ${w.file}:${w.line} ${w.fn}() → ${w.calls}`);
100
+ if (agg.dupStats.length || agg.dupReaddirs.length) {
101
+ console.log('\n②③ 同函数内重复的 stat/readdir(可合并成一次):');
102
+ for (const d of [...agg.dupStats, ...agg.dupReaddirs]) console.log(` ${d.file}:${d.line} ${d.fn}() ${d.expr}`);
103
+ }
104
+ console.log(`\n⑤ 逐文件扫描实现(readdir+stat 同函数,共 ${agg.scanners.length} 个;> 3 时审计规则 performance/multi-file-scanners 会报 notice):`);
105
+ for (const s of agg.scanners) console.log(` ${s.file}:${s.line} ${s.fn}()`);
106
+ }
107
+ process.exit(0); // 咨询性:恒 0(要拦提交走审计规则 ✓)
@@ -31,7 +31,7 @@ generatedBy: deepseek-official/deepseek-v4-flash · EIGHTfs 2026-10-02
31
31
  | `git_cred_env` | — | 输出凭据环境变量前缀(SSH `GIT_SSH_COMMAND` / HTTPS `GIT_ASKPASS`,不含明文) |
32
32
  | `git_gen_ssh_key` | `email`(必填), `force?` | 生成 SSH 密钥对(写入插件配置目录;私钥不出本机,公钥整行回传) |
33
33
  | `git_sluice` | `args`(必填) | git 命令透传(凭据自动注入;返回 status + stdout/stderr 原文) |
34
- | `git_api` | `path?`, `method?`, `query?`, `body?` | **直接调用本插件 28 条 HTTP API**(内部走 `handleHttp` 同一条代码路径,不另写实现);不传 `path` 则列出全部接口 |
34
+ | `git_api` | `path?`, `method?`, `query?`, `body?` | **直接调用本插件 35 条 HTTP API**(内部走 `handleHttp` 同一条代码路径,不另写实现);不传 `path` 则列出全部接口 |
35
35
 
36
36
  典型流程:`git_scan` 看改动 → `code_audit` 自查 → `git_commit_push`(审计通过才推)。
37
37
 
@@ -321,3 +321,20 @@ node scripts/readme-gen.mjs <repoPath> [--write <path>] [--template <path>]
321
321
  | 函数/复杂度被报为 blocker | 规则 `severity` 是上限,检查器不越级;报 blocker 说明 yml 里写的就是 error/blocker |
322
322
  | 克隆大文件反复失败 | 失败项的分片必须保留(`.dsh-parts`)才能跨轮 Range 续传;同轮清理分片会让大文件永远从 0 重来 |
323
323
  | 建了远端但推送报「远端查不到分支 master(API 404 / ls-remote 无该分支)」 | `git_remote_create` 旧版把 origin 写成 **REST API 端点**(`https://api.github.com/repos/<o>/<r>` ✗ 那不是 git remote)⇒ `git push/fetch origin` 必然失败。2026-10-09 已修(`lib/git/remote.js`):origin 统一写 `https://github.com/<o>/<r>`,并**自愈**——仓库已存在但 origin 仍是 API 形态时 `set-url` 改回;返回体新增 `originAction`(`add`/`repair`/`keep`)。旧仓库手工修:`git remote set-url origin ssh://git@ssh.github.com:443/<o>/<r>.git` 再 `git push -u origin master`(凭据用插件 `id_rsa` + `-p 443`)。⚠️ `lib/git/clone.js` 仍写 API 形态 origin(设计如此,插件自身推送不受影响,但 `git push origin` 会失败) |
324
+
325
+ ## 端点:AI 自设工作区路径(workspace-paths)
326
+
327
+ 环境注入里的「当前工作目录 cwd」原先取自**会话文件**(`agent.session.header.cwd`),实测可能是**陈旧路径**
328
+ (本机注入过 `0.1.6-alpha.1` 的旧工作区 ⇒ 反而误导)⇒ 改为让 AI 自己登记真实工作区:
329
+
330
+ | 方法 | 路径 | 说明 |
331
+ |---|---|---|
332
+ | GET | `/api/git-push/workspace-paths` | 读清单 + 注入预览(`injection` / `injectionActive` / `file`) |
333
+ | POST | `/api/git-push/workspace-paths` | 写清单:`{paths:[…], mode:"set"\|"add"\|"remove"}`;`{clear:true}` 清空 |
334
+
335
+ - **校验**:只收**绝对路径**、必须**存在且是目录**、去重、上限 20;全被拒或缺参一律 **400**(不返回"成功但空")
336
+ - **存储**:`<配置目录>/workspace-paths.json`(`paths` / `updatedAt` / `updatedBy`,原子写入)
337
+ - **注入**:自设清单**优先显示**(逐条 + 修改入口),会话 cwd 降级标注为「仅兜底,可能陈旧」;
338
+ 注入缓存键带上自设清单(否则改完不刷新)
339
+ - **调用**:`git_api({path:'workspace-paths', method:'POST', body:'{"paths":["/abs/path"]}'})`
340
+ - **回归**:`test/test-workspace-paths.mjs`(8 例,含「经 handleHttp 的 JSON 字符串 body」)