gen-doc-graphs.ts 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  1. /**
  2. * Generate the relationship layer above the module, Cordis, and tool catalogs.
  3. * Enumerable facts come from source; hybrid graphs add manifests for policy the
  4. * source cannot infer, while curated graphs explain flow and ownership.
  5. * `--check` verifies the generated set.
  6. */
  7. import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
  8. import { dirname, relative, resolve } from 'node:path'
  9. import ts from 'typescript'
  10. import { collectEvents, collectServices } from './gen-cordis-catalog.ts'
  11. import {
  12. collectPackageGraph,
  13. escapeMermaidLabel as escLabel,
  14. graphNodeId as nodeId,
  15. type PackageGraphNode,
  16. } from './package-graph.ts'
  17. import { TypeScriptProject } from './ts-project.ts'
  18. const root = resolve(import.meta.dirname, '..')
  19. type Pkg = PackageGraphNode
  20. interface GraphDoc {
  21. rel: string
  22. content: string
  23. }
  24. interface ServiceRole {
  25. key: string
  26. pkg: string
  27. title: string
  28. mode: 'core' | 'seam' | 'bundle'
  29. implementations?: string[]
  30. consumers?: string[]
  31. companions?: string[]
  32. note: string
  33. }
  34. interface ExamplePlugin {
  35. id: string
  36. name: string
  37. }
  38. interface EventRelation {
  39. dispatchers: Map<string, Set<string>>
  40. listeners: Set<string>
  41. }
  42. interface PackageSource {
  43. rel: string
  44. pkg: string
  45. sourceFile: ts.SourceFile
  46. }
  47. type EventReceiverKind = 'context' | 'agent-dispatch' | 'events-service'
  48. const GROUP_ORDER = [
  49. 'util',
  50. 'llm',
  51. 'core',
  52. 'bash',
  53. 'sandbox',
  54. 'fs',
  55. 'skill',
  56. 'compact',
  57. 'subagent',
  58. 'tasks',
  59. 'workflow',
  60. 'web',
  61. 'spill',
  62. 'todo',
  63. 'cordis',
  64. 'hooks',
  65. 'session-persistence',
  66. 'session-query',
  67. 'support',
  68. 'ui',
  69. ]
  70. const SERVICE_ROLES: ServiceRole[] = [
  71. {
  72. key: 'llm',
  73. pkg: 'llm',
  74. title: 'LLM adapter registry',
  75. mode: 'seam',
  76. implementations: ['llm-deepseek', 'llm-pi-ai', 'llm-replay'],
  77. consumers: ['agent-loop', 'compact-basic'],
  78. note: 'Adapters register provider implementations; the loop and compaction call the provider-neutral stream service.',
  79. },
  80. {
  81. key: 'sessions',
  82. pkg: 'session',
  83. title: 'In-memory session store',
  84. mode: 'core',
  85. consumers: ['agent-loop', 'agent', 'session-persistence', 'session-query', 'subagent-inprocess', 'invariants'],
  86. note: 'Owns append-only Session instances and emits the durable session event feed.',
  87. },
  88. {
  89. key: 'sessionPersistence',
  90. pkg: 'session-persistence',
  91. title: 'Durable session persistence seam',
  92. mode: 'seam',
  93. implementations: ['session-persistence-jsonl', 'session-persistence-sqlite'],
  94. consumers: ['agent-loop', 'tool-bash', 'hooks-claude', 'hooks-codex', 'acp', 'session-query'],
  95. note: 'Backends persist the same SessionEvent vocabulary; apps choose a backend at composition time.',
  96. },
  97. {
  98. key: 'sessionQuery',
  99. pkg: 'session-query',
  100. title: 'Exact session-history reads and traces',
  101. mode: 'seam',
  102. note: 'Resolves live and optional persisted logs into one logical corpus for exact reads and relationship traces.',
  103. },
  104. {
  105. key: 'systemPrompt',
  106. pkg: 'system-prompt',
  107. title: 'System prompt assembly registry',
  108. mode: 'core',
  109. consumers: ['agent-loop', 'tools', 'tool-fs', 'tool-web'],
  110. note: 'Collects prompt sections and model-facing tool schemas for each step.',
  111. },
  112. {
  113. key: 'tools',
  114. pkg: 'tools',
  115. title: 'Tool registry and guarded execution pipeline',
  116. mode: 'core',
  117. consumers: ['agent-loop', 'tool-ask-user', 'tool-bash', 'tool-cordis', 'tool-fs', 'tool-skill', 'tool-subagent', 'tool-todo', 'tool-web', 'acp'],
  118. note: 'Registers capabilities, owns Code Mode transport, and routes calls through pre-policy, monotonic guards, around dispatch, post-policy, and final-result observation.',
  119. },
  120. {
  121. key: 'userInteraction',
  122. pkg: 'user-interaction',
  123. title: 'Human question/answer seam',
  124. mode: 'seam',
  125. implementations: ['stdio-demo', 'acp'],
  126. consumers: ['tool-ask-user', 'stdio-demo', 'acp'],
  127. note: 'UI front doors provide the active human-answer provider; tool-ask-user pauses a tool call on the provider-neutral ask() promise.',
  128. },
  129. {
  130. key: 'skills',
  131. pkg: 'skill',
  132. title: 'Skill provider registry',
  133. mode: 'seam',
  134. implementations: ['skill-local'],
  135. consumers: ['tool-skill'],
  136. note: 'Merges provider skill catalogs; tool-skill renders the session-prefix catalog and loads complete skill bodies.',
  137. },
  138. {
  139. key: 'agents',
  140. pkg: 'agent',
  141. title: 'Agent registry',
  142. mode: 'core',
  143. consumers: ['agent-loop', 'acp', 'subagent-inprocess', 'stdio-demo', 'invariants'],
  144. note: 'Owns live Agent handles and the create/resume factory seam.',
  145. },
  146. {
  147. key: 'agentLoop',
  148. pkg: 'agent-loop',
  149. title: 'Concrete loop driver',
  150. mode: 'bundle',
  151. consumers: ['agent-spine-demo'],
  152. note: 'The one concrete loop plugin; extension packages depend on dsh-agent events and services, not on this package.',
  153. },
  154. {
  155. key: 'bash',
  156. pkg: 'bash',
  157. title: 'Bash executor seam',
  158. mode: 'seam',
  159. implementations: ['bash-local', 'bash-sandbox'],
  160. consumers: ['tool-bash', 'hooks-claude', 'hooks-codex'],
  161. note: 'The model-facing bash tools and hook bridges consume this seam; sandboxed or remote executors replace bash-local without touching them.',
  162. },
  163. {
  164. key: 'bashEnv',
  165. pkg: 'tool-bash',
  166. title: 'Managed bash environment registry',
  167. mode: 'core',
  168. note: 'Plugins declare effect-scoped DSH_* facts; tool-bash collects one trusted snapshot per execution and the executor rebuilds the namespace.',
  169. },
  170. {
  171. key: 'sandbox',
  172. pkg: 'sandbox',
  173. title: 'Process-sandbox seam',
  174. mode: 'seam',
  175. implementations: ['sandbox-local'],
  176. consumers: ['bash-sandbox'],
  177. note: 'Consumers hand over the exact argv they are about to spawn; same-world backends wrap it under a per-call policy and report enforcement.',
  178. },
  179. {
  180. key: 'approval',
  181. pkg: 'approval',
  182. title: 'Approval seam',
  183. mode: 'seam',
  184. implementations: ['acp'],
  185. consumers: ['tools', 'tool-bash'],
  186. note: 'One-shot permission decisions dispatched over the `approval/request` waterfall; answerers are listeners (the ACP bridge for its own agents), absence fails closed to `unavailable`.',
  187. },
  188. {
  189. key: 'permission',
  190. pkg: 'permission',
  191. title: 'Permission presets',
  192. mode: 'core',
  193. implementations: [],
  194. consumers: ['acp'],
  195. note: 'User-facing preset table (`workspace-write`/`danger-full-access`) bundling the sandbox-mode and approval-policy knobs; a switch writes one `permission/preset` event through to both knob events.',
  196. },
  197. {
  198. key: 'codeRuntime',
  199. pkg: 'code-runtime',
  200. title: 'Code-execution seam',
  201. mode: 'seam',
  202. implementations: ['code-runtime-worker'],
  203. consumers: ['tools'],
  204. note: 'Runs one model-written program against host-provided async bindings; backends differ by substrate and language (the tool registry consumes it for Code Mode).',
  205. },
  206. {
  207. key: 'fs',
  208. pkg: 'fs',
  209. title: 'Filesystem provider seam',
  210. mode: 'seam',
  211. implementations: ['fs-local'],
  212. consumers: ['tool-fs'],
  213. companions: ['fs-policy'],
  214. note: 'tool-fs executes read/write/edit through ctx.fs; fs-policy contributes observed-state checks through the fs/* event gate.',
  215. },
  216. {
  217. key: 'compact',
  218. pkg: 'compact',
  219. title: 'Compaction seam',
  220. mode: 'seam',
  221. implementations: ['compact-basic'],
  222. consumers: ['compact-basic'],
  223. note: 'The basic backend currently consumes the pre-step event directly; a model-facing compact tool remains deferred.',
  224. },
  225. {
  226. key: 'subagents',
  227. pkg: 'subagent',
  228. title: 'Subagent provider registry',
  229. mode: 'seam',
  230. implementations: ['subagent-spawn', 'subagent-fork', 'subagent-acp', 'subagent-mock'],
  231. consumers: ['tool-subagent'],
  232. note: 'Providers implement transports; tool-subagent exposes one configured provider as a model-facing tool name.',
  233. },
  234. {
  235. key: 'tasks',
  236. pkg: 'tasks',
  237. title: 'Background task registry',
  238. mode: 'core',
  239. consumers: ['tool-bash', 'tool-subagent', 'tool-tasks'],
  240. note: 'Producers (tool-bash background commands, tool-subagent background delegations) register running work; tool-tasks is the model-facing control surface that reads, lists, and kills it.',
  241. },
  242. {
  243. key: 'web',
  244. pkg: 'web',
  245. title: 'Web access provider registry',
  246. mode: 'seam',
  247. implementations: ['web-search-exa', 'web-search-perplexity', 'web-search-deepseek', 'web-fetch-local'],
  248. consumers: ['tool-web'],
  249. note: 'Search and fetch providers register into one ctx.web seam; tool-web owns the stable model-facing names.',
  250. },
  251. {
  252. key: 'spillStore',
  253. pkg: 'spill',
  254. title: 'Spill storage seam',
  255. mode: 'seam',
  256. implementations: ['spill-local'],
  257. consumers: ['spill-policy'],
  258. note: 'The backend saves oversized tool text and returns a model-facing locator plus retrieval hint; spill-policy is the tools/post-execute consumer that decides when to spill.',
  259. },
  260. {
  261. key: 'workflows',
  262. pkg: 'workflow',
  263. title: 'Workflow script engine',
  264. mode: 'seam',
  265. implementations: ['workflow-workerthread'],
  266. consumers: ['tool-workflow'],
  267. note: 'One engine per context (bash shape, no named-provider registry); the worker-thread engine fans agent() calls out through ctx.subagents.',
  268. },
  269. ]
  270. function generatedHeader(title: string): string[] {
  271. return [
  272. '<!-- Generated by scripts/gen-doc-graphs.ts - do not edit by hand.',
  273. ' Run `pnpm run gen-doc-graphs` to regenerate. -->',
  274. '',
  275. `# ${title}`,
  276. '',
  277. ]
  278. }
  279. function maintenanceFooter(source: string): string[] {
  280. return [`Maintenance mode: ${source}.`, '']
  281. }
  282. function graphIndexLink(rel: string): string {
  283. return relative('docs', rel).replaceAll('\\', '/')
  284. }
  285. function linkFromDoc(docRel: string, targetRel: string): string {
  286. return relative(dirname(docRel), targetRel).replaceAll('\\', '/')
  287. }
  288. function mermaidCode(value: string): string {
  289. return `<code>${value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</code>`
  290. }
  291. function repoLink(path: string, label: string, up = '..'): string {
  292. return `[${label}](${up}/${path})`
  293. }
  294. function sourceLink(source: string, up = '..'): string {
  295. return repoLink(source.split(':')[0] ?? source, `\`${source}\``, up)
  296. }
  297. function pkgLink(pkg: Pkg | undefined, fallback: string, up = '..'): string {
  298. return pkg ? repoLink(pkg.rel, `\`${pkg.short}\``, up) : `\`${fallback}\``
  299. }
  300. function pkgList(names: string[] | undefined, pkgsByShort: Map<string, Pkg>): string {
  301. if (!names || names.length === 0) return '-'
  302. return names.map(name => pkgLink(pkgsByShort.get(name), name)).join(', ')
  303. }
  304. function tableCell(value: string): string {
  305. return value.replace(/\|/g, '\\|').replace(/\n/g, '<br>')
  306. }
  307. function assertServiceRolesComplete(): void {
  308. const discovered = new Set(collectServices().map(service => service.key))
  309. const classified = new Set(SERVICE_ROLES.map(role => role.key))
  310. const missing = [...discovered].filter(key => !classified.has(key)).sort()
  311. const stale = [...classified].filter(key => !discovered.has(key)).sort()
  312. if (missing.length || stale.length) {
  313. throw new Error([
  314. missing.length ? `missing service role classification: ${missing.join(', ')}` : '',
  315. stale.length ? `stale service role classification: ${stale.join(', ')}` : '',
  316. ].filter(Boolean).join('; '))
  317. }
  318. }
  319. function renderCapabilitySeams(pkgs: Pkg[]): string {
  320. assertServiceRolesComplete()
  321. const pkgsByShort = new Map(pkgs.map(pkg => [pkg.short, pkg]))
  322. const maintenance = 'hybrid: services are discovered from Cordis declarations; interface/implementation/consumer roles are classified in `scripts/gen-doc-graphs.ts` with a completeness guard'
  323. const nodes = new Map<string, string>()
  324. const edges = new Set<string>()
  325. const companionEdges = new Set<string>()
  326. const addNode = (id: string, label: string): void => {
  327. if (!nodes.has(id)) nodes.set(id, ` ${id}["${escLabel(label)}"]`)
  328. }
  329. const addEdge = (from: string, to: string): void => { edges.add(` ${from} --> ${to}`) }
  330. const lines = generatedHeader('Capability Seams And Core Services')
  331. lines.push(
  332. 'A service can be a core spine service, a swappable capability seam, or a bundle/composition point. The graph shows the package that owns the service declaration, known implementation packages, and packages that consume the service directly.',
  333. '',
  334. '```mermaid',
  335. 'flowchart LR',
  336. )
  337. for (const role of SERVICE_ROLES) {
  338. const svc = nodeId('svc', role.key)
  339. const owner = nodeId('pkg', role.pkg)
  340. addNode(owner, role.pkg)
  341. addNode(svc, `ctx.${role.key}<br/>${role.title}`)
  342. addEdge(owner, svc)
  343. for (const impl of role.implementations ?? []) {
  344. addNode(nodeId('pkg', impl), impl)
  345. addEdge(nodeId('pkg', impl), svc)
  346. }
  347. for (const consumer of role.consumers ?? []) {
  348. addNode(nodeId('pkg', consumer), consumer)
  349. addEdge(svc, nodeId('pkg', consumer))
  350. }
  351. for (const companion of role.companions ?? []) {
  352. addNode(nodeId('pkg', companion), companion)
  353. companionEdges.add(` ${svc} -. event gate .-> ${nodeId('pkg', companion)}`)
  354. }
  355. }
  356. lines.push(...nodes.values(), ...[...edges].sort(), ...[...companionEdges].sort())
  357. lines.push('```', '', '| ctx key | Role | Owner | Implementations | Direct consumers | Companion plugins | Note |', '| --- | --- | --- | --- | --- | --- | --- |')
  358. for (const role of SERVICE_ROLES) {
  359. lines.push(`| \`ctx.${role.key}\` | \`${role.mode}\` | ${pkgLink(pkgsByShort.get(role.pkg), role.pkg)} | ${pkgList(role.implementations, pkgsByShort)} | ${pkgList(role.consumers, pkgsByShort)} | ${pkgList(role.companions, pkgsByShort)} | ${tableCell(role.note)} |`)
  360. }
  361. lines.push('', ...maintenanceFooter(maintenance))
  362. return lines.join('\n')
  363. }
  364. function parseExampleCordis(rel: string): ExamplePlugin[] {
  365. const text = readFileSync(resolve(root, rel), 'utf8')
  366. const plugins: ExamplePlugin[] = []
  367. let current: { id: string; name?: string } | null = null
  368. const flush = (): void => {
  369. if (current?.name) plugins.push({ id: current.id, name: current.name })
  370. }
  371. for (const line of text.split('\n')) {
  372. const id = /^-\s+id:\s+(.+?)\s*$/.exec(line)
  373. if (id?.[1] !== undefined) {
  374. flush()
  375. current = { id: stripYamlScalar(id[1]) }
  376. continue
  377. }
  378. const name = /^\s+name:\s+(.+?)\s*$/.exec(line)
  379. if (name?.[1] !== undefined && current) current.name = stripYamlScalar(name[1])
  380. }
  381. flush()
  382. return plugins
  383. }
  384. function stripYamlScalar(value: string): string {
  385. return value.trim().replace(/^['"]|['"]$/g, '')
  386. }
  387. const APP_EXAMPLES = [
  388. {
  389. id: 'echo',
  390. rel: 'examples/echo-agent/composition.md',
  391. title: 'Echo Agent App Composition',
  392. label: 'examples/echo-agent',
  393. config: 'examples/echo-agent/cordis.yml',
  394. summary: 'The echo demo swaps in a local mock LLM and teaching echo tool, then loads the stdio app package for the shared spine and terminal front door.',
  395. },
  396. {
  397. id: 'coding',
  398. rel: 'examples/coding-agent/composition.md',
  399. title: 'Coding Agent App Composition',
  400. label: 'examples/coding-agent',
  401. config: 'examples/coding-agent/cordis.yml',
  402. summary: 'The coding REPL demo adds the real DeepSeek adapter, filesystem tools, todo_write, compaction, and both subagent transports on top of the stdio app package.',
  403. },
  404. {
  405. id: 'cordis',
  406. rel: 'examples/cordis-agent/composition.md',
  407. title: 'Cordis Agent App Composition',
  408. label: 'examples/cordis-agent',
  409. config: 'examples/cordis-agent/cordis.yml',
  410. summary: 'The self-referential demo puts @deepseek-ai/dsh-tool-cordis on the coding spine, letting the agent inspect its own runtime and mount/unmount plugins into it.',
  411. },
  412. {
  413. id: 'acp',
  414. rel: 'examples/acp-agent/composition.md',
  415. title: 'ACP Agent App Composition',
  416. label: 'examples/acp-agent',
  417. config: 'examples/acp-agent/cordis.yml',
  418. summary: 'The ACP demo exposes the same agent spine over JSON-RPC stdio, with no stdout logger and no pre-created agent; clients create sessions through the ACP bridge.',
  419. },
  420. ]
  421. type AppExample = typeof APP_EXAMPLES[number]
  422. function renderAppExpansion(lines: string[], appNode: string, pluginName: string): void {
  423. const agentCore = nodeId('bundle', 'agent_core')
  424. const jsonl = nodeId('bundle', 'jsonl')
  425. lines.push(` ${appNode} --> ${agentCore}["@deepseek-ai/dsh-agent-spine-demo"]`)
  426. lines.push(` ${appNode} --> ${jsonl}["@deepseek-ai/dsh-session-persistence-jsonl"]`)
  427. if (pluginName === '@deepseek-ai/dsh-stdio-demo') {
  428. lines.push(` ${appNode} --> ${nodeId('frontdoor', 'stdio')}["readline UI<br/>console logger<br/>pre-created main agent"]`)
  429. } else if (pluginName === '@deepseek-ai/dsh-acp-demo') {
  430. lines.push(` ${appNode} --> ${nodeId('frontdoor', 'acp')}["@deepseek-ai/dsh-acp<br/>JSON-RPC stdio bridge<br/>sessions created by client"]`)
  431. }
  432. lines.push(
  433. ` ${agentCore} --> ${nodeId('spine', 'llm')}["ctx.llm"]`,
  434. ` ${agentCore} --> ${nodeId('spine', 'sessions')}["ctx.sessions"]`,
  435. ` ${agentCore} --> ${nodeId('spine', 'tools')}["ctx.tools + tool-bash"]`,
  436. ` ${agentCore} --> ${nodeId('spine', 'loop')}["ctx.agents + ctx.agentLoop"]`,
  437. )
  438. }
  439. function renderAppComposition(example: AppExample): string {
  440. const plugins = parseExampleCordis(example.config)
  441. const maintenance = 'hybrid: the leaf plugin list is parsed from its `cordis.yml`; app package expansion is curated from package source'
  442. const lines = generatedHeader(example.title)
  443. lines.push(
  444. example.summary,
  445. '',
  446. '```mermaid',
  447. 'flowchart LR',
  448. ` cfg["${escLabel(example.label)}<br/>cordis.yml"]`,
  449. )
  450. for (const plugin of plugins) {
  451. const pluginNode = nodeId(`plugin_${example.id}`, plugin.id)
  452. lines.push(` ${pluginNode}["${escLabel(plugin.id)}<br/>${escLabel(plugin.name)}"]`)
  453. lines.push(` cfg --> ${pluginNode}`)
  454. if (plugin.name === '@deepseek-ai/dsh-stdio-demo' || plugin.name === '@deepseek-ai/dsh-acp-demo') {
  455. renderAppExpansion(lines, pluginNode, plugin.name)
  456. }
  457. }
  458. lines.push(
  459. '```',
  460. '',
  461. '| Plugin id | Package / module |',
  462. '| --- | --- |',
  463. ...plugins.map(plugin => `| \`${plugin.id}\` | \`${plugin.name}\` |`),
  464. '',
  465. `Source config: [\`${example.config}\`](${linkFromDoc(example.rel, example.config)}).`,
  466. )
  467. lines.push('', ...maintenanceFooter(maintenance))
  468. return lines.join('\n')
  469. }
  470. /** Collect event dispatch/listener relations from real cross-file receiver types. */
  471. class EventRelationCollector {
  472. private readonly relations = new Map<string, EventRelation>()
  473. private readonly callSites = new Map<ts.SignatureDeclaration | ts.JSDocSignature, ts.CallExpression[]>()
  474. private readonly contextType: ts.Type
  475. private readonly agentDispatchType: ts.Type
  476. private readonly eventsServiceType: ts.Type
  477. constructor(
  478. private readonly project: TypeScriptProject,
  479. private readonly sources: readonly PackageSource[],
  480. ) {
  481. this.contextType = this.declaredType('vendor/cordis/src/context.ts', 'Context')
  482. this.agentDispatchType = this.declaredType('packages/core/agent/src/dispatch.ts', 'AgentEventDispatch')
  483. this.eventsServiceType = this.declaredType('vendor/cordis/src/events.ts', 'EventsService')
  484. this.indexCallSites()
  485. }
  486. /** Return all event relations discovered from the Program. */
  487. collect(): Map<string, EventRelation> {
  488. for (const source of this.sources) this.visitSource(source)
  489. return this.relations
  490. }
  491. /** Resolve one named class/interface declaration to its merged instance type. */
  492. private declaredType(relativePath: string, name: string): ts.Type {
  493. const sourceFile = this.project.sourceFile(relativePath)
  494. const declaration = sourceFile.statements.find((statement): statement is ts.ClassDeclaration | ts.InterfaceDeclaration => {
  495. return (ts.isClassDeclaration(statement) || ts.isInterfaceDeclaration(statement)) && statement.name?.text === name
  496. })
  497. const symbol = declaration?.name && this.project.checker.getSymbolAtLocation(declaration.name)
  498. if (!symbol) throw new Error(`cannot resolve TypeScript type ${name} from ${relativePath}`)
  499. return this.project.checker.getDeclaredTypeOfSymbol(symbol)
  500. }
  501. /** Index resolved local function calls for narrow argument-flow recovery. */
  502. private indexCallSites(): void {
  503. const visit = (node: ts.Node): void => {
  504. if (ts.isCallExpression(node)) {
  505. const declaration = this.project.checker.getResolvedSignature(node)?.declaration
  506. if (declaration) {
  507. const calls = this.callSites.get(declaration) ?? []
  508. calls.push(node)
  509. this.callSites.set(declaration, calls)
  510. }
  511. }
  512. ts.forEachChild(node, visit)
  513. }
  514. for (const source of this.sources) visit(source.sourceFile)
  515. }
  516. /** Walk one package source file and classify event API calls by receiver type. */
  517. private visitSource(source: PackageSource): void {
  518. const visit = (node: ts.Node): void => {
  519. if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
  520. const receiverKind = this.receiverKind(node.expression.expression)
  521. const method = node.expression.name.text
  522. if (receiverKind === 'events-service' && method === 'dispatch') {
  523. const argumentList = node.arguments[1]
  524. if (argumentList) {
  525. for (const event of this.eventNamesFromArgumentList(argumentList, new Set())) {
  526. this.addDispatcher(event, source.pkg, 'events.dispatch')
  527. }
  528. }
  529. } else if (receiverKind === 'context' || receiverKind === 'agent-dispatch') {
  530. const eventNames = this.eventNamesFromCall(node, receiverKind)
  531. if (method === 'on' || method === 'once') {
  532. for (const event of eventNames) this.ensure(event).listeners.add(source.pkg)
  533. } else if (method === 'emit' || method === 'parallel' || method === 'serial' || method === 'waterfall') {
  534. for (const event of eventNames) this.addDispatcher(event, source.pkg, method)
  535. }
  536. }
  537. }
  538. ts.forEachChild(node, visit)
  539. }
  540. visit(source.sourceFile)
  541. }
  542. /** Classify a receiver using assignability to the repository's actual event API types. */
  543. private receiverKind(receiver: ts.Expression): EventReceiverKind | undefined {
  544. const type = this.project.checker.getTypeAtLocation(receiver)
  545. if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never)) return undefined
  546. if (this.project.checker.isTypeAssignableTo(type, this.eventsServiceType)) return 'events-service'
  547. if (this.project.checker.isTypeAssignableTo(type, this.contextType)) return 'context'
  548. if (this.project.checker.isTypeAssignableTo(type, this.agentDispatchType)) return 'agent-dispatch'
  549. return undefined
  550. }
  551. /** Resolve the event-name argument for Context and fused agent dispatch calls. */
  552. private eventNamesFromCall(call: ts.CallExpression, receiverKind: Exclude<EventReceiverKind, 'events-service'>): Set<string> {
  553. const candidates = receiverKind === 'context' ? call.arguments.slice(0, 2) : call.arguments.slice(0, 1)
  554. for (const candidate of candidates) {
  555. const values = this.finiteStringValues(candidate)
  556. if (values) return values
  557. }
  558. return new Set()
  559. }
  560. /** Recover the event slot from the argument array handed to EventsService.dispatch(). */
  561. private eventNamesFromArgumentList(expression: ts.Expression, seen: Set<ts.Node>): Set<string> {
  562. const current = unwrapExpression(expression)
  563. if (seen.has(current)) return new Set()
  564. seen.add(current)
  565. if (ts.isArrayLiteralExpression(current)) {
  566. for (const element of current.elements.slice(0, 2)) {
  567. if (ts.isOmittedExpression(element) || ts.isSpreadElement(element)) continue
  568. const values = this.finiteStringValues(element)
  569. if (values) return values
  570. }
  571. return new Set()
  572. }
  573. if (ts.isConditionalExpression(current)) {
  574. return unionSets(
  575. this.eventNamesFromArgumentList(current.whenTrue, new Set(seen)),
  576. this.eventNamesFromArgumentList(current.whenFalse, new Set(seen)),
  577. )
  578. }
  579. if (!ts.isIdentifier(current)) return new Set()
  580. const symbol = this.project.checker.getSymbolAtLocation(current)
  581. if (!symbol) return new Set()
  582. const events = new Set<string>()
  583. for (const declaration of symbol.declarations ?? []) {
  584. if (ts.isVariableDeclaration(declaration) && declaration.initializer && isConstDeclaration(declaration)) {
  585. addAll(events, this.eventNamesFromArgumentList(declaration.initializer, new Set(seen)))
  586. } else if (ts.isParameter(declaration)) {
  587. addAll(events, this.eventNamesFromParameter(declaration, seen))
  588. }
  589. }
  590. return events
  591. }
  592. /** Follow a non-exported local helper parameter back to every resolved call site. */
  593. private eventNamesFromParameter(parameter: ts.ParameterDeclaration, seen: Set<ts.Node>): Set<string> {
  594. const owner = parameter.parent
  595. if (!ts.isFunctionDeclaration(owner) || hasExportModifier(owner)) return new Set()
  596. const index = owner.parameters.indexOf(parameter)
  597. if (index < 0) return new Set()
  598. const events = new Set<string>()
  599. for (const call of this.callSites.get(owner) ?? []) {
  600. const argument = call.arguments[index]
  601. if (argument) addAll(events, this.eventNamesFromArgumentList(argument, new Set(seen)))
  602. }
  603. return events
  604. }
  605. /** Return a finite string-literal value set, rejecting widened and generic strings. */
  606. private finiteStringValues(expression: ts.Expression): Set<string> | undefined {
  607. const current = unwrapExpression(expression)
  608. if (ts.isStringLiteralLike(current)) return new Set([current.text])
  609. if (this.isForwardedAgentEventParameter(current)) return undefined
  610. return finiteStringTypeValues(this.project.checker.getTypeAtLocation(current))
  611. }
  612. /** Reject the contextual parameter inside the AgentEventDispatch forwarding object. */
  613. private isForwardedAgentEventParameter(expression: ts.Expression): boolean {
  614. if (!ts.isIdentifier(expression)) return false
  615. const declarations = this.project.checker.getSymbolAtLocation(expression)?.declarations ?? []
  616. return declarations.some((declaration) => {
  617. if (!ts.isParameter(declaration)) return false
  618. const method = declaration.parent
  619. if (!ts.isMethodDeclaration(method) || !ts.isObjectLiteralExpression(method.parent)) return false
  620. const contextualType = this.project.checker.getContextualType(method.parent)
  621. return contextualType !== undefined
  622. && this.project.checker.isTypeAssignableTo(contextualType, this.agentDispatchType)
  623. })
  624. }
  625. /** Get or create one relation row. */
  626. private ensure(event: string): EventRelation {
  627. const existing = this.relations.get(event)
  628. if (existing) return existing
  629. const relation = { dispatchers: new Map<string, Set<string>>(), listeners: new Set<string>() }
  630. this.relations.set(event, relation)
  631. return relation
  632. }
  633. /** Add one dispatcher method without duplicating package/method labels. */
  634. private addDispatcher(event: string, pkg: string, method: string): void {
  635. const relation = this.ensure(event)
  636. const methods = relation.dispatchers.get(pkg) ?? new Set<string>()
  637. methods.add(method)
  638. relation.dispatchers.set(pkg, methods)
  639. }
  640. }
  641. /** Peel syntax-only wrappers that do not change an expression's runtime value. */
  642. function unwrapExpression(expression: ts.Expression): ts.Expression {
  643. let current = expression
  644. while (
  645. ts.isParenthesizedExpression(current)
  646. || ts.isAsExpression(current)
  647. || ts.isTypeAssertionExpression(current)
  648. || ts.isNonNullExpression(current)
  649. || ts.isSatisfiesExpression(current)
  650. ) {
  651. current = current.expression
  652. }
  653. return current
  654. }
  655. /** Return every value only when a type is a closed string-literal union. */
  656. function finiteStringTypeValues(type: ts.Type): Set<string> | undefined {
  657. if (type.flags & ts.TypeFlags.StringLiteral) {
  658. return new Set([(type as ts.StringLiteralType).value])
  659. }
  660. if (type.flags & ts.TypeFlags.Never) return new Set()
  661. if (!type.isUnion()) return undefined
  662. const values = new Set<string>()
  663. for (const member of type.types) {
  664. const memberValues = finiteStringTypeValues(member)
  665. if (!memberValues) return undefined
  666. addAll(values, memberValues)
  667. }
  668. return values
  669. }
  670. /** Return whether a variable declaration belongs to a const declaration list. */
  671. function isConstDeclaration(declaration: ts.VariableDeclaration): boolean {
  672. return (declaration.parent.flags & ts.NodeFlags.Const) !== 0
  673. }
  674. /** Return whether a declaration is visible to callers outside its source module. */
  675. function hasExportModifier(node: ts.Node): boolean {
  676. return ts.canHaveModifiers(node) && (ts.getModifiers(node)?.some((modifier) => {
  677. return modifier.kind === ts.SyntaxKind.ExportKeyword || modifier.kind === ts.SyntaxKind.DefaultKeyword
  678. }) ?? false)
  679. }
  680. /** Add every member of source to target. */
  681. function addAll<T>(target: Set<T>, source: ReadonlySet<T>): void {
  682. for (const value of source) target.add(value)
  683. }
  684. /** Return the union of two sets without mutating either input. */
  685. function unionSets<T>(left: ReadonlySet<T>, right: ReadonlySet<T>): Set<T> {
  686. const out = new Set(left)
  687. addAll(out, right)
  688. return out
  689. }
  690. function collectEventRelations(): Map<string, EventRelation> {
  691. const project = new TypeScriptProject(root)
  692. const sources = project.sourceFiles().flatMap((sourceFile): PackageSource[] => {
  693. const rel = project.relativePath(sourceFile)
  694. const match = /^packages\/[^/]+\/([^/]+)\/src\/.+\.ts$/.exec(rel)
  695. return match?.[1] ? [{ rel, pkg: match[1], sourceFile }] : []
  696. }).sort((left, right) => left.rel.localeCompare(right.rel))
  697. return new EventRelationCollector(project, sources).collect()
  698. }
  699. function relationPackages(map: Map<string, Set<string>>, pkgsByShort: Map<string, Pkg>): string {
  700. if (map.size === 0) return '-'
  701. return [...map.entries()]
  702. .sort(([a], [b]) => a.localeCompare(b))
  703. .map(([pkg, methods]) => `${pkgLink(pkgsByShort.get(pkg), pkg)} (${[...methods].sort().map(m => `\`${m}\``).join(', ')})`)
  704. .join(', ')
  705. }
  706. function listenerPackages(listeners: Set<string>, pkgsByShort: Map<string, Pkg>): string {
  707. if (listeners.size === 0) return '-'
  708. return [...listeners].sort().map(pkg => pkgLink(pkgsByShort.get(pkg), pkg)).join(', ')
  709. }
  710. function renderEventRelations(pkgs: Pkg[]): string {
  711. const events = collectEvents()
  712. const relations = collectEventRelations()
  713. const pkgsByShort = new Map(pkgs.map(pkg => [pkg.short, pkg]))
  714. const maintenance = 'generated: Cordis event declarations and producer/listener edges are resolved from the repository TypeScript Program'
  715. const lines = generatedHeader('Event Producer And Consumer Matrix')
  716. lines.push(
  717. 'This matrix shows which packages dispatch each harness-owned event and which packages listen to it. It is intentionally a table rather than one large graph: events are many-to-many, and dense relation data is easier to review in rows. Receiver and event-name types also cover contained dispatch sites that deliberately bypass `ctx.emit`, such as subagent lifecycle containment.',
  718. '',
  719. '| Event | Mode | Declared in | Dispatchers | Listeners |',
  720. '| --- | --- | --- | --- | --- |',
  721. )
  722. for (const event of [...events].sort((a, b) => a.name.localeCompare(b.name))) {
  723. const relation = relations.get(event.name) ?? { dispatchers: new Map<string, Set<string>>(), listeners: new Set<string>() }
  724. lines.push(`| \`${event.name}\` | \`${event.mode}\` | ${sourceLink(event.source)} | ${relationPackages(relation.dispatchers, pkgsByShort)} | ${listenerPackages(relation.listeners, pkgsByShort)} |`)
  725. }
  726. // Every declared event needs a dispatcher: zero means dead vocabulary or an
  727. // unrecognized semantic dispatch shape. Listener-free extension points remain valid.
  728. const undispatched = [...events]
  729. .filter(event => (relations.get(event.name)?.dispatchers.size ?? 0) === 0)
  730. .map(event => event.name)
  731. .sort()
  732. if (undispatched.length > 0) {
  733. throw new Error(
  734. `event-producer-consumer matrix: no dispatcher found for declared event${undispatched.length > 1 ? 's' : ''} `
  735. + `${undispatched.map(name => `"${name}"`).join(', ')} — dead vocabulary, or a dispatch shape the semantic scan misses `
  736. + '(teach scripts/gen-doc-graphs.ts the shape)',
  737. )
  738. }
  739. const declared = new Set(events.map(event => event.name))
  740. const extra = [...relations.keys()].filter(event => !declared.has(event)).sort()
  741. if (extra.length > 0) {
  742. lines.push('', '## Non-harness or undeclared event strings seen in package source', '', '| Event string | Dispatchers | Listeners |', '| --- | --- | --- |')
  743. for (const event of extra) {
  744. const relation = relations.get(event)
  745. if (!relation) continue
  746. lines.push(`| \`${event}\` | ${relationPackages(relation.dispatchers, pkgsByShort)} | ${listenerPackages(relation.listeners, pkgsByShort)} |`)
  747. }
  748. }
  749. lines.push('', ...maintenanceFooter(maintenance))
  750. return lines.join('\n')
  751. }
  752. function renderLifecycle(): string {
  753. const maintenance = 'curated Mermaid sequence; exact event signatures live in the generated Cordis catalog'
  754. return [
  755. ...generatedHeader('Agent Turn And Step Lifecycle'),
  756. 'This sequence is the visual companion to [architecture.md](architecture.md#loop-lifecycle-session--turn--step). It keeps durable replay facts on `session/event` and live control/status on `agent/*`.',
  757. '',
  758. '```mermaid',
  759. 'sequenceDiagram',
  760. ' participant User',
  761. ' participant Agent',
  762. ' participant Driver',
  763. ' participant Hooks as hook listeners',
  764. ' participant Prompt as ctx.systemPrompt',
  765. ' participant LLM as ctx.llm',
  766. ' participant Tools as ctx.tools',
  767. ' participant Session',
  768. ' participant Persistence',
  769. ' participant SDK as UI or SDK listener',
  770. ' User->>Agent: send(content)',
  771. ` Agent-->>SDK: ${mermaidCode('agent/queued')}`,
  772. ' Agent->>Driver: queued work wakes driver',
  773. ` Driver-->>SDK: ${mermaidCode('agent/status')} running`,
  774. ` Driver->>Session: ${mermaidCode('turn/start')}`,
  775. ` Driver->>Hooks: ${mermaidCode('agent/prompt-submit')} waterfall`,
  776. ' Hooks-->>Driver: allow, block, or add context',
  777. ` Driver->>Session: ${mermaidCode('user/message')} or rejected ${mermaidCode('turn/end')}`,
  778. ` Driver->>Prompt: ${mermaidCode('system-prompt/assemble')} waterfall`,
  779. ` Driver-->>Driver: ${mermaidCode('agent/pre-step')} serial checkpoint`,
  780. ` Driver->>Session: ${mermaidCode('step/start')}`,
  781. ` Driver->>LLM: ${mermaidCode('agent/request')} waterfall, then ${mermaidCode('llm/stream')} waterfall`,
  782. ' LLM-->>Driver: StreamChunk*',
  783. ` Driver->>Session: ${mermaidCode('assistant/chunk')}*`,
  784. ` Session-->>SDK: ${mermaidCode('session/event')} ${mermaidCode('assistant/chunk')}*`,
  785. ` Driver->>Hooks: ${mermaidCode('agent/step-result')} waterfall`,
  786. ` Driver->>Session: ${mermaidCode('assistant/message')}`,
  787. ` Driver->>Session: ${mermaidCode('tool/call')}`,
  788. ' Driver->>Tools: execute through pre and post waterfalls',
  789. ' Tools-->>Session: tool-owned events when applicable',
  790. ` Driver->>Session: ${mermaidCode('tool/result')} and ${mermaidCode('step/end')}`,
  791. ` Driver->>Hooks: ${mermaidCode('agent/turn-continuation')} waterfall`,
  792. ` Driver->>Hooks: ${mermaidCode('agent/turn-stop')} serial terminal checkpoint`,
  793. ` Driver->>Session: ${mermaidCode('turn/end')}`,
  794. ` Driver->>Persistence: ${mermaidCode('session/flush')} parallel checkpoint`,
  795. ` Driver-->>SDK: ${mermaidCode('agent/status')} idle`,
  796. '```',
  797. '',
  798. 'SDK users that need replayable transcript data should consume `session/event`; `agent/*` is the live coordination surface for queue/status, prompt interception, request shaping, steering, continuation, and errors.',
  799. '',
  800. ...maintenanceFooter(maintenance),
  801. ].join('\n')
  802. }
  803. function renderToolPipeline(): string {
  804. const maintenance = 'curated Mermaid flow; exact tool schemas and event signatures live in generated catalogs'
  805. return [
  806. ...generatedHeader('Tool Execution Pipeline'),
  807. 'This graph shows where policy, hooks, sandboxing, filesystem guards, result rewriting, final-outcome observation, and UI rendering fit without changing the loop. The transformable extension points are the `tools/pre-execute`, `tools/execute`, and `tools/post-execute` waterfalls; monotonic guards and `tools/result` are the owner-enforced boundaries around them.',
  808. '',
  809. '```mermaid',
  810. 'flowchart TD',
  811. ' model["Assistant message contains tool-call block"]',
  812. ` toolCall["Session event: ${mermaidCode('tool/call')}<br/>logged before execution"]`,
  813. ' presentCall["UI pending card<br/>presentCall(args)"]',
  814. ` pre["${mermaidCode('tools/pre-execute')} waterfall<br/>hooks, permission, sandbox"]`,
  815. ' guards["Registered monotonic guards<br/>deny or abstain; identity protected"]',
  816. ' denied["denied or approval refused<br/>tool body skipped"]',
  817. ` approval["${mermaidCode('ctx.approval')} one-shot prompt<br/>absent or unanswerable: deny"]`,
  818. ` around["${mermaidCode('tools/execute')} waterfall<br/>timeout, retry, metrics (around dispatch)"]`,
  819. ' toolBody["Registered tool execute() body"]',
  820. ` fsGate["${mermaidCode('fs/write-intent')} or ${mermaidCode('fs/edit-intent')}<br/>tool-fs mutations only"]`,
  821. ` owned["Tool-owned session events<br/>${mermaidCode('todo/write')}, ${mermaidCode('fs/observed')}, ${mermaidCode('hook/invoked')}, ${mermaidCode('hook/result')}, ${mermaidCode('tool/code-dispatch')}"]`,
  822. ` post["${mermaidCode('tools/post-execute')} waterfall<br/>accept, block, replace, add context"]`,
  823. ` final["${mermaidCode('tools/result')} synchronous notification<br/>frozen authoritative outcome"]`,
  824. ' context["Buffered additionalContexts<br/>context/message after all tool results"]',
  825. ` toolResult["Session event: ${mermaidCode('tool/result')}<br/>single model-facing outcome"]`,
  826. ' allResults["All calls in the step settled<br/>and tool/result events recorded"]',
  827. ' presentResult["UI completed card<br/>presentResult(args, result)"]',
  828. ' model --> toolCall',
  829. ' toolCall --> presentCall',
  830. ' toolCall --> pre',
  831. ' pre -->|allow| guards',
  832. ' guards -->|allow| around',
  833. ' guards -->|deny| denied',
  834. ' around --> toolBody',
  835. ' pre -->|deny| denied',
  836. ' pre -->|ask| approval',
  837. ' approval -->|allowed-once| guards',
  838. ' approval -->|rejected, cancelled, unavailable| denied',
  839. ' denied --> post',
  840. ' toolBody --> fsGate',
  841. ' fsGate --> toolBody',
  842. ' toolBody --> owned',
  843. ' toolBody --> around',
  844. ' around --> post',
  845. ' post --> final',
  846. ' final --> toolResult',
  847. ' toolResult --> presentResult',
  848. ' toolResult --> allResults',
  849. ' allResults --> context',
  850. '```',
  851. '',
  852. 'Filesystem read-before-edit checks stay below `tool-fs` on `fs/*` events. Generic pre/post waterfalls host hooks and approval policy; `ctx.approval` resolves asks before monotonic guards, and owner policy that must not be reordered remains a registered guard. Around-dispatch concerns such as timeouts wrap `tools/execute`, while `tools/result` observes the immutable outcome after transforms, lossless-JSON validation, and outer error normalization. This lets hooks span tool families without coupling the tools to one policy service. Code Mode sends both the reserved `run_code` transport and its serialized sub-calls through the pipeline; sub-calls carry the parent token, log `tool/code-dispatch`, surface denials as binding rejections, and omit `additionalContexts` to preserve call/result adjacency.',
  853. '',
  854. ...maintenanceFooter(maintenance),
  855. ].join('\n')
  856. }
  857. function renderSnapshotReplay(): string {
  858. const maintenance = 'curated Mermaid sequence based on the snapshot test harness'
  859. return [
  860. ...generatedHeader('ACP Snapshot Replay'),
  861. 'This graph explains what a snapshot scenario proves: recorded real-model session logs are replayed keylessly, ACP stdout is normalized and diffed, and scenario workspaces preserve tool side effects that the UI stream alone cannot prove.',
  862. '',
  863. '```mermaid',
  864. 'sequenceDiagram',
  865. ' participant Recorder as Real API recording',
  866. ' participant Fixture as snapshot fixture',
  867. ' participant Workspace',
  868. ' participant Replay as llm-replay adapter',
  869. ' participant ACP as acp-agent subprocess',
  870. ' participant Golden as stdout golden',
  871. ' Recorder->>Fixture: session.jsonl + workspace inputs',
  872. ' Fixture->>Workspace: seed files and hook configs',
  873. ' Fixture->>Replay: recorded StreamChunk script',
  874. ` Replay->>ACP: deterministic ${mermaidCode('llm/stream')} chunks`,
  875. ' ACP->>Workspace: bash, fs, and hook side effects',
  876. ' ACP->>Golden: normalized sessionUpdate stream',
  877. ' Golden-->>ACP: diff must be empty',
  878. '```',
  879. '',
  880. 'The fs and hook snapshot matrix is valuable because it proves world state, hook decisions, and failed tool-card rendering, not just that replay returns text.',
  881. '',
  882. ...maintenanceFooter(maintenance),
  883. ].join('\n')
  884. }
  885. function renderDocs(): GraphDoc[] {
  886. const pkgs = collectPackageGraph(root, GROUP_ORDER, 'gen-doc-graphs')
  887. const docs: GraphDoc[] = [
  888. { rel: 'docs/capability-seams.md', content: renderCapabilitySeams(pkgs) },
  889. ...APP_EXAMPLES.map(example => ({ rel: example.rel, content: renderAppComposition(example) })),
  890. { rel: 'docs/event-producer-consumer.md', content: renderEventRelations(pkgs) },
  891. { rel: 'docs/agent-lifecycle.md', content: renderLifecycle() },
  892. { rel: 'docs/tool-execution-pipeline.md', content: renderToolPipeline() },
  893. { rel: 'packages/ui/acp/snapshot-replay.md', content: renderSnapshotReplay() },
  894. ]
  895. docs.unshift({ rel: 'docs/graph-atlas.md', content: renderIndex(docs) })
  896. return docs
  897. }
  898. function renderIndex(docs: GraphDoc[]): string {
  899. const labels: Record<string, string> = {
  900. 'docs/capability-seams.md': 'capability seams and core services',
  901. 'examples/echo-agent/composition.md': 'echo-agent app composition',
  902. 'examples/coding-agent/composition.md': 'coding-agent app composition',
  903. 'examples/cordis-agent/composition.md': 'cordis-agent app composition',
  904. 'examples/acp-agent/composition.md': 'acp-agent app composition',
  905. 'docs/event-producer-consumer.md': 'event producer/consumer matrix',
  906. 'docs/agent-lifecycle.md': 'agent turn and step lifecycle',
  907. 'docs/tool-execution-pipeline.md': 'tool execution pipeline',
  908. 'packages/ui/acp/snapshot-replay.md': 'ACP snapshot replay',
  909. }
  910. const modes: Record<string, string> = {
  911. 'docs/capability-seams.md': 'hybrid generated',
  912. 'examples/echo-agent/composition.md': 'hybrid generated',
  913. 'examples/coding-agent/composition.md': 'hybrid generated',
  914. 'examples/cordis-agent/composition.md': 'hybrid generated',
  915. 'examples/acp-agent/composition.md': 'hybrid generated',
  916. 'docs/event-producer-consumer.md': 'hybrid generated',
  917. 'docs/agent-lifecycle.md': 'curated',
  918. 'docs/tool-execution-pipeline.md': 'curated',
  919. 'packages/ui/acp/snapshot-replay.md': 'curated',
  920. }
  921. const rows = [
  922. '| [module dependency graph](module-graph.md) | `generated` |',
  923. '| [tool schema catalog and package map](tool-catalog.md) | `generated` |',
  924. ...docs.map((doc) => {
  925. const link = graphIndexLink(doc.rel)
  926. return `| [${labels[doc.rel] ?? link}](${link}) | \`${modes[doc.rel] ?? 'generated'}\` |`
  927. }),
  928. ]
  929. const maintenance = 'mixed: each linked page declares generated, hybrid, or curated mode'
  930. return [
  931. ...generatedHeader('Documentation Graph Index'),
  932. 'These diagrams are the relationship layer above the generated catalogs. Use them to navigate package topology, capability seams, event flow, model-facing tools, app composition, and runtime lifecycle paths. Exact signatures and type shapes still live in the generated [events](cordis-catalog/events.md) / [services](cordis-catalog/services.md) catalogs, [tool-catalog.md](tool-catalog.md), and [core-data-structures/](core-data-structures/core.md).',
  933. '',
  934. 'The process decision behind this index is recorded in [the documentation graph RFC](rfc/implemented/process/2026-07-03-documentation-graph-atlas.md).',
  935. '',
  936. '| Graph | Mode |',
  937. '| --- | --- |',
  938. ...rows,
  939. '',
  940. 'Regenerate with `pnpm run gen-doc-graphs`; verify freshness with `pnpm run verify-doc-graphs`.',
  941. '',
  942. ...maintenanceFooter(maintenance),
  943. ].join('\n')
  944. }
  945. function main(): void {
  946. const docs = renderDocs()
  947. if (process.argv.includes('--check')) {
  948. const stale: string[] = []
  949. for (const doc of docs) {
  950. const abs = resolve(root, doc.rel)
  951. const committed = existsSync(abs) ? readFileSync(abs, 'utf8') : null
  952. if (committed !== doc.content) stale.push(doc.rel)
  953. }
  954. if (stale.length === 0) {
  955. console.log(`gen-doc-graphs: ${docs.length} graph doc(s) are up to date.`)
  956. return
  957. }
  958. console.error(`gen-doc-graphs: stale graph doc(s): ${stale.join(', ')}. Run \`pnpm run gen-doc-graphs\` and commit the result.`)
  959. process.exit(1)
  960. }
  961. for (const doc of docs) {
  962. mkdirSync(dirname(resolve(root, doc.rel)), { recursive: true })
  963. writeFileSync(resolve(root, doc.rel), doc.content)
  964. }
  965. console.log(`gen-doc-graphs: wrote ${docs.length} graph doc(s).`)
  966. }
  967. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  968. main()
  969. }