gen-doc-graphs.ts 44 KB

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