agiledev-cli 0.1.5 → 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 -185
  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
@@ -0,0 +1,994 @@
1
+ /**
2
+ * 调度器:轮询、去重、任务状态机、工作区锁、重试上限、交付与线上写保护。
3
+ *
4
+ * 调度器是确定性代码,不信任 LLM 自述成功;所有线上写操作都在写前复查最新状态。
5
+ */
6
+ import { execFile } from "node:child_process";
7
+ import { promisify } from "node:util";
8
+ import path from "node:path";
9
+ import fs from "node:fs";
10
+ import {
11
+ appendMessage, listTasks, readTask, writeTask, ACTIVE_TASK_STATES,
12
+ } from "./store.js";
13
+ import { readGitInfo, detectVerifyCommand } from "./workspace.js";
14
+ import { needsHumanOptions } from "./policy.js";
15
+ import { hasContext, loadBugContext } from "./context.js";
16
+ import { withinSchedule } from "./profile.js";
17
+ import { boundProjectSet, taskInProjectScope } from "./scope.js";
18
+ import { BUG_STATUS, WATCH_STATUSES } from "./agiledev.js";
19
+
20
+ const execFileAsync = promisify(execFile);
21
+
22
+ /* ======================== 禁止执行的验证命令 ======================== */
23
+
24
+ /**
25
+ * 绝对不允许自动执行的验证命令。
26
+ *
27
+ * 前端全量编译、打包和 TS 类型校验会把本机 CPU / 内存打满,
28
+ * 属于项目红线;即使 worker 或用户配置里写了,也必须拦下并明确报告,
29
+ * 不能"静默跳过当没看见",否则任务会被误判为验证通过。
30
+ */
31
+ const FORBIDDEN_VERIFY_PATTERNS = [
32
+ /(?:^|[\s;&|])(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i,
33
+ /(?:^|[\s;&|])(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b/i,
34
+ /\b(?:vite|webpack|rollup|turbo|next|nuxt|parcel|esbuild)\s+build\b/i,
35
+ /\btsc\b/i,
36
+ /\bvue-tsc\b/i,
37
+ // Java / Kotlin 构建
38
+ /\b(?:gradle|gradlew)\s+(?:\S+\s+)*(?:build|assemble|compileJava|compileKotlin)\b/i,
39
+ /\b(?:mvn|mvnw)\s+(?:[^\s]*\s+)*(?:package|compile|install|deploy)\b/i,
40
+ // .NET 构建
41
+ /\bdotnet\s+(?:build|publish|pack)\b/i,
42
+ // Go 构建(go test ./... 是安全的,仅拦 go build)
43
+ /\bgo\s+build\b/i,
44
+ // Make / Rake 构建目标
45
+ /\b(?:make|rake)\s+(?:\S+\s+)*build\b/i,
46
+ // Rust cargo build
47
+ /\bcargo\s+build\b/i,
48
+ ];
49
+
50
+ export function isForbiddenVerifyCommand(command) {
51
+ const text = String(command || "");
52
+ if (!text.trim()) return false;
53
+ return FORBIDDEN_VERIFY_PATTERNS.some(re => re.test(text));
54
+ }
55
+
56
+ export const MAX_REWORK_ROUNDS = 2;
57
+ export const MAX_REOPEN_CYCLES = 5;
58
+ export const TASK_TIMEOUT_MS = 60 * 60 * 1000;
59
+ // Worker 连续多久没有任何输出就判定为卡死(协调器传给 Agent 适配器的 idleTimeoutMs)
60
+ export const NO_PROGRESS_TIMEOUT_MS = 8 * 60 * 1000;
61
+ const BACKOFF_SECONDS = [15, 30, 60, 120, 300];
62
+ // 已完成 / 已停止的任务不必每轮都查线上状态:5 分钟同步一次足够发现 Reopened
63
+ const SYNC_TERMINAL_MS = 5 * 60 * 1000;
64
+ const SYNC_CONCURRENCY = 4;
65
+ const TERMINAL_TASK_STATES = new Set(["done", "stopped"]);
66
+
67
+ /**
68
+ * 缺陷重开 = 新一轮修复周期,必须清掉上一轮的交付与复核结论。
69
+ *
70
+ * 只改 status 不清理的话,deliverTask 会把上一轮的 commit 当成「已交付」而
71
+ * 直接跳过提交(缺陷被测试重开后看起来转成了待验证,实际新改动根本没提交),
72
+ * 返工次数与复核预算也会沿用旧值,导致新周期一上来就判定预算耗尽。
73
+ */
74
+ function newCyclePatch() {
75
+ return {
76
+ commit: null,
77
+ result: null,
78
+ verify: null,
79
+ changedFiles: null,
80
+ codeReview: null,
81
+ reviewRound: 0,
82
+ reviewPolicy: null,
83
+ verifyUnavailable: null,
84
+ reworkCount: 0,
85
+ dispatchCount: 0,
86
+ needsHuman: null,
87
+ workerSessionId: null,
88
+ interruptCount: 0,
89
+ timeoutCount: 0,
90
+ failCount: 0,
91
+ _baselineUntrusted: null,
92
+ };
93
+ }
94
+
95
+ /* ======================== 工具函数 ======================== */
96
+
97
+ /** 限制并发地处理数组;结果顺序与输入一致。 */
98
+ async function mapLimit(items, limit, fn) {
99
+ const list = Array.isArray(items) ? items : [];
100
+ const out = new Array(list.length);
101
+ let cursor = 0;
102
+ const workers = Array.from({ length: Math.max(1, Math.min(limit, list.length)) }, async () => {
103
+ while (cursor < list.length) {
104
+ const index = cursor++;
105
+ out[index] = await fn(list[index], index);
106
+ }
107
+ });
108
+ await Promise.all(workers);
109
+ return out;
110
+ }
111
+
112
+ export function bugKey(bug) {
113
+ return String(bug?.code || bug?.id || "unknown");
114
+ }
115
+
116
+ /** child 是否位于 parent 目录内(含相等)。路径比较统一小写,适配 Windows。 */
117
+ function isInside(child, parent) {
118
+ const c = path.resolve(child).toLowerCase();
119
+ const p = path.resolve(parent).toLowerCase();
120
+ return c === p || c.startsWith(p.endsWith(path.sep) ? p : p + path.sep);
121
+ }
122
+
123
+ /**
124
+ * 归一化验证命令配置:既接受单条字符串,也接受 [{ command, cwd, label }]。
125
+ * verifyCommands(数组)优先,verifyCommand(字符串)作为兼容字段合并,重复项去掉。
126
+ */
127
+ export function normalizeVerifyCommands(workspace = {}) {
128
+ const list = [];
129
+ const push = (v) => {
130
+ if (!v) return;
131
+ if (typeof v === "string") {
132
+ if (v.trim()) list.push({ command: v.trim(), cwd: null, label: null });
133
+ return;
134
+ }
135
+ if (typeof v.command === "string" && v.command.trim()) {
136
+ list.push({ command: v.command.trim(), cwd: v.cwd || null, label: v.label || null });
137
+ }
138
+ };
139
+
140
+ if (Array.isArray(workspace.verifyCommands)) workspace.verifyCommands.forEach(push);
141
+ else push(workspace.verifyCommands);
142
+ push(workspace.verifyCommand);
143
+
144
+ const seen = new Set();
145
+ return list.filter((s) => {
146
+ const key = `${s.cwd || ""}|${s.command}`;
147
+ if (seen.has(key)) return false;
148
+ seen.add(key);
149
+ return true;
150
+ });
151
+ }
152
+
153
+ /**
154
+ * 把接口错误归类成原因码,便于 status、控制台与日志用同一套说法。
155
+ * 登录失效、权限不足、网络故障必须能被区分开,否则用户不知道该做什么。
156
+ */
157
+ export function classifyError(e) {
158
+ const msg = String(e?.message || e || "");
159
+ if (/401|登录已过期|鉴权失败|API Key 无效/.test(msg)) return "auth_required";
160
+ if (/403|权限不足|无权限/.test(msg)) return "no_permission";
161
+ if (/404|不存在/.test(msg)) return "not_found";
162
+ if (/超时|网络请求失败|ENOTFOUND|ECONNREFUSED|EAI_AGAIN/.test(msg)) return "network";
163
+ return "unknown";
164
+ }
165
+
166
+ export function isActiveTask(task) {
167
+ return !!task && ACTIVE_TASK_STATES.includes(task.status);
168
+ }
169
+
170
+ /** 缺陷当前是否仍应被自动处理。 */
171
+ export function shouldWatch(bug) {
172
+ return !!bug && WATCH_STATUSES.includes(bug.status);
173
+ }
174
+
175
+ /** 严重程度文字别名:接口既可能给 P1/P2,也可能给中文或英文级别。 */
176
+ const SEVERITY_ALIASES = [
177
+ [/致命|阻塞|blocker|critical|fatal|紧急|urgent/, 1],
178
+ [/严重|major|high/, 2],
179
+ [/一般|正常|normal|medium/, 3],
180
+ [/提示|轻微|low|minor|trivial/, 4],
181
+ ];
182
+
183
+ /** 严重程度排序:P1 最先。 */
184
+ export function severityRank(bug) {
185
+ const s = String(bug?.severity || "").trim().toUpperCase();
186
+ const n = Number.parseInt(s.replace(/\D/g, ""), 10);
187
+ if (Number.isFinite(n)) return n;
188
+ for (const [re, rank] of SEVERITY_ALIASES) {
189
+ if (re.test(s)) return rank;
190
+ }
191
+ return 99;
192
+ }
193
+
194
+ /** 比较两个缺陷的优先级:P1 最先。 */
195
+ export function compareBugs(a, b) {
196
+ const s = severityRank(a) - severityRank(b);
197
+ if (s !== 0) return s;
198
+ return String(a?.created_at || "").localeCompare(String(b?.created_at || ""));
199
+ }
200
+
201
+ /** 按优先级排序(返回新数组,不改原数组)。 */
202
+ export function sortBugs(bugs) {
203
+ return [...(bugs || [])].sort(compareBugs);
204
+ }
205
+
206
+ /* ======================== 调度器 ======================== */
207
+
208
+ export class Scheduler {
209
+ constructor({ api, store, agent, workspace, options = {}, onEvent } = {}) {
210
+ this.api = api;
211
+ this.store = store;
212
+ this.agent = agent;
213
+ this.workspace = workspace;
214
+ this.options = options;
215
+ this.onEvent = onEvent;
216
+ this.paused = false;
217
+ this.timer = null;
218
+ this.polling = false;
219
+ this.backoffIndex = 0;
220
+ this.lastError = null;
221
+ this.stopped = false;
222
+ }
223
+
224
+ /**
225
+ * 只上报给上层,不在这里落盘:事件由 Service 统一写一次,
226
+ * 否则同一条事件会被写两遍(日志里出现重复行)。
227
+ */
228
+ emit(event) {
229
+ this.onEvent?.(event);
230
+ }
231
+
232
+ /* ---------- 轮询 ---------- */
233
+
234
+ start({ immediate = true } = {}) {
235
+ if (this.timer && !this.stopped) return; // 已在运行,避免重复计时器
236
+ this.stopped = false;
237
+ this.scheduleNext(immediate ? 0 : this.intervalMs);
238
+ }
239
+
240
+ /**
241
+ * 主动拉取一次并等待完成(启动时用)。
242
+ * 与 tick 共用 polling 锁,避免和周期轮询并发出两个请求。
243
+ */
244
+ async refreshNow() {
245
+ if (this.stopped || this.paused || this.polling) return 0;
246
+ this.polling = true;
247
+ try {
248
+ const found = await this.poll();
249
+ // 只要这一轮没有抛错就重置退避;"没发现新缺陷"也是正常成功
250
+ this.backoffIndex = 0;
251
+ return found;
252
+ } catch (e) {
253
+ this.lastError = String(e?.message || e);
254
+ this.emit({ type: "poll_error", message: this.lastError, reason: classifyError(e) });
255
+ return 0;
256
+ } finally {
257
+ this.polling = false;
258
+ }
259
+ }
260
+
261
+ scheduleNext(delayMs) {
262
+ if (this.stopped) return;
263
+ clearTimeout(this.timer);
264
+ this.timer = setTimeout(() => this.tick(), delayMs);
265
+ if (typeof this.timer.unref === "function") this.timer.unref();
266
+ }
267
+
268
+ get intervalMs() {
269
+ const seconds = this.options.intervalSeconds ?? 60;
270
+ return Math.max(15, Number(seconds) || 60) * 1000;
271
+ }
272
+
273
+ async tick() {
274
+ if (this.stopped) return;
275
+ if (this.paused) {
276
+ this.scheduleNext(this.intervalMs);
277
+ return;
278
+ }
279
+ if (this.polling) {
280
+ this.scheduleNext(this.intervalMs);
281
+ return;
282
+ }
283
+ this.polling = true;
284
+ try {
285
+ const found = await this.poll();
286
+ this.backoffIndex = 0;
287
+ this.scheduleNext(this.intervalMs);
288
+ } catch (e) {
289
+ this.lastError = String(e?.message || e);
290
+ const wait = BACKOFF_SECONDS[Math.min(this.backoffIndex, BACKOFF_SECONDS.length - 1)] * 1000;
291
+ this.backoffIndex += 1;
292
+ const reason = classifyError(e);
293
+ this.emit({ type: "poll_error", message: this.lastError, reason, retryInSeconds: wait / 1000 });
294
+ this.scheduleNext(wait);
295
+ } finally {
296
+ this.polling = false;
297
+ }
298
+ }
299
+
300
+ /**
301
+ * 同步本地已存在任务的线上最新状态。
302
+ * 当用户在外部手动修改、或由其他 Agent 修改并流转了缺陷时,
303
+ * 本地列表能够实时感知,更新 lastStatus,并在外部已解决时自动标记完成。
304
+ */
305
+ async syncExistingTasks() {
306
+ // 任务库是全局的:只同步当前已勾选项目的任务。
307
+ // 未勾选项目的历史任务既不查线上状态,也不会因为线上重开被重新排队。
308
+ const bound = boundProjectSet(this.workspace.projectIds);
309
+ if (!bound.size) return 0;
310
+ const tasks = this.store.listTasks().filter(t => taskInProjectScope(t, null, bound));
311
+ if (!tasks.length) return 0;
312
+
313
+ const now = Date.now();
314
+ // 活跃任务每轮同步;完成/停止的任务降频,避免每个轮询周期都把历史缺陷全查一遍
315
+ const due = tasks.filter(task => {
316
+ if (!task.bugId) return false;
317
+ if (!TERMINAL_TASK_STATES.has(task.status)) return true;
318
+ const last = Date.parse(task.lastSyncedAt || "") || 0;
319
+ return now - last >= SYNC_TERMINAL_MS;
320
+ });
321
+ if (!due.length) return 0;
322
+
323
+ const results = await mapLimit(due, SYNC_CONCURRENCY, task => this.syncOneTask(task, now));
324
+ return results.filter(Boolean).length;
325
+ }
326
+
327
+ /** 同步单个任务的线上最新状态;返回是否发生了需要落库的变化。 */
328
+ async syncOneTask(task, now = Date.now()) {
329
+ // 防御:调用方可能直接传入范围外任务(例如旧版本遗留的调用点)
330
+ if (!taskInProjectScope(task, this.workspace.projectIds)) return false;
331
+ try {
332
+ const fresh = await this.api.getBug(task.bugId);
333
+ if (!fresh || !fresh.status) return false;
334
+ const onlineStatus = fresh.status;
335
+
336
+ let needsWrite = false;
337
+ const patch = {};
338
+
339
+ // 1. 线上状态产生变化
340
+ if (task.lastStatus !== onlineStatus) {
341
+ patch.lastStatus = onlineStatus;
342
+ needsWrite = true;
343
+ }
344
+
345
+ // 2. 线上标题或严重级别有修改
346
+ if (fresh.title && fresh.title !== task.title) {
347
+ patch.title = fresh.title;
348
+ needsWrite = true;
349
+ }
350
+ if (fresh.severity && fresh.severity !== task.severity) {
351
+ patch.severity = fresh.severity;
352
+ needsWrite = true;
353
+ }
354
+
355
+ // 3. 外部已解决/已关闭/已转待验证:
356
+ // 如果本地任务尚未进入修改阶段(discovered/queued)或停留在待人工(needs_human),
357
+ // 直接标记为已完成,不再重复派工。
358
+ const TERMINAL_ONLINE = [
359
+ BUG_STATUS.TO_VERIFY,
360
+ BUG_STATUS.CLOSED,
361
+ "Resolved",
362
+ BUG_STATUS.REJECTED,
363
+ ];
364
+ if (TERMINAL_ONLINE.includes(onlineStatus) && ["discovered", "queued", "needs_human"].includes(task.status)) {
365
+ patch.status = "done";
366
+ patch.externalResolved = true;
367
+ needsWrite = true;
368
+ this.emit({
369
+ type: "task_done",
370
+ taskId: task.taskId,
371
+ message: `敏捷系统中缺陷状态已更新为「${onlineStatus}」,本地任务标记完成`,
372
+ });
373
+ }
374
+
375
+ // 4. 线上被重新打开(Reopened):本地若为已完成或已停止,重新排队修复。
376
+ // 这是新一轮修复周期,上一轮的提交/复核结论必须一起清掉。
377
+ if (onlineStatus === BUG_STATUS.REOPENED && (task.status === "done" || task.status === "stopped")) {
378
+ Object.assign(patch, newCyclePatch());
379
+ patch.status = "queued";
380
+ patch.cycle = (task.cycle || 1) + 1;
381
+ // 重开后测试通常补充了复现步骤 / 评论:把 loadedAt 置空,下一轮派工前
382
+ // 会重新拉取缺陷上下文(userNotes 等人工补充仍然保留)。
383
+ patch.context = { ...(task.context || {}), loadedAt: null };
384
+ needsWrite = true;
385
+ this.emit({
386
+ type: "task_reopened",
387
+ taskId: task.taskId,
388
+ message: `敏捷系统中缺陷已重新打开,重新排队修复`,
389
+ });
390
+ }
391
+
392
+ // 终态任务降频同步:没有变化时只记时间戳,不产生 task_updated 噪声
393
+ if (TERMINAL_TASK_STATES.has(needsWrite ? (patch.status || task.status) : task.status)) {
394
+ patch.lastSyncedAt = new Date(now).toISOString();
395
+ needsWrite = true;
396
+ }
397
+
398
+ if (!needsWrite) return false;
399
+
400
+ this.store.writeTask({ taskId: task.taskId, ...patch });
401
+ if (!patch.lastSyncedAt || patch.status || patch.title || patch.severity || patch.lastStatus) {
402
+ this.emit({
403
+ type: "task_updated",
404
+ taskId: task.taskId,
405
+ lastStatus: onlineStatus,
406
+ status: patch.status || task.status,
407
+ });
408
+ }
409
+ return true;
410
+ } catch {
411
+ // 单个缺陷查询失败不阻塞整体同步
412
+ return false;
413
+ }
414
+ }
415
+
416
+ /** 拉取一次缺陷并建立/更新任务。返回本次新建的任务数。 */
417
+ async poll() {
418
+ // 巡检时段闸门:不在工作时段就跳过本轮。
419
+ // 只跳过"检测",任务记录一条都不删,到下一个时段自动恢复。
420
+ const gate = withinSchedule(this.workspace.schedule);
421
+ if (!gate.ok) {
422
+ this.lastPollSkipped = { reason: gate.reason, message: gate.message, at: new Date().toISOString() };
423
+ this.emit({ type: "poll_skipped", reason: gate.reason, message: gate.message });
424
+ return 0;
425
+ }
426
+ this.lastPollSkipped = null;
427
+
428
+ // 1. 先同步已存在任务的线上最新状态
429
+ const updated = await this.syncExistingTasks();
430
+
431
+ // 2. 拉取分配给我的待处理 / 重开缺陷
432
+ const projectIds = this.workspace.projectIds || [];
433
+ if (!projectIds.length) return updated;
434
+
435
+ const bugs = [];
436
+ // 缺陷列表不一定回传 project_id;按项目逐个查询时记下归属,建任务时兜底,
437
+ // 否则任务会因缺 projectId 被作用域当成旧任务、永远不自动处理
438
+ const bugProjects = new Map();
439
+ for (const projectId of projectIds) {
440
+ const list = await this.api.listMyBugs({ projectId });
441
+ for (const b of list) {
442
+ if (!shouldWatch(b)) continue;
443
+ bugs.push(b);
444
+ if (b?.project_id == null) bugProjects.set(bugKey(b), projectId);
445
+ }
446
+ }
447
+ bugs.sort(compareBugs);
448
+
449
+ let created = 0;
450
+ for (const bug of bugs) {
451
+ const key = bugKey(bug);
452
+ const existing = this.store.readTask(key);
453
+ if (isActiveTask(existing)) continue;
454
+ if (existing?.status === "done" && existing.lastStatus === bug.status && !this.isNewCycle(bug, existing)) {
455
+ continue;
456
+ }
457
+ if (existing?.status === "needs_human" || existing?.status === "stopped") {
458
+ // 失败/待人工任务不自动重启,只有 retry 或重开才继续
459
+ if (existing.lastStatus !== bug.status) continue;
460
+ continue;
461
+ }
462
+
463
+ const task = this.store.writeTask({
464
+ taskId: key,
465
+ bugId: bug.id,
466
+ code: bug.code,
467
+ title: bug.title,
468
+ severity: bug.severity,
469
+ status: "discovered",
470
+ lastStatus: bug.status,
471
+ projectId: bug.project_id ?? bugProjects.get(key) ?? null,
472
+ cycle: (existing?.cycle ?? 0) + 1,
473
+ reworkRound: 0,
474
+ source: "poll",
475
+ // 已有记录说明是重开/重新发现的新周期:清掉上一轮结论,避免跳过提交
476
+ ...(existing ? newCyclePatch() : {}),
477
+ // 同上:新周期重新拉取缺陷上下文,拿到测试补充的复现信息
478
+ ...(existing?.context ? { context: { ...existing.context, loadedAt: null } } : {}),
479
+ });
480
+ created += 1;
481
+ this.emit({ type: "task_discovered", taskId: task.taskId, title: task.title, severity: task.severity });
482
+ // 发现即装载上下文:复现步骤、预期/实际行为、截图、评论。
483
+ // 不等主 Agent 转述——转述一定会丢信息,尤其是截图路径。
484
+ this.hydrateTaskContext(task.taskId).catch(() => {});
485
+ }
486
+ return created;
487
+ }
488
+
489
+ /**
490
+ * 装载缺陷上下文(详情 + 截图 + 评论)并写回任务。
491
+ *
492
+ * 失败不抛错:把失败原因记进上下文,Agent 会知道"上下文不全",
493
+ * 而不是拿着空上下文去猜问题。
494
+ */
495
+ async hydrateTaskContext(taskId) {
496
+ const task = this.store.readTask(taskId);
497
+ if (!task?.bugId) return null;
498
+ if (hasContext(task)) return task;
499
+
500
+ // 同一任务只装载一次:后台装载与派工前装载并发时共用同一个 Promise,
501
+ // 保证 ensureTaskContext 一定等到上下文真正落库后再返回。
502
+ if (!this._hydrating) this._hydrating = new Map();
503
+ if (this._hydrating.has(taskId)) return this._hydrating.get(taskId);
504
+
505
+ const job = this.doHydrateTaskContext(taskId, task).finally(() => {
506
+ this._hydrating.delete(taskId);
507
+ });
508
+ this._hydrating.set(taskId, job);
509
+ return job;
510
+ }
511
+
512
+ async doHydrateTaskContext(taskId, originalTask) {
513
+ try {
514
+ const { context } = await loadBugContext({ api: this.api, bugId: originalTask.bugId });
515
+ // 拉取期间可能有人往 context 里写了 userNotes / 人工回答,
516
+ // 所以写回前必须重新读一次,不能拿拉取前的旧快照整字段覆盖。
517
+ const current = this.store.readTask(taskId) || originalTask;
518
+ const merged = { ...(current.context || {}), ...context, loadError: null };
519
+ const updated = this.store.writeTask({ taskId, context: merged });
520
+ this.emit({ type: "task_context_loaded", taskId, hasScreenshots: (context.screenshots || []).length > 0 });
521
+ return updated;
522
+ } catch (e) {
523
+ const message = String(e?.message || e);
524
+ const current = this.store.readTask(taskId) || originalTask;
525
+ const merged = {
526
+ ...(current.context || {}),
527
+ loadError: message,
528
+ loadedAt: new Date().toISOString(),
529
+ };
530
+ this.store.writeTask({ taskId, context: merged });
531
+ this.emit({ type: "task_context_error", taskId, message });
532
+ return this.store.readTask(taskId);
533
+ }
534
+ }
535
+
536
+ /**
537
+ * 确保任务上下文已装载。派工前调用,保证修复 Agent 拿到完整缺陷信息。
538
+ * 已装载则直接返回,不重复拉取。
539
+ */
540
+ async ensureTaskContext(task) {
541
+ if (!task) return null;
542
+ if (hasContext(task)) return task;
543
+ return this.hydrateTaskContext(task.taskId);
544
+ }
545
+
546
+ /** Reopened 视为新一轮修复周期。 */
547
+ isNewCycle(bug, existing) {
548
+ return bug.status === BUG_STATUS.REOPENED && existing?.lastStatus !== BUG_STATUS.REOPENED;
549
+ }
550
+
551
+ /* ---------- 工作区基线 ---------- */
552
+
553
+ /**
554
+ * 读取工作区 Git 信息。
555
+ * 传 repos(工作树里的仓库绝对路径)时按仓库分别读,支持仓库不在工作区一级子目录的情况。
556
+ */
557
+ async readInfo(cwd = this.workspace.path, repos = null) {
558
+ if (!Array.isArray(repos) || !repos.length) return readGitInfo(cwd);
559
+ // repos 既接受路径字符串,也接受 { path, name }:配置档的仓库名可能和目录名不同,
560
+ // 用声明的名字才能在 diff 与 worker 申报之间对齐。
561
+ const entries = repos.map(r => {
562
+ if (typeof r === "string") return { path: r, name: path.basename(r) };
563
+ return {
564
+ path: r?.path || r?.relPath || r?.name,
565
+ name: r?.name || path.basename(String(r?.path || r?.relPath || "")),
566
+ };
567
+ }).filter(e => e.path);
568
+ if (!entries.length) return readGitInfo(cwd);
569
+ const infos = await Promise.all(entries.map(e => readGitInfo(e.path)));
570
+ const list = entries.map((e, i) => {
571
+ const info = infos[i] || {};
572
+ return {
573
+ path: path.resolve(e.path),
574
+ name: e.name,
575
+ head: info.head || null,
576
+ dirtyFiles: info.dirtyFiles || [],
577
+ };
578
+ });
579
+ // 路径统一成"相对工作区根":只有仓库目录不在工作区根下时才加仓库名前缀。
580
+ // 这样单仓库(含从仓库子目录启动、配置档只声明一个子仓库)都能与
581
+ // canonicalizeChangedFiles 的归一结果对齐,正常改动不会被误判成越界改动。
582
+ const cwdAbs = path.resolve(cwd).toLowerCase();
583
+ const dirties = list.flatMap(r => {
584
+ const own = path.resolve(r.path).toLowerCase() === cwdAbs;
585
+ return r.dirtyFiles.map(f => (own ? f : `${r.name}/${f}`));
586
+ });
587
+ const multi = list.length > 1;
588
+ return {
589
+ isRepo: !multi,
590
+ multiRepo: multi,
591
+ head: multi ? null : list[0].head,
592
+ dirtyFiles: dirties,
593
+ repos: list,
594
+ };
595
+ }
596
+
597
+ /**
598
+ * 记录工作区基线(git 状态指纹),用于识别越界修改与脏工作区。
599
+ * 不传参数时记录主工作区基线;隔离工作树在派工时单独记录。
600
+ */
601
+ async captureBaseline(cwd = this.workspace.path, { repos = null } = {}) {
602
+ const info = await this.readInfo(cwd, repos);
603
+ const baseline = {
604
+ at: new Date().toISOString(),
605
+ isRepo: info.isRepo,
606
+ multiRepo: !!info.multiRepo,
607
+ head: info.head,
608
+ dirtyFiles: info.dirtyFiles,
609
+ repos: (info.repos || []).map(r => ({
610
+ path: r.path, name: r.name, head: r.head, dirtyFiles: r.dirtyFiles,
611
+ })),
612
+ };
613
+ if (cwd === this.workspace.path && !repos) this.baseline = baseline;
614
+ return baseline;
615
+ }
616
+
617
+ /**
618
+ * 对比当前状态与基线,判断 worker 是否动过基线之外的文件。
619
+ * 多仓库工作区按仓库分别比较,返回的路径统一为"相对工作区"。
620
+ *
621
+ * baseline / cwd 可显式传入,供隔离工作树使用;不传则沿用主工作区。
622
+ */
623
+ async diffAgainstBaseline(baseline = this.baseline, cwd = this.workspace.path) {
624
+ const base = baseline;
625
+ if (!base?.isRepo && !base?.multiRepo) {
626
+ return { beyondBaseline: [], ok: true, note: "非 Git 目录,无 diff 保护" };
627
+ }
628
+ const repoPaths = (base.repos || [])
629
+ .filter(r => r?.path)
630
+ .map(r => ({ path: r.path, name: r.name || path.basename(r.path) }));
631
+ const info = await this.readInfo(cwd, repoPaths.length ? repoPaths : null);
632
+
633
+ if (base.multiRepo) {
634
+ const before = new Map((base.repos || []).map(r => [r.path, new Set(r.dirtyFiles || [])]));
635
+ const cwdAbs = path.resolve(cwd).toLowerCase();
636
+ const beyond = [];
637
+ for (const r of info.repos || []) {
638
+ const prev = before.get(r.path) || new Set();
639
+ // 与 readInfo 保持同一归一规则:仓库就在工作区根下时不加前缀
640
+ const own = path.resolve(r.path).toLowerCase() === cwdAbs;
641
+ for (const f of r.dirtyFiles) {
642
+ if (!prev.has(f)) beyond.push(own ? f : `${r.name}/${f}`);
643
+ }
644
+ }
645
+ return { beyondBaseline: beyond, ok: true, multiRepo: true, dirtyFiles: info.dirtyFiles };
646
+ }
647
+
648
+ const before = new Set(base.dirtyFiles || []);
649
+ const beyond = info.dirtyFiles.filter(f => !before.has(f));
650
+ return { beyondBaseline: beyond, ok: true, head: info.head, dirtyFiles: info.dirtyFiles };
651
+ }
652
+
653
+ /* ---------- 状态流转(带写前复查) ---------- */
654
+
655
+ /**
656
+ * 转到 InProgress:先复查线上状态与处理人,符合预期才写。
657
+ * 状态已被人工改动时返回 {ok:false, reason},由上层转人工。
658
+ */
659
+ async markInProgress(task) {
660
+ const fresh = await this.api.getBug(task.bugId);
661
+ const me = await this.api.whoami();
662
+ const alreadyMine = fresh.assignee_id === me.id || fresh.assignee_name === me.nickname;
663
+ // 已经是「处理中」且在我名下:直接继续。lastStatus 是轮询同步来的,可能滞后于
664
+ // 刚才的认领(派工后很快返工会被误判成「状态被人改了」而白白退回队列)。
665
+ if (alreadyMine && fresh.status === BUG_STATUS.IN_PROGRESS) {
666
+ return { ok: true, skipped: true };
667
+ }
668
+ if (fresh.status !== task.lastStatus) {
669
+ return {
670
+ ok: false,
671
+ reason: "status_changed",
672
+ onlineStatus: fresh.status,
673
+ message: `线上状态已变为 ${fresh.status},不再自动认领`,
674
+ };
675
+ }
676
+ try {
677
+ await this.api.transition(task.bugId, { toStatus: BUG_STATUS.IN_PROGRESS, assigneeId: me.id });
678
+ this.emit({ type: "bug_status", taskId: task.taskId, to: BUG_STATUS.IN_PROGRESS });
679
+ return { ok: true };
680
+ } catch (e) {
681
+ const msg = String(e?.message || e);
682
+ if (/403|权限/.test(msg)) {
683
+ return { ok: false, reason: "no_permission", message: "当前凭证无权流转缺陷状态" };
684
+ }
685
+ return { ok: false, reason: "transition_failed", message: msg };
686
+ }
687
+ }
688
+
689
+ /**
690
+ * 转到 ToVerify:仅在独立验证通过且线上状态未变时调用。
691
+ */
692
+ async markToVerify(task, notes) {
693
+ const fresh = await this.api.getBug(task.bugId);
694
+ if (fresh.status !== BUG_STATUS.IN_PROGRESS) {
695
+ return {
696
+ ok: false,
697
+ reason: "status_changed",
698
+ onlineStatus: fresh.status,
699
+ message: `线上状态为 ${fresh.status},不覆盖人工操作`,
700
+ };
701
+ }
702
+ try {
703
+ await this.api.transition(task.bugId, {
704
+ toStatus: BUG_STATUS.TO_VERIFY,
705
+ resolution: "fixed",
706
+ notes,
707
+ });
708
+ this.emit({ type: "bug_status", taskId: task.taskId, to: BUG_STATUS.TO_VERIFY });
709
+ return { ok: true };
710
+ } catch (e) {
711
+ const msg = String(e?.message || e);
712
+ const reason = /403|权限/.test(msg) ? "no_permission" : "transition_failed";
713
+ return { ok: false, reason, message: msg };
714
+ }
715
+ }
716
+
717
+ /* ---------- 独立验证 ---------- */
718
+
719
+ /**
720
+ * 按实际改动生成验证计划。
721
+ *
722
+ * 一条固定命令覆盖不了多仓库工作区:worker 同时改了前端和后端时,
723
+ * 只跑其中一个的 lint 等于没验证。规则:
724
+ * 1. 显式配置的命令总是执行(可带 cwd 限定到某个子仓库);
725
+ * 2. 被改动、但没有被任何显式命令覆盖的子仓库,自动补一条该子仓库能识别的命令;
726
+ * 3. 仍然覆盖不到的改动文件单独列出,交给调用方转人工——绝不假装验证通过。
727
+ */
728
+ buildVerifyPlan(changedFiles = [], { root = this.workspace.path, repos = null } = {}) {
729
+ const steps = [];
730
+ const forbidden = [];
731
+ const covered = new Set();
732
+
733
+ const excludedRepos = this.workspace.excludedRepos || [];
734
+ const eligibleFiles = changedFiles.filter(f => {
735
+ const lf = f.toLowerCase();
736
+ return !excludedRepos.some(e => {
737
+ const p = String(e.relPath || e.name || "").replace(/\\/g, "/").toLowerCase();
738
+ return p && (lf === p || lf.startsWith(p + "/"));
739
+ });
740
+ });
741
+
742
+ const pushStep = (step) => {
743
+ if (isForbiddenVerifyCommand(step.command)) {
744
+ forbidden.push({ ...step, reason: "forbidden_command" });
745
+ return;
746
+ }
747
+ steps.push(step);
748
+ };
749
+
750
+ for (const raw of normalizeVerifyCommands(this.workspace)) {
751
+ const cwd = raw.cwd ? path.resolve(root, raw.cwd) : root;
752
+ pushStep({ command: raw.command, cwd, label: raw.label || raw.command, source: "configured" });
753
+ covered.add(path.resolve(cwd));
754
+ }
755
+
756
+ // 多仓库时优先用配置档为每个仓库声明的验证命令;单仓库 workspace.repos 为空
757
+ const repoList = Array.isArray(repos) ? repos : (this.workspace.repos || []);
758
+ const uncovered = [];
759
+
760
+ // 配置档里为每个仓库声明了自己的验证命令:优先用它,不再自动猜。
761
+ for (const repo of repoList) {
762
+ const verifyList = Array.isArray(repo.verify) ? repo.verify : [];
763
+ if (!verifyList.length) continue;
764
+ // 仓库路径可能是绝对路径、相对工作区的相对路径,或只有目录名
765
+ const repoPath = repo.path || repo.relPath || repo.name;
766
+ const cwd = path.isAbsolute(repoPath) ? path.resolve(repoPath) : path.resolve(root, repoPath);
767
+ if (covered.has(cwd)) continue;
768
+ for (const command of verifyList) {
769
+ pushStep({ command, cwd, label: `${repo.name}: ${command}`, source: "repo" });
770
+ }
771
+ covered.add(cwd);
772
+ }
773
+
774
+ for (const file of eligibleFiles) {
775
+ const rel = String(file || "").trim().replace(/\\/g, "/").replace(/^\.\//, "");
776
+ if (!rel) continue;
777
+ const repo = repoList.find(r => {
778
+ // 改动路径可能是「配置档 relPath/...」或「仓库名/...」开头(提交与 diff 用后者)
779
+ const prefixes = [r.relPath, r.name]
780
+ .map(v => String(v || "").replace(/\\/g, "/").replace(/^\.\//, ""))
781
+ .filter(p => p && p !== ".");
782
+ return prefixes.some(prefix => rel === prefix || rel.startsWith(`${prefix}/`));
783
+ });
784
+ const repoPath = repo ? (repo.path || repo.relPath || repo.name) : null;
785
+ const unit = repoPath
786
+ ? (path.isAbsolute(repoPath) ? path.resolve(repoPath) : path.resolve(root, repoPath))
787
+ : root;
788
+
789
+ // 已有命令落在该单元内(或正好是该单元)就算覆盖
790
+ if ([...covered].some(c => isInside(unit, c) || isInside(c, unit))) continue;
791
+
792
+ const command = detectVerifyCommand(unit);
793
+ if (!command) { uncovered.push(rel); continue; }
794
+ pushStep({
795
+ command,
796
+ cwd: unit,
797
+ label: `${repo ? `${repo.name}: ` : ""}${command}`,
798
+ source: "detected",
799
+ });
800
+ covered.add(unit);
801
+ }
802
+
803
+ return { steps, uncovered, forbidden };
804
+ }
805
+
806
+ /**
807
+ * 执行独立验证。
808
+ *
809
+ * 传字符串时按单条命令执行(保持兼容);传 { changedFiles } 时按实际改动生成计划,
810
+ * 逐条执行,全部通过且没有未覆盖的改动才算通过。
811
+ */
812
+ async runVerify(input) {
813
+ const isDirect = typeof input === "string" || input == null;
814
+ const opts = (!isDirect && typeof input === "object") ? input : {};
815
+ const plan = isDirect
816
+ ? {
817
+ steps: input ? [{ command: input, cwd: this.workspace.path, label: input, source: "configured" }] : [],
818
+ uncovered: [],
819
+ forbidden: [],
820
+ }
821
+ : this.buildVerifyPlan(input.changedFiles || [], { root: opts.root, repos: opts.repos });
822
+
823
+ // 显式传入的单条命令也要过红线:build / tsc / vue-tsc 一律不执行
824
+ const blocked = (plan.forbidden || []).filter(step => isForbiddenVerifyCommand(step.command));
825
+ if (isDirect && plan.steps.length) {
826
+ for (const step of plan.steps) {
827
+ if (isForbiddenVerifyCommand(step.command)) blocked.push({ ...step, reason: "forbidden_command" });
828
+ }
829
+ if (blocked.length) {
830
+ plan.steps = plan.steps.filter(step => !isForbiddenVerifyCommand(step.command));
831
+ }
832
+ }
833
+
834
+ if (!plan.steps.length) {
835
+ if (blocked.length) {
836
+ return {
837
+ ok: false,
838
+ skipped: false,
839
+ reason: "forbidden_command",
840
+ steps: [],
841
+ uncovered: plan.uncovered,
842
+ forbidden: blocked,
843
+ summary: `验证命令被红线拦截(禁止编译/打包/类型检查):${blocked.map(s => s.command).join(";")}`,
844
+ };
845
+ }
846
+ return {
847
+ ok: false,
848
+ skipped: true,
849
+ reason: "no_command",
850
+ steps: [],
851
+ uncovered: plan.uncovered,
852
+ forbidden: [],
853
+ summary: plan.uncovered.length
854
+ ? `没有可用的验证命令,且有 ${plan.uncovered.length} 个改动文件未被覆盖:${plan.uncovered.join(", ")}`
855
+ : "未配置验证命令",
856
+ };
857
+ }
858
+
859
+ const results = [];
860
+ for (const step of plan.steps) {
861
+ try {
862
+ const { stdout, stderr } = await execFileAsync(step.command, {
863
+ cwd: step.cwd,
864
+ timeout: 5 * 60 * 1000,
865
+ windowsHide: true,
866
+ maxBuffer: 16 * 1024 * 1024,
867
+ shell: true,
868
+ });
869
+ results.push({
870
+ ...step,
871
+ ok: true,
872
+ exitCode: 0,
873
+ summary: String(stdout || "").slice(-2000),
874
+ stderr: String(stderr || "").slice(-1000),
875
+ });
876
+ } catch (e) {
877
+ results.push({
878
+ ...step,
879
+ ok: false,
880
+ exitCode: typeof e?.code === "number" ? e.code : null,
881
+ summary: String(e?.stdout || "").slice(-2000),
882
+ stderr: String(e?.stderr || e?.message || "").slice(-2000),
883
+ });
884
+ // 一条失败就停:后面的命令大概率也会失败,没必要再等
885
+ break;
886
+ }
887
+ }
888
+
889
+ const failed = results.find(r => !r.ok);
890
+ const coveredAll = plan.uncovered.length === 0 && blocked.length === 0;
891
+ const reason = failed ? "command_failed" : blocked.length ? "forbidden_command" : (coveredAll ? null : "uncovered_changes");
892
+ const forbiddenNote = blocked.length
893
+ ? `以下命令被红线拦截,未执行:${blocked.map(s => s.command).join(";")}`
894
+ : "";
895
+ return {
896
+ ok: !failed && coveredAll,
897
+ skipped: false,
898
+ reason,
899
+ steps: results,
900
+ uncovered: plan.uncovered,
901
+ forbidden: blocked,
902
+ // 兼容旧字段:整体摘要与失败输出
903
+ summary: failed
904
+ ? failed.summary
905
+ : [results.map(r => r.summary).filter(Boolean).join("\n"), forbiddenNote].filter(Boolean).join("\n").slice(-2000),
906
+ stderr: failed ? failed.stderr : "",
907
+ };
908
+ }
909
+
910
+ /* ---------- 人工介入 ---------- */
911
+
912
+ /** 任务转人工:必须带原因、已完成动作与建议下一步;并自动附上可点击选项。 */
913
+ needsHuman(taskId, { reason, done, next, options } = {}) {
914
+ const task = this.store.writeTask({
915
+ taskId,
916
+ status: "needs_human",
917
+ needsHuman: {
918
+ reason,
919
+ done,
920
+ next,
921
+ options: needsHumanOptions(reason, { suggested: options }),
922
+ at: new Date().toISOString(),
923
+ },
924
+ });
925
+ this.emit({ type: "task_needs_human", taskId, reason });
926
+ return task;
927
+ }
928
+
929
+ recordMessage(taskId, message) {
930
+ appendMessage(taskId, message);
931
+ }
932
+
933
+ /* ---------- 停止 ---------- */
934
+
935
+ stop() {
936
+ this.stopped = true;
937
+ clearTimeout(this.timer);
938
+ this.timer = null;
939
+ }
940
+ }
941
+
942
+ /* ======================== 状态机校验 ======================== */
943
+
944
+ const ALLOWED_TRANSITIONS = {
945
+ discovered: ["queued", "needs_human", "stopped"],
946
+ queued: ["launching", "needs_human", "stopped"],
947
+ launching: ["running", "needs_human", "stopped"],
948
+ running: ["verifying", "needs_human", "stopped"],
949
+ verifying: ["review", "needs_human", "stopped"],
950
+ review: ["running", "resolving", "needs_human", "stopped"],
951
+ resolving: ["done", "needs_human", "stopped"],
952
+ needs_human: ["queued", "running", "stopped"],
953
+ stopped: ["queued"],
954
+ done: ["queued"],
955
+ };
956
+
957
+ export function canTransition(from, to) {
958
+ if (from === to) return true;
959
+ return (ALLOWED_TRANSITIONS[from] || []).includes(to);
960
+ }
961
+
962
+ /** 写任务前校验状态迁移合法;非法迁移抛错,避免状态机被绕过。 */
963
+ export function transitionTask(store, taskId, nextStatus, patch = {}) {
964
+ const current = store.readTask(taskId);
965
+ if (!current) throw new Error(`未知任务: ${taskId}`);
966
+ if (!canTransition(current.status, nextStatus)) {
967
+ throw new Error(`非法状态迁移: ${current.status} -> ${nextStatus}`);
968
+ }
969
+ return store.writeTask({ taskId, status: nextStatus, ...patch });
970
+ }
971
+
972
+ /* ======================== 会话内任务清单 ======================== */
973
+
974
+ /** 生成给主 Agent / worker 的任务上下文摘要。 */
975
+ export function buildTaskContext(task, extra = {}) {
976
+ return {
977
+ taskId: task.taskId,
978
+ bugId: task.bugId,
979
+ code: task.code,
980
+ title: task.title,
981
+ severity: task.severity,
982
+ status: task.status,
983
+ cycle: task.cycle,
984
+ reworkRound: task.reworkRound,
985
+ workspace: task.workspace ?? null,
986
+ ...extra,
987
+ };
988
+ }
989
+
990
+ export function summarizeTasks(tasks = listTasks()) {
991
+ const counts = {};
992
+ for (const t of tasks) counts[t.status] = (counts[t.status] || 0) + 1;
993
+ return counts;
994
+ }