gen-doc-graphs.ts 61 KB

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