# CODEX_ADK - Project Context for Claude

**Last Updated:** 2025-10-26
**Project Status:** MVP v1.0.0 - Backend Ready, Frontend Integration Pending
**Grade:** A- (Backend), Development Phase (Frontend)

---

## Project Overview

**CODEX_ADK** (Codex API Development Kit) is a full-stack AI agent management platform called **Svrnty Console**. It's a sophisticated control panel for managing AI agents with support for multiple model providers (OpenAI, Anthropic, Ollama).

### Core Purpose
- Manage AI agents with dynamic model configuration
- Track conversations and execution history
- Support multiple model providers with encrypted API keys
- Provide a modern, responsive UI for agent management

---

## Architecture at a Glance

```
┌─────────────────────────────────────────────────────────┐
│                    FRONTEND (Flutter)                    │
│  ┌─────────────────────────────────────────────────┐   │
│  │  UI Layer (Dart - 10 files)                     │   │
│  │  - ConsoleLandingPage (main UI shell)           │   │
│  │  - NavigationSidebar (collapsible nav)          │   │
│  │  - ArchitechPage (module UI)                    │   │
│  └─────────────────────────────────────────────────┘   │
│  ┌─────────────────────────────────────────────────┐   │
│  │  API Layer (CQRS Client)                        │   │
│  │  - CqrsApiClient (Result<T> error handling)     │   │
│  │  - Type-safe endpoints from OpenAPI             │   │
│  │  - Serializable commands/queries                │   │
│  └─────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────┘
                          │ HTTP
                          ↓
┌─────────────────────────────────────────────────────────┐
│              BACKEND (ASP.NET Core 8.0)                 │
│  ┌─────────────────────────────────────────────────┐   │
│  │  API Layer (Controllers + Endpoints)            │   │
│  │  - OpenHarbor auto-generated controllers        │   │
│  │  - Manual endpoint registration                 │   │
│  │  - Global exception handling                    │   │
│  │  - Swagger/OpenAPI documentation                │   │
│  └─────────────────────────────────────────────────┘   │
│                          ↓
│  ┌─────────────────────────────────────────────────┐   │
│  │  CQRS Layer (Business Logic)                    │   │
│  │  - Commands (6): Create, Update, Delete, etc.   │   │
│  │  - Queries (7): Health, Get*, List*             │   │
│  │  - FluentValidation on commands                 │   │
│  └─────────────────────────────────────────────────┘   │
│                          ↓
│  ┌─────────────────────────────────────────────────┐   │
│  │  Data Access Layer (EF Core)                    │   │
│  │  - CodexDbContext                               │   │
│  │  - 5 Entities: Agent, AgentTool, Execution,     │   │
│  │    Conversation, ConversationMessage            │   │
│  │  - AES-256 encryption for API keys              │   │
│  │  - Dynamic query providers                      │   │
│  └─────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────┘
                          │
                          ↓
              ┌───────────────────────┐
              │  PostgreSQL 15 (Docker) │
              └───────────────────────┘
```

---

## Directory Structure

```
CODEX_ADK/
├── BACKEND/              (29MB) - C# ASP.NET Core 8.0 API
│   ├── Codex.Api/        - Controllers, endpoints, middleware, Program.cs
│   ├── Codex.CQRS/       - Commands (6) + Queries (7)
│   ├── Codex.Dal/        - EF Core entities, DbContext, migrations, services
│   ├── docs/             - OpenAPI spec, architecture docs, API reference
│   ├── docker-compose.yml
│   ├── CLAUDE.md
│   ├── DEPLOYMENT_STATUS.md
│   └── BACKEND-READINESS.md
│
└── FRONTEND/             (829MB) - Flutter/Dart mobile & web app
    ├── lib/              - Dart source (10 files)
    │   ├── main.dart     - App entry point
    │   ├── theme.dart    - Svrnty brand colors/fonts
    │   ├── console_landing_page.dart - Main UI shell
    │   ├── api/          - CQRS API client layer
    │   │   ├── client.dart
    │   │   ├── types.dart
    │   │   ├── endpoints/
    │   │   └── generated/ - AUTO-GENERATED from OpenAPI
    │   ├── components/   - NavigationSidebar
    │   └── pages/        - ArchitechPage
    ├── pubspec.yaml      - Dependencies
    ├── README_API.md     - API integration guide (14KB)
    ├── CLAUDE.md         - Development guidelines
    ├── .claude-docs/     - Strict typing, response protocol
    └── web/ios/android/macos/linux/windows/
```

