import { formatDistanceToNow } from 'date-fns';
import { IconUser, IconExternalLink, IconPlug, IconBolt, IconGitBranch, IconBrain } from '@tabler/icons-react';
import { z } from 'zod';

// src/utils/dateFormatters.ts
function formatDateTime(dateString) {
  if (!dateString) return "Never";
  const date = new Date(dateString);
  return date.toLocaleDateString("en-US", {
    year: "numeric",
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit"
  });
}
function formatDate(dateString) {
  if (!dateString) return "Never";
  const date = new Date(dateString);
  return date.toLocaleDateString("en-US", {
    year: "numeric",
    month: "short",
    day: "numeric"
  });
}
function formatChartAxisDate(dateString) {
  if (!dateString) return "";
  const date = new Date(dateString);
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const period = hour >= 12 ? "PM" : "AM";
  const hour12 = hour % 12 || 12;
  return `${month}/${day}, ${hour12}${period}`;
}
function formatRelativeTime(date) {
  if (!date) return "N/A";
  const dateObj = typeof date === "string" ? new Date(date) : date;
  return formatDistanceToNow(dateObj, { addSuffix: true });
}
function formatTimeAgo(date) {
  if (!date) return "-";
  const dateObj = typeof date === "string" ? new Date(date) : date;
  const diffMs = Date.now() - dateObj.getTime();
  const diffMinutes = Math.floor(diffMs / (1e3 * 60));
  const diffHours = Math.floor(diffMs / (1e3 * 60 * 60));
  const diffDays = Math.floor(diffMs / (1e3 * 60 * 60 * 24));
  if (diffMinutes < 1) return "Just now";
  if (diffHours < 1) return `${diffMinutes}m ago`;
  if (diffDays < 1) return `${diffHours}h ago`;
  if (diffDays === 1) return "1d ago";
  return `${diffDays}d ago`;
}

// src/utils/validateEmail.ts
var validateEmail = (email) => {
  return /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+$/.test(email);
};

// src/utils/error-utils.ts
var APIClientError = class extends Error {
  statusCode;
  code;
  requestId;
  fields;
  retryAfter;
  constructor(message, code, statusCode, requestId, fields, retryAfter) {
    super(message);
    this.name = "APIClientError";
    this.code = code;
    this.statusCode = statusCode;
    this.requestId = requestId;
    this.fields = fields;
    this.retryAfter = retryAfter;
  }
};
function isAPIClientError(error) {
  return error instanceof APIClientError;
}
function getErrorInfo(error) {
  if (isAPIClientError(error)) {
    return {
      message: error.message,
      code: error.code,
      requestId: error.requestId,
      statusCode: error.statusCode,
      fields: error.fields,
      retryAfter: error.retryAfter
    };
  }
  if (error instanceof Error) {
    return {
      message: error.message
    };
  }
  return {
    message: String(error)
  };
}
function getErrorTitle(code) {
  if (!code) return "Error";
  switch (code) {
    case "VALIDATION_ERROR":
      return "Validation Error";
    case "AUTHENTICATION_FAILED":
      return "Authentication Required";
    case "FORBIDDEN":
      return "Access Denied";
    case "NOT_FOUND":
      return "Not Found";
    case "CONFLICT":
      return "Conflict";
    case "RATE_LIMIT_EXCEEDED":
      return "Rate Limit Exceeded";
    case "INTERNAL_SERVER_ERROR":
      return "Server Error";
    case "SERVICE_UNAVAILABLE":
      return "Service Temporarily Unavailable";
    default:
      return "Error";
  }
}
function formatErrorMessage(message, requestId, fields, retryAfter) {
  let formatted = message;
  if (fields && Object.keys(fields).length > 0) {
    const fieldErrors = [];
    for (const [field, errors] of Object.entries(fields)) {
      const fieldName = field === "root" || field === "_root" ? "Request" : field;
      errors.forEach((error) => {
        fieldErrors.push(`\u2022 ${fieldName}: ${error}`);
      });
    }
    if (fieldErrors.length > 0) {
      formatted = fieldErrors.join("\n");
    }
  }
  if (retryAfter) {
    formatted += `

Please wait ${retryAfter} seconds before retrying.`;
  }
  if (requestId) {
    formatted += `

Request ID: ${requestId}`;
  }
  return formatted;
}
var ORGANIZATION_MODEL_ICON_TOKENS = [
  // Navigation / app areas
  "dashboard",
  "calendar",
  "sales",
  "crm",
  "lead-gen",
  "projects",
  "clients",
  "operations",
  "monitoring",
  "knowledge",
  "settings",
  "admin",
  "archive",
  "business",
  "finance",
  "platform",
  "seo",
  // Knowledge kinds
  "playbook",
  "strategy",
  "reference",
  // Resource kinds
  "agent",
  "workflow",
  "integration",
  "database",
  "user",
  "team",
  // Integration specifics
  "gmail",
  "google-sheets",
  "attio",
  // Surface / UI views
  "overview",
  "command-view",
  "command-queue",
  "pipeline",
  "lists",
  "resources",
  // Actions
  "approve",
  "reject",
  "retry",
  "edit",
  "view",
  "launch",
  "message",
  "message-plus",
  "escalate",
  "promote",
  "submit",
  "email",
  // Status
  "success",
  "error",
  "warning",
  "info",
  "pending",
  // OM / UI group icons
  "bolt",
  "building",
  "briefcase",
  "apps",
  "graph",
  "shield",
  "users",
  "chart-bar",
  "search"
];
var CustomIconTokenSchema = z.string().trim().max(80).regex(
  /^custom\.[a-z0-9]+(?:[-._][a-z0-9]+)*$/,
  'Custom icon tokens must start with "custom." followed by lowercase alphanumeric segments'
);
var OrganizationModelBuiltinIconTokenSchema = z.enum(ORGANIZATION_MODEL_ICON_TOKENS);
var OrganizationModelIconTokenSchema = z.union([
  OrganizationModelBuiltinIconTokenSchema,
  CustomIconTokenSchema
]);

// ../core/src/organization-model/domains/shared.ts
var ModelIdSchema = z.string().trim().min(1).max(100).regex(/^[a-z0-9]+(?:[-._][a-z0-9]+)*$/, "IDs must be lowercase and use -, _, or . separators");
var LabelSchema = z.string().trim().min(1).max(120);
var DescriptionSchema = z.string().trim().min(1).max(2e3);
var ColorTokenSchema = z.string().trim().min(1).max(50);
var IconNameSchema = OrganizationModelIconTokenSchema;
var PathSchema = z.string().trim().startsWith("/").max(300);
var ReferenceIdsSchema = z.array(ModelIdSchema).default([]);
var DisplayMetadataSchema = z.object({
  label: LabelSchema,
  description: DescriptionSchema.optional(),
  color: ColorTokenSchema.optional(),
  icon: IconNameSchema.optional()
});
var TechStackEntrySchema = z.object({
  /** Name of the external platform (e.g. "HubSpot", "Stripe", "Notion"). */
  platform: z.string().trim().min(1).max(200),
  /** Free-form description of what this integration is used for. */
  purpose: z.string().trim().min(1).max(500),
  /**
   * Health of the credential backing this integration.
   * - configured: credential present and valid
   * - pending: not yet set up
   * - expired: credential existed but has lapsed
   * - missing: expected but not present
   */
  credentialStatus: z.enum(["configured", "pending", "expired", "missing"]),
  /**
   * Whether this integration is the primary system of record for its domain
   * (e.g. HubSpot is SoR for contacts). Defaults to false.
   */
  isSystemOfRecord: z.boolean().default(false)
});
DisplayMetadataSchema.extend({
  id: ModelIdSchema,
  resourceId: z.string().trim().min(1).max(255),
  resourceType: z.enum(["workflow", "agent", "trigger", "integration", "external", "human_checkpoint"]),
  systemIds: ReferenceIdsSchema,
  entityIds: ReferenceIdsSchema,
  surfaceIds: ReferenceIdsSchema,
  actionIds: ReferenceIdsSchema,
  /** Optional tech-stack metadata for external-SaaS integrations. */
  techStack: TechStackEntrySchema.optional()
});

