@elevasis/core 0.14.0 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/index.d.ts +60 -0
  2. package/dist/index.js +198 -1
  3. package/dist/organization-model/index.d.ts +60 -0
  4. package/dist/organization-model/index.js +198 -1
  5. package/dist/test-utils/index.d.ts +399 -363
  6. package/dist/test-utils/index.js +198 -1
  7. package/package.json +3 -3
  8. package/src/_gen/__tests__/__snapshots__/contracts.md.snap +444 -309
  9. package/src/business/acquisition/activity-events.ts +12 -3
  10. package/src/business/acquisition/api-schemas.test.ts +315 -4
  11. package/src/business/acquisition/api-schemas.ts +140 -17
  12. package/src/business/acquisition/build-templates.ts +44 -0
  13. package/src/business/acquisition/crm-next-action.test.ts +262 -0
  14. package/src/business/acquisition/crm-next-action.ts +220 -0
  15. package/src/business/acquisition/crm-priority.test.ts +216 -0
  16. package/src/business/acquisition/crm-priority.ts +349 -0
  17. package/src/business/acquisition/crm-state-actions.test.ts +12 -21
  18. package/src/business/acquisition/deal-ownership.test.ts +351 -0
  19. package/src/business/acquisition/deal-ownership.ts +120 -0
  20. package/src/business/acquisition/derive-actions.test.ts +101 -37
  21. package/src/business/acquisition/derive-actions.ts +49 -24
  22. package/src/business/acquisition/index.ts +163 -149
  23. package/src/business/acquisition/types.ts +48 -4
  24. package/src/execution/engine/index.ts +4 -3
  25. package/src/execution/engine/tools/lead-service-types.ts +68 -51
  26. package/src/execution/engine/tools/platform/acquisition/list-tools.ts +6 -5
  27. package/src/execution/engine/tools/platform/acquisition/types.ts +3 -1
  28. package/src/execution/engine/tools/registry.ts +4 -3
  29. package/src/execution/engine/tools/tool-maps.ts +821 -816
  30. package/src/organization-model/domains/prospecting.ts +204 -1
  31. package/src/organization-model/domains/sales.test.ts +218 -0
  32. package/src/organization-model/domains/sales.ts +558 -366
  33. package/src/organization-model/types.ts +2 -2
  34. package/src/platform/constants/versions.ts +1 -1
  35. package/src/reference/_generated/contracts.md +444 -309
  36. package/src/supabase/database.types.ts +2978 -2958
