gen-doc-graphs.ts 67 KB

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