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.
- package/README.md +300 -173
- package/SKILL.md +114 -98
- package/adev.js +1319 -1285
- package/autofix/agents/antigravity.js +379 -0
- package/autofix/agents/claude.js +147 -0
- package/autofix/agents/codex.js +179 -0
- package/autofix/agents/exec.js +230 -0
- package/autofix/agents/index.js +400 -0
- package/autofix/agents/opencode.js +233 -0
- package/autofix/agents/pi.js +247 -0
- package/autofix/agiledev.js +98 -0
- package/autofix/bridge.js +371 -0
- package/autofix/cli.js +712 -0
- package/autofix/context.js +152 -0
- package/autofix/conversation.js +302 -0
- package/autofix/coordinator.js +2892 -0
- package/autofix/git.js +459 -0
- package/autofix/policy.js +230 -0
- package/autofix/profile.js +578 -0
- package/autofix/public/app.js +3668 -0
- package/autofix/public/i18n-id.js +282 -0
- package/autofix/public/index.html +32 -0
- package/autofix/public/style.css +2463 -0
- package/autofix/queue.js +146 -0
- package/autofix/scheduler.js +994 -0
- package/autofix/scope.js +32 -0
- package/autofix/service.js +1940 -0
- package/autofix/store.js +375 -0
- package/autofix/workspace.js +298 -0
- package/autofix/worktree.js +379 -0
- package/docs/autofix-design.md +801 -0
- package/docs/autofix-profiles.example.json +65 -0
- package/imgs/Bug/350/247/243/345/206/263/345/244/207/346/263/250.png +0 -0
- package/imgs/logo.png +0 -0
- package/imgs//344/277/256/346/224/271Bug/347/212/266/346/200/201.png +0 -0
- package/imgs//345/270/256/346/210/221/344/277/256/345/244/215Bug-20260922-010.png +0 -0
- 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
- 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
- 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
- package/package.json +39 -36
package/autofix/cli.js
ADDED
|
@@ -0,0 +1,712 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `adev autofix` 命令入口。
|
|
3
|
+
*
|
|
4
|
+
* 零参数启动:所有可选参数都按“本次参数 > 工作区记忆 > 全局记忆 > 自动探测/内置默认”解析,
|
|
5
|
+
* 已确认且无歧义时不出现任何交互提示。
|
|
6
|
+
*/
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import crypto from "node:crypto";
|
|
10
|
+
import { spawn } from "node:child_process";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
|
|
13
|
+
import { loadConfig } from "../adev.js";
|
|
14
|
+
import {
|
|
15
|
+
appendEvent, configPath, readConfig, readServiceState, readWorkspace, statePath, writeConfig,
|
|
16
|
+
writeWorkspace,
|
|
17
|
+
} from "./store.js";
|
|
18
|
+
import {
|
|
19
|
+
detectVerifyCommand, inspectWorkspace, normalizeWorkspacePath,
|
|
20
|
+
} from "./workspace.js";
|
|
21
|
+
import { detectAgents, resolveAgent } from "./agents/index.js";
|
|
22
|
+
import { Service, openConsole, REASON_MESSAGES } from "./service.js";
|
|
23
|
+
import { DEFAULT_PROMPT } from "./coordinator.js";
|
|
24
|
+
import {
|
|
25
|
+
describeSchedule, listProfiles, profileToWorkspace, resolveProfile,
|
|
26
|
+
} from "./profile.js";
|
|
27
|
+
|
|
28
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
29
|
+
const CLI_PATH = path.join(HERE, "cli.js");
|
|
30
|
+
const DEFAULT_PORT = 3210;
|
|
31
|
+
|
|
32
|
+
const SUBCOMMANDS = new Set([
|
|
33
|
+
"status", "pause", "resume", "stop", "ui", "say", "assign", "tell",
|
|
34
|
+
"answer", "retry", "config", "restart", "profiles",
|
|
35
|
+
]);
|
|
36
|
+
|
|
37
|
+
/* ======================== 参数解析 ======================== */
|
|
38
|
+
|
|
39
|
+
const VALUE_FLAGS = new Set([
|
|
40
|
+
"agent", "prompt", "model", "worker-model", "interval", "verify", "project", "profile",
|
|
41
|
+
]);
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* 解析 autofix 的参数。与通用 parseArgs 分开:autofix 的第二个参数可能是选项而非资源 action。
|
|
45
|
+
*/
|
|
46
|
+
export function parseAutofixArgs(argv) {
|
|
47
|
+
const out = { _: [], flags: {} };
|
|
48
|
+
for (let i = 0; i < argv.length; i++) {
|
|
49
|
+
const a = argv[i];
|
|
50
|
+
if (a.startsWith("--")) {
|
|
51
|
+
const raw = a.slice(2);
|
|
52
|
+
if (raw === "no-ui" || raw === "auto-verify" || raw === "foreground" || raw === "yes" || raw === "setup") {
|
|
53
|
+
out.flags[raw] = true;
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
// 工作树隔离开关:--worktree 强制开启,--no-worktree 强制关闭(默认自动判断)
|
|
57
|
+
if (raw === "worktree") { out.flags.worktree = true; continue; }
|
|
58
|
+
if (raw === "no-worktree") { out.flags.noWorktree = true; continue; }
|
|
59
|
+
const key = raw.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
60
|
+
const value = argv[i + 1];
|
|
61
|
+
if (value === undefined || value.startsWith("--")) {
|
|
62
|
+
throw new Error(`选项 --${raw} 需要一个值,例如: --${raw} <value>`);
|
|
63
|
+
}
|
|
64
|
+
out.flags[key] = value;
|
|
65
|
+
// --verify 可重复:多仓库工作区需要分别验证前端与后端
|
|
66
|
+
if (key === "verify") out.flags.verifyList = [...(out.flags.verifyList || []), value];
|
|
67
|
+
i += 1;
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
out._.push(a);
|
|
71
|
+
}
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
/* ======================== 控制接口客户端 ======================== */
|
|
77
|
+
|
|
78
|
+
async function control(port, token, pathname, options = {}) {
|
|
79
|
+
const res = await fetch(`http://127.0.0.1:${port}${pathname}`, {
|
|
80
|
+
method: options.method || "GET",
|
|
81
|
+
headers: {
|
|
82
|
+
"X-Autofix-Token": token,
|
|
83
|
+
...(options.body ? { "Content-Type": "application/json" } : {}),
|
|
84
|
+
},
|
|
85
|
+
body: options.body ? JSON.stringify(options.body) : undefined,
|
|
86
|
+
signal: AbortSignal.timeout(options.timeoutMs || 60 * 1000),
|
|
87
|
+
});
|
|
88
|
+
const payload = await res.json().catch(() => ({}));
|
|
89
|
+
if (!res.ok) throw new Error(payload.message || `请求失败(${res.status})`);
|
|
90
|
+
return payload;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function requireInstance() {
|
|
94
|
+
const state = readServiceState();
|
|
95
|
+
if (!state?.pid || !state.port || !state.token) {
|
|
96
|
+
throw new Error("Autofix 服务未运行。在目标目录执行 `adev autofix` 启动。");
|
|
97
|
+
}
|
|
98
|
+
return state;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/* ======================== 启动 ======================== */
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* 解析本次启动所需的全部参数,返回零参数可用的配置。
|
|
105
|
+
*/
|
|
106
|
+
export async function resolveStartup({ cwd, flags }) {
|
|
107
|
+
const config = readConfig();
|
|
108
|
+
const workspacePath = normalizeWorkspacePath(cwd);
|
|
109
|
+
const saved = readWorkspace(workspacePath);
|
|
110
|
+
const info = await inspectWorkspace(workspacePath);
|
|
111
|
+
const detected = await detectAgents();
|
|
112
|
+
|
|
113
|
+
// 工作区配置档:显式指定 > 当前目录命中 > 唯一可用。
|
|
114
|
+
// 配置档声明了多仓库结构与巡检时段,比"自动探测子目录"准确得多。
|
|
115
|
+
const profiles = listProfiles(cwd);
|
|
116
|
+
const profilePick = resolveProfile({ cwd, profileId: flags.profile || null, profiles });
|
|
117
|
+
const profile = profilePick.ok ? profilePick.profile : null;
|
|
118
|
+
|
|
119
|
+
const agentChoice = resolveAgent({
|
|
120
|
+
requested: flags.agent || null,
|
|
121
|
+
workspaceAgent: saved?.agent || profile?.agent || null,
|
|
122
|
+
lastAgent: config.lastAgent || null,
|
|
123
|
+
detected,
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
const prompt = flags.prompt || saved?.prompt || profile?.prompt || DEFAULT_PROMPT;
|
|
127
|
+
const intervalSeconds = flags.interval
|
|
128
|
+
? Math.max(15, Number.parseInt(flags.interval, 10) || 60)
|
|
129
|
+
: (saved?.intervalSeconds || profile?.intervalSeconds || config.intervalSeconds || 60);
|
|
130
|
+
const model = flags.model || saved?.model || profile?.model || config.model || null;
|
|
131
|
+
const workerModel = flags["workerModel"] || saved?.workerModel || profile?.workerModel || config.workerModel || null;
|
|
132
|
+
const workerAgent = flags["workerAgent"] || saved?.workerAgent || profile?.workerAgent || null;
|
|
133
|
+
|
|
134
|
+
// 显式 --verify(可多次)> 已保存的命令 > 配置档声明 > 自动识别;多仓库工作区根目录识别不到时,
|
|
135
|
+
// 由 scheduler 按实际改动的子仓库自动补命令。
|
|
136
|
+
const explicitVerify = (flags.verifyList && flags.verifyList.length)
|
|
137
|
+
? flags.verifyList
|
|
138
|
+
: (Array.isArray(saved?.verifyCommands) && saved.verifyCommands.length
|
|
139
|
+
? saved.verifyCommands
|
|
140
|
+
: (saved?.verifyCommand ? [saved.verifyCommand] : null));
|
|
141
|
+
const detectedVerify = detectVerifyCommand(workspacePath);
|
|
142
|
+
const profileVerify = Array.isArray(profile?.verifyCommands) ? profile.verifyCommands : [];
|
|
143
|
+
const verifyCommands = explicitVerify || (profileVerify.length ? profileVerify : (detectedVerify ? [detectedVerify] : []));
|
|
144
|
+
const verifyCommand = verifyCommands[0] || null;
|
|
145
|
+
|
|
146
|
+
let projectIds = saved?.projectIds || [];
|
|
147
|
+
let projectNames = saved?.projectNames || [];
|
|
148
|
+
let confirmedAt = saved?.confirmedAt || null;
|
|
149
|
+
let remoteKey = saved?.remoteKey || null;
|
|
150
|
+
|
|
151
|
+
const bindingValid = projectIds.length
|
|
152
|
+
&& saved?.path === workspacePath
|
|
153
|
+
&& (!saved?.remoteKey || saved.remoteKey === info.remoteKey);
|
|
154
|
+
|
|
155
|
+
if (!bindingValid) {
|
|
156
|
+
projectIds = [];
|
|
157
|
+
projectNames = [];
|
|
158
|
+
confirmedAt = null;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// 配置档声明了项目:作为配置页的预选值(仍需用户在页面确认后才生效)
|
|
162
|
+
if (!projectIds.length && profile?.projectIds?.length) {
|
|
163
|
+
projectIds = profile.projectIds;
|
|
164
|
+
projectNames = profile.projectNames || [];
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// 工作区根目录:配置档声明优先(多仓库结构都挂在它下面)
|
|
168
|
+
// 根目录不存在就退回当前目录,绝不因为配置写错路径就让服务起不来
|
|
169
|
+
const profileRootUsable = !!profile?.root && fs.existsSync(profile.root);
|
|
170
|
+
const profileRoot = profileRootUsable ? profile.root : workspacePath;
|
|
171
|
+
const profileWorkspace = profile
|
|
172
|
+
? profileToWorkspace(profile, { workspacePath: profileRoot, remoteKey: info.remoteKey })
|
|
173
|
+
: null;
|
|
174
|
+
// 仓库清单:配置档声明优先;没有配置档时退回自动探测到的子仓库
|
|
175
|
+
const repos = profileWorkspace?.repos?.length
|
|
176
|
+
? profileWorkspace.repos
|
|
177
|
+
: (info.multiRepo ? (info.repos || []).map(r => ({
|
|
178
|
+
name: r.name,
|
|
179
|
+
path: r.path,
|
|
180
|
+
relPath: r.name,
|
|
181
|
+
role: "other",
|
|
182
|
+
branch: null,
|
|
183
|
+
testBranch: null,
|
|
184
|
+
verify: [],
|
|
185
|
+
push: null,
|
|
186
|
+
enabled: true,
|
|
187
|
+
})) : []);
|
|
188
|
+
|
|
189
|
+
return {
|
|
190
|
+
config,
|
|
191
|
+
saved,
|
|
192
|
+
info,
|
|
193
|
+
detected,
|
|
194
|
+
agentChoice,
|
|
195
|
+
profiles,
|
|
196
|
+
profile,
|
|
197
|
+
profileError: profilePick.ok ? null : profilePick,
|
|
198
|
+
workspace: {
|
|
199
|
+
path: profileRoot,
|
|
200
|
+
agent: agentChoice.agent,
|
|
201
|
+
workerAgent,
|
|
202
|
+
prompt,
|
|
203
|
+
intervalSeconds,
|
|
204
|
+
model,
|
|
205
|
+
workerModel,
|
|
206
|
+
verifyCommand,
|
|
207
|
+
verifyCommands,
|
|
208
|
+
autoVerify: flags["autoVerify"] === true || saved?.autoVerify === true || profile?.autoVerify === true,
|
|
209
|
+
// 工作树隔离:--no-worktree 强制关闭、--worktree 强制开启,否则沿用上次选择/自动判断
|
|
210
|
+
isolateWorktrees: flags.noWorktree ? false : (flags.worktree ? true : (saved?.isolateWorktrees ?? null)),
|
|
211
|
+
projectIds,
|
|
212
|
+
projectNames,
|
|
213
|
+
confirmedAt,
|
|
214
|
+
remoteKey: info.remoteKey,
|
|
215
|
+
isRepo: info.isRepo,
|
|
216
|
+
// 多仓库工作区信息必须带下去:验证计划要按子仓库分别决定跑哪条命令
|
|
217
|
+
multiRepo: repos.length > 0,
|
|
218
|
+
repos,
|
|
219
|
+
dirty: info.dirty,
|
|
220
|
+
dirtyFiles: info.dirtyFiles,
|
|
221
|
+
// 配置档带来的调度策略
|
|
222
|
+
profileId: profile?.id || null,
|
|
223
|
+
profileLabel: profile?.label || null,
|
|
224
|
+
maxWorkers: profile?.maxWorkers || null,
|
|
225
|
+
schedule: profileWorkspace?.schedule || null,
|
|
226
|
+
review: profileWorkspace?.review || null,
|
|
227
|
+
push: profile?.push ?? null,
|
|
228
|
+
excludedRepos: profileWorkspace?.excludedRepos || [],
|
|
229
|
+
},
|
|
230
|
+
flags,
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* 后台启动服务进程。端口由父进程选定后传给子进程,避免两边不一致。
|
|
236
|
+
* 默认进入 setup 阶段:先提供网页配置,不立即轮询或派工。
|
|
237
|
+
*/
|
|
238
|
+
function spawnService({ cwd, flags, workspace, port }) {
|
|
239
|
+
const args = [CLI_PATH, "__serve", "--workspace", workspace.path, "--port", String(port), "--setup"];
|
|
240
|
+
if (flags["noUi"]) args.push("--no-ui");
|
|
241
|
+
const child = spawn(process.execPath, args, {
|
|
242
|
+
cwd,
|
|
243
|
+
detached: true,
|
|
244
|
+
stdio: "ignore",
|
|
245
|
+
windowsHide: true,
|
|
246
|
+
shell: false,
|
|
247
|
+
});
|
|
248
|
+
child.unref();
|
|
249
|
+
return child.pid;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** 等待服务健康检查通过。 */
|
|
253
|
+
async function waitHealthy(port, timeoutMs = 20000) {
|
|
254
|
+
const deadline = Date.now() + timeoutMs;
|
|
255
|
+
while (Date.now() < deadline) {
|
|
256
|
+
try {
|
|
257
|
+
const res = await fetch(`http://127.0.0.1:${port}/api/status`, {
|
|
258
|
+
signal: AbortSignal.timeout(1500),
|
|
259
|
+
});
|
|
260
|
+
if (res.status < 500) return true;
|
|
261
|
+
} catch { /* 还没起来 */ }
|
|
262
|
+
await new Promise(r => setTimeout(r, 300));
|
|
263
|
+
}
|
|
264
|
+
return false;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/* ======================== 主命令 ======================== */
|
|
268
|
+
|
|
269
|
+
export async function runAutofix(argv, { cwd = process.cwd() } = {}) {
|
|
270
|
+
const parsed = parseAutofixArgs(argv);
|
|
271
|
+
const flags = parsed.flags;
|
|
272
|
+
const sub = parsed._[0];
|
|
273
|
+
|
|
274
|
+
if (sub && SUBCOMMANDS.has(sub)) {
|
|
275
|
+
return runSubcommand(sub, parsed);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// --- 启动控制台(默认停在配置页,不直接开始修复) ---
|
|
279
|
+
const existing = Service.existingInstance();
|
|
280
|
+
if (existing) {
|
|
281
|
+
const sameWorkspace = existing.workspace === normalizeWorkspacePath(cwd);
|
|
282
|
+
if (sameWorkspace || !Object.keys(flags).length) {
|
|
283
|
+
console.log(`Autofix 控制台已在运行(工作区 ${existing.workspace},端口 ${existing.port})。`);
|
|
284
|
+
console.log(`控制台:${openConsole(existing.port)}`);
|
|
285
|
+
return 0;
|
|
286
|
+
}
|
|
287
|
+
console.log("本次带了新的参数,与运行中的实例不同。请先 `adev autofix stop`,再在目标目录重新启动。");
|
|
288
|
+
return 1;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const startup = await resolveStartup({ cwd, flags });
|
|
292
|
+
const { workspace, info } = startup;
|
|
293
|
+
const saved = startup.saved || {};
|
|
294
|
+
|
|
295
|
+
if (!info.exists) {
|
|
296
|
+
console.error(`[adev] 当前工作目录已失效:${workspace.path}`);
|
|
297
|
+
return 1;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// 把本次显式参数写入工作区,作为网页配置的预填值;是否启动由用户在页面决定。
|
|
301
|
+
const preset = {};
|
|
302
|
+
const setIf = (key, value) => {
|
|
303
|
+
if (value !== undefined && value !== null && value !== "") preset[key] = value;
|
|
304
|
+
};
|
|
305
|
+
setIf("remoteKey", info.remoteKey);
|
|
306
|
+
setIf("agent", flags.agent);
|
|
307
|
+
setIf("workerAgent", flags["workerAgent"]);
|
|
308
|
+
setIf("model", flags.model);
|
|
309
|
+
setIf("workerModel", flags["workerModel"]);
|
|
310
|
+
setIf("prompt", flags.prompt);
|
|
311
|
+
if (flags.interval) preset.intervalSeconds = workspace.intervalSeconds;
|
|
312
|
+
if (flags["autoVerify"]) preset.autoVerify = true;
|
|
313
|
+
if (flags.noWorktree) preset.isolateWorktrees = false;
|
|
314
|
+
else if (flags.worktree) preset.isolateWorktrees = true;
|
|
315
|
+
if (flags.verifyList?.length) {
|
|
316
|
+
preset.verifyCommands = flags.verifyList;
|
|
317
|
+
preset.verifyCommand = flags.verifyList[0];
|
|
318
|
+
}
|
|
319
|
+
if (flags.project) {
|
|
320
|
+
preset.projectIds = String(flags.project).split(",").map(s => s.trim()).filter(Boolean);
|
|
321
|
+
preset.projectNames = [];
|
|
322
|
+
}
|
|
323
|
+
if (flags.profile) preset.profileId = String(flags.profile).trim();
|
|
324
|
+
if (workspace.profileId) preset.profileId = workspace.profileId;
|
|
325
|
+
if (Object.keys(preset).length) writeWorkspace(workspace.path, preset);
|
|
326
|
+
|
|
327
|
+
const port = DEFAULT_PORT;
|
|
328
|
+
const pid = spawnService({ cwd, flags, workspace, port });
|
|
329
|
+
console.log(`Autofix 控制台已启动(PID ${pid})。`);
|
|
330
|
+
|
|
331
|
+
const healthy = await waitHealthy(port);
|
|
332
|
+
if (!healthy) {
|
|
333
|
+
console.error(`[adev] 控制台启动失败或超时。可查看日志目录:${path.join(process.env.HOME || process.env.USERPROFILE || ".", ".agiledev-autofix", "logs")}`);
|
|
334
|
+
return 1;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
const url = `http://127.0.0.1:${port}/`;
|
|
338
|
+
if (!flags["noUi"]) console.log(`控制台:${openConsole(port)}`);
|
|
339
|
+
else console.log(`控制台:${url}`);
|
|
340
|
+
|
|
341
|
+
// --yes:非交互场景按已保存/本次参数直接启动;默认必须由页面点击启动。
|
|
342
|
+
if (flags.yes) {
|
|
343
|
+
const mainAgent = flags.agent || workspace.agent || saved.agent;
|
|
344
|
+
if (!mainAgent) {
|
|
345
|
+
console.error("[adev] --yes 需要可用 Agent:请加 --agent claude|opencode|antigravity|codex|pi");
|
|
346
|
+
return 1;
|
|
347
|
+
}
|
|
348
|
+
const savedVerify = Array.isArray(saved.verifyCommands) && saved.verifyCommands.length
|
|
349
|
+
? saved.verifyCommands
|
|
350
|
+
: (saved.verifyCommand ? [saved.verifyCommand] : []);
|
|
351
|
+
let started;
|
|
352
|
+
try {
|
|
353
|
+
const state = readServiceState();
|
|
354
|
+
started = await control(port, state.token, "/api/start", {
|
|
355
|
+
method: "POST",
|
|
356
|
+
body: {
|
|
357
|
+
mainAgent,
|
|
358
|
+
workerAgent: flags["workerAgent"] || saved.workerAgent || mainAgent,
|
|
359
|
+
mainModel: flags.model ?? saved.model ?? workspace.model ?? "",
|
|
360
|
+
workerModel: flags["workerModel"] ?? saved.workerModel ?? workspace.workerModel ?? "",
|
|
361
|
+
projectIds: preset.projectIds || saved.projectIds || workspace.projectIds || [],
|
|
362
|
+
projectNames: preset.projectIds ? [] : (saved.projectNames || []),
|
|
363
|
+
intervalSeconds: flags.interval ? workspace.intervalSeconds : (saved.intervalSeconds || workspace.intervalSeconds),
|
|
364
|
+
verifyCommands: flags.verifyList?.length ? flags.verifyList : savedVerify,
|
|
365
|
+
autoVerify: flags["autoVerify"] === true || saved.autoVerify === true,
|
|
366
|
+
isolateWorktrees: workspace.isolateWorktrees ?? undefined,
|
|
367
|
+
prompt: flags.prompt || saved.prompt || workspace.prompt,
|
|
368
|
+
profileId: workspace.profileId || flags.profile || saved.profileId || null,
|
|
369
|
+
acceptRisk: true,
|
|
370
|
+
},
|
|
371
|
+
});
|
|
372
|
+
} catch (e) {
|
|
373
|
+
console.error(`[adev] 自动启动失败:${e?.message || e}`);
|
|
374
|
+
return 1;
|
|
375
|
+
}
|
|
376
|
+
const st = started?.status;
|
|
377
|
+
console.log(st?.phase === "running"
|
|
378
|
+
? `自动修复已启动:主 Agent ${st.workspace.agent},修复 Agent ${st.workspace.workerAgent},项目 ${st.workspace.projectNames.join(", ") || "未绑定(观察模式)"}`
|
|
379
|
+
: "控制台已就绪。");
|
|
380
|
+
return 0;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
console.log("请在页面中选择主 Agent、模型与敏捷项目,然后点击「启动自动修复」。");
|
|
384
|
+
return 0;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/* ======================== 子命令 ======================== */
|
|
388
|
+
|
|
389
|
+
async function runSubcommand(sub, parsed) {
|
|
390
|
+
const args = parsed._.slice(1);
|
|
391
|
+
|
|
392
|
+
// profiles 只读配置,不依赖服务是否在运行
|
|
393
|
+
if (sub === "profiles") {
|
|
394
|
+
const list = listProfiles(process.cwd());
|
|
395
|
+
if (!list.length) {
|
|
396
|
+
console.log("没有找到任何工作区配置档。");
|
|
397
|
+
console.log("请在项目内创建 .autofix.json,或在全局写 ~/.agiledev-autofix/profiles.json。");
|
|
398
|
+
return 0;
|
|
399
|
+
}
|
|
400
|
+
console.log(`工作区配置档(${list.length} 个):\n`);
|
|
401
|
+
for (const p of list) {
|
|
402
|
+
console.log(` ${p.id} ${p.label}`);
|
|
403
|
+
console.log(` 主目录:${p.root}`);
|
|
404
|
+
console.log(` 敏捷项目:${p.projectIds.join(", ") || "(未声明)"}${p.projectNames.length ? ` / ${p.projectNames.join("、")}` : ""}`);
|
|
405
|
+
if (p.repos.length) {
|
|
406
|
+
console.log(" 仓库:");
|
|
407
|
+
for (const r of p.repos) {
|
|
408
|
+
const parts = [`${r.name}`, `角色=${r.role}`];
|
|
409
|
+
if (r.branch) parts.push(`开发分支=${r.branch}`);
|
|
410
|
+
if (r.testBranch) parts.push(`测试分支=${r.testBranch}`);
|
|
411
|
+
if (r.verify?.length) parts.push(`验证=${r.verify.join(" | ")}`);
|
|
412
|
+
console.log(` - ${parts.join(" ")}`);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
console.log(` 巡检时段:${describeSchedule(p.schedule)}`);
|
|
416
|
+
console.log(` 复核阈值:改动 ≥${p.review.fileThreshold} 个文件或跨端时必须复核`);
|
|
417
|
+
console.log("");
|
|
418
|
+
}
|
|
419
|
+
console.log("使用:adev autofix --profile <id>");
|
|
420
|
+
return 0;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// config 只改全局配置文件,不依赖服务是否在运行
|
|
424
|
+
if (sub === "config") {
|
|
425
|
+
const patch = {};
|
|
426
|
+
if (parsed.flags.agent) patch.lastAgent = parsed.flags.agent;
|
|
427
|
+
if (parsed.flags.model) patch.model = parsed.flags.model;
|
|
428
|
+
if (parsed.flags["workerModel"]) patch.workerModel = parsed.flags.workerModel;
|
|
429
|
+
if (parsed.flags.interval) patch.intervalSeconds = Math.max(15, Number.parseInt(parsed.flags.interval, 10) || 60);
|
|
430
|
+
const next = writeConfig(patch);
|
|
431
|
+
console.log(`已更新全局配置:${configPath()}`);
|
|
432
|
+
console.log(JSON.stringify(next, null, 2));
|
|
433
|
+
|
|
434
|
+
// 验证命令属于工作区级配置:多仓库工作区可以重复传 --verify,分别覆盖前端与后端
|
|
435
|
+
const verifyList = parsed.flags.verifyList;
|
|
436
|
+
if (verifyList?.length) {
|
|
437
|
+
const wsPath = normalizeWorkspacePath(process.cwd());
|
|
438
|
+
const saved = readWorkspace(wsPath) || {};
|
|
439
|
+
writeWorkspace(wsPath, {
|
|
440
|
+
...saved,
|
|
441
|
+
verifyCommand: verifyList[0],
|
|
442
|
+
verifyCommands: verifyList,
|
|
443
|
+
});
|
|
444
|
+
console.log(`已更新工作区验证命令(${wsPath}):`);
|
|
445
|
+
for (const cmd of verifyList) console.log(` - ${cmd}`);
|
|
446
|
+
console.log("重启服务后生效:adev autofix restart");
|
|
447
|
+
}
|
|
448
|
+
return 0;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
const state = requireInstance();
|
|
452
|
+
const { port, token } = state;
|
|
453
|
+
|
|
454
|
+
switch (sub) {
|
|
455
|
+
case "status": {
|
|
456
|
+
const s = await control(port, token, "/api/status");
|
|
457
|
+
if (s.phase === "setup") {
|
|
458
|
+
console.log("状态:等待启动配置(请在控制台选择 Agent、模型与敏捷项目后启动)");
|
|
459
|
+
console.log(`控制台:http://127.0.0.1:${s.port}/`);
|
|
460
|
+
} else {
|
|
461
|
+
console.log(`状态:${s.paused ? "已暂停" : "运行中"}`);
|
|
462
|
+
}
|
|
463
|
+
console.log(`工作区:${s.workspace.path}`);
|
|
464
|
+
if (s.workspace.profileId) console.log(`配置档:${s.workspace.profileLabel || s.workspace.profileId}${s.workspace.repos?.length ? `(${s.workspace.repos.map(r => r.name).join("、")})` : ""}`);
|
|
465
|
+
console.log(`主 Agent:${s.workspace.agent || "未选择"}${s.workspace.model ? ` · 模型 ${s.workspace.model}` : ""}`);
|
|
466
|
+
console.log(`修复 Agent:${s.workspace.workerAgent || s.workspace.agent || "未选择"}${s.workspace.workerModel ? ` · 模型 ${s.workspace.workerModel}` : ""}`);
|
|
467
|
+
console.log(`敏捷项目:${s.workspace.projectNames.join(", ") || "未绑定"}`);
|
|
468
|
+
console.log(`巡检时段:${s.workspace.scheduleText || "未限制"}`);
|
|
469
|
+
console.log(`工作树隔离:${s.workspace.isolateWorktrees === true ? "已开启(每个任务独立 Git 工作树)" : (s.workspace.isolateWorktrees === false ? "已关闭(共享工作区)" : "自动(Git 仓库默认开启)")}`);
|
|
470
|
+
console.log(`验证命令:${(s.workspace.verifyCommands?.length ? s.workspace.verifyCommands : [s.workspace.verifyCommand]).filter(Boolean).join(" | ") || "未配置(按实际改动自动识别)"}`);
|
|
471
|
+
if (s.pollSkipped) console.log(`提示:${s.pollSkipped.message}(本轮未检测缺陷,任务记录保留)`);
|
|
472
|
+
if (s.reasonDetail && s.reason !== "normal" && s.reason !== "setup") console.log(`提示:${s.reasonDetail}`);
|
|
473
|
+
const t = s.tasks || {};
|
|
474
|
+
console.log(`任务:${Object.entries(t).map(([k, v]) => `${k} ${v}`).join(" · ") || "无"}`);
|
|
475
|
+
if (s.questions) console.log(`待你决定:${s.questions}`);
|
|
476
|
+
return 0;
|
|
477
|
+
}
|
|
478
|
+
case "pause":
|
|
479
|
+
await control(port, token, "/api/pause", { method: "POST", body: {} });
|
|
480
|
+
console.log("已暂停:不再检测与派工。");
|
|
481
|
+
return 0;
|
|
482
|
+
case "resume":
|
|
483
|
+
await control(port, token, "/api/resume", { method: "POST", body: {} });
|
|
484
|
+
console.log("已恢复。");
|
|
485
|
+
return 0;
|
|
486
|
+
case "stop":
|
|
487
|
+
await control(port, token, "/api/stop", { method: "POST", body: {} });
|
|
488
|
+
console.log("已停止。文件与任务记录保留。");
|
|
489
|
+
return 0;
|
|
490
|
+
case "ui":
|
|
491
|
+
console.log(`控制台:${openConsole(port)}`);
|
|
492
|
+
return 0;
|
|
493
|
+
case "say": {
|
|
494
|
+
const text = args.join(" ");
|
|
495
|
+
if (!text) { console.error("用法: adev autofix say \"指令\""); return 1; }
|
|
496
|
+
await control(port, token, "/api/say", { method: "POST", body: { text }, timeoutMs: 10 * 60 * 1000 });
|
|
497
|
+
console.log("已发送给主 Agent。");
|
|
498
|
+
return 0;
|
|
499
|
+
}
|
|
500
|
+
case "assign":
|
|
501
|
+
case "tell": {
|
|
502
|
+
const id = args[0];
|
|
503
|
+
const text = args.slice(1).join(" ");
|
|
504
|
+
if (!id) { console.error(`用法: adev autofix ${sub} <任务编号> "内容"`); return 1; }
|
|
505
|
+
await control(port, token, "/api/tools", {
|
|
506
|
+
method: "POST",
|
|
507
|
+
body: { name: "send_message", arguments: { taskId: id, text } },
|
|
508
|
+
});
|
|
509
|
+
console.log("已记录。");
|
|
510
|
+
return 0;
|
|
511
|
+
}
|
|
512
|
+
case "answer": {
|
|
513
|
+
const id = args[0];
|
|
514
|
+
const answer = args.slice(1).join(" ");
|
|
515
|
+
if (!id) { console.error("用法: adev autofix answer <问题编号> \"回答\""); return 1; }
|
|
516
|
+
const r = await control(port, token, "/api/answer", { method: "POST", body: { id, answer } });
|
|
517
|
+
if (!r.ok) { console.error(r.message || "回答失败"); return 1; }
|
|
518
|
+
console.log("已记录回答并通知主 Agent。");
|
|
519
|
+
return 0;
|
|
520
|
+
}
|
|
521
|
+
case "retry": {
|
|
522
|
+
const id = args[0];
|
|
523
|
+
if (!id) { console.error("用法: adev autofix retry <任务编号>"); return 1; }
|
|
524
|
+
await control(port, token, "/api/retry", { method: "POST", body: { id } });
|
|
525
|
+
console.log("已重新排队。");
|
|
526
|
+
return 0;
|
|
527
|
+
}
|
|
528
|
+
case "restart": {
|
|
529
|
+
await control(port, token, "/api/stop", { method: "POST", body: {} });
|
|
530
|
+
console.log("已停止。稍后在目标目录执行 `adev autofix` 重新启动。");
|
|
531
|
+
return 0;
|
|
532
|
+
}
|
|
533
|
+
default:
|
|
534
|
+
console.error(`未知的 autofix 子命令: ${sub}`);
|
|
535
|
+
return 1;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/* ======================== 服务进程入口 ======================== */
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* 服务进程以 detached + stdio: "ignore" 启动,崩溃堆栈默认完全丢失,
|
|
543
|
+
* 用户只会看到控制台突然失联。这里把未捕获异常落到 crash.log 与事件日志,
|
|
544
|
+
* 把「自动挂了」变成可定位的问题。
|
|
545
|
+
*/
|
|
546
|
+
function installCrashGuards() {
|
|
547
|
+
const logCrash = (kind, error) => {
|
|
548
|
+
const message = String(error?.message || error || "未知错误");
|
|
549
|
+
const stack = String(error?.stack || "");
|
|
550
|
+
const line = `[${new Date().toISOString()}] ${kind}: ${message}\n${stack ? `${stack}\n` : ""}`;
|
|
551
|
+
try {
|
|
552
|
+
fs.mkdirSync(statePath("logs"), { recursive: true });
|
|
553
|
+
fs.appendFileSync(path.join(statePath("logs"), "crash.log"), line, { mode: 0o600 });
|
|
554
|
+
} catch { /* 写日志本身失败时不能再抛异常 */ }
|
|
555
|
+
try {
|
|
556
|
+
appendEvent({ type: "service_crash", kind, message, stack: stack.slice(0, 4000) });
|
|
557
|
+
} catch { /* 事件日志写失败忽略 */ }
|
|
558
|
+
};
|
|
559
|
+
|
|
560
|
+
// 未处理的 Promise 拒绝通常只发生在某个异步分支:记录后继续运行,
|
|
561
|
+
// 不能因为它把整个服务带走,正在处理的 Agent 记录也会一起消失。
|
|
562
|
+
process.on("unhandledRejection", reason => logCrash("unhandledRejection", reason));
|
|
563
|
+
|
|
564
|
+
// 未捕获异常说明当前调用栈已经损坏:记录后退出,且把运行标记留在「异常结束」状态,
|
|
565
|
+
// 下次启动会自动恢复会话;这里不能调用 service.stop(),否则会被误判为用户主动停止。
|
|
566
|
+
process.on("uncaughtException", error => {
|
|
567
|
+
logCrash("uncaughtException", error);
|
|
568
|
+
process.exit(1);
|
|
569
|
+
});
|
|
570
|
+
|
|
571
|
+
// 非 0 退出码补记一笔,便于区分「主动停止」与「被系统结束」。
|
|
572
|
+
process.on("exit", code => {
|
|
573
|
+
if (code && code !== 0) logCrash("exit", `进程退出码 ${code}`);
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/** `__serve`:由父进程分离启动的服务进程。 */
|
|
578
|
+
export async function runServiceProcess(argv, { cwd = process.cwd() } = {}) {
|
|
579
|
+
installCrashGuards();
|
|
580
|
+
const parsed = parseAutofixArgs(argv);
|
|
581
|
+
const flags = parsed.flags;
|
|
582
|
+
const workspacePath = flags.workspace ? normalizeWorkspacePath(flags.workspace) : normalizeWorkspacePath(cwd);
|
|
583
|
+
|
|
584
|
+
const config = readConfig();
|
|
585
|
+
const saved = readWorkspace(workspacePath) || {};
|
|
586
|
+
const info = await inspectWorkspace(workspacePath);
|
|
587
|
+
const detected = await detectAgents();
|
|
588
|
+
const agentChoice = resolveAgent({
|
|
589
|
+
requested: flags.agent || null,
|
|
590
|
+
workspaceAgent: saved.agent || null,
|
|
591
|
+
lastAgent: config.lastAgent || null,
|
|
592
|
+
detected,
|
|
593
|
+
});
|
|
594
|
+
|
|
595
|
+
const setup = flags.setup === true;
|
|
596
|
+
|
|
597
|
+
// 服务进程也要解析配置档:多仓库结构、巡检时段、复核阈值都来自它
|
|
598
|
+
const profiles = listProfiles(workspacePath);
|
|
599
|
+
const profilePick = resolveProfile({ cwd: workspacePath, profileId: flags.profile || saved.profileId || null, profiles });
|
|
600
|
+
const profile = profilePick.ok ? profilePick.profile : null;
|
|
601
|
+
const profileWorkspace = profile
|
|
602
|
+
? profileToWorkspace(profile, { workspacePath: profile.root || workspacePath, remoteKey: info.remoteKey })
|
|
603
|
+
: null;
|
|
604
|
+
|
|
605
|
+
const repos = profileWorkspace?.repos?.length
|
|
606
|
+
? profileWorkspace.repos
|
|
607
|
+
: (info.multiRepo ? (info.repos || []).map(r => ({
|
|
608
|
+
name: r.name, path: r.path, relPath: r.name, role: "other",
|
|
609
|
+
branch: null, testBranch: null, verify: [], push: null, enabled: true,
|
|
610
|
+
})) : []);
|
|
611
|
+
|
|
612
|
+
const workspace = {
|
|
613
|
+
// 配置档写错 root 时退回真实 cwd,不能让服务挂在不存在的工作区上
|
|
614
|
+
path: (profile?.root && fs.existsSync(profile.root)) ? profile.root : workspacePath,
|
|
615
|
+
agent: saved.agent || profile?.agent || agentChoice.agent,
|
|
616
|
+
workerAgent: saved.workerAgent || profile?.workerAgent || null,
|
|
617
|
+
model: saved.model ?? config.model ?? profile?.model ?? null,
|
|
618
|
+
workerModel: saved.workerModel ?? config.workerModel ?? profile?.workerModel ?? null,
|
|
619
|
+
prompt: saved.prompt || profile?.prompt || DEFAULT_PROMPT,
|
|
620
|
+
intervalSeconds: saved.intervalSeconds || config.intervalSeconds || profile?.intervalSeconds || 60,
|
|
621
|
+
projectIds: saved.projectIds?.length ? saved.projectIds : (profile?.projectIds || []),
|
|
622
|
+
projectNames: saved.projectIds?.length ? (saved.projectNames || []) : (profile?.projectNames || []),
|
|
623
|
+
verifyCommand: saved.verifyCommand || (profile?.verifyCommands || [])[0] || detectVerifyCommand(workspacePath),
|
|
624
|
+
verifyCommands: Array.isArray(saved.verifyCommands) && saved.verifyCommands.length
|
|
625
|
+
? saved.verifyCommands
|
|
626
|
+
: ((saved.verifyCommand ? [saved.verifyCommand] : []).length
|
|
627
|
+
? (saved.verifyCommand ? [saved.verifyCommand] : [])
|
|
628
|
+
: (profile?.verifyCommands?.length ? profile.verifyCommands : (detectVerifyCommand(workspacePath) ? [detectVerifyCommand(workspacePath)] : []))),
|
|
629
|
+
autoVerify: saved.autoVerify === true || profile?.autoVerify === true,
|
|
630
|
+
isolateWorktrees: saved.isolateWorktrees ?? null,
|
|
631
|
+
remoteKey: info.remoteKey,
|
|
632
|
+
// 单仓库也要带下去:Coordinator 据此默认开启任务级工作树隔离
|
|
633
|
+
isRepo: info.isRepo,
|
|
634
|
+
multiRepo: repos.length > 0,
|
|
635
|
+
repos,
|
|
636
|
+
profileId: profile?.id || saved.profileId || null,
|
|
637
|
+
profileLabel: profile?.label || null,
|
|
638
|
+
maxWorkers: saved.maxWorkers || profile?.maxWorkers || null,
|
|
639
|
+
schedule: profileWorkspace?.schedule || null,
|
|
640
|
+
review: profileWorkspace?.review || null,
|
|
641
|
+
push: profile?.push ?? null,
|
|
642
|
+
excludedRepos: profileWorkspace?.excludedRepos || [],
|
|
643
|
+
};
|
|
644
|
+
|
|
645
|
+
const service = new Service({
|
|
646
|
+
workspace,
|
|
647
|
+
setup,
|
|
648
|
+
options: {
|
|
649
|
+
agent: workspace.agent,
|
|
650
|
+
workerAgent: workspace.workerAgent,
|
|
651
|
+
model: workspace.model,
|
|
652
|
+
workerModel: workspace.workerModel,
|
|
653
|
+
intervalSeconds: workspace.intervalSeconds,
|
|
654
|
+
port: Number(flags.port) || 3210,
|
|
655
|
+
},
|
|
656
|
+
});
|
|
657
|
+
|
|
658
|
+
const result = await service.start();
|
|
659
|
+
if (!result.ok) {
|
|
660
|
+
console.error(`[adev] 服务启动失败:${result.reason}`);
|
|
661
|
+
process.exit(1);
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
const shutdown = async () => {
|
|
665
|
+
await service.stop();
|
|
666
|
+
process.exit(0);
|
|
667
|
+
};
|
|
668
|
+
process.on("SIGINT", shutdown);
|
|
669
|
+
process.on("SIGTERM", shutdown);
|
|
670
|
+
return service;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/* ======================== 入口 ======================== */
|
|
674
|
+
|
|
675
|
+
export async function main(argv) {
|
|
676
|
+
const args = argv ?? process.argv.slice(2);
|
|
677
|
+
if (args[0] === "__serve") {
|
|
678
|
+
// 服务进程:保持事件循环存活,由服务自身管理退出
|
|
679
|
+
await runServiceProcess(args.slice(1));
|
|
680
|
+
return null;
|
|
681
|
+
}
|
|
682
|
+
try {
|
|
683
|
+
return await runAutofix(args);
|
|
684
|
+
} catch (e) {
|
|
685
|
+
console.error(`[adev] ${e?.message || e}`);
|
|
686
|
+
return 1;
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
export { REASON_MESSAGES };
|
|
691
|
+
|
|
692
|
+
/* ======================== 直接执行入口 ======================== */
|
|
693
|
+
|
|
694
|
+
function invokedDirectly() {
|
|
695
|
+
const entry = process.argv[1];
|
|
696
|
+
if (!entry) return false;
|
|
697
|
+
try {
|
|
698
|
+
return fs.realpathSync(path.resolve(entry)).toLowerCase()
|
|
699
|
+
=== fs.realpathSync(fileURLToPath(import.meta.url)).toLowerCase();
|
|
700
|
+
} catch {
|
|
701
|
+
return path.resolve(entry).toLowerCase() === fileURLToPath(import.meta.url).toLowerCase();
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
if (invokedDirectly()) {
|
|
706
|
+
main().then(code => {
|
|
707
|
+
if (code !== null && code !== undefined) process.exit(code);
|
|
708
|
+
}).catch(e => {
|
|
709
|
+
console.error(`[adev] ${e?.stack || e}`);
|
|
710
|
+
process.exit(1);
|
|
711
|
+
});
|
|
712
|
+
}
|