@elevasis/core 0.23.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (241) hide show
  1. package/dist/index.d.ts +1326 -552
  2. package/dist/index.js +869 -154
  3. package/dist/knowledge/index.d.ts +487 -209
  4. package/dist/knowledge/index.js +104 -1
  5. package/dist/organization-model/index.d.ts +1326 -552
  6. package/dist/organization-model/index.js +869 -154
  7. package/dist/test-utils/index.d.ts +357 -72
  8. package/dist/test-utils/index.js +795 -142
  9. package/package.json +5 -5
  10. package/src/README.md +14 -14
  11. package/src/__tests__/publish.test.ts +24 -24
  12. package/src/__tests__/template-core-compatibility.test.ts +9 -12
  13. package/src/_gen/__tests__/__snapshots__/contracts.md.snap +2102 -2096
  14. package/src/_gen/__tests__/scaffold-contracts.test.ts +30 -30
  15. package/src/auth/multi-tenancy/credentials/__tests__/encryption.test.ts +217 -217
  16. package/src/auth/multi-tenancy/credentials/server/encryption.ts +69 -69
  17. package/src/auth/multi-tenancy/credentials/server/kek-loader.ts +37 -37
  18. package/src/auth/multi-tenancy/index.ts +26 -26
  19. package/src/auth/multi-tenancy/invitations/api-schemas.ts +104 -104
  20. package/src/auth/multi-tenancy/memberships/api-schemas.ts +143 -143
  21. package/src/auth/multi-tenancy/memberships/index.ts +26 -26
  22. package/src/auth/multi-tenancy/memberships/membership.ts +130 -130
  23. package/src/auth/multi-tenancy/organizations/__tests__/api-schemas.test.ts +194 -194
  24. package/src/auth/multi-tenancy/organizations/api-schemas.ts +136 -136
  25. package/src/auth/multi-tenancy/permissions.test.ts +42 -42
  26. package/src/auth/multi-tenancy/permissions.ts +123 -123
  27. package/src/auth/multi-tenancy/role-management/api-schemas.ts +78 -78
  28. package/src/auth/multi-tenancy/role-management/index.ts +16 -16
  29. package/src/auth/multi-tenancy/theme-presets.ts +45 -45
  30. package/src/auth/multi-tenancy/types.ts +57 -57
  31. package/src/auth/multi-tenancy/users/api-schemas.ts +165 -165
  32. package/src/business/README.md +2 -2
  33. package/src/business/acquisition/activity-events.test.ts +250 -250
  34. package/src/business/acquisition/activity-events.ts +93 -93
  35. package/src/business/acquisition/api-schemas.test.ts +1883 -1843
  36. package/src/business/acquisition/api-schemas.ts +1492 -1497
  37. package/src/business/acquisition/build-templates.test.ts +240 -240
  38. package/src/business/acquisition/build-templates.ts +98 -98
  39. package/src/business/acquisition/crm-next-action.test.ts +262 -262
  40. package/src/business/acquisition/crm-next-action.ts +220 -220
  41. package/src/business/acquisition/crm-priority.test.ts +216 -216
  42. package/src/business/acquisition/crm-priority.ts +349 -349
  43. package/src/business/acquisition/crm-state-actions.test.ts +153 -153
  44. package/src/business/acquisition/deal-ownership.test.ts +351 -351
  45. package/src/business/acquisition/deal-ownership.ts +120 -120
  46. package/src/business/acquisition/derive-actions.test.ts +129 -104
  47. package/src/business/acquisition/derive-actions.ts +74 -84
  48. package/src/business/acquisition/index.ts +171 -170
  49. package/src/business/acquisition/ontology-validation.ts +309 -0
  50. package/src/business/acquisition/stateful.ts +30 -30
  51. package/src/business/acquisition/types.ts +396 -396
  52. package/src/business/clients/api-schemas.test.ts +115 -115
  53. package/src/business/clients/api-schemas.ts +158 -158
  54. package/src/business/clients/index.ts +1 -1
  55. package/src/business/crm/api-schemas.ts +40 -40
  56. package/src/business/crm/index.ts +1 -1
  57. package/src/business/deals/api-schemas.ts +87 -87
  58. package/src/business/deals/index.ts +1 -1
  59. package/src/business/index.ts +5 -5
  60. package/src/business/projects/types.ts +144 -144
  61. package/src/commands/queue/types/task.ts +15 -15
  62. package/src/execution/core/runner-types.ts +61 -61
  63. package/src/execution/core/sse-executions.ts +7 -7
  64. package/src/execution/engine/__tests__/fixtures/test-agents.ts +10 -10
  65. package/src/execution/engine/agent/core/__tests__/agent.test.ts +16 -16
  66. package/src/execution/engine/agent/core/__tests__/error-passthrough.test.ts +4 -4
  67. package/src/execution/engine/agent/core/types.ts +25 -25
  68. package/src/execution/engine/agent/index.ts +6 -6
  69. package/src/execution/engine/agent/reasoning/__tests__/request-builder.test.ts +24 -24
  70. package/src/execution/engine/index.ts +443 -443
  71. package/src/execution/engine/tools/integration/server/adapters/apify/__tests__/apify-run-actor.integration.test.ts +298 -298
  72. package/src/execution/engine/tools/integration/server/adapters/apify/apify-adapter.test.ts +55 -55
  73. package/src/execution/engine/tools/integration/server/adapters/apify/apify-adapter.ts +107 -107
  74. package/src/execution/engine/tools/integration/server/adapters/apollo/apollo-adapter.test.ts +48 -48
  75. package/src/execution/engine/tools/integration/server/adapters/apollo/apollo-adapter.ts +99 -99
  76. package/src/execution/engine/tools/integration/server/adapters/apollo/index.ts +1 -1
  77. package/src/execution/engine/tools/integration/server/adapters/attio/__tests__/attio-crud.integration.test.ts +363 -363
  78. package/src/execution/engine/tools/integration/server/adapters/attio/fetch/get-record/index.test.ts +162 -162
  79. package/src/execution/engine/tools/integration/server/adapters/attio/fetch/list-records/index.test.ts +316 -316
  80. package/src/execution/engine/tools/integration/server/adapters/clickup/clickup-adapter.test.ts +18 -18
  81. package/src/execution/engine/tools/integration/server/adapters/clickup/clickup-adapter.ts +194 -194
  82. package/src/execution/engine/tools/integration/server/adapters/clickup/index.ts +7 -7
  83. package/src/execution/engine/tools/integration/server/adapters/gmail/gmail-adapter.ts +204 -204
  84. package/src/execution/engine/tools/integration/server/adapters/gmail/gmail-tools.ts +105 -105
  85. package/src/execution/engine/tools/integration/server/adapters/google-calendar/google-calendar-adapter.ts +428 -428
  86. package/src/execution/engine/tools/integration/server/adapters/google-calendar/index.ts +2 -2
  87. package/src/execution/engine/tools/integration/server/adapters/google-sheets/__tests__/google-sheets.integration.test.ts +261 -261
  88. package/src/execution/engine/tools/integration/server/adapters/instantly/instantly-tools.ts +1474 -1474
  89. package/src/execution/engine/tools/integration/server/adapters/millionverifier/millionverifier-tools.ts +103 -103
  90. package/src/execution/engine/tools/integration/server/adapters/resend/fetch/send-email/index.test.ts +88 -88
  91. package/src/execution/engine/tools/integration/server/adapters/resend/fetch/send-email/index.ts +141 -141
  92. package/src/execution/engine/tools/integration/server/adapters/resend/fetch/utils/types.ts +76 -76
  93. package/src/execution/engine/tools/integration/server/adapters/signature-api/signature-api-tools.ts +182 -182
  94. package/src/execution/engine/tools/integration/server/adapters/stripe/stripe-tools.ts +310 -310
  95. package/src/execution/engine/tools/integration/service.test.ts +239 -239
  96. package/src/execution/engine/tools/integration/service.ts +172 -172
  97. package/src/execution/engine/tools/integration/tool.ts +255 -255
  98. package/src/execution/engine/tools/lead-service-types.ts +1005 -1005
  99. package/src/execution/engine/tools/messages.ts +43 -43
  100. package/src/execution/engine/tools/platform/acquisition/company-tools.ts +7 -7
  101. package/src/execution/engine/tools/platform/acquisition/contact-tools.ts +6 -6
  102. package/src/execution/engine/tools/platform/acquisition/list-tools.ts +6 -6
  103. package/src/execution/engine/tools/platform/acquisition/types.ts +280 -280
  104. package/src/execution/engine/tools/platform/email/types.ts +97 -97
  105. package/src/execution/engine/tools/registry.ts +704 -704
  106. package/src/execution/engine/tools/tool-maps.ts +831 -831
  107. package/src/execution/engine/tools/types.ts +234 -234
  108. package/src/execution/engine/workflow/types.ts +202 -202
  109. package/src/execution/external/__tests__/api-schemas.test.ts +127 -127
  110. package/src/execution/external/api-schemas.ts +40 -40
  111. package/src/execution/external/index.ts +1 -1
  112. package/src/index.ts +18 -18
  113. package/src/integrations/credentials/__tests__/api-schemas.test.ts +420 -420
  114. package/src/integrations/credentials/api-schemas.ts +146 -146
  115. package/src/integrations/credentials/schemas.ts +200 -200
  116. package/src/integrations/oauth/__tests__/provider-registry.test.ts +7 -7
  117. package/src/integrations/oauth/provider-registry.ts +74 -74
  118. package/src/integrations/oauth/server/credentials.ts +43 -43
  119. package/src/integrations/webhook-endpoints/__tests__/api-schemas.test.ts +327 -327
  120. package/src/integrations/webhook-endpoints/api-schemas.ts +103 -103
  121. package/src/integrations/webhook-endpoints/types.ts +58 -58
  122. package/src/knowledge/README.md +32 -32
  123. package/src/knowledge/__tests__/queries.test.ts +626 -535
  124. package/src/knowledge/format.ts +99 -99
  125. package/src/knowledge/index.ts +5 -5
  126. package/src/knowledge/published.ts +5 -5
  127. package/src/knowledge/queries.ts +269 -218
  128. package/src/operations/activities/api-schemas.ts +80 -80
  129. package/src/operations/activities/types.ts +64 -64
  130. package/src/organization-model/README.md +149 -149
  131. package/src/organization-model/__tests__/content-kinds-registry.test.ts +210 -210
  132. package/src/organization-model/__tests__/defaults.test.ts +168 -168
  133. package/src/organization-model/__tests__/domains/actions.test.ts +78 -56
  134. package/src/organization-model/__tests__/domains/customers.test.ts +299 -299
  135. package/src/organization-model/__tests__/domains/entities.test.ts +56 -56
  136. package/src/organization-model/__tests__/domains/goals.test.ts +493 -493
  137. package/src/organization-model/__tests__/domains/identity.test.ts +280 -280
  138. package/src/organization-model/__tests__/domains/navigation.test.ts +268 -268
  139. package/src/organization-model/__tests__/domains/offerings.test.ts +414 -414
  140. package/src/organization-model/__tests__/domains/policies.test.ts +323 -323
  141. package/src/organization-model/__tests__/domains/resource-mappings.test.ts +293 -293
  142. package/src/organization-model/__tests__/domains/resources.test.ts +382 -283
  143. package/src/organization-model/__tests__/domains/roles.test.ts +463 -463
  144. package/src/organization-model/__tests__/domains/statuses.test.ts +246 -246
  145. package/src/organization-model/__tests__/domains/systems.test.ts +209 -209
  146. package/src/organization-model/__tests__/flatten-additive-merge.test.ts +362 -361
  147. package/src/organization-model/__tests__/foundation.test.ts +77 -77
  148. package/src/organization-model/__tests__/get-resources-for-system.test.ts +144 -144
  149. package/src/organization-model/__tests__/graph.test.ts +1246 -887
  150. package/src/organization-model/__tests__/icons.test.ts +10 -1
  151. package/src/organization-model/__tests__/knowledge.test.ts +251 -15
  152. package/src/organization-model/__tests__/lookup-helpers.test.ts +438 -438
  153. package/src/organization-model/__tests__/migration-helpers.test.ts +591 -591
  154. package/src/organization-model/__tests__/prospecting-ssot.test.ts +103 -103
  155. package/src/organization-model/__tests__/recursive-system-schema.test.ts +535 -506
  156. package/src/organization-model/__tests__/resolve.test.ts +274 -164
  157. package/src/organization-model/__tests__/schema.test.ts +834 -301
  158. package/src/organization-model/__tests__/surface-projection.test.ts +284 -284
  159. package/src/organization-model/catalogs/lead-gen.ts +144 -144
  160. package/src/organization-model/content-kinds/config.ts +36 -36
  161. package/src/organization-model/content-kinds/index.ts +76 -72
  162. package/src/organization-model/content-kinds/pipeline.ts +68 -68
  163. package/src/organization-model/content-kinds/registry.ts +44 -44
  164. package/src/organization-model/content-kinds/status.ts +71 -71
  165. package/src/organization-model/content-kinds/template.ts +83 -83
  166. package/src/organization-model/content-kinds/types.ts +117 -117
  167. package/src/organization-model/contracts.ts +27 -27
  168. package/src/organization-model/defaults.ts +40 -50
  169. package/src/organization-model/domains/actions.ts +333 -239
  170. package/src/organization-model/domains/customers.ts +78 -78
  171. package/src/organization-model/domains/entities.ts +144 -144
  172. package/src/organization-model/domains/goals.ts +83 -83
  173. package/src/organization-model/domains/knowledge.ts +117 -101
  174. package/src/organization-model/domains/navigation.ts +139 -139
  175. package/src/organization-model/domains/offerings.ts +71 -71
  176. package/src/organization-model/domains/policies.ts +102 -102
  177. package/src/organization-model/domains/projects.ts +14 -14
  178. package/src/organization-model/domains/prospecting.ts +395 -395
  179. package/src/organization-model/domains/resources.ts +167 -132
  180. package/src/organization-model/domains/roles.ts +96 -96
  181. package/src/organization-model/domains/sales.test.ts +218 -218
  182. package/src/organization-model/domains/sales.ts +380 -380
  183. package/src/organization-model/domains/shared.ts +63 -63
  184. package/src/organization-model/domains/statuses.ts +339 -339
  185. package/src/organization-model/domains/systems.ts +217 -172
  186. package/src/organization-model/foundation.ts +75 -75
  187. package/src/organization-model/graph/build.ts +1016 -888
  188. package/src/organization-model/graph/index.ts +4 -4
  189. package/src/organization-model/graph/link.ts +10 -10
  190. package/src/organization-model/graph/schema.ts +76 -70
  191. package/src/organization-model/graph/types.ts +73 -67
  192. package/src/organization-model/helpers.ts +289 -241
  193. package/src/organization-model/icons.ts +78 -66
  194. package/src/organization-model/index.ts +130 -128
  195. package/src/organization-model/migration-helpers.ts +247 -244
  196. package/src/organization-model/ontology.ts +661 -0
  197. package/src/organization-model/organization-graph.mdx +110 -90
  198. package/src/organization-model/organization-model.mdx +226 -219
  199. package/src/organization-model/published.ts +289 -235
  200. package/src/organization-model/resolve.ts +146 -91
  201. package/src/organization-model/schema.ts +790 -671
  202. package/src/organization-model/surface-projection.ts +212 -212
  203. package/src/organization-model/types.ts +177 -167
  204. package/src/platform/api/types.ts +38 -38
  205. package/src/platform/constants/versions.ts +3 -3
  206. package/src/platform/index.ts +23 -23
  207. package/src/platform/registry/__tests__/command-view.test.ts +10 -10
  208. package/src/platform/registry/__tests__/resource-link.test.ts +35 -35
  209. package/src/platform/registry/__tests__/resource-registry.integration.test.ts +20 -20
  210. package/src/platform/registry/__tests__/resource-registry.nested-systems.test.ts +245 -245
  211. package/src/platform/registry/__tests__/resource-registry.test.ts +2053 -2053
  212. package/src/platform/registry/__tests__/validation.test.ts +1347 -1347
  213. package/src/platform/registry/command-view.ts +10 -10
  214. package/src/platform/registry/index.ts +103 -103
  215. package/src/platform/registry/resource-link.ts +32 -32
  216. package/src/platform/registry/resource-registry.ts +890 -890
  217. package/src/platform/registry/serialization.ts +295 -295
  218. package/src/platform/registry/serialized-types.ts +166 -166
  219. package/src/platform/registry/stats-types.ts +68 -68
  220. package/src/platform/registry/types.ts +425 -425
  221. package/src/platform/registry/validation.ts +745 -745
  222. package/src/platform/utils/__tests__/validation.test.ts +1084 -1084
  223. package/src/platform/utils/validation.ts +425 -425
  224. package/src/projects/api-schemas.test.ts +39 -39
  225. package/src/projects/api-schemas.ts +291 -291
  226. package/src/reference/_generated/contracts.md +2101 -2096
  227. package/src/reference/glossary.md +76 -76
  228. package/src/scaffold-registry/__tests__/index.test.ts +206 -206
  229. package/src/scaffold-registry/__tests__/schema.test.ts +166 -166
  230. package/src/scaffold-registry/index.ts +392 -392
  231. package/src/scaffold-registry/schema.ts +243 -243
  232. package/src/server.ts +289 -289
  233. package/src/supabase/database.types.ts +3153 -3153
  234. package/src/test-utils/README.md +37 -37
  235. package/src/test-utils/entities.ts +108 -108
  236. package/src/test-utils/fixtures/memberships.ts +82 -82
  237. package/src/test-utils/index.ts +12 -12
  238. package/src/test-utils/organization-model.ts +65 -65
  239. package/src/test-utils/published.ts +6 -6
  240. package/src/test-utils/rls/RLSTestContext.ts +588 -588
  241. package/src/test-utils/test-utils.test.ts +44 -44
