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

# Self-Correction

> How Synapse automatically fixes validation errors

## Overview

When validation detects issues in generated code, Synapse's self-correction system automatically attempts to fix them without manual intervention.

## The Self-Correction Loop

<Steps>
  <Step title="Initial Generation">
    GPT-5 Mini generates code based on your prompt
  </Step>

  <Step title="Validation">
    MCP validator checks the code and returns a score with specific issues
  </Step>

  <Step title="Correction Decision">
    If score is below 90, self-correction is triggered
  </Step>

  <Step title="Fix Generation">
    AI analyzes the issues and generates corrected code
  </Step>

  <Step title="Re-validation">
    Corrected code is validated again
  </Step>

  <Step title="Success or Retry">
    Process repeats up to 3 times until score ≥ 90 or attempts exhausted
  </Step>
</Steps>

## Success Rates

| Attempt       | Success Rate | Avg Score |
| ------------- | ------------ | --------- |
| **Initial**   | 13%          | 87/100    |
| **Attempt 1** | 87%          | 93/100    |
| **Attempt 2** | 97%          | 96/100    |
| **Attempt 3** | 99%          | 98/100    |

## Common Corrections

### Import Path Fixes

<Tabs>
  <Tab title="Before">
    ```typescript theme={null}
    // ❌ Wrong import path
    import { Banner, useCart } from '@shopify/ui-extensions-react';
    ```
  </Tab>

  <Tab title="After">
    ```typescript theme={null}
    // ✅ Corrected import path
    import { Banner, useCart } from '@shopify/ui-extensions-react/checkout';
    ```
  </Tab>
</Tabs>

### GraphQL Query Corrections

<Tabs>
  <Tab title="Before">
    ```graphql theme={null}
    # ❌ Wrong field name
    query {
      cart {
        totalPrice
      }
    }
    ```
  </Tab>

  <Tab title="After">
    ```graphql theme={null}
    # ✅ Correct field structure
    query {
      cart {
        cost {
          totalAmount {
            amount
            currencyCode
          }
        }
      }
    }
    ```
  </Tab>
</Tabs>

### Hook Usage Fixes

<Tabs>
  <Tab title="Before">
    ```typescript theme={null}
    // ❌ Conditional hook call
    function Component() {
      if (condition) {
        const cart = useCart();
      }
    }
    ```
  </Tab>

  <Tab title="After">
    ```typescript theme={null}
    // ✅ Hook at top level
    function Component() {
      const cart = useCart();
      
      if (!condition) return null;
      // use cart
    }
    ```
  </Tab>
</Tabs>

## How It Works

### 1. Issue Analysis

When validation fails, Synapse extracts specific issues:

```json theme={null}
{
  "issues": [
    {
      "type": "import_error",
      "message": "Module '@shopify/ui-extensions-react' has no exported member 'Banner'",
      "line": 1,
      "severity": "error"
    },
    {
      "type": "graphql_error", 
      "message": "Cannot query field 'totalPrice' on type 'Cart'",
      "line": 15,
      "severity": "error"
    }
  ]
}
```

### 2. Correction Prompt

Synapse creates a targeted correction prompt:

```typescript theme={null}
const correctionPrompt = `
The following Shopify extension code has validation errors:

ISSUES:
1. Import Error (Line 1): Module '@shopify/ui-extensions-react' has no exported member 'Banner'
   Fix: Add /checkout to the import path for checkout extensions

2. GraphQL Error (Line 15): Cannot query field 'totalPrice' on type 'Cart'
   Fix: Use cart.cost.totalAmount.amount instead

ORIGINAL CODE:
${originalCode}

INSTRUCTIONS:
- Fix ONLY the issues listed above
- Preserve all existing functionality
- Keep the same component structure
- Do not add new features
- Return the complete corrected code
`;
```

### 3. Intelligent Fixing

The AI understands context and makes precise fixes:

