---
title: "Build Process"
description: "Comprehensive guide to building TraceRTM packages, from development builds to production releases."
---

## Overview

TraceRTM uses a modern, multi-component build system optimized for both development speed and production reliability. This guide covers building all project components: Python packages, frontend applications, and containerized deployments.

### Build System Architecture

```
┌─────────────────────────────────────────────────────────┐
│                   Build System                          │
├─────────────────────────────────────────────────────────┤
│                                                         │
│  Python Backend (Hatchling)                            │
│  ├─ Core Package Build (tracertm)                      │
│  ├─ Entry Points (CLI commands)                        │
│  └─ Distribution Formats (wheel, sdist)                │
│                                                         │
│  Frontend Application (Vite + TanStack)                │
│  ├─ TypeScript Compilation                             │
│  ├─ Asset Bundling & Optimization                      │
│  └─ Static Site Generation                             │
│                                                         │
│  Container Images (Docker Multi-stage)                 │
│  ├─ Backend API Container                              │
│  ├─ Frontend Static Server                             │
│  └─ Multi-architecture Support (amd64, arm64)          │
│                                                         │
└─────────────────────────────────────────────────────────┘
```

### Key Technologies

- **Python Build**: [Hatchling](https://hatch.pypa.io/) (PEP 517/621 compliant)
- **Package Manager**: [uv](https://github.com/astral-sh/uv) (ultra-fast pip replacement)
- **Frontend Build**: [Vite](https://vitejs.dev/) with React 19
- **Task Runner**: [Poe the Poet](https://poethepoet.natn.io/)
- **Container Runtime**: Docker with multi-stage builds

---

## Python Package Building

### Build Backend: Hatchling

TraceRTM uses **Hatchling** as its build backend, configured in `pyproject.toml`:

```toml
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[tool.hatch.build.targets.wheel]
packages = ["src/tracertm"]

[tool.hatch.build.targets.sdist]
include = [
    "/src",
    "/tests",
    "/docs",
    "/pyproject.toml",
    "/README.md",
]
```

**Why Hatchling?**
- **PEP 517/621 compliant**: Modern Python packaging standards
- **Zero configuration**: Works out-of-the-box with sensible defaults
- **Fast builds**: Written in Python, optimized for speed
- **Editable installs**: Supports development workflows

### Package Manager: UV

UV is our primary package manager, offering significant performance improvements:

```bash
# Install uv (one-time setup)
curl -LsSf https://astral.sh/uv/install.sh | sh

# Install project in editable mode
uv pip install -e .

# Install with development dependencies
uv pip install -e ".[dev]"

# Install all optional dependency groups
uv pip install -e ".[all]"
```

**UV Performance Benefits**:
- 10-100x faster than pip for dependency resolution
- Parallel downloads and installations
- Better caching strategies
- Rust-based implementation

### Build Commands

#### Standard Build (Development)

```bash
# Build wheel and source distribution
python -m build

# Using uv (recommended)
uv build

# Output: dist/tracertm-0.1.0-py3-none-any.whl
#         dist/tracertm-0.1.0.tar.gz
```

#### Editable Install (Development)

```bash
# Install in editable mode (recommended for development)
uv pip install -e .

# With dev dependencies
uv pip install -e ".[dev,test]"

# Verify installation
python -c "import tracertm; print(tracertm.__version__)"
rtm --version
```

#### Production Build

```bash
# Clean previous builds
rm -rf dist/ build/ *.egg-info

# Build with uv (production-ready)
uv build --wheel

# Verify wheel contents
unzip -l dist/tracertm-0.1.0-py3-none-any.whl

# Install from wheel
pip install dist/tracertm-0.1.0-py3-none-any.whl
```

### Build Artifacts

After building, you'll find these artifacts:

```
dist/
├── tracertm-0.1.0-py3-none-any.whl    # Wheel distribution (recommended)
└── tracertm-0.1.0.tar.gz              # Source distribution
```

**Wheel Structure**:
```
tracertm-0.1.0-py3-none-any.whl
├── tracertm/                # Package code
│   ├── __init__.py
│   ├── api/                 # API client
│   ├── cli.py               # CLI entry point
│   ├── core/                # Core functionality
│   ├── models/              # Data models
│   ├── repositories/        # Data access
│   ├── services/            # Business logic
│   ├── storage/             # Storage layer
│   └── tui/                 # Terminal UI
├── tracertm-0.1.0.dist-info/
│   ├── METADATA             # Package metadata
│   ├── WHEEL                # Wheel metadata
│   ├── entry_points.txt     # Console scripts
│   └── RECORD               # File checksums
```

### Entry Points

The package provides two CLI entry points (configured in `pyproject.toml`):

```toml
[project.scripts]
rtm = "tracertm.cli:app"
tracertm = "tracertm.cli:app"
```

Both commands invoke the same Typer CLI application.

---

## Frontend Application Build

### Build Configuration

The frontend uses **Vite** for blazing-fast builds with Hot Module Replacement (HMR):

```json
{
  "scripts": {
    "dev": "vite dev",
    "build": "vite build",
    "preview": "vite preview"
  }
}
```

### Development Build

```bash
cd frontend/apps/web

# Start development server (http://localhost:3000)
npm run dev

# Features:
# - Hot Module Replacement (HMR)
# - Fast refresh for React components
# - Source maps enabled
# - Development-only runtime checks
```

### Production Build

```bash
cd frontend/apps/web

# Build for production
npm run build

# Output structure:
# dist/
# ├── index.html                    # Entry point
# ├── assets/
# │   ├── index-[hash].js          # Main bundle (minified)
# │   ├── index-[hash].css         # Styles (minified)
# │   └── vendor-[hash].js         # Dependencies chunk
# └── favicon.ico

# Preview production build locally
npm run preview
```

### Build Optimization

**Production build includes**:
- **Code Splitting**: Automatic vendor/app chunk separation
- **Tree Shaking**: Dead code elimination
- **Minification**: Terser for JS, cssnano for CSS
- **Asset Optimization**: Image compression, font subsetting
- **Cache Busting**: Content-based hashing for all assets

**Bundle Analysis**:
```bash
# Analyze bundle size
npm run build -- --mode analyze

# Check bundle composition
npx vite-bundle-visualizer
```

---

## Development vs Production Builds

### Development Build Characteristics

**Python**:
```bash
# Editable install (symlinks to source)
uv pip install -e ".[dev]"

# Features:
# - No wheel building required
# - Changes reflected immediately
# - Debug symbols included
# - Verbose logging enabled
```

**Frontend**:
```bash
npm run dev

# Features:
# - Unminified code
# - Source maps included
# - HMR enabled
# - React DevTools compatible
# - PropTypes validation active
```

### Production Build Characteristics

**Python**:
```bash
# Clean wheel build
uv build --wheel

# Optimizations:
# - Bytecode compilation (.pyc files)
# - No test files included
# - No development dependencies
# - Minimal metadata
```

**Frontend**:
```bash
npm run build

# Optimizations:
# - Minified JS/CSS
# - Tree shaking applied
# - Code splitting enabled
# - Gzip/Brotli compression ready
# - PropTypes stripped
# - Console logs removed
```

### Comparison Table

| Feature | Development | Production |
|---------|-------------|-----------|
| **Python Install** | Editable (`-e`) | Wheel install |
| **Build Time** | Instant | 10-30 seconds |
| **Frontend Size** | ~5-10 MB | ~500 KB gzipped |
| **Startup Time** | Fast | Fastest |
| **Debug Info** | Full | Minimal |
| **Source Maps** | Included | External/None |
| **Type Checking** | Runtime | Build-time only |

---

## Build Commands Reference

### Python Package Commands

```bash
# Full build workflow
uv build                          # Build wheel + sdist
uv build --wheel                  # Wheel only
uv build --sdist                  # Source distribution only

# Development
uv pip install -e .               # Editable install
uv pip install -e ".[dev]"        # With dev dependencies
uv pip install -e ".[all]"        # All optional dependencies

# Quality checks before build
uv run poe format                 # Format code (ruff)
uv run poe lint                   # Lint code (ruff)
uv run poe type-check             # Type check (mypy)
uv run poe type-check-strict      # Strict type check (basedpyright)
uv run poe test                   # Run tests
uv run poe test-cov               # Tests with coverage
uv run poe all                    # Full quality pipeline
```

### Frontend Build Commands

```bash
cd frontend/apps/web

# Development
npm run dev                       # Dev server (http://localhost:3000)
npm run dev -- --host             # Expose to network
npm run dev -- --port 3001        # Custom port

# Production
npm run build                     # Production build
npm run preview                   # Preview production build
npm run build -- --mode staging   # Staging build

# Quality
npm run lint                      # Biome linting
npm run lint:fix                  # Auto-fix linting issues
npm run format                    # Format code
npm run typecheck                 # TypeScript checking
npm run test                      # Run tests
npm run test:e2e                  # E2E tests (Playwright)
```

### Task Runner (Poe the Poet)

Poe tasks are defined in `pyproject.toml`:

```bash
# Code quality
poe format                        # Format with ruff
poe lint                          # Lint with ruff
poe type-check                    # Type check with mypy
poe type-check-strict             # Type check with basedpyright
poe arch-check                    # Architecture analysis (tach)
poe security                      # Security scan (semgrep)

# Testing
poe test                          # Run pytest
poe test-cov                      # Tests with coverage
poe test-parallel                 # Parallel test execution
poe test-unit                     # Unit tests only
poe test-integration              # Integration tests only

# Complete pipeline
poe quality                       # Format + lint + type check
poe all                           # Quality + security + tests
```

---

## Version Management

### Current Version

Version is defined in `pyproject.toml`:

```toml
[project]
name = "tracertm"
version = "0.1.0"
```

### Version Scheme

TraceRTM follows [Semantic Versioning](https://semver.org/):

```
MAJOR.MINOR.PATCH

0.1.0  → Initial development
0.2.0  → New features, backward compatible
1.0.0  → First stable release
1.1.0  → New features, backward compatible
1.1.1  → Bug fixes only
2.0.0  → Breaking changes
```

### Updating Version

```bash
# Manual update in pyproject.toml
[project]
version = "0.2.0"

# Rebuild after version change
uv build
```

### Version at Runtime

```python
# Access version in Python
import tracertm
print(tracertm.__version__)  # "0.1.0"

# CLI version check
rtm --version                # tracertm version 0.1.0
```

### Release Tagging

```bash
# Tag a release (triggers CI/CD)
git tag v0.1.0
git push origin v0.1.0

# CI will automatically:
# 1. Run quality checks
# 2. Build packages
# 3. Create GitHub release
# 4. Publish to PyPI
```

---

## Build Optimization

### Python Build Optimization

#### Minimal Build Time

```bash
# Skip documentation builds
uv build --no-build-isolation

# Parallel dependency resolution
uv pip install -e ".[dev]" --compile-bytecode
```

#### Smaller Wheels

```toml
# Exclude unnecessary files in pyproject.toml
[tool.hatch.build.targets.wheel]
exclude = [
    "tests/",
    "docs/",
    "*.md",
    ".gitignore",
]
```

#### Faster Installs

```bash
# Use UV's cache
export UV_CACHE_DIR=~/.cache/uv

# Install from local wheel
uv pip install dist/tracertm-0.1.0-py3-none-any.whl
```

### Frontend Build Optimization

#### Build Performance

```typescript
// vite.config.ts optimizations
export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          'vendor': ['react', 'react-dom'],
          'router': ['@tanstack/react-router'],
        }
      }
    },
    chunkSizeWarningLimit: 1000,
  },
  optimizeDeps: {
    include: ['react', 'react-dom'],
  }
})
```

#### Bundle Size Optimization

```bash
# Analyze bundle
npm run build
npx vite-bundle-visualizer

# Common optimizations:
# 1. Code splitting (automatic with Vite)
# 2. Tree shaking (automatic for ES modules)
# 3. Lazy loading routes
# 4. Dynamic imports for large components
```

#### Asset Optimization

```bash
# Image optimization
npm install -D vite-plugin-imagemin

# CSS purging (TailwindCSS)
# Automatic with Vite production build
```

---

## CI/CD Build Integration

### GitHub Actions Workflow

The CI/CD pipeline is defined in `.github/workflows/`:

#### Python Build Job

```yaml
# .github/workflows/ci.yml
python-tests:
  runs-on: ubuntu-latest
  steps:
    - name: Install UV
      run: curl -LsSf https://astral.sh/uv/install.sh | sh

    - name: Install dependencies
      run: uv pip install --system -e ".[dev,test]"

    - name: Run quality checks
      run: |
        ruff check src/ tests/
        mypy src/

    - name: Run tests
      run: pytest --cov=src/tracertm --cov-report=xml

    - name: Upload coverage
      uses: codecov/codecov-action@v4
```

#### Frontend Build Job

```yaml
frontend-build:
  runs-on: ubuntu-latest
  steps:
    - name: Setup Node.js
      uses: actions/setup-node@v4
      with:
        node-version: '20'
        cache: 'npm'

    - name: Install dependencies
      run: npm ci

    - name: Build
      run: npm run build

    - name: Upload artifacts
      uses: actions/upload-artifact@v4
      with:
        name: frontend-build
        path: dist/
```

#### Docker Build Job

```yaml
docker-build:
  needs: [python-tests]
  steps:
    - name: Set up Docker Buildx
      uses: docker/setup-buildx-action@v3

    - name: Build and push
      uses: docker/build-push-action@v5
      with:
        platforms: linux/amd64,linux/arm64
        cache-from: type=gha
        cache-to: type=gha,mode=max
```

### Release Workflow

```yaml
# .github/workflows/release.yml
release:
  on:
    push:
      tags: ['v*']
  steps:
    - name: Build package
      run: uv build

    - name: Create GitHub Release
      uses: softprops/action-gh-release@v1
      with:
        files: dist/*

    - name: Publish to PyPI
      run: uv publish --token ${{ secrets.PYPI_TOKEN }}
```

### Build Caching Strategies

**Python Dependencies**:
```yaml
- uses: actions/setup-python@v5
  with:
    python-version: '3.12'
    cache: 'pip'  # Cache pip packages
```

**Node Dependencies**:
```yaml
- uses: actions/setup-node@v4
  with:
    node-version: '20'
    cache: 'npm'  # Cache node_modules
```

**Docker Layers**:
```yaml
- uses: docker/build-push-action@v5
  with:
    cache-from: type=gha          # GitHub Actions cache
    cache-to: type=gha,mode=max   # Maximum caching
```

---

## Docker Container Builds

### Multi-stage Dockerfile

```dockerfile
# Backend build example
FROM python:3.12-slim AS builder

WORKDIR /app
COPY pyproject.toml .
RUN pip install --no-cache-dir hatchling && \
    pip wheel --no-cache-dir --wheel-dir /wheels .

FROM python:3.12-slim
COPY --from=builder /wheels /wheels
RUN pip install --no-cache-dir /wheels/*.whl && \
    rm -rf /wheels

CMD ["uvicorn", "tracertm.api.main:app"]
```

### Building Containers

```bash
# Build backend container
docker build -t tracertm-api:latest .

# Build with BuildKit (faster)
DOCKER_BUILDKIT=1 docker build -t tracertm-api:latest .

# Multi-architecture build
docker buildx build \
  --platform linux/amd64,linux/arm64 \
  -t tracertm-api:latest .
```

### Container Size Optimization

**Before optimization**: ~800 MB
**After optimization**: ~150 MB

**Techniques**:
1. Multi-stage builds (remove build dependencies)
2. Alpine base images (smaller footprint)
3. `.dockerignore` file (exclude unnecessary files)
4. Layer caching (order COPY commands strategically)

---

## Troubleshooting Build Issues

### Python Build Issues

#### Issue: "No module named hatchling"

```bash
# Solution: Install hatchling
pip install hatchling

# Or use uv (recommended)
uv pip install hatchling
```

#### Issue: "Failed building wheel"

```bash
# Solution: Clean previous builds
rm -rf dist/ build/ *.egg-info

# Rebuild
uv build
```

#### Issue: "ImportError after install"

```bash
# Solution: Verify PYTHONPATH
echo $PYTHONPATH

# Reinstall in editable mode
uv pip install -e .

# Verify
python -c "import tracertm; print(tracertm.__file__)"
```

### Frontend Build Issues

#### Issue: "JavaScript heap out of memory"

```bash
# Solution: Increase Node.js memory
export NODE_OPTIONS="--max-old-space-size=4096"
npm run build
```

#### Issue: "Module not found" errors

```bash
# Solution: Clear cache and reinstall
rm -rf node_modules package-lock.json
npm install
npm run build
```

#### Issue: "Type errors during build"

```bash
# Solution: Run typecheck separately
npm run typecheck

# Fix types, then rebuild
npm run build
```

### Docker Build Issues

#### Issue: "BuildKit not enabled"

```bash
# Solution: Enable BuildKit
export DOCKER_BUILDKIT=1

# Or set in Docker daemon.json
{
  "features": {
    "buildkit": true
  }
}
```

#### Issue: "Platform not supported"

```bash
# Solution: Use buildx for multi-platform
docker buildx create --use
docker buildx build --platform linux/amd64,linux/arm64 .
```

### CI/CD Build Issues

#### Issue: "Out of disk space"

```yaml
# Solution: Clean before build
- name: Clean disk space
  run: |
    docker system prune -af
    rm -rf /tmp/*
```

#### Issue: "Cache not working"

```yaml
# Solution: Verify cache configuration
- uses: actions/cache@v4
  with:
    path: ~/.cache/pip
    key: ${{ runner.os }}-pip-${{ hashFiles('**/pyproject.toml') }}
```

---

## Build Best Practices

### Development Workflow

1. **Use editable installs for Python**:
   ```bash
   uv pip install -e ".[dev]"
   ```

2. **Run quality checks before building**:
   ```bash
   poe quality  # Format, lint, type check
   ```

3. **Test before releasing**:
   ```bash
   poe test-cov
   ```

### Production Workflow

1. **Clean builds for releases**:
   ```bash
   rm -rf dist/ build/
   uv build
   ```

2. **Verify wheel contents**:
   ```bash
   unzip -l dist/*.whl
   ```

3. **Test installation in clean environment**:
   ```bash
   python -m venv /tmp/test-env
   source /tmp/test-env/bin/activate
   pip install dist/tracertm-*.whl
   rtm --version
   ```

### Performance Tips

1. **Use UV instead of pip** (10-100x faster)
2. **Enable build caching in CI/CD**
3. **Parallel test execution**: `pytest -n auto`
4. **Pre-compile Python modules**: `python -m compileall src/`
5. **Use Docker layer caching** for container builds

---

## Summary

TraceRTM's build system is designed for:
- **Speed**: UV for dependency management, Vite for frontend builds
- **Reliability**: PEP 517/621 compliance, automated testing
- **Flexibility**: Multiple build targets, optional dependencies
- **Production-ready**: Multi-stage Docker builds, CI/CD integration

**Quick reference**:
```bash
# Python development
uv pip install -e ".[dev]"

# Python production
uv build

# Frontend development
npm run dev

# Frontend production
npm run build

# Full quality pipeline
poe all

# Release
git tag v0.1.0 && git push --tags
```

For more details, see:
- [Development Setup](/docs/development/setup)
- [Testing Guide](/docs/development/testing)
- [Deployment Guide](/docs/deployment)