@@ -1,750 +1,865 @@
1
- import { z } from 'zod'
2
- import { lookupContentType } from './content-kinds/index'
3
- import { OrganizationModelBrandingSchema } from './domains/branding'
4
- import { OrganizationModelNavigationSchema, type SidebarNode } from './domains/navigation'
5
- import { IdentityDomainSchema, DEFAULT_ORGANIZATION_MODEL_IDENTITY } from './domains/identity'
6
- import { CustomersDomainSchema, DEFAULT_ORGANIZATION_MODEL_CUSTOMERS } from './domains/customers'
7
- import { OfferingsDomainSchema, DEFAULT_ORGANIZATION_MODEL_OFFERINGS } from './domains/offerings'
8
- import { RolesDomainSchema, DEFAULT_ORGANIZATION_MODEL_ROLES } from './domains/roles'
9
- import { GoalsDomainSchema, DEFAULT_ORGANIZATION_MODEL_GOALS } from './domains/goals'
10
- import { KnowledgeDomainSchema } from './domains/knowledge'
11
- import { SystemsDomainSchema, DEFAULT_ORGANIZATION_MODEL_SYSTEMS, type SystemEntry } from './domains/systems'
12
- import { ResourcesDomainSchema, DEFAULT_ORGANIZATION_MODEL_RESOURCES } from './domains/resources'
1
+ import { z } from 'zod'
2
+ import { lookupContentType } from './content-kinds/index'
3
+ import { OrganizationModelBrandingSchema } from './domains/branding'
4
+ import { OrganizationModelNavigationSchema, type SidebarNode } from './domains/navigation'
5
+ import { IdentityDomainSchema, DEFAULT_ORGANIZATION_MODEL_IDENTITY } from './domains/identity'
6
+ import { CustomersDomainSchema, DEFAULT_ORGANIZATION_MODEL_CUSTOMERS } from './domains/customers'
7
+ import { OfferingsDomainSchema, DEFAULT_ORGANIZATION_MODEL_OFFERINGS } from './domains/offerings'
8
+ import { RolesDomainSchema, DEFAULT_ORGANIZATION_MODEL_ROLES } from './domains/roles'
9
+ import { GoalsDomainSchema, DEFAULT_ORGANIZATION_MODEL_GOALS } from './domains/goals'
10
+ import { KnowledgeDomainSchema } from './domains/knowledge'
11
+ import { SystemsDomainSchema, DEFAULT_ORGANIZATION_MODEL_SYSTEMS, type SystemEntry } from './domains/systems'
12
+ import { ResourcesDomainSchema, DEFAULT_ORGANIZATION_MODEL_RESOURCES } from './domains/resources'
13
13
  import { ActionsDomainSchema, DEFAULT_ORGANIZATION_MODEL_ACTIONS } from './domains/actions'
14
14
  import { EntitiesDomainSchema, DEFAULT_ORGANIZATION_MODEL_ENTITIES } from './domains/entities'
15
15
  import { PoliciesDomainSchema, DEFAULT_ORGANIZATION_MODEL_POLICIES } from './domains/policies'
