tencent cloud

CodeBuddy Code Tutorial

Download
Focus Mode
Font Size
Last updated: 2026-09-30 18:27:33
AI-Translated & Reviewed
CodeBuddy Code is an intelligent programming environment. Unlike traditional Q&A assistants, CodeBuddy Code can read files, run commands, and modify code. Whether you are observing, providing guidance, or stepping away to do other things, it can solve problems autonomously.
This will change the way you work: instead of writing code yourself and then requesting a review, you describe the goal and let CodeBuddy Code explore, plan, and implement.
This guide brings together proven practice patterns across a variety of codebases, languages, and environments.

Core Principle: Managing the Context Window

Most practical tutorials revolve around one core constraint: the context window of CodeBuddy Code gradually fills up, and performance degrades accordingly.
The context window carries the entire conversation, including every message, every file that CodeBuddy Code reads, and the output of every command. A single debugging session or codebase exploration can consume tens of thousands of tokens.
When the context approaches saturation, CodeBuddy Code may "forget" earlier instructions or make errors more frequently. The context window is the most important resource you need to manage.

Methods for CodeBuddy Code to Verify Its Own Work

Core Recommendation:
Provide test cases, screenshots, or expected outputs so that CodeBuddy Code can verify its own work. This is the most immediate way to improve results.
When CodeBuddy Code can verify its own work, performance improves significantly—whether by running tests, comparing screenshots, or validating output results.
Without clear success criteria, it may produce code that looks correct but is actually ineffective. At that point, you become the only one who can spot the problems, and every error requires your personal investigation.
Policy
Before Improvement
After Improvement
Provide validation criteria.
Write a function to validate phone number format.
Write a validatePhone function. Test cases: 13812345678 returns true, 12345 returns false, 138-1234-5678 returns false. Run the tests after implementation.
Visually verify UI changes.
Optimize the style of this table.
[Paste screenshot] Implement according to this design. After completion, take a screenshot and compare it with the original image, list the differences, and fix them.
Resolve root causes.
Compilation failed.
Compilation failed. Error message: [paste error]. Identify the root cause and fix it. Do not just bypass the error. After fixing, confirm that compilation succeeds.
Verification can be a test suite, a linter, or a Bash command that checks the output. It is worth taking the time to make verification reliable enough.

Explore, Plan, Then Code

Core Recommendation:
Separate research, planning, and implementation to avoid solving the wrong problem.
Jumping straight into letting CodeBuddy Code write code may produce code that solves the wrong problem. Use plan mode to separate exploration from execution. The recommended workflow consists of four stages:

1. Explore

Enter plan mode. CodeBuddy Code only reads files and answers questions without making any modifications.
Read the src/payment directory to understand how we handle orders and refunds.
Also, take a look at how payment-related configurations are managed.

2. Plan

Have CodeBuddy Code output a detailed implementation plan.
I want to integrate WeChat Pay. Which files need to be modified? How does the payment flow work? Give me a detailed plan.
Press Ctrl+G to open the plan in a text editor, where you can edit it directly before CodeBuddy Code continues.

3. Implementation

Switch back to normal mode and let CodeBuddy Code implement the plan, verifying as it goes.
Implement the WeChat Pay flow according to your plan. Write tests for the callback notifications, run the test suite, and fix any failures.

4. Commit

Have CodeBuddy Code commit the code and create an MR.
Write a clear commit message, then open an MR.
Attention:
Plan mode is useful, but it comes with additional overhead. For well-scoped tasks with minimal changes, such as fixing a typo, adding a log line, or renaming a variable, you can let CodeBuddy Code execute directly. Plan mode is most valuable when you are unsure about the approach, when changes span multiple files, or when you are not familiar enough with the code to be modified.

Providing Specific Context in Prompts

