gen-cordis-api.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. /**
  2. * Generate the model-facing Cordis API data module from the same event/service
  3. * collector as the documentation catalogs. It emits original declaration
  4. * JSDoc, first-sentence summaries, raw signatures, transitive public type
  5. * shapes, and inherited context entries, without source pointers; output is
  6. * deterministic and `--check` verifies it.
  7. */
  8. import { globSync, readFileSync, writeFileSync } from 'node:fs'
  9. import { resolve } from 'node:path'
  10. import ts from 'typescript'
  11. import { collectEvents, collectServices, INHERITED_SERVICES } from './gen-cordis-catalog.ts'
  12. const root = resolve(import.meta.dirname, '..')
  13. const OUT = 'packages/cordis/tool-cordis/src/api-catalog.ts'
  14. /** Declarations longer than this render as a truncated stub — a shape the model cannot skim teaches nothing. */
  15. const MAX_DECL_CHARS = 1500
  16. /** The first sentence of a (possibly multi-line) JSDoc prose block. */
  17. function firstSentence(doc: string): string {
  18. const line = doc.split('\n', 1)[0] ?? ''
  19. const match = /^(.*?[.!?])(?:\s|$)/.exec(line)
  20. return (match?.[1] ?? line).trim()
  21. }
  22. /** Render a string as a single-quoted, lint-clean TS literal. */
  23. function quote(value: string): string {
  24. return `'${value.replace(/\\/g, '\\\\').replace(/'/g, '\\\'').replace(/\n/g, '\\n')}'`
  25. }
  26. /**
  27. * Collect exported interface and type shapes; omit names declared in multiple
  28. * packages rather than risk serving the wrong package's shape.
  29. */
  30. function collectTypeDecls(scanRoot: string = root): Map<string, string> {
  31. const printer = ts.createPrinter({ removeComments: true })
  32. const decls = new Map<string, string>()
  33. const ambiguous = new Set<string>()
  34. for (const rel of globSync('packages/*/*/src/*.ts', { cwd: scanRoot }).sort()) {
  35. const abs = resolve(scanRoot, rel)
  36. const sf = ts.createSourceFile(abs, readFileSync(abs, 'utf8'), ts.ScriptTarget.Latest, true)
  37. for (const stmt of sf.statements) {
  38. if (!ts.isInterfaceDeclaration(stmt) && !ts.isTypeAliasDeclaration(stmt)) continue
  39. if (!(stmt.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false)) continue
  40. const name = stmt.name.text
  41. if (decls.has(name)) {
  42. ambiguous.add(name)
  43. continue
  44. }
  45. const printed = printer.printNode(ts.EmitHint.Unspecified, stmt, sf).replace(/\r/g, '')
  46. decls.set(name, printed.length > MAX_DECL_CHARS
  47. ? `${printed.slice(0, MAX_DECL_CHARS)} /* …truncated — full shape in source */`
  48. : printed)
  49. }
  50. }
  51. for (const name of ambiguous) decls.delete(name)
  52. return decls
  53. }
  54. /** Resolve and sort the word-bounded transitive type closure referenced by seed text. */
  55. function referencedTypes(seeds: string[], decls: Map<string, string>): { name: string; declaration: string }[] {
  56. const included = new Map<string, string>()
  57. let frontier = seeds
  58. while (frontier.length > 0) {
  59. const next: string[] = []
  60. for (const [name, declaration] of decls) {
  61. if (included.has(name)) continue
  62. const pattern = new RegExp(`\\b${name}\\b`)
  63. if (frontier.some(text => pattern.test(text))) {
  64. included.set(name, declaration)
  65. next.push(declaration)
  66. }
  67. }
  68. frontier = next
  69. }
  70. return [...included].map(([name, declaration]) => ({ name, declaration })).sort((a, b) => a.name.localeCompare(b.name))
  71. }
  72. /** Render the whole generated module (pure, deterministic given sorted collector output). */
  73. function render(): string {
  74. const services = collectServices()
  75. const events = collectEvents().sort((a, b) => a.name.localeCompare(b.name))
  76. const types = referencedTypes(services.flatMap(service => service.methods.map(method => method.signature)), collectTypeDecls())
  77. const lines: string[] = [
  78. '/**',
  79. ' * Generated by scripts/gen-cordis-api.ts — do not edit by hand; run',
  80. ' * `pnpm run gen-cordis-api` to regenerate (freshness-gated by',
  81. ' * `pnpm run verify-cordis-api` in doc-sync).',
  82. ' *',
  83. ' * The machine-readable cordis API catalog `cordis_inspect` serves to the',
  84. ' * model: harness services (summary + public method signatures/JSDoc),',
  85. ' * harness events (mode + signature/JSDoc), and the inherited `ctx` surface. Produced by',
  86. ' * the same AST walk as docs/cordis-catalog, so this data and the rendered',
  87. ' * docs cannot diverge.',
  88. ' *',
  89. ' * @module @deepseek-ai/dsh-tool-cordis/api-catalog',
  90. ' */',
  91. '',
  92. '/** One public service method and its source-owned contract. */',
  93. 'export interface ServiceApiMethod {',
  94. ' /** Public method signature with its body stripped. */',
  95. ' signature: string',
  96. ' /** Original method JSDoc, with only container indentation removed. */',
  97. ' jsDoc: string',
  98. '}',
  99. '',
  100. '/** One harness `ctx.<key>` service: its one-line summary and public methods. */',
  101. 'export interface ServiceApiEntry {',
  102. ' /** The `ctx.<key>` name, e.g. `tools`. */',
  103. ' key: string',
  104. ' /** First sentence of the service class JSDoc. */',
  105. ' summary: string',
  106. ' /** Public methods, bodies stripped, in source order. */',
  107. ' methods: readonly ServiceApiMethod[]',
  108. '}',
  109. '',
  110. '/** One harness event: its dispatch mode, exact signature, and one-line summary. */',
  111. 'export interface EventApiEntry {',
  112. ' /** The scoped event name, e.g. `agent/status`. */',
  113. ' name: string',
  114. ' /** The dispatch mode from the declaration\'s `@mode` tag. */',
  115. ' mode: string',
  116. ' /** The exact listener signature, whitespace-normalized. */',
  117. ' signature: string',
  118. ' /** Original event JSDoc, with only container indentation removed. */',
  119. ' jsDoc: string',
  120. ' /** First sentence of the event JSDoc. */',
  121. ' summary: string',
  122. '}',
  123. '',
  124. '/** One inherited (cordis core + loader/hmr/timer) `ctx` member group with its summary. */',
  125. 'export interface InheritedApiEntry {',
  126. ' /** The `ctx` member name(s), e.g. `ctx.on / ctx.once`. */',
  127. ' name: string',
  128. ' /** One-line summary of what the member does. */',
  129. ' summary: string',
  130. '}',
  131. '',
  132. '/** One named type shape the service signatures reference. */',
  133. 'export interface TypeApiEntry {',
  134. ' /** The exported type/interface name, e.g. `BashRunResult`. */',
  135. ' name: string',
  136. ' /** The full declaration text, comments stripped. */',
  137. ' declaration: string',
  138. '}',
  139. '',
  140. '/** Every harness `ctx.<key>` service, sorted by key. */',
  141. 'export const SERVICE_API: readonly ServiceApiEntry[] = [',
  142. ]
  143. for (const service of services) {
  144. lines.push(' {')
  145. lines.push(` key: ${quote(service.key)},`)
  146. lines.push(` summary: ${quote(firstSentence(service.doc))},`)
  147. if (service.methods.length === 0) {
  148. lines.push(' methods: [],')
  149. } else {
  150. lines.push(' methods: [')
  151. for (const method of service.methods) {
  152. lines.push(' {')
  153. lines.push(` signature: ${quote(method.signature)},`)
  154. lines.push(` jsDoc: ${quote(method.jsDoc)},`)
  155. lines.push(' },')
  156. }
  157. lines.push(' ],')
  158. }
  159. lines.push(' },')
  160. }
  161. lines.push(
  162. ']',
  163. '',
  164. '/** Every harness event, sorted by name. */',
  165. 'export const EVENT_API: readonly EventApiEntry[] = [',
  166. )
  167. for (const event of events) {
  168. lines.push(' {')
  169. lines.push(` name: ${quote(event.name)},`)
  170. lines.push(` mode: ${quote(event.mode)},`)
  171. lines.push(` signature: ${quote(event.signature)},`)
  172. lines.push(` jsDoc: ${quote(event.jsDoc)},`)
  173. lines.push(` summary: ${quote(firstSentence(event.doc))},`)
  174. lines.push(' },')
  175. }
  176. lines.push(
  177. ']',
  178. '',
  179. '/** Shapes of every exported type the SERVICE_API signatures reference (transitively), sorted by name. */',
  180. 'export const TYPE_API: readonly TypeApiEntry[] = [',
  181. )
  182. for (const type of types) {
  183. lines.push(' {')
  184. lines.push(` name: ${quote(type.name)},`)
  185. lines.push(` declaration: ${quote(type.declaration)},`)
  186. lines.push(' },')
  187. }
  188. lines.push(
  189. ']',
  190. '',
  191. '/** The inherited `ctx` surface (cordis core + loader/hmr/timer), in curated order. */',
  192. 'export const INHERITED_CTX_API: readonly InheritedApiEntry[] = [',
  193. )
  194. for (const inherited of INHERITED_SERVICES) {
  195. lines.push(` { name: ${quote(inherited.name)}, summary: ${quote(inherited.summary)} },`)
  196. }
  197. lines.push(']', '')
  198. return lines.join('\n')
  199. }
  200. /** CLI entry: default writes the artifact, `--check` fails if the committed
  201. * copy is stale. Guarded behind an entry-point check so importing this module
  202. * for tests neither regenerates the committed file nor calls process.exit. */
  203. function main(): void {
  204. const content = render()
  205. if (process.argv.includes('--check')) {
  206. let committed: string | null = null
  207. try {
  208. committed = readFileSync(resolve(root, OUT), 'utf8')
  209. } catch {
  210. // Only ENOENT (not yet generated) is expected; a present-but-unreadable
  211. // file is not a state this repo produces. Either way the remedy is the
  212. // same — regenerate — so treat a read failure as "stale".
  213. committed = null
  214. }
  215. if (committed === content) {
  216. console.log(`gen-cordis-api: ${OUT} is up to date.`)
  217. process.exit(0)
  218. }
  219. console.error(`gen-cordis-api: ${OUT} is stale. Run \`pnpm run gen-cordis-api\` and commit ${OUT}.`)
  220. process.exit(1)
  221. }
  222. writeFileSync(resolve(root, OUT), content)
  223. console.log(`gen-cordis-api: wrote ${OUT}.`)
  224. }
  225. // Run only when invoked as a script, not when imported by a test.
  226. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  227. main()
  228. }