gen-doc-graphs.ts 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  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', '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',
  101. mode: 'seam',
  102. note: 'Resolves live and optional persisted logs into one logical corpus for exact reads.',
  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: 'sandbox',
  165. pkg: 'sandbox',
  166. title: 'Process-sandbox seam',
  167. mode: 'seam',
  168. implementations: ['sandbox-local'],
  169. consumers: ['bash-sandbox'],
  170. 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.',
  171. },
  172. {
  173. key: 'approval',
  174. pkg: 'approval',
  175. title: 'Approval seam',
  176. mode: 'seam',
  177. implementations: ['acp'],
  178. consumers: ['tools', 'tool-bash'],
  179. 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`.',
  180. },
  181. {
  182. key: 'permission',
  183. pkg: 'permission',
  184. title: 'Permission presets',
  185. mode: 'core',
  186. implementations: [],
  187. consumers: ['acp'],
  188. 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.',
  189. },
  190. {
  191. key: 'codeRuntime',
  192. pkg: 'code-runtime',
  193. title: 'Code-execution seam',
  194. mode: 'seam',
  195. implementations: ['code-runtime-worker'],
  196. consumers: ['tools'],
  197. 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).',
  198. },
  199. {
  200. key: 'fs',
  201. pkg: 'fs',
  202. title: 'Filesystem provider seam',
  203. mode: 'seam',
  204. implementations: ['fs-local'],
  205. consumers: ['tool-fs'],
  206. companions: ['fs-policy'],
  207. note: 'tool-fs executes read/write/edit through ctx.fs; fs-policy contributes observed-state checks through the fs/* event gate.',
  208. },
  209. {
  210. key: 'compact',
  211. pkg: 'compact',
  212. title: 'Compaction seam',
  213. mode: 'seam',
  214. implementations: ['compact-basic'],
  215. consumers: ['compact-basic'],
  216. note: 'The basic backend currently consumes the pre-step event directly; a model-facing compact tool remains deferred.',
  217. },
  218. {
  219. key: 'subagents',
  220. pkg: 'subagent',
  221. title: 'Subagent provider registry',
  222. mode: 'seam',
  223. implementations: ['subagent-spawn', 'subagent-fork', 'subagent-acp', 'subagent-mock'],
  224. consumers: ['tool-subagent'],
  225. note: 'Providers implement transports; tool-subagent exposes one configured provider as a model-facing tool name.',
  226. },
  227. {
  228. key: 'tasks',
  229. pkg: 'tasks',
  230. title: 'Background task registry',
  231. mode: 'core',
  232. consumers: ['tool-bash', 'tool-subagent', 'tool-tasks'],
  233. 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.',
  234. },
  235. {
  236. key: 'web',
  237. pkg: 'web',
  238. title: 'Web access provider registry',
  239. mode: 'seam',
  240. implementations: ['web-search-exa', 'web-search-perplexity', 'web-search-deepseek', 'web-fetch-local'],
  241. consumers: ['tool-web'],
  242. note: 'Search and fetch providers register into one ctx.web seam; tool-web owns the stable model-facing names.',
  243. },
  244. {
  245. key: 'spillStore',
  246. pkg: 'spill',
  247. title: 'Spill storage seam',
  248. mode: 'seam',
  249. implementations: ['spill-local'],
  250. consumers: ['spill-policy'],
  251. 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.',
  252. },
  253. {
  254. key: 'workflows',
  255. pkg: 'workflow',
  256. title: 'Workflow script engine',
  257. mode: 'seam',
  258. implementations: ['workflow-workerthread'],
  259. consumers: ['tool-workflow'],
  260. note: 'One engine per context (bash shape, no named-provider registry); the worker-thread engine fans agent() calls out through ctx.subagents.',
  261. },
  262. ]
  263. function generatedHeader(title: string): string[] {
  264. return [
  265. '<!-- Generated by scripts/gen-doc-graphs.ts - do not edit by hand.',
  266. ' Run `pnpm run gen-doc-graphs` to regenerate. -->',
  267. '',
  268. `# ${title}`,
  269. '',
  270. ]
  271. }
  272. function maintenanceFooter(source: string): string[] {
  273. return [`Maintenance mode: ${source}.`, '']
  274. }
  275. function graphIndexLink(rel: string): string {
  276. return relative('docs', rel).replaceAll('\\', '/')
  277. }
  278. function linkFromDoc(docRel: string, targetRel: string): string {
  279. return relative(dirname(docRel), targetRel).replaceAll('\\', '/')
  280. }
  281. function mermaidCode(value: string): string {
  282. return `<code>${value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</code>`
  283. }
  284. function repoLink(path: string, label: string, up = '..'): string {
  285. return `[${label}](${up}/${path})`
  286. }
  287. function sourceLink(source: string, up = '..'): string {
  288. return repoLink(source.split(':')[0] ?? source, `\`${source}\``, up)
  289. }
  290. function pkgLink(pkg: Pkg | undefined, fallback: string, up = '..'): string {
  291. return pkg ? repoLink(pkg.rel, `\`${pkg.short}\``, up) : `\`${fallback}\``
  292. }
  293. function pkgList(names: string[] | undefined, pkgsByShort: Map<string, Pkg>): string {
  294. if (!names || names.length === 0) return '-'
  295. return names.map(name => pkgLink(pkgsByShort.get(name), name)).join(', ')
  296. }
  297. function tableCell(value: string): string {
  298. return value.replace(/\|/g, '\\|').replace(/\n/g, '<br>')
  299. }
  300. function assertServiceRolesComplete(): void {
  301. const discovered = new Set(collectServices().map(service => service.key))
  302. const classified = new Set(SERVICE_ROLES.map(role => role.key))
  303. const missing = [...discovered].filter(key => !classified.has(key)).sort()
  304. const stale = [...classified].filter(key => !discovered.has(key)).sort()
  305. if (missing.length || stale.length) {
  306. throw new Error([
  307. missing.length ? `missing service role classification: ${missing.join(', ')}` : '',
  308. stale.length ? `stale service role classification: ${stale.join(', ')}` : '',
  309. ].filter(Boolean).join('; '))
  310. }
  311. }
  312. function renderCapabilitySeams(pkgs: Pkg[]): string {
  313. assertServiceRolesComplete()
  314. const pkgsByShort = new Map(pkgs.map(pkg => [pkg.short, pkg]))
  315. 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'
  316. const nodes = new Map<string, string>()
  317. const edges = new Set<string>()
  318. const companionEdges = new Set<string>()
  319. const addNode = (id: string, label: string): void => {
  320. if (!nodes.has(id)) nodes.set(id, ` ${id}["${escLabel(label)}"]`)
  321. }
  322. const addEdge = (from: string, to: string): void => { edges.add(` ${from} --> ${to}`) }
  323. const lines = generatedHeader('Capability Seams And Core Services')
  324. lines.push(
  325. '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.',
  326. '',
  327. '```mermaid',
  328. 'flowchart LR',
  329. )
  330. for (const role of SERVICE_ROLES) {
  331. const svc = nodeId('svc', role.key)
  332. const owner = nodeId('pkg', role.pkg)
  333. addNode(owner, role.pkg)
  334. addNode(svc, `ctx.${role.key}<br/>${role.title}`)
  335. addEdge(owner, svc)
  336. for (const impl of role.implementations ?? []) {
  337. addNode(nodeId('pkg', impl), impl)
  338. addEdge(nodeId('pkg', impl), svc)
  339. }
  340. for (const consumer of role.consumers ?? []) {
  341. addNode(nodeId('pkg', consumer), consumer)
  342. addEdge(svc, nodeId('pkg', consumer))
  343. }
  344. for (const companion of role.companions ?? []) {
  345. addNode(nodeId('pkg', companion), companion)
  346. companionEdges.add(` ${svc} -. event gate .-> ${nodeId('pkg', companion)}`)
  347. }
  348. }
  349. lines.push(...nodes.values(), ...[...edges].sort(), ...[...companionEdges].sort())
  350. lines.push('```', '', '| ctx key | Role | Owner | Implementations | Direct consumers | Companion plugins | Note |', '| --- | --- | --- | --- | --- | --- | --- |')
  351. for (const role of SERVICE_ROLES) {
  352. 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)} |`)
  353. }
  354. lines.push('', ...maintenanceFooter(maintenance))
  355. return lines.join('\n')
  356. }
  357. function parseExampleCordis(rel: string): ExamplePlugin[] {
  358. const text = readFileSync(resolve(root, rel), 'utf8')
  359. const plugins: ExamplePlugin[] = []
  360. let current: { id: string; name?: string } | null = null
  361. const flush = (): void => {
  362. if (current?.name) plugins.push({ id: current.id, name: current.name })
  363. }
  364. for (const line of text.split('\n')) {
  365. const id = /^-\s+id:\s+(.+?)\s*$/.exec(line)
  366. if (id?.[1] !== undefined) {
  367. flush()
  368. current = { id: stripYamlScalar(id[1]) }
  369. continue
  370. }
  371. const name = /^\s+name:\s+(.+?)\s*$/.exec(line)
  372. if (name?.[1] !== undefined && current) current.name = stripYamlScalar(name[1])
  373. }
  374. flush()
  375. return plugins
  376. }
  377. function stripYamlScalar(value: string): string {
  378. return value.trim().replace(/^['"]|['"]$/g, '')
  379. }
  380. const APP_EXAMPLES = [
  381. {
  382. id: 'echo',
  383. rel: 'examples/echo-agent/composition.md',
  384. title: 'Echo Agent App Composition',
  385. label: 'examples/echo-agent',
  386. config: 'examples/echo-agent/cordis.yml',
  387. 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.',
  388. },
  389. {
  390. id: 'coding',
  391. rel: 'examples/coding-agent/composition.md',
  392. title: 'Coding Agent App Composition',
  393. label: 'examples/coding-agent',
  394. config: 'examples/coding-agent/cordis.yml',
  395. 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.',
  396. },
  397. {
  398. id: 'cordis',
  399. rel: 'examples/cordis-agent/composition.md',
  400. title: 'Cordis Agent App Composition',
  401. label: 'examples/cordis-agent',
  402. config: 'examples/cordis-agent/cordis.yml',
  403. 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.',
  404. },
  405. {
  406. id: 'acp',
  407. rel: 'examples/acp-agent/composition.md',
  408. title: 'ACP Agent App Composition',
  409. label: 'examples/acp-agent',
  410. config: 'examples/acp-agent/cordis.yml',
  411. 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.',
  412. },
  413. ]
  414. type AppExample = typeof APP_EXAMPLES[number]
  415. function renderAppExpansion(lines: string[], appNode: string, pluginName: string): void {
  416. const agentCore = nodeId('bundle', 'agent_core')
  417. const jsonl = nodeId('bundle', 'jsonl')
  418. lines.push(` ${appNode} --> ${agentCore}["@deepseek-ai/dsh-agent-spine-demo"]`)
  419. lines.push(` ${appNode} --> ${jsonl}["@deepseek-ai/dsh-session-persistence-jsonl"]`)
  420. if (pluginName === '@deepseek-ai/dsh-stdio-demo') {
  421. lines.push(` ${appNode} --> ${nodeId('frontdoor', 'stdio')}["readline UI<br/>console logger<br/>pre-created main agent"]`)
  422. } else if (pluginName === '@deepseek-ai/dsh-acp-demo') {
  423. lines.push(` ${appNode} --> ${nodeId('frontdoor', 'acp')}["@deepseek-ai/dsh-acp<br/>JSON-RPC stdio bridge<br/>sessions created by client"]`)
  424. }
  425. lines.push(
  426. ` ${agentCore} --> ${nodeId('spine', 'llm')}["ctx.llm"]`,
  427. ` ${agentCore} --> ${nodeId('spine', 'sessions')}["ctx.sessions"]`,
  428. ` ${agentCore} --> ${nodeId('spine', 'tools')}["ctx.tools + tool-bash"]`,
  429. ` ${agentCore} --> ${nodeId('spine', 'loop')}["ctx.agents + ctx.agentLoop"]`,
  430. )
  431. }
  432. function renderAppComposition(example: AppExample): string {
  433. const plugins = parseExampleCordis(example.config)
  434. const maintenance = 'hybrid: the leaf plugin list is parsed from its `cordis.yml`; app package expansion is curated from package source'
  435. const lines = generatedHeader(example.title)
  436. lines.push(
  437. example.summary,
  438. '',
  439. '```mermaid',
  440. 'flowchart LR',
  441. ` cfg["${escLabel(example.label)}<br/>cordis.yml"]`,
  442. )
  443. for (const plugin of plugins) {
  444. const pluginNode = nodeId(`plugin_${example.id}`, plugin.id)
  445. lines.push(` ${pluginNode}["${escLabel(plugin.id)}<br/>${escLabel(plugin.name)}"]`)
  446. lines.push(` cfg --> ${pluginNode}`)
  447. if (plugin.name === '@deepseek-ai/dsh-stdio-demo' || plugin.name === '@deepseek-ai/dsh-acp-demo') {
  448. renderAppExpansion(lines, pluginNode, plugin.name)
  449. }
  450. }
  451. lines.push(
  452. '```',
  453. '',
  454. '| Plugin id | Package / module |',
  455. '| --- | --- |',
  456. ...plugins.map(plugin => `| \`${plugin.id}\` | \`${plugin.name}\` |`),
  457. '',
  458. `Source config: [\`${example.config}\`](${linkFromDoc(example.rel, example.config)}).`,
  459. )
  460. lines.push('', ...maintenanceFooter(maintenance))
  461. return lines.join('\n')
  462. }
  463. /** Collect event dispatch/listener relations from real cross-file receiver types. */
  464. class EventRelationCollector {
  465. private readonly relations = new Map<string, EventRelation>()
  466. private readonly callSites = new Map<ts.SignatureDeclaration | ts.JSDocSignature, ts.CallExpression[]>()
  467. private readonly contextType: ts.Type
  468. private readonly agentDispatchType: ts.Type
  469. private readonly eventsServiceType: ts.Type
  470. constructor(
  471. private readonly project: TypeScriptProject,
  472. private readonly sources: readonly PackageSource[],
  473. ) {
  474. this.contextType = this.declaredType('vendor/cordis/src/context.ts', 'Context')
  475. this.agentDispatchType = this.declaredType('packages/core/agent/src/dispatch.ts', 'AgentEventDispatch')
  476. this.eventsServiceType = this.declaredType('vendor/cordis/src/events.ts', 'EventsService')
  477. this.indexCallSites()
  478. }
  479. /** Return all event relations discovered from the Program. */
  480. collect(): Map<string, EventRelation> {
  481. for (const source of this.sources) this.visitSource(source)
  482. return this.relations
  483. }
  484. /** Resolve one named class/interface declaration to its merged instance type. */
  485. private declaredType(relativePath: string, name: string): ts.Type {
  486. const sourceFile = this.project.sourceFile(relativePath)
  487. const declaration = sourceFile.statements.find((statement): statement is ts.ClassDeclaration | ts.InterfaceDeclaration => {
  488. return (ts.isClassDeclaration(statement) || ts.isInterfaceDeclaration(statement)) && statement.name?.text === name
  489. })
  490. const symbol = declaration?.name && this.project.checker.getSymbolAtLocation(declaration.name)
  491. if (!symbol) throw new Error(`cannot resolve TypeScript type ${name} from ${relativePath}`)
  492. return this.project.checker.getDeclaredTypeOfSymbol(symbol)
  493. }
  494. /** Index resolved local function calls for narrow argument-flow recovery. */
  495. private indexCallSites(): void {
  496. const visit = (node: ts.Node): void => {
  497. if (ts.isCallExpression(node)) {
  498. const declaration = this.project.checker.getResolvedSignature(node)?.declaration
  499. if (declaration) {
  500. const calls = this.callSites.get(declaration) ?? []
  501. calls.push(node)
  502. this.callSites.set(declaration, calls)
  503. }
  504. }
  505. ts.forEachChild(node, visit)
  506. }
  507. for (const source of this.sources) visit(source.sourceFile)
  508. }
  509. /** Walk one package source file and classify event API calls by receiver type. */
  510. private visitSource(source: PackageSource): void {
  511. const visit = (node: ts.Node): void => {
  512. if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
  513. const receiverKind = this.receiverKind(node.expression.expression)
  514. const method = node.expression.name.text
  515. if (receiverKind === 'events-service' && method === 'dispatch') {
  516. const argumentList = node.arguments[1]
  517. if (argumentList) {
  518. for (const event of this.eventNamesFromArgumentList(argumentList, new Set())) {
  519. this.addDispatcher(event, source.pkg, 'events.dispatch')
  520. }
  521. }
  522. } else if (receiverKind === 'context' || receiverKind === 'agent-dispatch') {
  523. const eventNames = this.eventNamesFromCall(node, receiverKind)
  524. if (method === 'on' || method === 'once') {
  525. for (const event of eventNames) this.ensure(event).listeners.add(source.pkg)
  526. } else if (method === 'emit' || method === 'parallel' || method === 'serial' || method === 'waterfall') {
  527. for (const event of eventNames) this.addDispatcher(event, source.pkg, method)
  528. }
  529. }
  530. }
  531. ts.forEachChild(node, visit)
  532. }
  533. visit(source.sourceFile)
  534. }
  535. /** Classify a receiver using assignability to the repository's actual event API types. */
  536. private receiverKind(receiver: ts.Expression): EventReceiverKind | undefined {
  537. const type = this.project.checker.getTypeAtLocation(receiver)
  538. if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never)) return undefined
  539. if (this.project.checker.isTypeAssignableTo(type, this.eventsServiceType)) return 'events-service'
  540. if (this.project.checker.isTypeAssignableTo(type, this.contextType)) return 'context'
  541. if (this.project.checker.isTypeAssignableTo(type, this.agentDispatchType)) return 'agent-dispatch'
  542. return undefined
  543. }
  544. /** Resolve the event-name argument for Context and fused agent dispatch calls. */
  545. private eventNamesFromCall(call: ts.CallExpression, receiverKind: Exclude<EventReceiverKind, 'events-service'>): Set<string> {
  546. const candidates = receiverKind === 'context' ? call.arguments.slice(0, 2) : call.arguments.slice(0, 1)
  547. for (const candidate of candidates) {
  548. const values = this.finiteStringValues(candidate)
  549. if (values) return values
  550. }
  551. return new Set()
  552. }
  553. /** Recover the event slot from the argument array handed to EventsService.dispatch(). */
  554. private eventNamesFromArgumentList(expression: ts.Expression, seen: Set<ts.Node>): Set<string> {
  555. const current = unwrapExpression(expression)
  556. if (seen.has(current)) return new Set()
  557. seen.add(current)
  558. if (ts.isArrayLiteralExpression(current)) {
  559. for (const element of current.elements.slice(0, 2)) {
  560. if (ts.isOmittedExpression(element) || ts.isSpreadElement(element)) continue
  561. const values = this.finiteStringValues(element)
  562. if (values) return values
  563. }
  564. return new Set()
  565. }
  566. if (ts.isConditionalExpression(current)) {
  567. return unionSets(
  568. this.eventNamesFromArgumentList(current.whenTrue, new Set(seen)),
  569. this.eventNamesFromArgumentList(current.whenFalse, new Set(seen)),
  570. )
  571. }
  572. if (!ts.isIdentifier(current)) return new Set()
  573. const symbol = this.project.checker.getSymbolAtLocation(current)
  574. if (!symbol) return new Set()
  575. const events = new Set<string>()
  576. for (const declaration of symbol.declarations ?? []) {
  577. if (ts.isVariableDeclaration(declaration) && declaration.initializer && isConstDeclaration(declaration)) {
  578. addAll(events, this.eventNamesFromArgumentList(declaration.initializer, new Set(seen)))
  579. } else if (ts.isParameter(declaration)) {
  580. addAll(events, this.eventNamesFromParameter(declaration, seen))
  581. }
  582. }
  583. return events
  584. }
  585. /** Follow a non-exported local helper parameter back to every resolved call site. */
  586. private eventNamesFromParameter(parameter: ts.ParameterDeclaration, seen: Set<ts.Node>): Set<string> {
  587. const owner = parameter.parent
  588. if (!ts.isFunctionDeclaration(owner) || hasExportModifier(owner)) return new Set()
  589. const index = owner.parameters.indexOf(parameter)
  590. if (index < 0) return new Set()
  591. const events = new Set<string>()
  592. for (const call of this.callSites.get(owner) ?? []) {
  593. const argument = call.arguments[index]
  594. if (argument) addAll(events, this.eventNamesFromArgumentList(argument, new Set(seen)))
  595. }
  596. return events
  597. }
  598. /** Return a finite string-literal value set, rejecting widened and generic strings. */
  599. private finiteStringValues(expression: ts.Expression): Set<string> | undefined {
  600. const current = unwrapExpression(expression)
  601. if (ts.isStringLiteralLike(current)) return new Set([current.text])
  602. if (this.isForwardedAgentEventParameter(current)) return undefined
  603. return finiteStringTypeValues(this.project.checker.getTypeAtLocation(current))
  604. }
  605. /** Reject the contextual parameter inside the AgentEventDispatch forwarding object. */
  606. private isForwardedAgentEventParameter(expression: ts.Expression): boolean {
  607. if (!ts.isIdentifier(expression)) return false
  608. const declarations = this.project.checker.getSymbolAtLocation(expression)?.declarations ?? []
  609. return declarations.some((declaration) => {
  610. if (!ts.isParameter(declaration)) return false
  611. const method = declaration.parent
  612. if (!ts.isMethodDeclaration(method) || !ts.isObjectLiteralExpression(method.parent)) return false
  613. const contextualType = this.project.checker.getContextualType(method.parent)
  614. return contextualType !== undefined
  615. && this.project.checker.isTypeAssignableTo(contextualType, this.agentDispatchType)
  616. })
  617. }
  618. /** Get or create one relation row. */
  619. private ensure(event: string): EventRelation {
  620. const existing = this.relations.get(event)
  621. if (existing) return existing
  622. const relation = { dispatchers: new Map<string, Set<string>>(), listeners: new Set<string>() }
  623. this.relations.set(event, relation)
  624. return relation
  625. }
  626. /** Add one dispatcher method without duplicating package/method labels. */
  627. private addDispatcher(event: string, pkg: string, method: string): void {
  628. const relation = this.ensure(event)
  629. const methods = relation.dispatchers.get(pkg) ?? new Set<string>()
  630. methods.add(method)
  631. relation.dispatchers.set(pkg, methods)
  632. }
  633. }
  634. /** Peel syntax-only wrappers that do not change an expression's runtime value. */
  635. function unwrapExpression(expression: ts.Expression): ts.Expression {
  636. let current = expression
  637. while (
  638. ts.isParenthesizedExpression(current)
  639. || ts.isAsExpression(current)
  640. || ts.isTypeAssertionExpression(current)
  641. || ts.isNonNullExpression(current)
  642. || ts.isSatisfiesExpression(current)
  643. ) {
  644. current = current.expression
  645. }
  646. return current
  647. }
  648. /** Return every value only when a type is a closed string-literal union. */
  649. function finiteStringTypeValues(type: ts.Type): Set<string> | undefined {
  650. if (type.flags & ts.TypeFlags.StringLiteral) {
  651. return new Set([(type as ts.StringLiteralType).value])
  652. }
  653. if (type.flags & ts.TypeFlags.Never) return new Set()
  654. if (!type.isUnion()) return undefined
  655. const values = new Set<string>()
  656. for (const member of type.types) {
  657. const memberValues = finiteStringTypeValues(member)
  658. if (!memberValues) return undefined
  659. addAll(values, memberValues)
  660. }
  661. return values
  662. }
  663. /** Return whether a variable declaration belongs to a const declaration list. */
  664. function isConstDeclaration(declaration: ts.VariableDeclaration): boolean {
  665. return (declaration.parent.flags & ts.NodeFlags.Const) !== 0
  666. }
  667. /** Return whether a declaration is visible to callers outside its source module. */
  668. function hasExportModifier(node: ts.Node): boolean {
  669. return ts.canHaveModifiers(node) && (ts.getModifiers(node)?.some((modifier) => {
  670. return modifier.kind === ts.SyntaxKind.ExportKeyword || modifier.kind === ts.SyntaxKind.DefaultKeyword
  671. }) ?? false)
  672. }
  673. /** Add every member of source to target. */
  674. function addAll<T>(target: Set<T>, source: ReadonlySet<T>): void {
  675. for (const value of source) target.add(value)
  676. }
  677. /** Return the union of two sets without mutating either input. */
  678. function unionSets<T>(left: ReadonlySet<T>, right: ReadonlySet<T>): Set<T> {
  679. const out = new Set(left)
  680. addAll(out, right)
  681. return out
  682. }
  683. function collectEventRelations(): Map<string, EventRelation> {
  684. const project = new TypeScriptProject(root)
  685. const sources = project.sourceFiles().flatMap((sourceFile): PackageSource[] => {
  686. const rel = project.relativePath(sourceFile)
  687. const match = /^packages\/[^/]+\/([^/]+)\/src\/.+\.ts$/.exec(rel)
  688. return match?.[1] ? [{ rel, pkg: match[1], sourceFile }] : []
  689. }).sort((left, right) => left.rel.localeCompare(right.rel))
  690. return new EventRelationCollector(project, sources).collect()
  691. }
  692. function relationPackages(map: Map<string, Set<string>>, pkgsByShort: Map<string, Pkg>): string {
  693. if (map.size === 0) return '-'
  694. return [...map.entries()]
  695. .sort(([a], [b]) => a.localeCompare(b))
  696. .map(([pkg, methods]) => `${pkgLink(pkgsByShort.get(pkg), pkg)} (${[...methods].sort().map(m => `\`${m}\``).join(', ')})`)
  697. .join(', ')
  698. }
  699. function listenerPackages(listeners: Set<string>, pkgsByShort: Map<string, Pkg>): string {
  700. if (listeners.size === 0) return '-'
  701. return [...listeners].sort().map(pkg => pkgLink(pkgsByShort.get(pkg), pkg)).join(', ')
  702. }
  703. function renderEventRelations(pkgs: Pkg[]): string {
  704. const events = collectEvents()
  705. const relations = collectEventRelations()
  706. const pkgsByShort = new Map(pkgs.map(pkg => [pkg.short, pkg]))
  707. const maintenance = 'generated: Cordis event declarations and producer/listener edges are resolved from the repository TypeScript Program'
  708. const lines = generatedHeader('Event Producer And Consumer Matrix')
  709. lines.push(
  710. '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.',
  711. '',
  712. '| Event | Mode | Declared in | Dispatchers | Listeners |',
  713. '| --- | --- | --- | --- | --- |',
  714. )
  715. for (const event of [...events].sort((a, b) => a.name.localeCompare(b.name))) {
  716. const relation = relations.get(event.name) ?? { dispatchers: new Map<string, Set<string>>(), listeners: new Set<string>() }
  717. lines.push(`| \`${event.name}\` | \`${event.mode}\` | ${sourceLink(event.source)} | ${relationPackages(relation.dispatchers, pkgsByShort)} | ${listenerPackages(relation.listeners, pkgsByShort)} |`)
  718. }
  719. // Every declared event needs a dispatcher: zero means dead vocabulary or an
  720. // unrecognized semantic dispatch shape. Listener-free extension points remain valid.
  721. const undispatched = [...events]
  722. .filter(event => (relations.get(event.name)?.dispatchers.size ?? 0) === 0)
  723. .map(event => event.name)
  724. .sort()
  725. if (undispatched.length > 0) {
  726. throw new Error(
  727. `event-producer-consumer matrix: no dispatcher found for declared event${undispatched.length > 1 ? 's' : ''} `
  728. + `${undispatched.map(name => `"${name}"`).join(', ')} — dead vocabulary, or a dispatch shape the semantic scan misses `
  729. + '(teach scripts/gen-doc-graphs.ts the shape)',
  730. )
  731. }
  732. const declared = new Set(events.map(event => event.name))
  733. const extra = [...relations.keys()].filter(event => !declared.has(event)).sort()
  734. if (extra.length > 0) {
  735. lines.push('', '## Non-harness or undeclared event strings seen in package source', '', '| Event string | Dispatchers | Listeners |', '| --- | --- | --- |')
  736. for (const event of extra) {
  737. const relation = relations.get(event)
  738. if (!relation) continue
  739. lines.push(`| \`${event}\` | ${relationPackages(relation.dispatchers, pkgsByShort)} | ${listenerPackages(relation.listeners, pkgsByShort)} |`)
  740. }
  741. }
  742. lines.push('', ...maintenanceFooter(maintenance))
  743. return lines.join('\n')
  744. }
  745. function renderLifecycle(): string {
  746. const maintenance = 'curated Mermaid sequence; exact event signatures live in the generated Cordis catalog'
  747. return [
  748. ...generatedHeader('Agent Turn And Step Lifecycle'),
  749. '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/*`.',
  750. '',
  751. '```mermaid',
  752. 'sequenceDiagram',
  753. ' participant User',
  754. ' participant Agent',
  755. ' participant Driver',
  756. ' participant Hooks as hook listeners',
  757. ' participant Prompt as ctx.systemPrompt',
  758. ' participant LLM as ctx.llm',
  759. ' participant Tools as ctx.tools',
  760. ' participant Session',
  761. ' participant Persistence',
  762. ' participant SDK as UI or SDK listener',
  763. ' User->>Agent: send(content)',
  764. ` Agent-->>SDK: ${mermaidCode('agent/queued')}`,
  765. ' Agent->>Driver: queued work wakes driver',
  766. ` Driver-->>SDK: ${mermaidCode('agent/status')} running`,
  767. ` Driver->>Session: ${mermaidCode('turn/start')}`,
  768. ` Driver->>Hooks: ${mermaidCode('agent/prompt-submit')} waterfall`,
  769. ' Hooks-->>Driver: allow, block, or add context',
  770. ` Driver->>Session: ${mermaidCode('user/message')} or rejected ${mermaidCode('turn/end')}`,
  771. ` Driver->>Prompt: ${mermaidCode('system-prompt/assemble')} waterfall`,
  772. ` Driver-->>Driver: ${mermaidCode('agent/pre-step')} serial checkpoint`,
  773. ` Driver->>Session: ${mermaidCode('step/start')}`,
  774. ` Driver->>LLM: ${mermaidCode('agent/request')} waterfall, then ${mermaidCode('llm/stream')} waterfall`,
  775. ' LLM-->>Driver: StreamChunk*',
  776. ` Driver->>Session: ${mermaidCode('assistant/chunk')}*`,
  777. ` Session-->>SDK: ${mermaidCode('session/event')} ${mermaidCode('assistant/chunk')}*`,
  778. ` Driver->>Hooks: ${mermaidCode('agent/step-result')} waterfall`,
  779. ` Driver->>Session: ${mermaidCode('assistant/message')}`,
  780. ` Driver->>Session: ${mermaidCode('tool/call')}`,
  781. ' Driver->>Tools: execute through pre and post waterfalls',
  782. ' Tools-->>Session: tool-owned events when applicable',
  783. ` Driver->>Session: ${mermaidCode('tool/result')} and ${mermaidCode('step/end')}`,
  784. ` Driver->>Hooks: ${mermaidCode('agent/turn-continuation')} waterfall`,
  785. ` Driver->>Hooks: ${mermaidCode('agent/turn-stop')} serial terminal checkpoint`,
  786. ` Driver->>Session: ${mermaidCode('turn/end')}`,
  787. ` Driver->>Persistence: ${mermaidCode('session/flush')} parallel checkpoint`,
  788. ` Driver-->>SDK: ${mermaidCode('agent/status')} idle`,
  789. '```',
  790. '',
  791. '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.',
  792. '',
  793. ...maintenanceFooter(maintenance),
  794. ].join('\n')
  795. }
  796. function renderToolPipeline(): string {
  797. const maintenance = 'curated Mermaid flow; exact tool schemas and event signatures live in generated catalogs'
  798. return [
  799. ...generatedHeader('Tool Execution Pipeline'),
  800. '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.',
  801. '',
  802. '```mermaid',
  803. 'flowchart TD',
  804. ' model["Assistant message contains tool-call block"]',
  805. ` toolCall["Session event: ${mermaidCode('tool/call')}<br/>logged before execution"]`,
  806. ' presentCall["UI pending card<br/>presentCall(args)"]',
  807. ` pre["${mermaidCode('tools/pre-execute')} waterfall<br/>hooks, permission, sandbox"]`,
  808. ' guards["Registered monotonic guards<br/>deny or abstain; identity protected"]',
  809. ' denied["denied or approval refused<br/>tool body skipped"]',
  810. ` approval["${mermaidCode('ctx.approval')} one-shot prompt<br/>absent or unanswerable: deny"]`,
  811. ` around["${mermaidCode('tools/execute')} waterfall<br/>timeout, retry, metrics (around dispatch)"]`,
  812. ' toolBody["Registered tool execute() body"]',
  813. ` fsGate["${mermaidCode('fs/write-intent')} or ${mermaidCode('fs/edit-intent')}<br/>tool-fs mutations only"]`,
  814. ` owned["Tool-owned session events<br/>${mermaidCode('todo/write')}, ${mermaidCode('fs/observed')}, ${mermaidCode('hook/invoked')}, ${mermaidCode('hook/result')}, ${mermaidCode('tool/code-dispatch')}"]`,
  815. ` post["${mermaidCode('tools/post-execute')} waterfall<br/>accept, block, replace, add context"]`,
  816. ` final["${mermaidCode('tools/result')} synchronous notification<br/>frozen authoritative outcome"]`,
  817. ' context["Buffered additionalContexts<br/>context/message after all tool results"]',
  818. ` toolResult["Session event: ${mermaidCode('tool/result')}<br/>single model-facing outcome"]`,
  819. ' allResults["All calls in the step settled<br/>and tool/result events recorded"]',
  820. ' presentResult["UI completed card<br/>presentResult(args, result)"]',
  821. ' model --> toolCall',
  822. ' toolCall --> presentCall',
  823. ' toolCall --> pre',
  824. ' pre -->|allow| guards',
  825. ' guards -->|allow| around',
  826. ' guards -->|deny| denied',
  827. ' around --> toolBody',
  828. ' pre -->|deny| denied',
  829. ' pre -->|ask| approval',
  830. ' approval -->|allowed-once| guards',
  831. ' approval -->|rejected, cancelled, unavailable| denied',
  832. ' denied --> post',
  833. ' toolBody --> fsGate',
  834. ' fsGate --> toolBody',
  835. ' toolBody --> owned',
  836. ' toolBody --> around',
  837. ' around --> post',
  838. ' post --> final',
  839. ' final --> toolResult',
  840. ' toolResult --> presentResult',
  841. ' toolResult --> allResults',
  842. ' allResults --> context',
  843. '```',
  844. '',
  845. '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.',
  846. '',
  847. ...maintenanceFooter(maintenance),
  848. ].join('\n')
  849. }
  850. function renderSnapshotReplay(): string {
  851. const maintenance = 'curated Mermaid sequence based on the snapshot test harness'
  852. return [
  853. ...generatedHeader('ACP Snapshot Replay'),
  854. '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.',
  855. '',
  856. '```mermaid',
  857. 'sequenceDiagram',
  858. ' participant Recorder as Real API recording',
  859. ' participant Fixture as snapshot fixture',
  860. ' participant Workspace',
  861. ' participant Replay as llm-replay adapter',
  862. ' participant ACP as acp-agent subprocess',
  863. ' participant Golden as stdout golden',
  864. ' Recorder->>Fixture: session.jsonl + workspace inputs',
  865. ' Fixture->>Workspace: seed files and hook configs',
  866. ' Fixture->>Replay: recorded StreamChunk script',
  867. ` Replay->>ACP: deterministic ${mermaidCode('llm/stream')} chunks`,
  868. ' ACP->>Workspace: bash, fs, and hook side effects',
  869. ' ACP->>Golden: normalized sessionUpdate stream',
  870. ' Golden-->>ACP: diff must be empty',
  871. '```',
  872. '',
  873. '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.',
  874. '',
  875. ...maintenanceFooter(maintenance),
  876. ].join('\n')
  877. }
  878. function renderDocs(): GraphDoc[] {
  879. const pkgs = collectPackageGraph(root, GROUP_ORDER, 'gen-doc-graphs')
  880. const docs: GraphDoc[] = [
  881. { rel: 'docs/capability-seams.md', content: renderCapabilitySeams(pkgs) },
  882. ...APP_EXAMPLES.map(example => ({ rel: example.rel, content: renderAppComposition(example) })),
  883. { rel: 'docs/event-producer-consumer.md', content: renderEventRelations(pkgs) },
  884. { rel: 'docs/agent-lifecycle.md', content: renderLifecycle() },
  885. { rel: 'docs/tool-execution-pipeline.md', content: renderToolPipeline() },
  886. { rel: 'packages/ui/acp/snapshot-replay.md', content: renderSnapshotReplay() },
  887. ]
  888. docs.unshift({ rel: 'docs/graph-atlas.md', content: renderIndex(docs) })
  889. return docs
  890. }
  891. function renderIndex(docs: GraphDoc[]): string {
  892. const labels: Record<string, string> = {
  893. 'docs/capability-seams.md': 'capability seams and core services',
  894. 'examples/echo-agent/composition.md': 'echo-agent app composition',
  895. 'examples/coding-agent/composition.md': 'coding-agent app composition',
  896. 'examples/cordis-agent/composition.md': 'cordis-agent app composition',
  897. 'examples/acp-agent/composition.md': 'acp-agent app composition',
  898. 'docs/event-producer-consumer.md': 'event producer/consumer matrix',
  899. 'docs/agent-lifecycle.md': 'agent turn and step lifecycle',
  900. 'docs/tool-execution-pipeline.md': 'tool execution pipeline',
  901. 'packages/ui/acp/snapshot-replay.md': 'ACP snapshot replay',
  902. }
  903. const modes: Record<string, string> = {
  904. 'docs/capability-seams.md': 'hybrid generated',
  905. 'examples/echo-agent/composition.md': 'hybrid generated',
  906. 'examples/coding-agent/composition.md': 'hybrid generated',
  907. 'examples/cordis-agent/composition.md': 'hybrid generated',
  908. 'examples/acp-agent/composition.md': 'hybrid generated',
  909. 'docs/event-producer-consumer.md': 'hybrid generated',
  910. 'docs/agent-lifecycle.md': 'curated',
  911. 'docs/tool-execution-pipeline.md': 'curated',
  912. 'packages/ui/acp/snapshot-replay.md': 'curated',
  913. }
  914. const rows = [
  915. '| [module dependency graph](module-graph.md) | `generated` |',
  916. '| [tool schema catalog and package map](tool-catalog.md) | `generated` |',
  917. ...docs.map((doc) => {
  918. const link = graphIndexLink(doc.rel)
  919. return `| [${labels[doc.rel] ?? link}](${link}) | \`${modes[doc.rel] ?? 'generated'}\` |`
  920. }),
  921. ]
  922. const maintenance = 'mixed: each linked page declares generated, hybrid, or curated mode'
  923. return [
  924. ...generatedHeader('Documentation Graph Index'),
  925. '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).',
  926. '',
  927. 'The process decision behind this index is recorded in [the documentation graph RFC](rfc/implemented/process/2026-07-03-documentation-graph-atlas.md).',
  928. '',
  929. '| Graph | Mode |',
  930. '| --- | --- |',
  931. ...rows,
  932. '',
  933. 'Regenerate with `pnpm run gen-doc-graphs`; verify freshness with `pnpm run verify-doc-graphs`.',
  934. '',
  935. ...maintenanceFooter(maintenance),
  936. ].join('\n')
  937. }
  938. function main(): void {
  939. const docs = renderDocs()
  940. if (process.argv.includes('--check')) {
  941. const stale: string[] = []
  942. for (const doc of docs) {
  943. const abs = resolve(root, doc.rel)
  944. const committed = existsSync(abs) ? readFileSync(abs, 'utf8') : null
  945. if (committed !== doc.content) stale.push(doc.rel)
  946. }
  947. if (stale.length === 0) {
  948. console.log(`gen-doc-graphs: ${docs.length} graph doc(s) are up to date.`)
  949. return
  950. }
  951. console.error(`gen-doc-graphs: stale graph doc(s): ${stale.join(', ')}. Run \`pnpm run gen-doc-graphs\` and commit the result.`)
  952. process.exit(1)
  953. }
  954. for (const doc of docs) {
  955. mkdirSync(dirname(resolve(root, doc.rel)), { recursive: true })
  956. writeFileSync(resolve(root, doc.rel), doc.content)
  957. }
  958. console.log(`gen-doc-graphs: wrote ${docs.length} graph doc(s).`)
  959. }
  960. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  961. main()
  962. }