diff --git a/CLAUDE.md b/CLAUDE.md index b94b4c7..a60ef96 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,213 +4,86 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Project Overview -ConwayGame is a production-ready iOS implementation of Conway's Game of Life built with SwiftUI and Core Data. The architecture follows clean separation of concerns with distinct layers for game logic, persistence, and UI. +Conway's Game of Life implementation with three components: +- **ConwayGame/** - iOS SwiftUI app with Core Data persistence +- **ConwayGameEngine/** - Reusable Swift Package with pure game logic and CLI +- **ConwayAPI/** - Vapor REST API exposing engine functionality -## Documentation Structure - -This project maintains several documentation files with distinct purposes: - -- **CLAUDE.md** (this file): Guidance for Claude Code AI assistant when working with the codebase -- **CONTRIBUTING.md**: Comprehensive contributor guide for human developers (setup, architecture, workflow) -- **README.md**: Project overview and quick start instructions for end users -- **Swift API Documentation**: Comprehensive documentation comments throughout all public APIs following Apple's Swift documentation guidelines -- **GitHub Templates** (`.github/`): Structured templates for issues and pull requests - - Bug reports, feature requests, performance issues, documentation, and questions - - Pull request template with architecture impact assessment and testing checklists - -## Build and Test Commands +## Build & Test Commands ```bash -# Build the project -xcodebuild -scheme ConwayGame -configuration Debug build - -# Run all tests +# iOS app tests (all) xcodebuild -scheme ConwayGame -destination 'platform=iOS Simulator,name=iPhone 16 Pro' test -# Run specific test target -xcodebuild -scheme ConwayGameTests -destination 'platform=iOS Simulator,name=iPhone 16 Pro' test - -# Run specific test file (example) +# iOS specific test class xcodebuild -scheme ConwayGame -destination 'platform=iOS Simulator,name=iPhone 16 Pro' test -only-testing:ConwayGameTests/GameEngineTests -# Run specific test method (example) +# iOS specific test method xcodebuild -scheme ConwayGame -destination 'platform=iOS Simulator,name=iPhone 16 Pro' test -only-testing:ConwayGameTests/GameEngineTests/testBasicPatterns -# Build for release -xcodebuild -scheme ConwayGame -configuration Release build +# Engine package tests +cd ConwayGameEngine && swift test + +# API tests +cd ConwayAPI && swift test -# Clean build folder -xcodebuild -scheme ConwayGame clean +# Run CLI +cd ConwayGameEngine && swift run conway-cli pattern glider +cd ConwayGameEngine && swift run conway-cli run 10 10 20 random --density=0.3 --rules=highlife -# Swift Package commands -cd ConwayGameEngine +# Run API server +cd ConwayAPI && swift run conway-api -# Build Swift Package -swift build +# Format code (run before committing) +swiftformat ConwayGameEngine ConwayAPI -# Run Swift Package tests -swift test +# Check formatting +swiftformat ConwayGameEngine ConwayAPI --lint +``` -# Run CLI tool -swift run conway-cli --help -swift run conway-cli pattern glider +## Architecture -# Code Formatting Commands +``` +┌─────────────────────────┐ +│ iOS App (SwiftUI) │ Views → ViewModels +├─────────────────────────┤ +│ Service Layer │ GameService +├─────────────────────────┤ +│ Repository Layer │ CoreDataBoardRepository +├─────────────────────────┤ +│ ConwayGameEngine │ Pure game logic, no dependencies +└─────────────────────────┘ +``` -# Install SwiftFormat (if not already installed) -brew install swiftformat +**Key patterns:** +- Protocol-oriented design for all major components (testability) +- MVVM with `@MainActor` ViewModels +- Repository pattern abstracting Core Data +- Dependency injection via FactoryKit (`FactoryContainer.swift`) +- Centralized configuration (`GameEngineConfiguration`) eliminates magic numbers -# Format all Swift code in ConwayGameEngine -cd ConwayGameEngine && swiftformat . +**Naming conventions:** +- Protocols describe behavior: `GameEngine`, `GameService`, `BoardRepository` +- Implementations prefixed: `ConwayGameEngine`, `DefaultGameService`, `CoreDataBoardRepository` -# Check formatting without making changes (ConwayGameEngine) -cd ConwayGameEngine && swiftformat --lint . +## Code Style -# Format all Swift code in ConwayAPI -cd ConwayAPI && swiftformat . +SwiftFormat enforced in CI: +- Swift 5.9+, compatible with Swift 6 language mode +- 4-space indentation, 120-char line length +- No redundant `self`, alphabetized imports +- Use `struct` over `class` when possible +- Use `@inline(__always)` only for proven hot paths -# Check formatting without making changes (ConwayAPI) -cd ConwayAPI && swiftformat --lint . +## Error Handling -# Format entire project (run from project root) -swiftformat ConwayGameEngine ConwayAPI +- `GameError` enum for core operations +- `UserFriendlyError` protocol for UI-facing errors with recovery actions +- Context-aware wrapping via `ConwayGameUserError` -# Check entire project formatting (run from project root) -swiftformat ConwayGameEngine ConwayAPI --lint -``` +## Testing -## Architecture Overview - -The codebase follows a layered architecture designed for future extensibility and platform independence: - -### Core Layers - -1. **Configuration System** (`ConwayGameEngine/Sources/ConwayGameEngine/`) - - `GameEngineConfiguration`: Configurable Conway rules and simulation parameters - - `PlaySpeedConfiguration`: Animation timing configuration for iOS and CLI - - Supports multiple rule variants (Conway, HighLife, Day and Night) - - Eliminates magic numbers and ensures cross-platform consistency - -2. **Pure Game Logic Layer** (`Services/GameEngine.swift`) - - `GameEngine` protocol: Core Conway's Game of Life computation - - `ConwayGameEngine`: Optimized implementation with configurable rules and early termination - - `GameRules`: Static methods for cell survival/birth logic using configurable neighbor counts - -3. **Data Layer** (`Models/`) - - `Board`: Main entity with validation, state history for convergence detection - - `GameState`: Represents computed state at specific generation - - `GameError`: Comprehensive error handling enumeration - - `ConvergenceType`: Tracks game state evolution (continuing/extinct/cyclical) - -4. **Service Layer** (`Services/GameService.swift`) - - `GameService` protocol: Business logic orchestration - - `DefaultGameService`: Coordinates game engine, persistence, and convergence detection - - Async/await patterns for all operations - -5. **Repository Pattern** (`Repository/`) - - `BoardRepository` protocol: Persistence abstraction - - `CoreDataBoardRepository`: Core Data implementation - - Complete CRUD operations for boards - -6. **Dependency Injection** (`Utils/FactoryContainer.swift`) - - FactoryKit-based container managing all service dependencies and configurations - - Ensures consistent object graph and configuration throughout app - -7. **Error Handling & User Experience** (`Utils/`) - - `UserFriendlyError.swift`: Protocol-based system for transforming technical errors into user-friendly messages - - `ErrorAlertModifier.swift`: SwiftUI integration with contextual recovery actions and smart error alerts - - Context-aware recovery actions (.boardLoading, .gameSimulation, .dataPersistence) - - Comprehensive error transformation covering all Conway Game scenarios - -### Key Design Patterns - -- **Protocol-oriented design**: All major components are protocol-based for testability -- **Repository pattern**: Abstracts persistence layer -- **MVVM**: ViewModels coordinate between UI and services -- **Configuration management**: Centralized configuration system eliminates magic numbers -- **Dependency injection**: FactoryKit-based dependency injection ensures consistent configurations across iOS and CLI -- **Convergence detection**: Uses state hashing and history tracking for cycle/stability detection -- **User-friendly error handling**: Context-aware error transformation with actionable recovery options - -## Testing Structure - -- `GameEngineTests.swift`: Core Conway's Game logic, edge cases, patterns -- `GameServiceTests.swift`: Service layer integration tests -- `ConvergenceDetectorTests.swift`: Convergence detection algorithms -- `BoardRepositoryTests.swift`: Persistence layer tests -- `ViewModelTests.swift`: UI logic tests and error handling integration -- `UserFriendlyErrorTests.swift`: Error transformation, recovery actions, and context-aware behavior -- `PaginationViewModelTests.swift`: Pagination behavior and sorting tests -- `PerformanceBenchmarkTests.swift`: Core Data scaling and performance tests -- `SyntheticDataGenerator.swift`: Test data generation utility for performance testing - -## Performance Considerations - -- **Memory optimization**: Uses `@inline(__always)` for hot paths in game logic -- **Identity checking**: Game engine returns same instance when no changes occur -- **Early termination**: Computation stops when stable states are detected -- **Background processing**: Long computations run on background queues -- **State hashing**: Efficient bit-packed base64 encoding for cycle detection -- **Core Data pagination**: Efficient pagination with configurable page sizes to handle large datasets -- **Performance testing**: Comprehensive benchmark suite for Core Data scaling with `SyntheticDataGenerator` - -## Core Data Integration - -- Uses `PersistenceController.shared` for Core Data stack -- Boards persist across app launches with full state history -- Environment injection via `.managedObjectContext` in SwiftUI - -## Key Files for Extension - -- `GameEngineConfiguration.swift`: Add new rule variants or simulation parameters -- `PlaySpeedConfiguration.swift`: Modify timing configurations for iOS and CLI -- `GameEngine.swift`: Modify game computation algorithms or add optimizations -- `GameService.swift`: Add new game operations or API endpoints -- `Board.swift`: Extend data model (ensure validation updates) -- `BoardSortOption.swift`: Add new sorting options for board lists and pagination -- `BoardRepository.swift`: Add new repository methods for data access patterns -- `CoreDataBoardRepository.swift`: Implement new Core Data queries and pagination logic -- `BoardListViewModel.swift`: Extend pagination and filtering capabilities -- `FactoryContainer.swift`: Register new dependencies and configurations -- `ThemeManager.swift`: UI theming and appearance management -- `UserFriendlyError.swift`: Extend error transformation system for new error types or contexts -- `ErrorAlertModifier.swift`: Enhanced error presentation with contextual recovery actions -- `LRUCache.swift`: Performance optimization for caching -- `DesignTokens.swift`: UI design system constants -- `ConvergenceDetector.swift`: Enhance convergence detection algorithms -- `SyntheticDataGenerator.swift`: Extend test data generation for performance testing - -### Documentation Files -- `CONTRIBUTING.md`: Update when architecture changes or new development processes are added -- `.github/ISSUE_TEMPLATE/`: Update templates when new components are added or issue categories change -- `.github/pull_request_template.md`: Update when new architecture layers or testing requirements are introduced - -## Development Notes - -- Game logic is completely UI-independent for future platform portability -- All async operations use structured concurrency -- User-friendly error handling with contextual recovery actions transforms technical errors into actionable guidance -- State validation occurs at model level with throwing initializers -- Logging uses OSLog framework with categorized loggers -- Configuration system eliminates magic numbers and ensures consistency across platforms -- Multiple rule variants supported: Conway (default), HighLife, Day and Night -- CLI supports runtime configuration overrides via command-line options -- **API Documentation**: All public APIs include comprehensive Swift documentation comments with usage examples, parameter descriptions, and performance notes following Apple's Swift API Design Guidelines - -### Documentation Maintenance - -When making changes to the codebase, consider updating documentation: - -- **Architecture changes**: Update both CLAUDE.md and CONTRIBUTING.md to reflect new layers, patterns, or components -- **New features**: Update GitHub issue templates if new feature categories are introduced -- **Testing changes**: Update pull request template checklist and CONTRIBUTING.md testing sections -- **Build process changes**: Update build commands in both CLAUDE.md and CONTRIBUTING.md -- **New dependencies**: Update setup instructions in CONTRIBUTING.md -- **API changes**: Update Swift documentation comments when modifying public APIs, including: - - Parameter and return value descriptions - - Usage examples for complex methods - - Performance notes and complexity information - - Error conditions and handling guidance - - Maintain consistency with Apple's Swift API Design Guidelines - -Refer contributors to CONTRIBUTING.md for comprehensive setup and development workflow guidance. \ No newline at end of file +- >90% coverage target for core logic +- Integration tests in `EndToEndWorkflowTests.swift`, `CoreDataIntegrationTests.swift` +- `SyntheticDataGenerator.swift` for large dataset testing +- API tests use `XCTVapor` async helpers diff --git a/INTEGRATION_TESTS_README.md b/INTEGRATION_TESTS_README.md deleted file mode 100644 index 6b2434b..0000000 --- a/INTEGRATION_TESTS_README.md +++ /dev/null @@ -1,186 +0,0 @@ -# Conway's Game of Life - Integration Tests - -This project now includes comprehensive integration tests that validate the full system behavior across all layers and components. - -## Integration Test Overview - -### Test Categories Implemented - -#### 1. **Cross-Layer iOS Integration Tests** (`IntegrationTests.swift`) -- **Complete User Workflow**: Board creation → Play → Step → Jump → Final state → Reset -- **ViewModel + Service + Repository + Engine Integration**: End-to-end data flow validation -- **Error Handling**: Cross-layer error propagation and recovery -- **Theme Management**: UI theming integration with persistence -- **Configuration System**: Rule sets and play speed configurations -- **Memory Management**: Leak detection across components -- **Concurrent Access**: Multi-ViewModel operations on shared data -- **Convergence Detection**: Still life, oscillator, and extinction pattern validation -- **Performance Testing**: Large grid handling and timing validation - -#### 2. **Core Data Integration Tests** (`CoreDataIntegrationTests.swift`) -- **CRUD Operations**: Full Create, Read, Update, Delete lifecycle with real database -- **Pagination**: Large dataset pagination with sorting and searching -- **Search & Sort**: Complex query operations with performance validation -- **Data Integrity**: Constraint validation and serialization consistency -- **Concurrent Access**: Multi-threaded database operations -- **Performance Benchmarks**: Large dataset creation and retrieval timing -- **Schema Validation**: Core Data model consistency checks -- **Memory Management**: Large dataset memory usage patterns - -#### 3. **End-to-End User Workflow Tests** (`EndToEndWorkflowTests.swift`) -- **New User Onboarding**: Complete first-time user experience -- **Pattern Exploration**: Known Conway patterns (Glider, Block, Blinker, etc.) -- **Large Scale Management**: Bulk board operations and pagination -- **Multi-Session Workflow**: App restart simulation and data persistence -- **Advanced User Patterns**: Complex patterns like Gosper Glider Gun -- **Error Recovery**: User-friendly error handling and recovery actions -- **Theme & Configuration**: Settings persistence across sessions -- **Performance & Scalability**: Large grid and dataset handling - -#### 4. **Enhanced API Integration Tests** (`APIIntegrationTests.swift`) -- **Multi-Rule Workflows**: Conway, HighLife, Day & Night rule comparisons -- **Advanced Pattern Analysis**: Known patterns with expected behavior validation -- **Concurrent API Requests**: Load testing with mixed request types -- **Rate Limiting & Throttling**: API behavior under rapid requests -- **Complex Grid Patterns**: Real-world patterns and edge cases -- **Error Handling Scenarios**: Invalid inputs and recovery mechanisms -- **Performance Benchmarks**: Grid size scaling and response time validation -- **Content Negotiation**: Headers, CORS, and content type validation -- **Streaming Simulation**: Sequential requests mimicking real-time updates -- **Documentation Endpoints**: API metadata and rule information - -#### 5. **Shared Test Utilities** (`IntegrationTestUtilities.swift`) -- **Test Patterns**: Library of known Conway patterns with expected behaviors -- **Test Environment Setup**: Production-like environment configuration -- **Assertion Helpers**: Pattern behavior validation and grid comparison utilities -- **Performance Measurement**: Benchmarking tools with threshold validation -- **Concurrent Testing**: Race condition detection and concurrent operation runners -- **Mock Data Generation**: Random and structured test data creation -- **Base Test Classes**: Common setup and teardown patterns - -## Key Features of Integration Tests - -### Pattern Behavior Validation -Tests validate known Conway's Game of Life patterns: -- **Still Life**: Block (4 cells, stable) -- **Oscillators**: Blinker (3 cells, period 2), Toad (6 cells, period 2) -- **Spaceships**: Glider (5 cells, moves diagonally) -- **Complex Patterns**: Gosper Glider Gun (creates gliders infinitely) - -### Performance Testing -- **Grid Scaling**: Tests from 5x5 to 100x100 grids -- **Time Thresholds**: Configurable performance expectations -- **Memory Management**: Large dataset handling without leaks -- **Concurrent Load**: Multiple simultaneous operations - -### Error Recovery Testing -- **User-Friendly Errors**: Technical errors transformed to actionable messages -- **Recovery Actions**: Retry, reset, navigation options -- **Cross-Layer Propagation**: Error handling from engine to UI - -### Real-World Scenarios -- **Multi-Session Usage**: App lifecycle simulation -- **Large Datasets**: 1000+ boards with pagination -- **Complex User Journeys**: New user to advanced pattern exploration -- **Concurrent Users**: Multiple ViewModels and simultaneous operations - -## Running Integration Tests - -### iOS Integration Tests -```bash -# Run all iOS tests -xcodebuild -scheme ConwayGame -destination 'platform=iOS Simulator,name=iPhone 16 Pro' test - -# Run specific integration test files -xcodebuild -scheme ConwayGame -destination 'platform=iOS Simulator,name=iPhone 16 Pro' test -only-testing:ConwayGameTests/IntegrationTests -xcodebuild -scheme ConwayGame -destination 'platform=iOS Simulator,name=iPhone 16 Pro' test -only-testing:ConwayGameTests/CoreDataIntegrationTests -xcodebuild -scheme ConwayGame -destination 'platform=iOS Simulator,name=iPhone 16 Pro' test -only-testing:ConwayGameTests/EndToEndWorkflowTests -``` - -### API Integration Tests -```bash -# Run API integration tests -cd ConwayAPI -swift test - -# Run specific test class -swift test --filter APIIntegrationTests -``` - -### Swift Package Engine Tests -```bash -# Run engine integration tests -cd ConwayGameEngine -swift test -``` - -## Test Utilities Usage - -The shared utilities make it easy to write additional integration tests: - -```swift -@MainActor -final class MyIntegrationTest: BaseIntegrationTestCase { - - func testMyScenario() async throws { - // Create test board with known pattern - let boardId = try await createTestBoard(pattern: "glider") - - // Measure performance - let result = try await measurePerformance( - of: "myOperation", - expectedMaxTime: 1.0 - ) { - await testEnvironment.gameService.getNextState(boardId: boardId) - } - - // Validate pattern behavior - guard case .success(let state) = result else { - XCTFail("Operation failed") - return - } - - // Use utility assertions - assertPatternBehavior(state, matches: .spaceship(population: 5)) - } -} -``` - -## Configuration - -Test configurations are centralized in `IntegrationTestConfig`: - -```swift -struct IntegrationTestConfig { - static let defaultTimeout: TimeInterval = 30.0 - static let maxStepTime: TimeInterval = 0.5 - static let maxFinalStateTime: TimeInterval = 10.0 - static let concurrentOperationCount = 20 - static let stressTestBoardCount = 100 -} -``` - -## Performance Benchmarks - -Integration tests include performance benchmarking that tracks: -- Board creation time by size -- Step computation time by grid size -- Final state detection time -- Database operation performance -- API response times -- Memory usage patterns - -Results are automatically printed and can be used to detect performance regressions. - -## Benefits - -These integration tests provide: - -1. **Confidence**: Full system behavior validation -2. **Regression Detection**: Performance and functionality regression catching -3. **Documentation**: Real usage examples and expected behaviors -4. **Quality Assurance**: Production-like scenario testing -5. **Development Support**: Easy test utilities for new features -6. **Performance Monitoring**: Automated performance threshold validation - -The integration tests complement the existing unit tests by validating the complete system behavior, ensuring that all components work correctly together in real-world usage scenarios. \ No newline at end of file diff --git a/PR_SUMMARY.md b/PR_SUMMARY.md deleted file mode 100644 index f0c56db..0000000 --- a/PR_SUMMARY.md +++ /dev/null @@ -1,62 +0,0 @@ -# ConwayAPI: REST API, Middleware, Docker, and Test Suite Overhaul - -## Overview -This PR introduces a production-ready REST API for Conway's Game of Life using Vapor, improves middleware and validation, fixes Docker build flows for a monorepo, and modernizes the test suite to async XCTVapor with concise helpers. - -## Key Changes -- New Swift package `ConwayAPI` with full REST API. -- Middleware: custom error handling, CORS, JSON content type; renamed to avoid Vapor type collisions. -- Validation: clear errors, width/height in invalid responses, grid size caps. -- Docker: fixed build context to include local engine, added curl for health checks. -- Tests: migrated to async XCTVapor, added helpers for status + JSON assertions; cleaned noisy logs. -- Removed misplaced API artifacts from `ConwayGameEngine` (Dockerfiles, configure stub, API_README). - -## API Endpoints -- `GET /health` — health check -- `GET /api` — API info + endpoints -- `POST /api/game/step` — compute next generation -- `POST /api/game/simulate` — run N generations + convergence detection -- `POST /api/game/validate` — grid shape validation -- `GET /api/patterns` — list patterns -- `GET /api/patterns/{name}` — pattern detail -- `GET /api/rules` — list rule presets (Conway, HighLife, Day & Night) - -## Middleware & Error Handling -- `APIErrorMiddleware` — structured error responses; logs unexpected errors -- `SimpleCORSMiddleware` — permissive defaults for demos; configurable later -- `JSONContentTypeMiddleware` — ensures JSON Content-Type when absent -- ISO-8601 JSON encoding via ContentConfiguration - -## Validation -- Grid shape validation with actionable errors -- Error responses include `width` and `height` when invalid -- Grid size caps: default max 200x200 to protect resources - -## Docker/Compose -- `ConwayAPI/Dockerfile` builds from repo root and copies local engine -- Runtime image installs `curl`; health checks wired up -- `docker-compose.yml` builds with `context: ..` and proper `dockerfile` - -## Tests -- 38 tests across controllers + integration, all passing -- Async test lifecycle (`Application.make`, `asyncShutdown`) -- Helpers: `perform` and `decode` with status + optional JSON assertions -- Reduced vapor logs to warning level during tests - -## Risks & Notes -- CORS is permissive; consider env-driven configuration for production -- Grid caps are hard-coded; can be made configurable via env/app storage -- Convergence detector returns period 0 for cycles; future enhancement could compute the true period - -## How to Run -- Local: `cd ConwayAPI && swift run conway-api` then `GET /health` -- Tests: `cd ConwayAPI && swift test` -- Docker: `cd ConwayAPI && docker compose up --build` - -## Checklist -- [x] Build passes -- [x] Tests pass locally (38/38) -- [x] API docs link fixed -- [x] Docker builds from monorepo -- [x] No Vapor type name shadowing - diff --git a/conway_ios_plan.md b/conway_ios_plan.md deleted file mode 100644 index f2b8239..0000000 --- a/conway_ios_plan.md +++ /dev/null @@ -1,314 +0,0 @@ -# Conway's Game of Life - iOS Implementation Plan - -## Project Overview -Build a production-ready iOS app implementing Conway's Game of Life with internal API architecture. Target: Staff Mobile Engineer evaluation focusing on architecture, performance, and production readiness. - -## Functional Requirements -1. **Board State Management**: Create, save, and load board configurations with unique identifiers -2. **Next State Computation**: Calculate and return the next iteration of any board -3. **Multi-Step Forward**: Calculate board state X iterations ahead efficiently -4. **Final State Detection**: Detect convergence (stable patterns, oscillators, extinction) with configurable timeout -5. **Persistence**: Maintain board states across app restarts/crashes -6. **Error Handling**: Graceful failure when final state cannot be determined - -## Technical Architecture - -## Technical Architecture - -### Future-Proof Separation of Concerns -**Critical Design Principle**: The game logic must be completely decoupled from UI components in preparation for future fullstack evolution. The architecture should allow the game engine to be extracted into a separate module/framework without UI dependencies. - -### Core Components - -#### 1. Pure Game Logic Layer (Platform Agnostic) -```swift -// Pure business logic - no iOS/UI dependencies -protocol GameEngine { - func computeNextState(_ currentState: [[Bool]]) -> [[Bool]] - func computeStateAtGeneration(_ initialState: [[Bool]], generation: Int) -> [[Bool]] -} - -protocol ConvergenceDetector { - func checkConvergence(_ state: [[Bool]]) -> ConvergenceType -} - -struct GameRules { - static func shouldCellLive(isAlive: Bool, neighborCount: Int) -> Bool - static func countNeighbors(_ grid: [[Bool]], x: Int, y: Int) -> Int -} -``` - -#### 2. Data Layer (Platform Agnostic Models) -```swift -// Models with no UI/iOS dependencies -struct Board: Codable, Identifiable, Hashable -struct GameState: Codable -struct BoardMetadata: Codable -enum ConvergenceType: Codable - -// Repository abstraction -protocol BoardRepository { - func save(_ board: Board) async throws - func load(id: UUID) async throws -> Board? - func loadAll() async throws -> [Board] - func delete(id: UUID) async throws -} -``` - -#### 3. Service Layer (Business Logic Coordinator) -```swift -// Orchestrates game logic and persistence - no UI dependencies -protocol GameService { - func createBoard(_ initialState: [[Bool]]) async -> UUID - func getNextState(boardId: UUID) async -> Result - func getStateAtGeneration(boardId: UUID, generation: Int) async -> Result - func getFinalState(boardId: UUID, maxIterations: Int) async -> Result -} - -class DefaultGameService: GameService { - private let gameEngine: GameEngine - private let repository: BoardRepository - private let convergenceDetector: ConvergenceDetector - - // Pure business logic implementation -} -``` - -#### 4. iOS-Specific Implementation Layer -```swift -// iOS-specific implementations -class CoreDataBoardRepository: BoardRepository -class InMemoryBoardRepository: BoardRepository // for testing - -// Dependency injection container -class ServiceContainer { - lazy var gameService: GameService = DefaultGameService( - gameEngine: ConwayGameEngine(), - repository: CoreDataBoardRepository(), - convergenceDetector: DefaultConvergenceDetector() - ) -} -``` - -#### 5. UI Layer (iOS/SwiftUI Specific) -```swift -// UI consumes services via dependency injection -class GameViewModel: ObservableObject { - private let gameService: GameService - - init(gameService: GameService) { - self.gameService = gameService - } -} - -struct GameBoardView: View { - @StateObject private var viewModel: GameViewModel - - init(gameService: GameService) { - _viewModel = StateObject(wrappedValue: GameViewModel(gameService: gameService)) - } -} -``` - -### File Structure -``` -ConwayGameOfLife/ -├── App/ -│ ├── ConwayGameOfLifeApp.swift -│ └── ContentView.swift -├── Models/ -│ ├── Board.swift -│ ├── GameState.swift -│ └── GameError.swift -├── Services/ -│ ├── GameService.swift -│ ├── GameEngine.swift -│ └── ConvergenceDetector.swift -├── Repository/ -│ ├── BoardRepository.swift -│ └── CoreDataBoardRepository.swift -├── ViewModels/ -│ ├── GameViewModel.swift -│ └── BoardListViewModel.swift -├── Views/ -│ ├── GameBoardView.swift -│ ├── GameControlsView.swift -│ ├── BoardListView.swift -│ └── CreateBoardView.swift -├── Utils/ -│ ├── Extensions.swift -│ └── Constants.swift -└── Tests/ - ├── GameEngineTests.swift - ├── GameServiceTests.swift - └── ConvergenceDetectorTests.swift -``` - -## Implementation Details - -### Core Data Model -```swift -struct Board: Codable, Identifiable, Hashable { - let id: UUID - let name: String - let width: Int - let height: Int - let createdAt: Date - let currentGeneration: Int - let cells: [[Bool]] - let isActive: Bool - - // For cycle detection - let stateHistory: [String] // Hash of previous states -} - -struct GameState: Codable { - let boardId: UUID - let generation: Int - let cells: [[Bool]] - let isStable: Bool - let populationCount: Int -} -``` - -### Game Engine Algorithm -```swift -class ConwayGameEngine: GameEngine { - func computeNextState(_ currentState: [[Bool]]) -> [[Bool]] { - // Optimized neighbor counting - // Boundary handling - // Memory-efficient computation - } - - func computeStateAtGeneration(_ initialState: [[Bool]], generation: Int) -> [[Bool]] { - // Fast-forward with optimizations - // Early termination for stable states - } -} -``` - -### Convergence Detection Strategy -```swift -class ConvergenceDetector { - private var stateHistory: Set = [] - private var cycleLength: Int = 0 - - func checkConvergence(_ state: [[Bool]]) -> ConvergenceType { - let stateHash = hashState(state) - - // Check for extinction - if isExtinct(state) { return .extinct } - - // Check for cycles/stable states - if stateHistory.contains(stateHash) { - return .cyclical(period: cycleLength) - } - - stateHistory.insert(stateHash) - return .continuing - } -} -``` - -## Production-Ready Features - -### Performance Optimizations -- **Memory Management**: Use `autoreleasepool` for large computations -- **Background Processing**: Compute generations on background queue -- **UI Responsiveness**: Async/await patterns for long operations -- **Caching**: LRU cache for computed states -- **Lazy Loading**: Only compute visible board regions for large grids - -### Error Handling -```swift -enum GameError: LocalizedError { - case boardNotFound(UUID) - case convergenceTimeout(maxIterations: Int) - case invalidBoardDimensions - case persistenceError(Error) - case computationError(Error) -} -``` - -### Logging & Monitoring -```swift -import OSLog -extension Logger { - static let gameEngine = Logger(subsystem: "ConwayGame", category: "GameEngine") - static let persistence = Logger(subsystem: "ConwayGame", category: "Persistence") -} -``` - -### Testing Strategy -- **Unit Tests**: Game logic, convergence detection, state calculations -- **Integration Tests**: Service layer with mock repositories -- **UI Tests**: Basic user flows -- **Performance Tests**: Large board computations, memory usage -- **Snapshot Tests**: UI consistency across different board states - -### App Lifecycle Management -- **Background/Foreground**: Pause/resume active computations -- **Memory Pressure**: Implement cache eviction strategies -- **State Restoration**: Preserve UI state across app launches - -## UI/UX Design - -### Main Screens -1. **Board List**: Display saved boards with preview and metadata -2. **Game Board**: Interactive grid with play/pause/step controls -3. **Create Board**: Pattern templates or manual cell placement -4. **Board Details**: Statistics, generation count, population over time - -### User Interactions -- **Tap cells**: Toggle alive/dead state -- **Pinch/Zoom**: Navigate large boards -- **Play/Pause**: Animate through generations -- **Step**: Advance one generation -- **Fast Forward**: Jump to specific generation -- **Export/Import**: Share board configurations - -## Development Phases - -### Phase 1: Core Architecture -- Set up project structure -- Implement basic models and protocols -- Create game engine with unit tests -- Set up Core Data stack - -### Phase 2: Service Layer -- Implement GameService with all required methods -- Add persistence layer -- Implement convergence detection -- Error handling and logging - -### Phase 3: UI Implementation -- Create SwiftUI views and view models -- Implement interactive game board -- Add board management screens -- Handle app lifecycle events - -### Phase 4: Production Polish -- Performance optimizations -- Comprehensive testing -- Documentation -- Code review and refactoring - -### Phase 5: Demo Preparation -- Prepare architectural presentation -- Create sample board configurations -- Performance benchmarks -- Production readiness checklist - -## Success Metrics -- **Performance**: Handle 100x100 boards smoothly -- **Memory**: Stable memory usage under pressure -- **Reliability**: No crashes during normal operation -- **Testability**: >80% code coverage -- **Maintainability**: Clear architecture and documentation - -## Key Discussion Points for Interview -1. **Architecture Decisions**: Why MVVM + Repository pattern -2. **Performance Trade-offs**: Memory vs computation speed -3. **Scalability**: How to handle larger boards/more features -4. **Production Concerns**: Monitoring, debugging, maintenance -5. **iOS-Specific**: Core Data, background processing, memory management \ No newline at end of file diff --git a/project_status.md b/project_status.md deleted file mode 100644 index 11edc57..0000000 --- a/project_status.md +++ /dev/null @@ -1,42 +0,0 @@ -# Project Status - -## ✅ Completed Tasks - -### Low Impact, Low Effort -- **Contributing Guidelines** - No explicit guidelines for contributors -- **Magic Numbers** - Some constants like `maxAutoStepsPerRun = 500` could be better centralized in a configuration file -- **Core Data Scaling** - No pagination or lazy loading for large numbers of saved boards -- **Single Service Container** - While functional, it could benefit from a more sophisticated Dependency Injection (DI) framework for larger applications - -### Medium Impact, Low Effort -- **API Documentation** - Missing comprehensive API documentation for public interfaces - -### Medium Impact, Medium Effort -- **Integration Testing** - Could benefit from more end-to-end integration tests - -### High Impact, Medium Effort -- **Error UX** - Enhanced user experience around error states and recovery -- **CI/CD Configuration** - No visible continuous integration setup *(partially done)* - -### High Impact, High Effort -- **Missing Platform Abstraction** - No clear path for extending to other platforms beyond the Apple ecosystem - *Note: A REST API POC based on the Game's engine was created for expanding to other platforms* - -### Additional Completed Items -- **CI/CD Configuration** - Done for Engine, CLI and API - ---- - -## 📋 To-Do Items - -### High Impact, Low Effort -- **Tight Coupling with CoreData** - Although abstracted through the repository pattern, the main app is still tightly coupled to the CoreData implementation - -### High Impact, Medium Effort -- **Memory Growth** - State history tracking could consume significant memory for long-running simulations - -### Medium Impact, Medium Effort -- **Single-Threaded Computation** - The game engine doesn't utilize multiple cores for large grid calculations - -### High Impact, High Effort -- **State Management Complexity** - Multiple state synchronization points between the repository, service, and ViewModels could be simplified \ No newline at end of file