Core Recommendation:
The more precise the instructions, the fewer corrections will be needed later.
CodeBuddy Code can infer intent, but it cannot read minds. Reference specific files, state the constraints, and point to sample code.
Policy
Before Improvement
After Improvement
Limit task scope.
Add tests to user_service.py.
Write tests for user_service.py, focusing on edge cases of user logout without using mocks.
Point to source.
Why is the interface design of OrderProcessor so strange?
Check the git history of OrderProcessor and summarize how this interface evolved into its current form.
Reference existing patterns.
Add a search component.
Look at how existing components in src/components are written, especially the ProductCard.vue example. Implement a search component following the same pattern, supporting keyword highlighting and search history. Use only existing dependencies in the project.
Describe symptoms.
Login has a bug.
Users report that re-login fails after token expiration. Check the authentication flow in src/auth/, focusing on the token refresh logic. First write a test that reproduces the issue, then fix it.
Vague prompts are also useful during the exploration phase, allowing for repeated experimentation. Prompts like "What do you think could be improved in this file?" can often uncover issues you had not considered.

Providing Rich Content

Core Recommendation:
Reference files with @, paste screenshots, or pipe in data.
You can provide rich context to CodeBuddy Code in several ways:
Use @ to reference files: CodeBuddy Code reads the file before responding, so you don't have to describe where the code is.
Paste images directly: Copy/paste or drag and drop images into the input box.
Provide URLs: links to documentation and API references. Use /permissions to allow common domains.
Pipe in data: Run cat error.log | codebuddy to feed the file content directly to it.
Let CodeBuddy Code fetch it itself: Tell it to use Bash commands, MCP tools, or read files to obtain the required context.

Configuring Your Environment

A few simple configuration steps can make CodeBuddy Code more efficient across all sessions.

Setting the Preferred Language

If you want CodeBuddy Code to always respond in a specific language (such as Simplified Chinese), you can set the Language option via the /config command:
> /config
# Select Language and enter your preferred language, such as "Simplified Chinese".
Or configure it directly in ~/.codebuddy/settings.json:
{
"language": "Simplified Chinese"
}
After configuration, CodeBuddy Code will use the specified language for all responses and explanations, while technical terms and code identifiers remain unchanged. If left blank, the language is automatically determined based on your input.

Writing an Effective CODEBUDDY.md

Core Recommendation:
Run /init to generate an initial CODEBUDDY.md based on the current project structure, and then refine it gradually.
CODEBUDDY.md is a special file that CodeBuddy Code reads at the start of every conversation. It contains common commands, code style guidelines, and workflow rules, providing CodeBuddy Code with persistent context that cannot be inferred from the code itself.
The /init command analyzes your codebase, detects the build system, test framework, and code patterns, and generates a foundational version for you to refine further.
CODEBUDDY.md has no fixed format. Keep it short and readable. For example:
# Code style
- Use ES module syntax (import/export) instead of CommonJS (require).
- Use destructuring when importing (for example, import { foo } from 'bar').

# Workflow
- After making code changes, remember to run a type check.
- Run individual test files first instead of running the entire test suite frequently.
CODEBUDDY.md is loaded at the start of every session, so include only content that is universally applicable. For domain knowledge or workflows that are relevant only in specific scenarios, use Skills instead. CodeBuddy Code loads them on demand, keeping every conversation lean.
Keep it concise. As you write each line, ask yourself: "Will CodeBuddy Code make a mistake if this line is omitted?" If not, delete it. If CODEBUDDY.md becomes too long, CodeBuddy Code may instead overlook your most important instructions.
Should Write
Should Not Write
Commands that CodeBuddy Code cannot guess
Things that can be understood by reading the code
Code style that differs from default conventions
Standard language conventions
Test instructions and preferred test runner
Detailed API documentation (a link is sufficient)
Repository conventions (branch naming, MR conventions)
Information that changes frequently
Project-specific architectural decisions
Lengthy explanations or tutorials
Development environment pitfalls (required environment variables and similar)
File-by-file code descriptions
Common pitfalls or non-obvious behaviors
Vague instructions such as "write clean code"
If CodeBuddy Code has rules but still does not follow them, the file may be too long and the rules may be buried. If CodeBuddy Code asks a question whose answer is clearly in CODEBUDDY.md, the wording may be ambiguous. Treat CODEBUDDY.md like Code: check it when issues arise, refine it regularly, and observe whether CodeBuddy Code's behavior actually changes after modifications.
You can use emphasis words (such as "IMPORTANT" or "must") to improve compliance. Commit CODEBUDDY.md to git so that the team can maintain it together. The value of this file will accumulate over time.
CODEBUDDY.md supports importing other files by using the @path/to/file syntax:
Check @README.md for a project overview and @package.json for available npm commands.