---

## Technology Stack

### Backend
| Component | Technology | Version |
|-----------|-----------|---------|
| Framework | ASP.NET Core | 8.0 LTS |
| Language | C# | .NET 8.0 |
| CQRS | OpenHarbor.CQRS | 8.1.0-rc1 |
| ORM | Entity Framework Core | 8.0.11 |
| Database | PostgreSQL | 15 (Docker) |
| Validation | FluentValidation | 11.3.1 |
| Query Engine | PoweredSoft.DynamicQuery | 3.0.1 |
| Documentation | Swagger/OpenAPI | 3.0.1 |

**Runs on:** `http://localhost:5246` (HTTP) or `https://localhost:7108` (HTTPS)

### Frontend
| Component | Technology | Version |
|-----------|-----------|---------|
| Framework | Flutter | 3.x |
| Language | Dart | 3.9.2+ |
| UI Library | GetWidget | 7.0.0 |
| Icons | Iconsax | 0.0.8 |
| Animations | Animate Do | 3.1.2 |
| HTTP Client | http | 1.2.2 |
| JSON | json_annotation | 4.9.0 |

**Fonts:** Montserrat (UI), IBM Plex Mono (code)
**Theme:** Dark theme with Svrnty brand colors (Crimson Red #C44D58, Slate Blue #475C6C)

---

## API Endpoints (16 Total)

### Commands (6 endpoints - Write Operations)
1. `POST /api/command/createAgent` - Create AI agent
2. `POST /api/command/updateAgent` - Update agent config
3. `POST /api/command/deleteAgent` - Soft delete agent
4. `POST /api/command/createConversation` - Create conversation → returns `{id: Guid}`
5. `POST /api/command/startAgentExecution` - Start execution → returns `{id: Guid}`
6. `POST /api/command/completeAgentExecution` - Complete execution with results

### Queries (4 endpoints - Single Value Reads)
7. `POST /api/query/health` - Health check → `bool`
8. `POST /api/query/getAgent` - Get agent details → `AgentDto`
9. `POST /api/query/getAgentExecution` - Get execution → `AgentExecutionDto`
10. `POST /api/query/getConversation` - Get conversation → `ConversationDto`

### List Endpoints (6 endpoints - GET Reads)
11. `GET /api/agents` - List all agents (100 limit)
12. `GET /api/conversations` - List all conversations (100 limit)
13. `GET /api/executions` - List all executions (100 limit)
14. `GET /api/agents/{id}/conversations` - Agent conversations
15. `GET /api/agents/{id}/executions` - Agent execution history
16. `GET /api/executions/status/{status}` - Filter by status

**Contract:** All endpoints documented in `/BACKEND/docs/openapi.json`

---

## Database Schema (5 Entities)

### 1. Agent
**Purpose:** Store AI agent configurations with encrypted API keys

**Key Fields:**
- `Id` (Guid, PK)
- `Name`, `Description`
- `AgentType` (enum: Assistant, CodeGenerator, Analyzer, Custom)
- `Status` (enum: Active, Inactive, Archived)
- `ModelProviderType` (enum: OpenAI, Anthropic, Ollama)
- `ModelIdentifier` (string - e.g., "gpt-4o", "claude-3-5-sonnet")
- `EncryptedApiKey` (string - AES-256 encrypted)
- `SystemPrompt` (text)
- `MaxTokens`, `Temperature`
- `CreatedAt`, `UpdatedAt`, `IsDeleted`

**Relationships:**
- Has many `AgentTools`
- Has many `Conversations`
- Has many `AgentExecutions`

### 2. AgentTool
**Purpose:** Define tools/capabilities available to agents

**Key Fields:**
- `Id` (Guid, PK)
- `AgentId` (FK)
- `ToolType` (enum: WebSearch, CodeExecution, FileAccess, ApiCall, Custom)
- `Name`, `Description`
- `Configuration` (JSON)

### 3. Conversation
**Purpose:** Track message exchanges with agents

**Key Fields:**
- `Id` (Guid, PK)
- `AgentId` (FK)
- `Title`
- `CreatedAt`, `UpdatedAt`

**Relationships:**
- Belongs to `Agent`
- Has many `ConversationMessages`

### 4. ConversationMessage
**Purpose:** Individual messages in conversations

**Key Fields:**
- `Id` (Guid, PK)
- `ConversationId` (FK)
- `Role` (enum: User, Assistant, System)
- `Content` (text)
- `TokenCount` (int)
- `CreatedAt`

### 5. AgentExecution
**Purpose:** Track agent execution runs with metrics

**Key Fields:**
- `Id` (Guid, PK)
- `AgentId` (FK)
- `Status` (enum: Pending, Running, Completed, Failed, Cancelled)
- `StartedAt`, `CompletedAt`
- `InputData`, `OutputData` (JSON)
- `TotalTokensUsed`, `Cost` (decimal)
- `ErrorMessage`

---

## Key Design Patterns

### 1. CQRS (Command Query Responsibility Segregation)
- **Commands:** Write operations (create, update, delete) - return void or single values
- **Queries:** Read operations (get, list) - return typed data
- **Benefits:** Clear separation of concerns, optimized reads vs writes

### 2. Module System (PoweredSoft.Module)
- **AppModule:** Orchestrates all sub-modules
  - **CommandsModule:** Registers all command handlers + validators
  - **QueriesModule:** Registers all query handlers
  - **DalModule:** Registers EF Core DbContext + query overrides

### 3. Repository Pattern (via EF Core)
- `CodexDbContext` provides data access abstraction
- No raw SQL (all queries through LINQ)
- Migrations managed via EF Core CLI

### 4. Result<T> Pattern (Frontend)
- No try-catch blocks in API layer
- All errors via `Result<T>` type (Success or Error)
- Functional error handling

### 5. Contract-First Development
- OpenAPI schema is single source of truth
- Backend exports schema → Frontend generates types
- Type safety across the entire stack

---

## Security Features

### Backend
✅ **AES-256 Encryption** - All API keys encrypted at rest
✅ **Rate Limiting** - 1000 requests/min per client
✅ **CORS Configuration** - Controlled origins
✅ **Global Exception Handling** - No sensitive data leaks
✅ **FluentValidation** - Input validation on all commands

❌ **Missing:** JWT authentication (planned for v2)
❌ **Missing:** HTTPS enforcement in production
❌ **Missing:** API key rotation

### Frontend
✅ **Type Safety** - Strict typing, no dynamic types
✅ **Result<T> Error Handling** - No unhandled exceptions
✅ **API Contract Validation** - Types verified against schema

❌ **Missing:** Authentication token storage
❌ **Missing:** Secure credential handling

---

## Development Workflow

### Backend Setup
```bash
cd BACKEND
docker-compose up -d  # Start PostgreSQL + Ollama
dotnet ef database update --project Codex.Dal
dotnet run --project Codex.Api/Codex.Api.csproj
```

**Verify:** Open http://localhost:5246/swagger

### Frontend Setup
```bash
cd FRONTEND
flutter pub get
flutter run -d macos  # or -d chrome, -d ios
```

### Database Migrations
```bash
# Add new migration
dotnet ef migrations add MigrationName --project Codex.Dal

# Apply migration
dotnet ef database update --project Codex.Dal
```

### API Contract Export
```bash
cd BACKEND
./export-openapi.sh  # Exports to docs/openapi.json
cp docs/openapi.json ../FRONTEND/lib/api-schema.json
```

### Testing
**Backend:**
```bash
cd BACKEND
./test-endpoints.sh  # Manual endpoint testing
```

**Frontend:**
```bash
cd FRONTEND
flutter analyze
flutter test
./scripts/verify_api_types.sh
```

---

## Important Files to Know

### Backend
| File | Purpose | Lines |
|------|---------|-------|
| `BACKEND/Codex.Api/Program.cs` | App startup & configuration | 224 |
| `BACKEND/Codex.Dal/CodexDbContext.cs` | EF Core DbContext | 187 |
| `BACKEND/docs/openapi.json` | API contract (auto-generated) | - |
| `BACKEND/docs/ARCHITECTURE.md` | Design decisions | - |
| `BACKEND/BACKEND-READINESS.md` | MVP completion assessment | - |

### Frontend
| File | Purpose | Lines |
|------|---------|-------|
| `FRONTEND/lib/main.dart` | App entry point | 24 |
| `FRONTEND/lib/console_landing_page.dart` | Main UI shell | 400+ |
| `FRONTEND/lib/api/client.dart` | CQRS API client | 401 |
| `FRONTEND/README_API.md` | API integration guide | 14KB |
| `FRONTEND/.claude-docs/strict-typing.md` | Type safety rules | - |

---

## Current Status

### Backend (Grade: A-)
✅ All 16 endpoints working
✅ Database migrations applied
✅ FluentValidation on all commands
✅ OpenAPI documentation complete
✅ Docker services running (PostgreSQL, Ollama)
✅ AES-256 encryption for API keys
✅ Rate limiting configured
✅ Global exception handling

⚠️ **Ready for:** Local development, internal testing, frontend integration
❌ **Not ready for:** Public internet, production with real users

### Frontend (Grade: Development Phase)
✅ UI shell implemented (ConsoleLandingPage)
✅ Navigation sidebar working
✅ API client layer built
✅ Type-safe endpoint structure
✅ Dark theme with Svrnty branding

⏳ **Pending:** Full API integration, module pages, testing

---

## Key Principles for Development

### Backend (from CLAUDE.md)
1. **Pragmatism over Perfection** - Ship MVP, iterate later
2. **Contract-First** - OpenAPI spec drives all changes
3. **Type Safety** - No dynamic types, strong typing everywhere
4. **Validation First** - All commands validated before execution
5. **Security by Default** - Encrypt sensitive data, validate inputs

### Frontend (from CLAUDE.md)
1. **Strict Typing Only** - No dynamic, var, or untyped code
2. **Result<T> Error Handling** - No try-catch in API layer
3. **API Contract Sync** - Always verify types against schema
4. **Response Protocol** - Structured communication format
5. **Component Reusability** - Build reusable UI components

---

## External Integrations

1. **OpenAI API** - GPT-4o models (API key encrypted)
2. **Anthropic API** - Claude models (API key encrypted)
3. **Ollama** - Local LLM inference (Docker container on port 11434)
4. **PostgreSQL** - Database (Docker container on port 5432)

---

## Future Roadmap (v2+)

### Planned Features
- JWT authentication & authorization
- Real-time execution updates (SignalR/WebSockets)
- Pagination for large datasets
- API key rotation
- Agent templates & marketplace
- Multi-tenancy support
- Advanced metrics & analytics
- Export/import agent configurations

### Known Limitations (MVP v1.0.0)
- No authentication (all endpoints public)
- 100-item limit on list endpoints
- No pagination
- No real-time updates
- Basic error handling (no retry logic)
- Local development only (not production-hardened)

---

## Quick Reference

### Environment Variables
```bash
# Backend
DATABASE_URL=Host=localhost;Database=codex;Username=postgres;Password=postgres
ENCRYPTION_KEY=your-32-character-encryption-key

# Frontend
API_BASE_URL=http://localhost:5246
```

### Default Ports
- Backend API: `5246` (HTTP), `7108` (HTTPS)
- PostgreSQL: `5432`
- Ollama: `11434`
- Flutter Web: `62000` (dev server)

### Key Commands
```bash
# Backend
dotnet build
dotnet run --project Codex.Api/Codex.Api.csproj
dotnet ef migrations add <Name> --project Codex.Dal
dotnet ef database update --project Codex.Dal
./export-openapi.sh

# Frontend
flutter pub get
flutter run -d macos
flutter build macos
flutter analyze
flutter test

# Docker
docker-compose up -d
docker-compose down
docker-compose logs -f
```

---

## Documentation Index

### Backend Docs
- `/BACKEND/README.md` - Overview
- `/BACKEND/CLAUDE.md` - Development guidelines
- `/BACKEND/docs/ARCHITECTURE.md` - Design decisions
- `/BACKEND/docs/COMPLETE-API-REFERENCE.md` - Endpoint docs
- `/BACKEND/BACKEND-READINESS.md` - MVP assessment
- `/BACKEND/DEPLOYMENT_STATUS.md` - Deployment readiness

### Frontend Docs
- `/FRONTEND/README.md` - Overview
- `/FRONTEND/README_API.md` - API integration guide (14KB)
- `/FRONTEND/CLAUDE.md` - Development guidelines
- `/FRONTEND/.claude-docs/strict-typing.md` - Type safety rules
- `/FRONTEND/.claude-docs/response-protocol.md` - Response protocol
- `/FRONTEND/.claude-docs/api-contract-workflow.md` - API workflow

---

## Contact & Support

**Project Name:** CODEX_ADK (Svrnty Console)
**Version:** MVP v1.0.0
**Status:** Backend Ready, Frontend Integration Pending
**License:** (Not specified)
**Repository:** (Local development - no remote specified)

---

*This context document was generated on 2025-10-26 by Claude Code based on comprehensive codebase analysis.*
