dsh-git-push 2.10.5 → 2.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/.auditignore +2 -4
  2. package/README.md +78 -1487
  3. package/lib/app/audit-api.js +1 -1
  4. package/lib/app/command-registry.js +1 -1
  5. package/lib/app/inject-text.js +0 -1
  6. package/lib/app/tool-call.js +3 -3
  7. package/lib/ast/io-risk-loop.js +1 -1
  8. package/lib/ast/tokenizer.js +76 -1
  9. package/lib/ast/treesitter.js +78 -14
  10. package/lib/audit/collector.js +9 -1
  11. package/lib/audit/finding.js +8 -1
  12. package/lib/audit/history.js +1 -1
  13. package/lib/audit/orchestrate.js +59 -1
  14. package/lib/audit/report-yaml.js +5 -1
  15. package/lib/audit-rules/audit-rules-comment.yml +0 -68
  16. package/lib/audit-rules/audit-rules-csharp.yml +82 -0
  17. package/lib/audit-rules/audit-rules-structure.yml +2 -3
  18. package/lib/cli/commands-audit.mjs +1 -1
  19. package/lib/core/exec.js +109 -1
  20. package/lib/git/clone-history-mode.js +25 -4
  21. package/lib/git/push.js +1 -1
  22. package/lib/rule/loader.js +5 -1
  23. package/lib/score/index.js +63 -4
  24. package/lib/self/index.js +1 -1
  25. package/lib/skip-dirs.js +6 -3
  26. package/package.json +6 -1
  27. package/scripts/doc-tree.mjs +4 -2
  28. package/scripts/doc-version.mjs +4 -4
  29. package/scripts/{readme-gen.mjs → version-source.mjs} +8 -153
  30. package/skills/dev/dsh-git-push.md +3 -11
  31. package/skills/guide/guide-cli-scripts.md +0 -2
  32. package/assets/tree-sitter/LICENSE +0 -21
  33. package/assets/tree-sitter/README.md +0 -69
  34. package/assets/tree-sitter/VERSIONS.txt +0 -1
  35. package/assets/tree-sitter/tree-sitter-javascript.wasm +0 -0
  36. package/assets/tree-sitter/tree-sitter-python.wasm +0 -0
  37. package/assets/tree-sitter/tree-sitter-typescript.wasm +0 -0
  38. package/assets/tree-sitter/tree-sitter.js +0 -3980
  39. package/assets/tree-sitter/tree-sitter.wasm +0 -0
  40. package/lib/readme-templates/readme.yml +0 -38
  41. package/lib/vendor/js-yaml/LICENSE +0 -21
  42. package/lib/vendor/js-yaml/js-yaml.mjs +0 -3073
  43. package/scripts/scrub-user-wording.mjs +0 -420
@@ -31,7 +31,7 @@ decisions:
31
31
  reason: "现有 docs/(复数)已建立索引习惯,改名纯成本;新增目录一律单数,存量 docs/ 作为历史约定保留"
32
32
  - item: "script/ config/ dist/ log/"
33
33
  keep: false
34
- reason: "无构建步骤(源码即产物);配置走 settings 机制 + lib/ 内 yml 规则数据(audit-rules/ readme-templates/ 同源部署,不抽顶层)"
34
+ reason: "无构建步骤(源码即产物);配置走 settings 机制 + lib/ 内 yml 规则数据(audit-rules/ 同源部署,不抽顶层)"
35
35
  - item: "skills/"
36
36
  keep: true
37
37
  reason: "DSH 插件特性:注入给 AI 的手册(dsh-git-push.md / dsh-git-push-functions.md / git-workflow-gitpush/),通用规范未覆盖"
@@ -46,7 +46,7 @@ principles:
46
46
  - "一致性优先于花哨:同类文件放同目录,同目录命名风格统一"
47
47
  - "统一单数:所有功能目录用单数(tool/、test/、doc/、lib/),不用复数(tools/、tests/、docs/、libs/)"
48
48
  - "工具与源码同库:cli.mjs 根级 + lib/plugin-tools.js 注册 agent 工具,不建空 tool/ 目录"
49
- - "规则数据随代码:audit-rules/*.yml、readme-templates/*.yml 放 lib/ 子目录(files 白名单 + 相对路径解析依赖)"
49
+ - "规则数据随代码:audit-rules/*.yml 放 lib/ 子目录(files 白名单 + 相对路径解析依赖)"
50
50
  - "最小可用:不预设未来需求,目录按需添加"
51
51
 
52
52
  # ============================================================
@@ -86,7 +86,6 @@ directory_roles:
86
86
  - "audit.js - 审计引擎(L0 静态 + 规则执行)"
87
87
  - "rule-packs.js - YAML 规则装载/编译"
88
88
  - "audit-rules/ - 规则数据(nodejs/frontend/comment/dsh/npm/version/template/private/structure)"
89
- - "readme-templates/ - README 模板 yml"
90
89
  - "plugin-*.js - 装配层(host 等价:工具注册/HTTP/设置/审计服务接线)"
91
90
  - "client.js viewer.js- 客户端 UI(DSH 命名空间内)"
92
91
  dependencies: "模块间单向依赖、无环(拆分时保证);装配层依赖业务模块,业务模块不依赖装配层"
@@ -101,7 +101,7 @@ async function runStandardAudit(root, flags) {
101
101
  opts.ownership = probeRepoOwnership(root); // 与插件工具同参:隐私规则只对自有仓库生效
102
102
  const weights = pluginEqualWeights(cfg, flags);
103
103
  const auditResult = full ? await auditFull(root, opts) : await auditWithScope(root, opts);
104
- const quality = scoreQuality(auditResult.findings, weights, { files: auditResult.files });
104
+ const quality = scoreQuality(auditResult.findings, weights, { files: auditResult.files, dimFileCounts: auditResult.dimFileCounts });
105
105
  if (flags.json) {
106
106
  console.log(JSON.stringify({ ok: true, repo: root, scope: auditResult.scope, summary: auditResult.summary, quality, findings: auditResult.findings, files: auditResult.files, analysisCoverage: auditResult.analysisCoverage || null, yaml: auditResult.yaml }, null, 2));
107
107
  return;
package/lib/core/exec.js CHANGED
@@ -6,7 +6,7 @@
6
6
  * 所有 git 调用都经过此模块,便于统一超时与错误规整,避免各调用点各写一份。
7
7
  */
8
8
 
9
- import { execFile, execFileSync, spawnSync } from 'node:child_process';
9
+ import { execFile, execFileSync, spawn, spawnSync } from 'node:child_process';
10
10
  import { existsSync, statSync } from 'node:fs';
11
11
  import { delimiter as pathDelimiter, join } from 'node:path';
12
12
 
@@ -162,3 +162,111 @@ export function runGitAsync(args, { cwd = '', timeoutMs = 120_000, env = {}, noM
162
162
  });
163
163
  });
