Skip to content

API Reference

Lisa edited this page Dec 18, 2025 · 15 revisions

CKB HTTP API

REST API for Code Knowledge Backend (CKB) providing codebase comprehension capabilities.

Quick Start

# Start the server (default: localhost:8080)
./ckb serve

# Start on custom port
./ckb serve --port 8081

# Start on custom host
./ckb serve --host 0.0.0.0 --port 8080

API Endpoints

System & Health

GET /

Root endpoint with API information and available endpoints.

curl http://localhost:8080/

GET /health

Simple liveness check for load balancers.

curl http://localhost:8080/health

Response:

{
  "status": "healthy",
  "timestamp": "2024-12-16T12:00:00Z",
  "version": "0.1.0"
}

GET /ready

Readiness check that verifies backend availability.

curl http://localhost:8080/ready

Response:

{
  "status": "ready",
  "timestamp": "2024-12-16T12:00:00Z",
  "backends": {
    "scip": true,
    "lsp": true,
    "git": true
  }
}

GET /status

Comprehensive system status including repository, backends, and cache.

curl http://localhost:8080/status

Diagnostics

GET /doctor

Run diagnostic checks on all system components.

curl http://localhost:8080/doctor

Response:

{
  "status": "healthy",
  "timestamp": "2024-12-16T12:00:00Z",
  "checks": [
    {"name": "config", "status": "pass", "message": "Configuration is valid"},
    {"name": "scip", "status": "pass", "message": "SCIP backend available"}
  ],
  "issues": [],
  "summary": {
    "total": 4,
    "passed": 4,
    "warnings": 0,
    "failed": 0
  }
}

POST /doctor/fix

Get a fix script for detected issues.

curl -X POST http://localhost:8080/doctor/fix

Symbol Operations

GET /symbol/:id

Retrieve detailed information about a symbol.

curl http://localhost:8080/symbol/my-symbol-id

Response:

{
  "id": "my-symbol-id",
  "name": "ExampleSymbol",
  "kind": "function",
  "location": {
    "file": "example.go",
    "line": 42
  },
  "module": "example"
}

GET /search

Search for symbols matching a query.

Query Parameters:

  • q (required) - Search query
  • scope - Module ID to search within
  • kinds - Comma-separated list of symbol kinds
  • limit - Maximum results (default: 50)
  • merge - Merge strategy: "prefer-first" or "union"
  • repoStateMode - Repository state: "head" or "full"
  • depth - Search depth (default: 1)
  • includeExternal - Include external symbols (true/false)
  • refresh - Force refresh cache (true/false)
curl "http://localhost:8080/search?q=myFunction&limit=10&kinds=function,method"

Response:

{
  "query": "myFunction",
  "results": [],
  "total": 0,
  "hasMore": false,
  "timestamp": "2024-12-16T12:00:00Z"
}

GET /refs/:id

Find all references to a symbol.

curl http://localhost:8080/refs/my-symbol-id

Response:

{
  "symbolId": "my-symbol-id",
  "references": [],
  "total": 0,
  "timestamp": "2024-12-16T12:00:00Z"
}

Analysis

GET /architecture

Get an overview of the codebase architecture.

curl http://localhost:8080/architecture

Response:

{
  "timestamp": "2024-12-16T12:00:00Z",
  "modules": [],
  "dependencies": [],
  "metrics": {}
}

GET /impact/:id

Analyze the impact of changing a symbol.

curl http://localhost:8080/impact/my-symbol-id

Response:

{
  "symbolId": "my-symbol-id",
  "timestamp": "2024-12-16T12:00:00Z",
  "impact": {},
  "affected": [],
  "risk": "low"
}

Ownership & Architecture

GET /ownership

Get ownership for a file path or module.

Query Parameters:

  • path - File path to query ownership for
  • moduleId - Module ID to query ownership for (alternative to path)
  • includeHistory - Include ownership change history (true/false)
# Get ownership for a file
curl "http://localhost:8080/ownership?path=internal/api/handler.go"

# Get ownership for a module
curl "http://localhost:8080/ownership?moduleId=internal/api"

# Include ownership history
curl "http://localhost:8080/ownership?path=internal/api/handler.go&includeHistory=true"

Response:

