<!-- @generated by packages/sdk/scripts/copy-reference-docs.mjs -- DO NOT EDIT -->
<!-- Regenerate: pnpm scaffold:sync -->

<!-- @generated by scripts/monorepo/generate-scaffold-contracts.js — DO NOT EDIT -->
<!-- Regenerate: pnpm scaffold:sync -->
---
title: Reference Contracts
description: Auto-generated TypeScript contracts for SDK consumers. Do not edit manually.
---

> **Auto-generated** from source types. Do not edit manually. Run `node scripts/monorepo/generate-scaffold-contracts.js` to regenerate.

## Organization Model

### `OrganizationModel`

```typescript
export type OrganizationModel = z.infer<typeof OrganizationModelSchema>
```

### `OrganizationModelDomainKey`

```typescript
export type OrganizationModelDomainKey = z.infer<typeof OrganizationModelDomainKeySchema>
```

### `OrganizationModelDomainMetadata`

```typescript
export type OrganizationModelDomainMetadata = z.infer<typeof OrganizationModelDomainMetadataSchema>
```

### `OrganizationModelDomainMetadataByDomain`

```typescript
export type OrganizationModelDomainMetadataByDomain = z.infer<typeof OrganizationModelDomainMetadataByDomainSchema>
```

### `OrganizationModelBranding`

```typescript
export type OrganizationModelBranding = z.infer<typeof OrganizationModelBrandingSchema>
```

### `ClientProfile`

```typescript
export type ClientProfile = z.infer<typeof ClientProfileSchema>
```

### `ClientProfileBranding`

```typescript
export type ClientProfileBranding = z.infer<typeof ClientProfileBrandingSchema>
```

### `ClientProfileIdentity`

```typescript
export type ClientProfileIdentity = z.infer<typeof ClientProfileIdentitySchema>
```

### `ClientProfileLinks`

```typescript
export type ClientProfileLinks = z.infer<typeof ClientProfileLinksSchema>
```

### `ClientProfilePrompts`

```typescript
export type ClientProfilePrompts = z.infer<typeof ClientProfilePromptsSchema>
```

### `ClientProfileSource`

```typescript
export type ClientProfileSource = z.infer<typeof ClientProfileSourceSchema>
```

### `ClientProfileStatus`

```typescript
export type ClientProfileStatus = z.infer<typeof ClientProfileStatusSchema>
```

### `ClientProfileWorkspace`

```typescript
export type ClientProfileWorkspace = z.infer<typeof ClientProfileWorkspaceSchema>
```

### `OrganizationModelClients`

```typescript
export type OrganizationModelClients = z.infer<typeof ClientProfilesDomainSchema>
```

### `SalesPipeline`

```typescript
export type SalesPipeline = z.infer<typeof SalesPipelineSchema>
```

### `SalesStage`

```typescript
export type SalesStage = z.infer<typeof SalesStageSchema>
```

### `ProspectingBuildTemplate`

```typescript
export type ProspectingBuildTemplate = z.infer<typeof ProspectingBuildTemplateSchema>
```

### `ProspectingLifecycleStage`

```typescript
export type ProspectingLifecycleStage = z.infer<typeof ProspectingLifecycleStageSchema>
```

### `ProjectsDomainState`

```typescript
export type ProjectsDomainState = z.infer<typeof ProjectsDomainStateSchema>
```

### `NodeIdPath`

```typescript
export type NodeIdPath = z.infer<typeof NodeIdPathSchema>
```

### `NodeIdString`

```typescript
export type NodeIdString = z.infer<typeof NodeIdStringSchema>
```

### `OrganizationModelSurface`

```typescript
export type OrganizationModelSurface = z.infer<typeof SurfaceDefinitionSchema>
```

### `OrganizationModelNavigationGroup`

```typescript
export type OrganizationModelNavigationGroup = z.infer<typeof NavigationGroupSchema>
```

### `OrganizationModelNavigation`

```typescript
export type OrganizationModelNavigation = z.infer<typeof OrganizationModelNavigationSchema>
```

### `OrganizationModelSidebar`

```typescript
export type OrganizationModelSidebar = z.infer<typeof SidebarNavigationSchema>
```

### `OrganizationModelSidebarSection`

```typescript
export type OrganizationModelSidebarSection = z.infer<typeof SidebarSectionSchema>
```

### `OrganizationModelSidebarNode`

```typescript
export type OrganizationModelSidebarNode = z.infer<typeof SidebarNodeSchema>
```

### `OrganizationModelSidebarSurfaceTargets`

```typescript
export type OrganizationModelSidebarSurfaceTargets = z.infer<typeof SidebarSurfaceTargetsSchema>
```

### `OrganizationModelSidebarSurfaceNode`

```typescript
export type OrganizationModelSidebarSurfaceNode = Extract<OrganizationModelSidebarNode, { type: 'surface' }>
```

### `OrganizationModelSidebarGroupNode`

```typescript
export type OrganizationModelSidebarGroupNode = Extract<OrganizationModelSidebarNode, { type: 'group' }>
```

### `OrganizationModelTopbarActionNode`

```typescript
export type OrganizationModelTopbarActionNode = z.infer<typeof TopbarActionNodeSchema>
```

### `OrganizationModelTopbarSection`

```typescript
export type OrganizationModelTopbarSection = z.infer<typeof TopbarSectionSchema>
```

### `OrganizationModelTechStackEntry`

```typescript
export type OrganizationModelTechStackEntry = z.infer<typeof TechStackEntrySchema>
```

### `OrganizationModelStatuses`

```typescript
export type OrganizationModelStatuses = z.infer<typeof StatusesDomainSchema>
```

### `OrganizationModelStatusEntry`

```typescript
export type OrganizationModelStatusEntry = z.infer<typeof StatusEntrySchema>
```

### `OrganizationModelStatusSemanticClass`

```typescript
export type OrganizationModelStatusSemanticClass = z.infer<typeof StatusSemanticClassSchema>
```

### `OrganizationModelCustomers`

```typescript
export type OrganizationModelCustomers = z.infer<typeof CustomersDomainSchema>
```

### `OrganizationModelCustomerSegment`

```typescript
export type OrganizationModelCustomerSegment = z.infer<typeof CustomerSegmentSchema>
```

### `OrganizationModelCustomerFirmographics`

```typescript
export type OrganizationModelCustomerFirmographics = z.infer<typeof FirmographicsSchema>
```

### `OrganizationModelOfferings`

```typescript
export type OrganizationModelOfferings = z.infer<typeof OfferingsDomainSchema>
```

### `OrganizationModelProduct`

```typescript
export type OrganizationModelProduct = z.infer<typeof ProductSchema>
```

### `OrganizationModelPricingModel`

```typescript
export type OrganizationModelPricingModel = z.infer<typeof PricingModelSchema>
```

### `OrganizationModelRoles`

```typescript
export type OrganizationModelRoles = z.infer<typeof RolesDomainSchema>
```

### `OrganizationModelRole`

```typescript
export type OrganizationModelRole = z.infer<typeof RoleSchema>
```

### `OrganizationModelRoleId`

```typescript
export type OrganizationModelRoleId = z.infer<typeof RoleIdSchema>
```

### `OrganizationModelRoleHolder`

```typescript
export type OrganizationModelRoleHolder = z.infer<typeof RoleHolderSchema>
```

### `OrganizationModelHumanRoleHolder`

```typescript
export type OrganizationModelHumanRoleHolder = z.infer<typeof HumanRoleHolderSchema>
```

### `OrganizationModelAgentRoleHolder`

```typescript
export type OrganizationModelAgentRoleHolder = z.infer<typeof AgentRoleHolderSchema>
```

### `OrganizationModelTeamRoleHolder`

```typescript
export type OrganizationModelTeamRoleHolder = z.infer<typeof TeamRoleHolderSchema>
```

### `OrganizationModelGoals`

```typescript
export type OrganizationModelGoals = z.infer<typeof GoalsDomainSchema>
```

### `OrganizationModelObjective`

```typescript
export type OrganizationModelObjective = z.infer<typeof ObjectiveSchema>
```

### `OrganizationModelKeyResult`

```typescript
export type OrganizationModelKeyResult = z.infer<typeof KeyResultSchema>
```

### `OrganizationModelOntology`

```typescript
export type OrganizationModelOntology = z.infer<typeof OntologyScopeSchema>
```

### `OrganizationModelSystems`

```typescript
export type OrganizationModelSystems = z.infer<typeof SystemsDomainSchema>
```

### `OrganizationModelSystemEntry`

```typescript
export type OrganizationModelSystemEntry = z.infer<typeof SystemEntrySchema>
```

### `OrganizationModelSystemConfig`

```typescript
export type OrganizationModelSystemConfig = z.infer<typeof SystemConfigSchema>
```

### `OrganizationModelSystemId`

```typescript
export type OrganizationModelSystemId = z.infer<typeof SystemIdSchema>
```

### `OrganizationModelSystemPath`

```typescript
export type OrganizationModelSystemPath = z.infer<typeof SystemPathSchema>
```

### `OrganizationModelSystemKind`

```typescript
export type OrganizationModelSystemKind = z.infer<typeof SystemKindSchema>
```

### `OrganizationModelSystemLifecycle`

```typescript
export type OrganizationModelSystemLifecycle = z.infer<typeof SystemLifecycleSchema>
```

### `OrganizationModelSystemInterfaceKey`

```typescript
export type OrganizationModelSystemInterfaceKey = z.infer<typeof SystemInterfaceKeySchema>
```

### `OrganizationModelSystemInterfaceLifecycle`

```typescript
export type OrganizationModelSystemInterfaceLifecycle = z.infer<typeof SystemInterfaceLifecycleSchema>
```

### `OrganizationModelSystemInterfaceReadinessProfile`

```typescript
export type OrganizationModelSystemInterfaceReadinessProfile = z.infer<typeof SystemInterfaceReadinessProfileSchema>
```

### `OrganizationModelSystemApiInterface`

```typescript
export type OrganizationModelSystemApiInterface = z.infer<typeof SystemApiInterfaceSchema>
```

### `OrganizationModelSystemInterfaceRef`

```typescript
export type OrganizationModelSystemInterfaceRef = z.infer<typeof SystemInterfaceRefSchema>
```

### `OrganizationModelSystemStatus`

```typescript
/** @deprecated Use OrganizationModelSystemLifecycle. Accepted for one publish cycle. */
export type OrganizationModelSystemStatus = z.infer<typeof SystemStatusSchema>
```

### `OrganizationModelResources`

```typescript
export type OrganizationModelResources = z.infer<typeof ResourcesDomainSchema>
```

### `OrganizationModelResourceEntry`

```typescript
export type OrganizationModelResourceEntry = z.infer<typeof ResourceEntrySchema>
```

### `OrganizationModelResourceId`

```typescript
export type OrganizationModelResourceId = z.infer<typeof ResourceIdSchema>
```

### `OrganizationModelCodeReference`

```typescript
export type OrganizationModelCodeReference = z.infer<typeof CodeReferenceSchema>
```

### `OrganizationModelCodeReferenceRole`

```typescript
export type OrganizationModelCodeReferenceRole = z.infer<typeof CodeReferenceRoleSchema>
```

### `EventId`

```typescript
export type EventId = z.infer<typeof EventIdSchema>
```

### `EventEmissionDescriptor`

```typescript
export type EventEmissionDescriptor = z.infer<typeof EventEmissionDescriptorSchema>
```

### `EventDescriptor`

```typescript
export type EventDescriptor = z.infer<typeof EventDescriptorSchema>
```

### `OrganizationModelResourceKind`

```typescript
export type OrganizationModelResourceKind = z.infer<typeof ResourceKindSchema>
```

### `OrganizationModelResourceGovernanceStatus`

```typescript
export type OrganizationModelResourceGovernanceStatus = z.infer<typeof ResourceGovernanceStatusSchema>
```

### `OrganizationModelResourceOntologyBinding`

```typescript
export type OrganizationModelResourceOntologyBinding = z.infer<typeof ResourceOntologyBindingSchema>
```

### `OrganizationModelContractRef`

```typescript
export type OrganizationModelContractRef = z.infer<typeof ContractRefSchema>
```

### `OrganizationModelResourceOntologyBindingContract`

```typescript
export type OrganizationModelResourceOntologyBindingContract = ResourceOntologyBindingContract
```

### `OrganizationModelAgentKind`

```typescript
export type OrganizationModelAgentKind = z.infer<typeof AgentKindSchema>
```

### `OrganizationModelScriptResourceLanguage`

```typescript
export type OrganizationModelScriptResourceLanguage = z.infer<typeof ScriptResourceLanguageSchema>
```

### `OrganizationModelScriptResourceSource`

```typescript
export type OrganizationModelScriptResourceSource = z.infer<typeof ScriptResourceSourceSchema>
```

### `OrganizationModelWorkflowResourceEntry`

```typescript
export type OrganizationModelWorkflowResourceEntry = z.infer<typeof WorkflowResourceEntrySchema>
```

### `OrganizationModelAgentResourceEntry`

```typescript
export type OrganizationModelAgentResourceEntry = z.infer<typeof AgentResourceEntrySchema>
```

### `OrganizationModelIntegrationResourceEntry`

```typescript
export type OrganizationModelIntegrationResourceEntry = z.infer<typeof IntegrationResourceEntrySchema>
```

### `OrganizationModelScriptResourceEntry`

```typescript
export type OrganizationModelScriptResourceEntry = z.infer<typeof ScriptResourceEntrySchema>
```

### `OrganizationModelTopology`

```typescript
export type OrganizationModelTopology = z.infer<typeof OmTopologyDomainSchema>
```

### `OrganizationModelTopologyNodeKind`

