Workflow Examples
Production-ready CI/CD workflows for GitHub Actions, GitLab CI, and local git hooks.
All workflow files are available in the examples/ directory of the repository.
Want to enforce code standards? See Quality Gates for configuring thresholds, warn vs fail modes, and combining multiple gates.
Quick Install
# GitHub Actions - copy all workflows
cp examples/github-actions/*.yml .github/workflows/
# GitLab CI
cp examples/gitlab-ci/.gitlab-ci.yml .gitlab-ci.yml
# Git hooks
cp examples/hooks/pre-commit .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
Table of Contents
GitHub Actions
| Workflow | File | Purpose |
|---|---|---|
| Starter Template | starter-template.yml |
Start here - modular template, delete sections you don't need |
| Full Showcase | full-showcase.yml |
Complete demo - all features, CKB's own workflow |
| Impact Comment | impact-comment.yml |
Simple PR comment widget (minimal setup) |
| Impact Analysis | impact-analysis.yml |
Full impact analysis with risk gates |
| PR Analysis | pr-analysis.yml |
Risk assessment, reviewer suggestions, ownership drift |
| Scheduled Refresh | scheduled-refresh.yml |
Daily architecture model updates |
| Incremental Indexing | incremental-indexing.yml |
Fast CI with cached incremental indexes |
| Complexity Gate | complexity-gate.yml |
Block PRs exceeding complexity thresholds |
| Affected Tests | affected-tests.yml |
Run only tests affected by changes |
| Dead Code Detection | dead-code-detection.yml |
Weekly scan for unused code |
| Hotspot Monitor | hotspot-monitor.yml |
Track and alert on code hotspots |
| CODEOWNERS Sync | codeowners-sync.yml |
Auto-update CODEOWNERS from git history |
| Contract Check | contract-check.yml |
Detect cross-boundary API changes |
| Doc Quality | doc-quality.yml |
Documentation coverage and staleness |
| Risk Audit | risk-audit.yml |
8-factor codebase risk analysis |
| Slack Notifications | slack-notifications.yml |
Team alerts for high-risk changes |
| Reusable Analysis | reusable-analysis.yml |
Organization-wide standardized workflow |
| Eval Suite | eval-suite.yml |
Regression testing for search quality |
| Coupling Analysis | coupling-analysis.yml |
Detect co-change patterns and missing files |
| Language Quality | language-quality.yml |
Per-language indexer quality metrics |
| Telemetry Dead Code | telemetry-dead-code.yml |
Production-aware dead code detection |
Other Platforms
| Platform | Files | Purpose |
|---|---|---|
| GitLab CI | gitlab-ci/.gitlab-ci.yml |
Complete GitLab CI/CD configuration |
| Git Hooks | hooks/pre-commit, hooks/pre-push |
Local pre-commit and pre-push validation |
| Pre-commit Framework | hooks/.pre-commit-config.yaml |
pre-commit.com integration |
| Husky + lint-staged | hooks/husky-pre-commit, hooks/ckb-check.js |
Node.js project integration |
Best Practices
| Section | Topics |
|---|---|
| Security Hardening | SHA pinning, minimal permissions, OIDC |
| Caching Strategy | Restore-keys, conditional caching |
| Job Outputs vs Artifacts | When to use each |
| Reusable Workflows | Secrets inherit, workflow outputs |
| Composite Actions | Local CKB setup action |
| Performance Tips | Indexing, caching, parallelization |
Starter Template
File: examples/github-actions/starter-template.yml
A modular CI workflow with all CKB features as optional sections. Copy this file and delete the sections you don't need.
How to Use
- Copy the file to
.github/workflows/ckb.yml - Delete sections you don't need (each marked with
###) - Adjust thresholds in the
env:block - Commit and push
Features Included
Each feature is a self-contained section you can keep or remove:
| Section | Description | Delete if... |
|---|---|---|
| Impact Analysis | Shows what symbols changed and their dependencies | You only want basic metrics |
| Complexity Check | Warns/fails on high complexity code | You don't enforce complexity |
| Coupling Check | Warns when related files are missing | You don't track co-changes |
| Hotspot Check | Flags changes to volatile files | You don't track hotspots |
| Suggested Reviewers | Auto-assigns based on ownership | You assign reviewers manually |
| PR Comment | Posts beautiful summary comment | You prefer step summaries only |
| Quality Gates | Fails on configurable risk level | You want warnings only |
Configuration
All thresholds are configured via environment variables at the top:
env:
MAX_CYCLOMATIC: 15 # Cyclomatic complexity limit
MAX_COGNITIVE: 20 # Cognitive complexity limit
COUPLING_THRESHOLD: 0.7 # How related files must be (0.0-1.0)
FAIL_ON_RISK: critical # Risk level to fail on
DEAD_CODE_THRESHOLD: 0.9 # Dead code confidence threshold
Example: Minimal Setup
Keep only Impact Analysis and PR Comment for basic visibility:
# Delete these sections from the template:
# - Complexity Check
# - Coupling Check
# - Hotspot Check
# - Suggested Reviewers
# - Quality Gates
Example: Strict Quality Gate
Keep everything and tighten thresholds:
env:
MAX_CYCLOMATIC: 10 # Stricter than default
MAX_COGNITIVE: 15
FAIL_ON_RISK: high # Fail on high risk, not just critical
Triggers
pull_request- Runs on all PRsworkflow_dispatch- Manual trigger for testing
When to Use
Use this template when you want:
- A starting point that's easy to customize
- All features available to pick from
- Clear documentation of what each section does
For a non-modular reference, see Full Showcase.
Full Showcase
File: examples/github-actions/full-showcase.yml
The complete feature demonstration workflow - this is the actual workflow CKB uses on itself. It showcases every feature in a single, comprehensive workflow.
Features Included
- Risk scoring with badges
- Blast radius analysis
- Complexity gates
- Coupling analysis
- Contract detection (protobuf, GraphQL, OpenAPI)
- Dead code detection
- Ownership drift
- Suggested reviewers with auto-assignment
- Eval suite (regression testing)
- Language quality metrics
- Beautiful PR comments with collapsible sections
Example PR Comment
The showcase generates rich PR comments with badges, linked files, and collapsible sections:
## CKB Analysis
[]   
> ๐ฏ 5 changed โ 23 affected ยท ๐ฅ 2 hotspots ยท โ ๏ธ 3 risk ยท ๐ 1 complex
**Risk factors:** Touches 2 hotspot(s) โข Spans 3 modules
๐ฅ Suggested: **@api-team** (67%), **@jane-doe** (45%)
| Metric | Value | |
|:-------|------:|:-:|
| Impact Analysis | 5 symbols โ 23 affected | ๐ก |
| Doc Coverage | 78% | โ
|
| Complexity | 1 violations | โ ๏ธ |
| Blast Radius | 2 modules, 8 files | โ ๏ธ |
<details>
<summary>๐ฏ Change Impact Analysis ยท ๐ก MEDIUM ยท 5 changed โ 23 affected</summary>
| Metric | Value |
|:-------|------:|
| Symbols Changed | 5 |
| Directly Affected | 12 |
| Transitively Affected | 23 |
**Symbols changed in this PR:**
- `ExecuteQuery` [modified] โ `internal/query/engine.go`
- `ParseRequest` [modified] โ `internal/api/handlers.go`
**Downstream symbols affected:**
*Direct callers (12):*
- `HandleSearch` in `internal/api`
- `RunBatchQuery` in `internal/batch`
</details>
<details>
<summary>๐ Complexity ยท 1 violations</summary>
| File | Cyclomatic | Cognitive |
|:-----|----------:|----------:|
| `internal/query/engine.go` | โ ๏ธ 18 | โ ๏ธ 24 |
</details>
---
Generated by CKB ยท Run details
When to Use
Use this workflow when you want:
- The most comprehensive analysis possible
- A reference for building custom workflows
- To see all CKB features in action
Triggers
pull_request: branches: [develop, main]schedule: '0 3 * * *'(daily refresh)workflow_dispatch(manual with force option)
Impact Comment
File: examples/github-actions/impact-comment.yml
The simplest way to get CKB analysis on your PRs. Just 45 lines - posts impact analysis as a sticky PR comment.
What It Does
- Indexes the repository (with 24h cache)
- Generates impact analysis in markdown format
- Posts as a sticky PR comment (updates on each push)
Example PR Comment
## Change Impact Analysis ๐ก
**Risk Level:** medium
### Summary
| Metric | Value |
|--------|-------|
| Symbols Changed | 5 |
| Directly Affected | 12 |
| Transitively Affected | 23 |
| Modules in Blast Radius | 2 |
### Changed Symbols
- `ExecuteQuery` in `internal/query/engine.go`
- `ParseRequest` in `internal/api/handlers.go`
### Recommendations
- โ ๏ธ Changes span multiple modules - consider splitting PR
- โน๏ธ 2 hotspot files modified - extra review recommended
When to Use
Use this workflow when you want:
- Minimal setup (just copy the file)
- Basic impact visibility without risk gates
- A starting point before adding more features
Triggers
pull_request: [opened, synchronize]
Impact Analysis
File: examples/github-actions/impact-analysis.yml
Full change impact analysis with risk gates, automatic reviewer assignment, and PR comments.
What It Does
- Analyzes which symbols changed and their downstream impact
- Posts detailed impact analysis as PR comment
- Automatically requests reviewers based on code ownership
- Fails CI if risk level is critical (configurable)
- Caches index for faster subsequent runs
Example PR Comment
Same as Impact Comment, plus automatic reviewer assignment.
Risk Gate
The workflow fails if risk is critical:
::error::Critical risk detected. Manual review required.
## โ Critical Risk Detected
This PR affects critical paths. Please review carefully.
Outputs
The job exposes outputs for downstream jobs:
outputs:
risk: ${{ steps.impact.outputs.risk }}
affected: ${{ steps.impact.outputs.affected }}
When to Use
Use this workflow when you want:
- Impact analysis with automatic enforcement
- Reviewer auto-assignment
- A balance between simplicity and features
Triggers
pull_request: [opened, synchronize, reopened]push: branches: [main, develop]
PR Analysis
File: examples/github-actions/pr-analysis.yml
Comprehensive pull request analysis that posts a detailed comment with risk assessment, suggested reviewers, and ownership drift warnings.
What It Does
- Analyzes all changed files in the PR
- Calculates risk level based on impact and complexity
- Identifies hotspots touched by the changes
- Suggests reviewers based on code ownership
- Detects CODEOWNERS drift
- Posts a formatted comment on the PR
Example PR Comment
## CKB PR Analysis ๐ก
### Summary
- **Files Changed:** 12
- **Lines Changed:** +450 / -120
- **Modules Affected:** 3
- **Hotspots Touched:** 2
- **Risk Level:** medium
### Risk Factors
- Touches 2 hotspot(s)
- Spans 3 modules
- Modifies API contract boundary
### Suggestions
- Extra review recommended for hotspot changes
- Consider splitting into smaller PRs
### Suggested Reviewers
- **@api-team** - Owns 8 of 12 changed files
- **@jane-doe** - Recent contributor to auth module
- **@security-team** - Changes affect authentication
### โ ๏ธ Ownership Drift Detected
3 file(s) in this PR have significant ownership drift. Consider updating CODEOWNERS.
---
*Generated by CKB*
Triggers
pull_request: [opened, synchronize, reopened]
Scheduled Refresh
File: examples/github-actions/scheduled-refresh.yml
Daily job that refreshes CKB's architectural model, recomputes hotspots, and generates reports.
What It Does
- Runs full repository indexing
- Refreshes module detection
- Recomputes hotspot rankings
- Generates architecture report artifact
- Optionally commits
.ckb/cache for faster queries
Artifacts Generated
architecture.json- Full architecture datahotspots.json- Current hotspot rankingsdrift.json- Ownership drift analysisARCHITECTURE_REPORT.md- Human-readable summary
Triggers
schedule: '0 2 * * *'(daily at 2 AM UTC)workflow_dispatch(manual with scope/force options)
Incremental Indexing
File: examples/github-actions/incremental-indexing.yml
Optimized workflow using incremental indexing for fast CI runs.
What It Does
- Restores cached
.ckb/directory from previous runs - Uses incremental indexing for PRs (processes only changed files)
- Uses full indexing for main branch pushes (maximum accuracy)
- Caches results for next run
Performance
| 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 |
Triggers
pull_requestpush: branches: [main]
Complexity Gate
File: examples/github-actions/complexity-gate.yml
Quality gate that fails PRs when changed files exceed complexity thresholds.
What It Does
- Identifies source files changed in the PR
- Measures cyclomatic and cognitive complexity for each
- Compares against configurable thresholds
- Posts detailed report as PR comment
- Fails the check if any file exceeds thresholds
Example PR Comment
## Complexity Analysis
### Violations
- `internal/query/engine.go`: Cyclomatic complexity 23 exceeds 15
- `internal/query/engine.go`: Cognitive complexity 31 exceeds 20
### Warnings
- `internal/api/handlers.go`: Cyclomatic complexity 13 approaching limit
<details>
<summary>Thresholds</summary>
- Cyclomatic complexity: 15
- Cognitive complexity: 20
- Total file complexity: 100
</details>
---
*Generated by CKB*
Default Thresholds
| Metric | Default | Environment Variable |
|---|---|---|
| Cyclomatic | 15 | MAX_CYCLOMATIC |
| Cognitive | 20 | MAX_COGNITIVE |
| Total file | 100 | MAX_FILE_COMPLEXITY |
Triggers
pull_request: [opened, synchronize, reopened]
Affected Tests
File: examples/github-actions/affected-tests.yml
Smart test selection that runs only tests affected by code changes.
What It Does
- Analyzes which code paths changed in the PR
- Maps changes to affected tests using multiple strategies
- Runs only affected tests per language (Go, JS/TS, Python)
- Reports which tests were run and why
Test Selection Strategies
| Strategy | Accuracy | Requirements |
|---|---|---|
coverage |
Highest | Coverage file from previous run |
imports |
High | SCIP index |
naming |
Medium | Naming conventions (e.g., foo.go โ foo_test.go) |
Example Summary
## Affected Tests Summary
**Strategy:** coverage
**Tests run:** 12
<details>
<summary>Test files</summary>
- `internal/query/engine_test.go`
- `internal/query/parser_test.go`
- `internal/api/handlers_test.go`
</details>
Triggers
pull_request: [opened, synchronize, reopened]
Dead Code Detection
File: examples/github-actions/dead-code-detection.yml
Weekly scan for potentially unused code.
What It Does
- Scans repository for unused functions, types, and variables
- Filters by confidence threshold (default 90%)
- Generates detailed report with file locations
- Creates GitHub issue if significant dead code found
- Updates existing issue on subsequent runs
Example Report
# Dead Code Detection Report
**Run Date:** 2025-01-15
**Threshold:** 0.9
## Summary
- **Total candidates found:** 23
## High Confidence Candidates (>95%)
| File | Symbol | Type | Confidence |
|------|--------|------|------------|
| `internal/legacy/old_handler.go` | HandleV1Request | function | 98% |
| `internal/utils/deprecated.go` | FormatOldDate | function | 97% |
---
*Generated by CKB*
Triggers
schedule: '0 3 * * 1'(weekly on Mondays at 3 AM UTC)workflow_dispatch(manual with threshold/limit options)
Hotspot Monitor
File: examples/github-actions/hotspot-monitor.yml
Continuous monitoring of code hotspots with alerts.
What It Does
- Computes current hotspot rankings (churn ร complexity)
- Compares against historical baseline
- On PRs: warns if changes touch hotspot files
- On schedule: creates alert issues if hotspots worsen
- Tracks trends over time via artifacts
Example PR Warning
### Hotspot Warning
This PR modifies the following hotspot files:
- `internal/query/engine.go` (score: 0.89)
- `internal/api/handlers.go` (score: 0.72)
Extra review recommended for changes to high-churn files.
Triggers
schedule: '0 5 * * *'(daily at 5 AM UTC)pull_request: [opened, synchronize]workflow_dispatch
CODEOWNERS Sync
File: examples/github-actions/codeowners-sync.yml
Automated CODEOWNERS maintenance based on git history.
What It Does
- Analyzes git history to determine actual file ownership
- Compares with declared CODEOWNERS rules
- Generates suggested CODEOWNERS updates
- Creates a PR with the proposed changes
- Supports dry-run mode for preview
Example PR Description
# Ownership Drift Report
This PR updates CODEOWNERS based on actual commit history.
## Summary
- **Files with ownership drift:** 15
- **Significant changes:** 8
## Changes
| Path | Declared Owner | Actual Owner | Confidence |
|------|----------------|--------------|------------|
| `internal/api/` | @backend-team | @api-team | 87% |
| `internal/auth/oauth.go` | @backend-team | @security-team | 92% |
---
*Generated by CKB ownership analysis*
Triggers
schedule: '0 4 * * 0'(weekly on Sundays at 4 AM UTC)workflow_dispatch(manual with threshold/dry_run options)
Contract Check
File: examples/github-actions/contract-check.yml
Detects changes to API contracts and warns about cross-boundary impact.
What It Does
- Identifies changed contract files (protobuf, OpenAPI, swagger)
- Analyzes impact on downstream consumers
- Generates contract change checklist
- Fails if high-risk contract changes detected
Example Report
## Contract Change Analysis
This PR modifies API contract files. Cross-boundary impact analysis:
### `proto/api/v1/user.proto`
- **Visibility:** public
- **Known consumers:** 2
- **Risk level:** high
**Consumers:**
- frontend (high confidence)
- mobile-app (medium confidence)
**Risk factors:**
- Public contract with 2 known consumers
- Breaking field removal detected
Triggers
pull_request(on paths:**/*.proto,**/openapi*.yaml, etc.)
Doc Quality
File: examples/github-actions/doc-quality.yml
Enforces documentation coverage and detects stale symbol references.
What It Does
- Indexes documentation and code
- Checks documentation coverage against threshold
- Detects stale symbol references (renamed/deleted symbols)
- Posts quality report as PR comment
Example Report
## Documentation Quality Report
### โ
Coverage: 78% (threshold: 70%)
### โ ๏ธ Stale References: 3
The following documentation references symbols that may have changed:
- `docs/api.md:45`: UserService.authenticate (symbol renamed)
- `docs/guide.md:120`: handleRequest (symbol deleted)
---
*Generated by CKB documentation analysis*
Triggers
pull_request(on paths:**/*.md,**/*.go,**/*.ts,**/*.py)
Risk Audit
File: examples/github-actions/risk-audit.yml
Comprehensive 8-factor codebase risk analysis.
Risk Factors
| Factor | Weight | Description |
|---|---|---|
| Complexity | 20% | Cyclomatic/cognitive complexity |
| Test Coverage | 20% | Percentage covered by tests |
| Bus Factor | 15% | Single-author code is risky |
| Security Sensitive | 15% | Auth/crypto/credential code |
| Staleness | 10% | Time since last modification |
| Error Rate | 10% | Runtime errors from telemetry |
| Coupling | 5% | Tightly coupled files |
| Churn | 5% | Frequency of changes |
What It Does
- Analyzes entire codebase for risk factors
- Generates prioritized list of risky files
- Identifies quick wins (low effort, high impact)
- Creates GitHub issue for tracking
- Uploads detailed report as artifact
Example Report
# Risk Audit Report
## Summary
| Risk Level | Count |
|------------|-------|
| ๐ด Critical | 3 |
| ๐ High | 12 |
| ๐ก Medium | 45 |
## Critical Risk Files
| File | Score | Top Factors |
|------|-------|-------------|
| `internal/auth/login.go` | 82 | security_sensitive, complexity |
| `internal/api/legacy.go` | 78 | bus_factor, staleness |
## Quick Wins
- **Add tests**: `internal/auth/login.go` (effort: medium, impact: high)
- **Add second reviewer**: `internal/core/engine.go` (effort: low, impact: high)
Triggers
schedule: '0 6 * * 1'(weekly on Mondays at 6 AM UTC)workflow_dispatch
Slack Notifications
File: examples/github-actions/slack-notifications.yml
Team notifications for high-risk changes and daily summaries.
What It Does
- Analyzes PR risk level
- Sends Slack alert for high/critical risk PRs
- Sends daily summary with hotspot and dead code stats
- Includes links to PR and action details
Example Slack Message
๐จ High-Risk PR Detected
Repository: your-org/your-repo
Risk Level: critical
Files Changed: 23
Transitively Affected: 156
PR: #142 - Refactor authentication system
Author: jane-doe
Generated by CKB analysis
Required Secret
SLACK_WEBHOOK_URL- Slack incoming webhook URL
Triggers
pull_request: [opened, synchronize](high-risk alerts)schedule: '0 9 * * 1-5'(daily summary, weekdays 9 AM UTC)
Reusable Analysis
File: examples/github-actions/reusable-analysis.yml
Standardized analysis workflow for organization-wide use.
Usage
In your org's .github repo, place the workflow, then call from any repo:
name: PR Analysis
on: [pull_request]
jobs:
analyze:
uses: your-org/.github/.github/workflows/reusable-analysis.yml@main
with:
risk_threshold: 'high'
enable_complexity: true
enable_ownership: true
max_cyclomatic: 20
secrets:
token: ${{ secrets.GITHUB_TOKEN }}
Inputs
| Input | Type | Default | Description |
|---|---|---|---|
risk_threshold |
string | critical |
Risk level to fail on |
enable_complexity |
boolean | true |
Enable complexity checking |
enable_ownership |
boolean | true |
Enable ownership drift detection |
enable_reviewers |
boolean | true |
Auto-request reviewers |
max_cyclomatic |
number | 15 |
Maximum cyclomatic complexity |
max_cognitive |
number | 20 |
Maximum cognitive complexity |
ckb_version |
string | latest |
CKB version to install |
Outputs
| Output | Description |
|---|---|
risk_level |
Detected risk level |
files_changed |
Number of files changed |
complexity_violations |
Number of complexity violations |
Eval Suite
File: examples/github-actions/eval-suite.yml
Regression testing for CKB search quality. Ensures code intelligence accuracy doesn't degrade over time.
What It Does
- Loads test fixtures from
.ckb/fixtures/directory - Runs queries against each fixture and compares to expected results
- Calculates pass rate and identifies failed tests
- Posts detailed report as PR comment
- Fails CI if pass rate drops below threshold (default 90%)
Example PR Comment
## Eval Suite Results
### โ
Pass Rate: 94% (47/50)
### Failed Tests
| Test | Expected | Actual | Reason |
|------|----------|--------|--------|
| `find-auth-handler` | `internal/auth/handler.go` | `internal/api/auth.go` | Wrong file matched |
| `reference-count` | 12 | 8 | Missing references |
<details>
<summary>Test Categories</summary>
- **navigation**: 15/15
- **references**: 18/20
- **search**: 14/15
</details>
---
*Generated by CKB eval suite*
Fixture Format
Create JSON files in .ckb/fixtures/:
{
"id": "find-user-service",
"category": "navigation",
"query": "definition UserService",
"expected": {
"file": "internal/user/service.go",
"symbol": "UserService"
}
}
Triggers
pull_request(on code and fixture changes)schedule: '0 4 * * 0'(weekly on Sundays)workflow_dispatch(manual with threshold option)
Coupling Analysis
File: examples/github-actions/coupling-analysis.yml
Detects files that frequently change together. Catches incomplete changes and identifies refactoring opportunities.
What It Does
On Pull Requests:
- Analyzes files changed in the PR
- Checks git history for co-change patterns
- Warns if coupled files are missing from the PR
- Posts comment with potentially missing files
On Schedule:
- Analyzes all file coupling across the codebase
- Identifies highly correlated file pairs
- Finds "hub files" that couple with many others
- Creates issue for refactoring candidates
Example PR Comment
## Coupling Analysis
### โ ๏ธ Potentially Missing Changes
These files frequently change together with files in this PR but were not included:
| Missing File | Usually Changed With | Correlation | Co-changes |
|--------------|---------------------|-------------|------------|
| `internal/user/repository.go` | `internal/user/service.go` | 85% | 12 |
| `internal/user/types.go` | `internal/user/service.go` | 78% | 8 |
### What This Means
Files with high coupling often need to change together. Consider:
- Are any changes missing from this PR?
- Should these files be refactored to reduce coupling?
- Is this an intentional partial change?
Weekly Report
# Weekly Coupling Report
## Highly Coupled File Pairs
| File A | File B | Correlation | Co-changes |
|--------|--------|-------------|------------|
| `internal/api/handler.go` | `internal/api/types.go` | 92% | 45 |
| `internal/auth/login.go` | `internal/auth/session.go` | 88% | 32 |
## Hub Files (appear in multiple couplings)
- `internal/api/handler.go` (8 couplings)
- `internal/core/engine.go` (6 couplings)
Configuration
| Input | Default | Description |
|---|---|---|
min_correlation |
0.7 |
Minimum correlation threshold |
min_cochanges |
5 |
Minimum co-change count |
Triggers
pull_request: [opened, synchronize, reopened]schedule: '0 5 * * 1'(weekly on Mondays)workflow_dispatch
Language Quality
File: examples/github-actions/language-quality.yml
Monitors indexer quality per language and alerts on degradation.
What It Does
- Runs
ckb doctorto check indexer availability - Queries language quality metrics from CKB server
- Tracks quality over time with baseline comparison
- Detects degradation between runs
- Creates alert issue for low quality languages
Example Dashboard
# Language Quality Dashboard
## Summary
**Overall Quality Score:** 85%
### Indexer Coverage
| Tier | Count | Description |
|------|-------|-------------|
| Tier 1 (SCIP) | 3 | Full semantic analysis |
| Tier 2 (LSP) | 2 | Go-to-definition, references |
| Tier 3 (Tree-sitter) | 4 | Syntax-based navigation |
### Environment Status
| Status | Count |
|--------|-------|
| โ
Ready | 7 |
| โ ๏ธ Partial | 1 |
| โ Missing | 1 |
### Language Details
| Language | Quality | Tier | Status | Issues |
|----------|---------|------|--------|--------|
| Go | 95% | scip | ready | โ |
| TypeScript | 92% | scip | ready | โ |
| Python | 78% | lsp | ready | slow startup |
| Rust | 85% | scip | partial | missing rust-analyzer |
### โ ๏ธ Low Quality Languages
These languages have quality below 70%:
- **Shell**: 45% quality
### Recommendations
**Install missing indexers:**
- Rust: `rustup component add rust-analyzer`
Quality Tiers
| Tier | Backend | Capabilities |
|---|---|---|
| Tier 1 | SCIP | Full semantic: definitions, references, implementations, type hierarchy |
| Tier 2 | LSP | Go-to-definition, find references |
| Tier 3 | Tree-sitter | Syntax navigation, symbol extraction |
Triggers
schedule: '0 6 * * *'(daily at 6 AM UTC)push: branches: [main](on dependency file changes)workflow_dispatch
Telemetry Dead Code
File: examples/github-actions/telemetry-dead-code.yml
Combines static analysis with production telemetry for high-confidence dead code detection.
What It Does
- Runs static dead code analysis (finds unused symbols)
- Queries production telemetry for runtime call data
- Cross-references both sources for highest confidence
- Generates combined report with recommendations
- Creates issue for confirmed dead code
Why Telemetry Matters
| Source | Confidence | Catches |
|---|---|---|
| Static only | Medium | Unused in code |
| Telemetry only | High | Never called in production |
| Both sources | Very High | Unused AND never called |
Example Report
# Dead Code Analysis Report
## Summary
| Source | Candidates | High Confidence (>95%) |
|--------|------------|------------------------|
| Static Analysis | 45 | 12 |
| Production Telemetry | 23 | 18 |
| **Confirmed by Both** | 8 | โ |
**Telemetry Coverage:** 1,234 / 1,567 symbols (79%)
## ๐ด Confirmed Dead Code (Both Sources)
These symbols are unused in both static analysis AND production:
| Symbol | File | Static Conf. | Last Called |
|--------|------|--------------|-------------|
| `HandleLegacyAuth` | `internal/auth/legacy.go` | 98% | Never |
| `ParseOldFormat` | `internal/parser/v1.go` | 96% | Never |
| `DeprecatedHandler` | `internal/api/old.go` | 95% | Never |
## ๐ Static Analysis Only (>95% confidence)
| Symbol | File | Type | Confidence |
|--------|------|------|------------|
| `unusedHelper` | `internal/utils/helpers.go` | function | 97% |
| `OldConfig` | `internal/config/legacy.go` | struct | 96% |
## ๐ก Telemetry Dead Code (No production calls)
| Symbol | File | Last Called | Days Since |
|--------|------|-------------|------------|
| `RareFeature` | `internal/features/rare.go` | 2024-06-15 | 180 |
## Recommendations
1. **Immediate cleanup:** Remove 8 symbol(s) confirmed dead by both sources
Prerequisites
- Telemetry collection enabled (see Telemetry)
- Telemetry data available at configured endpoint
Configuration
| Input | Default | Description |
|---|---|---|
static_threshold |
0.9 |
Static analysis confidence threshold |
telemetry_days |
30 |
Days of telemetry data to analyze |
include_static |
true |
Include static-only analysis |
Triggers
schedule: '0 4 * * 1'(weekly on Mondays)workflow_dispatch
GitLab CI
Directory: examples/gitlab-ci/
Complete GitLab CI/CD configuration.
Installation
cp examples/gitlab-ci/.gitlab-ci.yml .gitlab-ci.yml
Or include in existing config:
include:
- local: 'ci/ckb.gitlab-ci.yml'
Jobs
| Job | Stage | Trigger | Description |
|---|---|---|---|
index |
setup | All | Index repository |
impact-analysis |
analyze | MR | Analyze change impact |
complexity-check |
analyze | MR | Check complexity thresholds |
suggest-reviewers |
analyze | MR | Get suggested reviewers |
hotspot-check |
analyze | MR | Warn about hotspot changes |
post-mr-notes |
report | MR | Post combined report as MR note |
architecture-refresh |
analyze | Schedule | Full architecture refresh |
Required Variables
| Variable | Description |
|---|---|
GITLAB_TOKEN |
GitLab API token with api scope (for MR notes) |
Git Hooks
Directory: examples/hooks/
Local development hooks for pre-commit and pre-push validation.
Installation
cp examples/hooks/pre-commit .git/hooks/pre-commit
cp examples/hooks/pre-push .git/hooks/pre-push
chmod +x .git/hooks/pre-commit .git/hooks/pre-push
pre-commit
Blocks commits with:
- Complexity violations (cyclomatic > 15, cognitive > 20)
- Critical risk level changes
- Warnings for hotspot modifications
pre-push
Validates branch before pushing:
- Analyzes full diff against base branch
- Blocks critical-risk pushes
- Optional dead code detection
Example Output
Running CKB pre-commit checks...
Checking complexity...
ERROR: internal/query/engine.go has cyclomatic complexity 23 (max: 15)
Checking change impact...
Risk level: medium
Checking hotspots...
Warning: Modifying high-risk hotspot: internal/query/engine.go (score: 0.89)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Pre-commit check FAILED
Errors: 1
Warnings: 2
Fix the errors above or use 'git commit --no-verify' to bypass.
Configuration
| Variable | Default | Description |
|---|---|---|
CKB_MAX_CYCLOMATIC |
15 |
Maximum cyclomatic complexity |
CKB_MAX_COGNITIVE |
20 |
Maximum cognitive complexity |
CKB_BLOCK_CRITICAL |
true |
Block critical risk commits |
CKB_WARN_HIGH |
true |
Warn on high risk commits |
Pre-commit Framework
File: examples/hooks/.pre-commit-config.yaml
Integration with pre-commit.com.
Installation
pip install pre-commit
cp examples/hooks/.pre-commit-config.yaml .pre-commit-config.yaml
pre-commit install
Hooks Included
ckb-complexity- Check complexity thresholdsckb-impact- Warn on high-risk changesckb-hotspot-warn- Warn when modifying hotspots
Husky + lint-staged
Files: examples/hooks/husky-pre-commit, examples/hooks/ckb-check.js
Integration for Node.js projects using Husky and lint-staged.
Installation
npm install -D husky lint-staged
npx husky init
cp examples/hooks/husky-pre-commit .husky/pre-commit
cp examples/hooks/ckb-check.js scripts/ckb-check.js
chmod +x .husky/pre-commit scripts/ckb-check.js
package.json Configuration
{
"scripts": {
"prepare": "husky"
},
"lint-staged": {
"*.{ts,tsx,js,jsx}": [
"eslint --fix",
"prettier --write",
"node scripts/ckb-check.js"
]
}
}
Best Practices
Security Hardening
Pin actions to commit SHAs instead of tags for supply chain security:
# Recommended - pinned to SHA
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- uses: actions/cache@6849a6489940f00c2f30c0fb92c6274307ccb58a # v4.1.2
# Less secure - tag can be moved
- uses: actions/checkout@v4
Use minimal permissions with explicit scopes:
permissions:
contents: read # Read repo contents
pull-requests: write # Post PR comments
# All other permissions default to 'none'
Disable all permissions for jobs that don't need them:
jobs:
analyze:
permissions: {} # No GitHub API access needed
Use OIDC for cloud authentication instead of long-lived secrets:
permissions:
id-token: write # Required for OIDC
contents: read
steps:
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789:role/github-actions
aws-region: us-east-1
Caching Strategy
Use restore-keys for fallback when exact cache miss:
- uses: actions/cache@v4
with:
path: .ckb/
key: ckb-${{ runner.os }}-${{ hashFiles('**/*.go') }}-${{ github.sha }}
restore-keys: |
ckb-${{ runner.os }}-${{ hashFiles('**/*.go') }}-
ckb-${{ runner.os }}-
Separate restore and save for conditional caching:
- uses: actions/cache/restore@v4
id: cache
with:
path: .ckb/
key: ckb-${{ runner.os }}-${{ hashFiles('go.sum') }}
- name: Index (only if cache miss)
if: steps.cache.outputs.cache-hit != 'true'
run: ckb index
- uses: actions/cache/save@v4
if: always()
with:
path: .ckb/
key: ckb-${{ runner.os }}-${{ hashFiles('go.sum') }}
Job Outputs vs Artifacts
Use job outputs for small data (<1MB) between jobs:
jobs:
analyze:
outputs:
risk: ${{ steps.impact.outputs.risk }}
affected: ${{ steps.impact.outputs.affected }}
steps:
- id: impact
run: |
echo "risk=high" >> $GITHUB_OUTPUT
echo "affected=42" >> $GITHUB_OUTPUT
gate:
needs: analyze
if: needs.analyze.outputs.risk == 'critical'
steps:
- run: echo "Blocking critical risk PR"
Use artifacts for larger files or cross-workflow sharing:
- uses: actions/upload-artifact@v4
with:
name: ckb-analysis
path: '*.json'
retention-days: 7
Reusable Workflows
Pass secrets with inherit for same-org workflows:
jobs:
analyze:
uses: your-org/.github/.github/workflows/ckb-analysis.yml@main
secrets: inherit # Pass all secrets from caller
Define workflow outputs for caller consumption:
# In reusable workflow
on:
workflow_call:
outputs:
risk_level:
description: "Detected risk level"
value: ${{ jobs.analyze.outputs.risk }}
jobs:
analyze:
outputs:
risk: ${{ steps.impact.outputs.risk }}
Call from another workflow:
jobs:
ckb:
uses: your-org/.github/.github/workflows/ckb-analysis.yml@main
gate:
needs: ckb
if: needs.ckb.outputs.risk_level == 'critical'
runs-on: ubuntu-latest
steps:
- run: exit 1
Composite Actions
Create a local composite action for repeated CKB steps:
# .github/actions/ckb-setup/action.yml
name: 'CKB Setup'
description: 'Install and initialize CKB'
inputs:
cache-key:
description: 'Cache key suffix'
default: ''
outputs:
cache-hit:
description: 'Whether cache was restored'
value: ${{ steps.cache.outputs.cache-hit }}
runs:
using: composite
steps:
- uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm install -g @tastehub/ckb
shell: bash
- uses: actions/cache@v4
id: cache
with:
path: .ckb/
key: ckb-${{ runner.os }}-${{ inputs.cache-key }}
restore-keys: ckb-${{ runner.os }}-
- run: ckb init && ckb index --if-stale=24h
shell: bash
Use in workflows:
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: ./.github/actions/ckb-setup
with:
cache-key: ${{ hashFiles('go.sum') }}
- run: ckb pr-summary --format=json
Performance Tips
| Tip | Impact | Implementation |
|---|---|---|
Use --if-stale=24h |
Skip indexing if recent | ckb index --if-stale=24h |
| Limit analyzed files | Faster on large PRs | head -20 in file loops |
| Use incremental indexing | O(changed) vs O(total) | Default for PRs |
Cache .ckb/ directory |
Reuse index across runs | actions/cache@v4 |
| Run gates in parallel | Faster total time | Separate jobs with needs |
See Also
- CI-CD-Integration - Full integration guide with concepts and API reference
- Quality Gates - Complexity, risk, coupling, and coverage gate configuration
- Impact-Analysis - Understanding change impact
- Configuration - CKB configuration options
- Quick-Start - Getting started with CKB