gen-doc-graphs.ts 62 KB

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