@elevasis/ui 2.40.1 → 2.41.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 (92) hide show
  1. package/dist/api/index.js +4 -6
  2. package/dist/app/index.css +384 -0
  3. package/dist/app/index.d.ts +108 -0
  4. package/dist/app/index.js +17 -27
  5. package/dist/auth/index.css +659 -0
  6. package/dist/auth/index.js +19 -6
  7. package/dist/charts/index.css +533 -0
  8. package/dist/charts/index.js +18 -15
  9. package/dist/{chunk-RXH4D6TY.js → chunk-5M4HSHQ5.js} +631 -2
  10. package/dist/{chunk-TE4P6OSJ.js → chunk-7FJI76OH.js} +1 -1
  11. package/dist/chunk-GMXGDO3I.js +244 -0
  12. package/dist/{chunk-CXY7FMUM.js → chunk-GUKY77FJ.js} +50 -4
  13. package/dist/{chunk-5JYKCULK.js → chunk-NZ2F5RQ4.js} +44 -2
  14. package/dist/{chunk-WF7CONXF.js → chunk-OJJK27GC.js} +658 -6
  15. package/dist/{chunk-RX6RSKWC.js → chunk-QDXTIQT4.js} +29255 -18312
  16. package/dist/{chunk-73EWE2EW.js → chunk-V5HWC5EW.js} +1 -1
  17. package/dist/components/chat/index.js +1 -2
  18. package/dist/components/index.css +149 -149
  19. package/dist/components/index.js +13 -37
  20. package/dist/components/navigation/index.css +659 -0
  21. package/dist/components/navigation/index.js +25 -4
  22. package/dist/features/auth/index.js +14 -38
  23. package/dist/features/clients/index.css +149 -149
  24. package/dist/features/clients/index.js +13 -37
  25. package/dist/features/crm/index.js +13 -37
  26. package/dist/features/dashboard/index.js +13 -37
  27. package/dist/features/delivery/index.js +13 -37
  28. package/dist/features/knowledge/index.css +659 -0
  29. package/dist/features/knowledge/index.js +25 -248
  30. package/dist/features/lead-gen/index.d.ts +81 -0
  31. package/dist/features/lead-gen/index.js +13 -37
  32. package/dist/features/monitoring/index.js +13 -37
  33. package/dist/features/monitoring/requests/index.d.ts +69 -7
  34. package/dist/features/monitoring/requests/index.js +32 -41
  35. package/dist/features/operations/index.d.ts +79 -0
  36. package/dist/features/operations/index.js +13 -37
  37. package/dist/features/seo/index.js +1 -4
  38. package/dist/features/settings/index.js +13 -37
  39. package/dist/hooks/access/index.css +659 -0
  40. package/dist/hooks/access/index.js +19 -5
  41. package/dist/hooks/delivery/index.js +13 -37
  42. package/dist/hooks/index.d.ts +18 -6
  43. package/dist/hooks/index.js +13 -37
  44. package/dist/hooks/published.d.ts +18 -6
  45. package/dist/hooks/published.js +13 -37
  46. package/dist/index.d.ts +151 -7
  47. package/dist/index.js +14 -38
  48. package/dist/initialization/index.js +1 -1
  49. package/dist/knowledge/index.css +659 -0
  50. package/dist/knowledge/index.d.ts +81 -0
  51. package/dist/knowledge/index.js +25 -15
  52. package/dist/layout/index.css +659 -0
  53. package/dist/layout/index.d.ts +18 -2
  54. package/dist/layout/index.js +24 -7
  55. package/dist/organization/index.js +13 -37
  56. package/dist/provider/index.css +384 -0
  57. package/dist/provider/index.d.ts +120 -1
  58. package/dist/provider/index.js +18 -22
  59. package/dist/provider/published.css +533 -0
  60. package/dist/provider/published.d.ts +121 -2
  61. package/dist/provider/published.js +18 -17
  62. package/dist/test-utils/index.js +4 -6
  63. package/dist/theme/index.js +2 -5
  64. package/dist/theme/presets/index.js +1 -2
  65. package/dist/utils/index.js +1 -3
  66. package/package.json +3 -3
  67. package/dist/chunk-3KMDHCAR.js +0 -52
  68. package/dist/chunk-4DRI3G36.js +0 -1016
  69. package/dist/chunk-5EYJ2GIN.js +0 -122
  70. package/dist/chunk-66U7JOWV.js +0 -425
  71. package/dist/chunk-6D4LCJ52.js +0 -10
  72. package/dist/chunk-6EV47QQW.js +0 -340
  73. package/dist/chunk-6ROXVZ3L.js +0 -9
  74. package/dist/chunk-7MTWRSUZ.js +0 -357
  75. package/dist/chunk-7PHY5ONQ.js +0 -85
  76. package/dist/chunk-B2DZLPDL.js +0 -39
  77. package/dist/chunk-CLDCYJQT.js +0 -1
  78. package/dist/chunk-CTJBPF3Z.js +0 -734
  79. package/dist/chunk-DT3QYZVU.js +0 -23
  80. package/dist/chunk-IIMU5YAJ.js +0 -53
  81. package/dist/chunk-IUQAP4IO.js +0 -2131
  82. package/dist/chunk-J3FLIZY4.js +0 -423
  83. package/dist/chunk-K7GKKETO.js +0 -3157
  84. package/dist/chunk-L7GXUSCV.js +0 -215
  85. package/dist/chunk-LJDYY3XB.js +0 -133
  86. package/dist/chunk-NYBEU5TE.js +0 -118
  87. package/dist/chunk-RH5VWWSC.js +0 -624
  88. package/dist/chunk-SJNIOGVX.js +0 -112
  89. package/dist/chunk-TYRUKGGD.js +0 -46
  90. package/dist/chunk-WLOQ4IBG.js +0 -654
  91. package/dist/chunk-X4WBGKJQ.js +0 -138
  92. package/dist/chunk-X7D6SUKR.js +0 -1234
