verify-md-links.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. /**
  2. * Doc-sync gate: verify that every relative Markdown cross-link resolves to a
  3. * file that exists. Docs in this repo link to each other by relative path
  4. * (`[topic](../implemented/2026-…-….md)`, `[the cookbook](adding-a-tool.md)`);
  5. * a rename or a move silently breaks those links, and nothing caught it before
  6. * review. The RFC tree reorganization (one `docs/rfc/` with proposed/
  7. * implemented/ rejected/ subfolders, every file renamed to a dated slug) is the
  8. * motivating case: ~40 inter-doc links were rewritten by hand, and a single
  9. * fat-fingered path would have shipped a dead link.
  10. *
  11. * Detection is AST-based, mirroring verify-md-wrap: parse each file with
  12. * mdast-util-from-markdown + GFM, then walk every `link`, `image`, and
  13. * `definition` node. A target is checked when it is a RELATIVE path; these are
  14. * skipped because they are not ours to verify:
  15. * - absolute URLs with a scheme (`https:`, `http:`, `mailto:`, …),
  16. * - protocol-relative URLs (`//host/path`),
  17. * - root-absolute paths (`/foo` — no stable base in a repo checkout),
  18. * - pure in-page anchors (`#section`).
  19. * For a relative target the `#fragment` and `?query` are stripped, the path is
  20. * resolved against the linking file's directory, and the result must exist on
  21. * disk. This is checker, not fixer: it reports and never rewrites.
  22. *
  23. * Scope is the other doc-sync gates' set plus the two AGENTS.md files AND the
  24. * repo-authored agent-skill Markdown under `.agents/skills/` — those skill
  25. * files cross-link into the docs tree (e.g. the dsh-code-review skill cites the
  26. * RFC index), so a rename must not silently break them either: README.md,
  27. * docs/** /*.md, packages/* /README.md, AGENTS.md, packages/AGENTS.md,
  28. * .agents/skills/** /*.md. The root and packages/ CLAUDE.md are symlinks to the
  29. * AGENTS.md files, so they are deduped by real path.
  30. *
  31. * Run: `tsx scripts/verify-md-links.ts`.
  32. */
  33. import { existsSync, readFileSync, realpathSync } from 'node:fs'
  34. import { dirname, relative, resolve } from 'node:path'
  35. import { glob } from 'node:fs/promises'
  36. import { fromMarkdown } from 'mdast-util-from-markdown'
  37. import { gfmFromMarkdown } from 'mdast-util-gfm'
  38. import { gfm } from 'micromark-extension-gfm'
  39. import type { Nodes } from 'mdast'
  40. const root = resolve(import.meta.dirname, '..')
  41. /**
  42. * Files to check: doc-typecheck's scope, the AGENTS.md pair, and repo-authored
  43. * agent-skill Markdown (which this repo's own docs reorg rewrites links in).
  44. */
  45. const PATTERNS = [
  46. 'README.md',
  47. 'docs/**/*.md',
  48. 'packages/*/README.md',
  49. 'AGENTS.md',
  50. 'packages/AGENTS.md',
  51. '.agents/skills/**/*.md',
  52. ]
  53. /** A broken relative link: a target path that does not resolve to a file. */
  54. interface Violation {
  55. file: string
  56. /** 1-based line where the link/image/definition node starts. */
  57. line: number
  58. url: string
  59. }
  60. /**
  61. * True for targets this gate must NOT check: scheme-qualified URLs (`https:`,
  62. * `mailto:`, …), protocol-relative (`//host`), root-absolute (`/path`), and
  63. * pure in-page anchors (`#frag`). Everything else is a relative path we own.
  64. */
  65. function isExternalOrAnchor(url: string): boolean {
  66. if (url.startsWith('#')) return true
  67. if (url.startsWith('//')) return true
  68. if (url.startsWith('/')) return true
  69. // A scheme like `https:` / `mailto:` — a colon before any slash, dot, or hash.
  70. return /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url)
  71. }
  72. /**
  73. * Strip the `#fragment` and `?query` from a link target, then percent-decode
  74. * the remaining path so an encoded target (`My%20File.md`, `READ%4DE.md`)
  75. * probes the real filename on disk, the way a Markdown renderer resolves it. A
  76. * malformed escape (`%zz`) makes `decodeURIComponent` throw; we keep the raw
  77. * path in that case so the link is reported as broken (a `%zz` target is not a
  78. * file anyone meant to link) rather than crashing the gate.
  79. */
  80. function pathPart(url: string): string {
  81. const raw = url.replace(/[#?].*$/, '')
  82. try {
  83. return decodeURIComponent(raw)
  84. } catch {
  85. // decodeURIComponent throws only on a malformed percent-escape; the raw
  86. // string is then a path no renderer resolves, so fall through to the
  87. // existence check, which reports it broken.
  88. return raw
  89. }
  90. }
  91. /** Find every broken relative cross-link in one Markdown file via its AST. */
  92. function findViolations(absPath: string): Violation[] {
  93. const file = relative(root, absPath)
  94. const dir = dirname(absPath)
  95. const source = readFileSync(absPath, 'utf8')
  96. const tree = fromMarkdown(source, { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()] })
  97. const out: Violation[] = []
  98. const check = (url: string, node: Nodes): void => {
  99. if (isExternalOrAnchor(url)) return
  100. const target = pathPart(url)
  101. // A bare `#anchor` reduced to empty path is a same-file anchor — skip.
  102. if (target === '') return
  103. const resolved = resolve(dir, target)
  104. if (!existsSync(resolved)) {
  105. out.push({ file, line: node.position?.start.line ?? 0, url })
  106. }
  107. }
  108. const visit = (node: Nodes): void => {
  109. if ((node.type === 'link' || node.type === 'image' || node.type === 'definition') && 'url' in node) {
  110. check(node.url, node)
  111. }
  112. if ('children' in node) {
  113. for (const child of node.children) visit(child)
  114. }
  115. }
  116. visit(tree)
  117. return out
  118. }
  119. const seen = new Set<string>()
  120. const all: Violation[] = []
  121. let checked = 0
  122. for (const pattern of PATTERNS) {
  123. for await (const match of glob(pattern, { cwd: root })) {
  124. const abs = resolve(root, match)
  125. // CLAUDE.md symlinks resolve onto AGENTS.md; dedupe by real path so a file
  126. // matched twice (or via symlink) is checked once.
  127. const real = realpathSync(abs)
  128. if (seen.has(real)) continue
  129. seen.add(real)
  130. checked++
  131. all.push(...findViolations(abs))
  132. }
  133. }
  134. if (all.length === 0) {
  135. console.log(`verify-md-links: ${checked} file(s) checked, all relative cross-links resolve.`)
  136. process.exit(0)
  137. }
  138. console.error('verify-md-links: broken relative cross-links found (target does not exist):')
  139. for (const v of all) {
  140. console.error(` ${v.file}:${v.line} ${v.url}`)
  141. }
  142. process.exit(1)