# Requirement traceability

Every BRD requirement mapped to where it is implemented and how to see it. Paths are relative to `src/`. Tests are in `tests/core.test.ts` (named by requirement ID).

Legend: **Live** = works against the real provider once credentials are connected · **Sandbox** = simulated provider for testing before app review.

## 3. Users & roles
| ID | Implementation | Where to see it |
|---|---|---|
| AUTH-001 | `lib/rbac.ts` (exact BRD matrix), roles table, clone/edit API in `api/handlers/admin.ts` | Settings → Roles & permissions |

## 6.1 Unified customer data
| ID | Implementation | UI |
|---|---|---|
| CDP-001 | `db/schema.ts` contacts/identities, `lib/services/contacts.ts` `timeline()` | Contact profile |
| CDP-002 | `upsertContact()` E.164 + email resolution, `mergeContacts()`/`undoMerge()` with `merge_logs` | Contact → Identities & merges |
| CDP-003 | `POST /v1/events`, `/v1/events/batch`, `app/t.js` snippet, `api/track/collect` stitching | Forms → Share & embed |
| CDP-004 | `consents` table, `canMessage()` enforced in `sendMessage()`, consent CSV export | Contact → Consent |
| CDP-005 | `custom_field_defs`, usable in segments/journeys/forms/API | Settings → Fields & objects |
| CDP-006 | `lib/services/segments.ts` SQL compiler, refresh every 4 min | Segments |
| CDP-007 | `custom_object_defs/records`, `/v1/custom-objects/*` | Settings → Fields & objects; contact “Linked records” |
| CDP-008 | `contacts/import` page (CSV/XLSX in browser, 500-row chunks), `lib/services/import.ts` preview + error report | Contacts → Import |
| CDP-009 | `exportContact()`, `deleteContact()` hard delete across modules | Settings → Privacy & data |

## 6.2 Integrations hub
| ID | Implementation |
|---|---|
| INT-001 | `connectors/*` + OAuth start/callback in `api/handlers/admin.ts`; tokens in `lib/vault.ts` (AES-256-GCM); Meta long-lived refresh, Google refresh token; expiry → alert + `integration.disconnected` |
| INT-002 | `integration_logs`, `connectors/http.ts` logs every call; health table, Sync now / Retry |
| INT-003 | `POST /v1/hooks/{workspace_key}/{source}` with Meta/Google/Stripe signature verification and optional HMAC for generic sources |
| INT-004 | `lib/webhooks.ts` HMAC-SHA256 `X-Signature`, retries 24 h, replay |
| INT-005 | Field mapping tab (Integrations → Manage), applied in `connectors/meta.ts` |
| INT-006 | Journey “HTTP request” action with templated URL/headers/body (`lib/services/journeys.ts`) |
| INT-007 | REST hooks (`/v1/webhooks` subscribe/unsubscribe), `/v1/me` auth test, actions via `/v1/leads`, `/v1/contacts/upsert`, `/v1/events`; Zapier/Make/n8n catalog entries |

## 6.3 Lead management
| ID | Implementation |
|---|---|
| LEAD-001 | `captureLead()` from Meta Lead Ads, Google lead forms, web forms, WhatsApp/Messenger inbound, generic webhook and `/v1/leads` |
| LEAD-002 | Configurable pipelines (Settings → Pipelines), drag-and-drop board, `POST /v1/deals/{id}/stage` |
| LEAD-003 | `routeLead()` round-robin / source / project / territory / workload + notification |
| LEAD-004 | `checkSla()` every minute: alert or reassign |
| LEAD-005 | Tasks with due dates, 15-min reminders, Google Calendar push job |
| LEAD-006 | Activity logging; Twilio click-to-call with recording callback → timeline + AI summary |
| LEAD-007 | `changeStage()` validation + stage sheet in UI |
| LEAD-008 | `changeStage()` → `queueConversions()` |

## 6.4 Journeys
| ID | Implementation |
|---|---|
| FLOW-001 | All 8 triggers + manual (`TRIGGERS` in `journeys.ts`); date-based in daily cron |
| FLOW-002 | Condition node (segment rule engine), A/B split node |
| FLOW-003 | send message, assign, update field, add/remove tag, create task, wait, HTTP request, notify team, move stage, start AI agent |
| FLOW-004 | React Flow canvas `app/(app)/journeys/[id]`; immutable `journey_versions`; runs pinned to version |
| FLOW-005 | Goal config + `checkGoals()` on stage/tag/event |
| FLOW-006 | Per-node entered/completed/failed counters on canvas; Execution log tab |
| FLOW-007 | `quietHoursDelay()` + frequency cap in `sendMessage()`; deferred steps resume after quiet hours |

