Files
sta/specs/constitution.md

244 lines
9.0 KiB
Markdown
Raw Normal View History

<!--
SYNC IMPACT REPORT
==================
Version Change: 1.0.0 → 1.1.0
Amendment Date: 2025-12-27
Type: MINOR - New principle added
Modified Principles:
- Principle I: Enhanced with explicit SOLID principles reference
Added Sections:
- New Principle VI: SOLID Principles
Removed Sections:
- None
Templates Status:
✅ plan-template.md - already aligned
✅ spec-template.md - already aligned
✅ spec-checklist.md - already aligned
✅ tasks-template.md - already aligned
Follow-up TODOs:
- None (all changes integrated)
Rationale:
Adding SOLID principles as an explicit constitutional principle reinforces
the existing clean architecture and hexagonal architecture principles with
concrete design guidelines. This is a MINOR bump because it adds new
governance guidance without changing existing principles.
-->
# STA (Smart Temperature & Appliance Control) Constitution
## Core Principles
### I. Hexagonal Architecture (Clean Architecture)
The system MUST follow hexagonal architecture principles with clear separation of concerns:
- **Domain Layer**: Pure business logic with no external dependencies
- **Application Layer**: Use cases and orchestration logic
- **Infrastructure Layer**: External concerns (HTTP, Modbus, persistence)
- **Presentation Layer**: API contracts and DTOs
All dependencies MUST point inward. Infrastructure and presentation layers depend on domain/application, never the reverse. This ensures testability, maintainability, and framework independence.
**SOLID Alignment**: This principle directly enforces Dependency Inversion Principle (DIP) through inward-pointing dependencies and Interface Segregation Principle (ISP) through layer boundaries.
**Rationale**: Hexagonal architecture enables independent testing of business logic, technology substitution without domain changes, and clear ownership boundaries between layers.
### II. Domain-Driven Design
The domain model MUST be rich and expressive:
- Domain entities encapsulate business rules and invariants
- Value objects are immutable and self-validating
- Repositories abstract persistence concerns
- Services contain domain logic that doesn't belong to entities
- Clear ubiquitous language shared between code and specifications
Domain types MUST NOT leak across architectural boundaries. DTOs and domain entities are distinct.
**Rationale**: DDD ensures the codebase reflects real-world domain concepts, making it easier to reason about, maintain, and evolve as business requirements change.
### III. Test-First Development (NON-NEGOTIABLE)
TDD is mandatory for all feature development:
1. Write failing tests first
2. User reviews and approves test scenarios
3. Implement minimal code to pass tests
4. Refactor while keeping tests green
Test coverage MUST include:
- Unit tests for domain logic (isolated, fast)
- Integration tests for infrastructure adapters (Modbus, HTTP)
- Contract tests for API endpoints
- Mock-based tests to avoid hardware dependencies during CI
**Rationale**: Test-first ensures specifications are validated before implementation, prevents regression, and serves as executable documentation. The red-green-refactor cycle enforces disciplined development.
### IV. API-First Design
All functionality MUST be exposed through well-defined API contracts:
- RESTful HTTP API for web interface (Poem + OpenAPI)
- Modbus TCP protocol for relay hardware communication
- Clear separation between public API contracts and internal implementation
- OpenAPI specifications generated and maintained automatically
- API versioning strategy for backward compatibility
Backend (Rust) and frontend (TypeScript/Vue) communicate exclusively through documented API contracts.
**Rationale**: API-first design enables parallel frontend/backend development, clear integration points, and prevents tight coupling between presentation and business logic.
### V. Observability & Monitoring
Production systems MUST be observable:
- Structured logging at all architectural boundaries (tracing crate)
- Request/response logging for HTTP and Modbus communication
- Health check endpoints for system status
- Error context preserved across layer boundaries (thiserror)
- JSON log format for production environments
- Human-readable format for development
Debugging MUST be possible without modifying code.
**Rationale**: Observability enables rapid diagnosis of production issues, performance analysis, and understanding system behavior under real-world conditions.
### VI. SOLID Principles
All code MUST adhere to SOLID design principles:
**Single Responsibility Principle (SRP)**:
- Each module, class, or function has ONE reason to change
- Domain entities focus on business rules only
- Infrastructure adapters focus on external integration only
- Controllers/handlers focus on request orchestration only
**Open/Closed Principle (OCP)**:
- Entities open for extension via traits/interfaces
- Closed for modification through trait implementations
- New behavior added through new implementations, not modifications
**Liskov Substitution Principle (LSP)**:
- Trait implementations MUST be substitutable without breaking behavior
- Mock implementations MUST honor trait contracts
- Repository implementations MUST preserve domain semantics
**Interface Segregation Principle (ISP)**:
- Traits MUST be focused and minimal
- Clients depend only on methods they use
- Large interfaces split into role-specific traits
**Dependency Inversion Principle (DIP)**:
- High-level domain logic depends on abstractions (traits)
- Low-level infrastructure implements abstractions
- Dependencies injected through constructors/builders
- No direct instantiation of concrete infrastructure types in domain
**Rationale**: SOLID principles ensure code remains maintainable, testable, and extensible as the system evolves. They provide concrete design rules that support the broader clean architecture goals.
## Technology Stack
### Backend (Rust)
- **Web Framework**: Poem with OpenAPI support (poem-openapi)
- **Async Runtime**: Tokio
- **Modbus Protocol**: tokio-modbus 0.17.0
- **Configuration**: config crate with YAML support
- **Logging**: tracing + tracing-subscriber
- **Error Handling**: thiserror
- **Testing**: Built-in Rust test framework + mockall
### Frontend (TypeScript/Vue)
- **Framework**: Vue 3 with TypeScript
- **HTTP Client**: Type-safe API client generated from OpenAPI specs
- **Build Tool**: Vite
- **State Management**: Pinia (if needed for complex state)
### Architecture Patterns
- Clean/Hexagonal architecture with explicit layer boundaries
- Repository pattern for persistence abstraction
- Trait-based dependency injection
- Mock-based testing to avoid hardware dependencies
- SOLID principles applied to all design decisions
## Development Workflow
### Feature Development Process
1. **Specification Phase**:
- Write feature specification in `specs/<feature>/spec.md`
- Define data model in `specs/<feature>/data-model.md`
- Create implementation plan in `specs/<feature>/plan.md`
- Document API contracts in `specs/<feature>/contracts/`
2. **Test-First Implementation**:
- Write failing tests for domain logic
- Write failing tests for infrastructure adapters
- Write failing contract tests for API endpoints
- Get user approval on test scenarios
- Implement code to pass tests
- Refactor while maintaining green tests
3. **Integration & Validation**:
- Integration tests with mocked hardware
- Real hardware testing (when available)
- OpenAPI documentation validation
- Code review focusing on architectural compliance
### Code Review Requirements
All code changes MUST be reviewed for:
- Compliance with hexagonal architecture principles
- SOLID principles adherence
- Domain model clarity and expressiveness
- Test coverage and quality
- API contract adherence
- Observability (logging, error context)
- No domain logic leaking into infrastructure layer
### Quality Gates
Code MUST NOT be merged unless:
- All tests pass (unit + integration)
- Test coverage meets minimum thresholds
- Architecture review confirms layer separation
- SOLID principles validated (no SRP/DIP violations)
- OpenAPI specs are up-to-date
- Logging captures key operational events
## Governance
This constitution supersedes all other development practices and guidelines. All architectural decisions MUST align with the principles defined herein.
### Amendment Process
Amendments to this constitution require:
1. Documented rationale for the change
2. Impact analysis on existing codebase
3. Migration plan if breaking existing patterns
4. Approval before implementation
### Compliance Verification
- All pull requests MUST verify constitutional compliance
- Architecture decisions MUST be justified against these principles
- Complexity introduced MUST be necessary to uphold principles
- Violations MUST be addressed before merge
### Version Control
This constitution uses semantic versioning:
- **MAJOR**: Breaking changes to core principles
- **MINOR**: New principles or significant clarifications
- **PATCH**: Typo fixes, wording improvements
**Version**: 1.1.0 | **Ratified**: 2025-12-27 | **Last Amended**: 2025-12-27