Skip to main content

README

GitLab Duo Foundational Agents & Flows

Last Updated: January 7, 2026 GitLab Version: 18.8+ (GA Release) Model: Anthropic Claude Sonnet 4.5

Overview

GitLab Duo Agent Platform reached General Availability (GA) in January 2026 with GitLab 18.8. The platform introduces 3 foundational agents and 4 foundational flows that provide AI-powered assistance throughout the software development lifecycle.

Key Capabilities

  • Autonomous Task Execution: Agents can break down complex requests into subtasks and execute them independently
  • Tool Integration: Native integration with GitLab APIs, Git operations, and external tools
  • Context-Aware: Agents maintain conversation history and project context
  • Multi-Agent Collaboration: Agents can work together on complex tasks
  • Extensible: Custom agents can be built using the platform

Foundational Agents

1. Planner Agent

Purpose: Breaks down high-level goals into actionable tasks and creates implementation plans.

Capabilities:

  • Analyzes project requirements and creates detailed implementation plans
  • Breaks down epics into issues and tasks
  • Estimates effort and identifies dependencies
  • Suggests optimal task ordering
  • Creates issue hierarchies automatically

Example Usage:

# .gitlab/agents/planner-config.yml agent: name: planner version: "1.0" model: claude-sonnet-4.5 prompts: - role: system content: | You are a software project planner. Break down user requests into: 1. Clear, actionable tasks 2. Technical requirements 3. Dependencies and ordering 4. Estimated effort actions: - name: create_issues gitlab_api: true - name: update_epic gitlab_api: true

CLI Example:

# Use Planner Agent to break down a feature request glab duo chat --agent planner \ --prompt "Create implementation plan for OAuth2 authentication system" # Output: Creates epic with child issues, estimates, and dependencies

API Integration:

// Using GitLab Agent SDK import { GitLabDuo } from '@gitlab/agent-sdk'; const duo = new GitLabDuo({ token: process.env.GITLAB_TOKEN, projectId: '12345' }); const plan = await duo.agents.planner.execute({ goal: 'Implement microservices architecture for user service', context: { technologies: ['Node.js', 'PostgreSQL', 'Redis'], constraints: ['Must maintain backward compatibility'] } }); // Returns structured plan with issues, milestones, and dependencies console.log(plan.tasks); // Array of actionable tasks console.log(plan.epic); // Epic structure console.log(plan.dependencies); // Task dependency graph

2. Security Analyst Agent

Availability: GitLab Ultimate only Purpose: Performs security analysis, vulnerability assessment, and compliance checking.

Capabilities:

  • Analyzes code for security vulnerabilities (SAST integration)
  • Reviews dependency vulnerabilities (Dependency Scanning)
  • Checks for secrets and sensitive data exposure
  • Validates compliance with security policies
  • Provides remediation guidance
  • Generates security reports

Example Configuration:

# .gitlab/agents/security-analyst-config.yml agent: name: security_analyst version: "1.0" model: claude-sonnet-4.5 tier: ultimate # Ultimate only security: scans: - sast - dependency_scanning - secret_detection - container_scanning policies: - name: critical_vulns action: block severity: critical - name: high_vulns action: warn severity: high compliance: - framework: SOC2 - framework: GDPR

MR Integration:

# .gitlab-ci.yml security_analysis: stage: test script: - glab duo agent run security_analyst \ --context merge_request \ --mr-iid $CI_MERGE_REQUEST_IID rules: - if: $CI_MERGE_REQUEST_ID allow_failure: false # Block MR if critical issues found

Example Output:

glab duo chat --agent security_analyst \ --prompt "Analyze MR !123 for security vulnerabilities" # Output: # CRITICAL: SQL Injection vulnerability detected # File: src/api/users.ts:45 # Pattern: Direct string concatenation in SQL query # Recommendation: Use parameterized queries # # HIGH: Dependency vulnerability # Package: lodash@4.17.19 # CVE: CVE-2020-8203 # Fix: Upgrade to lodash@4.17.21 # # PASSED: No secrets detected # PASSED: Container scan clean

