cli.test.mjs 1.76 KB
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/)
})