gen-doc-graphs.ts 62 KB

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