gen-cordis-api.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. * Reduce an exported class to its type shape: drop method/constructor bodies
  28. * and property initializers so the catalog serves member signatures, not
  29. * implementation. An abstract class (e.g. `Agent`) is a public type consumers
  30. * program against, so it belongs in the type closure alongside interfaces.
  31. */
  32. function classShape(node: ts.ClassDeclaration): ts.ClassDeclaration {
  33. const isNonPublic = (member: ts.ClassElement): boolean =>
  34. (ts.canHaveModifiers(member) ? ts.getModifiers(member) : undefined)?.some(m =>
  35. m.kind === ts.SyntaxKind.PrivateKeyword || m.kind === ts.SyntaxKind.ProtectedKeyword) ?? false
  36. const members = node.members.flatMap((member): ts.ClassElement[] => {
  37. // A model-facing type shape carries only the public surface — drop private,
  38. // protected, and #private members, and strip every kept member's body.
  39. if (isNonPublic(member) || (ts.isPropertyDeclaration(member) && ts.isPrivateIdentifier(member.name))) return []
  40. if (ts.isMethodDeclaration(member)) {
  41. return [ts.factory.updateMethodDeclaration(
  42. member, member.modifiers, member.asteriskToken, member.name, member.questionToken,
  43. member.typeParameters, member.parameters, member.type, undefined)]
  44. }
  45. if (ts.isConstructorDeclaration(member)) {
  46. return [ts.factory.updateConstructorDeclaration(member, member.modifiers, member.parameters, undefined)]
  47. }
  48. if (ts.isGetAccessorDeclaration(member)) {
  49. return [ts.factory.updateGetAccessorDeclaration(
  50. member, member.modifiers, member.name, member.parameters, member.type, undefined)]
  51. }
  52. if (ts.isSetAccessorDeclaration(member)) {
  53. return [ts.factory.updateSetAccessorDeclaration(
  54. member, member.modifiers, member.name, member.parameters, undefined)]
  55. }
  56. if (ts.isPropertyDeclaration(member)) {
  57. return [ts.factory.updatePropertyDeclaration(
  58. member, member.modifiers, member.name, member.questionToken ?? member.exclamationToken, member.type, undefined)]
  59. }
  60. return [member]
  61. })
  62. return ts.factory.updateClassDeclaration(
  63. node, node.modifiers, node.name, node.typeParameters, node.heritageClauses, members)
  64. }
  65. /**
  66. * Collect exported interface, type-alias, and (body-stripped) class shapes;
  67. * omit names declared in multiple packages rather than risk serving the wrong
  68. * package's shape.
  69. */
  70. function collectTypeDecls(scanRoot: string = root): Map<string, string> {
  71. const printer = ts.createPrinter({ removeComments: true })
  72. const decls = new Map<string, string>()
  73. const ambiguous = new Set<string>()
  74. for (const rel of globSync('packages/*/*/src/*.ts', { cwd: scanRoot }).sort()) {
  75. const abs = resolve(scanRoot, rel)
  76. const sf = ts.createSourceFile(abs, readFileSync(abs, 'utf8'), ts.ScriptTarget.Latest, true)
  77. for (const stmt of sf.statements) {
  78. const named = ts.isInterfaceDeclaration(stmt) || ts.isTypeAliasDeclaration(stmt) || ts.isClassDeclaration(stmt)
  79. if (!named || stmt.name === undefined) continue
  80. if (!(stmt.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false)) continue
  81. const name = stmt.name.text
  82. if (decls.has(name)) {
  83. ambiguous.add(name)
  84. continue
  85. }
  86. const emit = ts.isClassDeclaration(stmt) ? classShape(stmt) : stmt
  87. const printed = printer.printNode(ts.EmitHint.Unspecified, emit, sf).replace(/\r/g, '')
  88. decls.set(name, printed.length > MAX_DECL_CHARS
  89. ? `${printed.slice(0, MAX_DECL_CHARS)} /* …truncated — full shape in source */`
  90. : printed)
  91. }
  92. }
  93. for (const name of ambiguous) decls.delete(name)
  94. return decls
  95. }
  96. /** Resolve and sort the word-bounded transitive type closure referenced by seed text. */
  97. function referencedTypes(seeds: string[], decls: Map<string, string>): { name: string; declaration: string }[] {
  98. const included = new Map<string, string>()
  99. let frontier = seeds
  100. while (frontier.length > 0) {
  101. const next: string[] = []
  102. for (const [name, declaration] of decls) {
  103. if (included.has(name)) continue
  104. const pattern = new RegExp(`\\b${name}\\b`)
  105. if (frontier.some(text => pattern.test(text))) {
  106. included.set(name, declaration)
  107. next.push(declaration)
  108. }
  109. }
  110. frontier = next
  111. }
  112. return [...included].map(([name, declaration]) => ({ name, declaration })).sort((a, b) => a.name.localeCompare(b.name))
  113. }
  114. /** Render the whole generated module (pure, deterministic given sorted collector output). */
  115. function render(): string {
  116. const services = collectServices()
  117. const events = collectEvents().sort((a, b) => a.name.localeCompare(b.name))
  118. const types = referencedTypes(services.flatMap(service => service.methods.map(method => method.signature)), collectTypeDecls())
  119. const lines: string[] = [
  120. '/**',
  121. ' * Generated by scripts/gen-cordis-api.ts — do not edit by hand; run',
  122. ' * `pnpm run gen-cordis-api` to regenerate (freshness-gated by',
  123. ' * `pnpm run verify-cordis-api` in doc-sync).',
  124. ' *',
  125. ' * The machine-readable cordis API catalog `cordis_inspect` serves to the',
  126. ' * model: harness services (summary + public method signatures/JSDoc),',
  127. ' * harness events (mode + signature/JSDoc), and the inherited `ctx` surface. Produced by',
  128. ' * the same AST walk as docs/cordis-catalog, so this data and the rendered',
  129. ' * docs cannot diverge.',
  130. ' *',
  131. ' * @module @deepseek-ai/dsh-tool-cordis/api-catalog',
  132. ' */',
  133. '',
  134. '/** One public service method and its source-owned contract. */',
  135. 'export interface ServiceApiMethod {',
  136. ' /** Public method signature with its body stripped. */',
  137. ' signature: string',
  138. ' /** Original method JSDoc, with only container indentation removed. */',
  139. ' jsDoc: string',
  140. '}',
  141. '',
  142. '/** One harness `ctx.<key>` service: its one-line summary and public methods. */',
  143. 'export interface ServiceApiEntry {',
  144. ' /** The `ctx.<key>` name, e.g. `tools`. */',
  145. ' key: string',
  146. ' /** First sentence of the service class JSDoc. */',
  147. ' summary: string',
  148. ' /** Public methods, bodies stripped, in source order. */',
  149. ' methods: readonly ServiceApiMethod[]',
  150. '}',
  151. '',
  152. '/** One harness event: its dispatch mode, exact signature, and one-line summary. */',
  153. 'export interface EventApiEntry {',
  154. ' /** The scoped event name, e.g. `agent/status`. */',
  155. ' name: string',
  156. ' /** The dispatch mode from the declaration\'s `@mode` tag. */',
  157. ' mode: string',
  158. ' /** The exact listener signature, whitespace-normalized. */',
  159. ' signature: string',
  160. ' /** Original event JSDoc, with only container indentation removed. */',
  161. ' jsDoc: string',
  162. ' /** First sentence of the event JSDoc. */',
  163. ' summary: string',
  164. '}',
  165. '',
  166. '/** One inherited (cordis core + loader/hmr/timer) `ctx` member group with its summary. */',
  167. 'export interface InheritedApiEntry {',
  168. ' /** The `ctx` member name(s), e.g. `ctx.on / ctx.once`. */',
  169. ' name: string',
  170. ' /** One-line summary of what the member does. */',
  171. ' summary: string',
  172. '}',
  173. '',
  174. '/** One named type shape the service signatures reference. */',
  175. 'export interface TypeApiEntry {',
  176. ' /** The exported type/interface name, e.g. `BashRunResult`. */',
  177. ' name: string',
  178. ' /** The full declaration text, comments stripped. */',
  179. ' declaration: string',
  180. '}',
  181. '',
  182. '/** Every harness `ctx.<key>` service, sorted by key. */',
  183. 'export const SERVICE_API: readonly ServiceApiEntry[] = [',
  184. ]
  185. for (const service of services) {
  186. lines.push(' {')
  187. lines.push(` key: ${quote(service.key)},`)
  188. lines.push(` summary: ${quote(firstSentence(service.doc))},`)
  189. if (service.methods.length === 0) {
  190. lines.push(' methods: [],')
  191. } else {
  192. lines.push(' methods: [')
  193. for (const method of service.methods) {
  194. lines.push(' {')
  195. lines.push(` signature: ${quote(method.signature)},`)
  196. lines.push(` jsDoc: ${quote(method.jsDoc)},`)
  197. lines.push(' },')
  198. }
  199. lines.push(' ],')
  200. }
  201. lines.push(' },')
  202. }
  203. lines.push(
  204. ']',
  205. '',
  206. '/** Every harness event, sorted by name. */',
  207. 'export const EVENT_API: readonly EventApiEntry[] = [',
  208. )
  209. for (const event of events) {
  210. lines.push(' {')
  211. lines.push(` name: ${quote(event.name)},`)
  212. lines.push(` mode: ${quote(event.mode)},`)
  213. lines.push(` signature: ${quote(event.signature)},`)
  214. lines.push(` jsDoc: ${quote(event.jsDoc)},`)
  215. lines.push(` summary: ${quote(firstSentence(event.doc))},`)
  216. lines.push(' },')
  217. }
  218. lines.push(
  219. ']',
  220. '',
  221. '/** Shapes of every exported type the SERVICE_API signatures reference (transitively), sorted by name. */',
  222. 'export const TYPE_API: readonly TypeApiEntry[] = [',
  223. )
  224. for (const type of types) {
  225. lines.push(' {')
  226. lines.push(` name: ${quote(type.name)},`)
  227. lines.push(` declaration: ${quote(type.declaration)},`)
  228. lines.push(' },')
  229. }
  230. lines.push(
  231. ']',
  232. '',
  233. '/** The inherited `ctx` surface (cordis core + loader/hmr/timer), in curated order. */',
  234. 'export const INHERITED_CTX_API: readonly InheritedApiEntry[] = [',
  235. )
  236. for (const inherited of INHERITED_SERVICES) {
  237. lines.push(` { name: ${quote(inherited.name)}, summary: ${quote(inherited.summary)} },`)
  238. }
  239. lines.push(']', '')
  240. return lines.join('\n')
  241. }
  242. /** CLI entry: default writes the artifact, `--check` fails if the committed
  243. * copy is stale. Guarded behind an entry-point check so importing this module
  244. * for tests neither regenerates the committed file nor calls process.exit. */
  245. function main(): void {
  246. const content = render()
  247. if (process.argv.includes('--check')) {
  248. let committed: string | null = null
  249. try {
  250. committed = readFileSync(resolve(root, OUT), 'utf8')
  251. } catch {
  252. // Only ENOENT (not yet generated) is expected; a present-but-unreadable
  253. // file is not a state this repo produces. Either way the remedy is the
  254. // same — regenerate — so treat a read failure as "stale".
  255. committed = null
  256. }
  257. if (committed === content) {
  258. console.log(`gen-cordis-api: ${OUT} is up to date.`)
  259. process.exit(0)
  260. }
  261. console.error(`gen-cordis-api: ${OUT} is stale. Run \`pnpm run gen-cordis-api\` and commit ${OUT}.`)
  262. process.exit(1)
  263. }
  264. writeFileSync(resolve(root, OUT), content)
  265. console.log(`gen-cordis-api: wrote ${OUT}.`)
  266. }
  267. // Run only when invoked as a script, not when imported by a test.
  268. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  269. main()
  270. }