gen-doc-graphs.ts 66 KB

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