gen-doc-graphs.ts 64 KB

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