# CodeBuddy Code Best Practices

> From configuring your environment to parallel scaling, master the techniques and patterns that make CodeBuddy Code work at its best.

CodeBuddy Code is an intelligent programming environment. Unlike traditional Q&A assistants, CodeBuddy can read files, execute commands, modify code, and autonomously solve problems while you observe, guide, or step away.

This changes how you work. Instead of writing code yourself and asking for review, you describe goals and let CodeBuddy explore, plan, and implement.

This guide covers patterns that have proven effective across various codebases, languages, and environments.


## Give CodeBuddy Ways to Verify Its Work

> **Core Advice**: Provide tests, screenshots, or expected outputs so CodeBuddy can self-check. This is the single practice that improves results the most.

CodeBuddy performs significantly better when it can verify its own work—running tests, comparing screenshots, validating outputs.

Without clear success criteria, it may produce results that look correct but don't actually work. You become the only feedback loop, and every mistake requires your attention.

| Strategy | Before | After |
|----------|--------|-------|
| **Provide verification criteria** | *"Implement a function that validates emails"* | *"Write a validateEmail function. Test cases: user@example.com returns true, invalid returns false, user@.com returns false. Run the tests after implementing"* |
| **Verify UI changes visually** | *"Make the dashboard look better"* | *"[paste screenshot] Implement this design. After finishing, take a screenshot and compare with the original, list differences and fix them"* |
| **Address root causes** | *"Build is failing"* | *"Build is failing, error message: [paste error]. Fix it and verify the build succeeds. Address the root cause, don't just suppress the error"* |

Verification can be a test suite, linter, or Bash command that checks output. Invest time to make verification reliable.

---

## Explore First, Plan Second, Code Third

> **Core Advice**: Separate research and planning from implementation to avoid solving the wrong problem.

Having CodeBuddy code directly may produce code that solves the wrong problem. Use plan mode to separate exploration from execution.

The recommended workflow has four phases:

### 1. Explore

Enter plan mode. CodeBuddy reads files and answers questions but doesn't make any changes.

```
> Read src/auth and understand how we handle sessions and login.
> Also look at how we manage environment variables for keys.
```

### 2. Plan

Have CodeBuddy create a detailed implementation plan.

```
> I want to add OAuth login. What files need to be modified? What's the session flow? Create a plan.
```

Press `Ctrl+G` to open the plan in a text editor and edit directly before CodeBuddy continues.

### 3. Implement

Switch back to normal mode and let CodeBuddy code, validating against the plan.

```
> Implement the OAuth flow according to your plan. Write tests for the callback handler, run the test suite and fix any failures.
```

### 4. Commit

Have CodeBuddy commit with a descriptive message and create an MR.

```
> Commit with a descriptive message and open an MR
```

> **Note**: Plan mode is useful but adds overhead. For tasks with clear scope and small modifications (like fixing typos, adding log lines, renaming variables), let CodeBuddy execute directly. Planning is most valuable when you're uncertain about the approach, changes span multiple files, or you're unfamiliar with the code being modified.

---

## Provide Specific Context in Prompts

> **Core Advice**: The more precise your instructions, the fewer corrections needed.

CodeBuddy can infer intent but can't read minds. Reference specific files, mention constraints, point to example patterns.

| Strategy | Before | After |
|----------|--------|-------|
| **Scope the task** | *"Add tests for foo.py"* | *"Write tests for foo.py covering edge cases for user logout. Avoid using mocks"* |
| **Point to sources** | *"Why is ExecutionFactory's API so weird?"* | *"Look at ExecutionFactory's git history and summarize how its API evolved"* |
| **Reference existing patterns** | *"Add a calendar component"* | *"Look at how existing components on the homepage are implemented to understand the pattern. HotDogWidget.php is a good example. Follow this pattern to implement a new calendar component that supports month selection and year navigation. Build from scratch, don't use libraries beyond what the codebase already has"* |
| **Describe symptoms** | *"Fix the login bug"* | *"Users report login fails after session timeout. Check the authentication flow in src/auth/, especially token refresh. Write a failing test that reproduces the issue, then fix it"* |

Vague prompts are also useful during exploration, where iteration is acceptable. Prompts like `"What would you improve about this file?"` can surface questions you didn't know to ask.

### Provide Rich Content

