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.
Core Principle: Managing the Context Window β
Most best practices stem from one constraint: CodeBuddy's context window fills up quickly, and performance degrades accordingly.
The context window contains the entire conversation, including every message, every file CodeBuddy reads, and every command output. A single debugging session or codebase exploration can consume tens of thousands of tokens.
This matters because when context approaches capacity, CodeBuddy may start "forgetting" earlier instructions or make mistakes more frequently. The context window is the most important resource to manage.
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 MRNote: 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
/permissionsto allow common domains - Pipe in data: Run
cat error.log | codebuddyto 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
/initto 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 suiteCODEBUDDY.md loads every session, so only include broadly applicable content. For domain knowledge or workflows relevant only in specific situations, use Skills 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.mdYou 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 itCODEBUDDY.local.mdand.gitignoreit - Parent directories: For monorepos, both
root/CODEBUDDY.mdandroot/foo/CODEBUDDY.mdare automatically loaded - Subdirectories: When CodeBuddy works with files in these subdirectories, subdirectory CODEBUDDY.md files are loaded on demand
Configure Permissions β
Core Advice: Use
/permissionsto allow safe commands, or use/sandboxfor 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 lintorgit 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-permissionsin sandboxes without network access.
Learn more about configuring permissions and enabling sandboxing.
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 addto connect external tools like Notion, Figma, or your database.
Through MCP servers, 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 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.mdfiles in.codebuddy/skills/to provide CodeBuddy with domain knowledge and reusable workflows.
Skills 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 MRRun /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 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
/pluginto browse the marketplace. Plugins add skills, tools, and integrations without configuration.
Plugins 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.
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 ofbar()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 theEsckey. Context is preserved and you can redirectEsc + Escor/rewind: PressEsctwice or run/rewindto 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
/clearbetween 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
/clearfrequently 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 casesUse 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 --continueto pick up where you left off, or--resumeto 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 conversationsUse /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-jsonfor 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-jsonRun 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 -pfor each. Use--allowedToolsto 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 *)"
done3. 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_commandUse --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-permissionsin 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 - Get started in 5 minutes
- Common Workflows - Step-by-step guides for debugging, testing, MRs, and more
- CODEBUDDY.md Memory Management - Store project conventions and persistent context
- Skills System - Extend AI expertise
- Settings Configuration - Configure CodeBuddy Code behavior
- CLI Reference - Complete command line reference
Master these best practices and make CodeBuddy Code your most capable programming companion