gen-cordis-catalog.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. /**
  2. * Generate the Cordis event and service catalogs from static declarations.
  3. * The walk enforces event modes, JSDoc parameter/return completeness, and
  4. * signature type-link coverage; inherited Cordis services come from the
  5. * curated table below. `--check` verifies both committed artifacts.
  6. */
  7. import { globSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
  8. import { dirname, resolve, sep } from 'node:path'
  9. import ts from 'typescript'
  10. import { renderCordisCoreApiPages } from './cordis-core-api.ts'
  11. import { checkParams, checkReturns, parseJsDoc, parseTags, pointer, rawJsDoc, reportViolations, type Mode } from './jsdoc.ts'
  12. import { cordisModuleBody, eventMembers, serviceClasses } from './cordis-walk.ts'
  13. const root = resolve(import.meta.dirname, '..')
  14. const OUT_EVENTS = 'docs/cordis-catalog/events.md'
  15. const OUT_SERVICES = 'docs/cordis-catalog/services.md'
  16. /** The fenced-block info string for generated signature blocks (skipped by
  17. * doc-typecheck, since a bare signature fragment is not standalone-compilable). */
  18. const FENCE = 'ts cordis-catalog'
  19. /**
  20. * One primary core-data-structures page per project type used by a generated
  21. * signature. This stays curated because union names intentionally do not
  22. * reuse the type-equivalence manifest's map-symbol entries and some symbols
  23. * appear on more than one page.
  24. */
  25. export const LINK_MAP: Record<string, string> = {
  26. Agent: 'core.md',
  27. AgentCancelCause: 'core.md',
  28. AgentOptions: 'core.md',
  29. AgentStatus: 'core.md',
  30. ContentBlock: 'core.md',
  31. ContinuationDecision: 'core.md',
  32. ContinuationStop: 'core.md',
  33. GenerateOptions: 'core.md',
  34. AgentMessage: 'core.md',
  35. AgentMessageId: 'core.md',
  36. HookContext: 'core.md',
  37. LlmCallConfig: 'core.md',
  38. LlmModelContext: 'core.md',
  39. LlmFailure: 'llm-streaming.md',
  40. LlmModelInfo: 'core.md',
  41. LlmProviderInfo: 'core.md',
  42. Message: 'core.md',
  43. MessageSource: 'core.md',
  44. PromptDecision: 'core.md',
  45. RequestError: 'core.md',
  46. RequestErrorDecision: 'core.md',
  47. PreparedReferencedMessage: 'session-reference.md',
  48. SessionReferenceCandidate: 'session-reference.md',
  49. SessionReferenceInput: 'session-reference.md',
  50. SessionEvent: 'core.md',
  51. SessionId: 'core.md',
  52. SessionStartSource: 'core.md',
  53. SessionLogSnapshot: 'session-query.md',
  54. SessionSurfaceSnapshot: 'session-query.md',
  55. ApprovalOutcome: 'approval.md',
  56. ApprovalPolicy: 'approval.md',
  57. ApprovalRequest: 'approval.md',
  58. ApprovalService: 'approval.md',
  59. BashExecRequest: 'bash.md',
  60. BashExecSpec: 'bash.md',
  61. BashProcess: 'bash.md',
  62. BashRunResult: 'bash.md',
  63. DshEnvironment: 'bash.md',
  64. CodeRunRequest: 'code-runtime.md',
  65. CodeRunResult: 'code-runtime.md',
  66. CompactionResult: 'compaction.md',
  67. CompactionTrigger: 'compaction.md',
  68. PruneResult: 'compaction.md',
  69. FileReadOutcome: 'filesystem.md',
  70. FsDirEntry: 'filesystem.md',
  71. FsEditOutcome: 'filesystem.md',
  72. FsEditRequest: 'filesystem.md',
  73. FsInfo: 'filesystem.md',
  74. FsPathInfo: 'filesystem.md',
  75. FsPolicyExec: 'filesystem.md',
  76. FsTarget: 'filesystem.md',
  77. FsVersion: 'filesystem.md',
  78. FsWriteIntent: 'filesystem.md',
  79. FsWriteOutcome: 'filesystem.md',
  80. CreateGoalRequest: 'goal.md',
  81. EditGoalRequest: 'goal.md',
  82. GoalBlockReason: 'goal.md',
  83. GoalChanged: 'goal.md',
  84. GoalRef: 'goal.md',
  85. GoalView: 'goal.md',
  86. CommandDefinition: 'commands.md',
  87. CommandDescriptor: 'commands.md',
  88. CommandResult: 'commands.md',
  89. CommandSurface: 'commands.md',
  90. LlmAdapter: 'llm-streaming.md',
  91. LlmService: 'llm-streaming.md',
  92. StreamChunk: 'llm-streaming.md',
  93. CreateSessionOptions: 'persistence.md',
  94. SessionHeader: 'persistence.md',
  95. SessionLocation: 'persistence.md',
  96. SessionPersistenceSnapshot: 'persistence.md',
  97. ConfinedArgv: 'sandbox.md',
  98. SandboxExecutionPolicy: 'sandbox.md',
  99. SandboxMode: 'sandbox.md',
  100. SandboxPolicy: 'sandbox.md',
  101. PtyBackend: 'pty.md',
  102. PtyReadRequest: 'pty.md',
  103. PtyReadResult: 'pty.md',
  104. PtySendOperation: 'pty.md',
  105. PtySendRequest: 'pty.md',
  106. PtySessionId: 'pty.md',
  107. PtySessionSnapshot: 'pty.md',
  108. PtySignal: 'pty.md',
  109. PtySignalResult: 'pty.md',
  110. PtySpawnRequest: 'pty.md',
  111. PtySpawnResult: 'pty.md',
  112. SandboxPolicyRequest: 'sandbox.md',
  113. ScopeKey: 'scope.md',
  114. Scoped: 'scope.md',
  115. EpochHeader: 'session.md',
  116. OutOfBandSessionEventType: 'session.md',
  117. Session: 'session.md',
  118. SessionEventMap: 'session.md',
  119. TurnEndReason: 'session.md',
  120. TurnTrigger: 'session.md',
  121. SessionEventReadRequest: 'session-query.md',
  122. SessionEventRecord: 'session-query.md',
  123. SessionEventResultFilter: 'session-query.md',
  124. SessionEventSearchDocument: 'session-query.md',
  125. SessionEventSearchHit: 'session-query.md',
  126. SessionEventSearchPage: 'session-query.md',
  127. SessionEventSearchRequest: 'session-query.md',
  128. SessionEventTrace: 'session-query.md',
  129. SessionEventTraceObservation: 'session-query.md',
  130. SessionEventTraceRequest: 'session-query.md',
  131. SessionEventWindow: 'session-query.md',
  132. SessionLineageTrace: 'session-query.md',
  133. SessionRecord: 'session-query.md',
  134. SessionResultFilter: 'session-query.md',
  135. SessionSearchExecContext: 'session-query.md',
  136. SessionSearchHit: 'session-query.md',
  137. SessionSearchPage: 'session-query.md',
  138. SessionSearchRequest: 'session-query.md',
  139. SessionTitleObservation: 'session-query.md',
  140. SessionTitleObservationResult: 'session-query.md',
  141. SessionTitleProvider: 'session-title.md',
  142. SessionTitleSnapshot: 'session-title.md',
  143. SkillDefinition: 'skills.md',
  144. SkillLookupOptions: 'skills.md',
  145. SkillProvider: 'skills.md',
  146. SkillRegistration: 'skills.md',
  147. SkillSummary: 'skills.md',
  148. SaveTextSpill: 'spill.md',
  149. SpillRef: 'spill.md',
  150. SubagentProvider: 'subagent.md',
  151. SubagentRun: 'subagent.md',
  152. SubagentService: 'subagent.md',
  153. SubagentStartRequest: 'subagent.md',
  154. AssembleContext: 'system-prompt.md',
  155. PromptSection: 'system-prompt.md',
  156. SystemPrompt: 'system-prompt.md',
  157. ToolProviderResult: 'system-prompt.md',
  158. TaskDoneListener: 'tasks.md',
  159. TaskId: 'tasks.md',
  160. TaskRead: 'tasks.md',
  161. TaskSnapshot: 'tasks.md',
  162. TaskStart: 'tasks.md',
  163. TokenMeasurement: 'token-meter.md',
  164. PostToolDecision: 'tools.md',
  165. PreToolDecision: 'tools.md',
  166. ToolDefinition: 'tools.md',
  167. ToolExecution: 'tools.md',
  168. ToolDispatchExecution: 'tools.md',
  169. ToolExecutionInput: 'tools.md',
  170. ToolExecutionMode: 'tools.md',
  171. ToolExecutionResult: 'tools.md',
  172. ToolExecutionToken: 'tools.md',
  173. ToolGuard: 'tools.md',
  174. ToolRegistry: 'tools.md',
  175. ToolRestriction: 'tools.md',
  176. ToolSchema: 'tools.md',
  177. AskUserQuestionAnswer: 'user-interaction.md',
  178. AskUserQuestionRequest: 'user-interaction.md',
  179. UserInteractionProvider: 'user-interaction.md',
  180. WebFetchProvider: 'web.md',
  181. WebFetchRequest: 'web.md',
  182. WebFetchResult: 'web.md',
  183. WebSearchProvider: 'web.md',
  184. WebSearchRequest: 'web.md',
  185. WebSearchResult: 'web.md',
  186. WorkflowRun: 'workflow.md',
  187. WorkflowRunInfo: 'workflow.md',
  188. WorkflowStartRequest: 'workflow.md',
  189. }
  190. /** TypeScript lib and pinned framework types that have no repository-owned data page. */
  191. const FOUNDATION_TYPE_NAMES = new Set([
  192. 'AbortSignal',
  193. 'AsyncIterable',
  194. 'Context',
  195. 'Error',
  196. 'Pick',
  197. 'Promise',
  198. 'Readonly',
  199. ])
  200. /** Project types deliberately documented outside the core-data catalog. */
  201. const TYPE_LINK_EXEMPTIONS: Readonly<Record<string, string>> = {
  202. AgentFactory: 'agent creation seam is owned by packages/core/agent/README.md',
  203. AgentHandle: 'agent ownership handle is owned by packages/core/agent/README.md',
  204. BashEnvContributor: 'service-local extension type is owned by packages/bash/tool-bash/src/index.ts',
  205. BashEnvVariableInfo: 'service-local metadata type is owned by packages/bash/tool-bash/src/index.ts',
  206. CompactAgentContext: 'compaction service input is owned by packages/compact/compact/src/index.ts',
  207. CreateAgentOptions: 'agent creation contract is owned by packages/core/agent/README.md',
  208. Domain: 'domain interface is owned by packages/storage/storage-domain/README.md',
  209. DomainChanged: 'event-local snapshot is owned by packages/storage/storage-domain/src/events.ts',
  210. DomainFacility: 'domain form facility is owned by packages/storage/storage-domain/README.md',
  211. DomainImpl: 'domain implementation contract is owned by packages/storage/storage-domain/README.md',
  212. DomainSpec: 'domain declaration contract is owned by packages/storage/storage-domain/README.md',
  213. StorageBackend: 'backend contract is owned by packages/storage/storage/src/backend.ts',
  214. StorageForms: 'merge-extensible form map is owned by packages/storage/storage/src/index.ts',
  215. InvariantInstaller: 'service-local contribution contract is owned by packages/support/invariants/README.md',
  216. LocaleDict: 'service-local dictionary shape is owned by packages/client/i18n/src/index.ts',
  217. WebBootGraph: 'web boot graph wire shape is owned by packages/client/modules/src/client/index.ts',
  218. WebRoute: 'route registration contract is owned by packages/host/webserver/src/index.ts',
  219. ThemeTokens: 'service-local token dictionary is owned by packages/client/ui-theme/src/index.ts',
  220. Translate: 'service-local bound translator is owned by packages/client/i18n/src/index.ts',
  221. TuiOverlayRequest: 'service-local extension contract is owned by packages/ui/tui/README.md',
  222. TuiOverlaySession: 'service-local extension contract is owned by packages/ui/tui/README.md',
  223. InvariantRegistration: 'service-local lifecycle handle is owned by packages/support/invariants/README.md',
  224. PresetOption: 'deployment menu metadata is owned by packages/ui/permission/README.md',
  225. PresetSpec: 'deployment preset composition is owned by packages/ui/permission/README.md',
  226. PromptAssembly: 'assembly result is owned by packages/core/system-prompt/README.md',
  227. ResumeAgentOptions: 'agent resume contract is owned by packages/core/agent/README.md',
  228. SessionForkSource: 'service-local fork input is owned by packages/core/session/src/index.ts',
  229. SubagentRunEndInfo: 'event-local snapshot is owned by packages/subagent/subagent/src/index.ts',
  230. SubagentRunInfo: 'event-local snapshot is owned by packages/subagent/subagent/src/index.ts',
  231. WorkflowAgentEndInfo: 'event-local snapshot is owned by packages/workflow/workflow/src/index.ts',
  232. WorkflowAgentInfo: 'event-local snapshot is owned by packages/workflow/workflow/src/index.ts',
  233. WorkflowResultInfo: 'event-local snapshot is owned by packages/workflow/workflow/src/index.ts',
  234. Workspace: 'workspace entity contract is owned by packages/workspace/workspace/README.md',
  235. WorkspaceId: 'branded id is owned by packages/workspace/workspace/README.md',
  236. }
  237. /** Collect named references from parameter, generic-constraint/default, and return types. */
  238. function signatureTypeNames(member: ts.MethodSignature | ts.MethodDeclaration, sf: ts.SourceFile): string[] {
  239. const declared = new Set(member.typeParameters?.map(parameter => parameter.name.text) ?? [])
  240. const referenced = new Set<string>()
  241. const visit = (node: ts.Node): void => {
  242. if (ts.isTypeReferenceNode(node)) referenced.add(node.typeName.getText(sf))
  243. if (ts.isTypeQueryNode(node)) referenced.add(node.exprName.getText(sf))
  244. ts.forEachChild(node, visit)
  245. }
  246. for (const parameter of member.typeParameters ?? []) {
  247. if (parameter.constraint) visit(parameter.constraint)
  248. if (parameter.default) visit(parameter.default)
  249. }
  250. for (const parameter of member.parameters) {
  251. if (parameter.type) visit(parameter.type)
  252. }
  253. if (member.type) visit(member.type)
  254. return [...referenced].filter(name => !declared.has(name)).sort()
  255. }
  256. /** Append fail-closed signature type-link violations with actionable ownership choices. */
  257. function checkTypeLinks(
  258. where: string,
  259. member: ts.MethodSignature | ts.MethodDeclaration,
  260. sf: ts.SourceFile,
  261. violations: string[],
  262. ): void {
  263. for (const name of signatureTypeNames(member, sf)) {
  264. if (Object.hasOwn(LINK_MAP, name)
  265. || FOUNDATION_TYPE_NAMES.has(name)
  266. || Object.hasOwn(TYPE_LINK_EXEMPTIONS, name)) continue
  267. violations.push(
  268. `${where} references unclassified type '${name}'. Add it to LINK_MAP with its core-data-structures page, `
  269. + 'to FOUNDATION_TYPE_NAMES if TypeScript or Cordis owns it, or to TYPE_LINK_EXEMPTIONS with '
  270. + 'the non-catalog documentation owner.',
  271. )
  272. }
  273. }
  274. /** Throw one aggregated diagnostic for every unclassified signature type. */
  275. function reportTypeLinkViolations(gate: string, violations: string[]): void {
  276. if (violations.length === 0) return
  277. throw new Error(
  278. `${gate}: ${violations.length} signature type-link coverage violation(s):\n`
  279. + violations.map(violation => ` ${violation}`).join('\n'),
  280. )
  281. }
  282. /** One harness event, extracted from an `interface Events` block. */
  283. interface EventEntry {
  284. /** Scoped name, e.g. `agent/request`. */
  285. name: string
  286. /** The scope prefix, e.g. `agent` (everything before the first `/`). */
  287. scope: string
  288. /** Full signature text (the method-signature member, JSDoc stripped). */
  289. signature: string
  290. /** Original declaration JSDoc, dedented from its containing interface. */
  291. jsDoc: string
  292. /** Dispatch mode from the `@mode` tag. */
  293. mode: Mode
  294. /** Description prose (JSDoc minus the `@mode` tag), one line per paragraph. */
  295. doc: string
  296. /** Source pointer `packages/…/file.ts:line` of the declaration. */
  297. source: string
  298. }
  299. /** One public service method and the source contract attached to it. */
  300. interface ServiceMethodEntry {
  301. /** Public method signature (body stripped). */
  302. signature: string
  303. /** Original method JSDoc, dedented from its containing class. */
  304. jsDoc: string
  305. }
  306. /** One harness service, extracted from an `interface Context` block. */
  307. interface ServiceEntry {
  308. /** The `ctx.<key>` name, e.g. `llm`. */
  309. key: string
  310. /** The service class/interface name, e.g. `LlmService`. */
  311. type: string
  312. /** Whether the service class is abstract (a seam interface). */
  313. abstract: boolean
  314. /** Class-level JSDoc prose, one line per paragraph. */
  315. doc: string
  316. /** Public methods (bodies stripped), in source order. */
  317. methods: ServiceMethodEntry[]
  318. /** Source pointer of the class declaration. */
  319. source: string
  320. }
  321. /** A terse inherited-tier entry (pinned vendor surface). */
  322. interface InheritedEntry {
  323. name: string
  324. summary: string
  325. /** Source pointer `vendor/…:line`. */
  326. source: string
  327. }
  328. // cordisModuleBody / eventMembers / serviceClasses live in cordis-walk.ts.
  329. /** The signature text of a method-signature member (everything but a body). */
  330. function memberSignature(member: ts.TypeElement | ts.ClassElement, sf: ts.SourceFile): string {
  331. const full = member.getText(sf)
  332. const body = (member as { body?: ts.Node }).body
  333. const sig = body ? full.slice(0, full.length - body.getText(sf).length) : full
  334. return sig.replace(/\s*;?\s*$/, '').replace(/\s+/g, ' ').trim()
  335. }
  336. /**
  337. * Copy a node's original JSDoc while removing only the indentation imposed by
  338. * its containing interface or class.
  339. */
  340. function jsDocText(text: string, sf: ts.SourceFile, node: ts.Node): string {
  341. const raw = rawJsDoc(text, node)
  342. if (!raw) return ''
  343. const start = text.lastIndexOf(raw, node.getStart(sf))
  344. const { line } = sf.getLineAndCharacterOfPosition(start)
  345. const lineStart = sf.getPositionOfLineAndCharacter(line, 0)
  346. const indent = text.slice(lineStart, start)
  347. return raw.split('\n')
  348. .map((lineText, index) => index > 0 && lineText.startsWith(indent) ? lineText.slice(indent.length) : lineText)
  349. .join('\n')
  350. }
  351. /** Walk every harness `interface Events` block and extract its events, hard-
  352. * erroring (aggregated) on any JSDoc-completeness violation: a missing/
  353. * contradicted `@mode`, missing description prose, or an undocumented payload
  354. * parameter. `scanRoot` defaults to the repo root; tests pass a fixture dir. */
  355. export function collectEvents(scanRoot: string = root): EventEntry[] {
  356. const entries: EventEntry[] = []
  357. const violations: string[] = []
  358. const typeLinkViolations: string[] = []
  359. for (const rel of globSync('packages/*/*/src/*.ts', { cwd: scanRoot }).map(s => s.split(sep).join('/')).sort()) {
  360. const abs = resolve(scanRoot, rel)
  361. const text = readFileSync(abs, 'utf8')
  362. if (!text.includes('interface Events')) continue
  363. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  364. const body = cordisModuleBody(sf)
  365. if (!body) continue
  366. for (const { name, member } of eventMembers(body, sf)) {
  367. const signature = memberSignature(member, sf)
  368. const raw = rawJsDoc(text, member)
  369. const { doc, mode } = parseJsDoc(raw)
  370. const src = pointer(rel, sf, member)
  371. const where = `event '${name}' (${src})`
  372. checkTypeLinks(where, member, sf, typeLinkViolations)
  373. if (!mode) {
  374. violations.push(`${where} is missing an @mode tag. Add '@mode emit|waterfall|parallel|serial' to its JSDoc (see AGENTS.md).`)
  375. }
  376. // Conclusive structural check: a trailing `next: () => …` parameter is a
  377. // waterfall. (emit vs parallel vs serial is not structurally
  378. // distinguishable, so it is trusted from the tag.)
  379. const last = member.parameters.at(-1)
  380. const hasNext = !!last && last.name.getText(sf) === 'next'
  381. if (mode && hasNext && mode !== 'waterfall') {
  382. violations.push(`${where} has a trailing 'next' parameter (structurally a waterfall) but is tagged '@mode ${mode}'. Fix the tag or the signature.`)
  383. }
  384. if (mode && !hasNext && mode === 'waterfall') {
  385. violations.push(`${where} is tagged '@mode waterfall' but has no trailing 'next' parameter. A waterfall delegates via next().`)
  386. }
  387. if (!doc) violations.push(`${where} has no description prose. Say what happened / what a listener may do, above the block tags.`)
  388. // Payload parameters need a non-empty @param. The `this` receiver is not
  389. // payload, and a waterfall's trailing `next` is covered by its mode.
  390. const { params } = parseTags(raw)
  391. checkParams(where, 'event', member.parameters, params, sf,
  392. p => (ts.isIdentifier(p.name) && p.name.text === 'this') || (hasNext && p === last), violations)
  393. if (mode) entries.push({ name, scope: name.split('/')[0] ?? name, signature, jsDoc: jsDocText(text, sf, member), mode, doc, source: src })
  394. }
  395. }
  396. reportViolations('gen-cordis-catalog', violations)
  397. reportTypeLinkViolations('gen-cordis-catalog', typeLinkViolations)
  398. return entries
  399. }
  400. /** Walk every harness `interface Context` block + its service class, hard-
  401. * erroring (aggregated) on any JSDoc-completeness violation: a class or public
  402. * method without JSDoc prose, an undocumented parameter, a stale `@param`, a
  403. * missing `@returns` on a non-void method, or an inferred (unannotated) return
  404. * type the pure-AST walk cannot classify.
  405. * `scanRoot` defaults to the repo root; tests pass a fixture dir. */
  406. export function collectServices(scanRoot: string = root): ServiceEntry[] {
  407. const entries: ServiceEntry[] = []
  408. const violations: string[] = []
  409. const typeLinkViolations: string[] = []
  410. for (const rel of globSync('packages/*/*/src/index.ts', { cwd: scanRoot }).map(s => s.split(sep).join('/')).sort()) {
  411. const abs = resolve(scanRoot, rel)
  412. const text = readFileSync(abs, 'utf8')
  413. if (!text.includes('interface Context')) continue
  414. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  415. const body = cordisModuleBody(sf)
  416. if (!body) continue
  417. // Resolve each ctx key to its service class (shared walk) and emit an entry.
  418. for (const { key, type, cls, abstract, doc: clsDoc } of serviceClasses(body, sf, rel, violations)) {
  419. const methods: ServiceMethodEntry[] = []
  420. for (const member of cls.members) {
  421. if (!ts.isMethodDeclaration(member)) continue
  422. // Only instance methods callable through `ctx.<key>` are surface;
  423. // private, protected, and static methods are not.
  424. const nonPublic = member.modifiers?.some(m =>
  425. m.kind === ts.SyntaxKind.PrivateKeyword
  426. || m.kind === ts.SyntaxKind.ProtectedKeyword
  427. || m.kind === ts.SyntaxKind.StaticKeyword)
  428. || ts.isPrivateIdentifier(member.name)
  429. if (nonPublic) continue
  430. const memberName = member.name.getText(sf)
  431. if (memberName.startsWith('[')) continue // computed/symbol members
  432. const where = `service method ctx.${key}.${memberName} (${pointer(rel, sf, member)})`
  433. checkTypeLinks(where, member, sf, typeLinkViolations)
  434. const raw = rawJsDoc(text, member)
  435. methods.push({ signature: memberSignature(member, sf), jsDoc: jsDocText(text, sf, member) })
  436. if (!raw) { violations.push(`${where} has no JSDoc.`); continue }
  437. if (!parseJsDoc(raw).doc) violations.push(`${where} has no description prose above its block tags.`)
  438. const { params, returns } = parseTags(raw)
  439. // Every parameter needs a non-empty @param (`this` receiver exempt),
  440. // and a non-void ANNOTATED result needs a non-empty @returns — the
  441. // shared checkers carry the exact contract.
  442. checkParams(where, 'service', member.parameters, params, sf,
  443. p => ts.isIdentifier(p.name) && p.name.text === 'this', violations)
  444. checkReturns(where, member.type, returns, sf, violations)
  445. }
  446. entries.push({
  447. key,
  448. type,
  449. abstract,
  450. doc: clsDoc,
  451. methods,
  452. source: pointer(rel, sf, cls),
  453. })
  454. }
  455. }
  456. reportViolations('gen-cordis-catalog', violations)
  457. reportTypeLinkViolations('gen-cordis-catalog', typeLinkViolations)
  458. return entries.sort((a, b) => a.key.localeCompare(b.key))
  459. }
  460. /**
  461. * The inherited tier — cordis core + loader/hmr/timer. Curated, terse, and
  462. * hand-summarized because (a) it is pinned vendor source that changes only on a
  463. * deliberate vendor sync, (b) the cordis-core `Context` mixes true ctx members
  464. * with non-service fields (`root`, `baseUrl`, `logger`) that a blind walk would
  465. * wrongly surface as services, and (c) the internal/* events carry no JSDoc to
  466. * render. Source pointers are verified against vendor by `verify-md-links`'
  467. * sibling check is N/A; keep them current on a vendor bump.
  468. */
  469. const INHERITED_EVENTS: InheritedEntry[] = [
  470. { name: 'internal/plugin', summary: 'A plugin fiber was created.', source: 'vendor/cordis/src/events.ts:328' },
  471. { name: 'internal/status', summary: 'A fiber changed lifecycle state.', source: 'vendor/cordis/src/events.ts:330' },
  472. { name: 'internal/service', summary: 'Interception hook for a service binding (no core producer).', source: 'vendor/cordis/src/events.ts:332' },
  473. { name: 'internal/update', summary: 'Waterfall: a fiber config update is being applied.', source: 'vendor/cordis/src/events.ts:334' },
  474. { name: 'internal/get', summary: 'Waterfall: a service is being read from the store.', source: 'vendor/cordis/src/events.ts:336' },
  475. { name: 'internal/set', summary: 'Waterfall: a service is being written to the store.', source: 'vendor/cordis/src/events.ts:338' },
  476. { name: 'internal/listener', summary: 'A listener was registered.', source: 'vendor/cordis/src/events.ts:340' },
  477. { name: 'internal/dispatch', summary: 'An event is being dispatched to listeners.', source: 'vendor/cordis/src/events.ts:342' },
  478. { name: 'hmr/change', summary: 'A watched source file changed on disk.', source: 'vendor/hmr/src/index.ts:20' },
  479. { name: 'hmr/reload', summary: 'Plugins are being reloaded after a change.', source: 'vendor/hmr/src/index.ts:21' },
  480. { name: 'exit', summary: 'The process is exiting on a signal.', source: 'vendor/loader/src/index.ts:23' },
  481. { name: 'loader/config-update', summary: 'The loader config tree changed.', source: 'vendor/loader/src/index.ts:24' },
  482. { name: 'loader/entry-init', summary: 'A config entry is being initialized.', source: 'vendor/loader/src/index.ts:25' },
  483. { name: 'loader/partial-dispose', summary: 'An entry is being partially disposed on reload.', source: 'vendor/loader/src/index.ts:26' },
  484. { name: 'loader/patch-context', summary: 'A context is being patched during a reload.', source: 'vendor/loader/src/index.ts:27' },
  485. ]
  486. export const INHERITED_SERVICES: InheritedEntry[] = [
  487. { name: 'ctx.on / ctx.once', summary: 'Register an event listener (disposable).', source: 'vendor/cordis/src/events.ts:34' },
  488. { name: 'ctx.emit / ctx.parallel / ctx.serial / ctx.bail / ctx.waterfall', summary: 'Dispatch an event (sync / awaited / first-bail / veto-chain).', source: 'vendor/cordis/src/events.ts:34' },
  489. { name: 'ctx.plugin / ctx.inject', summary: 'Load a plugin / declare required services.', source: 'vendor/cordis/src/registry.ts:164' },
  490. { name: 'ctx.effect', summary: 'Register a disposable side effect tied to the fiber.', source: 'vendor/cordis/src/fiber.ts:9' },
  491. { name: 'ctx.get / ctx.set / ctx.provide / ctx.accessor / ctx.mixin', summary: 'Low-level service-store access and binding.', source: 'vendor/cordis/src/reflect.ts:7' },
  492. { name: 'ctx.extend / ctx.isolate / ctx.intercept', summary: 'Derive a child context (scoped services / isolation / interception).', source: 'vendor/cordis/src/context.ts:42' },
  493. { name: 'ctx.root / ctx.scope / ctx.fiber / ctx.registry / ctx.reflect / ctx.events / ctx.logger', summary: 'Ambient handles onto the running context graph.', source: 'vendor/cordis/src/context.ts:16' },
  494. { name: 'ctx.timer (+ interval / timeout / throttle / debounce / setTimeout / setInterval)', summary: 'Disposable timer helpers. The `timer` key is provided at runtime; the six helpers are mixed onto ctx directly (declared via Pick).', source: 'vendor/timer/src/index.ts:4' },
  495. { name: 'ctx.loader', summary: 'The config Loader that booted the app (present under the loader).', source: 'vendor/loader/src/index.ts:30' },
  496. { name: 'ctx.hmr', summary: 'The hot-module-reload watcher (present under the hmr plugin).', source: 'vendor/hmr/src/index.ts:15' },
  497. ]
  498. /** Render the cross-link "Types:" line for a signature, or '' if none apply. */
  499. function typeLinks(signature: string): string {
  500. const seen = new Set<string>()
  501. for (const name of Object.keys(LINK_MAP)) {
  502. if (new RegExp(`\\b${name}\\b`).test(signature)) seen.add(name)
  503. }
  504. if (seen.size === 0) return ''
  505. const links = [...seen].sort().map(n => `[${n}](../core-data-structures/${LINK_MAP[n]})`)
  506. return `Types: ${links.join(' · ')}`
  507. }
  508. /** Render one harness event entry. */
  509. function renderEvent(e: EventEntry): string[] {
  510. const out = [`### \`${e.name}\` — ${e.mode}`, '']
  511. if (e.doc) out.push(e.doc, '')
  512. out.push('```' + FENCE, e.jsDoc, e.signature, '```', '')
  513. const links = typeLinks(e.signature)
  514. if (links) out.push(links, '')
  515. out.push(`Source: [\`${e.source}\`](../../${e.source.split(':')[0]})`, '')
  516. return out
  517. }
  518. /** Render one harness service entry. */
  519. function renderService(s: ServiceEntry): string[] {
  520. const kind = s.abstract ? ' (abstract seam)' : ''
  521. const out = [`## \`ctx.${s.key}\` — \`${s.type}\`${kind}`, '']
  522. if (s.doc) out.push(s.doc, '')
  523. if (s.methods.length) {
  524. const declarations = s.methods.flatMap((method, index) => [
  525. ...(index > 0 ? [''] : []),
  526. method.jsDoc,
  527. method.signature,
  528. ])
  529. out.push('```' + FENCE, ...declarations, '```', '')
  530. const links = typeLinks(s.methods.map(method => method.signature).join('\n'))
  531. if (links) out.push(links, '')
  532. }
  533. out.push(`Source: [\`${s.source}\`](../../${s.source.split(':')[0]})`, '')
  534. return out
  535. }
  536. /** The shared generated-file banner comment. */
  537. const BANNER = [
  538. '<!-- Generated by scripts/gen-cordis-catalog.ts — do not edit by hand.',
  539. ' Run `pnpm run gen-cordis-catalog` to regenerate. -->',
  540. '',
  541. ]
  542. /** The shared GENERATED + freshness-gate + fence notice paragraph. */
  543. const GATE_NOTICE = 'This file is GENERATED from source (`scripts/gen-cordis-catalog.ts`) and verified fresh by `pnpm run verify-cordis-catalog` (part of `doc-sync`) — do not edit it by hand. Signature blocks use a `ts cordis-catalog` fence and include the original source JSDoc immediately before each event or service method. doc-typecheck skips these bare declaration fragments; type names in a signature link to the page that documents them.'
  544. /** Render the events catalog (pure, deterministic given sorted inputs). */
  545. export function renderEvents(events: EventEntry[]): string {
  546. const lines: string[] = [
  547. ...BANNER,
  548. '# Cordis Events Catalog',
  549. '',
  550. 'Every cordis event a plugin can listen to: exact signature, dispatch mode, and original declaration JSDoc. This is one axis of the **wiring** reference a plugin author works against — the callable `ctx.<key>` surface is the sibling [services catalog](services.md), and [core-data-structures/](../core-data-structures/core.md) catalogs the *data structures* these signatures move around.',
  551. '',
  552. GATE_NOTICE,
  553. '',
  554. 'The **harness tier** below (the `@deepseek-ai/dsh-*` packages) is the vocabulary this repo owns, grouped by scope. The **inherited tier** at the end is the cordis-core + loader/hmr/timer event surface a plugin also sees — pinned vendor source, summarized tersely. The event-dispatch methods themselves are generated in the [Cordis core Events API](core/events.md).',
  555. '',
  556. 'Dispatch modes: **emit** (fire-and-forget), **waterfall** (each listener gets `next()` and may transform or veto — see [waterfall semantics](../cordis-primer.md#cordis-waterfall-semantics)), **parallel** (awaited fan-out; all listeners run), **serial** (awaited in registration order until one returns a bail value — anything other than `null`, `false`, or `undefined`).',
  557. '',
  558. ]
  559. const scopes = [...new Set(events.map(e => e.scope))].sort()
  560. for (const scope of scopes) {
  561. lines.push(`## \`${scope}/*\``, '')
  562. for (const e of events.filter(x => x.scope === scope).sort((a, b) => a.name.localeCompare(b.name))) {
  563. lines.push(...renderEvent(e))
  564. }
  565. }
  566. lines.push(
  567. '## Inherited events (cordis core + loader/hmr/timer)',
  568. '',
  569. 'The framework events every plugin also sees, beyond the harness vocabulary above. This is pinned vendor source ([vendoring policy](../../vendor/README.md)); it is summarized here so the page is a complete picture of the event bus, without elevating framework internals to the harness tier\'s prominence.',
  570. '',
  571. )
  572. for (const e of INHERITED_EVENTS) {
  573. lines.push(`- \`${e.name}\` — ${e.summary} ([\`${e.source}\`](../../${e.source.split(':')[0]}))`)
  574. }
  575. lines.push('')
  576. return lines.join('\n')
  577. }
  578. /** Render the services catalog (pure, deterministic given sorted inputs). */
  579. export function renderServices(services: ServiceEntry[]): string {
  580. const lines: string[] = [
  581. ...BANNER,
  582. '# Cordis Services Catalog',
  583. '',
  584. 'Every `ctx.<key>` service a plugin can call: the exact public interface with original method JSDoc, plus the class JSDoc. This is one axis of the **wiring** reference a plugin author works against — the events a plugin listens to are the sibling [events catalog](events.md), and [core-data-structures/](../core-data-structures/core.md) catalogs the *data structures* these signatures move around. An abstract seam (e.g. `ctx.bash`) is implemented by a separate package; the interface is what consumers code against.',
  585. '',
  586. GATE_NOTICE,
  587. '',
  588. 'The **harness tier** below (the `@deepseek-ai/dsh-*` packages) is the vocabulary this repo owns. The **inherited tier** at the end is the cordis-core + loader/hmr/timer `ctx` surface a plugin also sees — pinned vendor source, summarized tersely. Detailed Context, Fiber, Registry, and Service APIs are generated in the [Cordis core API](core/context.md).',
  589. '',
  590. ]
  591. for (const s of services) lines.push(...renderService(s))
  592. lines.push(
  593. '## Inherited `ctx` members (cordis core + loader/hmr/timer)',
  594. '',
  595. 'The framework `ctx` surface every plugin also sees, beyond the harness services above. This is pinned vendor source ([vendoring policy](../../vendor/README.md)); it is summarized here so the page is a complete picture of what `ctx` offers, without elevating framework internals to the harness tier\'s prominence.',
  596. '',
  597. )
  598. for (const s of INHERITED_SERVICES) {
  599. lines.push(`- \`${s.name}\` — ${s.summary} ([\`${s.source}\`](../../${s.source.split(':')[0]}))`)
  600. }
  601. lines.push('')
  602. return lines.join('\n')
  603. }
  604. /** CLI entry: `--write` (default) writes both catalogs, `--check` fails if
  605. * either is stale. Guarded behind an entry-point check so importing this module
  606. * for tests neither regenerates the committed files nor calls process.exit. */
  607. function main(): void {
  608. const outputs: [string, string][] = [
  609. [OUT_EVENTS, renderEvents(collectEvents())],
  610. [OUT_SERVICES, renderServices(collectServices())],
  611. ...renderCordisCoreApiPages(),
  612. ]
  613. if (process.argv.includes('--check')) {
  614. const stale: string[] = []
  615. for (const [out, content] of outputs) {
  616. let committed: string | null = null
  617. try {
  618. committed = readFileSync(resolve(root, out), 'utf8')
  619. } catch {
  620. // Only ENOENT (not yet generated) is expected; a present-but-unreadable
  621. // file is not a state this repo produces. Either way the remedy is the
  622. // same — regenerate — so treat a read failure as "stale".
  623. committed = null
  624. }
  625. if (committed !== content) stale.push(out)
  626. }
  627. if (stale.length === 0) {
  628. console.log(`gen-cordis-catalog: ${outputs.length} generated file(s) are up to date.`)
  629. process.exit(0)
  630. }
  631. console.error(`gen-cordis-catalog: ${stale.join(' and ')} ${stale.length === 1 ? 'is' : 'are'} stale. Run \`pnpm run gen-cordis-catalog\` and commit the result.`)
  632. process.exit(1)
  633. }
  634. for (const [out, content] of outputs) {
  635. const destination = resolve(root, out)
  636. mkdirSync(dirname(destination), { recursive: true })
  637. writeFileSync(destination, content)
  638. }
  639. console.log(`gen-cordis-catalog: wrote ${outputs.length} generated file(s).`)
  640. }
  641. // Run only when invoked as a script, not when imported by a test.
  642. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  643. main()
  644. }