{
  "path": "internal/api/handler.go",
  "owners": [
    {
      "identity": "@api-team",
      "scope": "maintainer",
      "source": "codeowners",
      "confidence": 1.0
    },
    {
      "identity": "alice@example.com",
      "scope": "reviewer",
      "source": "git-blame",
      "confidence": 0.79,
      "weightedLines": 0.35
    }
  ],
  "suggestedReviewers": ["@api-team", "alice@example.com"],
  "timestamp": "2024-12-16T12:00:00Z"
}

GET /responsibilities/:moduleId

Get responsibilities for a module.

curl http://localhost:8080/responsibilities/internal/api

Response:

{
  "moduleId": "internal/api",
  "summary": "HTTP API handlers and middleware",
  "capabilities": ["request routing", "authentication", "response formatting"],
  "keySymbols": ["Handler", "Router", "Middleware"],
  "confidence": 0.85,
  "source": "inferred",
  "timestamp": "2024-12-16T12:00:00Z"
}

GET /hotspots

Get hotspot analysis with trend data.

Query Parameters:

  • scope - Module or path to scope analysis
  • days - Time window in days (default: 30)
  • limit - Maximum results (default: 20)
curl "http://localhost:8080/hotspots?scope=internal/query&days=30&limit=20"

Response:

{
  "hotspots": [
    {
      "targetId": "internal/query/engine.go",
      "score": 0.85,
      "trend": {
        "direction": "increasing",
        "velocity": 0.02,
        "projection30d": 0.91
      },
      "metrics": {
        "churnCommits30d": 12,
        "churnAuthors30d": 3,
        "complexityCyclomatic": 25
      }
    }
  ],
  "timestamp": "2024-12-16T12:00:00Z"
}

GET /decisions

List or search Architectural Decision Records.

Query Parameters:

  • moduleId - Filter by affected module
  • status - Filter by status (proposed, accepted, deprecated, superseded)
  • search - Full-text search in title and content
# List all decisions
curl http://localhost:8080/decisions

# Filter by module
curl "http://localhost:8080/decisions?moduleId=internal/api"

# Search decisions
curl "http://localhost:8080/decisions?search=caching"

Response:

{
  "decisions": [
    {
      "id": "ADR-001",
      "title": "Use SCIP for code indexing",
      "status": "accepted",
      "createdAt": "2024-12-01T10:00:00Z",
      "affectedModules": ["internal/backends/scip"]
    }
  ],
  "total": 1,
  "timestamp": "2024-12-16T12:00:00Z"
}

POST /decisions

Create a new Architectural Decision Record.

curl -X POST http://localhost:8080/decisions \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Use Redis for caching",
    "context": "We need distributed caching for multi-instance deployments...",
    "decision": "We will use Redis as our caching layer...",
    "consequences": ["Requires Redis infrastructure", "Enables horizontal scaling"],
    "affectedModules": ["internal/cache"],
    "status": "proposed"
  }'

Response:

{
  "id": "ADR-002",
  "path": "~/.ckb/repos/<hash>/decisions/ADR-002-use-redis-for-caching.md",
  "status": "created",
  "timestamp": "2024-12-16T12:00:00Z"
}

POST /refresh

Refresh the architectural model.

Request Body:

{
  "scope": "all",
  "force": false,
  "dryRun": false
}

Scope options: all, modules, ownership, hotspots, responsibilities

# Refresh everything
curl -X POST http://localhost:8080/refresh \
  -H "Content-Type: application/json" \
  -d '{"scope": "all"}'

# Refresh only ownership
curl -X POST http://localhost:8080/refresh \
  -H "Content-Type: application/json" \
  -d '{"scope": "ownership"}'

# Dry run
curl -X POST http://localhost:8080/refresh \
  -H "Content-Type: application/json" \
  -d '{"scope": "all", "dryRun": true}'

Response:

{
  "status": "completed",
  "changes": {
    "modules": 5,
    "ownership": 12,
    "hotspots": 8,
    "responsibilities": 5
  },
  "duration": "2.5s",
  "timestamp": "2024-12-16T12:00:00Z"
}

Cache Operations

POST /cache/warm

Initiate cache warming for commonly accessed data.

curl -X POST http://localhost:8080/cache/warm

Response:

{
  "status": "success",
  "message": "Cache warming initiated",
  "timestamp": "2024-12-16T12:00:00Z"
}

POST /cache/clear

Clear all cached data.

curl -X POST http://localhost:8080/cache/clear

Response:

