# CodeBuddy Code GitLab CI/CD Integration

## Overview

CodeBuddy Code supports deep integration with GitLab CI/CD, enabling you to leverage AI assistance for code review, automated implementation, and intelligent optimization tasks within your CI/CD pipelines. This integration is built on top of the CodeBuddy Code CLI, allowing you to programmatically use AI capabilities in GitLab CI jobs.


## How It Works

CodeBuddy Code leverages GitLab CI/CD to run AI tasks in isolated jobs and submit results via MRs:

1. **Event-Driven Orchestration**: GitLab listens for your chosen triggers (e.g., Issues, MRs, or @codebuddy mentions in comments). Jobs collect context and codebase information, build prompts, and run CodeBuddy Code.

2. **Sandboxed Execution**: Each interaction runs in a container with strict network and filesystem rules. CodeBuddy Code enforces workspace-scoped permission constraints on writes. Every change flows through MRs, reviewers can see diffs, and approval workflows still apply.

---

## What Can CodeBuddy Do?

CodeBuddy Code supports powerful CI/CD workflows that transform how you collaborate with code:

- Create and update MRs from Issue descriptions or comments
- Analyze performance regressions and suggest optimizations
- Implement features directly in branches, then create MRs
- Fix bugs and regressions found in tests or comments
- Respond to follow-up comments to iteratively refine requested changes

---

## Configuration Guide

### Quick Setup

The fastest way to get started is to add a minimal job to .gitlab-ci.yml and set your API key as a protected variable.

**Step 1: Add Protected CI/CD Variables**

Go to your GitLab project's **Settings → CI/CD → Variables** and add the following environment variables:

**Authentication Configuration:**

Add the following environment variables in your GitLab project's **Settings → CI/CD → Variables**:

- **CODEBUDDY_API_KEY** (Required)
  - API key for model interface calls
  - When configuring, check: ✅ Protect variable, ✅ Mask variable

**Optional Configuration:**

- **CODEBUDDY_INTERNET_ENVIRONMENT**
  - Network environment configuration (China version users need to set to `internal`, iOA users set to `iOA`)

- **CODEBUDDY_BASE_URL**
  - Custom base URL for model service (must be compatible with OpenAI API protocol)

- **GITLAB_ACCESS_TOKEN**
  - GitLab project access token (requires api scope)
  - Used for CodeBuddy to create/update MRs and comments
  - If not configured, defaults to using `CI_JOB_TOKEN`
  - When configuring, check: ✅ Protect variable, ✅ Mask variable

