AI Development Guide - Structum LabΒΆ
Guide completa per sviluppo AI-assisted (Agent & Chat-based)
π IndiceΒΆ
π― Project CharterΒΆ
VisionΒΆ
Structum Γ¨ lβinfrastruttura invisibile per applicazioni Python production-ready.
Non Γ¨ un framework web/CLI/ORM. Γ il layer fondazionale che gestisce:
Configuration management
Logging & Observability
Database connections
Authentication & Authorization
Caching & Storage
Message queues & Background jobs
CLI tooling
MissionΒΆ
Agnostic, Modular, Production-Ready
Agnostic by Design: Solo Protocol interfaces, nessun lock-in
Modulare: Core minimalista + plugin opzionali
Production-Ready: Ogni feature Γ¨ enterprise-grade dallβinizio
ArchitetturaΒΆ
packages/
βββ core/src/structum_lab/ # Framework core (Protocols + base)
βββ dynaconf/src/structum_lab/ # Configuration plugin
βββ observability/src/structum_lab/ # Logging & metrics plugin
βββ auth/src/structum_lab/ # Authentication (in development)
βββ database/src/structum_lab/ # Database interfaces (in development)
βββ di/src/structum_lab/ # Dependency Injection
βββ bootstrap/src/structum_lab/ # Bootstrap & initialization
Principio fondamentale: Il core contiene SOLO Protocol interfaces. Nessuna logica.
Plugin RoadmapΒΆ
PrioritΓ :
structum_database (Critical) - Connection pooling + ORM-agnostic
structum_auth (Critical) - JWT + OAuth2 + RBAC
structum_cli (High, Core) - Typer + Rich CLI infrastructure
structum_storage (High) - S3/Local/Azure abstraction
structum_messaging (High) - Redis Streams/RabbitMQ/Kafka
structum_cache (High) - Redis/Memcached
structum_jobs (Medium) - Celery background workers
structum_testing (Low) - Fixtures + mocks per tutti i plugin
π€ AI Primer - Context EssenzialeΒΆ
Cosa Deve Sapere un AIΒΆ
1. Filosofia del ProgettoΒΆ
Vibe Coding Ready: Il progetto Γ¨ progettato per AI development.
ROADMAP dettagliata (~2200 righe) con esempi completi
Ogni plugin ha spec complete con codice runnable
Pattern standardizzati e ripetibili
Anti-pattern documentati
2. Struttura RepositoryΒΆ
structum-lab/
βββ packages/ # Monorepo packages
β βββ core/src/structum_lab/ # Core interfaces & base
β βββ dynaconf/src/structum_lab/ # Config (COMPLETE)
β βββ observability/src/structum_lab/ # Logs+Metrics (COMPLETE)
β βββ auth/src/structum_lab/ # Authentication (WIP)
β βββ database/src/structum_lab/ # Database (WIP)
β βββ di/src/structum_lab/ # Dependency Injection (COMPLETE)
β βββ bootstrap/src/structum_lab/ # Bootstrap (COMPLETE)
βββ demo/ # Demo suite
β βββ 01-logging-basics/ # Logging fundamentals
β βββ 02-observability-full/ # Metrics + context
β βββ 03-zero-config/ # Auto-discovery
β βββ 04-web-integration/ # FastAPI integration
β βββ 05-standalone-plugins/ # Plugins without DI
β βββ 10-di-fastapi/ # DI with FastAPI
β βββ archive/ # Legacy demos
βββ docs/ # MkDocs documentation
βββ ROADMAP.md # Plugin development guide
βββ pyproject.toml # Root monorepo config
3. Detailed explanation of core modules architectureΒΆ
1. Agnostic by Design
# Core: Solo l'interfaccia
class DatabaseInterface(Protocol):
def get_connection(self) -> Connection: ...
def transaction(self) -> ContextManager: ...
# Plugin: Implementazione concreta (SQLAlchemy, psycopg, etc.)
class SQLAlchemyDatabase(DatabaseInterface):
# Implementazione specifica
Principio: Lβapplicazione dipende dallβinterfaccia, non dallβimplementazione.
β Permette di cambiare backend senza riscrivere codice.
2. Modulare & StratificatoΒΆ
Architettura a 3 layer:
βββββββββββββββββββββββββββββββββββββββ
β Application (demo) β β Usa le interfaces
βββββββββββββββββββββββββββββββββββββββ€
β Plugins (dynaconf, observability) β β Implementazioni concrete
βββββββββββββββββββββββββββββββββββββββ€
β Core (structum_lab) β β Solo Protocols
βββββββββββββββββββββββββββββββββββββββ
Principio: Il core Γ¨ minimalista, i plugin sono opzionali.
β Installi solo ciΓ² che ti serve.
Core Modules ClarificationΒΆ
Important: Il core ha 3 moduli built-in:
packages/core/src/structum_lab/
βββ config/ # ConfigInterface protocol
βββ logging/ # LoggerInterface protocol
βββ monitoring/ # MetricsInterface protocol
βββ auth/ # AuthInterface protocol
βββ database/ # DatabaseInterface protocol
βββ plugins/ # Plugin system base
Il core contiene principalmente interfaces (Protocols)!
Le implementazioni sono in package separati:
packages/
βββ dynaconf/src/structum_lab/
β βββ DynaconfConfigProvider implements ConfigInterface
βββ observability/src/structum_lab/
βββ StructuredLogger implements LoggerInterface
βββ PrometheusMetrics implements MetricsInterface
Pattern:
Core Module β Package Implementation
-------------- ----------------------
config/ β packages/dynaconf/
logging/ β packages/observability/ (logging part)
monitoring/ β packages/observability/ (Prometheus part)
auth/ β packages/auth/
database/ β packages/database/
Why bundle logging + monitoring in one plugin?
βObservabilityβ is a unified concept
Same backend often provides both (Datadog, Prometheus+Loki)
Reduces plugin proliferation
Industry standard pattern
Why these 3 modules in core?
config: Needed by ALL plugins (get_config())
logging: Needed for debugging (get_logger())
monitoring: Needed for production observability (get_metrics())
All 3 have NoOp fallbacks, so core has zero external dependencies!
3. Plugin Development PatternΒΆ
SEMPRE seguire questo ordine:
# 1. Core Interface (Protocol)
# packages/core/src/structum_lab/database/interfaces.py
class DatabaseInterface(Protocol):
def get_connection(self) -> Connection: ...
def transaction(self) -> ContextManager: ...
def health_check(self) -> Dict[str, Any]: ...
# 2. Plugin Implementation
# packages/database/src/structum_lab/sqlalchemy.py
class SQLAlchemyDatabase(DatabaseInterface):
# Implementazione concreta
def __init__(self):
cfg = get_config() # SEMPRE da config
self._metrics = get_metrics("structum.database") # SEMPRE emit metrics
self._log = get_logger(__name__) # SEMPRE structured logging
Checklist Obbligatorio per ogni plugin:
β Protocol nel core
β Config-driven (no hardcoded)
β Metrics emission
β Structured logging
β Health checks
β Graceful shutdown
β Documentation
β Tests
4. Code Style & StandardsΒΆ
Type Hints: 100% coverage, mypy strict mode
from typing import Protocol, Dict, Any, Optional
def get_config(profile: Optional[str] = None) -> Dict[str, Any]:
...
Naming Conventions:
Interfaces:
XyzInterface(Protocol)Implementations:
ConcreteXyz(es.SQLAlchemyDatabase)Plugin prefix:
structum_(es.structum_database)
Imports: Core mai dipende da plugin
# β
CORRETTO (plugin importa core)
from structum_lab.config import get_config
# β SBAGLIATO (core importa plugin)
from structum_database import SQLAlchemy # NO!
5. Documentation RequirementsΒΆ
Per ogni plugin:
README.md- Quick startdocs/- Detailed guidesEsempi in
demo/Entry in main
ROADMAP.md
π€ Guida per AI Agent (Agentic)ΒΆ
Scenario: AI con accesso diretto alla codebase via IDE tools.
Capabilities DisponibiliΒΆ
LβAI Agent puΓ²:
β Leggere/scrivere file
β Eseguire comandi (git, pytest, mypy)
β Navigare codebase
β Run tests
β Commit changes
Workflow ConsigliatoΒΆ
Step 1: PlanningΒΆ
1. Leggi ROADMAP.md sezione del plugin target
2. Verifica architettura esistente in packages/core/
3. Identifica dependencies (altri plugin)
4. Crea implementation_plan.md artifact
Step 2: ImplementationΒΆ
1. Crea Protocol in packages/core/src/structum_lab/[nome]/interfaces.py
2. Crea __init__.py in packages/core/src/structum_lab/[nome]/
3. Crea package dir in packages/[nome]/
4. Crea src/structum_lab/ in packages/[nome]/src/structum_lab/
5. Implementa concrete class
6. Aggiungi health checks
7. Aggiungi metrics
8. Crea tests
Step 3: IntegrationΒΆ
1. Update demo app in demo/
2. Create documentation in docs/
3. Update ROADMAP.md con progress
4. Run full test suite
Step 4: QualityΒΆ
# L'AI deve eseguire questi comandi:
mypy src/ --strict
pytest tests/ -v --cov
ruff check src/
black --check src/
Comandi ChiaveΒΆ
# Setup
pip install -e packages/core
pip install -e packages/[nome]
# Development
pytest tests/ -v
mypy packages/*/src/ --strict
ruff check packages/*/src/
# Documentation
mkdocs serve
# Git
git add -A
git commit -m "feat(plugin): add [nome] package"
git push
File da Creare (Template)ΒΆ
Core Interface:
# packages/core/src/structum_lab/[nome]/interfaces.py
from typing import Protocol, Dict, Any
class [Nome]Interface(Protocol):
"""Protocol for [description]."""
def operation(self) -> Any:
"""[Docstring]."""
...
def health_check(self) -> Dict[str, Any]:
"""Return health status."""
...
def shutdown(self) -> None:
"""Graceful shutdown."""
...
Plugin Implementation:
# packages/[nome]/src/structum_lab/provider.py
from structum_lab.[nome] import [Nome]Interface
from structum_lab.config import get_config
from structum_lab.monitoring import get_metrics
from structum_lab.logging import get_logger
class Concrete[Nome]([Nome]Interface):
def __init__(self):
self.cfg = get_config()
self.metrics = get_metrics("structum.[nome]")
self.log = get_logger(__name__)
# Setup based on config
def operation(self) -> Any:
# Emit metrics
self.metrics.increment("operations.total")
self.log.info("Operation executed")
...
def health_check(self) -> Dict[str, Any]:
return {"status": "healthy"}
def shutdown(self):
self.log.info("Shutting down")
# Cleanup
π¬ Guida per AI Chat-basedΒΆ
Scenario: AI senza accesso diretto al codice, solo chat.
Context NecessarioΒΆ
Lβutente deve fornire:
Link a ROADMAP.md
Sezione specifica del plugin da implementare
File esistenti rilevanti (se modifiche)
AI Response PatternΒΆ
LβAI dovrebbe:
Confermare comprensione del task
Elencare file da creare
Fornire codice completo per ogni file
Includere comandi da eseguire
Specificare test da scrivere
Example InteractionΒΆ
User: βImplementa structum_database Phase 1 (SQLAlchemy)β
AI Response Structure:
## Implementation Plan
Files to create:
1. packages/core/src/structum_lab/database/interfaces.py
2. packages/core/src/structum_lab/database/__init__.py
3. packages/database/src/structum_lab/sqlalchemy.py
4. tests/test_database.py
## File 1: Core Interface
[Complete code block]
## File 2: Plugin Implementation
[Complete code block]
## Commands to Run
```bash
# Create directories
mkdir -p packages/database/src/structum_lab
mkdir -p packages/core/src/structum_lab/database
# Create files
[Step by step]
# Test
pytest tests/test_database.py -v
Next StepsΒΆ
Review code
Run tests
Update ROADMAP.md progress
---
## π Workflow Operativi
### Workflow 1: Nuovo Plugin (da Zero)
```markdown
1. READ: ROADMAP.md sezione plugin
2. CREATE: Core interface in packages/core/
3. CREATE: Package implementation in packages/
4. CREATE: Tests in tests/
5. CREATE: Documentation in docs/
6. UPDATE: Demo in demo/
7. RUN: Quality checks (mypy, pytest, ruff)
8. COMMIT: Changes with conventional commits
9. UPDATE: ROADMAP.md progress
Workflow 2: Estendere Plugin EsistenteΒΆ
1. READ: Existing plugin code
2. IDENTIFY: Integration points
3. EXTEND: Add new methods to interface
4. IMPLEMENT: New methods in concrete class
5. UPDATE: Tests
6. UPDATE: Documentation
7. RUN: Full test suite
8. COMMIT: Changes
Workflow 3: Fix BugΒΆ
1. READ: Bug report / failing test
2. LOCATE: Root cause in code
3. FIX: Issue with minimal change
4. ADD: Regression test
5. VERIFY: All tests pass
6. COMMIT: Fix with issue reference
β Quality GatesΒΆ
Pre-commit (Obbligatori)ΒΆ
# Type checking
mypy src/ --strict
# Exit code must be 0
# Code formatting
black src/ --check
# Exit code must be 0
# Linting
ruff check src/
# Exit code must be 0
# Tests
pytest tests/ -v --cov --cov-report=term-missing
# Coverage must be >90%
Pre-merge (Obbligatori)ΒΆ
# All pre-commit checks +
# Integration tests
pytest tests/integration/ -v
# Documentation build
mkdocs build --strict
# Security scan
bandit -r src/
# Dependency check
safety check
Success CriteriaΒΆ
Un plugin Γ¨ completo quando:
β Protocol nel core
β Almeno 1 implementazione concreta
β Usato in almeno 1 demo
β Documentazione completa
β Test coverage >90%
β Mypy strict passa
β Security scan pulito
β Health checks implementati
π Conventional CommitsΒΆ
Format:
<type>(<scope>): <description>
[optional body]
[optional footer]
Types:
feat: New featurefix: Bug fixdocs: Documentationrefactor: Code refactoringtest: Test changeschore: Maintenance
Examples:
feat(database): add SQLAlchemy provider
fix(auth): handle expired JWT tokens
docs(roadmap): update plugin priorities
refactor(cache): extract Redis client to separate class
test(messaging): add integration tests for pub/sub
chore(deps): update dependencies
π― Quick ReferenceΒΆ
File LocationsΒΆ
Component |
Location |
Purpose |
|---|---|---|
Core Interfaces |
|
Protocol definitions |
Package Implementations |
|
Concrete implementations |
Demos |
|
Usage examples |
Docs |
|
MkDocs documentation |
Tests |
|
Test suite |
Roadmap |
|
Development guide |
Key CommandsΒΆ
# Development
pip install -e packages/core
pip install -e "packages/dynaconf[dev]"
pip install -e "packages/observability[dev]"
# Quality
mypy packages/*/src/ --strict && pytest tests/ -v && ruff check packages/*/src/
# Documentation
mkdocs serve # http://localhost:8000
# Git
git add -A
git commit -m "feat(scope): description"
git push origin main
Key Files to Read FirstΒΆ
ROADMAP.md - Complete development guide
packages/core/src/structum_lab/config/interface.py - Example protocol
packages/dynaconf/src/structum_lab/core/provider.py - Example implementation
demo/01-logging-basics/ - Working demo
docs/modules/monitoring.md - Documentation example
π Getting Started (AI Checklist)ΒΆ
Prima di iniziare qualsiasi task:
[ ] Ho letto ROADMAP.md?
[ ] Ho capito lβarchitettura core/plugins?
[ ] So quale plugin devo implementare?
[ ] Ho verificato le dependencies?
[ ] Ho identificato i file da creare/modificare?
Durante implementation:
[ ] Sto seguendo il pattern Protocol β Implementation?
[ ] Sto usando get_config() per configuration?
[ ] Sto emettendo metrics?
[ ] Sto loggando con structured logger?
[ ] Ho aggiunto health checks?
[ ] Ho implementato graceful shutdown?
Prima di commit:
[ ] mypy passa?
[ ] pytest passa?
[ ] Coverage >90%?
[ ] Documentation aggiornata?
[ ] Demo aggiornata?
[ ] ROADMAP aggiornata?
Il progetto Γ¨ AI-ready. Happy coding! π€β¨