Automated Security Reviews:

// Webhook handler for automatic security analysis import { GitLabWebhook } from '@gitlab/webhook-sdk'; const webhook = new GitLabWebhook({ secret: process.env.WEBHOOK_SECRET }); webhook.on('merge_request.opened', async (event) => { const result = await duo.agents.securityAnalyst.analyze({ mergeRequestId: event.object_attributes.iid, projectId: event.project.id }); if (result.criticalIssues.length > 0) { // Block MR await duo.mergeRequests.addNote({ projectId: event.project.id, mergeRequestIid: event.object_attributes.iid, body: ` Security issues found:\n${result.summary}` }); // Update approval status await duo.mergeRequests.updateApprovalState({ projectId: event.project.id, mergeRequestIid: event.object_attributes.iid, approved: false }); } });

3. Data Analyst Agent

Purpose: Performs data analysis, generates insights, and creates visualizations from project data.

Capabilities:

  • Analyzes CI/CD metrics and performance data
  • Generates DORA metrics reports
  • Analyzes issue and MR trends
  • Creates data visualizations
  • Identifies bottlenecks and optimization opportunities
  • Queries GitLab analytics APIs

Example Usage:

# Generate DORA metrics report glab duo chat --agent data_analyst \ --prompt "Generate DORA metrics report for last quarter" # Analyze CI/CD performance glab duo chat --agent data_analyst \ --prompt "Identify pipeline bottlenecks and suggest optimizations" # Issue trend analysis glab duo chat --agent data_analyst \ --prompt "Analyze issue resolution time trends by label"

Configuration:

# .gitlab/agents/data-analyst-config.yml agent: name: data_analyst version: "1.0" model: claude-sonnet-4.5 data_sources: - gitlab_api - value_stream_analytics - ci_cd_analytics - issue_analytics visualizations: - type: chart library: plotly - type: dashboard tool: grafana queries: dora_metrics: - deployment_frequency - lead_time_for_changes - time_to_restore_service - change_failure_rate

API Integration:

// Generate custom analytics report const report = await duo.agents.dataAnalyst.generateReport({ type: 'dora_metrics', timeRange: { start: '2025-10-01', end: '2025-12-31' }, groupBy: 'week', projects: ['12345', '67890'] }); // Returns structured data + visualizations console.log(report.metrics.deploymentFrequency); // 15.3 per week console.log(report.metrics.leadTime); // 2.5 days console.log(report.visualizations.chart); // Plotly JSON console.log(report.recommendations); // AI-generated insights

Dashboard Integration:

# .gitlab/dashboards/team-metrics.yml title: "Team Performance Dashboard" panels: - title: "DORA Metrics" agent: data_analyst query: | Generate DORA metrics for the last 30 days grouped by week with trend analysis refresh: 1h - title: "MR Resolution Time" agent: data_analyst query: | Calculate average MR time-to-merge by label and author refresh: 6h - title: "Pipeline Performance" agent: data_analyst query: | Analyze pipeline duration trends and identify slowest jobs refresh: 1h

Foundational Flows

Foundational flows are pre-built multi-agent workflows that orchestrate multiple agents to accomplish complex tasks.

1. Software Development Flow

Purpose: End-to-end software development workflow from concept to deployment.

Agents Used: Planner Code Generator Security Analyst Reviewer

Workflow Stages:

  1. Planning: Planner Agent breaks down requirements
  2. Implementation: Code generation and scaffolding
  3. Security: Security Analyst performs vulnerability scan
  4. Review: Automated code review with suggestions
  5. Testing: Test generation and execution
  6. Documentation: Auto-generate docs from code
  7. Deployment: CI/CD pipeline execution

Configuration:

