Commit 4191c758 by 张立顺

feat: generate and query project knowledge

1 parent c6c7e451
/**
* @file 构建知识图谱及所有受管 Markdown 视图。
*/
import path from 'node:path'
import { buildKnowledgeGraph } from './build-knowledge-graph.mjs'
import { writeKnowledgeArtifacts } from './knowledge-artifacts.mjs'
function rootArgument(argv) {
const index = argv.indexOf('--root')
if (index === -1) return process.cwd()
if (!argv[index + 1]) throw new Error('--root requires a directory')
return path.resolve(argv[index + 1])
}
/**
* 构建指定项目的图谱及 Markdown 产物。
*
* @param {{rootDir: string}} options 项目根目录。
* @returns {Promise<{graph: object, files: string[]}>} 图谱和写入文件列表。
*/
export async function buildKnowledgeArtifacts({ rootDir }) {
const graph = await buildKnowledgeGraph({ rootDir })
const files = writeKnowledgeArtifacts({ graph, rootDir })
return { graph, files }
}
const rootDir = rootArgument(process.argv.slice(2))
const { graph, files } = await buildKnowledgeArtifacts({ rootDir })
console.log(
`knowledge graph: ${graph.stats.nodeCount} nodes, ${graph.stats.edgeCount} edges, ${graph.stats.unresolvedCount} unresolved`,
)
console.log(`wrote ${files.length} managed artifacts`)
/**
* @file 重新扫描源码并检查受管知识产物是否漂移。
*/
import path from 'node:path'
import { buildKnowledgeGraph } from './build-knowledge-graph.mjs'
import { checkKnowledgeArtifacts } from './knowledge-artifacts.mjs'
function rootArgument(argv) {
const index = argv.indexOf('--root')
if (index === -1) return process.cwd()
if (!argv[index + 1]) throw new Error('--root requires a directory')
return path.resolve(argv[index + 1])
}
/**
* 检查指定项目的知识图谱与 Markdown 视图是否需要重新生成。
*
* @param {{rootDir: string}} options 项目根目录。
* @returns {Promise<string[]>} 漂移文件列表。
*/
export async function checkCurrentKnowledgeArtifacts({ rootDir }) {
const graph = await buildKnowledgeGraph({ rootDir })
return checkKnowledgeArtifacts({ graph, rootDir })
}
const rootDir = rootArgument(process.argv.slice(2))
const drift = await checkCurrentKnowledgeArtifacts({ rootDir })
if (drift.length) {
console.error('knowledge artifacts are stale:')
for (const file of drift) console.error(`- ${file}`)
console.error('run npm run knowledge:build')
process.exitCode = 1
} else {
console.log('knowledge artifacts are current')
}
/**
* @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()
import assert from 'node:assert/strict'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import test from 'node:test'
import { fileURLToPath, pathToFileURL } from 'node:url'
const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
const fixtureRoot = path.join(
projectRoot,
'tests/knowledge-graph/fixtures/mini-program',
)
const scriptsRoot = path.join(projectRoot, 'scripts/knowledge-graph')
async function loadModule(fileName) {
const modulePath = path.join(scriptsRoot, fileName)
assert.equal(fs.existsSync(modulePath), true, `${fileName} must exist`)
return import(pathToFileURL(modulePath))
}
async function fixtureGraph() {
const { buildKnowledgeGraph } = await loadModule('build-knowledge-graph.mjs')
return buildKnowledgeGraph({ rootDir: fixtureRoot })
}
test('renders all generated views and reports drift', async (t) => {
const { writeKnowledgeArtifacts, checkKnowledgeArtifacts } =
await loadModule('knowledge-artifacts.mjs')
const graph = await fixtureGraph()
const outputRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'knowledge-artifacts-'))
t.after(() => fs.rmSync(outputRoot, { recursive: true, force: true }))
const written = writeKnowledgeArtifacts({ graph, rootDir: outputRoot })
assert.deepEqual(written, [
'docs/COMPONENT-PAGE-INDEX.md',
'docs/generated/API-CALLER-INDEX.md',
'docs/generated/GLOBAL-STATE-INDEX.md',
'docs/generated/PROJECT-SUMMARY.md',
'docs/generated/ROUTE-PAGE-INDEX.md',
'docs/generated/domains/main.md',
'docs/generated/domains/pkg.md',
'docs/generated/knowledge-graph.json',
])
const componentIndex = fs.readFileSync(
path.join(outputRoot, 'docs/COMPONENT-PAGE-INDEX.md'),
'utf8',
)
const componentLine = componentIndex
.split(/\r?\n/)
.find((line) => line.includes('`components/card/card`'))
assert.match(componentLine, /\| 2 \|/)
assert.equal((componentLine.match(/`pages\/home\/home`/g) || []).length, 1)
const apiIndex = fs.readFileSync(
path.join(outputRoot, 'docs/generated/API-CALLER-INDEX.md'),
'utf8',
)
const apiLine = apiIndex
.split(/\r?\n/)
.find((line) => line.includes('`api/order.js#fetchOrder`'))
assert.equal((apiLine.match(/`pages\/home\/home.js`/g) || []).length, 1)
const stateIndex = fs.readFileSync(
path.join(outputRoot, 'docs/generated/GLOBAL-STATE-INDEX.md'),
'utf8',
)
const stateLine = stateIndex
.split(/\r?\n/)
.find((line) => line.includes('`wx.$orderListRefresh`'))
assert.equal((stateLine.match(/`pages\/home\/home.js`/g) || []).length, 1)
const mainDomain = fs.readFileSync(
path.join(outputRoot, 'docs/generated/domains/main.md'),
'utf8',
)
assert.match(mainDomain, /docs\/home\.md/)
assert.match(mainDomain, /api\/order\.js#fetchOrder/)
assert.match(
fs.readFileSync(path.join(outputRoot, 'docs/generated/domains/pkg.md'), 'utf8'),
/fixture business semantics are not documented/,
)
assert.deepEqual(checkKnowledgeArtifacts({ graph, rootDir: outputRoot }), [])
fs.appendFileSync(
path.join(outputRoot, 'docs/generated/PROJECT-SUMMARY.md'),
'drift',
)
assert.deepEqual(checkKnowledgeArtifacts({ graph, rootDir: outputRoot }), [
'docs/generated/PROJECT-SUMMARY.md',
])
})
test('reports and removes obsolete generated domain files', async (t) => {
const { writeKnowledgeArtifacts, checkKnowledgeArtifacts } =
await loadModule('knowledge-artifacts.mjs')
const graph = await fixtureGraph()
const outputRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'knowledge-stale-domain-'))
t.after(() => fs.rmSync(outputRoot, { recursive: true, force: true }))
writeKnowledgeArtifacts({ graph, rootDir: outputRoot })
const staleRelative = 'docs/generated/domains/removed-domain.md'
const stalePath = path.join(outputRoot, staleRelative)
fs.writeFileSync(stalePath, '# obsolete\n')
assert.deepEqual(checkKnowledgeArtifacts({ graph, rootDir: outputRoot }), [
staleRelative,
])
writeKnowledgeArtifacts({ graph, rootDir: outputRoot })
assert.equal(fs.existsSync(stalePath), false)
})
test('queries upstream consumers, downstream dependencies, tests and docs', async () => {
const { queryKnowledgeGraph } = await loadModule('query-knowledge-graph.mjs')
const graph = await fixtureGraph()
const result = queryKnowledgeGraph(graph, {
keywords: ['orderListRefresh'],
depth: 2,
direction: 'both',
})
assert.deepEqual(Object.keys(result), [
'seeds',
'directMatches',
'upstreamConsumers',
'downstreamDependencies',
'crossDomainRisks',
'testCandidates',
'documents',
'unresolved',
'evidence',
])
assert.ok(result.seeds.some((node) => node.id === 'globalState:wx.$orderListRefresh'))
const relatedNodes = [...result.directMatches, ...result.upstreamConsumers]
assert.ok(relatedNodes.some((node) => node.id.includes('pages/home/home.js#loadPageData')))
assert.ok(relatedNodes.some((node) => node.id.includes('pkg/pages/detail/detail.js#onLoad')))
assert.ok(result.testCandidates.some((node) => node.path === 'tests/home.test.mjs'))
assert.equal(
result.downstreamDependencies.some(
(node) => node.path === 'tests/main-unrelated.test.mjs',
),
false,
'domain containment must not expand a field query to unrelated sources',
)
assert.ok(result.documents.some((node) => node.path === 'docs/home.md'))
assert.ok(result.evidence.every((edge) => edge.evidence.path && edge.type))
})
test('supports directional queries without classifying required changes', async () => {
const { queryKnowledgeGraph } = await loadModule('query-knowledge-graph.mjs')
const graph = await fixtureGraph()
const result = queryKnowledgeGraph(graph, {
keywords: ['fetchOrder'],
depth: 2,
direction: 'upstream',
})
assert.equal('requiredChanges' in result, false)
assert.ok(result.seeds.some((node) => node.type === 'apiOperation'))
assert.ok(result.upstreamConsumers.some((node) => node.id.includes('#loadPageData')))
assert.deepEqual(result.downstreamDependencies, [])
})
test('matches field identifiers without persisting their runtime values', async () => {
const { queryKnowledgeGraph } = await loadModule('query-knowledge-graph.mjs')
const graph = await fixtureGraph()
const result = queryKnowledgeGraph(graph, {
keywords: ['yqMerchantId'],
depth: 1,
direction: 'both',
})
assert.ok(
result.directMatches.some(
(node) =>
node.type === 'method' &&
node.id.includes('pages/home/home.js#loadPageData'),
),
)
assert.equal(JSON.stringify(result).includes('id=fixture'), false)
})
import assert from 'node:assert/strict'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { spawnSync } from 'node:child_process'
import test from 'node:test'
import { fileURLToPath } from 'node:url'
const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
const fixtureRoot = path.join(
projectRoot,
'tests/knowledge-graph/fixtures/mini-program',
)
function runScript(script, args) {
return spawnSync(process.execPath, [path.join(projectRoot, script), ...args], {
cwd: projectRoot,
encoding: 'utf8',
})
}
test('build and check CLIs manage the same deterministic artifacts', (t) => {
const buildScript = 'scripts/knowledge-graph/knowledge-build.mjs'
const checkScript = 'scripts/knowledge-graph/knowledge-check.mjs'
assert.equal(fs.existsSync(path.join(projectRoot, buildScript)), true, 'build CLI must exist')
assert.equal(fs.existsSync(path.join(projectRoot, checkScript)), true, 'check CLI must exist')
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'knowledge-cli-'))
t.after(() => fs.rmSync(tempRoot, { recursive: true, force: true }))
fs.cpSync(fixtureRoot, tempRoot, { recursive: true })
const build = runScript(buildScript, ['--root', tempRoot])
assert.equal(build.status, 0, build.stderr)
assert.match(build.stdout, /knowledge graph: \d+ nodes, \d+ edges/)
const check = runScript(checkScript, ['--root', tempRoot])
assert.equal(check.status, 0, check.stderr)
assert.match(check.stdout, /knowledge artifacts are current/)
fs.appendFileSync(
path.join(tempRoot, 'docs/generated/PROJECT-SUMMARY.md'),
'drift',
)
const stale = runScript(checkScript, ['--root', tempRoot])
assert.equal(stale.status, 1)
assert.match(stale.stderr, /PROJECT-SUMMARY\.md/)
})
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!