```typescript
export type OrganizationModelTopologyNodeKind = z.infer<typeof OmTopologyNodeKindSchema>
```

### `OrganizationModelTopologyNodeRef`

```typescript
export type OrganizationModelTopologyNodeRef = z.infer<typeof OmTopologyNodeRefSchema>
```

### `OrganizationModelTopologyRelationshipKind`

```typescript
export type OrganizationModelTopologyRelationshipKind = z.infer<typeof OmTopologyRelationshipKindSchema>
```

### `OrganizationModelTopologyRelationship`

```typescript
export type OrganizationModelTopologyRelationship = z.infer<typeof OmTopologyRelationshipSchema>
```

### `OrganizationModelTopologyMetadata`

```typescript
export type OrganizationModelTopologyMetadata = z.infer<typeof OmTopologyMetadataSchema>
```

### `OrganizationModelTopologySystemInterfaceGrant`

```typescript
export type OrganizationModelTopologySystemInterfaceGrant = z.infer<typeof OmTopologySystemInterfaceGrantSchema>
```

### `OrganizationModelTopologySystemInterfaceGrantMetadata`

```typescript
export type OrganizationModelTopologySystemInterfaceGrantMetadata = z.infer<
  typeof OmTopologySystemInterfaceGrantMetadataSchema
>
```

### `OrganizationModelActions`

```typescript
export type OrganizationModelActions = z.infer<typeof ActionsDomainSchema>
```

### `OrganizationModelAction`

```typescript
export type OrganizationModelAction = z.infer<typeof ActionSchema>
```

### `OrganizationModelActionId`

```typescript
export type OrganizationModelActionId = z.infer<typeof ActionIdSchema>
```

### `OrganizationModelActionScope`

```typescript
export type OrganizationModelActionScope = z.infer<typeof ActionScopeSchema>
```

### `OrganizationModelActionRef`

```typescript
export type OrganizationModelActionRef = z.infer<typeof ActionRefSchema>
```

### `OrganizationModelActionInvocationKind`

```typescript
export type OrganizationModelActionInvocationKind = z.infer<typeof ActionInvocationKindSchema>
```

### `OrganizationModelActionInvocation`

```typescript
export type OrganizationModelActionInvocation = z.infer<typeof ActionInvocationSchema>
```

### `EntityId`

```typescript
export type EntityId = z.infer<typeof EntityIdSchema>
```

### `EntityLink`

```typescript
export type EntityLink = z.infer<typeof EntityLinkSchema>
```

### `Entity`

```typescript
export type Entity = z.infer<typeof EntitySchema>
```

### `OrganizationModelEntity`

```typescript
export type OrganizationModelEntity = z.infer<typeof EntitySchema>
```

### `OrganizationModelEntities`

```typescript
export type OrganizationModelEntities = z.infer<typeof EntitiesDomainSchema>
```

### `OrganizationModelPolicies`

```typescript
export type OrganizationModelPolicies = z.infer<typeof PoliciesDomainSchema>
```

### `OrganizationModelPolicy`

```typescript
export type OrganizationModelPolicy = z.infer<typeof PolicySchema>
```

### `OrganizationModelPolicyId`

```typescript
export type OrganizationModelPolicyId = z.infer<typeof PolicyIdSchema>
```

### `OrganizationModelPolicyApplicability`

```typescript
export type OrganizationModelPolicyApplicability = z.infer<typeof PolicyApplicabilitySchema>
```

### `OrganizationModelPolicyTrigger`

```typescript
export type OrganizationModelPolicyTrigger = z.infer<typeof PolicyTriggerSchema>
```

### `OrganizationModelPolicyPredicate`

```typescript
export type OrganizationModelPolicyPredicate = z.infer<typeof PolicyPredicateSchema>
```

### `OrganizationModelPolicyEffect`

```typescript
export type OrganizationModelPolicyEffect = z.infer<typeof PolicyEffectSchema>
```

### `OrganizationModelKnowledge`

```typescript
export type OrganizationModelKnowledge = z.infer<typeof KnowledgeDomainSchema>
```

### `OrgKnowledgeNode`

```typescript
export type OrgKnowledgeNode = z.infer<typeof OrgKnowledgeNodeSchema>
```

### `OrgKnowledgeNodeInput`

```typescript
export type OrgKnowledgeNodeInput = z.input<typeof OrgKnowledgeNodeSchema>
```

### `OrgKnowledgeKind`

```typescript
export type OrgKnowledgeKind = z.infer<typeof OrgKnowledgeKindSchema>
```

### `KnowledgeTargetKind`

```typescript
export type KnowledgeTargetKind = z.infer<typeof KnowledgeTargetKindSchema>
```

### `KnowledgeTargetRef`

```typescript
export type KnowledgeTargetRef = z.infer<typeof KnowledgeTargetRefSchema>
```

### `KnowledgeLink`

```typescript
export type KnowledgeLink = z.infer<typeof KnowledgeLinkSchema>
```

### `OrganizationModelIconToken`

```typescript
export type OrganizationModelIconToken = z.infer<typeof OrganizationModelIconTokenSchema>
```

### `OrganizationModelBuiltinIconToken`

```typescript
export type OrganizationModelBuiltinIconToken = z.infer<typeof OrganizationModelBuiltinIconTokenSchema>
```

### `DeepPartial`

```typescript
export type DeepPartial<T> =
  T extends Array<infer U> ? Array<DeepPartial<U>> : T extends object ? { [K in keyof T]?: DeepPartial<T[K]> } : T
```

## Feature System

### `ElevasisOrganizationModel`

```typescript
export type ElevasisOrganizationModel = Omit<OrganizationModel, 'knowledge'> & {
  knowledge?: OrganizationModel['knowledge']
}
```

### `SystemSidebarComponent`

```typescript
export type SystemSidebarComponent = ComponentType
```

### `SystemIconComponent`

```typescript
export type SystemIconComponent = ComponentType<{ size?: number; stroke?: number }>
```

### `SystemSidebarWidthResolver`

```typescript
export type SystemSidebarWidthResolver = number | ((context: { currentPath: string }) => number)
```

### `SystemModule`

```typescript
export interface SystemModule {
  /** Unique stable identifier for this UI system module. */
  key: string
  /** Organization Model system id this module presents. Omit for navigation-only app surfaces. */
  systemId?: string
  /** Route prefixes owned by navigation-only app surfaces. */
  routePrefixes?: string[]
  /** Capability identifiers contributed by this system module. */
  capabilityIds?: string[]
  /** Icon used when this system node appears in shell navigation. */
  icon?: SystemIconComponent
  /** Sidebar component rendered when this system's subtree route is active. */
  sidebar?: SystemSidebarComponent
  /** Optional shell sidebar width override. Defaults to 250px. */
  sidebarWidth?: SystemSidebarWidthResolver
  /** Operations-only bridge connecting this system to the organization graph node. */
  organizationGraph?: OrganizationGraphSystemBridge
}
```

### `ResolvedSystemAccess`

```typescript
export interface ResolvedSystemAccess {
  systemKey: string
  systemId?: string
  enabled: boolean
}
```

### `ResolvedSystemSemantics`

```typescript
export interface ResolvedSystemSemantics {
  capabilityIds: string[]
}
```

### `ResolvedSystemModule`

```typescript
export interface ResolvedSystemModule extends SystemModule {
  access: ResolvedSystemAccess
  semantics: ResolvedSystemSemantics
}
```

### `ResolvedShellSystem`

```typescript
export type ResolvedShellSystem = OrganizationModelSystemEntry & {
  label: string
  iconComponent?: SystemIconComponent
}
```

### `ResolvedShellModel`

```typescript
export interface ResolvedShellModel {
  systems: readonly ResolvedShellSystem[]
  findByPath: (path: string) => ResolvedShellSystem | undefined
  findById: (id: string) => ResolvedShellSystem | undefined
  childrenOf: (id: string) => ResolvedShellSystem[]
  ancestorsOf: (id: string) => ResolvedShellSystem[]
  parentOf: (id: string) => ResolvedShellSystem | undefined
  topLevel: () => ResolvedShellSystem[]
  requiresAdminFor: (id: string) => boolean
  devOnlyFor: (id: string) => boolean
}
```

### `ShellSidebarLinkItem`

```typescript
export interface ShellSidebarLinkItem {
  label: string
  link: string
  exact?: boolean
  activeMatchPaths?: string[]
}
```

### `ShellSidebarLinkGroup`

```typescript
export interface ShellSidebarLinkGroup {
  icon: SystemIconComponent
  label: string
  links?: ShellSidebarLinkItem[]
  link?: string
}
```

### `ShellSidebarProjectionOptions`

```typescript
export interface ShellSidebarProjectionOptions {
  isPlatformAdmin?: boolean
  isDev?: boolean
  section?: 'primary' | 'bottom'
}
```

### `ShellRouteMatchStatus`

```typescript
export type ShellRouteMatchStatus = 'matched' | 'hidden' | 'unmatched'
```

### `ResolvedShellRouteMatch`

```typescript
export interface ResolvedShellRouteMatch {
  status: ShellRouteMatchStatus
  path: string
  system?: ResolvedSystemModule
  node?: ResolvedShellSystem
}
```

### `ShellRuntime`

```typescript
export interface ShellRuntime {
  resolveRoute: (path: string) => ResolvedShellRouteMatch
}
```

### `ResolvedTopbarAction`

```typescript
/**
 * A resolved topbar action — the OM node after gating/filtering, with icon resolved
 * from the semantic icon registry. Passed to `TopbarActionModule.render`.
 */
export interface ResolvedTopbarAction {
  id: string
  label: string
  tooltip?: string
  icon: TablerIconComponent
  order: number
}
```

### `TopbarActionModule`

```typescript
/**
 * A topbar action module — binds a registry key to UI behavior (a render callback).
 * The key must match `navigation.topbar[id]`. The OM supplies data + visibility;
 * the module supplies behavior.
 */
export interface TopbarActionModule {
  /** Stable key that matches the `id` of a `navigation.topbar` node. */
  key: string
  /** Render the topbar action. Receives the resolved OM node (icon pre-resolved). */
  render: (ctx: { node: ResolvedTopbarAction }) => ReactNode
}
```

### `ResolvedTopbarActionEntry`

```typescript
/** A joined entry emitted by `getTopbarActions`: resolved OM node + module behavior. */
export interface ResolvedTopbarActionEntry {
  node: ResolvedTopbarAction
  render: TopbarActionModule['render']
}
```

### `TopbarActionsProjectionOptions`

```typescript
export interface TopbarActionsProjectionOptions {
  isPlatformAdmin?: boolean
  isDev?: boolean
}
```

### `OrganizationGraphSystemBridge`

```typescript
export interface OrganizationGraphSystemBridge {
  systemId?: string
}
```

### `OrganizationGraphContextValue`

```typescript
export interface OrganizationGraphContextValue {
  available: boolean
  systemId?: string
  systemPath?: string
}
```

### `ElevasisSystemsProviderProps`

```typescript
export interface ElevasisSystemsProviderProps {
  systems?: SystemModule[]
  /** Registered topbar action modules. OM node presence controls visibility; module supplies behavior. */
  topbarActions?: TopbarActionModule[]
  organizationModel?: ElevasisOrganizationModel
  timeRange?: TimeRange
  operationsApiUrl?: string
  operationsSSEManager?: SSEConnectionManagerLike
  deliveryApiUrl?: string
  deliverySSEManager?: SSEConnectionManagerLike
  disabledSubsectionPaths?: string[]
  children: ReactNode
}
```

### `ElevasisSystemsContextValue`

```typescript
export interface ElevasisSystemsContextValue {
  shellModel: ResolvedShellModel
  shellRuntime: ShellRuntime
  getSidebarLinks: (options?: ShellSidebarProjectionOptions) => ShellSidebarLinkGroup[]
  /** Returns the list of topbar actions visible to the current user, in order. */
  getTopbarActions: (options?: TopbarActionsProjectionOptions) => ResolvedTopbarActionEntry[]
  enabledResolvedSystems: ResolvedSystemModule[]
  resolvedSystems: ResolvedSystemModule[]
  organizationGraph: OrganizationGraphContextValue
  organizationModel?: OrganizationModel
  timeRange?: TimeRange
  operationsApiUrl?: string
  operationsSSEManager?: SSEConnectionManagerLike
  deliveryApiUrl?: string
  deliverySSEManager?: SSEConnectionManagerLike
  disabledSubsectionPaths: string[]
  isSystemEnabled: (key: string) => boolean
  getResolvedSystem: (key: string) => ResolvedSystemModule | undefined
}
```

## Resource Registry

### `ResourceStatus`

```typescript
/**
 * Environment/deployment status for resources
 */
export type ResourceStatus = 'dev' | 'prod'
```

### `ResourceType`

```typescript
/**
 * All resource types in the platform
 * Used as the discriminator field in ResourceDefinition
 */
export type ResourceType = 'agent' | 'workflow' | 'trigger' | 'integration' | 'external' | 'human'
```

### `ExecutableResourceType`

```typescript
/**
 * Executable resource types (subset of ResourceType)
 * These resources can be directly executed by the execution engine
 */
export type ExecutableResourceType = 'workflow' | 'agent'
```

### `ResourceSystemSummary`

```typescript
export type ResourceSystemSummary = Pick<SystemEntry, 'id' | 'title' | 'description' | 'kind' | 'lifecycle'>
```

### `ResourceDefinition`

