---
title: "Best Practices for AI Code Agents"
source: https://docs.autohand.ai/guides/ace/best-practices
---

# Best Practices for AI Code Agents

Working with AI code agents is a skill. These best practices will help you get more done with less friction, whether you're debugging, building features, or refactoring entire codebases.

## The right mindset

AI code agents are not autocomplete on steroids. They're autonomous collaborators that can read files, run commands, make decisions, and iterate on solutions. To work effectively with them:

-   **Think in outcomes, not steps**: Describe what you want to achieve, not how to achieve it. Let the agent figure out the path.
-   **Trust but verify**: Agents make mistakes. Review their work, especially for security-sensitive code.
-   **Iterate fast**: If something isn't working, interrupt and redirect. Don't wait for a long task to fail.
-   **Provide context, not instructions**: The more the agent understands about your codebase and goals, the better it performs.

**Key insight:** The best results come from treating agents as capable junior developers who need context, not as command-line tools that need exact syntax.

## Plan before you build

The single most impactful practice is planning before coding. Ask the agent to research your codebase, identify dependencies, and propose implementation strategies before writing a single line of code.

### When to request a plan

-   Adding new features that touch multiple files
-   Refactoring existing systems
-   Working in unfamiliar codebases
-   Tasks where architecture decisions matter

### How to request planning

``` bash
# Ask the agent to plan before implementing
"Before implementing anything, create a detailed plan for adding user authentication"

# Or be explicit about exploring first
"Explore the codebase and understand how payments work before making any changes"

# For complex tasks, use auto-mode with checkpoints
autohand --auto-mode --checkpoint-interval 5
```

### What good plans include

-   Files that need to be created or modified
-   Dependencies and their order
-   Potential risks or breaking changes
-   Testing strategy

Review the plan, ask questions, and only approve when you're confident in the approach. This upfront investment saves hours of debugging later.

## Context management

Agents perform better with the right context. Too little context leads to wrong assumptions. Too much context wastes tokens and slows responses. Autohand provides several ways to manage context effectively.

### AGENTS.md files

Create an `AGENTS.md` file in your project root to provide persistent context about your codebase. Autohand automatically reads this file at the start of each session.

``` markdown
# AGENTS.md

## Project Overview
This is a Next.js 14 application using the App Router, TypeScript, and Prisma ORM.

## Architecture
- `/app` - Next.js App Router pages and layouts
- `/lib` - Shared utilities and database client
- `/components` - React components with shadcn/ui

## Code Style
- Use TypeScript strict mode
- Prefer server components where possible
- Use Zod for runtime validation

## Commands
- `bun run dev` - Start development server
- `bun run test` - Run tests
- `bun run db:push` - Push schema changes
```

### Initialize with /init

Use the `/init` command to generate an AGENTS.md file based on your project structure:

``` bash
# Generate AGENTS.md for your project
/init

# The agent will analyze your codebase and create appropriate context
```

### Skills for domain-specific knowledge

Use [skills](/docs/working-with-autohand-code/skills.html) to package domain-specific knowledge that agents can invoke when needed.

``` bash
# List available skills
/skills

# Skills are automatically discovered from:
# - .autohand/skills/
# - ~/.autohand/skills/
# - Project-specific skill directories

# Enable automatic skill detection
autohand --auto-skill
```

### Fresh conversations

Start new conversations when switching tasks. Context from unrelated tasks can confuse agents and lead to incorrect solutions.

``` bash
# Start a fresh session
/new

# Or manage sessions explicitly
/sessions          # List all sessions
/session my-task   # Switch to a named session
/resume            # Resume last session
```

### Add context directories

``` bash
# Add additional directories to context
/add-dir ./libs/shared

# Useful when working across multiple packages
```

## Effective prompting

How you communicate with agents matters. Clear, specific prompts lead to better results.

### Be specific about scope

| Instead of | Try |
|---|---|
| "Fix the bug" | "Fix the null pointer exception in UserService.getProfile when user.address is undefined" |
| "Make it faster" | "Optimize the database query in getOrders to reduce response time from 2s to under 200ms" |
| "Add tests" | "Add unit tests for the PaymentProcessor class covering successful payments, failed payments, and refunds" |

