Thanks to visit codestin.com
Credit goes to github.com

Skip to content

User Guide

Lisa edited this page Dec 26, 2025 · 33 revisions

CKB User Guide

Table of Contents


Introduction

CKB (Code Knowledge Backend) is a tool that helps AI assistants understand your codebase. It provides a unified interface to query code intelligence from multiple backends (SCIP, LSP, Git) and returns optimized responses designed for LLM context windows.

Getting Started

Prerequisites

  • Node.js 16+ (for npm install) or Go 1.21+ (for building from source)
  • Git repository
  • (Optional) SCIP index for your project — run ckb index to auto-generate
  • (Optional) Language server for your project's language

Installation

npm (Recommended):

# Install globally
npm install -g @tastehub/ckb

# Or run directly without installing
npx @tastehub/ckb --help

Build from source:

git clone https://github.com/SimplyLiz/CodeMCP.git
cd CodeMCP
go build -o ckb ./cmd/ckb

# Add to PATH or move to /usr/local/bin
mv ckb /usr/local/bin/

Initialize Your Project

Navigate to your project root and initialize CKB:

cd /path/to/your/project
ckb init

This creates a .ckb/ directory with:

  • config.json - Configuration file
  • ckb.db - SQLite database for caching and symbol mappings

Verify Setup

# Check system status
ckb status

# Run diagnostics
ckb doctor

Configure AI Tool (Optional)

If you use an AI coding assistant, configure CKB as an MCP server:

# Interactive setup - choose your AI tool
ckb setup

# Or specify directly
ckb setup --tool=claude-code
ckb setup --tool=cursor
ckb setup --tool=vscode

See ckb setup for all options, or MCP Integration for manual configuration.

Core Concepts

Stable Symbol IDs

CKB assigns stable IDs to symbols that survive refactoring:

ckb:myrepo:sym:a1b2c3d4e5f6...

When a symbol is renamed, CKB creates an alias from the old ID to the new one, so references using the old ID continue to work.

Repository State

CKB tracks repository state using:

  • HEAD commit hash
  • Staged changes hash
  • Working tree changes hash
  • Untracked files hash

This composite state ID is used for cache invalidation.

Backend Ladder

CKB queries backends in priority order:

  1. SCIP - Pre-computed index (fastest, most accurate)
  2. LSP - Language server (real-time, may be slower)
  3. Git - Fallback for basic operations

Analysis Tiers (v7.2)

CKB operates in three tiers based on available backends:

Tier What's Available When to Use
Fast Tree-sitter only Quick lookups, low latency, no setup required
Standard SCIP index Precise cross-references (default when index exists)
Full SCIP + Telemetry Runtime usage data, dead code detection

Controlling the tier:

# CLI flag (per-command)
ckb search "Handler" --tier=fast
ckb impact "sym" --tier=standard

# Environment variable (session-wide)
export CKB_TIER=fast
ckb search "Handler"

# Config file (project default)
# .ckb/config.json: {"tier": "standard"}

Precedence: CLI flag > CKB_TIER env var > config > auto-detect

Tier requirements:

  • --tier=fast: Always available
  • --tier=standard: Requires SCIP index (run ckb index)
  • --tier=full: Requires SCIP + telemetry configuration

If you request a tier that isn't available, CKB will warn and fall back to the highest available tier.

Architectural Memory

CKB maintains persistent knowledge that survives across sessions:

  • Module Registry - Boundaries, responsibilities, and tags for each module
  • Ownership Registry - Who owns what code (from CODEOWNERS + git blame)
  • Hotspot Tracker - Historical risk tracking with trend analysis
  • Decision Log - Architectural Decision Records (ADRs)

This data is stored in ~/.ckb/repos/<repo-hash>/ and persists until explicitly refreshed.

Annotations (v6.5)

Annotations are metadata you add to modules and decisions. They're consumed by other CKB tools to provide richer context:

Annotation Type Created With Consumed By
ADRs ckb decisions create explain, justify, impact, modules
Module Metadata ckb modules annotate explain, modules, responsibilities

Key behavior:

  • ADRs with --module flags automatically surface when querying those modules
  • justify won't recommend removing code that has an accepted ADR
  • Module annotations override inferred descriptions with higher confidence

See ckb decisions and ckb modules annotate for usage.

CLI Commands

ckb init

Initialize CKB in the current directory.

ckb init

Creates .ckb/config.json with default settings.

ckb index

Build or update the SCIP index for code intelligence. Auto-detects language and runs the appropriate indexer.

# Auto-detect language and index
ckb index

# Skip if index is already current
ckb index   # Says "Index is current" if fresh

# Force re-index even if fresh
ckb index --force

# Dry run - show command without executing
ckb index --dry-run

# Specify language manually
ckb index --lang go
ckb index --lang typescript

Smart Indexing (v7.2):

CKB tracks index freshness automatically. When you run ckb index:

  1. Fresh index: Skips with message "Index is current (HEAD = abc1234)"
  2. Stale (commits behind): Shows "Index is stale: 3 commit(s) behind HEAD"
  3. Stale (uncommitted changes): Shows "Index is stale: uncommitted changes detected"
  4. Legacy index: Re-indexes to enable freshness tracking

