Help us shape the future of Go! Take the 2026 Go Developer Survey

diverge

module
v0.17.0 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: Apache-2.0

README

Diverge

Diverge

Branch your infrastructure, not just your code.

CI License Go Version Release

Environment-as-a-service engine for Kubernetes. Diverge creates ephemeral preview environments with async routing, Prometheus observability, GitLab support, SDK propagation, and configurable database provisioning. Extensible via a pluggable provider registry.

Get Started

curl -fsSL https://raw.githubusercontent.com/divergedev/diverge/main/install.sh | sh

Documentation: https://divergedev.com

Try It

In-Repo Fullstack Demo (examples/fullstack-demo/) → — Runnable 3-service Go monorepo (storefront-web, checkout-api, fulfillment-worker) showcasing delta PreviewGroup deploys, header propagation, PostgreSQL schema-per-PR + Atlas migrations, Flipt feature overrides, scale-to-zero hibernation, and AgentTask gVisor sandboxes.

5-minute demo → — Multi-repo preview environments with k3d + Envoy Gateway. Features a complete hands-on bank-demo showcasing database schema isolation and automated migration jobs!

Quick Start

Diverge CLI Quickstart Demo

You can quickly test Diverge locally with the CLI:

diverge dev --service my-app

How It Works: Delta Previews vs. Full-Stack Duplication

Delta Preview vs Traditional Full-Stack Duplication

Turnkey CI/CD (divergedev/diverge@v0.16.0)

Deploy a delta PreviewGroup for only the services modified in a Pull Request and pass routing-header-json directly into Playwright E2E tests:

- name: Deploy Diverge Delta Preview
  id: diverge
  uses: divergedev/diverge@v0.16.0
  with:
    kubeconfig: ${{ secrets.PREVIEW_KUBECONFIG }}
    image-registry: ghcr.io/acme
    base-url: https://staging.example.com
    wait: "true"

- name: Run Playwright E2E Against Preview
  if: steps.diverge.outputs.skipped != 'true'
  run: npx playwright test
  env:
    PREVIEW_URL: ${{ steps.diverge.outputs.preview-url }}
    EXTRA_HTTP_HEADERS: ${{ steps.diverge.outputs.routing-header-json }}

Helm Install

helm install diverge oci://ghcr.io/divergedev/charts/diverge --version <version>

See charts/diverge/values.yaml for configuration options.

