gen-doc-graphs.ts 47 KB

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