## 6.5 Messaging & inbox
| ID | Implementation |
|---|---|
| MSG-001 | `connectors/messaging.ts` WhatsApp Cloud API; 24-h window + approved-template enforcement; inbound threading |
| MSG-002 | SES (SigV4) / SendGrid, open pixel + click redirect, bounce/complaint suppression |
| MSG-003 | BD gateway (unicode detection) + Twilio, DLR webhooks, provider failover |
| MSG-004 | Messenger/Instagram via Meta connector |
| MSG-005 | Inbox: assignment, internal notes, canned replies, status, AI agent toggle |
| MSG-006 | Broadcasts to segments: schedule, throttle, consent/caps/quiet hours |
| MSG-007 | `renderTemplate()` `{{var|fallback}}`, live preview, AI drafting |

## 7.1 Ads
| ID | Implementation |
|---|---|
| ADS-001 | Meta, Google (P1), TikTok, LinkedIn (P2) connectors; multiple accounts with currency/timezone |
| ADS-002 | Daily sync in cron + manual Refresh; `ad_metrics_daily` hierarchy |
| ADS-003 | `lib/services/conversions.ts` — CAPI + Google `uploadClickConversions`, hashed IDs, fbc/gclid, dedupe by event_id |
| ADS-004 | `lead_sources` campaign/ad set/ad + fbclid/gclid, shown on contact Attribution card |
| ADS-005 | Ads command center + `campaignPerformance()` (CPL, cost/QL, cost/sale, ROAS) |
| ADS-006 | `checkPacing()` + monthly plan per account |
| ADS-007 | Segment audience sync (Meta Custom Audiences, Google Customer Match), daily |
| ADS-008 | Write actions only via approval queue; audit before/after with user or agent |

## 7.2 Content
| ID | Implementation |
|---|---|
| CNT-001 | Month/week/list calendar with drag-to-reschedule |
| CNT-002 | `publishDuePosts()` every minute, external post IDs logged |
| CNT-003 | draft → in review → approved → scheduled; `/approve/{token}` client link without login |
| CNT-004 | Asset library (folders/tags, upload or URL) + brand kit |
| CNT-005 | `syncPostMetrics()` daily |

## 7.3 Analytics
| ID | Implementation |
|---|---|
| ANL-001 | `funnel()` with filters date/source/campaign/project/rep |
| ANL-002 | First/last touch in `attribution()` |
| ANL-003 | Linear, time-decay (7-day half-life), position-based (40/20/40) — model switch recalculates |
| ANL-004 | Saved reports, PDF (`pdf-lib`), weekly Monday / monthly email |
| ANL-005 | White-label PDF and `/r/{token}` share page |
| ANL-006 | `repPerformance()` leaderboard |
| ANL-007 | GA4 Data API + Search Console on Analytics page |

## 7.4 Pages & forms
| ID | Implementation |
|---|---|
| PAGE-001 | Form builder; hosted `/f/{ws}/{slug}`, iframe embed, REST; hidden UTM/fbclid/gclid/anonymous id capture |
| PAGE-002 | Honeypot, min fill time, per-IP rate limit, Turnstile option, client + server phone validation |
| PAGE-003 | Block-based page builder `/p/{ws}/{slug}` |
| PAGE-004 | Custom domains via `middleware.ts` → `/d/{host}`; SSL by Vercel |
| PAGE-005 | Weighted variants, sticky cookie, conversion per variant + z-test confidence |
| PAGE-006 | Meta Pixel / GA4 / GTM injection, fire on page view and submit |

## 7.5 Admin
| ID | Implementation |
|---|---|
| ADM-001 | Agency → workspaces → memberships; every query scoped by `workspace_id`; isolation test |
| ADM-002 | Google SSO, bcrypt passwords, TOTP MFA, per-workspace enforcement |
| ADM-003 | `audit_logs` on all writes + integration actions; search by user/object/date; 1-year retention |
| ADM-004 | Plans, seats, usage meters, invoices; Stripe / SSLCommerz / bKash checkout + IPN |
| ADM-005 | Agency branding (logo, colour, product name, login domain), white-label reports |
| ADM-006 | Workspace timezone/currency (BDT/USD/AUD)/language (EN/BN) |
| ADM-007 | Scoped API keys (`tp_live_…`, SHA-256 hashed), enforced per route |

