dsh-git-push 2.18.2 → 2.20.17

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 (90) hide show
  1. package/.gitignore +4 -0
  2. package/README.md +12 -5
  3. package/cli-audit.mjs +141 -0
  4. package/cli-tool.mjs +86 -0
  5. package/cli.mjs +116 -324
  6. package/lib/ARCHITECTURE.md +3 -0
  7. package/lib/app/audit-api.js +1 -1
  8. package/lib/app/command-registry.js +16 -3
  9. package/lib/app/constants.js +9 -0
  10. package/lib/app/handlers/clone.js +12 -3
  11. package/lib/app/handlers/http-constants.js +11 -2
  12. package/lib/app/handlers/npm.js +4 -2
  13. package/lib/app/handlers/repos.js +10 -1
  14. package/lib/app/handlers/settings.js +9 -1
  15. package/lib/app/http-handlers.js +24 -3
  16. package/lib/app/inject-text.js +1 -0
  17. package/lib/app/schema-audit.js +42 -0
  18. package/lib/app/schema.js +19 -19
  19. package/lib/app/scope-check.js +69 -0
  20. package/lib/app/settings-bridge.js +51 -0
  21. package/lib/app/tool-call.js +56 -7
  22. package/lib/ast/credential.js +130 -14
  23. package/lib/ast/dataflow.js +127 -10
  24. package/lib/ast/index.js +2 -0
  25. package/lib/ast/naming.js +9 -1
  26. package/lib/ast/scope-collisions.js +228 -0
  27. package/lib/ast/treesitter.js +142 -1
  28. package/lib/audit/history.js +1 -1
  29. package/lib/audit/orchestrate.js +93 -6
  30. package/lib/audit/scope-policy.js +110 -0
  31. package/lib/audit-rules/audit-rules-dsh.yml +16 -1
  32. package/lib/audit-rules/audit-rules-nodejs.yml +21 -6
  33. package/lib/audit-rules/audit-rules-paths.yml +7 -1
  34. package/lib/audit-ui-sdk/contract.js +117 -0
  35. package/lib/audit-ui-sdk/index.js +17 -0
  36. package/lib/checks/common.js +4 -4
  37. package/lib/checks/dispatch.js +5 -0
  38. package/lib/checks/index.js +2 -0
  39. package/lib/checks/regex.js +8 -3
  40. package/lib/checks/scope-collision.js +68 -0
  41. package/lib/cli/commands-audit.mjs +13 -18
  42. package/lib/cli/commands-tool.mjs +93 -0
  43. package/lib/cli/commands-vcs.mjs +2 -1
  44. package/lib/cli/shared.mjs +448 -0
  45. package/lib/client-parts/{account.js → git/account.js} +1 -1
  46. package/lib/client-parts/{actions.js → git/actions.js} +26 -11
  47. package/lib/client-parts/{apply.js → git/apply.js} +1 -1
  48. package/lib/client-parts/{browser.js → git/browser.js} +1 -1
  49. package/lib/client-parts/{const.js → git/const.js} +6 -1
  50. package/lib/client-parts/{controller.js → git/controller.js} +23 -11
  51. package/lib/client-parts/{icons.js → git/icons.js} +1 -1
  52. package/lib/client-parts/{loader.js → git/loader.js} +1 -1
  53. package/lib/client-parts/{npm.js → git/npm.js} +1 -1
  54. package/lib/client-parts/{page.js → git/page.js} +11 -21
  55. package/lib/client-parts/{repo.js → git/repo.js} +1 -1
  56. package/lib/client-parts/{settings.js → git/settings.js} +1 -1
  57. package/lib/client-parts/{utils.js → git/utils.js} +1 -1
  58. package/lib/client.js +75 -354
  59. package/lib/commit-push/pre-commit-engine.js +388 -0
  60. package/lib/commit-push.js +44 -17
  61. package/lib/exempt/index.js +5 -2
  62. package/lib/git/ignore.js +6 -4
  63. package/lib/git/init-compat.js +83 -4
  64. package/lib/git/push.js +25 -2
  65. package/lib/git/sensitive.js +30 -1
  66. package/lib/git/transport.js +31 -10
  67. package/lib/http/index.js +82 -10
  68. package/lib/lint-adapter/detect.js +161 -0
  69. package/lib/lint-adapter/index.js +50 -0
  70. package/lib/lint-adapter/runner.js +133 -0
  71. package/lib/npm/npmrc.js +22 -5
  72. package/lib/rule/compilers/structure.js +24 -0
  73. package/lib/score/index.js +36 -4
  74. package/lib/self/index.js +1 -1
  75. package/package.json +25 -2
  76. package/scripts/audit-gate.mjs +235 -0
  77. package/scripts/build-client.mjs +15 -8
  78. package/scripts/bump-version.mjs +20 -5
  79. package/scripts/check-js-scope.mjs +87 -0
  80. package/scripts/check.mjs +51 -4
  81. package/scripts/scan-file-io.mjs +5 -1
  82. package/scripts/scan-version.mjs +10 -7
  83. package/skills/dev/dsh-git-push.md +70 -2
  84. package/skills/guide/guide-audit.md +11 -11
  85. package/skills/guide/guide-cli-scripts.md +3 -3
  86. package/skills/guide/guide-commit-push.md +2 -2
  87. package/skills/guide/guide-inject-ui.md +0 -16
  88. package/assets/start.sh +0 -396
  89. package/scripts/scan-hardcoded-paths.mjs +0 -125
  90. /package/lib/client-parts/{audit.js → audit/audit.js} +0 -0
