gen-doc-graphs.ts 61 KB

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