// ../core/src/organization-model/helpers.ts
function defineDomainRecord(schema, entries) {
  return Object.fromEntries(
    entries.map((entry) => {
      const parsed = schema.parse(entry);
      return [parsed.id, parsed];
    })
  );
}
function childSystemsOf(system) {
  return system.systems ?? system.subsystems ?? {};
}
function defaultPathFor(id) {
  return `/${id.replaceAll(".", "/")}`;
}
function parentIdOf(id) {
  const index = id.lastIndexOf(".");
  return index === -1 ? void 0 : id.slice(0, index);
}
function findById(systems, id) {
  return systems[id];
}
function findByPath(systems, path) {
  return Object.values(systems).find((system) => (system.path ?? system.ui?.path ?? defaultPathFor(system.id)) === path);
}
function childrenOf(systems, id) {
  const prefix = `${id}.`;
  return Object.values(systems).filter(
    (system) => system.id.startsWith(prefix) && !system.id.slice(prefix.length).includes(".")
  );
}
function topLevel(systems) {
  return Object.values(systems).filter((system) => !system.id.includes("."));
}
function ancestorsOf(systems, id) {
  const segments = id.split(".");
  const ids = segments.map((_, index) => segments.slice(0, index + 1).join("."));
  return ids.map((ancestorId) => findById(systems, ancestorId)).filter((system) => Boolean(system));
}
function parentOf(systems, id) {
  const parentId = parentIdOf(id);
  return parentId ? findById(systems, parentId) : void 0;
}
function inheritedValue(systems, id, getValue) {
  return ancestorsOf(systems, id).slice().reverse().map(getValue).find((value) => value !== void 0);
}
function requiresAdminFor(systems, id) {
  return inheritedValue(systems, id, (system) => system.requiresAdmin) ?? false;
}
function devOnlyFor(systems, id) {
  return inheritedValue(systems, id, (system) => system.devOnly || system.lifecycle === "beta" || void 0) ?? false;
}
function getSystem(model, path) {
  const flatMatch = model.systems[path];
  if (flatMatch !== void 0) return flatMatch;
  const segments = path.split(".");
  let current = model.systems;
  let node;
  for (const seg of segments) {
    node = current[seg];
    if (node === void 0) return void 0;
    current = childSystemsOf(node);
  }
  return node;
}
function getSystemAncestors(model, path) {
  const flatMatch = model.systems[path];
  if (flatMatch !== void 0) {
    const ancestorIds = path.split(".").map((_, index, segments2) => segments2.slice(0, index + 1).join(".")).slice(0, -1);
    return [
      ...ancestorIds.map((ancestorId) => model.systems[ancestorId]).filter((system) => system !== void 0),
      flatMatch
    ];
  }
  const segments = path.split(".");
  const result = [];
  let current = model.systems;
  for (const seg of segments) {
    const node = current[seg];
    if (node === void 0) return [];
    result.push(node);
    current = childSystemsOf(node);
  }
  return result;
}
function listAllSystems(model) {
  const results = [];
  function walk(map, prefix) {
    for (const [localId2, system] of Object.entries(map)) {
      const fullPath = prefix ? `${prefix}.${localId2}` : localId2;
      results.push({ path: fullPath, system });
      const childSystems = childSystemsOf(system);
      if (Object.keys(childSystems).length > 0) {
        walk(childSystems, fullPath);
      }
    }
  }
  walk(model.systems, "");
  return results;
}
function isPlainJsonObject(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function mergeJsonConfig(base, override) {
  const result = { ...base };
  for (const [key, value] of Object.entries(override)) {
    const existing = result[key];
    result[key] = isPlainJsonObject(existing) && isPlainJsonObject(value) ? mergeJsonConfig(existing, value) : value;
  }
  return result;
}
function resolveSystemConfig(model, path) {
  const system = getSystem(model, path);
  if (system === void 0) return {};
  return mergeJsonConfig({}, system.config ?? {});
}
function getResourcesForSystem(model, systemPath, options = {}) {
  const { includeDescendants = false } = options;
  const prefix = systemPath + ".";
  return Object.values(model.resources ?? {}).filter(
    (r) => r.systemPath === systemPath || includeDescendants && r.systemPath.startsWith(prefix)
  );
}

// ../core/src/organization-model/domains/entities.ts
var EntityIdSchema = ModelIdSchema;
var EntityLinkKindSchema = z.enum(["belongs-to", "has-many", "has-one", "many-to-many"]).meta({ label: "Link kind" });
var EntityLinkSchema = z.object({
  toEntity: EntityIdSchema.meta({ ref: "entity" }),
  kind: EntityLinkKindSchema,
  via: z.string().trim().min(1).max(255).optional(),
  label: LabelSchema.optional()
});
var EntitySchema = z.object({
  id: EntityIdSchema,
  /** Domain-map iteration order. Convention: multiples of 10 (10, 20, 30, ...) to allow easy insertion. */
  order: z.number(),
  label: LabelSchema,
  description: DescriptionSchema.optional(),
  ownedBySystemId: ModelIdSchema.meta({ ref: "system" }),
  table: z.string().trim().min(1).max(255).optional(),
  rowSchema: ModelIdSchema.optional(),
  stateCatalogId: ModelIdSchema.optional(),
  links: z.array(EntityLinkSchema).optional()
});
var EntitiesDomainSchema = z.record(z.string(), EntitySchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
  message: "Each entity entry id must match its map key"
}).default({});
function defineEntities(entries) {
  return defineDomainRecord(EntitySchema, entries);
}

