type: epic

title: Phase 1: Foundation (Auth, Git Repos, Project Structure)

description: Rebuild Headquarter platform from scratch starting with foundational layer: Authentik OAuth auth, git repository management with bare repos on disk, SSH key management, user profiles, and basic project structure. Provides core infrastructure for Phase 2 (tool spawning) and Phase 3 (collaboration).

status: open


type: story

title: US-001: Docker Infrastructure & Project Bootstrap

description:
As a developer, I want a Docker Compose setup with all required services so that I can run the platform locally.

## Acceptance Criteria
- [ ] `docker-compose.yml` with PostgreSQL, Redis, Traefik, and Authentik services
- [ ] `apps/api/Dockerfile` with multi-stage build for FastAPI
- [ ] `apps/web/Dockerfile` for React SPA with Vite
- [ ] `.env.example` documenting all required environment variables
- [ ] Health checks for all services
- [ ] `Makefile` with common commands (`make up`, `make down`, `make logs`, `make migrate`)
- [ ] Git repo storage directory mounted as Docker volume

## Quality Gates
- `pytest` must pass
- `mypy .` must pass
- `ruff check .` must pass


title: US-002: Database Models & Alembic Migrations

description:
As a developer, I want database models for users, projects, and git repos so that the data layer is consistent and versioned.

## Acceptance Criteria
- [ ] SQLAlchemy models: User, Project, GitRepository, SSHKey, UserConfig
- [ ] Relationships: User owns Projects, Project has GitRepositories, User has SSHKeys
- [ ] Alembic initialized with initial migration script
- [ ] Migration command documented in Makefile
- [ ] Database seed script for development (creates test user)
- [ ] All models use SQLAlchemy 2.0 async style

## Quality Gates
- `pytest` must pass
- `mypy .` must pass
- `ruff check .` must pass


title: US-003: Authentik OAuth Authentication with httpOnly Cookies

description:
As a user, I want to log in via Authentik OAuth with secure httpOnly cookies so that my session is protected from XSS attacks.

## Acceptance Criteria
- [ ] OAuth2/OIDC flow implemented with Authentik as provider
- [ ] Callback endpoint exchanges code for tokens and sets httpOnly, Secure, SameSite=strict cookies
- [ ] Token refresh mechanism with refresh token rotation
- [ ] `/auth/me` endpoint returning current authenticated user
- [ ] `/auth/logout` endpoint clearing all auth cookies
- [ ] JWT validation middleware protecting all API routes (except public)
- [ ] Frontend login button redirecting to Authentik
- [ ] Frontend handles OAuth callback and refreshes user state
- [ ] Tests mocking Authentik OIDC endpoints

## Quality Gates
- `pytest` must pass
- `mypy .` must pass
- `ruff check .` must pass


title: US-004: User Profile Management

description:
As a user, I want to view and edit my profile so that my information is up to date.

## Acceptance Criteria
- [ ] `GET /users/me` endpoint returning current user profile
- [ ] `PATCH /users/me` endpoint for updating profile fields (name, email)
- [ ] Frontend profile page displaying user info
- [ ] Frontend profile edit form with validation
- [ ] Avatar upload support (stored locally, not external service)
- [ ] Tests for profile CRUD operations

## Quality Gates
- `pytest` must pass
- `mypy .` must pass
- `ruff check .` must pass
- `npm run typecheck` must pass
- `npm run lint` must pass


title: US-005: Git Repository Creation & Cloning

description:
As a user, I want to create new git repositories or clone existing ones so that I can start working on projects.

## Acceptance Criteria
- [ ] `POST /repos` endpoint to create a new bare git repository
- [ ] `POST /repos/clone` endpoint to clone an existing repo (bare mirror)
- [ ] Repositories stored as bare repos on disk in structured path (`/data/repos/{user_id}/{project_id}/{repo_name}.git`)
- [ ] `GET /repos` listing all user repositories
- [ ] `GET /repos/{id}` returning repo details (name, path, created_at, last_push)
- [ ] `DELETE /repos/{id}` removing repo from disk and database
- [ ] Validation preventing duplicate repo names per project
- [ ] Frontend repo list page
- [ ] Frontend forms for create and clone operations
- [ ] Tests for repo lifecycle (create, clone, delete)

