gen-doc-graphs.ts 68 KB

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