```typescript
/**
 * Base interface for ALL platform resources
 * Shared by both executable (agents, workflows) and non-executable (triggers, integrations, etc.) resources
 */
export interface ResourceDefinition {
  /** Unique resource identifier */
  resourceId: string

  /** Display name */
  name: string

  /** Purpose and functionality description */
  description: string

  /** Version for change tracking and evolution */
  version: string

  /** Resource type discriminator */
  type: ResourceType

  /** Environment/deployment status */
  status: ResourceStatus

  /** Graph links to Organization Model nodes */
  links?: ResourceLink[]

  /** Infrastructure category for filtering */
  category?: ResourceCategory

  /** Whether the agent supports multi-turn sessions (agents only) */
  sessionCapable?: boolean

  /** Whether the resource is local (monorepo) or remote (externally deployed) */
  origin?: 'local' | 'remote'

  /** OM System membership — dot-separated system path (e.g. "sys.lead-gen"), when backed by a Resource descriptor */
  systemPath?: string

  /** Display metadata for the owning OM System */
  system?: ResourceSystemSummary

  /** Governance lifecycle status from the OM Resource descriptor */
  governanceStatus?: ResourceGovernanceStatus

  /** Whether this resource is archived and should be excluded from registration and deployment */
  archived?: boolean
}
```

### `RuntimeResourceDescriptor`

```typescript
export type RuntimeResourceDescriptor = Extract<ResourceEntry, { kind: 'workflow' | 'agent' | 'integration' }>
```

### `DescriptorBackedResourceDefinition`

```typescript
export type DescriptorBackedResourceDefinition<
  TResource extends RuntimeResourceDescriptor = RuntimeResourceDescriptor
> = Omit<ResourceDefinition, 'resourceId' | 'type'> & {
  /** OM descriptor that owns canonical identity and governance metadata. */
  resource: TResource
  resourceId?: never
  type?: never
}
```

### `BoundResourceDefinition`

```typescript
export type BoundResourceDefinition<TResource extends RuntimeResourceDescriptor = RuntimeResourceDescriptor> = Omit<
  DescriptorBackedResourceDefinition<TResource>,
  'resource'
> &
  ResourceDefinition & {
    resource: TResource
    resourceId: TResource['id']
    type: TResource['kind']
  }
```

### `ResourceList`

```typescript
/**
 * Resource list for organization
 * Returns ResourceDefinition metadata (not full definitions)
 */
export interface ResourceList {
  workflows: ResourceDefinition[]
  agents: ResourceDefinition[]
  total: number
  organizationName: string
  environment?: 'dev' | 'prod'
}
```

### `WebhookProviderType`

```typescript
/** Webhook provider identifiers */
export type WebhookProviderType = 'cal-com' | 'stripe' | 'signature-api' | 'instantly' | 'apify' | 'test'
```

### `WebhookTriggerConfig`

```typescript
/** Webhook trigger configuration */
export interface WebhookTriggerConfig {
  /** Provider identifier */
  provider: WebhookProviderType
  /** Event type for documentation (not used for matching - workflow handles routing) */
  event?: string
  /** Optional filtering (e.g., specific form ID for Fillout) */
  filter?: Record<string, string>
  /** References credential in credentials table for per-org webhook secrets */
  credentialName?: string
}
```

### `ScheduleTriggerConfig`

```typescript
/** Schedule trigger configuration */
export interface ScheduleTriggerConfig {
  /** Cron expression (e.g., '0 6 * * *') */
  cron: string
  /** Optional timezone (default: UTC) */
  timezone?: string
}
```

### `EventTriggerConfig`

```typescript
/** Event trigger configuration */
export interface EventTriggerConfig {
  /** Internal event type */
  eventType: string
  /** Event source */
  source?: string
}
```

### `TriggerConfig`

```typescript
/** Union of all trigger configs */
export type TriggerConfig = WebhookTriggerConfig | ScheduleTriggerConfig | EventTriggerConfig
```

### `TriggerDefinition`

```typescript
/**
 * Trigger metadata - entry points that initiate resource execution
 *
 * Triggers represent how executions start: webhooks from external services,
 * scheduled cron jobs, platform events, or manual user actions.
 *
 * BREAKING CHANGES (2025-11-30):
 * - Now extends ResourceDefinition (inherits: resourceId, name, description, version, type, status, links, category)
 * - Field renames: `id` -> `resourceId` (inherited), `type` -> `triggerType`
 * - Relationship rename: `invokes` -> `triggers` (unified vocabulary)
 * - New required fields: `version` (inherited), `type: 'trigger'` (inherited)
 * - triggers object now includes `externalResources` option
 *
 * @example
 * // TriggerDefinition - metadata only
 * {
 *   resourceId: 'trigger-new-order',
 *   type: 'trigger',
 *   triggerType: 'webhook',
 *   name: 'New Order',
 *   description: 'Webhook from Shopify on new orders',
 *   version: '1.0.0',
 *   status: 'prod',
 *   webhookPath: '/webhooks/shopify/orders'
 * }
 *
 * // Relationships declared in ResourceRelationships (not on TriggerDefinition):
 * // relationships: {
 * //   'trigger-new-order': { triggers: { workflows: ['order-fulfillment-workflow'] } }
 * // }
 */
export interface TriggerDefinition extends ResourceDefinition {
  /** Resource type discriminator (narrowed from base union) */
  type: 'trigger'

  /** Trigger mechanism type (renamed from 'type' to avoid collision with base type discriminator) */
  triggerType: 'webhook' | 'schedule' | 'manual' | 'event'

  /** Type-specific configuration */
  config?: TriggerConfig

  // Legacy fields (deprecated, use config instead)
  /** For webhook triggers: path like '/webhooks/shopify/orders' */
  webhookPath?: string
  /** For schedule triggers: cron expression like '0 6 * * *' */
  schedule?: string
  /** For event triggers: event type like 'low-stock-alert' */
  eventType?: string

  // NOTE: What this trigger starts is declared in ResourceRelationships, not here
  // This prevents duplication - triggers are forward-declared in relationships
}
```

### `IntegrationDefinition`

```typescript
/**
 * Integration metadata - external service connections
 *
 * References credentials table for actual connection. No connection status
 * stored here (queried at runtime from credentials table).
 *
 * BREAKING CHANGES (2025-11-30):
 * - Now extends ResourceDefinition (inherits: resourceId, name, description, version, type, status, links, category)
 * - Field renames: `id` -> `resourceId` (inherited)
 * - New required field: `status` (inherited) - organizations must add status to all integrations
 * - New required field: `version` (inherited) - organizations must add version to all integrations
 * - New required field: `type: 'integration'` (inherited) - resource type discriminator
 *
 * @example
 * {
 *   resourceId: 'integration-shopify-prod',
 *   type: 'integration',
 *   provider: 'shopify',
 *   credentialName: 'shopify-prod',
 *   name: 'Shopify Production',
 *   description: 'E-commerce platform',
 *   version: '1.0.0',
 *   status: 'prod'
 * }
 */
export interface IntegrationDefinition extends ResourceDefinition {
  /** Resource type discriminator (narrowed from base union) */
  type: 'integration'

  /** OM descriptor that owns canonical identity and governance metadata. */
  resource?: Extract<ResourceEntry, { kind: 'integration' }>

  /** Integration provider type */
  provider: IntegrationType
  /** References credentials table (e.g., 'shopify-prod', 'zendesk-api') */
  credentialName: string
}
```

### `RelationshipDeclaration`

```typescript
/**
 * Explicit resource relationship declaration
 *
 * Single-direction only - Command View derives reverse relationships.
 * Agents/workflows declare what they trigger and use.
 *
 * @example
 * {
 *   triggers: { workflows: ['order-fulfillment-workflow'] },
 *   uses: { integrations: ['integration-shopify-prod', 'integration-postgres'] }
 * }
 */
export interface RelationshipDeclaration {
  /** Resources this resource triggers */
  triggers?: {
    /** Agent resourceIds this resource triggers */
    agents?: string[]
    /** Workflow resourceIds this resource triggers */
    workflows?: string[]
  }
  /** Integrations this resource uses */
  uses?: {
    /** Integration IDs this resource uses */
    integrations?: string[]
  }
}
```

### `ResourceRelationships`

```typescript
/**
 * Resource relationships map
 * Maps resourceId to its relationship declarations
 *
 * @example
 * {
 *   'order-processor-agent': {
 *     triggers: { workflows: ['order-fulfillment-workflow'] },
 *     uses: { integrations: ['integration-shopify-prod'] }
 *   }
 * }
 */
export type ResourceRelationships = Record<string, RelationshipDeclaration>
```

### `ExternalPlatform`

```typescript
/**
 * External platform type
 * Supported third-party automation platforms
 */
export type ExternalPlatform = 'n8n' | 'make' | 'zapier' | 'other'
```

### `ExternalResourceDefinition`

```typescript
/**
 * External automation resource metadata
 *
 * Represents workflows/automations running on third-party platforms
 * (n8n, Make, Zapier, etc.) for visualization in Command View.
 *
 * NOTE: This is metadata ONLY for visualization. No execution logic,
 * no API integration with external platforms, no status syncing.
 *
 * BREAKING CHANGES (2025-11-30):
 * - Now extends ResourceDefinition (inherits: resourceId, name, description, version, type, status, links, category)
 * - Field renames: `id` -> `resourceId` (inherited)
 * - New required field: `version` (inherited) - organizations must add version to all external resources
 * - New required field: `type: 'external'` (inherited) - resource type discriminator
 * - REMOVED FIELD: `triggeredBy` - per relationship-consolidation design, all relationships are forward-only declarations
 *
 * @example
 * {
 *   resourceId: 'external-n8n-order-sync',
 *   type: 'external',
 *   version: '1.0.0',
 *   platform: 'n8n',
 *   name: 'Shopify Order Sync',
 *   description: 'Legacy n8n workflow for syncing Shopify orders',
 *   status: 'prod',
 *   platformUrl: 'https://n8n.client.com/workflow/123',
 *   triggers: { workflows: ['order-fulfillment-workflow'] },
 *   uses: { integrations: ['integration-shopify-prod'] }
 * }
 */
export interface ExternalResourceDefinition extends ResourceDefinition {
  /** Resource type discriminator (narrowed from base union) */
  type: 'external'

  /** Platform type */
  platform: ExternalPlatform

  // Optional platform-specific metadata
  /** Link to external platform (e.g., n8n workflow editor URL) */
  platformUrl?: string
  /** Platform's internal ID/reference */
  externalId?: string

  /** What this external resource triggers (external -> internal) */
  triggers?: {
    /** Elevasis workflow resourceIds this external automation triggers */
    workflows?: string[]
    /** Elevasis agent resourceIds this external automation triggers */
    agents?: string[]
  }

  /** Integrations this external resource uses (shared credentials) */
  uses?: {
    /** Integration IDs this external automation uses */
    integrations?: string[]
  }

  // NOTE: triggeredBy field removed - per relationship-consolidation design,
  // all relationships are forward-only declarations. Graph edges are built
  // from forward declarations only.
}
```

### `ApiInterfaceConformanceGap`

```typescript
/**
 * Describes a system that has API-backed resources but lacks an `apiInterface`
 * declaration. Used by `detectMissingApiInterfaceDeclarations` as the return
 * payload that drives both CLI warnings and scaffold fill-mode input.
 */
export interface ApiInterfaceConformanceGap {
  /** Dot-separated system path (e.g. "sales.lead-gen"). */
  systemPath: string
  /** Resource IDs in this system that have non-empty ontology bindings. */
  resourceIds: string[]
  /** Human-readable description of the gap. */
  message: string
}
```

### `HumanCheckpointDefinition`

```typescript
/**
 * Human Checkpoint definition - human decision points in automation
 *
 * Represents where human judgment is deployed in the automation landscape.
 * Tasks with matching command_queue_group are routed to this checkpoint.
 *
 * BREAKING CHANGES (2025-11-30):
 * - Now extends ResourceDefinition (inherits: resourceId, name, description, version, type, status, links, category)
 * - Field renames: `id` -> `resourceId` (inherited)
 * - description is now REQUIRED (was optional) - organizations must add description to all human checkpoints
 * - New required field: `version` (inherited) - organizations must add version to all human checkpoints
 * - New required field: `type: 'human'` (inherited) - resource type discriminator
 *
 * @example
 * {
 *   resourceId: 'sales-approval',
 *   type: 'human',
 *   name: 'Sales Approval Queue',
 *   description: 'High-value order approvals for sales team',
 *   version: '1.0.0',
 *   status: 'prod',
 *   requestedBy: { agents: ['order-processor-agent'] },
 *   routesTo: { agents: ['order-fulfillment-agent'] }
 * }
 */
export interface HumanCheckpointDefinition extends ResourceDefinition {
  /** Resource type discriminator (narrowed from base union) */
  type: 'human'

  /** Resources that create tasks for this checkpoint */
  requestedBy?: {
    /** Agent resourceIds that request approval here */
    agents?: string[]
    /** Workflow resourceIds that request approval here */
    workflows?: string[]
  }

  /** Resources that receive approved decisions */
  routesTo?: {
    /** Agent resourceIds that handle approved tasks */
    agents?: string[]
    /** Workflow resourceIds that handle approved tasks */
    workflows?: string[]
  }
}
```

## Deployment Spec

### `DeploymentSpec`

```typescript
/**
 * Organization-specific resource collection
 *
 * Complete manifest of all automation resources for an organization.
 * Used by ResourceRegistry for discovery and Command View for visualization.
 */
export interface DeploymentSpec {
  /** Deployment version (semver) */
  version: string
  /** Optional full Organization Model snapshot used for OM-code validation and deployment persistence */
  organizationModel?: OrganizationModel
  /** Workflow definitions */
  workflows?: WorkflowDefinition[]
  /** Agent definitions */
  agents?: AgentDefinition[]

  // Resource Manifest fields (optional for backwards compatibility)
  /** Trigger definitions - entry points that initiate executions */
  triggers?: TriggerDefinition[]
  /** Integration definitions - external service connections */
  integrations?: IntegrationDefinition[]
  /** Explicit relationship declarations between resources */
  relationships?: ResourceRelationships
  /** External automation resources (n8n, Make, Zapier, etc.) */
  externalResources?: ExternalResourceDefinition[]
  /** Human checkpoint definitions - human decision points in automation */
  humanCheckpoints?: HumanCheckpointDefinition[]
}
```

