Email Orchestration Workflow (EML)¶
Module Purpose: The central nervous system of the platform. It continuously connects to mailboxes (Outlook/Gmail/IMAP), extracts intent from unstructured emails using AI, and routes them to the correct workflow (Sales, ERP, or Support).
[!NOTE] Philosophy: "No Email Left Behind." Every incoming email must either be converted to a Lead, linked to an Order, or explicitly archived. Zero inbox is the goal. Work/Life Guardrail: System must strictly differentiate between Work, Personal, and System noise (OTPs) to prevent cluttering the Kanban board.
Use Case Quick Reference¶
| ID | Title | Priority |
|---|---|---|
| US-EML-001 | Monitor Email Mailboxes | P1 |
| US-EML-002 | Contextual AI Triage | P1 |
| US-EML-003 | Automated Stream Routing | P1 |
| US-EML-004 | Create Lead from Email | P1 |
| US-EML-005 | Link Email to Existing Lead | P1 |
| US-EML-006 | Track Quote Milestone | P1 |
| US-EML-007 | Lookup Order in ERP | P1 |
| US-EML-008 | Set Dispatch Priority Flag | P1 |
| US-EML-009 | Send Dispatch Confirmation | P1 |
| US-EML-010 | Assign Task ID to Email | P1 |
| US-EML-011 | Update Task Status | P1 |
| US-EML-012 | Send Escalation Alert | P2 |
| US-EML-013 | Multi-Entity Validation | P1 |
| US-EML-014 | Pincode Route Planning | P2 |
| US-EML-015 | Campaign Result Tracking | P2 |
| US-EML-016 | Outlook-to-Salesforce Push | P2 |
| US-EML-017 | Entity-Centric Mail Threading | P2 |
US-EML-001: Monitor Email Mailboxes¶
What It Does¶
Continuously polls connected mailboxes (Outlook 365, Gmail, IMAP), fetches new emails, downloads attachments, and pushes them into the central processing queue.
Alpha Pebble Playbook: Activity-Stream Engineering. Every incoming email is treated as an immutable event in the global business stream, ensuring zero data loss and perfect auditability.
Who: System Background Worker
When: Continuous (24/7)
How It Works¶
- Poll: Worker wakes up every 30s.
- Fetch: Connects via OAuth2/IMAP. Queries
UNSEENmessages. - Sorbet Strategy (Sync):
- When categorized, the automation immediately moves the email out of the Inbox into a specific subfolder (e.g.,
Finance / Pending). - The email is kept Unread in that subfolder.
- The Outlook unread count serves as a "Parallel Task indicator" alongside the Kanban board.
- Enqueue: Pushes to
processing_queue.
Edge Cases¶
Token Expiry: Automatically refreshes OAuth tokens.
Giant Attachment: > 25MB flags a StorageExceeded event in the stream for manual handling.
US-EML-002: Agentic Email Triage (AI)¶
What It Does¶
The "Traffic Cop" of the enterprise. Analyzes incoming email content to determine the correct operational or sales stream.
AI Methodology: Agentic Triage (LangGraph) Unlike simple linear classification, this module employs a directed acyclic graph (using the LangGraph pattern) to manage multi-step reasoning: 1. Semantic Extraction: Extracts intent, sender context, and product relevance. 2. Self-Correction Loop: The AI reviews its own initial classification against industrial business rules to ensure accuracy. 3. Context Validation: Verifies against the CRM/Master data to distinguish between new signals and ongoing threads. 4. Shadow Learning (The "Why?" Loop): - For low-confidence moves, the system triggers a "Why?" questionnaire upon human override. - Collecting these "Why" reasons builds the baseline for Phase 2 Thresholding.
Hierarchical Triage (2-Level)¶
To ensure accountability while leveraging central oversight, triage follows a two-tiered hierarchy:
- Level 1: Global Ingestion Triage (The "Air Traffic Controller")
- Target: All incoming emails that AI cannot classify with >90% confidence.
- Queue: Global Unclassified Queue.
- Action: Administrator or centralized controller identifies the Stream (Sales, Logistics, Tender).
-
Goal: Clean the intake and ensure every email has a home department.
-
Level 2: HOD Distribution Triage (The "Department Head")
- Target: Emails already assigned to a specific Stream (e.g., "Sales").
- Queue: HOD Pending Queue (within the Stream).
- Action: The HOD of that department (e.g., Sales Manager) sees the "New" arrivals and:
- Assigns to a Rep (Staff A, Staff B).
- Re-routes back to Global if the stream was wrong.
- Sets Priority (P0, P1).
- Goal: Tactical workload distribution and final verification of intent.
Who: System AI Engine + Human HOD
When: Immediately after Ingestion
Technical Implementation (Rule-Based)¶
- Normalization: System extracts "Clean Text" (strip HTML, remove "Re:/Fwd:" prefixes) from subject and body.
- Keyword Match:
- CRM_KEYWORDS: quote, pricing, inquiry → Set
metadata.stream = 'CRM',metadata.category = 'Enquiry'. - ERP_KEYWORDS: dispatch, tracking, invoice, PO → Set
metadata.stream = 'ERP',metadata.category = 'Logistics'. - TENDER_KEYWORDS: tender, bid, RFP, EOI → Set
metadata.stream = 'Tender',metadata.category = 'Tender Alert'. - Noise/Personal Filter:
- SYSTEM: OTP, login code, verification → Set
metadata.stream = 'Ignore',metadata.category = 'System'. - PERSONAL: bank, movie, dinner, personal (if from personal-tagged domains) → Set
metadata.stream = 'Ignore',metadata.category = 'Personal'. - GREETINGS: Happy Birthday, Anniversary, Festival → Set
metadata.stream = 'Archive',metadata.category = 'Greetings'. - Fallback: If both or neither match, set
metadata.stream = 'CRM',metadata.category = 'Needs Triage'.
Detailed Acceptance Criteria (LLM Intent Extraction)¶
- For all newly ingested emails, system calls LLM with Subject + Body (max 2000 chars).
- JSONB Response Structure includes
confidence_score. - HITL Feedback: If user rejects a suggested classification, UI MUST prompt for "Why?".
- 2-Level Routing: System MUST support moving cards between "Global Unclassified" and "Department Pending" buckets.
- Just This Once: Provide a toggle to exclude a specific move from the training set (Edge case handling).
- Fail-Safe: In case of LLM failure/timeout, the system MUST fallback to the default triage category.
US-EML-003: Automated Stream Routing (AI)¶
What It Does¶
Maintains system high-throughput by automatically routing emails to the correct functional board (Kanban) or archiving non-operational noise. This ensure that users only interact with high-value signals while maintaining a complete audit trail in the Activity Stream.
Who: System AI Engine
When: Post-Classification
How It Works¶
- Master Sheet Lookup: Scans the Decision Matrix (Intent → Action → Steps) to find deterministic matches.
- Action Automation: Executes the "Series of Actions" defined in the sheet (Log to Plane, Tag Developer, etc.).
- Sorbet Flip: Once task is "Done" in Plane.so, system marks email as Read in Outlook and moves to Archive.
Detailed Acceptance Criteria¶
- Regex Extraction: Identify Order IDs (e.g.,
PO-1234) and link them to the ERP stream. - Activity Linking: If match found and contact has an "Active" Ticket: Link email as a new
Activityand setmetadata.linked_entity_id. - Latency Goals: Keyword rules MUST execute in <100ms; LLM calls target <3s.
Edge Cases¶
Ambiguous Email: "Where is my order?" (Could be Complaint or Status Check). Logic: Default to CRM Complaint for human review if sentiment is negative.
US-EML-004: Create Lead from Email¶
What It Does¶
Auto-generates a "Prelead" record from a raw email. It scrapes the sender's info, company signature, and product interest to pre-fill the form, saving the rep 5 minutes of data entry. If the sender is verified as a non-existent corporate entity, the system auto-creates a New Customer Shell in the CRM Master.
Who: System
When: Classification = Enquiry
How It Works¶
- Scraping:
- Sender: Use
Fromheader. - Company: Extract from
@domain.comor Email Signature text. - Phone: Regex scan signature for
+91... - Product: NLP keyword extraction from body ("Zinc Oxide", "Titanium").
- Creation:
- Inser into
preleadstable. - Status:
New. - Source:
Email Inbound. - Snapshot: Saves HTML rendering of email as a static image/file attached to the lead for audit.
Success Signals¶
✅ Pre-fills 80% of fields accurately.
✅ Captures Email Signature details (Phone/Designation).
US-EML-005: Link Email to Existing Lead¶
What It Does¶
Prevents duplicates. Checks if the sender john@apple.com already exists in the CRM. If yes, it logs this email as an "Activity" on John's timeline instead of creating a new Lead.
Who: System Dedupe Engine
When: Before creating new lead
How It Works¶
- Lookup: Query
contactstable by Email Address. - Match Found:
- Add Email to
activitiestable linked to Contact ID. - Bump "Last Interaction" timestamp.
- Notify Account Manager: "New email from John".
- Thread Check: If subject matches previous thread, attach to existing Ticket/Opp.
- No Match: Proceed to US-EML-004.
US-EML-006: Track Quote Milestone¶
What It Does¶
Monitors the "Quote Sent" SLA. If a lead requested a quote but none was sent within 24 hours, it flags the manager.
Who: System Watchdog
When: Periodic Check
How It Works¶
- Trigger: Card moved to "Quote Requested" column.
- Timer: Starts 24h countdown.
- Check: Has a file been uploaded to "Quotations" tab?
- Breach: If Timer > 24h and No Quote:
- Turn Card Red.
- Send Email to Team Lead.
US-EML-007: Lookup Order in ERP¶
What It Does¶
For ERP-stream emails, it acts as a bridge. It takes the specific Order ID mentioned in the email and calls the ERP API to fetch live status (e.g., "Packed", "Shipped").
Who: System Connector
When: Stream = ERP
How It Works¶
- Extraction: Identify
ORD-2023-001. - API Call: GET
/erp/orders/ORD-2023-001. - Enrichment:
- Add "Order Status: Shipped" tag to the email card.
- Display "Expected Delivery: 12th Jan" on the card face.
US-EML-008: Set Dispatch Priority Flag¶
What It Does¶
Allows a Sales Rep to mark an order as "Urgent" directly from the email interface. This pushes a priority flag to the Warehouse ERP view.
Who: Sales Rep
When: Manual Action (Card Button)
How It Works¶
- User Action: Clicks "Mark Urgent Dispatch" on email card.
- System:
- Updates CRM Task Priority = High.
- API Push: Updates ERP Order
priorityfield. - Notify: Slack message to Warehouse Manager.
US-EML-009: Send Dispatch Confirmation¶
What It Does¶
Closes the loop. When ERP marks order as "Shipped", system auto-sends the tracking details to the customer, replying to their original status enquiry thread.
Who: System Automation
When: ERP Status Change event
How It Works¶
- Trigger: ERP Webhook
order.shipped. - Compose:
- Template: "Your order {ID} has shipped via {Carrier}."
- Tracking URL: Generated dynamically.
- Send: Reply to last customer email thread.
- Close: Archive the enquiry card.
US-EML-010: Assign Task ID to Email¶
What It Does¶
Ensures every actionable email has a unique internal ID (e.g., TSK-9988) separate from the email ID, used for SLA tracking and ticketing.
Who: System
When: On Ingestion
How It Works¶
- Generate:
TSK-YYYY-{Sequence}. - Stamp: Save in database.
- Reference: Add to Email Subject in replies:
[Ref: TSK-9988]. This ensures future replies thread correctly.
US-EML-011: Update Task Status¶
What It Does¶
Syncs the visual Kanban status (e.g., "In Progress") with the underlying database record, ensuring reporting dashboards are accurate.
Who: System / User
When: Drag-and-drop event
How It Works¶
- Event: User drags card to "Done".
- Update: Set
status = Closed,completed_at = Now(). - Implicit Update (No-Touch): When a user sends a "Reply" (external) or "Reply All" (internal) from their Outlook/Pebble inbox, the system detects the intent (e.g., "PO Sent" or "Issue Resolved") and auto-updates the Kanban card status.
- Log: Record "User X closed task TSK-9988" in audit log.
US-EML-012: Send Escalation Alert¶
What It Does¶
The "Siren". If High Priority items sit untouched for > 4 hours, it notifies senior management.
Who: System Watchdog
When: Hourly Cron
How It Works¶
- Scan: Find cards where
Priority = HighANDLast_Activity > 4 hours. - Alert:
- Level 1 (4h): Email User.
- Level 2 (8h): Email Manager.
- Level 3 (24h): Email VP Sales.
US-EML-013: Multi-Entity Validation & Identity Triage¶
What It Does¶
Checks if the customer exists in any of the group companies using official identifiers (GST/PAN/CIN). Prevents creating "Acme Corp" in Entity A if it already exists in Entity B (unless intentional), or helps link them as Group Companies.
Who: System Validator
When: Lead Creation
Technical Implementation¶
- GST Extraction: System extracts 15-character GSTIN using regex from email body or dedicated field.
- Identity Verification: System calls
POST /api/verify/gst(via sandbox/mock API for POC). - Global Search: Query
customer_mastersacross ALL legal entity schemas using GSTIN. - Match Found: Set
metadata.duplicate_found = trueand record the Entity/ID. - Fuzzy Name Matching: If no GST found, calculate Jaro-Winkler distance (>0.8 threshold).
Detailed Acceptance Criteria¶
- UI displays badge: Green (Verified), Yellow (Name Mismatch), Red (Invalid).
- If duplicate found, card detail view shows "Duplicate Match Found" alert.
- Option [Link to Group]: Populates
group_parent_idin the new record. - Option [Create Independent]: Forces new local record with an audit warning.
- Zero "Silent" duplicates created when GST is present.
US-EML-014: Pincode-based Route Planning¶
What It Does¶
Helps field sales planning. When a rep visits a customer, system suggests "Nearby Leads" based on pincode proximity to maximize trip value.
Who: Sales Rep (Mobile App)
When: Planning visits
How It Works¶
- Input: Target Customer Pincode (e.g., 400001).
- Search: Find all Open Enquiries with Pincode within 5km radius.
- Display: List/Map view. "3 other leads near here."
US-EML-015: Campaign Result Tracking¶
What It Does¶
Closes the ROAS loop. Tracks how many inbound enquiries resulted from specific email/marketing campaigns.
Who: System Analytics
When: Enquiry Ingestion
How It Works¶
- Match: Check if sender email target was in a recent Outbound Campaign list.
- Tag: If yes, tag Lead Source = "Campaign: Q1 Promo".
- Attribute: If this lead converts to Order, attribute revenue to that Campaign ID.
US-EML-016: Outlook-to-Salesforce Push¶
What It Does¶
A manual plugin for Outlook. Allows users to "Right Click -> Push to Pebble" for emails that bypassed the auto-ingestion (e.g., personal inbox).
Who: User (Outlook Plugin)
When: Manual
How It Works¶
- Select: User highlights email in Outlook.
- Click: "Push to Pebble" button.
- Action: Plugin sends JSON payload (Body, Attachments) to Pebble Ingestion API
v1/ingest/email. - Feedback: Show "Success! Ticket #123 created."
US-EML-017: Entity-Centric Mail Threading¶
What It Does¶
Goes beyond standard reply-to headers. Uses Knowledge Graph data to link emails that don't share a thread ID but do share an Enterprise Entity (e.g., linking a new enquiry from a different person at the same company to the primary Company record).
Alpha Pebble Playbook: Enterprise Context Layer.
Who: System Background Processor
When: On Inbound Ingestion
How It Works¶
- Extraction: Identify Sender Domain and Company Signature.
- Graph Lookup: Query the Unified Semantic Index for shared identifiers (GSTIN, Domain, shared contacts).
- Association: If a high-confidence match is found with an existing Company Entity, the email is linked to that Entity's Activity Stream even if it's the first interaction with this specific sender.
- Visibility: Card appears on the Kanban Board with a "Group Connection" badge.
Metadata Schema (JSONB)¶
Every email and prelead stores its intelligence in a standardized metadata JSONB block:
{
"stream": "CRM | ERP",
"category": "Enquiry | Complaint | Logistics | Support",
"intent_tags": ["Sample_Req", "Price_Query"],
"sentiment": "Positive | Neutral | Negative",
"confidence_score": 0.0,
"identity": {
"gst_verified": true,
"duplicate_found": false,
"duplicate_entity": "Entity_B"
},
"threading": {
"parent_id": "UUID",
"is_reply": true
}
}
Traceability Map¶
- EML-001 Monitor Email Mailboxes -> Aligns with PRD: Email Orchestration UC-EML-001 and PRD US-EML-001 (CRM/ERP routing) in
tasks/prd-ai-email-classification.md. - EML-002 Classify Email to CRM Stream -> See PRD: AI Email Classification US-EML-002;
tasks/prd-ai-email-classification.md. - EML-003 Classify Email to ERP Stream -> See PRD: AI Email Classification US-EML-003;
tasks/prd-ai-email-classification.md. - EML-004 Create Lead from Email -> See PRD: AI Email Classification US-EML-004;
tasks/prd-ai-email-classification.md. - EML-013 Multi-Entity Validation -> See US-EML-013 above.