# .gitlab/flows/software-development.yml flow: name: software_development version: "1.0" stages: - name: planning agent: planner inputs: - user_requirements outputs: - implementation_plan - task_breakdown - name: implementation agent: code_generator inputs: - implementation_plan outputs: - source_code - tests - name: security_scan agent: security_analyst inputs: - source_code outputs: - security_report gates: - critical_vulns: 0 - high_vulns: max 2 - name: code_review agent: reviewer inputs: - source_code - security_report outputs: - review_comments - approval_status - name: documentation agent: doc_generator inputs: - source_code outputs: - api_docs - user_guide - name: deployment agent: deployer inputs: - source_code - approval_status outputs: - deployment_url

CLI Execution:

# Start the full development flow glab duo flow run software_development \ --input "Build REST API for user management" \ --context project_id=12345 \ --interactive # Flow will: # 1. Create implementation plan # 2. Generate code scaffolding # 3. Run security scans # 4. Perform code review # 5. Generate documentation # 6. Create MR with all artifacts

API Integration:

// Execute flow programmatically const result = await duo.flows.softwareDevelopment.execute({ requirements: ` Create a REST API for user management with: - CRUD operations for users - JWT authentication - Role-based access control - PostgreSQL database `, options: { autoCreateMR: true, targetBranch: 'main', assignee: '@me' } }); // Monitor flow progress result.on('stage_complete', (stage) => { console.log(` ${stage.name} completed`); }); result.on('error', (error) => { console.error(` Error in ${error.stage}: ${error.message}`); }); // Wait for completion await result.waitForCompletion(); console.log(`MR created: ${result.mergeRequest.url}`);

2. Developer Flow (Issue to MR)

Purpose: Automated workflow from issue creation to merge request.

Workflow:

  1. Issue Analysis: Parse issue description and extract requirements
  2. Branch Creation: Create feature branch from issue
  3. Implementation: Generate initial code implementation
  4. Testing: Create test cases
  5. MR Creation: Open merge request with description
  6. Review Assignment: Auto-assign reviewers based on code owners

Configuration:

# .gitlab/flows/developer-flow.yml flow: name: developer_flow version: "1.0" trigger: issue.labeled labels: - "workflow::automated" stages: - name: analyze_issue agent: planner extract: - requirements - acceptance_criteria - technical_constraints - name: create_branch gitlab_api: branches.create branch_name: "${issue.iid}-${issue.slug}" ref: main - name: implement agent: code_generator inputs: - requirements outputs: - source_files - name: generate_tests agent: test_generator coverage_target: 80 - name: create_mr gitlab_api: merge_requests.create source_branch: "${issue.branch}" target_branch: main title: "Resolve \"${issue.title}\"" description: | Closes #${issue.iid} ## Implementation ${implementation.summary} ## Testing ${tests.coverage}% coverage ## Checklist - [x] Tests added - [x] Documentation updated - [ ] Reviewed by code owner

Label-Triggered Automation:

# Add label to issue to trigger flow glab issue update 456 --add-label "workflow::automated" # Flow automatically: # 1. Analyzes issue requirements # 2. Creates branch: 456-add-oauth-support # 3. Generates implementation code # 4. Creates comprehensive tests # 5. Opens MR with full description # 6. Assigns code owners for review

Webhook Integration:

// Trigger flow on issue creation webhook.on('issue.opened', async (event) => { // Check if issue has automation label if (event.labels.includes('workflow::automated')) { const flowResult = await duo.flows.developerFlow.execute({ issueId: event.object_attributes.iid, projectId: event.project.id }); // Post update to issue await duo.issues.addNote({ projectId: event.project.id, issueIid: event.object_attributes.iid, body: ` Developer Flow started: ${flowResult.status_url}` }); } });

3. Code Review Flow

Purpose: Automated code review with AI assistance.

Agents Used: Security Analyst Code Reviewer Test Analyzer

Review Aspects:

  1. Security: Vulnerability scanning and secret detection
  2. Quality: Code smells, complexity, maintainability
  3. Best Practices: Language-specific conventions
  4. Test Coverage: Adequacy of test cases
  5. Documentation: Completeness of comments and docs
  6. Performance: Potential optimization opportunities

Configuration:

