gen-doc-graphs.ts 61 KB

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