gen-doc-graphs.ts 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  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, 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. import { TypeScriptProject } from './ts-project.ts'
  18. const root = resolve(import.meta.dirname, '..')
  19. type Pkg = PackageGraphNode
  20. interface GraphDoc {
  21. rel: string
  22. content: string
  23. }
  24. interface ServiceRole {
  25. key: string
  26. pkg: string
  27. title: string
  28. mode: 'core' | 'seam' | 'bundle'
  29. implementations?: string[]
  30. consumers?: string[]
  31. companions?: string[]
  32. note: string
  33. }
  34. interface ExamplePlugin {
  35. id: string
  36. name: string
  37. }
  38. interface EventRelation {
  39. dispatchers: Map<string, Set<string>>
  40. listeners: Set<string>
  41. }
  42. interface PackageSource {
  43. rel: string
  44. pkg: string
  45. sourceFile: ts.SourceFile
  46. }
  47. type EventReceiverKind = 'context' | 'agent-dispatch' | 'events-service'
  48. const GROUP_ORDER = [
  49. 'util',
  50. 'llm',
  51. 'core',
  52. 'bash',
  53. 'sandbox',
  54. 'fs',
  55. 'skill',
  56. 'compact',
  57. 'subagent',
  58. 'tasks',
  59. 'workflow',
  60. 'web',
  61. 'spill',
  62. 'todo',
  63. 'cordis',
  64. 'hooks',
  65. 'session-persistence',
  66. 'session-query',
  67. 'support',
  68. 'ui',
  69. ]
  70. const SERVICE_ROLES: ServiceRole[] = [
  71. {
  72. key: 'llm',
  73. pkg: 'llm',
  74. title: 'LLM adapter registry',
  75. mode: 'seam',
  76. implementations: ['llm-deepseek', 'llm-pi-ai', 'llm-replay'],
  77. consumers: ['agent-loop', 'compact-basic'],
  78. note: 'Adapters register provider implementations; the loop and compaction call the provider-neutral stream service.',
  79. },
  80. {
  81. key: 'tokenMeter',
  82. pkg: 'token-meter',
  83. title: 'Replay token measurement',
  84. mode: 'core',
  85. consumers: ['compact-basic'],
  86. note: 'Owns isolated per-session replay folds; pressure consumers share immutable revisioned measurements.',
  87. },
  88. {
  89. key: 'sessions',
  90. pkg: 'session',
  91. title: 'In-memory session store',
  92. mode: 'core',
  93. consumers: ['agent-loop', 'agent', 'cli-demo', 'session-persistence', 'session-query', 'subagent-inprocess', 'invariants'],
  94. note: 'Owns append-only Session instances and emits the durable session event feed.',
  95. },
  96. {
  97. key: 'sessionPersistence',
  98. pkg: 'session-persistence',
  99. title: 'Durable session persistence seam',
  100. mode: 'seam',
  101. implementations: ['session-persistence-jsonl', 'session-persistence-sqlite'],
  102. consumers: ['agent-loop', 'tool-bash', 'hooks-claude', 'hooks-codex', 'acp', 'session-query'],
  103. note: 'Backends persist the same SessionEvent vocabulary; apps choose a backend at composition time.',
  104. },
  105. {
  106. key: 'sessionQuery',
  107. pkg: 'session-query',
  108. title: 'Exact session-history reads and traces',
  109. mode: 'seam',
  110. note: 'Resolves live and optional persisted logs into one logical corpus for exact reads and relationship traces.',
  111. },
  112. {
  113. key: 'systemPrompt',
  114. pkg: 'system-prompt',
  115. title: 'System prompt assembly registry',
  116. mode: 'core',
  117. consumers: ['agent-loop', 'tools', 'tool-fs', 'tool-web'],
  118. note: 'Collects prompt sections and model-facing tool schemas for each step.',
  119. },
  120. {
  121. key: 'tools',
  122. pkg: 'tools',
  123. title: 'Tool registry and guarded execution pipeline',
  124. mode: 'core',
  125. consumers: ['agent-loop', 'tool-ask-user', 'tool-bash', 'tool-cordis', 'tool-fs', 'tool-skill', 'tool-subagent', 'tool-todo', 'tool-web', 'acp'],
  126. note: 'Registers capabilities, owns Code Mode transport, and routes calls through pre-policy, monotonic guards, around dispatch, post-policy, and final-result observation.',
  127. },
  128. {
  129. key: 'userInteraction',
  130. pkg: 'user-interaction',
  131. title: 'Human question/answer seam',
  132. mode: 'seam',
  133. implementations: ['stdio-demo', 'acp'],
  134. consumers: ['tool-ask-user', 'stdio-demo', 'acp'],
  135. note: 'UI front doors provide the active human-answer provider; tool-ask-user pauses a tool call on the provider-neutral ask() promise.',
  136. },
  137. {
  138. key: 'skills',
  139. pkg: 'skill',
  140. title: 'Skill provider registry',
  141. mode: 'seam',
  142. implementations: ['skill-local'],
  143. consumers: ['tool-skill'],
  144. note: 'Merges provider skill catalogs; tool-skill renders the session-prefix catalog and loads complete skill bodies.',
  145. },
  146. {
  147. key: 'agents',
  148. pkg: 'agent',
  149. title: 'Agent service',
  150. mode: 'core',
  151. consumers: ['agent-loop', 'acp', 'cli-demo', 'subagent-inprocess', 'stdio-demo', 'invariants'],
  152. note: 'Owns live Agent handles, the create/resume factory seam, and process-local initiator propagation.',
  153. },
  154. {
  155. key: 'agentLoop',
  156. pkg: 'agent-loop',
  157. title: 'Concrete loop driver',
  158. mode: 'bundle',
  159. consumers: ['agent-spine-demo'],
  160. note: 'The one concrete loop plugin; extension packages depend on dsh-agent events and services, not on this package.',
  161. },
  162. {
  163. key: 'bash',
  164. pkg: 'bash',
  165. title: 'Bash executor seam',
  166. mode: 'seam',
  167. implementations: ['bash-local', 'bash-sandbox'],
  168. consumers: ['tool-bash', 'hooks-claude', 'hooks-codex'],
  169. note: 'The model-facing bash tools and hook bridges consume this seam; sandboxed or remote executors replace bash-local without touching them.',
  170. },
  171. {
  172. key: 'bashEnv',
  173. pkg: 'tool-bash',
  174. title: 'Managed bash environment registry',
  175. mode: 'core',
  176. note: 'Plugins declare effect-scoped DSH_* facts; tool-bash collects one trusted snapshot per execution and the executor rebuilds the namespace.',
  177. },
  178. {
  179. key: 'sandbox',
  180. pkg: 'sandbox',
  181. title: 'Process-sandbox seam',
  182. mode: 'seam',
  183. implementations: ['sandbox-local'],
  184. consumers: ['bash-sandbox'],
  185. 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.',
  186. },
  187. {
  188. key: 'sandboxPolicy',
  189. pkg: 'sandbox-policy',
  190. title: 'Sandbox policy home',
  191. mode: 'core',
  192. implementations: [],
  193. consumers: ['bash-sandbox', 'fs-sandbox'],
  194. note: 'The one home for the deployment default mode + workspace root; only the sandboxed executor and provider read the service (the tool layers use the pure `sandbox/mode` fold it also exports). Both enforcing families read it so bash and fs cannot confine to different roots.',
  195. },
  196. {
  197. key: 'approval',
  198. pkg: 'approval',
  199. title: 'Approval seam',
  200. mode: 'seam',
  201. implementations: ['acp'],
  202. consumers: ['tools', 'tool-bash'],
  203. 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`.',
  204. },
  205. {
  206. key: 'permission',
  207. pkg: 'permission',
  208. title: 'Permission presets',
  209. mode: 'core',
  210. implementations: [],
  211. consumers: ['acp'],
  212. 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.',
  213. },
  214. {
  215. key: 'codeRuntime',
  216. pkg: 'code-runtime',
  217. title: 'Code-execution seam',
  218. mode: 'seam',
  219. implementations: ['code-runtime-worker'],
  220. consumers: ['tools'],
  221. 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).',
  222. },
  223. {
  224. key: 'fs',
  225. pkg: 'fs',
  226. title: 'Filesystem provider seam',
  227. mode: 'seam',
  228. implementations: ['fs-local', 'fs-sandbox'],
  229. consumers: ['tool-fs'],
  230. companions: ['fs-policy'],
  231. note: 'tool-fs executes read/write/edit through ctx.fs; fs-sandbox fences mutations by the shared sandbox mode; fs-policy contributes observed-state checks through the fs/* event gate.',
  232. },
  233. {
  234. key: 'compact',
  235. pkg: 'compact',
  236. title: 'Compaction seam',
  237. mode: 'seam',
  238. implementations: ['compact-basic'],
  239. consumers: ['compact-basic'],
  240. note: 'The basic backend consumes post-step pressure and request-error recovery events; a model-facing compact tool remains deferred.',
  241. },
  242. {
  243. key: 'subagents',
  244. pkg: 'subagent',
  245. title: 'Subagent provider registry',
  246. mode: 'seam',
  247. implementations: ['subagent-spawn', 'subagent-fork', 'subagent-acp'],
  248. consumers: ['tool-subagent'],
  249. note: 'Providers implement transports; tool-subagent exposes one configured provider as a model-facing tool name.',
  250. },
  251. {
  252. key: 'tasks',
  253. pkg: 'tasks',
  254. title: 'Background task registry',
  255. mode: 'core',
  256. consumers: ['tool-bash', 'tool-subagent', 'tool-tasks'],
  257. 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.',
  258. },
  259. {
  260. key: 'web',
  261. pkg: 'web',
  262. title: 'Web access provider registry',
  263. mode: 'seam',
  264. implementations: ['web-search-exa', 'web-search-perplexity', 'web-search-deepseek', 'web-fetch-local'],
  265. consumers: ['tool-web'],
  266. note: 'Search and fetch providers register into one ctx.web seam; tool-web owns the stable model-facing names.',
  267. },
  268. {
  269. key: 'spillStore',
  270. pkg: 'spill',
  271. title: 'Spill storage seam',
  272. mode: 'seam',
  273. implementations: ['spill-local'],
  274. consumers: ['spill-policy'],
  275. note: 'The backend saves oversized tool text and returns a model-facing locator plus retrieval hint; spill-policy is the tools/post-execute consumer that decides when to spill.',
  276. },
  277. {
  278. key: 'workflows',
  279. pkg: 'workflow',
  280. title: 'Workflow script engine',
  281. mode: 'seam',
  282. implementations: ['workflow-workerthread'],
  283. consumers: ['tool-workflow'],
  284. note: 'One engine per context (bash shape, no named-provider registry); the worker-thread engine fans agent() calls out through ctx.subagents.',
  285. },
  286. ]
  287. function generatedHeader(title: string): string[] {
  288. return [
  289. '<!-- Generated by scripts/gen-doc-graphs.ts - do not edit by hand.',
  290. ' Run `pnpm run gen-doc-graphs` to regenerate. -->',
  291. '',
  292. `# ${title}`,
  293. '',
  294. ]
  295. }
  296. function maintenanceFooter(source: string): string[] {
  297. return [`Maintenance mode: ${source}.`, '']
  298. }
  299. function graphIndexLink(rel: string): string {
  300. return relative('docs', rel).replaceAll('\\', '/')
  301. }
  302. function linkFromDoc(docRel: string, targetRel: string): string {
  303. return relative(dirname(docRel), targetRel).replaceAll('\\', '/')
  304. }
  305. function mermaidCode(value: string): string {
  306. return `<code>${value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</code>`
  307. }
  308. function repoLink(path: string, label: string, up = '..'): string {
  309. return `[${label}](${up}/${path})`
  310. }
  311. function sourceLink(source: string, up = '..'): string {
  312. return repoLink(source.split(':')[0] ?? source, `\`${source}\``, up)
  313. }
  314. function pkgLink(pkg: Pkg | undefined, fallback: string, up = '..'): string {
  315. return pkg ? repoLink(pkg.rel, `\`${pkg.short}\``, up) : `\`${fallback}\``
  316. }
  317. function pkgList(names: string[] | undefined, pkgsByShort: Map<string, Pkg>): string {
  318. if (!names || names.length === 0) return '-'
  319. return names.map(name => pkgLink(pkgsByShort.get(name), name)).join(', ')
  320. }
  321. function tableCell(value: string): string {
  322. return value.replace(/\|/g, '\\|').replace(/\n/g, '<br>')
  323. }
  324. function assertServiceRolesComplete(): void {
  325. const discovered = new Set(collectServices().map(service => service.key))
  326. const classified = new Set(SERVICE_ROLES.map(role => role.key))
  327. const missing = [...discovered].filter(key => !classified.has(key)).sort()
  328. const stale = [...classified].filter(key => !discovered.has(key)).sort()
  329. if (missing.length || stale.length) {
  330. throw new Error([
  331. missing.length ? `missing service role classification: ${missing.join(', ')}` : '',
  332. stale.length ? `stale service role classification: ${stale.join(', ')}` : '',
  333. ].filter(Boolean).join('; '))
  334. }
  335. }
  336. function renderCapabilitySeams(pkgs: Pkg[]): string {
  337. assertServiceRolesComplete()
  338. const pkgsByShort = new Map(pkgs.map(pkg => [pkg.short, pkg]))
  339. 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'
  340. const nodes = new Map<string, string>()
  341. const edges = new Set<string>()
  342. const companionEdges = new Set<string>()
  343. const addNode = (id: string, label: string): void => {
  344. if (!nodes.has(id)) nodes.set(id, ` ${id}["${escLabel(label)}"]`)
  345. }
  346. const addEdge = (from: string, to: string): void => { edges.add(` ${from} --> ${to}`) }
  347. const lines = generatedHeader('Capability Seams And Core Services')
  348. lines.push(
  349. '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.',
  350. '',
  351. '```mermaid',
  352. 'flowchart LR',
  353. )
  354. for (const role of SERVICE_ROLES) {
  355. const svc = nodeId('svc', role.key)
  356. const owner = nodeId('pkg', role.pkg)
  357. addNode(owner, role.pkg)
  358. addNode(svc, `ctx.${role.key}<br/>${role.title}`)
  359. addEdge(owner, svc)
  360. for (const impl of role.implementations ?? []) {
  361. addNode(nodeId('pkg', impl), impl)
  362. addEdge(nodeId('pkg', impl), svc)
  363. }
  364. for (const consumer of role.consumers ?? []) {
  365. addNode(nodeId('pkg', consumer), consumer)
  366. addEdge(svc, nodeId('pkg', consumer))
  367. }
  368. for (const companion of role.companions ?? []) {
  369. addNode(nodeId('pkg', companion), companion)
  370. companionEdges.add(` ${svc} -. event gate .-> ${nodeId('pkg', companion)}`)
  371. }
  372. }
  373. lines.push(...nodes.values(), ...[...edges].sort(), ...[...companionEdges].sort())
  374. lines.push('```', '', '| ctx key | Role | Owner | Implementations | Direct consumers | Companion plugins | Note |', '| --- | --- | --- | --- | --- | --- | --- |')
  375. for (const role of SERVICE_ROLES) {
  376. 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)} |`)
  377. }
  378. lines.push('', ...maintenanceFooter(maintenance))
  379. return lines.join('\n')
  380. }
  381. function parseExampleCordis(rel: string): ExamplePlugin[] {
  382. const text = readFileSync(resolve(root, rel), 'utf8')
  383. const plugins: ExamplePlugin[] = []
  384. let current: { id: string; name?: string } | null = null
  385. const flush = (): void => {
  386. if (current?.name) plugins.push({ id: current.id, name: current.name })
  387. }
  388. for (const line of text.split('\n')) {
  389. const id = /^-\s+id:\s+(.+?)\s*$/.exec(line)
  390. if (id?.[1] !== undefined) {
  391. flush()
  392. current = { id: stripYamlScalar(id[1]) }
  393. continue
  394. }
  395. const name = /^\s+name:\s+(.+?)\s*$/.exec(line)
  396. if (name?.[1] !== undefined && current) current.name = stripYamlScalar(name[1])
  397. }
  398. flush()
  399. return plugins
  400. }
  401. function stripYamlScalar(value: string): string {
  402. return value.trim().replace(/^['"]|['"]$/g, '')
  403. }
  404. const APP_EXAMPLES = [
  405. {
  406. id: 'echo',
  407. rel: 'examples/echo-agent/composition.md',
  408. title: 'Echo Agent App Composition',
  409. label: 'examples/echo-agent',
  410. config: 'examples/echo-agent/cordis.yml',
  411. 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.',
  412. },
  413. {
  414. id: 'repl',
  415. rel: 'examples/repl-agent/composition.md',
  416. title: 'REPL Agent App Composition',
  417. label: 'examples/repl-agent',
  418. config: 'examples/repl-agent/cordis.yml',
  419. summary: 'The REPL agent demo adds the real DeepSeek adapter, filesystem tools, todo_write, compaction, and both subagent transports on top of the stdio app package.',
  420. },
  421. {
  422. id: 'tui',
  423. rel: 'examples/tui-agent/composition.md',
  424. title: 'TUI Agent App Composition',
  425. label: 'examples/tui-agent',
  426. config: 'examples/tui-agent/cordis.yml',
  427. summary: 'The TUI agent reuses the repl-agent backend and tool composition while fixing the shared terminal app to the full-screen dsh-tui front door.',
  428. },
  429. {
  430. id: 'headless',
  431. rel: 'examples/headless-agent/composition.md',
  432. title: 'Headless Agent App Composition',
  433. label: 'examples/headless-agent',
  434. config: 'examples/headless-agent/cordis.yml',
  435. summary: 'The headless demo combines the real DeepSeek adapter and coding capabilities with the one-shot app package, format-pure stdout, and one fresh persisted top-level session.',
  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, exampleId: string): void {
  456. const agentCore = nodeId('bundle', 'agent_core')
  457. const jsonl = nodeId('bundle', 'jsonl')
  458. lines.push(` ${appNode} --> ${agentCore}["@deepseek-ai/dsh-agent-spine-demo"]`)
  459. lines.push(` ${appNode} --> ${jsonl}["@deepseek-ai/dsh-session-persistence-jsonl"]`)
  460. if (pluginName === '@deepseek-ai/dsh-stdio-demo') {
  461. const frontDoor = exampleId === 'tui'
  462. ? '@deepseek-ai/dsh-tui<br/>pre-created main agent'
  463. : exampleId === 'repl'
  464. ? '@deepseek-ai/dsh-stdio<br/>pre-created main agent'
  465. : 'dsh-tui (TTY) / dsh-stdio (pipes)<br/>pre-created main agent'
  466. lines.push(` ${appNode} --> ${nodeId('frontdoor', 'stdio')}["${frontDoor}"]`)
  467. } else if (pluginName === '@deepseek-ai/dsh-cli-demo') {
  468. lines.push(` ${appNode} --> ${nodeId('frontdoor', 'cli')}["one-shot driver<br/>format-pure stdout<br/>fresh top-level agent"]`)
  469. } else if (pluginName === '@deepseek-ai/dsh-acp-demo') {
  470. lines.push(` ${appNode} --> ${nodeId('frontdoor', 'acp')}["@deepseek-ai/dsh-acp<br/>JSON-RPC stdio bridge<br/>sessions created by client"]`)
  471. }
  472. lines.push(
  473. ` ${agentCore} --> ${nodeId('spine', 'llm')}["ctx.llm"]`,
  474. ` ${agentCore} --> ${nodeId('spine', 'sessions')}["ctx.sessions"]`,
  475. ` ${agentCore} --> ${nodeId('spine', 'tools')}["ctx.tools + tool-bash"]`,
  476. ` ${agentCore} --> ${nodeId('spine', 'loop')}["ctx.agents + ctx.agentLoop"]`,
  477. )
  478. }
  479. function renderAppComposition(example: AppExample): string {
  480. const plugins = parseExampleCordis(example.config)
  481. const maintenance = 'hybrid: the leaf plugin list is parsed from its `cordis.yml`; app package expansion is curated from package source'
  482. const lines = generatedHeader(example.title)
  483. lines.push(
  484. example.summary,
  485. '',
  486. '```mermaid',
  487. 'flowchart LR',
  488. ` cfg["${escLabel(example.label)}<br/>cordis.yml"]`,
  489. )
  490. for (const plugin of plugins) {
  491. const pluginNode = nodeId(`plugin_${example.id}`, plugin.id)
  492. lines.push(` ${pluginNode}["${escLabel(plugin.id)}<br/>${escLabel(plugin.name)}"]`)
  493. lines.push(` cfg --> ${pluginNode}`)
  494. if (plugin.name === '@deepseek-ai/dsh-stdio-demo' || plugin.name === '@deepseek-ai/dsh-cli-demo' || plugin.name === '@deepseek-ai/dsh-acp-demo') {
  495. renderAppExpansion(lines, pluginNode, plugin.name, example.id)
  496. }
  497. }
  498. lines.push(
  499. '```',
  500. '',
  501. '| Plugin id | Package / module |',
  502. '| --- | --- |',
  503. ...plugins.map(plugin => `| \`${plugin.id}\` | \`${plugin.name}\` |`),
  504. '',
  505. `Source config: [\`${example.config}\`](${linkFromDoc(example.rel, example.config)}).`,
  506. )
  507. lines.push('', ...maintenanceFooter(maintenance))
  508. return lines.join('\n')
  509. }
  510. /** Collect event dispatch/listener relations from real cross-file receiver types. */
  511. class EventRelationCollector {
  512. private readonly relations = new Map<string, EventRelation>()
  513. private readonly callSites = new Map<ts.SignatureDeclaration | ts.JSDocSignature, ts.CallExpression[]>()
  514. private readonly contextType: ts.Type
  515. private readonly agentDispatchType: ts.Type
  516. private readonly eventsServiceType: ts.Type
  517. constructor(
  518. private readonly project: TypeScriptProject,
  519. private readonly sources: readonly PackageSource[],
  520. ) {
  521. this.contextType = this.declaredType('vendor/cordis/src/context.ts', 'Context')
  522. this.agentDispatchType = this.declaredType('packages/core/agent/src/dispatch.ts', 'AgentEventDispatch')
  523. this.eventsServiceType = this.declaredType('vendor/cordis/src/events.ts', 'EventsService')
  524. this.indexCallSites()
  525. }
  526. /** Return all event relations discovered from the Program. */
  527. collect(): Map<string, EventRelation> {
  528. for (const source of this.sources) this.visitSource(source)
  529. return this.relations
  530. }
  531. /** Resolve one named class/interface declaration to its merged instance type. */
  532. private declaredType(relativePath: string, name: string): ts.Type {
  533. const sourceFile = this.project.sourceFile(relativePath)
  534. const declaration = sourceFile.statements.find((statement): statement is ts.ClassDeclaration | ts.InterfaceDeclaration => {
  535. return (ts.isClassDeclaration(statement) || ts.isInterfaceDeclaration(statement)) && statement.name?.text === name
  536. })
  537. const symbol = declaration?.name && this.project.checker.getSymbolAtLocation(declaration.name)
  538. if (!symbol) throw new Error(`cannot resolve TypeScript type ${name} from ${relativePath}`)
  539. return this.project.checker.getDeclaredTypeOfSymbol(symbol)
  540. }
  541. /** Index resolved local function calls for narrow argument-flow recovery. */
  542. private indexCallSites(): void {
  543. const visit = (node: ts.Node): void => {
  544. if (ts.isCallExpression(node)) {
  545. const declaration = this.project.checker.getResolvedSignature(node)?.declaration
  546. if (declaration) {
  547. const calls = this.callSites.get(declaration) ?? []
  548. calls.push(node)
  549. this.callSites.set(declaration, calls)
  550. }
  551. }
  552. ts.forEachChild(node, visit)
  553. }
  554. for (const source of this.sources) visit(source.sourceFile)
  555. }
  556. /** Walk one package source file and classify event API calls by receiver type. */
  557. private visitSource(source: PackageSource): void {
  558. const visit = (node: ts.Node): void => {
  559. if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
  560. const receiverKind = this.receiverKind(node.expression.expression)
  561. const method = node.expression.name.text
  562. if (receiverKind === 'events-service' && method === 'dispatch') {
  563. const argumentList = node.arguments[1]
  564. if (argumentList) {
  565. for (const event of this.eventNamesFromArgumentList(argumentList, new Set())) {
  566. this.addDispatcher(event, source.pkg, 'events.dispatch')
  567. }
  568. }
  569. } else if (receiverKind === 'context' || receiverKind === 'agent-dispatch') {
  570. const eventNames = this.eventNamesFromCall(node, receiverKind)
  571. if (method === 'on' || method === 'once') {
  572. for (const event of eventNames) this.ensure(event).listeners.add(source.pkg)
  573. } else if (method === 'emit' || method === 'parallel' || method === 'serial' || method === 'waterfall') {
  574. for (const event of eventNames) this.addDispatcher(event, source.pkg, method)
  575. }
  576. }
  577. }
  578. ts.forEachChild(node, visit)
  579. }
  580. visit(source.sourceFile)
  581. }
  582. /** Classify a receiver using assignability to the repository's actual event API types. */
  583. private receiverKind(receiver: ts.Expression): EventReceiverKind | undefined {
  584. const type = this.project.checker.getTypeAtLocation(receiver)
  585. if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never)) return undefined
  586. if (this.project.checker.isTypeAssignableTo(type, this.eventsServiceType)) return 'events-service'
  587. if (this.project.checker.isTypeAssignableTo(type, this.contextType)) return 'context'
  588. if (this.project.checker.isTypeAssignableTo(type, this.agentDispatchType)) return 'agent-dispatch'
  589. return undefined
  590. }
  591. /** Resolve the event-name argument for Context and fused agent dispatch calls. */
  592. private eventNamesFromCall(call: ts.CallExpression, receiverKind: Exclude<EventReceiverKind, 'events-service'>): Set<string> {
  593. const candidates = receiverKind === 'context' ? call.arguments.slice(0, 2) : call.arguments.slice(0, 1)
  594. for (const candidate of candidates) {
  595. const values = this.finiteStringValues(candidate)
  596. if (values) return values
  597. }
  598. return new Set()
  599. }
  600. /** Recover the event slot from the argument array handed to EventsService.dispatch(). */
  601. private eventNamesFromArgumentList(expression: ts.Expression, seen: Set<ts.Node>): Set<string> {
  602. const current = unwrapExpression(expression)
  603. if (seen.has(current)) return new Set()
  604. seen.add(current)
  605. if (ts.isArrayLiteralExpression(current)) {
  606. for (const element of current.elements.slice(0, 2)) {
  607. if (ts.isOmittedExpression(element) || ts.isSpreadElement(element)) continue
  608. const values = this.finiteStringValues(element)
  609. if (values) return values
  610. }
  611. return new Set()
  612. }
  613. if (ts.isConditionalExpression(current)) {
  614. return unionSets(
  615. this.eventNamesFromArgumentList(current.whenTrue, new Set(seen)),
  616. this.eventNamesFromArgumentList(current.whenFalse, new Set(seen)),
  617. )
  618. }
  619. if (!ts.isIdentifier(current)) return new Set()
  620. const symbol = this.project.checker.getSymbolAtLocation(current)
  621. if (!symbol) return new Set()
  622. const events = new Set<string>()
  623. for (const declaration of symbol.declarations ?? []) {
  624. if (ts.isVariableDeclaration(declaration) && declaration.initializer && isConstDeclaration(declaration)) {
  625. addAll(events, this.eventNamesFromArgumentList(declaration.initializer, new Set(seen)))
  626. } else if (ts.isParameter(declaration)) {
  627. addAll(events, this.eventNamesFromParameter(declaration, seen))
  628. }
  629. }
  630. return events
  631. }
  632. /** Follow a non-exported local helper parameter back to every resolved call site. */
  633. private eventNamesFromParameter(parameter: ts.ParameterDeclaration, seen: Set<ts.Node>): Set<string> {
  634. const owner = parameter.parent
  635. if (!ts.isFunctionDeclaration(owner) || hasExportModifier(owner)) return new Set()
  636. const index = owner.parameters.indexOf(parameter)
  637. if (index < 0) return new Set()
  638. const events = new Set<string>()
  639. for (const call of this.callSites.get(owner) ?? []) {
  640. const argument = call.arguments[index]
  641. if (argument) addAll(events, this.eventNamesFromArgumentList(argument, new Set(seen)))
  642. }
  643. return events
  644. }
  645. /** Return a finite string-literal value set, rejecting widened and generic strings. */
  646. private finiteStringValues(expression: ts.Expression): Set<string> | undefined {
  647. const current = unwrapExpression(expression)
  648. if (ts.isStringLiteralLike(current)) return new Set([current.text])
  649. if (this.isForwardedAgentEventParameter(current)) return undefined
  650. return finiteStringTypeValues(this.project.checker.getTypeAtLocation(current))
  651. }
  652. /** Reject the contextual parameter inside the AgentEventDispatch forwarding object. */
  653. private isForwardedAgentEventParameter(expression: ts.Expression): boolean {
  654. if (!ts.isIdentifier(expression)) return false
  655. const declarations = this.project.checker.getSymbolAtLocation(expression)?.declarations ?? []
  656. return declarations.some((declaration) => {
  657. if (!ts.isParameter(declaration)) return false
  658. const method = declaration.parent
  659. if (!ts.isMethodDeclaration(method) || !ts.isObjectLiteralExpression(method.parent)) return false
  660. const contextualType = this.project.checker.getContextualType(method.parent)
  661. return contextualType !== undefined
  662. && this.project.checker.isTypeAssignableTo(contextualType, this.agentDispatchType)
  663. })
  664. }
  665. /** Get or create one relation row. */
  666. private ensure(event: string): EventRelation {
  667. const existing = this.relations.get(event)
  668. if (existing) return existing
  669. const relation = { dispatchers: new Map<string, Set<string>>(), listeners: new Set<string>() }
  670. this.relations.set(event, relation)
  671. return relation
  672. }
  673. /** Add one dispatcher method without duplicating package/method labels. */
  674. private addDispatcher(event: string, pkg: string, method: string): void {
  675. const relation = this.ensure(event)
  676. const methods = relation.dispatchers.get(pkg) ?? new Set<string>()
  677. methods.add(method)
  678. relation.dispatchers.set(pkg, methods)
  679. }
  680. }
  681. /** Peel syntax-only wrappers that do not change an expression's runtime value. */
  682. function unwrapExpression(expression: ts.Expression): ts.Expression {
  683. let current = expression
  684. while (
  685. ts.isParenthesizedExpression(current)
  686. || ts.isAsExpression(current)
  687. || ts.isTypeAssertionExpression(current)
  688. || ts.isNonNullExpression(current)
  689. || ts.isSatisfiesExpression(current)
  690. ) {
  691. current = current.expression
  692. }
  693. return current
  694. }
  695. /** Return every value only when a type is a closed string-literal union. */
  696. function finiteStringTypeValues(type: ts.Type): Set<string> | undefined {
  697. if (type.flags & ts.TypeFlags.StringLiteral) {
  698. return new Set([(type as ts.StringLiteralType).value])
  699. }
  700. if (type.flags & ts.TypeFlags.Never) return new Set()
  701. if (!type.isUnion()) return undefined
  702. const values = new Set<string>()
  703. for (const member of type.types) {
  704. const memberValues = finiteStringTypeValues(member)
  705. if (!memberValues) return undefined
  706. addAll(values, memberValues)
  707. }
  708. return values
  709. }
  710. /** Return whether a variable declaration belongs to a const declaration list. */
  711. function isConstDeclaration(declaration: ts.VariableDeclaration): boolean {
  712. return (declaration.parent.flags & ts.NodeFlags.Const) !== 0
  713. }
  714. /** Return whether a declaration is visible to callers outside its source module. */
  715. function hasExportModifier(node: ts.Node): boolean {
  716. return ts.canHaveModifiers(node) && (ts.getModifiers(node)?.some((modifier) => {
  717. return modifier.kind === ts.SyntaxKind.ExportKeyword || modifier.kind === ts.SyntaxKind.DefaultKeyword
  718. }) ?? false)
  719. }
  720. /** Add every member of source to target. */
  721. function addAll<T>(target: Set<T>, source: ReadonlySet<T>): void {
  722. for (const value of source) target.add(value)
  723. }
  724. /** Return the union of two sets without mutating either input. */
  725. function unionSets<T>(left: ReadonlySet<T>, right: ReadonlySet<T>): Set<T> {
  726. const out = new Set(left)
  727. addAll(out, right)
  728. return out
  729. }
  730. function collectEventRelations(): Map<string, EventRelation> {
  731. const project = new TypeScriptProject(root)
  732. const sources = project.sourceFiles().flatMap((sourceFile): PackageSource[] => {
  733. const rel = project.relativePath(sourceFile)
  734. const match = /^packages\/[^/]+\/([^/]+)\/src\/.+\.ts$/.exec(rel)
  735. return match?.[1] ? [{ rel, pkg: match[1], sourceFile }] : []
  736. }).sort((left, right) => left.rel.localeCompare(right.rel))
  737. return new EventRelationCollector(project, sources).collect()
  738. }
  739. function relationPackages(map: Map<string, Set<string>>, pkgsByShort: Map<string, Pkg>): string {
  740. if (map.size === 0) return '-'
  741. return [...map.entries()]
  742. .sort(([a], [b]) => a.localeCompare(b))
  743. .map(([pkg, methods]) => `${pkgLink(pkgsByShort.get(pkg), pkg)} (${[...methods].sort().map(m => `\`${m}\``).join(', ')})`)
  744. .join(', ')
  745. }
  746. function listenerPackages(listeners: Set<string>, pkgsByShort: Map<string, Pkg>): string {
  747. if (listeners.size === 0) return '-'
  748. return [...listeners].sort().map(pkg => pkgLink(pkgsByShort.get(pkg), pkg)).join(', ')
  749. }
  750. function renderEventRelations(pkgs: Pkg[]): string {
  751. const events = collectEvents()
  752. const relations = collectEventRelations()
  753. const pkgsByShort = new Map(pkgs.map(pkg => [pkg.short, pkg]))
  754. const maintenance = 'generated: Cordis event declarations and producer/listener edges are resolved from the repository TypeScript Program'
  755. const lines = generatedHeader('Event Producer And Consumer Matrix')
  756. lines.push(
  757. '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. Receiver and event-name types also cover contained dispatch sites that deliberately bypass `ctx.emit`, such as subagent lifecycle containment.',
  758. '',
  759. '| Event | Mode | Declared in | Dispatchers | Listeners |',
  760. '| --- | --- | --- | --- | --- |',
  761. )
  762. for (const event of [...events].sort((a, b) => a.name.localeCompare(b.name))) {
  763. const relation = relations.get(event.name) ?? { dispatchers: new Map<string, Set<string>>(), listeners: new Set<string>() }
  764. lines.push(`| \`${event.name}\` | \`${event.mode}\` | ${sourceLink(event.source)} | ${relationPackages(relation.dispatchers, pkgsByShort)} | ${listenerPackages(relation.listeners, pkgsByShort)} |`)
  765. }
  766. // Every declared event needs a dispatcher: zero means dead vocabulary or an
  767. // unrecognized semantic dispatch shape. Listener-free extension points remain valid.
  768. const undispatched = [...events]
  769. .filter(event => (relations.get(event.name)?.dispatchers.size ?? 0) === 0)
  770. .map(event => event.name)
  771. .sort()
  772. if (undispatched.length > 0) {
  773. throw new Error(
  774. `event-producer-consumer matrix: no dispatcher found for declared event${undispatched.length > 1 ? 's' : ''} `
  775. + `${undispatched.map(name => `"${name}"`).join(', ')} — dead vocabulary, or a dispatch shape the semantic scan misses `
  776. + '(teach scripts/gen-doc-graphs.ts the shape)',
  777. )
  778. }
  779. const declared = new Set(events.map(event => event.name))
  780. const extra = [...relations.keys()].filter(event => !declared.has(event)).sort()
  781. if (extra.length > 0) {
  782. lines.push('', '## Non-harness or undeclared event strings seen in package source', '', '| Event string | Dispatchers | Listeners |', '| --- | --- | --- |')
  783. for (const event of extra) {
  784. const relation = relations.get(event)
  785. if (!relation) continue
  786. lines.push(`| \`${event}\` | ${relationPackages(relation.dispatchers, pkgsByShort)} | ${listenerPackages(relation.listeners, pkgsByShort)} |`)
  787. }
  788. }
  789. lines.push('', ...maintenanceFooter(maintenance))
  790. return lines.join('\n')
  791. }
  792. function renderLifecycle(): string {
  793. const maintenance = 'curated Mermaid sequence; exact event signatures live in the generated Cordis catalog'
  794. return [
  795. ...generatedHeader('Agent Turn And Step Lifecycle'),
  796. '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/*`.',
  797. '',
  798. '```mermaid',
  799. 'sequenceDiagram',
  800. ' participant User',
  801. ' participant Agent',
  802. ' participant Driver',
  803. ' participant Hooks as hook listeners',
  804. ' participant Prompt as ctx.systemPrompt',
  805. ' participant LLM as ctx.llm',
  806. ' participant Tools as ctx.tools',
  807. ' participant Session',
  808. ' participant Persistence',
  809. ' participant SDK as UI or SDK listener',
  810. ' User->>Agent: send(content)',
  811. ` Agent-->>SDK: ${mermaidCode('agent/queued')}`,
  812. ' Agent->>Driver: queued work wakes driver',
  813. ` Driver-->>SDK: ${mermaidCode('agent/status')} running`,
  814. ` Driver->>Session: ${mermaidCode('turn/start')}`,
  815. ` Driver->>Hooks: ${mermaidCode('agent/prompt-submit')} waterfall`,
  816. ' Hooks-->>Driver: allow, block, or add context',
  817. ` Driver->>Session: ${mermaidCode('user/message')} or rejected ${mermaidCode('turn/end')}`,
  818. ` Driver->>Prompt: ${mermaidCode('system-prompt/assemble')} waterfall`,
  819. ` Driver-->>Driver: ${mermaidCode('agent/pre-step')} serial checkpoint`,
  820. ` Driver->>Session: ${mermaidCode('step/start')}`,
  821. ` Driver->>LLM: ${mermaidCode('agent/request')} waterfall, then ${mermaidCode('llm/stream')} waterfall`,
  822. ' LLM-->>Driver: StreamChunk*',
  823. ` Driver->>Session: ${mermaidCode('assistant/chunk')}*`,
  824. ` Session-->>SDK: ${mermaidCode('session/event')} ${mermaidCode('assistant/chunk')}*`,
  825. ' alt final adapter or terminal in-band request failure',
  826. ` Driver->>Session: ${mermaidCode('step/end')}`,
  827. ` Driver->>Hooks: ${mermaidCode('agent/request-error')} waterfall`,
  828. ' Hooks-->>Driver: retry in a new step or preserve the original error',
  829. ' else model request succeeded',
  830. ` Driver->>Hooks: ${mermaidCode('agent/step-result')} waterfall`,
  831. ` Driver->>Session: ${mermaidCode('assistant/message')}`,
  832. ' Driver->>Tools: classify pending call by executionMode',
  833. ' loop barriers and bounded rolling pool, reclassify before start',
  834. ' opt call starts',
  835. ` Driver->>Session: ${mermaidCode('tool/call')}`,
  836. ' Driver->>Tools: ordered pre, concurrent execute',
  837. ' Tools-->>Session: tool-owned events when applicable',
  838. ' end',
  839. ' opt next model-order result ready',
  840. ' Driver->>Tools: ordered post',
  841. ` Driver->>Session: ${mermaidCode('tool/result')}`,
  842. ' end',
  843. ' end',
  844. ' Driver->>Session: post-tool context and steering',
  845. ` Driver->>Hooks: ${mermaidCode('agent/post-step')} serial checkpoint`,
  846. ` Driver->>Session: ${mermaidCode('step/end')}`,
  847. ` Driver->>Hooks: ${mermaidCode('agent/turn-continuation')} waterfall`,
  848. ` Driver->>Hooks: ${mermaidCode('agent/turn-stop')} serial terminal checkpoint`,
  849. ' end',
  850. ` Driver->>Session: ${mermaidCode('turn/end')}`,
  851. ` Driver->>Persistence: ${mermaidCode('session/flush')} parallel checkpoint`,
  852. ` Driver-->>SDK: ${mermaidCode('agent/status')} idle`,
  853. '```',
  854. '',
  855. 'The `assistant/message` edge records every successful provider call, including content-less and `max-tokens` finishes. Empty content stays out of derived history while the durable anchor retains usage and exact chunk provenance, including an explicit empty source set.',
  856. '',
  857. '`dsh-compact-basic` uses `agent/post-step` for pressure after those durable facts and `agent/request-error` only for canonical context overflow. Recovery compacts between the closed failed step and a fresh retry step, and returns retry only when the surface replacement generation advances; otherwise the original request error remains authoritative.',
  858. '',
  859. '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.',
  860. '',
  861. ...maintenanceFooter(maintenance),
  862. ].join('\n')
  863. }
  864. function renderToolPipeline(): string {
  865. const maintenance = 'curated Mermaid flow; exact tool schemas and event signatures live in generated catalogs'
  866. return [
  867. ...generatedHeader('Tool Execution Pipeline'),
  868. '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.',
  869. '',
  870. '```mermaid',
  871. 'flowchart TD',
  872. ' model["Assistant message contains tool-call block"]',
  873. ` toolCall["Session event: ${mermaidCode('tool/call')}<br/>logged before execution"]`,
  874. ' presentCall["UI pending card<br/>presentCall(args)"]',
  875. ` pre["${mermaidCode('tools/pre-execute')} waterfall<br/>hooks, permission, sandbox"]`,
  876. ' guards["Registered monotonic guards<br/>deny or abstain; identity protected"]',
  877. ' denied["denied or approval refused<br/>tool body skipped"]',
  878. ` approval["${mermaidCode('ctx.approval')} one-shot prompt<br/>absent or unanswerable: deny"]`,
  879. ` around["${mermaidCode('tools/execute')} waterfall<br/>timeout, retry, metrics (around dispatch)"]`,
  880. ' toolBody["Registered tool execute() body"]',
  881. ` fsGate["${mermaidCode('fs/write-intent')} or ${mermaidCode('fs/edit-intent')}<br/>tool-fs mutations only"]`,
  882. ` owned["Tool-owned session events<br/>${mermaidCode('todo/write')}, ${mermaidCode('fs/observed')}, ${mermaidCode('hook/invoked')}, ${mermaidCode('hook/result')}, ${mermaidCode('tool/code-dispatch')}"]`,
  883. ` post["${mermaidCode('tools/post-execute')} waterfall<br/>accept, block, replace, add context"]`,
  884. ` final["${mermaidCode('tools/result')} synchronous notification<br/>frozen authoritative outcome"]`,
  885. ' context["Active-batch additionalContexts FIFO<br/>context/message after recorded tool results"]',
  886. ` toolResult["Session event: ${mermaidCode('tool/result')}<br/>single model-facing outcome"]`,
  887. ' allResults["Tool batch settled<br/>recorded tool/result events complete"]',
  888. ' presentResult["UI completed card<br/>presentResult(args, result)"]',
  889. ' model --> toolCall',
  890. ' toolCall --> presentCall',
  891. ' toolCall --> pre',
  892. ' pre -->|allow| guards',
  893. ' guards -->|allow| around',
  894. ' guards -->|deny| denied',
  895. ' around --> toolBody',
  896. ' pre -->|deny| denied',
  897. ' pre -->|ask| approval',
  898. ' approval -->|allowed-once| guards',
  899. ' approval -->|rejected, cancelled, unavailable| denied',
  900. ' denied --> post',
  901. ' toolBody --> fsGate',
  902. ' fsGate --> toolBody',
  903. ' toolBody --> owned',
  904. ' toolBody --> around',
  905. ' around --> post',
  906. ' post --> final',
  907. ' final --> toolResult',
  908. ' toolResult --> presentResult',
  909. ' toolResult --> allResults',
  910. ' allResults --> context',
  911. '```',
  912. '',
  913. '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 `additionalContexts` to preserve call/result adjacency.',
  914. '',
  915. ...maintenanceFooter(maintenance),
  916. ].join('\n')
  917. }
  918. function renderSnapshotReplay(): string {
  919. const maintenance = 'curated Mermaid sequence based on the snapshot test harness'
  920. return [
  921. ...generatedHeader('ACP Snapshot Replay'),
  922. '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.',
  923. '',
  924. '```mermaid',
  925. 'sequenceDiagram',
  926. ' participant Recorder as Real API recording',
  927. ' participant Fixture as snapshot fixture',
  928. ' participant Workspace',
  929. ' participant Replay as llm-replay adapter',
  930. ' participant ACP as acp-agent subprocess',
  931. ' participant Expected as stdout expected output',
  932. ' Recorder->>Fixture: session.jsonl + workspace inputs',
  933. ' Fixture->>Workspace: seed files and hook configs',
  934. ' Fixture->>Replay: recorded StreamChunk script',
  935. ` Replay->>ACP: deterministic ${mermaidCode('llm/stream')} chunks`,
  936. ' ACP->>Workspace: bash, fs, and hook side effects',
  937. ' ACP->>Expected: normalized sessionUpdate stream',
  938. ' Expected-->>ACP: diff must be empty',
  939. '```',
  940. '',
  941. '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.',
  942. '',
  943. ...maintenanceFooter(maintenance),
  944. ].join('\n')
  945. }
  946. function renderDocs(): GraphDoc[] {
  947. const pkgs = collectPackageGraph(root, GROUP_ORDER, 'gen-doc-graphs')
  948. const docs: GraphDoc[] = [
  949. { rel: 'docs/capability-seams.md', content: renderCapabilitySeams(pkgs) },
  950. ...APP_EXAMPLES.map(example => ({ rel: example.rel, content: renderAppComposition(example) })),
  951. { rel: 'docs/event-producer-consumer.md', content: renderEventRelations(pkgs) },
  952. { rel: 'docs/agent-lifecycle.md', content: renderLifecycle() },
  953. { rel: 'docs/tool-execution-pipeline.md', content: renderToolPipeline() },
  954. { rel: 'packages/ui/acp/snapshot-replay.md', content: renderSnapshotReplay() },
  955. ]
  956. docs.unshift({ rel: 'docs/graph-atlas.md', content: renderIndex(docs) })
  957. return docs
  958. }
  959. function renderIndex(docs: GraphDoc[]): string {
  960. const labels: Record<string, string> = {
  961. 'docs/capability-seams.md': 'capability seams and core services',
  962. 'examples/echo-agent/composition.md': 'echo-agent app composition',
  963. 'examples/repl-agent/composition.md': 'repl-agent app composition',
  964. 'examples/headless-agent/composition.md': 'headless-agent app composition',
  965. 'examples/tui-agent/composition.md': 'tui-agent app composition',
  966. 'examples/cordis-agent/composition.md': 'cordis-agent app composition',
  967. 'examples/acp-agent/composition.md': 'acp-agent app composition',
  968. 'docs/event-producer-consumer.md': 'event producer/consumer matrix',
  969. 'docs/agent-lifecycle.md': 'agent turn and step lifecycle',
  970. 'docs/tool-execution-pipeline.md': 'tool execution pipeline',
  971. 'packages/ui/acp/snapshot-replay.md': 'ACP snapshot replay',
  972. }
  973. const modes: Record<string, string> = {
  974. 'docs/capability-seams.md': 'hybrid generated',
  975. 'examples/echo-agent/composition.md': 'hybrid generated',
  976. 'examples/repl-agent/composition.md': 'hybrid generated',
  977. 'examples/headless-agent/composition.md': 'hybrid generated',
  978. 'examples/tui-agent/composition.md': 'hybrid generated',
  979. 'examples/cordis-agent/composition.md': 'hybrid generated',
  980. 'examples/acp-agent/composition.md': 'hybrid generated',
  981. 'docs/event-producer-consumer.md': 'hybrid generated',
  982. 'docs/agent-lifecycle.md': 'curated',
  983. 'docs/tool-execution-pipeline.md': 'curated',
  984. 'packages/ui/acp/snapshot-replay.md': 'curated',
  985. }
  986. const rows = [
  987. '| [module dependency graph](module-graph.md) | `generated` |',
  988. '| [tool schema catalog and package map](tool-catalog.md) | `generated` |',
  989. ...docs.map((doc) => {
  990. const link = graphIndexLink(doc.rel)
  991. return `| [${labels[doc.rel] ?? link}](${link}) | \`${modes[doc.rel] ?? 'generated'}\` |`
  992. }),
  993. ]
  994. const maintenance = 'mixed: each linked page declares generated, hybrid, or curated mode'
  995. return [
  996. ...generatedHeader('Documentation Graph Index'),
  997. '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).',
  998. '',
  999. 'The process decision behind this index is recorded in [the documentation graph Agent Note](../.agents/notes/implemented/process/2026-07-03-documentation-graph-atlas.md).',
  1000. '',
  1001. '| Graph | Mode |',
  1002. '| --- | --- |',
  1003. ...rows,
  1004. '',
  1005. 'Regenerate with `pnpm run gen-doc-graphs`; verify freshness with `pnpm run verify-doc-graphs`.',
  1006. '',
  1007. ...maintenanceFooter(maintenance),
  1008. ].join('\n')
  1009. }
  1010. function main(): void {
  1011. const docs = renderDocs()
  1012. if (process.argv.includes('--check')) {
  1013. const stale: string[] = []
  1014. for (const doc of docs) {
  1015. const abs = resolve(root, doc.rel)
  1016. const committed = existsSync(abs) ? readFileSync(abs, 'utf8') : null
  1017. if (committed !== doc.content) stale.push(doc.rel)
  1018. }
  1019. if (stale.length === 0) {
  1020. console.log(`gen-doc-graphs: ${docs.length} graph doc(s) are up to date.`)
  1021. return
  1022. }
  1023. console.error(`gen-doc-graphs: stale graph doc(s): ${stale.join(', ')}. Run \`pnpm run gen-doc-graphs\` and commit the result.`)
  1024. process.exit(1)
  1025. }
  1026. for (const doc of docs) {
  1027. mkdirSync(dirname(resolve(root, doc.rel)), { recursive: true })
  1028. writeFileSync(resolve(root, doc.rel), doc.content)
  1029. }
  1030. console.log(`gen-doc-graphs: wrote ${docs.length} graph doc(s).`)
  1031. }
  1032. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  1033. main()
  1034. }