## 8. AI
| ID | Implementation |
|---|---|
| AI-001 | `generateContent()` 3–6 variants, EN/BN/both, brand voice |
| AI-002 | `agentReply()` tool-using agent (save_qualification, book_next_step, handoff_to_human); one-click takeover in Inbox |
| AI-003 | Per-workspace logistic regression on won/lost, weekly retrain, heuristic until minimum history |
| AI-004 | `detectAnomalies()` CPL/CTR/spend/leads vs 7-day baseline |
| AI-005 | `askData()` — model plans a safe query over a fixed metric catalogue; answer shows chart, query and metric definition (keyword fallback without a key) |
| AI-006 | `budgetRecommendations()` + `nextBestAction()` with reasoning & expected impact |
| AI-007 | `summarizeConversation()` / `summarizeActivity()` → `ai_summary` timeline entries |
| AI-008 | `ai_actions` approval queue, auto-approve rules with limits (admins only) |
| §8.2 rules | `lib/ai/gateway.ts`: provider-agnostic gateway (Anthropic SDK), credits metering, 24-h prompt cache, cheaper model for simple tasks, prompts/tool calls logged in `ai_logs`, consent checks before any send |

## 11. API & webhooks
`api/router.ts` route table → `/api/v1/*`, OpenAPI at `/api/v1/openapi.json`, human docs at `/docs/api`. Conventions (Bearer keys, Idempotency-Key, cursor pagination, `filter[...]`, X-RateLimit headers, error envelope) in `app/api/v1/[...path]/route.ts`. All 20 outbound event types in `lib/webhooks.ts`.

## 12. Non-functional
| ID | How it is addressed |
|---|---|
| NFR-001 | Workspace scoping on every query + isolation tests (RLS hardening path in DEPLOYMENT.md) |
| NFR-002 | TLS (Vercel), AES-256-GCM vault, HSTS/nosniff headers, no secrets in tables |
| NFR-003 | MFA + configurable session timeout |
| NFR-004/007 | Stateless serverless functions, queue-based background work |
| NFR-006/008 | Idempotent webhooks (external lead id, provider message id, conversion event id), retries with backoff, dead-letter + replay |
| NFR-010/011 | Consent records, export/deletion, TCPA opt-in for US SMS, STOP keywords, WhatsApp template rules, quiet hours |
| NFR-013 | Language switch (EN/বাংলা) per user and workspace — navigation and shared labels are translated in `lib/i18n.ts`; page body copy is English and is extended by adding keys there. Unicode/Bangla everywhere in data, SMS and AI; BDT/USD/AUD; per-workspace timezone |
| NFR-014/015 | Keyboard focus rings, labelled controls, responsive layouts down to 375 px (inbox & leads) |

## 13. Module 11 — Social inbox & engagement (SOC-*)
Extends the existing inbox, contacts, identity resolution, journeys, AI gateway/approval queue, webhooks and RBAC rather than duplicating them. Migration `drizzle/0001_social_inbox.sql` is additive only (no drops/renames). Provider endpoints are marked `VERIFY` in `connectors/social.ts`.

