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