164
164
  }
165
+
166
+ /* ─────────────────── 流式执行:按「无进展」判停摆 ─────────────────── */
167
+
168
+ /**
169
+ * 流式 git 执行:**只判「有没有进展」,不设固定总时长**。
170
+ *
171
+ * 为什么需要:`runGit` 是 execFileSync + 死超时(默认 120s)。对大仓库的 `git fetch`
172
+ * 来说这必然半途而废 —— 实测 6.9GB / 7374 文件的仓库,fetch 要跑十几分钟以上,
173
+ * 但它其实一直在正常下载(`--progress` 的百分比行持续刷新)。真正该防的不是"慢",
174
+ * 是"卡住不动":所以这里改成**只要有输出就把看门狗往后推**,
175
+ * 连续 `stallLimit` 完全没有输出才判定停摆并结束进程。
176
+ *
177
+ * 与 runGit 的关系:语义一致(同前置参数、同镜像注入、同 DSH_GIT_ENFORCE_PASS 门禁),
178
+ * 区别只在于**超时判据**与"必须流式读 stderr 才能看见进度"。
179
+ *
180
+ * @param {string[]} args git 参数(自动前置 GIT_GLOBAL_ARGS)
181
+ * @param {{cwd?:string, env?:object, noMirror?:boolean, stallMs?:number,
182
+ * onProgress?:(line:string)=>void}} [o]
183
+ * stallMs:连续多少毫秒无任何输出算停摆(未传则读 DSH_GIT_FETCH_STALL_MS,再缺省 300000 = 5 分钟)
184
+ * @returns {Promise<{ok:boolean, stdout:string, stderr:string, stalled:boolean, ms:number}>}
185
+ * `stalled=true` 表示是按"停摆"结束的(不是 git 自己报错)——
186
+ * 调用方据此提示"可重试续传",别把它当成仓库/网络错误。
187
+ */
188
+ export function runGitStream(args, { cwd = '', env = {}, noMirror = false, stallMs, onProgress } = {}) {
189
+ const base = GIT_GLOBAL_ARGS;
190
+ const bin = resolveGitBin();
191
+ if (!bin) return Promise.resolve({ ok: false, stdout: '', stderr: GIT_MISSING_MSG, stalled: false, ms: 0 });
192
+ const mirrorEnv = {};
193
+ if (!noMirror && GIT_READ_VERBS.has(String(args[0] || ''))) mirrorGitConfigEnv(mirrorEnv, { mode: 'read' });
194
+ // 停摆阈值优先级:显式传参 > 环境变量 > 默认 5 分钟。
195
+ // 默认值依据「fetch 带 --progress、正常下载会持续刷行」估计;若现场遇到长时间静默
196
+ // 但仍在工作的阶段(大 pack 解压/校验无进度行),可用 DSH_GIT_FETCH_STALL_MS 放宽,
197
+ // 不必改代码重发版——这类阈值只能在真实大仓库上才调得准。
198
+ const groupKill = process.platform !== 'win32';
199
+ const envStall = Number(process.env.DSH_GIT_FETCH_STALL_MS);
200
+ const stallLimit = Number(stallMs) > 0 ? Number(stallMs) : (envStall > 0 ? envStall : 300_000);
201
+ const startedAt = Date.now();
202
+ return new Promise((resolve) => {
203
+ let child;
204
+ try {
205
+ child = spawn(bin, cwd ? base.concat(['-C', cwd], args) : base.concat(args), {
206
+ stdio: ['ignore', 'pipe', 'pipe'],
207
+ // detached:让 git 自成进程组。git fetch 会再派生 git-remote-https 这类传输子进程,
208
+ // 只结束直接子进程时孙进程可能仍占着连接、把下载拖在后台;按进程组结束才真停下。
209
+ // Windows 无进程组语义,退回单进程结束。
210
+ detached: groupKill,
211
+ env: { ...process.env, ...mirrorEnv, DSH_GIT_ENFORCE_PASS: '1', ...env },
212
+ });
213
+ } catch (e) {
214
+ resolve({ ok: false, stdout: '', stderr: String(e?.message || e), stalled: false, ms: 0 });
215
+ return;
216
+ }
217
+ let stdoutBuf = '';
218
+ let stderrTail = '';
219
+ let lastActivity = Date.now();
220
+ let stalled = false;
221
+ let settled = false;
222
+ const feed = (chunk, isErr) => {
223
+ lastActivity = Date.now();
224
+ const text = String(chunk);
225
+ if (!isErr) { stdoutBuf = (stdoutBuf + text).slice(-1024 * 1024); return; }
226
+ // 进度行用 \r 覆盖刷新:按换行/回车切开逐段回调,末段落进 tail 供失败时示错
227
+ stderrTail = (stderrTail + text).slice(-8192);
228
+ if (typeof onProgress === 'function') {
229
+ for (const line of text.split(/[\r\n]+/)) {
230
+ const t = line.trim();
231
+ if (!t) continue;
232
+ // 回调由调用方提供(进度推送/日志),它抛错会变成 data 事件的未捕获异常
233
+ // ⇒ 常驻宿主进程被一个进度回调带走。进度只是观测信息,绝不能因它中断传输。
234
+ try { onProgress(t); } catch { /* 进度回调失败不影响执行 */ }
235
+ }
236
+ }
237
+ };
238
+ child.stdout && child.stdout.on('data', (c) => feed(c, false));
239
+ child.stderr && child.stderr.on('data', (c) => feed(c, true));
240
+ // 看门狗只量"距上次输出多久";没有总时长上限(慢≠异常,卡住才是)
241
+ const tickMs = Math.min(5000, Math.max(1000, Math.floor(stallLimit / 4)));
242
+ // 结束整个进程组(含 git 派生的传输子进程);组的创建见 spawn 的 detached
243
+ const signal = (sig) => {
244
+ try {
245
+ if (groupKill && child.pid) process.kill(-child.pid, sig);
246
+ else child.kill(sig);
247
+ } catch {
248
+ try { child.kill(sig); } catch { /* 已退出 */ }
249
+ }
250
+ };
251
+ const watchdog = setInterval(() => {
252
+ if (Date.now() - lastActivity <= stallLimit) return;
253
+ stalled = true;
254
+ signal('SIGTERM');
255
+ // 宽限 3 秒仍未退出则强杀,避免残留子进程挂住调用方的 job
256
+ const killer = setTimeout(() => { signal('SIGKILL'); }, 3000);
257
+ if (killer && typeof killer.unref === 'function') killer.unref();
258
+ }, tickMs);
259
+ const finish = (code, errMsg) => {
260
+ if (settled) return;
261
+ settled = true;
262
+ clearInterval(watchdog);
263
+ const ok = !stalled && code === 0;
264
+ const errText = stalled
265
+ ? `连续 ${Math.round(stallLimit / 1000)}s 无任何进展,已结束(可重试续传,已下载部分不丢)`
266
+ : String(errMsg || stderrTail.trim() || `git 退出码 ${code}`);
267
+ resolve({ ok, stdout: ok ? stdoutBuf.trim() : '', stderr: ok ? '' : errText, stalled, ms: Date.now() - startedAt });
268
+ };
269
+ child.on('error', (e) => finish(null, String(e?.message || e)));
270
+ child.on('close', (code) => finish(code, ''));
271
+ });
272
+ }
@@ -15,7 +15,7 @@ import { githubFetch } from './api.js';
15
15
  import { fetchCommitChain } from './clone-history.js';