# .gitlab/flows/code-review.yml flow: name: code_review version: "1.0" trigger: merge_request.opened stages: - name: security_review agent: security_analyst blocking: true checks: - sast - secret_detection - dependency_scanning - name: code_quality agent: code_reviewer checks: - complexity - duplication - code_smells - best_practices thresholds: complexity: 15 duplication: 5% - name: test_review agent: test_analyzer requirements: - coverage: 80% - unit_tests: required - integration_tests: recommended - name: documentation_review agent: doc_reviewer checks: - public_api_documented - readme_updated - changelog_entry - name: generate_summary agent: summarizer outputs: - review_summary - approval_recommendation actions: on_critical_issues: - block_mr - notify_author - assign_security_team on_minor_issues: - add_comments - suggest_improvements on_pass: - approve_mr - notify_author

MR Widget Integration:

The Code Review Flow results are displayed directly in the GitLab MR interface:


   AI Code Review Summary                            

   Security: No issues found                         
    Quality: 3 minor issues                          
   Tests: 85% coverage (exceeds 80% requirement)     
    Documentation: README needs update               

  Recommendation: APPROVE with minor changes           

CLI Usage:

# Manually trigger code review glab duo flow run code_review --mr 123 # Review specific files glab duo flow run code_review --mr 123 \ --files "src/api/*.ts" # Custom review focus glab duo flow run code_review --mr 123 \ --focus security,performance

4. CI/CD Conversion Flow

Purpose: Convert existing CI/CD configurations to GitLab CI/CD format.

Supported Sources:

  • Jenkins (Jenkinsfile)
  • GitHub Actions (.github/workflows)
  • CircleCI (.circleci/config.yml)
  • Travis CI (.travis.yml)
  • Azure Pipelines (azure-pipelines.yml)

Conversion Capabilities:

  1. Pipeline Structure: Jobs, stages, dependencies
  2. Environment Variables: Secrets and configuration
  3. Matrix Builds: Parallel execution strategies
  4. Caching: Dependency caching optimization
  5. Artifacts: Build artifact management
  6. Deployment: Environment-specific deployments
  7. Triggers: Branch rules, scheduled pipelines
  8. Services: Database and service containers

Configuration:

# .gitlab/flows/cicd-conversion.yml flow: name: cicd_conversion version: "1.0" inputs: - source_file - source_platform stages: - name: parse_source agent: cicd_parser outputs: - pipeline_structure - jobs - dependencies - name: map_to_gitlab agent: cicd_mapper mapping_rules: - github_actions_to_gitlab - jenkins_to_gitlab outputs: - gitlab_ci_config - name: optimize agent: cicd_optimizer optimizations: - parallel_jobs - caching_strategy - artifact_management - name: validate gitlab_ci: lint - name: generate_documentation agent: doc_generator outputs: - migration_guide - differences_summary

Example: GitHub Actions to GitLab CI

Input (GitHub Actions):

# .github/workflows/ci.yml name: CI on: [push, pull_request] jobs: test: runs-on: ubuntu-latest strategy: matrix: node-version: [14, 16, 18] steps: - uses: actions/checkout@v2 - name: Use Node.js ${{ matrix.node-version }} uses: actions/setup-node@v2 with: node-version: ${{ matrix.node-version }} - run: npm ci - run: npm test - run: npm run build

CLI Conversion:

# Convert GitHub Actions to GitLab CI glab duo flow run cicd_conversion \ --source .github/workflows/ci.yml \ --platform github_actions \ --output .gitlab-ci.yml # Review and apply glab duo flow conversion review glab duo flow conversion apply

Output (GitLab CI):

# .gitlab-ci.yml (generated) stages: - test - build variables: npm_config_cache: "$CI_PROJECT_DIR/.npm" .test_template: stage: test image: node:${NODE_VERSION} cache: key: ${CI_COMMIT_REF_SLUG}-${NODE_VERSION} paths: - .npm/ - node_modules/ before_script: - npm ci script: - npm test rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event" - if: $CI_COMMIT_BRANCH test:node-14: extends: .test_template variables: NODE_VERSION: "14" test:node-16: extends: .test_template variables: NODE_VERSION: "16" test:node-18: extends: .test_template variables: NODE_VERSION: "18" build: stage: build image: node:18 dependencies: - test:node-18 script: - npm ci - npm run build artifacts: paths: - dist/ expire_in: 1 week rules: - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