@@ -0,0 +1,133 @@
1
+ /**
2
+ * 外部 linter 委托层 · 调用 + 适配
3
+ *
4
+ * 职责:跑被审项目自带的官方 linter(当前 ruff),把其 JSON 输出适配成统一 finding 结构。
5
+ *
6
+ * 两条硬约束(用户 2026-11-06 确立):
7
+ * ① **只进评分与报告,绝不进拦截门禁**——所有外部 finding 的 severity 一律封顶 `warning`
8
+ * (isBlockerFinding 认 blocker/error 才拦,见 lib/audit/finding.js)。即 ruff 判 error 的规则
9
+ * (如语法错误 E9xx)在这里也只算警告,「别人的规则集」不裁决本仓库能否提交。
10
+ * ② **探不到/跑不动/超时/输出坏 ⇒ 一律降级返回空**,交回自研规则,绝不抛错中断审计(D5)。
11
+ *
12
+ * 去重:外部 finding 带 `source: 'linter:ruff'`,rule id 带 `ruff/` 前缀——与自研规则 id 天然不同名,
13
+ * 同一处即便两侧都命中也是「两个来源各记一次」(口径与 ext-runner 一致),由评分层每文件每维度去重兜底。
14
+ * noqa:ruff 自身遵守项目里的 `# noqa` / per-file-ignores(被抑制的项不输出),故本层不重复实现豁免。
15
+ */
16
+ import { execFile } from 'node:child_process';
17
+ import { promisify } from 'node:util';
18
+
19
+ const execFileAsync = promisify(execFile);
20
+
21
+ /** 单次委托的超时(毫秒)。ruff 是 Rust 实现,全仓扫描通常秒级;给足冗余但设上限防挂死。 */
22
+ const LINTER_TIMEOUT_MS = 60000;
23
+ /** stdout 上限(大仓库 JSON 可达数十 MB)。超限报错→降级,不误当「无问题」。 */
24
+ const LINTER_MAX_BUFFER = 64 * 1024 * 1024;
25
+
26
+ /** ruff 规则码前缀 → 本引擎维度(取最贴近的一项;未知前缀兜底可维护性)。 */
27
+ const RUFF_DIM_BY_PREFIX = [
28
+ [/^E\d/, ['可读性']], // pycodestyle Error:行宽/空白等格式
29
+ [/^W\d/, ['可读性']], // pycodestyle Warning
30
+ [/^F\d/, ['健壮性', '可维护性']], // Pyflakes:未定义名/未用导入(真缺陷)
31
+ [/^I\d/, ['可读性']], // isort:导入排序
32
+ [/^UP\d/, ['可维护性']], // pyupgrade:过时写法
33
+ [/^B\d/, ['健壮性']], // bugbear:常见 bug 模式
34
+ [/^C4/, ['性能']], // comprehension 优化
35
+ [/^SIM/, ['可维护性']], // simplify
36
+ [/^S\d/, ['安全性']], // bandit 安全
37
+ [/^RUF/, ['可维护性']], // ruff 自有
38
+ ];
39
+ function ruffDims(code) {
40
+ const c = String(code || '');
41
+ for (const [re, dims] of RUFF_DIM_BY_PREFIX) if (re.test(c)) return dims;
42
+ return ['可维护性'];
43
+ }
44
+
45
+ /**
46
+ * 把一条 ruff JSON 命中转成 finding(severity 恒为 warning——只报告不拦截)。
47
+ * @returns {object|null} 结构不完整返回 null(丢弃该条,不影响其余)
48
+ */
49
+ export function ruffItemToFinding(item, repoRoot) {
50
+ if (!item || typeof item !== 'object') return null;
51
+ const file = relFile(String(item.filename || ''), repoRoot);
52
+ if (!file) return null;
53
+ const code = item.code || 'ruff';
54
+ const line = Number(item?.location?.row) || 1;
55
+ return {
56
+ file,
57
+ line,
58
+ rule: `ruff/${code}`,
59
+ kind: 'linter',
60
+ severity: 'warning', // 硬约束①:封顶 warning,永不 blocker/error
61
+ message: `${item.message || 'ruff 告警'}(ruff ${code})`,
62
+ dimensions: ruffDims(code),
63
+ source: 'linter:ruff',
64
+ scoreImpact: 1, // 计入评分维度(这是委托层的意义:反映真实代码质量)
65
+ };
66
+ }
67
+
68
+ /** 绝对路径 → 相对仓库根(与自研 finding 的 file 口径一致,均为正斜杠相对路径)。 */
69
+ function relFile(abs, repoRoot) {
70
+ const norm = String(abs).replace(/\\/g, '/');
71
+ const root = String(repoRoot || '').replace(/\\/g, '/').replace(/\/+$/, '');
72
+ if (root && norm.startsWith(`${root}/`)) return norm.slice(root.length + 1);
73
+ // 相对路径(部分 linter/配置下输出相对)原样返回——压成 basename 会丢目录、与自研口径不一致
74
+ const isAbsolute = norm.startsWith('/') || /^[A-Za-z]:\//.test(norm);
75
+ if (!isAbsolute) return norm;
76
+ // 绝对路径且在 root 之外:取文件名兜底,不把他人机器/其它挂载的绝对路径写进报告
77
+ return norm.split('/').pop();
78
+ }
79
+
80
+ /** 解析 ruff JSON(数组或含 message 的对象);非法返回 null。 */
81
+ function parseRuffJson(stdout) {
82
+ const txt = String(stdout || '').trim();
83
+ if (!txt) return [];
84
+ try {
85
+ const data = JSON.parse(txt);
86
+ return Array.isArray(data) ? data : null;
87
+ } catch {
88
+ return null;
89
+ }
90
+ }
91
+
92
+ /**
93
+ * 对一个 linter 委托执行:调用 → 解析 → 适配。任何失败一律降级为 { findings: [], note }。
94
+ * @param {{key:string, bin:string}} linter detect.js 的产出
95
+ * @param {string} repoRoot 仓库根(作 cwd 与 target,ruff 从 cwd 读项目配置)
96
+ * @returns {Promise<{findings: Array, note: string}>}
97
+ */
98
+ export async function runLinter(linter, repoRoot) {
99
+ if (linter.key !== 'ruff') return { findings: [], note: `未适配的 linter:${linter.key}` };
100
+ let stdout = '';
101
+ try {
102
+ // --no-fix:委托层绝不改动被审文件(只读判定)。target=仓库根,ruff 递归并按项目配置过滤。
103
+ const res = await execFileAsync(
104
+ linter.bin,
105
+ ['check', '--output-format', 'json', '--no-fix', '.'],
106
+ { cwd: repoRoot, timeout: LINTER_TIMEOUT_MS, maxBuffer: LINTER_MAX_BUFFER, stdio: ['ignore', 'pipe', 'pipe'] },
107
+ );
108
+ stdout = res.stdout;
109
+ } catch (e) {
110
+ // ruff 退出码语义(实测其官方约定):0=无问题、1=有 lint 问题(stdout 仍是合法 JSON)、
111
+ // ≥2=真错误(配置非法/崩溃)。execFile 在非零码时抛,只有 **code===1 且有 stdout** 才是可用产出;
112
+ // 其余一律降级——否则「ruff 崩了、stdout 为空」会被当成「外部权威源判定无问题」,
113
+ // 这是假阴性(危险且最隐蔽的一种失败)。
114
+ if (e && e.code === 1 && e.stdout) {
115
+ stdout = e.stdout;
116
+ } else {
117
+ const why = e?.killed
118
+ ? `超时(${Math.round(LINTER_TIMEOUT_MS / 1000)}s)`
119
+ : e?.code === 'ENOENT'
120
+ ? '可执行缺失'
121
+ : `退出码 ${e?.code ?? '?'}(ruff 真错误/崩溃)`;
122
+ return { findings: [], note: `ruff 委托降级跳过(${why}),已回退自研规则` };
123
+ }
124
+ }
125
+ const arr = parseRuffJson(stdout);
126
+ if (arr === null) return { findings: [], note: 'ruff 输出非合法 JSON,降级跳过' };
127
+ const out = [];
128
+ for (const item of arr) {
129
+ const f = ruffItemToFinding(item, repoRoot);
130
+ if (f) out.push(f);
131
+ }
132
+ return { findings: out, note: `ruff 委托产出 ${out.length} 条(仅评分/报告,不拦截)` };
133
+ }
package/lib/npm/npmrc.js CHANGED
@@ -9,9 +9,24 @@ import { join } from 'node:path';
9
9
 