> **Core Advice**: Use `@` to reference files, paste screenshots/images, or pipe in data directly.

You can provide rich data to CodeBuddy in multiple ways:

- **Reference files with `@`**: CodeBuddy reads files before responding, no need to describe code locations
- **Paste images directly**: Copy/paste or drag-drop images into prompts
- **Provide URLs**: Links to documentation and API references. Use `/permissions` to allow common domains
- **Pipe in data**: Run `cat error.log | codebuddy` to send file content directly
- **Let CodeBuddy fetch it**: Tell CodeBuddy to use Bash commands, MCP tools, or read files to get context

---

## Configure Your Environment

A few setup steps can make CodeBuddy Code significantly more effective across all sessions.

### Set Your Preferred Language

If you want CodeBuddy Code to always respond in a specific language (e.g., Simplified Chinese), you can set the Language option via the `/config` command:

```
> /config
# Select Language, enter your preferred language, e.g., "Simplified Chinese"
```

Or configure it directly in `~/.codebuddy/settings.json`:

```json
{
  "language": "Simplified Chinese"
}
```

After setting, CodeBuddy Code will use the specified language for all responses and explanations, while technical terms and code identifiers remain unchanged. Leave it empty to automatically detect based on your input language.

### Write an Effective CODEBUDDY.md

> **Core Advice**: Run `/init` to generate an initial CODEBUDDY.md based on your current project structure, then refine it over time.

CODEBUDDY.md is a special file CodeBuddy reads at the start of every conversation. Include Bash commands, code style, and workflow rules. This provides CodeBuddy with persistent context that **cannot be inferred from code**.

The `/init` command analyzes the codebase, detects build systems, test frameworks, and code patterns, giving you a foundation to refine.

CODEBUDDY.md has no fixed format, but keep it short and human-readable. For example:

```markdown
# Code Style
- Use ES modules (import/export) syntax, not CommonJS (require)
- Destructure imports where possible (e.g., import { foo } from 'bar')

# Workflow
- Always type-check after completing a series of code changes
- For performance, prefer running single tests over the entire test suite
```

CODEBUDDY.md loads every session, so only include broadly applicable content. For domain knowledge or workflows relevant only in specific situations, use [Skills](skills.md) instead. CodeBuddy loads them on demand without bloating every conversation.

Keep it concise. For each line, ask yourself: *"Would removing this cause CodeBuddy to make mistakes?"* If not, remove it. A bloated CODEBUDDY.md causes CodeBuddy to ignore your actual instructions.

| Should Include | Should Not Include |
|----------------|-------------------|
| Bash commands CodeBuddy can't guess | Content CodeBuddy can figure out by reading code |
| Code style rules different from defaults | Standard language conventions CodeBuddy already knows |
| Test instructions and preferred test runner | Detailed API documentation (use links instead) |
| Repository etiquette (branch naming, MR conventions) | Information that changes frequently |
| Project-specific architectural decisions | Long explanations or tutorials |
| Development environment quirks (required env vars) | File-by-file description of the codebase |
| Common pitfalls or non-obvious behavior | Self-evident practices like "write clean code" |

If CodeBuddy still does things you don't want despite having rules, the file may be too long and rules are being ignored. If CodeBuddy asks questions answered in CODEBUDDY.md, the wording may be ambiguous. Treat CODEBUDDY.md like code: review when things go wrong, regularly trim, and test changes by observing whether CodeBuddy's behavior actually changes.

You can increase compliance by adding emphasis (like "IMPORTANT" or "YOU MUST"). Commit CODEBUDDY.md to git so the team can contribute. The value of this file compounds over time.

CODEBUDDY.md files can import other files using `@path/to/import` syntax:

```markdown
See @README.md for project overview, @package.json for available npm commands.

# Additional Notes
- Git workflow: @docs/git-instructions.md
- Personal overrides: @~/.codebuddy/my-project-instructions.md
```

You can place CODEBUDDY.md files in multiple locations:

- **Home directory (`~/.codebuddy/CODEBUDDY.md`)**: Applies to all CodeBuddy sessions
- **Project root (`./CODEBUDDY.md`)**: Commit to git to share with the team, or name it `CODEBUDDY.local.md` and `.gitignore` it
- **Parent directories**: For monorepos, both `root/CODEBUDDY.md` and `root/foo/CODEBUDDY.md` are automatically loaded
- **Subdirectories**: When CodeBuddy works with files in these subdirectories, subdirectory CODEBUDDY.md files are loaded on demand

