codeai

module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 13, 2026 License: MIT

README

CodeAI

Go Version License Build Status Coverage

A Go-based runtime for defining and executing AI agent specifications using a declarative domain-specific language (DSL). CodeAI provides a structured approach to building backend services with built-in support for databases, authentication, workflows, jobs, events, and integrations.


Table of Contents


Overview

CodeAI is a declarative backend framework that allows developers and LLMs to define entire backend services using a simple, readable DSL. Instead of writing boilerplate code for APIs, database schemas, authentication, and background jobs, you describe what you want and CodeAI generates the runtime.

Key Benefits
  • Declarative DSL: Define entities, endpoints, workflows, and jobs in a human-readable format
  • LLM-Friendly: Designed to be easily understood and generated by AI assistants
  • Production-Ready Infrastructure: Built-in auth, caching, circuit breakers, retry logic, and observability
  • Type-Safe: Full validation at parse time with detailed error messages
  • Extensible: Modular architecture with pluggable integrations
Target Audience
  • LLM Agents: Generate complete backend specifications programmatically
  • Backend Developers: Rapidly prototype and build production services
  • DevOps Engineers: Deploy standardized, observable microservices
  • Startups: Accelerate time-to-market with minimal boilerplate
Project Status

Version: 1.0 | Status: 90% Complete

Component Status
Go Runtime Infrastructure Production-Ready
CLI Tool Complete
Database Module (PostgreSQL) Complete
Database Module (MongoDB) Complete
HTTP/API Module (Chi Router) Complete
Authentication (JWT/JWKS/RBAC) Complete
Caching (Redis/Memory) Complete
Workflow Engine (Temporal) Complete
Job Scheduler (Asynq) Complete
Event System Complete
Integration Layer Complete
Observability Stack Complete
DSL Parser Complete (Core language)

Quick Start

One-Line Installation
go install github.com/bargom/codeai/cmd/codeai@latest
Or Build from Source
git clone https://github.com/bargom/codeai.git
cd codeai
make build
./bin/codeai version
Basic Usage
# Parse a DSL file
./bin/codeai parse myapp.cai

# Validate syntax
./bin/codeai validate myapp.cai

# Start the API server
./bin/codeai server start --db-name codeai

# Generate shell completions
./bin/codeai completion bash > /etc/bash_completion.d/codeai

Full Quick Start Guide


Features

DSL Language

Define your backend with a clean, declarative syntax:

Feature Description
Variables var name = "value"
Control Flow if, else, for-in loops
Functions User-defined with parameters
Shell Execution exec { kubectl get pods }
Comments Single-line // and multi-line /* */
Backend Modules
Module Description Technology
Database (PostgreSQL) Relational database with migrations, repositories lib/pq
Database (MongoDB) Document database with collections, embedded docs mongo-driver
HTTP/API RESTful endpoints with Chi router go-chi/chi
Authentication JWT validation, JWKS support, RBAC golang-jwt
Caching Redis and in-memory caching go-redis
Workflows Long-running processes with compensation Temporal
Job Scheduler Cron and interval-based jobs Asynq
Events Pub/sub event system with persistence Custom
Integrations REST/GraphQL clients with resilience Custom
Built-In Patterns
Pattern Description
Circuit Breaker Prevent cascade failures with configurable thresholds
Retry with Backoff Exponential and linear retry strategies
Saga Pattern Distributed transaction compensation
Rate Limiting Request throttling per client
Request Validation Automatic input validation
Pagination Cursor and offset-based pagination
Observability
Feature Technology
Structured Logging Go slog with JSON output
Metrics Prometheus with /metrics endpoint
Health Checks /health, /ready, /live endpoints
Tracing OpenTelemetry integration
Graceful Shutdown Clean connection draining
OpenAPI Generation

Automatic OpenAPI 3.0 specification generation from your DSL definitions.


DSL Example

Simple Application
// myapp.cai - Configuration Example

var appName = "MyService"
var environment = "production"
var maxConnections = 100

// Feature flags
var features = ["auth", "caching", "metrics"]
var debugMode = false

// Process each feature
for feature in features {
    var current = feature
}

// Conditional configuration
if debugMode {
    var logLevel = "debug"
} else {
    var logLevel = "info"
}

// Initialize service
exec {
    echo "Starting $appName in $environment"
}
Parse and Validate
# Parse to JSON AST
./bin/codeai parse --output json myapp.cai

# Validate syntax and semantics
./bin/codeai validate myapp.cai
API Interaction
# Health check
curl http://localhost:8080/health