10
10
  import { credentialsDir } from '../core/credentials.js';
11
11
  import { writeTextAtomic } from '../core/atomic-json.js';
12
+ import { DEFAULT_REGISTRY } from './registry.js';
12
13
 
13
14
  export const NPMRC_FILE = 'npmrc';
14
15
 
16
+ /**
17
+ * 归一化 registry:空串、纯空白、undefined 都回落默认值。
18
+ *
19
+ * 为什么必须有这层:`registry=`(空值)写进 npmrc 后,npm 会在构建 nerf-dart 时
20
+ * 用 `new URL('')` 直接抛 `ERR_INVALID_URL`,所有 npm 子命令全部不可用——
21
+ * 而调用方很容易写成 `registry: cfg?.npmRegistry || ''`(未配置 → 空串),
22
+ * 函数默认值又只在 `undefined` 时生效,于是空串一路穿到底。实测踩过:
23
+ * 撤包工具因此完全跑不起来,报的还是「Invalid URL」这种看不出根因的错。
24
+ */
25
+ function effectiveRegistry(registry) {
26
+ const text = String(registry || '').trim();
27
+ return text || DEFAULT_REGISTRY;
28
+ }
29
+
15
30
  /** 按 registry 推导 authToken 行前缀:`//host/path/`(用于 `//host/:_authToken=…`)。 */