{
  "status": "success",
  "message": "Cache cleared",
  "timestamp": "2024-12-16T12:00:00Z"
}

Documentation

GET /openapi.json

Get the OpenAPI 3.0 specification for the API.

curl http://localhost:8080/openapi.json

Error Responses

All errors return a consistent JSON structure:

{
  "error": "Symbol not found",
  "code": "SYMBOL_NOT_FOUND",
  "details": null,
  "suggestedFixes": [
    {
      "type": "run-command",
      "command": "ckb doctor",
      "safe": true,
      "description": "Check system configuration"
    }
  ],
  "drilldowns": []
}

HTTP Status Codes

Status Meaning
200 Success
400 Bad Request - Invalid parameters
404 Not Found - Resource doesn't exist
410 Gone - Resource was deleted
412 Precondition Failed - Index stale
413 Payload Too Large - Budget exceeded
422 Unprocessable Entity - Validation error
429 Too Many Requests - Rate limited
500 Internal Server Error
503 Service Unavailable - Backend unavailable
504 Gateway Timeout

Request Headers

Supported Headers

  • X-Request-ID - Custom request ID (auto-generated if not provided)
  • Content-Type: application/json - For POST requests

Response Headers

  • Content-Type: application/json - All responses are JSON
  • X-Request-ID - Request ID for tracing
  • Access-Control-Allow-Origin: * - CORS enabled for local dev

Middleware

The API includes the following middleware (in order):

  1. CORS - Enables cross-origin requests
  2. Request ID - Generates unique request IDs
  3. Logging - Logs all requests and responses
  4. Recovery - Recovers from panics

Testing

Manual Testing

# Start server
./ckb serve --port 8081

# Test all endpoints
curl http://localhost:8081/health | jq .
curl http://localhost:8081/status | jq .
curl "http://localhost:8081/search?q=test" | jq .
curl -X POST http://localhost:8081/cache/clear | jq .

Using jq for Pretty Output

# Install jq if not already installed
brew install jq  # macOS
apt-get install jq  # Linux

# Pretty print responses
curl -s http://localhost:8080/status | jq .

Configuration

Server configuration via command-line flags:

Flag Default Description
--port 8080 Port to listen on
--host localhost Host to bind to

Graceful Shutdown

The server supports graceful shutdown via interrupt signals:

# Press Ctrl+C to stop the server
# Or send SIGTERM
kill -TERM <pid>

The server will:

  1. Stop accepting new connections
  2. Wait for active requests to complete (up to 10 seconds)
  3. Shut down cleanly

Logging

The API logs all requests and responses with:

  • HTTP method and path
  • Query parameters
  • Status code
  • Response time
  • Request ID

Example log output:

2024-12-16T12:00:00Z [info] HTTP request | method=GET, path=/status, requestID=abc-123
2024-12-16T12:00:01Z [info] HTTP response | method=GET, path=/status, status=200, duration=100ms, requestID=abc-123

Development

Building

go build -o ckb ./cmd/ckb

Running in Development

# Start with default settings
./ckb serve

# Start with custom port for development
./ckb serve --port 8081

Testing with curl

# Save to file
curl http://localhost:8080/status > status.json

# Show headers
curl -i http://localhost:8080/health

# Show request/response with verbose
curl -v http://localhost:8080/ready

Integration

With Frontend Applications

// Fetch status
fetch('http://localhost:8080/status')
  .then(res => res.json())
  .then(data => console.log(data));

// Search symbols
fetch('http://localhost:8080/search?q=myFunction&limit=10')
  .then(res => res.json())
  .then(data => console.log(data));

With Other Tools

# HTTPie
http GET localhost:8080/status

# wget
wget -qO- http://localhost:8080/health

# Python
python -c "import requests; print(requests.get('http://localhost:8080/status').json())"

Troubleshooting

Server won't start

# Check if port is already in use
lsof -i :8080

# Use different port
./ckb serve --port 8081

Connection refused

# Verify server is running
ps aux | grep ckb

# Check server logs for errors
./ckb serve 2>&1 | tee server.log

Invalid JSON responses

# Validate JSON
curl http://localhost:8080/status | jq .

# Check response headers
curl -i http://localhost:8080/status

Support

For issues or questions:

  1. Check the OpenAPI spec: GET /openapi.json
  2. Review server logs
  3. Check the implementation documentation: PHASE-4.2-IMPLEMENTATION.md

Clone this wiki locally