agiledev-cli 0.1.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +300 -173
  2. package/SKILL.md +114 -98
  3. package/adev.js +1319 -1285
  4. package/autofix/agents/antigravity.js +379 -0
  5. package/autofix/agents/claude.js +147 -0
  6. package/autofix/agents/codex.js +179 -0
  7. package/autofix/agents/exec.js +230 -0
  8. package/autofix/agents/index.js +400 -0
  9. package/autofix/agents/opencode.js +233 -0
  10. package/autofix/agents/pi.js +247 -0
  11. package/autofix/agiledev.js +98 -0
  12. package/autofix/bridge.js +371 -0
  13. package/autofix/cli.js +712 -0
  14. package/autofix/context.js +152 -0
  15. package/autofix/conversation.js +302 -0
  16. package/autofix/coordinator.js +2892 -0
  17. package/autofix/git.js +459 -0
  18. package/autofix/policy.js +230 -0
  19. package/autofix/profile.js +578 -0
  20. package/autofix/public/app.js +3668 -0
  21. package/autofix/public/i18n-id.js +282 -0
  22. package/autofix/public/index.html +32 -0
  23. package/autofix/public/style.css +2463 -0
  24. package/autofix/queue.js +146 -0
  25. package/autofix/scheduler.js +994 -0
  26. package/autofix/scope.js +32 -0
  27. package/autofix/service.js +1940 -0
  28. package/autofix/store.js +375 -0
  29. package/autofix/workspace.js +298 -0
  30. package/autofix/worktree.js +379 -0
  31. package/docs/autofix-design.md +801 -0
  32. package/docs/autofix-profiles.example.json +65 -0
  33. package/imgs/Bug/350/247/243/345/206/263/345/244/207/346/263/250.png +0 -0
  34. package/imgs/logo.png +0 -0
  35. package/imgs//344/277/256/346/224/271Bug/347/212/266/346/200/201.png +0 -0
  36. package/imgs//345/270/256/346/210/221/344/277/256/345/244/215Bug-20260922-010.png +0 -0
  37. package/imgs//346/237/245/347/234/213/345/271/266/345/210/206/346/236/220/351/234/200/346/261/202/346/226/207/346/241/243.png +0 -0
  38. package/imgs//347/234/213/344/270/200/344/270/213/346/210/221/347/216/260/345/234/250/346/234/211/345/223/252/344/272/233/345/274/200/345/217/221/344/273/273/345/212/241.png +0 -0
  39. package/imgs//347/234/213/344/270/200/344/270/213/346/210/221/350/277/230/346/234/211/345/223/252/344/272/233Bug/346/234/252/350/247/243/345/206/263.png +0 -0
  40. package/package.json +39 -36
