gen-doc-graphs.ts 36 KB

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