gen-doc-graphs.ts 69 KB

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