@@ -1,366 +1,558 @@
1
- import { z } from 'zod'
2
- import { DescriptionSchema, DisplayMetadataSchema, ModelIdSchema, ReferenceIdsSchema } from './shared'
3
-
4
- export const SalesStageSemanticClassSchema = z.enum(['open', 'active', 'nurturing', 'closed_won', 'closed_lost'])
5
-
6
- export const SalesStageSchema = DisplayMetadataSchema.extend({
7
- id: ModelIdSchema,
8
- order: z.number().int().min(0),
9
- semanticClass: SalesStageSemanticClassSchema,
10
- surfaceIds: ReferenceIdsSchema,
11
- resourceIds: ReferenceIdsSchema
12
- })
13
-
14
- export const SalesPipelineSchema = z.object({
15
- id: ModelIdSchema,
16
- label: z.string().trim().min(1).max(120),
17
- description: DescriptionSchema.optional(),
18
- entityId: ModelIdSchema,
19
- stages: z.array(SalesStageSchema).min(1)
20
- })
21
-
22
- export const OrganizationModelSalesSchema = z.object({
23
- entityId: ModelIdSchema,
24
- defaultPipelineId: ModelIdSchema,
25
- pipelines: z.array(SalesPipelineSchema).min(1)
26
- })
27
-
28
- export const DEFAULT_ORGANIZATION_MODEL_SALES: z.infer<typeof OrganizationModelSalesSchema> = {
29
- entityId: 'crm.deal',
30
- defaultPipelineId: 'default',
31
- pipelines: [
32
- {
33
- id: 'default',
34
- label: 'Default Pipeline',
35
- entityId: 'crm.deal',
36
- stages: [
37
- {
38
- id: 'interested',
39
- label: 'Interested',
40
- color: 'blue',
41
- order: 1,
42
- semanticClass: 'open',
43
- surfaceIds: ['crm.pipeline'],
44
- resourceIds: []
45
- },
46
- {
47
- id: 'proposal',
48
- label: 'Proposal',
49
- color: 'yellow',
50
- order: 2,
51
- semanticClass: 'active',
52
- surfaceIds: ['crm.pipeline'],
53
- resourceIds: []
54
- },
55
- {
56
- id: 'closing',
57
- label: 'Closing',
58
- color: 'lime',
59
- order: 3,
60
- semanticClass: 'active',
61
- surfaceIds: ['crm.pipeline'],
62
- resourceIds: []
63
- },
64
- {
65
- id: 'closed_won',
66
- label: 'Closed Won',
67
- color: 'green',
68
- order: 4,
69
- semanticClass: 'closed_won',
70
- surfaceIds: ['crm.pipeline'],
71
- resourceIds: []
72
- },
73
- {
74
- id: 'closed_lost',
75
- label: 'Closed Lost',
76
- color: 'red',
77
- order: 5,
78
- semanticClass: 'closed_lost',
79
- surfaceIds: ['crm.pipeline'],
80
- resourceIds: []
81
- },
82
- {
83
- id: 'nurturing',
84
- label: 'Nurturing',
85
- color: 'grape',
86
- order: 6,
87
- semanticClass: 'nurturing',
88
- surfaceIds: ['crm.pipeline'],
89
- resourceIds: []
90
- }
91
- ]
92
- }
93
- ]
94
- }
95
-
96
- // ============================================================================
97
- // Lead-Gen Stateful Pipeline Definitions (Decision N8, Wave 4)
98
- //
99
- // Defines the (pipeline_key, stage_key, state_key) vocabulary for the three
100
- // entities that carry the Stateful trait via Track B:
101
- // - acq_lists (pipeline_key='lead-gen', stage_key='lifecycle')
102
- // - acq_list_members (pipeline_key='lead-gen', stages: outreach / prospecting / qualification)
103
- // - acq_list_companies (pipeline_key='lead-gen', stages: outreach / prospecting / qualification)
104
- //
105
- // DB columns (pipeline_key, stage_key, state_key) remain free-form text with no
106
- // CHECK constraint — new states can be introduced without a migration (Decision N8).
107
- // These definitions are the org-specific source of truth consumed by UI and tooling.
108
- //
109
- // State vocabularies sourced from the post-restructure sales tree (W3 canonical):
110
- // outreach/:
111
- // - personalized (instantly-personalization.ts → contacts)
112
- // - uploaded (instantly-upload.ts → contacts)
113
- // - interested (instantly-reply-handler.ts → contacts, initial reply transition)
114
- // prospecting/:
115
- // - populated (apify-acquire.ts, apify-scrape.ts → companies)
116
- // - extracted (website-extract.ts → companies)
117
- // - discovered (email-discovery.ts, anymailfinder-enrich.ts → contacts)
118
- // - verified (email-verification.ts → contacts)
119
- // qualification/:
120
- // - qualified (company-qualification.ts → companies)
121
- //
122
- // The 'pending' state is the W2 backfill default (coalesce(stage, 'pending')).
123
- // It is valid in any stage and represents "not yet processed by a workflow step".
124
- // ============================================================================
125
-
126
- /** One state within a stage — minimal shape: key + display label. */
127
- export interface StatefulStateDefinition {
128
- /** Matches state_key values written by workflow steps. */
129
- stateKey: string
130
- label: string
131
- }
132
-
133
- /** One stage within a pipeline — has a stage_key and an ordered list of valid states. */
134
- export interface StatefulStageDefinition {
135
- /** Matches stage_key values written by workflow steps. */
136
- stageKey: string
137
- label: string
138
- states: StatefulStateDefinition[]
139
- }
140
-
141
- /**
142
- * Pipeline definition for a single entity participating in the Stateful trait.
143
- * Parallel to acq_deals' pipeline_key concept but structured for lead-gen entities.
144
- */
145
- export interface StatefulPipelineDefinition {
146
- /** Matches pipeline_key values in the database (e.g. 'lead-gen'). */
147
- pipelineKey: string
148
- label: string
149
- /** Entity this pipeline applies to (e.g. 'acq.list', 'acq.list-member', 'acq.list-company'). */
150
- entityKey: string
151
- stages: StatefulStageDefinition[]
152
- }
153
-
154
- /**
155
- * Find a pipeline definition by pipeline_key within an array of definitions.
156
- * Preferred over direct array indexing since the model is array-based (not keyed).
157
- */
158
- export function findPipeline(
159
- definitions: StatefulPipelineDefinition[],
160
- pipelineKey: string
161
- ): StatefulPipelineDefinition | undefined {
162
- return definitions.find((def) => def.pipelineKey === pipelineKey)
163
- }
164
-
165
- /** Common states that appear across multiple stages. */
166
- const PENDING_STATE: StatefulStateDefinition = { stateKey: 'pending', label: 'Pending' }
167
-
168
- /**
169
- * Lead-gen pipeline definition for acq_list_members (contacts).
170
- * Three stages matching the post-restructure sales subdomain tree.
171
- *
172
- * Note: members visit outreach and prospecting states depending on which
173
- * workflow last processed them. stage_key is set per-transition by the workflow.
174
- */
175
- export const ACQ_LIST_MEMBERS_LEAD_GEN_PIPELINE: StatefulPipelineDefinition = {
176
- pipelineKey: 'lead-gen',
177
- label: 'Lead Generation',
178
- entityKey: 'acq.list-member',
179
- stages: [
180
- {
181
- stageKey: 'outreach',
182
- label: 'Outreach',
183
- states: [
184
- PENDING_STATE,
185
- { stateKey: 'personalized', label: 'Personalized' },
186
- { stateKey: 'uploaded', label: 'Uploaded' },
187
- { stateKey: 'interested', label: 'Interested' }
188
- ]
189
- },
190
- {
191
- stageKey: 'prospecting',
192
- label: 'Prospecting',
193
- states: [
194
- PENDING_STATE,
195
- { stateKey: 'discovered', label: 'Discovered' },
196
- { stateKey: 'verified', label: 'Verified' }
197
- ]
198
- },
199
- {
200
- stageKey: 'qualification',
201
- label: 'Qualification',
202
- states: [PENDING_STATE]
203
- }
204
- ]
205
- }
206
-
207
- /**
208
- * Lead-gen pipeline definition for acq_list_companies.
209
- * Three stages matching the post-restructure sales subdomain tree.
210
- *
211
- * Note: companies visit prospecting and qualification states depending on which
212
- * workflow last processed them. stage_key is set per-transition by the workflow.
213
- */
214
- export const ACQ_LIST_COMPANIES_LEAD_GEN_PIPELINE: StatefulPipelineDefinition = {
215
- pipelineKey: 'lead-gen',
216
- label: 'Lead Generation',
217
- entityKey: 'acq.list-company',
218
- stages: [
219
- {
220
- stageKey: 'outreach',
221
- label: 'Outreach',
222
- states: [PENDING_STATE]
223
- },
224
- {
225
- stageKey: 'prospecting',
226
- label: 'Prospecting',
227
- states: [
228
- PENDING_STATE,
229
- { stateKey: 'populated', label: 'Populated' },
230
- { stateKey: 'extracted', label: 'Extracted' }
231
- ]
232
- },
233
- {
234
- stageKey: 'qualification',
235
- label: 'Qualification',
236
- states: [PENDING_STATE, { stateKey: 'qualified', label: 'Qualified' }]
237
- }
238
- ]
239
- }
240
-
241
- /**
242
- * All lead-gen pipeline definitions indexed by entity key.
243
- * Use findPipeline() to locate a definition by pipeline_key within any of these arrays.
244
- */
245
- export const LEAD_GEN_PIPELINE_DEFINITIONS: Record<string, StatefulPipelineDefinition[]> = {
246
- 'acq.list-member': [ACQ_LIST_MEMBERS_LEAD_GEN_PIPELINE],
247
- 'acq.list-company': [ACQ_LIST_COMPANIES_LEAD_GEN_PIPELINE]
248
- }
249
-
250
- // ============================================================================
251
- // Lead-Gen Stage Catalog (Slice C — flag-based processing model)
252
- //
253
- // Canonical set of processing stage keys for the flag-based model that replaces
254
- // the stateful trait on acq_list_members and acq_list_companies. Each key maps
255
- // to a flag in the processing_state jsonb column (bare boolean per Decision #7).
256
- //
257
- // Sources:
258
- // ACQ_LIST_MEMBERS_LEAD_GEN_PIPELINE → personalized, uploaded, interested,
259
- // discovered, verified
260
- // ACQ_LIST_COMPANIES_LEAD_GEN_PIPELINE → populated, extracted, qualified
261
- // Design plan hint (lead-gen-domain-cleanup.mdx §4) → scraped, enriched
262
- //
263
- // Wave 2 will validate pipeline_config.stages[].key against this catalog at
264
- // list-create/update time. Each lead-gen workflow in operations will declare
265
- // stageImplemented: '<key>' in its WorkflowDefinition (Slice D-2).
266
- // ============================================================================
267
-
268
- /** One entry in the lead-gen stage catalog. */
269
- export interface LeadGenStageCatalogEntry {
270
- /** Matches the flag key written into processing_state jsonb (e.g. 'scraped'). */
271
- key: string
272
- /** Human-readable label for UI display. */
273
- label: string
274
- /** Short description of what this stage represents. */
275
- description: string
276
- /** Canonical pipeline order for UI sorting. Lower = earlier in the funnel. */
277
- order: number
278
- /** Which entity's processing_state jsonb carries this flag. */
279
- entity: 'company' | 'contact'
280
- }
281
-
282
- /**
283
- * Canonical lead-gen processing stage catalog.
284
- * Keys are the flag names written by workflow steps into processing_state jsonb.
285
- *
286
- * Ordered roughly by pipeline progression (prospecting → outreach → qualification).
287
- */
288
- export const LEAD_GEN_STAGE_CATALOG: Record<string, LeadGenStageCatalogEntry> = {
289
- // Prospecting — company population
290
- scraped: {
291
- key: 'scraped',
292
- label: 'Scraped',
293
- description: 'Company was scraped from a source directory (Apify actor run).',
294
- order: 1,
295
- entity: 'company'
296
- },
297
- populated: {
298
- key: 'populated',
299
- label: 'Populated',
300
- description: 'Company record populated with structured data from scrape results.',
301
- order: 2,
302
- entity: 'company'
303
- },
304
- extracted: {
305
- key: 'extracted',
306
- label: 'Extracted',
307
- description: 'Website content extracted and parsed for company intelligence.',
308
- order: 3,
309
- entity: 'company'
310
- },
311
- enriched: {
312
- key: 'enriched',
313
- label: 'Enriched',
314
- description: 'Company or contact enriched with third-party data (e.g. Tomba, Anymailfinder).',
315
- order: 4,
316
- entity: 'company'
317
- },
318
-
319
- // Prospecting — contact discovery
320
- discovered: {
321
- key: 'discovered',
322
- label: 'Discovered',
323
- description: 'Contact email address discovered via an email-discovery workflow.',
324
- order: 5,
325
- entity: 'contact'
326
- },
327
- verified: {
328
- key: 'verified',
329
- label: 'Verified',
330
- description: 'Contact email address verified as deliverable (email verification workflow).',
331
- order: 6,
332
- entity: 'contact'
333
- },
334
-
335
- // Qualification
336
- qualified: {
337
- key: 'qualified',
338
- label: 'Qualified',
339
- description: 'Company passed the ICP qualification rubric (company-qualification workflow).',
340
- order: 7,
341
- entity: 'company'
342
- },
343
-
344
- // Outreach
345
- personalized: {
346
- key: 'personalized',
347
- label: 'Personalized',
348
- description: 'Outreach message personalized for the contact (Instantly personalization workflow).',
349
- order: 8,
350
- entity: 'contact'
351
- },
352
- uploaded: {
353
- key: 'uploaded',
354
- label: 'Uploaded',
355
- description: 'Contact uploaded to an Instantly campaign for outreach.',
356
- order: 9,
357
- entity: 'contact'
358
- },
359
- interested: {
360
- key: 'interested',
361
- label: 'Interested',
362
- description: 'Contact replied with a positive signal (Instantly reply-handler transition).',
363
- order: 10,
364
- entity: 'contact'
365
- }
366
- }
1
+ import { z } from 'zod'
2
+ import { DescriptionSchema, DisplayMetadataSchema, ModelIdSchema, ReferenceIdsSchema } from './shared'
3
+
4
+ export const SalesStageSemanticClassSchema = z.enum(['open', 'active', 'nurturing', 'closed_won', 'closed_lost'])
5
+
6
+ export const SalesStageSchema = DisplayMetadataSchema.extend({
7
+ id: ModelIdSchema,
8
+ order: z.number().int().min(0),
9
+ semanticClass: SalesStageSemanticClassSchema,
10
+ surfaceIds: ReferenceIdsSchema,
11
+ resourceIds: ReferenceIdsSchema
12
+ })
13
+
14
+ export const SalesPipelineSchema = z.object({
15
+ id: ModelIdSchema,
16
+ label: z.string().trim().min(1).max(120),
17
+ description: DescriptionSchema.optional(),
18
+ entityId: ModelIdSchema,
19
+ stages: z.array(SalesStageSchema).min(1)
20
+ })
21
+
22
+ export const OrganizationModelSalesSchema = z.object({
23
+ entityId: ModelIdSchema,
24
+ defaultPipelineId: ModelIdSchema,
25
+ pipelines: z.array(SalesPipelineSchema).min(1)
26
+ })
27
+
28
+ export const DEFAULT_ORGANIZATION_MODEL_SALES: z.infer<typeof OrganizationModelSalesSchema> = {
29
+ entityId: 'crm.deal',
30
+ defaultPipelineId: 'default',
31
+ pipelines: [
32
+ {
33
+ id: 'default',
34
+ label: 'Default Pipeline',
35
+ entityId: 'crm.deal',
36
+ stages: [
37
+ {
38
+ id: 'interested',
39
+ label: 'Interested',
40
+ color: 'blue',
41
+ order: 1,
42
+ semanticClass: 'open',
43
+ surfaceIds: ['crm.pipeline'],
44
+ resourceIds: []
45
+ },
46
+ {
47
+ id: 'proposal',
48
+ label: 'Proposal',
49
+ color: 'yellow',
50
+ order: 2,
51
+ semanticClass: 'active',
52
+ surfaceIds: ['crm.pipeline'],
53
+ resourceIds: []
54
+ },
55
+ {
56
+ id: 'closing',
57
+ label: 'Closing',
58
+ color: 'lime',
59
+ order: 3,
60
+ semanticClass: 'active',
61
+ surfaceIds: ['crm.pipeline'],
62
+ resourceIds: []
63
+ },
64
+ {
65
+ id: 'closed_won',
66
+ label: 'Closed Won',
67
+ color: 'green',
68
+ order: 4,
69
+ semanticClass: 'closed_won',
70
+ surfaceIds: ['crm.pipeline'],
71
+ resourceIds: []
72
+ },
73
+ {
74
+ id: 'closed_lost',
75
+ label: 'Closed Lost',
76
+ color: 'red',
77
+ order: 5,
78
+ semanticClass: 'closed_lost',
79
+ surfaceIds: ['crm.pipeline'],
80
+ resourceIds: []
81
+ },
82
+ {
83
+ id: 'nurturing',
84
+ label: 'Nurturing',
85
+ color: 'grape',
86
+ order: 6,
87
+ semanticClass: 'nurturing',
88
+ surfaceIds: ['crm.pipeline'],
89
+ resourceIds: []
90
+ }
91
+ ]
92
+ }
93
+ ]
94
+ }
95
+
96
+ // ============================================================================
97
+ // Lead-Gen Stateful Pipeline Definitions (Decision N8, Wave 4)
98
+ //
99
+ // Defines the (pipeline_key, stage_key, state_key) vocabulary for the three
100
+ // entities that carry the Stateful trait via Track B:
101
+ // - acq_lists (pipeline_key='lead-gen', stage_key='lifecycle')
102
+ // - acq_list_members (pipeline_key='lead-gen', stages: outreach / prospecting / qualification)
103
+ // - acq_list_companies (pipeline_key='lead-gen', stages: outreach / prospecting / qualification)
104
+ //
105
+ // DB columns (pipeline_key, stage_key, state_key) remain free-form text with no
106
+ // CHECK constraint — new states can be introduced without a migration (Decision N8).
107
+ // These definitions are the org-specific source of truth consumed by UI and tooling.
108
+ //
109
+ // State vocabularies sourced from the post-restructure sales tree (W3 canonical):
110
+ // outreach/:
111
+ // - personalized (instantly-personalization.ts → contacts)
112
+ // - uploaded (instantly-upload.ts → contacts)
113
+ // - interested (instantly-reply-handler.ts → contacts, initial reply transition)
114
+ // prospecting/:
115
+ // - populated (apify-acquire.ts, apify-scrape.ts → companies)
116
+ // - extracted (website-extract.ts → companies)
117
+ // - discovered (email-discovery.ts, anymailfinder-enrich.ts → contacts)
118
+ // - verified (email-verification.ts → contacts)
119
+ // qualification/:
120
+ // - qualified (company-qualification.ts → companies)
121
+ //
122
+ // The 'pending' state is the W2 backfill default (coalesce(stage, 'pending')).
123
+ // It is valid in any stage and represents "not yet processed by a workflow step".
124
+ // ============================================================================
125
+
126
+ /** One state within a stage — minimal shape: key + display label. */
127
+ export interface StatefulStateDefinition {
128
+ /** Matches state_key values written by workflow steps. */
129
+ stateKey: string
130
+ label: string
131
+ }
132
+
133
+ /** One stage within a pipeline — has a stage_key and an ordered list of valid states. */
134
+ export interface StatefulStageDefinition {
135
+ /** Matches stage_key values written by workflow steps. */
136
+ stageKey: string
137
+ label: string
138
+ states: StatefulStateDefinition[]
139
+ }
140
+
141
+ /**
142
+ * Pipeline definition for a single entity participating in the Stateful trait.
143
+ * Parallel to acq_deals' pipeline_key concept but structured for lead-gen entities.
144
+ */
145
+ export interface StatefulPipelineDefinition {
146
+ /** Matches pipeline_key values in the database (e.g. 'lead-gen'). */
147
+ pipelineKey: string
148
+ label: string
149
+ /** Entity this pipeline applies to (e.g. 'acq.list', 'acq.list-member', 'acq.list-company'). */
150
+ entityKey: string
151
+ stages: StatefulStageDefinition[]
152
+ }
153
+
154
+ export type CrmPriorityBucketKey = 'needs_response' | 'follow_up_due' | 'waiting' | 'stale' | 'closed_low'
155
+
156
+ export interface CrmPriorityBucketDefinition {
157
+ bucketKey: CrmPriorityBucketKey
158
+ label: string
159
+ /** Lower ranks sort first in deal lists and pipeline columns. */
160
+ rank: number
161
+ /** UI color token. Consumers may map this to their design system. */
162
+ color: string
163
+ }
164
+
165
+ export interface CrmPriorityRuleConfig {
166
+ buckets: CrmPriorityBucketDefinition[]
167
+ closedStageKeys: string[]
168
+ followUpAfterDaysByStateKey: Record<string, number>
169
+ staleAfterDays: number
170
+ }
171
+
172
+ /**
173
+ * Find a pipeline definition by pipeline_key within an array of definitions.
174
+ * Preferred over direct array indexing since the model is array-based (not keyed).
175
+ */
176
+ export function findPipeline(
177
+ definitions: StatefulPipelineDefinition[],
178
+ pipelineKey: string
179
+ ): StatefulPipelineDefinition | undefined {
180
+ return definitions.find((def) => def.pipelineKey === pipelineKey)
181
+ }
182
+
183
+ /**
184
+ * Returns the valid states for a given stage within a pipeline definition.
185
+ * Returns an empty array if the stage is not found.
186
+ */
187
+ export function getValidStatesForStage(
188
+ definition: StatefulPipelineDefinition,
189
+ stageKey: string
190
+ ): StatefulStateDefinition[] {
191
+ return definition.stages.find((s) => s.stageKey === stageKey)?.states ?? []
192
+ }
193
+
194
+ // ============================================================================
195
+ // CRM Stateful Pipeline Definition
196
+ //
197
+ // Defines the (pipeline_key, stage_key, state_key) vocabulary for crm.deal
198
+ // entities. Stage keys match DEFAULT_ORGANIZATION_MODEL_SALES.pipelines[0].stages.
199
+ //
200
+ // State vocabularies sourced from the CRM action/handler tree:
201
+ // interested/:
202
+ // - discovery_replied (instantly-reply-handler.ts → first/subsequent reply)
203
+ // - discovery_link_sent (crm-send-booking-link.ts, crm-rebook.ts → booking link sent)
204
+ // - discovery_nudging (crm-send-nudge.ts → nudge sent after link)
205
+ // - discovery_booking_cancelled (booking-revert.ts → Cal cancellation webhook)
206
+ // - reply_sent (crm-send-reply.ts → operator reply sent)
207
+ // - followup_1_sent (crm-reply-followup.ts day=3)
208
+ // - followup_2_sent (crm-reply-followup.ts day=5)
209
+ // - followup_3_sent (crm-reply-followup.ts day=7)
210
+ // proposal, closing, closed_won, closed_lost, nurturing: no observed sub-states
211
+ // ============================================================================
212
+
213
+ export const CRM_DISCOVERY_REPLIED_STATE: StatefulStateDefinition = {
214
+ stateKey: 'discovery_replied',
215
+ label: 'Discovery Replied'
216
+ }
217
+ export const CRM_DISCOVERY_LINK_SENT_STATE: StatefulStateDefinition = {
218
+ stateKey: 'discovery_link_sent',
219
+ label: 'Discovery Link Sent'
220
+ }
221
+ export const CRM_DISCOVERY_NUDGING_STATE: StatefulStateDefinition = {
222
+ stateKey: 'discovery_nudging',
223
+ label: 'Discovery Nudging'
224
+ }
225
+ export const CRM_DISCOVERY_BOOKING_CANCELLED_STATE: StatefulStateDefinition = {
226
+ stateKey: 'discovery_booking_cancelled',
227
+ label: 'Discovery Booking Cancelled'
228
+ }
229
+ export const CRM_REPLY_SENT_STATE: StatefulStateDefinition = {
230
+ stateKey: 'reply_sent',
231
+ label: 'Reply Sent'
232
+ }
233
+ export const CRM_FOLLOWUP_1_SENT_STATE: StatefulStateDefinition = {
234
+ stateKey: 'followup_1_sent',
235
+ label: 'Follow-up 1 Sent'
236
+ }
237
+ export const CRM_FOLLOWUP_2_SENT_STATE: StatefulStateDefinition = {
238
+ stateKey: 'followup_2_sent',
239
+ label: 'Follow-up 2 Sent'
240
+ }
241
+ export const CRM_FOLLOWUP_3_SENT_STATE: StatefulStateDefinition = {
242
+ stateKey: 'followup_3_sent',
243
+ label: 'Follow-up 3 Sent'
244
+ }
245
+
246
+ export const CRM_PIPELINE_DEFINITION: StatefulPipelineDefinition = {
247
+ pipelineKey: 'crm',
248
+ label: 'CRM',
249
+ entityKey: 'crm.deal',
250
+ stages: [
251
+ {
252
+ stageKey: 'interested',
253
+ label: 'Interested',
254
+ states: [
255
+ CRM_DISCOVERY_REPLIED_STATE,
256
+ CRM_DISCOVERY_LINK_SENT_STATE,
257
+ CRM_DISCOVERY_NUDGING_STATE,
258
+ CRM_DISCOVERY_BOOKING_CANCELLED_STATE,
259
+ CRM_REPLY_SENT_STATE,
260
+ CRM_FOLLOWUP_1_SENT_STATE,
261
+ CRM_FOLLOWUP_2_SENT_STATE,
262
+ CRM_FOLLOWUP_3_SENT_STATE
263
+ ]
264
+ },
265
+ { stageKey: 'proposal', label: 'Proposal', states: [] },
266
+ { stageKey: 'closing', label: 'Closing', states: [] },
267
+ { stageKey: 'closed_won', label: 'Closed Won', states: [] },
268
+ { stageKey: 'closed_lost', label: 'Closed Lost', states: [] },
269
+ { stageKey: 'nurturing', label: 'Nurturing', states: [] }
270
+ ]
271
+ }
272
+
273
+ export const CRM_PRIORITY_BUCKETS: CrmPriorityBucketDefinition[] = [
274
+ { bucketKey: 'needs_response', label: 'Needs Response', rank: 10, color: 'red' },
275
+ { bucketKey: 'follow_up_due', label: 'Follow-up Due', rank: 20, color: 'orange' },
276
+ { bucketKey: 'waiting', label: 'Waiting', rank: 30, color: 'blue' },
277
+ { bucketKey: 'stale', label: 'Stale', rank: 40, color: 'gray' },
278
+ { bucketKey: 'closed_low', label: 'Closed', rank: 50, color: 'dark' }
279
+ ]
280
+
281
+ export const DEFAULT_CRM_PRIORITY_RULE_CONFIG: CrmPriorityRuleConfig = {
282
+ buckets: CRM_PRIORITY_BUCKETS,
283
+ closedStageKeys: ['closed_won', 'closed_lost'],
284
+ followUpAfterDaysByStateKey: {
285
+ discovery_link_sent: 3,
286
+ discovery_nudging: 2,
287
+ reply_sent: 3,
288
+ followup_1_sent: 3,
289
+ followup_2_sent: 5,
290
+ followup_3_sent: 7
291
+ },
292
+ staleAfterDays: 14
293
+ }
294
+
295
+ // ============================================================================
296
+ // CRM Next-Action Rule Config
297
+ //
298
+ // Maps (state_key, ownership) → suggested action key from DEFAULT_CRM_ACTIONS.
299
+ // Per-org overrides live at organizations.config.crm.next_actions; merged at
300
+ // evaluator read time (same pattern as priority). The evaluator returns the
301
+ // action's `key` string, or null for closed deals / unrecognised combinations.
302
+ // ============================================================================
303
+
304
+ export interface CrmNextActionMapping {
305
+ /** state_key to match, or '*' for any state. */
306
+ stateKey: string
307
+ /** ownership value to match ('us' | 'them'), or '*' for any. */
308
+ ownership: 'us' | 'them' | '*'
309
+ /** Action key from DEFAULT_CRM_ACTIONS (or a custom org-defined key). */
310
+ actionKey: string
311
+ /**
312
+ * When true, this mapping only fires if age >= staleAfterDays.
313
+ * Defaults to false.
314
+ */
315
+ requiresStale?: boolean
316
+ }
317
+
318
+ export interface CrmNextActionRuleConfig {
319
+ mappings: CrmNextActionMapping[]
320
+ /** Fallback action key when ownership === 'us' and no explicit mapping matches. */
321
+ ownershipUsFallback: string
322
+ }
323
+
324
+ /**
325
+ * Default next-action rule config. Evaluated in order — first match wins.
326
+ *
327
+ * Mapping table (state_key, ownership) → action_key:
328
+ * (discovery_link_sent, 'them') → 'send_nudge' (after staleAfterDays)
329
+ * (discovery_replied, 'us') 'send_reply'
330
+ * (discovery_nudging, 'them') → 'send_nudge'
331
+ * (*, 'us') ownershipUsFallback ('send_reply')
332
+ *
333
+ * Closed deals → null (handled before mapping evaluation).
334
+ */
335
+ export const DEFAULT_CRM_NEXT_ACTION_RULE_CONFIG: CrmNextActionRuleConfig = {
336
+ mappings: [
337
+ {
338
+ stateKey: 'discovery_link_sent',
339
+ ownership: 'them',
340
+ actionKey: 'send_nudge',
341
+ requiresStale: true
342
+ },
343
+ {
344
+ stateKey: 'discovery_replied',
345
+ ownership: 'us',
346
+ actionKey: 'send_reply'
347
+ },
348
+ {
349
+ stateKey: 'discovery_nudging',
350
+ ownership: 'them',
351
+ actionKey: 'send_nudge'
352
+ }
353
+ ],
354
+ ownershipUsFallback: 'send_reply'
355
+ }
356
+
357
+ /** Common states that appear across multiple stages. */
358
+ const PENDING_STATE: StatefulStateDefinition = { stateKey: 'pending', label: 'Pending' }
359
+
360
+ /**
361
+ * Lead-gen pipeline definition for acq_list_members (contacts).
362
+ * Three stages matching the post-restructure sales subdomain tree.
363
+ *
364
+ * Note: members visit outreach and prospecting states depending on which
365
+ * workflow last processed them. stage_key is set per-transition by the workflow.
366
+ */
367
+ export const ACQ_LIST_MEMBERS_LEAD_GEN_PIPELINE: StatefulPipelineDefinition = {
368
+ pipelineKey: 'lead-gen',
369
+ label: 'Lead Generation',
370
+ entityKey: 'acq.list-member',
371
+ stages: [
372
+ {
373
+ stageKey: 'outreach',
374
+ label: 'Outreach',
375
+ states: [
376
+ PENDING_STATE,
377
+ { stateKey: 'personalized', label: 'Personalized' },
378
+ { stateKey: 'uploaded', label: 'Uploaded' },
379
+ { stateKey: 'interested', label: 'Interested' }
380
+ ]
381
+ },
382
+ {
383
+ stageKey: 'prospecting',
384
+ label: 'Prospecting',
385
+ states: [
386
+ PENDING_STATE,
387
+ { stateKey: 'discovered', label: 'Discovered' },
388
+ { stateKey: 'verified', label: 'Verified' }
389
+ ]
390
+ },
391
+ {
392
+ stageKey: 'qualification',
393
+ label: 'Qualification',
394
+ states: [PENDING_STATE]
395
+ }
396
+ ]
397
+ }
398
+
399
+ /**
400
+ * Lead-gen pipeline definition for acq_list_companies.
401
+ * Three stages matching the post-restructure sales subdomain tree.
402
+ *
403
+ * Note: companies visit prospecting and qualification states depending on which
404
+ * workflow last processed them. stage_key is set per-transition by the workflow.
405
+ */
406
+ export const ACQ_LIST_COMPANIES_LEAD_GEN_PIPELINE: StatefulPipelineDefinition = {
407
+ pipelineKey: 'lead-gen',
408
+ label: 'Lead Generation',
409
+ entityKey: 'acq.list-company',
410
+ stages: [
411
+ {
412
+ stageKey: 'outreach',
413
+ label: 'Outreach',
414
+ states: [PENDING_STATE]
415
+ },
416
+ {
417
+ stageKey: 'prospecting',
418
+ label: 'Prospecting',
419
+ states: [
420
+ PENDING_STATE,
421
+ { stateKey: 'populated', label: 'Populated' },
422
+ { stateKey: 'extracted', label: 'Extracted' }
423
+ ]
424
+ },
425
+ {
426
+ stageKey: 'qualification',
427
+ label: 'Qualification',
428
+ states: [PENDING_STATE, { stateKey: 'qualified', label: 'Qualified' }]
429
+ }
430
+ ]
431
+ }
432
+
433
+ /**
434
+ * All lead-gen pipeline definitions indexed by entity key.
435
+ * Use findPipeline() to locate a definition by pipeline_key within any of these arrays.
436
+ */
437
+ export const LEAD_GEN_PIPELINE_DEFINITIONS: Record<string, StatefulPipelineDefinition[]> = {
438
+ 'acq.list-member': [ACQ_LIST_MEMBERS_LEAD_GEN_PIPELINE],
439
+ 'acq.list-company': [ACQ_LIST_COMPANIES_LEAD_GEN_PIPELINE]
440
+ }
441
+
442
+ // ============================================================================
443
+ // Lead-Gen Stage Catalog (status-based processing model)
444
+ //
445
+ // Canonical set of processing stage keys for the status-map model that replaces
446
+ // the stateful trait on acq_list_members and acq_list_companies. Each key maps
447
+ // to a terminal status string in the processing_state jsonb column.
448
+ //
449
+ // Sources:
450
+ // ACQ_LIST_MEMBERS_LEAD_GEN_PIPELINE → personalized, uploaded, interested,
451
+ // discovered, verified
452
+ // ACQ_LIST_COMPANIES_LEAD_GEN_PIPELINE → populated, extracted, qualified
453
+ // Design plan hint (lead-gen-domain-cleanup.mdx §4) → scraped, enriched
454
+ //
455
+ // Wave 2 will validate pipeline_config.stages[].key against this catalog at
456
+ // list-create/update time. Each lead-gen workflow in operations will declare
457
+ // stageImplemented: '<key>' in its WorkflowDefinition (Slice D-2).
458
+ // ============================================================================
459
+
460
+ /** One entry in the lead-gen stage catalog. */
461
+ export interface LeadGenStageCatalogEntry {
462
+ /** Matches the status key written into processing_state jsonb (e.g. 'scraped'). */
463
+ key: string
464
+ /** Human-readable label for UI display. */
465
+ label: string
466
+ /** Short description of what this stage represents. */
467
+ description: string
468
+ /** Canonical pipeline order for UI sorting. Lower = earlier in the funnel. */
469
+ order: number
470
+ /** Which entity's processing_state jsonb carries this stage status. */
471
+ entity: 'company' | 'contact'
472
+ }
473
+
474
+ /**
475
+ * Canonical lead-gen processing stage catalog.
476
+ * Keys are the stage names written by workflow steps into processing_state jsonb.
477
+ *
478
+ * Ordered roughly by pipeline progression (prospecting → outreach → qualification).
479
+ */
480
+ export const LEAD_GEN_STAGE_CATALOG: Record<string, LeadGenStageCatalogEntry> = {
481
+ // Prospecting — company population
482
+ scraped: {
483
+ key: 'scraped',
484
+ label: 'Scraped',
485
+ description: 'Company was scraped from a source directory (Apify actor run).',
486
+ order: 1,
487
+ entity: 'company'
488
+ },
489
+ populated: {
490
+ key: 'populated',
491
+ label: 'Populated',
492
+ description: 'Company record populated with structured data from scrape results.',
493
+ order: 2,
494
+ entity: 'company'
495
+ },
496
+ extracted: {
497
+ key: 'extracted',
498
+ label: 'Extracted',
499
+ description: 'Website content extracted and parsed for company intelligence.',
500
+ order: 3,
501
+ entity: 'company'
502
+ },
503
+ enriched: {
504
+ key: 'enriched',
505
+ label: 'Enriched',
506
+ description: 'Company or contact enriched with third-party data (e.g. Tomba, Anymailfinder).',
507
+ order: 4,
508
+ entity: 'company'
509
+ },
510
+
511
+ // Prospecting — contact discovery
512
+ discovered: {
513
+ key: 'discovered',
514
+ label: 'Discovered',
515
+ description: 'Contact email address discovered via an email-discovery workflow.',
516
+ order: 5,
517
+ entity: 'contact'
518
+ },
519
+ verified: {
520
+ key: 'verified',
521
+ label: 'Verified',
522
+ description: 'Contact email address verified as deliverable (email verification workflow).',
523
+ order: 6,
524
+ entity: 'contact'
525
+ },
526
+
527
+ // Qualification
528
+ qualified: {
529
+ key: 'qualified',
530
+ label: 'Qualified',
531
+ description: 'Company passed the ICP qualification rubric (company-qualification workflow).',
532
+ order: 7,
533
+ entity: 'company'
534
+ },
535
+
536
+ // Outreach
537
+ personalized: {
538
+ key: 'personalized',
539
+ label: 'Personalized',
540
+ description: 'Outreach message personalized for the contact (Instantly personalization workflow).',
541
+ order: 8,
542
+ entity: 'contact'
543
+ },
544
+ uploaded: {
545
+ key: 'uploaded',
546
+ label: 'Uploaded',
547
+ description: 'Contact uploaded to an Instantly campaign for outreach.',
548
+ order: 9,
549
+ entity: 'contact'
550
+ },
551
+ interested: {
552
+ key: 'interested',
553
+ label: 'Interested',
554
+ description: 'Contact replied with a positive signal (Instantly reply-handler transition).',
555
+ order: 10,
556
+ entity: 'contact'
557
+ }
558
+ }