### Configure Permissions

> **Core Advice**: Use `/permissions` to allow safe commands, or use `/sandbox` for OS-level isolation. This reduces interruptions while maintaining control.

By default, CodeBuddy Code requests permission for operations that may modify the system: file writes, Bash commands, MCP tools, etc. This is safe but tedious. After the tenth approval, you're not really reviewing anymore, just clicking through. There are two ways to reduce these interruptions:

- **Permission allowlist**: Allow specific tools you know are safe (like `npm run lint` or `git commit`)
- **Sandbox**: Enable OS-level isolation that limits filesystem and network access, allowing CodeBuddy to work more freely within defined boundaries

Alternatively, use `--dangerously-skip-permissions` to bypass all permission checks, suitable for contained workflows like fixing lint errors or generating boilerplate code.

> **Warning**: Letting CodeBuddy run arbitrary commands can lead to data loss, system damage, or data exfiltration through prompt injection. Only use `--dangerously-skip-permissions` in sandboxes without network access.

Learn more about [configuring permissions](settings.md) and [enabling sandboxing](sandboxing.md).

### Use CLI Tools

> **Core Advice**: Tell CodeBuddy Code to use CLI tools like `gh`, `sentry-cli`, etc. when interacting with external services.

CLI tools are the most context-efficient way to interact with external services. If you use GitHub/GitLab, install the respective CLI. CodeBuddy knows how to use it to create issues, open MRs, and read comments. Without the CLI, CodeBuddy can still use APIs, but unauthenticated requests often hit rate limits.

CodeBuddy is also good at learning CLI tools it doesn't recognize. Try prompts like: `Use 'foo-cli-tool --help' to learn about the foo tool, then use it to solve A, B, C.`

### Connect MCP Servers

> **Core Advice**: Run `codebuddy mcp add` to connect external tools like Notion, Figma, or your database.

Through [MCP servers](mcp.md), you can have CodeBuddy implement features from issue trackers, query databases, analyze monitoring data, integrate designs from Figma, and automate workflows.

### Set Up Hooks

> **Core Advice**: Use hooks for operations that must happen every time without exception.

[Hooks](hooks-guide.md) automatically run scripts at specific points in CodeBuddy's workflow. Unlike CODEBUDDY.md instructions which are advisory, hooks are deterministic and guarantee operations happen.

CodeBuddy can write hooks for you. Try prompts like: *"Write a hook that runs eslint after every file edit"* or *"Write a hook that blocks writes to the migrations folder"*. Run `/hooks` for interactive configuration, or edit `.codebuddy/settings.json` directly.

### Create Skills

> **Core Advice**: Create `SKILL.md` files in `.codebuddy/skills/` to provide CodeBuddy with domain knowledge and reusable workflows.

[Skills](skills.md) extend CodeBuddy's knowledge with project, team, or domain-specific information. CodeBuddy automatically applies them when relevant, or you can invoke them directly with `/skill-name`.

Create skills by adding a directory with a `SKILL.md` file in `.codebuddy/skills/`:

```markdown
# .codebuddy/skills/api-conventions/SKILL.md
---
name: api-conventions
description: REST API design conventions for our services
---
# API Conventions
- Use kebab-case for URL paths
- Use camelCase for JSON properties
- Always include pagination for list endpoints
- Version APIs in URL paths (/v1/, /v2/)
```

Skills can also define repeatable workflows you invoke directly:

```markdown
# .codebuddy/skills/fix-issue/SKILL.md
---
name: fix-issue
description: Fix a GitHub issue
disable-model-invocation: true
---
Analyze and fix GitHub issue: $ARGUMENTS.

1. Use `gh issue view` to get issue details
2. Understand the problem described in the issue
3. Search for relevant files in the codebase
4. Implement necessary changes to fix the issue
5. Write and run tests to verify the fix
6. Ensure code passes lint and type checks
7. Create a descriptive commit message
8. Push and create an MR
```

Run `/fix-issue 1234` to invoke it. Use `disable-model-invocation: true` for workflows with side effects that you want to trigger manually.

### Create Custom Subagents