# Additional Notes
- Git workflow: @docs/git-workflow.md
- Personal configuration: @~/.codebuddy/my-overrides.md
CODEBUDDY.md can be placed in multiple locations:
Home directory (~/.codebuddy/CODEBUDDY.md): applies to all CodeBuddy Code sessions.
Project root directory (./CODEBUDDY.md): commit to git to share with the team, or name it CODEBUDDY.local.md and add it to .gitignore
Parent directory: suitable for monorepos, where both root/CODEBUDDY.md and root/packages/foo/CODEBUDDY.md are loaded automatically.
Subdirectory: loaded on demand when CodeBuddy Code processes files in that subdirectory.

Configuring Permissions

Core Recommendation:
Use /permissions to allow safe commands, or use /sandbox to enable system-level isolation. Reduce interruptions while maintaining control.
By default, CodeBuddy Code requests permission for operations that may modify the system, such as writing files, running commands, and calling MCP tools. This is safe, but frequent confirmations are annoying. By the tenth approval, you are no longer reading the prompts and are just mechanically clicking through. There are two ways to reduce these interruptions:
Permission allowlist: allows you to confirm specific safe commands, such as npm run lint or git commit
Sandbox mode: enables system-level isolation, limits file system and network access, and allows CodeBuddy Code to work more freely within defined boundaries.
You can also use --dangerously-skip-permissions to skip all permission checks, which is suitable for closed workflows such as fixing lint errors or generating boilerplate code.
Warning:
Allowing CodeBuddy Code to run commands freely may lead to data loss, system damage, or data leakage through prompt injection. --dangerously-skip-permissions should only be used in a sandboxed environment without network access.

Using CLI Tools

Core Recommendation:
When interacting with external services, have CodeBuddy Code use CLI tools such as gh, glab, and sentry-cli.
CLI tools are the most context-efficient way to interact with external services. If you use GitHub or GitLab, install the corresponding CLI. CodeBuddy Code knows how to use it to create issues, open MRs, and read comments. Without a CLI, CodeBuddy Code can also call APIs directly, but unauthenticated requests can easily trigger rate limiting.
CodeBuddy Code is also good at learning unfamiliar CLI tools. Try a prompt like this: First use 'some-cli --help' to learn about the tool, then use it to accomplish X, Y, and Z.

Connecting to an MCP Server

Core Recommendation:
Run codebuddy mcp add to connect external tools such as Notion, Figma, or databases.
Through MCP servers, CodeBuddy Code can directly pull requirements from issue systems, query databases, analyze monitoring data, and integrate Figma designs to automate workflows.

Setting Up Hooks

Core Recommendation:
Use hooks for operations that must run every time without exception.
Hooks automatically run scripts at specific points in the CodeBuddy Code workflow. Unlike the instructions in CODEBUDDY.md, which are merely "suggestions", hooks are deterministic and guaranteed to execute.
CodeBuddy Code can help you write hooks. Try prompts like this: "Write a hook that automatically runs eslint after each file edit" or "Write a hook that blocks writes to the migrations directory". Run /hooks for interactive configuration, or directly edit .codebuddy/settings.json.

Creating Skills

Core Recommendation:
Create a SKILL.md file in the .codebuddy/skills/ directory to supplement CodeBuddy Code with domain knowledge and reusable workflows.
Skills can extend CodeBuddy Code's capabilities with project-, team-, or domain-specific information. CodeBuddy Code automatically applies them in relevant scenarios, and you can also invoke them manually with /skill-name.
Create a directory under .codebuddy/skills/ and place a SKILL.md file in it to create a skill:
# .codebuddy/skills/api-conventions/SKILL.md
---
name: api-conventions
description: REST API design specifications for our service
---
# API Specification
- Use kebab-case for URL paths.
- Use camelCase for JSON fields.
- List APIs must support pagination.
- Place the API version in the URL path (/v1/, /v2/).
Skills can also define reusable workflows:
# .codebuddy/skills/fix-issue/SKILL.md
---
name: fix-issue
description: Fix GitLab issues
disable-model-invocation: true
---
Analyze and fix the GitLab issue: $ARGUMENTS.

