> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gu1.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Update Rule

> Update an existing rule configuration — in the gu1 rules engine for compliance and risk detection, with examples for update use cases.

## Overview

Updates an existing rule's configuration. All fields are optional - only include the fields you want to update. Updating a rule automatically increments its version number and maintains version history for audit purposes.

## Endpoint

```
PATCH http://api.gu1.ai/rules/{id}
```

## Authentication

Requires a valid API key in the Authorization header:

```bash theme={null}
Authorization: Bearer YOUR_API_KEY
```

## Path Parameters

<ParamField path="id" type="string" required>
  UUID of the rule to update
</ParamField>

## Request Body

All fields are optional. Only include fields you want to modify.

<ParamField body="name" type="string">
  Update rule name
</ParamField>

<ParamField body="description" type="string">
  Update rule description
</ParamField>

<ParamField body="category" type="string">
  Update category: `kyc`, `kyb`, `aml`, `fraud`, `compliance`, `custom`
</ParamField>

<ParamField body="enabled" type="boolean">
  Enable or disable the rule
</ParamField>

<ParamField body="priority" type="number">
  Update priority (1-100)
</ParamField>

<ParamField body="score" type="number">
  Update risk score (0-100)
</ParamField>

<ParamField body="status" type="string">
  Update status: `draft`, `in_progress`, `in_review`, `active`, `shadow`, `archived`, `inactive`
</ParamField>

<ParamField body="conditions" type="object">
  Update condition logic
</ParamField>

<ParamField body="actions" type="array">
  Update actions array
</ParamField>

<ParamField body="targetEntityTypes" type="array">
  Update target entity types
</ParamField>

<ParamField body="evaluationMode" type="string">
  Update evaluation mode: `sync` or `async`
</ParamField>

<ParamField body="riskMatrixId" type="string">
  Update associated risk matrix UUID
</ParamField>

<ParamField body="scope" type="object">
  Update scope configuration
</ParamField>

<ParamField body="tags" type="array">
  Update tags array
</ParamField>

## Response

<ResponseField name="id" type="string">
  UUID of the updated rule
</ResponseField>

<ResponseField name="version" type="number">
  New version number (incremented)
</ResponseField>

<ResponseField name="previousVersionId" type="string">
  UUID of the previous version
</ResponseField>

<ResponseField name="updatedBy" type="string">
  User ID who updated the rule
</ResponseField>

<ResponseField name="updatedAt" type="string">
  ISO timestamp of the update
</ResponseField>

Returns the complete updated rule object with all fields.

## Example Requests

### Enable/Disable Rule

<CodeGroup>
  ```bash cURL theme={null}
  curl -X PATCH http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "enabled": false
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea',
    {
      method: 'PATCH',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        enabled: false
      })
    }
  );

  const rule = await response.json();
  console.log('Rule disabled. New version:', rule.version);
  ```

  ```python Python theme={null}
  import requests

  response = requests.patch(
      'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'enabled': False
      }
  )

  rule = response.json()
  print(f"Rule disabled. New version: {rule['version']}")
  ```
</CodeGroup>

### Update Priority and Score

<CodeGroup>
  ```bash cURL theme={null}
  curl -X PATCH http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "priority": 90,
      "score": 75
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea',
    {
      method: 'PATCH',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        priority: 90,
        score: 75
      })
    }
  );

  const rule = await response.json();
  console.log('Priority and score updated');
  ```

  ```python Python theme={null}
  response = requests.patch(
      'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'priority': 90,
          'score': 75
      }
  )

  rule = response.json()
  print('Priority and score updated')
  ```
</CodeGroup>

### Update Conditions

<CodeGroup>
  ```bash cURL theme={null}
  curl -X PATCH http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "conditions": {
        "operator": "OR",
        "conditions": [
          {
            "id": "cond-1",
            "type": "simple",
            "field": "enrichmentData.normalized.taxId",
            "operator": "eq",
            "value": "33.592.510/0001-54",
            "filters": []
          },
          {
            "id": "cond-2",
            "type": "simple",
            "field": "enrichmentData.normalized.taxId",
            "operator": "eq",
            "value": "12.345.678/0001-90",
            "filters": []
          }
        ]
      }
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea',
    {
      method: 'PATCH',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        conditions: {
          operator: 'OR',
          conditions: [
            {
              id: 'cond-1',
              type: 'simple',
              field: 'enrichmentData.normalized.taxId',
              operator: 'eq',
              value: '33.592.510/0001-54',
              filters: []
            },
            {
              id: 'cond-2',
              type: 'simple',
              field: 'enrichmentData.normalized.taxId',
              operator: 'eq',
              value: '12.345.678/0001-90',
              filters: []
            }
          ]
        }
      })
    }
  );

  const rule = await response.json();
  console.log('Conditions updated. Now checking 2 CNPJs');
  ```

  ```python Python theme={null}
  response = requests.patch(
      'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'conditions': {
              'operator': 'OR',
              'conditions': [
                  {
                      'id': 'cond-1',
                      'type': 'simple',
                      'field': 'enrichmentData.normalized.taxId',
                      'operator': 'eq',
                      'value': '33.592.510/0001-54',
                      'filters': []
                  },
                  {
                      'id': 'cond-2',
                      'type': 'simple',
                      'field': 'enrichmentData.normalized.taxId',
                      'operator': 'eq',
                      'value': '12.345.678/0001-90',
                      'filters': []
                  }
              ]
          }
      }
  )

  rule = response.json()
  print('Conditions updated. Now checking 2 CNPJs')
  ```