Migration Report:

# CI/CD Migration Report ## Conversion Summary - Source: GitHub Actions (.github/workflows/ci.yml) - Target: GitLab CI/CD (.gitlab-ci.yml) - Status: Successfully converted ## Changes & Improvements ### Matrix Strategy - Converted to parallel jobs with GitLab CI - Optimized: Uses job templates for DRY configuration - Performance: Added npm caching (reduces build time ~40%) ### Caching Strategy - Added npm_config_cache for faster dependency installation - Cache key includes branch name and Node version - Estimated time savings: 2-3 minutes per pipeline ### Rules & Triggers - Converted GitHub Actions triggers to GitLab rules - Runs on: merge requests, branch commits - Build artifacts only on default branch ### Recommendations 1. Consider using GitLab CI/CD Components for reusability 2. Add SAST scanning (available in your GitLab tier) 3. Enable merge trains for better CI efficiency 4. Add deployment stages for staging/production ## Next Steps 1. Review generated .gitlab-ci.yml 2. Test pipeline with: `glab ci lint` 3. Create MR to replace GitHub Actions 4. Monitor first pipeline run 5. Archive .github/workflows/ directory

API Integration:

// Convert CI/CD programmatically const conversion = await duo.flows.cicdConversion.execute({ sourceFile: '.github/workflows/ci.yml', sourcePlatform: 'github_actions', options: { optimize: true, addGitLabFeatures: ['sast', 'dependency_scanning'], generateDocs: true } }); console.log(conversion.gitlabCi); // Generated .gitlab-ci.yml content console.log(conversion.migrationGuide); // Migration documentation console.log(conversion.improvements); // List of optimizations applied

Agent Platform Architecture

Model Configuration

All foundational agents use Anthropic Claude Sonnet 4.5 as the default LLM:

# Global agent configuration agents: default_model: claude-sonnet-4.5 provider: anthropic models: claude-sonnet-4.5: context_window: 200000 output_tokens: 8192 temperature: 0.2 # Low temperature for consistent output fallback: model: claude-haiku-4.0 trigger: rate_limit_exceeded

Authentication & Authorization

OIDC Token-Based Authentication:

# .gitlab-ci.yml agent_execution: id_tokens: GITLAB_OIDC_TOKEN: aud: https://gitlab.com script: - glab duo agent run planner \ --auth-token $GITLAB_OIDC_TOKEN \ --prompt "Plan feature implementation"

Permission Scopes:

# .gitlab/agents/permissions.yml agents: planner: permissions: - read_issues - create_issues - read_epics - create_epics security_analyst: permissions: - read_code - read_vulnerabilities - create_vulnerabilities - read_merge_requests data_analyst: permissions: - read_analytics - read_ci_cd_analytics - read_value_stream_analytics

Tool Integration

Agents can use GitLab-provided tools and external tools:

# .gitlab/agents/tools.yml tools: gitlab: - issues_api - merge_requests_api - ci_cd_api - analytics_api - repository_api external: - name: jira type: mcp_server url: https://mcp.jira.com - name: slack type: webhook url: https://hooks.slack.com/services/... - name: custom_linter type: executable command: ./scripts/lint.sh

Monitoring & Observability

Tracing Agent Execution:

# .gitlab/agents/observability.yml observability: tracing: enabled: true provider: opentelemetry endpoint: https://otel-collector.gitlab.com metrics: - agent_execution_time - agent_success_rate - tool_call_duration - token_usage logging: level: info structured: true destination: gitlab_logs

View Agent Traces:

# View agent execution traces glab duo traces --agent planner --last 24h # View specific execution glab duo trace show abc123-def456 # Export traces for analysis glab duo traces export --format json > traces.json

