gen-cordis-catalog.ts 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  1. /**
  2. * Generate the per-subsystem Cordis service/event reference regions from the
  3. * Typert catalog projection. Every harness `ctx.<key>` service and event scope
  4. * maps to exactly one `docs/subsystems/` page through the curated tables below;
  5. * the generator injects each page's Cordis API reference between its GENERATED markers —
  6. * into both language sides of the pair, localizing paired document paths for
  7. * the Chinese side while retaining every other byte — and re-records a pair's
  8. * `.i18n.yaml` only when nothing outside the region changed. The
  9. * projection enforces event modes, JSDoc parameter/return completeness, and
  10. * signature type-link coverage; the inherited (vendor) tier renders to
  11. * `docs/cordis-api/inherited.md`. `--check` verifies every generated artifact.
  12. *
  13. * Generated regions embed `file:line` source pointers, so inserting lines ABOVE a
  14. * recorded symbol makes the committed output stale even though nothing about the
  15. * symbol changed. Regenerate after editing any file this projection records — the
  16. * failure otherwise surfaces as the "reproduces every committed catalog artifact
  17. * byte for byte" test failing, which reads like a snapshot regression rather than
  18. * a missing regeneration.
  19. */
  20. import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
  21. import { dirname, resolve } from 'node:path'
  22. import {
  23. projectCordisCatalog,
  24. renderInheritedPage,
  25. renderPageRegion,
  26. REGION_BEGIN,
  27. REGION_END,
  28. } from '@deepseek-ai/dsh-typert-generator'
  29. import type { CordisCatalogPolicy } from '@deepseek-ai/dsh-typert-generator'
  30. import { renderCordisCoreApiPages } from './cordis-core-api.ts'
  31. import { contextKeyMap, contextMergeFiles, eventNameList } from './cordis-walk.ts'
  32. import {
  33. blobHash,
  34. parsePairMeta,
  35. parseTranslationPairingManifest,
  36. partitionGeneratedRegions,
  37. renderPairMeta,
  38. translationPairSourcePredicate,
  39. } from './translation-pairing.ts'
  40. import { rewriteTranslationLinkLocales } from './translation-links.ts'
  41. const root = resolve(import.meta.dirname, '..')
  42. const SUBSYSTEMS_DIR = 'docs/subsystems'
  43. const OUT_INHERITED = 'docs/cordis-api/inherited.md'
  44. const OUT_RUNTIME_API = 'packages/extensions/tool-cordis/src/api-catalog.ts'
  45. export { REGION_BEGIN, REGION_END }
  46. /**
  47. * The owning subsystems page for every harness `ctx.<key>` service the
  48. * projection discovers. Fail-closed both ways: a discovered key absent here
  49. * and an entry whose key the projection no longer discovers are both hard
  50. * errors, so the partition can never silently drift from the service API.
  51. */
  52. export const SERVICE_PAGE: Record<string, string> = {
  53. agentLoop: 'core.md',
  54. agentDefaultModel: 'core.md',
  55. agentPresets: 'core.md',
  56. agents: 'core.md',
  57. apiProxy: 'typert.md',
  58. approval: 'approval.md',
  59. attachments: 'attachment.md',
  60. shell: 'shell.md',
  61. shellEnv: 'shell.md',
  62. clientModules: 'client-modules.md',
  63. codeRuntime: 'code-runtime.md',
  64. commands: 'commands.md',
  65. compaction: 'compaction.md',
  66. cordisInspect: 'extensions.md',
  67. authorization: 'credentials.md',
  68. credentials: 'credentials.md',
  69. directoryPicker: 'workspace.md',
  70. deepseekLlmApiExtensions: 'llm-streaming.md',
  71. dynamicCordisRunner: 'extensions.md',
  72. e2b: 'subprocess.md',
  73. fileReferences: 'session-reference.md',
  74. fs: 'filesystem.md',
  75. goals: 'goal.md',
  76. webServer: 'web-server.md',
  77. invariants: 'invariants.md',
  78. llm: 'llm-streaming.md',
  79. lsp: 'lsp.md',
  80. messageFeedback: 'feedback.md',
  81. permissionPresets: 'permission-presets.md',
  82. planMode: 'plan.md',
  83. terminals: 'terminal.md',
  84. sandbox: 'sandbox.md',
  85. sandboxPolicy: 'sandbox.md',
  86. sessionPersistence: 'persistence.md',
  87. sessionQuery: 'session-query.md',
  88. sessionReferenceResolver: 'session-reference.md',
  89. sessionProjectionCache: 'session-projection.md',
  90. sessionProjections: 'session-projection.md',
  91. sessionController: 'session.md',
  92. sessions: 'session.md',
  93. settings: 'settings.md',
  94. sessionTitle: 'session-title.md',
  95. skills: 'skills.md',
  96. spillStore: 'spill.md',
  97. storage: 'storage.md',
  98. storageDomain: 'storage.md',
  99. subagentModelSelection: 'subagent.md',
  100. subagents: 'subagent.md',
  101. subprocess: 'subprocess.md',
  102. systemPrompt: 'system-prompt.md',
  103. jobs: 'jobs.md',
  104. sessionTelemetry: 'session-telemetry.md',
  105. agentTeams: 'agent-team.md',
  106. tokenMeter: 'token-meter.md',
  107. toolResultPruner: 'compaction.md',
  108. tools: 'tools.md',
  109. typert: 'typert.md',
  110. typertGateway: 'typert.md',
  111. userQuestions: 'user-questions.md',
  112. web: 'web.md',
  113. workflowEngine: 'workflow.md',
  114. webhookRuntime: 'webhook.md',
  115. workspaceRegistry: 'workspace.md',
  116. workspaceController: 'workspace.md',
  117. }
  118. /**
  119. * Context keys declared in `interface Context` merges that the rendering
  120. * projection cannot see, each with the reason and its documentation owner.
  121. * The scan that enforces this list reads EVERY `declare module '@deepseek-ai/cordis'`
  122. * Context merge under `packages/x/x/src/**` — any depth, not only root
  123. * `index.ts` files with a same-named service class — so a new service can
  124. * never silently join this blind spot: it either enters {@link SERVICE_PAGE}
  125. * or names itself here. Client-face keys (the projection analyzes the host
  126. * face only) name the package README that owns their surface.
  127. *
  128. * Two categories remain, and neither is a projection gap a scanning rule could
  129. * close. An OPTIONAL key (`key?: X`) is a value the launcher or boot code
  130. * installs before the tree mounts, which the analyzer skips by rule because no
  131. * plugin provides it and `inject` cannot reach it. A client-face key belongs to
  132. * the browser Context, which this host-face program never sees; the browser
  133. * surface has its own generated catalog (`scripts/gen-client-catalog.ts`, served
  134. * to a model as `cordis_runtime_inspect what:"client"`).
  135. */
  136. export const SERVICE_WALK_EXEMPTIONS: Record<string, string> = {
  137. agent: 'not a service: the DX accessor field on Agent.ctx (root accessor defaulting to undefined) — docs/subsystems/core.md owns the Agent handle',
  138. appReady: 'not a service: launcher-provided successful-startup signal — packages/boot/cmdline/README.md owns the launcher contract',
  139. appExit: 'not a service: launcher-provided bounded process-exit callback — packages/boot/cmdline/README.md owns the launcher contract',
  140. cmdlineArgs: 'not a service: launcher-provided immutable app argument accessor — packages/boot/cmdline/README.md owns the launcher contract',
  141. configuredAgentIdentities: 'not a service: launcher-provided boot-context value (ConfiguredAgentIdentities | undefined) — packages/core/agent-loop/README.md owns this launcher contract',
  142. launcherSessionQueryPath: 'not a service: launcher-provided boot-context value (string | undefined) — packages/session-query/session-query-sqlite/README.md owns this launcher contract',
  143. dshHomePath: 'not a service: boot-provided root accessor function (typeof dshHomePath | undefined) for Loader !!js config expressions — packages/boot/app-boot/README.md owns the boot contract',
  144. launchEnvironment: 'not a service: launcher-provided root accessor value (LaunchEnvironmentSnapshot | undefined) — packages/util/launch-environment/README.md owns this launcher contract',
  145. connection: 'interface-typed (HostConnectionHandle); implementing class HostConnectionService is declared in rpc-host.ts — packages/client/connection/README.md owns the API',
  146. uiRenderer: 'client-side interface-typed browser service — packages/client/ui-renderer/README.md owns the API',
  147. uiSession: 'client-side Session source adapter — packages/client/ui-session/README.md owns the API',
  148. uiConversation: 'client-side Conversation registries and assembler — packages/client/ui-conversation/README.md owns the API',
  149. uiWorkspace: 'client-side Workspace navigation adapter — packages/client/ui-workspace/README.md owns the API',
  150. settingsSchema: 'client-side schema introspection service — packages/client/ui-settings/README.md owns the API',
  151. settingsScope: 'client-side settings-namespace transport service — packages/client/ui-settings/README.md owns the API',
  152. chatFileMentions: 'client-side slot-contract accessor (ChatFileMentions) — packages/client/ui-chat/README.md owns the API',
  153. commandUi: 'client-side interface-typed browser service — packages/client/ui-commands/README.md owns the API',
  154. conversation: 'client-side interface-typed browser service — packages/client/ui-conversation/README.md owns the API',
  155. layout: 'client-side interface-typed browser service — packages/client/ui-layout/README.md owns the API',
  156. locale: 'client-side interface-typed browser service — packages/client/locale/README.md owns the API',
  157. modelDirectories: 'client-side interface-typed browser service — packages/client/ui-model-selection/README.md owns the API',
  158. modules: 'client-side interface-typed browser service — packages/client/modules/README.md owns the API',
  159. remote: 'client-side interface-typed gateway accessor (ClientRemote) — packages/api/gateway/README.md owns the API',
  160. sessionLogDownload: 'client-side browser download controller — packages/session-query/session-log-export/README.md owns the API',
  161. inputTriggers: 'client-side interface-typed browser service — packages/client/ui-input-trigger/README.md owns the API',
  162. timer: 'client-side dynamic-package timer service — packages/extensions/cordis-client-runner/README.md owns the API',
  163. slots: 'client-side interface-typed browser service — packages/client/ui-renderer/README.md owns the API',
  164. theme: 'client-side interface-typed browser service — packages/client/ui-theme/README.md owns the API',
  165. workspaces: 'client-side interface-typed browser service — packages/api/workspace-controller/README.md owns the API',
  166. }
  167. /**
  168. * The owning subsystems page for every harness event scope (the segment
  169. * before the first `/`) the projection renders. Fail-closed exactly like
  170. * {@link SERVICE_PAGE}. Client-face events (`slash/*`, `theme/change`, …) are
  171. * invisible to the host-face projection and therefore never reach this map;
  172. * {@link EVENT_WALK_EXEMPTIONS} names each one with its documentation owner.
  173. */
  174. export const EVENT_SCOPE_PAGE: Record<string, string> = {
  175. 'agent': 'core.md',
  176. 'agent-loop': 'core.md',
  177. 'agent-preset': 'core.md',
  178. 'api-session': 'session.md',
  179. 'approval': 'approval.md',
  180. 'commands': 'commands.md',
  181. 'cordis': 'extensions.md',
  182. 'authorization': 'credentials.md',
  183. 'credentials': 'credentials.md',
  184. 'domain': 'storage.md',
  185. 'fs': 'filesystem.md',
  186. 'goal': 'goal.md',
  187. 'llm': 'llm-streaming.md',
  188. 'session': 'session.md',
  189. 'settings': 'settings.md',
  190. 'skills': 'skills.md',
  191. 'subagent': 'subagent.md',
  192. 'system-prompt': 'system-prompt.md',
  193. 'session-telemetry': 'session-telemetry.md',
  194. 'tools': 'tools.md',
  195. 'user-questions': 'user-questions.md',
  196. 'webserver': 'web-server.md',
  197. 'workflow': 'workflow.md',
  198. }
  199. /**
  200. * Event names declared in `interface Events` merges that the rendering
  201. * projection cannot see, each with the reason and its documentation owner.
  202. * The mirror of {@link SERVICE_WALK_EXEMPTIONS} for events: an independent
  203. * scan reads EVERY `declare module '@deepseek-ai/cordis'` Events merge under
  204. * `packages/x/x/src/**`, so a declared event either renders onto a subsystems
  205. * page (via {@link EVENT_SCOPE_PAGE}) or names itself here — never vanishes
  206. * silently. Keys are full event names rather than scopes, so a scope-level
  207. * exemption cannot mask another declaration in that scope.
  208. */
  209. export const EVENT_WALK_EXEMPTIONS: Record<string, string> = {
  210. 'command/executed': 'client-face local command acknowledgment — packages/client/ui-commands/README.md owns the API',
  211. 'connection/reset': 'client-face transport signal — packages/api/session-controller/README.md owns the API',
  212. 'locale/change': 'client-face locale switch signal — packages/client/locale/README.md owns the API',
  213. 'slash/input-begin-command': 'client-face slash-input protocol — packages/client/ui-input-trigger/README.md owns the API',
  214. 'slash/input-consume-token': 'client-face slash-input protocol — packages/client/ui-input-trigger/README.md owns the API',
  215. 'slash/input-insert-reference': 'client-face slash-input protocol — packages/client/ui-input-trigger/README.md owns the API',
  216. 'slash/input-insert-text': 'client-face slash-input protocol — packages/client/ui-input-trigger/README.md owns the API',
  217. 'slots/changed': 'client-face slot invalidation signal — packages/client/ui-renderer/README.md owns the API',
  218. 'theme/change': 'client-face theme switch signal — packages/client/ui-theme/README.md owns the API',
  219. }
  220. /**
  221. * One primary subsystems page per project type used by a generated
  222. * signature. This stays curated because union names intentionally do not
  223. * reuse the type-equivalence manifest's map-symbol entries and some symbols
  224. * appear on more than one page.
  225. */
  226. export const LINK_MAP: Readonly<Record<string, string>> = {
  227. Agent: 'core.md',
  228. AgentCancelCause: 'core.md',
  229. AgentFactory: 'core.md',
  230. AgentHandle: 'core.md',
  231. ModelSelection: 'core.md',
  232. AgentOptions: 'core.md',
  233. AgentStatus: 'core.md',
  234. ContentBlock: 'llm-streaming.md',
  235. CreateAgentOptions: 'core.md',
  236. GenerateOptions: 'llm-streaming.md',
  237. InboxItem: 'core.md',
  238. InboxPlacement: 'core.md',
  239. MessageId: 'llm-streaming.md',
  240. ResumeAgentOptions: 'core.md',
  241. SettleReason: 'core.md',
  242. AdapterRegistrationHandle: 'llm-streaming.md',
  243. DirectoryRegistrationHandle: 'llm-streaming.md',
  244. DeepSeekLlmApiExtensionMap: 'llm-streaming.md',
  245. DeepSeekLlmApiExtensionProvider: 'llm-streaming.md',
  246. DeepSeekLlmApiExtensionRequest: 'llm-streaming.md',
  247. LlmCallConfig: 'llm-streaming.md',
  248. LlmModelContext: 'llm-streaming.md',
  249. LlmModelReasoningInfo: 'llm-streaming.md',
  250. LlmResolvedModelInfo: 'llm-streaming.md',
  251. LlmFailure: 'llm-streaming.md',
  252. LlmImageRequestPricing: 'llm-streaming.md',
  253. LlmModelInfo: 'llm-streaming.md',
  254. LlmProviderInfo: 'llm-streaming.md',
  255. LlmConfigurableProvider: 'llm-streaming.md',
  256. LlmModelDiscoveryRequest: 'llm-streaming.md',
  257. LlmDiscoveredModel: 'llm-streaming.md',
  258. ResolvedRetryPolicy: 'llm-streaming.md',
  259. Message: 'llm-streaming.md',
  260. MessageSource: 'llm-streaming.md',
  261. MessageFeedbackDeleteRequest: 'feedback.md',
  262. MessageFeedbackDeleteResult: 'feedback.md',
  263. MessageFeedbackDeleteValue: 'feedback.md',
  264. MessageFeedbackFailure: 'feedback.md',
  265. MessageFeedbackItem: 'feedback.md',
  266. MessageFeedbackListRequest: 'feedback.md',
  267. MessageFeedbackListResult: 'feedback.md',
  268. MessageFeedbackListValue: 'feedback.md',
  269. MessageFeedbackNoteBlank: 'feedback.md',
  270. MessageFeedbackNoteTooLarge: 'feedback.md',
  271. MessageFeedbackPutRequest: 'feedback.md',
  272. MessageFeedbackPutResult: 'feedback.md',
  273. MessageFeedbackRating: 'feedback.md',
  274. MessageFeedbackRejected: 'feedback.md',
  275. MessageFeedbackSessionNotFound: 'feedback.md',
  276. MessageFeedbackSuccess: 'feedback.md',
  277. MessageFeedbackTargetNotFound: 'feedback.md',
  278. MessageFeedbackVersion: 'feedback.md',
  279. MessageFeedbackVersionConflict: 'feedback.md',
  280. UserMessage: 'session.md',
  281. ApiSessionAgentResult: 'session.md',
  282. PreStepDecision: 'core.md',
  283. PreStepContext: 'core.md',
  284. RequestErrorAction: 'core.md',
  285. RequestFailureContext: 'core.md',
  286. PreparedReferencedMessage: 'session-reference.md',
  287. FileReferenceCandidate: 'session-reference.md',
  288. SessionReferenceCandidate: 'session-reference.md',
  289. SessionReferenceMentionCandidate: 'session-reference.md',
  290. SessionReferenceInput: 'session-reference.md',
  291. SessionAttachmentRequest: 'session.md',
  292. SessionAttachmentValue: 'session.md',
  293. SessionCancelRequest: 'session.md',
  294. SessionCancelValue: 'session.md',
  295. SessionControlFrame: 'session.md',
  296. SessionCreateRequest: 'session.md',
  297. SessionCreateValue: 'session.md',
  298. SessionEvent: 'session.md',
  299. SessionFollowFrame: 'session.md',
  300. SessionFollowRequest: 'session.md',
  301. SessionForkRequest: 'session.md',
  302. SessionForkValue: 'session.md',
  303. SessionId: 'core.md',
  304. SessionListRequest: 'session.md',
  305. SessionListValue: 'session.md',
  306. SessionModels: 'session.md',
  307. SessionModelsRequest: 'session.md',
  308. SessionPage: 'session.md',
  309. SessionPageRequest: 'session.md',
  310. SessionPromptRequest: 'session.md',
  311. SessionPromptValue: 'session.md',
  312. SessionRenameRequest: 'session.md',
  313. SessionRenameValue: 'session.md',
  314. SessionRespondReceipt: 'session.md',
  315. SessionRespondRequest: 'session.md',
  316. SessionSearchValue: 'session.md',
  317. SessionSelectModelRequest: 'session.md',
  318. SessionSelectModelValue: 'session.md',
  319. SessionSummary: 'session.md',
  320. SessionUpdateQueueRequest: 'session.md',
  321. SessionUpdateQueueValue: 'session.md',
  322. SessionStartSource: 'core.md',
  323. SessionLogSnapshot: 'session-query.md',
  324. SessionSurfaceSnapshot: 'session-query.md',
  325. ApprovalOutcome: 'approval.md',
  326. ApprovalPolicy: 'approval.md',
  327. ApprovalRequest: 'approval.md',
  328. ApprovalRequestEvent: 'approval.md',
  329. ApprovalService: 'approval.md',
  330. AskUserQuestionRequestEvent: 'user-questions.md',
  331. EncodedImageAttachment: 'attachment.md',
  332. ImageAttachmentAccess: 'llm-streaming.md',
  333. ImageAttachmentRef: 'attachment.md',
  334. ImageRequestPolicy: 'attachment.md',
  335. RequestImageAttachment: 'attachment.md',
  336. SaveImageAttachment: 'attachment.md',
  337. StoredImageAttachment: 'attachment.md',
  338. ShellExecRequest: 'shell.md',
  339. ShellExecSpec: 'shell.md',
  340. ShellProcess: 'shell.md',
  341. ShellRunResult: 'shell.md',
  342. DshEnvironment: 'subprocess.md',
  343. SubprocessHandle: 'subprocess.md',
  344. SubprocessOutcome: 'subprocess.md',
  345. SubprocessOutputRead: 'subprocess.md',
  346. SubprocessOutputReader: 'subprocess.md',
  347. SubprocessSpawnSpec: 'subprocess.md',
  348. SubprocessTerminalHandle: 'subprocess.md',
  349. SubprocessTerminalSpawnSpec: 'subprocess.md',
  350. CodeRunRequest: 'code-runtime.md',
  351. CodeRunResult: 'code-runtime.md',
  352. CompactionResult: 'compaction.md',
  353. CompactionTrigger: 'compaction.md',
  354. PruneResult: 'compaction.md',
  355. FileReadOutcome: 'filesystem.md',
  356. FsDirEntry: 'filesystem.md',
  357. FsEditOutcome: 'filesystem.md',
  358. FsEditRequest: 'filesystem.md',
  359. FsInfo: 'filesystem.md',
  360. FsObservation: 'filesystem.md',
  361. FsPathInfo: 'filesystem.md',
  362. FsObservationActor: 'filesystem.md',
  363. FsTarget: 'filesystem.md',
  364. FsVersion: 'filesystem.md',
  365. FsWriteIntent: 'filesystem.md',
  366. FsWriteOutcome: 'filesystem.md',
  367. CreateGoalRequest: 'goal.md',
  368. EditGoalRequest: 'goal.md',
  369. GoalBlockReason: 'goal.md',
  370. GoalChanged: 'goal.md',
  371. GoalRef: 'goal.md',
  372. GoalView: 'goal.md',
  373. CreateGoalResult: 'goal.md',
  374. CommandDefinition: 'commands.md',
  375. CommandDescriptor: 'commands.md',
  376. CommandId: 'commands.md',
  377. CommandResult: 'commands.md',
  378. CommandSurface: 'commands.md',
  379. LspProvider: 'lsp.md',
  380. LspQueryRequest: 'lsp.md',
  381. LspQueryResult: 'lsp.md',
  382. LlmAdapter: 'llm-streaming.md',
  383. PreparedLlmCall: 'llm-streaming.md',
  384. PreparedDeepSeekLlmApiExtensions: 'llm-streaming.md',
  385. LlmRuntime: 'llm-streaming.md',
  386. StreamChunk: 'llm-streaming.md',
  387. SkillProviderControl: 'skills.md',
  388. CreateSessionOptions: 'persistence.md',
  389. PrepareSessionOptions: 'persistence.md',
  390. SessionHeader: 'persistence.md',
  391. SessionInspection: 'persistence.md',
  392. BorrowedSessionSource: 'persistence.md',
  393. SessionLocation: 'persistence.md',
  394. SessionPreparation: 'persistence.md',
  395. SessionPersistenceSnapshot: 'persistence.md',
  396. SessionRawArtifact: 'persistence.md',
  397. ConfinedArgv: 'sandbox.md',
  398. SandboxExecutionPolicy: 'sandbox.md',
  399. SandboxMode: 'sandbox.md',
  400. SandboxPolicy: 'sandbox.md',
  401. TerminalBackend: 'terminal.md',
  402. TerminalReadRequest: 'terminal.md',
  403. TerminalReadResult: 'terminal.md',
  404. TerminalSendOperation: 'terminal.md',
  405. TerminalSendRequest: 'terminal.md',
  406. TerminalSessionId: 'terminal.md',
  407. TerminalSessionSnapshot: 'terminal.md',
  408. TerminalSignal: 'terminal.md',
  409. TerminalSignalResult: 'terminal.md',
  410. TerminalSpawnRequest: 'terminal.md',
  411. TerminalSpawnResult: 'terminal.md',
  412. SandboxPolicyRequest: 'sandbox.md',
  413. ScopeKey: 'scope.md',
  414. Scoped: 'scope.md',
  415. EpochHeader: 'session.md',
  416. Session: 'session.md',
  417. SessionEventMap: 'session.md',
  418. TurnEndReason: 'session.md',
  419. TurnTrigger: 'session.md',
  420. SessionEventReadRequest: 'session-query.md',
  421. SessionEventRecord: 'session-query.md',
  422. SessionEventResultFilter: 'session-query.md',
  423. SessionEventSearchDocument: 'session-query.md',
  424. SessionEventSearchHit: 'session-query.md',
  425. SessionEventSearchPage: 'session-query.md',
  426. SessionEventSearchRequest: 'session-query.md',
  427. SessionEventTrace: 'session-query.md',
  428. SessionEventTraceObservation: 'session-query.md',
  429. SessionEventTraceRequest: 'session-query.md',
  430. SessionEventWindow: 'session-query.md',
  431. SessionLineageTrace: 'session-query.md',
  432. SessionObservation: 'session-query.md',
  433. SessionObservationOptions: 'session-query.md',
  434. SessionRecord: 'session-query.md',
  435. SessionResultFilter: 'session-query.md',
  436. SessionSearchExecContext: 'session-query.md',
  437. SessionSearchHit: 'session-query.md',
  438. SessionSearchPage: 'session-query.md',
  439. SessionSearchRequest: 'session-query.md',
  440. SessionTitleObservation: 'session-query.md',
  441. SessionTitleObservationResult: 'session-query.md',
  442. SessionTitleProvider: 'session-title.md',
  443. SessionTitleSnapshot: 'session-title.md',
  444. SkillCatalogSnapshot: 'skills.md',
  445. SkillDefinition: 'skills.md',
  446. SkillLookupOptions: 'skills.md',
  447. SkillProvider: 'skills.md',
  448. SkillProviderObservation: 'skills.md',
  449. SkillRegistration: 'skills.md',
  450. SkillViewOptions: 'skills.md',
  451. SkillSummary: 'skills.md',
  452. SaveTextSpill: 'spill.md',
  453. SpillRef: 'spill.md',
  454. ContinuableCreateRequest: 'subagent.md',
  455. ContinuableCreateSpec: 'subagent.md',
  456. ContinuableSetupContribution: 'subagent.md',
  457. ContinuableStart: 'subagent.md',
  458. ContinuableStartSpec: 'subagent.md',
  459. CoordinatorMessageSource: 'subagent.md',
  460. SubagentDescendantListEntry: 'subagent.md',
  461. SubagentFollowupOptions: 'subagent.md',
  462. SubagentInterruptAuthority: 'subagent.md',
  463. SubagentListEntry: 'subagent.md',
  464. SubagentProvider: 'subagent.md',
  465. SubagentReportDelivery: 'subagent.md',
  466. SubagentReportMessageSource: 'subagent.md',
  467. SubagentReportOptions: 'subagent.md',
  468. SubagentRun: 'subagent.md',
  469. SubagentRuntime: 'subagent.md',
  470. SubagentStartRequest: 'subagent.md',
  471. AssembleContext: 'system-prompt.md',
  472. PromptContext: 'system-prompt.md',
  473. PromptSection: 'system-prompt.md',
  474. SystemPrompt: 'system-prompt.md',
  475. ToolProviderResult: 'system-prompt.md',
  476. JobDoneListener: 'jobs.md',
  477. JobId: 'jobs.md',
  478. JobRead: 'jobs.md',
  479. JobSnapshot: 'jobs.md',
  480. JobStart: 'jobs.md',
  481. JobsChangedListener: 'jobs.md',
  482. CreateTeamTaskRequest: 'agent-team.md',
  483. SendTeamMessageRequest: 'agent-team.md',
  484. SendTeamMessageResult: 'agent-team.md',
  485. SpawnTeammateRequest: 'agent-team.md',
  486. SpawnTeammateResult: 'agent-team.md',
  487. TeamId: 'agent-team.md',
  488. TeamMemberView: 'agent-team.md',
  489. TeamMembership: 'agent-team.md',
  490. TeamTaskId: 'agent-team.md',
  491. TeamTaskView: 'agent-team.md',
  492. TeamWaitResult: 'agent-team.md',
  493. UpdateTeamTaskRequest: 'agent-team.md',
  494. TokenMeasurement: 'token-meter.md',
  495. CodeDispatchLog: 'tools.md',
  496. PostToolDecision: 'tools.md',
  497. PreToolDecision: 'tools.md',
  498. ToolDefinition: 'tools.md',
  499. ToolExecution: 'tools.md',
  500. ToolDispatchExecution: 'tools.md',
  501. ToolExecutionInput: 'tools.md',
  502. ToolExecutionMode: 'tools.md',
  503. ToolExecutionResult: 'tools.md',
  504. ToolExecutionToken: 'tools.md',
  505. ToolGuard: 'tools.md',
  506. ToolPresentationMode: 'tools.md',
  507. ToolRuntime: 'tools.md',
  508. ToolRestriction: 'tools.md',
  509. ToolSchema: 'tools.md',
  510. SettingsNamespace: 'settings.md',
  511. SettingsRegisterOptions: 'settings.md',
  512. SettingsScope: 'settings.md',
  513. SettingsDescriptor: 'settings.md',
  514. SettingsPathOp: 'settings.md',
  515. SettingsDescribeOptions: 'settings.md',
  516. SettingsUpdateSource: 'settings.md',
  517. AuthorizationEntry: 'credentials.md',
  518. AuthorizationFlow: 'credentials.md',
  519. AuthorizationInteraction: 'credentials.md',
  520. AuthorizationMethod: 'credentials.md',
  521. AuthorizationNotice: 'credentials.md',
  522. AuthorizationOutcome: 'credentials.md',
  523. AuthorizationPrompt: 'credentials.md',
  524. AuthorizationRequest: 'credentials.md',
  525. AuthorizationSession: 'credentials.md',
  526. AuthorizationSettlement: 'credentials.md',
  527. AuthorizationStatus: 'credentials.md',
  528. CredentialRef: 'credentials.md',
  529. CredentialKey: 'credentials.md',
  530. CredentialInfo: 'credentials.md',
  531. CredentialRecord: 'credentials.md',
  532. CredentialRecordEntry: 'credentials.md',
  533. CredentialRecordInfo: 'credentials.md',
  534. ResolvedCredential: 'credentials.md',
  535. AskUserQuestionAnswer: 'user-questions.md',
  536. AskUserQuestionRequest: 'user-questions.md',
  537. UserQuestionProvider: 'user-questions.md',
  538. WebFetchProvider: 'web.md',
  539. WebFetchRequest: 'web.md',
  540. WebFetchResult: 'web.md',
  541. WebSearchProvider: 'web.md',
  542. WebSearchRequest: 'web.md',
  543. WebSearchResult: 'web.md',
  544. WorkflowRun: 'workflow.md',
  545. VerifiedWebhookDelivery: 'webhook.md',
  546. WebhookRule: 'webhook.md',
  547. PresetOption: 'permission-presets.md',
  548. PresetSpec: 'permission-presets.md',
  549. InvariantInstaller: 'invariants.md',
  550. WebRoute: 'web-server.md',
  551. IndexInjection: 'web-server.md',
  552. StorageBackend: 'storage.md',
  553. StorageForms: 'storage.md',
  554. Domain: 'storage.md',
  555. DomainSpec: 'storage.md',
  556. DomainChanged: 'storage.md',
  557. DomainFacility: 'storage.md',
  558. Workspace: 'workspace.md',
  559. WorkspaceArchiveSessionRequest: 'workspace.md',
  560. WorkspaceArchiveValue: 'workspace.md',
  561. WorkspaceCreateRequest: 'workspace.md',
  562. WorkspaceCreateValue: 'workspace.md',
  563. WorkspaceDeleteRequest: 'workspace.md',
  564. WorkspaceDeleteValue: 'workspace.md',
  565. WorkspaceFollowFrame: 'workspace.md',
  566. WorkspaceId: 'workspace.md',
  567. WorkspaceInsertBeforeRequest: 'workspace.md',
  568. WorkspaceInsertSessionBeforeRequest: 'workspace.md',
  569. WorkspaceOrderValue: 'workspace.md',
  570. WorkspaceRenameRequest: 'workspace.md',
  571. WorkspaceValue: 'workspace.md',
  572. ClientArtifactBaseline: 'client-modules.md',
  573. WebBootGraph: 'client-modules.md',
  574. SessionTelemetryRecord: 'session-telemetry.md',
  575. WorkflowRunInfo: 'workflow.md',
  576. WorkflowStartRequest: 'workflow.md',
  577. ProjectionDefinition: 'session-projection.md',
  578. SessionProjectionMap: 'session-projection.md',
  579. SessionProjectionStateMap: 'session-projection.md',
  580. ProjectionChangeListener: 'session-projection.md',
  581. ProjectionSnapshot: 'session-projection.md',
  582. ProjectionCheckpoint: 'session-projection.md',
  583. DirectoryPickerCapability: 'workspace.md',
  584. TypertContribution: 'invariants.md',
  585. TypertRemoteEventSource: 'typert.md',
  586. TypertFace: 'invariants.md',
  587. TypertPackageFilter: 'invariants.md',
  588. TypertPackageRecord: 'invariants.md',
  589. TypertSchemaFilter: 'invariants.md',
  590. TypertSchemaRecord: 'invariants.md',
  591. }
  592. /** TypeScript lib and pinned framework types with no repository-owned data page. */
  593. export const FOUNDATION_TYPE_NAMES: ReadonlySet<string> = new Set([
  594. 'AbortSignal',
  595. 'AsyncIterable',
  596. 'Context',
  597. 'Error',
  598. 'EntryTree',
  599. 'Exclude',
  600. 'Extract',
  601. 'Map',
  602. 'NonNullable',
  603. 'Omit',
  604. 'Partial',
  605. 'Pick',
  606. 'Promise',
  607. 'Record',
  608. 'Readonly',
  609. 'Uint8Array',
  610. ])
  611. /** Project types deliberately documented outside the subsystems catalog. */
  612. export const TYPE_LINK_EXEMPTIONS: Readonly<Record<string, string>> = {
  613. z: 'schemastery schema constructor is owned by vendor/schemastery (vendored upstream)',
  614. BeginCommandRequest: 'event-local request contract is owned by packages/client/ui-input-trigger/src/types.ts',
  615. InsertReferenceRequest: 'event-local request contract is owned by packages/client/ui-input-trigger/src/types.ts',
  616. ConsumeTokenRequest: 'event-local request contract is owned by packages/client/ui-input-trigger/src/types.ts',
  617. InsertTextRequest: 'event-local request contract is owned by packages/client/ui-input-trigger/src/types.ts',
  618. AgentHandle: 'agent ownership handle is owned by packages/core/agent/README.md',
  619. AgentPreset: 'discovered preset record is owned by packages/preset/agent-presets/README.md',
  620. PresetMetadata: 'preset display text is owned by packages/preset/agent-presets/README.md',
  621. BashEnvContributor: 'service-local extension type is owned by packages/shell/tool-bash/src/index.ts',
  622. BashEnvVariableInfo: 'service-local metadata type is owned by packages/shell/tool-bash/src/index.ts',
  623. CompactionAgentContext: 'compaction service input is owned by packages/compaction/compaction/src/index.ts',
  624. ManualCompactAgentContext: 'manual compaction service input is owned by packages/compaction/compaction/src/index.ts',
  625. ClientResponse: 'wire response message is owned by packages/host/apiproxy/src/api/rpc.ts',
  626. ApprovalRequestId: 'dynamic Plugin approval identity is owned by packages/extensions/cordis-host-runner/src/types.ts',
  627. CordisErrorDetails: 'Cordis runtime error payload is owned by packages/extensions/cordis-host-runner/src/types.ts',
  628. CordisInspectPlatform: 'Cordis inspect platform identity is owned by packages/extensions/cordis-host-runner/src/types.ts',
  629. CordisInspectProviderManifest: 'Cordis inspect provider manifest is owned by packages/extensions/cordis-host-runner/src/types.ts',
  630. CordisInspectProviderView: 'Cordis inspect provider view is owned by packages/extensions/cordis-host-runner/src/types.ts',
  631. CordisInspectQueryRequest: 'Cordis inspect transport payload is owned by packages/extensions/cordis-host-runner/src/types.ts',
  632. CordisInspectQueryResolution: 'Cordis inspect query result is owned by packages/extensions/cordis-host-runner/src/types.ts',
  633. CordisInspectQueryResolved: 'Cordis inspect transport payload is owned by packages/extensions/cordis-host-runner/src/types.ts',
  634. CordisInspectRequestId: 'Cordis inspect request identity is owned by packages/extensions/cordis-host-runner/src/types.ts',
  635. CordisInspectResolveAck: 'Cordis inspect resolution acknowledgement is owned by packages/extensions/cordis-host-runner/src/types.ts',
  636. CordisDynamicPackageId: 'dynamic Package identity is owned by packages/extensions/cordis-host-runner/src/types.ts',
  637. CordisDynamicPluginId: 'dynamic Plugin identity is owned by packages/extensions/cordis-host-runner/src/types.ts',
  638. CordisDynamicPluginRunId: 'dynamic Plugin run identity is owned by packages/extensions/cordis-host-runner/src/types.ts',
  639. CordisDynamicRunMode: 'dynamic Plugin activation mode is owned by packages/extensions/cordis-host-runner/src/types.ts',
  640. DynamicCordisClientSource: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  641. DynamicCordisDefineReceipt: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  642. DynamicCordisDefineRequest: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  643. DynamicCordisHostHalfResult: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  644. DynamicCordisInventoryRow: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  645. DynamicCordisInvokeResult: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  646. DynamicCordisPackageInspection: 'dynamic Package source inspection is owned by packages/extensions/cordis-host-runner/src/registry.ts',
  647. DynamicCordisPluginInspection: 'dynamic Plugin inspection is owned by packages/extensions/cordis-host-runner/src/registry.ts',
  648. DynamicCordisRequestResolved: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  649. DynamicCordisRetracted: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  650. DynamicCordisRunRequest: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  651. DynamicCordisPackage: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  652. DynamicCordisReference: 'dynamic Plugin reference is owned by packages/extensions/cordis-host-runner/src/registry.ts',
  653. DynamicCordisRenderFailure: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  654. DynamicCordisResolveAck: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  655. DynamicCordisRunResolution: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  656. DynamicCordisRunResponse: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  657. DynamicCordisSnapshotRow: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  658. DynamicCordisStopResponse: 'dynamic Plugin stop result is owned by packages/extensions/cordis-host-runner/src/types.ts',
  659. DynamicCordisUndefineReceipt: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  660. HostCordisInspectProviderRegistration: 'Host inspect provider registration is owned by packages/extensions/cordis-host-runner/src/inspect-registry.ts',
  661. DomainImpl: 'domain implementation contract is owned by packages/storage/storage-domain/README.md',
  662. CommandExecution: 'executor return contract is owned by packages/interaction/commands/src/index.ts',
  663. 'z.core.JSONSchema.BaseSchema': 'zod projection output is owned by the zod v4 API',
  664. 'z.core.ToJSONSchemaParams': 'zod projection parameters are owned by the zod v4 API',
  665. TypertDisposer: 'Typert lifecycle contract is owned by packages/typert/protocol/README.md',
  666. InvokeRemoteRequest: 'gateway invocation contract is owned by packages/api/gateway/README.md',
  667. LocaleDict: 'service-local dictionary fields are owned by packages/client/i18n/src/index.ts',
  668. ThemeTokens: 'service-local token dictionary is owned by packages/client/ui-theme/src/index.ts',
  669. Translate: 'service-local bound translator is owned by packages/client/i18n/src/index.ts',
  670. WebUpgradeRoute:
  671. 'upgrade route registration contract is owned by packages/host/webserver/src/index.ts',
  672. InvariantRegistration: 'service-local lifecycle handle is owned by packages/runtime-diagnostics/invariants/README.md',
  673. JsonValue: 'JSON value union is owned by packages/core/session/src/json.ts',
  674. KnobState: 'projection unit state fields are owned by packages/interaction/permission-presets/README.md',
  675. PermissionSelect: 'permissions projection payload is owned by packages/interaction/permission-presets/src/types.ts',
  676. PromptAssembly: 'assembly result is owned by packages/core/system-prompt/README.md',
  677. RequestRunId: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  678. RpcReceipt: 'carrier-layer receipt is owned by packages/host/apiproxy/src/api/rpc.ts',
  679. Sandbox: 'external E2B SDK handle is owned by packages/e2b/e2b/README.md',
  680. SessionForkSource: 'service-local fork input is owned by packages/core/session/src/index.ts',
  681. SubagentRunEndInfo: 'event payload contract is owned by packages/subagent/subagent/src/types.ts',
  682. SubagentRunInfo: 'event payload contract is owned by packages/subagent/subagent/src/types.ts',
  683. WorkflowAgentEndInfo: 'event-local snapshot is owned by packages/workflow/workflow/src/index.ts',
  684. WorkflowAgentInfo: 'event-local snapshot is owned by packages/workflow/workflow/src/index.ts',
  685. WorkflowResultInfo: 'event-local snapshot is owned by packages/workflow/workflow/src/index.ts',
  686. }
  687. /** Repository data policy consumed by the Cordis catalog projector. */
  688. export const CORDIS_CATALOG_POLICY: CordisCatalogPolicy = {
  689. linkedTypePages: LINK_MAP,
  690. foundationTypeNames: FOUNDATION_TYPE_NAMES,
  691. typeLinkExemptions: TYPE_LINK_EXEMPTIONS,
  692. runtimeServiceExclusions: new Set(['cordisInspect', 'dynamicCordisRunner']),
  693. runtimeServices: [{
  694. key: 'timer',
  695. type: 'TimerService',
  696. abstract: false,
  697. doc: 'Disposable timer helpers mixed into Cordis contexts.',
  698. source: 'vendor/timer/src/index.ts:12',
  699. methods: [
  700. {
  701. signature: 'timeout(callback: () => void, delay: number): () => void',
  702. jsDoc: '/** Run a callback once and return its disposer. */',
  703. },
  704. {
  705. signature: 'timeout(delay: number): Promise<void>',
  706. jsDoc: '/** Resolve after a delay; disposal rejects the pending promise. */',
  707. },
  708. {
  709. signature: 'interval(callback: () => void, delay: number): () => void',
  710. jsDoc: '/** Run a callback repeatedly and return its disposer. */',
  711. },
  712. {
  713. signature: 'interval<R = any>(delay: number): AsyncIterableIterator<void, R, void>',
  714. jsDoc: '/** Return an async iterator of timer ticks. */',
  715. },
  716. {
  717. signature: 'throttle<F extends (...args: any[]) => void>(callback: F, delay: number, noTrailing?: boolean): F & { dispose: () => void }',
  718. jsDoc: '/** Return a throttled function whose timer is disposed with the current fiber. */',
  719. },
  720. {
  721. signature: 'debounce<F extends (...args: any[]) => void>(callback: F, delay: number): F & { dispose: () => void }',
  722. jsDoc: '/** Return a debounced function whose timer is disposed with the current fiber. */',
  723. },
  724. ],
  725. }],
  726. inheritedEvents: [
  727. { name: 'internal/plugin', summary: 'A plugin fiber was created.', source: 'vendor/cordis/src/events.ts:328' },
  728. { name: 'internal/status', summary: 'A fiber changed lifecycle state.', source: 'vendor/cordis/src/events.ts:330' },
  729. { name: 'internal/service', summary: 'Interception hook for a service binding (no core producer).', source: 'vendor/cordis/src/events.ts:332' },
  730. { name: 'internal/update', summary: 'Waterfall: a fiber config update is being applied.', source: 'vendor/cordis/src/events.ts:334' },
  731. { name: 'internal/get', summary: 'Waterfall: a service is being read from the store.', source: 'vendor/cordis/src/events.ts:336' },
  732. { name: 'internal/set', summary: 'Waterfall: a service is being written to the store.', source: 'vendor/cordis/src/events.ts:338' },
  733. { name: 'internal/listener', summary: 'A listener was registered.', source: 'vendor/cordis/src/events.ts:340' },
  734. { name: 'internal/dispatch', summary: 'An event is being dispatched to listeners.', source: 'vendor/cordis/src/events.ts:342' },
  735. { name: 'hmr/change', summary: 'A watched source file changed on disk.', source: 'vendor/hmr/src/index.ts:20' },
  736. { name: 'hmr/reload', summary: 'Plugins are being reloaded after a change.', source: 'vendor/hmr/src/index.ts:21' },
  737. { name: 'exit', summary: 'The process is exiting on a signal.', source: 'vendor/loader/src/index.ts:23' },
  738. { name: 'loader/config-update', summary: 'The loader config tree changed.', source: 'vendor/loader/src/index.ts:24' },
  739. { name: 'loader/entry-init', summary: 'A config entry is being initialized.', source: 'vendor/loader/src/index.ts:25' },
  740. { name: 'loader/partial-dispose', summary: 'An entry is being partially disposed on reload.', source: 'vendor/loader/src/index.ts:26' },
  741. { name: 'loader/patch-context', summary: 'A context is being patched during a reload.', source: 'vendor/loader/src/index.ts:27' },
  742. ],
  743. inheritedServices: [
  744. { name: 'ctx.on / ctx.once', summary: 'Register an event listener (disposable).', source: 'vendor/cordis/src/events.ts:34' },
  745. { name: 'ctx.emit / ctx.parallel / ctx.serial / ctx.bail / ctx.waterfall', summary: 'Dispatch an event (sync / awaited / first-bail / short-circuit chain).', source: 'vendor/cordis/src/events.ts:34' },
  746. { name: 'ctx.plugin / ctx.inject', summary: 'Load a plugin / declare required services.', source: 'vendor/cordis/src/registry.ts:164' },
  747. { name: 'ctx.effect', summary: 'Register a disposable side effect tied to the fiber.', source: 'vendor/cordis/src/fiber.ts:9' },
  748. { name: 'ctx.get / ctx.set / ctx.provide / ctx.accessor / ctx.mixin', summary: 'Low-level service-store access and binding.', source: 'vendor/cordis/src/reflect.ts:7' },
  749. { name: 'ctx.extend / ctx.isolate / ctx.intercept', summary: 'Derive a child context (scoped services / isolation / interception).', source: 'vendor/cordis/src/context.ts:42' },
  750. { name: 'ctx.root / ctx.scope / ctx.fiber / ctx.registry / ctx.reflect / ctx.events / ctx.logger', summary: 'Ambient handles onto the running context graph.', source: 'vendor/cordis/src/context.ts:16' },
  751. { name: 'ctx.timer (+ interval / timeout / throttle / debounce)', summary: 'Disposable timer helpers. The `timer` key is provided at runtime; the four supported helpers are mixed onto ctx directly (declared via Pick).', source: 'vendor/timer/src/index.ts:4' },
  752. { name: 'ctx.loader', summary: 'The config Loader that booted the app (present under the loader).', source: 'vendor/loader/src/index.ts:30' },
  753. { name: 'ctx.hmr', summary: 'The hot-module-reload watcher (present under the hmr plugin).', source: 'vendor/hmr/src/index.ts:15' },
  754. ],
  755. }
  756. /**
  757. * Splice a page's generated Cordis API region into its Markdown content.
  758. * The page must contain exactly one `cordis-surface` marker region (the markers are
  759. * part of the hand-owned page skeleton once, then owned by the generator);
  760. * zero or several is a partition error the caller reports with the page path.
  761. * The match is on THIS generator's exact markers, not the generic region
  762. * grammar, so a page carrying only some other generator's region fails loud
  763. * instead of having that region overwritten.
  764. * @param content - the page's current full Markdown text.
  765. * @param region - the freshly rendered marker-delimited region.
  766. * @returns the page text with the region replaced.
  767. */
  768. export function spliceRegion(content: string, region: string): string {
  769. const lines = content.split('\n')
  770. const begins = lines.flatMap((line, index) => (line === REGION_BEGIN ? [index] : []))
  771. const ends = lines.flatMap((line, index) => (line === REGION_END ? [index] : []))
  772. if (begins.length !== 1 || ends.length !== 1) {
  773. throw new Error(`expected exactly 1 cordis-surface region, found ${begins.length} BEGIN/${ends.length} END; add the BEGIN/END cordis-surface markers once`)
  774. }
  775. const begin = begins[0] ?? -1
  776. const end = ends[0] ?? -1
  777. if (end < begin) throw new Error('cordis-surface END marker precedes its BEGIN')
  778. return [...lines.slice(0, begin), ...region.split('\n'), ...lines.slice(end + 1)].join('\n')
  779. }
  780. /** The declared-vs-rendered inputs {@link walkPartitionProblems} judges. */
  781. export interface WalkPartitionInput {
  782. /** Service key → source pointer, as the rendering projection produced them. */
  783. readonly renderedKeys: ReadonlyMap<string, string>
  784. /** Event scopes the rendering projection produced. */
  785. readonly renderedScopes: ReadonlySet<string>
  786. /** Event names the rendering projection produced. */
  787. readonly renderedEventNames: ReadonlySet<string>
  788. /** Context key → first declaring file, from the independent AST scan. */
  789. readonly declaredKeys: ReadonlyMap<string, string>
  790. /** Event name → first declaring file, from the independent AST scan. */
  791. readonly declaredEvents: ReadonlyMap<string, string>
  792. }
  793. /** The curated partition maps {@link walkPartitionProblems} enforces. */
  794. export interface WalkPartitionMaps {
  795. readonly servicePage: Readonly<Record<string, string>>
  796. readonly serviceWalkExemptions: Readonly<Record<string, string>>
  797. readonly eventScopePage: Readonly<Record<string, string>>
  798. readonly eventWalkExemptions: Readonly<Record<string, string>>
  799. }
  800. /** Project paired Markdown destinations in one generated region to the page's locale. */
  801. export function localizePageRegion(region: string, pageRel: string, scanRoot: string = root): string {
  802. if (!pageRel.endsWith('.zh.md')) return region
  803. const manifest = parseTranslationPairingManifest(
  804. readFileSync(resolve(scanRoot, 'scripts/translation-pairing.manifest.json'), 'utf8'),
  805. )
  806. return rewriteTranslationLinkLocales(region, {
  807. repoRoot: scanRoot,
  808. sourcePath: pageRel,
  809. isTranslationPairSource: translationPairSourcePredicate(manifest),
  810. }).content
  811. }
  812. /**
  813. * Judge the rendered API and the independent AST scan against the curated
  814. * partition maps, fail-closed in both directions for services AND events: a
  815. * rendered key/scope must be mapped to a page, a mapped key/scope must still
  816. * render, and — the backstop — a DECLARED key/event the projection cannot see
  817. * must carry a named walk exemption (a rendered one must not). A third
  818. * direction guards the scan itself: everything rendered must also be declared
  819. * to the scan, so a scan blind spot cannot decay silently. Pure so the
  820. * acceptance paths are provable without running the projection.
  821. * @param input - rendered API plus the declared-key/event scans.
  822. * @param maps - the curated page maps and walk exemptions.
  823. * @returns one message per violation, empty when the partition holds.
  824. */
  825. export function walkPartitionProblems(input: WalkPartitionInput, maps: WalkPartitionMaps): string[] {
  826. const problems: string[] = []
  827. for (const [key, source] of input.renderedKeys) {
  828. if (!Object.hasOwn(maps.servicePage, key)) problems.push(`service ctx.${key} (${source}) has no SERVICE_PAGE entry; every service maps to exactly one subsystems page.`)
  829. }
  830. for (const scope of [...input.renderedScopes].sort()) {
  831. if (!Object.hasOwn(maps.eventScopePage, scope)) problems.push(`event scope '${scope}/*' has no EVENT_SCOPE_PAGE entry; every event scope maps to exactly one subsystems page.`)
  832. }
  833. for (const key of Object.keys(maps.servicePage)) {
  834. if (!input.renderedKeys.has(key)) problems.push(`SERVICE_PAGE maps 'ctx.${key}' but the projection discovers no such service; remove the stale entry.`)
  835. }
  836. for (const scope of Object.keys(maps.eventScopePage)) {
  837. if (!input.renderedScopes.has(scope)) problems.push(`EVENT_SCOPE_PAGE maps '${scope}/*' but the projection discovers no such scope; remove the stale entry.`)
  838. }
  839. // The rendering projection only sees a Context key it can resolve to a
  840. // documented service class. The independent scan reads EVERY Context merge
  841. // so a key the projection cannot render must either be rendered (mapped) or
  842. // carry a named SERVICE_WALK_EXEMPTIONS reason — never vanish silently.
  843. for (const [key, rel] of input.declaredKeys) {
  844. const rendered = input.renderedKeys.has(key)
  845. const exempt = Object.hasOwn(maps.serviceWalkExemptions, key)
  846. if (!rendered && !exempt) {
  847. problems.push(`ctx.${key} (${rel}) is declared in a Context merge but invisible to the rendering projection; map it in SERVICE_PAGE (after making it renderable) or name it in SERVICE_WALK_EXEMPTIONS with its documentation owner.`)
  848. }
  849. if (rendered && exempt) problems.push(`ctx.${key} is rendered by the projection but still listed in SERVICE_WALK_EXEMPTIONS; remove the stale exemption.`)
  850. }
  851. for (const key of Object.keys(maps.serviceWalkExemptions)) {
  852. if (!input.declaredKeys.has(key)) problems.push(`SERVICE_WALK_EXEMPTIONS names 'ctx.${key}' but no Context merge declares it; remove the stale exemption.`)
  853. }
  854. // The event mirror of the service backstop: the projection walks only files
  855. // reachable from host-face package exports, so a client-face or unreachable
  856. // Events merge would otherwise vanish without a trace.
  857. for (const [name, rel] of input.declaredEvents) {
  858. const rendered = input.renderedEventNames.has(name)
  859. const exempt = Object.hasOwn(maps.eventWalkExemptions, name)
  860. if (!rendered && !exempt) {
  861. problems.push(`event '${name}' (${rel}) is declared in an Events merge but invisible to the rendering projection; make it renderable (mapped via EVENT_SCOPE_PAGE) or name it in EVENT_WALK_EXEMPTIONS with its documentation owner.`)
  862. }
  863. if (rendered && exempt) problems.push(`event '${name}' is rendered by the projection but still listed in EVENT_WALK_EXEMPTIONS; remove the stale exemption.`)
  864. }
  865. for (const name of Object.keys(maps.eventWalkExemptions)) {
  866. if (!input.declaredEvents.has(name)) problems.push(`EVENT_WALK_EXEMPTIONS names '${name}' but no Events merge declares it; remove the stale exemption.`)
  867. }
  868. // Self-check the scan itself: everything the projection renders is declared
  869. // in a Context/Events merge the scan must also reach, so a rendered key or
  870. // event the scan cannot see means the SCAN regressed (glob, prefilter, or
  871. // block walk) — a partial blind spot that exemption staleness alone would
  872. // never appear.
  873. for (const key of input.renderedKeys.keys()) {
  874. if (!input.declaredKeys.has(key)) problems.push(`ctx.${key} is rendered by the projection but the independent scan finds no Context merge declaring it; the scan has a blind spot (glob, prefilter, or module-block walk) — fix the scan, not the maps.`)
  875. }
  876. for (const name of input.renderedEventNames) {
  877. if (!input.declaredEvents.has(name)) problems.push(`event '${name}' is rendered by the projection but the independent scan finds no Events merge declaring it; the scan has a blind spot (glob, prefilter, or module-block walk) — fix the scan, not the maps.`)
  878. }
  879. return problems
  880. }
  881. /**
  882. * Compute every generated artifact: the inherited-tier page, the model-facing
  883. * runtime API module, plus, per mapped subsystems page, the pair's two updated
  884. * documents with the injected region. Fail-loud partition checks live here: an
  885. * unmapped service/event scope, a mapping whose page file does not exist, a
  886. * curated entry whose key/scope the projection no longer discovers, a declared
  887. * Context key or Events member the projection cannot see without a named walk
  888. * exemption, and a mapped page missing its markers are all aggregated errors.
  889. * @returns `[repo-relative path, exact content]` for every generated artifact.
  890. */
  891. export function computeOutputs(): [string, string][] {
  892. const { projector, model } = projectCordisCatalog(root, CORDIS_CATALOG_POLICY)
  893. const services = [...model.services]
  894. const events = [...model.events]
  895. const declaredKeys = new Map<string, string>()
  896. const declaredEvents = new Map<string, string>()
  897. for (const { rel, sf, body } of contextMergeFiles(root, ['packages/*/*/src/**/*.ts', 'packages/*/*/src/**/*.tsx'])) {
  898. for (const key of contextKeyMap(body, sf).keys()) {
  899. if (!declaredKeys.has(key)) declaredKeys.set(key, rel)
  900. }
  901. for (const name of eventNameList(body, sf)) {
  902. if (!declaredEvents.has(name)) declaredEvents.set(name, rel)
  903. }
  904. }
  905. const problems = walkPartitionProblems({
  906. renderedKeys: new Map(services.map(s => [s.key, s.source])),
  907. renderedScopes: new Set(events.map(e => e.scope)),
  908. renderedEventNames: new Set(events.map(e => e.name)),
  909. declaredKeys,
  910. declaredEvents,
  911. }, {
  912. servicePage: SERVICE_PAGE,
  913. serviceWalkExemptions: SERVICE_WALK_EXEMPTIONS,
  914. eventScopePage: EVENT_SCOPE_PAGE,
  915. eventWalkExemptions: EVENT_WALK_EXEMPTIONS,
  916. })
  917. if (problems.length > 0) throw new Error(`gen-cordis-catalog: ${problems.length} partition violation(s):\n${problems.map(p => ` ${p}`).join('\n')}`)
  918. const pages = [...new Set([...Object.values(SERVICE_PAGE), ...Object.values(EVENT_SCOPE_PAGE)])].sort()
  919. const outputs: [string, string][] = [
  920. [OUT_INHERITED, renderInheritedPage(CORDIS_CATALOG_POLICY)],
  921. [OUT_RUNTIME_API, projector.renderRuntimeApi(model)],
  922. ]
  923. for (const page of pages) {
  924. const region = renderPageRegion(
  925. page,
  926. services.filter(s => SERVICE_PAGE[s.key] === page),
  927. events.filter(e => EVENT_SCOPE_PAGE[e.scope] === page),
  928. CORDIS_CATALOG_POLICY,
  929. )
  930. for (const side of [page, page.replace(/\.md$/, '.zh.md')]) {
  931. const rel = `${SUBSYSTEMS_DIR}/${side}`
  932. const localizedRegion = localizePageRegion(region, rel)
  933. let current: string
  934. try {
  935. current = readFileSync(resolve(root, rel), 'utf8')
  936. } catch {
  937. // Both pair sides must exist before a region can be injected; the
  938. // pairing gate owns pair completeness, this generator names the miss.
  939. problems.push(`${rel}: mapped subsystems page does not exist.`)
  940. continue
  941. }
  942. try {
  943. outputs.push([rel, spliceRegion(current, localizedRegion)])
  944. } catch (error) {
  945. problems.push(`${rel}: ${error instanceof Error ? error.message : String(error)}`)
  946. }
  947. }
  948. }
  949. if (problems.length > 0) throw new Error(`gen-cordis-catalog: ${problems.length} page violation(s):\n${problems.map(p => ` ${p}`).join('\n')}`)
  950. return outputs
  951. }
  952. /**
  953. * Re-record a pair's `.i18n.yaml` after a region write ONLY when the write is
  954. * region-confined: both sides' region-stripped content must be byte-equal to
  955. * the region-stripped previous content whose hashes the record holds. The
  956. * caller supplies the previous bytes (read before writing); human-content
  957. * drift leaves the record untouched so the pairing gate still demands the
  958. * normal translation flow.
  959. * @param pageRel - repo-relative English page path (`docs/subsystems/x.md`).
  960. * @param before - pre-write bytes per repo-relative path.
  961. * @param scanRoot - repository root override for tests.
  962. * @returns true when the record was refreshed.
  963. */
  964. export function maybeRecordPair(pageRel: string, before: Map<string, Buffer>, scanRoot: string = root): boolean {
  965. const zhRel = pageRel.replace(/\.md$/, '.zh.md')
  966. const metaRel = pageRel.replace(/\.md$/, '.i18n.yaml')
  967. const metaAbs = resolve(scanRoot, metaRel)
  968. let meta: string
  969. try {
  970. meta = readFileSync(metaAbs, 'utf8')
  971. } catch {
  972. // No record yet: a brand-new pair is recorded by the author's --write
  973. // after review, never silently by regeneration.
  974. return false
  975. }
  976. // The record must contain exactly the two valid entries for THIS pair;
  977. // a malformed or renamed-key sidecar is the pairing gate's problem to
  978. // report, never something regeneration silently repairs into validity.
  979. const recorded = parsePairMeta(meta)
  980. const names = [pageRel, zhRel].map(rel => rel.split('/').at(-1) ?? rel)
  981. if (!recorded || recorded.size !== 2 || !names.every(name => recorded.has(name))) return false
  982. for (const rel of [pageRel, zhRel]) {
  983. const previous = before.get(rel)
  984. if (!previous) return false
  985. if (recorded.get(rel.split('/').at(-1) ?? rel) !== blobHash(previous)) return false
  986. const current = readFileSync(resolve(scanRoot, rel))
  987. const strippedBefore = partitionGeneratedRegions(previous.toString('utf8')).stripped
  988. const strippedAfter = partitionGeneratedRegions(current.toString('utf8')).stripped
  989. if (strippedBefore !== strippedAfter) return false
  990. }
  991. const source = readFileSync(resolve(scanRoot, pageRel))
  992. const zh = readFileSync(resolve(scanRoot, zhRel))
  993. writeFileSync(metaAbs, renderPairMeta(pageRel, blobHash(source), zhRel, blobHash(zh)))
  994. return true
  995. }
  996. /** CLI entry: default regenerates every artifact, `--check` fails if any is
  997. * stale. Guarded behind an entry-point check so importing this module for
  998. * tests neither regenerates the committed files nor calls process.exit.
  999. * @returns nothing; writes files or reports freshness through the process.
  1000. */
  1001. export function main(): void {
  1002. const outputs: [string, string][] = [
  1003. ...computeOutputs(),
  1004. ...renderCordisCoreApiPages(),
  1005. ]
  1006. if (process.argv.includes('--check')) {
  1007. const stale: string[] = []
  1008. for (const [out, content] of outputs) {
  1009. let committed: string | null = null
  1010. try {
  1011. committed = readFileSync(resolve(root, out), 'utf8')
  1012. } catch {
  1013. // Only ENOENT (not yet generated) is expected; a present-but-unreadable
  1014. // file is not a state this repo produces. Either way the remedy is the
  1015. // same — regenerate — so treat a read failure as "stale".
  1016. committed = null
  1017. }
  1018. if (committed !== content) stale.push(out)
  1019. }
  1020. if (stale.length === 0) {
  1021. console.log(`gen-cordis-catalog: ${outputs.length} generated file(s)/region(s) are up to date.`)
  1022. process.exit(0)
  1023. }
  1024. console.error(`gen-cordis-catalog: stale — ${stale.join(', ')}. Run \`pnpm run gen-cordis-catalog\` and commit the result.`)
  1025. process.exit(1)
  1026. }
  1027. const before = new Map<string, Buffer>()
  1028. for (const [out] of outputs) {
  1029. try {
  1030. before.set(out, readFileSync(resolve(root, out)))
  1031. } catch {
  1032. // First generation of this artifact; nothing to guard, nothing to record.
  1033. }
  1034. }
  1035. let changedPages = 0
  1036. let recorded = 0
  1037. for (const [out, content] of outputs) {
  1038. const destination = resolve(root, out)
  1039. if (before.get(out)?.toString('utf8') === content) continue
  1040. mkdirSync(dirname(destination), { recursive: true })
  1041. writeFileSync(destination, content)
  1042. changedPages++
  1043. }
  1044. for (const page of [...new Set([...Object.values(SERVICE_PAGE), ...Object.values(EVENT_SCOPE_PAGE)])]) {
  1045. const rel = `${SUBSYSTEMS_DIR}/${page}`
  1046. const zhRel = rel.replace(/\.md$/, '.zh.md')
  1047. const wroteEither = [rel, zhRel].some((side) => {
  1048. const previous = before.get(side)
  1049. return previous !== undefined && previous.toString('utf8') !== readFileSync(resolve(root, side), 'utf8')
  1050. })
  1051. if (wroteEither && maybeRecordPair(rel, before)) recorded++
  1052. }
  1053. console.log(`gen-cordis-catalog: ${outputs.length} artifact(s) computed, ${changedPages} written, ${recorded} pair record(s) refreshed.`)
  1054. }
  1055. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  1056. main()
  1057. }