gen-cordis-catalog.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. /**
  2. * Generate (and verify) the cordis events and services catalogs in
  3. * docs/cordis-catalog/events.md and docs/cordis-catalog/services.md.
  4. *
  5. * The two pages are the WIRING-axis reference, one axis each: every cordis
  6. * event a plugin can listen to (exact signature + dispatch mode) and every
  7. * `ctx.<key>` service it can call (exact public interface). They complement the
  8. * core-data-structures catalog (the VOCABULARY axis — the types these
  9. * signatures move around).
  10. *
  11. * The catalogs are FULLY GENERATED from source — never hand-edit them. The
  12. * codebase is disciplined enough that a pure-AST pass captures the whole
  13. * truthful surface: every event/service is a string literal that round-trips
  14. * to a static `interface Events` / `interface Context` declaration (no
  15. * dynamically-named events, no runtime-only services). So the committed files
  16. * are build artifacts and a regenerate-and-diff freshness check (`--check`)
  17. * makes drift structurally impossible. Because generation enumerates source
  18. * rather than checking a hand-written subset, a brand-new event cannot be
  19. * silently undocumented — it appears in the next regenerate, and an
  20. * un-regenerated file fails `--check`.
  21. *
  22. * `tsx scripts/gen-cordis-catalog.ts` → write both catalogs
  23. * `tsx scripts/gen-cordis-catalog.ts --check` → exit 1 if a committed
  24. * catalog is stale (CI /
  25. * pre-push gate)
  26. *
  27. * The HARNESS tier (the `@deepseek-ai/dsh-*` events + services) is rendered in
  28. * full from source: signature, the `@mode` badge, and the declaration's JSDoc.
  29. * Every harness event MUST carry an `@mode emit|waterfall|parallel|serial` tag
  30. * — the generator hard-errors on a missing tag, and where the signature shape is
  31. * conclusive (a trailing `next: () => …` parameter is structurally a waterfall)
  32. * it asserts the tag agrees and hard-errors on a contradiction. Beyond the tag,
  33. * the walk enforces JSDoc COMPLETENESS on the whole harness surface (the
  34. * jsdoc-completeness-gate RFC): every event and public service method carries
  35. * description prose; every payload parameter has a non-empty `@param` (`this`
  36. * receivers and the trailing waterfall `next` are exempt — next's semantics are
  37. * documented once by the mode); a service method with a non-`void`/
  38. * `Promise<void>` return carries a non-empty `@returns` and needs an EXPLICIT
  39. * return type annotation (a pure-AST walk cannot classify an inferred return);
  40. * a stale `@param` naming no real parameter errors. Violations aggregate into
  41. * ONE error listing every offender. The tags are enforcement-only: parseJsDoc
  42. * stops prose at the first block tag, so they never change the rendered
  43. * catalog. The parsing + check helpers live in `scripts/jsdoc.ts`, shared with
  44. * the whole-export-surface gate (`scripts/verify-export-jsdoc.ts`) so
  45. * "documented" means the same thing on both surfaces. The INHERITED
  46. * tier (cordis core + loader/hmr/timer) is pinned vendor source a plugin author
  47. * also sees; it is rendered tersely (name + one-line + source pointer) from a
  48. * curated table in this script, NOT elevated to the harness tier's prominence.
  49. *
  50. * Signature fences use the ` ```ts cordis-catalog ` info string: doc-typecheck
  51. * recognizes it and skips compilation (the signatures are fragments, not
  52. * standalone-compilable, like the ` ```ts type-equiv ` blocks).
  53. */
  54. import { globSync, readFileSync, writeFileSync } from 'node:fs'
  55. import { resolve } from 'node:path'
  56. import ts from 'typescript'
  57. import { checkParams, checkReturns, parseJsDoc, parseTags, pointer, rawJsDoc, reportViolations, type Mode } from './jsdoc.ts'
  58. const root = resolve(import.meta.dirname, '..')
  59. const OUT_EVENTS = 'docs/cordis-catalog/events.md'
  60. const OUT_SERVICES = 'docs/cordis-catalog/services.md'
  61. /** The fenced-block info string for generated signature blocks (skipped by
  62. * doc-typecheck, since a bare signature fragment is not standalone-compilable). */
  63. const FENCE = 'ts cordis-catalog'
  64. /**
  65. * Cross-link map: a type name that appears in a signature → the
  66. * core-data-structures page that documents it (path relative to the catalogs'
  67. * folder).
  68. * Hand-curated and catalog-owned, NOT derived from type-equiv.manifest.json —
  69. * that manifest documents the `…Map` symbols (`ContentBlockMap`) while
  70. * signatures reference the derived UNION names (`ContentBlock`), and it lists a
  71. * few symbols on two pages. Here each name resolves to exactly one PRIMARY page.
  72. * Shared with `gen-config-catalog.ts` (each caller prefixes its own relative
  73. * path to `core-data-structures/`), so both catalogs cross-link identically.
  74. * TODO(catalog-type-links): add a verifier or generator for link-map coverage
  75. * so new hook-era decision types like `PromptDecision` / `PreToolDecision` do
  76. * not silently appear in signatures without a "Types:" link.
  77. */
  78. export const LINK_MAP: Record<string, string> = {
  79. Agent: 'core.md',
  80. ContentBlock: 'core.md',
  81. Message: 'core.md',
  82. MessageSource: 'core.md',
  83. GenerateOptions: 'core.md',
  84. LlmCallConfig: 'core.md',
  85. SessionEvent: 'core.md',
  86. StreamChunk: 'llm-streaming.md',
  87. TurnEndReason: 'session.md',
  88. ToolDefinition: 'tools.md',
  89. ToolExecution: 'tools.md',
  90. ToolExecutionInput: 'tools.md',
  91. ToolExecutionResult: 'tools.md',
  92. ToolExecutionToken: 'tools.md',
  93. ApprovalOutcome: 'approval.md',
  94. ApprovalPolicy: 'approval.md',
  95. ApprovalRequest: 'approval.md',
  96. BashExecRequest: 'bash.md',
  97. BashExecSpec: 'bash.md',
  98. BashRunResult: 'bash.md',
  99. BashTask: 'bash.md',
  100. BashTaskRead: 'bash.md',
  101. ConfinedArgv: 'sandbox.md',
  102. SandboxMode: 'sandbox.md',
  103. SandboxPolicy: 'sandbox.md',
  104. CodeRunRequest: 'code-runtime.md',
  105. CodeRunResult: 'code-runtime.md',
  106. FsEditOutcome: 'filesystem.md',
  107. FsEditRequest: 'filesystem.md',
  108. FsInfo: 'filesystem.md',
  109. FsTarget: 'filesystem.md',
  110. FsVersion: 'filesystem.md',
  111. FsWriteIntent: 'filesystem.md',
  112. FsWriteOutcome: 'filesystem.md',
  113. FsPolicyExec: 'filesystem.md',
  114. FileReadOutcome: 'filesystem.md',
  115. }
  116. /** One harness event, extracted from an `interface Events` block. */
  117. interface EventEntry {
  118. /** Scoped name, e.g. `agent/request`. */
  119. name: string
  120. /** The scope prefix, e.g. `agent` (everything before the first `/`). */
  121. scope: string
  122. /** Full signature text (the method-signature member, JSDoc stripped). */
  123. signature: string
  124. /** Dispatch mode from the `@mode` tag. */
  125. mode: Mode
  126. /** Description prose (JSDoc minus the `@mode` tag), one line per paragraph. */
  127. doc: string
  128. /** Source pointer `packages/…/file.ts:line` of the declaration. */
  129. source: string
  130. }
  131. /** One harness service, extracted from an `interface Context` block. */
  132. interface ServiceEntry {
  133. /** The `ctx.<key>` name, e.g. `llm`. */
  134. key: string
  135. /** The service class/interface name, e.g. `LlmService`. */
  136. type: string
  137. /** Whether the service class is abstract (a seam interface). */
  138. abstract: boolean
  139. /** Class-level JSDoc prose, one line per paragraph. */
  140. doc: string
  141. /** Public method signatures (bodies stripped), in source order. */
  142. methods: string[]
  143. /** Source pointer of the class declaration. */
  144. source: string
  145. }
  146. /** A terse inherited-tier entry (pinned vendor surface). */
  147. interface InheritedEntry {
  148. name: string
  149. summary: string
  150. /** Source pointer `vendor/…:line`. */
  151. source: string
  152. }
  153. /** Find the `declare module 'cordis'` body in a source file, or null. */
  154. function cordisModuleBody(sf: ts.SourceFile): ts.ModuleBlock | null {
  155. for (const stmt of sf.statements) {
  156. if (ts.isModuleDeclaration(stmt) && ts.isStringLiteral(stmt.name) && stmt.name.text === 'cordis') {
  157. if (stmt.body && ts.isModuleBlock(stmt.body)) return stmt.body
  158. }
  159. }
  160. return null
  161. }
  162. /** The signature text of a method-signature member (everything but a body). */
  163. function memberSignature(member: ts.TypeElement | ts.ClassElement, sf: ts.SourceFile): string {
  164. const full = member.getText(sf)
  165. const body = (member as { body?: ts.Node }).body
  166. const sig = body ? full.slice(0, full.length - body.getText(sf).length) : full
  167. return sig.replace(/\s*;?\s*$/, '').replace(/\s+/g, ' ').trim()
  168. }
  169. /** Walk every harness `interface Events` block and extract its events, hard-
  170. * erroring (aggregated) on any JSDoc-completeness violation: a missing/
  171. * contradicted `@mode`, missing description prose, or an undocumented payload
  172. * parameter. `scanRoot` defaults to the repo root; tests pass a fixture dir. */
  173. export function collectEvents(scanRoot: string = root): EventEntry[] {
  174. const entries: EventEntry[] = []
  175. const violations: string[] = []
  176. for (const rel of globSync('packages/*/*/src/*.ts', { cwd: scanRoot }).sort()) {
  177. const abs = resolve(scanRoot, rel)
  178. const text = readFileSync(abs, 'utf8')
  179. if (!text.includes('interface Events')) continue
  180. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  181. const body = cordisModuleBody(sf)
  182. if (!body) continue
  183. for (const stmt of body.statements) {
  184. if (!ts.isInterfaceDeclaration(stmt) || stmt.name.text !== 'Events') continue
  185. for (const member of stmt.members) {
  186. if (!ts.isMethodSignature(member)) continue
  187. const name = ts.isStringLiteral(member.name) ? member.name.text : member.name.getText(sf)
  188. const signature = memberSignature(member, sf)
  189. const raw = rawJsDoc(text, member)
  190. const { doc, mode } = parseJsDoc(raw)
  191. const src = pointer(rel, sf, member)
  192. const where = `event '${name}' (${src})`
  193. if (!mode) {
  194. violations.push(`${where} is missing an @mode tag. Add '@mode emit|waterfall|parallel|serial' to its JSDoc (see AGENTS.md).`)
  195. }
  196. // Conclusive structural check: a trailing `next: () => …` parameter is a
  197. // waterfall. (emit vs parallel vs serial is not structurally
  198. // distinguishable, so it is trusted from the tag.)
  199. const last = member.parameters.at(-1)
  200. const hasNext = !!last && last.name.getText(sf) === 'next'
  201. if (mode && hasNext && mode !== 'waterfall') {
  202. violations.push(`${where} has a trailing 'next' parameter (structurally a waterfall) but is tagged '@mode ${mode}'. Fix the tag or the signature.`)
  203. }
  204. if (mode && !hasNext && mode === 'waterfall') {
  205. violations.push(`${where} is tagged '@mode waterfall' but has no trailing 'next' parameter. A waterfall delegates via next().`)
  206. }
  207. if (!doc) violations.push(`${where} has no description prose. Say what happened / what a listener may do, above the block tags.`)
  208. // Payload parameters need a non-empty @param each. Exempt the `this`
  209. // receiver annotation (not payload) and the trailing waterfall `next`
  210. // (mode machinery, documented once by @mode semantics). Documenting an
  211. // exempt parameter anyway is allowed — only absence is checked.
  212. const { params } = parseTags(raw)
  213. checkParams(where, 'event', member.parameters, params, sf,
  214. p => (ts.isIdentifier(p.name) && p.name.text === 'this') || (hasNext && p === last), violations)
  215. if (mode) entries.push({ name, scope: name.split('/')[0] ?? name, signature, mode, doc, source: src })
  216. }
  217. }
  218. }
  219. reportViolations('gen-cordis-catalog', violations)
  220. return entries
  221. }
  222. /** Walk every harness `interface Context` block + its service class, hard-
  223. * erroring (aggregated) on any JSDoc-completeness violation: a class or public
  224. * method without JSDoc prose, an undocumented parameter, a stale `@param`, a
  225. * missing `@returns` on a non-void method, or an inferred (unannotated) return
  226. * type the pure-AST walk cannot classify.
  227. * `scanRoot` defaults to the repo root; tests pass a fixture dir. */
  228. export function collectServices(scanRoot: string = root): ServiceEntry[] {
  229. const entries: ServiceEntry[] = []
  230. const violations: string[] = []
  231. for (const rel of globSync('packages/*/*/src/index.ts', { cwd: scanRoot }).sort()) {
  232. const abs = resolve(scanRoot, rel)
  233. const text = readFileSync(abs, 'utf8')
  234. if (!text.includes('interface Context')) continue
  235. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  236. const body = cordisModuleBody(sf)
  237. if (!body) continue
  238. // The ctx key → type mapping(s) declared in this file's interface Context.
  239. const keyToType = new Map<string, string>()
  240. for (const stmt of body.statements) {
  241. if (!ts.isInterfaceDeclaration(stmt) || stmt.name.text !== 'Context') continue
  242. for (const member of stmt.members) {
  243. if (!ts.isPropertySignature(member) || !member.type) continue
  244. const key = member.name.getText(sf)
  245. keyToType.set(key, member.type.getText(sf))
  246. }
  247. }
  248. if (keyToType.size === 0) continue
  249. // Find each service class declared in the same file and emit an entry.
  250. for (const [key, type] of keyToType) {
  251. const cls = sf.statements.find(
  252. (s): s is ts.ClassDeclaration => ts.isClassDeclaration(s) && s.name?.text === type,
  253. )
  254. if (!cls) continue // a Pick-mixin member (e.g. timer helpers), not a class here
  255. const abstract = cls.modifiers?.some(m => m.kind === ts.SyntaxKind.AbstractKeyword) ?? false
  256. const clsDoc = parseJsDoc(rawJsDoc(text, cls)).doc
  257. if (!clsDoc) violations.push(`service ctx.${key} (${pointer(rel, sf, cls)}): class ${type} has no JSDoc.`)
  258. const methods: string[] = []
  259. for (const member of cls.members) {
  260. if (!ts.isMethodDeclaration(member)) continue
  261. // Only the PUBLIC callable surface a `ctx.<key>` consumer sees. Drop
  262. // private/protected (a protected method like `notifyTaskDone` is a
  263. // subclass hook, not something a plugin calls through `ctx.bash`) and
  264. // static (not reachable through the instance).
  265. const nonPublic = member.modifiers?.some(m =>
  266. m.kind === ts.SyntaxKind.PrivateKeyword
  267. || m.kind === ts.SyntaxKind.ProtectedKeyword
  268. || m.kind === ts.SyntaxKind.StaticKeyword)
  269. || ts.isPrivateIdentifier(member.name)
  270. if (nonPublic) continue
  271. const memberName = member.name.getText(sf)
  272. if (memberName.startsWith('[')) continue // computed/symbol members
  273. methods.push(memberSignature(member, sf))
  274. const where = `service method ctx.${key}.${memberName} (${pointer(rel, sf, member)})`
  275. const raw = rawJsDoc(text, member)
  276. if (!raw) { violations.push(`${where} has no JSDoc.`); continue }
  277. if (!parseJsDoc(raw).doc) violations.push(`${where} has no description prose above its block tags.`)
  278. const { params, returns } = parseTags(raw)
  279. // Every parameter needs a non-empty @param (`this` receiver exempt),
  280. // and a non-void ANNOTATED result needs a non-empty @returns — the
  281. // shared checkers carry the exact contract.
  282. checkParams(where, 'service', member.parameters, params, sf,
  283. p => ts.isIdentifier(p.name) && p.name.text === 'this', violations)
  284. checkReturns(where, member.type, returns, sf, violations)
  285. }
  286. entries.push({
  287. key,
  288. type,
  289. abstract,
  290. doc: clsDoc,
  291. methods,
  292. source: pointer(rel, sf, cls),
  293. })
  294. }
  295. }
  296. reportViolations('gen-cordis-catalog', violations)
  297. return entries.sort((a, b) => a.key.localeCompare(b.key))
  298. }
  299. /**
  300. * The inherited tier — cordis core + loader/hmr/timer. Curated, terse, and
  301. * hand-summarized because (a) it is pinned vendor source that changes only on a
  302. * deliberate vendor sync, (b) the cordis-core `Context` mixes true ctx members
  303. * with non-service fields (`root`, `baseUrl`, `logger`) that a blind walk would
  304. * wrongly surface as services, and (c) the internal/* events carry no JSDoc to
  305. * render. Source pointers are verified against vendor by `verify-md-links`'
  306. * sibling check is N/A; keep them current on a vendor bump.
  307. */
  308. const INHERITED_EVENTS: InheritedEntry[] = [
  309. { name: 'internal/plugin', summary: 'A plugin fiber was created.', source: 'vendor/cordis/src/events.ts:197' },
  310. { name: 'internal/status', summary: 'A fiber changed lifecycle state.', source: 'vendor/cordis/src/events.ts:198' },
  311. { name: 'internal/service', summary: 'Interception hook for a service binding (no core producer).', source: 'vendor/cordis/src/events.ts:199' },
  312. { name: 'internal/update', summary: 'Waterfall: a fiber config update is being applied.', source: 'vendor/cordis/src/events.ts:200' },
  313. { name: 'internal/get', summary: 'Waterfall: a service is being read from the store.', source: 'vendor/cordis/src/events.ts:201' },
  314. { name: 'internal/set', summary: 'Waterfall: a service is being written to the store.', source: 'vendor/cordis/src/events.ts:202' },
  315. { name: 'internal/listener', summary: 'A listener was registered.', source: 'vendor/cordis/src/events.ts:203' },
  316. { name: 'internal/dispatch', summary: 'An event is being dispatched to listeners.', source: 'vendor/cordis/src/events.ts:204' },
  317. { name: 'hmr/change', summary: 'A watched source file changed on disk.', source: 'vendor/hmr/src/index.ts:20' },
  318. { name: 'hmr/reload', summary: 'Plugins are being reloaded after a change.', source: 'vendor/hmr/src/index.ts:21' },
  319. { name: 'exit', summary: 'The process is exiting on a signal.', source: 'vendor/loader/src/index.ts:23' },
  320. { name: 'loader/config-update', summary: 'The loader config tree changed.', source: 'vendor/loader/src/index.ts:24' },
  321. { name: 'loader/entry-init', summary: 'A config entry is being initialized.', source: 'vendor/loader/src/index.ts:25' },
  322. { name: 'loader/partial-dispose', summary: 'An entry is being partially disposed on reload.', source: 'vendor/loader/src/index.ts:26' },
  323. { name: 'loader/patch-context', summary: 'A context is being patched during a reload.', source: 'vendor/loader/src/index.ts:27' },
  324. ]
  325. export const INHERITED_SERVICES: InheritedEntry[] = [
  326. { name: 'ctx.on / ctx.once', summary: 'Register an event listener (disposable).', source: 'vendor/cordis/src/events.ts:29' },
  327. { 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:29' },
  328. { name: 'ctx.plugin / ctx.inject', summary: 'Load a plugin / declare required services.', source: 'vendor/cordis/src/registry.ts:144' },
  329. { name: 'ctx.effect', summary: 'Register a disposable side effect tied to the fiber.', source: 'vendor/cordis/src/fiber.ts:9' },
  330. { 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' },
  331. { name: 'ctx.extend / ctx.isolate / ctx.intercept', summary: 'Derive a child context (scoped services / isolation / interception).', source: 'vendor/cordis/src/context.ts:35' },
  332. { 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' },
  333. { 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' },
  334. { name: 'ctx.loader', summary: 'The config Loader that booted the app (present under the loader).', source: 'vendor/loader/src/index.ts:30' },
  335. { name: 'ctx.hmr', summary: 'The hot-module-reload watcher (present under the hmr plugin).', source: 'vendor/hmr/src/index.ts:15' },
  336. ]
  337. /** Render the cross-link "Types:" line for a signature, or '' if none apply. */
  338. function typeLinks(signature: string): string {
  339. const seen = new Set<string>()
  340. for (const name of Object.keys(LINK_MAP)) {
  341. if (new RegExp(`\\b${name}\\b`).test(signature)) seen.add(name)
  342. }
  343. if (seen.size === 0) return ''
  344. const links = [...seen].sort().map(n => `[${n}](../core-data-structures/${LINK_MAP[n]})`)
  345. return `Types: ${links.join(' · ')}`
  346. }
  347. /** Render one harness event entry. */
  348. function renderEvent(e: EventEntry): string[] {
  349. const out = [`### \`${e.name}\` — ${e.mode}`, '']
  350. if (e.doc) out.push(e.doc, '')
  351. out.push('```' + FENCE, e.signature, '```', '')
  352. const links = typeLinks(e.signature)
  353. if (links) out.push(links, '')
  354. out.push(`Source: [\`${e.source}\`](../../${e.source.split(':')[0]})`, '')
  355. return out
  356. }
  357. /** Render one harness service entry. */
  358. function renderService(s: ServiceEntry): string[] {
  359. const kind = s.abstract ? ' (abstract seam)' : ''
  360. const out = [`## \`ctx.${s.key}\` — \`${s.type}\`${kind}`, '']
  361. if (s.doc) out.push(s.doc, '')
  362. if (s.methods.length) {
  363. out.push('```' + FENCE, ...s.methods, '```', '')
  364. const links = typeLinks(s.methods.join('\n'))
  365. if (links) out.push(links, '')
  366. }
  367. out.push(`Source: [\`${s.source}\`](../../${s.source.split(':')[0]})`, '')
  368. return out
  369. }
  370. /** The shared generated-file banner comment. */
  371. const BANNER = [
  372. '<!-- Generated by scripts/gen-cordis-catalog.ts — do not edit by hand.',
  373. ' Run `pnpm run gen-cordis-catalog` to regenerate. -->',
  374. '',
  375. ]
  376. /** The shared GENERATED + freshness-gate + fence notice paragraph. */
  377. 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 (skipped by doc-typecheck, since a bare signature is not standalone-compilable). Type names in a signature link to the page that documents them.'
  378. /** Render the events catalog (pure, deterministic given sorted inputs). */
  379. function renderEvents(events: EventEntry[]): string {
  380. const lines: string[] = [
  381. ...BANNER,
  382. '# Cordis Events Catalog',
  383. '',
  384. 'Every cordis event a plugin can listen to: exact signature, dispatch mode, and the declaration\'s 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.',
  385. '',
  386. GATE_NOTICE,
  387. '',
  388. '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.',
  389. '',
  390. '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`).',
  391. '',
  392. ]
  393. const scopes = [...new Set(events.map(e => e.scope))].sort()
  394. for (const scope of scopes) {
  395. lines.push(`## \`${scope}/*\``, '')
  396. for (const e of events.filter(x => x.scope === scope).sort((a, b) => a.name.localeCompare(b.name))) {
  397. lines.push(...renderEvent(e))
  398. }
  399. }
  400. lines.push(
  401. '## Inherited events (cordis core + loader/hmr/timer)',
  402. '',
  403. '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.',
  404. '',
  405. )
  406. for (const e of INHERITED_EVENTS) {
  407. lines.push(`- \`${e.name}\` — ${e.summary} ([\`${e.source}\`](../../${e.source.split(':')[0]}))`)
  408. }
  409. lines.push('')
  410. return lines.join('\n')
  411. }
  412. /** Render the services catalog (pure, deterministic given sorted inputs). */
  413. function renderServices(services: ServiceEntry[]): string {
  414. const lines: string[] = [
  415. ...BANNER,
  416. '# Cordis Services Catalog',
  417. '',
  418. 'Every `ctx.<key>` service a plugin can call: the exact public interface 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.',
  419. '',
  420. GATE_NOTICE,
  421. '',
  422. '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.',
  423. '',
  424. ]
  425. for (const s of services) lines.push(...renderService(s))
  426. lines.push(
  427. '## Inherited `ctx` members (cordis core + loader/hmr/timer)',
  428. '',
  429. '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.',
  430. '',
  431. )
  432. for (const s of INHERITED_SERVICES) {
  433. lines.push(`- \`${s.name}\` — ${s.summary} ([\`${s.source}\`](../../${s.source.split(':')[0]}))`)
  434. }
  435. lines.push('')
  436. return lines.join('\n')
  437. }
  438. /** CLI entry: `--write` (default) writes both catalogs, `--check` fails if
  439. * either is stale. Guarded behind an entry-point check so importing this module
  440. * for tests neither regenerates the committed files nor calls process.exit. */
  441. function main(): void {
  442. const outputs: [string, string][] = [
  443. [OUT_EVENTS, renderEvents(collectEvents())],
  444. [OUT_SERVICES, renderServices(collectServices())],
  445. ]
  446. if (process.argv.includes('--check')) {
  447. const stale: string[] = []
  448. for (const [out, content] of outputs) {
  449. let committed: string | null = null
  450. try {
  451. committed = readFileSync(resolve(root, out), 'utf8')
  452. } catch {
  453. // Only ENOENT (not yet generated) is expected; a present-but-unreadable
  454. // file is not a state this repo produces. Either way the remedy is the
  455. // same — regenerate — so treat a read failure as "stale".
  456. committed = null
  457. }
  458. if (committed !== content) stale.push(out)
  459. }
  460. if (stale.length === 0) {
  461. console.log(`gen-cordis-catalog: ${OUT_EVENTS} and ${OUT_SERVICES} are up to date.`)
  462. process.exit(0)
  463. }
  464. console.error(`gen-cordis-catalog: ${stale.join(' and ')} ${stale.length === 1 ? 'is' : 'are'} stale. Run \`pnpm run gen-cordis-catalog\` and commit the result.`)
  465. process.exit(1)
  466. }
  467. for (const [out, content] of outputs) writeFileSync(resolve(root, out), content)
  468. console.log(`gen-cordis-catalog: wrote ${OUT_EVENTS} and ${OUT_SERVICES}.`)
  469. }
  470. // Run only when invoked as a script, not when imported by a test.
  471. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  472. main()
  473. }