gen-doc-graphs.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  1. /**
  2. * Generate (and verify) the relationship-diagram docs.
  3. *
  4. * This is the relationship layer above the existing catalogs:
  5. * - module-graph.md answers "which packages depend on which packages?"
  6. * - cordis-catalog/ answers "which events and services exist?"
  7. * - tool-catalog.md answers "which tools does the model see?"
  8. * - generated relationship diagrams answer "how do those pieces fit together?"
  9. *
  10. * Generated pages discover the enumerable facts from source. Hybrid pages use
  11. * discovered inventory plus small manifests for policy that source cannot infer
  12. * (for example, whether a package is an implementation or consumer in a seam).
  13. * Curated pages are still emitted here so the graph docs are one regenerated unit,
  14. * but their diagrams intentionally explain flow and ownership rather than
  15. * pretending to enumerate every source edge.
  16. *
  17. * `tsx scripts/gen-doc-graphs.ts` -> write generated diagram docs
  18. * `tsx scripts/gen-doc-graphs.ts --check` -> exit 1 if any file is stale
  19. */
  20. import { existsSync, globSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
  21. import { dirname, relative, resolve } from 'node:path'
  22. import ts from 'typescript'
  23. import { collectEvents, collectServices } from './gen-cordis-catalog.ts'
  24. const root = resolve(import.meta.dirname, '..')
  25. const SCOPE = '@deepseek-ai/dsh-'
  26. interface PkgJson {
  27. name: string
  28. peerDependencies?: Record<string, string>
  29. }
  30. interface Pkg {
  31. short: string
  32. name: string
  33. group: string
  34. rel: string
  35. deps: string[]
  36. }
  37. interface GraphDoc {
  38. rel: string
  39. content: string
  40. }
  41. interface ServiceRole {
  42. key: string
  43. pkg: string
  44. title: string
  45. mode: 'core' | 'seam' | 'bundle'
  46. implementations?: string[]
  47. consumers?: string[]
  48. companions?: string[]
  49. note: string
  50. }
  51. interface ExamplePlugin {
  52. id: string
  53. name: string
  54. }
  55. interface EventRelation {
  56. dispatchers: Map<string, Set<string>>
  57. listeners: Set<string>
  58. }
  59. const GROUP_ORDER = [
  60. 'util',
  61. 'llm',
  62. 'core',
  63. 'bash',
  64. 'fs',
  65. 'compact',
  66. 'subagent',
  67. 'web',
  68. 'todo',
  69. 'cordis',
  70. 'hooks',
  71. 'session-persistence',
  72. 'support',
  73. 'ui',
  74. ]
  75. const SERVICE_ROLES: ServiceRole[] = [
  76. {
  77. key: 'llm',
  78. pkg: 'llm',
  79. title: 'LLM adapter registry',
  80. mode: 'seam',
  81. implementations: ['llm-deepseek', 'llm-pi-ai', 'llm-replay'],
  82. consumers: ['agent-loop', 'compact-basic'],
  83. note: 'Adapters register provider implementations; the loop and compaction call the provider-neutral stream service.',
  84. },
  85. {
  86. key: 'sessions',
  87. pkg: 'session',
  88. title: 'In-memory session store',
  89. mode: 'core',
  90. consumers: ['agent-loop', 'agent', 'session-persistence', 'subagent-inprocess', 'invariants'],
  91. note: 'Owns append-only Session instances and emits the durable session event feed.',
  92. },
  93. {
  94. key: 'sessionPersistence',
  95. pkg: 'session-persistence',
  96. title: 'Durable session persistence seam',
  97. mode: 'seam',
  98. implementations: ['session-persistence-jsonl', 'session-persistence-sqlite'],
  99. consumers: ['agent-loop', 'acp'],
  100. note: 'Backends persist the same SessionEvent vocabulary; apps choose a backend at composition time.',
  101. },
  102. {
  103. key: 'systemPrompt',
  104. pkg: 'system-prompt',
  105. title: 'System prompt assembly registry',
  106. mode: 'core',
  107. consumers: ['agent-loop', 'tools', 'tool-fs', 'tool-web'],
  108. note: 'Collects prompt sections and model-facing tool schemas for each step.',
  109. },
  110. {
  111. key: 'tools',
  112. pkg: 'tools',
  113. title: 'Tool registry and execution waterfall',
  114. mode: 'core',
  115. consumers: ['agent-loop', 'tool-bash', 'tool-cordis', 'tool-fs', 'tool-subagent', 'tool-todo', 'tool-web', 'acp'],
  116. note: 'Registers tool definitions, exposes schemas to the prompt, and routes calls through tools/pre-execute and tools/post-execute.',
  117. },
  118. {
  119. key: 'agents',
  120. pkg: 'agent',
  121. title: 'Agent registry',
  122. mode: 'core',
  123. consumers: ['agent-loop', 'acp', 'subagent-inprocess', 'stdio-agent', 'invariants'],
  124. note: 'Owns live Agent handles and the create/resume factory seam.',
  125. },
  126. {
  127. key: 'agentLoop',
  128. pkg: 'agent-loop',
  129. title: 'Concrete loop driver',
  130. mode: 'bundle',
  131. consumers: ['agent-core'],
  132. note: 'The one concrete loop plugin; extension packages depend on dsh-agent events and services, not on this package.',
  133. },
  134. {
  135. key: 'bash',
  136. pkg: 'bash',
  137. title: 'Bash executor seam',
  138. mode: 'seam',
  139. implementations: ['bash-local'],
  140. consumers: ['tool-bash', 'hooks-claude', 'hooks-codex'],
  141. note: 'The model-facing bash tools and hook bridges consume this seam; sandboxed or remote executors can replace bash-local.',
  142. },
  143. {
  144. key: 'codeRuntime',
  145. pkg: 'code-runtime',
  146. title: 'Code-execution seam',
  147. mode: 'seam',
  148. implementations: ['code-runtime-worker'],
  149. consumers: [],
  150. note: 'Runs one model-written program against host-provided async bindings; backends differ by substrate and language (the Code Mode RFC specifies the worker-thread backend and the tool-registry consumer).',
  151. },
  152. {
  153. key: 'fs',
  154. pkg: 'fs',
  155. title: 'Filesystem provider seam',
  156. mode: 'seam',
  157. implementations: ['fs-local'],
  158. consumers: ['tool-fs'],
  159. companions: ['fs-policy'],
  160. note: 'tool-fs executes read/write/edit through ctx.fs; fs-policy contributes observed-state checks through the fs/* event gate.',
  161. },
  162. {
  163. key: 'compact',
  164. pkg: 'compact',
  165. title: 'Compaction seam',
  166. mode: 'seam',
  167. implementations: ['compact-basic'],
  168. consumers: ['compact-basic'],
  169. note: 'The basic backend currently consumes the pre-step event directly; a model-facing compact tool remains deferred.',
  170. },
  171. {
  172. key: 'subagents',
  173. pkg: 'subagent',
  174. title: 'Subagent provider registry',
  175. mode: 'seam',
  176. implementations: ['subagent-spawn', 'subagent-fork', 'subagent-acp', 'subagent-mock'],
  177. consumers: ['tool-subagent'],
  178. note: 'Providers implement transports; tool-subagent exposes one configured provider as a model-facing tool name.',
  179. },
  180. {
  181. key: 'web',
  182. pkg: 'web',
  183. title: 'Web access provider registry',
  184. mode: 'seam',
  185. implementations: ['web-search-exa', 'web-search-perplexity', 'web-search-deepseek', 'web-fetch-local'],
  186. consumers: ['tool-web'],
  187. note: 'Search and fetch providers register into one ctx.web seam; tool-web owns the stable model-facing names.',
  188. },
  189. ]
  190. const DYNAMIC_EVENT_DISPATCHERS: Array<{ event: string; pkg: string; method: string }> = [
  191. // Subagent lifecycle events intentionally bypass ctx.emit and call
  192. // ctx.events.dispatch directly so one throwing listener cannot starve later
  193. // listeners or strand an already-started child run.
  194. { event: 'subagent/start', pkg: 'subagent', method: 'events.dispatch' },
  195. { event: 'subagent/end', pkg: 'subagent', method: 'events.dispatch' },
  196. ]
  197. function generatedHeader(title: string): string[] {
  198. return [
  199. '<!-- Generated by scripts/gen-doc-graphs.ts - do not edit by hand.',
  200. ' Run `pnpm run gen-doc-graphs` to regenerate. -->',
  201. '',
  202. `# ${title}`,
  203. '',
  204. ]
  205. }
  206. function maintenanceFooter(source: string): string[] {
  207. return [`Maintenance mode: ${source}.`, '']
  208. }
  209. function graphIndexLink(rel: string): string {
  210. return relative('docs', rel).replaceAll('\\', '/')
  211. }
  212. function linkFromDoc(docRel: string, targetRel: string): string {
  213. return relative(dirname(docRel), targetRel).replaceAll('\\', '/')
  214. }
  215. function collectPackages(): Pkg[] {
  216. const pkgs: Pkg[] = []
  217. for (const rel of globSync('packages/*/*/package.json', { cwd: root }).sort()) {
  218. const json = JSON.parse(readFileSync(resolve(root, rel), 'utf8')) as PkgJson
  219. if (!json.name.startsWith(SCOPE)) continue
  220. const [, group, leaf] = rel.split('/')
  221. if (group === undefined || leaf === undefined) throw new Error(`gen-doc-graphs: unexpected package path ${rel}`)
  222. const deps = Object.keys(json.peerDependencies ?? {})
  223. .filter(dep => dep.startsWith(SCOPE))
  224. .map(dep => dep.slice(SCOPE.length))
  225. .sort()
  226. pkgs.push({
  227. short: json.name.slice(SCOPE.length),
  228. name: json.name,
  229. group,
  230. rel: dirname(rel),
  231. deps,
  232. })
  233. }
  234. return topoSort(pkgs)
  235. }
  236. function topoSort(pkgs: Pkg[]): Pkg[] {
  237. const remaining = new Map(pkgs.map(p => [p.short, p]))
  238. const placed = new Set<string>()
  239. const out: Pkg[] = []
  240. while (remaining.size > 0) {
  241. const ready = [...remaining.values()]
  242. .filter(pkg => pkg.deps.every(dep => placed.has(dep)))
  243. .sort(comparePackages)
  244. if (ready.length === 0) throw new Error(`gen-doc-graphs: dependency cycle among ${[...remaining.keys()].join(', ')}`)
  245. for (const pkg of ready) {
  246. out.push(pkg)
  247. placed.add(pkg.short)
  248. remaining.delete(pkg.short)
  249. }
  250. }
  251. return out
  252. }
  253. function comparePackages(a: Pkg, b: Pkg): number {
  254. const groupA = GROUP_ORDER.indexOf(a.group)
  255. const groupB = GROUP_ORDER.indexOf(b.group)
  256. const normA = groupA === -1 ? Number.MAX_SAFE_INTEGER : groupA
  257. const normB = groupB === -1 ? Number.MAX_SAFE_INTEGER : groupB
  258. return normA - normB || a.group.localeCompare(b.group) || a.short.localeCompare(b.short)
  259. }
  260. function nodeId(prefix: string, value: string): string {
  261. return `${prefix}_${value.replace(/[^a-zA-Z0-9_]/g, '_')}`
  262. }
  263. function escLabel(value: string): string {
  264. return value.replace(/"/g, '\\"')
  265. }
  266. function mermaidCode(value: string): string {
  267. return `<code>${value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</code>`
  268. }
  269. function repoLink(path: string, label: string, up = '..'): string {
  270. return `[${label}](${up}/${path})`
  271. }
  272. function sourceLink(source: string, up = '..'): string {
  273. return repoLink(source.split(':')[0] ?? source, `\`${source}\``, up)
  274. }
  275. function pkgLink(pkg: Pkg | undefined, fallback: string, up = '..'): string {
  276. return pkg ? repoLink(pkg.rel, `\`${pkg.short}\``, up) : `\`${fallback}\``
  277. }
  278. function pkgList(names: string[] | undefined, pkgsByShort: Map<string, Pkg>): string {
  279. if (!names || names.length === 0) return '-'
  280. return names.map(name => pkgLink(pkgsByShort.get(name), name)).join(', ')
  281. }
  282. function tableCell(value: string): string {
  283. return value.replace(/\|/g, '\\|').replace(/\n/g, '<br>')
  284. }
  285. function assertServiceRolesComplete(): void {
  286. const discovered = new Set(collectServices().map(service => service.key))
  287. const classified = new Set(SERVICE_ROLES.map(role => role.key))
  288. const missing = [...discovered].filter(key => !classified.has(key)).sort()
  289. const stale = [...classified].filter(key => !discovered.has(key)).sort()
  290. if (missing.length || stale.length) {
  291. throw new Error([
  292. missing.length ? `missing service role classification: ${missing.join(', ')}` : '',
  293. stale.length ? `stale service role classification: ${stale.join(', ')}` : '',
  294. ].filter(Boolean).join('; '))
  295. }
  296. }
  297. function renderCapabilitySeams(pkgs: Pkg[]): string {
  298. assertServiceRolesComplete()
  299. const pkgsByShort = new Map(pkgs.map(pkg => [pkg.short, pkg]))
  300. 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'
  301. const nodes = new Map<string, string>()
  302. const edges = new Set<string>()
  303. const companionEdges = new Set<string>()
  304. const addNode = (id: string, label: string): void => {
  305. if (!nodes.has(id)) nodes.set(id, ` ${id}["${escLabel(label)}"]`)
  306. }
  307. const addEdge = (from: string, to: string): void => { edges.add(` ${from} --> ${to}`) }
  308. const lines = generatedHeader('Capability Seams And Core Services')
  309. lines.push(
  310. '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.',
  311. '',
  312. '```mermaid',
  313. 'flowchart LR',
  314. )
  315. for (const role of SERVICE_ROLES) {
  316. const svc = nodeId('svc', role.key)
  317. const owner = nodeId('pkg', role.pkg)
  318. addNode(owner, role.pkg)
  319. addNode(svc, `ctx.${role.key}<br/>${role.title}`)
  320. addEdge(owner, svc)
  321. for (const impl of role.implementations ?? []) {
  322. addNode(nodeId('pkg', impl), impl)
  323. addEdge(nodeId('pkg', impl), svc)
  324. }
  325. for (const consumer of role.consumers ?? []) {
  326. addNode(nodeId('pkg', consumer), consumer)
  327. addEdge(svc, nodeId('pkg', consumer))
  328. }
  329. for (const companion of role.companions ?? []) {
  330. addNode(nodeId('pkg', companion), companion)
  331. companionEdges.add(` ${svc} -. event gate .-> ${nodeId('pkg', companion)}`)
  332. }
  333. }
  334. lines.push(...nodes.values(), ...[...edges].sort(), ...[...companionEdges].sort())
  335. lines.push('```', '', '| ctx key | Role | Owner | Implementations | Direct consumers | Companion plugins | Note |', '| --- | --- | --- | --- | --- | --- | --- |')
  336. for (const role of SERVICE_ROLES) {
  337. 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)} |`)
  338. }
  339. lines.push('', ...maintenanceFooter(maintenance))
  340. return lines.join('\n')
  341. }
  342. function parseExampleCordis(rel: string): ExamplePlugin[] {
  343. const text = readFileSync(resolve(root, rel), 'utf8')
  344. const plugins: ExamplePlugin[] = []
  345. let current: { id: string; name?: string } | null = null
  346. const flush = (): void => {
  347. if (current?.name) plugins.push({ id: current.id, name: current.name })
  348. }
  349. for (const line of text.split('\n')) {
  350. const id = /^-\s+id:\s+(.+?)\s*$/.exec(line)
  351. if (id?.[1] !== undefined) {
  352. flush()
  353. current = { id: stripYamlScalar(id[1]) }
  354. continue
  355. }
  356. const name = /^\s+name:\s+(.+?)\s*$/.exec(line)
  357. if (name?.[1] !== undefined && current) current.name = stripYamlScalar(name[1])
  358. }
  359. flush()
  360. return plugins
  361. }
  362. function stripYamlScalar(value: string): string {
  363. return value.trim().replace(/^['"]|['"]$/g, '')
  364. }
  365. const APP_EXAMPLES = [
  366. {
  367. id: 'echo',
  368. rel: 'examples/echo-agent/composition.md',
  369. title: 'Echo Agent App Composition',
  370. label: 'examples/echo-agent',
  371. config: 'examples/echo-agent/cordis.yml',
  372. 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.',
  373. },
  374. {
  375. id: 'coding',
  376. rel: 'examples/coding-agent/composition.md',
  377. title: 'Coding Agent App Composition',
  378. label: 'examples/coding-agent',
  379. config: 'examples/coding-agent/cordis.yml',
  380. 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.',
  381. },
  382. {
  383. id: 'cordis',
  384. rel: 'examples/cordis-agent/composition.md',
  385. title: 'Cordis Agent App Composition',
  386. label: 'examples/cordis-agent',
  387. config: 'examples/cordis-agent/cordis.yml',
  388. 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.',
  389. },
  390. {
  391. id: 'acp',
  392. rel: 'examples/acp-agent/composition.md',
  393. title: 'ACP Agent App Composition',
  394. label: 'examples/acp-agent',
  395. config: 'examples/acp-agent/cordis.yml',
  396. 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.',
  397. },
  398. ]
  399. type AppExample = typeof APP_EXAMPLES[number]
  400. function renderAppExpansion(lines: string[], appNode: string, pluginName: string): void {
  401. const agentCore = nodeId('bundle', 'agent_core')
  402. const jsonl = nodeId('bundle', 'jsonl')
  403. lines.push(` ${appNode} --> ${agentCore}["@deepseek-ai/dsh-agent-core"]`)
  404. lines.push(` ${appNode} --> ${jsonl}["@deepseek-ai/dsh-session-persistence-jsonl"]`)
  405. if (pluginName === '@deepseek-ai/dsh-stdio-agent') {
  406. lines.push(` ${appNode} --> ${nodeId('frontdoor', 'stdio')}["readline UI<br/>console logger<br/>pre-created main agent"]`)
  407. } else if (pluginName === '@deepseek-ai/dsh-acp-agent') {
  408. lines.push(` ${appNode} --> ${nodeId('frontdoor', 'acp')}["@deepseek-ai/dsh-acp<br/>JSON-RPC stdio bridge<br/>sessions created by client"]`)
  409. }
  410. lines.push(
  411. ` ${agentCore} --> ${nodeId('spine', 'llm')}["ctx.llm"]`,
  412. ` ${agentCore} --> ${nodeId('spine', 'sessions')}["ctx.sessions"]`,
  413. ` ${agentCore} --> ${nodeId('spine', 'tools')}["ctx.tools + tool-bash"]`,
  414. ` ${agentCore} --> ${nodeId('spine', 'loop')}["ctx.agents + ctx.agentLoop"]`,
  415. )
  416. }
  417. function renderAppComposition(example: AppExample): string {
  418. const plugins = parseExampleCordis(example.config)
  419. const maintenance = 'hybrid: the leaf plugin list is parsed from its `cordis.yml`; app package expansion is curated from package source'
  420. const lines = generatedHeader(example.title)
  421. lines.push(
  422. example.summary,
  423. '',
  424. '```mermaid',
  425. 'flowchart LR',
  426. ` cfg["${escLabel(example.label)}<br/>cordis.yml"]`,
  427. )
  428. for (const plugin of plugins) {
  429. const pluginNode = nodeId(`plugin_${example.id}`, plugin.id)
  430. lines.push(` ${pluginNode}["${escLabel(plugin.id)}<br/>${escLabel(plugin.name)}"]`)
  431. lines.push(` cfg --> ${pluginNode}`)
  432. if (plugin.name === '@deepseek-ai/dsh-stdio-agent' || plugin.name === '@deepseek-ai/dsh-acp-agent') {
  433. renderAppExpansion(lines, pluginNode, plugin.name)
  434. }
  435. }
  436. lines.push(
  437. '```',
  438. '',
  439. '| Plugin id | Package / module |',
  440. '| --- | --- |',
  441. ...plugins.map(plugin => `| \`${plugin.id}\` | \`${plugin.name}\` |`),
  442. '',
  443. `Source config: [\`${example.config}\`](${linkFromDoc(example.rel, example.config)}).`,
  444. )
  445. lines.push('', ...maintenanceFooter(maintenance))
  446. return lines.join('\n')
  447. }
  448. function collectEventRelations(): Map<string, EventRelation> {
  449. const out = new Map<string, EventRelation>()
  450. const ensure = (event: string): EventRelation => {
  451. const existing = out.get(event)
  452. if (existing) return existing
  453. const next = { dispatchers: new Map<string, Set<string>>(), listeners: new Set<string>() }
  454. out.set(event, next)
  455. return next
  456. }
  457. for (const rel of globSync('packages/*/*/src/**/*.ts', { cwd: root }).sort()) {
  458. const [, , leaf] = rel.split('/')
  459. if (leaf === undefined) continue
  460. const text = readFileSync(resolve(root, rel), 'utf8')
  461. const sf = ts.createSourceFile(rel, text, ts.ScriptTarget.Latest, true)
  462. const visit = (node: ts.Node): void => {
  463. if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
  464. const method = node.expression.name.text
  465. if (!isCordisContextReceiver(node.expression, sf)) {
  466. ts.forEachChild(node, visit)
  467. return
  468. }
  469. if (method === 'on') {
  470. const event = eventArg(node.arguments, method)
  471. if (event) ensure(event).listeners.add(leaf)
  472. } else if (method === 'emit' || method === 'parallel' || method === 'serial' || method === 'waterfall') {
  473. const event = eventArg(node.arguments, method)
  474. if (event) {
  475. const relation = ensure(event)
  476. const methods = relation.dispatchers.get(leaf) ?? new Set<string>()
  477. methods.add(method)
  478. relation.dispatchers.set(leaf, methods)
  479. }
  480. }
  481. }
  482. ts.forEachChild(node, visit)
  483. }
  484. visit(sf)
  485. }
  486. for (const entry of DYNAMIC_EVENT_DISPATCHERS) {
  487. const relation = ensure(entry.event)
  488. const methods = relation.dispatchers.get(entry.pkg) ?? new Set<string>()
  489. methods.add(entry.method)
  490. relation.dispatchers.set(entry.pkg, methods)
  491. }
  492. return out
  493. }
  494. function isCordisContextReceiver(expr: ts.PropertyAccessExpression, sf: ts.SourceFile): boolean {
  495. const target = expr.expression.getText(sf)
  496. return target === 'ctx' || target === 'this.ctx'
  497. }
  498. function eventArg(args: ts.NodeArray<ts.Expression>, method: string): string | undefined {
  499. if (method === 'waterfall') {
  500. const arg = args.find(ts.isStringLiteralLike)
  501. return arg?.text
  502. }
  503. const first = args[0]
  504. return first && ts.isStringLiteralLike(first) ? first.text : undefined
  505. }
  506. function relationPackages(map: Map<string, Set<string>>, pkgsByShort: Map<string, Pkg>): string {
  507. if (map.size === 0) return '-'
  508. return [...map.entries()]
  509. .sort(([a], [b]) => a.localeCompare(b))
  510. .map(([pkg, methods]) => `${pkgLink(pkgsByShort.get(pkg), pkg)} (${[...methods].sort().map(m => `\`${m}\``).join(', ')})`)
  511. .join(', ')
  512. }
  513. function listenerPackages(listeners: Set<string>, pkgsByShort: Map<string, Pkg>): string {
  514. if (listeners.size === 0) return '-'
  515. return [...listeners].sort().map(pkg => pkgLink(pkgsByShort.get(pkg), pkg)).join(', ')
  516. }
  517. function renderEventRelations(pkgs: Pkg[]): string {
  518. const events = collectEvents()
  519. const relations = collectEventRelations()
  520. const pkgsByShort = new Map(pkgs.map(pkg => [pkg.short, pkg]))
  521. const maintenance = 'hybrid generated: Cordis event declarations and most producer/listener edges are AST-scanned; dynamic dispatch sites are classified in `scripts/gen-doc-graphs.ts`'
  522. const lines = generatedHeader('Event Producer And Consumer Matrix')
  523. lines.push(
  524. '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. Dynamic dispatch overrides cover sites that deliberately bypass `ctx.emit`, such as subagent lifecycle containment.',
  525. '',
  526. '| Event | Mode | Declared in | Dispatchers | Listeners |',
  527. '| --- | --- | --- | --- | --- |',
  528. )
  529. for (const event of [...events].sort((a, b) => a.name.localeCompare(b.name))) {
  530. const relation = relations.get(event.name) ?? { dispatchers: new Map<string, Set<string>>(), listeners: new Set<string>() }
  531. lines.push(`| \`${event.name}\` | \`${event.mode}\` | ${sourceLink(event.source)} | ${relationPackages(relation.dispatchers, pkgsByShort)} | ${listenerPackages(relation.listeners, pkgsByShort)} |`)
  532. }
  533. const declared = new Set(events.map(event => event.name))
  534. const extra = [...relations.keys()].filter(event => !declared.has(event)).sort()
  535. if (extra.length > 0) {
  536. lines.push('', '## Non-harness or undeclared event strings seen in package source', '', '| Event string | Dispatchers | Listeners |', '| --- | --- | --- |')
  537. for (const event of extra) {
  538. const relation = relations.get(event)
  539. if (!relation) continue
  540. lines.push(`| \`${event}\` | ${relationPackages(relation.dispatchers, pkgsByShort)} | ${listenerPackages(relation.listeners, pkgsByShort)} |`)
  541. }
  542. }
  543. lines.push('', ...maintenanceFooter(maintenance))
  544. return lines.join('\n')
  545. }
  546. function renderLifecycle(): string {
  547. const maintenance = 'curated Mermaid sequence; exact event signatures live in the generated Cordis catalog'
  548. return [
  549. ...generatedHeader('Agent Turn And Step Lifecycle'),
  550. '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/*`.',
  551. '',
  552. '```mermaid',
  553. 'sequenceDiagram',
  554. ' participant User',
  555. ' participant Agent',
  556. ' participant Driver',
  557. ' participant Hooks as hook listeners',
  558. ' participant Prompt as ctx.systemPrompt',
  559. ' participant LLM as ctx.llm',
  560. ' participant Tools as ctx.tools',
  561. ' participant Session',
  562. ' participant Persistence',
  563. ' participant SDK as UI or SDK listener',
  564. ' User->>Agent: send(content)',
  565. ` Agent-->>SDK: ${mermaidCode('agent/queued')}`,
  566. ' Agent->>Driver: queued work wakes driver',
  567. ` Driver-->>SDK: ${mermaidCode('agent/status')} running`,
  568. ` Driver->>Session: ${mermaidCode('turn/start')}`,
  569. ` Driver->>Hooks: ${mermaidCode('agent/prompt-submit')} waterfall`,
  570. ' Hooks-->>Driver: allow, block, or add context',
  571. ` Driver->>Session: ${mermaidCode('user/message')} or rejected ${mermaidCode('turn/end')}`,
  572. ` Driver->>Prompt: ${mermaidCode('system-prompt/assemble')} waterfall`,
  573. ` Driver-->>Driver: ${mermaidCode('agent/pre-step')} serial checkpoint`,
  574. ` Driver->>Session: ${mermaidCode('step/start')}`,
  575. ` Driver->>LLM: ${mermaidCode('agent/request')} waterfall, then ${mermaidCode('llm/stream')} waterfall`,
  576. ' LLM-->>Driver: StreamChunk*',
  577. ` Driver->>Session: ${mermaidCode('assistant/chunk')}*`,
  578. ` Session-->>SDK: ${mermaidCode('session/event')} ${mermaidCode('assistant/chunk')}*`,
  579. ` Driver->>Hooks: ${mermaidCode('agent/step-result')} waterfall`,
  580. ` Driver->>Session: ${mermaidCode('assistant/message')}`,
  581. ` Driver->>Session: ${mermaidCode('tool/call')}`,
  582. ' Driver->>Tools: execute through pre and post waterfalls',
  583. ' Tools-->>Session: tool-owned events when applicable',
  584. ` Driver->>Session: ${mermaidCode('tool/result')} and ${mermaidCode('step/end')}`,
  585. ` Driver->>Hooks: ${mermaidCode('agent/turn-continuation')} waterfall`,
  586. ` Driver->>Session: ${mermaidCode('turn/end')}`,
  587. ` Driver->>Persistence: ${mermaidCode('session/flush')} parallel checkpoint`,
  588. ` Driver-->>SDK: ${mermaidCode('agent/status')} idle`,
  589. '```',
  590. '',
  591. '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.',
  592. '',
  593. ...maintenanceFooter(maintenance),
  594. ].join('\n')
  595. }
  596. function renderToolPipeline(): string {
  597. const maintenance = 'curated Mermaid flow; exact tool schemas and event signatures live in generated catalogs'
  598. return [
  599. ...generatedHeader('Tool Execution Pipeline'),
  600. 'This graph shows where policy, hooks, sandboxing, filesystem guards, result rewriting, and UI rendering fit without changing the loop. The key extension points are the `tools/pre-execute`, `tools/execute`, and `tools/post-execute` waterfalls.',
  601. '',
  602. '```mermaid',
  603. 'flowchart TD',
  604. ' model["Assistant message contains tool-call block"]',
  605. ` toolCall["Session event: ${mermaidCode('tool/call')}<br/>logged before execution"]`,
  606. ' presentCall["UI pending card<br/>presentCall(args)"]',
  607. ` pre["${mermaidCode('tools/pre-execute')} waterfall<br/>hooks, permission, sandbox"]`,
  608. ' denied["deny or ask<br/>tool body skipped"]',
  609. ` around["${mermaidCode('tools/execute')} waterfall<br/>timeout, retry, metrics (around dispatch)"]`,
  610. ' toolBody["Registered tool execute() body"]',
  611. ` fsGate["${mermaidCode('fs/write-intent')} or ${mermaidCode('fs/edit-intent')}<br/>tool-fs mutations only"]`,
  612. ` owned["Tool-owned session events<br/>${mermaidCode('todo/write')}, ${mermaidCode('fs/observed')}, ${mermaidCode('hook/invoked')}, ${mermaidCode('hook/result')}"]`,
  613. ` post["${mermaidCode('tools/post-execute')} waterfall<br/>accept, block, replace, add context"]`,
  614. ' context["Buffered additionalContext<br/>context/message after all tool results"]',
  615. ` toolResult["Session event: ${mermaidCode('tool/result')}<br/>single model-facing outcome"]`,
  616. ' presentResult["UI completed card<br/>presentResult(args, result)"]',
  617. ' model --> toolCall',
  618. ' toolCall --> presentCall',
  619. ' toolCall --> pre',
  620. ' pre -->|allow| around',
  621. ' around --> toolBody',
  622. ' pre -->|deny or ask| denied',
  623. ' denied --> post',
  624. ' toolBody --> fsGate',
  625. ' fsGate --> toolBody',
  626. ' toolBody --> owned',
  627. ' toolBody --> around',
  628. ' around --> post',
  629. ' post --> context',
  630. ' post --> toolResult',
  631. ' toolResult --> presentResult',
  632. '```',
  633. '',
  634. 'Filesystem read-before-edit checks live below `tool-fs` on the `fs/*` event gate; hook bridges and future permission prompts live on the generic pre/post tool waterfalls; and around-dispatch concerns like the tool-call timeout policy (`@deepseek-ai/dsh-timeout-policy`) wrap core dispatch on `tools/execute`. That split lets the same hooks observe bash, fs, web, todo, and subagent calls without coupling those tools to one policy service.',
  635. '',
  636. ...maintenanceFooter(maintenance),
  637. ].join('\n')
  638. }
  639. function renderSnapshotReplay(): string {
  640. const maintenance = 'curated Mermaid sequence based on the snapshot test harness'
  641. return [
  642. ...generatedHeader('ACP Snapshot Replay'),
  643. '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.',
  644. '',
  645. '```mermaid',
  646. 'sequenceDiagram',
  647. ' participant Recorder as Real API recording',
  648. ' participant Fixture as snapshot fixture',
  649. ' participant Workspace',
  650. ' participant Replay as llm-replay adapter',
  651. ' participant ACP as acp-agent subprocess',
  652. ' participant Golden as stdout golden',
  653. ' Recorder->>Fixture: session.jsonl + workspace inputs',
  654. ' Fixture->>Workspace: seed files and hook configs',
  655. ' Fixture->>Replay: recorded StreamChunk script',
  656. ` Replay->>ACP: deterministic ${mermaidCode('llm/stream')} chunks`,
  657. ' ACP->>Workspace: bash, fs, and hook side effects',
  658. ' ACP->>Golden: normalized sessionUpdate stream',
  659. ' Golden-->>ACP: diff must be empty',
  660. '```',
  661. '',
  662. '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.',
  663. '',
  664. ...maintenanceFooter(maintenance),
  665. ].join('\n')
  666. }
  667. function renderDocs(): GraphDoc[] {
  668. const pkgs = collectPackages()
  669. const docs: GraphDoc[] = [
  670. { rel: 'docs/capability-seams.md', content: renderCapabilitySeams(pkgs) },
  671. ...APP_EXAMPLES.map(example => ({ rel: example.rel, content: renderAppComposition(example) })),
  672. { rel: 'docs/event-producer-consumer.md', content: renderEventRelations(pkgs) },
  673. { rel: 'docs/agent-lifecycle.md', content: renderLifecycle() },
  674. { rel: 'docs/tool-execution-pipeline.md', content: renderToolPipeline() },
  675. { rel: 'packages/ui/acp/snapshot-replay.md', content: renderSnapshotReplay() },
  676. ]
  677. docs.unshift({ rel: 'docs/graph-atlas.md', content: renderIndex(docs) })
  678. return docs
  679. }
  680. function renderIndex(docs: GraphDoc[]): string {
  681. const labels: Record<string, string> = {
  682. 'docs/capability-seams.md': 'capability seams and core services',
  683. 'examples/echo-agent/composition.md': 'echo-agent app composition',
  684. 'examples/coding-agent/composition.md': 'coding-agent app composition',
  685. 'examples/cordis-agent/composition.md': 'cordis-agent app composition',
  686. 'examples/acp-agent/composition.md': 'acp-agent app composition',
  687. 'docs/event-producer-consumer.md': 'event producer/consumer matrix',
  688. 'docs/agent-lifecycle.md': 'agent turn and step lifecycle',
  689. 'docs/tool-execution-pipeline.md': 'tool execution pipeline',
  690. 'packages/ui/acp/snapshot-replay.md': 'ACP snapshot replay',
  691. }
  692. const modes: Record<string, string> = {
  693. 'docs/capability-seams.md': 'hybrid generated',
  694. 'examples/echo-agent/composition.md': 'hybrid generated',
  695. 'examples/coding-agent/composition.md': 'hybrid generated',
  696. 'examples/cordis-agent/composition.md': 'hybrid generated',
  697. 'examples/acp-agent/composition.md': 'hybrid generated',
  698. 'docs/event-producer-consumer.md': 'hybrid generated',
  699. 'docs/agent-lifecycle.md': 'curated',
  700. 'docs/tool-execution-pipeline.md': 'curated',
  701. 'packages/ui/acp/snapshot-replay.md': 'curated',
  702. }
  703. const rows = [
  704. '| [module dependency graph](module-graph.md) | `generated` |',
  705. '| [tool schema catalog and package map](tool-catalog.md) | `generated` |',
  706. ...docs.map((doc) => {
  707. const link = graphIndexLink(doc.rel)
  708. return `| [${labels[doc.rel] ?? link}](${link}) | \`${modes[doc.rel] ?? 'generated'}\` |`
  709. }),
  710. ]
  711. const maintenance = 'mixed: each linked page declares generated, hybrid, or curated mode'
  712. return [
  713. ...generatedHeader('Documentation Graph Index'),
  714. '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).',
  715. '',
  716. 'The process decision behind this index is recorded in [the documentation graph RFC](rfc/implemented/process/2026-07-03-documentation-graph-atlas.md).',
  717. '',
  718. '| Graph | Mode |',
  719. '| --- | --- |',
  720. ...rows,
  721. '',
  722. 'Regenerate with `pnpm run gen-doc-graphs`; verify freshness with `pnpm run verify-doc-graphs`.',
  723. '',
  724. ...maintenanceFooter(maintenance),
  725. ].join('\n')
  726. }
  727. function main(): void {
  728. const docs = renderDocs()
  729. if (process.argv.includes('--check')) {
  730. const stale: string[] = []
  731. for (const doc of docs) {
  732. const abs = resolve(root, doc.rel)
  733. const committed = existsSync(abs) ? readFileSync(abs, 'utf8') : null
  734. if (committed !== doc.content) stale.push(doc.rel)
  735. }
  736. if (stale.length === 0) {
  737. console.log(`gen-doc-graphs: ${docs.length} graph doc(s) are up to date.`)
  738. return
  739. }
  740. console.error(`gen-doc-graphs: stale graph doc(s): ${stale.join(', ')}. Run \`pnpm run gen-doc-graphs\` and commit the result.`)
  741. process.exit(1)
  742. }
  743. for (const doc of docs) {
  744. mkdirSync(dirname(resolve(root, doc.rel)), { recursive: true })
  745. writeFileSync(resolve(root, doc.rel), doc.content)
  746. }
  747. console.log(`gen-doc-graphs: wrote ${docs.length} graph doc(s).`)
  748. }
  749. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  750. main()
  751. }