16
-
17
- // Phase 4 cut: 'sales', 'prospecting', 'projects', 'statuses' removed.
18
- // domainMetadata.knowledge covers versioning for the knowledge flat-map (D7).
19
- export const OrganizationModelDomainKeySchema = z.enum([
20
- 'branding',
21
- 'identity',
22
- 'customers',
23
- 'offerings',
24
- 'roles',
25
- 'goals',
16
+ import {
17
+ compileOrganizationOntology,
18
+ DEFAULT_ONTOLOGY_SCOPE,
19
+ listResolvedOntologyRecords,
20
+ OntologyScopeSchema,
21
+ type OntologyKind
22
+ } from './ontology'
23
+
24
+ // Phase 4 cut: 'sales', 'prospecting', 'projects', 'statuses' removed.
25
+ // domainMetadata.knowledge covers versioning for the knowledge flat-map (D7).
26
+ export const OrganizationModelDomainKeySchema = z.enum([
27
+ 'branding',
28
+ 'identity',
29
+ 'customers',
30
+ 'offerings',
31
+ 'roles',
32
+ 'goals',
26
33
  'systems',
34
+ 'ontology',
27
35
  'resources',
28
- 'actions',
29
- 'entities',
30
- 'policies',
31
- 'knowledge'
32
- ])
33
-
34
- export const OrganizationModelDomainMetadataSchema = z.object({
35
- version: z.literal(1).default(1),
36
- lastModified: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'lastModified must be an ISO date string (YYYY-MM-DD)')
37
- })
38
-
39
- export const DEFAULT_ORGANIZATION_MODEL_DOMAIN_METADATA: Record<
40
- z.infer<typeof OrganizationModelDomainKeySchema>,
41
- z.infer<typeof OrganizationModelDomainMetadataSchema>
42
- > = {
43
- branding: { version: 1, lastModified: '2026-05-10' },
44
- identity: { version: 1, lastModified: '2026-05-10' },
45
- customers: { version: 1, lastModified: '2026-05-10' },
46
- offerings: { version: 1, lastModified: '2026-05-10' },
47
- roles: { version: 1, lastModified: '2026-05-10' },
48
- goals: { version: 1, lastModified: '2026-05-10' },
36
+ 'actions',
37
+ 'entities',
38
+ 'policies',
39
+ 'knowledge'
40
+ ])
41
+
42
+ export const OrganizationModelDomainMetadataSchema = z.object({
43
+ version: z.literal(1).default(1),
44
+ lastModified: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'lastModified must be an ISO date string (YYYY-MM-DD)')
45
+ })
46
+
47
+ export const DEFAULT_ORGANIZATION_MODEL_DOMAIN_METADATA: Record<
48
+ z.infer<typeof OrganizationModelDomainKeySchema>,
49
+ z.infer<typeof OrganizationModelDomainMetadataSchema>
50
+ > = {
51
+ branding: { version: 1, lastModified: '2026-05-10' },
52
+ identity: { version: 1, lastModified: '2026-05-10' },
53
+ customers: { version: 1, lastModified: '2026-05-10' },
54
+ offerings: { version: 1, lastModified: '2026-05-10' },
55
+ roles: { version: 1, lastModified: '2026-05-10' },
56
+ goals: { version: 1, lastModified: '2026-05-10' },
49
57
  systems: { version: 1, lastModified: '2026-05-10' },
58
+ ontology: { version: 1, lastModified: '2026-05-14' },
50
59
  resources: { version: 1, lastModified: '2026-05-10' },
51
- actions: { version: 1, lastModified: '2026-05-10' },
52
- entities: { version: 1, lastModified: '2026-05-10' },
53
- policies: { version: 1, lastModified: '2026-05-10' },
54
- knowledge: { version: 1, lastModified: '2026-05-10' }
55
- }
56
-
57
- export const OrganizationModelDomainMetadataByDomainSchema = z
58
- .object({
59
- branding: OrganizationModelDomainMetadataSchema,
60
- identity: OrganizationModelDomainMetadataSchema,
61
- customers: OrganizationModelDomainMetadataSchema,
62
- offerings: OrganizationModelDomainMetadataSchema,
63
- roles: OrganizationModelDomainMetadataSchema,
64
- goals: OrganizationModelDomainMetadataSchema,
60
+ actions: { version: 1, lastModified: '2026-05-10' },
61
+ entities: { version: 1, lastModified: '2026-05-10' },
62
+ policies: { version: 1, lastModified: '2026-05-10' },
63
+ knowledge: { version: 1, lastModified: '2026-05-10' }
64
+ }
65
+
66
+ export const OrganizationModelDomainMetadataByDomainSchema = z
67
+ .object({
68
+ branding: OrganizationModelDomainMetadataSchema,
69
+ identity: OrganizationModelDomainMetadataSchema,
70
+ customers: OrganizationModelDomainMetadataSchema,
71
+ offerings: OrganizationModelDomainMetadataSchema,
72
+ roles: OrganizationModelDomainMetadataSchema,
73
+ goals: OrganizationModelDomainMetadataSchema,
65
74
  systems: OrganizationModelDomainMetadataSchema,
75
+ ontology: OrganizationModelDomainMetadataSchema,
66
76
  resources: OrganizationModelDomainMetadataSchema,
67
- actions: OrganizationModelDomainMetadataSchema,
68
- entities: OrganizationModelDomainMetadataSchema,
69
- policies: OrganizationModelDomainMetadataSchema,
70
- knowledge: OrganizationModelDomainMetadataSchema
71
- })
72
- .partial()
73
- .default(DEFAULT_ORGANIZATION_MODEL_DOMAIN_METADATA)
74
- .transform((metadata) => ({ ...DEFAULT_ORGANIZATION_MODEL_DOMAIN_METADATA, ...metadata }))
75
-
76
- // Phase 4 schema cut (D8):
77
- // REMOVED top-level fields: sales, prospecting, projects, statuses
78
- // ADDED navigation.sidebar as the authored shell tree
79
- // knowledge: now Record<id, OrgKnowledgeNode> flat map (D3); version/lastModified in domainMetadata.knowledge (D7)
80
- //
81
- // Clean migration rule:
82
- // NO top-level surfaces / navigationGroups compatibility fields.
83
- // Surfaces are derived from navigation.sidebar routeable leaves.
84
- const OrganizationModelSchemaBase = z.object({
85
- version: z.literal(1).default(1),
86
- domainMetadata: OrganizationModelDomainMetadataByDomainSchema,
87
- branding: OrganizationModelBrandingSchema,
88
- navigation: OrganizationModelNavigationSchema,
89
- identity: IdentityDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_IDENTITY),
90
- customers: CustomersDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_CUSTOMERS),
91
- offerings: OfferingsDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_OFFERINGS),
92
- roles: RolesDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_ROLES),
93
- goals: GoalsDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_GOALS),
77
+ actions: OrganizationModelDomainMetadataSchema,
78
+ entities: OrganizationModelDomainMetadataSchema,
79
+ policies: OrganizationModelDomainMetadataSchema,
80
+ knowledge: OrganizationModelDomainMetadataSchema
81
+ })
82
+ .partial()
83
+ .default(DEFAULT_ORGANIZATION_MODEL_DOMAIN_METADATA)
84
+ .transform((metadata) => ({ ...DEFAULT_ORGANIZATION_MODEL_DOMAIN_METADATA, ...metadata }))
85
+
86
+ // Phase 4 schema cut (D8):
87
+ // REMOVED top-level fields: sales, prospecting, projects, statuses
88
+ // ADDED navigation.sidebar as the authored shell tree
89
+ // knowledge: now Record<id, OrgKnowledgeNode> flat map (D3); version/lastModified in domainMetadata.knowledge (D7)
90
+ //
91
+ // Clean migration rule:
92
+ // NO top-level surfaces / navigationGroups compatibility fields.
93
+ // Surfaces are derived from navigation.sidebar routeable leaves.
94
+ const OrganizationModelSchemaBase = z.object({
95
+ version: z.literal(1).default(1),
96
+ domainMetadata: OrganizationModelDomainMetadataByDomainSchema,
97
+ branding: OrganizationModelBrandingSchema,
98
+ navigation: OrganizationModelNavigationSchema,
99
+ identity: IdentityDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_IDENTITY),
100
+ customers: CustomersDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_CUSTOMERS),
101
+ offerings: OfferingsDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_OFFERINGS),
102
+ roles: RolesDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_ROLES),
103
+ goals: GoalsDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_GOALS),
94
104
  systems: SystemsDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_SYSTEMS),
105
+ ontology: OntologyScopeSchema.default(DEFAULT_ONTOLOGY_SCOPE),
95
106
  resources: ResourcesDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_RESOURCES),
96
- actions: ActionsDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_ACTIONS),
97
- entities: EntitiesDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_ENTITIES),
98
- policies: PoliciesDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_POLICIES),
99
- // D3: flat Record<id, OrgKnowledgeNode> — no wrapper object
100
- knowledge: KnowledgeDomainSchema.default({})
101
- })
102
-
103
- function addIssue(ctx: z.RefinementCtx, path: Array<string | number>, message: string): void {
104
- ctx.addIssue({
105
- code: z.ZodIssueCode.custom,
106
- path,
107
- message
108
- })
109
- }
110
-
111
- function isLifecycleEnabled(lifecycle: string | undefined, enabled: boolean | undefined): boolean {
112
- if (enabled === false) return false
113
- return lifecycle !== 'deprecated' && lifecycle !== 'archived'
114
- }
115
-
116
- function defaultSystemPathFor(id: string): string {
117
- return `/${id.replaceAll('.', '/')}`
118
- }
119
-
120
- function asRoleHolderArray(
121
- heldBy: NonNullable<z.infer<typeof OrganizationModelSchemaBase>['roles'][string]['heldBy']>
122
- ) {
123
- return Array.isArray(heldBy) ? heldBy : [heldBy]
124
- }
125
-
107
+ actions: ActionsDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_ACTIONS),
108
+ entities: EntitiesDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_ENTITIES),
109
+ policies: PoliciesDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_POLICIES),
110
+ // D3: flat Record<id, OrgKnowledgeNode> — no wrapper object
111
+ knowledge: KnowledgeDomainSchema.default({})
112
+ })
113
+
114
+ function addIssue(ctx: z.RefinementCtx, path: Array<string | number>, message: string): void {
115
+ ctx.addIssue({
116
+ code: z.ZodIssueCode.custom,
117
+ path,
118
+ message
119
+ })
120
+ }
121
+
122
+ function isLifecycleEnabled(lifecycle: string | undefined, enabled: boolean | undefined): boolean {
123
+ if (enabled === false) return false
124
+ return lifecycle !== 'deprecated' && lifecycle !== 'archived'
125
+ }
126
+
127
+ function defaultSystemPathFor(id: string): string {
128
+ return `/${id.replaceAll('.', '/')}`
129
+ }
130
+
131
+ function asRoleHolderArray(
132
+ heldBy: NonNullable<z.infer<typeof OrganizationModelSchemaBase>['roles'][string]['heldBy']>
133
+ ) {
134
+ return Array.isArray(heldBy) ? heldBy : [heldBy]
135
+ }
136
+
126
137
  function isKnowledgeKindCompatibleWithTarget(knowledgeKind: string, targetKind: string): boolean {
127
- if (knowledgeKind === 'reference') return true
138
+ if (knowledgeKind === 'reference') return true
128
139
  if (knowledgeKind === 'playbook') {
129
- return ['system', 'resource', 'stage', 'action'].includes(targetKind)
140
+ return ['system', 'resource', 'stage', 'action', 'ontology'].includes(targetKind)
130
141
  }
131
142
  if (knowledgeKind === 'strategy') {
132
- return ['system', 'goal', 'offering', 'customer-segment'].includes(targetKind)
143
+ return ['system', 'goal', 'offering', 'customer-segment', 'ontology'].includes(targetKind)
133
144
  }
134
145
  return false
135
146
  }
136
147
 