## Quality Gates
- `pytest` must pass
- `mypy .` must pass
- `ruff check .` must pass
- `npm run typecheck` must pass
- `npm run lint` must pass


title: US-006: SSH Key Management

description:
As a user, I want to generate and manage SSH keys for git operations so that I can authenticate with external git providers.

## Acceptance Criteria
- [ ] `POST /ssh-keys` endpoint generating Ed25519 key pair
- [ ] `GET /ssh-keys` listing user's SSH keys
- [ ] `DELETE /ssh-keys/{id}` removing a key
- [ ] Public key displayed in OpenSSH format
- [ ] Private key encrypted at rest (using Fernet with app secret)
- [ ] SSH keys associated with User (global) or Project (project-specific)
- [ ] Frontend SSH key management page
- [ ] Frontend key generation with one-click copy of public key
- [ ] Tests for key generation and encryption

## Quality Gates
- `pytest` must pass
- `mypy .` must pass
- `ruff check .` must pass
- `npm run typecheck` must pass
- `npm run lint` must pass


title: US-007: Project Structure & Organization

description:
As a user, I want to organize repositories into projects so that I can group related work.

## Acceptance Criteria
- [ ] `POST /projects` endpoint creating a new project
- [ ] `GET /projects` listing user's projects
- [ ] `GET /projects/{id}` returning project with associated repos
- [ ] `PATCH /projects/{id}` updating project name/description
- [ ] `DELETE /projects/{id}` deleting project and all associated repos
- [ ] Project settings page for default SSH key selection
- [ ] Frontend project list and detail pages
- [ ] Frontend project creation form
- [ ] Tests for project CRUD and cascading delete

## Quality Gates
- `pytest` must pass
- `mypy .` must pass
- `ruff check .` must pass
- `npm run typecheck` must pass
- `npm run lint` must pass


title: US-008: User Configuration System

description:
As a user, I want to set global preferences so that the platform behaves according to my preferences.

## Acceptance Criteria
- [ ] `UserConfig` model with key-value storage (JSONB)
- [ ] `GET /config` endpoint returning user configuration
- [ ] `PATCH /config` endpoint updating configuration
- [ ] Supported config keys: default_editor, theme, git_user_name, git_user_email
- [ ] Frontend settings page with config form
- [ ] Config applied on frontend (theme, default values)
- [ ] Tests for config CRUD

## Quality Gates
- `pytest` must pass
- `mypy .` must pass
- `ruff check .` must pass
- `npm run typecheck` must pass
- `npm run lint` must pass


title: US-009: Frontend Foundation & Layout

description:
As a user, I want a modern React frontend with navigation so that I can access all features.

## Acceptance Criteria
- [ ] React 18+ with TypeScript and Vite
- [ ] React Router setup with protected routes
- [ ] Tailwind CSS for styling
- [ ] Layout component with header, sidebar navigation, and main content area
- [ ] Navigation links: Dashboard, Projects, Repositories, SSH Keys, Settings
- [ ] Responsive design (mobile hamburger menu)
- [ ] Loading states and error boundaries
- [ ] Axios/fetch configured with credentials (cookies)
- [ ] Basic dashboard page showing user stats (repo count, project count)

## Quality Gates
- `pytest` must pass
- `mypy .` must pass
- `ruff check .` must pass
- `npm run typecheck` must pass
- `npm run lint` must pass


title: US-010: API Documentation & Health Checks

description:
As a developer, I want API documentation and health endpoints so that I can monitor and integrate with the platform.

## Acceptance Criteria
- [ ] OpenAPI/Swagger UI at `/docs` with all endpoints documented
- [ ] `/health` endpoint returning database and service status
- [ ] `/health/db` endpoint for database connectivity check
- [ ] README in `apps/api/` with setup instructions
- [ ] Architecture Decision Record (ADR) for httpOnly cookie auth choice
- [ ] All quality gates passing

## Quality Gates
- `pytest` must pass
- `mypy .` must pass
- `ruff check .` must pass


title: Phase 2: Tool Runtime (Docker Tools, Web Access, Terminal)

description: Extend Headquarter platform with Docker-based tool runtime system. Enables launching development tools (code-server, Jupyter, opencode) from git repositories, accessing their web UIs via Traefik routes, and interacting through web-based terminals. Tools are defined via Docker Compose templates and spawned into isolated containers.


