MutuelleFit is a thin Insurance bounded context POC: multi-tenant enrol / dispense → carrier affiliation behind an anti-corruption layer → Santé premium instructions for a payroll stub. Design sources: constitution, docs/base.md, Spec Kit feature 001-mutuelle-enrolment-cotisations.
One breath: DDD decides the walls (who owns enrolment vs payroll vs employee). System design decides the pipes and failure modes (api / worker / outbox / queue / retries). They nest — they are not competitors.
Figures use seed data only (Company 1 / Employee 1). No live credentials. Carrier names are ACL stubs. Hover or focus a figure to blur it and read the contract.
Live guided demo on GitHub Pages — a cursor walks Docs → enrol until Covered → Architecture play → Cards. It loads only when you click below (so the auto-tour cannot yank page scroll). Full screen: MutuelleFit demo.

Guided demo — Play demo or Play demo with music (Bensound).
What the vertical proves — constitution principles I–VII plus Spec Kit clarifications:
| # | Contract | Evidence |
|---|---|---|
| 1 | Enrol is async | 202 + PendingExternal; Active only after ACL confirm |
| 2 | Bounded writes | Insurance never writes Payroll tables; ids + cents on the bus |
| 3 | ACL, not products | Same EnrolEmployee; InsurerGateway → AlanStub | AxaStub |
| 4 | Outbox + idempotency in Postgres | Same TX as aggregate; (companyId, route, key) store |
| 5 | ANI money | Integer EUR cents; employer ≥ 50%; half-up + remainder |
| 6 | Tenant isolation | X-Company-Id mismatch → 403 |
| 7 | Honest failure | Retry ×3 → Failed + DLQ counter — never silent Active |
| 8 | Agentic rails | Spec Kit + domain skills block illegal transitions |
Target pain: double entry between HRIS and insurer, wrong cotisations on the bulletin, leavers still “covered.” The POC is the smallest vertical that still has real architecture — not claims, marketplace, or DSN/URSSAF.
Pitch: for many client companies, turn employee lifecycle into mutuelle affiliation and payroll-ready cotisations — DDD vertical + events + outbox + swappable carrier ACLs.

Five ownership zones. Write authority is the cut that matters — not how many containers you deploy. Walls first (Insurance vs Employee vs Payroll); then pipes (HTTPS commands, outbox → bus, ACL HTTPS, webhooks).

Hexagonal / ports-and-adapters. Driving adapters: HTTP domain API + worker. Driven adapters: Postgres, in-process bus (prod-shaped → SQS / SNS / EventBridge), AlanStub / AxaStub. Domain aggregates contain zero carrier DTOs — only InsurerGateway. That is the anti-corruption layer.
Context map. Employee / Company are upstream. Payroll is downstream customer/supplier via PremiumInstructionIssued. Carriers are conformist at the ACL, not in the core model. Identity is stub headers (X-Role, X-Company-Id) in the POC.
flowchart TB
subgraph Upstream["Upstream"]
EMP[Employee]
CO[Company]
ID[Identity stub]
end
subgraph InsuranceBC["Insurance BC"]
API["Domain API /v1"]
AGG["Enrolment aggregate + FSM"]
OB[(outbox · idempotency · audit)]
W[Activation worker]
GW["InsurerGateway"]
end
subgraph Downstream["Downstream / edge"]
PAY[Payroll stub]
ALAN[AlanStub]
AXA[AxaStub]
end
EMP -->|Terminated| W
CO -->|carrier config| AGG
ID -->|authZ| API
API --> AGG
AGG --> OB
W --> OB
W --> GW
GW --> ALAN
GW --> AXA
W -->|PremiumInstructionIssued| PAY

Command → same-TX outbox → worker → ACL → Active → premium instruction → payroll stub.