## CRM Platform Primitives

### `AcqCompany`

```typescript
/**
 * Company record in the acquisition database.
 * Contains enriched company data from various sources.
 * Transformed from AcqCompanyRow with camelCase properties.
 */
export interface AcqCompany {
  id: string
  organizationId: string
  name: string
  domain: string | null
  linkedinUrl: string | null
  website: string | null
  numEmployees: number | null
  foundedYear: number | null
  locationCity: string | null
  locationState: string | null
  category: string | null
  categoryPain: string | null
  segment: string | null
  processingState: CompanyProcessingState | null
  /** @deprecated Use `processingState`. This legacy DB column has been removed; responses return null. */
  pipelineStatus?: LegacyPipelineStatus | null
  enrichmentData: CompanyEnrichmentData | null
  source: string | null
  batchId: string | null
  status: 'active' | 'invalid'
  verticalResearch: string | null
  /** Track A: flat qualification score (null until a scoring rubric is defined). Added by W1 migration. */
  qualificationScore: number | null
  /** Track A: flat qualification signals jsonb preserving the result payload shape. Added by W1 migration. */
  qualificationSignals: Record<string, unknown> | null
  /** Track A: key identifying the rubric used for qualification. Added by W1 migration. */
  qualificationRubricKey: string | null
  createdAt: Date
  updatedAt: Date
}
```

### `AcqContact`

```typescript
/**
 * Contact record in the acquisition database.
 * Contains enriched contact data and personalization content.
 * Transformed from AcqContactRow with camelCase properties.
 */
export interface AcqContact {
  id: string
  organizationId: string
  companyId: string | null
  email: string
  emailValid: 'VALID' | 'INVALID' | 'RISKY' | 'UNKNOWN' | null
  firstName: string | null
  lastName: string | null
  linkedinUrl: string | null
  title: string | null
  headline: string | null
  filterReason: string | null
  openingLine: string | null
  source: string | null
  sourceId: string | null
  processingState: ContactProcessingState | null
  /** @deprecated Use `processingState`. This legacy DB column has been removed; responses return null. */
  pipelineStatus?: LegacyPipelineStatus | null
  enrichmentData: ContactEnrichmentData | null
  /** Attio Person record ID - set when contact responds and is added to CRM */
  attioPersonId: string | null
  batchId: string | null
  status: 'active' | 'invalid'
  createdAt: Date
  updatedAt: Date
}
```

### `DealStage`

```typescript
export type DealStage = 'interested' | 'proposal' | 'closing' | 'closed_won' | 'closed_lost' | 'nurturing'
```

### `DealPriorityBucketKey`

```typescript
export type DealPriorityBucketKey = 'needs_response' | 'follow_up_due' | 'waiting' | 'stale' | 'closed_low'
```

### `DealPriority`

```typescript
export interface DealPriority {
  bucketKey: DealPriorityBucketKey
  rank: number
  label: string
  color: string
  reason: string
  latestActivityAt: string | null
  nextActionAt: string | null
}
```

### `KanbanStageConfig`

```typescript
export interface KanbanStageConfig {
  color: string // Mantine color token (e.g. 'blue', 'teal')
  label?: string // Optional display label override
}
```

### `KanbanBoardConfig`

```typescript
export type KanbanBoardConfig = Partial<Record<DealStage, KanbanStageConfig>>
```

### `DealContact`

```typescript
export interface DealContact {
  id: string
  first_name: string | null
  last_name: string | null
  email: string
  title: string | null
  headline: string | null
  linkedin_url: string | null
  processing_state: Record<string, unknown> | null
  enrichment_data: Record<string, unknown> | null
  company: {
    id: string
    name: string
    domain: string | null
    website: string | null
    linkedin_url: string | null
    segment: string | null
    category: string | null
    num_employees: number | null
  } | null
}
```

### `DealFilters`

```typescript
export interface DealFilters {
  stage?: DealStage
  search?: string
  limit?: number
  offset?: number
}
```

### `DealListItem`

```typescript
/** Deal list item with joined contact and company data */
export interface DealListItem extends AcqDealRow {
  priority: DealPriority
  ownership: 'us' | 'them' | null
  nextAction: string | null
  contact: DealContact | null
}
```

### `DealDetail`

```typescript
export type DealDetail = DealListItem
```

### `AcqDealTaskKind`

```typescript
/** Task kind options for a deal task (human follow-up action type) */
export type AcqDealTaskKind = 'call' | 'email' | 'meeting' | 'other'
```

### `AcqDealTask`

```typescript
/**
 * A CRM to-do item attached to a deal representing a human follow-up action.
 * Transformed from AcqDealTaskRow with camelCase properties.
 */
export interface AcqDealTask {
  id: string
  organizationId: string
  dealId: string
  title: string
  description: string | null
  kind: AcqDealTaskKind
  dueAt: string | null
  assigneeUserId: string | null
  completedAt: string | null
  completedByUserId: string | null
  createdAt: string
  updatedAt: string
  createdByUserId: string | null
}
```

### `CrmPriorityBucketKey`

```typescript
export type CrmPriorityBucketKey = 'needs_response' | 'follow_up_due' | 'waiting' | 'stale' | 'closed_low'
```

### `CrmPriorityBucketDefinition`

```typescript
export interface CrmPriorityBucketDefinition {
  bucketKey: CrmPriorityBucketKey
  label: string
  /** Lower ranks sort first in deal lists and pipeline columns. */
  rank: number
  /** UI color token. Consumers may map this to their design system. */
  color: string
}
```

### `CrmPriorityRuleConfig`

```typescript
export interface CrmPriorityRuleConfig {
  buckets: CrmPriorityBucketDefinition[]
  closedStageKeys: string[]
  followUpAfterDaysByStateKey: Record<string, number>
  staleAfterDays: number
}
```

### `DealStageSchema`

```typescript
export const DealStageSchema = CrmStageKeySchema
```

### `AcqDealTaskKindSchema`

```typescript
export const AcqDealTaskKindSchema = z.enum(['call', 'email', 'meeting', 'other'])
```

### `DealIdParamsSchema`

```typescript
export const DealIdParamsSchema = z.object({
  dealId: UuidSchema
})
```

### `DealTaskIdParamsSchema`

```typescript
export const DealTaskIdParamsSchema = z.object({
  dealId: UuidSchema,
  taskId: UuidSchema
})
```

### `ListDealsQuerySchema`

```typescript
export const ListDealsQuerySchema = z
  .object({
    stage: DealStageSchema.optional(),
    list: UuidSchema.optional(),
    batch: z.string().trim().min(1).max(255).optional(),
    staleSince: z.string().datetime().optional(),
    search: z.string().optional(),
    limit: z.coerce.number().int().positive().default(50),
    offset: z.coerce.number().int().min(0).default(0)
  })
  .strict()
```

### `DealLookupQuerySchema`

```typescript
export const DealLookupQuerySchema = z
  .object({
    search: z.string().trim().min(1).max(200).optional(),
    limit: z.coerce.number().int().min(1).max(25).default(10)
  })
  .strict()
```

### `ListDealTasksDueQuerySchema`

```typescript
export const ListDealTasksDueQuerySchema = z
  .object({
    window: z.enum(['overdue', 'today', 'today_and_overdue', 'upcoming']).optional(),
    assigneeUserId: UuidSchema.optional()
  })
  .strict()
```

### `CreateDealNoteRequestSchema`

```typescript
export const CreateDealNoteRequestSchema = z
  .object({
    body: z.string().trim().min(1).max(10000)
  })
  .strict()
```

### `CreateDealTaskRequestSchema`

```typescript
export const CreateDealTaskRequestSchema = z
  .object({
    title: z.string().trim().min(1).max(255),
    description: z.string().nullable().optional(),
    kind: AcqDealTaskKindSchema.optional(),
    dueAt: z.string().datetime().nullable().optional(),
    assigneeUserId: UuidSchema.nullable().optional()
  })
  .strict()
```

### `TransitionItemRequestSchema`

```typescript
export const TransitionItemRequestSchema = z
  .object({
    pipelineKey: z.string().min(1),
    stageKey: z.string().min(1),
    stateKey: z.string().min(1).nullable().optional(),
    reason: z.string().optional(),
    expectedUpdatedAt: z.string().datetime().optional()
  })
  .strict()
```

### `ExecuteActionParamsSchema`

```typescript
export const ExecuteActionParamsSchema = z
  .object({
    dealId: UuidSchema,
    actionKey: NonEmptyStringSchema
  })
  .strict()
```

### `ExecuteActionRequestSchema`

```typescript
export const ExecuteActionRequestSchema = z
  .object({
    payload: z.record(z.string(), z.unknown()).optional()
  })
  .strict()
```

### `DealContactSummarySchema`

```typescript
/**
 * Contact summary nested inside DealListItem / DealDetailResponse.
 * Matches the joined shape returned by useDeals / useDealDetail Supabase queries.
 */
export const DealContactSummarySchema = z.object({
  id: z.string(),
  first_name: z.string().nullable(),
  last_name: z.string().nullable(),
  email: z.string(),
  title: z.string().nullable(),
  headline: z.string().nullable(),
  linkedin_url: z.string().nullable(),
  processing_state: ProcessingStateSchema.nullable(),
  enrichment_data: z.record(z.string(), z.unknown()).nullable(),
  company: z
    .object({
      id: z.string(),
      name: z.string(),
      domain: z.string().nullable(),
      website: z.string().nullable(),
      linkedin_url: z.string().nullable(),
      segment: z.string().nullable(),
      category: z.string().nullable(),
      num_employees: z.number().nullable()
    })
    .nullable()
})
```

### `DealPrioritySchema`

```typescript
export const DealPrioritySchema = z.object({
  bucketKey: z.enum(['needs_response', 'follow_up_due', 'waiting', 'stale', 'closed_low']),
  rank: z.number().int(),
  label: z.string(),
  color: z.string(),
  reason: z.string(),
  latestActivityAt: z.string().nullable(),
  nextActionAt: z.string().nullable()
})
```

### `DealListItemSchema`

```typescript
/**
 * Deal list item with joined contact (and company via contact).
 * Matches DealListItem from @repo/core types.
 */
export const DealListItemSchema = z.object({
  // acq_deals columns
  id: z.string(),
  organization_id: z.string(),
  client_id: z.string().nullable().optional(),
  contact_id: z.string().nullable(),
  contact_email: z.string(),
  pipeline_key: z.string(),
  stage_key: z.string().nullable(),
  state_key: z.string().nullable(),
  activity_log: z.unknown(),
  discovery_data: z.unknown().nullable(),
  discovery_submitted_at: z.string().nullable(),
  discovery_submitted_by: z.string().nullable(),
  proposal_data: z.unknown().nullable(),
  proposal_sent_at: z.string().nullable(),
  proposal_pdf_url: z.string().nullable(),
  signature_envelope_id: z.string().nullable(),
  source_list_id: z.string().nullable(),
  source_type: z.string().nullable(),
  initial_fee: z.number().nullable(),
  monthly_fee: z.number().nullable(),
  closed_lost_at: z.string().nullable(),
  closed_lost_reason: z.string().nullable(),
  created_at: z.string(),
  updated_at: z.string(),
  priority: DealPrioritySchema,
  ownership: z.enum(['us', 'them']).nullable(),
  nextAction: z.string().nullable(),
  // joined relation
  contact: DealContactSummarySchema.nullable()
})
```

### `DealListResponseSchema`

```typescript
export const DealListResponseSchema = z.object({
  data: z.array(DealListItemSchema),
  total: z.number().int(),
  limit: z.number().int(),
  offset: z.number().int()
})
```

### `DealDetailResponseSchema`

```typescript
/**
 * Deal detail shape — currently the same as a list item (full joined record).
 * Additive fields keep existing DealListItem callers compatible.
 */
export const DealDetailResponseSchema = DealListItemSchema.extend({
  conversation: DealConversationSchema,
  lineage: DealLineageSchema.optional()
})
```

### `DealNoteResponseSchema`

```typescript
/**
 * Single acq_deal_notes row (camelCase API representation).
 */
export const DealNoteResponseSchema = z.object({
  id: z.string(),
  dealId: z.string(),
  organizationId: z.string(),
  authorUserId: z.string().nullable(),
  body: z.string(),
  createdAt: z.string(),
  updatedAt: z.string()
})
```

### `DealNoteListResponseSchema`

```typescript
export const DealNoteListResponseSchema = z.array(DealNoteResponseSchema)
```

### `DealTaskResponseSchema`

```typescript
/**
 * Single acq_deal_tasks row (camelCase API representation).
 * Matches AcqDealTask domain type from types.ts.
 */
export const DealTaskResponseSchema = z.object({
  id: z.string(),
  organizationId: z.string(),
  dealId: z.string(),
  title: z.string(),
  description: z.string().nullable(),
  kind: AcqDealTaskKindSchema,
  dueAt: z.string().nullable(),
  assigneeUserId: z.string().nullable(),
  completedAt: z.string().nullable(),
  completedByUserId: z.string().nullable(),
  createdAt: z.string(),
  updatedAt: z.string(),
  createdByUserId: z.string().nullable()
})
```

### `DealTaskListResponseSchema`