// ../core/src/organization-model/domains/actions.ts
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");
z.enum(["slash-command", "mcp-tool", "api-endpoint", "script-execution"]).meta({ label: "Invocation kind" });
var ActionIdSchema = ModelIdSchema;
var ActionScopeSchema = z.union([
  z.literal("global"),
  z.object({
    domain: ModelIdSchema
  })
]);
var ActionRefSchema = z.object({
  actionId: ActionIdSchema.meta({ ref: "action" }),
  intent: z.enum(["exposes", "consumes"]).meta({ label: "Intent" })
});
var SlashCommandInvocationSchema = z.object({
  kind: z.literal("slash-command"),
  command: z.string().trim().min(1).max(200).regex(/^\/[^\s].*$/, "Slash commands must start with /"),
  toolFactory: ModelIdSchema.optional()
});
var McpToolInvocationSchema = z.object({
  kind: z.literal("mcp-tool"),
  server: ModelIdSchema,
  name: ModelIdSchema
});
var ApiEndpointInvocationSchema = z.object({
  kind: z.literal("api-endpoint"),
  method: z.enum(["GET", "POST", "PATCH", "DELETE"]).meta({ label: "HTTP method" }),
  path: z.string().trim().startsWith("/").max(500),
  requestSchema: ModelIdSchema.optional(),
  responseSchema: ModelIdSchema.optional()
});
var ScriptExecutionInvocationSchema = z.object({
  kind: z.literal("script-execution"),
  resourceId: ActionResourceIdSchema
});
var ActionInvocationSchema = z.discriminatedUnion("kind", [
  SlashCommandInvocationSchema,
  McpToolInvocationSchema,
  ApiEndpointInvocationSchema,
  ScriptExecutionInvocationSchema
]);
var ActionSchema = z.object({
  id: ActionIdSchema,
  /** Domain-map iteration order. Convention: multiples of 10 (10, 20, 30, ...) to allow easy insertion. */
  order: z.number(),
  label: LabelSchema,
  description: DescriptionSchema.optional(),
  scope: ActionScopeSchema.default("global"),
  resourceId: ActionResourceIdSchema.optional(),
  affects: z.array(EntityIdSchema.meta({ ref: "entity" })).optional(),
  invocations: z.array(ActionInvocationSchema).default([]),
  knowledge: z.array(ModelIdSchema.meta({ ref: "knowledge" })).default([]).optional(),
  lifecycle: z.enum(["draft", "beta", "active", "deprecated", "archived"]).meta({ label: "Lifecycle", color: "teal" }).default("active")
});
var ActionsDomainSchema = z.record(z.string(), ActionSchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
  message: "Each action entry id must match its map key"
}).default({});
var DEFAULT_ORGANIZATION_MODEL_ACTIONS = {};
function defineActions(entries) {
  return defineDomainRecord(ActionSchema, entries);
}
var OntologyKindSchema = z.enum([
  "object",
  "link",
  "action",
  "catalog",
  "event",
  "interface",
  "value-type",
  "property",
  "group",
  "endpoint"
]);
var SYSTEM_PATH_PATTERN = "[a-z0-9][a-z0-9-]*(?:\\.[a-z0-9][a-z0-9-]*)*";
var LOCAL_ID_PATTERN = "[a-z0-9][a-z0-9._-]*";
var ONTOLOGY_ID_PATTERN = `^(global|${SYSTEM_PATH_PATTERN}):(${OntologyKindSchema.options.join("|")})\\/(${LOCAL_ID_PATTERN})$`;
var ONTOLOGY_ID_REGEX = new RegExp(ONTOLOGY_ID_PATTERN);
var OntologyIdSchema = z.string().trim().min(1).max(300).regex(ONTOLOGY_ID_REGEX, "Ontology IDs must use <system-path>:<kind>/<local-id> or global:<kind>/<local-id>");
function parseOntologyId(id) {
  const normalized = OntologyIdSchema.parse(id);
  const match = ONTOLOGY_ID_REGEX.exec(normalized);
  if (match === null) {
    throw new Error(`Invalid ontology ID "${id}"`);
  }
  return {
    id: normalized,
    scope: match[1],
    kind: match[2],
    localId: match[3],
    isGlobal: match[1] === "global"
  };
}
function formatOntologyId(input) {
  return OntologyIdSchema.parse(`${input.scope}:${input.kind}/${input.localId}`);
}
var OntologyReferenceListSchema = z.array(OntologyIdSchema).default([]).optional();
var OntologyRecordBaseSchema = z.object({
  id: OntologyIdSchema,
  label: z.string().trim().min(1).max(160).optional(),
  description: z.string().trim().min(1).max(2e3).optional(),
  ownerSystemId: z.string().trim().min(1).max(200).optional(),
  aliases: z.array(OntologyIdSchema).optional()
}).passthrough();
var OntologyObjectTypeSchema = OntologyRecordBaseSchema.extend({
  properties: z.record(z.string().trim().min(1).max(200), z.unknown()).optional(),
  storage: z.record(z.string(), z.unknown()).optional()
});
var OntologyLinkTypeSchema = OntologyRecordBaseSchema.extend({
  from: OntologyIdSchema,
  to: OntologyIdSchema,
  cardinality: z.string().trim().min(1).max(80).optional(),
  via: z.string().trim().min(1).max(255).optional()
});
var OntologyActionTypeSchema = OntologyRecordBaseSchema.extend({
  actsOn: OntologyReferenceListSchema,
  input: z.record(z.string().trim().min(1).max(200), z.unknown()).optional(),
  effects: z.array(z.record(z.string(), z.unknown())).optional()
});
var OntologyCatalogTypeSchema = OntologyRecordBaseSchema.extend({
  kind: z.string().trim().min(1).max(120).optional(),
  appliesTo: OntologyIdSchema.optional(),
  entries: z.record(z.string().trim().min(1).max(200), z.unknown()).optional()
});
var OntologyEventTypeSchema = OntologyRecordBaseSchema.extend({
  payload: z.record(z.string().trim().min(1).max(200), z.unknown()).optional()
});
var OntologyInterfaceTypeSchema = OntologyRecordBaseSchema.extend({
  properties: z.record(z.string().trim().min(1).max(200), z.unknown()).optional()
});
var OntologyValueTypeSchema = OntologyRecordBaseSchema.extend({
  primitive: z.string().trim().min(1).max(120).optional()
});
var OntologySharedPropertySchema = OntologyRecordBaseSchema.extend({
  valueType: OntologyIdSchema.optional(),
  searchable: z.boolean().optional(),
  pii: z.boolean().optional()
});
var OntologyGroupSchema = OntologyRecordBaseSchema.extend({
  members: OntologyReferenceListSchema
});
var OntologyEndpointTypeSchema = OntologyRecordBaseSchema.extend({
  route: z.string().trim().min(1).max(500).optional()
});
var OntologyScopeSchema = z.object({
  objectTypes: z.record(OntologyIdSchema, OntologyObjectTypeSchema).default({}).optional(),
  linkTypes: z.record(OntologyIdSchema, OntologyLinkTypeSchema).default({}).optional(),
  actionTypes: z.record(OntologyIdSchema, OntologyActionTypeSchema).default({}).optional(),
  catalogTypes: z.record(OntologyIdSchema, OntologyCatalogTypeSchema).default({}).optional(),
  eventTypes: z.record(OntologyIdSchema, OntologyEventTypeSchema).default({}).optional(),
  interfaceTypes: z.record(OntologyIdSchema, OntologyInterfaceTypeSchema).default({}).optional(),
  valueTypes: z.record(OntologyIdSchema, OntologyValueTypeSchema).default({}).optional(),
  sharedProperties: z.record(OntologyIdSchema, OntologySharedPropertySchema).default({}).optional(),
  groups: z.record(OntologyIdSchema, OntologyGroupSchema).default({}).optional(),
  endpoints: z.record(OntologyIdSchema, OntologyEndpointTypeSchema).default({}).optional()
}).default({});
var DEFAULT_ONTOLOGY_SCOPE = {
  valueTypes: {
    "global:value-type/uuid": {
      id: "global:value-type/uuid",
      label: "UUID",
      primitive: "string"
    },
    "global:value-type/text": {
      id: "global:value-type/text",
      label: "Text",
      primitive: "string"
    },
    "global:value-type/url": {
      id: "global:value-type/url",
      label: "URL",
      primitive: "string"
    },
    "global:value-type/email": {
      id: "global:value-type/email",
      label: "Email",
      primitive: "string"
    }
  }
};
var SCOPE_KIND = {
  objectTypes: "object",
  linkTypes: "link",
  actionTypes: "action",
  catalogTypes: "catalog",
  eventTypes: "event",
  interfaceTypes: "interface",
  valueTypes: "value-type",
  sharedProperties: "property",
  groups: "group",
  endpoints: "endpoint"
};
var SCOPE_KEYS = Object.keys(SCOPE_KIND);
function ontologyGraphNodeId(id) {
  return `ontology:${OntologyIdSchema.parse(id)}`;
}
function listResolvedOntologyRecords(index) {
  return SCOPE_KEYS.flatMap((scopeKey) => {
    const kind = SCOPE_KIND[scopeKey];
    return Object.entries(index[scopeKey]).sort(([leftId], [rightId]) => leftId.localeCompare(rightId)).map(([id, record]) => ({
      id,
      kind,
      record
    }));
  });
}
function originFromContext(context) {
  return {
    kind: context.kind,
    source: context.source,
    path: context.path,
    ...context.systemPath !== void 0 ? { systemPath: context.systemPath } : {},
    ...context.legacyId !== void 0 ? { legacyId: context.legacyId } : {}
  };
}
function createEmptyIndex() {
  return {
    objectTypes: {},
    linkTypes: {},
    actionTypes: {},
    catalogTypes: {},
    eventTypes: {},
    interfaceTypes: {},
    valueTypes: {},
    sharedProperties: {},
    groups: {},
    endpoints: {}
  };
}
function sortResolvedOntologyIndex(index) {
  const sorted = createEmptyIndex();
  for (const scopeKey of SCOPE_KEYS) {
    const target = sorted[scopeKey];
    for (const [id, record] of Object.entries(index[scopeKey]).sort(
      ([leftId], [rightId]) => leftId.localeCompare(rightId)
    )) {
      target[id] = record;
    }
  }
  return sorted;
}
function childSystemsOf2(system) {
  return system.systems ?? system.subsystems ?? {};
}
function addRecord(index, diagnostics, sourcesById, scopeKey, record, context) {
  let parsed;
  try {
    parsed = parseOntologyId(record.id);
  } catch {
    diagnostics.push({
      code: "invalid_ontology_id",
      message: `Invalid ontology ID "${record.id}" from ${context.source} at ${context.path.join(".")}`,
      id: record.id,
      path: context.path,
      source: context.source,
      origin: originFromContext(context)
    });
    return;
  }
  const expectedKind = SCOPE_KIND[scopeKey];
  if (parsed.kind !== expectedKind) {
    diagnostics.push({
      code: "ontology_kind_mismatch",
      message: `Ontology ID "${record.id}" has kind "${parsed.kind}" but was authored in ${scopeKey} (${expectedKind}) at ${context.path.join(".")}`,
      id: record.id,
      path: context.path,
      source: context.source,
      origin: originFromContext(context)
    });
    return;
  }
  const existing = sourcesById.get(parsed.id);
  if (existing !== void 0) {
    diagnostics.push({
      code: "duplicate_ontology_id",
      message: `Duplicate ontology ID "${parsed.id}" from ${context.source} at ${context.path.join(".")} conflicts with ${existing.source} at ${existing.path.join(".")}`,
      id: parsed.id,
      path: context.path,
      source: context.source,
      origin: originFromContext(context),
      existingSource: existing.source,
      existingOrigin: originFromContext(existing)
    });
    return;
  }
  sourcesById.set(parsed.id, context);
  index[scopeKey][parsed.id] = {
    ...record,
    origin: originFromContext(context)
  };
}
function addScope(index, diagnostics, sourcesById, scope, source, path) {
  if (scope === void 0) return;
  for (const scopeKey of SCOPE_KEYS) {
    const records = scope[scopeKey] ?? {};
    for (const [key, record] of Object.entries(records)) {
      addRecord(index, diagnostics, sourcesById, scopeKey, record, {
        source,
        path: [...path, scopeKey, key],
        kind: "authored",
        systemPath: source.startsWith("system:") ? source.slice("system:".length, -".ontology".length) : void 0
      });
    }
  }
}
function legacyObjectId(entity) {
  return formatOntologyId({ scope: entity.ownedBySystemId, kind: "object", localId: entity.id });
}
function legacyActionOwner(action, entities) {
  const firstAffectedEntityId = action.affects?.find((entityId) => entities[entityId] !== void 0);
  if (firstAffectedEntityId !== void 0) {
    return entities[firstAffectedEntityId].ownedBySystemId;
  }
  if (typeof action.scope === "object") {
    return action.scope.domain;
  }
  return "global";
}
function addLegacyEntityProjections(index, diagnostics, sourcesById, entities) {
  for (const entity of Object.values(entities)) {
    const objectType = {
      id: legacyObjectId(entity),
      label: entity.label,
      description: entity.description,
      ownerSystemId: entity.ownedBySystemId,
      ...entity.table !== void 0 ? {
        storage: {
          kind: "table",
          table: entity.table
        }
      } : {},
      ...entity.rowSchema !== void 0 ? { rowSchema: entity.rowSchema } : {},
      ...entity.stateCatalogId !== void 0 ? { stateCatalogId: entity.stateCatalogId } : {}
    };
    addRecord(index, diagnostics, sourcesById, "objectTypes", objectType, {
      source: "legacy.entities",
      path: ["entities", entity.id],
      kind: "projected",
      systemPath: entity.ownedBySystemId,
      legacyId: entity.id
    });
    entity.links?.forEach((link, linkIndex) => {
      const targetEntity = entities[link.toEntity];
      if (targetEntity === void 0) return;
      const linkType = {
        id: formatOntologyId({
          scope: entity.ownedBySystemId,
          kind: "link",
          localId: `${entity.id}-${link.toEntity}-${linkIndex}`
        }),
        label: link.label ?? link.kind,
        ownerSystemId: entity.ownedBySystemId,
        from: legacyObjectId(entity),
        to: legacyObjectId(targetEntity),
        cardinality: link.kind,
        ...link.via !== void 0 ? { via: link.via } : {}
      };
      addRecord(index, diagnostics, sourcesById, "linkTypes", linkType, {
        source: "legacy.entities.links",
        path: ["entities", entity.id, "links", linkIndex],
        kind: "projected",
        systemPath: entity.ownedBySystemId,
        legacyId: `${entity.id}.links.${linkIndex}`
      });
    });
  }
}
function addLegacyActionProjections(index, diagnostics, sourcesById, actions, entities) {
  for (const action of Object.values(actions)) {
    const ownerSystemId = legacyActionOwner(action, entities);
    const actionType = {
      id: formatOntologyId({ scope: ownerSystemId, kind: "action", localId: action.id }),
      label: action.label,
      description: action.description,
      ownerSystemId,
      actsOn: action.affects?.map((entityId) => entities[entityId] ? legacyObjectId(entities[entityId]) : void 0).filter((id) => id !== void 0),
      ...action.resourceId !== void 0 ? { resourceId: action.resourceId } : {},
      ...action.invocations !== void 0 ? { invocations: action.invocations } : {},
      ...action.lifecycle !== void 0 ? { lifecycle: action.lifecycle } : {},
      legacyActionId: action.id
    };
    addRecord(index, diagnostics, sourcesById, "actionTypes", actionType, {
      source: "legacy.actions",
      path: ["actions", action.id],
      kind: "projected",
      systemPath: ownerSystemId,
      legacyId: action.id
    });
  }
}
function addSystemScopes(index, diagnostics, sourcesById, systems, prefix, schemaPath) {
  for (const [key, system] of Object.entries(systems)) {
    const systemPath = prefix ? `${prefix}.${key}` : key;
    const currentPath = [...schemaPath, key];
    addScope(index, diagnostics, sourcesById, system.ontology, `system:${systemPath}.ontology`, [
      ...currentPath,
      "ontology"
    ]);
    addSystemScopes(index, diagnostics, sourcesById, childSystemsOf2(system), systemPath, [
      ...currentPath,
      system.systems !== void 0 ? "systems" : "subsystems"
    ]);
  }
}
function compileOrganizationOntology(model) {
  const ontology = createEmptyIndex();
  const diagnostics = [];
  const sourcesById = /* @__PURE__ */ new Map();
  addScope(ontology, diagnostics, sourcesById, model.ontology, "organization.ontology", ["ontology"]);
  addSystemScopes(ontology, diagnostics, sourcesById, model.systems ?? {}, "", ["systems"]);
  addLegacyEntityProjections(ontology, diagnostics, sourcesById, model.entities ?? {});
  addLegacyActionProjections(ontology, diagnostics, sourcesById, model.actions ?? {}, model.entities ?? {});
  return { ontology: sortResolvedOntologyIndex(ontology), diagnostics };
}

