Kuzu Event Bus - AI Coding Agent Instructions
Guides AI coding agents to build a multi-tenant Kuzu graph database service with hexagonal architecture, TDD, and DDD.
What this file does
Guides AI coding agents to build a multi-tenant Kuzu graph database service with hexagonal architecture, TDD, and DDD.
When to use it
- You want an AI agent to follow strict hexagonal architecture and TDD
- You are building a multi-tenant service with Kuzu graph database
- You need a consistent pattern for protocol-based ports and dependency injection
- You want to enforce YAGNI and fail-fast principles in code generation
Assumes this stack
trigger: always_on
Kuzu Event Bus - AI Coding Agent Instructions
šÆ Project Overview
Multi-tenant Kuzu graph database service with FastAPI and hexagonal architecture. Core mission: Simple, testable, evolvable service following Clean Architecture, TDD (Test-Driven Development), DDD (Domain-Driven Design), and YAGNI principles, failfast and logs.
šļø Architecture Fundamentals
Hexagonal Architecture (STRICT)
src/
āāā domain/ # Pure business logic (CustomerAccount, TenantName)
āāā application/ # Use case orchestration (CustomerAccountService)
āāā infrastructure/ # Technical adapters (InMemoryTenantRepository)
āāā presentation/ # FastAPI controllers (customers, databases, health)
CRITICAL: Domain never depends on infrastructure. Use Protocol-based ports for dependency inversion.
YAGNI Strategy
- Start simple: Memory-based implementations for MVP
- Migrate progressively: PostgreSQL/Redis only when metrics justify
- No over-engineering: One feature at a time
Development Methodologies
- TDD (Test-Driven Development): Red-Green-Refactor cycle mandatory
- DDD (Domain-Driven Design): Business logic drives architecture
- Fail Fast: Explicit validation, immediate error detection
š Development Workflow
Test-First Development (TDD)
# Run tests (from backend/)
pytest # All tests
pytest tests/unit/ # Unit tests only
pytest tests/integration/ # Integration tests
pytest --cov=src # With coverage
TDD Cycle: Red (failing test) ā Green (minimal code) ā Refactor (improve)
Test Structure: tests/{unit,integration,e2e}/ mirroring src/ structure
Development Environment
# Setup (from backend/)
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
# Services
docker-compose up -d # Redis, PostgreSQL, MinIO
# Run API server
uvicorn src.presentation.api.main:app --reload
šÆ Core Patterns & Conventions
1. Protocol-Based Ports (Not ABC)
# ā
GOOD: Port in domain/shared/ports/
@runtime_checkable
class CustomerAccountRepository(Protocol):
async def save(self, customer: CustomerAccount) -> str: ...
# ā
GOOD: Adapter in infrastructure/
class InMemoryCustomerRepository:
async def save(self, customer: CustomerAccount) -> str:
# Implementation
2. Immutable Value Objects
@dataclass(frozen=True)
class TenantName:
value: str
def __post_init__(self):
if len(self.value) < 3:
raise ValidationError("Must be at least 3 characters")
if not re.match(r'^[a-z0-9-]+$', self.value):
raise ValidationError("Invalid characters")
3. Explicit Exception Handling
# ā
GOOD: Specific business exceptions
class BusinessRuleViolation(Exception): pass
class ValidationError(Exception): pass
# ā
GOOD: Fail fast validation
if not tenant_name:
raise ValidationError("Tenant name required")
# ā BAD: Silent failures
if not tenant_name:
return None
4. FastAPI Dependency Injection
# ā
GOOD: Factory functions for YAGNI
def get_customer_service() -> CustomerAccountService:
return CustomerAccountService(
account_repository=InMemoryTenantRepository(),
auth_service=SimpleAuthService(),
)
# Use in endpoints
@router.post("/register")
async def register(
request: CustomerRegistrationRequest,
service: CustomerAccountService = Depends(get_customer_service)
):
5. API Key Pattern
# ā
GOOD: Consistent format with prefix
def generate_api_key() -> str:
return f"kb_{secrets.token_urlsafe(32)}"
# ā
GOOD: Format validation
if not api_key.startswith("kb_"):
raise ValidationError("Invalid API key format")
š ļø Key Implementation Details
Multi-Tenant Isolation
- Customer: Top-level account entity
- Tenant: Isolated workspace within customer
- Storage: Tenant-specific folders in MinIO (
/{tenant_name}/databases/)
Authentication Middleware
Located in src/api/middleware/authentication.py - validates API keys across all endpoints except health checks.
Current MVP Scope
Implemented:
- ā Customer registration with API key generation
- ā
Health checks (
/health/) - ā Architecture foundation
- ā 84+ passing tests
Next priorities:
- API key authentication on endpoints
- Database management endpoints
- Query execution basics
- Migration to persistent storage (only when needed)
šÆ Code Generation Guidelines
When generating code:
- Type hints mandatory - MyPy must pass
- Async/await for all I/O operations
- Domain language - Use business vocabulary (CustomerAccount, not User)
- Protocol over ABC - Use
@runtime_checkableprotocols - Frozen dataclasses - For all value objects
- Test-first - Write failing test before implementation
- Repository pattern - For all data persistence
- Dependency injection - Use FastAPI Depends()
Critical File Management Rules
- Explicit file names -
customer_account_service.py, notservice.py - Respect hexagonal layers - Never put domain logic in infrastructure files
- Modify existing files - Don't recreate files that already exist, update them
- Follow existing structure - Check
src/layout before creating new files
Example: Adding New Domain Entity
# 1. Value object
@dataclass(frozen=True)
class DatabaseName:
value: str
def __post_init__(self): # validation
# 2. Port (interface)
class DatabaseRepository(Protocol):
async def save(self, db: Database) -> str: ...
# 3. Entity
@dataclass
class Database:
name: DatabaseName
tenant_id: str
# 4. Test first
def test_database_creation():
db = Database(DatabaseName("test-db"), "tenant-123")
assert db.name.value == "test-db"
# 5. Service
class DatabaseManagementService:
def __init__(self, repository: DatabaseRepository): ...
š Key Files to Reference
src/domain/shared/ports/- All protocol definitionssrc/domain/tenant_management/customer_account.py- Core entity patternssrc/infrastructure/memory/- YAGNI implementation examplessrc/api/routers/customers.py- FastAPI endpoint patternspyproject.toml- Test configuration and dependencies
Focus on following existing patterns rather than introducing new approaches. The codebase prioritizes consistency and simplicity over clever solutions.
ā ļø Important Constraints
- NEVER recreate existing files - Always modify/extend existing implementations
- Respect hexagonal boundaries - Domain code stays in
domain/, infrastructure ininfrastructure/ - Use explicit naming - File names must clearly indicate their purpose and layer
- Check existing structure first - Use semantic search to understand current implementation before adding new code
- NO "Enhanced" prefixes - Never create files with "Enhanced", "Improved", "Better" or similar prefixes. Instead, merge enhanced functionality directly into existing components or create new files with descriptive names
- Avoid duplication - Always merge functionality into existing components rather than creating duplicated files with prefix variations
What's inside
10 sections covering architecture, workflow, patterns, implementation details, and constraints with 6 code examples
Change this for your project
- Replace
superWorldSavior/KuzuEventBuswith your own repository name - Replace
src/with your project's source directory if different - Replace
backend/with your project's backend directory if different
Where it goes
Save in docs/ or the repository root. Gives agents and new contributors a map of the codebase.
Worth borrowing
- Protocol-based ports over ABC for dependency inversion
- Frozen dataclasses for immutable value objects with validation in __post_init__
- Explicit business exceptions instead of silent returns
Related Documents
PCB Design Sources for Industry-Scale Testing
Lists GitHub repos and communities where you can download real PCB designs for testing optimization at scale.
Design Document: BharatSeva AI
Describes a 10-agent AWS system that helps India's informal workers access government schemes via voice-first, serverless architecture.
OpenClaw Enterprise Transformation Plan
Transforms a single-user AI agent into a dual-mode platform supporting both viral open-source and Fortune 500 enterprise deployments through phased security, IAM, audit, multi-tenancy, and Kubernetes features.
Qwen Image and Edit: Open-sourcing and Local GGUF Generations with Lightning
Documents the Qwen-Image and Qwen-Image-Edit models, covering architecture, training, benchmarks, ComfyUI setup, and prompting techniques for local GGUF deployment.