</CodeGroup>

### Add Actions

<CodeGroup>
  ```bash cURL theme={null}
  curl -X PATCH http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "actions": [
        {
          "type": "createAlert",
          "createAlert": {
            "type": "COMPLIANCE",
            "title": "High Risk Entity Detected",
            "description": "Entity matched high-risk criteria",
            "severity": "CRITICAL",
            "recipients": ["compliance@company.com", "security@company.com"]
          },
          "tags": ["high-risk", "urgent"]
        },
        {
          "type": "updateEntityStatus",
          "updateEntityStatus": {
            "status": "under_review",
            "reason": "Flagged by automated rule"
          }
        },
        {
          "type": "sendNotification",
          "sendNotification": {
            "channel": "email",
            "recipients": ["compliance-lead@company.com"],
            "message": "Immediate review required for high-risk entity"
          }
        }
      ]
    }'
  ```
</CodeGroup>

### Update Status to Shadow Mode

<CodeGroup>
  ```bash cURL theme={null}
  curl -X PATCH http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "status": "shadow",
      "enabled": true
    }'
  ```

  ```javascript JavaScript theme={null}
  // Deploy rule in shadow mode (logs matches without executing actions)
  const response = await fetch(
    'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea',
    {
      method: 'PATCH',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        status: 'shadow',
        enabled: true
      })
    }
  );

  const rule = await response.json();
  console.log('Rule deployed in shadow mode for testing');
  ```

  ```python Python theme={null}
  # Deploy rule in shadow mode
  response = requests.patch(
      'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'status': 'shadow',
          'enabled': True
      }
  )

  rule = response.json()
  print('Rule deployed in shadow mode for testing')
  ```
</CodeGroup>

### Update Tags

<CodeGroup>
  ```bash cURL theme={null}
  curl -X PATCH http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "tags": ["blocklist", "high-priority", "brazil", "automated"]
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea',
    {
      method: 'PATCH',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        tags: ['blocklist', 'high-priority', 'brazil', 'automated']
      })
    }
  );

  const rule = await response.json();
  console.log('Tags updated');
  ```

  ```python Python theme={null}
  response = requests.patch(
      'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'tags': ['blocklist', 'high-priority', 'brazil', 'automated']
      }
  )

  rule = response.json()
  print('Tags updated')
  ```
</CodeGroup>

## Response Example

```json theme={null}
{
  "id": "e2cdd639-52cc-4749-9b16-927bfa5dfaea",
  "organizationId": "71e8f908-e032-4fcb-b0ce-ad0cd0ffb236",
  "name": "CNPJ Blocklist Check",
  "description": "Block companies with specific CNPJ",
  "category": "kyb",
  "status": "active",
  "enabled": true,
  "priority": 90,
  "score": 75,
  "conditions": {...},
  "actions": [...],
  "scope": {...},
  "targetEntityTypes": ["company"],
  "evaluationMode": "sync",
  "riskMatrixId": "d257247b-af7b-402a-ad8f-eac209e2990e",
  "version": 2,
  "previousVersionId": "e2cdd639-52cc-4749-9b16-927bfa5dfaea-v1",
  "tags": ["blocklist", "high-priority"],
  "createdBy": "f35c10cb-9b67-4cda-9aea-f36567375dba",
  "createdAt": "2024-12-22T14:10:28.131Z",
  "updatedBy": "f35c10cb-9b67-4cda-9aea-f36567375dba",
  "updatedAt": "2024-12-23T10:30:00.000Z",
  "stats": {
    "failures": 0,
    "successes": 7,
    "executions": 7
  }
}
```

## Error Responses

### 404 Not Found

```json theme={null}
{
  "error": "Rule not found",
  "id": "e2cdd639-52cc-4749-9b16-927bfa5dfaea"
}
```

### 400 Bad Request - Invalid Data

```json theme={null}
{
  "error": "Validation failed",
  "details": {
    "field": "priority",
    "message": "Priority must be between 1 and 100"
  }
}
```

### 401 Unauthorized

```json theme={null}
{
  "error": "Invalid or missing API key"
}
```

### 403 Forbidden

```json theme={null}
{
  "error": "Access denied",
  "message": "You don't have permission to update this rule"
}
```

### 409 Conflict

```json theme={null}
{
  "error": "Rule is currently being executed",
  "message": "Cannot update rule during active execution"
}
```

## Use Cases

### Progressive Rule Refinement

