14 KiB
WhatsApp Group Messaging — Engineering Review
Date: 2026-06-11
Project: SquareMCP / hermes-mcp
Status: REVIEWED — Option 2 selected, ready to implement
Reviewed by: Claude Code (plan-eng-review skill)
Related: 2026-06-11-whatsapp-group-messaging-spec, 2026-06-11-whatsapp-63024-and-group-messaging-investigation, 2026-06-10-twilio-whatsapp-webhook-deployment
Decision Summary
Chosen path: Option 2 — Fan-out 1:1 over existing infrastructure.
Option 1 (Twilio Conversations API, 2.5–3 days) was declined at the scope challenge. The spec's own spike recommendation was the deciding factor: if Meta still requires each participant to text the business number first regardless of Conversations API (likely), Option 1 buys nothing over Option 2. Build Option 2 now (~4 hours). Do the Conversations API spike before committing to Option 1.
Context: Why Group Messaging at All
The lodge-first launch wants lodge members to interact with SquareMCP via a shared WhatsApp thread — weekly draft approvals and "onboard in the room" (lodge member texts the SquareMCP number at the July meeting and gets auto-provisioned).
Constraint confirmed 2026-06-11: WhatsApp deprecated the native Groups API in April 2020. The Twilio/Meta Business Platform number (+1 954-738-5805) cannot be added as a participant in an existing WhatsApp group chat. Twilio's own FAQ states this explicitly.
Option Comparison
Option 1 — Twilio Conversations API (NOT chosen)
Creates one Twilio-managed Conversation thread. All lodge members are Participants. Messages fan out through +1 954-738-5805 to everyone — real shared context, everyone sees each other's approvals.
Why it was considered:
- True shared-thread experience
- Sets up multi-tenant group infra for future chapters
Why it was declined (for now):
- Core assumption unvalidated: Can a number be added as a Participant and receive messages before it has texted +1 954-738-5805? If Meta requires each participant to initiate first (likely), Option 1 collapses to Option 2 at the delivery layer anyway — with 4 new files, 2 new DB tables, and 3x the code debt.
- Spike required: 0.5 day to confirm Meta opt-in mechanics before committing 2.5–3 days of build.
Effort: 2.5–3 days + 0.5-day spike.
What Option 1 would have needed (from the original spec):
src/webhooks/twilio-conversations.ts— new webhook for Conversations eventssrc/conversations/conversations-client.ts— Conversations REST wrappersrc/conversations/schema.sql—conversations+conversation_participantstablessrc/webhooks/twilio-conversations.test.ts- New env vars:
TWILIO_CONVERSATIONS_SERVICE_SID,LODGE_CONVERSATION_SID - New
POST /webhook/twilio/conversationsendpoint
Option 2 — Fan-Out 1:1 (CHOSEN)
No Conversations API. Each lodge member opts in 1:1 (texts +1 954-738-5805 once). Weekly draft cron fans out the same message to all opted-in numbers. Replies are handled individually by the existing webhook. Approval is first-reply-wins.
Why it was chosen:
- Delivers the "lodge gets drafts" use case for ~4 hours of work vs 3 days
- No new webhook routes, no new Twilio infrastructure
- Extends existing
src/webhooks/twilio-whatsapp.tsrather than adding a parallel system - Worst case: indistinguishable from Option 1 at the member experience level if Meta requires initiation anyway
Tradeoff accepted: Members can't see each other's replies. The group approval is per-person, not a shared thread visible to all. This is acceptable for the pilot phase.
Architecture (Option 2)
What stays unchanged
POST /webhook/twilio/whatsapp— handler signature, HMAC-SHA1 validation, Redis dedup, TwiML ACK pattern all unchanged- Redis
twilio_wa_number:+19547385805 → customerIdmapping — still works; resolves to the lodge's customer ID; participant check happens after handleApproval(customerId, from, messageId, body, numMedia)— same signaturesrc/index.ts— no new route needed
Change 1: New table pilot_participants
CREATE TABLE pilot_participants (
id VARCHAR(36) NOT NULL DEFAULT (UUID()),
customer_id VARCHAR(255) NOT NULL,
phone_e164 VARCHAR(20) NOT NULL,
opted_in_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
opted_out_at DATETIME NULL,
INDEX idx_participant_lookup (customer_id, phone_e164)
);
The (customer_id, phone_e164) compound index makes the allowlist check a covered lookup. At lodge scale (5–50 members) this is effectively free.
pilot_owner_phone on the customers table is not dropped — leave it, avoids a destructive migration and there may be existing code paths that reference it. Lodge-style customers that use pilot_participants just leave it null.
Change 2: Allowlist check in handleApproval (lines 66–74 of twilio-whatsapp.ts)
Before:
interface CustomerRow extends RowDataPacket {
pilot_owner_phone: string | null;
}
const [customers] = await pool.query<CustomerRow[]>(
'SELECT pilot_owner_phone FROM customers WHERE id = ?',
[customerId]
);
const pilotPhone = customers[0]?.pilot_owner_phone ?? '';
if (!pilotPhone || from !== pilotPhone) {
console.log(`[twilio-webhook] sender ${from} not in allowlist, customerId=${customerId}, MessageSid=${messageId}`);
return;
}
After:
const [participants] = await pool.query<RowDataPacket[]>(
`SELECT 1 FROM pilot_participants
WHERE customer_id = ? AND phone_e164 = ?
AND opted_in_at IS NOT NULL AND opted_out_at IS NULL`,
[customerId, from]
);
if (participants.length === 0) {
console.log(`[twilio-webhook] sender ${from} not in allowlist, customerId=${customerId}`);
return;
}
Remove the CustomerRow interface entirely — it's no longer needed.
Change 3: Auto-enrollment on first message
New exported function in twilio-whatsapp.ts:
export async function autoEnrollParticipant(
customerId: string,
phone: string
): Promise<void> {
try {
await getPool().query(
`INSERT INTO pilot_participants (id, customer_id, phone_e164)
VALUES (UUID(), ?, ?)
ON DUPLICATE KEY UPDATE opted_in_at = opted_in_at`,
[customerId, phone]
);
} catch (err) {
console.error(`[twilio-webhook] autoEnrollParticipant failed, customerId=${customerId}, phone=${phone}:`, err);
}
}
This is called in handleTwilioWhatsApp, after the Redis customerId lookup and before handleApproval:
const customerId = await redis.get(`twilio_wa_number:${to}`).catch(() => null);
if (!customerId) { ... return; }
await autoEnrollParticipant(customerId, from); // ← new line
handleApproval(customerId, from, messageId, body, numMedia).catch(...);
Note: ON DUPLICATE KEY UPDATE opted_in_at = opted_in_at is a no-op UPDATE that satisfies MySQL's duplicate-key constraint without actually changing the row. This means the first message from any number auto-enrolls them, and subsequent messages are idempotent. If a keyword gate is wanted later ("text JOIN to opt in"), swap this for a conditional check before inserting.
Change 4: "Already approved" UX (required for group context)
When multiple members reply "1" within a short window, the second person currently gets "No pending drafts right now. New ones arrive on Monday." — confusing in a group context where the draft was just approved seconds ago by someone else.
Add this check just before the drafts.length === 0 empty-queue message:
if (drafts.length === 0) {
// Check if another group member just approved
const [recentApprovals] = await pool.query<RowDataPacket[]>(
`SELECT id FROM post_drafts
WHERE tenant_id = ? AND status = 'approved'
AND approved_at > NOW() - INTERVAL 24 HOUR
ORDER BY approved_at DESC LIMIT 1`,
[customerId]
);
if (recentApprovals.length > 0) {
await sendMessage({ to: from, message: 'Draft already approved by a group member — tracking link is live.' });
return;
}
await sendMessage({ to: from, message: 'No pending drafts right now. New ones arrive on Monday.' });
return;
}
Fan-out (for the weekly cron — not in scope here)
When src/pilot/cron.ts is built, the fan-out send looks like:
const [participants] = await pool.query<RowDataPacket[]>(
`SELECT phone_e164 FROM pilot_participants
WHERE customer_id = ? AND opted_in_at IS NOT NULL AND opted_out_at IS NULL`,
[customerId]
);
for (const row of participants) {
await sendMessage({ to: row.phone_e164, message: draftText });
}
Code Quality Notes
Files touched for this feature:
| File | Change |
|---|---|
src/migrations/YYYYMMDD_add_pilot_participants.sql |
New. CREATE TABLE + index. |
src/webhooks/twilio-whatsapp.ts |
Modified. ~20 line net change. |
src/webhooks/twilio-whatsapp.test.ts |
Modified. 2 mock updates + 7–8 new tests. |
src/index.ts — no change. Route registration is already one thin app.post line.
What to remove from twilio-whatsapp.ts:
CustomerRowinterface (lines 47–49 in current code) — thepilot_owner_phonequery is gone, so this interface is orphaned.
Tests
Existing tests that need mock updates (2):
handleApproval — non-allowlist sender rejected: currently mockspool.queryreturning{ pilot_owner_phone: null }. Change to mock returning 0 rows frompilot_participants.handleApproval — approval with tracking link: currently mockspool.queryreturning{ pilot_owner_phone: '+19548710505' }. Change to mock returning 1 row frompilot_participants.
New tests to add (7–8):
| # | Scenario | Expected |
|---|---|---|
| 1 | Opted-in participant replies "1" — baseline multi-sender | Draft approved, tracking link sent |
| 2 | Second participant replies "1" after first approval | "Draft already approved by a group member" message sent, no double-publish |
| 3 | Opted-out participant (opted_out_at IS NOT NULL) replies "1" |
Rejected as non-allowlist (same as unknown sender) |
| 4 | New phone texts in for first time | autoEnrollParticipant INSERT fires, no crash |
| 5 | Already-enrolled phone texts again | INSERT is idempotent (ON DUPLICATE KEY no-op), no duplicate row |
| 6 | autoEnrollParticipant DB error |
Approval flow continues, error logged, no 500 |
| 7 | No pending drafts + no recent approvals | "No pending drafts right now" message (unchanged behavior) |
| 8 | No pending drafts + recently-approved row | "Draft already approved" message, not the Monday message |
Total after changes: ~25–26 tests.
Performance
No concerns at lodge scale (5–50 members).
pilot_participantsallowlist check: 1 indexed query, effectively O(1)- "Already approved" check: 1 additional query, only in the no-pending-drafts branch
autoEnrollParticipant: INSERT IGNORE on every message — if this ever matters at higher volume, a Redis membership cache (SET NXper phone) can front it. Not needed now.
Open Questions (carried forward from original spec)
-
Spike: Option 1 viability. Can a number be added as a Conversations Participant and receive messages before it has messaged +1 954-738-5805? If Meta allows business-initiated adds via pre-approved template, Option 1 buys real value (true shared thread). 0.5-day spike, run before committing to Option 1 build.
-
Approval policy. First-reply-wins is the default here (existing Redis dedup + "already approved" branch). Designated-approver and majority-vote are deferred.
-
Single conversation vs. per-chapter. Option 2 supports this naturally — multiple lodge chapters would each have their own
customerId, each with their ownpilot_participantsrows. No code change needed for multi-chapter. -
"STOP" opt-out keyword. The
opted_out_atcolumn is designed for it. Handler not in scope here — text "STOP" currently falls through as an unrecognized reply ("Reply 1, 2, or 3..."). Safe to leave for now.
Effort Estimate
| Piece | Estimate |
|---|---|
| Migration: CREATE TABLE pilot_participants | 15 min |
handleApproval allowlist change + CustomerRow removal |
30 min |
autoEnrollParticipant function + wire-up |
30 min |
| "Already approved" UX branch | 30 min |
| Test mock updates (2 existing) + 7–8 new tests | 1.5–2 hr |
| Total | ~4 hours |
Compare: Option 1 would have been 2.5–3 days + 0.5-day spike.
NOT in Scope
- Fan-out send in
src/pilot/cron.ts— cron is a separate build; this review covers inbound/approval only - Facebook publish wire-up — separate task
- "STOP" opt-out keyword handler
- Conversations API (Option 1) — deferred until spike confirms Meta opt-in mechanics
- Any change to the existing 1:1 Alex Ferrari flow — stays as-is, group support is strictly additive
Implementation Handoff (copy-paste ready)
If handing to a separate agent:
Implement lodge group messaging (Option 2, fan-out 1:1) in
hermes-mcp. Full spec in[[2026-06-11-whatsapp-group-messaging-spec]], review decisions in[[2026-06-11-whatsapp-group-messaging-eng-review]].Four changes to
src/webhooks/twilio-whatsapp.ts:
- Replace
CustomerRowinterface +pilot_owner_phonequery (lines 47–74) with aSELECT 1 FROM pilot_participants WHERE customer_id = ? AND phone_e164 = ? AND opted_in_at IS NOT NULL AND opted_out_at IS NULLcheck.- Add
autoEnrollParticipant(customerId, phone)— INSERT INTO pilot_participants ... ON DUPLICATE KEY UPDATE opted_in_at = opted_in_at. Call it inhandleTwilioWhatsAppafter Redis customerId lookup, beforehandleApproval.- Add "already approved" branch in the
drafts.length === 0path — querypost_drafts WHERE status = 'approved' AND approved_at > NOW() - INTERVAL 24 HOURand send "Draft already approved by a group member" if found.- Write migration:
CREATE TABLE pilot_participants (id VARCHAR(36) NOT NULL DEFAULT (UUID()), customer_id VARCHAR(255) NOT NULL, phone_e164 VARCHAR(20) NOT NULL, opted_in_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, opted_out_at DATETIME NULL, INDEX idx_participant_lookup (customer_id, phone_e164)).Update
twilio-whatsapp.test.ts: fix 2 existing mocks (pilot_owner_phone → pilot_participants), add 8 new tests covering multi-sender approval, auto-enroll, opted-out rejection, "already approved" UX, and idempotent re-enrollment.Do NOT touch
src/index.ts. Do NOT droppilot_owner_phonefrom the customers table. Follow the migration file style from[[2026-06-09-mysql-backed-tracking-links]].