137
- export const OrganizationModelSchema = OrganizationModelSchemaBase.superRefine((model, ctx) => {
138
- // Collect ALL system entries recursively top-level systems plus any nested subsystems.
139
- // Wave 2 canonical OM authors nested subsystems (e.g. sys → subsystems → 'lead-gen' with id
140
- // 'sys.lead-gen'). Resource systemPath cross-refs must resolve against the full flattened set.
141
- type SystemWithPath = { path: string; schemaPath: Array<string | number>; system: SystemEntry }
142
-
148
+ function isRecord(value: unknown): value is Record<string, unknown> {
149
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
150
+ }
151
+
152
+ export const OrganizationModelSchema = OrganizationModelSchemaBase.superRefine((model, ctx) => {
153
+ // Collect ALL system entries recursively — top-level systems plus any nested subsystems.
154
+ // Wave 2 canonical OM authors nested subsystems (e.g. sys → subsystems → 'lead-gen' with id
155
+ // 'sys.lead-gen'). Resource systemPath cross-refs must resolve against the full flattened set.
156
+ type SystemWithPath = { path: string; schemaPath: Array<string | number>; system: SystemEntry }
157
+
143
158
  function collectAllSystems(
144
159
  systems: Record<string, SystemEntry>,
145
160
  prefix = '',
146
161
  schemaPath: Array<string | number> = ['systems']
147
162
  ): SystemWithPath[] {
148
- const result: SystemWithPath[] = []
149
- for (const [key, system] of Object.entries(systems)) {
163
+ const result: SystemWithPath[] = []
164
+ for (const [key, system] of Object.entries(systems)) {
150
165
  const path = prefix ? `${prefix}.${key}` : key
151
166
  const currentSchemaPath = [...schemaPath, key]
152
167
  result.push({ path, schemaPath: currentSchemaPath, system })
153
- if (system.subsystems !== undefined) {
154
- result.push(...collectAllSystems(system.subsystems, path, [...currentSchemaPath, 'subsystems']))
168
+ const childSystems = system.systems ?? system.subsystems
169
+ if (childSystems !== undefined) {
170
+ result.push(
171
+ ...collectAllSystems(childSystems, path, [...currentSchemaPath, system.systems !== undefined ? 'systems' : 'subsystems'])
172
+ )
155
173
  }
156
174
  }
157
175
  return result
158
- }
159
-
160
- const allSystems = collectAllSystems(model.systems)
161
- const systemsById = new Map<string, SystemEntry>()
162
- for (const { path, system } of allSystems) {
163
- systemsById.set(path, system)
164
- systemsById.set(system.id, system)
165
- }
166
-
167
- const systemIdsByEffectivePath = new Map<string, string>()
168
- allSystems.forEach(({ path, schemaPath, system }) => {
169
- if (system.parentSystemId !== undefined && !systemsById.has(system.parentSystemId)) {
170
- addIssue(
171
- ctx,
172
- [...schemaPath, 'parentSystemId'],
173
- `System "${system.id}" references unknown parent "${system.parentSystemId}"`
174
- )
175
- }
176
-
176
+ }
177
+
178
+ const allSystems = collectAllSystems(model.systems)
179
+ const systemsById = new Map<string, SystemEntry>()
180
+ for (const { path, system } of allSystems) {
181
+ systemsById.set(path, system)
182
+ systemsById.set(system.id, system)
183
+ }
184
+
185
+ const systemIdsByEffectivePath = new Map<string, string>()
186
+ allSystems.forEach(({ path, schemaPath, system }) => {
187
+ if (system.parentSystemId !== undefined && !systemsById.has(system.parentSystemId)) {
188
+ addIssue(
189
+ ctx,
190
+ [...schemaPath, 'parentSystemId'],
191
+ `System "${system.id}" references unknown parent "${system.parentSystemId}"`
192
+ )
193
+ }
194
+
177
195
  const hasChildren =
178
- Object.keys(system.subsystems ?? {}).length > 0 ||
196
+ Object.keys(system.systems ?? system.subsystems ?? {}).length > 0 ||
179
197
  allSystems.some((candidate) => candidate.path.startsWith(`${path}.`) && !candidate.path.slice(path.length + 1).includes('.'))
180
- const contributesRoutePath = system.ui?.path !== undefined || system.path !== undefined || !hasChildren
181
- if (contributesRoutePath) {
182
- const effectivePath = system.ui?.path ?? system.path ?? defaultSystemPathFor(path)
183
- const existingSystemId = systemIdsByEffectivePath.get(effectivePath)
184
- if (existingSystemId !== undefined) {
185
- addIssue(
186
- ctx,
187
- [...schemaPath, system.ui?.path !== undefined ? 'ui' : 'path'],
188
- `System "${path}" effective path "${effectivePath}" duplicates system "${existingSystemId}"`
189
- )
190
- } else {
191
- systemIdsByEffectivePath.set(effectivePath, path)
192
- }
193
- }
194
-
195
- if (hasChildren && isLifecycleEnabled(system.lifecycle, system.enabled)) {
198
+ const contributesRoutePath = system.ui?.path !== undefined || system.path !== undefined || !hasChildren
199
+ if (contributesRoutePath) {
200
+ const effectivePath = system.ui?.path ?? system.path ?? defaultSystemPathFor(path)
201
+ const existingSystemId = systemIdsByEffectivePath.get(effectivePath)
202
+ if (existingSystemId !== undefined) {
203
+ addIssue(
204
+ ctx,
205
+ [...schemaPath, system.ui?.path !== undefined ? 'ui' : 'path'],
206
+ `System "${path}" effective path "${effectivePath}" duplicates system "${existingSystemId}"`
207
+ )
208
+ } else {
209
+ systemIdsByEffectivePath.set(effectivePath, path)
210
+ }
211
+ }
212
+
213
+ if (hasChildren && isLifecycleEnabled(system.lifecycle, system.enabled)) {
196
214
  const hasEnabledDescendant =
197
- Object.values(system.subsystems ?? {}).some((candidate) =>
215
+ Object.values(system.systems ?? system.subsystems ?? {}).some((candidate) =>
198
216
  isLifecycleEnabled(candidate.lifecycle, candidate.enabled)
199
217
  ) ||
200
- allSystems.some(
201
- (candidate) =>
202
- candidate.path.startsWith(`${path}.`) &&
203
- !candidate.path.slice(path.length + 1).includes('.') &&
204
- isLifecycleEnabled(candidate.system.lifecycle, candidate.system.enabled)
205
- )
206
- if (!hasEnabledDescendant) {
207
- addIssue(
208
- ctx,
209
- [...schemaPath, 'lifecycle'],
210
- `System "${path}" is active but has no active descendants`
211
- )
212
- }
213
- }
214
- })
215
-
216
- allSystems.forEach(({ schemaPath, system }) => {
217
- const visited = new Set<string>()
218
- let currentParentId = system.parentSystemId
219
-
220
- while (currentParentId !== undefined) {
221
- if (currentParentId === system.id || visited.has(currentParentId)) {
222
- addIssue(ctx, [...schemaPath, 'parentSystemId'], `System "${system.id}" has a parent cycle`)
223
- return
224
- }
225
-
226
- visited.add(currentParentId)
227
- currentParentId = systemsById.get(currentParentId)?.parentSystemId
228
- }
229
- })
230
-
231
- type CollectedSidebarSurface = {
232
- id: string
233
- node: Extract<SidebarNode, { type: 'surface' }>
234
- path: Array<string | number>
235
- }
236
-
237
- function normalizeRoutePath(path: string): string {
238
- return path.length > 1 ? path.replace(/\/+$/, '') : path
239
- }
240
-
241
- const sidebarNodeIds = new Map<string, Array<string | number>>()
242
- const sidebarSurfacePaths = new Map<string, string>()
243
- const sidebarSurfaces: CollectedSidebarSurface[] = []
244
-
245
- function collectSidebarNodes(
246
- nodes: Record<string, SidebarNode>,
247
- schemaPath: Array<string | number>
218
+ allSystems.some(
219
+ (candidate) =>
220
+ candidate.path.startsWith(`${path}.`) &&
221
+ !candidate.path.slice(path.length + 1).includes('.') &&
222
+ isLifecycleEnabled(candidate.system.lifecycle, candidate.system.enabled)
223
+ )
224
+ if (!hasEnabledDescendant) {
225
+ addIssue(
226
+ ctx,
227
+ [...schemaPath, 'lifecycle'],
228
+ `System "${path}" is active but has no active descendants`
229
+ )
230
+ }
231
+ }
232
+ })
233
+
234
+ allSystems.forEach(({ schemaPath, system }) => {
235
+ const visited = new Set<string>()
236
+ let currentParentId = system.parentSystemId
237
+
238
+ while (currentParentId !== undefined) {
239
+ if (currentParentId === system.id || visited.has(currentParentId)) {
240
+ addIssue(ctx, [...schemaPath, 'parentSystemId'], `System "${system.id}" has a parent cycle`)
241
+ return
242
+ }
243
+
244
+ visited.add(currentParentId)
245
+ currentParentId = systemsById.get(currentParentId)?.parentSystemId
246
+ }
247
+ })
248
+
249
+ type CollectedSidebarSurface = {
250
+ id: string
251
+ node: Extract<SidebarNode, { type: 'surface' }>
252
+ path: Array<string | number>
253
+ }
254
+
255
+ function normalizeRoutePath(path: string): string {
256
+ return path.length > 1 ? path.replace(/\/+$/, '') : path
257
+ }
258
+
259
+ const sidebarNodeIds = new Map<string, Array<string | number>>()
260
+ const sidebarSurfacePaths = new Map<string, string>()
261
+ const sidebarSurfaces: CollectedSidebarSurface[] = []
262
+
263
+ function collectSidebarNodes(
264
+ nodes: Record<string, SidebarNode>,
265
+ schemaPath: Array<string | number>
266
+ ): void {
267
+ Object.entries(nodes).forEach(([nodeId, node]) => {
268
+ const nodePath = [...schemaPath, nodeId]
269
+ const existingNodePath = sidebarNodeIds.get(nodeId)
270
+ if (existingNodePath !== undefined) {
271
+ addIssue(ctx, nodePath, `Sidebar node id "${nodeId}" duplicates another sidebar node`)
272
+ } else {
273
+ sidebarNodeIds.set(nodeId, nodePath)
274
+ }
275
+
276
+ if (node.type === 'group') {
277
+ collectSidebarNodes(node.children, [...nodePath, 'children'])
278
+ return
279
+ }
280
+
281
+ sidebarSurfaces.push({ id: nodeId, node, path: nodePath })
282
+ const normalizedPath = normalizeRoutePath(node.path)
283
+ const existingSurfaceId = sidebarSurfacePaths.get(normalizedPath)
284
+ if (existingSurfaceId !== undefined) {
285
+ addIssue(
286
+ ctx,
287
+ [...nodePath, 'path'],
288
+ `Sidebar surface path "${node.path}" duplicates surface "${existingSurfaceId}"`
289
+ )
290
+ } else {
291
+ sidebarSurfacePaths.set(normalizedPath, nodeId)
292
+ }
293
+
294
+ node.targets?.systems?.forEach((systemId, systemIndex) => {
295
+ if (!systemsById.has(systemId)) {
296
+ addIssue(
297
+ ctx,
298
+ [...nodePath, 'targets', 'systems', systemIndex],
299
+ `Sidebar surface "${nodeId}" references unknown system "${systemId}"`
300
+ )
301
+ }
302
+ })
303
+ })
304
+ }
305
+
306
+ collectSidebarNodes(model.navigation.sidebar.primary, ['navigation', 'sidebar', 'primary'])
307
+ collectSidebarNodes(model.navigation.sidebar.bottom, ['navigation', 'sidebar', 'bottom'])
308
+
309
+ // Offerings -> CustomerSegment cross-ref: targetSegmentIds must resolve
310
+ const segmentsById = new Map(Object.entries(model.customers))
311
+ Object.values(model.offerings).forEach((product) => {
312
+ product.targetSegmentIds.forEach((segmentId, segmentIndex) => {
313
+ if (!segmentsById.has(segmentId)) {
314
+ addIssue(
315
+ ctx,
316
+ ['offerings', product.id, 'targetSegmentIds', segmentIndex],
317
+ `Product "${product.id}" references unknown customer segment "${segmentId}"`
318
+ )
319
+ }
320
+ })
321
+
322
+ // Offerings -> System cross-ref: deliveryFeatureId must resolve (when present)
323
+ if (product.deliveryFeatureId !== undefined && !systemsById.has(product.deliveryFeatureId)) {
324
+ addIssue(
325
+ ctx,
326
+ ['offerings', product.id, 'deliveryFeatureId'],
327
+ `Product "${product.id}" references unknown delivery system "${product.deliveryFeatureId}"`
328
+ )
329
+ }
330
+ })
331
+
332
+ // Goals -> period-range validation: periodEnd must be strictly after periodStart
333
+ Object.values(model.goals).forEach((objective) => {
334
+ if (objective.periodEnd <= objective.periodStart) {
335
+ addIssue(
336
+ ctx,
337
+ ['goals', objective.id, 'periodEnd'],
338
+ `Goal "${objective.id}" has periodEnd "${objective.periodEnd}" which must be strictly after periodStart "${objective.periodStart}"`
339
+ )
340
+ }
341
+ })
342
+
343
+ const goalsById = new Map(Object.entries(model.goals))
344
+ // Phase 4: knowledge is now a flat Record<id, OrgKnowledgeNode> — no .nodes array
345
+ const knowledgeById = new Map(Object.entries(model.knowledge))
346
+ const actionsById = new Map(Object.entries(model.actions))
347
+ const entitiesById = new Map(Object.entries(model.entities))
348
+ const policiesById = new Map(Object.entries(model.policies))
349
+
350
+ sidebarSurfaces.forEach(({ id, node, path }) => {
351
+ node.targets?.entities?.forEach((entityId, entityIndex) => {
352
+ if (!entitiesById.has(entityId)) {
353
+ addIssue(
354
+ ctx,
355
+ [...path, 'targets', 'entities', entityIndex],
356
+ `Sidebar surface "${id}" references unknown entity "${entityId}"`
357
+ )
358
+ }
359
+ })
360
+
361
+ node.targets?.actions?.forEach((actionId, actionIndex) => {
362
+ if (!actionsById.has(actionId)) {
363
+ addIssue(
364
+ ctx,
365
+ [...path, 'targets', 'actions', actionIndex],
366
+ `Sidebar surface "${id}" references unknown action "${actionId}"`
367
+ )
368
+ }
369
+ })
370
+ })
371
+
372
+ Object.values(model.entities).forEach((entity) => {
373
+ if (!systemsById.has(entity.ownedBySystemId)) {
374
+ addIssue(
375
+ ctx,
376
+ ['entities', entity.id, 'ownedBySystemId'],
377
+ `Entity "${entity.id}" references unknown ownedBySystemId "${entity.ownedBySystemId}"`
378
+ )
379
+ }
380
+
381
+ entity.links?.forEach((link, linkIndex) => {
382
+ if (!entitiesById.has(link.toEntity)) {
383
+ addIssue(
384
+ ctx,
385
+ ['entities', entity.id, 'links', linkIndex, 'toEntity'],
386
+ `Entity "${entity.id}" links to unknown entity "${link.toEntity}"`
387
+ )
388
+ }
389
+ })
390
+ })
391
+
392
+ // Roles -> reportsToId cross-ref: each reportsToId must resolve to another role in the same collection
393
+ const rolesById = new Map(Object.entries(model.roles))
394
+ Object.values(model.roles).forEach((role) => {
395
+ if (role.reportsToId !== undefined && !rolesById.has(role.reportsToId)) {
396
+ addIssue(
397
+ ctx,
398
+ ['roles', role.id, 'reportsToId'],
399
+ `Role "${role.id}" references unknown reportsToId "${role.reportsToId}"`
400
+ )
401
+ }
402
+ })
403
+
404
+ Object.values(model.roles).forEach((role) => {
405
+ const visited = new Set<string>()
406
+ let currentReportsToId = role.reportsToId
407
+
408
+ while (currentReportsToId !== undefined) {
409
+ if (currentReportsToId === role.id || visited.has(currentReportsToId)) {
410
+ addIssue(ctx, ['roles', role.id, 'reportsToId'], `Role "${role.id}" has a reportsToId cycle`)
411
+ return
412
+ }
413
+
414
+ visited.add(currentReportsToId)
415
+ currentReportsToId = rolesById.get(currentReportsToId)?.reportsToId
416
+ }
417
+ })
418
+
419
+ Object.values(model.roles).forEach((role) => {
420
+ role.responsibleFor?.forEach((systemId, systemIndex) => {
421
+ if (!systemsById.has(systemId)) {
422
+ addIssue(
423
+ ctx,
424
+ ['roles', role.id, 'responsibleFor', systemIndex],
425
+ `Role "${role.id}" references unknown responsibleFor system "${systemId}"`
426
+ )
427
+ }
428
+ })
429
+ })
430
+
431
+ allSystems.forEach(({ schemaPath, system }) => {
432
+ if (system.responsibleRoleId !== undefined && !rolesById.has(system.responsibleRoleId)) {
433
+ addIssue(
434
+ ctx,
435
+ [...schemaPath, 'responsibleRoleId'],
436
+ `System "${system.id}" references unknown responsibleRoleId "${system.responsibleRoleId}"`
437
+ )
438
+ }
439
+
440
+ system.governedByKnowledge?.forEach((nodeId, nodeIndex) => {
441
+ if (!knowledgeById.has(nodeId)) {
442
+ addIssue(
443
+ ctx,
444
+ [...schemaPath, 'governedByKnowledge', nodeIndex],
445
+ `System "${system.id}" references unknown knowledge node "${nodeId}"`
446
+ )
447
+ }
448
+ })
449
+
450
+ system.drivesGoals?.forEach((goalId, goalIndex) => {
451
+ if (!goalsById.has(goalId)) {
452
+ addIssue(
453
+ ctx,
454
+ [...schemaPath, 'drivesGoals', goalIndex],
455
+ `System "${system.id}" references unknown goal "${goalId}"`
456
+ )
457
+ }
458
+ })
459
+
460
+ system.actions?.forEach((actionRef, actionIndex) => {
461
+ if (!actionsById.has(actionRef.actionId)) {
462
+ addIssue(
463
+ ctx,
464
+ [...schemaPath, 'actions', actionIndex, 'actionId'],
465
+ `System "${system.id}" references unknown action "${actionRef.actionId}"`
466
+ )
467
+ }
468
+ })
469
+
470
+ system.policies?.forEach((policyId, policyIndex) => {
471
+ if (!policiesById.has(policyId)) {
472
+ addIssue(
473
+ ctx,
474
+ [...schemaPath, 'policies', policyIndex],
475
+ `System "${system.id}" references unknown policy "${policyId}"`
476
+ )
477
+ }
478
+ })
479
+ })
480
+
481
+ Object.values(model.actions).forEach((action) => {
482
+ action.affects?.forEach((entityId, entityIndex) => {
483
+ if (!entitiesById.has(entityId)) {
484
+ addIssue(
485
+ ctx,
486
+ ['actions', action.id, 'affects', entityIndex],
487
+ `Action "${action.id}" affects unknown entity "${entityId}"`
488
+ )
489
+ }
490
+ })
491
+ })
492
+
493
+ // Phase 4: sales / prospecting / projects compound-domain entity cross-ref checks removed.
494
+ // Those entity bindings now live in system.content (Wave 2 canonicalOrganizationModel).
495
+
496
+ const resourcesById = new Map(Object.entries(model.resources))
497
+ sidebarSurfaces.forEach(({ id, node, path }) => {
498
+ node.targets?.resources?.forEach((resourceId, resourceIndex) => {
499
+ if (!resourcesById.has(resourceId)) {
500
+ addIssue(
501
+ ctx,
502
+ [...path, 'targets', 'resources', resourceIndex],
503
+ `Sidebar surface "${id}" references unknown resource "${resourceId}"`
504
+ )
505
+ }
506
+ })
507
+ })
508
+ // Phase 4: stageIds previously sourced from model.prospecting.*Stages; stages now live in
509
+ // system.content as schema:stage nodes. knowledge 'stage' target validation is kept permissive
510
+ // (always false) — Wave 2 will wire a content-based stage lookup when canonical OM lands.
511
+ const stageIds = new Set<string>()
512
+ const actionIds = new Set(Object.keys(model.actions))
513
+ const offeringsById = new Map(Object.entries(model.offerings))
514
+ const ontologyCompilation = compileOrganizationOntology(model)
515
+ const ontologyIndexByKind = {
516
+ object: ontologyCompilation.ontology.objectTypes,
517
+ link: ontologyCompilation.ontology.linkTypes,
518
+ action: ontologyCompilation.ontology.actionTypes,
519
+ catalog: ontologyCompilation.ontology.catalogTypes,
520
+ event: ontologyCompilation.ontology.eventTypes,
521
+ interface: ontologyCompilation.ontology.interfaceTypes,
522
+ 'value-type': ontologyCompilation.ontology.valueTypes,
523
+ property: ontologyCompilation.ontology.sharedProperties,
524
+ group: ontologyCompilation.ontology.groups,
525
+ surface: ontologyCompilation.ontology.surfaces
526
+ } satisfies Record<OntologyKind, Record<string, unknown>>
527
+ const ontologyIds = new Set(Object.values(ontologyIndexByKind).flatMap((index) => Object.keys(index)))
528
+
529
+ const ontologyReferenceKeyKinds = {
530
+ valueType: 'value-type',
531
+ catalogType: 'catalog',
532
+ objectType: 'object',
533
+ eventType: 'event',
534
+ actionType: 'action',
535
+ linkType: 'link',
536
+ interfaceType: 'interface',
537
+ propertyType: 'property',
538
+ groupType: 'group',
539
+ surfaceType: 'surface',
540
+ stepCatalog: 'catalog'
541
+ } satisfies Record<string, OntologyKind>
542
+
543
+ function validateKnownOntologyReferences(
544
+ ownerId: string,
545
+ value: unknown,
546
+ path: Array<string | number>,
547
+ seen = new WeakSet<object>()
248
548
  ): void {
249
- Object.entries(nodes).forEach(([nodeId, node]) => {
250
- const nodePath = [...schemaPath, nodeId]
251
- const existingNodePath = sidebarNodeIds.get(nodeId)
252
- if (existingNodePath !== undefined) {
253
- addIssue(ctx, nodePath, `Sidebar node id "${nodeId}" duplicates another sidebar node`)
254
- } else {
255
- sidebarNodeIds.set(nodeId, nodePath)
256
- }
549
+ if (Array.isArray(value)) {
550
+ value.forEach((entry, index) => validateKnownOntologyReferences(ownerId, entry, [...path, index], seen))
551
+ return
552
+ }
257
553
 
258
- if (node.type === 'group') {
259
- collectSidebarNodes(node.children, [...nodePath, 'children'])
260
- return
261
- }
554
+ if (!isRecord(value)) return
555
+ if (seen.has(value)) return
556
+ seen.add(value)
262
557
 
263
- sidebarSurfaces.push({ id: nodeId, node, path: nodePath })
264
- const normalizedPath = normalizeRoutePath(node.path)
265
- const existingSurfaceId = sidebarSurfacePaths.get(normalizedPath)
266
- if (existingSurfaceId !== undefined) {
267
- addIssue(
268
- ctx,
269
- [...nodePath, 'path'],
270
- `Sidebar surface path "${node.path}" duplicates surface "${existingSurfaceId}"`
271
- )
272
- } else {
273
- sidebarSurfacePaths.set(normalizedPath, nodeId)
274
- }
275
-
276
- node.targets?.systems?.forEach((systemId, systemIndex) => {
277
- if (!systemsById.has(systemId)) {
558
+ Object.entries(value).forEach(([key, entry]) => {
559
+ const expectedKind = ontologyReferenceKeyKinds[key as keyof typeof ontologyReferenceKeyKinds]
560
+ if (expectedKind !== undefined) {
561
+ if (typeof entry !== 'string') {
562
+ addIssue(ctx, [...path, key], `Ontology record "${ownerId}" ${key} must be an ontology ID string`)
563
+ } else if (ontologyIndexByKind[expectedKind][entry] === undefined) {
278
564
  addIssue(
279
565
  ctx,
280
- [...nodePath, 'targets', 'systems', systemIndex],
281
- `Sidebar surface "${nodeId}" references unknown system "${systemId}"`
566
+ [...path, key],
567
+ `Ontology record "${ownerId}" ${key} references unknown ${expectedKind} ontology ID "${entry}"`
282
568
  )
283
569
  }
284
- })
285
- })
286
- }
287
-
288
- collectSidebarNodes(model.navigation.sidebar.primary, ['navigation', 'sidebar', 'primary'])
289
- collectSidebarNodes(model.navigation.sidebar.bottom, ['navigation', 'sidebar', 'bottom'])
290
-
291
- // Offerings -> CustomerSegment cross-ref: targetSegmentIds must resolve
292
- const segmentsById = new Map(Object.entries(model.customers))
293
- Object.values(model.offerings).forEach((product) => {
294
- product.targetSegmentIds.forEach((segmentId, segmentIndex) => {
295
- if (!segmentsById.has(segmentId)) {
296
- addIssue(
297
- ctx,
298
- ['offerings', product.id, 'targetSegmentIds', segmentIndex],
299
- `Product "${product.id}" references unknown customer segment "${segmentId}"`
300
- )
301
- }
302
- })
303
-
304
- // Offerings -> System cross-ref: deliveryFeatureId must resolve (when present)
305
- if (product.deliveryFeatureId !== undefined && !systemsById.has(product.deliveryFeatureId)) {
306
- addIssue(
307
- ctx,
308
- ['offerings', product.id, 'deliveryFeatureId'],
309
- `Product "${product.id}" references unknown delivery system "${product.deliveryFeatureId}"`
310
- )
311
- }
312
- })
313
-
314
- // Goals -> period-range validation: periodEnd must be strictly after periodStart
315
- Object.values(model.goals).forEach((objective) => {
316
- if (objective.periodEnd <= objective.periodStart) {
317
- addIssue(
318
- ctx,
319
- ['goals', objective.id, 'periodEnd'],
320
- `Goal "${objective.id}" has periodEnd "${objective.periodEnd}" which must be strictly after periodStart "${objective.periodStart}"`
321
- )
322
- }
323
- })
324
-
325
- const goalsById = new Map(Object.entries(model.goals))
326
- // Phase 4: knowledge is now a flat Record<id, OrgKnowledgeNode> — no .nodes array
327
- const knowledgeById = new Map(Object.entries(model.knowledge))
328
- const actionsById = new Map(Object.entries(model.actions))
329
- const entitiesById = new Map(Object.entries(model.entities))
330
- const policiesById = new Map(Object.entries(model.policies))
331
-
332
- sidebarSurfaces.forEach(({ id, node, path }) => {
333
- node.targets?.entities?.forEach((entityId, entityIndex) => {
334
- if (!entitiesById.has(entityId)) {
335
- addIssue(
336
- ctx,
337
- [...path, 'targets', 'entities', entityIndex],
338
- `Sidebar surface "${id}" references unknown entity "${entityId}"`
339
- )
340
570
  }
341
- })
342
571
 
343
- node.targets?.actions?.forEach((actionId, actionIndex) => {
344
- if (!actionsById.has(actionId)) {
345
- addIssue(
346
- ctx,
347
- [...path, 'targets', 'actions', actionIndex],
348
- `Sidebar surface "${id}" references unknown action "${actionId}"`
349
- )
350
- }
572
+ validateKnownOntologyReferences(ownerId, entry, [...path, key], seen)
351
573
  })
352
- })
353
-
354
- Object.values(model.entities).forEach((entity) => {
355
- if (!systemsById.has(entity.ownedBySystemId)) {
356
- addIssue(
357
- ctx,
358
- ['entities', entity.id, 'ownedBySystemId'],
359
- `Entity "${entity.id}" references unknown ownedBySystemId "${entity.ownedBySystemId}"`
360
- )
361
- }
362
-
363
- entity.links?.forEach((link, linkIndex) => {
364
- if (!entitiesById.has(link.toEntity)) {
365
- addIssue(
366
- ctx,
367
- ['entities', entity.id, 'links', linkIndex, 'toEntity'],
368
- `Entity "${entity.id}" links to unknown entity "${link.toEntity}"`
369
- )
370
- }
371
- })
372
- })
373
-
374
- // Roles -> reportsToId cross-ref: each reportsToId must resolve to another role in the same collection
375
- const rolesById = new Map(Object.entries(model.roles))
376
- Object.values(model.roles).forEach((role) => {
377
- if (role.reportsToId !== undefined && !rolesById.has(role.reportsToId)) {
378
- addIssue(
379
- ctx,
380
- ['roles', role.id, 'reportsToId'],
381
- `Role "${role.id}" references unknown reportsToId "${role.reportsToId}"`
382
- )
383
- }
384
- })
385
-
386
- Object.values(model.roles).forEach((role) => {
387
- const visited = new Set<string>()
388
- let currentReportsToId = role.reportsToId
389
-
390
- while (currentReportsToId !== undefined) {
391
- if (currentReportsToId === role.id || visited.has(currentReportsToId)) {
392
- addIssue(ctx, ['roles', role.id, 'reportsToId'], `Role "${role.id}" has a reportsToId cycle`)
393
- return
394
- }
395
-
396
- visited.add(currentReportsToId)
397
- currentReportsToId = rolesById.get(currentReportsToId)?.reportsToId
398
- }
399
- })
400
-
401
- Object.values(model.roles).forEach((role) => {
402
- role.responsibleFor?.forEach((systemId, systemIndex) => {
403
- if (!systemsById.has(systemId)) {
404
- addIssue(
405
- ctx,
406
- ['roles', role.id, 'responsibleFor', systemIndex],
407
- `Role "${role.id}" references unknown responsibleFor system "${systemId}"`
408
- )
409
- }
410
- })
411
- })
412
-
413
- allSystems.forEach(({ schemaPath, system }) => {
414
- if (system.responsibleRoleId !== undefined && !rolesById.has(system.responsibleRoleId)) {
415
- addIssue(
416
- ctx,
417
- [...schemaPath, 'responsibleRoleId'],
418
- `System "${system.id}" references unknown responsibleRoleId "${system.responsibleRoleId}"`
419
- )
420
- }
421
-
422
- system.governedByKnowledge?.forEach((nodeId, nodeIndex) => {
423
- if (!knowledgeById.has(nodeId)) {
424
- addIssue(
425
- ctx,
426
- [...schemaPath, 'governedByKnowledge', nodeIndex],
427
- `System "${system.id}" references unknown knowledge node "${nodeId}"`
428
- )
429
- }
430
- })
431
-
432
- system.drivesGoals?.forEach((goalId, goalIndex) => {
433
- if (!goalsById.has(goalId)) {
434
- addIssue(
435
- ctx,
436
- [...schemaPath, 'drivesGoals', goalIndex],
437
- `System "${system.id}" references unknown goal "${goalId}"`
438
- )
439
- }
440
- })
441
-
442
- system.actions?.forEach((actionRef, actionIndex) => {
443
- if (!actionsById.has(actionRef.actionId)) {
444
- addIssue(
445
- ctx,
446
- [...schemaPath, 'actions', actionIndex, 'actionId'],
447
- `System "${system.id}" references unknown action "${actionRef.actionId}"`
448
- )
449
- }
450
- })
451
-
452
- system.policies?.forEach((policyId, policyIndex) => {
453
- if (!policiesById.has(policyId)) {
454
- addIssue(
455
- ctx,
456
- [...schemaPath, 'policies', policyIndex],
457
- `System "${system.id}" references unknown policy "${policyId}"`
458
- )
459
- }
460
- })
461
- })
462
-
463
- Object.values(model.actions).forEach((action) => {
464
- action.affects?.forEach((entityId, entityIndex) => {
465
- if (!entitiesById.has(entityId)) {
466
- addIssue(
467
- ctx,
468
- ['actions', action.id, 'affects', entityIndex],
469
- `Action "${action.id}" affects unknown entity "${entityId}"`
470
- )
471
- }
472
- })
473
- })
474
-
475
- // Phase 4: sales / prospecting / projects compound-domain entity cross-ref checks removed.
476
- // Those entity bindings now live in system.content (Wave 2 canonicalOrganizationModel).
574
+ }
477
575
 
478
- const resourcesById = new Map(Object.entries(model.resources))
479
- sidebarSurfaces.forEach(({ id, node, path }) => {
480
- node.targets?.resources?.forEach((resourceId, resourceIndex) => {
481
- if (!resourcesById.has(resourceId)) {
482
- addIssue(
483
- ctx,
484
- [...path, 'targets', 'resources', resourceIndex],
485
- `Sidebar surface "${id}" references unknown resource "${resourceId}"`
486
- )
487
- }
488
- })
489
- })
490
- // Phase 4: stageIds previously sourced from model.prospecting.*Stages; stages now live in
491
- // system.content as schema:stage nodes. knowledge 'stage' target validation is kept permissive
492
- // (always false) — Wave 2 will wire a content-based stage lookup when canonical OM lands.
493
- const stageIds = new Set<string>()
494
- const actionIds = new Set(Object.keys(model.actions))
495
- const offeringsById = new Map(Object.entries(model.offerings))
576
+ for (const { id, record } of listResolvedOntologyRecords(ontologyCompilation.ontology)) {
577
+ validateKnownOntologyReferences(id, record, record.origin.path)
578
+ }
496
579
 
497
580
  Object.values(model.policies).forEach((policy) => {
498
- policy.appliesTo.systemIds.forEach((systemId, systemIndex) => {
499
- if (!systemsById.has(systemId)) {
500
- addIssue(
501
- ctx,
502
- ['policies', policy.id, 'appliesTo', 'systemIds', systemIndex],
503
- `Policy "${policy.id}" applies to unknown system "${systemId}"`
504
- )
505
- }
506
- })
507
-
508
- policy.appliesTo.actionIds.forEach((actionId, actionIndex) => {
509
- if (!actionsById.has(actionId)) {
510
- addIssue(
511
- ctx,
512
- ['policies', policy.id, 'appliesTo', 'actionIds', actionIndex],
513
- `Policy "${policy.id}" applies to unknown action "${actionId}"`
514
- )
515
- }
516
- })
517
-
518
- policy.actions.forEach((action, actionIndex) => {
519
- if (action.kind === 'invoke-action' && !actionsById.has(action.actionId)) {
520
- addIssue(
521
- ctx,
522
- ['policies', policy.id, 'actions', actionIndex, 'actionId'],
523
- `Policy "${policy.id}" invokes unknown action "${action.actionId}"`
524
- )
525
- }
526
- if (
527
- (action.kind === 'notify-role' || action.kind === 'require-approval') &&
528
- action.roleId !== undefined &&
529
- !rolesById.has(action.roleId)
530
- ) {
531
- addIssue(
532
- ctx,
533
- ['policies', policy.id, 'actions', actionIndex, 'roleId'],
534
- `Policy "${policy.id}" references unknown role "${action.roleId}"`
535
- )
536
- }
537
- })
538
-
539
- if (policy.trigger.kind === 'action-invocation' && !actionsById.has(policy.trigger.actionId)) {
540
- addIssue(
541
- ctx,
542
- ['policies', policy.id, 'trigger', 'actionId'],
543
- `Policy "${policy.id}" references unknown trigger action "${policy.trigger.actionId}"`
544
- )
545
- }
546
- })
547
-
548
- function knowledgeTargetExists(kind: string, id: string): boolean {
549
- if (kind === 'system') return systemsById.has(id)
550
- if (kind === 'resource') return resourcesById.has(id)
551
- if (kind === 'knowledge') return knowledgeById.has(id)
552
- if (kind === 'stage') return stageIds.has(id)
553
- if (kind === 'action') return actionIds.has(id)
554
- if (kind === 'role') return rolesById.has(id)
581
+ policy.appliesTo.systemIds.forEach((systemId, systemIndex) => {
582
+ if (!systemsById.has(systemId)) {
583
+ addIssue(
584
+ ctx,
585
+ ['policies', policy.id, 'appliesTo', 'systemIds', systemIndex],
586
+ `Policy "${policy.id}" applies to unknown system "${systemId}"`
587
+ )
588
+ }
589
+ })
590
+
591
+ policy.appliesTo.actionIds.forEach((actionId, actionIndex) => {
592
+ if (!actionsById.has(actionId)) {
593
+ addIssue(
594
+ ctx,
595
+ ['policies', policy.id, 'appliesTo', 'actionIds', actionIndex],
596
+ `Policy "${policy.id}" applies to unknown action "${actionId}"`
597
+ )
598
+ }
599
+ })
600
+
601
+ policy.actions.forEach((action, actionIndex) => {
602
+ if (action.kind === 'invoke-action' && !actionsById.has(action.actionId)) {
603
+ addIssue(
604
+ ctx,
605
+ ['policies', policy.id, 'actions', actionIndex, 'actionId'],
606
+ `Policy "${policy.id}" invokes unknown action "${action.actionId}"`
607
+ )
608
+ }
609
+ if (
610
+ (action.kind === 'notify-role' || action.kind === 'require-approval') &&
611
+ action.roleId !== undefined &&
612
+ !rolesById.has(action.roleId)
613
+ ) {
614
+ addIssue(
615
+ ctx,
616
+ ['policies', policy.id, 'actions', actionIndex, 'roleId'],
617
+ `Policy "${policy.id}" references unknown role "${action.roleId}"`
618
+ )
619
+ }
620
+ })
621
+
622
+ if (policy.trigger.kind === 'action-invocation' && !actionsById.has(policy.trigger.actionId)) {
623
+ addIssue(
624
+ ctx,
625
+ ['policies', policy.id, 'trigger', 'actionId'],
626
+ `Policy "${policy.id}" references unknown trigger action "${policy.trigger.actionId}"`
627
+ )
628
+ }
629
+ })
630
+
631
+ function knowledgeTargetExists(kind: string, id: string): boolean {
632
+ if (kind === 'system') return systemsById.has(id)
633
+ if (kind === 'resource') return resourcesById.has(id)
634
+ if (kind === 'knowledge') return knowledgeById.has(id)
635
+ if (kind === 'stage') return stageIds.has(id)
636
+ if (kind === 'action') return actionIds.has(id)
637
+ if (kind === 'role') return rolesById.has(id)
555
638
  if (kind === 'goal') return goalsById.has(id)
556
639
  if (kind === 'customer-segment') return segmentsById.has(id)
557
640
  if (kind === 'offering') return offeringsById.has(id)
641
+ if (kind === 'ontology') return ontologyIds.has(id)
558
642
  return false
559
643
  }
560
-
561
- // Phase 4: model.knowledge is now Record<id, OrgKnowledgeNode> — iterate Object.values
562
- Object.entries(model.knowledge).forEach(([nodeId, node]) => {
563
- node.links.forEach((link, linkIndex) => {
564
- if (!knowledgeTargetExists(link.target.kind, link.target.id)) {
565
- addIssue(
566
- ctx,
567
- ['knowledge', nodeId, 'links', linkIndex, 'target'],
568
- `Knowledge node "${node.id}" references unknown ${link.target.kind} target "${link.target.id}"`
569
- )
570
- }
571
-
572
- if (!isKnowledgeKindCompatibleWithTarget(node.kind, link.target.kind)) {
573
- addIssue(
574
- ctx,
575
- ['knowledge', nodeId, 'links', linkIndex, 'target', 'kind'],
576
- `Knowledge node "${node.id}" kind "${node.kind}" cannot govern ${link.target.kind} targets`
577
- )
578
- }
579
-
580
- // `governedByKnowledge` is validated one-way on target nodes above. Knowledge
581
- // links may be authored first and remain valid as forward references.
582
- })
583
- })
584
-
644
+
645
+ // Phase 4: model.knowledge is now Record<id, OrgKnowledgeNode> — iterate Object.values
646
+ Object.entries(model.knowledge).forEach(([nodeId, node]) => {
647
+ node.links.forEach((link, linkIndex) => {
648
+ if (!knowledgeTargetExists(link.target.kind, link.target.id)) {
649
+ addIssue(
650
+ ctx,
651
+ ['knowledge', nodeId, 'links', linkIndex, 'target'],
652
+ `Knowledge node "${node.id}" references unknown ${link.target.kind} target "${link.target.id}"`
653
+ )
654
+ }
655
+
656
+ if (!isKnowledgeKindCompatibleWithTarget(node.kind, link.target.kind)) {
657
+ addIssue(
658
+ ctx,
659
+ ['knowledge', nodeId, 'links', linkIndex, 'target', 'kind'],
660
+ `Knowledge node "${node.id}" kind "${node.kind}" cannot govern ${link.target.kind} targets`
661
+ )
662
+ }
663
+
664
+ // `governedByKnowledge` is validated one-way on target nodes above. Knowledge
665
+ // links may be authored first and remain valid as forward references.
666
+ })
667
+ })
668
+
585
669
  Object.values(model.resources).forEach((resource) => {
586
- if (!systemsById.has(resource.systemPath)) {
587
- addIssue(
588
- ctx,
589
- ['resources', resource.id, 'systemPath'],
590
- `Resource "${resource.id}" references unknown system path "${resource.systemPath}"`
591
- )
592
- }
593
-
594
- if (resource.ownerRoleId !== undefined && !rolesById.has(resource.ownerRoleId)) {
595
- addIssue(
596
- ctx,
597
- ['resources', resource.id, 'ownerRoleId'],
598
- `Resource "${resource.id}" references unknown ownerRoleId "${resource.ownerRoleId}"`
599
- )
600
- }
601
-
602
- if (resource.kind === 'agent' && resource.actsAsRoleId !== undefined && !rolesById.has(resource.actsAsRoleId)) {
603
- addIssue(
604
- ctx,
605
- ['resources', resource.id, 'actsAsRoleId'],
606
- `Agent resource "${resource.id}" references unknown actsAsRoleId "${resource.actsAsRoleId}"`
607
- )
670
+ if (!systemsById.has(resource.systemPath)) {
671
+ addIssue(
672
+ ctx,
673
+ ['resources', resource.id, 'systemPath'],
674
+ `Resource "${resource.id}" references unknown system path "${resource.systemPath}"`
675
+ )
676
+ }
677
+
678
+ if (resource.ownerRoleId !== undefined && !rolesById.has(resource.ownerRoleId)) {
679
+ addIssue(
680
+ ctx,
681
+ ['resources', resource.id, 'ownerRoleId'],
682
+ `Resource "${resource.id}" references unknown ownerRoleId "${resource.ownerRoleId}"`
683
+ )
684
+ }
685
+
686
+ if (resource.kind === 'agent' && resource.actsAsRoleId !== undefined && !rolesById.has(resource.actsAsRoleId)) {
687
+ addIssue(
688
+ ctx,
689
+ ['resources', resource.id, 'actsAsRoleId'],
690
+ `Agent resource "${resource.id}" references unknown actsAsRoleId "${resource.actsAsRoleId}"`
691
+ )
608
692
  }
609
693
  })
610
694
 
611
- Object.values(model.roles).forEach((role) => {
612
- if (role.heldBy === undefined) return
613
-
614
- asRoleHolderArray(role.heldBy).forEach((holder, holderIndex) => {
615
- if (holder.kind !== 'agent') return
616
-
617
- const resource = resourcesById.get(holder.agentId)
618
- if (resource === undefined) {
619
- addIssue(
620
- ctx,
621
- ['roles', role.id, 'heldBy', Array.isArray(role.heldBy) ? holderIndex : 'agentId'],
622
- `Role "${role.id}" references unknown agent holder resource "${holder.agentId}"`
623
- )
624
- return
625
- }
626
-
627
- if (resource.kind !== 'agent') {
695
+ function validateResourceOntologyBinding(
696
+ resourceId: string,
697
+ bindingKey: 'implements' | 'reads' | 'writes' | 'usesCatalogs' | 'emits',
698
+ expectedKind: OntologyKind,
699
+ ids: string[] | undefined
700
+ ): void {
701
+ ids?.forEach((ontologyId, ontologyIndex) => {
702
+ if (ontologyIndexByKind[expectedKind][ontologyId] === undefined) {
628
703
  addIssue(
629
704
  ctx,
630
- ['roles', role.id, 'heldBy', Array.isArray(role.heldBy) ? holderIndex : 'agentId'],
631
- `Role "${role.id}" agent holder "${holder.agentId}" must reference an agent resource`
705
+ ['resources', resourceId, 'ontology', bindingKey, ontologyIndex],
706
+ `Resource "${resourceId}" ontology binding "${bindingKey}" references unknown ${expectedKind} ontology ID "${ontologyId}"`
632
707
  )
633
708
  }
634
709
  })
635
- })
710
+ }
636
711
 
637
- // Phase 4: model.knowledge is now Record<id, OrgKnowledgeNode>
638
- Object.entries(model.knowledge).forEach(([nodeId, node]) => {
639
- node.ownerIds.forEach((roleId, ownerIndex) => {
640
- if (!rolesById.has(roleId)) {
641
- addIssue(
642
- ctx,
643
- ['knowledge', nodeId, 'ownerIds', ownerIndex],
644
- `Knowledge node "${node.id}" references unknown owner role "${roleId}"`
645
- )
646
- }
647
- })
712
+ Object.values(model.resources).forEach((resource) => {
713
+ const binding = resource.ontology
714
+ if (binding === undefined) return
715
+
716
+ validateResourceOntologyBinding(resource.id, 'implements', 'action', binding.implements)
717
+ validateResourceOntologyBinding(resource.id, 'reads', 'object', binding.reads)
718
+ validateResourceOntologyBinding(resource.id, 'writes', 'object', binding.writes)
719
+ validateResourceOntologyBinding(resource.id, 'usesCatalogs', 'catalog', binding.usesCatalogs)
720
+ validateResourceOntologyBinding(resource.id, 'emits', 'event', binding.emits)
648
721
  })
649
-
650
- // ---------------------------------------------------------------------------
651
- // B3, B4, B5, L19 — ContentNode refines (Phase 3, Wave 1A)
652
- // ---------------------------------------------------------------------------
653
- //
654
- // These refines apply recursively to every system in the model tree
655
- // (top-level systems + nested subsystems at any depth).
656
- //
657
- // B3 Cycle detection: parentContentId chain must not form a cycle.
658
- // B4 — Same-system-only: parentContentId must resolve within the same content map.
659
- // B5 — Payload validation: registered (kind, type) pairs validate data against
660
- // the registered payloadSchema; unregistered pairs pass through (per D2).
661
- // L19 Same-meta-kind parent: when both child and parent are registered, they
662
- // must share the same `kind` (meta-category).
663
-
722
+
723
+ Object.values(model.roles).forEach((role) => {
724
+ if (role.heldBy === undefined) return
725
+
726
+ asRoleHolderArray(role.heldBy).forEach((holder, holderIndex) => {
727
+ if (holder.kind !== 'agent') return
728
+
729
+ const resource = resourcesById.get(holder.agentId)
730
+ if (resource === undefined) {
731
+ addIssue(
732
+ ctx,
733
+ ['roles', role.id, 'heldBy', Array.isArray(role.heldBy) ? holderIndex : 'agentId'],
734
+ `Role "${role.id}" references unknown agent holder resource "${holder.agentId}"`
735
+ )
736
+ return
737
+ }
738
+
739
+ if (resource.kind !== 'agent') {
740
+ addIssue(
741
+ ctx,
742
+ ['roles', role.id, 'heldBy', Array.isArray(role.heldBy) ? holderIndex : 'agentId'],
743
+ `Role "${role.id}" agent holder "${holder.agentId}" must reference an agent resource`
744
+ )
745
+ }
746
+ })
747
+ })
748
+
749
+ // Phase 4: model.knowledge is now Record<id, OrgKnowledgeNode>
750
+ Object.entries(model.knowledge).forEach(([nodeId, node]) => {
751
+ node.ownerIds.forEach((roleId, ownerIndex) => {
752
+ if (!rolesById.has(roleId)) {
753
+ addIssue(
754
+ ctx,
755
+ ['knowledge', nodeId, 'ownerIds', ownerIndex],
756
+ `Knowledge node "${node.id}" references unknown owner role "${roleId}"`
757
+ )
758
+ }
759
+ })
760
+ })
761
+
762
+ // ---------------------------------------------------------------------------
763
+ // B3, B4, B5, L19 — ContentNode refines (Phase 3, Wave 1A)
764
+ // ---------------------------------------------------------------------------
765
+ //
766
+ // These refines apply recursively to every system in the model tree
767
+ // (top-level systems + nested subsystems at any depth).
768
+ //
769
+ // B3 — Cycle detection: parentContentId chain must not form a cycle.
770
+ // B4 — Same-system-only: parentContentId must resolve within the same content map.
771
+ // B5 — Payload validation: registered (kind, type) pairs validate data against
772
+ // the registered payloadSchema; unregistered pairs pass through (per D2).
773
+ // L19 — Same-meta-kind parent: when both child and parent are registered, they
774
+ // must share the same `kind` (meta-category).
775
+
664
776
  type SystemLike = {
665
777
  id?: string
666
778
  content?: Record<string, { kind: string; type: string; parentContentId?: string; data?: Record<string, unknown> }>
779
+ systems?: Record<string, SystemLike>
667
780
  subsystems?: Record<string, SystemLike>
668
781
  }
669
782
 
670
783
  function validateSystemContent(system: SystemLike, systemPath: Array<string | number>): void {
784
+ const childSystems = system.systems ?? system.subsystems
785
+ const childKey = system.systems !== undefined ? 'systems' : 'subsystems'
671
786
  const content = system.content
672
787
  if (content === undefined || Object.keys(content).length === 0) {
673
- // Recurse into subsystems even when own content is absent.
674
- if (system.subsystems !== undefined) {
675
- Object.entries(system.subsystems).forEach(([childKey, child]) => {
676
- validateSystemContent(child, [...systemPath, 'subsystems', childKey])
788
+ // Recurse into child systems even when own content is absent.
789
+ if (childSystems !== undefined) {
790
+ Object.entries(childSystems).forEach(([childLocalId, child]) => {
791
+ validateSystemContent(child, [...systemPath, childKey, childLocalId])
677
792
  })
678
793
  }
679
794
  return
680
- }
681
-
682
- // B4 — verify every parentContentId resolves within this content map.
683
- Object.entries(content).forEach(([localId, node]) => {
684
- if (node.parentContentId !== undefined && !(node.parentContentId in content)) {
685
- addIssue(
686
- ctx,
687
- [...systemPath, 'content', localId, 'parentContentId'],
688
- `Content node "${localId}" parentContentId "${node.parentContentId}" does not resolve within the same system`
689
- )
690
- }
691
- })
692
-
693
- // B3 — cycle detection on parentContentId chains within this content map.
694
- Object.entries(content).forEach(([localId, node]) => {
695
- const visited = new Set<string>()
696
- let currentId: string | undefined = node.parentContentId
697
-
698
- while (currentId !== undefined) {
699
- if (currentId === localId || visited.has(currentId)) {
700
- addIssue(
701
- ctx,
702
- [...systemPath, 'content', localId, 'parentContentId'],
703
- `Content node "${localId}" has a parentContentId cycle`
704
- )
705
- break
706
- }
707
- visited.add(currentId)
708
- currentId = content[currentId]?.parentContentId
709
- }
710
- })
711
-
712
- // B5 + L19 — per-node payload validation and same-meta-kind parent constraint.
713
- Object.entries(content).forEach(([localId, node]) => {
714
- const childDef = lookupContentType(node.kind, node.type)
715
-
716
- // B5 — validate data against registered payloadSchema when pair is known.
717
- if (childDef !== undefined && node.data !== undefined) {
718
- const result = childDef.payloadSchema.safeParse(node.data)
719
- if (!result.success) {
720
- addIssue(
721
- ctx,
722
- [...systemPath, 'content', localId, 'data'],
723
- `Content node "${localId}" (${node.kind}:${node.type}) data failed payload validation: ${result.error.message}`
724
- )
725
- }
726
- }
727
-
728
- // L19 — when both child and parent are registered, they must share the same kind.
729
- if (node.parentContentId !== undefined && childDef !== undefined) {
730
- const parentNode = content[node.parentContentId]
731
- if (parentNode !== undefined) {
732
- const parentDef = lookupContentType(parentNode.kind, parentNode.type)
733
- if (parentDef !== undefined && childDef.kind !== parentDef.kind) {
734
- addIssue(
735
- ctx,
736
- [...systemPath, 'content', localId, 'parentContentId'],
737
- `Content node "${localId}" kind "${childDef.kind}" cannot parent under "${node.parentContentId}" kind "${parentDef.kind}": parentContentId must be same-meta-kind (per L19)`
738
- )
739
- }
740
- }
741
- }
742
- })
743
-
744
- // Recurse into subsystems.
745
- if (system.subsystems !== undefined) {
746
- Object.entries(system.subsystems).forEach(([childKey, child]) => {
747
- validateSystemContent(child, [...systemPath, 'subsystems', childKey])
795
+ }
796
+
797
+ // B4 — verify every parentContentId resolves within this content map.
798
+ Object.entries(content).forEach(([localId, node]) => {
799
+ if (node.parentContentId !== undefined && !(node.parentContentId in content)) {
800
+ addIssue(
801
+ ctx,
802
+ [...systemPath, 'content', localId, 'parentContentId'],
803
+ `Content node "${localId}" parentContentId "${node.parentContentId}" does not resolve within the same system`
804
+ )
805
+ }
806
+ })
807
+
808
+ // B3 — cycle detection on parentContentId chains within this content map.
809
+ Object.entries(content).forEach(([localId, node]) => {
810
+ const visited = new Set<string>()
811
+ let currentId: string | undefined = node.parentContentId
812
+
813
+ while (currentId !== undefined) {
814
+ if (currentId === localId || visited.has(currentId)) {
815
+ addIssue(
816
+ ctx,
817
+ [...systemPath, 'content', localId, 'parentContentId'],
818
+ `Content node "${localId}" has a parentContentId cycle`
819
+ )
820
+ break
821
+ }
822
+ visited.add(currentId)
823
+ currentId = content[currentId]?.parentContentId
824
+ }
825
+ })
826
+
827
+ // B5 + L19 — per-node payload validation and same-meta-kind parent constraint.
828
+ Object.entries(content).forEach(([localId, node]) => {
829
+ const childDef = lookupContentType(node.kind, node.type)
830
+
831
+ // B5 — validate data against registered payloadSchema when pair is known.
832
+ if (childDef !== undefined && node.data !== undefined) {
833
+ const result = childDef.payloadSchema.safeParse(node.data)
834
+ if (!result.success) {
835
+ addIssue(
836
+ ctx,
837
+ [...systemPath, 'content', localId, 'data'],
838
+ `Content node "${localId}" (${node.kind}:${node.type}) data failed payload validation: ${result.error.message}`
839
+ )
840
+ }
841
+ }
842
+
843
+ // L19 — when both child and parent are registered, they must share the same kind.
844
+ if (node.parentContentId !== undefined && childDef !== undefined) {
845
+ const parentNode = content[node.parentContentId]
846
+ if (parentNode !== undefined) {
847
+ const parentDef = lookupContentType(parentNode.kind, parentNode.type)
848
+ if (parentDef !== undefined && childDef.kind !== parentDef.kind) {
849
+ addIssue(
850
+ ctx,
851
+ [...systemPath, 'content', localId, 'parentContentId'],
852
+ `Content node "${localId}" kind "${childDef.kind}" cannot parent under "${node.parentContentId}" kind "${parentDef.kind}": parentContentId must be same-meta-kind (per L19)`
853
+ )
854
+ }
855
+ }
856
+ }
857
+ })
858
+
859
+ // Recurse into child systems.
860
+ if (childSystems !== undefined) {
861
+ Object.entries(childSystems).forEach(([childLocalId, child]) => {
862
+ validateSystemContent(child, [...systemPath, childKey, childLocalId])
748
863
  })
749
864
  }
750
865
  }
@@ -752,4 +867,8 @@ export const OrganizationModelSchema = OrganizationModelSchemaBase.superRefine((
752
867
  Object.entries(model.systems).forEach(([systemKey, system]) => {
753
868
  validateSystemContent(system as SystemLike, ['systems', systemKey])
754
869
  })
870
+
871
+ for (const diagnostic of ontologyCompilation.diagnostics) {
872
+ addIssue(ctx, diagnostic.path, diagnostic.message)
873
+ }
755
874
  })