gen-doc-graphs.ts 65 KB

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