16
31
  export function registryAuthPrefix(registry = '') {
17
32
  try {
@@ -23,11 +38,12 @@ export function registryAuthPrefix(registry = '') {
23
38
  }
24
39
 
25
40
  /** 生成 npmrc 文本(纯函数,便于测试):registry 行 +(有 token 时)authToken 行。 */
26
- export function npmrcText({ registry = 'https://registry.npmjs.org/', token = '' } = {}) {
27
- const lines = [`registry=${registry}`];
41
+ export function npmrcText({ registry = DEFAULT_REGISTRY, token = '' } = {}) {
42
+ const effective = effectiveRegistry(registry);
43
+ const lines = [`registry=${effective}`];
28
44
  const t = String(token || '').trim();
29
45
  if (t) {
30
- const prefix = registryAuthPrefix(registry);
46
+ const prefix = registryAuthPrefix(effective);
31
47
  if (prefix) lines.push(`${prefix}:_authToken=${t}`);
32
48
  }
33
49
  return `${lines.join('\n')}\n`;
@@ -48,9 +64,10 @@ export function writeNpmrc({ workspaceRoot = '', registry = 'https://registry.np
48
64
  }
49
65
 
50
66
  /** 拼 npm 全局参数:统一走我们的 npmrc + 显式 registry(不改用户全局配置)。 */
51
- export function npmArgs({ npmrcFile = '', registry = 'https://registry.npmjs.org/' } = {}) {
67
+ export function npmArgs({ npmrcFile = '', registry = DEFAULT_REGISTRY } = {}) {
52
68
  const args = [];
53
69
  if (npmrcFile) args.push('--userconfig', npmrcFile);
54
- if (registry) args.push('--registry', registry);
70
+ const effective = effectiveRegistry(registry);
71
+ if (effective) args.push('--registry', effective);
55
72
  return args;
56
73
  }
@@ -81,3 +81,27 @@ registerCompiler(
81
81
  dimensions: pickDimensions(r, [DIMENSIONS.可部署性]),
82
82
  }),
83
83
  );
84
+
85
+ /* ───────────────────────── 注册:拼接产物作用域撞名(dsh 槽位,scope-collision) ───────────────────────── */
86
+
87
+ /**
88
+ * 拼接产物作用域撞名(多段 JS 拼进同一作用域时 var/function 静默覆盖)。
89
+ * 认领条件:显式 kind==='scope-collision'。
90
+ *
91
+ * 编译产物**故意不带任何项目契约**(前缀 / 顶层零声明 / 产物文件清单):
92
+ * 规则包是跨仓库共享的(同一份 yml 审计所有仓库),契约必须取自被审项目自己的
93
+ * package.json(lib/audit/scope-policy.js)——写进 yml 会让别人项目也收到
94
+ * 「缺少 dshgp_ 前缀」这类与它无关的告警。
95
+ * 作用域(exts / exclude_paths / file_patterns)仍走统一补齐(lib/rule/registry.js),
96
+ * 本编译器无需自己处理。
97
+ */
98
+ registerCompiler(
99
+ 'scope-collision',
100
+ (r) => r?.kind === 'scope-collision',
101
+ (r) => ruleOut({
102
+ id: r.id, name: r.name || r.id, kind: 'scope-collision', severity: r.severity || 'error',
103
+ level: severityLevel(r.severity || 'error'),
104
+ message: r.description || r.name || '拼接产物作用域撞名',
105
+ dimensions: pickDimensions(r, [DIMENSIONS.健壮性, DIMENSIONS.可维护性]),
106
+ }),
107
+ );
@@ -117,12 +117,15 @@ export function countHitFilesByDimension(findings = []) {
117
117
  * 防零分塌陷:对数衰减替代线性扣分——10 个错误和 100 个错误有明显分差(不都归 0),floor=0.1 保留微弱区分度。
118
118
  * @param {Array} findings
119
119
  * @param {object} [weights] 覆盖权重(默认 DEFAULT_WEIGHTS)
120
- * @param {object} [context] { files?: number, scope?: string } —— files=0(空目录/0 变动)时
121
- * 不评分(score:null + emptyResult:true),防止「没扫到任何文件却直接满分」。
120
+ * @param {object} [context] { files?: number, scope?: string, dimFileCounts?: object, dimRuleCounts?: object }
121
+ * —— files=0(空目录/0 变动)时不评分(score:null + emptyResult:true),防止「没扫到任何文件却直接满分」;
122
+ * dimRuleCounts(维度→生效规则绑定数)给出时,**零规则维度权重记 0**(无检测能力的维度不再贡献满分,
123
+ * 见下方「零规则维度记 0」);缺省则沿用旧口径(不缩放),行为逐位等价。
124
+ * 返回 uncoveredDimensions:被记 0 的维度清单,供报告显式标注「本维度无检测能力」。
122
125
  * @returns {{dims: object, score: number|null, level: 'A'|'B'|'C'|'D'|'E'|null, weights: object, emptyResult?: boolean, emptyReason?: string}}
123
126
  */
124
127
  export function scoreQuality(findings = [], weights = {}, context = {}) {
125
- const { files = null, docsScore = null, dimFileCounts = null } = context;
128
+ const { files = null, docsScore = null, dimFileCounts = null, dimRuleCounts = null } = context;
126
129
  // 0 文件(空目录 / diff 0 变动)不评分——findings 为空时对数衰减天然给满分,
127
130
  // 但「没扫到任何文件」不等于「代码健康」,返回 null 明确区分(调用方展示「未扫描到内容」)。
128
131
  if (files !== null && Number(files) === 0) {
@@ -169,6 +172,24 @@ export function scoreQuality(findings = [], weights = {}, context = {}) {
169
172
  // 数据文件占比高的仓库里,用总文件数会把代码问题被数据资产数量摊薄(实测某资源仓库
170
173
  // 3086 个文本文件中 2701 个是清单 json,可读性权重被稀释到 1/10)。
171
174
  // 缺 dimFileCounts(旧调用方/独立调用)→ 回退总文件数,行为与上一版一致。
175
+ // ── 零规则维度记 0(2026-11-06):某维度在本次生效的规则集里**一条规则都没绑定**,
176
+ // 说明它对本仓库**没有检测能力**——此前它按「无命中=满分 10 + 满设定权重」计入总分,
177
+ // 于是「测不到」被算成「质量高」(实测外部仓库:安全性权重 18 仅 3 处规则绑定,
178
+ // 测试覆盖/可观测性/开发者体验 0 处绑定,五维齐满分把分抬到 85/A,而人工核实出 6 个真问题)。
179
+ // 记 0 等价于**把该维度剔出分母**:既不贡献满分、也不因满分稀释其它维度的扣分,
180
+ // 总分只在「真被测过的维度」上归一——口径更诚实且实现最简(不造新规则、不改衰减曲线)。
181
+ // 判据用**生效规则集**(已按仓库语言/槽位过滤后的 grouped),不是全量规则表:
182
+ // 纯 Python 仓库里没有 C# 专属规则属正常,不该因此把「可维护性」记 0。
183
+ // 缺 dimRuleCounts(旧调用方/独立调用)⇒ 不启用本口径,行为与改造前逐位等价。
184
+ const ruleCountOf = (dim) => {
185
+ if (!dimRuleCounts || typeof dimRuleCounts !== 'object') return null;
186
+ const n = Number(dimRuleCounts[dim]);
187
+ return Number.isFinite(n) ? n : 0;
188
+ };
189
+ // 防全塌保护:只有「规则集确实给出了维度绑定信息」(至少一个维度计数>0)时才启用本口径。
190
+ // 极端情形(自定义规则集所有规则都不声明 dimensions ⇒ dimRuleCounts 为 {},十维全 0)
191
+ // 会让分母塌成 0、总分算成 0——那不是「诚实」而是失真,故整条口径退回旧行为(不缩放)。
192
+ const coverageKnown = DIMENSION_ORDER.some((d) => ruleCountOf(d) > 0);
172
193
  const denomOf = (dim) => {
173
194
  const perDim = Number(dimFileCounts?.[dim]) > 0 ? Number(dimFileCounts[dim]) : 0;
174
195
  return perDim || (Number(files) > 0 ? Number(files) : 0);
@@ -186,7 +207,14 @@ export function scoreQuality(findings = [], weights = {}, context = {}) {
186
207
  return hf > 0 ? Math.min(1, hf / total) : null; // 无命中 → 不缩放
187
208
  };
188
209
  const dynamicWeights = {};
210
+ const uncoveredDimensions = [];
189
211
  for (const d of DIMENSION_ORDER) {
212
+ // 零规则维度:直接记 0 权重(不进分母),并登记供报告显式标注「本维度无检测能力」
213
+ if (coverageKnown && ruleCountOf(d) === 0) {
214
+ dynamicWeights[d] = 0;
215
+ uncoveredDimensions.push(d);
216
+ continue;
217
+ }
190
218
  const ratio = dynamicRatio(d);
191
219
  dynamicWeights[d] = (weightMap[d] || 0) * (ratio === null ? 1 : ratio);
192
220
  }
@@ -198,5 +226,9 @@ export function scoreQuality(findings = [], weights = {}, context = {}) {
198
226
  ? Math.round(((weightedSum / totalWeight) * percentScale) * SCORE_ROUND_FACTOR) / SCORE_ROUND_FACTOR
199
227
  : 0;
200
228
  const level = score >= LEVEL_A_MIN ? 'A' : score >= LEVEL_B_MIN ? 'B' : score >= LEVEL_C_MIN ? 'C' : score >= LEVEL_D_MIN ? 'D' : 'E';
201
- return { dims, counts, score, level, weights: weightMap, dynamicWeights };
229
+ return {
230
+ dims, counts, score, level, weights: weightMap, dynamicWeights,
231
+ // 启用零规则口径时回传清单(空数组=十维都有检测能力);未启用则为 null,调用方据此区分口径
232
+ uncoveredDimensions: coverageKnown ? uncoveredDimensions : null,
233
+ };
202
234
  }
package/lib/self/index.js CHANGED
@@ -9,7 +9,7 @@
9
9
  */
10
10
 
11
11
 
12
- export const VERSION = '2.18.2'; // 2.18.2:审计扩展新增两条 DSH 插件 blocker 规则(访问 ctx 服务但未 inject / 入口 default 导出覆盖命名导出)。历史 —— 2.18.1:修发布前冒烟的两个选项目缺陷——① `exports` 里的非 JS 资源(.yml/.json 等)曾被当模块 import,对正常包抛 ERR_UNKNOWN_FILE_EXTENSION,把好包拦在发布前;② 点出口 `"."` 曾被跳过,导致主入口从来没被测过、门禁形同虚设。现在按目标扩展名与条件导出挑出「真正能被 Node 加载」的入口,并给两侧行为补了单测。历史:2.18.0 新增 npm_unpublish(撤包,默认 dryRun)。
12
+ export const VERSION = '2.20.17'; // 2.20.17:修桌面端(dsh-app://)所有写接口 403 NO_ORIGIN + 本地列表超时改预算传播 + 放行判据加固。① 桌面壳 forwardWebRequest 转发 /api/* 时显式剥离 Origin,checkOrigin 对无 Origin 的写请求一律拒,导致设置页所有保存/开关/按钮失效且不留日志 → 无 Origin 时要求「Content-Type=application/json + 本机来源」同时成立才放行;② 本机判定以 TCP 对端地址(socket.remoteAddress,内核给出不可伪造)为准,Host 仅在拿不到 socket 时兜底——只信 Host 会被 `Host: 127.0.0.1` 伪造绕过;isLoopbackHost 补裸 IPv6 与 ::ffff: 映射形态;③ 恢复 403 拒绝日志 http-rejects.log(query 凭据键打码);④ settings-set 凭据类回显改「(已保存)」;⑤ 前端保存先 await 写入结果再提示;⑥ clone-progress 改 GET 轮询;⑦ 本地列表 SSH 探测改为预算传播(每步 timeoutMs = min(单步上限, 剩余预算)),扫描长轮询 60s→20s、前端单请求 25s,轮次耗尽不再误报「扫描完成」。历史:2.20.15:
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.18.2",
3
+ "version": "2.20.17",
4
4
  "description": "DSH git 自动提交推送插件——统一函数入口架构(规则/审计/git/自身/侧边栏/评分/豁免/上下文/HTTP/测试十大总入口)",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -16,6 +16,8 @@
16
16
  "scripts",
17
17
  "assets",
18
18
  "cli.mjs",
19
+ "cli-audit.mjs",
20
+ "cli-tool.mjs",
19
21
  "cordis.patch.yml",
20
22
  "README.md",
21
23
  "LICENSE",
@@ -23,7 +25,9 @@
23
25
  ".gitignore"
24
26
  ],
25
27
  "bin": {
26
- "git-sluice": "./cli.mjs"
28
+ "git-sluice": "./cli.mjs",
29
+ "audit-sluice": "./cli-audit.mjs",
30
+ "tool-sluice": "./cli-tool.mjs"
27
31
  },
28
32
  "dsh": {
29
33
  "bundle": {
@@ -97,5 +101,24 @@
97
101
  "js-yaml": "4.1.0",
98
102
  "tree-sitter-wasms": "0.1.13",
99
103
  "web-tree-sitter": "0.25.10"
104
+ },
105
+ "dshScopeCheck": {
106
+ "note": "拼接产物作用域检查:files 里每个文件都查「同作用域重名 / 顶层声明 / 命名前缀」。查法:git-sluice scope-check(无参数即读本块 files);其它项目只要在自己的 package.json 写同名字段即可复用同一套判定",
107
+ "files": [
108
+ "lib/client.js"
109
+ ],
110
+ "prefix": "dshgp_",
111
+ "allowlist": [
112
+ "module",
113
+ "exports",
114
+ "jsx",
115
+ "react",
116
+ "store",
117
+ "NS",
118
+ "SETTINGS_NS",
119
+ "inject",
120
+ "apply"
121
+ ],
122
+ "topLevelMustBeEmpty": true
100
123
  }
101
124
  }
@@ -0,0 +1,235 @@
1
+ #!/usr/bin/env node
2
+ // 提交前审计引擎 · 轻量门禁入口(不是给人看的 CLI,只服务 commit 门禁)
3
+ //
4
+ // 为什么单独开一个入口、不复用 cli.mjs(实测数字决定,别改成"复用更省事"):
5
+ // 同一仓库、同一 scope、同一台 CIFS 机器上——
6
+ // 进程内直接调审计内核 1.0s
7
+ // 本轻量入口(子进程 + JSON) 1.3s
8
+ // cli.mjs audit --json 6.4s
9
+ // 多出来的 5.4s 全是 cli.mjs 全家桶的 ESM 模块解析(account/vcs/doc/npm/git 命令族被
10
+ // 一路链式 import 进来),与本次审计无关。门禁每次提交都要跑,不能为此付 5 秒。
11
+ // 所以本文件**只** import 审计内核与评分两层,加任何新的 import 前先量耗时。
12
+ //
13
+ // 契约(与实现语言无关,替代引擎照此实现即可):
14
+ // stdout : 一行 JSON { ok, scope, summary, quality, findings, files }
15
+ // 退出码 : 0 = 无 blocker(放行)/ 1 = 有 blocker(拦截)/ 2 = 执行失败(参数错、内部异常)
16
+ // stderr : 仅诊断信息,不参与判定
17
+ // --blockers-only : findings 只留 blocker 级(大仓 4900 条约 3.8MB,门禁未必需要全量)
18
+ //
19
+ // stdout 纯净性:审计过程里任何 console.* / 直接 stdout 写入都被临时改道到 stderr,
20
+ // 最后只由本文件写那一行 JSON。否则调用方 JSON.parse 会被进度噪音打死(历史故障)。
21
+ //
22
+ // 参数缺省语义(必须与插件默认配置等价,测试钉住):
23
+ // --max-scan-files 缺省 = DEFAULT_MAX_SCAN_FILES(3000),**不是 0**
24
+ // —— capScanFiles 里 0 的含义是「不限」,把缺省当 0 会把大仓全量扫,语义正好相反。
25
+ // --disabled-slots 缺省 = 不禁用任何槽位。
26
+ // --slots 缺省 = 不限定规则包(加载层默认偏好顺序);只在调用方显式给白名单时传。
27
+
28
+ import { fileURLToPath } from 'node:url';
29
+ import { resolve } from 'node:path';
30
+
31
+ // 宿主文档漂移检查器接线(导入即安装,幂等):`lib/audit/**` 不许 import scripts/**,
32
+ // 这两个检查器由宿主入口注入。漏掉这一行会让「目录树漂移 / 函数列表漂移」两类 finding
33
+ // 整类消失(实测同一棵树上少 4 条 finding)——**行为一致性要求本入口必须显式接线**,
34
+ // 与 lib/commit-push.js / cli.mjs 两处宿主入口同款。依赖只有 node 内置模块,几乎零加载代价。
35
+ import '../lib/app/host-doc-checks.js';
36
+ import { auditWithScope } from '../lib/audit/index.js';
37
+ import { scoreQuality } from '../lib/score/index.js';
38
+
39
+ /** 退出码语义(任何语言都能实现 exit 0/1/2,比让调用方解析 JSON 猜语义可靠)。 */
40
+ export const EXIT_OK = 0;
41
+ export const EXIT_BLOCKED = 1;
42
+ export const EXIT_FAILED = 2;
43
+
44
+ /**
45
+ * 引擎侧「全量扫描文件数上限」默认值。
46
+ * 单一来源是 lib/app/schema-audit.js 的 DEFAULT_MAX_SCAN_FILES(3000,由 lib/client/index.js
47
+ * 的 MAX_SCAN_FILES_DEFAULT 与之对齐)。本文件不复用那个常量是因为轻量入口不能 import
48
+ * lib/app/ 与 lib/client/(那会把加载代价拉回去)。代价是两处数字必须相等 ——
49
+ * test/test-pre-commit-engine.mjs 用 defaultConfig().maxScanFiles 钉住这条,改一处漏另一处会变红。
50
+ */
51
+ export const DEFAULT_MAX_SCAN_FILES = 3000;
52
+
53
+ /** 参数错误统一用这个错误类型,main 据此输出「用法」而不是「内部异常」。 */
54
+ export class GateUsageError extends Error {
55
+ constructor(message) {
56
+ super(message);
57
+ this.name = 'GateUsageError';
58
+ }
59
+ }
60
+
61
+ /**
62
+ * 解析命令行参数(纯函数,测试可直接调用,不必起子进程)。
63
+ * @param {string[]} argv 不含 node 与脚本路径的参数表
64
+ * @returns {{repo: string, scope: 'diff'|'full', rulesetDir: string, weights: object,
65
+ * maxScanFiles: number, disabledSlots: string[], blockersOnly: boolean, json: boolean}}
66
+ */
67
+ /** 取值的参数解析器(各自单职责,主循环只做分派——避免一个巨型 if 链)。 */
68
+ function parseScopeValue(rawValue) {
69
+ if (rawValue !== 'diff' && rawValue !== 'full') throw new GateUsageError(`--scope 只接受 diff|full,收到:${rawValue}`);
70
+ return rawValue;
71
+ }
72
+
73
+ function parseWeightsValue(rawValue) {
74
+ let parsedWeights;
75
+ try {
76
+ parsedWeights = JSON.parse(rawValue);
77
+ } catch (e) {
78
+ throw new GateUsageError(`--weights 不是合法 JSON:${e.message}`);
79
+ }
80
+ return parsedWeights && typeof parsedWeights === 'object' ? parsedWeights : {};
81
+ }
82
+
83
+ function parseMaxScanFilesValue(rawValue) {
84
+ const asNumber = Number(rawValue);
85
+ // 只接受非负有限数:0 有明确含义(不限),所以不能用 falsy 判断把它当成「没传」
86
+ if (!Number.isFinite(asNumber) || asNumber < 0) throw new GateUsageError(`--max-scan-files 需要非负数字,收到:${rawValue}`);
87
+ return asNumber;
88
+ }
89
+
90
+ function parseSlotListValue(rawValue) {
91
+ return String(rawValue).split(',').map((slotName) => slotName.trim()).filter(Boolean);
92
+ }
93
+
94
+ /**
95
+ * 参数分派表:键是参数名,值是「要不要取值 + 怎么落到解析结果上」。
96
+ * 未知参数一律报错(不做静默忽略)——拼错的参数被忽略,等于门禁悄悄少传一项设置。
97
+ */
98
+ const GATE_FLAG_SPECS = {
99
+ '--repo': { needsValue: true, apply: (target, rawValue) => { target.repo = rawValue; } },
100
+ '--scope': { needsValue: true, apply: (target, rawValue) => { target.scope = parseScopeValue(rawValue); } },
101
+ '--ruleset': { needsValue: true, apply: (target, rawValue) => { target.rulesetDir = rawValue; } },
102
+ '--weights': { needsValue: true, apply: (target, rawValue) => { target.weights = parseWeightsValue(rawValue); } },
103
+ '--max-scan-files': { needsValue: true, apply: (target, rawValue) => { target.maxScanFiles = parseMaxScanFilesValue(rawValue); } },
104
+ '--disabled-slots': { needsValue: true, apply: (target, rawValue) => { target.disabledSlots = parseSlotListValue(rawValue); } },
105
+ '--slots': { needsValue: true, apply: (target, rawValue) => { target.slots = parseSlotListValue(rawValue); } },
106
+ '--blockers-only': { needsValue: false, apply: (target) => { target.blockersOnly = true; } },
107
+ '--json': { needsValue: false, apply: (target) => { target.json = true; } },
108
+ };
109
+
110
+ /**
111
+ * 解析命令行参数(纯函数,测试可直接调用,不必起子进程)。
112
+ * @param {string[]} argv 不含 node 与脚本路径的参数表
113
+ * @returns {{repo: string, scope: 'diff'|'full', rulesetDir: string, weights: object,
114
+ * maxScanFiles: number, disabledSlots: string[], slots: string[], blockersOnly: boolean, json: boolean}}
115
+ */
116
+ export function parseGateArgs(argv = []) {
117
+ const target = {
118
+ repo: '',
119
+ scope: 'diff',
120
+ rulesetDir: '',
121
+ weights: {},
122
+ maxScanFiles: DEFAULT_MAX_SCAN_FILES,
123
+ disabledSlots: [],
124
+ slots: [],
125
+ blockersOnly: false,
126
+ json: false,
127
+ };
128
+ for (let cursor = 0; cursor < argv.length; cursor += 1) {
129
+ const flagName = argv[cursor];
130
+ const spec = GATE_FLAG_SPECS[flagName];
131
+ if (!spec) throw new GateUsageError(`不认识的参数:${flagName}`);
132
+ if (!spec.needsValue) { spec.apply(target); continue; }
133
+ const flagValue = argv[cursor + 1];
134
+ if (flagValue === undefined) throw new GateUsageError(`参数 ${flagName} 缺少取值`);
135
+ cursor += 1;
136
+ spec.apply(target, flagValue);
137
+ }
138
+ if (!target.repo) throw new GateUsageError('缺少必填参数 --repo <仓库绝对路径>');
139
+ return target;
140
+ }
141
+
142
+ /**
143
+ * 跑一次审计并组装契约 JSON(纯逻辑,测试可直接调用)。
144
+ * 与旧「进程内提交门禁」逐项对齐的点:
145
+ * · scope / maxScanFiles / rulesetDir / disabledSlots 的取值路径完全相同;
146
+ * · 评分上下文只给 files / dimFileCounts / dimRuleCounts(**不给 docsScore**)——
147
+ * 旧 runAudit 就是这么调的,多给一项会让分数变化;
148
+ * · summary 直接透传内核结果,不在这里重新计数。
149
+ * @param {object} opts parseGateArgs 的返回值
150
+ * @returns {Promise<{ok: boolean, scope: string, summary: object, quality: object, findings: object[], files: number}>}
151
+ */
152
+ export async function runGateAudit(opts) {
153
+ const auditResult = await auditWithScope(opts.repo, {
154
+ scope: opts.scope,
155
+ maxScanFiles: opts.maxScanFiles,
156
+ rulesetDir: opts.rulesetDir,
157
+ // 空数组与 undefined 在加载层同义(都用默认偏好顺序),显式给 undefined 更贴合旧行为
158
+ slots: Array.isArray(opts.slots) && opts.slots.length ? opts.slots : undefined,
159
+ disabledSlots: Array.isArray(opts.disabledSlots) ? opts.disabledSlots : [],
160
+ });
161
+ const quality = scoreQuality(auditResult.findings, opts.weights, {
162
+ files: auditResult.files,
163
+ dimFileCounts: auditResult.dimFileCounts,
164
+ dimRuleCounts: auditResult.dimRuleCounts,
165
+ });
166
+ const findings = opts.blockersOnly
167
+ ? (auditResult.findings || []).filter((finding) => finding.severity === 'blocker')
168
+ : (auditResult.findings || []);
169
+ return {
170
+ ok: (auditResult.summary?.blocker ?? 0) === 0,
171
+ scope: auditResult.scope,
172
+ summary: auditResult.summary,
173
+ quality,
174
+ findings,
175
+ files: auditResult.files,
176
+ };
177
+ }
178
+
179
+ /**
180
+ * 把审计期间的一切 stdout 写入改道到 stderr,返回还原函数。
181
+ * 为什么不用「审计结束后从 stdout 里找 JSON 行」:findings 可达数 MB 且内容里可能含
182
+ * 花括号,正则挑行不可靠;从源头保证 stdout 只有一行才是可验证的。
183
+ */
184
+ export function muteStdout() {
185
+ const originalWrite = process.stdout.write;
186
+ process.stdout.write = process.stderr.write.bind(process.stderr);
187
+ return () => { process.stdout.write = originalWrite; };
188
+ }
189
+
190
+ /** 写契约 JSON 并在冲刷完成后退出(flush 后再 exit,避免大 payload 被截断)。 */
191
+ function emitAndExit(result, exitCode) {
192
+ const payload = `${JSON.stringify(result)}\n`;
193
+ process.stdout.write(payload, () => { process.exit(exitCode); });
194
+ }
195
+
196
+ /** 入口:解析 → 审计 → 输出 → 定退出码。 */
197
+ async function main(argv) {
198
+ let opts;
199
+ try {
200
+ opts = parseGateArgs(argv);
201
+ } catch (e) {
202
+ process.stderr.write(`${e.name === 'GateUsageError' ? '参数错误' : '内部错误'}:${e.message}\n`);
203
+ return EXIT_FAILED;
204
+ }
205
+ const restoreStdout = muteStdout();
206
+ let gateAuditResult;
207
+ try {
208
+ gateAuditResult = await runGateAudit(opts);
209
+ } catch (e) {
210
+ process.stderr.write(`审计执行失败(repo=${opts.repo} scope=${opts.scope}):${e?.stack || e}\n`);
211
+ return EXIT_FAILED;
212
+ } finally {
213
+ restoreStdout();
214
+ }
215
+ emitAndExit(gateAuditResult, gateAuditResult.ok ? EXIT_OK : EXIT_BLOCKED);
216
+ // emitAndExit 内部已注册退出,这里返回一个占位码保持函数语义完整
217
+ return gateAuditResult.ok ? EXIT_OK : EXIT_BLOCKED;
218
+ }
219
+
220
+ /** 直接执行时才真正开跑:被测试 import 时不得产生副作用。 */
221
+ function invokedDirectly() {
222
+ const entry = process.argv[1];
223
+ if (!entry) return false;
224
+ try { return resolve(entry) === resolve(fileURLToPath(import.meta.url)); } catch { return false; }
225
+ }
226
+
227
+ if (invokedDirectly()) {
228
+ main(process.argv.slice(2)).then((code) => {
229
+ // 正常路径里 emitAndExit 已经退出;走到这里说明审计抛错或没输出结果
230
+ if (typeof code === 'number') process.exitCode = code;
231
+ }).catch((e) => {
232
+ process.stderr.write(`未捕获异常:${e?.stack || e}\n`);
233
+ process.exit(EXIT_FAILED);
234
+ });
235
+ }
@@ -25,7 +25,15 @@ import { join, dirname } from 'node:path';
25
25
  import { fileURLToPath } from 'node:url';
26
26
 
27
27
  export const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
28
- export const PARTS_DIR = join(ROOT, 'lib', 'client-parts');
28
+ // 分片按侧分目录(2026-11-08 UI 与审计解耦):
29
+ // · lib/client-parts/git/** —— git / 发布 / 工具链侧,**参与构建**(本文件的 PARTS_DIR)
30
+ // · lib/client-parts/audit/** —— 审计侧,**不参与构建**(UI 上不再有审计 Tab)
31
+ // 审计侧分片留在源码里可查可改(将来拆成独立项目时整体搬走),但不进产物 ⇒ 不进 UI。
32
+ // 不参与构建的方式:不在 PARTS_DIR 下 ⇒ readParts 的「未登记分片」检查天然扫不到它,
33
+ // 也不会因「缺片」报错(缺片检查只针对 PART_ORDER 里列出的片)。
34
+ export const PARTS_DIR = join(ROOT, 'lib', 'client-parts', 'git');
35
+ /** 不参与构建的分片目录(只做归档,构建脚本不读、不校验)。 */
36
+ export const ARCHIVE_PARTS_DIR = join(ROOT, 'lib', 'client-parts', 'audit');
29
37
  export const OUT_FILE = join(ROOT, 'lib', 'client.js');
30
38
 
31
39
  /**
@@ -36,7 +44,7 @@ export const OUT_FILE = join(ROOT, 'lib', 'client.js');
36
44
  * 命名约定:分片文件名**不带数字序号**(顺序只由本表这一处权威声明)。
37
45
  * 序号前缀看似方便,实则会漂移——重排/插片时新旧序号并存,扫目录看到的顺序
38
46
  * 与真实拼接顺序不一致,比没有序号更坏。顺序信息集中在 PART_ORDER +
39
- * 每个分片头注释的「第 N/14 片」锚点,改序只改这两处。
47
+ * 每个分片头注释的「第 N/M 片」锚点,改序只改这两处。
40
48
  */
41
49
  export const PART_ORDER = [
42
50
  'loader.js', // [1] loader + factory 头 + require + NS(必须首片)
@@ -47,12 +55,11 @@ export const PART_ORDER = [
47
55
  'browser.js', // [6] 目录选择器
48
56
  'repo.js', // [7] 仓库管理卡
49
57
  'npm.js', // [7续] NPM 面板(账号卡 + 装包表单 + npm 凭据字段)
50
- 'audit.js', // [8] 审计 Tab
51
- 'settings.js', // [9] 设置 Tab
52
- 'page.js', // [10] 页面装配(GitPushPage)
53
- 'controller.js', // [11] Controller:状态机 + 数据加载
54
- 'actions.js', // [11续] Controller:动作注入
55
- 'apply.js', // [12] 收尾:注册 settings.section + factory 返回(必须末片)
58
+ 'settings.js', // [8] 设置 Tab(原第 9 片;审计 Tab 已移出构建)
59
+ 'page.js', // [9] 页面装配(GitPushPage,两选项卡)
60
+ 'controller.js', // [10] Controller:状态机 + 数据加载
61
+ 'actions.js', // [10续] Controller:动作注入
62
+ 'apply.js', // [11] 收尾:注册 settings.section + factory 返回(必须末片)
56
63
  ];
57
64
 
58
65
  /** 读出全部分片内容(缺片直接报错,避免拼出半份产物当成功)。 */