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

# AI-Powered Features

> AI-generated commit messages, code review, and intelligent assistance

You made changes. The AI can see exactly what changed. Why are you still writing commit messages?

```bash theme={null}
wit ai commit -a -x
```

Done. The AI reads your diff, writes a message that actually describes what you did, and commits.

This is one of several places where wit uses AI to eliminate busywork:

* **Commit messages** - AI reads your diff and writes the message
* **Code review** - Catch issues before your teammates do
* **Semantic search** - Ask questions about your codebase in English
* **Conflict resolution** - Get AI suggestions for merge conflicts

## Setup

### API Key Configuration

AI features require an API key from OpenAI or Anthropic:

```bash theme={null}
# For OpenAI (GPT-4o, GPT-4o-mini, etc.)
export OPENAI_API_KEY=sk-your-key-here

# OR for Anthropic (Claude)
export ANTHROPIC_API_KEY=sk-ant-your-key-here
```

Add to your shell profile for persistence:

```bash theme={null}
# ~/.bashrc or ~/.zshrc
export OPENAI_API_KEY=sk-your-key-here
```

### Check Configuration

```bash theme={null}
wit ai status
```

Output:

```
wit AI Status

Available: Yes
Model: openai/gpt-4o
Provider: openai

Environment Variables:
  OPENAI_API_KEY: Set
  ANTHROPIC_API_KEY: Not set
  WIT_AI_MODEL: (not set, using default)
```

### Using Different Models

```bash theme={null}
# Use Claude instead of GPT-4o
export WIT_AI_MODEL=anthropic/claude-sonnet-4
export ANTHROPIC_API_KEY=sk-ant-...

# Use GPT-4o-mini (faster, cheaper)
export WIT_AI_MODEL=openai/gpt-4o-mini
export OPENAI_API_KEY=sk-...
```

## AI Commands

### Natural Language Commands

Ask questions or give commands in plain English:

```bash theme={null}
# Check status
wit ai "what files have I changed?"
wit ai "show me unstaged changes"

# View history
wit ai "show me the last 5 commits"
wit ai "what did I commit yesterday?"

# Branch operations
wit ai "what branch am I on?"
wit ai "list all branches"
wit ai "switch to the main branch"

# Search
wit ai "find commits mentioning 'login'"
wit ai "search for files containing 'TODO'"
```

### Generate Commit Messages

```bash theme={null}
# First, stage your changes
wit add .

# Generate a commit message
wit ai commit
```

**Output:**

```
Generating commit message...

Suggested commit message:

----------------------------------------------------------------
feat: add user authentication middleware

- Implement JWT token validation
- Add role-based access control
- Create auth error handling
----------------------------------------------------------------

To use this message, run:
  wit commit -m "feat: add user authentication middleware"

Or add --execute (-x) to commit directly:
  wit ai commit -x
```

**Options:**

```bash theme={null}
wit ai commit           # Generate message for staged changes
wit ai commit -a        # Stage all tracked files + generate message
wit ai commit -x        # Generate AND execute the commit
wit ai commit -a -x     # Stage all, generate, and commit in one command
```

### Code Review

Get AI-powered feedback on your changes:

```bash theme={null}
# Review all changes (staged + unstaged)
wit ai review

# Review only staged changes
wit ai review --staged
```

**Example output:**

```
Reviewing changes...

## Code Review Summary

### Issues Found

1. **Warning** - `src/auth.ts:42`
   Missing null check before accessing `user.email`
   Suggestion: Add optional chaining: `user?.email`

2. **Info** - `src/utils.ts:15`
   Consider using const instead of let for `config`

### Security Concerns
- API key is being logged in debug mode (line 78)

### Suggestions
- Add input validation for the email field
- Consider adding rate limiting to the auth endpoint
```

### Explain Commits

Understand what a commit does:

```bash theme={null}
# Explain the latest commit
wit ai explain

# Explain a specific commit
wit ai explain HEAD~3
wit ai explain abc1234
```

**Example output:**

```
Explaining commit...

## Commit abc1234: "refactor: extract validation logic"

This commit reorganizes the validation code by:

1. **What it does**: Extracts inline validation logic from the 
   UserController into a dedicated ValidationService class.

2. **Why it was made**: This separation of concerns makes the code
   more testable and follows the Single Responsibility Principle.

3. **What it affects**: 
   - `src/controllers/UserController.ts` (simplified)
   - `src/services/ValidationService.ts` (new file)
   - `src/tests/validation.test.ts` (new tests)
```

### Conflict Resolution

Get AI help resolving merge conflicts:

```bash theme={null}
# Start a merge
wit merge feature-branch

# If there are conflicts, ask for help
wit ai resolve

# Or resolve a specific file
wit ai resolve src/config.ts
```

**Example output:**

