gen-doc-graphs.ts 67 KB

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