gen-cordis-catalog.ts 30 KB

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