Key Features

  • Autonomous Agent Sandboxes (AgentTask): Run AI coding agents inside isolated Kubernetes sandboxes (gvisor / kata / agent-sandbox) with attenuated Macaroon capability tokens, network policy egress lockdowns, automatic linked preview environments (PreviewEnvironmentReady condition, divergedev.com/preview-url annotation), and live LLM cost/token metering via POST /api/v1/agenttask/meter.
  • PreviewGroup Orchestration: Manage multiple child environments and services under a single CR tied directly to an MR/PR. Automatic orphan cleanup and label-based ownership.
  • Provider Registry: Pluggable, extensible architecture — add new routing, deployer, notifier, sandbox, or database providers with a single file. Zero changes to the controller.
  • Scale-to-Zero & FinOps Namespace Quotas: Idle preview environments automatically scale to zero via KEDA HTTP Add-on (HTTPScaledObject) or annotation-based idle hibernation (divergedev.com/hibernate-after, divergedev.com/last-traffic-at). Namespace-level FinOps quotas (divergedev.com/max-active-environments, divergedev.com/max-cnpg-clusters, divergedev.com/max-hourly-cost-usd, divergedev.com/quota-exceed-policy: hibernate-oldest | reject) automatically hibernate the oldest idle environment when concurrency or budget caps are reached.
  • Activator Proxy (activator-proxy): Smart routing that directs traffic to the pod when ready. Includes X-Preview-Env header injection, a shared informer for efficient pod state tracking, and an optional auto-refreshing HTML wake-up splash page (--wake-splash flag / X-Diverge-Wake-Splash: true header and GET /-/wakeup-status readiness endpoint).
  • Delta Deployment & Baseline Drift Detection: Only deploy what changed, falling back to a baseline for unmodified services. Automatically computes a deterministic SHA-256 baseline fingerprint (divergedev.com/baseline-fingerprint) across baseline Deployments, ConfigMaps, and Secrets, surfacing drift warnings (BaselineDriftDetected=True, ⚠️ drift in diverge top) or auto-refreshing preview pods (divergedev.com/drift-policy: sync).
  • Header-Based Routing & Gateway API: Leverages Gateway API (HTTPRoute + GRPCRoute + cross-namespace ReferenceGrant), Istio (ambient-mesh / waypoint), Cilium, Linkerd, and the Diverge Proxy to route traffic seamlessly using HTTP/gRPC headers.
  • Configurable DB Modes & Atlas Migrations: Options for shared, schema, snapshot, or fresh databases via in-cluster schema and CloudNativePG (cnpg) providers, plus native Atlas Operator (AtlasMigration / AtlasSchema) integration.
  • Schema-per-Environment: Actual execution of SQL-based schema provisioning (via SQLExecutor) with public schema write-protection, declarative seedSource seeding (public, schema:<name>, configmap:<name>[/<key>]), regex-validated naming, injection prevention, auto-generated diverge-db-env-<env> Secret (DATABASE_URL and DIVERGE_PREVIEW_SCHEMA), and automated migration Jobs.
  • MR-Triggered Lifecycle: Environments spin up when a Merge Request opens and tear down upon merge/close.
  • Merge Gating: GitLab/GitHub commit status checks (diverge/preview) block merges until environments are healthy.
  • Argo CD & Direct Deploy: Argo CD GitOps (Application CRs) and No-ArgoCD mode (DirectDeployer) for Helm charts and Kustomize overlays.
  • Feature Flags & OpenFeature: Isolated flag evaluation per preview environment. Out-of-the-box support for in-cluster flagd ConfigMaps, remote Flipt ephemeral namespaces, Flagsmith ephemeral identities, and Unleash context-constrained strategies with automated cleanup on MR merge.
  • Environment Export: diverge env export extracts environment variables from preview pods for local development (dotenv, JSON, shell formats).
  • Test Integration: CI trigger and polling support to run automated tests against preview environments.
  • Prometheus Metrics: Reconciliation duration, deployment status, route counts, active environments, preview group gauges, per-environment cost estimation (diverge_environment_estimated_hourly_cost_usd), and idle hibernation tracking (divergedev.com/hibernate-after, divergedev.com/last-traffic-at).
  • Namespace Labels: Custom labels on preview namespaces (e.g., istio.io/dataplane-mode: ambient for zero-trust mTLS).
  • Security Hardened: Macaroon capability tokens, webhook secret constant-time comparison, RFC 7230 header validation, safe SHA handling, ArgoCD namespace bypass prevention, IPv6-safe pod URLs, typed Server-Side Apply (SSA), and strict label validation.
  • Finalizer-Based Lifecycle: Kubernetes finalizers ensure clean teardown of all resources (routing, database, sandboxes, ArgoCD apps) even during force-deletes.
  • TTL Auto-Expiry: Automatic environment cleanup after configurable TTL with requeue-based expiry.
  • Multi-SCM Notifiers & Webhooks: GitLab MR comments and GitHub PR comments with status updates and interactive PR/MR slash commands (/diverge preview, /diverge fix <objective>, /diverge extend-ttl [duration], /diverge teardown, /diverge pause, /diverge resume).
  • E2E Tested: End-to-end tests with Kind/k3d, Envoy Gateway, Istio, Cilium, Linkerd, and real CRD reconciliation.
  • ConnectRPC API Server & Web Dashboard: Opt-in API server (server.enabled: true in Helm) featuring an embedded React Web UI (server.dashboard.enabled: true), ConnectRPC (HTTP/1.1 + HTTP/2), OIDC JWT + K8s TokenReview + Macaroon authentication, namespace-scoped RBAC authorization, structured audit logging, list pagination, optimistic concurrency, and HTTP reverse tunnels.
  • Service Topology & Route Simulation: diverge route <service> traces request paths through your service graph. diverge graph show renders the topology as Mermaid, DOT, or JSON.
  • Changed-Service Detection: diverge diff identifies which services are affected by your code changes using git diff + path-based service mapping. Outputs JSON for CI integration.
  • Prometheus Topology Discovery: Auto-discovers service dependencies from Istio, Linkerd, or Cilium mesh metrics. Background cache with stale-while-revalidate for zero-latency CLI responses.

