gen-doc-graphs.ts 60 KB

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