gen-doc-graphs.ts 44 KB

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