Same ACID transaction:
- Enforce invariants — ≤1 open
PendingExternal|Activeper(companyId, employeeId); plan exists; insurance enabled;coverage = collective. - Persist Enrolment as
PendingExternal. - Insert outbox row (
event_type+ jsonb payload). - Upsert
idempotency_keys(company_id, route, key)→ cached 202 body.
Worker drains Pending / outbox → createMember → on success FSM → Active + EmployeeEnrolledInInsurance + PremiumInstructionIssued. Timeout increments attempt_count; after 3 → Failed + dead_letter_counters.
Example · enrol (Company A / Alan)
curl -sS \
-H "X-Role: company.admin" \
-H "X-Company-Id: company-a" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: demo-enrol-a-1" \
-X POST "http://localhost:3810/v1/companies/company-a/enrolments" \
-d '{
"employeeId": "emp-a1",
"planId": "sante-base",
"coverage": "collective",
"effectiveFrom": "2026-04-01"
}'
# → 202 { enrolmentId, status: "PendingExternal" }
Example · dual carrier (Company B / AXA)
curl -sS \
-H "X-Role: company.admin" \
-H "X-Company-Id: company-b" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: demo-enrol-b-1" \
-X POST "http://localhost:3810/v1/companies/company-b/enrolments" \
-d '{
"employeeId": "emp-b1",
"planId": "sante-base",
"coverage": "collective",
"effectiveFrom": "2026-04-01"
}'
# ACL log differs; PremiumInstruction shape identical
Example · published language
PremiumInstructionIssued {
eventId, occurredAt, companyId, employeeId, enrolmentId,
periodFrom, periodTo, // Europe/Paris month of effectiveFrom
employerShareCents, // half-up from plan.employerSharePct
employeeShareCents, // remainder so sum === premium
currency: "EUR"
}
Command vs event. EnrolEmployee is a command — please do X; it can be refused (400 / 403 / 409). EmployeeEnrolledInInsurance and PremiumInstructionIssued are domain events — past-tense facts others react to. Never name an event UpdateEnrolment (a DB verb); consumers need a business fact. One aggregate TX in Insurance; Payroll must not join that TX.
Money: splitShares(monthlyPremiumCents, employerSharePct) rejects employerSharePct < 50, half-up on employer cents, employee gets remainder. Seed plan → 60 / 40 EUR on the bulletin preview.
Effective dating & proration. Cover and premium instructions carry a validity interval, not only a “current” flag. Spec Kit locked period = whole calendar month of effectiveFrom in Europe/Paris (full_month — no mid-month pro-rata engine in v1). Say the rule aloud, then stick to it; fixing a wrong premium means a new/changed instruction + audit, not a silent rewrite of history.
Illegal transitions are rejected in the aggregate. UI labels map 1:1 to engine names.

Spec Kit defaults that stop invention: missing Idempotency-Key → 400; replay → 202 same body; terminate vs activate → terminate wins; webhook already Active → 200 no-op; Cancel on Dispensed / Failed → 409.
Saga vs FSM. Enrolment is multi-step in life (accept → insurer → Active → Payroll), but the MVP keeps an Enrolment FSM + worker retries — not a saga framework. Introduce an explicit saga (with compensations as first-class steps) only when branching gets heavy. Pending + leave already compensates locally and at the ACL without a workflow engine.
Reliability tables are the design. Domain refs stay boring on purpose.

| Table | Pattern | Key columns |
|---|---|---|
enrollments | Aggregate write model | status, attempt_count, insurer_member_id, carrier |
outbox | Transactional outbox | event_type, payload, published_at |
idempotency_keys | Command dedupe | (company_id, route, key) → response_body |
audit_log | Append-only trail | correlation_id, action, detail |
dead_letter_counters | Ops signal | count, last_enrollment_id |
payroll_lines | Downstream stub | Written from events — not from enrol commands |
Insurance’s own HTTP API — not the insurer’s, not Payroll’s. Command / query style; server enforces invariants + authZ.
| Method | Path | Role | Intent |
|---|---|---|---|
POST | /v1/companies/:id/enrolments | company.admin | EnrolEmployee + Idempotency-Key |
POST | /v1/companies/:id/dispenses | company.admin | DispenseEmployee |
POST | /v1/enrolments/:id/cancellations | company.admin | CancelEnrolment → Ended |
GET | /v1/companies/:id/enrolments | company.admin | List cover |
GET | /v1/enrolments/:id | company.admin | Detail |
GET | /v1/me/cover | employee.self | My cover |
POST | /v1/webhooks/carriers/:carrier | carrier sig | Confirm / reject |
POST | /v1/dev/platform-events | system.worker | Terminate ingress |
GET | /v1/companies/:id/payroll-lines | company.admin | Bulletin preview |
GET | /v1/companies/:id/audit | company.admin | Audit tail |
Webhook path (carrier → us). Never trust the body blindly: verify signature (X-Carrier-Signature stub secret in POC → 401 if wrong) → dedupe insurerEventId (inbox) → match/upsert on insurerMemberId / enrolmentId → drive the FSM via a domain command → emit our events on the outbox (not raw insurer JSON). Out-of-order is OK if upsert is idempotent. Demo gate may activate sync via stubs; the webhook contract still exists so duplicate notify is a no-op, not a second Active.
Happy path is cheap. This table is the review gate:
| Case | Expected |
|---|---|
| Double-click enrol | Same Idempotency-Key → same enrolment |
| Insurer timeout | Pending → retry → Failed@3 + DLQ counter |
| Duplicate webhook | insurerEventId inbox → no-op |
| Terminate while Pending | Cancel local + compensate stub |
| Dispense instead of enrol | Dispensed; no PremiumInstruction |
| Wrong company | 403 |
| Dispense while Active / Pending | 409 |
| Missing Idempotency-Key | 400 |
Example · tenancy 403
curl -sS -o /dev/null -w "%{http_code}\n" \
-H "X-Role: company.admin" \
-H "X-Company-Id: company-a" \
-H "Idempotency-Key: x" \
-H "Content-Type: application/json" \
-X POST "http://localhost:3810/v1/companies/company-b/enrolments" \
-d '{"employeeId":"emp-b1","planId":"sante-base","coverage":"collective","effectiveFrom":"2026-04-01"}'
# → 403
Example · terminate
curl -sS \
-H "X-Role: system.worker" \
-H "Content-Type: application/json" \
-X POST "http://localhost:3810/v1/dev/platform-events" \
-d @fixtures/employee-terminated.json
# → Ended + compensate + PremiumInstruction Stop
Thin client: commands + projections. Never calls the carrier. Never writes payslip lines.