1. Use `glab issue view` to obtain issue details.
2. Understand the problem description.
3. Search the codebase for relevant files.
4. Implement the fix.
5. Write tests and run verification.
6. Ensure that lint and type checks pass.
7. Write a clear commit message.
8. Push and create an MR.
Run /fix-issue 1234 to invoke it. For workflows with side effects, add disable-model-invocation: true to ensure they can only be triggered manually.

Creating a Custom Subagent

Core Recommendation:
Define specialized assistants in .codebuddy/agents/, and CodeBuddy Code can delegate specific tasks to them.
Subagents run in isolated contexts with their own tool permission sets. They are suitable for tasks that require reading a large number of files or focused execution, and they do not interfere with your main conversation.
# .codebuddy/agents/security-reviewer.md
---
name: security-reviewer
description: Review code for security vulnerabilities.
tools: Read, Grep, Glob, Bash
model: claude-sonnet-4-20250514
---
You are a senior security engineer. When reviewing code, focus on the following:
- Injection vulnerabilities (SQL injection, XSS, command injection)
- Authentication and authorization flaws
- Hardcoded keys or credentials in the code
- Insecure data handling

Provide the specific line numbers and fix suggestions.
Explicitly tell CodeBuddy Code to use a subagent: "Use a subagent to review the security issues in this code."

Installing the Plugin

Core Recommendation:
Run /plugin to browse the plugin marketplace. Plugins can add skills, tools, and integrations with one click, with no additional configuration required.
Plugins package skills, hooks, subagents, and MCP servers into an installable unit, provided by the community and official sources. If you are using a typed language, you can install a code intelligence plugin to give CodeBuddy Code precise symbol navigation and automatic error detection after editing.
For guidance on choosing between skills, subagents, hooks, and MCP, see Extending CodeBuddy Code.

Effective Communication

How you communicate with CodeBuddy Code directly affects the quality of its output.

Asking Questions About the Codebase

Core Recommendation:
Ask CodeBuddy Code as you would ask a senior engineer.
When getting familiar with a new codebase, use CodeBuddy Code as a learning and exploration tool. You can ask it the questions you would otherwise ask your colleagues:
How does the logging system work?
How do I create an API?
What does defer func() { ... }() on line 78 of handler.go do?
What edge cases does PaymentService handle?
Why is processAsync() called here instead of processSync()?
This is a highly efficient onboarding approach that shortens ramp-up time and reduces interruptions to your colleagues. No special skills are required—just ask directly.

Having CodeBuddy Code Interview You

Core Recommendation:
Before building a major feature, let CodeBuddy Code interview you first. Start with a brief description, and let it use the AskUserQuestion tool to dig into the details.
CodeBuddy Code will ask questions you may not have considered, covering technical implementation, user experience, edge cases, and various trade-offs.
I want to build a [brief description]. Interview me in detail using the AskUserQuestion tool.
Ask about technical approaches, user experience, edge cases, potential risks, and trade-offs. Don't ask obvious questions—dig into the difficult points I may not have considered.
Keep asking until we have covered all aspects, and then write the complete requirements specification to SPEC.md.
After the specification is complete, start a new session to implement it. A new session provides clean context so you can focus on implementation, and you have the written specification to refer to at any time.

Managing Your Sessions

Conversations are persistent and reversible. Make good use of this!

Correct Early, Correct Often

Core Recommendation:
As soon as you notice CodeBuddy Code going off track, correct it immediately.
Good results come from tight feedback loops. Although CodeBuddy Code can sometimes get it right in one go, quick corrections often lead to better solutions faster.
Esc: Press the Esc key to interrupt CodeBuddy Code mid-task. The context will be preserved, so you can redirect it.
Esc + Esc or /rewind: Press Esc twice or run /rewind to open the rewind menu and restore the previous conversation and code state.
Undo the recent changes: have CodeBuddy Code roll back its modifications.
/clear: Clear the context between unrelated tasks. Stuffing too much irrelevant content into the context will slow things down.
If you have corrected the same issue twice and it is still wrong, the context is likely cluttered with failed attempts. At this point, run /clear and start over with a clearer prompt, incorporating what you have learned. A clean session with a better prompt almost always yields better results than a long session with repeated corrections.

Managing Context Proactively