Best Practices

1. Agent Selection

Use Planner Agent when:

  • Breaking down large features or epics
  • Creating implementation roadmaps
  • Estimating project timelines
  • Identifying task dependencies

Use Security Analyst Agent when (Ultimate only):

  • Reviewing merge requests for vulnerabilities
  • Auditing codebase security posture
  • Validating compliance requirements
  • Generating security reports

Use Data Analyst Agent when:

  • Generating DORA metrics
  • Analyzing team performance
  • Identifying CI/CD bottlenecks
  • Creating data visualizations

2. Flow Configuration

Optimize Flow Performance:

# Use parallel stages where possible stages: - name: parallel_checks parallel: - security_scan - code_quality - test_coverage wait: all # Wait for all parallel stages - name: review depends_on: parallel_checks

Error Handling:

# Graceful error handling stages: - name: risky_operation agent: custom_agent on_error: action: retry max_retries: 3 backoff: exponential on_failure: action: notify channels: - slack: #dev-alerts - gitlab_issue: labels: ["agent-failure", "needs-investigation"]

3. Token Usage Optimization

Control Token Consumption:

# .gitlab/agents/token-limits.yml agents: planner: max_input_tokens: 50000 max_output_tokens: 4096 security_analyst: max_input_tokens: 100000 # Needs more context for code analysis max_output_tokens: 8192 data_analyst: max_input_tokens: 75000 max_output_tokens: 4096 cost_controls: daily_token_limit: 1000000 alert_threshold: 80% auto_pause: true

Monitor Usage:

# View token usage by agent glab duo usage --agent planner --timeframe 7d # Cost analysis glab duo cost-analysis --group blueflyio --month 2025-12

4. Security Considerations

Secrets Management:

# Never expose secrets to agents agents: security_analyst: secrets: allowed: false # Agent cannot access CI/CD variables data_access: code: read_only variables: deny tokens: deny

Audit Logging:

# Enable comprehensive audit logs audit: log_all_agent_actions: true log_tool_calls: true log_llm_prompts: false # Don't log sensitive prompts retention_days: 90

5. Testing Agents

Test Agent Configuration:

# .gitlab/agents/test-config.yml test_mode: enabled: true mock_llm: true # Use mock responses instead of real LLM mock_tools: true # Mock tool calls mock_responses: planner: - scenario: "simple_feature" response: | Implementation Plan: 1. Create database schema 2. Implement API endpoints 3. Add tests

Run Agent Tests:

# Test agent configuration glab duo test --agent planner --scenario simple_feature # Validate flow configuration glab duo flow validate software_development # Dry run (no actual actions) glab duo flow run developer_flow --dry-run --issue 123

Migration from Other Platforms

From GitHub Copilot Workspace

GitHub Copilot Workspace users can migrate to GitLab Duo:

# Export Copilot configuration gh copilot config export > copilot-config.json # Convert to GitLab Duo format glab duo migrate --from github_copilot \ --config copilot-config.json \ --output .gitlab/agents/ # Test migrated agents glab duo test --all-agents

From Jenkins + Plugins

Jenkins automation can be migrated to GitLab Agent Platform:

# Convert Jenkinsfile + plugins to GitLab Duo flows glab duo flow convert \ --from jenkins \ --jenkinsfile Jenkinsfile \ --output .gitlab/flows/ # The conversion handles: # - Pipeline stages GitLab CI stages # - Jenkins plugins GitLab Duo agents or tools # - Groovy scripts Agent prompts or bash scripts

Resources

Documentation

Training & Examples

Support

Next Steps

  1. Enable GitLab Duo: Settings GitLab Duo Enable Agent Platform
  2. Configure First Agent: Start with Planner Agent for issue breakdown
  3. Setup Developer Flow: Automate issue-to-MR workflow
  4. Enable Security Scans: Configure Security Analyst for MR reviews
  5. Monitor Usage: Track agent execution and token usage
  6. Optimize Flows: Iterate based on team feedback and metrics

Related Documentation: