gen-doc-graphs.ts 45 KB

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