gen-cordis-catalog.ts 60 KB

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