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