Index metadata is stored in .ckb/index-meta.json:

{
  "version": 1,
  "createdAt": "2024-12-21T12:00:00Z",
  "commitHash": "abc123...",
  "repoStateId": "...",
  "fileCount": 150,
  "duration": "2.1s",
  "indexer": "scip-go"
}

Incremental Indexing (v7.3 - Go only):

For Go projects, CKB uses incremental indexing by default—only changed files are processed:

# Incremental update (default for Go)
ckb index

# Output:
Incremental Index Complete
--------------------------
Files:   3 modified, 1 added, 0 deleted
Symbols: 15 added, 8 removed
Time:    1.2s

# Force full reindex
ckb index --force

Incremental indexing is much faster but has accuracy trade-offs:

Query After Incremental
Go to definition Always accurate
Find refs FROM changed files Always accurate
Find refs TO changed symbols May be stale
Call graph (callers) May be stale

Use --force when you need 100% accurate reverse references. See Incremental Indexing for details.

Supported Languages:

Language Indexer Install
Go scip-go go install github.com/sourcegraph/scip-go@latest
TypeScript/JavaScript scip-typescript npm install -g @sourcegraph/scip-typescript
Python scip-python pip install scip-python
Rust rust-analyzer rustup component add rust-analyzer
Java scip-java cs install scip-java
Kotlin scip-java Gradle plugin integration
C/C++ scip-clang Download from releases
Dart scip_dart dart pub global activate scip_dart
Ruby scip-ruby Download from releases
C# scip-dotnet dotnet tool install --global scip-dotnet
PHP scip-php composer require --dev davidrjenni/scip-php

Flags:

Flag Description
--force Re-index even if index is current
--dry-run Show command without executing
--lang Force specific language (go, ts, py, rs, java, cpp, etc.)
--compdb Path to compile_commands.json (C/C++ only)

ckb status

Show system status including:

  • Repository state
  • Backend availability
  • Cache statistics
  • Index freshness (v7.2)
ckb status

Index Status (v7.2):

The status output includes an Index Status section:

Index Status:
  ✓ Up to date (HEAD = abc1234)
  Files: 150

Or when stale:

Index Status:
  ⚠ 3 commit(s) behind HEAD + uncommitted changes
  Run 'ckb index' to refresh.

ckb doctor

Run diagnostic checks:

# General diagnostics
ckb doctor

# Check requirements for a specific tier
ckb doctor --tier enhanced
ckb doctor --tier full

# Output as JSON
ckb doctor --format json

General Diagnostics (no flags):

  • Configuration validity
  • Backend availability
  • SCIP index presence and freshness
  • Orphaned index detection (index exists but source files missing)
  • Database integrity
  • Optional tools availability (gh CLI, git version)

Orphaned Index Check:

CKB detects when a SCIP index exists but the source files it references are missing:

Index Status:
  ⚠ Orphaned index detected
    Index references files that no longer exist.
    This can happen after branch switches or major refactors.
    Run 'ckb index --force' to rebuild.

Optional Tools Check:

CKB checks for optional tools that enhance functionality:

Optional Tools:
  ✓ gh CLI v2.40.0 (enables PR integration)
  ✓ git v2.43.0 (minimum: v2.25.0)
  ⚠ jq not found (optional: enables JSON filtering in scripts)

Tier-Specific Diagnostics (--tier flag):

Checks if required tools are installed for a specific analysis tier:

ckb doctor --tier enhanced

Example output:

CKB Doctor - Enhanced Tier Requirements
=============================================

Go: Y Ready
  Y scip-go v1.0.0

TypeScript: N Not Ready
  N scip-typescript not found
    Suggested install: npm install -g @sourcegraph/scip-typescript

Summary: 1/2 languages ready for enhanced tier.

Flags:

Flag Description
--tier Check requirements for specific tier (basic, enhanced, full)
--format Output format (human, json)
--fix Output fix script with suggested commands
--check Run specific check only (git, scip, lsp, config, storage)

Tier names: Accepts both naming conventions:

  • basic or fast — Tree-sitter only (always available)
  • enhanced or standard — Requires SCIP indexers
  • full — Requires SCIP indexers + LSP servers

ckb setup

Configure CKB as an MCP server for AI coding tools.

# Interactive setup - select AI tool and scope
ckb setup

# Configure for a specific tool
ckb setup --tool=claude-code
ckb setup --tool=cursor
ckb setup --tool=windsurf
ckb setup --tool=vscode
ckb setup --tool=opencode
ckb setup --tool=claude-desktop

# Configure globally (applies to all projects)
ckb setup --tool=cursor --global

# Use npx for portable setup
ckb setup --tool=claude-code --npx

Supported Tools:

Tool Project Config Global Config
Claude Code .mcp.json claude mcp add
Cursor .cursor/mcp.json ~/.cursor/mcp.json
Windsurf N/A ~/.codeium/mcp_config.json
VS Code .vscode/mcp.json code --add-mcp
OpenCode opencode.json ~/.config/opencode/opencode.json
Claude Desktop N/A Platform-specific config

Flags:

Flag Description
--tool AI tool to configure (claude-code, cursor, windsurf, vscode, opencode, claude-desktop)
--global Configure globally for all projects
--npx Use npx @tastehub/ckb instead of local binary

