@elevasis/sdk 1.21.0 → 1.22.1

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 (160) hide show
  1. package/dist/cli.cjs +1239 -173
  2. package/dist/index.d.ts +1752 -464
  3. package/dist/index.js +3477 -143
  4. package/dist/node/index.d.ts +1 -0
  5. package/dist/node/index.js +19 -1
  6. package/dist/test-utils/index.d.ts +1188 -127
  7. package/dist/test-utils/index.js +3359 -152
  8. package/dist/worker/index.js +3148 -80
  9. package/package.json +2 -2
  10. package/reference/claude-config/hooks/post-edit-validate.mjs +98 -98
  11. package/reference/claude-config/hooks/scaffold-registry-reminder.mjs +188 -188
  12. package/reference/claude-config/hooks/tool-failure-recovery.mjs +73 -73
  13. package/reference/claude-config/registries/graph-skills.json +4 -4
  14. package/reference/claude-config/registries/knowledge-flags.json +0 -2
  15. package/reference/claude-config/rules/active-change-index.md +80 -80
  16. package/reference/claude-config/rules/agent-start-here.md +277 -277
  17. package/reference/claude-config/rules/deployment.md +57 -57
  18. package/reference/claude-config/rules/error-handling.md +56 -56
  19. package/reference/claude-config/rules/execution.md +40 -40
  20. package/reference/claude-config/rules/frontend.md +4 -4
  21. package/reference/claude-config/rules/observability.md +31 -31
  22. package/reference/claude-config/rules/operations.md +29 -17
  23. package/reference/claude-config/rules/organization-model.md +113 -81
  24. package/reference/claude-config/rules/organization-os.md +115 -113
  25. package/reference/claude-config/rules/package-taxonomy.md +33 -33
  26. package/reference/claude-config/rules/platform.md +42 -42
  27. package/reference/claude-config/rules/shared-types.md +49 -46
  28. package/reference/claude-config/rules/task-tracking.md +47 -47
  29. package/reference/claude-config/rules/ui.md +200 -200
  30. package/reference/claude-config/rules/vibe.md +235 -235
  31. package/reference/claude-config/scripts/statusline-command.js +18 -18
  32. package/reference/claude-config/settings.json +34 -34
  33. package/reference/claude-config/skills/deploy/{SKILL.md → skill.md} +156 -156
  34. package/reference/claude-config/skills/dsp/SKILL.md +66 -66
  35. package/reference/claude-config/skills/elevasis/SKILL.md +235 -235
  36. package/reference/claude-config/skills/explore/SKILL.md +6 -6
  37. package/reference/claude-config/skills/git-sync/SKILL.md +126 -126
  38. package/reference/claude-config/skills/knowledge/SKILL.md +314 -299
  39. package/reference/claude-config/skills/knowledge/operations/codify-level-a.md +100 -100
  40. package/reference/claude-config/skills/knowledge/operations/codify-level-b.md +159 -159
  41. package/reference/claude-config/skills/knowledge/operations/customers.md +109 -109
  42. package/reference/claude-config/skills/knowledge/operations/features.md +76 -76
  43. package/reference/claude-config/skills/knowledge/operations/goals.md +118 -118
  44. package/reference/claude-config/skills/knowledge/operations/identity.md +93 -93
  45. package/reference/claude-config/skills/knowledge/operations/labels.md +94 -94
  46. package/reference/claude-config/skills/knowledge/operations/offerings.md +109 -109
  47. package/reference/claude-config/skills/knowledge/operations/roles.md +99 -99
  48. package/reference/claude-config/skills/knowledge/operations/techStack.md +30 -30
  49. package/reference/claude-config/skills/project/SKILL.md +1088 -1088
  50. package/reference/claude-config/skills/run-ui/SKILL.md +73 -73
  51. package/reference/claude-config/skills/save/SKILL.md +3 -3
  52. package/reference/claude-config/skills/setup/SKILL.md +275 -275
  53. package/reference/claude-config/skills/status/SKILL.md +59 -59
  54. package/reference/claude-config/skills/submit-request/SKILL.md +180 -180
  55. package/reference/claude-config/skills/sync/SKILL.md +47 -47
  56. package/reference/claude-config/skills/tutorial/SKILL.md +259 -259
  57. package/reference/claude-config/skills/tutorial/progress-template.md +74 -74
  58. package/reference/claude-config/skills/tutorial/technical.md +1303 -1303
  59. package/reference/claude-config/skills/tutorial/vibe-coder.md +890 -890
  60. package/reference/claude-config/sync-notes/2026-04-22-git-sync-and-sync-notes.md +27 -27
  61. package/reference/claude-config/sync-notes/2026-04-22-lead-gen-deliverability-removal.md +30 -30
  62. package/reference/claude-config/sync-notes/2026-04-24-test-utils-and-template-tests.md +73 -73
  63. package/reference/claude-config/sync-notes/2026-04-24-ui-consolidation-and-sdk-cli-train.md +86 -86
  64. package/reference/claude-config/sync-notes/2026-04-25-auth-role-system-and-settings-roles.md +55 -55
  65. package/reference/claude-config/sync-notes/2026-04-27-crm-hitl-action-layer-cutover.md +97 -97
  66. package/reference/claude-config/sync-notes/2026-04-27-lead-gen-substrate-train.md +112 -112
  67. package/reference/claude-config/sync-notes/2026-04-29-crm-state-and-lead-gen-processing-status.md +93 -93
  68. package/reference/claude-config/sync-notes/2026-05-02-crm-ownership-next-action.md +58 -58
  69. package/reference/claude-config/sync-notes/2026-05-02-template-hardcode-workos-config.md +56 -56
  70. package/reference/claude-config/sync-notes/2026-05-04-elevasis-workspace.md +71 -71
  71. package/reference/claude-config/sync-notes/2026-05-04-knowledge-bundle.md +83 -83
  72. package/reference/claude-config/sync-notes/2026-05-04-template-skills-run-ui-and-tutorial.md +59 -59
  73. package/reference/claude-config/sync-notes/2026-05-05-list-builder.md +42 -42
  74. package/reference/claude-config/sync-notes/2026-05-06-crm-spine.md +60 -60
  75. package/reference/claude-config/sync-notes/2026-05-06-sdk-changes-release-train.md +37 -37
  76. package/reference/claude-config/sync-notes/2026-05-07-sdk-changes-release-train.md +34 -34
  77. package/reference/claude-config/sync-notes/2026-05-08-resource-governance-scaffold-guidance.md +38 -38
  78. package/reference/claude-config/sync-notes/2026-05-09-clients-domain.md +32 -32
  79. package/reference/claude-config/sync-notes/2026-05-09-command-system.md +33 -33
  80. package/reference/claude-config/sync-notes/2026-05-09-resource-governance-and-misc.md +69 -69
  81. package/reference/claude-config/sync-notes/2026-05-12-sdk-ready-release-train.md +30 -30
  82. package/reference/claude-config/sync-notes/2026-05-14-organization-model-ontology-refactor.md +45 -0
  83. package/reference/claude-config/sync-notes/README.md +43 -43
  84. package/reference/cli.mdx +808 -808
  85. package/reference/concepts.mdx +146 -146
  86. package/reference/deployment/api.mdx +297 -297
  87. package/reference/deployment/command-center.mdx +209 -209
  88. package/reference/deployment/index.mdx +195 -195
  89. package/reference/deployment/provided-features.mdx +107 -107
  90. package/reference/deployment/ui-execution.mdx +250 -250
  91. package/reference/examples/organization-model.ts +171 -84
  92. package/reference/framework/agent.mdx +156 -156
  93. package/reference/framework/index.mdx +195 -195
  94. package/reference/framework/interaction-guidance.mdx +182 -182
  95. package/reference/framework/memory.mdx +326 -326
  96. package/reference/framework/project-structure.mdx +282 -282
  97. package/reference/framework/tutorial-system.mdx +135 -135
  98. package/reference/getting-started.mdx +142 -142
  99. package/reference/index.mdx +106 -106
  100. package/reference/packages/core/src/README.md +14 -14
  101. package/reference/packages/core/src/business/README.md +2 -2
  102. package/reference/packages/core/src/knowledge/README.md +32 -32
  103. package/reference/packages/core/src/organization-model/README.md +149 -149
  104. package/reference/packages/core/src/test-utils/README.md +37 -37
  105. package/reference/packages/ui/src/api/README.md +18 -18
  106. package/reference/packages/ui/src/app/README.md +24 -24
  107. package/reference/packages/ui/src/auth/README.md +18 -18
  108. package/reference/packages/ui/src/components/README.md +24 -24
  109. package/reference/packages/ui/src/execution/README.md +16 -16
  110. package/reference/packages/ui/src/features/README.md +28 -28
  111. package/reference/packages/ui/src/graph/README.md +16 -16
  112. package/reference/packages/ui/src/hooks/README.md +23 -23
  113. package/reference/packages/ui/src/initialization/README.md +19 -19
  114. package/reference/packages/ui/src/knowledge/README.md +31 -31
  115. package/reference/packages/ui/src/organization/README.md +18 -18
  116. package/reference/packages/ui/src/profile/README.md +19 -19
  117. package/reference/packages/ui/src/provider/README.md +32 -32
  118. package/reference/packages/ui/src/router/README.md +18 -18
  119. package/reference/packages/ui/src/sse/README.md +13 -13
  120. package/reference/packages/ui/src/test-utils/README.md +7 -7
  121. package/reference/packages/ui/src/theme/README.md +23 -23
  122. package/reference/packages/ui/src/theme/presets/README.md +19 -19
  123. package/reference/packages/ui/src/types/README.md +16 -16
  124. package/reference/packages/ui/src/utils/README.md +18 -18
  125. package/reference/packages/ui/src/zustand/README.md +18 -18
  126. package/reference/platform-tools/adapters-integration.mdx +301 -301
  127. package/reference/platform-tools/adapters-platform.mdx +553 -553
  128. package/reference/platform-tools/index.mdx +217 -217
  129. package/reference/platform-tools/type-safety.mdx +82 -82
  130. package/reference/resources/index.mdx +349 -349
  131. package/reference/resources/patterns.mdx +449 -449
  132. package/reference/resources/types.mdx +116 -116
  133. package/reference/roadmap.mdx +165 -165
  134. package/reference/runtime.mdx +173 -173
  135. package/reference/scaffold/core/organization-graph.mdx +110 -90
  136. package/reference/scaffold/core/organization-model.mdx +225 -213
  137. package/reference/scaffold/index.mdx +67 -67
  138. package/reference/scaffold/operations/propagation-pipeline.md +77 -77
  139. package/reference/scaffold/operations/scaffold-maintenance.md +12 -12
  140. package/reference/scaffold/operations/workflow-recipes.md +138 -138
  141. package/reference/scaffold/recipes/add-a-feature.md +307 -85
  142. package/reference/scaffold/recipes/add-a-resource.md +137 -103
  143. package/reference/scaffold/recipes/customize-knowledge-browser.md +5 -5
  144. package/reference/scaffold/recipes/customize-organization-model.md +275 -138
  145. package/reference/scaffold/recipes/extend-a-base-entity.md +8 -8
  146. package/reference/scaffold/recipes/extend-crm.md +3 -3
  147. package/reference/scaffold/recipes/extend-lead-gen.md +394 -394
  148. package/reference/scaffold/recipes/gate-by-feature-or-admin.md +118 -118
  149. package/reference/scaffold/recipes/index.md +46 -46
  150. package/reference/scaffold/recipes/query-the-knowledge-graph.md +197 -170
  151. package/reference/scaffold/reference/contracts.md +2136 -2093
  152. package/reference/scaffold/reference/glossary.md +76 -76
  153. package/reference/scaffold/ui/composition-extensibility.mdx +233 -233
  154. package/reference/scaffold/ui/customization.md +243 -243
  155. package/reference/scaffold/ui/feature-flags-and-gating.md +46 -46
  156. package/reference/scaffold/ui/feature-shell.mdx +72 -72
  157. package/reference/scaffold/ui/recipes.md +221 -214
  158. package/reference/spine/spine-primer.md +96 -96
  159. package/reference/templates/index.mdx +47 -47
  160. package/reference/troubleshooting.mdx +223 -223
@@ -6512,73 +6512,78 @@ Fix the errors and generate a valid output.
6512
6512
  }
6513
6513
  };
6514
6514
  var ORGANIZATION_MODEL_ICON_TOKENS = [
6515
- "nav.dashboard",
6516
- "nav.calendar",
6517
- "nav.sales",
6518
- "nav.crm",
6519
- "nav.lead-gen",
6520
- "nav.projects",
6521
- "nav.operations",
6522
- "nav.monitoring",
6523
- "nav.knowledge",
6524
- "nav.settings",
6525
- "nav.admin",
6526
- "nav.archive",
6527
- "knowledge.playbook",
6528
- "knowledge.strategy",
6529
- "knowledge.reference",
6530
- "feature.dashboard",
6531
- "feature.calendar",
6532
- "feature.business",
6533
- "feature.sales",
6534
- "feature.crm",
6535
- "feature.finance",
6536
- "feature.lead-gen",
6537
- "feature.platform",
6538
- "feature.projects",
6539
- "feature.operations",
6540
- "feature.knowledge",
6541
- "feature.monitoring",
6542
- "feature.settings",
6543
- "feature.admin",
6544
- "feature.archive",
6545
- "feature.seo",
6546
- "resource.agent",
6547
- "resource.workflow",
6548
- "resource.integration",
6549
- "resource.database",
6550
- "resource.user",
6551
- "resource.team",
6552
- "integration.gmail",
6553
- "integration.google-sheets",
6554
- "integration.attio",
6555
- "surface.dashboard",
6556
- "surface.calendar",
6557
- "surface.overview",
6558
- "surface.command-view",
6559
- "surface.command-queue",
6560
- "surface.pipeline",
6561
- "surface.lists",
6562
- "surface.resources",
6563
- "surface.settings",
6564
- "status.success",
6565
- "status.error",
6566
- "status.warning",
6567
- "status.info",
6568
- "status.pending",
6569
- "action.approve",
6570
- "action.reject",
6571
- "action.retry",
6572
- "action.edit",
6573
- "action.view",
6574
- "action.launch",
6575
- "action.message",
6576
- "action.escalate",
6577
- "action.promote",
6578
- "action.submit",
6579
- "action.email"
6515
+ // Navigation / app areas
6516
+ "dashboard",
6517
+ "calendar",
6518
+ "sales",
6519
+ "crm",
6520
+ "lead-gen",
6521
+ "projects",
6522
+ "operations",
6523
+ "monitoring",
6524
+ "knowledge",
6525
+ "settings",
6526
+ "admin",
6527
+ "archive",
6528
+ "business",
6529
+ "finance",
6530
+ "platform",
6531
+ "seo",
6532
+ // Knowledge kinds
6533
+ "playbook",
6534
+ "strategy",
6535
+ "reference",
6536
+ // Resource kinds
6537
+ "agent",
6538
+ "workflow",
6539
+ "integration",
6540
+ "database",
6541
+ "user",
6542
+ "team",
6543
+ // Integration specifics
6544
+ "gmail",
6545
+ "google-sheets",
6546
+ "attio",
6547
+ // Surface / UI views
6548
+ "overview",
6549
+ "command-view",
6550
+ "command-queue",
6551
+ "pipeline",
6552
+ "lists",
6553
+ "resources",
6554
+ // Actions
6555
+ "approve",
6556
+ "reject",
6557
+ "retry",
6558
+ "edit",
6559
+ "view",
6560
+ "launch",
6561
+ "message",
6562
+ "escalate",
6563
+ "promote",
6564
+ "submit",
6565
+ "email",
6566
+ // Status
6567
+ "success",
6568
+ "error",
6569
+ "warning",
6570
+ "info",
6571
+ "pending",
6572
+ // OM / UI group icons
6573
+ "bolt",
6574
+ "building",
6575
+ "briefcase",
6576
+ "apps",
6577
+ "graph",
6578
+ "shield",
6579
+ "users",
6580
+ "chart-bar",
6581
+ "search"
6580
6582
  ];
6581
- var CustomIconTokenSchema = z.string().trim().max(80).regex(/^custom\.[a-z0-9]+(?:[-._][a-z0-9]+)*$/, "Custom icon tokens must start with custom.");
6583
+ var CustomIconTokenSchema = z.string().trim().max(80).regex(
6584
+ /^custom\.[a-z0-9]+(?:[-._][a-z0-9]+)*$/,
6585
+ 'Custom icon tokens must start with "custom." followed by lowercase alphanumeric segments'
6586
+ );
6582
6587
  var OrganizationModelBuiltinIconTokenSchema = z.enum(ORGANIZATION_MODEL_ICON_TOKENS);
