Configuration Reference

Configuration Reference

This document covers all configuration options for Huitzo platform, SDK, and CLI.

Environment Variables

Platform (Backend)

Every platform setting is read with the HUITZO_ prefix. The settings model declares env_prefix = "HUITZO_", so an unprefixed DATABASE_URL / SECRET_KEY in your environment is silently ignored and the process boots as if the value were never set. The only deliberate exceptions are the Celery broker variables — see Task Queue (Celery).

Variable Required Default Description
HUITZO_DATABASE_URL ✅ - PostgreSQL connection string (async driver, e.g. postgresql+asyncpg://…). Its role must be NOSUPERUSER NOBYPASSRLS, or the backend and the worker refuse to start (boot guard)
HUITZO_DATABASE_ADMIN_URL ✅ with huitzo_app HUITZO_DATABASE_URL Owner/superuser URL used by migrations. Required whenever the runtime role is huitzo_app, or migrations run as that unprivileged role. Set it on the migration process only, never on the backend, worker or beat (placement)
HUITZO_ALLOW_PRIVILEGED_DB_ROLE ❌ false Local development only: boot even though the HUITZO_DATABASE_URL role is SUPERUSER or BYPASSRLS. Honoured only with HUITZO_DEBUG=true outside HUITZO_DEPLOYMENT_MODE=cloud, and logs a warning on every boot (boot guard)
HUITZO_REDIS_URL ❌ redis://localhost:6379/0 Redis connection string for the shared-core cache
HUITZO_JWT_SECRET_KEY ✅ - JWT signing key (min 32 chars outside debug mode)
HUITZO_AUDIT_PEPPER ✅ (non-debug) - HMAC pepper for admin audit-log redaction (min 32 chars)
HUITZO_SECRETS_ENCRYPTION_KEY ✅ (non-debug) - AES-256-GCM key for user secrets, encrypted columns and the LLM provider API keys stored in the registry (64-char hex). Rotate it with rekey-secrets
HUITZO_SECRETS_ENCRYPTION_KEY_PREVIOUS ❌ - A second, decrypt-only key during a rotation (64-char hex, must differ from the current key): first the incoming key, then the key being retired. Values sealed under it can be read; nothing is written with it. Remove it once rekey-secrets has run
HUITZO_SECRETS_LOOKUP_HASH_KEY ✅ when ..._PREVIOUS is set HUITZO_SECRETS_ENCRYPTION_KEY HMAC key for lookup hashes (64-char hex). Set it to the original encryption key before the first rotation and never change or remove it: stored lookup hashes cannot be recomputed
HUITZO_DEBUG ❌ false Enable debug mode (relaxes the secret validators above to warnings)
HUITZO_LOG_LEVEL ❌ INFO Logging level (DEBUG/INFO/WARNING/ERROR/CRITICAL)

The four required secrets are validated at boot. See apps/backend/src/backend/config.py for the authoritative field list and validators.

Deployment Mode

All deployment modes use the same Docker image. The HUITZO_DEPLOYMENT_MODE parameter activates deployment-specific code modules:

Variable Required Default Description
HUITZO_DEPLOYMENT_MODE ❌ self_hosted Deployment mode: cloud, self_hosted, edge. Cloud production must set this explicitly — Settings.deployment_mode defaults to self_hosted in code (apps/backend/src/backend/config.py) and in every shipped Docker/Compose/Helm artifact in this repo; nothing here defaults a deployment to cloud.
HUITZO_DEFAULT_TENANT_ID ❌ Auto-generated Fixed tenant ID for self-hosted/edge mode

Mode-specific behavior:

Mode Active Modules Description
cloud core + cloud Multi-tenant SaaS with billing
self_hosted core + self_hosted Single-tenant with license validation
edge core + edge Offline-capable (Year 3+)

The codebase is organized into modular directories (core/, cloud/, self_hosted/, edge/) with strict import boundaries. This enables future deployment-specific builds when enterprise requirements demand it.

See Deployment Modes for deployment mode details and Build System for the build architecture.

Storage Backend

PostgreSQL is the single database for all deployments. Simple by design, scalable by architecture.

PostgreSQL and Redis can be: - Containers (as in docker-compose examples) - Cloud-managed services (AWS RDS, Azure Database, ElastiCache, etc.) - On-premises dedicated servers

Variable Required Default Description
HUITZO_DATABASE_URL ✅ - PostgreSQL connection string
HUITZO_REDIS_URL ❌ redis://localhost:6379/0 Redis connection string

Connection string formats:

# PostgreSQL
HUITZO_DATABASE_URL=postgresql+asyncpg://user:password@host:5432/database

# Redis
HUITZO_REDIS_URL=redis://host:6379/0
HUITZO_REDIS_URL=redis://:password@host:6379/0
HUITZO_REDIS_URL=rediss://:password@host:6379/0  # TLS

See Self-Hosting Guide for cloud provider examples and Storage Backends for backend protocol details.

File Storage

File uploads and pack output files use a pluggable storage backend. The ctx.files API works identically regardless of backend.

Variable Required Default Description
HUITZO_FILE_STORAGE_BACKEND No local Backend: local, s3, azure, gcs
HUITZO_FILE_STORAGE_PATH No /app/uploads Path for local backend
HUITZO_FILE_MAX_SIZE_MB No 100 Maximum file size

Backend options:

Backend Best For Configuration
local Single-instance, dev/test Volume mount to /app/uploads
s3 Production, multi-instance AWS S3, MinIO, DigitalOcean Spaces
azure Azure deployments Azure Blob Storage
gcs GCP deployments Google Cloud Storage

S3-Compatible (AWS S3, MinIO, DigitalOcean Spaces):

Variable Required Default Description
HUITZO_S3_BUCKET Yes - Bucket name
HUITZO_S3_REGION Yes* us-east-1 AWS region
HUITZO_S3_ENDPOINT No AWS default Custom endpoint (MinIO, Spaces)
HUITZO_S3_ACCESS_KEY_ID Yes - Access key
HUITZO_S3_SECRET_ACCESS_KEY Yes - Secret key
HUITZO_S3_USE_SSL No true Use HTTPS
HUITZO_S3_PATH_STYLE No false Path-style URLs for the AWS default endpoint; a custom HUITZO_S3_ENDPOINT always uses them

Azure Blob Storage:

Variable Required Default Description
HUITZO_AZURE_STORAGE_ACCOUNT Yes - Storage account name
HUITZO_AZURE_STORAGE_KEY Yes* - Storage account key
HUITZO_AZURE_CONTAINER Yes - Container name
HUITZO_AZURE_USE_MANAGED_IDENTITY No false Use managed identity

Google Cloud Storage:

Variable Required Default Description
HUITZO_GCS_BUCKET Yes - Bucket name
HUITZO_GCS_PROJECT Yes - GCP project ID
HUITZO_GCS_CREDENTIALS_FILE No* - Service account JSON path

See File Storage Backends for detailed configuration examples and migration guide.

HTTP Security

Variable Required Default Description
HUITZO_HTTP_DEFAULT_TIMEOUT No 30 Default timeout for HTTP requests (seconds)
HUITZO_HTTP_MAX_RETRIES No 3 Attempts per ctx.http request, the first included; a 502, 503 or 504, a timeout or a connection error is retried
HUITZO_HTTP_MAX_REDIRECTS No 5 Maximum redirects one ctx.http request follows

ctx.http verifies certificates and allows only the pack's own allowed_domains (plus an HTTP Integration's base_url host). There is no setting to disable verification or to add a platform-wide domain allowlist.

Integrations SSRF Guard / Local AI Runtime

See Security Boundaries for the full model.

