gen-doc-graphs.ts 44 KB

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