# Create a configuration
curl -X POST http://localhost:8080/configs \
  -H "Content-Type: application/json" \
  -d '{"name": "myapp", "content": "var x = 1"}'

# List configurations
curl http://localhost:8080/configs

# Execute a deployment
curl -X POST http://localhost:8080/deployments/UUID/execute

Architecture

┌─────────────────────────────────────────────────────────────────────────┐
│                              HTTP Layer                                  │
│  ┌───────────────────────────────────────────────────────────────────┐  │
│  │              Chi Router + Middleware Stack                         │  │
│  │  (RequestID, RealIP, Logger, Recoverer, Timeout, JSON)            │  │
│  └───────────────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────┘
                                    │
                    ┌───────────────┼───────────────┐
                    ▼               ▼               ▼
            ┌───────────┐   ┌───────────┐   ┌───────────┐
            │   Auth    │   │  Handlers │   │  OpenAPI  │
            │Middleware │   │  (CRUD)   │   │   Docs    │
            └───────────┘   └───────────┘   └───────────┘
                                    │
┌─────────────────────────────────────────────────────────────────────────┐
│                        Business Logic Layer                              │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐               │
│  │  Parser  │  │ Workflow │  │Scheduler │  │ Validator│               │
│  │  (DSL)   │  │(Temporal)│  │ (Asynq)  │  │          │               │
│  └──────────┘  └──────────┘  └──────────┘  └──────────┘               │
└─────────────────────────────────────────────────────────────────────────┘
                                    │
┌─────────────────────────────────────────────────────────────────────────┐
│                       Infrastructure Layer                               │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐               │
│  │ Database │  │  Event   │  │  Cache   │  │Integration│               │
│  │(Postgres)│  │   Bus    │  │ (Redis)  │  │(REST/GQL)│               │
│  └──────────┘  └──────────┘  └──────────┘  └──────────┘               │
└─────────────────────────────────────────────────────────────────────────┘
                                    │
┌─────────────────────────────────────────────────────────────────────────┐
│                      Cross-Cutting Concerns                              │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐               │
│  │ Logging  │  │ Metrics  │  │  Health  │  │ Shutdown │               │
│  │ (slog)   │  │(Promethe)│  │  Checks  │  │ Graceful │               │
│  └──────────┘  └──────────┘  └──────────┘  └──────────┘               │
└─────────────────────────────────────────────────────────────────────────┘
Directory Structure
codeai/
├── cmd/codeai/           # CLI entry point (Cobra commands)
│   └── cmd/              # parse, validate, server, deploy, config
├── internal/             # Private application code
│   ├── api/              # HTTP handlers, router, server
│   ├── ast/              # Abstract Syntax Tree definitions
│   ├── auth/             # JWT validation, JWKS, middleware
│   ├── cache/            # Redis and memory caching
│   ├── database/         # PostgreSQL, migrations, repositories
│   ├── event/            # Event bus and dispatching
│   ├── health/           # Health check endpoints
│   ├── openapi/          # OpenAPI specification generation
│   ├── pagination/       # Pagination utilities
│   ├── parser/           # DSL lexer and parser (Participle)
│   ├── query/            # Query builder and executor
│   ├── rbac/             # Role-based access control
│   ├── scheduler/        # Asynq job scheduler
│   ├── shutdown/         # Graceful shutdown handling
│   ├── validation/       # Input validation middleware
│   ├── validator/        # AST validation
│   ├── webhook/          # Webhook delivery system
│   └── workflow/         # Temporal workflow orchestration
├── pkg/                  # Public libraries
│   ├── integration/      # REST, GraphQL clients, circuit breaker
│   ├── logging/          # Structured logging utilities
│   ├── metrics/          # Prometheus metrics
│   └── types/            # Shared type definitions
├── config/               # Configuration files (YAML)
├── docs/                 # Documentation
└── test/                 # Integration and performance tests

Requirements

Required
Dependency Version Purpose
Go 1.24+ Runtime and build
PostgreSQL 14+ Primary database
Make Any Build automation
Optional
Dependency Version Purpose
MongoDB 4.4+ Document database (alternative/complement to PostgreSQL)
Redis 6+ Caching layer
Docker 20+ Containerization, integration tests
Temporal 1.20+ Workflow orchestration
Verify Installation
go version          # go1.24.0 or higher
psql --version      # PostgreSQL 14.x or higher
make --version      # GNU Make 3.81 or higher

