gen-doc-graphs.ts 33 KB

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