```typescript
export const DealTaskListResponseSchema = z.array(DealTaskResponseSchema)
```

### `DealSchemas`

```typescript
export const DealSchemas = {
  // Primitives
  CrmStageKey: CrmStageKeySchema,
  CrmStateKey: CrmStateKeySchema,
  DealStage: DealStageSchema,

  // Params
  DealIdParams: DealIdParamsSchema,
  DealTaskIdParams: DealTaskIdParamsSchema,

  // Queries
  ListDealsQuery: ListDealsQuerySchema,
  DealLookupQuery: DealLookupQuerySchema,
  ListDealTasksDueQuery: ListDealTasksDueQuerySchema,

  // Request bodies
  CreateDealNoteRequest: CreateDealNoteRequestSchema,
  CreateDealTaskRequest: CreateDealTaskRequestSchema,
  TransitionItemRequest: CrmTransitionItemRequestSchema,
  TransitionDealStateRequest: TransitionDealStateRequestSchema,
  ExecuteActionParams: ExecuteActionParamsSchema,
  ExecuteActionRequest: ExecuteActionRequestSchema,

  // Responses
  DealPriority: DealPrioritySchema,
  DealListResponse: DealListResponseSchema,
  DealSummaryResponse: DealSummaryResponseSchema,
  DealLookupResponse: DealLookupResponseSchema,
  ConversationMessage: ConversationMessageSchema,
  DealLineageListRef: DealLineageListRefSchema,
  DealLineageProjectRef: DealLineageProjectRefSchema,
  DealLineageClientRef: DealLineageClientRefSchema,
  DealLineage: DealLineageSchema,
  DealDetailResponse: DealDetailResponseSchema,
  DealNoteResponse: DealNoteResponseSchema,
  DealNoteListResponse: DealNoteListResponseSchema,
  DealTaskResponse: DealTaskResponseSchema,
  DealTaskListResponse: DealTaskListResponseSchema
}
```

### `Action`

```typescript
export interface Action {
  key: string
  label: string
  payloadSchema?: z.ZodTypeAny
}
```

### `ActionDef`

```typescript
export interface ActionDef {
  key: string
  label: string
  isAvailableFor: (deal: AcqDealRow) => boolean
  workflowId: string
  payloadSchema?: z.ZodTypeAny
}
```

### `CrmToolMap`

```typescript
export type CrmToolMap = {
  getRecentActivity: { params: CrmRecentActivityParams; result: RecentActivityEntry[] }
  listDeals: { params: CrmListDealsParams; result: DealListItem[] }
  getDeal: { params: CrmGetDealParams; result: DealDetail | null }
  getDealByEmail: { params: CrmGetDealByEmailParams; result: DealDetail | null }
  createDealNote: { params: CrmDealNoteParams; result: AcqDealNote }
  listDealNotes: { params: Omit<ListDealNotesParams, 'organizationId'>; result: AcqDealNote[] }
  createDealTask: { params: CrmDealTaskParams; result: AcqDealTask }
  listDealTasks: { params: Omit<ListDealTasksParams, 'organizationId'>; result: AcqDealTask[] }
  listDealTasksDue: { params: CrmTaskDueParams; result: AcqDealTask[] }
  completeDealTask: { params: Omit<CompleteDealTaskParams, 'organizationId'>; result: AcqDealTask }
  recordActivity: { params: CrmRecordActivityParams; result: void }
  deleteDeal: { params: CrmDeleteDealParams; result: void }
}
```

## Lead Gen Platform Primitives

### `WebPost`

```typescript
/**
 * Represents a web post from company website scraping.
 * Used for recent blog posts, news, or announcements.
 */
export interface WebPost {
  /** ISO date string of when the post was published */
  date: string
  /** Title of the web post */
  title: string
  /** Brief summary of the post content */
  summary: string
  /** AI-generated insight about the post's relevance */
  aiInsight?: string
}
```

### `CompanyEnrichmentData`

```typescript
/**
 * Enrichment data collected for a company from various sources.
 */
export interface CompanyEnrichmentData {
  googleMaps?: {
    placeId?: string
    totalScore?: number
    reviewsCount?: number
    address?: string
    phone?: string
    categoryName?: string
    googleMapsUrl?: string
    scrapedAt?: string
  }
  websiteCrawl?: {
    companyDescription?: string
    services?: string[]
    specialties?: string[]
    staff?: Array<{ name: string; title?: string; email?: string }>
    automationGaps?: string[]
    targetAudience?: string
    category?: string
    segment?: string
    recentWin?: string
    emailCount?: number
    pageCount?: number
    totalChars?: number
    crawledAt?: string
    extractedAt?: string
  }
  website?: {
    missionVision?: string
    uniqueAttributes?: string
    coreOfferings?: string
    targetAudience?: string
    companyValues?: string
    businessDescription?: string
    recentPosts?: Array<{ date?: string; title?: string; summary?: string; aiInsight?: string }>
  }
  tomba?: {
    waterfallEmail?: {
      email: string
      name?: string
      title?: string
      department?: string
    } | null
    genericEmail?: string | null
    totalFound?: number
    searchedAt?: string
  }
}
```

### `ContactEnrichmentData`

```typescript
/**
 * Enrichment data collected for a contact from various sources.
 */
export interface ContactEnrichmentData {
  linkedin?: {
    summary?: string
    pastExperience?: string
    education?: string
    activity?: Array<{ date?: string; content?: string }>
  }
}
```

### `AcqList`

```typescript
export interface AcqList {
  id: string
  organizationId: string
  name: string
  description: string | null
  batchIds: string[]
  instantlyCampaignId: string | null
  status: ListStatus
  scrapingConfig: ScrapingConfig
  icp: IcpRubric
  pipelineConfig: PipelineConfig
  metadata: AcqListMetadata
  launchedAt: Date | null
  completedAt: Date | null
  createdAt: Date
}
```

### `AcqCompany`

```typescript
/**
 * Company record in the acquisition database.
 * Contains enriched company data from various sources.
 * Transformed from AcqCompanyRow with camelCase properties.
 */
export interface AcqCompany {
  id: string
  organizationId: string
  name: string
  domain: string | null
  linkedinUrl: string | null
  website: string | null
  numEmployees: number | null
  foundedYear: number | null
  locationCity: string | null
  locationState: string | null
  category: string | null
  categoryPain: string | null
  segment: string | null
  processingState: CompanyProcessingState | null
  /** @deprecated Use `processingState`. This legacy DB column has been removed; responses return null. */
  pipelineStatus?: LegacyPipelineStatus | null
  enrichmentData: CompanyEnrichmentData | null
  source: string | null
  batchId: string | null
  status: 'active' | 'invalid'
  verticalResearch: string | null
  /** Track A: flat qualification score (null until a scoring rubric is defined). Added by W1 migration. */
  qualificationScore: number | null
  /** Track A: flat qualification signals jsonb preserving the result payload shape. Added by W1 migration. */
  qualificationSignals: Record<string, unknown> | null
  /** Track A: key identifying the rubric used for qualification. Added by W1 migration. */
  qualificationRubricKey: string | null
  createdAt: Date
  updatedAt: Date
}
```

### `AcqContact`

```typescript
/**
 * Contact record in the acquisition database.
 * Contains enriched contact data and personalization content.
 * Transformed from AcqContactRow with camelCase properties.
 */
export interface AcqContact {
  id: string
  organizationId: string
  companyId: string | null
  email: string
  emailValid: 'VALID' | 'INVALID' | 'RISKY' | 'UNKNOWN' | null
  firstName: string | null
  lastName: string | null
  linkedinUrl: string | null
  title: string | null
  headline: string | null
  filterReason: string | null
  openingLine: string | null
  source: string | null
  sourceId: string | null
  processingState: ContactProcessingState | null
  /** @deprecated Use `processingState`. This legacy DB column has been removed; responses return null. */
  pipelineStatus?: LegacyPipelineStatus | null
  enrichmentData: ContactEnrichmentData | null
  /** Attio Person record ID - set when contact responds and is added to CRM */
  attioPersonId: string | null
  batchId: string | null
  status: 'active' | 'invalid'
  createdAt: Date
  updatedAt: Date
}
```

### `ListTelemetry`

```typescript
/**
 * Live-scan aggregate telemetry for a single list, computed on demand from
 * the list junction tables and current contact deliverability state.
 * `stageCounts` are attempted counts from list-row processing_state.
 */
export interface ListTelemetry {
  listId: string
  totalCompanies: number
  totalContacts: number
  stageCounts: {
    populated: number
    extracted: number
    qualified: number
    discovered: number
    verified: number
    personalized: number
    uploaded: number
  }
  deliverability: {
    valid: number
    risky: number
    invalid: number
    unknown: number
    bounced: number
  }
  /** Reserved -- active workflow IDs associated with this list. */
  activeWorkflows?: string[]
}
```

### `ListStageCountsSchema`

```typescript
export const ListStageCountsSchema = z.object({
  // Attempted counts by canonical lead-gen stage. The detailed status
  // distribution lives on ListProgress; telemetry keeps the overview payload small.
  stageCounts: z.object({
    populated: z.number().int(),
    extracted: z.number().int(),
    qualified: z.number().int(),
    discovered: z.number().int(),
    verified: z.number().int(),
    personalized: z.number().int(),
    uploaded: z.number().int()
  }),
  deliverability: z.object({
    valid: z.number().int(),
    risky: z.number().int(),
    invalid: z.number().int(),
    unknown: z.number().int(),
    bounced: z.number().int()
  })
})
```

### `ListTelemetrySchema`

```typescript
export const ListTelemetrySchema = z.object({
  listId: UuidSchema,
  totalCompanies: z.number().int(),
  totalContacts: z.number().int(),
  stageCounts: ListStageCountsSchema.shape.stageCounts,
  deliverability: ListStageCountsSchema.shape.deliverability,
  activeWorkflows: z.array(z.string()).optional()
})
```

### `ListIdParamsSchema`

```typescript
export const ListIdParamsSchema = z.object({
  listId: UuidSchema
})
```

### `CreateListRequestSchema`

```typescript
export const CreateListRequestSchema = z
  .object({
    name: z.string().trim().min(1).max(255),
    description: z.string().trim().nullable().optional(),
    status: ListStatusSchema.optional(),
    buildTemplateId: ProspectingBuildTemplateIdSchema.optional(),
    scrapingConfig: ScrapingConfigSchema.optional(),
    icp: IcpRubricSchema.optional(),
    pipelineConfig: PipelineConfigSchema.optional()
  })
  .strict()
```

### `UpdateListRequestSchema`

```typescript
export const UpdateListRequestSchema = z
  .object({
    name: z.string().trim().min(1).max(255).optional(),
    description: z.string().trim().nullable().optional(),
    batchIds: z.array(z.string()).optional(),
    buildTemplateId: ProspectingBuildTemplateIdSchema.optional(),
    confirmBuildTemplateChange: z.literal(true).optional()
  })
  .strict()
  .refine(
    (data) =>
      data.name !== undefined ||
      data.description !== undefined ||
      data.batchIds !== undefined ||
      data.buildTemplateId !== undefined,
    {
      message: 'At least one field (name, description, batchIds, or buildTemplateId) must be provided'
    }
  )
  .refine((data) => data.buildTemplateId === undefined || data.confirmBuildTemplateChange === true, {
    message: 'confirmBuildTemplateChange must be true when changing buildTemplateId',
    path: ['confirmBuildTemplateChange']
  })
```

### `UpdateListConfigRequestSchema`

```typescript
/**
 * Partial patch for the three jsonb config columns. UI sends only the edited
 * subtree; server writes the field as-is (no deep merge — each column is
 * replaced atomically when present in the patch).
 */
export const UpdateListConfigRequestSchema = z
  .object({
    scrapingConfig: ScrapingConfigSchema.partial().optional(),
    icp: IcpRubricSchema.partial().optional(),
    pipelineConfig: PipelineConfigSchema.partial().optional()
  })
  .strict()
  .refine((data) => data.scrapingConfig !== undefined || data.icp !== undefined || data.pipelineConfig !== undefined, {
    message: 'At least one of scrapingConfig, icp, or pipelineConfig must be provided'
  })
```

### `AddCompaniesToListRequestSchema`

```typescript
export const AddCompaniesToListRequestSchema = z
  .object({
    companyIds: z.array(UuidSchema).min(1).max(1000)
  })
  .strict()
```

### `RemoveCompaniesFromListRequestSchema`

```typescript
export const RemoveCompaniesFromListRequestSchema = z
  .object({
    companyIds: z.array(UuidSchema).min(1).max(1000)
  })
  .strict()
```

### `AddContactsToListRequestSchema`

```typescript
export const AddContactsToListRequestSchema = z
  .object({
    contactIds: z.array(UuidSchema).min(1).max(1000)
  })
  .strict()
```

### `RecordListExecutionRequestSchema`

```typescript
export const RecordListExecutionRequestSchema = z
  .object({
    executionId: UuidSchema,
    configSnapshot: z.record(z.string(), z.unknown()).optional()
  })
  .strict()
```

### `AcqListResponseSchema`

```typescript
/**
 * Single list as returned by /api/acquisition/lists/:id etc.
 * Camel-cased domain shape matching AcqList in types.ts.
 */
export const AcqListResponseSchema = z.object({
  id: z.string(),
  organizationId: z.string(),
  name: z.string(),
  description: z.string().nullable(),
  batchIds: z.array(z.string()),
  instantlyCampaignId: z.string().nullable(),
  /** Lifecycle status (draft | enriching | launched | closing | archived). */
  status: ListStatusSchema,
  metadata: AcqListMetadataSchema,
  launchedAt: z.string().nullable(),
  completedAt: z.string().nullable(),
  createdAt: z.string(),
  /** Scraping criteria stored as jsonb on the row. */
  scrapingConfig: ScrapingConfigSchema,
  /** ICP / qualification rubric stored as jsonb on the row. */
  icp: IcpRubricSchema,
  /** Pipeline presentation contract stored as jsonb on the row. */
  pipelineConfig: PipelineConfigSchema
})
```