// ../core/src/organization-model/domains/systems.ts
var SystemKindSchema = z.enum(["product", "operational", "platform", "diagnostic"]).meta({ label: "System kind", color: "blue" });
var SystemLifecycleSchema = z.enum(["draft", "beta", "active", "deprecated", "archived"]).meta({ label: "Lifecycle", color: "teal" });
var SystemStatusSchema = z.enum(["active", "deprecated", "archived"]).meta({ label: "Status", color: "teal" });
var SystemIdSchema = ModelIdSchema;
var SystemPathSchema = z.string().trim().min(1).regex(
  /^[a-z0-9][a-z0-9-]*(?:\.[a-z0-9][a-z0-9-]*)*$/,
  'must be a dotted lowercase path (e.g. "sales.lead-gen" or "sales.crm")'
);
var UiPositionSchema = z.enum(["sidebar-primary", "sidebar-bottom"]).meta({ label: "UI position" });
var NodeIdStringSchema = z.string().trim().min(1).max(200).regex(
  /^[a-z][a-z-]*:([a-z0-9-]+)(\.[a-z0-9-]+)*(:[a-z0-9.-]+)*$/,
  "Node references must use kind:dotted-path (e.g. system:sales.crm or resource:lead-gen.company.qualify)"
);
var SystemUiSchema = z.object({
  path: PathSchema,
  surfaces: ReferenceIdsSchema,
  icon: IconNameSchema.optional(),
  order: z.number().int().optional()
});
var SystemInterfaceKeySchema = ModelIdSchema;
var SystemInterfaceLifecycleSchema = z.enum(["draft", "active", "disabled", "deprecated", "archived"]).meta({ label: "System interface lifecycle", color: "teal" });
var SYSTEM_INTERFACE_PROFILES = [
  {
    systemPath: "sales.lead-gen",
    interfaceKey: "api",
    readinessProfile: "sales.lead-gen.api"
  },
  {
    systemPath: "sales.crm",
    interfaceKey: "api",
    readinessProfile: "sales.crm.api"
  },
  {
    systemPath: "sales.lead-gen",
    interfaceKey: "crm-handoff",
    readinessProfile: "sales.lead-gen.crm-handoff"
  }
];
var SYSTEM_INTERFACE_READINESS_PROFILES = SYSTEM_INTERFACE_PROFILES.map(
  (profile) => profile.readinessProfile
);
var SystemInterfaceReadinessProfileSchema = z.enum(SYSTEM_INTERFACE_READINESS_PROFILES);
var SystemInterfaceResourceScopeSchema = z.array(ModelIdSchema).default([]);
var SystemApiInterfaceSchema = z.object({
  lifecycle: SystemInterfaceLifecycleSchema.default("active"),
  readinessProfile: SystemInterfaceReadinessProfileSchema.optional(),
  /**
   * Resource ids that participate in this API interface. This scopes readiness
   * derivation without duplicating authored required/provided contract refs.
   */
  resourceIds: SystemInterfaceResourceScopeSchema.optional()
}).strict();
var SystemInterfaceRefSchema = z.object({
  systemPath: SystemPathSchema,
  interfaceKey: SystemInterfaceKeySchema
}).strict();
var JsonValueSchema = z.lazy(
  () => z.union([
    z.string(),
    z.number(),
    z.boolean(),
    z.null(),
    z.array(JsonValueSchema),
    z.record(z.string(), JsonValueSchema)
  ])
);
var SystemConfigSchema = z.record(z.string().trim().min(1).max(200), JsonValueSchema).default({}).optional();
var SystemEntrySchema = z.object({
  /** Stable tenant-defined system id (e.g. "sys.lead-gen" or "sales.crm"). */
  id: SystemIdSchema,
  /** Human-readable system label shown in UI, governance, and operations surfaces. */
  label: LabelSchema.optional(),
  /** @deprecated Use label. Accepted for pre-consolidation System declarations. */
  title: LabelSchema.optional(),
  /** One-paragraph purpose statement for the bounded context. */
  description: DescriptionSchema.optional(),
  /** Closed system shape enum; catalog values remain tenant-defined. */
  kind: SystemKindSchema.optional(),
  /** Optional self-reference for System hierarchy. */
  parentSystemId: SystemIdSchema.optional(),
  /** Optional UI presence. Systems without UI omit this. */
  ui: SystemUiSchema.optional(),
  /** Canonical lifecycle state. Replaces Feature.enabled/devOnly and System.status. */
  lifecycle: SystemLifecycleSchema.optional(),
  /** Optional role responsible for this system. */
  responsibleRoleId: ModelIdSchema.meta({ ref: "role" }).optional(),
  /** Optional knowledge nodes that govern this system. */
  governedByKnowledge: z.array(ModelIdSchema.meta({ ref: "knowledge" })).default([]).optional(),
  /** Optional actions this system exposes or consumes. */
  actions: z.array(ActionRefSchema).optional(),
  /** Optional operational policies that apply to this system. */
  policies: z.array(ModelIdSchema.meta({ ref: "policy" })).default([]).optional(),
  /** Optional goals this system contributes to. */
  drivesGoals: z.array(ModelIdSchema.meta({ ref: "goal" })).default([]).optional(),
  /** Thin API runtime-boundary marker. Readiness is derived from scoped resources and topology. */
  apiInterface: SystemApiInterfaceSchema.optional(),
  /** @deprecated Use lifecycle. Accepted for one publish cycle. */
  status: SystemStatusSchema.optional(),
  /** @deprecated Use ui.path. Kept for one-cycle Feature compatibility. */
  path: PathSchema.optional(),
  /** @deprecated Use ui.icon. Kept for one-cycle Feature compatibility. */
  icon: IconNameSchema.optional(),
  /** @deprecated UI placement hint, retained for one-cycle compatibility. */
  uiPosition: UiPositionSchema.optional(),
  /** @deprecated Use lifecycle. */
  enabled: z.boolean().optional(),
  /** @deprecated Use lifecycle: "beta". */
  devOnly: z.boolean().optional(),
  requiresAdmin: z.boolean().optional(),
  /** Domain-map iteration order. Convention: multiples of 10 (10, 20, 30, ...) to allow easy insertion. */
  order: z.number(),
  /**
   * System-local JSON settings and defaults. Strongly typed OM fields,
   * secrets, credentials, and runtime state stay outside this bucket.
   */
  config: SystemConfigSchema,
  /**
   * System-owned ontology declarations. `systems` is now the canonical child
   * key; this scope holds the object, action, catalog, link, event, and
   * shared contract records owned by this system.
   */
  ontology: OntologyScopeSchema.optional(),
  /**
   * Recursive child systems, authored via nesting (per L11).
   * The key is the local system id; the full path is computed by joining
   * ancestor keys with `.` (e.g. parent key `'sales'` + child key `'crm'` → `'sales.crm'`).
   * Per Phase 4: `id` and `parentSystemId` fields will be removed in favour of
   * position-derived paths. Both still exist on this schema for backward compat.
   */
  systems: z.lazy(() => z.record(z.string().trim().min(1).max(100), SystemEntrySchema)).optional(),
  /** @deprecated Use systems. Accepted as a compatibility alias during the ontology bridge. */
  subsystems: z.lazy(() => z.record(z.string().trim().min(1).max(100), SystemEntrySchema)).optional()
}).strict().refine((system) => system.label !== void 0 || system.title !== void 0, {
  path: ["label"],
  message: "System must provide label or title"
}).transform((system) => {
  const normalizedSystem = system.systems !== void 0 && system.subsystems === void 0 ? { ...system, subsystems: system.systems } : system;
  if (normalizedSystem.status === void 0) return normalizedSystem;
  console.warn("[organization-model] System.status is deprecated; use System.lifecycle instead.");
  return normalizedSystem.lifecycle === void 0 ? { ...normalizedSystem, lifecycle: normalizedSystem.status } : normalizedSystem;
});
var SystemsDomainSchema = z.record(z.string(), SystemEntrySchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
  message: "Each system entry id must match its map key"
}).default({});
var DEFAULT_ORGANIZATION_MODEL_SYSTEMS = {};

