gen-cordis-api.ts 10 KB

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