@elevasis/sdk 1.44.3 → 1.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (259) hide show
  1. package/dist/cli.cjs +35026 -30226
  2. package/dist/index.d.ts +1786 -808
  3. package/dist/index.js +789 -739
  4. package/dist/node/index.d.ts +105 -181
  5. package/dist/node/index.js +2 -2
  6. package/dist/test-utils/index.d.ts +901 -359
  7. package/dist/test-utils/index.js +587 -824
  8. package/dist/worker/index.d.ts +12685 -0
  9. package/dist/worker/index.js +188 -216
  10. package/package.json +4 -7
  11. package/reference/_navigation.md +161 -22
  12. package/reference/_reference-manifest.json +228 -4
  13. package/reference/claude-config.md +8 -0
  14. package/reference/core/exports.mdx +2 -0
  15. package/reference/core/index.mdx +3 -3
  16. package/reference/examples/organization-model.ts +117 -111
  17. package/reference/index.mdx +4 -4
  18. package/reference/packages/core/src/business/README.md +4 -1
  19. package/reference/packages/core/src/content/README.md +19 -0
  20. package/reference/packages/core/src/organization-model/README.md +148 -149
  21. package/reference/packages/core/src/organization-model/readiness/README.md +42 -0
  22. package/reference/packages/ui/src/features/README.md +28 -28
  23. package/reference/rules/active-change-index.md +40 -54
  24. package/reference/rules/agent-runtime.md +81 -0
  25. package/reference/rules/agent-start-here.md +71 -163
  26. package/reference/rules/deployment.md +33 -10
  27. package/reference/rules/error-handling.md +26 -0
  28. package/reference/rules/execution.md +13 -0
  29. package/reference/rules/frontend.md +10 -3
  30. package/reference/rules/observability.md +9 -1
  31. package/reference/rules/operations.md +26 -17
  32. package/reference/rules/organization-model.md +74 -88
  33. package/reference/rules/organization-os.md +71 -88
  34. package/reference/rules/package-taxonomy.md +11 -2
  35. package/reference/rules/platform.md +13 -7
  36. package/reference/rules/shared-types.md +36 -0
  37. package/reference/rules/task-tracking.md +30 -5
  38. package/reference/rules/ui.md +145 -3
  39. package/reference/rules/vibe-intents.md +271 -0
  40. package/reference/rules/vibe.md +17 -243
  41. package/reference/scaffold/core/organization-graph.mdx +112 -99
  42. package/reference/scaffold/core/organization-model.mdx +231 -215
  43. package/reference/scaffold/operations/propagation-pipeline.md +16 -17
  44. package/reference/scaffold/operations/scaffold-maintenance.md +22 -20
  45. package/reference/scaffold/operations/workflow-recipes.md +72 -20
  46. package/reference/scaffold/recipes/add-a-feature.md +156 -146
  47. package/reference/scaffold/recipes/add-a-resource.md +123 -117
  48. package/reference/scaffold/recipes/customize-crm-actions.md +28 -13
  49. package/reference/scaffold/recipes/customize-knowledge-browser.md +52 -117
  50. package/reference/scaffold/recipes/customize-organization-model.md +161 -149
  51. package/reference/scaffold/recipes/extend-a-base-entity.md +156 -140
  52. package/reference/scaffold/recipes/extend-content.md +265 -0
  53. package/reference/scaffold/recipes/extend-crm.md +16 -11
  54. package/reference/scaffold/recipes/extend-lead-gen.md +37 -21
  55. package/reference/scaffold/recipes/gate-by-feature-or-admin.md +160 -118
  56. package/reference/scaffold/recipes/index.md +6 -3
  57. package/reference/scaffold/recipes/query-the-knowledge-graph.md +23 -23
  58. package/reference/scaffold/reference/contracts.md +30 -56
  59. package/reference/scaffold/reference/feature-registry.md +3 -0
  60. package/reference/scaffold/reference/glossary.md +4 -4
  61. package/reference/scaffold/reference/system-interface-capabilities.md +5 -4
  62. package/reference/scaffold/ui/composition-extensibility.mdx +271 -232
  63. package/reference/scaffold/ui/customization.md +2 -2
  64. package/reference/scaffold/ui/feature-flags-and-gating.md +14 -6
  65. package/reference/scaffold/ui/feature-shell.mdx +277 -62
  66. package/reference/scaffold/ui/recipes.md +229 -197
  67. package/reference/sdk/cli-management.mdx +166 -33
  68. package/reference/sdk/cli.mdx +90 -13
  69. package/reference/sdk/concepts.mdx +2 -0
  70. package/reference/sdk/define-builders.mdx +76 -0
  71. package/reference/sdk/deployment/command-center.mdx +6 -2
  72. package/reference/sdk/deployment/execution-reference.mdx +64 -186
  73. package/reference/sdk/deployment/index.mdx +2 -0
  74. package/reference/sdk/exports.mdx +4 -4
  75. package/reference/sdk/framework/agent.mdx +52 -116
  76. package/reference/sdk/framework/index.mdx +46 -65
  77. package/reference/sdk/framework/project-structure.mdx +150 -205
  78. package/reference/sdk/framework/tutorial-system.mdx +2 -2
  79. package/reference/sdk/human-in-the-loop.mdx +152 -0
  80. package/reference/sdk/index.mdx +6 -7
  81. package/reference/sdk/platform-tools/adapters-platform.mdx +3 -1
  82. package/reference/sdk/platform-tools/index.mdx +12 -0
  83. package/reference/sdk/platform-tools/type-safety.mdx +4 -0
  84. package/reference/sdk/project-deployment-spec.mdx +131 -0
  85. package/reference/sdk/resources/index.mdx +21 -7
  86. package/reference/sdk/resources/patterns.mdx +54 -24
  87. package/reference/sdk/resources/types.mdx +7 -4
  88. package/reference/sdk/templates/data-enrichment.mdx +7 -3
  89. package/reference/sdk/templates/email-sender.mdx +139 -135
  90. package/reference/sdk/templates/lead-scorer.mdx +5 -1
  91. package/reference/sdk/templates/pdf-generator.mdx +155 -151
  92. package/reference/sdk/templates/recurring-job.mdx +195 -189
  93. package/reference/sdk/templates/text-classifier.mdx +4 -0
  94. package/reference/sdk/templates/web-scraper.mdx +139 -135
  95. package/reference/spine/spine-primer.md +135 -96
  96. package/reference/ui/exports.mdx +1 -0
  97. package/reference/ui/index.mdx +14 -7
  98. package/dist/types/worker/adapters/anymailfinder.d.ts +0 -14
  99. package/dist/types/worker/adapters/apify.d.ts +0 -14
  100. package/dist/types/worker/adapters/approval.d.ts +0 -23
  101. package/dist/types/worker/adapters/attio.d.ts +0 -22
  102. package/dist/types/worker/adapters/clickup.d.ts +0 -22
  103. package/dist/types/worker/adapters/create-adapter.d.ts +0 -41
  104. package/dist/types/worker/adapters/crm.d.ts +0 -20
  105. package/dist/types/worker/adapters/dropbox.d.ts +0 -14
  106. package/dist/types/worker/adapters/email.d.ts +0 -25
  107. package/dist/types/worker/adapters/execution.d.ts +0 -22
  108. package/dist/types/worker/adapters/gmail.d.ts +0 -14
  109. package/dist/types/worker/adapters/google-sheets.d.ts +0 -14
  110. package/dist/types/worker/adapters/index.d.ts +0 -33
  111. package/dist/types/worker/adapters/instantly.d.ts +0 -14
  112. package/dist/types/worker/adapters/lead.d.ts +0 -28
  113. package/dist/types/worker/adapters/list.d.ts +0 -9
  114. package/dist/types/worker/adapters/llm.d.ts +0 -45
  115. package/dist/types/worker/adapters/millionverifier.d.ts +0 -14
  116. package/dist/types/worker/adapters/notification.d.ts +0 -28
  117. package/dist/types/worker/adapters/pdf.d.ts +0 -22
  118. package/dist/types/worker/adapters/projects.d.ts +0 -20
  119. package/dist/types/worker/adapters/resend.d.ts +0 -14
  120. package/dist/types/worker/adapters/scheduler.d.ts +0 -25
  121. package/dist/types/worker/adapters/signature-api.d.ts +0 -14
  122. package/dist/types/worker/adapters/storage.d.ts +0 -33
  123. package/dist/types/worker/adapters/stripe.d.ts +0 -14
  124. package/dist/types/worker/adapters/tomba.d.ts +0 -14
  125. package/dist/types/worker/index.d.ts +0 -60
  126. package/dist/types/worker/platform.d.ts +0 -90
  127. package/dist/types/worker/utils.d.ts +0 -9
  128. package/reference/claude-config/Overview.md +0 -230
  129. package/reference/claude-config/hooks/post-edit-validate.mjs +0 -98
  130. package/reference/claude-config/hooks/scaffold-registry-reminder.mjs +0 -187
  131. package/reference/claude-config/hooks/tool-failure-recovery.mjs +0 -73
  132. package/reference/claude-config/registries/graph-skills.json +0 -4
  133. package/reference/claude-config/registries/knowledge-flags.json +0 -154
  134. package/reference/claude-config/registries/skill-coverage.json +0 -20
  135. package/reference/claude-config/rules/active-change-index.md +0 -22
  136. package/reference/claude-config/rules/agent-start-here.md +0 -22
  137. package/reference/claude-config/rules/deployment.md +0 -22
  138. package/reference/claude-config/rules/error-handling.md +0 -22
  139. package/reference/claude-config/rules/execution.md +0 -22
  140. package/reference/claude-config/rules/frontend.md +0 -22
  141. package/reference/claude-config/rules/observability.md +0 -22
  142. package/reference/claude-config/rules/operations.md +0 -22
  143. package/reference/claude-config/rules/organization-model.md +0 -22
  144. package/reference/claude-config/rules/organization-os.md +0 -22
  145. package/reference/claude-config/rules/package-taxonomy.md +0 -22
  146. package/reference/claude-config/rules/platform.md +0 -22
  147. package/reference/claude-config/rules/shared-types.md +0 -22
  148. package/reference/claude-config/rules/task-tracking.md +0 -22
  149. package/reference/claude-config/rules/topbar-actions.md +0 -70
  150. package/reference/claude-config/rules/ui.md +0 -22
  151. package/reference/claude-config/rules/vibe.md +0 -22
  152. package/reference/claude-config/scripts/statusline-command.js +0 -18
  153. package/reference/claude-config/settings.json +0 -30
  154. package/reference/claude-config/skills/client/SKILL.md +0 -201
  155. package/reference/claude-config/skills/deploy/SKILL.md +0 -159
  156. package/reference/claude-config/skills/dsp/SKILL.md +0 -66
  157. package/reference/claude-config/skills/elevasis/SKILL.md +0 -251
  158. package/reference/claude-config/skills/explore/SKILL.md +0 -78
  159. package/reference/claude-config/skills/git-sync/SKILL.md +0 -166
  160. package/reference/claude-config/skills/om/SKILL.md +0 -475
  161. package/reference/claude-config/skills/om/operations/build.md +0 -237
  162. package/reference/claude-config/skills/om/operations/codify-level-a.md +0 -109
  163. package/reference/claude-config/skills/om/operations/codify-level-b.md +0 -159
  164. package/reference/claude-config/skills/om/operations/customers.md +0 -114
  165. package/reference/claude-config/skills/om/operations/features.md +0 -88
  166. package/reference/claude-config/skills/om/operations/goals.md +0 -123
  167. package/reference/claude-config/skills/om/operations/identity.md +0 -97
  168. package/reference/claude-config/skills/om/operations/labels.md +0 -110
  169. package/reference/claude-config/skills/om/operations/offerings.md +0 -114
  170. package/reference/claude-config/skills/om/operations/roles.md +0 -104
  171. package/reference/claude-config/skills/om/operations/scaffold.md +0 -163
  172. package/reference/claude-config/skills/om/operations/techStack.md +0 -38
  173. package/reference/claude-config/skills/project/SKILL.md +0 -1114
  174. package/reference/claude-config/skills/run-ui/SKILL.md +0 -73
  175. package/reference/claude-config/skills/save/SKILL.md +0 -183
  176. package/reference/claude-config/skills/setup/SKILL.md +0 -290
  177. package/reference/claude-config/skills/status/SKILL.md +0 -59
  178. package/reference/claude-config/skills/submit-request/SKILL.md +0 -180
  179. package/reference/claude-config/skills/sync/SKILL.md +0 -47
  180. package/reference/claude-config/skills/tutorial/SKILL.md +0 -259
  181. package/reference/claude-config/skills/tutorial/progress-template.md +0 -74
  182. package/reference/claude-config/skills/tutorial/technical.md +0 -1303
  183. package/reference/claude-config/skills/tutorial/vibe-coder.md +0 -890
  184. package/reference/claude-config/sync-notes/2026-04-22-git-sync-and-sync-notes.md +0 -27
  185. package/reference/claude-config/sync-notes/2026-04-22-lead-gen-deliverability-removal.md +0 -30
  186. package/reference/claude-config/sync-notes/2026-04-24-test-utils-and-template-tests.md +0 -73
  187. package/reference/claude-config/sync-notes/2026-04-24-ui-consolidation-and-sdk-cli-train.md +0 -86
  188. package/reference/claude-config/sync-notes/2026-04-25-auth-role-system-and-settings-roles.md +0 -55
  189. package/reference/claude-config/sync-notes/2026-04-27-crm-hitl-action-layer-cutover.md +0 -97
  190. package/reference/claude-config/sync-notes/2026-04-27-lead-gen-substrate-train.md +0 -112
  191. package/reference/claude-config/sync-notes/2026-04-29-crm-state-and-lead-gen-processing-status.md +0 -93
  192. package/reference/claude-config/sync-notes/2026-05-02-crm-ownership-next-action.md +0 -58
  193. package/reference/claude-config/sync-notes/2026-05-02-template-hardcode-workos-config.md +0 -56
  194. package/reference/claude-config/sync-notes/2026-05-04-elevasis-workspace.md +0 -71
  195. package/reference/claude-config/sync-notes/2026-05-04-knowledge-bundle.md +0 -83
  196. package/reference/claude-config/sync-notes/2026-05-04-template-skills-run-ui-and-tutorial.md +0 -59
  197. package/reference/claude-config/sync-notes/2026-05-05-list-builder.md +0 -42
  198. package/reference/claude-config/sync-notes/2026-05-06-crm-spine.md +0 -60
  199. package/reference/claude-config/sync-notes/2026-05-06-sdk-changes-release-train.md +0 -37
  200. package/reference/claude-config/sync-notes/2026-05-07-sdk-changes-release-train.md +0 -34
  201. package/reference/claude-config/sync-notes/2026-05-08-resource-governance-scaffold-guidance.md +0 -38
  202. package/reference/claude-config/sync-notes/2026-05-09-clients-domain.md +0 -32
  203. package/reference/claude-config/sync-notes/2026-05-09-command-system.md +0 -33
  204. package/reference/claude-config/sync-notes/2026-05-09-resource-governance-and-misc.md +0 -69
  205. package/reference/claude-config/sync-notes/2026-05-12-sdk-ready-release-train.md +0 -30
  206. package/reference/claude-config/sync-notes/2026-05-14-organization-model-ontology-refactor.md +0 -45
  207. package/reference/claude-config/sync-notes/2026-05-15-om-skill-rename-and-write-family.md +0 -52
  208. package/reference/claude-config/sync-notes/2026-05-17-sdk-boundary-consolidation.md +0 -33
  209. package/reference/claude-config/sync-notes/2026-05-20-om-define-helpers.md +0 -32
  210. package/reference/claude-config/sync-notes/2026-05-22-access-model-and-right-panel.md +0 -43
  211. package/reference/claude-config/sync-notes/2026-05-22-lead-gen-tenant-config.md +0 -40
  212. package/reference/claude-config/sync-notes/2026-05-22-org-model-multi-file-split.md +0 -61
  213. package/reference/claude-config/sync-notes/2026-05-23-branding-names-to-identity.md +0 -49
  214. package/reference/claude-config/sync-notes/2026-05-23-lead-gen-manage-access.md +0 -31
  215. package/reference/claude-config/sync-notes/2026-05-23-om-deployment-drift-detection.md +0 -42
  216. package/reference/claude-config/sync-notes/2026-05-23-om-full-model-deploy-contract.md +0 -33
  217. package/reference/claude-config/sync-notes/2026-05-23-ui-sdk-package-fixes.md +0 -37
  218. package/reference/claude-config/sync-notes/2026-05-24-platform-invite-router-core-baseline.md +0 -28
  219. package/reference/claude-config/sync-notes/2026-05-24-system-interface-readiness.md +0 -43
  220. package/reference/claude-config/sync-notes/2026-05-25-invitation-login-loader.md +0 -26
  221. package/reference/claude-config/sync-notes/2026-05-25-om-topbar-requests.md +0 -33
  222. package/reference/claude-config/sync-notes/2026-05-25-system-interface-profile-registry-and-substrate.md +0 -35
  223. package/reference/claude-config/sync-notes/2026-05-25-tenant-om-scaffold-cli.md +0 -49
  224. package/reference/claude-config/sync-notes/2026-05-25-vibe-operate-intent.md +0 -47
  225. package/reference/claude-config/sync-notes/2026-05-28-om-snapshot-sdk-workflow-config.md +0 -33
  226. package/reference/claude-config/sync-notes/2026-05-30-client-source-and-om-profiles.md +0 -39
  227. package/reference/claude-config/sync-notes/2026-06-02-knowledge-nested-group-routing.md +0 -27
  228. package/reference/claude-config/sync-notes/2026-06-02-nest-projects-under-platform.md +0 -45
  229. package/reference/claude-config/sync-notes/2026-06-03-skill-autogen-and-client-skill.md +0 -34
  230. package/reference/claude-config/sync-notes/2026-06-04-scaffold-registry-lane-severity.md +0 -34
  231. package/reference/claude-config/sync-notes/2026-06-05-appearance-app-mode-decouple.md +0 -29
  232. package/reference/claude-config/sync-notes/2026-06-05-ontology-endpoint-rename-and-knowledge-browser-ui.md +0 -86
  233. package/reference/claude-config/sync-notes/2026-06-06-om-build-systems-scaffold.md +0 -47
  234. package/reference/claude-config/sync-notes/2026-06-06-om-item-copy-references.md +0 -50
  235. package/reference/claude-config/sync-notes/2026-06-08-knowledge-base-page-not-found-fix.md +0 -76
  236. package/reference/claude-config/sync-notes/2026-06-09-agent-sessions-public-agent-chat-route.md +0 -75
  237. package/reference/claude-config/sync-notes/2026-06-09-sdk-cli-load-org-model-resolution.md +0 -42
  238. package/reference/claude-config/sync-notes/2026-06-12-agent-grants-visualizer-operations.md +0 -30
  239. package/reference/claude-config/sync-notes/2026-06-14-session-ux-and-project-cli-json.md +0 -33
  240. package/reference/claude-config/sync-notes/2026-06-14-shared-session-conversation-view.md +0 -26
  241. package/reference/claude-config/sync-notes/2026-06-15-session-chat-zero-wiring.md +0 -46
  242. package/reference/claude-config/sync-notes/2026-06-17-agent-session-ux-features.md +0 -34
  243. package/reference/claude-config/sync-notes/2026-06-25-shared-page-scroll-contract-guard.md +0 -52
  244. package/reference/claude-config/sync-notes/2026-06-26-leadgen-overview-om-telemetry.md +0 -47
  245. package/reference/claude-config/sync-notes/2026-07-21-agent-scaffold-hardening.md +0 -75
  246. package/reference/claude-config/sync-notes/2026-07-23-agent-session-memory.md +0 -49
  247. package/reference/claude-config/sync-notes/2026-07-23-workos-org-marker.md +0 -50
  248. package/reference/claude-config/sync-notes/2026-07-24-claude-5-models-and-session-surface-fixes.md +0 -116
  249. package/reference/claude-config/sync-notes/2026-07-27-agent-strict-output-and-turn-drift.md +0 -73
  250. package/reference/claude-config/sync-notes/2026-07-28-agent-reply-is-its-own-field.md +0 -84
  251. package/reference/claude-config/sync-notes/2026-07-30-login-screen-and-member-provisioning-state.md +0 -114
  252. package/reference/claude-config/sync-notes/2026-08-02-auth-guard-defaults-and-truncation-fix.md +0 -122
  253. package/reference/claude-config/sync-notes/2026-08-03-agent-prose-escape-normalization.md +0 -88
  254. package/reference/claude-config/sync-notes/2026-08-03-cli-gateway-errors-and-request-timeout.md +0 -120
  255. package/reference/claude-config/sync-notes/README.md +0 -43
  256. package/reference/sdk/framework/interaction-guidance.mdx +0 -182
  257. package/reference/sdk/framework/memory.mdx +0 -326
  258. package/reference/sdk/framework/resource-documentation.mdx +0 -90
  259. package/reference/sdk/roadmap.mdx +0 -164