### `AcqListListResponseSchema`

```typescript
export const AcqListListResponseSchema = z.array(AcqListResponseSchema)
```

### `ListTelemetryResponseSchema`

```typescript
export const ListTelemetryResponseSchema = ListTelemetrySchema
```

### `ListTelemetryListResponseSchema`

```typescript
export const ListTelemetryListResponseSchema = z.array(ListTelemetrySchema)
```

### `ListExecutionSummarySchema`

```typescript
/**
 * Row from acq_list_executions joined with the execution summary,
 * shaped for the /lists/:id/executions response.
 */
export const ListExecutionSummarySchema = z.object({
  executionId: z.string(),
  resourceId: z.string(),
  status: z.string(),
  createdAt: z.string(),
  completedAt: z.string().nullable(),
  durationMs: z.number().int().nullable(),
  input: z.unknown().nullable().optional()
})
```

### `ListExecutionsResponseSchema`

```typescript
export const ListExecutionsResponseSchema = z.array(ListExecutionSummarySchema)
```

### `AcqCompanyStatusSchema`

```typescript
export const AcqCompanyStatusSchema = z.enum(['active', 'invalid'])
```

### `AcqContactStatusSchema`

```typescript
export const AcqContactStatusSchema = z.enum(['active', 'invalid'])
```

### `AcqEmailValidSchema`

```typescript
export const AcqEmailValidSchema = z.enum(['VALID', 'INVALID', 'RISKY', 'UNKNOWN'])
```

### `CompanyIdParamsSchema`

```typescript
export const CompanyIdParamsSchema = z.object({
  companyId: UuidSchema
})
```

### `ContactIdParamsSchema`

```typescript
export const ContactIdParamsSchema = z.object({
  contactId: UuidSchema
})
```

### `ListCompaniesQuerySchema`

```typescript
export const ListCompaniesQuerySchema = z
  .object({
    search: z.string().trim().min(1).max(200).optional(),
    listId: UuidSchema.optional(),
    domain: z.string().trim().min(1).max(255).optional(),
    website: z.string().trim().min(1).max(2048).optional(),
    segment: z.string().trim().min(1).max(255).optional(),
    category: z.string().trim().min(1).max(255).optional(),
    pipelineStatus: z.unknown().optional(),
    batchId: z.string().trim().min(1).max(255).optional(),
    status: AcqCompanyStatusSchema.optional(),
    includeAll: QueryBooleanSchema.optional(),
    limit: z.coerce.number().int().min(1).max(5000).default(50),
    offset: z.coerce.number().int().min(0).default(0)
  })
  .strict()
```

### `ListContactsQuerySchema`

```typescript
export const ListContactsQuerySchema = z
  .object({
    search: z.string().trim().min(1).max(200).optional(),
    listId: UuidSchema.optional(),
    openingLineIsNull: QueryBooleanSchema.optional(),
    batchId: z.string().trim().min(1).max(255).optional(),
    contactStatus: AcqContactStatusSchema.optional(),
    limit: z.coerce.number().int().min(1).max(5000).default(5000),
    offset: z.coerce.number().int().min(0).default(0)
  })
  .strict()
```

### `CreateCompanyRequestSchema`

```typescript
export const CreateCompanyRequestSchema = z
  .object({
    name: z.string().trim().min(1).max(255),
    clientId: UuidSchema.nullable().optional(),
    domain: z.string().trim().min(1).max(255).optional(),
    linkedinUrl: z.string().trim().url().optional(),
    website: z.string().trim().url().optional(),
    numEmployees: z.number().int().min(0).optional(),
    foundedYear: z.number().int().optional(),
    locationCity: z.string().trim().min(1).max(255).optional(),
    locationState: z.string().trim().min(1).max(255).optional(),
    category: z.string().trim().min(1).max(255).optional(),
    source: z.string().trim().min(1).max(255).optional(),
    batchId: z.string().trim().min(1).max(255).optional(),
    pipelineStatus: z.unknown().optional(),
    verticalResearch: z.string().trim().min(1).max(5000).optional()
  })
  .strict()
```

### `UpdateCompanyRequestSchema`

```typescript
export const UpdateCompanyRequestSchema = z
  .object({
    name: z.string().trim().min(1).max(255).optional(),
    clientId: UuidSchema.nullable().optional(),
    domain: z.string().trim().min(1).max(255).optional(),
    linkedinUrl: z.string().trim().url().optional(),
    website: z.string().trim().url().optional(),
    numEmployees: z.number().int().min(0).optional(),
    foundedYear: z.number().int().optional(),
    locationCity: z.string().trim().min(1).max(255).optional(),
    locationState: z.string().trim().min(1).max(255).optional(),
    category: z.string().trim().min(1).max(255).optional(),
    segment: z.string().trim().min(1).max(255).optional(),
    processingState: CompanyProcessingStateSchema.optional(),
    pipelineStatus: z.unknown().optional(),
    enrichmentData: z.record(z.string(), z.unknown()).optional(),
    source: z.string().trim().min(1).max(255).optional(),
    batchId: z.string().trim().min(1).max(255).optional(),
    status: AcqCompanyStatusSchema.optional(),
    verticalResearch: z.string().trim().min(1).max(5000).nullable().optional()
  })
  .strict()
  .refine(
    (data) =>
      data.name !== undefined ||
      data.clientId !== undefined ||
      data.domain !== undefined ||
      data.linkedinUrl !== undefined ||
      data.website !== undefined ||
      data.numEmployees !== undefined ||
      data.foundedYear !== undefined ||
      data.locationCity !== undefined ||
      data.locationState !== undefined ||
      data.category !== undefined ||
      data.segment !== undefined ||
      data.processingState !== undefined ||
      data.pipelineStatus !== undefined ||
      data.enrichmentData !== undefined ||
      data.source !== undefined ||
      data.batchId !== undefined ||
      data.status !== undefined ||
      data.verticalResearch !== undefined,
    {
      message: 'At least one field must be provided'
    }
  )
```

### `CreateContactRequestSchema`

```typescript
export const CreateContactRequestSchema = z
  .object({
    email: z.string().trim().email(),
    clientId: UuidSchema.nullable().optional(),
    companyId: UuidSchema.optional(),
    firstName: z.string().trim().min(1).max(255).optional(),
    lastName: z.string().trim().min(1).max(255).optional(),
    linkedinUrl: z.string().trim().url().optional(),
    title: z.string().trim().min(1).max(255).optional(),
    source: z.string().trim().min(1).max(255).optional(),
    sourceId: z.string().trim().min(1).max(255).optional(),
    batchId: z.string().trim().min(1).max(255).optional(),
    pipelineStatus: z.unknown().optional()
  })
  .strict()
```

### `UpdateContactRequestSchema`

```typescript
export const UpdateContactRequestSchema = z
  .object({
    companyId: UuidSchema.optional(),
    clientId: UuidSchema.nullable().optional(),
    emailValid: AcqEmailValidSchema.optional(),
    firstName: z.string().trim().min(1).max(255).optional(),
    lastName: z.string().trim().min(1).max(255).optional(),
    linkedinUrl: z.string().trim().url().optional(),
    title: z.string().trim().min(1).max(255).optional(),
    headline: z.string().trim().min(1).max(5000).optional(),
    filterReason: z.string().trim().min(1).max(5000).optional(),
    openingLine: z.string().trim().min(1).max(5000).optional(),
    processingState: ContactProcessingStateSchema.optional(),
    pipelineStatus: z.unknown().optional(),
    enrichmentData: z.record(z.string(), z.unknown()).optional(),
    status: AcqContactStatusSchema.optional()
  })
  .strict()
  .refine(
    (data) =>
      data.companyId !== undefined ||
      data.clientId !== undefined ||
      data.emailValid !== undefined ||
      data.firstName !== undefined ||
      data.lastName !== undefined ||
      data.linkedinUrl !== undefined ||
      data.title !== undefined ||
      data.headline !== undefined ||
      data.filterReason !== undefined ||
      data.openingLine !== undefined ||
      data.processingState !== undefined ||
      data.pipelineStatus !== undefined ||
      data.enrichmentData !== undefined ||
      data.status !== undefined,
    {
      message: 'At least one field must be provided'
    }
  )
```

### `AcqCompanyResponseSchema`

```typescript
export const AcqCompanyResponseSchema = z.object({
  id: z.string(),
  organizationId: z.string(),
  clientId: z.string().nullable().optional(),
  name: z.string(),
  domain: z.string().nullable(),
  linkedinUrl: z.string().nullable(),
  website: z.string().nullable(),
  numEmployees: z.number().nullable(),
  foundedYear: z.number().nullable(),
  locationCity: z.string().nullable(),
  locationState: z.string().nullable(),
  category: z.string().nullable(),
  categoryPain: z.string().nullable(),
  segment: z.string().nullable(),
  processingState: CompanyProcessingStateSchema.nullable(),
  pipelineStatus: z.unknown().nullable().optional(),
  enrichmentData: z.record(z.string(), z.unknown()).nullable(),
  source: z.string().nullable(),
  batchId: z.string().nullable(),
  status: AcqCompanyStatusSchema,
  contactCount: z.number().int().min(0),
  verticalResearch: z.string().nullable(),
  createdAt: z.string(),
  updatedAt: z.string()
})
```

### `AcqCompanyListResponseSchema`

```typescript
export const AcqCompanyListResponseSchema = z.object({
  data: z.array(AcqCompanyResponseSchema),
  total: z.number().int(),
  limit: z.number().int(),
  offset: z.number().int()
})
```

### `AcqCompanyFacetsResponseSchema`

```typescript
export const AcqCompanyFacetsResponseSchema = z.object({
  segments: z.array(z.string()),
  categories: z.array(z.string()),
  statuses: z.array(AcqCompanyStatusSchema)
})
```

### `AcqContactCompanySummarySchema`

```typescript
export const AcqContactCompanySummarySchema = z.object({
  id: z.string(),
  name: z.string(),
  domain: z.string().nullable(),
  website: z.string().nullable(),
  linkedinUrl: z.string().nullable(),
  segment: z.string().nullable(),
  category: z.string().nullable(),
  status: AcqCompanyStatusSchema
})
```

### `AcqContactResponseSchema`

```typescript
export const AcqContactResponseSchema = z.object({
  id: z.string(),
  organizationId: z.string(),
  clientId: z.string().nullable().optional(),
  companyId: z.string().nullable(),
  email: z.string(),
  emailValid: AcqEmailValidSchema.nullable(),
  firstName: z.string().nullable(),
  lastName: z.string().nullable(),
  linkedinUrl: z.string().nullable(),
  title: z.string().nullable(),
  headline: z.string().nullable(),
  filterReason: z.string().nullable(),
  openingLine: z.string().nullable(),
  source: z.string().nullable(),
  sourceId: z.string().nullable(),
  processingState: ContactProcessingStateSchema.nullable(),
  pipelineStatus: z.unknown().nullable().optional(),
  enrichmentData: z.record(z.string(), z.unknown()).nullable(),
  attioPersonId: z.string().nullable(),
  batchId: z.string().nullable(),
  status: AcqContactStatusSchema,
  company: AcqContactCompanySummarySchema.nullable().optional(),
  createdAt: z.string(),
  updatedAt: z.string()
})
```

### `AcqContactListResponseSchema`

```typescript
export const AcqContactListResponseSchema = z.object({
  data: z.array(AcqContactResponseSchema),
  total: z.number().int(),
  limit: z.number().int(),
  offset: z.number().int()
})
```

### `AcqArtifactOwnerKindSchema`

```typescript
export const AcqArtifactOwnerKindSchema = z.enum(['company', 'contact', 'deal', 'list', 'list_member'])
```

### `ListArtifactsQuerySchema`

```typescript
export const ListArtifactsQuerySchema = z
  .object({
    ownerKind: AcqArtifactOwnerKindSchema,
    ownerId: UuidSchema
  })
  .strict()
```

### `CreateArtifactRequestSchema`

```typescript
export const CreateArtifactRequestSchema = z
  .object({
    ownerKind: AcqArtifactOwnerKindSchema,
    ownerId: UuidSchema,
    kind: z.string().trim().min(1).max(255),
    content: z.record(z.string(), z.unknown()),
    sourceExecutionId: UuidSchema.optional()
  })
  .strict()
```

### `AcqArtifactResponseSchema`

```typescript
export const AcqArtifactResponseSchema = z.object({
  id: z.string(),
  organizationId: z.string(),
  ownerKind: z.string(),
  ownerId: z.string(),
  kind: z.string(),
  content: z.record(z.string(), z.unknown()),
  sourceExecutionId: z.string().nullable(),
  createdBy: z.string().nullable(),
  createdAt: z.string(),
  version: z.number().int()
})
```

### `AcqArtifactListResponseSchema`

```typescript
export const AcqArtifactListResponseSchema = z.object({
  artifacts: z.array(AcqArtifactResponseSchema)
})
```

### `ListMembersQuerySchema`

```typescript
export const ListMembersQuerySchema = z
  .object({
    limit: z.coerce.number().int().min(1).max(500).default(50),
    offset: z.coerce.number().int().min(0).default(0)
  })
  .strict()
```

### `MemberIdParamsSchema`

```typescript
export const MemberIdParamsSchema = z.object({
  memberId: UuidSchema
})
```

### `AcqListMemberContactSummarySchema`