For manual configuration or other MCP clients, see MCP Integration.

ckb search

Search for symbols:

# Basic search
ckb search "myFunction"

# Filter by kind
ckb search "User" --kinds=class,interface

# Limit results
ckb search "handle" --limit=10

# Search within module
ckb search "process" --scope=internal/api

ckb refs

Find references to a symbol:

# Find all references
ckb refs "symbol-id"

# Limit scope
ckb refs "symbol-id" --scope=internal/

# Include test files
ckb refs "symbol-id" --include-tests

ckb impact

Analyze impact of changing a symbol:

# Basic impact analysis
ckb impact "symbol-id"

# Set analysis depth (1-4, default 2)
ckb impact "symbol-id" --depth=3

# Include telemetry data
ckb impact "symbol-id" --telemetry --period=90d

Output includes (v7.6+):

  • Blast radius summary (module count, file count, unique callers, risk level)
  • Direct callers (distance 1)
  • Transitive callers (distance 2+, when depth > 1)
  • Risk score with 4-factor breakdown
  • Affected modules with impact counts

ckb affected-tests (v7.5)

Find tests affected by code changes. Dramatically reduces CI time by running only relevant tests.

# Get tests for uncommitted changes
ckb affected-tests

# Output as runnable command
ckb affected-tests --output=command
# → go test -run 'TestAuth|TestLogin' ./...

# Output as simple list (one test per line)
ckb affected-tests --format=list

# Specify coverage file
ckb affected-tests --coverage=./coverage/lcov.info

# Strategy options
ckb affected-tests --strategy=precise  # Only tests directly covering changes
ckb affected-tests --strategy=safe     # Include transitive tests (default)
ckb affected-tests --strategy=full     # All tests in affected packages

Flags:

Flag Default Description
--output - Output format: command (runnable), default shows details
--format - list for one test per line, json for machine-readable
--coverage auto Path to coverage file
--strategy safe Test selection strategy

See Impact-Analysis#affected-tests-v80 for full documentation.

ckb reviewers

Get suggested reviewers for code changes based on CODEOWNERS and git history.

# Get reviewers for uncommitted changes
ckb reviewers

# Include owners of affected (not just changed) code
ckb reviewers --include-affected

# For a specific commit range
ckb reviewers --range=main..HEAD

# Output format for gh CLI
ckb reviewers --format=gh
# → user1,user2,@team-name

# JSON output for scripting
ckb reviewers --format=json

Flags:

Flag Default Description
--include-affected false Include owners of transitively affected code
--range - Git commit range
--format human Output format: human, json, gh

See Impact-Analysis#reviewer-suggestions for full documentation.

ckb serve

Start the HTTP API server:

# Default (localhost:8080)
ckb serve

# Custom port
ckb serve --port 8081

# Bind to all interfaces
ckb serve --host 0.0.0.0

# Start with index server mode (v7.3)
ckb serve --index-server --index-config config.toml

ckb token (v7.3)

Manage API tokens for the index server. Tokens are stored in the server data directory (default: ~/.ckb-server).

# Create a new token
ckb token create --name "CI Upload" --scopes write
ckb token create --name "Read-only" --scopes read --repos "myorg/*"
ckb token create --name "Admin" --scopes admin --expires 30d

# List all tokens
ckb token list
ckb token list --show-revoked
ckb token list --format json

# Revoke a token
ckb token revoke ckb_key_abc123

# Rotate a token (new secret, same key ID)
ckb token rotate ckb_key_abc123

