gen-doc-graphs.ts 48 KB

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