gen-doc-graphs.ts 69 KB

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