```
Resolving: src/config.ts

## Conflict Analysis

**Our version (main):**
- Sets `maxRetries` to 3
- Uses synchronous file loading

**Their version (feature-branch):**
- Sets `maxRetries` to 5
- Uses async file loading with error handling

## Recommended Resolution

I recommend keeping their version because:
1. Higher retry count improves reliability
2. Async loading prevents blocking the main thread
3. Their error handling is more robust
```

## AI Tools

wit's AI agent has access to specialized tools that give it full capabilities:

### Repository Understanding

| Tool          | Purpose                                                         |
| ------------- | --------------------------------------------------------------- |
| `getStatus`   | Understand repository state (staged, modified, untracked files) |
| `getDiff`     | Analyze changes between commits or working directory            |
| `getLog`      | Review commit history                                           |
| `getBranches` | Navigate and list branches                                      |
| `search`      | Intelligent code and commit search                              |

### Taking Actions

| Tool           | Purpose                      |
| -------------- | ---------------------------- |
| `stageFiles`   | Stage files for commit       |
| `createCommit` | Generate and create commits  |
| `switchBranch` | Switch to a different branch |
| `undo`         | Undo recent operations       |

### Conflict Resolution

| Tool                | Purpose                                  |
| ------------------- | ---------------------------------------- |
| `getMergeConflicts` | Retrieve structured conflict information |
| `resolveConflict`   | Apply a resolution to a conflict         |

The AI agent can use these tools to perform complex multi-step operations like:

```bash theme={null}
# AI can understand this request and use multiple tools
wit ai "stage all test files and commit with a descriptive message"

# Or help resolve conflicts
wit ai "show me the conflicts and help me resolve them"
```

## Programmatic Usage

Use AI features in your TypeScript code:

```typescript theme={null}
import { getTsgitAgent, createTsgitMastra } from 'wit/ai';

// Get the agent
const agent = getTsgitAgent();

// Generate a response
const result = await agent.generate('What files have changed?');
console.log(result.text);

// Stream a response
const stream = await agent.stream('Review my staged changes');
for await (const chunk of stream.textStream) {
  process.stdout.write(chunk);
}
```

### Using Individual Tools

```typescript theme={null}
import { witTools } from 'wit/ai';

// Get repository status
const status = await witTools.getStatus.execute({ path: '.' });
console.log('Modified files:', status.modified);

// Get diff
const diff = await witTools.getDiff.execute({ 
  staged: true,
  contextLines: 5 
});
console.log(diff.summary);

// Create a commit
const commit = await witTools.createCommit.execute({
  message: 'feat: add new feature',
  all: true,
});
console.log('Committed:', commit.shortHash);
```

## Tips

1. **Be specific**: "Show commits from last week that modified auth files" works better than "show commits"

2. **Use context**: The AI understands git concepts:
   * "What's the difference between my branch and main?"
   * "Have I already committed the login changes?"

3. **Iterate**: If the AI's first response isn't quite right, follow up with more details

4. **Commit messages**: The AI follows conventional commits format. For best results:
   * Stage related changes together
   * Don't mix unrelated changes in one commit

5. **Code review**: Run `wit ai review` before pushing to catch issues early

## Environment Variables

| Variable            | Description                         | Default         |
| ------------------- | ----------------------------------- | --------------- |
| `OPENAI_API_KEY`    | OpenAI API key for GPT models       | -               |
| `ANTHROPIC_API_KEY` | Anthropic API key for Claude models | -               |
| `WIT_AI_MODEL`      | Model to use                        | `openai/gpt-4o` |

## Supported Models

The AI integration uses `@mastra/core` which supports:

* **OpenAI**: `openai/gpt-4o`, `openai/gpt-4o-mini`, `openai/gpt-4-turbo`
* **Anthropic**: `anthropic/claude-sonnet-4`, `anthropic/claude-3-haiku`
* **And more** via the Mastra model router

## Privacy & Security

<Note>
  AI features send code to external APIs. Consider:

  * Don't use on sensitive/proprietary code without approval
  * Review AI suggestions before applying
  * Only diff content is sent, not your full repository
</Note>

### What's Sent

* Diff content (staged changes)
* Commit messages (for context)
* File paths

### What's NOT Sent

* Unstaged file contents (unless explicitly reviewing)
* Full repository history
* Configuration files with secrets

## Troubleshooting

<AccordionGroup>
  <Accordion title="AI features not working">
    Check your API key:

    ```bash theme={null}
    wit ai status
    ```

    Make sure `OPENAI_API_KEY` or `ANTHROPIC_API_KEY` is set correctly.
  </Accordion>

  <Accordion title="Rate limiting">
    If you hit rate limits:

    * Wait a few minutes
    * Consider upgrading your API plan
    * Use a faster/cheaper model like `openai/gpt-4o-mini`
  </Accordion>

  <Accordion title="Poor suggestions">
    For better results:

    * Stage related changes together
    * Don't mix unrelated changes
    * Be specific in natural language queries
  </Accordion>
</AccordionGroup>