Installation

From Source
# Clone repository
git clone https://github.com/bargom/codeai.git
cd codeai

# Install dependencies
go mod download

# Build binary
make build

# Verify installation
./bin/codeai version
./bin/codeai --help
Database Setup
# Create database
createdb codeai

# Run migrations
./bin/codeai server migrate --db-name codeai --db-user postgres

# Or with custom settings
./bin/codeai server migrate \
  --db-host localhost \
  --db-port 5432 \
  --db-name codeai \
  --db-user codeai_user \
  --db-password secret

Development

Running Tests
# All tests with race detector
make test

# Unit tests only
make test-unit

# Integration tests (requires PostgreSQL)
make test-integration

# CLI integration tests
make test-cli

# Coverage report
make test-coverage
# Open coverage.html in browser
Running Benchmarks
# All benchmarks
make bench

# Parser benchmarks
make bench-parse

# Validator benchmarks
make bench-validate
Code Quality
# Run linter
make lint

# Tidy dependencies
make tidy

# Clean build artifacts
make clean
Available Make Targets
Target Description
make build Build the application binary
make test Run all tests with race detector
make test-unit Run unit tests only
make test-integration Run integration tests
make test-coverage Generate coverage report
make bench Run benchmarks
make lint Run linters (go vet)
make clean Clean build artifacts
make tidy Tidy go modules
Contributing

See CONTRIBUTING.md for guidelines on:

  • Code style and conventions
  • Pull request process
  • Testing requirements
  • Documentation standards

Deployment

Docker
# Dockerfile
FROM golang:1.24-alpine AS builder
WORKDIR /app
COPY . .
RUN go build -ldflags "-s -w" -o codeai ./cmd/codeai

FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /app
COPY --from=builder /app/codeai .
EXPOSE 8080
CMD ["./codeai", "server", "start"]
# Build and run
docker build -t codeai:latest .
docker run -p 8080:8080 \
  -e CODEAI_DB_HOST=host.docker.internal \
  -e CODEAI_DB_NAME=codeai \
  codeai:latest
Kubernetes
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: codeai
spec:
  replicas: 3
  selector:
    matchLabels:
      app: codeai
  template:
    metadata:
      labels:
        app: codeai
    spec:
      containers:
      - name: codeai
        image: codeai:latest
        ports:
        - containerPort: 8080
        env:
        - name: CODEAI_DB_HOST
          valueFrom:
            secretKeyRef:
              name: codeai-secrets
              key: db-host
        - name: CODEAI_DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: codeai-secrets
              key: db-password
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /ready
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 5
---
apiVersion: v1
kind: Service
metadata:
  name: codeai
spec:
  selector:
    app: codeai
  ports:
  - port: 80
    targetPort: 8080
  type: ClusterIP

Full Deployment Guide


Documentation

Document Description
Quick Start Get up and running in minutes
DSL Language Spec Complete language reference
DSL Cheatsheet Quick syntax reference
Database Guide PostgreSQL and MongoDB configuration
Architecture System design and module details
API Reference HTTP API documentation
Workflows & Jobs Background processing guide
Integration Patterns External service integration
Observability Logging, metrics, and tracing
Testing Testing strategies and examples
Deployment Production deployment guide
Troubleshooting Common issues and solutions
Migration Guide Version upgrade instructions
Contributing Contribution guidelines
Implementation Status Current feature status

Environment Variables

Variable Default Description
CODEAI_DB_HOST localhost PostgreSQL host
CODEAI_DB_PORT 5432 PostgreSQL port
CODEAI_DB_NAME codeai Database name
CODEAI_DB_USER postgres Database user
CODEAI_DB_PASSWORD (empty) Database password
CODEAI_DB_SSLMODE disable SSL mode
CODEAI_MONGODB_URI (empty) MongoDB connection URI
CODEAI_MONGODB_DATABASE (empty) MongoDB database name
CODEAI_SERVER_HOST localhost Server bind host
CODEAI_SERVER_PORT 8080 Server bind port
CODEAI_REDIS_URL (empty) Redis connection URL
CODEAI_JWT_SECRET (empty) JWT signing secret
CODEAI_JWKS_URL (empty) JWKS endpoint URL

License

This project is licensed under the MIT License - see the LICENSE file for details.

MIT License

Copyright (c) 2026 bargom

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

Acknowledgments

Built with excellent open-source projects:


CodeAI - Declarative Backend Development
GitHub | Quick Start | API Docs

Directories

