gen-doc-graphs.ts 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. /**
  2. * Generate the relationship layer above the module, Cordis, and tool catalogs.
  3. * Enumerable facts come from source; hybrid graphs add manifests for policy the
  4. * source cannot infer, while curated graphs explain flow and ownership.
  5. * `--check` verifies the generated set.
  6. */
  7. import { existsSync, globSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
  8. import { dirname, relative, resolve } from 'node:path'
  9. import ts from 'typescript'
  10. import { collectEvents, collectServices } from './gen-cordis-catalog.ts'
  11. import {
  12. collectPackageGraph,
  13. escapeMermaidLabel as escLabel,
  14. graphNodeId as nodeId,
  15. type PackageGraphNode,
  16. } from './package-graph.ts'
  17. const root = resolve(import.meta.dirname, '..')
  18. type Pkg = PackageGraphNode
  19. interface GraphDoc {
  20. rel: string
  21. content: string
  22. }
  23. interface ServiceRole {
  24. key: string
  25. pkg: string
  26. title: string
  27. mode: 'core' | 'seam' | 'bundle'
  28. implementations?: string[]
  29. consumers?: string[]
  30. companions?: string[]
  31. note: string
  32. }
  33. interface ExamplePlugin {
  34. id: string
  35. name: string
  36. }
  37. interface EventRelation {
  38. dispatchers: Map<string, Set<string>>
  39. listeners: Set<string>
  40. }
  41. const GROUP_ORDER = [
  42. 'util',
  43. 'llm',
  44. 'core',
  45. 'bash',
  46. 'sandbox',
  47. 'fs',
  48. 'skill',
  49. 'compact',
  50. 'subagent',
  51. 'web',
  52. 'todo',
  53. 'cordis',
  54. 'hooks',
  55. 'session-persistence',
  56. 'session-query',
  57. 'support',
  58. 'ui',
  59. ]
  60. const SERVICE_ROLES: ServiceRole[] = [
  61. {
  62. key: 'llm',
  63. pkg: 'llm',
  64. title: 'LLM adapter registry',
  65. mode: 'seam',
  66. implementations: ['llm-deepseek', 'llm-pi-ai', 'llm-replay'],
  67. consumers: ['agent-loop', 'compact-basic'],
  68. note: 'Adapters register provider implementations; the loop and compaction call the provider-neutral stream service.',
  69. },
  70. {
  71. key: 'sessions',
  72. pkg: 'session',
  73. title: 'In-memory session store',
  74. mode: 'core',
  75. consumers: ['agent-loop', 'agent', 'session-persistence', 'session-query', 'subagent-inprocess', 'invariants'],
  76. note: 'Owns append-only Session instances and emits the durable session event feed.',
  77. },
  78. {
  79. key: 'sessionPersistence',
  80. pkg: 'session-persistence',
  81. title: 'Durable session persistence seam',
  82. mode: 'seam',
  83. implementations: ['session-persistence-jsonl', 'session-persistence-sqlite'],
  84. consumers: ['agent-loop', 'acp', 'session-query'],
  85. note: 'Backends persist the same SessionEvent vocabulary; apps choose a backend at composition time.',
  86. },
  87. {
  88. key: 'sessionQuery',
  89. pkg: 'session-query',
  90. title: 'Exact session-history reads',
  91. mode: 'seam',
  92. note: 'Resolves live and optional persisted logs into one logical corpus for exact reads.',
  93. },
  94. {
  95. key: 'systemPrompt',
  96. pkg: 'system-prompt',
  97. title: 'System prompt assembly registry',
  98. mode: 'core',
  99. consumers: ['agent-loop', 'tools', 'tool-fs', 'tool-web'],
  100. note: 'Collects prompt sections and model-facing tool schemas for each step.',
  101. },
  102. {
  103. key: 'tools',
  104. pkg: 'tools',
  105. title: 'Tool registry and guarded execution pipeline',
  106. mode: 'core',
  107. consumers: ['agent-loop', 'tool-ask-user', 'tool-bash', 'tool-cordis', 'tool-fs', 'tool-skill', 'tool-subagent', 'tool-todo', 'tool-web', 'acp'],
  108. note: 'Registers capabilities, owns Code Mode transport, and routes calls through pre-policy, monotonic guards, around dispatch, post-policy, and final-result observation.',
  109. },
  110. {
  111. key: 'userInteraction',
  112. pkg: 'user-interaction',
  113. title: 'Human question/answer seam',
  114. mode: 'seam',
  115. implementations: ['stdio-agent', 'acp'],
  116. consumers: ['tool-ask-user', 'stdio-agent', 'acp'],
  117. note: 'UI front doors provide the active human-answer provider; tool-ask-user pauses a tool call on the provider-neutral ask() promise.',
  118. },
  119. {
  120. key: 'skills',
  121. pkg: 'skill',
  122. title: 'Skill provider registry',
  123. mode: 'seam',
  124. implementations: ['skill-local'],
  125. consumers: ['tool-skill'],
  126. note: 'Merges provider skill catalogs; tool-skill renders the session-prefix catalog and loads complete skill bodies.',
  127. },
  128. {
  129. key: 'agents',
  130. pkg: 'agent',
  131. title: 'Agent registry',
  132. mode: 'core',
  133. consumers: ['agent-loop', 'acp', 'subagent-inprocess', 'stdio-agent', 'invariants'],
  134. note: 'Owns live Agent handles and the create/resume factory seam.',
  135. },
  136. {
  137. key: 'agentLoop',
  138. pkg: 'agent-loop',
  139. title: 'Concrete loop driver',
  140. mode: 'bundle',
  141. consumers: ['agent-core'],
  142. note: 'The one concrete loop plugin; extension packages depend on dsh-agent events and services, not on this package.',
  143. },
  144. {
  145. key: 'bash',
  146. pkg: 'bash',
  147. title: 'Bash executor seam',
  148. mode: 'seam',
  149. implementations: ['bash-local', 'bash-sandbox'],
  150. consumers: ['tool-bash', 'hooks-claude', 'hooks-codex'],
  151. note: 'The model-facing bash tools and hook bridges consume this seam; sandboxed or remote executors replace bash-local without touching them.',
  152. },
  153. {
  154. key: 'bashEnv',
  155. pkg: 'tool-bash',
  156. title: 'Managed bash environment registry',
  157. mode: 'core',
  158. note: 'Plugins declare effect-scoped DSH_* facts; tool-bash collects one trusted snapshot per execution and the executor rebuilds the namespace.',
  159. },
  160. {
  161. key: 'sandbox',
  162. pkg: 'sandbox',
  163. title: 'Process-sandbox seam',
  164. mode: 'seam',
  165. implementations: ['sandbox-local'],
  166. consumers: ['bash-sandbox'],
  167. note: 'Consumers hand over the exact argv they are about to spawn; same-world backends wrap it under a per-call policy and report enforcement.',
  168. },
  169. {
  170. key: 'approval',
  171. pkg: 'approval',
  172. title: 'Approval seam',
  173. mode: 'seam',
  174. implementations: ['acp'],
  175. consumers: ['tools', 'tool-bash'],
  176. note: 'One-shot permission decisions dispatched over the `approval/request` waterfall; answerers are listeners (the ACP bridge for its own agents), absence fails closed to `unavailable`.',
  177. },
  178. {
  179. key: 'permission',
  180. pkg: 'permission',
  181. title: 'Permission presets',
  182. mode: 'core',
  183. implementations: [],
  184. consumers: ['acp'],
  185. note: 'User-facing preset table (`workspace-write`/`danger-full-access`) bundling the sandbox-mode and approval-policy knobs; a switch writes one `permission/preset` event through to both knob events.',
  186. },
  187. {
  188. key: 'codeRuntime',
  189. pkg: 'code-runtime',
  190. title: 'Code-execution seam',
  191. mode: 'seam',
  192. implementations: ['code-runtime-worker'],
  193. consumers: ['tools'],
  194. note: 'Runs one model-written program against host-provided async bindings; backends differ by substrate and language (the tool registry consumes it for Code Mode).',
  195. },
  196. {
  197. key: 'fs',
  198. pkg: 'fs',
  199. title: 'Filesystem provider seam',
  200. mode: 'seam',
  201. implementations: ['fs-local'],
  202. consumers: ['tool-fs'],
  203. companions: ['fs-policy'],
  204. note: 'tool-fs executes read/write/edit through ctx.fs; fs-policy contributes observed-state checks through the fs/* event gate.',
  205. },
  206. {
  207. key: 'compact',
  208. pkg: 'compact',
  209. title: 'Compaction seam',
  210. mode: 'seam',
  211. implementations: ['compact-basic'],
  212. consumers: ['compact-basic'],
  213. note: 'The basic backend currently consumes the pre-step event directly; a model-facing compact tool remains deferred.',
  214. },
  215. {
  216. key: 'subagents',
  217. pkg: 'subagent',
  218. title: 'Subagent provider registry',
  219. mode: 'seam',
  220. implementations: ['subagent-spawn', 'subagent-fork', 'subagent-acp', 'subagent-mock'],
  221. consumers: ['tool-subagent'],
  222. note: 'Providers implement transports; tool-subagent exposes one configured provider as a model-facing tool name.',
  223. },
  224. {
  225. key: 'web',
  226. pkg: 'web',
  227. title: 'Web access provider registry',
  228. mode: 'seam',
  229. implementations: ['web-search-exa', 'web-search-perplexity', 'web-search-deepseek', 'web-fetch-local'],
  230. consumers: ['tool-web'],
  231. note: 'Search and fetch providers register into one ctx.web seam; tool-web owns the stable model-facing names.',
  232. },
  233. {
  234. key: 'workflows',
  235. pkg: 'workflow',
  236. title: 'Workflow script engine',
  237. mode: 'seam',
  238. implementations: ['workflow-workerthread'],
  239. consumers: ['tool-workflow'],
  240. note: 'One engine per context (bash shape, no named-provider registry); the worker-thread engine fans agent() calls out through ctx.subagents.',
  241. },
  242. ]
  243. const DYNAMIC_EVENT_DISPATCHERS: Array<{ event: string; pkg: string; method: string }> = [
  244. // Creation notifications preserve synchronous veto/rollback but observe
  245. // returned promises explicitly so async listener rejection is not unhandled.
  246. { event: 'agent/created', pkg: 'agent', method: 'events.dispatch' },
  247. // Registry disposal reuses the stable carrier captured before entry commit
  248. // and contains each listener directly rather than rebuilding via agentEvents.
  249. { event: 'agent/disposed', pkg: 'agent', method: 'events.dispatch' },
  250. { event: 'session/created', pkg: 'session', method: 'events.dispatch' },
  251. // Session event callbacks are likewise resolved before the log push, then
  252. // invoked individually after commit so observer failures are contained.
  253. { event: 'session/event', pkg: 'session', method: 'events.dispatch' },
  254. // Flush resolves the scoped callback set directly so internal instrumentation
  255. // cannot substitute the accepted session before parallel invocation.
  256. { event: 'session/flush', pkg: 'session', method: 'events.dispatch' },
  257. // Session disposal uses direct callback resolution so teardown contains each
  258. // synchronous throw and returned-promise rejection independently.
  259. { event: 'session/disposed', pkg: 'session', method: 'events.dispatch' },
  260. // tools/result uses ctx.events.dispatch directly so the registry can invoke
  261. // every synchronous observer while containing each callback independently.
  262. { event: 'tools/result', pkg: 'tools', method: 'events.dispatch' },
  263. // Subagent lifecycle events intentionally bypass ctx.emit and call
  264. // ctx.events.dispatch directly so one throwing listener cannot starve later
  265. // listeners or strand an already-started child run.
  266. { event: 'subagent/start', pkg: 'subagent', method: 'events.dispatch' },
  267. { event: 'subagent/end', pkg: 'subagent', method: 'events.dispatch' },
  268. // provider-removed fires inside the provider registration's DISPOSER and
  269. // routes through the same contained dispatch (see emitLifecycle in
  270. // dsh-subagent), so the AST scan cannot attribute it either.
  271. { event: 'subagent/provider-removed', pkg: 'subagent', method: 'events.dispatch' },
  272. // The workflow/* lifecycle events dispatch the same way, for the same
  273. // per-listener-containment reason (WorkflowService.emitWorkflowEvent).
  274. { event: 'workflow/start', pkg: 'workflow', method: 'events.dispatch' },
  275. { event: 'workflow/phase', pkg: 'workflow', method: 'events.dispatch' },
  276. { event: 'workflow/log', pkg: 'workflow', method: 'events.dispatch' },
  277. { event: 'workflow/agent-start', pkg: 'workflow', method: 'events.dispatch' },
  278. { event: 'workflow/agent-end', pkg: 'workflow', method: 'events.dispatch' },
  279. { event: 'workflow/end', pkg: 'workflow', method: 'events.dispatch' },
  280. ]
  281. const DYNAMIC_EVENT_LISTENERS: Array<{ event: string; pkg: string }> = [
  282. // The invariants oracle marks the session started from its global
  283. // internal/dispatch listener before product session-start callbacks run.
  284. { event: 'agent/session-start', pkg: 'invariants' },
  285. ]
  286. function generatedHeader(title: string): string[] {
  287. return [
  288. '<!-- Generated by scripts/gen-doc-graphs.ts - do not edit by hand.',
  289. ' Run `pnpm run gen-doc-graphs` to regenerate. -->',
  290. '',
  291. `# ${title}`,
  292. '',
  293. ]
  294. }
  295. function maintenanceFooter(source: string): string[] {
  296. return [`Maintenance mode: ${source}.`, '']
  297. }
  298. function graphIndexLink(rel: string): string {
  299. return relative('docs', rel).replaceAll('\\', '/')
  300. }
  301. function linkFromDoc(docRel: string, targetRel: string): string {
  302. return relative(dirname(docRel), targetRel).replaceAll('\\', '/')
  303. }
  304. function mermaidCode(value: string): string {
  305. return `<code>${value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</code>`
  306. }
  307. function repoLink(path: string, label: string, up = '..'): string {
  308. return `[${label}](${up}/${path})`
  309. }
  310. function sourceLink(source: string, up = '..'): string {
  311. return repoLink(source.split(':')[0] ?? source, `\`${source}\``, up)
  312. }
  313. function pkgLink(pkg: Pkg | undefined, fallback: string, up = '..'): string {
  314. return pkg ? repoLink(pkg.rel, `\`${pkg.short}\``, up) : `\`${fallback}\``
  315. }
  316. function pkgList(names: string[] | undefined, pkgsByShort: Map<string, Pkg>): string {
  317. if (!names || names.length === 0) return '-'
  318. return names.map(name => pkgLink(pkgsByShort.get(name), name)).join(', ')
  319. }
  320. function tableCell(value: string): string {
  321. return value.replace(/\|/g, '\\|').replace(/\n/g, '<br>')
  322. }
  323. function assertServiceRolesComplete(): void {
  324. const discovered = new Set(collectServices().map(service => service.key))
  325. const classified = new Set(SERVICE_ROLES.map(role => role.key))
  326. const missing = [...discovered].filter(key => !classified.has(key)).sort()
  327. const stale = [...classified].filter(key => !discovered.has(key)).sort()
  328. if (missing.length || stale.length) {
  329. throw new Error([
  330. missing.length ? `missing service role classification: ${missing.join(', ')}` : '',
  331. stale.length ? `stale service role classification: ${stale.join(', ')}` : '',
  332. ].filter(Boolean).join('; '))
  333. }
  334. }
  335. function renderCapabilitySeams(pkgs: Pkg[]): string {
  336. assertServiceRolesComplete()
  337. const pkgsByShort = new Map(pkgs.map(pkg => [pkg.short, pkg]))
  338. 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'
  339. const nodes = new Map<string, string>()
  340. const edges = new Set<string>()
  341. const companionEdges = new Set<string>()
  342. const addNode = (id: string, label: string): void => {
  343. if (!nodes.has(id)) nodes.set(id, ` ${id}["${escLabel(label)}"]`)
  344. }
  345. const addEdge = (from: string, to: string): void => { edges.add(` ${from} --> ${to}`) }
  346. const lines = generatedHeader('Capability Seams And Core Services')
  347. lines.push(
  348. '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.',
  349. '',
  350. '```mermaid',
  351. 'flowchart LR',
  352. )
  353. for (const role of SERVICE_ROLES) {
  354. const svc = nodeId('svc', role.key)
  355. const owner = nodeId('pkg', role.pkg)
  356. addNode(owner, role.pkg)
  357. addNode(svc, `ctx.${role.key}<br/>${role.title}`)
  358. addEdge(owner, svc)
  359. for (const impl of role.implementations ?? []) {
  360. addNode(nodeId('pkg', impl), impl)
  361. addEdge(nodeId('pkg', impl), svc)
  362. }
  363. for (const consumer of role.consumers ?? []) {
  364. addNode(nodeId('pkg', consumer), consumer)
  365. addEdge(svc, nodeId('pkg', consumer))
  366. }
  367. for (const companion of role.companions ?? []) {
  368. addNode(nodeId('pkg', companion), companion)
  369. companionEdges.add(` ${svc} -. event gate .-> ${nodeId('pkg', companion)}`)
  370. }
  371. }
  372. lines.push(...nodes.values(), ...[...edges].sort(), ...[...companionEdges].sort())
  373. lines.push('```', '', '| ctx key | Role | Owner | Implementations | Direct consumers | Companion plugins | Note |', '| --- | --- | --- | --- | --- | --- | --- |')
  374. for (const role of SERVICE_ROLES) {
  375. 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)} |`)
  376. }
  377. lines.push('', ...maintenanceFooter(maintenance))
  378. return lines.join('\n')
  379. }
  380. function parseExampleCordis(rel: string): ExamplePlugin[] {
  381. const text = readFileSync(resolve(root, rel), 'utf8')
  382. const plugins: ExamplePlugin[] = []
  383. let current: { id: string; name?: string } | null = null
  384. const flush = (): void => {
  385. if (current?.name) plugins.push({ id: current.id, name: current.name })
  386. }
  387. for (const line of text.split('\n')) {
  388. const id = /^-\s+id:\s+(.+?)\s*$/.exec(line)
  389. if (id?.[1] !== undefined) {
  390. flush()
  391. current = { id: stripYamlScalar(id[1]) }
  392. continue
  393. }
  394. const name = /^\s+name:\s+(.+?)\s*$/.exec(line)
  395. if (name?.[1] !== undefined && current) current.name = stripYamlScalar(name[1])
  396. }
  397. flush()
  398. return plugins
  399. }
  400. function stripYamlScalar(value: string): string {
  401. return value.trim().replace(/^['"]|['"]$/g, '')
  402. }
  403. const APP_EXAMPLES = [
  404. {
  405. id: 'echo',
  406. rel: 'examples/echo-agent/composition.md',
  407. title: 'Echo Agent App Composition',
  408. label: 'examples/echo-agent',
  409. config: 'examples/echo-agent/cordis.yml',
  410. 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.',
  411. },
  412. {
  413. id: 'coding',
  414. rel: 'examples/coding-agent/composition.md',
  415. title: 'Coding Agent App Composition',
  416. label: 'examples/coding-agent',
  417. config: 'examples/coding-agent/cordis.yml',
  418. 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.',
  419. },
  420. {
  421. id: 'cordis',
  422. rel: 'examples/cordis-agent/composition.md',
  423. title: 'Cordis Agent App Composition',
  424. label: 'examples/cordis-agent',
  425. config: 'examples/cordis-agent/cordis.yml',
  426. 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.',
  427. },
  428. {
  429. id: 'acp',
  430. rel: 'examples/acp-agent/composition.md',
  431. title: 'ACP Agent App Composition',
  432. label: 'examples/acp-agent',
  433. config: 'examples/acp-agent/cordis.yml',
  434. 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.',
  435. },
  436. ]
  437. type AppExample = typeof APP_EXAMPLES[number]
  438. function renderAppExpansion(lines: string[], appNode: string, pluginName: string): void {
  439. const agentCore = nodeId('bundle', 'agent_core')
  440. const jsonl = nodeId('bundle', 'jsonl')
  441. lines.push(` ${appNode} --> ${agentCore}["@deepseek-ai/dsh-agent-core"]`)
  442. lines.push(` ${appNode} --> ${jsonl}["@deepseek-ai/dsh-session-persistence-jsonl"]`)
  443. if (pluginName === '@deepseek-ai/dsh-stdio-agent') {
  444. lines.push(` ${appNode} --> ${nodeId('frontdoor', 'stdio')}["readline UI<br/>console logger<br/>pre-created main agent"]`)
  445. } else if (pluginName === '@deepseek-ai/dsh-acp-agent') {
  446. lines.push(` ${appNode} --> ${nodeId('frontdoor', 'acp')}["@deepseek-ai/dsh-acp<br/>JSON-RPC stdio bridge<br/>sessions created by client"]`)
  447. }
  448. lines.push(
  449. ` ${agentCore} --> ${nodeId('spine', 'llm')}["ctx.llm"]`,
  450. ` ${agentCore} --> ${nodeId('spine', 'sessions')}["ctx.sessions"]`,
  451. ` ${agentCore} --> ${nodeId('spine', 'tools')}["ctx.tools + tool-bash"]`,
  452. ` ${agentCore} --> ${nodeId('spine', 'loop')}["ctx.agents + ctx.agentLoop"]`,
  453. )
  454. }
  455. function renderAppComposition(example: AppExample): string {
  456. const plugins = parseExampleCordis(example.config)
  457. const maintenance = 'hybrid: the leaf plugin list is parsed from its `cordis.yml`; app package expansion is curated from package source'
  458. const lines = generatedHeader(example.title)
  459. lines.push(
  460. example.summary,
  461. '',
  462. '```mermaid',
  463. 'flowchart LR',
  464. ` cfg["${escLabel(example.label)}<br/>cordis.yml"]`,
  465. )
  466. for (const plugin of plugins) {
  467. const pluginNode = nodeId(`plugin_${example.id}`, plugin.id)
  468. lines.push(` ${pluginNode}["${escLabel(plugin.id)}<br/>${escLabel(plugin.name)}"]`)
  469. lines.push(` cfg --> ${pluginNode}`)
  470. if (plugin.name === '@deepseek-ai/dsh-stdio-agent' || plugin.name === '@deepseek-ai/dsh-acp-agent') {
  471. renderAppExpansion(lines, pluginNode, plugin.name)
  472. }
  473. }
  474. lines.push(
  475. '```',
  476. '',
  477. '| Plugin id | Package / module |',
  478. '| --- | --- |',
  479. ...plugins.map(plugin => `| \`${plugin.id}\` | \`${plugin.name}\` |`),
  480. '',
  481. `Source config: [\`${example.config}\`](${linkFromDoc(example.rel, example.config)}).`,
  482. )
  483. lines.push('', ...maintenanceFooter(maintenance))
  484. return lines.join('\n')
  485. }
  486. function collectEventRelations(): Map<string, EventRelation> {
  487. const out = new Map<string, EventRelation>()
  488. const ensure = (event: string): EventRelation => {
  489. const existing = out.get(event)
  490. if (existing) return existing
  491. const next = { dispatchers: new Map<string, Set<string>>(), listeners: new Set<string>() }
  492. out.set(event, next)
  493. return next
  494. }
  495. for (const rel of globSync('packages/*/*/src/**/*.ts', { cwd: root }).sort()) {
  496. const [, , leaf] = rel.split('/')
  497. if (leaf === undefined) continue
  498. const text = readFileSync(resolve(root, rel), 'utf8')
  499. const sf = ts.createSourceFile(rel, text, ts.ScriptTarget.Latest, true)
  500. const visit = (node: ts.Node): void => {
  501. if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
  502. const method = node.expression.name.text
  503. if (!isCordisContextReceiver(node.expression, sf)) {
  504. ts.forEachChild(node, visit)
  505. return
  506. }
  507. if (method === 'on') {
  508. const event = eventArg(node.arguments, method)
  509. if (event) ensure(event).listeners.add(leaf)
  510. } else if (method === 'emit' || method === 'parallel' || method === 'serial' || method === 'waterfall') {
  511. const event = eventArg(node.arguments, method)
  512. if (event) {
  513. const relation = ensure(event)
  514. const methods = relation.dispatchers.get(leaf) ?? new Set<string>()
  515. methods.add(method)
  516. relation.dispatchers.set(leaf, methods)
  517. }
  518. }
  519. }
  520. ts.forEachChild(node, visit)
  521. }
  522. visit(sf)
  523. }
  524. for (const entry of DYNAMIC_EVENT_DISPATCHERS) {
  525. const relation = ensure(entry.event)
  526. const methods = relation.dispatchers.get(entry.pkg) ?? new Set<string>()
  527. methods.add(entry.method)
  528. relation.dispatchers.set(entry.pkg, methods)
  529. }
  530. for (const entry of DYNAMIC_EVENT_LISTENERS) {
  531. ensure(entry.event).listeners.add(entry.pkg)
  532. }
  533. return out
  534. }
  535. function isCordisContextReceiver(expr: ts.PropertyAccessExpression, sf: ts.SourceFile): boolean {
  536. // The chained fused-dispatch spelling: `agentEvents(ctx, agent).emit(…)` —
  537. // the receiver is a call expression, not an identifier.
  538. if (ts.isCallExpression(expr.expression) && expr.expression.expression.getText(sf) === 'agentEvents') {
  539. return true
  540. }
  541. const target = expr.expression.getText(sf)
  542. if (target === 'ctx' || target === 'this.ctx') return true
  543. // Scoped-dispatch spellings are conventional names. Keep this list in sync
  544. // with renames or the relationship matrix can silently lose an edge.
  545. return target === 'events' || target === 'childCtx' || target === 'this.loopCtx' || target === 'emitCtx'
  546. }
  547. function eventArg(args: ts.NodeArray<ts.Expression>, method: string): string | undefined {
  548. if (method === 'waterfall') {
  549. const arg = args.find(ts.isStringLiteralLike)
  550. return arg?.text
  551. }
  552. const first = args[0]
  553. if (first && ts.isStringLiteralLike(first)) return first.text
  554. // Scope-carrier dispatch: `emit(carrier, 'event/name', …)` puts the event
  555. // name second. Accept a string literal in position 1 when position 0 is a
  556. // non-literal expression (the carrier).
  557. const second = args[1]
  558. return second && ts.isStringLiteralLike(second) ? second.text : undefined
  559. }
  560. function relationPackages(map: Map<string, Set<string>>, pkgsByShort: Map<string, Pkg>): string {
  561. if (map.size === 0) return '-'
  562. return [...map.entries()]
  563. .sort(([a], [b]) => a.localeCompare(b))
  564. .map(([pkg, methods]) => `${pkgLink(pkgsByShort.get(pkg), pkg)} (${[...methods].sort().map(m => `\`${m}\``).join(', ')})`)
  565. .join(', ')
  566. }
  567. function listenerPackages(listeners: Set<string>, pkgsByShort: Map<string, Pkg>): string {
  568. if (listeners.size === 0) return '-'
  569. return [...listeners].sort().map(pkg => pkgLink(pkgsByShort.get(pkg), pkg)).join(', ')
  570. }
  571. function renderEventRelations(pkgs: Pkg[]): string {
  572. const events = collectEvents()
  573. const relations = collectEventRelations()
  574. const pkgsByShort = new Map(pkgs.map(pkg => [pkg.short, pkg]))
  575. 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`'
  576. const lines = generatedHeader('Event Producer And Consumer Matrix')
  577. lines.push(
  578. '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.',
  579. '',
  580. '| Event | Mode | Declared in | Dispatchers | Listeners |',
  581. '| --- | --- | --- | --- | --- |',
  582. )
  583. for (const event of [...events].sort((a, b) => a.name.localeCompare(b.name))) {
  584. const relation = relations.get(event.name) ?? { dispatchers: new Map<string, Set<string>>(), listeners: new Set<string>() }
  585. lines.push(`| \`${event.name}\` | \`${event.mode}\` | ${sourceLink(event.source)} | ${relationPackages(relation.dispatchers, pkgsByShort)} | ${listenerPackages(relation.listeners, pkgsByShort)} |`)
  586. }
  587. // Every declared event needs a dispatcher: zero means dead vocabulary or an
  588. // unrecognized dispatch spelling. Listener-free extension points remain valid.
  589. const undispatched = [...events]
  590. .filter(event => (relations.get(event.name)?.dispatchers.size ?? 0) === 0)
  591. .map(event => event.name)
  592. .sort()
  593. if (undispatched.length > 0) {
  594. throw new Error(
  595. `event-producer-consumer matrix: no dispatcher found for declared event${undispatched.length > 1 ? 's' : ''} `
  596. + `${undispatched.map(name => `"${name}"`).join(', ')} — dead vocabulary, or a dispatch spelling the scan misses `
  597. + '(teach scripts/gen-doc-graphs.ts the spelling or add a DYNAMIC_EVENT_DISPATCHERS override)',
  598. )
  599. }
  600. const declared = new Set(events.map(event => event.name))
  601. const extra = [...relations.keys()].filter(event => !declared.has(event)).sort()
  602. if (extra.length > 0) {
  603. lines.push('', '## Non-harness or undeclared event strings seen in package source', '', '| Event string | Dispatchers | Listeners |', '| --- | --- | --- |')
  604. for (const event of extra) {
  605. const relation = relations.get(event)
  606. if (!relation) continue
  607. lines.push(`| \`${event}\` | ${relationPackages(relation.dispatchers, pkgsByShort)} | ${listenerPackages(relation.listeners, pkgsByShort)} |`)
  608. }
  609. }
  610. lines.push('', ...maintenanceFooter(maintenance))
  611. return lines.join('\n')
  612. }
  613. function renderLifecycle(): string {
  614. const maintenance = 'curated Mermaid sequence; exact event signatures live in the generated Cordis catalog'
  615. return [
  616. ...generatedHeader('Agent Turn And Step Lifecycle'),
  617. '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/*`.',
  618. '',
  619. '```mermaid',
  620. 'sequenceDiagram',
  621. ' participant User',
  622. ' participant Agent',
  623. ' participant Driver',
  624. ' participant Hooks as hook listeners',
  625. ' participant Prompt as ctx.systemPrompt',
  626. ' participant LLM as ctx.llm',
  627. ' participant Tools as ctx.tools',
  628. ' participant Session',
  629. ' participant Persistence',
  630. ' participant SDK as UI or SDK listener',
  631. ' User->>Agent: send(content)',
  632. ` Agent-->>SDK: ${mermaidCode('agent/queued')}`,
  633. ' Agent->>Driver: queued work wakes driver',
  634. ` Driver-->>SDK: ${mermaidCode('agent/status')} running`,
  635. ` Driver->>Session: ${mermaidCode('turn/start')}`,
  636. ` Driver->>Hooks: ${mermaidCode('agent/prompt-submit')} waterfall`,
  637. ' Hooks-->>Driver: allow, block, or add context',
  638. ` Driver->>Session: ${mermaidCode('user/message')} or rejected ${mermaidCode('turn/end')}`,
  639. ` Driver->>Prompt: ${mermaidCode('system-prompt/assemble')} waterfall`,
  640. ` Driver-->>Driver: ${mermaidCode('agent/pre-step')} serial checkpoint`,
  641. ` Driver->>Session: ${mermaidCode('step/start')}`,
  642. ` Driver->>LLM: ${mermaidCode('agent/request')} waterfall, then ${mermaidCode('llm/stream')} waterfall`,
  643. ' LLM-->>Driver: StreamChunk*',
  644. ` Driver->>Session: ${mermaidCode('assistant/chunk')}*`,
  645. ` Session-->>SDK: ${mermaidCode('session/event')} ${mermaidCode('assistant/chunk')}*`,
  646. ` Driver->>Hooks: ${mermaidCode('agent/step-result')} waterfall`,
  647. ` Driver->>Session: ${mermaidCode('assistant/message')}`,
  648. ` Driver->>Session: ${mermaidCode('tool/call')}`,
  649. ' Driver->>Tools: execute through pre and post waterfalls',
  650. ' Tools-->>Session: tool-owned events when applicable',
  651. ` Driver->>Session: ${mermaidCode('tool/result')} and ${mermaidCode('step/end')}`,
  652. ` Driver->>Hooks: ${mermaidCode('agent/turn-continuation')} waterfall`,
  653. ` Driver->>Hooks: ${mermaidCode('agent/turn-stop')} serial terminal checkpoint`,
  654. ` Driver->>Session: ${mermaidCode('turn/end')}`,
  655. ` Driver->>Persistence: ${mermaidCode('session/flush')} parallel checkpoint`,
  656. ` Driver-->>SDK: ${mermaidCode('agent/status')} idle`,
  657. '```',
  658. '',
  659. '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.',
  660. '',
  661. ...maintenanceFooter(maintenance),
  662. ].join('\n')
  663. }
  664. function renderToolPipeline(): string {
  665. const maintenance = 'curated Mermaid flow; exact tool schemas and event signatures live in generated catalogs'
  666. return [
  667. ...generatedHeader('Tool Execution Pipeline'),
  668. 'This graph shows where policy, hooks, sandboxing, filesystem guards, result rewriting, final-outcome observation, and UI rendering fit without changing the loop. The transformable extension points are the `tools/pre-execute`, `tools/execute`, and `tools/post-execute` waterfalls; monotonic guards and `tools/result` are the owner-enforced boundaries around them.',
  669. '',
  670. '```mermaid',
  671. 'flowchart TD',
  672. ' model["Assistant message contains tool-call block"]',
  673. ` toolCall["Session event: ${mermaidCode('tool/call')}<br/>logged before execution"]`,
  674. ' presentCall["UI pending card<br/>presentCall(args)"]',
  675. ` pre["${mermaidCode('tools/pre-execute')} waterfall<br/>hooks, permission, sandbox"]`,
  676. ' guards["Registered monotonic guards<br/>deny or abstain; identity protected"]',
  677. ' denied["denied or approval refused<br/>tool body skipped"]',
  678. ` approval["${mermaidCode('ctx.approval')} one-shot prompt<br/>absent or unanswerable: deny"]`,
  679. ` around["${mermaidCode('tools/execute')} waterfall<br/>timeout, retry, metrics (around dispatch)"]`,
  680. ' toolBody["Registered tool execute() body"]',
  681. ` fsGate["${mermaidCode('fs/write-intent')} or ${mermaidCode('fs/edit-intent')}<br/>tool-fs mutations only"]`,
  682. ` owned["Tool-owned session events<br/>${mermaidCode('todo/write')}, ${mermaidCode('fs/observed')}, ${mermaidCode('hook/invoked')}, ${mermaidCode('hook/result')}, ${mermaidCode('tool/code-dispatch')}"]`,
  683. ` post["${mermaidCode('tools/post-execute')} waterfall<br/>accept, block, replace, add context"]`,
  684. ` final["${mermaidCode('tools/result')} synchronous notification<br/>frozen authoritative outcome"]`,
  685. ' context["Buffered additionalContext<br/>context/message after all tool results"]',
  686. ` toolResult["Session event: ${mermaidCode('tool/result')}<br/>single model-facing outcome"]`,
  687. ' allResults["All calls in the step settled<br/>and tool/result events recorded"]',
  688. ' presentResult["UI completed card<br/>presentResult(args, result)"]',
  689. ' model --> toolCall',
  690. ' toolCall --> presentCall',
  691. ' toolCall --> pre',
  692. ' pre -->|allow| guards',
  693. ' guards -->|allow| around',
  694. ' guards -->|deny| denied',
  695. ' around --> toolBody',
  696. ' pre -->|deny| denied',
  697. ' pre -->|ask| approval',
  698. ' approval -->|allowed-once| guards',
  699. ' approval -->|rejected, cancelled, unavailable| denied',
  700. ' denied --> post',
  701. ' toolBody --> fsGate',
  702. ' fsGate --> toolBody',
  703. ' toolBody --> owned',
  704. ' toolBody --> around',
  705. ' around --> post',
  706. ' post --> final',
  707. ' final --> toolResult',
  708. ' toolResult --> presentResult',
  709. ' toolResult --> allResults',
  710. ' allResults --> context',
  711. '```',
  712. '',
  713. 'Filesystem read-before-edit checks stay below `tool-fs` on `fs/*` events. Generic pre/post waterfalls host hooks and approval policy; `ctx.approval` resolves asks before monotonic guards, and owner policy that must not be reordered remains a registered guard. Around-dispatch concerns such as timeouts wrap `tools/execute`, while `tools/result` observes the immutable outcome after transforms, lossless-JSON validation, and outer error normalization. This lets hooks span tool families without coupling the tools to one policy service. Code Mode sends both the reserved `run_code` transport and its serialized sub-calls through the pipeline; sub-calls carry the parent token, log `tool/code-dispatch`, surface denials as binding rejections, and omit `additionalContext` to preserve call/result adjacency.',
  714. '',
  715. ...maintenanceFooter(maintenance),
  716. ].join('\n')
  717. }
  718. function renderSnapshotReplay(): string {
  719. const maintenance = 'curated Mermaid sequence based on the snapshot test harness'
  720. return [
  721. ...generatedHeader('ACP Snapshot Replay'),
  722. '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.',
  723. '',
  724. '```mermaid',
  725. 'sequenceDiagram',
  726. ' participant Recorder as Real API recording',
  727. ' participant Fixture as snapshot fixture',
  728. ' participant Workspace',
  729. ' participant Replay as llm-replay adapter',
  730. ' participant ACP as acp-agent subprocess',
  731. ' participant Golden as stdout golden',
  732. ' Recorder->>Fixture: session.jsonl + workspace inputs',
  733. ' Fixture->>Workspace: seed files and hook configs',
  734. ' Fixture->>Replay: recorded StreamChunk script',
  735. ` Replay->>ACP: deterministic ${mermaidCode('llm/stream')} chunks`,
  736. ' ACP->>Workspace: bash, fs, and hook side effects',
  737. ' ACP->>Golden: normalized sessionUpdate stream',
  738. ' Golden-->>ACP: diff must be empty',
  739. '```',
  740. '',
  741. '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.',
  742. '',
  743. ...maintenanceFooter(maintenance),
  744. ].join('\n')
  745. }
  746. function renderDocs(): GraphDoc[] {
  747. const pkgs = collectPackageGraph(root, GROUP_ORDER, 'gen-doc-graphs')
  748. const docs: GraphDoc[] = [
  749. { rel: 'docs/capability-seams.md', content: renderCapabilitySeams(pkgs) },
  750. ...APP_EXAMPLES.map(example => ({ rel: example.rel, content: renderAppComposition(example) })),
  751. { rel: 'docs/event-producer-consumer.md', content: renderEventRelations(pkgs) },
  752. { rel: 'docs/agent-lifecycle.md', content: renderLifecycle() },
  753. { rel: 'docs/tool-execution-pipeline.md', content: renderToolPipeline() },
  754. { rel: 'packages/ui/acp/snapshot-replay.md', content: renderSnapshotReplay() },
  755. ]
  756. docs.unshift({ rel: 'docs/graph-atlas.md', content: renderIndex(docs) })
  757. return docs
  758. }
  759. function renderIndex(docs: GraphDoc[]): string {
  760. const labels: Record<string, string> = {
  761. 'docs/capability-seams.md': 'capability seams and core services',
  762. 'examples/echo-agent/composition.md': 'echo-agent app composition',
  763. 'examples/coding-agent/composition.md': 'coding-agent app composition',
  764. 'examples/cordis-agent/composition.md': 'cordis-agent app composition',
  765. 'examples/acp-agent/composition.md': 'acp-agent app composition',
  766. 'docs/event-producer-consumer.md': 'event producer/consumer matrix',
  767. 'docs/agent-lifecycle.md': 'agent turn and step lifecycle',
  768. 'docs/tool-execution-pipeline.md': 'tool execution pipeline',
  769. 'packages/ui/acp/snapshot-replay.md': 'ACP snapshot replay',
  770. }
  771. const modes: Record<string, string> = {
  772. 'docs/capability-seams.md': 'hybrid generated',
  773. 'examples/echo-agent/composition.md': 'hybrid generated',
  774. 'examples/coding-agent/composition.md': 'hybrid generated',
  775. 'examples/cordis-agent/composition.md': 'hybrid generated',
  776. 'examples/acp-agent/composition.md': 'hybrid generated',
  777. 'docs/event-producer-consumer.md': 'hybrid generated',
  778. 'docs/agent-lifecycle.md': 'curated',
  779. 'docs/tool-execution-pipeline.md': 'curated',
  780. 'packages/ui/acp/snapshot-replay.md': 'curated',
  781. }
  782. const rows = [
  783. '| [module dependency graph](module-graph.md) | `generated` |',
  784. '| [tool schema catalog and package map](tool-catalog.md) | `generated` |',
  785. ...docs.map((doc) => {
  786. const link = graphIndexLink(doc.rel)
  787. return `| [${labels[doc.rel] ?? link}](${link}) | \`${modes[doc.rel] ?? 'generated'}\` |`
  788. }),
  789. ]
  790. const maintenance = 'mixed: each linked page declares generated, hybrid, or curated mode'
  791. return [
  792. ...generatedHeader('Documentation Graph Index'),
  793. '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).',
  794. '',
  795. 'The process decision behind this index is recorded in [the documentation graph RFC](rfc/implemented/process/2026-07-03-documentation-graph-atlas.md).',
  796. '',
  797. '| Graph | Mode |',
  798. '| --- | --- |',
  799. ...rows,
  800. '',
  801. 'Regenerate with `pnpm run gen-doc-graphs`; verify freshness with `pnpm run verify-doc-graphs`.',
  802. '',
  803. ...maintenanceFooter(maintenance),
  804. ].join('\n')
  805. }
  806. function main(): void {
  807. const docs = renderDocs()
  808. if (process.argv.includes('--check')) {
  809. const stale: string[] = []
  810. for (const doc of docs) {
  811. const abs = resolve(root, doc.rel)
  812. const committed = existsSync(abs) ? readFileSync(abs, 'utf8') : null
  813. if (committed !== doc.content) stale.push(doc.rel)
  814. }
  815. if (stale.length === 0) {
  816. console.log(`gen-doc-graphs: ${docs.length} graph doc(s) are up to date.`)
  817. return
  818. }
  819. console.error(`gen-doc-graphs: stale graph doc(s): ${stale.join(', ')}. Run \`pnpm run gen-doc-graphs\` and commit the result.`)
  820. process.exit(1)
  821. }
  822. for (const doc of docs) {
  823. mkdirSync(dirname(resolve(root, doc.rel)), { recursive: true })
  824. writeFileSync(resolve(root, doc.rel), doc.content)
  825. }
  826. console.log(`gen-doc-graphs: wrote ${docs.length} graph doc(s).`)
  827. }
  828. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  829. main()
  830. }