title: US-011: Tool Type Definition System

description:
As an admin, I want to define tool types using Docker Compose templates so that new tools can be added without code changes.

## Acceptance Criteria
- [ ] Create ToolType model with fields: name, description, docker_compose_template, icon, category, default_env_vars, default_ports
- [ ] Support template variables: {{REPO_PATH}}, {{WORKSPACE_DIR}}, {{USER_ID}}, {{PROJECT_ID}}, {{TOOL_ID}}
- [ ] Seed database with 3 built-in tool types: code-server, jupyter-notebook, opencode
- [ ] GET /tool-types endpoint listing all available tool types
- [ ] GET /tool-types/{id} returning tool type details
- [ ] Docker Compose templates validated on create/update
- [ ] Tests for template validation and variable substitution

## Quality Gates
- pytest must pass
- mypy . must pass
- ruff check . must pass


title: US-012: Tool Instance Model & Database Schema

description:
As a developer, I want a database model for tool instances so that I can track running tools and their state.

## Acceptance Criteria
- [ ] Create ToolInstance model with fields: id, name, project_id, repo_id, tool_type_id, status, container_id, subdomain, ports, env_vars, created_at, started_at, stopped_at
- [ ] Status enum: pending, building, running, stopped, error
- [ ] Relationship: ToolInstance belongs to Project and GitRepository
- [ ] Alembic migration for tool instance tables
- [ ] ToolInstanceConfig model for per-instance config overrides
- [ ] Tests for model relationships and status transitions

## Quality Gates
- pytest must pass
- mypy . must pass
- ruff check . must pass


title: US-013: Docker Compose Template Engine

description:
As a developer, I want a template engine that renders Docker Compose files with project-specific values so that tools launch with correct configuration.

## Acceptance Criteria
- [ ] Implement template rendering engine (Jinja2 or string replacement)
- [ ] Variable substitution: {{REPO_PATH}}, {{WORKSPACE_DIR}}, {{USER_ID}}, {{PROJECT_ID}}, {{TOOL_ID}}, {{SUBDOMAIN}}
- [ ] Support environment variable injection from project/user config
- [ ] Support port mapping configuration (host port allocation)
- [ ] Support volume mounts (repo code, config files, persistent data)
- [ ] Support network attachment (Traefik network)
- [ ] Tests for template rendering with various inputs

## Quality Gates
- pytest must pass
- mypy . must pass
- ruff check . must pass


title: US-014: Tool Spawning & Docker Integration

description:
As a user, I want to launch tools from my repositories so that I can start working immediately.

## Acceptance Criteria
- [ ] POST /tools endpoint to create and launch a tool instance
- [ ] Accept parameters: name, project_id, repo_id, tool_type_id, env_vars (optional), config_overrides (optional)
- [ ] Generate unique subdomain: {tool-name}-{tool-id}.hq.local
- [ ] Render Docker Compose template with project values
- [ ] Execute docker compose up -d to launch container
- [ ] Store container_id and update status to running
- [ ] Handle build errors and set status to error with logs
- [ ] POST /tools/{id}/stop to stop container (docker compose stop)
- [ ] POST /tools/{id}/start to start stopped container
- [ ] DELETE /tools/{id} to stop and remove container + data
- [ ] Tests mocking Docker compose commands

## Quality Gates
- pytest must pass
- mypy . must pass
- ruff check . must pass


title: US-015: Traefik Route Generation

description:
As a user, I want tools accessible via clean URLs so that I can access them without remembering ports.

## Acceptance Criteria
- [ ] Auto-generate Traefik labels on tool containers:
  - traefik.enable=true
  - traefik.http.routers.{tool_id}.rule=Host({subdomain}.hq.local)
  - traefik.http.routers.{tool_id}.entrypoints=web
  - traefik.http.services.{tool_id}.loadbalancer.server.port={port}
- [ ] Tools join Traefik Docker network for routing
- [ ] GET /tools/{id}/url returning accessible URL
- [ ] Handle subdomain collisions (append random suffix if needed)
- [ ] Support HTTPS in production (websecure entrypoint)
- [ ] Tests for label generation and URL construction

## Quality Gates
- pytest must pass
- mypy . must pass
- ruff check . must pass


