gen-cordis-catalog.ts 58 KB

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