query-knowledge-graph.mjs
7.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
/**
* @file 在已生成图谱上执行确定性的关键词与邻接查询。
* 查询只提供证据候选,不替代 Agent 对“必改/可能波及/明确不改”的语义判断。
*/
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
function compareText(left, right) {
return left < right ? -1 : left > right ? 1 : 0
}
function stableItems(items) {
return [...items].sort((left, right) => compareText(left.id, right.id))
}
function searchableText(node) {
return [
node.id,
node.name,
node.path,
...(node.aliases || []),
...(node.roots || []),
...(node.entrypoints || []),
...(node.riskKeywords || []),
...(node.symbols || []),
]
.filter(Boolean)
.join('\n')
.toLocaleLowerCase('en')
}
function uniqueNodes(ids, nodeById) {
return stableItems([...ids].map((id) => nodeById.get(id)).filter(Boolean))
}
function walkDirection(seedIds, edges, direction, depth) {
const visited = new Set(seedIds)
const discovered = new Set()
const usedEdges = new Set()
let frontier = new Set(seedIds)
for (let level = 0; level < depth; level += 1) {
const next = new Set()
for (const [index, edge] of edges.entries()) {
// contains/declares 用于反查归属;向下展开会把一个域或文件的全部成员误当成依赖。
if (
direction === 'downstream' &&
(edge.type === 'contains' || edge.type === 'declares')
) {
continue
}
const fromMatches = direction === 'downstream' && frontier.has(edge.from)
const toMatches = direction === 'upstream' && frontier.has(edge.to)
if (!fromMatches && !toMatches) continue
const target = fromMatches ? edge.to : edge.from
usedEdges.add(index)
if (visited.has(target)) continue
visited.add(target)
discovered.add(target)
next.add(target)
}
frontier = next
if (!frontier.size) break
}
return { discovered, usedEdges }
}
function relatedTestsAndDocuments(graph, relevantIds, nodeById) {
const relevantPaths = new Set(
[...relevantIds]
.map((id) => nodeById.get(id)?.path)
.filter(Boolean),
)
const tests = new Set()
const documents = new Set()
const edgeIndexes = new Set()
for (const [index, edge] of graph.edges.entries()) {
const from = nodeById.get(edge.from)
const to = nodeById.get(edge.to)
const touchesRelevant =
relevantIds.has(edge.from) ||
relevantIds.has(edge.to) ||
relevantPaths.has(from?.path) ||
relevantPaths.has(to?.path)
if (!touchesRelevant) continue
if (edge.type === 'coveredBy' && to?.type === 'test') {
tests.add(to.id)
edgeIndexes.add(index)
}
if (edge.type === 'documentedBy' && to?.type === 'document') {
documents.add(to.id)
edgeIndexes.add(index)
}
}
return { tests, documents, edgeIndexes }
}
/**
* 查询图谱中与关键词相关的上下游、测试、文档和未解析风险。
*
* @param {object} graph 已生成图谱。
* @param {{keywords: string[], depth?: number, direction?: 'both'|'upstream'|'downstream'}} options 查询参数。
* @returns {object} 固定字段和固定排序的查询结果。
*/
export function queryKnowledgeGraph(
graph,
{ keywords, depth = 2, direction = 'both' },
) {
const normalizedKeywords = [...new Set((keywords || []).map((item) => String(item).trim().toLocaleLowerCase('en')).filter(Boolean))]
if (!normalizedKeywords.length) throw new Error('at least one --keyword is required')
if (!Number.isInteger(depth) || depth < 0 || depth > 3) {
throw new Error('--depth must be an integer between 0 and 3')
}
if (!['both', 'upstream', 'downstream'].includes(direction)) {
throw new Error('--direction must be both, upstream, or downstream')
}
const nodeById = new Map(graph.nodes.map((node) => [node.id, node]))
const direct = graph.nodes.filter((node) => {
const value = searchableText(node)
return normalizedKeywords.some((keyword) => value.includes(keyword))
})
const seedIds = new Set(direct.map((node) => node.id))
const upstream =
direction === 'downstream'
? { discovered: new Set(), usedEdges: new Set() }
: walkDirection(seedIds, graph.edges, 'upstream', depth)
const downstream =
direction === 'upstream'
? { discovered: new Set(), usedEdges: new Set() }
: walkDirection(seedIds, graph.edges, 'downstream', depth)
const relevantIds = new Set([
...seedIds,
...upstream.discovered,
...downstream.discovered,
])
const related = relatedTestsAndDocuments(graph, relevantIds, nodeById)
const evidenceIndexes = new Set([
...upstream.usedEdges,
...downstream.usedEdges,
...related.edgeIndexes,
])
const crossDomainRisks = [...evidenceIndexes]
.map((index) => graph.edges[index])
.filter((edge) => {
const fromDomain = nodeById.get(edge.from)?.domain
const toDomain = nodeById.get(edge.to)?.domain
return fromDomain && toDomain && fromDomain !== toDomain
})
.sort((left, right) => compareText(JSON.stringify(left), JSON.stringify(right)))
const relevantPaths = new Set(
[...relevantIds].map((id) => nodeById.get(id)?.path).filter(Boolean),
)
const unresolved = graph.unresolved
.filter(
(item) =>
relevantPaths.has(item.path) ||
normalizedKeywords.some((keyword) => item.path.toLocaleLowerCase('en').includes(keyword)),
)
.sort((left, right) => compareText(JSON.stringify(left), JSON.stringify(right)))
const evidence = [...evidenceIndexes]
.map((index) => graph.edges[index])
.sort((left, right) => compareText(JSON.stringify(left), JSON.stringify(right)))
return {
seeds: stableItems(direct),
directMatches: stableItems(direct),
upstreamConsumers: uniqueNodes(upstream.discovered, nodeById),
downstreamDependencies: uniqueNodes(downstream.discovered, nodeById),
crossDomainRisks,
testCandidates: uniqueNodes(related.tests, nodeById),
documents: uniqueNodes(related.documents, nodeById),
unresolved,
evidence,
}
}
function parseArguments(argv) {
const options = { keywords: [], depth: 2, direction: 'both', format: 'json' }
for (let index = 0; index < argv.length; index += 1) {
const argument = argv[index]
if (argument === '--keyword') options.keywords.push(argv[++index])
else if (argument === '--depth') options.depth = Number(argv[++index])
else if (argument === '--direction') options.direction = argv[++index]
else if (argument === '--format') options.format = argv[++index]
else throw new Error(`unknown argument: ${argument}`)
}
return options
}
function markdownResult(result) {
const section = (title, items) => `## ${title}\n\n${items.length ? items.map((item) => `- \`${item.path || item.id}\``).join('\n') : '- 暂无'}\n`
return `# 影响查询结果\n\n${section('直接命中', result.directMatches)}\n${section('上游消费者', result.upstreamConsumers)}\n${section('下游依赖', result.downstreamDependencies)}\n${section('测试候选', result.testCandidates)}\n${section('相关文档', result.documents)}`
}
async function main() {
const graphPath = path.join(process.cwd(), 'docs/generated/knowledge-graph.json')
if (!fs.existsSync(graphPath)) {
throw new Error('knowledge graph is missing; run npm run knowledge:build first')
}
const graph = JSON.parse(fs.readFileSync(graphPath, 'utf8'))
const options = parseArguments(process.argv.slice(2))
const result = queryKnowledgeGraph(graph, options)
if (options.format === 'json') console.log(JSON.stringify(result, null, 2))
else if (options.format === 'md' || options.format === 'markdown') {
console.log(markdownResult(result))
} else {
throw new Error('--format must be json or md')
}
}
const isMain =
process.argv[1] &&
path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url))
if (isMain) await main()