Flow Myna

AI Integration

Use this prompt with Cursor, GitHub Copilot, or any AI coding assistant to integrate Flow Myna into your codebase. The AI will analyze your code, suggest what to track, and implement it step-by-step with your approval.

How It Works

1

AI Asks Questions

The AI will ask what process you want to track and if you have an API key. Answer these first.

2

Review Plan

The AI analyzes your codebase and presents a plan. No code changes until you approve.

3

Implement

The AI implements tracking step-by-step, confirming each change with you.

Copy the Prompt

Select your preferred SDK/language, then copy the prompt and paste it into your AI coding assistant.

# Flow Myna Integration Prompt

Help me integrate Flow Myna process mining into my application.

**IMPORTANT: YOU MUST ASK ME QUESTIONS FIRST. Do NOT analyze code or create a plan until I answer.**

---

## ABOUT FLOW MYNA

Flow Myna is a process mining platform that visualizes how work flows through your systems. It collects events that happen to objects in your business processes.

**Core concepts:**
- **EVENTS**: Activities that happen (e.g., "Order Placed", "Invoice Sent", "Ticket Resolved")
- **OBJECTS**: Business entities involved (e.g., Order, Customer, Invoice, Ticket)
- Each event links one or more objects together, building a process graph over time

**Example**: "Order Placed" links an Order object. Later, "Order Shipped" links the same Order. Flow Myna connects these to show the full order lifecycle.

---

## YOUR FIRST TASK: ASK ME THESE QUESTIONS

Before doing anything else, ask me:

1. **What process or workflow do you want to track?**
   (e.g., "order fulfillment", "support tickets", "invoice processing", "user onboarding")

2. **What is the PRIMARY OBJECT that flows through this process?**
   - This is the "case" or "instance" - each one represents a single run through the process
   - Examples: "each Order", "each Support Ticket", "each Loan Application", "each User Session"
   - This object should be created at the START of the process so ALL events can link to it
   - User identifiers (email, user_id) should typically be PROPERTIES on this object, not the object itself

