gen-doc-graphs.ts 44 KB

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