```javascript theme={null}
// Start with shadow mode, then gradually activate
async function deployRuleProgressively(ruleId) {
  // Phase 1: Deploy in shadow mode
  console.log('Phase 1: Shadow mode deployment...');
  await fetch(`http://api.gu1.ai/rules/${ruleId}`, {
    method: 'PATCH',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      status: 'shadow',
      enabled: true
    })
  });

  // Wait and monitor for 1 week...
  console.log('Monitoring shadow mode for 1 week...');

  // Phase 2: Activate with low priority
  console.log('Phase 2: Activating with low priority...');
  await fetch(`http://api.gu1.ai/rules/${ruleId}`, {
    method: 'PATCH',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      status: 'active',
      priority: 20
    })
  });

  // Wait and monitor performance...
  console.log('Monitoring performance...');

  // Phase 3: Increase priority if performing well
  console.log('Phase 3: Increasing priority...');
  await fetch(`http://api.gu1.ai/rules/${ruleId}`, {
    method: 'PATCH',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      priority: 80
    })
  });

  console.log('✅ Rule fully deployed');
}
```

### Bulk Update Rules by Category

```python theme={null}
def bulk_update_by_category(category, updates):
    """Update all rules in a category"""
    # Get all rules in category
    response = requests.get(
        'http://api.gu1.ai/rules',
        headers={
            'Authorization': 'Bearer YOUR_API_KEY'
        },
        params={
            'category': category,
            'pageSize': 100
        }
    )

    rules = response.json()['rules']

    print(f"Updating {len(rules)} rules in category '{category}'...")

    for rule in rules:
        update_response = requests.patch(
            f'http://api.gu1.ai/rules/{rule["id"]}',
            headers={
                'Authorization': 'Bearer YOUR_API_KEY',
                'Content-Type': 'application/json'
            },
            json=updates
        )

        if update_response.status_code == 200:
            print(f"  ✅ Updated: {rule['name']}")
        else:
            print(f"  ❌ Failed: {rule['name']}")

    print(f"Bulk update completed")

# Example: Disable all AML rules temporarily
bulk_update_by_category('aml', {'enabled': False})
```

### A/B Testing Rules

```javascript theme={null}
async function setupRuleABTest(ruleId) {
  // Get original rule
  const originalResponse = await fetch(
    `http://api.gu1.ai/rules/${ruleId}`,
    {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );

  const original = await originalResponse.json();

  // Create variant with different score
  const variantResponse = await fetch(
    'http://api.gu1.ai/rules',
    {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        ...original,
        id: undefined,
        name: original.name + ' (Variant)',
        score: original.score + 10,
        tags: [...original.tags, 'ab-test', 'variant'],
        enabled: false // Start disabled
      })
    }
  );

  const variant = await variantResponse.json();

  // Tag original as control
  await fetch(`http://api.gu1.ai/rules/${ruleId}`, {
    method: 'PATCH',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      tags: [...original.tags, 'ab-test', 'control']
    })
  });

  console.log('A/B test setup complete');
  console.log('Control:', ruleId);
  console.log('Variant:', variant.id);

  return { control: ruleId, variant: variant.id };
}
```

### Rotate Action Recipients

```python theme={null}
def rotate_alert_recipients(rule_id, new_recipients):
    """Update alert recipients for a rule"""
    # Get current rule
    response = requests.get(
        f'http://api.gu1.ai/rules/{rule_id}',
        headers={
            'Authorization': 'Bearer YOUR_API_KEY'
        }
    )

    rule = response.json()

    # Update alert recipients in actions
    updated_actions = []
    for action in rule['actions']:
        if action['type'] == 'createAlert':
            action['createAlert']['recipients'] = new_recipients
        updated_actions.append(action)

    # Update rule
    update_response = requests.patch(
        f'http://api.gu1.ai/rules/{rule_id}',
        headers={
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json'
        },
        json={
            'actions': updated_actions
        }
    )

    if update_response.status_code == 200:
        print(f"✅ Alert recipients updated to: {new_recipients}")
    else:
        print(f"❌ Failed to update recipients")

    return update_response.json()
```

## Best Practices

1. **Partial Updates**: Only send fields you want to change
2. **Test First**: Use execute endpoint to test before updating production rules
3. **Shadow Mode**: Test condition changes in shadow mode before activating
4. **Version History**: Keep track of version numbers for rollback capability
5. **Monitor Stats**: Watch execution statistics after updates
6. **Gradual Rollout**: Update priority gradually when deploying new logic
7. **Tag Changes**: Tag rules with update metadata for tracking

## Versioning

Each update creates a new version:

* `version`: Increments by 1
* `previousVersionId`: Links to previous version
* Version history is maintained for audit and rollback

## Notes

* Updates are applied immediately for sync rules
* Async rules may take a few minutes to reflect changes
* Statistics are preserved across updates
* Disabled rules don't execute but remain in the system

## See Also

* [Get Rule](/en/api-reference/rules/get) - Retrieve current rule state
* [Execute Rule](/en/api-reference/rules/execute) - Test updated rules
* [Create Rule](/en/api-reference/rules/create) - Create new rules
* [List Rules](/en/api-reference/rules/list) - Query rules
