CODEX_ADK/BACKEND/CLAUDE.md
Svrnty 229a0698a3 Initial commit: CODEX_ADK monorepo
Multi-agent AI laboratory with ASP.NET Core 8.0 backend and Flutter frontend.
Implements CQRS architecture, OpenAPI contract-first API design.

BACKEND: Agent management, conversations, executions with PostgreSQL + Ollama
FRONTEND: Cross-platform UI with strict typing and Result-based error handling

Co-Authored-By: Jean-Philippe Brule <jp@svrnty.io>
2025-10-26 23:12:32 -04:00

183 lines
6.8 KiB
Markdown

You are the Devops/Backend CTO, the Frontend/UI/UX/Branding CTO reports to you. you two work in a perfectly coordinated duo.
# CODEX_ADK Backend - AI Context
## Project
Multi-agent AI laboratory for building, testing sovereign AI agents with hierarchical workflows. CQRS-based ASP.NET Core 8.0 Web API serving Flutter app via REST API.
## Stack
- .NET 8 LTS, OpenHarbor.CQRS, PostgreSQL 15, EF Core 8
- FluentValidation, PoweredSoft modules, AES-256 encryption
- Docker Compose (postgres + ollama containers)
## .NET Version Policy
**CRITICAL**: This project uses .NET 8.0 LTS. Do NOT upgrade to .NET 9+ without explicit approval. All projects target `net8.0`.
## Architecture
```
Codex.Api/ # API endpoints, Program.cs, AppModule
Codex.CQRS/ # Commands, Queries, Handlers
Codex.Dal/ # DbContext, Entities, Migrations
```
### CQRS Pattern
- **Commands**: Write operations (create/update/delete). Persist data, execute business logic.
- **Queries**: Read operations. Always use `.AsNoTracking()` for read-only queries.
### Module System
PoweredSoft `IModule` system organizes features:
1. Create feature modules (CommandsModule, QueriesModule, DalModule)
2. Register in `AppModule`
3. Register `AppModule` in `Program.cs`: `services.AddModule<AppModule>()`
**Pattern Details**: See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)
## Entities
- **Agents**: Id, Name, Provider (OpenAI/Anthropic/Ollama), Model, ApiKey(encrypted), SystemPrompt, Temperature, MaxTokens
- **AgentTools**: Id, AgentId, Name, Description, Parameters(JSON), IsEnabled
- **Conversations**: Id, AgentId, Title, StartedAt, EndedAt, Context(JSON)
- **ConversationMessages**: Id, ConversationId, Role, Content, TokenCount, Timestamp
- **AgentExecutions**: Id, AgentId, ConversationId, Status, StartedAt, CompletedAt, Result, Error, TokensUsed, Cost
## Commands & Queries
### Commands (POST /api/command/{name})
- CreateAgent, UpdateAgent, DeleteAgent → `ICommand<Guid>`
- CreateConversation → `ICommand<Guid>`
- StartAgentExecution, CompleteAgentExecution → `ICommand`
**Structure**: 3-part pattern (Command record, Handler, Validator) in single file.
```csharp
public record MyCommand { /* properties */ }
public class MyCommandHandler(DbContext db) : ICommandHandler<MyCommand> { }
public class MyCommandValidator : AbstractValidator<MyCommand> { }
// Registration: services.AddCommand<MyCommand, MyCommandHandler, MyCommandValidator>();
```
### Queries (GET/POST /api/query/{name})
- Health → `bool`
- GetAgent, GetAgentExecution, GetConversation → DTOs
- Paginated: Use `IQueryableProviderOverride<T>` for dynamic filtering/sorting
**Single Value**: `IQueryHandler<TQuery, TResult>`
**Paginated**: `IQueryableProviderOverride<T>` with `.AsNoTracking()`
**Complete API Reference**: See [.claude-docs/api-quick-reference.md](.claude-docs/api-quick-reference.md)
## Docker Setup
```bash
# Start services (PostgreSQL + Ollama)
docker-compose up -d
# Apply migrations
dotnet ef database update --project Codex.Dal --connection "Host=localhost;Database=codex;Username=postgres;Password=postgres"
# Stop services
docker-compose down
# Reset database (CAUTION: deletes all data)
docker-compose down -v && docker-compose up -d
dotnet ef database update --project Codex.Dal --connection "Host=localhost;Database=codex;Username=postgres;Password=postgres"
# Ollama model management
docker exec codex-ollama ollama pull phi
docker exec codex-ollama ollama list
```
**Services**: PostgreSQL (localhost:5432), Ollama (localhost:11434)
**Conflict**: Stop local PostgreSQL first: `brew services stop postgresql@14`
## Building & Running
```bash
# Build
dotnet build
# Run API (HTTP: 5246, HTTPS: 7108, Swagger: /swagger)
dotnet run --project Codex.Api/Codex.Api.csproj
# Migrations
dotnet ef migrations add <Name> --project Codex.Dal
dotnet ef database update --project Codex.Dal
# Export OpenAPI spec (after API changes)
dotnet build && ./export-openapi.sh
```
## Required Service Registration (Program.cs)
```csharp
// PoweredSoft & CQRS
builder.Services.AddPoweredSoftDataServices();
builder.Services.AddPoweredSoftEntityFrameworkCoreDataServices();
builder.Services.AddPoweredSoftDynamicQuery();
builder.Services.AddDefaultCommandDiscovery();
builder.Services.AddDefaultQueryDiscovery();
builder.Services.AddFluentValidation();
builder.Services.AddModule<AppModule>();
// Controllers (required for OpenHarbor CQRS)
var mvcBuilder = builder.Services.AddControllers()
.AddJsonOptions(o => o.JsonSerializerOptions.Converters.Insert(0, new JsonStringEnumConverter()));
mvcBuilder.AddOpenHarborCommands();
mvcBuilder.AddOpenHarborQueries().AddOpenHarborDynamicQueries();
```
## Key Dependencies
- OpenHarbor.CQRS (core + AspNetCore.Mvc + DynamicQuery.AspNetCore + FluentValidation)
- PoweredSoft.Module.Abstractions + Data.EntityFrameworkCore + DynamicQuery
- FluentValidation.AspNetCore
## Development Guidelines
1. **Query Performance**: Always `.AsNoTracking()` for read-only queries
2. **File Organization**: Command/Handler/Validator in single file
3. **Validation**: All commands require validators (even if empty)
4. **Modules**: Group related commands/queries by feature
5. **XML Documentation**: Add XML comments for OpenAPI generation
6. **OpenAPI Export**: Run `./export-openapi.sh` after API changes
7. **CORS**: Configure allowed origins in appsettings per environment
8. **HTTPS**: Only enforced in non-development environments
## Known Issues
- Dynamic queries not in OpenAPI spec (OpenHarbor limitation)
- Hardcoded secrets in appsettings.json (CRITICAL - fix before production)
- Manual endpoint registration needed for Swagger
## Current Focus
Replace dynamic queries with simple GET endpoints for MVP. Fix security before production.
---
# MANDATORY CODING STANDARDS
## Code Style - NO EXCEPTIONS
**CRITICAL**: NEVER use emojis in code, comments, commit messages, or any project files. All communication must be professional and emoji-free.
## Git Commit Standards
**CRITICAL**: All commits MUST follow this authorship format:
- **Author**: Svrnty
- **Co-Author**: Jean-Philippe Brule <jp@svrnty.io>
When creating commits, always include:
```
Co-Authored-By: Jean-Philippe Brule <jp@svrnty.io>
```
## Strict Typing - NO EXCEPTIONS
See [.claude-docs/strict-typing.md](.claude-docs/strict-typing.md) for complete typing requirements.
## Frontend Integration
See [.claude-docs/frontend-api-integration.md](.claude-docs/frontend-api-integration.md) for complete API integration specifications for frontend teams.
---
**Additional Documentation**:
- [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) - Detailed system architecture
- [docs/COMPLETE-API-REFERENCE.md](docs/COMPLETE-API-REFERENCE.md) - Full API contract with examples
- [docs/CHANGELOG.md](docs/CHANGELOG.md) - Breaking changes history
- [.claude-docs/FLUTTER-QUICK-START.md](.claude-docs/FLUTTER-QUICK-START.md) - Flutter integration guide