verify-package-paths.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. * A reference to a package's build OUTPUT (`packages/<group>/<pkg>/lib/…`,
  32. * e.g. `packages/ui/acp-agent/lib/bin.js` cited by a built-bin smoke) is also
  33. * skipped — it is emitted only by `pnpm run build`, which CI runs AFTER this
  34. * gate, so flagging it would be a false positive on a path that is correct but
  35. * not yet on disk. That skip is scoped to a REAL package root: a stale
  36. * group-less `packages/acp-agent/lib/bin.js` is still flagged (its root does not
  37. * exist — exactly the moved-package drift this gate catches).
  38. *
  39. * Run: `tsx scripts/verify-package-paths.ts`.
  40. */
  41. import { existsSync, globSync, readdirSync, readFileSync, realpathSync } from 'node:fs'
  42. import { relative, resolve } from 'node:path'
  43. const root = resolve(import.meta.dirname, '..')
  44. /** Markdown + repo-authored TypeScript that may cite package paths. */
  45. const PATTERNS = [
  46. 'README.md',
  47. 'docs/**/*.md',
  48. 'packages/*/*.md',
  49. 'packages/*/*/*.md',
  50. 'AGENTS.md',
  51. 'packages/AGENTS.md',
  52. 'packages/**/*.ts',
  53. 'examples/**/*.ts',
  54. ]
  55. /** Paths excluded from the scan: built output and vendored upstream source. */
  56. const isExcluded = (p: string): boolean =>
  57. p.includes('/lib/') || p.endsWith('.d.ts') || p.startsWith('vendor/')
  58. /**
  59. * Directory names of every real package, `packages/<group>/<pkg>`. A broken
  60. * reference is only flagged when one of its segments is in this set — that is
  61. * what scopes the gate to DRIFT (a moved real package) rather than typos or
  62. * not-yet-existing packages named in a proposal.
  63. */
  64. function realPackageNames(): Set<string> {
  65. const names = new Set<string>()
  66. const pkgRoot = resolve(root, 'packages')
  67. for (const group of readdirSync(pkgRoot, { withFileTypes: true })) {
  68. if (!group.isDirectory()) continue
  69. for (const pkg of readdirSync(resolve(pkgRoot, group.name), { withFileTypes: true })) {
  70. if (pkg.isDirectory()) names.add(pkg.name)
  71. }
  72. }
  73. return names
  74. }
  75. const packageNames = realPackageNames()
  76. /**
  77. * Match a `packages/<path>` reference token. The character class is plain path
  78. * characters only, so a glob (`*`), placeholder (`<`, `>`), or brace expansion
  79. * (`{`, `}`, `,`) terminates the match before those chars and is never probed —
  80. * those are patterns, not real paths. A trailing `.`/`/` (e.g. a sentence-ending
  81. * period) is trimmed before the existence check.
  82. */
  83. const PKG_REF = /\bpackages\/[A-Za-z0-9._/-]+/g
  84. /** A broken package reference: a stale root-relative `packages/…` path. */
  85. interface Violation {
  86. file: string
  87. /** 1-based line where the reference appears. */
  88. line: number
  89. ref: string
  90. }
  91. /**
  92. * Find every DRIFTED `packages/…` reference in one file: a token that does not
  93. * resolve on disk AND names a real package in one of its segments (so it is a
  94. * moved path, not a typo or a not-yet-existing package). The same real-package
  95. * test also screens out a bare `packages` (no segment) and illustrative
  96. * skeletons whose segment is not a package.
  97. */
  98. function findViolations(absPath: string): Violation[] {
  99. const file = relative(root, absPath)
  100. const source = readFileSync(absPath, 'utf8')
  101. const out: Violation[] = []
  102. const lines = source.split('\n')
  103. for (let i = 0; i < lines.length; i++) {
  104. const line = lines[i]
  105. if (line === undefined) continue
  106. for (const m of line.matchAll(PKG_REF)) {
  107. // Trim a trailing path separator or sentence punctuation that the greedy
  108. // class may have swallowed (`packages/core/tools.` / `…/tools/`).
  109. const ref = m[0].replace(/[./]+$/, '')
  110. if (existsSync(resolve(root, ref))) continue
  111. // A reference INTO a package's built `lib/` is a build OUTPUT, not an
  112. // authored-source location: it does not exist until `pnpm run build` emits
  113. // it, and CI runs this gate BEFORE the build step. Skip it — but ONLY when
  114. // the `packages/<group>/<pkg>` ROOT it sits under is real and on disk, so
  115. // `packages/ui/acp-agent/lib/bin.js` (correct, just not yet built) is
  116. // exempt while a stale `packages/acp-agent/lib/bin.js` (group-less, the
  117. // exact moved-package drift this gate exists to catch) still flags. A bare
  118. // `lib` segment is not a blanket escape hatch.
  119. const parts = ref.split('/')
  120. const libAt = parts.indexOf('lib')
  121. if (libAt === 3 && existsSync(resolve(root, parts.slice(0, 3).join('/')))) continue
  122. // Only a stale path to a REAL (moved) package is a violation; a segment
  123. // matching a live package name is the drift signal.
  124. const segments = ref.split('/').slice(1)
  125. if (segments.some(seg => packageNames.has(seg))) {
  126. out.push({ file, line: i + 1, ref })
  127. }
  128. }
  129. }
  130. return out
  131. }
  132. const all: Violation[] = []
  133. let checked = 0
  134. const seen = new Set<string>()
  135. for (const pattern of PATTERNS) {
  136. for (const match of globSync(pattern, { cwd: root })) {
  137. if (isExcluded(match)) continue
  138. // Dedup by real path: the root/packages CLAUDE.md are symlinks to AGENTS.md.
  139. const real = realpathSync(resolve(root, match))
  140. if (seen.has(real)) continue
  141. seen.add(real)
  142. checked++
  143. all.push(...findViolations(real))
  144. }
  145. }
  146. if (all.length === 0) {
  147. console.log(`verify-package-paths: ${checked} file(s) checked, all packages/* references resolve.`)
  148. process.exit(0)
  149. }
  150. console.error('verify-package-paths: broken packages/* references found (target does not exist):')
  151. for (const v of all) {
  152. console.error(` ${v.file}:${v.line} ${v.ref}`)
  153. }
  154. process.exit(1)