@@ -1,3157 +0,0 @@
1
- import { OntologyScopeSchema, OntologyIdSchema, DEFAULT_ONTOLOGY_SCOPE, compileOrganizationOntology, listResolvedOntologyRecords, listAllSystems, defineDomainRecord, ontologyGraphNodeId, parseOntologyId, getAllProspectingStages, getAllPipelines, getAllProjectStatuses, getLeadGenStageCatalog, getAllBuildTemplates } from './chunk-RH5VWWSC.js';
2
- import { IconMail, IconSend, IconFileText, IconClock, IconArrowUp, IconMessageCircle, IconRocket, IconEye, IconEdit, IconAlertTriangle, IconRefresh, IconX, IconCheck, IconShieldLock, IconActivity, IconTopologyStar3, IconApps, IconBriefcase, IconBuilding, IconBolt, IconSearch, IconChartBar, IconUsers, IconInfoCircle, IconDatabase, IconGitBranch, IconDashboard, IconBuildingStore, IconUser, IconPlug, IconBrain, IconTargetArrow, IconBook, IconLayoutGrid, IconArchive, IconSettings, IconTool, IconCalendar } from '@tabler/icons-react';
3
- import { jsx } from 'react/jsx-runtime';
4
- import { z } from 'zod';
5
-
6
- var DEFAULT_SEMANTIC_ICON_REGISTRY = {
7
- // Navigation / app areas
8
- dashboard: IconDashboard,
9
- calendar: IconCalendar,
10
- sales: IconChartBar,
11
- crm: IconBuildingStore,
12
- "lead-gen": IconTargetArrow,
13
- projects: IconBriefcase,
14
- clients: IconUsers,
15
- operations: IconTool,
16
- monitoring: IconChartBar,
17
- knowledge: IconBrain,
18
- settings: IconSettings,
19
- admin: IconShieldLock,
20
- archive: IconArchive,
21
- business: IconBriefcase,
22
- finance: IconChartBar,
23
- platform: IconLayoutGrid,
24
- seo: IconSearch,
25
- // Knowledge kinds
26
- playbook: IconBook,
27
- strategy: IconTargetArrow,
28
- reference: IconFileText,
29
- // Resource kinds
30
- agent: IconBrain,
31
- workflow: IconGitBranch,
32
- integration: IconPlug,
33
- database: IconDatabase,
34
- user: IconUser,
35
- team: IconUsers,
36
- // Integration specifics
37
- gmail: IconMail,
38
- "google-sheets": IconDatabase,
39
- attio: IconBuildingStore,
40
- // Surface / UI views
41
- overview: IconDashboard,
42
- "command-view": IconTopologyStar3,
43
- "command-queue": IconSend,
44
- pipeline: IconGitBranch,
45
- lists: IconFileText,
46
- resources: IconDatabase,
47
- // Actions
48
- approve: IconCheck,
49
- reject: IconX,
50
- retry: IconRefresh,
51
- edit: IconEdit,
52
- view: IconEye,
53
- launch: IconRocket,
54
- message: IconMessageCircle,
55
- escalate: IconAlertTriangle,
56
- promote: IconArrowUp,
57
- submit: IconSend,
58
- email: IconMail,
59
- // Status
60
- success: IconCheck,
61
- error: IconX,
62
- warning: IconAlertTriangle,
63
- info: IconInfoCircle,
64
- pending: IconClock,
65
- // OM / UI group icons
66
- bolt: IconBolt,
67
- building: IconBuilding,
68
- briefcase: IconBriefcase,
69
- apps: IconApps,
70
- graph: IconTopologyStar3,
71
- shield: IconShieldLock,
72
- users: IconUsers,
73
- "chart-bar": IconChartBar,
74
- search: IconSearch,
75
- // UI-only om.* group tokens (not in the core enum — kept for registry lookup
76
- // by components that reference them directly via extendSemanticIconRegistry)
77
- "om.quick-access": IconBolt,
78
- "om.profile": IconBuilding,
79
- "om.business-model": IconBriefcase,
80
- "om.systems": IconApps,
81
- "om.graph": IconTopologyStar3,
82
- "om.governance-wiring": IconShieldLock,
83
- // Graph node-kind fallback tokens (used internally by knowledge-tree helpers)
84
- "entity.record": IconActivity,
85
- "event.lifecycle": IconActivity,
86
- "policy.governance": IconShieldLock,
87
- // Compatibility aliases for existing command queue payloads.
88
- IconCheck,
89
- IconX,
90
- IconRefresh,
91
- IconAlertTriangle,
92
- IconEdit,
93
- IconEye,
94
- IconRocket,
95
- IconMessageCircle,
96
- IconArrowUp,
97
- IconClock,
98
- IconFileText,
99
- IconSend,
100
- IconMail
101
- };
102
- var semanticIconRegistry = { ...DEFAULT_SEMANTIC_ICON_REGISTRY };
103
- function extendSemanticIconRegistry(overrides) {
104
- semanticIconRegistry = { ...semanticIconRegistry, ...overrides };
105
- }
106
- function getSemanticIconComponent(token, fallbackToken) {
107
- const icon = resolveSemanticIconComponent(token);
108
- if (icon) return icon;
109
- if (fallbackToken && semanticIconRegistry[fallbackToken]) return semanticIconRegistry[fallbackToken];
110
- return IconInfoCircle;
111
- }
112
- function resolveSemanticIconComponent(token) {
113
- if (!token) return null;
114
- return semanticIconRegistry[token] ?? null;
115
- }
116
- function SemanticIcon({
117
- token,
118
- fallbackToken,
119
- size = 16,
120
- stroke = 1.8,
121
- className,
122
- style,
123
- "aria-hidden": ariaHidden = true
124
- }) {
125
- const Icon = getSemanticIconComponent(token, fallbackToken);
126
- return /* @__PURE__ */ jsx(
127
- "span",
128
- {
129
- className,
130
- "aria-hidden": ariaHidden,
131
- style: {
132
- display: "inline-flex",
133
- alignItems: "center",
134
- justifyContent: "center",
135
- width: size,
136
- height: size,
137
- minWidth: size,
138
- color: "currentColor",
139
- flexShrink: 0,
140
- ...style
141
- },
142
- children: /* @__PURE__ */ jsx(Icon, { size, stroke })
143
- }
144
- );
145
- }
146
- var ORGANIZATION_MODEL_ICON_TOKENS = [
147
- // Navigation / app areas
148
- "dashboard",
149
- "calendar",
150
- "sales",
151
- "crm",
152
- "lead-gen",
153
- "projects",
154
- "clients",
155
- "operations",
156
- "monitoring",
157
- "knowledge",
158
- "settings",
159
- "admin",
160
- "archive",
161
- "business",
162
- "finance",
163
- "platform",
164
- "seo",
165
- // Knowledge kinds
166
- "playbook",
167
- "strategy",
168
- "reference",
169
- // Resource kinds
170
- "agent",
171
- "workflow",
172
- "integration",
173
- "database",
174
- "user",
175
- "team",
176
- // Integration specifics
177
- "gmail",
178
- "google-sheets",
179
- "attio",
180
- // Surface / UI views
181
- "overview",
182
- "command-view",
183
- "command-queue",
184
- "pipeline",
185
- "lists",
186
- "resources",
187
- // Actions
188
- "approve",
189
- "reject",
190
- "retry",
191
- "edit",
192
- "view",
193
- "launch",
194
- "message",
195
- "escalate",
196
- "promote",
197
- "submit",
198
- "email",
199
- // Status
200
- "success",
201
- "error",
202
- "warning",
203
- "info",
204
- "pending",
205
- // OM / UI group icons
206
- "bolt",
207
- "building",
208
- "briefcase",
209
- "apps",
210
- "graph",
211
- "shield",
212
- "users",
213
- "chart-bar",
214
- "search"
215
- ];
216
- var CustomIconTokenSchema = z.string().trim().max(80).regex(
217
- /^custom\.[a-z0-9]+(?:[-._][a-z0-9]+)*$/,
218
- 'Custom icon tokens must start with "custom." followed by lowercase alphanumeric segments'
219
- );
220
- var OrganizationModelBuiltinIconTokenSchema = z.enum(ORGANIZATION_MODEL_ICON_TOKENS);
221
- var OrganizationModelIconTokenSchema = z.union([
222
- OrganizationModelBuiltinIconTokenSchema,
223
- CustomIconTokenSchema
224
- ]);
225
-
226
- // ../core/src/organization-model/domains/shared.ts
227
- var ModelIdSchema = z.string().trim().min(1).max(100).regex(/^[a-z0-9]+(?:[-._][a-z0-9]+)*$/, "IDs must be lowercase and use -, _, or . separators");
228
- var LabelSchema = z.string().trim().min(1).max(120);
229
- var DescriptionSchema = z.string().trim().min(1).max(2e3);
230
- var ColorTokenSchema = z.string().trim().min(1).max(50);
231
- var IconNameSchema = OrganizationModelIconTokenSchema;
232
- var PathSchema = z.string().trim().startsWith("/").max(300);
233
- var ReferenceIdsSchema = z.array(ModelIdSchema).default([]);
234
- var DisplayMetadataSchema = z.object({
235
- label: LabelSchema,
236
- description: DescriptionSchema.optional(),
237
- color: ColorTokenSchema.optional(),
238
- icon: IconNameSchema.optional()
239
- });
240
- var TechStackEntrySchema = z.object({
241
- /** Name of the external platform (e.g. "HubSpot", "Stripe", "Notion"). */
242
- platform: z.string().trim().min(1).max(200),
243
- /** Free-form description of what this integration is used for. */
244
- purpose: z.string().trim().min(1).max(500),
245
- /**
246
- * Health of the credential backing this integration.
247
- * - configured: credential present and valid
248
- * - pending: not yet set up
249
- * - expired: credential existed but has lapsed
250
- * - missing: expected but not present
251
- */
252
- credentialStatus: z.enum(["configured", "pending", "expired", "missing"]),
253
- /**
254
- * Whether this integration is the primary system of record for its domain
255
- * (e.g. HubSpot is SoR for contacts). Defaults to false.
256
- */
257
- isSystemOfRecord: z.boolean().default(false)
258
- });
259
- DisplayMetadataSchema.extend({
260
- id: ModelIdSchema,
261
- resourceId: z.string().trim().min(1).max(255),
262
- resourceType: z.enum(["workflow", "agent", "trigger", "integration", "external", "human_checkpoint"]),
263
- systemIds: ReferenceIdsSchema,
264
- entityIds: ReferenceIdsSchema,
265
- surfaceIds: ReferenceIdsSchema,
266
- actionIds: ReferenceIdsSchema,
267
- /** Optional tech-stack metadata for external-SaaS integrations. */
268
- techStack: TechStackEntrySchema.optional()
269
- });
270
-
271
- // ../core/src/organization-model/domains/entities.ts
272
- var EntityIdSchema = ModelIdSchema;
273
- var EntityLinkKindSchema = z.enum(["belongs-to", "has-many", "has-one", "many-to-many"]).meta({ label: "Link kind" });
274
- var EntityLinkSchema = z.object({
275
- toEntity: EntityIdSchema.meta({ ref: "entity" }),
276
- kind: EntityLinkKindSchema,
277
- via: z.string().trim().min(1).max(255).optional(),
278
- label: LabelSchema.optional()
279
- });
280
- var EntitySchema = z.object({
281
- id: EntityIdSchema,
282
- /** Domain-map iteration order. Convention: multiples of 10 (10, 20, 30, ...) to allow easy insertion. */
283
- order: z.number(),
284
- label: LabelSchema,
285
- description: DescriptionSchema.optional(),
286
- ownedBySystemId: ModelIdSchema.meta({ ref: "system" }),
287
- table: z.string().trim().min(1).max(255).optional(),
288
- rowSchema: ModelIdSchema.optional(),
289
- stateCatalogId: ModelIdSchema.optional(),
290
- links: z.array(EntityLinkSchema).optional()
291
- });
292
- var EntitiesDomainSchema = z.record(z.string(), EntitySchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
293
- message: "Each entity entry id must match its map key"
294
- }).default({});
295
- function defineEntities(entries) {
296
- return defineDomainRecord(EntitySchema, entries);
297
- }
298
-
299
- // ../core/src/organization-model/domains/actions.ts
300
- var ActionResourceIdSchema = z.string().trim().min(1).max(255).regex(/^[A-Za-z0-9]+(?:[-._][A-Za-z0-9]+)*$/, "Resource IDs must use letters, numbers, -, _, or . separators");
301
- z.enum(["slash-command", "mcp-tool", "api-endpoint", "script-execution"]).meta({ label: "Invocation kind" });
302
- var ActionIdSchema = ModelIdSchema;
303
- var ActionScopeSchema = z.union([
304
- z.literal("global"),
305
- z.object({
306
- domain: ModelIdSchema
307
- })
308
- ]);
309
- var ActionRefSchema = z.object({
310
- actionId: ActionIdSchema.meta({ ref: "action" }),
311
- intent: z.enum(["exposes", "consumes"]).meta({ label: "Intent" })
312
- });
313
- var SlashCommandInvocationSchema = z.object({
314
- kind: z.literal("slash-command"),
315
- command: z.string().trim().min(1).max(200).regex(/^\/[^\s].*$/, "Slash commands must start with /"),
316
- toolFactory: ModelIdSchema.optional()
317
- });
318
- var McpToolInvocationSchema = z.object({
319
- kind: z.literal("mcp-tool"),
320
- server: ModelIdSchema,
321
- name: ModelIdSchema
322
- });
323
- var ApiEndpointInvocationSchema = z.object({
324
- kind: z.literal("api-endpoint"),
325
- method: z.enum(["GET", "POST", "PATCH", "DELETE"]).meta({ label: "HTTP method" }),
326
- path: z.string().trim().startsWith("/").max(500),
327
- requestSchema: ModelIdSchema.optional(),
328
- responseSchema: ModelIdSchema.optional()
329
- });
330
- var ScriptExecutionInvocationSchema = z.object({
331
- kind: z.literal("script-execution"),
332
- resourceId: ActionResourceIdSchema
333
- });
334
- var ActionInvocationSchema = z.discriminatedUnion("kind", [
335
- SlashCommandInvocationSchema,
336
- McpToolInvocationSchema,
337
- ApiEndpointInvocationSchema,
338
- ScriptExecutionInvocationSchema
339
- ]);
340
- var ActionSchema = z.object({
341
- id: ActionIdSchema,
342
- /** Domain-map iteration order. Convention: multiples of 10 (10, 20, 30, ...) to allow easy insertion. */
343
- order: z.number(),
344
- label: LabelSchema,
345
- description: DescriptionSchema.optional(),
346
- scope: ActionScopeSchema.default("global"),
347
- resourceId: ActionResourceIdSchema.optional(),
348
- affects: z.array(EntityIdSchema.meta({ ref: "entity" })).optional(),
349
- invocations: z.array(ActionInvocationSchema).default([]),
350
- knowledge: z.array(ModelIdSchema.meta({ ref: "knowledge" })).default([]).optional(),
351
- lifecycle: z.enum(["draft", "beta", "active", "deprecated", "archived"]).meta({ label: "Lifecycle", color: "teal" }).default("active")
352
- });
353
- var ActionsDomainSchema = z.record(z.string(), ActionSchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
354
- message: "Each action entry id must match its map key"
355
- }).default({});
356
- var DEFAULT_ORGANIZATION_MODEL_ACTIONS = {};
357
- function defineActions(entries) {
358
- return defineDomainRecord(ActionSchema, entries);
359
- }
360
-
361
- // ../core/src/organization-model/domains/systems.ts
362
- var SystemKindSchema = z.enum(["product", "operational", "platform", "diagnostic"]).meta({ label: "System kind", color: "blue" });
363
- var SystemLifecycleSchema = z.enum(["draft", "beta", "active", "deprecated", "archived"]).meta({ label: "Lifecycle", color: "teal" });
364
- var SystemStatusSchema = z.enum(["active", "deprecated", "archived"]).meta({ label: "Status", color: "teal" });
365
- var SystemIdSchema = ModelIdSchema;
366
- var SystemPathSchema = z.string().trim().min(1).regex(
367
- /^[a-z0-9][a-z0-9-]*(?:\.[a-z0-9][a-z0-9-]*)*$/,
368
- 'must be a dotted lowercase path (e.g. "sales.lead-gen" or "sales.crm")'
369
- );
370
- var UiPositionSchema = z.enum(["sidebar-primary", "sidebar-bottom"]).meta({ label: "UI position" });
371
- var NodeIdStringSchema = z.string().trim().min(1).max(200).regex(
372
- /^[a-z][a-z-]*:([a-z0-9-]+)(\.[a-z0-9-]+)*(:[a-z0-9.-]+)*$/,
373
- "Node references must use kind:dotted-path (e.g. system:sales.crm or resource:lead-gen.company.qualify)"
374
- );
375
- var SystemUiSchema = z.object({
376
- path: PathSchema,
377
- surfaces: ReferenceIdsSchema,
378
- icon: IconNameSchema.optional(),
379
- order: z.number().int().optional()
380
- });
381
- var SystemInterfaceKeySchema = ModelIdSchema;
382
- var SystemInterfaceLifecycleSchema = z.enum(["draft", "active", "disabled", "deprecated", "archived"]).meta({ label: "System interface lifecycle", color: "teal" });
383
- var SystemInterfaceReadinessProfileSchema = z.string().trim().min(1).max(200).regex(
384
- /^[a-z0-9][a-z0-9-]*(?:\.[a-z0-9][a-z0-9-]*)*(?:\.[a-z0-9][a-z0-9-]*)?$/,
385
- 'Readiness profiles must use dotted lowercase identifiers (e.g. "sales.lead-gen.api")'
386
- );
387
- var SystemInterfaceResourceScopeSchema = z.array(ModelIdSchema).default([]);
388
- var SystemApiInterfaceSchema = z.object({
389
- lifecycle: SystemInterfaceLifecycleSchema.default("active"),
390
- readinessProfile: SystemInterfaceReadinessProfileSchema.optional(),
391
- /**
392
- * Resource ids that participate in this API interface. This scopes readiness
393
- * derivation without duplicating authored required/provided contract refs.
394
- */
395
- resourceIds: SystemInterfaceResourceScopeSchema.optional()
396
- }).strict();
397
- var SystemInterfaceRefSchema = z.object({
398
- systemPath: SystemPathSchema,
399
- interfaceKey: SystemInterfaceKeySchema
400
- }).strict();
401
- var JsonValueSchema = z.lazy(
402
- () => z.union([
403
- z.string(),
404
- z.number(),
405
- z.boolean(),
406
- z.null(),
407
- z.array(JsonValueSchema),
408
- z.record(z.string(), JsonValueSchema)
409
- ])
410
- );
411
- var SystemConfigSchema = z.record(z.string().trim().min(1).max(200), JsonValueSchema).default({}).optional();
412
- var SystemEntrySchema = z.object({
413
- /** Stable tenant-defined system id (e.g. "sys.lead-gen" or "sales.crm"). */
414
- id: SystemIdSchema,
415
- /** Human-readable system label shown in UI, governance, and operations surfaces. */
416
- label: LabelSchema.optional(),
417
- /** @deprecated Use label. Accepted for pre-consolidation System declarations. */
418
- title: LabelSchema.optional(),
419
- /** One-paragraph purpose statement for the bounded context. */
420
- description: DescriptionSchema.optional(),
421
- /** Closed system shape enum; catalog values remain tenant-defined. */
422
- kind: SystemKindSchema.optional(),
423
- /** Optional self-reference for System hierarchy. */
424
- parentSystemId: SystemIdSchema.optional(),
425
- /** Optional UI presence. Systems without UI omit this. */
426
- ui: SystemUiSchema.optional(),
427
- /** Canonical lifecycle state. Replaces Feature.enabled/devOnly and System.status. */
428
- lifecycle: SystemLifecycleSchema.optional(),
429
- /** Optional role responsible for this system. */
430
- responsibleRoleId: ModelIdSchema.meta({ ref: "role" }).optional(),
431
- /** Optional knowledge nodes that govern this system. */
432
- governedByKnowledge: z.array(ModelIdSchema.meta({ ref: "knowledge" })).default([]).optional(),
433
- /** Optional actions this system exposes or consumes. */
434
- actions: z.array(ActionRefSchema).optional(),
435
- /** Optional operational policies that apply to this system. */
436
- policies: z.array(ModelIdSchema.meta({ ref: "policy" })).default([]).optional(),
437
- /** Optional goals this system contributes to. */
438
- drivesGoals: z.array(ModelIdSchema.meta({ ref: "goal" })).default([]).optional(),
439
- /** Thin API runtime-boundary marker. Readiness is derived from scoped resources and topology. */
440
- apiInterface: SystemApiInterfaceSchema.optional(),
441
- /** @deprecated Use lifecycle. Accepted for one publish cycle. */
442
- status: SystemStatusSchema.optional(),
443
- /** @deprecated Use ui.path. Kept for one-cycle Feature compatibility. */
444
- path: PathSchema.optional(),
445
- /** @deprecated Use ui.icon. Kept for one-cycle Feature compatibility. */
446
- icon: IconNameSchema.optional(),
447
- /** @deprecated Feature color token, retained for one-cycle compatibility. */
448
- color: ColorTokenSchema.optional(),
449
- /** @deprecated UI placement hint, retained for one-cycle compatibility. */
450
- uiPosition: UiPositionSchema.optional(),
451
- /** @deprecated Use lifecycle. */
452
- enabled: z.boolean().optional(),
453
- /** @deprecated Use lifecycle: "beta". */
454
- devOnly: z.boolean().optional(),
455
- requiresAdmin: z.boolean().optional(),
456
- /** Domain-map iteration order. Convention: multiples of 10 (10, 20, 30, ...) to allow easy insertion. */
457
- order: z.number(),
458
- /**
459
- * System-local JSON settings and defaults. Strongly typed OM fields,
460
- * secrets, credentials, and runtime state stay outside this bucket.
461
- */
462
- config: SystemConfigSchema,
463
- /**
464
- * System-owned ontology declarations. `systems` is now the canonical child
465
- * key; this scope holds the object, action, catalog, link, event, and
466
- * shared contract records owned by this system.
467
- */
468
- ontology: OntologyScopeSchema.optional(),
469
- /**
470
- * Recursive child systems, authored via nesting (per L11).
471
- * The key is the local system id; the full path is computed by joining
472
- * ancestor keys with `.` (e.g. parent key `'sales'` + child key `'crm'` → `'sales.crm'`).
473
- * Per Phase 4: `id` and `parentSystemId` fields will be removed in favour of
474
- * position-derived paths. Both still exist on this schema for backward compat.
475
- */
476
- systems: z.lazy(() => z.record(z.string().trim().min(1).max(100), SystemEntrySchema)).optional(),
477
- /** @deprecated Use systems. Accepted as a compatibility alias during the ontology bridge. */
478
- subsystems: z.lazy(() => z.record(z.string().trim().min(1).max(100), SystemEntrySchema)).optional()
479
- }).strict().refine((system) => system.label !== void 0 || system.title !== void 0, {
480
- path: ["label"],
481
- message: "System must provide label or title"
482
- }).transform((system) => {
483
- const normalizedSystem = system.systems !== void 0 && system.subsystems === void 0 ? { ...system, subsystems: system.systems } : system;
484
- if (normalizedSystem.status === void 0) return normalizedSystem;
485
- console.warn("[organization-model] System.status is deprecated; use System.lifecycle instead.");
486
- return normalizedSystem.lifecycle === void 0 ? { ...normalizedSystem, lifecycle: normalizedSystem.status } : normalizedSystem;
487
- });
488
- var SystemsDomainSchema = z.record(z.string(), SystemEntrySchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
489
- message: "Each system entry id must match its map key"
490
- }).default({});
491
- var DEFAULT_ORGANIZATION_MODEL_SYSTEMS = {};
492
- var BusinessHoursDaySchema = z.object({
493
- open: z.string().trim().regex(/^\d{2}:\d{2}$/, "Expected HH:MM format"),
494
- close: z.string().trim().regex(/^\d{2}:\d{2}$/, "Expected HH:MM format")
495
- });
496
- var BusinessHoursSchema = z.object({
497
- monday: BusinessHoursDaySchema.optional(),
498
- tuesday: BusinessHoursDaySchema.optional(),
499
- wednesday: BusinessHoursDaySchema.optional(),
500
- thursday: BusinessHoursDaySchema.optional(),
501
- friday: BusinessHoursDaySchema.optional(),
502
- saturday: BusinessHoursDaySchema.optional(),
503
- sunday: BusinessHoursDaySchema.optional()
504
- }).default({});
505
- var IdentityDomainSchema = z.object({
506
- /** Why the organization exists — one or two plain-language sentences. */
507
- mission: z.string().trim().max(1e3).default(""),
508
- /** Long-term direction the organization is moving toward. */
509
- vision: z.string().trim().max(1e3).default(""),
510
- /** Legal registered name of the entity. */
511
- legalName: z.string().trim().max(200).default(""),
512
- /**
513
- * Type of legal entity (e.g. "LLC", "Corporation", "Sole Proprietor",
514
- * "Non-profit"). Free-form string so it covers any jurisdiction.
515
- */
516
- entityType: z.string().trim().max(100).default(""),
517
- /**
518
- * Primary jurisdiction of registration or operation
519
- * (e.g. "United States – Delaware", "Canada – Ontario").
520
- */
521
- jurisdiction: z.string().trim().max(200).default(""),
522
- /**
523
- * Industry category — broad classification (e.g. "Marketing Agency",
524
- * "Software / SaaS", "Professional Services").
525
- */
526
- industryCategory: z.string().trim().max(200).default(""),
527
- /**
528
- * Geographic focus — where the organization primarily operates or serves
529
- * (e.g. "North America", "Global", "Southeast Asia").
530
- */
531
- geographicFocus: z.string().trim().max(200).default(""),
532
- /**
533
- * IANA timezone identifier for the organization's primary operating timezone
534
- * (e.g. "America/Los_Angeles", "Europe/London", "UTC").
535
- */
536
- timeZone: z.string().trim().max(100).default("UTC"),
537
- /** Typical operating hours per day of week. Empty object means not configured. */
538
- businessHours: BusinessHoursSchema,
539
- /**
540
- * Long-form markdown capturing client context, problem narrative, and domain
541
- * background. Populated by /setup; surfaced to agents as organizational context.
542
- * Optional — many projects have no external client.
543
- */
544
- clientBrief: z.string().trim().default(""),
545
- /**
546
- * Display name of the organization as shown to end users.
547
- * Recommended placement for display naming — prefer this over the deprecated
548
- * `branding.organizationName`. Falls back to `branding.organizationName` for
549
- * legacy tenants that have not yet migrated.
550
- */
551
- organizationName: LabelSchema.optional(),
552
- /**
553
- * Display name of the primary product or platform.
554
- * Recommended placement for display naming — prefer this over the deprecated
555
- * `branding.productName`. Falls back to `branding.productName` for legacy tenants.
556
- */
557
- productName: LabelSchema.optional(),
558
- /**
559
- * Short abbreviated name used in space-constrained UI surfaces (max 40 chars).
560
- * Recommended placement for display naming — prefer this over the deprecated
561
- * `branding.shortName`. Falls back to `branding.shortName` for legacy tenants.
562
- */
563
- shortName: z.string().trim().min(1).max(40).optional(),
564
- /**
565
- * Plain-language description of the organization for display and discovery.
566
- * Recommended placement for display naming — prefer this over the deprecated
567
- * `branding.description`. Falls back to `branding.description` for legacy tenants.
568
- */
569
- description: DescriptionSchema.optional()
570
- }).passthrough();
571
- var DEFAULT_ORGANIZATION_MODEL_IDENTITY = {
572
- mission: "",
573
- vision: "",
574
- legalName: "",
575
- entityType: "",
576
- jurisdiction: "",
577
- industryCategory: "",
578
- geographicFocus: "",
579
- timeZone: "UTC",
580
- businessHours: {},
581
- clientBrief: ""
582
- };
583
- var ContractRefSchema = z.string().trim().min(1).max(500).regex(
584
- /^[A-Za-z0-9@](?:[A-Za-z0-9_./@-]*[A-Za-z0-9_])?\/?[A-Za-z0-9_./@-]*#[A-Za-z_$][A-Za-z0-9_$]*$/,
585
- "ContractRef must be in the format package/subpath#ExportName (e.g. @repo/elevasis-core/contracts/apollo-import#inputSchema)"
586
- );
587
- z.enum(["workflow", "agent", "integration", "script"]).meta({ label: "Resource kind", color: "orange" });
588
- var ResourceGovernanceStatusSchema = z.enum(["active", "deprecated", "archived"]).meta({ label: "Governance status", color: "teal" });
589
- var AgentKindSchema = z.enum(["orchestrator", "specialist", "utility", "platform"]).meta({ label: "Agent kind", color: "violet" });
590
- var ScriptResourceLanguageSchema = z.enum(["shell", "sql", "typescript", "python"]).meta({ label: "Language" });
591
- var CodeReferenceRoleSchema = z.enum(["entrypoint", "handler", "schema", "test", "docs", "config"]).meta({ label: "Code reference role", color: "blue" });
592
- 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");
593
- var EventIdSchema = z.string().trim().min(1).max(300).regex(
594
- /^[A-Za-z0-9]+(?:[-._][A-Za-z0-9]+)*:[a-z0-9]+(?:[-._][a-z0-9]+)*$/,
595
- "Event IDs must use <owner-id>:<event-key>"
596
- );
597
- var EventKeySchema = ModelIdSchema;
598
- var EventEmissionDescriptorSchema = z.object({
599
- eventKey: EventKeySchema,
600
- label: z.string().trim().min(1).max(120),
601
- payloadSchema: ModelIdSchema.optional(),
602
- lifecycle: SystemLifecycleSchema.optional()
603
- });
604
- EventEmissionDescriptorSchema.extend({
605
- id: EventIdSchema,
606
- ownerId: z.union([ResourceIdSchema, ModelIdSchema]),
607
- ownerKind: z.enum(["resource", "entity"]).meta({ label: "Owner kind" })
608
- });
609
- var ResourceOntologyBindingSchema = z.object({
610
- actions: z.array(OntologyIdSchema).optional(),
611
- primaryAction: OntologyIdSchema.optional(),
612
- reads: z.array(OntologyIdSchema).optional(),
613
- writes: z.array(OntologyIdSchema).optional(),
614
- usesCatalogs: z.array(OntologyIdSchema).optional(),
615
- emits: z.array(OntologyIdSchema).optional(),
616
- /**
617
- * Optional typed contract binding for this resource's workflow I/O.
618
- * Each ref is a `package/subpath#ExportName` string that resolves to a
619
- * Zod schema in `@repo/elevasis-core` (or the consumer's equivalent package).
620
- *
621
- * Absence of this field preserves all existing behavior — it is additive + optional.
622
- * Tier-1 validation (schema.ts): ref-string shape only (browser-safe, no imports).
623
- * Tier-2 validation (om:verify): intra-package typed-map resolution asserts ZodType.
624
- */
625
- contract: z.object({
626
- input: ContractRefSchema.optional(),
627
- output: ContractRefSchema.optional()
628
- }).optional()
629
- }).superRefine((binding, ctx) => {
630
- if (binding.primaryAction === void 0) return;
631
- if (binding.actions?.includes(binding.primaryAction)) return;
632
- ctx.addIssue({
633
- code: z.ZodIssueCode.custom,
634
- path: ["primaryAction"],
635
- message: "Resource ontology primaryAction must be included in actions"
636
- });
637
- });
638
- var CodeReferenceSchema = z.object({
639
- path: z.string().trim().min(1).max(500).regex(/^[A-Za-z0-9_./$@()[\] -]+$/, "Code reference paths must be repo-relative paths"),
640
- role: CodeReferenceRoleSchema,
641
- symbol: z.string().trim().min(1).max(200).optional(),
642
- description: z.string().trim().min(1).max(300).optional()
643
- });
644
- var ResourceEntryBaseSchema = z.object({
645
- /** Canonical resource id; runtime resourceId derives from this value. */
646
- id: ResourceIdSchema,
647
- /** Domain-map iteration order. Convention: multiples of 10 (10, 20, 30, ...) to allow easy insertion. */
648
- order: z.number().default(0),
649
- /** Required single System membership — value is a dot-separated system path (e.g. "sales.lead-gen"). */
650
- systemPath: SystemPathSchema.meta({ ref: "system" }),
651
- /** Executable display title owned by the OM Resource descriptor. */
652
- title: LabelSchema.optional(),
653
- /** Executable display description owned by the OM Resource descriptor. */
654
- description: DescriptionSchema.optional(),
655
- /** Optional role responsible for maintaining this resource. */
656
- ownerRoleId: ModelIdSchema.meta({ ref: "role" }).optional(),
657
- status: ResourceGovernanceStatusSchema,
658
- /**
659
- * Ontology contract bindings for the semantic work this resource performs.
660
- * `emits` stays nested here so top-level resource emits descriptors remain
661
- * compatible with graph event projection during the bridge.
662
- */
663
- ontology: ResourceOntologyBindingSchema.optional(),
664
- /** Repo-relative implementation breadcrumbs for agents and operators. */
665
- codeRefs: z.array(CodeReferenceSchema).default([])
666
- });
667
- var WorkflowResourceEntrySchema = ResourceEntryBaseSchema.extend({
668
- kind: z.literal("workflow"),
669
- emits: z.array(EventEmissionDescriptorSchema).optional()
670
- });
671
- var AgentResourceEntrySchema = ResourceEntryBaseSchema.extend({
672
- kind: z.literal("agent"),
673
- /** Mirrors code-side AgentConfig.kind. */
674
- agentKind: AgentKindSchema,
675
- /** Role this agent embodies, if any. */
676
- actsAsRoleId: ModelIdSchema.meta({ ref: "role" }).optional(),
677
- /** Mirrors AgentConfig.sessionCapable. */
678
- sessionCapable: z.boolean(),
679
- /** Broad/composite callable entry points orchestrated by this agent. */
680
- invocations: z.array(ActionInvocationSchema).default([]),
681
- emits: z.array(EventEmissionDescriptorSchema).optional()
682
- });
683
- var IntegrationResourceEntrySchema = ResourceEntryBaseSchema.extend({
684
- kind: z.literal("integration"),
685
- provider: z.string().trim().min(1).max(100)
686
- });
687
- var ScriptResourceSourceSchema = z.union([
688
- z.string().trim().min(1).max(5e4),
689
- z.object({
690
- file: z.string().trim().min(1).max(500)
691
- })
692
- ]);
693
- var ScriptResourceEntrySchema = ResourceEntryBaseSchema.extend({
694
- kind: z.literal("script"),
695
- language: ScriptResourceLanguageSchema,
696
- source: ScriptResourceSourceSchema
697
- });
698
- var ResourceEntrySchema = z.discriminatedUnion("kind", [
699
- WorkflowResourceEntrySchema,
700
- AgentResourceEntrySchema,
701
- IntegrationResourceEntrySchema,
702
- ScriptResourceEntrySchema
703
- ]);
704
- var ResourcesDomainSchema = z.record(z.string(), ResourceEntrySchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
705
- message: "Each resource entry id must match its map key"
706
- }).default({});
707
- var DEFAULT_ORGANIZATION_MODEL_RESOURCES = {};
708
- function defineResources(resources) {
709
- return Object.fromEntries(
710
- Object.entries(resources).map(([key, resource]) => [key, ResourceEntrySchema.parse(resource)])
711
- );
712
- }
713
-
714
- // ../core/src/organization-model/contracts.ts
715
- var PROJECTS_VIEW_ACTION_ID = "delivery.projects.view";
716
- var OrganizationModelBrandingSchema = z.object({
717
- /**
718
- * @deprecated Prefer `identity.organizationName`; branding retains it for back-compat.
719
- * Legacy tenants that have not set `identity.organizationName` fall back to this field.
720
- */
721
- organizationName: LabelSchema,
722
- /**
723
- * @deprecated Prefer `identity.productName`; branding retains it for back-compat.
724
- * Legacy tenants that have not set `identity.productName` fall back to this field.
725
- */
726
- productName: LabelSchema,
727
- /**
728
- * @deprecated Prefer `identity.shortName`; branding retains it for back-compat.
729
- * Legacy tenants that have not set `identity.shortName` fall back to this field.
730
- */
731
- shortName: z.string().trim().min(1).max(40),
732
- /**
733
- * @deprecated Prefer `identity.description`; branding retains it for back-compat.
734
- * Legacy tenants that have not set `identity.description` fall back to this field.
735
- */
736
- description: DescriptionSchema.optional(),
737
- logos: z.object({
738
- light: z.string().trim().min(1).max(2048).optional(),
739
- dark: z.string().trim().min(1).max(2048).optional()
740
- }).default({}),
741
- /**
742
- * Brand voice — how the organization communicates. Plain-language description
743
- * of tone, register, and personality (e.g. "Direct and human — no jargon").
744
- * Max 280 characters.
745
- */
746
- voice: z.string().trim().max(280).optional(),
747
- /**
748
- * Brand tagline or positioning statement — the memorable one-liner that
749
- * captures the brand's promise or differentiator. Max 200 characters.
750
- */
751
- tagline: z.string().trim().max(200).optional(),
752
- /**
753
- * Core brand values — an ordered list of principles the organization stands
754
- * for (e.g. ["Transparency", "Craftsmanship", "Velocity"]). Each entry must
755
- * be a non-empty trimmed string.
756
- */
757
- values: z.array(z.string().trim().min(1)).optional(),
758
- /**
759
- * ID of the active UI theme preset from the UI theme-presets registry.
760
- * The UI layer resolves this to colors and typography via `usePresetsContext()`.
761
- * Free-form string — validation and fallback state are handled at the UI layer.
762
- * Min 1, max 64 characters.
763
- */
764
- themePresetId: z.string().trim().min(1).max(64).optional()
765
- }).passthrough();
766
- var DEFAULT_ORGANIZATION_MODEL_BRANDING = {
767
- organizationName: "Default Organization",
768
- productName: "Organization OS",
769
- shortName: "Org OS",
770
- logos: {}
771
- };
772
- var FirmographicsSchema = z.object({
773
- /** Industry vertical (e.g. "Marketing Agency", "Legal", "Real Estate"). */
774
- industry: z.string().trim().max(200).optional(),
775
- /**
776
- * Company headcount band (e.g. "1–10", "11–50", "51–200", "200+").
777
- * Free-form string to accommodate any band notation.
778
- */
779
- companySize: z.string().trim().max(100).optional(),
780
- /**
781
- * Primary geographic region the segment operates in or is targeted from
782
- * (e.g. "North America", "Europe", "Global").
783
- */
784
- region: z.string().trim().max(200).optional()
785
- });
786
- var CustomerSegmentSchema = z.object({
787
- /** Stable unique identifier for the segment (e.g. "segment-smb-agencies"). */
788
- id: z.string().trim().min(1).max(100),
789
- /** Domain-map iteration order. Convention: multiples of 10 (10, 20, 30, ...) to allow easy insertion. */
790
- order: z.number(),
791
- /** Human-readable name shown to agents and in UI (e.g. "SMB Marketing Agencies"). */
792
- name: z.string().trim().max(200).default(""),
793
- /** One or two sentences describing who this segment is. */
794
- description: z.string().trim().max(2e3).default(""),
795
- /**
796
- * The primary job(s) this segment is trying to get done — the goal they hire
797
- * a product/service to accomplish. Plain-language narrative or bullet list.
798
- */
799
- jobsToBeDone: z.string().trim().max(2e3).default(""),
800
- /**
801
- * Pains — frustrations, obstacles, and risks the segment experiences
802
- * when trying to accomplish their jobs-to-be-done.
803
- */
804
- pains: z.array(z.string().trim().max(500)).default([]),
805
- /**
806
- * Gains — outcomes and benefits the segment desires; positive motivators
807
- * beyond merely resolving pains.
808
- */
809
- gains: z.array(z.string().trim().max(500)).default([]),
810
- /** Firmographic profile for targeting and filtering. */
811
- firmographics: FirmographicsSchema.default({}),
812
- /**
813
- * Value proposition — one or two sentences stating why this organization's
814
- * offering is uniquely suited for this segment's needs.
815
- */
816
- valueProp: z.string().trim().max(2e3).default("")
817
- });
818
- var CustomersDomainSchema = z.record(z.string(), CustomerSegmentSchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
819
- message: "Each segment entry id must match its map key"
820
- }).default({});
821
- var DEFAULT_ORGANIZATION_MODEL_CUSTOMERS = {};
822
- var PricingModelSchema = z.enum(["one-time", "subscription", "usage-based", "custom"]).meta({ label: "Pricing model", color: "green" });
823
- var ProductSchema = z.object({
824
- /** Stable unique identifier for the product (e.g. "product-starter-plan"). */
825
- id: z.string().trim().min(1).max(100),
826
- /** Domain-map iteration order. Convention: multiples of 10 (10, 20, 30, ...) to allow easy insertion. */
827
- order: z.number(),
828
- /** Human-readable name shown to agents and in UI (e.g. "Starter Plan"). */
829
- name: z.string().trim().max(200).default(""),
830
- /** One or two sentences describing what this product/service delivers. */
831
- description: z.string().trim().max(2e3).default(""),
832
- /**
833
- * How this product is priced:
834
- * - "one-time" — single purchase (setup fee, project fee)
835
- * - "subscription" — recurring (monthly/annual SaaS, retainer)
836
- * - "usage-based" — metered by consumption (API calls, seats)
837
- * - "custom" — negotiated or bespoke pricing
838
- */
839
- pricingModel: PricingModelSchema.default("custom"),
840
- /** Base price amount (≥ 0). Currency unit defined by `currency`. */
841
- price: z.number().min(0).default(0),
842
- /**
843
- * ISO 4217 currency code (e.g. "USD", "EUR", "GBP").
844
- * Free-form string to accommodate any currency; defaults to "USD".
845
- */
846
- currency: z.string().trim().max(10).default("USD"),
847
- /**
848
- * IDs of customer segments this product targets.
849
- * Each id must reference a declared `customers.segments[].id`.
850
- * Cross-reference enforced in `OrganizationModelSchema.superRefine()`.
851
- */
852
- targetSegmentIds: z.array(z.string().trim().min(1)).default([]),
853
- /**
854
- * Optional: ID of the platform system responsible for delivering this product.
855
- * When present, must reference a declared `systems.systems[].id`.
856
- * Cross-reference enforced in `OrganizationModelSchema.superRefine()`.
857
- */
858
- deliveryFeatureId: z.string().trim().min(1).optional()
859
- });
860
- var OfferingsDomainSchema = z.record(z.string(), ProductSchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
861
- message: "Each product entry id must match its map key"
862
- }).default({});
863
- var DEFAULT_ORGANIZATION_MODEL_OFFERINGS = {};
864
- var RoleIdSchema = ModelIdSchema;
865
- var HumanRoleHolderSchema = z.object({
866
- kind: z.literal("human"),
867
- userId: z.string().trim().min(1).max(200)
868
- });
869
- var AgentRoleHolderSchema = z.object({
870
- kind: z.literal("agent"),
871
- agentId: ResourceIdSchema.meta({ ref: "resource" })
872
- });
873
- var TeamRoleHolderSchema = z.object({
874
- kind: z.literal("team"),
875
- memberIds: z.array(z.string().trim().min(1).max(200)).min(1)
876
- });
877
- var RoleHolderSchema = z.discriminatedUnion("kind", [
878
- HumanRoleHolderSchema,
879
- AgentRoleHolderSchema,
880
- TeamRoleHolderSchema
881
- ]);
882
- var RoleHoldersSchema = z.union([RoleHolderSchema, z.array(RoleHolderSchema).min(1)]);
883
- var RoleSchema = z.object({
884
- /** Stable unique identifier for the role (e.g. "role-ceo", "role-head-of-sales"). */
885
- id: RoleIdSchema,
886
- /** Domain-map iteration order. Convention: multiples of 10 (10, 20, 30, ...) to allow easy insertion. */
887
- order: z.number(),
888
- /** Human-readable title shown to agents and in UI (e.g. "CEO", "Head of Sales"). */
889
- title: z.string().trim().min(1).max(200),
890
- /**
891
- * List of responsibilities this role owns - plain-language descriptions of
892
- * what the person in this role is accountable for delivering.
893
- * Defaults to empty array so minimal role definitions stay concise.
894
- */
895
- responsibilities: z.array(z.string().trim().max(500)).default([]),
896
- /**
897
- * Optional: ID of another role this role reports to.
898
- * When present, must reference another `roles[].id` in the same organization.
899
- */
900
- reportsToId: RoleIdSchema.meta({ ref: "role" }).optional(),
901
- /**
902
- * Optional: human, agent, or team holder currently filling this role.
903
- * Agent holders reference OM Resource IDs and are validated at the model level.
904
- */
905
- heldBy: RoleHoldersSchema.optional(),
906
- /**
907
- * Optional Systems this role is accountable for.
908
- * Cross-reference enforced in `OrganizationModelSchema.superRefine()`.
909
- */
910
- responsibleFor: z.array(SystemIdSchema.meta({ ref: "system" })).optional()
911
- });
912
- var RolesDomainSchema = z.record(z.string(), RoleSchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
913
- message: "Each role entry id must match its map key"
914
- }).default({});
915
- var DEFAULT_ORGANIZATION_MODEL_ROLES = {};
916
- var KeyResultSchema = z.object({
917
- /** Stable unique identifier for the measurable outcome (e.g. "kr-revenue-q1"). */
918
- id: z.string().trim().min(1).max(100),
919
- /** Plain-language description of this measurable outcome (e.g. "Increase trial-to-paid conversion"). */
920
- description: z.string().trim().min(1).max(500),
921
- /**
922
- * What is being measured — the metric name (e.g. "monthly revenue", "NPS score",
923
- * "trial-to-paid conversion rate"). Free-form string.
924
- */
925
- targetMetric: z.string().trim().min(1).max(200),
926
- /** Current measured value. Defaults to 0 when not yet tracked. */
927
- currentValue: z.number().default(0),
928
- /**
929
- * Target value to reach for this measurable outcome to be considered achieved.
930
- * Optional — omit if the outcome is directional (e.g. "reduce churn") without
931
- * a hard numeric target.
932
- */
933
- targetValue: z.number().optional()
934
- });
935
- var ISO_DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/;
936
- var ObjectiveSchema = z.object({
937
- /** Stable unique identifier for the goal (e.g. "goal-grow-arr-q1-2026"). */
938
- id: z.string().trim().min(1).max(100),
939
- /** Domain-map iteration order. Convention: multiples of 10 (10, 20, 30, ...) to allow easy insertion. */
940
- order: z.number(),
941
- /** Plain-language description of what the organization wants to achieve. */
942
- description: z.string().trim().min(1).max(1e3),
943
- /**
944
- * Start of the period this goal is active for — ISO 8601 date string (YYYY-MM-DD).
945
- * Must be strictly before `periodEnd`.
946
- */
947
- periodStart: z.string().regex(ISO_DATE_REGEX, "periodStart must be an ISO date string (YYYY-MM-DD)"),
948
- /**
949
- * End of the period this goal is active for — ISO 8601 date string (YYYY-MM-DD).
950
- * Must be strictly after `periodStart`.
951
- * Enforced via `OrganizationModelSchema.superRefine()`.
952
- */
953
- periodEnd: z.string().regex(ISO_DATE_REGEX, "periodEnd must be an ISO date string (YYYY-MM-DD)"),
954
- /**
955
- * List of measurable outcomes that define success for this goal.
956
- * Defaults to empty array so goals can be declared before outcomes are defined.
957
- */
958
- keyResults: z.array(KeyResultSchema).default([])
959
- });
960
- var GoalsDomainSchema = z.record(z.string(), ObjectiveSchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
961
- message: "Each objective entry id must match its map key"
962
- }).default({});
963
- var DEFAULT_ORGANIZATION_MODEL_GOALS = {};
964
- var SecretLikeMetadataKeySchema = /(?:secret|password|passwd|token|api[-_]?key|credential|private[-_]?key)/i;
965
- 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-----)/;
966
- z.enum([
967
- "system",
968
- "resource",
969
- "ontology",
970
- "policy",
971
- "role",
972
- "trigger",
973
- "humanCheckpoint",
974
- "externalResource"
975
- ]);
976
- var OmTopologyRelationshipKindSchema = z.enum(["triggers", "uses", "approval"]);
977
- var OmTopologyNodeRefSchema = z.discriminatedUnion("kind", [
978
- z.object({ kind: z.literal("system"), id: ModelIdSchema }),
979
- z.object({ kind: z.literal("resource"), id: ResourceIdSchema }),
980
- z.object({ kind: z.literal("ontology"), id: OntologyIdSchema }),
981
- z.object({ kind: z.literal("policy"), id: ModelIdSchema }),
982
- z.object({ kind: z.literal("role"), id: ModelIdSchema }),
983
- z.object({ kind: z.literal("trigger"), id: ResourceIdSchema }),
984
- z.object({ kind: z.literal("humanCheckpoint"), id: ResourceIdSchema }),
985
- z.object({ kind: z.literal("externalResource"), id: ResourceIdSchema })
986
- ]);
987
- var OmTopologyMetadataSchema = z.record(z.string().trim().min(1).max(120), JsonValueSchema).superRefine((metadata, ctx) => {
988
- function visit(value, path) {
989
- if (typeof value === "string" && SecretLikeMetadataValueSchema.test(value)) {
990
- ctx.addIssue({
991
- code: z.ZodIssueCode.custom,
992
- path,
993
- message: "Topology metadata must not contain secret-like values"
994
- });
995
- return;
996
- }
997
- if (Array.isArray(value)) {
998
- value.forEach((entry, index) => visit(entry, [...path, index]));
999
- return;
1000
- }
1001
- if (typeof value !== "object" || value === null) return;
1002
- Object.entries(value).forEach(([key, entry]) => {
1003
- if (SecretLikeMetadataKeySchema.test(key)) {
1004
- ctx.addIssue({
1005
- code: z.ZodIssueCode.custom,
1006
- path: [...path, key],
1007
- message: `Topology metadata key "${key}" looks secret-like`
1008
- });
1009
- }
1010
- visit(entry, [...path, key]);
1011
- });
1012
- }
1013
- visit(metadata, []);
1014
- });
1015
- var OmTopologySystemInterfaceGrantSchema = z.object({
1016
- consumer: SystemInterfaceRefSchema,
1017
- provider: SystemInterfaceRefSchema,
1018
- resourceIds: z.array(ResourceIdSchema).default([]),
1019
- ontologyIds: z.array(OntologyIdSchema).default([])
1020
- }).strict();
1021
- z.object({
1022
- systemInterfaceGrant: OmTopologySystemInterfaceGrantSchema
1023
- }).strict();
1024
- var OmTopologyRelationshipSchema = z.object({
1025
- from: OmTopologyNodeRefSchema,
1026
- kind: OmTopologyRelationshipKindSchema,
1027
- to: OmTopologyNodeRefSchema,
1028
- systemPath: SystemPathSchema.optional(),
1029
- required: z.boolean().optional(),
1030
- metadata: OmTopologyMetadataSchema.optional()
1031
- });
1032
- var OmTopologyDomainSchema = z.object({
1033
- version: z.literal(1).default(1),
1034
- relationships: z.record(z.string().trim().min(1).max(255), OmTopologyRelationshipSchema).default({})
1035
- }).default({ version: 1, relationships: {} });
1036
- var DEFAULT_ORGANIZATION_MODEL_TOPOLOGY = {
1037
- version: 1,
1038
- relationships: {}
1039
- };
1040
- function idFrom(input) {
1041
- return typeof input === "string" ? input : input.id;
1042
- }
1043
- function parseRef(kind, id) {
1044
- return OmTopologyNodeRefSchema.parse({ kind, id });
1045
- }
1046
- function isNodeRef(input) {
1047
- return OmTopologyNodeRefSchema.safeParse(input).success;
1048
- }
1049
- function isResourceEntry(input) {
1050
- if (typeof input !== "object" || input === null) return false;
1051
- const candidate = input;
1052
- return typeof candidate.id === "string" && typeof candidate.systemPath === "string" && typeof candidate.status === "string" && ["workflow", "agent", "integration", "script"].includes(String(candidate.kind));
1053
- }
1054
- var topologyRef = {
1055
- system: (system) => parseRef("system", idFrom(system)),
1056
- resource: (resource) => parseRef("resource", idFrom(resource)),
1057
- ontology: (record) => parseRef("ontology", idFrom(record)),
1058
- policy: (policy) => parseRef("policy", idFrom(policy)),
1059
- role: (role) => parseRef("role", idFrom(role)),
1060
- trigger: (trigger) => parseRef("trigger", idFrom(trigger)),
1061
- humanCheckpoint: (checkpoint) => parseRef("humanCheckpoint", idFrom(checkpoint)),
1062
- externalResource: (externalResource) => parseRef("externalResource", idFrom(externalResource))
1063
- };
1064
- var topologyRelationship = {
1065
- triggers: (from, to, options = {}) => defineTopologyRelationship({
1066
- ...options,
1067
- from,
1068
- kind: "triggers",
1069
- to
1070
- }),
1071
- uses: (from, to, options = {}) => defineTopologyRelationship({
1072
- ...options,
1073
- from,
1074
- kind: "uses",
1075
- to
1076
- }),
1077
- approval: (from, to, options = {}) => defineTopologyRelationship({
1078
- ...options,
1079
- from,
1080
- kind: "approval",
1081
- to
1082
- }),
1083
- usesIntegration: (from, integration, options = {}) => defineTopologyRelationship({
1084
- required: true,
1085
- ...options,
1086
- from,
1087
- kind: "uses",
1088
- to: integration
1089
- }),
1090
- requestsApproval: (from, checkpoint, options = {}) => defineTopologyRelationship({
1091
- required: true,
1092
- ...options,
1093
- from,
1094
- kind: "approval",
1095
- to: topologyRef.humanCheckpoint(checkpoint)
1096
- }),
1097
- checkpointRoutesTo: (checkpoint, to, options = {}) => defineTopologyRelationship({
1098
- required: true,
1099
- ...options,
1100
- from: topologyRef.humanCheckpoint(checkpoint),
1101
- kind: "triggers",
1102
- to
1103
- })
1104
- };
1105
- function compileTopologyNodeRef(input) {
1106
- if (isNodeRef(input)) return input;
1107
- if (isResourceEntry(input)) return topologyRef.resource(input);
1108
- throw new Error("Topology node refs must be typed node objects or serializable { kind, id } refs");
1109
- }
1110
- function defineTopologyRelationship(input) {
1111
- return OmTopologyRelationshipSchema.parse({
1112
- ...input,
1113
- from: compileTopologyNodeRef(input.from),
1114
- to: compileTopologyNodeRef(input.to)
1115
- });
1116
- }
1117
- function defineTopology(relationships) {
1118
- const entries = Array.isArray(relationships) ? relationships.map((relationship, index) => [`relationship-${index + 1}`, relationship]) : Object.entries(relationships);
1119
- return OmTopologyDomainSchema.parse({
1120
- version: 1,
1121
- relationships: Object.fromEntries(entries.map(([key, relationship]) => [key, defineTopologyRelationship(relationship)]))
1122
- });
1123
- }
1124
- var PolicyIdSchema = ModelIdSchema;
1125
- var PolicyApplicabilitySchema = z.object({
1126
- systemIds: z.array(ModelIdSchema.meta({ ref: "system" })).default([]),
1127
- actionIds: z.array(ModelIdSchema.meta({ ref: "action" })).default([]),
1128
- resourceIds: z.array(ModelIdSchema.meta({ ref: "resource" })).default([]),
1129
- roleIds: z.array(ModelIdSchema.meta({ ref: "role" })).default([])
1130
- });
1131
- var PolicyTriggerSchema = z.discriminatedUnion("kind", [
1132
- z.object({
1133
- kind: z.literal("event"),
1134
- eventId: EventIdSchema.meta({ ref: "event" })
1135
- }),
1136
- z.object({
1137
- kind: z.literal("action-invocation"),
1138
- actionId: ModelIdSchema.meta({ ref: "action" })
1139
- }),
1140
- z.object({
1141
- kind: z.literal("schedule"),
1142
- cron: z.string().trim().min(1).max(120)
1143
- }),
1144
- z.object({
1145
- kind: z.literal("manual")
1146
- })
1147
- ]);
1148
- var PolicyPredicateSchema = z.discriminatedUnion("kind", [
1149
- z.object({
1150
- kind: z.literal("always")
1151
- }),
1152
- z.object({
1153
- kind: z.literal("expression"),
1154
- expression: z.string().trim().min(1).max(2e3)
1155
- }),
1156
- z.object({
1157
- kind: z.literal("threshold"),
1158
- metric: ModelIdSchema,
1159
- operator: z.enum(["lt", "lte", "eq", "gte", "gt"]).meta({ label: "Operator" }),
1160
- value: z.number()
1161
- })
1162
- ]);
1163
- var PolicyEffectSchema = z.discriminatedUnion("kind", [
1164
- z.object({
1165
- kind: z.literal("require-approval"),
1166
- roleId: ModelIdSchema.meta({ ref: "role" }).optional()
1167
- }),
1168
- z.object({
1169
- kind: z.literal("invoke-action"),
1170
- actionId: ModelIdSchema.meta({ ref: "action" })
1171
- }),
1172
- z.object({
1173
- kind: z.literal("notify-role"),
1174
- roleId: ModelIdSchema.meta({ ref: "role" })
1175
- }),
1176
- z.object({
1177
- kind: z.literal("block")
1178
- })
1179
- ]);
1180
- var PolicySchema = z.object({
1181
- id: PolicyIdSchema,
1182
- /** Domain-map iteration order. Convention: multiples of 10 (10, 20, 30, ...) to allow easy insertion. */
1183
- order: z.number(),
1184
- label: LabelSchema,
1185
- description: DescriptionSchema.optional(),
1186
- trigger: PolicyTriggerSchema,
1187
- predicate: PolicyPredicateSchema.default({ kind: "always" }),
1188
- actions: z.array(PolicyEffectSchema).min(1),
1189
- appliesTo: PolicyApplicabilitySchema.default({
1190
- systemIds: [],
1191
- actionIds: [],
1192
- resourceIds: [],
1193
- roleIds: []
1194
- }),
1195
- lifecycle: z.enum(["draft", "beta", "active", "deprecated", "archived"]).meta({ label: "Lifecycle", color: "teal" }).default("active")
1196
- });
1197
- var PoliciesDomainSchema = z.record(z.string(), PolicySchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
1198
- message: "Each policy entry id must match its map key"
1199
- }).default({});
1200
- var DEFAULT_ORGANIZATION_MODEL_POLICIES = {};
1201
- var SurfaceTypeSchema = z.enum(["page", "dashboard", "graph", "detail", "list", "settings"]).meta({ label: "Surface type", color: "blue" });
1202
- var SurfaceDefinitionSchema = z.object({
1203
- id: ModelIdSchema,
1204
- label: LabelSchema,
1205
- path: PathSchema,
1206
- surfaceType: SurfaceTypeSchema,
1207
- description: DescriptionSchema.optional(),
1208
- enabled: z.boolean().default(true),
1209
- devOnly: z.boolean().optional(),
1210
- icon: IconNameSchema.optional(),
1211
- systemIds: z.array(ModelIdSchema.meta({ ref: "system" })).default([]),
1212
- entityIds: z.array(ModelIdSchema.meta({ ref: "entity" })).default([]),
1213
- resourceIds: z.array(ModelIdSchema.meta({ ref: "resource" })).default([]),
1214
- actionIds: z.array(ModelIdSchema.meta({ ref: "action" })).default([]),
1215
- parentId: ModelIdSchema.meta({ ref: "surface" }).optional()
1216
- });
1217
- var SidebarSurfaceTargetsSchema = z.object({
1218
- systems: z.array(ModelIdSchema.meta({ ref: "system" })).default([]).optional(),
1219
- entities: z.array(ModelIdSchema.meta({ ref: "entity" })).default([]).optional(),
1220
- resources: z.array(ModelIdSchema.meta({ ref: "resource" })).default([]).optional(),
1221
- actions: z.array(ModelIdSchema.meta({ ref: "action" })).default([]).optional()
1222
- }).default({});
1223
- var SidebarNodeSchema = z.lazy(
1224
- () => z.discriminatedUnion("type", [
1225
- z.object({
1226
- type: z.literal("group"),
1227
- label: LabelSchema,
1228
- description: DescriptionSchema.optional(),
1229
- icon: IconNameSchema.optional(),
1230
- order: z.number().int().optional(),
1231
- children: z.record(z.string(), SidebarNodeSchema).default({})
1232
- }),
1233
- z.object({
1234
- type: z.literal("surface"),
1235
- label: LabelSchema,
1236
- path: PathSchema,
1237
- surfaceType: SurfaceTypeSchema,
1238
- description: DescriptionSchema.optional(),
1239
- icon: IconNameSchema.optional(),
1240
- order: z.number().int().optional(),
1241
- targets: SidebarSurfaceTargetsSchema.optional(),
1242
- devOnly: z.boolean().optional(),
1243
- requiresAdmin: z.boolean().optional()
1244
- })
1245
- ])
1246
- );
1247
- var SidebarSectionSchema = z.record(z.string(), SidebarNodeSchema).default({});
1248
- var SidebarNavigationSchema = z.object({
1249
- primary: SidebarSectionSchema,
1250
- bottom: SidebarSectionSchema
1251
- }).default({ primary: {}, bottom: {} });
1252
- var OrganizationModelNavigationSchema = z.object({
1253
- sidebar: SidebarNavigationSchema
1254
- }).default({ sidebar: { primary: {}, bottom: {} } });
1255
- function getSortedSidebarEntries(nodes) {
1256
- return Object.entries(nodes).sort(([leftId, left], [rightId, right]) => {
1257
- const orderDelta = (left.order ?? Number.MAX_SAFE_INTEGER) - (right.order ?? Number.MAX_SAFE_INTEGER);
1258
- return orderDelta === 0 ? leftId.localeCompare(rightId) : orderDelta;
1259
- });
1260
- }
1261
- z.object({
1262
- id: ModelIdSchema,
1263
- label: LabelSchema,
1264
- placement: z.string().trim().min(1).max(50),
1265
- surfaceIds: z.array(ModelIdSchema.meta({ ref: "surface" })).default([])
1266
- });
1267
- var KnowledgeTargetKindSchema = z.enum([
1268
- "system",
1269
- "resource",
1270
- "knowledge",
1271
- "stage",
1272
- "action",
1273
- "role",
1274
- "goal",
1275
- "customer-segment",
1276
- "offering",
1277
- "ontology"
1278
- ]).meta({ label: "Target kind" });
1279
- var KnowledgeTargetRefSchema = z.object({
1280
- kind: KnowledgeTargetKindSchema,
1281
- // Ontology targets use the canonical '<scope>:<kind>/<local-id>' ontology id format.
1282
- // Business-logic validation of target existence is done in OrganizationModelSchema.superRefine.
1283
- id: z.string().trim().min(1).max(300)
1284
- }).superRefine((target, ctx) => {
1285
- if (target.kind !== "ontology") return;
1286
- const result = OntologyIdSchema.safeParse(target.id);
1287
- if (!result.success) {
1288
- ctx.addIssue({
1289
- code: z.ZodIssueCode.custom,
1290
- path: ["id"],
1291
- message: "Ontology knowledge targets must use <system-path>:<kind>/<local-id> or global:<kind>/<local-id>"
1292
- });
1293
- }
1294
- });
1295
- var LegacyKnowledgeLinkSchema = z.object({
1296
- nodeId: z.union([NodeIdStringSchema, z.templateLiteral(["ontology:", OntologyIdSchema])])
1297
- }).superRefine((link, ctx) => {
1298
- const [kind] = link.nodeId.split(":");
1299
- if (!KnowledgeTargetKindSchema.safeParse(kind).success) {
1300
- ctx.addIssue({
1301
- code: z.ZodIssueCode.custom,
1302
- path: ["nodeId"],
1303
- message: `Unknown knowledge target kind "${kind}"`
1304
- });
1305
- }
1306
- });
1307
- var CanonicalKnowledgeLinkSchema = z.object({
1308
- target: KnowledgeTargetRefSchema
1309
- });
1310
- function nodeIdFromTarget(target) {
1311
- return `${target.kind}:${target.id}`;
1312
- }
1313
- function targetFromNodeId(nodeId2) {
1314
- const [kind, ...idParts] = nodeId2.split(":");
1315
- return {
1316
- kind: KnowledgeTargetKindSchema.parse(kind),
1317
- id: idParts.join(":")
1318
- };
1319
- }
1320
- var KnowledgeLinkSchema = z.union([CanonicalKnowledgeLinkSchema, LegacyKnowledgeLinkSchema]).transform((link) => {
1321
- const target = "target" in link ? link.target : targetFromNodeId(link.nodeId);
1322
- return {
1323
- target,
1324
- nodeId: nodeIdFromTarget(target)
1325
- };
1326
- });
1327
- var OrgKnowledgeKindSchema = z.enum(["playbook", "strategy", "reference"]).meta({ label: "Knowledge kind", color: "grape" });
1328
- var OrgKnowledgeNodeSchema = z.object({
1329
- id: ModelIdSchema,
1330
- kind: OrgKnowledgeKindSchema,
1331
- title: z.string().trim().min(1).max(200),
1332
- summary: z.string().trim().min(1).max(1e3),
1333
- icon: IconNameSchema.optional(),
1334
- /** Canonical documentation URL when body content is a local summary. */
1335
- externalUrl: z.string().trim().url().max(500).optional(),
1336
- /** Optional generated source file path for local MDX-backed knowledge nodes. */
1337
- sourceFilePath: z.string().trim().min(1).max(500).optional(),
1338
- /** Raw MDX string. Phase 2 will introduce a structured block format. */
1339
- body: z.string().trim().min(1),
1340
- /**
1341
- * Graph links to other OM nodes this knowledge node governs.
1342
- * Each link emits a `governs` edge: knowledge-node -> target node.
1343
- */
1344
- links: z.array(KnowledgeLinkSchema).default([]),
1345
- /** Role identifiers that own this knowledge node. */
1346
- ownerIds: z.array(RoleIdSchema.meta({ ref: "role" })).default([]),
1347
- /** ISO date string (YYYY-MM-DD or full ISO 8601) of last meaningful update. */
1348
- updatedAt: z.string().trim().min(1).max(50)
1349
- });
1350
- var KnowledgeDomainSchema = z.record(ModelIdSchema, OrgKnowledgeNodeSchema).default({});
1351
-
1352
- // ../core/src/organization-model/cross-ref.ts
1353
- var ONTOLOGY_REFERENCE_KEY_KINDS = {
1354
- valueType: "value-type",
1355
- catalogType: "catalog",
1356
- objectType: "object",
1357
- eventType: "event",
1358
- actionType: "action",
1359
- linkType: "link",
1360
- interfaceType: "interface",
1361
- propertyType: "property",
1362
- groupType: "group",
1363
- surfaceType: "surface",
1364
- stepCatalog: "catalog"
1365
- };
1366
- function buildOmCrossRefIndex(model) {
1367
- const systemsById = /* @__PURE__ */ new Map();
1368
- for (const { path, system } of listAllSystems(model)) {
1369
- systemsById.set(path, system);
1370
- systemsById.set(system.id, system);
1371
- }
1372
- const resourceIds = new Set(Object.keys(model.resources ?? {}));
1373
- const knowledgeIds = new Set(Object.keys(model.knowledge ?? {}));
1374
- const roleIds = new Set(Object.keys(model.roles ?? {}));
1375
- const goalIds = new Set(Object.keys(model.goals ?? {}));
1376
- const actionIds = new Set(Object.keys(model.actions ?? {}));
1377
- const customerSegmentIds = new Set(Object.keys(model.customers ?? {}));
1378
- const offeringIds = new Set(Object.keys(model.offerings ?? {}));
1379
- const ontologyCompilation = compileOrganizationOntology(model);
1380
- const ontologyIndexByKind = {
1381
- object: ontologyCompilation.ontology.objectTypes,
1382
- link: ontologyCompilation.ontology.linkTypes,
1383
- action: ontologyCompilation.ontology.actionTypes,
1384
- catalog: ontologyCompilation.ontology.catalogTypes,
1385
- event: ontologyCompilation.ontology.eventTypes,
1386
- interface: ontologyCompilation.ontology.interfaceTypes,
1387
- "value-type": ontologyCompilation.ontology.valueTypes,
1388
- property: ontologyCompilation.ontology.sharedProperties,
1389
- group: ontologyCompilation.ontology.groups,
1390
- surface: ontologyCompilation.ontology.surfaces
1391
- };
1392
- const ontologyIds = new Set(Object.values(ontologyIndexByKind).flatMap((index) => Object.keys(index)));
1393
- const stageIds = /* @__PURE__ */ new Set();
1394
- for (const catalog of Object.values(ontologyCompilation.ontology.catalogTypes)) {
1395
- if (catalog.kind !== "stage") continue;
1396
- const entries = catalog.entries;
1397
- if (entries !== void 0) {
1398
- for (const stageId of Object.keys(entries)) {
1399
- stageIds.add(stageId);
1400
- }
1401
- }
1402
- }
1403
- return {
1404
- systemsById,
1405
- resourceIds,
1406
- knowledgeIds,
1407
- roleIds,
1408
- goalIds,
1409
- actionIds,
1410
- customerSegmentIds,
1411
- offeringIds,
1412
- ontologyIds,
1413
- ontologyIndexByKind,
1414
- stageIds
1415
- };
1416
- }
1417
- function knowledgeTargetExists(index, kind, id) {
1418
- if (kind === "system") return index.systemsById.has(id);
1419
- if (kind === "resource") return index.resourceIds.has(id);
1420
- if (kind === "knowledge") return index.knowledgeIds.has(id);
1421
- if (kind === "stage") return index.stageIds.has(id);
1422
- if (kind === "action") return index.actionIds.has(id);
1423
- if (kind === "role") return index.roleIds.has(id);
1424
- if (kind === "goal") return index.goalIds.has(id);
1425
- if (kind === "customer-segment") return index.customerSegmentIds.has(id);
1426
- if (kind === "offering") return index.offeringIds.has(id);
1427
- if (kind === "ontology") return index.ontologyIds.has(id);
1428
- return false;
1429
- }
1430
-
1431
- // ../core/src/organization-model/schema-refinements.ts
1432
- function addIssue(ctx, path, message) {
1433
- ctx.addIssue({
1434
- code: z.ZodIssueCode.custom,
1435
- path,
1436
- message
1437
- });
1438
- }
1439
- function isLifecycleEnabled(lifecycle, enabled) {
1440
- if (enabled === false) return false;
1441
- return lifecycle !== "deprecated" && lifecycle !== "archived";
1442
- }
1443
- function defaultSystemPathFor(id) {
1444
- return `/${id.replaceAll(".", "/")}`;
1445
- }
1446
- function asRoleHolderArray(heldBy) {
1447
- return Array.isArray(heldBy) ? heldBy : [heldBy];
1448
- }
1449
- function isKnowledgeKindCompatibleWithTarget(knowledgeKind, targetKind) {
1450
- if (knowledgeKind === "reference") return true;
1451
- if (knowledgeKind === "playbook") {
1452
- return ["system", "resource", "stage", "action", "ontology"].includes(targetKind);
1453
- }
1454
- if (knowledgeKind === "strategy") {
1455
- return ["system", "goal", "offering", "customer-segment", "ontology"].includes(targetKind);
1456
- }
1457
- return false;
1458
- }
1459
- function isRecord(value) {
1460
- return typeof value === "object" && value !== null && !Array.isArray(value);
1461
- }
1462
- function refineOrganizationModel(model, ctx) {
1463
- function collectAllSystems(systems, prefix = "", schemaPath = ["systems"]) {
1464
- const result = [];
1465
- for (const [key, system] of Object.entries(systems)) {
1466
- const path = prefix ? `${prefix}.${key}` : key;
1467
- const currentSchemaPath = [...schemaPath, key];
1468
- result.push({ path, schemaPath: currentSchemaPath, system });
1469
- const childSystems = system.systems ?? system.subsystems;
1470
- if (childSystems !== void 0) {
1471
- result.push(
1472
- ...collectAllSystems(childSystems, path, [
1473
- ...currentSchemaPath,
1474
- system.systems !== void 0 ? "systems" : "subsystems"
1475
- ])
1476
- );
1477
- }
1478
- }
1479
- return result;
1480
- }
1481
- const allSystems = collectAllSystems(model.systems);
1482
- const systemsById = /* @__PURE__ */ new Map();
1483
- for (const { path, system } of allSystems) {
1484
- systemsById.set(path, system);
1485
- systemsById.set(system.id, system);
1486
- }
1487
- const systemIdsByEffectivePath = /* @__PURE__ */ new Map();
1488
- allSystems.forEach(({ path, schemaPath, system }) => {
1489
- if (system.parentSystemId !== void 0 && !systemsById.has(system.parentSystemId)) {
1490
- addIssue(
1491
- ctx,
1492
- [...schemaPath, "parentSystemId"],
1493
- `System "${system.id}" references unknown parent "${system.parentSystemId}"`
1494
- );
1495
- }
1496
- const hasChildren = Object.keys(system.systems ?? system.subsystems ?? {}).length > 0 || allSystems.some(
1497
- (candidate) => candidate.path.startsWith(`${path}.`) && !candidate.path.slice(path.length + 1).includes(".")
1498
- );
1499
- const contributesRoutePath = system.ui?.path !== void 0 || system.path !== void 0 || !hasChildren;
1500
- if (contributesRoutePath) {
1501
- const effectivePath = system.ui?.path ?? system.path ?? defaultSystemPathFor(path);
1502
- const existingSystemId = systemIdsByEffectivePath.get(effectivePath);
1503
- if (existingSystemId !== void 0) {
1504
- addIssue(
1505
- ctx,
1506
- [...schemaPath, system.ui?.path !== void 0 ? "ui" : "path"],
1507
- `System "${path}" effective path "${effectivePath}" duplicates system "${existingSystemId}"`
1508
- );
1509
- } else {
1510
- systemIdsByEffectivePath.set(effectivePath, path);
1511
- }
1512
- }
1513
- if (hasChildren && isLifecycleEnabled(system.lifecycle, system.enabled)) {
1514
- const hasEnabledDescendant = Object.values(system.systems ?? system.subsystems ?? {}).some(
1515
- (candidate) => isLifecycleEnabled(candidate.lifecycle, candidate.enabled)
1516
- ) || allSystems.some(
1517
- (candidate) => candidate.path.startsWith(`${path}.`) && !candidate.path.slice(path.length + 1).includes(".") && isLifecycleEnabled(candidate.system.lifecycle, candidate.system.enabled)
1518
- );
1519
- if (!hasEnabledDescendant) {
1520
- addIssue(ctx, [...schemaPath, "lifecycle"], `System "${path}" is active but has no active descendants`);
1521
- }
1522
- }
1523
- });
1524
- allSystems.forEach(({ schemaPath, system }) => {
1525
- const visited = /* @__PURE__ */ new Set();
1526
- let currentParentId = system.parentSystemId;
1527
- while (currentParentId !== void 0) {
1528
- if (currentParentId === system.id || visited.has(currentParentId)) {
1529
- addIssue(ctx, [...schemaPath, "parentSystemId"], `System "${system.id}" has a parent cycle`);
1530
- return;
1531
- }
1532
- visited.add(currentParentId);
1533
- currentParentId = systemsById.get(currentParentId)?.parentSystemId;
1534
- }
1535
- });
1536
- function normalizeRoutePath(path) {
1537
- return path.length > 1 ? path.replace(/\/+$/, "") : path;
1538
- }
1539
- const sidebarNodeIds = /* @__PURE__ */ new Map();
1540
- const sidebarSurfacePaths = /* @__PURE__ */ new Map();
1541
- const sidebarSurfaces = [];
1542
- function collectSidebarNodes(nodes, schemaPath) {
1543
- Object.entries(nodes).forEach(([nodeId2, node]) => {
1544
- const nodePath = [...schemaPath, nodeId2];
1545
- const existingNodePath = sidebarNodeIds.get(nodeId2);
1546
- if (existingNodePath !== void 0) {
1547
- addIssue(ctx, nodePath, `Sidebar node id "${nodeId2}" duplicates another sidebar node`);
1548
- } else {
1549
- sidebarNodeIds.set(nodeId2, nodePath);
1550
- }
1551
- if (node.type === "group") {
1552
- collectSidebarNodes(node.children, [...nodePath, "children"]);
1553
- return;
1554
- }
1555
- sidebarSurfaces.push({ id: nodeId2, node, path: nodePath });
1556
- const normalizedPath = normalizeRoutePath(node.path);
1557
- const existingSurfaceId = sidebarSurfacePaths.get(normalizedPath);
1558
- if (existingSurfaceId !== void 0) {
1559
- addIssue(
1560
- ctx,
1561
- [...nodePath, "path"],
1562
- `Sidebar surface path "${node.path}" duplicates surface "${existingSurfaceId}"`
1563
- );
1564
- } else {
1565
- sidebarSurfacePaths.set(normalizedPath, nodeId2);
1566
- }
1567
- node.targets?.systems?.forEach((systemId, systemIndex) => {
1568
- if (!systemsById.has(systemId)) {
1569
- addIssue(
1570
- ctx,
1571
- [...nodePath, "targets", "systems", systemIndex],
1572
- `Sidebar surface "${nodeId2}" references unknown system "${systemId}"`
1573
- );
1574
- }
1575
- });
1576
- });
1577
- }
1578
- collectSidebarNodes(model.navigation.sidebar.primary, ["navigation", "sidebar", "primary"]);
1579
- collectSidebarNodes(model.navigation.sidebar.bottom, ["navigation", "sidebar", "bottom"]);
1580
- const segmentsById = new Map(Object.entries(model.customers));
1581
- Object.values(model.offerings).forEach((product) => {
1582
- product.targetSegmentIds.forEach((segmentId, segmentIndex) => {
1583
- if (!segmentsById.has(segmentId)) {
1584
- addIssue(
1585
- ctx,
1586
- ["offerings", product.id, "targetSegmentIds", segmentIndex],
1587
- `Product "${product.id}" references unknown customer segment "${segmentId}"`
1588
- );
1589
- }
1590
- });
1591
- if (product.deliveryFeatureId !== void 0 && !systemsById.has(product.deliveryFeatureId)) {
1592
- addIssue(
1593
- ctx,
1594
- ["offerings", product.id, "deliveryFeatureId"],
1595
- `Product "${product.id}" references unknown delivery system "${product.deliveryFeatureId}"`
1596
- );
1597
- }
1598
- });
1599
- Object.values(model.goals).forEach((objective) => {
1600
- if (objective.periodEnd <= objective.periodStart) {
1601
- addIssue(
1602
- ctx,
1603
- ["goals", objective.id, "periodEnd"],
1604
- `Goal "${objective.id}" has periodEnd "${objective.periodEnd}" which must be strictly after periodStart "${objective.periodStart}"`
1605
- );
1606
- }
1607
- });
1608
- const goalsById = new Map(Object.entries(model.goals));
1609
- const knowledgeById = new Map(Object.entries(model.knowledge));
1610
- const actionsById = new Map(Object.entries(model.actions));
1611
- const entitiesById = new Map(Object.entries(model.entities));
1612
- const policiesById = new Map(Object.entries(model.policies));
1613
- sidebarSurfaces.forEach(({ id, node, path }) => {
1614
- node.targets?.entities?.forEach((entityId, entityIndex) => {
1615
- if (!entitiesById.has(entityId)) {
1616
- addIssue(
1617
- ctx,
1618
- [...path, "targets", "entities", entityIndex],
1619
- `Sidebar surface "${id}" references unknown entity "${entityId}"`
1620
- );
1621
- }
1622
- });
1623
- node.targets?.actions?.forEach((actionId, actionIndex) => {
1624
- if (!actionsById.has(actionId)) {
1625
- addIssue(
1626
- ctx,
1627
- [...path, "targets", "actions", actionIndex],
1628
- `Sidebar surface "${id}" references unknown action "${actionId}"`
1629
- );
1630
- }
1631
- });
1632
- });
1633
- Object.values(model.entities).forEach((entity) => {
1634
- if (systemsById.size > 0 && !systemsById.has(entity.ownedBySystemId)) {
1635
- addIssue(
1636
- ctx,
1637
- ["entities", entity.id, "ownedBySystemId"],
1638
- `Entity "${entity.id}" references unknown ownedBySystemId "${entity.ownedBySystemId}"`
1639
- );
1640
- }
1641
- entity.links?.forEach((link, linkIndex) => {
1642
- if (!entitiesById.has(link.toEntity)) {
1643
- addIssue(
1644
- ctx,
1645
- ["entities", entity.id, "links", linkIndex, "toEntity"],
1646
- `Entity "${entity.id}" links to unknown entity "${link.toEntity}"`
1647
- );
1648
- }
1649
- });
1650
- });
1651
- const rolesById = new Map(Object.entries(model.roles));
1652
- Object.values(model.roles).forEach((role) => {
1653
- if (role.reportsToId !== void 0 && !rolesById.has(role.reportsToId)) {
1654
- addIssue(
1655
- ctx,
1656
- ["roles", role.id, "reportsToId"],
1657
- `Role "${role.id}" references unknown reportsToId "${role.reportsToId}"`
1658
- );
1659
- }
1660
- });
1661
- Object.values(model.roles).forEach((role) => {
1662
- const visited = /* @__PURE__ */ new Set();
1663
- let currentReportsToId = role.reportsToId;
1664
- while (currentReportsToId !== void 0) {
1665
- if (currentReportsToId === role.id || visited.has(currentReportsToId)) {
1666
- addIssue(ctx, ["roles", role.id, "reportsToId"], `Role "${role.id}" has a reportsToId cycle`);
1667
- return;
1668
- }
1669
- visited.add(currentReportsToId);
1670
- currentReportsToId = rolesById.get(currentReportsToId)?.reportsToId;
1671
- }
1672
- });
1673
- Object.values(model.roles).forEach((role) => {
1674
- role.responsibleFor?.forEach((systemId, systemIndex) => {
1675
- if (!systemsById.has(systemId)) {
1676
- addIssue(
1677
- ctx,
1678
- ["roles", role.id, "responsibleFor", systemIndex],
1679
- `Role "${role.id}" references unknown responsibleFor system "${systemId}"`
1680
- );
1681
- }
1682
- });
1683
- });
1684
- allSystems.forEach(({ schemaPath, system }) => {
1685
- if (system.responsibleRoleId !== void 0 && !rolesById.has(system.responsibleRoleId)) {
1686
- addIssue(
1687
- ctx,
1688
- [...schemaPath, "responsibleRoleId"],
1689
- `System "${system.id}" references unknown responsibleRoleId "${system.responsibleRoleId}"`
1690
- );
1691
- }
1692
- system.governedByKnowledge?.forEach((nodeId2, nodeIndex) => {
1693
- if (!knowledgeById.has(nodeId2)) {
1694
- addIssue(
1695
- ctx,
1696
- [...schemaPath, "governedByKnowledge", nodeIndex],
1697
- `System "${system.id}" references unknown knowledge node "${nodeId2}"`
1698
- );
1699
- }
1700
- });
1701
- system.drivesGoals?.forEach((goalId, goalIndex) => {
1702
- if (!goalsById.has(goalId)) {
1703
- addIssue(
1704
- ctx,
1705
- [...schemaPath, "drivesGoals", goalIndex],
1706
- `System "${system.id}" references unknown goal "${goalId}"`
1707
- );
1708
- }
1709
- });
1710
- system.actions?.forEach((actionRef, actionIndex) => {
1711
- if (!actionsById.has(actionRef.actionId)) {
1712
- addIssue(
1713
- ctx,
1714
- [...schemaPath, "actions", actionIndex, "actionId"],
1715
- `System "${system.id}" references unknown action "${actionRef.actionId}"`
1716
- );
1717
- }
1718
- });
1719
- system.policies?.forEach((policyId, policyIndex) => {
1720
- if (!policiesById.has(policyId)) {
1721
- addIssue(
1722
- ctx,
1723
- [...schemaPath, "policies", policyIndex],
1724
- `System "${system.id}" references unknown policy "${policyId}"`
1725
- );
1726
- }
1727
- });
1728
- });
1729
- Object.values(model.actions).forEach((action) => {
1730
- action.affects?.forEach((entityId, entityIndex) => {
1731
- if (!entitiesById.has(entityId)) {
1732
- addIssue(
1733
- ctx,
1734
- ["actions", action.id, "affects", entityIndex],
1735
- `Action "${action.id}" affects unknown entity "${entityId}"`
1736
- );
1737
- }
1738
- });
1739
- });
1740
- const resourcesById = new Map(Object.entries(model.resources));
1741
- sidebarSurfaces.forEach(({ id, node, path }) => {
1742
- node.targets?.resources?.forEach((resourceId, resourceIndex) => {
1743
- if (!resourcesById.has(resourceId)) {
1744
- addIssue(
1745
- ctx,
1746
- [...path, "targets", "resources", resourceIndex],
1747
- `Sidebar surface "${id}" references unknown resource "${resourceId}"`
1748
- );
1749
- }
1750
- });
1751
- });
1752
- const idx = buildOmCrossRefIndex(model);
1753
- const { ontologyIndexByKind, ontologyIds } = idx;
1754
- const ontologyCompilation = compileOrganizationOntology(model);
1755
- function topologyTargetExists(ref) {
1756
- if (ref.kind === "system") return systemsById.has(ref.id);
1757
- if (ref.kind === "resource") return resourcesById.has(ref.id);
1758
- if (ref.kind === "ontology") return ontologyIds.has(ref.id);
1759
- if (ref.kind === "policy") return policiesById.has(ref.id);
1760
- if (ref.kind === "role") return rolesById.has(ref.id);
1761
- return true;
1762
- }
1763
- Object.entries(model.topology.relationships).forEach(([relationshipId, relationship]) => {
1764
- ["from", "to"].forEach((side) => {
1765
- const ref = relationship[side];
1766
- if (topologyTargetExists(ref)) return;
1767
- addIssue(
1768
- ctx,
1769
- ["topology", "relationships", relationshipId, side],
1770
- `Topology relationship "${relationshipId}" ${side} references unknown ${ref.kind} "${ref.id}"`
1771
- );
1772
- });
1773
- });
1774
- function validateKnownOntologyReferences(ownerId, value, path, seen = /* @__PURE__ */ new WeakSet()) {
1775
- if (Array.isArray(value)) {
1776
- value.forEach((entry, index) => validateKnownOntologyReferences(ownerId, entry, [...path, index], seen));
1777
- return;
1778
- }
1779
- if (!isRecord(value)) return;
1780
- if (seen.has(value)) return;
1781
- seen.add(value);
1782
- Object.entries(value).forEach(([key, entry]) => {
1783
- const expectedKind = ONTOLOGY_REFERENCE_KEY_KINDS[key];
1784
- if (expectedKind !== void 0) {
1785
- if (typeof entry !== "string") {
1786
- addIssue(ctx, [...path, key], `Ontology record "${ownerId}" ${key} must be an ontology ID string`);
1787
- } else if (ontologyIndexByKind[expectedKind][entry] === void 0) {
1788
- addIssue(
1789
- ctx,
1790
- [...path, key],
1791
- `Ontology record "${ownerId}" ${key} references unknown ${expectedKind} ontology ID "${entry}"`
1792
- );
1793
- }
1794
- }
1795
- validateKnownOntologyReferences(ownerId, entry, [...path, key], seen);
1796
- });
1797
- }
1798
- for (const { id, record } of listResolvedOntologyRecords(ontologyCompilation.ontology)) {
1799
- validateKnownOntologyReferences(id, record, record.origin.path);
1800
- }
1801
- Object.values(model.policies).forEach((policy) => {
1802
- policy.appliesTo.systemIds.forEach((systemId, systemIndex) => {
1803
- if (!systemsById.has(systemId)) {
1804
- addIssue(
1805
- ctx,
1806
- ["policies", policy.id, "appliesTo", "systemIds", systemIndex],
1807
- `Policy "${policy.id}" applies to unknown system "${systemId}"`
1808
- );
1809
- }
1810
- });
1811
- policy.appliesTo.actionIds.forEach((actionId, actionIndex) => {
1812
- if (!actionsById.has(actionId)) {
1813
- addIssue(
1814
- ctx,
1815
- ["policies", policy.id, "appliesTo", "actionIds", actionIndex],
1816
- `Policy "${policy.id}" applies to unknown action "${actionId}"`
1817
- );
1818
- }
1819
- });
1820
- policy.actions.forEach((action, actionIndex) => {
1821
- if (action.kind === "invoke-action" && !actionsById.has(action.actionId)) {
1822
- addIssue(
1823
- ctx,
1824
- ["policies", policy.id, "actions", actionIndex, "actionId"],
1825
- `Policy "${policy.id}" invokes unknown action "${action.actionId}"`
1826
- );
1827
- }
1828
- if ((action.kind === "notify-role" || action.kind === "require-approval") && action.roleId !== void 0 && !rolesById.has(action.roleId)) {
1829
- addIssue(
1830
- ctx,
1831
- ["policies", policy.id, "actions", actionIndex, "roleId"],
1832
- `Policy "${policy.id}" references unknown role "${action.roleId}"`
1833
- );
1834
- }
1835
- });
1836
- if (policy.trigger.kind === "action-invocation" && !actionsById.has(policy.trigger.actionId)) {
1837
- addIssue(
1838
- ctx,
1839
- ["policies", policy.id, "trigger", "actionId"],
1840
- `Policy "${policy.id}" references unknown trigger action "${policy.trigger.actionId}"`
1841
- );
1842
- }
1843
- });
1844
- Object.entries(model.knowledge).forEach(([nodeId2, node]) => {
1845
- node.links.forEach((link, linkIndex) => {
1846
- if (!knowledgeTargetExists(idx, link.target.kind, link.target.id)) {
1847
- addIssue(
1848
- ctx,
1849
- ["knowledge", nodeId2, "links", linkIndex, "target"],
1850
- `Knowledge node "${node.id}" references unknown ${link.target.kind} target "${link.target.id}"`
1851
- );
1852
- }
1853
- if (!isKnowledgeKindCompatibleWithTarget(node.kind, link.target.kind)) {
1854
- addIssue(
1855
- ctx,
1856
- ["knowledge", nodeId2, "links", linkIndex, "target", "kind"],
1857
- `Knowledge node "${node.id}" kind "${node.kind}" cannot govern ${link.target.kind} targets`
1858
- );
1859
- }
1860
- });
1861
- });
1862
- Object.values(model.resources).forEach((resource) => {
1863
- if (!systemsById.has(resource.systemPath)) {
1864
- addIssue(
1865
- ctx,
1866
- ["resources", resource.id, "systemPath"],
1867
- `Resource "${resource.id}" references unknown system path "${resource.systemPath}"`
1868
- );
1869
- }
1870
- if (resource.ownerRoleId !== void 0 && !rolesById.has(resource.ownerRoleId)) {
1871
- addIssue(
1872
- ctx,
1873
- ["resources", resource.id, "ownerRoleId"],
1874
- `Resource "${resource.id}" references unknown ownerRoleId "${resource.ownerRoleId}"`
1875
- );
1876
- }
1877
- if (resource.kind === "agent" && resource.actsAsRoleId !== void 0 && !rolesById.has(resource.actsAsRoleId)) {
1878
- addIssue(
1879
- ctx,
1880
- ["resources", resource.id, "actsAsRoleId"],
1881
- `Agent resource "${resource.id}" references unknown actsAsRoleId "${resource.actsAsRoleId}"`
1882
- );
1883
- }
1884
- });
1885
- allSystems.forEach(({ path: systemPath, schemaPath, system }) => {
1886
- system.apiInterface?.resourceIds?.forEach((resourceId, resourceIndex) => {
1887
- const resource = resourcesById.get(resourceId);
1888
- if (resource === void 0) {
1889
- addIssue(
1890
- ctx,
1891
- [...schemaPath, "apiInterface", "resourceIds", resourceIndex],
1892
- `System Interface "${systemPath}/api" scopes unknown resource "${resourceId}"`
1893
- );
1894
- return;
1895
- }
1896
- if (resource.systemPath !== systemPath) {
1897
- addIssue(
1898
- ctx,
1899
- [...schemaPath, "apiInterface", "resourceIds", resourceIndex],
1900
- `System Interface "${systemPath}/api" scopes resource "${resourceId}" from system "${resource.systemPath}"`
1901
- );
1902
- }
1903
- });
1904
- });
1905
- function validateResourceOntologyBinding(resourceId, bindingKey, expectedKind, ids) {
1906
- const ontologyIds2 = ids === void 0 ? [] : Array.isArray(ids) ? ids : [ids];
1907
- ontologyIds2.forEach((ontologyId, ontologyIndex) => {
1908
- if (ontologyIndexByKind[expectedKind][ontologyId] === void 0) {
1909
- addIssue(
1910
- ctx,
1911
- ["resources", resourceId, "ontology", bindingKey, ...Array.isArray(ids) ? [ontologyIndex] : []],
1912
- `Resource "${resourceId}" ontology binding "${bindingKey}" references unknown ${expectedKind} ontology ID "${ontologyId}"`
1913
- );
1914
- }
1915
- });
1916
- }
1917
- Object.values(model.resources).forEach((resource) => {
1918
- const binding = resource.ontology;
1919
- if (binding === void 0) return;
1920
- validateResourceOntologyBinding(resource.id, "actions", "action", binding.actions);
1921
- validateResourceOntologyBinding(resource.id, "primaryAction", "action", binding.primaryAction);
1922
- validateResourceOntologyBinding(resource.id, "reads", "object", binding.reads);
1923
- validateResourceOntologyBinding(resource.id, "writes", "object", binding.writes);
1924
- validateResourceOntologyBinding(resource.id, "usesCatalogs", "catalog", binding.usesCatalogs);
1925
- validateResourceOntologyBinding(resource.id, "emits", "event", binding.emits);
1926
- if (binding.contract !== void 0) {
1927
- const contractEntries = [
1928
- ["input", binding.contract.input],
1929
- ["output", binding.contract.output]
1930
- ];
1931
- for (const [side, ref] of contractEntries) {
1932
- if (ref === void 0) continue;
1933
- const result = ContractRefSchema.safeParse(ref);
1934
- if (!result.success) {
1935
- addIssue(
1936
- ctx,
1937
- ["resources", resource.id, "ontology", "contract", side],
1938
- `Resource "${resource.id}" contract.${side} "${ref}" is not a valid ContractRef (expected "package/subpath#ExportName")`
1939
- );
1940
- }
1941
- }
1942
- }
1943
- });
1944
- Object.values(model.roles).forEach((role) => {
1945
- if (role.heldBy === void 0) return;
1946
- asRoleHolderArray(role.heldBy).forEach((holder, holderIndex) => {
1947
- if (holder.kind !== "agent") return;
1948
- const resource = resourcesById.get(holder.agentId);
1949
- if (resource === void 0) {
1950
- addIssue(
1951
- ctx,
1952
- ["roles", role.id, "heldBy", Array.isArray(role.heldBy) ? holderIndex : "agentId"],
1953
- `Role "${role.id}" references unknown agent holder resource "${holder.agentId}"`
1954
- );
1955
- return;
1956
- }
1957
- if (resource.kind !== "agent") {
1958
- addIssue(
1959
- ctx,
1960
- ["roles", role.id, "heldBy", Array.isArray(role.heldBy) ? holderIndex : "agentId"],
1961
- `Role "${role.id}" agent holder "${holder.agentId}" must reference an agent resource`
1962
- );
1963
- }
1964
- });
1965
- });
1966
- Object.entries(model.knowledge).forEach(([nodeId2, node]) => {
1967
- node.ownerIds.forEach((roleId, ownerIndex) => {
1968
- if (!rolesById.has(roleId)) {
1969
- addIssue(
1970
- ctx,
1971
- ["knowledge", nodeId2, "ownerIds", ownerIndex],
1972
- `Knowledge node "${node.id}" references unknown owner role "${roleId}"`
1973
- );
1974
- }
1975
- });
1976
- });
1977
- for (const diagnostic of ontologyCompilation.diagnostics) {
1978
- addIssue(ctx, diagnostic.path, diagnostic.message);
1979
- }
1980
- }
1981
-
1982
- // ../core/src/organization-model/schema.ts
1983
- z.enum([
1984
- "branding",
1985
- "identity",
1986
- "customers",
1987
- "offerings",
1988
- "roles",
1989
- "goals",
1990
- "systems",
1991
- "ontology",
1992
- "resources",
1993
- "topology",
1994
- "actions",
1995
- "entities",
1996
- "policies",
1997
- "knowledge"
1998
- ]);
1999
- var OrganizationModelDomainMetadataSchema = z.object({
2000
- version: z.literal(1).default(1),
2001
- lastModified: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "lastModified must be an ISO date string (YYYY-MM-DD)")
2002
- });
2003
- var DEFAULT_ORGANIZATION_MODEL_DOMAIN_METADATA = {
2004
- branding: { version: 1, lastModified: "2026-05-10" },
2005
- identity: { version: 1, lastModified: "2026-05-10" },
2006
- customers: { version: 1, lastModified: "2026-05-10" },
2007
- offerings: { version: 1, lastModified: "2026-05-10" },
2008
- roles: { version: 1, lastModified: "2026-05-10" },
2009
- goals: { version: 1, lastModified: "2026-05-10" },
2010
- systems: { version: 1, lastModified: "2026-05-10" },
2011
- ontology: { version: 1, lastModified: "2026-05-14" },
2012
- resources: { version: 1, lastModified: "2026-05-10" },
2013
- topology: { version: 1, lastModified: "2026-05-14" },
2014
- actions: { version: 1, lastModified: "2026-05-10" },
2015
- entities: { version: 1, lastModified: "2026-05-10" },
2016
- policies: { version: 1, lastModified: "2026-05-10" },
2017
- knowledge: { version: 1, lastModified: "2026-05-10" }
2018
- };
2019
- var OrganizationModelDomainMetadataByDomainSchema = z.object({
2020
- branding: OrganizationModelDomainMetadataSchema,
2021
- identity: OrganizationModelDomainMetadataSchema,
2022
- customers: OrganizationModelDomainMetadataSchema,
2023
- offerings: OrganizationModelDomainMetadataSchema,
2024
- roles: OrganizationModelDomainMetadataSchema,
2025
- goals: OrganizationModelDomainMetadataSchema,
2026
- systems: OrganizationModelDomainMetadataSchema,
2027
- ontology: OrganizationModelDomainMetadataSchema,
2028
- resources: OrganizationModelDomainMetadataSchema,
2029
- topology: OrganizationModelDomainMetadataSchema,
2030
- actions: OrganizationModelDomainMetadataSchema,
2031
- entities: OrganizationModelDomainMetadataSchema,
2032
- policies: OrganizationModelDomainMetadataSchema,
2033
- knowledge: OrganizationModelDomainMetadataSchema
2034
- }).partial().default(DEFAULT_ORGANIZATION_MODEL_DOMAIN_METADATA).transform((metadata) => ({ ...DEFAULT_ORGANIZATION_MODEL_DOMAIN_METADATA, ...metadata }));
2035
- var OrganizationModelSchemaBase = z.object({
2036
- version: z.literal(1).default(1),
2037
- domainMetadata: OrganizationModelDomainMetadataByDomainSchema,
2038
- branding: OrganizationModelBrandingSchema.default(DEFAULT_ORGANIZATION_MODEL_BRANDING),
2039
- navigation: OrganizationModelNavigationSchema,
2040
- identity: IdentityDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_IDENTITY),
2041
- customers: CustomersDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_CUSTOMERS),
2042
- offerings: OfferingsDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_OFFERINGS),
2043
- roles: RolesDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_ROLES),
2044
- goals: GoalsDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_GOALS),
2045
- systems: SystemsDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_SYSTEMS),
2046
- ontology: OntologyScopeSchema.default(DEFAULT_ONTOLOGY_SCOPE),
2047
- resources: ResourcesDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_RESOURCES),
2048
- topology: OmTopologyDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_TOPOLOGY),
2049
- actions: ActionsDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_ACTIONS),
2050
- entities: EntitiesDomainSchema.default({}),
2051
- policies: PoliciesDomainSchema.default(DEFAULT_ORGANIZATION_MODEL_POLICIES),
2052
- // D3: flat Record<id, OrgKnowledgeNode> — no wrapper object
2053
- knowledge: KnowledgeDomainSchema.default({})
2054
- });
2055
- var OrganizationModelSchema = OrganizationModelSchemaBase.superRefine(refineOrganizationModel);
2056
-
2057
- // ../core/src/organization-model/defaults.ts
2058
- var DEFAULT_ORGANIZATION_MODEL_KNOWLEDGE = {};
2059
- var DEFAULT_ORGANIZATION_MODEL_ENTITIES = {};
2060
- var DEFAULT_ORGANIZATION_MODEL_NAVIGATION = {
2061
- sidebar: {
2062
- primary: {},
2063
- bottom: {}
2064
- }
2065
- };
2066
- var DEFAULT_ORGANIZATION_MODEL = {
2067
- version: 1,
2068
- domainMetadata: DEFAULT_ORGANIZATION_MODEL_DOMAIN_METADATA,
2069
- branding: DEFAULT_ORGANIZATION_MODEL_BRANDING,
2070
- navigation: DEFAULT_ORGANIZATION_MODEL_NAVIGATION,
2071
- identity: DEFAULT_ORGANIZATION_MODEL_IDENTITY,
2072
- customers: DEFAULT_ORGANIZATION_MODEL_CUSTOMERS,
2073
- offerings: DEFAULT_ORGANIZATION_MODEL_OFFERINGS,
2074
- roles: DEFAULT_ORGANIZATION_MODEL_ROLES,
2075
- goals: DEFAULT_ORGANIZATION_MODEL_GOALS,
2076
- // Generic empty systems map. Elevasis-specific systems (platform, sales, sales.crm,
2077
- // sales.lead-gen, monitoring, settings, admin, etc.) have been relocated to
2078
- // `@repo/elevasis-core/src/organization-model/systems.ts` via `canonicalOrganizationModel`.
2079
- // Tenant OM configs supply their own systems via `resolveOrganizationModel`.
2080
- systems: {},
2081
- ontology: DEFAULT_ONTOLOGY_SCOPE,
2082
- resources: DEFAULT_ORGANIZATION_MODEL_RESOURCES,
2083
- topology: DEFAULT_ORGANIZATION_MODEL_TOPOLOGY,
2084
- // Generic empty actions map. Elevasis-specific action entries have been relocated to
2085
- // `@repo/elevasis-core/src/organization-model/actions.ts`.
2086
- actions: {},
2087
- entities: DEFAULT_ORGANIZATION_MODEL_ENTITIES,
2088
- policies: DEFAULT_ORGANIZATION_MODEL_POLICIES,
2089
- knowledge: DEFAULT_ORGANIZATION_MODEL_KNOWLEDGE
2090
- };
2091
-
2092
- // ../core/src/organization-model/resolve.ts
2093
- function isPlainObject(value) {
2094
- return typeof value === "object" && value !== null && !Array.isArray(value);
2095
- }
2096
- function collectNestedSystemPaths(systems, prefix = "") {
2097
- const paths = /* @__PURE__ */ new Set();
2098
- for (const [key, value] of Object.entries(systems)) {
2099
- if (!isPlainObject(value)) continue;
2100
- const path = prefix ? `${prefix}.${key}` : key;
2101
- for (const childKey of ["systems", "subsystems"]) {
2102
- const childSystems = value[childKey];
2103
- if (!isPlainObject(childSystems)) continue;
2104
- for (const childPath of collectNestedSystemPaths(childSystems, path)) {
2105
- paths.add(childPath);
2106
- }
2107
- }
2108
- if (prefix !== "") {
2109
- paths.add(path);
2110
- }
2111
- }
2112
- return paths;
2113
- }
2114
- function pruneFlatSystemDescendantCollisions(base, override) {
2115
- const result = { ...base };
2116
- for (const nestedPath of collectNestedSystemPaths(override)) {
2117
- delete result[nestedPath];
2118
- }
2119
- return result;
2120
- }
2121
- function deepMerge(base, override) {
2122
- if (override === void 0) {
2123
- return base;
2124
- }
2125
- if (Array.isArray(base)) {
2126
- return override ?? base;
2127
- }
2128
- if (!isPlainObject(base) || !isPlainObject(override)) {
2129
- return override ?? base;
2130
- }
2131
- const result = { ...base };
2132
- for (const [key, value] of Object.entries(override)) {
2133
- if (value === void 0) continue;
2134
- const existing = result[key];
2135
- if (key === "systems" && isPlainObject(existing) && isPlainObject(value)) {
2136
- result[key] = deepMerge(pruneFlatSystemDescendantCollisions(existing, value), value);
2137
- continue;
2138
- }
2139
- result[key] = isPlainObject(existing) && isPlainObject(value) ? deepMerge(existing, value) : value;
2140
- }
2141
- return result;
2142
- }
2143
- function resolveOrganizationModel(override, organizationIdOrOptions, options) {
2144
- const resolvedOptions = typeof organizationIdOrOptions === "object" ? organizationIdOrOptions : options;
2145
- const mergeDefaults = resolvedOptions?.mergeDefaults ?? true;
2146
- const merged = mergeDefaults ? deepMerge(DEFAULT_ORGANIZATION_MODEL, override) : override ?? {};
2147
- return OrganizationModelSchema.parse(merged);
2148
- }
2149
- var OrganizationGraphNodeKindSchema = z.enum([
2150
- "organization",
2151
- "system",
2152
- "role",
2153
- "action",
2154
- "entity",
2155
- "event",
2156
- "policy",
2157
- "stage",
2158
- "resource",
2159
- "knowledge",
2160
- "customer-segment",
2161
- "offering",
2162
- "goal",
2163
- "surface",
2164
- "navigation-group",
2165
- // Ontology records are projected from compiled System.ontology scopes.
2166
- "ontology"
2167
- ]);
2168
- var OrganizationGraphEdgeKindSchema = z.enum([
2169
- "contains",
2170
- "references",
2171
- "maps_to",
2172
- "uses",
2173
- "governs",
2174
- "links",
2175
- "affects",
2176
- "emits",
2177
- "originates_from",
2178
- "triggers",
2179
- "approval",
2180
- "applies_to",
2181
- "effects",
2182
- "actions",
2183
- "reads",
2184
- "writes",
2185
- "uses_catalog"
2186
- ]);
2187
- var OrganizationGraphNodeSchema = z.object({
2188
- id: z.string().trim().min(1).max(400),
2189
- kind: OrganizationGraphNodeKindSchema,
2190
- label: LabelSchema,
2191
- sourceId: z.string().trim().min(1).max(400).optional(),
2192
- description: DescriptionSchema.optional(),
2193
- icon: IconNameSchema.optional(),
2194
- enabled: z.boolean().optional(),
2195
- ontologyKind: z.string().trim().min(1).max(80).optional(),
2196
- resourceType: z.enum(["workflow", "agent", "trigger", "integration", "external", "human_checkpoint", "script"]).optional()
2197
- });
2198
- var OrganizationGraphEdgeSchema = z.object({
2199
- id: z.string().trim().min(1).max(900),
2200
- kind: OrganizationGraphEdgeKindSchema,
2201
- sourceId: z.string().trim().min(1).max(400),
2202
- targetId: z.string().trim().min(1).max(400),
2203
- label: z.string().trim().min(1).max(120).optional(),
2204
- relationshipType: z.enum(["triggers", "uses", "approval"]).optional()
2205
- });
2206
- var OrganizationGraphSchema = z.object({
2207
- version: z.literal(1),
2208
- organizationModelVersion: OrganizationModelSchema.shape.version,
2209
- nodes: z.array(OrganizationGraphNodeSchema),
2210
- edges: z.array(OrganizationGraphEdgeSchema)
2211
- });
2212
- var BuildOrganizationGraphInputSchema = z.object({
2213
- organizationModel: OrganizationModelSchema,
2214
- commandViewData: z.unknown().optional()
2215
- });
2216
-
2217
- // ../core/src/organization-model/graph/build.ts
2218
- function nodeId(kind, sourceId) {
2219
- return kind === "organization" ? "organization-model" : `${kind}:${sourceId ?? ""}`;
2220
- }
2221
- function edgeId(kind, sourceId, targetId, variant) {
2222
- return variant ? `edge:${kind}:${variant}:${sourceId}:${targetId}` : `edge:${kind}:${sourceId}:${targetId}`;
2223
- }
2224
- function pushUniqueNode(nodes, seen, node) {
2225
- if (seen.has(node.id)) return;
2226
- seen.add(node.id);
2227
- nodes.push(node);
2228
- }
2229
- function pushUniqueEdge(edges, seen, edge) {
2230
- if (seen.has(edge.id)) return;
2231
- seen.add(edge.id);
2232
- edges.push(edge);
2233
- }
2234
- function collectSidebarGraphNodes(nodes, groups, surfaces, parentGroupId) {
2235
- Object.entries(nodes).sort(([leftId, left], [rightId, right]) => {
2236
- const orderDelta = (left.order ?? Number.MAX_SAFE_INTEGER) - (right.order ?? Number.MAX_SAFE_INTEGER);
2237
- return orderDelta === 0 ? leftId.localeCompare(rightId) : orderDelta;
2238
- }).forEach(([id, node]) => {
2239
- if (node.type === "group") {
2240
- groups.push({ id, node, ...parentGroupId !== void 0 ? { parentGroupId } : {} });
2241
- collectSidebarGraphNodes(node.children, groups, surfaces, id);
2242
- return;
2243
- }
2244
- surfaces.push({ id, node, ...parentGroupId !== void 0 ? { parentGroupId } : {} });
2245
- });
2246
- }
2247
- function upsertResourceNode(nodes, seen, resourceNodesById, node) {
2248
- const existing = resourceNodesById.get(node.id);
2249
- if (existing) {
2250
- if (!existing.label || existing.label === existing.sourceId) {
2251
- existing.label = node.label;
2252
- }
2253
- if (!existing.description && node.description) {
2254
- existing.description = node.description;
2255
- }
2256
- if (!existing.sourceId && node.sourceId) {
2257
- existing.sourceId = node.sourceId;
2258
- }
2259
- if (!existing.resourceType && node.resourceType) {
2260
- existing.resourceType = node.resourceType;
2261
- }
2262
- return existing;
2263
- }
2264
- resourceNodesById.set(node.id, node);
2265
- pushUniqueNode(nodes, seen, node);
2266
- return node;
2267
- }
2268
- function ensureResourceNode(nodes, seen, resourceNodesById, resourceId) {
2269
- const existing = resourceNodesById.get(nodeId("resource", resourceId));
2270
- if (existing) return existing;
2271
- return upsertResourceNode(nodes, seen, resourceNodesById, {
2272
- id: nodeId("resource", resourceId),
2273
- kind: "resource",
2274
- label: resourceId,
2275
- sourceId: resourceId
2276
- });
2277
- }
2278
- function normalizeCommandViewResourceType(resourceType) {
2279
- return resourceType === "human" ? "human_checkpoint" : resourceType;
2280
- }
2281
- function normalizeOrganizationModelResourceType(resourceType) {
2282
- return resourceType;
2283
- }
2284
- function collectCommandViewResources(commandViewData) {
2285
- return [
2286
- ...commandViewData.workflows,
2287
- ...commandViewData.agents,
2288
- ...commandViewData.triggers,
2289
- ...commandViewData.integrations,
2290
- ...commandViewData.externalResources,
2291
- ...commandViewData.humanCheckpoints
2292
- ];
2293
- }
2294
- function invocationSignature(invocation) {
2295
- switch (invocation.kind) {
2296
- case "slash-command":
2297
- return `${invocation.kind}:${invocation.command}`;
2298
- case "mcp-tool":
2299
- return `${invocation.kind}:${invocation.server}:${invocation.name}`;
2300
- case "api-endpoint":
2301
- return `${invocation.kind}:${invocation.method}:${invocation.path}`;
2302
- case "script-execution":
2303
- return `${invocation.kind}:${invocation.resourceId}`;
2304
- }
2305
- }
2306
- function invocationLabel(invocation) {
2307
- switch (invocation.kind) {
2308
- case "slash-command":
2309
- return invocation.command;
2310
- case "mcp-tool":
2311
- return `${invocation.server}.${invocation.name}`;
2312
- case "api-endpoint":
2313
- return `${invocation.method} ${invocation.path}`;
2314
- case "script-execution":
2315
- return `script ${invocation.resourceId}`;
2316
- }
2317
- }
2318
- function eventNodeId(eventId) {
2319
- return nodeId("event", eventId);
2320
- }
2321
- function ontologyLabel(id, label) {
2322
- return label ?? parseOntologyId(id).localId;
2323
- }
2324
- function pushOntologyBindingEdges(edges, edgeIds, resourceNodeId, kind, ids) {
2325
- ids?.forEach((ontologyId) => {
2326
- const targetId = ontologyGraphNodeId(ontologyId);
2327
- pushUniqueEdge(edges, edgeIds, {
2328
- id: edgeId(kind, resourceNodeId, targetId),
2329
- kind,
2330
- sourceId: resourceNodeId,
2331
- targetId
2332
- });
2333
- });
2334
- }
2335
- function buildResourceEventDescriptor(resourceId, emission) {
2336
- return {
2337
- ...emission,
2338
- id: `${resourceId}:${emission.eventKey}`,
2339
- ownerId: resourceId,
2340
- ownerKind: "resource"
2341
- };
2342
- }
2343
- function buildEntityEventDescriptor(entity, eventKey, label) {
2344
- return {
2345
- id: `${entity.id}:${eventKey}`,
2346
- ownerId: entity.id,
2347
- ownerKind: "entity",
2348
- eventKey,
2349
- label
2350
- };
2351
- }
2352
- function pushEventProjection(nodes, nodeIds, edges, edgeIds, eventNodeIdsByEventId, event, sourceNodeId, edgeKind) {
2353
- const id = eventNodeId(event.id);
2354
- eventNodeIdsByEventId.set(event.id, id);
2355
- pushUniqueNode(nodes, nodeIds, {
2356
- id,
2357
- kind: "event",
2358
- label: event.label,
2359
- sourceId: event.id
2360
- });
2361
- const sourceId = edgeKind === "originates_from" ? id : sourceNodeId;
2362
- const targetId = edgeKind === "originates_from" ? sourceNodeId : id;
2363
- pushUniqueEdge(edges, edgeIds, {
2364
- id: edgeId(edgeKind, sourceId, targetId),
2365
- kind: edgeKind,
2366
- sourceId,
2367
- targetId
2368
- });
2369
- }
2370
- function buildOrganizationGraph(input) {
2371
- const parsed = BuildOrganizationGraphInputSchema.parse(input);
2372
- const organizationModel = parsed.organizationModel;
2373
- const commandViewData = parsed.commandViewData;
2374
- const nodes = [];
2375
- const edges = [];
2376
- const nodeIds = /* @__PURE__ */ new Set();
2377
- const edgeIds = /* @__PURE__ */ new Set();
2378
- const resourceNodesById = /* @__PURE__ */ new Map();
2379
- const organizationModelResourceIds = new Set(Object.keys(organizationModel.resources));
2380
- const actionIdsByInvocation = /* @__PURE__ */ new Map();
2381
- const projectedEventNodeIdsByEventId = /* @__PURE__ */ new Map();
2382
- const ontologyCompilation = compileOrganizationOntology(organizationModel);
2383
- const organizationNode = {
2384
- id: nodeId("organization"),
2385
- kind: "organization",
2386
- label: "Organization Model"
2387
- };
2388
- pushUniqueNode(nodes, nodeIds, organizationNode);
2389
- const systemsWithPaths = listAllSystems(organizationModel);
2390
- const systemPathByRef = /* @__PURE__ */ new Map();
2391
- for (const { path, system } of systemsWithPaths) {
2392
- systemPathByRef.set(path, path);
2393
- systemPathByRef.set(system.id, path);
2394
- }
2395
- const validSystemRefs = new Set(systemPathByRef.keys());
2396
- const systemNodeId = (systemRef) => nodeId("system", systemPathByRef.get(systemRef) ?? systemRef);
2397
- function topologyNodeId(ref) {
2398
- if (ref.kind === "system") return systemNodeId(ref.id);
2399
- if (ref.kind === "resource") return nodeId("resource", ref.id);
2400
- if (ref.kind === "ontology") return ontologyGraphNodeId(ref.id);
2401
- if (ref.kind === "policy") return nodeId("policy", ref.id);
2402
- if (ref.kind === "role") return nodeId("role", ref.id);
2403
- return nodeId("resource", ref.id);
2404
- }
2405
- function ensureTopologyNode(ref) {
2406
- const id = topologyNodeId(ref);
2407
- if (nodeIds.has(id)) return id;
2408
- if (ref.kind === "resource") {
2409
- ensureResourceNode(nodes, nodeIds, resourceNodesById, ref.id);
2410
- return id;
2411
- }
2412
- if (ref.kind === "trigger" || ref.kind === "humanCheckpoint" || ref.kind === "externalResource") {
2413
- pushUniqueNode(nodes, nodeIds, {
2414
- id,
2415
- kind: "resource",
2416
- label: ref.id,
2417
- sourceId: ref.id,
2418
- resourceType: ref.kind === "trigger" ? "trigger" : ref.kind === "humanCheckpoint" ? "human_checkpoint" : "external"
2419
- });
2420
- }
2421
- return id;
2422
- }
2423
- for (const { path, system } of systemsWithPaths.sort((a, b) => a.path.localeCompare(b.path))) {
2424
- const id = nodeId("system", path);
2425
- pushUniqueNode(nodes, nodeIds, {
2426
- id,
2427
- kind: "system",
2428
- label: system.label ?? system.title ?? system.id,
2429
- sourceId: path,
2430
- description: system.description,
2431
- icon: system.ui?.icon ?? system.icon,
2432
- enabled: system.enabled
2433
- });
2434
- pushUniqueEdge(edges, edgeIds, {
2435
- id: edgeId("contains", organizationNode.id, id),
2436
- kind: "contains",
2437
- sourceId: organizationNode.id,
2438
- targetId: id
2439
- });
2440
- const parentSystemId = path.includes(".") ? path.slice(0, path.lastIndexOf(".")) : void 0;
2441
- if (parentSystemId !== void 0) {
2442
- pushUniqueEdge(edges, edgeIds, {
2443
- id: edgeId("contains", nodeId("system", parentSystemId), id),
2444
- kind: "contains",
2445
- sourceId: nodeId("system", parentSystemId),
2446
- targetId: id
2447
- });
2448
- }
2449
- }
2450
- for (const { id: ontologyId, kind, record } of listResolvedOntologyRecords(ontologyCompilation.ontology).sort(
2451
- (a, b) => a.id.localeCompare(b.id)
2452
- )) {
2453
- const id = ontologyGraphNodeId(ontologyId);
2454
- const parsedId = parseOntologyId(ontologyId);
2455
- pushUniqueNode(nodes, nodeIds, {
2456
- id,
2457
- kind: "ontology",
2458
- label: ontologyLabel(ontologyId, record.label),
2459
- sourceId: ontologyId,
2460
- description: record.description,
2461
- ontologyKind: kind
2462
- });
2463
- const ownerSystemId = record.ownerSystemId ?? (parsedId.isGlobal ? void 0 : parsedId.scope);
2464
- if (ownerSystemId !== void 0 && validSystemRefs.has(ownerSystemId)) {
2465
- pushUniqueEdge(edges, edgeIds, {
2466
- id: edgeId("contains", systemNodeId(ownerSystemId), id, `ontology-${kind}`),
2467
- kind: "contains",
2468
- sourceId: systemNodeId(ownerSystemId),
2469
- targetId: id
2470
- });
2471
- } else {
2472
- pushUniqueEdge(edges, edgeIds, {
2473
- id: edgeId("contains", organizationNode.id, id, `ontology-${kind}`),
2474
- kind: "contains",
2475
- sourceId: organizationNode.id,
2476
- targetId: id
2477
- });
2478
- }
2479
- if (kind === "link") {
2480
- const link = record;
2481
- pushUniqueEdge(edges, edgeIds, {
2482
- id: edgeId("links", ontologyGraphNodeId(link.from), ontologyGraphNodeId(link.to), ontologyId),
2483
- kind: "links",
2484
- sourceId: ontologyGraphNodeId(link.from),
2485
- targetId: ontologyGraphNodeId(link.to),
2486
- label: link.label ?? parsedId.localId
2487
- });
2488
- }
2489
- if (kind === "action") {
2490
- const action = record;
2491
- for (const targetOntologyId of action.actsOn ?? []) {
2492
- pushUniqueEdge(edges, edgeIds, {
2493
- id: edgeId("affects", id, ontologyGraphNodeId(targetOntologyId), ontologyId),
2494
- kind: "affects",
2495
- sourceId: id,
2496
- targetId: ontologyGraphNodeId(targetOntologyId)
2497
- });
2498
- }
2499
- }
2500
- if (kind === "catalog") {
2501
- const catalog = record;
2502
- if (catalog.appliesTo === void 0) continue;
2503
- pushUniqueEdge(edges, edgeIds, {
2504
- id: edgeId("applies_to", id, ontologyGraphNodeId(catalog.appliesTo), ontologyId),
2505
- kind: "applies_to",
2506
- sourceId: id,
2507
- targetId: ontologyGraphNodeId(catalog.appliesTo)
2508
- });
2509
- }
2510
- if (kind === "group") {
2511
- const group = record;
2512
- for (const memberOntologyId of group.members ?? []) {
2513
- pushUniqueEdge(edges, edgeIds, {
2514
- id: edgeId("contains", id, ontologyGraphNodeId(memberOntologyId), ontologyId),
2515
- kind: "contains",
2516
- sourceId: id,
2517
- targetId: ontologyGraphNodeId(memberOntologyId)
2518
- });
2519
- }
2520
- }
2521
- }
2522
- for (const role of Object.values(organizationModel.roles).sort((a, b) => a.id.localeCompare(b.id))) {
2523
- const id = nodeId("role", role.id);
2524
- pushUniqueNode(nodes, nodeIds, {
2525
- id,
2526
- kind: "role",
2527
- label: role.title,
2528
- sourceId: role.id,
2529
- description: role.responsibilities.length > 0 ? role.responsibilities.join("; ") : void 0
2530
- });
2531
- pushUniqueEdge(edges, edgeIds, {
2532
- id: edgeId("contains", organizationNode.id, id),
2533
- kind: "contains",
2534
- sourceId: organizationNode.id,
2535
- targetId: id
2536
- });
2537
- if (role.reportsToId !== void 0) {
2538
- pushUniqueEdge(edges, edgeIds, {
2539
- id: edgeId("references", id, nodeId("role", role.reportsToId), "reports-to"),
2540
- kind: "references",
2541
- sourceId: id,
2542
- targetId: nodeId("role", role.reportsToId),
2543
- label: "reports to"
2544
- });
2545
- }
2546
- for (const systemId of role.responsibleFor ?? []) {
2547
- pushUniqueEdge(edges, edgeIds, {
2548
- id: edgeId("governs", id, systemNodeId(systemId), "responsible-for"),
2549
- kind: "governs",
2550
- sourceId: id,
2551
- targetId: systemNodeId(systemId),
2552
- label: "responsible for"
2553
- });
2554
- }
2555
- }
2556
- for (const node of Object.values(organizationModel.knowledge).sort((a, b) => a.id.localeCompare(b.id))) {
2557
- const id = nodeId("knowledge", node.id);
2558
- pushUniqueNode(nodes, nodeIds, {
2559
- id,
2560
- kind: "knowledge",
2561
- label: node.title,
2562
- sourceId: node.id,
2563
- description: node.summary,
2564
- icon: node.icon
2565
- });
2566
- pushUniqueEdge(edges, edgeIds, {
2567
- id: edgeId("contains", organizationNode.id, id),
2568
- kind: "contains",
2569
- sourceId: organizationNode.id,
2570
- targetId: id
2571
- });
2572
- for (const link of node.links) {
2573
- const targetId = link.target.kind === "system" ? systemNodeId(link.target.id) : link.target.kind === "ontology" ? ontologyGraphNodeId(link.target.id) : link.nodeId;
2574
- pushUniqueEdge(edges, edgeIds, {
2575
- id: edgeId("governs", id, targetId),
2576
- kind: "governs",
2577
- sourceId: id,
2578
- targetId
2579
- });
2580
- }
2581
- }
2582
- const allStages = [
2583
- ...getAllProspectingStages(organizationModel, "company"),
2584
- ...getAllProspectingStages(organizationModel, "contact")
2585
- ].sort((a, b) => a.order - b.order || a.id.localeCompare(b.id));
2586
- for (const stage of allStages) {
2587
- const id = nodeId("stage", stage.id);
2588
- pushUniqueNode(nodes, nodeIds, {
2589
- id,
2590
- kind: "stage",
2591
- label: stage.label,
2592
- sourceId: stage.id,
2593
- ...stage.description ? { description: stage.description } : {},
2594
- ...stage.icon ? { icon: stage.icon } : {}
2595
- });
2596
- pushUniqueEdge(edges, edgeIds, {
2597
- id: edgeId("contains", organizationNode.id, id),
2598
- kind: "contains",
2599
- sourceId: organizationNode.id,
2600
- targetId: id
2601
- });
2602
- }
2603
- for (const action of Object.values(organizationModel.actions).sort((a, b) => a.id.localeCompare(b.id))) {
2604
- const id = nodeId("action", action.id);
2605
- pushUniqueNode(nodes, nodeIds, {
2606
- id,
2607
- kind: "action",
2608
- label: action.label,
2609
- sourceId: action.id,
2610
- description: action.description
2611
- });
2612
- pushUniqueEdge(edges, edgeIds, {
2613
- id: edgeId("contains", organizationNode.id, id),
2614
- kind: "contains",
2615
- sourceId: organizationNode.id,
2616
- targetId: id
2617
- });
2618
- if (action.resourceId !== void 0) {
2619
- const resourceNode = ensureResourceNode(nodes, nodeIds, resourceNodesById, action.resourceId);
2620
- pushUniqueEdge(edges, edgeIds, {
2621
- id: edgeId("maps_to", id, resourceNode.id),
2622
- kind: "maps_to",
2623
- sourceId: id,
2624
- targetId: resourceNode.id
2625
- });
2626
- }
2627
- for (const entityId of action.affects ?? []) {
2628
- pushUniqueEdge(edges, edgeIds, {
2629
- id: edgeId("affects", id, nodeId("entity", entityId)),
2630
- kind: "affects",
2631
- sourceId: id,
2632
- targetId: nodeId("entity", entityId)
2633
- });
2634
- }
2635
- for (const invocation of action.invocations) {
2636
- const key = invocationSignature(invocation);
2637
- const existing = actionIdsByInvocation.get(key);
2638
- if (existing) {
2639
- existing.push(id);
2640
- } else {
2641
- actionIdsByInvocation.set(key, [id]);
2642
- }
2643
- }
2644
- }
2645
- for (const entity of Object.values(organizationModel.entities).sort(
2646
- (a, b) => a.order - b.order || a.id.localeCompare(b.id)
2647
- )) {
2648
- const id = nodeId("entity", entity.id);
2649
- pushUniqueNode(nodes, nodeIds, {
2650
- id,
2651
- kind: "entity",
2652
- label: entity.label,
2653
- sourceId: entity.id,
2654
- description: entity.description
2655
- });
2656
- pushUniqueEdge(edges, edgeIds, {
2657
- id: edgeId("contains", systemNodeId(entity.ownedBySystemId), id, "system-entity"),
2658
- kind: "contains",
2659
- sourceId: systemNodeId(entity.ownedBySystemId),
2660
- targetId: id
2661
- });
2662
- for (const [linkIndex, link] of (entity.links ?? []).entries()) {
2663
- pushUniqueEdge(edges, edgeIds, {
2664
- id: edgeId("links", id, nodeId("entity", link.toEntity), `${link.kind}-${linkIndex}`),
2665
- kind: "links",
2666
- sourceId: id,
2667
- targetId: nodeId("entity", link.toEntity),
2668
- label: link.label ?? link.kind
2669
- });
2670
- }
2671
- if (entity.stateCatalogId !== void 0) {
2672
- const stateEvents = [];
2673
- if (entity.stateCatalogId === "crm.pipeline") {
2674
- for (const { pipeline } of getAllPipelines(organizationModel).filter(({ pipeline: p }) => p.entityId === entity.id).sort((a, b) => a.pipeline.id.localeCompare(b.pipeline.id))) {
2675
- for (const stage of [...pipeline.stages].sort((a, b) => a.order - b.order || a.id.localeCompare(b.id))) {
2676
- stateEvents.push(buildEntityEventDescriptor(entity, stage.id, stage.label));
2677
- }
2678
- }
2679
- }
2680
- if (entity.stateCatalogId === "delivery.task") {
2681
- for (const status of getAllProjectStatuses(organizationModel, "task").sort(
2682
- (a, b) => a.order - b.order || a.id.localeCompare(b.id)
2683
- )) {
2684
- stateEvents.push(buildEntityEventDescriptor(entity, status.id, status.label));
2685
- }
2686
- }
2687
- if (entity.stateCatalogId === "lead-gen.company" || entity.stateCatalogId === "lead-gen.contact") {
2688
- const leadGenEntity = entity.stateCatalogId === "lead-gen.company" ? "company" : "contact";
2689
- for (const stage of Object.values(getLeadGenStageCatalog(organizationModel)).sort(
2690
- (a, b) => a.order - b.order || a.key.localeCompare(b.key)
2691
- )) {
2692
- if (stage.entity !== leadGenEntity && !(stage.additionalEntities ?? []).includes(leadGenEntity)) continue;
2693
- stateEvents.push(buildEntityEventDescriptor(entity, stage.key, stage.label));
2694
- }
2695
- }
2696
- for (const event of stateEvents) {
2697
- pushEventProjection(
2698
- nodes,
2699
- nodeIds,
2700
- edges,
2701
- edgeIds,
2702
- projectedEventNodeIdsByEventId,
2703
- event,
2704
- id,
2705
- "originates_from"
2706
- );
2707
- }
2708
- }
2709
- }
2710
- for (const { path, system } of systemsWithPaths.sort((a, b) => a.path.localeCompare(b.path))) {
2711
- for (const actionRef of system.actions ?? []) {
2712
- pushUniqueEdge(edges, edgeIds, {
2713
- id: edgeId("uses", nodeId("system", path), nodeId("action", actionRef.actionId), actionRef.intent),
2714
- kind: "uses",
2715
- sourceId: nodeId("system", path),
2716
- targetId: nodeId("action", actionRef.actionId),
2717
- label: actionRef.intent
2718
- });
2719
- }
2720
- }
2721
- const validSystemPaths = /* @__PURE__ */ new Set([...validSystemRefs]);
2722
- for (const resource of Object.values(organizationModel.resources).sort((a, b) => a.id.localeCompare(b.id))) {
2723
- const resourceNode = upsertResourceNode(nodes, nodeIds, resourceNodesById, {
2724
- id: nodeId("resource", resource.id),
2725
- kind: "resource",
2726
- label: resource.id,
2727
- sourceId: resource.id,
2728
- resourceType: normalizeOrganizationModelResourceType(resource.kind)
2729
- });
2730
- if (validSystemPaths.has(resource.systemPath)) {
2731
- pushUniqueEdge(edges, edgeIds, {
2732
- id: edgeId("contains", systemNodeId(resource.systemPath), resourceNode.id, "system-resource"),
2733
- kind: "contains",
2734
- sourceId: systemNodeId(resource.systemPath),
2735
- targetId: resourceNode.id
2736
- });
2737
- }
2738
- pushOntologyBindingEdges(edges, edgeIds, resourceNode.id, "actions", resource.ontology?.actions);
2739
- pushOntologyBindingEdges(edges, edgeIds, resourceNode.id, "reads", resource.ontology?.reads);
2740
- pushOntologyBindingEdges(edges, edgeIds, resourceNode.id, "writes", resource.ontology?.writes);
2741
- pushOntologyBindingEdges(edges, edgeIds, resourceNode.id, "uses_catalog", resource.ontology?.usesCatalogs);
2742
- pushOntologyBindingEdges(edges, edgeIds, resourceNode.id, "emits", resource.ontology?.emits);
2743
- if (resource.kind === "workflow" || resource.kind === "agent") {
2744
- for (const emission of resource.emits ?? []) {
2745
- pushEventProjection(
2746
- nodes,
2747
- nodeIds,
2748
- edges,
2749
- edgeIds,
2750
- projectedEventNodeIdsByEventId,
2751
- buildResourceEventDescriptor(resource.id, emission),
2752
- resourceNode.id,
2753
- "emits"
2754
- );
2755
- }
2756
- }
2757
- if (resource.kind === "agent") {
2758
- for (const [index, invocation] of resource.invocations.entries()) {
2759
- const label = invocationLabel(invocation);
2760
- if (invocation.kind === "script-execution") {
2761
- const targetNode = ensureResourceNode(nodes, nodeIds, resourceNodesById, invocation.resourceId);
2762
- pushUniqueEdge(edges, edgeIds, {
2763
- id: edgeId("uses", resourceNode.id, targetNode.id, `agent-invocation-${index}`),
2764
- kind: "uses",
2765
- sourceId: resourceNode.id,
2766
- targetId: targetNode.id,
2767
- label
2768
- });
2769
- continue;
2770
- }
2771
- for (const actionNodeId of actionIdsByInvocation.get(invocationSignature(invocation)) ?? []) {
2772
- pushUniqueEdge(edges, edgeIds, {
2773
- id: edgeId("references", resourceNode.id, actionNodeId, `agent-invocation-${index}`),
2774
- kind: "references",
2775
- sourceId: resourceNode.id,
2776
- targetId: actionNodeId,
2777
- label
2778
- });
2779
- }
2780
- }
2781
- }
2782
- }
2783
- for (const policy of Object.values(organizationModel.policies).sort(
2784
- (a, b) => a.order - b.order || a.id.localeCompare(b.id)
2785
- )) {
2786
- const id = nodeId("policy", policy.id);
2787
- pushUniqueNode(nodes, nodeIds, {
2788
- id,
2789
- kind: "policy",
2790
- label: policy.label,
2791
- sourceId: policy.id,
2792
- description: policy.description
2793
- });
2794
- pushUniqueEdge(edges, edgeIds, {
2795
- id: edgeId("contains", organizationNode.id, id),
2796
- kind: "contains",
2797
- sourceId: organizationNode.id,
2798
- targetId: id
2799
- });
2800
- for (const systemId of policy.appliesTo.systemIds) {
2801
- pushUniqueEdge(edges, edgeIds, {
2802
- id: edgeId("applies_to", id, systemNodeId(systemId), "system"),
2803
- kind: "applies_to",
2804
- sourceId: id,
2805
- targetId: systemNodeId(systemId)
2806
- });
2807
- }
2808
- for (const actionId of policy.appliesTo.actionIds) {
2809
- pushUniqueEdge(edges, edgeIds, {
2810
- id: edgeId("applies_to", id, nodeId("action", actionId), "action"),
2811
- kind: "applies_to",
2812
- sourceId: id,
2813
- targetId: nodeId("action", actionId)
2814
- });
2815
- }
2816
- for (const resourceId of policy.appliesTo.resourceIds) {
2817
- const resourceNode = ensureResourceNode(nodes, nodeIds, resourceNodesById, resourceId);
2818
- pushUniqueEdge(edges, edgeIds, {
2819
- id: edgeId("applies_to", id, resourceNode.id, "resource"),
2820
- kind: "applies_to",
2821
- sourceId: id,
2822
- targetId: resourceNode.id
2823
- });
2824
- }
2825
- for (const roleId of policy.appliesTo.roleIds) {
2826
- pushUniqueEdge(edges, edgeIds, {
2827
- id: edgeId("applies_to", id, nodeId("role", roleId), "role"),
2828
- kind: "applies_to",
2829
- sourceId: id,
2830
- targetId: nodeId("role", roleId)
2831
- });
2832
- }
2833
- if (policy.trigger.kind === "event") {
2834
- const eventNode = projectedEventNodeIdsByEventId.get(policy.trigger.eventId);
2835
- if (eventNode !== void 0) {
2836
- pushUniqueEdge(edges, edgeIds, {
2837
- id: edgeId("triggers", eventNode, id),
2838
- kind: "triggers",
2839
- sourceId: eventNode,
2840
- targetId: id
2841
- });
2842
- }
2843
- } else if (policy.trigger.kind === "action-invocation") {
2844
- pushUniqueEdge(edges, edgeIds, {
2845
- id: edgeId("triggers", nodeId("action", policy.trigger.actionId), id),
2846
- kind: "triggers",
2847
- sourceId: nodeId("action", policy.trigger.actionId),
2848
- targetId: id
2849
- });
2850
- }
2851
- for (const [effectIndex, effect] of policy.actions.entries()) {
2852
- if (effect.kind === "invoke-action") {
2853
- pushUniqueEdge(edges, edgeIds, {
2854
- id: edgeId("effects", id, nodeId("action", effect.actionId), `invoke-action-${effectIndex}`),
2855
- kind: "effects",
2856
- sourceId: id,
2857
- targetId: nodeId("action", effect.actionId),
2858
- label: "invoke action"
2859
- });
2860
- }
2861
- if ((effect.kind === "notify-role" || effect.kind === "require-approval") && effect.roleId !== void 0) {
2862
- pushUniqueEdge(edges, edgeIds, {
2863
- id: edgeId("effects", id, nodeId("role", effect.roleId), `${effect.kind}-${effectIndex}`),
2864
- kind: "effects",
2865
- sourceId: id,
2866
- targetId: nodeId("role", effect.roleId),
2867
- label: effect.kind
2868
- });
2869
- }
2870
- }
2871
- }
2872
- for (const [relationshipId, relationship] of Object.entries(organizationModel.topology.relationships).sort(
2873
- ([a], [b]) => a.localeCompare(b)
2874
- )) {
2875
- const sourceId = ensureTopologyNode(relationship.from);
2876
- const targetId = ensureTopologyNode(relationship.to);
2877
- pushUniqueEdge(edges, edgeIds, {
2878
- id: edgeId(relationship.kind, sourceId, targetId, `topology-${relationshipId}`),
2879
- kind: relationship.kind,
2880
- sourceId,
2881
- targetId,
2882
- relationshipType: relationship.kind
2883
- });
2884
- }
2885
- for (const segment of Object.values(organizationModel.customers).sort(
2886
- (a, b) => a.order - b.order || a.id.localeCompare(b.id)
2887
- )) {
2888
- const id = nodeId("customer-segment", segment.id);
2889
- pushUniqueNode(nodes, nodeIds, {
2890
- id,
2891
- kind: "customer-segment",
2892
- label: segment.name,
2893
- sourceId: segment.id,
2894
- description: segment.description || void 0
2895
- });
2896
- pushUniqueEdge(edges, edgeIds, {
2897
- id: edgeId("contains", organizationNode.id, id),
2898
- kind: "contains",
2899
- sourceId: organizationNode.id,
2900
- targetId: id
2901
- });
2902
- }
2903
- for (const product of Object.values(organizationModel.offerings).sort(
2904
- (a, b) => a.order - b.order || a.id.localeCompare(b.id)
2905
- )) {
2906
- const id = nodeId("offering", product.id);
2907
- pushUniqueNode(nodes, nodeIds, {
2908
- id,
2909
- kind: "offering",
2910
- label: product.name,
2911
- sourceId: product.id,
2912
- description: product.description || void 0
2913
- });
2914
- pushUniqueEdge(edges, edgeIds, {
2915
- id: edgeId("contains", organizationNode.id, id),
2916
- kind: "contains",
2917
- sourceId: organizationNode.id,
2918
- targetId: id
2919
- });
2920
- for (const segmentId of product.targetSegmentIds) {
2921
- pushUniqueEdge(edges, edgeIds, {
2922
- id: edgeId("applies_to", id, nodeId("customer-segment", segmentId), "targets-segment"),
2923
- kind: "applies_to",
2924
- sourceId: id,
2925
- targetId: nodeId("customer-segment", segmentId),
2926
- label: "targets"
2927
- });
2928
- }
2929
- }
2930
- for (const objective of Object.values(organizationModel.goals).sort(
2931
- (a, b) => a.order - b.order || a.id.localeCompare(b.id)
2932
- )) {
2933
- const id = nodeId("goal", objective.id);
2934
- pushUniqueNode(nodes, nodeIds, {
2935
- id,
2936
- kind: "goal",
2937
- label: objective.description,
2938
- sourceId: objective.id
2939
- });
2940
- pushUniqueEdge(edges, edgeIds, {
2941
- id: edgeId("contains", organizationNode.id, id),
2942
- kind: "contains",
2943
- sourceId: organizationNode.id,
2944
- targetId: id
2945
- });
2946
- }
2947
- const sidebarGroups = [];
2948
- const sidebarSurfaces = [];
2949
- collectSidebarGraphNodes(organizationModel.navigation.sidebar.primary, sidebarGroups, sidebarSurfaces);
2950
- collectSidebarGraphNodes(organizationModel.navigation.sidebar.bottom, sidebarGroups, sidebarSurfaces);
2951
- for (const { id: surfaceSourceId, node: surface, parentGroupId } of sidebarSurfaces) {
2952
- const id = nodeId("surface", surfaceSourceId);
2953
- pushUniqueNode(nodes, nodeIds, {
2954
- id,
2955
- kind: "surface",
2956
- label: surface.label,
2957
- sourceId: surfaceSourceId,
2958
- description: surface.description,
2959
- icon: surface.icon,
2960
- enabled: true
2961
- });
2962
- pushUniqueEdge(edges, edgeIds, {
2963
- id: edgeId("contains", parentGroupId ? nodeId("navigation-group", parentGroupId) : organizationNode.id, id),
2964
- kind: "contains",
2965
- sourceId: parentGroupId ? nodeId("navigation-group", parentGroupId) : organizationNode.id,
2966
- targetId: id
2967
- });
2968
- for (const systemId of surface.targets?.systems ?? []) {
2969
- if (!validSystemRefs.has(systemId)) continue;
2970
- pushUniqueEdge(edges, edgeIds, {
2971
- id: edgeId("applies_to", id, systemNodeId(systemId), "surface-system"),
2972
- kind: "applies_to",
2973
- sourceId: id,
2974
- targetId: systemNodeId(systemId)
2975
- });
2976
- }
2977
- }
2978
- for (const { id: groupSourceId, node: group, parentGroupId } of sidebarGroups) {
2979
- const id = nodeId("navigation-group", groupSourceId);
2980
- pushUniqueNode(nodes, nodeIds, {
2981
- id,
2982
- kind: "navigation-group",
2983
- label: group.label,
2984
- sourceId: groupSourceId
2985
- });
2986
- pushUniqueEdge(edges, edgeIds, {
2987
- id: edgeId("contains", parentGroupId ? nodeId("navigation-group", parentGroupId) : organizationNode.id, id),
2988
- kind: "contains",
2989
- sourceId: parentGroupId ? nodeId("navigation-group", parentGroupId) : organizationNode.id,
2990
- targetId: id
2991
- });
2992
- }
2993
- for (const template of getAllBuildTemplates(organizationModel).sort((a, b) => a.id.localeCompare(b.id))) {
2994
- const steps = template.steps;
2995
- const stepById = new Map(steps.map((s) => [s.id, s]));
2996
- for (const step of [...steps].sort((a, b) => a.id.localeCompare(b.id))) {
2997
- const stageNodeId = nodeId("stage", step.stageKey);
2998
- const actionNodeId = nodeId("action", step.actionKey);
2999
- pushUniqueEdge(edges, edgeIds, {
3000
- id: edgeId("uses", stageNodeId, actionNodeId, step.id),
3001
- kind: "uses",
3002
- sourceId: stageNodeId,
3003
- targetId: actionNodeId
3004
- });
3005
- for (const depId of step.dependsOn ?? []) {
3006
- const depStep = stepById.get(depId);
3007
- if (depStep) {
3008
- const depStageNodeId = nodeId("stage", depStep.stageKey);
3009
- pushUniqueEdge(edges, edgeIds, {
3010
- id: edgeId("references", stageNodeId, depStageNodeId, step.id),
3011
- kind: "references",
3012
- sourceId: stageNodeId,
3013
- targetId: depStageNodeId
3014
- });
3015
- }
3016
- }
3017
- }
3018
- }
3019
- if (commandViewData) {
3020
- const commandViewResources = collectCommandViewResources(commandViewData).sort(
3021
- (a, b) => a.resourceId.localeCompare(b.resourceId)
3022
- );
3023
- for (const resource of commandViewResources) {
3024
- const id = nodeId("resource", resource.resourceId);
3025
- const resourceNode = upsertResourceNode(nodes, nodeIds, resourceNodesById, {
3026
- id,
3027
- kind: "resource",
3028
- label: resource.name,
3029
- sourceId: resource.resourceId,
3030
- description: resource.description,
3031
- resourceType: normalizeCommandViewResourceType(resource.type)
3032
- });
3033
- if (!organizationModelResourceIds.has(resource.resourceId)) {
3034
- pushUniqueEdge(edges, edgeIds, {
3035
- id: edgeId("contains", organizationNode.id, resourceNode.id),
3036
- kind: "contains",
3037
- sourceId: organizationNode.id,
3038
- targetId: resourceNode.id
3039
- });
3040
- }
3041
- }
3042
- for (const relationship of [...commandViewData.edges].sort((a, b) => a.id.localeCompare(b.id))) {
3043
- const sourceNode = ensureResourceNode(nodes, nodeIds, resourceNodesById, relationship.source);
3044
- const targetNode = ensureResourceNode(nodes, nodeIds, resourceNodesById, relationship.target);
3045
- pushUniqueEdge(edges, edgeIds, {
3046
- id: edgeId("contains", organizationNode.id, sourceNode.id),
3047
- kind: "contains",
3048
- sourceId: organizationNode.id,
3049
- targetId: sourceNode.id
3050
- });
3051
- pushUniqueEdge(edges, edgeIds, {
3052
- id: edgeId("contains", organizationNode.id, targetNode.id),
3053
- kind: "contains",
3054
- sourceId: organizationNode.id,
3055
- targetId: targetNode.id
3056
- });
3057
- pushUniqueEdge(edges, edgeIds, {
3058
- id: edgeId("references", sourceNode.id, targetNode.id, relationship.relationship),
3059
- kind: "references",
3060
- sourceId: sourceNode.id,
3061
- targetId: targetNode.id,
3062
- label: relationship.relationship,
3063
- relationshipType: relationship.relationship
3064
- });
3065
- }
3066
- }
3067
- const graph = {
3068
- version: 1,
3069
- organizationModelVersion: organizationModel.version,
3070
- nodes,
3071
- edges
3072
- };
3073
- return OrganizationGraphSchema.parse(graph);
3074
- }
3075
-
3076
- // ../core/src/organization-model/surface-projection.ts
3077
- function collectSystemsById(model) {
3078
- const systemsById = /* @__PURE__ */ new Map();
3079
- for (const { path, system } of listAllSystems(model)) {
3080
- systemsById.set(path, system);
3081
- systemsById.set(system.id, system);
3082
- }
3083
- return systemsById;
3084
- }
3085
- function getSystemWithAncestors(systemsById, systemId) {
3086
- const systems = [];
3087
- let current = systemsById.get(systemId);
3088
- while (current !== void 0) {
3089
- systems.unshift(current);
3090
- current = current.parentSystemId ? systemsById.get(current.parentSystemId) : void 0;
3091
- }
3092
- return systems;
3093
- }
3094
- function hasInheritedFlag(systemsById, systemIds, flag) {
3095
- return systemIds.some(
3096
- (systemId) => getSystemWithAncestors(systemsById, systemId).some((system) => system[flag] === true)
3097
- );
3098
- }
3099
- function isLifecycleEnabled2(system) {
3100
- if (system.enabled === false) return false;
3101
- return system.lifecycle !== "deprecated" && system.lifecycle !== "archived";
3102
- }
3103
- function isLifecycleDevOnly(system) {
3104
- return system.devOnly === true || system.lifecycle === "beta";
3105
- }
3106
- function isSystemEnabled(systemsById, systemId) {
3107
- const systemLineage = getSystemWithAncestors(systemsById, systemId);
3108
- return systemLineage.length > 0 && systemLineage.every(isLifecycleEnabled2);
3109
- }
3110
- function unique(values) {
3111
- return [...new Set(values)];
3112
- }
3113
- function collectSidebarSurfaces(nodes, schemaPath, surfaces = []) {
3114
- getSortedSidebarEntries(nodes).forEach(([id, node]) => {
3115
- const nodePath = [...schemaPath, id];
3116
- if (node.type === "group") {
3117
- collectSidebarSurfaces(node.children, [...nodePath, "children"], surfaces);
3118
- return;
3119
- }
3120
- surfaces.push({ id, surface: node, path: nodePath });
3121
- });
3122
- return surfaces;
3123
- }
3124
- function getSidebarSurfaces(model) {
3125
- return [
3126
- ...collectSidebarSurfaces(model.navigation.sidebar.primary, ["navigation", "sidebar", "primary"]),
3127
- ...collectSidebarSurfaces(model.navigation.sidebar.bottom, ["navigation", "sidebar", "bottom"])
3128
- ];
3129
- }
3130
- function projectOrganizationSurfaces(model) {
3131
- const systemsById = collectSystemsById(model);
3132
- return getSidebarSurfaces(model).map(({ id, surface }) => {
3133
- const targets = surface.targets ?? {};
3134
- const systemIds = unique((targets.systems ?? []).filter((systemId) => systemsById.has(systemId)));
3135
- const enabled = systemIds.every((candidate) => isSystemEnabled(systemsById, candidate));
3136
- const devOnly = surface.devOnly === true || hasInheritedFlag(systemsById, systemIds, "devOnly") || systemIds.some((candidate) => getSystemWithAncestors(systemsById, candidate).some(isLifecycleDevOnly));
3137
- const requiresAdmin = hasInheritedFlag(systemsById, systemIds, "requiresAdmin");
3138
- return {
3139
- id,
3140
- label: surface.label,
3141
- path: surface.path,
3142
- surfaceType: surface.surfaceType,
3143
- ...surface.description !== void 0 ? { description: surface.description } : {},
3144
- ...surface.icon !== void 0 ? { icon: surface.icon } : {},
3145
- ...surface.order !== void 0 ? { order: surface.order } : {},
3146
- systemIds,
3147
- entityIds: [...targets.entities ?? []],
3148
- resourceIds: [...targets.resources ?? []],
3149
- actionIds: [...targets.actions ?? []],
3150
- enabled,
3151
- ...devOnly ? { devOnly } : {},
3152
- ...surface.requiresAdmin === true || requiresAdmin ? { requiresAdmin: true } : {}
3153
- };
3154
- });
3155
- }
3156
-
3157
- export { ActionSchema, AgentResourceEntrySchema, DEFAULT_ORGANIZATION_MODEL, DEFAULT_SEMANTIC_ICON_REGISTRY, EntitySchema, IdentityDomainSchema, IntegrationResourceEntrySchema, OrgKnowledgeNodeSchema, PROJECTS_VIEW_ACTION_ID, PolicySchema, RoleSchema, ScriptResourceEntrySchema, SemanticIcon, SurfaceDefinitionSchema, SystemEntrySchema, WorkflowResourceEntrySchema, buildOrganizationGraph, defineActions, defineEntities, defineResources, defineTopology, extendSemanticIconRegistry, getSemanticIconComponent, getSortedSidebarEntries, projectOrganizationSurfaces, resolveOrganizationModel, resolveSemanticIconComponent, topologyRef, topologyRelationship };