gen-doc-graphs.ts 63 KB

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