package/dist/index.js CHANGED
@@ -576,10 +576,28 @@ z.record(z.string(), ActionSchema).refine((record) => Object.entries(record).eve
576
576
  message: "Each action entry id must match its map key"
577
577
  }).default({});
578
578
 
579
+ // ../core/src/organization-model/readiness/profile-registry.ts
580
+ var _builtInProfileValidators = /* @__PURE__ */ new Map();
581
+ function registerBuiltInReadinessProfile(profileId, registration) {
582
+ _builtInProfileValidators.set(profileId, registration);
583
+ }
584
+ function getBuiltInReadinessProfile(profileId) {
585
+ return _builtInProfileValidators.get(profileId);
586
+ }
587
+ var _interfaceMarkerResolvers = /* @__PURE__ */ new Map();
588
+ function interfaceMarkerKey(systemPath, interfaceKey) {
589
+ return `${systemPath}::${interfaceKey}`;
590
+ }
591
+ function registerReadinessInterfaceMarker(systemPath, interfaceKey, resolver) {
592
+ _interfaceMarkerResolvers.set(interfaceMarkerKey(systemPath, interfaceKey), resolver);
593
+ }
594
+ function resolveReadinessInterfaceMarker(model, systemPath, interfaceKey) {
595
+ return _interfaceMarkerResolvers.get(interfaceMarkerKey(systemPath, interfaceKey))?.(model);
596
+ }
597
+
579
598
  // ../core/src/organization-model/domains/systems.ts
580
599
  var SystemKindSchema = z.enum(["product", "operational", "platform", "diagnostic"]).meta({ label: "System kind", color: "blue" });
581
600
  var SystemLifecycleSchema = z.enum(["draft", "beta", "active", "deprecated", "archived"]).meta({ label: "Lifecycle", color: "teal" });
582
- var SystemStatusSchema = z.enum(["active", "deprecated", "archived"]).meta({ label: "Status", color: "teal" });
583
601
  var SystemIdSchema = ModelIdSchema;
