gen-doc-graphs.ts 36 KB

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