gen-doc-graphs.ts 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372
  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'],
  314. note: 'The bash executors, the LSP host, and the ACP subagent backend 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'],
  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. const id = /^-\s+id:\s+(.+?)\s*$/.exec(line)
  579. if (id?.[1] !== undefined) {
  580. flush()
  581. current = { id: stripYamlScalar(id[1]) }
  582. continue
  583. }
  584. const name = /^\s+name:\s+(.+?)\s*$/.exec(line)
  585. if (name?.[1] !== undefined && current) current.name = stripYamlScalar(name[1])
  586. }
  587. flush()
  588. return plugins
  589. }
  590. function stripYamlScalar(value: string): string {
  591. return value.trim().replace(/^['"]|['"]$/g, '')
  592. }
  593. const APP_EXAMPLES = [
  594. {
  595. id: 'dsh_base',
  596. rel: 'apps/cli/composition.md',
  597. title: 'DSH Base Composition',
  598. label: 'apps/cli/config/base.cordis.yml',
  599. config: 'apps/cli/config/base.cordis.yml',
  600. summary: 'The raw CLI applies one required caller-selected patch list over this shared base; Web and headless apply their own shipped overlays.',
  601. },
  602. {
  603. id: 'headless',
  604. rel: 'examples/headless-agent/composition.md',
  605. title: 'Headless Agent App Composition',
  606. label: 'examples/headless-agent',
  607. config: 'examples/headless-agent/cordis.yml',
  608. 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.',
  609. },
  610. {
  611. id: 'acp',
  612. rel: 'examples/acp-agent/composition.md',
  613. title: 'ACP Automation App Composition',
  614. label: 'examples/acp-agent',
  615. config: 'examples/acp-agent/cordis.yml',
  616. 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.',
  617. },
  618. ]
  619. type AppExample = typeof APP_EXAMPLES[number]
  620. function renderAppExpansion(lines: string[], appNode: string, pluginName: string): void {
  621. const agentCore = nodeId('bundle', 'agent_core')
  622. const jsonl = nodeId('bundle', 'jsonl')
  623. lines.push(` ${appNode} --> ${agentCore}["@deepseek-ai/dsh-agent-spine-demo"]`)
  624. lines.push(` ${appNode} --> ${jsonl}["@deepseek-ai/dsh-session-persistence-jsonl"]`)
  625. if (pluginName === '@deepseek-ai/dsh-cli-demo') {
  626. lines.push(` ${appNode} --> ${nodeId('frontdoor', 'cli')}["one-shot driver<br/>format-pure stdout<br/>fresh top-level agent"]`)
  627. } else if (pluginName === '@deepseek-ai/dsh-acp-demo') {
  628. lines.push(` ${appNode} --> ${nodeId('frontdoor', 'acp')}["@deepseek-ai/dsh-acp<br/>automation-only JSON-RPC stdio<br/>fresh sessions created by client"]`)
  629. }
  630. lines.push(
  631. ` ${agentCore} --> ${nodeId('spine', 'llm')}["ctx.llm"]`,
  632. ` ${agentCore} --> ${nodeId('spine', 'sessions')}["ctx.sessions"]`,
  633. ` ${agentCore} --> ${nodeId('spine', 'tools')}["ctx.tools + tool-bash"]`,
  634. ` ${agentCore} --> ${nodeId('spine', 'loop')}["ctx.agents + ctx.agentLoop"]`,
  635. )
  636. }
  637. function renderAppComposition(example: AppExample): string {
  638. const plugins = parseExampleCordis(example.config)
  639. const maintenance = 'hybrid: the leaf plugin list is parsed from its `cordis.yml`; app package expansion is curated from package source'
  640. const lines = generatedHeader(example.title)
  641. lines.push(
  642. example.summary,
  643. '',
  644. '```mermaid',
  645. 'flowchart LR',
  646. ` cfg["${escLabel(example.label)}<br/>cordis.yml"]`,
  647. )
  648. for (const plugin of plugins) {
  649. const pluginNode = nodeId(`plugin_${example.id}`, plugin.id)
  650. lines.push(` ${pluginNode}["${escLabel(plugin.id)}<br/>${escLabel(plugin.name)}"]`)
  651. lines.push(` cfg --> ${pluginNode}`)
  652. if (plugin.name === '@deepseek-ai/dsh-cli-demo' || plugin.name === '@deepseek-ai/dsh-acp-demo') {
  653. renderAppExpansion(lines, pluginNode, plugin.name)
  654. }
  655. }
  656. lines.push(
  657. '```',
  658. '',
  659. '| Plugin id | Package / module |',
  660. '| --- | --- |',
  661. ...plugins.map(plugin => `| \`${plugin.id}\` | \`${plugin.name}\` |`),
  662. '',
  663. `Source config: [\`${example.config}\`](${linkFromDoc(example.rel, example.config)}).`,
  664. )
  665. lines.push('', ...maintenanceFooter(maintenance))
  666. return lines.join('\n')
  667. }
  668. type CallSiteIndex = Map<ts.SignatureDeclaration | ts.JSDocSignature, ts.CallExpression[]>
  669. /**
  670. * The only method names visitSource classifies; receiver typing runs on these
  671. * alone. Obligation: every method name matched by a branch inside visitSource
  672. * must appear here — the prefilter drops non-members before any branch runs,
  673. * so a branch for an unlisted name is silently dead.
  674. */
  675. const EVENT_API_METHODS = new Set(['on', 'once', 'emit', 'parallel', 'serial', 'waterfall', 'dispatch'])
  676. /** Collect event dispatch/listener relations from real cross-file receiver types. */
  677. export class EventRelationCollector {
  678. private readonly relations = new Map<string, EventRelation>()
  679. private readonly fileCallSites = new Map<ts.SourceFile, CallSiteIndex>()
  680. private readonly localCalleeProofs = new Map<ts.FunctionDeclaration, boolean>()
  681. private globalCallSites: CallSiteIndex | null = null
  682. private readonly contextType: ts.Type
  683. private readonly agentDispatchType: ts.Type
  684. private readonly eventsServiceType: ts.Type
  685. private readonly packageSourceFiles: ReadonlySet<ts.SourceFile>
  686. constructor(
  687. private readonly project: TypeScriptProject,
  688. private readonly sources: readonly PackageSource[],
  689. ) {
  690. this.contextType = this.declaredType('vendor/cordis/src/context.ts', 'Context')
  691. this.agentDispatchType = this.declaredType('packages/core/agent/src/dispatch.ts', 'AgentEventDispatch')
  692. this.eventsServiceType = this.declaredType('vendor/cordis/src/events.ts', 'EventsService')
  693. this.packageSourceFiles = new Set(sources.map(source => source.sourceFile))
  694. }
  695. /** Return all event relations discovered from the Program. */
  696. collect(): Map<string, EventRelation> {
  697. for (const source of this.sources) this.visitSource(source)
  698. return this.relations
  699. }
  700. /** Resolve one named class/interface declaration to its merged instance type. */
  701. private declaredType(relativePath: string, name: string): ts.Type {
  702. const sourceFile = this.project.sourceFile(relativePath)
  703. const declaration = sourceFile.statements.find((statement): statement is ts.ClassDeclaration | ts.InterfaceDeclaration => {
  704. return (ts.isClassDeclaration(statement) || ts.isInterfaceDeclaration(statement)) && statement.name?.text === name
  705. })
  706. const symbol = declaration?.name && this.project.checker.getSymbolAtLocation(declaration.name)
  707. if (!symbol) throw new Error(`cannot resolve TypeScript type ${name} from ${relativePath}`)
  708. return this.project.checker.getDeclaredTypeOfSymbol(symbol)
  709. }
  710. /** Index resolved function calls in the given files for narrow argument-flow recovery. */
  711. private buildCallSiteIndex(files: Iterable<ts.SourceFile>): CallSiteIndex {
  712. const index: CallSiteIndex = new Map()
  713. const visit = (node: ts.Node): void => {
  714. if (ts.isCallExpression(node)) {
  715. const declaration = this.project.checker.getResolvedSignature(node)?.declaration
  716. if (declaration) {
  717. const calls = index.get(declaration) ?? []
  718. calls.push(node)
  719. index.set(declaration, calls)
  720. }
  721. }
  722. ts.forEachChild(node, visit)
  723. }
  724. for (const file of files) visit(file)
  725. return index
  726. }
  727. /**
  728. * Return every indexed call resolving to one local helper declaration.
  729. * Fast path: when every same-file reference to the non-exported helper is
  730. * provably a direct callee, module scoping confines all of its calls to that
  731. * file, so only that file is indexed. Any other reference shape may alias
  732. * the function value outward, so the original full package-source index
  733. * decides instead.
  734. */
  735. private callSitesFor(owner: ts.FunctionDeclaration): ts.CallExpression[] {
  736. if (!this.globalCallSites && !this.provenLocalCallee(owner)) {
  737. this.globalCallSites = this.buildCallSiteIndex(this.packageSourceFiles)
  738. }
  739. if (this.globalCallSites) return this.globalCallSites.get(owner) ?? []
  740. const file = owner.getSourceFile()
  741. let index = this.fileCallSites.get(file)
  742. if (!index) {
  743. index = this.buildCallSiteIndex([file])
  744. this.fileCallSites.set(file, index)
  745. }
  746. return index.get(owner) ?? []
  747. }
  748. /**
  749. * Prove every same-file reference to one helper is a direct callee. The
  750. * proof owns its premises: an exported helper or a helper in a global
  751. * script file (no import/export means program-wide scope, callable from
  752. * another file with no same-file reference at all) fails immediately.
  753. * Alias escapes (re-export statements, default exports, value reads)
  754. * resolve back to the owner symbol at a non-callee position and fail the
  755. * proof, as does anything the scan cannot positively classify.
  756. */
  757. private provenLocalCallee(owner: ts.FunctionDeclaration): boolean {
  758. const cached = this.localCalleeProofs.get(owner)
  759. if (cached !== undefined) return cached
  760. if (hasExportModifier(owner) || !ts.isExternalModule(owner.getSourceFile())) {
  761. this.localCalleeProofs.set(owner, false)
  762. return false
  763. }
  764. const name = owner.name
  765. const ownerSymbol = name && this.project.checker.getSymbolAtLocation(name)
  766. let proven = !!ownerSymbol
  767. const refersToOwner = (identifier: ts.Identifier): boolean => {
  768. // Shorthand properties resolve to the property symbol; ask for the value side.
  769. const local = ts.isShorthandPropertyAssignment(identifier.parent)
  770. ? this.project.checker.getShorthandAssignmentValueSymbol(identifier.parent)
  771. : this.project.checker.getSymbolAtLocation(identifier)
  772. if (!local) return false
  773. const symbol = local.flags & ts.SymbolFlags.Alias
  774. ? this.project.checker.getAliasedSymbol(local)
  775. : local
  776. return symbol === ownerSymbol
  777. }
  778. const visit = (node: ts.Node): void => {
  779. if (!proven) return
  780. if (ts.isIdentifier(node) && node !== name && node.text === name?.text
  781. && !isDirectCallee(node) && refersToOwner(node)) {
  782. proven = false
  783. return
  784. }
  785. ts.forEachChild(node, visit)
  786. }
  787. visit(owner.getSourceFile())
  788. this.localCalleeProofs.set(owner, proven)
  789. return proven
  790. }
  791. /** Walk one package source file and classify event API calls by receiver type. */
  792. private visitSource(source: PackageSource): void {
  793. const visit = (node: ts.Node): void => {
  794. if (ts.isCallExpression(node)) {
  795. if (this.isAgentEventEmitter(node.expression)) {
  796. const event = node.arguments[2]
  797. if (event) {
  798. for (const name of this.finiteStringValues(event) ?? []) {
  799. this.addDispatcher(name, source.pkg, 'emitAgentEvent')
  800. }
  801. }
  802. } else if (ts.isPropertyAccessExpression(node.expression) && EVENT_API_METHODS.has(node.expression.name.text)) {
  803. const receiverKind = this.receiverKind(node.expression.expression)
  804. const method = node.expression.name.text
  805. if (receiverKind === 'events-service' && method === 'dispatch') {
  806. const argumentList = node.arguments[1]
  807. if (argumentList) {
  808. for (const event of this.eventNamesFromArgumentList(argumentList, new Set())) {
  809. this.addDispatcher(event, source.pkg, 'events.dispatch')
  810. }
  811. }
  812. } else if (receiverKind === 'context' || receiverKind === 'agent-dispatch') {
  813. const eventNames = this.eventNamesFromCall(node, receiverKind)
  814. if (method === 'on' || method === 'once') {
  815. for (const event of eventNames) this.ensure(event).listeners.add(source.pkg)
  816. } else if (method === 'emit' || method === 'parallel' || method === 'serial' || method === 'waterfall') {
  817. for (const event of eventNames) this.addDispatcher(event, source.pkg, method)
  818. }
  819. }
  820. }
  821. }
  822. ts.forEachChild(node, visit)
  823. }
  824. visit(source.sourceFile)
  825. }
  826. /** Match the exported contained-notification helper by declaration identity. */
  827. private isAgentEventEmitter(expression: ts.Expression): boolean {
  828. if (!ts.isIdentifier(expression)) return false
  829. const local = this.project.checker.getSymbolAtLocation(expression)
  830. if (!local) return false
  831. const symbol = local.flags & ts.SymbolFlags.Alias
  832. ? this.project.checker.getAliasedSymbol(local)
  833. : local
  834. const declarations = symbol.declarations ?? []
  835. return declarations.some((declaration) => {
  836. return ts.isFunctionDeclaration(declaration)
  837. && declaration.name?.text === 'emitAgentEvent'
  838. && this.project.relativePath(declaration.getSourceFile()) === 'packages/core/agent/src/dispatch.ts'
  839. })
  840. }
  841. /** Classify a receiver using assignability to the repository's actual event API types. */
  842. private receiverKind(receiver: ts.Expression): EventReceiverKind | undefined {
  843. const type = this.project.checker.getTypeAtLocation(receiver)
  844. if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never)) return undefined
  845. if (this.project.checker.isTypeAssignableTo(type, this.eventsServiceType)) return 'events-service'
  846. if (this.project.checker.isTypeAssignableTo(type, this.contextType)) return 'context'
  847. if (this.project.checker.isTypeAssignableTo(type, this.agentDispatchType)) return 'agent-dispatch'
  848. return undefined
  849. }
  850. /** Resolve the event-name argument for Context and fused agent dispatch calls. */
  851. private eventNamesFromCall(call: ts.CallExpression, receiverKind: Exclude<EventReceiverKind, 'events-service'>): Set<string> {
  852. const candidates = receiverKind === 'context' ? call.arguments.slice(0, 2) : call.arguments.slice(0, 1)
  853. for (const candidate of candidates) {
  854. const values = this.finiteStringValues(candidate)
  855. if (values) return values
  856. }
  857. return new Set()
  858. }
  859. /** Recover the event slot from the argument array handed to EventsService.dispatch(). */
  860. private eventNamesFromArgumentList(expression: ts.Expression, seen: Set<ts.Node>): Set<string> {
  861. const current = unwrapExpression(expression)
  862. if (seen.has(current)) return new Set()
  863. seen.add(current)
  864. if (ts.isArrayLiteralExpression(current)) {
  865. for (const element of current.elements.slice(0, 2)) {
  866. if (ts.isOmittedExpression(element) || ts.isSpreadElement(element)) continue
  867. const values = this.finiteStringValues(element)
  868. if (values) return values
  869. }
  870. return new Set()
  871. }
  872. if (ts.isConditionalExpression(current)) {
  873. return unionSets(
  874. this.eventNamesFromArgumentList(current.whenTrue, new Set(seen)),
  875. this.eventNamesFromArgumentList(current.whenFalse, new Set(seen)),
  876. )
  877. }
  878. if (!ts.isIdentifier(current)) return new Set()
  879. const symbol = this.project.checker.getSymbolAtLocation(current)
  880. if (!symbol) return new Set()
  881. const events = new Set<string>()
  882. for (const declaration of symbol.declarations ?? []) {
  883. if (ts.isVariableDeclaration(declaration) && declaration.initializer && isConstDeclaration(declaration)) {
  884. addAll(events, this.eventNamesFromArgumentList(declaration.initializer, new Set(seen)))
  885. } else if (ts.isParameter(declaration)) {
  886. addAll(events, this.eventNamesFromParameter(declaration, seen))
  887. }
  888. }
  889. return events
  890. }
  891. /** Follow a non-exported local helper parameter back to every resolved call site. */
  892. private eventNamesFromParameter(parameter: ts.ParameterDeclaration, seen: Set<ts.Node>): Set<string> {
  893. const owner = parameter.parent
  894. if (!ts.isFunctionDeclaration(owner) || hasExportModifier(owner)) return new Set()
  895. const index = owner.parameters.indexOf(parameter)
  896. if (index < 0) return new Set()
  897. const events = new Set<string>()
  898. for (const call of this.callSitesFor(owner)) {
  899. const argument = call.arguments[index]
  900. if (argument) addAll(events, this.eventNamesFromArgumentList(argument, new Set(seen)))
  901. }
  902. return events
  903. }
  904. /** Return a finite string-literal value set, rejecting widened and generic strings. */
  905. private finiteStringValues(expression: ts.Expression): Set<string> | undefined {
  906. const current = unwrapExpression(expression)
  907. if (ts.isStringLiteralLike(current)) return new Set([current.text])
  908. if (this.isForwardedAgentEventParameter(current)) return undefined
  909. return finiteStringTypeValues(this.project.checker.getTypeAtLocation(current))
  910. }
  911. /** Reject the contextual parameter inside the AgentEventDispatch forwarding object. */
  912. private isForwardedAgentEventParameter(expression: ts.Expression): boolean {
  913. if (!ts.isIdentifier(expression)) return false
  914. const declarations = this.project.checker.getSymbolAtLocation(expression)?.declarations ?? []
  915. return declarations.some((declaration) => {
  916. if (!ts.isParameter(declaration)) return false
  917. const method = declaration.parent
  918. if (!ts.isMethodDeclaration(method) || !ts.isObjectLiteralExpression(method.parent)) return false
  919. const contextualType = this.project.checker.getContextualType(method.parent)
  920. return contextualType !== undefined
  921. && this.project.checker.isTypeAssignableTo(contextualType, this.agentDispatchType)
  922. })
  923. }
  924. /** Get or create one relation row. */
  925. private ensure(event: string): EventRelation {
  926. const existing = this.relations.get(event)
  927. if (existing) return existing
  928. const relation = { dispatchers: new Map<string, Set<string>>(), listeners: new Set<string>() }
  929. this.relations.set(event, relation)
  930. return relation
  931. }
  932. /** Add one dispatcher method without duplicating package/method labels. */
  933. private addDispatcher(event: string, pkg: string, method: string): void {
  934. const relation = this.ensure(event)
  935. const methods = relation.dispatchers.get(pkg) ?? new Set<string>()
  936. methods.add(method)
  937. relation.dispatchers.set(pkg, methods)
  938. }
  939. }
  940. /** Return whether an identifier is the callee of a call, seen through value-preserving wrappers. */
  941. function isDirectCallee(identifier: ts.Identifier): boolean {
  942. let current: ts.Node = identifier
  943. while (
  944. ts.isParenthesizedExpression(current.parent)
  945. || ts.isAsExpression(current.parent)
  946. || ts.isTypeAssertionExpression(current.parent)
  947. || ts.isNonNullExpression(current.parent)
  948. || ts.isSatisfiesExpression(current.parent)
  949. ) {
  950. current = current.parent
  951. }
  952. return ts.isCallExpression(current.parent) && current.parent.expression === current
  953. }
  954. /** Peel syntax-only wrappers that do not change an expression's runtime value. */
  955. function unwrapExpression(expression: ts.Expression): ts.Expression {
  956. let current = expression
  957. while (
  958. ts.isParenthesizedExpression(current)
  959. || ts.isAsExpression(current)
  960. || ts.isTypeAssertionExpression(current)
  961. || ts.isNonNullExpression(current)
  962. || ts.isSatisfiesExpression(current)
  963. ) {
  964. current = current.expression
  965. }
  966. return current
  967. }
  968. /** Return every value only when a type is a closed string-literal union. */
  969. function finiteStringTypeValues(type: ts.Type): Set<string> | undefined {
  970. if (type.flags & ts.TypeFlags.StringLiteral) {
  971. return new Set([(type as ts.StringLiteralType).value])
  972. }
  973. if (type.flags & ts.TypeFlags.Never) return new Set()
  974. if (!type.isUnion()) return undefined
  975. const values = new Set<string>()
  976. for (const member of type.types) {
  977. const memberValues = finiteStringTypeValues(member)
  978. if (!memberValues) return undefined
  979. addAll(values, memberValues)
  980. }
  981. return values
  982. }
  983. /** Return whether a variable declaration belongs to a const declaration list. */
  984. function isConstDeclaration(declaration: ts.VariableDeclaration): boolean {
  985. return (declaration.parent.flags & ts.NodeFlags.Const) !== 0
  986. }
  987. /** Return whether a declaration is visible to callers outside its source module. */
  988. function hasExportModifier(node: ts.Node): boolean {
  989. return ts.canHaveModifiers(node) && (ts.getModifiers(node)?.some((modifier) => {
  990. return modifier.kind === ts.SyntaxKind.ExportKeyword || modifier.kind === ts.SyntaxKind.DefaultKeyword
  991. }) ?? false)
  992. }
  993. /** Add every member of source to target. */
  994. function addAll<T>(target: Set<T>, source: ReadonlySet<T>): void {
  995. for (const value of source) target.add(value)
  996. }
  997. /** Return the union of two sets without mutating either input. */
  998. function unionSets<T>(left: ReadonlySet<T>, right: ReadonlySet<T>): Set<T> {
  999. const out = new Set(left)
  1000. addAll(out, right)
  1001. return out
  1002. }
  1003. /**
  1004. * Select the package source files of one project in deterministic order.
  1005. * @param project - the loaded repository TypeScript project.
  1006. * @returns `packages/<group>/<pkg>/src` files tagged with their package name.
  1007. */
  1008. export function collectPackageSources(project: TypeScriptProject): PackageSource[] {
  1009. return project.sourceFiles().flatMap((sourceFile): PackageSource[] => {
  1010. const rel = project.relativePath(sourceFile)
  1011. const match = /^packages\/[^/]+\/([^/]+)\/src\/.+\.ts$/.exec(rel)
  1012. return match?.[1] ? [{ rel, pkg: match[1], sourceFile }] : []
  1013. }).sort((left, right) => left.rel.localeCompare(right.rel))
  1014. }
  1015. function collectEventRelations(): Map<string, EventRelation> {
  1016. const project = new TypeScriptProject(root)
  1017. return new EventRelationCollector(project, collectPackageSources(project)).collect()
  1018. }
  1019. function relationPackages(map: Map<string, Set<string>>, pkgsByShort: Map<string, Pkg>): string {
  1020. if (map.size === 0) return '-'
  1021. return [...map.entries()]
  1022. .sort(([a], [b]) => a.localeCompare(b))
  1023. .map(([pkg, methods]) => `${pkgLink(pkgsByShort.get(pkg), pkg)} (${[...methods].sort().map(m => `\`${m}\``).join(', ')})`)
  1024. .join(', ')
  1025. }
  1026. function listenerPackages(listeners: Set<string>, pkgsByShort: Map<string, Pkg>): string {
  1027. if (listeners.size === 0) return '-'
  1028. return [...listeners].sort().map(pkg => pkgLink(pkgsByShort.get(pkg), pkg)).join(', ')
  1029. }
  1030. function renderEventRelations(pkgs: Pkg[], events: readonly EventEntry[]): string {
  1031. const relations = collectEventRelations()
  1032. const pkgsByShort = new Map(pkgs.map(pkg => [pkg.short, pkg]))
  1033. const maintenance = 'generated: Cordis event declarations and producer/listener edges are resolved from the repository TypeScript Program'
  1034. const lines = generatedHeader('Event Producer And Consumer Matrix')
  1035. lines.push(
  1036. '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.',
  1037. '',
  1038. '| Event | Mode | Declared in | Dispatchers | Listeners |',
  1039. '| --- | --- | --- | --- | --- |',
  1040. )
  1041. for (const event of [...events].sort((a, b) => a.name.localeCompare(b.name))) {
  1042. const relation = relations.get(event.name) ?? { dispatchers: new Map<string, Set<string>>(), listeners: new Set<string>() }
  1043. lines.push(`| \`${event.name}\` | \`${event.mode}\` | ${sourceLink(event.source)} | ${relationPackages(relation.dispatchers, pkgsByShort)} | ${listenerPackages(relation.listeners, pkgsByShort)} |`)
  1044. }
  1045. // Every declared event needs a dispatcher: zero means dead vocabulary or an
  1046. // unrecognized semantic dispatch shape. Listener-free extension points remain
  1047. // valid. Client-declared events are exempt: the relation scan seeds the HOST
  1048. // aggregate program only (host+client cannot share one program — the cordis
  1049. // Context merges collide), so client dispatch sites are structurally
  1050. // invisible here; their rows stay in the table for the declarations' sake.
  1051. const undispatched = [...events]
  1052. .filter(event => !event.source.startsWith('packages/client/'))
  1053. .filter(event => (relations.get(event.name)?.dispatchers.size ?? 0) === 0)
  1054. .map(event => event.name)
  1055. .sort()
  1056. if (undispatched.length > 0) {
  1057. throw new Error(
  1058. `event-producer-consumer matrix: no dispatcher found for declared event${undispatched.length > 1 ? 's' : ''} `
  1059. + `${undispatched.map(name => `"${name}"`).join(', ')} — dead vocabulary, or a dispatch shape the semantic scan misses `
  1060. + '(teach scripts/gen-doc-graphs.ts the shape)',
  1061. )
  1062. }
  1063. const declared = new Set(events.map(event => event.name))
  1064. const extra = [...relations.keys()].filter(event => !declared.has(event)).sort()
  1065. if (extra.length > 0) {
  1066. lines.push('', '## Non-harness or undeclared event strings seen in package source', '', '| Event string | Dispatchers | Listeners |', '| --- | --- | --- |')
  1067. for (const event of extra) {
  1068. const relation = relations.get(event)
  1069. if (!relation) continue
  1070. lines.push(`| \`${event}\` | ${relationPackages(relation.dispatchers, pkgsByShort)} | ${listenerPackages(relation.listeners, pkgsByShort)} |`)
  1071. }
  1072. }
  1073. lines.push('', ...maintenanceFooter(maintenance))
  1074. return lines.join('\n')
  1075. }
  1076. function renderLifecycle(): string {
  1077. const maintenance = 'curated Mermaid sequence; exact event signatures live in the generated Cordis catalog'
  1078. return [
  1079. ...generatedHeader('Agent Turn And Step Lifecycle'),
  1080. '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/*`.',
  1081. '',
  1082. '```mermaid',
  1083. 'sequenceDiagram',
  1084. ' participant User',
  1085. ' participant Agent',
  1086. ' participant Driver',
  1087. ' participant Hooks as hook listeners',
  1088. ' participant Prompt as ctx.systemPrompt',
  1089. ' participant LLM as ctx.llm',
  1090. ' participant Tools as ctx.tools',
  1091. ' participant Session',
  1092. ' participant SDK as UI or SDK listener',
  1093. ' User->>Agent: followup(content)',
  1094. ` Agent-->>SDK: ${mermaidCode('agent/inbox/spliced')}`,
  1095. ` Agent-->>SDK: ${mermaidCode('agent/inbox/inserted')} { message }`,
  1096. ' Agent->>Driver: queued work wakes driver',
  1097. ` Driver-->>SDK: ${mermaidCode('agent/status')} running`,
  1098. ' Note over Agent,Driver: claim pending next-step input plus one queued prompt',
  1099. ` Driver-->>SDK: ${mermaidCode('agent/inbox/spliced')} pure deletion`,
  1100. ` Driver-->>SDK: ${mermaidCode('agent/inbox/claimed')} { message, turn } per message`,
  1101. ` Driver->>Hooks: ${mermaidCode('agent/pre-step')} waterfall`,
  1102. ' Hooks-->>Driver: authoritative reject or enter(messages)',
  1103. ' alt proposed step rejected or pre-step failed',
  1104. ' Driver-->>Driver: claimed batch stays removed, no turn opens',
  1105. ' else enter proposed step',
  1106. ` Driver->>Session: ${mermaidCode('turn/start')}`,
  1107. ` Driver->>Session: ${mermaidCode('step/start')}`,
  1108. ` Driver->>Session: ${mermaidCode('user/message')} per entered message`,
  1109. ` Driver->>Prompt: ${mermaidCode('system-prompt/assemble')} waterfall`,
  1110. ` Driver->>LLM: ${mermaidCode('agent/request')} waterfall, then ${mermaidCode('llm/stream')} waterfall`,
  1111. ' LLM-->>Driver: StreamChunk*',
  1112. ` Driver->>Session: ${mermaidCode('assistant/chunk')}*`,
  1113. ` Session-->>SDK: ${mermaidCode('session/event')} ${mermaidCode('assistant/chunk')}*`,
  1114. ' alt final adapter or terminal in-band request failure',
  1115. ` Driver->>Session: ${mermaidCode('step/end')}`,
  1116. ` Driver->>Hooks: ${mermaidCode('agent/request-error')} waterfall`,
  1117. ' Hooks-->>Driver: return retry action or preserve the original error',
  1118. ' else model request succeeded',
  1119. ` Driver->>Session: ${mermaidCode('assistant/message')}`,
  1120. ' Driver->>Tools: classify pending call by executionMode',
  1121. ' loop barriers and bounded rolling pool, reclassify before start',
  1122. ' opt call starts',
  1123. ` Driver->>Session: ${mermaidCode('tool/call')}`,
  1124. ' Driver->>Tools: ordered pre, concurrent execute',
  1125. ' Tools-->>Session: tool-owned events when applicable',
  1126. ' end',
  1127. ' opt next model-order result ready',
  1128. ' Driver->>Tools: ordered post',
  1129. ` Driver->>Session: ${mermaidCode('tool/result')}`,
  1130. ' end',
  1131. ' end',
  1132. ` Driver->>Session: ${mermaidCode('step/end')}`,
  1133. ' opt natural stop and next-step inbox empty',
  1134. ` Driver->>Hooks: ${mermaidCode('agent/turn-stopping')} serial terminal checkpoint`,
  1135. ' end',
  1136. ' opt next-step input is pending',
  1137. ' Driver-->>Driver: claim pending next-step input',
  1138. ` Driver-->>SDK: ${mermaidCode('agent/inbox/claimed')} { message, turn } per message`,
  1139. ` Driver->>Hooks: ${mermaidCode('agent/pre-step')} waterfall`,
  1140. ' Hooks-->>Driver: authoritative reject or enter(messages)',
  1141. ' end',
  1142. ' end',
  1143. ` Driver->>Session: ${mermaidCode('turn/end')}`,
  1144. ' end',
  1145. ` Driver-->>SDK: ${mermaidCode('agent/status')} idle`,
  1146. '```',
  1147. '',
  1148. '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.',
  1149. '',
  1150. '`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.',
  1151. '',
  1152. '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.',
  1153. '',
  1154. '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.',
  1155. '',
  1156. ...maintenanceFooter(maintenance),
  1157. ].join('\n')
  1158. }
  1159. function renderToolPipeline(): string {
  1160. const maintenance = 'curated Mermaid flow; exact tool schemas and event signatures live in generated catalogs'
  1161. return [
  1162. ...generatedHeader('Tool Execution Pipeline'),
  1163. '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.',
  1164. '',
  1165. '```mermaid',
  1166. 'flowchart TD',
  1167. ' model["Assistant message contains tool-call block"]',
  1168. ` toolCall["Session event: ${mermaidCode('tool/call')}<br/>logged before execution"]`,
  1169. ' presentCall["UI pending card<br/>presentCall(args)"]',
  1170. ` pre["${mermaidCode('tools/pre-execute')} waterfall<br/>hooks, permission, sandbox"]`,
  1171. ' guards["Registered monotonic guards<br/>deny or abstain; identity protected"]',
  1172. ' denied["denied or approval refused<br/>tool body skipped"]',
  1173. ` approval["${mermaidCode('ctx.approval')} one-shot prompt<br/>absent or unanswerable: deny"]`,
  1174. ` around["${mermaidCode('tools/execute')} waterfall<br/>timeout, retry, metrics (around dispatch)"]`,
  1175. ' toolBody["Registered tool execute() body"]',
  1176. ` fsGate["${mermaidCode('fs/write-intent')} or ${mermaidCode('fs/edit-intent')}<br/>tool-fs mutations only"]`,
  1177. ` owned["Tool-owned session events<br/>${mermaidCode('todo/write')}, ${mermaidCode('fs/observed')}, ${mermaidCode('hook/invoked')}, ${mermaidCode('hook/result')}, ${mermaidCode('tool/code-dispatch')}"]`,
  1178. ` post["${mermaidCode('tools/post-execute')} waterfall<br/>accept, block, replace, add context"]`,
  1179. ' normalized["Registry outer normalization<br/>pipeline/result snapshot throws become isError"]',
  1180. ' finalize["ToolDefinition.finalizeContent<br/>last content-only invariant"]',
  1181. ` final["${mermaidCode('tools/result')} synchronous notification<br/>frozen authoritative outcome"]`,
  1182. ' context["Active-batch additionalContexts FIFO<br/>injected user/message after recorded tool results"]',
  1183. ` toolResult["Session event: ${mermaidCode('tool/result')}<br/>single model-facing outcome"]`,
  1184. ' allResults["Tool batch settled<br/>recorded tool/result events complete"]',
  1185. ' presentResult["UI completed card<br/>presentResult(args, result)"]',
  1186. ' model --> toolCall',
  1187. ' toolCall --> presentCall',
  1188. ' toolCall --> pre',
  1189. ' pre -->|allow| guards',
  1190. ' guards -->|allow| around',
  1191. ' guards -->|deny| denied',
  1192. ' guards -.->|throw| normalized',
  1193. ' around --> toolBody',
  1194. ' pre -->|deny| denied',
  1195. ' pre -->|ask| approval',
  1196. ' approval -->|allowed-once| guards',
  1197. ' approval -->|rejected, cancelled, unavailable| denied',
  1198. ' approval -.->|throw| normalized',
  1199. ' denied --> post',
  1200. ' pre -.->|throw| normalized',
  1201. ' toolBody --> fsGate',
  1202. ' fsGate --> toolBody',
  1203. ' toolBody --> owned',
  1204. ' toolBody --> around',
  1205. ' around --> post',
  1206. ' around -.->|wrapper throws| normalized',
  1207. ' post -.->|throw| normalized',
  1208. ' post --> finalize',
  1209. ' normalized --> finalize',
  1210. ' finalize --> final',
  1211. ' final --> toolResult',
  1212. ' toolResult --> presentResult',
  1213. ' toolResult --> allResults',
  1214. ' allResults --> context',
  1215. '```',
  1216. '',
  1217. '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.',
  1218. '',
  1219. ...maintenanceFooter(maintenance),
  1220. ].join('\n')
  1221. }
  1222. function renderDocs(): GraphDoc[] {
  1223. const pkgs = collectPackageGraph(root, GROUP_ORDER, 'gen-doc-graphs')
  1224. const { model } = projectCordisCatalog(root, CORDIS_CATALOG_POLICY)
  1225. const docs: GraphDoc[] = [
  1226. { rel: 'docs/capability-seams.md', content: renderCapabilitySeams(pkgs, model.services) },
  1227. ...APP_EXAMPLES.map(example => ({ rel: example.rel, content: renderAppComposition(example) })),
  1228. { rel: 'docs/event-producer-consumer.md', content: renderEventRelations(pkgs, model.events) },
  1229. { rel: 'docs/agent-lifecycle.md', content: renderLifecycle() },
  1230. { rel: 'docs/tool-execution-pipeline.md', content: renderToolPipeline() },
  1231. ]
  1232. docs.unshift({ rel: 'docs/graph-atlas.md', content: renderIndex(docs) })
  1233. return docs
  1234. }
  1235. function renderIndex(docs: GraphDoc[]): string {
  1236. const labels: Record<string, string> = {
  1237. 'docs/capability-seams.md': 'capability seams and core services',
  1238. 'apps/cli/composition.md': 'dsh shared base composition',
  1239. 'examples/headless-agent/composition.md': 'headless-agent app composition',
  1240. 'examples/cordis-agent/composition.md': 'cordis-agent app composition',
  1241. 'examples/acp-agent/composition.md': 'acp-agent app composition',
  1242. 'docs/event-producer-consumer.md': 'event producer/consumer matrix',
  1243. 'docs/agent-lifecycle.md': 'agent turn and step lifecycle',
  1244. 'docs/tool-execution-pipeline.md': 'tool execution pipeline',
  1245. }
  1246. const modes: Record<string, string> = {
  1247. 'docs/capability-seams.md': 'hybrid generated',
  1248. 'apps/cli/composition.md': 'hybrid generated',
  1249. 'examples/headless-agent/composition.md': 'hybrid generated',
  1250. 'examples/cordis-agent/composition.md': 'hybrid generated',
  1251. 'examples/acp-agent/composition.md': 'hybrid generated',
  1252. 'docs/event-producer-consumer.md': 'hybrid generated',
  1253. 'docs/agent-lifecycle.md': 'curated',
  1254. 'docs/tool-execution-pipeline.md': 'curated',
  1255. }
  1256. const rows = [
  1257. '| [module dependency graph](module-graph.md) | `generated` |',
  1258. '| [tool schema catalog and package map](tool-catalog.md) | `generated` |',
  1259. ...docs.map((doc) => {
  1260. const link = graphIndexLink(doc.rel)
  1261. return `| [${labels[doc.rel] ?? link}](${link}) | \`${modes[doc.rel] ?? 'generated'}\` |`
  1262. }),
  1263. ]
  1264. const maintenance = 'mixed: each linked page declares generated, hybrid, or curated mode'
  1265. return [
  1266. ...generatedHeader('Documentation Graph Index'),
  1267. '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).',
  1268. '',
  1269. '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).',
  1270. '',
  1271. '| Graph | Mode |',
  1272. '| --- | --- |',
  1273. ...rows,
  1274. '',
  1275. 'Regenerate with `pnpm run gen-doc-graphs`; verify freshness with `pnpm run verify-doc-graphs`.',
  1276. '',
  1277. ...maintenanceFooter(maintenance),
  1278. ].join('\n')
  1279. }
  1280. function main(): void {
  1281. const docs = renderDocs()
  1282. if (process.argv.includes('--check')) {
  1283. const stale: string[] = []
  1284. for (const doc of docs) {
  1285. const abs = resolve(root, doc.rel)
  1286. const committed = existsSync(abs) ? readFileSync(abs, 'utf8') : null
  1287. if (committed !== doc.content) stale.push(doc.rel)
  1288. }
  1289. if (stale.length === 0) {
  1290. console.log(`gen-doc-graphs: ${docs.length} graph doc(s) are up to date.`)
  1291. return
  1292. }
  1293. console.error(`gen-doc-graphs: stale graph doc(s): ${stale.join(', ')}. Run \`pnpm run gen-doc-graphs\` and commit the result.`)
  1294. process.exit(1)
  1295. }
  1296. for (const doc of docs) {
  1297. mkdirSync(dirname(resolve(root, doc.rel)), { recursive: true })
  1298. writeFileSync(resolve(root, doc.rel), doc.content)
  1299. }
  1300. console.log(`gen-doc-graphs: wrote ${docs.length} graph doc(s).`)
  1301. }
  1302. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  1303. main()
  1304. }