Core Recommendation:
Run /clear to clear the context when switching tasks.
When the context is nearly full, CodeBuddy Code automatically compresses the conversation history, preserving important code and decisions while freeing up space.
In long sessions, the context window of CodeBuddy Code can become cluttered with irrelevant conversations, file contents, and command output. This slows things down and can sometimes distract it.
Use /clear frequently between tasks to thoroughly clear the context.
When automatic compression is triggered, CodeBuddy Code summarizes the most important content, including code patterns, file states, and key decisions.
For finer-grained control, run /compact <instruction>, for example /compact keep only API-related changes.
You can also specify compression rules in CODEBUDDY.md, for example "Always keep the list of modified files and test commands during compression", to ensure that critical context is not lost.

Using Subagents for Research

Core Recommendation:
Use "Send a subagent to investigate X" to delegate research tasks. Subagents work in isolated contexts and do not pollute your main conversation.
Context is the core bottleneck, and subagents are one of the key tools for addressing this issue. When CodeBuddy Code explores a codebase, it reads a large number of files, all of which consume your context. Subagents run in isolated context windows and only return a summary at the end:
Send a subagent to investigate how our authentication system handles token refresh.
Also check if there are any existing OAuth tools that can be reused.
Subagents dive deep into the codebase, read relevant files, and then report their findings — all without disrupting your main conversation.
You can also use a subagent to verify a feature after CodeBuddy Code has implemented it:
Send a subagent to check the edge cases of this code.

Using Checkpoints for Rollback

Core Recommendation:
Every operation in CodeBuddy Code creates a checkpoint. You can restore the conversation, the code, or both together to any previous state.
CodeBuddy Code automatically creates a checkpoint before making changes. Press Escape twice or run /rewind to open the checkpoint menu. You can choose to restore only the conversation (keeping code changes), restore only the code (keeping the conversation), or restore both.
You don't need to carefully plan every step. Feel free to let CodeBuddy Code try some adventurous approaches. If they don't work, roll back and try a different approach. Checkpoints persist across sessions, so you can close the terminal and still rewind after you come back.
Warning:
Checkpoints only track changes made by CodeBuddy Code, not external processes. They cannot replace git.

Resuming a Conversation

Core Recommendation:
Run codebuddy --continue to continue the previous conversation, or use --resume to pick one from recent sessions.
CodeBuddy Code saves conversations locally. When a task spans multiple sessions (for example, you start working on a feature, get interrupted, and come back the next day to continue), you don't need to explain the context from scratch:
codebuddy --continue # Continue the most recent conversation
codebuddy --resume # Select from previous sessions
Use /rename to give a session a meaningful name (for example, "Payment Refactoring" or "Memory Leak Investigation") so you can find it later. Manage sessions like you manage git branches, with each workstream having its own independent, persistent context.

Automation and Scaling

Once you can use a single CodeBuddy Code efficiently, you can multiply your output through parallel sessions, headless mode, and script orchestration.
Everything so far has assumed a "one person, one CodeBuddy Code, one conversation" scenario. But CodeBuddy Code can scale horizontally. This section covers how to do more.

Headless Mode

Core Recommendation:
Use codebuddy -p "prompt" in CI, pre-commit hooks, or scripts. Add --output-format stream-json to get streaming JSON output.
You can run CodeBuddy Code headlessly with codebuddy -p "your prompt", without an interactive session. This is the way to integrate CodeBuddy Code into CI pipelines, pre-commit hooks, or any automated workflow. Output formats (plain text, JSON, streaming JSON) allow you to parse results programmatically.
# One-time Query
codebuddy -p "Explain what this project does"

# Structured output for easy script processing
codebuddy -p "List all API endpoints" --output-format json

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

Parallel Multi-Sessions

Core Recommendation:
Running multiple CodeBuddy Code sessions in parallel can accelerate development, run isolated experiments, or launch complex workflows.
There are two main ways to run parallel sessions:
Multiple terminal windows: launch multiple CodeBuddy Code instances in different directories
Git Worktrees: each session works in its own worktree.
Beyond parallel acceleration, multiple sessions can also enable quality-oriented workflows. Fresh context facilitates code review because CodeBuddy Code is not biased toward the code it just wrote.
For example, the "write code/review code" pattern:
Session A (Code Writing)
Session B (Code Review)
Implement a rate limiting middleware for API endpoints.
-
-
Review the rate limiter implementation in @src/middleware/rateLimiter.ts. Identify edge cases and race conditions, and check whether it is consistent with existing middleware patterns.
These are the review comments: [Output from Session B]. Address these issues.
-
You can do the same with testing: have one CodeBuddy Code write tests while another writes code to make the tests pass.

