knowledge-artifacts.mjs
10.3 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
/**
* @file 将知识图谱渲染为面向开发者的 Markdown 视图,并执行漂移检查。
*/
import fs from 'node:fs'
import path from 'node:path'
import { serializeGraph } from './build-knowledge-graph.mjs'
function compareText(left, right) {
return left < right ? -1 : left > right ? 1 : 0
}
function sortById(items) {
return [...items].sort((left, right) => compareText(left.id, right.id))
}
function displayPath(node) {
return node.path || node.name || node.id
}
function sortedUnique(items) {
return [...new Set(items.filter(Boolean))].sort(compareText)
}
function markdownTable(headers, rows) {
const heading = `| ${headers.join(' | ')} |`
const divider = `| ${headers.map(() => '---').join(' | ')} |`
if (!rows.length) return `${heading}\n${divider}\n| ${headers.map((_, index) => (index === 0 ? '暂无' : '')).join(' | ')} |`
return [
heading,
divider,
...rows.map((row) => `| ${row.map((cell) => String(cell).replace(/\|/g, '\\|')).join(' | ')} |`),
].join('\n')
}
function generatedNotice() {
return '> 此文件由 `npm run knowledge:build` 生成。代码事实请勿手工修改;业务语义维护在 `docs/knowledge/`。'
}
function projectSummary(graph) {
const typeRows = Object.entries(graph.stats.nodeTypes).map(([type, count]) => [type, count])
const edgeRows = Object.entries(graph.stats.edgeTypes).map(([type, count]) => [type, count])
return `# 项目知识图谱概览
${generatedNotice()}
## 规模
- 节点:${graph.stats.nodeCount}
- 关系:${graph.stats.edgeCount}
- 未解析:${graph.stats.unresolvedCount}
## 节点类型
${markdownTable(['类型', '数量'], typeRows)}
## 关系类型
${markdownTable(['类型', '数量'], edgeRows)}
## 使用入口
- 更新事实:\`npm run knowledge:build\`
- 检查漂移:\`npm run knowledge:check\`
- 查询影响:\`npm run impact -- --keyword <关键词> --depth 2 --direction both --format json\`
`
}
function domainView(graph, domain) {
const nodeById = new Map(graph.nodes.map((node) => [node.id, node]))
const linkedDocuments = graph.edges
.filter(
(edge) =>
edge.from === domain.id && edge.type === 'documentedBy',
)
.map((edge) => nodeById.get(edge.to))
.filter((node) => node?.type === 'document')
const nodes = [
...new Map(
[
...graph.nodes.filter((node) => node.domain === domain.name),
...linkedDocuments,
].map((node) => [node.id, node]),
).values(),
]
const rows = ['page', 'component', 'apiOperation', 'globalState', 'test', 'document'].map((type) => [
type,
nodes.filter((node) => node.type === type).length,
])
const entrypoints = domain.entrypoints || []
const nodeRows = sortById(nodes)
.filter((node) => ['page', 'component', 'apiOperation', 'globalState', 'test', 'document'].includes(node.type))
.map((node) => [
node.type,
`\`${
node.type === 'apiOperation'
? `${node.path}#${node.name}`
: displayPath(node)
}\``,
])
const gapRows = (domain.knownGaps || []).map((gap) => [gap.reason, gap.nextStep])
return `# ${domain.name} 领域索引
${generatedNotice()}
## 人工语义
- 别名:${(domain.aliases || []).join('、') || '未维护'}
- 根目录:${(domain.roots || []).map((item) => `\`${item}\``).join('、') || '未维护'}
- 核心入口:${entrypoints.map((item) => `\`${item}\``).join('、') || '未维护'}
- 风险关键词:${(domain.riskKeywords || []).map((item) => `\`${item}\``).join('、') || '未维护'}
## 已知文档缺口
${markdownTable(['缺口', '补齐时机'], gapRows)}
## 机器事实统计
${markdownTable(['类型', '数量'], rows)}
## 可定位实体
${markdownTable(['类型', '路径/符号'], nodeRows)}
`
}
function apiCallerIndex(graph) {
const nodeById = new Map(graph.nodes.map((node) => [node.id, node]))
const operations = sortById(graph.nodes.filter((node) => node.type === 'apiOperation'))
const rows = operations.map((operation) => {
const callers = sortedUnique(
graph.edges
.filter((edge) => edge.type === 'callsApi' && edge.to === operation.id)
.map((edge) => displayPath(nodeById.get(edge.from))),
)
const endpoints = sortedUnique(
graph.edges
.filter((edge) => edge.type === 'callsEndpoint' && edge.from === operation.id)
.map((edge) => displayPath(nodeById.get(edge.to))),
)
return [
`\`${operation.path}#${operation.name}\``,
callers.map((item) => `\`${item}\``).join('<br>') || '—',
endpoints.map((item) => `\`${item}\``).join('<br>') || '—',
]
})
return `# API 调用方索引
${generatedNotice()}
${markdownTable(['API 操作', '调用方', '后端路径'], rows)}
`
}
function routeIndex(graph) {
const nodeById = new Map(graph.nodes.map((node) => [node.id, node]))
const rows = graph.edges
.filter((edge) => edge.type === 'navigatesTo')
.map((edge) => [
`\`${displayPath(nodeById.get(edge.from))}\``,
`\`${displayPath(nodeById.get(edge.to))}\``,
`\`${edge.evidence.path}:${edge.evidence.line}\``,
])
return `# 路由索引
${generatedNotice()}
${markdownTable(['来源', '目标页面', '证据'], rows)}
`
}
function globalStateIndex(graph) {
const nodeById = new Map(graph.nodes.map((node) => [node.id, node]))
const states = sortById(graph.nodes.filter((node) => node.type === 'globalState'))
const rows = states.map((state) => {
const readers = sortedUnique(
graph.edges
.filter((edge) => edge.type === 'readsState' && edge.to === state.id)
.map((edge) => displayPath(nodeById.get(edge.from))),
)
const writers = sortedUnique(
graph.edges
.filter((edge) => edge.type === 'writesState' && edge.to === state.id)
.map((edge) => displayPath(nodeById.get(edge.from))),
)
return [
`\`${state.name}\``,
readers.map((item) => `\`${item}\``).join('<br>') || '—',
writers.map((item) => `\`${item}\``).join('<br>') || '—',
]
})
return `# 全局状态索引
${generatedNotice()}
${markdownTable(['状态', '读取方', '写入方'], rows)}
`
}
function componentPageIndex(graph) {
const nodeById = new Map(graph.nodes.map((node) => [node.id, node]))
const components = sortById(graph.nodes.filter((node) => node.type === 'component'))
const rows = components.map((component) => {
const edges = graph.edges.filter(
(edge) => edge.type === 'usesComponent' && edge.to === component.id,
)
const consumers = sortedUnique(
edges.map((edge) => {
const owner = nodeById.get(edge.from)
return edge.evidence.path === 'app.json'
? 'app.json (global)'
: displayPath(owner)
}),
)
const highRisk =
consumers.length >= 5 ||
/Merchant-Seles|Coupon|Popup/i.test(component.path || component.name)
return [
highRisk ? '**高**' : '',
`\`${component.path}\``,
consumers.length,
consumers.map((item) => `\`${item}\``).join('<br>') || '—',
]
})
return `# 组件 → 页面反向索引(usingComponents)
${generatedNotice()}
> 边界:本地组件注册来自 JSON,应用级组件同时结合 WXML 实际标签;第三方组件不进入业务图谱。
高风险:引用数 ≥ 5,或命中 Merchant-Seles / Coupon / Popup 等治理名单。
${markdownTable(['风险', '组件路径', '引用数', '引用方'], rows)}
`
}
/**
* 生成全部受管产物的内存内容。
*
* @param {object} graph 知识图谱。
* @returns {Map<string, string>} 相对路径到稳定文本的映射。
*/
export function createKnowledgeArtifactContents(graph) {
const contents = new Map()
contents.set('docs/COMPONENT-PAGE-INDEX.md', componentPageIndex(graph))
contents.set('docs/generated/API-CALLER-INDEX.md', apiCallerIndex(graph))
contents.set('docs/generated/GLOBAL-STATE-INDEX.md', globalStateIndex(graph))
contents.set('docs/generated/PROJECT-SUMMARY.md', projectSummary(graph))
contents.set('docs/generated/ROUTE-PAGE-INDEX.md', routeIndex(graph))
for (const domain of sortById(
graph.nodes.filter((node) => node.type === 'domain'),
)) {
contents.set(`docs/generated/domains/${domain.name}.md`, domainView(graph, domain))
}
contents.set('docs/generated/knowledge-graph.json', serializeGraph(graph))
return new Map([...contents].sort(([left], [right]) => compareText(left, right)))
}
function obsoleteDomainArtifacts(contents, rootDir) {
const relativeDirectory = 'docs/generated/domains'
const directory = path.join(rootDir, relativeDirectory)
if (!fs.existsSync(directory)) return []
const expected = new Set(
[...contents.keys()].filter((item) =>
item.startsWith(`${relativeDirectory}/`),
),
)
return fs
.readdirSync(directory, { withFileTypes: true })
.filter((entry) => entry.isFile() && entry.name.endsWith('.md'))
.map((entry) => `${relativeDirectory}/${entry.name}`)
.filter((item) => !expected.has(item))
.sort(compareText)
}
/**
* 写入知识图谱及 Markdown 视图。
*
* @param {{graph: object, rootDir: string}} options 图谱与目标项目根目录。
* @returns {string[]} 已写入的相对路径。
*/
export function writeKnowledgeArtifacts({ graph, rootDir }) {
const contents = createKnowledgeArtifactContents(graph)
for (const relativePath of obsoleteDomainArtifacts(contents, rootDir)) {
fs.rmSync(path.join(rootDir, relativePath))
}
for (const [relativePath, content] of contents) {
const outputPath = path.join(rootDir, relativePath)
fs.mkdirSync(path.dirname(outputPath), { recursive: true })
fs.writeFileSync(outputPath, content.endsWith('\n') ? content : `${content}\n`, 'utf8')
}
return [...contents.keys()]
}
/**
* 比较磁盘产物与当前图谱,返回缺失或漂移文件。
*
* @param {{graph: object, rootDir: string}} options 图谱与项目根目录。
* @returns {string[]} 漂移的相对路径。
*/
export function checkKnowledgeArtifacts({ graph, rootDir }) {
const contents = createKnowledgeArtifactContents(graph)
const drift = []
for (const [relativePath, rawContent] of contents) {
const expected = rawContent.endsWith('\n') ? rawContent : `${rawContent}\n`
const absolutePath = path.join(rootDir, relativePath)
if (!fs.existsSync(absolutePath) || fs.readFileSync(absolutePath, 'utf8') !== expected) {
drift.push(relativePath)
}
}
return [...drift, ...obsoleteDomainArtifacts(contents, rootDir)].sort(compareText)
}