# Development Guide ## Prerequisites | Tool | Version | Notes | |---|---|---| | Python | 3.11+ | Use `pyenv` or system package | | Node.js | 20+ | LTS recommended | | PostgreSQL | 15+ | With pgvector extension | | Redis | 7+ | Local instance or Docker | | Ollama | latest | For local embeddings | | Docker | 24+ | Optional but recommended | --- ## Environment setup Copy the example env file and fill in required values: ```bash cp .env.example .env ``` ### Required variables | Variable | Description | |---|---| | `DATABASE_URL` | Async PostgreSQL URL: `postgresql+asyncpg://user:pass@host/db` | | `SECRET_KEY` | 32+ char random string for JWT signing | | `ANTHROPIC_API_KEY` | Anthropic API key for text generation | | `OLLAMA_BASE_URL` | Ollama host (default `http://localhost:11434`) | ### Redis variables Three Redis roles, all defaulting to `redis://localhost:6379`: | Variable | Role | |---|---| | `ARQ_REDIS_URL` | ARQ job queue — can be Upstash or local | | `CACHE_REDIS_URL` | L2 search cache — can be Upstash or local | | `LOCAL_REDIS_URL` | WebSocket pub/sub — **must** be a real persistent Redis, not Upstash HTTP | In local dev, a single Redis instance can serve all three by pointing all three variables to `redis://localhost:6379`. ### Optional variables | Variable | Default | Description | |---|---|---| | `AI_PROVIDER` | `anthropic` | `anthropic`, `ollama`, `google`, `azure` | | `AI_MODEL` | `claude-3-haiku-20240307` | Model ID for the chosen provider | | `AI_TEXT_EMBEDDING_PROVIDER` | `ollama` | Embedding backend | | `GOOGLE_API_KEY` | — | Required if `AI_PROVIDER=google` | | `AZURE_OPENAI_API_KEY` | — | Required if `AI_PROVIDER=azure` | | `RESEND_API_KEY` | — | Transactional email (password reset, mentions) | | `RESEND_FROM_EMAIL` | — | Sender address for Resend | | `UPLOAD_DIR` | `uploads` | Local file attachment storage | | `S3_BUCKET` | — | S3-compatible bucket (overrides local storage) | | `S3_ACCESS_KEY` | — | S3 credentials | | `S3_SECRET_KEY` | — | S3 credentials | | `S3_ENDPOINT_URL` | — | Custom endpoint for MinIO or similar | | `ALLOWED_ORIGINS` | `["*"]` | CORS allowlist as JSON array | | `DEBUG` | `false` | Enables detailed error pages | | `SUPER_ADMIN_EMAIL` | `admin@3sc.com` | Auto-linked SUPERADMIN email | | `ACCESS_TOKEN_EXPIRE_MINUTES` | `60` | JWT access token TTL | | `REFRESH_TOKEN_EXPIRE_DAYS` | `7` | JWT refresh token TTL | --- ## Database setup ### Install pgvector ```bash # macOS (Homebrew) brew install pgvector # Ubuntu/Debian sudo apt install postgresql-15-pgvector # Docker — use pgvector/pgvector image (see compose.example.yml) ``` ### Run migrations ```bash # Apply all pending migrations alembic upgrade head # Create a new migration after editing models/ alembic revision --autogenerate -m "describe your change" # Roll back one migration alembic downgrade -1 ``` Migration files live in `alembic/versions/`. The `env.py` uses the async SQLAlchemy engine from `core/database.py`. --- ## Running locally (no Docker) ```bash # 1. Install Python dependencies pip install -r requirements.txt pip install -r requirements-ai.txt # AI/ML packages (heavier) # 2. Start services redis-server & ollama serve & ollama pull nomic-embed-text # pull the embedding model # 3. Run migrations alembic upgrade head # 4. Start the API (auto-reload on save) uvicorn main:app --reload --port 8000 # 5. Start background workers (separate terminals) arq nexus_worker.RegularWorkerSettings arq nexus_worker.HeavyWorkerSettings # 6. Start frontend dev servers cd frontend npm install npm run dev -w apps/customer # http://localhost:5173 npm run dev -w apps/internal # http://localhost:5174 ``` --- ## Running with Docker ```bash # Build and start everything (API + Redis + Ollama) docker compose -f compose.example.yml up --build # Or use the Windows one-click script ./scripts/start_local.bat ``` The compose file mounts the local source tree so code changes are picked up without a full rebuild (except for frontend assets). --- ## Project structure quick-reference ``` api/v1/ HTTP routers — one file per domain agents/ LangGraph agent graph, nodes, prompts, tools core/ config.py All settings (Pydantic BaseSettings) database.py Async SQLAlchemy engine factory deps.py FastAPI dependencies (auth, workspace context) security.py JWT creation/validation, password hashing cache.py L1 LRU + L2 Redis + semantic cache websockets.py Redis pub/sub manager permissions.py Role hierarchy helpers audit.py Compliance audit log models/ SQLAlchemy ORM models schemas/ Pydantic request/response schemas services/ Business logic (TicketService, etc.) tasks/ ARQ background job functions ai.py Summarization, embedding, memory analytics.py Workspace insight generation notifications.py Email/webhook dispatch system.py Heartbeat, SLA monitor, job latch alembic/ Database migrations frontend/ apps/customer/ Customer portal (React + Vite) apps/internal/ Internal console (React + Vite) packages/shared/ Shared components and hooks tests/ pytest test suite scripts/ Dev and production helper scripts ``` --- ## Testing ```bash # Run the full test suite pytest # Run a specific module pytest tests/test_tickets.py -v # With coverage pytest --cov=. --cov-report=term-missing ``` Test configuration is in `pytest.ini`. Tests use an in-memory SQLite database by default (see `tests/conftest.py`). Set `TEST_DATABASE_URL` in your env to point at a real PostgreSQL instance for integration tests. --- ## Code conventions - **Async everywhere**: all route handlers, service methods, and DB calls are `async`. Never use synchronous DB calls inside an `async` context. - **Pydantic schemas for I/O**: request bodies and responses use schemas from `schemas/`. Models are never returned directly. - **Workspace scope on every query**: all DB queries must include a `workspace_id` filter. Use `get_current_workspace()` from `core/deps.py`. - **Background work via ARQ**: do not do heavy work in a request handler. Enqueue a job with `core/tasks.enqueue(...)`. - **No comments on obvious code**: only document non-obvious invariants or workarounds. --- ## Common issues **`pgvector` extension not found** ```sql CREATE EXTENSION IF NOT EXISTS vector; ``` Run this on your database once. Alembic migrations assume the extension exists. **Ollama model not available** ```bash ollama pull nomic-embed-text ``` Embedding jobs will fail silently if the model isn't pulled. **ARQ worker not picking up jobs** Check that `ARQ_REDIS_URL` points to the same Redis instance the API is using. If you see `ConnectionRefused`, Redis may not be running. **WebSocket connections drop immediately** `LOCAL_REDIS_URL` must point to a persistent Redis (not Upstash HTTP-only). Use `redis://localhost:6379` in local dev.