> **Core Advice**: Define specialized helpers in `.codebuddy/agents/` that CodeBuddy can delegate isolated tasks to.

[Subagents](sub-agents.md) run in their own context with their own set of allowed tools. They're suitable for tasks that read many files or require focus without cluttering your main conversation.

```markdown
# .codebuddy/agents/security-reviewer.md
---
name: security-reviewer
description: Review code for security vulnerabilities
tools: Read, Grep, Glob, Bash
model: opus
---
You are a senior security engineer. Review code for:
- Injection vulnerabilities (SQL, XSS, command injection)
- Authentication and authorization flaws
- Secrets or credentials in code
- Insecure data handling

Provide specific line number references and suggested fixes.
```

Explicitly tell CodeBuddy to use subagents: *"Use a subagent to review this code for security issues."*

### Install Plugins

> **Core Advice**: Run `/plugin` to browse the marketplace. Plugins add skills, tools, and integrations without configuration.

[Plugins](plugins.md) package skills, hooks, subagents, and MCP servers into single installable units provided by the community and officially. If you use typed languages, install code intelligence plugins to give CodeBuddy precise symbol navigation and automatic error detection after edits.

For guidance on choosing between skills, subagents, hooks, and MCP, see [Extending CodeBuddy Code](plugins.md).

---

## Communicate Effectively

How you communicate with CodeBuddy Code significantly affects result quality.

### Ask Questions About the Codebase

> **Core Advice**: Ask CodeBuddy questions like you would ask a senior engineer.

When familiarizing yourself with a new codebase, use CodeBuddy Code for learning and exploration. You can ask CodeBuddy the same kinds of questions you'd ask other engineers:

- How does the logging system work?
- How do I create a new API endpoint?
- What does the `async move { ... }` on line 134 of foo.rs do?
- What edge cases does CustomerOnboardingFlowImpl handle?
- Why does this code call `foo()` instead of `bar()` at line 333?

Using CodeBuddy Code this way is an effective onboarding workflow, improving ramp-up time and reducing dependency on other engineers. No special prompting techniques needed: just ask directly.

### Have CodeBuddy Interview You

> **Core Advice**: For larger features, have CodeBuddy interview you first. Start with a brief prompt and let CodeBuddy use the AskUserQuestion tool to interview you.

CodeBuddy will ask about things you may not have considered, including technical implementation, UI/UX, edge cases, and tradeoffs.

```
I want to build [brief description]. Use the AskUserQuestion tool to interview me in detail.

Ask about technical implementation, UI/UX, edge cases, concerns, and tradeoffs. Don't ask obvious questions, dig deep into difficult points I may not have considered.

Continue interviewing until we've covered everything, then write the complete spec to SPEC.md.
```

Once the spec is complete, start a new session to execute it. The new session has clean context fully focused on implementation, and you have a written spec to reference.

---

## Manage Your Sessions

Conversations are persistent and reversible. Take advantage of this!

### Correct Early and Often

> **Core Advice**: Correct CodeBuddy as soon as you notice it going off course.

The best results come from tight feedback loops. While CodeBuddy can occasionally solve problems perfectly on the first try, quick corrections usually lead to better solutions faster.

- **`Esc`**: Stop CodeBuddy midway with the `Esc` key. Context is preserved and you can redirect
- **`Esc + Esc` or `/rewind`**: Press `Esc` twice or run `/rewind` to open the rewind menu and restore previous conversation and code state
- **`"Undo that"`**: Have CodeBuddy revert its changes
- **`/clear`**: Reset context between unrelated tasks. Long sessions with irrelevant context degrade performance

If you're correcting CodeBuddy on the same issue more than twice in the same session, context is already cluttered with failed attempts. Run `/clear` and start fresh with a more specific prompt incorporating what you learned. A clean session with a better prompt almost always outperforms a long session accumulating corrections.

### Actively Manage Context

> **Core Advice**: Run `/clear` between unrelated tasks to reset context.

When you approach the context limit, CodeBuddy Code automatically compresses conversation history, preserving important code and decisions while freeing space.

In long sessions, CodeBuddy's context window can fill with irrelevant conversations, file contents, and commands. This degrades performance and sometimes distracts CodeBuddy.