584
602
  var SystemPathSchema = z.string().trim().min(1).regex(
585
603
  /^[a-z0-9][a-z0-9-]*(?:\.[a-z0-9][a-z0-9-]*)*$/,
@@ -593,8 +611,7 @@ z.string().trim().min(1).max(200).regex(
593
611
  var SystemUiSchema = z.object({
594
612
  path: PathSchema,
595
613
  surfaces: ReferenceIdsSchema,
596
- icon: IconNameSchema.optional(),
597
- order: z.number().int().optional()
614
+ icon: IconNameSchema.optional()
598
615
  });
599
616
  var SystemInterfaceKeySchema = ModelIdSchema;
600
617
  var SystemInterfaceLifecycleSchema = z.enum(["draft", "active", "disabled", "deprecated", "archived"]).meta({ label: "System interface lifecycle", color: "teal" });
@@ -623,17 +640,23 @@ var SystemInterfaceResourceScopeSchema = z.array(ModelIdSchema).default([]);
623
640
  var SystemApiInterfaceReadinessContractSchema = z.object({
624
641
  /** Ontology IDs of object types the interface depends on. */
625
642
  requiredObjects: z.array(z.string().trim().min(1)).default([]),
626
- /** Ontology IDs of catalog types the interface requires (must be non-empty). */
627
- requiredCatalogs: z.array(z.string().trim().min(1)).default([]),
628
- /** Optional ontology kind filters (reserved for future profile extensions). */
629
- requiredKinds: z.array(z.string().trim().min(1)).optional()
643
+ /**
644
+ * Ontology IDs of catalog types the interface requires. Must declare at least one
645
+ * entry a `readinessContract` with no `requiredCatalogs` asserts nothing at all,
646
+ * so it has no `.default([])`; omitting the field is rejected the same as an
647
+ * explicit empty array.
648
+ */
649
+ requiredCatalogs: z.array(z.string().trim().min(1)).min(1)
630
650
  }).strict();
631
651
  var SystemApiInterfaceSchema = z.object({
632
652
  lifecycle: SystemInterfaceLifecycleSchema.default("active"),
633
653
  /**
634
654
  * Open-string profile id. Built-in platform presets are looked up through
635
655
  * the profile registry; custom ids are validated structurally via
636
- * `readinessContract`. Optional `profileForInterface` provides a default.
656
+ * `readinessContract`. Optional at the schema layer, but readiness
657
+ * computation rejects an interface that omits it with a
658
+ * `missing-readiness-profile` diagnostic — there is no positional
659
+ * fallback to `${systemPath}.${interfaceKey}`.
637
660
  */
638
661
  readinessProfile: SystemInterfaceReadinessProfileSchema.optional(),
639
662
  /**
@@ -648,27 +671,25 @@ var SystemApiInterfaceSchema = z.object({
648
671
  */
649
672
  readinessContract: SystemApiInterfaceReadinessContractSchema.optional()
650
673
  }).strict();
651
- var _profileRegistry = new Map(
652
- SYSTEM_INTERFACE_READINESS_PROFILES.map((profileId) => [
653
- profileId,
654
- { profileId, kind: "built-in" }
655
- ])
656
- );
674
+ var _customProfileIds = /* @__PURE__ */ new Set();
675
+ function isReservedPlatformProfileId(profileId) {
676
+ return SYSTEM_INTERFACE_READINESS_PROFILES.includes(profileId);
677
+ }
657
678
  function lookupReadinessProfile(profileId) {
658
- return _profileRegistry.get(profileId);
679
+ if (isReservedPlatformProfileId(profileId) || getBuiltInReadinessProfile(profileId) !== void 0) {
680
+ return { profileId, kind: "built-in" };
681
+ }
682
+ if (_customProfileIds.has(profileId)) return { profileId, kind: "custom" };
683
+ return void 0;
659
684
  }
660
685
  function registerReadinessProfile(profileId) {
661
- const existing = _profileRegistry.get(profileId);
686
+ const existing = lookupReadinessProfile(profileId);
662
687
  if (existing !== void 0) return existing;
663
- const entry = { profileId, kind: "custom" };
664
- _profileRegistry.set(profileId, entry);
665
- return entry;
666
- }
667
- function profileForInterface(systemPath, interfaceKey, readinessProfile) {
668
- return readinessProfile ?? `${systemPath}.${interfaceKey}`;
688
+ _customProfileIds.add(profileId);
689
+ return { profileId, kind: "custom" };
669
690
  }
670
691
  function isBuiltInReadinessProfile(profileId) {
671
- return _profileRegistry.get(profileId)?.kind === "built-in";
692
+ return isReservedPlatformProfileId(profileId) || getBuiltInReadinessProfile(profileId) !== void 0;
672
693
  }
673
694
  var SystemInterfaceRefSchema = z.object({
674
695
  systemPath: SystemPathSchema,
@@ -700,7 +721,7 @@ var SystemEntrySchema = z.object({
700
721
  parentSystemId: SystemIdSchema.optional(),
701
722
  /** Optional UI presence. Systems without UI omit this. */
702
723
  ui: SystemUiSchema.optional(),
703
- /** Canonical lifecycle state. Replaces Feature.enabled/devOnly and System.status. */
724
+ /** Canonical lifecycle state. `beta` is what gates a System to dev-mode viewers. */
704
725
  lifecycle: SystemLifecycleSchema.optional(),
705
726
  /** Optional role responsible for this system. */
706
727
  responsibleRoleId: ModelIdSchema.meta({ ref: "role" }).optional(),
@@ -708,14 +729,10 @@ var SystemEntrySchema = z.object({
708
729
  governedByKnowledge: z.array(ModelIdSchema.meta({ ref: "knowledge" })).default([]).optional(),
709
730
  /** Optional actions this system exposes or consumes. */
710
731
  actions: z.array(ActionRefSchema).optional(),
711
- /** Optional operational policies that apply to this system. */
712
- policies: z.array(ModelIdSchema.meta({ ref: "policy" })).default([]).optional(),
713
732
  /** Optional goals this system contributes to. */
714
733
  drivesGoals: z.array(ModelIdSchema.meta({ ref: "goal" })).default([]).optional(),
715
734
  /** Thin API runtime-boundary marker. Readiness is derived from scoped resources and topology. */
716
735
  apiInterface: SystemApiInterfaceSchema.optional(),
717
- /** @deprecated Use lifecycle. Accepted for one publish cycle. */
718
- status: SystemStatusSchema.optional(),
719
736
  /** @deprecated Use ui.path. Kept for one-cycle Feature compatibility. */
720
737
  path: PathSchema.optional(),
721
738
  /** @deprecated Use ui.icon. Kept for one-cycle Feature compatibility. */
@@ -724,9 +741,6 @@ var SystemEntrySchema = z.object({
724
741
  uiPosition: UiPositionSchema.optional(),
725
742
  /** @deprecated Use lifecycle. */
726
743
  enabled: z.boolean().optional(),
727
- /** @deprecated Use lifecycle: "beta". */
728
- devOnly: z.boolean().optional(),
729
- requiresAdmin: z.boolean().optional(),
730
744
  /** Domain-map iteration order. Convention: multiples of 10 (10, 20, 30, ...) to allow easy insertion. */
731
745
  order: z.number(),
732
746
  /**
@@ -753,12 +767,9 @@ var SystemEntrySchema = z.object({
753
767
  }).strict().refine((system) => system.label !== void 0 || system.title !== void 0, {
754
768
  path: ["label"],
755
769
  message: "System must provide label or title"
756
- }).transform((system) => {
757
- const normalizedSystem = system.systems !== void 0 && system.subsystems === void 0 ? { ...system, subsystems: system.systems } : system;
758
- if (normalizedSystem.status === void 0) return normalizedSystem;
759
- console.warn("[organization-model] System.status is deprecated; use System.lifecycle instead.");
760
- return normalizedSystem.lifecycle === void 0 ? { ...normalizedSystem, lifecycle: normalizedSystem.status } : normalizedSystem;
761
- });
770
+ }).transform(
771
+ (system) => system.systems !== void 0 && system.subsystems === void 0 ? { ...system, subsystems: system.systems } : system
772
+ );
762
773
  z.record(z.string(), SystemEntrySchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
763
774
  message: "Each system entry id must match its map key"
764
775
  }).default({});
@@ -933,7 +944,6 @@ var OmTopologyNodeKindSchema = z.enum([
933
944
  "system",
934
945
  "resource",
935
946
  "ontology",
936
- "policy",
937
947
  "role",
938
948
  "trigger",
939
949
  "humanCheckpoint",
@@ -944,7 +954,6 @@ var OmTopologyNodeRefSchema = z.discriminatedUnion("kind", [
944
954
  z.object({ kind: z.literal("system"), id: ModelIdSchema }),
945
955
  z.object({ kind: z.literal("resource"), id: ResourceIdSchema }),
946
956
  z.object({ kind: z.literal("ontology"), id: OntologyIdSchema }),
947
- z.object({ kind: z.literal("policy"), id: ModelIdSchema }),
948
957
  z.object({ kind: z.literal("role"), id: ModelIdSchema }),
949
958
  z.object({ kind: z.literal("trigger"), id: ResourceIdSchema }),
950
959
  z.object({ kind: z.literal("humanCheckpoint"), id: ResourceIdSchema }),
@@ -1017,7 +1026,6 @@ var topologyRef = {
1017
1026
  system: (system) => parseRef("system", idFrom(system)),
1018
1027
  resource: (resource) => parseRef("resource", idFrom(resource)),
1019
1028
  ontology: (record) => parseRef("ontology", idFrom(record)),
1020
- policy: (policy) => parseRef("policy", idFrom(policy)),
1021
1029
  role: (role) => parseRef("role", idFrom(role)),
1022
1030
  trigger: (trigger) => parseRef("trigger", idFrom(trigger)),
1023
1031
  humanCheckpoint: (checkpoint) => parseRef("humanCheckpoint", idFrom(checkpoint)),
@@ -1093,7 +1101,9 @@ function defineTopology(relationships) {
1093
1101
  const entries = Array.isArray(relationships) ? relationships.map((relationship, index) => [`relationship-${index + 1}`, relationship]) : Object.entries(relationships);
1094
1102
  return OmTopologyDomainSchema.parse({
1095
1103
  version: 1,
1096
- relationships: Object.fromEntries(entries.map(([key, relationship]) => [key, defineTopologyRelationship(relationship)]))
1104
+ relationships: Object.fromEntries(
1105
+ entries.map(([key, relationship]) => [key, defineTopologyRelationship(relationship)])
1106
+ )
1097
1107
  });
1098
1108
  }
1099
1109
 
@@ -1130,6 +1140,7 @@ function appliesToEntityKind(catalog) {
1130
1140
  if (id === "deal") return void 0;
1131
1141
  return void 0;
1132
1142
  }
1143
+ formatOntologyId({ scope: "sales.crm", kind: "catalog", localId: "crm.pipeline" });
1133
1144
  function getLeadGenStageCatalog(model) {
1134
1145
  const results = {};
1135
1146
  for (const catalog of catalogRecords(model).filter(
@@ -1214,100 +1225,425 @@ var ProspectingBuildTemplateSchema = DisplayMetadataSchema.extend({
1214
1225
  steps: z.array(ProspectingBuildTemplateStepSchema).min(1)
1215
1226
  });
1216
1227
 
1217
- // src/contract-ref.ts
1218
- var ContractRefResolutionError = class extends Error {
1219
- constructor(code, message, ref) {
1220
- super(message);
1221
- this.code = code;
1222
- this.ref = ref;
1223
- this.name = "ContractRefResolutionError";
1228
+ // ../core/src/organization-model/readiness/engine.ts
1229
+ var SystemInterfaceReadinessError = class extends Error {
1230
+ code;
1231
+ statusCode = 503;
1232
+ systemPath;
1233
+ interfaceKey;
1234
+ readinessProfile;
1235
+ issues;
1236
+ constructor(result) {
1237
+ const firstIssue = result.issues[0];
1238
+ super(formatInterfaceReadinessFailure(result));
1239
+ this.name = "SystemInterfaceReadinessError";
1240
+ this.code = firstIssue?.family ?? "SYSTEM_INTERFACE_NOT_READY";
1241
+ this.systemPath = result.systemPath;
1242
+ this.interfaceKey = result.interfaceKey;
1243
+ this.readinessProfile = result.readinessProfile;
1244
+ this.issues = result.issues;
1224
1245
  }
1225
1246
  };
1226
- function isZodType(value) {
1227
- return typeof value === "object" && value !== null && "_def" in value;
1247
+ function addReadinessIssue(issues, family, code, message, details = {}) {
1248
+ issues.push({
1249
+ family,
1250
+ code,
1251
+ message,
1252
+ ...details
1253
+ });
1228
1254
  }
1229
- function resolveContractRef(ref, registry) {
1230
- const parsed = parseContractRef(ref);
1231
- const moduleNamespace = registry[parsed.moduleSpecifier];
1232
- if (moduleNamespace === void 0) {
1233
- throw new ContractRefResolutionError(
1234
- "contract-ref-unknown-module",
1235
- `ContractRef "${ref}" references unknown module "${parsed.moduleSpecifier}".`,
1236
- ref
1237
- );
1255
+ function formatInterfaceIdentity(systemPath, interfaceKey) {
1256
+ return `${systemPath}/${interfaceKey}`;
1257
+ }
1258
+ function readinessMarkerPath(context) {
1259
+ return context.interfaceKey === "api" ? `systems.${context.systemPath}.apiInterface` : void 0;
1260
+ }
1261
+ function readinessMarkerFieldPath(context, suffix) {
1262
+ const base = readinessMarkerPath(context);
1263
+ return base === void 0 ? void 0 : `${base}${suffix}`;
1264
+ }
1265
+ function formatInterfaceReadinessFailure(result) {
1266
+ const identity = formatInterfaceIdentity(result.systemPath, result.interfaceKey);
1267
+ const issueSummary = result.issues.map((issue) => `${issue.family}:${issue.code}: ${issue.message}`).join("; ");
1268
+ return `${identity} readiness failed${result.readinessProfile ? ` (${result.readinessProfile})` : ""}: ${issueSummary}`;
1269
+ }
1270
+ function formatSupportedReadinessProfiles() {
1271
+ return SYSTEM_INTERFACE_PROFILES.map((p) => `"${p.readinessProfile}"`).join(", ");
1272
+ }
1273
+ function isPlainRecord(value) {
1274
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1275
+ }
1276
+ function getCatalogEntries(catalog) {
1277
+ return isPlainRecord(catalog.entries) ? catalog.entries : {};
1278
+ }
1279
+ function getActiveScopedResources(model, resourceIds, issues, context) {
1280
+ const resources = [];
1281
+ for (const [index, resourceId] of resourceIds.entries()) {
1282
+ const resource = model.resources?.[resourceId];
1283
+ const path = readinessMarkerFieldPath(context, `.resourceIds.${index}`);
1284
+ if (resource === void 0) {
1285
+ addReadinessIssue(
1286
+ issues,
1287
+ "SYSTEM_INTERFACE_NOT_READY",
1288
+ "missing-resource",
1289
+ `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" scopes missing resource "${resourceId}".`,
1290
+ { path, ref: resourceId }
1291
+ );
1292
+ continue;
1293
+ }
1294
+ if (resource.systemPath !== context.systemPath) {
1295
+ addReadinessIssue(
1296
+ issues,
1297
+ "SYSTEM_INTERFACE_INVALID",
1298
+ "resource-system-mismatch",
1299
+ `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" scopes resource "${resourceId}" from system "${resource.systemPath}".`,
1300
+ { path, ref: resourceId }
1301
+ );
1302
+ continue;
1303
+ }
1304
+ if (resource.status !== "active") {
1305
+ addReadinessIssue(
1306
+ issues,
1307
+ "SYSTEM_INTERFACE_NOT_READY",
1308
+ "inactive-resource",
1309
+ `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" scopes inactive resource "${resourceId}".`,
1310
+ { path, ref: resourceId }
1311
+ );
1312
+ continue;
1313
+ }
1314
+ resources.push(resource);
1238
1315
  }
1239
- const exportValue = moduleNamespace[parsed.exportName];
1240
- if (exportValue === void 0) {
1241
- throw new ContractRefResolutionError(
1242
- "contract-ref-unknown-export",
1243
- `ContractRef "${ref}" references unknown export "${parsed.exportName}".`,
1244
- ref
1316
+ return resources;
1317
+ }
1318
+ function resourceBindingIds(resources, key) {
1319
+ return new Set(resources.flatMap((resource) => resource.ontology?.[key] ?? []));
1320
+ }
1321
+ function requireScopedBinding(issues, boundIds, bindingKey, ontologyId, context) {
1322
+ if (boundIds.has(ontologyId)) return;
1323
+ addReadinessIssue(
1324
+ issues,
1325
+ "SYSTEM_INTERFACE_NOT_READY",
1326
+ "missing-resource-binding",
1327
+ `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" has no active scoped resource with ontology.${bindingKey} binding "${ontologyId}".`,
1328
+ { path: readinessMarkerFieldPath(context, ".resourceIds"), ref: ontologyId }
1329
+ );
1330
+ }
1331
+ function ontologyOwnerMatches(ontologyId, expectedSystemPath, catalog) {
1332
+ if (catalog?.ownerSystemId !== void 0) return catalog.ownerSystemId === expectedSystemPath;
1333
+ return parseOntologyId(ontologyId).scope === expectedSystemPath;
1334
+ }
1335
+ function requireObjectReadiness(issues, index, objectId, context) {
1336
+ const object = index.ontology.objectTypes[objectId];
1337
+ if (object === void 0) {
1338
+ addReadinessIssue(
1339
+ issues,
1340
+ "SYSTEM_INTERFACE_NOT_READY",
1341
+ "missing-object",
1342
+ `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" is missing required object type "${objectId}".`,
1343
+ { ref: objectId }
1245
1344
  );
1345
+ return;
1246
1346
  }
1247
- if (!isZodType(exportValue)) {
1248
- throw new ContractRefResolutionError(
1249
- "contract-ref-not-zod-type",
1250
- `ContractRef "${ref}" resolves to "${parsed.exportName}" but it is not a ZodType.`,
1251
- ref
1347
+ const ownerSystemId = object.ownerSystemId ?? parseOntologyId(objectId).scope;
1348
+ if (ownerSystemId !== context.systemPath) {
1349
+ addReadinessIssue(
1350
+ issues,
1351
+ "SYSTEM_INTERFACE_INVALID",
1352
+ "foreign-object",
1353
+ `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" requires object "${objectId}" owned by "${ownerSystemId}".`,
1354
+ { ref: objectId }
1252
1355
  );
1253
1356
  }
1254
- return {
1255
- ref,
1256
- moduleSpecifier: parsed.moduleSpecifier,
1257
- exportName: parsed.exportName,
1258
- value: exportValue
1259
- };
1260
1357
  }
1261
- async function concurrentPool(opts) {
1262
- const { items, concurrency, process, onSuccess, onError } = opts;
1263
- const results = [];
1264
- let nextIndex = 0;
1265
- let succeeded = 0;
1266
- let failed = 0;
1267
- const active = /* @__PURE__ */ new Set();
1268
- const enqueue = () => {
1269
- while (active.size < concurrency && nextIndex < items.length) {
1270
- const idx = nextIndex++;
1271
- const item = items[idx];
1272
- const task = process(item, idx).then((value) => {
1273
- results.push({ index: idx, value });
1274
- succeeded++;
1275
- onSuccess?.(value, item, idx);
1276
- }).catch((error) => {
1277
- results.push({ index: idx, error });
1278
- failed++;
1279
- onError?.(error, item, idx);
1280
- }).finally(() => {
1281
- active.delete(task);
1282
- enqueue();
1283
- });
1284
- active.add(task);
1285
- }
1286
- };
1287
- enqueue();
1288
- while (active.size > 0) {
1289
- await Promise.race(active);
1358
+ function requireCatalogReadiness(issues, index, catalogId, context) {
1359
+ const catalog = index.ontology.catalogTypes[catalogId];
1360
+ if (catalog === void 0) {
1361
+ addReadinessIssue(
1362
+ issues,
1363
+ "SYSTEM_INTERFACE_NOT_READY",
1364
+ "missing-catalog",
1365
+ `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" is missing required catalog "${catalogId}".`,
1366
+ { ref: catalogId }
1367
+ );
1368
+ return void 0;
1290
1369
  }
1291
- return { results, succeeded, failed };
1370
+ if (context.allowForeignOwner !== true && !ontologyOwnerMatches(catalogId, context.systemPath, catalog)) {
1371
+ addReadinessIssue(
1372
+ issues,
1373
+ "SYSTEM_INTERFACE_INVALID",
1374
+ "foreign-catalog",
1375
+ `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" requires catalog "${catalogId}" owned by "${catalog.ownerSystemId ?? parseOntologyId(catalogId).scope}".`,
1376
+ { ref: catalogId }
1377
+ );
1378
+ }
1379
+ if (Object.keys(getCatalogEntries(catalog)).length === 0) {
1380
+ addReadinessIssue(
1381
+ issues,
1382
+ "SYSTEM_INTERFACE_NOT_READY",
1383
+ "empty-catalog",
1384
+ `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" requires catalog entries for "${catalogId}".`,
1385
+ { ref: catalogId }
1386
+ );
1387
+ }
1388
+ return catalog;
1292
1389
  }
1293
- var diagnosticOutput = z.object({
1294
- success: z.boolean(),
1295
- tool: z.string(),
1296
- method: z.string(),
1297
- result: z.unknown().optional(),
1298
- error: z.string().optional(),
1299
- durationMs: z.number().optional()
1300
- });
1301
- var integrationInput = z.object({
1302
- credential: z.string().describe("Credential name registered for this integration")
1303
- });
1304
- async function runDiagnostic(tool, method, fn) {
1305
- const start = Date.now();
1306
- try {
1307
- const result = await fn();
1308
- return { success: true, tool, method, result, durationMs: Date.now() - start };
1309
- } catch (error) {
1310
- return { success: false, tool, method, error: String(error), durationMs: Date.now() - start };
1390
+ function requireContractReadiness(issues, index, resources, contract, context) {
1391
+ const reads = resourceBindingIds(resources, "reads");
1392
+ const catalogs = resourceBindingIds(resources, "usesCatalogs");
1393
+ for (const objectId of contract.requiredObjects) {
1394
+ requireObjectReadiness(issues, index, objectId, context);
1395
+ requireScopedBinding(issues, reads, "reads", objectId, context);
1396
+ }
1397
+ for (const catalogId of contract.requiredCatalogs) {
1398
+ requireCatalogReadiness(issues, index, catalogId, context);
1399
+ requireScopedBinding(issues, catalogs, "usesCatalogs", catalogId, context);
1400
+ }
1401
+ }
1402
+ function getSystemInterfaceReadinessMarker(model, request) {
1403
+ const system = getSystem(model, request.systemPath);
1404
+ if (system === void 0) return void 0;
1405
+ const registeredMarker = resolveReadinessInterfaceMarker(model, request.systemPath, request.interfaceKey);
1406
+ if (registeredMarker !== void 0) return registeredMarker;
1407
+ if (request.interfaceKey === "api" && system.apiInterface !== void 0) {
1408
+ return system.apiInterface;
1409
+ }
1410
+ return void 0;
1411
+ }
1412
+ function compileReadinessOntology(model, readinessProfile, prepareModel) {
1413
+ const preparedModel = prepareModel !== void 0 ? prepareModel(model) : model;
1414
+ const compilation = compileOrganizationOntology(preparedModel);
1415
+ if (compilation.diagnostics.length > 0) {
1416
+ const summary = compilation.diagnostics.map((diagnostic) => diagnostic.message).join("; ");
1417
+ throw new Error(`${readinessProfile} ontology validation index failed to compile: ${summary}`);
1418
+ }
1419
+ return { ontology: compilation.ontology };
1420
+ }
1421
+ function tryCompileReadinessOntology(model, readinessProfile, prepareModel, issues) {
1422
+ try {
1423
+ return compileReadinessOntology(model, readinessProfile, prepareModel);
1424
+ } catch (error) {
1425
+ addReadinessIssue(
1426
+ issues,
1427
+ "SYSTEM_INTERFACE_INVALID",
1428
+ "ontology-compile-failed",
1429
+ error instanceof Error ? error.message : String(error)
1430
+ );
1431
+ return void 0;
1432
+ }
1433
+ }
1434
+ function computeInterfaceReadiness(model, request) {
1435
+ const issues = [];
1436
+ const system = getSystem(model, request.systemPath);
1437
+ const systemInterface = getSystemInterfaceReadinessMarker(model, request);
1438
+ const readinessProfile = systemInterface?.readinessProfile;
1439
+ const scopedResourceIds = systemInterface?.resourceIds ?? [];
1440
+ if (system === void 0) {
1441
+ addReadinessIssue(
1442
+ issues,
1443
+ "SYSTEM_INTERFACE_MISSING",
1444
+ "missing-system",
1445
+ `System "${request.systemPath}" is missing.`,
1446
+ { ref: request.systemPath }
1447
+ );
1448
+ return {
1449
+ ready: false,
1450
+ systemPath: request.systemPath,
1451
+ interfaceKey: request.interfaceKey,
1452
+ scopedResourceIds,
1453
+ issues
1454
+ };
1455
+ }
1456
+ if (systemInterface === void 0) {
1457
+ addReadinessIssue(
1458
+ issues,
1459
+ "SYSTEM_INTERFACE_MISSING",
1460
+ "missing-interface",
1461
+ `System "${request.systemPath}" does not declare interface "${request.interfaceKey}".`,
1462
+ { path: readinessMarkerPath(request) }
1463
+ );
1464
+ return {
1465
+ ready: false,
1466
+ systemPath: request.systemPath,
1467
+ interfaceKey: request.interfaceKey,
1468
+ scopedResourceIds,
1469
+ issues
1470
+ };
1471
+ }
1472
+ if (systemInterface.lifecycle !== "active") {
1473
+ addReadinessIssue(
1474
+ issues,
1475
+ "SYSTEM_INTERFACE_DISABLED",
1476
+ "inactive-interface",
1477
+ `System Interface "${formatInterfaceIdentity(request.systemPath, request.interfaceKey)}" lifecycle is "${systemInterface.lifecycle}".`,
1478
+ { path: readinessMarkerFieldPath(request, ".lifecycle") }
1479
+ );
1480
+ return {
1481
+ ready: false,
1482
+ systemPath: request.systemPath,
1483
+ interfaceKey: request.interfaceKey,
1484
+ readinessProfile,
1485
+ scopedResourceIds,
1486
+ issues
1487
+ };
1488
+ }
1489
+ if (readinessProfile === void 0) {
1490
+ addReadinessIssue(
1491
+ issues,
1492
+ "SYSTEM_INTERFACE_INVALID",
1493
+ "missing-readiness-profile",
1494
+ `System Interface "${formatInterfaceIdentity(request.systemPath, request.interfaceKey)}" declares an apiInterface but no readinessProfile. Declare a built-in profile (${formatSupportedReadinessProfiles()}) or a custom id paired with a readinessContract.`,
1495
+ { path: readinessMarkerFieldPath(request, ".readinessProfile") }
1496
+ );
1497
+ return {
1498
+ ready: false,
1499
+ systemPath: request.systemPath,
1500
+ interfaceKey: request.interfaceKey,
1501
+ scopedResourceIds,
1502
+ issues
1503
+ };
1504
+ }
1505
+ const isBuiltIn = isBuiltInReadinessProfile(readinessProfile);
1506
+ const readinessContract = systemInterface.readinessContract;
1507
+ if (!isBuiltIn && readinessContract === void 0) {
1508
+ addReadinessIssue(
1509
+ issues,
1510
+ "SYSTEM_INTERFACE_INVALID",
1511
+ "missing-readiness-contract",
1512
+ `System Interface "${formatInterfaceIdentity(request.systemPath, request.interfaceKey)}" uses custom readiness profile "${readinessProfile}" but declares no readinessContract. Built-in profiles: ${formatSupportedReadinessProfiles()}.`,
1513
+ { path: readinessMarkerFieldPath(request, ".readinessContract"), ref: readinessProfile }
1514
+ );
1515
+ return {
1516
+ ready: false,
1517
+ systemPath: request.systemPath,
1518
+ interfaceKey: request.interfaceKey,
1519
+ readinessProfile,
1520
+ scopedResourceIds,
1521
+ issues
1522
+ };
1523
+ }
1524
+ if (scopedResourceIds.length === 0) {
1525
+ addReadinessIssue(
1526
+ issues,
1527
+ "SYSTEM_INTERFACE_NOT_READY",
1528
+ "missing-scoped-resources",
1529
+ `System Interface "${formatInterfaceIdentity(request.systemPath, request.interfaceKey)}" must scope at least one active resource.`,
1530
+ { path: readinessMarkerFieldPath(request, ".resourceIds") }
1531
+ );
1532
+ }
1533
+ const resources = getActiveScopedResources(model, scopedResourceIds, issues, request);
1534
+ const registration = getBuiltInReadinessProfile(readinessProfile);
1535
+ const index = tryCompileReadinessOntology(model, readinessProfile, registration?.prepareModel, issues);
1536
+ if (index !== void 0) {
1537
+ if (registration !== void 0) {
1538
+ registration.validate(issues, index, resources, model, request);
1539
+ } else if (readinessContract !== void 0) {
1540
+ requireContractReadiness(issues, index, resources, readinessContract, request);
1541
+ }
1542
+ }
1543
+ return {
1544
+ ready: issues.length === 0,
1545
+ systemPath: request.systemPath,
1546
+ interfaceKey: request.interfaceKey,
1547
+ readinessProfile,
1548
+ scopedResourceIds,
1549
+ issues
1550
+ };
1551
+ }
1552
+
1553
+ // src/contract-ref.ts
1554
+ var ContractRefResolutionError = class extends Error {
1555
+ constructor(code, message, ref) {
1556
+ super(message);
1557
+ this.code = code;
1558
+ this.ref = ref;
1559
+ this.name = "ContractRefResolutionError";
1560
+ }
1561
+ };
1562
+ function isZodType(value) {
1563
+ return typeof value === "object" && value !== null && "_def" in value;
1564
+ }
1565
+ function resolveContractRef(ref, registry) {
1566
+ const parsed = parseContractRef(ref);
1567
+ const moduleNamespace = registry[parsed.moduleSpecifier];
1568
+ if (moduleNamespace === void 0) {
1569
+ throw new ContractRefResolutionError(
1570
+ "contract-ref-unknown-module",
1571
+ `ContractRef "${ref}" references unknown module "${parsed.moduleSpecifier}".`,
1572
+ ref
1573
+ );
1574
+ }
1575
+ const exportValue = moduleNamespace[parsed.exportName];
1576
+ if (exportValue === void 0) {
1577
+ throw new ContractRefResolutionError(
1578
+ "contract-ref-unknown-export",
1579
+ `ContractRef "${ref}" references unknown export "${parsed.exportName}".`,
1580
+ ref
1581
+ );
1582
+ }
1583
+ if (!isZodType(exportValue)) {
1584
+ throw new ContractRefResolutionError(
1585
+ "contract-ref-not-zod-type",
1586
+ `ContractRef "${ref}" resolves to "${parsed.exportName}" but it is not a ZodType.`,
1587
+ ref
1588
+ );
1589
+ }
1590
+ return {
1591
+ ref,
1592
+ moduleSpecifier: parsed.moduleSpecifier,
1593
+ exportName: parsed.exportName,
1594
+ value: exportValue
1595
+ };
1596
+ }
1597
+ async function concurrentPool(opts) {
1598
+ const { items, concurrency, process, onSuccess, onError } = opts;
1599
+ const results = [];
1600
+ let nextIndex = 0;
1601
+ let succeeded = 0;
1602
+ let failed = 0;
1603
+ const active = /* @__PURE__ */ new Set();
1604
+ const enqueue = () => {
1605
+ while (active.size < concurrency && nextIndex < items.length) {
1606
+ const idx = nextIndex++;
1607
+ const item = items[idx];
1608
+ const task = process(item, idx).then((value) => {
1609
+ results.push({ index: idx, value });
1610
+ succeeded++;
1611
+ onSuccess?.(value, item, idx);
1612
+ }).catch((error) => {
1613
+ results.push({ index: idx, error });
1614
+ failed++;
1615
+ onError?.(error, item, idx);
1616
+ }).finally(() => {
1617
+ active.delete(task);
1618
+ enqueue();
1619
+ });
1620
+ active.add(task);
1621
+ }
1622
+ };
1623
+ enqueue();
1624
+ while (active.size > 0) {
1625
+ await Promise.race(active);
1626
+ }
1627
+ return { results, succeeded, failed };
1628
+ }
1629
+ var diagnosticOutput = z.object({
1630
+ success: z.boolean(),
1631
+ tool: z.string(),
1632
+ method: z.string(),
1633
+ result: z.unknown().optional(),
1634
+ error: z.string().optional(),
1635
+ durationMs: z.number().optional()
1636
+ });
1637
+ var integrationInput = z.object({
1638
+ credential: z.string().describe("Credential name registered for this integration")
1639
+ });
1640
+ async function runDiagnostic(tool, method, fn) {
1641
+ const start = Date.now();
1642
+ try {
1643
+ const result = await fn();
1644
+ return { success: true, tool, method, result, durationMs: Date.now() - start };
1645
+ } catch (error) {
1646
+ return { success: false, tool, method, error: String(error), durationMs: Date.now() - start };
1311
1647
  }
1312
1648
  }
1313
1649
  var NAME_PREFIXES = /^(dr\.?|prof\.?|mr\.?|mrs\.?|ms\.?|rev\.?)\s+/i;
@@ -4047,612 +4383,24 @@ function buildIterationResponseSchemaUncached(tools, capabilities) {
4047
4383
  // returns zero memory references -- so this description is the only framework-owned
4048
4384
  // lever on how a memory value is written. It matters more here than in `message`:
4049
4385
  // a session-memory value is re-sent on every iteration of every subsequent turn and
4050
- // never ages out, so one literal escape stored here is one the model re-reads forever.
4051
- description: "Stored verbatim and replayed to you on every later turn. Write real line breaks and real quotation marks -- the two characters \\n are not a line break."
4052
- }
4053
- },
4054
- required: ["key", "value"],
4055
- additionalProperties: false
4056
- }
4057
- },
4058
- delete: { type: "array", items: { type: "string" } }
4059
- },
4060
- additionalProperties: false
4061
- };
4062
- }
4063
- return {
4064
- type: "object",
4065
- properties,
4066
- required: capabilities.message === "required" ? ["nextActions", "message", "reasoning"] : ["nextActions", "reasoning"],
4067
- additionalProperties: false
4068
- };
4069
- }
4070
-
4071
- // ../core/src/business/acquisition/ontology-validation.ts
4072
- var LEAD_GEN_API_INTERFACE = SYSTEM_INTERFACE_PROFILES[0];
4073
- var CRM_API_INTERFACE = SYSTEM_INTERFACE_PROFILES[1];
4074
- var LEAD_GEN_CRM_HANDOFF_INTERFACE = SYSTEM_INTERFACE_PROFILES[2];
4075
- var LEAD_GEN_API_READINESS_LABEL = LEAD_GEN_API_INTERFACE.readinessProfile;
4076
- var CRM_API_READINESS_LABEL = CRM_API_INTERFACE.readinessProfile;
4077
- LEAD_GEN_CRM_HANDOFF_INTERFACE.readinessProfile;
4078
- var LEAD_GEN_LIST_OBJECT_ONTOLOGY_ID = formatOntologyId({
4079
- scope: "sales.lead-gen",
4080
- kind: "object",
4081
- localId: "list"
4082
- });
4083
- var LEAD_GEN_COMPANY_OBJECT_ONTOLOGY_ID = formatOntologyId({
4084
- scope: "sales.lead-gen",
4085
- kind: "object",
4086
- localId: "company"
4087
- });
4088
- var LEAD_GEN_CONTACT_OBJECT_ONTOLOGY_ID = formatOntologyId({
4089
- scope: "sales.lead-gen",
4090
- kind: "object",
4091
- localId: "contact"
4092
- });
4093
- var LEAD_GEN_BUILD_TEMPLATE_CATALOG_ONTOLOGY_ID = formatOntologyId({
4094
- scope: "sales.lead-gen",
4095
- kind: "catalog",
4096
- localId: "build-template"
4097
- });
4098
- var LEAD_GEN_COMPANY_STAGE_CATALOG_ONTOLOGY_ID = formatOntologyId({
4099
- scope: "sales.lead-gen",
4100
- kind: "catalog",
4101
- localId: "company-stage"
4102
- });
4103
- var LEAD_GEN_CONTACT_STAGE_CATALOG_ONTOLOGY_ID = formatOntologyId({
4104
- scope: "sales.lead-gen",
4105
- kind: "catalog",
4106
- localId: "contact-stage"
4107
- });
4108
- var CRM_PIPELINE_CATALOG_ONTOLOGY_ID = formatOntologyId({
4109
- scope: "sales.crm",
4110
- kind: "catalog",
4111
- localId: "crm.pipeline"
4112
- });
4113
- var LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID = formatOntologyId({
4114
- scope: "sales.lead-gen",
4115
- kind: "catalog",
4116
- localId: "lead-gen.stage-catalog"
4117
- });
4118
- var SystemInterfaceReadinessError = class extends Error {
4119
- code;
4120
- statusCode = 503;
4121
- systemPath;
4122
- interfaceKey;
4123
- readinessProfile;
4124
- issues;
4125
- constructor(result) {
4126
- const firstIssue = result.issues[0];
4127
- super(formatInterfaceReadinessFailure(result));
4128
- this.name = "SystemInterfaceReadinessError";
4129
- this.code = firstIssue?.family ?? "SYSTEM_INTERFACE_NOT_READY";
4130
- this.systemPath = result.systemPath;
4131
- this.interfaceKey = result.interfaceKey;
4132
- this.readinessProfile = result.readinessProfile;
4133
- this.issues = result.issues;
4134
- }
4135
- };
4136
- function createLeadGenStageCatalog(model) {
4137
- return {
4138
- id: LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID,
4139
- label: "Lead Gen Processing Stages",
4140
- ownerSystemId: "sales.lead-gen",
4141
- kind: "processing-stage-catalog",
4142
- entries: Object.fromEntries(
4143
- Object.entries(getLeadGenStageCatalog(model)).map(([key, entry]) => [
4144
- key,
4145
- {
4146
- ...entry
4147
- }
4148
- ])
4149
- ),
4150
- legacyCatalogKey: "LEAD_GEN_STAGE_CATALOG"
4151
- };
4152
- }
4153
- function isPlainRecord(value) {
4154
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
4155
- }
4156
- function addReadinessIssue(issues, family, code, message, details = {}) {
4157
- issues.push({
4158
- family,
4159
- code,
4160
- message,
4161
- ...details
4162
- });
4163
- }
4164
- function formatInterfaceIdentity(systemPath, interfaceKey) {
4165
- return `${systemPath}/${interfaceKey}`;
4166
- }
4167
- function readinessMarkerPath(context) {
4168
- return context.interfaceKey === "api" ? `systems.${context.systemPath}.apiInterface` : `systems.${context.systemPath}.derivedCrmHandoffReadiness`;
4169
- }
4170
- function formatInterfaceReadinessFailure(result) {
4171
- const identity = formatInterfaceIdentity(result.systemPath, result.interfaceKey);
4172
- const issueSummary = result.issues.map((issue) => `${issue.family}:${issue.code}: ${issue.message}`).join("; ");
4173
- return `${identity} readiness failed${result.readinessProfile ? ` (${result.readinessProfile})` : ""}: ${issueSummary}`;
4174
- }
4175
- function formatSupportedReadinessProfiles() {
4176
- return SYSTEM_INTERFACE_PROFILES.map((p) => `"${p.readinessProfile}"`).join(", ");
4177
- }
4178
- function throwIfInterfaceNotReady(result) {
4179
- if (result.ready) return;
4180
- throw new SystemInterfaceReadinessError(result);
4181
- }
4182
- function getActiveScopedResources(model, resourceIds, issues, context) {
4183
- const resources = [];
4184
- for (const [index, resourceId] of resourceIds.entries()) {
4185
- const resource = model.resources?.[resourceId];
4186
- const path = `${readinessMarkerPath(context)}.resourceIds.${index}`;
4187
- if (resource === void 0) {
4188
- addReadinessIssue(
4189
- issues,
4190
- "SYSTEM_INTERFACE_NOT_READY",
4191
- "missing-resource",
4192
- `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" scopes missing resource "${resourceId}".`,
4193
- { path, ref: resourceId }
4194
- );
4195
- continue;
4196
- }
4197
- if (resource.systemPath !== context.systemPath) {
4198
- addReadinessIssue(
4199
- issues,
4200
- "SYSTEM_INTERFACE_INVALID",
4201
- "resource-system-mismatch",
4202
- `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" scopes resource "${resourceId}" from system "${resource.systemPath}".`,
4203
- { path, ref: resourceId }
4204
- );
4205
- continue;
4206
- }
4207
- if (resource.status !== "active") {
4208
- addReadinessIssue(
4209
- issues,
4210
- "SYSTEM_INTERFACE_NOT_READY",
4211
- "inactive-resource",
4212
- `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" scopes inactive resource "${resourceId}".`,
4213
- { path, ref: resourceId }
4214
- );
4215
- continue;
4216
- }
4217
- resources.push(resource);
4218
- }
4219
- return resources;
4220
- }
4221
- function resourceBindingIds(resources, key) {
4222
- return new Set(resources.flatMap((resource) => resource.ontology?.[key] ?? []));
4223
- }
4224
- function requireScopedBinding(issues, boundIds, bindingKey, ontologyId, context) {
4225
- if (boundIds.has(ontologyId)) return;
4226
- addReadinessIssue(
4227
- issues,
4228
- "SYSTEM_INTERFACE_NOT_READY",
4229
- "missing-resource-binding",
4230
- `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" has no active scoped resource with ontology.${bindingKey} binding "${ontologyId}".`,
4231
- { path: `${readinessMarkerPath(context)}.resourceIds`, ref: ontologyId }
4232
- );
4233
- }
4234
- function ontologyOwnerMatches(ontologyId, expectedSystemPath, catalog) {
4235
- if (catalog?.ownerSystemId !== void 0) return catalog.ownerSystemId === expectedSystemPath;
4236
- return parseOntologyId(ontologyId).scope === expectedSystemPath;
4237
- }
4238
- function requireObjectReadiness(issues, index, objectId, context) {
4239
- const object = index.ontology.objectTypes[objectId];
4240
- if (object === void 0) {
4241
- addReadinessIssue(
4242
- issues,
4243
- "SYSTEM_INTERFACE_NOT_READY",
4244
- "missing-object",
4245
- `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" is missing required object type "${objectId}".`,
4246
- { ref: objectId }
4247
- );
4248
- return;
4249
- }
4250
- const ownerSystemId = object.ownerSystemId ?? parseOntologyId(objectId).scope;
4251
- if (ownerSystemId !== context.systemPath) {
4252
- addReadinessIssue(
4253
- issues,
4254
- "SYSTEM_INTERFACE_INVALID",
4255
- "foreign-object",
4256
- `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" requires object "${objectId}" owned by "${ownerSystemId}".`,
4257
- { ref: objectId }
4258
- );
4259
- }
4260
- }
4261
- function requireCatalogReadiness(issues, index, catalogId, context) {
4262
- const catalog = index.ontology.catalogTypes[catalogId];
4263
- if (catalog === void 0) {
4264
- addReadinessIssue(
4265
- issues,
4266
- "SYSTEM_INTERFACE_NOT_READY",
4267
- "missing-catalog",
4268
- `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" is missing required catalog "${catalogId}".`,
4269
- { ref: catalogId }
4270
- );
4271
- return void 0;
4272
- }
4273
- if (context.allowForeignOwner !== true && !ontologyOwnerMatches(catalogId, context.systemPath, catalog)) {
4274
- addReadinessIssue(
4275
- issues,
4276
- "SYSTEM_INTERFACE_INVALID",
4277
- "foreign-catalog",
4278
- `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" requires catalog "${catalogId}" owned by "${catalog.ownerSystemId ?? parseOntologyId(catalogId).scope}".`,
4279
- { ref: catalogId }
4280
- );
4281
- }
4282
- if (Object.keys(getCatalogEntries(catalog)).length === 0) {
4283
- addReadinessIssue(
4284
- issues,
4285
- "SYSTEM_INTERFACE_NOT_READY",
4286
- "empty-catalog",
4287
- `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" requires catalog entries for "${catalogId}".`,
4288
- { ref: catalogId }
4289
- );
4290
- }
4291
- return catalog;
4292
- }
4293
- function requireLeadGenInterfaceReadiness(issues, index, resources, context) {
4294
- const reads = resourceBindingIds(resources, "reads");
4295
- const catalogs = resourceBindingIds(resources, "usesCatalogs");
4296
- for (const objectId of [
4297
- LEAD_GEN_LIST_OBJECT_ONTOLOGY_ID,
4298
- LEAD_GEN_COMPANY_OBJECT_ONTOLOGY_ID,
4299
- LEAD_GEN_CONTACT_OBJECT_ONTOLOGY_ID
4300
- ]) {
4301
- requireObjectReadiness(issues, index, objectId, context);
4302
- requireScopedBinding(issues, reads, "reads", objectId, context);
4303
- }
4304
- for (const catalogId of [
4305
- LEAD_GEN_BUILD_TEMPLATE_CATALOG_ONTOLOGY_ID,
4306
- LEAD_GEN_COMPANY_STAGE_CATALOG_ONTOLOGY_ID,
4307
- LEAD_GEN_CONTACT_STAGE_CATALOG_ONTOLOGY_ID
4308
- ]) {
4309
- requireCatalogReadiness(issues, index, catalogId, context);
4310
- requireScopedBinding(issues, catalogs, "usesCatalogs", catalogId, context);
4311
- }
4312
- const templateStepCatalog = findLeadGenTemplateStepCatalog(index);
4313
- if (templateStepCatalog === void 0) {
4314
- addReadinessIssue(
4315
- issues,
4316
- "SYSTEM_INTERFACE_NOT_READY",
4317
- "missing-template-step-catalog",
4318
- `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" is missing a lead-gen template-step catalog.`
4319
- );
4320
- } else {
4321
- requireCatalogReadiness(issues, index, templateStepCatalog.id, context);
4322
- requireScopedBinding(issues, catalogs, "usesCatalogs", templateStepCatalog.id, context);
4323
- }
4324
- const leadGenStageCatalog = requireCatalogReadiness(issues, index, LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID, context);
4325
- return leadGenStageCatalog;
4326
- }
4327
- function requireCrmInterfaceReadiness(issues, index, resources, context) {
4328
- const catalogs = resourceBindingIds(resources, "usesCatalogs");
4329
- const crmPipelineCatalog = requireCatalogReadiness(issues, index, CRM_PIPELINE_CATALOG_ONTOLOGY_ID, context);
4330
- requireScopedBinding(issues, catalogs, "usesCatalogs", CRM_PIPELINE_CATALOG_ONTOLOGY_ID, context);
4331
- return crmPipelineCatalog;
4332
- }
4333
- function findSystemInterfaceGrant(model, consumer, provider) {
4334
- return Object.values(model.topology?.relationships ?? {}).find((relationship) => {
4335
- const grant = relationship.metadata?.["systemInterfaceGrant"];
4336
- if (!isPlainRecord(grant) || !isPlainRecord(grant.consumer) || !isPlainRecord(grant.provider)) return false;
4337
- return grant.consumer.systemPath === consumer.systemPath && grant.consumer.interfaceKey === consumer.interfaceKey && grant.provider.systemPath === provider.systemPath && grant.provider.interfaceKey === provider.interfaceKey;
4338
- });
4339
- }
4340
- function requireHandoffBridgeReadiness(issues, model, context) {
4341
- const crmResult = computeInterfaceReadiness(model, CRM_API_INTERFACE);
4342
- if (!crmResult.ready) {
4343
- for (const issue of crmResult.issues) {
4344
- addReadinessIssue(
4345
- issues,
4346
- "SYSTEM_BRIDGE_NOT_READY",
4347
- issue.code,
4348
- `Provider interface ${formatInterfaceIdentity(CRM_API_INTERFACE.systemPath, CRM_API_INTERFACE.interfaceKey)} is not ready: ${issue.message}`,
4349
- { path: issue.path, ref: issue.ref }
4350
- );
4351
- }
4352
- }
4353
- const bridgeGrant = findSystemInterfaceGrant(model, context, CRM_API_INTERFACE);
4354
- if (bridgeGrant === void 0) {
4355
- addReadinessIssue(
4356
- issues,
4357
- "SYSTEM_BRIDGE_NOT_READY",
4358
- "missing-topology-grant",
4359
- `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" requires a scoped topology grant to "${formatInterfaceIdentity(CRM_API_INTERFACE.systemPath, CRM_API_INTERFACE.interfaceKey)}".`
4360
- );
4361
- }
4362
- return bridgeGrant;
4363
- }
4364
- function getLeadGenCrmHandoffResourceIds(model) {
4365
- return Object.values(model.resources ?? {}).filter(
4366
- (resource) => resource.systemPath === LEAD_GEN_CRM_HANDOFF_INTERFACE.systemPath && resource.ontology?.usesCatalogs?.includes(CRM_PIPELINE_CATALOG_ONTOLOGY_ID) === true
4367
- ).map((resource) => resource.id);
4368
- }
4369
- function getSystemInterfaceReadinessMarker(model, request) {
4370
- const system = getSystem(model, request.systemPath);
4371
- if (system === void 0) return void 0;
4372
- if (request.systemPath === LEAD_GEN_CRM_HANDOFF_INTERFACE.systemPath && request.interfaceKey === LEAD_GEN_CRM_HANDOFF_INTERFACE.interfaceKey) {
4373
- return {
4374
- lifecycle: "active",
4375
- readinessProfile: LEAD_GEN_CRM_HANDOFF_INTERFACE.readinessProfile,
4376
- resourceIds: getLeadGenCrmHandoffResourceIds(model)
4377
- };
4378
- }
4379
- if (request.interfaceKey === "api" && system.apiInterface !== void 0) {
4380
- return system.apiInterface;
4381
- }
4382
- return void 0;
4383
- }
4384
- function mergeLeadGenDerivedCatalogs(model) {
4385
- const baseCatalogTypes = model.ontology?.catalogTypes ?? {};
4386
- const derivedCatalogTypes = {};
4387
- if (baseCatalogTypes[LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID] === void 0) {
4388
- derivedCatalogTypes[LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID] = createLeadGenStageCatalog(model);
4389
- }
4390
- if (Object.keys(derivedCatalogTypes).length === 0) return model;
4391
- return {
4392
- ...model,
4393
- ontology: {
4394
- ...model.ontology ?? {},
4395
- catalogTypes: {
4396
- ...baseCatalogTypes,
4397
- ...derivedCatalogTypes
4398
- }
4399
- }
4400
- };
4401
- }
4402
- function compileBusinessOntology(model, contractId) {
4403
- const compilation = compileOrganizationOntology(mergeLeadGenDerivedCatalogs(model));
4404
- if (compilation.diagnostics.length > 0) {
4405
- const summary = compilation.diagnostics.map((diagnostic) => diagnostic.message).join("; ");
4406
- throw new Error(`${contractId} ontology validation index failed to compile: ${summary}`);
4407
- }
4408
- return {
4409
- ontology: compilation.ontology,
4410
- actionTypesByLegacyId: indexActionTypesByLegacyId(compilation.ontology.actionTypes)
4411
- };
4412
- }
4413
- function tryCompileBusinessOntology(model, readinessProfile, issues) {
4414
- try {
4415
- return compileBusinessOntology(model, readinessProfile);
4416
- } catch (error) {
4417
- addReadinessIssue(
4418
- issues,
4419
- "SYSTEM_INTERFACE_INVALID",
4420
- "ontology-compile-failed",
4421
- error instanceof Error ? error.message : String(error)
4422
- );
4423
- return void 0;
4424
- }
4425
- }
4426
- function requireContractReadiness(issues, index, resources, contract, context) {
4427
- const reads = resourceBindingIds(resources, "reads");
4428
- const catalogs = resourceBindingIds(resources, "usesCatalogs");
4429
- for (const objectId of contract.requiredObjects) {
4430
- requireObjectReadiness(issues, index, objectId, context);
4431
- requireScopedBinding(issues, reads, "reads", objectId, context);
4432
- }
4433
- for (const catalogId of contract.requiredCatalogs) {
4434
- requireCatalogReadiness(issues, index, catalogId, context);
4435
- requireScopedBinding(issues, catalogs, "usesCatalogs", catalogId, context);
4436
- }
4437
- }
4438
- function computeInterfaceReadiness(model, request) {
4439
- const issues = [];
4440
- const system = getSystem(model, request.systemPath);
4441
- const systemInterface = getSystemInterfaceReadinessMarker(model, request);
4442
- const readinessProfile = systemInterface === void 0 ? void 0 : profileForInterface(request.systemPath, request.interfaceKey, systemInterface.readinessProfile);
4443
- const scopedResourceIds = systemInterface?.resourceIds ?? [];
4444
- if (system === void 0) {
4445
- addReadinessIssue(
4446
- issues,
4447
- "SYSTEM_INTERFACE_MISSING",
4448
- "missing-system",
4449
- `System "${request.systemPath}" is missing.`,
4450
- { ref: request.systemPath }
4451
- );
4452
- return {
4453
- ready: false,
4454
- systemPath: request.systemPath,
4455
- interfaceKey: request.interfaceKey,
4456
- scopedResourceIds,
4457
- issues
4458
- };
4459
- }
4460
- if (systemInterface === void 0) {
4461
- addReadinessIssue(
4462
- issues,
4463
- "SYSTEM_INTERFACE_MISSING",
4464
- "missing-interface",
4465
- `System "${request.systemPath}" does not declare interface "${request.interfaceKey}".`,
4466
- { path: readinessMarkerPath(request) }
4467
- );
4468
- return {
4469
- ready: false,
4470
- systemPath: request.systemPath,
4471
- interfaceKey: request.interfaceKey,
4472
- scopedResourceIds,
4473
- issues
4474
- };
4475
- }
4476
- if (systemInterface.lifecycle !== "active") {
4477
- addReadinessIssue(
4478
- issues,
4479
- "SYSTEM_INTERFACE_DISABLED",
4480
- "inactive-interface",
4481
- `System Interface "${formatInterfaceIdentity(request.systemPath, request.interfaceKey)}" lifecycle is "${systemInterface.lifecycle}".`,
4482
- { path: `${readinessMarkerPath(request)}.lifecycle` }
4483
- );
4484
- }
4485
- const checkedReadinessProfile = readinessProfile ?? profileForInterface(request.systemPath, request.interfaceKey);
4486
- const isBuiltIn = isBuiltInReadinessProfile(checkedReadinessProfile);
4487
- const readinessContract = systemInterface.readinessContract;
4488
- if (!isBuiltIn && readinessContract === void 0) {
4489
- addReadinessIssue(
4490
- issues,
4491
- "SYSTEM_INTERFACE_INVALID",
4492
- "missing-readiness-contract",
4493
- `System Interface "${formatInterfaceIdentity(request.systemPath, request.interfaceKey)}" uses custom readiness profile "${checkedReadinessProfile}" but declares no readinessContract. Built-in profiles: ${formatSupportedReadinessProfiles()}.`,
4494
- { path: `${readinessMarkerPath(request)}.readinessContract`, ref: checkedReadinessProfile }
4495
- );
4496
- return {
4497
- ready: false,
4498
- systemPath: request.systemPath,
4499
- interfaceKey: request.interfaceKey,
4500
- readinessProfile: checkedReadinessProfile,
4501
- scopedResourceIds,
4502
- issues
4503
- };
4504
- }
4505
- if (scopedResourceIds.length === 0) {
4506
- addReadinessIssue(
4507
- issues,
4508
- "SYSTEM_INTERFACE_NOT_READY",
4509
- "missing-scoped-resources",
4510
- `System Interface "${formatInterfaceIdentity(request.systemPath, request.interfaceKey)}" must scope at least one active resource.`,
4511
- { path: `${readinessMarkerPath(request)}.resourceIds` }
4512
- );
4513
- }
4514
- const resources = getActiveScopedResources(model, scopedResourceIds, issues, request);
4515
- const index = tryCompileBusinessOntology(model, checkedReadinessProfile, issues);
4516
- if (index !== void 0) {
4517
- if (checkedReadinessProfile === LEAD_GEN_API_INTERFACE.readinessProfile) {
4518
- requireLeadGenInterfaceReadiness(issues, index, resources, request);
4519
- } else if (checkedReadinessProfile === CRM_API_INTERFACE.readinessProfile) {
4520
- requireCrmInterfaceReadiness(issues, index, resources, request);
4521
- } else if (checkedReadinessProfile === LEAD_GEN_CRM_HANDOFF_INTERFACE.readinessProfile) {
4522
- requireLeadGenInterfaceReadiness(issues, index, resources, request);
4523
- requireCrmInterfaceReadiness(issues, index, resources, { ...request, allowForeignOwner: true });
4524
- requireHandoffBridgeReadiness(issues, model, request);
4525
- } else if (readinessContract !== void 0) {
4526
- requireContractReadiness(issues, index, resources, readinessContract, request);
4527
- }
4528
- }
4529
- return {
4530
- ready: issues.length === 0,
4531
- systemPath: request.systemPath,
4532
- interfaceKey: request.interfaceKey,
4533
- readinessProfile: checkedReadinessProfile,
4534
- scopedResourceIds,
4535
- issues
4536
- };
4537
- }
4538
- function requireObjectType(index, objectId, contractId) {
4539
- if (index.ontology.objectTypes[objectId] === void 0) {
4540
- throw new Error(`${contractId} is missing required object type: ${objectId}`);
4541
- }
4542
- }
4543
- function requireCatalog(index, catalogId, contractId) {
4544
- const catalog = index.ontology.catalogTypes[catalogId];
4545
- if (catalog === void 0) {
4546
- throw new Error(`${contractId} is missing required catalog: ${catalogId}`);
4547
- }
4548
- return catalog;
4549
- }
4550
- function requireCatalogEntries(catalog, contractId) {
4551
- if (Object.keys(getCatalogEntries(catalog)).length === 0) {
4552
- throw new Error(`${contractId} requires catalog entries for ${catalog.id}`);
4553
- }
4554
- }
4555
- function findLeadGenTemplateStepCatalog(index) {
4556
- return Object.values(index.ontology.catalogTypes).find(
4557
- (catalog) => catalog.ownerSystemId === "sales.lead-gen" && catalog.kind === "template-step" && catalog.appliesTo === LEAD_GEN_LIST_OBJECT_ONTOLOGY_ID
4558
- );
4559
- }
4560
- function requireLeadGenApiReadiness(index) {
4561
- requireObjectType(index, LEAD_GEN_LIST_OBJECT_ONTOLOGY_ID, LEAD_GEN_API_READINESS_LABEL);
4562
- requireObjectType(index, LEAD_GEN_COMPANY_OBJECT_ONTOLOGY_ID, LEAD_GEN_API_READINESS_LABEL);
4563
- requireObjectType(index, LEAD_GEN_CONTACT_OBJECT_ONTOLOGY_ID, LEAD_GEN_API_READINESS_LABEL);
4564
- requireCatalogEntries(
4565
- requireCatalog(index, LEAD_GEN_BUILD_TEMPLATE_CATALOG_ONTOLOGY_ID, LEAD_GEN_API_READINESS_LABEL),
4566
- LEAD_GEN_API_READINESS_LABEL
4567
- );
4568
- requireCatalogEntries(
4569
- requireCatalog(index, LEAD_GEN_COMPANY_STAGE_CATALOG_ONTOLOGY_ID, LEAD_GEN_API_READINESS_LABEL),
4570
- LEAD_GEN_API_READINESS_LABEL
4571
- );
4572
- requireCatalogEntries(
4573
- requireCatalog(index, LEAD_GEN_CONTACT_STAGE_CATALOG_ONTOLOGY_ID, LEAD_GEN_API_READINESS_LABEL),
4574
- LEAD_GEN_API_READINESS_LABEL
4575
- );
4576
- const templateStepCatalog = findLeadGenTemplateStepCatalog(index);
4577
- if (templateStepCatalog === void 0) {
4578
- throw new Error(`${LEAD_GEN_API_READINESS_LABEL} is missing a lead-gen template-step catalog`);
4579
- }
4580
- requireCatalogEntries(templateStepCatalog, LEAD_GEN_API_READINESS_LABEL);
4581
- const leadGenStageCatalog = requireCatalog(index, LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID, LEAD_GEN_API_READINESS_LABEL);
4582
- requireCatalogEntries(leadGenStageCatalog, LEAD_GEN_API_READINESS_LABEL);
4583
- return leadGenStageCatalog;
4584
- }
4585
- function requireCrmApiReadiness(index) {
4586
- const crmPipelineCatalog = requireCatalog(index, CRM_PIPELINE_CATALOG_ONTOLOGY_ID, CRM_API_READINESS_LABEL);
4587
- requireCatalogEntries(crmPipelineCatalog, CRM_API_READINESS_LABEL);
4588
- return crmPipelineCatalog;
4589
- }
4590
- function compileBusinessOntologyValidationIndex(model) {
4591
- throwIfInterfaceNotReady(computeInterfaceReadiness(model, LEAD_GEN_API_INTERFACE));
4592
- throwIfInterfaceNotReady(computeInterfaceReadiness(model, CRM_API_INTERFACE));
4593
- const index = compileBusinessOntology(model, "legacy acquisition business ontology");
4594
- return {
4595
- ...index,
4596
- leadGenStageCatalog: requireLeadGenApiReadiness(index),
4597
- crmPipelineCatalog: requireCrmApiReadiness(index)
4598
- };
4599
- }
4600
- function indexActionTypesByLegacyId(actionTypes) {
4601
- const byLegacyId = {};
4602
- for (const actionType of Object.values(actionTypes)) {
4603
- const legacyActionId = actionType["legacyActionId"];
4604
- if (typeof legacyActionId === "string") {
4605
- byLegacyId[legacyActionId] = actionType;
4606
- }
4607
- }
4608
- return byLegacyId;
4609
- }
4610
- function getCatalogEntries(catalog) {
4611
- return isPlainRecord(catalog.entries) ? catalog.entries : {};
4612
- }
4613
- function asLeadGenStageEntry(key, value) {
4614
- const record = isPlainRecord(value) ? value : {};
4615
- const entity = record.entity === "contact" ? "contact" : "company";
4616
- const additionalEntities = Array.isArray(record.additionalEntities) ? record.additionalEntities.filter(
4617
- (item) => item === "company" || item === "contact"
4618
- ) : void 0;
4619
- const recordEntity = record.recordEntity === "company" || record.recordEntity === "contact" ? record.recordEntity : void 0;
4620
- const recordStageKey = typeof record.recordStageKey === "string" ? record.recordStageKey : void 0;
4621
- return {
4622
- key: typeof record.key === "string" ? record.key : key,
4623
- label: typeof record.label === "string" ? record.label : key,
4624
- description: typeof record.description === "string" ? record.description : "",
4625
- order: typeof record.order === "number" ? record.order : 0,
4626
- entity,
4627
- ...additionalEntities !== void 0 ? { additionalEntities } : {},
4628
- ...recordEntity !== void 0 ? { recordEntity } : {},
4629
- ...recordStageKey !== void 0 ? { recordStageKey } : {}
4630
- };
4631
- }
4632
- function createLeadGenStageValidators(index) {
4633
- const getCatalog = () => Object.fromEntries(
4634
- Object.entries(getCatalogEntries(index.leadGenStageCatalog)).map(([key, value]) => [
4635
- key,
4636
- asLeadGenStageEntry(key, value)
4637
- ])
4638
- );
4639
- const getEntry = (stageKey) => getCatalog()[stageKey];
4640
- return {
4641
- getLeadGenStageCatalog: getCatalog,
4642
- getLeadGenStageEntry: getEntry,
4643
- isLeadGenStageKey: (stageKey) => getEntry(stageKey) !== void 0,
4644
- isLeadGenStageValidForEntity: (stageKey, entity) => {
4645
- const stage = getEntry(stageKey);
4646
- return stage !== void 0 && (stage.entity === entity || stage.additionalEntities?.includes(entity) === true);
4647
- },
4648
- isLeadGenRecordStageValidForEntity: (stageKey, entity) => {
4649
- const stage = getEntry(stageKey);
4650
- return stage !== void 0 && (stage.entity === entity || stage.additionalEntities?.includes(entity) === true || stage.recordEntity === entity);
4651
- },
4652
- resolveLeadGenRecordStageKey: (stageKey, entity) => {
4653
- const stage = getEntry(stageKey);
4654
- return stage?.recordEntity === entity && stage.recordStageKey ? stage.recordStageKey : stageKey;
4655
- }
4386
+ // never ages out, so one literal escape stored here is one the model re-reads forever.
4387
+ description: "Stored verbatim and replayed to you on every later turn. Write real line breaks and real quotation marks -- the two characters \\n are not a line break."
4388
+ }
4389
+ },
4390
+ required: ["key", "value"],
4391
+ additionalProperties: false
4392
+ }
4393
+ },
4394
+ delete: { type: "array", items: { type: "string" } }
4395
+ },
4396
+ additionalProperties: false
4397
+ };
4398
+ }
4399
+ return {
4400
+ type: "object",
4401
+ properties,
4402
+ required: capabilities.message === "required" ? ["nextActions", "message", "reasoning"] : ["nextActions", "reasoning"],
4403
+ additionalProperties: false
4656
4404
  };
4657
4405
  }
