cli.js
14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
const { spawnSync } = require("node:child_process");
const fs = require("node:fs");
const path = require("node:path");
const process = require("node:process");
const { planAffectedTests } = require("./affected-tests");
const {
buildKnowledgeGraph,
buildKnowledgeOverlay,
serializeGraph,
} = require("./build-knowledge-graph");
const { queryImpact } = require("./query-impact");
const GENERATED_GRAPH = ".ai/generated/knowledge-graph.json";
const GENERATED_INDEX = ".ai/generated/domain-index.md";
function uniqueSorted(values) {
return [...new Set(values.filter(Boolean))].sort((left, right) => left.localeCompare(right, "en"));
}
function parseArguments(argv) {
const result = {
command: argv[0] || "help",
keywords: [],
depth: 2,
direction: "both",
format: "markdown",
list: false,
full: false,
verbose: false,
};
for (let index = 1; index < argv.length; index += 1) {
const argument = argv[index];
if (["--list", "--full", "--verbose"].includes(argument)) {
result[argument.slice(2)] = true;
continue;
}
const key = argument.slice(2);
const value = argv[index + 1];
if (!argument.startsWith("--") || value === undefined || value.startsWith("--")) {
throw new Error(`Invalid argument: ${argument}`);
}
index += 1;
if (key === "keyword") {
result.keywords.push(value);
} else if (key === "depth") {
result.depth = Number.parseInt(value, 10);
} else if (["direction", "format", "base", "head"].includes(key)) {
result[key] = value;
} else {
throw new Error(`Unknown option: --${key}`);
}
}
return result;
}
function valuesForDomain(graph, domainId, types, mapper, predicate = () => true) {
return uniqueSorted(graph.nodes
.filter(node => (node.domainIds || []).includes(domainId) && types.includes(node.type) && predicate(node))
.map(mapper));
}
function markdownList(values, emptyText, limit = 40) {
if (!values.length) {
return emptyText;
}
const visible = values.slice(0, limit);
const suffix = values.length > visible.length ? `;另有 ${values.length - visible.length} 项见 JSON 图谱` : "";
return `${visible.map(value => `\`${value}\``).join("、")}${suffix}`;
}
function renderDomainIndex(graph) {
const lines = [
"# 业务域知识图谱索引",
"",
"> 此文件由 `npm run knowledge:build` 自动生成。业务规则以 `.ai/docs/knowledge/` 的人工文档为准。",
"",
];
const domains = graph.nodes.filter(node => node.type === "domain");
for (const domain of domains) {
const domainId = domain.id.slice("domain:".length);
const ownedViewRoots = [...(domain.meta?.entrypoints || []), ...(domain.meta?.roots || [])]
.filter(entrypoint => entrypoint.startsWith("src/views/"));
const routes = valuesForDomain(graph, domainId, ["route"], (node) => {
const routePath = node.meta?.routePath ? ` ${node.meta.routePath}` : "";
return `${node.meta?.routeName || node.name}${routePath}`;
}, node => node.path === domain.path);
const views = valuesForDomain(graph, domainId, ["view", "component"], node => node.path, node => ownedViewRoots.some(root => node.path === root || node.path.startsWith(`${root}/`)));
const apis = valuesForDomain(graph, domainId, ["apiOperation", "endpoint"], node => node.name);
const vuex = valuesForDomain(graph, domainId, ["vuexState", "vuexGetter", "vuexAction", "vuexMutation"], node => node.name);
const tests = valuesForDomain(graph, domainId, ["test"], node => node.path);
const documents = valuesForDomain(graph, domainId, ["document"], node => node.path)
.filter(file => file.startsWith(".ai/docs/knowledge/"));
const entrypoints = [...(domain.meta?.entrypoints || []), ...(domain.meta?.roots || [])];
lines.push(
`## ${domainId} ${domain.name}`,
"",
`- 入口:${markdownList(entrypoints, "未人工配置入口")}`,
`- 路由(${routes.length}):${markdownList(routes, "未扫描到静态路由")}`,
`- 视图/组件(${views.length}):${markdownList(views, "未扫描到关联视图或组件", 25)}`,
`- API/ROP(${apis.length}):${markdownList(apis, "未扫描到静态 API 关系", 25)}`,
`- Vuex(${vuex.length}):${markdownList(vuex, "未扫描到静态 Vuex 关系", 25)}`,
`- 测试(${tests.length}):${markdownList(tests, "未发现候选测试", 25)}`,
documents.length
? `- 业务文档:${markdownList(documents, "")}`
: "- 文档缺口:尚无人工维护的深度业务文档;不要据此臆造业务规则。",
"",
);
}
return `${lines.join("\n").trimEnd()}\n`;
}
function formatImpactMarkdown(result) {
const sections = [
["Seeds", result.seeds],
["Direct matches", result.directMatches],
["Upstream consumers", result.upstreamConsumers],
["Downstream dependencies", result.downstreamDependencies],
["Cross-domain risks", result.crossDomainRisks],
["Test candidates", result.testCandidates],
["Documents", result.documents],
];
const lines = ["# 需求影响查询", ""];
for (const [title, nodes] of sections) {
lines.push(`## ${title}`, "");
if (!nodes.length) {
lines.push("- 无", "");
continue;
}
nodes.forEach(node => lines.push(`- \`${node.id}\`${node.path ? ` — ${node.path}` : ""}`));
lines.push("");
}
lines.push("## Unresolved", "");
if (!result.unresolved.length) {
lines.push("- 无", "");
} else {
result.unresolved.forEach(item => lines.push(
`- \`${item.kind}\` ${item.path}:${item.line}:${item.column} — ${item.reason}${item.known ? "(已登记)" : ""}`,
));
lines.push("");
}
lines.push("## Evidence", "", `- 共 ${result.evidence.length} 条关系证据;JSON 格式包含完整 evidence。`, "");
return `${lines.join("\n").trimEnd()}\n`;
}
function parseGitDiff(output) {
const changedFiles = [];
const deletedFiles = [];
const renamedFiles = [];
for (const line of output.split(/\r?\n/).filter(Boolean)) {
const [status, ...files] = line.split("\t");
if (status.startsWith("R") && files.length >= 2) {
changedFiles.push(files[0], files[1]);
renamedFiles.push(files[0], files[1]);
} else if (files[0]) {
changedFiles.push(files[0]);
if (status === "D") {
deletedFiles.push(files[0]);
}
}
}
return {
changedFiles: uniqueSorted(changedFiles.map(file => file.replace(/\\/g, "/"))),
deletedFiles: uniqueSorted(deletedFiles.map(file => file.replace(/\\/g, "/"))),
renamedFiles: uniqueSorted(renamedFiles.map(file => file.replace(/\\/g, "/"))),
};
}
function runProcess(command, args, options = {}) {
const result = spawnSync(command, args, {
cwd: options.cwd || process.cwd(),
encoding: "utf8",
stdio: options.stdio || "pipe",
shell: false,
});
if (result.error || result.status !== 0) {
const detail = result.stderr || result.stdout || result.error?.message || "unknown error";
throw new Error(`${command} ${args.join(" ")} failed: ${detail.trim()}`);
}
return result.stdout || "";
}
function collectGitChanges(rootDir, options) {
let diffOutput;
if (options.base || options.head) {
const base = options.base || "HEAD^";
const head = options.head || "HEAD";
diffOutput = runProcess("git", ["diff", "--name-status", "-M", `${base}...${head}`], { cwd: rootDir });
} else {
diffOutput = runProcess("git", ["diff", "--name-status", "-M", "HEAD"], { cwd: rootDir });
}
const changes = parseGitDiff(diffOutput);
if (!options.base && !options.head) {
const untracked = runProcess("git", ["ls-files", "--others", "--exclude-standard"], { cwd: rootDir })
.split(/\r?\n/)
.filter(Boolean)
.map(file => file.replace(/\\/g, "/"));
changes.changedFiles = uniqueSorted([...changes.changedFiles, ...untracked]);
}
return changes;
}
function mergeGraphOverlay(baseGraph, overlay, changedFiles) {
const changed = new Set(changedFiles);
const nodeById = new Map(baseGraph.nodes
.filter(node => !node.path || !changed.has(node.path))
.map(node => [node.id, node]));
overlay.nodes.forEach(node => nodeById.set(node.id, node));
const edges = [
...baseGraph.edges.filter(edge => !changed.has(edge.evidence.path)
&& nodeById.has(edge.from) && nodeById.has(edge.to)),
...overlay.edges,
];
const edgeByKey = new Map(edges.map(edge => [JSON.stringify(edge), edge]));
const unresolved = [
...baseGraph.unresolved.filter(item => !changed.has(item.path)),
...overlay.unresolved,
].sort((left, right) => JSON.stringify(left).localeCompare(JSON.stringify(right), "en"));
return {
schemaVersion: baseGraph.schemaVersion,
nodes: [...nodeById.values()].sort((left, right) => left.id.localeCompare(right.id, "en")),
edges: [...edgeByKey.values()].sort((left, right) => JSON.stringify(left).localeCompare(JSON.stringify(right), "en")),
unresolved,
stats: baseGraph.stats,
};
}
function findRelatedTestsWithJest(rootDir, changedFiles) {
const runtimeFiles = changedFiles
.filter(file => /^src\/.*\.(?:js|vue)$/.test(file) && fs.existsSync(path.join(rootDir, file)))
.map(file => path.join(rootDir, file));
if (!runtimeFiles.length) {
return [];
}
const jestBin = require.resolve("jest/bin/jest");
const output = runProcess(process.execPath, [
jestBin,
"--config",
path.join(rootDir, "jest.config.js"),
"--findRelatedTests",
...runtimeFiles,
"--listTests",
"--json",
"--runInBand",
], { cwd: rootDir });
const jsonStart = output.indexOf("[");
if (jsonStart < 0) {
return [];
}
return uniqueSorted(JSON.parse(output.slice(jsonStart))
.map(file => path.relative(rootDir, file).replace(/\\/g, "/")));
}
function readGeneratedGraph(rootDir) {
const graphPath = path.join(rootDir, GENERATED_GRAPH);
if (!fs.existsSync(graphPath)) {
throw new Error(`Missing ${GENERATED_GRAPH}; run npm run knowledge:build first`);
}
return JSON.parse(fs.readFileSync(graphPath, "utf8"));
}
function buildArtifacts(rootDir) {
const graph = buildKnowledgeGraph({ rootDir });
const artifacts = {
[GENERATED_GRAPH]: serializeGraph(graph),
[GENERATED_INDEX]: renderDomainIndex(graph),
};
return { graph, artifacts };
}
function writeArtifacts(rootDir, artifacts) {
for (const [file, content] of Object.entries(artifacts)) {
const target = path.join(rootDir, file);
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, content, "utf8");
}
}
function checkArtifacts(rootDir) {
const { graph, artifacts } = buildArtifacts(rootDir);
const drift = Object.entries(artifacts)
.filter(([file, expected]) => !fs.existsSync(path.join(rootDir, file))
|| fs.readFileSync(path.join(rootDir, file), "utf8") !== expected)
.map(([file]) => file);
const unknown = graph.unresolved.filter(item => !item.known);
if (drift.length || unknown.length) {
const messages = [];
if (drift.length) {
messages.push(`Generated artifacts drifted: ${drift.join(", ")}`);
}
if (unknown.length) {
messages.push(`Unregistered unresolved relationships: ${unknown.length}`);
}
throw new Error(messages.join("; "));
}
return graph;
}
function printAffectedPlan(plan, format) {
if (format === "json") {
process.stdout.write(`${JSON.stringify(plan, null, 2)}\n`);
return;
}
process.stdout.write([
`mode: ${plan.mode}`,
`reasons: ${plan.reasons.join(", ") || "none"}`,
`domains: ${plan.domains.join(", ") || "none"}`,
`tests: ${plan.testFiles.join(", ") || "none"}`,
...plan.commands.map(command => `command: ${command}`),
"",
].join("\n"));
}
function executeAffectedPlan(rootDir, plan, verbose) {
const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm";
function runNpm(args) {
const result = spawnSync(npmCommand, args, { cwd: rootDir, stdio: "inherit", shell: false });
if (result.error || result.status !== 0) {
process.exitCode = result.status || 1;
return false;
}
return true;
}
if (plan.mode === "full") {
runNpm(["run", "test:unit", "--", "--ci"]);
} else if (plan.mode === "targeted") {
const args = ["run", "test:unit", "--", "--runTestsByPath", ...plan.testFiles];
if (verbose) {
args.push("--verbose");
}
runNpm(args);
} else if (plan.mode === "knowledge-only") {
if (runNpm(["run", "knowledge:test"])) {
runNpm(["run", "knowledge:check"]);
}
}
}
function runAffected(rootDir, options) {
const changes = collectGitChanges(rootDir, {
base: options.base || process.env.CI_MERGE_REQUEST_DIFF_BASE_SHA,
head: options.head || process.env.CI_COMMIT_SHA,
});
const baseGraph = readGeneratedGraph(rootDir);
const overlay = buildKnowledgeOverlay({
rootDir,
baseGraph,
files: changes.changedFiles,
});
const graph = mergeGraphOverlay(baseGraph, overlay, changes.changedFiles);
let standardTestFiles = [];
let forceFull = options.full;
try {
standardTestFiles = findRelatedTestsWithJest(rootDir, changes.changedFiles);
} catch (error) {
forceFull = true;
if (options.verbose) {
process.stderr.write(`${error.message}\n`);
}
}
const plan = planAffectedTests({
rootDir,
graph,
changedFiles: changes.changedFiles,
deletedFiles: changes.deletedFiles,
renamedFiles: changes.renamedFiles,
standardTestFiles,
full: forceFull,
verbose: options.verbose,
});
printAffectedPlan(plan, options.format);
if (!options.list) {
executeAffectedPlan(rootDir, plan, options.verbose);
}
return plan;
}
function printHelp() {
process.stdout.write(`Knowledge graph commands:\n\n`
+ ` build\n check\n impact --keyword <value> [--depth 2] [--direction both] [--format json|markdown]\n`
+ ` affected [--base <ref>] [--head <ref>] [--list] [--format json] [--full] [--verbose]\n`);
}
function main(argv = process.argv.slice(2), rootDir = process.cwd()) {
const options = parseArguments(argv);
if (options.command === "build") {
const { graph, artifacts } = buildArtifacts(rootDir);
writeArtifacts(rootDir, artifacts);
process.stdout.write(`knowledge graph: ${graph.stats.nodeCount} nodes, ${graph.stats.edgeCount} edges, ${graph.stats.unresolvedCount} unresolved\n`);
} else if (options.command === "check") {
const graph = checkArtifacts(rootDir);
process.stdout.write(`knowledge graph is current (${graph.stats.nodeCount} nodes)\n`);
} else if (options.command === "impact") {
if (!options.keywords.length) {
throw new Error("At least one --keyword is required");
}
if (!Number.isInteger(options.depth) || options.depth < 0) {
throw new Error("--depth must be a non-negative integer");
}
if (!["both", "upstream", "downstream"].includes(options.direction)) {
throw new Error("--direction must be both, upstream or downstream");
}
const result = queryImpact(readGeneratedGraph(rootDir), options);
process.stdout.write(options.format === "json"
? `${JSON.stringify(result, null, 2)}\n`
: formatImpactMarkdown(result));
} else if (options.command === "affected") {
runAffected(rootDir, options);
} else {
printHelp();
}
}
if (require.main === module) {
try {
main();
} catch (error) {
process.stderr.write(`${error.message}\n`);
process.exitCode = 1;
}
}
module.exports = {
buildArtifacts,
checkArtifacts,
collectGitChanges,
findRelatedTestsWithJest,
formatImpactMarkdown,
main,
mergeGraphOverlay,
parseArguments,
parseGitDiff,
renderDomainIndex,
runAffected,
writeArtifacts,
};