Prove domain + events + multi-company + two carriers. Everything else is seed, fixture, or stub.
| Must code | Seed | Mock / defer |
|---|---|---|
| Enrolment aggregate + FSM tests | companies A/B, employees, plan, reasons, admins | Real Alan / AXA HTTP |
| Domain API enrol / list / get | employerSharePct ≥ 50 | SSO |
| Outbox same TX + publisher | dispense reason codes | SQS / K8s / Terraform |
| Worker + AlanStub + AxaStub | AXA setup-sheet fixture | DSN / URSSAF |
| Idempotency + 403 tests | — | Marketplace, claims |
| Terminate handler | employee-terminated fixture | ChangeCoverage |
Ship order: seed → aggregate + tests → API → outbox → worker + stubs → idempotency → tenancy → terminate → demo curls / thin React.
Local: API :3810, worker, Postgres :5433, UI :5810 (hub.yaml). Cloud is transport — not a redesign:
| POC | Production-shaped | Concern |
|---|---|---|
| SQL outbox + publisher | Outbox → SQS / SNS / EventBridge | Fan-out, retry, DLQ |
| Activation worker | EKS / ECS / Lambda consumer | Scale consumers ≠ API |
| Idempotency + inbox | Exactly-once effect | Blips, webhook dupes |
InsurerGateway stubs | Real partner HTTP, same port | Adapter swap |
X-Correlation-Id + DLQ counters | Traces, metrics, alarms | Operability |
At-least-once is the default. SQS (and webhooks) can deliver more than once. Visibility timeout: while a worker processes a message, others don’t see it; if the process dies before delete/ack, the message reappears — that is the duplicate. Design for at-least-once delivery + idempotent handlers (outbox publish once logically; inbox / eventId / Idempotency-Key for effects). SNS = publish once, fan-out to many queues; SQS = competing consumers on one queue. DLQ = park poison after N fails and alert — don’t retry forever. Don’t bet on exactly-once delivery; aim for exactly-once effect.
Scale target: thousands of companies × employees × monthly payroll runs without leave-drift — not enrol QPS theatre.
What kept velocity from deleting the design:
- Spec Kit — constitution → specify → plan → tasks → implement.
- Domain skills —
insurance-domain,insurer-acl,insurance-demo. hub.yaml— shared ports for humans and agents.- Subagents + browser — explore in parallel, verify Cover / Docs on localhost.
Clarifications locked ~30 POC defaults (Europe/Paris month, cents canonical, Failed re-enrolable, terminate wins races, …). That is why agents did not invent a synchronous Active shortcut.
flowchart LR
subgraph Spec["Spec Kit"]
C[Constitution]
S[Spec + clarifications]
P[Plan / tasks]
I[Implement]
end
subgraph Skills["Skills"]
D[insurance-domain]
A[insurer-acl]
M[insurance-demo]
end
C --> S --> P --> I
D --> I
A --> I
M --> I
I --> Demo[Cover + curls + tests]
- Walls then pipes — DDD ownership first; api/worker/queue second.
- Aggregate + FSM honesty — Waiting is a product feature; saga only if branching demands it.
- Command ≠ event — refuseable intent vs past-tense facts.
- Transactional outbox + idempotency — in the schema; at-least-once on the bus.
- ACL + signed webhooks — partner JSON stays at the edge.
- Tenant authZ — 403 is a demo step.
- Integer money + explicit period rule — ANI cents;
full_month/Europe/Paris. - Edge matrix — Spec Kit clarifications beat vibes.
- Agentic speed with a constitution — otherwise the UI lies.
MutuelleFit stays a POC: stubs, seed companies, thin admin. The contracts above are what transfer — whether the bus is in-process or EventBridge.