Async & Cache Routing

Diverge provides fully isolated preview environments for asynchronous queues and shared caches.

  • Subdomain vs Header Routing: Use mode: subdomain for frontend-to-backend workflows without passing custom headers.
  • Available Providers: Supported provisioners include Temporal, Kafka (with bounded topic retention.ms via divergedev.com/kafka-retention-ms or TTL), Redis / Valkey (key-prefix isolation preview:<env>: with non-blocking RESP SCAN + UNLINK teardown on --redis-addr / DIVERGE_REDIS_ADDR), Noop, and Webhook.
  • Slim Builds: Use no_temporal and no_kafka build tags for smaller binaries.

See the Async Routing Guide for full configuration details and YAML examples.

Security

Diverge takes security seriously. The platform features strict CRD OpenAPI validation, context timeouts on all external calls, and prevention mechanisms for shell/markdown injection in templates. The controller uses RBAC-scoped clients to ensure it only has the permissions it needs. Webhook interactions are secured using constant-time comparisons for secrets and RFC 7230-compliant header validation. Recent hardening includes Macaroon capability auth with namespace-scoped secret indexing, ArgoCD namespace bypass prevention, safe SHA handling to eliminate panics, IPv6-safe pod URLs, comprehensive label validation, and Typed Server-Side Apply (SSA) to ensure safe resource updates.

  • Container images are signed with cosign using keyless (OIDC) identity
  • Every release includes an SBOM (SPDX) attached to the container image
  • CRD YAML bundles are published as release artifacts
  • Helm chart is published to oci://ghcr.io/divergedev/charts
  • GitHub Actions are pinned to commit SHAs

Architecture

Diverge End-to-End Architecture Overview

Diverge consists of 5 core binaries and an embedded Web UI compiled and released via goreleaser:

  1. Controller (diverge-controller): The Kubernetes operator that watches PreviewGroup, Environment, and AgentTask Custom Resources (CRs), reconciles them, and provisions routing, databases, sandboxes, and GitOps resources.
  2. API Server & Web UI (diverge-server): ConnectRPC server (server.enabled: true) serving the embedded React Web Dashboard, OIDC/TokenReview/Macaroon authentication, real-time environment/log streaming, and local-to-cluster HTTP tunnels.
  3. Proxy (diverge-proxy): A reverse proxy that facilitates header-based L7 routing to preview environments.
  4. Activator (activator-proxy): A proxy for scale-to-zero workloads. Wakes up sleeping pods on the first request and seamlessly routes traffic once they are ready.
  5. CLI & MCP Server (diverge): Terminal CLI and stdio Model Context Protocol (diverge mcp) server for AI agents and IDEs.

PreviewGroup Example

A minimal PreviewGroup Custom Resource managing multiple services for a single MR:

apiVersion: divergedev.com/v1alpha1
kind: PreviewGroup
metadata:
  name: mr-42
spec:
  source:
    provider: gitlab
    project: myorg/platform
    branch: feat/payments
  routing:
    headerKey: x-preview-env
    headerValue: "42"
  services:
    - name: payments-api
      image: registry.example.com/payments:mr-42
      mode: image
      port: 8080
    - name: gateway
      mode: baseline

CLI Commands

The diverge CLI helps you manage environments efficiently:

  • diverge init - Initialize a .diverge.yaml config or local Kubernetes playground
  • diverge create - Create a new environment
  • diverge curl - Send HTTP requests to a preview environment and compare against baseline (--compare-baseline)
  • diverge list - List active environments
  • diverge status - Check the status of an environment
  • diverge top - Live terminal dashboard (watch) of environments, FinOps burn rate, hibernation state, and AgentTasks
  • diverge open - Open the preview URL in your browser (--magic for one-click ?_diverge_env= cookie URL)
  • diverge logs - Stream logs for a preview environment
  • diverge dev - Local development mode with preview routing
  • diverge doctor - Diagnose cluster, CRD, Gateway, and environment health
  • diverge env export - Export environment variables (dotenv, JSON, shell)
  • diverge mcp - Run MCP server over stdio (diverge mcp setup to auto-configure Cursor, Claude Code, and Windsurf)
  • diverge preview - Create preview environments from CLI
  • diverge validate - Validate your .diverge.yaml
  • diverge delete - Delete an environment
  • diverge version - Show CLI version

