gen-cordis-api.ts 8.7 KB

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