gen-doc-graphs.ts 71 KB

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