Variable Required Default Description
HUITZO_ALLOW_INTERNAL_HOSTS ❌ false Self-hosted/edge only: permits tenant-authored Integration probes/connections to reach loopback, link-local, and RFC1918 addresses. Has no effect when HUITZO_DEPLOYMENT_MODE=cloud (#1262).
HUITZO_LOCAL_AI_TRUSTED_BIND_HOSTS ❌ - Comma-separated IPs/CIDRs the Local AI Runtime's own HUITZO_LOCAL_AI_BIND_ADDRESS may target besides localhost, e.g. a WireGuard-reachable GPU host. Independent of the flag above — set it before deploying to a box whose bind address is already non-localhost, or process startup fails.

Authentication

Variable Required Default Description
JWT_ALGORITHM ❌ HS256 JWT algorithm
JWT_ACCESS_TOKEN_EXPIRE_MINUTES ❌ 30 Access token TTL
JWT_REFRESH_TOKEN_EXPIRE_DAYS ❌ 7 Refresh token TTL

Access tokens are bound to the session that issued them: each request checks that the token's sid session is live and that the user and tenants are active (session-bound access tokens). The check's per-process cache (15 s, 10,000 entries) is fixed, not configurable: it is the bound on how long a revoked session's tokens keep working. Step-up routes compare sessions.reauth_at, not the token's iat, with a fixed 900 s window (step-up).

Services

LLM providers, models, platform API keys, the default model and profile mappings are not environment variables: they live in the LLM registry and are managed at /admin/llm (ADR-038 §3.2, cutover). HUITZO_OPENAI_API_KEY, HUITZO_ANTHROPIC_API_KEY, HUITZO_LLM_CLOUD_ENABLED and HUITZO_LLM_ROUTING_* are no longer read.

Variable Required Default Description
HUITZO_SENDGRID_API_KEY ❌ - SendGrid API key for email. Unset → email is disabled
HUITZO_EMAIL_FROM ⚠️ [email protected] From: address on every message the deployment sends. The default is Huitzo's own domain and is deliberately not a boot-time requirement (a missing value must never take the backend down). Any deployment that sets HUITZO_SENDGRID_API_KEY must override it with an address at a domain it controls, with SPF + DKIM published for SendGrid. Leaving it empty, malformed, at the default, or at a shipped placeholder domain (@yourdomain.com) logs a startup warning and reports email as degraded on /health/integrations
HUITZO_EMAIL_TRANSPORT ❌ - Planned, not read yet (#2198). sendgrid, smtp or none; unset means sendgrid when HUITZO_SENDGRID_API_KEY is set, otherwise none (email platform). Today the platform sends through SendGrid only; SMTP exists only as a per-pack integration provider, covered below
HUITZO_USER_NOTIFICATIONS_ALLOWED ❌ - Planned, not read yet (#2198). Ceiling on the user_email_notifications platform setting (email platform)
HUITZO_ELEVENLABS_API_KEY ❌ - ElevenLabs API key for platform speech synthesis (ctx.tts, ADR 029). Platform-owned — never visible to packs. Unset → every ctx.tts call raises a typed IntegrationError
HUITZO_TELEGRAM_BOT_TOKEN ❌ - Telegram bot token
HUITZO_RUNNER_EXPECTED_CLI_VERSION ❌ - The huitzo CLI release this Hub image was built against — the expected reference for the runner-fleet CLI currency axis (#1583, runner-channel §5.3). Baked at image build into /app/expected-cli-release.json, which is what this setting defaults to — never hand-set in production: CI passes the launcher's cli-release.json version as the EXPECTED_CLI_VERSION build arg, and the Dockerfile falls back to the tools/cli submodule's pyproject.toml version. Set it explicitly only for a dev or self-hosted image that carries no baked fact. No value at all ⇒ the CLI axis reads unknown / no_expected_reference for the whole fleet (visible, not silent). Telemetry only — it gates nothing
HUITZO_RUNNER_EXPECTED_CLI_VERSION_SOURCE ❌ - Where the value above came from: release (the launcher's cli-release.json, what CI passes), submodule (the Dockerfile's build-time fallback derived from tools/cli/pyproject.toml) or empty — an expected version set without a source is reported as unspecified, and no expected version at all as none. Always reported alongside the expected version so the provenance of the reference itself is visible — a stale reference makes runners read ahead, and the source is how an operator tells that from a runner problem

⚠️ = has a working default, but a deployment using the feature must override it.

Sender authentication is a DNS responsibility, not an application one: SendGrid accepts any From: domain, and the receiving server decides based on SPF/DKIM/DMARC records published on that domain. See Integrations → Sender authentication.

SMTP is not a platform environment setting — it is configured per-integration through the integrations registry (provider type smtp), not via env vars. See Integrations for provider configuration.

Observability

Variable Required Default Description
HUITZO_METRICS_TOKEN ❌ - Bearer token gating the Prometheus /metrics endpoint. Unset → /metrics is disabled and returns 503 (fail-closed; never served unauthenticated). Set it on any deployment you scrape. The backend logs a startup warning in non-debug mode when it is missing. See Observability.
HUITZO_LOG_LEVEL ❌ INFO Root log level (DEBUG/INFO/WARNING/ERROR/CRITICAL; forced to DEBUG when HUITZO_DEBUG=true).
HUITZO_SENTRY_DSN ❌ - Sentry DSN for the backend, the Celery worker and Celery beat. Unset: Sentry is never initialized. Set it on the worker as well as the backend, or a failed beat task and an ERROR line on a money path (the ledger invariant check) reach no one. See Observability.
HUITZO_SENTRY_ENVIRONMENT ❌ development Environment tag on every backend and worker Sentry event.
HUITZO_LOG_FORMAT ❌ json Log output format (json or text).

Secrets Management

Huitzo uses a three-tier secrets model to manage API keys and credentials with proper access boundaries:

Tier Owner Scope Access Method
Platform Admin Platform services No SDK accessor — the platform uses them internally to service ctx.llm / ctx.email / ctx.tts / ctx.telegram
Pack Developer Single pack ctx.config.get("setting") — not yet available (ctx.config)
User End User User + Pack await ctx.secrets.require("USER_API_KEY")

Platform Secrets (Tier 1) are set via backend environment variables — except LLM provider API keys, which are registry data: they are stored encrypted on the provider's row and set at /admin/llm (ADR-038 §3.5), never in the environment. The SDK gives a pack no way to name one — there is no ctx.env accessor, and one is not planned for platform credentials. A pack requests a capability (await ctx.llm.complete(...)) and the platform resolves which key to use. Note that this is an API-surface contract rather than an enforced boundary on its own — pack code runs in a per-execution child with a scrubbed environment, under a separate sandbox UID only where the image ships the helper, so without it an untrusted pack must be treated as holding the deployment's platform credentials (details).

# pseudocode — backend deploy environment
HUITZO_SENDGRID_API_KEY=<sendgrid key>

User Secrets (Tier 3) are per-user API keys that end users provide for their own external services. They are declared in pack manifests and managed through the Dashboard UI or CLI.

Variable Required Default Description
HUITZO_SECRETS_ENCRYPTION_KEY ✅ (non-debug) none AES-256-GCM key (64-char hex / 32 bytes) for user secrets, encrypted columns and the LLM provider API keys stored in the registry. Backend refuses to boot in non-debug mode without it. Rotate it as described below.

Security: - All secrets encrypted at rest (AES-256-GCM) - User secrets isolated per user + pack - Secret values never logged - Access audited for compliance

See Secrets Management Reference for complete documentation.

Rotating the secrets encryption key

HUITZO_SECRETS_ENCRYPTION_KEY rotates in place, with no re-entry of secrets:

Step Action
0 Upgrade to a release that has rekey-secrets (compose: its install.sh; Helm: helm upgrade), changing no key
1 Once, before the first rotation: set HUITZO_SECRETS_LOOKUP_HASH_KEY to the current key (it stays forever)
2 Set HUITZO_SECRETS_ENCRYPTION_KEY_PREVIOUS to a NEW key (current key unchanged) for the backend, worker (remote compute-pool workers too), beat and migrate processes. Run rekey-secrets --dry-run against that configuration BEFORE restarting anything (it checks the lookup-hash key), then deploy: every reader learns the new key before any writer uses it
3 Swap them (current = new key, previous = old key) and deploy. Reads try the new key, then the old one; writes use the new key
4 python -m backend.manage rekey-secrets --dry-run (with the admin URL): counts per table and a check of the lookup-hash key against stored hashes, writes nothing
5 python -m backend.manage rekey-secrets: re-encrypts every value under the new key in one transaction
6 Verify: a second dry run reports zero values left to re-key
7 Remove HUITZO_SECRETS_ENCRYPTION_KEY_PREVIOUS and deploy

This applies to the shipped compose stacks and Helm chart, which forward both rotation variables; Huitzo production has its own procedure, rotate the key on Huitzo production.

The full procedure, with the container invocation, is the runbook's rotate the column encryption key; the design is column encryption key rotation.

Task Queue (Celery)

These three are read WITHOUT the HUITZO_ prefix. worker/celery.py reads them straight from the process environment rather than through the settings model, so HUITZO_REDIS_URL does not configure the broker. Setting only HUITZO_REDIS_URL leaves the worker on its built-in redis://localhost:6379/1 default — which, inside a container, points at the container itself and never reaches your Redis. A worker started that way logs a broker-fallback warning and then sits idle consuming nothing.

Variable Required Default Description
CELERY_BROKER_URL ⚠️ set it REDIS_URL verbatim (database NOT rewritten), else redis://localhost:6379/1 Celery broker URL, read by the worker
CELERY_RESULT_BACKEND ❌ REDIS_URL re-pointed at DB 2, else redis://localhost:6379/2 Celery result backend (Redis DB 2)
REDIS_URL ❌ redis://localhost:6379 Unprefixed fallback both of the above derive from
CELERY_QUEUES ❌ all declared queues Comma-separated queue list reported in the compute heartbeat

Set CELERY_BROKER_URL explicitly on every worker — do not lean on the fallback. The two rows above are deliberately asymmetric and it is not a typo: the result backend re-points REDIS_URL at database 2, while the broker uses REDIS_URL exactly as given. Meanwhile the producer side resolves its broker somewhere else entirely — the backend reads the prefixed HUITZO_CELERY_BROKER_URL, falling back to HUITZO_REDIS_URL re-pointed at database 1. So a deployment that sets REDIS_URL=redis://redis:6379/0 and omits CELERY_BROKER_URL ends up with the backend publishing to database 1 and the worker consuming from database 0. Nothing errors; tasks simply queue forever and no command ever runs. The worker logs a broker-split warning at startup when it detects exactly this, but the fix is to pin the variable.

Note also that CELERY_BROKER_URL (unprefixed) configures only the worker. Pointing a worker at an external broker with that name alone splits it from the backend again — set HUITZO_CELERY_BROKER_URL to the same value.

Set REDIS_URL, HUITZO_REDIS_URL and CELERY_BROKER_URL on every worker: the first two are the Celery transport fallback and the shared-core cache client respectively, and neither of them is a substitute for the third.

Celery broker TLS

A rediss:// Celery broker (CELERY_BROKER_URL on the worker, HUITZO_CELERY_BROKER_URL / HUITZO_REDIS_URL on the backend and extensions) or result backend (CELERY_RESULT_BACKEND) is connected with certificate verification required: the server certificate must chain to a trusted CA and name the host. Without this, kombu falls back to ssl_cert_reqs=CERT_NONE, which encrypts the link but lets anyone on the path impersonate the broker and read or inject task messages. Every Celery client in the platform (the worker app and each backend or extension producer) applies the same rule; plain redis:// URLs are unchanged.

Variable Required Default Description
HUITZO_CELERY_SSL_CA_CERTS No system CA store Path to a PEM CA bundle that signed the broker certificate (private CA, or a managed Redis that does not use a public CA). Read from the process environment (not the .env settings file) by the worker, the beat dispatch lock and every producer; it must be a file, or the backend and worker refuse to start. Compose passes it through to app and worker.

To opt out deliberately, put ?ssl_cert_reqs=none (or optional) in the broker URL; an explicit value in the URL wins over the default. Accepted spellings are exactly CERT_REQUIRED, CERT_OPTIONAL, CERT_NONE, required, optional and none (case-sensitive); anything else stops the backend and the worker at startup rather than connecting unverified. Other ssl_* URL parameters (ssl_ca_certs, ssl_certfile, ssl_keyfile, ssl_check_hostname) are honoured and merged with the CA bundle above. Weakened verification is logged as a warning naming the broker host. Disabling verification re-opens the man-in-the-middle exposure above: use it only as a temporary last resort.

Worker visibility timeout

Commands are acknowledged late, so Redis keeps a delivery invisible until the command finishes or the Celery transport's visibility_timeout elapses, after which it hands the message to another worker. The worker sets this to 36000 s (10 h), derived from the stale-execution reaper's long-queue budget (32430 s) plus a margin, so a command that stays within its queue's budget is not started a second time. Redis's own default is one hour. The value is global to the broker connection (the fast and medium queues get it too), so after a worker crash a message is redelivered only after up to 10 h; the reaper fails the tracking row earlier.

Variable Required Default Description
HUITZO_WORKER_VISIBILITY_TIMEOUT No 36000 Redelivery window in whole seconds. Read from the process environment by the worker only; producers need no matching value. A non-integer value, or one outside 32430 to 604800, is logged and replaced by the default. Compose passes it through to worker.

Every worker sharing a broker must use the same value. A worker with a smaller one redelivers unacked messages at that smaller interval. A command whose manifest timeout exceeds 36000 s can still be redelivered and run twice (scaling.md; validate-time check tracked in #1926).

Worker (Celery) — required environment

A Huitzo worker is not a thin remote agent. It loads the same settings model as the backend and serves each pack command's context (storage, secrets, metering) to that command's isolated child, which means it opens its own connections to PostgreSQL and Redis. There is no HTTP-only / remote-worker mode: a worker that cannot reach Postgres and Redis directly on the deployment's private network cannot run a single task.

HUITZO_INTERNAL_BACKEND_URL is not a way to run a worker over the public API. It is used for one thing — the compute-pool heartbeat POST — and its host must resolve inside a loopback allowlist (localhost, 127.0.0.1, ::1, backend, worker). A public hostname such as https://huitzo.example.com is rejected and the heartbeat is skipped; it never affects task execution.

Variable Required Purpose
HUITZO_DATABASE_URL ✅ Direct PostgreSQL connection (the worker reads/writes execution rows itself)
HUITZO_JWT_SECRET_KEY ✅ Shared settings model — must match the backend
HUITZO_AUDIT_PEPPER ✅ (non-debug) Audit-log redaction — must match the backend
HUITZO_SECRETS_ENCRYPTION_KEY ✅ (non-debug) Encrypted columns + user secrets, and decrypting the LLM provider keys the worker's LLM calls use — must match the backend
HUITZO_SECRETS_ENCRYPTION_KEY_PREVIOUS, HUITZO_SECRETS_LOOKUP_HASH_KEY during / after a rotation Must match the backend
HUITZO_REDIS_URL ❌ Shared-core cache client
CELERY_BROKER_URL ⚠️ set it Celery broker — see the warning in Task Queue (Celery); the fallback silently splits producer from consumer
CELERY_RESULT_BACKEND ❌ Celery result backend — see Task Queue (Celery)
HUITZO_INTERNAL_BACKEND_URL ❌ Compute heartbeat target only; allowlisted hosts only
HUITZO_WORKER_TOKEN ❌ Bearer token for the compute heartbeat (compute-pool.md §3.4). On the backend it is only the bootstrap seed, used until the first rotation from /admin/compute; the backend then keeps only the digest of the rotated token

Beyond booting, a worker needs runtime parity with the rest of the fleet. Every worker consumes the same queues, so a capability the others have and this one lacks makes identical tasks succeed or fail depending on which worker Celery routes them to. Mirror HUITZO_DEPLOYMENT_MODE and HUITZO_ELEVENLABS_API_KEY when the backend sets them, and every billing and metering flag: the worker builds the same Settings, runs the same boot validators, and meters, settles and sweeps on its own. The rule and the full flag list are in worker parity. A worker also needs the shared pack-wheel volume mounted — installed pack code lives only there and the worker has no on-demand install path.

Startup preflight. Before the worker boots its consumer it runs three checks and, outside debug mode, aborts with a single actionable message and a non-zero exit so the container restarts loudly instead of idling with zero working tasks:

  1. Presence — every required variable above carries a non-blank value.
  2. Validity — the settings model actually builds. Presence alone cannot tell a too-short JWT secret or a non-hex encryption key from a good one, and both are rejected by the same validators, so a present-but-invalid value would otherwise produce a green worker that fails every task.
  3. Broker sanity — warning only, never fatal. Covers both the no-broker fallback and the producer/consumer database split described above.
# illustrative — not literal output
huitzo worker preflight FAILED — missing required environment:
  HUITZO_JWT_SECRET_KEY  (…why it is needed…)
  HUITZO_AUDIT_PEPPER    (…why it is needed…)
See docs/reference/configuration.md#worker-required-environment

Under HUITZO_DEBUG=true the presence and validity checks log a warning and let the process continue, so image-build import smoke tests still work. Implementation: apps/worker/src/worker/preflight.py.

Global Timeouts

Variable Required Default Description
HUITZO_GLOBAL_TIMEOUT ❌ 28800 Platform-wide max command timeout (seconds)
HUITZO_DEFAULT_COMMAND_TIMEOUT ❌ 60 Default timeout for commands without explicit setting
HUITZO_MAX_PACK_TIMEOUT ❌ 28800 Maximum allowed pack-level timeout

The timeout hierarchy is: Command ≤ Pack ≤ Platform Global. See Commands Reference for details.

Self-Hosted (Licensing)

Licensing is a pure-offline, Ed25519-signed license.json verified locally — no license server, no online validation, no machine activation (ADR-007 / ADR-008). The OS reads a signed file and resolves a VALID / GRACE / INVALID state from its expires_at.

Variable Required Default Description
HUITZO_LICENSE_PATH ❌* /etc/huitzo/license.json Path to the Huitzo-signed license.json.
HUITZO_OFFLINE_GRACE_DAYS ❌ unset Lowers the grace window after the file's expires_at (days). It can never raise the signed grace_days (caps: 7 Preview, 14 otherwise); a value above 14 fails at boot, and the error names the cap (ADR-008 D2). Unset, the signed value applies.
HUITZO_LICENSE_CHECK_INTERVAL ❌ 3600 Interval to re-read the license file from disk (seconds). Capped at 3600; a higher value fails at boot. Expiry is evaluated on every request regardless.

*A signed license.json is required for self_hosted deployment mode; the path variable is optional because it defaults. Place the file on disk (and mount it into the containers) — there is no license key to set.

See Quick start for installation and License status and renewal for installing, renewing and reloading a license file.

Self-Hosted (Billing Isolation)

Self-hosted Huitzo Core runs fully operational with SaaS billing absent, unconfigured, or unreachable — metering is a reporting feature there, never a gate (ADR-035 §8).

Variable Required Default Description
HUITZO_USAGE_TRACKING_ENABLED ❌ false Core per-tenant usage measurement: gates the Core execution_usage recorder (ADR-043 DR-24d). Measured quantities only — no wallet, no lots, no ledger, no prices, no outbound calls; a write failure never fails or blocks a command. Off: no row is written and no database session is opened. Independent of the flag below, which no longer reads it. With billing on, keep it on: the stuck hold sweep charges a failed settlement only when this recorder wrote the execution's row. With billing on and this flag off the backend logs a startup WARNING naming that consequence: the charge stays reserved (boot checks). Managed runners need it too: their HUITZO_MANAGED rows are written only by this recorder, and with HUITZO_MANAGED_RUNNERS_ENABLED on and this flag off the backend logs a startup WARNING (managed runners staging runbook).
HUITZO_SAAS_BILLING_ENABLED ❌ false The named opt-in: permits outbound SaaS billing calls, wallet debits, and hard enforcement. On, every chokepoint charges the acting tenant's wallet (the credit_accounts row with user_id NULL), including scheduled work with no actor, and fails closed for platform-funded work: a hold, a 402 INSUFFICIENT_CREDITS or a 503 RESERVATION_UNAVAILABLE, never an unreserved run (ADR-041 D3). The tenant wallet is the only wallet model and has no flag of its own (the tenant wallet). Refused at load unless HUITZO_PAYG_ENABLED, HUITZO_ACCRUAL_ENABLED and HUITZO_LLM_PRICING_ENABLED are all on (ADR-041 E1). Off: nothing is reserved, charged or refused. true on an image without the SaaS extension is inert — logged once at startup, never a startup error.

Note: the "never blocked" guarantee above now covers every credit refusal path. Core's older, separate llm_preflight_gate — which could return HTTP 402 under an unrelated flag — was deleted with ADR-019's Ledger A (migration saas_0014), so these two flags are the only things that can gate a command on credit.

See Usage Tracking & Billing Isolation for the operator-facing walkthrough.

Process-Isolation Boundary

There is no switch here. Every call of a pack command — a single command on any queue, a pipeline stage, a nested ctx.commands call — runs in its own per-execution child process (ADR-039), and the backend and worker register a pack's commands from metadata an isolated child stored, never importing it (Static registration). The former HUITZO_ISOLATION_BOUNDARY_*_ENABLED switches are removed: there is no in-process path left to switch to. A leftover variable has no effect.

Variable Required Default Description
HUITZO_PACK_STARTUP_LOAD_BUDGET_SECONDS ❌ 20 How long backend and worker startup wait for the registration of active pack builds before serving or consuming (a worker child: at most half of HUITZO_WORKER_PROC_ALIVE_TIMEOUT). Only builds whose command metadata is stored are registered; none is described inline. Past it a WARNING gives the progress and the rest finishes in a background thread; a build not registered yet is served through its first use. Minimum 1.
HUITZO_PACK_BUILD_NOT_READY_RETRY_WINDOW_SECONDS ❌ 1800 How long a worker task (command or pipeline run) whose pack build is not repaired or registrable yet is retried (after 15 s, doubling up to 2 minutes), wall-clock from the first attempt that found it not ready; a retry is scheduled only if it is due inside the window. Past it the task fails as PACK_BUILD_UNAVAILABLE. The row stays queued (PENDING) meanwhile. Minimum 1, maximum 1800 (the pipeline-run sweep's margin includes it).
HUITZO_PACK_PERMISSION_REPAIR_BUDGET_SECONDS ❌ 20 How long backend and worker startup wait for the pack build permission repair before the backend serves or the worker consumes. Past it a WARNING gives the progress and the rest of the pass finishes in a background thread; until a build is repaired it is not registered, and REST and MCP calls to its commands answer the retryable 503 PACK_BUILD_NOT_READY. Minimum 1.
HUITZO_CHILD_CLEANUP_WAIT_SECONDS ❌ 30 How long an execution, on any surface, waits in total for the cleanup after its child: the scan of the child's process group for survivors and the removal of its workspace. Past it an error is logged and the execution returns; a scan still running counts as finding survivors (the group is killed), and the removal goes on in the background (ADR-039: fork safety and bounded cleanup). Minimum 1.

Not a full confinement boundary. Where the image ships the sandbox helper, the child runs under a separate sandbox UID that cannot read the parent's environment or private files (ADR-039 Sandbox UID); without the helper it runs under the parent's uid, with no PID-namespace or filesystem separation. Either way every tenant's child shares one uid and the network; see Isolation Strategy.

Inline command limits

Bounds on commands that run inline in the API process (the fast queue on POST /api/v1/commands/{namespace} and MCP tools/call). Under the default process isolation each such execution spawns its own child process. These settings decide how many inline executions can run at once and how long each may take, with or without isolation (ADR-039: inline admission).

Variable Required Default Description
HUITZO_INLINE_SPAWN_MAX_PER_TENANT ❌ 2 Inline command executions one tenant may have running at once, across every API process (counted in Redis; each process also enforces it on its own count, which still holds during a Redis outage). The next one is refused with 429. Minimum 1.
HUITZO_INLINE_SPAWN_MAX_GLOBAL ❌ 6 Inline command executions the API process runs at once, across all tenants. The next one is refused with 429. Minimum 1. Each execution can hold up to 5 child processes when its command nests ctx.commands calls (the command and four nested levels), so size memory for 5 × this value.
HUITZO_INLINE_COMMAND_TIMEOUT_SECONDS ❌ 40 Cap on an inline execution's timeout, counted from admission (the request taking its slot) to the answer: the execution row, context creation, pack loading, credit holds, child spawn and the command itself all end by it, and a stall in any of them is answered as a timeout. A command declaring a longer timeout is cut to this. The cap plus what can still happen after it (the child's kill, reap and connection drain, up to about 11 s; the credit handbacks, 2 s; a completed run's commit, 3 s; the outcome writes, 1 s each) must stay below your reverse proxy's read timeout for /api (proxy_read_timeout 60s in the dashboard image's apps/dashboard/nginx.conf) so a slow command is answered by the API's own 504 with code: TIMEOUT; the default 40 leaves that room. Removing the workspace the command left behind is outside that sum: the answer waits for it at most HUITZO_CHILD_CLEANUP_WAIT_SECONDS (default 30 s, see Process-Isolation Boundary), so a command that leaves a very large tree can still reach the proxy's bare 504; lower that setting if that matters to you. Set it too close to the proxy's value and callers get the proxy's bare 504 again. Minimum 1.

Where they are counted. The tenant limit is counted in Redis, so it holds across every API process and replica; each process also enforces it on its own count, which still holds during a Redis outage. The total (HUITZO_INLINE_SPAWN_MAX_GLOBAL) is counted per API process, because it sizes that process's children and memory (shared limits). Celery workers are not counted: their own concurrency bounds the medium and long queues. A slot stays taken until its execution's child has been killed and its workspace removed, even when the caller cancelled.

Streaming stages

A streaming pipeline stage runs in its isolated child and hands its chunks to the parent one at a time (ADR-039: streaming stages). A chunk is at most 1 MiB of JSON and 16,384 values across all its fields. The limits below bound the memory the parent holds, never how much passes through: a chunk is charged its decoded size (encoded bytes plus an allowance per value) while it waits in a buffer or an edge queue, and given back when the next stage takes it, so a stream of any total length passes. What a run keeps (its result, and what its joiners read from streaming branches) stays charged until the run ends.

Variable Required Default Description
HUITZO_PIPELINE_CHUNKS_MAX_BYTES ❌ 268435456 (256 MiB) Most memory one pipeline run's chunks may take in the process at once (waiting chunks plus what it keeps). Past it the run fails with "The pipeline holds more than … bytes of chunks at once (HUITZO_PIPELINE_CHUNKS_MAX_BYTES)". Minimum 1 MiB.
HUITZO_PIPELINE_CHUNKS_MAX_BYTES_PER_PROCESS ❌ 1073741824 (1 GiB) Most memory all pipeline runs' chunks may take in one API or worker process at once; one tenant may take at most a quarter. Past either, a run is refused with the retryable 429. Size it with the process's memory. Minimum 4 MiB.
HUITZO_STREAM_STAGE_MAX_BYTES ❌ 1073741824 (1 GiB) Most bytes one streaming stage may emit in total, as encoded JSON. An abuse ceiling, not a memory bound: past it the stage fails with "A streaming stage emitted more than … bytes (HUITZO_STREAM_STAGE_MAX_BYTES)". Minimum 1 MiB.

Huitzo Studio

Deployment-level settings for Huitzo Studio and the runner fleet. Every one of them must reach the container, not just the .env file: Settings reads the process environment. In the reference compose stack every HUITZO_* line of .env reaches the backend and the worker through app.env (the compose settings rule), so a setting left out of .env is absent from both and its default below applies. A line with a blank value is passed as blank, not omitted: never write one for an image-baked value.

Variable Required Default Description
HUITZO_STUDIO_DEFAULT_COMMAND_ALLOWLIST ⚠️ [] JSON list of exact argv[0] strings — typically absolute binary paths, since the runner's ScopeEnforcer matches argv[0] exactly — bound into the signed scope of a dashboard intent-only build that supplies no explicit allowlist. Empty is default-DENY: such a build resolves an empty allowlist and every stage command is refused fail-closed, so a deployment that wants agentic builds must set this to the runner box's tool paths. An explicit REST caller's own least-privilege allowlist is always used verbatim.
HUITZO_STUDIO_DEFAULT_REPO_URL ❌ scaffold:studio-workspace repo_handle bound to a dashboard intent-only build that supplies no repo. A from-intent scaffold build authors in the runner's confined workspace rather than cloning, so the handle is metadata. The default is deliberately an opaque, host-less sentinel (an opaque:path form with no // authority) so it contributes no host to the signed egress allowlist and the egress set stays at the strict default (model API + registries only).
HUITZO_STUDIO_PLAN_EXECUTE_ATTEMPT_CAP ❌ 3 Max total executions per approved plan — the approve dispatch counts as the first, and every POST /plans/{id}/execute beyond the cap answers 429 with the attempt_cap class. Exactly 1 disables explicit re-execution (the approve is the one execution). 0 or negative is refused at startup rather than silently 429-ing forever.
HUITZO_STUDIO_SPEC_JOB_BUDGET_S ❌ 600 Wall-clock budget in seconds for one async SPECIFY job. Threaded into spec_service.draft_spec as budget_s, replacing the interactive SPECIFY policy's own ceilings for cloud-routed calls; a SPECIFY profile that resolves to local (Ollama) inference is governed by HUITZO_LOCAL_AI_TIMEOUT instead. Exceeding it fails the job with a user-facing timeout — it never leaves a job pending or running forever.
HUITZO_STUDIO_STEWARD_ENABLED ❌ true Run the Mission Steward sweep every 5 minutes: find Studio sessions nobody is moving, log studio_mission_stalled, alert. false stops the sweep before any query.
HUITZO_STUDIO_STEWARD_REMEDIATE ❌ true Let the steward run its closed, bounded remediation menu (re-run CLARIFY scoring, fail an abandoned SPECIFY/plan/build job through its existing failure path so the session shows its retry). false = detect-only: stalls are still logged, recorded and alerted.
HUITZO_RUNNER_ADMISSION_CAP ❌ 50 Max number of concurrently active (online) runners the fleet will admit. At or over the cap a new runner is refused at the register/heartbeat admission seam; runners already online keep working — only growth is blocked. The enforceable proxy for the support-cost budget; raise it without a code change as the budget grows. A value <= 0 blocks all new admissions (the explicit fleet-growth freeze).

⚠️ = has a working default, but a deployment using the feature must override it.

The two HUITZO_RUNNER_EXPECTED_CLI_VERSION* variables are documented under Services — leave both unset in production; the image bakes them.

PAYG wallet

The switches of the PAYG wallet (ADR-036), plus the Stripe and dashboard-origin settings every money path below reads. The D-024 flag ladder says where each sits in the order and which flags are refused at load without HUITZO_PAYG_ENABLED.

Variable Required Default Description
HUITZO_PAYG_ENABLED ❌ false Turn the PAYG wallet on: registration stops writing a saas_subscriptions row (the tenant's wallet account is written either way, on a database that has the SaaS tables), and the wallet routes answer (/api/v1/wallet, /wallet/lots, /wallet/topup/*, /wallet/usage/*, /wallet/reload/*). Off: those routes are 404, a settled top-up webhook is dropped with the warning payg_topup_settlement_dropped_payg_dark, and no signup seed is written by either trigger. HUITZO_SAAS_BILLING_ENABLED and HUITZO_SEED_ON_VERIFICATION are refused at load without it: the chokepoint would charge tenant accounts nobody can read or top up through the app, and no seed would be granted.
HUITZO_SIGNUP_GRANT_ENABLED ❌ false Stamp new wallet accounts eligible for the 50-credit signup seed (Credits: signup seed). Read once, at account creation: the value in force is written to credit_accounts.wallet_signup_grant_eligible and never re-evaluated, so turning it on later does not make an existing account eligible. Off: no account created while it is off is ever seeded by the lazy seed, and HUITZO_SEED_ON_VERIFICATION is refused at load.
HUITZO_PAYG_RATE_LIMIT_ENABLED ❌ true The per-user arm of the SaaS rate limiter (rate limiting). On by default. The plan budgets apply; no plan has a commands-per-hour cap. false turns the per-user arm off entirely, per-minute budgets included; the Team pooled arm and HUITZO_RATE_LIMIT_ENABLED are unaffected. A blank value means the default. Backend only (the limiter is HTTP middleware).
HUITZO_STRIPE_SECRET_KEY ⚠️ - Stripe secret API key. Needed by every Stripe call: top-up Checkout, card setup, auto-recharge, the Team invoice rail, usage blocks, refunds and Stripe Tax. Set it on the backend and the worker (the worker initiates auto-recharges).
HUITZO_STRIPE_WEBHOOK_SECRET ⚠️ - Signing secret of the one Stripe webhook endpoint, POST /api/v1/billing/webhook (webhook troubleshooting). Backend only.
HUITZO_FRONTEND_URL ⚠️ http://localhost:3000 The dashboard origin. Checkout and portal redirect URLs are validated against it, and the links in the verification, coupon and renewal emails are built from it. A deployment that leaves the default sends emails that link to localhost.

⚠️ = optional for a deployment that sells nothing; required before any flag in the D-024 flag ladder that moves money or sends email.

Metering v2 flags

Metering v2 introduces three flags (ADR-038 §7); all three ship as of this page. All are dark by default and byte-identical when off — with every one of them off, metering behaviour is indistinguishable from the pre-Metering-v2 build.

Variable Required Default Description
HUITZO_ACCRUAL_ENABLED ❌ false Record sub-credit costs exactly and accumulate them per account instead of flooring every charge up to a whole credit (ADR-038 §5). Off: no new column is written, no accumulator moves, and no accrual_drawdowns row is created.
HUITZO_LLM_PRICING_ENABLED ❌ false Price, authorize, reserve, and settle LLM token usage at the llm_backend chokepoint (ADR-038 §1–§2, LLM Chokepoint Metering spec). Off: the LLM path makes no reservation, no settlement, and no registry-snapshot read. May only be enabled when HUITZO_ACCRUAL_ENABLED is also enabled — see the validator below.
HUITZO_PRICING_FROM_DB_ENABLED ❌ false Price compute.seconds/tts.characters/llm.tokens from the versioned price_versions rows a rate-policy publish maintains, instead of backend.metering.rate_card's code constants (ADR-038 §6, rate-policy publishing schema spec). Off: ProductPricer reads only the code constants. On: byte-identical against the seeded v1 rows, since they equal the code constants they replace. Independent of HUITZO_ACCRUAL_ENABLED/HUITZO_LLM_PRICING_ENABLED — governs the rate source, not the accrual/rounding mechanism — so no startup-validator pairing applies to it.

Turning HUITZO_ACCRUAL_ENABLED off again is safe and loses nothing. Accrued remainders stop growing; they are not discarded, and no already-written row is invalidated. The next time the flag is on, the remainder resumes as the first claim against the account's live lots.

HUITZO_ACCRUAL_ENABLED flips first, and the order is not negotiable (ADR-038 §7.3). HUITZO_LLM_PRICING_ENABLED without accrual would floor every LLM call up to one whole credit — a 100×+ over-charge on a typical completion.

The startup pairing validator

Because that mistake is one environment-variable flip away in a console at 2am, the machine refuses it rather than warning about it (ADR-038 §7.2). Settings validation fails at load — so the API and worker processes refuse to start, before any request is served — when:

HUITZO_LLM_PRICING_ENABLED=true  and  HUITZO_ACCRUAL_ENABLED=false

The error names both variables and states the fix. The startup validator that refuses to boot on the unsafe pairing lands with the flag it guards (HUITZO_LLM_PRICING_ENABLED), not with HUITZO_ACCRUAL_ENABLED. The other three combinations of those two flags are all valid with billing off: both off, accrual only, and both on. There is no silent downgrade of either flag. HUITZO_SAAS_BILLING_ENABLED is refused the same way without both of them and HUITZO_PAYG_ENABLED (_validate_saas_billing_pairing, flag ladder). HUITZO_PRICING_FROM_DB_ENABLED is not part of this pairing (see its row above) and may flip independently of either.

D-024 plans and the tenant wallet

Variable Required Default Description
HUITZO_HOUSE_PLAN_ENABLED ❌ false Enable the internal house plan for the first-party and demo tenants (ADR-041 D11): staff provisioning and budget writes at /api/v1/admin/tenants/{id}/house-plan (404 while off; see REST: house plan), and, with HUITZO_SAAS_BILLING_ENABLED also on, a house tenant is funded by its monthly budget only, never by credit lots or the ledger, with a 402 at 100% of budget. Not paired with billing: house may be provisioned before billing goes on. Off: a house tenant draws its wallet like any other tenant.
HUITZO_HOUSE_BUDGET_ALERT_ONLY_ENABLED ❌ false FQ-2 alert-only mode: a house tenant past 100% of its budget keeps running, the overflow settles as uncollected, and a house_budget_exhausted warning is logged, instead of a 402. Refused at startup without HUITZO_HOUSE_PLAN_ENABLED. Leave off until the founder rules on FQ-2.
HUITZO_TEAM_INVOICE_RAIL_ENABLED ❌ false Reopen the Team stripe_invoice rail (ADR-041 D9, billing: Team invoice rail): staff may provision a Team plan billed by a Stripe send_invoice subscription on the tenant's billing-profile customer, the admin tenant page offers the mode, and PATCH …/team-subscription upgrades an invoice-mode plan with a Stripe proration and a prorated allowance. Refused at startup without HUITZO_SAAS_BILLING_ENABLED. Needs the hz_team_*_monthly Prices (provision_catalog.py --team). Counsel-gated: leave off until the allowance framing is confirmed. Off: stripe_invoice provisioning is refused with 409 team_stripe_invoice_out_of_scope and invoice-mode rows reject the PATCH, exactly as before.
HUITZO_TEAM_USAGE_BLOCKS_ENABLED ❌ false Enable invoiced usage blocks, the Team overflow option (ADR-041 D12): staff issue a one-off Stripe invoice for at least 5,000 credits at /api/v1/admin/tenants/{id}/usage-blocks (404 while off; see REST: usage blocks), and a paid block becomes one purchase lot on the tenant account. Off: a block payment webhook is a logged no-op 200. Refused at startup without HUITZO_SAAS_BILLING_ENABLED. Subscribe the Stripe webhook endpoint to invoice.paid before turning it on.
HUITZO_SENDGRID_TEMPLATE_COUPON ❌ - SendGrid dynamic template id for the coupon delivery email, sent when a staff or tenant coupon is minted with bound_email (REST: coupon delivery email, D-024 CR77). Template data: recipient_email, coupon_url, coupon_code, support_email, signup, tenant_name. Unset: the worker sends a plain text and HTML body. Coupons themselves have no flag: since the access-code fold (D-024 CR78) the staff, tenant and redeem routes and coupon registration are always on (ADR-042 D14).
HUITZO_COUPON_CREDITS_ENABLED ❌ false Register the SaaS credits.grant and plan.assign coupon capabilities (ADR-042 D7, D-024 CR71, CR72): staff may mint coupons that grant promotional credits, where a redemption writes one source='coupon' lot plus one ledger grant entry on the landing tenant's wallet (Credits: coupon credits), and coupons that give a team tenant a Team-plan trial (billing: Team trials; also needs HUITZO_TEAM_LIFECYCLE_V2_ENABLED, whose sweep then rolls each trial until its trial_ends_at and ends it there; rows without trial_ends_at, every staff-provisioned row, keep their cancel timing). Off: the SaaS extension registers no coupon handler, so a mint of either is 422 coupon_capability_unavailable and redeeming an existing one gives the uniform coupon_invalid refusal with nothing written.
HUITZO_PROMO_BUDGET_ENFORCED ❌ false Enforce the monthly promotional budget (ADR-042 D13, D-024 CR73; Credits: promotional budget): a coupon-credit grant that does not fit under the 25,000-credit monthly cap (New York month) is queued for staff approval at /api/v1/admin/promo-grants instead of written; the redemption still succeeds with the outcome queued. Off: every grant is counted against the cap but never refused or queued. The 80% alert fires either way.
HUITZO_EMAIL_VERIFICATION_ENABLED ❌ false Enable email verification (ADR-042 D11, D-024 CR74): GET /api/v1/auth/verify-email/status, POST /api/v1/auth/verify-email/send and the public POST /api/v1/auth/verify-email (REST: email verification), and the dashboard's verify banner and /verify-email page. Needs the SaaS extension (the email_verifications table is saas_0034). SendGrid is not required to boot: without HUITZO_SENDGRID_API_KEY the worker dead-letters each email. Off: the three routes return 404 and the banner is hidden.
HUITZO_PACK_PRICING_ENABLED ❌ false Enable server-owned pack pricing versions (execution pricing §3, D-024 CR82): the owner's GET and POST /api/v1/packs/{pack_id}/pricing-versions and the staff GET /api/v1/admin/pack-pricing with POST …/{version_id}/approve and …/reject (REST: pack pricing versions), and the approved-price read (pack_approved_price, saas_0036). Also gates the pack.price reserve, settle and release and the pack_fee_settlements record (settlement spec §0.4.2, CR83); command and pipeline executions charge P beside compute (settlement spec §0.4.6, CR87). Needs the SaaS extension; refused at load unless HUITZO_SAAS_BILLING_ENABLED is on. Off: every route returns 404, the read resolves no price (P = 0), and no pack.price charge or fee record is written.
HUITZO_SENDGRID_TEMPLATE_VERIFY_EMAIL ❌ - SendGrid dynamic template id for the verification email. Template data: user_email, verify_url, token_ttl_hours, support_email and the brand fields. Unset: the worker sends a plain text and HTML body.
HUITZO_VERIFY_EMAIL_SEND_IP_RATE_LIMIT_PER_HOUR ❌ 3 Max POST /api/v1/auth/verify-email/send calls per client IP per hour bucket before 429 (ADR-042 D9). Fails closed on a Redis outage (503).
HUITZO_VERIFY_EMAIL_SEND_USER_RATE_LIMIT_PER_HOUR ❌ 3 Max POST /api/v1/auth/verify-email/send calls per signed-in user per hour bucket before 429. Fails closed on a Redis outage (503).
HUITZO_SEED_ON_VERIFICATION ❌ false Grant the 50-credit signup seed at the first verification (ADR-042 D12, D-024 CR75; Credits: signup seed): an email verification or the first settled top-up, only in a home tenant on payg, once per tenant, through the promotional budget. Registration stamps eligibility only in a home tenant. Needs HUITZO_SIGNUP_GRANT_ENABLED (it writes the eligibility stamp at account creation; an account created while it was off is never seeded) and HUITZO_PAYG_ENABLED; the email trigger also needs HUITZO_EMAIL_VERIFICATION_ENABLED. Refused at load without HUITZO_SIGNUP_GRANT_ENABLED or HUITZO_PAYG_ENABLED: this flag turns the lazy seed off, so with either missing no seed would ever be granted (flag ladder: admission and promotions). Nothing refuses it without HUITZO_EMAIL_VERIFICATION_ENABLED; a first settled top-up then seeds and an email verification cannot happen. Off: the legacy lazy seed on GET /api/v1/wallet stays in force.
HUITZO_SEED_IP_VELOCITY_PER_DAY ❌ 3 Max email verifications per client IP (the keyed request_ip_hash) per rolling 24 hours that receive the signup seed. Over it the verification succeeds and no seed is written (log only).
HUITZO_REQUIRE_SIGNUP_COUPON ❌ true Require a signup coupon at POST /api/v1/auth/register (ADR-042 D14): a coupon_code carrying account.create, the only admission credential since the access-code fold (D-024 CR78). On: a body without one is 400. Off: registration is open (dev and test only); a coupon_code that is sent is still redeemed. Renamed from HUITZO_REQUIRE_ACCESS_CODE with no alias (D-024 CR70); the old variable is ignored.
HUITZO_TEAM_CARD_OVERFLOW_ENABLED ❌ false Enable the tenant card, the Team overflow option (ADR-041 D12): a Team tenant's owner and admins may save a card on the tenant's Stripe customer (POST /api/v1/wallet/topup/card-setup, 404 while off; see REST: tenant card setup) and top up the tenant account, always on the tenant customer from its billing profile, never a personal one. The owner and admins may also arm auto-recharge on the tenant account (PATCH /wallet/reload/policy, POST /wallet/auto-reload/enable; tenant auto-recharge). Members stay 409 team_managed_billing. Off: the plan gate refuses every Team caller, as before, and a card-setup webhook is a logged no-op 200. Refused at startup without HUITZO_SAAS_BILLING_ENABLED. Subscribe the Stripe webhook endpoint to checkout.session.completed (already required for top-ups) before turning it on.
HUITZO_PAYG_AUTO_RELOAD_ENABLED ❌ false Auto-recharge on the tenant account (Credits: tenant auto-recharge, ADR-041 D12): a downward crossing of the trigger balance on a payg or team_* tenant account records one attempt, and the huitzo.wallet_reload_sweep beat task charges the tenant's Stripe customer from its billing profile within a minute. Money-moving. Refused at startup without HUITZO_SAAS_BILLING_ENABLED. The Mexican-consumer and unknown-country block is not behind this flag. Off: no attempt is written, and the sweep drains open attempts without a provider call.
HUITZO_LOT_OWNER_CAPTURE_ENABLED ❌ false Record owner and payment facts on every paid lot (ADR-041 lot owner snapshot): top-up Checkout requires a billing address and uses the tenant's Stripe customer (created on the first checkout), and top-up and auto-reload settlement stamp country, region, postal code, owner type and name, amount paid, currency, tax, cost basis and a payment-reference hash. Enabling auto-reload then needs an address on file (409 billing_address_required). Not paired with any other flag. Off: Checkout, settlement and auto-reload are unchanged, and the backend refuses to start once the owner-snapshot cutover is less than 30 days away (boot checks). See lot owner capture.

The tenant wallet has no flag. The wallet belongs to the tenant (ADR-041 C3): registration provisions the tenant account, and every wallet route (balance, top-up grant and history, rung, usage, auto-reload policy and opt-out, signup seed, auto-reload payer) acts on it. Auto-reload policy and opt-out writes, top-up checkout, and the wallet's totals (usage summary, top-up history) are limited to the tenant's owner and admins (ADR-041 D7; see REST: tenant wallet). HUITZO_SAAS_BILLING_ENABLED decides whether anything is charged; the D-024 flag ladder gives the order.

HUITZO_TENANT_WALLET_ENABLED was removed on 2026-10-09 together with the personal-wallet model it switched from (migration plan §5). A line left in .env is ignored: delete it. A deployment that still holds funded personal accounts runs the cutover on release v0.17.x before upgrading; the saas_0044 migration refuses the upgrade otherwise (upgrade notes).

D-024 credit compliance

Variable Required Default Description
HUITZO_LOT_EXPIRY_SWEEP_ENABLED ❌ false Run the hourly lot expiry sweep in the worker (Credits: lot expiry sweep, ADR-041 D13): each lot past expires_at gets one expiration ledger entry for its remaining credits (a drained lot is stamped with no entry), and auto-reload is re-evaluated per account. Off: the tick issues no query. Not paired with any other flag (ADR-041 E1).
HUITZO_CREDIT_EXPIRY_REMINDERS_ENABLED ❌ false Send the daily credit expiry reminders from the worker (Credits: expiry reminders, ADR-041 D13): a notice 30 days and 7 days before each lot with credits remaining expires, to the tenant's owners and admins, in Spanish when the billing country is MX. Each (lot, notice) is sent once. Off: the tick issues no query. Not paired with any other flag (ADR-041 E1).
HUITZO_WALLET_ALERTS_ENABLED ❌ false Evaluate and email the wallet alerts (Credits: wallet alerts, ADR-041 C4/D4): the balance alerts at 50%, 25% and the at-threshold level for every personal or tenant account, independent of HUITZO_PAYG_AUTO_RELOAD_ENABLED, and the Team allowance alerts at 25% and 0 units remaining. Rows are written pending at settlement and emailed after commit by the worker's 60 s huitzo.wallet_alert_dispatch tick; rows written before the flag was on are never sent. Set it on the backend and the worker alike. Off: every settlement statement is the pre-CR38 one and the tick issues no query. Not paired with any other flag (ADR-041 E1).
HUITZO_PAID_BALANCE_CAP_ENABLED ❌ false Enforce the $1,900 paid-balance cap (Credits: paid balance cap, ADR-041 D13): top-up checkout over the cap is a 400 paid_balance_cap_exceeded before Stripe, an over-cap auto-reload writes no attempt (reload_state=capped) or is expired at initiation, and a settlement that lands over the cap is granted and logged as a reconciliation incident. Counsel-gated (FinCEN "associated value"), so it ships dark. Off: no cap query on any path. Not paired with any other flag (ADR-041 E1).
HUITZO_PAID_BALANCE_CAP_CREDITS ❌ 19000 The paid-balance cap in credits (19,000 = $1,900). Read only while HUITZO_PAID_BALANCE_CAP_ENABLED is on.
HUITZO_DISPUTE_CLAWBACK_ENABLED ❌ false Claw back a chargeback (Credits: dispute clawback, ADR-041 disputes and refunds): charge.dispute.created (and charge.dispute.closed lost) zeroes the disputed paid lot with a negative adjustment, records one credit_writeoffs row, freezes the account (closed at the second dispute), disables auto-reload and revokes seed eligibility. A frozen or closed account then gets 402 at the chokepoint for every product, and top-up checkout and auto-reload enable refuse it with 409. Set it on the backend and the worker alike (the worker runs chokepoint work). Off: dispute events are acknowledged and ignored, and no path reads the freeze. Not paired with any other flag (ADR-041 E1).
HUITZO_PAYG_REFUNDS_ENABLED ❌ false The 30-day refund of an untouched paid lot (Credits: paid-lot refunds, ADR-041 disputes and refunds): staff POST /api/v1/admin/wallet/lots/{lot_id}/refund refunds amount_paid_minor + tax_minor (less the retained Stripe fee outside Mexico and California consumers) and retires the lot with a negative adjustment; refund.created and charge.refunded mirror refunds made anywhere, proportionally. Counsel-gated (auto-renewal laws), so it ships dark; the Terms must allow refunds first. Off: the route answers 404 and refund events are acknowledged and ignored. Not refused without HUITZO_LOT_OWNER_CAPTURE_ENABLED, but the backend logs a startup WARNING: the staff route refuses every lot sold while capture is off (boot checks). Otherwise not paired with any other flag (ADR-041 E1).
HUITZO_STRIPE_TAX_ENABLED ❌ false Collect tax on top through Stripe Tax (Credits: Stripe Tax, ADR-041 Stripe Tax and MXN): automatic_tax on the top-up Checkout, the Team send_invoice subscription and usage-block invoices; auto-reload prices the tax with a Tax Calculation before the PaymentIntent (a tax refusal expires the attempt, tax_calculation_failed, re-arming the policy, and nothing is charged; a transient Stripe error leaves it for the sweep) and records a Tax Transaction on success; credits are granted from the subtotal, never the tax. Refunds of a taxed auto-reload reverse its Tax Transaction. Ships dark until finance has the registrations; provision the tax codes first (provision_catalog.py --tax). Set it on the backend and the worker alike (the worker initiates auto-reloads). Refused at startup without HUITZO_LOT_OWNER_CAPTURE_ENABLED (the tax is recorded in the lot snapshot). Off: every Checkout kwarg and Stripe call is unchanged and no Tax API call is made.
HUITZO_MXN_PRESENTMENT_ENABLED ❌ false Charge Mexican top-ups in pesos (Credits: MXN presentment, ADR-041 Stripe Tax and MXN): when the tenant billing profile's country is MX, the top-up Checkout is created in mxn with the Spanish locale and the USD subtotal in its metadata, and settlement grants credits from that USD subtotal. Provision the peso prices first (provision_catalog.py --mxn). Counsel-gated (Mexico RFC/IVA route), so it ships dark. Backend only. Refused at startup without HUITZO_STRIPE_TAX_ENABLED (a peso charge carries IVA). Off: no peso session, and every Checkout kwarg is unchanged.
HUITZO_TEAM_LIFECYCLE_V2_ENABLED ❌ false The Team lifecycle v2 (Billing: Team lifecycle, ADR-041 D10): 15 days of grace, then suspended (allowance suspended, paid lots usable) and, 30 days later, read_only, where writes on the tenant get 402 tenant_read_only (billing, payment, auth and staff routes stay open) and the chokepoint refuses billable work; a Team downgrade is recorded as pending_plan_id and a cancellation as cancel_at_period_end, both applied at the period roll with no proration; a contract upgrade prorates the allowance; Team contract terms are month-to-month. Set it on the backend and the worker alike (the sweep and chokepoint run in the worker). Off: 14 days of grace, immediate contract plan changes, a required contract term, and no path reads read_only. Not paired with any other flag (ADR-041 E1).
HUITZO_TEAM_RENEWAL_NOTICE_ENABLED ❌ false The Team renewal notice and recurring-charge consent (Billing: renewal notice and consent, ADR-041 D10): the hourly Team sweep sends one notice 5 days before each renewal of an active Team plan, to the tenant's owners and admins and the billing contact, and Team provisioning records the consent (actor, time, terms version) on the plan row. Set it on the backend (provisioning) and the worker (the sweep) alike. Off: no query reads or writes either. Not paired with any other flag (ADR-041 E1).

D-024 flag ladder

The order to take a deployment from "every flag at its default" to the full D-024 model (ADR-041, ADR-042). Each flag's own row, in the tables above, says what it does; this section says what it needs, what refuses a wrong combination and when to turn it on. The staff procedures that go with the rungs are the Team onboarding runbook (Team plans) and the coupons and promotional budget runbook.

Four rules hold for every rung.

  1. Defaults. Every flag below defaults to false except HUITZO_PAYG_RATE_LIMIT_ENABLED and HUITZO_REQUIRE_SIGNUP_COUPON, which default to true. With every flag at its default no D-024 money path runs.
  2. Boot validators. The _validate_*_pairing validators on Settings (apps/backend/src/backend/config.py) refuse a wrong pairing: the process exits at configuration load, before it serves a request, and the error names both variables and the fix. A cell that says nothing refuses it means the deployment boots with the wrong combination and silently does less than the flag promises, so that prerequisite is checked by hand. Four more checks run when the backend starts (boot checks).
  3. Worker parity. Every flag carries the same value on the backend and the worker. The reference compose stack does this by construction (worker parity).
  4. Revert. Turn flags off in the reverse of the order below. A flag cannot go off while a flag that requires it is still on: the same validator refuses the boot. The exceptions are in revert rules.

0. Foundations

All of these predate D-024. The SaaS extension must be mounted: without it every flag in this ladder is inert. A backend whose license grants saas refuses to start when the extension is missing from the image or fails to mount (boot checks).

Order Flag Gates Requires Refused at boot by
0.1 HUITZO_PAYG_ENABLED Wallet registration, the wallet routes, top-up settlement, the signup seed HUITZO_STRIPE_SECRET_KEY, HUITZO_STRIPE_WEBHOOK_SECRET, HUITZO_FRONTEND_URL Nothing refuses it (it is the prerequisite of rungs 0.4 and 1.5)
0.2 HUITZO_ACCRUAL_ENABLED Exact sub-credit accounting — Nothing (it is the prerequisite)
0.3 HUITZO_LLM_PRICING_ENABLED LLM reservation and settlement HUITZO_ACCRUAL_ENABLED _validate_metering_v2_flag_pairing
0.4 HUITZO_SAAS_BILLING_ENABLED The tenant wallet: every chokepoint charges the acting tenant and fails closed (a hold, a 402 or a 503); the wallet routes act on the tenant account The SaaS extension; HUITZO_PAYG_ENABLED, or no tenant can read or top up its wallet; HUITZO_ACCRUAL_ENABLED and HUITZO_LLM_PRICING_ENABLED, or an LLM call never reserves at its exact cost _validate_saas_billing_pairing. Without the extension it is inert and logged once at startup
any HUITZO_PRICING_FROM_DB_ENABLED Prices read from price_versions — No pairing
any HUITZO_USAGE_TRACKING_ENABLED The Core execution_usage recorder, which the stuck-hold sweep and the admin usage pages read — No pairing. On with billing, or the backend logs a startup WARNING (boot checks)

HUITZO_PAYG_RATE_LIMIT_ENABLED stays at its default (true) through the whole ladder: the plan rate budgets apply (rate limiting).

Rung 0.4 charges every tenant from its first request. On a deployment that already has team tenants, fund each one first (a Team plan, the house plan or a grant: rung 2), or its members get 402.

1. Admission and promotions

Independent of billing; these may go on before or after rung 0.4. Coupons themselves have no flag: the staff, tenant and redeem routes are always on (ADR-042 D14).

Order Flag Gates Requires Refused at boot by
default HUITZO_REQUIRE_SIGNUP_COUPON Registration needs an account.create coupon — No pairing. Leave on outside dev and test
1.1 HUITZO_COUPON_CREDITS_ENABLED The credits.grant and plan.assign coupon capabilities HUITZO_SAAS_BILLING_ENABLED for the credits to be spendable; plan.assign also needs HUITZO_TEAM_LIFECYCLE_V2_ENABLED (a mint without it is 422) Nothing refuses it
1.2 HUITZO_PROMO_BUDGET_ENFORCED Over-cap promotional grants queue for staff instead of being written Staff who watch the Promo Grants queue Nothing refuses it. Off, promotional exposure is counted but unbounded
1.3 HUITZO_EMAIL_VERIFICATION_ENABLED The verify-email routes and the dashboard banner The SaaS extension; HUITZO_SENDGRID_API_KEY (without it each email is dead-lettered); HUITZO_FRONTEND_URL Nothing refuses it
1.4 HUITZO_SIGNUP_GRANT_ENABLED The eligibility stamp on new wallet accounts HUITZO_PAYG_ENABLED Nothing refuses it
1.5 HUITZO_SEED_ON_VERIFICATION The seed lands at first verification, through the promotional budget, instead of on the first wallet read HUITZO_SIGNUP_GRANT_ENABLED and HUITZO_PAYG_ENABLED; HUITZO_EMAIL_VERIFICATION_ENABLED for the email trigger (without it only a first settled top-up seeds) _validate_seed_on_verification_pairing for the signup grant and the PAYG wallet. Nothing refuses it without HUITZO_EMAIL_VERIFICATION_ENABLED (Credits: signup seed)

Turn 1.4 on before 1.5 and before the registrations that should be seeded: the stamp is written once, at account creation, and never backfilled. The lazy seed (1.5 off) does not draw on the promotional budget; the verified seed does.

2. House and Team plans

What funds a tenant other than its own purchases. Plan writers and period opens do not need billing on, so a tenant can be given its plan before rung 0.4 charges it.

Order Flag Gates Requires Refused at boot by
2.1 HUITZO_HOUSE_PLAN_ENABLED Staff provisioning of house; with rung 0.4, budget-only funding of house tenants — (not paired with billing: house may be provisioned first) No pairing
2.2 HUITZO_HOUSE_BUDGET_ALERT_ONLY_ENABLED A house tenant past 100% of budget keeps running HUITZO_HOUSE_PLAN_ENABLED. Leave off until the founder rules on FQ-2 _validate_house_budget_alert_only_pairing
2.3 HUITZO_TEAM_LIFECYCLE_V2_ENABLED 15-day grace, read_only, scheduled downgrade and cancel, month-to-month terms, coupon trials — No pairing
2.4 HUITZO_TEAM_RENEWAL_NOTICE_ENABLED The 5-day renewal notice and the consent record — No pairing
2.5 HUITZO_TEAM_INVOICE_RAIL_ENABLED The Team stripe_invoice rail HUITZO_SAAS_BILLING_ENABLED; the hz_team_*_monthly Prices; counsel sign-off _validate_team_invoice_rail_pairing

3. On the tenant wallet

Each of these lands or charges credits on the tenant account, which is spent only while billing is on, so each is refused at boot without rung 0.4.

Order Flag Gates Requires Refused at boot by
3.1 HUITZO_TEAM_USAGE_BLOCKS_ENABLED Staff-issued invoiced usage blocks HUITZO_SAAS_BILLING_ENABLED; the Stripe webhook subscribed to invoice.paid _validate_team_usage_blocks_pairing
3.2 HUITZO_TEAM_CARD_OVERFLOW_ENABLED Team owners and admins save a card and top up the tenant wallet HUITZO_SAAS_BILLING_ENABLED (and so HUITZO_PAYG_ENABLED: the card-setup route is 404 without it) _validate_team_card_overflow_pairing
3.3 HUITZO_PAYG_AUTO_RELOAD_ENABLED Auto-recharge on the tenant account. Money-moving HUITZO_SAAS_BILLING_ENABLED (and so HUITZO_PAYG_ENABLED: the reload-policy and auto-reload enable routes are 404 without it); for a Team tenant also 3.2 _validate_payg_auto_reload_pairing
3.4 HUITZO_PACK_PRICING_ENABLED Pack pricing versions, the pack.price charge and the records-only platform fee HUITZO_SAAS_BILLING_ENABLED _validate_pack_pricing_pairing

4. Compliance

None of these is paired with billing. The first three form a chain; the rest are independent of each other.

Order Flag Gates Requires Refused at boot by
4.1 HUITZO_LOT_OWNER_CAPTURE_ENABLED The owner and payment snapshot on every paid lot; a billing address at top-up Checkout — No pairing. Off, the backend refuses to start once the owner-snapshot cutover is less than 30 days away (boot checks)
4.2 HUITZO_STRIPE_TAX_ENABLED Tax collected on top through Stripe Tax HUITZO_LOT_OWNER_CAPTURE_ENABLED; the tax codes (provision_catalog.py --tax); finance's registrations _validate_stripe_tax_pairing
4.3 HUITZO_MXN_PRESENTMENT_ENABLED Peso top-ups for tenants billed in Mexico HUITZO_STRIPE_TAX_ENABLED; the peso prices (provision_catalog.py --mxn); counsel sign-off _validate_mxn_presentment_pairing
any HUITZO_PAID_BALANCE_CAP_ENABLED The paid-balance cap, HUITZO_PAID_BALANCE_CAP_CREDITS (19,000 credits) Counsel sign-off No pairing
any HUITZO_LOT_EXPIRY_SWEEP_ENABLED The hourly expiry sweep in the worker — No pairing
any HUITZO_CREDIT_EXPIRY_REMINDERS_ENABLED The 30-day and 7-day expiry notices HUITZO_SENDGRID_API_KEY No pairing
any HUITZO_WALLET_ALERTS_ENABLED Balance and Team allowance alerts, emailed HUITZO_SENDGRID_API_KEY No pairing
any HUITZO_DISPUTE_CLAWBACK_ENABLED Chargeback clawback and the account freeze The Stripe webhook subscribed to charge.dispute.created and charge.dispute.closed No pairing
any HUITZO_PAYG_REFUNDS_ENABLED The staff 30-day refund and the refund mirror Terms that allow refunds; the Stripe webhook subscribed to refund.created and charge.refunded; for the staff route, lots sold with 4.1 on Nothing refuses it without HUITZO_LOT_OWNER_CAPTURE_ENABLED (lots sold earlier already lack the snapshot): the backend logs a startup WARNING, and the staff route answers 409 lot_not_refundable for every lot sold while capture was off (boot checks)

Turn 4.1 on before the first top-up that may ever need a staff refund. The snapshot is insert-only: a lot sold while capture was off never gains one (known states).

Worker parity

The worker loads the same Settings class as the backend, runs the same validators at boot, and does billing work of its own: it executes queued commands and pipelines through the same chokepoint, settles their charges, and runs the sweeps (lot expiry, expiry reminders, wallet alerts, auto-recharge, the Team lifecycle and renewal notices). A flag set on the backend only gives two different platforms depending on which process handles the work: an inline command charged one way and the same command on a queue charged another.

The rule: every flag in this ladder, and every flag in Metering v2, billing isolation and PAYG wallet, carries the same value on the backend and on every worker. A flag that only a route reads is harmless on the worker; a flag missing from the worker is not.

Settings reads the container's environment, never .env itself.

The compose settings rule

In the reference stack (deploy/compose/docker-compose.yml, and the worker pools of docker-compose.compute.yml) the backend and every worker receive their application settings from the same two places and from nowhere else:

Source Carries Maintained by
app.env, loaded by both services as their env_file Every HUITZO_* application setting of deploy/compose/.env, verbatim deploy/scripts/render-app-env.sh, which deploy.sh runs before its first compose command
The shared x-app-environment map The few settings a stack with no .env needs a compose-level default for (database and Redis URLs, the boot secrets, debug, log level, the license path) The compose file

So a setting is one line in .env, and it reaches both processes or neither. No variable is named per service, and no compose edit is needed for a new flag. apps/backend/tests/test_compose_app_env_parity.py fails the build when a Settings field is passed to one service and not the other, in the base file or an overlay.

What an operator needs to know:

  • app.env is required. Without it docker compose refuses the project instead of starting both services on code defaults. deploy.sh renders it on every deploy and deploy/systemd/huitzo-stack.service on every start and reload (bootstrap-vm.sh installs the script beside the compose file); after editing .env and restarting by hand, run deploy/scripts/render-app-env.sh first. Local development with no .env renders an empty file.
  • Only application settings are copied. Lines without the HUITZO_ prefix (the Grafana password, the unprefixed Celery and Redis URLs) stay out of the application containers, and so do the five prefixed names that configure the stack around the application rather than the application: the database and Redis container passwords, the nginx config name, the install directory and the host path of the license file (the INFRA_ONLY list in render-app-env.sh; none is a Settings field, and a test holds the list to that). Compose still reads all of them from .env for its own interpolation.
  • A quoted value may carry a trailing comment, as compose allows: KEY="value" # note.
  • .env must be plain KEY=VALUE lines. The render refuses export, leading spaces, spaces around =, a quoted value spanning lines and CRLF line endings, names the line, and leaves the previous app.env in place.
  • A blank value is passed as blank. HUITZO_PAYG_ENABLED= is not "unset": for a boolean it fails validation at load. Delete the line to get the default.
  • A variable exported in the shell is not a setting. Only .env is rendered; the shell reaches a container only through the few names in the shared map.

To see what a process received: docker compose exec backend env against docker compose exec worker env, filtered for HUITZO_. A deployment that writes its own compose file follows the same rule: one env_file for both services.

Boot checks

Five checks need more than Settings, or only warn, and run when the backend starts (apps/backend/src/backend/main.py, apps/backend/src/backend/boot_guards.py). The worker builds Settings only, so it runs the pairing validators and none of these.

Check When it fires Result
SaaS surface mounted The license grants saas and the SaaS extension is missing from the image, or its configure, validate, on_enable or mount step raised (an import error in one router is enough) Startup fails. A core-only license is never checked, and any other extension that fails is still only excluded and logged
Owner-snapshot cutover HUITZO_LOT_OWNER_CAPTURE_ENABLED is off and the database's credit_lot_owner_snapshot_cutover() has passed or is less than 30 days away Startup fails. From the cutover the database refuses a purchase lot without an owner snapshot (saas_0023), and settlement stamps one only while capture is on, so a top-up or auto-recharge would charge the card and grant no credits
Refunds without capture HUITZO_PAYG_REFUNDS_ENABLED is on and HUITZO_LOT_OWNER_CAPTURE_ENABLED is off WARNING at startup, the backend starts. Every lot sold while capture is off can never be refunded through the staff route (409 lot_not_refundable, reason snapshot_incomplete); the snapshot is insert-only
Billing without usage tracking HUITZO_SAAS_BILLING_ENABLED is on and HUITZO_USAGE_TRACKING_ENABLED is off WARNING at startup, the backend starts. The two flags stay independent (ADR-043 DR-24d), but a charge whose settlement fails cannot be recovered by the stuck-hold sweep and stays reserved
Managed runners without usage tracking HUITZO_MANAGED_RUNNERS_ENABLED is on and HUITZO_USAGE_TRACKING_ENABLED is off WARNING at startup, the backend starts. A managed checkout's gateway calls and compute seconds are written only by the Core usage recorder, so it meters nothing and its usage reads as zero, the staff build-spend report answers usage_tracking: false, and the per-build measured-cost histogram observes nothing (managed runners staging runbook, build spend)

The cutover is a far-future sentinel today (9999-12-31), so the second check passes on every current deployment. It issues no query while capture is on, and none on a database without the function (a core-only deployment). With capture off, a failed read of the cutover fails startup too: a backend that cannot tell whether its top-ups will be refused does not serve them. A release that moves the cutover to a real instant therefore needs capture on, on the backend and the worker, at least 30 days before it.

Revert rules

Every flag is reverted by turning it off, in reverse ladder order. The wallet model itself is not a flag: turning billing off stops every charge and every refusal, and the only way back to the personal-wallet model is the release that still had it (migration plan §6). The exceptions and the orderings the validators force:

Flag Revert rule
HUITZO_SAAS_BILLING_ENABLED First turn off every flag that requires it (usage blocks, card overflow, auto-recharge, pack pricing, the Team invoice rail), or the boot is refused. Off, every execution runs unreserved and uncharged; balances, lots and holds are kept
HUITZO_HOUSE_PLAN_ENABLED Only after billing is off, or house tenants get 402
HUITZO_LLM_PRICING_ENABLED Only after HUITZO_SAAS_BILLING_ENABLED is off, or the boot is refused
HUITZO_ACCRUAL_ENABLED Only after HUITZO_LLM_PRICING_ENABLED is off. Accrued remainders are kept, not lost
HUITZO_PAYG_ENABLED Only after HUITZO_SAAS_BILLING_ENABLED and HUITZO_SEED_ON_VERIFICATION are off, or the boot is refused
HUITZO_SIGNUP_GRANT_ENABLED Only after HUITZO_SEED_ON_VERIFICATION is off, or the boot is refused. Accounts already stamped eligible then get the lazy seed on their next wallet read
HUITZO_LOT_OWNER_CAPTURE_ENABLED Only after HUITZO_STRIPE_TAX_ENABLED is off, which needs HUITZO_MXN_PRESENTMENT_ENABLED off first. Lots sold while it is off cannot be refunded through the staff route
HUITZO_SEED_ON_VERIFICATION Off restores the lazy seed. An account stamped eligible keeps its eligibility once
HUITZO_PROMO_BUDGET_ENFORCED Off stops queueing. Requests already queued stay in the Promo Grants queue and can still be approved or rejected
HUITZO_PAYG_AUTO_RELOAD_ENABLED Off is safe: the sweep drains open attempts with no provider call. An attempt already in flight at Stripe is reaped as unresolved after an hour and disarms that wallet's auto-recharge
HUITZO_TEAM_LIFECYCLE_V2_ENABLED Scheduled downgrades, scheduled cancellations, read_only and coupon trials are read and applied only while it is on. Settle those rows before turning it off
HUITZO_COUPON_CREDITS_ENABLED Off makes existing credits.grant and plan.assign coupons unredeemable (the uniform coupon_invalid); lots already granted stay

Coupons have no flag to revert: the coupon routes have been unconditional since the access-code fold (D-024 CR78, ADR-042 D14), and the invite and access-code folds are not reversible.

Studio

Studio-specific backend settings (apps/backend/src/backend/config.py). This table is a shared landing spot for Studio env vars — add a new block rather than folding rows into an unrelated table.

Dashboard create-from-intent + plan re-execution:

Variable Required Default Description
HUITZO_STUDIO_DEFAULT_COMMAND_ALLOWLIST ❌ [] (JSON list) Default command_allowlist (exact argv[0] strings, typically absolute binary paths) bound into the signed scope of a dashboard intent-only build (POST /builds with only {"prompt": "..."}) that supplies no explicit allowlist. Empty ⇒ default-deny: an intent-only build cannot run any stage until an operator sets this to the runner box's tool paths.
HUITZO_STUDIO_DEFAULT_REPO_URL ❌ scaffold:studio-workspace Default repo_url bound as the repo handle of a dashboard intent-only build that supplies no repo. The default is an opaque, host-less scaffold sentinel — it contributes no host to the signed egress allowlist, so the egress set stays the strict default (model API + registries only). An explicit API caller still passes its own repo_url.
HUITZO_STUDIO_SPEC_JOB_BUDGET_S ❌ 600 Wall-clock budget in seconds for one async SPECIFY job (worker.tasks.spec_job), threaded into spec_service.draft_spec as budget_s and replacing the interactive SPECIFY policy's own latency ceilings for cloud-routed calls (SD11-fix1; a local/Ollama-routed SPECIFY profile is governed by settings.local_ai.timeout instead). Exceeding it fails the job with a user-facing timeout message; the job is never left pending/running forever.
HUITZO_STUDIO_PLAN_EXECUTE_ATTEMPT_CAP ❌ 3 Max total executions per approved plan (T17): the approve dispatch plus every POST /plans/{id}/execute re-execution. At the cap the route answers 429 (attempt_cap). Must be >= 1 — 1 disables explicit re-execution entirely (the approve is the only execution).

Huitzo-managed runners

Settings of Huitzo-managed Studio runners. The feature flag is off by default and the pool, image and gateway-model settings are empty; the remaining settings have working defaults. With HUITZO_MANAGED_RUNNERS_ENABLED off nothing in this table has any effect. The deployment offers managed runners only when the capability block says enabled: true: the flag, the runner channel, a fully configured default pool and a pinned image.

Variable Default Description
HUITZO_MANAGED_RUNNERS_ENABLED false The feature flag. Off: no route, no dispatch fallback, capability enabled: false.
HUITZO_MANAGED_RUNNER_DEFAULT_POOL empty The pool new checkouts queue on. Lower-case letters, digits and -, starting with a letter or digit, at most 64 characters.
HUITZO_MANAGED_RUNNER_POOL_TOKENS {} (JSON object) Pool name to the sha256 hex (64 lower-case characters) of that pool's bearer token. The plaintext token stays on the pool host. Keys follow the pool-name rule above, and two pools may not share a digest; a bad key, a bad digest or a duplicate fails settings validation at boot.
HUITZO_MANAGED_RUNNER_POOL_RUNTIMES {} (JSON object) Pool name to its required container runtime, runc or runsc. Keys follow the pool-name rule above; anything else fails settings validation at boot. A pool with no entry never promotes a checkout.
HUITZO_MANAGED_RUNNER_POOL_CAPACITY 3 Slots per pool, an integer from 1 to 256 (anything else fails at settings load). The effective capacity is the smaller of this and the pool agent's reported usable slots.
HUITZO_MANAGED_RUNNER_TENANT_CONCURRENCY 1 Live checkouts per tenant.
HUITZO_MANAGED_RUNNER_QUEUE_EXPIRY_SECONDS 1800 Capacity wait after which a queued checkout expires.
HUITZO_MANAGED_RUNNER_JOB_TTL_SECONDS 28800 Lifetime of the envelope signed at promotion: the job's lease limit.
HUITZO_MANAGED_RUNNER_SECRET_TTL_SECONDS 300 Window in which the pool agent must fetch a checkout's one-time secret.
HUITZO_MANAGED_RUNNER_API_URL empty The Hub URL containers dial; also the gateway's base URL and an egress allowlist entry.
HUITZO_MANAGED_RUNNER_IMAGE_DIGEST empty sha256:<64 hex> of the runner image the pool runs.
HUITZO_MANAGED_RUNNER_IMAGE_CLI_VERSION empty The CLI version in that image. Must read as a release, major.minor[.patch], at or above HUITZO_RUNNER_MIN_SECURE_VERSION; anything else halts the pool (halted_below_floor). Also feeds the change-build gate: a Studio change build runs on Huitzo only when this is at least 0.23.1 (studio-artifact-model).
HUITZO_MANAGED_RUNNER_IMAGE_SDK_VERSION empty The SDK version in that image; feeds the stage, resume and base_snapshot gates of a managed dispatch.
HUITZO_MANAGED_RUNNER_IMAGE_CHANNEL_VERSION empty The runner-channel protocol version (major.minor) the CLI in that image speaks. The Hub serves the image only when it negotiates against the Hub's minimum channel version and is not denied by the S69 secure-version floor or a revoked range; otherwise the pool halts (halted_below_floor). Required for the capability.
HUITZO_MANAGED_RUNNER_EGRESS_ALLOWLIST the default list (JSON list) Exact host names containers may reach through the egress proxy. The host of HUITZO_MANAGED_RUNNER_API_URL is always added.
HUITZO_MANAGED_RUNNER_EGRESS_REQUIRED_HOSTS ["pypi.org", "files.pythonhosted.org", "registry.npmjs.org"] (JSON list) Exact, lower-case host names a job whose signed egress list is not empty still reaches, when the egress allowlist also has them (per-job allowlist). An entry with a scheme, port, path or wildcard refuses startup.
HUITZO_LLM_GATEWAY_UPSTREAM_URL https://api.anthropic.com The model provider the gateway forwards to.
HUITZO_LLM_GATEWAY_MODEL_ALLOWLIST [] (JSON list) Model ids the gateway serves. Empty serves none.
HUITZO_LLM_GATEWAY_BETA_ALLOWLIST [] (JSON list) anthropic-beta values the gateway forwards.
HUITZO_LLM_GATEWAY_SERVER_TOOL_ALLOWLIST ["web_search"] (JSON list) Provider server tool families forwarded: a tool type matches its family, or the family plus _ and digits (web_search_20250305).
HUITZO_LLM_GATEWAY_MAX_BODY_BYTES 4194304 Gateway request body cap (4 MiB).
HUITZO_LLM_GATEWAY_REQUEST_TIMEOUT_SECONDS 600 Per-call deadline of a gateway call.
HUITZO_STUDIO_PROJECT_STORE_BACKEND local The project store backend: local or s3 (any S3 API).
HUITZO_STUDIO_PROJECT_STORE_PATH /app/data/studio-projects Root directory of the local backend. Must be a persistent volume.
HUITZO_STUDIO_PROJECT_STORE_S3_ENDPOINT_URL empty The s3 backend's endpoint. Required with s3: the Hub refuses to start without it.
HUITZO_STUDIO_PROJECT_STORE_S3_REGION auto Signing region.
HUITZO_STUDIO_PROJECT_STORE_S3_BUCKET empty The bucket. Required with s3. Give it a lifecycle rule that aborts incomplete multipart uploads.
HUITZO_STUDIO_PROJECT_STORE_S3_ACCESS_KEY_ID empty Required with s3.
HUITZO_STUDIO_PROJECT_STORE_S3_SECRET_ACCESS_KEY empty Required with s3. Secret.
HUITZO_STUDIO_PROJECT_STORE_S3_PREFIX empty Key prefix inside the bucket.
HUITZO_STUDIO_PROJECT_STORE_S3_ADDRESSING_STYLE path path or virtual.
HUITZO_STUDIO_PROJECT_STORE_S3_SSE empty Sent as ServerSideEncryption on every write when set (e.g. AES256); otherwise the bucket's default encryption applies.
HUITZO_STUDIO_PROJECT_SNAPSHOT_MAX_BYTES 209715200 Cap on a snapshot's source archive.

There is no gateway token lifetime setting: a token lives as long as its job's lease.

Database backups

Hub-managed database backups (admin console §5.11). The backend holds only the control-plane key, the download-ticket key and the download switch; everything else belongs to the backup sidecar, which reads its own environment (§5.11.9) and never Settings. A staff session can change none of these.

Backend (apps/backend/src/backend/config.py):

Variable Required Default Description
HUITZO_BACKUP_DOWNLOAD_ENABLED ❌ false when HUITZO_DEPLOYMENT_MODE=cloud, otherwise true Whether /admin/backups/{id}/download-ticket may issue tickets at all. Also set on the sidecar, which re-checks it before streaming. No database row can enable it. The sidecar fails closed when neither this nor HUITZO_DEPLOYMENT_MODE is set (§5.11.9)
HUITZO_BACKUP_CTL_HMAC_KEY ❌ - 32 random bytes, base64. Authenticates every backend → sidecar request and keys the stream tickets. Without it the routes that call the sidecar (list, request, status, verify, delete, download-ticket, and the download GET) answer 503 backup_service_unavailable; the settings routes still work
HUITZO_BACKUP_CTL_URL ❌ http://backup:8081 Where the backend reaches the sidecar on the backup-ctl network
HUITZO_BACKUP_TICKET_KEY ❌ - MAC key (at least 32 characters) of the download-ticket entries in Redis. Backend only, never the worker. Without it no ticket is issued (503)

Sidecar (apps/backend/src/backend/backups/config.py): HUITZO_BACKUP_DOWNLOAD_ENABLED, HUITZO_BACKUP_CTL_HMAC_KEY, HUITZO_BACKUP_CTL_LISTEN, HUITZO_BACKUP_DATABASE_URL, HUITZO_BACKUP_AUDIT_DATABASE_URL, HUITZO_BACKUP_AGE_RECIPIENTS, HUITZO_BACKUP_RETENTION_MIN_SCHEDULED, HUITZO_BACKUP_RETENTION_MIN_DAILY, HUITZO_BACKUP_RETENTION_MIN_PREDEPLOY, HUITZO_BACKUP_TRUSTED_SIGNERS, HUITZO_BACKUP_DIR, HUITZO_BACKUP_KEYS_DIR, HUITZO_BACKUP_PGDATA_PROBE and HUITZO_BACKUP_METRICS_TEXTFILE, each described in §5.11.9.


SDK Configuration

Per-Command Configuration

Commands can be configured via decorator parameters:

from huitzo_sdk import command

@command(
    name="my-command",
    namespace="mypack",
    version="1.0.0",
    timeout=60,           # Seconds
    retries=3,            # Retry attempts
    queue="medium",       # fast | medium | long
    output_format="json", # json | text | markdown
)
async def my_command(args, ctx):
    pass

Environment Variables (SDK)

The SDK (huitzo_sdk) reads only these HUITZO_* variables:

Variable Default Description
HUITZO_DEMO_MODE off Enables fixture-backed demo clients (refused when HUITZO_ENV=production)
HUITZO_DEMO_FIXTURES_DIR - Fixture directory used with demo mode
HUITZO_ENV - production makes demo mode and the local secrets fallback refuse to start

Secrets resolved by the local secrets backend come from HUITZO_SECRET_<NAME> variables. The SDK has no configuration file.


CLI Configuration

The CLI merges three sources, with the following precedence (highest to lowest):

  1. Environment variables (HUITZO_API_URL, HUITZO_DEV_PORT)
  2. User config (~/.config/huitzo/config.yaml; $XDG_CONFIG_HOME/huitzo/config.yaml when set; %APPDATA%\huitzo\config.yaml on Windows)
  3. Project config (huitzo.yaml in the project root)
  4. Defaults (api_url is https://huitzo.ai)

Project Configuration (huitzo.yaml)

huitzo.yaml in the pack root is also the pack manifest. The CLI reads these keys from it:

# huitzo.yaml
api_url: https://huitzo.acme-internal.com   # API endpoint (self-hosted)

dev:
  port: 8080              # Local proxy port
  verbose: false
  auto_reload: true
  persist_sandbox: false  # Keep sandbox after Ctrl+C

auth:
  token_file: /path/to/token   # optional

Auth tokens are never stored in config files: huitzo login writes ~/.huitzo/token and HUITZO_AUTH_TOKEN overrides it. There is no OIDC or SAML configuration.

User Configuration (~/.config/huitzo/config.yaml)

The same keys (api_url, auth, dev, telemetry) apply user-wide. Manage them with huitzo config.

# ~/.config/huitzo/config.yaml
api_url: https://huitzo.ai
dev:
  port: 9000

Environment Variables (CLI)

Variable Default Description
HUITZO_API_URL https://huitzo.ai API endpoint
HUITZO_AUTH_TOKEN - Authentication token (not persisted)
HUITZO_DEV_PORT 8080 Local dev proxy port

Self-Hosted Configuration

For self-hosted/enterprise deployments, point the CLI at your instance with --url or HUITZO_API_URL:

export HUITZO_API_URL=https://huitzo.acme-internal.com
huitzo login

huitzo login takes --url, --email and --tenant only. Enterprise SSO (OIDC/SAML) is not built yet.

Configuration Precedence Example

Given these configurations:

# ~/.config/huitzo/config.yaml (user)
api_url: https://huitzo.ai
dev:
  port: 9000

# huitzo.yaml (project)
api_url: https://huitzo.acme.com
dev:
  persist_sandbox: true

And environment:

export HUITZO_DEV_PORT=7000

The effective configuration would be: - api_url: https://huitzo.ai (user config beats project config) - dev.port: 7000 (from environment) - dev.persist_sandbox: true (from project; sections merge key by key)


Database Configuration

PostgreSQL

Connection string format:

postgresql://user:password@host:port/database

Example:

HUITZO_DATABASE_URL=postgresql+asyncpg://huitzo_app:password@localhost:5432/huitzo

The runtime role must be NOSUPERUSER NOBYPASSRLS; migrations use the owner role through HUITZO_DATABASE_ADMIN_URL (boot guard).

Connection Pool Settings

Variable Default Description
DATABASE_POOL_SIZE 5 Connection pool size
DATABASE_MAX_OVERFLOW 10 Max overflow connections
DATABASE_POOL_TIMEOUT 30 Pool timeout (seconds)
DATABASE_POOL_RECYCLE 1800 Recycle connections (seconds)

Row-Level Security

RLS is automatically enabled. Tenant isolation is enforced via:

-- Automatic policy on all tables with tenant_id
CREATE POLICY tenant_isolation ON tablename
    USING (tenant_id = current_setting('app.current_tenant')::uuid);

Redis Configuration

Connection string format:

redis://[:password@]host:port/db

Examples:

# Local, no password
HUITZO_REDIS_URL=redis://localhost:6379/0

# With password
HUITZO_REDIS_URL=redis://:mypassword@localhost:6379/0

# TLS
HUITZO_REDIS_URL=rediss://user:pass@host:6379/0

Celery additionally reads an unprefixed REDIS_URL (plus CELERY_BROKER_URL / CELERY_RESULT_BACKEND) — see Task Queue (Celery). Worker deployments set both.

Redis Settings

Variable Default Description
REDIS_MAX_CONNECTIONS 10 Max connection pool size
REDIS_SOCKET_TIMEOUT 5 Socket timeout (seconds)
REDIS_RETRY_ON_TIMEOUT true Retry on timeout

Database Migrations

Huitzo uses Alembic for database schema migrations. Migrations track changes to PostgreSQL schema over time and allow safe upgrades and rollbacks.

Migration Commands

Migrations run with Alembic from the backend image. On a customer install the one-shot migrate service runs them (Operations):

# pseudocode: from the install directory (/opt/huitzo)
docker compose run --rm migrate                              # apply pending migrations
docker compose run --rm migrate python -m alembic current    # current revision
docker compose run --rm migrate python -m alembic history    # migration history

In a development checkout, run uv run alembic upgrade head (or current, history, revision --autogenerate -m "...") from apps/backend. Migrations only move forward on a customer install: going back to an older release means restoring a backup (Upgrade).

Migration File Structure

Migrations are stored in backend/migrations/versions/:

backend/
├── migrations/
│   ├── env.py              # Alembic environment config
│   ├── script.py.mako      # Migration template
│   └── versions/
│       ├── 001_initial_schema.py
│       ├── 002_add_pack_registry.py
│       └── 003_add_user_preferences.py

Example Migration

# migrations/versions/003_add_user_preferences.py
"""Add user preferences table

Revision ID: 003_preferences
Revises: 002_pack_registry
Create Date: 2026-01-22 10:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import JSONB

revision = '003_preferences'
down_revision = '002_pack_registry'

def upgrade():
    op.create_table(
        'user_preferences',
        sa.Column('id', sa.UUID(), primary_key=True),
        sa.Column('user_id', sa.UUID(), sa.ForeignKey('users.id'), nullable=False),
        sa.Column('tenant_id', sa.UUID(), sa.ForeignKey('tenants.id'), nullable=False),
        sa.Column('preferences', JSONB, nullable=False, server_default='{}'),
        sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.func.now()),
        sa.Column('updated_at', sa.DateTime(timezone=True), onupdate=sa.func.now()),
    )
    op.create_index('ix_user_preferences_user_id', 'user_preferences', ['user_id'])

    # Enable RLS
    op.execute('ALTER TABLE user_preferences ENABLE ROW LEVEL SECURITY')
    op.execute('''
        CREATE POLICY tenant_isolation ON user_preferences
        USING (tenant_id = current_setting('app.tenant_id')::uuid)
    ''')

def downgrade():
    op.drop_table('user_preferences')

Independent per-chain baselines (ADR-023)

The migration history is collapsed into one baseline per chain (the pre-alpha migration-baseline squash, ADR-023). Each chain is an independent alembic upgrade head with its own version table in the same database:

Chain Version table Baseline Applied by
core alembic_version 0001 alembic upgrade head
saas alembic_version_saas saas_0001 python -m huitzo_ext_saas.migrate upgrade head

The deploy applies core first, then the saas chain only when the deployed, signature-verified license grants saas (ADR-023 D5). A license without saas runs the core chain only — the database has no SaaS tables.

Version Tracking

Migration state is stored in the per-chain version tables:

-- Core chain
SELECT version_num FROM alembic_version;
-- version_num
-- 0001

-- SaaS chain (only present when the license grants saas)
SELECT version_num FROM alembic_version_saas;
-- version_num
-- saas_0001

Self-Hosted Migrations

On a customer install, install.sh runs the migrate service on every install and upgrade, before the application services start. In the stack built from the repository, migrations run during a deploy (via deploy/scripts/deploy.sh, which is license-aware — it runs the saas chain only when the license grants saas; see the deploy script migration policy):

# pseudocode — docker-compose.yml (conceptual; deploy/scripts/deploy.sh is canonical)
services:
  migrate:
    image: <huitzo-backend-image>:<version>
    # Core chain ALWAYS; SaaS chain ONLY when the deployed license grants `saas`
    # (a signature-verified check). A core-only license runs core and stops.
    command:
      - sh
      - -ec
      - |
        alembic upgrade head                                  # core chain (always)
        if python -m backend.licensing.grants saas; then      # exit 0 = granted
          python -m huitzo_ext_saas.migrate upgrade head      # saas chain (gated)
        fi

To run the core chain manually in the source-built stack:

# pseudocode
docker compose exec backend alembic upgrade head

Migration Best Practices

  1. Always create reversible migrations - Include both upgrade() and downgrade()
  2. Test migrations on a copy - Never run untested migrations on production
  3. Back up before migrating - pg_dump before any upgrade
  4. Keep migrations small - One logical change per migration
  5. Use transactions - Alembic wraps migrations in transactions by default

Logging Configuration

Log Levels

Level Description
DEBUG Detailed debugging information
INFO General operational information
WARNING Warning messages
ERROR Error messages
CRITICAL Critical errors

Log Format

Logs are structured JSON by default:

{
  "timestamp": "2026-01-22T12:00:00Z",
  "level": "INFO",
  "logger": "webcli.api",
  "message": "Request completed",
  "correlation_id": "abc-123",
  "duration_ms": 45
}

Configuration

HUITZO_LOG_LEVEL=INFO         # DEBUG | INFO | WARNING | ERROR | CRITICAL
HUITZO_LOG_FORMAT=json        # json | text
HUITZO_LOG_OUTPUT=stdout      # stdout | file
HUITZO_LOG_FILE_PATH=/var/log/huitzo/app.log

Security Configuration

Secret Key Generation

Generate a secure secret key:

# Python
python -c "import secrets; print(secrets.token_urlsafe(32))"

# OpenSSL
openssl rand -base64 32

HTTPS/TLS

For production, always use HTTPS. Configure via reverse proxy (nginx):

server {
    listen 443 ssl;
    server_name huitzo.ai;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    location / {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

Rate Limiting

Variable Default Description
HUITZO_RATE_LIMIT_ENABLED true Kill switch for every rate limit (fixed windows and token buckets), including the fail-closed registration limits. Concurrency leases that bound resource use stay on (shared limits)
HUITZO_LOGIN_IP_RATE_LIMIT_PER_MINUTE 5 Max login attempts per client IP per 60s window before 429. Fails closed: a Redis outage answers 503
HUITZO_RUNNER_CHANNEL_RATE_CAPACITY 10 Burst of the runner channel's per-tenant token bucket (claim, poll-job, heartbeat, status, publish-upload), shared by every Hub process. During a Redis outage each process spends from its own bucket of the same size (shared limits)
HUITZO_RUNNER_CHANNEL_RATE_REFILL_PER_SECOND 1.0 Tokens per second that bucket refills
HUITZO_PUBLISH_TENANT_RATE_PER_HOUR 30 Publishes (pack create, version upload, Studio build publish) one tenant may make per hour, as a burst refilling evenly over the hour. Past it, 429 publish_rate_limited with Retry-After. Fails closed: a Redis outage answers 503 (publish limits)
HUITZO_PUBLISH_USER_RATE_PER_HOUR 20 The same, per user. Fails closed
HUITZO_REGISTER_IP_RATE_LIMIT_PER_MINUTE 5 Max POST /api/v1/auth/register calls per client IP per 60s window before 429. Raise it for the staging E2E runner
HUITZO_REGISTER_HOURLY_CAP 100 Max successful registrations platform-wide per hour bucket before register returns 503
HUITZO_COUPON_REDEEM_IP_RATE_LIMIT_PER_MINUTE 5 Max POST /api/v1/coupons/redeem calls per client IP per 60s window before 429 (ADR-042 D9). Fails closed: a Redis outage answers 503
HUITZO_COUPON_REDEEM_USER_RATE_LIMIT_PER_HOUR 10 Max coupon redeem calls per signed-in user per hour bucket before 429. Fails closed
HUITZO_COUPON_REDEEM_HOURLY_CAP 200 Max successful coupon redemptions platform-wide per hour bucket before redeem returns 503 coupon_redeem_at_capacity. Fails closed
HUITZO_TRUSTED_PROXY_CIDRS ["127.0.0.0/8","10.0.0.0/8","172.16.0.0/12","192.168.0.0/16","::1/128","fc00::/7"] JSON list of CIDRs whose X-Real-IP names the client for rate limiting. The default (loopback, RFC 1918, IPv6 ULA) covers nginx on a Docker bridge. An explicit [] keys every limit on the transport peer, which buckets every client behind a proxy together. When the backend :8000 is reachable beyond the host, narrow it to nginx's address. See the trusted-proxy contract
HUITZO_EDGE_TRUSTED_PROXIES empty Read by the dashboard container, not the backend. Comma-separated IP addresses or CIDRs of the HTTPS proxies in front of the dashboard; nginx restores the client from their X-Forwarded-For and sends it as X-Real-IP, and passes their X-Forwarded-Proto. Empty trusts nothing (X-Real-IP is the TCP peer). A malformed entry, a hostname, or a prefix wider than /8 (IPv4) or /16 (IPv6), such as 0.0.0.0/0 or ::/0, stops the container at start. The customer compose's https profile sets Caddy's fixed address (one hop). See client IP behind an HTTPS proxy
HUITZO_NETWORK_SUBNET, HUITZO_NETWORK_DYNAMIC_RANGE, HUITZO_CADDY_ADDRESS 172.16.231.0/24, 172.16.231.128/25, 172.16.231.10 Customer compose only: the huitzo-network subnet, the range Docker assigns from, and Caddy's fixed address outside it, which install.sh writes to HUITZO_EDGE_TRUSTED_PROXIES. If the subnet collides with a network the host reaches, run install.sh --no-up, change them together in .env, then run it again; keep a private range (install.sh stops on an inconsistent set). See connected install
HUITZO_TRUSTED_PROXY_HOSTS ["127.0.0.1"] Proxies trusted for X-Forwarded-Proto/-For scheme and host resolution only; never the rate-limit key

The registration limits fail closed: a Redis outage makes POST /api/v1/auth/register answer 503 (ADR-042 D9). So do login, password change (signed in and from the login screen), forgot and reset, reauth, and publish. Every limit is held in Redis and shared by all backend processes; the outage policy of each is in shared limits.

Feedback extension

Read only where huitzo-ext-feedback is mounted (spec); harmless and unused elsewhere.

Variable Default Description
HUITZO_FEEDBACK_INBOX (empty) Platform-staff feedback inbox address(es), comma-separated. Empty falls back to HUITZO_PLATFORM_STAFF_EMAILS; with both empty, staff notification is skipped (the admin console remains the record)
HUITZO_FEEDBACK_IP_RATE_LIMIT_PER_MINUTE 5 Max feedback submissions per client IP per 60s window before 429
HUITZO_FEEDBACK_USER_RATE_LIMIT_PER_HOUR 10 Max feedback submissions per user per rolling hour before 429

Feature Flags

Variable Default Description
FEATURE_DASHBOARD true Enable dashboard support
FEATURE_WEBSOCKET true Enable WebSocket connections
FEATURE_FILE_UPLOAD true Enable file uploads
FEATURE_LLM true Enable LLM service
FEATURE_EMAIL true Enable email service
FEATURE_TELEGRAM false Enable Telegram integration

Example Configuration

Development .env

# Core (huitzo_app is created without a password: set it once after the
# migrations, deploy/compose/README.md step 5)
HUITZO_DATABASE_URL=postgresql+asyncpg://huitzo_app:password@localhost:5432/huitzo
# Local development only: one shell runs both alembic and the app. The customer
# bundle sets the admin URL on its migrate service alone.
HUITZO_DATABASE_ADMIN_URL=postgresql+asyncpg://huitzo:password@localhost:5432/huitzo
HUITZO_REDIS_URL=redis://localhost:6379/0
HUITZO_JWT_SECRET_KEY=dev-secret-key-change-in-production

# Environment
HUITZO_DEBUG=true
HUITZO_LOG_LEVEL=DEBUG

# Celery
CELERY_TASK_ALWAYS_EAGER=true

Production .env

# Core
HUITZO_DATABASE_URL=postgresql+asyncpg://huitzo_app:[email protected]:5432/huitzo
# HUITZO_DATABASE_ADMIN_URL goes in the migration process's environment only,
# never in the file the backend, worker and beat read
HUITZO_REDIS_URL=redis://:[email protected]:6379/0
HUITZO_JWT_SECRET_KEY=production-secret-key-64-chars-minimum-random
HUITZO_AUDIT_PEPPER=production-audit-pepper-32-chars-minimum-random
HUITZO_SECRETS_ENCRYPTION_KEY=<64-char-hex>

# Environment
HUITZO_DEBUG=false
HUITZO_LOG_LEVEL=INFO

# Celery transport — unprefixed by design (see Task Queue (Celery) above).
# Workers need these AND the four core secrets above.
REDIS_URL=redis://:[email protected]:6379/0
CELERY_BROKER_URL=redis://:[email protected]:6379/1
CELERY_RESULT_BACKEND=redis://:[email protected]:6379/2

# Services
HUITZO_SENDGRID_API_KEY=SG....
# Replace yourdomain.com — it must be a domain you control, with SPF + DKIM
# published for SendGrid. Left as-is it is detected as a placeholder and the
# `email` integration reports `degraded`.
HUITZO_EMAIL_FROM=[email protected]

# Rate limiting
RATE_LIMIT_ENABLED=true
RATE_LIMIT_REQUESTS=100
RATE_LIMIT_WINDOW=60

# Self-hosted license (a Huitzo-signed license.json verified locally; no key)
HUITZO_LICENSE_PATH=/etc/huitzo/license.json