rfc-index.ts 5.9 KB

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