artifactsAndImpact.test.mjs 6.52 KB
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)
})