3. **Do you already have a Flow Myna API key?** (If not, I'll tell you how to get one)

4. **Is there anything specific about your codebase I should know?**
   (e.g., "order logic is in src/services/orders.py", or just let me explore)

**STOP HERE. Ask these questions and wait for my answers before proceeding.**

---

## AFTER I ANSWER, YOU WILL:

1. **ANALYZE** my codebase to find where the process happens
2. **IDENTIFY THE OBJECT LIFECYCLE** - when is the primary object created? Ensure it's created at the START
3. **MAP THE PROCESS** - identify all steps AND branching points (see below)
4. **SUGGEST** specific events and objects to track
5. **PRESENT** a plan showing exactly what you'll add and where
6. **WAIT** for my approval before making any changes
7. **IMPLEMENT** the changes

---

## IDENTIFYING BRANCHING POINTS

Processes are rarely purely linear. Look for these branching patterns:

| Pattern | Example | How to Track |
|---------|---------|--------------|
| **Choice A vs B** | Pay with card vs Pay with PayPal | Track both as separate events with distinguishing properties |
| **Error/Failure** | Payment declined, validation failed | Track "Error Encountered" with error_type property |
| **Retry/Back** | User goes back to edit, retries action | Track "Step Back" or "Retry" with context |
| **Optional actions** | View details, apply coupon | Track when user engages |
| **Skip** | Skip optional step | Track "Step Skipped" |
| **Early exit** | Abandon cart, cancel, timeout | Track abandonment point |

**Ask yourself:**
- Where can the user make a choice?
- Where can things go wrong?
- Where might users hesitate or go back?
- What optional interactions show engagement?

---

## CRITICAL: OBJECT CREATION TIMING

**THE PRIMARY OBJECT MUST EXIST BEFORE ANY EVENTS ARE TRACKED.**

❌ **Wrong approach** (Order created mid-process):
```
Event: "Shopping Started" → linked to Customer (no Order yet)
Event: "Item Added" → linked to Customer (still no Order)
Event: "Checkout Started" → NOW creates Order
Event: "Payment Complete" → linked to Order
```
This creates disconnected events - some linked to Customer, some to Order.

✅ **Correct approach** (Order created at start):
```
API call: POST /cart/create → returns order_id (even as draft/pending)
Event: "Shopping Started" → linked to Order
Event: "Item Added" → linked to Order  
Event: "Payment Complete" → linked to Order
```
ALL events link to the same Order object from the beginning.

**If your primary object can't be created until mid-process** (e.g., needs data from user), create a placeholder/draft record at the start that gets populated later.

---

## IMPLEMENTATION REFERENCE

Use the Flow Myna Python SDK:

```python
from flowmyna import FlowMyna
import os

client = FlowMyna(api_key=os.environ["FLOWMYNA_API_KEY"])

# Record an event linked to an object
client.record_event(
    event="Order Placed",
    objects=[
        {"type": "Order", "id": "ORD-123", "properties": {"customer_email": "jane@example.com"}},
    ],
    properties={"channel": "web", "total": 99.99}
)
```

---

## IMPLEMENTATION RULES

### 1. Simple, Single Tracking Function
Create ONE generic tracking function, not individual helpers for each event:

```python
# ✅ Good - single parameterized function
def track_event(event: str, order_id: str, properties: dict = None):
    ...

track_event("Order Placed", order_id, {"total": 99.99})
track_event("Order Shipped", order_id, {"carrier": "FedEx"})
```

```python
# ❌ Bad - many specific functions (over-engineered, harder to maintain)
def track_order_placed(order_id, total): ...
def track_order_shipped(order_id, carrier): ...
def track_order_delivered(order_id): ...
```

### 2. Fire and Forget
Tracking calls should never block the main application. Use background execution:

```python
from concurrent.futures import ThreadPoolExecutor
_executor = ThreadPoolExecutor(max_workers=2)

def track_event(...):
    _executor.submit(_send_event, ...)  # Non-blocking
```

### 3. Fail Silently
If FLOWMYNA_API_KEY isn't set or API fails, log a warning but never crash:

```python
if not order_id:
    logger.warning(f"No order_id for event '{event}' - skipping")
    return
```

### 4. One Object Type Per Process
Link ALL events to the primary object type. User identifiers go in properties:

```python
# ✅ Good - Order is the object, customer_email is a property
objects=[{"type": "Order", "id": order_id, "properties": {"customer_email": email}}]

# ❌ Bad - mixing object types creates disconnected graphs  
objects=[{"type": "Customer", "id": email}]  # Some events
objects=[{"type": "Order", "id": order_id}]  # Other events
```

### 5. Meaningful Names
- Event names: Human-readable actions ("Order Shipped", not "order_shipped")
- Object types: Singular nouns ("Order", not "orders")

### 6. Useful Properties
Include properties that enable analysis:
- Counts: `item_count`, `attempt_number`
- Choices: `payment_method`, `shipping_option`
- Context: `error_type`, `from_step`, `to_step`
- Values: `total`, `discount_applied`

---

## FRONTEND + BACKEND PATTERN

For web apps with both frontend and backend:

1. **Create object on backend** via API call at process start
2. **Return object ID** to frontend
3. **Frontend stores ID** and passes to all subsequent API calls
4. **Both frontend and backend** can track events using the same ID

```
Frontend                          Backend
   |                                 |
   |-- POST /order/create ---------> |
   |                                 | Creates Order (draft)
   |<-- { order_id: "ORD-123" } ---- |
   |                                 |
   | [stores order_id in state]      |
   |                                 |
   |-- POST /track ----------------> |  (frontend events)
   |   { event: "Item Added",        |
   |     order_id: "ORD-123" }       |
   |                                 |
   |-- POST /order/checkout -------> |
   |   { order_id: "ORD-123" }       |  (backend tracks events too)
   |                                 |
```

---

## EXAMPLE: E-COMMERCE ORDER PROCESS

**Primary Object:** Order (created when shopping session starts)

**Events to track:**

| Event | When | Properties |
|-------|------|------------|
| Order Started | Session begins | `source` |
| Item Added | Add to cart | `product_id`, `quantity` |
| Item Removed | Remove from cart | `product_id` |
| Coupon Applied | Apply discount | `coupon_code`, `discount` |
| Checkout Started | Begin checkout | `item_count`, `subtotal` |
| Shipping Selected | Choose shipping | `shipping_method` |
| Payment Attempted | Submit payment | `payment_method` |
| Payment Failed | Payment error | `error_type`, `error_message` |
| Payment Succeeded | Payment complete | `total`, `payment_method` |
| Order Confirmed | Order finalized | `total`, `item_count` |

**Branching points captured:**
- Item Added vs Item Removed (engagement)
- Coupon Applied (optional action)
- Payment Attempted → Succeeded vs Failed (critical branch)
- Could add: Step Back, Checkout Abandoned

---

## CHECKLIST BEFORE IMPLEMENTATION

- [ ] Primary object identified and created at START of process
- [ ] All events link to the same object type
- [ ] User identifiers are properties, not object IDs
- [ ] Branching points identified (choices, errors, retries, skips)
- [ ] Single generic tracking function (not many helpers)
- [ ] Fire-and-forget execution (non-blocking)
- [ ] Fail-safe error handling (never crash the app)

---

**Now ask me the questions above!**

Tips for Best Results

  • Be specific about the process — Instead of "track everything", say "track order fulfillment from checkout to delivery". This helps the AI focus.
  • Mention key files or modules — If you know where the process logic lives, tell the AI (e.g., "the order service is in src/services/orders/").
  • Review the suggested events — The AI will propose events to track. Remove ones you don't need and add any it missed.
  • Start small — Track one process well before expanding. You can always run the prompt again for additional processes.
  • Check the utility module — The AI creates a tracking utility. Review it to ensure it follows your project's patterns.

What Gets Tracked

The AI will typically suggest tracking:

PatternExample EventsObjects
State changesOrder Created, Order Paid, Order ShippedOrder, Customer
AssignmentsTicket Assigned, Case EscalatedTicket, Agent, Team
ApprovalsInvoice Approved, Request RejectedInvoice, Approver
HandoffsLead Qualified, Lead ConvertedLead, Sales Rep, Account