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/store.js
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* autofix 本地状态存储。
|
|
3
|
+
*
|
|
4
|
+
* - 全局配置:~/.agiledev-autofix.json(兜底值,跨目录复用)
|
|
5
|
+
* - 运行状态:~/.agiledev-autofix/(state / workspaces / tasks / sessions / events)
|
|
6
|
+
*
|
|
7
|
+
* 所有 JSON 写入走原子替换(临时文件 + rename),并用单写队列串行化,
|
|
8
|
+
* 避免服务进程与 CLI 子命令同时写坏文件。
|
|
9
|
+
*/
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
import os from "node:os";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
import crypto from "node:crypto";
|
|
14
|
+
|
|
15
|
+
const CONFIG_VERSION = 1;
|
|
16
|
+
const DEFAULT_INTERVAL_SECONDS = 60;
|
|
17
|
+
const MIN_INTERVAL_SECONDS = 15;
|
|
18
|
+
|
|
19
|
+
export const TASK_STATES = Object.freeze([
|
|
20
|
+
"discovered", "queued", "launching", "running", "verifying",
|
|
21
|
+
"review", "resolving", "done", "needs_human", "stopped",
|
|
22
|
+
]);
|
|
23
|
+
|
|
24
|
+
export const ACTIVE_TASK_STATES = Object.freeze([
|
|
25
|
+
"discovered", "queued", "launching", "running", "verifying", "review", "resolving",
|
|
26
|
+
]);
|
|
27
|
+
|
|
28
|
+
/* ======================== 路径 ======================== */
|
|
29
|
+
|
|
30
|
+
export function homeDir() {
|
|
31
|
+
const override = process.env.ADEV_AUTOFIX_HOME;
|
|
32
|
+
if (override) return path.resolve(override);
|
|
33
|
+
return path.join(os.homedir(), ".agiledev-autofix");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function configPath() {
|
|
37
|
+
const override = process.env.ADEV_AUTOFIX_CONFIG;
|
|
38
|
+
if (override) return path.resolve(override);
|
|
39
|
+
return path.join(os.homedir(), ".agiledev-autofix.json");
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function statePath(...parts) {
|
|
43
|
+
return path.join(homeDir(), ...parts);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function ensureDir(dir) {
|
|
47
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
48
|
+
return dir;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/* ======================== 原子写入与单写队列 ======================== */
|
|
52
|
+
|
|
53
|
+
let writeChain = Promise.resolve();
|
|
54
|
+
|
|
55
|
+
/** 串行执行写操作;同一进程内不会有并发写。 */
|
|
56
|
+
export function enqueueWrite(fn) {
|
|
57
|
+
const next = writeChain.then(fn, fn);
|
|
58
|
+
writeChain = next.then(() => undefined, () => undefined);
|
|
59
|
+
return next;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Windows 上 rename 偶发 EPERM/EBUSY:目标文件刚创建就被杀毒或索引服务打开。
|
|
64
|
+
* 这类错误是瞬时的,短暂重试即可,不能当成真正的写失败。
|
|
65
|
+
*/
|
|
66
|
+
function renameWithRetry(from, to, attempts = 6) {
|
|
67
|
+
for (let i = 0; ; i++) {
|
|
68
|
+
try {
|
|
69
|
+
fs.renameSync(from, to);
|
|
70
|
+
return;
|
|
71
|
+
} catch (e) {
|
|
72
|
+
const retryable = e?.code === "EPERM" || e?.code === "EBUSY" || e?.code === "EACCES";
|
|
73
|
+
if (!retryable || i >= attempts - 1) throw e;
|
|
74
|
+
const until = Date.now() + 15;
|
|
75
|
+
while (Date.now() < until) { /* 短暂让出,等句柄释放 */ }
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function writeJsonAtomic(file, data) {
|
|
81
|
+
ensureDir(path.dirname(file));
|
|
82
|
+
const text = JSON.stringify(data, null, 2) + "\n";
|
|
83
|
+
const tmp = `${file}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2, 8)}.tmp`;
|
|
84
|
+
fs.writeFileSync(tmp, text, { mode: 0o600 });
|
|
85
|
+
try {
|
|
86
|
+
renameWithRetry(tmp, file);
|
|
87
|
+
} catch (e) {
|
|
88
|
+
try { fs.unlinkSync(tmp); } catch { /* 忽略残留 */ }
|
|
89
|
+
throw e;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function readJsonFile(file, fallback) {
|
|
94
|
+
try {
|
|
95
|
+
const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
96
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
|
|
97
|
+
} catch { /* 不存在或损坏时回退 */ }
|
|
98
|
+
return fallback;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/* ======================== 全局配置 ======================== */
|
|
102
|
+
|
|
103
|
+
export function defaultConfig() {
|
|
104
|
+
return {
|
|
105
|
+
version: CONFIG_VERSION,
|
|
106
|
+
agent: "auto",
|
|
107
|
+
lastAgent: null,
|
|
108
|
+
model: null,
|
|
109
|
+
workerModel: null,
|
|
110
|
+
intervalSeconds: DEFAULT_INTERVAL_SECONDS,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function readConfig() {
|
|
115
|
+
const cfg = { ...defaultConfig(), ...readJsonFile(configPath(), {}) };
|
|
116
|
+
cfg.intervalSeconds = normalizeInterval(cfg.intervalSeconds);
|
|
117
|
+
return cfg;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function writeConfig(patch) {
|
|
121
|
+
const next = { ...readConfig(), ...patch };
|
|
122
|
+
next.version = CONFIG_VERSION;
|
|
123
|
+
next.intervalSeconds = normalizeInterval(next.intervalSeconds);
|
|
124
|
+
writeJsonAtomic(configPath(), next);
|
|
125
|
+
return next;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function normalizeInterval(value) {
|
|
129
|
+
const n = Number.parseInt(value, 10);
|
|
130
|
+
if (!Number.isFinite(n) || n < MIN_INTERVAL_SECONDS) return DEFAULT_INTERVAL_SECONDS;
|
|
131
|
+
return n;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/* ======================== 工作区状态 ======================== */
|
|
135
|
+
|
|
136
|
+
/** 工作区按规范化真实路径分文件保存,一个用户可以服务多个目录。 */
|
|
137
|
+
export function workspaceFile(workspacePath) {
|
|
138
|
+
const key = crypto.createHash("sha256").update(workspacePath.toLowerCase()).digest("hex").slice(0, 12);
|
|
139
|
+
const name = path.basename(workspacePath).replace(/[^a-zA-Z0-9._-]/g, "_") || "workspace";
|
|
140
|
+
return statePath("workspaces", `${name}-${key}.json`);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function readWorkspace(workspacePath) {
|
|
144
|
+
return readJsonFile(workspaceFile(workspacePath), null);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function writeWorkspace(workspacePath, patch) {
|
|
148
|
+
const current = readWorkspace(workspacePath) || {};
|
|
149
|
+
const next = { ...current, ...patch, path: workspacePath };
|
|
150
|
+
writeJsonAtomic(workspaceFile(workspacePath), next);
|
|
151
|
+
return next;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** 列出本机保存过的所有工作区记录(迁移全局文件夹映射时用)。 */
|
|
155
|
+
export function listWorkspaces() {
|
|
156
|
+
const dir = statePath("workspaces");
|
|
157
|
+
let files = [];
|
|
158
|
+
try { files = fs.readdirSync(dir); } catch { return []; }
|
|
159
|
+
return files
|
|
160
|
+
.filter(f => f.endsWith(".json"))
|
|
161
|
+
.map(f => readJsonFile(path.join(dir, f), null))
|
|
162
|
+
.filter(ws => ws && typeof ws === "object");
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/* ======================== 全局项目文件夹映射 ======================== */
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* 「敏捷项目 → 本地文件夹」映射是跨工作区复用的:用户在 A 目录配好
|
|
169
|
+
* 前后端目录后,去 B 目录启动服务也应该能看到,而不是每个工作区各配一遍。
|
|
170
|
+
*
|
|
171
|
+
* 文件不存在返回 null(用于判断是否已做过一次性迁移);存在但为空返回 {}。
|
|
172
|
+
*/
|
|
173
|
+
export function readProjectFolderStore() {
|
|
174
|
+
return readJsonFile(statePath("project-folders.json"), null);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function writeProjectFolderStore(projectFolders) {
|
|
178
|
+
const next = { projectFolders: projectFolders || {}, updatedAt: new Date().toISOString() };
|
|
179
|
+
writeJsonAtomic(statePath("project-folders.json"), next);
|
|
180
|
+
return next.projectFolders;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/* ======================== 任务 ======================== */
|
|
184
|
+
|
|
185
|
+
function taskFile(bugKey) {
|
|
186
|
+
return statePath("tasks", `${String(bugKey).replace(/[^a-zA-Z0-9._-]/g, "_")}.json`);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function readTask(bugKey) {
|
|
190
|
+
return readJsonFile(taskFile(bugKey), null);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export function writeTask(task) {
|
|
194
|
+
if (!task?.taskId) throw new Error("任务缺少 taskId");
|
|
195
|
+
const current = readTask(task.taskId) || {};
|
|
196
|
+
const next = {
|
|
197
|
+
...current,
|
|
198
|
+
...task,
|
|
199
|
+
updatedAt: new Date().toISOString(),
|
|
200
|
+
createdAt: current.createdAt || task.createdAt || new Date().toISOString(),
|
|
201
|
+
};
|
|
202
|
+
// 先合并再校验:允许只传局部字段(如 verify/context),状态沿用原值。
|
|
203
|
+
if (!TASK_STATES.includes(next.status)) throw new Error(`未知任务状态: ${next.status}`);
|
|
204
|
+
writeJsonAtomic(taskFile(task.taskId), next);
|
|
205
|
+
return next;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export function listTasks() {
|
|
209
|
+
const dir = statePath("tasks");
|
|
210
|
+
let files = [];
|
|
211
|
+
try { files = fs.readdirSync(dir); } catch { return []; }
|
|
212
|
+
const tasks = [];
|
|
213
|
+
for (const f of files) {
|
|
214
|
+
if (!f.endsWith(".json")) continue;
|
|
215
|
+
const t = readJsonFile(path.join(dir, f), null);
|
|
216
|
+
if (t?.taskId) tasks.push(t);
|
|
217
|
+
}
|
|
218
|
+
tasks.sort((a, b) => String(b.updatedAt || "").localeCompare(String(a.updatedAt || "")));
|
|
219
|
+
return tasks;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/* ======================== 会话 ======================== */
|
|
223
|
+
|
|
224
|
+
export function readSessions() {
|
|
225
|
+
return readJsonFile(statePath("sessions.json"), { sessions: {} });
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export function writeSessions(sessions) {
|
|
229
|
+
writeJsonAtomic(statePath("sessions.json"), sessions);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export function setSession(key, value) {
|
|
233
|
+
const data = readSessions();
|
|
234
|
+
data.sessions = data.sessions || {};
|
|
235
|
+
if (value === null) delete data.sessions[key];
|
|
236
|
+
else data.sessions[key] = { ...(data.sessions[key] || {}), ...value };
|
|
237
|
+
writeSessions(data);
|
|
238
|
+
return data.sessions;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/* ======================== 服务状态 ======================== */
|
|
242
|
+
|
|
243
|
+
export function readServiceState() {
|
|
244
|
+
return readJsonFile(statePath("state.json"), null);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export function writeServiceState(patch) {
|
|
248
|
+
const next = { ...(readServiceState() || {}), ...patch };
|
|
249
|
+
writeJsonAtomic(statePath("state.json"), next);
|
|
250
|
+
return next;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export function clearServiceState() {
|
|
254
|
+
try { fs.unlinkSync(statePath("state.json")); } catch { /* 已删除 */ }
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/* ======================== 事件日志 ======================== */
|
|
258
|
+
|
|
259
|
+
let eventAppendCount = 0;
|
|
260
|
+
|
|
261
|
+
export function appendEvent(event) {
|
|
262
|
+
const dir = ensureDir(statePath("logs"));
|
|
263
|
+
const file = path.join(dir, "events.jsonl");
|
|
264
|
+
// 事件日志长期运行会无限增长(此前已到 16MB)。每 200 次追加检查一次大小,
|
|
265
|
+
// 超过 8MB 就轮转成 events.1.jsonl(只保留上一份),避免读写变慢与磁盘占用。
|
|
266
|
+
if (++eventAppendCount % 200 === 0) {
|
|
267
|
+
try {
|
|
268
|
+
if (fs.statSync(file).size > 8 * 1024 * 1024) {
|
|
269
|
+
fs.renameSync(file, path.join(dir, "events.1.jsonl"));
|
|
270
|
+
}
|
|
271
|
+
} catch { /* 文件不存在/被占用时忽略,下次再试 */ }
|
|
272
|
+
}
|
|
273
|
+
const line = JSON.stringify({ at: new Date().toISOString(), ...event }) + "\n";
|
|
274
|
+
fs.appendFileSync(file, line, { mode: 0o600 });
|
|
275
|
+
return event;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
export function readEvents(limit = 200) {
|
|
279
|
+
const file = path.join(statePath("logs"), "events.jsonl");
|
|
280
|
+
let text = "";
|
|
281
|
+
try { text = fs.readFileSync(file, "utf8"); } catch { return []; }
|
|
282
|
+
const lines = text.split("\n").filter(Boolean);
|
|
283
|
+
return lines.slice(-limit).map(l => {
|
|
284
|
+
try { return JSON.parse(l); } catch { return null; }
|
|
285
|
+
}).filter(Boolean);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/* ======================== 共享消息 ======================== */
|
|
289
|
+
|
|
290
|
+
export function appendMessage(taskId, message) {
|
|
291
|
+
const dir = ensureDir(statePath("messages"));
|
|
292
|
+
const file = path.join(dir, `${String(taskId).replace(/[^a-zA-Z0-9._-]/g, "_")}.jsonl`);
|
|
293
|
+
const line = JSON.stringify({ at: new Date().toISOString(), ...message }) + "\n";
|
|
294
|
+
fs.appendFileSync(file, line, { mode: 0o600 });
|
|
295
|
+
return message;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
export function readMessages(taskId, limit = 100) {
|
|
299
|
+
const file = path.join(statePath("messages"), `${String(taskId).replace(/[^a-zA-Z0-9._-]/g, "_")}.jsonl`);
|
|
300
|
+
let text = "";
|
|
301
|
+
try { text = fs.readFileSync(file, "utf8"); } catch { return []; }
|
|
302
|
+
const lines = text.split("\n").filter(Boolean);
|
|
303
|
+
return lines.slice(-limit).map(l => {
|
|
304
|
+
try { return JSON.parse(l); } catch { return null; }
|
|
305
|
+
}).filter(Boolean);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/* ======================== 人工决策 ======================== */
|
|
309
|
+
|
|
310
|
+
export function readQuestions() {
|
|
311
|
+
return readJsonFile(statePath("questions.json"), { questions: [] });
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
export function writeQuestions(questions) {
|
|
315
|
+
writeJsonAtomic(statePath("questions.json"), { questions });
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export function addQuestion(question) {
|
|
319
|
+
const data = readQuestions();
|
|
320
|
+
data.questions.push(question);
|
|
321
|
+
writeQuestions(data.questions);
|
|
322
|
+
return question;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
export function updateQuestion(id, patch) {
|
|
326
|
+
const data = readQuestions();
|
|
327
|
+
let found = null;
|
|
328
|
+
data.questions = data.questions.map(q => {
|
|
329
|
+
if (q.id !== id) return q;
|
|
330
|
+
found = { ...q, ...patch };
|
|
331
|
+
return found;
|
|
332
|
+
});
|
|
333
|
+
writeQuestions(data.questions);
|
|
334
|
+
return found;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
export function listPendingQuestions() {
|
|
338
|
+
return readQuestions().questions.filter(q => q.status === "pending");
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/* ======================== 存储适配器 ======================== */
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* 把上面的模块级函数打包成对象,便于注入到调度器与协调器,
|
|
345
|
+
* 也便于测试时整体替换成假实现。
|
|
346
|
+
*/
|
|
347
|
+
export function createStore() {
|
|
348
|
+
return {
|
|
349
|
+
readConfig,
|
|
350
|
+
writeConfig,
|
|
351
|
+
readWorkspace,
|
|
352
|
+
writeWorkspace,
|
|
353
|
+
listWorkspaces,
|
|
354
|
+
readProjectFolderStore,
|
|
355
|
+
writeProjectFolderStore,
|
|
356
|
+
readTask,
|
|
357
|
+
writeTask,
|
|
358
|
+
listTasks,
|
|
359
|
+
readSessions,
|
|
360
|
+
writeSessions,
|
|
361
|
+
setSession,
|
|
362
|
+
readServiceState,
|
|
363
|
+
writeServiceState,
|
|
364
|
+
clearServiceState,
|
|
365
|
+
appendEvent,
|
|
366
|
+
readEvents,
|
|
367
|
+
appendMessage,
|
|
368
|
+
readMessages,
|
|
369
|
+
readQuestions,
|
|
370
|
+
writeQuestions,
|
|
371
|
+
addQuestion,
|
|
372
|
+
updateQuestion,
|
|
373
|
+
listPendingQuestions,
|
|
374
|
+
};
|
|
375
|
+
}
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 工作区识别:当前目录规范化、Git 信息、项目候选匹配、验证命令识别。
|
|
3
|
+
*
|
|
4
|
+
* 匹配原则:本地目录与 AgileDev 项目没有共享唯一 ID,自动识别只能给出候选,
|
|
5
|
+
* 必须由用户确认后才能绑定。绝不按 bug 标题或关键词猜项目。
|
|
6
|
+
*/
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import { execFile } from "node:child_process";
|
|
10
|
+
import { promisify } from "node:util";
|
|
11
|
+
|
|
12
|
+
const execFileAsync = promisify(execFile);
|
|
13
|
+
|
|
14
|
+
/* ======================== 目录规范化 ======================== */
|
|
15
|
+
|
|
16
|
+
/** 取真实路径(Windows 短路径/大小写/符号链接归一),失败时退回 resolve。 */
|
|
17
|
+
export function normalizeWorkspacePath(cwd) {
|
|
18
|
+
const resolved = path.resolve(cwd || process.cwd());
|
|
19
|
+
try {
|
|
20
|
+
return fs.realpathSync.native(resolved);
|
|
21
|
+
} catch {
|
|
22
|
+
try { return fs.realpathSync(resolved); } catch { return resolved; }
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function workspaceExists(dir) {
|
|
27
|
+
try { return fs.statSync(dir).isDirectory(); } catch { return false; }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/* ======================== Git 信息 ======================== */
|
|
31
|
+
|
|
32
|
+
async function git(cwd, args) {
|
|
33
|
+
try {
|
|
34
|
+
const { stdout } = await execFileAsync("git", ["-C", cwd, ...args], {
|
|
35
|
+
timeout: 8000,
|
|
36
|
+
windowsHide: true,
|
|
37
|
+
maxBuffer: 8 * 1024 * 1024,
|
|
38
|
+
});
|
|
39
|
+
// 只去掉行尾空白:porcelain 的每行以状态字母开头,首行可能是 " M path",
|
|
40
|
+
// 用 trim() 会吃掉这个前导空格,导致路径被截错一个字符。
|
|
41
|
+
return String(stdout || "").replace(/\s+$/, "");
|
|
42
|
+
} catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** 读取单个仓库的指纹。 */
|
|
48
|
+
async function readSingleRepo(dir) {
|
|
49
|
+
const remote = await git(dir, ["config", "--get", "remote.origin.url"]);
|
|
50
|
+
const head = await git(dir, ["rev-parse", "HEAD"]);
|
|
51
|
+
const status = await git(dir, ["status", "--porcelain"]);
|
|
52
|
+
const dirtyFiles = status
|
|
53
|
+
? status.split(/\r?\n/).filter(Boolean).map(l => l.slice(3).trim()).filter(Boolean)
|
|
54
|
+
: [];
|
|
55
|
+
return { remote: remote || null, head: head || null, dirtyFiles };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** 当前目录不是仓库时,找出它下面"本身就是仓库根"的一级子目录。 */
|
|
59
|
+
async function findSubRepos(cwd) {
|
|
60
|
+
let entries = [];
|
|
61
|
+
try { entries = fs.readdirSync(cwd, { withFileTypes: true }); } catch { return []; }
|
|
62
|
+
const dirs = entries
|
|
63
|
+
.filter(e => e.isDirectory() && !e.name.startsWith(".") && e.name !== "node_modules")
|
|
64
|
+
.map(e => path.join(cwd, e.name));
|
|
65
|
+
const repos = [];
|
|
66
|
+
for (const dir of dirs) {
|
|
67
|
+
const top = await git(dir, ["rev-parse", "--show-toplevel"]);
|
|
68
|
+
if (!top) continue;
|
|
69
|
+
// 只收"这个子目录自己就是仓库根"的,避免把仓库内部的普通目录当成独立仓库
|
|
70
|
+
if (normalizeWorkspacePath(top).toLowerCase() !== normalizeWorkspacePath(dir).toLowerCase()) continue;
|
|
71
|
+
repos.push(dir);
|
|
72
|
+
}
|
|
73
|
+
return repos;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* 读取工作区的 Git 指纹:remote、HEAD、脏状态。
|
|
78
|
+
*
|
|
79
|
+
* 三种形态:
|
|
80
|
+
* - 单仓库:当前目录在某个仓库内(isRepo=true)
|
|
81
|
+
* - 多仓库工作区:当前目录不是仓库,但一级子目录是(multiRepo=true),
|
|
82
|
+
* 常见于把前端/后端/H5 放在同一个项目目录下统一管理
|
|
83
|
+
* - 非 Git:两者都不成立,无 diff 保护
|
|
84
|
+
*/
|
|
85
|
+
export async function readGitInfo(cwd) {
|
|
86
|
+
const inside = await git(cwd, ["rev-parse", "--is-inside-work-tree"]);
|
|
87
|
+
if (inside === "true") {
|
|
88
|
+
const info = await readSingleRepo(cwd);
|
|
89
|
+
return {
|
|
90
|
+
isRepo: true,
|
|
91
|
+
multiRepo: false,
|
|
92
|
+
remote: info.remote,
|
|
93
|
+
head: info.head,
|
|
94
|
+
dirtyFiles: info.dirtyFiles,
|
|
95
|
+
dirty: info.dirtyFiles.length > 0,
|
|
96
|
+
repos: [{
|
|
97
|
+
path: normalizeWorkspacePath(cwd),
|
|
98
|
+
name: path.basename(cwd),
|
|
99
|
+
head: info.head,
|
|
100
|
+
remote: info.remote,
|
|
101
|
+
dirtyFiles: info.dirtyFiles,
|
|
102
|
+
}],
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const subPaths = await findSubRepos(cwd);
|
|
107
|
+
if (subPaths.length) {
|
|
108
|
+
const repos = [];
|
|
109
|
+
for (const p of subPaths) {
|
|
110
|
+
const r = await readSingleRepo(p);
|
|
111
|
+
repos.push({
|
|
112
|
+
path: normalizeWorkspacePath(p),
|
|
113
|
+
name: path.basename(p),
|
|
114
|
+
head: r.head,
|
|
115
|
+
remote: r.remote,
|
|
116
|
+
dirtyFiles: r.dirtyFiles,
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
return {
|
|
120
|
+
isRepo: false,
|
|
121
|
+
multiRepo: true,
|
|
122
|
+
remote: repos.find(r => r.remote)?.remote || null,
|
|
123
|
+
head: null,
|
|
124
|
+
// 多仓库时统一成"相对工作区"的路径,与 worker 报告和基线比较时不会串
|
|
125
|
+
dirtyFiles: repos.flatMap(r => r.dirtyFiles.map(f => `${r.name}/${f}`)),
|
|
126
|
+
dirty: repos.some(r => r.dirtyFiles.length > 0),
|
|
127
|
+
repos,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
return { isRepo: false, multiRepo: false, remote: null, head: null, dirtyFiles: [], dirty: false, repos: [] };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Git remote 归一化指纹:跨写法比较。
|
|
136
|
+
* git@host:team/x.git 与 https://host/team/x 必须得到同一个键,
|
|
137
|
+
* 否则目录绑定会被误判为"已过期"。
|
|
138
|
+
*/
|
|
139
|
+
export function normalizeRemote(remote) {
|
|
140
|
+
if (!remote) return null;
|
|
141
|
+
let s = String(remote).trim();
|
|
142
|
+
s = s.replace(/^[a-zA-Z]+:\/\//, ""); // 去掉协议
|
|
143
|
+
s = s.replace(/^[^/@]+@/, ""); // 去掉 user@
|
|
144
|
+
s = s.replace(/:/g, "/"); // scp 风格的冒号 → 斜杠
|
|
145
|
+
s = s.replace(/\.git$/i, ""); // 去掉 .git
|
|
146
|
+
s = s.replace(/\/+$/, "");
|
|
147
|
+
return s.toLowerCase();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/* ======================== 目录特征 ======================== */
|
|
151
|
+
|
|
152
|
+
/** 目录名、package.json 名称等可读特征,用于给项目候选排序。 */
|
|
153
|
+
export function readDirFingerprints(cwd) {
|
|
154
|
+
const dirName = path.basename(cwd).toLowerCase();
|
|
155
|
+
const names = new Set([dirName]);
|
|
156
|
+
try {
|
|
157
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(cwd, "package.json"), "utf8"));
|
|
158
|
+
if (typeof pkg?.name === "string" && pkg.name.trim()) names.add(pkg.name.trim().toLowerCase());
|
|
159
|
+
} catch { /* 没有 package.json 或不可读 */ }
|
|
160
|
+
try {
|
|
161
|
+
const pom = fs.readFileSync(path.join(cwd, "pom.xml"), "utf8");
|
|
162
|
+
const m = pom.match(/<artifactId>([^<]+)<\/artifactId>/);
|
|
163
|
+
if (m?.[1]) names.add(m[1].trim().toLowerCase());
|
|
164
|
+
} catch { /* 非 Maven 项目 */ }
|
|
165
|
+
return [...names];
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/* ======================== 项目候选匹配 ======================== */
|
|
169
|
+
|
|
170
|
+
function normalizeToken(s) {
|
|
171
|
+
return String(s || "").toLowerCase().replace(/[^a-z0-9一-龥]+/g, "");
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* 为每个敏捷项目算匹配分并给出依据。
|
|
176
|
+
* 返回按分数降序排列的候选;分数 0 的项目不作为候选。
|
|
177
|
+
*/
|
|
178
|
+
export function matchProjects(projects, { fingerprints = [], remote = null } = {}) {
|
|
179
|
+
const tokens = fingerprints.map(normalizeToken).filter(Boolean);
|
|
180
|
+
const remoteKey = normalizeRemote(remote);
|
|
181
|
+
const remoteParts = remoteKey ? remoteKey.split(/[\/:]/).filter(Boolean) : [];
|
|
182
|
+
|
|
183
|
+
const scored = [];
|
|
184
|
+
for (const p of projects || []) {
|
|
185
|
+
const projectName = String(p?.name || "");
|
|
186
|
+
const pn = normalizeToken(projectName);
|
|
187
|
+
if (!pn) continue;
|
|
188
|
+
const reasons = [];
|
|
189
|
+
let score = 0;
|
|
190
|
+
|
|
191
|
+
for (const t of tokens) {
|
|
192
|
+
if (!t) continue;
|
|
193
|
+
if (pn === t) { score += 60; reasons.push("目录/包名与项目名完全一致"); break; }
|
|
194
|
+
if (pn.includes(t) || t.includes(pn)) { score += 35; reasons.push("目录/包名与项目名部分匹配"); break; }
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
if (remoteKey && remoteParts.length) {
|
|
198
|
+
const last = remoteParts[remoteParts.length - 1];
|
|
199
|
+
if (last && pn.includes(normalizeToken(last))) {
|
|
200
|
+
score += 25;
|
|
201
|
+
reasons.push("Git remote 仓库名与项目名相关");
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (score > 0) scored.push({ projectId: p.id, name: projectName, status: p.status ?? null, score, reasons: [...new Set(reasons)] });
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
scored.sort((a, b) => b.score - a.score || String(a.name).localeCompare(String(b.name)));
|
|
209
|
+
return scored;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/* ======================== 验证命令识别 ======================== */
|
|
213
|
+
|
|
214
|
+
function readPackageJson(cwd) {
|
|
215
|
+
try { return JSON.parse(fs.readFileSync(path.join(cwd, "package.json"), "utf8")); } catch { return null; }
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* 猜测独立验证命令。返回 null 表示无法识别——此时不阻塞启动,
|
|
220
|
+
* 只是不能自动转待验证,需要人工补充。
|
|
221
|
+
*/
|
|
222
|
+
export function detectVerifyCommand(cwd) {
|
|
223
|
+
const pkg = readPackageJson(cwd);
|
|
224
|
+
if (pkg?.scripts) {
|
|
225
|
+
const scripts = pkg.scripts;
|
|
226
|
+
if (typeof scripts.test === "string" && scripts.test.trim()) {
|
|
227
|
+
const isWatch = /(--watch|-w\b|jest --watch|vitest(?!.*run))/.test(scripts.test);
|
|
228
|
+
if (!isWatch) {
|
|
229
|
+
const pkgManager = detectPackageManager(cwd);
|
|
230
|
+
return `${pkgManager} test`;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
if (typeof scripts["test:ci"] === "string" && scripts["test:ci"].trim()) {
|
|
234
|
+
return `${detectPackageManager(cwd)} run test:ci`;
|
|
235
|
+
}
|
|
236
|
+
// 绝不自动回退到 build / tsc / vue-tsc:全量编译和类型检查会拖垮机器,
|
|
237
|
+
// 这类命令只能由用户显式配置,且执行前仍会被 scheduler 的禁止清单拦下。
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
try {
|
|
241
|
+
const mk = fs.readFileSync(path.join(cwd, "Makefile"), "utf8");
|
|
242
|
+
if (/^test\s*:/m.test(mk)) return "make test";
|
|
243
|
+
} catch { /* 没有 Makefile */ }
|
|
244
|
+
|
|
245
|
+
try {
|
|
246
|
+
fs.statSync(path.join(cwd, "pyproject.toml"));
|
|
247
|
+
return "python -m pytest";
|
|
248
|
+
} catch { /* 不是 Python 项目 */ }
|
|
249
|
+
|
|
250
|
+
try {
|
|
251
|
+
fs.statSync(path.join(cwd, "go.mod"));
|
|
252
|
+
return "go test ./...";
|
|
253
|
+
} catch { /* 不是 Go 项目 */ }
|
|
254
|
+
|
|
255
|
+
try {
|
|
256
|
+
fs.statSync(path.join(cwd, "pom.xml"));
|
|
257
|
+
return "mvn -q test";
|
|
258
|
+
} catch { /* 不是 Maven 项目 */ }
|
|
259
|
+
|
|
260
|
+
return null;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export function detectPackageManager(cwd) {
|
|
264
|
+
if (fs.existsSync(path.join(cwd, "pnpm-lock.yaml"))) return "pnpm";
|
|
265
|
+
if (fs.existsSync(path.join(cwd, "yarn.lock"))) return "yarn";
|
|
266
|
+
if (fs.existsSync(path.join(cwd, "bun.lockb")) || fs.existsSync(path.join(cwd, "bun.lock"))) return "bun";
|
|
267
|
+
return "npm";
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/* ======================== 候选生成 ======================== */
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* 汇总当前目录的全部可识别特征,供上层生成候选或判定"无法识别"。
|
|
274
|
+
*/
|
|
275
|
+
export async function inspectWorkspace(cwd) {
|
|
276
|
+
const gitInfo = await readGitInfo(cwd);
|
|
277
|
+
const base = readDirFingerprints(cwd);
|
|
278
|
+
// 多仓库工作区把子仓库目录名也当作特征,方便匹配项目
|
|
279
|
+
const subNames = gitInfo.multiRepo ? gitInfo.repos.map(r => r.name.toLowerCase()) : [];
|
|
280
|
+
const fingerprints = [...new Set([...base, ...subNames])];
|
|
281
|
+
const remoteKey = gitInfo.multiRepo
|
|
282
|
+
? (gitInfo.repos.map(r => normalizeRemote(r.remote)).filter(Boolean).sort().join("|") || null)
|
|
283
|
+
: normalizeRemote(gitInfo.remote);
|
|
284
|
+
return {
|
|
285
|
+
path: cwd,
|
|
286
|
+
exists: workspaceExists(cwd),
|
|
287
|
+
isRepo: gitInfo.isRepo,
|
|
288
|
+
multiRepo: !!gitInfo.multiRepo,
|
|
289
|
+
repos: gitInfo.repos || [],
|
|
290
|
+
remote: gitInfo.remote,
|
|
291
|
+
remoteKey,
|
|
292
|
+
head: gitInfo.head,
|
|
293
|
+
dirty: gitInfo.dirty,
|
|
294
|
+
dirtyFiles: gitInfo.dirtyFiles,
|
|
295
|
+
fingerprints,
|
|
296
|
+
recognizable: gitInfo.isRepo || gitInfo.multiRepo || fingerprints.length > 1,
|
|
297
|
+
};
|
|
298
|
+
}
|