Installation

Install via shell script:

curl -fsSL https://divergedev.com/install.sh | sh

Or download and verify first:

curl -fsSL -o install.sh https://divergedev.com/install.sh
sha256sum install.sh  # verify contents
sh install.sh

Or install via Go:

go install github.com/divergedev/diverge/cmd/diverge@latest

Install via Helm (Kubernetes Operator)

helm repo add diverge https://divergedev.github.io/diverge
helm repo update
helm install diverge diverge/diverge --namespace diverge-system --create-namespace

Docker Images (for reference)

The controller, server, and proxy images are available at:

docker pull ghcr.io/divergedev/diverge:latest

Or download the binary from Releases.

Development

Diverge supports both 1-click GitHub Codespaces / VS Code Dev Containers (.devcontainer/devcontainer.json) and Nix (flake.nix).

# Enter the Nix development shell
nix develop

# Apply CRDs and run locally
nix develop -c make install
nix develop -c make run

See CONTRIBUTING.md for the full developer guide, testing conventions, and Property-Based Testing (PBT) workflow using the Hegel framework (hegel.dev/go/hegel).

Contributing

See CONTRIBUTING.md and GitHub Issues for planned features and open work.

License

Apache 2.0

Directories

Path Synopsis
api
gen/diverge/v1alpha1
Code generated by protoc-gen-proto2mcp.
Code generated by protoc-gen-proto2mcp.
v1alpha1
Package v1alpha1 contains API Schema definitions for the diverge v1alpha1 API group +kubebuilder:object:generate=true +groupName=divergedev.com
Package v1alpha1 contains API Schema definitions for the diverge v1alpha1 API group +kubebuilder:object:generate=true +groupName=divergedev.com
cmd
activator-proxy command
agent-runner command
controller command
diverge command
proxy command
server command
config
examples
gen
internal
argocd
Package argocd manages Argo CD Application custom resources for environment deployments using server-side apply.
Package argocd manages Argo CD Application custom resources for environment deployments using server-side apply.
async
Package async provides interfaces for async infrastructure provisioning.
Package async provides interfaces for async infrastructure provisioning.
cli
Package cli implements the diverge command-line interface, providing commands for creating, listing, deleting, and managing preview environments.
Package cli implements the diverge command-line interface, providing commands for creating, listing, deleting, and managing preview environments.
deployer
Package deployer provides pluggable service deployment backends.
Package deployer provides pluggable service deployment backends.
git
metrics
Package metrics defines and registers Prometheus metrics for all Diverge subsystems.
Package metrics defines and registers Prometheus metrics for all Diverge subsystems.
notifier
Package notifier provides integrations for posting deployment status notifications to code review platforms such as GitHub and GitLab.
Package notifier provides integrations for posting deployment status notifications to code review platforms such as GitHub and GitLab.
observability
Package observability wires OpenTelemetry for this service.
Package observability wires OpenTelemetry for this service.
proxy
Package proxy implements the Diverge reverse proxy for subdomain-based routing of requests to preview environments.
Package proxy implements the Diverge reverse proxy for subdomain-based routing of requests to preview environments.
routing
Package routing manages Kubernetes networking resources for environment traffic routing, with implementations for Gateway API and Istio.
Package routing manages Kubernetes networking resources for environment traffic routing, with implementations for Gateway API and Istio.
server/dashboard
Package dashboard provides embedded static assets for the Diverge web dashboard.
Package dashboard provides embedded static assets for the Diverge web dashboard.
testing
Package testing provides test integration for preview environments.
Package testing provides test integration for preview environments.
pkg
database
Package database defines the public API for Diverge database providers.
Package database defines the public API for Diverge database providers.
features
Package features defines the public API for Diverge feature flag providers.
Package features defines the public API for Diverge feature flag providers.
sdk

Jump to

Keyboard shortcuts

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