dsh-devdock 0.0.0-stage → 2.5.0
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/CHANGELOG.md +190 -0
- package/CONTRACT.md +639 -0
- package/LICENSE +21 -0
- package/PUBLISHING.md +175 -0
- package/README.md +272 -2
- package/assets/devdock-256.png +0 -0
- package/assets/devdock-32.png +0 -0
- package/assets/devdock-512.png +0 -0
- package/assets/devdock-64.png +0 -0
- package/assets/icon-256.png +0 -0
- package/assets/screenshots/account-card.png +0 -0
- package/assets/screenshots/cards.png +0 -0
- package/assets/screenshots/manage.png +0 -0
- package/assets/screenshots/push-tab.png +0 -0
- package/assets/screenshots/review.png +0 -0
- package/assets/screenshots/settings.png +0 -0
- package/client.js +12312 -0
- package/cordis.patch.yml +7 -0
- package/icon.svg +6 -0
- package/index.js +95 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +180 -4
- package/src/host/cloudflare.js +1027 -0
- package/src/host/git.js +1664 -0
- package/src/host/github.js +1922 -0
- package/src/host/index.js +4716 -0
- package/src/host/npm.js +424 -0
- package/src/host/npmcli.js +288 -0
- package/src/host/review.js +627 -0
- package/src/host/store.js +1063 -0
|
@@ -0,0 +1,627 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-push — the pre-push review engine (CONTRACT §3d).
|
|
3
|
+
*
|
|
4
|
+
* Two independent passes, deliberately in this order:
|
|
5
|
+
*
|
|
6
|
+
* 1. **Rule pass** — cheap, deterministic, and runs even when no model is
|
|
7
|
+
* reachable. It catches the class of mistake that matters most (a live
|
|
8
|
+
* token, a private key) without spending a token on it. This is also the
|
|
9
|
+
* floor the feature degrades to when the host has no `llm` service.
|
|
10
|
+
* 2. **Model pass** — the selected preset prompts plus the user's own words
|
|
11
|
+
* are sent to the host's model, which returns JSON findings.
|
|
12
|
+
*
|
|
13
|
+
* Neither pass may ever put a secret into a response. The rule pass records
|
|
14
|
+
* positions and a redacted placeholder; the model prompt has already been
|
|
15
|
+
* built from already-collected (and redacted) diff text.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** Severity order, most severe first; used for sorting and for the UI chips. */
|
|
19
|
+
export const SEVERITY_ORDER = ['blocker', 'high', 'medium', 'low', 'info'];
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Built-in review presets.
|
|
23
|
+
*
|
|
24
|
+
* These are code, not stored data: they are the product's opinion about what a
|
|
25
|
+
* pre-push review should look at, and they must survive a user wiping their
|
|
26
|
+
* saved presets. Titles and prompts are Chinese because every visible string in
|
|
27
|
+
* this plugin is.
|
|
28
|
+
*/
|
|
29
|
+
export const BUILTIN_PRESETS = Object.freeze([
|
|
30
|
+
{
|
|
31
|
+
id: 'builtin_secrets_token',
|
|
32
|
+
category: 'secrets',
|
|
33
|
+
title: '令牌与密钥泄漏',
|
|
34
|
+
description: '查找提交内容里露出的访问令牌、API Key、私钥块',
|
|
35
|
+
prompt: [
|
|
36
|
+
'检查以下代码差异,找出任何被写入源码或配置的凭据:GitHub/PAT 令牌、云厂商 API Key、',
|
|
37
|
+
'数据库密码、SSH 或 TLS 私钥、OAuth client secret、webhook 签名密钥。',
|
|
38
|
+
'特别注意:常量字符串、默认配置、注释、示例文件、测试夹具中被硬编码的密钥。',
|
|
39
|
+
'对每处命中给出文件、大致行号和它属于哪一类凭据。不要复述密钥本身。',
|
|
40
|
+
].join('\n'),
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
id: 'builtin_secrets_env',
|
|
44
|
+
category: 'secrets',
|
|
45
|
+
title: '凭据读取方式不当',
|
|
46
|
+
description: '密钥被打印、写进日志,或被当成普通字符串拼接',
|
|
47
|
+
prompt: [
|
|
48
|
+
'检查差异中是否存在让凭据泄漏的使用方式:把 token/password 打进日志或异常消息、',
|
|
49
|
+
'拼接进 URL 后输出、写进 localStorage 或明文文件、在错误提示里回显。',
|
|
50
|
+
'指出具体位置,并给出更安全的写法建议。',
|
|
51
|
+
].join('\n'),
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
id: 'builtin_privacy_pii',
|
|
55
|
+
category: 'privacy',
|
|
56
|
+
title: '个人信息与联系方式',
|
|
57
|
+
description: '真实姓名、手机号、邮箱、身份证号、住址等个人数据',
|
|
58
|
+
prompt: [
|
|
59
|
+
'检查差异中是否包含真实的个人数据:姓名、手机号、邮箱地址、身份证/护照号、',
|
|
60
|
+
'住址、银行卡号、人脸或证件照片引用。测试数据里也应使用明显的占位值而不是真人信息。',
|
|
61
|
+
'对每处命中说明它是真实数据还是占位符。',
|
|
62
|
+
].join('\n'),
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
id: 'builtin_privacy_local',
|
|
66
|
+
category: 'privacy',
|
|
67
|
+
title: '本机与设备信息',
|
|
68
|
+
description: '绝对路径里的用户名、机器名、内网 IP、临时目录',
|
|
69
|
+
prompt: [
|
|
70
|
+
'检查差异中是否泄漏了本机环境信息:包含用户名的绝对路径(如 C:/Users/<姓名>/)、',
|
|
71
|
+
'计算机名、内网 IP、代理地址、公司内部域名、仅在作者机器上存在的临时目录。',
|
|
72
|
+
'这些会让代码在别人机器上失效,也可能暴露内部环境。给出位置与替换建议。',
|
|
73
|
+
].join('\n'),
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
id: 'builtin_integrity_markers',
|
|
77
|
+
category: 'integrity',
|
|
78
|
+
title: '冲突标记与调试残留',
|
|
79
|
+
description: '未解决的合并冲突、console.log、debugger、注释掉的代码',
|
|
80
|
+
prompt: [
|
|
81
|
+
'检查差异中是否残留:未解决的合并冲突标记(<<<<<<< / ======= / >>>>>>>)、',
|
|
82
|
+
'调试语句(console.log、debugger、print、fmt.Println)、被大段注释掉却没有说明的代码、',
|
|
83
|
+
'临时的 TODO/FIXME/XXX 标记。区分「有意保留」和「忘记删除」。',
|
|
84
|
+
].join('\n'),
|
|
85
|
+
},
|
|
86
|
+
{
|
|
87
|
+
id: 'builtin_integrity_tests',
|
|
88
|
+
category: 'integrity',
|
|
89
|
+
title: '测试与实现不一致',
|
|
90
|
+
description: '测试被删除或跳过、空实现、缺少对新增分支的覆盖',
|
|
91
|
+
prompt: [
|
|
92
|
+
'检查差异中新增或修改的逻辑是否有对应测试:是否有测试被删除、被 skip/xfail、',
|
|
93
|
+
'断言被削弱,是否有新函数只有空实现或直接 return 占位,是否有明显未被覆盖的新分支。',
|
|
94
|
+
'指出具体缺口,而不是泛泛要求「补充测试」。',
|
|
95
|
+
].join('\n'),
|
|
96
|
+
},
|
|
97
|
+
{
|
|
98
|
+
id: 'builtin_quality_bugs',
|
|
99
|
+
category: 'quality',
|
|
100
|
+
title: '明显逻辑缺陷',
|
|
101
|
+
description: '空值未处理、边界错误、异步未等待、资源未释放',
|
|
102
|
+
prompt: [
|
|
103
|
+
'检查差异中可能导致运行时错误的问题:未处理的 null/undefined、数组越界、',
|
|
104
|
+
'await 遗漏导致拿到 Promise、异常吞掉后继续执行、文件或连接未关闭、',
|
|
105
|
+
'竞态条件、无限循环风险。对每个问题给出触发条件。',
|
|
106
|
+
].join('\n'),
|
|
107
|
+
},
|
|
108
|
+
{
|
|
109
|
+
id: 'builtin_quality_config',
|
|
110
|
+
category: 'quality',
|
|
111
|
+
title: '硬编码与配置耦合',
|
|
112
|
+
description: '写死的地址、端口、密钥路径、环境假设',
|
|
113
|
+
prompt: [
|
|
114
|
+
'检查差异中是否把本应可配置的值写死:服务器地址、端口、超时时间、',
|
|
115
|
+
'仅适用于某台机器的路径、只在开发环境成立的假设。给出应改为配置项的位置。',
|
|
116
|
+
].join('\n'),
|
|
117
|
+
},
|
|
118
|
+
]);
|
|
119
|
+
|
|
120
|
+
/** The categories the UI groups cards by, in display order. */
|
|
121
|
+
export const REVIEW_CATEGORIES = Object.freeze([
|
|
122
|
+
{ id: 'secrets', label: '敏感信息' },
|
|
123
|
+
{ id: 'privacy', label: '隐私' },
|
|
124
|
+
{ id: 'integrity', label: '完整性' },
|
|
125
|
+
{ id: 'quality', label: '质量' },
|
|
126
|
+
{ id: 'custom', label: '自定义' },
|
|
127
|
+
]);
|
|
128
|
+
|
|
129
|
+
/* ------------------------------------------------------------------ */
|
|
130
|
+
/* Rule pass */
|
|
131
|
+
/* ------------------------------------------------------------------ */
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Known credential shapes.
|
|
135
|
+
*
|
|
136
|
+
* Ordered most-specific first so a GitHub token is not also reported as a
|
|
137
|
+
* generic "high entropy string". `secretKind` is what the finding shows the
|
|
138
|
+
* user; the matched text itself is NEVER returned.
|
|
139
|
+
*/
|
|
140
|
+
const SECRET_PATTERNS = [
|
|
141
|
+
{ id: 'github-pat-classic', label: 'GitHub 经典令牌', re: /\bghp_[A-Za-z0-9]{36}\b/g },
|
|
142
|
+
{ id: 'github-pat-fine', label: 'GitHub 细粒度令牌', re: /\bgithub_pat_[A-Za-z0-9_]{20,}\b/g },
|
|
143
|
+
{ id: 'github-oauth', label: 'GitHub OAuth 令牌', re: /\bgh[osur]_[A-Za-z0-9]{36}\b/g },
|
|
144
|
+
{ id: 'openai-key', label: 'OpenAI API Key', re: /\bsk-[A-Za-z0-9_-]{20,}\b/g },
|
|
145
|
+
{ id: 'aws-access-key', label: 'AWS Access Key', re: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g },
|
|
146
|
+
{ id: 'slack-token', label: 'Slack 令牌', re: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g },
|
|
147
|
+
{ id: 'google-api-key', label: 'Google API Key', re: /\bAIza[0-9A-Za-z_-]{35}\b/g },
|
|
148
|
+
{ id: 'stripe-key', label: 'Stripe 密钥', re: /\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b/g },
|
|
149
|
+
{
|
|
150
|
+
id: 'private-key',
|
|
151
|
+
label: '私钥块',
|
|
152
|
+
re: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY-----/g,
|
|
153
|
+
},
|
|
154
|
+
{
|
|
155
|
+
id: 'bearer-token',
|
|
156
|
+
label: 'Authorization 头中的令牌',
|
|
157
|
+
re: /\bAuthorization\s*:\s*Bearer\s+[A-Za-z0-9._-]{20,}/gi,
|
|
158
|
+
},
|
|
159
|
+
{
|
|
160
|
+
id: 'assigned-secret',
|
|
161
|
+
label: '硬编码的密码 / 密钥',
|
|
162
|
+
re: /\b(?:password|passwd|secret|token|api[_-]?key|access[_-]?key)\b\s*[:=]\s*['"][^'"\s]{12,}['"]/gi,
|
|
163
|
+
},
|
|
164
|
+
];
|
|
165
|
+
|
|
166
|
+
/** Values that are obviously placeholders, so an assignment is not a finding. */
|
|
167
|
+
const PLACEHOLDER_RE = /^(?:x{3,}|\.{3,}|<[^>]*>|\$\{[^}]*\}|change[-_]?me|your[-_]|example|placeholder|dummy|test|todo|redacted|\*+)$/i;
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* 判断一段令牌文本是否「明显是测试夹具的假值」。
|
|
171
|
+
*
|
|
172
|
+
* 测试为了验证扫描器能抓到各种形态,会写 ghp_bbbbbb…、ghp_AAAAAAAA… 这类
|
|
173
|
+
* 重复字符占位符。它们不是真实凭据,报成 blocker 只是噪音。
|
|
174
|
+
*
|
|
175
|
+
* 判定标准(任一命中即视为假值):
|
|
176
|
+
* - 同一字符连续出现 5 次以上(ghp_bbbbbbbb…)
|
|
177
|
+
* - 含 test / example / dummy / fixture / placeholder / sample 字样
|
|
178
|
+
* - 本身就是纯占位符(如 xxxxx、******)
|
|
179
|
+
*
|
|
180
|
+
* @param {string} matched 扫描到的那段文本
|
|
181
|
+
* @returns {boolean}
|
|
182
|
+
*/
|
|
183
|
+
function looksLikeFixture(matched) {
|
|
184
|
+
const text = String(matched ?? '');
|
|
185
|
+
if (text === '') return false;
|
|
186
|
+
// 重复字符:同一字符连续 5 次以上(ghp_bbbbbbbb…、ghp_AAAAAAAA…)
|
|
187
|
+
if (/([A-Za-z0-9])\1{4,}/.test(text)) return true;
|
|
188
|
+
// 明显的占位/测试字眼。用子串判断而非 \b,因为 test 两侧常是下划线
|
|
189
|
+
//(ghp_test_token、github_pat_…),\b 会把下划线当成单词字符导致漏判。
|
|
190
|
+
if (/(?:test|example|dummy|fixture|placeholder|sample|fake|mock)/i.test(text)) return true;
|
|
191
|
+
// 引号或尖括号里包着纯占位符(token: "<your-token-here>"、
|
|
192
|
+
// password = "REPLACE_ME")也要降噪。
|
|
193
|
+
const inner = /['"]([^'"]+)['"]|<([^>]+)>/.exec(text);
|
|
194
|
+
if (inner && PLACEHOLDER_RE.test((inner[1] ?? inner[2] ?? '').trim())) return true;
|
|
195
|
+
// 纯占位符
|
|
196
|
+
if (PLACEHOLDER_RE.test(text)) return true;
|
|
197
|
+
return false;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Scan one text block for credential shapes.
|
|
202
|
+
*
|
|
203
|
+
* Returns findings with a `line` (1-based within the block) and a short,
|
|
204
|
+
* REDACTED excerpt: only the label and enough context to locate the line. The
|
|
205
|
+
* matched secret never leaves this function.
|
|
206
|
+
*
|
|
207
|
+
* @param {string} text
|
|
208
|
+
* @param {{file?: string, lineOffset?: number}} [where]
|
|
209
|
+
* @returns {object[]} findings.
|
|
210
|
+
*/
|
|
211
|
+
export function scanSecrets(text, where = {}) {
|
|
212
|
+
const findings = [];
|
|
213
|
+
const lines = String(text ?? '').split('\n');
|
|
214
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
215
|
+
const line = lines[i];
|
|
216
|
+
if (line.length === 0) continue;
|
|
217
|
+
for (const pattern of SECRET_PATTERNS) {
|
|
218
|
+
pattern.re.lastIndex = 0;
|
|
219
|
+
const match = pattern.re.exec(line);
|
|
220
|
+
if (!match) continue;
|
|
221
|
+
const matched = match[0];
|
|
222
|
+
// 测试夹具里的假令牌(重复字符、test/example 字样等)不是泄露,
|
|
223
|
+
// 对所有令牌类型都跳过,而不只是 assigned-secret 这一种。
|
|
224
|
+
if (looksLikeFixture(matched)) continue;
|
|
225
|
+
// Skip matches that are themselves already redacted.
|
|
226
|
+
if (/(?:\*{3,}|…|\.\.\.)/.test(matched)) continue;
|
|
227
|
+
findings.push({
|
|
228
|
+
severity: 'blocker',
|
|
229
|
+
category: 'secrets',
|
|
230
|
+
title: `疑似${pattern.label}`,
|
|
231
|
+
detail: `第 ${(where.lineOffset ?? 0) + i + 1} 行出现${pattern.label}形态的字符串,`
|
|
232
|
+
+ '其内容已被隐藏。若确实需要提交,请改从环境变量或密钥管理服务读取。',
|
|
233
|
+
file: where.file,
|
|
234
|
+
line: (where.lineOffset ?? 0) + i + 1,
|
|
235
|
+
suggestion: '从代码中移除该值,改从环境变量或 secrets 管理读取,并立即吊销已泄漏的凭据。',
|
|
236
|
+
});
|
|
237
|
+
// One finding per line is enough; a line rarely holds two different kinds
|
|
238
|
+
// and repeating it would bury the useful ones.
|
|
239
|
+
break;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
return findings;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/* ------------------------------------------------------------------ */
|
|
246
|
+
/* Diff collection */
|
|
247
|
+
/* ------------------------------------------------------------------ */
|
|
248
|
+
|
|
249
|
+
/** Files larger than this are summarized instead of being read. */
|
|
250
|
+
export const MAX_FILE_BYTES = 200 * 1024;
|
|
251
|
+
|
|
252
|
+
/** Guard against a runaway diff taking the whole request budget. */
|
|
253
|
+
const MAX_PATCH_CHARS = 400_000;
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* The base a push would start from: the merge-base with the branch's upstream.
|
|
258
|
+
*
|
|
259
|
+
* @param {import('./git.js').GitRunner} runner
|
|
260
|
+
* @param {string} path
|
|
261
|
+
* @param {string} branch
|
|
262
|
+
* @param {Iterable<string>} [secrets]
|
|
263
|
+
* @returns {Promise<{base: string, count: number}|null>} null when nothing is outgoing.
|
|
264
|
+
*/
|
|
265
|
+
async function outgoingRange(runner, path, branch, secrets) {
|
|
266
|
+
if (!branch) return null;
|
|
267
|
+
// Does the branch track an upstream, and does that ref exist locally?
|
|
268
|
+
const upstream = await runner.run(
|
|
269
|
+
['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}'],
|
|
270
|
+
{ cwd: path, allowFailure: true, secrets },
|
|
271
|
+
);
|
|
272
|
+
const upstreamRef = String(upstream.stdout || '').trim();
|
|
273
|
+
let base = '';
|
|
274
|
+
if (upstream.code === 0 && upstreamRef !== '') {
|
|
275
|
+
const resolved = await runner.run(['rev-parse', upstreamRef], {
|
|
276
|
+
cwd: path, allowFailure: true, secrets,
|
|
277
|
+
});
|
|
278
|
+
if (resolved.code === 0) base = String(resolved.stdout || '').trim();
|
|
279
|
+
} else {
|
|
280
|
+
// No upstream: fall back to the matching origin/ ref, which is what the
|
|
281
|
+
// plugin's own push would update.
|
|
282
|
+
const remoteRef = 'refs/remotes/origin/' + branch;
|
|
283
|
+
const resolved = await runner.run(['rev-parse', '--verify', '--quiet', remoteRef], {
|
|
284
|
+
cwd: path, allowFailure: true, secrets,
|
|
285
|
+
});
|
|
286
|
+
if (resolved.code === 0) base = String(resolved.stdout || '').trim();
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// No base at all means this is the FIRST push of a branch: every commit in
|
|
290
|
+
// the history is outgoing, so diff against the empty tree.
|
|
291
|
+
const from = base !== '' ? base : EMPTY_TREE;
|
|
292
|
+
const count = await runner.run(['rev-list', '--count', from + '..HEAD'], {
|
|
293
|
+
cwd: path, allowFailure: true, secrets,
|
|
294
|
+
});
|
|
295
|
+
const n = Number(String(count.stdout || '0').trim());
|
|
296
|
+
if (!Number.isFinite(n) || n <= 0) return null;
|
|
297
|
+
return { base: from, count: n };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** The git empty-tree object, used as the base of a branch's first push. */
|
|
301
|
+
const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Collect the changes that a push would send, for review.
|
|
305
|
+
*
|
|
306
|
+
* Same return shape as collectReviewChanges so callers (and the prompt
|
|
307
|
+
* builder) do not care where the text came from.
|
|
308
|
+
*
|
|
309
|
+
* @param {import('./git.js').GitRunner} runner
|
|
310
|
+
* @param {string} path
|
|
311
|
+
* @param {object} options
|
|
312
|
+
* @returns {Promise<object|null>}
|
|
313
|
+
*/
|
|
314
|
+
async function collectOutgoingChanges(runner, path, options = {}) {
|
|
315
|
+
const branch = await runner.currentBranch(path).catch(() => null);
|
|
316
|
+
const range = await outgoingRange(runner, path, branch, options.secrets);
|
|
317
|
+
if (!range) return null;
|
|
318
|
+
|
|
319
|
+
const maxFiles = Number.isFinite(options.maxFiles) ? Math.max(1, Math.trunc(options.maxFiles)) : 60;
|
|
320
|
+
const numstat = await runner.run(
|
|
321
|
+
['diff', '--numstat', range.base, 'HEAD'],
|
|
322
|
+
{ cwd: path, allowFailure: true, secrets: options.secrets },
|
|
323
|
+
);
|
|
324
|
+
const rows = String(numstat.stdout || '')
|
|
325
|
+
.split('\n')
|
|
326
|
+
.map((line) => line.trim())
|
|
327
|
+
.filter((line) => line !== '')
|
|
328
|
+
.map((line) => {
|
|
329
|
+
const [add, del, ...rest] = line.split('\t');
|
|
330
|
+
return {
|
|
331
|
+
path: rest.join('\t'),
|
|
332
|
+
additions: Number(add) || 0,
|
|
333
|
+
deletions: Number(del) || 0,
|
|
334
|
+
binary: add === '-' || del === '-',
|
|
335
|
+
};
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
const files = [];
|
|
339
|
+
const chunks = [];
|
|
340
|
+
const patchParts = [];
|
|
341
|
+
let budget = MAX_PATCH_CHARS;
|
|
342
|
+
let truncated = false;
|
|
343
|
+
|
|
344
|
+
for (const row of rows) {
|
|
345
|
+
if (files.length >= maxFiles || budget <= 0) { truncated = true; break; }
|
|
346
|
+
if (row.binary) {
|
|
347
|
+
files.push({ path: row.path, additions: 0, deletions: 0, skipped: '二进制文件,未送审' });
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
// A rename shows the full path pair; git accepts either side.
|
|
351
|
+
const patch = await runner.run(
|
|
352
|
+
['diff', '--no-color', '--unified=3', range.base, 'HEAD', '--', row.path],
|
|
353
|
+
{ cwd: path, allowFailure: true, secrets: options.secrets },
|
|
354
|
+
);
|
|
355
|
+
const text = String(patch.stdout || '');
|
|
356
|
+
if (text === '') continue;
|
|
357
|
+
const clipped = text.length > budget ? text.slice(0, budget) : text;
|
|
358
|
+
if (clipped.length < text.length) truncated = true;
|
|
359
|
+
budget -= clipped.length;
|
|
360
|
+
files.push({ path: row.path, additions: row.additions, deletions: row.deletions });
|
|
361
|
+
chunks.push({ path: row.path, text: clipped });
|
|
362
|
+
patchParts.push(clipped);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
if (files.length === 0) return null;
|
|
366
|
+
return {
|
|
367
|
+
files,
|
|
368
|
+
chunks,
|
|
369
|
+
patch: patchParts.join('\n'),
|
|
370
|
+
truncated,
|
|
371
|
+
// Lets the UI and the tool say what was actually examined.
|
|
372
|
+
scope: 'outgoing',
|
|
373
|
+
range,
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* Build a unified, human-readable representation of the changes to review.
|
|
379
|
+
*
|
|
380
|
+
* @param {import('./git.js').GitRunner} runner
|
|
381
|
+
* @param {string} path repository path.
|
|
382
|
+
* @param {object} options
|
|
383
|
+
* @param {boolean} [options.staged] only the index.
|
|
384
|
+
* @param {string[]} [options.includeFiles]
|
|
385
|
+
* @param {number} [options.maxFiles]
|
|
386
|
+
* @param {Iterable<string>} [options.secrets] for redaction.
|
|
387
|
+
* @returns {Promise<{files: object[], chunks: {path: string, text: string}[], patch: string, truncated: boolean}>}
|
|
388
|
+
*/
|
|
389
|
+
export async function collectReviewChanges(runner, path, options = {}) {
|
|
390
|
+
const status = await runner.status(path, { secrets: options.secrets });
|
|
391
|
+
const maxFiles = Number.isFinite(options.maxFiles) ? Math.max(1, Math.trunc(options.maxFiles)) : 60;
|
|
392
|
+
const wanted = Array.isArray(options.includeFiles) && options.includeFiles.length > 0
|
|
393
|
+
? new Set(options.includeFiles)
|
|
394
|
+
: null;
|
|
395
|
+
|
|
396
|
+
const files = [];
|
|
397
|
+
const chunks = [];
|
|
398
|
+
let budget = MAX_PATCH_CHARS;
|
|
399
|
+
let truncated = false;
|
|
400
|
+
|
|
401
|
+
/** Read the exact diff text for one path. */
|
|
402
|
+
const diffFor = async (file, staged) => {
|
|
403
|
+
try {
|
|
404
|
+
const out = await runner.diff(path, {
|
|
405
|
+
file,
|
|
406
|
+
staged: Boolean(staged),
|
|
407
|
+
secrets: options.secrets,
|
|
408
|
+
});
|
|
409
|
+
return String(out && out.patch ? out.patch : '');
|
|
410
|
+
} catch {
|
|
411
|
+
return '';
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
|
|
415
|
+
for (const entry of status.files) {
|
|
416
|
+
if (files.length >= maxFiles) {
|
|
417
|
+
truncated = true;
|
|
418
|
+
break;
|
|
419
|
+
}
|
|
420
|
+
if (wanted && !wanted.has(entry.path)) continue;
|
|
421
|
+
if (entry.conflicted) {
|
|
422
|
+
files.push({ path: entry.path, additions: 0, deletions: 0, skipped: '存在合并冲突,未送审' });
|
|
423
|
+
continue;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
let text = await diffFor(entry.path, entry.staged || options.staged);
|
|
427
|
+
// An untracked file has no diff at all — its whole content IS the change,
|
|
428
|
+
// so it must be read explicitly or the review would silently ignore the
|
|
429
|
+
// most common kind of new secret (a file written and not yet added).
|
|
430
|
+
// `readWorkingFile` already returns a `--no-index` unified diff against
|
|
431
|
+
// /dev/null, so its text can be appended as-is; wrapping it again would
|
|
432
|
+
// double the '+' prefixes and produce nonsense line counts.
|
|
433
|
+
if (text.trim() === '' && entry.untracked) {
|
|
434
|
+
try {
|
|
435
|
+
const body = await runner.readWorkingFile(path, entry.path, MAX_FILE_BYTES, {
|
|
436
|
+
secrets: options.secrets,
|
|
437
|
+
});
|
|
438
|
+
if (body && body.binary) {
|
|
439
|
+
files.push({ path: entry.path, additions: 0, deletions: 0, skipped: '二进制文件,未送审' });
|
|
440
|
+
continue;
|
|
441
|
+
}
|
|
442
|
+
text = String((body && body.text) || '');
|
|
443
|
+
if (text.trim() === '') {
|
|
444
|
+
// Nothing readable: either the file is empty or git declined. Either
|
|
445
|
+
// way there is no content to review, so it is not a failure.
|
|
446
|
+
continue;
|
|
447
|
+
}
|
|
448
|
+
if (text.length >= MAX_FILE_BYTES * 2) {
|
|
449
|
+
files.push({ path: entry.path, additions: 0, deletions: 0, skipped: `超过 ${MAX_FILE_BYTES / 1024} KB,未送审` });
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
} catch {
|
|
453
|
+
files.push({ path: entry.path, additions: 0, deletions: 0, skipped: '无法读取内容' });
|
|
454
|
+
continue;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
if (text.trim() === '') continue;
|
|
458
|
+
|
|
459
|
+
const plus = (text.match(/^\+(?!\+\+)/gm) || []).length;
|
|
460
|
+
const minus = (text.match(/^-(?!--)/gm) || []).length;
|
|
461
|
+
files.push({ path: entry.path, additions: plus, deletions: minus });
|
|
462
|
+
|
|
463
|
+
if (budget <= 0) {
|
|
464
|
+
truncated = true;
|
|
465
|
+
continue;
|
|
466
|
+
}
|
|
467
|
+
const slice = text.length <= budget ? text : text.slice(0, budget);
|
|
468
|
+
if (slice.length < text.length) truncated = true;
|
|
469
|
+
budget -= slice.length;
|
|
470
|
+
chunks.push({ path: entry.path, text: slice });
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
// Nothing in the working tree, but there may still be commits waiting to go
|
|
474
|
+
// out. Reviewing "what a push would send" is the whole point of the feature,
|
|
475
|
+
// so falling back here is what makes the clean-tree case safe instead of a
|
|
476
|
+
// false all-clear.
|
|
477
|
+
if (files.length === 0 && options.includeOutgoing !== false) {
|
|
478
|
+
const outgoing = await collectOutgoingChanges(runner, path, options);
|
|
479
|
+
if (outgoing) return outgoing;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
return {
|
|
483
|
+
files,
|
|
484
|
+
chunks,
|
|
485
|
+
patch: chunks.map((c) => c.text).join('\n'),
|
|
486
|
+
truncated,
|
|
487
|
+
scope: 'working',
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/* ------------------------------------------------------------------ */
|
|
492
|
+
/* Model pass */
|
|
493
|
+
/* ------------------------------------------------------------------ */
|
|
494
|
+
|
|
495
|
+
/** The instruction that shapes the model's reply into parseable JSON. */
|
|
496
|
+
const SYSTEM_PROMPT = [
|
|
497
|
+
'你是一名代码审查员,负责在代码被推送到远端之前做最后一道检查。',
|
|
498
|
+
'你只会收到一次变更的差异文本,没有工具可用,也不能假设自己能看到仓库的其他部分。',
|
|
499
|
+
'',
|
|
500
|
+
'严格按以下要求输出:',
|
|
501
|
+
'1. 只输出一个 JSON 对象,不要 Markdown 代码围栏,不要任何解释性前后缀。',
|
|
502
|
+
'2. 结构为 {"findings":[{...}],"summary":"..."}。',
|
|
503
|
+
'3. 每个 finding 的字段:',
|
|
504
|
+
' severity: blocker | high | medium | low | info',
|
|
505
|
+
' category: secrets | privacy | integrity | quality',
|
|
506
|
+
' title: 一句话说清问题',
|
|
507
|
+
' detail: 为什么这是问题,以及触发条件',
|
|
508
|
+
' file: 相关文件路径(必须来自输入的差异)',
|
|
509
|
+
' line: 大致行号(数字,可省略)',
|
|
510
|
+
' suggestion: 可执行的修复建议',
|
|
511
|
+
'4. summary 用一两句话总结这次变更的整体风险。',
|
|
512
|
+
'5. 不要报告「看起来没问题」之类的空结论;没有问题就返回空 findings 数组。',
|
|
513
|
+
'6. 绝不要把你看到的密钥、密码或令牌原文写进输出,只用「已隐藏」代替。',
|
|
514
|
+
].join('\n');
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* Ask the host's model to review one change set.
|
|
518
|
+
*
|
|
519
|
+
* @param {object} llm the host `llm` service (may be undefined).
|
|
520
|
+
* @param {object} request
|
|
521
|
+
* @returns {Promise<{findings: object[], summary: string, usage?: object, model: object|null}>}
|
|
522
|
+
*/
|
|
523
|
+
export async function runModelReview(llm, request) {
|
|
524
|
+
const { provider, model, reasoningEffort, prompt, signal } = request;
|
|
525
|
+
if (!llm || typeof llm.stream !== 'function' || !provider || !model) {
|
|
526
|
+
return { findings: [], summary: '', model: null };
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
const options = {
|
|
530
|
+
provider,
|
|
531
|
+
model,
|
|
532
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
|
|
533
|
+
system: SYSTEM_PROMPT,
|
|
534
|
+
signal,
|
|
535
|
+
};
|
|
536
|
+
if (reasoningEffort) options.reasoningEffort = reasoningEffort;
|
|
537
|
+
|
|
538
|
+
let text = '';
|
|
539
|
+
let usage;
|
|
540
|
+
for await (const chunk of llm.stream(options)) {
|
|
541
|
+
if (!chunk) continue;
|
|
542
|
+
if (chunk.type === 'text-delta') text += chunk.text;
|
|
543
|
+
else if (chunk.type === 'usage') usage = chunk.usage;
|
|
544
|
+
else if (chunk.type === 'finish' && chunk.reason && chunk.reason.kind === 'error') {
|
|
545
|
+
throw new Error(chunk.reason.failure?.message ?? '模型返回错误');
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
const parsed = parseModelJson(text);
|
|
550
|
+
return {
|
|
551
|
+
findings: parsed.findings,
|
|
552
|
+
summary: parsed.summary,
|
|
553
|
+
usage,
|
|
554
|
+
model: { provider, model },
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* Pull the JSON object out of a model reply.
|
|
560
|
+
*
|
|
561
|
+
* Models wrap JSON in code fences and occasionally add a sentence before or
|
|
562
|
+
* after it, so the extraction is permissive; when nothing parses, the whole
|
|
563
|
+
* reply becomes the summary rather than an error — a review that returned prose
|
|
564
|
+
* is still useful, and failing the request would lose it.
|
|
565
|
+
*
|
|
566
|
+
* @param {string} text
|
|
567
|
+
* @returns {{findings: object[], summary: string}}
|
|
568
|
+
*/
|
|
569
|
+
export function parseModelJson(text) {
|
|
570
|
+
const raw = String(text ?? '').trim();
|
|
571
|
+
if (raw === '') return { findings: [], summary: '' };
|
|
572
|
+
const unfenced = raw.replace(/^```(?:json)?\s*/i, '').replace(/```\s*$/, '').trim();
|
|
573
|
+
const start = unfenced.indexOf('{');
|
|
574
|
+
const end = unfenced.lastIndexOf('}');
|
|
575
|
+
if (start >= 0 && end > start) {
|
|
576
|
+
try {
|
|
577
|
+
const parsed = JSON.parse(unfenced.slice(start, end + 1));
|
|
578
|
+
const findings = Array.isArray(parsed.findings)
|
|
579
|
+
? parsed.findings.filter((f) => f && typeof f === 'object').map(normalizeFinding)
|
|
580
|
+
: [];
|
|
581
|
+
return {
|
|
582
|
+
findings,
|
|
583
|
+
summary: typeof parsed.summary === 'string' ? parsed.summary : '',
|
|
584
|
+
};
|
|
585
|
+
} catch {
|
|
586
|
+
// fall through to the prose fallback
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
return { findings: [], summary: unfenced };
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* Coerce one model-produced finding into the wire shape.
|
|
594
|
+
* @param {object} raw
|
|
595
|
+
* @returns {object}
|
|
596
|
+
*/
|
|
597
|
+
export function normalizeFinding(raw) {
|
|
598
|
+
const severity = SEVERITY_ORDER.includes(raw.severity) ? raw.severity : 'medium';
|
|
599
|
+
const category = typeof raw.category === 'string' && raw.category !== '' ? raw.category : 'quality';
|
|
600
|
+
const line = Number.isFinite(raw.line) ? Math.trunc(raw.line) : undefined;
|
|
601
|
+
return {
|
|
602
|
+
severity,
|
|
603
|
+
category,
|
|
604
|
+
title: String(raw.title ?? '').slice(0, 200) || '未命名问题',
|
|
605
|
+
detail: String(raw.detail ?? '').slice(0, 4000),
|
|
606
|
+
file: typeof raw.file === 'string' ? raw.file : undefined,
|
|
607
|
+
line,
|
|
608
|
+
suggestion: typeof raw.suggestion === 'string' ? raw.suggestion.slice(0, 2000) : undefined,
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/**
|
|
613
|
+
* Sort findings most-severe first, then by file so the panel reads top-down.
|
|
614
|
+
* @param {object[]} findings
|
|
615
|
+
* @returns {object[]}
|
|
616
|
+
*/
|
|
617
|
+
export function sortFindings(findings) {
|
|
618
|
+
const rank = (s) => {
|
|
619
|
+
const i = SEVERITY_ORDER.indexOf(s);
|
|
620
|
+
return i < 0 ? SEVERITY_ORDER.length : i;
|
|
621
|
+
};
|
|
622
|
+
return [...findings].sort((a, b) => {
|
|
623
|
+
const bySeverity = rank(a.severity) - rank(b.severity);
|
|
624
|
+
if (bySeverity !== 0) return bySeverity;
|
|
625
|
+
return String(a.file ?? '').localeCompare(String(b.file ?? ''));
|
|
626
|
+
});
|
|
627
|
+
}
|