gen-doc-graphs.ts 69 KB

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