```typescript
export const AcqListMemberContactSummarySchema = z.object({
  id: z.string(),
  email: z.string(),
  firstName: z.string().nullable(),
  lastName: z.string().nullable(),
  title: z.string().nullable(),
  linkedinUrl: z.string().nullable(),
  companyId: z.string().nullable()
})
```

### `AcqListMemberResponseSchema`

```typescript
export const AcqListMemberResponseSchema = z.object({
  id: z.string(),
  listId: z.string(),
  contactId: z.string(),
  pipelineKey: z.string(),
  stageKey: z.string(),
  stateKey: z.string(),
  activityLog: z.unknown(),
  addedAt: z.string(),
  addedBy: z.string().nullable(),
  sourceExecutionId: z.string().nullable(),
  contact: AcqListMemberContactSummarySchema.nullable()
})
```

### `AcqListMembersResponseSchema`

```typescript
export const AcqListMembersResponseSchema = z.object({
  members: z.array(AcqListMemberResponseSchema)
})
```

### `ListCompanyIdParamsSchema`

```typescript
export const ListCompanyIdParamsSchema = z.object({
  listCompanyId: UuidSchema
})
```

### `AcqListCompanyResponseSchema`

```typescript
export const AcqListCompanyResponseSchema = z.object({
  id: z.string(),
  listId: z.string(),
  companyId: z.string(),
  pipelineKey: z.string(),
  stageKey: z.string(),
  stateKey: z.string(),
  activityLog: z.unknown(),
  addedAt: z.string(),
  addedBy: z.string().nullable(),
  sourceExecutionId: z.string().nullable()
})
```

### `AcqCompanySchemas`

```typescript
export const AcqCompanySchemas = {
  CompanyProcessingState: CompanyProcessingStateSchema,
  CompanyIdParams: CompanyIdParamsSchema,
  ListCompaniesQuery: ListCompaniesQuerySchema,
  CreateCompanyRequest: CreateCompanyRequestSchema,
  UpdateCompanyRequest: UpdateCompanyRequestSchema,
  AcqCompanyResponse: AcqCompanyResponseSchema,
  AcqCompanyListResponse: AcqCompanyListResponseSchema,
  AcqCompanyFacetsResponse: AcqCompanyFacetsResponseSchema
}
```

### `AcqContactSchemas`

```typescript
export const AcqContactSchemas = {
  ContactProcessingState: ContactProcessingStateSchema,
  ContactIdParams: ContactIdParamsSchema,
  ListContactsQuery: ListContactsQuerySchema,
  CreateContactRequest: CreateContactRequestSchema,
  UpdateContactRequest: UpdateContactRequestSchema,
  AcqContactResponse: AcqContactResponseSchema,
  AcqContactListResponse: AcqContactListResponseSchema
}
```

### `AcqListSchemas`

```typescript
export const AcqListSchemas = {
  // Params
  ListIdParams: ListIdParamsSchema,

  // Primitives (for UI / tests)
  ListStatus: ListStatusSchema,
  ScrapingConfig: ScrapingConfigSchema,
  IcpRubric: IcpRubricSchema,
  PipelineConfig: PipelineConfigSchema,
  DataMode: DataModeSchema,
  PipelineStage: PipelineStageSchema,
  BuildPlanSnapshot: BuildPlanSnapshotSchema,
  BuildPlanSnapshotStep: BuildPlanSnapshotStepSchema,
  AcqListMetadata: AcqListMetadataSchema,
  LeadGenStageKey: LeadGenStageKeySchema,
  LeadGenActionKey: LeadGenActionKeySchema,
  ProcessingStageStatus: ProcessingStageStatusSchema,
  ProcessingState: ProcessingStateSchema,
  ListStageCounts: ListStageCountsSchema,
  ListTelemetry: ListTelemetrySchema,

  // Requests
  ListReadQuery: ListReadQuerySchema,
  GetListQuery: GetListQuerySchema,
  CreateListRequest: CreateListRequestSchema,
  UpdateListRequest: UpdateListRequestSchema,
  UpdateListStatusRequest: UpdateListStatusRequestSchema,
  UpdateListConfigRequest: UpdateListConfigRequestSchema,
  AddCompaniesToListRequest: AddCompaniesToListRequestSchema,
  RemoveCompaniesFromListRequest: RemoveCompaniesFromListRequestSchema,
  AddContactsToListRequest: AddContactsToListRequestSchema,
  RecordListExecutionRequest: RecordListExecutionRequestSchema,

  // Responses
  AcqListResponse: AcqListResponseSchema,
  AcqListDetailResponse: AcqListDetailResponseSchema,
  AcqListListResponse: AcqListListResponseSchema,
  AcqListDealRef: AcqListDealRefSchema,
  AcqListLineage: AcqListLineageSchema,
  AcqListStatusResponse: AcqListStatusResponseSchema,
  ListTelemetryResponse: ListTelemetryResponseSchema,
  ListTelemetryListResponse: ListTelemetryListResponseSchema,
  ListExecutionsResponse: ListExecutionsResponseSchema,
  ListProgressResponse: ListProgressResponseSchema
}
```

### `AcqSubstrateSchemas`

```typescript
export const AcqSubstrateSchemas = {
  // Artifacts
  ListArtifactsQuery: ListArtifactsQuerySchema,
  CreateArtifactRequest: CreateArtifactRequestSchema,
  AcqArtifactResponse: AcqArtifactResponseSchema,
  AcqArtifactListResponse: AcqArtifactListResponseSchema,

  // List members
  ListMembersQuery: ListMembersQuerySchema,
  ListRecordsQuery: ListRecordsQuerySchema,
  MemberIdParams: MemberIdParamsSchema,
  AcqListMemberResponse: AcqListMemberResponseSchema,
  AcqListMembersResponse: AcqListMembersResponseSchema,
  AcqListCompanyRecordRow: AcqListCompanyRecordRowSchema,
  AcqListContactRecordRow: AcqListContactRecordRowSchema,
  ListRecordRow: ListRecordRowSchema,
  ListRecordsResponse: ListRecordsResponseSchema,

  // List companies
  ListCompanyIdParams: ListCompanyIdParamsSchema,
  AcqListCompanyResponse: AcqListCompanyResponseSchema,

  // Transition (generic stateful substrate)
  TransitionItemRequest: TransitionItemRequestSchema
}
```

### `Stateful`

```typescript
/**
 * Stateful trait — the (pipeline_key, stage_key, state_key, activity_log) quartet
 * applied to acq_deals (CRM HITL, shipped 2026-04-27) and being generalized to
 * acq_lists / acq_list_members / acq_list_companies via Track B.
 */
export interface Stateful {
  pipeline_key: string
  stage_key: string
  state_key: string
  activity_log: ActivityEvent[]
}
```

### `TransitionItem`

```typescript
/** Generic transition shape — concrete per-entity transitionItem implementations satisfy this. */
export type TransitionItem<T extends Stateful, TEvent extends ActivityEvent> = (
  item: T,
  transition: { stage_key?: string; state_key?: string; event: TEvent }
) => T
```

### `DeriveActions`

```typescript
/** Generic action-derivation shape — concrete per-entity deriveActions implementations satisfy this. */
export type DeriveActions<T extends Stateful, TAction> = (item: T) => TAction[]
```

### `StatefulSchema`

```typescript
export const StatefulSchema = z.object({
  pipeline_key: z.string(),
  stage_key: z.string(),
  state_key: z.string(),
  activity_log: z.array(ActivityEventSchema)
})
```

### `StatefulStateDefinition`

```typescript
/** One state within a stage: minimal shape of key + display label. */
export interface StatefulStateDefinition {
  /** Matches state_key values written by workflow steps. */
  stateKey: string
  label: string
}
```

### `StatefulStageDefinition`

```typescript
/** One stage within a pipeline: has a stage_key and ordered valid states. */
export interface StatefulStageDefinition {
  /** Matches stage_key values written by workflow steps. */
  stageKey: string
  label: string
  /** UI color token. Consumers may map this to their design system. */
  color?: string
  states: StatefulStateDefinition[]
}
```

### `StatefulPipelineDefinition`

```typescript
/**
 * Pipeline definition for a single entity participating in the Stateful trait.
 * Parallel to acq_deals' pipeline_key concept but structured for any entity.
 */
export interface StatefulPipelineDefinition {
  /** Matches pipeline_key values in the database. */
  pipelineKey: string
  label: string
  /** Entity this pipeline applies to. */
  entityKey: string
  stages: StatefulStageDefinition[]
}
```

### `PaginationParams`

```typescript
export interface PaginationParams {
  limit: number
  offset: number
}
```

### `PaginatedResult`

```typescript
export interface PaginatedResult<T> {
  data: T[]
  total: number
  limit: number
  offset: number
}
```

### `CreateListParams`

```typescript
export interface CreateListParams {
  organizationId: string
  name: string
  description?: string
  type?: string
  batchIds?: string[]
  instantlyCampaignId?: string
  status?: ListStatus
  buildTemplateId?: string
  metadata?: Record<string, unknown>
  scrapingConfig?: ScrapingConfig
  icp?: IcpRubric
  pipelineConfig?: PipelineConfig
}
```

### `UpdateListParams`

```typescript
export interface UpdateListParams {
  name?: string
  description?: string
  batchIds?: string[]
}
```

### `CreateCompanyParams`

```typescript
export interface CreateCompanyParams {
  organizationId: string
  name: string
  domain?: string
  linkedinUrl?: string
  website?: string
  numEmployees?: number
  foundedYear?: number
  locationCity?: string
  locationState?: string
  category?: string
  source?: string
  batchId?: string
  verticalResearch?: string
  /** @deprecated Use processingState. Accepted as a no-op compatibility bridge for external tenants. */
  pipelineStatus?: unknown
}
```

### `UpdateCompanyParams`

```typescript
export interface UpdateCompanyParams {
  name?: string
  domain?: string
  linkedinUrl?: string
  website?: string
  numEmployees?: number
  foundedYear?: number
  locationCity?: string
  locationState?: string
  category?: string
  segment?: string
  processingState?: ProcessingState
  /** @deprecated Use processingState. Accepted as a no-op compatibility bridge for external tenants. */
  pipelineStatus?: unknown
  enrichmentData?: Record<string, unknown>
  source?: string
  batchId?: string
  status?: 'active' | 'invalid'
  verticalResearch?: string | null
  /** Track A: flat qualification score column (null until a scoring rubric is defined) */
  qualificationScore?: number | null
  /** Track A: flat qualification signals jsonb */
  qualificationSignals?: Record<string, unknown> | null
  /** Track A: key identifying the rubric used for qualification */
  qualificationRubricKey?: string | null
}
```

### `UpsertCompanyParams`

```typescript
export type UpsertCompanyParams = CreateCompanyParams
```

### `CompanyFilters`

```typescript
export interface CompanyFilters {
  listId?: string // Filter to companies in a specific list (via acq_list_companies)
  search?: string
  domain?: string
  website?: string
  segment?: string
  category?: string
  processingState?: ProcessingState
  /** @deprecated Use processingState. Accepted as a no-op compatibility bridge for external tenants. */
  pipelineStatus?: unknown
  /** Exclude companies whose processing state contains this value (PostgREST NOT contains) */
  processingStateNot?: ProcessingState
  batchId?: string
  status?: 'active' | 'invalid'
  includeAll?: boolean
  excludeColumns?: Array<'enrichmentData' | 'processingState'>
  limit?: number
}
```

### `CreateContactParams`

```typescript
export interface CreateContactParams {
  organizationId: string
  email: string
  companyId?: string
  firstName?: string
  lastName?: string
  linkedinUrl?: string
  title?: string
  source?: string
  sourceId?: string
  batchId?: string
  /** @deprecated Use processingState. Accepted as a no-op compatibility bridge for external tenants. */
  pipelineStatus?: unknown
}
```

### `UpdateContactParams`

```typescript
export interface UpdateContactParams {
  companyId?: string
  emailValid?: 'VALID' | 'INVALID' | 'RISKY' | 'UNKNOWN'
  firstName?: string
  lastName?: string
  linkedinUrl?: string
  title?: string
  headline?: string
  filterReason?: string
  openingLine?: string
  processingState?: ProcessingState
  /** @deprecated Use processingState. Accepted as a no-op compatibility bridge for external tenants. */
  pipelineStatus?: unknown
  enrichmentData?: Record<string, unknown>
  status?: 'active' | 'invalid'
}
```

### `UpsertContactParams`

```typescript
export type UpsertContactParams = CreateContactParams
```

### `ContactFilters`

```typescript
export interface ContactFilters {
  listId?: string // Filter to contacts in a specific list (via acq_list_members)
  search?: string
  openingLineIsNull?: boolean // Filter to contacts without personalization
  processingState?: ProcessingState
  /** @deprecated Use processingState. Accepted as a no-op compatibility bridge for external tenants. */
  pipelineStatus?: unknown
  batchId?: string
  contactStatus?: 'active' | 'invalid' // Filter by contact status (soft-delete flag)
}
```

### `UpsertSocialPostParams`

```typescript
export interface UpsertSocialPostParams {
  organizationId: string
  platform: string
  platformPostId: string
  authorName: string
  authorUrl?: string | null
  postTitle: string
  postText: string
  postUrl: string
  engagementCount?: number
  commentsCount?: number
  postedAt: string
  metadata?: Record<string, unknown>
  relevanceScore?: number
  matchedKeywords?: string[]
  matchedQuery?: string | null
  initialDraft?: string | null
  finalResponse?: string | null
  sourceCategory?: string | null
}
```

### `UpsertSocialPostsParams`

