gen-doc-graphs.ts 66 KB

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