### Provide acceptance criteria

Tell the agent what success looks like:

``` text
Add a password reset feature. It should:
- Send an email with a reset link
- Links expire after 1 hour
- Users can't reuse their last 3 passwords
- Log all reset attempts for security audit
- Work with our existing email service in lib/email.ts
```

### Use constraints

Constraints help agents make better decisions:

``` text
Refactor the authentication module. Constraints:
- Don't change the public API
- Keep backward compatibility with existing tokens
- No new dependencies
- Must pass all existing tests
```

## Test-driven development

Tests are the best way to verify agent work. They provide clear success criteria and catch regressions automatically.

### Write tests first

``` text
1. Write a failing test for the feature
2. Ask the agent to make it pass
3. Review the implementation
4. Add edge case tests
5. Have the agent handle edge cases
```

### Use tests as specifications

``` bash
# Point the agent to tests
"Make all tests in tests/payment.test.ts pass"

# Or run tests as part of verification
"After implementing the feature, run the test suite and fix any failures"
```

### Use linting and formatting

Autohand includes built-in support for code quality checks:

``` bash
# Check linting issues
/lint

# Configure formatters
/formatters

# Ask the agent to fix issues
"Fix all linting errors in the codebase"
```

### Typed languages help

TypeScript, Go, Rust, and other typed languages provide compile-time verification. Type errors give agents immediate feedback on mistakes.

``` bash
# Have the agent fix type errors
"Fix all TypeScript errors in the codebase"

# Use strict mode for better error detection
# tsconfig.json: "strict": true
```

## Review strategies

Agent output needs review. The goal is to catch issues without creating bottlenecks.

### Watch in real-time

Monitor agent progress as it works. If you see it heading in the wrong direction, interrupt early:

``` bash
# Press Ctrl+C to interrupt
# Then redirect
"Stop. That approach won't work because of X. Instead, try Y."
```

### Use diff review

After agents make changes, review the diff before committing:

``` bash
# Review changes with git
git diff

# Ask the agent to explain changes
"Explain the changes you made to the authentication module"

# Undo the last change if needed
/undo
```

### Commit with context

Use the built-in commit command for well-formatted commits:

``` bash
# Create a commit with agent-generated message
/commit

# The agent will analyze changes and create an appropriate commit message
```

### Automated checks with hooks

Set up hooks to run checks automatically after agent actions:

``` bash
# View available hooks
/hooks

# Hooks can trigger on events like:
# - before_tool_call
# - after_tool_call
# - on_file_change
# - on_error
```

## Automation workflows

Autohand excels at automating repetitive tasks. Use auto-mode and skills for common operations.

### Auto-mode for autonomous operation

Auto-mode lets the agent work autonomously with git worktree isolation:

``` bash
# Enable auto-mode for autonomous operation
autohand --auto-mode

# Configure iteration limits
autohand --auto-mode --max-iterations 50

# Set checkpoint intervals for long tasks
autohand --auto-mode --checkpoint-interval 10

# Toggle auto-mode during a session
/automode
```

### Non-interactive mode

Run agents without interaction for automation pipelines:

``` bash
# Run with automatic yes to prompts
autohand -y --prompt "Update all dependencies and fix any breaking changes"

# Use in CI/CD pipelines
autohand --yes --prompt "Review the changes and add inline comments"

# Run with a completion promise for scripting
autohand --completion-promise --prompt "Generate API documentation"
```

### Automatic skill detection

Enable automatic skill detection to let the agent use skills without explicit invocation:

``` bash
# Enable automatic skill detection
autohand --auto-skill

# The agent will automatically detect and use relevant skills
# based on the task context
```

### Export and share sessions

``` bash
# Export current session
/export

# Share session with team
/share
```

## Multi-agent patterns

For complex tasks, multiple agents working in parallel can be more effective than a single agent.

### Parallel exploration

Run multiple agents to explore different solutions:

``` bash
# Terminal 1: Agent exploring solution A
autohand --prompt "Implement caching using Redis"

# Terminal 2: Agent exploring solution B
autohand --prompt "Implement caching using in-memory LRU"

# Compare results and choose the best approach
```