```typescript
export interface UpsertSocialPostsParams {
  organizationId: string
  posts: Omit<UpsertSocialPostParams, 'organizationId'>[]
}
```

### `UpsertSocialPostsResult`

```typescript
export interface UpsertSocialPostsResult {
  inserted: number
  duplicatesSkipped: number
}
```

### `AddContactsToListParams`

```typescript
export interface AddContactsToListParams {
  organizationId: string
  listId: string
  contactIds: string[]
}
```

### `AddContactsToListResult`

```typescript
export interface AddContactsToListResult {
  added: number
  alreadyExisted: number
}
```

### `UpdateListConfigParams`

```typescript
export interface UpdateListConfigParams {
  organizationId: string
  listId: string
  scrapingConfig?: ScrapingConfig
  icp?: IcpRubric
  pipelineConfig?: PipelineConfig
}
```

### `UpdateCompanyStageParams`

```typescript
export interface UpdateCompanyStageParams {
  organizationId: string
  listId: string
  companyId: string
  stage: string
  status?: ProcessingStageStatus
  data?: unknown
  executionId?: string
}
```

### `UpdateContactStageParams`

```typescript
export interface UpdateContactStageParams {
  organizationId: string
  listId: string
  contactId: string
  stage: string
  status?: ProcessingStageStatus
  data?: unknown
  executionId?: string
}
```

### `AddCompaniesToListParams`

```typescript
export interface AddCompaniesToListParams {
  organizationId: string
  listId: string
  companyIds: string[]
}
```

### `AddCompaniesToListResult`

```typescript
export interface AddCompaniesToListResult {
  added: number
  alreadyExisted: number
}
```

### `RemoveCompaniesFromListParams`

```typescript
export interface RemoveCompaniesFromListParams {
  organizationId: string
  listId: string
  companyIds: string[]
}
```

### `RemoveCompaniesFromListResult`

```typescript
export interface RemoveCompaniesFromListResult {
  removed: number
}
```

### `RecordListExecutionParams`

```typescript
export interface RecordListExecutionParams {
  organizationId: string
  listId: string
  executionId: string
  configSnapshot?: Record<string, unknown>
}
```

### `ListExecutionSummary`

```typescript
export interface ListExecutionSummary {
  executionId: string
  resourceId: string
  status: string
  createdAt: string
  completedAt: string | null
  durationMs: number | null
  input?: unknown
}
```

### `BulkImportParams`

```typescript
export interface BulkImportParams {
  organizationId: string
  contacts: CreateContactParams[]
  listId?: string
}
```

### `BulkImportResult`

```typescript
export interface BulkImportResult {
  created: number
  updated: number
  errors: Array<{ email: string; error: string }>
}
```

### `BulkImportCompanyEntry`

```typescript
export interface BulkImportCompanyEntry {
  name: string
  domain: string
  website?: string
  locationCity?: string
  locationState?: string
  category?: string
  source?: string
  enrichmentData?: Record<string, unknown>
  processingState?: ProcessingState
}
```

### `BulkImportCompaniesParams`

```typescript
export interface BulkImportCompaniesParams {
  organizationId: string
  batchId: string
  companies: BulkImportCompanyEntry[]
}
```

### `BulkImportCompaniesResult`

```typescript
export interface BulkImportCompaniesResult {
  created: number
  skipped: number
  errors: Array<{ companyName: string; error: string }>
}
```

### `LeadToolMap`

```typescript
export type LeadToolMap = {
  // List operations
  listLists: { params: Record<string, never>; result: AcqList[] }
  createList: { params: Omit<CreateListParams, 'organizationId'>; result: AcqList }
  updateList: { params: { id: string } & UpdateListParams; result: AcqList }
  deleteList: { params: { id: string }; result: void }
  addContactsToList: { params: Omit<AddContactsToListParams, 'organizationId'>; result: AddContactsToListResult }
  addCompaniesToList: { params: Omit<AddCompaniesToListParams, 'organizationId'>; result: AddCompaniesToListResult }
  updateCompanyStage: {
    params: Omit<UpdateCompanyStageParams, 'organizationId'>
    result: void
  }
  updateContactStage: {
    params: Omit<UpdateContactStageParams, 'organizationId'>
    result: void
  }
  clearCompanyStages: {
    params: Omit<ClearCompanyStagesParams, 'organizationId'>
    result: void
  }
  clearContactStages: {
    params: Omit<ClearContactStagesParams, 'organizationId'>
    result: void
  }
  // Company operations
  createCompany: { params: Omit<CreateCompanyParams, 'organizationId'>; result: AcqCompany }
  upsertCompany: { params: Omit<UpsertCompanyParams, 'organizationId'>; result: AcqCompany }
  updateCompany: { params: { id: string } & UpdateCompanyParams; result: AcqCompany }
  getCompany: { params: { id: string }; result: AcqCompany | null }
  listCompanies: { params: CompanyFilters; result: AcqCompany[] }
  deleteCompany: { params: { id: string }; result: void }
  // Contact operations
  createContact: { params: Omit<CreateContactParams, 'organizationId'>; result: AcqContact }
  upsertContact: { params: Omit<UpsertContactParams, 'organizationId'>; result: AcqContact }
  updateContact: { params: { id: string } & UpdateContactParams; result: AcqContact }
  getContact: { params: { id: string }; result: AcqContact | null }
  getContactByEmail: { params: { email: string }; result: AcqContact | null }
  listContacts: {
    params: ContactFilters & { limit?: number; offset?: number }
    result: PaginatedResult<AcqContact>
  }
  deleteContact: { params: { id: string }; result: void }
  bulkImportContacts: { params: Omit<BulkImportParams, 'organizationId'>; result: BulkImportResult }
  bulkImportCompanies: {
    params: Omit<BulkImportCompaniesParams, 'organizationId'>
    result: BulkImportCompaniesResult
  }
  deactivateContactsByCompany: {
    params: { companyId: string }
    result: { deactivated: number }
  }
  // Deal operations
  upsertDeal: { params: Omit<UpsertDealParams, 'organizationId'>; result: AcqDeal }
  getDealByEmail: { params: { email: string }; result: AcqDeal | null }
  getDealByEnvelopeId: { params: { envelopeId: string }; result: AcqDeal | null }
  updateDealEnvelopeId: { params: { dealId: string; envelopeId: string }; result: AcqDeal | null }
  getDealById: { params: Omit<GetDealByIdParams, 'organizationId'>; result: AcqDeal | null }
  getContactById: { params: Omit<GetContactByIdParams, 'organizationId'>; result: AcqContact | null }
  getCompanyById: { params: Omit<GetCompanyByIdParams, 'organizationId'>; result: AcqCompany | null }
  // Deal-sync operations
  updateDiscoveryData: { params: Omit<UpdateDiscoveryDataParams, 'organizationId'>; result: void }
  updateProposalData: { params: Omit<UpdateProposalDataParams, 'organizationId'>; result: void }
  markProposalSent: { params: Omit<MarkProposalSentParams, 'organizationId'>; result: void }
  markProposalReviewed: { params: Omit<MarkProposalReviewedParams, 'organizationId'>; result: void }
  updateCloseLostReason: { params: Omit<UpdateCloseLostReasonParams, 'organizationId'>; result: void }
  updateFees: { params: Omit<UpdateFeesParams, 'organizationId'>; result: void }
  cacheInstantlyThreadIds: { params: Omit<CacheInstantlyThreadIdsParams, 'organizationId'>; result: void }
  transitionItem: { params: Omit<TransitionItemParams, 'organizationId'>; result: void }
  setContactNurture: { params: Omit<SetContactNurtureParams, 'organizationId'>; result: void }
  cancelSchedulesAndHitlByEmail: {
    params: Omit<CancelSchedulesAndHitlByEmailParams, 'organizationId'>
    result: { schedulesCancelled: number; hitlDeleted: number }
  }
  cancelHitlByDealId: { params: Omit<CancelHitlByDealIdParams, 'organizationId'>; result: { hitlDeleted: number } }
  clearDealFields: { params: Omit<ClearDealFieldsParams, 'organizationId'>; result: void }
  deleteDeal: { params: Omit<DeleteDealParams, 'organizationId'>; result: void }
  recordDealActivity: {
    params: Omit<RecordDealActivityParams, 'organizationId'>
    result: void
  }
  // Deal note operations
  createDealNote: {
    params: Omit<CreateDealNoteParams, 'organizationId'>
    result: AcqDealNote
  }
  listDealNotes: {
    params: Omit<ListDealNotesParams, 'organizationId'>
    result: AcqDealNote[]
  }
  // Deal task operations
  createDealTask: {
    params: Omit<CreateDealTaskParams, 'organizationId'>
    result: AcqDealTask
  }
  listDealTasks: {
    params: Omit<ListDealTasksParams, 'organizationId'>
    result: AcqDealTask[]
  }
  listDealTasksDue: {
    params: Omit<ListDealTasksDueParams, 'organizationId'>
    result: AcqDealTask[]
  }
  completeDealTask: {
    params: Omit<CompleteDealTaskParams, 'organizationId'>
    result: AcqDealTask
  }
  // Deal query & analytics operations
  listDeals: { params: DealFilters; result: AcqDeal[] }
  getDealPipelineAnalytics: { params: { recentLimit?: number }; result: DealPipelineAnalytics }
  // Enrichment data operations
  mergeEnrichmentData: {
    params: { id: string; table: 'acq_companies' | 'acq_contacts'; data: Record<string, unknown> }
    result: void
  }
  // Social monitoring operations
  upsertSocialPosts: {
    params: { posts: Omit<UpsertSocialPostParams, 'organizationId'>[] }
    result: UpsertSocialPostsResult
  }
  setDealStateKey: {
    params: {
      dealId: string
      stateKey: string
    }
    result: { ok: true }
  }
  // CRM workflow helpers
  transitionDeal: {
    params: {
      dealId: string
      toStage: string
      toState?: string
    }
    result: { deal: AcqDeal }
  }
  loadDeal: {
    params: { dealId: string }
    result: DealDetail | null
  }
}
```

### `ListToolMap`

```typescript
export type ListToolMap = {
  getConfig: {
    params: { listId: string }
    result: {
      scrapingConfig: ScrapingConfig
      icp: IcpRubric
      pipelineConfig: PipelineConfig & { dataMode: 'mock' | 'live' }
    }
  }
  recordExecution: {
    params: Omit<RecordListExecutionParams, 'organizationId'>
    result: void
  }
  updateCompanyStage: {
    params: Omit<UpdateCompanyStageParams, 'organizationId'>
    result: void
  }
  updateContactStage: {
    params: Omit<UpdateContactStageParams, 'organizationId'>
    result: void
  }
  clearCompanyStages: {
    params: Omit<ClearCompanyStagesParams, 'organizationId'>
    result: void
  }
  clearContactStages: {
    params: Omit<ClearContactStagesParams, 'organizationId'>
    result: void
  }
  listPendingCompanyIds: {
    params: Omit<ListPendingCompanyIdsParams, 'organizationId'>
    result: string[]
  }
  listPendingContactIds: {
    params: Omit<ListPendingContactIdsParams, 'organizationId'>
    result: string[]
  }
}
```

## Knowledge Platform Primitives

### `KnowledgeLinkSchema`

```typescript
export const KnowledgeLinkSchema = z
  .union([CanonicalKnowledgeLinkSchema, LegacyKnowledgeLinkSchema])
  .transform((link) => {
    const target = 'target' in link ? link.target : targetFromNodeId(link.nodeId)
    return {
      target,
      nodeId: nodeIdFromTarget(target)
    }
  })
```

### `OrgKnowledgeKindSchema`

```typescript
export const OrgKnowledgeKindSchema = z
  .enum(['playbook', 'strategy', 'reference'])
  .meta({ label: 'Knowledge kind', color: 'grape' })
```

### `OrgKnowledgeNodeSchema`

```typescript
export const OrgKnowledgeNodeSchema = z.object({
  id: ModelIdSchema,
  kind: OrgKnowledgeKindSchema,
  title: z.string().trim().min(1).max(200),
  summary: z.string().trim().min(1).max(1000),
  icon: IconNameSchema.optional(),
  /** Canonical documentation URL when body content is a local summary. */
  externalUrl: z.string().trim().url().max(500).optional(),
  /** Optional generated source file path for local MDX-backed knowledge nodes. */
  sourceFilePath: z.string().trim().min(1).max(500).optional(),
  /** Raw MDX string. Phase 2 will introduce a structured block format. */
  body: z.string().trim().min(1),
  /**
   * Graph links to other OM nodes this knowledge node governs.
   * Each link emits a `governs` edge: knowledge-node -> target node.
   */
  links: z.array(KnowledgeLinkSchema).default([]),
  /** Role identifiers that own this knowledge node. */
  ownerIds: z.array(RoleIdSchema.meta({ ref: 'role' })).default([]),
  /** ISO date string (YYYY-MM-DD or full ISO 8601) of last meaningful update. */
  updatedAt: z.string().trim().min(1).max(50)
})
```

### `KnowledgeDomainSchema`

```typescript
export const KnowledgeDomainSchema = z.record(ModelIdSchema, OrgKnowledgeNodeSchema).default({})
```

### `OrgKnowledgeNode`

```typescript
export type OrgKnowledgeNode = z.infer<typeof OrgKnowledgeNodeSchema>
```

### `OrgKnowledgeKind`

```typescript
export type OrgKnowledgeKind = z.infer<typeof OrgKnowledgeKindSchema>
```

### `KnowledgeLink`

```typescript
export type KnowledgeLink = z.infer<typeof KnowledgeLinkSchema>
```

### `KnowledgeDomain`

```typescript
export type KnowledgeDomain = z.infer<typeof KnowledgeDomainSchema>
```