Path Synopsis
cmd
codeai command
Package main is the entry point for the CodeAI CLI.
Package main is the entry point for the CodeAI CLI.
codeai/cmd
Package cmd provides the CLI commands for CodeAI.
Package cmd provides the CLI commands for CodeAI.
codeai/testing
Package testing provides test utilities for CLI commands.
Package testing provides test utilities for CLI commands.
internal
api
Package api provides HTTP handlers for the CodeAI API.
Package api provides HTTP handlers for the CodeAI API.
api/handlers
Package handlers contains HTTP request handlers for the API.
Package handlers contains HTTP request handlers for the API.
api/handlers/compensation
Package compensation provides HTTP handlers for compensation operations.
Package compensation provides HTTP handlers for compensation operations.
api/handlers/jobs
Package jobs provides HTTP handlers for job-related API endpoints.
Package jobs provides HTTP handlers for job-related API endpoints.
api/handlers/notifications
Package notifications provides HTTP handlers for notification endpoints.
Package notifications provides HTTP handlers for notification endpoints.
api/handlers/webhooks
Package webhooks provides HTTP handlers for webhook management endpoints.
Package webhooks provides HTTP handlers for webhook management endpoints.
api/handlers/workflow
Package workflow provides HTTP handlers for workflow operations.
Package workflow provides HTTP handlers for workflow operations.
api/middleware
Package middleware provides HTTP middleware for the API.
Package middleware provides HTTP middleware for the API.
api/testing
Package testing provides test utilities for the API package.
Package testing provides test utilities for the API package.
api/types
Package types defines API request and response types.
Package types defines API request and response types.
ast
Package ast defines the Abstract Syntax Tree for CodeAI specifications.
Package ast defines the Abstract Syntax Tree for CodeAI specifications.
auth
Package auth provides JWT authentication and authorization for CodeAI.
Package auth provides JWT authentication and authorization for CodeAI.
cache
Package cache provides caching functionality with Redis and in-memory backends.
Package cache provides caching functionality with Redis and in-memory backends.
database
Package database provides database connectivity and operations.
Package database provides database connectivity and operations.
database/models
Package models defines domain models for the database layer.
Package models defines domain models for the database layer.
database/mongodb
Package mongodb provides MongoDB database connectivity and repository operations.
Package mongodb provides MongoDB database connectivity and repository operations.
database/repository
Package repository implements the repository pattern for data access.
Package repository implements the repository pattern for data access.
database/setup
Package setup provides database connection setup with repository initialization.
Package setup provides database connection setup with repository initialization.
database/testing
Package testing provides test helpers for database tests.
Package testing provides test helpers for database tests.
engine
Core execution engine
Core execution engine
event
Package event provides an event dispatcher for the application.
Package event provides an event dispatcher for the application.
event/builder
Package builder provides a fluent API for constructing events.
Package builder provides a fluent API for constructing events.
event/bus
Package bus provides the core event bus functionality for pub/sub messaging.
Package bus provides the core event bus functionality for pub/sub messaging.
event/dispatcher
Package dispatcher provides event dispatching with persistence.
Package dispatcher provides event dispatching with persistence.
event/handlers
Package handlers provides specialized event handlers for complex event processing.
Package handlers provides specialized event handlers for complex event processing.
event/repository
Package repository provides data access for events.
Package repository provides data access for events.
event/subscribers
Package subscribers provides built-in event subscribers.
Package subscribers provides built-in event subscribers.
health
Package health provides health check functionality for the application.
Package health provides health check functionality for the application.
health/checks
Package checks provides built-in health checkers.
Package checks provides built-in health checkers.
llm
LLM API client interface
LLM API client interface
notification/email
Package email provides email notification services using Brevo.
Package email provides email notification services using Brevo.
notification/email/repository
Package repository provides email persistence.
Package repository provides email persistence.
notification/email/subscriber
Package subscriber provides event subscribers for email notifications.
Package subscriber provides event subscribers for email notifications.
notification/email/templates
Package templates provides email template management.
Package templates provides email template management.
openapi
Package openapi provides OpenAPI 3.0 specification generation from CodeAI AST.
Package openapi provides OpenAPI 3.0 specification generation from CodeAI AST.
pagination
Package pagination provides offset and cursor-based pagination support for database queries with filtering integration.
Package pagination provides offset and cursor-based pagination support for database queries with filtering integration.
parser
Package parser provides a Participle-based parser for the CodeAI DSL.
Package parser provides a Participle-based parser for the CodeAI DSL.
query
Package query provides a query language parser and SQL compiler for CodeAI.
Package query provides a query language parser and SQL compiler for CodeAI.
rbac
Package rbac provides role-based access control with permission inheritance.
Package rbac provides role-based access control with permission inheritance.
scheduler
Package scheduler provides configuration and initialization for the job scheduler.
Package scheduler provides configuration and initialization for the job scheduler.
scheduler/handlers
Package handlers provides the task handler registry for the scheduler.
Package handlers provides the task handler registry for the scheduler.
scheduler/monitoring
Package monitoring provides metrics and monitoring for the scheduler.
Package monitoring provides metrics and monitoring for the scheduler.
scheduler/queue
Package queue provides a job queue manager using Asynq.
Package queue provides a job queue manager using Asynq.
scheduler/repository
Package repository provides data access for scheduler jobs.
Package repository provides data access for scheduler jobs.
scheduler/service
Package service provides the main scheduler service for job management.
Package service provides the main scheduler service for job management.
scheduler/tasks
Package tasks defines task types and handlers for the scheduler.
Package tasks defines task types and handlers for the scheduler.
validation
Package validation provides input validation with detailed error messages.
Package validation provides input validation with detailed error messages.
validator
Package validator provides semantic validation for CodeAI AST.
Package validator provides semantic validation for CodeAI AST.
webhook/queue
Package queue provides asynchronous webhook delivery with worker pool.
Package queue provides asynchronous webhook delivery with worker pool.
webhook/repository
Package repository provides data access for webhook configurations and deliveries.
Package repository provides data access for webhook configurations and deliveries.
webhook/retry
Package retry provides automatic retry handling for failed webhook deliveries.
Package retry provides automatic retry handling for failed webhook deliveries.
webhook/security
Package security provides cryptographic utilities for webhook signing and verification.
Package security provides cryptographic utilities for webhook signing and verification.
webhook/service
Package service provides the webhook business logic layer.
Package service provides the webhook business logic layer.
webhook/subscriber
Package subscriber provides event bus integration for webhooks.
Package subscriber provides event bus integration for webhooks.
workflow/activities
Package activities implements Temporal activities for workflow execution.
Package activities implements Temporal activities for workflow execution.
workflow/activities/compensation
Package compensation provides compensation (rollback) activities for workflow steps.
Package compensation provides compensation (rollback) activities for workflow steps.
workflow/compensation
Package compensation provides enhanced saga pattern support for workflow compensation.
Package compensation provides enhanced saga pattern support for workflow compensation.
workflow/compensation/repository
Package repository provides data access for compensation records.
Package repository provides data access for compensation records.
workflow/compensation/testing
Package testing provides test utilities for compensation workflows.
Package testing provides test utilities for compensation workflows.
workflow/definitions
Package definitions contains workflow and activity type definitions.
Package definitions contains workflow and activity type definitions.
workflow/engine
Package engine provides the core workflow engine implementation.
Package engine provides the core workflow engine implementation.
workflow/patterns
Package patterns provides reusable workflow patterns for the workflow engine.
Package patterns provides reusable workflow patterns for the workflow engine.
workflow/repository
Package repository provides data persistence for workflow executions.
Package repository provides data persistence for workflow executions.
pkg
integration
Package integration provides resilience patterns for external service communication.
Package integration provides resilience patterns for external service communication.
integration/brevo
Package brevo provides a client for the Brevo (Sendinblue) transactional email API.
Package brevo provides a client for the Brevo (Sendinblue) transactional email API.
integration/graphql
Package graphql provides a GraphQL client with resilience patterns.
Package graphql provides a GraphQL client with resilience patterns.
integration/redis
Package redis provides a Redis client wrapper for the scheduler.
Package redis provides a Redis client wrapper for the scheduler.
integration/rest
Package rest provides a REST client with resilience patterns.
Package rest provides a REST client with resilience patterns.
integration/temporal
Package temporal provides Temporal client integration utilities.
Package temporal provides Temporal client integration utilities.
integration/webhook
Package webhook provides HTTP webhook client and types for external integrations.
Package webhook provides HTTP webhook client and types for external integrations.
logging
Package logging provides structured logging with request tracing and sensitive data redaction.
Package logging provides structured logging with request tracing and sensitive data redaction.
metrics
Package metrics provides Prometheus metrics collection for the CodeAI application.
Package metrics provides Prometheus metrics collection for the CodeAI application.
types
Shared type definitions
Shared type definitions

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL