agiledev-cli 0.1.4 → 0.3.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.
Files changed (40) hide show
  1. package/README.md +300 -173
  2. package/SKILL.md +114 -98
  3. package/adev.js +1319 -1285
  4. package/autofix/agents/antigravity.js +379 -0
  5. package/autofix/agents/claude.js +147 -0
  6. package/autofix/agents/codex.js +179 -0
  7. package/autofix/agents/exec.js +230 -0
  8. package/autofix/agents/index.js +400 -0
  9. package/autofix/agents/opencode.js +233 -0
  10. package/autofix/agents/pi.js +247 -0
  11. package/autofix/agiledev.js +98 -0
  12. package/autofix/bridge.js +371 -0
  13. package/autofix/cli.js +712 -0
  14. package/autofix/context.js +152 -0
  15. package/autofix/conversation.js +302 -0
  16. package/autofix/coordinator.js +2892 -0
  17. package/autofix/git.js +459 -0
  18. package/autofix/policy.js +230 -0
  19. package/autofix/profile.js +578 -0
  20. package/autofix/public/app.js +3668 -0
  21. package/autofix/public/i18n-id.js +282 -0
  22. package/autofix/public/index.html +32 -0
  23. package/autofix/public/style.css +2463 -0
  24. package/autofix/queue.js +146 -0
  25. package/autofix/scheduler.js +994 -0
  26. package/autofix/scope.js +32 -0
  27. package/autofix/service.js +1940 -0
  28. package/autofix/store.js +375 -0
  29. package/autofix/workspace.js +298 -0
  30. package/autofix/worktree.js +379 -0
  31. package/docs/autofix-design.md +801 -0
  32. package/docs/autofix-profiles.example.json +65 -0
  33. package/imgs/Bug/350/247/243/345/206/263/345/244/207/346/263/250.png +0 -0
  34. package/imgs/logo.png +0 -0
  35. package/imgs//344/277/256/346/224/271Bug/347/212/266/346/200/201.png +0 -0
  36. package/imgs//345/270/256/346/210/221/344/277/256/345/244/215Bug-20260922-010.png +0 -0
  37. package/imgs//346/237/245/347/234/213/345/271/266/345/210/206/346/236/220/351/234/200/346/261/202/346/226/207/346/241/243.png +0 -0
  38. package/imgs//347/234/213/344/270/200/344/270/213/346/210/221/347/216/260/345/234/250/346/234/211/345/223/252/344/272/233/345/274/200/345/217/221/344/273/273/345/212/241.png +0 -0
  39. package/imgs//347/234/213/344/270/200/344/270/213/346/210/221/350/277/230/346/234/211/345/223/252/344/272/233Bug/346/234/252/350/247/243/345/206/263.png +0 -0
  40. package/package.json +39 -36
