gen-cordis-catalog.ts 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  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. LlmModelInfo: 'llm-streaming.md',
  253. LlmProviderInfo: 'llm-streaming.md',
  254. LlmConfigurableProvider: 'llm-streaming.md',
  255. LlmModelDiscoveryRequest: 'llm-streaming.md',
  256. LlmDiscoveredModel: 'llm-streaming.md',
  257. ResolvedRetryPolicy: 'llm-streaming.md',
  258. Message: 'llm-streaming.md',
  259. MessageSource: 'llm-streaming.md',
  260. MessageFeedbackDeleteRequest: 'feedback.md',
  261. MessageFeedbackDeleteResult: 'feedback.md',
  262. MessageFeedbackDeleteValue: 'feedback.md',
  263. MessageFeedbackFailure: 'feedback.md',
  264. MessageFeedbackItem: 'feedback.md',
  265. MessageFeedbackListRequest: 'feedback.md',
  266. MessageFeedbackListResult: 'feedback.md',
  267. MessageFeedbackListValue: 'feedback.md',
  268. MessageFeedbackNoteBlank: 'feedback.md',
  269. MessageFeedbackNoteTooLarge: 'feedback.md',
  270. MessageFeedbackPutRequest: 'feedback.md',
  271. MessageFeedbackPutResult: 'feedback.md',
  272. MessageFeedbackRating: 'feedback.md',
  273. MessageFeedbackRejected: 'feedback.md',
  274. MessageFeedbackSessionNotFound: 'feedback.md',
  275. MessageFeedbackSuccess: 'feedback.md',
  276. MessageFeedbackTargetNotFound: 'feedback.md',
  277. MessageFeedbackVersion: 'feedback.md',
  278. MessageFeedbackVersionConflict: 'feedback.md',
  279. UserMessage: 'session.md',
  280. ApiSessionAgentResult: 'session.md',
  281. PreStepDecision: 'core.md',
  282. PreStepContext: 'core.md',
  283. RequestErrorAction: 'core.md',
  284. RequestFailureContext: 'core.md',
  285. PreparedReferencedMessage: 'session-reference.md',
  286. FileReferenceCandidate: 'session-reference.md',
  287. SessionReferenceCandidate: 'session-reference.md',
  288. SessionReferenceMentionCandidate: 'session-reference.md',
  289. SessionReferenceInput: 'session-reference.md',
  290. SessionAttachmentRequest: 'session.md',
  291. SessionAttachmentValue: 'session.md',
  292. SessionCancelRequest: 'session.md',
  293. SessionCancelValue: 'session.md',
  294. SessionControlFrame: 'session.md',
  295. SessionCreateRequest: 'session.md',
  296. SessionCreateValue: 'session.md',
  297. SessionEvent: 'session.md',
  298. SessionFollowFrame: 'session.md',
  299. SessionFollowRequest: 'session.md',
  300. SessionForkRequest: 'session.md',
  301. SessionForkValue: 'session.md',
  302. SessionId: 'core.md',
  303. SessionListRequest: 'session.md',
  304. SessionListValue: 'session.md',
  305. SessionModels: 'session.md',
  306. SessionModelsRequest: 'session.md',
  307. SessionPage: 'session.md',
  308. SessionPageRequest: 'session.md',
  309. SessionPromptRequest: 'session.md',
  310. SessionPromptValue: 'session.md',
  311. SessionRenameRequest: 'session.md',
  312. SessionRenameValue: 'session.md',
  313. SessionRespondReceipt: 'session.md',
  314. SessionRespondRequest: 'session.md',
  315. SessionSearchValue: 'session.md',
  316. SessionSelectModelRequest: 'session.md',
  317. SessionSelectModelValue: 'session.md',
  318. SessionSummary: 'session.md',
  319. SessionUpdateQueueRequest: 'session.md',
  320. SessionUpdateQueueValue: 'session.md',
  321. SessionStartSource: 'core.md',
  322. SessionLogSnapshot: 'session-query.md',
  323. SessionSurfaceSnapshot: 'session-query.md',
  324. ApprovalOutcome: 'approval.md',
  325. ApprovalPolicy: 'approval.md',
  326. ApprovalRequest: 'approval.md',
  327. ApprovalRequestEvent: 'approval.md',
  328. ApprovalService: 'approval.md',
  329. AskUserQuestionRequestEvent: 'user-questions.md',
  330. EncodedImageAttachment: 'attachment.md',
  331. ImageAttachmentAccess: 'llm-streaming.md',
  332. ImageAttachmentRef: 'attachment.md',
  333. ImageRequestPolicy: 'attachment.md',
  334. RequestImageAttachment: 'attachment.md',
  335. SaveImageAttachment: 'attachment.md',
  336. StoredImageAttachment: 'attachment.md',
  337. ShellExecRequest: 'shell.md',
  338. ShellExecSpec: 'shell.md',
  339. ShellProcess: 'shell.md',
  340. ShellRunResult: 'shell.md',
  341. DshEnvironment: 'subprocess.md',
  342. SubprocessHandle: 'subprocess.md',
  343. SubprocessOutcome: 'subprocess.md',
  344. SubprocessOutputRead: 'subprocess.md',
  345. SubprocessOutputReader: 'subprocess.md',
  346. SubprocessSpawnSpec: 'subprocess.md',
  347. SubprocessTerminalHandle: 'subprocess.md',
  348. SubprocessTerminalSpawnSpec: 'subprocess.md',
  349. CodeRunRequest: 'code-runtime.md',
  350. CodeRunResult: 'code-runtime.md',
  351. CompactionResult: 'compaction.md',
  352. CompactionTrigger: 'compaction.md',
  353. PruneResult: 'compaction.md',
  354. FileReadOutcome: 'filesystem.md',
  355. FsDirEntry: 'filesystem.md',
  356. FsEditOutcome: 'filesystem.md',
  357. FsEditRequest: 'filesystem.md',
  358. FsInfo: 'filesystem.md',
  359. FsObservation: 'filesystem.md',
  360. FsPathInfo: 'filesystem.md',
  361. FsObservationActor: 'filesystem.md',
  362. FsTarget: 'filesystem.md',
  363. FsVersion: 'filesystem.md',
  364. FsWriteIntent: 'filesystem.md',
  365. FsWriteOutcome: 'filesystem.md',
  366. CreateGoalRequest: 'goal.md',
  367. EditGoalRequest: 'goal.md',
  368. GoalBlockReason: 'goal.md',
  369. GoalChanged: 'goal.md',
  370. GoalRef: 'goal.md',
  371. GoalView: 'goal.md',
  372. CreateGoalResult: 'goal.md',
  373. CommandDefinition: 'commands.md',
  374. CommandDescriptor: 'commands.md',
  375. CommandId: 'commands.md',
  376. CommandResult: 'commands.md',
  377. CommandSurface: 'commands.md',
  378. LspProvider: 'lsp.md',
  379. LspQueryRequest: 'lsp.md',
  380. LspQueryResult: 'lsp.md',
  381. LlmAdapter: 'llm-streaming.md',
  382. PreparedLlmCall: 'llm-streaming.md',
  383. PreparedDeepSeekLlmApiExtensions: 'llm-streaming.md',
  384. LlmRuntime: 'llm-streaming.md',
  385. StreamChunk: 'llm-streaming.md',
  386. SkillProviderControl: 'skills.md',
  387. CreateSessionOptions: 'persistence.md',
  388. PrepareSessionOptions: 'persistence.md',
  389. SessionHeader: 'persistence.md',
  390. SessionInspection: 'persistence.md',
  391. BorrowedSessionSource: 'persistence.md',
  392. SessionLocation: 'persistence.md',
  393. SessionPreparation: 'persistence.md',
  394. SessionPersistenceSnapshot: 'persistence.md',
  395. SessionRawArtifact: 'persistence.md',
  396. ConfinedArgv: 'sandbox.md',
  397. SandboxExecutionPolicy: 'sandbox.md',
  398. SandboxMode: 'sandbox.md',
  399. SandboxPolicy: 'sandbox.md',
  400. TerminalBackend: 'terminal.md',
  401. TerminalReadRequest: 'terminal.md',
  402. TerminalReadResult: 'terminal.md',
  403. TerminalSendOperation: 'terminal.md',
  404. TerminalSendRequest: 'terminal.md',
  405. TerminalSessionId: 'terminal.md',
  406. TerminalSessionSnapshot: 'terminal.md',
  407. TerminalSignal: 'terminal.md',
  408. TerminalSignalResult: 'terminal.md',
  409. TerminalSpawnRequest: 'terminal.md',
  410. TerminalSpawnResult: 'terminal.md',
  411. SandboxPolicyRequest: 'sandbox.md',
  412. ScopeKey: 'scope.md',
  413. Scoped: 'scope.md',
  414. EpochHeader: 'session.md',
  415. Session: 'session.md',
  416. SessionEventMap: 'session.md',
  417. TurnEndReason: 'session.md',
  418. TurnTrigger: 'session.md',
  419. SessionEventReadRequest: 'session-query.md',
  420. SessionEventRecord: 'session-query.md',
  421. SessionEventResultFilter: 'session-query.md',
  422. SessionEventSearchDocument: 'session-query.md',
  423. SessionEventSearchHit: 'session-query.md',
  424. SessionEventSearchPage: 'session-query.md',
  425. SessionEventSearchRequest: 'session-query.md',
  426. SessionEventTrace: 'session-query.md',
  427. SessionEventTraceObservation: 'session-query.md',
  428. SessionEventTraceRequest: 'session-query.md',
  429. SessionEventWindow: 'session-query.md',
  430. SessionLineageTrace: 'session-query.md',
  431. SessionObservation: 'session-query.md',
  432. SessionObservationOptions: 'session-query.md',
  433. SessionRecord: 'session-query.md',
  434. SessionResultFilter: 'session-query.md',
  435. SessionSearchExecContext: 'session-query.md',
  436. SessionSearchHit: 'session-query.md',
  437. SessionSearchPage: 'session-query.md',
  438. SessionSearchRequest: 'session-query.md',
  439. SessionTitleObservation: 'session-query.md',
  440. SessionTitleObservationResult: 'session-query.md',
  441. SessionTitleProvider: 'session-title.md',
  442. SessionTitleSnapshot: 'session-title.md',
  443. SkillCatalogSnapshot: 'skills.md',
  444. SkillDefinition: 'skills.md',
  445. SkillLookupOptions: 'skills.md',
  446. SkillProvider: 'skills.md',
  447. SkillProviderObservation: 'skills.md',
  448. SkillRegistration: 'skills.md',
  449. SkillViewOptions: 'skills.md',
  450. SkillSummary: 'skills.md',
  451. SaveTextSpill: 'spill.md',
  452. SpillRef: 'spill.md',
  453. ContinuableCreateRequest: 'subagent.md',
  454. ContinuableCreateSpec: 'subagent.md',
  455. ContinuableSetupContribution: 'subagent.md',
  456. ContinuableStart: 'subagent.md',
  457. ContinuableStartSpec: 'subagent.md',
  458. CoordinatorMessageSource: 'subagent.md',
  459. SubagentDescendantListEntry: 'subagent.md',
  460. SubagentFollowupOptions: 'subagent.md',
  461. SubagentInterruptAuthority: 'subagent.md',
  462. SubagentListEntry: 'subagent.md',
  463. SubagentProvider: 'subagent.md',
  464. SubagentReportDelivery: 'subagent.md',
  465. SubagentReportMessageSource: 'subagent.md',
  466. SubagentReportOptions: 'subagent.md',
  467. SubagentRun: 'subagent.md',
  468. SubagentRuntime: 'subagent.md',
  469. SubagentStartRequest: 'subagent.md',
  470. AssembleContext: 'system-prompt.md',
  471. PromptContext: 'system-prompt.md',
  472. PromptSection: 'system-prompt.md',
  473. SystemPrompt: 'system-prompt.md',
  474. ToolProviderResult: 'system-prompt.md',
  475. JobDoneListener: 'jobs.md',
  476. JobId: 'jobs.md',
  477. JobRead: 'jobs.md',
  478. JobSnapshot: 'jobs.md',
  479. JobStart: 'jobs.md',
  480. JobsChangedListener: 'jobs.md',
  481. CreateTeamTaskRequest: 'agent-team.md',
  482. SendTeamMessageRequest: 'agent-team.md',
  483. SendTeamMessageResult: 'agent-team.md',
  484. SpawnTeammateRequest: 'agent-team.md',
  485. SpawnTeammateResult: 'agent-team.md',
  486. TeamId: 'agent-team.md',
  487. TeamMemberView: 'agent-team.md',
  488. TeamMembership: 'agent-team.md',
  489. TeamTaskId: 'agent-team.md',
  490. TeamTaskView: 'agent-team.md',
  491. TeamWaitResult: 'agent-team.md',
  492. UpdateTeamTaskRequest: 'agent-team.md',
  493. TokenMeasurement: 'token-meter.md',
  494. CodeDispatchLog: 'tools.md',
  495. PostToolDecision: 'tools.md',
  496. PreToolDecision: 'tools.md',
  497. ToolDefinition: 'tools.md',
  498. ToolExecution: 'tools.md',
  499. ToolDispatchExecution: 'tools.md',
  500. ToolExecutionInput: 'tools.md',
  501. ToolExecutionMode: 'tools.md',
  502. ToolExecutionResult: 'tools.md',
  503. ToolExecutionToken: 'tools.md',
  504. ToolGuard: 'tools.md',
  505. ToolPresentationMode: 'tools.md',
  506. ToolRuntime: 'tools.md',
  507. ToolRestriction: 'tools.md',
  508. ToolSchema: 'tools.md',
  509. SettingsNamespace: 'settings.md',
  510. SettingsRegisterOptions: 'settings.md',
  511. SettingsScope: 'settings.md',
  512. SettingsDescriptor: 'settings.md',
  513. SettingsPathOp: 'settings.md',
  514. SettingsDescribeOptions: 'settings.md',
  515. SettingsUpdateSource: 'settings.md',
  516. AuthorizationEntry: 'credentials.md',
  517. AuthorizationFlow: 'credentials.md',
  518. AuthorizationInteraction: 'credentials.md',
  519. AuthorizationMethod: 'credentials.md',
  520. AuthorizationNotice: 'credentials.md',
  521. AuthorizationOutcome: 'credentials.md',
  522. AuthorizationPrompt: 'credentials.md',
  523. AuthorizationRequest: 'credentials.md',
  524. AuthorizationSession: 'credentials.md',
  525. AuthorizationSettlement: 'credentials.md',
  526. AuthorizationStatus: 'credentials.md',
  527. CredentialRef: 'credentials.md',
  528. CredentialKey: 'credentials.md',
  529. CredentialInfo: 'credentials.md',
  530. CredentialRecord: 'credentials.md',
  531. CredentialRecordEntry: 'credentials.md',
  532. CredentialRecordInfo: 'credentials.md',
  533. ResolvedCredential: 'credentials.md',
  534. AskUserQuestionAnswer: 'user-questions.md',
  535. AskUserQuestionRequest: 'user-questions.md',
  536. UserQuestionProvider: 'user-questions.md',
  537. WebFetchProvider: 'web.md',
  538. WebFetchRequest: 'web.md',
  539. WebFetchResult: 'web.md',
  540. WebSearchProvider: 'web.md',
  541. WebSearchRequest: 'web.md',
  542. WebSearchResult: 'web.md',
  543. WorkflowRun: 'workflow.md',
  544. VerifiedWebhookDelivery: 'webhook.md',
  545. WebhookRule: 'webhook.md',
  546. PresetOption: 'permission-presets.md',
  547. PresetSpec: 'permission-presets.md',
  548. InvariantInstaller: 'invariants.md',
  549. WebRoute: 'web-server.md',
  550. IndexInjection: 'web-server.md',
  551. StorageBackend: 'storage.md',
  552. StorageForms: 'storage.md',
  553. Domain: 'storage.md',
  554. DomainSpec: 'storage.md',
  555. DomainChanged: 'storage.md',
  556. DomainFacility: 'storage.md',
  557. Workspace: 'workspace.md',
  558. WorkspaceArchiveSessionRequest: 'workspace.md',
  559. WorkspaceArchiveValue: 'workspace.md',
  560. WorkspaceCreateRequest: 'workspace.md',
  561. WorkspaceCreateValue: 'workspace.md',
  562. WorkspaceDeleteRequest: 'workspace.md',
  563. WorkspaceDeleteValue: 'workspace.md',
  564. WorkspaceFollowFrame: 'workspace.md',
  565. WorkspaceId: 'workspace.md',
  566. WorkspaceInsertBeforeRequest: 'workspace.md',
  567. WorkspaceInsertSessionBeforeRequest: 'workspace.md',
  568. WorkspaceOrderValue: 'workspace.md',
  569. WorkspaceRenameRequest: 'workspace.md',
  570. WorkspaceValue: 'workspace.md',
  571. ClientArtifactBaseline: 'client-modules.md',
  572. WebBootGraph: 'client-modules.md',
  573. SessionTelemetryRecord: 'session-telemetry.md',
  574. WorkflowRunInfo: 'workflow.md',
  575. WorkflowStartRequest: 'workflow.md',
  576. ProjectionDefinition: 'session-projection.md',
  577. SessionProjectionMap: 'session-projection.md',
  578. SessionProjectionStateMap: 'session-projection.md',
  579. ProjectionChangeListener: 'session-projection.md',
  580. ProjectionSnapshot: 'session-projection.md',
  581. ProjectionCheckpoint: 'session-projection.md',
  582. DirectoryPickerCapability: 'workspace.md',
  583. TypertContribution: 'invariants.md',
  584. TypertRemoteEventSource: 'typert.md',
  585. TypertFace: 'invariants.md',
  586. TypertPackageFilter: 'invariants.md',
  587. TypertPackageRecord: 'invariants.md',
  588. TypertSchemaFilter: 'invariants.md',
  589. TypertSchemaRecord: 'invariants.md',
  590. }
  591. /** TypeScript lib and pinned framework types with no repository-owned data page. */
  592. export const FOUNDATION_TYPE_NAMES: ReadonlySet<string> = new Set([
  593. 'AbortSignal',
  594. 'AsyncIterable',
  595. 'Context',
  596. 'Error',
  597. 'EntryTree',
  598. 'Exclude',
  599. 'Extract',
  600. 'Map',
  601. 'NonNullable',
  602. 'Omit',
  603. 'Partial',
  604. 'Pick',
  605. 'Promise',
  606. 'Record',
  607. 'Readonly',
  608. 'Uint8Array',
  609. ])
  610. /** Project types deliberately documented outside the subsystems catalog. */
  611. export const TYPE_LINK_EXEMPTIONS: Readonly<Record<string, string>> = {
  612. z: 'schemastery schema constructor is owned by vendor/schemastery (vendored upstream)',
  613. BeginCommandRequest: 'event-local request contract is owned by packages/client/ui-input-trigger/src/types.ts',
  614. InsertReferenceRequest: 'event-local request contract is owned by packages/client/ui-input-trigger/src/types.ts',
  615. ConsumeTokenRequest: 'event-local request contract is owned by packages/client/ui-input-trigger/src/types.ts',
  616. InsertTextRequest: 'event-local request contract is owned by packages/client/ui-input-trigger/src/types.ts',
  617. AgentHandle: 'agent ownership handle is owned by packages/core/agent/README.md',
  618. AgentPreset: 'discovered preset record is owned by packages/preset/agent-presets/README.md',
  619. PresetMetadata: 'preset display text is owned by packages/preset/agent-presets/README.md',
  620. BashEnvContributor: 'service-local extension type is owned by packages/shell/tool-bash/src/index.ts',
  621. BashEnvVariableInfo: 'service-local metadata type is owned by packages/shell/tool-bash/src/index.ts',
  622. CompactionAgentContext: 'compaction service input is owned by packages/compaction/compaction/src/index.ts',
  623. ManualCompactAgentContext: 'manual compaction service input is owned by packages/compaction/compaction/src/index.ts',
  624. ClientResponse: 'wire response message is owned by packages/host/apiproxy/src/api/rpc.ts',
  625. ApprovalRequestId: 'dynamic Plugin approval identity is owned by packages/extensions/cordis-host-runner/src/types.ts',
  626. CordisErrorDetails: 'Cordis runtime error payload is owned by packages/extensions/cordis-host-runner/src/types.ts',
  627. CordisInspectPlatform: 'Cordis inspect platform identity is owned by packages/extensions/cordis-host-runner/src/types.ts',
  628. CordisInspectProviderManifest: 'Cordis inspect provider manifest is owned by packages/extensions/cordis-host-runner/src/types.ts',
  629. CordisInspectProviderView: 'Cordis inspect provider view is owned by packages/extensions/cordis-host-runner/src/types.ts',
  630. CordisInspectQueryRequest: 'Cordis inspect transport payload is owned by packages/extensions/cordis-host-runner/src/types.ts',
  631. CordisInspectQueryResolution: 'Cordis inspect query result is owned by packages/extensions/cordis-host-runner/src/types.ts',
  632. CordisInspectQueryResolved: 'Cordis inspect transport payload is owned by packages/extensions/cordis-host-runner/src/types.ts',
  633. CordisInspectRequestId: 'Cordis inspect request identity is owned by packages/extensions/cordis-host-runner/src/types.ts',
  634. CordisInspectResolveAck: 'Cordis inspect resolution acknowledgement is owned by packages/extensions/cordis-host-runner/src/types.ts',
  635. CordisDynamicPackageId: 'dynamic Package identity is owned by packages/extensions/cordis-host-runner/src/types.ts',
  636. CordisDynamicPluginId: 'dynamic Plugin identity is owned by packages/extensions/cordis-host-runner/src/types.ts',
  637. CordisDynamicPluginRunId: 'dynamic Plugin run identity is owned by packages/extensions/cordis-host-runner/src/types.ts',
  638. CordisDynamicRunMode: 'dynamic Plugin activation mode is owned by packages/extensions/cordis-host-runner/src/types.ts',
  639. DynamicCordisClientSource: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  640. DynamicCordisDefineReceipt: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  641. DynamicCordisDefineRequest: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  642. DynamicCordisHostHalfResult: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  643. DynamicCordisInventoryRow: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  644. DynamicCordisInvokeResult: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  645. DynamicCordisPackageInspection: 'dynamic Package source inspection is owned by packages/extensions/cordis-host-runner/src/registry.ts',
  646. DynamicCordisPluginInspection: 'dynamic Plugin inspection is owned by packages/extensions/cordis-host-runner/src/registry.ts',
  647. DynamicCordisRequestResolved: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  648. DynamicCordisRetracted: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  649. DynamicCordisRunRequest: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  650. DynamicCordisPackage: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  651. DynamicCordisReference: 'dynamic Plugin reference is owned by packages/extensions/cordis-host-runner/src/registry.ts',
  652. DynamicCordisRenderFailure: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  653. DynamicCordisResolveAck: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  654. DynamicCordisRunResolution: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  655. DynamicCordisRunResponse: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  656. DynamicCordisSnapshotRow: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  657. DynamicCordisStopResponse: 'dynamic Plugin stop result is owned by packages/extensions/cordis-host-runner/src/types.ts',
  658. DynamicCordisUndefineReceipt: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  659. HostCordisInspectProviderRegistration: 'Host inspect provider registration is owned by packages/extensions/cordis-host-runner/src/inspect-registry.ts',
  660. DomainImpl: 'domain implementation contract is owned by packages/storage/storage-domain/README.md',
  661. CommandExecution: 'executor return contract is owned by packages/interaction/commands/src/index.ts',
  662. 'z.core.JSONSchema.BaseSchema': 'zod projection output is owned by the zod v4 API',
  663. 'z.core.ToJSONSchemaParams': 'zod projection parameters are owned by the zod v4 API',
  664. TypertDisposer: 'Typert lifecycle contract is owned by packages/typert/protocol/README.md',
  665. InvokeRemoteRequest: 'gateway invocation contract is owned by packages/api/gateway/README.md',
  666. LocaleDict: 'service-local dictionary fields are owned by packages/client/i18n/src/index.ts',
  667. ThemeTokens: 'service-local token dictionary is owned by packages/client/ui-theme/src/index.ts',
  668. Translate: 'service-local bound translator is owned by packages/client/i18n/src/index.ts',
  669. WebUpgradeRoute:
  670. 'upgrade route registration contract is owned by packages/host/webserver/src/index.ts',
  671. InvariantRegistration: 'service-local lifecycle handle is owned by packages/runtime-diagnostics/invariants/README.md',
  672. JsonValue: 'JSON value union is owned by packages/core/session/src/json.ts',
  673. KnobState: 'projection unit state fields are owned by packages/interaction/permission-presets/README.md',
  674. PermissionSelect: 'permissions projection payload is owned by packages/interaction/permission-presets/src/types.ts',
  675. PromptAssembly: 'assembly result is owned by packages/core/system-prompt/README.md',
  676. RequestRunId: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts',
  677. RpcReceipt: 'carrier-layer receipt is owned by packages/host/apiproxy/src/api/rpc.ts',
  678. Sandbox: 'external E2B SDK handle is owned by packages/e2b/e2b/README.md',
  679. SessionForkSource: 'service-local fork input is owned by packages/core/session/src/index.ts',
  680. SubagentRunEndInfo: 'event payload contract is owned by packages/subagent/subagent/src/types.ts',
  681. SubagentRunInfo: 'event payload contract is owned by packages/subagent/subagent/src/types.ts',
  682. WorkflowAgentEndInfo: 'event-local snapshot is owned by packages/workflow/workflow/src/index.ts',
  683. WorkflowAgentInfo: 'event-local snapshot is owned by packages/workflow/workflow/src/index.ts',
  684. WorkflowResultInfo: 'event-local snapshot is owned by packages/workflow/workflow/src/index.ts',
  685. }
  686. /** Repository data policy consumed by the Cordis catalog projector. */
  687. export const CORDIS_CATALOG_POLICY: CordisCatalogPolicy = {
  688. linkedTypePages: LINK_MAP,
  689. foundationTypeNames: FOUNDATION_TYPE_NAMES,
  690. typeLinkExemptions: TYPE_LINK_EXEMPTIONS,
  691. runtimeServiceExclusions: new Set(['cordisInspect', 'dynamicCordisRunner']),
  692. runtimeServices: [{
  693. key: 'timer',
  694. type: 'TimerService',
  695. abstract: false,
  696. doc: 'Disposable timer helpers mixed into Cordis contexts.',
  697. source: 'vendor/timer/src/index.ts:12',
  698. methods: [
  699. {
  700. signature: 'timeout(callback: () => void, delay: number): () => void',
  701. jsDoc: '/** Run a callback once and return its disposer. */',
  702. },
  703. {
  704. signature: 'timeout(delay: number): Promise<void>',
  705. jsDoc: '/** Resolve after a delay; disposal rejects the pending promise. */',
  706. },
  707. {
  708. signature: 'interval(callback: () => void, delay: number): () => void',
  709. jsDoc: '/** Run a callback repeatedly and return its disposer. */',
  710. },
  711. {
  712. signature: 'interval<R = any>(delay: number): AsyncIterableIterator<void, R, void>',
  713. jsDoc: '/** Return an async iterator of timer ticks. */',
  714. },
  715. {
  716. signature: 'throttle<F extends (...args: any[]) => void>(callback: F, delay: number, noTrailing?: boolean): F & { dispose: () => void }',
  717. jsDoc: '/** Return a throttled function whose timer is disposed with the current fiber. */',
  718. },
  719. {
  720. signature: 'debounce<F extends (...args: any[]) => void>(callback: F, delay: number): F & { dispose: () => void }',
  721. jsDoc: '/** Return a debounced function whose timer is disposed with the current fiber. */',
  722. },
  723. ],
  724. }],
  725. inheritedEvents: [
  726. { name: 'internal/plugin', summary: 'A plugin fiber was created.', source: 'vendor/cordis/src/events.ts:328' },
  727. { name: 'internal/status', summary: 'A fiber changed lifecycle state.', source: 'vendor/cordis/src/events.ts:330' },
  728. { name: 'internal/service', summary: 'Interception hook for a service binding (no core producer).', source: 'vendor/cordis/src/events.ts:332' },
  729. { name: 'internal/update', summary: 'Waterfall: a fiber config update is being applied.', source: 'vendor/cordis/src/events.ts:334' },
  730. { name: 'internal/get', summary: 'Waterfall: a service is being read from the store.', source: 'vendor/cordis/src/events.ts:336' },
  731. { name: 'internal/set', summary: 'Waterfall: a service is being written to the store.', source: 'vendor/cordis/src/events.ts:338' },
  732. { name: 'internal/listener', summary: 'A listener was registered.', source: 'vendor/cordis/src/events.ts:340' },
  733. { name: 'internal/dispatch', summary: 'An event is being dispatched to listeners.', source: 'vendor/cordis/src/events.ts:342' },
  734. { name: 'hmr/change', summary: 'A watched source file changed on disk.', source: 'vendor/hmr/src/index.ts:20' },
  735. { name: 'hmr/reload', summary: 'Plugins are being reloaded after a change.', source: 'vendor/hmr/src/index.ts:21' },
  736. { name: 'exit', summary: 'The process is exiting on a signal.', source: 'vendor/loader/src/index.ts:23' },
  737. { name: 'loader/config-update', summary: 'The loader config tree changed.', source: 'vendor/loader/src/index.ts:24' },
  738. { name: 'loader/entry-init', summary: 'A config entry is being initialized.', source: 'vendor/loader/src/index.ts:25' },
  739. { name: 'loader/partial-dispose', summary: 'An entry is being partially disposed on reload.', source: 'vendor/loader/src/index.ts:26' },
  740. { name: 'loader/patch-context', summary: 'A context is being patched during a reload.', source: 'vendor/loader/src/index.ts:27' },
  741. ],
  742. inheritedServices: [
  743. { name: 'ctx.on / ctx.once', summary: 'Register an event listener (disposable).', source: 'vendor/cordis/src/events.ts:34' },
  744. { 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' },
  745. { name: 'ctx.plugin / ctx.inject', summary: 'Load a plugin / declare required services.', source: 'vendor/cordis/src/registry.ts:164' },
  746. { name: 'ctx.effect', summary: 'Register a disposable side effect tied to the fiber.', source: 'vendor/cordis/src/fiber.ts:9' },
  747. { 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' },
  748. { name: 'ctx.extend / ctx.isolate / ctx.intercept', summary: 'Derive a child context (scoped services / isolation / interception).', source: 'vendor/cordis/src/context.ts:42' },
  749. { 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' },
  750. { 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' },
  751. { name: 'ctx.loader', summary: 'The config Loader that booted the app (present under the loader).', source: 'vendor/loader/src/index.ts:30' },
  752. { name: 'ctx.hmr', summary: 'The hot-module-reload watcher (present under the hmr plugin).', source: 'vendor/hmr/src/index.ts:15' },
  753. ],
  754. }
  755. /**
  756. * Splice a page's generated Cordis API region into its Markdown content.
  757. * The page must contain exactly one `cordis-surface` marker region (the markers are
  758. * part of the hand-owned page skeleton once, then owned by the generator);
  759. * zero or several is a partition error the caller reports with the page path.
  760. * The match is on THIS generator's exact markers, not the generic region
  761. * grammar, so a page carrying only some other generator's region fails loud
  762. * instead of having that region overwritten.
  763. * @param content - the page's current full Markdown text.
  764. * @param region - the freshly rendered marker-delimited region.
  765. * @returns the page text with the region replaced.
  766. */
  767. export function spliceRegion(content: string, region: string): string {
  768. const lines = content.split('\n')
  769. const begins = lines.flatMap((line, index) => (line === REGION_BEGIN ? [index] : []))
  770. const ends = lines.flatMap((line, index) => (line === REGION_END ? [index] : []))
  771. if (begins.length !== 1 || ends.length !== 1) {
  772. throw new Error(`expected exactly 1 cordis-surface region, found ${begins.length} BEGIN/${ends.length} END; add the BEGIN/END cordis-surface markers once`)
  773. }
  774. const begin = begins[0] ?? -1
  775. const end = ends[0] ?? -1
  776. if (end < begin) throw new Error('cordis-surface END marker precedes its BEGIN')
  777. return [...lines.slice(0, begin), ...region.split('\n'), ...lines.slice(end + 1)].join('\n')
  778. }
  779. /** The declared-vs-rendered inputs {@link walkPartitionProblems} judges. */
  780. export interface WalkPartitionInput {
  781. /** Service key → source pointer, as the rendering projection produced them. */
  782. readonly renderedKeys: ReadonlyMap<string, string>
  783. /** Event scopes the rendering projection produced. */
  784. readonly renderedScopes: ReadonlySet<string>
  785. /** Event names the rendering projection produced. */
  786. readonly renderedEventNames: ReadonlySet<string>
  787. /** Context key → first declaring file, from the independent AST scan. */
  788. readonly declaredKeys: ReadonlyMap<string, string>
  789. /** Event name → first declaring file, from the independent AST scan. */
  790. readonly declaredEvents: ReadonlyMap<string, string>
  791. }
  792. /** The curated partition maps {@link walkPartitionProblems} enforces. */
  793. export interface WalkPartitionMaps {
  794. readonly servicePage: Readonly<Record<string, string>>
  795. readonly serviceWalkExemptions: Readonly<Record<string, string>>
  796. readonly eventScopePage: Readonly<Record<string, string>>
  797. readonly eventWalkExemptions: Readonly<Record<string, string>>
  798. }
  799. /** Project paired Markdown destinations in one generated region to the page's locale. */
  800. export function localizePageRegion(region: string, pageRel: string, scanRoot: string = root): string {
  801. if (!pageRel.endsWith('.zh.md')) return region
  802. const manifest = parseTranslationPairingManifest(
  803. readFileSync(resolve(scanRoot, 'scripts/translation-pairing.manifest.json'), 'utf8'),
  804. )
  805. return rewriteTranslationLinkLocales(region, {
  806. repoRoot: scanRoot,
  807. sourcePath: pageRel,
  808. isTranslationPairSource: translationPairSourcePredicate(manifest),
  809. }).content
  810. }
  811. /**
  812. * Judge the rendered API and the independent AST scan against the curated
  813. * partition maps, fail-closed in both directions for services AND events: a
  814. * rendered key/scope must be mapped to a page, a mapped key/scope must still
  815. * render, and — the backstop — a DECLARED key/event the projection cannot see
  816. * must carry a named walk exemption (a rendered one must not). A third
  817. * direction guards the scan itself: everything rendered must also be declared
  818. * to the scan, so a scan blind spot cannot decay silently. Pure so the
  819. * acceptance paths are provable without running the projection.
  820. * @param input - rendered API plus the declared-key/event scans.
  821. * @param maps - the curated page maps and walk exemptions.
  822. * @returns one message per violation, empty when the partition holds.
  823. */
  824. export function walkPartitionProblems(input: WalkPartitionInput, maps: WalkPartitionMaps): string[] {
  825. const problems: string[] = []
  826. for (const [key, source] of input.renderedKeys) {
  827. 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.`)
  828. }
  829. for (const scope of [...input.renderedScopes].sort()) {
  830. 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.`)
  831. }
  832. for (const key of Object.keys(maps.servicePage)) {
  833. if (!input.renderedKeys.has(key)) problems.push(`SERVICE_PAGE maps 'ctx.${key}' but the projection discovers no such service; remove the stale entry.`)
  834. }
  835. for (const scope of Object.keys(maps.eventScopePage)) {
  836. if (!input.renderedScopes.has(scope)) problems.push(`EVENT_SCOPE_PAGE maps '${scope}/*' but the projection discovers no such scope; remove the stale entry.`)
  837. }
  838. // The rendering projection only sees a Context key it can resolve to a
  839. // documented service class. The independent scan reads EVERY Context merge
  840. // so a key the projection cannot render must either be rendered (mapped) or
  841. // carry a named SERVICE_WALK_EXEMPTIONS reason — never vanish silently.
  842. for (const [key, rel] of input.declaredKeys) {
  843. const rendered = input.renderedKeys.has(key)
  844. const exempt = Object.hasOwn(maps.serviceWalkExemptions, key)
  845. if (!rendered && !exempt) {
  846. 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.`)
  847. }
  848. if (rendered && exempt) problems.push(`ctx.${key} is rendered by the projection but still listed in SERVICE_WALK_EXEMPTIONS; remove the stale exemption.`)
  849. }
  850. for (const key of Object.keys(maps.serviceWalkExemptions)) {
  851. if (!input.declaredKeys.has(key)) problems.push(`SERVICE_WALK_EXEMPTIONS names 'ctx.${key}' but no Context merge declares it; remove the stale exemption.`)
  852. }
  853. // The event mirror of the service backstop: the projection walks only files
  854. // reachable from host-face package exports, so a client-face or unreachable
  855. // Events merge would otherwise vanish without a trace.
  856. for (const [name, rel] of input.declaredEvents) {
  857. const rendered = input.renderedEventNames.has(name)
  858. const exempt = Object.hasOwn(maps.eventWalkExemptions, name)
  859. if (!rendered && !exempt) {
  860. 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.`)
  861. }
  862. if (rendered && exempt) problems.push(`event '${name}' is rendered by the projection but still listed in EVENT_WALK_EXEMPTIONS; remove the stale exemption.`)
  863. }
  864. for (const name of Object.keys(maps.eventWalkExemptions)) {
  865. if (!input.declaredEvents.has(name)) problems.push(`EVENT_WALK_EXEMPTIONS names '${name}' but no Events merge declares it; remove the stale exemption.`)
  866. }
  867. // Self-check the scan itself: everything the projection renders is declared
  868. // in a Context/Events merge the scan must also reach, so a rendered key or
  869. // event the scan cannot see means the SCAN regressed (glob, prefilter, or
  870. // block walk) — a partial blind spot that exemption staleness alone would
  871. // never appear.
  872. for (const key of input.renderedKeys.keys()) {
  873. 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.`)
  874. }
  875. for (const name of input.renderedEventNames) {
  876. 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.`)
  877. }
  878. return problems
  879. }
  880. /**
  881. * Compute every generated artifact: the inherited-tier page, the model-facing
  882. * runtime API module, plus, per mapped subsystems page, the pair's two updated
  883. * documents with the injected region. Fail-loud partition checks live here: an
  884. * unmapped service/event scope, a mapping whose page file does not exist, a
  885. * curated entry whose key/scope the projection no longer discovers, a declared
  886. * Context key or Events member the projection cannot see without a named walk
  887. * exemption, and a mapped page missing its markers are all aggregated errors.
  888. * @returns `[repo-relative path, exact content]` for every generated artifact.
  889. */
  890. export function computeOutputs(): [string, string][] {
  891. const { projector, model } = projectCordisCatalog(root, CORDIS_CATALOG_POLICY)
  892. const services = [...model.services]
  893. const events = [...model.events]
  894. const declaredKeys = new Map<string, string>()
  895. const declaredEvents = new Map<string, string>()
  896. for (const { rel, sf, body } of contextMergeFiles(root, ['packages/*/*/src/**/*.ts', 'packages/*/*/src/**/*.tsx'])) {
  897. for (const key of contextKeyMap(body, sf).keys()) {
  898. if (!declaredKeys.has(key)) declaredKeys.set(key, rel)
  899. }
  900. for (const name of eventNameList(body, sf)) {
  901. if (!declaredEvents.has(name)) declaredEvents.set(name, rel)
  902. }
  903. }
  904. const problems = walkPartitionProblems({
  905. renderedKeys: new Map(services.map(s => [s.key, s.source])),
  906. renderedScopes: new Set(events.map(e => e.scope)),
  907. renderedEventNames: new Set(events.map(e => e.name)),
  908. declaredKeys,
  909. declaredEvents,
  910. }, {
  911. servicePage: SERVICE_PAGE,
  912. serviceWalkExemptions: SERVICE_WALK_EXEMPTIONS,
  913. eventScopePage: EVENT_SCOPE_PAGE,
  914. eventWalkExemptions: EVENT_WALK_EXEMPTIONS,
  915. })
  916. if (problems.length > 0) throw new Error(`gen-cordis-catalog: ${problems.length} partition violation(s):\n${problems.map(p => ` ${p}`).join('\n')}`)
  917. const pages = [...new Set([...Object.values(SERVICE_PAGE), ...Object.values(EVENT_SCOPE_PAGE)])].sort()
  918. const outputs: [string, string][] = [
  919. [OUT_INHERITED, renderInheritedPage(CORDIS_CATALOG_POLICY)],
  920. [OUT_RUNTIME_API, projector.renderRuntimeApi(model)],
  921. ]
  922. for (const page of pages) {
  923. const region = renderPageRegion(
  924. page,
  925. services.filter(s => SERVICE_PAGE[s.key] === page),
  926. events.filter(e => EVENT_SCOPE_PAGE[e.scope] === page),
  927. CORDIS_CATALOG_POLICY,
  928. )
  929. for (const side of [page, page.replace(/\.md$/, '.zh.md')]) {
  930. const rel = `${SUBSYSTEMS_DIR}/${side}`
  931. const localizedRegion = localizePageRegion(region, rel)
  932. let current: string
  933. try {
  934. current = readFileSync(resolve(root, rel), 'utf8')
  935. } catch {
  936. // Both pair sides must exist before a region can be injected; the
  937. // pairing gate owns pair completeness, this generator names the miss.
  938. problems.push(`${rel}: mapped subsystems page does not exist.`)
  939. continue
  940. }
  941. try {
  942. outputs.push([rel, spliceRegion(current, localizedRegion)])
  943. } catch (error) {
  944. problems.push(`${rel}: ${error instanceof Error ? error.message : String(error)}`)
  945. }
  946. }
  947. }
  948. if (problems.length > 0) throw new Error(`gen-cordis-catalog: ${problems.length} page violation(s):\n${problems.map(p => ` ${p}`).join('\n')}`)
  949. return outputs
  950. }
  951. /**
  952. * Re-record a pair's `.i18n.yaml` after a region write ONLY when the write is
  953. * region-confined: both sides' region-stripped content must be byte-equal to
  954. * the region-stripped previous content whose hashes the record holds. The
  955. * caller supplies the previous bytes (read before writing); human-content
  956. * drift leaves the record untouched so the pairing gate still demands the
  957. * normal translation flow.
  958. * @param pageRel - repo-relative English page path (`docs/subsystems/x.md`).
  959. * @param before - pre-write bytes per repo-relative path.
  960. * @param scanRoot - repository root override for tests.
  961. * @returns true when the record was refreshed.
  962. */
  963. export function maybeRecordPair(pageRel: string, before: Map<string, Buffer>, scanRoot: string = root): boolean {
  964. const zhRel = pageRel.replace(/\.md$/, '.zh.md')
  965. const metaRel = pageRel.replace(/\.md$/, '.i18n.yaml')
  966. const metaAbs = resolve(scanRoot, metaRel)
  967. let meta: string
  968. try {
  969. meta = readFileSync(metaAbs, 'utf8')
  970. } catch {
  971. // No record yet: a brand-new pair is recorded by the author's --write
  972. // after review, never silently by regeneration.
  973. return false
  974. }
  975. // The record must contain exactly the two valid entries for THIS pair;
  976. // a malformed or renamed-key sidecar is the pairing gate's problem to
  977. // report, never something regeneration silently repairs into validity.
  978. const recorded = parsePairMeta(meta)
  979. const names = [pageRel, zhRel].map(rel => rel.split('/').at(-1) ?? rel)
  980. if (!recorded || recorded.size !== 2 || !names.every(name => recorded.has(name))) return false
  981. for (const rel of [pageRel, zhRel]) {
  982. const previous = before.get(rel)
  983. if (!previous) return false
  984. if (recorded.get(rel.split('/').at(-1) ?? rel) !== blobHash(previous)) return false
  985. const current = readFileSync(resolve(scanRoot, rel))
  986. const strippedBefore = partitionGeneratedRegions(previous.toString('utf8')).stripped
  987. const strippedAfter = partitionGeneratedRegions(current.toString('utf8')).stripped
  988. if (strippedBefore !== strippedAfter) return false
  989. }
  990. const source = readFileSync(resolve(scanRoot, pageRel))
  991. const zh = readFileSync(resolve(scanRoot, zhRel))
  992. writeFileSync(metaAbs, renderPairMeta(pageRel, blobHash(source), zhRel, blobHash(zh)))
  993. return true
  994. }
  995. /** CLI entry: default regenerates every artifact, `--check` fails if any is
  996. * stale. Guarded behind an entry-point check so importing this module for
  997. * tests neither regenerates the committed files nor calls process.exit.
  998. * @returns nothing; writes files or reports freshness through the process.
  999. */
  1000. export function main(): void {
  1001. const outputs: [string, string][] = [
  1002. ...computeOutputs(),
  1003. ...renderCordisCoreApiPages(),
  1004. ]
  1005. if (process.argv.includes('--check')) {
  1006. const stale: string[] = []
  1007. for (const [out, content] of outputs) {
  1008. let committed: string | null = null
  1009. try {
  1010. committed = readFileSync(resolve(root, out), 'utf8')
  1011. } catch {
  1012. // Only ENOENT (not yet generated) is expected; a present-but-unreadable
  1013. // file is not a state this repo produces. Either way the remedy is the
  1014. // same — regenerate — so treat a read failure as "stale".
  1015. committed = null
  1016. }
  1017. if (committed !== content) stale.push(out)
  1018. }
  1019. if (stale.length === 0) {
  1020. console.log(`gen-cordis-catalog: ${outputs.length} generated file(s)/region(s) are up to date.`)
  1021. process.exit(0)
  1022. }
  1023. console.error(`gen-cordis-catalog: stale — ${stale.join(', ')}. Run \`pnpm run gen-cordis-catalog\` and commit the result.`)
  1024. process.exit(1)
  1025. }
  1026. const before = new Map<string, Buffer>()
  1027. for (const [out] of outputs) {
  1028. try {
  1029. before.set(out, readFileSync(resolve(root, out)))
  1030. } catch {
  1031. // First generation of this artifact; nothing to guard, nothing to record.
  1032. }
  1033. }
  1034. let changedPages = 0
  1035. let recorded = 0
  1036. for (const [out, content] of outputs) {
  1037. const destination = resolve(root, out)
  1038. if (before.get(out)?.toString('utf8') === content) continue
  1039. mkdirSync(dirname(destination), { recursive: true })
  1040. writeFileSync(destination, content)
  1041. changedPages++
  1042. }
  1043. for (const page of [...new Set([...Object.values(SERVICE_PAGE), ...Object.values(EVENT_SCOPE_PAGE)])]) {
  1044. const rel = `${SUBSYSTEMS_DIR}/${page}`
  1045. const zhRel = rel.replace(/\.md$/, '.zh.md')
  1046. const wroteEither = [rel, zhRel].some((side) => {
  1047. const previous = before.get(side)
  1048. return previous !== undefined && previous.toString('utf8') !== readFileSync(resolve(root, side), 'utf8')
  1049. })
  1050. if (wroteEither && maybeRecordPair(rel, before)) recorded++
  1051. }
  1052. console.log(`gen-cordis-catalog: ${outputs.length} artifact(s) computed, ${changedPages} written, ${recorded} pair record(s) refreshed.`)
  1053. }
  1054. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  1055. main()
  1056. }