4658
4406
 
@@ -4833,14 +4581,12 @@ function addTopologyIssues(issues, orgName, deployment, organizationModel, syste
4833
4581
  const relationships = organizationModel.topology?.relationships;
4834
4582
  if (relationships === void 0) return;
4835
4583
  const rolesById = new Set(Object.keys(organizationModel.roles ?? {}));
4836
- const policiesById = new Set(Object.keys(organizationModel.policies ?? {}));
4837
4584
  const triggerIds = new Set(deployment.triggers?.map((trigger) => trigger.resourceId) ?? []);
4838
4585
  const humanCheckpointIds = new Set(deployment.humanCheckpoints?.map((checkpoint) => checkpoint.resourceId) ?? []);
4839
4586
  const externalResourceIds = new Set(deployment.externalResources?.map((external) => external.resourceId) ?? []);
4840
4587
  const topologyRefExists = (ref) => {
4841
4588
  if (ref.kind === "system") return systemsById.has(ref.id);
4842
4589
  if (ref.kind === "resource") return omResourcesById.has(ref.id);
4843
- if (ref.kind === "policy") return policiesById.has(ref.id);
4844
4590
  if (ref.kind === "role") return rolesById.has(ref.id);
4845
4591
  if (ref.kind === "trigger") return triggerIds.has(ref.id);
4846
4592
  if (ref.kind === "humanCheckpoint") return humanCheckpointIds.has(ref.id);
@@ -5023,7 +4769,6 @@ function validateDeclaredSystemInterfaceReadiness(orgName, organizationModel) {
5023
4769
  message: `System Interface "${path}/${interfaceKey}" references unknown readiness profile "${readinessProfile}".`
5024
4770
  });
5025
4771
  }