// ../core/src/organization-model/migration-helpers.ts
function catalogRecords(model) {
  return Object.values(compileOrganizationOntology(model).ontology.catalogTypes);
}
function localId(id) {
  return parseOntologyId(id).localId;
}
function systemScope(id, fallback) {
  return parseOntologyId(id).scope || fallback || "";
}
function entriesOf(catalog) {
  return Object.entries(catalog.entries ?? {}).map(([id, value]) => [
    id,
    value && typeof value === "object" && !Array.isArray(value) ? value : {}
  ]);
}
function stringValue(value) {
  return typeof value === "string" ? value : void 0;
}
function stringArray(value) {
  return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
}
function numberValue(value, fallback = 0) {
  return typeof value === "number" ? value : fallback;
}
function stageFromEntry(entryId, entry) {
  return {
    id: entryId,
    label: stringValue(entry.label) ?? entryId,
    order: numberValue(entry.order),
    semanticClass: stringValue(entry.semanticClass) ?? "open",
    surfaceIds: stringArray(entry.surfaceIds),
    resourceIds: stringArray(entry.resourceIds),
    color: stringValue(entry.color)
  };
}
function appliesToLocalId(catalog) {
  const appliesTo = catalog.appliesTo;
  if (appliesTo === void 0) return void 0;
  return parseOntologyId(appliesTo).localId;
}
function appliesToEntityKind(catalog) {
  const id = appliesToLocalId(catalog);
  if (id === "company" || id === "contact" || id === "project" || id === "milestone" || id === "task") return id;
  if (id === "deal") return void 0;
  return void 0;
}
function getAllPipelines(model) {
  return catalogRecords(model).filter((catalog) => catalog.kind === "pipeline").map((catalog) => {
    const pipeline = {
      id: localId(catalog.id),
      label: catalog.label ?? localId(catalog.id),
      ...catalog.description ? { description: catalog.description } : {},
      entityId: appliesToLocalId(catalog) ?? "",
      stages: entriesOf(catalog).map(([entryId, entry]) => stageFromEntry(entryId, entry)).sort((a, b) => a.order - b.order || a.id.localeCompare(b.id))
    };
    return { systemPath: catalog.ownerSystemId ?? systemScope(catalog.id), pipeline };
  }).sort((a, b) => a.systemPath.localeCompare(b.systemPath) || a.pipeline.id.localeCompare(b.pipeline.id));
}
function getAllBuildTemplates(model) {
  const catalogs = catalogRecords(model);
  const stepCatalogs = new Map(
    catalogs.filter((catalog) => catalog.kind === "template-step").map((catalog) => [catalog.id, catalog])
  );
  return catalogs.filter((catalog) => catalog.kind === "template").flatMap(
    (catalog) => entriesOf(catalog).map(([templateId, templateEntry]) => {
      const stepCatalogId = stringValue(templateEntry.stepCatalog);
      const stepCatalog = stepCatalogId !== void 0 ? stepCatalogs.get(stepCatalogId) : void 0;
      const steps = stepCatalog === void 0 ? [] : entriesOf(stepCatalog).sort(
        ([leftId, left], [rightId, right]) => numberValue(left.order, Number.MAX_SAFE_INTEGER) - numberValue(right.order, Number.MAX_SAFE_INTEGER) || leftId.localeCompare(rightId)
      );
      return {
        order: numberValue(templateEntry.order, Number.MAX_SAFE_INTEGER),
        template: {
          id: templateId,
          label: stringValue(templateEntry.label) ?? templateId,
          ...stringValue(templateEntry.description) ? { description: stringValue(templateEntry.description) } : {},
          ...stringValue(templateEntry.color) ? { color: stringValue(templateEntry.color) } : {},
          steps: steps.map(([stepId, step]) => ({
            id: stepId,
            label: stringValue(step.label) ?? stepId,
            ...stringValue(step.description) ? { description: stringValue(step.description) } : {},
            ...step
          }))
        }
      };
    })
  ).sort((a, b) => a.order - b.order || a.template.id.localeCompare(b.template.id)).map(({ template }) => template);
}
function getAllProspectingStages(model, kind) {
  return catalogRecords(model).filter((catalog) => catalog.kind === "stage" && appliesToEntityKind(catalog) === kind).flatMap(
    (catalog) => entriesOf(catalog).map(([entryId, entry]) => ({
      id: entryId,
      label: stringValue(entry.label) ?? entryId,
      order: numberValue(entry.order),
      ...stringValue(entry.color) ? { color: stringValue(entry.color) } : {},
      ...stringValue(entry.description) ? { description: stringValue(entry.description) } : {}
    }))
  ).sort((a, b) => a.order - b.order || a.id.localeCompare(b.id));
}
function getLeadGenStageCatalog(model) {
  const results = {};
  for (const catalog of catalogRecords(model).filter(
    (record) => record.kind === "stage" && (record.ownerSystemId ?? systemScope(record.id)) === "sales.lead-gen"
  )) {
    const catalogEntity = appliesToEntityKind(catalog);
    if (catalogEntity !== "company" && catalogEntity !== "contact") continue;
    for (const [entryId, entry] of entriesOf(catalog)) {
      const entity = entry.entity === "contact" ? "contact" : entry.entity === "company" ? "company" : catalogEntity;
      const additionalEntities = stringArray(entry.additionalEntities).filter(
        (item) => item === "company" || item === "contact"
      );
      const recordEntity = entry.recordEntity === "company" || entry.recordEntity === "contact" ? entry.recordEntity : void 0;
      const recordStageKey = stringValue(entry.recordStageKey);
      results[entryId] = {
        key: entryId,
        label: stringValue(entry.label) ?? entryId,
        description: stringValue(entry.description) ?? "",
        order: numberValue(entry.order),
        entity,
        ...additionalEntities.length > 0 ? { additionalEntities } : {},
        ...recordEntity ? { recordEntity } : {},
        ...recordStageKey ? { recordStageKey } : {}
      };
    }
  }
  return Object.fromEntries(
    Object.entries(results).sort(([, a], [, b]) => a.order - b.order || a.key.localeCompare(b.key))
  );
}
function getAllProjectStatuses(model, appliesTo) {
  return catalogRecords(model).filter((catalog) => catalog.kind === "status-flow" && appliesToEntityKind(catalog) === appliesTo).flatMap(
    (catalog) => entriesOf(catalog).map(([entryId, entry]) => ({
      id: entryId,
      label: stringValue(entry.label) ?? entryId,
      order: numberValue(entry.order),
      ...stringValue(entry.color) ? { color: stringValue(entry.color) } : {},
      ...stringValue(entry.description) ? { description: stringValue(entry.description) } : {}
    }))
  ).sort((a, b) => a.order - b.order || a.id.localeCompare(b.id));
}

