gen-doc-graphs.ts 49 KB

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