gen-doc-graphs.ts 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631
  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. 'attachment',
  57. 'document',
  58. 'llm',
  59. 'core',
  60. 'typert',
  61. 'goal',
  62. 'experimental',
  63. 'process',
  64. 'bash',
  65. 'pty',
  66. 'sandbox',
  67. 'ssh',
  68. 'fs',
  69. 'skill',
  70. 'compact',
  71. 'subagent',
  72. 'tasks',
  73. 'workflow',
  74. 'web',
  75. 'webhook',
  76. 'spill',
  77. 'todo',
  78. 'plan',
  79. 'cordis',
  80. 'hooks',
  81. 'session-persistence',
  82. 'session-query',
  83. 'session-title',
  84. 'telemetry',
  85. 'storage',
  86. 'workspace',
  87. 'support',
  88. 'acp',
  89. 'ui',
  90. ]
  91. const SERVICE_ROLES: ServiceRole[] = [
  92. {
  93. key: 'hmr',
  94. pkg: 'hmr',
  95. title: 'Serialized module and configuration reloads',
  96. mode: 'core',
  97. consumers: ['app-boot'],
  98. note: 'Owns module and exact configuration watchers; application mutations share its queue and automatic reloads await the application file lock.',
  99. },
  100. {
  101. key: 'pluginManager',
  102. pkg: 'plugin-manager',
  103. title: 'Current-profile plugin and bundle management',
  104. mode: 'core',
  105. consumers: ['plugin-manager', 'ui-settings-plugin-inventory'],
  106. note: 'Shares profile package operations with the CLI and reports persisted and running state to Web and agent callers.',
  107. },
  108. {
  109. key: 'profileContext',
  110. pkg: 'app-boot',
  111. title: 'Launcher-owned profile data',
  112. mode: 'core',
  113. consumers: ['plugin-manager'],
  114. note: 'The dsh launcher supplies data-only profile locations and composition inputs; reload scheduling belongs to dsh-hmr.',
  115. },
  116. {
  117. key: 'connection',
  118. pkg: 'client-connection',
  119. title: 'Authenticated browser transport',
  120. mode: 'core',
  121. consumers: ['api-gateway', 'host-frontend-static'],
  122. note: 'Owns browser authentication and shared HTTP request dispatch; API adapters register endpoints and streams.',
  123. },
  124. {
  125. key: 'mcpResources',
  126. pkg: 'mcp-resources',
  127. title: 'Scoped MCP resource access',
  128. mode: 'seam',
  129. implementations: ['mcp-client'],
  130. consumers: ['mcp-resources'],
  131. note: 'Connection-owned providers serve shared resource tools in the calling agent scope.',
  132. },
  133. {
  134. key: 'browserUse',
  135. pkg: 'browser-use',
  136. title: 'Browser-use provider registration',
  137. mode: 'seam',
  138. implementations: ['experimental-browser-use-playwright-mcp', 'experimental-browser-use-chrome-devtools-mcp', 'experimental-browser-use-stagehand-native'],
  139. consumers: ['experimental-browser-use-playwright-mcp', 'experimental-browser-use-chrome-devtools-mcp', 'experimental-browser-use-stagehand-native'],
  140. note: 'One provider-owned name per service instance. Providers own their tools and browser resources per live Session; the shared service has no browser operation API.',
  141. },
  142. {
  143. key: 'computerUse',
  144. pkg: 'computer-use',
  145. title: 'Computer-use provider registration',
  146. mode: 'seam',
  147. implementations: ['experimental-computer-use-cua-driver-mcp', 'experimental-computer-use-cua-driver-native'],
  148. consumers: ['experimental-computer-use-cua-driver-mcp', 'experimental-computer-use-cua-driver-native'],
  149. note: 'One provider-owned name per service instance. Each provider also owns its model tools; the service has no common action API, runtime selection, or Session workflow lock.',
  150. },
  151. {
  152. key: 'officeToPdf', pkg: 'office-to-pdf', title: 'Office to PDF conversion',
  153. mode: 'core', consumers: ['client-ui-sidebar-documentpreview'],
  154. note: 'Authorized Office bytes are converted on the Host using the declared native target engine, or Node WASM when no native target is declared.',
  155. },
  156. {
  157. key: 'attachments',
  158. pkg: 'attachment',
  159. title: 'Durable binary attachment storage',
  160. mode: 'seam',
  161. implementations: ['attachment-local'],
  162. consumers: ['api-session-controller', 'tool-fs', 'llm-pi-ai', 'llm-deepseek'],
  163. note: 'The host commits accepted images before session events; provider adapters resolve authorized durable references into provider-native content.',
  164. },
  165. {
  166. key: 'fileUploads',
  167. pkg: 'client-file-upload',
  168. title: 'Agent-scoped staged file uploads',
  169. mode: 'core',
  170. consumers: ['api-session-controller'],
  171. note: 'Owns streaming intake, durable storage, and staged receipt lifetime; the Session controller binds receipts to accepted submissions.',
  172. },
  173. {
  174. key: 'llm',
  175. pkg: 'llm',
  176. title: 'LLM adapter registry',
  177. mode: 'seam',
  178. implementations: ['llm-deepseek', 'llm-pi-ai', 'llm-replay'],
  179. consumers: ['agent-loop', 'compaction-basic'],
  180. note: 'Adapters register provider implementations; the loop and compaction call the provider-neutral stream service.',
  181. },
  182. {
  183. key: 'deepseekLlmApiExtensions',
  184. pkg: 'deepseek-llm-api-extensions',
  185. title: 'Official DeepSeek request extensions',
  186. mode: 'seam',
  187. implementations: ['session-log-deepseek', 'plugin-package-inventory-deepseek'],
  188. consumers: ['llm-deepseek'],
  189. note: 'Plugins prepare independent top-level fields; the official adapter merges them and commits their delivery state after HTTP acceptance.',
  190. },
  191. {
  192. key: 'tokenMeter',
  193. pkg: 'token-meter',
  194. title: 'Replay token measurement',
  195. mode: 'core',
  196. consumers: ['compaction-basic'],
  197. note: 'Owns isolated per-session replay folds; pressure consumers share immutable revisioned measurements.',
  198. },
  199. {
  200. key: 'toolResultPruner',
  201. pkg: 'compaction-tool-result-pruner',
  202. title: 'Model-free tool-result pruning',
  203. mode: 'core',
  204. consumers: ['compaction-basic'],
  205. note: 'Rewrites oversized current tool results through replayable single-node surface replacements before summary compaction.',
  206. },
  207. {
  208. key: 'sessions',
  209. pkg: 'session',
  210. title: 'In-memory session store',
  211. mode: 'core',
  212. consumers: ['agent-loop', 'agent', 'session-persistence', 'session-query', 'session-query-sqlite', 'subagent-in-process-driver', 'invariants', 'message-feedback'],
  213. note: 'Owns append-only Session instances and emits the durable session event feed.',
  214. },
  215. {
  216. key: 'sessionController',
  217. pkg: 'api-session-controller',
  218. title: 'Host Session Remote controller',
  219. mode: 'core',
  220. note: 'Owns Session commands, cold reads, durable-event following, live control state, model catalogs, workspace opening, and Agent activation policy.',
  221. },
  222. {
  223. key: 'sessionFileReferences',
  224. pkg: 'api-session-controller',
  225. title: 'Session-addressed file-reference Remote adapter',
  226. mode: 'core',
  227. note: 'Delegates file-reference discovery through the Session Controller\'s established Agent lookup policy.',
  228. },
  229. {
  230. key: 'sessionSkillCatalog',
  231. pkg: 'api-session-controller',
  232. title: 'Session-addressed skill Remote adapter',
  233. mode: 'core',
  234. note: 'Lists the Session composition\'s user-invocable skills without activating a cold Agent.',
  235. },
  236. {
  237. key: 'credentialsController',
  238. pkg: 'api-settings-controller',
  239. title: 'Host credential-surface Remote controller',
  240. mode: 'core',
  241. note: 'Projects the credential-reference seam onto the generated Remote namespace: batch fan-out, view projection, and refusal mapping live here, not on the seam Definition.',
  242. },
  243. {
  244. key: 'settingsController',
  245. pkg: 'api-settings-controller',
  246. title: 'Host settings-surface Remote controller',
  247. mode: 'core',
  248. note: 'Projects the user-settings seam onto the generated Remote namespace: the read is always redacted and every refusal is classified here, not on the seam Definition.',
  249. },
  250. {
  251. key: 'workspaceFiles',
  252. pkg: 'api-workspace-files',
  253. title: 'Host workspace file Remote service',
  254. mode: 'core',
  255. note: 'Serves stat, paged text, byte windows, directory listings, and the change feed for files inside a Session\'s workspace root, confined by lstat, containment, and a stat re-check.',
  256. },
  257. {
  258. key: 'workspaceChanges',
  259. pkg: 'workspace-changes',
  260. title: 'Host per-turn changed-file summaries',
  261. mode: 'core',
  262. note: 'Serves the summary each workspace/changes event announced and each listed file\'s turn-start and turn-end comparison, by Session and event sequence, until that Session is disposed; the log carries only the turn.',
  263. },
  264. {
  265. key: 'terminalController',
  266. pkg: 'api-terminal-controller',
  267. title: 'Session interactive terminal Remote controller',
  268. mode: 'core',
  269. note: 'Owns user terminal processes, default shell resolution and bounded screen recovery through the subprocess provider and typed Remote transport.',
  270. },
  271. {
  272. key: 'workspaceController',
  273. pkg: 'api-workspace-controller',
  274. title: 'Host Workspace Remote controller',
  275. mode: 'core',
  276. note: 'Owns Workspace commands and reconnect-safe Workspace state delivery through the generated Remote namespace.',
  277. },
  278. {
  279. key: 'directoryPickerController',
  280. pkg: 'api-workspace-controller',
  281. title: 'Host directory-picking Remote controller',
  282. mode: 'core',
  283. note: 'Carries the picking seam onto the wire: capability gating, cancellation, and the seam-coded failures a browser directory flow discriminates on.',
  284. },
  285. {
  286. key: 'invariants',
  287. pkg: 'invariants',
  288. title: 'Package-owned invariant registry',
  289. mode: 'core',
  290. consumers: ['session', 'agent', 'scope', 'agent-loop'],
  291. note: 'Companion subpaths register owner-local checks; the service owns selection, uniqueness, child fibers, and package-attributed failures.',
  292. },
  293. {
  294. key: 'typert',
  295. pkg: 'typert-registry',
  296. title: 'Runtime type registry',
  297. mode: 'core',
  298. consumers: ['typert-loader', 'api-gateway'],
  299. 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.',
  300. },
  301. {
  302. key: 'typertGateway',
  303. pkg: 'api-gateway',
  304. title: 'Typert Host invocation gateway',
  305. mode: 'core',
  306. note: 'Associates generated Remote descriptors with live Cordis services, resolves registered identities, and exposes unary calls through the shared Connection RPC carrier.',
  307. },
  308. {
  309. key: 'sessionPersistence',
  310. pkg: 'session-persistence',
  311. title: 'Durable session persistence seam',
  312. mode: 'seam',
  313. implementations: ['session-persistence-jsonl'],
  314. consumers: ['agent-loop', 'tool-bash', 'hooks-claude-code', 'hooks-codex', 'session-query', 'session-query-sqlite', 'message-feedback'],
  315. note: 'The JSONL backend persists the SessionEvent vocabulary as one artifact per Session.',
  316. },
  317. {
  318. key: 'settings',
  319. pkg: 'settings',
  320. title: 'User-settings seam',
  321. mode: 'seam',
  322. implementations: ['settings-file'],
  323. consumers: ['api-settings-controller', 'llm-deepseek', 'llm-pi-ai'],
  324. 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 settings controller serves redacted layered descriptors and writes the user layer.',
  325. },
  326. {
  327. key: 'subagentModelSelection',
  328. pkg: 'tool-subagent',
  329. title: 'Subagent model-selection preference',
  330. mode: 'core',
  331. consumers: ['tool-subagent'],
  332. note: 'Owns the default-off settings namespace that Agent-scoped delegation tools sample when composing a new top-level Session.',
  333. },
  334. {
  335. key: 'credentials',
  336. pkg: 'credentials',
  337. title: 'Credential seam',
  338. mode: 'seam',
  339. implementations: ['credentials-local'],
  340. consumers: ['api-settings-controller', 'llm-deepseek', 'llm-pi-ai'],
  341. note: 'Configuration carries references to secrets; providers own the values. Consumers resolve per operation, so a rotated credential reaches the very next request; the settings controller exposes value-free views and write-only storage.',
  342. },
  343. {
  344. key: 'authorization',
  345. pkg: 'authorization',
  346. title: 'Authorization flow registry',
  347. mode: 'seam',
  348. implementations: [],
  349. consumers: ['llm-pi-ai'],
  350. note: 'Flows are registered by the plugin that knows how to obtain one credential and keyed by the record they write; the seam owns the conversation and the one-attempt-per-key lifecycle, never the protocol.',
  351. },
  352. {
  353. key: 'sessionTelemetry',
  354. pkg: 'session-telemetry',
  355. title: 'Session telemetry seam',
  356. mode: 'seam',
  357. implementations: ['session-telemetry-otel'],
  358. consumers: [],
  359. note: 'The seam captures, redacts, and hands session records to one backend; nothing else consumes the service — its output leaves the process.',
  360. },
  361. {
  362. key: 'storage',
  363. pkg: 'storage',
  364. title: 'Non-session storage hub',
  365. mode: 'seam',
  366. implementations: ['storage-json', 'storage-sqlite'],
  367. consumers: ['storage-domain'],
  368. 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.',
  369. },
  370. {
  371. key: 'storageDomain',
  372. pkg: 'storage-domain',
  373. title: 'Domain data facility',
  374. mode: 'core',
  375. consumers: ['workspace'],
  376. note: 'Waits for every configured backend, then publishes the domain form as one lifecycle-bound service for typed durable state.',
  377. },
  378. {
  379. key: 'messageFeedback',
  380. pkg: 'message-feedback',
  381. title: 'Lifecycle-bound message feedback',
  382. mode: 'core',
  383. note: 'Owns per-assistant-message feedback in the canonical Session log, target validation, per-item compare-and-set, and the Host unary Remote contract. Feedback stays outside model history; log export follows the consumer policy.',
  384. },
  385. {
  386. key: 'sessionFeedback',
  387. pkg: 'command-feedback',
  388. title: 'Session-level feedback recorder',
  389. mode: 'core',
  390. note: 'Records one Session-level remark with its category as a log-only feedback/record event on a live Session through the Host unary Remote contract; the /feedback command shares the same producer.',
  391. },
  392. {
  393. key: 'workspaceRegistry',
  394. pkg: 'workspace',
  395. title: 'Workspace entity registry',
  396. mode: 'core',
  397. consumers: ['api-workspace-controller', 'api-session-controller'],
  398. note: 'Owns WorkspaceId-branded records over the domain facility; stable sessionIds accounts drive Host RPC and GUI projections.',
  399. },
  400. {
  401. key: 'sessionQuery',
  402. pkg: 'session-query',
  403. title: 'Session reads, traces, filters, and search',
  404. mode: 'seam',
  405. implementations: ['session-query-sqlite'],
  406. consumers: ['session-reference', 'tool-session-query'],
  407. 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.',
  408. },
  409. {
  410. key: 'fileReferences',
  411. pkg: 'file-reference',
  412. title: 'File reference discovery',
  413. mode: 'seam',
  414. implementations: ['file-reference-local'],
  415. consumers: ['api-session-controller'],
  416. note: 'The interface returns path-only completion candidates within an Agent cwd; providers own namespace access and ranking without reading file contents.',
  417. },
  418. {
  419. key: 'sessionReferenceResolver',
  420. pkg: 'session-reference',
  421. title: 'Cross-session snapshot preparation',
  422. mode: 'core',
  423. note: 'Projects bounded current-surface conversation snapshots into durable untrusted message context; host adapters own mention syntax.',
  424. },
  425. {
  426. key: 'sessionTitle',
  427. pkg: 'session-title',
  428. title: 'Log-backed session titles',
  429. mode: 'seam',
  430. implementations: ['session-title-first-prompt-llm', 'session-title-all-prompts-llm'],
  431. note: 'Owns the deterministic fallback, latest-title fold, and sole optional asynchronous provider registration.',
  432. },
  433. {
  434. key: 'systemPrompt',
  435. pkg: 'system-prompt',
  436. title: 'System prompt assembly registry',
  437. mode: 'core',
  438. consumers: ['agent-loop', 'tools', 'tool-fs', 'tool-terminal', 'tool-web'],
  439. note: 'Collects prompt sections and model-facing tool schemas for each step.',
  440. },
  441. {
  442. key: 'tools',
  443. pkg: 'tools',
  444. title: 'Tool registry and guarded execution pipeline',
  445. mode: 'core',
  446. consumers: ['agent-loop', 'tool-ask-user', 'tool-bash', 'tool-cordis', 'tool-fs', 'tool-terminal', 'tool-skill', 'tool-subagent', 'tool-todo', 'tool-web'],
  447. note: 'Registers capabilities, owns PTC mode transport, and routes calls through pre-policy, monotonic guards, around dispatch, post-policy, and final-result observation.',
  448. },
  449. {
  450. key: 'userQuestions',
  451. pkg: 'user-questions',
  452. title: 'Human question/answer seam',
  453. mode: 'seam',
  454. consumers: ['tool-ask-user'],
  455. note: 'UI front ends provide the active human-answer provider; tool-ask-user pauses a tool call on the provider-neutral ask() promise.',
  456. },
  457. {
  458. key: 'planMode',
  459. pkg: 'plan-mode',
  460. title: 'Plan collaboration state',
  461. mode: 'core',
  462. 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.',
  463. },
  464. {
  465. key: 'agentPresets',
  466. pkg: 'agent-presets',
  467. title: 'Per-session agent composition',
  468. mode: 'core',
  469. note: 'Discovers preset directories over trusted and user-authored roots and mounts one preset cordis.yml under an agent scope during creation, rejecting a row that never activates or that publishes into the root service realm.',
  470. },
  471. {
  472. key: 'commands',
  473. pkg: 'commands',
  474. title: 'Human command registry',
  475. mode: 'core',
  476. note: 'Plugins register direct human commands without sending invocations to the model.',
  477. },
  478. {
  479. key: 'sessionProjections',
  480. pkg: 'session-projection',
  481. title: 'Session projection units',
  482. mode: 'core',
  483. consumers: ['api-session-controller', 'tool-todo', 'session-title'],
  484. note: 'Domains register state-driven fold units; the eager drive keeps per-session watermark states and the Session controller serves baselines and pushes changed values.',
  485. },
  486. {
  487. key: 'sessionProjectionCache',
  488. pkg: 'session-projection-cache',
  489. title: 'Persisted projection cache',
  490. mode: 'core',
  491. consumers: ['api-session-controller', 'session-query', 'session-reference', 'subagent'],
  492. 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.',
  493. },
  494. {
  495. key: 'skills',
  496. pkg: 'skill',
  497. title: 'Skill provider registry',
  498. mode: 'seam',
  499. implementations: ['skill-badge', 'skill-filesystem', 'skill-office'],
  500. consumers: ['tool-skill'],
  501. note: 'Merges provider skill catalogs; tool-skill renders the session-prefix catalog and loads complete skill bodies.',
  502. },
  503. {
  504. key: 'agents',
  505. pkg: 'agent',
  506. title: 'Agent service',
  507. mode: 'core',
  508. consumers: ['agent-loop', 'acp', 'subagent-in-process-driver'],
  509. note: 'Owns live Agent handles, the create/resume factory seam, and process-local initiator propagation.',
  510. },
  511. {
  512. key: 'agentDefaultModel',
  513. pkg: 'agent-default-model',
  514. title: 'Default Agent model selection',
  515. mode: 'core',
  516. consumers: ['api-session-controller', 'headless'],
  517. note: 'Layers the default ModelSelection through settings so direct and Host-backed Agent entry points share one state owner.',
  518. },
  519. {
  520. key: 'agentLoop',
  521. pkg: 'agent-loop',
  522. title: 'Concrete loop driver',
  523. mode: 'bundle',
  524. consumers: ['base', 'sdk-minimal'],
  525. note: 'The one concrete loop plugin; extension packages depend on dsh-agent events and services, not on this package.',
  526. },
  527. {
  528. key: 'goals',
  529. pkg: 'goal',
  530. title: 'Same-session goal domain',
  531. mode: 'core',
  532. note: 'Folds revisioned objective state from the session log and keeps live continuation activation process-local.',
  533. },
  534. {
  535. key: 'ssh',
  536. pkg: 'ssh',
  537. title: 'POSIX SSH connection owner',
  538. mode: 'core',
  539. consumers: ['fs-ssh', 'subprocess-ssh', 'sandbox-ssh'],
  540. note: 'Owns one authenticated OpenSSH connection, installed helper identity, independent program streams and disconnect cleanup for the paired remote providers.',
  541. },
  542. {
  543. key: 'subprocess',
  544. pkg: 'subprocess',
  545. title: 'Subprocess seam',
  546. mode: 'seam',
  547. implementations: ['subprocess-local', 'subprocess-ssh'],
  548. consumers: ['bash-local', 'bash-sandbox', 'terminal-bash', 'lsp-stdio', 'subagent-acp', 'subagent-codex', 'subagent-claude-code'],
  549. 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.',
  550. },
  551. {
  552. key: 'shell',
  553. pkg: 'shell',
  554. title: 'Bash executor seam',
  555. mode: 'seam',
  556. implementations: ['bash-local', 'bash-sandbox', 'pwsh-local'],
  557. consumers: ['tool-bash', 'tool-pwsh', 'hooks-claude-code', 'hooks-codex'],
  558. note: 'The model-facing shell tools and hook bridges consume this seam; sandboxed, remote, or PowerShell executors replace bash-local without touching them.',
  559. },
  560. {
  561. key: 'shellEnv',
  562. pkg: 'shell-env',
  563. title: 'Managed bash environment registry',
  564. mode: 'core',
  565. consumers: ['tool-bash', 'tool-pwsh'],
  566. note: 'Plugins declare effect-scoped DSH_* facts; each shell tool collects one trusted snapshot per execution and its executor rebuilds the namespace.',
  567. },
  568. {
  569. key: 'terminals',
  570. pkg: 'terminal',
  571. title: 'Persistent PTY session registry',
  572. mode: 'seam',
  573. implementations: ['terminal-bash'],
  574. consumers: ['tool-terminal'],
  575. note: 'The registry owns exact-Agent session identity and cleanup; backends own terminal mechanics, while tool-terminal exposes the owner-scoped model tools.',
  576. },
  577. {
  578. key: 'sandbox',
  579. pkg: 'sandbox',
  580. title: 'Process-sandbox seam',
  581. mode: 'seam',
  582. implementations: ['sandbox-local', 'sandbox-ssh'],
  583. consumers: ['bash-sandbox', 'terminal-bash'],
  584. 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.',
  585. },
  586. {
  587. key: 'sandboxPolicy',
  588. pkg: 'sandbox-policy',
  589. title: 'Sandbox policy home',
  590. mode: 'core',
  591. implementations: [],
  592. consumers: ['bash-sandbox', 'fs-sandbox', 'terminal-bash'],
  593. 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.',
  594. },
  595. {
  596. key: 'approval',
  597. pkg: 'user-approval',
  598. title: 'Approval seam',
  599. mode: 'seam',
  600. implementations: [],
  601. consumers: ['tools', 'tool-bash', 'acp'],
  602. 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`.',
  603. },
  604. {
  605. key: 'permissionPresets',
  606. pkg: 'permission-presets',
  607. title: 'Permission presets',
  608. mode: 'core',
  609. implementations: [],
  610. 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.',
  611. },
  612. {
  613. key: 'ptcRuntime',
  614. pkg: 'ptc-runtime',
  615. title: 'PTC execution seam',
  616. mode: 'seam',
  617. implementations: ['ptc-runtime-node', 'experimental-ptc-runtime-python'],
  618. consumers: ['tools', 'workflow-ptc'],
  619. note: 'Runs programs against host-provided async bindings; tools owns PTC presentation and workflow-ptc owns workflow orchestration.',
  620. },
  621. {
  622. key: 'fs',
  623. pkg: 'fs',
  624. title: 'Filesystem provider seam',
  625. mode: 'seam',
  626. implementations: ['fs-local', 'fs-sandbox', 'fs-ssh'],
  627. consumers: ['tool-fs'],
  628. companions: ['fs-observation-policy'],
  629. note: 'tool-fs executes read/write/edit through ctx.fs; fs-sandbox fences mutations by the shared sandbox mode; fs-observation-policy contributes observed-state checks through the fs/* event gate.',
  630. },
  631. {
  632. key: 'compaction',
  633. pkg: 'compaction',
  634. title: 'Compaction seam',
  635. mode: 'seam',
  636. implementations: ['compaction-basic'],
  637. consumers: ['compaction-basic'],
  638. note: 'The basic backend consumes post-step pressure and request-error recovery events; there is no model-facing compact tool.',
  639. },
  640. {
  641. key: 'subagents',
  642. pkg: 'subagent',
  643. title: 'Subagent provider and continuation service',
  644. mode: 'seam',
  645. implementations: ['subagent-spawn-in-process', 'subagent-fork-in-process', 'subagent-acp', 'subagent-codex', 'subagent-claude-code', 'subagent-dsh-sdk'],
  646. consumers: ['tool-subagent', 'tool-subagent-control', 'tool-ralph'],
  647. 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.',
  648. },
  649. {
  650. key: 'agentTeams',
  651. pkg: 'experimental-agent-team',
  652. title: 'Agent Teams coordination domain',
  653. mode: 'core',
  654. consumers: ['experimental-tool-agent-team', 'experimental-client-ui-agent-team'],
  655. note: 'Owns the implicit-root roster, durable peer mailbox, shared task DAG, continuable-child lifecycle, and generated Team Remote methods; tool-agent-team contributes model controls and client-ui-agent-team mounts the browser contribution.',
  656. },
  657. {
  658. key: 'inspector',
  659. pkg: 'inspector',
  660. title: 'Cross-realm runtime inspection',
  661. mode: 'core',
  662. note: 'Owns the Worker-hosted CDP target and the transport-independent Host and Client observation and Cordis-tree query API.',
  663. },
  664. {
  665. key: 'jobs',
  666. pkg: 'jobs',
  667. title: 'Background job registry',
  668. mode: 'seam',
  669. implementations: ['jobs-local'],
  670. consumers: ['tool-bash', 'tool-terminal', 'tool-subagent', 'tool-jobs'],
  671. note: 'Producers (background bash, PTY sends, and subagent delegations) register running work; tool-jobs is the model-facing controller that reads, lists, and kills it; jobs-local is the process-local registry.',
  672. },
  673. {
  674. key: 'web',
  675. pkg: 'web',
  676. title: 'Web access provider registry',
  677. mode: 'seam',
  678. implementations: ['web-search-exa', 'web-search-perplexity', 'web-search-deepseek', 'web-fetch-http'],
  679. consumers: ['tool-web'],
  680. note: 'Search and fetch providers register into one ctx.web seam; tool-web owns the stable model-facing names.',
  681. },
  682. {
  683. key: 'spillStore',
  684. pkg: 'spill',
  685. title: 'Spill storage seam',
  686. mode: 'seam',
  687. implementations: ['spill-local'],
  688. consumers: ['spill-policy'],
  689. 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.',
  690. },
  691. {
  692. key: 'directoryPicker',
  693. pkg: 'host-directory-picker',
  694. title: 'Workspace-directory picking seam',
  695. mode: 'seam',
  696. implementations: ['host-directory-picker-native', 'host-directory-picker-browse'],
  697. consumers: ['api-workspace-controller'],
  698. 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).',
  699. },
  700. {
  701. key: 'webServer',
  702. pkg: 'host-webserver',
  703. title: 'HTTP route registration',
  704. mode: 'core',
  705. consumers: ['client-connection', 'client-modules', 'client-hmr'],
  706. note: 'Plain node:http carrier: named-route registry, index transform taps, and the static dist fallback; web-transport plugins register their own routes.',
  707. },
  708. {
  709. key: 'clientModules',
  710. pkg: 'client-modules',
  711. title: 'Client plugin graph host',
  712. mode: 'core',
  713. consumers: ['client-hmr'],
  714. note: 'Composes the __DSH_BOOT__ entry graph from an incremental dsh.client scan, serves plugin bundles, and notifies rebuilt/graph-changed subscribers.',
  715. },
  716. {
  717. key: 'workflowEngine',
  718. pkg: 'workflow',
  719. title: 'Workflow script engine',
  720. mode: 'seam',
  721. implementations: ['workflow-ptc'],
  722. consumers: ['tool-workflow', 'tool-ralph'],
  723. note: 'One engine per context, as in bash, with no named-provider registry; the general workflow and fixed Ralph consumers start runs whose agent() calls fan out through ctx.subagents.',
  724. },
  725. {
  726. key: 'webhookRuntime',
  727. pkg: 'webhook',
  728. title: 'Webhook rule runtime',
  729. mode: 'core',
  730. consumers: ['webhook-github'],
  731. note: 'Provider adapters dispatch authenticated deliveries; trusted plugins register independent process-local rules, and the runtime turns non-null results into ordinary Workspace-backed Sessions without delivery or completion state.',
  732. },
  733. {
  734. key: 'lsp',
  735. pkg: 'lsp',
  736. title: 'Language-server navigation seam',
  737. mode: 'seam',
  738. implementations: ['lsp-stdio'],
  739. consumers: ['tool-lsp'],
  740. note: 'Provider registration and selection plus normalized query execution over exactly four operations; the seam offers no protocol escape hatch, so a backend translates into the normalized request and result.',
  741. },
  742. {
  743. key: 'dynamicCordisRunner',
  744. pkg: 'cordis-host-runner',
  745. title: 'Dynamic Cordis package host runner',
  746. mode: 'core',
  747. consumers: ['tool-cordis'],
  748. note: 'Owns the in-memory definition registry, the vm sandbox for host halves, and the request-run round trip; browser pages reach the same service over the wire through its remote namespace.',
  749. },
  750. {
  751. key: 'cordisInspect',
  752. pkg: 'cordis-host-runner',
  753. title: 'Dynamic Cordis inspect registry',
  754. mode: 'core',
  755. consumers: ['tool-cordis'],
  756. note: 'Registers host inspect providers, mirrors the client provider manifest, and routes client queries through the dynamic Cordis transport.',
  757. },
  758. ]
  759. function generatedHeader(title: string): string[] {
  760. return [
  761. '<!-- Generated by scripts/gen-doc-graphs.ts - do not edit by hand.',
  762. ' Run `pnpm run gen-doc-graphs` to regenerate. -->',
  763. '',
  764. `# ${title}`,
  765. '',
  766. ]
  767. }
  768. function maintenanceFooter(source: string): string[] {
  769. return [`Maintenance mode: ${source}.`, '']
  770. }
  771. function graphIndexLink(rel: string): string {
  772. return relative('docs', rel).replaceAll('\\', '/')
  773. }
  774. function linkFromDoc(docRel: string, targetRel: string): string {
  775. return relative(dirname(docRel), targetRel).replaceAll('\\', '/')
  776. }
  777. function mermaidCode(value: string): string {
  778. return `<code>${value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</code>`
  779. }
  780. function repoLink(path: string, label: string, up = '..'): string {
  781. return `[${label}](${up}/${path})`
  782. }
  783. function sourceLink(source: string, up = '..'): string {
  784. return repoLink(source.split(':')[0] ?? source, `\`${source}\``, up)
  785. }
  786. function pkgLink(pkg: Pkg | undefined, fallback: string, up = '..'): string {
  787. return pkg ? repoLink(pkg.rel, `\`${pkg.short}\``, up) : `\`${fallback}\``
  788. }
  789. function pkgList(names: string[] | undefined, pkgsByShort: Map<string, Pkg>): string {
  790. if (!names || names.length === 0) return '-'
  791. return names.map(name => pkgLink(pkgsByShort.get(name), name)).join(', ')
  792. }
  793. function tableCell(value: string): string {
  794. return value.replace(/\|/g, '\\|').replace(/\n/g, '<br>')
  795. }
  796. function assertServiceRolesComplete(services: readonly ServiceEntry[]): void {
  797. const discovered = new Set(services.map(service => service.key))
  798. const classified = new Set(SERVICE_ROLES.map(role => role.key))
  799. const missing = [...discovered].filter(key => !classified.has(key)).sort()
  800. const stale = [...classified].filter(key => !discovered.has(key)).sort()
  801. if (missing.length || stale.length) {
  802. throw new Error([
  803. missing.length ? `missing service role classification: ${missing.join(', ')}` : '',
  804. stale.length ? `stale service role classification: ${stale.join(', ')}` : '',
  805. ].filter(Boolean).join('; '))
  806. }
  807. }
  808. function renderCapabilitySeams(pkgs: Pkg[], services: readonly ServiceEntry[]): string {
  809. assertServiceRolesComplete(services)
  810. const pkgsByShort = new Map(pkgs.map(pkg => [pkg.short, pkg]))
  811. 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'
  812. const nodes = new Map<string, string>()
  813. const edges = new Set<string>()
  814. const companionEdges = new Set<string>()
  815. const addNode = (id: string, label: string): void => {
  816. if (!nodes.has(id)) nodes.set(id, ` ${id}["${escLabel(label)}"]`)
  817. }
  818. const addEdge = (from: string, to: string): void => { edges.add(` ${from} --> ${to}`) }
  819. const lines = generatedHeader('Capability Seams And Core Services')
  820. lines.push(
  821. '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.',
  822. '',
  823. '```mermaid',
  824. 'flowchart LR',
  825. )
  826. for (const role of SERVICE_ROLES) {
  827. const svc = nodeId('svc', role.key)
  828. const owner = nodeId('pkg', role.pkg)
  829. addNode(owner, role.pkg)
  830. addNode(svc, `ctx.${role.key}<br/>${role.title}`)
  831. addEdge(owner, svc)
  832. for (const impl of role.implementations ?? []) {
  833. addNode(nodeId('pkg', impl), impl)
  834. addEdge(nodeId('pkg', impl), svc)
  835. }
  836. for (const consumer of role.consumers ?? []) {
  837. addNode(nodeId('pkg', consumer), consumer)
  838. addEdge(svc, nodeId('pkg', consumer))
  839. }
  840. for (const companion of role.companions ?? []) {
  841. addNode(nodeId('pkg', companion), companion)
  842. companionEdges.add(` ${svc} -. event gate .-> ${nodeId('pkg', companion)}`)
  843. }
  844. }
  845. lines.push(...nodes.values(), ...[...edges].sort(), ...[...companionEdges].sort())
  846. lines.push('```', '', '| ctx key | Role | Owner | Implementations | Direct consumers | Companion plugins | Note |', '| --- | --- | --- | --- | --- | --- | --- |')
  847. for (const role of SERVICE_ROLES) {
  848. 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)} |`)
  849. }
  850. lines.push('', ...maintenanceFooter(maintenance))
  851. return lines.join('\n')
  852. }
  853. function parseExampleCordis(rel: string): ExamplePlugin[] {
  854. const text = readFileSync(resolve(root, rel), 'utf8')
  855. const plugins: ExamplePlugin[] = []
  856. let current: { id: string; name?: string } | null = null
  857. const flush = (): void => {
  858. if (current?.name) plugins.push({ id: current.id, name: current.name })
  859. }
  860. for (const line of text.split('\n')) {
  861. // Top-level rows (`- id:`) and bundle-patch insert rows (` - id:`).
  862. const id = /^\s*-\s+id:\s+(.+?)\s*$/.exec(line)
  863. if (id?.[1] !== undefined) {
  864. flush()
  865. current = { id: stripYamlScalar(id[1]) }
  866. continue
  867. }
  868. const name = /^\s+name:\s+(.+?)\s*$/.exec(line)
  869. if (name?.[1] !== undefined && current) current.name = stripYamlScalar(name[1])
  870. }
  871. flush()
  872. return plugins
  873. }
  874. function stripYamlScalar(value: string): string {
  875. return value.trim().replace(/^['"]|['"]$/g, '')
  876. }
  877. const APP_EXAMPLES = [
  878. {
  879. id: 'dsh_base',
  880. rel: 'apps/cli/composition.md',
  881. title: 'DSH Base Composition',
  882. label: 'packages/bundle/base/cordis.patch.yml',
  883. config: 'packages/bundle/base/cordis.patch.yml',
  884. summary: 'The dsh-base bundle patch shared by the web, headless, sdk, and acp profiles; their mode bundles and user layers patch over it, while sdk-minimal owns a separate standalone tree.',
  885. },
  886. ]
  887. type AppExample = typeof APP_EXAMPLES[number]
  888. function renderAppComposition(example: AppExample): string {
  889. const plugins = parseExampleCordis(example.config)
  890. const maintenance = 'hybrid: the patch row list is parsed from its `cordis.yml`; app package expansion is curated from package source'
  891. const lines = generatedHeader(example.title)
  892. lines.push(
  893. example.summary,
  894. '',
  895. '```mermaid',
  896. 'flowchart LR',
  897. ` cfg["${escLabel(example.label)}<br/>cordis.yml"]`,
  898. )
  899. for (const plugin of plugins) {
  900. const pluginNode = nodeId(`plugin_${example.id}`, plugin.id)
  901. lines.push(` ${pluginNode}["${escLabel(plugin.id)}<br/>${escLabel(plugin.name)}"]`)
  902. lines.push(` cfg --> ${pluginNode}`)
  903. }
  904. lines.push(
  905. '```',
  906. '',
  907. '| Plugin id | Package / module |',
  908. '| --- | --- |',
  909. ...plugins.map(plugin => `| \`${plugin.id}\` | \`${plugin.name}\` |`),
  910. '',
  911. `Source config: [\`${example.config}\`](${linkFromDoc(example.rel, example.config)}).`,
  912. )
  913. lines.push('', ...maintenanceFooter(maintenance))
  914. return lines.join('\n')
  915. }
  916. type CallSiteIndex = Map<ts.SignatureDeclaration | ts.JSDocSignature, ts.CallExpression[]>
  917. /**
  918. * The only method names visitSource classifies; receiver typing runs on these
  919. * alone. Obligation: every method name matched by a branch inside visitSource
  920. * must appear here — the prefilter drops non-members before any branch runs,
  921. * so a branch for an unlisted name is silently dead.
  922. */
  923. const EVENT_API_METHODS = new Set(['on', 'once', 'emit', 'parallel', 'serial', 'waterfall', 'dispatch'])
  924. /**
  925. * Collect event dispatch/listener relations from real cross-file receiver types.
  926. *
  927. * TODO: the program is seeded from the host aggregate alone (ts-project.ts
  928. * documents why: one program cannot hold both faces' Context merges), so a
  929. * Client package enters only when a host file imports it. Client-face
  930. * listeners on client-face events are therefore under-reported —
  931. * `connection/reset` omits `ui-skill`/`ui-agent-preset`. Closing it needs a
  932. * second Client program whose relations merge into these, not a wider seed.
  933. */
  934. export class EventRelationCollector {
  935. private readonly relations = new Map<string, EventRelation>()
  936. private readonly fileCallSites = new Map<ts.SourceFile, CallSiteIndex>()
  937. private readonly localCalleeProofs = new Map<ts.FunctionDeclaration, boolean>()
  938. private globalCallSites: CallSiteIndex | null = null
  939. private readonly contextType: ts.Type
  940. private readonly agentDispatchType: ts.Type
  941. private readonly eventsServiceType: ts.Type
  942. private readonly packageSourceFiles: ReadonlySet<ts.SourceFile>
  943. constructor(
  944. private readonly project: TypeScriptProject,
  945. private readonly sources: readonly PackageSource[],
  946. ) {
  947. this.contextType = this.declaredType('vendor/cordis/src/context.ts', 'Context')
  948. this.agentDispatchType = this.declaredType('packages/core/agent/src/dispatch.ts', 'AgentEventDispatch')
  949. this.eventsServiceType = this.declaredType('vendor/cordis/src/events.ts', 'EventsService')
  950. this.packageSourceFiles = new Set(sources.map(source => source.sourceFile))
  951. }
  952. /** Return all event relations discovered from the Program. */
  953. collect(): Map<string, EventRelation> {
  954. for (const source of this.sources) this.visitSource(source)
  955. return this.relations
  956. }
  957. /** Resolve one named class/interface declaration to its merged instance type. */
  958. private declaredType(relativePath: string, name: string): ts.Type {
  959. const sourceFile = this.project.sourceFile(relativePath)
  960. const declaration = sourceFile.statements.find((statement): statement is ts.ClassDeclaration | ts.InterfaceDeclaration => {
  961. return (ts.isClassDeclaration(statement) || ts.isInterfaceDeclaration(statement)) && statement.name?.text === name
  962. })
  963. const symbol = declaration?.name && this.project.checker.getSymbolAtLocation(declaration.name)
  964. if (!symbol) throw new Error(`cannot resolve TypeScript type ${name} from ${relativePath}`)
  965. return this.project.checker.getDeclaredTypeOfSymbol(symbol)
  966. }
  967. /** Index resolved function calls in the given files for narrow argument-flow recovery. */
  968. private buildCallSiteIndex(files: Iterable<ts.SourceFile>): CallSiteIndex {
  969. const index: CallSiteIndex = new Map()
  970. const visit = (node: ts.Node): void => {
  971. if (ts.isCallExpression(node)) {
  972. const declaration = this.project.checker.getResolvedSignature(node)?.declaration
  973. if (declaration) {
  974. const calls = index.get(declaration) ?? []
  975. calls.push(node)
  976. index.set(declaration, calls)
  977. }
  978. }
  979. ts.forEachChild(node, visit)
  980. }
  981. for (const file of files) visit(file)
  982. return index
  983. }
  984. /**
  985. * Return every indexed call resolving to one local helper declaration.
  986. * Fast path: when every same-file reference to the non-exported helper is
  987. * provably a direct callee, module scoping confines all of its calls to that
  988. * file, so only that file is indexed. Any other reference form may alias
  989. * the function value outward, so the original full package-source index
  990. * decides instead.
  991. */
  992. private callSitesFor(owner: ts.FunctionDeclaration): ts.CallExpression[] {
  993. if (!this.globalCallSites && !this.provenLocalCallee(owner)) {
  994. this.globalCallSites = this.buildCallSiteIndex(this.packageSourceFiles)
  995. }
  996. if (this.globalCallSites) return this.globalCallSites.get(owner) ?? []
  997. const file = owner.getSourceFile()
  998. let index = this.fileCallSites.get(file)
  999. if (!index) {
  1000. index = this.buildCallSiteIndex([file])
  1001. this.fileCallSites.set(file, index)
  1002. }
  1003. return index.get(owner) ?? []
  1004. }
  1005. /**
  1006. * Prove every same-file reference to one helper is a direct callee. The
  1007. * proof owns its premises: an exported helper or a helper in a global
  1008. * script file (no import/export means program-wide scope, callable from
  1009. * another file with no same-file reference at all) fails immediately.
  1010. * Alias escapes (re-export statements, default exports, value reads)
  1011. * resolve back to the owner symbol at a non-callee position and fail the
  1012. * proof, as does anything the scan cannot positively classify.
  1013. */
  1014. private provenLocalCallee(owner: ts.FunctionDeclaration): boolean {
  1015. const cached = this.localCalleeProofs.get(owner)
  1016. if (cached !== undefined) return cached
  1017. if (hasExportModifier(owner) || !ts.isExternalModule(owner.getSourceFile())) {
  1018. this.localCalleeProofs.set(owner, false)
  1019. return false
  1020. }
  1021. const name = owner.name
  1022. const ownerSymbol = name && this.project.checker.getSymbolAtLocation(name)
  1023. let proven = !!ownerSymbol
  1024. const refersToOwner = (identifier: ts.Identifier): boolean => {
  1025. // Shorthand properties resolve to the property symbol; ask for the value side.
  1026. const local = ts.isShorthandPropertyAssignment(identifier.parent)
  1027. ? this.project.checker.getShorthandAssignmentValueSymbol(identifier.parent)
  1028. : this.project.checker.getSymbolAtLocation(identifier)
  1029. if (!local) return false
  1030. const symbol = local.flags & ts.SymbolFlags.Alias
  1031. ? this.project.checker.getAliasedSymbol(local)
  1032. : local
  1033. return symbol === ownerSymbol
  1034. }
  1035. const visit = (node: ts.Node): void => {
  1036. if (!proven) return
  1037. if (ts.isIdentifier(node) && node !== name && node.text === name?.text
  1038. && !isDirectCallee(node) && refersToOwner(node)) {
  1039. proven = false
  1040. return
  1041. }
  1042. ts.forEachChild(node, visit)
  1043. }
  1044. visit(owner.getSourceFile())
  1045. this.localCalleeProofs.set(owner, proven)
  1046. return proven
  1047. }
  1048. /** Walk one package source file and classify event API calls by receiver type. */
  1049. private visitSource(source: PackageSource): void {
  1050. const visit = (node: ts.Node): void => {
  1051. if (ts.isCallExpression(node)) {
  1052. if (this.isAgentEventEmitter(node.expression)) {
  1053. const event = node.arguments[2]
  1054. if (event) {
  1055. for (const name of this.finiteStringValues(event) ?? []) {
  1056. this.addDispatcher(name, source.pkg, 'emitAgentEvent')
  1057. }
  1058. }
  1059. } else if (ts.isPropertyAccessExpression(node.expression) && EVENT_API_METHODS.has(node.expression.name.text)) {
  1060. const receiverKind = this.receiverKind(node.expression.expression)
  1061. const method = node.expression.name.text
  1062. if (receiverKind === 'events-service' && method === 'dispatch') {
  1063. const argumentList = node.arguments[1]
  1064. if (argumentList) {
  1065. for (const event of this.eventNamesFromArgumentList(argumentList, new Set())) {
  1066. this.addDispatcher(event, source.pkg, 'events.dispatch')
  1067. }
  1068. }
  1069. } else if (receiverKind === 'context' || receiverKind === 'agent-dispatch') {
  1070. const eventNames = this.eventNamesFromCall(node, receiverKind)
  1071. if (method === 'on' || method === 'once') {
  1072. for (const event of eventNames) this.ensure(event).listeners.add(source.pkg)
  1073. } else if (method === 'emit' || method === 'parallel' || method === 'serial' || method === 'waterfall') {
  1074. for (const event of eventNames) this.addDispatcher(event, source.pkg, method)
  1075. }
  1076. }
  1077. }
  1078. }
  1079. ts.forEachChild(node, visit)
  1080. }
  1081. visit(source.sourceFile)
  1082. }
  1083. /** Match the exported contained-notification helper by declaration identity. */
  1084. private isAgentEventEmitter(expression: ts.Expression): boolean {
  1085. if (!ts.isIdentifier(expression)) return false
  1086. const local = this.project.checker.getSymbolAtLocation(expression)
  1087. if (!local) return false
  1088. const symbol = local.flags & ts.SymbolFlags.Alias
  1089. ? this.project.checker.getAliasedSymbol(local)
  1090. : local
  1091. const declarations = symbol.declarations ?? []
  1092. return declarations.some((declaration) => {
  1093. return ts.isFunctionDeclaration(declaration)
  1094. && declaration.name?.text === 'emitAgentEvent'
  1095. && this.project.relativePath(declaration.getSourceFile()) === 'packages/core/agent/src/dispatch.ts'
  1096. })
  1097. }
  1098. /** Classify a receiver using assignability to the repository's actual event API types. */
  1099. private receiverKind(receiver: ts.Expression): EventReceiverKind | undefined {
  1100. const type = this.project.checker.getTypeAtLocation(receiver)
  1101. if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never)) return undefined
  1102. if (this.project.checker.isTypeAssignableTo(type, this.eventsServiceType)) return 'events-service'
  1103. if (this.project.checker.isTypeAssignableTo(type, this.contextType)) return 'context'
  1104. if (this.project.checker.isTypeAssignableTo(type, this.agentDispatchType)) return 'agent-dispatch'
  1105. return undefined
  1106. }
  1107. /** Resolve the event-name argument for Context and fused agent dispatch calls. */
  1108. private eventNamesFromCall(call: ts.CallExpression, receiverKind: Exclude<EventReceiverKind, 'events-service'>): Set<string> {
  1109. const candidates = receiverKind === 'context' ? call.arguments.slice(0, 2) : call.arguments.slice(0, 1)
  1110. for (const candidate of candidates) {
  1111. const values = this.finiteStringValues(candidate)
  1112. if (values) return values
  1113. }
  1114. return new Set()
  1115. }
  1116. /** Recover the event slot from the argument array handed to EventsService.dispatch(). */
  1117. private eventNamesFromArgumentList(expression: ts.Expression, seen: Set<ts.Node>): Set<string> {
  1118. const current = unwrapExpression(expression)
  1119. if (seen.has(current)) return new Set()
  1120. seen.add(current)
  1121. if (ts.isArrayLiteralExpression(current)) {
  1122. for (const element of current.elements.slice(0, 2)) {
  1123. if (ts.isOmittedExpression(element) || ts.isSpreadElement(element)) continue
  1124. const values = this.finiteStringValues(element)
  1125. if (values) return values
  1126. }
  1127. return new Set()
  1128. }
  1129. if (ts.isConditionalExpression(current)) {
  1130. return unionSets(
  1131. this.eventNamesFromArgumentList(current.whenTrue, new Set(seen)),
  1132. this.eventNamesFromArgumentList(current.whenFalse, new Set(seen)),
  1133. )
  1134. }
  1135. if (!ts.isIdentifier(current)) return new Set()
  1136. const symbol = this.project.checker.getSymbolAtLocation(current)
  1137. if (!symbol) return new Set()
  1138. const events = new Set<string>()
  1139. for (const declaration of symbol.declarations ?? []) {
  1140. if (ts.isVariableDeclaration(declaration) && declaration.initializer && isConstDeclaration(declaration)) {
  1141. addAll(events, this.eventNamesFromArgumentList(declaration.initializer, new Set(seen)))
  1142. } else if (ts.isParameter(declaration)) {
  1143. addAll(events, this.eventNamesFromParameter(declaration, seen))
  1144. }
  1145. }
  1146. return events
  1147. }
  1148. /** Follow a non-exported local helper parameter back to every resolved call site. */
  1149. private eventNamesFromParameter(parameter: ts.ParameterDeclaration, seen: Set<ts.Node>): Set<string> {
  1150. const owner = parameter.parent
  1151. if (!ts.isFunctionDeclaration(owner) || hasExportModifier(owner)) return new Set()
  1152. const index = owner.parameters.indexOf(parameter)
  1153. if (index < 0) return new Set()
  1154. const events = new Set<string>()
  1155. for (const call of this.callSitesFor(owner)) {
  1156. const argument = call.arguments[index]
  1157. if (argument) addAll(events, this.eventNamesFromArgumentList(argument, new Set(seen)))
  1158. }
  1159. return events
  1160. }
  1161. /** Return a finite string-literal value set, rejecting widened and generic strings. */
  1162. private finiteStringValues(expression: ts.Expression): Set<string> | undefined {
  1163. const current = unwrapExpression(expression)
  1164. if (ts.isStringLiteralLike(current)) return new Set([current.text])
  1165. if (this.isForwardedAgentEventParameter(current)) return undefined
  1166. return finiteStringTypeValues(this.project.checker.getTypeAtLocation(current))
  1167. }
  1168. /** Reject the contextual parameter inside the AgentEventDispatch forwarding object. */
  1169. private isForwardedAgentEventParameter(expression: ts.Expression): boolean {
  1170. if (!ts.isIdentifier(expression)) return false
  1171. const declarations = this.project.checker.getSymbolAtLocation(expression)?.declarations ?? []
  1172. return declarations.some((declaration) => {
  1173. if (!ts.isParameter(declaration)) return false
  1174. const method = declaration.parent
  1175. if (!ts.isMethodDeclaration(method) || !ts.isObjectLiteralExpression(method.parent)) return false
  1176. const contextualType = this.project.checker.getContextualType(method.parent)
  1177. return contextualType !== undefined
  1178. && this.project.checker.isTypeAssignableTo(contextualType, this.agentDispatchType)
  1179. })
  1180. }
  1181. /** Get or create one relation row. */
  1182. private ensure(event: string): EventRelation {
  1183. const existing = this.relations.get(event)
  1184. if (existing) return existing
  1185. const relation = { dispatchers: new Map<string, Set<string>>(), listeners: new Set<string>() }
  1186. this.relations.set(event, relation)
  1187. return relation
  1188. }
  1189. /** Add one dispatcher method without duplicating package/method labels. */
  1190. private addDispatcher(event: string, pkg: string, method: string): void {
  1191. const relation = this.ensure(event)
  1192. const methods = relation.dispatchers.get(pkg) ?? new Set<string>()
  1193. methods.add(method)
  1194. relation.dispatchers.set(pkg, methods)
  1195. }
  1196. }
  1197. /** Return whether an identifier is the callee of a call, seen through value-preserving wrappers. */
  1198. function isDirectCallee(identifier: ts.Identifier): boolean {
  1199. let current: ts.Node = identifier
  1200. while (
  1201. ts.isParenthesizedExpression(current.parent)
  1202. || ts.isAsExpression(current.parent)
  1203. || ts.isTypeAssertionExpression(current.parent)
  1204. || ts.isNonNullExpression(current.parent)
  1205. || ts.isSatisfiesExpression(current.parent)
  1206. ) {
  1207. current = current.parent
  1208. }
  1209. return ts.isCallExpression(current.parent) && current.parent.expression === current
  1210. }
  1211. /** Peel syntax-only wrappers that do not change an expression's runtime value. */
  1212. function unwrapExpression(expression: ts.Expression): ts.Expression {
  1213. let current = expression
  1214. while (
  1215. ts.isParenthesizedExpression(current)
  1216. || ts.isAsExpression(current)
  1217. || ts.isTypeAssertionExpression(current)
  1218. || ts.isNonNullExpression(current)
  1219. || ts.isSatisfiesExpression(current)
  1220. ) {
  1221. current = current.expression
  1222. }
  1223. return current
  1224. }
  1225. /** Return every value only when a type is a closed string-literal union. */
  1226. function finiteStringTypeValues(type: ts.Type): Set<string> | undefined {
  1227. if (type.flags & ts.TypeFlags.StringLiteral) {
  1228. return new Set([(type as ts.StringLiteralType).value])
  1229. }
  1230. if (type.flags & ts.TypeFlags.Never) return new Set()
  1231. if (!type.isUnion()) return undefined
  1232. const values = new Set<string>()
  1233. for (const member of type.types) {
  1234. const memberValues = finiteStringTypeValues(member)
  1235. if (!memberValues) return undefined
  1236. addAll(values, memberValues)
  1237. }
  1238. return values
  1239. }
  1240. /** Return whether a variable declaration belongs to a const declaration list. */
  1241. function isConstDeclaration(declaration: ts.VariableDeclaration): boolean {
  1242. return (declaration.parent.flags & ts.NodeFlags.Const) !== 0
  1243. }
  1244. /** Return whether a declaration is visible to callers outside its source module. */
  1245. function hasExportModifier(node: ts.Node): boolean {
  1246. return ts.canHaveModifiers(node) && (ts.getModifiers(node)?.some((modifier) => {
  1247. return modifier.kind === ts.SyntaxKind.ExportKeyword || modifier.kind === ts.SyntaxKind.DefaultKeyword
  1248. }) ?? false)
  1249. }
  1250. /** Add every member of source to target. */
  1251. function addAll<T>(target: Set<T>, source: ReadonlySet<T>): void {
  1252. for (const value of source) target.add(value)
  1253. }
  1254. /** Return the union of two sets without mutating either input. */
  1255. function unionSets<T>(left: ReadonlySet<T>, right: ReadonlySet<T>): Set<T> {
  1256. const out = new Set(left)
  1257. addAll(out, right)
  1258. return out
  1259. }
  1260. /**
  1261. * Select the package source files of one project in deterministic order.
  1262. * @param project - the loaded repository TypeScript project.
  1263. * @returns `packages/<group>/<pkg>/src` files tagged with their package name.
  1264. */
  1265. export function collectPackageSources(project: TypeScriptProject): PackageSource[] {
  1266. return project.sourceFiles().flatMap((sourceFile): PackageSource[] => {
  1267. const rel = project.relativePath(sourceFile)
  1268. const match = /^packages\/[^/]+\/([^/]+)\/src\/.+\.ts$/.exec(rel)
  1269. return match?.[1] ? [{ rel, pkg: match[1], sourceFile }] : []
  1270. }).sort((left, right) => left.rel.localeCompare(right.rel))
  1271. }
  1272. function collectEventRelations(): Map<string, EventRelation> {
  1273. const project = new TypeScriptProject(root)
  1274. return new EventRelationCollector(project, collectPackageSources(project)).collect()
  1275. }
  1276. function relationPackages(map: Map<string, Set<string>>, pkgsByShort: Map<string, Pkg>): string {
  1277. if (map.size === 0) return '-'
  1278. return [...map.entries()]
  1279. .sort(([a], [b]) => a.localeCompare(b))
  1280. .map(([pkg, methods]) => `${pkgLink(pkgsByShort.get(pkg), pkg)} (${[...methods].sort().map(m => `\`${m}\``).join(', ')})`)
  1281. .join(', ')
  1282. }
  1283. function listenerPackages(listeners: Set<string>, pkgsByShort: Map<string, Pkg>): string {
  1284. if (listeners.size === 0) return '-'
  1285. return [...listeners].sort().map(pkg => pkgLink(pkgsByShort.get(pkg), pkg)).join(', ')
  1286. }
  1287. function renderEventRelations(pkgs: Pkg[], events: readonly EventEntry[]): string {
  1288. const relations = collectEventRelations()
  1289. const pkgsByShort = new Map(pkgs.map(pkg => [pkg.short, pkg]))
  1290. const maintenance = 'generated: Cordis event declarations and producer/listener edges are resolved from the repository TypeScript Program'
  1291. const lines = generatedHeader('Event Producer And Consumer Matrix')
  1292. lines.push(
  1293. 'This matrix shows which packages dispatch each harness-owned event and which packages listen to it. Events are many-to-many, so the dense relation data is presented as a table rather than one large graph. Receiver and event-name types also cover contained dispatch sites that deliberately bypass `ctx.emit`, such as subagent lifecycle containment.',
  1294. '',
  1295. '| Event | Mode | Declared in | Dispatchers | Listeners |',
  1296. '| --- | --- | --- | --- | --- |',
  1297. )
  1298. for (const event of [...events].sort((a, b) => a.name.localeCompare(b.name))) {
  1299. const relation = relations.get(event.name) ?? { dispatchers: new Map<string, Set<string>>(), listeners: new Set<string>() }
  1300. lines.push(`| \`${event.name}\` | \`${event.mode}\` | ${sourceLink(event.source)} | ${relationPackages(relation.dispatchers, pkgsByShort)} | ${listenerPackages(relation.listeners, pkgsByShort)} |`)
  1301. }
  1302. // Every declared event needs a dispatcher: zero means dead vocabulary or an
  1303. // unrecognized semantic dispatch form. Listener-free extension points remain
  1304. // valid. Client-declared events are exempt: the relation scan seeds the HOST
  1305. // aggregate program only (host+client cannot share one program — the cordis
  1306. // Context merges collide), so client dispatch sites are structurally
  1307. // invisible here; their rows stay in the table for the declarations' sake.
  1308. const undispatched = [...events]
  1309. .filter(event => !event.source.startsWith('packages/client/'))
  1310. .filter(event => (relations.get(event.name)?.dispatchers.size ?? 0) === 0)
  1311. .map(event => event.name)
  1312. .sort()
  1313. if (undispatched.length > 0) {
  1314. throw new Error(
  1315. `event-producer-consumer matrix: no dispatcher found for declared event${undispatched.length > 1 ? 's' : ''} `
  1316. + `${undispatched.map(name => `"${name}"`).join(', ')} — dead vocabulary, or a dispatch form the semantic scan misses `
  1317. + '(teach scripts/gen-doc-graphs.ts that form)',
  1318. )
  1319. }
  1320. const declared = new Set(events.map(event => event.name))
  1321. const extra = [...relations.keys()].filter(event => !declared.has(event)).sort()
  1322. if (extra.length > 0) {
  1323. lines.push('', '## Non-harness or undeclared event strings seen in package source', '', '| Event string | Dispatchers | Listeners |', '| --- | --- | --- |')
  1324. for (const event of extra) {
  1325. const relation = relations.get(event)
  1326. if (!relation) continue
  1327. lines.push(`| \`${event}\` | ${relationPackages(relation.dispatchers, pkgsByShort)} | ${listenerPackages(relation.listeners, pkgsByShort)} |`)
  1328. }
  1329. }
  1330. lines.push('', ...maintenanceFooter(maintenance))
  1331. return lines.join('\n')
  1332. }
  1333. function renderLifecycle(): string {
  1334. const maintenance = 'curated Mermaid sequence; exact event signatures live in the generated Cordis catalog'
  1335. return [
  1336. ...generatedHeader('Agent Turn And Step Lifecycle'),
  1337. 'This sequence is the visual companion to [architecture.md](architecture.md#turn-flow). It keeps durable replay facts on `session/event` and live control/status on `agent/*`.',
  1338. '',
  1339. '```mermaid',
  1340. 'sequenceDiagram',
  1341. ' participant User',
  1342. ' participant Agent',
  1343. ' participant Driver',
  1344. ' participant Hooks as hook listeners',
  1345. ' participant Prompt as ctx.systemPrompt',
  1346. ' participant LLM as ctx.llm',
  1347. ' participant Tools as ctx.tools',
  1348. ' participant Session',
  1349. ' participant SDK as UI or SDK listener',
  1350. ' User->>Agent: followup(content)',
  1351. ` Agent-->>SDK: ${mermaidCode('agent/inbox/spliced')}`,
  1352. ` Agent-->>SDK: ${mermaidCode('agent/inbox/inserted')} { message }`,
  1353. ' Agent->>Driver: queued work wakes driver',
  1354. ` Driver-->>SDK: ${mermaidCode('agent/status')} running`,
  1355. ` Driver->>Session: ${mermaidCode('turn/start')}`,
  1356. ' Note over Agent,Driver: claim pending next-step input plus one queued prompt',
  1357. ` Driver-->>SDK: ${mermaidCode('agent/inbox/spliced')} pure deletion`,
  1358. ` Driver-->>SDK: ${mermaidCode('agent/inbox/claimed')} { message, turn } per message`,
  1359. ` Driver->>Prompt: ${mermaidCode('system-prompt/assemble')} waterfall`,
  1360. ` Driver->>Hooks: ${mermaidCode('agent/pre-step')} waterfall`,
  1361. ' Hooks-->>Driver: authoritative reject or enter(messages)',
  1362. ' alt proposed step rejected, first batch empty, or pre-step failed',
  1363. ' Driver-->>Driver: claimed batch stays removed, the open turn spends no step',
  1364. ' else enter proposed step',
  1365. ` Driver->>Session: ${mermaidCode('step/start')}`,
  1366. ` Driver->>Hooks: ${mermaidCode('agent/request')} waterfall`,
  1367. ' Driver->>LLM: prepareCall(config, signal)',
  1368. ' Note over Driver,LLM: cancellation during either async phase commits neither system nor users',
  1369. ' Note over Driver,Session: synchronous admission using the prepared call capability',
  1370. ` Driver->>Session: ${mermaidCode('system/message')} ordered per-node reconciliation`,
  1371. ` Driver->>Session: ${mermaidCode('user/message')} per entered message`,
  1372. ` Driver->>Session: ${mermaidCode('request/header')} and ${mermaidCode('request/context')} as needed`,
  1373. ' Driver->>Driver: derive and freeze request from the log',
  1374. ` Driver->>LLM: bound prepared call through ${mermaidCode('llm/stream')} waterfall`,
  1375. ' LLM-->>Driver: StreamChunk*',
  1376. ` Driver-->>SDK: ${mermaidCode('agent/assistant-stream')} chunk*`,
  1377. ' alt final adapter or terminal in-band request failure',
  1378. ` Driver->>Session: ${mermaidCode('assistant/attempt')}`,
  1379. ` Driver-->>SDK: ${mermaidCode('agent/assistant-stream')} committed end`,
  1380. ` Driver->>Hooks: ${mermaidCode('agent/request-error')} waterfall`,
  1381. ' Hooks-->>Driver: return retry action or preserve the original error',
  1382. ' Note over Driver,LLM: retry in the open step: prepare and reconcile the same rendered assembly without repeating pre-step or users',
  1383. ' else model request succeeded',
  1384. ` Driver->>Session: ${mermaidCode('assistant/message')}`,
  1385. ` Driver-->>SDK: ${mermaidCode('agent/assistant-stream')} committed end`,
  1386. ' Driver->>Tools: classify pending call by executionMode',
  1387. ' loop barriers and bounded rolling pool, reclassify before start',
  1388. ' opt call starts',
  1389. ` Driver->>Session: ${mermaidCode('tool/call')}`,
  1390. ' Driver->>Tools: ordered pre, concurrent execute',
  1391. ' Tools-->>Session: tool-owned events when applicable',
  1392. ' end',
  1393. ' opt next model-order result ready',
  1394. ' Driver->>Tools: ordered post',
  1395. ` Driver->>Session: ${mermaidCode('tool/result')}`,
  1396. ' end',
  1397. ' end',
  1398. ` Driver->>Session: ${mermaidCode('step/end')}`,
  1399. ' opt natural stop and next-step inbox empty',
  1400. ` Driver->>Hooks: ${mermaidCode('agent/turn-stopping')} serial terminal checkpoint`,
  1401. ' end',
  1402. ' opt next-step input is pending',
  1403. ' Driver-->>Driver: claim pending next-step input',
  1404. ` Driver-->>SDK: ${mermaidCode('agent/inbox/claimed')} { message, turn } per message`,
  1405. ` Driver->>Hooks: ${mermaidCode('agent/pre-step')} waterfall`,
  1406. ' Hooks-->>Driver: authoritative reject or enter(messages)',
  1407. ' end',
  1408. ' end',
  1409. ' end',
  1410. ` Driver->>Session: ${mermaidCode('turn/end')}`,
  1411. ` Driver-->>SDK: ${mermaidCode('agent/status')} idle`,
  1412. '```',
  1413. '',
  1414. 'The `assistant/message` event records every successful provider call, including content-less and `max-tokens` finishes, and embeds the exact compact timed stream. Empty content stays out of derived history. A failed, retried, cancelled, or stream-error attempt that reaches settlement without a surface message records its stream as `assistant/attempt`. Live `agent/assistant-stream` chunk frames are transient; replay reads either durable settlement, and a hard process loss before settlement leaves no durable attempt stream.',
  1415. '',
  1416. '`dsh-compaction-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 runs within the open step and retries only when pruning or summarization advances the surface replacement generation; otherwise the original request error remains authoritative. Each retry prepares its call and reconciles the retained rendered assembly before request derivation, without repeating assembly, pre-step, or user admission.',
  1417. '',
  1418. 'The returned `agent/pre-step` decision is authoritative; listeners wrapping `next()` preserve downstream messages and `startsRequestSeries` unless replacement is intentional. Steering and injected context pass through the same waterfall after a later claim operation takes their next-step batch.',
  1419. '',
  1420. 'SDK users that need replayable transcript data should consume `session/event`; `agent/*` is the live coordination API for queue/status, prompt interception, request construction, steering, continuation, and errors.',
  1421. '',
  1422. ...maintenanceFooter(maintenance),
  1423. ].join('\n')
  1424. }
  1425. function renderToolPipeline(): string {
  1426. const maintenance = 'curated Mermaid flow; exact tool schemas and event signatures live in generated catalogs'
  1427. return [
  1428. ...generatedHeader('Tool Execution Pipeline'),
  1429. 'This graph shows where policy, hooks, sandboxing, filesystem guards, result rewriting, final-outcome observation, and UI rendering run without changing the loop. The `tools/pre-execute` waterfall runs first, monotonic guards run next, and the `tools/execute` and `tools/post-execute` waterfalls follow; the three waterfalls may transform a call. Definition-owned `finalizeContent` and `tools/result` run afterward.',
  1430. '',
  1431. '```mermaid',
  1432. 'flowchart TD',
  1433. ' model["Assistant message contains tool-call block"]',
  1434. ` toolCall["Session event: ${mermaidCode('tool/call')}<br/>logged before execution"]`,
  1435. ' presentCall["UI pending card<br/>presentCall(args)"]',
  1436. ` pre["${mermaidCode('tools/pre-execute')} waterfall<br/>hooks, permission, sandbox"]`,
  1437. ' guards["Registered monotonic guards<br/>deny or abstain; identity protected"]',
  1438. ' denied["denied or approval refused<br/>tool body skipped"]',
  1439. ` approval["${mermaidCode('ctx.approval')} one-shot prompt<br/>absent or unanswerable: deny"]`,
  1440. ` around["${mermaidCode('tools/execute')} waterfall<br/>timeout, retry, metrics (around dispatch)"]`,
  1441. ' toolBody["Registered tool execute() body"]',
  1442. ` fsGate["${mermaidCode('fs/write-intent')} or ${mermaidCode('fs/edit-intent')}<br/>tool-fs mutations only"]`,
  1443. ` owned["Tool-owned session events<br/>${mermaidCode('todo/write')}, ${mermaidCode('fs/observed')}, ${mermaidCode('hook/invoked')}, ${mermaidCode('hook/result')}, ${mermaidCode('tool/ptc-dispatch')}"]`,
  1444. ` post["${mermaidCode('tools/post-execute')} waterfall<br/>accept, block, replace, add context"]`,
  1445. ' normalized["Registry outer normalization<br/>pipeline/result snapshot throws become isError"]',
  1446. ' finalize["ToolDefinition.finalizeContent<br/>last content-only invariant"]',
  1447. ` final["${mermaidCode('tools/result')} synchronous notification<br/>frozen authoritative outcome"]`,
  1448. ' context["Active-batch additionalContexts FIFO<br/>injected user/message after recorded tool results"]',
  1449. ` toolResult["Session event: ${mermaidCode('tool/result')}<br/>single model-facing outcome"]`,
  1450. ' allResults["Tool batch settled<br/>recorded tool/result events complete"]',
  1451. ' presentResult["UI completed card<br/>presentResult(args, result)"]',
  1452. ' model --> toolCall',
  1453. ' toolCall --> presentCall',
  1454. ' toolCall --> pre',
  1455. ' pre -->|allow| guards',
  1456. ' guards -->|allow| around',
  1457. ' guards -->|deny| denied',
  1458. ' guards -.->|throw| normalized',
  1459. ' around --> toolBody',
  1460. ' pre -->|deny| denied',
  1461. ' pre -->|ask| approval',
  1462. ' approval -->|allowed-once| guards',
  1463. ' approval -->|rejected, cancelled, unavailable| denied',
  1464. ' approval -.->|throw| normalized',
  1465. ' denied --> post',
  1466. ' pre -.->|throw| normalized',
  1467. ' toolBody --> fsGate',
  1468. ' fsGate --> toolBody',
  1469. ' toolBody --> owned',
  1470. ' toolBody --> around',
  1471. ' around --> post',
  1472. ' around -.->|wrapper throws| normalized',
  1473. ' post -.->|throw| normalized',
  1474. ' post --> finalize',
  1475. ' normalized --> finalize',
  1476. ' finalize --> final',
  1477. ' final --> toolResult',
  1478. ' toolResult --> presentResult',
  1479. ' toolResult --> allResults',
  1480. ' allResults --> context',
  1481. '```',
  1482. '',
  1483. '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. PTC mode sends both the reserved `run_code` transport and its serialized sub-calls through the pipeline; sub-calls carry the parent token, log `tool/ptc-dispatch`, return denials as binding rejections, and omit `additionalContexts` to preserve call/result adjacency.',
  1484. '',
  1485. ...maintenanceFooter(maintenance),
  1486. ].join('\n')
  1487. }
  1488. function renderDocs(): GraphDoc[] {
  1489. const pkgs = collectPackageGraph(root, GROUP_ORDER, 'gen-doc-graphs')
  1490. const { model } = projectCordisCatalog(root, CORDIS_CATALOG_POLICY)
  1491. const docs: GraphDoc[] = [
  1492. { rel: 'docs/capability-seams.md', content: renderCapabilitySeams(pkgs, model.services) },
  1493. ...APP_EXAMPLES.map(example => ({ rel: example.rel, content: renderAppComposition(example) })),
  1494. { rel: 'docs/event-producer-consumer.md', content: renderEventRelations(pkgs, model.events) },
  1495. { rel: 'docs/agent-lifecycle.md', content: renderLifecycle() },
  1496. { rel: 'docs/tool-execution-pipeline.md', content: renderToolPipeline() },
  1497. ]
  1498. docs.unshift({ rel: 'docs/graph-atlas.md', content: renderIndex(docs) })
  1499. return docs
  1500. }
  1501. function renderIndex(docs: GraphDoc[]): string {
  1502. const labels: Record<string, string> = {
  1503. 'docs/capability-seams.md': 'capability seams and core services',
  1504. 'apps/cli/composition.md': 'dsh shared base composition',
  1505. 'docs/event-producer-consumer.md': 'event producer/consumer matrix',
  1506. 'docs/agent-lifecycle.md': 'agent turn and step lifecycle',
  1507. 'docs/tool-execution-pipeline.md': 'tool execution pipeline',
  1508. }
  1509. const modes: Record<string, string> = {
  1510. 'docs/capability-seams.md': 'hybrid generated',
  1511. 'apps/cli/composition.md': 'hybrid generated',
  1512. 'docs/event-producer-consumer.md': 'hybrid generated',
  1513. 'docs/agent-lifecycle.md': 'curated',
  1514. 'docs/tool-execution-pipeline.md': 'curated',
  1515. }
  1516. const rows = [
  1517. '| [module dependency graph](module-graph.md) | `generated` |',
  1518. '| [tool schema catalog and package map](tool-catalog.md) | `generated` |',
  1519. ...docs.map((doc) => {
  1520. const link = graphIndexLink(doc.rel)
  1521. return `| [${labels[doc.rel] ?? link}](${link}) | \`${modes[doc.rel] ?? 'generated'}\` |`
  1522. }),
  1523. ]
  1524. const maintenance = 'mixed: each linked page declares generated, hybrid, or curated mode'
  1525. return [
  1526. ...generatedHeader('Documentation Graph Index'),
  1527. 'These diagrams show relationships that the generated catalogs do not. Use them to find package relationships, capability seams, event flow, model-facing tools, app composition, and runtime lifecycle paths. Exact signatures and type definitions still live in the [subsystem pages](subsystems/core.md) (types + the generated Cordis API regions) and [tool-catalog.md](tool-catalog.md).',
  1528. '',
  1529. '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).',
  1530. '',
  1531. '| Graph | Mode |',
  1532. '| --- | --- |',
  1533. ...rows,
  1534. '',
  1535. 'Regenerate with `pnpm run gen-doc-graphs`; verify freshness with `pnpm run verify-doc-graphs`.',
  1536. '',
  1537. ...maintenanceFooter(maintenance),
  1538. ].join('\n')
  1539. }
  1540. function main(): void {
  1541. const docs = renderDocs()
  1542. if (process.argv.includes('--check')) {
  1543. const stale: string[] = []
  1544. for (const doc of docs) {
  1545. const abs = resolve(root, doc.rel)
  1546. const committed = existsSync(abs) ? readFileSync(abs, 'utf8') : null
  1547. if (committed !== doc.content) stale.push(doc.rel)
  1548. }
  1549. if (stale.length === 0) {
  1550. console.log(`gen-doc-graphs: ${docs.length} graph doc(s) are up to date.`)
  1551. return
  1552. }
  1553. console.error(`gen-doc-graphs: stale graph doc(s): ${stale.join(', ')}. Run \`pnpm run gen-doc-graphs\` and commit the result.`)
  1554. process.exit(1)
  1555. }
  1556. for (const doc of docs) {
  1557. mkdirSync(dirname(resolve(root, doc.rel)), { recursive: true })
  1558. writeFileSync(resolve(root, doc.rel), doc.content)
  1559. }
  1560. console.log(`gen-doc-graphs: wrote ${docs.length} graph doc(s).`)
  1561. }
  1562. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  1563. main()
  1564. }