package/adev.js CHANGED
@@ -1,1285 +1,1319 @@
1
- #!/usr/bin/env node
2
- /**
3
- * agiledev-cli — AgileDev 敏捷研发管理系统 CLI(命令名:adev)
4
- *
5
- * 数据来源:/api/v1/*(Bearer Token 鉴权)。单文件、零第三方依赖(Node >= 18)。
6
- *
7
- * 资源与常用命令:
8
- * adev me | members list | projects | dashboard | kanban
9
- * adev bugs list|show|create|update|claim|resolve|reject|reopen|close|transition|comments|comment|stats
10
- * adev reqs list|show|create|update|set-test-date|data-sources|assign-iteration|shelve|unshelve|reactivate|revoke|delete
11
- * adev tasks list|show|create|update|delete|batch
12
- * adev versions list|show|stats|start|start-testing|complete|accept|release
13
- * adev incidents list|show|create|update|claim|resolve|reject|reopen|transition|delete
14
- * adev tests list|show|cases|transition
15
- * adev kb list|show|categories|annotations
16
- * adev weekly list|show|draft
17
- *
18
- * 所有写操作均支持 --data '<json>' 或 --json-file <path> 直接透传请求体。
19
- */
20
-
21
- import fs from "node:fs";
22
- import os from "node:os";
23
- import path from "node:path";
24
- import { createRequire } from "node:module";
25
- import { fileURLToPath } from "node:url";
26
-
27
- const require = createRequire(import.meta.url);
28
- const { version: VERSION } = require("./package.json");
29
-
30
- /* ======================== 常量 ======================== */
31
-
32
- const DEFAULT_BASE_URL = "https://scrum.chitem.com";
33
- const DEFAULT_PAGE_SIZE = 20;
34
- const MEMBER_PAGE_SIZE = 100;
35
- const ASSIGNEE_FILTER_PAGE_SIZE = 200;
36
- const RESOLVE_SEARCH_PAGE_SIZE = 50;
37
- const MAX_PARALLEL_DOWNLOADS = 5;
38
- const REQUEST_TIMEOUT_MS = 30000;
39
-
40
- const CONFIG_CANDIDATES = [
41
- path.join(os.homedir(), ".agiledev-cli.json"),
42
- path.join(process.cwd(), "adev.config.json"),
43
- ];
44
-
45
- /* ======================== 错误 ======================== */
46
-
47
- class AdevError extends Error {
48
- constructor(msg) {
49
- super(msg);
50
- this.name = "AdevError";
51
- }
52
- }
53
-
54
- function die(msg) {
55
- throw new AdevError(msg);
56
- }
57
-
58
- /* ======================== 配置 ======================== */
59
-
60
- function normalizeConfig(cfg) {
61
- const next = { baseURL: DEFAULT_BASE_URL, token: "", ...(cfg || {}) };
62
- let base = String(next.baseURL || DEFAULT_BASE_URL).trim().replace(/\/+$/, "");
63
- base = base.replace(/\/api\/v1$/i, "");
64
- next.baseURL = base || DEFAULT_BASE_URL;
65
- next.token = String(next.token ?? "").trim();
66
- return next;
67
- }
68
-
69
- function loadConfig() {
70
- let fileCfg = {};
71
- for (const p of CONFIG_CANDIDATES) {
72
- try {
73
- const parsed = JSON.parse(fs.readFileSync(p, "utf8"));
74
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
75
- fileCfg = parsed;
76
- break;
77
- }
78
- } catch { /* 下一个候选 */ }
79
- }
80
- const env = {};
81
- if (process.env.ADEV_BASE_URL) env.baseURL = process.env.ADEV_BASE_URL;
82
- if (process.env.ADEV_TOKEN) env.token = process.env.ADEV_TOKEN;
83
- return normalizeConfig({ ...fileCfg, ...env });
84
- }
85
-
86
- /** 在已有配置上打补丁。unset 中的键会被删除,避免登录覆盖掉无关字段。 */
87
- function applyConfigPatch(existing, patch, unset = []) {
88
- const next = existing && typeof existing === "object" && !Array.isArray(existing) ? { ...existing } : {};
89
- Object.assign(next, patch);
90
- for (const k of unset) delete next[k];
91
- if (!next.baseURL) next.baseURL = DEFAULT_BASE_URL;
92
- return next;
93
- }
94
-
95
- function readConfigFile(p) {
96
- try {
97
- const parsed = JSON.parse(fs.readFileSync(p, "utf8"));
98
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
99
- } catch { /* 新文件或损坏 */ }
100
- return {};
101
- }
102
-
103
- function writeConfigFile(p, data) {
104
- const text = JSON.stringify(data, null, 2) + "\n";
105
- const tmp = `${p}.${process.pid}.tmp`;
106
- try {
107
- fs.writeFileSync(tmp, text, { mode: 0o600 });
108
- try { fs.chmodSync(tmp, 0o600); } catch { /* Windows 不支持 chmod */ }
109
- fs.renameSync(tmp, p);
110
- } catch (e) {
111
- try { fs.unlinkSync(tmp); } catch { /* 忽略残留临时文件 */ }
112
- die(`写入配置文件失败 (${p}):${e.message}`);
113
- }
114
- }
115
-
116
- function updateConfig(patch, unset = []) {
117
- const p = CONFIG_CANDIDATES[0];
118
- const next = applyConfigPatch(readConfigFile(p), patch, unset);
119
- writeConfigFile(p, next);
120
- return p;
121
- }
122
-
123
- function saveToken(token) {
124
- // 保留 username,方便之后 adev login 回车沿用;authType 标明当前凭证是 API Key
125
- const p = updateConfig({ token, authType: "token" });
126
- console.log(`已保存到 ${p}`);
127
- }
128
-
129
- function isPasswordSession(cfg) {
130
- return cfg.authType === "login" || (cfg.authType !== "token" && !!cfg.username);
131
- }
132
-
133
- function authLabel(cfg) {
134
- return isPasswordSession(cfg) ? `账号密码登录(${cfg.username})` : "API Key";
135
- }
136
-
137
- /** 登录成功后写回内存中的 cfg。随后的 /auth/me 必须用新 token,不能沿用加载时的旧凭证。 */
138
- function withLogin(cfg, token, username) {
139
- return { ...cfg, token, username, authType: "login" };
140
- }
141
-
142
- /* ======================== HTTP ======================== */
143
-
144
- let ME_CACHE = null;
145
-
146
- function isTimeoutError(e) {
147
- return e?.name === "TimeoutError" || e?.name === "AbortError";
148
- }
149
-
150
- function networkHint(e, cfg) {
151
- if (isTimeoutError(e)) {
152
- return `请求超时(${REQUEST_TIMEOUT_MS / 1000}s):请确认已接入公司网络/VPN,且 ${cfg.baseURL} 可达。`;
153
- }
154
- const code = e.cause?.code ? ` (${e.cause.code})` : "";
155
- return `网络请求失败:${e.message}${code}\n请确认已接入公司网络/VPN,且 ${cfg.baseURL} 可达。`;
156
- }
157
-
158
- async function request(cfg, method, resPath, { params, body } = {}) {
159
- const qs = params
160
- ? "?" + Object.entries(params)
161
- .filter(([, v]) => v !== undefined && v !== null && v !== "")
162
- .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&")
163
- : "";
164
- const url = `${cfg.baseURL}/api/v1${resPath}${qs}`;
165
- let res;
166
- try {
167
- // Node 内置 fetch 默认不走 HTTP_PROXY,正好直连内网
168
- res = await fetch(url, {
169
- method,
170
- headers: { Authorization: `Bearer ${cfg.token}`, ...(body ? { "Content-Type": "application/json" } : {}) },
171
- body: body ? JSON.stringify(body) : undefined,
172
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
173
- });
174
- } catch (e) {
175
- die(networkHint(e, cfg));
176
- }
177
- if (res.status === 401) {
178
- die(isPasswordSession(cfg)
179
- ? `登录已过期,请重新执行 \`adev login\`(账号 ${cfg.username})`
180
- : "鉴权失败(401):API Key 无效或已过期,请执行 `adev config set-token <token>` 或 `adev login`(账号密码登录)");
181
- }
182
- if (res.status === 403) die(`权限不足(403):无权访问 ${resPath}`);
183
- if (res.status === 404) die(`资源不存在(404):${resPath}`);
184
- if (res.status >= 500) die(`服务器错误(${res.status}):${method} ${resPath},请稍后重试`);
185
- let payload;
186
- try { payload = await res.json(); } catch { die(`响应不是 JSON (HTTP ${res.status}):${method} ${url}`); }
187
- if (!payload || typeof payload !== "object") die(`响应不是 JSON 对象 (HTTP ${res.status}):${method} ${url}`);
188
- if (payload.code !== 200) {
189
- const hint = payload.code === 40300 ? "\n(当前 API Key 无此模块权限,请到平台为该 Key 分配权限)" : "";
190
- const bodyText = body ? `\n body: ${JSON.stringify(body).slice(0, 500)}` : "";
191
- die(`接口错误 code=${payload.code} message=${payload.message}${hint}\n ${method} ${url}${bodyText}`);
192
- }
193
- return payload.data;
194
- }
195
-
196
- const api = (cfg, p, params) => request(cfg, "GET", p, { params });
197
- const post = (cfg, p, body) => request(cfg, "POST", p, { body: body ?? {} });
198
- const put = (cfg, p, body) => request(cfg, "PUT", p, { body: body ?? {} });
199
- const del = (cfg, p) => request(cfg, "DELETE", p);
200
-
201
- async function me(cfg) {
202
- if (!ME_CACHE) ME_CACHE = await api(cfg, "/auth/me");
203
- return ME_CACHE;
204
- }
205
-
206
- /** 把 "me" 解析为当前用户 id */
207
- async function resolveUserId(cfg, v) {
208
- if (v === undefined || v === null || v === "" || v === false) return undefined;
209
- if (v === "me") return (await me(cfg)).id;
210
- return v;
211
- }
212
-
213
- function requireToken(cfg) {
214
- if (!cfg.token) die("未配置凭证:请执行 `adev login`(账号密码)或 `adev config set-token <token>`");
215
- }
216
-
217
- /* ======================== auth(登录) ======================== */
218
-
219
- /**
220
- * 把一段终端输入切成完整行。
221
- * raw 模式下 Windows 回车常常是 \\r\\n,必须把紧跟 \\r 的 \\n 吃掉,否则一行会被读成两行。
222
- */
223
- function feedInput(state, chunk) {
224
- const lines = [];
225
- for (const c of chunk) {
226
- if (c === "\u0003") { state.interrupted = true; break; }
227
- if (c === "\r") {
228
- lines.push(state.buf);
229
- state.buf = "";
230
- state.skipLf = true;
231
- } else if (c === "\n") {
232
- if (state.skipLf) state.skipLf = false;
233
- else { lines.push(state.buf); state.buf = ""; }
234
- } else if (state.raw && (c === "\u007f" || c === "\b")) {
235
- state.skipLf = false;
236
- state.buf = state.buf.slice(0, -1);
237
- } else {
238
- state.skipLf = false;
239
- state.buf += c;
240
- }
241
- }
242
- return lines;
243
- }
244
-
245
- /** 基于 stdin 事件流的行读取器(TTY / 管道 / IDE 终端下行为一致) */
246
- function createLineReader() {
247
- const stdin = process.stdin;
248
- stdin.setEncoding("utf8");
249
- stdin.resume();
250
- const state = { buf: "", skipLf: false, raw: false, interrupted: false };
251
- const queue = [];
252
- const waiters = [];
253
- const settle = line => { if (waiters.length) waiters.shift()(line); else queue.push(line); };
254
- stdin.on("data", chunk => {
255
- for (const line of feedInput(state, chunk)) settle(line);
256
- if (state.interrupted) {
257
- if (stdin.isTTY) { try { stdin.setRawMode(false); } catch { /* 忽略 */ } }
258
- process.stdout.write("\n");
259
- process.exit(130);
260
- }
261
- });
262
- stdin.on("end", () => { settle(state.buf); state.buf = ""; while (waiters.length) settle(""); });
263
- const nextLine = () => (queue.length ? Promise.resolve(queue.shift()) : new Promise(r => waiters.push(r)));
264
- return {
265
- ask(prompt) { process.stdout.write(prompt); return nextLine(); },
266
- async askHidden(prompt) {
267
- process.stdout.write(prompt);
268
- const isTTY = !!stdin.isTTY;
269
- if (isTTY) { stdin.setRawMode(true); state.raw = true; }
270
- try {
271
- return queue.length ? queue.shift() : await nextLine();
272
- } finally {
273
- if (isTTY) { stdin.setRawMode(false); state.raw = false; }
274
- process.stdout.write("\n");
275
- }
276
- },
277
- };
278
- }
279
-
280
- async function loginCmd(cfg, o) {
281
- const io = createLineReader();
282
- const saved = cfg.username || "";
283
- const raw0 = o._[0] !== undefined ? String(o._[0]) : await io.ask(`账号${saved ? `(回车使用 ${saved})` : ""}: `);
284
- const username = raw0.trim() || saved;
285
- if (!username) die("账号不能为空");
286
- const password = await io.askHidden("密码: ");
287
- if (!password) die("密码不能为空");
288
-
289
- let res;
290
- try {
291
- res = await fetch(`${cfg.baseURL}/api/v1/auth/login`, {
292
- method: "POST",
293
- headers: { "Content-Type": "application/json" },
294
- body: JSON.stringify({ username, password }),
295
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
296
- });
297
- } catch (e) {
298
- die(networkHint(e, cfg));
299
- }
300
- let payload;
301
- try { payload = await res.json(); } catch { die(`登录响应异常 (HTTP ${res.status})`); }
302
- if (!payload || typeof payload !== "object" || payload.code !== 200) {
303
- die(`登录失败:${payload?.message || payload?.detail || "HTTP " + res.status}`);
304
- }
305
- const token = payload.data?.access_token;
306
- if (!token) die("登录响应中未找到 access_token 字段,请联系管理员确认接口版本");
307
-
308
- const savedPath = updateConfig({ baseURL: cfg.baseURL, token, username, authType: "login" });
309
- Object.assign(cfg, withLogin(cfg, token, username));
310
- ME_CACHE = null;
311
- let u;
312
- try {
313
- u = await me(cfg);
314
- } catch (e) {
315
- console.log(`凭证已保存到 ${savedPath}`);
316
- throw e;
317
- }
318
- console.log(`✓ 登录成功:${u.nickname || u.real_name || u.username}(${u.role || "未知角色"})`);
319
- console.log(`凭证已保存到 ${savedPath}`);
320
- }
321
-
322
- async function logoutCmd(cfg) {
323
- // 服务端使 token 失效;已过期或网络失败不阻塞本地清理
324
- if (cfg.token) {
325
- try {
326
- await fetch(`${cfg.baseURL}/api/v1/auth/logout`, {
327
- method: "POST",
328
- headers: { Authorization: `Bearer ${cfg.token}` },
329
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
330
- });
331
- } catch { /* 忽略 */ }
332
- }
333
- updateConfig({ baseURL: cfg.baseURL || DEFAULT_BASE_URL }, ["token", "username", "authType"]);
334
- console.log("已退出登录并清除本地凭证");
335
- }
336
-
337
- /* ======================== setup(一键安装 AI skill) ======================== */
338
-
339
- async function setupCmd(cfg) {
340
- const pkgDir = path.dirname(fileURLToPath(import.meta.url));
341
- const skills = [
342
- { src: path.join(pkgDir, "SKILL.md"), name: "adev" },
343
- { src: path.join(pkgDir, "skills", "adev-login", "SKILL.md"), name: "adev-login" },
344
- ];
345
- for (const s of skills) {
346
- if (!fs.existsSync(s.src)) die(`包内缺少 ${s.src},安装包可能不完整,请重新 npm install -g agiledev-cli`);
347
- }
348
-
349
- // 统一安装到用户级共享目录 ~/.agents/skills:一份技能,各 AI 助手(ZCode 等)通用,不重复散落
350
- const destRoot = path.join(os.homedir(), ".agents", "skills");
351
- for (const s of skills) {
352
- const dest = path.join(destRoot, s.name, "SKILL.md");
353
- fs.mkdirSync(path.dirname(dest), { recursive: true });
354
- fs.copyFileSync(s.src, dest);
355
- console.log(`✓ 已安装 ${dest}`);
356
- }
357
- console.log("\n技能统一安装在用户级共享目录 ~/.agents/skills,各 AI 助手共用这一份。");
358
- console.log(cfg.token
359
- ? "凭证已配置。新开一个 AI 会话即可说「看看测试提了哪些 bug」「帮我登录敏捷系统」等指令。"
360
- : "下一步:执行 `adev login` 登录敏捷系统(账号密码即网页登录账号)。");
361
- }
362
-
363
- /* ======================== 工具函数 ======================== */
364
-
365
- function displayWidth(s) {
366
- let w = 0;
367
- for (const ch of String(s)) {
368
- const c = ch.codePointAt(0);
369
- w += (c >= 0x1100 && (c <= 0x115f || c === 0x2329 || c === 0x232a ||
370
- (c >= 0x2e80 && c <= 0xa4cf && c !== 0x303f) || (c >= 0xac00 && c <= 0xd7a3) ||
371
- (c >= 0xf900 && c <= 0xfaff) || (c >= 0xfe30 && c <= 0xfe6f) ||
372
- (c >= 0xff00 && c <= 0xff60) || (c >= 0xffe0 && c <= 0xffe6))) ? 2 : 1;
373
- }
374
- return w;
375
- }
376
-
377
- function trunc(s, width) {
378
- s = String(s ?? "");
379
- if (displayWidth(s) <= width) return s;
380
- let out = "", w = 0;
381
- for (const ch of s) {
382
- const cw = displayWidth(ch);
383
- if (w + cw > width - 1) break;
384
- out += ch; w += cw;
385
- }
386
- return out + "…";
387
- }
388
-
389
- function padCell(s, width) {
390
- s = trunc(s, width);
391
- return s + " ".repeat(Math.max(0, width - displayWidth(s)));
392
- }
393
-
394
- function renderTable(headers, widths, rows) {
395
- console.log(headers.map((h, i) => padCell(h, widths[i])).join(" "));
396
- for (const r of rows) console.log(r.map((c, i) => padCell(c, widths[i])).join(" "));
397
- }
398
-
399
- const BUG_STATUS_ZH = {
400
- Pending: "待处理", InProgress: "处理中", ToVerify: "待验证", Reopened: "重新打开",
401
- Rejected: "已拒绝", Closed: "已关闭", Released: "已发布",
402
- };
403
- const RESOLUTION_ZH = {
404
- fixed: "已修复", wontfix: "不修复", duplicate: "重复提交",
405
- cannot_reproduce: "无法复现", by_design: "设计如此", later: "后续版本",
406
- };
407
- const fmtDate = (s) => (s ? String(s).replace("T", " ").slice(0, 16) : "");
408
- const printJson = (data) => console.log(JSON.stringify(data, null, 2));
409
-
410
- function pageNum(v, fallback) {
411
- const n = parseInt(v, 10);
412
- return Number.isFinite(n) && n > 0 ? n : fallback;
413
- }
414
-
415
- function asItems(data) {
416
- if (Array.isArray(data)) return data;
417
- if (Array.isArray(data?.items)) return data.items;
418
- return [];
419
- }
420
-
421
- function safeCodePoint(c, fallback) {
422
- return Number.isInteger(c) && c > 0 && c <= 0x10ffff ? String.fromCodePoint(c) : fallback;
423
- }
424
-
425
- function htmlToText(html) {
426
- if (!html) return "(空)";
427
- return String(html)
428
- .replace(/<img[^>]*src="([^"]*)"[^>]*>/gi, "\n[图片: $1]\n")
429
- .replace(/<br\s*\/?>/gi, "\n")
430
- .replace(/<\/(p|div|li|h[1-6]|tr)>/gi, "\n")
431
- .replace(/<[^>]+>/g, "")
432
- .replace(/&#(\d+);/g, (m, n) => safeCodePoint(Number(n), m))
433
- .replace(/&#x([0-9a-f]+);/gi, (m, h) => safeCodePoint(parseInt(h, 16), m))
434
- .replace(/&nbsp;/g, " ")
435
- .replace(/&lt;/g, "<")
436
- .replace(/&gt;/g, ">")
437
- .replace(/&quot;/g, '"')
438
- .replace(/&#39;|&apos;/g, "'")
439
- .replace(/&amp;/g, "&")
440
- .replace(/\n{3,}/g, "\n\n")
441
- .trim();
442
- }
443
-
444
- const extractImages = (html) =>
445
- [...String(html || "").matchAll(/<img[^>]*src="([^"]*)"[^>]*>/gi)].map(m => m[1]).filter(Boolean);
446
-
447
- function resolveAssetUrl(base, raw) {
448
- if (/^https?:\/\//i.test(raw)) return raw;
449
- if (raw.startsWith("/")) return base + raw;
450
- return `${base}/${raw}`;
451
- }
452
-
453
- function imageExt(url) {
454
- try {
455
- const pathname = new URL(url, "https://placeholder.local").pathname;
456
- const m = pathname.match(/\.(png|jpe?g|gif|webp|bmp)$/i);
457
- return m ? m[1].toLowerCase() : "png";
458
- } catch {
459
- return "png";
460
- }
461
- }
462
-
463
- async function downloadImages(cfg, htmlFields, dir) {
464
- const urls = [...new Set(htmlFields.flatMap(extractImages))].filter(Boolean);
465
- if (!urls.length) return [];
466
- fs.mkdirSync(dir, { recursive: true });
467
- const saved = [];
468
- for (let start = 0; start < urls.length; start += MAX_PARALLEL_DOWNLOADS) {
469
- const batch = urls.slice(start, start + MAX_PARALLEL_DOWNLOADS);
470
- const results = await Promise.allSettled(batch.map(async (raw, j) => {
471
- const i = start + j;
472
- const u = resolveAssetUrl(cfg.baseURL, raw);
473
- const res = await fetch(u, {
474
- headers: { Authorization: `Bearer ${cfg.token}` },
475
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
476
- });
477
- if (!res.ok) throw new Error(`${u} HTTP ${res.status}`);
478
- const buf = Buffer.from(await res.arrayBuffer());
479
- const file = path.join(dir, `img${i + 1}.${imageExt(u)}`);
480
- await fs.promises.writeFile(file, buf);
481
- return { src: raw, file };
482
- }));
483
- for (const r of results) {
484
- if (r.status === "fulfilled") saved.push(r.value);
485
- else console.error(` (图片下载失败: ${r.reason?.message || r.reason})`);
486
- }
487
- }
488
- return saved;
489
- }
490
-
491
- function printSavedImages(images) {
492
- if (!images.length) return;
493
- console.log(`\n== 截图(已下载到本地,可直接查看)==`);
494
- images.forEach(i => console.log(` ${i.file} <- ${i.src}`));
495
- }
496
-
497
- function imageDir(o, kind, id) {
498
- return o.imagesDir || path.join(os.tmpdir(), "agiledev-cli", "images", `${kind}-${id}`);
499
- }
500
-
501
- async function loadImages(cfg, o, kind, id, fields) {
502
- if (o.noImages) return [];
503
- return downloadImages(cfg, fields, imageDir(o, kind, id));
504
- }
505
-
506
- const SKIP_DETAIL_KEYS = new Set(["id", "code", "title"]);
507
-
508
- function printLooseFields(obj) {
509
- for (const k of Object.keys(obj)) {
510
- if (SKIP_DETAIL_KEYS.has(k)) continue;
511
- const v = obj[k];
512
- if (v === null || v === undefined || v === "" || typeof v === "object") continue;
513
- if (typeof v === "string" && /[<>]|static\/uploads/.test(v)) console.log(`\n== ${k} ==\n${htmlToText(v)}`);
514
- else console.log(`${k}: ${v}`);
515
- }
516
- }
517
-
518
- function printTotal(total, items, nameFilter) {
519
- const n = total ?? items.length;
520
- console.log(`共 ${n} 条${nameFilter ? `(本地过滤后 ${items.length} 条)` : ""}\n`);
521
- }
522
-
523
- /* ======================== 参数解析 ======================== */
524
-
525
- /** kebab-case → camelCase(如 --json-file → jsonFile) */
526
- const kebabToCamel = (s) => s.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
527
- const BOOLEAN_FLAGS = new Set(["json", "yes", "force", "mine", "no-images"]);
528
-
529
- function parseArgs(argv) {
530
- const opts = { _: [] };
531
- for (let i = 0; i < argv.length; i++) {
532
- const a = argv[i];
533
- if (a.startsWith("--")) {
534
- const raw = a.slice(2);
535
- const key = kebabToCamel(raw);
536
- if (BOOLEAN_FLAGS.has(raw)) { opts[key] = true; continue; }
537
- if (i + 1 >= argv.length || argv[i + 1].startsWith("--")) {
538
- die(`选项 ${a} 需要一个值,例如: ${a} <value>`);
539
- }
540
- opts[key] = argv[++i];
541
- } else opts._.push(a);
542
- }
543
- return opts;
544
- }
545
-
546
- function parseJson(text, label) {
547
- try { return JSON.parse(text); }
548
- catch (e) { die(`${label} 不是合法 JSON:${e.message}`); }
549
- }
550
-
551
- function readTextFile(p) {
552
- try { return fs.readFileSync(p, "utf8"); }
553
- catch (e) { die(`读取 ${p} 失败:${e.message}`); }
554
- }
555
-
556
- function optionalJson(opts, label = "--data") {
557
- if (opts.data) return parseJson(opts.data, label);
558
- if (opts.jsonFile) return parseJson(readTextFile(opts.jsonFile), opts.jsonFile);
559
- return undefined;
560
- }
561
-
562
- function readJsonInput(opts, label = "--data") {
563
- const value = optionalJson(opts, label);
564
- if (value === undefined) die(`缺少 ${label} '<json>' 或 --json-file <path>`);
565
- return value;
566
- }
567
-
568
- function jsonObject(value, label = "--data") {
569
- if (value === null || typeof value !== "object" || Array.isArray(value)) die(`${label} 需要 JSON 对象`);
570
- return value;
571
- }
572
-
573
- /** 通用写操作 body:--data '<json>' / --json-file <path> / 常用 flag 收集 */
574
- function buildBody(opts, picked = []) {
575
- const raw = optionalJson(opts);
576
- const body = raw === undefined ? {} : jsonObject(raw);
577
- for (const k of picked) if (opts[k] !== undefined) body[k] = opts[k];
578
- return body;
579
- }
580
-
581
- function usage() {
582
- console.log(`adev v${VERSION} — AgileDev 敏捷研发管理系统 CLI
583
-
584
- 资源与子命令(<id> 一般也接受编号如 BUG-20260922-009;写操作通用 --data '<json>'/--json-file 透传请求体):
585
-
586
- login [账号] 账号密码登录(免 API Key,密码不回显)
587
- logout 退出登录并清除本地凭证
588
- whoami 当前登录身份
589
- setup 一键安装 Skill 文件到用户级共享目录 ~/.agents/skills
590
-
591
- me 当前登录用户(原始 JSON)
592
- members list 成员列表
593
- projects [--json] 项目列表
594
- dashboard 工作台总览
595
- kanban 效能看板总览
596
-
597
- bugs list|show|stats|comments
598
- bugs create|update 创建/编辑缺陷
599
- bugs claim|resolve|reject|reopen|close|transition 状态流转
600
- bugs comment <id> --content "xx" 发表评论
601
- bugs ai-analyze --data '{"title":...}'
602
-
603
- reqs list|show|create|update|delete
604
- reqs set-test-date <id> --date 2026-09-30 设置提测时间
605
- reqs data-sources <id> [--data ...] 查看/保存数据源对接清单
606
- reqs assign-iteration <id> --iteration 101 分配到迭代
607
- reqs shelve|unshelve|reactivate|revoke <id>
608
-
609
- tasks list|show|create|update|delete
610
- tasks batch --data '[{...},...]' 批量创建(AI 拆解用)
611
-
612
- versions list|show|stats
613
- versions start|start-testing|complete|accept <id> 迭代状态流转
614
- versions release <id> [--notes "xx"]
615
-
616
- incidents list|show|create|update|delete|claim|resolve|reject|reopen|transition
617
- tests list [--project 28] | show <id> | cases <versionId> | transition <id> --data ...
618
- kb categories | list [--category id] [--keyword x] | show <id> | annotations <docId>
619
- weekly list [--mine] | show <id> | draft [--week 2026-09-22]
620
-
621
- list 通用选项:
622
- --project <id|名称> --status <值> --severity P1 --assignee <名|id|me>
623
- --keyword <词> --page n --size n(默认 ${DEFAULT_PAGE_SIZE}) --mine(只看我的)
624
- 缺陷/需求/任务按姓名过滤时在本地匹配,并自动至少拉取 ${ASSIGNEE_FILTER_PAGE_SIZE} 条
625
- show 选项: --json --images-dir <dir> --no-images
626
-
627
- 通用选项: --version/-v --help/-h
628
-
629
- Bug/故障状态: Pending待处理 InProgress处理中 ToVerify待验证 Reopened重新打开 Rejected已拒绝 Closed已关闭(故障另有 Released已发布)
630
- Bug 解决方案: fixed已修复 wontfix不修复 duplicate重复 cannot_reproduce无法复现 by_design设计如此 later后续版本
631
- 需求状态(中文): 待处理/已准入/开发中/已发布/已拒绝/暂缓 任务状态(中文): 待开始/开发中/已暂停/已完成/不处理
632
-
633
- 配置: 环境变量 ADEV_BASE_URL/ADEV_TOKEN > ~/.agiledev-cli.json > ./adev.config.json`);
634
- }
635
-
636
- async function resolveProjectId(cfg, keyword) {
637
- if (/^\d+$/.test(keyword)) return keyword;
638
- const projects = await api(cfg, "/projects/simple");
639
- const hits = projects.filter(p => p.name.includes(keyword));
640
- if (hits.length === 1) return hits[0].id;
641
- die((hits.length === 0 ? `找不到名称包含"${keyword}"的项目` : `"${keyword}"匹配到多个项目,请用 id`) + `。候选:\n` +
642
- projects.map(p => ` ${p.id} ${p.name}`).join("\n"));
643
- }
644
-
645
- /** show 入参:纯数字当 id;否则按 code 精确匹配(走 keyword 搜索) */
646
- async function resolveResourceId(cfg, resource, input, codeField = "code") {
647
- if (!input) die("缺少 id 或编号参数");
648
- if (/^\d+$/.test(input)) return input;
649
- const data = await api(cfg, `/${resource}`, { keyword: input, page_size: RESOLVE_SEARCH_PAGE_SIZE });
650
- const hit = asItems(data).find(i => i[codeField] === input);
651
- if (!hit) die(`未找到编号为 ${input} 的记录`);
652
- return hit.id;
653
- }
654
-
655
- async function projectParam(cfg, opts) {
656
- if (opts.project) return { project_id: await resolveProjectId(cfg, String(opts.project)) };
657
- return {};
658
- }
659
-
660
- /**
661
- * 组装 list 查询。
662
- * assigneeParam 为 assignee_id 时,姓名无法传给服务端,改为放大 page_size 后本地过滤。
663
- * 故障接口的 assignee 直接接受 "me" 或姓名。
664
- */
665
- async function listQuery(cfg, o, { assigneeParam = "assignee_id", filters = ["status", "keyword"] } = {}) {
666
- const params = {
667
- page: pageNum(o.page, 1),
668
- page_size: pageNum(o.size, DEFAULT_PAGE_SIZE),
669
- ...(await projectParam(cfg, o)),
670
- };
671
- for (const key of filters) if (o[key] !== undefined) params[key] = o[key];
672
- let nameFilter = null;
673
- if (o.mine || o.assignee === "me") {
674
- params[assigneeParam] = assigneeParam === "assignee" ? "me" : (await me(cfg)).id;
675
- } else if (o.assignee !== undefined && String(o.assignee) !== "") {
676
- if (assigneeParam === "assignee" || /^\d+$/.test(String(o.assignee))) params[assigneeParam] = o.assignee;
677
- else {
678
- nameFilter = String(o.assignee);
679
- params.page_size = Math.max(params.page_size, ASSIGNEE_FILTER_PAGE_SIZE);
680
- }
681
- }
682
- return { params, nameFilter };
683
- }
684
-
685
- function applyNameFilter(items, nameFilter, field = "assignee_name") {
686
- if (!nameFilter) return items;
687
- return items.filter(i => (i[field] || "").includes(nameFilter));
688
- }
689
-
690
- /* ======================== bugs ======================== */
691
-
692
- async function bugsList(cfg, o) {
693
- const { params, nameFilter } = await listQuery(cfg, o, { filters: ["status", "severity", "keyword"] });
694
- const data = await api(cfg, "/bugs", params);
695
- const items = applyNameFilter(asItems(data), nameFilter);
696
- if (o.json) { printJson({ ...data, items }); return; }
697
- printTotal(data.total, items, nameFilter);
698
- renderTable(["id", "编号", "标题", "级别", "状态", "处理人", "报告人", "迭代", "创建"],
699
- [6, 18, 40, 5, 17, 9, 9, 22, 16],
700
- items.map(b => [b.id, b.code, b.title, b.severity || "", `${b.status}(${BUG_STATUS_ZH[b.status] || ""})`,
701
- b.assignee_name || "", b.reporter_name || "", b.version_iteration_name || "", fmtDate(b.created_at)]));
702
- }
703
-
704
- async function bugsShow(cfg, o) {
705
- const id = await resolveResourceId(cfg, "bugs", o._[0]);
706
- const b = await api(cfg, `/bugs/${id}`);
707
- if (o.json) { printJson(b); return; }
708
- const images = await loadImages(cfg, o, "bug", b.id, [b.description, b.steps_to_reproduce, b.expected_behavior, b.actual_behavior]);
709
- console.log(`【${b.code}】${b.title}`);
710
- console.log(`id: ${b.id} | 级别: ${b.severity || "-"} | 状态: ${b.status}(${BUG_STATUS_ZH[b.status] || ""}) | 解决方案: ${b.resolution ? b.resolution + "(" + (RESOLUTION_ZH[b.resolution] || "") + ")" : "-"}`);
711
- console.log(`迭代: ${b.version_iteration_name || "-"}`);
712
- console.log(`报告人: ${b.reporter_name || "-"} | 处理人: ${b.assignee_name || "-"} | 创建: ${fmtDate(b.created_at)} | 更新: ${fmtDate(b.updated_at)}`);
713
- console.log(`\n== 复现步骤 ==\n${htmlToText(b.steps_to_reproduce)}`);
714
- console.log(`\n== 预期行为 ==\n${htmlToText(b.expected_behavior)}`);
715
- console.log(`\n== 实际行为 ==\n${htmlToText(b.actual_behavior)}`);
716
- if (b.description) console.log(`\n== 描述 ==\n${htmlToText(b.description)}`);
717
- if (b.resolution_notes) console.log(`\n== 处理说明 ==\n${htmlToText(b.resolution_notes)}`);
718
- printSavedImages(images);
719
- }
720
-
721
- /** 缺陷/故障状态流转。动作别名 -> transition body(与前端 to_status 取值一致) */
722
- async function transition(cfg, kind, id, action, o) {
723
- const body = buildBody(o);
724
- const note = o.notes || o.reason || o.note || "";
725
- const alias = {
726
- claim: { to_status: "InProgress" },
727
- start: { to_status: "InProgress" },
728
- resolve: { to_status: "ToVerify", resolution: o.resolution || "fixed", resolution_notes: note },
729
- reject: { to_status: "Rejected", resolution: o.resolution || "wontfix", resolution_notes: note },
730
- reopen: { to_status: "Reopened", resolution_notes: note },
731
- close: { to_status: "Closed" },
732
- release: { to_status: "Released" },
733
- };
734
- const payload = { ...(alias[action] || { to_status: action }), ...body };
735
- if (o.assignee) payload.assignee_id = await resolveUserId(cfg, o.assignee);
736
- if (action === "claim" && payload.assignee_id === undefined) payload.assignee_id = (await me(cfg)).id;
737
- const data = await post(cfg, `/${kind}/${id}/transition`, payload);
738
- console.log(`${kind.slice(0, -1)} ${id} -> ${payload.to_status} 完成`);
739
- if (o.json) printJson(data);
740
- return data;
741
- }
742
-
743
- async function commentsCmd(cfg, kind, o, mode) {
744
- const id = await resolveResourceId(cfg, kind, o._[0]);
745
- if (mode === "list") {
746
- const data = await api(cfg, `/${kind}/${id}/comments`);
747
- if (o.json) { printJson(data); return; }
748
- const list = asItems(data);
749
- for (const c of list) {
750
- console.log(`-- ${c.user_name || c.author_name || c.user_id || "?"} @ ${fmtDate(c.created_at)}`);
751
- console.log(` ${htmlToText(c.content).replace(/\n/g, "\n ")}`);
752
- }
753
- if (!list.length) console.log("(暂无评论)");
754
- } else {
755
- if (!o.content) die('缺少 --content "评论内容"');
756
- const extra = optionalJson(o);
757
- await post(cfg, `/${kind}/${id}/comments`, { content: o.content, ...(extra === undefined ? {} : jsonObject(extra)) });
758
- console.log("评论已发表");
759
- }
760
- }
761
-
762
- /* ======================== reqs(需求/backlogs) ======================== */
763
-
764
- async function reqsList(cfg, o) {
765
- const { params, nameFilter } = await listQuery(cfg, o, { filters: ["status", "keyword"] });
766
- const data = await api(cfg, "/backlogs", params);
767
- const items = applyNameFilter(asItems(data), nameFilter);
768
- if (o.json) { printJson({ ...data, items }); return; }
769
- printTotal(data.total, items, nameFilter);
770
- renderTable(["id", "编号", "标题", "类型", "状态", "处理人", "提测时间", "创建"],
771
- [6, 18, 40, 8, 8, 9, 12, 16],
772
- items.map(r => [r.id, r.code, r.title, r.type || "", r.status || "", r.assignee_name || "",
773
- (r.test_date || "").slice(0, 10), fmtDate(r.created_at)]));
774
- }
775
-
776
- async function reqsShow(cfg, o) {
777
- const id = await resolveResourceId(cfg, "backlogs", o._[0]);
778
- const r = await api(cfg, `/backlogs/${id}`);
779
- if (o.json) { printJson(r); return; }
780
- const images = await loadImages(cfg, o, "req", r.id, [r.description, r.content, r.remark]);
781
- console.log(`【${r.code}】${r.title}`);
782
- printLooseFields(r);
783
- printSavedImages(images);
784
- }
785
-
786
- /* ======================== tasks ======================== */
787
-
788
- async function tasksList(cfg, o) {
789
- const { params, nameFilter } = await listQuery(cfg, o, { filters: ["status", "keyword"] });
790
- if (o.version) params.version_iteration_id = o.version;
791
- const data = await api(cfg, "/tasks", params);
792
- const items = applyNameFilter(asItems(data), nameFilter);
793
- if (o.json) { printJson({ ...data, items }); return; }
794
- printTotal(data.total, items, nameFilter);
795
- renderTable(["id", "标题", "状态", "处理人", "需求id", "迭代", "创建"],
796
- [6, 46, 9, 9, 8, 22, 16],
797
- items.map(t => [t.id, t.title, t.status || "", t.assignee_name || "",
798
- t.backlog_id ?? "", t.version_iteration_name || "", fmtDate(t.created_at)]));
799
- }
800
-
801
- /* ======================== versions(迭代) ======================== */
802
-
803
- async function versionsList(cfg, o) {
804
- const params = {
805
- page: pageNum(o.page, 1), page_size: pageNum(o.size, DEFAULT_PAGE_SIZE), status: o.status, keyword: o.keyword,
806
- };
807
- if (o.project) params.project_id = await resolveProjectId(cfg, String(o.project));
808
- const data = await api(cfg, "/versions", params);
809
- const items = asItems(data);
810
- if (o.json) { printJson(data); return; }
811
- printTotal(data.total, items);
812
- renderTable(["id", "名称", "版本号", "项目", "状态", "开始", "发布"],
813
- [5, 32, 9, 18, 11, 12, 12],
814
- items.map(v => [v.id, v.name, v.version_number || "", v.project_name || "", v.status || "",
815
- (v.start_date || "").slice(0, 10), (v.release_date || "").slice(0, 10)]));
816
- }
817
-
818
- async function versionsAction(cfg, o, act) {
819
- const id = o._[0];
820
- if (!id) die("缺少迭代 id");
821
- if (act === "show") {
822
- printJson(await api(cfg, `/versions/${id}`));
823
- return;
824
- }
825
- const extra = optionalJson(o);
826
- if (act === "release") {
827
- await post(cfg, `/versions/${id}/release`, { release_notes: o.notes || "", ...jsonObject(extra ?? {}) });
828
- } else {
829
- await post(cfg, `/versions/${id}/${act}`, extra ?? {});
830
- }
831
- console.log(`迭代 ${id} -> ${act} 完成`);
832
- }
833
-
834
- /* ======================== incidents(线上故障) ======================== */
835
-
836
- async function incidentsList(cfg, o) {
837
- const { params } = await listQuery(cfg, o, { assigneeParam: "assignee", filters: ["status", "severity", "keyword"] });
838
- const data = await api(cfg, "/incidents", params);
839
- const items = asItems(data);
840
- if (o.json) { printJson(data); return; }
841
- printTotal(data.total, items);
842
- renderTable(["id", "编号", "标题", "级别", "状态", "处理人", "创建"],
843
- [6, 18, 46, 5, 17, 9, 16],
844
- items.map(i => [i.id, i.code, i.title, i.severity || "", `${i.status}(${BUG_STATUS_ZH[i.status] || ""})`,
845
- i.assignee_name || "", fmtDate(i.created_at)]));
846
- }
847
-
848
- async function incidentsShow(cfg, o) {
849
- const id = await resolveResourceId(cfg, "incidents", o._[0]);
850
- const d = await api(cfg, `/incidents/${id}`);
851
- if (o.json) { printJson(d); return; }
852
- const images = await loadImages(cfg, o, "inc", d.id, [d.description, d.actual_behavior, d.content]);
853
- console.log(`【${d.code}】${d.title}`);
854
- printLooseFields(d);
855
- printSavedImages(images);
856
- }
857
-
858
- /* ======================== tests(测试计划) ======================== */
859
-
860
- async function testsList(cfg, o) {
861
- const params = {};
862
- if (o.project) params.project_id = await resolveProjectId(cfg, String(o.project));
863
- if (o.version) params.version_iteration_id = o.version;
864
- const data = await api(cfg, "/test-plans/all", params);
865
- const items = asItems(data);
866
- if (o.json) { printJson(items); return; }
867
- printTotal(items.length, items);
868
- renderTable(["id", "名称", "版本/迭代", "状态", "负责人"],
869
- [6, 36, 26, 10, 10],
870
- items.map(t => [t.id, t.name || t.title, t.version_iteration_name || t.version_name || "",
871
- t.status || "", t.test_leader_name || t.owner_name || ""]));
872
- }
873
-
874
- /* ======================== knowledge(知识库) ======================== */
875
-
876
- async function kbCategories(cfg, o) {
877
- const data = await api(cfg, "/knowledge/categories");
878
- if (o.json) { printJson(data); return; }
879
- const walk = (nodes, depth = 0) => {
880
- for (const n of nodes) {
881
- console.log(`${" ".repeat(depth)}${n.id} ${n.name}`);
882
- if (n.children?.length) walk(n.children, depth + 1);
883
- }
884
- };
885
- walk(asItems(data));
886
- }
887
-
888
- async function kbList(cfg, o) {
889
- const params = { page: pageNum(o.page, 1), page_size: pageNum(o.size, DEFAULT_PAGE_SIZE), keyword: o.keyword };
890
- if (o.category) params.category_id = o.category;
891
- if (o.project) params.project_id = await resolveProjectId(cfg, String(o.project));
892
- const data = await api(cfg, "/knowledge/docs", params);
893
- const items = asItems(data);
894
- if (o.json) { printJson(data); return; }
895
- printTotal(data.total, items);
896
- renderTable(["id", "标题", "分类", "更新人", "更新时间"],
897
- [6, 52, 16, 9, 16],
898
- items.map(d => [d.id, d.title, d.category_name || (d.category_id ?? ""), d.updater_name || d.updated_by_name || "", fmtDate(d.updated_at)]));
899
- }
900
-
901
- async function kbShow(cfg, o) {
902
- const id = o._[0];
903
- if (!id) die("缺少文档 id");
904
- const d = await api(cfg, `/knowledge/docs/${id}`);
905
- if (o.json) { printJson(d); return; }
906
- console.log(`【${d.title}】id=${d.id} 分类=${d.category_name || (d.category_id ?? "-")}`);
907
- const body = d.content ?? d.html ?? d.body ?? "";
908
- console.log(`\n${htmlToText(body) || "(正文为空,用 --json 查看原始数据)"}`);
909
- }
910
-
911
- async function kbAnnotations(cfg, o) {
912
- const id = o._[0];
913
- if (!id) die("缺少文档 id");
914
- const data = await api(cfg, `/knowledge/docs/${id}/annotations`);
915
- const items = asItems(data);
916
- if (o.json) { printJson(items); return; }
917
- for (const a of items) {
918
- console.log(`-- [#${a.id}] ${a.user_name || a.creator_name || "?"} @ ${fmtDate(a.created_at)} 状态=${a.status || "-"}`);
919
- console.log(` ${htmlToText(a.content || a.quote || "").replace(/\n/g, "\n ")}`);
920
- }
921
- if (!items.length) console.log("(暂无批注)");
922
- }
923
-
924
- /* ======================== weekly / dashboard / kanban ======================== */
925
-
926
- async function weeklyCmd(cfg, o, act) {
927
- if (act === "draft") {
928
- // 后端必填 week_start(周一日期);--week 缺省时取本周一
929
- const monday = (d => { const x = new Date(d); const diff = (x.getDay() + 6) % 7; x.setDate(x.getDate() - diff); return x.toISOString().slice(0, 10); })(new Date());
930
- printJson(await api(cfg, "/weekly-reports/draft", { week_start: o.week || monday }));
931
- return;
932
- }
933
- if (act === "show") {
934
- if (!o._[0]) die("缺少 id 参数");
935
- printJson(await api(cfg, `/weekly-reports/${o._[0]}`));
936
- return;
937
- }
938
- // 后端要求 scope(mine/all/subordinates);--mine 传 scope 免去了 user_id 过滤,也绕开"查看全部"权限
939
- const params = { scope: o.mine || o.user ? "mine" : "all", page: pageNum(o.page, 1), page_size: pageNum(o.size, DEFAULT_PAGE_SIZE) };
940
- if (!o.mine && o.user) params.user_id = o.user;
941
- if (o.week) params.week_start = o.week;
942
- const data = await api(cfg, "/weekly-reports", params);
943
- const items = asItems(data);
944
- if (o.json) { printJson(data); return; }
945
- printTotal(data.total, items);
946
- renderTable(["id", "周起始", "姓名", "状态", "提交时间"],
947
- [6, 12, 10, 10, 16],
948
- items.map(w => [w.id, (w.week_start || "").slice(0, 10), w.user_name || w.real_name || "", w.status || "", fmtDate(w.submitted_at || w.created_at)]));
949
- }
950
-
951
- async function dashboardCmd(cfg, o) {
952
- const d = await api(cfg, "/dashboard/workbench");
953
- if (o.json) { printJson(d); return; }
954
- if (d.greeting) console.log(d.greeting + "\n");
955
- const simple = {};
956
- for (const [k, v] of Object.entries(d)) {
957
- if (v === null || typeof v !== "object") simple[k] = v;
958
- else if (Array.isArray(v)) simple[k] = `[${v.length} 项,--json 查看明细]`;
959
- else simple[k] = Object.keys(v).slice(0, 6).join(", ") + " …(--json 查看)";
960
- }
961
- printJson(simple);
962
- }
963
-
964
- async function kanbanCmd(cfg, o) {
965
- const params = o.project ? { project_id: await resolveProjectId(cfg, String(o.project)) } : {};
966
- printJson(await api(cfg, "/efficiency/overview", params));
967
- }
968
-
969
- /* ======================== 命令分发 ======================== */
970
-
971
- /** 命令别名映射 → 标准命令名 */
972
- const CMD_ALIASES = {
973
- me: "me",
974
- login: "login", logout: "logout", whoami: "whoami", setup: "setup",
975
- members: "members", member: "members",
976
- projects: "projects", project: "projects",
977
- dashboard: "dashboard",
978
- kanban: "kanban",
979
- bugs: "bugs", bug: "bugs",
980
- reqs: "reqs", req: "reqs", backlogs: "reqs", backlog: "reqs",
981
- tasks: "tasks", task: "tasks",
982
- versions: "versions", version: "versions", iters: "versions", iter: "versions",
983
- incidents: "incidents", incident: "incidents", inc: "incidents",
984
- tests: "tests", test: "tests", "test-plans": "tests",
985
- kb: "kb", knowledge: "kb",
986
- weekly: "weekly", weeklies: "weekly",
987
- config: "config",
988
- };
989
-
990
- const NO_AUTH_CMDS = new Set(["login", "logout", "config", "setup"]);
991
-
992
- async function main() {
993
- const cfg = loadConfig();
994
- const [rawCmd, action, ...rest] = process.argv.slice(2);
995
- const o = parseArgs(rest);
996
- const resolveId = async (resource) => {
997
- if (!o._[0]) die("缺少 id 参数");
998
- return resolveResourceId(cfg, resource, String(o._[0]));
999
- };
1000
-
1001
- if (!rawCmd || rawCmd === "help" || rawCmd === "--help" || rawCmd === "-h") { usage(); process.exit(0); }
1002
- if (rawCmd === "--version" || rawCmd === "-v") { console.log(`adev v${VERSION}`); process.exit(0); }
1003
-
1004
- const cmd = CMD_ALIASES[rawCmd];
1005
- if (!cmd) die(`未知命令: ${rawCmd}(执行 adev --help 查看用法)`);
1006
- if (!NO_AUTH_CMDS.has(cmd)) requireToken(cfg);
1007
-
1008
- switch (cmd) {
1009
- case "config":
1010
- if (action === "set-token") { if (!o._[0]) die("用法: adev config set-token <token>"); saveToken(o._[0]); }
1011
- else if (action === "show") {
1012
- printJson({ ...cfg, token: cfg.token ? cfg.token.slice(0, 4) + "****(已隐藏)" : "(未设置)" });
1013
- console.log(`配置文件: ${CONFIG_CANDIDATES.join(" 或 ")}`);
1014
- } else usage();
1015
- break;
1016
-
1017
- case "me": printJson(await me(cfg)); break;
1018
-
1019
- case "login": await loginCmd(cfg, o); break;
1020
- case "logout": await logoutCmd(cfg); break;
1021
- case "setup": await setupCmd(cfg); break;
1022
- case "whoami": {
1023
- const u = await me(cfg);
1024
- console.log(`${u.nickname || u.real_name || u.username}(${u.username}) 角色=${u.role || "?"} | 认证方式: ${authLabel(cfg)}`);
1025
- break;
1026
- }
1027
-
1028
- case "members": {
1029
- const data = await api(cfg, "/members", {
1030
- page: pageNum(o.page, 1), page_size: pageNum(o.size, MEMBER_PAGE_SIZE), keyword: o.keyword,
1031
- });
1032
- const items = asItems(data);
1033
- if (o.json) printJson(items);
1034
- else renderTable(["id", "用户名", "姓名", "角色", "状态"], [6, 14, 10, 12, 8],
1035
- items.map(m => [m.id, m.username, m.real_name || m.nickname || "", m.role || "", m.status || ""]));
1036
- break;
1037
- }
1038
-
1039
- case "projects": {
1040
- const list = await api(cfg, "/projects/simple");
1041
- if (o.json) printJson(list);
1042
- else renderTable(["id", "名称", "状态"], [6, 40, 10], list.map(p => [p.id, p.name, p.status]));
1043
- break;
1044
- }
1045
-
1046
- case "dashboard": await dashboardCmd(cfg, o); break;
1047
- case "kanban": await kanbanCmd(cfg, o); break;
1048
-
1049
- /* ---------- bugs ---------- */
1050
- case "bugs": {
1051
- const A = action || "list";
1052
- if (A === "list") await bugsList(cfg, o);
1053
- else if (A === "show") await bugsShow(cfg, o);
1054
- else if (A === "stats") printJson(await api(cfg, "/bugs/stats", await projectParam(cfg, o)));
1055
- else if (A === "create") {
1056
- const body = buildBody(o, ["title", "severity", "priority", "description", "steps_to_reproduce", "expected_behavior", "actual_behavior", "source", "environment"]);
1057
- if (o.project) body.project_id = await resolveProjectId(cfg, String(o.project));
1058
- if (!body.title) die("缺少 --title");
1059
- const d = await post(cfg, "/bugs", body);
1060
- console.log(`缺陷已登记: id=${d.id} ${d.code || ""}`);
1061
- }
1062
- else if (A === "update") {
1063
- const id = await resolveId("bugs");
1064
- await put(cfg, `/bugs/${id}`, buildBody(o, ["title", "severity", "priority", "description", "assignee_id"]));
1065
- console.log("已更新");
1066
- }
1067
- else if (["claim", "resolve", "reject", "reopen", "close"].includes(A)) {
1068
- await transition(cfg, "bugs", await resolveId("bugs"), A, o);
1069
- }
1070
- else if (A === "transition") {
1071
- if (!o.to) die("transition 需要 --to <状态>");
1072
- await transition(cfg, "bugs", await resolveId("bugs"), o.to, o);
1073
- }
1074
- else if (A === "comments") await commentsCmd(cfg, "bugs", o, "list");
1075
- else if (A === "comment") await commentsCmd(cfg, "bugs", o, "add");
1076
- else if (A === "ai-analyze") printJson(await post(cfg, "/bugs/ai-analyze", optionalJson(o) ?? {}));
1077
- else die(`未知的 bugs 子命令: ${A}(执行 adev --help 查看用法)`);
1078
- break;
1079
- }
1080
-
1081
- /* ---------- reqs ---------- */
1082
- case "reqs": {
1083
- const A = action || "list";
1084
- if (A === "list") await reqsList(cfg, o);
1085
- else if (A === "show") await reqsShow(cfg, o);
1086
- else if (A === "create") {
1087
- const body = buildBody(o, ["title", "type", "description", "content", "priority"]);
1088
- if (o.project) body.project_id = await resolveProjectId(cfg, String(o.project));
1089
- if (!body.title) die("缺少 --title");
1090
- const d = await post(cfg, "/backlogs", body);
1091
- console.log(`需求已创建: id=${d.id} ${d.code || ""}`);
1092
- }
1093
- else if (A === "update") {
1094
- const id = await resolveId("backlogs");
1095
- await put(cfg, `/backlogs/${id}`, buildBody(o, ["title", "type", "description", "content", "priority", "assignee_id"]));
1096
- console.log("已更新");
1097
- }
1098
- else if (A === "delete") { await del(cfg, `/backlogs/${await resolveId("backlogs")}`); console.log("已删除"); }
1099
- else if (A === "set-test-date") {
1100
- const id = await resolveId("backlogs");
1101
- if (!o.date) die("缺少 --date YYYY-MM-DD");
1102
- await put(cfg, `/backlogs/${id}/test-date`, { test_date: o.date });
1103
- console.log(`提测时间已设为 ${o.date}`);
1104
- }
1105
- else if (A === "data-sources") {
1106
- const id = await resolveId("backlogs");
1107
- if (o.data || o.jsonFile) {
1108
- await put(cfg, `/backlogs/${id}/data-sources`, { items: readJsonInput(o, "数据源清单") });
1109
- console.log("数据源对接清单已保存");
1110
- } else printJson(await api(cfg, `/backlogs/${id}/data-sources`));
1111
- }
1112
- else if (A === "assign-iteration") {
1113
- const id = await resolveId("backlogs");
1114
- if (!o.iteration) die("缺少 --iteration <迭代id>");
1115
- await put(cfg, `/backlogs/${id}/assign-iteration`, { version_iteration_id: o.iteration });
1116
- console.log("已分配迭代");
1117
- }
1118
- else if (["shelve", "unshelve", "reactivate", "revoke"].includes(A)) {
1119
- const id = await resolveId("backlogs");
1120
- await post(cfg, `/backlogs/${id}/${A}`, optionalJson(o) ?? {});
1121
- console.log(`${A} 完成`);
1122
- }
1123
- else die(`未知的 reqs 子命令: ${A}(执行 adev --help 查看用法)`);
1124
- break;
1125
- }
1126
-
1127
- /* ---------- tasks ---------- */
1128
- case "tasks": {
1129
- const A = action || "list";
1130
- if (A === "list") await tasksList(cfg, o);
1131
- else if (A === "show") {
1132
- if (!o._[0]) die("缺少 id 参数");
1133
- printJson(await api(cfg, `/tasks/${o._[0]}`));
1134
- }
1135
- else if (A === "create") {
1136
- const body = buildBody(o, ["title", "type", "description", "priority", "due_date", "estimate_hours", "backlog_id"]);
1137
- if (o.project) body.project_id = await resolveProjectId(cfg, String(o.project));
1138
- if (o.assignee) body.assignee_id = await resolveUserId(cfg, o.assignee);
1139
- if (o.version) body.version_iteration_id = o.version;
1140
- if (!body.title) die("缺少 --title");
1141
- const d = await post(cfg, "/tasks", body);
1142
- console.log(`任务已创建: id=${d.id ?? JSON.stringify(d)}`);
1143
- }
1144
- else if (A === "update") {
1145
- if (!o._[0]) die("缺少 id 参数");
1146
- const body = buildBody(o, ["title", "type", "description", "priority", "due_date", "status", "estimate_hours"]);
1147
- if (o.assignee) body.assignee_id = await resolveUserId(cfg, o.assignee);
1148
- await put(cfg, `/tasks/${o._[0]}`, body);
1149
- console.log("已更新");
1150
- }
1151
- else if (A === "delete") {
1152
- if (!o._[0]) die("缺少 id 参数");
1153
- await del(cfg, `/tasks/${o._[0]}`);
1154
- console.log("已删除");
1155
- }
1156
- else if (A === "batch") {
1157
- const list = readJsonInput(o, "batch");
1158
- if (!Array.isArray(list)) die("batch 需要 JSON 数组,如 --data '[{\"title\":...},...]'");
1159
- const d = await post(cfg, "/tasks/batch", list);
1160
- console.log(`批量创建完成: ${JSON.stringify(d).slice(0, 300)}`);
1161
- }
1162
- else die(`未知的 tasks 子命令: ${A}(执行 adev --help 查看用法)`);
1163
- break;
1164
- }
1165
-
1166
- /* ---------- versions ---------- */
1167
- case "versions": {
1168
- const A = action || "list";
1169
- if (A === "list") await versionsList(cfg, o);
1170
- else if (A === "stats") printJson(await api(cfg, "/versions/stats", await projectParam(cfg, o)));
1171
- else if (["show", "start", "start-testing", "complete", "accept", "release"].includes(A)) await versionsAction(cfg, o, A);
1172
- else die(`未知的 versions 子命令: ${A}(执行 adev --help 查看用法)`);
1173
- break;
1174
- }
1175
-
1176
- /* ---------- incidents ---------- */
1177
- case "incidents": {
1178
- const A = action || "list";
1179
- if (A === "list") await incidentsList(cfg, o);
1180
- else if (A === "show") await incidentsShow(cfg, o);
1181
- else if (A === "create") {
1182
- const body = buildBody(o, ["title", "severity", "priority", "description", "actual_behavior", "environment", "source"]);
1183
- if (o.project) body.project_id = await resolveProjectId(cfg, String(o.project));
1184
- if (!body.title) die("缺少 --title");
1185
- const d = await post(cfg, "/incidents", body);
1186
- console.log(`故障已登记: id=${d.id} ${d.code || ""}`);
1187
- }
1188
- else if (A === "update") {
1189
- const id = await resolveId("incidents");
1190
- await put(cfg, `/incidents/${id}`, buildBody(o, ["title", "severity", "priority", "description"]));
1191
- console.log("已更新");
1192
- }
1193
- else if (A === "delete") { await del(cfg, `/incidents/${await resolveId("incidents")}`); console.log("已删除"); }
1194
- else if (["claim", "resolve", "reject", "reopen", "close", "release"].includes(A)) {
1195
- await transition(cfg, "incidents", await resolveId("incidents"), A, o);
1196
- }
1197
- else if (A === "transition") {
1198
- if (!o.to) die("transition 需要 --to <状态>");
1199
- await transition(cfg, "incidents", await resolveId("incidents"), o.to, o);
1200
- }
1201
- else die(`未知的 incidents 子命令: ${A}(执行 adev --help 查看用法)`);
1202
- break;
1203
- }
1204
-
1205
- /* ---------- tests ---------- */
1206
- case "tests": {
1207
- const A = action || "list";
1208
- if (A === "list") await testsList(cfg, o);
1209
- else if (A === "show") {
1210
- if (!o._[0]) die("缺少 id 参数");
1211
- printJson(await api(cfg, `/test-plans/${o._[0]}`));
1212
- }
1213
- else if (A === "cases") {
1214
- if (!o._[0]) die("缺少 id 参数");
1215
- printJson(await api(cfg, `/test-plans/version/${o._[0]}/cases`, o.project ? { project_id: await resolveProjectId(cfg, String(o.project)) } : {}));
1216
- }
1217
- else if (A === "transition") {
1218
- if (!o._[0]) die("缺少 id 参数");
1219
- await put(cfg, `/test-plans/${o._[0]}/transition`, optionalJson(o) ?? {});
1220
- console.log("已流转");
1221
- }
1222
- else die(`未知的 tests 子命令: ${A}(执行 adev --help 查看用法)`);
1223
- break;
1224
- }
1225
-
1226
- /* ---------- knowledge ---------- */
1227
- case "kb": {
1228
- const A = action || "list";
1229
- if (A === "categories") await kbCategories(cfg, o);
1230
- else if (A === "list") await kbList(cfg, o);
1231
- else if (A === "show") await kbShow(cfg, o);
1232
- else if (A === "annotations") await kbAnnotations(cfg, o);
1233
- else die(`未知的 kb 子命令: ${A}(执行 adev --help 查看用法)`);
1234
- break;
1235
- }
1236
-
1237
- /* ---------- weekly ---------- */
1238
- case "weekly":
1239
- await weeklyCmd(cfg, o, action || "list");
1240
- break;
1241
- }
1242
- }
1243
-
1244
- function invokedDirectly() {
1245
- const entry = process.argv[1];
1246
- if (!entry) return false;
1247
- // npm install -g <本地目录> 在 Windows 上可能以 junction 链接进全局 node_modules,
1248
- // argv[1] 是链接路径而 import.meta.url 是解析后的真实路径,必须先 realpath 归一化再比较。
1249
- try {
1250
- return fs.realpathSync(path.resolve(entry)).toLowerCase()
1251
- === fs.realpathSync(fileURLToPath(import.meta.url)).toLowerCase();
1252
- } catch {
1253
- return path.resolve(entry).toLowerCase() === fileURLToPath(import.meta.url).toLowerCase();
1254
- }
1255
- }
1256
-
1257
- if (invokedDirectly()) {
1258
- main().catch(e => {
1259
- if (e instanceof AdevError) console.error(`[adev] ${e.message}`);
1260
- else console.error(`[adev] ${e.stack || e}`);
1261
- process.exit(1);
1262
- });
1263
- }
1264
-
1265
- export {
1266
- AdevError,
1267
- parseArgs,
1268
- htmlToText,
1269
- trunc,
1270
- displayWidth,
1271
- buildBody,
1272
- readJsonInput,
1273
- applyConfigPatch,
1274
- applyNameFilter,
1275
- feedInput,
1276
- fmtDate,
1277
- pageNum,
1278
- asItems,
1279
- imageExt,
1280
- resolveAssetUrl,
1281
- normalizeConfig,
1282
- withLogin,
1283
- isPasswordSession,
1284
- authLabel,
1285
- };
1
+ #!/usr/bin/env node
2
+ /**
3
+ * agiledev-cli — AgileDev 敏捷研发管理系统 CLI(命令名:adev)
4
+ *
5
+ * 数据来源:/api/v1/*(Bearer Token 鉴权)。单文件、零第三方依赖(Node >= 18)。
6
+ *
7
+ * 资源与常用命令:
8
+ * adev me | members list | projects | dashboard | kanban
9
+ * adev bugs list|show|create|update|claim|resolve|reject|reopen|close|transition|comments|comment|stats
10
+ * adev reqs list|show|create|update|set-test-date|data-sources|assign-iteration|shelve|unshelve|reactivate|revoke|delete
11
+ * adev tasks list|show|create|update|delete|batch
12
+ * adev versions list|show|stats|start|start-testing|complete|accept|release
13
+ * adev incidents list|show|create|update|claim|resolve|reject|reopen|transition|delete
14
+ * adev tests list|show|cases|transition
15
+ * adev kb list|show|categories|annotations
16
+ * adev weekly list|show|draft
17
+ *
18
+ * 所有写操作均支持 --data '<json>' 或 --json-file <path> 直接透传请求体。
19
+ */
20
+
21
+ import fs from "node:fs";
22
+ import os from "node:os";
23
+ import path from "node:path";
24
+ import { createRequire } from "node:module";
25
+ import { fileURLToPath } from "node:url";
26
+
27
+ const require = createRequire(import.meta.url);
28
+ const { version: VERSION } = require("./package.json");
29
+
30
+ /* ======================== 常量 ======================== */
31
+
32
+ const DEFAULT_BASE_URL = "https://scrum.chitem.com";
33
+ const DEFAULT_PAGE_SIZE = 20;
34
+ const MEMBER_PAGE_SIZE = 100;
35
+ const ASSIGNEE_FILTER_PAGE_SIZE = 200;
36
+ const RESOLVE_SEARCH_PAGE_SIZE = 50;
37
+ const MAX_PARALLEL_DOWNLOADS = 5;
38
+ const REQUEST_TIMEOUT_MS = 30000;
39
+
40
+ const CONFIG_CANDIDATES = [
41
+ path.join(os.homedir(), ".agiledev-cli.json"),
42
+ path.join(process.cwd(), "adev.config.json"),
43
+ ];
44
+
45
+ /* ======================== 错误 ======================== */
46
+
47
+ class AdevError extends Error {
48
+ constructor(msg) {
49
+ super(msg);
50
+ this.name = "AdevError";
51
+ }
52
+ }
53
+
54
+ function die(msg) {
55
+ throw new AdevError(msg);
56
+ }
57
+
58
+ /* ======================== 配置 ======================== */
59
+
60
+ function normalizeConfig(cfg) {
61
+ const next = { baseURL: DEFAULT_BASE_URL, token: "", ...(cfg || {}) };
62
+ let base = String(next.baseURL || DEFAULT_BASE_URL).trim().replace(/\/+$/, "");
63
+ base = base.replace(/\/api\/v1$/i, "");
64
+ next.baseURL = base || DEFAULT_BASE_URL;
65
+ next.token = String(next.token ?? "").trim();
66
+ return next;
67
+ }
68
+
69
+ function loadConfig() {
70
+ let fileCfg = {};
71
+ for (const p of CONFIG_CANDIDATES) {
72
+ try {
73
+ const parsed = JSON.parse(fs.readFileSync(p, "utf8"));
74
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
75
+ fileCfg = parsed;
76
+ break;
77
+ }
78
+ } catch { /* 下一个候选 */ }
79
+ }
80
+ const env = {};
81
+ if (process.env.ADEV_BASE_URL) env.baseURL = process.env.ADEV_BASE_URL;
82
+ if (process.env.ADEV_TOKEN) env.token = process.env.ADEV_TOKEN;
83
+ return normalizeConfig({ ...fileCfg, ...env });
84
+ }
85
+
86
+ /** 在已有配置上打补丁。unset 中的键会被删除,避免登录覆盖掉无关字段。 */
87
+ function applyConfigPatch(existing, patch, unset = []) {
88
+ const next = existing && typeof existing === "object" && !Array.isArray(existing) ? { ...existing } : {};
89
+ Object.assign(next, patch);
90
+ for (const k of unset) delete next[k];
91
+ if (!next.baseURL) next.baseURL = DEFAULT_BASE_URL;
92
+ return next;
93
+ }
94
+
95
+ function readConfigFile(p) {
96
+ try {
97
+ const parsed = JSON.parse(fs.readFileSync(p, "utf8"));
98
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
99
+ } catch { /* 新文件或损坏 */ }
100
+ return {};
101
+ }
102
+
103
+ function writeConfigFile(p, data) {
104
+ const text = JSON.stringify(data, null, 2) + "\n";
105
+ const tmp = `${p}.${process.pid}.tmp`;
106
+ try {
107
+ fs.writeFileSync(tmp, text, { mode: 0o600 });
108
+ try { fs.chmodSync(tmp, 0o600); } catch { /* Windows 不支持 chmod */ }
109
+ fs.renameSync(tmp, p);
110
+ } catch (e) {
111
+ try { fs.unlinkSync(tmp); } catch { /* 忽略残留临时文件 */ }
112
+ die(`写入配置文件失败 (${p}):${e.message}`);
113
+ }
114
+ }
115
+
116
+ function updateConfig(patch, unset = []) {
117
+ const p = CONFIG_CANDIDATES[0];
118
+ const next = applyConfigPatch(readConfigFile(p), patch, unset);
119
+ writeConfigFile(p, next);
120
+ return p;
121
+ }
122
+
123
+ function saveToken(token) {
124
+ // 保留 username,方便之后 adev login 回车沿用;authType 标明当前凭证是 API Key
125
+ const p = updateConfig({ token, authType: "token" });
126
+ console.log(`已保存到 ${p}`);
127
+ }
128
+
129
+ function isPasswordSession(cfg) {
130
+ return cfg.authType === "login" || (cfg.authType !== "token" && !!cfg.username);
131
+ }
132
+
133
+ function authLabel(cfg) {
134
+ return isPasswordSession(cfg) ? `账号密码登录(${cfg.username})` : "API Key";
135
+ }
136
+
137
+ /** 登录成功后写回内存中的 cfg。随后的 /auth/me 必须用新 token,不能沿用加载时的旧凭证。 */
138
+ function withLogin(cfg, token, username) {
139
+ return { ...cfg, token, username, authType: "login" };
140
+ }
141
+
142
+ /* ======================== HTTP ======================== */
143
+
144
+ let ME_CACHE = null;
145
+
146
+ function isTimeoutError(e) {
147
+ return e?.name === "TimeoutError" || e?.name === "AbortError";
148
+ }
149
+
150
+ function networkHint(e, cfg) {
151
+ if (isTimeoutError(e)) {
152
+ return `请求超时(${REQUEST_TIMEOUT_MS / 1000}s):请确认已接入公司网络/VPN,且 ${cfg.baseURL} 可达。`;
153
+ }
154
+ const code = e.cause?.code ? ` (${e.cause.code})` : "";
155
+ return `网络请求失败:${e.message}${code}\n请确认已接入公司网络/VPN,且 ${cfg.baseURL} 可达。`;
156
+ }
157
+
158
+ async function request(cfg, method, resPath, { params, body } = {}) {
159
+ const qs = params
160
+ ? "?" + Object.entries(params)
161
+ .filter(([, v]) => v !== undefined && v !== null && v !== "")
162
+ .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&")
163
+ : "";
164
+ const url = `${cfg.baseURL}/api/v1${resPath}${qs}`;
165
+ let res;
166
+ try {
167
+ // Node 内置 fetch 默认不走 HTTP_PROXY,正好直连内网
168
+ res = await fetch(url, {
169
+ method,
170
+ headers: { Authorization: `Bearer ${cfg.token}`, ...(body ? { "Content-Type": "application/json" } : {}) },
171
+ body: body ? JSON.stringify(body) : undefined,
172
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
173
+ });
174
+ } catch (e) {
175
+ die(networkHint(e, cfg));
176
+ }
177
+ if (res.status === 401) {
178
+ die(isPasswordSession(cfg)
179
+ ? `登录已过期,请重新执行 \`adev login\`(账号 ${cfg.username})`
180
+ : "鉴权失败(401):API Key 无效或已过期,请执行 `adev config set-token <token>` 或 `adev login`(账号密码登录)");
181
+ }
182
+ if (res.status === 403) die(`权限不足(403):无权访问 ${resPath}`);
183
+ if (res.status === 404) die(`资源不存在(404):${resPath}`);
184
+ if (res.status >= 500) die(`服务器错误(${res.status}):${method} ${resPath},请稍后重试`);
185
+ let payload;
186
+ try { payload = await res.json(); } catch { die(`响应不是 JSON (HTTP ${res.status}):${method} ${url}`); }
187
+ if (!payload || typeof payload !== "object") die(`响应不是 JSON 对象 (HTTP ${res.status}):${method} ${url}`);
188
+ if (payload.code !== 200) {
189
+ const hint = payload.code === 40300 ? "\n(当前 API Key 无此模块权限,请到平台为该 Key 分配权限)" : "";
190
+ const bodyText = body ? `\n body: ${JSON.stringify(body).slice(0, 500)}` : "";
191
+ die(`接口错误 code=${payload.code} message=${payload.message}${hint}\n ${method} ${url}${bodyText}`);
192
+ }
193
+ return payload.data;
194
+ }
195
+
196
+ const api = (cfg, p, params) => request(cfg, "GET", p, { params });
197
+ const post = (cfg, p, body) => request(cfg, "POST", p, { body: body ?? {} });
198
+ const put = (cfg, p, body) => request(cfg, "PUT", p, { body: body ?? {} });
199
+ const del = (cfg, p) => request(cfg, "DELETE", p);
200
+
201
+ async function me(cfg) {
202
+ if (!ME_CACHE) ME_CACHE = await api(cfg, "/auth/me");
203
+ return ME_CACHE;
204
+ }
205
+
206
+ /** 把 "me" 解析为当前用户 id */
207
+ async function resolveUserId(cfg, v) {
208
+ if (v === undefined || v === null || v === "" || v === false) return undefined;
209
+ if (v === "me") return (await me(cfg)).id;
210
+ return v;
211
+ }
212
+
213
+ function requireToken(cfg) {
214
+ if (!cfg.token) die("未配置凭证:请执行 `adev login`(账号密码)或 `adev config set-token <token>`");
215
+ }
216
+
217
+ /* ======================== auth(登录) ======================== */
218
+
219
+ /**
220
+ * 把一段终端输入切成完整行。
221
+ * raw 模式下 Windows 回车常常是 \\r\\n,必须把紧跟 \\r 的 \\n 吃掉,否则一行会被读成两行。
222
+ */
223
+ function feedInput(state, chunk) {
224
+ const lines = [];
225
+ for (const c of chunk) {
226
+ if (c === "\u0003") { state.interrupted = true; break; }
227
+ if (c === "\r") {
228
+ lines.push(state.buf);
229
+ state.buf = "";
230
+ state.skipLf = true;
231
+ } else if (c === "\n") {
232
+ if (state.skipLf) state.skipLf = false;
233
+ else { lines.push(state.buf); state.buf = ""; }
234
+ } else if (state.raw && (c === "\u007f" || c === "\b")) {
235
+ state.skipLf = false;
236
+ state.buf = state.buf.slice(0, -1);
237
+ } else {
238
+ state.skipLf = false;
239
+ state.buf += c;
240
+ }
241
+ }
242
+ return lines;
243
+ }
244
+
245
+ /** 基于 stdin 事件流的行读取器(TTY / 管道 / IDE 终端下行为一致) */
246
+ function createLineReader() {
247
+ const stdin = process.stdin;
248
+ stdin.setEncoding("utf8");
249
+ stdin.resume();
250
+ const state = { buf: "", skipLf: false, raw: false, interrupted: false };
251
+ const queue = [];
252
+ const waiters = [];
253
+ const settle = line => { if (waiters.length) waiters.shift()(line); else queue.push(line); };
254
+ stdin.on("data", chunk => {
255
+ for (const line of feedInput(state, chunk)) settle(line);
256
+ if (state.interrupted) {
257
+ if (stdin.isTTY) { try { stdin.setRawMode(false); } catch { /* 忽略 */ } }
258
+ process.stdout.write("\n");
259
+ process.exit(130);
260
+ }
261
+ });
262
+ stdin.on("end", () => { settle(state.buf); state.buf = ""; while (waiters.length) settle(""); });
263
+ const nextLine = () => (queue.length ? Promise.resolve(queue.shift()) : new Promise(r => waiters.push(r)));
264
+ return {
265
+ ask(prompt) { process.stdout.write(prompt); return nextLine(); },
266
+ async askHidden(prompt) {
267
+ process.stdout.write(prompt);
268
+ const isTTY = !!stdin.isTTY;
269
+ if (isTTY) { stdin.setRawMode(true); state.raw = true; }
270
+ try {
271
+ return queue.length ? queue.shift() : await nextLine();
272
+ } finally {
273
+ if (isTTY) { stdin.setRawMode(false); state.raw = false; }
274
+ process.stdout.write("\n");
275
+ }
276
+ },
277
+ };
278
+ }
279
+
280
+ async function loginCmd(cfg, o) {
281
+ const io = createLineReader();
282
+ const saved = cfg.username || "";
283
+ const raw0 = o._[0] !== undefined ? String(o._[0]) : await io.ask(`账号${saved ? `(回车使用 ${saved})` : ""}: `);
284
+ const username = raw0.trim() || saved;
285
+ if (!username) die("账号不能为空");
286
+ const password = await io.askHidden("密码: ");
287
+ if (!password) die("密码不能为空");
288
+
289
+ let res;
290
+ try {
291
+ res = await fetch(`${cfg.baseURL}/api/v1/auth/login`, {
292
+ method: "POST",
293
+ headers: { "Content-Type": "application/json" },
294
+ body: JSON.stringify({ username, password }),
295
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
296
+ });
297
+ } catch (e) {
298
+ die(networkHint(e, cfg));
299
+ }
300
+ let payload;
301
+ try { payload = await res.json(); } catch { die(`登录响应异常 (HTTP ${res.status})`); }
302
+ if (!payload || typeof payload !== "object" || payload.code !== 200) {
303
+ die(`登录失败:${payload?.message || payload?.detail || "HTTP " + res.status}`);
304
+ }
305
+ const token = payload.data?.access_token;
306
+ if (!token) die("登录响应中未找到 access_token 字段,请联系管理员确认接口版本");
307
+
308
+ const savedPath = updateConfig({ baseURL: cfg.baseURL, token, username, authType: "login" });
309
+ Object.assign(cfg, withLogin(cfg, token, username));
310
+ ME_CACHE = null;
311
+ let u;
312
+ try {
313
+ u = await me(cfg);
314
+ } catch (e) {
315
+ console.log(`凭证已保存到 ${savedPath}`);
316
+ throw e;
317
+ }
318
+ console.log(`✓ 登录成功:${u.nickname || u.real_name || u.username}(${u.role || "未知角色"})`);
319
+ console.log(`凭证已保存到 ${savedPath}`);
320
+ }
321
+
322
+ async function logoutCmd(cfg) {
323
+ // 服务端使 token 失效;已过期或网络失败不阻塞本地清理
324
+ if (cfg.token) {
325
+ try {
326
+ await fetch(`${cfg.baseURL}/api/v1/auth/logout`, {
327
+ method: "POST",
328
+ headers: { Authorization: `Bearer ${cfg.token}` },
329
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
330
+ });
331
+ } catch { /* 忽略 */ }
332
+ }
333
+ updateConfig({ baseURL: cfg.baseURL || DEFAULT_BASE_URL }, ["token", "username", "authType"]);
334
+ console.log("已退出登录并清除本地凭证");
335
+ }
336
+
337
+ /* ======================== setup(一键安装 AI skill) ======================== */
338
+
339
+ async function setupCmd(cfg) {
340
+ const pkgDir = path.dirname(fileURLToPath(import.meta.url));
341
+ const skills = [
342
+ { src: path.join(pkgDir, "SKILL.md"), name: "adev" },
343
+ { src: path.join(pkgDir, "skills", "adev-login", "SKILL.md"), name: "adev-login" },
344
+ ];
345
+ for (const s of skills) {
346
+ if (!fs.existsSync(s.src)) die(`包内缺少 ${s.src},安装包可能不完整,请重新 npm install -g agiledev-cli`);
347
+ }
348
+
349
+ // 统一安装到用户级共享目录 ~/.agents/skills:一份技能,各 AI 助手(ZCode 等)通用,不重复散落
350
+ const destRoot = path.join(os.homedir(), ".agents", "skills");
351
+ for (const s of skills) {
352
+ const dest = path.join(destRoot, s.name, "SKILL.md");
353
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
354
+ fs.copyFileSync(s.src, dest);
355
+ console.log(`✓ 已安装 ${dest}`);
356
+ }
357
+ console.log("\n技能统一安装在用户级共享目录 ~/.agents/skills,各 AI 助手共用这一份。");
358
+ console.log(cfg.token
359
+ ? "凭证已配置。新开一个 AI 会话即可说「看看测试提了哪些 bug」「帮我登录敏捷系统」等指令。"
360
+ : "下一步:执行 `adev login` 登录敏捷系统(账号密码即网页登录账号)。");
361
+ }
362
+
363
+ /* ======================== 工具函数 ======================== */
364
+
365
+ function displayWidth(s) {
366
+ let w = 0;
367
+ for (const ch of String(s)) {
368
+ const c = ch.codePointAt(0);
369
+ w += (c >= 0x1100 && (c <= 0x115f || c === 0x2329 || c === 0x232a ||
370
+ (c >= 0x2e80 && c <= 0xa4cf && c !== 0x303f) || (c >= 0xac00 && c <= 0xd7a3) ||
371
+ (c >= 0xf900 && c <= 0xfaff) || (c >= 0xfe30 && c <= 0xfe6f) ||
372
+ (c >= 0xff00 && c <= 0xff60) || (c >= 0xffe0 && c <= 0xffe6))) ? 2 : 1;
373
+ }
374
+ return w;
375
+ }
376
+
377
+ function trunc(s, width) {
378
+ s = String(s ?? "");
379
+ if (displayWidth(s) <= width) return s;
380
+ let out = "", w = 0;
381
+ for (const ch of s) {
382
+ const cw = displayWidth(ch);
383
+ if (w + cw > width - 1) break;
384
+ out += ch; w += cw;
385
+ }
386
+ return out + "…";
387
+ }
388
+
389
+ function padCell(s, width) {
390
+ s = trunc(s, width);
391
+ return s + " ".repeat(Math.max(0, width - displayWidth(s)));
392
+ }
393
+
394
+ function renderTable(headers, widths, rows) {
395
+ console.log(headers.map((h, i) => padCell(h, widths[i])).join(" "));
396
+ for (const r of rows) console.log(r.map((c, i) => padCell(c, widths[i])).join(" "));
397
+ }
398
+
399
+ const BUG_STATUS_ZH = {
400
+ Pending: "待处理", InProgress: "处理中", ToVerify: "待验证", Reopened: "重新打开",
401
+ Rejected: "已拒绝", Closed: "已关闭", Released: "已发布",
402
+ };
403
+ const RESOLUTION_ZH = {
404
+ fixed: "已修复", wontfix: "不修复", duplicate: "重复提交",
405
+ cannot_reproduce: "无法复现", by_design: "设计如此", later: "后续版本",
406
+ };
407
+ const fmtDate = (s) => (s ? String(s).replace("T", " ").slice(0, 16) : "");
408
+ const printJson = (data) => console.log(JSON.stringify(data, null, 2));
409
+
410
+ function pageNum(v, fallback) {
411
+ const n = parseInt(v, 10);
412
+ return Number.isFinite(n) && n > 0 ? n : fallback;
413
+ }
414
+
415
+ function asItems(data) {
416
+ if (Array.isArray(data)) return data;
417
+ if (Array.isArray(data?.items)) return data.items;
418
+ return [];
419
+ }
420
+
421
+ function safeCodePoint(c, fallback) {
422
+ return Number.isInteger(c) && c > 0 && c <= 0x10ffff ? String.fromCodePoint(c) : fallback;
423
+ }
424
+
425
+ function htmlToText(html) {
426
+ if (!html) return "(空)";
427
+ return String(html)
428
+ .replace(/<img[^>]*src="([^"]*)"[^>]*>/gi, "\n[图片: $1]\n")
429
+ .replace(/<br\s*\/?>/gi, "\n")
430
+ .replace(/<\/(p|div|li|h[1-6]|tr)>/gi, "\n")
431
+ .replace(/<[^>]+>/g, "")
432
+ .replace(/&#(\d+);/g, (m, n) => safeCodePoint(Number(n), m))
433
+ .replace(/&#x([0-9a-f]+);/gi, (m, h) => safeCodePoint(parseInt(h, 16), m))
434
+ .replace(/&nbsp;/g, " ")
435
+ .replace(/&lt;/g, "<")
436
+ .replace(/&gt;/g, ">")
437
+ .replace(/&quot;/g, '"')
438
+ .replace(/&#39;|&apos;/g, "'")
439
+ .replace(/&amp;/g, "&")
440
+ .replace(/\n{3,}/g, "\n\n")
441
+ .trim();
442
+ }
443
+
444
+ const extractImages = (html) =>
445
+ [...String(html || "").matchAll(/<img[^>]*src="([^"]*)"[^>]*>/gi)].map(m => m[1]).filter(Boolean);
446
+
447
+ function resolveAssetUrl(base, raw) {
448
+ if (/^https?:\/\//i.test(raw)) return raw;
449
+ if (raw.startsWith("/")) return base + raw;
450
+ return `${base}/${raw}`;
451
+ }
452
+
453
+ function imageExt(url) {
454
+ try {
455
+ const pathname = new URL(url, "https://placeholder.local").pathname;
456
+ const m = pathname.match(/\.(png|jpe?g|gif|webp|bmp)$/i);
457
+ return m ? m[1].toLowerCase() : "png";
458
+ } catch {
459
+ return "png";
460
+ }
461
+ }
462
+
463
+ async function downloadImages(cfg, htmlFields, dir) {
464
+ const urls = [...new Set(htmlFields.flatMap(extractImages))].filter(Boolean);
465
+ if (!urls.length) return [];
466
+ fs.mkdirSync(dir, { recursive: true });
467
+ const saved = [];
468
+ for (let start = 0; start < urls.length; start += MAX_PARALLEL_DOWNLOADS) {
469
+ const batch = urls.slice(start, start + MAX_PARALLEL_DOWNLOADS);
470
+ const results = await Promise.allSettled(batch.map(async (raw, j) => {
471
+ const i = start + j;
472
+ const u = resolveAssetUrl(cfg.baseURL, raw);
473
+ const res = await fetch(u, {
474
+ headers: { Authorization: `Bearer ${cfg.token}` },
475
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
476
+ });
477
+ if (!res.ok) throw new Error(`${u} HTTP ${res.status}`);
478
+ const buf = Buffer.from(await res.arrayBuffer());
479
+ const file = path.join(dir, `img${i + 1}.${imageExt(u)}`);
480
+ await fs.promises.writeFile(file, buf);
481
+ return { src: raw, file };
482
+ }));
483
+ for (const r of results) {
484
+ if (r.status === "fulfilled") saved.push(r.value);
485
+ else console.error(` (图片下载失败: ${r.reason?.message || r.reason})`);
486
+ }
487
+ }
488
+ return saved;
489
+ }
490
+
491
+ function printSavedImages(images) {
492
+ if (!images.length) return;
493
+ console.log(`\n== 截图(已下载到本地,可直接查看)==`);
494
+ images.forEach(i => console.log(` ${i.file} <- ${i.src}`));
495
+ }
496
+
497
+ function imageDir(o, kind, id) {
498
+ return o.imagesDir || path.join(os.tmpdir(), "agiledev-cli", "images", `${kind}-${id}`);
499
+ }
500
+
501
+ async function loadImages(cfg, o, kind, id, fields) {
502
+ if (o.noImages) return [];
503
+ return downloadImages(cfg, fields, imageDir(o, kind, id));
504
+ }
505
+
506
+ const SKIP_DETAIL_KEYS = new Set(["id", "code", "title"]);
507
+
508
+ function printLooseFields(obj) {
509
+ for (const k of Object.keys(obj)) {
510
+ if (SKIP_DETAIL_KEYS.has(k)) continue;
511
+ const v = obj[k];
512
+ if (v === null || v === undefined || v === "" || typeof v === "object") continue;
513
+ if (typeof v === "string" && /[<>]|static\/uploads/.test(v)) console.log(`\n== ${k} ==\n${htmlToText(v)}`);
514
+ else console.log(`${k}: ${v}`);
515
+ }
516
+ }
517
+
518
+ function printTotal(total, items, nameFilter) {
519
+ const n = total ?? items.length;
520
+ console.log(`共 ${n} 条${nameFilter ? `(本地过滤后 ${items.length} 条)` : ""}\n`);
521
+ }
522
+
523
+ /* ======================== 参数解析 ======================== */
524
+
525
+ /** kebab-case → camelCase(如 --json-file → jsonFile) */
526
+ const kebabToCamel = (s) => s.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
527
+ const BOOLEAN_FLAGS = new Set(["json", "yes", "force", "mine", "no-images"]);
528
+
529
+ function parseArgs(argv) {
530
+ const opts = { _: [] };
531
+ for (let i = 0; i < argv.length; i++) {
532
+ const a = argv[i];
533
+ if (a.startsWith("--")) {
534
+ const raw = a.slice(2);
535
+ const key = kebabToCamel(raw);
536
+ if (BOOLEAN_FLAGS.has(raw)) { opts[key] = true; continue; }
537
+ if (i + 1 >= argv.length || argv[i + 1].startsWith("--")) {
538
+ die(`选项 ${a} 需要一个值,例如: ${a} <value>`);
539
+ }
540
+ opts[key] = argv[++i];
541
+ } else opts._.push(a);
542
+ }
543
+ return opts;
544
+ }
545
+
546
+ function parseJson(text, label) {
547
+ try { return JSON.parse(text); }
548
+ catch (e) { die(`${label} 不是合法 JSON:${e.message}`); }
549
+ }
550
+
551
+ function readTextFile(p) {
552
+ try { return fs.readFileSync(p, "utf8"); }
553
+ catch (e) { die(`读取 ${p} 失败:${e.message}`); }
554
+ }
555
+
556
+ function optionalJson(opts, label = "--data") {
557
+ if (opts.data) return parseJson(opts.data, label);
558
+ if (opts.jsonFile) return parseJson(readTextFile(opts.jsonFile), opts.jsonFile);
559
+ return undefined;
560
+ }
561
+
562
+ function readJsonInput(opts, label = "--data") {
563
+ const value = optionalJson(opts, label);
564
+ if (value === undefined) die(`缺少 ${label} '<json>' 或 --json-file <path>`);
565
+ return value;
566
+ }
567
+
568
+ function jsonObject(value, label = "--data") {
569
+ if (value === null || typeof value !== "object" || Array.isArray(value)) die(`${label} 需要 JSON 对象`);
570
+ return value;
571
+ }
572
+
573
+ /** 通用写操作 body:--data '<json>' / --json-file <path> / 常用 flag 收集 */
574
+ function buildBody(opts, picked = []) {
575
+ const raw = optionalJson(opts);
576
+ const body = raw === undefined ? {} : jsonObject(raw);
577
+ for (const k of picked) if (opts[k] !== undefined) body[k] = opts[k];
578
+ return body;
579
+ }
580
+
581
+ function usage() {
582
+ console.log(`adev v${VERSION} — AgileDev 敏捷研发管理系统 CLI
583
+
584
+ 资源与子命令(<id> 一般也接受编号如 BUG-20260922-009;写操作通用 --data '<json>'/--json-file 透传请求体):
585
+
586
+ login [账号] 账号密码登录(免 API Key,密码不回显)
587
+ logout 退出登录并清除本地凭证
588
+ whoami 当前登录身份
589
+ setup 一键安装 Skill 文件到用户级共享目录 ~/.agents/skills
590
+
591
+ me 当前登录用户(原始 JSON)
592
+ members list 成员列表
593
+ projects [--json] 项目列表
594
+ dashboard 工作台总览
595
+ kanban 效能看板总览
596
+
597
+ bugs list|show|stats|comments
598
+ bugs create|update 创建/编辑缺陷
599
+ bugs claim|resolve|reject|reopen|close|transition 状态流转
600
+ bugs comment <id> --content "xx" 发表评论
601
+ bugs ai-analyze --data '{"title":...}'
602
+
603
+ reqs list|show|create|update|delete
604
+ reqs set-test-date <id> --date 2026-09-30 设置提测时间
605
+ reqs data-sources <id> [--data ...] 查看/保存数据源对接清单
606
+ reqs assign-iteration <id> --iteration 101 分配到迭代
607
+ reqs shelve|unshelve|reactivate|revoke <id>
608
+
609
+ tasks list|show|create|update|delete
610
+ tasks batch --data '[{...},...]' 批量创建(AI 拆解用)
611
+
612
+ versions list|show|stats
613
+ versions start|start-testing|complete|accept <id> 迭代状态流转
614
+ versions release <id> [--notes "xx"]
615
+
616
+ incidents list|show|create|update|delete|claim|resolve|reject|reopen|transition
617
+ tests list [--project 28] | show <id> | cases <versionId> | transition <id> --data ...
618
+ kb categories | list [--category id] [--keyword x] | show <id> | annotations <docId>
619
+ weekly list [--mine] | show <id> | draft [--week 2026-09-22]
620
+
621
+ autofix 本地自动巡检修复服务(当前目录为工作区)
622
+ adev autofix 打开控制台,在页面选择 Agent / 模型 / 项目后启动
623
+ adev autofix [--agent claude|opencode|antigravity] [--worker-agent ...] [--prompt "..."]
624
+ [--model ...] [--worker-model ...] [--interval 60]
625
+ [--verify "npm test"] [--auto-verify] [--no-ui] [--project <id>]
626
+ [--profile <配置档id>] [--yes]
627
+ adev autofix status|pause|resume|stop|ui|restart|profiles
628
+ adev autofix say "指令" | tell <任务编号> "说明" | answer <问题编号> "回答" | retry <任务编号>
629
+ 参数按“本次 > 工作区记忆 > 全局记忆 > 自动探测/内置默认”解析,并预填到配置页;
630
+ --yes 跳过页面点击,直接按预填值启动(非交互/脚本场景)
631
+ --profile 指定工作区配置档(项目 + 多仓库 + 分支 + 巡检时段),见 .autofix.json
632
+
633
+ list 通用选项:
634
+ --project <id|名称> --status <值> --severity P1 --assignee <名|id|me>
635
+ --keyword <词> --page n --size n(默认 ${DEFAULT_PAGE_SIZE}) --mine(只看我的)
636
+ 缺陷/需求/任务按姓名过滤时在本地匹配,并自动至少拉取 ${ASSIGNEE_FILTER_PAGE_SIZE} 条
637
+ show 选项: --json --images-dir <dir> --no-images
638
+
639
+ 通用选项: --version/-v --help/-h
640
+
641
+ Bug/故障状态: Pending待处理 InProgress处理中 ToVerify待验证 Reopened重新打开 Rejected已拒绝 Closed已关闭(故障另有 Released已发布)
642
+ Bug 解决方案: fixed已修复 wontfix不修复 duplicate重复 cannot_reproduce无法复现 by_design设计如此 later后续版本
643
+ 需求状态(中文): 待处理/已准入/开发中/已发布/已拒绝/暂缓 任务状态(中文): 待开始/开发中/已暂停/已完成/不处理
644
+
645
+ 配置: 环境变量 ADEV_BASE_URL/ADEV_TOKEN > ~/.agiledev-cli.json > ./adev.config.json`);
646
+ }
647
+
648
+ async function resolveProjectId(cfg, keyword) {
649
+ if (/^\d+$/.test(keyword)) return keyword;
650
+ const projects = await api(cfg, "/projects/simple");
651
+ const hits = projects.filter(p => p.name.includes(keyword));
652
+ if (hits.length === 1) return hits[0].id;
653
+ die((hits.length === 0 ? `找不到名称包含"${keyword}"的项目` : `"${keyword}"匹配到多个项目,请用 id`) + `。候选:\n` +
654
+ projects.map(p => ` ${p.id} ${p.name}`).join("\n"));
655
+ }
656
+
657
+ /** show 入参:纯数字当 id;否则按 code 精确匹配(走 keyword 搜索) */
658
+ async function resolveResourceId(cfg, resource, input, codeField = "code") {
659
+ if (!input) die("缺少 id 或编号参数");
660
+ if (/^\d+$/.test(input)) return input;
661
+ const data = await api(cfg, `/${resource}`, { keyword: input, page_size: RESOLVE_SEARCH_PAGE_SIZE });
662
+ const hit = asItems(data).find(i => i[codeField] === input);
663
+ if (!hit) die(`未找到编号为 ${input} 的记录`);
664
+ return hit.id;
665
+ }
666
+
667
+ async function projectParam(cfg, opts) {
668
+ if (opts.project) return { project_id: await resolveProjectId(cfg, String(opts.project)) };
669
+ return {};
670
+ }
671
+
672
+ /**
673
+ * 组装 list 查询。
674
+ * assigneeParam 为 assignee_id 时,姓名无法传给服务端,改为放大 page_size 后本地过滤。
675
+ * 故障接口的 assignee 直接接受 "me" 或姓名。
676
+ */
677
+ async function listQuery(cfg, o, { assigneeParam = "assignee_id", filters = ["status", "keyword"] } = {}) {
678
+ const params = {
679
+ page: pageNum(o.page, 1),
680
+ page_size: pageNum(o.size, DEFAULT_PAGE_SIZE),
681
+ ...(await projectParam(cfg, o)),
682
+ };
683
+ for (const key of filters) if (o[key] !== undefined) params[key] = o[key];
684
+ let nameFilter = null;
685
+ if (o.mine || o.assignee === "me") {
686
+ params[assigneeParam] = assigneeParam === "assignee" ? "me" : (await me(cfg)).id;
687
+ } else if (o.assignee !== undefined && String(o.assignee) !== "") {
688
+ if (assigneeParam === "assignee" || /^\d+$/.test(String(o.assignee))) params[assigneeParam] = o.assignee;
689
+ else {
690
+ nameFilter = String(o.assignee);
691
+ params.page_size = Math.max(params.page_size, ASSIGNEE_FILTER_PAGE_SIZE);
692
+ }
693
+ }
694
+ return { params, nameFilter };
695
+ }
696
+
697
+ function applyNameFilter(items, nameFilter, field = "assignee_name") {
698
+ if (!nameFilter) return items;
699
+ return items.filter(i => (i[field] || "").includes(nameFilter));
700
+ }
701
+
702
+ /* ======================== bugs ======================== */
703
+
704
+ async function bugsList(cfg, o) {
705
+ const { params, nameFilter } = await listQuery(cfg, o, { filters: ["status", "severity", "keyword"] });
706
+ const data = await api(cfg, "/bugs", params);
707
+ const items = applyNameFilter(asItems(data), nameFilter);
708
+ if (o.json) { printJson({ ...data, items }); return; }
709
+ printTotal(data.total, items, nameFilter);
710
+ renderTable(["id", "编号", "标题", "级别", "状态", "处理人", "报告人", "迭代", "创建"],
711
+ [6, 18, 40, 5, 17, 9, 9, 22, 16],
712
+ items.map(b => [b.id, b.code, b.title, b.severity || "", `${b.status}(${BUG_STATUS_ZH[b.status] || ""})`,
713
+ b.assignee_name || "", b.reporter_name || "", b.version_iteration_name || "", fmtDate(b.created_at)]));
714
+ }
715
+
716
+ async function bugsShow(cfg, o) {
717
+ const id = await resolveResourceId(cfg, "bugs", o._[0]);
718
+ const b = await api(cfg, `/bugs/${id}`);
719
+ if (o.json) { printJson(b); return; }
720
+ const images = await loadImages(cfg, o, "bug", b.id, [b.description, b.steps_to_reproduce, b.expected_behavior, b.actual_behavior]);
721
+ console.log(`【${b.code}】${b.title}`);
722
+ console.log(`id: ${b.id} | 级别: ${b.severity || "-"} | 状态: ${b.status}(${BUG_STATUS_ZH[b.status] || ""}) | 解决方案: ${b.resolution ? b.resolution + "(" + (RESOLUTION_ZH[b.resolution] || "") + ")" : "-"}`);
723
+ console.log(`迭代: ${b.version_iteration_name || "-"}`);
724
+ console.log(`报告人: ${b.reporter_name || "-"} | 处理人: ${b.assignee_name || "-"} | 创建: ${fmtDate(b.created_at)} | 更新: ${fmtDate(b.updated_at)}`);
725
+ console.log(`\n== 复现步骤 ==\n${htmlToText(b.steps_to_reproduce)}`);
726
+ console.log(`\n== 预期行为 ==\n${htmlToText(b.expected_behavior)}`);
727
+ console.log(`\n== 实际行为 ==\n${htmlToText(b.actual_behavior)}`);
728
+ if (b.description) console.log(`\n== 描述 ==\n${htmlToText(b.description)}`);
729
+ if (b.resolution_notes) console.log(`\n== 处理说明 ==\n${htmlToText(b.resolution_notes)}`);
730
+ printSavedImages(images);
731
+ }
732
+
733
+ /** 缺陷/故障状态流转。动作别名 -> transition body(与前端 to_status 取值一致) */
734
+ async function transition(cfg, kind, id, action, o) {
735
+ const body = buildBody(o);
736
+ const note = o.notes || o.reason || o.note || "";
737
+ const alias = {
738
+ claim: { to_status: "InProgress" },
739
+ start: { to_status: "InProgress" },
740
+ resolve: { to_status: "ToVerify", resolution: o.resolution || "fixed", resolution_notes: note },
741
+ reject: { to_status: "Rejected", resolution: o.resolution || "wontfix", resolution_notes: note },
742
+ reopen: { to_status: "Reopened", resolution_notes: note },
743
+ close: { to_status: "Closed" },
744
+ release: { to_status: "Released" },
745
+ };
746
+ const payload = { ...(alias[action] || { to_status: action }), ...body };
747
+ if (o.assignee) payload.assignee_id = await resolveUserId(cfg, o.assignee);
748
+ if (action === "claim" && payload.assignee_id === undefined) payload.assignee_id = (await me(cfg)).id;
749
+ const data = await post(cfg, `/${kind}/${id}/transition`, payload);
750
+ console.log(`${kind.slice(0, -1)} ${id} -> ${payload.to_status} 完成`);
751
+ if (o.json) printJson(data);
752
+ return data;
753
+ }
754
+
755
+ async function commentsCmd(cfg, kind, o, mode) {
756
+ const id = await resolveResourceId(cfg, kind, o._[0]);
757
+ if (mode === "list") {
758
+ const data = await api(cfg, `/${kind}/${id}/comments`);
759
+ if (o.json) { printJson(data); return; }
760
+ const list = asItems(data);
761
+ for (const c of list) {
762
+ console.log(`-- ${c.user_name || c.author_name || c.user_id || "?"} @ ${fmtDate(c.created_at)}`);
763
+ console.log(` ${htmlToText(c.content).replace(/\n/g, "\n ")}`);
764
+ }
765
+ if (!list.length) console.log("(暂无评论)");
766
+ } else {
767
+ if (!o.content) die('缺少 --content "评论内容"');
768
+ const extra = optionalJson(o);
769
+ await post(cfg, `/${kind}/${id}/comments`, { content: o.content, ...(extra === undefined ? {} : jsonObject(extra)) });
770
+ console.log("评论已发表");
771
+ }
772
+ }
773
+
774
+ /* ======================== reqs(需求/backlogs) ======================== */
775
+
776
+ async function reqsList(cfg, o) {
777
+ const { params, nameFilter } = await listQuery(cfg, o, { filters: ["status", "keyword"] });
778
+ const data = await api(cfg, "/backlogs", params);
779
+ const items = applyNameFilter(asItems(data), nameFilter);
780
+ if (o.json) { printJson({ ...data, items }); return; }
781
+ printTotal(data.total, items, nameFilter);
782
+ renderTable(["id", "编号", "标题", "类型", "状态", "处理人", "提测时间", "创建"],
783
+ [6, 18, 40, 8, 8, 9, 12, 16],
784
+ items.map(r => [r.id, r.code, r.title, r.type || "", r.status || "", r.assignee_name || "",
785
+ (r.test_date || "").slice(0, 10), fmtDate(r.created_at)]));
786
+ }
787
+
788
+ async function reqsShow(cfg, o) {
789
+ const id = await resolveResourceId(cfg, "backlogs", o._[0]);
790
+ const r = await api(cfg, `/backlogs/${id}`);
791
+ if (o.json) { printJson(r); return; }
792
+ const images = await loadImages(cfg, o, "req", r.id, [r.description, r.content, r.remark]);
793
+ console.log(`【${r.code}】${r.title}`);
794
+ printLooseFields(r);
795
+ printSavedImages(images);
796
+ }
797
+
798
+ /* ======================== tasks ======================== */
799
+
800
+ async function tasksList(cfg, o) {
801
+ const { params, nameFilter } = await listQuery(cfg, o, { filters: ["status", "keyword"] });
802
+ if (o.version) params.version_iteration_id = o.version;
803
+ const data = await api(cfg, "/tasks", params);
804
+ const items = applyNameFilter(asItems(data), nameFilter);
805
+ if (o.json) { printJson({ ...data, items }); return; }
806
+ printTotal(data.total, items, nameFilter);
807
+ renderTable(["id", "标题", "状态", "处理人", "需求id", "迭代", "创建"],
808
+ [6, 46, 9, 9, 8, 22, 16],
809
+ items.map(t => [t.id, t.title, t.status || "", t.assignee_name || "",
810
+ t.backlog_id ?? "", t.version_iteration_name || "", fmtDate(t.created_at)]));
811
+ }
812
+
813
+ /* ======================== versions(迭代) ======================== */
814
+
815
+ async function versionsList(cfg, o) {
816
+ const params = {
817
+ page: pageNum(o.page, 1), page_size: pageNum(o.size, DEFAULT_PAGE_SIZE), status: o.status, keyword: o.keyword,
818
+ };
819
+ if (o.project) params.project_id = await resolveProjectId(cfg, String(o.project));
820
+ const data = await api(cfg, "/versions", params);
821
+ const items = asItems(data);
822
+ if (o.json) { printJson(data); return; }
823
+ printTotal(data.total, items);
824
+ renderTable(["id", "名称", "版本号", "项目", "状态", "开始", "发布"],
825
+ [5, 32, 9, 18, 11, 12, 12],
826
+ items.map(v => [v.id, v.name, v.version_number || "", v.project_name || "", v.status || "",
827
+ (v.start_date || "").slice(0, 10), (v.release_date || "").slice(0, 10)]));
828
+ }
829
+
830
+ async function versionsAction(cfg, o, act) {
831
+ const id = o._[0];
832
+ if (!id) die("缺少迭代 id");
833
+ if (act === "show") {
834
+ printJson(await api(cfg, `/versions/${id}`));
835
+ return;
836
+ }
837
+ const extra = optionalJson(o);
838
+ if (act === "release") {
839
+ await post(cfg, `/versions/${id}/release`, { release_notes: o.notes || "", ...jsonObject(extra ?? {}) });
840
+ } else {
841
+ await post(cfg, `/versions/${id}/${act}`, extra ?? {});
842
+ }
843
+ console.log(`迭代 ${id} -> ${act} 完成`);
844
+ }
845
+
846
+ /* ======================== incidents(线上故障) ======================== */
847
+
848
+ async function incidentsList(cfg, o) {
849
+ const { params } = await listQuery(cfg, o, { assigneeParam: "assignee", filters: ["status", "severity", "keyword"] });
850
+ const data = await api(cfg, "/incidents", params);
851
+ const items = asItems(data);
852
+ if (o.json) { printJson(data); return; }
853
+ printTotal(data.total, items);
854
+ renderTable(["id", "编号", "标题", "级别", "状态", "处理人", "创建"],
855
+ [6, 18, 46, 5, 17, 9, 16],
856
+ items.map(i => [i.id, i.code, i.title, i.severity || "", `${i.status}(${BUG_STATUS_ZH[i.status] || ""})`,
857
+ i.assignee_name || "", fmtDate(i.created_at)]));
858
+ }
859
+
860
+ async function incidentsShow(cfg, o) {
861
+ const id = await resolveResourceId(cfg, "incidents", o._[0]);
862
+ const d = await api(cfg, `/incidents/${id}`);
863
+ if (o.json) { printJson(d); return; }
864
+ const images = await loadImages(cfg, o, "inc", d.id, [d.description, d.actual_behavior, d.content]);
865
+ console.log(`【${d.code}】${d.title}`);
866
+ printLooseFields(d);
867
+ printSavedImages(images);
868
+ }
869
+
870
+ /* ======================== tests(测试计划) ======================== */
871
+
872
+ async function testsList(cfg, o) {
873
+ const params = {};
874
+ if (o.project) params.project_id = await resolveProjectId(cfg, String(o.project));
875
+ if (o.version) params.version_iteration_id = o.version;
876
+ const data = await api(cfg, "/test-plans/all", params);
877
+ const items = asItems(data);
878
+ if (o.json) { printJson(items); return; }
879
+ printTotal(items.length, items);
880
+ renderTable(["id", "名称", "版本/迭代", "状态", "负责人"],
881
+ [6, 36, 26, 10, 10],
882
+ items.map(t => [t.id, t.name || t.title, t.version_iteration_name || t.version_name || "",
883
+ t.status || "", t.test_leader_name || t.owner_name || ""]));
884
+ }
885
+
886
+ /* ======================== knowledge(知识库) ======================== */
887
+
888
+ async function kbCategories(cfg, o) {
889
+ const data = await api(cfg, "/knowledge/categories");
890
+ if (o.json) { printJson(data); return; }
891
+ const walk = (nodes, depth = 0) => {
892
+ for (const n of nodes) {
893
+ console.log(`${" ".repeat(depth)}${n.id} ${n.name}`);
894
+ if (n.children?.length) walk(n.children, depth + 1);
895
+ }
896
+ };
897
+ walk(asItems(data));
898
+ }
899
+
900
+ async function kbList(cfg, o) {
901
+ const params = { page: pageNum(o.page, 1), page_size: pageNum(o.size, DEFAULT_PAGE_SIZE), keyword: o.keyword };
902
+ if (o.category) params.category_id = o.category;
903
+ if (o.project) params.project_id = await resolveProjectId(cfg, String(o.project));
904
+ const data = await api(cfg, "/knowledge/docs", params);
905
+ const items = asItems(data);
906
+ if (o.json) { printJson(data); return; }
907
+ printTotal(data.total, items);
908
+ renderTable(["id", "标题", "分类", "更新人", "更新时间"],
909
+ [6, 52, 16, 9, 16],
910
+ items.map(d => [d.id, d.title, d.category_name || (d.category_id ?? ""), d.updater_name || d.updated_by_name || "", fmtDate(d.updated_at)]));
911
+ }
912
+
913
+ async function kbShow(cfg, o) {
914
+ const id = o._[0];
915
+ if (!id) die("缺少文档 id");
916
+ const d = await api(cfg, `/knowledge/docs/${id}`);
917
+ if (o.json) { printJson(d); return; }
918
+ console.log(`【${d.title}】id=${d.id} 分类=${d.category_name || (d.category_id ?? "-")}`);
919
+ const body = d.content ?? d.html ?? d.body ?? "";
920
+ console.log(`\n${htmlToText(body) || "(正文为空,用 --json 查看原始数据)"}`);
921
+ }
922
+
923
+ async function kbAnnotations(cfg, o) {
924
+ const id = o._[0];
925
+ if (!id) die("缺少文档 id");
926
+ const data = await api(cfg, `/knowledge/docs/${id}/annotations`);
927
+ const items = asItems(data);
928
+ if (o.json) { printJson(items); return; }
929
+ for (const a of items) {
930
+ console.log(`-- [#${a.id}] ${a.user_name || a.creator_name || "?"} @ ${fmtDate(a.created_at)} 状态=${a.status || "-"}`);
931
+ console.log(` ${htmlToText(a.content || a.quote || "").replace(/\n/g, "\n ")}`);
932
+ }
933
+ if (!items.length) console.log("(暂无批注)");
934
+ }
935
+
936
+ /* ======================== weekly / dashboard / kanban ======================== */
937
+
938
+ async function weeklyCmd(cfg, o, act) {
939
+ if (act === "draft") {
940
+ // 后端必填 week_start(周一日期);--week 缺省时取本周一
941
+ const monday = (d => { const x = new Date(d); const diff = (x.getDay() + 6) % 7; x.setDate(x.getDate() - diff); return x.toISOString().slice(0, 10); })(new Date());
942
+ printJson(await api(cfg, "/weekly-reports/draft", { week_start: o.week || monday }));
943
+ return;
944
+ }
945
+ if (act === "show") {
946
+ if (!o._[0]) die("缺少 id 参数");
947
+ printJson(await api(cfg, `/weekly-reports/${o._[0]}`));
948
+ return;
949
+ }
950
+ // 后端要求 scope(mine/all/subordinates);--mine 传 scope 免去了 user_id 过滤,也绕开"查看全部"权限
951
+ const params = { scope: o.mine || o.user ? "mine" : "all", page: pageNum(o.page, 1), page_size: pageNum(o.size, DEFAULT_PAGE_SIZE) };
952
+ if (!o.mine && o.user) params.user_id = o.user;
953
+ if (o.week) params.week_start = o.week;
954
+ const data = await api(cfg, "/weekly-reports", params);
955
+ const items = asItems(data);
956
+ if (o.json) { printJson(data); return; }
957
+ printTotal(data.total, items);
958
+ renderTable(["id", "周起始", "姓名", "状态", "提交时间"],
959
+ [6, 12, 10, 10, 16],
960
+ items.map(w => [w.id, (w.week_start || "").slice(0, 10), w.user_name || w.real_name || "", w.status || "", fmtDate(w.submitted_at || w.created_at)]));
961
+ }
962
+
963
+ async function dashboardCmd(cfg, o) {
964
+ const d = await api(cfg, "/dashboard/workbench");
965
+ if (o.json) { printJson(d); return; }
966
+ if (d.greeting) console.log(d.greeting + "\n");
967
+ const simple = {};
968
+ for (const [k, v] of Object.entries(d)) {
969
+ if (v === null || typeof v !== "object") simple[k] = v;
970
+ else if (Array.isArray(v)) simple[k] = `[${v.length} 项,--json 查看明细]`;
971
+ else simple[k] = Object.keys(v).slice(0, 6).join(", ") + " …(--json 查看)";
972
+ }
973
+ printJson(simple);
974
+ }
975
+
976
+ async function kanbanCmd(cfg, o) {
977
+ const params = o.project ? { project_id: await resolveProjectId(cfg, String(o.project)) } : {};
978
+ printJson(await api(cfg, "/efficiency/overview", params));
979
+ }
980
+
981
+ /* ======================== 命令分发 ======================== */
982
+
983
+ /** 命令别名映射 → 标准命令名 */
984
+ const CMD_ALIASES = {
985
+ me: "me",
986
+ login: "login", logout: "logout", whoami: "whoami", setup: "setup",
987
+ members: "members", member: "members",
988
+ projects: "projects", project: "projects",
989
+ dashboard: "dashboard",
990
+ kanban: "kanban",
991
+ bugs: "bugs", bug: "bugs",
992
+ reqs: "reqs", req: "reqs", backlogs: "reqs", backlog: "reqs",
993
+ tasks: "tasks", task: "tasks",
994
+ versions: "versions", version: "versions", iters: "versions", iter: "versions",
995
+ incidents: "incidents", incident: "incidents", inc: "incidents",
996
+ tests: "tests", test: "tests", "test-plans": "tests",
997
+ kb: "kb", knowledge: "kb",
998
+ weekly: "weekly", weeklies: "weekly",
999
+ config: "config",
1000
+ };
1001
+
1002
+ const NO_AUTH_CMDS = new Set(["login", "logout", "config", "setup"]);
1003
+
1004
+ async function main() {
1005
+ const cfg = loadConfig();
1006
+ const [rawCmd, action, ...rest] = process.argv.slice(2);
1007
+
1008
+ // autofix 的第二个参数是选项而非资源 action,必须在通用分发前单独解析。
1009
+ // 也不在全局分发阶段强制要求 token,否则登录过期时 status/stop 都不可用。
1010
+ if (rawCmd === "autofix") {
1011
+ const { main: autofixMain } = await import("./autofix/cli.js");
1012
+ const code = await autofixMain([action, ...rest].filter(v => v !== undefined));
1013
+ // 服务进程自行管理生命周期,不能在这里强制退出
1014
+ if (code !== null && code !== undefined) process.exit(code);
1015
+ return;
1016
+ }
1017
+
1018
+ const o = parseArgs(rest);
1019
+ const resolveId = async (resource) => {
1020
+ if (!o._[0]) die("缺少 id 参数");
1021
+ return resolveResourceId(cfg, resource, String(o._[0]));
1022
+ };
1023
+
1024
+ if (!rawCmd || rawCmd === "help" || rawCmd === "--help" || rawCmd === "-h") { usage(); process.exit(0); }
1025
+ if (rawCmd === "--version" || rawCmd === "-v") { console.log(`adev v${VERSION}`); process.exit(0); }
1026
+
1027
+ const cmd = CMD_ALIASES[rawCmd];
1028
+ if (!cmd) die(`未知命令: ${rawCmd}(执行 adev --help 查看用法)`);
1029
+ if (!NO_AUTH_CMDS.has(cmd)) requireToken(cfg);
1030
+
1031
+ switch (cmd) {
1032
+ case "config":
1033
+ if (action === "set-token") { if (!o._[0]) die("用法: adev config set-token <token>"); saveToken(o._[0]); }
1034
+ else if (action === "show") {
1035
+ printJson({ ...cfg, token: cfg.token ? cfg.token.slice(0, 4) + "****(已隐藏)" : "(未设置)" });
1036
+ console.log(`配置文件: ${CONFIG_CANDIDATES.join(" 或 ")}`);
1037
+ } else usage();
1038
+ break;
1039
+
1040
+ case "me": printJson(await me(cfg)); break;
1041
+
1042
+ case "login": await loginCmd(cfg, o); break;
1043
+ case "logout": await logoutCmd(cfg); break;
1044
+ case "setup": await setupCmd(cfg); break;
1045
+ case "whoami": {
1046
+ const u = await me(cfg);
1047
+ console.log(`${u.nickname || u.real_name || u.username}(${u.username}) 角色=${u.role || "?"} | 认证方式: ${authLabel(cfg)}`);
1048
+ break;
1049
+ }
1050
+
1051
+ case "members": {
1052
+ const data = await api(cfg, "/members", {
1053
+ page: pageNum(o.page, 1), page_size: pageNum(o.size, MEMBER_PAGE_SIZE), keyword: o.keyword,
1054
+ });
1055
+ const items = asItems(data);
1056
+ if (o.json) printJson(items);
1057
+ else renderTable(["id", "用户名", "姓名", "角色", "状态"], [6, 14, 10, 12, 8],
1058
+ items.map(m => [m.id, m.username, m.real_name || m.nickname || "", m.role || "", m.status || ""]));
1059
+ break;
1060
+ }
1061
+
1062
+ case "projects": {
1063
+ const list = await api(cfg, "/projects/simple");
1064
+ if (o.json) printJson(list);
1065
+ else renderTable(["id", "名称", "状态"], [6, 40, 10], list.map(p => [p.id, p.name, p.status]));
1066
+ break;
1067
+ }
1068
+
1069
+ case "dashboard": await dashboardCmd(cfg, o); break;
1070
+ case "kanban": await kanbanCmd(cfg, o); break;
1071
+
1072
+ /* ---------- bugs ---------- */
1073
+ case "bugs": {
1074
+ const A = action || "list";
1075
+ if (A === "list") await bugsList(cfg, o);
1076
+ else if (A === "show") await bugsShow(cfg, o);
1077
+ else if (A === "stats") printJson(await api(cfg, "/bugs/stats", await projectParam(cfg, o)));
1078
+ else if (A === "create") {
1079
+ const body = buildBody(o, ["title", "severity", "priority", "description", "steps_to_reproduce", "expected_behavior", "actual_behavior", "source", "environment"]);
1080
+ if (o.project) body.project_id = await resolveProjectId(cfg, String(o.project));
1081
+ if (!body.title) die("缺少 --title");
1082
+ const d = await post(cfg, "/bugs", body);
1083
+ console.log(`缺陷已登记: id=${d.id} ${d.code || ""}`);
1084
+ }
1085
+ else if (A === "update") {
1086
+ const id = await resolveId("bugs");
1087
+ await put(cfg, `/bugs/${id}`, buildBody(o, ["title", "severity", "priority", "description", "assignee_id"]));
1088
+ console.log("已更新");
1089
+ }
1090
+ else if (["claim", "resolve", "reject", "reopen", "close"].includes(A)) {
1091
+ await transition(cfg, "bugs", await resolveId("bugs"), A, o);
1092
+ }
1093
+ else if (A === "transition") {
1094
+ if (!o.to) die("transition 需要 --to <状态>");
1095
+ await transition(cfg, "bugs", await resolveId("bugs"), o.to, o);
1096
+ }
1097
+ else if (A === "comments") await commentsCmd(cfg, "bugs", o, "list");
1098
+ else if (A === "comment") await commentsCmd(cfg, "bugs", o, "add");
1099
+ else if (A === "ai-analyze") printJson(await post(cfg, "/bugs/ai-analyze", optionalJson(o) ?? {}));
1100
+ else die(`未知的 bugs 子命令: ${A}(执行 adev --help 查看用法)`);
1101
+ break;
1102
+ }
1103
+
1104
+ /* ---------- reqs ---------- */
1105
+ case "reqs": {
1106
+ const A = action || "list";
1107
+ if (A === "list") await reqsList(cfg, o);
1108
+ else if (A === "show") await reqsShow(cfg, o);
1109
+ else if (A === "create") {
1110
+ const body = buildBody(o, ["title", "type", "description", "content", "priority"]);
1111
+ if (o.project) body.project_id = await resolveProjectId(cfg, String(o.project));
1112
+ if (!body.title) die("缺少 --title");
1113
+ const d = await post(cfg, "/backlogs", body);
1114
+ console.log(`需求已创建: id=${d.id} ${d.code || ""}`);
1115
+ }
1116
+ else if (A === "update") {
1117
+ const id = await resolveId("backlogs");
1118
+ await put(cfg, `/backlogs/${id}`, buildBody(o, ["title", "type", "description", "content", "priority", "assignee_id"]));
1119
+ console.log("已更新");
1120
+ }
1121
+ else if (A === "delete") { await del(cfg, `/backlogs/${await resolveId("backlogs")}`); console.log("已删除"); }
1122
+ else if (A === "set-test-date") {
1123
+ const id = await resolveId("backlogs");
1124
+ if (!o.date) die("缺少 --date YYYY-MM-DD");
1125
+ await put(cfg, `/backlogs/${id}/test-date`, { test_date: o.date });
1126
+ console.log(`提测时间已设为 ${o.date}`);
1127
+ }
1128
+ else if (A === "data-sources") {
1129
+ const id = await resolveId("backlogs");
1130
+ if (o.data || o.jsonFile) {
1131
+ await put(cfg, `/backlogs/${id}/data-sources`, { items: readJsonInput(o, "数据源清单") });
1132
+ console.log("数据源对接清单已保存");
1133
+ } else printJson(await api(cfg, `/backlogs/${id}/data-sources`));
1134
+ }
1135
+ else if (A === "assign-iteration") {
1136
+ const id = await resolveId("backlogs");
1137
+ if (!o.iteration) die("缺少 --iteration <迭代id>");
1138
+ await put(cfg, `/backlogs/${id}/assign-iteration`, { version_iteration_id: o.iteration });
1139
+ console.log("已分配迭代");
1140
+ }
1141
+ else if (["shelve", "unshelve", "reactivate", "revoke"].includes(A)) {
1142
+ const id = await resolveId("backlogs");
1143
+ await post(cfg, `/backlogs/${id}/${A}`, optionalJson(o) ?? {});
1144
+ console.log(`${A} 完成`);
1145
+ }
1146
+ else die(`未知的 reqs 子命令: ${A}(执行 adev --help 查看用法)`);
1147
+ break;
1148
+ }
1149
+
1150
+ /* ---------- tasks ---------- */
1151
+ case "tasks": {
1152
+ const A = action || "list";
1153
+ if (A === "list") await tasksList(cfg, o);
1154
+ else if (A === "show") {
1155
+ if (!o._[0]) die("缺少 id 参数");
1156
+ printJson(await api(cfg, `/tasks/${o._[0]}`));
1157
+ }
1158
+ else if (A === "create") {
1159
+ const body = buildBody(o, ["title", "type", "description", "priority", "due_date", "estimate_hours", "backlog_id"]);
1160
+ if (o.project) body.project_id = await resolveProjectId(cfg, String(o.project));
1161
+ if (o.assignee) body.assignee_id = await resolveUserId(cfg, o.assignee);
1162
+ if (o.version) body.version_iteration_id = o.version;
1163
+ if (!body.title) die("缺少 --title");
1164
+ const d = await post(cfg, "/tasks", body);
1165
+ console.log(`任务已创建: id=${d.id ?? JSON.stringify(d)}`);
1166
+ }
1167
+ else if (A === "update") {
1168
+ if (!o._[0]) die("缺少 id 参数");
1169
+ const body = buildBody(o, ["title", "type", "description", "priority", "due_date", "status", "estimate_hours"]);
1170
+ if (o.assignee) body.assignee_id = await resolveUserId(cfg, o.assignee);
1171
+ await put(cfg, `/tasks/${o._[0]}`, body);
1172
+ console.log("已更新");
1173
+ }
1174
+ else if (A === "delete") {
1175
+ if (!o._[0]) die("缺少 id 参数");
1176
+ await del(cfg, `/tasks/${o._[0]}`);
1177
+ console.log("已删除");
1178
+ }
1179
+ else if (A === "batch") {
1180
+ const list = readJsonInput(o, "batch");
1181
+ if (!Array.isArray(list)) die("batch 需要 JSON 数组,如 --data '[{\"title\":...},...]'");
1182
+ const d = await post(cfg, "/tasks/batch", list);
1183
+ console.log(`批量创建完成: ${JSON.stringify(d).slice(0, 300)}`);
1184
+ }
1185
+ else die(`未知的 tasks 子命令: ${A}(执行 adev --help 查看用法)`);
1186
+ break;
1187
+ }
1188
+
1189
+ /* ---------- versions ---------- */
1190
+ case "versions": {
1191
+ const A = action || "list";
1192
+ if (A === "list") await versionsList(cfg, o);
1193
+ else if (A === "stats") printJson(await api(cfg, "/versions/stats", await projectParam(cfg, o)));
1194
+ else if (["show", "start", "start-testing", "complete", "accept", "release"].includes(A)) await versionsAction(cfg, o, A);
1195
+ else die(`未知的 versions 子命令: ${A}(执行 adev --help 查看用法)`);
1196
+ break;
1197
+ }
1198
+
1199
+ /* ---------- incidents ---------- */
1200
+ case "incidents": {
1201
+ const A = action || "list";
1202
+ if (A === "list") await incidentsList(cfg, o);
1203
+ else if (A === "show") await incidentsShow(cfg, o);
1204
+ else if (A === "create") {
1205
+ const body = buildBody(o, ["title", "severity", "priority", "description", "actual_behavior", "environment", "source"]);
1206
+ if (o.project) body.project_id = await resolveProjectId(cfg, String(o.project));
1207
+ if (!body.title) die("缺少 --title");
1208
+ const d = await post(cfg, "/incidents", body);
1209
+ console.log(`故障已登记: id=${d.id} ${d.code || ""}`);
1210
+ }
1211
+ else if (A === "update") {
1212
+ const id = await resolveId("incidents");
1213
+ await put(cfg, `/incidents/${id}`, buildBody(o, ["title", "severity", "priority", "description"]));
1214
+ console.log("已更新");
1215
+ }
1216
+ else if (A === "delete") { await del(cfg, `/incidents/${await resolveId("incidents")}`); console.log("已删除"); }
1217
+ else if (["claim", "resolve", "reject", "reopen", "close", "release"].includes(A)) {
1218
+ await transition(cfg, "incidents", await resolveId("incidents"), A, o);
1219
+ }
1220
+ else if (A === "transition") {
1221
+ if (!o.to) die("transition 需要 --to <状态>");
1222
+ await transition(cfg, "incidents", await resolveId("incidents"), o.to, o);
1223
+ }
1224
+ else die(`未知的 incidents 子命令: ${A}(执行 adev --help 查看用法)`);
1225
+ break;
1226
+ }
1227
+
1228
+ /* ---------- tests ---------- */
1229
+ case "tests": {
1230
+ const A = action || "list";
1231
+ if (A === "list") await testsList(cfg, o);
1232
+ else if (A === "show") {
1233
+ if (!o._[0]) die("缺少 id 参数");
1234
+ printJson(await api(cfg, `/test-plans/${o._[0]}`));
1235
+ }
1236
+ else if (A === "cases") {
1237
+ if (!o._[0]) die("缺少 id 参数");
1238
+ printJson(await api(cfg, `/test-plans/version/${o._[0]}/cases`, o.project ? { project_id: await resolveProjectId(cfg, String(o.project)) } : {}));
1239
+ }
1240
+ else if (A === "transition") {
1241
+ if (!o._[0]) die("缺少 id 参数");
1242
+ await put(cfg, `/test-plans/${o._[0]}/transition`, optionalJson(o) ?? {});
1243
+ console.log("已流转");
1244
+ }
1245
+ else die(`未知的 tests 子命令: ${A}(执行 adev --help 查看用法)`);
1246
+ break;
1247
+ }
1248
+
1249
+ /* ---------- knowledge ---------- */
1250
+ case "kb": {
1251
+ const A = action || "list";
1252
+ if (A === "categories") await kbCategories(cfg, o);
1253
+ else if (A === "list") await kbList(cfg, o);
1254
+ else if (A === "show") await kbShow(cfg, o);
1255
+ else if (A === "annotations") await kbAnnotations(cfg, o);
1256
+ else die(`未知的 kb 子命令: ${A}(执行 adev --help 查看用法)`);
1257
+ break;
1258
+ }
1259
+
1260
+ /* ---------- weekly ---------- */
1261
+ case "weekly":
1262
+ await weeklyCmd(cfg, o, action || "list");
1263
+ break;
1264
+ }
1265
+ }
1266
+
1267
+ function invokedDirectly() {
1268
+ const entry = process.argv[1];
1269
+ if (!entry) return false;
1270
+ // npm install -g <本地目录> 在 Windows 上可能以 junction 链接进全局 node_modules,
1271
+ // argv[1] 是链接路径而 import.meta.url 是解析后的真实路径,必须先 realpath 归一化再比较。
1272
+ try {
1273
+ return fs.realpathSync(path.resolve(entry)).toLowerCase()
1274
+ === fs.realpathSync(fileURLToPath(import.meta.url)).toLowerCase();
1275
+ } catch {
1276
+ return path.resolve(entry).toLowerCase() === fileURLToPath(import.meta.url).toLowerCase();
1277
+ }
1278
+ }
1279
+
1280
+ if (invokedDirectly()) {
1281
+ main().catch(e => {
1282
+ if (e instanceof AdevError) console.error(`[adev] ${e.message}`);
1283
+ else console.error(`[adev] ${e.stack || e}`);
1284
+ process.exit(1);
1285
+ });
1286
+ }
1287
+
1288
+ export {
1289
+ AdevError,
1290
+ parseArgs,
1291
+ htmlToText,
1292
+ trunc,
1293
+ displayWidth,
1294
+ buildBody,
1295
+ readJsonInput,
1296
+ applyConfigPatch,
1297
+ applyNameFilter,
1298
+ feedInput,
1299
+ fmtDate,
1300
+ pageNum,
1301
+ asItems,
1302
+ imageExt,
1303
+ resolveAssetUrl,
1304
+ normalizeConfig,
1305
+ withLogin,
1306
+ isPasswordSession,
1307
+ authLabel,
1308
+ // autofix 子模块复用的内部 API 适配(只读 + 明确的写接口)
1309
+ loadConfig,
1310
+ api,
1311
+ post,
1312
+ put,
1313
+ del,
1314
+ me,
1315
+ request,
1316
+ resolveResourceId,
1317
+ downloadImages,
1318
+ imageDir,
1319
+ };