> 📖 **Complete Configuration Guide**: Based on your account type, refer to the corresponding configuration methods and API KEY retrieval locations:
> - **iOA Account Users** (internal company): See [Using API KEY with iOA Account](settings.md#ioa-账号使用-api-key)
> - **China Version Users**: See [Using API KEY with China Version](settings.md#中国版使用-api-key)
> - **International Version Users**: See [Using API KEY with International Version](settings.md#海外版使用-api-key)
>
> Each section includes complete environment variable configuration methods and API KEY retrieval locations.

**Step 2: Add CodeBuddy Job to .gitlab-ci.yml**

```yaml
stages:
  - ai

codebuddy:
  stage: ai
  image: node:24-alpine3.21
  # Adjust trigger rules as needed:
  # - Manual run
  # - Merge request events
  # - Triggered via Web/API when comments contain '@codebuddy'
  rules:
    - if: '$CI_PIPELINE_SOURCE == "web"'
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
  variables:
    GIT_STRATEGY: fetch
    # CODEBUDDY_API_KEY is automatically injected from CI/CD variables
    # Optional variables: CODEBUDDY_BASE_URL, GITLAB_ACCESS_TOKEN
  before_script:
    - apk update
    - apk add --no-cache git curl bash
    - npm install -g @tencent-ai/codebuddy-code
    # Verify CODEBUDDY_API_KEY is set
    - |
      if [ -z "$CODEBUDDY_API_KEY" ]; then
        echo "Error: CODEBUDDY_API_KEY is not set. Please configure it in GitLab CI/CD variables"
        exit 1
      fi
  script:
    # Optional: Start GitLab MCP server (if provided by your environment)
    - /bin/gitlab-mcp-server || true
    # Pass context through web/API trigger when using AI_FLOW_* variables
    - echo "$AI_FLOW_INPUT for $AI_FLOW_CONTEXT on $AI_FLOW_EVENT"
    - >
      codebuddy
      -p "${AI_FLOW_INPUT:-'Review this MR and implement requested changes'}"
      --permission-mode acceptEdits
      --allowedTools "Bash(*) Read(*) Edit(*) Write(*) mcp__gitlab"
      --debug
```

After adding the job and API key variable, test by manually running the job through CI/CD → Pipelines, or trigger it from an MR to have CodeBuddy propose updates in the branch and create an MR when needed.

### Manual Configuration (Recommended for Production)

If you need finer control:

1. **Add Project Credentials for GitLab API Operations**:
   - By default, uses CI_JOB_TOKEN, or create a project access token with api scope
   - If using PAT, store it as GITLAB_ACCESS_TOKEN (masked)

2. **Add CodeBuddy Job to .gitlab-ci.yml** (see example above)

3. **(Optional) Enable Mention-Driven Triggers**:
   - Add a project Webhook for "notes" to your event listener (if using)
   - Have the listener call the pipeline trigger API when comments contain @codebuddy, passing variables like AI_FLOW_INPUT and AI_FLOW_CONTEXT

---

## Usage Examples

### Transform Issue into MR

In an Issue comment:
```
@codebuddy Implement this feature based on the Issue description
```

CodeBuddy analyzes the Issue and codebase, writes changes in a branch, and creates an MR for review.

### Get Implementation Help

In an MR discussion:
```
@codebuddy Suggest a specific approach to cache the results of this API call
```

CodeBuddy proposes changes, adds appropriate caching code, and updates the MR.

### Quick Bug Fix

In an Issue or MR comment:
```
@codebuddy Fix the TypeError in the user dashboard component
```

CodeBuddy locates the bug, implements a fix, and updates the branch or creates a new MR.

---

## Best Practices

### CODEBUDDY.md Configuration

Create a CODEBUDDY.md file in your repository root to define coding standards, review criteria, and project-specific rules. CodeBuddy reads this file during execution and follows your conventions when proposing changes.

Example CODEBUDDY.md:
```markdown
# Project Coding Standards

## Code Style
- Use ESLint and Prettier for code formatting
- Follow Airbnb JavaScript Style Guide
- Use TypeScript strict mode

## Commit Conventions
- Follow Conventional Commits specification
- Use Chinese for commit messages
- Each commit should contain only one logical change

## Testing Requirements
- All new features must include unit tests
- Test coverage must be at least 80%
- Use Jest as the testing framework

## MR Review Checklist
- Code passes all CI checks
- At least one team member has approved
- Update relevant documentation
```

### Security Considerations

**Never commit sensitive information to the repository!** Always use GitLab CI/CD variables:

- Add sensitive configuration as masked variables (mark as protected if needed)
- Limit job permissions and network egress
- Review CodeBuddy's MRs as you would any other contributor's

### Performance Optimization

- Keep CODEBUDDY.md concise and clear
- Provide clear Issue/MR descriptions to reduce iterations
- Configure reasonable job timeouts to avoid runaway executions
- Cache npm and package installations in Runners (if possible)

### CI Cost Control

When using CodeBuddy Code with GitLab CI/CD, be aware of associated costs:

**GitLab Runner Time:**
- CodeBuddy runs on your GitLab Runner and consumes compute minutes
- Check your GitLab plan's Runner billing details

**Cost Optimization Recommendations:**
- Use specific @codebuddy commands to reduce unnecessary rounds
- Set appropriate --max-turns and job timeout values
- Limit concurrency to control parallel runs

### Security and Governance

- Each job runs in an isolated container with restricted network access
- CodeBuddy's changes flow through MRs, reviewers can see every diff
- Branch protection and approval rules apply to AI-generated code
- CodeBuddy Code uses workspace-scoped permissions to constrain writes

---

## Troubleshooting

### CodeBuddy Doesn't Respond to @codebuddy Commands

- Verify your pipeline is being triggered (manually, MR events, or via note event listener/Webhook)
- Ensure CI/CD variables exist and are configured correctly
- Check that comments contain @codebuddy (not /codebuddy) and your mention trigger is configured

### Job Cannot Write Comments or Create MRs

- Ensure CI_JOB_TOKEN has sufficient permissions for the project, or use a project access token with api scope
- Check that the mcp__gitlab tool is enabled in --allowedTools
- Confirm the job is running in an MR context or has sufficient context via AI_FLOW_* variables

### Authentication Errors

**Authentication Variables Not Set:**
- Confirm `CODEBUDDY_API_KEY` is added in your GitLab project's **Settings → CI/CD → Variables**
- Check the variable name spelling is correct (case-sensitive)
- If "Protect variable" is set, ensure the job runs on a protected branch

**API Authentication Failed (401 Unauthorized):**
- Verify the API key is valid and not expired
- Confirm no extra spaces or newlines were included when copying the API key
- Check the API key has sufficient permission scopes
- See [Settings Configuration Documentation](settings.md#认证配置) for detailed configuration methods

**API Connection Failed:**
- Check `CODEBUDDY_BASE_URL` is configured correctly (if using a custom endpoint)
- Verify the GitLab Runner can access the CodeBuddy API server
- Confirm the URL format is correct, including protocol (e.g., `https://api.example.com`)

**Key Visible in Logs:**
- Ensure ✅ Mask variable is checked when configuring CI/CD variables
- Avoid directly echoing or printing the API key in scripts

**GitLab Access Token Related Issues:**

- Check that the configured CI/CD variables are set correctly
- Verify the related access permission configuration
- Ensure CI_JOB_TOKEN or GITLAB_ACCESS_TOKEN has sufficient permissions (api scope)

### Job Timeout

- Increase the job's timeout configuration
- Simplify prompts to reduce processing time
- Consider breaking large tasks into multiple smaller tasks

---

## Advanced Configuration

### Common Parameters and Variables

**Environment Variables:**

CodeBuddy Code uses the following environment variables in CI/CD environments:

**Authentication Configuration:**
- `CODEBUDDY_API_KEY`: Used for model interface calls, suitable for CI/CD non-interactive environments

**Optional Configuration:**
- `CODEBUDDY_BASE_URL`: Custom base URL for model service
- `GITLAB_ACCESS_TOKEN`: GitLab API access token (for MR operations)
- `CI_JOB_TOKEN`: Job token automatically provided by GitLab CI

**Flow Control Variables:**
- `AI_FLOW_INPUT`: User input passed through Web/API triggers
- `AI_FLOW_CONTEXT`: Context information (e.g., Issue ID, MR ID, etc.)
- `AI_FLOW_EVENT`: Trigger event type (e.g., note, issue, merge_request)

> 📖 For detailed descriptions and configuration examples of each environment variable, please refer to [Settings Configuration Documentation](settings.md#环境变量)

**Command Line Parameters:**

CodeBuddy Code supports these common inputs:

- **prompt** (-p): Provide instructions inline
- **max-turns**: Limit the number of back-and-forth iterations
- **permission-mode**: Permission mode (e.g., acceptEdits)
- **allowedTools**: List of allowed tools
- **debug**: Enable debug output

**Note:** Exact flags and parameters may vary depending on @tencent-ai/codebuddy-code version. Run `codebuddy --help` in the job to see supported options.

### Customizing CodeBuddy Behavior

You can guide CodeBuddy through two main approaches:

1. **CODEBUDDY.md**: Define coding standards, security requirements, and project conventions. CodeBuddy reads this file during execution and follows your rules.

2. **Custom Prompts**: Pass task-specific instructions via prompt/prompt_file in the job. Use different prompts for different jobs (e.g., review, implementation, refactoring).

### Multi-Environment Configuration

You can configure different CodeBuddy jobs for different environments (development, testing, production):

```yaml
# Development environment - Auto-trigger
codebuddy-dev:
  stage: ai
  rules:
    - if: '$CI_COMMIT_BRANCH == "develop"'
  script:
    - codebuddy -p "Quick review and auto-merge"

# Production environment - Manual trigger
codebuddy-prod:
  stage: ai
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'
      when: manual
  script:
    - codebuddy -p "Detailed review, generate complete change report"
```

---

## Reference Resources

- [CodeBuddy Code Official Documentation](./README.md)
- [CLI Reference](cli-reference.md)
- [Settings Configuration](settings.md)
- [Common Workflows](common-workflows.md)
- [Troubleshooting](troubleshooting.md)

---

**Empower your CI/CD pipeline with AI and boost development efficiency!**
