@classytic/crm 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,335 +1,363 @@
1
- # Changelog
2
-
3
- All notable changes to `@classytic/crm` are documented here.
4
-
5
- ## [0.7.0] — 2026-07-05
6
-
7
- ### Added — org-wide email suppression list
8
-
9
- - **`Suppression` entity** (`crm.repositories.suppression`, model
10
- `Suppression`): global per-org "never email this address again" list —
11
- the gate hosts consult before EVERY outbound email. Unsubscribes on
12
- `Subscription` stay per-campaign; suppression is org-wide.
13
- - `suppress(email, { reason, source?, subjectKind?, subjectId?, metadata? }, ctx?)`
14
- — idempotent `getOrCreate` on the unique `(organizationId, email)`
15
- index (no check-then-save); emits `crm:suppression.added` only when
16
- THIS call inserted the row.
17
- - `isSuppressed(email, ctx?)` → boolean.
18
- - `filterSuppressed(emails, ctx?)` → `Set<string>` of the suppressed
19
- subset — ONE `$in` query for the campaign-fanout hot path.
20
- - `unsuppress(email, ctx?)` — atomic delete; emits
21
- `crm:suppression.removed` only when a row was actually removed.
22
- - All verbs normalize emails (trim + lowercase; schema stores lowercase).
23
- - **`SUPPRESSION_REASONS`** (`'bounce' | 'complaint' | 'unsubscribe' |
24
- 'manual'`) — the first three `satisfies readonly EmailEventKind[]` (P6),
25
- so a rename in `EMAIL_EVENT_KINDS` fails compilation here.
26
- - **Events** `crm:suppression.added` / `crm:suppression.removed` — Zod
27
- catalog definitions included (no-drift invariant stays green);
28
- `organizationId` rides event meta as usual.
29
- - **Validators** `suppressSchema` / `unsuppressSchema` /
30
- `suppressionFilterSchema`.
31
-
32
- ### Added — reply-detection exit verb
33
-
34
- - **`EnrollmentRepository.exitActiveOnReply(subjects, ctx?)`** — the ONE
35
- method a host's `crm:message.received` subscriber calls: finds ACTIVE
36
- enrollments for the given `{ subjectKind, subjectId }` list, batch-loads
37
- their sequences in a single `$in` query, skips those with
38
- `replyDetectionEnabled === false`, and exits the rest via `exit(id,
39
- 'reply')` (each exit emits `crm:enrollment.exited`). Lost CAS races
40
- (concurrent pause/complete/exit) are skipped, not failed. Returns the
41
- enrollments this call exited.
42
- - `EnrollmentRepositoryDeps` now carries `sequences: SequenceRepository`
43
- (same cross-repo deps idiom as `OpportunityRepository.pipelines` /
44
- `MessageRepository.conversations`) — wired automatically by
45
- `createCrm()`; only hosts constructing `EnrollmentRepository` by hand
46
- need to pass it.
47
-
48
- ## [0.6.0] — 2026-07-02
49
-
50
- Breaking-in-behavior release (ships as MINOR per house convention):
51
- outbox-first, session-safe event dispatch — the previously deferred
52
- PACKAGE_RULES §P8/§P8.1 work.
53
-
54
- ### Added — unit-of-work contract (P8.1, shared with refit/review/cart/invoice)
55
-
56
- - **`engine.withTransaction(ctx, body)`** — runs `body` inside a MongoDB
57
- transaction with post-commit event discipline: events dispatched through
58
- `txCtx` are queued under `ctx[PENDING_EVENTS]` and flushed to the
59
- transport only AFTER commit; the queue resets on retry attempts; an abort
60
- leaks nothing to in-process subscribers. Reuses the caller's session (and
61
- queue) when `ctx.session` is already set. Standalone-Mongo dev boots opt
62
- in via the existing `allowNonTransactional: true`.
63
- - **`PENDING_EVENTS`** (`Symbol.for('@classytic/crm:pendingEvents')`) +
64
- **`flushPending(transport, queue, logger?)`** + **`runUnit`** exported
65
- from the root for hosts composing their own outer transaction.
66
- - **`CrmConfig.outbox?: OutboxStore`** (from `@classytic/primitives/outbox`)
67
- — when wired, every domain event is persisted via
68
- `outbox.save(event, { session })` in the SAME session as the business
69
- write; the host's relay publishes committed rows. Outbox save failures
70
- PROPAGATE (P8: a swallowed save means the write persists while its event
71
- vanishes).
72
- - **`CrmEventDispatcher`** — EventTransport-compatible wrapper repositories
73
- route every event through (`engine.events` is now this wrapper; the host
74
- `publish`/`subscribe` surface is unchanged).
75
- - **`UnmanagedSessionError`** (`code: 'UNMANAGED_SESSION'`) — a host-owned
76
- `ctx.session` arriving with neither an outbox nor a `PENDING_EVENTS`
77
- queue now throws instead of ghost-publishing mid-transaction.
78
- **Behavioral break:** callers that previously threaded a bare session and
79
- tolerated ghost events must switch to `engine.withTransaction` (or wire
80
- an outbox / attach a queue).
81
-
82
- ### Added — timezone-aware forecasting
83
-
84
- - **`ForecastOptions.timeZone`** — IANA zone for the default month bucket
85
- (e.g. `'Asia/Dhaka'`). Without it, months cut at UTC boundaries: a deal
86
- expected to close July 1, 02:00 Dhaka time (June 30, 20:00 UTC) files
87
- under JUNE. Uses `civilDateOf` from `@classytic/primitives/timezone`.
88
- Peer floor bumped: `@classytic/primitives >=0.9.0`.
89
-
90
- ### Fixed — sequence/enrollment (completes the 0.6.0 WIP)
91
-
92
- - **Event catalog no-drift restored**: 10 missing Zod definitions added
93
- (`crm:sequence.{created,active,paused,archived}`,
94
- `crm:enrollment.{created,step_sent,paused,resumed,completed,exited}`) —
95
- `crm:sequence.created` and `crm:enrollment.step_sent` are host-emitted
96
- (create via `def.create()`), the rest publish in-repo.
97
- - **`EnrollmentRepository.setWorkflowRunId` / `advanceStep` no longer
98
- bypass the repository**: both used raw `model.findOneAndUpdate` with a
99
- manual tenant filter — escaping `multiTenantPlugin` scoping AND
100
- `ctx.session` (a call inside `withTransaction` would commit outside the
101
- transaction). `advanceStep` is now a `claim()` CAS on `currentStepIndex`
102
- with `where: { status: 'active' }`; `setWorkflowRunId` goes through
103
- `repo.update`.
104
-
105
- ### Tests
106
-
107
- - 14 new: `tests/unit/dispatch.test.ts` (6 — outbox propagation/session
108
- routing/guard/swallow), `tests/integration/unit-of-work.test.ts` (3 —
109
- convert() on a replica set: zero mid-tx events, post-commit flush, abort
110
- leaks nothing, bare-session guard), `tests/unit/forecast-timezone.test.ts`
111
- (5 — the +06:00 month-boundary trap). 110/110 total.
112
-
113
- ## [0.5.1] — 2026-06-14
114
-
115
- ### Fixed — declaration bundle
116
-
117
- - **fix: declaration bundle exported mangled aliases; consumer named imports
118
- now resolve.** The published `dist/index.d.ts` re-exported every public
119
- symbol under a minified alias (`export { AccountRepository as A, CRM_EVENTS
120
- as Rr, … }`), so downstream `import { AccountRepository, CRM_EVENTS } from
121
- '@classytic/crm'` failed with TS2305 / TS2460. Root cause: the `./events`
122
- entry re-exports a strict subset of the `index` barrel, which made
123
- `rolldown-plugin-dts` alias every name on the superset (`index`) entry when
124
- both were emitted in a single pass. Build now runs `index` and `events` as
125
- two independent tsdown passes (array config) so each `.d.ts` exports real
126
- names. `tsdown` bumped `^0.14.2` → `^0.21.10` to match sibling packages.
127
- No runtime/API change.
128
-
129
- ## [0.5.0] — 2026-06-14
130
-
131
- Stack upgrade + verified correctness fixes + PACKAGE_RULES compliance. No
132
- new features. Clean break — no deprecation aliases.
133
-
134
- ### Changed — stack currency
135
-
136
- - Peers bumped: `@classytic/mongokit` `>=3.16.0`, `@classytic/repo-core`
137
- `>=0.6.0`, `@classytic/primitives` `>=0.7.1`, `mongoose` `>=9.4.1`.
138
- Clean-installed from npm and verified resolved (3.16.0 / 0.6.0 / 0.7.2).
139
-
140
- ### Added — PACKAGE_RULES compliance
141
-
142
- - **Zod event catalog (rule 18).** New `crmEventDefinitions[]` (56 events,
143
- one Zod schema each) exported from the package root and a new `./events`
144
- subpath. Timestamps are `z.iso.datetime()`. A no-drift invariant test
145
- asserts every `CRM_EVENTS` constant has a definition. Hosts wire these
146
- into arc's `EventRegistry` for publish-time validation + OpenAPI.
147
- - **Model-collision policy (rule 21).** `createCrm()` now throws
148
- `CrmModelCollisionError` when a model name is already registered; pass
149
- `forceRecreate: true` (test/hot-reload) to delete + re-register.
150
- - **Index management (rule 35).** New `autoIndex` config flag (default
151
- `true`) and `engine.syncIndexes()` for `autoIndex: false` production
152
- boots.
153
- - **Capability boot gate.** `createCrm()` asserts the backend supports
154
- `upsert` / `getOrCreate` / `duplicateKeyError` (and `transactions`,
155
- unless `allowNonTransactional: true`) so misconfigured deployments fail
156
- loud at boot instead of mid-convert.
157
-
158
- ### Fixed — domain correctness
159
-
160
- - **Lead / Subscription / Campaign dedup are now race-safe.** Added
161
- authoritative partial-unique indexes — lead `(organizationId, email)`,
162
- campaign `(organizationId, name)`, subscription `(organizationId,
163
- contactId, campaignId)` scoped to live statuses — and catch the
164
- residual `E11000` via `isDuplicateKeyError`, re-throwing the same typed
165
- domain error the pre-check emits. The prior check-then-save left a
166
- TOCTOU window.
167
- - **Owner reassignment is now atomic.** `assign()` on lead / account /
168
- contact / opportunity / conversation uses a single `findOneAndUpdate`
169
- CAS (`{ ownerId: { $ne } }` guard, `returnDocument: 'before'`) — no
170
- read-modify-write lost-update window, and the emitted `previousOwnerId`
171
- is the true pre-image under concurrency.
172
- - **Cross-tenant leak in dashboard/feed reads closed.** `findRecentForFeed`,
173
- `countCreatedSince`, `countOpen`, `sumWonSince`, `countOverduePlanned`
174
- dropped raw `Model.find` / `countDocuments` with a manual
175
- `if (ctx) organizationId` filter (which read ALL tenants when ctx was
176
- absent) for the tenant-scoped `findAll` / `count` repository methods.
177
-
178
- ### Build hygiene
179
-
180
- - Sourcemaps and declaration maps are no longer emitted (`sourceMap` /
181
- `declarationMap` off in tsconfig; `sourcemap: false` in tsdown) — both
182
- leak source.
183
- - Removed `@deprecated` markers from `ConvertResult` convenience id fields
184
- (kept the fields; they were never deprecated, just mislabelled).
185
- - Dropped the stale pnpm lockfile/workspace and the bundled `.tgz`;
186
- installs are npm-from-registry only.
187
-
188
- ### Docs
189
-
190
- - Rewrote the README to the engine-factory API (`createCrm` + repository
191
- domain verbs). The previous README documented the abandoned v0.1
192
- port/adapter design (`AccountService`, `InMemory*Repository`,
193
- `OutreachPort`) that no longer exists.
194
-
195
- ### Tests
196
-
197
- - Added `tests/integration/invariants.test.ts` (tenant probe, lead +
198
- subscription dedup races, atomic reassignment) and
199
- `tests/unit/event-catalog.test.ts` (no-drift + round-trip). 87 → 96
200
- tests.
201
-
202
- ## [0.4.0] — 2026-05-22
203
-
204
- ### Changed — Subscription model renamed to `EmailSubscription`
205
-
206
- **Breaking at the Mongo identity level.** The CRM's email opt-in resource
207
- now registers as Mongoose model `EmailSubscription` (was `Subscription`)
208
- and persists into the `email_subscriptions` collection (was
209
- `subscriptions`).
210
-
211
- **Why:** the previous name collided with `@classytic/revenue`'s
212
- `Subscription` model when both packages were loaded on the same
213
- Mongoose connection — `RevenueModelCollisionError` at boot. Renaming
214
- gives the two concepts distinct identities at the DB level and lets
215
- revenue + CRM coexist without the host having to split connections.
216
-
217
- **TypeScript surface is unchanged.** `ISubscriptionDocument`,
218
- `SubscriptionRepository`, `subscription.handlers.ts`,
219
- `CrmModels.Subscription`, etc. all keep their existing names — only
220
- the Mongoose model name string and the underlying collection name
221
- changed. Consumers that import from `@classytic/crm` need no source
222
- changes; the host only needs to migrate existing data (see below).
223
-
224
- ### Migration
225
-
226
- For DBs with existing CRM subscription rows in the legacy `subscriptions`
227
- collection (distinguishable from revenue rows by `contactId` presence):
228
-
229
- ```js
230
- // MongoDB shell — one-time migration
231
- db.subscriptions.aggregate([
232
- { $match: { contactId: { $exists: true } } },
233
- { $out: 'email_subscriptions' },
234
- ]);
235
- // Then remove the migrated docs from the legacy collection:
236
- db.subscriptions.deleteMany({ contactId: { $exists: true } });
237
- ```
238
-
239
- Hosts using only CRM (no revenue) can also run this — leftover rows in
240
- `subscriptions` won't cause boot errors because there's no collision
241
- without revenue.
242
-
243
- ## [0.3.0] — 2026-05-17
244
-
245
- ### Added — `EmailEvent` domain
246
-
247
- Closes the loop between outbound CRM sends and recipient engagement.
248
- Hosts can now record opens, clicks, bounces, complaints, and unsubscribes
249
- against a Contact / Subscription / Campaign tuple — and downstream
250
- services (drip-sequence "if opened" branches, lead scoring, suppression
251
- lists) consume the same events without polling the email transport.
252
-
253
- - **Entity & enum** — `EmailEvent` (append-only) plus the
254
- `EmailEventKind` enum (`open` / `click` / `bounce` / `complaint` /
255
- `unsubscribe`) split into `ENGAGEMENT_KINDS` and `SUPPRESSION_KINDS`
256
- helper sets for classification at call sites.
257
- - **Port** — `EmailEventRepository` with filtered list, per-subject
258
- timeline, per-campaign aggregates (`uniqueOpens`, `uniqueClicks`,
259
- `bounces`, `complaints`, `unsubscribes`, `totalEvents`), and a
260
- GDPR-style `deleteForSubject()` purge.
261
- - **Service** — `EmailEventService.recordOpen()` /
262
- `.recordClick({ url })` / `.recordBounce()` / `.recordComplaint()` /
263
- `.recordUnsubscribe()` + read-side `.listForSubject()`,
264
- `.aggregateForCampaign()`, and `.hasEngaged(subjectId, campaignId,
265
- kind)` for drip-condition checks.
266
- - **Events** — `crm:email_event.opened` / `.clicked` / `.bounced` /
267
- `.complained` / `.unsubscribed` with Zod-validated payloads in
268
- `event-catalog`, wired into `crmEventDefinitions[]`.
269
- - **In-memory adapter** — `InMemoryEmailEventRepository` (tests +
270
- dev). Hosts implement against Mongo / Postgres / etc.
271
-
272
- ### Added — re-exports from `@classytic/primitives@0.6.0`
273
-
274
- To eliminate duplicate type imports at consumer call sites:
275
-
276
- ```ts
277
- import {
278
- appendStatus,
279
- StatusChangeEntry,
280
- StatusHistory,
281
- timeInStatus,
282
- lastTransitionTo,
283
- } from '@classytic/crm';
284
- ```
285
-
286
- These pass through from `@classytic/primitives/status-history`. The
287
- existing entity-specific `LeadStatusEntry` / `OpportunityStatusEntry` /
288
- etc. names are still exported for back-compat — they remain structurally
289
- compatible with `StatusChangeEntry<TStatus>`.
290
-
291
- ### Changed
292
-
293
- - Peer dep `@classytic/primitives` bumped from `>=0.5.0` to `>=0.6.0`
294
- to access the new `status-history` subpath and value-typed primitives.
295
- - Test harness `buildHarness()` now also exposes an
296
- `emailEvents: EmailEventService` and `emailEventRepo` for integration
297
- tests that exercise the engagement → drip path.
298
-
299
- ### Dependencies
300
-
301
- - `@classytic/primitives@>=0.6.0` (peer, was `>=0.5.0`)
302
- - `zod@>=4.0.0` (peer, unchanged)
303
-
304
- ## [0.1.0] — 2026-04-18
305
-
306
- Initial release.
307
-
308
- ### Added
309
-
310
- - **Eight domain entities.** `Contact`, `Account`, `Lead`, `Opportunity`, `Pipeline` (+ nested `Stage`), `Activity`, `Note`, `LossReason`.
311
- - **Three state machines.** Lead (`new` → `contacted` → `qualified` → `converted`, + `disqualified` / `nurturing` branches), Opportunity (`open` → `won` / `lost` / `abandoned` with in-pipeline Stage movement), Activity (`planned` → `in_progress` → `completed` / `cancelled`). All transitions CAS-guarded with explicit `*_TRANSITIONS` maps and `canTransition*` guards.
312
- - **Six services.**
313
- - `ContactService` — CRUD + tag filtering + email lookup.
314
- - `AccountService` — CRUD + domain lookup.
315
- - `PipelineService` — create, archive, stage helpers (`getStage`, `getFirstStage`, `getNextStage`).
316
- - `OpportunityService` — create at first stage (or specified), `moveToStage` with advance/regress event disambiguation, `win` / `lose` (with `lostReasonId`) / `abandon`.
317
- - `LeadService` — CRUD + full lifecycle (`markContacted`, `qualify`, `disqualify`, `nurture`) + `convert()` — the crown-jewel verb that atomically creates Contact + Account + Opportunity and transitions the lead to `converted`.
318
- - `ActivityService` — polymorphic activities (`plan`, `start`, `complete`, `cancel`) + notes (`addNote`, `listNotesBySubject`).
319
- - **Pure calculators.**
320
- - `defaultLeadScorer` + `composeScorers(...rules)` — host injects whatever rubric (firmographics, in-app signals, ML prediction, enrichment) via a `(lead: Lead) => number` function.
321
- - `forecast(opportunities, options?)` — committed + weighted pipeline by bucket (default ISO month), with custom bucket function support. Currency-mismatch detection.
322
- - `pipelineConversion(opportunities, stageIds)` — where do deals die? returns per-stage current count + won/lost counts + conversion rate.
323
- - **Nine repository ports** — one per entity (plus `EventTransport`, `IdGenerator`, `Clock`, optional `OutreachPort`). Full in-memory reference implementations shipped.
324
- - **Typed error hierarchy** rooted at `CrmError`: `NotFoundError`, `InvalidLeadTransitionError`, `InvalidOpportunityTransitionError`, `InvalidActivityTransitionError`, `StageNotInPipelineError`, `LeadAlreadyConvertedError`, `DuplicateLeadError`, `EmptyPipelineError`.
325
- - **Nineteen lifecycle events** (`CRM_EVENTS`): covering lead/account/contact/opportunity/pipeline/activity/note verbs, all following `crm:<resource>.<verb>` per PACKAGE_RULES rule 12.
326
- - **Optional `OutreachPort`** — one-method (`send`) + `NullOutreachPort` + `InMemoryOutreachPort` (recording). Host subscribes to `crm:activity.*` events and drives the port from their automation layer (keeps pacing / retry / bounce handling out of the core).
327
- - **Testing.** `vitest.config.ts` projects split `unit` + `integration` per [testing-infrastructure.md](../../testing-infrastructure.md). 48 tests (7 files) — all green in <1.5s.
328
-
329
- ### Design choices
330
-
331
- - Pure-TS port-based pattern — consistent with `@classytic/manufacturing`, `@classytic/assets`, `@classytic/fleet`, `@classytic/carrier-*`.
332
- - Separate Lead + Opportunity models (erpnext style) rather than unified (odoo style) — cleaner semantics for pre-qualification vs in-pipeline data and enables distinct analytics.
333
- - Polymorphic Activity / Note via `subjectKind` + `subjectId` so hosts can extend without schema changes.
334
- - `LeadService.convert()` is atomic in intent and sequenced for auditability — it creates Account, then Contact, then Opportunity, then transitions the lead. If a downstream repo fails, the ones that succeeded persist (hosts using Mongoose sessions get atomicity at their layer).
335
- - Campaigns, appointment booking, competitors, contracts, team routing, RBAC, custom-field validation, email-thread parsing deferred to v0.2+ to keep the surface focused.
1
+ # Changelog
2
+
3
+ All notable changes to `@classytic/crm` are documented here.
4
+
5
+ ## [0.9.0] — unpublished (2026-07-15)
6
+
7
+ ### Changed — mongokit 3.22 adopted (peer floors: mongokit >=3.22.0, repo-core >=0.13.0, primitives >=0.11.0)
8
+
9
+ - **Seven transition verbs ride `applyTransition`** (activity, campaign,
10
+ enrollment exit + generic, lead, sequence, subscription, opportunity):
11
+ machine pre-flight + CAS + accurate race diagnosis via the machines'
12
+ existing errorFactories. All `this as any` casts at those sites are gone
13
+ (native method).
14
+ - **FIXED a real concurrency defect**: five sites built `statusHistory` by
15
+ read-modify-write (`[...(existing.statusHistory ?? []), entry]`) inside
16
+ the CAS patch — concurrent writers could drop history entries. Entries
17
+ now ride `$push` via the `push` arg, byte-identical shapes preserved.
18
+ - **`EmailEvent` log fence enforced** — "append-only" was a doc comment;
19
+ `appendOnlyPlugin` now refuses every mutation path (405
20
+ `APPEND_ONLY_VIOLATION`), with `deleteMany` allowed for host-gated GDPR
21
+ erasure of a recipient's rows.
22
+ - DELIBERATELY unchanged: `enrollment.advanceStep` (non-status
23
+ `currentStepIndex` CAS with null semantics) and opportunity's stage-move
24
+ claim — correct raw `claim` usage, not transition boilerplate.
25
+
26
+ ## [0.8.0] — 2026-07-11
27
+
28
+ ### Added — engagement-based lead scoring
29
+ - **`ILeadEngagement` on the Lead** (`{ opens, clicks, replies, activities, lastEngagedAt? }`, nested default `{}` so old rows read as zeros). Behavioural counters, distinct from firmographic fields.
30
+ - **`LeadRepository.recordEngagement(id, signal, ctx)`** where `signal ∈ 'open'|'click'|'reply'|'activity'` (`LeadEngagementSignal`). Atomic `$inc` on the matching counter + `lastEngagedAt` via `findOneAndUpdate`, then `recomputeScore`. Hosts feed it off `crm:message.received` (reply), `crm:activity.*` (activity), and email open/click tracking.
31
+ - **`defaultLeadScorer` now weighs engagement** on top of firmographic fit: reply ×25 · click ×8 · open ×2 · activity ×5, capped at +80. `LeadInput` picks up `engagement`. Pure/deterministic — no wall-clock. Absent engagement scores as zero (score unchanged for pre-existing leads until a signal lands).
32
+
33
+ ## [0.7.0] — 2026-07-05
34
+
35
+ ### Added — org-wide email suppression list
36
+
37
+ - **`Suppression` entity** (`crm.repositories.suppression`, model
38
+ `Suppression`): global per-org "never email this address again" list —
39
+ the gate hosts consult before EVERY outbound email. Unsubscribes on
40
+ `Subscription` stay per-campaign; suppression is org-wide.
41
+ - `suppress(email, { reason, source?, subjectKind?, subjectId?, metadata? }, ctx?)`
42
+ — idempotent `getOrCreate` on the unique `(organizationId, email)`
43
+ index (no check-then-save); emits `crm:suppression.added` only when
44
+ THIS call inserted the row.
45
+ - `isSuppressed(email, ctx?)` → boolean.
46
+ - `filterSuppressed(emails, ctx?)` → `Set<string>` of the suppressed
47
+ subset — ONE `$in` query for the campaign-fanout hot path.
48
+ - `unsuppress(email, ctx?)` — atomic delete; emits
49
+ `crm:suppression.removed` only when a row was actually removed.
50
+ - All verbs normalize emails (trim + lowercase; schema stores lowercase).
51
+ - **`SUPPRESSION_REASONS`** (`'bounce' | 'complaint' | 'unsubscribe' |
52
+ 'manual'`) — the first three `satisfies readonly EmailEventKind[]` (P6),
53
+ so a rename in `EMAIL_EVENT_KINDS` fails compilation here.
54
+ - **Events** `crm:suppression.added` / `crm:suppression.removed` — Zod
55
+ catalog definitions included (no-drift invariant stays green);
56
+ `organizationId` rides event meta as usual.
57
+ - **Validators** `suppressSchema` / `unsuppressSchema` /
58
+ `suppressionFilterSchema`.
59
+
60
+ ### Added — reply-detection exit verb
61
+
62
+ - **`EnrollmentRepository.exitActiveOnReply(subjects, ctx?)`** — the ONE
63
+ method a host's `crm:message.received` subscriber calls: finds ACTIVE
64
+ enrollments for the given `{ subjectKind, subjectId }` list, batch-loads
65
+ their sequences in a single `$in` query, skips those with
66
+ `replyDetectionEnabled === false`, and exits the rest via `exit(id,
67
+ 'reply')` (each exit emits `crm:enrollment.exited`). Lost CAS races
68
+ (concurrent pause/complete/exit) are skipped, not failed. Returns the
69
+ enrollments this call exited.
70
+ - `EnrollmentRepositoryDeps` now carries `sequences: SequenceRepository`
71
+ (same cross-repo deps idiom as `OpportunityRepository.pipelines` /
72
+ `MessageRepository.conversations`) — wired automatically by
73
+ `createCrm()`; only hosts constructing `EnrollmentRepository` by hand
74
+ need to pass it.
75
+
76
+ ## [0.6.0] — 2026-07-02
77
+
78
+ Breaking-in-behavior release (ships as MINOR per house convention):
79
+ outbox-first, session-safe event dispatch — the previously deferred
80
+ PACKAGE_RULES §P8/§P8.1 work.
81
+
82
+ ### Added — unit-of-work contract (P8.1, shared with refit/review/cart/invoice)
83
+
84
+ - **`engine.withTransaction(ctx, body)`** — runs `body` inside a MongoDB
85
+ transaction with post-commit event discipline: events dispatched through
86
+ `txCtx` are queued under `ctx[PENDING_EVENTS]` and flushed to the
87
+ transport only AFTER commit; the queue resets on retry attempts; an abort
88
+ leaks nothing to in-process subscribers. Reuses the caller's session (and
89
+ queue) when `ctx.session` is already set. Standalone-Mongo dev boots opt
90
+ in via the existing `allowNonTransactional: true`.
91
+ - **`PENDING_EVENTS`** (`Symbol.for('@classytic/crm:pendingEvents')`) +
92
+ **`flushPending(transport, queue, logger?)`** + **`runUnit`** exported
93
+ from the root for hosts composing their own outer transaction.
94
+ - **`CrmConfig.outbox?: OutboxStore`** (from `@classytic/primitives/outbox`)
95
+ — when wired, every domain event is persisted via
96
+ `outbox.save(event, { session })` in the SAME session as the business
97
+ write; the host's relay publishes committed rows. Outbox save failures
98
+ PROPAGATE (P8: a swallowed save means the write persists while its event
99
+ vanishes).
100
+ - **`CrmEventDispatcher`** — EventTransport-compatible wrapper repositories
101
+ route every event through (`engine.events` is now this wrapper; the host
102
+ `publish`/`subscribe` surface is unchanged).
103
+ - **`UnmanagedSessionError`** (`code: 'UNMANAGED_SESSION'`) — a host-owned
104
+ `ctx.session` arriving with neither an outbox nor a `PENDING_EVENTS`
105
+ queue now throws instead of ghost-publishing mid-transaction.
106
+ **Behavioral break:** callers that previously threaded a bare session and
107
+ tolerated ghost events must switch to `engine.withTransaction` (or wire
108
+ an outbox / attach a queue).
109
+
110
+ ### Added — timezone-aware forecasting
111
+
112
+ - **`ForecastOptions.timeZone`** — IANA zone for the default month bucket
113
+ (e.g. `'Asia/Dhaka'`). Without it, months cut at UTC boundaries: a deal
114
+ expected to close July 1, 02:00 Dhaka time (June 30, 20:00 UTC) files
115
+ under JUNE. Uses `civilDateOf` from `@classytic/primitives/timezone`.
116
+ Peer floor bumped: `@classytic/primitives >=0.9.0`.
117
+
118
+ ### Fixed — sequence/enrollment (completes the 0.6.0 WIP)
119
+
120
+ - **Event catalog no-drift restored**: 10 missing Zod definitions added
121
+ (`crm:sequence.{created,active,paused,archived}`,
122
+ `crm:enrollment.{created,step_sent,paused,resumed,completed,exited}`) —
123
+ `crm:sequence.created` and `crm:enrollment.step_sent` are host-emitted
124
+ (create via `def.create()`), the rest publish in-repo.
125
+ - **`EnrollmentRepository.setWorkflowRunId` / `advanceStep` no longer
126
+ bypass the repository**: both used raw `model.findOneAndUpdate` with a
127
+ manual tenant filter — escaping `multiTenantPlugin` scoping AND
128
+ `ctx.session` (a call inside `withTransaction` would commit outside the
129
+ transaction). `advanceStep` is now a `claim()` CAS on `currentStepIndex`
130
+ with `where: { status: 'active' }`; `setWorkflowRunId` goes through
131
+ `repo.update`.
132
+
133
+ ### Tests
134
+
135
+ - 14 new: `tests/unit/dispatch.test.ts` (6 — outbox propagation/session
136
+ routing/guard/swallow), `tests/integration/unit-of-work.test.ts` (3 —
137
+ convert() on a replica set: zero mid-tx events, post-commit flush, abort
138
+ leaks nothing, bare-session guard), `tests/unit/forecast-timezone.test.ts`
139
+ (5 — the +06:00 month-boundary trap). 110/110 total.
140
+
141
+ ## [0.5.1] — 2026-06-14
142
+
143
+ ### Fixed — declaration bundle
144
+
145
+ - **fix: declaration bundle exported mangled aliases; consumer named imports
146
+ now resolve.** The published `dist/index.d.ts` re-exported every public
147
+ symbol under a minified alias (`export { AccountRepository as A, CRM_EVENTS
148
+ as Rr, … }`), so downstream `import { AccountRepository, CRM_EVENTS } from
149
+ '@classytic/crm'` failed with TS2305 / TS2460. Root cause: the `./events`
150
+ entry re-exports a strict subset of the `index` barrel, which made
151
+ `rolldown-plugin-dts` alias every name on the superset (`index`) entry when
152
+ both were emitted in a single pass. Build now runs `index` and `events` as
153
+ two independent tsdown passes (array config) so each `.d.ts` exports real
154
+ names. `tsdown` bumped `^0.14.2` → `^0.21.10` to match sibling packages.
155
+ No runtime/API change.
156
+
157
+ ## [0.5.0] — 2026-06-14
158
+
159
+ Stack upgrade + verified correctness fixes + PACKAGE_RULES compliance. No
160
+ new features. Clean break — no deprecation aliases.
161
+
162
+ ### Changed — stack currency
163
+
164
+ - Peers bumped: `@classytic/mongokit` `>=3.16.0`, `@classytic/repo-core`
165
+ `>=0.6.0`, `@classytic/primitives` `>=0.7.1`, `mongoose` `>=9.4.1`.
166
+ Clean-installed from npm and verified resolved (3.16.0 / 0.6.0 / 0.7.2).
167
+
168
+ ### Added — PACKAGE_RULES compliance
169
+
170
+ - **Zod event catalog (rule 18).** New `crmEventDefinitions[]` (56 events,
171
+ one Zod schema each) exported from the package root and a new `./events`
172
+ subpath. Timestamps are `z.iso.datetime()`. A no-drift invariant test
173
+ asserts every `CRM_EVENTS` constant has a definition. Hosts wire these
174
+ into arc's `EventRegistry` for publish-time validation + OpenAPI.
175
+ - **Model-collision policy (rule 21).** `createCrm()` now throws
176
+ `CrmModelCollisionError` when a model name is already registered; pass
177
+ `forceRecreate: true` (test/hot-reload) to delete + re-register.
178
+ - **Index management (rule 35).** New `autoIndex` config flag (default
179
+ `true`) and `engine.syncIndexes()` for `autoIndex: false` production
180
+ boots.
181
+ - **Capability boot gate.** `createCrm()` asserts the backend supports
182
+ `upsert` / `getOrCreate` / `duplicateKeyError` (and `transactions`,
183
+ unless `allowNonTransactional: true`) so misconfigured deployments fail
184
+ loud at boot instead of mid-convert.
185
+
186
+ ### Fixed — domain correctness
187
+
188
+ - **Lead / Subscription / Campaign dedup are now race-safe.** Added
189
+ authoritative partial-unique indexes — lead `(organizationId, email)`,
190
+ campaign `(organizationId, name)`, subscription `(organizationId,
191
+ contactId, campaignId)` scoped to live statuses — and catch the
192
+ residual `E11000` via `isDuplicateKeyError`, re-throwing the same typed
193
+ domain error the pre-check emits. The prior check-then-save left a
194
+ TOCTOU window.
195
+ - **Owner reassignment is now atomic.** `assign()` on lead / account /
196
+ contact / opportunity / conversation uses a single `findOneAndUpdate`
197
+ CAS (`{ ownerId: { $ne } }` guard, `returnDocument: 'before'`) — no
198
+ read-modify-write lost-update window, and the emitted `previousOwnerId`
199
+ is the true pre-image under concurrency.
200
+ - **Cross-tenant leak in dashboard/feed reads closed.** `findRecentForFeed`,
201
+ `countCreatedSince`, `countOpen`, `sumWonSince`, `countOverduePlanned`
202
+ dropped raw `Model.find` / `countDocuments` with a manual
203
+ `if (ctx) organizationId` filter (which read ALL tenants when ctx was
204
+ absent) for the tenant-scoped `findAll` / `count` repository methods.
205
+
206
+ ### Build hygiene
207
+
208
+ - Sourcemaps and declaration maps are no longer emitted (`sourceMap` /
209
+ `declarationMap` off in tsconfig; `sourcemap: false` in tsdown) — both
210
+ leak source.
211
+ - Removed `@deprecated` markers from `ConvertResult` convenience id fields
212
+ (kept the fields; they were never deprecated, just mislabelled).
213
+ - Dropped the stale pnpm lockfile/workspace and the bundled `.tgz`;
214
+ installs are npm-from-registry only.
215
+
216
+ ### Docs
217
+
218
+ - Rewrote the README to the engine-factory API (`createCrm` + repository
219
+ domain verbs). The previous README documented the abandoned v0.1
220
+ port/adapter design (`AccountService`, `InMemory*Repository`,
221
+ `OutreachPort`) that no longer exists.
222
+
223
+ ### Tests
224
+
225
+ - Added `tests/integration/invariants.test.ts` (tenant probe, lead +
226
+ subscription dedup races, atomic reassignment) and
227
+ `tests/unit/event-catalog.test.ts` (no-drift + round-trip). 87 → 96
228
+ tests.
229
+
230
+ ## [0.4.0] — 2026-05-22
231
+
232
+ ### Changed — Subscription model renamed to `EmailSubscription`
233
+
234
+ **Breaking at the Mongo identity level.** The CRM's email opt-in resource
235
+ now registers as Mongoose model `EmailSubscription` (was `Subscription`)
236
+ and persists into the `email_subscriptions` collection (was
237
+ `subscriptions`).
238
+
239
+ **Why:** the previous name collided with `@classytic/revenue`'s
240
+ `Subscription` model when both packages were loaded on the same
241
+ Mongoose connection — `RevenueModelCollisionError` at boot. Renaming
242
+ gives the two concepts distinct identities at the DB level and lets
243
+ revenue + CRM coexist without the host having to split connections.
244
+
245
+ **TypeScript surface is unchanged.** `ISubscriptionDocument`,
246
+ `SubscriptionRepository`, `subscription.handlers.ts`,
247
+ `CrmModels.Subscription`, etc. all keep their existing names — only
248
+ the Mongoose model name string and the underlying collection name
249
+ changed. Consumers that import from `@classytic/crm` need no source
250
+ changes; the host only needs to migrate existing data (see below).
251
+
252
+ ### Migration
253
+
254
+ For DBs with existing CRM subscription rows in the legacy `subscriptions`
255
+ collection (distinguishable from revenue rows by `contactId` presence):
256
+
257
+ ```js
258
+ // MongoDB shell — one-time migration
259
+ db.subscriptions.aggregate([
260
+ { $match: { contactId: { $exists: true } } },
261
+ { $out: 'email_subscriptions' },
262
+ ]);
263
+ // Then remove the migrated docs from the legacy collection:
264
+ db.subscriptions.deleteMany({ contactId: { $exists: true } });
265
+ ```
266
+
267
+ Hosts using only CRM (no revenue) can also run this — leftover rows in
268
+ `subscriptions` won't cause boot errors because there's no collision
269
+ without revenue.
270
+
271
+ ## [0.3.0] — 2026-05-17
272
+
273
+ ### Added — `EmailEvent` domain
274
+
275
+ Closes the loop between outbound CRM sends and recipient engagement.
276
+ Hosts can now record opens, clicks, bounces, complaints, and unsubscribes
277
+ against a Contact / Subscription / Campaign tuple — and downstream
278
+ services (drip-sequence "if opened" branches, lead scoring, suppression
279
+ lists) consume the same events without polling the email transport.
280
+
281
+ - **Entity & enum** — `EmailEvent` (append-only) plus the
282
+ `EmailEventKind` enum (`open` / `click` / `bounce` / `complaint` /
283
+ `unsubscribe`) split into `ENGAGEMENT_KINDS` and `SUPPRESSION_KINDS`
284
+ helper sets for classification at call sites.
285
+ - **Port** — `EmailEventRepository` with filtered list, per-subject
286
+ timeline, per-campaign aggregates (`uniqueOpens`, `uniqueClicks`,
287
+ `bounces`, `complaints`, `unsubscribes`, `totalEvents`), and a
288
+ GDPR-style `deleteForSubject()` purge.
289
+ - **Service** — `EmailEventService.recordOpen()` /
290
+ `.recordClick({ url })` / `.recordBounce()` / `.recordComplaint()` /
291
+ `.recordUnsubscribe()` + read-side `.listForSubject()`,
292
+ `.aggregateForCampaign()`, and `.hasEngaged(subjectId, campaignId,
293
+ kind)` for drip-condition checks.
294
+ - **Events** — `crm:email_event.opened` / `.clicked` / `.bounced` /
295
+ `.complained` / `.unsubscribed` with Zod-validated payloads in
296
+ `event-catalog`, wired into `crmEventDefinitions[]`.
297
+ - **In-memory adapter** — `InMemoryEmailEventRepository` (tests +
298
+ dev). Hosts implement against Mongo / Postgres / etc.
299
+
300
+ ### Added — re-exports from `@classytic/primitives@0.6.0`
301
+
302
+ To eliminate duplicate type imports at consumer call sites:
303
+
304
+ ```ts
305
+ import {
306
+ appendStatus,
307
+ StatusChangeEntry,
308
+ StatusHistory,
309
+ timeInStatus,
310
+ lastTransitionTo,
311
+ } from '@classytic/crm';
312
+ ```
313
+
314
+ These pass through from `@classytic/primitives/status-history`. The
315
+ existing entity-specific `LeadStatusEntry` / `OpportunityStatusEntry` /
316
+ etc. names are still exported for back-compat — they remain structurally
317
+ compatible with `StatusChangeEntry<TStatus>`.
318
+
319
+ ### Changed
320
+
321
+ - Peer dep `@classytic/primitives` bumped from `>=0.5.0` to `>=0.6.0`
322
+ to access the new `status-history` subpath and value-typed primitives.
323
+ - Test harness `buildHarness()` now also exposes an
324
+ `emailEvents: EmailEventService` and `emailEventRepo` for integration
325
+ tests that exercise the engagement → drip path.
326
+
327
+ ### Dependencies
328
+
329
+ - `@classytic/primitives@>=0.6.0` (peer, was `>=0.5.0`)
330
+ - `zod@>=4.0.0` (peer, unchanged)
331
+
332
+ ## [0.1.0] — 2026-04-18
333
+
334
+ Initial release.
335
+
336
+ ### Added
337
+
338
+ - **Eight domain entities.** `Contact`, `Account`, `Lead`, `Opportunity`, `Pipeline` (+ nested `Stage`), `Activity`, `Note`, `LossReason`.
339
+ - **Three state machines.** Lead (`new` → `contacted` → `qualified` → `converted`, + `disqualified` / `nurturing` branches), Opportunity (`open` → `won` / `lost` / `abandoned` with in-pipeline Stage movement), Activity (`planned` → `in_progress` → `completed` / `cancelled`). All transitions CAS-guarded with explicit `*_TRANSITIONS` maps and `canTransition*` guards.
340
+ - **Six services.**
341
+ - `ContactService` — CRUD + tag filtering + email lookup.
342
+ - `AccountService` — CRUD + domain lookup.
343
+ - `PipelineService` — create, archive, stage helpers (`getStage`, `getFirstStage`, `getNextStage`).
344
+ - `OpportunityService` — create at first stage (or specified), `moveToStage` with advance/regress event disambiguation, `win` / `lose` (with `lostReasonId`) / `abandon`.
345
+ - `LeadService` — CRUD + full lifecycle (`markContacted`, `qualify`, `disqualify`, `nurture`) + `convert()` — the crown-jewel verb that atomically creates Contact + Account + Opportunity and transitions the lead to `converted`.
346
+ - `ActivityService` — polymorphic activities (`plan`, `start`, `complete`, `cancel`) + notes (`addNote`, `listNotesBySubject`).
347
+ - **Pure calculators.**
348
+ - `defaultLeadScorer` + `composeScorers(...rules)` — host injects whatever rubric (firmographics, in-app signals, ML prediction, enrichment) via a `(lead: Lead) => number` function.
349
+ - `forecast(opportunities, options?)` — committed + weighted pipeline by bucket (default ISO month), with custom bucket function support. Currency-mismatch detection.
350
+ - `pipelineConversion(opportunities, stageIds)` — where do deals die? returns per-stage current count + won/lost counts + conversion rate.
351
+ - **Nine repository ports** — one per entity (plus `EventTransport`, `IdGenerator`, `Clock`, optional `OutreachPort`). Full in-memory reference implementations shipped.
352
+ - **Typed error hierarchy** rooted at `CrmError`: `NotFoundError`, `InvalidLeadTransitionError`, `InvalidOpportunityTransitionError`, `InvalidActivityTransitionError`, `StageNotInPipelineError`, `LeadAlreadyConvertedError`, `DuplicateLeadError`, `EmptyPipelineError`.
353
+ - **Nineteen lifecycle events** (`CRM_EVENTS`): covering lead/account/contact/opportunity/pipeline/activity/note verbs, all following `crm:<resource>.<verb>` per PACKAGE_RULES rule 12.
354
+ - **Optional `OutreachPort`** — one-method (`send`) + `NullOutreachPort` + `InMemoryOutreachPort` (recording). Host subscribes to `crm:activity.*` events and drives the port from their automation layer (keeps pacing / retry / bounce handling out of the core).
355
+ - **Testing.** `vitest.config.ts` projects split `unit` + `integration` per [testing-infrastructure.md](../../testing-infrastructure.md). 48 tests (7 files) — all green in <1.5s.
356
+
357
+ ### Design choices
358
+
359
+ - Pure-TS port-based pattern — consistent with `@classytic/manufacturing`, `@classytic/assets`, `@classytic/fleet`, `@classytic/carrier-*`.
360
+ - Separate Lead + Opportunity models (erpnext style) rather than unified (odoo style) — cleaner semantics for pre-qualification vs in-pipeline data and enables distinct analytics.
361
+ - Polymorphic Activity / Note via `subjectKind` + `subjectId` so hosts can extend without schema changes.
362
+ - `LeadService.convert()` is atomic in intent and sequenced for auditability — it creates Account, then Contact, then Opportunity, then transitions the lead. If a downstream repo fails, the ones that succeeded persist (hosts using Mongoose sessions get atomicity at their layer).
363
+ - Campaigns, appointment booking, competitors, contracts, team routing, RBAC, custom-field validation, email-thread parsing deferred to v0.2+ to keep the surface focused.