// ../core/src/business/acquisition/ontology-validation.ts
var LEAD_GEN_API_INTERFACE = SYSTEM_INTERFACE_PROFILES[0];
var CRM_API_INTERFACE = SYSTEM_INTERFACE_PROFILES[1];
var LEAD_GEN_CRM_HANDOFF_INTERFACE = SYSTEM_INTERFACE_PROFILES[2];
LEAD_GEN_API_INTERFACE.readinessProfile;
CRM_API_INTERFACE.readinessProfile;
LEAD_GEN_CRM_HANDOFF_INTERFACE.readinessProfile;
var LEAD_GEN_LIST_OBJECT_ONTOLOGY_ID = formatOntologyId({
  scope: "sales.lead-gen",
  kind: "object",
  localId: "list"
});
var LEAD_GEN_COMPANY_OBJECT_ONTOLOGY_ID = formatOntologyId({
  scope: "sales.lead-gen",
  kind: "object",
  localId: "company"
});
var LEAD_GEN_CONTACT_OBJECT_ONTOLOGY_ID = formatOntologyId({
  scope: "sales.lead-gen",
  kind: "object",
  localId: "contact"
});
var LEAD_GEN_BUILD_TEMPLATE_CATALOG_ONTOLOGY_ID = formatOntologyId({
  scope: "sales.lead-gen",
  kind: "catalog",
  localId: "build-template"
});
var LEAD_GEN_COMPANY_STAGE_CATALOG_ONTOLOGY_ID = formatOntologyId({
  scope: "sales.lead-gen",
  kind: "catalog",
  localId: "company-stage"
});
var LEAD_GEN_CONTACT_STAGE_CATALOG_ONTOLOGY_ID = formatOntologyId({
  scope: "sales.lead-gen",
  kind: "catalog",
  localId: "contact-stage"
});
var CRM_PIPELINE_CATALOG_ONTOLOGY_ID = formatOntologyId({
  scope: "sales.crm",
  kind: "catalog",
  localId: "crm.pipeline"
});
var LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID = formatOntologyId({
  scope: "sales.lead-gen",
  kind: "catalog",
  localId: "lead-gen.stage-catalog"
});
function createLeadGenStageCatalog(model) {
  return {
    id: LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID,
    label: "Lead Gen Processing Stages",
    ownerSystemId: "sales.lead-gen",
    kind: "processing-stage-catalog",
    entries: Object.fromEntries(
      Object.entries(getLeadGenStageCatalog(model)).map(([key, entry]) => [
        key,
        {
          ...entry
        }
      ])
    ),
    legacyCatalogKey: "LEAD_GEN_STAGE_CATALOG"
  };
}
function isPlainRecord(value) {
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function addReadinessIssue(issues, family, code, message, details = {}) {
  issues.push({
    family,
    code,
    message,
    ...details
  });
}
function formatInterfaceIdentity(systemPath, interfaceKey) {
  return `${systemPath}/${interfaceKey}`;
}
function profileForInterface(systemPath, interfaceKey, readinessProfile) {
  return readinessProfile ?? `${systemPath}.${interfaceKey}`;
}
function readinessMarkerPath(context) {
  return context.interfaceKey === "api" ? `systems.${context.systemPath}.apiInterface` : `systems.${context.systemPath}.derivedCrmHandoffReadiness`;
}
function formatSupportedReadinessProfiles() {
  return SYSTEM_INTERFACE_READINESS_PROFILES.map((profile) => `"${profile}"`).join(", ");
}
function getActiveScopedResources(model, resourceIds, issues, context) {
  const resources = [];
  for (const [index, resourceId] of resourceIds.entries()) {
    const resource = model.resources?.[resourceId];
    const path = `${readinessMarkerPath(context)}.resourceIds.${index}`;
    if (resource === void 0) {
      addReadinessIssue(
        issues,
        "SYSTEM_INTERFACE_NOT_READY",
        "missing-resource",
        `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" scopes missing resource "${resourceId}".`,
        { path, ref: resourceId }
      );
      continue;
    }
    if (resource.systemPath !== context.systemPath) {
      addReadinessIssue(
        issues,
        "SYSTEM_INTERFACE_INVALID",
        "resource-system-mismatch",
        `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" scopes resource "${resourceId}" from system "${resource.systemPath}".`,
        { path, ref: resourceId }
      );
      continue;
    }
    if (resource.status !== "active") {
      addReadinessIssue(
        issues,
        "SYSTEM_INTERFACE_NOT_READY",
        "inactive-resource",
        `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" scopes inactive resource "${resourceId}".`,
        { path, ref: resourceId }
      );
      continue;
    }
    resources.push(resource);
  }
  return resources;
}
function resourceBindingIds(resources, key) {
  return new Set(resources.flatMap((resource) => resource.ontology?.[key] ?? []));
}
function requireScopedBinding(issues, boundIds, bindingKey, ontologyId, context) {
  if (boundIds.has(ontologyId)) return;
  addReadinessIssue(
    issues,
    "SYSTEM_INTERFACE_NOT_READY",
    "missing-resource-binding",
    `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" has no active scoped resource with ontology.${bindingKey} binding "${ontologyId}".`,
    { path: `${readinessMarkerPath(context)}.resourceIds`, ref: ontologyId }
  );
}
function ontologyOwnerMatches(ontologyId, expectedSystemPath, catalog) {
  if (catalog?.ownerSystemId !== void 0) return catalog.ownerSystemId === expectedSystemPath;
  return parseOntologyId(ontologyId).scope === expectedSystemPath;
}
function requireObjectReadiness(issues, index, objectId, context) {
  const object = index.ontology.objectTypes[objectId];
  if (object === void 0) {
    addReadinessIssue(
      issues,
      "SYSTEM_INTERFACE_NOT_READY",
      "missing-object",
      `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" is missing required object type "${objectId}".`,
      { ref: objectId }
    );
    return;
  }
  const ownerSystemId = object.ownerSystemId ?? parseOntologyId(objectId).scope;
  if (ownerSystemId !== context.systemPath) {
    addReadinessIssue(
      issues,
      "SYSTEM_INTERFACE_INVALID",
      "foreign-object",
      `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" requires object "${objectId}" owned by "${ownerSystemId}".`,
      { ref: objectId }
    );
  }
}
function requireCatalogReadiness(issues, index, catalogId, context) {
  const catalog = index.ontology.catalogTypes[catalogId];
  if (catalog === void 0) {
    addReadinessIssue(
      issues,
      "SYSTEM_INTERFACE_NOT_READY",
      "missing-catalog",
      `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" is missing required catalog "${catalogId}".`,
      { ref: catalogId }
    );
    return void 0;
  }
  if (context.allowForeignOwner !== true && !ontologyOwnerMatches(catalogId, context.systemPath, catalog)) {
    addReadinessIssue(
      issues,
      "SYSTEM_INTERFACE_INVALID",
      "foreign-catalog",
      `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" requires catalog "${catalogId}" owned by "${catalog.ownerSystemId ?? parseOntologyId(catalogId).scope}".`,
      { ref: catalogId }
    );
  }
  if (Object.keys(getCatalogEntries(catalog)).length === 0) {
    addReadinessIssue(
      issues,
      "SYSTEM_INTERFACE_NOT_READY",
      "empty-catalog",
      `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" requires catalog entries for "${catalogId}".`,
      { ref: catalogId }
    );
  }
  return catalog;
}
function requireLeadGenInterfaceReadiness(issues, index, resources, context) {
  const reads = resourceBindingIds(resources, "reads");
  const catalogs = resourceBindingIds(resources, "usesCatalogs");
  for (const objectId of [
    LEAD_GEN_LIST_OBJECT_ONTOLOGY_ID,
    LEAD_GEN_COMPANY_OBJECT_ONTOLOGY_ID,
    LEAD_GEN_CONTACT_OBJECT_ONTOLOGY_ID
  ]) {
    requireObjectReadiness(issues, index, objectId, context);
    requireScopedBinding(issues, reads, "reads", objectId, context);
  }
  for (const catalogId of [
    LEAD_GEN_BUILD_TEMPLATE_CATALOG_ONTOLOGY_ID,
    LEAD_GEN_COMPANY_STAGE_CATALOG_ONTOLOGY_ID,
    LEAD_GEN_CONTACT_STAGE_CATALOG_ONTOLOGY_ID
  ]) {
    requireCatalogReadiness(issues, index, catalogId, context);
    requireScopedBinding(issues, catalogs, "usesCatalogs", catalogId, context);
  }
  const templateStepCatalog = findLeadGenTemplateStepCatalog(index);
  if (templateStepCatalog === void 0) {
    addReadinessIssue(
      issues,
      "SYSTEM_INTERFACE_NOT_READY",
      "missing-template-step-catalog",
      `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" is missing a lead-gen template-step catalog.`
    );
  } else {
    requireCatalogReadiness(issues, index, templateStepCatalog.id, context);
    requireScopedBinding(issues, catalogs, "usesCatalogs", templateStepCatalog.id, context);
  }
  const leadGenStageCatalog = requireCatalogReadiness(issues, index, LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID, context);
  return leadGenStageCatalog;
}
function requireCrmInterfaceReadiness(issues, index, resources, context) {
  const catalogs = resourceBindingIds(resources, "usesCatalogs");
  const crmPipelineCatalog = requireCatalogReadiness(issues, index, CRM_PIPELINE_CATALOG_ONTOLOGY_ID, context);
  requireScopedBinding(issues, catalogs, "usesCatalogs", CRM_PIPELINE_CATALOG_ONTOLOGY_ID, context);
  return crmPipelineCatalog;
}
function findSystemInterfaceGrant(model, consumer, provider) {
  return Object.values(model.topology?.relationships ?? {}).find((relationship) => {
    const grant = relationship.metadata?.["systemInterfaceGrant"];
    if (!isPlainRecord(grant) || !isPlainRecord(grant.consumer) || !isPlainRecord(grant.provider)) return false;
    return grant.consumer.systemPath === consumer.systemPath && grant.consumer.interfaceKey === consumer.interfaceKey && grant.provider.systemPath === provider.systemPath && grant.provider.interfaceKey === provider.interfaceKey;
  });
}
function requireHandoffBridgeReadiness(issues, model, context) {
  const crmResult = computeInterfaceReadiness(model, CRM_API_INTERFACE);
  if (!crmResult.ready) {
    for (const issue of crmResult.issues) {
      addReadinessIssue(
        issues,
        "SYSTEM_BRIDGE_NOT_READY",
        issue.code,
        `Provider interface ${formatInterfaceIdentity(CRM_API_INTERFACE.systemPath, CRM_API_INTERFACE.interfaceKey)} is not ready: ${issue.message}`,
        { path: issue.path, ref: issue.ref }
      );
    }
  }
  const bridgeGrant = findSystemInterfaceGrant(model, context, CRM_API_INTERFACE);
  if (bridgeGrant === void 0) {
    addReadinessIssue(
      issues,
      "SYSTEM_BRIDGE_NOT_READY",
      "missing-topology-grant",
      `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" requires a scoped topology grant to "${formatInterfaceIdentity(CRM_API_INTERFACE.systemPath, CRM_API_INTERFACE.interfaceKey)}".`
    );
  }
  return bridgeGrant;
}
function getLeadGenCrmHandoffResourceIds(model) {
  return Object.values(model.resources ?? {}).filter(
    (resource) => resource.systemPath === LEAD_GEN_CRM_HANDOFF_INTERFACE.systemPath && resource.ontology?.usesCatalogs?.includes(CRM_PIPELINE_CATALOG_ONTOLOGY_ID) === true
  ).map((resource) => resource.id);
}
function getSystemInterfaceReadinessMarker(model, request) {
  const system = getSystem(model, request.systemPath);
  if (system === void 0) return void 0;
  if (request.interfaceKey === LEAD_GEN_API_INTERFACE.interfaceKey) {
    return system.apiInterface;
  }
  if (request.systemPath === LEAD_GEN_CRM_HANDOFF_INTERFACE.systemPath && request.interfaceKey === LEAD_GEN_CRM_HANDOFF_INTERFACE.interfaceKey) {
    return {
      lifecycle: "active",
      readinessProfile: LEAD_GEN_CRM_HANDOFF_INTERFACE.readinessProfile,
      resourceIds: getLeadGenCrmHandoffResourceIds(model)
    };
  }
  return void 0;
}
function mergeLeadGenDerivedCatalogs(model) {
  const baseCatalogTypes = model.ontology?.catalogTypes ?? {};
  const derivedCatalogTypes = {};
  if (baseCatalogTypes[LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID] === void 0) {
    derivedCatalogTypes[LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID] = createLeadGenStageCatalog(model);
  }
  if (Object.keys(derivedCatalogTypes).length === 0) return model;
  return {
    ...model,
    ontology: {
      ...model.ontology ?? {},
      catalogTypes: {
        ...baseCatalogTypes,
        ...derivedCatalogTypes
      }
    }
  };
}
function compileBusinessOntology(model, contractId) {
  const compilation = compileOrganizationOntology(mergeLeadGenDerivedCatalogs(model));
  if (compilation.diagnostics.length > 0) {
    const summary = compilation.diagnostics.map((diagnostic) => diagnostic.message).join("; ");
    throw new Error(`${contractId} ontology validation index failed to compile: ${summary}`);
  }
  return {
    ontology: compilation.ontology,
    actionTypesByLegacyId: indexActionTypesByLegacyId(compilation.ontology.actionTypes)
  };
}
function tryCompileBusinessOntology(model, readinessProfile, issues) {
  try {
    return compileBusinessOntology(model, readinessProfile);
  } catch (error) {
    addReadinessIssue(
      issues,
      "SYSTEM_INTERFACE_INVALID",
      "ontology-compile-failed",
      error instanceof Error ? error.message : String(error)
    );
    return void 0;
  }
}
function computeInterfaceReadiness(model, request) {
  const issues = [];
  const system = getSystem(model, request.systemPath);
  const systemInterface = getSystemInterfaceReadinessMarker(model, request);
  const readinessProfile = systemInterface === void 0 ? void 0 : profileForInterface(request.systemPath, request.interfaceKey, systemInterface.readinessProfile);
  const scopedResourceIds = systemInterface?.resourceIds ?? [];
  if (system === void 0) {
    addReadinessIssue(
      issues,
      "SYSTEM_INTERFACE_MISSING",
      "missing-system",
      `System "${request.systemPath}" is missing.`,
      { ref: request.systemPath }
    );
    return {
      ready: false,
      systemPath: request.systemPath,
      interfaceKey: request.interfaceKey,
      scopedResourceIds,
      issues
    };
  }
  if (systemInterface === void 0) {
    addReadinessIssue(
      issues,
      "SYSTEM_INTERFACE_MISSING",
      "missing-interface",
      `System "${request.systemPath}" does not declare interface "${request.interfaceKey}".`,
      { path: readinessMarkerPath(request) }
    );
    return {
      ready: false,
      systemPath: request.systemPath,
      interfaceKey: request.interfaceKey,
      scopedResourceIds,
      issues
    };
  }
  if (systemInterface.lifecycle !== "active") {
    addReadinessIssue(
      issues,
      "SYSTEM_INTERFACE_DISABLED",
      "inactive-interface",
      `System Interface "${formatInterfaceIdentity(request.systemPath, request.interfaceKey)}" lifecycle is "${systemInterface.lifecycle}".`,
      { path: `${readinessMarkerPath(request)}.lifecycle` }
    );
  }
  const supportedProfile = readinessProfile !== void 0 && SYSTEM_INTERFACE_PROFILES.some((profile) => profile.readinessProfile === readinessProfile);
  if (!supportedProfile) {
    addReadinessIssue(
      issues,
      "SYSTEM_INTERFACE_INVALID",
      "unknown-readiness-profile",
      `System Interface "${formatInterfaceIdentity(request.systemPath, request.interfaceKey)}" references unknown readiness profile "${readinessProfile}". Supported profiles: ${formatSupportedReadinessProfiles()}. Custom Systems should not declare apiInterface; route custom behavior through workflows/operations plus ontology, resources, and topology.`,
      { path: `${readinessMarkerPath(request)}.readinessProfile`, ref: readinessProfile }
    );
    return {
      ready: false,
      systemPath: request.systemPath,
      interfaceKey: request.interfaceKey,
      readinessProfile,
      scopedResourceIds,
      issues
    };
  }
  if (scopedResourceIds.length === 0) {
    addReadinessIssue(
      issues,
      "SYSTEM_INTERFACE_NOT_READY",
      "missing-scoped-resources",
      `System Interface "${formatInterfaceIdentity(request.systemPath, request.interfaceKey)}" must scope at least one active resource.`,
      { path: `${readinessMarkerPath(request)}.resourceIds` }
    );
  }
  const checkedReadinessProfile = readinessProfile;
  if (checkedReadinessProfile === void 0) {
    throw new Error("Supported readiness profile unexpectedly resolved to undefined");
  }
  const resources = getActiveScopedResources(model, scopedResourceIds, issues, request);
  const index = tryCompileBusinessOntology(model, checkedReadinessProfile, issues);
  if (index !== void 0) {
    if (checkedReadinessProfile === LEAD_GEN_API_INTERFACE.readinessProfile) {
      requireLeadGenInterfaceReadiness(issues, index, resources, request);
    } else if (checkedReadinessProfile === CRM_API_INTERFACE.readinessProfile) {
      requireCrmInterfaceReadiness(issues, index, resources, request);
    } else if (checkedReadinessProfile === LEAD_GEN_CRM_HANDOFF_INTERFACE.readinessProfile) {
      requireLeadGenInterfaceReadiness(issues, index, resources, request);
      requireCrmInterfaceReadiness(issues, index, resources, { ...request, allowForeignOwner: true });
      requireHandoffBridgeReadiness(issues, model, request);
    }
  }
  return {
    ready: issues.length === 0,
    systemPath: request.systemPath,
    interfaceKey: request.interfaceKey,
    readinessProfile,
    scopedResourceIds,
    issues
  };
}
function findLeadGenTemplateStepCatalog(index) {
  return Object.values(index.ontology.catalogTypes).find(
    (catalog) => catalog.ownerSystemId === "sales.lead-gen" && catalog.kind === "template-step" && catalog.appliesTo === LEAD_GEN_LIST_OBJECT_ONTOLOGY_ID
  );
}
function indexActionTypesByLegacyId(actionTypes) {
  const byLegacyId = {};
  for (const actionType of Object.values(actionTypes)) {
    const legacyActionId = actionType["legacyActionId"];
    if (typeof legacyActionId === "string") {
      byLegacyId[legacyActionId] = actionType;
    }
  }
  return byLegacyId;
}
function getCatalogEntries(catalog) {
  return isPlainRecord(catalog.entries) ? catalog.entries : {};
}

// ../core/src/platform/registry/resource-metadata.ts
var resourceTypeIconNames = {
  agent: "IconBrain",
  workflow: "IconGitBranch",
  trigger: "IconBolt",
  integration: "IconPlug",
  external: "IconExternalLink",
  human: "IconUser"
};
var resourceTypeColors = {
  agent: "violet",
  workflow: "blue",
  trigger: "orange",
  integration: "teal",
  external: "gray",
  human: "yellow"
};
function getResourceIconName(type) {
  return resourceTypeIconNames[type];
}
function getResourceColor(type) {
  return resourceTypeColors[type];
}

// src/utils/resource-icons.tsx
var iconNameToComponent = {
  IconBrain,
  IconGitBranch,
  IconBolt,
  IconPlug,
  IconExternalLink,
  IconUser
};
function getResourceIcon(type) {
  const iconName = getResourceIconName(type);
  return iconNameToComponent[iconName];
}

// src/utils/constants/api.ts
var API_URL = import.meta.env.PROD ? "https://api.elevasis.io" : "http://localhost:5170";

// src/utils/constants/cache.ts
var STALE_TIME_MONITORING = 3e4;
var STALE_TIME_ADMIN = 6e4;
var STALE_TIME_DEFAULT = 3e5;
var GC_TIME_SHORT = 3e5;
var GC_TIME_MEDIUM = 6e5;
var GC_TIME_LONG = 18e5;

// src/utils/constants/ui.ts
var PAGE_SIZE_DEFAULT = 20;
var LIMIT_ACTIVITY_FEED = 50;
var DEBOUNCE_FILTER = 150;
var DEBOUNCE_SLIDER = 500;
var OAUTH_FLOW_TIMEOUT = 3e5;

// src/utils/suppress-warnings.ts
var SUPPRESSED_WARNINGS = [
  // Mantine SegmentedControl data-orientation deprecation warnings
  /Unsupported style property.*data-orientation/i,
  /Did you mean.*dataOrientation/i,
  // Recharts/Mantine Charts dimension warnings (charts work fine after layout completes)
  /The width\(-1\) and height\(-1\) of chart should be greater than 0/i
];
var originalConsoleError = console.error;
var originalConsoleWarn = console.warn;
function suppressKnownWarnings() {
  console.error = (...args) => {
    const message = args.join(" ");
    const shouldSuppress = SUPPRESSED_WARNINGS.some((pattern) => pattern.test(message));
    if (!shouldSuppress) {
      originalConsoleError(...args);
    }
  };
  console.warn = (...args) => {
    const message = args.join(" ");
    const shouldSuppress = SUPPRESSED_WARNINGS.some((pattern) => pattern.test(message));
    if (!shouldSuppress) {
      originalConsoleWarn(...args);
    }
  };
}
function restoreConsole() {
  console.error = originalConsoleError;
  console.warn = originalConsoleWarn;
}

// src/utils/browser-mocks.ts
function setupMatchMedia() {
  const win = globalThis.window;
  if (typeof win === "undefined") return;
  Object.defineProperty(win, "matchMedia", {
    writable: true,
    value: (query) => ({
      matches: false,
      media: query,
      onchange: null,
      addListener: () => {
      },
      removeListener: () => {
      },
      addEventListener: () => {
      },
      removeEventListener: () => {
      },
      dispatchEvent: () => true
    })
  });
}
function setupResizeObserver() {
  globalThis.ResizeObserver = class ResizeObserver {
    observe() {
    }
    unobserve() {
    }
    disconnect() {
    }
  };
}
function setupBrowserMocks() {
  setupMatchMedia();
  setupResizeObserver();
}

export { APIClientError, API_URL, ActionInvocationSchema, ActionSchema, ActionsDomainSchema, DEBOUNCE_FILTER, DEBOUNCE_SLIDER, DEFAULT_ONTOLOGY_SCOPE, DEFAULT_ORGANIZATION_MODEL_ACTIONS, DEFAULT_ORGANIZATION_MODEL_SYSTEMS, DescriptionSchema, EntitiesDomainSchema, EntitySchema, GC_TIME_LONG, GC_TIME_MEDIUM, GC_TIME_SHORT, IconNameSchema, JsonValueSchema, LEAD_GEN_API_INTERFACE, LIMIT_ACTIVITY_FEED, LabelSchema, ModelIdSchema, NodeIdStringSchema, OAUTH_FLOW_TIMEOUT, OntologyIdSchema, OntologyScopeSchema, PAGE_SIZE_DEFAULT, PathSchema, STALE_TIME_ADMIN, STALE_TIME_DEFAULT, STALE_TIME_MONITORING, SystemEntrySchema, SystemIdSchema, SystemInterfaceRefSchema, SystemLifecycleSchema, SystemPathSchema, SystemsDomainSchema, ancestorsOf, childrenOf, compileOrganizationOntology, computeInterfaceReadiness, defaultPathFor, defineActions, defineEntities, devOnlyFor, findById, findByPath, formatChartAxisDate, formatDate, formatDateTime, formatErrorMessage, formatRelativeTime, formatTimeAgo, getAllBuildTemplates, getAllPipelines, getAllProjectStatuses, getAllProspectingStages, getErrorInfo, getErrorTitle, getLeadGenStageCatalog, getResourceColor, getResourceIcon, getResourcesForSystem, getSystem, getSystemAncestors, isAPIClientError, listAllSystems, listResolvedOntologyRecords, ontologyGraphNodeId, parentOf, parseOntologyId, requiresAdminFor, resolveSystemConfig, restoreConsole, setupBrowserMocks, suppressKnownWarnings, topLevel, validateEmail };