- Use `/clear` frequently between tasks to completely reset the context window
- When auto-compression triggers, CodeBuddy summarizes the most important content including code patterns, file states, and key decisions
- For more control, run `/compact <instructions>`, like `/compact focus on API changes`
- Customize compression behavior in CODEBUDDY.md with instructions like `"When compressing, always preserve the complete list of modified files and any test commands"` to ensure critical context is retained

### Use Subagents for Investigation

> **Core Advice**: Delegate research with `"Use a subagent to investigate X"`. They explore in a separate context, keeping your main conversation clean for implementation.

Since context is your fundamental constraint, subagents are one of the most powerful tools available. When CodeBuddy researches the codebase, it reads many files, all consuming your context. Subagents run in a separate context window and return summaries:

```
Use a subagent to investigate how our authentication system handles token refresh,
and whether we have any existing OAuth utilities we can reuse.
```

The subagent explores the codebase, reads relevant files, and returns findings, all without cluttering your main conversation.

You can also use subagents for validation after CodeBuddy implements something:

```
Use a subagent to review this code for edge cases
```

### Use Checkpoints to Roll Back

> **Core Advice**: Every operation CodeBuddy makes creates a checkpoint. You can restore conversation, code, or both to any previous checkpoint.

CodeBuddy automatically creates checkpoints before changes. Double-tap `Escape` or run `/rewind` to open the checkpoint menu. You can restore just the conversation (keeping code changes), just the code (keeping conversation), or both.

No need to carefully plan every step—you can tell CodeBuddy to try something risky. If it doesn't work, roll back and try a different approach. Checkpoints persist across sessions, so you can close the terminal and still roll back later.

> **Warning**: Checkpoints only track changes *CodeBuddy* makes, not external processes. This is not a replacement for git.

### Resume Conversations

> **Core Advice**: Run `codebuddy --continue` to pick up where you left off, or `--resume` to select from recent sessions.

CodeBuddy Code saves conversations locally. When tasks span multiple sessions (you start a feature, get interrupted, come back the next day), you don't have to re-explain context:

```bash
codebuddy --continue    # Resume the most recent conversation
codebuddy --resume      # Select from recent conversations
```

Use `/rename` to give sessions descriptive names (`"oauth-migration"`, `"debugging-memory-leak"`) to find them later. Treat sessions like branches. Different workflows can have separate, persistent contexts.

---

## Automate and Scale

Once you can use one CodeBuddy effectively, multiply your output with parallel sessions, headless mode, and fan-out patterns.

Everything so far assumes one person, one CodeBuddy, one conversation. But CodeBuddy Code can scale horizontally. The techniques in this section show how you can accomplish more.

### Run Headless Mode

> **Core Advice**: Use `codebuddy -p "prompt"` in CI, pre-commit hooks, or scripts. Add `--output-format stream-json` for streaming JSON output.

With `codebuddy -p "your prompt"`, you can run CodeBuddy headlessly without an interactive session. Headless mode is how you integrate CodeBuddy into CI pipelines, pre-commit hooks, or any automated workflow. Output formats (plain text, JSON, streaming JSON) let you parse results programmatically.

```bash
# One-off queries
codebuddy -p "Explain what this project does"

# Structured output for scripts
codebuddy -p "List all API endpoints" --output-format json

# Streaming output for real-time processing
codebuddy -p "Analyze this log file" --output-format stream-json
```

### Run Multiple CodeBuddy Sessions

> **Core Advice**: Run multiple CodeBuddy sessions in parallel to accelerate development, run isolated experiments, or launch complex workflows.

There are two main ways to run parallel sessions:

- **Multiple terminal windows**: Start multiple CodeBuddy instances in different directories
- **Git Worktrees**: Each session works in its own isolated worktree

Beyond parallelizing work, multiple sessions enable quality-oriented workflows. Fresh context improves code review because CodeBuddy won't be biased toward code it just wrote.

For example, use a writer/reviewer pattern:

| Session A (Writer) | Session B (Reviewer) |
|--------------------|---------------------|
| `Implement a rate limiter for our API endpoints` | |
| | `Review the rate limiter implementation in @src/middleware/rateLimiter.ts. Look for edge cases, race conditions, and consistency with our existing middleware patterns.` |
| `Here's the review feedback: [Session B output]. Address these issues.` | |

You can do something similar with tests: have one CodeBuddy write tests, then another write code to pass them.