<AccordionGroup>
  <Accordion title="Pattern Recognition">
    Recognizes common Shopify patterns and applies standard fixes

    * Import paths: Adds `/checkout`, `/admin`, `/pos` as appropriate
    * GraphQL: Uses Shopify's schema to find correct field paths
    * Hooks: Moves to top level and restructures conditionals
    * Props: Matches TypeScript definitions
  </Accordion>

  <Accordion title="Context Preservation">
    Maintains the original intent and structure

    * Keeps variable names
    * Preserves logic flow
    * Maintains comments
    * Retains error handling
  </Accordion>

  <Accordion title="Multi-Issue Handling">
    Fixes multiple issues simultaneously

    * Prioritizes critical errors
    * Groups related fixes
    * Avoids creating new issues
    * Validates dependencies between fixes
  </Accordion>
</AccordionGroup>

## Example Self-Correction Session

### Original Generation

```typescript theme={null}
import { Banner, useCart } from '@shopify/ui-extensions-react';

export default function FreeShippingBanner() {
  const cart = useCart();
  
  if (cart.totalPrice > 50) {
    return null;
  }
  
  return (
    <Banner status="info">
      Add ${50 - cart.totalPrice} more for free shipping!
    </Banner>
  );
}
```

**Validation Score:** 62/100

**Issues Found:**

* Import path missing `/checkout`
* `cart.totalPrice` doesn't exist
* `status` prop should be `tone`

### After Attempt 1

```typescript theme={null}
import { Banner, useCart } from '@shopify/ui-extensions-react/checkout';

export default function FreeShippingBanner() {
  const cart = useCart();
  
  const total = parseFloat(cart.cost.totalAmount.amount);
  
  if (total > 50) {
    return null;
  }
  
  const remaining = 50 - total;
  
  return (
    <Banner tone="info">
      Add ${remaining.toFixed(2)} more for free shipping!
    </Banner>
  );
}
```

**Validation Score:** 95/100

**Result:** ✅ Success! Code ready to deploy.

## When Self-Correction Fails

If self-correction doesn't reach a score of 90 after 3 attempts:

1. **User Notification**: You're informed of the persistent issues
2. **Partial Deployment**: Code can still be deployed if score ≥ 75
3. **Manual Review**: Recommended for scores \< 75
4. **Support Escalation**: Complex issues are flagged for team review

### Manual Intervention

You can always view and edit the generated code:

```typescript theme={null}
// Click "View Code" in the dashboard
// Edit directly in the code editor
// Re-run validation manually
// Deploy when satisfied
```

## Configuration

You can adjust self-correction behavior:

```json theme={null}
{
  "selfCorrection": {
    "enabled": true,
    "maxAttempts": 3,
    "minScore": 90,
    "autoDeployThreshold": 95
  }
}
```

## Best Practices

<CardGroup cols={2}>
  <Card title="Write Clear Prompts" icon="message">
    Specific prompts lead to better initial code and fewer corrections
  </Card>

  <Card title="Review Corrections" icon="eye">
    Check what was changed to learn and improve future prompts
  </Card>

  <Card title="Report Patterns" icon="flag">
    If the same issue repeats, let us know to improve the system
  </Card>

  <Card title="Use Validation" icon="shield-check">
    Always validate before deploying, even with high scores
  </Card>
</CardGroup>

## Limitations

<Warning>
  Self-correction cannot fix:

  * Fundamental logic errors (wrong business rules)
  * Missing required features
  * Performance issues
  * Security vulnerabilities beyond basic validation

  These require prompt revision or manual coding.
</Warning>

## Next Steps

<CardGroup cols={2}>
  <Card title="Validation Details" icon="magnifying-glass" href="/concepts/validation">
    Learn what triggers self-correction
  </Card>

  <Card title="Debugging Guide" icon="bug" href="/advanced/debugging">
    Fix issues manually when needed
  </Card>

  <Card title="Best Practices" icon="star" href="/advanced/best-practices">
    Write prompts that generate better code
  </Card>

  <Card title="Troubleshooting" icon="wrench" href="/advanced/troubleshooting">
    Common issues and solutions
  </Card>
</CardGroup>