5026
- continue;
5027
4772
  }
5028
4773
  const result = computeInterfaceReadiness(model, { systemPath: path, interfaceKey });
5029
4774
  for (const issue of result.issues) {
@@ -7160,28 +6905,42 @@ z.object({
7160
6905
  limit: z.number().int(),
7161
6906
  offset: z.number().int()
7162
6907
  });
7163
- var AcqArtifactOwnerKindSchema = z.enum(["company", "contact", "deal", "list", "list_member"]);
6908
+ var AcqArtifactOwnerKindSchema = z.enum(["company", "contact", "deal", "list", "list_member", "organization"]);
7164
6909
  z.object({
7165
6910
  ownerKind: AcqArtifactOwnerKindSchema,
7166
- ownerId: UuidSchema
6911
+ ownerId: UuidSchema.optional()
7167
6912
  }).strict();
6913
+ var PipelineIdSchema = z.string().trim().min(1).max(255);
7168
6914
  z.object({
7169
6915
  ownerKind: AcqArtifactOwnerKindSchema,
7170
- ownerId: UuidSchema,
6916
+ // Nullable + optional: an org-owned artifact (ownerKind: 'organization') has no
6917
+ // single owning entity row. See the comment on AcqArtifactOwnerKindSchema above.
6918
+ ownerId: UuidSchema.nullable().optional(),
7171
6919
  kind: z.string().trim().min(1).max(255),
7172
6920
  content: z.record(z.string(), z.unknown()),
7173
- sourceExecutionId: UuidSchema.optional()
6921
+ sourceExecutionId: UuidSchema.optional(),
6922
+ // Nullable + optional: acquisition's own artifacts (audits, proposals, ICP docs) predate the
6923
+ // pipeline concept and have none. `getActiveArtifact` filters on it, so any artifact meant to
6924
+ // be resolvable as "the active document for pipeline X" MUST supply it -- artifacts-platform-tool
6925
+ // .mdx Step 3 defect 1.
6926
+ pipelineId: PipelineIdSchema.nullable().optional()
7174
6927
  }).strict();
7175
6928
  var AcqArtifactResponseSchema = z.object({
7176
6929
  id: z.string(),
7177
6930
  organizationId: z.string(),
7178
6931
  ownerKind: z.string(),
7179
- ownerId: z.string(),
6932
+ // Nullable as of content-pipeline-foundation D14: an org-owned artifact has no owning entity row.
6933
+ // CreateArtifactRequestSchema already accepted a null ownerId; this response schema not doing so
6934
+ // was Step 3 defect 2 -- an org-owned artifact inserted fine and then failed serialization.
6935
+ ownerId: z.string().nullable(),
7180
6936
  kind: z.string(),
6937
+ pipelineId: z.string().nullable(),
7181
6938
  content: z.record(z.string(), z.unknown()),
7182
6939
  sourceExecutionId: z.string().nullable(),
7183
6940
  createdBy: z.string().nullable(),
7184
6941
  createdAt: z.string(),
6942
+ updatedAt: z.string(),
6943
+ isActive: z.boolean(),
7185
6944
  version: z.number().int()
7186
6945
  });
7187
6946
  z.object({
@@ -7380,6 +7139,297 @@ function deriveActions(deal, actions = []) {
7380
7139
  return actions.filter((a) => a.isAvailableFor(deal)).map(({ key, label, payloadSchema }) => ({ key, label, payloadSchema }));
7381
7140
  }
7382
7141
 
7142
+ // ../core/src/business/acquisition/ontology-validation.ts
7143
+ var LEAD_GEN_API_INTERFACE = SYSTEM_INTERFACE_PROFILES[0];
7144
+ var CRM_API_INTERFACE = SYSTEM_INTERFACE_PROFILES[1];
7145
+ var LEAD_GEN_CRM_HANDOFF_INTERFACE = SYSTEM_INTERFACE_PROFILES[2];
7146
+ LEAD_GEN_API_INTERFACE.readinessProfile;
7147
+ CRM_API_INTERFACE.readinessProfile;
7148
+ LEAD_GEN_CRM_HANDOFF_INTERFACE.readinessProfile;
7149
+ var LEAD_GEN_LIST_OBJECT_ONTOLOGY_ID = formatOntologyId({
7150
+ scope: "sales.lead-gen",
7151
+ kind: "object",
7152
+ localId: "list"
7153
+ });
7154
+ var LEAD_GEN_COMPANY_OBJECT_ONTOLOGY_ID = formatOntologyId({
7155
+ scope: "sales.lead-gen",
7156
+ kind: "object",
7157
+ localId: "company"
7158
+ });
7159
+ var LEAD_GEN_CONTACT_OBJECT_ONTOLOGY_ID = formatOntologyId({
7160
+ scope: "sales.lead-gen",
7161
+ kind: "object",
7162
+ localId: "contact"
7163
+ });
7164
+ var LEAD_GEN_BUILD_TEMPLATE_CATALOG_ONTOLOGY_ID = formatOntologyId({
7165
+ scope: "sales.lead-gen",
7166
+ kind: "catalog",
7167
+ localId: "build-template"
7168
+ });
7169
+ var LEAD_GEN_COMPANY_STAGE_CATALOG_ONTOLOGY_ID = formatOntologyId({
7170
+ scope: "sales.lead-gen",
7171
+ kind: "catalog",
7172
+ localId: "company-stage"
7173
+ });
7174
+ var LEAD_GEN_CONTACT_STAGE_CATALOG_ONTOLOGY_ID = formatOntologyId({
7175
+ scope: "sales.lead-gen",
7176
+ kind: "catalog",
7177
+ localId: "contact-stage"
7178
+ });
7179
+ var CRM_PIPELINE_CATALOG_ONTOLOGY_ID = formatOntologyId({
7180
+ scope: "sales.crm",
7181
+ kind: "catalog",
7182
+ localId: "crm.pipeline"
7183
+ });
7184
+ var LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID = formatOntologyId({
7185
+ scope: "sales.lead-gen",
7186
+ kind: "catalog",
7187
+ localId: "lead-gen.stage-catalog"
7188
+ });
7189
+ var LEAD_GEN_API_READINESS_CONTRACT = {
7190
+ requiredObjects: [
7191
+ LEAD_GEN_LIST_OBJECT_ONTOLOGY_ID,
7192
+ LEAD_GEN_COMPANY_OBJECT_ONTOLOGY_ID,
7193
+ LEAD_GEN_CONTACT_OBJECT_ONTOLOGY_ID
7194
+ ],
7195
+ requiredCatalogs: [
7196
+ LEAD_GEN_BUILD_TEMPLATE_CATALOG_ONTOLOGY_ID,
7197
+ LEAD_GEN_COMPANY_STAGE_CATALOG_ONTOLOGY_ID,
7198
+ LEAD_GEN_CONTACT_STAGE_CATALOG_ONTOLOGY_ID
7199
+ ]
7200
+ };
7201
+ var CRM_API_READINESS_CONTRACT = {
7202
+ requiredObjects: [],
7203
+ requiredCatalogs: [CRM_PIPELINE_CATALOG_ONTOLOGY_ID]
7204
+ };
7205
+ function isPlainRecord2(value) {
7206
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
7207
+ }
7208
+ function createLeadGenStageCatalog(model) {
7209
+ return {
7210
+ id: LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID,
7211
+ label: "Lead Gen Processing Stages",
7212
+ ownerSystemId: "sales.lead-gen",
7213
+ kind: "processing-stage-catalog",
7214
+ entries: Object.fromEntries(
7215
+ Object.entries(getLeadGenStageCatalog(model)).map(([key, entry]) => [
7216
+ key,
7217
+ {
7218
+ ...entry
7219
+ }
7220
+ ])
7221
+ ),
7222
+ legacyCatalogKey: "LEAD_GEN_STAGE_CATALOG"
7223
+ };
7224
+ }
7225
+ function throwIfInterfaceNotReady(result) {
7226
+ if (result.ready) return;
7227
+ throw new SystemInterfaceReadinessError(result);
7228
+ }
7229
+ function requireLeadGenSupplementalReadiness(issues, index, resources, context) {
7230
+ const catalogs = resourceBindingIds(resources, "usesCatalogs");
7231
+ const templateStepCatalog = findLeadGenTemplateStepCatalog(index);
7232
+ if (templateStepCatalog === void 0) {
7233
+ addReadinessIssue(
7234
+ issues,
7235
+ "SYSTEM_INTERFACE_NOT_READY",
7236
+ "missing-template-step-catalog",
7237
+ `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" is missing a lead-gen template-step catalog.`
7238
+ );
7239
+ } else {
7240
+ requireCatalogReadiness(issues, index, templateStepCatalog.id, context);
7241
+ requireScopedBinding(issues, catalogs, "usesCatalogs", templateStepCatalog.id, context);
7242
+ }
7243
+ requireCatalogReadiness(issues, index, LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID, context);
7244
+ }
7245
+ function requireLeadGenInterfaceReadiness(issues, index, resources, context) {
7246
+ requireContractReadiness(issues, index, resources, LEAD_GEN_API_READINESS_CONTRACT, context);
7247
+ requireLeadGenSupplementalReadiness(issues, index, resources, context);
7248
+ }
7249
+ function requireCrmInterfaceReadiness(issues, index, resources, context) {
7250
+ requireContractReadiness(issues, index, resources, CRM_API_READINESS_CONTRACT, context);
7251
+ }
7252
+ function findSystemInterfaceGrant(model, consumer, provider) {
7253
+ return Object.values(model.topology?.relationships ?? {}).find((relationship) => {
7254
+ const grant = relationship.metadata?.["systemInterfaceGrant"];
7255
+ if (!isPlainRecord2(grant) || !isPlainRecord2(grant.consumer) || !isPlainRecord2(grant.provider)) return false;
7256
+ return grant.consumer.systemPath === consumer.systemPath && grant.consumer.interfaceKey === consumer.interfaceKey && grant.provider.systemPath === provider.systemPath && grant.provider.interfaceKey === provider.interfaceKey;
7257
+ });
7258
+ }
7259
+ function requireHandoffBridgeReadiness(issues, model, context) {
7260
+ const crmResult = computeInterfaceReadiness(model, CRM_API_INTERFACE);
7261
+ if (!crmResult.ready) {
7262
+ for (const issue of crmResult.issues) {
7263
+ addReadinessIssue(
7264
+ issues,
7265
+ "SYSTEM_BRIDGE_NOT_READY",
7266
+ issue.code,
7267
+ `Provider interface ${formatInterfaceIdentity(CRM_API_INTERFACE.systemPath, CRM_API_INTERFACE.interfaceKey)} is not ready: ${issue.message}`,
7268
+ { path: issue.path, ref: issue.ref }
7269
+ );
7270
+ }
7271
+ }
7272
+ const bridgeGrant = findSystemInterfaceGrant(model, context, CRM_API_INTERFACE);
7273
+ if (bridgeGrant === void 0) {
7274
+ addReadinessIssue(
7275
+ issues,
7276
+ "SYSTEM_BRIDGE_NOT_READY",
7277
+ "missing-topology-grant",
7278
+ `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" requires a scoped topology grant to "${formatInterfaceIdentity(CRM_API_INTERFACE.systemPath, CRM_API_INTERFACE.interfaceKey)}".`
7279
+ );
7280
+ }
7281
+ return bridgeGrant;
7282
+ }
7283
+ function getLeadGenCrmHandoffResourceIds(model) {
7284
+ return Object.values(model.resources ?? {}).filter(
7285
+ (resource) => resource.systemPath === LEAD_GEN_CRM_HANDOFF_INTERFACE.systemPath && resource.ontology?.usesCatalogs?.includes(CRM_PIPELINE_CATALOG_ONTOLOGY_ID) === true
7286
+ ).map((resource) => resource.id);
7287
+ }
7288
+ function mergeLeadGenDerivedCatalogs(model) {
7289
+ const baseCatalogTypes = model.ontology?.catalogTypes ?? {};
7290
+ const derivedCatalogTypes = {};
7291
+ if (baseCatalogTypes[LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID] === void 0) {
7292
+ derivedCatalogTypes[LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID] = createLeadGenStageCatalog(model);
7293
+ }
7294
+ if (Object.keys(derivedCatalogTypes).length === 0) return model;
7295
+ return {
7296
+ ...model,
7297
+ ontology: {
7298
+ ...model.ontology ?? {},
7299
+ catalogTypes: {
7300
+ ...baseCatalogTypes,
7301
+ ...derivedCatalogTypes
7302
+ }
7303
+ }
7304
+ };
7305
+ }
7306
+ function compileBusinessOntology(model, contractId, includeLeadGenDerivedCatalogs) {
7307
+ const preparedModel = mergeLeadGenDerivedCatalogs(model) ;
7308
+ const compilation = compileOrganizationOntology(preparedModel);
7309
+ if (compilation.diagnostics.length > 0) {
7310
+ const summary = compilation.diagnostics.map((diagnostic) => diagnostic.message).join("; ");
7311
+ throw new Error(`${contractId} ontology validation index failed to compile: ${summary}`);
7312
+ }
7313
+ return {
7314
+ ontology: compilation.ontology,
7315
+ actionTypesByLegacyId: indexActionTypesByLegacyId(compilation.ontology.actionTypes)
7316
+ };
7317
+ }
7318
+ registerBuiltInReadinessProfile(LEAD_GEN_API_INTERFACE.readinessProfile, {
7319
+ validate: (issues, index, resources, _model, context) => requireLeadGenInterfaceReadiness(issues, index, resources, context),
7320
+ prepareModel: mergeLeadGenDerivedCatalogs
7321
+ });
7322
+ registerBuiltInReadinessProfile(CRM_API_INTERFACE.readinessProfile, {
7323
+ validate: (issues, index, resources, _model, context) => requireCrmInterfaceReadiness(issues, index, resources, context)
7324
+ });
7325
+ registerBuiltInReadinessProfile(LEAD_GEN_CRM_HANDOFF_INTERFACE.readinessProfile, {
7326
+ validate: (issues, index, resources, model, context) => {
7327
+ requireLeadGenInterfaceReadiness(issues, index, resources, context);
7328
+ requireCrmInterfaceReadiness(issues, index, resources, { ...context, allowForeignOwner: true });
7329
+ requireHandoffBridgeReadiness(issues, model, context);
7330
+ },
7331
+ prepareModel: mergeLeadGenDerivedCatalogs
7332
+ });
7333
+ registerReadinessInterfaceMarker(
7334
+ LEAD_GEN_CRM_HANDOFF_INTERFACE.systemPath,
7335
+ LEAD_GEN_CRM_HANDOFF_INTERFACE.interfaceKey,
7336
+ (model) => ({
7337
+ lifecycle: "active",
7338
+ readinessProfile: LEAD_GEN_CRM_HANDOFF_INTERFACE.readinessProfile,
7339
+ resourceIds: getLeadGenCrmHandoffResourceIds(model)
7340
+ })
7341
+ );
7342
+ function findLeadGenTemplateStepCatalog(index) {
7343
+ return Object.values(index.ontology.catalogTypes).find(
7344
+ (catalog) => catalog.ownerSystemId === "sales.lead-gen" && catalog.kind === "template-step" && catalog.appliesTo === LEAD_GEN_LIST_OBJECT_ONTOLOGY_ID
7345
+ );
7346
+ }
7347
+ function requireReadyCatalog(index, catalogId, readinessLabel) {
7348
+ const catalog = index.ontology.catalogTypes[catalogId];
7349
+ if (catalog === void 0) {
7350
+ throw new Error(
7351
+ `${readinessLabel} readiness passed but catalog "${catalogId}" is unexpectedly absent from the compiled ontology.`
7352
+ );
7353
+ }
7354
+ return catalog;
7355
+ }
7356
+ function compileBusinessOntologyValidationIndex(model) {
7357
+ throwIfInterfaceNotReady(computeInterfaceReadiness(model, LEAD_GEN_API_INTERFACE));
7358
+ throwIfInterfaceNotReady(computeInterfaceReadiness(model, CRM_API_INTERFACE));
7359
+ const index = compileBusinessOntology(model, "legacy acquisition business ontology");
7360
+ return {
7361
+ ...index,
7362
+ leadGenStageCatalog: requireReadyCatalog(
7363
+ index,
7364
+ LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID,
7365
+ "legacy acquisition business ontology"
7366
+ ),
7367
+ crmPipelineCatalog: requireReadyCatalog(
7368
+ index,
7369
+ CRM_PIPELINE_CATALOG_ONTOLOGY_ID,
7370
+ "legacy acquisition business ontology"
7371
+ )
7372
+ };
7373
+ }
7374
+ function indexActionTypesByLegacyId(actionTypes) {
7375
+ const byLegacyId = {};
7376
+ for (const actionType of Object.values(actionTypes)) {
7377
+ const legacyActionId = actionType["legacyActionId"];
7378
+ if (typeof legacyActionId === "string") {
7379
+ byLegacyId[legacyActionId] = actionType;
7380
+ }
7381
+ }
7382
+ return byLegacyId;
7383
+ }
7384
+ function getCatalogEntries2(catalog) {
7385
+ return isPlainRecord2(catalog.entries) ? catalog.entries : {};
7386
+ }
7387
+ function asLeadGenStageEntry(key, value) {
7388
+ const record = isPlainRecord2(value) ? value : {};
7389
+ const entity = record.entity === "contact" ? "contact" : "company";
7390
+ const additionalEntities = Array.isArray(record.additionalEntities) ? record.additionalEntities.filter(
7391
+ (item) => item === "company" || item === "contact"
7392
+ ) : void 0;
7393
+ const recordEntity = record.recordEntity === "company" || record.recordEntity === "contact" ? record.recordEntity : void 0;
7394
+ const recordStageKey = typeof record.recordStageKey === "string" ? record.recordStageKey : void 0;
7395
+ return {
7396
+ key: typeof record.key === "string" ? record.key : key,
7397
+ label: typeof record.label === "string" ? record.label : key,
7398
+ description: typeof record.description === "string" ? record.description : "",
7399
+ order: typeof record.order === "number" ? record.order : 0,
7400
+ entity,
7401
+ ...additionalEntities !== void 0 ? { additionalEntities } : {},
7402
+ ...recordEntity !== void 0 ? { recordEntity } : {},
7403
+ ...recordStageKey !== void 0 ? { recordStageKey } : {}
7404
+ };
7405
+ }
7406
+ function createLeadGenStageValidators(index) {
7407
+ const getCatalog = () => Object.fromEntries(
7408
+ Object.entries(getCatalogEntries2(index.leadGenStageCatalog)).map(([key, value]) => [
7409
+ key,
7410
+ asLeadGenStageEntry(key, value)
7411
+ ])
7412
+ );
7413
+ const getEntry = (stageKey) => getCatalog()[stageKey];
7414
+ return {
7415
+ getLeadGenStageCatalog: getCatalog,
7416
+ getLeadGenStageEntry: getEntry,
7417
+ isLeadGenStageKey: (stageKey) => getEntry(stageKey) !== void 0,
7418
+ isLeadGenStageValidForEntity: (stageKey, entity) => {
7419
+ const stage = getEntry(stageKey);
7420
+ return stage !== void 0 && (stage.entity === entity || stage.additionalEntities?.includes(entity) === true);
7421
+ },
7422
+ isLeadGenRecordStageValidForEntity: (stageKey, entity) => {
7423
+ const stage = getEntry(stageKey);
7424
+ return stage !== void 0 && (stage.entity === entity || stage.additionalEntities?.includes(entity) === true || stage.recordEntity === entity);
7425
+ },
7426
+ resolveLeadGenRecordStageKey: (stageKey, entity) => {
7427
+ const stage = getEntry(stageKey);
7428
+ return stage?.recordEntity === entity && stage.recordStageKey ? stage.recordStageKey : stageKey;
7429
+ }
7430
+ };
7431
+ }
7432
+
7383
7433
  // src/project-deployment-spec.ts
7384
7434
  function toSdkResourceDescriptor(resource, getResourceOntologyBinding) {
7385
7435
  const ontologyBinding = getResourceOntologyBinding?.(resource.id);
@@ -7528,4 +7578,4 @@ function defineWorkflowConfig(resourceId, descriptors, actionRegistry = []) {
7528
7578
  }
7529
7579
  var ListBuilderStageKeySchema = z.string().min(1);
7530
7580
 
7531
- export { ActivityEventSchema, BuildPlanSnapshotStepSchema, ProspectingBuildTemplateSchema as BuildTemplateSchema, ContractRefResolutionError, CrmStageKeySchema, CrmStateKeySchema, EmailSchema, ExecutionError, ListBuilderStageKeySchema, ProcessingStageStatusSchema, RegistryValidationError, ResourceRegistry, StepType, ToolingError, bindResourceDescriptor, compileBusinessOntologyValidationIndex, concurrentPool, createLeadGenStageValidators, defineContract, defineResource, defineResourceOntology, defineResources, defineStep, defineTopology, defineTopologyRelationship, defineWorkflow, defineWorkflowConfig, deriveActions, diagnosticOutput, integrationInput, isBuiltInReadinessProfile, isZodType, lookupReadinessProfile, parseTopologyNodeRef, profileForInterface, projectDeploymentSpec, projectTopologyRelationships, registerReadinessProfile, resolveContractRef, runDiagnostic, splitName, toSdkResourceDescriptor, topologyRef, topologyRelationship, validateDeclaredSystemInterfaceReadiness, validateResourceGovernance, withPlatformAgentResourceDescriptor, withPlatformAgentResourceDescriptors, withPlatformIntegrationResourceDescriptor, withPlatformIntegrationResourceDescriptors, withPlatformResourceDescriptor, withPlatformResourceDescriptors };
7581
+ export { ActivityEventSchema, BuildPlanSnapshotStepSchema, ProspectingBuildTemplateSchema as BuildTemplateSchema, ContractRefResolutionError, CrmStageKeySchema, CrmStateKeySchema, EmailSchema, ExecutionError, ListBuilderStageKeySchema, ProcessingStageStatusSchema, RegistryValidationError, ResourceRegistry, StepType, ToolingError, bindResourceDescriptor, compileBusinessOntologyValidationIndex, concurrentPool, createLeadGenStageValidators, defineContract, defineResource, defineResourceOntology, defineResources, defineStep, defineTopology, defineTopologyRelationship, defineWorkflow, defineWorkflowConfig, deriveActions, diagnosticOutput, integrationInput, isBuiltInReadinessProfile, isZodType, lookupReadinessProfile, parseTopologyNodeRef, projectDeploymentSpec, projectTopologyRelationships, registerReadinessProfile, resolveContractRef, runDiagnostic, splitName, toSdkResourceDescriptor, topologyRef, topologyRelationship, validateDeclaredSystemInterfaceReadiness, validateResourceGovernance, withPlatformAgentResourceDescriptor, withPlatformAgentResourceDescriptors, withPlatformIntegrationResourceDescriptor, withPlatformIntegrationResourceDescriptors, withPlatformResourceDescriptor, withPlatformResourceDescriptors };