### Fan Out Across Files

> **Core Advice**: Loop over tasks, calling `codebuddy -p` for each. Use `--allowedTools` to scope permissions for batch operations.

For large migrations or analysis, you can distribute work across multiple parallel CodeBuddy invocations:

**1. Generate a task list**

Have CodeBuddy list all files that need migration (e.g., `List all 2000 Python files that need migration`)

**2. Write a script to loop over the list**

```bash
for file in $(cat files.txt); do
  codebuddy -p "Migrate $file from React to Vue. Return OK or FAIL." \
    --allowedTools "Edit,Bash(git commit *)"
done
```

**3. Test on a few files first, then run at scale**

Refine the prompt based on what goes wrong with the first 2-3 files, then run on the full set. The `--allowedTools` flag limits what CodeBuddy can do, which is important for unattended runs.

You can also integrate CodeBuddy into existing data/processing pipelines:

```bash
codebuddy -p "<your prompt>" --output-format json | your_command
```

Use `--verbose` when developing, turn it off in production.

### Safe Autonomous Mode

Use `codebuddy --dangerously-skip-permissions` to bypass all permission checks and let CodeBuddy work uninterrupted. This is suitable for workflows like fixing lint errors or generating boilerplate code.

> **Warning**: Letting CodeBuddy run arbitrary commands is risky and can lead to data loss, system damage, or data exfiltration (e.g., through prompt injection attacks). To minimize these risks, use `--dangerously-skip-permissions` in containers without network access.
>
> With sandboxing enabled (`/sandbox`), you get similar autonomy with better security. Sandboxing pre-defines boundaries rather than bypassing all checks.

---

## Avoid Common Failure Modes

These are common mistakes. Recognizing them early saves time:

### 1. Kitchen Sink Sessions

You start with one task, then ask CodeBuddy about unrelated things, then return to the first task. Context fills with irrelevant information.

**Solution**: Use `/clear` between unrelated tasks.

### 2. Repeated Corrections

CodeBuddy gets something wrong, you correct it, still wrong, you correct again. Context becomes polluted with failed attempts.

**Solution**: After two failed corrections, `/clear` and write a better initial prompt incorporating what you learned.

### 3. Over-specified CODEBUDDY.md

If your CODEBUDDY.md is too long, CodeBuddy will ignore half of it because important rules get lost in noise.

**Solution**: Trim ruthlessly. If CodeBuddy already gets it right without that instruction, remove it or convert to a hook.

### 4. Trust-Then-Verify Gap

CodeBuddy produces an implementation that looks reasonable but doesn't handle edge cases.

**Solution**: Always provide verification (tests, scripts, screenshots). If you can't verify it, don't ship it.

### 5. Infinite Exploration

You tell CodeBuddy to "investigate" something without scoping it. CodeBuddy reads hundreds of files, filling up context.

**Solution**: Scope investigations narrowly, or use subagents so exploration doesn't consume your main context.

---

## Cultivate Your Intuition

The patterns in this guide aren't set in stone. They're starting points that usually work, but may not be optimal for every situation.

Sometimes you *should* let context accumulate because you're deep into a complex problem and history is valuable. Sometimes you should skip planning and let CodeBuddy figure it out because the task is exploratory. Sometimes a vague prompt is exactly right because you want to see how CodeBuddy interprets the problem before constraining it.

Notice what works. When CodeBuddy produces great output, notice what you did: prompt structure, context you provided, mode you were in. When CodeBuddy struggles, ask why. Context too noisy? Prompt too vague? Task too big for one pass?

Over time, you'll develop intuition that no guide can capture. You'll know when to be specific and when to be open, when to plan and when to explore, when to clear context and when to let it accumulate.

---

## Related Resources

- **[Quick Start Guide](quickstart.md)** - Get started in 5 minutes
- **[Common Workflows](common-workflows.md)** - Step-by-step guides for debugging, testing, MRs, and more
- **[CODEBUDDY.md Memory Management](memory.md)** - Store project conventions and persistent context
- **[Skills System](skills.md)** - Extend AI expertise
- **[Settings Configuration](settings.md)** - Configure CodeBuddy Code behavior
- **[CLI Reference](cli-reference.md)** - Complete command line reference

---

*Master these best practices and make CodeBuddy Code your most capable programming companion*
