gen-doc-graphs.ts 49 KB

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