package/autofix/git.js ADDED
@@ -0,0 +1,459 @@
1
+ /**
2
+ * 提交与合并:把自动修复的改动落到 Git 上,并按团队流程合并进测试分支、推送。
3
+ *
4
+ * 设计原则(宁可不做,也不能做错):
5
+ * - 只提交本任务申报过的文件,绝不 `git add -A`:并行修复时别人的改动不能被顺带提交。
6
+ * - 工作区不干净、还有任务在跑、或不在仓库里时一律跳过,返回原因而不是报错。
7
+ * - 合并用 --no-ff 保证测试分支能看清每次提测;冲突就 abort 掉,把未完成的提交留在原分支上。
8
+ * - 提交信息用团队规范:Angular 类型 + scope + 中文 subject + 缺陷编号,结尾带 Co-Authored-By。
9
+ */
10
+ import { execFile } from "node:child_process";
11
+ import path from "node:path";
12
+ import { promisify } from "node:util";
13
+
14
+ const execFileAsync = promisify(execFile);
15
+
16
+ /** 只有明确失败(非 0 退出码)才算失败;找不到 git 也返回 ok:false。 */
17
+ async function git(cwd, args, { timeout = 30000 } = {}) {
18
+ try {
19
+ const { stdout, stderr } = await execFileAsync("git", ["-C", cwd, ...args], {
20
+ timeout,
21
+ windowsHide: true,
22
+ maxBuffer: 16 * 1024 * 1024,
23
+ env: {
24
+ ...process.env,
25
+ // 避免 git 在等编辑器/密码时把后台服务挂死
26
+ GIT_TERMINAL_PROMPT: "0",
27
+ GIT_EDITOR: "true",
28
+ GIT_MERGE_AUTOEDIT: "no",
29
+ },
30
+ });
31
+ return { ok: true, stdout: String(stdout || ""), stderr: String(stderr || "") };
32
+ } catch (e) {
33
+ return {
34
+ ok: false,
35
+ code: typeof e?.code === "number" ? e.code : null,
36
+ stdout: String(e?.stdout || ""),
37
+ stderr: String(e?.stderr || e?.message || ""),
38
+ };
39
+ }
40
+ }
41
+
42
+ /** 常见测试/集成分支名,按命中顺序优先。 */
43
+ const TEST_BRANCH_CANDIDATES = ["test", "testing", "dev", "develop", "uat", "sit", "release/test", "feature/test"];
44
+
45
+ /** 各 Agent 的署名,用于提交信息尾部的 Co-Authored-By。 */
46
+ const CO_AUTHOR = {
47
+ claude: "Claude Code <noreply@anthropic.com>",
48
+ opencode: "OpenCode <noreply@opencode.ai>",
49
+ antigravity: "Antigravity <noreply@google.com>",
50
+ };
51
+
52
+ /** 是否为 Git 仓库(含子目录在仓库内的情况)。 */
53
+ export async function isRepo(cwd) {
54
+ const r = await git(cwd, ["rev-parse", "--is-inside-work-tree"]);
55
+ return r.ok && r.stdout.trim() === "true";
56
+ }
57
+
58
+ /** 当前分支名;游离 HEAD 时返回 null。 */
59
+ export async function currentBranch(cwd) {
60
+ const r = await git(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]);
61
+ if (!r.ok) return null;
62
+ const name = r.stdout.trim();
63
+ return name && name !== "HEAD" ? name : null;
64
+ }
65
+
66
+ /** 本地分支列表。 */
67
+ export async function listBranches(cwd) {
68
+ const r = await git(cwd, ["for-each-ref", "--format=%(refname:short)", "refs/heads"]);
69
+ if (!r.ok) return [];
70
+ return r.stdout.split(/\r?\n/).map(s => s.trim()).filter(Boolean);
71
+ }
72
+
73
+ /** 工作区未提交的改动(porcelain 原始行)。 */
74
+ export async function dirtyEntries(cwd) {
75
+ const r = await git(cwd, ["status", "--porcelain"]);
76
+ if (!r.ok) return [];
77
+ return r.stdout.split(/\r?\n/).filter(Boolean);
78
+ }
79
+
80
+ export function isClean(dirty) {
81
+ return !dirty || dirty.length === 0;
82
+ }
83
+
84
+ /**
85
+ * 选测试分支:用户显式配置优先;否则在仓库现有分支里找常见的测试分支。
86
+ * 都没有就返回 null —— 此时只提交、不合并,绝不自己造分支。
87
+ */
88
+ export function pickTestBranch(branches = [], configured = null) {
89
+ const list = (branches || []).map(b => String(b || "").trim()).filter(Boolean);
90
+ const pick = (name) => {
91
+ const want = String(name || "").trim().toLowerCase();
92
+ if (!want) return null;
93
+ return list.find(b => b.toLowerCase() === want) || null;
94
+ };
95
+ const explicit = pick(configured);
96
+ if (explicit) return explicit;
97
+ for (const name of TEST_BRANCH_CANDIDATES) {
98
+ const hit = pick(name);
99
+ if (hit) return hit;
100
+ }
101
+ return null;
102
+ }
103
+
104
+ /**
105
+ * 生成提交信息(团队规范:Angular + 中文 subject + 缺陷编号)。
106
+ *
107
+ * fix(admin-ui): 修复会员列表分页报错 (BUG-20261110-001)
108
+ *
109
+ * 根因:分页参数未随筛选条件重置。
110
+ * 改动:src/views/member/list.vue
111
+ *
112
+ * Co-Authored-By: Claude Code <noreply@anthropic.com>
113
+ */
114
+ export function buildCommitMessage(task, { scope = null, type = "fix", coAuthor = null } = {}) {
115
+ const code = task.code || task.taskId || "";
116
+ const rawTitle = String(task.title || "自动修复").replace(/\s+/g, " ").trim();
117
+ // subject 控制在 20 个中文字以内,太长截断并补省略号
118
+ const title = rawTitle.length > 20 ? `${rawTitle.slice(0, 20)}…` : rawTitle;
119
+ const scopePart = scope ? `(${scope})` : "";
120
+ const codePart = code ? ` (${code})` : "";
121
+
122
+ const lines = [`${type}${scopePart}: ${title}${codePart}`];
123
+ const body = [];
124
+ if (task.result?.summary) body.push(String(task.result.summary).trim());
125
+ const files = task.changedFiles || task.result?.changedFiles || [];
126
+ if (files.length) body.push("", `改动文件:${files.slice(0, 20).join("、")}`);
127
+ if (body.length) lines.push("", ...body);
128
+
129
+ const author = coAuthor || CO_AUTHOR[task.workerAgent] || CO_AUTHOR.claude;
130
+ lines.push("", `Co-Authored-By: ${author}`);
131
+ return lines.join("\n");
132
+ }
133
+
134
+ /**
135
+ * 提交本任务的文件。
136
+ *
137
+ * @param {object} opts
138
+ * @param {string} opts.cwd 仓库目录
139
+ * @param {string[]} opts.files 本任务改动的文件(相对仓库路径)
140
+ * @param {string} opts.message 提交信息
141
+ * @returns {Promise<{ok:boolean, committed:boolean, reason?:string, message:string}>}
142
+ */
143
+ export async function commitFiles({ cwd, files = [], message }) {
144
+ let list = (files || []).map(f => String(f || "").trim()).filter(Boolean);
145
+ if (!list.length) return { ok: true, committed: false, reason: "no_files", message: "没有需要提交的文件" };
146
+ if (!(await isRepo(cwd))) return { ok: true, committed: false, reason: "no_git", message: "工作区不是 Git 仓库,跳过提交" };
147
+
148
+ // 只 add 本任务的文件:用 pathspec 明确列出,防止把并行任务的改动一起提交
149
+ let add = await git(cwd, ["add", "--", ...list]);
150
+ if (!add.ok) {
151
+ // 返工的文件是跨轮并集:里面可能残留上一轮存在、本轮被删掉/改名的旧路径。
152
+ // git add 遇到匹配不到的 pathspec 会整条命令失败,最终表现为交付卡在「需人工」。
153
+ // 这里剔除「索引里没有、工作区也不存在」的路径后重试一次;已跟踪后被删除的
154
+ // 文件仍会出现在索引里(保留删除),目录路径则按前缀匹配保留。
155
+ const known = await git(cwd, ["ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", ...list]);
156
+ const knownSet = new Set(
157
+ known.ok ? known.stdout.split("\0").map(v => v.trim()).filter(Boolean) : [],
158
+ );
159
+ const valid = knownSet.size
160
+ ? list.filter(f => {
161
+ if (knownSet.has(f)) return true;
162
+ const prefix = `${f.replace(/\\/g, "/").replace(/\/+$/, "")}/`;
163
+ for (const k of knownSet) if (k.startsWith(prefix)) return true;
164
+ return false;
165
+ })
166
+ : [];
167
+ if (valid.length && valid.length < list.length) {
168
+ add = await git(cwd, ["add", "--", ...valid]);
169
+ if (add.ok) list = valid;
170
+ }
171
+ }
172
+ if (!add.ok) {
173
+ return { ok: false, committed: false, reason: "add_failed", message: (add.stderr || add.stdout).slice(-500) || "git add 失败" };
174
+ }
175
+ // 暂存区为空说明这些文件其实没变化(例如被回滚),不必造空提交
176
+ const staged = await git(cwd, ["diff", "--cached", "--name-only"]);
177
+ if (staged.ok && !staged.stdout.trim()) {
178
+ return { ok: true, committed: false, reason: "nothing_staged", message: "改动已在提交记录中,无需重复提交" };
179
+ }
180
+ const commit = await git(cwd, ["commit", "-m", message]);
181
+ if (!commit.ok) {
182
+ const err = (commit.stderr || commit.stdout || "").slice(-500);
183
+ // 没配 git 身份是很常见的环境问题:按环境问题上报,让用户只处理这一件事
184
+ const reason = /user\.name|user\.email|Author identity unknown|unable to auto-detect email/i.test(err)
185
+ ? "no_identity"
186
+ : "commit_failed";
187
+ return { ok: false, committed: false, reason, message: err || "git commit 失败" };
188
+ }
189
+ const head = await git(cwd, ["rev-parse", "--short", "HEAD"]);
190
+ return {
191
+ ok: true,
192
+ committed: true,
193
+ reason: null,
194
+ branch: await currentBranch(cwd),
195
+ commit: head.ok ? head.stdout.trim() : null,
196
+ message: `已提交 ${list.length} 个文件${head.ok ? `(${head.stdout.trim()})` : ""}`,
197
+ };
198
+ }
199
+
200
+ /**
201
+ * 切到指定分支(提测前确保在开发分支上)。
202
+ *
203
+ * 切不过去不算致命错误:可能是工作区有未提交改动,或分支还不存在。
204
+ * 返回原因让上层决定是继续还是转人工,绝不自己建分支。
205
+ */
206
+ export async function ensureBranch(cwd, branch) {
207
+ const want = String(branch || "").trim();
208
+ if (!want) return { ok: true, switched: false, reason: "no_branch_configured", message: "未配置开发分支,沿用当前分支" };
209
+ const now = await currentBranch(cwd);
210
+ if (now === want) return { ok: true, switched: false, reason: "already", message: `已在 ${want}` };
211
+
212
+ const exists = (await listBranches(cwd)).some(b => b === want);
213
+ if (!exists) {
214
+ return { ok: false, switched: false, reason: "branch_missing", message: `本地没有分支 ${want},不会自动创建` };
215
+ }
216
+ const checkout = await git(cwd, ["checkout", want]);
217
+ if (!checkout.ok) {
218
+ return {
219
+ ok: false,
220
+ switched: false,
221
+ reason: "checkout_failed",
222
+ message: (checkout.stderr || checkout.stdout).slice(-400) || `切不到 ${want}`,
223
+ };
224
+ }
225
+ return { ok: true, switched: true, reason: null, message: `已切到 ${want}` };
226
+ }
227
+
228
+ /** 推送分支到远端。 */
229
+ export async function pushBranch(cwd, branch, { remote = "origin" } = {}) {
230
+ const target = String(branch || "").trim();
231
+ if (!target) return { ok: true, pushed: false, reason: "no_branch", message: "没有分支可推送" };
232
+ const push = await git(cwd, ["push", remote, target], { timeout: 120000 });
233
+ if (!push.ok) {
234
+ return {
235
+ ok: false,
236
+ pushed: false,
237
+ reason: "push_failed",
238
+ message: (push.stderr || push.stdout || "").slice(-600) || `推送 ${target} 失败`,
239
+ };
240
+ }
241
+ return { ok: true, pushed: true, branch: target, message: `已推送 ${target}` };
242
+ }
243
+
244
+ /**
245
+ * 把 from 分支合并进测试分支,推送测试分支,并切回 from 分支。
246
+ *
247
+ * 流程与团队 playbook 一致:checkout test → pull origin test → merge --no-ff
248
+ * → push origin test → checkout 回开发分支。
249
+ * 冲突时 abort 掉这次合并,测试分支保持原样,改动仍在 from 分支上,不丢代码。
250
+ */
251
+ export async function mergeIntoTestBranch({ cwd, from, testBranch, push = false, remote = "origin" }) {
252
+ if (!from || !testBranch) return { ok: true, merged: false, pushed: false, reason: "no_branch", message: "缺少分支信息,跳过合并" };
253
+ if (from === testBranch) return { ok: true, merged: false, pushed: false, reason: "same_branch", message: `已在测试分支 ${testBranch} 上,无需合并` };
254
+
255
+ const checkout = await git(cwd, ["checkout", testBranch]);
256
+ if (!checkout.ok) {
257
+ return { ok: false, merged: false, pushed: false, reason: "checkout_failed", message: (checkout.stderr || checkout.stdout).slice(-500) || `切不到 ${testBranch}` };
258
+ }
259
+
260
+ // 先把远端 test 的改动快进过来,避免基于过期的本地 test 合并。
261
+ // 没有远端 / 无 upstream 是常见的本地开发环境,不阻断合并,只在结果里留一句说明。
262
+ let pullNote = "";
263
+ const pull = await git(cwd, ["pull", "--ff-only", remote, testBranch], { timeout: 90000 });
264
+ if (!pull.ok) {
265
+ pullNote = `(未拉取远端 ${testBranch}:${(pull.stderr || pull.stdout || "").trim().slice(-160)})`;
266
+ }
267
+
268
+ const merge = await git(cwd, ["merge", "--no-ff", "-m", `chore(${testBranch}): 合入 ${from} 的自动修复`, from]);
269
+ if (!merge.ok) {
270
+ const err = (merge.stderr || merge.stdout || "").slice(-800);
271
+ // 冲突:撤销合并,回到干净状态,代码仍留在 from 分支
272
+ await git(cwd, ["merge", "--abort"]);
273
+ await git(cwd, ["checkout", from]);
274
+ const conflicted = /CONFLICT|Automatic merge failed/i.test(err);
275
+ return {
276
+ ok: false,
277
+ merged: false,
278
+ pushed: false,
279
+ reason: conflicted ? "merge_conflict" : "merge_failed",
280
+ message: err || `合并到 ${testBranch} 失败`,
281
+ };
282
+ }
283
+
284
+ // 合并成功:按需推送测试分支
285
+ let pushed = false;
286
+ let pushMessage = "";
287
+ if (push) {
288
+ const p = await pushBranch(cwd, testBranch, { remote });
289
+ pushed = !!p.pushed;
290
+ pushMessage = p.message || "";
291
+ if (!p.ok) {
292
+ // 推送失败不回滚合并:代码已经在本地测试分支上,保留现场让上层转人工
293
+ await git(cwd, ["checkout", from]);
294
+ return {
295
+ ok: false,
296
+ merged: true,
297
+ pushed: false,
298
+ reason: "push_failed",
299
+ message: `已合并到 ${testBranch},但推送失败:${p.message}`,
300
+ };
301
+ }
302
+ }
303
+
304
+ // 切回原分支:后续修复继续在开发分支上进行
305
+ const back = await git(cwd, ["checkout", from]);
306
+ return {
307
+ ok: true,
308
+ merged: true,
309
+ pushed,
310
+ testBranch,
311
+ message: `已合并到 ${testBranch}${pushed ? "并已推送" : ""}${back.ok ? `,并切回 ${from}` : ""}${pullNote}`,
312
+ };
313
+ }
314
+
315
+ function toPosix(p) {
316
+ return String(p || "").replace(/\\/g, "/").replace(/^\.\//, "");
317
+ }
318
+
319
+ function isInsidePath(child, parent) {
320
+ const c = toPosix(child).toLowerCase();
321
+ const p = toPosix(parent).toLowerCase();
322
+ return !!p && (c === p || c.startsWith(p.endsWith("/") ? p : `${p}/`));
323
+ }
324
+
325
+ /**
326
+ * 把修复 Agent 报告的改动路径整理成统一的「仓库名/仓库内相对路径」。
327
+ *
328
+ * Agent 可能报相对工作区的路径、仓库名开头的路径,也可能直接报绝对路径
329
+ * (项目文件夹不在启动目录下时很常见)。统一后才能:
330
+ * - 与 diff 基线里的 `${仓库名}/${文件}` 对齐,避免误判越界改动;
331
+ * - 按仓库拆分提交与验证。单仓库工作区保持原来的相对路径格式。
332
+ */
333
+ export function canonicalizeChangedFiles(files = [], repos = [], root = null) {
334
+ const list = (Array.isArray(repos) ? repos : []).filter(r => r && r.name);
335
+ const multi = list.length > 1;
336
+ const rootAbs = root ? path.resolve(root) : null;
337
+ const out = [];
338
+ const seen = new Set();
339
+
340
+ const resolveRelative = file => {
341
+ // 单仓库也需要归一:配置档仓库名可能和目录名不同(relPath=app-ui、name=app),
342
+ // 统一成 name 前缀后才能和基线 diff 对齐。
343
+ if (!list.length) return file;
344
+ const lower = file.toLowerCase();
345
+ let best = null;
346
+ for (const repo of list) {
347
+ const candidates = [toPosix(repo.name), toPosix(repo.relPath ?? repo.name)];
348
+ for (const prefix of candidates) {
349
+ if (!prefix || prefix === ".") continue;
350
+ const pl = prefix.toLowerCase();
351
+ if (lower !== pl && !lower.startsWith(`${pl}/`)) continue;
352
+ const rest = file.slice(prefix.length).replace(/^\//, "");
353
+ if (!best || prefix.length > best.len) best = { repo, len: prefix.length, rest };
354
+ }
355
+ }
356
+ return best ? `${best.repo.name}/${best.rest}` : file;
357
+ };
358
+
359
+ for (const raw of files) {
360
+ let file = toPosix(raw);
361
+ if (!file) continue;
362
+ const isAbs = path.isAbsolute(file) || /^[a-zA-Z]:\//.test(file);
363
+ let mapped = file;
364
+
365
+ if (isAbs) {
366
+ const abs = path.resolve(file);
367
+ let best = null;
368
+ for (const repo of list) {
369
+ if (!repo.path) continue;
370
+ const repoPath = path.resolve(repo.path);
371
+ if (isInsidePath(abs, repoPath) && (!best || repoPath.length > best.repoPath.length)) {
372
+ best = { repo, repoPath };
373
+ }
374
+ }
375
+ if (best) {
376
+ const rel = path.relative(best.repoPath, abs).replace(/\\/g, "/");
377
+ // 仓库就是工作区根时不加前缀;仓库在根目录之下(单仓库也一样)才加,
378
+ // 与 scheduler.readInfo 的归一规则保持一致。
379
+ const own = rootAbs
380
+ ? best.repoPath.toLowerCase() === rootAbs.toLowerCase()
381
+ : !multi;
382
+ mapped = own ? rel : `${best.repo.name}/${rel}`;
383
+ } else if (rootAbs && isInsidePath(abs, rootAbs)) {
384
+ mapped = resolveRelative(toPosix(path.relative(rootAbs, abs)));
385
+ }
386
+ } else {
387
+ mapped = resolveRelative(file);
388
+ }
389
+
390
+ const key = mapped.toLowerCase();
391
+ if (seen.has(key)) continue;
392
+ seen.add(key);
393
+ out.push(mapped);
394
+ }
395
+ return out;
396
+ }
397
+
398
+ /**
399
+ * 把改动按仓库拆开:返回每个仓库下实际改动的文件。
400
+ *
401
+ * 改动路径是相对工作区根的(形如 `ynrm-admin-ui/src/a.vue`),
402
+ * 这里按配置档声明的仓库路径做前缀剥离,剥离不出来的归到根仓库。
403
+ */
404
+ export function groupFilesByRepo(changedFiles = [], repos = []) {
405
+ const groups = new Map();
406
+ const push = (key, repo, file) => {
407
+ if (!groups.has(key)) {
408
+ groups.set(key, { key, repo: repo || null, files: [] });
409
+ }
410
+ groups.get(key).files.push(file);
411
+ };
412
+
413
+ // 路径为 "." 的仓库 = 工作区根本身就是那个仓库(单仓库项目常见)。
414
+ // 它不能被跳过,否则该仓库声明的分支 / 测试分支 / push 策略全部失效。
415
+ const rootRepo = (repos || []).find(r => {
416
+ const p = String(r.relPath ?? r.name ?? "").replace(/\\/g, "/").replace(/^\.\//, "");
417
+ return p === "." || p === "";
418
+ }) || null;
419
+
420
+ for (const raw of changedFiles || []) {
421
+ const file = toPosix(String(raw || "").trim());
422
+ if (!file) continue;
423
+ const lower = file.toLowerCase();
424
+ const isAbs = path.isAbsolute(file) || /^[a-zA-Z]:\//.test(file);
425
+ let hit = null;
426
+ let prefixUsed = "";
427
+
428
+ for (const repo of repos || []) {
429
+ // 相对前缀:配置档 relPath 与仓库名(Agent 常按目录名报告)
430
+ const candidates = [toPosix(repo.relPath ?? repo.name ?? ""), toPosix(repo.name ?? "")];
431
+ // 绝对路径:直接落在仓库真实目录里
432
+ if (repo.path) candidates.push(toPosix(path.resolve(repo.path)));
433
+ for (const prefix of candidates) {
434
+ if (!prefix || prefix === ".") continue;
435
+ const pl = prefix.toLowerCase();
436
+ if (lower === pl || lower.startsWith(`${pl}/`)) {
437
+ if (!hit || prefix.length > prefixUsed.length) {
438
+ hit = repo;
439
+ prefixUsed = prefix;
440
+ }
441
+ }
442
+ }
443
+ }
444
+
445
+ if (hit) {
446
+ const rel = isAbs
447
+ ? path.relative(prefixUsed, path.resolve(file)).replace(/\\/g, "/")
448
+ : file.slice(prefixUsed.length).replace(/^\//, "");
449
+ push(hit.name, hit, rel);
450
+ } else if (rootRepo) {
451
+ // 单仓库:文件相对工作区根,也相对该仓库根,直接原样使用
452
+ push(rootRepo.name, rootRepo, file);
453
+ } else {
454
+ push("__root__", null, file);
455
+ }
456
+ }
457
+
458
+ return [...groups.values()];
459
+ }
@@ -0,0 +1,230 @@
1
+ /**
2
+ * 修复策略:复核判定、复核轮次预算与人工介入选项。
3
+ *
4
+ * 目标:能自己决定的绝不问人。人工只在「需要业务/产品决策」或「环境缺失」时出场,
5
+ * 而且出场时必须给出可直接点的选项,而不是一段看不懂的文字。
6
+ *
7
+ * 复核不是一刀切:
8
+ * - 简单问题免复核(文案、单文件小改、样式展示、笔误、局部参数);
9
+ * - 复杂问题必须复核(核心业务逻辑、系统底层、改动面大、跨前后端)。
10
+ */
11
+
12
+ /* ======================== 改动面分析 ======================== */
13
+
14
+ /**
15
+ * 把改动文件列表归到具体仓库与端(前端/后端/移动端)。
16
+ *
17
+ * 归仓库优先用配置档里声明的仓库路径;没有配置时退回"取第一段目录名"的粗略规则,
18
+ * 至少能判断出改动是否同时落在前端与后端。
19
+ */
20
+ export function classifyChangeScope({ changedFiles = [], repos = [] } = {}) {
21
+ const files = (changedFiles || []).map(f => String(f || "").trim().replace(/\\/g, "/").replace(/^\.\//, "")).filter(Boolean);
22
+ const touched = new Map();
23
+
24
+ // 路径为 "." 的根仓库:工作区根即是该仓库,未匹配到具体子仓库的文件都归它
25
+ const rootRepo = (repos || []).find(r => {
26
+ const p = String(r.relPath ?? r.name ?? "").replace(/\\/g, "/").replace(/^\.\//, "");
27
+ return p === "." || p === "";
28
+ }) || null;
29
+
30
+ for (const file of files) {
31
+ const lower = file.toLowerCase();
32
+ let hit = null;
33
+ for (const repo of repos || []) {
34
+ const prefix = String(repo.relPath ?? repo.name ?? "").replace(/\\/g, "/").replace(/^\.\//, "");
35
+ if (!prefix || prefix === ".") continue;
36
+ if (lower === prefix.toLowerCase() || lower.startsWith(`${prefix.toLowerCase()}/`)) {
37
+ hit = repo;
38
+ break;
39
+ }
40
+ }
41
+ if (!hit) {
42
+ // 单仓库项目:根仓库的角色要生效,不能一律当"未知端"
43
+ hit = rootRepo || { name: file.split("/")[0], relPath: file.split("/")[0], role: "other" };
44
+ }
45
+ const key = hit.name;
46
+ if (!touched.has(key)) {
47
+ touched.set(key, { name: hit.name, role: hit.role || "other", files: [], relPath: hit.relPath || hit.name });
48
+ }
49
+ touched.get(key).files.push(file);
50
+ }
51
+
52
+ const reposTouched = [...touched.values()];
53
+ const roles = [...new Set(reposTouched.map(r => r.role))];
54
+ const frontend = roles.includes("frontend");
55
+ const backend = roles.includes("backend");
56
+ const mobile = roles.includes("mobile");
57
+
58
+ return {
59
+ fileCount: files.length,
60
+ files,
61
+ repos: reposTouched,
62
+ roles,
63
+ // 跨前后端:前端 + 后端同时被改
64
+ crossFrontendBackend: frontend && backend,
65
+ // 跨端:涉及两种及以上"已知端"(前端/后端/移动端)
66
+ crossRole: roles.filter(r => r !== "other").length >= 2,
67
+ touchesBackend: backend,
68
+ touchesFrontend: frontend,
69
+ touchesMobile: mobile,
70
+ };
71
+ }
72
+
73
+ /* ======================== 复核判定 ======================== */
74
+
75
+ /** 命中即视为"核心业务逻辑",必须复核。 */
76
+ const CORE_BUSINESS_KEYWORDS = [
77
+ "权限", "授权", "数据范围", "数据权限", "角色归属", "门店归属",
78
+ "金额", "价格", "订单", "结算", "库存", "支付", "退款", "对账", "发票",
79
+ "账期", "补贴", "优惠", "积分", "优惠券",
80
+ ];
81
+
82
+ /** 命中即视为"系统底层",必须复核。 */
83
+ const SYSTEM_KEYWORDS = [
84
+ "缓存", "事务", "SQL", "sql", "索引", "锁", "并发", "幂等",
85
+ "鉴权", "认证", "框架", "拦截器", "过滤器", "网关", "序列化", "定时任务",
86
+ ];
87
+
88
+ /** 命中即视为"简单问题",可免复核。 */
89
+ const SIMPLE_KEYWORDS = [
90
+ "文案", "提示语", "错别字", "笔误", "标点", "文案错误", "文案修改",
91
+ "样式", "颜色", "间距", "布局", "间距调整", "展示", "显示问题", "展示异常",
92
+ ];
93
+
94
+ function hitKeyword(text, keywords) {
95
+ if (!text) return [];
96
+ const s = String(text);
97
+ return keywords.filter(k => s.includes(k));
98
+ }
99
+
100
+ /**
101
+ * 按缺陷与改动面决定复核策略。
102
+ *
103
+ * @param {string} severity 缺陷级别
104
+ * @param {object} ctx
105
+ * @param {string} ctx.title 缺陷标题
106
+ * @param {string} ctx.description 缺陷描述
107
+ * @param {string[]} ctx.changedFiles 本次改动的文件
108
+ * @param {object[]} ctx.repos 工作区仓库声明(含 relPath / role)
109
+ * @param {object} ctx.review 工作区级复核配置(fileThreshold 等)
110
+ * @param {number} ctx.reworkCount 已返工轮数
111
+ */
112
+ export function reviewPolicy(severity, ctx = {}) {
113
+ const {
114
+ title = "", description = "", changedFiles = [], repos = [], review = {}, reworkCount = 0,
115
+ } = ctx || {};
116
+
117
+ const sev = String(severity || "");
118
+ const complexSeverity = /致命|阻塞|blocker|critical|fatal|严重|major|high|urgent|紧急/i.test(sev);
119
+ const trivialSeverity = /提示|轻微|优化|建议|trivial|minor|low|suggestion|cosmetic/i.test(sev);
120
+
121
+ const scope = classifyChangeScope({ changedFiles, repos });
122
+ const threshold = Number.isFinite(Number(review.fileThreshold)) ? Number(review.fileThreshold) : 6;
123
+ const crossRoleRequiresReview = review.crossRoleRequiresReview !== false;
124
+ const keywords = Array.isArray(review.keywords) && review.keywords.length ? review.keywords : CORE_BUSINESS_KEYWORDS;
125
+
126
+ const text = `${title || ""}\n${description || ""}`;
127
+ const businessHits = hitKeyword(text, keywords);
128
+ const systemHits = hitKeyword(text, SYSTEM_KEYWORDS);
129
+ const simpleHits = hitKeyword(text, SIMPLE_KEYWORDS);
130
+
131
+ const reasons = [];
132
+ if (complexSeverity) reasons.push("缺陷级别高");
133
+ if (businessHits.length) reasons.push(`涉及核心业务逻辑(${businessHits.join("、")})`);
134
+ if (systemHits.length) reasons.push(`涉及系统底层(${systemHits.join("、")})`);
135
+ if (scope.fileCount >= threshold) reasons.push(`改动文件 ${scope.fileCount} 个(阈值 ${threshold})`);
136
+ if (scope.crossFrontendBackend) reasons.push("同时改动前端与后端");
137
+ else if (crossRoleRequiresReview && scope.crossRole) reasons.push(`跨端改动(${scope.roles.join("、")})`);
138
+
139
+ // 必须复核:命中任一硬性条件
140
+ const requiresCodeReview = reasons.length > 0;
141
+
142
+ // 可免复核:级别轻微 / 文案笔误类 / 只动一个小文件,且没命中任何"必须复核"条件。
143
+ // 「单文件小改」免复核是巡检口径里明确列出的场景。
144
+ const simpleChange = scope.fileCount <= 1;
145
+ const skipReview = !requiresCodeReview && (trivialSeverity || simpleHits.length > 0 || simpleChange);
146
+
147
+ let level = "normal";
148
+ let maxRounds = 1;
149
+ let maxRework = 2;
150
+ if (requiresCodeReview) {
151
+ level = "complex";
152
+ maxRounds = 2;
153
+ } else if (skipReview) {
154
+ level = "trivial";
155
+ maxRounds = 0;
156
+ maxRework = 1;
157
+ }
158
+
159
+ const note = requiresCodeReview
160
+ ? `必须复核:${reasons.join(";")}`
161
+ : skipReview
162
+ ? "简单问题免复核,改完直接提测"
163
+ : "一般缺陷:复核 1 轮,改对就直接提测";
164
+
165
+ return {
166
+ level,
167
+ maxRounds,
168
+ maxRework,
169
+ skipReview,
170
+ requiresCodeReview,
171
+ reasons,
172
+ scope,
173
+ note,
174
+ reworkCount,
175
+ };
176
+ }
177
+
178
+ /* ======================== 人工介入选项 ======================== */
179
+
180
+ const OPTION_LIBRARY = {
181
+ retry: { id: "retry", label: "重新排队修复", consequence: "清掉当前阻塞结论,回到待派工,由主 Agent 重新安排修复" },
182
+ ask_agent: { id: "ask_agent", label: "让 Agent 再判断一次", consequence: "把现状交回主 Agent,由它决定返工还是接受(不改变线上状态)" },
183
+ skip_verify: { id: "skip_verify", label: "忽略验证,进入复核", consequence: "不跑验证命令,直接进入复核;主 Agent 会人工看改动与验证情况" },
184
+ finish: { id: "finish", label: "直接转待验证", consequence: "跳过复核,把缺陷流转到待验证,测试同学可立即验证" },
185
+ commit_retry: { id: "commit_retry", label: "重试提交并合并", consequence: "再次尝试提交本任务改动并合并到测试分支" },
186
+ commit_skip: { id: "commit_skip", label: "只提交,不合并", consequence: "把改动提交到当前分支,不合并测试分支" },
187
+ open_worker: { id: "open_worker", label: "接着上次会话继续修", consequence: "复用修复 Agent 的会话,让它带着当前结论继续" },
188
+ abort: { id: "abort", label: "停止这个任务", consequence: "中断修复,任务置为已停止,改动与记录保留" },
189
+ };
190
+
191
+ /** 每种阻塞原因对应哪些按钮。顺序即展示顺序。 */
192
+ const REASON_OPTIONS = {
193
+ no_command: ["skip_verify", "retry", "abort"],
194
+ uncovered_changes: ["skip_verify", "retry", "abort"],
195
+ verify_failed: ["ask_agent", "retry", "skip_verify", "abort"],
196
+ out_of_scope_changes: ["ask_agent", "retry", "abort"],
197
+ merge_conflict: ["commit_skip", "retry", "abort"],
198
+ commit_failed: ["commit_retry", "commit_skip", "abort"],
199
+ no_identity: ["commit_skip", "abort"],
200
+ transition_failed: ["retry", "commit_retry", "abort"],
201
+ agent_missing: ["abort"],
202
+ worker_idle_timeout: ["retry", "open_worker", "abort"],
203
+ user_aborted: ["retry", "abort"],
204
+ review_exhausted: ["finish", "retry", "abort"],
205
+ manual_keep: ["finish", "commit_retry", "abort"],
206
+ agent_timeout: ["retry", "ask_agent", "abort"],
207
+ worker_failed: ["retry", "ask_agent", "abort"],
208
+ service_restarted_repeatedly: ["retry", "ask_agent", "abort"],
209
+ dispatch_limit: ["ask_agent", "retry", "abort"],
210
+ no_test_branch: ["commit_skip", "retry", "abort"],
211
+ push_failed: ["commit_retry", "commit_skip", "abort"],
212
+ code_review_failed: ["ask_agent", "retry", "abort"],
213
+ };
214
+
215
+ /** 默认(主 Agent 自由提问、未知原因)给的通用选项。 */
216
+ const DEFAULT_OPTIONS = ["ask_agent", "retry", "abort"];
217
+
218
+ /**
219
+ * 把 needsHuman 的原因翻译成可点击选项。
220
+ * 原因可能是 markdown / 长句(主 Agent 的提问),此时退回通用选项。
221
+ */
222
+ export function needsHumanOptions(reason, { suggested = [] } = {}) {
223
+ const raw = String(reason || "").trim();
224
+ const key = Object.keys(REASON_OPTIONS).find(k => raw === k || raw.includes(k));
225
+ const ids = key ? REASON_OPTIONS[key] : DEFAULT_OPTIONS;
226
+ const fromIds = ids.map(id => OPTION_LIBRARY[id]).filter(Boolean);
227
+ const extra = (Array.isArray(suggested) ? suggested : [])
228
+ .filter(o => o && o.id && !fromIds.some(x => x.id === o.id));
229
+ return [...fromIds, ...extra];
230
+ }