gen-doc-graphs.ts 53 KB

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