dsh-git-push 2.18.2 → 2.20.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.gitignore +4 -0
- package/README.md +3 -0
- package/cli.mjs +16 -3
- package/lib/ARCHITECTURE.md +3 -0
- package/lib/app/audit-api.js +1 -1
- package/lib/app/command-registry.js +13 -1
- package/lib/app/inject-text.js +1 -0
- package/lib/app/scope-check.js +69 -0
- package/lib/app/tool-call.js +49 -2
- package/lib/ast/credential.js +130 -14
- package/lib/ast/dataflow.js +127 -10
- package/lib/ast/index.js +2 -0
- package/lib/ast/naming.js +9 -1
- package/lib/ast/scope-collisions.js +228 -0
- package/lib/ast/treesitter.js +142 -1
- package/lib/audit/history.js +1 -1
- package/lib/audit/orchestrate.js +93 -6
- package/lib/audit/scope-policy.js +110 -0
- package/lib/audit-rules/audit-rules-dsh.yml +16 -1
- package/lib/audit-rules/audit-rules-nodejs.yml +21 -6
- package/lib/checks/common.js +4 -4
- package/lib/checks/dispatch.js +5 -0
- package/lib/checks/index.js +2 -0
- package/lib/checks/regex.js +2 -2
- package/lib/checks/scope-collision.js +68 -0
- package/lib/cli/commands-audit.mjs +1 -1
- package/lib/commit-push.js +6 -1
- package/lib/exempt/index.js +5 -2
- package/lib/git/ignore.js +6 -4
- package/lib/git/init-compat.js +83 -4
- package/lib/git/push.js +25 -2
- package/lib/git/sensitive.js +30 -1
- package/lib/lint-adapter/detect.js +161 -0
- package/lib/lint-adapter/index.js +50 -0
- package/lib/lint-adapter/runner.js +133 -0
- package/lib/rule/compilers/structure.js +24 -0
- package/lib/score/index.js +36 -4
- package/lib/self/index.js +1 -1
- package/package.json +20 -1
- package/scripts/bump-version.mjs +20 -5
- package/scripts/check-js-scope.mjs +87 -0
- package/scripts/check.mjs +39 -1
- package/skills/dev/dsh-git-push.md +8 -2
package/lib/git/init-compat.js
CHANGED
|
@@ -22,8 +22,9 @@
|
|
|
22
22
|
* 因此降级路径 = 手写 `.git/{HEAD,config}` + 空 `objects/refs/info` 目录,绕开 git 的
|
|
23
23
|
* config 写入流程;config 里预先写死 `filemode = false`。
|
|
24
24
|
*/
|
|
25
|
-
import { existsSync, mkdirSync, writeFileSync, chmodSync, rmSync, realpathSync } from 'node:fs';
|
|
26
|
-
import { join } from 'node:path';
|
|
25
|
+
import { existsSync, mkdirSync, writeFileSync, readFileSync, chmodSync, rmSync, realpathSync } from 'node:fs';
|
|
26
|
+
import { join, resolve } from 'node:path';
|
|
27
|
+
import { statSync } from 'node:fs';
|
|
27
28
|
import { runGit } from './exec.js';
|
|
28
29
|
|
|
29
30
|
/**
|
|
@@ -79,9 +80,53 @@ export function writeMinimalGitDir(dir, { branch = 'master', remoteName = 'origi
|
|
|
79
80
|
if (remoteUrl) {
|
|
80
81
|
lines.push(`[remote "${remoteName}"]`, `\turl = ${remoteUrl}`, `\tfetch = +refs/heads/*:refs/remotes/${remoteName}/*`);
|
|
81
82
|
}
|
|
83
|
+
// 注意:**不要**在这里写仓库级 [safe] directory —— 实测(git 2.55)所有权检查发生在
|
|
84
|
+
// 读取该仓库 config **之前**,被检查的目录无法自证可信,写了也不生效。
|
|
85
|
+
// 对外可用由 registerTrustedRepo() 走 global 配置解决,见该函数说明。
|
|
82
86
|
writeFileSync(join(g, 'config'), lines.join('\n') + '\n');
|
|
83
87
|
}
|
|
84
88
|
|
|
89
|
+
/**
|
|
90
|
+
* 把仓库登记进**用户 global** 的 safe.directory,使这个目录对裸 git(用户/外部工具/CI)也可用。
|
|
91
|
+
*
|
|
92
|
+
* 为什么必须走 global 而不是仓库 config(三条实测事实,git 2.55.0):
|
|
93
|
+
* ① 仓库级 `[safe] directory` **不生效**——所有权检查发生在读取该仓库 config 之前,
|
|
94
|
+
* 被检查目录无法自证可信(实测:仓库 config 含该段,裸 git status 仍 fatal)。
|
|
95
|
+
* ② `-c safe.directory=<绝对路径>` 生效;global 写同一条同样生效(实测通过)。
|
|
96
|
+
* ③ 需要它的场景真实存在:CIFS/SMB 挂载带 forceuid 时目录属主被映射成挂载用户
|
|
97
|
+
* (本机 `杜渊`(1026))而进程 uid 是套件用户(284371),于是 git 对**任何**命令报
|
|
98
|
+
* `detected dubious ownership`。插件内部走 runGit(GIT_GLOBAL_ARGS 已带 safe.directory=*)
|
|
99
|
+
* 感觉不到,但建完仓交出去,用户一敲 git 就挂 ——「建仓成功、仓库不可用」是历史事故同型。
|
|
100
|
+
*
|
|
101
|
+
* 只登记**这一个具体路径**(不是 `*`):范围最小,不改用户对所有仓库的信任策略。
|
|
102
|
+
* 幂等:已在列表里就不重复追加。同 uid 的本地盘不需要登记,跳过以免污染用户配置。
|
|
103
|
+
* @param {string} dir 仓库目录(会归一成绝对路径)
|
|
104
|
+
* @param {(args: string[], opts: object) => {ok:boolean, stdout?:string, stderr?:string}} [exec] 注入点(测试用)
|
|
105
|
+
* @returns {{registered: boolean, needed: boolean, skipped?: string, stderr?: string}}
|
|
106
|
+
*/
|
|
107
|
+
export function registerTrustedRepo(dir, exec) {
|
|
108
|
+
const run = typeof exec === 'function' ? exec : (args, opts) => runGit(args, opts);
|
|
109
|
+
// 无 getuid 的平台(Windows)git 不做所有权检查,直接跳过
|
|
110
|
+
if (typeof process.getuid !== 'function') {
|
|
111
|
+
return { registered: false, needed: false, skipped: '该平台无 uid 概念,git 不做所有权检查' };
|
|
112
|
+
}
|
|
113
|
+
const abs = resolve(String(dir || ''));
|
|
114
|
+
if (!abs) return { registered: false, needed: false, skipped: '空路径' };
|
|
115
|
+
let ownerUid = null;
|
|
116
|
+
try { ownerUid = statSync(abs).uid; } catch { /* 拿不到属主时保守当作需要登记 */ }
|
|
117
|
+
if (ownerUid !== null && ownerUid === process.getuid()) {
|
|
118
|
+
return { registered: false, needed: false, skipped: '属主与当前进程一致,git 不会判 dubious' };
|
|
119
|
+
}
|
|
120
|
+
// safe.directory 是可重复键:读现有列表判幂等,避免每次建仓堆一条
|
|
121
|
+
const cur = run(['config', '--global', '--get-all', 'safe.directory'], {});
|
|
122
|
+
const list = String(cur && cur.stdout || '').split('\n').map((x) => x.trim()).filter(Boolean);
|
|
123
|
+
if (list.includes(abs)) return { registered: false, needed: true, skipped: '已登记' };
|
|
124
|
+
const r = run(['config', '--global', '--add', 'safe.directory', abs], {});
|
|
125
|
+
return r && r.ok
|
|
126
|
+
? { registered: true, needed: true }
|
|
127
|
+
: { registered: false, needed: true, stderr: (r && r.stderr) || '写 global safe.directory 失败' };
|
|
128
|
+
}
|
|
129
|
+
|
|
85
130
|
/**
|
|
86
131
|
* 初始化 git 仓库(自动适配不支持 chmod 的文件系统)。
|
|
87
132
|
*
|
|
@@ -112,6 +157,32 @@ export function initRepoCompat(dir, { branch = 'master', remoteUrl = '', chmodOk
|
|
|
112
157
|
}
|
|
113
158
|
}
|
|
114
159
|
|
|
160
|
+
/**
|
|
161
|
+
* 撤销 registerTrustedRepo 的登记(删除 global 里**该具体路径**那一条,不动其它条目)。
|
|
162
|
+
*
|
|
163
|
+
* 为什么成对提供:registerTrustedRepo 写的是用户 global 配置,仓库被删/迁移后条目会变死路径。
|
|
164
|
+
* 不自动清理别人的条目(用户可能有意保留暂时未挂载的路径),只把「谁登记谁注销」的能力交出去——
|
|
165
|
+
* 测试用它做到零污染(不留死条目在真实配置里),运维也可用它收拾残留。
|
|
166
|
+
* @param {string} dir 之前登记过的目录
|
|
167
|
+
* @returns {{removed: boolean, stderr?: string}}
|
|
168
|
+
*/
|
|
169
|
+
export function unregisterTrustedRepo(dir, exec) {
|
|
170
|
+
const run = typeof exec === 'function' ? exec : (args, opts) => runGit(args, opts);
|
|
171
|
+
const abs = resolve(String(dir || ''));
|
|
172
|
+
if (!abs) return { removed: false, stderr: '空路径' };
|
|
173
|
+
// git config --unset-all 的 value 参数按**正则**匹配:路径里的 . \ 等须转义,否则会过宽命中他项
|
|
174
|
+
const pattern = abs.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
175
|
+
const r = run(['config', '--global', '--unset-all', 'safe.directory', pattern], {});
|
|
176
|
+
// 键不存在/无匹配时 git 返回非 0:语义上是「本来就没登记」,视为成功
|
|
177
|
+
if (!r?.ok && !/invalid section|key does not match|no section/i.test(String(r?.stderr || ''))) {
|
|
178
|
+
const cur = run(['config', '--global', '--get-all', 'safe.directory'], {});
|
|
179
|
+
if (String(cur?.stdout || '').split('\n').map((x) => x.trim()).includes(abs)) {
|
|
180
|
+
return { removed: false, stderr: r?.stderr || '注销失败' };
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return { removed: true };
|
|
184
|
+
}
|
|
185
|
+
|
|
115
186
|
/**
|
|
116
187
|
* 现有 .git 是否**真的可用**(不是"目录存在"就算)。
|
|
117
188
|
*
|
|
@@ -149,11 +220,19 @@ export function isUsableRepo(dir) {
|
|
|
149
220
|
*/
|
|
150
221
|
export function ensureUsableLocalRepo(dir, { branch = 'master', remoteUrl = '', remoteName = 'origin', chmodOk, gitInit } = {}) {
|
|
151
222
|
const exec = typeof gitInit === 'function' ? gitInit : (args, opts) => runGit(args, opts);
|
|
152
|
-
if (isUsableRepo(dir))
|
|
223
|
+
if (isUsableRepo(dir)) {
|
|
224
|
+
// keep:不动用户既有仓库结构,但「对外可用」该登记还得登记——
|
|
225
|
+
// 历史建仓与标准 git init 都没写过 global safe.directory,CIFS 卷上外部 git 一直不可用。
|
|
226
|
+
const trusted = registerTrustedRepo(dir, exec);
|
|
227
|
+
return { ok: true, action: 'keep', via: 'existing', filemode: null, trusted };
|
|
228
|
+
}
|
|
153
229
|
const hadPartial = hasGitDir(dir);
|
|
154
230
|
const r = initRepoCompat(dir, { branch, remoteUrl, remoteName, chmodOk, gitInit: exec });
|
|
155
231
|
if (!r.ok) return { ok: false, action: 'failed', via: r.via, filemode: r.filemode, stderr: r.stderr };
|
|
156
|
-
|
|
232
|
+
// 两条 init 路径(标准 git init / 手写降级)都不保证外部裸 git 可用:
|
|
233
|
+
// CIFS forceuid 卷上属主 uid 与进程 uid 不一致,需登记 global safe.directory 才交得出可用仓库。
|
|
234
|
+
const trusted = registerTrustedRepo(dir, exec);
|
|
235
|
+
return { ok: true, action: hadPartial ? 'repair' : 'create', via: r.via, filemode: r.filemode, trusted };
|
|
157
236
|
}
|
|
158
237
|
|
|
159
238
|
/** .git 目录是否已存在(续跑判断:已 init 过就不再重复写)。 */
|
package/lib/git/push.js
CHANGED
|
@@ -62,6 +62,9 @@ export async function commitAndPush({
|
|
|
62
62
|
pushGate = false, pushConfirmed = false, paths = '', remote = '',
|
|
63
63
|
// 推送后是否等 CI 结果(默认不等:多数推送不需要阻塞);ciTimeoutSec 为等待上限
|
|
64
64
|
waitCi = false, ciTimeoutSec = 900,
|
|
65
|
+
// 敏感文件扫描是否执行:**与审计同一开关**(audit 关 ⇒ 不扫),不再享有「强制全仓」特权。
|
|
66
|
+
// 缺省 true 仅为兼容直接调用方(CLI/测试);工具路径由 tool-call 按 cfg.auditEnabled 显式传入。
|
|
67
|
+
scanSensitive = true,
|
|
65
68
|
} = {}) {
|
|
66
69
|
const steps = [];
|
|
67
70
|
if (!repoPath || !existsSync(join(repoPath, '.git'))) return { ok: false, steps: ['预检'], error: `非 git 仓库: ${repoPath || '(空)'}` };
|
|
@@ -140,9 +143,29 @@ export async function commitAndPush({
|
|
|
140
143
|
const vis = await resolveRepoVisibility(repoPath, token);
|
|
141
144
|
const privateExempt = vis.visibility === 'private';
|
|
142
145
|
const visReason = privateExempt ? `private(${vis.owner}/${vis.repo})` : '';
|
|
146
|
+
// ★ 敏感扫描的**作用面**:只扫「本次将提交的文件」,不递归全仓。
|
|
147
|
+
// 为什么(2026-11-06 实测,另一个会话在 CIFS 仓库上复现):scanSensitiveFiles 原实现递归
|
|
148
|
+
// 读全仓每个文件的内容;在 CIFS/SMB 上每文件一次网络往返 ≈ 1 秒 ⇒ 724 文件的仓库 =
|
|
149
|
+
// 分钟级(实测单文件改动卡满 15 分钟仍未返回,而同仓 0 改动秒回——因为零改动会整段跳过)。
|
|
150
|
+
// 且与「改动文件数」无关(扫的是全仓),这正对应用户观察到的「单文件也一样慢」。
|
|
151
|
+
// 提交只关心将要入库的内容 ⇒ 扫变更集即可,语义更准、代价骤降。
|
|
152
|
+
// 变更集来源:paths 精确模式用 pathList;否则解析 preStatus(git status --porcelain)。
|
|
153
|
+
const changedForScan = pathList.length
|
|
154
|
+
? pathList
|
|
155
|
+
: String(preStatus.stdout || '')
|
|
156
|
+
.split('\n')
|
|
157
|
+
.map((l) => l.replace(/\r$/, ''))
|
|
158
|
+
.filter(Boolean)
|
|
159
|
+
.map((line) => {
|
|
160
|
+
const body = line.slice(2).trim(); // 去掉 XY 状态位
|
|
161
|
+
const arrow = body.indexOf(' -> '); // 重命名取新名
|
|
162
|
+
return (arrow >= 0 ? body.slice(arrow + 4) : body).replace(/^"|"$/g, '');
|
|
163
|
+
})
|
|
164
|
+
.filter((rel) => rel && !rel.endsWith('/'));
|
|
165
|
+
// 敏感扫描与审计同地位:审计关闭时不扫(此前无论 audit 开关都会全仓扫,等于特权步骤)。
|
|
143
166
|
const gi = privateExempt
|
|
144
|
-
? { added: 0, files: (await scanSensitiveFiles(repoPath)).map((h) => h.path), baseline: 0, custom: 0, tracked: [], unstaged: [], skipped: 'private-repo-exempt' }
|
|
145
|
-
: await ensureGitignore(repoPath, { customIgnorePatterns });
|
|
167
|
+
? { added: 0, files: scanSensitive ? (await scanSensitiveFiles(repoPath, { onlyPaths: changedForScan })).map((h) => h.path) : [], baseline: 0, custom: 0, tracked: [], unstaged: [], skipped: 'private-repo-exempt' }
|
|
168
|
+
: await ensureGitignore(repoPath, { customIgnorePatterns, onlyPaths: changedForScan, scanSensitive });
|
|
146
169
|
// 敏感文件只报告不动作(既定行为:扫描到不改动 git 忽略,由仓库方自行处理)
|
|
147
170
|
if (gi.files.length) steps.push(`sensitive-scan(${gi.files.length}文件, 只报告)`);
|
|
148
171
|
else if (gi?.added > 0) steps.push(`.gitignore(+${gi.added}条)`);
|
package/lib/git/sensitive.js
CHANGED
|
@@ -109,7 +109,36 @@ async function scanOneSensitiveFile(dir, it, relPath) {
|
|
|
109
109
|
return fields.length ? { path: relPath, fields } : null;
|
|
110
110
|
}
|
|
111
111
|
|
|
112
|
-
|
|
112
|
+
/**
|
|
113
|
+
* 扫描敏感文件。
|
|
114
|
+
* @param {string} repoPath 仓库根
|
|
115
|
+
* @param {{onlyPaths?: string[]|null}} [opts]
|
|
116
|
+
* onlyPaths:**只扫这些相对路径**(提交路径用)。给了就不递归全仓——
|
|
117
|
+
* 提交时关心的只是"将要入库的内容",把全仓 700+ 文件逐个 readFile 在 CIFS/SMB 上
|
|
118
|
+
* 是分钟级开销(实测:单文件改动 commit 卡 2 分 41 秒,而 0 改动秒回 ——
|
|
119
|
+
* 因为零改动会整段跳过本函数,有改动则必然全仓扫一遍)。
|
|
120
|
+
* 缺省(不传/空)= 原行为:递归全仓。
|
|
121
|
+
*/
|
|
122
|
+
export async function scanSensitiveFiles(repoPath, { onlyPaths = null } = {}) {
|
|
123
|
+
if (Array.isArray(onlyPaths)) {
|
|
124
|
+
const hits = [];
|
|
125
|
+
for (const rel0 of onlyPaths) {
|
|
126
|
+
const rel = String(rel0 || '').replace(/\\/g, '/').replace(/^\.\//, '').trim();
|
|
127
|
+
if (!rel || rel.endsWith('/')) continue; // 目录项跳过
|
|
128
|
+
const abs = join(repoPath, rel);
|
|
129
|
+
try {
|
|
130
|
+
const st = await stat(abs);
|
|
131
|
+
if (!st.isFile()) continue;
|
|
132
|
+
} catch { continue; } // 已删除/不可读:跳过
|
|
133
|
+
const slash = rel.lastIndexOf('/');
|
|
134
|
+
const dir = slash >= 0 ? join(repoPath, rel.slice(0, slash)) : repoPath;
|
|
135
|
+
const name = slash >= 0 ? rel.slice(slash + 1) : rel;
|
|
136
|
+
// scanOneSensitiveFile 只看 it.name + dir 拼路径,这里给一个最小 Dirent 形状
|
|
137
|
+
const hit = await scanOneSensitiveFile(dir, { name }, rel);
|
|
138
|
+
if (hit) hits.push(hit);
|
|
139
|
+
}
|
|
140
|
+
return hits;
|
|
141
|
+
}
|
|
113
142
|
const hits = [];
|
|
114
143
|
// 递归扫描:改异步以免在大仓库上逐文件阻塞事件循环
|
|
115
144
|
// (readdir 带 withFileTypes,目录项类型一次带回;内容读取与 stat 同样异步化)
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 外部 linter 委托层 · 探测
|
|
3
|
+
*
|
|
4
|
+
* 职责:判断被审项目是否**自带官方 linter**(配置存在),并**自探测**出可执行的工具路径。
|
|
5
|
+
*
|
|
6
|
+
* 设计口径(docs/2026-11-06-审计插件本体审视与优化方向讨论.案例d3dx.md 方向 A):
|
|
7
|
+
* · 委托层只负责「外部有权威判定源时用它」,绝不在外部工具缺失时硬失败——探测不到即返回 null,
|
|
8
|
+
* 调用方(runner)据此**降级跳过**,交回自研规则(D5:增强件坏了不能拖垮门禁)。
|
|
9
|
+
* · 工具副本按 project-self-tools 存项目 tools/ 目录;本机/CI 没有 tools 副本时回退 PATH 与常见路径。
|
|
10
|
+
*
|
|
11
|
+
* 路径探测四律(tool-self-detection):环境变量覆盖 → 项目 tools/ 自带 → PATH → 常见绝对路径;
|
|
12
|
+
* 每条候选都必须校验**可执行**(-x),仅存在不够(CIFS/noexec 上会存在但跑不了)。
|
|
13
|
+
*/
|
|
14
|
+
import { existsSync, readFileSync, constants, accessSync } from 'node:fs';
|
|
15
|
+
import { join } from 'node:path';
|
|
16
|
+
import { execFileSync } from 'node:child_process';
|
|
17
|
+
|
|
18
|
+
// 插件根:与 ext-runner 同源——统一从 lib/core/config.js 导入,不自行 resolve
|
|
19
|
+
// (两处各算一次是 duplicate-constant,换了目录层级就会不一致;见 ext-runner 同款修复)。
|
|
20
|
+
import { PLUGIN_ROOT } from '../core/config.js';
|
|
21
|
+
|
|
22
|
+
/** 支持的 linter 与其**配置指纹**(探测「项目是否用了它」的依据,均为项目根级文件/字段)。 */
|
|
23
|
+
export const LINTERS = [
|
|
24
|
+
{
|
|
25
|
+
key: 'ruff',
|
|
26
|
+
lang: 'py',
|
|
27
|
+
// 命中任一即认为项目在用 ruff
|
|
28
|
+
configHits: ['ruff.toml', '.ruff.toml'],
|
|
29
|
+
tomlTable: '[tool.ruff',
|
|
30
|
+
// 工具可执行名(PATH 与 tools/ 下同名查找)
|
|
31
|
+
bin: 'ruff',
|
|
32
|
+
envOverride: 'DSH_GIT_PUSH_RUFF',
|
|
33
|
+
},
|
|
34
|
+
];
|
|
35
|
+
|
|
36
|
+
/** 是否可执行(存在 + x 位;Windows 下 existsSync 即可,无 x 位概念)。 */
|
|
37
|
+
function isExecutable(p) {
|
|
38
|
+
try {
|
|
39
|
+
if (!existsSync(p)) return false;
|
|
40
|
+
// process.platform === 'win32' 时不校验 mode(NTFS 无 POSIX x 位)
|
|
41
|
+
if (process.platform === 'win32') return true;
|
|
42
|
+
accessSync(p, constants.X_OK);
|
|
43
|
+
return true;
|
|
44
|
+
} catch {
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 项目根是否存在该 linter 的配置(ruff:独立 toml 或 pyproject 的 [tool.ruff] 段)。 */
|
|
50
|
+
function hasConfig(repoRoot, linter) {
|
|
51
|
+
for (const f of linter.configHits) {
|
|
52
|
+
if (existsSync(join(repoRoot, f))) return true;
|
|
53
|
+
}
|
|
54
|
+
const pyproject = join(repoRoot, 'pyproject.toml');
|
|
55
|
+
if (existsSync(pyproject)) {
|
|
56
|
+
try {
|
|
57
|
+
const txt = readFileSync(pyproject, 'utf8');
|
|
58
|
+
// 粗略匹配 [tool.ruff] / [tool.ruff.lint] 等段头(配置指纹,非语义解析)
|
|
59
|
+
if (txt.includes(linter.tomlTable)) return true;
|
|
60
|
+
} catch { /* 读不动就当没配置 */ }
|
|
61
|
+
}
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 自探测 linter 可执行路径(简版:只要「有没有」,不要「为什么没有」)。
|
|
67
|
+
* 候选清单唯一来源是 binCandidates —— 与 resolveBinDetailed 共用,
|
|
68
|
+
* 避免四律改一处漏一处导致「详版找得到、简版找不到」的自相矛盾。
|
|
69
|
+
* @returns {string|null} 首个可执行候选;全落空 null(调用方降级)
|
|
70
|
+
*/
|
|
71
|
+
export function resolveBin(repoRoot, linter) {
|
|
72
|
+
for (const c of binCandidates(repoRoot, linter)) {
|
|
73
|
+
if (c && isExecutable(c)) return c;
|
|
74
|
+
}
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** PATH 里找可执行(不依赖 which 命令,扫 PATH 各段)。 */
|
|
79
|
+
function tryWhich(bin) {
|
|
80
|
+
const paths = (process.env.PATH || '').split(process.platform === 'win32' ? ';' : ':');
|
|
81
|
+
const exts = process.platform === 'win32' ? ['.exe', '.cmd', ''] : [''];
|
|
82
|
+
for (const dir of paths) {
|
|
83
|
+
if (!dir) continue;
|
|
84
|
+
for (const e of exts) {
|
|
85
|
+
const p = join(dir, bin + e);
|
|
86
|
+
if (isExecutable(p)) return p;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* 探测结果:项目内所有「有配置且工具可执行」的 linter,附版本(拿不到版本不阻断)。
|
|
94
|
+
* @returns {Array<{key,lang,bin,version}>}
|
|
95
|
+
*/
|
|
96
|
+
export function detectLinters(repoRoot) {
|
|
97
|
+
return detectLinterStatus(repoRoot).ok;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* 探测状态全貌(委托层可观测性 bugfix):
|
|
102
|
+
* ok = 可委托(有配置 + 工具可执行)
|
|
103
|
+
* unavailable = **项目声明了要用的 linter,但工具不可用**——必须与「项目根本没配置」区分开。
|
|
104
|
+
*
|
|
105
|
+
* 为什么单列(实测事故):部署副本迁移时 tools/ruff 丢了可执行位(cp/同步不保 mode),
|
|
106
|
+
* 旧行为是静默返回 [],报告里与「项目没装 ruff」完全无法区分——委托层宣称要防的静默空转,
|
|
107
|
+
* 恰恰发生在它自己身上(灯下黑)。unavailable 让这类问题当场可见、且给出修复动作。
|
|
108
|
+
* @returns {{ok: Array<{key,lang,bin,version}>, unavailable: Array<{key,reason}>}}
|
|
109
|
+
*/
|
|
110
|
+
export function detectLinterStatus(repoRoot) {
|
|
111
|
+
const ok = [];
|
|
112
|
+
const unavailable = [];
|
|
113
|
+
for (const linter of LINTERS) {
|
|
114
|
+
if (!hasConfig(repoRoot, linter)) continue;
|
|
115
|
+
const r = resolveBinDetailed(repoRoot, linter);
|
|
116
|
+
if (r.bin) ok.push({ key: linter.key, lang: linter.lang, bin: r.bin, version: tryVersion(r.bin) });
|
|
117
|
+
else unavailable.push({ key: linter.key, reason: r.reason });
|
|
118
|
+
}
|
|
119
|
+
return { ok, unavailable };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** 候选路径清单(四律:env 覆盖 → 插件 tools/ → 项目 tools/ → PATH → 常见绝对路径)。 */
|
|
123
|
+
function binCandidates(repoRoot, linter) {
|
|
124
|
+
const out = [];
|
|
125
|
+
if (process.env[linter.envOverride]) out.push(process.env[linter.envOverride]);
|
|
126
|
+
for (const d of ['tools', 'tool']) {
|
|
127
|
+
out.push(join(PLUGIN_ROOT, d, linter.bin));
|
|
128
|
+
out.push(join(PLUGIN_ROOT, d, linter.bin, linter.bin)); // tools/ruff/ruff(pip --target 装法)
|
|
129
|
+
}
|
|
130
|
+
for (const d of ['tools', 'tool']) out.push(join(repoRoot, d, linter.bin));
|
|
131
|
+
const which = tryWhich(linter.bin);
|
|
132
|
+
if (which) out.push(which);
|
|
133
|
+
out.push('/usr/local/bin/' + linter.bin, '/usr/bin/' + linter.bin);
|
|
134
|
+
return out;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** resolveBin 的详版:落空时给出可诊断原因(区分「存在但缺 +x」与「压根没有」)。 */
|
|
138
|
+
function resolveBinDetailed(repoRoot, linter) {
|
|
139
|
+
const candidates = binCandidates(repoRoot, linter);
|
|
140
|
+
let existsOnly = null;
|
|
141
|
+
for (const c of candidates) {
|
|
142
|
+
if (!c) continue;
|
|
143
|
+
if (isExecutable(c)) return { bin: c };
|
|
144
|
+
if (existsOnly === null && existsSync(c)) existsOnly = c;
|
|
145
|
+
}
|
|
146
|
+
if (existsOnly) {
|
|
147
|
+
return { bin: null, reason: '文件存在但不可执行(疑似同步/拷贝丢了可执行位):' + existsOnly + ';修复:chmod 755 该文件' };
|
|
148
|
+
}
|
|
149
|
+
const n = candidates.filter(Boolean).length;
|
|
150
|
+
return { bin: null, reason: '未找到可执行(探测 ' + n + ' 个候选路径);修复:把 ' + linter.bin + ' 放入 tools/,或 export ' + linter.envOverride + '=路径,或装进 PATH' };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** 取 `bin --version` 首行(失败返回空串,不影响委托)。 */
|
|
154
|
+
function tryVersion(bin) {
|
|
155
|
+
try {
|
|
156
|
+
const out = execFileSync(bin, ['--version'], { encoding: 'utf8', timeout: 8000, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
157
|
+
return String(out).split('\n')[0].trim().slice(0, 40);
|
|
158
|
+
} catch {
|
|
159
|
+
return '';
|
|
160
|
+
}
|
|
161
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 外部 linter 委托层 · 入口(方向 A)
|
|
3
|
+
*
|
|
4
|
+
* 一次调用完成「探测项目自带 linter → 逐个委托执行 → 聚合 finding」。
|
|
5
|
+
* 与 ext-runner 同构:auditFull/auditWithScope 末尾并入其产出,任何环节失败都降级为空数组。
|
|
6
|
+
*
|
|
7
|
+
* 输出契约(供编排层与测试消费):
|
|
8
|
+
* { findings: Array, linted: Array<{key,bin,version,count,note}> }
|
|
9
|
+
* —— linted 记录「本次委托了哪些外部 linter、各产出多少」,让「用没用上外部权威源」在报告里可见
|
|
10
|
+
* (与 treeUsage 同一防再哑思路:委托层若长期空转,报告能看到,不至于误以为外部精度已生效)。
|
|
11
|
+
*/
|
|
12
|
+
import { detectLinters, detectLinterStatus } from './detect.js';
|
|
13
|
+
import { runLinter } from './runner.js';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @param {string} repoRoot 仓库根
|
|
17
|
+
* @param {object} [opts] { linters?: 覆盖探测结果(测试注入用), log? }
|
|
18
|
+
*/
|
|
19
|
+
export async function runLintAdapters(repoRoot, opts = {}) {
|
|
20
|
+
// let:未注入时由探测结果赋值(对 const 赋值会在运行期抛 TypeError,node --check 抓不到)
|
|
21
|
+
let linters = opts.linters;
|
|
22
|
+
const unavailable = [];
|
|
23
|
+
if (!linters) {
|
|
24
|
+
// 走真实探测:unavailable(项目声明了 linter 但工具不可用)必须进 linted,
|
|
25
|
+
// 否则「部署副本迁移丢了 +x」这类问题与「项目压根没配 ruff」在报告里同样沉默——
|
|
26
|
+
// 委托层宣称防静默空转,自己不能再有灯下黑。
|
|
27
|
+
const st = detectLinterStatus(repoRoot);
|
|
28
|
+
linters = st.ok;
|
|
29
|
+
unavailable.push(...st.unavailable);
|
|
30
|
+
}
|
|
31
|
+
const findings = [];
|
|
32
|
+
const linted = [];
|
|
33
|
+
// 不可用项也记一条(count=0 + reason 含修复动作),使「为什么没委托成」可读。
|
|
34
|
+
for (const u of unavailable) {
|
|
35
|
+
linted.push({ key: u.key, bin: '', version: '', count: 0, unavailable: true, note: `未委托:${u.reason}` });
|
|
36
|
+
}
|
|
37
|
+
for (const linter of linters) {
|
|
38
|
+
let res;
|
|
39
|
+
try {
|
|
40
|
+
res = await runLinter(linter, repoRoot);
|
|
41
|
+
} catch (e) {
|
|
42
|
+
res = { findings: [], note: `执行异常降级跳过:${(e && e.message) || e}` };
|
|
43
|
+
}
|
|
44
|
+
findings.push(...res.findings);
|
|
45
|
+
linted.push({ key: linter.key, bin: linter.bin, version: linter.version || '', count: res.findings.length, note: res.note });
|
|
46
|
+
}
|
|
47
|
+
return { findings, linted };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export { detectLinters } from './detect.js';
|
|
@@ -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
|
+
}
|
|
@@ -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
|
+
);
|
package/lib/score/index.js
CHANGED
|
@@ -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
|
|
121
|
-
*
|
|
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 {
|
|
229
|
+
return {
|
|
230
|
+
dims, counts, score, level, weights: weightMap, dynamicWeights,
|
|
231
|
+
// 启用零规则口径时回传清单(空数组=十维都有检测能力);未启用则为 null,调用方据此区分口径
|
|
232
|
+
uncoveredDimensions: coverageKnown ? uncoveredDimensions : null,
|
|
233
|
+
};
|
|
202
234
|
}
|