16
16
  import { replayHistory } from './clone-replay.js';
17
17
  import { createReplayIo } from './clone-replay-io.js';
18
- import { runGit } from './exec.js';
18
+ import { runGit, runGitStream } from './exec.js';
19
19
  import { initRepoCompat } from './init-compat.js';
20
20
  import { resolveOwnerVisibility, accessPlan, sshGitUrl } from './visibility.js';
21
21
  import { resolveSshKeys } from './credentials.js';
@@ -159,9 +159,30 @@ export async function cloneWithGitFetch({
159
159
  }
160
160
 
161
161
  // 显式 refspec:同时写入 refs/remotes/origin/<branch>,后续可据此建本地分支并设上游
162
- const fetchArgs = ['fetch', '--no-tags', ...(n ? [`--depth=${n}`] : []), 'origin', `+refs/heads/${branch}:refs/remotes/origin/${branch}`];
163
- const fetched = run(fetchArgs);
164
- if (!fetched?.ok) return fail(`git fetch 失败:${fetched?.stderr || '未知'}`);
162
+ // fetch 走**流式执行 + 停摆判据**(runGitStream),不用 runGit 的死超时:
163
+ // 大仓库 fetch 要跑十几分钟且一直在正常下载(--progress 行持续刷新),
164
+ // 固定 120s 必然半途而废;这里只在"连续无任何输出"时才结束(默认 5 分钟,
165
+ // 测试可用 deps.fetchStallMs 覆盖)。已下载的对象都在 .git 里,重试即续传。
166
+ const streamGit = deps.runGitStream || runGitStream;
167
+ const fetchArgs = ['fetch', '--progress', '--no-tags', ...(n ? [`--depth=${n}`] : []), 'origin', `+refs/heads/${branch}:refs/remotes/origin/${branch}`];
168
+ let lastProgress = '';
169
+ const fetched = await streamGit(fetchArgs, {
170
+ cwd: repoPath,
171
+ env: sshEnv,
172
+ noMirror: !plan.useMirror,
173
+ stallMs: Number(deps.fetchStallMs) > 0 ? Number(deps.fetchStallMs) : 300_000,
174
+ onProgress: (line) => { const t = String(line).trim(); if (t) lastProgress = t.slice(0, 160); },
175
+ });
176
+ steps.push({ cmd: fetchArgs.join(' '), ok: !!fetched?.ok, ms: fetched?.ms, stalled: !!fetched?.stalled, ...(fetched?.ok && lastProgress ? { lastProgress } : {}) });
177
+ if (!fetched?.ok) {
178
+ // 停摆与真失败必须区分:停摆是"没进展、可续传",不是仓库/网络错误。
179
+ // "可重试续传"这句在消费方兜底——上游 stderr 已带则去重,未带也保证提示到位,
180
+ // 避免换了流式实现后调用方看不到"已下载部分不丢"这个关键信息。
181
+ const detail = String(fetched?.stderr || '').trim() || '连续无任何进展';
182
+ return fail(fetched?.stalled
183
+ ? `git fetch 停摆:${detail}${/续传/.test(detail) ? '' : '(可重试续传,已下载部分不丢)'}`
184
+ : `git fetch 失败:${detail === '连续无任何进展' ? '未知' : detail}`);
185
+ }
165
186
 
166
187
  const rev = git(['rev-parse', `refs/remotes/origin/${branch}`], gitOpts);
167
188
  const sha = String(rev?.stdout || '').trim();
package/lib/git/push.js CHANGED
@@ -426,7 +426,7 @@ export function readmeCheckHint(repoPath) {
426
426
  const hasReadme = ['README.md', 'readme.md', 'README', 'readme'].some((n) => existsSync(join(repoPath, n)));
427
427
  return hasReadme
428
428
  ? { needed: true, hasReadme: true, hint: '提交前核对 README:功能表/版本记录/用法与本次改动一致,过时先改 README 再提交' }
429
- : { needed: true, hasReadme: false, hint: '仓库无 README,提交前先补(可用脚本 `node scripts/readme-gen.mjs <repo> [--write README.md]` 生成,或按 docs/ 文档模板写)' };
429
+ : { needed: true, hasReadme: false, hint: '仓库无 README,提交前先补(按 README 使用手册规范手工撰写)' };
430
430
  }
431
431
 
432
432
  /**
@@ -9,7 +9,11 @@ import { readFileSync, readdirSync, existsSync, writeFileSync } from 'node:fs';
9
9
  import { normalizeScopeRules } from './scope.js';
10
10
  import { join, dirname } from 'node:path';
11
11
  import { fileURLToPath } from 'node:url';
12
- import { load as yamlLoad } from '../vendor/js-yaml/js-yaml.mjs';
12
+ // js-yaml 走 npm 依赖(仓库内不保存副本)。
13
+ // 这里**故意用静态 import**:规则加载是启动关键路径,依赖没装上就应当在模块加载期
14
+ // 抛 ERR_MODULE_NOT_FOUND(错误里带包名,够响亮),而不是被 try/catch 吞成「0 条规则」
15
+ // 继续跑——静默无规则比启动失败更危险(口径见 docs/2026-10-28-弃零依赖引入npm与AST优先规则方案.MD D5)。
16
+ import { load as yamlLoad } from 'js-yaml';
13
17
 
14
18
  const __dirname = dirname(fileURLToPath(import.meta.url));
15
19
  export const RULE_YAML_DIR = join(__dirname, '..', 'audit-rules');
@@ -79,6 +79,30 @@ export function countByDimension(findings = []) {
79
79
  return counts;
80
80
  }
81
81
 
82
+ /**
83
+ * 每维度**命中文件数**(file 去重)——动态权重的分子。
84
+ *
85
+ * 与 countByDimension 同口径:`scoreImpact === 0` 的纯提示不计(它们本就不拉低分数);
86
+ * blocker 与 warning 在这里都只算「该文件命中过这个维度」一次——动态权重衡量的是
87
+ * **问题覆盖面**,不是问题条数(条数已由 countByDimension 的对数衰减承担)。
88
+ * 无文件的仓库级 finding(如 folder/locale)记为 1 个「文件」,避免整维度被算成 0 命中。
89
+ */
90
+ export function countHitFilesByDimension(findings = []) {
91
+ const sets = new Map();
92
+ for (const f of findings) {
93
+ if (f.scoreImpact === 0) continue;
94
+ const fileKey = f.file || '__repo__';
95
+ for (const dim of f.dimensions || []) {
96
+ if (!(dim in DEFAULT_WEIGHTS)) continue;
97
+ if (!sets.has(dim)) sets.set(dim, new Set());
98
+ sets.get(dim).add(fileKey);
99
+ }
100
+ }
101
+ const out = Object.fromEntries(DIMENSION_ORDER.map((d) => [d, 0]));
102
+ for (const [dim, set] of sets) out[dim] = set.size;
103
+ return out;
104
+ }
105
+
82
106
  /**
83
107
  * 计算 10 维度评分与总分(0-100)。
84
108
  *
@@ -95,7 +119,7 @@ export function countByDimension(findings = []) {
95
119
  * @returns {{dims: object, score: number|null, level: 'A'|'B'|'C'|'D'|'E'|null, weights: object, emptyResult?: boolean, emptyReason?: string}}
96
120
  */
97
121
  export function scoreQuality(findings = [], weights = {}, context = {}) {
98
- const { files = null, docsScore = null } = context;
122
+ const { files = null, docsScore = null, dimFileCounts = null } = context;
99
123
  // 0 文件(空目录 / diff 0 变动)不评分——findings 为空时对数衰减天然给满分,
100
124
  // 但「没扫到任何文件」不等于「代码健康」,返回 null 明确区分(调用方展示「未扫描到内容」)。
101
125
  if (files !== null && Number(files) === 0) {
@@ -128,13 +152,48 @@ export function scoreQuality(findings = [], weights = {}, context = {}) {
128
152
  // 最终得分 = Σ(维度得分 × 权重) / Σ权重 × 10(Σ(10×w)/Σw×10 = 100 满分;floor 0.1 时全扣 ≈ 1 分)
129
153
  // 保留**三位小数**(不再 Math.round 取整)——整数分丢失维度间差异(79 与 79.4 同显 79);
130
154
  // 侧边栏/工具展示更精细,也便于对照「同一仓库改一处代码后分数动了多少」;level 档位用同一分值判定。
131
- const totalWeight = Object.values(weightMap).reduce((a, b) => a + b, 0);
132
- const weightedSum = DIMENSION_ORDER.reduce((a, d) => a + dims[d] * (weightMap[d] || 0), 0);
155
+ // ── 动态权重(2026-10-30):实际权重 = 设定权重 × 动态权重,动态权重 = 命中文件数 / 总文件数 ──
156
+ // 语义:某维度只在少数文件出问题时,它的实际权重按「问题覆盖面」缩小(扣分更轻);
157
+ // 问题铺满全仓时动态权重=1,退化为纯静态权重(与历史分数一致)。
158
+ // 三条口径(已与需求方对齐):
159
+ // ① 分母用 Σ实际权重(而非固定 100)——否则「全绿」会因有效权重全为 0 而算出 0 分;
160
+ // ② **无命中的维度不缩放**(用设定权重):该维度没问题,必须保持满分贡献,
161
+ // 否则满分会被自己的 0 权重拖成 0 分;
162
+ // ③ 文档维度也参与:它的「命中文件数」取 docsScore.files(仓库里实际存在的文档文件),
163
+ // 因为它本身是加分制、没有「命中问题的文件」概念;无文档文件信息时回退不缩放。
164
+ // 总文件数缺失(files=null,旧调用方)⇒ 全部不缩放,行为与改造前逐位等价。
165
+ // 分母优先用**该维度可作用文件数**(dimFileCounts,由审计编排层按规则 exts 声明统计):
166
+ // 数据文件占比高的仓库里,用总文件数会把代码问题被数据资产数量摊薄(实测某资源仓库
167
+ // 3086 个文本文件中 2701 个是清单 json,可读性权重被稀释到 1/10)。
168
+ // 缺 dimFileCounts(旧调用方/独立调用)→ 回退总文件数,行为与上一版一致。
169
+ const denomOf = (dim) => {
170
+ const perDim = Number(dimFileCounts?.[dim]) > 0 ? Number(dimFileCounts[dim]) : 0;
171
+ return perDim || (Number(files) > 0 ? Number(files) : 0);
172
+ };
173
+ const anyDenom = DIMENSION_ORDER.some((d) => denomOf(d) > 0);
174
+ const hitFiles = anyDenom ? countHitFilesByDimension(findings) : null;
175
+ const dynamicRatio = (dim) => {
176
+ const total = denomOf(dim);
177
+ if (!total) return null; // 该维度既无分母也无总文件数 → 不启用动态权重
178
+ if (dim === '文档') {
179
+ const docFiles = Array.isArray(docsScore?.files) ? docsScore.files.length : 0;
180
+ return docFiles > 0 ? Math.min(1, docFiles / total) : null;
181
+ }
182
+ const hf = hitFiles[dim] || 0;
183
+ return hf > 0 ? Math.min(1, hf / total) : null; // 无命中 → 不缩放
184
+ };
185
+ const dynamicWeights = {};
186
+ for (const d of DIMENSION_ORDER) {
187
+ const ratio = dynamicRatio(d);
188
+ dynamicWeights[d] = (weightMap[d] || 0) * (ratio === null ? 1 : ratio);
189
+ }
190
+ const totalWeight = Object.values(dynamicWeights).reduce((a, b) => a + b, 0);
191
+ const weightedSum = DIMENSION_ORDER.reduce((a, d) => a + dims[d] * (dynamicWeights[d] || 0), 0);
133
192
  // 百分比映射:Σ(dims×w)/Σw 是 0~10 的分值,×10 归一到 0~100;再按 SCORE_DECIMALS 保留小数
134
193
  const percentScale = 10;
135
194
  const score = totalWeight > 0
136
195
  ? Math.round(((weightedSum / totalWeight) * percentScale) * SCORE_ROUND_FACTOR) / SCORE_ROUND_FACTOR
137
196
  : 0;
138
197
  const level = score >= LEVEL_A_MIN ? 'A' : score >= LEVEL_B_MIN ? 'B' : score >= LEVEL_C_MIN ? 'C' : score >= LEVEL_D_MIN ? 'D' : 'E';
139
- return { dims, counts, score, level, weights: weightMap };
198
+ return { dims, counts, score, level, weights: weightMap, dynamicWeights };
140
199
  }
package/lib/self/index.js CHANGED
@@ -9,7 +9,7 @@
9
9
  */
10
10
 
11
11
 
12
- export const VERSION = '2.10.5'; // 2.10.5:隐私/凭据类规则只对自有仓库生效(他人仓库等同关闭):克隆的第三方仓库里第三方 LICENSE/ReadMe 的作者邮箱不再成片报 blocker(实测某 Unity 项目 3 条 blocker 全由此而来);判不出归属时照旧生效(保守)。归属探测放装配层 lib/app/repo-ownership.js(依赖 git 层),审计层 lib/audit/ownership.js 只留纯函数并消费注入的归属字符串,守住『lib/audit 不依赖 lib/git』边界;CLI 与插件工具同参注入,保证两边结果一致。新增 scripts/bump-version.mjs:一键升版(默认 dry-run、--apply 才写盘),把散在三处的版本号收口,并自动重生成派生文档。另含 2.10.4 的 CIFS 克隆修复。。历史:2.10.4:修掉「克隆到 CIFS/SMB 挂载失败」——根因是 git init 要把 core.filemode 写进 .git/config,而写 config 走 config.lock→chmod→rename,挂载带 nounix 时 chmod 恒 EPERM ⇒ git 直接 fatal(留下未初始化的空 .git,整体克隆失败)。新增 lib/git/init-compat.js:真去 chmod 一个临时文件探测能力,不支持时手工搭最小 .git 结构(HEAD + config[filemode=false] + 空 objects/refs/info;remote 段一并手写,因 git remote add 同样要写 config),绕开 git 的 config 写入流程;实测降级后 add/commit/log/status/remote 全部正常。三处 init 调用点(clone.js / clone-history-mode.js / clone-replay-io.js)统一走该兼容层,deps 可注入 chmodOk 便于测试。新增 test/test-init-compat.mjs(6 例,含「降级结构必须是真仓库」与自证)。实测:katboi01/UmaViewer(157MB)经插件成功克隆到 CIFS 挂载,HEAD 与远端一致、脏文件 0。。2.10.3:忽略链路端到端回归。
12
+ export const VERSION = '2.13.2'; // 2.13.2:动态权重分母改按「该维度可作用文件数」——总文件数里混着数据资产(实测 ModelStage 管道内 374 文件中清单 json 占比极高),可读性规则声明 exts=js/mjs/ts… 却按总文件数摊薄 ⇒ 代码问题被数据数量稀释。新增 computeDimFileCounts(编排层按规则 exts 声明统计每维度分母,与 filterRulesByExt 同一取 ext 口径;未声明 exts 的规则按代码文件 CODE_EXTS 计——那批规则实际只作用代码);scoreQuality 优先用维度分母、缺失回退总文件数(向后兼容)。修复过程自证两处:未声明规则误按全文件计导致分母虚高、同一文件同维度双重 +1 导致 741>374——均有测试钉住。历史:2.13.1:大仓库 fetch 按无进展判停摆。2.13.0:动态权重。
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/lib/skip-dirs.js CHANGED
@@ -10,13 +10,16 @@
10
10
  * 白名单(gitignore negation)不受影响:collector walk 对「被忽略目录」按前缀跳过,
11
11
  * 但 gitignore 白名单恢复的目录仍会进入(黑名单初筛 + 白名单补充)。
12
12
  *
13
- * 消费方:lib/audit/collector.js(审计文件收集)、lib/git/sensitive.js(敏感扫描)、
14
- * scripts/scrub-user-wording.mjs(沟通措辞清洗)。
13
+ * 消费方:lib/audit/collector.js(审计文件收集)、lib/git/sensitive.js(敏感扫描)。
15
14
  */
16
15
  import { existsSync, readFileSync, readdirSync } from 'node:fs';
17
16
  import { join, dirname } from 'node:path';
18
17
  import { fileURLToPath } from 'node:url';
19
- import { load as yamlLoad } from './vendor/js-yaml/js-yaml.mjs';
18
+ // js-yaml 走 npm 依赖(仓库内不保存副本)。
19
+ // 这里**故意用静态 import**:规则加载是启动关键路径,依赖没装上就应当在模块加载期
20
+ // 抛 ERR_MODULE_NOT_FOUND(错误里带包名,够响亮),而不是被 try/catch 吞成「0 条规则」
21
+ // 继续跑——静默无规则比启动失败更危险(口径见 docs/2026-10-28-弃零依赖引入npm与AST优先规则方案.MD D5)。
22
+ import { load as yamlLoad } from 'js-yaml';
20
23
 
21
24
  /** 硬编码基线:只许这两个(勿改)。 */
22
25
  export const SKIP_DIRS = new Set(['node_modules', '.git']);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-git-push",
3
- "version": "2.10.5",
3
+ "version": "2.13.2",
4
4
  "description": "DSH git 自动提交推送插件——统一函数入口架构(规则/审计/git/自身/侧边栏/评分/豁免/上下文/HTTP/测试十大总入口)",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -92,5 +92,10 @@
92
92
  "check": "node scripts/check.mjs",
93
93
  "scan-version": "node scripts/scan-version.mjs",
94
94
  "check:drift": "node scripts/doc-drift.mjs"
95
+ },
96
+ "dependencies": {
97
+ "js-yaml": "4.1.0",
98
+ "tree-sitter-wasms": "0.1.13",
99
+ "web-tree-sitter": "0.25.10"
95
100
  }
96
101
  }
@@ -300,8 +300,10 @@ function applyBlock(text, newTree) {
300
300
 
301
301
  /* ───────────────────────── check:漂移对比 ───────────────────────── */
302
302
 
303
- export function checkDrift({ readmePath = DEFAULT_README, root = ROOT } = {}) {
304
- const text = readReadme(readmePath);
303
+ export function checkDrift({ readmePath = '', root = ROOT } = {}) {
304
+ // 树宿主可迁移(README 拆出后落到 docs/ 下带标记块的 md)⇒ 与 apply 同用 resolveTargetMd
305
+ // 自动探测,而不是写死 README。显式传 readmePath 时行为不变。
306
+ const text = readReadme(resolveTargetMd(root, readmePath));
305
307
  const block = findBlock(text);
306
308
  const real = buildTreeText(gitLsFiles(root), loadMapping(root), basename(root));
307
309
  const map = loadMapping(root);
@@ -6,9 +6,9 @@
6
6
  * 分体式文档三兄弟之一(doc-tree 文件树 / doc-func 函数列表 / doc-version 版本列表)。
7
7
  * 版本表数据源 = `docs/releases.json`(每版一行说明)+ 版本真源文件(package.json 等)
8
8
  * + `version-metrics.json`(可选量化记录);**不读 git log**(2026-10-16 改,原因见
9
- * readme-gen.mjs 的 buildReadmeVersionTable 注释)。
9
+ * version-source.mjs 的 buildReadmeVersionTable 注释)。
10
10
  * 写入宿主 md(README 有 dshgp-version 标记块用 README,否则 docs/ 带块 md)。
11
- * 复用 readme-gen.mjs 的 buildReadmeVersionTable(版本聚合逻辑单一事实源)。
11
+ * 复用 version-source.mjs 的 buildReadmeVersionTable(版本聚合逻辑单一事实源)。
12
12
  *
13
13
  * 用法:
14
14
  * node scripts/doc-version.mjs gen [--root <项目根>] # 打印版本表文本
@@ -19,7 +19,7 @@ import { readFileSync, writeFileSync, existsSync } from 'node:fs';
19
19
  import { join, resolve, relative, basename, dirname } from 'node:path';
20
20
  import { fileURLToPath } from 'node:url';
21
21
  import { findMarkedHostMd } from './doc-tree.mjs';
22
- import { buildReadmeVersionTable, detectVersionSource, projectVersionOf, readReleases, VERSION_SOURCES } from './readme-gen.mjs';
22
+ import { buildReadmeVersionTable, detectVersionSource, projectVersionOf, readReleases, VERSION_SOURCES } from './version-source.mjs';
23
23
 
24
24
  const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
25
25
  const MARKER = 'dshgp-version';
@@ -27,7 +27,7 @@ const MARK_START = `<!-- ${MARKER}:start -->`;
27
27
  const MARK_END = `<!-- ${MARKER}:end -->`;
28
28
 
29
29
  /**
30
- * 版本源探测与读取**已迁到 scripts/readme-gen.mjs**(版本表生成与版本源同源,避免两处各写一份)。
30
+ * 版本源探测与读取**在 scripts/version-source.mjs**(版本表生成与版本源同源,避免两处各写一份)。
31
31
  * 这里只做再导出,保持旧调用方的 import 路径不变。
32
32
  *
33
33
  * ⚠️ 2026-10-16 起:版本表**不再读 git log**(`detectVersionSource` 不再回退 'git-log')——
@@ -1,65 +1,16 @@
1
- #!/usr/bin/env node
2
1
  /**
3
- * README 生成脚本(独立运行——自 lib/readme-gen/index.js 抽出,插件代码与文档生成脚本分离)
2
+ * 版本源探测与版本表聚合(供 doc-version 门禁生成 CHANGELOG/README 版本表使用)。
4
3
  *
5
- * 从插件工具 git_gen_readme 抽离为独立脚本;插件仅引用文档/skill,不再内置生成能力。
6
- * 用途:按模板生成仓库 README(占位符 {{name}}/{{description}}/{{version}}/{{toc}}/{{versionTable}})。
4
+ * 来历:原先与 README 模板渲染混在 scripts/readme-gen.mjs 里;README 生成能力已作废(README 改由
5
+ * readme-spec 手工维护、不再按模板渲染),故把**仍在关键路径上**的版本源逻辑单独拆出,
6
+ * 模板渲染/TOC/genReadme 一并删除,避免死代码继续挂在门禁脚本的依赖链上。
7
7
  *
8
- * 用法:
9
- * node scripts/readme-gen.mjs <repoPath> [--write <path>] [--template <path_or_yml>]
10
- * 缺省只打印生成内容(README 模板文本),--write 才落盘。
11
- *
12
- * 模板优先级:--template 指定 > <repo>/template/README.md > 本脚本附带的 readme.yml > 内置兜底。
8
+ * 纯读取:只读 package.json 等版本文件、docs/releases.json、version-metrics.json,
9
+ * 不写盘、不改仓库(写入由 doc-version.mjs 负责)。
13
10
  */
14
- import { existsSync, readFileSync, writeFileSync, readdirSync } from 'node:fs';
15
- import { dirname, join } from 'node:path';
16
- import { fileURLToPath } from 'node:url';
11
+ import { existsSync, readFileSync } from 'node:fs';
12
+ import { join } from 'node:path';
17
13
  import { spawnSync } from 'node:child_process';
18
- import { load as yamlLoad } from '../lib/vendor/js-yaml/js-yaml.mjs';
19
-
20
- const __dirname = dirname(fileURLToPath(import.meta.url));
21
- /** 插件根(scripts/readme-gen.mjs → ../../) */
22
- const PLUGIN_ROOT = join(__dirname, '..');
23
- /** yml 模板目录(复用插件 lib/readme-templates,脚本相对路径 = ../lib/readme-templates) */
24
- const README_TEMPLATE_YML_DIR = join(__dirname, '..', 'lib', 'readme-templates');
25
-
26
- /** 内置兜底模板 */
27
- const DEFAULT_README_TEMPLATE = `# {{name}}
28
-
29
- > {{description}}
30
-
31
- ## 目录
32
-
33
- {{toc}}
34
-
35
- ## 架构设计
36
-
37
- <!-- INSERT: 项目核心架构说明(分层/组件/模块/关键设计决策) -->
38
-
39
- ## 文件目录结构及作用
40
-
41
- <!-- INSERT: 关键文件/目录清单 + 每项作用说明 -->
42
-
43
- ## 启动脚本
44
-
45
- <!-- INSERT: start.sh 用法:start / stop / restart / status,含端口与环境要求 -->
46
-
47
- ## API 总览
48
-
49
- <!-- INSERT: | 方法 | 路径 | 说明 | -->
50
-
51
- ## 版本列表
52
-
53
- {{versionTable}}
54
-
55
- ## 注意事项
56
-
57
- <!-- INSERT: 踩过的坑、边界条件、依赖环境要求、已知限制 -->
58
-
59
- ## 开发计划 / 疑难杂症
60
-
61
- <!-- INSERT: 待办功能、已知问题、未解决的技术难题 -->
62
- `;
63
14
 
64
15
  /** runGit 精简单机版(git log 取提交标题,供版本表聚合)。 */
65
16
  function runGit(args, { cwd = '' } = {}) {
@@ -72,61 +23,6 @@ function runGit(args, { cwd = '' } = {}) {
72
23
  }
73
24
 
74
25
  /** 渲染 yml 模板({ header, sections })→ markdown 模板文本(占位符原样保留)。 */
75
- export function renderReadmeTemplateYml(data) {
76
- const rawHeader = data?.header;
77
- const header = (typeof rawHeader === 'string' ? rawHeader
78
- : (rawHeader && typeof rawHeader === 'object') ? [rawHeader.title, rawHeader.intro].filter(Boolean).join('\n\n')
79
- : '').trim();
80
- const sections = Array.isArray(data?.sections) ? data.sections : [];
81
- const parts = [];
82
- if (header) parts.push(header);
83
- for (const s of sections) {
84
- const title = String(s?.title || '').trim();
85
- if (!title) continue;
86
- parts.push(`## ${title}\n\n${String(s?.body ?? '')}`);
87
- }
88
- return parts.join('\n\n') + '\n';
89
- }
90
-
91
- /** 装载 yml 模板(templates/*.yml 首个可用),失败返回 null。 */
92
- export function loadReadmeTemplateYml(dir = README_TEMPLATE_YML_DIR) {
93
- let names = [];
94
- try { names = readdirSync(dir); } catch { return null; }
95
- const file = names.filter((f) => /\.ya?ml$/i.test(f)).sort()[0];
96
- if (!file) return null;
97
- const full = join(dir, file);
98
- try {
99
- const parsedYml = yamlLoad(readFileSync(full, 'utf8'));
100
- if (!parsedYml || typeof parsedYml !== 'object') return null;
101
- return { file: full, data: parsedYml, template: renderReadmeTemplateYml(parsedYml) };
102
- } catch { return null; }
103
- }
104
-
105
- /** 解析 README 模板:显式模板 > <repo>/template/README.md > yml > 内置兜底。 */
106
- export function resolveReadmeTemplate({ repoPath = '', explicit = '' } = {}) {
107
- if (explicit) {
108
- try { const t = readFileSync(explicit, 'utf8'); if (t.trim()) return { source: explicit, template: t }; } catch { /* 忽略 */ }
109
- }
110
- for (const cand of [join(repoPath, 'template', 'README.md')]) {
111
- try { if (existsSync(cand)) { const t = readFileSync(cand, 'utf8'); if (t.trim()) return { source: cand, template: t }; } } catch { /* 忽略 */ }
112
- }
113
- const yml = loadReadmeTemplateYml();
114
- if (yml) return { source: yml.file, template: yml.template, yml: yml.data };
115
- return { source: 'builtin', template: DEFAULT_README_TEMPLATE };
116
- }
117
-
118
- /** 从模板自动生成目录(## 标题 → 锚点,'目录' 不列)。 */
119
- export function tocFromTemplate(template) {
120
- const titles = [];
121
- for (const line of String(template || '').split('\n')) {
122
- const match = line.match(/^##\s+(.+?)\s*$/);
123
- if (!match) continue;
124
- const t = match[1].trim();
125
- if (t === '目录') continue;
126
- titles.push(t);
127
- }
128
- return titles.map((t) => `- [${t}](#${t})`).join('\n');
129
- }
130
26
 
131
27
  const VERSION_RE = /\bv?(\d+)\.(\d+)\.(\d+)\b/;
132
28
 
@@ -275,44 +171,3 @@ export function buildReadmeVersionTable(repoPath) {
275
171
  }
276
172
 
277
173
  /** 生成 README 文本(不落盘)。 */
278
- export function genReadme({ repoPath, template = '' } = {}) {
279
- let name = '项目名', description = '一句话简介', version = null;
280
- try {
281
- const pkg = JSON.parse(readFileSync(join(repoPath, 'package.json'), 'utf8'));
282
- if (pkg.name) name = pkg.name;
283
- if (pkg.description) description = pkg.description;
284
- if (pkg.version) version = pkg.version;
285
- } catch { /* 非 npm 用默认 */ }
286
- const vtable = toString(buildReadmeVersionTable(repoPath));
287
- const { source, template: tpl } = resolveReadmeTemplate({ repoPath, template });
288
- const toc = tocFromTemplate(tpl);
289
- const content = tpl
290
- .replaceAll('{{name}}', name).replaceAll('{{description}}', description)
291
- .replaceAll('{{version}}', version || '').replaceAll('{{toc}}', toc)
292
- .replaceAll('{{versionTable}}', vtable);
293
- return { ok: true, content, name, description, version, templateSource: source, versionTable: buildReadmeVersionTable(repoPath), toc };
294
- }
295
-
296
- function toString(arr) { return Array.isArray(arr) ? arr.join('\n') : String(arr || ''); }
297
-
298
- function main(argv) {
299
- const args = [...argv];
300
- const repoPath = args.find((a) => !a.startsWith('--'));
301
- const writeIdx = args.indexOf('--write');
302
- const writePath = writeIdx >= 0 ? args[writeIdx + 1] : '';
303
- const tplIdx = args.indexOf('--template');
304
- const template = tplIdx >= 0 ? args[tplIdx + 1] : '';
305
- if (!repoPath) { console.error('用法: node scripts/readme-gen.mjs <repoPath> [--write <path>] [--template <path>]'); process.exit(1); }
306
- const r = genReadme({ repoPath, template });
307
- if (!r.ok) { console.error(r.error); process.exit(1); }
308
- if (writePath) { try { writeFileSync(writePath, r.content, 'utf8'); console.error(`已生成: ${writePath}(模板:${r.templateSource})`); } catch (e) { console.error('写入失败:', e?.message); process.exit(1); } }
309
- else process.stdout.write(r.content);
310
- }
311
-
312
- // 仅作为 CLI 直接运行时执行 main;作为模块 import 供测试时不自动跑(用 import.meta 判断是否入口)
313
- if (process.argv[1] && import.meta.url && String(import.meta.url).startsWith('file:')) {
314
- try {
315
- const entry = fileURLToPath(import.meta.url);
316
- if (entry === String(process.argv[1])) main(process.argv.slice(2));
317
- } catch { /* 非 file url 不做入口判断 */ }
318
- }
@@ -227,17 +227,10 @@ pnpm add github:EIGHTfs/dsh-git-push#<commit>
227
227
 
228
228
  **约定**:README 不直接内嵌长文档(版本表/文件树/函数列表),改为「## 分体式文档」节链接引用。三脚本命令统一 `gen`(打印)/ `apply`(写宿主,自动探测带标记块的 md)/ `check`(查漂移);宿主探测复用公共函数 `findMarkedHostMd(root, marker)`(优先 README,README 无标记块时扫描 .md 找含块文件)。
229
229
 
230
- ### 9.2 README 生成(已抽独立脚本,非插件工具)
230
+ ### 9.2 README 生成(能力已下线)
231
231
 
232
- `git_gen_readme` 插件工具已于 2026-09-29 移除,改为**独立脚本**:
233
-
234
- ```bash
235
- node scripts/readme-gen.mjs <repoPath> [--write <path>] [--template <path>]
236
- ```
237
-
238
- - 只打印不写 → 不传 `--write`;`--write README.md` 才落盘
239
- - `--template` 指定自定义模板(缺省 `lib/readme-templates/readme.yml`);占位符 `{{name}} {{description}} {{version}} {{toc}} {{versionTable}}`
240
- - 插件不再内置生成能力,push.js 的「仓库无 README」提示引用此脚本
232
+ `git_gen_readme` 工具与模板渲染脚本均已移除:README 由使用手册规范手工维护,不再按模板生成。
233
+ 「仓库无 README」之类的提示保留,但不再指向任何生成脚本。
241
234
 
242
235
  ### 9.3 doc-tree 自动探测 md(2026-09-29)
243
236
 
@@ -272,7 +265,6 @@ node scripts/readme-gen.mjs <repoPath> [--write <path>] [--template <path>]
272
265
  | `git_remote_create` | **`repo`**、`visibility?`(默认 private)、`dryRun?` | 同名存在则复用,否则创建并把 origin 指向 API 地址;`ensureRemoteRepo` |
273
266
  | `git_set_visibility` | **`repo`**、**`visibility`** | `PATCH /repos/{owner}/{repo}` 的 private 字段;改 public 前须确认无凭据暴露;`setVisibility` |
274
267
  | `link_check` | `path?`(缺省 workspaceRoot) | 分级扣分(404/403 −3、DNS −2、超时/5xx −1,flaky 域名 ×0.2);**只 warning 永不 blocker**;并发 10;`checkLinks`/`probeLinks` |
275
- | `git_gen_readme` | **`repo`**、`writePath?`(缺省只返回内容) | 模板优先级:插件 `template/README.md` > 内置 `readme.yml` > 代码兜底;版本表由 `git log --reverse` 聚合;`genReadme` |
276
268
 
277
269
  **接线层**(`lib/plugin/index.js`,Host 侧四段真实 API):工具 `ctx.inject(['tools'])` → `register(defineTool(spec))`(`output.render` **必须返回块数组**);提示词注入 `inject(['systemPrompt'])` → `section({name, order, text})`;HTTP `inject(['webServer'])` → `register({kind:'prefix', path, handler})`;客户端**不在此注册**(由 package.json `dsh.client` + `exports["./client"]` 自动发现)。
278
270