6583
6588
  var OrganizationModelIconTokenSchema = z.union([
6584
6589
  OrganizationModelBuiltinIconTokenSchema,
@@ -6591,7 +6596,7 @@ var LabelSchema = z.string().trim().min(1).max(120);
6591
6596
  var DescriptionSchema = z.string().trim().min(1).max(2e3);
6592
6597
  var ColorTokenSchema = z.string().trim().min(1).max(50);
6593
6598
  var IconNameSchema = OrganizationModelIconTokenSchema;
6594
- z.string().trim().startsWith("/").max(300);
6599
+ var PathSchema = z.string().trim().startsWith("/").max(300);
6595
6600
  var ReferenceIdsSchema = z.array(ModelIdSchema).default([]);
6596
6601
  var DisplayMetadataSchema = z.object({
6597
6602
  label: LabelSchema,
@@ -6651,7 +6656,7 @@ var EntitySchema = z.object({
6651
6656
  stateCatalogId: ModelIdSchema.optional(),
6652
6657
  links: z.array(EntityLinkSchema).optional()
6653
6658
  });
6654
- z.record(z.string(), EntitySchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
6659
+ var EntitiesDomainSchema = z.record(z.string(), EntitySchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
6655
6660
  message: "Each entity entry id must match its map key"
6656
6661
  }).default({});
6657
6662
  var ENTITY_ENTRY_INPUTS = [
@@ -6749,7 +6754,7 @@ var ENTITY_ENTRY_INPUTS = [
6749
6754
  ]
6750
6755
  }
6751
6756
  ];
6752
- Object.fromEntries(
6757
+ var DEFAULT_ORGANIZATION_MODEL_ENTITIES = Object.fromEntries(
6753
6758
  ENTITY_ENTRY_INPUTS.map((entity) => {
6754
6759
  const parsed = EntitySchema.parse(entity);
6755
6760
  return [parsed.id, parsed];
@@ -6766,7 +6771,7 @@ var ActionScopeSchema = z.union([
6766
6771
  domain: ModelIdSchema
6767
6772
  })
6768
6773
  ]);
6769
- z.object({
6774
+ var ActionRefSchema = z.object({
6770
6775
  actionId: ActionIdSchema.meta({ ref: "action" }),
6771
6776
  intent: z.enum(["exposes", "consumes"]).meta({ label: "Intent" })
6772
6777
  });
@@ -6810,7 +6815,7 @@ var ActionSchema = z.object({
6810
6815
  knowledge: z.array(ModelIdSchema.meta({ ref: "knowledge" })).default([]).optional(),
6811
6816
  lifecycle: z.enum(["draft", "beta", "active", "deprecated", "archived"]).meta({ label: "Lifecycle", color: "teal" }).default("active")
6812
6817
  });
6813
- z.record(z.string(), ActionSchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
6818
+ var ActionsDomainSchema = z.record(z.string(), ActionSchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
6814
6819
  message: "Each action entry id must match its map key"
6815
6820
  }).default({});
6816
6821
  var LEAD_GEN_ACTION_ENTRY_INPUTS = [
@@ -6940,6 +6945,99 @@ var LEAD_GEN_ACTION_ENTRIES = Object.fromEntries(
6940
6945
  return [parsed.id, parsed];
6941
6946
  })
6942
6947
  );
6948
+ var CRM_ACTION_ENTRY_INPUTS = [
6949
+ {
6950
+ id: "send_reply",
6951
+ order: 210,
6952
+ label: "Send Reply",
6953
+ description: "Send a contextual reply for an active CRM deal.",
6954
+ scope: { domain: "sales" },
6955
+ resourceId: "crm-send-reply-workflow",
6956
+ affects: ["crm.deal"]
6957
+ },
6958
+ {
6959
+ id: "send_link",
6960
+ order: 220,
6961
+ label: "Send Booking Link",
6962
+ description: "Send a booking link to move a deal toward a scheduled call.",
6963
+ scope: { domain: "sales" },
6964
+ resourceId: "crm-send-booking-link-workflow",
6965
+ affects: ["crm.deal"]
6966
+ },
6967
+ {
6968
+ id: "send_nudge",
6969
+ order: 230,
6970
+ label: "Send Nudge",
6971
+ description: "Send a follow-up nudge for a stalled CRM deal.",
6972
+ scope: { domain: "sales" },
6973
+ resourceId: "crm-send-nudge-workflow",
6974
+ affects: ["crm.deal"]
6975
+ },
6976
+ {
6977
+ id: "rebook",
6978
+ order: 240,
6979
+ label: "Rebook",
6980
+ description: "Rebook a missed or rescheduled CRM appointment.",
6981
+ scope: { domain: "sales" },
6982
+ resourceId: "crm-rebook-workflow",
6983
+ affects: ["crm.deal"]
6984
+ },
6985
+ {
6986
+ id: "move_to_proposal",
6987
+ order: 250,
6988
+ label: "Move to Proposal",
6989
+ description: "Advance a qualified CRM deal into the proposal stage.",
6990
+ scope: { domain: "sales" },
6991
+ resourceId: "move_to_proposal-workflow",
6992
+ affects: ["crm.deal"]
6993
+ },
6994
+ {
6995
+ id: "move_to_closing",
6996
+ order: 260,
6997
+ label: "Move to Closing",
6998
+ description: "Advance a proposal-stage CRM deal into closing.",
6999
+ scope: { domain: "sales" },
7000
+ resourceId: "move_to_closing-workflow",
7001
+ affects: ["crm.deal"]
7002
+ },
7003
+ {
7004
+ id: "move_to_closed_won",
7005
+ order: 270,
7006
+ label: "Close Won",
7007
+ description: "Mark a CRM deal as closed won.",
7008
+ scope: { domain: "sales" },
7009
+ resourceId: "move_to_closed_won-workflow",
7010
+ affects: ["crm.deal"]
7011
+ },
7012
+ {
7013
+ id: "move_to_closed_lost",
7014
+ order: 280,
7015
+ label: "Close Lost",
7016
+ description: "Mark a CRM deal as closed lost.",
7017
+ scope: { domain: "sales" },
7018
+ resourceId: "move_to_closed_lost-workflow",
7019
+ affects: ["crm.deal"]
7020
+ },
7021
+ {
7022
+ id: "move_to_nurturing",
7023
+ order: 290,
7024
+ label: "Move to Nurturing",
7025
+ description: "Move a CRM deal into nurturing for future follow-up.",
7026
+ scope: { domain: "sales" },
7027
+ resourceId: "move_to_nurturing-workflow",
7028
+ affects: ["crm.deal"]
7029
+ }
7030
+ ];
7031
+ var CRM_ACTION_ENTRIES = Object.fromEntries(
7032
+ CRM_ACTION_ENTRY_INPUTS.map((action) => {
7033
+ const parsed = ActionSchema.parse(action);
7034
+ return [parsed.id, parsed];
7035
+ })
7036
+ );
7037
+ var DEFAULT_ORGANIZATION_MODEL_ACTIONS = {
7038
+ ...LEAD_GEN_ACTION_ENTRIES,
7039
+ ...CRM_ACTION_ENTRIES
7040
+ };
6943
7041
 
6944
7042
  // ../core/src/organization-model/domains/prospecting.ts
6945
7043
  DisplayMetadataSchema.extend({
@@ -7078,7 +7176,7 @@ var DTC_RECORD_COLUMNS = {
7078
7176
  ]
7079
7177
  }
7080
7178
  };
7081
- var ACTION_REGISTRY = Object.values(LEAD_GEN_ACTION_ENTRIES);
7179
+ Object.values(LEAD_GEN_ACTION_ENTRIES);
7082
7180
  var PROSPECTING_STEPS = {
7083
7181
  localServices: {
7084
7182
  sourceCompanies: {
@@ -7418,92 +7516,3064 @@ var LEAD_GEN_STAGE_CATALOG = {
7418
7516
  order: 11,
7419
7517
  entity: "contact"
7420
7518
  }
7421
- };
7422
-
7423
- // ../core/src/organization-model/domains/sales.ts
7424
- var SalesStageSemanticClassSchema = z.enum(["open", "active", "nurturing", "closed_won", "closed_lost"]);
7425
- var SalesStageSchema = DisplayMetadataSchema.extend({
7426
- id: ModelIdSchema,
7427
- order: z.number().int().min(0),
7428
- semanticClass: SalesStageSemanticClassSchema,
7429
- surfaceIds: ReferenceIdsSchema,
7430
- resourceIds: ReferenceIdsSchema
7431
- });
7432
- z.object({
7433
- id: ModelIdSchema,
7434
- label: z.string().trim().min(1).max(120),
7435
- description: DescriptionSchema.optional(),
7436
- entityId: ModelIdSchema,
7437
- stages: z.array(SalesStageSchema).min(1)
7519
+ };
7520
+
7521
+ // ../core/src/organization-model/domains/sales.ts
7522
+ var SalesStageSemanticClassSchema = z.enum(["open", "active", "nurturing", "closed_won", "closed_lost"]);
7523
+ var SalesStageSchema = DisplayMetadataSchema.extend({
7524
+ id: ModelIdSchema,
7525
+ order: z.number().int().min(0),
7526
+ semanticClass: SalesStageSemanticClassSchema,
7527
+ surfaceIds: ReferenceIdsSchema,
7528
+ resourceIds: ReferenceIdsSchema
7529
+ });
7530
+ z.object({
7531
+ id: ModelIdSchema,
7532
+ label: z.string().trim().min(1).max(120),
7533
+ description: DescriptionSchema.optional(),
7534
+ entityId: ModelIdSchema,
7535
+ stages: z.array(SalesStageSchema).min(1)
7536
+ });
7537
+ var CRM_DISCOVERY_REPLIED_STATE = {
7538
+ stateKey: "discovery_replied",
7539
+ label: "Discovery Replied"
7540
+ };
7541
+ var CRM_DISCOVERY_LINK_SENT_STATE = {
7542
+ stateKey: "discovery_link_sent",
7543
+ label: "Discovery Link Sent"
7544
+ };
7545
+ var CRM_DISCOVERY_NUDGING_STATE = {
7546
+ stateKey: "discovery_nudging",
7547
+ label: "Discovery Nudging"
7548
+ };
7549
+ var CRM_DISCOVERY_BOOKING_CANCELLED_STATE = {
7550
+ stateKey: "discovery_booking_cancelled",
7551
+ label: "Discovery Booking Cancelled"
7552
+ };
7553
+ var CRM_REPLY_SENT_STATE = {
7554
+ stateKey: "reply_sent",
7555
+ label: "Reply Sent"
7556
+ };
7557
+ var CRM_FOLLOWUP_1_SENT_STATE = {
7558
+ stateKey: "followup_1_sent",
7559
+ label: "Follow-up 1 Sent"
7560
+ };
7561
+ var CRM_FOLLOWUP_2_SENT_STATE = {
7562
+ stateKey: "followup_2_sent",
7563
+ label: "Follow-up 2 Sent"
7564
+ };
7565
+ var CRM_FOLLOWUP_3_SENT_STATE = {
7566
+ stateKey: "followup_3_sent",
7567
+ label: "Follow-up 3 Sent"
7568
+ };
7569
+ var CRM_PIPELINE_DEFINITION = {
7570
+ pipelineKey: "crm",
7571
+ label: "CRM",
7572
+ entityKey: "crm.deal",
7573
+ stages: [
7574
+ {
7575
+ stageKey: "interested",
7576
+ label: "Interested",
7577
+ color: "blue",
7578
+ states: [
7579
+ CRM_DISCOVERY_REPLIED_STATE,
7580
+ CRM_DISCOVERY_LINK_SENT_STATE,
7581
+ CRM_DISCOVERY_NUDGING_STATE,
7582
+ CRM_DISCOVERY_BOOKING_CANCELLED_STATE,
7583
+ CRM_REPLY_SENT_STATE,
7584
+ CRM_FOLLOWUP_1_SENT_STATE,
7585
+ CRM_FOLLOWUP_2_SENT_STATE,
7586
+ CRM_FOLLOWUP_3_SENT_STATE
7587
+ ]
7588
+ },
7589
+ { stageKey: "proposal", label: "Proposal", color: "yellow", states: [] },
7590
+ { stageKey: "closing", label: "Closing", color: "orange", states: [] },
7591
+ { stageKey: "closed_won", label: "Closed Won", color: "green", states: [] },
7592
+ { stageKey: "closed_lost", label: "Closed Lost", color: "red", states: [] },
7593
+ { stageKey: "nurturing", label: "Nurturing", color: "grape", states: [] }
7594
+ ]
7595
+ };
7596
+ var OrganizationModelBrandingSchema = z.object({
7597
+ organizationName: LabelSchema,
7598
+ productName: LabelSchema,
7599
+ shortName: z.string().trim().min(1).max(40),
7600
+ description: DescriptionSchema.optional(),
7601
+ logos: z.object({
7602
+ light: z.string().trim().min(1).max(2048).optional(),
7603
+ dark: z.string().trim().min(1).max(2048).optional()
7604
+ }).default({})
7605
+ });
7606
+ var DEFAULT_ORGANIZATION_MODEL_BRANDING = {
7607
+ organizationName: "Default Organization",
7608
+ productName: "Elevasis",
7609
+ shortName: "Elevasis",
7610
+ logos: {}
7611
+ };
7612
+ var BusinessHoursDaySchema = z.object({
7613
+ open: z.string().trim().regex(/^\d{2}:\d{2}$/, "Expected HH:MM format"),
7614
+ close: z.string().trim().regex(/^\d{2}:\d{2}$/, "Expected HH:MM format")
7615
+ });
7616
+ var BusinessHoursSchema = z.object({
7617
+ monday: BusinessHoursDaySchema.optional(),
7618
+ tuesday: BusinessHoursDaySchema.optional(),
7619
+ wednesday: BusinessHoursDaySchema.optional(),
7620
+ thursday: BusinessHoursDaySchema.optional(),
7621
+ friday: BusinessHoursDaySchema.optional(),
7622
+ saturday: BusinessHoursDaySchema.optional(),
7623
+ sunday: BusinessHoursDaySchema.optional()
7624
+ }).default({});
7625
+ var IdentityDomainSchema = z.object({
7626
+ /** Why the organization exists — one or two plain-language sentences. */
7627
+ mission: z.string().trim().max(1e3).default(""),
7628
+ /** Long-term direction the organization is moving toward. */
7629
+ vision: z.string().trim().max(1e3).default(""),
7630
+ /** Legal registered name of the entity. */
7631
+ legalName: z.string().trim().max(200).default(""),
7632
+ /**
7633
+ * Type of legal entity (e.g. "LLC", "Corporation", "Sole Proprietor",
7634
+ * "Non-profit"). Free-form string so it covers any jurisdiction.
7635
+ */
7636
+ entityType: z.string().trim().max(100).default(""),
7637
+ /**
7638
+ * Primary jurisdiction of registration or operation
7639
+ * (e.g. "United States – Delaware", "Canada – Ontario").
7640
+ */
7641
+ jurisdiction: z.string().trim().max(200).default(""),
7642
+ /**
7643
+ * Industry category — broad classification (e.g. "Marketing Agency",
7644
+ * "Software / SaaS", "Professional Services").
7645
+ */
7646
+ industryCategory: z.string().trim().max(200).default(""),
7647
+ /**
7648
+ * Geographic focus — where the organization primarily operates or serves
7649
+ * (e.g. "North America", "Global", "Southeast Asia").
7650
+ */
7651
+ geographicFocus: z.string().trim().max(200).default(""),
7652
+ /**
7653
+ * IANA timezone identifier for the organization's primary operating timezone
7654
+ * (e.g. "America/Los_Angeles", "Europe/London", "UTC").
7655
+ */
7656
+ timeZone: z.string().trim().max(100).default("UTC"),
7657
+ /** Typical operating hours per day of week. Empty object means not configured. */
7658
+ businessHours: BusinessHoursSchema,
7659
+ /**
7660
+ * Long-form markdown capturing client context, problem narrative, and domain
7661
+ * background. Populated by /setup; surfaced to agents as organizational context.
7662
+ * Optional — many projects have no external client.
7663
+ */
7664
+ clientBrief: z.string().trim().default("")
7665
+ });
7666
+ var DEFAULT_ORGANIZATION_MODEL_IDENTITY = {
7667
+ mission: "",
7668
+ vision: "",
7669
+ legalName: "",
7670
+ entityType: "",
7671
+ jurisdiction: "",
7672
+ industryCategory: "",
7673
+ geographicFocus: "",
7674
+ timeZone: "UTC",
7675
+ businessHours: {},
7676
+ clientBrief: ""
7677
+ };
7678
+ var FirmographicsSchema = z.object({
7679
+ /** Industry vertical (e.g. "Marketing Agency", "Legal", "Real Estate"). */
7680
+ industry: z.string().trim().max(200).optional(),
7681
+ /**
7682
+ * Company headcount band (e.g. "1–10", "11–50", "51–200", "200+").
7683
+ * Free-form string to accommodate any band notation.
7684
+ */
7685
+ companySize: z.string().trim().max(100).optional(),
7686
+ /**
7687
+ * Primary geographic region the segment operates in or is targeted from
7688
+ * (e.g. "North America", "Europe", "Global").
7689
+ */
7690
+ region: z.string().trim().max(200).optional()
7691
+ });
7692
+ var CustomerSegmentSchema = z.object({
7693
+ /** Stable unique identifier for the segment (e.g. "segment-smb-agencies"). */
7694
+ id: z.string().trim().min(1).max(100),
7695
+ /** Domain-map iteration order. Convention: multiples of 10 (10, 20, 30, ...) to allow easy insertion. */
7696
+ order: z.number(),
7697
+ /** Human-readable name shown to agents and in UI (e.g. "SMB Marketing Agencies"). */
7698
+ name: z.string().trim().max(200).default(""),
7699
+ /** One or two sentences describing who this segment is. */
7700
+ description: z.string().trim().max(2e3).default(""),
7701
+ /**
7702
+ * The primary job(s) this segment is trying to get done — the goal they hire
7703
+ * a product/service to accomplish. Plain-language narrative or bullet list.
7704
+ */
7705
+ jobsToBeDone: z.string().trim().max(2e3).default(""),
7706
+ /**
7707
+ * Pains — frustrations, obstacles, and risks the segment experiences
7708
+ * when trying to accomplish their jobs-to-be-done.
7709
+ */
7710
+ pains: z.array(z.string().trim().max(500)).default([]),
7711
+ /**
7712
+ * Gains — outcomes and benefits the segment desires; positive motivators
7713
+ * beyond merely resolving pains.
7714
+ */
7715
+ gains: z.array(z.string().trim().max(500)).default([]),
7716
+ /** Firmographic profile for targeting and filtering. */
7717
+ firmographics: FirmographicsSchema.default({}),
7718
+ /**
7719
+ * Value proposition — one or two sentences stating why this organization's
7720
+ * offering is uniquely suited for this segment's needs.
7721
+ */
7722
+ valueProp: z.string().trim().max(2e3).default("")
7723
+ });
7724
+ var CustomersDomainSchema = z.record(z.string(), CustomerSegmentSchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
7725
+ message: "Each segment entry id must match its map key"
7726
+ }).default({});
7727
+ var DEFAULT_ORGANIZATION_MODEL_CUSTOMERS = {};
7728
+ var PricingModelSchema = z.enum(["one-time", "subscription", "usage-based", "custom"]).meta({ label: "Pricing model", color: "green" });
7729
+ var ProductSchema = z.object({
7730
+ /** Stable unique identifier for the product (e.g. "product-starter-plan"). */
7731
+ id: z.string().trim().min(1).max(100),
7732
+ /** Domain-map iteration order. Convention: multiples of 10 (10, 20, 30, ...) to allow easy insertion. */
7733
+ order: z.number(),
7734
+ /** Human-readable name shown to agents and in UI (e.g. "Starter Plan"). */
7735
+ name: z.string().trim().max(200).default(""),
7736
+ /** One or two sentences describing what this product/service delivers. */
7737
+ description: z.string().trim().max(2e3).default(""),
7738
+ /**
7739
+ * How this product is priced:
7740
+ * - "one-time" — single purchase (setup fee, project fee)
7741
+ * - "subscription" — recurring (monthly/annual SaaS, retainer)
7742
+ * - "usage-based" — metered by consumption (API calls, seats)
7743
+ * - "custom" — negotiated or bespoke pricing
7744
+ */
7745
+ pricingModel: PricingModelSchema.default("custom"),
7746
+ /** Base price amount (≥ 0). Currency unit defined by `currency`. */
7747
+ price: z.number().min(0).default(0),
7748
+ /**
7749
+ * ISO 4217 currency code (e.g. "USD", "EUR", "GBP").
7750
+ * Free-form string to accommodate any currency; defaults to "USD".
7751
+ */
7752
+ currency: z.string().trim().max(10).default("USD"),
7753
+ /**
7754
+ * IDs of customer segments this product targets.
7755
+ * Each id must reference a declared `customers.segments[].id`.
7756
+ * Cross-reference enforced in `OrganizationModelSchema.superRefine()`.
7757
+ */
7758
+ targetSegmentIds: z.array(z.string().trim().min(1)).default([]),
7759
+ /**
7760
+ * Optional: ID of the platform system responsible for delivering this product.
7761
+ * When present, must reference a declared `systems.systems[].id`.
7762
+ * Cross-reference enforced in `OrganizationModelSchema.superRefine()`.
7763
+ */
7764
+ deliveryFeatureId: z.string().trim().min(1).optional()
7765
+ });
7766
+ var OfferingsDomainSchema = z.record(z.string(), ProductSchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
7767
+ message: "Each product entry id must match its map key"
7768
+ }).default({});
7769
+ var DEFAULT_ORGANIZATION_MODEL_OFFERINGS = {};
7770
+ var ContentNodeBaseSchema = z.object({
7771
+ /** Human-readable label for the content node. */
7772
+ label: z.string().trim().min(1).max(120).meta({ label: "Label" }),
7773
+ /** Optional one-paragraph description. */
7774
+ description: z.string().trim().min(1).max(2e3).optional().meta({ label: "Description" }),
7775
+ /** Optional display order within the system content map. */
7776
+ order: z.number().int().optional().meta({ label: "Order" }),
7777
+ /**
7778
+ * Local NodeId of the parent content node within the SAME system.
7779
+ * Per B4/L9: MUST resolve to a sibling in the same `system.content` map.
7780
+ * Per L19: parent and child MUST share the same `kind` (meta-category).
7781
+ */
7782
+ parentContentId: z.string().trim().min(1).max(200).optional().meta({ label: "Parent content id" })
7783
+ });
7784
+ var ContentNodeSchema = ContentNodeBaseSchema.extend({
7785
+ /** Meta-category (e.g. 'schema', 'config', 'knowledge', tenant-defined). */
7786
+ kind: z.string().trim().min(1).max(100).meta({ label: "Kind" }),
7787
+ /** Specific family within the meta-category (e.g. 'pipeline', 'kv'). */
7788
+ type: z.string().trim().min(1).max(100).meta({ label: "Type" }),
7789
+ /** Payload data; validated against registered payloadSchema when (kind, type) is known. */
7790
+ data: z.record(z.string(), z.unknown()).optional().meta({ label: "Data" })
7791
+ });
7792
+ z.object({
7793
+ /** Meta-category (tenant-defined or registry-shipped). */
7794
+ kind: z.string().trim().min(1).max(100).meta({ label: "Kind" }),
7795
+ /** Specific family within the meta-category. */
7796
+ type: z.string().trim().min(1).max(100).meta({ label: "Type" }),
7797
+ /** Human-readable label shown in the KB tree and describe views. */
7798
+ label: z.string().trim().min(1).max(120).meta({ label: "Label" }),
7799
+ /** Optional description. */
7800
+ description: z.string().trim().min(1).max(2e3).optional().meta({ label: "Description" }),
7801
+ /**
7802
+ * Which KB tree group this extension renders in.
7803
+ * Per L6: 'business-model' places it alongside Customers / Offerings / Goals.
7804
+ */
7805
+ treeGroup: z.union([z.enum(["profile", "business-model", "systems", "graph", "governance-wiring"]), z.string().min(1).max(100)]).meta({ label: "Tree group" }),
7806
+ /** Untyped payload; shape governed by the registered payloadSchema when available. */
7807
+ data: z.record(z.string(), z.unknown()).optional().meta({ label: "Data" })
7808
+ });
7809
+ var OntologyKindSchema = z.enum([
7810
+ "object",
7811
+ "link",
7812
+ "action",
7813
+ "catalog",
7814
+ "event",
7815
+ "interface",
7816
+ "value-type",
7817
+ "property",
7818
+ "group",
7819
+ "surface"
7820
+ ]);
7821
+ var SYSTEM_PATH_PATTERN = "[a-z0-9][a-z0-9-]*(?:\\.[a-z0-9][a-z0-9-]*)*";
7822
+ var LOCAL_ID_PATTERN = "[a-z0-9][a-z0-9._-]*";
7823
+ var ONTOLOGY_ID_PATTERN = `^(global|${SYSTEM_PATH_PATTERN}):(${OntologyKindSchema.options.join("|")})\\/(${LOCAL_ID_PATTERN})$`;
7824
+ var ONTOLOGY_ID_REGEX = new RegExp(ONTOLOGY_ID_PATTERN);
7825
+ var OntologyIdSchema = z.string().trim().min(1).max(300).regex(
7826
+ ONTOLOGY_ID_REGEX,
7827
+ "Ontology IDs must use <system-path>:<kind>/<local-id> or global:<kind>/<local-id>"
7828
+ );
7829
+ function parseOntologyId(id) {
7830
+ const normalized = OntologyIdSchema.parse(id);
7831
+ const match = ONTOLOGY_ID_REGEX.exec(normalized);
7832
+ if (match === null) {
7833
+ throw new Error(`Invalid ontology ID "${id}"`);
7834
+ }
7835
+ return {
7836
+ id: normalized,
7837
+ scope: match[1],
7838
+ kind: match[2],
7839
+ localId: match[3],
7840
+ isGlobal: match[1] === "global"
7841
+ };
7842
+ }
7843
+ function formatOntologyId(input) {
7844
+ return OntologyIdSchema.parse(`${input.scope}:${input.kind}/${input.localId}`);
7845
+ }
7846
+ var OntologyReferenceListSchema = z.array(OntologyIdSchema).default([]).optional();
7847
+ var OntologyRecordBaseSchema = z.object({
7848
+ id: OntologyIdSchema,
7849
+ label: z.string().trim().min(1).max(160).optional(),
7850
+ description: z.string().trim().min(1).max(2e3).optional(),
7851
+ ownerSystemId: z.string().trim().min(1).max(200).optional(),
7852
+ aliases: z.array(OntologyIdSchema).optional()
7853
+ }).passthrough();
7854
+ var OntologyObjectTypeSchema = OntologyRecordBaseSchema.extend({
7855
+ properties: z.record(z.string().trim().min(1).max(200), z.unknown()).optional(),
7856
+ storage: z.record(z.string(), z.unknown()).optional()
7857
+ });
7858
+ var OntologyLinkTypeSchema = OntologyRecordBaseSchema.extend({
7859
+ from: OntologyIdSchema,
7860
+ to: OntologyIdSchema,
7861
+ cardinality: z.string().trim().min(1).max(80).optional(),
7862
+ via: z.string().trim().min(1).max(255).optional()
7863
+ });
7864
+ var OntologyActionTypeSchema = OntologyRecordBaseSchema.extend({
7865
+ actsOn: OntologyReferenceListSchema,
7866
+ input: z.record(z.string().trim().min(1).max(200), z.unknown()).optional(),
7867
+ effects: z.array(z.record(z.string(), z.unknown())).optional()
7868
+ });
7869
+ var OntologyCatalogTypeSchema = OntologyRecordBaseSchema.extend({
7870
+ kind: z.string().trim().min(1).max(120).optional(),
7871
+ appliesTo: OntologyIdSchema.optional(),
7872
+ entries: z.record(z.string().trim().min(1).max(200), z.unknown()).optional()
7873
+ });
7874
+ var OntologyEventTypeSchema = OntologyRecordBaseSchema.extend({
7875
+ payload: z.record(z.string().trim().min(1).max(200), z.unknown()).optional()
7876
+ });
7877
+ var OntologyInterfaceTypeSchema = OntologyRecordBaseSchema.extend({
7878
+ properties: z.record(z.string().trim().min(1).max(200), z.unknown()).optional()
7879
+ });
7880
+ var OntologyValueTypeSchema = OntologyRecordBaseSchema.extend({
7881
+ primitive: z.string().trim().min(1).max(120).optional()
7882
+ });
7883
+ var OntologySharedPropertySchema = OntologyRecordBaseSchema.extend({
7884
+ valueType: OntologyIdSchema.optional(),
7885
+ searchable: z.boolean().optional(),
7886
+ pii: z.boolean().optional()
7887
+ });
7888
+ var OntologyGroupSchema = OntologyRecordBaseSchema.extend({
7889
+ members: OntologyReferenceListSchema
7890
+ });
7891
+ var OntologySurfaceTypeSchema = OntologyRecordBaseSchema.extend({
7892
+ route: z.string().trim().min(1).max(500).optional()
7893
+ });
7894
+ var OntologyScopeSchema = z.object({
7895
+ objectTypes: z.record(OntologyIdSchema, OntologyObjectTypeSchema).default({}).optional(),
7896
+ linkTypes: z.record(OntologyIdSchema, OntologyLinkTypeSchema).default({}).optional(),
7897
+ actionTypes: z.record(OntologyIdSchema, OntologyActionTypeSchema).default({}).optional(),
7898
+ catalogTypes: z.record(OntologyIdSchema, OntologyCatalogTypeSchema).default({}).optional(),
7899
+ eventTypes: z.record(OntologyIdSchema, OntologyEventTypeSchema).default({}).optional(),
7900
+ interfaceTypes: z.record(OntologyIdSchema, OntologyInterfaceTypeSchema).default({}).optional(),
7901
+ valueTypes: z.record(OntologyIdSchema, OntologyValueTypeSchema).default({}).optional(),
7902
+ sharedProperties: z.record(OntologyIdSchema, OntologySharedPropertySchema).default({}).optional(),
7903
+ groups: z.record(OntologyIdSchema, OntologyGroupSchema).default({}).optional(),
7904
+ surfaces: z.record(OntologyIdSchema, OntologySurfaceTypeSchema).default({}).optional()
7905
+ }).default({});
7906
+ var DEFAULT_ONTOLOGY_SCOPE = {
7907
+ valueTypes: {
7908
+ "global:value-type/uuid": {
7909
+ id: "global:value-type/uuid",
7910
+ label: "UUID",
7911
+ primitive: "string"
7912
+ },
7913
+ "global:value-type/text": {
7914
+ id: "global:value-type/text",
7915
+ label: "Text",
7916
+ primitive: "string"
7917
+ },
7918
+ "global:value-type/url": {
7919
+ id: "global:value-type/url",
7920
+ label: "URL",
7921
+ primitive: "string"
7922
+ },
7923
+ "global:value-type/email": {
7924
+ id: "global:value-type/email",
7925
+ label: "Email",
7926
+ primitive: "string"
7927
+ }
7928
+ }
7929
+ };
7930
+ var SCOPE_KIND = {
7931
+ objectTypes: "object",
7932
+ linkTypes: "link",
7933
+ actionTypes: "action",
7934
+ catalogTypes: "catalog",
7935
+ eventTypes: "event",
7936
+ interfaceTypes: "interface",
7937
+ valueTypes: "value-type",
7938
+ sharedProperties: "property",
7939
+ groups: "group",
7940
+ surfaces: "surface"
7941
+ };
7942
+ var SCOPE_KEYS = Object.keys(SCOPE_KIND);
7943
+ function listResolvedOntologyRecords(index2) {
7944
+ return SCOPE_KEYS.flatMap((scopeKey) => {
7945
+ const kind = SCOPE_KIND[scopeKey];
7946
+ return Object.entries(index2[scopeKey]).sort(([leftId], [rightId]) => leftId.localeCompare(rightId)).map(([id, record]) => ({
7947
+ id,
7948
+ kind,
7949
+ record
7950
+ }));
7951
+ });
7952
+ }
7953
+ function originFromContext(context) {
7954
+ return {
7955
+ kind: context.kind,
7956
+ source: context.source,
7957
+ path: context.path,
7958
+ ...context.systemPath !== void 0 ? { systemPath: context.systemPath } : {},
7959
+ ...context.legacyId !== void 0 ? { legacyId: context.legacyId } : {}
7960
+ };
7961
+ }
7962
+ function createEmptyIndex() {
7963
+ return {
7964
+ objectTypes: {},
7965
+ linkTypes: {},
7966
+ actionTypes: {},
7967
+ catalogTypes: {},
7968
+ eventTypes: {},
7969
+ interfaceTypes: {},
7970
+ valueTypes: {},
7971
+ sharedProperties: {},
7972
+ groups: {},
7973
+ surfaces: {}
7974
+ };
7975
+ }
7976
+ function sortResolvedOntologyIndex(index2) {
7977
+ const sorted = createEmptyIndex();
7978
+ for (const scopeKey of SCOPE_KEYS) {
7979
+ const target = sorted[scopeKey];
7980
+ for (const [id, record] of Object.entries(index2[scopeKey]).sort(
7981
+ ([leftId], [rightId]) => leftId.localeCompare(rightId)
7982
+ )) {
7983
+ target[id] = record;
7984
+ }
7985
+ }
7986
+ return sorted;
7987
+ }
7988
+ function childSystemsOf(system) {
7989
+ return system.systems ?? system.subsystems ?? {};
7990
+ }
7991
+ function addRecord(index2, diagnostics, sourcesById, scopeKey, record, context) {
7992
+ let parsed;
7993
+ try {
7994
+ parsed = parseOntologyId(record.id);
7995
+ } catch {
7996
+ diagnostics.push({
7997
+ code: "invalid_ontology_id",
7998
+ message: `Invalid ontology ID "${record.id}" from ${context.source} at ${context.path.join(".")}`,
7999
+ id: record.id,
8000
+ path: context.path,
8001
+ source: context.source,
8002
+ origin: originFromContext(context)
8003
+ });
8004
+ return;
8005
+ }
8006
+ const expectedKind = SCOPE_KIND[scopeKey];
8007
+ if (parsed.kind !== expectedKind) {
8008
+ diagnostics.push({
8009
+ code: "ontology_kind_mismatch",
8010
+ message: `Ontology ID "${record.id}" has kind "${parsed.kind}" but was authored in ${scopeKey} (${expectedKind}) at ${context.path.join(".")}`,
8011
+ id: record.id,
8012
+ path: context.path,
8013
+ source: context.source,
8014
+ origin: originFromContext(context)
8015
+ });
8016
+ return;
8017
+ }
8018
+ const existing = sourcesById.get(parsed.id);
8019
+ if (existing !== void 0) {
8020
+ diagnostics.push({
8021
+ code: "duplicate_ontology_id",
8022
+ message: `Duplicate ontology ID "${parsed.id}" from ${context.source} at ${context.path.join(".")} conflicts with ${existing.source} at ${existing.path.join(".")}`,
8023
+ id: parsed.id,
8024
+ path: context.path,
8025
+ source: context.source,
8026
+ origin: originFromContext(context),
8027
+ existingSource: existing.source,
8028
+ existingOrigin: originFromContext(existing)
8029
+ });
8030
+ return;
8031
+ }
8032
+ sourcesById.set(parsed.id, context);
8033
+ index2[scopeKey][parsed.id] = {
8034
+ ...record,
8035
+ origin: originFromContext(context)
8036
+ };
8037
+ }
8038
+ function addScope(index2, diagnostics, sourcesById, scope, source, path) {
8039
+ if (scope === void 0) return;
8040
+ for (const scopeKey of SCOPE_KEYS) {
8041
+ const records = scope[scopeKey] ?? {};
8042
+ for (const [key, record] of Object.entries(records)) {
8043
+ addRecord(index2, diagnostics, sourcesById, scopeKey, record, {
8044
+ source,
8045
+ path: [...path, scopeKey, key],
8046
+ kind: "authored",
8047
+ systemPath: source.startsWith("system:") ? source.slice("system:".length, -".ontology".length) : void 0
8048
+ });
8049
+ }
8050
+ }
8051
+ }
8052
+ function legacyObjectId(entity) {
8053
+ return formatOntologyId({ scope: entity.ownedBySystemId, kind: "object", localId: entity.id });
8054
+ }
8055
+ function legacyActionOwner(action, entities) {
8056
+ const firstAffectedEntityId = action.affects?.find((entityId) => entities[entityId] !== void 0);
8057
+ if (firstAffectedEntityId !== void 0) {
8058
+ return entities[firstAffectedEntityId].ownedBySystemId;
8059
+ }
8060
+ if (typeof action.scope === "object") {
8061
+ return action.scope.domain;
8062
+ }
8063
+ return "global";
8064
+ }
8065
+ function addLegacyEntityProjections(index2, diagnostics, sourcesById, entities) {
8066
+ for (const entity of Object.values(entities)) {
8067
+ const objectType = {
8068
+ id: legacyObjectId(entity),
8069
+ label: entity.label,
8070
+ description: entity.description,
8071
+ ownerSystemId: entity.ownedBySystemId,
8072
+ ...entity.table !== void 0 ? {
8073
+ storage: {
8074
+ kind: "table",
8075
+ table: entity.table
8076
+ }
8077
+ } : {},
8078
+ ...entity.rowSchema !== void 0 ? { rowSchema: entity.rowSchema } : {},
8079
+ ...entity.stateCatalogId !== void 0 ? { stateCatalogId: entity.stateCatalogId } : {}
8080
+ };
8081
+ addRecord(index2, diagnostics, sourcesById, "objectTypes", objectType, {
8082
+ source: "legacy.entities",
8083
+ path: ["entities", entity.id],
8084
+ kind: "projected",
8085
+ systemPath: entity.ownedBySystemId,
8086
+ legacyId: entity.id
8087
+ });
8088
+ entity.links?.forEach((link, linkIndex) => {
8089
+ const targetEntity = entities[link.toEntity];
8090
+ if (targetEntity === void 0) return;
8091
+ const linkType = {
8092
+ id: formatOntologyId({
8093
+ scope: entity.ownedBySystemId,
8094
+ kind: "link",
8095
+ localId: `${entity.id}-${link.toEntity}-${linkIndex}`
8096
+ }),
8097
+ label: link.label ?? link.kind,
8098
+ ownerSystemId: entity.ownedBySystemId,
8099
+ from: legacyObjectId(entity),
8100
+ to: legacyObjectId(targetEntity),
8101
+ cardinality: link.kind,
8102
+ ...link.via !== void 0 ? { via: link.via } : {}
8103
+ };
8104
+ addRecord(index2, diagnostics, sourcesById, "linkTypes", linkType, {
8105
+ source: "legacy.entities.links",
8106
+ path: ["entities", entity.id, "links", linkIndex],
8107
+ kind: "projected",
8108
+ systemPath: entity.ownedBySystemId,
8109
+ legacyId: `${entity.id}.links.${linkIndex}`
8110
+ });
8111
+ });
8112
+ }
8113
+ }
8114
+ function addLegacyActionProjections(index2, diagnostics, sourcesById, actions, entities) {
8115
+ for (const action of Object.values(actions)) {
8116
+ const ownerSystemId = legacyActionOwner(action, entities);
8117
+ const actionType = {
8118
+ id: formatOntologyId({ scope: ownerSystemId, kind: "action", localId: action.id }),
8119
+ label: action.label,
8120
+ description: action.description,
8121
+ ownerSystemId,
8122
+ actsOn: action.affects?.map((entityId) => entities[entityId] ? legacyObjectId(entities[entityId]) : void 0).filter((id) => id !== void 0),
8123
+ ...action.resourceId !== void 0 ? { resourceId: action.resourceId } : {},
8124
+ ...action.invocations !== void 0 ? { invocations: action.invocations } : {},
8125
+ ...action.lifecycle !== void 0 ? { lifecycle: action.lifecycle } : {},
8126
+ legacyActionId: action.id
8127
+ };
8128
+ addRecord(index2, diagnostics, sourcesById, "actionTypes", actionType, {
8129
+ source: "legacy.actions",
8130
+ path: ["actions", action.id],
8131
+ kind: "projected",
8132
+ systemPath: ownerSystemId,
8133
+ legacyId: action.id
8134
+ });
8135
+ }
8136
+ }
8137
+ function addSystemContentProjections(index2, diagnostics, sourcesById, systemPath, system, schemaPath) {
8138
+ const content = system.content ?? {};
8139
+ for (const [localId, node] of Object.entries(content)) {
8140
+ if (node.kind !== "schema") continue;
8141
+ const entries = Object.fromEntries(
8142
+ Object.entries(content).filter(([, candidate]) => candidate.parentContentId === localId).map(([entryId, candidate]) => [
8143
+ entryId,
8144
+ {
8145
+ label: candidate.label ?? entryId,
8146
+ type: candidate.type,
8147
+ ...candidate.description !== void 0 ? { description: candidate.description } : {},
8148
+ ...candidate.data !== void 0 ? candidate.data : {}
8149
+ }
8150
+ ])
8151
+ );
8152
+ const catalogType = {
8153
+ id: formatOntologyId({ scope: systemPath, kind: "catalog", localId }),
8154
+ label: node.label ?? localId,
8155
+ description: node.description,
8156
+ ownerSystemId: systemPath,
8157
+ kind: node.type,
8158
+ ...typeof node.data?.["entityId"] === "string" ? { appliesTo: formatOntologyId({ scope: systemPath, kind: "object", localId: node.data["entityId"] }) } : {},
8159
+ ...Object.keys(entries).length > 0 ? { entries } : {},
8160
+ ...node.data !== void 0 ? { data: node.data } : {}
8161
+ };
8162
+ addRecord(index2, diagnostics, sourcesById, "catalogTypes", catalogType, {
8163
+ source: "legacy.system.content",
8164
+ path: [...schemaPath, "content", localId],
8165
+ kind: "projected",
8166
+ systemPath,
8167
+ legacyId: `${systemPath}:${localId}`
8168
+ });
8169
+ }
8170
+ }
8171
+ function addSystemScopes(index2, diagnostics, sourcesById, systems, prefix, schemaPath) {
8172
+ for (const [key, system] of Object.entries(systems)) {
8173
+ const systemPath = prefix ? `${prefix}.${key}` : key;
8174
+ const currentPath = [...schemaPath, key];
8175
+ addScope(index2, diagnostics, sourcesById, system.ontology, `system:${systemPath}.ontology`, [
8176
+ ...currentPath,
8177
+ "ontology"
8178
+ ]);
8179
+ addSystemContentProjections(index2, diagnostics, sourcesById, systemPath, system, currentPath);
8180
+ addSystemScopes(index2, diagnostics, sourcesById, childSystemsOf(system), systemPath, [
8181
+ ...currentPath,
8182
+ system.systems !== void 0 ? "systems" : "subsystems"
8183
+ ]);
8184
+ }
8185
+ }
8186
+ function compileOrganizationOntology(model) {
8187
+ const ontology = createEmptyIndex();
8188
+ const diagnostics = [];
8189
+ const sourcesById = /* @__PURE__ */ new Map();
8190
+ addScope(ontology, diagnostics, sourcesById, model.ontology, "organization.ontology", ["ontology"]);
8191
+ addSystemScopes(ontology, diagnostics, sourcesById, model.systems ?? {}, "", ["systems"]);
8192
+ addLegacyEntityProjections(ontology, diagnostics, sourcesById, model.entities ?? {});
8193
+ addLegacyActionProjections(ontology, diagnostics, sourcesById, model.actions ?? {}, model.entities ?? {});
8194
+ return { ontology: sortResolvedOntologyIndex(ontology), diagnostics };
8195
+ }
8196
+
8197
+ // ../core/src/organization-model/domains/systems.ts
8198
+ var SystemKindSchema = z.enum(["product", "operational", "platform", "diagnostic"]).meta({ label: "System kind", color: "blue" });
8199
+ var SystemLifecycleSchema = z.enum(["draft", "beta", "active", "deprecated", "archived"]).meta({ label: "Lifecycle", color: "teal" });
8200
+ var SystemStatusSchema = z.enum(["active", "deprecated", "archived"]).meta({ label: "Status", color: "teal" });
8201
+ var SystemIdSchema = ModelIdSchema;
8202
+ var SystemPathSchema = z.string().trim().min(1).regex(
8203
+ /^[a-z0-9][a-z0-9-]*(?:\.[a-z0-9][a-z0-9-]*)*$/,
8204
+ 'must be a dotted lowercase path (e.g. "sales.lead-gen" or "sales.crm")'
8205
+ );
8206
+ var UiPositionSchema = z.enum(["sidebar-primary", "sidebar-bottom"]).meta({ label: "UI position" });
8207
+ var NodeIdStringSchema = z.string().trim().min(1).max(200).regex(
8208
+ /^[a-z][a-z-]*:([a-z0-9-]+)(\.[a-z0-9-]+)*(:[a-z0-9.-]+)*$/,
8209
+ "Node references must use kind:dotted-path (e.g. system:sales.crm or content-node:sales.crm:pipeline-id)"
8210
+ );
8211
+ var SystemUiSchema = z.object({
8212
+ path: PathSchema,
8213
+ surfaces: ReferenceIdsSchema,
8214
+ icon: IconNameSchema.optional(),
8215
+ order: z.number().int().optional()
8216
+ });
8217
+ var JsonValueSchema = z.lazy(
8218
+ () => z.union([
8219
+ z.string(),
8220
+ z.number(),
8221
+ z.boolean(),
8222
+ z.null(),
8223
+ z.array(JsonValueSchema),
8224
+ z.record(z.string(), JsonValueSchema)
8225
+ ])
8226
+ );
8227
+ var SystemConfigSchema = z.record(z.string().trim().min(1).max(200), JsonValueSchema).default({}).optional();
8228
+ var SystemEntrySchema = z.object({
8229
+ /** Stable tenant-defined system id (e.g. "sys.lead-gen" or "sales.crm"). */
8230
+ id: SystemIdSchema,
8231
+ /** Human-readable system label shown in UI, governance, and operations surfaces. */
8232
+ label: LabelSchema.optional(),
8233
+ /** @deprecated Use label. Accepted for pre-consolidation System declarations. */
8234
+ title: LabelSchema.optional(),
8235
+ /** One-paragraph purpose statement for the bounded context. */
8236
+ description: DescriptionSchema.optional(),
8237
+ /** Closed system shape enum; catalog values remain tenant-defined. */
8238
+ kind: SystemKindSchema.optional(),
8239
+ /** Optional self-reference for System hierarchy. */
8240
+ parentSystemId: SystemIdSchema.optional(),
8241
+ /** Optional UI presence. Systems without UI omit this. */
8242
+ ui: SystemUiSchema.optional(),
8243
+ /** Canonical lifecycle state. Replaces Feature.enabled/devOnly and System.status. */
8244
+ lifecycle: SystemLifecycleSchema.optional(),
8245
+ /** Optional role responsible for this system. */
8246
+ responsibleRoleId: ModelIdSchema.meta({ ref: "role" }).optional(),
8247
+ /** Optional knowledge nodes that govern this system. */
8248
+ governedByKnowledge: z.array(ModelIdSchema.meta({ ref: "knowledge" })).default([]).optional(),
8249
+ /** Optional actions this system exposes or consumes. */
8250
+ actions: z.array(ActionRefSchema).optional(),
8251
+ /** Optional operational policies that apply to this system. */
8252
+ policies: z.array(ModelIdSchema.meta({ ref: "policy" })).default([]).optional(),
8253
+ /** Optional goals this system contributes to. */
8254
+ drivesGoals: z.array(ModelIdSchema.meta({ ref: "goal" })).default([]).optional(),
8255
+ /** @deprecated Use lifecycle. Accepted for one publish cycle. */
8256
+ status: SystemStatusSchema.optional(),
8257
+ /** @deprecated Use ui.path. Kept for one-cycle Feature compatibility. */
8258
+ path: PathSchema.optional(),
8259
+ /** @deprecated Use ui.icon. Kept for one-cycle Feature compatibility. */
8260
+ icon: IconNameSchema.optional(),
8261
+ /** @deprecated Feature color token, retained for one-cycle compatibility. */
8262
+ color: ColorTokenSchema.optional(),
8263
+ /** @deprecated UI placement hint, retained for one-cycle compatibility. */
8264
+ uiPosition: UiPositionSchema.optional(),
8265
+ /** @deprecated Use lifecycle. */
8266
+ enabled: z.boolean().optional(),
8267
+ /** @deprecated Use lifecycle: "beta". */
8268
+ devOnly: z.boolean().optional(),
8269
+ requiresAdmin: z.boolean().optional(),
8270
+ /** Domain-map iteration order. Convention: multiples of 10 (10, 20, 30, ...) to allow easy insertion. */
8271
+ order: z.number(),
8272
+ /**
8273
+ * System-local JSON settings and defaults. Strongly typed OM fields,
8274
+ * secrets, credentials, and runtime state stay outside this bucket.
8275
+ */
8276
+ config: SystemConfigSchema,
8277
+ /**
8278
+ * System-owned ontology declarations. `systems` is now the canonical child
8279
+ * key; this scope holds the object, action, catalog, link, event, and
8280
+ * shared contract records owned by this system.
8281
+ */
8282
+ ontology: OntologyScopeSchema.optional(),
8283
+ /**
8284
+ * @deprecated Compatibility-only bridge for old tenant content nodes and
8285
+ * migration readers. New schema/catalog authoring belongs in ontology;
8286
+ * new system-local settings belong in config. Bridge nodes are keyed by
8287
+ * local NodeId and may still project to content-node:* graph IDs.
8288
+ */
8289
+ content: z.record(z.string().trim().min(1).max(200), ContentNodeSchema).optional(),
8290
+ /**
8291
+ * Recursive child systems, authored via nesting (per L11).
8292
+ * The key is the local system id; the full path is computed by joining
8293
+ * ancestor keys with `.` (e.g. parent key `'sales'` + child key `'crm'` → `'sales.crm'`).
8294
+ * Per Phase 4: `id` and `parentSystemId` fields will be removed in favour of
8295
+ * position-derived paths. Both still exist on this schema for backward compat.
8296
+ */
8297
+ systems: z.lazy(() => z.record(z.string().trim().min(1).max(100), SystemEntrySchema)).optional(),
8298
+ /** @deprecated Use systems. Accepted as a compatibility alias during the ontology bridge. */
8299
+ subsystems: z.lazy(() => z.record(z.string().trim().min(1).max(100), SystemEntrySchema)).optional()
8300
+ }).refine((system) => system.label !== void 0 || system.title !== void 0, {
8301
+ path: ["label"],
8302
+ message: "System must provide label or title"
8303
+ }).transform((system) => {
8304
+ const normalizedSystem = system.systems !== void 0 && system.subsystems === void 0 ? { ...system, subsystems: system.systems } : system;
8305
+ if (normalizedSystem.status === void 0) return normalizedSystem;
8306
+ console.warn("[organization-model] System.status is deprecated; use System.lifecycle instead.");
8307
+ return normalizedSystem.lifecycle === void 0 ? { ...normalizedSystem, lifecycle: normalizedSystem.status } : normalizedSystem;
8308
+ });
8309
+ var SystemsDomainSchema = z.record(z.string(), SystemEntrySchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
8310
+ message: "Each system entry id must match its map key"
8311
+ }).default({});
8312
+ var DEFAULT_ORGANIZATION_MODEL_SYSTEMS = {};
8313
+
8314
+ // ../core/src/organization-model/domains/resources.ts
8315
+ z.enum(["workflow", "agent", "integration", "script"]).meta({ label: "Resource kind", color: "orange" });
8316
+ var ResourceGovernanceStatusSchema = z.enum(["active", "deprecated", "archived"]).meta({ label: "Governance status", color: "teal" });
8317
+ var AgentKindSchema = z.enum(["orchestrator", "specialist", "utility", "platform"]).meta({ label: "Agent kind", color: "violet" });
8318
+ var ScriptResourceLanguageSchema = z.enum(["shell", "sql", "typescript", "python"]).meta({ label: "Language" });
8319
+ var CodeReferenceRoleSchema = z.enum(["entrypoint", "handler", "schema", "test", "docs", "config"]).meta({ label: "Code reference role", color: "blue" });
8320
+ var ResourceIdSchema = z.string().trim().min(1).max(255).regex(/^[A-Za-z0-9]+(?:[-._][A-Za-z0-9]+)*$/, "Resource IDs must use letters, numbers, -, _, or . separators");
8321
+ var EventIdSchema = z.string().trim().min(1).max(300).regex(
8322
+ /^[A-Za-z0-9]+(?:[-._][A-Za-z0-9]+)*:[a-z0-9]+(?:[-._][a-z0-9]+)*$/,
8323
+ "Event IDs must use <owner-id>:<event-key>"
8324
+ );
8325
+ var EventKeySchema = ModelIdSchema;
8326
+ var EventEmissionDescriptorSchema = z.object({
8327
+ eventKey: EventKeySchema,
8328
+ label: z.string().trim().min(1).max(120),
8329
+ payloadSchema: ModelIdSchema.optional(),
8330
+ lifecycle: SystemLifecycleSchema.optional()
8331
+ });
8332
+ EventEmissionDescriptorSchema.extend({
8333
+ id: EventIdSchema,
8334
+ ownerId: z.union([ResourceIdSchema, ModelIdSchema]),
8335
+ ownerKind: z.enum(["resource", "entity"]).meta({ label: "Owner kind" })
8336
+ });
8337
+ var ResourceOntologyBindingSchema = z.object({
8338
+ actions: z.array(OntologyIdSchema).optional(),
8339
+ primaryAction: OntologyIdSchema.optional(),
8340
+ reads: z.array(OntologyIdSchema).optional(),
8341
+ writes: z.array(OntologyIdSchema).optional(),
8342
+ usesCatalogs: z.array(OntologyIdSchema).optional(),
8343
+ emits: z.array(OntologyIdSchema).optional()
8344
+ }).superRefine((binding, ctx) => {
8345
+ if (binding.primaryAction === void 0) return;
8346
+ if (binding.actions?.includes(binding.primaryAction)) return;
8347
+ ctx.addIssue({
8348
+ code: z.ZodIssueCode.custom,
8349
+ path: ["primaryAction"],
8350
+ message: "Resource ontology primaryAction must be included in actions"
8351
+ });
8352
+ });
8353
+ var CodeReferenceSchema = z.object({
8354
+ path: z.string().trim().min(1).max(500).regex(/^[A-Za-z0-9_./$@()[\] -]+$/, "Code reference paths must be repo-relative paths"),
8355
+ role: CodeReferenceRoleSchema,
8356
+ symbol: z.string().trim().min(1).max(200).optional(),
8357
+ description: z.string().trim().min(1).max(300).optional()
8358
+ });
8359
+ var ResourceEntryBaseSchema = z.object({
8360
+ /** Canonical resource id; runtime resourceId derives from this value. */
8361
+ id: ResourceIdSchema,
8362
+ /** Domain-map iteration order. Convention: multiples of 10 (10, 20, 30, ...) to allow easy insertion. */
8363
+ order: z.number().default(0),
8364
+ /** Required single System membership — value is a dot-separated system path (e.g. "sales.lead-gen"). */
8365
+ systemPath: SystemPathSchema.meta({ ref: "system" }),
8366
+ /** Executable display title owned by the OM Resource descriptor. */
8367
+ title: LabelSchema.optional(),
8368
+ /** Executable display description owned by the OM Resource descriptor. */
8369
+ description: DescriptionSchema.optional(),
8370
+ /** Optional role responsible for maintaining this resource. */
8371
+ ownerRoleId: ModelIdSchema.meta({ ref: "role" }).optional(),
8372
+ status: ResourceGovernanceStatusSchema,
8373
+ /**
8374
+ * Ontology contract bindings for the semantic work this resource performs.
8375
+ * `emits` stays nested here so top-level resource emits descriptors remain
8376
+ * compatible with graph event projection during the bridge.
8377
+ */
8378
+ ontology: ResourceOntologyBindingSchema.optional(),
8379
+ /** Repo-relative implementation breadcrumbs for agents and operators. */
8380
+ codeRefs: z.array(CodeReferenceSchema).default([])
8381
+ });
8382
+ var WorkflowResourceEntrySchema = ResourceEntryBaseSchema.extend({
8383
+ kind: z.literal("workflow"),
8384
+ emits: z.array(EventEmissionDescriptorSchema).optional()
8385
+ });
8386
+ var AgentResourceEntrySchema = ResourceEntryBaseSchema.extend({
8387
+ kind: z.literal("agent"),
8388
+ /** Mirrors code-side AgentConfig.kind. */
8389
+ agentKind: AgentKindSchema,
8390
+ /** Role this agent embodies, if any. */
8391
+ actsAsRoleId: ModelIdSchema.meta({ ref: "role" }).optional(),
8392
+ /** Mirrors AgentConfig.sessionCapable. */
8393
+ sessionCapable: z.boolean(),
8394
+ /** Broad/composite callable entry points orchestrated by this agent. */
8395
+ invocations: z.array(ActionInvocationSchema).default([]),
8396
+ emits: z.array(EventEmissionDescriptorSchema).optional()
8397
+ });
8398
+ var IntegrationResourceEntrySchema = ResourceEntryBaseSchema.extend({
8399
+ kind: z.literal("integration"),
8400
+ provider: z.string().trim().min(1).max(100)
8401
+ });
8402
+ var ScriptResourceSourceSchema = z.union([
8403
+ z.string().trim().min(1).max(5e4),
8404
+ z.object({
8405
+ file: z.string().trim().min(1).max(500)
8406
+ })
8407
+ ]);
8408
+ var ScriptResourceEntrySchema = ResourceEntryBaseSchema.extend({
8409
+ kind: z.literal("script"),
8410
+ language: ScriptResourceLanguageSchema,
8411
+ source: ScriptResourceSourceSchema
8412
+ });
8413
+ var ResourceEntrySchema = z.discriminatedUnion("kind", [
8414
+ WorkflowResourceEntrySchema,
8415
+ AgentResourceEntrySchema,
8416
+ IntegrationResourceEntrySchema,
8417
+ ScriptResourceEntrySchema
8418
+ ]);
8419
+ var ResourcesDomainSchema = z.record(z.string(), ResourceEntrySchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
8420
+ message: "Each resource entry id must match its map key"
8421
+ }).default({});
8422
+ var DEFAULT_ORGANIZATION_MODEL_RESOURCES = {};
8423
+
8424
+ // ../core/src/organization-model/domains/roles.ts
8425
+ var RoleIdSchema = ModelIdSchema;
8426
+ var HumanRoleHolderSchema = z.object({
8427
+ kind: z.literal("human"),
8428
+ userId: z.string().trim().min(1).max(200)
8429
+ });
8430
+ var AgentRoleHolderSchema = z.object({
8431
+ kind: z.literal("agent"),
8432
+ agentId: ResourceIdSchema.meta({ ref: "resource" })
8433
+ });
8434
+ var TeamRoleHolderSchema = z.object({
8435
+ kind: z.literal("team"),
8436
+ memberIds: z.array(z.string().trim().min(1).max(200)).min(1)
8437
+ });
8438
+ var RoleHolderSchema = z.discriminatedUnion("kind", [
8439
+ HumanRoleHolderSchema,
8440
+ AgentRoleHolderSchema,
8441
+ TeamRoleHolderSchema
8442
+ ]);
8443
+ var RoleHoldersSchema = z.union([RoleHolderSchema, z.array(RoleHolderSchema).min(1)]);
8444
+ var RoleSchema = z.object({
8445
+ /** Stable unique identifier for the role (e.g. "role-ceo", "role-head-of-sales"). */
8446
+ id: RoleIdSchema,
8447
+ /** Domain-map iteration order. Convention: multiples of 10 (10, 20, 30, ...) to allow easy insertion. */
8448
+ order: z.number(),
8449
+ /** Human-readable title shown to agents and in UI (e.g. "CEO", "Head of Sales"). */
8450
+ title: z.string().trim().min(1).max(200),
8451
+ /**
8452
+ * List of responsibilities this role owns - plain-language descriptions of
8453
+ * what the person in this role is accountable for delivering.
8454
+ * Defaults to empty array so minimal role definitions stay concise.
8455
+ */
8456
+ responsibilities: z.array(z.string().trim().max(500)).default([]),
8457
+ /**
8458
+ * Optional: ID of another role this role reports to.
8459
+ * When present, must reference another `roles[].id` in the same organization.
8460
+ */
8461
+ reportsToId: RoleIdSchema.meta({ ref: "role" }).optional(),
8462
+ /**
8463
+ * Optional: human, agent, or team holder currently filling this role.
8464
+ * Agent holders reference OM Resource IDs and are validated at the model level.
8465
+ */
8466
+ heldBy: RoleHoldersSchema.optional(),
8467
+ /**
8468
+ * Optional Systems this role is accountable for.
8469
+ * Cross-reference enforced in `OrganizationModelSchema.superRefine()`.
8470
+ */
8471
+ responsibleFor: z.array(SystemIdSchema.meta({ ref: "system" })).optional()
8472
+ });
8473
+ var RolesDomainSchema = z.record(z.string(), RoleSchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
8474
+ message: "Each role entry id must match its map key"
8475
+ }).default({});
8476
+ var DEFAULT_ORGANIZATION_MODEL_ROLES = {};
8477
+ var KeyResultSchema = z.object({
8478
+ /** Stable unique identifier for the measurable outcome (e.g. "kr-revenue-q1"). */
8479
+ id: z.string().trim().min(1).max(100),
8480
+ /** Plain-language description of this measurable outcome (e.g. "Increase trial-to-paid conversion"). */
8481
+ description: z.string().trim().min(1).max(500),
8482
+ /**
8483
+ * What is being measured — the metric name (e.g. "monthly revenue", "NPS score",
8484
+ * "trial-to-paid conversion rate"). Free-form string.
8485
+ */
8486
+ targetMetric: z.string().trim().min(1).max(200),
8487
+ /** Current measured value. Defaults to 0 when not yet tracked. */
8488
+ currentValue: z.number().default(0),
8489
+ /**
8490
+ * Target value to reach for this measurable outcome to be considered achieved.
8491
+ * Optional — omit if the outcome is directional (e.g. "reduce churn") without
8492
+ * a hard numeric target.
8493
+ */
8494
+ targetValue: z.number().optional()
8495
+ });
8496
+ var ISO_DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/;
8497
+ var ObjectiveSchema = z.object({
8498
+ /** Stable unique identifier for the goal (e.g. "goal-grow-arr-q1-2026"). */
8499
+ id: z.string().trim().min(1).max(100),
8500
+ /** Domain-map iteration order. Convention: multiples of 10 (10, 20, 30, ...) to allow easy insertion. */
8501
+ order: z.number(),
8502
+ /** Plain-language description of what the organization wants to achieve. */
8503
+ description: z.string().trim().min(1).max(1e3),
8504
+ /**
8505
+ * Start of the period this goal is active for — ISO 8601 date string (YYYY-MM-DD).
8506
+ * Must be strictly before `periodEnd`.
8507
+ */
8508
+ periodStart: z.string().regex(ISO_DATE_REGEX, "periodStart must be an ISO date string (YYYY-MM-DD)"),
8509
+ /**
8510
+ * End of the period this goal is active for — ISO 8601 date string (YYYY-MM-DD).
8511
+ * Must be strictly after `periodStart`.
8512
+ * Enforced via `OrganizationModelSchema.superRefine()`.
8513
+ */
8514
+ periodEnd: z.string().regex(ISO_DATE_REGEX, "periodEnd must be an ISO date string (YYYY-MM-DD)"),
8515
+ /**
8516
+ * List of measurable outcomes that define success for this goal.
8517
+ * Defaults to empty array so goals can be declared before outcomes are defined.
8518
+ */
8519
+ keyResults: z.array(KeyResultSchema).default([])
8520
+ });
8521
+ var GoalsDomainSchema = z.record(z.string(), ObjectiveSchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
8522
+ message: "Each objective entry id must match its map key"
8523
+ }).default({});
8524
+ var DEFAULT_ORGANIZATION_MODEL_GOALS = {};
8525
+ var SecretLikeMetadataKeySchema = /(?:secret|password|passwd|token|api[-_]?key|credential|private[-_]?key)/i;
8526
+ var SecretLikeMetadataValueSchema = /(?:sk-[A-Za-z0-9_-]{12,}|pk_live_[A-Za-z0-9_-]{12,}|eyJ[A-Za-z0-9_-]{20,}|-----BEGIN (?:RSA |OPENSSH |EC )?PRIVATE KEY-----)/;
8527
+ z.enum([
8528
+ "system",
8529
+ "resource",
8530
+ "ontology",
8531
+ "policy",
8532
+ "role",
8533
+ "trigger",
8534
+ "humanCheckpoint",
8535
+ "externalResource"
8536
+ ]);
8537
+ var OmTopologyRelationshipKindSchema = z.enum(["triggers", "uses", "approval"]);
8538
+ var OmTopologyNodeRefSchema = z.discriminatedUnion("kind", [
8539
+ z.object({ kind: z.literal("system"), id: ModelIdSchema }),
8540
+ z.object({ kind: z.literal("resource"), id: ResourceIdSchema }),
8541
+ z.object({ kind: z.literal("ontology"), id: OntologyIdSchema }),
8542
+ z.object({ kind: z.literal("policy"), id: ModelIdSchema }),
8543
+ z.object({ kind: z.literal("role"), id: ModelIdSchema }),
8544
+ z.object({ kind: z.literal("trigger"), id: ResourceIdSchema }),
8545
+ z.object({ kind: z.literal("humanCheckpoint"), id: ResourceIdSchema }),
8546
+ z.object({ kind: z.literal("externalResource"), id: ResourceIdSchema })
8547
+ ]);
8548
+ var OmTopologyMetadataSchema = z.record(z.string().trim().min(1).max(120), JsonValueSchema).superRefine((metadata, ctx) => {
8549
+ function visit(value, path) {
8550
+ if (typeof value === "string" && SecretLikeMetadataValueSchema.test(value)) {
8551
+ ctx.addIssue({
8552
+ code: z.ZodIssueCode.custom,
8553
+ path,
8554
+ message: "Topology metadata must not contain secret-like values"
8555
+ });
8556
+ return;
8557
+ }
8558
+ if (Array.isArray(value)) {
8559
+ value.forEach((entry, index2) => visit(entry, [...path, index2]));
8560
+ return;
8561
+ }
8562
+ if (typeof value !== "object" || value === null) return;
8563
+ Object.entries(value).forEach(([key, entry]) => {
8564
+ if (SecretLikeMetadataKeySchema.test(key)) {
8565
+ ctx.addIssue({
8566
+ code: z.ZodIssueCode.custom,
8567
+ path: [...path, key],
8568
+ message: `Topology metadata key "${key}" looks secret-like`
8569
+ });
8570
+ }
8571
+ visit(entry, [...path, key]);
8572
+ });
8573
+ }
8574
+ visit(metadata, []);
8575
+ });
8576
+ var OmTopologyRelationshipSchema = z.object({
8577
+ from: OmTopologyNodeRefSchema,
8578
+ kind: OmTopologyRelationshipKindSchema,
8579
+ to: OmTopologyNodeRefSchema,
8580
+ systemPath: SystemPathSchema.optional(),
8581
+ required: z.boolean().optional(),
8582
+ metadata: OmTopologyMetadataSchema.optional()
8583
+ });
8584
+ var OmTopologyDomainSchema = z.object({
8585
+ version: z.literal(1).default(1),
8586
+ relationships: z.record(z.string().trim().min(1).max(255), OmTopologyRelationshipSchema).default({})
8587
+ }).default({ version: 1, relationships: {} });
8588
+ var DEFAULT_ORGANIZATION_MODEL_TOPOLOGY = {
8589
+ version: 1,
8590
+ relationships: {}
8591
+ };
8592
+ var PolicyIdSchema = ModelIdSchema;
8593
+ var PolicyApplicabilitySchema = z.object({
8594
+ systemIds: z.array(ModelIdSchema.meta({ ref: "system" })).default([]),
8595
+ actionIds: z.array(ModelIdSchema.meta({ ref: "action" })).default([]),
8596
+ resourceIds: z.array(ModelIdSchema.meta({ ref: "resource" })).default([]),
8597
+ roleIds: z.array(ModelIdSchema.meta({ ref: "role" })).default([])
8598
+ });
8599
+ var PolicyTriggerSchema = z.discriminatedUnion("kind", [
8600
+ z.object({
8601
+ kind: z.literal("event"),
8602
+ eventId: EventIdSchema.meta({ ref: "event" })
8603
+ }),
8604
+ z.object({
8605
+ kind: z.literal("action-invocation"),
8606
+ actionId: ModelIdSchema.meta({ ref: "action" })
8607
+ }),
8608
+ z.object({
8609
+ kind: z.literal("schedule"),
8610
+ cron: z.string().trim().min(1).max(120)
8611
+ }),
8612
+ z.object({
8613
+ kind: z.literal("manual")
8614
+ })
8615
+ ]);
8616
+ var PolicyPredicateSchema = z.discriminatedUnion("kind", [
8617
+ z.object({
8618
+ kind: z.literal("always")
8619
+ }),
8620
+ z.object({
8621
+ kind: z.literal("expression"),
8622
+ expression: z.string().trim().min(1).max(2e3)
8623
+ }),
8624
+ z.object({
8625
+ kind: z.literal("threshold"),
8626
+ metric: ModelIdSchema,
8627
+ operator: z.enum(["lt", "lte", "eq", "gte", "gt"]).meta({ label: "Operator" }),
8628
+ value: z.number()
8629
+ })
8630
+ ]);
8631
+ var PolicyEffectSchema = z.discriminatedUnion("kind", [
8632
+ z.object({
8633
+ kind: z.literal("require-approval"),
8634
+ roleId: ModelIdSchema.meta({ ref: "role" }).optional()
8635
+ }),
8636
+ z.object({
8637
+ kind: z.literal("invoke-action"),
8638
+ actionId: ModelIdSchema.meta({ ref: "action" })
8639
+ }),
8640
+ z.object({
8641
+ kind: z.literal("notify-role"),
8642
+ roleId: ModelIdSchema.meta({ ref: "role" })
8643
+ }),
8644
+ z.object({
8645
+ kind: z.literal("block")
8646
+ })
8647
+ ]);
8648
+ var PolicySchema = z.object({
8649
+ id: PolicyIdSchema,
8650
+ /** Domain-map iteration order. Convention: multiples of 10 (10, 20, 30, ...) to allow easy insertion. */
8651
+ order: z.number(),
8652
+ label: LabelSchema,
8653
+ description: DescriptionSchema.optional(),
8654
+ trigger: PolicyTriggerSchema,
8655
+ predicate: PolicyPredicateSchema.default({ kind: "always" }),
8656
+ actions: z.array(PolicyEffectSchema).min(1),
8657
+ appliesTo: PolicyApplicabilitySchema.default({
8658
+ systemIds: [],
8659
+ actionIds: [],
8660
+ resourceIds: [],
8661
+ roleIds: []
8662
+ }),
8663
+ lifecycle: z.enum(["draft", "beta", "active", "deprecated", "archived"]).meta({ label: "Lifecycle", color: "teal" }).default("active")
8664
+ });
8665
+ var PoliciesDomainSchema = z.record(z.string(), PolicySchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
8666
+ message: "Each policy entry id must match its map key"
8667
+ }).default({});
8668
+ var DEFAULT_ORGANIZATION_MODEL_POLICIES = {};
8669
+
8670
+ // ../core/src/organization-model/content-kinds/registry.ts
8671
+ function defineContentType(def) {
8672
+ return def;
8673
+ }
8674
+ var PipelinePayloadSchema = z.object({
8675
+ /**
8676
+ * Local NodeId of the entity this pipeline applies to (e.g. 'crm.deal').
8677
+ * `.meta({ ref: 'entity' })` enables SchemaDrivenFieldList to render a
8678
+ * clickable graph link to the referenced entity node.
8679
+ */
8680
+ entityId: z.string().trim().min(1).max(200).meta({ label: "Entity", ref: "entity", hint: "The entity type this pipeline tracks" }),
8681
+ /**
8682
+ * Optional Kanban column color token for UI rendering.
8683
+ */
8684
+ kanbanColor: z.string().trim().min(1).max(40).optional().meta({ label: "Kanban color", hint: "UI color token" })
8685
+ });
8686
+ var pipelineKind = defineContentType({
8687
+ kind: "schema",
8688
+ type: "pipeline",
8689
+ label: "Pipeline",
8690
+ description: "A named progression pipeline that applies to a specific entity type.",
8691
+ payloadSchema: PipelinePayloadSchema,
8692
+ parentTypes: []
8693
+ });
8694
+ var StagePayloadSchema = z.object({
8695
+ /**
8696
+ * Semantic classification for this stage.
8697
+ * Drives color, icon, and CRM-priority logic in consuming views.
8698
+ * Optional — prospecting stages use data.entityKind instead.
8699
+ * Enum aligned with SalesStageSemanticClassSchema (sales.ts).
8700
+ */
8701
+ semanticClass: z.enum(["open", "active", "nurturing", "closed_won", "closed_lost", "won", "lost", "closed"]).optional().meta({ label: "Semantic class", hint: "Semantic meaning of this stage", color: "blue" })
8702
+ });
8703
+ var stageKind = defineContentType({
8704
+ kind: "schema",
8705
+ type: "stage",
8706
+ label: "Stage",
8707
+ description: "A stage within a pipeline. Must be parented under a schema:pipeline content node.",
8708
+ payloadSchema: StagePayloadSchema,
8709
+ parentTypes: ["schema:pipeline"]
8710
+ });
8711
+ var TemplatePayloadSchema = z.object({
8712
+ /**
8713
+ * Optional description surfaced in the KB describe view and tooling.
8714
+ */
8715
+ description: z.string().trim().min(1).max(2e3).optional().meta({ label: "Description", hint: "What this template is used for" })
8716
+ });
8717
+ var templateKind = defineContentType({
8718
+ kind: "schema",
8719
+ type: "template",
8720
+ label: "Template",
8721
+ description: "A named build template (e.g. a prospecting pipeline sequence).",
8722
+ payloadSchema: TemplatePayloadSchema,
8723
+ parentTypes: []
8724
+ });
8725
+ var TemplateStepPayloadSchema = z.object({
8726
+ /**
8727
+ * Which entity type this step primarily operates on.
8728
+ */
8729
+ primaryEntity: z.enum(["company", "contact"]).meta({ label: "Primary entity", hint: "Entity type this step processes", color: "blue" }),
8730
+ /**
8731
+ * Action key identifying the workflow action executed by this step.
8732
+ * `.meta({ ref: 'action' })` enables SchemaDrivenFieldList to render a
8733
+ * clickable graph link.
8734
+ */
8735
+ actionKey: z.string().trim().min(1).max(200).meta({ label: "Action", ref: "action", hint: "Workflow action executed by this step" }),
8736
+ /**
8737
+ * IDs of sibling step local NodeIds this step depends on.
8738
+ */
8739
+ dependsOn: z.array(z.string().trim().min(1).max(200)).optional().meta({ label: "Depends on", hint: "Local NodeIds of prerequisite steps" })
8740
+ });
8741
+ var templateStepKind = defineContentType({
8742
+ kind: "schema",
8743
+ type: "template-step",
8744
+ label: "Template Step",
8745
+ description: "A step within a build template. Must be parented under a schema:template content node.",
8746
+ payloadSchema: TemplateStepPayloadSchema,
8747
+ parentTypes: ["schema:template"]
8748
+ });
8749
+ var StatusFlowPayloadSchema = z.object({
8750
+ /**
8751
+ * Which entity scope this status flow governs.
8752
+ */
8753
+ appliesTo: z.enum(["project", "milestone", "task"]).meta({ label: "Applies to", hint: "Entity scope governed by this status flow", color: "blue" })
8754
+ });
8755
+ var statusFlowKind = defineContentType({
8756
+ kind: "schema",
8757
+ type: "status-flow",
8758
+ label: "Status Flow",
8759
+ description: "A named set of statuses governing a project, milestone, or task entity.",
8760
+ payloadSchema: StatusFlowPayloadSchema,
8761
+ parentTypes: []
8762
+ });
8763
+ var StatusPayloadSchema = z.object({
8764
+ /**
8765
+ * Semantic classification string for this status.
8766
+ * Free-form to allow tenant-defined classifications (e.g. 'active', 'blocked',
8767
+ * 'completed'). Used by UI to apply color and icon fallbacks.
8768
+ * Optional — status nodes may omit this when the label is self-descriptive.
8769
+ */
8770
+ semanticClass: z.string().trim().min(1).max(100).optional().meta({ label: "Semantic class", hint: "Semantic meaning of this status (e.g. active, blocked, completed)" }),
8771
+ /**
8772
+ * Optional UI color token override for this status.
8773
+ */
8774
+ color: z.string().trim().min(1).max(40).optional().meta({ label: "Color", hint: "UI color token" })
8775
+ });
8776
+ var statusKind = defineContentType({
8777
+ kind: "schema",
8778
+ type: "status",
8779
+ label: "Status",
8780
+ description: "A single status within a status flow. Must be parented under a schema:status-flow content node.",
8781
+ payloadSchema: StatusPayloadSchema,
8782
+ parentTypes: ["schema:status-flow"]
8783
+ });
8784
+ var ConfigKvPayloadSchema = z.object({
8785
+ /**
8786
+ * Flat key-value entries. Values are JSON primitives.
8787
+ * Keys are short identifiers (e.g. 'maxBatchSize', 'featureEnabled').
8788
+ */
8789
+ entries: z.record(z.string().trim().min(1).max(200), z.union([z.string(), z.number(), z.boolean(), z.null()])).meta({ label: "Entries", hint: "Key-value configuration entries (string, number, boolean, or null values)" })
8790
+ });
8791
+ var configKvKind = defineContentType({
8792
+ kind: "config",
8793
+ type: "kv",
8794
+ label: "Key-Value Config",
8795
+ description: "A flat key-value configuration store co-located with a system. Values are JSON primitives.",
8796
+ payloadSchema: ConfigKvPayloadSchema,
8797
+ parentTypes: []
8798
+ });
8799
+
8800
+ // ../core/src/organization-model/content-kinds/index.ts
8801
+ var CONTENT_KIND_REGISTRY = {
8802
+ "schema:pipeline": pipelineKind,
8803
+ "schema:stage": stageKind,
8804
+ "schema:template": templateKind,
8805
+ "schema:template-step": templateStepKind,
8806
+ "schema:status-flow": statusFlowKind,
8807
+ "schema:status": statusKind,
8808
+ "config:kv": configKvKind
8809
+ };
8810
+ function lookupContentType(kind, type3) {
8811
+ const key = `${kind}:${type3}`;
8812
+ return CONTENT_KIND_REGISTRY[key];
8813
+ }
8814
+ var SurfaceTypeSchema = z.enum(["page", "dashboard", "graph", "detail", "list", "settings"]).meta({ label: "Surface type", color: "blue" });
8815
+ z.object({
8816
+ id: ModelIdSchema,
8817
+ label: LabelSchema,
8818
+ path: PathSchema,
8819
+ surfaceType: SurfaceTypeSchema,
8820
+ description: DescriptionSchema.optional(),
8821
+ enabled: z.boolean().default(true),
8822
+ devOnly: z.boolean().optional(),
8823
+ icon: IconNameSchema.optional(),
8824
+ systemIds: z.array(ModelIdSchema.meta({ ref: "system" })).default([]),
8825
+ entityIds: z.array(ModelIdSchema.meta({ ref: "entity" })).default([]),
8826
+ resourceIds: z.array(ModelIdSchema.meta({ ref: "resource" })).default([]),
8827
+ actionIds: z.array(ModelIdSchema.meta({ ref: "action" })).default([]),
8828
+ parentId: ModelIdSchema.meta({ ref: "surface" }).optional()
8829
+ });
8830
+ var SidebarSurfaceTargetsSchema = z.object({
8831
+ systems: z.array(ModelIdSchema.meta({ ref: "system" })).default([]).optional(),
8832
+ entities: z.array(ModelIdSchema.meta({ ref: "entity" })).default([]).optional(),
8833
+ resources: z.array(ModelIdSchema.meta({ ref: "resource" })).default([]).optional(),
8834
+ actions: z.array(ModelIdSchema.meta({ ref: "action" })).default([]).optional()
8835
+ }).default({});
8836
+ var SidebarNodeSchema = z.lazy(
8837
+ () => z.discriminatedUnion("type", [
8838
+ z.object({
8839
+ type: z.literal("group"),
8840
+ label: LabelSchema,
8841
+ description: DescriptionSchema.optional(),
8842
+ icon: IconNameSchema.optional(),
8843
+ order: z.number().int().optional(),
8844
+ children: z.record(z.string(), SidebarNodeSchema).default({})
8845
+ }),
8846
+ z.object({
8847
+ type: z.literal("surface"),
8848
+ label: LabelSchema,
8849
+ path: PathSchema,
8850
+ surfaceType: SurfaceTypeSchema,
8851
+ description: DescriptionSchema.optional(),
8852
+ icon: IconNameSchema.optional(),
8853
+ order: z.number().int().optional(),
8854
+ targets: SidebarSurfaceTargetsSchema.optional(),
8855
+ devOnly: z.boolean().optional(),
8856
+ requiresAdmin: z.boolean().optional()
8857
+ })
8858
+ ])
8859
+ );
8860
+ var SidebarSectionSchema = z.record(z.string(), SidebarNodeSchema).default({});
8861
+ var SidebarNavigationSchema = z.object({
8862
+ primary: SidebarSectionSchema,
8863
+ bottom: SidebarSectionSchema
8864
+ }).default({ primary: {}, bottom: {} });
8865
+ var OrganizationModelNavigationSchema = z.object({
8866
+ sidebar: SidebarNavigationSchema
8867
+ }).default({ sidebar: { primary: {}, bottom: {} } });
8868
+ z.object({
8869
+ id: ModelIdSchema,
8870
+ label: LabelSchema,
8871
+ placement: z.string().trim().min(1).max(50),
8872
+ surfaceIds: z.array(ModelIdSchema.meta({ ref: "surface" })).default([])
8873
+ });
8874
+ var KnowledgeTargetKindSchema = z.enum([
8875
+ "system",
8876
+ "resource",
8877
+ "knowledge",
8878
+ "stage",
8879
+ "action",
8880
+ "role",
8881
+ "goal",
8882
+ "customer-segment",
8883
+ "offering",
8884
+ "ontology",
8885
+ // D4: content nodes are a valid knowledge target after compound-domain data moved into system.content
8886
+ "content-node"
8887
+ ]).meta({ label: "Target kind" });
8888
+ var KnowledgeTargetRefSchema = z.object({
8889
+ kind: KnowledgeTargetKindSchema,
8890
+ // D4: content-node targets use a qualified id format '<system-path>:<local-content-id>'.
8891
+ // Ontology targets use the canonical '<scope>:<kind>/<local-id>' ontology id format.
8892
+ // Business-logic validation of target existence is done in OrganizationModelSchema.superRefine.
8893
+ id: z.string().trim().min(1).max(300)
8894
+ }).superRefine((target, ctx) => {
8895
+ if (target.kind !== "ontology") return;
8896
+ const result = OntologyIdSchema.safeParse(target.id);
8897
+ if (!result.success) {
8898
+ ctx.addIssue({
8899
+ code: z.ZodIssueCode.custom,
8900
+ path: ["id"],
8901
+ message: "Ontology knowledge targets must use <system-path>:<kind>/<local-id> or global:<kind>/<local-id>"
8902
+ });
8903
+ }
8904
+ });
8905
+ var LegacyKnowledgeLinkSchema = z.object({
8906
+ nodeId: z.union([NodeIdStringSchema, z.templateLiteral(["ontology:", OntologyIdSchema])])
8907
+ });
8908
+ var CanonicalKnowledgeLinkSchema = z.object({
8909
+ target: KnowledgeTargetRefSchema
8910
+ });
8911
+ function nodeIdFromTarget(target) {
8912
+ return `${target.kind}:${target.id}`;
8913
+ }
8914
+ function targetFromNodeId(nodeId) {
8915
+ const [kind, ...idParts] = nodeId.split(":");
8916
+ return {
8917
+ kind: KnowledgeTargetKindSchema.parse(kind),
8918
+ id: idParts.join(":")
8919
+ };
8920
+ }
8921
+ var KnowledgeLinkSchema = z.union([CanonicalKnowledgeLinkSchema, LegacyKnowledgeLinkSchema]).transform((link) => {
8922
+ const target = "target" in link ? link.target : targetFromNodeId(link.nodeId);
8923
+ return {
8924
+ target,
8925
+ nodeId: nodeIdFromTarget(target)
8926
+ };
8927
+ });
8928
+ var OrgKnowledgeKindSchema = z.enum(["playbook", "strategy", "reference"]).meta({ label: "Knowledge kind", color: "grape" });
8929
+ var OrgKnowledgeNodeSchema = z.object({
8930
+ id: ModelIdSchema,
8931
+ kind: OrgKnowledgeKindSchema,
8932
+ title: z.string().trim().min(1).max(200),
8933
+ summary: z.string().trim().min(1).max(1e3),
8934
+ icon: IconNameSchema.optional(),
8935
+ /** Canonical documentation URL when body content is a local summary. */
8936
+ externalUrl: z.string().trim().url().max(500).optional(),
8937
+ /** Optional generated source file path for local MDX-backed knowledge nodes. */
8938
+ sourceFilePath: z.string().trim().min(1).max(500).optional(),
8939
+ /** Raw MDX string. Phase 2 will introduce a structured block format. */
8940
+ body: z.string().trim().min(1),
8941
+ /**
8942
+ * Graph links to other OM nodes this knowledge node governs.
8943
+ * Each link emits a `governs` edge: knowledge-node -> target node.
8944
+ */
8945
+ links: z.array(KnowledgeLinkSchema).default([]),
8946
+ /** Role identifiers that own this knowledge node. */
8947
+ ownerIds: z.array(RoleIdSchema.meta({ ref: "role" })).default([]),
8948
+ /** ISO date string (YYYY-MM-DD or full ISO 8601) of last meaningful update. */
8949
+ updatedAt: z.string().trim().min(1).max(50)
8950
+ });
8951
+ var KnowledgeDomainSchema = z.record(ModelIdSchema, OrgKnowledgeNodeSchema).default({});
8952
+
8953
+ // ../core/src/organization-model/schema.ts
8954
+ z.enum([
8955
+ "branding",
8956
+ "identity",
8957
+ "customers",
8958
+ "offerings",
8959
+ "roles",
8960
+ "goals",
8961
+ "systems",
8962
+ "ontology",
8963
+ "resources",
8964
+ "topology",
8965
+ "actions",
8966
+ "entities",
8967
+ "policies",
8968
+ "knowledge"
8969
+ ]);
8970
+ var OrganizationModelDomainMetadataSchema = z.object({
8971
+ version: z.literal(1).default(1),
8972
+ lastModified: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "lastModified must be an ISO date string (YYYY-MM-DD)")
8973
+ });
8974
+ var DEFAULT_ORGANIZATION_MODEL_DOMAIN_METADATA = {
8975
+ branding: { version: 1, lastModified: "2026-05-10" },
8976
+ identity: { version: 1, lastModified: "2026-05-10" },
8977
+ customers: { version: 1, lastModified: "2026-05-10" },
8978
+ offerings: { version: 1, lastModified: "2026-05-10" },
8979
+ roles: { version: 1, lastModified: "2026-05-10" },
8980
+ goals: { version: 1, lastModified: "2026-05-10" },
8981
+ systems: { version: 1, lastModified: "2026-05-10" },
8982
+ ontology: { version: 1, lastModified: "2026-05-14" },
8983
+ resources: { version: 1, lastModified: "2026-05-10" },
8984
+ topology: { version: 1, lastModified: "2026-05-14" },
8985
+ actions: { version: 1, lastModified: "2026-05-10" },
8986
+ entities: { version: 1, lastModified: "2026-05-10" },
8987
+ policies: { version: 1, lastModified: "2026-05-10" },
8988
+ knowledge: { version: 1, lastModified: "2026-05-10" }
8989
+ };
8990
+ var OrganizationModelDomainMetadataByDomainSchema = z.object({
8991
+ branding: OrganizationModelDomainMetadataSchema,
8992
+ identity: OrganizationModelDomainMetadataSchema,
8993
+ customers: OrganizationModelDomainMetadataSchema,
8994
+ offerings: OrganizationModelDomainMetadataSchema,
8995
+ roles: OrganizationModelDomainMetadataSchema,
8996
+ goals: OrganizationModelDomainMetadataSchema,
8997
+ systems: OrganizationModelDomainMetadataSchema,
8998
+ ontology: OrganizationModelDomainMetadataSchema,
8999
+ resources: OrganizationModelDomainMetadataSchema,
9000
+ topology: OrganizationModelDomainMetadataSchema,
9001
+ actions: OrganizationModelDomainMetadataSchema,
9002
+ entities: OrganizationModelDomainMetadataSchema,
9003
+ policies: OrganizationModelDomainMetadataSchema,
9004
+ knowledge: OrganizationModelDomainMetadataSchema
9005
+ }).partial().default(DEFAULT_ORGANIZATION_MODEL_DOMAIN_METADATA).transform((metadata) => ({ ...DEFAULT_ORGANIZATION_MODEL_DOMAIN_METADATA, ...metadata }));
9006
+ var OrganizationModelSchemaBase = z.object({
9007
+ version: z.literal(1).default(1),
9008
+ domainMetadata: OrganizationModelDomainMetadataByDomainSchema,
9009
+ branding: OrganizationModelBrandingSchema,
9010
+ navigation: OrganizationModelNavigationSchema,
9011
+ identity: IdentityDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_IDENTITY),
9012
+ customers: CustomersDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_CUSTOMERS),
9013
+ offerings: OfferingsDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_OFFERINGS),
9014
+ roles: RolesDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_ROLES),
9015
+ goals: GoalsDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_GOALS),
9016
+ systems: SystemsDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_SYSTEMS),
9017
+ ontology: OntologyScopeSchema.default(DEFAULT_ONTOLOGY_SCOPE),
9018
+ resources: ResourcesDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_RESOURCES),
9019
+ topology: OmTopologyDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_TOPOLOGY),
9020
+ actions: ActionsDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_ACTIONS),
9021
+ entities: EntitiesDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_ENTITIES),
9022
+ policies: PoliciesDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_POLICIES),
9023
+ // D3: flat Record<id, OrgKnowledgeNode> — no wrapper object
9024
+ knowledge: KnowledgeDomainSchema.default({})
9025
+ });
9026
+ function addIssue(ctx, path, message) {
9027
+ ctx.addIssue({
9028
+ code: z.ZodIssueCode.custom,
9029
+ path,
9030
+ message
9031
+ });
9032
+ }
9033
+ function isLifecycleEnabled(lifecycle, enabled) {
9034
+ if (enabled === false) return false;
9035
+ return lifecycle !== "deprecated" && lifecycle !== "archived";
9036
+ }
9037
+ function defaultSystemPathFor(id) {
9038
+ return `/${id.replaceAll(".", "/")}`;
9039
+ }
9040
+ function asRoleHolderArray(heldBy) {
9041
+ return Array.isArray(heldBy) ? heldBy : [heldBy];
9042
+ }
9043
+ function isKnowledgeKindCompatibleWithTarget(knowledgeKind, targetKind) {
9044
+ if (knowledgeKind === "reference") return true;
9045
+ if (knowledgeKind === "playbook") {
9046
+ return ["system", "resource", "stage", "action", "ontology"].includes(targetKind);
9047
+ }
9048
+ if (knowledgeKind === "strategy") {
9049
+ return ["system", "goal", "offering", "customer-segment", "ontology"].includes(targetKind);
9050
+ }
9051
+ return false;
9052
+ }
9053
+ function isRecord(value) {
9054
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9055
+ }
9056
+ OrganizationModelSchemaBase.superRefine((model, ctx) => {
9057
+ function collectAllSystems(systems, prefix = "", schemaPath = ["systems"]) {
9058
+ const result = [];
9059
+ for (const [key, system] of Object.entries(systems)) {
9060
+ const path = prefix ? `${prefix}.${key}` : key;
9061
+ const currentSchemaPath = [...schemaPath, key];
9062
+ result.push({ path, schemaPath: currentSchemaPath, system });
9063
+ const childSystems = system.systems ?? system.subsystems;
9064
+ if (childSystems !== void 0) {
9065
+ result.push(
9066
+ ...collectAllSystems(childSystems, path, [...currentSchemaPath, system.systems !== void 0 ? "systems" : "subsystems"])
9067
+ );
9068
+ }
9069
+ }
9070
+ return result;
9071
+ }
9072
+ const allSystems = collectAllSystems(model.systems);
9073
+ const systemsById = /* @__PURE__ */ new Map();
9074
+ for (const { path, system } of allSystems) {
9075
+ systemsById.set(path, system);
9076
+ systemsById.set(system.id, system);
9077
+ }
9078
+ const systemIdsByEffectivePath = /* @__PURE__ */ new Map();
9079
+ allSystems.forEach(({ path, schemaPath, system }) => {
9080
+ if (system.parentSystemId !== void 0 && !systemsById.has(system.parentSystemId)) {
9081
+ addIssue(
9082
+ ctx,
9083
+ [...schemaPath, "parentSystemId"],
9084
+ `System "${system.id}" references unknown parent "${system.parentSystemId}"`
9085
+ );
9086
+ }
9087
+ const hasChildren = Object.keys(system.systems ?? system.subsystems ?? {}).length > 0 || allSystems.some((candidate) => candidate.path.startsWith(`${path}.`) && !candidate.path.slice(path.length + 1).includes("."));
9088
+ const contributesRoutePath = system.ui?.path !== void 0 || system.path !== void 0 || !hasChildren;
9089
+ if (contributesRoutePath) {
9090
+ const effectivePath = system.ui?.path ?? system.path ?? defaultSystemPathFor(path);
9091
+ const existingSystemId = systemIdsByEffectivePath.get(effectivePath);
9092
+ if (existingSystemId !== void 0) {
9093
+ addIssue(
9094
+ ctx,
9095
+ [...schemaPath, system.ui?.path !== void 0 ? "ui" : "path"],
9096
+ `System "${path}" effective path "${effectivePath}" duplicates system "${existingSystemId}"`
9097
+ );
9098
+ } else {
9099
+ systemIdsByEffectivePath.set(effectivePath, path);
9100
+ }
9101
+ }
9102
+ if (hasChildren && isLifecycleEnabled(system.lifecycle, system.enabled)) {
9103
+ const hasEnabledDescendant = Object.values(system.systems ?? system.subsystems ?? {}).some(
9104
+ (candidate) => isLifecycleEnabled(candidate.lifecycle, candidate.enabled)
9105
+ ) || allSystems.some(
9106
+ (candidate) => candidate.path.startsWith(`${path}.`) && !candidate.path.slice(path.length + 1).includes(".") && isLifecycleEnabled(candidate.system.lifecycle, candidate.system.enabled)
9107
+ );
9108
+ if (!hasEnabledDescendant) {
9109
+ addIssue(
9110
+ ctx,
9111
+ [...schemaPath, "lifecycle"],
9112
+ `System "${path}" is active but has no active descendants`
9113
+ );
9114
+ }
9115
+ }
9116
+ });
9117
+ allSystems.forEach(({ schemaPath, system }) => {
9118
+ const visited = /* @__PURE__ */ new Set();
9119
+ let currentParentId = system.parentSystemId;
9120
+ while (currentParentId !== void 0) {
9121
+ if (currentParentId === system.id || visited.has(currentParentId)) {
9122
+ addIssue(ctx, [...schemaPath, "parentSystemId"], `System "${system.id}" has a parent cycle`);
9123
+ return;
9124
+ }
9125
+ visited.add(currentParentId);
9126
+ currentParentId = systemsById.get(currentParentId)?.parentSystemId;
9127
+ }
9128
+ });
9129
+ function normalizeRoutePath(path) {
9130
+ return path.length > 1 ? path.replace(/\/+$/, "") : path;
9131
+ }
9132
+ const sidebarNodeIds = /* @__PURE__ */ new Map();
9133
+ const sidebarSurfacePaths = /* @__PURE__ */ new Map();
9134
+ const sidebarSurfaces = [];
9135
+ function collectSidebarNodes(nodes, schemaPath) {
9136
+ Object.entries(nodes).forEach(([nodeId, node]) => {
9137
+ const nodePath = [...schemaPath, nodeId];
9138
+ const existingNodePath = sidebarNodeIds.get(nodeId);
9139
+ if (existingNodePath !== void 0) {
9140
+ addIssue(ctx, nodePath, `Sidebar node id "${nodeId}" duplicates another sidebar node`);
9141
+ } else {
9142
+ sidebarNodeIds.set(nodeId, nodePath);
9143
+ }
9144
+ if (node.type === "group") {
9145
+ collectSidebarNodes(node.children, [...nodePath, "children"]);
9146
+ return;
9147
+ }
9148
+ sidebarSurfaces.push({ id: nodeId, node, path: nodePath });
9149
+ const normalizedPath = normalizeRoutePath(node.path);
9150
+ const existingSurfaceId = sidebarSurfacePaths.get(normalizedPath);
9151
+ if (existingSurfaceId !== void 0) {
9152
+ addIssue(
9153
+ ctx,
9154
+ [...nodePath, "path"],
9155
+ `Sidebar surface path "${node.path}" duplicates surface "${existingSurfaceId}"`
9156
+ );
9157
+ } else {
9158
+ sidebarSurfacePaths.set(normalizedPath, nodeId);
9159
+ }
9160
+ node.targets?.systems?.forEach((systemId, systemIndex) => {
9161
+ if (!systemsById.has(systemId)) {
9162
+ addIssue(
9163
+ ctx,
9164
+ [...nodePath, "targets", "systems", systemIndex],
9165
+ `Sidebar surface "${nodeId}" references unknown system "${systemId}"`
9166
+ );
9167
+ }
9168
+ });
9169
+ });
9170
+ }
9171
+ collectSidebarNodes(model.navigation.sidebar.primary, ["navigation", "sidebar", "primary"]);
9172
+ collectSidebarNodes(model.navigation.sidebar.bottom, ["navigation", "sidebar", "bottom"]);
9173
+ const segmentsById = new Map(Object.entries(model.customers));
9174
+ Object.values(model.offerings).forEach((product) => {
9175
+ product.targetSegmentIds.forEach((segmentId, segmentIndex) => {
9176
+ if (!segmentsById.has(segmentId)) {
9177
+ addIssue(
9178
+ ctx,
9179
+ ["offerings", product.id, "targetSegmentIds", segmentIndex],
9180
+ `Product "${product.id}" references unknown customer segment "${segmentId}"`
9181
+ );
9182
+ }
9183
+ });
9184
+ if (product.deliveryFeatureId !== void 0 && !systemsById.has(product.deliveryFeatureId)) {
9185
+ addIssue(
9186
+ ctx,
9187
+ ["offerings", product.id, "deliveryFeatureId"],
9188
+ `Product "${product.id}" references unknown delivery system "${product.deliveryFeatureId}"`
9189
+ );
9190
+ }
9191
+ });
9192
+ Object.values(model.goals).forEach((objective) => {
9193
+ if (objective.periodEnd <= objective.periodStart) {
9194
+ addIssue(
9195
+ ctx,
9196
+ ["goals", objective.id, "periodEnd"],
9197
+ `Goal "${objective.id}" has periodEnd "${objective.periodEnd}" which must be strictly after periodStart "${objective.periodStart}"`
9198
+ );
9199
+ }
9200
+ });
9201
+ const goalsById = new Map(Object.entries(model.goals));
9202
+ const knowledgeById = new Map(Object.entries(model.knowledge));
9203
+ const actionsById = new Map(Object.entries(model.actions));
9204
+ const entitiesById = new Map(Object.entries(model.entities));
9205
+ const policiesById = new Map(Object.entries(model.policies));
9206
+ sidebarSurfaces.forEach(({ id, node, path }) => {
9207
+ node.targets?.entities?.forEach((entityId, entityIndex) => {
9208
+ if (!entitiesById.has(entityId)) {
9209
+ addIssue(
9210
+ ctx,
9211
+ [...path, "targets", "entities", entityIndex],
9212
+ `Sidebar surface "${id}" references unknown entity "${entityId}"`
9213
+ );
9214
+ }
9215
+ });
9216
+ node.targets?.actions?.forEach((actionId, actionIndex) => {
9217
+ if (!actionsById.has(actionId)) {
9218
+ addIssue(
9219
+ ctx,
9220
+ [...path, "targets", "actions", actionIndex],
9221
+ `Sidebar surface "${id}" references unknown action "${actionId}"`
9222
+ );
9223
+ }
9224
+ });
9225
+ });
9226
+ Object.values(model.entities).forEach((entity) => {
9227
+ if (!systemsById.has(entity.ownedBySystemId)) {
9228
+ addIssue(
9229
+ ctx,
9230
+ ["entities", entity.id, "ownedBySystemId"],
9231
+ `Entity "${entity.id}" references unknown ownedBySystemId "${entity.ownedBySystemId}"`
9232
+ );
9233
+ }
9234
+ entity.links?.forEach((link, linkIndex) => {
9235
+ if (!entitiesById.has(link.toEntity)) {
9236
+ addIssue(
9237
+ ctx,
9238
+ ["entities", entity.id, "links", linkIndex, "toEntity"],
9239
+ `Entity "${entity.id}" links to unknown entity "${link.toEntity}"`
9240
+ );
9241
+ }
9242
+ });
9243
+ });
9244
+ const rolesById = new Map(Object.entries(model.roles));
9245
+ Object.values(model.roles).forEach((role) => {
9246
+ if (role.reportsToId !== void 0 && !rolesById.has(role.reportsToId)) {
9247
+ addIssue(
9248
+ ctx,
9249
+ ["roles", role.id, "reportsToId"],
9250
+ `Role "${role.id}" references unknown reportsToId "${role.reportsToId}"`
9251
+ );
9252
+ }
9253
+ });
9254
+ Object.values(model.roles).forEach((role) => {
9255
+ const visited = /* @__PURE__ */ new Set();
9256
+ let currentReportsToId = role.reportsToId;
9257
+ while (currentReportsToId !== void 0) {
9258
+ if (currentReportsToId === role.id || visited.has(currentReportsToId)) {
9259
+ addIssue(ctx, ["roles", role.id, "reportsToId"], `Role "${role.id}" has a reportsToId cycle`);
9260
+ return;
9261
+ }
9262
+ visited.add(currentReportsToId);
9263
+ currentReportsToId = rolesById.get(currentReportsToId)?.reportsToId;
9264
+ }
9265
+ });
9266
+ Object.values(model.roles).forEach((role) => {
9267
+ role.responsibleFor?.forEach((systemId, systemIndex) => {
9268
+ if (!systemsById.has(systemId)) {
9269
+ addIssue(
9270
+ ctx,
9271
+ ["roles", role.id, "responsibleFor", systemIndex],
9272
+ `Role "${role.id}" references unknown responsibleFor system "${systemId}"`
9273
+ );
9274
+ }
9275
+ });
9276
+ });
9277
+ allSystems.forEach(({ schemaPath, system }) => {
9278
+ if (system.responsibleRoleId !== void 0 && !rolesById.has(system.responsibleRoleId)) {
9279
+ addIssue(
9280
+ ctx,
9281
+ [...schemaPath, "responsibleRoleId"],
9282
+ `System "${system.id}" references unknown responsibleRoleId "${system.responsibleRoleId}"`
9283
+ );
9284
+ }
9285
+ system.governedByKnowledge?.forEach((nodeId, nodeIndex) => {
9286
+ if (!knowledgeById.has(nodeId)) {
9287
+ addIssue(
9288
+ ctx,
9289
+ [...schemaPath, "governedByKnowledge", nodeIndex],
9290
+ `System "${system.id}" references unknown knowledge node "${nodeId}"`
9291
+ );
9292
+ }
9293
+ });
9294
+ system.drivesGoals?.forEach((goalId, goalIndex) => {
9295
+ if (!goalsById.has(goalId)) {
9296
+ addIssue(
9297
+ ctx,
9298
+ [...schemaPath, "drivesGoals", goalIndex],
9299
+ `System "${system.id}" references unknown goal "${goalId}"`
9300
+ );
9301
+ }
9302
+ });
9303
+ system.actions?.forEach((actionRef, actionIndex) => {
9304
+ if (!actionsById.has(actionRef.actionId)) {
9305
+ addIssue(
9306
+ ctx,
9307
+ [...schemaPath, "actions", actionIndex, "actionId"],
9308
+ `System "${system.id}" references unknown action "${actionRef.actionId}"`
9309
+ );
9310
+ }
9311
+ });
9312
+ system.policies?.forEach((policyId, policyIndex) => {
9313
+ if (!policiesById.has(policyId)) {
9314
+ addIssue(
9315
+ ctx,
9316
+ [...schemaPath, "policies", policyIndex],
9317
+ `System "${system.id}" references unknown policy "${policyId}"`
9318
+ );
9319
+ }
9320
+ });
9321
+ });
9322
+ Object.values(model.actions).forEach((action) => {
9323
+ action.affects?.forEach((entityId, entityIndex) => {
9324
+ if (!entitiesById.has(entityId)) {
9325
+ addIssue(
9326
+ ctx,
9327
+ ["actions", action.id, "affects", entityIndex],
9328
+ `Action "${action.id}" affects unknown entity "${entityId}"`
9329
+ );
9330
+ }
9331
+ });
9332
+ });
9333
+ const resourcesById = new Map(Object.entries(model.resources));
9334
+ sidebarSurfaces.forEach(({ id, node, path }) => {
9335
+ node.targets?.resources?.forEach((resourceId, resourceIndex) => {
9336
+ if (!resourcesById.has(resourceId)) {
9337
+ addIssue(
9338
+ ctx,
9339
+ [...path, "targets", "resources", resourceIndex],
9340
+ `Sidebar surface "${id}" references unknown resource "${resourceId}"`
9341
+ );
9342
+ }
9343
+ });
9344
+ });
9345
+ const stageIds = /* @__PURE__ */ new Set();
9346
+ const actionIds = new Set(Object.keys(model.actions));
9347
+ const offeringsById = new Map(Object.entries(model.offerings));
9348
+ const ontologyCompilation = compileOrganizationOntology(model);
9349
+ const ontologyIndexByKind = {
9350
+ object: ontologyCompilation.ontology.objectTypes,
9351
+ link: ontologyCompilation.ontology.linkTypes,
9352
+ action: ontologyCompilation.ontology.actionTypes,
9353
+ catalog: ontologyCompilation.ontology.catalogTypes,
9354
+ event: ontologyCompilation.ontology.eventTypes,
9355
+ interface: ontologyCompilation.ontology.interfaceTypes,
9356
+ "value-type": ontologyCompilation.ontology.valueTypes,
9357
+ property: ontologyCompilation.ontology.sharedProperties,
9358
+ group: ontologyCompilation.ontology.groups,
9359
+ surface: ontologyCompilation.ontology.surfaces
9360
+ };
9361
+ const ontologyIds = new Set(Object.values(ontologyIndexByKind).flatMap((index2) => Object.keys(index2)));
9362
+ function topologyTargetExists(ref) {
9363
+ if (ref.kind === "system") return systemsById.has(ref.id);
9364
+ if (ref.kind === "resource") return resourcesById.has(ref.id);
9365
+ if (ref.kind === "ontology") return ontologyIds.has(ref.id);
9366
+ if (ref.kind === "policy") return policiesById.has(ref.id);
9367
+ if (ref.kind === "role") return rolesById.has(ref.id);
9368
+ return true;
9369
+ }
9370
+ Object.entries(model.topology.relationships).forEach(([relationshipId, relationship]) => {
9371
+ ["from", "to"].forEach((side) => {
9372
+ const ref = relationship[side];
9373
+ if (topologyTargetExists(ref)) return;
9374
+ addIssue(
9375
+ ctx,
9376
+ ["topology", "relationships", relationshipId, side],
9377
+ `Topology relationship "${relationshipId}" ${side} references unknown ${ref.kind} "${ref.id}"`
9378
+ );
9379
+ });
9380
+ });
9381
+ const ontologyReferenceKeyKinds = {
9382
+ valueType: "value-type",
9383
+ catalogType: "catalog",
9384
+ objectType: "object",
9385
+ eventType: "event",
9386
+ actionType: "action",
9387
+ linkType: "link",
9388
+ interfaceType: "interface",
9389
+ propertyType: "property",
9390
+ groupType: "group",
9391
+ surfaceType: "surface",
9392
+ stepCatalog: "catalog"
9393
+ };
9394
+ function validateKnownOntologyReferences(ownerId, value, path, seen = /* @__PURE__ */ new WeakSet()) {
9395
+ if (Array.isArray(value)) {
9396
+ value.forEach((entry, index2) => validateKnownOntologyReferences(ownerId, entry, [...path, index2], seen));
9397
+ return;
9398
+ }
9399
+ if (!isRecord(value)) return;
9400
+ if (seen.has(value)) return;
9401
+ seen.add(value);
9402
+ Object.entries(value).forEach(([key, entry]) => {
9403
+ const expectedKind = ontologyReferenceKeyKinds[key];
9404
+ if (expectedKind !== void 0) {
9405
+ if (typeof entry !== "string") {
9406
+ addIssue(ctx, [...path, key], `Ontology record "${ownerId}" ${key} must be an ontology ID string`);
9407
+ } else if (ontologyIndexByKind[expectedKind][entry] === void 0) {
9408
+ addIssue(
9409
+ ctx,
9410
+ [...path, key],
9411
+ `Ontology record "${ownerId}" ${key} references unknown ${expectedKind} ontology ID "${entry}"`
9412
+ );
9413
+ }
9414
+ }
9415
+ validateKnownOntologyReferences(ownerId, entry, [...path, key], seen);
9416
+ });
9417
+ }
9418
+ for (const { id, record } of listResolvedOntologyRecords(ontologyCompilation.ontology)) {
9419
+ validateKnownOntologyReferences(id, record, record.origin.path);
9420
+ }
9421
+ Object.values(model.policies).forEach((policy) => {
9422
+ policy.appliesTo.systemIds.forEach((systemId, systemIndex) => {
9423
+ if (!systemsById.has(systemId)) {
9424
+ addIssue(
9425
+ ctx,
9426
+ ["policies", policy.id, "appliesTo", "systemIds", systemIndex],
9427
+ `Policy "${policy.id}" applies to unknown system "${systemId}"`
9428
+ );
9429
+ }
9430
+ });
9431
+ policy.appliesTo.actionIds.forEach((actionId, actionIndex) => {
9432
+ if (!actionsById.has(actionId)) {
9433
+ addIssue(
9434
+ ctx,
9435
+ ["policies", policy.id, "appliesTo", "actionIds", actionIndex],
9436
+ `Policy "${policy.id}" applies to unknown action "${actionId}"`
9437
+ );
9438
+ }
9439
+ });
9440
+ policy.actions.forEach((action, actionIndex) => {
9441
+ if (action.kind === "invoke-action" && !actionsById.has(action.actionId)) {
9442
+ addIssue(
9443
+ ctx,
9444
+ ["policies", policy.id, "actions", actionIndex, "actionId"],
9445
+ `Policy "${policy.id}" invokes unknown action "${action.actionId}"`
9446
+ );
9447
+ }
9448
+ if ((action.kind === "notify-role" || action.kind === "require-approval") && action.roleId !== void 0 && !rolesById.has(action.roleId)) {
9449
+ addIssue(
9450
+ ctx,
9451
+ ["policies", policy.id, "actions", actionIndex, "roleId"],
9452
+ `Policy "${policy.id}" references unknown role "${action.roleId}"`
9453
+ );
9454
+ }
9455
+ });
9456
+ if (policy.trigger.kind === "action-invocation" && !actionsById.has(policy.trigger.actionId)) {
9457
+ addIssue(
9458
+ ctx,
9459
+ ["policies", policy.id, "trigger", "actionId"],
9460
+ `Policy "${policy.id}" references unknown trigger action "${policy.trigger.actionId}"`
9461
+ );
9462
+ }
9463
+ });
9464
+ function knowledgeTargetExists(kind, id) {
9465
+ if (kind === "system") return systemsById.has(id);
9466
+ if (kind === "resource") return resourcesById.has(id);
9467
+ if (kind === "knowledge") return knowledgeById.has(id);
9468
+ if (kind === "stage") return stageIds.has(id);
9469
+ if (kind === "action") return actionIds.has(id);
9470
+ if (kind === "role") return rolesById.has(id);
9471
+ if (kind === "goal") return goalsById.has(id);
9472
+ if (kind === "customer-segment") return segmentsById.has(id);
9473
+ if (kind === "offering") return offeringsById.has(id);
9474
+ if (kind === "ontology") return ontologyIds.has(id);
9475
+ return false;
9476
+ }
9477
+ Object.entries(model.knowledge).forEach(([nodeId, node]) => {
9478
+ node.links.forEach((link, linkIndex) => {
9479
+ if (!knowledgeTargetExists(link.target.kind, link.target.id)) {
9480
+ addIssue(
9481
+ ctx,
9482
+ ["knowledge", nodeId, "links", linkIndex, "target"],
9483
+ `Knowledge node "${node.id}" references unknown ${link.target.kind} target "${link.target.id}"`
9484
+ );
9485
+ }
9486
+ if (!isKnowledgeKindCompatibleWithTarget(node.kind, link.target.kind)) {
9487
+ addIssue(
9488
+ ctx,
9489
+ ["knowledge", nodeId, "links", linkIndex, "target", "kind"],
9490
+ `Knowledge node "${node.id}" kind "${node.kind}" cannot govern ${link.target.kind} targets`
9491
+ );
9492
+ }
9493
+ });
9494
+ });
9495
+ Object.values(model.resources).forEach((resource) => {
9496
+ if (!systemsById.has(resource.systemPath)) {
9497
+ addIssue(
9498
+ ctx,
9499
+ ["resources", resource.id, "systemPath"],
9500
+ `Resource "${resource.id}" references unknown system path "${resource.systemPath}"`
9501
+ );
9502
+ }
9503
+ if (resource.ownerRoleId !== void 0 && !rolesById.has(resource.ownerRoleId)) {
9504
+ addIssue(
9505
+ ctx,
9506
+ ["resources", resource.id, "ownerRoleId"],
9507
+ `Resource "${resource.id}" references unknown ownerRoleId "${resource.ownerRoleId}"`
9508
+ );
9509
+ }
9510
+ if (resource.kind === "agent" && resource.actsAsRoleId !== void 0 && !rolesById.has(resource.actsAsRoleId)) {
9511
+ addIssue(
9512
+ ctx,
9513
+ ["resources", resource.id, "actsAsRoleId"],
9514
+ `Agent resource "${resource.id}" references unknown actsAsRoleId "${resource.actsAsRoleId}"`
9515
+ );
9516
+ }
9517
+ });
9518
+ function validateResourceOntologyBinding(resourceId, bindingKey, expectedKind, ids) {
9519
+ const ontologyIds2 = ids === void 0 ? [] : Array.isArray(ids) ? ids : [ids];
9520
+ ontologyIds2.forEach((ontologyId, ontologyIndex) => {
9521
+ if (ontologyIndexByKind[expectedKind][ontologyId] === void 0) {
9522
+ addIssue(
9523
+ ctx,
9524
+ [
9525
+ "resources",
9526
+ resourceId,
9527
+ "ontology",
9528
+ bindingKey,
9529
+ ...Array.isArray(ids) ? [ontologyIndex] : []
9530
+ ],
9531
+ `Resource "${resourceId}" ontology binding "${bindingKey}" references unknown ${expectedKind} ontology ID "${ontologyId}"`
9532
+ );
9533
+ }
9534
+ });
9535
+ }
9536
+ Object.values(model.resources).forEach((resource) => {
9537
+ const binding = resource.ontology;
9538
+ if (binding === void 0) return;
9539
+ validateResourceOntologyBinding(resource.id, "actions", "action", binding.actions);
9540
+ validateResourceOntologyBinding(resource.id, "primaryAction", "action", binding.primaryAction);
9541
+ validateResourceOntologyBinding(resource.id, "reads", "object", binding.reads);
9542
+ validateResourceOntologyBinding(resource.id, "writes", "object", binding.writes);
9543
+ validateResourceOntologyBinding(resource.id, "usesCatalogs", "catalog", binding.usesCatalogs);
9544
+ validateResourceOntologyBinding(resource.id, "emits", "event", binding.emits);
9545
+ });
9546
+ Object.values(model.roles).forEach((role) => {
9547
+ if (role.heldBy === void 0) return;
9548
+ asRoleHolderArray(role.heldBy).forEach((holder, holderIndex) => {
9549
+ if (holder.kind !== "agent") return;
9550
+ const resource = resourcesById.get(holder.agentId);
9551
+ if (resource === void 0) {
9552
+ addIssue(
9553
+ ctx,
9554
+ ["roles", role.id, "heldBy", Array.isArray(role.heldBy) ? holderIndex : "agentId"],
9555
+ `Role "${role.id}" references unknown agent holder resource "${holder.agentId}"`
9556
+ );
9557
+ return;
9558
+ }
9559
+ if (resource.kind !== "agent") {
9560
+ addIssue(
9561
+ ctx,
9562
+ ["roles", role.id, "heldBy", Array.isArray(role.heldBy) ? holderIndex : "agentId"],
9563
+ `Role "${role.id}" agent holder "${holder.agentId}" must reference an agent resource`
9564
+ );
9565
+ }
9566
+ });
9567
+ });
9568
+ Object.entries(model.knowledge).forEach(([nodeId, node]) => {
9569
+ node.ownerIds.forEach((roleId, ownerIndex) => {
9570
+ if (!rolesById.has(roleId)) {
9571
+ addIssue(
9572
+ ctx,
9573
+ ["knowledge", nodeId, "ownerIds", ownerIndex],
9574
+ `Knowledge node "${node.id}" references unknown owner role "${roleId}"`
9575
+ );
9576
+ }
9577
+ });
9578
+ });
9579
+ function validateSystemContent(system, systemPath) {
9580
+ const childSystems = system.systems ?? system.subsystems;
9581
+ const childKey = system.systems !== void 0 ? "systems" : "subsystems";
9582
+ const content = system.content;
9583
+ if (content === void 0 || Object.keys(content).length === 0) {
9584
+ if (childSystems !== void 0) {
9585
+ Object.entries(childSystems).forEach(([childLocalId, child]) => {
9586
+ validateSystemContent(child, [...systemPath, childKey, childLocalId]);
9587
+ });
9588
+ }
9589
+ return;
9590
+ }
9591
+ Object.entries(content).forEach(([localId, node]) => {
9592
+ if (node.parentContentId !== void 0 && !(node.parentContentId in content)) {
9593
+ addIssue(
9594
+ ctx,
9595
+ [...systemPath, "content", localId, "parentContentId"],
9596
+ `Content node "${localId}" parentContentId "${node.parentContentId}" does not resolve within the same system`
9597
+ );
9598
+ }
9599
+ });
9600
+ Object.entries(content).forEach(([localId, node]) => {
9601
+ const visited = /* @__PURE__ */ new Set();
9602
+ let currentId = node.parentContentId;
9603
+ while (currentId !== void 0) {
9604
+ if (currentId === localId || visited.has(currentId)) {
9605
+ addIssue(
9606
+ ctx,
9607
+ [...systemPath, "content", localId, "parentContentId"],
9608
+ `Content node "${localId}" has a parentContentId cycle`
9609
+ );
9610
+ break;
9611
+ }
9612
+ visited.add(currentId);
9613
+ currentId = content[currentId]?.parentContentId;
9614
+ }
9615
+ });
9616
+ Object.entries(content).forEach(([localId, node]) => {
9617
+ const childDef = lookupContentType(node.kind, node.type);
9618
+ if (childDef !== void 0 && node.data !== void 0) {
9619
+ const result = childDef.payloadSchema.safeParse(node.data);
9620
+ if (!result.success) {
9621
+ addIssue(
9622
+ ctx,
9623
+ [...systemPath, "content", localId, "data"],
9624
+ `Content node "${localId}" (${node.kind}:${node.type}) data failed payload validation: ${result.error.message}`
9625
+ );
9626
+ }
9627
+ }
9628
+ if (node.parentContentId !== void 0 && childDef !== void 0) {
9629
+ const parentNode = content[node.parentContentId];
9630
+ if (parentNode !== void 0) {
9631
+ const parentDef = lookupContentType(parentNode.kind, parentNode.type);
9632
+ if (parentDef !== void 0 && childDef.kind !== parentDef.kind) {
9633
+ addIssue(
9634
+ ctx,
9635
+ [...systemPath, "content", localId, "parentContentId"],
9636
+ `Content node "${localId}" kind "${childDef.kind}" cannot parent under "${node.parentContentId}" kind "${parentDef.kind}": parentContentId must be same-meta-kind (per L19)`
9637
+ );
9638
+ }
9639
+ }
9640
+ }
9641
+ });
9642
+ if (childSystems !== void 0) {
9643
+ Object.entries(childSystems).forEach(([childLocalId, child]) => {
9644
+ validateSystemContent(child, [...systemPath, childKey, childLocalId]);
9645
+ });
9646
+ }
9647
+ }
9648
+ Object.entries(model.systems).forEach(([systemKey, system]) => {
9649
+ validateSystemContent(system, ["systems", systemKey]);
9650
+ });
9651
+ for (const diagnostic of ontologyCompilation.diagnostics) {
9652
+ addIssue(ctx, diagnostic.path, diagnostic.message);
9653
+ }
7438
9654
  });
