gen-doc-graphs.ts 61 KB

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