gen-doc-graphs.ts 43 KB

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