gen-doc-graphs.ts 65 KB

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