# CI/CD Integration CKB becomes your **single source of truth for change risk** in CI/CD pipelines. Instead of treating code review as a human-only process, CKB provides precomputed analysis that travels with every PR. > **Looking for ready-to-use workflows?** See [[Workflow Examples]] for production-ready templates for GitHub Actions, GitLab CI, and local git hooks—with example PR comment outputs. > > **Want to enforce code standards?** See [[Quality Gates]] for configuring complexity, risk, coupling, and coverage gates. > > All workflow files are in the [`examples/`](https://github.com/SimplyLiz/CodeMCP/tree/master/examples) directory. --- ## Getting Started Choose a workflow based on your needs: | I want to... | Platform | Workflow | |--------------|----------|----------| | **Unified PR review (recommended)** | GitHub | [`pr-review.yml`](https://github.com/SimplyLiz/CodeMCP/blob/master/examples/github-actions/pr-review.yml) | | Use the composite GitHub Action | GitHub | [`action/ckb-review`](https://github.com/SimplyLiz/CodeMCP/tree/master/action/ckb-review) | | Individual analysis (legacy) | GitHub | [`pr-analysis.yml`](https://github.com/SimplyLiz/CodeMCP/blob/master/examples/github-actions/pr-analysis.yml) | | Customize with optional features | GitHub | [`starter-template.yml`](https://github.com/SimplyLiz/CodeMCP/blob/master/examples/github-actions/starter-template.yml) | | See all CKB capabilities | GitHub | [`full-showcase.yml`](https://github.com/SimplyLiz/CodeMCP/blob/master/examples/github-actions/full-showcase.yml) | | Use GitLab CI | GitLab | [`gitlab-ckb-review.yml`](https://github.com/SimplyLiz/CodeMCP/blob/master/ci/gitlab-ckb-review.yml) | Copy the workflow to your `.github/workflows/` (or `.gitlab-ci.yml`) and customize as needed. **Quick install** (works in any CI): ```bash npm install -g @tastehub/ckb ckb init ckb index ``` **Unified review** (recommended — replaces the HTTP API approach): ```bash # Run all 21 checks, get JSON output ckb review --ci --base=main --format=json # PR comment-ready markdown ckb review --base=main --format=markdown # GitHub Actions annotations ckb review --base=main --format=github-actions # SARIF for Code Scanning ckb review --base=main --format=sarif ``` > See [[Code Review]] for full documentation of all checks, policy configuration, and output formats. **Legacy HTTP API** (still available): ```bash ckb serve --port 8080 & curl -X POST http://localhost:8080/pr/summary \ -H "Content-Type: application/json" \ -d '{"baseBranch": "main", "headBranch": "HEAD"}' ``` --- ## What CKB Provides in CI - **Blast radius** — Know exactly what breaks before merging - **Suggested reviewers** — Based on actual code ownership, not guesswork - **Boundary detection** — Flag when "local" changes cross API contracts - **Risk scoring** — Quantified risk based on hotspots, module spread, and history - **Complexity gates** — Block merges that exceed complexity thresholds - **Coupling analysis** — Warn when tightly-coupled files change independently - **Dead code detection** — Identify unused code from static analysis - **Affected tests** — Run only tests affected by changes - **Documentation coverage** — Enforce doc coverage and detect stale references The pattern: start the server (`ckb serve`) and call the HTTP API. CLI commands are also available for local use and scripting. --- ## How It Works When you call `ckb pr-summary`, CKB: 1. **Diffs the branches** using git (base vs head) 2. **Maps files to modules** based on path structure 3. **Checks each file against hotspot data** — flags files with score > 0.5 4. **Queries ownership** for each changed file (CODEOWNERS + git-blame) 5. **Calculates risk** based on: file count, lines changed, hotspots touched, module spread 6. **Returns structured JSON** with everything a PR comment needs **Example response:** ```json { "summary": { "totalFiles": 12, "totalAdditions": 450, "totalDeletions": 120, "totalModules": 3, "hotspotsTouched": 2 }, "riskAssessment": { "level": "medium", "score": 0.45, "factors": ["Touches 2 hotspot(s)", "Spans 3 modules"], "suggestions": ["Extra review recommended for hotspot files"] }, "suggestedReviewers": [ {"owner": "@api-team", "reason": "Owns 8 of 12 changed files", "coverage": 0.67} ], "modulesAffected": [ {"moduleId": "internal/api", "filesChanged": 8, "riskLevel": "medium"} ] } ``` --- ## Installation in CI **npm (Recommended):** ```yaml - uses: actions/setup-node@v4 with: node-version: '20' - name: Install CKB run: npm install -g @tastehub/ckb ``` **npx (no install):** ```yaml - name: Run CKB run: npx @tastehub/ckb pr-summary --base=main ``` **Pre-built binary:** ```yaml - run: | curl -sSL https://github.com/SimplyLiz/CodeMCP/releases/latest/download/ckb_linux_amd64.tar.gz | tar xz sudo mv ckb /usr/local/bin/ ``` **Build from source:** ```yaml - uses: actions/setup-go@v5 with: go-version: '1.22' - run: | git clone https://github.com/SimplyLiz/CodeMCP.git /tmp/codemcp cd /tmp/codemcp && go build -o /usr/local/bin/ckb ./cmd/ckb ``` --- ## Critical: Full Git History CKB needs git history for ownership analysis. Without it, suggested reviewers will be empty. ```yaml - uses: actions/checkout@v4 with: fetch-depth: 0 # Required for git-blame analysis ``` --- ## Environment Validation Before running CKB analysis, validate that your CI environment has the required tooling: ```yaml - name: Validate CKB Environment run: | RESULT=$(ckb doctor --tier=standard --format json) MISSING=$(echo "$RESULT" | jq '[.languages[] | select(.status == "missing")] | length') if [ "$MISSING" -gt 0 ]; then echo "::warning::Missing $MISSING language tools" ckb doctor --tier=standard fi ``` ### Tier Requirements | Tier | Tools Required | Use Case | |------|---------------|----------| | `fast` | None (tree-sitter built-in) | Quick PR checks | | `standard` | SCIP indexers (scip-go, scip-typescript, etc.) | Full code intelligence | | `full` | Standard + LSP servers | Maximum accuracy | --- ## CLI Commands for CI These commands work directly without starting a server: ```bash # PR analysis ckb pr-summary --base=main --head=HEAD # Impact analysis ckb impact diff --base=main --format=json ckb impact --range=main..HEAD --format=markdown # Affected tests ckb affected-tests --range=main..HEAD --output=command # Suggested reviewers ckb reviewers --range=main..HEAD --format=gh # Complexity analysis ckb complexity internal/query/engine.go --format=json # Coupling analysis ckb coupling --files=file1.go,file2.go --min-correlation=0.7 # Risk audit ckb audit --min-score=60 --limit=20 # Dead code detection ckb dead-code --threshold=0.9 --limit=20 # Hotspots ckb hotspots --limit=20 # Ownership drift ckb ownership --drift --threshold=0.3 ``` --- ## HTTP API Endpoints Start the server first: `ckb serve --port 8080 &` | Endpoint | Method | Description | |----------|--------|-------------| | `/pr/summary` | POST | PR analysis with ownership | | `/ownership/drift` | GET | CODEOWNERS accuracy check | | `/hotspots` | GET | High-churn files | | `/architecture/refresh` | POST | Rebuild cached analysis | | `/jobs/:id` | GET | Check async job status | | `/health` | GET | Liveness probe | | `/ready` | GET | Readiness probe | | `/metrics` | GET | Prometheus metrics | | `/telemetry/dead-code` | GET | Dead code candidates | | `/meta/languages` | GET | Language quality dashboard | | `/cache/warm` | POST | Pre-warm cache | | `/cache/clear` | POST | Clear cache | | `/complexity` | GET | File complexity analysis | | `/contracts/impact` | GET | Contract change impact | **Example:** ```bash curl -s -X POST http://localhost:8080/pr/summary \ -H "Content-Type: application/json" \ -d '{"baseBranch": "main"}' ``` --- ## Incremental Indexing For Go projects, CKB supports incremental indexing that only processes changed files. This dramatically speeds up CI pipelines. | Scenario | Full Index | Incremental | |----------|------------|-------------| | Large Go project (10k files) | ~60s | ~2-5s | | Typical PR (5-10 files) | ~60s | ~1-2s | | Single file hotfix | ~60s | <1s | **Key insight:** PR pipelines typically change a small fraction of files. Incremental indexing is O(changed files), not O(total files). ### Caching Strategy ```yaml - name: Restore Cache uses: actions/cache@v4 with: path: .ckb/ key: ckb-${{ runner.os }}-${{ github.ref }}-${{ github.sha }} restore-keys: | ckb-${{ runner.os }}-${{ github.ref }}- ckb-${{ runner.os }}- - name: Index run: | ckb init ckb index # Incremental by default - name: Save Cache uses: actions/cache/save@v4 if: always() with: path: .ckb/ key: ckb-${{ runner.os }}-${{ github.ref }}-${{ github.sha }} ``` Use `ckb index --force` for nightly builds when accuracy matters. Use incremental for PRs when speed matters. See [[Incremental Indexing]] for accuracy guarantees and troubleshooting. ### Trigger Refresh via API (v7.5) If running the CKB daemon, trigger index refresh via HTTP: ```bash # Incremental refresh (fastest) curl -X POST http://localhost:9120/api/v1/refresh # Full reindex (when accuracy is critical) curl -X POST http://localhost:9120/api/v1/refresh -d '{"full": true}' # Specify repository path curl -X POST http://localhost:9120/api/v1/refresh -d '{"repo": "/path/to/repo"}' ``` This is useful for: - Post-deploy hooks that need fresh indexes - Scheduled jobs that maintain index freshness - Integration with external build systems See [[Daemon-Mode#index-refresh-api-v75]] for full documentation. --- ## Change Impact Analysis CKB's Change Impact Analysis maps git diffs to SCIP symbols, then uses the call graph to identify what downstream code might break. ### Output Formats | Format | Use Case | |--------|----------| | `--format=json` | Machine-readable for scripting | | `--format=markdown` | PR comments, GitHub/GitLab integration | | `--format=text` | Human-readable terminal output (default) | ### ROI: Real CI Savings | Scenario | Full Suite | With Affected Tests | Savings | |----------|------------|---------------------|---------| | 10,000 tests, 45 min | 45 min | ~5 min (typical PR) | 89% | | 50 CI runs/day | 37.5 hours | ~4 hours | $500+/day* | *Assuming $0.008/min for CI compute See [[Impact-Analysis]] for full documentation including risk scoring and confidence levels. --- ## Complexity Gates Fail CI when code complexity exceeds thresholds. High cyclomatic complexity correlates with bugs and maintenance burden. ```bash # Check a single file ckb complexity internal/query/engine.go --format=json # Response includes: { "summary": { "maxCyclomatic": 12, "maxCognitive": 18, "averageCyclomatic": 2.71 }, "functions": [ {"name": "Execute", "cyclomatic": 8, "cognitive": 12, "risk": "medium"} ] } ``` See [[Workflow Examples#complexity-gate]] for a complete workflow. --- ## Dead Code Detection Identify unused code using static analysis: ```bash ckb dead-code --threshold=0.9 --limit=20 --format=json ``` Response includes confidence scores and reasons: ```json { "candidates": [ { "symbol": "legacyHandler", "path": "internal/api/legacy.go:45", "reason": "No references found in codebase", "confidence": 0.95 } ] } ``` See [[Workflow Examples#dead-code-detection]] for automated weekly scans. --- ## Coupling Analysis Detect tightly coupled files that change together. Warns when coupled files change independently: ```bash ckb coupling --files=handler.go,service.go --min-correlation=0.7 ``` Response: ```json { "changedFiles": ["internal/api/handler.go"], "missingCoupled": [ { "file": "internal/api/handler_test.go", "coupledTo": "internal/api/handler.go", "couplingScore": 0.92, "cochangeCount": 45 } ] } ``` --- ## Risk Audit Comprehensive 8-factor risk analysis: | Factor | Weight | Description | |--------|--------|-------------| | `complexity` | 20% | Cyclomatic/cognitive complexity | | `test_coverage` | 20% | Percentage of code covered by tests | | `bus_factor` | 15% | Number of contributors | | `security_sensitive` | 15% | Contains auth/crypto/credential code | | `staleness` | 10% | Time since last modification | | `error_rate` | 10% | Runtime errors from telemetry | | `co_change_coupling` | 5% | Tightly coupled files | | `churn` | 5% | Frequency of changes | ```bash ckb audit --min-score=60 --limit=20 --format=json ``` See [[Workflow Examples#risk-audit]] for weekly risk audits. --- ## Compliance Audit Gate CI on regulatory compliance violations across 20 frameworks (GDPR, PCI DSS, HIPAA, ISO 27001, and more): ```bash # Fail on error-severity compliance findings ckb audit compliance --framework=gdpr,pci-dss --ci --fail-on=error # Full audit with SARIF output for IDE integration ckb audit compliance --framework=all --format=sarif # Scope to specific paths ckb audit compliance --framework=hipaa --scope=internal/patient/ --ci ``` Each finding maps to specific regulation articles with CWE references and confidence scores. Cross-framework mapping automatically surfaces all applicable regulations for a single finding. See [[Compliance-Audit]] for full documentation, supported frameworks, and output format. --- ## Contract-Aware CI When changes touch API contracts (protobuf, OpenAPI), CKB can detect cross-boundary impact that simple file diffs miss. ```bash curl -s "http://localhost:8080/contracts/impact?path=proto/api/v1/user.proto" ``` Response: ```json { "contract": "proto/api/v1/user.proto", "visibility": "public", "consumers": [ {"repo": "frontend", "confidence": "high"}, {"repo": "mobile-app", "confidence": "medium"} ], "riskLevel": "high", "riskFactors": ["Public contract with 2 known consumers"] } ``` See [[Workflow Examples#contract-check]] for contract safety workflows. --- ## Documentation Coverage CI Enforce documentation coverage and detect stale symbol references: ```bash # Check coverage ckb docs coverage --fail-under=80 # Find stale references ckb docs stale --all --format=json # Check docs for a symbol before renaming ckb docs symbol "UserService.Authenticate" ``` See [[Workflow Examples#doc-quality]] for documentation quality workflows. --- ## Health and Readiness Checks For Kubernetes deployments: | Endpoint | Purpose | Response | |----------|---------|----------| | `GET /health` | Liveness probe | `{"status": "ok"}` | | `GET /health/detailed` | Full component status | Status of each subsystem | | `GET /ready` | Readiness probe | 200 if ready, 503 if not | ```yaml # Kubernetes probes livenessProbe: httpGet: path: /health port: 8080 initialDelaySeconds: 5 readinessProbe: httpGet: path: /ready port: 8080 initialDelaySeconds: 2 ``` --- ## Prometheus Metrics CKB exports metrics in Prometheus format: | Metric | Type | Description | |--------|------|-------------| | `ckb_requests_total` | Counter | Total API requests | | `ckb_request_duration_seconds` | Histogram | Request latency | | `ckb_cache_hits_total` | Counter | Cache hit count | | `ckb_symbols_indexed` | Gauge | Number of indexed symbols | | `ckb_index_age_seconds` | Gauge | Time since last index | ```bash curl -s http://localhost:8080/metrics ``` --- ## Cache Management ### Pre-warming Cache ```bash curl -X POST "http://localhost:8080/cache/warm" \ -H "Content-Type: application/json" \ -d '{"scope": "architecture"}' ``` ### Clearing Cache ```bash # Clear all cache curl -X POST "http://localhost:8080/cache/clear" # Clear specific tier curl -X POST "http://localhost:8080/cache/clear" \ -H "Content-Type: application/json" \ -d '{"tier": "query"}' ``` ### Cache Tiers | Tier | Contents | TTL | |------|----------|-----| | `query` | Symbol lookups, references | 5 min | | `view` | Architecture, hotspots | 1 hour | | `negative` | "Not found" results | 10 min | --- ## Upload to Central Index Server For organizations using a central CKB index server: ```yaml - name: Upload Index env: CKB_TOKEN: ${{ secrets.CKB_TOKEN }} run: | curl -X POST "${{ vars.CKB_SERVER_URL }}/index/repos/${{ github.repository }}/upload" \ -H "Authorization: Bearer $CKB_TOKEN" \ -H "Content-Type: application/octet-stream" \ -H "Content-Encoding: gzip" \ -H "X-CKB-Commit: ${{ github.sha }}" \ --data-binary @<(gzip -c index.scip) ``` See [[Authentication]] for token configuration. --- ## Environment Variables | Variable | Description | Default | |----------|-------------|---------| | `CKB_REPO_ROOT` | Repository root path | Current directory | | `CKB_LOG_LEVEL` | Log verbosity (debug/info/warn/error) | `info` | | `CKB_CONFIG_PATH` | Config file location | `.ckb/config.json` | | `CKB_TIER` | Analysis tier: `fast`, `standard`, or `full` | Auto-detected | --- ## Tips 1. **Cache the `.ckb/` directory** — Enables incremental indexing across runs 2. **Use `fetch-depth: 0`** — Required for git-blame analysis 3. **Run refresh on schedule** — Keep data fresh without blocking PRs 4. **Use async for big repos** — Avoid CI timeout issues with `/architecture/refresh?async=true` 5. **Use incremental indexing for PRs** — O(changed files) instead of O(total files) 6. **Use `--force` for nightly builds** — Ensures maximum accuracy 7. **Validate with `ckb doctor --tier`** — Catch missing tools early 8. **Use `/ready` for health checks** — Wait for server before queries 9. **Export `/metrics` for dashboards** — Track CKB performance over time --- ## Recommended Rollout 1. **Start with PR comments** (informational only) 2. **Add hotspot warnings** after you trust the data 3. **Add contract boundary detection** for API changes 4. **Consider ownership drift** on a schedule, not every PR 5. **Add enforcement** (failing builds) only after the team trusts the signals --- ## Workflow Templates Ready-to-use workflow files are available in the [`examples/`](https://github.com/SimplyLiz/CodeMCP/tree/master/examples) directory: | Directory | Contents | |-----------|----------| | `examples/github-actions/` | 13 GitHub Actions workflows | | `examples/gitlab-ci/` | Complete GitLab CI configuration | | `examples/hooks/` | Git hooks, pre-commit framework, Husky | See [[Workflow Examples]] for full documentation of each workflow with example outputs. --- ## Related Pages - [[Workflow Examples]] — Production-ready CI/CD templates - [[Quality Gates]] — Complexity, risk, coupling, and coverage gates - [[Impact-Analysis]] — Blast radius, risk scoring, and change analysis - [[Authentication]] — Token management and scopes - [[Daemon-Mode]] — Webhook-triggered indexing - [[Federation]] — Cross-repo index publishing - [[Incremental-Indexing]] — Efficient index updates - [[Configuration]] — CI-related configuration options