Flags:

  • --name - Human-readable token name (required for create)
  • --scopes - Permissions: read, write, admin (required for create)
  • --repos - Restrict to repos matching glob patterns (e.g., myorg/*)
  • --expires - Expiration time (e.g., 30d, 1h, 2024-12-31)
  • --rate-limit - Custom rate limit (requests/minute)
  • --data-dir - Server data directory (default: ~/.ckb-server)
  • --format - Output format: human, json

Scopes:

Scope Permissions
read GET requests (symbol lookup, search)
write POST requests (upload index, create repo)
admin DELETE requests, token management

See Authentication for full configuration details.

ckb symbol

Get detailed information about a specific symbol:

# Get symbol by stable ID
ckb symbol "ckb:myrepo:sym:abc123"

# Output as human-readable format
ckb symbol "ckb:myrepo:sym:abc123" --format=human

# Use full repo state (includes dirty working tree)
ckb symbol "ckb:myrepo:sym:abc123" --repo-state-mode=full

ckb arch

Get a high-level architecture view of the codebase:

# Basic architecture overview
ckb arch

# Increase dependency depth
ckb arch --depth=3

# Include external dependencies
ckb arch --include-external-deps

# Force refresh (bypass cache)
ckb arch --refresh

ckb mcp

Start the MCP (Model Context Protocol) server for AI assistant integration:

# Start MCP server (stdio mode)
ckb mcp

# List available presets with tool counts and token estimates
ckb mcp --list-presets

# Start with a specific tool preset (v7.4)
ckb mcp --preset=review

# Start with verbose logging
ckb mcp --verbose

# Start with auto-reindex on changes (v7.2)
ckb mcp --watch

# Start for a specific repository (v7.3)
ckb mcp --repo /path/to/repo

Tool Presets (v7.4):

Presets reduce token overhead by up to 83% by limiting exposed tools to task-relevant sets. Use --list-presets to see all options. The default core preset (14 tools) covers most workflows; the AI can expand mid-session if needed.

See Presets for complete preset documentation including tool lists and configuration examples.

Repository Selection (v7.3):

By default, CKB uses the current directory. For tools like Claude Desktop that don't have a project context, you can specify the repository:

  1. --repo flag: ckb mcp --repo /path/to/repo
  2. CKB_REPO environment variable: CKB_REPO=/path/to/repo ckb mcp

Priority: --repo flag > CKB_REPO env var > current directory

Watch Mode (v7.2):

With --watch, CKB polls for changes every 30 seconds:

  • Checks index freshness against current repo state
  • If stale (commits behind or uncommitted changes), triggers reindex
  • Logs reindex activity to stderr
  • Uses lock file to prevent conflicts with manual ckb index

This is useful for long-running MCP sessions where you want the index to stay fresh automatically.

See MCP Integration for Claude Desktop setup and Presets for preset configuration.

ckb diag

Create a diagnostic bundle for troubleshooting:

# Create diagnostic bundle
ckb diag --out ckb-diagnostic.zip

# Anonymize symbol names and paths
ckb diag --out ckb-diagnostic.zip --anonymize

The bundle includes sanitized configuration, doctor output, backend status, and system information. It excludes source code and sensitive credentials.

ckb refresh

Refresh the architectural model:

# Refresh everything
ckb refresh

# Refresh only ownership
ckb refresh --scope ownership

# Force refresh even if data is fresh
ckb refresh --force

# Dry run - see what would change
ckb refresh --dry-run

Scopes:

  • all - Refresh everything (default)
  • modules - Module detection only
  • ownership - CODEOWNERS + git blame
  • hotspots - Hotspot snapshots
  • responsibilities - Module responsibilities

ckb ownership

Query code ownership:

# Get ownership for a file
ckb ownership internal/api/handler.go

# Get ownership for a module
ckb ownership --module internal/api

# Include ownership history
ckb ownership internal/api/handler.go --history

ckb decisions

Work with Architectural Decision Records (ADRs). ADRs document important architectural choices and their rationale.

# List all decisions
ckb decisions

# Filter by status
ckb decisions --status accepted

# Search decisions
ckb decisions --search "caching"

# Create a new decision (interactive)
ckb decisions create --interactive

# Create with flags
ckb decisions create \
  --title "Use Redis for caching" \
  --context "User sessions need fast access..." \
  --decision "We will use Redis with 1-hour TTL" \
  --consequence "New infrastructure dependency" \
  --module internal/cache \
  --alternative "Memcached"

v6.5 Integration: Once you create an ADR with --module, it automatically appears in:

  • ckb explain <symbol> - Shows related ADRs for the symbol's module
  • ckb justify <symbol> - Prevents "remove" verdict for intentionally kept code
  • ckb impact <symbol> - Lists ADRs for affected modules
  • MCP tools: explainSymbol, justifySymbol, analyzeImpact, getModuleOverview

Example workflow:

# 1. Record why you're keeping "unused" extension points
ckb decisions create \
  --title "Plugin extension points" \
  --context "Need extensibility for third-party plugins" \
  --decision "Keep extension interfaces even without current callers" \
  --module internal/plugins \
  --status accepted

# 2. Now justifySymbol won't flag plugin interfaces as dead code
ckb justify internal/plugins/PluginInterface
# Returns: "investigate" with "related to ADR-001: Plugin extension points"

ckb federation

Manage repository federations for cross-repo queries. See Federation for full documentation.

# Create a federation
ckb federation create platform --description "Our microservices"

# Add repositories
ckb federation add platform --repo-id=api --path=/code/api-service
ckb federation add platform --repo-id=auth --path=/code/auth-service

# List federations
ckb federation list

# Check federation status
ckb federation status platform

# List repos in federation
ckb federation repos platform

# Sync federation index
ckb federation sync platform

# Rename a repo in federation
ckb federation rename platform old-api api

# Remove a repo from federation
ckb federation remove platform old-api

# Delete a federation
ckb federation delete platform --force

Remote Federation (v7.3):

# Add a remote CKB index server
ckb federation add-remote <federation> <name> --url=<url> [--token=<token>] [--cache-ttl=1h] [--timeout=30s]

# Remove a remote server
ckb federation remove-remote <federation> <name>

# List remote servers
ckb federation list-remote <federation> [--json]

# Sync metadata from remote server(s)
ckb federation sync-remote <federation> [name] [--json]

# Check remote server status
ckb federation status-remote <federation> <name> [--json]

# Enable/disable remote server
ckb federation enable-remote <federation> <name>
ckb federation disable-remote <federation> <name>

Subcommands:

  • create - Create a new federation
  • delete - Delete a federation
  • list - List all federations
  • status - Show federation status
  • add - Add a repository
  • remove - Remove a repository
  • rename - Rename a repository
  • repos - List repositories
  • sync - Sync federation index
  • search-modules - Search modules across federation
  • search-ownership - Search ownership across federation
  • hotspots - Get hotspots across federation
  • search-decisions - Search decisions across federation
  • add-remote - Add a remote CKB index server (v7.3)
  • remove-remote - Remove a remote server (v7.3)
  • list-remote - List remote servers (v7.3)
  • sync-remote - Sync metadata from remote server(s) (v7.3)
  • status-remote - Check remote server status (v7.3)
  • enable-remote - Enable a remote server (v7.3)
  • disable-remote - Disable a remote server (v7.3)

ckb daemon

Manage the CKB daemon for always-on code intelligence. See Daemon Mode for full documentation.

# Start the daemon
ckb daemon start [--port=9120] [--bind=localhost] [--foreground]

# Stop the daemon
ckb daemon stop

# Restart the daemon
ckb daemon restart

# Check daemon status
ckb daemon status

# View logs
ckb daemon logs [--follow] [--lines=100]

Subcommands:

  • start - Start the daemon process
  • stop - Stop the daemon gracefully
  • restart - Stop and start the daemon
  • status - Show daemon status and statistics
  • logs - View daemon log output

ckb daemon schedule

Manage scheduled tasks:

# List all schedules
ckb daemon schedule list

# Run a schedule immediately
ckb daemon schedule run <schedule-id>

# Enable/disable a schedule
ckb daemon schedule enable <schedule-id>
ckb daemon schedule disable <schedule-id>

ckb webhooks

Manage webhook notifications:

# List configured webhooks
ckb webhooks list

# Test a webhook
ckb webhooks test <webhook-id>

# View delivery history
ckb webhooks deliveries <webhook-id> [--status=failed]

# Retry failed deliveries
ckb webhooks retry <webhook-id>

# View dead letter queue
ckb webhooks dead-letter <webhook-id>

ckb contracts

Manage and analyze API contracts across federations. See Federation for full documentation.

# List all contracts in a federation
ckb contracts list platform

# Filter by repo, type, or visibility
ckb contracts list platform --repo=api --type=proto --visibility=public

# Analyze impact of changing a contract
ckb contracts impact platform --repo=api --path=proto/api/v1/user.proto

# Include transitive consumers and heuristic edges
ckb contracts impact platform --repo=api --path=proto/api/v1/user.proto --include-transitive --include-heuristic

# Get contract dependencies for a repo
ckb contracts deps platform --repo=api --direction=dependencies
ckb contracts deps platform --repo=api --direction=consumers
ckb contracts deps platform --repo=api --direction=both

# Show contract statistics
ckb contracts stats platform

# Suppress a false positive edge
ckb contracts suppress platform --edge=123 --reason="Not actually used"

# Verify an edge (increase confidence)
ckb contracts verify platform --edge=123

Subcommands:

  • list - List API contracts in a federation
  • impact - Analyze impact of changing a contract
  • deps - Get contract dependencies for a repository
  • stats - Show contract statistics
  • suppress - Suppress a false positive contract edge
  • verify - Verify a contract edge

Supported Contract Types:

  • proto - Protocol Buffers (.proto files)
  • openapi - OpenAPI/Swagger specifications (.yaml, .json)

ckb telemetry

Manage and query runtime telemetry data. See Configuration for telemetry setup.

# Check telemetry status and coverage
ckb telemetry status

# View observed usage for a symbol
ckb telemetry usage --repo=my-repo --symbol="internal/api/handler.go:HandleRequest"

# List services that couldn't be mapped to repos
ckb telemetry unmapped

# Test how a service name maps to a repo
ckb telemetry test-map "my-service-name"

Subcommands:

  • status - Show telemetry status and coverage metrics
  • usage - Show observed usage for a specific symbol
  • unmapped - List unmapped services
  • test-map - Test service → repo mapping

Coverage Levels:

Level Score Feature Access
High ≥ 0.80 Full: dead code, impact enrichment, usage display
Medium ≥ 0.60 Partial: usage display, impact enrichment (with warnings)
Low ≥ 0.40 Limited: usage display only (with caveats)
Insufficient < 0.40 None: telemetry features disabled

ckb dead-code

Find potential dead code using runtime telemetry. Requires telemetry to be enabled with medium+ coverage.

# Find dead code candidates in current repo
ckb dead-code

# Find dead code with higher confidence threshold
ckb dead-code --min-confidence=0.8

# Find dead code in a specific repo
ckb dead-code --repo=my-repo

# Limit results
ckb dead-code --limit=50

Flags:

Flag Default Description
--repo current Repository ID to analyze
--min-confidence 0.7 Minimum confidence threshold (0-1)
--limit 100 Maximum candidates to return

Output includes:

  • Symbol name and file path
  • Static reference count
  • Confidence score (capped at 0.90)
  • Coverage context

Important: Dead code detection is advisory. Always verify before deleting code. See Configuration for exclusion patterns.

ckb explain

Explain why code exists with full context—origin, evolution, warnings, and related references.

# Explain a file
ckb explain internal/api/handler.go

# Explain a specific line
ckb explain internal/api/handler.go:42

# Include co-change information
ckb explain internal/api/handler.go --co-change

# Skip usage analysis for faster response
ckb explain internal/api/handler.go --no-usage

# Limit history entries
ckb explain internal/api/handler.go --history-limit=20

Flags:

Flag Default Description
--co-change true Include co-change coupling data
--usage true Include usage analysis
--history-limit 10 Maximum history entries to show

Output includes:

  • Origin (who created it, when, why)
  • Evolution timeline (changes over time)
  • Contributors and bus factor
  • Co-changes (files that change together)
  • Warnings (stale, temporary code, high coupling)
  • References (linked issues, PRs, JIRA tickets)

ckb coupling

Analyze co-change coupling—find files that historically change together.

# Analyze coupling for a file
ckb coupling internal/query/engine.go

# Set minimum correlation threshold
ckb coupling internal/query/engine.go --min-correlation=0.5

# Extend time window (days)
ckb coupling internal/query/engine.go --window=730

# Limit results
ckb coupling internal/query/engine.go --limit=10

Flags:

Flag Default Description
--min-correlation 0.3 Minimum correlation to include (0-1)
--window 365 Time window in days
--limit 20 Maximum results

Output includes:

  • Coupled files with correlation scores
  • Co-commit counts
  • Shared authors
  • Last co-change date
  • Coupling summary (strong/moderate/weak)
  • Insights and recommendations

ckb export

Export codebase structure in LLM-friendly format.

# Full export
ckb export

# Filter by complexity
ckb export --min-complexity=10

# Filter by usage
ckb export --min-calls=100

# Limit symbols
ckb export --max-symbols=200

# Exclude optional data
ckb export --no-usage --no-ownership

# Output to file
ckb export --out codebase-summary.txt

Flags:

Flag Default Description
--usage true Include call counts (requires telemetry)
--ownership true Include owners
--contracts true Include contract information
--complexity true Include complexity metrics
--min-complexity 0 Skip symbols below this complexity
--min-calls 0 Skip symbols below this call count
--max-symbols unlimited Maximum symbols to include
--out stdout Output file path

Output format:

# Codebase: my-project
# Symbols: 150 | Files: 45 | Modules: 8

## internal/api/ (owner: @api-team)
  ! handler.go
      $ Server                  c=5  calls=10k/day ★★★
      # HandleRequest()         c=12 calls=8k/day  ★★★

ckb audit

Audit codebase for risky code based on multiple weighted signals.

# Full risk audit
ckb audit

# Set minimum risk score
ckb audit --min-score=60

# Focus on specific factor
ckb audit --factor=complexity

# Get quick wins (high impact, low effort)
ckb audit --quick-wins

# Limit results
ckb audit --limit=20

Flags:

Flag Default Description
--min-score 40 Minimum risk score (0-100)
--limit 50 Maximum results
--factor all Focus on specific factor
--quick-wins false Return only high-impact, low-effort items

Risk Factors (weighted):

Factor Weight Description
Complexity 20% Cyclomatic/cognitive complexity
Test Coverage 20% Lack of test coverage
Bus Factor 15% Single-author code
Security 15% Handles auth, crypto, PII
Staleness 10% Not touched in 6+ months
Error Rate 10% Runtime error frequency
Coupling 5% High co-change coupling
Churn 5% Frequent modifications

Output includes:

  • Risk score per file/symbol
  • Factor breakdown with weights
  • Top contributing factors
  • Remediation suggestions
  • Quick wins (when --quick-wins enabled)

ckb modules

Get module overview and manage module annotations.

# Get overview of current directory
ckb modules

# Get overview of specific module
ckb modules internal/api

# Get with friendly name
ckb modules --name="API Layer" internal/api

# Human-readable output
ckb modules --format=human

Subcommands:

ckb modules annotate

Add or update module metadata. Annotations are persisted and used by other CKB tools.

# Add responsibility
ckb modules annotate internal/api --responsibility="HTTP API handlers"

# Add capabilities and tags
ckb modules annotate internal/api --capabilities="REST,WebSocket" --tags="core,infrastructure"

# Define API boundaries
ckb modules annotate internal/api --public-paths="handler.go,routes.go" --internal-paths="helpers.go"

# Full annotation
ckb modules annotate internal/auth \
  --responsibility="OAuth2 token validation and session management" \
  --capabilities="OAuth2,JWT,Sessions" \
  --tags="security,core"

v6.5 Integration: Annotated modules get richer context in:

  • ckb modules / getModuleOverview - Shows annotations in output
  • ckb explain <symbol> / explainSymbol - Includes module annotations
  • ckb modules responsibilities / getModuleResponsibilities - Declared annotations override inferred with higher confidence

Declared vs Inferred:

  • Without annotation: CKB infers responsibility from code (lower confidence)
  • With annotation: Your declared responsibility is used (higher confidence, source: "declared")

ckb modules responsibilities

Get responsibilities for modules:

# Get all module responsibilities
ckb modules responsibilities

# Get for specific module
ckb modules responsibilities internal/api

# Include file-level responsibilities
ckb modules responsibilities --include-files

# Limit results
ckb modules responsibilities --limit=50

ckb justify

Get keep/investigate/remove verdict for a symbol with evidence.

# Justify a symbol
ckb justify 'scip-go gomod myproject myproject/pkg/MyFunction'

# Human-readable output
ckb justify --format=human 'symbol-id'

Returns verdict (keep/investigate/remove) with evidence including:

  • Reference count
  • Export status
  • Entrypoint relationships
  • Telemetry usage data

ckb callgraph

Get caller/callee relationships for a symbol.

# Get full call graph (both directions)
ckb callgraph 'symbol-id'

# Callers only
ckb callgraph --direction=callers 'symbol-id'

# Callees only
ckb callgraph --direction=callees 'symbol-id'

# Set traversal depth (1-4)
ckb callgraph --depth=2 'symbol-id'

ckb entrypoints

List system entrypoints (API handlers, CLI mains, background jobs).

# List all entrypoints
ckb entrypoints

# Filter by module
ckb entrypoints --module=internal/api

# Limit results
ckb entrypoints --limit=50

ckb trace

Trace how a symbol is reached from system entrypoints.

# Trace usage paths
ckb trace 'symbol-id'

# Limit paths returned
ckb trace --max-paths=20 'symbol-id'

# Set maximum path depth
ckb trace --max-depth=3 'symbol-id'

ckb hotspots

Find high-churn, high-complexity code areas.

# Get hotspots
ckb hotspots

# Top N hotspots
ckb hotspots --limit=50

# Filter by minimum score
ckb hotspots --min-score=0.5

# Filter by module
ckb hotspots --module=internal/api

ckb diff-summary

Summarize what changed and what might break.

# Default: last 30 days
ckb diff-summary

# Single commit
ckb diff-summary --commit=abc1234

# Commit range
ckb diff-summary --base=main --head=feature/my-branch

# Time window
ckb diff-summary --start=2024-01-01 --end=2024-06-30

ckb pr-summary

Analyze a pull request with risk assessment.

# Analyze current branch's PR
ckb pr-summary

# Analyze specific PR by number
ckb pr-summary --pr=123

# Specify base branch
ckb pr-summary --base=main --head=feature/my-branch

ckb jobs

Manage background jobs.

# List all jobs
ckb jobs list

# Get job status
ckb jobs status <job-id>

# Cancel a job
ckb jobs cancel <job-id>

ckb concepts

Discover key codebase concepts.

# List key concepts
ckb concepts

# Limit results
ckb concepts --limit=30

# Filter by minimum importance
ckb concepts --min-importance=0.5

ckb recent

Find recently relevant files.

# Get recently relevant files
ckb recent

# Within specific time window (days)
ckb recent --days=7

# Limit results
ckb recent --limit=30

ckb complexity

Get complexity metrics for a file.

# Analyze file complexity
ckb complexity path/to/file.go

# Include function-level breakdown
ckb complexity --functions path/to/file.go

ckb docs

Manage documentation-symbol linking. See Doc-Symbol Linking for full documentation.

# Index documentation for symbol references
ckb docs index

# Force re-index all docs
ckb docs index --force

# Find docs that reference a symbol
ckb docs symbol Engine.Start

# List symbols referenced in a document
ckb docs file README.md

# Check for stale references in a document
ckb docs stale README.md

# Check all docs for stale references
ckb docs stale --all

# Get documentation coverage statistics
ckb docs coverage

# Fail CI if coverage below threshold
ckb docs coverage --fail-under=80

# Find docs linked to a module
ckb docs module internal/api

Subcommands:

  • index - Scan and index documentation for symbol references
  • symbol <name> - Find docs referencing a symbol
  • file <path> - Show symbols in a document
  • stale [path] - Check for stale references (--all for all docs)
  • coverage - Documentation coverage statistics
  • module <id> - Find docs linked to a module via directive

Flags for coverage:

Flag Description
--fail-under Exit code 1 if coverage below threshold (0-100)
--exported-only Only count exported/public symbols
--top Number of top undocumented symbols to show (default: 10)

Detection Methods:

  • Backtick references: UserService.Authenticate
  • Directive references: <!-- ckb:symbol full.symbol.path -->
  • Module linking: <!-- ckb:module internal/auth -->
  • Fence scanning: Extracts symbols from fenced code blocks (8 languages)

ckb repo

Manage the global repository registry. This enables quick context switching between multiple repositories in MCP sessions.

# Add current directory to registry
ckb repo add myproject

# Add a specific path
ckb repo add api /path/to/api

# List all registered repos
ckb repo list

# Set default repo
ckb repo default myproject

# Get repo info
ckb repo info myproject

# Remove a repo from registry
ckb repo remove myproject

# Rename a repo alias
ckb repo rename old-name new-name

# Print current repo (for scripts)
ckb repo which

# Validate all registered repos
ckb repo check

Subcommands:

Command Description
add [name] [path] Register a repo. Path defaults to cwd, name defaults to directory name
list List all repos grouped by state (valid, uninitialized, missing)
remove <name> Unregister a repo
rename <old> <new> Rename a repo alias
default [name] Get or set the default repo
use <name> Alias for default
info [name] Show detailed repo info
which Print current repo (exits 1 if none)
check Validate all repos and report status

Flags:

Flag Description
--force Overwrite if name exists (for add)
--json JSON output (for list, info, check)

Repo States:

  • valid - Path exists and .ckb/ is initialized
  • uninitialized - Path exists but .ckb/ is missing
  • missing - Path no longer exists

MCP Integration:

Use the --repo flag to start MCP with a specific repo active:

ckb mcp --repo myproject

Or use MCP tools to switch context:

  • listRepos - List available repos
  • switchRepo(name) - Switch to a different repo
  • getActiveRepo - Get current repo info

Registry Location: ~/.ckb/repos.json

ckb metrics (v7.4)

View and export wide-result metrics for tool optimization.

# View aggregated metrics
ckb metrics

# Filter by time range
ckb metrics --days=30

# Filter by tool
ckb metrics --tool=findReferences

# Output formats
ckb metrics --format=human   # Default, human-readable
ckb metrics --format=json    # Machine-readable

# Export for version comparison
ckb metrics export --version=v7.4 > benchmarks/v7.4.json
ckb metrics export --version=v7.5 > benchmarks/v7.5.json

Tracked tools: searchSymbols, findReferences, analyzeImpact, getCallGraph, getHotspots, summarizePr

Metrics tracked:

  • Invocations per tool
  • Bytes/tokens per response
  • Truncation rates
  • Response size distribution

See Telemetry#wide-result-metrics for full documentation.

ckb eval (v7.4)

Evaluate hybrid retrieval quality. Used for testing search improvements.

# Run evaluation suite
ckb eval

# Custom fixtures
ckb eval --fixtures=./my-tests.json

# JSON output for CI
ckb eval --format=json

# Verbose output with per-query details
ckb eval --verbose

Output metrics:

  • Recall@K (how many relevant results found in top K)
  • MRR (Mean Reciprocal Rank)
  • Latency (p50, p95, p99)

See Hybrid-Retrieval#evaluation for fixture format.

ckb diff (v7.3)

Generate delta manifests for server-side ingestion. Used in CI for O(delta) updates.

# Compare two snapshot databases
ckb diff \
  --base /path/to/old-snapshot.db \
  --new /path/to/new-snapshot.db \
  --output delta.json

Output: A delta JSON manifest containing:

  • Added/modified/deleted symbols
  • Added/deleted references
  • Added/deleted call graph edges
  • File changes

Use case: CI generates deltas that the CKB server can ingest in O(delta) time instead of O(N) full comparison.

See Incremental-Indexing#delta-artifacts-v4 for full documentation.

Working with Responses

Response Structure

All CKB responses include:

{
  "data": { ... },
  "provenance": {
    "backends": ["scip", "lsp"],
    "repoStateId": "abc123...",
    "cachedAt": "2025-12-16T12:00:00Z"
  },
  "warnings": [],
  "drilldowns": []
}

Drilldowns

When results are truncated, CKB suggests follow-up queries:

{
  "drilldowns": [
    {
      "label": "Explore top module: internal/api",
      "query": "getModuleOverview internal/api",
      "relevanceScore": 0.9
    }
  ]
}

Warnings

CKB reports limitations in analysis:

{
  "warnings": [
    {
      "severity": "warning",
      "text": "SCIP index is 3 commits behind HEAD"
    }
  ]
}

CI/CD Integration

For GitHub Actions workflows, PR analysis, and automated architecture refresh, see the dedicated CI/CD Integration guide.

Best Practices

Keep SCIP Index Fresh

CKB tracks index freshness automatically (v7.2). Just run:

ckb index

It will:

  • Skip if index is current ("Index is current")
  • Reindex if stale ("Index is stale: 3 commit(s) behind HEAD")
  • Show what's changed before reindexing

For long-running sessions, use watch mode:

ckb mcp --watch   # Auto-reindexes every 30s when stale

Use Scoped Queries

For large codebases, scope queries to specific modules:

ckb search "handler" --scope=internal/api

Monitor Cache

Check cache statistics to ensure efficient operation:

ckb status

Keep Ownership Data Fresh

Ownership drift happens when CODEOWNERS says one thing but git history shows someone else actually maintains the code. This matters for:

  • Getting accurate reviewer suggestions
  • Understanding who to ask about code changes
  • Keeping CODEOWNERS accurate

Check for drift:

ckb ownership drift --threshold=0.3

Refresh ownership data:

ckb refresh --scope ownership

How often? Weekly is sufficient — ownership patterns change slowly. Unlike the SCIP index (which should stay current with code changes), ownership is based on months of git history and drifts gradually.

Automation options:

Run Doctor Regularly

ckb doctor

Fix any issues before they impact queries.

Troubleshooting

"Backend unavailable" errors

  1. Check if the backend is installed
  2. Run ckb doctor to diagnose
  3. Check backend-specific configuration in .ckb/config.json

Stale results

  1. Check repository state with ckb status
  2. Regenerate SCIP index if stale
  3. Clear cache: ckb cache clear

Slow queries

  1. Ensure SCIP index exists (fastest backend)
  2. Reduce query scope
  3. Lower result limits
  4. Check if LSP server is responsive

Next Steps

  • Daemon Mode - Always-on service with scheduler, watcher, and webhooks
  • Federation - Cross-repository queries, contract analysis, and unified visibility
  • API Reference - Detailed API documentation
  • Configuration - All configuration options, telemetry setup, MODULES.toml format, and ADR workflow
  • Architecture - How CKB works internally
  • MCP Integration - AI assistant integration with 76 MCP tools

Clone this wiki locally