title: US-016: Web-Based Terminal (xterm.js)

description:
As a user, I want a terminal in my browser to interact with running tools so that I don't need SSH access.

## Acceptance Criteria
- [ ] WebSocket endpoint /ws/terminal/{tool_id} for terminal sessions
- [ ] Use docker exec to spawn shell in running container
- [ ] Stream stdin/stdout/stderr via WebSocket
- [ ] Terminal resize support (COLS, ROWS)
- [ ] Session cleanup on disconnect
- [ ] Authentication: only tool owner can access terminal
- [ ] Frontend terminal component using xterm.js
- [ ] Terminal connects to WebSocket with auth token
- [ ] Support multiple terminal sessions per tool
- [ ] Tests for WebSocket terminal lifecycle

## Quality Gates
- pytest must pass
- mypy . must pass
- ruff check . must pass
- npm run typecheck must pass
- npm run lint must pass


title: US-017: Tool Status Monitoring & Logs

description:
As a user, I want to see if my tools are running and view their logs so that I can debug issues.

## Acceptance Criteria
- [ ] GET /tools/{id}/status returning real-time container status
- [ ] GET /tools/{id}/logs returning recent container logs (tail 100)
- [ ] GET /tools/{id}/logs/stream WebSocket for live log streaming
- [ ] Frontend tool dashboard showing:
  - Status indicator (running/stopped/error)
  - Uptime counter
  - Quick actions (start/stop/restart)
  - Log viewer with auto-scroll
- [ ] Auto-refresh status every 5 seconds
- [ ] Tests for status checking and log retrieval

## Quality Gates
- pytest must pass
- mypy . must pass
- ruff check . must pass
- npm run typecheck must pass
- npm run lint must pass


title: US-018: Frontend Tool Management UI

description:
As a user, I want a web interface to manage my tools so that I can launch, monitor, and access them easily.

## Acceptance Criteria
- [ ] Tools page listing all user's tool instances
- [ ] Launch Tool button opening creation form
- [ ] Form fields: name, project (dropdown), repository (dropdown), tool type (dropdown), environment variables (key-value), config overrides
- [ ] Tool detail page showing:
  - Status and info
  - Open button (links to tool URL)
  - Terminal button (opens web terminal)
  - Logs panel
  - Settings (env vars, restart, delete)
- [ ] Tool cards on dashboard showing quick stats
- [ ] Empty state when no tools exist
- [ ] Tests for tool CRUD operations in frontend

## Quality Gates
- pytest must pass
- mypy . must pass
- ruff check . must pass
- npm run typecheck must pass
- npm run lint must pass


title: US-019: Tool Configuration & Environment Variables

description:
As a user, I want to configure tools with custom environment variables and settings so that they work for my specific needs.

## Acceptance Criteria
- [ ] Global tool config at user level (default env vars for all tools)
- [ ] Project-level tool config (overrides global defaults)
- [ ] Tool instance-level config (overrides project defaults)
- [ ] PATCH /tools/{id}/config endpoint for updating config
- [ ] Config inheritance: user defaults -> project overrides -> instance overrides
- [ ] Frontend config editor with key-value pairs
- [ ] Support for secret values (masked in UI, encrypted at rest)
- [ ] Tests for config inheritance and override logic

## Quality Gates
- pytest must pass
- mypy . must pass
- ruff check . must pass
- npm run typecheck must pass
- npm run lint must pass


title: US-020: Phase 2 Integration & Documentation

description:
As a developer, I want Phase 2 fully integrated with Phase 1 and documented so that the platform is cohesive.

## Acceptance Criteria
- [ ] Tool instances linked to projects and repositories (Phase 1 models)
- [ ] SSH keys from Phase 1 available inside tool containers (mount ~/.ssh)
- [ ] Git user config from Phase 1 applied to tool containers
- [ ] Update API docs with all new endpoints
- [ ] README section for tool configuration
- [ ] Architecture Decision Record (ADR) for Docker Compose template approach
- [ ] All quality gates passing
- [ ] End-to-end test: create repo -> launch code-server -> access via URL -> open terminal

## Quality Gates
- pytest must pass
- mypy . must pass
- ruff check . must pass
- npm run typecheck must pass
- npm run lint must pass