Script Orchestration

Core Recommendation:
Loop through the task list and call codebuddy -p once for each task. Use --allowedTools to limit the permission scope of batch operations.
For large-scale migrations or batch analysis, you can distribute work across multiple parallel CodeBuddy Code invocations:
1. Generate a task list.
Have CodeBuddy Code list all files that need to be processed (for example, list all 2,000 Python files that need to be migrated).
2. Write a script to loop through and process.
for file in $(cat files.txt); do
codebuddy -p "Migrate $file from a Class component to Hooks. Return OK or FAIL." \\
--allowedTools "Edit,Bash(git commit *)"
done
3. Test on a small scale first, then run at scale.
Adjust the prompts based on the execution results of the first few files, then run the full list. --allowedTools limits the tools that CodeBuddy Code can use, which is important in unattended scenarios.
You can also integrate CodeBuddy Code into your existing data processing pipelines:
codebuddy -p "<your prompt>" --output-format json | your_command
Add --verbose during development for easier debugging, and remove it in production.

Secure Autonomous Mode

You can use codebuddy --dangerously-skip-permissions to skip all permission checks, allowing CodeBuddy Code to work without interruption. This is suitable for closed workflows such as fixing lint errors or generating boilerplate code.
Warning:
Allowing CodeBuddy Code to run commands freely is risky and may lead to data loss, system damage, or data leakage through prompt injection. To reduce the risk, use --dangerously-skip-permissions in a container without network access.
With the sandbox enabled (/sandbox), you get similar autonomy with better security. The sandbox defines boundaries upfront instead of bypassing all checks.

Avoiding Common Pitfalls

These are common failure patterns. Identifying them early can save you a lot of time:

1. Irrelevant Context Interference

You start with one task, ask CodeBuddy Code about some unrelated things in between, and then return to the first task. The context becomes cluttered with irrelevant information.
Solution: Use /clear when switching tasks.

2. Repeated Corrections

CodeBuddy Code makes a mistake, you correct it, it is still wrong, and you correct it again. The context becomes polluted by failed attempts.
Solution: If two corrections don't work, use /clear and then write a better prompt that incorporates what you've learned.

3. Excessive Content in CODEBUDDY.md

If CODEBUDDY.md is too long, CodeBuddy Code will ignore half of it because important rules are buried in the noise.
Solution: Trim ruthlessly. If CodeBuddy Code does the right thing without a rule, delete it or convert it into a hook.

4. Trust Without Verification

The code produced by CodeBuddy Code looks fine, but edge cases are not actually handled.
Solution: Always provide a means of verification (tests, scripts, screenshots). Do not ship anything that cannot be verified.

5. Unbounded Exploration

You ask CodeBuddy Code to "look into" something without defining a scope. CodeBuddy Code reads hundreds of files and fills up the context.
Solution: Narrow the scope of the investigation, or use a subagent so that the exploration does not consume the main conversation's context.

Developing Your Intuition

The patterns in this guide are not dogma. They are generally effective starting points, but not necessarily the optimal solution for every scenario. Sometimes you should let context accumulate because you are digging deep into a complex problem and the history is valuable. Sometimes you should skip planning and let CodeBuddy Code explore on its own because the task itself is exploratory. Sometimes a vague prompt is exactly right because you want to see how CodeBuddy Code interprets the problem before you add constraints.
Pay attention to what works. When CodeBuddy Code produces great results, reflect on what you did: how you wrote the prompt, what context you provided, and what patterns you used. When CodeBuddy Code struggles, ask yourself why: Is the context too messy? Is the prompt too vague? Is the task too large to handle in one go?
Over time, you will develop an intuition that no guide can replace. You will know when to be specific and when to be open-ended, when to plan and when to explore, and when to clear the context and when to let it accumulate.

Help and Support

Was this page helpful?

Help us improve! Rate your documentation experience in 5 mins.

Feedback