# Rules App

Automation rules for thread and message processing in Dexxy.

## Purpose

This app provides a rule engine for automating actions on incoming threads and messages. Rules are defined with conditions (predicates) and actions, enabling workflows like auto-tagging, routing, and notifications without manual intervention.

## Models

### Rule

An automation rule with conditions and actions.

| Field | Type | Description |
|-------|------|-------------|
| `workspace` | ForeignKey | Workspace scope |
| `name` | CharField | Rule name |
| `description` | TextField | What the rule does |
| `predicate` | JSONField | Conditions that trigger the rule |
| `action_type` | CharField | Type of action to perform |
| `action_params` | JSONField | Action configuration |
| `priority` | IntegerField | Execution order (lower = first) |
| `is_enabled` | BooleanField | Rule active state |

## Rule Structure

### Predicates (Conditions)

Predicates are JSON objects defining when a rule should fire:

```json
{
  "type": "and",
  "conditions": [
    {"field": "source.kind", "operator": "equals", "value": "github_repo"},
    {"field": "title", "operator": "contains", "value": "bug"}
  ]
}
```

**Operators:**
- `equals`, `not_equals`
- `contains`, `not_contains`
- `starts_with`, `ends_with`
- `matches` (regex)

### Actions

Actions define what happens when conditions match:

```json
{
  "action_type": "add_tag",
  "action_params": {"tag_id": 123}
}
```

**Action Types:**
- `add_tag` - Apply a tag to the thread
- `remove_tag` - Remove a tag from the thread
- `set_status` - Change thread status
- `notify` - Send a notification
- `assign` - Assign to a team member

## GraphQL API

### Queries

- `rules(workspace_id, is_enabled?)` - List rules with optional filter
- `rule(id)` - Get a specific rule

### Mutations

- `createRule(input)` - Create a new rule (admin only)
- `updateRule(id, input)` - Update rule configuration
- `deleteRule(id)` - Delete a rule (admin only)

## Key Patterns

1. **Priority Ordering**: Rules execute in priority order
2. **Admin-Only Management**: Rule creation/deletion requires admin role
3. **JSON-Based Logic**: Flexible conditions without schema changes
4. **Enable/Disable**: Rules can be deactivated without deletion

## Execution Flow

```
New Thread/Message Arrives
    ↓
Rules Engine Fetches Enabled Rules (ordered by priority)
    ↓
For Each Rule:
    - Evaluate predicate against thread/message
    - If match: Execute action
    ↓
Continue to next rule
```

## Dependencies

- `accounts.Workspace`
- Background task queue for rule execution
- `messages.Thread`, `messages.Tag` for actions

## File Structure

```
rules/
├── models.py      # Rule model
├── graphql.py     # GraphQL types, queries, mutations
├── apps.py        # Django app config
└── migrations/    # Database migrations
```
