rfc-index.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. /**
  2. * Shared source of truth for the RFC index: the tree walker (structure rules)
  3. * and the README table renderer. `gen-rfc-index.ts` writes the generated
  4. * regions; `verify-rfc-classification.ts` checks structure and asserts the
  5. * committed regions are fresh. Pure module — no side effects on import.
  6. *
  7. * The layout contract ([the classification RFC](../docs/rfc/implemented/process/2026-06-20-rfc-classification.md)):
  8. * every RFC lives at `docs/rfc/{lifecycle}/{class}/yyyy-mm-dd-topic.md`, the
  9. * folder IS the label, and both sets are CLOSED — extending either means
  10. * amending this module AND the README's Classification prose.
  11. *
  12. * The index (`docs/rfc/INDEX.md`) is GENERATED in full: per-lifecycle sections
  13. * whose rows are derived from each RFC's path (lifecycle/class), H1 (title,
  14. * with an optional `RFC: ` prefix stripped), and filename date, sorted by date
  15. * then filename. The curated prose lives in README.md, which carries no index
  16. * rows at all.
  17. */
  18. import { readFileSync, readdirSync } from 'node:fs'
  19. import { resolve } from 'node:path'
  20. import { globSync } from 'node:fs'
  21. export const rfcRoot = resolve(import.meta.dirname, '../docs/rfc')
  22. /** The closed set of RFC lifecycles (top-level folders under docs/rfc/). */
  23. const LIFECYCLES = ['proposed', 'implemented', 'rejected'] as const
  24. /**
  25. * The closed set of RFC classes (nested folder under each lifecycle). Adding a
  26. * class is a deliberate act: extend this list AND the README's Classification
  27. * section. The gate rejects any folder not listed here.
  28. */
  29. const CLASSES = ['feature', 'bug-fix', 'simplification', 'architecture', 'process', 'testing'] as const
  30. /** Non-RFC Markdown allowed to sit directly at a lifecycle root. */
  31. const ROOT_ALLOWLIST = new Set(['AGENTS.md', 'CLAUDE.md'])
  32. /** Title-case a class/lifecycle folder name for a README heading. */
  33. const heading = (s: string): string => s.charAt(0).toUpperCase() + s.slice(1)
  34. /** One RFC file, as discovered by the walker. */
  35. export interface Rfc {
  36. lifecycle: string
  37. cls: string
  38. base: string
  39. /** Path relative to docs/rfc — the README link target. */
  40. rel: string
  41. /** H1 text with any `RFC: ` prefix stripped — the README row title. */
  42. title: string
  43. /** `yyyy-mm-dd` from the filename — the "First proposed" column. */
  44. date: string
  45. }
  46. /**
  47. * Walk the RFC tree, enforcing the structure rules. Returns every valid RFC
  48. * plus one error string per violation (unknown lifecycle or class folder, bad
  49. * depth, bad filename, missing/malformed H1). Callers treat a non-empty error
  50. * list as fatal — the index is only generated from a structurally valid tree.
  51. */
  52. export function walkRfcTree(): { rfcs: Rfc[]; errors: string[] } {
  53. const rfcs: Rfc[] = []
  54. const errors: string[] = []
  55. // The lifecycle set is closed too: any directory under docs/rfc/ that is not
  56. // a known lifecycle would otherwise hold RFCs invisible to the walk below.
  57. for (const entry of readdirSync(rfcRoot, { withFileTypes: true })) {
  58. if (entry.isDirectory() && !(LIFECYCLES as readonly string[]).includes(entry.name)) {
  59. errors.push(`structure: ${entry.name}/ — unknown lifecycle folder (allowed: ${LIFECYCLES.join(', ')})`)
  60. }
  61. }
  62. for (const lifecycle of LIFECYCLES) {
  63. for (const match of globSync(`${lifecycle}/**/*.md`, { cwd: rfcRoot }).sort()) {
  64. const segs = match.split('/')
  65. // Allowlisted file directly at the lifecycle root (e.g. implemented/AGENTS.md).
  66. if (segs.length === 2 && ROOT_ALLOWLIST.has(segs[1] ?? '')) continue
  67. // A Chinese counterpart (foo.zh.md, docs/i18n/README.md) is the SAME RFC,
  68. // indexed via its English filename; the pairing gate owns its consistency.
  69. if (match.endsWith('.zh.md')) continue
  70. const cls = segs[1]
  71. const base = segs[2]
  72. if (segs.length !== 3 || cls === undefined || base === undefined) {
  73. errors.push(`structure: ${match} — expected {lifecycle}/{class}/file.md (got depth ${segs.length})`)
  74. continue
  75. }
  76. if (!(CLASSES as readonly string[]).includes(cls)) {
  77. errors.push(`structure: ${match} — unknown class folder "${cls}" (allowed: ${CLASSES.join(', ')})`)
  78. continue
  79. }
  80. if (!/^\d{4}-\d{2}-\d{2}-.+\.md$/.test(base)) {
  81. errors.push(`structure: ${match} — filename must be yyyy-mm-dd-topic.md`)
  82. continue
  83. }
  84. const firstLine = readFileSync(resolve(rfcRoot, match), 'utf8').split('\n', 1)[0] ?? ''
  85. const h1 = /^#\s+(?:RFC:\s+)?(.+?)\s*$/.exec(firstLine)
  86. if (!h1?.[1]) {
  87. errors.push(`title: ${match} — first line must be an H1 (\`# RFC: <title>\` or \`# <title>\`), got: ${JSON.stringify(firstLine)}`)
  88. continue
  89. }
  90. rfcs.push({ lifecycle, cls, base, rel: match, title: h1[1], date: base.slice(0, 10) })
  91. }
  92. }
  93. return { rfcs, errors }
  94. }
  95. /**
  96. * Render one lifecycle's section body: a `### {Class}` heading plus a
  97. * `| Title | First proposed |` table for every non-empty class, in CLASSES
  98. * order, rows sorted by date then filename.
  99. */
  100. function renderLifecycle(rfcs: Rfc[], lifecycle: string): string {
  101. const sections: string[] = []
  102. for (const cls of CLASSES) {
  103. const rows = rfcs
  104. .filter(r => r.lifecycle === lifecycle && r.cls === cls)
  105. .sort((a, b) => a.date.localeCompare(b.date) || a.base.localeCompare(b.base))
  106. if (rows.length === 0) continue
  107. const table = rows.map(r => `| [${r.title}](${r.rel}) | ${r.date} |`).join('\n')
  108. sections.push(`### ${heading(cls)}\n\n| Title | First proposed |\n|---|---|\n${table}`)
  109. }
  110. return sections.join('\n\n')
  111. }
  112. /**
  113. * Render the complete `docs/rfc/INDEX.md` content: a generated-file banner
  114. * followed by one `## {Lifecycle}` section per lifecycle in canonical order.
  115. * The whole file is generated state — there is no curated region to preserve.
  116. */
  117. export function renderIndex(rfcs: Rfc[]): string {
  118. const parts = [
  119. '# RFC index',
  120. '',
  121. 'Generated by `pnpm run gen-rfc-index` from the RFC tree — never edit by hand; `verify-rfc-classification` fails when this file is stale. The curated front door — layout, classification, when to write one, and the in-file format — is [README.md](README.md).',
  122. ]
  123. for (const lifecycle of LIFECYCLES) {
  124. parts.push('', `## ${heading(lifecycle)}`, '', renderLifecycle(rfcs, lifecycle))
  125. }
  126. return `${parts.join('\n')}\n`
  127. }
  128. /** Matches an index-shaped table row (a `| [title](lifecycle/…) |` line) — generated state that must not appear in curated prose. */
  129. export const INDEX_ROW = /^\|\s*\[[^\]]+\]\((?:proposed|implemented|rejected)\//