verify-type-equiv.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. /**
  2. * Verify every `ts type-equiv` and `ts public-api` block against the source
  3. * symbol named by the manifest. Ordinary entries preserve the complete
  4. * declaration; `public-api` entries preserve a class's body-stripped public
  5. * declaration. Blocks and entries have a one-to-one relationship; comparison
  6. * ignores whitespace and non-JSDoc comments but preserves declaration
  7. * structure and every original JSDoc comment. Byte-identical `.zh.md` blocks
  8. * reuse the manifest-backed check of their unsuffixed sibling.
  9. */
  10. import { globSync, readFileSync, existsSync } from 'node:fs'
  11. import { resolve, sep } from 'node:path'
  12. import ts from 'typescript'
  13. import { markdownFences } from './markdown.ts'
  14. import { partitionPairedMarkdownDerivatives } from './paired-markdown-derivatives.ts'
  15. import { isArchivedAgentNotePath } from './repo-files.ts'
  16. const root = resolve(import.meta.dirname, '..')
  17. /** Scan doc-typecheck's full Markdown scope so unmanifested blocks also fail. */
  18. const MARKDOWN_GLOBS = ['README.md', '.agents/notes/**/*.md', 'docs/**/*.md', 'packages/*/*.md', 'packages/*/*/*.md']
  19. /** One manifest entry: a source-equivalence block and its source symbol. */
  20. interface ManifestEntry {
  21. /** Doc file (repo-relative) containing the source-equivalence block. */
  22. doc: string
  23. /** The declared symbol the block must match (e.g. `SessionEvent`). */
  24. symbol: string
  25. /** Source file (repo-relative) that exports the symbol. */
  26. source: string
  27. /** Complete declaration (default), or a body-stripped public class API. */
  28. projection?: 'public-api'
  29. }
  30. /** One extracted ` ```ts type-equiv ` or ` ```ts public-api ` block. */
  31. interface EquivBlock {
  32. doc: string
  33. /** 1-based line of the opening fence (for diagnostics). */
  34. line: number
  35. /** Symbol name parsed from the block's declaration. */
  36. symbol: string
  37. /** Complete declaration (default), or a body-stripped public class API. */
  38. projection?: 'public-api'
  39. /** Block body (the pasted declaration). */
  40. code: string
  41. }
  42. /** Normalize declaration structure independently of comments and whitespace. */
  43. function normalizeStructure(code: string): string {
  44. return code
  45. .replace(/\/\*[\s\S]*?\*\//g, '')
  46. .replace(/(^|[^:])\/\/.*$/gm, '$1')
  47. .replace(/\s+/g, ' ')
  48. .trim()
  49. }
  50. /**
  51. * Extract normalized JSDoc comments in source order. Type declarations in this
  52. * repository do not contain comment delimiters inside string literals.
  53. */
  54. function normalizeJSDoc(code: string): string[] {
  55. return [...code.matchAll(/\/\*\*[\s\S]*?\*\//g)]
  56. .map(match => match[0].replace(/\s+/g, ' ').trim())
  57. }
  58. /** Strip source-only export modifiers. */
  59. function stripExport(code: string): string {
  60. return code.replace(/^export\s+(default\s+)?/, '')
  61. }
  62. /** Parse the declared symbol name from a source-equivalence block body. */
  63. function blockSymbol(code: string): string | null {
  64. const sf = ts.createSourceFile('type-equiv.ts', code, ts.ScriptTarget.Latest, /* setParentNodes */ false, ts.ScriptKind.TS)
  65. for (const stmt of sf.statements) {
  66. const named =
  67. ts.isInterfaceDeclaration(stmt) || ts.isTypeAliasDeclaration(stmt)
  68. || ts.isClassDeclaration(stmt) || ts.isEnumDeclaration(stmt)
  69. if (named && stmt.name) return stmt.name.text
  70. }
  71. return null
  72. }
  73. /** Extract every source-equivalence block from one Markdown file. */
  74. function extractEquivBlocks(docRel: string): EquivBlock[] {
  75. const blocks: EquivBlock[] = []
  76. for (const fence of markdownFences(readFileSync(resolve(root, docRel), 'utf8'))) {
  77. if (fence.info === 'ts type-equiv public-api') {
  78. throw new Error(`verify-type-equiv: ${docRel}:${fence.line} — use the concise \`ts public-api\` fence`)
  79. }
  80. if (fence.info !== 'ts type-equiv' && fence.info !== 'ts public-api') continue
  81. if (!fence.closed) {
  82. throw new Error(`verify-type-equiv: ${docRel}:${fence.line} — unterminated type-equivalence fence (missing closing \`\`\`)`)
  83. }
  84. const symbol = blockSymbol(fence.code)
  85. if (symbol === null) {
  86. throw new Error(`verify-type-equiv: ${docRel}:${fence.line} — type-equiv block has no parseable interface/type/class declaration`)
  87. }
  88. blocks.push({
  89. doc: docRel,
  90. line: fence.line,
  91. symbol,
  92. code: fence.code,
  93. ...(fence.info === 'ts public-api' ? { projection: 'public-api' as const } : {}),
  94. })
  95. }
  96. return blocks
  97. }
  98. /**
  99. * The declaration text of `symbol` in `sourceRel`, with `export` stripped, or
  100. * null when the symbol is not declared there. Uses the TS parser so it spans
  101. * interfaces, type aliases (including mapped/generic ones), classes, and enums
  102. * uniformly while including declaration and member JSDoc.
  103. */
  104. function sourceDeclaration(sourceRel: string, symbol: string): string | null {
  105. const abs = resolve(root, sourceRel)
  106. const text = readFileSync(abs, 'utf8')
  107. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, /* setParentNodes */ true)
  108. for (const stmt of sf.statements) {
  109. const named =
  110. ts.isInterfaceDeclaration(stmt) || ts.isTypeAliasDeclaration(stmt)
  111. || ts.isClassDeclaration(stmt) || ts.isEnumDeclaration(stmt)
  112. if (named && stmt.name?.text === symbol) {
  113. const declarationStart = stmt.getStart(sf)
  114. const jsDoc = ts.getJSDocCommentsAndTags(stmt)
  115. .filter(ts.isJSDoc)
  116. .map(doc => text.slice(doc.pos, doc.end))
  117. .join('\n')
  118. const declaration = stripExport(text.slice(declarationStart, stmt.getEnd()))
  119. return jsDoc === '' ? declaration : `${jsDoc}\n${declaration}`
  120. }
  121. }
  122. return null
  123. }
  124. /** Leading source JSDoc attached to one declaration or member. */
  125. function sourceJSDoc(text: string, node: ts.Node): string {
  126. return ts.getJSDocCommentsAndTags(node)
  127. .filter(ts.isJSDoc)
  128. .map(doc => text.slice(doc.pos, doc.end))
  129. .join('\n')
  130. }
  131. /** Whether a class member is part of its public declaration. */
  132. function isPublicMember(member: ts.ClassElement): boolean {
  133. if (ts.isClassStaticBlockDeclaration(member)) return false
  134. const name = ts.getNameOfDeclaration(member)
  135. if (name && ts.isPrivateIdentifier(name)) return false
  136. const modifiers = ts.canHaveModifiers(member) ? ts.getModifiers(member) : undefined
  137. return !(modifiers?.some(modifier =>
  138. modifier.kind === ts.SyntaxKind.PrivateKeyword
  139. || modifier.kind === ts.SyntaxKind.ProtectedKeyword,
  140. ) ?? false)
  141. }
  142. /** Remove an implementation body while retaining the source signature. */
  143. function bodylessMember(text: string, sf: ts.SourceFile, member: ts.ClassElement): string {
  144. const start = member.getStart(sf)
  145. let end = member.end
  146. if (ts.isConstructorDeclaration(member) || ts.isMethodDeclaration(member)
  147. || ts.isGetAccessorDeclaration(member) || ts.isSetAccessorDeclaration(member)) {
  148. if (member.body) end = member.body.getStart(sf)
  149. }
  150. if (ts.isPropertyDeclaration(member) && member.initializer) end = member.initializer.getStart(sf)
  151. const signature = text.slice(start, end).trimEnd().replace(/;$/, '').replace(/=\s*$/, '').trimEnd()
  152. return `${signature};`
  153. }
  154. /**
  155. * Render a class as an ambient declaration containing only its public fields,
  156. * constructor, accessors, and methods. Implementation bodies and private or
  157. * protected members are deliberately absent; original class/member JSDoc is
  158. * retained so the projection is the source-owned public contract.
  159. */
  160. function sourcePublicApi(sourceRel: string, symbol: string): string | null {
  161. const abs = resolve(root, sourceRel)
  162. const text = readFileSync(abs, 'utf8')
  163. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, /* setParentNodes */ true)
  164. for (const stmt of sf.statements) {
  165. if (!ts.isClassDeclaration(stmt) || stmt.name?.text !== symbol) continue
  166. const classDoc = sourceJSDoc(text, stmt)
  167. const abstract = stmt.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.AbstractKeyword) ? 'abstract ' : ''
  168. const typeParameters = stmt.typeParameters?.map(parameter => parameter.getText(sf)).join(', ')
  169. const heritage = stmt.heritageClauses?.map(clause => clause.getText(sf)).join(' ')
  170. const header = `declare ${abstract}class ${symbol}${typeParameters ? `<${typeParameters}>` : ''}${heritage ? ` ${heritage}` : ''} {`
  171. const members = stmt.members
  172. .filter(isPublicMember)
  173. .map((member) => {
  174. const jsDoc = sourceJSDoc(text, member)
  175. const declaration = bodylessMember(text, sf, member)
  176. return jsDoc === '' ? declaration : `${jsDoc}\n${declaration}`
  177. })
  178. const declaration = [header, ...members.map(member => member.split('\n').map(line => ` ${line}`).join('\n')), '}'].join('\n')
  179. return classDoc === '' ? declaration : `${classDoc}\n${declaration}`
  180. }
  181. return null
  182. }
  183. const manifestRaw = readFileSync(resolve(root, 'scripts/type-equiv.manifest.json'), 'utf8')
  184. const manifest = JSON.parse(manifestRaw) as { entries: ManifestEntry[] }
  185. const entries = manifest.entries
  186. // Key a block/entry by doc + symbol + projection. A symbol may be documented in
  187. // more than one doc, and a doc may carry both complete and projected forms.
  188. const keyOf = (x: { doc: string; symbol: string; projection?: 'public-api' }): string =>
  189. `${x.doc}::${x.symbol}::${x.projection ?? 'declaration'}`
  190. // Collect every type-equiv block across ALL docs in scope — not only the docs
  191. // the manifest names — so a block in an unmanifested doc is found and reported
  192. // as an orphan rather than silently skipped.
  193. const docSet = new Set<string>()
  194. for (const pattern of MARKDOWN_GLOBS) {
  195. for (const match of globSync(pattern, { cwd: root })) {
  196. const normalized = match.split(sep).join('/')
  197. if (!isArchivedAgentNotePath(normalized)) docSet.add(normalized)
  198. }
  199. }
  200. const extractedBlocks: EquivBlock[] = [...docSet].sort().flatMap(extractEquivBlocks)
  201. const { primary: blocks, derivatives } = partitionPairedMarkdownDerivatives(
  202. extractedBlocks,
  203. block => block.doc,
  204. block => `${block.projection ?? 'declaration'}\0${block.code}`,
  205. )
  206. const errors: string[] = []
  207. // A manifest entry naming a doc that does not exist (or is outside the scanned
  208. // scope, so no block could ever match it) is an error in its own right.
  209. for (const d of [...new Set(entries.map(e => e.doc))]) {
  210. if (!existsSync(resolve(root, d))) errors.push(`manifest references ${d}, which does not exist`)
  211. else if (!docSet.has(d)) errors.push(`manifest references ${d}, which is outside the scanned markdown scope (${MARKDOWN_GLOBS.join(', ')})`)
  212. }
  213. // Duplicate-block guard: the same projected symbol twice in one doc is ambiguous.
  214. const blockByKey = new Map<string, EquivBlock>()
  215. for (const b of blocks) {
  216. const k = keyOf(b)
  217. const prior = blockByKey.get(k)
  218. if (prior) {
  219. errors.push(`duplicate type-equiv block for ${b.symbol} in ${b.doc} (lines ${prior.line} and ${b.line})`)
  220. continue
  221. }
  222. blockByKey.set(k, b)
  223. }
  224. // Duplicate-entry guard in the manifest.
  225. const entryByKey = new Map<string, ManifestEntry>()
  226. for (const e of entries) {
  227. const k = keyOf(e)
  228. if (entryByKey.has(k)) {
  229. errors.push(`duplicate manifest entry for ${e.symbol} in ${e.doc}`)
  230. continue
  231. }
  232. entryByKey.set(k, e)
  233. }
  234. // 1:1 correspondence: orphan blocks (no entry) and orphan entries (no block).
  235. for (const b of blocks) {
  236. if (!entryByKey.has(keyOf(b))) {
  237. errors.push(`type-equiv block ${b.symbol} (${b.doc}:${b.line}) has no manifest entry — add one to scripts/type-equiv.manifest.json`)
  238. }
  239. }
  240. for (const e of entries) {
  241. if (!blockByKey.has(keyOf(e))) {
  242. errors.push(`manifest entry ${e.symbol} (${e.doc}) has no matching type-equiv block — remove it or add the block`)
  243. }
  244. }
  245. // Verbatim check: each matched block must equal its source declaration.
  246. let verified = 0
  247. for (const e of entries) {
  248. const b = blockByKey.get(keyOf(e))
  249. if (!b) continue // already reported as an orphan entry
  250. const decl = e.projection === 'public-api'
  251. ? sourcePublicApi(e.source, e.symbol)
  252. : sourceDeclaration(e.source, e.symbol)
  253. if (decl === null) {
  254. errors.push(`symbol ${e.symbol} not found in ${e.source} (manifest entry for ${e.doc})`)
  255. continue
  256. }
  257. const doc = stripExport(b.code)
  258. const sourceStructure = normalizeStructure(decl)
  259. const docStructure = normalizeStructure(doc)
  260. const sourceJSDoc = normalizeJSDoc(decl)
  261. const docJSDoc = normalizeJSDoc(doc)
  262. if (sourceStructure !== docStructure || JSON.stringify(sourceJSDoc) !== JSON.stringify(docJSDoc)) {
  263. errors.push(
  264. `DRIFT: ${e.doc}:${b.line} — type-equiv block for ${e.symbol} does not match ${e.source}.\n`
  265. + ` source structure: ${sourceStructure}\n`
  266. + ` doc structure: ${docStructure}\n`
  267. + ` source JSDoc: ${JSON.stringify(sourceJSDoc)}\n`
  268. + ` doc JSDoc: ${JSON.stringify(docJSDoc)}`,
  269. )
  270. continue
  271. }
  272. verified++
  273. }
  274. if (errors.length === 0) {
  275. console.log(`verify-type-equiv: ${verified} type-equiv block(s) match source structure and JSDoc (1:1 with manifest); ${derivatives.length} paired derivative(s).`)
  276. process.exit(0)
  277. }
  278. console.error('verify-type-equiv: type-equiv verification failed:')
  279. for (const e of errors) console.error(` ${e}`)
  280. console.error(`\n(checked ${blocks.length} primary block(s) across ${new Set(blocks.map(b => b.doc)).size} doc(s), ${derivatives.length} paired derivative(s); manifest at scripts/type-equiv.manifest.json)`)
  281. process.exit(1)