# Engineering Review — Lodge Brothers Beta **Date:** 2026-06-09 **Status:** COMPLETE **Related:** [[2026-06-09-lodge-brothers-beta-design]], [[2026-06-09-marketplace-release-checklist]], [[Platform Setup Guide]] --- ## Overview Engineering review of the Lodge Brothers Beta design doc (`garfield-main-design-20260608-151238.md`). Three new flows: AI Content Drafting, UTM Click Tracking, Lead Dashboard. **Stack:** TypeScript, Express, MySQL, Redis, `@anthropic-ai/sdk@0.96` (already installed) --- ## Step 0 — Scope Challenge ### What already exists and can be reused directly | Needed by design | Existing code | Location | |---|---|---| | Anthropic API client | `@anthropic-ai/sdk ^0.96.0` already in deps | `package.json` | | Facebook posting | `createPost(args, customer?)` | `src/clients/facebook.ts:114` | | Instagram posting | `createImagePost(args, customer?)` | `src/clients/instagram.ts` | | WhatsApp send | `sendMessage()`, `sendTemplate()` | `src/clients/whatsapp.ts` | | Inbound WhatsApp routing | `routeWhatsAppWebhook()` + `handleInboundWhatsAppMessage()` | `src/multitenancy/webhook-router.ts`, `src/index.ts:1307` | | Auth for dashboard | `requireAuth` (JWT cookie, Bearer, API key) | `src/index.ts:362` | | Slack alerts | `postToSlack()` + existing alert functions | `src/notifications/slack.ts` | | Schema migrations | `ensureColumn()` + `CREATE TABLE IF NOT EXISTS` | `src/db.ts:10` | | Redis distributed lock for cron | `COMPARE_DELETE_LUA` + Redis `SET NX EX` | `src/billing/cron.ts` | | In-process scheduling | `setInterval` pattern | `src/email-poller.ts:38` | **Minimum new files:** 2 — `src/pilot/cron.ts` + inline extension of `src/index.ts`. No new framework, no new dependency. --- ## Section 1 — Architecture ### Three independent flows **Flow A: Weekly Draft Generation** ``` main() → startPilotDraftCron() setInterval(nextMonday0800UTC, WEEK_MS) src/pilot/cron.ts: runDraftCron() ├── Redis SET draft:cron:lock NX EX 3600 ├── getPool().query("SELECT id, industry, location FROM customers │ WHERE pilot_active = 1 AND pilot_paused = 0") ├── for each tenant: │ ├── getPosts({limit: 5}, customer) [last 5 posts for context] │ ├── Anthropic().messages.create(...) → 3 draft objects │ ├── INSERT post_drafts (draft_text_social, draft_text_wa, status='pending') │ └── sendTemplate(pilot_owner_phone, 'lodge_approval', ...) [Meta Cloud API] └── redis COMPARE_DELETE lock ``` **Flow B: Approval + Publish** ``` POST /webhook/whatsapp (Meta Cloud API format) ├── HMAC verify ├── res.status(200).send('EVENT_RECEIVED') [always ack first] └── routeWhatsAppWebhook(body) → RoutedWebhookEvent[] ↓ handleInboundWhatsAppMessage(event) ├── isPilotApproval(event)? │ ← event.message.from === customer.pilot_owner_phone │ ← event.message.text.body in ["1","2","3"] ├── SELECT post_drafts WHERE customer_id=? AND status='pending' │ ORDER BY created_at DESC LIMIT 3 ├── UPDATE post_drafts SET status='approved', approved_at=NOW() │ WHERE id=? AND status='pending' ← idempotency guard ├── if affectedRows === 0: skip (duplicate reply) ├── token = crypto.randomBytes(6).toString('base64url') ├── redis.set(utm:{token}, {tenant_id, draft_id, destination_url}, EX 7776000) ├── createPost({message: draft_text_social + utm_link}, customer) [FB] ├── createImagePost({caption: ...}, customer) [IG] └── on error: UPDATE status='publish_error' + postToSlack(...) on success: sendMessage(pilot_owner_phone, "Posted! Clicks: /t/{token}") ``` **Flow C: UTM Redirect + Dashboard** ``` GET /t/:token ├── redis.get(utm:{token}) → {tenant_id, draft_id, destination_url} ├── if null → 404 ├── if bot (User-Agent regex) → 302, skip INCR ├── redis.incr(utm:clicks:{tenant_id}:{draft_id}) ├── redis.zAdd(utm:timeline:{tenant_id}, {score: Date.now(), value: draft_id}) └── res.redirect(302, destination_url) GET /dashboard (requireAuth) ├── customer = req.customer ├── SELECT id, draft_text_social, created_at, status, approved_at │ FROM post_drafts WHERE tenant_id=? ORDER BY created_at DESC LIMIT 30 ├── pipeline = redis.multi() │ for each draft: pipeline.get(utm:clicks:{tenant_id}:{draft_id}) │ results = await pipeline.exec() └── res.send(renderDashboardHtml(drafts, clickCounts)) ``` ### Data model additions (inline in `initDatabase()`, not a separate migration file) ```sql -- New table CREATE TABLE IF NOT EXISTS post_drafts ( id INT AUTO_INCREMENT PRIMARY KEY, tenant_id VARCHAR(255) NOT NULL, draft_text_social TEXT NOT NULL, draft_text_wa TEXT NOT NULL, destination_url VARCHAR(512) NULL, utm_token VARCHAR(32) NULL, status ENUM('pending','approved','rejected','expired','publish_error') DEFAULT 'pending', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, approved_at TIMESTAMP NULL, INDEX idx_tenant_status (tenant_id, status), INDEX idx_tenant_created (tenant_id, created_at) ) -- ensureColumn additions to customers table pilot_active TINYINT(1) DEFAULT 0 pilot_paused TINYINT(1) DEFAULT 0 pilot_end_date DATE NULL pilot_owner_phone VARCHAR(32) NULL -- Alex's personal WA number for approval auth industry VARCHAR(128) NULL location VARCHAR(128) NULL ``` --- ## Section 2 — Code Quality: 5 Issues ### Issue 1 — `handleToolCall` must NOT be used for internal publish actions ⚠️ HIGH The design calls `handleToolCall('facebook_create_post', ...)` on approval. `handleToolCall` runs `checkLimit()` billing enforcement (`src/tools.ts:812`). A pilot tenant's approved post being blocked by a billing limit is a silent failure that kills the product for Alex. Call the client functions directly: ```typescript // ❌ Design says this: await handleToolCall('facebook_create_post', { message, link }, customer); // ✅ Do this instead: import { createPost } from '../clients/facebook.js'; import { createImagePost } from '../clients/instagram.js'; await createPost({ message: draft.draft_text_social, link: utmUrl }, customer); await createImagePost({ caption: draft.draft_text_social }, customer); ``` ### Issue 2 — WhatsApp send path: must use Meta Cloud API, not Twilio ⚠️ HIGH The approval message goes from SquareMCP → Alex via WhatsApp. Alex replies "1". The existing `/webhook/whatsapp` is wired for Meta Cloud API format (`body.object === 'whatsapp_business_account'`). There is NO Twilio inbound webhook endpoint in this codebase. If you send via Twilio (`isTwilioAccount('default') === true` in `whatsapp.ts:12`), Alex's reply routes back through Twilio's format — a different endpoint that doesn't exist. The reply is silently dropped. Fix: the approval `sendTemplate()` call must use Alex's connected Meta credentials (stored via `storeCredential`), not the Twilio dev path. Pass `customer` to `sendTemplate()` — the function already handles this. ### Issue 3 — Missing `pilot_owner_phone` means any "1" reply triggers a publish ⚠️ HIGH The approval handler routes by `phone_number_id` (SquareMCP's number) → `customerId`. If any of Alex's clients sends "1" to that same number, it fires an approval. Fix: add `pilot_owner_phone` to `customers` (in schema above). Gate the handler on `event.message.from === customer.pilot_owner_phone`. ### Issue 4 — `migrations/` pattern conflicts with existing schema approach ⚠️ MEDIUM The design specifies a file in `migrations/YYYYMMDD_add_post_drafts.sql`. The codebase has no `migrations/` directory and no migration runner. Adding a `.sql` file with no runner is dead code. Use `CREATE TABLE IF NOT EXISTS` + `ensureColumn()` inside `initDatabase()` in `src/db.ts`. This is idempotent, test-friendly, and consistent with all 5 existing tables. ### Issue 5 — Cron scheduling: no external trigger exists ⚠️ MEDIUM `billing/cron.ts` defines `runInvoiceCron()` but it is **never called** anywhere — not in `main()`, not in `index.ts`. The design's "Weekly cron" has the same gap. The working pattern is `setInterval` inside `main()` (see `startEmailPoller`). Use the same: ```typescript // src/pilot/cron.ts export function startPilotDraftCron(): void { const msUntilNextMonday = computeNextMonday0800UTC(); setTimeout(function tick() { runDraftCron().catch(err => console.error('[pilot-cron] error:', err)); setTimeout(tick, 7 * 24 * 60 * 60 * 1000); }, msUntilNextMonday); } ``` --- ## Section 3 — Tests The test suite (vitest) already covers the cron Redis lock pattern, billing middleware, credential store. Pattern: mock Redis and DB with `vi.mock()`, test through the exported function. **New coverage needed:** ``` src/pilot/cron.test.ts ✓ Redis lock prevents double-run ✓ Claude API error → status=error, Slack alert, no crash ✓ Drafts INSERT'd with status='pending' for each active pilot tenant ✓ sendTemplate called once per tenant with correct phone + draft preview src/pilot/approval.test.ts ✓ Reply "1" approves first pending draft ✓ Reply "2" approves second pending draft (correct index) ✓ Reply "4" → no-op (invalid) ✓ Duplicate "1" reply → affectedRows=0 → no double-publish (idempotency) ✓ Reply from non-pilot-owner phone → no-op ✓ Publish error → status=publish_error + Slack alert fired src/utm.test.ts ✓ Valid token → 302 to destination, click counter incremented ✓ Bot UA → 302 redirect, counter NOT incremented ✓ Unknown token → 404 ✓ Expired token (TTL gone) → 404 ``` **Coverage gap:** `src/clients/facebook.ts` and `src/clients/instagram.ts` have zero test coverage. The most dangerous failure is a silent publish error (post_id returns empty string, status never set). Add at minimum one happy-path + one error-path test for `createPost`. --- ## Section 4 — Performance **Weekly draft cron — Claude API latency:** - 1 pilot tenant: ~2-5s per call, fine - 10 tenants sequential: ~20-50s, fine within 1-hour Redis lock TTL - 50+ tenants: use `Promise.allSettled` in batches of 5 Mark as TODO comment in cron file. No premature abstraction needed for v1. **Dashboard Redis reads:** Use a pipeline from day one — collapses 30 round-trips to 1: ```typescript const pipeline = redis.multi(); for (const draft of drafts) { pipeline.get(`utm:clicks:${customerId}:${draft.id}`); } const results = await pipeline.exec(); ``` **UTM redirect:** Redis `GET` + `INCR` + `ZADD` adds ~1ms. No concern. --- ## Required Outputs ### NOT in scope (hold the line) - Scheduling / calendar view for posts - Platform analytics API (Instagram Insights, etc.) - LinkedIn, TikTok, Twitter, Telegram, Discord for Alex - WhatsApp client broadcast to Alex's contact list (week 4) - Lead intake form hosted by SquareMCP - `timezone` field on customers (UTC for v1) ### What already exists (do not rebuild) - Facebook post client (`clients/facebook.ts`) - Instagram post client (`clients/instagram.ts`) - WhatsApp send + template (`clients/whatsapp.ts`) - Inbound WhatsApp webhook routing (`multitenancy/webhook-router.ts`) - Slack alert infrastructure (`notifications/slack.ts`) - Redis singleton + distributed lock pattern - `requireAuth` middleware - `@anthropic-ai/sdk` (already installed) ### TODOs before week 1 with Alex - [ ] **Confirm Alex has a Facebook Page (not personal profile)** — hard block before any code - [ ] Add `ANTHROPIC_API_KEY` to `hermes-k8s.yaml` - [ ] Confirm `SLACK_PILOT_WEBHOOK_URL` env is set (already used in slack.ts) - [ ] Confirm which WhatsApp number Alex will use for approvals → set `pilot_owner_phone` - [ ] Pre-approve one Meta utility template: "Your 3 posts are ready: reply 1, 2, or 3" ### Failure modes | Failure | Impact | Mitigation | |---|---|---| | Claude API down on Monday | No drafts generated, Alex hears nothing | `status=error` + Slack alert to admin | | Alex doesn't reply in 72h | Drafts expire, pilot clock ticks with no posts | `status=expired` + Slack inactivity alert | | Facebook publish fails after approval | Alex approved, post never went out | `status=publish_error` + Slack + reply to Alex | | Duplicate "1" reply (WA delivers twice) | Two identical posts published | Idempotency guard: `affectedRows === 0` check | | Wrong person sends "1" | Unauthorized publish | `pilot_owner_phone` gate | | Redis down | UTM clicks not counted | Catch Redis error, `302` redirect still works | ### Implementation order ``` Day 1 (parallel): A) Schema changes: post_drafts + pilot columns in db.ts [30 min] B) UTM redirect GET /t/:token + Redis storage [1 h] Day 2 (parallel): A) src/pilot/cron.ts: Claude API + draft INSERT + send WA [3 h] B) Approval handler: extend handleInboundWhatsAppMessage [2 h] Day 3 (parallel): A) Dashboard GET /dashboard: server-rendered HTML + pipeline [2 h] B) Tests: cron.test.ts + approval.test.ts + utm.test.ts [2 h] Day 4: Wire into main() + K8s env vars + end-to-end test with real WA [2 h] ``` Schema (Day 1A) is the only hard dependency. Everything else is independent. --- ## Bottom Line The infrastructure reuse is higher than the spec implies — you're wiring 3 flows on top of working clients and auth, not building from scratch. The 5 issues above are pre-empt problems (silent publish failures, wrong sender triggering publishes, dead migration files). Fix them before Alex sees the product. The biggest non-code risk remains unchanged: **call Alex this week** before writing any of this.