| ID | Implementation |
|---|---|
| SOC-001 | `social_accounts`; `discover()` lists Pages / IG / YouTube channels / GBP locations (sandbox + live); new accounts start inactive; Settings → Social inbox |
| SOC-002 | App-level `/api/meta/webhook` (verify token, X-Hub-Signature-256, 200 + enqueue, fan-out by page/IG id → workspace; WhatsApp by WABA id); per-workspace `/v1/hooks/:key/meta` also ingests comments & DMs |
| SOC-003 | Per-platform capability matrix (`CAPABILITIES`), enforced by `act()` before every call; shown on accounts |
| SOC-004 | `runBackfill()` 30 days on activation; historical items never fire rules or SLAs |
| SOC-005/006 | `pollAccount()` for YouTube, Google reviews, TikTok, LinkedIn; 30-min safety-net poll for Meta; `enqueuePolls()` in the worker cron |
| SOC-007 | `tokenHealth()` daily → account `disconnected`, admin alert, `social_account.disconnected` webhook |
| SOC-008 | Dedupe on (workspace, channel, external_comment_id); edits keep `edit_history`; platform removes/hides mirrored |
| SOC-009/010 | Thread grouping by parent comment (`external_thread_id`); the page's own comments recorded as outbound, never open conversations |
| SOC-011…013 | DMs keep using `conversations`/`messages` (`kind = dm`); comment threads (`comment_thread`) and reviews (`review`) share the same inbox, filters and SLAs |
| SOC-014/015 | `social_objects` (post/reel/video/ad) with caption, thumbnail, permalink; ads mapped to posts (`syncAdMap()` + `ads.external_id`) so ad comments show campaign context |
| SOC-020…022 | Inbox filter rail (views, type, channel, account, intent, tag, post), SLA timers, kind badges, post thumbnails, counts (`/inbox/counts`), SSE `/api/inbox/stream` |
| SOC-023 | Assign (manual, round-robin by team skipping away agents), statuses open/pending/snoozed/resolved/closed |
| SOC-024 | Saved replies = extended `canned_replies` (title, variables, channels, language) via `/saved-replies`; `/` picker in every composer |
| SOC-025 | Internal notes with @mentions → notifications |
| SOC-026 | 2-minute soft lock (`lockConversation`), "X is replying" banner, take-over |
| SOC-027 | `POST /conversations/bulk` (assign/resolve/snooze/tag/hide/spam) |
| SOC-028 | Snooze with auto-wake (`socialMinute`) and reopen on new inbound |
| SOC-030/031 | Public reply (threaded) and private reply (one per comment, platform window, linked DM conversation) |
| SOC-032/033 | Hide/unhide, delete (confirm), like — all through `connectors/social.act()` |
| SOC-034 | Contact card: identities, deals, other conversations across channels, tags |
| SOC-035 | Move to WhatsApp: approved template when opted in, else click-to-chat link by private reply / DM |
| SOC-036 | Provider errors shown on the reply with Retry; token errors flag the integration and account |
| SOC-040/041 | Create lead from a comment/thread → `captureLead({contactId})`, attribution channel `facebook_comment` etc. + ad/campaign ids |
| SOC-042 | Phones/emails in comments/DMs attached to the contact (no consent implied) with identity-based merge |
| SOC-043/044 | Lightweight `social_engager` contacts per platform identity (`fb_psid`, `ig_scoped_id`, …); never matched by name |
| SOC-050…053 | `engagement_rules` (auto-reply, comment→DM, moderation, routing, AI, alert): conditions (keywords EN/BN/Banglish, intent, sentiment, rating, language, phone, link, profanity, competitor, contact field), 14 action types, reply variations rotated |
| SOC-054 | Rate limits: per minute, once per person per post, once per person per day |
| SOC-055 | Schedules: always / business hours / after hours (away replies) |
| SOC-056 | `/engagement-rules/test` dry run (classification + matched actions, nothing sent) |
| SOC-057/058 | Priority order, stop-processing, `rule_firings` log + per-rule stats; moderation evaluated before replies |
| SOC-060 | Google reviews with stars, owner reply publish/edit (`review_reply`) |
| SOC-061 | ≤2★ reviews → urgent + manager alert + AI draft to approvals; complaint and comment-spike alerts |
| SOC-062 | Built-in EN/Bangla/Banglish profanity list + workspace blocked words & competitor names; author blocklist |
| SOC-063 | `moderation_events` log with actor (user/rule/AI) and reason; undo hide; `/inbox/moderation` |
| SOC-070…073 | SLA policies per kind (dm 15m, comment 60m, review 24h; urgent ¼, high ½) in business hours; breach → priority, alert, `conversation.sla_breached`, optional reassign; availability & teams |
| SOC-080…084 | `engagementReport()` (volume, replied %, median/p90 first response, resolution, by channel/account/agent/day, sentiment over time, intents, top posts/ads with leads & won revenue, automation impact), CSV, daily rollup `engagement_metrics_daily`, "Social engagement" client-report section |
| SOC-090 | Capabilities `social`, `social_moderate`, `social_rules`, `social_ai`, `social_analytics` (+ API scopes `social:read/write/moderate`, `rules:write`); existing roles get defaults merged in |
| SOC-091 | `memberships.social_account_ids` restricts agents to specific pages (list, detail, reply, reports) |
| SOC-AI-001 | Rules-based classifier (`social-text.ts`: intent, sentiment, language en/bn/banglish, phones incl. Bangla digits, spam, toxicity) + async AI refinement via the gateway |
| SOC-AI-002…004 | `suggestReplies()` 2–3 suggestions grounded in the knowledge base, brand voice, thread and contact/deal; language matching (Banglish → Banglish or Bangla) |
| SOC-AI-005/006 | Autopilot with confidence threshold, allowed intents, public-reply switch; otherwise `social_reply` in the AI approval queue (editable before sending) |
| SOC-AI-007 | Summary note on resolve (`social.ai.summary`) |
| SOC-AI-008 | Review reply drafts always go to approval |
| SOC-AI-009 | Hand-off to a human on request or negative sentiment; one-click take-over |
| Guardrails | No prices/discounts absent from the KB (confidence capped), never public replies to complaints/legal threats, personal data scrubbed from public replies |
| Webhooks | `comment.received/replied/hidden/deleted`, `review.received/replied`, `conversation.assigned/resolved/sla_breached`, `engagement_rule.fired`, `social_account.disconnected` |
| Tests | `tests/social.test.ts` (17 acceptance tests) |

