dsh-devdock-review 0.0.0-stage → 3.0.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 +30 -0
- package/LICENSE +21 -0
- package/README.md +163 -2
- package/client.js +1657 -0
- package/cordis.patch.yml +11 -0
- package/icon.svg +9 -0
- package/index.js +62 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +122 -4
- package/src/host/platform.js +728 -0
|
@@ -0,0 +1,728 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DevDock · 发布前审查 · 平台定义。
|
|
3
|
+
*
|
|
4
|
+
* 这个包把「审查」从 GitHub / npm 两个平台插件里提出来单独成包。理由:
|
|
5
|
+
*
|
|
6
|
+
* - npm 的发布前审查比 GitHub 的推送前审查更完善(它连 npm pack 会打进去
|
|
7
|
+
* 哪些文件都算了),而两者共用同一套预设、模型选择与结果结构;
|
|
8
|
+
* - 审查是一件事,不该在两个平台里各长一份,否则必然分叉;
|
|
9
|
+
* - GitHub / npm 插件只需要判断「审查插件在不在」,在就给可用入口。
|
|
10
|
+
*
|
|
11
|
+
* ## 与内核的分工
|
|
12
|
+
*
|
|
13
|
+
* 内核仍然持有扫描原语(`scanSecrets` / `runModelReview` / `normalizeFinding`
|
|
14
|
+
* / `sortFindings`)与 Git、npm 的执行器——因为 Cloudflare 的部署前审查也
|
|
15
|
+
* 用同一套原语,把它们搬走会让内核失去那个能力。这个包持有的是**审查产品**
|
|
16
|
+
* 本身:预设目录、路由、编排逻辑、以及「agent 不得自行审查」的闸门。
|
|
17
|
+
*
|
|
18
|
+
* ## 路由
|
|
19
|
+
*
|
|
20
|
+
* 内核把平台路由挂在 `/api/push/review` 之下,所以这里的 `/presets` 实际是
|
|
21
|
+
* `/api/push/review/presets`。
|
|
22
|
+
*
|
|
23
|
+
* @module src/host/platform.js
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
27
|
+
import path from 'node:path';
|
|
28
|
+
|
|
29
|
+
import { GitRunner } from 'dsh-devdock-core/src/host/git.js';
|
|
30
|
+
import { NpmRunner, mapPackResult, parsePackJson } from 'dsh-devdock-core/src/host/npmcli.js';
|
|
31
|
+
import {
|
|
32
|
+
BUILTIN_PRESETS,
|
|
33
|
+
MAX_FILE_BYTES,
|
|
34
|
+
REVIEW_CATEGORIES,
|
|
35
|
+
collectReviewChanges,
|
|
36
|
+
normalizeFinding,
|
|
37
|
+
runModelReview,
|
|
38
|
+
scanSecrets,
|
|
39
|
+
sortFindings,
|
|
40
|
+
} from 'dsh-devdock-core/src/host/review.js';
|
|
41
|
+
|
|
42
|
+
/** 一次审查最多读取的文件数,防止一次点选把整个仓库读进内存。 */
|
|
43
|
+
const DEFAULT_MAX_FILES = 60;
|
|
44
|
+
/** npm 包审查的默认文件上限(包通常比仓库小,但 node_modules 之外仍可能很多)。 */
|
|
45
|
+
const DEFAULT_PACK_MAX_FILES = 80;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 构造审查平台定义。
|
|
49
|
+
*
|
|
50
|
+
* @param {object} context 内核注入的平台上下文(store / llm / httpError …)
|
|
51
|
+
* @returns {object} 归一化前的平台定义
|
|
52
|
+
*/
|
|
53
|
+
export function reviewPlatform(context) {
|
|
54
|
+
const {
|
|
55
|
+
store,
|
|
56
|
+
httpError,
|
|
57
|
+
requireString,
|
|
58
|
+
optionalString,
|
|
59
|
+
optionalBool,
|
|
60
|
+
} = context;
|
|
61
|
+
|
|
62
|
+
/* ---------------- 共用小工具 ---------------- */
|
|
63
|
+
|
|
64
|
+
/** 复用同一个 Git 执行器:二进制与超时只解析一次。 */
|
|
65
|
+
let gitRunner = null;
|
|
66
|
+
const runner = async () => {
|
|
67
|
+
if (gitRunner) return gitRunner;
|
|
68
|
+
const settings = await store.settings();
|
|
69
|
+
gitRunner = new GitRunner({ gitPath: settings.gitPath });
|
|
70
|
+
return gitRunner;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/** 复用同一个 npm 执行器。 */
|
|
74
|
+
let npmRunner = null;
|
|
75
|
+
const npm = () => {
|
|
76
|
+
if (npmRunner) return npmRunner;
|
|
77
|
+
npmRunner = new NpmRunner();
|
|
78
|
+
return npmRunner;
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
/** 当前持有的令牌,用于输出脱敏。 */
|
|
82
|
+
const secretsOf = async () => {
|
|
83
|
+
try {
|
|
84
|
+
return await context.secrets();
|
|
85
|
+
} catch {
|
|
86
|
+
return [];
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 选中的预设 + 用户自定义提示词。
|
|
92
|
+
*
|
|
93
|
+
* 内置项从代码取,自定义项从存储取;两者的 id 空间是分开的,所以一次
|
|
94
|
+
* 勾选可能同时命中两张表。
|
|
95
|
+
*/
|
|
96
|
+
const choosePresets = async (body) => {
|
|
97
|
+
const presetIds = Array.isArray(body.presetIds)
|
|
98
|
+
? body.presetIds.filter((id) => typeof id === 'string' && id !== '')
|
|
99
|
+
: [];
|
|
100
|
+
const custom = await store.reviewPresets();
|
|
101
|
+
return [
|
|
102
|
+
...BUILTIN_PRESETS.filter((preset) => presetIds.includes(preset.id)),
|
|
103
|
+
...custom.filter((preset) => presetIds.includes(preset.id)),
|
|
104
|
+
];
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* 解析出实际要用的 provider / model。
|
|
109
|
+
*
|
|
110
|
+
* 调用方没指定时用宿主给出的默认值;仍然没有就交给 runModelReview 干净地
|
|
111
|
+
* 降级(只跑规则检查),而不是抛错——审查永远不该挡住操作。
|
|
112
|
+
*/
|
|
113
|
+
const resolveModel = async (body) => {
|
|
114
|
+
const llm = context.llm();
|
|
115
|
+
let provider = optionalString(body.provider);
|
|
116
|
+
let model = optionalString(body.model);
|
|
117
|
+
if (llm && (!provider || !model)) {
|
|
118
|
+
try {
|
|
119
|
+
const fallback = await context.reviewModels();
|
|
120
|
+
if (fallback.default) {
|
|
121
|
+
provider = provider ?? fallback.default.provider;
|
|
122
|
+
model = model ?? fallback.default.model;
|
|
123
|
+
}
|
|
124
|
+
} catch { /* 保留调用方给的值 */ }
|
|
125
|
+
}
|
|
126
|
+
return { llm, provider, model };
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
/** 预设提示词 + 用户补充要求 → 一段指令文本。 */
|
|
130
|
+
const instructionsOf = (chosen, customPrompt) => [
|
|
131
|
+
...chosen.map((preset) => `## ${preset.title}\n${preset.prompt}`),
|
|
132
|
+
...(customPrompt ? [`## 用户补充要求\n${customPrompt}`] : []),
|
|
133
|
+
].join('\n\n');
|
|
134
|
+
|
|
135
|
+
/** 默认摘要:没内容时说「没有」,有问题时报数量,而不是留空让界面瞎猜。 */
|
|
136
|
+
const summaryOf = (summary, findings) => {
|
|
137
|
+
if (summary !== '') return summary;
|
|
138
|
+
return findings.length === 0 ? '未发现明显问题。' : `共发现 ${findings.length} 处需要关注的问题。`;
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
/* ---------------- agent 审查闸门 ---------------- */
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* 等待用户确认的审查请求。
|
|
145
|
+
*
|
|
146
|
+
* **这是安全策略,不是 UI 便利**:审查会读取整个项目的改动内容,模型
|
|
147
|
+
* 不能自行决定「我要读一遍这个仓库」。所以 agent 调用 review 时只登记
|
|
148
|
+
* 一个请求,由界面打开配置窗口,用户确认后才真正执行。
|
|
149
|
+
*
|
|
150
|
+
* 只有一个槽位:用户还没点的时候再请求一次,会得到 `already_pending`
|
|
151
|
+
* 而不是排队——否则 agent 可能在一个循环里不断堆积请求。
|
|
152
|
+
*/
|
|
153
|
+
let pending = null;
|
|
154
|
+
|
|
155
|
+
const publicPending = () => {
|
|
156
|
+
if (!pending) return null;
|
|
157
|
+
return {
|
|
158
|
+
id: pending.id,
|
|
159
|
+
path: pending.path,
|
|
160
|
+
presetIds: [...pending.presetIds],
|
|
161
|
+
customPrompt: pending.customPrompt,
|
|
162
|
+
source: pending.source,
|
|
163
|
+
createdAt: pending.createdAt,
|
|
164
|
+
};
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
const raise = (request) => {
|
|
168
|
+
if (pending) {
|
|
169
|
+
return {
|
|
170
|
+
status: 'already_pending',
|
|
171
|
+
message: '已有一个待确认的审查请求,用户尚未在界面中确认。不要重复请求,也不要自行执行审查。',
|
|
172
|
+
pending: publicPending(),
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
pending = {
|
|
176
|
+
id: `rvreq_${Date.now().toString(36)}`,
|
|
177
|
+
path: String(request.path ?? ''),
|
|
178
|
+
presetIds: Array.isArray(request.presetIds) ? request.presetIds : [],
|
|
179
|
+
customPrompt: String(request.customPrompt ?? ''),
|
|
180
|
+
source: String(request.source ?? 'agent'),
|
|
181
|
+
createdAt: Date.now(),
|
|
182
|
+
};
|
|
183
|
+
return {
|
|
184
|
+
status: 'awaiting_user',
|
|
185
|
+
message: '已在界面中打开审查配置窗口,等待用户选择审查项。在用户确认并开始之前,不要再次调用 review,也不要用其他方式自行执行审查。',
|
|
186
|
+
pending: publicPending(),
|
|
187
|
+
};
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
/* ---------------- 三种审查对象 ---------------- */
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* 审查 git 待推送的改动。
|
|
194
|
+
*
|
|
195
|
+
* @param {object} body `{ path, presetIds, customPrompt, provider, model,
|
|
196
|
+
* reasoningEffort, staged, includeFiles, maxFiles }`
|
|
197
|
+
* @returns {Promise<object>}
|
|
198
|
+
*/
|
|
199
|
+
async function runGitReview(body) {
|
|
200
|
+
const repoPath = requireString(body, 'path', '仓库路径');
|
|
201
|
+
const secrets = await secretsOf();
|
|
202
|
+
const git = await runner();
|
|
203
|
+
const root = (await git.assertRepo(repoPath, { secrets })).root;
|
|
204
|
+
|
|
205
|
+
const chosen = await choosePresets(body);
|
|
206
|
+
const customPrompt = optionalString(body.customPrompt) ?? '';
|
|
207
|
+
|
|
208
|
+
const changes = await collectReviewChanges(git, root, {
|
|
209
|
+
staged: optionalBool(body.staged, false),
|
|
210
|
+
includeFiles: Array.isArray(body.includeFiles) ? body.includeFiles : undefined,
|
|
211
|
+
maxFiles: Number.isFinite(body.maxFiles) ? body.maxFiles : DEFAULT_MAX_FILES,
|
|
212
|
+
secrets,
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
// ---- 第一遍:规则扫描。永远执行,不花 token。 ----
|
|
216
|
+
const ruleFindings = [];
|
|
217
|
+
for (const chunk of changes.chunks) {
|
|
218
|
+
ruleFindings.push(...scanSecrets(chunk.text, { file: chunk.path }));
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// ---- 第二遍:模型审查(尽力而为)。 ----
|
|
222
|
+
const { llm, provider, model } = await resolveModel(body);
|
|
223
|
+
|
|
224
|
+
const promptParts = [];
|
|
225
|
+
const instructions = instructionsOf(chosen, customPrompt);
|
|
226
|
+
if (instructions !== '') promptParts.push(instructions);
|
|
227
|
+
|
|
228
|
+
promptParts.push('## 审查范围');
|
|
229
|
+
promptParts.push(changes.scope === 'outgoing'
|
|
230
|
+
? `当前分支有 ${changes.range ? changes.range.count : '若干'} 个提交尚未推送,本次审查的是它们相对远端的差异。`
|
|
231
|
+
: '本次审查的是工作区中尚未提交的改动。');
|
|
232
|
+
/* 少了这段,模型会把「文件列表里没有」误读成「项目缺少文件」——在发布
|
|
233
|
+
* 前那种最要紧的审查上,这是最典型的误报来源。 */
|
|
234
|
+
promptParts.push('注意:文件列表只包含本次改动涉及的文件。未出现在列表中的文件属于仓库既有内容,'
|
|
235
|
+
+ '不代表它们不存在、未提交或不随包发布——不要据此推断项目缺少文件。');
|
|
236
|
+
if (changes.truncated === true) {
|
|
237
|
+
promptParts.push('严重提示:本次差异因体积限制被截断,你看到的内容并不完整。'
|
|
238
|
+
+ '不要因为某个改动看起来缺失就断定功能不完整,只针对你实际看到的内容报告问题。');
|
|
239
|
+
}
|
|
240
|
+
promptParts.push(`## 变更文件(${changes.files.length} 个)`);
|
|
241
|
+
promptParts.push(changes.files
|
|
242
|
+
.map((file) => `- ${file.path}${file.skipped ? `(未送审:${file.skipped})` : ''}`)
|
|
243
|
+
.join('\n'));
|
|
244
|
+
promptParts.push('## 差异');
|
|
245
|
+
promptParts.push(changes.patch === '' ? '(没有可审查的改动)' : changes.patch);
|
|
246
|
+
|
|
247
|
+
let modelFindings = [];
|
|
248
|
+
let summary = '';
|
|
249
|
+
let usage;
|
|
250
|
+
let degraded = false;
|
|
251
|
+
|
|
252
|
+
if (changes.patch === '') {
|
|
253
|
+
summary = '没有检测到待推送的改动。';
|
|
254
|
+
} else if (!llm) {
|
|
255
|
+
degraded = true;
|
|
256
|
+
summary = '宿主未提供 llm 服务,本次只执行了规则检查(敏感信息扫描)。';
|
|
257
|
+
} else if (!provider || !model) {
|
|
258
|
+
degraded = true;
|
|
259
|
+
summary = '未找到可用的模型,本次只执行了规则检查(敏感信息扫描)。';
|
|
260
|
+
} else {
|
|
261
|
+
try {
|
|
262
|
+
const result = await runModelReview(llm, {
|
|
263
|
+
provider,
|
|
264
|
+
model,
|
|
265
|
+
reasoningEffort: optionalString(body.reasoningEffort),
|
|
266
|
+
prompt: promptParts.join('\n\n'),
|
|
267
|
+
});
|
|
268
|
+
modelFindings = result.findings.map(normalizeFinding);
|
|
269
|
+
summary = result.summary;
|
|
270
|
+
usage = result.usage;
|
|
271
|
+
} catch (error) {
|
|
272
|
+
degraded = true;
|
|
273
|
+
summary = `模型审查失败(${String(error && error.message ? error.message : error)}),本次只执行了规则检查。`;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const findings = sortFindings([...ruleFindings, ...modelFindings]);
|
|
278
|
+
return {
|
|
279
|
+
reviewId: `review_${Date.now().toString(36)}`,
|
|
280
|
+
scope: 'git',
|
|
281
|
+
model: provider && model ? { provider, model, label: `${provider} / ${model}` } : null,
|
|
282
|
+
effort: optionalString(body.reasoningEffort) ?? null,
|
|
283
|
+
files: changes.files,
|
|
284
|
+
findings,
|
|
285
|
+
summary: summaryOf(summary, findings),
|
|
286
|
+
usage,
|
|
287
|
+
degraded,
|
|
288
|
+
truncated: changes.truncated,
|
|
289
|
+
// "working" = 未提交改动;"outgoing" = 推送会发出去的提交。
|
|
290
|
+
// 两个问题不同,界面必须说清回答的是哪个,否则「干净」会被误读。
|
|
291
|
+
changesScope: changes.scope === 'outgoing' ? 'outgoing' : 'working',
|
|
292
|
+
outgoingCommits: changes.range ? changes.range.count : 0,
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* 审查 npm 会打进去的包内容。
|
|
298
|
+
*
|
|
299
|
+
* 依赖正在运行的 npm 自己算文件清单:`files` 字段、`.npmignore`、默认
|
|
300
|
+
* 忽略项的规则复杂到不值得重写,而用户之后手动 `npm publish` 的正是这份
|
|
301
|
+
* 清单。
|
|
302
|
+
*
|
|
303
|
+
* @param {object} body
|
|
304
|
+
* @returns {Promise<object>}
|
|
305
|
+
*/
|
|
306
|
+
async function runPackageReview(body) {
|
|
307
|
+
const dir = typeof body.path === 'string' && body.path.trim() !== ''
|
|
308
|
+
? body.path.trim()
|
|
309
|
+
: process.cwd();
|
|
310
|
+
|
|
311
|
+
// 1. npm 会打进去哪些文件——与打包面板同一数据源,结果必然一致。
|
|
312
|
+
const packed = mapPackResult(parsePackJson(
|
|
313
|
+
(await npm().run(['pack', '--dry-run', '--json'], { cwd: dir })).stdout,
|
|
314
|
+
));
|
|
315
|
+
|
|
316
|
+
// 2. 读这些文件的文本内容。二进制与超大文件跳过并记下原因。
|
|
317
|
+
const maxFiles = Number.isFinite(body.maxFiles) ? Number(body.maxFiles) : DEFAULT_PACK_MAX_FILES;
|
|
318
|
+
const files = [];
|
|
319
|
+
const chunks = [];
|
|
320
|
+
let truncated = false;
|
|
321
|
+
|
|
322
|
+
for (const row of packed.files) {
|
|
323
|
+
if (chunks.length >= maxFiles) { truncated = true; break; }
|
|
324
|
+
const rel = row.path.replace(/\/$/, '');
|
|
325
|
+
if (/(^|\/)(node_modules|\.git)\//.test(rel)) continue;
|
|
326
|
+
if (row.size > MAX_FILE_BYTES) {
|
|
327
|
+
files.push({ path: rel, skipped: '文件过大' });
|
|
328
|
+
truncated = true;
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
let text;
|
|
332
|
+
try {
|
|
333
|
+
text = await readFile(path.join(dir, rel), 'utf8');
|
|
334
|
+
} catch {
|
|
335
|
+
files.push({ path: rel, skipped: '无法读取' });
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
if (text.includes('\u0000')) {
|
|
339
|
+
files.push({ path: rel, skipped: '二进制文件' });
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
files.push({ path: rel });
|
|
343
|
+
chunks.push({ path: rel, text });
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// 3. 规则扫描:永远执行。
|
|
347
|
+
const ruleFindings = [];
|
|
348
|
+
for (const chunk of chunks) {
|
|
349
|
+
ruleFindings.push(...scanSecrets(chunk.text, { file: chunk.path }));
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// 4. 包完整性:这不是「代码问题」,但发布前必须看见。
|
|
353
|
+
if (packed.totalFiles === 0) {
|
|
354
|
+
ruleFindings.push(normalizeFinding({
|
|
355
|
+
severity: 'blocker',
|
|
356
|
+
title: '包内没有任何文件',
|
|
357
|
+
detail: 'npm pack 没有收集到文件,发布出去会是一个空包。检查 files 字段与 .npmignore。',
|
|
358
|
+
file: 'package.json',
|
|
359
|
+
}));
|
|
360
|
+
}
|
|
361
|
+
if (!packed.files.some((row) => /(^|\/)readme(\.md|\.txt)?$/i.test(row.path))) {
|
|
362
|
+
ruleFindings.push(normalizeFinding({
|
|
363
|
+
severity: 'medium',
|
|
364
|
+
title: '包里没有 README',
|
|
365
|
+
detail: 'npm 页面会没有任何说明文字,用户看到的是一个空白页。',
|
|
366
|
+
file: 'README.md',
|
|
367
|
+
}));
|
|
368
|
+
}
|
|
369
|
+
const sizeLimit = 10 * 1024 * 1024;
|
|
370
|
+
if (packed.size !== null && packed.size > sizeLimit) {
|
|
371
|
+
ruleFindings.push(normalizeFinding({
|
|
372
|
+
severity: 'medium',
|
|
373
|
+
title: '包体积偏大',
|
|
374
|
+
detail: `压缩后 ${Math.round(packed.size / 1024)} KB。检查是否误把构建产物或测试数据打进来了。`,
|
|
375
|
+
file: 'package.json',
|
|
376
|
+
}));
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// 5. 模型审查。
|
|
380
|
+
const chosen = await choosePresets(body);
|
|
381
|
+
const customPrompt = optionalString(body.customPrompt) ?? '';
|
|
382
|
+
const { llm, provider, model } = await resolveModel(body);
|
|
383
|
+
|
|
384
|
+
const promptParts = [];
|
|
385
|
+
const instructions = instructionsOf(chosen, customPrompt);
|
|
386
|
+
if (instructions !== '') promptParts.push(instructions);
|
|
387
|
+
promptParts.push('## 审查范围');
|
|
388
|
+
promptParts.push('本次审查的是 npm 发布包的内容:以下文件就是 npm pack 会打进去的全部文件,'
|
|
389
|
+
+ '不代表项目里只有这些文件。未列出的文件不会随包发布,不要据此推断项目缺少文件。');
|
|
390
|
+
promptParts.push(`## 包内文件(${files.length} 个,压缩后 ${packed.size ?? 0} 字节)`);
|
|
391
|
+
promptParts.push(files
|
|
392
|
+
.map((file) => `- ${file.path}${file.skipped ? `(未送审:${file.skipped})` : ''}`)
|
|
393
|
+
.join('\n'));
|
|
394
|
+
promptParts.push('## 内容');
|
|
395
|
+
promptParts.push(chunks.length === 0
|
|
396
|
+
? '(没有可审查的文本内容)'
|
|
397
|
+
: chunks.map((chunk) => `### ${chunk.path}\n\`\`\`\n${chunk.text}\n\`\`\``).join('\n\n'));
|
|
398
|
+
if (truncated) {
|
|
399
|
+
promptParts.push('严重提示:因体积或数量限制,本次内容并不完整。只针对你实际看到的内容报告问题。');
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
let modelFindings = [];
|
|
403
|
+
let summary = '';
|
|
404
|
+
let usage;
|
|
405
|
+
let degraded = false;
|
|
406
|
+
|
|
407
|
+
if (!llm) {
|
|
408
|
+
degraded = true;
|
|
409
|
+
summary = '宿主未提供 llm 服务,本次只执行了规则检查(敏感信息扫描)。';
|
|
410
|
+
} else if (!provider || !model) {
|
|
411
|
+
degraded = true;
|
|
412
|
+
summary = '未找到可用的模型,本次只执行了规则检查(敏感信息扫描)。';
|
|
413
|
+
} else if (chunks.length === 0) {
|
|
414
|
+
summary = '包里没有可审查的文本内容。';
|
|
415
|
+
} else {
|
|
416
|
+
try {
|
|
417
|
+
const result = await runModelReview(llm, {
|
|
418
|
+
provider,
|
|
419
|
+
model,
|
|
420
|
+
reasoningEffort: optionalString(body.reasoningEffort),
|
|
421
|
+
prompt: promptParts.join('\n\n'),
|
|
422
|
+
});
|
|
423
|
+
modelFindings = result.findings.map(normalizeFinding);
|
|
424
|
+
summary = result.summary;
|
|
425
|
+
usage = result.usage;
|
|
426
|
+
} catch (error) {
|
|
427
|
+
degraded = true;
|
|
428
|
+
summary = `模型审查失败(${String(error && error.message ? error.message : error)}),本次只执行了规则检查。`;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
const findings = sortFindings([...ruleFindings, ...modelFindings]);
|
|
433
|
+
return {
|
|
434
|
+
reviewId: `npmreview_${Date.now().toString(36)}`,
|
|
435
|
+
scope: 'package',
|
|
436
|
+
model: provider && model ? { provider, model, label: `${provider} / ${model}` } : null,
|
|
437
|
+
effort: optionalString(body.reasoningEffort) ?? null,
|
|
438
|
+
files,
|
|
439
|
+
findings,
|
|
440
|
+
summary: summaryOf(summary, findings),
|
|
441
|
+
usage,
|
|
442
|
+
degraded,
|
|
443
|
+
truncated,
|
|
444
|
+
pack: {
|
|
445
|
+
totalFiles: packed.totalFiles,
|
|
446
|
+
size: packed.size,
|
|
447
|
+
unpackedSize: packed.unpackedSize,
|
|
448
|
+
},
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* 一次审查覆盖整个项目:git 未提交改动 + npm 包内容。
|
|
454
|
+
*
|
|
455
|
+
* 同一份代码既是 git 的改动源,也是 npm 的发布内容。跑两次既慢又会让同
|
|
456
|
+
* 一个问题报两遍,所以这里一次收齐,结果按 scope 标注来源。
|
|
457
|
+
*
|
|
458
|
+
* @param {object} body
|
|
459
|
+
* @returns {Promise<object>}
|
|
460
|
+
*/
|
|
461
|
+
async function runProjectReview(body) {
|
|
462
|
+
const dir = typeof body.path === 'string' && body.path.trim() !== ''
|
|
463
|
+
? body.path.trim()
|
|
464
|
+
: process.cwd();
|
|
465
|
+
|
|
466
|
+
const collections = [];
|
|
467
|
+
const skipped = [];
|
|
468
|
+
|
|
469
|
+
/* ---- 1. git 改动 ---- */
|
|
470
|
+
if (body.includeGit !== false) {
|
|
471
|
+
const gitDir = path.join(dir, '.git');
|
|
472
|
+
let isRepo = false;
|
|
473
|
+
try { isRepo = (await stat(gitDir)).isDirectory(); } catch { isRepo = false; }
|
|
474
|
+
if (isRepo) {
|
|
475
|
+
try {
|
|
476
|
+
const secrets = await secretsOf();
|
|
477
|
+
const git = await runner();
|
|
478
|
+
const root = (await git.assertRepo(dir, { secrets })).root;
|
|
479
|
+
const changes = await collectReviewChanges(git, root, {
|
|
480
|
+
staged: false,
|
|
481
|
+
maxFiles: Number.isFinite(body.maxFiles) ? Number(body.maxFiles) : DEFAULT_MAX_FILES,
|
|
482
|
+
secrets,
|
|
483
|
+
});
|
|
484
|
+
for (const chunk of changes.chunks) {
|
|
485
|
+
collections.push({ scope: 'git', path: chunk.path, text: chunk.text });
|
|
486
|
+
}
|
|
487
|
+
if (changes.truncated) skipped.push({ scope: 'git', reason: '改动过多,已截断' });
|
|
488
|
+
} catch (error) {
|
|
489
|
+
skipped.push({ scope: 'git', reason: error.message });
|
|
490
|
+
}
|
|
491
|
+
} else {
|
|
492
|
+
skipped.push({ scope: 'git', reason: '不是 git 仓库' });
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/* ---- 2. npm 包内容 ---- */
|
|
497
|
+
let packed = null;
|
|
498
|
+
if (body.includePack !== false) {
|
|
499
|
+
try {
|
|
500
|
+
await readFile(path.join(dir, 'package.json'), 'utf8');
|
|
501
|
+
packed = mapPackResult(parsePackJson(
|
|
502
|
+
(await npm().run(['pack', '--dry-run', '--json'], { cwd: dir })).stdout,
|
|
503
|
+
));
|
|
504
|
+
for (const row of packed.files) {
|
|
505
|
+
const rel = row.path.replace(/\/$/, '');
|
|
506
|
+
if (/(^|\/)(node_modules|\.git)\//.test(rel)) continue;
|
|
507
|
+
// 已经在 git 里出现过的文件不重复审:同一份内容只报一次。
|
|
508
|
+
if (collections.some((row2) => row2.path === rel)) continue;
|
|
509
|
+
if (row.size > MAX_FILE_BYTES) {
|
|
510
|
+
skipped.push({ scope: 'npm', reason: `${rel} 过大` });
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
513
|
+
try {
|
|
514
|
+
const text = await readFile(path.join(dir, rel), 'utf8');
|
|
515
|
+
if (text.includes('\u0000')) continue;
|
|
516
|
+
collections.push({ scope: 'npm', path: rel, text });
|
|
517
|
+
} catch { /* 读不到就跳过 */ }
|
|
518
|
+
}
|
|
519
|
+
} catch (error) {
|
|
520
|
+
skipped.push({ scope: 'npm', reason: error.code === 'ENOENT' ? '没有 package.json' : error.message });
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/* ---- 3. 规则扫描 ---- */
|
|
525
|
+
const ruleFindings = [];
|
|
526
|
+
for (const row of collections) {
|
|
527
|
+
for (const finding of scanSecrets(row.text, { file: row.path })) {
|
|
528
|
+
ruleFindings.push({ ...normalizeFinding(finding), scope: row.scope });
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/* ---- 4. 模型审查(一次覆盖全部内容) ---- */
|
|
533
|
+
const chosen = await choosePresets(body);
|
|
534
|
+
const customPrompt = optionalString(body.customPrompt) ?? '';
|
|
535
|
+
const { llm, provider, model } = await resolveModel(body);
|
|
536
|
+
|
|
537
|
+
const scopes = new Set(collections.map((row) => row.scope));
|
|
538
|
+
let modelFindings = [];
|
|
539
|
+
let summary = '';
|
|
540
|
+
let usage;
|
|
541
|
+
let degraded = false;
|
|
542
|
+
|
|
543
|
+
if (collections.length === 0) {
|
|
544
|
+
summary = '没有可审查的内容:既没有未提交的 git 改动,也没有可打包的 npm 文件。';
|
|
545
|
+
} else if (!llm) {
|
|
546
|
+
degraded = true;
|
|
547
|
+
summary = '宿主未提供 llm 服务,本次只执行了规则检查(敏感信息扫描)。';
|
|
548
|
+
} else if (!provider || !model) {
|
|
549
|
+
degraded = true;
|
|
550
|
+
summary = '未找到可用的模型,本次只执行了规则检查(敏感信息扫描)。';
|
|
551
|
+
} else {
|
|
552
|
+
const promptParts = [];
|
|
553
|
+
const instructions = instructionsOf(chosen, customPrompt);
|
|
554
|
+
if (instructions !== '') promptParts.push(instructions);
|
|
555
|
+
promptParts.push('## 审查范围');
|
|
556
|
+
promptParts.push('这是一个项目的完整待发布内容,包含两部分:'
|
|
557
|
+
+ 'git 未提交改动(即将提交)和 npm 包内容(即将发布)。'
|
|
558
|
+
+ '同一条问题只报一次,报告时说明它影响哪一部分。'
|
|
559
|
+
+ '未列出的文件不代表项目缺少文件,只代表本次不涉及。');
|
|
560
|
+
promptParts.push(`## 文件(${collections.length} 个)`);
|
|
561
|
+
promptParts.push(collections.map((row) => `- [${row.scope}] ${row.path}`).join('\n'));
|
|
562
|
+
promptParts.push('## 内容');
|
|
563
|
+
promptParts.push(collections.map((row) =>
|
|
564
|
+
`### [${row.scope}] ${row.path}\n\`\`\`\n${row.text}\n\`\`\``).join('\n\n'));
|
|
565
|
+
|
|
566
|
+
try {
|
|
567
|
+
const result = await runModelReview(llm, {
|
|
568
|
+
provider,
|
|
569
|
+
model,
|
|
570
|
+
reasoningEffort: optionalString(body.reasoningEffort),
|
|
571
|
+
prompt: promptParts.join('\n\n'),
|
|
572
|
+
});
|
|
573
|
+
modelFindings = result.findings.map((row) => ({
|
|
574
|
+
...normalizeFinding(row),
|
|
575
|
+
scope: row.scope || (scopes.size > 1 ? 'both' : [...scopes][0] || 'project'),
|
|
576
|
+
}));
|
|
577
|
+
summary = result.summary;
|
|
578
|
+
usage = result.usage;
|
|
579
|
+
} catch (error) {
|
|
580
|
+
degraded = true;
|
|
581
|
+
summary = `模型审查失败(${String(error && error.message ? error.message : error)}),本次只执行了规则检查。`;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
const findings = sortFindings([...ruleFindings, ...modelFindings]);
|
|
586
|
+
return {
|
|
587
|
+
reviewId: `project_${Date.now().toString(36)}`,
|
|
588
|
+
scope: 'project',
|
|
589
|
+
model: provider && model ? { provider, model, label: `${provider} / ${model}` } : null,
|
|
590
|
+
effort: optionalString(body.reasoningEffort) ?? null,
|
|
591
|
+
files: collections.map((row) => ({ path: row.path, scope: row.scope })),
|
|
592
|
+
findings,
|
|
593
|
+
summary: summaryOf(summary, findings),
|
|
594
|
+
usage,
|
|
595
|
+
degraded,
|
|
596
|
+
skipped,
|
|
597
|
+
pack: packed
|
|
598
|
+
? { totalFiles: packed.totalFiles, size: packed.size, unpackedSize: packed.unpackedSize }
|
|
599
|
+
: null,
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/* ---------------- 平台定义 ---------------- */
|
|
604
|
+
|
|
605
|
+
return {
|
|
606
|
+
id: 'review',
|
|
607
|
+
label: '审查',
|
|
608
|
+
order: 40,
|
|
609
|
+
icon: 'ReviewMark',
|
|
610
|
+
|
|
611
|
+
/**
|
|
612
|
+
* 业务方法集合。
|
|
613
|
+
*
|
|
614
|
+
* 路由与工具动作都调用这里,所以界面点「开始审查」和模型请求审查走的是
|
|
615
|
+
* 同一条代码路径(one operation, two callers)。
|
|
616
|
+
*/
|
|
617
|
+
host: {
|
|
618
|
+
/** 内置 + 自定义审查项,以及分组用的分类表。 */
|
|
619
|
+
async presets() {
|
|
620
|
+
return {
|
|
621
|
+
builtin: BUILTIN_PRESETS.map((preset) => ({ ...preset, builtin: true })),
|
|
622
|
+
custom: await store.reviewPresets(),
|
|
623
|
+
categories: REVIEW_CATEGORIES.map((category) => ({ ...category })),
|
|
624
|
+
};
|
|
625
|
+
},
|
|
626
|
+
|
|
627
|
+
async presetSave(body) {
|
|
628
|
+
const title = requireString(body, 'title', '预设标题');
|
|
629
|
+
const prompt = requireString(body, 'prompt', '提示词');
|
|
630
|
+
const preset = await store.saveReviewPreset({
|
|
631
|
+
id: optionalString(body.id),
|
|
632
|
+
title,
|
|
633
|
+
prompt,
|
|
634
|
+
description: optionalString(body.description) ?? '',
|
|
635
|
+
category: optionalString(body.category) ?? 'custom',
|
|
636
|
+
});
|
|
637
|
+
return { preset };
|
|
638
|
+
},
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* 删除一条自定义预设。
|
|
642
|
+
*
|
|
643
|
+
* 内置项显式拒绝:它们不在存储里,静默回「找不到」会让刚点了删除的
|
|
644
|
+
* 用户以为程序坏了。
|
|
645
|
+
*/
|
|
646
|
+
async presetDelete(body) {
|
|
647
|
+
const id = requireString(body, 'id', '预设 id');
|
|
648
|
+
if (BUILTIN_PRESETS.some((preset) => preset.id === id)) {
|
|
649
|
+
throw httpError(409, 'CONFLICT', '内置审查项不能删除,只能在审查时取消勾选。');
|
|
650
|
+
}
|
|
651
|
+
const removed = await store.deleteReviewPreset(id);
|
|
652
|
+
if (!removed) throw httpError(404, 'NOT_FOUND', '找不到这条预设,可能已被删除。');
|
|
653
|
+
return { deleted: true };
|
|
654
|
+
},
|
|
655
|
+
|
|
656
|
+
models: () => context.reviewModels(),
|
|
657
|
+
|
|
658
|
+
pending: async () => ({ pending: publicPending() }),
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* 用户回应了待确认请求(开始审查,或关掉了窗口)。
|
|
662
|
+
* 清空才能让下一次 agent 请求重新弹窗,否则会被去重逻辑吞掉。
|
|
663
|
+
*/
|
|
664
|
+
async pendingClear(body) {
|
|
665
|
+
const id = optionalString(body?.id);
|
|
666
|
+
if (id !== undefined && pending && pending.id !== id) return { cleared: false };
|
|
667
|
+
const had = pending !== null;
|
|
668
|
+
pending = null;
|
|
669
|
+
return { cleared: had };
|
|
670
|
+
},
|
|
671
|
+
|
|
672
|
+
run: runGitReview,
|
|
673
|
+
package: runPackageReview,
|
|
674
|
+
project: runProjectReview,
|
|
675
|
+
},
|
|
676
|
+
|
|
677
|
+
routes: [
|
|
678
|
+
{ path: '/presets', method: 'GET', run: async ({ host }) => host.presets() },
|
|
679
|
+
{ path: '/presets', method: 'POST', run: async ({ body, host }) => host.presetSave(body) },
|
|
680
|
+
{ path: '/presets/delete', method: 'POST', run: async ({ body, host }) => host.presetDelete(body) },
|
|
681
|
+
{ path: '/models', method: 'GET', run: async ({ host }) => host.models() },
|
|
682
|
+
{ path: '/pending', method: 'GET', run: async ({ host }) => host.pending() },
|
|
683
|
+
{ path: '/pending/clear', method: 'POST', run: async ({ body, host }) => host.pendingClear(body) },
|
|
684
|
+
{ path: '/run', method: 'POST', run: async ({ body, host }) => host.run(body) },
|
|
685
|
+
{ path: '/package', method: 'POST', run: async ({ body, host }) => host.package(body) },
|
|
686
|
+
{ path: '/project', method: 'POST', run: async ({ body, host }) => host.project(body) },
|
|
687
|
+
],
|
|
688
|
+
|
|
689
|
+
actions: [
|
|
690
|
+
{
|
|
691
|
+
id: 'review',
|
|
692
|
+
description: '请求用户确认后审查待推送的改动。只会登记一个待确认请求并在界面中打开配置窗口,'
|
|
693
|
+
+ '不会自行执行审查——用户确认后才真正运行。',
|
|
694
|
+
parameters: {
|
|
695
|
+
path: { type: 'string', description: '仓库路径' },
|
|
696
|
+
presetIds: {
|
|
697
|
+
type: 'array',
|
|
698
|
+
items: { type: 'string' },
|
|
699
|
+
description: '要使用的审查项 id(见平台 action `presets`)',
|
|
700
|
+
},
|
|
701
|
+
customPrompt: { type: 'string', description: '额外的审查要求' },
|
|
702
|
+
},
|
|
703
|
+
/**
|
|
704
|
+
* agent 走的路径只登记请求,绝不自行执行。
|
|
705
|
+
*
|
|
706
|
+
* 这条策略就是「审查必须经过人」的实现:模型能发起、不能决定。
|
|
707
|
+
*/
|
|
708
|
+
run: async (args) => raise({
|
|
709
|
+
path: String(args?.path ?? ''),
|
|
710
|
+
presetIds: Array.isArray(args?.presetIds) ? args.presetIds : [],
|
|
711
|
+
customPrompt: String(args?.customPrompt ?? ''),
|
|
712
|
+
source: 'agent',
|
|
713
|
+
}),
|
|
714
|
+
render: (value) => value?.message ?? JSON.stringify(value),
|
|
715
|
+
},
|
|
716
|
+
{
|
|
717
|
+
id: 'presets',
|
|
718
|
+
description: '列出可用的审查项(内置与自定义),用于选择审查范围。',
|
|
719
|
+
run: async (_args, host) => host.presets(),
|
|
720
|
+
render: (value) => {
|
|
721
|
+
const builtin = (value.builtin || []).map((preset) => `- ${preset.id}:${preset.title}`).join('\n');
|
|
722
|
+
const custom = (value.custom || []).map((preset) => `- ${preset.id}:${preset.title}`).join('\n');
|
|
723
|
+
return [`内置审查项:`, builtin || '(无)', '', '自定义审查项:', custom || '(无)'].join('\n');
|
|
724
|
+
},
|
|
725
|
+
},
|
|
726
|
+
],
|
|
727
|
+
};
|
|
728
|
+
}
|