gen-doc-graphs.ts 65 KB

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