gen-doc-graphs.ts 72 KB

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