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. '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', 'api-gateway'],
  134. 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.',
  135. },
  136. {
  137. key: 'typertGateway',
  138. pkg: 'api-gateway',
  139. title: 'TypeRT Host invocation gateway',
  140. mode: 'core',
  141. note: 'Associates generated Remote descriptors with live Cordis services, resolves registered identities, and exposes unary calls through the shared Connection RPC carrier.',
  142. },
  143. {
  144. key: 'sessionPersistence',
  145. pkg: 'session-persistence',
  146. title: 'Durable session persistence seam',
  147. mode: 'seam',
  148. implementations: ['session-persistence-jsonl', 'session-persistence-sqlite'],
  149. consumers: ['agent-loop', 'tool-bash', 'hooks-claude', 'hooks-codex', 'session-query', 'session-query-sqlite'],
  150. note: 'Backends persist the same SessionEvent vocabulary; apps choose a backend at composition time.',
  151. },
  152. {
  153. key: 'settings',
  154. pkg: 'settings',
  155. title: 'User-settings seam',
  156. mode: 'seam',
  157. implementations: ['settings-local'],
  158. consumers: ['llm-deepseek', 'llm-pi-ai', 'apiproxy'],
  159. 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.',
  160. },
  161. {
  162. key: 'credentials',
  163. pkg: 'credentials',
  164. title: 'Credential seam',
  165. mode: 'seam',
  166. implementations: ['credentials-local'],
  167. consumers: ['llm-deepseek', 'llm-pi-ai', 'apiproxy'],
  168. 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.',
  169. },
  170. {
  171. key: 'telemetry',
  172. pkg: 'session-telemetry',
  173. title: 'Session telemetry seam',
  174. mode: 'seam',
  175. implementations: ['session-telemetry-otel'],
  176. consumers: [],
  177. note: 'The seam captures, redacts, and hands session records to one backend; nothing else consumes the service — its output leaves the process.',
  178. },
  179. {
  180. key: 'storage',
  181. pkg: 'storage',
  182. title: 'Non-session storage hub',
  183. mode: 'seam',
  184. implementations: ['storage-json', 'storage-sqlite'],
  185. consumers: ['storage-domain'],
  186. 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.',
  187. },
  188. {
  189. key: 'storageDomain',
  190. pkg: 'storage-domain',
  191. title: 'Domain data facility',
  192. mode: 'core',
  193. consumers: ['workspace'],
  194. note: 'Waits for every configured backend, then publishes the domain form as one lifecycle-bound service for typed durable state.',
  195. },
  196. {
  197. key: 'workspace',
  198. pkg: 'workspace',
  199. title: 'Workspace entity registry',
  200. mode: 'core',
  201. consumers: ['apiproxy'],
  202. note: 'Owns WorkspaceId-branded records over the domain facility; stable sessionIds accounts drive Host RPC and GUI projections.',
  203. },
  204. {
  205. key: 'sessionQuery',
  206. pkg: 'session-query',
  207. title: 'Session reads, traces, filters, and search',
  208. mode: 'seam',
  209. implementations: ['session-query-sqlite'],
  210. consumers: ['session-reference', 'tool-session-query'],
  211. 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.',
  212. },
  213. {
  214. key: 'sessionReferences',
  215. pkg: 'session-reference',
  216. title: 'Cross-session snapshot preparation',
  217. mode: 'core',
  218. note: 'Projects bounded current-surface conversation snapshots into durable untrusted message context; host adapters own mention syntax.',
  219. },
  220. {
  221. key: 'sessionTitle',
  222. pkg: 'session-title',
  223. title: 'Log-backed session titles',
  224. mode: 'seam',
  225. implementations: ['session-title-first-message-llm', 'session-title-all-messages-llm'],
  226. note: 'Owns the deterministic fallback, latest-title fold, and sole optional asynchronous provider registration.',
  227. },
  228. {
  229. key: 'systemPrompt',
  230. pkg: 'system-prompt',
  231. title: 'System prompt assembly registry',
  232. mode: 'core',
  233. consumers: ['agent-loop', 'tools', 'tool-fs', 'tool-pty', 'tool-web'],
  234. note: 'Collects prompt sections and model-facing tool schemas for each step.',
  235. },
  236. {
  237. key: 'tools',
  238. pkg: 'tools',
  239. title: 'Tool registry and guarded execution pipeline',
  240. mode: 'core',
  241. consumers: ['agent-loop', 'tool-ask-user', 'tool-bash', 'tool-cordis', 'tool-fs', 'tool-pty', 'tool-skill', 'tool-subagent', 'tool-todo', 'tool-web'],
  242. note: 'Registers capabilities, owns Code Mode transport, and routes calls through pre-policy, monotonic guards, around dispatch, post-policy, and final-result observation.',
  243. },
  244. {
  245. key: 'userInteraction',
  246. pkg: 'user-interaction',
  247. title: 'Human question/answer seam',
  248. mode: 'seam',
  249. consumers: ['tool-ask-user'],
  250. note: 'UI front doors provide the active human-answer provider; tool-ask-user pauses a tool call on the provider-neutral ask() promise.',
  251. },
  252. {
  253. key: 'planMode',
  254. pkg: 'plan-mode',
  255. title: 'Plan collaboration state',
  256. mode: 'core',
  257. 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.',
  258. },
  259. {
  260. key: 'agentPresets',
  261. pkg: 'agent-presets',
  262. title: 'Per-session agent composition',
  263. mode: 'core',
  264. note: 'Discovers preset directories over trusted and user-authored roots and mounts one preset cordis.yml under an agent scope during creation, rejecting a row that never activates or that publishes into the root service realm.',
  265. },
  266. {
  267. key: 'commands',
  268. pkg: 'commands',
  269. title: 'Human command registry',
  270. mode: 'core',
  271. note: 'Plugins register direct human commands without sending invocations to the model.',
  272. },
  273. {
  274. key: 'sessionProjections',
  275. pkg: 'session-projection',
  276. title: 'Session projection units',
  277. mode: 'core',
  278. consumers: ['tool-todo', 'session-title', 'host-apiproxy'],
  279. note: 'Domains register state-driven fold units; the eager drive keeps per-session watermark states and api-proxy serves baselines and pushes changed values.',
  280. },
  281. {
  282. key: 'sessionProjectionCache',
  283. pkg: 'session-projection-cache',
  284. title: 'Persisted projection cache',
  285. mode: 'core',
  286. consumers: ['host-apiproxy'],
  287. 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.',
  288. },
  289. {
  290. key: 'skills',
  291. pkg: 'skill',
  292. title: 'Skill provider registry',
  293. mode: 'seam',
  294. implementations: ['skill-local'],
  295. consumers: ['tool-skill'],
  296. note: 'Merges provider skill catalogs; tool-skill renders the session-prefix catalog and loads complete skill bodies.',
  297. },
  298. {
  299. key: 'agents',
  300. pkg: 'agent',
  301. title: 'Agent service',
  302. mode: 'core',
  303. consumers: ['agent-loop', 'acp', 'cli-demo', 'subagent-inprocess'],
  304. note: 'Owns live Agent handles, the create/resume factory seam, and process-local initiator propagation.',
  305. },
  306. {
  307. key: 'agentLoop',
  308. pkg: 'agent-loop',
  309. title: 'Concrete loop driver',
  310. mode: 'bundle',
  311. consumers: ['agent-spine-demo'],
  312. note: 'The one concrete loop plugin; extension packages depend on dsh-agent events and services, not on this package.',
  313. },
  314. {
  315. key: 'goals',
  316. pkg: 'goal',
  317. title: 'Same-session goal domain',
  318. mode: 'core',
  319. note: 'Folds revisioned objective state from the session log and keeps live continuation activation process-local.',
  320. },
  321. {
  322. key: 'subprocess',
  323. pkg: 'subprocess',
  324. title: 'Subprocess seam',
  325. mode: 'seam',
  326. implementations: ['subprocess-local'],
  327. consumers: ['bash-local', 'bash-sandbox', 'lsp-local', 'subagent-acp', 'subagent-codex', 'subagent-claude-code'],
  328. note: 'The bash executors, the LSP host, and the out-of-process ACP, Codex, and Claude Code subagent backends spawn their children through ctx.subprocess; the service owns tree lifetime, stdio dispositions (pipes, inherit, bounded spill-backed collection), and kill escalation.',
  329. },
  330. {
  331. key: 'bash',
  332. pkg: 'bash',
  333. title: 'Bash executor seam',
  334. mode: 'seam',
  335. implementations: ['bash-local', 'bash-sandbox', 'pwsh-local'],
  336. consumers: ['tool-bash', 'tool-pwsh', 'hooks-claude', 'hooks-codex'],
  337. note: 'The model-facing shell tools and hook bridges consume this seam; sandboxed, remote, or PowerShell executors replace bash-local without touching them.',
  338. },
  339. {
  340. key: 'bashEnv',
  341. pkg: 'bash-env',
  342. title: 'Managed bash environment registry',
  343. mode: 'core',
  344. consumers: ['tool-bash', 'tool-pwsh'],
  345. note: 'Plugins declare effect-scoped DSH_* facts; each shell tool collects one trusted snapshot per execution and its executor rebuilds the namespace.',
  346. },
  347. {
  348. key: 'pty',
  349. pkg: 'pty',
  350. title: 'Persistent PTY session registry',
  351. mode: 'seam',
  352. implementations: ['pty-local'],
  353. consumers: ['tool-pty'],
  354. note: 'The registry owns exact-Agent session identity and cleanup; backends own terminal mechanics, while tool-pty exposes the owner-scoped model surface.',
  355. },
  356. {
  357. key: 'sandbox',
  358. pkg: 'sandbox',
  359. title: 'Process-sandbox seam',
  360. mode: 'seam',
  361. implementations: ['sandbox-local'],
  362. consumers: ['bash-sandbox', 'pty-local'],
  363. 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.',
  364. },
  365. {
  366. key: 'sandboxPolicy',
  367. pkg: 'sandbox-policy',
  368. title: 'Sandbox policy home',
  369. mode: 'core',
  370. implementations: [],
  371. consumers: ['bash-sandbox', 'fs-sandbox', 'pty-local'],
  372. 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.',
  373. },
  374. {
  375. key: 'approval',
  376. pkg: 'approval',
  377. title: 'Approval seam',
  378. mode: 'seam',
  379. implementations: ['acp'],
  380. consumers: ['tools', 'tool-bash'],
  381. 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`.',
  382. },
  383. {
  384. key: 'permission',
  385. pkg: 'permission',
  386. title: 'Permission presets',
  387. mode: 'core',
  388. implementations: [],
  389. 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.',
  390. },
  391. {
  392. key: 'codeRuntime',
  393. pkg: 'code-runtime',
  394. title: 'Code-execution seam',
  395. mode: 'seam',
  396. implementations: ['code-runtime-worker'],
  397. consumers: ['tools'],
  398. 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).',
  399. },
  400. {
  401. key: 'fs',
  402. pkg: 'fs',
  403. title: 'Filesystem provider seam',
  404. mode: 'seam',
  405. implementations: ['fs-local', 'fs-sandbox'],
  406. consumers: ['tool-fs'],
  407. companions: ['fs-policy'],
  408. 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.',
  409. },
  410. {
  411. key: 'compact',
  412. pkg: 'compact',
  413. title: 'Compaction seam',
  414. mode: 'seam',
  415. implementations: ['compact-basic'],
  416. consumers: ['compact-basic'],
  417. note: 'The basic backend consumes post-step pressure and request-error recovery events; a model-facing compact tool remains deferred.',
  418. },
  419. {
  420. key: 'subagents',
  421. pkg: 'subagent',
  422. title: 'Subagent provider and continuation service',
  423. mode: 'seam',
  424. implementations: ['subagent-spawn', 'subagent-fork', 'subagent-acp', 'subagent-codex', 'subagent-claude-code', 'subagent-dsh-sdk'],
  425. consumers: ['tool-subagent', 'tool-subagent-control', 'tool-ralph'],
  426. 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.',
  427. },
  428. {
  429. key: 'tasks',
  430. pkg: 'tasks',
  431. title: 'Background task registry',
  432. mode: 'seam',
  433. implementations: ['tasks-local'],
  434. consumers: ['tool-bash', 'tool-pty', 'tool-subagent', 'tool-tasks'],
  435. 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.',
  436. },
  437. {
  438. key: 'web',
  439. pkg: 'web',
  440. title: 'Web access provider registry',
  441. mode: 'seam',
  442. implementations: ['web-search-exa', 'web-search-perplexity', 'web-search-deepseek', 'web-fetch-local'],
  443. consumers: ['tool-web'],
  444. note: 'Search and fetch providers register into one ctx.web seam; tool-web owns the stable model-facing names.',
  445. },
  446. {
  447. key: 'spillStore',
  448. pkg: 'spill',
  449. title: 'Spill storage seam',
  450. mode: 'seam',
  451. implementations: ['spill-local'],
  452. consumers: ['spill-policy'],
  453. 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.',
  454. },
  455. {
  456. key: 'directoryPicker',
  457. pkg: 'directory-picker',
  458. title: 'Workspace-directory picking seam',
  459. mode: 'seam',
  460. implementations: ['directory-picker-native', 'directory-picker-browse'],
  461. consumers: ['apiproxy'],
  462. 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).',
  463. },
  464. {
  465. key: 'httpServer',
  466. pkg: 'webserver',
  467. title: 'HTTP route registration',
  468. mode: 'core',
  469. consumers: ['connection', 'modules', 'hmr'],
  470. note: 'Plain node:http carrier: named-route registry, index transform taps, and the static dist fallback; web-transport plugins register their own routes.',
  471. },
  472. {
  473. key: 'clientModuleHost',
  474. pkg: 'modules',
  475. title: 'Client plugin graph host',
  476. mode: 'core',
  477. consumers: ['hmr'],
  478. note: 'Composes the __DSH_BOOT__ entry graph from an incremental dshClient scan, serves plugin bundles, and notifies rebuilt/graph-changed subscribers.',
  479. },
  480. {
  481. key: 'workflows',
  482. pkg: 'workflow',
  483. title: 'Workflow script engine',
  484. mode: 'seam',
  485. implementations: ['workflow-workerthread'],
  486. consumers: ['tool-workflow', 'tool-ralph'],
  487. 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.',
  488. },
  489. ]
  490. function generatedHeader(title: string): string[] {
  491. return [
  492. '<!-- Generated by scripts/gen-doc-graphs.ts - do not edit by hand.',
  493. ' Run `pnpm run gen-doc-graphs` to regenerate. -->',
  494. '',
  495. `# ${title}`,
  496. '',
  497. ]
  498. }
  499. function maintenanceFooter(source: string): string[] {
  500. return [`Maintenance mode: ${source}.`, '']
  501. }
  502. function graphIndexLink(rel: string): string {
  503. return relative('docs', rel).replaceAll('\\', '/')
  504. }
  505. function linkFromDoc(docRel: string, targetRel: string): string {
  506. return relative(dirname(docRel), targetRel).replaceAll('\\', '/')
  507. }
  508. function mermaidCode(value: string): string {
  509. return `<code>${value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</code>`
  510. }
  511. function repoLink(path: string, label: string, up = '..'): string {
  512. return `[${label}](${up}/${path})`
  513. }
  514. function sourceLink(source: string, up = '..'): string {
  515. return repoLink(source.split(':')[0] ?? source, `\`${source}\``, up)
  516. }
  517. function pkgLink(pkg: Pkg | undefined, fallback: string, up = '..'): string {
  518. return pkg ? repoLink(pkg.rel, `\`${pkg.short}\``, up) : `\`${fallback}\``
  519. }
  520. function pkgList(names: string[] | undefined, pkgsByShort: Map<string, Pkg>): string {
  521. if (!names || names.length === 0) return '-'
  522. return names.map(name => pkgLink(pkgsByShort.get(name), name)).join(', ')
  523. }
  524. function tableCell(value: string): string {
  525. return value.replace(/\|/g, '\\|').replace(/\n/g, '<br>')
  526. }
  527. function assertServiceRolesComplete(services: readonly ServiceEntry[]): void {
  528. const discovered = new Set(services.map(service => service.key))
  529. const classified = new Set(SERVICE_ROLES.map(role => role.key))
  530. const missing = [...discovered].filter(key => !classified.has(key)).sort()
  531. const stale = [...classified].filter(key => !discovered.has(key)).sort()
  532. if (missing.length || stale.length) {
  533. throw new Error([
  534. missing.length ? `missing service role classification: ${missing.join(', ')}` : '',
  535. stale.length ? `stale service role classification: ${stale.join(', ')}` : '',
  536. ].filter(Boolean).join('; '))
  537. }
  538. }
  539. function renderCapabilitySeams(pkgs: Pkg[], services: readonly ServiceEntry[]): string {
  540. assertServiceRolesComplete(services)
  541. const pkgsByShort = new Map(pkgs.map(pkg => [pkg.short, pkg]))
  542. 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'
  543. const nodes = new Map<string, string>()
  544. const edges = new Set<string>()
  545. const companionEdges = new Set<string>()
  546. const addNode = (id: string, label: string): void => {
  547. if (!nodes.has(id)) nodes.set(id, ` ${id}["${escLabel(label)}"]`)
  548. }
  549. const addEdge = (from: string, to: string): void => { edges.add(` ${from} --> ${to}`) }
  550. const lines = generatedHeader('Capability Seams And Core Services')
  551. lines.push(
  552. '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.',
  553. '',
  554. '```mermaid',
  555. 'flowchart LR',
  556. )
  557. for (const role of SERVICE_ROLES) {
  558. const svc = nodeId('svc', role.key)
  559. const owner = nodeId('pkg', role.pkg)
  560. addNode(owner, role.pkg)
  561. addNode(svc, `ctx.${role.key}<br/>${role.title}`)
  562. addEdge(owner, svc)
  563. for (const impl of role.implementations ?? []) {
  564. addNode(nodeId('pkg', impl), impl)
  565. addEdge(nodeId('pkg', impl), svc)
  566. }
  567. for (const consumer of role.consumers ?? []) {
  568. addNode(nodeId('pkg', consumer), consumer)
  569. addEdge(svc, nodeId('pkg', consumer))
  570. }
  571. for (const companion of role.companions ?? []) {
  572. addNode(nodeId('pkg', companion), companion)
  573. companionEdges.add(` ${svc} -. event gate .-> ${nodeId('pkg', companion)}`)
  574. }
  575. }
  576. lines.push(...nodes.values(), ...[...edges].sort(), ...[...companionEdges].sort())
  577. lines.push('```', '', '| ctx key | Role | Owner | Implementations | Direct consumers | Companion plugins | Note |', '| --- | --- | --- | --- | --- | --- | --- |')
  578. for (const role of SERVICE_ROLES) {
  579. 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)} |`)
  580. }
  581. lines.push('', ...maintenanceFooter(maintenance))
  582. return lines.join('\n')
  583. }
  584. function parseExampleCordis(rel: string): ExamplePlugin[] {
  585. const text = readFileSync(resolve(root, rel), 'utf8')
  586. const plugins: ExamplePlugin[] = []
  587. let current: { id: string; name?: string } | null = null
  588. const flush = (): void => {
  589. if (current?.name) plugins.push({ id: current.id, name: current.name })
  590. }
  591. for (const line of text.split('\n')) {
  592. // Top-level rows (`- id:`) and bundle-patch insert rows (` - id:`).
  593. const id = /^\s*-\s+id:\s+(.+?)\s*$/.exec(line)
  594. if (id?.[1] !== undefined) {
  595. flush()
  596. current = { id: stripYamlScalar(id[1]) }
  597. continue
  598. }
  599. const name = /^\s+name:\s+(.+?)\s*$/.exec(line)
  600. if (name?.[1] !== undefined && current) current.name = stripYamlScalar(name[1])
  601. }
  602. flush()
  603. return plugins
  604. }
  605. function stripYamlScalar(value: string): string {
  606. return value.trim().replace(/^['"]|['"]$/g, '')
  607. }
  608. const APP_EXAMPLES = [
  609. {
  610. id: 'dsh_base',
  611. rel: 'apps/cli/composition.md',
  612. title: 'DSH Base Composition',
  613. label: 'packages/bundle/base/cordis.patch.yml',
  614. config: 'packages/bundle/base/cordis.patch.yml',
  615. 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.',
  616. },
  617. {
  618. id: 'headless',
  619. rel: 'examples/headless-agent/composition.md',
  620. title: 'Headless Agent App Composition',
  621. label: 'examples/headless-agent',
  622. config: 'examples/headless-agent/cordis.yml',
  623. 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.',
  624. },
  625. {
  626. id: 'acp',
  627. rel: 'examples/acp-agent/composition.md',
  628. title: 'ACP Automation App Composition',
  629. label: 'examples/acp-agent',
  630. config: 'examples/acp-agent/cordis.yml',
  631. 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.',
  632. },
  633. ]
  634. type AppExample = typeof APP_EXAMPLES[number]
  635. function renderAppExpansion(lines: string[], appNode: string, pluginName: string): void {
  636. const agentCore = nodeId('bundle', 'agent_core')
  637. const jsonl = nodeId('bundle', 'jsonl')
  638. lines.push(` ${appNode} --> ${agentCore}["@deepseek-ai/dsh-agent-spine-demo"]`)
  639. lines.push(` ${appNode} --> ${jsonl}["@deepseek-ai/dsh-session-persistence-jsonl"]`)
  640. if (pluginName === '@deepseek-ai/dsh-cli-demo') {
  641. lines.push(` ${appNode} --> ${nodeId('frontdoor', 'cli')}["one-shot driver<br/>format-pure stdout<br/>fresh top-level agent"]`)
  642. } else 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-cli-demo' || 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. }