7439
- var CRM_DISCOVERY_REPLIED_STATE = {
7440
- stateKey: "discovery_replied",
7441
- label: "Discovery Replied"
7442
- };
7443
- var CRM_DISCOVERY_LINK_SENT_STATE = {
7444
- stateKey: "discovery_link_sent",
7445
- label: "Discovery Link Sent"
7446
- };
7447
- var CRM_DISCOVERY_NUDGING_STATE = {
7448
- stateKey: "discovery_nudging",
7449
- label: "Discovery Nudging"
7450
- };
7451
- var CRM_DISCOVERY_BOOKING_CANCELLED_STATE = {
7452
- stateKey: "discovery_booking_cancelled",
7453
- label: "Discovery Booking Cancelled"
7454
- };
7455
- var CRM_REPLY_SENT_STATE = {
7456
- stateKey: "reply_sent",
7457
- label: "Reply Sent"
7458
- };
7459
- var CRM_FOLLOWUP_1_SENT_STATE = {
7460
- stateKey: "followup_1_sent",
7461
- label: "Follow-up 1 Sent"
7462
- };
7463
- var CRM_FOLLOWUP_2_SENT_STATE = {
7464
- stateKey: "followup_2_sent",
7465
- label: "Follow-up 2 Sent"
7466
- };
7467
- var CRM_FOLLOWUP_3_SENT_STATE = {
7468
- stateKey: "followup_3_sent",
7469
- label: "Follow-up 3 Sent"
9655
+
9656
+ // ../core/src/organization-model/defaults.ts
9657
+ var DEFAULT_ORGANIZATION_MODEL_KNOWLEDGE = {};
9658
+ var DEFAULT_ORGANIZATION_MODEL_ENTITIES2 = DEFAULT_ORGANIZATION_MODEL_ENTITIES;
9659
+ var DEFAULT_ORGANIZATION_MODEL_NAVIGATION = {
9660
+ sidebar: {
9661
+ primary: {
9662
+ dashboard: {
9663
+ type: "surface",
9664
+ label: "Dashboard",
9665
+ path: "/",
9666
+ surfaceType: "dashboard",
9667
+ icon: "dashboard",
9668
+ order: 10,
9669
+ targets: { systems: ["dashboard"] }
9670
+ },
9671
+ business: {
9672
+ type: "group",
9673
+ label: "Business",
9674
+ icon: "business",
9675
+ order: 20,
9676
+ children: {
9677
+ sales: {
9678
+ type: "surface",
9679
+ label: "Sales",
9680
+ path: "/sales",
9681
+ surfaceType: "page",
9682
+ icon: "sales",
9683
+ order: 10,
9684
+ targets: { systems: ["sales"] }
9685
+ },
9686
+ clients: {
9687
+ type: "surface",
9688
+ label: "Clients",
9689
+ path: "/clients",
9690
+ surfaceType: "list",
9691
+ icon: "projects",
9692
+ order: 20,
9693
+ targets: { systems: ["clients"] }
9694
+ },
9695
+ projects: {
9696
+ type: "surface",
9697
+ label: "Projects",
9698
+ path: "/projects",
9699
+ surfaceType: "page",
9700
+ icon: "projects",
9701
+ order: 30,
9702
+ targets: { systems: ["projects"] }
9703
+ }
9704
+ }
9705
+ },
9706
+ operations: {
9707
+ type: "group",
9708
+ label: "Operations",
9709
+ icon: "operations",
9710
+ order: 30,
9711
+ children: {
9712
+ "operations-overview": {
9713
+ type: "surface",
9714
+ label: "Overview",
9715
+ path: "/operations",
9716
+ surfaceType: "page",
9717
+ order: 10,
9718
+ targets: { systems: ["operations.overview"] }
9719
+ },
9720
+ "operations-systems": {
9721
+ type: "surface",
9722
+ label: "Systems",
9723
+ path: "/operations/systems",
9724
+ surfaceType: "page",
9725
+ order: 20,
9726
+ targets: { systems: ["operations"] }
9727
+ },
9728
+ "operations-resources": {
9729
+ type: "surface",
9730
+ label: "Resources",
9731
+ path: "/operations/resources",
9732
+ surfaceType: "list",
9733
+ order: 30,
9734
+ targets: { systems: ["operations.resources"] }
9735
+ },
9736
+ "operations-command-queue": {
9737
+ type: "surface",
9738
+ label: "Command Queue",
9739
+ path: "/operations/command-queue",
9740
+ surfaceType: "list",
9741
+ order: 40,
9742
+ targets: { systems: ["operations.command-queue"] }
9743
+ },
9744
+ "operations-task-scheduler": {
9745
+ type: "surface",
9746
+ label: "Task Scheduler",
9747
+ path: "/operations/task-scheduler",
9748
+ surfaceType: "list",
9749
+ order: 50,
9750
+ targets: { systems: ["operations.task-scheduler"] }
9751
+ }
9752
+ }
9753
+ },
9754
+ monitoring: {
9755
+ type: "group",
9756
+ label: "Monitoring",
9757
+ icon: "monitoring",
9758
+ order: 40,
9759
+ children: {
9760
+ "monitoring-overview": {
9761
+ type: "surface",
9762
+ label: "Overview",
9763
+ path: "/monitoring",
9764
+ surfaceType: "page",
9765
+ order: 10,
9766
+ targets: { systems: ["monitoring"] }
9767
+ },
9768
+ "monitoring-calendar": {
9769
+ type: "surface",
9770
+ label: "Calendar",
9771
+ path: "/monitoring/calendar",
9772
+ surfaceType: "page",
9773
+ order: 20,
9774
+ targets: { systems: ["monitoring.calendar"] }
9775
+ },
9776
+ "monitoring-activity-log": {
9777
+ type: "surface",
9778
+ label: "Activity Log",
9779
+ path: "/monitoring/activity-log",
9780
+ surfaceType: "list",
9781
+ order: 30,
9782
+ targets: { systems: ["monitoring.activity-log"] }
9783
+ },
9784
+ "monitoring-execution-logs": {
9785
+ type: "surface",
9786
+ label: "Execution Logs",
9787
+ path: "/monitoring/execution-logs",
9788
+ surfaceType: "list",
9789
+ order: 40,
9790
+ targets: { systems: ["monitoring.execution-logs"] }
9791
+ },
9792
+ "monitoring-execution-health": {
9793
+ type: "surface",
9794
+ label: "Execution Health",
9795
+ path: "/monitoring/execution-health",
9796
+ surfaceType: "dashboard",
9797
+ order: 50,
9798
+ targets: { systems: ["monitoring.execution-health"] }
9799
+ },
9800
+ "monitoring-notifications": {
9801
+ type: "surface",
9802
+ label: "Notifications",
9803
+ path: "/monitoring/notifications",
9804
+ surfaceType: "list",
9805
+ order: 60,
9806
+ targets: { systems: ["monitoring.notifications"] }
9807
+ },
9808
+ "monitoring-requests": {
9809
+ type: "surface",
9810
+ label: "Requests",
9811
+ path: "/monitoring/requests",
9812
+ surfaceType: "list",
9813
+ order: 70,
9814
+ targets: { systems: ["monitoring.submitted-requests"] }
9815
+ }
9816
+ }
9817
+ },
9818
+ knowledge: {
9819
+ type: "surface",
9820
+ label: "Knowledge Base",
9821
+ path: "/knowledge",
9822
+ surfaceType: "page",
9823
+ icon: "knowledge",
9824
+ order: 50
9825
+ }
9826
+ },
9827
+ bottom: {
9828
+ settings: {
9829
+ type: "group",
9830
+ label: "Settings",
9831
+ icon: "settings",
9832
+ order: 10,
9833
+ children: {
9834
+ "settings-account": {
9835
+ type: "surface",
9836
+ label: "Account",
9837
+ path: "/settings/account",
9838
+ surfaceType: "settings",
9839
+ order: 10,
9840
+ targets: { systems: ["settings.account"] }
9841
+ },
9842
+ "settings-appearance": {
9843
+ type: "surface",
9844
+ label: "Appearance",
9845
+ path: "/settings/appearance",
9846
+ surfaceType: "settings",
9847
+ order: 20,
9848
+ targets: { systems: ["settings.appearance"] }
9849
+ },
9850
+ "settings-roles": {
9851
+ type: "surface",
9852
+ label: "My Roles",
9853
+ path: "/settings/roles",
9854
+ surfaceType: "settings",
9855
+ order: 30,
9856
+ targets: { systems: ["settings.roles"] }
9857
+ },
9858
+ "settings-organization": {
9859
+ type: "surface",
9860
+ label: "Organization",
9861
+ path: "/settings/organization",
9862
+ surfaceType: "settings",
9863
+ order: 40,
9864
+ targets: { systems: ["settings.organization"] }
9865
+ },
9866
+ "settings-credentials": {
9867
+ type: "surface",
9868
+ label: "Credentials",
9869
+ path: "/settings/credentials",
9870
+ surfaceType: "settings",
9871
+ order: 50,
9872
+ targets: { systems: ["settings.credentials"] }
9873
+ },
9874
+ "settings-api-keys": {
9875
+ type: "surface",
9876
+ label: "API Keys",
9877
+ path: "/settings/api-keys",
9878
+ surfaceType: "settings",
9879
+ order: 60,
9880
+ targets: { systems: ["settings.api-keys"] }
9881
+ },
9882
+ "settings-webhooks": {
9883
+ type: "surface",
9884
+ label: "Webhooks",
9885
+ path: "/settings/webhooks",
9886
+ surfaceType: "settings",
9887
+ order: 70,
9888
+ targets: { systems: ["settings.webhooks"] }
9889
+ },
9890
+ "settings-deployments": {
9891
+ type: "surface",
9892
+ label: "Deployments",
9893
+ path: "/settings/deployments",
9894
+ surfaceType: "settings",
9895
+ order: 80,
9896
+ targets: { systems: ["settings.deployments"] }
9897
+ }
9898
+ }
9899
+ },
9900
+ admin: {
9901
+ type: "group",
9902
+ label: "Admin",
9903
+ icon: "admin",
9904
+ order: 20,
9905
+ children: {
9906
+ "admin-dashboard": {
9907
+ type: "surface",
9908
+ label: "Dashboard",
9909
+ path: "/admin/dashboard",
9910
+ surfaceType: "dashboard",
9911
+ order: 10,
9912
+ targets: { systems: ["admin"] },
9913
+ requiresAdmin: true
9914
+ },
9915
+ "admin-system-health": {
9916
+ type: "surface",
9917
+ label: "System Health",
9918
+ path: "/admin/system-health",
9919
+ surfaceType: "dashboard",
9920
+ order: 20,
9921
+ targets: { systems: ["admin.system-health"] },
9922
+ requiresAdmin: true
9923
+ },
9924
+ "admin-organizations": {
9925
+ type: "surface",
9926
+ label: "Organizations",
9927
+ path: "/admin/organizations",
9928
+ surfaceType: "list",
9929
+ order: 30,
9930
+ targets: { systems: ["admin.organizations"] },
9931
+ requiresAdmin: true
9932
+ },
9933
+ "admin-users": {
9934
+ type: "surface",
9935
+ label: "Users",
9936
+ path: "/admin/users",
9937
+ surfaceType: "list",
9938
+ order: 40,
9939
+ targets: { systems: ["admin.users"] },
9940
+ requiresAdmin: true
9941
+ },
9942
+ "admin-design-showcase": {
9943
+ type: "surface",
9944
+ label: "Design Showcase",
9945
+ path: "/admin/design-showcase",
9946
+ surfaceType: "page",
9947
+ order: 50,
9948
+ targets: { systems: ["admin.design-showcase"] },
9949
+ requiresAdmin: true
9950
+ },
9951
+ "admin-debug": {
9952
+ type: "surface",
9953
+ label: "Debug",
9954
+ path: "/admin/debug",
9955
+ surfaceType: "page",
9956
+ order: 60,
9957
+ targets: { systems: ["admin.debug"] },
9958
+ requiresAdmin: true
9959
+ }
9960
+ }
9961
+ }
9962
+ }
9963
+ }
7470
9964
  };
7471
- var CRM_PIPELINE_DEFINITION = {
7472
- pipelineKey: "crm",
7473
- stages: [
7474
- {
7475
- stageKey: "interested",
7476
- label: "Interested",
9965
+ var DEFAULT_ORGANIZATION_MODEL = {
9966
+ version: 1,
9967
+ domainMetadata: DEFAULT_ORGANIZATION_MODEL_DOMAIN_METADATA,
9968
+ branding: DEFAULT_ORGANIZATION_MODEL_BRANDING,
9969
+ navigation: DEFAULT_ORGANIZATION_MODEL_NAVIGATION,
9970
+ identity: DEFAULT_ORGANIZATION_MODEL_IDENTITY,
9971
+ customers: DEFAULT_ORGANIZATION_MODEL_CUSTOMERS,
9972
+ offerings: DEFAULT_ORGANIZATION_MODEL_OFFERINGS,
9973
+ roles: DEFAULT_ORGANIZATION_MODEL_ROLES,
9974
+ goals: DEFAULT_ORGANIZATION_MODEL_GOALS,
9975
+ systems: {
9976
+ dashboard: {
9977
+ id: "dashboard",
9978
+ order: 10,
9979
+ label: "Dashboard",
9980
+ enabled: true,
9981
+ lifecycle: "active",
9982
+ path: "/",
9983
+ icon: "dashboard"
9984
+ },
9985
+ platform: {
9986
+ id: "platform",
9987
+ order: 30,
9988
+ label: "Platform",
9989
+ description: "Elevasis platform architecture, capabilities, and implementation patterns",
9990
+ enabled: true,
9991
+ lifecycle: "active",
9992
+ color: "cyan",
9993
+ icon: "platform"
9994
+ },
9995
+ finance: {
9996
+ id: "finance",
9997
+ order: 40,
9998
+ label: "Finance",
9999
+ description: "Finance operations, accounting, billing, reconciliation, and tax prep",
10000
+ enabled: true,
10001
+ lifecycle: "active",
10002
+ color: "green",
10003
+ icon: "finance"
10004
+ },
10005
+ sales: {
10006
+ id: "sales",
10007
+ order: 60,
10008
+ label: "Sales",
10009
+ description: "Revenue workflows and customer acquisition",
10010
+ enabled: true,
10011
+ lifecycle: "active",
7477
10012
  color: "blue",
7478
- states: [
7479
- CRM_DISCOVERY_REPLIED_STATE,
7480
- CRM_DISCOVERY_LINK_SENT_STATE,
7481
- CRM_DISCOVERY_NUDGING_STATE,
7482
- CRM_DISCOVERY_BOOKING_CANCELLED_STATE,
7483
- CRM_REPLY_SENT_STATE,
7484
- CRM_FOLLOWUP_1_SENT_STATE,
7485
- CRM_FOLLOWUP_2_SENT_STATE,
7486
- CRM_FOLLOWUP_3_SENT_STATE
7487
- ]
10013
+ icon: "sales",
10014
+ path: "/sales"
7488
10015
  },
7489
- { stageKey: "proposal", label: "Proposal", color: "yellow", states: [] },
7490
- { stageKey: "closing", label: "Closing", color: "orange", states: [] },
7491
- { stageKey: "closed_won", label: "Closed Won", color: "green", states: [] },
7492
- { stageKey: "closed_lost", label: "Closed Lost", color: "red", states: [] },
7493
- { stageKey: "nurturing", label: "Nurturing", color: "grape", states: [] }
7494
- ]
10016
+ "sales.crm": {
10017
+ id: "sales.crm",
10018
+ order: 70,
10019
+ label: "CRM",
10020
+ description: "Relationship pipeline and deal management",
10021
+ enabled: true,
10022
+ lifecycle: "active",
10023
+ actions: Object.values(CRM_ACTION_ENTRIES).map((action) => ({
10024
+ actionId: action.id,
10025
+ intent: "exposes"
10026
+ })),
10027
+ color: "blue",
10028
+ icon: "crm",
10029
+ path: "/crm"
10030
+ },
10031
+ "sales.lead-gen": {
10032
+ id: "sales.lead-gen",
10033
+ order: 80,
10034
+ label: "Lead Gen",
10035
+ description: "Prospecting, qualification, and outreach preparation",
10036
+ enabled: true,
10037
+ lifecycle: "active",
10038
+ actions: Object.values(LEAD_GEN_ACTION_ENTRIES).map((action) => ({
10039
+ actionId: action.id,
10040
+ intent: "exposes"
10041
+ })),
10042
+ color: "cyan",
10043
+ icon: "lead-gen",
10044
+ path: "/lead-gen"
10045
+ },
10046
+ projects: {
10047
+ id: "projects",
10048
+ order: 90,
10049
+ label: "Projects",
10050
+ description: "Projects, milestones, and client work execution",
10051
+ enabled: true,
10052
+ lifecycle: "active",
10053
+ color: "orange",
10054
+ icon: "projects",
10055
+ path: "/projects"
10056
+ },
10057
+ clients: {
10058
+ id: "clients",
10059
+ order: 100,
10060
+ label: "Clients",
10061
+ description: "Client relationships, accounts, and business context",
10062
+ enabled: true,
10063
+ lifecycle: "active",
10064
+ color: "orange",
10065
+ icon: "projects",
10066
+ path: "/clients"
10067
+ },
10068
+ operations: {
10069
+ id: "operations",
10070
+ order: 110,
10071
+ label: "Operations",
10072
+ description: "Operational resources, topology, and orchestration visibility",
10073
+ enabled: true,
10074
+ lifecycle: "active",
10075
+ color: "violet",
10076
+ icon: "operations"
10077
+ },
10078
+ "knowledge.command-view": {
10079
+ id: "knowledge.command-view",
10080
+ order: 120,
10081
+ label: "Command View",
10082
+ enabled: true,
10083
+ lifecycle: "active",
10084
+ path: "/knowledge/command-view",
10085
+ devOnly: true
10086
+ },
10087
+ "operations.overview": {
10088
+ id: "operations.overview",
10089
+ order: 130,
10090
+ label: "Overview",
10091
+ enabled: true,
10092
+ lifecycle: "active",
10093
+ path: "/operations"
10094
+ },
10095
+ "operations.resources": {
10096
+ id: "operations.resources",
10097
+ order: 140,
10098
+ label: "Resources",
10099
+ enabled: true,
10100
+ lifecycle: "active",
10101
+ path: "/operations/resources"
10102
+ },
10103
+ "operations.command-queue": {
10104
+ id: "operations.command-queue",
10105
+ order: 150,
10106
+ label: "Command Queue",
10107
+ enabled: true,
10108
+ lifecycle: "active",
10109
+ path: "/operations/command-queue"
10110
+ },
10111
+ "operations.sessions": {
10112
+ id: "operations.sessions",
10113
+ order: 160,
10114
+ label: "Sessions",
10115
+ enabled: false,
10116
+ lifecycle: "deprecated",
10117
+ path: "/operations/sessions"
10118
+ },
10119
+ "operations.task-scheduler": {
10120
+ id: "operations.task-scheduler",
10121
+ order: 170,
10122
+ label: "Task Scheduler",
10123
+ enabled: true,
10124
+ lifecycle: "active",
10125
+ path: "/operations/task-scheduler"
10126
+ },
10127
+ monitoring: {
10128
+ id: "monitoring",
10129
+ order: 180,
10130
+ label: "Monitoring",
10131
+ enabled: true,
10132
+ lifecycle: "active"
10133
+ },
10134
+ "monitoring.calendar": {
10135
+ id: "monitoring.calendar",
10136
+ order: 190,
10137
+ label: "Calendar",
10138
+ description: "Google Calendar events and agenda views",
10139
+ enabled: true,
10140
+ lifecycle: "active",
10141
+ path: "/monitoring/calendar",
10142
+ icon: "calendar"
10143
+ },
10144
+ "monitoring.activity-log": {
10145
+ id: "monitoring.activity-log",
10146
+ order: 200,
10147
+ label: "Activity Log",
10148
+ enabled: true,
10149
+ lifecycle: "active",
10150
+ path: "/monitoring/activity-log"
10151
+ },
10152
+ "monitoring.execution-logs": {
10153
+ id: "monitoring.execution-logs",
10154
+ order: 210,
10155
+ label: "Execution Logs",
10156
+ enabled: true,
10157
+ lifecycle: "active",
10158
+ path: "/monitoring/execution-logs"
10159
+ },
10160
+ "monitoring.execution-health": {
10161
+ id: "monitoring.execution-health",
10162
+ order: 220,
10163
+ label: "Execution Health",
10164
+ enabled: true,
10165
+ lifecycle: "active",
10166
+ path: "/monitoring/execution-health"
10167
+ },
10168
+ "monitoring.cost-analytics": {
10169
+ id: "monitoring.cost-analytics",
10170
+ order: 230,
10171
+ label: "Cost Analytics",
10172
+ enabled: false,
10173
+ lifecycle: "deprecated",
10174
+ path: "/monitoring/cost-analytics"
10175
+ },
10176
+ "monitoring.notifications": {
10177
+ id: "monitoring.notifications",
10178
+ order: 240,
10179
+ label: "Notifications",
10180
+ enabled: true,
10181
+ lifecycle: "active",
10182
+ path: "/monitoring/notifications"
10183
+ },
10184
+ "monitoring.submitted-requests": {
10185
+ id: "monitoring.submitted-requests",
10186
+ order: 250,
10187
+ label: "Submitted Requests",
10188
+ enabled: true,
10189
+ lifecycle: "active",
10190
+ path: "/monitoring/requests"
10191
+ },
10192
+ settings: {
10193
+ id: "settings",
10194
+ order: 260,
10195
+ label: "Settings",
10196
+ enabled: true,
10197
+ lifecycle: "active",
10198
+ icon: "settings"
10199
+ },
10200
+ "settings.account": {
10201
+ id: "settings.account",
10202
+ order: 270,
10203
+ label: "Account",
10204
+ enabled: true,
10205
+ lifecycle: "active",
10206
+ path: "/settings/account"
10207
+ },
10208
+ "settings.appearance": {
10209
+ id: "settings.appearance",
10210
+ order: 280,
10211
+ label: "Appearance",
10212
+ enabled: true,
10213
+ lifecycle: "active",
10214
+ path: "/settings/appearance"
10215
+ },
10216
+ "settings.roles": {
10217
+ id: "settings.roles",
10218
+ order: 290,
10219
+ label: "My Roles",
10220
+ enabled: true,
10221
+ lifecycle: "active",
10222
+ path: "/settings/roles"
10223
+ },
10224
+ "settings.organization": {
10225
+ id: "settings.organization",
10226
+ order: 300,
10227
+ label: "Organization",
10228
+ enabled: true,
10229
+ lifecycle: "active",
10230
+ path: "/settings/organization"
10231
+ },
10232
+ "settings.credentials": {
10233
+ id: "settings.credentials",
10234
+ order: 310,
10235
+ label: "Credentials",
10236
+ enabled: true,
10237
+ lifecycle: "active",
10238
+ path: "/settings/credentials"
10239
+ },
10240
+ "settings.api-keys": {
10241
+ id: "settings.api-keys",
10242
+ order: 320,
10243
+ label: "API Keys",
10244
+ enabled: true,
10245
+ lifecycle: "active",
10246
+ path: "/settings/api-keys"
10247
+ },
10248
+ "settings.webhooks": {
10249
+ id: "settings.webhooks",
10250
+ order: 330,
10251
+ label: "Webhooks",
10252
+ enabled: true,
10253
+ lifecycle: "active",
10254
+ path: "/settings/webhooks"
10255
+ },
10256
+ "settings.deployments": {
10257
+ id: "settings.deployments",
10258
+ order: 340,
10259
+ label: "Deployments",
10260
+ enabled: true,
10261
+ lifecycle: "active",
10262
+ path: "/settings/deployments"
10263
+ },
10264
+ admin: {
10265
+ id: "admin",
10266
+ order: 350,
10267
+ label: "Admin",
10268
+ enabled: true,
10269
+ lifecycle: "active",
10270
+ path: "/admin",
10271
+ icon: "admin",
10272
+ requiresAdmin: true
10273
+ },
10274
+ "admin.system-health": {
10275
+ id: "admin.system-health",
10276
+ order: 360,
10277
+ label: "System Health",
10278
+ enabled: true,
10279
+ lifecycle: "active",
10280
+ path: "/admin/system-health"
10281
+ },
10282
+ "admin.organizations": {
10283
+ id: "admin.organizations",
10284
+ order: 370,
10285
+ label: "Organizations",
10286
+ enabled: true,
10287
+ lifecycle: "active",
10288
+ path: "/admin/organizations"
10289
+ },
10290
+ "admin.users": {
10291
+ id: "admin.users",
10292
+ order: 380,
10293
+ label: "Users",
10294
+ enabled: true,
10295
+ lifecycle: "active",
10296
+ path: "/admin/users"
10297
+ },
10298
+ "admin.design-showcase": {
10299
+ id: "admin.design-showcase",
10300
+ order: 390,
10301
+ label: "Design Showcase",
10302
+ enabled: true,
10303
+ lifecycle: "active",
10304
+ path: "/admin/design-showcase"
10305
+ },
10306
+ "admin.debug": {
10307
+ id: "admin.debug",
10308
+ order: 400,
10309
+ label: "Debug",
10310
+ enabled: true,
10311
+ lifecycle: "active",
10312
+ path: "/admin/debug"
10313
+ },
10314
+ archive: {
10315
+ id: "archive",
10316
+ order: 410,
10317
+ label: "Archive",
10318
+ enabled: true,
10319
+ lifecycle: "active",
10320
+ path: "/archive",
10321
+ icon: "archive",
10322
+ devOnly: true
10323
+ },
10324
+ "archive.agent-chat": {
10325
+ id: "archive.agent-chat",
10326
+ order: 420,
10327
+ label: "Agent Chat",
10328
+ enabled: true,
10329
+ lifecycle: "active",
10330
+ path: "/archive/agent-chat"
10331
+ },
10332
+ "archive.execution-runner": {
10333
+ id: "archive.execution-runner",
10334
+ order: 430,
10335
+ label: "Execution Runner",
10336
+ enabled: true,
10337
+ lifecycle: "active",
10338
+ path: "/archive/execution-runner"
10339
+ },
10340
+ seo: {
10341
+ id: "seo",
10342
+ order: 440,
10343
+ label: "SEO",
10344
+ enabled: false,
10345
+ lifecycle: "deprecated",
10346
+ path: "/seo"
10347
+ },
10348
+ knowledge: {
10349
+ id: "knowledge",
10350
+ order: 450,
10351
+ label: "Knowledge",
10352
+ description: "Operational knowledge, playbooks, and strategy docs",
10353
+ enabled: true,
10354
+ lifecycle: "active",
10355
+ color: "teal",
10356
+ icon: "knowledge"
10357
+ },
10358
+ "knowledge.base": {
10359
+ id: "knowledge.base",
10360
+ order: 460,
10361
+ label: "Knowledge Base",
10362
+ enabled: true,
10363
+ lifecycle: "active",
10364
+ path: "/knowledge"
10365
+ }
10366
+ },
10367
+ ontology: DEFAULT_ONTOLOGY_SCOPE,
10368
+ resources: DEFAULT_ORGANIZATION_MODEL_RESOURCES,
10369
+ topology: DEFAULT_ORGANIZATION_MODEL_TOPOLOGY,
10370
+ actions: DEFAULT_ORGANIZATION_MODEL_ACTIONS,
10371
+ entities: DEFAULT_ORGANIZATION_MODEL_ENTITIES2,
10372
+ policies: DEFAULT_ORGANIZATION_MODEL_POLICIES,
10373
+ // Phase 4 (D1): statuses top-level field removed; bridge status mirrors may
10374
+ // still project from System.content, but primary authoring belongs in ontology.
10375
+ knowledge: DEFAULT_ORGANIZATION_MODEL_KNOWLEDGE
7495
10376
  };
7496
10377
 
10378
+ // ../core/src/business/acquisition/ontology-validation.ts
10379
+ var CRM_PIPELINE_CATALOG_ONTOLOGY_ID = formatOntologyId({
10380
+ scope: "sales.crm",
10381
+ kind: "catalog",
10382
+ localId: "crm.pipeline"
10383
+ });
10384
+ var LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID = formatOntologyId({
10385
+ scope: "sales.lead-gen",
10386
+ kind: "catalog",
10387
+ localId: "lead-gen.stage-catalog"
10388
+ });
10389
+ var CRM_DEAL_OBJECT_ONTOLOGY_ID = formatOntologyId({
10390
+ scope: "sales.crm",
10391
+ kind: "object",
10392
+ localId: "crm.deal"
10393
+ });
10394
+ function createCrmPipelineCatalog() {
10395
+ return {
10396
+ id: CRM_PIPELINE_CATALOG_ONTOLOGY_ID,
10397
+ label: CRM_PIPELINE_DEFINITION.label,
10398
+ ownerSystemId: "sales.crm",
10399
+ kind: "pipeline",
10400
+ appliesTo: CRM_DEAL_OBJECT_ONTOLOGY_ID,
10401
+ entries: Object.fromEntries(
10402
+ CRM_PIPELINE_DEFINITION.stages.map((stage, index2) => [
10403
+ stage.stageKey,
10404
+ {
10405
+ key: stage.stageKey,
10406
+ label: stage.label,
10407
+ order: (index2 + 1) * 10,
10408
+ ...stage.color !== void 0 ? { color: stage.color } : {},
10409
+ states: stage.states.map((state) => ({ ...state }))
10410
+ }
10411
+ ])
10412
+ ),
10413
+ legacyPipelineKey: CRM_PIPELINE_DEFINITION.pipelineKey,
10414
+ legacyEntityKey: CRM_PIPELINE_DEFINITION.entityKey
10415
+ };
10416
+ }
10417
+ function createLeadGenStageCatalog() {
10418
+ return {
10419
+ id: LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID,
10420
+ label: "Lead Gen Processing Stages",
10421
+ ownerSystemId: "sales.lead-gen",
10422
+ kind: "processing-stage-catalog",
10423
+ entries: Object.fromEntries(
10424
+ Object.entries(LEAD_GEN_STAGE_CATALOG).map(([key, entry]) => [
10425
+ key,
10426
+ {
10427
+ ...entry
10428
+ }
10429
+ ])
10430
+ ),
10431
+ legacyCatalogKey: "LEAD_GEN_STAGE_CATALOG"
10432
+ };
10433
+ }
10434
+ function isPlainRecord(value) {
10435
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
10436
+ }
10437
+ function mergeBridgeCatalogs(model) {
10438
+ const baseCatalogTypes = model.ontology?.catalogTypes ?? {};
10439
+ const bridgeCatalogTypes = {};
10440
+ if (baseCatalogTypes[CRM_PIPELINE_CATALOG_ONTOLOGY_ID] === void 0) {
10441
+ bridgeCatalogTypes[CRM_PIPELINE_CATALOG_ONTOLOGY_ID] = createCrmPipelineCatalog();
10442
+ }
10443
+ if (baseCatalogTypes[LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID] === void 0) {
10444
+ bridgeCatalogTypes[LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID] = createLeadGenStageCatalog();
10445
+ }
10446
+ if (Object.keys(bridgeCatalogTypes).length === 0) return model;
10447
+ return {
10448
+ ...model,
10449
+ ontology: {
10450
+ ...model.ontology ?? {},
10451
+ catalogTypes: {
10452
+ ...baseCatalogTypes,
10453
+ ...bridgeCatalogTypes
10454
+ }
10455
+ }
10456
+ };
10457
+ }
10458
+ function compileBusinessOntologyValidationIndex(model = DEFAULT_ORGANIZATION_MODEL) {
10459
+ const compilation = compileOrganizationOntology(mergeBridgeCatalogs(model));
10460
+ if (compilation.diagnostics.length > 0) {
10461
+ const summary = compilation.diagnostics.map((diagnostic) => diagnostic.message).join("; ");
10462
+ throw new Error(`Business ontology validation index failed to compile: ${summary}`);
10463
+ }
10464
+ const crmPipelineCatalog = compilation.ontology.catalogTypes[CRM_PIPELINE_CATALOG_ONTOLOGY_ID];
10465
+ const leadGenStageCatalog = compilation.ontology.catalogTypes[LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID];
10466
+ if (crmPipelineCatalog === void 0 || leadGenStageCatalog === void 0) {
10467
+ throw new Error("Business ontology validation index is missing CRM or lead-gen catalog bridge records");
10468
+ }
10469
+ return {
10470
+ ontology: compilation.ontology,
10471
+ crmPipelineCatalog,
10472
+ leadGenStageCatalog,
10473
+ actionTypesByLegacyId: indexActionTypesByLegacyId(compilation.ontology.actionTypes)
10474
+ };
10475
+ }
10476
+ function indexActionTypesByLegacyId(actionTypes) {
10477
+ const byLegacyId = {};
10478
+ for (const actionType of Object.values(actionTypes)) {
10479
+ const legacyActionId = actionType["legacyActionId"];
10480
+ if (typeof legacyActionId === "string") {
10481
+ byLegacyId[legacyActionId] = actionType;
10482
+ }
10483
+ }
10484
+ return byLegacyId;
10485
+ }
10486
+ var BUSINESS_ONTOLOGY_VALIDATION_INDEX = compileBusinessOntologyValidationIndex();
10487
+ function getCatalogEntries(catalog) {
10488
+ return isPlainRecord(catalog.entries) ? catalog.entries : {};
10489
+ }
10490
+ function asCrmStageEntry(key, value) {
10491
+ const record = isPlainRecord(value) ? value : {};
10492
+ const label = typeof record.label === "string" ? record.label : key;
10493
+ const order = typeof record.order === "number" ? record.order : 0;
10494
+ const color = typeof record.color === "string" ? record.color : void 0;
10495
+ const rawStates = Array.isArray(record.states) ? record.states : [];
10496
+ const states = rawStates.flatMap((state) => {
10497
+ if (!isPlainRecord(state) || typeof state.stateKey !== "string") return [];
10498
+ return [
10499
+ {
10500
+ stateKey: state.stateKey,
10501
+ label: typeof state.label === "string" ? state.label : state.stateKey
10502
+ }
10503
+ ];
10504
+ });
10505
+ return {
10506
+ key,
10507
+ label,
10508
+ order,
10509
+ ...color !== void 0 ? { color } : {},
10510
+ states
10511
+ };
10512
+ }
10513
+ function asLeadGenStageEntry(key, value) {
10514
+ const record = isPlainRecord(value) ? value : {};
10515
+ const entity = record.entity === "contact" ? "contact" : "company";
10516
+ const additionalEntities = Array.isArray(record.additionalEntities) ? record.additionalEntities.filter(
10517
+ (item) => item === "company" || item === "contact"
10518
+ ) : void 0;
10519
+ const recordEntity = record.recordEntity === "company" || record.recordEntity === "contact" ? record.recordEntity : void 0;
10520
+ const recordStageKey = typeof record.recordStageKey === "string" ? record.recordStageKey : void 0;
10521
+ return {
10522
+ key: typeof record.key === "string" ? record.key : key,
10523
+ label: typeof record.label === "string" ? record.label : key,
10524
+ description: typeof record.description === "string" ? record.description : "",
10525
+ order: typeof record.order === "number" ? record.order : 0,
10526
+ entity,
10527
+ ...additionalEntities !== void 0 ? { additionalEntities } : {},
10528
+ ...recordEntity !== void 0 ? { recordEntity } : {},
10529
+ ...recordStageKey !== void 0 ? { recordStageKey } : {}
10530
+ };
10531
+ }
10532
+ var CRM_STAGE_KEYS_FROM_ONTOLOGY = Object.keys(
10533
+ getCatalogEntries(BUSINESS_ONTOLOGY_VALIDATION_INDEX.crmPipelineCatalog)
10534
+ );
10535
+ var CRM_STATE_KEYS_FROM_ONTOLOGY = Object.values(
10536
+ getCatalogEntries(BUSINESS_ONTOLOGY_VALIDATION_INDEX.crmPipelineCatalog)
10537
+ ).flatMap((entry, index2) => {
10538
+ const stageKey = CRM_STAGE_KEYS_FROM_ONTOLOGY[index2];
10539
+ if (stageKey === void 0) return [];
10540
+ return asCrmStageEntry(stageKey, entry).states.map((state) => state.stateKey);
10541
+ });
10542
+ Object.keys(
10543
+ getCatalogEntries(BUSINESS_ONTOLOGY_VALIDATION_INDEX.leadGenStageCatalog)
10544
+ );
10545
+ function getLeadGenStageCatalogFromOntology() {
10546
+ return Object.fromEntries(
10547
+ Object.entries(getCatalogEntries(BUSINESS_ONTOLOGY_VALIDATION_INDEX.leadGenStageCatalog)).map(([key, value]) => [
10548
+ key,
10549
+ asLeadGenStageEntry(key, value)
10550
+ ])
10551
+ );
10552
+ }
10553
+ function getLeadGenStageEntry(stageKey) {
10554
+ return getLeadGenStageCatalogFromOntology()[stageKey];
10555
+ }
10556
+ function isLeadGenStageKey(stageKey) {
10557
+ return getLeadGenStageEntry(stageKey) !== void 0;
10558
+ }
10559
+ function isLeadGenRecordStageValidForEntity(stageKey, entity) {
10560
+ const stage = getLeadGenStageEntry(stageKey);
10561
+ return stage !== void 0 && (stage.entity === entity || stage.additionalEntities?.includes(entity) === true || stage.recordEntity === entity);
10562
+ }
10563
+ function isLeadGenActionKey(actionKey) {
10564
+ return actionKey.startsWith("lead-gen.") && BUSINESS_ONTOLOGY_VALIDATION_INDEX.actionTypesByLegacyId[actionKey] !== void 0;
10565
+ }
10566
+
7497
10567
  // ../core/src/business/acquisition/api-schemas.ts
7498
10568
  var ProcessingStageStatusSchema = z.enum(["success", "no_result", "skipped", "error"]);
7499
- var LeadGenStageKeySchema = z.string().refine((value) => Object.prototype.hasOwnProperty.call(LEAD_GEN_STAGE_CATALOG, value), {
10569
+ var LeadGenStageKeySchema = z.string().refine((value) => isLeadGenStageKey(value), {
7500
10570
  message: "processing state key must match LEAD_GEN_STAGE_CATALOG"
7501
10571
  });
7502
- var LeadGenActionKeySchema = z.string().refine((value) => ACTION_REGISTRY.some((c) => c.id === value), {
10572
+ var LeadGenActionKeySchema = z.string().refine((value) => isLeadGenActionKey(value), {
7503
10573
  message: "actionKey must match ACTION_REGISTRY"
7504
10574
  });
7505
- var crmStageKeys = CRM_PIPELINE_DEFINITION.stages.map((stage) => stage.stageKey);
7506
- var crmStateKeys = CRM_PIPELINE_DEFINITION.stages.flatMap((stage) => stage.states.map((state) => state.stateKey));
10575
+ var crmStageKeys = CRM_STAGE_KEYS_FROM_ONTOLOGY;
10576
+ var crmStateKeys = CRM_STATE_KEYS_FROM_ONTOLOGY;
7507
10577
  var CrmStageKeySchema = z.enum(crmStageKeys);
7508
10578
  var CrmStateKeySchema = z.enum(crmStateKeys);
7509
10579
  var ProcessingStateEntrySchema = z.object({
@@ -7758,7 +10828,7 @@ var IcpRubricSchema = z.object({
7758
10828
  customRules: z.string().optional()
7759
10829
  });
7760
10830
  var PipelineStageSchema = z.object({
7761
- key: z.string().refine((value) => Object.prototype.hasOwnProperty.call(LEAD_GEN_STAGE_CATALOG, value), {
10831
+ key: z.string().refine((value) => isLeadGenStageKey(value), {
7762
10832
  message: "pipeline stage key must match LEAD_GEN_STAGE_CATALOG"
7763
10833
  }),
7764
10834
  label: z.string().optional(),
@@ -8230,9 +11300,7 @@ z.object({
8230
11300
  offset: z.coerce.number().int().min(0).default(0)
8231
11301
  }).strict().superRefine((query, ctx) => {
8232
11302
  if (!query.stage) return;
8233
- const stage = LEAD_GEN_STAGE_CATALOG[query.stage];
8234
- const validEntity = stage?.entity === query.entity || stage?.additionalEntities?.includes(query.entity) || stage?.recordEntity === query.entity;
8235
- if (!validEntity) {
11303
+ if (!isLeadGenRecordStageValidForEntity(query.stage, query.entity)) {
8236
11304
  ctx.addIssue({
8237
11305
  code: z.ZodIssueCode.custom,
8238
11306
  message: `stage "${query.stage}" is not valid for ${query.entity} records`,
@@ -8698,14 +11766,18 @@ createAdapter("execution", ["trigger", "triggerAsync"]);
8698
11766
  createAdapter("email", ["send"]);
8699
11767
 
8700
11768
  // ../core/src/organization-model/helpers.ts
11769
+ function childSystemsOf2(system) {
11770
+ return system.systems ?? system.subsystems ?? {};
11771
+ }
8701
11772
  function listAllSystems(model) {
8702
11773
  const results = [];
8703
11774
  function walk(map2, prefix) {
8704
11775
  for (const [localId, system] of Object.entries(map2)) {
8705
11776
  const fullPath = prefix ? `${prefix}.${localId}` : localId;
8706
11777
  results.push({ path: fullPath, system });
8707
- if (system.subsystems) {
8708
- walk(system.subsystems, fullPath);
11778
+ const childSystems = childSystemsOf2(system);
11779
+ if (Object.keys(childSystems).length > 0) {
11780
+ walk(childSystems, fullPath);
8709
11781
  }
8710
11782
  }
8711
11783
  }
@@ -8766,6 +11838,119 @@ function getRuntimeResources(resources) {
8766
11838
  }))
8767
11839
  ];
8768
11840
  }
11841
+ function hasOntologySources(organizationModel) {
11842
+ return organizationModel.ontology !== void 0 || organizationModel.entities !== void 0 || organizationModel.actions !== void 0 || Object.values(organizationModel.systems ?? {}).some(systemHasOntologySource);
11843
+ }
11844
+ function systemHasOntologySource(system) {
11845
+ if (system.ontology !== void 0 || system.content !== void 0 && Object.keys(system.content).length > 0) return true;
11846
+ return Object.values(system.systems ?? system.subsystems ?? {}).some(systemHasOntologySource);
11847
+ }
11848
+ function ontologyIndexForKind(index2, kind) {
11849
+ switch (kind) {
11850
+ case "object":
11851
+ return index2.objectTypes;
11852
+ case "link":
11853
+ return index2.linkTypes;
11854
+ case "action":
11855
+ return index2.actionTypes;
11856
+ case "catalog":
11857
+ return index2.catalogTypes;
11858
+ case "event":
11859
+ return index2.eventTypes;
11860
+ case "interface":
11861
+ return index2.interfaceTypes;
11862
+ case "value-type":
11863
+ return index2.valueTypes;
11864
+ case "property":
11865
+ return index2.sharedProperties;
11866
+ case "group":
11867
+ return index2.groups;
11868
+ case "surface":
11869
+ return index2.surfaces;
11870
+ }
11871
+ }
11872
+ function sameJson(left, right) {
11873
+ return JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
11874
+ }
11875
+ function addOntologyBindingIssues(issues, orgName, resource, ontologyIndex) {
11876
+ const binding = resource.ontology;
11877
+ if (binding === void 0) return;
11878
+ if ((resource.kind === "workflow" || resource.kind === "agent") && (binding.actions?.length ?? 0) === 0) {
11879
+ addGovernanceIssue(
11880
+ issues,
11881
+ "missing-ontology-actions",
11882
+ orgName,
11883
+ resource.id,
11884
+ `[${orgName}] Resource '${resource.id}' declares ontology bindings but no ontology actions.`
11885
+ );
11886
+ }
11887
+ if (binding.primaryAction !== void 0 && !binding.actions?.includes(binding.primaryAction)) {
11888
+ addGovernanceIssue(
11889
+ issues,
11890
+ "primary-action-mismatch",
11891
+ orgName,
11892
+ resource.id,
11893
+ `[${orgName}] Resource '${resource.id}' primaryAction '${binding.primaryAction}' must be included in ontology.actions.`
11894
+ );
11895
+ }
11896
+ if (ontologyIndex === void 0) return;
11897
+ const validateRefs = (bindingKey, expectedKind, refs) => {
11898
+ const values = refs === void 0 ? [] : Array.isArray(refs) ? refs : [refs];
11899
+ const index2 = ontologyIndexForKind(ontologyIndex, expectedKind);
11900
+ for (const ref of values) {
11901
+ if (index2[ref] !== void 0) continue;
11902
+ addGovernanceIssue(
11903
+ issues,
11904
+ "ontology-reference-missing",
11905
+ orgName,
11906
+ resource.id,
11907
+ `[${orgName}] Resource '${resource.id}' ontology.${bindingKey} references missing ${expectedKind} ontology record '${ref}'.`
11908
+ );
11909
+ }
11910
+ };
11911
+ validateRefs("actions", "action", binding.actions);
11912
+ validateRefs("primaryAction", "action", binding.primaryAction);
11913
+ validateRefs("reads", "object", binding.reads);
11914
+ validateRefs("writes", "object", binding.writes);
11915
+ validateRefs("usesCatalogs", "catalog", binding.usesCatalogs);
11916
+ validateRefs("emits", "event", binding.emits);
11917
+ }
11918
+ function addTopologyIssues(issues, orgName, deployment, organizationModel, systemsById, omResourcesById, ontologyIndex) {
11919
+ const relationships = organizationModel.topology?.relationships;
11920
+ if (relationships === void 0) return;
11921
+ const rolesById = new Set(Object.keys(organizationModel.roles ?? {}));
11922
+ const policiesById = new Set(Object.keys(organizationModel.policies ?? {}));
11923
+ const triggerIds = new Set(deployment.triggers?.map((trigger) => trigger.resourceId) ?? []);
11924
+ const humanCheckpointIds = new Set(deployment.humanCheckpoints?.map((checkpoint) => checkpoint.resourceId) ?? []);
11925
+ const externalResourceIds = new Set(deployment.externalResources?.map((external) => external.resourceId) ?? []);
11926
+ const topologyRefExists = (ref) => {
11927
+ if (ref.kind === "system") return systemsById.has(ref.id);
11928
+ if (ref.kind === "resource") return omResourcesById.has(ref.id);
11929
+ if (ref.kind === "policy") return policiesById.has(ref.id);
11930
+ if (ref.kind === "role") return rolesById.has(ref.id);
11931
+ if (ref.kind === "trigger") return triggerIds.has(ref.id);
11932
+ if (ref.kind === "humanCheckpoint") return humanCheckpointIds.has(ref.id);
11933
+ if (ref.kind === "externalResource") return externalResourceIds.has(ref.id);
11934
+ if (ref.kind === "ontology") {
11935
+ if (ontologyIndex === void 0) return true;
11936
+ return Object.values(ontologyIndex).some((records) => records[ref.id] !== void 0);
11937
+ }
11938
+ return false;
11939
+ };
11940
+ for (const [relationshipId, relationship] of Object.entries(relationships)) {
11941
+ ["from", "to"].forEach((side) => {
11942
+ const ref = relationship[side];
11943
+ if (topologyRefExists(ref)) return;
11944
+ addGovernanceIssue(
11945
+ issues,
11946
+ "topology-reference-missing",
11947
+ orgName,
11948
+ ref.id,
11949
+ `[${orgName}] Topology relationship '${relationshipId}' ${side} references missing ${ref.kind} '${ref.id}'.`
11950
+ );
11951
+ });
11952
+ }
11953
+ }
8769
11954
  function validateResourceGovernance(orgName, deployment, organizationModel = deployment.organizationModel, options = {}) {
8770
11955
  const mode = getResourceValidatorMode(options.mode);
8771
11956
  const omResourcesMap = organizationModel?.resources;
@@ -8781,6 +11966,17 @@ function validateResourceGovernance(orgName, deployment, organizationModel = dep
8781
11966
  const omResourcesById = new Map(activeOmResources.map((resource) => [resource.id, resource]));
8782
11967
  const runtimeResources = getRuntimeResources(deployment);
8783
11968
  const runtimeResourcesById = new Map(runtimeResources.map((resource) => [resource.resourceId, resource]));
11969
+ const ontologyCompilation = hasOntologySources(organizationModel) ? compileOrganizationOntology(organizationModel) : void 0;
11970
+ const ontologyIndex = ontologyCompilation?.ontology;
11971
+ for (const diagnostic of ontologyCompilation?.diagnostics ?? []) {
11972
+ addGovernanceIssue(
11973
+ issues,
11974
+ "ontology-reference-missing",
11975
+ orgName,
11976
+ diagnostic.id,
11977
+ `[${orgName}] ${diagnostic.message}`
11978
+ );
11979
+ }
8784
11980
  for (const resource of activeOmResources) {
8785
11981
  if (!systemsById.has(resource.systemPath)) {
8786
11982
  addGovernanceIssue(
@@ -8820,6 +12016,16 @@ function validateResourceGovernance(orgName, deployment, organizationModel = dep
8820
12016
  `[${orgName}] Resource '${resource.id}' system mismatch: code descriptor has '${runtimeResource.descriptor.systemPath}', OM has '${resource.systemPath}'.`
8821
12017
  );
8822
12018
  }
12019
+ if (runtimeResource.descriptor && !sameJson(runtimeResource.descriptor.ontology, resource.ontology)) {
12020
+ addGovernanceIssue(
12021
+ issues,
12022
+ "descriptor-mismatch",
12023
+ orgName,
12024
+ resource.id,
12025
+ `[${orgName}] Resource '${resource.id}' ontology descriptor mismatch between code and OM.`
12026
+ );
12027
+ }
12028
+ addOntologyBindingIssues(issues, orgName, resource, ontologyIndex);
8823
12029
  }
8824
12030
  for (const runtimeResource of runtimeResources) {
8825
12031
  const omResource = omResourcesById.get(runtimeResource.resourceId);
@@ -8861,6 +12067,7 @@ function validateResourceGovernance(orgName, deployment, organizationModel = dep
8861
12067
  );
8862
12068
  }
8863
12069
  }
12070
+ addTopologyIssues(issues, orgName, deployment, organizationModel, systemsById, omResourcesById, ontologyIndex);
8864
12071
  emitGovernanceIssues(issues, mode, options.onWarning);
8865
12072
  return {
8866
12073
  valid: issues.length === 0,