verify-type-equiv.ts 13 KB

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