rfc-index.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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 README's per-lifecycle tables are GENERATED between marker comments
  13. * (`<!-- gen-rfc-index:begin {lifecycle} -->` … `end`): section headings and
  14. * rows are derived from each RFC's path (lifecycle/class), H1 (title, with an
  15. * optional `RFC: ` prefix stripped), and filename date, sorted by date then
  16. * filename. Prose outside the markers is curated by hand and never touched.
  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. /** The begin/end marker lines that delimit one lifecycle's generated region. */
  96. const markers = (lifecycle: string): { begin: string; end: string } => ({
  97. begin: `<!-- gen-rfc-index:begin ${lifecycle} -->`,
  98. end: `<!-- gen-rfc-index:end ${lifecycle} -->`,
  99. })
  100. /**
  101. * Render one lifecycle's generated region body: a `### {Class}` heading plus a
  102. * `| Title | First proposed |` table for every non-empty class, in CLASSES
  103. * order, rows sorted by date then filename.
  104. */
  105. function renderLifecycle(rfcs: Rfc[], lifecycle: string): string {
  106. const sections: string[] = []
  107. for (const cls of CLASSES) {
  108. const rows = rfcs
  109. .filter(r => r.lifecycle === lifecycle && r.cls === cls)
  110. .sort((a, b) => a.date.localeCompare(b.date) || a.base.localeCompare(b.base))
  111. if (rows.length === 0) continue
  112. const table = rows.map(r => `| [${r.title}](${r.rel}) | ${r.date} |`).join('\n')
  113. sections.push(`### ${heading(cls)}\n\n| Title | First proposed |\n|---|---|\n${table}`)
  114. }
  115. return sections.join('\n\n')
  116. }
  117. /**
  118. * Splice freshly rendered regions into the README text. Throws when a marker
  119. * pair is missing, duplicated, or out of order, when a region does not sit
  120. * under its own `## {Lifecycle}` heading, or when an index-shaped table row
  121. * (a `| [title](lifecycle/…)` line) appears OUTSIDE the generated regions —
  122. * the markers are part of the curated prose, the heading above each region is
  123. * the one its lifecycle names, and index rows live only inside the regions
  124. * (prose links to RFCs remain fine anywhere).
  125. */
  126. export function spliceReadme(readme: string, rfcs: Rfc[]): string {
  127. let out = readme
  128. const regions: Array<{ from: number; to: number }> = []
  129. for (const lifecycle of LIFECYCLES) {
  130. const { begin, end } = markers(lifecycle)
  131. const beginAt = out.indexOf(begin)
  132. const endAt = out.indexOf(end)
  133. if (beginAt === -1 || endAt === -1 || endAt < beginAt) {
  134. throw new Error(`README.md is missing the ${JSON.stringify(begin)} … ${JSON.stringify(end)} marker pair`)
  135. }
  136. if (out.indexOf(begin, beginAt + 1) !== -1 || out.indexOf(end, endAt + 1) !== -1) {
  137. throw new Error(`README.md has a duplicated ${lifecycle} index marker`)
  138. }
  139. // The region must sit directly under its own lifecycle heading: the last
  140. // H2 above the begin marker is `## {Heading(lifecycle)}`, or the heading
  141. // itself has drifted while the generated table stayed put.
  142. const before = out.slice(0, beginAt)
  143. const lastH2 = [...before.matchAll(/^##\s+(.+?)\s*$/gm)].at(-1)?.[1]
  144. if (lastH2 !== heading(lifecycle)) {
  145. throw new Error(`README.md: the ${lifecycle} index region is not under a "## ${heading(lifecycle)}" heading (found "## ${lastH2 ?? '<none>'}")`)
  146. }
  147. out = `${out.slice(0, beginAt + begin.length)}\n${renderLifecycle(rfcs, lifecycle)}\n${out.slice(endAt)}`
  148. regions.push({ from: out.indexOf(begin), to: out.indexOf(markers(lifecycle).end) + markers(lifecycle).end.length })
  149. }
  150. // Index rows are generated state: a table row linking into a lifecycle
  151. // folder anywhere OUTSIDE the regions is a hand-added index entry the
  152. // generator would never reconcile.
  153. let offset = 0
  154. for (const line of out.split('\n')) {
  155. const inRegion = regions.some(r => offset >= r.from && offset < r.to)
  156. if (!inRegion && /^\|\s*\[[^\]]+\]\((?:proposed|implemented|rejected)\//.test(line)) {
  157. throw new Error(`README.md: index-shaped row outside the generated regions: ${JSON.stringify(line.slice(0, 80))}`)
  158. }
  159. offset += line.length + 1
  160. }
  161. return out
  162. }