### Specialization

Different agents for different tasks:

-   **Research agent**: Explores codebase, gathers context
-   **Implementation agent**: Writes code based on research
-   **Review agent**: Checks implementation for issues
-   **Test agent**: Writes and runs tests

### External agents

Manage external agent integrations:

``` bash
# List configured agents
/agents

# Create a new agent configuration
/agents-new

# External agents can be configured for specialized capabilities
# like browser automation, data analysis, or domain-specific tasks
```

## Permission management

Autohand uses a permission system to control what actions agents can take.

### View and manage permissions

``` bash
# View current permissions
/permissions

# Permissions control access to:
# - File system operations
# - Command execution
# - Network requests
# - Sensitive operations
```

### Permission levels

-   **Ask**: Prompt before each action
-   **Allow**: Permit automatically
-   **Deny**: Block automatically

**Security tip:** Start with restrictive permissions and expand as needed. Review permission requests carefully, especially for file writes and command execution.

## Security considerations

Agents have significant access to your system. Follow these practices to stay secure.

### Review sensitive operations

Always review agent actions that involve:

-   Authentication and authorization code
-   Database queries with user input
-   API endpoints handling sensitive data
-   Infrastructure configuration
-   Dependency changes

### Use sandboxed environments

For risky operations, use sandboxed or staging environments:

``` bash
# Run agents against staging
DATABASE_URL=$STAGING_DB autohand --prompt "Migrate the database schema"

# Use auto-mode with git worktree isolation
autohand --auto-mode  # Changes happen in isolated worktree
```

### Memory management

Use memory commands to manage what the agent remembers:

``` bash
# View and manage agent memory
/memory

# Memory stores context between sessions
# Review periodically for sensitive information
```

## Learning your codebase

Use agents to understand unfamiliar code. They're excellent at exploration and explanation.

### Ask questions like a teammate

``` text
"How does the payment processing work in this codebase?"

"What happens when a user submits an order?"

"Where is authentication handled and what middleware is involved?"

"What's the data flow from API request to database?"
```

### Generate documentation

``` bash
# Document a module
"Create documentation for the order processing module, including:
- High-level architecture
- Key functions and their purposes
- Data models
- Common use cases"
```

### Trace execution paths

``` text
"Trace the code path when a user clicks 'Submit Order'.
Show me every function that gets called and what it does."
```

## When things go wrong

Agents aren't perfect. Here's how to handle common issues.

### Agent is stuck in a loop

``` bash
# Interrupt with Ctrl+C
# Then provide more context
"Stop. The approach isn't working because [reason].
Let's try a different approach: [alternative]"
```

### Agent made incorrect changes

``` bash
# Undo the last change
/undo

# Or revert with git
git checkout -- .

# Provide clarification
"That's not what I meant. I need X, not Y."
```

### Agent doesn't understand the codebase

``` bash
# Initialize an AGENTS.md file
/init

# Or provide more context manually
"Before making changes, read these files to understand the architecture:
- lib/core/engine.ts
- lib/core/types.ts
- docs/ARCHITECTURE.md"
```

### Switch models for better results

``` bash
# Switch to a different model during session
/model z-ai/glm-4.7

# Or start with a specific model
autohand --model gpt-4o

# List available models for your provider
/model
```

### Get help

``` bash
# View all available commands
/help

# Send feedback about issues
/feedback
```

## Summary

Working effectively with AI code agents comes down to a few key principles:

1.  **Plan first**: Ask for plans before complex implementations
2.  **Manage context**: Use AGENTS.md, /init, skills, and /new for fresh starts
3.  **Be specific**: Clear prompts with acceptance criteria
4.  **Test everything**: Tests are your safety net
5.  **Review actively**: Watch progress, use /undo, and interrupt early
6.  **Automate workflows**: Use --auto-mode and --auto-skill for repetitive tasks
7.  **Stay secure**: Manage permissions and review sensitive changes carefully

The more you work with agents, the better you'll get at communicating with them. Start with small tasks, build confidence, and gradually take on more complex challenges.