## 14. Industry packs (category-specific internal module)
`lib/industry.ts` defines 17 categories (9 service-based, 8 product & manufacturing) plus "Other". The industry is chosen at setup, when an agency creates a client workspace, or later in **Settings → General → Industry** (`POST /v1/workspace/industry`). Each pack sets:

| Area | What changes |
|---|---|
| Funnel | Industry pipeline stages (e.g. Banking: Contacted → Eligibility checked → Branch appointment → Application → KYC → Approval → Account opened). Stable ids `new/qualified/site_visit/won/lost` keep conversion mappings (Qualified, SiteVisit, Won) and the API unchanged |
| Lead fields | Category custom fields (e.g. Banking: product interest, amount, income band, KYC status) |
| AI | Agent role, qualification questions, next-best-action, content prompts, social replies; compliance guardrails for regulated categories (banking, healthcare, pharma): autopilot off, no public AI replies |
| Wording | Booked step (Site visit / Branch appointment / Test drive / Demo…), "Project" field label (Product, Service, Model…), examples, knowledge-base hints, Meta lead-form field samples |
| Starters | Knowledge-base questions (inactive until answered) and saved replies |
| SLA | Lead first-response target per category |
| Sandbox | Neutral sample campaigns and comments outside real estate |

`lib/services/industry.ts → applyIndustry()` is non-destructive: a pipeline with deals is kept and a new default pipeline is added; fields, starters and replies are only added when missing.

## 15. Account & data security
| Control | Implementation |
|---|---|
| Two-factor (every method) | `lib/security/mfa.ts`: passkeys & security keys (WebAuthn, `@simplewebauthn`), authenticator apps (TOTP — Google/Microsoft Authenticator, Authy, 1Password), SMS codes, email codes, 10 single-use backup codes, "trust this device" (hashed token, configurable days) |
| Code safety | TOTP secrets AES-256-GCM encrypted, each 30-s step usable once; email/SMS codes 6 digits, 10 min, 5 attempts, HMAC-hashed, 45-s resend cool-down, 8/hour cap; backup codes HMAC-hashed |
| Sign-in protection | Rate limits per IP+email, per IP and per user for codes; account lock 15 min after 8 wrong passwords; equal-time failure path; breached-password check; workspace minimum length; failed sign-ins and all 2FA events in the audit log; new-device email alerts |
| Workspace policy | Settings → Security policy: require 2FA, allowed methods, IP allowlist (IPv4/IPv6, CIDR, self-lock-out guard), password length, trusted-device days, session timeout, member 2FA coverage, unlock / reset 2FA / sign out members, security event log |
| Sessions | Server-side sessions (revocable), list and sign-out per device, sign out everywhere else; password change revokes other sessions and trusted devices |
| Web hardening | Same-origin check on every cookie-authenticated write (CSRF), SameSite=Lax httpOnly secure cookies, `X-Frame-Options`/`frame-ancestors` (embeddable forms exempt), `Permissions-Policy`, COOP, HSTS, nosniff; single-use invitations; Google sign-in state bound to a browser nonce |
| Data at rest | Integration secrets in the AES-256-GCM vault, API keys SHA-256 hashed, passwords bcrypt; Neon encrypts storage; workspace isolation tested (NFR-001) |
| Delivery | `lib/security/deliver.ts`: Resend / SendGrid / Twilio / any SMS gateway from env, else a live email/SMS integration of the user's workspace; development logs codes to the server console; production refuses to pretend |
| Tests | `tests/security.test.ts` (7) |
