Skip to content

Trace-native CI/CD for AI agents — production failures become regression tests that block the PR. Auto-detect, cluster, freeze into hermetic cases, replay in CI for $0.

17.6 KB
Raw Blame
# Full Tracely stack. One command:
#   docker compose up -d --build --wait        (host 8000 free)
#   TRACELY_BACKEND_PORT=8088 docker compose up -d --build --wait   (host 8000 busy)
# Then open http://localhost:3001 (or ${TRACELY_WEB_PORT}).

x-app-env: &app-env
  TRACELY_ENV: docker
  DATABASE_URL: postgresql+asyncpg://tracely:tracely@postgres:5432/tracely
  ALEMBIC_DATABASE_URL: postgresql+psycopg://tracely:tracely@postgres:5432/tracely
  # Span store: clickhouse (legacy) | postgres. API and worker must agree.
  SPAN_STORE: ${SPAN_STORE:-clickhouse}
  SPAN_RETENTION_DAYS: ${SPAN_RETENTION_DAYS:-90}
  CLICKHOUSE_HOST: clickhouse
  CLICKHOUSE_PORT: "8123"
  CLICKHOUSE_USER: default
  CLICKHOUSE_PASSWORD: ""
  CLICKHOUSE_DATABASE: tracely
  # ClickHouse's own telemetry (query_log, trace_log, …) ships with NO TTL and is never read by
  # Tracely — left alone it outgrows every customer trace on a small box. A nightly beat sweep
  # caps it; 0 turns the sweep off (keep your query_log when debugging).
  CH_SYSTEM_LOG_TTL_DAYS: ${CH_SYSTEM_LOG_TTL_DAYS:-3}
  REDIS_URL: redis://redis:6379/0
  # Celery worker pool — solo/1 for local (numba/UMAP/HDBSCAN are fork-fragile). Prod sets these
  # to prefork / >=2 in the deploy env. Also forwarded to the worker command above.
  CELERY_POOL: ${CELERY_POOL:-solo}
  CELERY_CONCURRENCY: ${CELERY_CONCURRENCY:-1}
  # The queue the API produces onto and the worker drains — the ops self-check measures its depth.
  CELERY_QUEUE: ${CELERY_QUEUE:-ingestion}
  # Where the beat self-check sends "this deployment is degraded" (Slack incoming webhook or any
  # webhook URL). Blank = log only: it still runs and still logs a `selfcheck` heartbeat.
  OPS_ALERT_WEBHOOK: ${OPS_ALERT_WEBHOOK:-}
  S3_ENDPOINT_URL: http://minio:9000
  S3_REGION: us-east-1
  S3_ACCESS_KEY_ID: tracely
  S3_SECRET_ACCESS_KEY: tracely-secret
  S3_BUCKET: tracely-events
  S3_EVENT_PREFIX: events/
  # LLM access: every chat call (judge, metric generation, failure-intel agents) goes through
  # LangChain `create_agent` on OpenRouter, and embeddings go through its OpenAI-compatible
  # /embeddings endpoint — OPENROUTER_API_KEY alone is enough. OPENAI_API_KEY / LLM_JUDGE_API_KEY
  # are the legacy direct-endpoint fallbacks used when no OpenRouter key is set.
  OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-}
  # Decision models (TypeSafe Jev) are served on OpenRouter's Decisions API, not chat completions.
  # New evaluation columns start on this decision model; text work defaults to LLM_JUDGE_MODEL.
  COLUMN_DEFAULT_MODEL: ${COLUMN_DEFAULT_MODEL:-typesafe/jev-1.13}
  LLM_JUDGE_MODEL: ${LLM_JUDGE_MODEL:-openai/gpt-6-luna}
  OPENROUTER_DECISIONS_URL: ${OPENROUTER_DECISIONS_URL:-https://openrouter.ai/api/alpha/decisions}
  OPENAI_API_KEY: ${OPENAI_API_KEY:-}
  LLM_JUDGE_API_KEY: ${OPENAI_API_KEY:-}
  # Encrypts a workspace's own OpenRouter key (Settings -> LLM key) at rest. Any string
  # >=32 chars; generate with `openssl rand -base64 32`. Blank = that feature can't be used.
  SECRETS_ENCRYPTION_KEY: ${SECRETS_ENCRYPTION_KEY:-}
  # Output-token cap per judge/agent call. OpenRouter reserves credit for the FULL max_tokens up
  # front, so leaving this unset makes calls fail with "requires more credits" long before the
  # balance is spent. Raise only if a reasoning-heavy judge model gets truncated.
  LLM_MAX_OUTPUT_TOKENS: ${LLM_MAX_OUTPUT_TOKENS:-4096}
  # The dashboard's chat widget. Runs on OUR OpenRouter key (it explains the product, so it has
  # to answer in a workspace that brought no key of its own) — the one LLM call customers don't
  # pay for. ASSISTANT_REASONING_EFFORT: ""|minimal|low|medium|high.
  ASSISTANT_MODEL: ${ASSISTANT_MODEL:-anthropic/claude-sonnet-5.5}
  ASSISTANT_REASONING_EFFORT: ${ASSISTANT_REASONING_EFFORT:-medium}
  # A cheap model picks which of the assistant's ~30 tools a question needs, so the expensive
  # one never carries all of them. ASSISTANT_MAX_TOOLS=0 turns selection off.
  ASSISTANT_TOOL_SELECTOR_MODEL: ${ASSISTANT_TOOL_SELECTOR_MODEL:-openai/gpt-oss-120b}
  ASSISTANT_MAX_TOOLS: ${ASSISTANT_MAX_TOOLS:-8}
  ASSISTANT_MAX_MODEL_CALLS: ${ASSISTANT_MAX_MODEL_CALLS:-12}
  # USD one conversation may spend of OUR credit, cumulative across its turns.
  ASSISTANT_BUDGET_USD: ${ASSISTANT_BUDGET_USD:-1.0}
  # Audits: seconds one worker tick may spend on a rollout before yielding to ingestion, and how
  # many rollouts of one run may be in flight (needs CELERY_CONCURRENCY > 1 to matter).
  AUDIT_SLICE_S: ${AUDIT_SLICE_S:-45}
  AUDIT_MAX_PARALLEL: ${AUDIT_MAX_PARALLEL:-2}
  AUDIT_IMAGE_MODEL: ${AUDIT_IMAGE_MODEL:-google/gemini-2.5-flash-image}
  AUDIT_TTS_MODEL: ${AUDIT_TTS_MODEL:-hexgrad/kokoro-82m}
  AUDIT_TTS_VOICE: ${AUDIT_TTS_VOICE:-af_heart}
  # Real environments for audits. Blank = audits can only invent tool results. `docker` runs each
  # rollout in a sibling container and needs the Docker socket in the worker — start the stack
  # with `-f docker-compose.yml -f docker-compose.sandbox.yml`, which sets this and mounts it.
  SANDBOX_BACKEND: ${SANDBOX_BACKEND:-}
  SANDBOX_IMAGE: ${SANDBOX_IMAGE:-tracely-sandbox:latest}
  SANDBOX_EGRESS_NETWORK: ${SANDBOX_EGRESS_NETWORK:-}
  # Assistant speech mode: realtime voice, browser-direct via ephemeral tokens the backend
  # mints. OpenAI rides OPENAI_API_KEY above; Grok needs its own. Blank = provider hidden.
  XAI_API_KEY: ${XAI_API_KEY:-}
  VOICE_OPENAI_MODEL: ${VOICE_OPENAI_MODEL:-gpt-realtime}
  VOICE_XAI_MODEL: ${VOICE_XAI_MODEL:-grok-voice-latest}
  # AI Observability: attaches a PostHog CallbackHandler to every judge/assistant/simulation LLM
  # call (infrastructure/llm/provider.py). Blank = no capture, like every other optional key here.
  POSTHOG_API_KEY: ${POSTHOG_API_KEY:-}
  POSTHOG_HOST: ${POSTHOG_HOST:-https://us.i.posthog.com}
  # Meta-analysis ("Analyze") synthesis model + rolling-summary compression model. The heavy
  # lifting (correlations/outliers; verbatim short steps) is deterministic; these only set the
  # model for the prose/compression LLM calls (both via the OpenRouter provider).
  META_ANALYSIS_MODEL: ${META_ANALYSIS_MODEL:-openai/gpt-6-sol}
  ROLLING_SUMMARY_MODEL: ${ROLLING_SUMMARY_MODEL:-openai/gpt-6-luna}
  ROLLING_SUMMARY_STEP_MAX_TOKENS: ${ROLLING_SUMMARY_STEP_MAX_TOKENS:-512}
  ROLLING_SUMMARY_MAX_TOKENS: ${ROLLING_SUMMARY_MAX_TOKENS:-16000}
  # Record what Tracely itself did — the judge's prompt and reply, the attacker's move, the call
  # to the customer's endpoint — as a trace, behind the "Show eval" toggle. Costs one small extra
  # trace per evaluation; set false on a high-volume project that doesn't need the audit trail.
  INTROSPECTION_ENABLED: ${INTROSPECTION_ENABLED:-true}
  EVAL_CHAT_ENABLED: ${EVAL_CHAT_ENABLED:-true}
  EVAL_CHAT_POOL_SIZE: ${EVAL_CHAT_POOL_SIZE:-8}
  # Where the worker reaches this API (the Data page's "Seed demo data" runs the seeder there).
  INTERNAL_API_URL: ${INTERNAL_API_URL:-http://backend:8000}
  # Failure clustering. CLUSTER_MERGE_SIMILARITY: token overlap at which a new failure joins an
  # existing cluster instead of starting one (higher = tighter/more clusters, >1 = exact-signature
  # only). CLUSTER_MIN_SIZE: default floor for the clusters list (>=2).
  CLUSTER_MERGE_SIMILARITY: ${CLUSTER_MERGE_SIMILARITY:-0.5}
  CLUSTER_MIN_SIZE: ${CLUSTER_MIN_SIZE:-5}
  # Auth (default "dev" = no human login, ingest key only — the stack runs open out of the box).
  # Self-host: set AUTH_MODE=local and SESSION_SECRET ($(openssl rand -hex 32)) in .env, then docker compose up
  AUTH_MODE: ${AUTH_MODE:-dev}
  SESSION_SECRET: ${SESSION_SECRET:-}
  SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-604800}
  CLERK_ISSUER: ${CLERK_ISSUER:-}
  CLERK_JWKS_URL: ${CLERK_JWKS_URL:-}
  CLERK_AUDIENCE: ${CLERK_AUDIENCE:-}
  CLERK_SECRET_KEY: ${CLERK_SECRET_KEY:-}
  FRONTEND_ORIGIN: ${FRONTEND_ORIGIN:-}
  # Transactional email (Resend) — optional; invites are emailed when RESEND_API_KEY is set.
  RESEND_API_KEY: ${RESEND_API_KEY:-}
  EMAIL_FROM: "${EMAIL_FROM:-Tracely <[email protected]>}"
  APP_BASE_URL: ${APP_BASE_URL:-http://localhost:3001}
  # Error tracking (Sentry) — optional; the API and the worker each init on their own when set.
  SENTRY_DSN: ${SENTRY_DSN:-}
  SENTRY_ENVIRONMENT: ${SENTRY_ENVIRONMENT:-}
  # Hosted-cloud billing — all off by default; self-hosters never need these. BILLING_ENABLED
  # turns on the monthly trace quota (counted in the WORKER, enforced in the API — the shared
  # anchor is what makes sure both see the flag). REQUIRE_PROJECT_LLM_KEY makes server-wide LLM
  # keys inapplicable everywhere, so every AI feature runs only on a workspace's own key.
  BILLING_ENABLED: ${BILLING_ENABLED:-false}
  FREE_TRACE_LIMIT: ${FREE_TRACE_LIMIT:-20000}
  PRO_TRACE_LIMIT: ${PRO_TRACE_LIMIT:-1000000}
  # Days of traces each plan keeps. The ClickHouse TTL (90d) is the floor for everyone;
  # the nightly `tracely.enforce_retention` sweep shortens it — only when billing is on.
  FREE_RETENTION_DAYS: ${FREE_RETENTION_DAYS:-7}
  PRO_RETENTION_DAYS: ${PRO_RETENTION_DAYS:-90}
  # Per-organization caps on workspaces and seats (company accounts; personal ones are always
  # 1/1). Only enforced when BILLING_ENABLED.
  FREE_WORKSPACE_LIMIT: ${FREE_WORKSPACE_LIMIT:-3}
  PRO_WORKSPACE_LIMIT: ${PRO_WORKSPACE_LIMIT:-10}
  FREE_SEAT_LIMIT: ${FREE_SEAT_LIMIT:-3}
  PRO_SEAT_LIMIT: ${PRO_SEAT_LIMIT:-10}
  # How many company orgs one user may belong to. One: an org is a quota pool, and a bigger
  # account means a bigger org (more workspaces/seats), never a second one.
  MAX_ORGANIZATIONS_PER_USER: ${MAX_ORGANIZATIONS_PER_USER:-1}
  # Multi-tenant signup: off means the first registrant claims the deployment and everyone else
  # arrives by invite (the safe self-host default).
  ALLOW_PUBLIC_SIGNUP: ${ALLOW_PUBLIC_SIGNUP:-false}
  # Agent endpoints / monitor webhooks on private addresses. Unset = allowed outside prod.
  ALLOW_PRIVATE_URLS: ${ALLOW_PRIVATE_URLS:-}
  # Scenario gates warn when an evaluator's mean falls this much vs the last green gate.
  GATE_SCORE_DROP_WARN: ${GATE_SCORE_DROP_WARN:-0.1}
  REQUIRE_PROJECT_LLM_KEY: ${REQUIRE_PROJECT_LLM_KEY:-false}
  STRIPE_SECRET_KEY: ${STRIPE_SECRET_KEY:-}
  STRIPE_WEBHOOK_SECRET: ${STRIPE_WEBHOOK_SECRET:-}
  STRIPE_PRICE_PRO: ${STRIPE_PRICE_PRO:-}

services:
  # ── infra ────────────────────────────────────────────────────────────────
  clickhouse:
    image: clickhouse/clickhouse-server:24.8
    ports:
      - "8123:8123"
      - "9009:9000"
    environment:
      CLICKHOUSE_DB: tracely
      CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT: "1"
    ulimits:
      nofile: { soft: 262144, hard: 262144 }
    volumes:
      - ./.data/clickhouse:/var/lib/clickhouse
    healthcheck:
      test: ["CMD", "clickhouse-client", "--query", "SELECT 1"]
      interval: 5s
      timeout: 3s
      retries: 30

  postgres:
    image: pgvector/pgvector:pg17   # postgres 17 + the `vector` extension
    ports:
      - "5432:5432"
    environment:
      POSTGRES_USER: tracely
      POSTGRES_PASSWORD: tracely
      POSTGRES_DB: tracely
    volumes:
      - ./.data/postgres:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U tracely"]
      interval: 5s
      timeout: 3s
      retries: 30

  redis:
    image: redis:7
    command: ["redis-server", "--maxmemory-policy", "noeviction"]
    ports:
      - "6380:6379"
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 30

  # MinIO stopped publishing images (minio/minio and minio/mc are gone from Docker Hub);
  # pgsty/* is the community-maintained drop-in build.
  minio:
    image: pgsty/minio
    command: server /data --console-address ":9001"
    ports:
      - "9000:9000"
      - "9001:9001"
    environment:
      MINIO_ROOT_USER: tracely
      MINIO_ROOT_PASSWORD: tracely-secret
    volumes:
      - ./.data/minio:/data

  minio-init:
    image: pgsty/mc
    depends_on:
      minio:
        condition: service_started
    entrypoint: >
      /bin/sh -c "
      until mc alias set local http://minio:9000 tracely tracely-secret; do echo waiting for minio; sleep 1; done &&
      mc mb -p local/tracely-events &&
      echo 'bucket ready';
      "

  # ── app ──────────────────────────────────────────────────────────────────
  # one-shot: ClickHouse + Alembic migrations, then seed the default project/key
  migrate:
    image: tracely-backend
    build:
      context: .
      dockerfile: Dockerfile.backend
    environment: *app-env
    depends_on:
      clickhouse:
        condition: service_healthy
      postgres:
        condition: service_healthy
    command: ["sh", "-c", "python -m tracely.infrastructure.clickhouse.migrations && (cd backend && alembic upgrade head) && python -m tracely.infrastructure.llm.checkpointer && python -m tracely.services.seeding_service"]
    volumes:                       # live source so new migrations apply without an image rebuild
      - ./backend:/app/backend
      - ./workers:/app/workers
      - ./sdk:/app/sdk
      - ./scripts:/app/scripts
    restart: "no"

  backend:
    image: tracely-backend
    environment: *app-env
    depends_on:
      migrate:
        condition: service_completed_successfully
      redis:
        condition: service_healthy
      minio-init:
        condition: service_completed_successfully
    command: ["uvicorn", "tracely.api.main:app", "--host", "0.0.0.0", "--port", "8000"]
    volumes:                       # editable install -> live source for fast iteration
      - ./backend:/app/backend
      - ./workers:/app/workers
      - ./sdk:/app/sdk
      - ./scripts:/app/scripts
    ports:
      - "${TRACELY_BACKEND_PORT:-8000}:8000"
    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://localhost:8000/health').status==200 else 1)"]
      interval: 5s
      timeout: 3s
      retries: 30
      start_period: 20s

  worker:
    image: tracely-backend
    environment: *app-env
    depends_on:
      migrate:
        condition: service_completed_successfully
      redis:
        condition: service_healthy
      clickhouse:
        condition: service_healthy
      minio-init:
        condition: service_completed_successfully
    # Pool + concurrency come from CELERY_POOL / CELERY_CONCURRENCY (defaults: solo / 1 for local dev,
    # since numba/UMAP/HDBSCAN in failure-intelligence are fork-fragile). Prod uses prefork with
    # concurrency >= 2 — set both in the prod env and recreate the worker.
    # `-B` embeds the beat scheduler in this worker — monitors and the ops self-check are
    # beat-driven and simply never fired without it. Fine for a single local worker; in prod run
    # exactly ONE beat process (see DEPLOY.md) or every worker re-fires the schedule.
    command: ["sh", "-c", "celery -A tracely_workers.worker worker --pool=${CELERY_POOL:-solo} --concurrency=${CELERY_CONCURRENCY:-1} --beat --loglevel=info"]
    volumes:                       # editable install -> live source for fast iteration
      - ./backend:/app/backend
      - ./workers:/app/workers
      - ./sdk:/app/sdk
      - ./scripts:/app/scripts

  # one-shot (profile "demo"): populate the WHOLE product — conversations + failure clusters + the
  # regression/gate half — so the running instance never shows the empty Test/Ship side (the
  # "looks like a Langfuse clone" state). Idempotent; safe to leave enabled across restarts.
  #   docker compose --profile demo up -d --build --wait
  demo:
    image: tracely-backend
    profiles: ["demo"]
    environment:
      <<: *app-env
      TRACELY_API: http://backend:8000
      TRACELY_KEY: tracely_dev_key
    depends_on:
      backend:
        condition: service_healthy
      worker:
        condition: service_started
    command: ["python", "scripts/seed_demo.py"]
    volumes:                       # live source so script edits apply without an image rebuild
      - ./backend:/app/backend
      - ./workers:/app/workers
      - ./sdk:/app/sdk
      - ./scripts:/app/scripts
    restart: "no"

  frontend:
    image: tracely-frontend
    build:
      context: ./frontend
      dockerfile: Dockerfile
    command: ["pnpm", "exec", "next", "dev", "-H", "0.0.0.0"]
    volumes:
      - ./frontend/app:/app/app           # live source -> next dev hot-reload (node_modules/.next stay baked)
      - ./frontend/middleware.ts:/app/middleware.ts   # the auth guard lives outside app/ — without this, edits to it silently never reach the container
      - ./frontend/tailwind.config.ts:/app/tailwind.config.ts   # theme tokens also live outside app/ — a new token used by app/ code fails the build without this
    environment:
      TRACELY_API: http://backend:8000     # server-side fetch uses the compose network
      TRACELY_KEY: tracely_dev_key         # dev-mode fallback only (AUTH_MODE=dev)
      NEXT_PUBLIC_AUTH_MODE: ${AUTH_MODE:-dev}   # dev | local | clerk (must match backend AUTH_MODE)
      NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: ${NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY:-}
      CLERK_SECRET_KEY: ${CLERK_SECRET_KEY:-}
      NEXT_PUBLIC_CLERK_SIGN_IN_URL: /sign-in
      NEXT_PUBLIC_CLERK_SIGN_UP_URL: /sign-up
      NEXT_PUBLIC_POSTHOG_KEY: ${NEXT_PUBLIC_POSTHOG_KEY:-}   # empty = analytics fully off
      WATCHPACK_POLLING: "true"            # reliable HMR over the macOS bind mount
    depends_on:
      backend:
        condition: service_healthy
    ports:
      - "${TRACELY_WEB_PORT:-3001}:3000"
    healthcheck:
      test: ["CMD", "node", "-e", "require('http').get('http://localhost:3000',r=>process.exit(r.statusCode<500?0:1)).on('error',()=>process.exit(1))"]
      interval: 5s
      timeout: 3s
      retries: 40
      start_period: 40s