@vocvx/aiv-cli 0.0.0-stage → 0.1.1

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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +98 -2
  3. package/aiv.mjs +1347 -0
  4. package/package.json +38 -4
package/aiv.mjs ADDED
@@ -0,0 +1,1347 @@
1
+ #!/usr/bin/env node
2
+ // AIV 命令行:解析需求、启动验证、看报告树、看影响面。
3
+ // 只通过 HTTP 与平台交互,不直连数据库,也不在本地跑浏览器。
4
+ import { execFileSync } from "node:child_process";
5
+ import fsSync from "node:fs";
6
+ import os from "node:os";
7
+ import pathMod from "node:path";
8
+
9
+ const CONFIG_DIR = pathMod.join(os.homedir(), ".aiv");
10
+ const CONFIG_PATH = pathMod.join(CONFIG_DIR, "config.json");
11
+
12
+ function readConfig() {
13
+ try {
14
+ return JSON.parse(fsSync.readFileSync(CONFIG_PATH, "utf8")) || {};
15
+ } catch {
16
+ return {};
17
+ }
18
+ }
19
+
20
+ function writeConfig(next) {
21
+ fsSync.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
22
+ fsSync.writeFileSync(CONFIG_PATH, JSON.stringify(next, null, 2), { mode: 0o600 });
23
+ }
24
+
25
+ const config = readConfig();
26
+ // 优先级:环境变量 > ~/.aiv/config.json(aiv login 写入)> 官方平台地址
27
+ // 自建部署用 --server 或 AIV_API_URL 指过去;本地开发通常 AIV_API_URL=http://127.0.0.1:4174。
28
+ const DEFAULT_BASE = "https://aiv.vocvx.com";
29
+ const BASE = (process.env.AIV_API_URL || config.apiUrl || DEFAULT_BASE).replace(/\/+$/, "");
30
+ const TOKEN = process.env.AIV_API_TOKEN || config.apiToken || "";
31
+
32
+ function authHeaders(extra = {}) {
33
+ return { ...extra, ...(TOKEN ? { authorization: `Bearer ${TOKEN}` } : {}) };
34
+ }
35
+
36
+ const args = process.argv.slice(2);
37
+ const command = args[0] || "help";
38
+ // aiv <命令> --help / -h:任何命令都先打用法,避免误触发登录、验证等有副作用的操作。
39
+ const helpRequested = args.slice(1).some((arg) => arg === "--help" || arg === "-h");
40
+
41
+ if (["--version", "-v", "version"].includes(command)) {
42
+ let version = "0.1.0";
43
+ try {
44
+ const pkg = JSON.parse(fsSync.readFileSync(new URL("./package.json", import.meta.url), "utf8"));
45
+ version = pkg.version || version;
46
+ } catch {
47
+ // 单独分发 aiv.mjs 时没有 package.json,用内置版本号
48
+ }
49
+ console.log(`aiv ${version}`);
50
+ process.exit(0);
51
+ }
52
+ const rest = args.slice(1);
53
+
54
+ function flag(name) {
55
+ return rest.includes(`--${name}`);
56
+ }
57
+
58
+ function option(name, fallback = "") {
59
+ const index = rest.indexOf(`--${name}`);
60
+ if (index === -1) return fallback;
61
+ const value = rest[index + 1];
62
+ return value && !value.startsWith("--") ? value : fallback;
63
+ }
64
+
65
+ // 支持重复出现的参数(例如多个 --file)。返回所有取值。
66
+ function options(name) {
67
+ const values = [];
68
+ rest.forEach((item, index) => {
69
+ if (item !== `--${name}`) return;
70
+ const value = rest[index + 1];
71
+ if (value && !value.startsWith("--")) values.push(value);
72
+ });
73
+ return values;
74
+ }
75
+
76
+ function positional() {
77
+ return rest.filter((item, index) => {
78
+ if (item.startsWith("--")) return false;
79
+ const previous = rest[index - 1];
80
+ return !(previous && previous.startsWith("--"));
81
+ });
82
+ }
83
+
84
+ // 连不上时给一句人话:fetch 的 "fetch failed" 对使用者毫无信息量。
85
+ async function fetchOrExplain(url, init) {
86
+ try {
87
+ return await fetch(url, init);
88
+ } catch (error) {
89
+ const code = error?.cause?.code || error?.code || "";
90
+ const reason = {
91
+ ENOTFOUND: "域名解析失败,检查 --server 地址是否正确",
92
+ ECONNREFUSED: "连接被拒绝,确认平台服务已启动且端口正确",
93
+ ETIMEDOUT: "连接超时,检查网络 / 防火墙 / 安全组",
94
+ CERT_HAS_EXPIRED: "证书已过期",
95
+ DEPTH_ZERO_SELF_SIGNED_CERT: "自签名证书:可设 NODE_EXTRA_CA_CERTS 指向 CA 文件",
96
+ UNABLE_TO_VERIFY_LEAF_SIGNATURE: "证书链不完整:可设 NODE_EXTRA_CA_CERTS 指向 CA 文件",
97
+ SELF_SIGNED_CERT_IN_CHAIN: "证书链含自签名证书:可设 NODE_EXTRA_CA_CERTS 指向 CA 文件",
98
+ }[code] || error?.cause?.message || error?.message || "未知错误";
99
+ const fallback = BASE === DEFAULT_BASE ? ";如果连的是自建部署,请加 --server <你的平台地址>(或 export AIV_API_URL=...)" : "";
100
+ const hint = new Error(`无法连接 ${BASE}:${reason}${code ? `(${code})` : ""}${fallback}`);
101
+ hint.status = 0;
102
+ throw hint;
103
+ }
104
+ }
105
+
106
+ async function call(pathname, init) {
107
+ const response = await fetchOrExplain(`${BASE}${pathname}`, {
108
+ ...init,
109
+ headers: authHeaders({ "content-type": "application/json", ...(init?.headers || {}) }),
110
+ });
111
+ const text = await response.text();
112
+ let body;
113
+ try {
114
+ body = text ? JSON.parse(text) : {};
115
+ } catch {
116
+ body = { raw: text };
117
+ }
118
+ if (!response.ok) {
119
+ const message = body?.error || `HTTP ${response.status}`;
120
+ const error = new Error(message);
121
+ error.status = response.status;
122
+ throw error;
123
+ }
124
+ return body;
125
+ }
126
+
127
+ // 文档上传是 multipart,不能走 call() 的 JSON 头。
128
+ async function callForm(pathname, form) {
129
+ const response = await fetch(`${BASE}${pathname}`, {
130
+ method: "POST",
131
+ headers: authHeaders(),
132
+ body: form,
133
+ });
134
+ const text = await response.text();
135
+ let body;
136
+ try {
137
+ body = text ? JSON.parse(text) : {};
138
+ } catch {
139
+ body = { raw: text };
140
+ }
141
+ if (!response.ok) {
142
+ const error = new Error(body?.error || `HTTP ${response.status}`);
143
+ error.status = response.status;
144
+ throw error;
145
+ }
146
+ return body;
147
+ }
148
+
149
+ const LOCAL_PROJECT_FILE = ".aiv.json";
150
+
151
+ // 当前目录所在 Git 仓库根目录(不在 Git 里就用 cwd)。
152
+ function gitRoot(startDir = process.cwd()) {
153
+ try {
154
+ const root = execFileSync("git", ["rev-parse", "--show-toplevel"], {
155
+ cwd: startDir,
156
+ encoding: "utf8",
157
+ stdio: ["ignore", "pipe", "ignore"],
158
+ }).trim();
159
+ return root || startDir;
160
+ } catch {
161
+ return startDir;
162
+ }
163
+ }
164
+
165
+ function readLocalProject(startDir = process.cwd()) {
166
+ let dir = pathMod.resolve(startDir);
167
+ for (let depth = 0; depth < 6; depth += 1) {
168
+ const candidate = pathMod.join(dir, LOCAL_PROJECT_FILE);
169
+ try {
170
+ const parsed = JSON.parse(fsSync.readFileSync(candidate, "utf8"));
171
+ if (parsed?.projectId) return { ...parsed, file: candidate };
172
+ } catch {
173
+ // 继续向上找
174
+ }
175
+ const parent = pathMod.dirname(dir);
176
+ if (parent === dir) break;
177
+ dir = parent;
178
+ }
179
+ return null;
180
+ }
181
+
182
+ function writeLocalProject(payload, rootDir = gitRoot()) {
183
+ const file = pathMod.join(rootDir, LOCAL_PROJECT_FILE);
184
+ fsSync.writeFileSync(file, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
185
+ return file;
186
+ }
187
+
188
+ // 手动输入的地址/路径要能被平台直接使用:地址补协议并校验,路径展开 ~ 后确认是目录。
189
+ function normalizeUrl(value) {
190
+ const raw = String(value || "").trim();
191
+ if (!raw) return "";
192
+ const withScheme = /^https?:\/\//i.test(raw) ? raw : `http://${raw}`;
193
+ try {
194
+ const parsed = new URL(withScheme);
195
+ if (!parsed.hostname) throw new Error("no host");
196
+ } catch {
197
+ throw new Error(`访问地址不合法:${value}(示例:http://127.0.0.1:5173 或 aiv.vocvx.com)`);
198
+ }
199
+ return withScheme.replace(/\/+$/, "") || withScheme;
200
+ }
201
+
202
+ function normalizeSourceDir(value) {
203
+ const raw = String(value || "").trim();
204
+ if (!raw) return "";
205
+ const expanded = raw.replace(/^~(?=$|\/)/, os.homedir());
206
+ const target = pathMod.resolve(expanded);
207
+ let stat;
208
+ try {
209
+ stat = fsSync.statSync(target);
210
+ } catch {
211
+ throw new Error(`源码目录不存在:${target}`);
212
+ }
213
+ if (!stat.isDirectory()) throw new Error(`源码路径不是文件夹:${target}`);
214
+ return target;
215
+ }
216
+
217
+ // ---- 本次测哪部分代码 ----
218
+ // 默认 working:有未提交改动就测改动;工作区干净自动回退到最近一次提交;all 扫整个仓库。
219
+ const SCOPE_ALIASES = {
220
+ working: "working",
221
+ uncommitted: "working",
222
+ "working-tree": "working",
223
+ commit: "latest-commit",
224
+ latest: "latest-commit",
225
+ "latest-commit": "latest-commit",
226
+ all: "all",
227
+ full: "all",
228
+ repo: "all",
229
+ };
230
+
231
+ function requestedScope() {
232
+ const raw = option("scope");
233
+ if (!raw) return "working";
234
+ const normalized = SCOPE_ALIASES[String(raw).toLowerCase()];
235
+ if (!normalized) {
236
+ throw new Error("--scope 只能是 working(未提交改动,默认)、commit(最近一次提交)或 all(全部代码)。");
237
+ }
238
+ return normalized;
239
+ }
240
+
241
+ function gitOutput(root, args) {
242
+ try {
243
+ return execFileSync("git", args, {
244
+ cwd: root,
245
+ encoding: "utf8",
246
+ stdio: ["ignore", "pipe", "ignore"],
247
+ });
248
+ } catch {
249
+ return null;
250
+ }
251
+ }
252
+
253
+ // 本地预览用:和平台判定规则一致(未提交 → 干净时最近一次提交),只是提前告诉用户测什么。
254
+ function detectLocalChanges(root) {
255
+ const inside = gitOutput(root, ["rev-parse", "--is-inside-work-tree"]);
256
+ if (!inside || inside.trim() !== "true") return { available: false, reason: "不是 Git 仓库" };
257
+ const status = gitOutput(root, ["status", "--porcelain", "--untracked-files=all"]);
258
+ if (status === null) return { available: false, reason: "无法读取工作区改动" };
259
+ const files = status
260
+ .split("\n")
261
+ .map((line) => line.trim())
262
+ .filter(Boolean)
263
+ .filter((line) => !line.slice(0, 2).includes("D"))
264
+ .map((line) => line.replace(/^.{2}\s+/, "").replace(/^.* -> /, ""))
265
+ // 平台自己写的文件不算代码改动。
266
+ .filter((file) => file !== ".aiv.json" && !file.endsWith("/.aiv.json") && !/(^|\/)aiv-reports\//.test(file));
267
+ if (files.length) return { available: true, mode: "working", files };
268
+ const commit = gitOutput(root, ["rev-parse", "--short", "HEAD"]);
269
+ return {
270
+ available: true,
271
+ mode: commit ? "latest-commit" : "none",
272
+ commit: commit ? commit.trim() : null,
273
+ files: [],
274
+ };
275
+ }
276
+
277
+ function describeScope(scope, root, { remote = false } = {}) {
278
+ if (scope === "all") return "全部代码(--scope all)";
279
+ // 远端执行节点上的仓库本地看不到,只能说明规则,具体文件由节点计算。
280
+ if (remote) {
281
+ return scope === "latest-commit"
282
+ ? "最近一次提交(由执行节点计算)"
283
+ : "未提交改动,工作区干净时自动回退最近一次提交(由执行节点计算)";
284
+ }
285
+ const changes = detectLocalChanges(root);
286
+ if (!changes.available) return `全部代码(${changes.reason})`;
287
+ if (scope === "latest-commit") {
288
+ return changes.mode === "working"
289
+ ? `最近一次提交 ${changes.commit || "HEAD"}(工作区还有 ${changes.files.length} 个未提交改动,本次不测)`
290
+ : `最近一次提交 ${changes.commit || "HEAD"}`;
291
+ }
292
+ if (changes.mode === "working") return `未提交改动 ${changes.files.length} 个文件`;
293
+ if (changes.mode === "latest-commit") return `最近一次提交 ${changes.commit}(工作区干净,自动回退)`;
294
+ return "全部代码(仓库还没有提交)";
295
+ }
296
+
297
+ async function applyScope(project, scope) {
298
+ if ((project.codeAnalysisScope || "working") === scope) return project;
299
+ const updated = await call(`/api/projects/${project.id}`, {
300
+ method: "PUT",
301
+ body: JSON.stringify({ codeAnalysisScope: scope }),
302
+ });
303
+ project.codeAnalysisScope = updated?.codeAnalysisScope || scope;
304
+ return project;
305
+ }
306
+
307
+ async function listProjects() {
308
+ const bootstrap = await call("/api/bootstrap");
309
+ return (bootstrap.products || []).flatMap((product) =>
310
+ (product.projects || []).map((project) => ({ ...project, productName: product.name })),
311
+ );
312
+ }
313
+
314
+ function samePath(left, right) {
315
+ if (!left || !right) return false;
316
+ const normalize = (value) => pathMod.resolve(String(value)).replace(/\/+$/, "").toLowerCase();
317
+ try {
318
+ return normalize(fsSync.realpathSync(left)) === normalize(fsSync.realpathSync(right));
319
+ } catch {
320
+ return normalize(left) === normalize(right);
321
+ }
322
+ }
323
+
324
+ async function findProject(query) {
325
+ const projects = await listProjects();
326
+ const match = projects.find((project) => project.id === query) || projects.find((project) => project.name === query);
327
+ if (!match) {
328
+ const names = projects.map((project) => `${project.name}(${project.id})`).join("、");
329
+ throw new Error(`未找到项目「${query}」。可用项目:${names || "无"}`);
330
+ }
331
+ return match;
332
+ }
333
+
334
+ // 没传 --project 时按「.aiv.json → 仓库路径 → 目录名」自动识别项目。
335
+ async function detectProject() {
336
+ const local = readLocalProject();
337
+ if (local?.projectId) {
338
+ try {
339
+ return { ...(await findProject(local.projectId)), detectedBy: `.aiv.json(${local.file})` };
340
+ } catch {
341
+ // 本地记录失效就继续自动匹配
342
+ }
343
+ }
344
+ const root = gitRoot();
345
+ const projects = await listProjects();
346
+ const byPath = projects.find((project) => samePath(project.codeRepositoryPath, root));
347
+ if (byPath) {
348
+ try {
349
+ writeLocalProject({ projectId: byPath.id, projectName: byPath.name, codePath: root, url: byPath.url || "" }, root);
350
+ } catch {
351
+ // 目录只读时忽略,不影响本次识别
352
+ }
353
+ return { ...byPath, detectedBy: `代码路径 ${root}` };
354
+ }
355
+ const dirName = pathMod.basename(root).toLowerCase();
356
+ const byName = projects.filter((project) => String(project.name || "").toLowerCase() === dirName);
357
+ if (byName.length === 1) {
358
+ try {
359
+ writeLocalProject({ projectId: byName[0].id, projectName: byName[0].name, codePath: root, url: byName[0].url || "" }, root);
360
+ } catch {
361
+ // 忽略只读目录
362
+ }
363
+ return { ...byName[0], detectedBy: `目录名 ${dirName}` };
364
+ }
365
+ const names = projects.map((project) => `${project.name}(${project.id})`).join("、");
366
+ throw new Error(
367
+ `无法自动识别当前目录对应的项目(${root})。请指定 --project <id|名称>,或先运行 aiv init 绑定。\n可用项目:${names || "无"}`,
368
+ );
369
+ }
370
+
371
+ // --project 传了就按它;没传就自动识别(打印识别依据,避免静默跑错项目)。
372
+ async function resolveProject(query, { quiet = false } = {}) {
373
+ if (query) return findProject(query);
374
+ if (process.env.AIV_PROJECT) return findProject(process.env.AIV_PROJECT);
375
+ const project = await detectProject();
376
+ if (!quiet) console.log(`· 已自动识别项目「${project.name}」(依据:${project.detectedBy})`);
377
+ return project;
378
+ }
379
+
380
+ // 本地开发地址探测:package.json 里 vite/web 脚本的端口,或常见端口。
381
+ function detectLocalUrl() {
382
+ const root = gitRoot();
383
+ const ports = new Set();
384
+ try {
385
+ const pkg = JSON.parse(fsSync.readFileSync(pathMod.join(root, "package.json"), "utf8"));
386
+ for (const value of Object.values(pkg.scripts || {})) {
387
+ const match = String(value).match(/--port[=\s]+(\d{2,5})/);
388
+ if (match) ports.add(Number(match[1]));
389
+ }
390
+ } catch {
391
+ // 没有 package.json 就只看常见端口
392
+ }
393
+ for (const configName of ["vite.config.ts", "vite.config.js", "vite.config.mjs"]) {
394
+ try {
395
+ const text = fsSync.readFileSync(pathMod.join(root, configName), "utf8");
396
+ const match = text.match(/port:\s*(\d{2,5})/);
397
+ if (match) ports.add(Number(match[1]));
398
+ } catch {
399
+ // 忽略
400
+ }
401
+ }
402
+ for (const port of [3000, 5173, 3173, 8080, 8000]) ports.add(port);
403
+ return [...ports].map((port) => `http://127.0.0.1:${port}`);
404
+ }
405
+
406
+ // 设备授权登录:CLI 发起 → 浏览器点一下授权 → CLI 轮询拿到 Token。
407
+ function openBrowser(url) {
408
+ if (flag("no-browser") || process.env.AIV_NO_BROWSER === "1") return;
409
+ try {
410
+ if (process.platform === "darwin") execFileSync("open", [url], { stdio: "ignore" });
411
+ else if (process.platform === "win32") execFileSync("cmd", ["/c", "start", "", url], { stdio: "ignore" });
412
+ else execFileSync("xdg-open", [url], { stdio: "ignore" });
413
+ } catch {
414
+ // 打不开浏览器不算失败:地址已经打印出来了,用户手动打开即可
415
+ }
416
+ }
417
+
418
+ async function waitForBrowserApproval(server, code, intervalSeconds = 2) {
419
+ const deadline = Date.now() + 10 * 60 * 1000;
420
+ process.stdout.write(" 等待浏览器授权");
421
+ while (Date.now() < deadline) {
422
+ await new Promise((resolve) => setTimeout(resolve, Math.max(intervalSeconds, 1) * 1000));
423
+ process.stdout.write(".");
424
+ let response;
425
+ try {
426
+ response = await fetch(`${server}/api/cli/pair/status?code=${encodeURIComponent(code)}`);
427
+ } catch {
428
+ continue;
429
+ }
430
+ if (response.status === 404) throw new Error("授权码已过期,请重新执行 aiv login。");
431
+ if (!response.ok) continue;
432
+ const body = await response.json().catch(() => ({}));
433
+ if (body.status === "approved" && body.token) {
434
+ process.stdout.write("\n");
435
+ return body;
436
+ }
437
+ }
438
+ process.stdout.write("\n");
439
+ throw new Error("等待授权超时(10 分钟),请重新执行 aiv login。");
440
+ }
441
+
442
+ async function loginWithBrowser(server) {
443
+ const response = await fetch(`${server}/api/cli/pair/start`, {
444
+ method: "POST",
445
+ headers: { "content-type": "application/json" },
446
+ body: JSON.stringify({ device: os.hostname() }),
447
+ });
448
+ const started = await response.json().catch(() => ({}));
449
+ if (!response.ok) {
450
+ // 老版本平台没有这个接口:会被登录闸门拦成 LOGIN_REQUIRED / 404,给出可继续操作的建议。
451
+ const missing = response.status === 404 || started.code === "LOGIN_REQUIRED";
452
+ const hint = missing ? "\n 这台平台的版本还没启用浏览器授权,可以先用:aiv login --phone <手机号>" : "";
453
+ throw new Error(`${started.error || `无法发起浏览器授权(HTTP ${response.status})`}${hint}`);
454
+ }
455
+
456
+ console.log("请在浏览器中确认授权(已尝试自动打开):");
457
+ console.log(` ${started.verifyUrl}`);
458
+ console.log(` 登录码:${started.code}(10 分钟内有效,只能使用一次)`);
459
+ openBrowser(started.verifyUrl);
460
+ if (!process.stdin.isTTY) console.log(" 当前不是交互终端,仍在后台等待授权…");
461
+
462
+ const result = await waitForBrowserApproval(server, started.code, started.interval || 2);
463
+ // 地址以「CLI 自己刚刚连通的地址」为准:显式传了 --server / AIV_API_URL 就记它,
464
+ // 否则用平台回报的公网地址(这样内网 CLI 也能记下对外可用的域名)。
465
+ const explicitServer = Boolean(option("server") || process.env.AIV_API_URL);
466
+ const apiUrl = explicitServer ? server : (result.serverUrl || server);
467
+ writeConfig({ ...readConfig(), apiUrl, apiToken: result.token });
468
+ console.log(`已登录:${CONFIG_PATH}`);
469
+ console.log(` 平台:${apiUrl} · Token 已保存(授权账号:${result.approvedBy || "当前登录账号"})`);
470
+ console.log(" 下一步:在当前项目目录运行 aiv init(绑定项目)或 aiv parse(解析 + 验证)");
471
+ }
472
+
473
+ async function promptLine(question) {
474
+ const readline = await import("node:readline");
475
+ return new Promise((resolve) => {
476
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
477
+ rl.question(question, (answer) => {
478
+ rl.close();
479
+ resolve(answer.trim());
480
+ });
481
+ });
482
+ }
483
+
484
+ const ASSET_SKIP = new Set(["node_modules", "dist", "build", ".git", "data", ".venv", "__pycache__", "coverage"]);
485
+ const PRD_DIR_HINTS = ["prd", "需求", "requirements", "spec", "specs"];
486
+ const UED_DIR_HINTS = ["ued", "设计", "design", "designs", "prototype", "原型", "mockup", "mockups"];
487
+ const PRD_EXTENSIONS = [".md", ".docx", ".pdf", ".txt"];
488
+ const UED_EXTENSIONS = [".html", ".htm", ".png", ".jpg", ".jpeg", ".pdf"];
489
+ const ASSET_MAX_DEPTH = 3;
490
+
491
+ // 在项目仓库里找 PRD / UED 素材:先看目录名提示,再看文件名关键字。
492
+ function discoverAssets(root = gitRoot()) {
493
+ const found = [];
494
+ const walk = (dir, depth) => {
495
+ if (depth > ASSET_MAX_DEPTH) return;
496
+ let entries = [];
497
+ try {
498
+ entries = fsSync.readdirSync(dir, { withFileTypes: true });
499
+ } catch {
500
+ return;
501
+ }
502
+ for (const entry of entries) {
503
+ if (entry.name.startsWith(".") || ASSET_SKIP.has(entry.name)) continue;
504
+ const full = pathMod.join(dir, entry.name);
505
+ if (entry.isDirectory()) {
506
+ walk(full, depth + 1);
507
+ continue;
508
+ }
509
+ const extension = pathMod.extname(entry.name).toLowerCase();
510
+ const lowerDir = pathMod.dirname(pathMod.relative(root, full)).toLowerCase();
511
+ const lowerName = entry.name.toLowerCase();
512
+ const dirParts = lowerDir.split(pathMod.sep);
513
+ const inPrdDir = PRD_DIR_HINTS.some((hint) => dirParts.some((part) => part.includes(hint)));
514
+ const inUedDir = UED_DIR_HINTS.some((hint) => dirParts.some((part) => part.includes(hint)));
515
+ const looksPrd = /prd|需求|requirement|spec/.test(lowerName);
516
+ const looksUed = /ued|设计|design|prototype|原型|mock/.test(lowerName);
517
+ if (PRD_EXTENSIONS.includes(extension) && (inPrdDir || looksPrd)) {
518
+ found.push({ file: full, kind: "prd", name: entry.name });
519
+ } else if (UED_EXTENSIONS.includes(extension) && (inUedDir || looksUed)) {
520
+ found.push({ file: full, kind: "ued", name: entry.name });
521
+ }
522
+ }
523
+ };
524
+ walk(root, 0);
525
+ // 同一份文件只留一次;最多各取 5 份,避免把整个仓库传上去。
526
+ const unique = [...new Map(found.map((item) => [item.file, item])).values()];
527
+ const pick = (kind) => unique.filter((item) => item.kind === kind).slice(0, 5);
528
+ return [...pick("prd"), ...pick("ued")];
529
+ }
530
+
531
+ async function probeUrl(url) {
532
+ try {
533
+ const response = await fetch(url, { signal: AbortSignal.timeout(2500), redirect: "manual" });
534
+ return response.status < 500;
535
+ } catch {
536
+ return false;
537
+ }
538
+ }
539
+
540
+ function printRows(title, rows) {
541
+ console.log(`\n${title}`);
542
+ for (const row of rows) console.log(` ${row}`);
543
+ console.log("");
544
+ }
545
+
546
+ // 报告是验证的最终产物:先打印摘要,再把 PDF 落到本地目录,用户不用再记 ID。
547
+ function printReportSummary(report) {
548
+ if (!report) return console.log("\n验证完成,但本次没有生成报告。");
549
+ console.log(`\n报告 ${report.id} · ${report.conclusion} · 覆盖 ${report.coverage}/${report.totalRequirements}`);
550
+ if (report.prioritySummary) {
551
+ const { URGENT = 0, CRITICAL = 0, HIGH = 0, MEDIUM = 0, LOW = 0 } = report.prioritySummary;
552
+ console.log(` 优先级:紧急 ${URGENT} · 严重 ${CRITICAL} · 高 ${HIGH} · 中 ${MEDIUM} · 低 ${LOW}`);
553
+ }
554
+ if (report.fingerprint) {
555
+ console.log(` 指纹:Prompt ${report.fingerprint.promptVersion} · 源码 ${String(report.fingerprint.sourceCommit || "未记录").slice(0, 8)} · 应用 ${report.fingerprint.appVersion || "未暴露"}`);
556
+ }
557
+ }
558
+
559
+ async function downloadReportPdf(reportId, out) {
560
+ const fs = await import("node:fs/promises");
561
+ const path = await import("node:path");
562
+ const target = path.resolve(out || path.join("aiv-reports", `${reportId}.pdf`));
563
+ const response = await fetch(`${BASE}/api/reports/${reportId}/export.pdf`, { headers: authHeaders() });
564
+ if (!response.ok) {
565
+ const payload = await response.json().catch(() => ({}));
566
+ throw new Error(payload.error || `导出失败(${response.status})`);
567
+ }
568
+ const buffer = Buffer.from(await response.arrayBuffer());
569
+ await fs.mkdir(path.dirname(target), { recursive: true });
570
+ await fs.writeFile(target, buffer);
571
+ return { file: target, bytes: buffer.length };
572
+ }
573
+
574
+ async function saveProject(project) {
575
+ await call(`/api/projects/${project.id}`, {
576
+ method: "PUT",
577
+ body: JSON.stringify({ name: project.name, url: project.url, saved: true }),
578
+ });
579
+ }
580
+
581
+ // 启动验证 → 轮询进度 → 打印报告摘要 → 下载 PDF。parse / verify 共用同一段流程。
582
+ async function runVerification(project, { json = false, extra = {} } = {}) {
583
+ let task;
584
+ try {
585
+ task = await call(`/api/projects/${project.id}/verification-tasks`, { method: "POST", body: "{}" });
586
+ } catch (error) {
587
+ if (/请先完成需求解析并保存项目/.test(error.message)) {
588
+ throw new Error(`${error.message}(提示:先运行 aiv parse --project ${project.name},或使用 aiv verify --parse 让 CLI 自动解析并保存)`);
589
+ }
590
+ throw error;
591
+ }
592
+ if (!json) console.log(`任务 ${task.id} 已创建(${project.name}),等待执行…`);
593
+ if (flag("no-wait")) {
594
+ if (json) console.log(JSON.stringify(task, null, 2));
595
+ else console.log("(--no-wait:已提交,稍后用 aiv report <报告ID> 查看结果)");
596
+ return task;
597
+ }
598
+ let lastStatus = "";
599
+ let pendingTicks = 0;
600
+ for (;;) {
601
+ await new Promise((resolve) => setTimeout(resolve, 3000));
602
+ const current = await call(`/api/verification-tasks/${task.id}`);
603
+ if (current.status !== lastStatus) {
604
+ lastStatus = current.status;
605
+ if (!json) console.log(` ${current.status} · ${current.phase || ""}`);
606
+ }
607
+ // 排队超过 1 分钟仍没开始:多半是没有可用的执行节点,先给出可执行的下一步,别让人干等。
608
+ pendingTicks = current.status === "PENDING" ? pendingTicks + 1 : 0;
609
+ if (pendingTicks === 20) {
610
+ const boot = await call("/api/bootstrap").catch(() => ({}));
611
+ const online = (boot.runners || []).filter((runner) => runner.status === "online");
612
+ if (!boot.runnerAvailable && !online.length) {
613
+ throw new Error(
614
+ `任务 ${task.id} 仍在排队:平台没有可用的执行节点(Runner)。\n`
615
+ + " · 启动本机 Runner(见 USAGE-CLI「执行节点」)后任务会自动继续\n"
616
+ + ` · 报告生成后用 aiv report <报告ID> 查看,本命令可先用 --no-wait 提交任务`,
617
+ );
618
+ }
619
+ }
620
+ if (!["COMPLETED", "FAILED", "CANCELLED"].includes(current.status)) continue;
621
+ if (current.status !== "COMPLETED") {
622
+ const reason = current.error || current.status;
623
+ const runnerHint = /runner|执行节点|节点|no device/i.test(reason)
624
+ ? "\n 提示:验证需要执行节点(Runner)在线,见 USAGE-CLI 的「执行节点」一节。"
625
+ : "";
626
+ throw new Error(`验证任务未完成:${reason}${runnerHint}`);
627
+ }
628
+ const report = current.reportId ? await call(`/api/reports/${current.reportId}`) : null;
629
+ let pdf = null;
630
+ if (report && !flag("no-export")) {
631
+ try {
632
+ pdf = await downloadReportPdf(report.id, option("out"));
633
+ } catch (error) {
634
+ // 导出失败不该吞掉报告本身:提示后仍返回摘要。
635
+ if (json) pdf = { error: error.message };
636
+ else console.log(` ! PDF 导出失败:${error.message}(可用 aiv export --report ${report.id} 重试)`);
637
+ }
638
+ }
639
+ if (json) {
640
+ console.log(JSON.stringify({ ...extra, task: current, report, pdf }, null, 2));
641
+ return;
642
+ }
643
+ printReportSummary(report);
644
+ if (pdf) console.log(` PDF:${pdf.file}(${(pdf.bytes / 1024 / 1024).toFixed(1)} MB)`);
645
+ if (report) {
646
+ console.log(` 平台查看:${BASE} → 验收报告 · ${report.id}`);
647
+ console.log(` 明细:aiv tree --report ${report.id} · aiv ued --report ${report.id} · aiv export --report ${report.id}`);
648
+ }
649
+ console.log("");
650
+ return;
651
+ }
652
+ }
653
+
654
+ function renderTree(nodes, depth = 0) {
655
+ for (const node of nodes) {
656
+ const status = node.priorityLabel || node.status || "";
657
+ const badge = status ? ` [${status}]` : "";
658
+ console.log(`${" ".repeat(depth)}- ${node.label}${badge}`);
659
+ if (node.children?.length) renderTree(node.children, depth + 1);
660
+ }
661
+ }
662
+
663
+ async function runProductKnowledge(action, productQuery) {
664
+ const bootstrap = await call("/api/bootstrap");
665
+ const product = (bootstrap.products || []).find(
666
+ (item) => item.id === productQuery || item.name === productQuery,
667
+ );
668
+ if (!product) {
669
+ const names = (bootstrap.products || []).map((item) => `${item.name}(${item.id})`).join("、");
670
+ throw new Error(`未找到产品「${productQuery}」。可用产品:${names || "无"}`);
671
+ }
672
+ if (action === "build") {
673
+ const result = await call(`/api/products/${product.id}/knowledge/build`, {
674
+ method: "POST",
675
+ body: JSON.stringify({ useAi: !flag("no-ai") }),
676
+ });
677
+ if (flag("json")) return console.log(JSON.stringify(result, null, 2));
678
+ const { build } = result;
679
+ console.log(`\n${product.name} · 产品共享知识重建完成(${(build.elapsedMs / 1000).toFixed(1)}s · ${build.projects} 个项目)`);
680
+ for (const [level, info] of Object.entries(build.levels)) {
681
+ if (!info.entries) continue;
682
+ console.log(` ${level} ${info.label}:${info.entries} 条 / ${info.chars} 字`);
683
+ }
684
+ console.log(` 共享页面 ${build.sharedPages} 个 · 向量 ${build.vectors?.provider || "无"}(${build.vectors?.pgvector?.written || 0} 条入库)`);
685
+ if (build.warnings?.length) build.warnings.forEach((item) => console.log(` ! ${item}`));
686
+ return console.log("");
687
+ }
688
+ const summary = await call(`/api/products/${product.id}/knowledge`);
689
+ if (flag("json")) return console.log(JSON.stringify(summary, null, 2));
690
+ const { levels, lastBuild } = summary.summary;
691
+ console.log(`\n${product.name} · 产品共享知识`);
692
+ for (const [level, info] of Object.entries(levels)) {
693
+ if (!info.entries) continue;
694
+ console.log(` ${level} ${info.label}:${info.entries} 条 / ${info.chars} 字`);
695
+ }
696
+ if (lastBuild) {
697
+ console.log(` 覆盖项目 ${lastBuild.projects || 0} 个 · 共享页面 ${lastBuild.sharedPages || 0} 个 · 最近构建 ${lastBuild.builtAt}`);
698
+ } else {
699
+ console.log(" 尚未构建,运行 aiv kb build --product " + product.name);
700
+ }
701
+ console.log("");
702
+ }
703
+
704
+ const commands = {
705
+ async help() {
706
+ console.log(`AIV CLI · 用法
707
+
708
+ aiv login [--server <平台地址>] 登录:打开网页授权,点一下就完成(推荐)
709
+ aiv login --no-browser 只打印授权链接,不自动开浏览器(SSH / 纯终端)
710
+ aiv login --phone <手机号> | --code <登录码> | --token <Token>
711
+ 备用登录方式:短信验证码 / 一次性登录码 / API Token(CI)
712
+ aiv init [--project <id|名称>] [--url <地址>] [--path <源码目录>] [--scope working|commit|all]
713
+ 绑定项目:自动识别源码路径/探测本地地址,也可手动指定,写 .aiv.json
714
+ aiv logout 清除本地 Token
715
+ aiv usage 查看当前 Token 余额与扣点记录
716
+ aiv config [--project <id|名称>] [--url <地址>] [--path <源码目录>] [--login-path <路径>]
717
+ [--depth basic|deep|expert] [--scope working|commit|all] [--name <名称>] [--save]
718
+ 修改项目配置(不传参数 = 查看当前配置)
719
+ aiv upload [--project <id|名称>] --file <文件> [--file <文件>...] [--kind prd|ued]
720
+ 上传 PRD / UED(默认按扩展名自动识别)
721
+ aiv parse [--project <id|名称>] [--paste-file <文件>] 一条命令跑完:解析需求 → 保存 → 验证 → 报告落盘
722
+ [--no-verify] [--no-wait] [--out <文件>] [--no-export] [--json]
723
+ [--scope working|commit|all] 测哪部分代码(默认 working:未提交改动,干净时回退最近一次提交)
724
+ aiv verify [--project <id|名称>] [--parse] [--no-wait] [--out <文件>] [--no-export] [--json]
725
+ [--scope working|commit|all] 启动验证并等结果(不传项目则自动识别当前仓库)
726
+ aiv requirements --project <id|名称> [--json] 需求清单
727
+ aiv tree --report <报告ID> [--view issues] [--json] 需求 / 问题树
728
+ aiv impact --report <报告ID> [--json] 影响面分析
729
+ aiv ued --report <报告ID> [--json] 重新做 UED 设计比对(设计稿 vs 实现,含功能块成对图)
730
+ aiv report <报告ID> [--json] 报告摘要
731
+ aiv export --report <报告ID> [--out <文件>] 按已有报告重新导出 PDF(默认 aiv-reports/<报告ID>.pdf)
732
+ aiv kb build (--project|--product <id|名称>) [--no-ai] 重建 L1→L4 知识库(--product 重建同产品共享知识)
733
+ aiv kb show (--project|--product <id|名称>) 知识库分层与压缩比
734
+ aiv kb search --project <id|名称> --q "<查询词>" [--k 8] [--level L3] [--no-shared] [--no-rerank]
735
+ aiv kb context --project <id|名称> (--requirement <需求ID> | --q "<文本>") [--no-shared]
736
+ aiv kb expand --project <id|名称> --entry <条目ID> [--depth 2]
737
+ aiv projects 项目列表
738
+ aiv tasks [--json] 最近验证任务
739
+
740
+ 自动识别:在项目仓库里运行时,aiv 会按 .aiv.json → 源码路径 → 目录名匹配项目,无需再传 --project。
741
+
742
+ 报告产物:验证完成即打印结论/优先级摘要,并把 PDF 写到 ./aiv-reports/<报告ID>.pdf(--out 指定路径,
743
+ --no-export 不落盘)。平台上同时可见:<平台地址> → 验收报告 → <报告ID>。
744
+
745
+ 环境变量:AIV_API_URL(当前 ${BASE})· AIV_API_TOKEN(${TOKEN ? "已配置" : "未配置"})`);
746
+ },
747
+
748
+ async login() {
749
+ const server = (option("server") || BASE).replace(/\/+$/, "");
750
+ const code = option("code");
751
+ const phone = option("phone");
752
+ const interactive = process.stdin.isTTY && !flag("no-input");
753
+
754
+
755
+ // 方式一(与网页统一):手机号 + 短信验证码 → 换长期 API Token
756
+ if (phone || (code && /^\d{6}$/.test(code))) {
757
+ let targetPhone = phone;
758
+ if (!targetPhone) {
759
+ throw new Error("手机号登录需要 --phone <手机号>,例如:aiv login --phone 13800001234");
760
+ }
761
+ if (!/^1[3-9]\d{9}$/.test(targetPhone)) throw new Error("手机号格式不正确(11 位,1 开头)。");
762
+ let otp = code;
763
+ // 只发码不登录:给脚本/CI 分两步调用(先拿码,再带 --code 登录)。
764
+ if (!otp || flag("send-only")) {
765
+ const sendResponse = await fetch(`${server}/api/auth/cli/send-code`, {
766
+ method: "POST",
767
+ headers: { "content-type": "application/json" },
768
+ body: JSON.stringify({ phone: targetPhone }),
769
+ });
770
+ const sent = await sendResponse.json().catch(() => ({}));
771
+ if (!sendResponse.ok) throw new Error(sent.error || `验证码发送失败(HTTP ${sendResponse.status})`);
772
+ if (sent.devCode) console.log(`· 当前未配置短信服务,开发验证码:${sent.devCode}`);
773
+ else console.log("· 验证码已发送,请查看手机短信。");
774
+ if (flag("send-only")) return;
775
+ if (!otp) {
776
+ if (!interactive) {
777
+ throw new Error(`请带上 --code <6 位验证码> 完成登录(非交互环境)。开发验证码已在上方输出。`);
778
+ }
779
+ otp = await promptLine("请输入 6 位短信验证码:");
780
+ }
781
+ }
782
+ const loginResponse = await fetch(`${server}/api/auth/cli/login`, {
783
+ method: "POST",
784
+ headers: { "content-type": "application/json" },
785
+ body: JSON.stringify({ phone: targetPhone, code: otp.trim(), agreed: true, device: "cli" }),
786
+ });
787
+ const payload = await loginResponse.json().catch(() => ({}));
788
+ if (!loginResponse.ok) throw new Error(payload.error || `登录失败(HTTP ${loginResponse.status})`);
789
+ writeConfig({ ...readConfig(), apiUrl: server, apiToken: payload.token, user: payload.user });
790
+ console.log(`已登录:${CONFIG_PATH}`);
791
+ console.log(` 账号:${payload.user?.phoneMasked || targetPhone} · 平台:${server} · API 余额 ${payload.record?.balance ?? 0} 点`);
792
+ if (payload.welcome?.amountCents) {
793
+ console.log(` 新用户入驻赠送 ¥${(payload.welcome.amountCents / 100).toFixed(2)} 已到账(优先扣减,见 aiv usage / 账户中心 → 履约单)`);
794
+ }
795
+ console.log(" 下一步:在当前项目目录直接运行 aiv init(绑定项目)或 aiv parse(解析 + 验证)");
796
+ return;
797
+ }
798
+
799
+ // 登录码方式(推荐):网页端「CLI 访问」里点生成,10 分钟内一次性使用
800
+ if (code) {
801
+ const response = await fetch(`${server}/api/cli/login`, {
802
+ method: "POST",
803
+ headers: { "content-type": "application/json" },
804
+ body: JSON.stringify({ code }),
805
+ });
806
+ const payload = await response.json().catch(() => ({}));
807
+ if (!response.ok) {
808
+ throw new Error(payload.error || `登录失败(HTTP ${response.status})`);
809
+ }
810
+ writeConfig({ ...readConfig(), apiUrl: server, apiToken: payload.token });
811
+ console.log(`已登录:${CONFIG_PATH}`);
812
+ console.log(` 平台:${server} · API 余额 ${payload.record?.balance ?? 0} 点(1 点 = ¥0.01)`);
813
+ console.log(" 下一步:在当前项目目录运行 aiv init(绑定项目)或直接 aiv verify");
814
+ return;
815
+ }
816
+
817
+ const token = option("token") || positional()[0];
818
+ if (!token) {
819
+ // 没有任何凭据参数时:走浏览器授权(最省事,不用手抄登录码)
820
+ return loginWithBrowser(server);
821
+ }
822
+ const response = await fetch(`${server}/api/usage`, {
823
+ headers: { authorization: `Bearer ${token}` },
824
+ });
825
+ if (response.status === 401) throw new Error("Token 无效或已撤销,请到平台重新创建。");
826
+ if (!response.ok) throw new Error(`平台返回 HTTP ${response.status},请确认 --server 地址正确。`);
827
+ const data = await response.json();
828
+ writeConfig({ ...readConfig(), apiUrl: server, apiToken: token });
829
+ console.log(`已保存 Token(${data.token?.name || "CLI"})到 ${CONFIG_PATH}`);
830
+ console.log(` 平台:${server} · 余额 ${data.token?.balance ?? 0} 点`);
831
+ console.log(" 以后直接运行 aiv verify / report 即可,不用再带 token。");
832
+ },
833
+
834
+ async logout() {
835
+ const current = readConfig();
836
+ delete current.apiToken;
837
+ writeConfig(current);
838
+ console.log(`已清除本地 Token(${CONFIG_PATH})。`);
839
+ },
840
+
841
+ async usage() {
842
+ if (!TOKEN) throw new Error("还没有登录:先运行 aiv login --phone <手机号>(或 --token <API Token> / 设置 AIV_API_TOKEN)。");
843
+ const data = await call("/api/usage");
844
+ if (flag("json")) return console.log(JSON.stringify(data, null, 2));
845
+ const token = data.token || {};
846
+ console.log(`\nToken:${token.name || "-"} · 余额 ${token.balance ?? 0} 点(已用 ${token.spentCredits ?? 0} / 共 ${token.grantedCredits ?? 0})`);
847
+ console.log("点数:1 点 = ¥0.01;价目:解析 30 点 · 启动验证 100 点 · 重跑 UED 10 点 · 重建知识库 20 点。");
848
+ if (!data.entries?.length) return console.log(" 暂无扣点记录。\n");
849
+ console.log(" 最近记录:");
850
+ for (const entry of data.entries) {
851
+ console.log(` ${entry.createdAt.slice(0, 19).replace("T", " ")} · ${entry.label} · -${entry.credits} 点 · ${entry.detail || ""}`);
852
+ }
853
+ console.log("");
854
+ },
855
+
856
+ // 把当前目录绑定到某个项目:自动识别源码路径,探测本地地址,写 .aiv.json。
857
+ async init() {
858
+ if (!TOKEN) throw new Error("还没有登录:先运行 aiv login --phone <手机号>(或 aiv login --code <登录码>)。");
859
+ // 源码目录:--path 手动指定(可在仓库外执行),否则用当前仓库根目录。
860
+ const root = normalizeSourceDir(option("path")) || gitRoot();
861
+ const projects = await listProjects();
862
+ const explicit = option("project") || positional()[0];
863
+ let project = null;
864
+ if (explicit) {
865
+ project = await findProject(explicit);
866
+ } else {
867
+ project = projects.find((item) => samePath(item.codeRepositoryPath, root))
868
+ || projects.find((item) => String(item.name || "").toLowerCase() === pathMod.basename(root).toLowerCase());
869
+ }
870
+ if (!project) {
871
+ const names = projects.map((item) => `${item.name}(${item.id})`).join("、");
872
+ throw new Error(`没能自动匹配到项目。请用 aiv init --project <id|名称> 指定。\n可用项目:${names || "无"}`);
873
+ }
874
+
875
+ // 源码路径:项目没配就写当前仓库根目录
876
+ const patch = {};
877
+ if (!project.codeRepositoryPath || !samePath(project.codeRepositoryPath, root)) {
878
+ patch.codeRepositoryPath = root;
879
+ }
880
+
881
+ // 访问地址:显式 --url > 项目已有 > 本地探测
882
+ let url = normalizeUrl(option("url"));
883
+ if (!url && !project.url) {
884
+ for (const candidate of detectLocalUrl()) {
885
+ if (await probeUrl(candidate)) {
886
+ url = candidate;
887
+ console.log(`· 探测到本地服务:${candidate}`);
888
+ break;
889
+ }
890
+ }
891
+ }
892
+ if (url && url !== project.url) patch.url = url;
893
+
894
+ // 新绑定默认只测本次改动(未提交优先,干净时回退最近一次提交)。
895
+ if (!project.codeAnalysisScope) patch.codeAnalysisScope = requestedScope();
896
+
897
+ let updated = project;
898
+ if (Object.keys(patch).length) {
899
+ updated = await call(`/api/projects/${project.id}`, {
900
+ method: "PUT",
901
+ body: JSON.stringify({ ...patch, saved: Boolean(project.saved) }),
902
+ });
903
+ console.log(`· 已更新项目配置:${Object.keys(patch).map((key) => `${key}=${patch[key]}`).join(" · ")}`);
904
+ }
905
+
906
+ const file = writeLocalProject({
907
+ projectId: updated.id,
908
+ projectName: updated.name,
909
+ productName: updated.productName || "",
910
+ codePath: root,
911
+ url: updated.url || "",
912
+ }, root);
913
+
914
+ console.log(`\n已绑定「${updated.name}」→ ${file}`);
915
+ console.log(` 源码路径:${root}`);
916
+ console.log(` 应用地址:${updated.url || "未配置(用 --url 补,或在网页项目配置里填)"}`);
917
+ console.log(` 代码范围:${describeScope(updated.codeAnalysisScope || "working", root)}(--scope working|commit|all 可改)`);
918
+ const assets = discoverAssets(root);
919
+ const prdCount = assets.filter((item) => item.kind === "prd").length;
920
+ const uedCount = assets.filter((item) => item.kind === "ued").length;
921
+ if (prdCount || uedCount) {
922
+ console.log(` 发现需求素材:PRD ${prdCount} 份 · UED ${uedCount} 份 —— 需要时执行 aiv upload(不带 --file 会自动扫描并让你确认)`);
923
+ } else {
924
+ console.log(" 没发现本地 PRD/UED:用 aiv upload --file <文件> 上传,或在网页「项目配置」里上传");
925
+ console.log(" (PRD/UED 是验证的输入,不提供就没有需求可验收)");
926
+ }
927
+ console.log(" 之后在这个目录直接运行:aiv parse → aiv verify → aiv report <报告ID>");
928
+ },
929
+
930
+ async config() {
931
+ const query = option("project") || positional()[0];
932
+ const project = await resolveProject(query);
933
+ const body = {};
934
+ const mapping = [
935
+ ["name", "name"],
936
+ ["url", "url"],
937
+ ["path", "codeRepositoryPath"],
938
+ ["login-path", "loginPath"],
939
+ ["depth", "verificationDepth"],
940
+ ["scope", "codeAnalysisScope"],
941
+ ["login-method", "loginMethod"],
942
+ ];
943
+ for (const [flagName, field] of mapping) {
944
+ const value = option(flagName);
945
+ if (!value) continue;
946
+ if (field === "url") body.url = normalizeUrl(value);
947
+ else if (field === "codeRepositoryPath") body.codeRepositoryPath = normalizeSourceDir(value);
948
+ else if (field === "codeAnalysisScope") {
949
+ const scope = SCOPE_ALIASES[String(value).toLowerCase()];
950
+ if (!scope) throw new Error("--scope 只能是 working(未提交改动)、commit(最近一次提交)或 all(全部代码)。");
951
+ body.codeAnalysisScope = scope;
952
+ } else body[field] = value;
953
+ }
954
+ if (flag("save")) body.saved = true;
955
+ if (!Object.keys(body).length) {
956
+ const local = readLocalProject();
957
+ console.log(`当前项目:${project.name}(${project.id})${local ? ` · 本地绑定 ${local.file}` : ""}`);
958
+ console.log(` 应用地址:${project.url || "未配置"} · 源码路径:${project.codeRepositoryPath || "未配置"}`);
959
+ console.log(` 登录路径:${project.loginPath || "未配置"} · 验证深度:${project.verificationDepth || "deep"} · 代码范围:${project.codeAnalysisScope || "latest-commit"}`);
960
+ console.log("可改:--url / --path / --login-path / --depth / --scope / --login-method / --save");
961
+ return;
962
+ }
963
+ const updated = await call(`/api/projects/${project.id}`, {
964
+ method: "PUT",
965
+ body: JSON.stringify(body),
966
+ });
967
+ if (flag("json")) return console.log(JSON.stringify(updated, null, 2));
968
+ console.log(`已更新「${updated.name}」:地址 ${updated.url || "未配置"} · 项目路径 ${updated.codeRepositoryPath || "未配置"} · 深度 ${updated.verificationDepth || "deep"} · ${updated.saved ? "已保存" : "未保存"}`);
969
+ // 本地绑定跟着改,避免 .aiv.json 里还留着旧地址/旧路径。
970
+ const local = readLocalProject();
971
+ if (local && local.projectId === project.id && (body.url || body.codeRepositoryPath)) {
972
+ const { file: _file, ...binding } = local;
973
+ const file = writeLocalProject({
974
+ ...binding,
975
+ url: updated.url || "",
976
+ codePath: updated.codeRepositoryPath || local.codePath || "",
977
+ }, body.codeRepositoryPath || local.codePath || gitRoot());
978
+ console.log(`已同步本地绑定:${file}`);
979
+ }
980
+ },
981
+
982
+ async upload() {
983
+ const query = option("project") || positional()[0];
984
+ const requestedKind = option("kind", "auto");
985
+ if (!["auto", "prd", "ued"].includes(requestedKind)) {
986
+ throw new Error("--kind 只能是 prd、ued 或 auto(默认按扩展名识别)。");
987
+ }
988
+ const project = await resolveProject(query);
989
+ let files = options("file");
990
+
991
+ // 不传 --file:自动扫描仓库里的 PRD/UED,确认后上传(--dry-run 只看清单)。
992
+ if (!files.length) {
993
+ const discovered = discoverAssets(gitRoot());
994
+ if (!discovered.length) {
995
+ throw new Error(
996
+ "没有在当前仓库里找到 PRD / UED 素材。请用 --file 指定,例如:\n"
997
+ + " aiv upload --file PRD.md --file 设计稿.html",
998
+ );
999
+ }
1000
+ console.log(`在当前仓库发现 ${discovered.length} 份素材:`);
1001
+ for (const item of discovered) {
1002
+ console.log(` [${item.kind.toUpperCase()}] ${pathMod.relative(gitRoot(), item.file)}`);
1003
+ }
1004
+ if (flag("dry-run")) return;
1005
+ if (!flag("yes")) {
1006
+ if (!process.stdin.isTTY) throw new Error("请加 --yes 确认上传,或 --dry-run 只看清单。");
1007
+ const answer = await promptLine("确认上传以上素材到平台?(y/N) ");
1008
+ if (!/^y(es)?$/i.test(answer)) return console.log("已取消上传。");
1009
+ }
1010
+ files = discovered.map((item) => item.file);
1011
+ if (requestedKind === "auto") {
1012
+ // 自动扫描已经判断过 kind,用发现的类型,避免 PDF 二义性。
1013
+ project.__assetKinds = new Map(discovered.map((item) => [item.file, item.kind]));
1014
+ }
1015
+ }
1016
+
1017
+ const fs = await import("node:fs/promises");
1018
+ const path = await import("node:path");
1019
+ const uploads = [];
1020
+ for (const filePath of files) {
1021
+ const extension = path.extname(filePath).toLowerCase();
1022
+ let kind = requestedKind === "auto" ? (project.__assetKinds?.get(filePath) || "auto") : requestedKind;
1023
+ if (kind === "auto") {
1024
+ if ([".md", ".docx", ".txt"].includes(extension)) kind = "prd";
1025
+ else if ([".html", ".htm", ".png", ".jpg", ".jpeg"].includes(extension)) kind = "ued";
1026
+ else if (extension === ".pdf") {
1027
+ throw new Error(`「${path.basename(filePath)}」是 PDF,无法自动判断是 PRD 还是 UED,请加 --kind prd 或 --kind ued。`);
1028
+ } else {
1029
+ throw new Error(`不认识的文件类型「${extension || path.basename(filePath)}」:PRD 用 pdf/docx/md/txt,UED 用 pdf/html/图片。`);
1030
+ }
1031
+ }
1032
+ const allowed = kind === "prd" ? PRD_EXTENSIONS : UED_EXTENSIONS;
1033
+ if (!allowed.includes(extension)) {
1034
+ throw new Error(
1035
+ kind === "prd"
1036
+ ? `PRD 仅支持 PDF、DOCX、Markdown 或 TXT,收到「${path.basename(filePath)}」。`
1037
+ : `UED 仅支持 PDF、HTML 或图片,收到「${path.basename(filePath)}」。`,
1038
+ );
1039
+ }
1040
+ let buffer;
1041
+ try {
1042
+ buffer = await fs.readFile(filePath);
1043
+ } catch {
1044
+ throw new Error(`读不到文件:${filePath}`);
1045
+ }
1046
+ const form = new FormData();
1047
+ form.append("file", new Blob([buffer]), path.basename(filePath));
1048
+ const updated = await callForm(`/api/projects/${project.id}/documents/${kind}`, form);
1049
+ uploads.push({ kind, name: path.basename(filePath), bytes: buffer.length, documents: updated.documents || [] });
1050
+ }
1051
+
1052
+ const documents = uploads[uploads.length - 1].documents;
1053
+ const count = (documentKind) => documents.filter((doc) => doc.kind === documentKind).length;
1054
+ if (flag("json")) {
1055
+ return console.log(JSON.stringify({
1056
+ documents,
1057
+ uploaded: uploads.map(({ kind, name, bytes }) => ({ kind, name, bytes })),
1058
+ }, null, 2));
1059
+ }
1060
+ for (const item of uploads) {
1061
+ console.log(`已上传 ${item.kind.toUpperCase()}:${item.name}(${(item.bytes / 1024).toFixed(0)} KB)`);
1062
+ }
1063
+ console.log(` 当前文档:PRD ${count("prd")} 份 · UED ${count("ued")} 份。`);
1064
+ console.log(" 注意:上传后需求基线会清空,下一步执行 aiv parse 重新解析需求。");
1065
+ },
1066
+
1067
+ async projects() {
1068
+ const root = gitRoot();
1069
+ const local = readLocalProject();
1070
+ const bootstrap = await call("/api/bootstrap");
1071
+ const rows = (bootstrap.products || []).flatMap((product) =>
1072
+ (product.projects || []).map((project) => ({
1073
+ name: project.name,
1074
+ id: project.id,
1075
+ product: product.name,
1076
+ parsed: project.parsed,
1077
+ saved: project.saved,
1078
+ url: project.url,
1079
+ codePath: project.codeRepositoryPath,
1080
+ current: project.id === local?.projectId || samePath(project.codeRepositoryPath, root),
1081
+ })),
1082
+ );
1083
+ if (flag("json")) return console.log(JSON.stringify(rows, null, 2));
1084
+ printRows(
1085
+ "项目",
1086
+ rows.map(
1087
+ (row) => `${row.current ? "★ " : ""}${row.name} (${row.id}) · ${row.product} · ${row.parsed ? "已解析" : "未解析"} · ${row.saved ? "已保存" : "未保存"} · ${row.url || "无地址"}${row.codePath ? ` · ${row.codePath}` : ""}`,
1088
+ ),
1089
+ );
1090
+ if (local) console.log(`\n★ 表示与当前目录绑定(${local.file})或源码路径匹配。`);
1091
+ },
1092
+
1093
+ async tasks() {
1094
+ const bootstrap = await call("/api/bootstrap");
1095
+ const tasks = bootstrap.verificationTasks || [];
1096
+ if (flag("json")) return console.log(JSON.stringify(tasks, null, 2));
1097
+ printRows("最近任务", tasks.slice(0, 15).map((task) => `${task.id} · ${task.status} · ${task.projectName || ""} · ${task.reportId || "无报告"}`));
1098
+ },
1099
+
1100
+ async parse() {
1101
+ const query = positional()[0] || option("project");
1102
+ const project = await resolveProject(query);
1103
+ const scope = requestedScope();
1104
+ const body = {};
1105
+ const pasteFile = option("paste-file");
1106
+ if (pasteFile) {
1107
+ const fs = await import("node:fs/promises");
1108
+ body.pastedPrd = await fs.readFile(pasteFile, "utf8");
1109
+ body.prdInputMode = "paste";
1110
+ }
1111
+ // 需求范围按「本次改动」收敛,所以范围要在解析之前定下来。
1112
+ const scopeHint = { remote: Boolean(project.runnerId) };
1113
+ if (!flag("json")) console.log(`变更范围:${describeScope(scope, project.codeRepositoryPath || gitRoot(), scopeHint)}`);
1114
+ await applyScope(project, scope);
1115
+ const result = await call(`/api/projects/${project.id}/parse`, {
1116
+ method: "POST",
1117
+ body: JSON.stringify(body),
1118
+ });
1119
+ const parsed = result.requirements.length;
1120
+ if (flag("no-verify")) {
1121
+ if (flag("json")) return console.log(JSON.stringify(result, null, 2));
1122
+ console.log(`已解析 ${parsed} 条需求(原始 ${result.originalRequirementCount ?? parsed} 条)`);
1123
+ return console.log(" 只解析不验证(--no-verify)。下一步:aiv verify");
1124
+ }
1125
+ if (!flag("json")) {
1126
+ console.log(`已解析 ${parsed} 条需求(原始 ${result.originalRequirementCount ?? parsed} 条)`);
1127
+ }
1128
+ if (!project.url) {
1129
+ throw new Error(
1130
+ `项目「${project.name}」还没有应用访问地址,无法继续验证(需求已解析完成)。\n`
1131
+ + ` aiv config --url http://127.0.0.1:5173 --save\n`
1132
+ + " aiv verify",
1133
+ );
1134
+ }
1135
+ await saveProject(project);
1136
+ if (!flag("json")) console.log(" 项目已保存,开始自动验证…");
1137
+ await runVerification(project, { json: flag("json"), extra: { requirements: parsed } });
1138
+ },
1139
+
1140
+ async requirements() {
1141
+ const query = positional()[0] || option("project");
1142
+ const project = await resolveProject(query);
1143
+ const tree = await call(`/api/projects/${project.id}/tree`);
1144
+ if (flag("json")) return console.log(JSON.stringify(tree, null, 2));
1145
+ console.log(`\n${project.name} · ${tree.counts.pages} 个页面 / ${tree.counts.features} 个功能 / ${tree.counts.requirements} 条需求 / ${tree.counts.leaves} 条验收点\n`);
1146
+ renderTree(tree.nodes);
1147
+ },
1148
+
1149
+ async tree() {
1150
+ const reportId = option("report") || positional()[0];
1151
+ if (!reportId) throw new Error("请用 --report 指定报告 ID。");
1152
+ const view = option("view", "verification") === "issues" ? "issues" : "verification";
1153
+ const tree = await call(`/api/reports/${reportId}/tree?view=${view}`);
1154
+ if (flag("json")) return console.log(JSON.stringify(tree, null, 2));
1155
+ console.log(`\n${reportId} · ${view === "issues" ? "问题树" : "验证结果树"} · ${tree.counts.pages} 页面 / ${tree.counts.features} 功能 / ${tree.counts.requirements} 需求 / ${tree.counts.leaves} 明细\n`);
1156
+ renderTree(tree.nodes);
1157
+ },
1158
+
1159
+ async ued() {
1160
+ const reportId = option("report") || positional()[0];
1161
+ if (!reportId) throw new Error("请用 --report 指定报告 ID。");
1162
+ const result = await call(`/api/reports/${reportId}/ued/refresh`, { method: "POST", body: "{}" });
1163
+ const comparison = result.uedComparison || {};
1164
+ if (flag("json")) return console.log(JSON.stringify(comparison, null, 2));
1165
+ console.log(`\n${comparison.note || "UED 比对完成"}`);
1166
+ for (const design of comparison.designs || []) {
1167
+ const page = design.page ? `${design.page} ${design.path || ""}` : "未匹配到页面";
1168
+ const similarity = design.similarity != null ? ` 相似度 ${(design.similarity * 100).toFixed(1)}%` : "";
1169
+ console.log(` ${design.name} · ${design.status} · ${page}${similarity}`);
1170
+ for (const module of design.modules || []) {
1171
+ const moduleSim = module.similarity != null ? ` 相似度 ${(module.similarity * 100).toFixed(1)}%` : "";
1172
+ console.log(` - ${module.feature} · ${module.status}${moduleSim}`);
1173
+ if (module.designUrl) console.log(` 设计稿:${module.designUrl}`);
1174
+ if (module.pageUrl) console.log(` 实现:${module.pageUrl}`);
1175
+ if (module.note) console.log(` ${module.note}`);
1176
+ }
1177
+ if (!design.modules?.length && design.note) console.log(` ${design.note}`);
1178
+ }
1179
+ console.log("");
1180
+ },
1181
+
1182
+ async export() {
1183
+ const reportId = option("report") || positional()[0];
1184
+ if (!reportId) throw new Error("请用 --report 指定报告 ID。");
1185
+ const { file, bytes } = await downloadReportPdf(reportId, option("out"));
1186
+ console.log(`已导出 ${file}(${(bytes / 1024 / 1024).toFixed(1)} MB)`);
1187
+ },
1188
+
1189
+ async impact() {
1190
+ const reportId = option("report") || positional()[0];
1191
+ if (!reportId) throw new Error("请用 --report 指定报告 ID。");
1192
+ const report = await call(`/api/reports/${reportId}`);
1193
+ const impact = report.impactAnalysis;
1194
+ if (flag("json")) return console.log(JSON.stringify(impact, null, 2));
1195
+ if (!impact) return console.log("该报告没有影响面分析。");
1196
+ console.log(`\n${impact.note}`);
1197
+ for (const item of impact.items || []) {
1198
+ console.log(` [${item.risk}] ${item.kind} · ${item.target} — ${item.reason}`);
1199
+ }
1200
+ console.log("");
1201
+ },
1202
+
1203
+ async report() {
1204
+ const reportId = positional()[0] || option("report");
1205
+ if (!reportId) throw new Error("请用 aiv report <报告ID>。");
1206
+ const report = await call(`/api/reports/${reportId}`);
1207
+ if (flag("json")) return console.log(JSON.stringify(report, null, 2));
1208
+ printReportSummary(report);
1209
+ console.log(` PDF:aiv export --report ${report.id}`);
1210
+ console.log(` 平台查看:${BASE} → 验收报告 · ${report.id}\n`);
1211
+ },
1212
+
1213
+ async kb() {
1214
+ const action = positional()[0] || "show";
1215
+ const productQuery = option("product");
1216
+ if (productQuery) return runProductKnowledge(action, productQuery);
1217
+ const projectQuery = option("project") || positional()[1];
1218
+ const project = await resolveProject(projectQuery);
1219
+ if (action === "search") {
1220
+ const query = option("q");
1221
+ if (!query) throw new Error("请用 --q 提供查询词。");
1222
+ const params = new URLSearchParams({ q: query, k: option("k", "8") });
1223
+ if (option("level")) params.set("level", option("level"));
1224
+ if (flag("no-shared")) params.set("shared", "false");
1225
+ if (flag("no-rerank")) params.set("rerank", "false");
1226
+ const result = await call(`/api/projects/${project.id}/knowledge/search?${params}`);
1227
+ if (flag("json")) return console.log(JSON.stringify(result, null, 2));
1228
+ const rerankNote = result.reranked ? " · 已按模型相关性重排" : result.rerankNote ? ` · ${result.rerankNote}` : "";
1229
+ console.log(`\n查询「${query}」· 向量 ${result.provider || "无"}(${result.vectorSource || "-"})· 共享知识 ${result.sharedEntries || 0} 条${rerankNote}`);
1230
+ for (const hit of result.hits) {
1231
+ const rerankScore = hit.rerankScore != null ? `,相关性 ${hit.rerankScore}/10` : "";
1232
+ console.log(` [${hit.level}] ${hit.scope || "-"} · ${hit.summary}(RRF ${hit.score}${rerankScore},词法 ${hit.lexical},向量 ${hit.vector})`);
1233
+ }
1234
+ return console.log("");
1235
+ }
1236
+ if (action === "context") {
1237
+ const requirementId = option("requirement");
1238
+ const queryText = option("q");
1239
+ if (!requirementId && !queryText) throw new Error("请用 --requirement 或 --q 指定延迟查找目标。");
1240
+ const params = new URLSearchParams();
1241
+ if (requirementId) params.set("requirementId", requirementId);
1242
+ if (queryText) params.set("q", queryText);
1243
+ if (flag("no-shared")) params.set("shared", "false");
1244
+ const context = await call(`/api/projects/${project.id}/knowledge/context?${params}`);
1245
+ if (flag("json")) return console.log(JSON.stringify(context, null, 2));
1246
+ console.log(`\n延迟查找:注入 ${context.trace.usedChars} 字 / 预算 ${context.trace.budgetChars} 字 · 原始 L1 ${context.trace.rawLevel1Chars} 字 · 本项目 ${context.trace.projectEntries ?? "-"} 条 + 产品共享 ${context.trace.sharedEntries ?? 0} 条 · 检索 ${context.trace.retrieval || "-"}`);
1247
+ console.log(context.text);
1248
+ return console.log("");
1249
+ }
1250
+ if (action === "build") {
1251
+ const body = JSON.stringify({ useAi: !flag("no-ai") });
1252
+ const result = await call(`/api/projects/${project.id}/knowledge/build`, { method: "POST", body });
1253
+ if (flag("json")) return console.log(JSON.stringify(result, null, 2));
1254
+ const { build } = result;
1255
+ console.log(`\n${project.name} · 知识库重建完成(${build.elapsedMs}ms · ${build.usedAiForL3 ? "模型提炼" : "确定性模板"})`);
1256
+ for (const [level, info] of Object.entries(build.levels)) {
1257
+ console.log(` ${level} ${info.label}:${info.entries} 条 / ${info.chars} 字`);
1258
+ }
1259
+ for (const [pair, ratio] of Object.entries(build.compression)) {
1260
+ console.log(` 压缩 ${pair}:${(ratio * 100).toFixed(1)}%`);
1261
+ }
1262
+ console.log(` L1→L4 总压缩比:${(build.overallRatio * 100).toFixed(2)}%(${build.levels.L1.chars} 字 → ${build.levels.L4.chars} 字)`);
1263
+ if (build.warnings?.length) build.warnings.forEach((item) => console.log(` ! ${item}`));
1264
+ return console.log("");
1265
+ }
1266
+ if (action === "expand") {
1267
+ const entryId = option("entry");
1268
+ if (!entryId) throw new Error("请用 --entry 指定条目 ID。");
1269
+ const depth = option("depth", "1");
1270
+ const result = await call(`/api/projects/${project.id}/knowledge/entries/${entryId}?depth=${depth}`);
1271
+ if (flag("json")) return console.log(JSON.stringify(result, null, 2));
1272
+ for (const node of result.expansion?.nodes || []) {
1273
+ console.log(`${" ".repeat(node.depth)}[${node.level}] ${node.title}(${node.sources} 个来源)`);
1274
+ }
1275
+ return console.log("");
1276
+ }
1277
+ const summary = await call(`/api/projects/${project.id}/knowledge`);
1278
+ if (flag("json")) return console.log(JSON.stringify(summary, null, 2));
1279
+ const { levels, lastBuild } = summary.summary;
1280
+ console.log(`\n${project.name} · 知识库`);
1281
+ for (const [level, info] of Object.entries(levels)) {
1282
+ console.log(` ${level} ${info.label}:${info.entries} 条 / ${info.chars} 字`);
1283
+ }
1284
+ if (lastBuild) {
1285
+ for (const [pair, ratio] of Object.entries(lastBuild.compression || {})) {
1286
+ console.log(` 压缩 ${pair}:${(ratio * 100).toFixed(1)}%`);
1287
+ }
1288
+ console.log(` 最近一次构建:${lastBuild.builtAt} · ${lastBuild.elapsedMs}ms · 向量 ${lastBuild.vectors?.provider || "无"}`);
1289
+ }
1290
+ console.log("");
1291
+ },
1292
+
1293
+ async verify() {
1294
+ const query = positional()[0] || option("project");
1295
+ const project = await resolveProject(query);
1296
+
1297
+ // PRD/UED 是验证的输入:没解析过需求时先说清楚要补什么,别让用户撞服务端报错。
1298
+ if (!flag("parse") && !project.parsed) {
1299
+ const assets = discoverAssets();
1300
+ const hint = assets.length
1301
+ ? `当前仓库发现 ${assets.length} 份素材(${assets.map((item) => pathMod.relative(gitRoot(), item.file)).slice(0, 4).join("、")})`
1302
+ : "当前仓库没发现 PRD/UED 文件";
1303
+ throw new Error(
1304
+ `项目「${project.name}」还没有可验证的需求(PRD/UED 是必填输入)。\n`
1305
+ + ` ${hint}\n`
1306
+ + " 下一步:aiv upload (自动扫描并在确认后上传;也可 --file PRD.md --file 设计稿.html)\n"
1307
+ + " aiv parse (一步完成:解析需求 → 验证 → 报告落盘)",
1308
+ );
1309
+ }
1310
+ if (!project.url) {
1311
+ throw new Error(`项目「${project.name}」还没有应用访问地址:aiv config --url http://127.0.0.1:5173 --save`);
1312
+ }
1313
+ const scope = requestedScope();
1314
+ if (!flag("json")) {
1315
+ console.log(`变更范围:${describeScope(scope, project.codeRepositoryPath || gitRoot(), { remote: Boolean(project.runnerId) })}`);
1316
+ }
1317
+ await applyScope(project, scope);
1318
+ if (flag("parse")) {
1319
+ const parsed = await call(`/api/projects/${project.id}/parse`, { method: "POST", body: "{}" });
1320
+ console.log(`需求已重新解析:${parsed.requirements.length} 条。`);
1321
+ // 解析会把项目标记为「未保存」,验证前必须保存,否则平台会拒绝启动。
1322
+ await saveProject(project);
1323
+ console.log("项目已保存。");
1324
+ } else if (project.parsed && !project.saved) {
1325
+ // 与界面上的「一键验证」一致:已解析但未保存时先保存再启动。
1326
+ await saveProject(project);
1327
+ console.log("项目未保存,已自动保存。");
1328
+ }
1329
+ await runVerification(project, { json: flag("json") });
1330
+ },
1331
+ };
1332
+
1333
+ try {
1334
+ const handler = commands[command];
1335
+ if (helpRequested) {
1336
+ await commands.help();
1337
+ process.exitCode = 0;
1338
+ } else if (!handler) {
1339
+ await commands.help();
1340
+ process.exitCode = command === "help" ? 0 : 2;
1341
+ } else {
1342
+ await handler();
1343
+ }
1344
+ } catch (error) {
1345
+ console.error(`错误:${error.message}`);
1346
+ process.exitCode = 1;
1347
+ }