gen-doc-graphs.ts 67 KB

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