verify-package-paths.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. /**
  2. * Doc-sync gate: catch DRIFTED `packages/<path>` references — a path to a
  3. * package that has MOVED, written as prose in Markdown or in a TypeScript
  4. * comment/string. Docs and comments cite package locations by root-relative
  5. * path (`packages/core/tools/src/index.ts`, `see packages/ui/acp`);
  6. * `verify-md-links` only parses Markdown LINK targets and `verify-doc-refs`
  7. * only checks `docs/*.md` tokens, so a `packages/…` path sitting in backtick
  8. * prose or a code comment goes unchecked. The package-hierarchy reorg is the
  9. * motivating case: it moved every package under a `{group}/` folder, so a stale
  10. * `packages/tools` (now `packages/core/tools`) reads fine to a human but points
  11. * at nothing.
  12. *
  13. * The check is drift-scoped, NOT a blanket existence test: a broken
  14. * `packages/<path>` token is a violation ONLY when one of its path segments is
  15. * the directory name of a package that actually exists on disk — i.e. the
  16. * package is real and the path is merely stale. A token naming a package that
  17. * exists NOWHERE (`packages/code-runtime` in a forward-looking proposal, an
  18. * illustrative `packages/<name>/` skeleton) is left alone: this gate reports
  19. * MOVED paths, not hypothetical or future ones, so it applies uniformly to
  20. * proposed/implemented/rejected docs without per-lifecycle exclusions. This is
  21. * checker, not fixer: it reports and never rewrites.
  22. *
  23. * Detection is a token scan, NOT an AST walk: package refs live in free prose,
  24. * backticks, and comments. We match `packages/<path>` tokens whose path is made
  25. * of plain path characters, so a glob, a `<placeholder>`, or a `{brace,expansion}`
  26. * terminates the match before those chars and is never probed.
  27. *
  28. * Scope mirrors the other doc gates plus repo-authored TypeScript: Markdown
  29. * across README/docs/packages/AGENTS, and `.ts` under packages/** and
  30. * examples/** (excluding built `lib/`, `*.d.ts`, and vendored upstream source).
  31. *
  32. * Run: `tsx scripts/verify-package-paths.ts`.
  33. */
  34. import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs'
  35. import { relative, resolve } from 'node:path'
  36. import { glob } from 'node:fs/promises'
  37. const root = resolve(import.meta.dirname, '..')
  38. /** Markdown + repo-authored TypeScript that may cite package paths. */
  39. const PATTERNS = [
  40. 'README.md',
  41. 'docs/**/*.md',
  42. 'packages/*/*.md',
  43. 'packages/*/*/*.md',
  44. 'AGENTS.md',
  45. 'packages/AGENTS.md',
  46. 'packages/**/*.ts',
  47. 'examples/**/*.ts',
  48. ]
  49. /** Paths excluded from the scan: built output and vendored upstream source. */
  50. const isExcluded = (p: string): boolean =>
  51. p.includes('/lib/') || p.endsWith('.d.ts') || p.startsWith('vendor/')
  52. /**
  53. * Directory names of every real package, `packages/<group>/<pkg>`. A broken
  54. * reference is only flagged when one of its segments is in this set — that is
  55. * what scopes the gate to DRIFT (a moved real package) rather than typos or
  56. * not-yet-existing packages named in a proposal.
  57. */
  58. function realPackageNames(): Set<string> {
  59. const names = new Set<string>()
  60. const pkgRoot = resolve(root, 'packages')
  61. for (const group of readdirSync(pkgRoot, { withFileTypes: true })) {
  62. if (!group.isDirectory()) continue
  63. for (const pkg of readdirSync(resolve(pkgRoot, group.name), { withFileTypes: true })) {
  64. if (pkg.isDirectory()) names.add(pkg.name)
  65. }
  66. }
  67. return names
  68. }
  69. const packageNames = realPackageNames()
  70. /**
  71. * Match a `packages/<path>` reference token. The character class is plain path
  72. * characters only, so a glob (`*`), placeholder (`<`, `>`), or brace expansion
  73. * (`{`, `}`, `,`) terminates the match before those chars and is never probed —
  74. * those are patterns, not real paths. A trailing `.`/`/` (e.g. a sentence-ending
  75. * period) is trimmed before the existence check.
  76. */
  77. const PKG_REF = /\bpackages\/[A-Za-z0-9._/-]+/g
  78. /** A broken package reference: a stale root-relative `packages/…` path. */
  79. interface Violation {
  80. file: string
  81. /** 1-based line where the reference appears. */
  82. line: number
  83. ref: string
  84. }
  85. /**
  86. * Find every DRIFTED `packages/…` reference in one file: a token that does not
  87. * resolve on disk AND names a real package in one of its segments (so it is a
  88. * moved path, not a typo or a not-yet-existing package). The same real-package
  89. * test also screens out a bare `packages` (no segment) and illustrative
  90. * skeletons whose segment is not a package.
  91. */
  92. function findViolations(absPath: string): Violation[] {
  93. const file = relative(root, absPath)
  94. const source = readFileSync(absPath, 'utf8')
  95. const out: Violation[] = []
  96. const lines = source.split('\n')
  97. for (let i = 0; i < lines.length; i++) {
  98. const line = lines[i]
  99. if (line === undefined) continue
  100. for (const m of line.matchAll(PKG_REF)) {
  101. // Trim a trailing path separator or sentence punctuation that the greedy
  102. // class may have swallowed (`packages/core/tools.` / `…/tools/`).
  103. const ref = m[0].replace(/[./]+$/, '')
  104. if (existsSync(resolve(root, ref))) continue
  105. // Only a stale path to a REAL (moved) package is a violation; a segment
  106. // matching a live package name is the drift signal.
  107. const segments = ref.split('/').slice(1)
  108. if (segments.some(seg => packageNames.has(seg))) {
  109. out.push({ file, line: i + 1, ref })
  110. }
  111. }
  112. }
  113. return out
  114. }
  115. const all: Violation[] = []
  116. let checked = 0
  117. const seen = new Set<string>()
  118. for (const pattern of PATTERNS) {
  119. for await (const match of glob(pattern, { cwd: root })) {
  120. if (isExcluded(match)) continue
  121. // Dedup by real path: the root/packages CLAUDE.md are symlinks to AGENTS.md.
  122. const real = realpathSync(resolve(root, match))
  123. if (seen.has(real)) continue
  124. seen.add(real)
  125. checked++
  126. all.push(...findViolations(real))
  127. }
  128. }
  129. if (all.length === 0) {
  130. console.log(`verify-package-paths: ${checked} file(s) checked, all packages/* references resolve.`)
  131. process.exit(0)
  132. }
  133. console.error('verify-package-paths: broken packages/* references found (target does not exist):')
  134. for (const v of all) {
  135. console.error(` ${v.file}:${v.line} ${v.ref}`)
  136. }
  137. process.exit(1)