diff --git a/.claude/FILE-MAP.md b/.claude/FILE-MAP.md new file mode 100644 index 0000000..3163e82 --- /dev/null +++ b/.claude/FILE-MAP.md @@ -0,0 +1,205 @@ +# FILE-MAP - FantasyFactio Code Index + + + +Last Updated: 2025-12-02 + +--- + +## Quick Navigation + +### By Purpose + +| Purpose | Location | Files | +|---------|----------|-------| +| **Entry Point** | lib/ | `main.dart` | +| **Game Logic** | lib/domain/ | entities/, usecases/, core/ | +| **Game Rendering** | lib/game/ | camera/, components/ | +| **Tests** | test/, integration_test/ | `*_test.dart` files | + +--- + +## lib/ - Application Code + +### Core Application Entry Point + +| File | Purpose | Status | LOC | +|------|---------|--------|-----| +| `main.dart` | App initialization, Firebase setup, theme | ✅ Complete | 400+ | + +### lib/domain/ - Business Logic (Framework-Independent) + +#### Core Types + +| File | Description | Exports | Status | +|------|-------------|---------|--------| +| `core/either.dart` | Either type for error handling | Either, Left, Right | ✅ Complete | +| `core/result.dart` | Result wrapper | Result | ✅ Complete | + +#### Entities + +| File | Class | Purpose | Status | Tests | +|------|-------|---------|--------|-------| +| `entities/building.dart` | Building | Defines building structure, production, upgrade config | ✅ Complete | ✅ Yes | +| `entities/resource.dart` | Resource | Game resource (wood, iron, etc) with capacity | ✅ Complete | ✅ Yes | +| `entities/player_economy.dart` | PlayerEconomy | Player's game state (gold, buildings, inventory) | ✅ Complete (⚠️ BUG) | ✅ Yes | + +**Known Issues in entities:** +- PlayerEconomy.addResource() - BUG: Returns unchanged if resource doesn't exist (see CLAUDE.md) + +#### Use Cases + +| File | Class | Purpose | Input | Output | Status | +|-------|-------|---------|-------|--------|--------| +| `usecases/collect_resources_usecase.dart` | CollectResourcesUseCase | Collect resources from building | PlayerEconomy, Building | Result | ✅ Coded (❌ Broken by entity bug) | +| `usecases/upgrade_building_usecase.dart` | UpgradeBuildingUseCase | Upgrade building (costs gold) | PlayerEconomy, Building | Result | ✅ Complete | + +### lib/game/ - Flame Game Engine Layer + +#### Camera System + +| File | Class | Purpose | Status | +|------|-------|---------|--------| +| `camera/grid_camera.dart` | GridCamera | Isometric camera with zoom modes | ✅ Complete (⚠️ Animation TODO) | +| `camera/grid_camera_config.dart` | GridCameraConfig | Camera configuration parameters | ✅ Complete | + +**Known Issues:** +- Line 302: TODO comment for smooth animation not implemented +- Hardcoded zoom levels (should be in config) + +#### Game Components + +| File | Class | Purpose | Status | Renders | +|-------|-------|---------|--------|---------| +| `components/grid_component.dart` | GridComponent | 50×50 isometric grid renderer | ✅ Complete | Grid tiles, debug info | +| `components/building_component.dart` | BuildingComponent | Building sprite and interaction detection | ✅ Complete | Building sprites with glow | + +**Features:** +- Grid culling (spatial optimization) +- Isometric coordinate conversion +- Touch detection for tap interactions + +### lib/data/ - Data Persistence (If Exists) + +**Status:** Not yet reviewed in detail. Expected to contain: +- `models/` - JSON-serializable data classes +- `repositories/` - Hive and Firebase implementations +- `datasources/` - Local and remote data sources + +--- + +## test/ - Unit Tests + +### Unit Test Files + +| File | Tests | Coverage | Status | +|------|-------|----------|--------| +| `domain/entities/building_test.dart` | Building entity | Medium | ✅ Complete | +| `domain/entities/resource_test.dart` | Resource entity | Medium | ✅ Complete | +| `domain/entities/player_economy_test.dart` | PlayerEconomy | High | ✅ Complete | +| `domain/usecases/collect_resources_test.dart` | CollectResourcesUseCase | High (~40 tests) | ✅ Complete | +| `domain/usecases/upgrade_building_test.dart` | UpgradeBuildingUseCase | High (~30 tests) | ✅ Complete | +| `game/camera/grid_camera_test.dart` | GridCamera | Medium | ✅ Complete | +| `game/components/building_component_test.dart` | BuildingComponent | Medium | ✅ Complete | +| `game/components/grid_component_test.dart` | GridComponent | Medium | ✅ Complete | +| `hive_storage_test.dart` | Hive adapter registration | Low | ✅ Basic | +| `widget_test.dart` | Generic Flutter test | Low | ✅ Placeholder | + +**Summary:** +- ~70-80 unit tests estimated +- Good coverage for domain layer +- Missing presentation layer tests + +--- + +## integration_test/ - Integration Tests + +| File | Tests | Status | Issue | +|------|-------|--------|-------| +| `core_gameplay_loop_test.dart` | Core gameplay COLLECT→UPGRADE flow | ❌ Won't Compile | BUG #1: Wrong parameter name | + +**Issues:** +- Integration test uses wrong parameter name `buildingId` instead of `building` +- Cannot verify if actual gameplay works until this is fixed + +--- + +## pubspec.yaml - Dependencies + +| Dependency | Version | Purpose | Status | +|-----------|---------|---------|--------| +| flutter | 3.16+ | UI framework | ✅ | +| flame | 1.33.0 | 2D game engine | ✅ | +| riverpod | 3.0+ | State management | ✅ | +| firebase_core | latest | Firebase backend | ✅ | +| firebase_auth | latest | Auth service | ✅ | +| firebase_firestore | latest | Cloud database | ✅ | +| firebase_analytics | latest | Event tracking | ✅ | +| hive | latest | Local storage | ✅ | +| hive_flutter | latest | Hive UI | ✅ | + +--- + +## Key Statistics + +| Metric | Value | +|--------|-------| +| **Total Files in lib/** | ~20 files | +| **Domain Layer Files** | 9 files | +| **Game Layer Files** | 6 files | +| **Test Files** | ~15 files | +| **Total Lines of Code** | ~3,500 (estimated) | +| **Total Test Lines** | ~1,500 (estimated) | + +--- + +## File Organization Rules + +### Adding New Files + +When adding new code, follow this pattern: + +1. **Domain logic** → `lib/domain/{layer}/{name}.dart` + - Layer: `core/`, `entities/`, `usecases/`, `repositories/` + - Example: `lib/domain/usecases/build_conveyor_usecase.dart` + +2. **Game components** → `lib/game/components/{name}_component.dart` + - Example: `lib/game/components/conveyor_component.dart` + +3. **Data/persistence** → `lib/data/{layer}/{name}.dart` + - Layer: `models/`, `datasources/`, `repositories/` + +4. **Tests** → Mirror lib structure in `test/` + - Unit test: `test/domain/usecases/build_conveyor_test.dart` + - Integration test: `integration_test/conveyor_flow_test.dart` + +### File Naming + +- **Dart files:** snake_case.dart + - UseCase: `collect_resources_usecase.dart` + - Entity: `building.dart` + - Component: `building_component.dart` + +- **Classes:** PascalCase + - `CollectResourcesUseCase` + - `BuildingComponent` + - `GridCamera` + +- **Functions/methods:** camelCase + - `collectResources()` + - `calculateProduction()` + +--- + +## How to Update This File + +When you add/modify files: + +1. Add new row to appropriate table +2. Update **Key Statistics** at bottom +3. Include file status (✅ Complete, ⏳ In Progress, ❌ Broken) +4. Include test status if applicable +5. Note any known issues or TODOs +6. Update "Last Updated" date + +**This file is AI-optimized to reduce search time. Keep it accurate!** diff --git a/.claude/PATTERNS.md b/.claude/PATTERNS.md new file mode 100644 index 0000000..0637be8 --- /dev/null +++ b/.claude/PATTERNS.md @@ -0,0 +1,611 @@ +# PATTERNS - Code Patterns & Conventions + + + +Last Updated: 2025-12-02 + +--- + +## Quick Reference + +When writing code, use these proven patterns from the existing codebase. + +--- + +## Clean Architecture Layers + +### 1. Domain Layer (Business Logic) + +Domain layer is **framework-independent**. No imports of Flutter, Flame, or external packages except core types. + +```dart +// lib/domain/usecases/collect_resources_usecase.dart + +import 'package:trade_factory_masters/domain/core/result.dart'; +import 'package:trade_factory_masters/domain/entities/building.dart'; +import 'package:trade_factory_masters/domain/entities/player_economy.dart'; + +enum CollectError { generic } + +class CollectResourcesUseCase { + Result execute({ + required PlayerEconomy economy, + required Building building, + }) { + // Pure business logic - no side effects + // Return Result.success() or Result.failure() + return Result.success(updatedEconomy); + } +} +``` + +**Key Points:** +- No Flutter imports +- Stateless (pure functions) +- Return Result type +- Throw no exceptions (use Result instead) + +### 2. Game Layer (Flame Components) + +Game components handle rendering and interaction only. Complex logic should be in domain layer. + +```dart +// lib/game/components/building_component.dart + +import 'package:flame/components.dart'; + +class BuildingComponent extends PositionComponent { + late Sprite _sprite; + bool _isSelected = false; + + @override + Future onLoad() async { + _sprite = await Sprite.load('images/buildings/farm.png'); + size = Vector2(64, 64); + } + + @override + void render(Canvas canvas) { + _sprite.render(canvas, position: position, size: size); + if (_isSelected) { + _drawSelectedIndicator(canvas); + } + } + + @override + void onTapDown(TapDownEvent event) { + _isSelected = !_isSelected; + } +} +``` + +**Key Points:** +- Inherit from appropriate Flame component +- Keep rendering separate from logic +- Delegate business logic to domain layer +- Use onLoad() for resource initialization + +### 3. Entity Pattern + +Entities are immutable, represent core domain objects. + +```dart +// lib/domain/entities/building.dart + +class Building { + final String id; + final String name; + final int level; + final double productionRate; // resources per second + + const Building({ + required this.id, + required this.name, + required this.level, + required this.productionRate, + }); + + // Create modified copy (immutability pattern) + Building copyWith({ + String? id, + String? name, + int? level, + double? productionRate, + }) { + return Building( + id: id ?? this.id, + name: name ?? this.name, + level: level ?? this.level, + productionRate: productionRate ?? this.productionRate, + ); + } + + // Equality for testing + @override + bool operator ==(Object other) => + identical(this, other) || + other is Building && + runtimeType == other.runtimeType && + id == other.id && + level == other.level; + + @override + int get hashCode => id.hashCode ^ level.hashCode; +} +``` + +**Key Points:** +- Use `const` constructor (enables compiler optimization) +- Implement `==` and `hashCode` for testing +- Use `copyWith()` for immutable updates +- No mutable state + +### 4. Use Case Pattern + +Use cases orchestrate domain logic and return Result type. + +```dart +// lib/domain/usecases/upgrade_building_usecase.dart + +import 'package:trade_factory_masters/domain/core/result.dart'; + +enum UpgradeError { + insufficientGold, + maxLevelReached, + generic, +} + +class UpgradeBuildingUseCase { + Result execute({ + required PlayerEconomy economy, + required Building building, + }) { + // Validate preconditions + if (economy.gold < building.upgradeCost) { + return Result.failure(UpgradeError.insufficientGold); + } + + if (building.level >= building.maxLevel) { + return Result.failure(UpgradeError.maxLevelReached); + } + + // Execute domain logic + final upgradedBuilding = building.copyWith( + level: building.level + 1, + productionRate: building.productionRate * 1.2, + ); + + final updatedEconomy = economy + .removeGold(building.upgradeCost) + .updateBuilding(upgradedBuilding); + + return Result.success(updatedEconomy); + } +} +``` + +**Key Points:** +- Method is called `execute()` +- Returns `Result` +- Validate preconditions first +- Use domain objects, not data models + +--- + +## Error Handling Pattern + +### Result Type + +```dart +// lib/domain/core/result.dart + +abstract class Result { + const Result(); + + factory Result.success(Success value) = _Success; + factory Result.failure(Failure error) = _Failure; + + T fold( + T Function(Success) onSuccess, + T Function(Failure) onFailure, + ); +} + +class _Success extends Result { + final Success value; + const _Success(this.value); + + @override + T fold(T Function(Success) onSuccess, T Function(Failure) _) => + onSuccess(value); +} + +class _Failure extends Result { + final Failure error; + const _Failure(this.error); + + @override + T fold(T Function(Success) _, T Function(Failure) onFailure) => + onFailure(error); +} +``` + +### Usage in Code + +```dart +// Using fold() pattern (recommended) +final result = CollectResourcesUseCase().execute( + economy: currentEconomy, + building: selectedBuilding, +); + +result.fold( + (success) => updateGameState(success), + (failure) => showErrorDialog(failure), +); + +// Or check with pattern matching +if (result is _Success) { + updateGameState(result.value); +} else if (result is _Failure) { + showErrorDialog(result.error); +} +``` + +**Benefits:** +- No exceptions thrown +- Type-safe error handling +- Forces you to handle failure case +- Composable and testable + +--- + +## State Management Pattern (Riverpod) + +### Provider Pattern + +```dart +// lib/infrastructure/providers/game_state_provider.dart + +import 'package:riverpod/riverpod.dart'; +import 'package:trade_factory_masters/domain/entities/player_economy.dart'; + +// Simple state provider (mutable) +final gameStateProvider = StateProvider((ref) { + return PlayerEconomy( + gold: 100, + buildings: [], + inventory: {}, + tier: 1, + lastSeen: DateTime.now(), + ); +}); + +// Use in UI (ConsumerWidget) +class GameScreen extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final gameState = ref.watch(gameStateProvider); + + return Scaffold( + body: Text('Gold: ${gameState.gold}'), + floatingActionButton: FloatingActionButton( + onPressed: () { + ref.read(gameStateProvider.notifier).state = + gameState.copyWith(gold: gameState.gold + 10); + }, + ), + ); + } +} +``` + +### Using with Use Cases + +```dart +// Define use case as provider +final collectResourcesProvider = Provider((ref) { + return CollectResourcesUseCase(); +}); + +// Use in ConsumerWidget +class GameScreen extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final gameState = ref.watch(gameStateProvider); + final collectResources = ref.watch(collectResourcesProvider); + + return GestureDetector( + onTap: () { + final result = collectResources.execute( + economy: gameState, + building: selectedBuilding, + ); + + result.fold( + (success) { + ref.read(gameStateProvider.notifier).state = success; + }, + (failure) => showError(failure), + ); + }, + ); + } +} +``` + +--- + +## Camera/Grid Pattern + +### Coordinate Conversion + +```dart +// Converting between grid and screen coordinates + +// Grid coordinates (0,0 to 50,49) → Screen coordinates (pixels) +Vector2 gridToScreen(int gridX, int gridY) { + final screenX = (gridX - gridY) * tileWidth / 2; + final screenY = (gridX + gridY) * tileHeight / 2; + return Vector2(screenX, screenY); +} + +// Screen coordinates (pixels) → Grid coordinates +Pair screenToGrid(Vector2 screenPos) { + final gridX = (screenPos.x / tileWidth + screenPos.y / tileHeight).toInt(); + final gridY = (screenPos.y / tileHeight - screenPos.x / tileWidth).toInt(); + return Pair(gridX, gridY); +} +``` + +### Camera Zoom Example + +```dart +// Zoom levels +const double MIN_ZOOM = 0.3; +const double MAX_ZOOM = 2.0; + +// Apply zoom (in game component) +canvas.scale(zoomLevel); +canvas.translate(-camera.position.x, -camera.position.y); +// render components +``` + +--- + +## Testing Patterns + +### Unit Test Pattern + +```dart +// test/domain/entities/building_test.dart + +import 'package:flutter_test/flutter_test.dart'; +import 'package:trade_factory_masters/domain/entities/building.dart'; + +void main() { + group('Building', () { + test('creates building with correct properties', () { + const building = Building( + id: 'farm-1', + name: 'Farm', + level: 1, + productionRate: 1.0, + ); + + expect(building.id, equals('farm-1')); + expect(building.level, equals(1)); + expect(building.productionRate, equals(1.0)); + }); + + test('copyWith creates new instance with updated values', () { + const original = Building( + id: 'farm-1', + name: 'Farm', + level: 1, + productionRate: 1.0, + ); + + final updated = original.copyWith(level: 2); + + expect(original.level, equals(1)); // Original unchanged + expect(updated.level, equals(2)); // New instance has update + expect(updated.id, equals('farm-1')); // Other fields unchanged + }); + + test('equality works correctly', () { + const building1 = Building( + id: 'farm-1', + name: 'Farm', + level: 1, + productionRate: 1.0, + ); + + const building2 = Building( + id: 'farm-1', + name: 'Farm', + level: 1, + productionRate: 1.0, + ); + + expect(building1, equals(building2)); + }); + }); +} +``` + +### Integration Test Pattern + +```dart +// integration_test/core_gameplay_loop_test.dart + +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; +import 'package:trade_factory_masters/main.dart' as app; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + testWidgets('complete gameplay loop', (WidgetTester tester) async { + app.main(); + await tester.pumpAndSettle(); + + // Test steps + expect(find.text('Gold: 100'), findsOneWidget); + + // Tap building + await tester.tap(find.byType(BuildingComponent)); + await tester.pumpAndSettle(); + + // Verify result + expect(find.text('Gold: 110'), findsOneWidget); + }); +} +``` + +--- + +## File Naming Conventions + +| Element | Format | Example | +|---------|--------|---------| +| File | snake_case.dart | `collect_resources_usecase.dart` | +| Class | PascalCase | `CollectResourcesUseCase` | +| Enum | PascalCase | `CollectError` | +| Function | camelCase | `collectResources()` | +| Variable | camelCase | `currentEconomy` | +| Constant | UPPER_SNAKE_CASE | `MAX_GRID_WIDTH` | +| Private field | _camelCase | `_isSelected` | +| Private function | _camelCase | `_drawGlowEffect()` | + +--- + +## Import Organization + +```dart +// 1. Dart imports first +import 'dart:async'; +import 'dart:math'; + +// 2. Flutter imports +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +// 3. Package imports (external) +import 'package:flame/components.dart'; +import 'package:riverpod/riverpod.dart'; + +// 4. Project imports (internal) +import 'package:trade_factory_masters/domain/entities/building.dart'; +import 'package:trade_factory_masters/domain/usecases/collect_resources_usecase.dart'; + +// 5. Relative imports (for same package, sparingly) +import '../entities/building.dart'; +``` + +--- + +## Code Style Guidelines + +### Formatting + +- Use `dart format` automatically (run before commit) +- Max line length: 120 characters +- 2-space indentation + +### Comments + +```dart +// Use single-line comments for single statements +int calculateCost(int level) { + // Production cost increases exponentially with level + return 10 * (2 << level); +} + +// Use doc comments (///) for public APIs +/// Calculates the cost to upgrade a building to next level +/// +/// [level] Current building level +/// Returns the gold cost for next upgrade +int calculateUpgradeCost(int level) { + return 10 * (2 << level); +} +``` + +### Null Safety + +```dart +// Always use non-null types where possible +String name; // ✅ Required + +// Use ? only when null is a valid value +String? nickname; // ✅ Nullable + +// Use ! only after null checks +final value = maybeNull; +if (value != null) { + print(value.length); // ✅ Type narrowing +} +``` + +--- + +## Avoid Common Mistakes + +### ❌ DON'T + +```dart +// Don't throw exceptions in domain layer +throw Exception('Not enough gold'); + +// Don't mix UI and domain logic +void collect() { + final result = useCase.execute(...); + navigator.push(...); // UI code in domain! +} + +// Don't use mutable state in entities +class Building { + int level = 1; // ❌ Mutable +} + +// Don't hardcode values +final maxZoom = 2.0; // ❌ Magic number +``` + +### ✅ DO + +```dart +// Return Result type instead +return Result.failure(CollectError.insufficientGold); + +// Keep domain logic separate from UI +final result = useCase.execute(...); +result.fold( + (success) => ref.read(provider.notifier).state = success, + (failure) => showError(failure), +); + +// Use immutable entities +class Building { + final int level; + Building({required this.level}); +} + +// Extract magic numbers to constants +static const double MAX_ZOOM = 2.0; +``` + +--- + +## How to Update This File + +When discovering new patterns or established conventions: + +1. Add new section with clear example +2. Show both pattern and anti-pattern if relevant +3. Explain why this pattern is preferred +4. Reference files where pattern is used +5. Include test examples if applicable + +**This file is AI-optimized for quick pattern lookup. Keep examples short and clear!** diff --git a/.claude/PROMPTS.md b/.claude/PROMPTS.md new file mode 100644 index 0000000..fca0bc6 --- /dev/null +++ b/.claude/PROMPTS.md @@ -0,0 +1,537 @@ +# PROMPTS - Ready-to-Use Task Prompts + + + +Last Updated: 2025-12-02 + +--- + +## Using These Prompts + +These are **starting templates** for common tasks. Customize with specifics: + +- Replace `{PLACEHOLDER}` with actual values +- Add context from epic files +- Include file:line references when discussing bugs +- Reference PATTERNS.md for code style + +--- + +## 1. Fix Critical Bug + +Use this when starting work on a known bug. + +``` +Task: Fix Bug - {BUG_NAME} + +Status: The bug is documented in docs/2-MANAGEMENT/EPIC-1-ISSUES.md - Bug #{NUMBER} + +Bug Description: +- Location: {FILE}:{LINE} +- Issue: {WHAT'S WRONG} +- Impact: {WHY IT MATTERS} +- Expected behavior: {WHAT SHOULD HAPPEN} + +Requirements: +1. Read the bug documentation +2. Read the affected code file +3. Fix the bug +4. Add/update unit tests +5. Verify the fix doesn't break other tests +6. Commit with message: "fix: {description}" + +After completing: +- Update CLAUDE.md Known Issues section (remove if fixed) +- Update FILE-MAP.md status +- Update docs/2-MANAGEMENT/project-status.md +``` + +**Examples:** + +``` +Task: Fix Bug #1 - Integration Test Compilation Error + +Location: integration_test/core_gameplay_loop_test.dart + +Details: +- The test uses wrong parameter name 'buildingId' instead of 'building' +- UpgradeBuilding.execute() expects Building object, not String +- Integration test won't compile + +Requirements: +1. Open integration_test/core_gameplay_loop_test.dart +2. Find all lines with "buildingId:" (expect ~4 instances) +3. Change to "building: {buildingName}" +4. Run: flutter test integration_test/ +5. Verify test compiles and runs +6. Commit with: "fix: correct integration test parameters" +``` + +--- + +## 2. Implement New Feature (Story) + +Use when implementing a story from the epic backlog. + +``` +Task: Implement Story - {EPIC}.{STORY_NUMBER}: {STORY_NAME} + +Sprint: {SPRINT_NUMBER} +Story Points: {SP} +Priority: {P0/P1/P2} + +Story Description: +As a {USER_TYPE} +I want {ACTION} +So that {BENEFIT} + +Acceptance Criteria: +- [ ] {AC1} +- [ ] {AC2} +- [ ] {AC3} + +Technical Notes: +{FROM EPIC FILE} + +Dependencies: +- {STORY_X.Y} (if any) + +Requirements: +1. Read full story in docs/2-MANAGEMENT/epics/epic-{N}.md +2. Review PATTERNS.md for relevant patterns +3. Create files following FILE-MAP.md organization +4. Write unit tests as you code +5. Ensure all tests pass +6. Update FILE-MAP.md with new files +7. Update epic story status: ✅ Done +8. Update project-status.md progress + +Architecture: +- Domain logic: lib/domain/{core|entities|usecases}/ +- Game code: lib/game/components/ or lib/game/camera/ +- Tests: test/ or integration_test/ +- Follow patterns from PATTERNS.md +``` + +**Example:** + +``` +Task: Implement Story - EPIC-02.1: Building Definitions + +Story Points: 8 +Sprint: Sprint 2 + +Story: +As a Player +I want to know what resources each building produces and costs +So that I can plan my factory efficiently + +Acceptance Criteria: +- [ ] Create BuildingConfig class with production/upgrade data +- [ ] Load configs from JSON file +- [ ] Farm produces 1 wood per second +- [ ] Mine produces 1 iron per second +- [ ] Upgrade cost formula works (100 * level^2) +- [ ] All configs tested + +Technical Implementation: +- Create lib/domain/entities/building_config.dart +- Create building_configs.json data file +- Implement config loader in data layer +- Add unit tests for configs +- Integration test: verify loaded configs match expected values + +Dependencies: +- STORY-01.2: Resource entity (DONE) +``` + +--- + +## 3. Continue Work on Project + +Use when resuming work or checking status. + +``` +Task: Continue Development on FantasyFactio + +First Steps: +1. Read CLAUDE.md (current status) +2. Read docs/2-MANAGEMENT/project-status.md (progress) +3. Read docs/2-MANAGEMENT/MVP-TODO.md (what's left) +4. Review latest epic in docs/2-MANAGEMENT/epics/ + +Current Context: +- Phase: {EPIC_PHASE} +- Completed: {STORIES_DONE} +- In Progress: {CURRENT_WORK} +- Next: {UPCOMING} + +Your Task: +1. Summarize project status +2. List 3 next prioritized tasks +3. Identify any blockers +4. Suggest next action (with detailed steps) + +Focus Areas: +- Epic 1 bug fixes (Critical) +- Epic 2 planning/implementation (High Priority) +- Documentation updates (Medium Priority) +``` + +--- + +## 4. Create Documentation + +Use when writing or updating project documentation. + +``` +Task: Update Documentation - {TOPIC} + +Type: {Bug Report / Architecture / Feature / Progress} +Target Audience: {Developer / Team Lead / Product Manager} + +Content Requirements: +1. {WHAT TO INCLUDE} +2. {WHAT TO INCLUDE} +3. {FORMAT/STRUCTURE} + +Location: docs/{PATH}/{filename}.md + +Template Structure: +- Title +- Quick Summary (1-3 sentences) +- Context (if needed) +- Content (main body) +- Examples (if applicable) +- References (links to related docs) +- Last Updated + +After writing: +1. Proof-read for clarity +2. Add AI-INDEX comment at top +3. Check for broken internal links +4. Update CLAUDE.md if relevant +``` + +**Example:** + +``` +Task: Create Epic 1 Issues Document + +Type: Bug Report +Location: docs/2-MANAGEMENT/EPIC-1-ISSUES.md + +Content: +- Title: Epic 1 - Identified Issues & Fixes +- Overview: List of bugs found during Epic 1 code review +- Critical Issues (with detailed fixes) + - Bug #1: Integration Test Compilation + - Bug #2: Resource Inventory Logic + - Bug #3: Type Cast Syntax +- Medium Issues (nice-to-fix) +- Testing Strategy (how to verify fixes) +- Commit History (once fixed) + +Format: Markdown, use tables for organization +``` + +--- + +## 5. Code Review + +Use when reviewing implementation or helping debug. + +``` +Task: Code Review - {FILE_PATH} + +Purpose: {Review for correctness / Test coverage / Performance} + +Files to Review: +- {lib/path/file1.dart} +- {lib/path/file2.dart} + +Checklist: +- [ ] Follows patterns from PATTERNS.md +- [ ] Properly handles errors (Result type) +- [ ] Tests exist and cover edge cases +- [ ] No hardcoded values (use constants) +- [ ] Immutability enforced (entities) +- [ ] Naming follows conventions +- [ ] No performance issues +- [ ] Comments where logic isn't obvious + +For Each File: +1. Summarize what the code does +2. List any issues found (with severity) +3. Suggest improvements (if appropriate) +4. Check against PATTERNS.md +5. Verify tests exist + +Output Format: +## {Filename} +**Status:** {✅ Looks good / ⚠️ Needs fixes / ❌ Blocked} +**Summary:** {What it does} +**Issues:** {List any problems} +**Suggestions:** {Improvements} +``` + +--- + +## 6. Run Tests & Verify + +Use when testing implementation. + +``` +Task: Run Tests & Verify Implementation + +Test Type: {Unit / Integration / All} +Scope: {Specific file / Specific feature / All tests} + +Commands: +1. Unit tests: + flutter test test/ + +2. Integration tests: + flutter test integration_test/ + +3. Code analysis: + flutter analyze + +4. Specific test file: + flutter test test/domain/entities/building_test.dart + +After Running: +1. Report which tests pass/fail +2. If failures: provide error messages +3. Identify patterns in failures +4. Suggest fixes for failing tests +5. Verify coverage for modified files + +Success Criteria: +- All tests pass ✅ +- No warnings from analysis ✅ +- Coverage > 80% for touched code ✅ +``` + +--- + +## 7. Refactor Code + +Use when improving existing code without changing behavior. + +``` +Task: Refactor - {WHAT TO IMPROVE} + +Scope: {Specific function / Entire class / Multiple files} +Goal: {Improve readability / Remove duplication / Extract constants} + +Before Changes: +1. Read and understand current implementation +2. Identify what needs improvement +3. Check if existing tests cover this code +4. Plan refactoring steps + +Refactoring Steps: +1. {Step 1 - what to change} +2. {Step 2 - verify still works} +3. {Step 3 - test} + +After Refactoring: +- [ ] All tests still pass +- [ ] No functional changes +- [ ] Code is clearer/more maintainable +- [ ] Commit message explains why + +Commit Format: +refactor: {description of improvement} +``` + +**Example:** + +``` +Task: Refactor - Extract Magic Numbers to Constants + +Goal: Improve maintainability by removing hardcoded values + +Files to Update: +- lib/main.dart (grid config, camera config) +- lib/game/components/building_component.dart (offsets, radius) + +Steps: +1. Create lib/config/game_config.dart +2. Define constants: GRID_WIDTH, GRID_HEIGHT, MIN_ZOOM, MAX_ZOOM, etc. +3. Update lib/main.dart to import and use constants +4. Update lib/game/components/building_component.dart +5. Run: flutter test +6. Commit: refactor: extract game config constants +``` + +--- + +## 8. Database/Schema Changes + +Use when modifying data models or storage. + +``` +Task: Update Data Model - {MODEL_NAME} + +Type: {Add field / Remove field / Modify structure} +Scope: {Domain entity / Firestore schema / Hive storage} + +Current State: +- Current model in: {FILE_PATH} +- Related schema in: .claude/TABLES.md + +Changes: +1. {What to add/change} +2. {Affects} +3. {Migration needed} + +Implementation Checklist: +- [ ] Update domain entity (lib/domain/entities/) +- [ ] Add/update copyWith() if fields changed +- [ ] Update == and hashCode +- [ ] Update TABLES.md schema doc +- [ ] Create/update tests +- [ ] Update any dependent code +- [ ] Plan Firestore migration (if needed) +- [ ] Plan Hive migration (if needed) + +Testing: +- [ ] Unit tests for new/changed fields +- [ ] Serialization/deserialization tests +- [ ] Backward compatibility tests (if migrating) + +Commit: +feat: add {field} to {Model} entity +or +refactor: update {Model} schema +``` + +--- + +## 9. Performance Investigation + +Use when investigating performance issues. + +``` +Task: Performance Investigation - {ISSUE} + +Symptom: {What's slow / What's using too much memory / What's crashing} +Impact: {How it affects gameplay / Users} + +Investigation Steps: +1. Identify the bottleneck + - Is it CPU? (profiling needed) + - Is it memory? (heap analysis) + - Is it rendering? (frame drops) + - Is it storage? (Hive/Firestore) + +2. Measure current performance + - FPS: {measure in game} + - Memory: {check device monitor} + - Load time: {measure with diagnostics} + +3. Profile affected code + - Add performance markers + - Measure specific operations + - Identify slowest parts + +4. Propose optimizations + - Code changes + - Architecture changes + - Algorithm improvements + +5. Implement & test + - Apply optimization + - Re-measure performance + - Verify no regression elsewhere + +Report Format: +- Current: {metric X} +- Target: {metric Y} +- Optimization: {what was changed} +- Result: {new metric} +- Impact: {how much better} +``` + +--- + +## Template Variables Reference + +| Variable | Replace With | Example | +|----------|--------------|---------| +| `{BUG_NAME}` | Short bug title | Integration Test Parameter Mismatch | +| `{FILE}` | File path | lib/domain/entities/player_economy.dart | +| `{LINE}` | Line number | 52-56 | +| `{EPIC}` | Epic number | EPIC-02 | +| `{STORY_NUMBER}` | Story number | 2.1 | +| `{SP}` | Story points | 8 | +| `{SPRINT_NUMBER}` | Sprint number | Sprint 2 | +| `{USER_TYPE}` | Type of user | Player / Game Master | +| `{ACTION}` | What user does | collect resources from buildings | +| `{BENEFIT}` | Why it matters | progress in the game | +| `{AC}` | Acceptance criteria | building on grid works correctly | + +--- + +## Workflow Tips + +### Before Starting Any Task + +1. Read the relevant prompt template above +2. Customize with specific context +3. Read referenced documentation +4. Check for dependencies + +### During Implementation + +1. Refer back to prompt for requirements +2. Use PATTERNS.md for code examples +3. Keep tests passing throughout +4. Update FILE-MAP.md as you go + +### After Completing + +1. Update status in epic file +2. Update project-status.md +3. Commit with good message +4. Note any blockers for next task + +--- + +## Common Workflow Chains + +### Fix Critical Bug → Move to Next Epic + +``` +1. Fix Bug (use Prompt #1) +2. Update docs (use Prompt #4) +3. Run Tests (use Prompt #6) +4. Plan Epic 2 (use Prompt #2) +``` + +### Implement Full Epic (Multiple Stories) + +``` +For Each Story: + 1. Use Prompt #2 (Implement Feature) + 2. Use Prompt #6 (Run Tests) + 3. Use Prompt #3 (Continue Work - check status) +``` + +### Performance Improvements + +``` +1. Use Prompt #9 (Performance Investigation) +2. Use Prompt #7 (Refactor Code) +3. Use Prompt #6 (Run Tests & Verify) +``` + +--- + +## Last Updated + +- Date: 2025-12-02 +- Total Prompts: 9 +- Added: Documentation, Code Review, Performance Prompts diff --git a/.claude/TABLES.md b/.claude/TABLES.md new file mode 100644 index 0000000..fe4a946 --- /dev/null +++ b/.claude/TABLES.md @@ -0,0 +1,450 @@ +# TABLES - Database Schema & Entity Models + + + +Last Updated: 2025-12-02 + +--- + +## Quick Reference + +Game state is stored in: +- **Local:** Hive (offline-first, on device) +- **Remote:** Firebase Firestore (cloud sync, multi-device) + +**Sync Strategy:** Optimistic local updates → async cloud sync + +--- + +## Core Data Models + +### 1. PlayerEconomy (Game State) + +**Purpose:** Represents current player progress and inventory + +**Location:** `lib/domain/entities/player_economy.dart` + +**Fields:** + +| Field | Type | Required | Constraints | Notes | +|-------|------|----------|-------------|-------| +| playerId | String | ✓ | UUID | Who owns this economy | +| gold | int | ✓ | ≥ 0 | Currency for upgrades | +| buildings | List | ✓ | 0-50 | Player's buildings | +| inventory | Map | ✓ | Max capacity | Resources held | +| tier | int | ✓ | 1-3 | Progression tier | +| lastSeen | DateTime | ✓ | - | For offline production calc | + +**Example in Code:** + +```dart +const economy = PlayerEconomy( + playerId: 'player-123', + gold: 500, + buildings: [farmBuilding, minerBuilding], + inventory: { + 'wood': Resource(amount: 150), + 'iron': Resource(amount: 80), + }, + tier: 1, + lastSeen: DateTime.now(), +); +``` + +**Firestore Collection:** `players/{playerId}/economy` + +**Hive Box:** `player_economy` (key: playerId) + +--- + +### 2. Building (Domain Entity) + +**Purpose:** Definition of a building type and current instance + +**Location:** `lib/domain/entities/building.dart` + +**Fields:** + +| Field | Type | Required | Constraints | Notes | +|-------|------|----------|-------------|-------| +| id | String | ✓ | "farm-1", "mine-2" | Unique building instance | +| name | String | ✓ | 1-50 chars | Display name | +| type | BuildingType | ✓ | enum | farm, mine, factory, etc | +| level | int | ✓ | 1-10 | Upgrade level | +| gridX | int | ✓ | 0-49 | Grid position | +| gridY | int | ✓ | 0-49 | Grid position | +| productionRate | double | ✓ | ≥ 0.1 | Resources per second | +| production | String | ✓ | "wood", "iron" | What it produces | +| upgradeCost | int | ✓ | ≥ 10 | Gold per upgrade | +| maxLevel | int | ✓ | 5-10 | Level cap | + +**Firestore:** `players/{playerId}/buildings/{buildingId}` + +**Hive:** Nested in `player_economy` → buildings list + +**Example:** + +```dart +const farm = Building( + id: 'farm-1', + name: 'Farm', + type: BuildingType.farm, + level: 1, + gridX: 5, + gridY: 10, + productionRate: 1.0, + production: 'wood', + upgradeCost: 100, + maxLevel: 10, +); +``` + +--- + +### 3. Resource (Game Item) + +**Purpose:** Represents a tradeable/usable resource + +**Location:** `lib/domain/entities/resource.dart` + +**Fields:** + +| Field | Type | Required | Constraints | Notes | +|-------|------|----------|-------------|-------| +| id | String | ✓ | "wood", "iron" | Unique resource type | +| displayName | String | ✓ | 1-50 chars | UI display | +| type | ResourceType | ✓ | tier1, tier2 | Gameplay tier | +| amount | int | ✓ | 0 to maxCapacity | Current quantity held | +| maxCapacity | int | ✓ | ≥ 100 | Inventory limit per resource | +| iconPath | String | ✓ | "assets/..." | Sprite path for UI | + +**Firestore:** Nested in inventory under `players/{playerId}/economy` + +**Example:** + +```dart +const wood = Resource( + id: 'wood', + displayName: 'Wood', + type: ResourceType.tier1, + amount: 150, + maxCapacity: 500, + iconPath: 'assets/images/resources/wood.png', +); +``` + +--- + +## Firestore Collection Structure + +``` +firestore/ +└── players/ (Collection) + └── {playerId}/ (Document) + ├── email: "user@example.com" + ├── createdAt: Timestamp + ├── economy/ (Document) + │ ├── gold: 500 + │ ├── tier: 1 + │ ├── lastSeen: Timestamp + │ ├── buildings: [ + │ │ {id, name, level, gridX, gridY, ...}, + │ │ ... + │ │ ] + │ └── inventory: { + │ "wood": {id, amount, maxCapacity, ...}, + │ "iron": {...}, + │ ... + │ } + └── metadata/ (Document) + ├── lastModified: Timestamp + ├── dataVersion: 1 + └── platform: "mobile" +``` + +--- + +## Hive Box Structure + +Hive is used for local-first offline storage, synced to Firestore when online. + +### boxes Configuration + +```dart +// lib/infrastructure/hive/hive_boxes.dart + +class HiveBoxes { + static const String playerEconomy = 'player_economy'; + static const String buildings = 'buildings'; + static const String resources = 'resources'; + static const String metadata = 'metadata'; +} +``` + +### Data in Hive + +``` +Hive Boxes: +├── player_economy +│ └── playerId -> PlayerEconomy object +├── buildings +│ └── buildingId -> Building object +├── resources +│ └── resourceId -> Resource object +└── metadata + └── 'last_sync' -> DateTime + └── 'app_version' -> String +``` + +--- + +## Important Data Rules + +### 1. Immutability + +All entities are **immutable** - updates create new instances via `copyWith()`: + +```dart +// ❌ DON'T +economy.gold += 100; + +// ✅ DO +economy = economy.copyWith(gold: economy.gold + 100); +``` + +### 2. Grid Constraints + +Building positions must respect grid: + +```dart +// Grid is 50x50 (0-49 for both X and Y) +if (building.gridX < 0 || building.gridX >= 50) { + return false; // Invalid position +} +if (building.gridY < 0 || building.gridY >= 50) { + return false; // Invalid position +} +``` + +### 3. Resource Capacity + +Resources cannot exceed maxCapacity: + +```dart +final newAmount = min(resource.amount + collected, resource.maxCapacity); +``` + +### 4. Level Constraints + +Buildings have minimum (1) and maximum (maxLevel) levels: + +```dart +if (building.level < 1 || building.level > building.maxLevel) { + return false; // Invalid level +} +``` + +--- + +## Tier-Based Content Unlock + +Game has 3 tiers with progressive unlocks: + +| Tier | Buildings | Resources | Features | Unlock Condition | +|------|-----------|-----------|----------|-----------------| +| **1** | Farm, Mine | Wood, Iron | Manual collecting | Default | +| **2** | Conveyor, Splitter | Gold (ore) | Automation system | Reach Tier 2 milestone | +| **3** | Advanced Conveyor | Advanced resources | Economy deepens | Reach Tier 3 milestone | + +--- + +## Migration Strategy + +### Data Version + +All player data includes `dataVersion` to track schema changes: + +```dart +{ + "playerId": "...", + "dataVersion": 1, // ← Schema version + "economy": { ... } +} +``` + +**Current Version:** 1 + +**Migration Example:** + +```dart +// When schema changes, increment version and migrate +if (loadedData.dataVersion < 2) { + // Apply migrations + loadedData = migrateV1toV2(loadedData); + loadedData.dataVersion = 2; +} +``` + +--- + +## Type Enums + +### BuildingType + +```dart +enum BuildingType { + farm, // Produces wood + mine, // Produces iron + factory, // Refines resources (Tier 2+) + conveyor, // Transports resources (Tier 2+) +} +``` + +### ResourceType + +```dart +enum ResourceType { + tier1, // Basic resources (wood, iron) + tier2, // Refined resources (copper, gold) + tier3, // Advanced resources +} +``` + +--- + +## Backup & Sync + +### Local Backup (Hive) + +- Stored automatically on device +- Survives app crashes +- Used for offline play + +### Cloud Sync (Firestore) + +- Manual sync trigger via `SyncManager` +- Conflict resolution: client wins for UX (user action = authority) +- Async operation (doesn't block gameplay) + +### Edge Cases + +| Scenario | Handling | +|----------|----------| +| Offline then online | Local changes sync, cloud wins if older | +| Multi-device login | Latest timestamp wins | +| Server error | Retry with exponential backoff | +| Data corruption | Restore from backup | + +--- + +## How to Add New Data Models + +When adding new entity: + +1. Create `lib/domain/entities/{name}.dart` +2. Make immutable with `copyWith()` +3. Implement `==` and `hashCode` +4. Add to FILE-MAP.md +5. Create Firestore path in docs +6. Add Hive box (if persistent) +7. Add tests in `test/domain/entities/{name}_test.dart` + +**Example of adding new entity:** + +```dart +// lib/domain/entities/conveyor.dart +class Conveyor { + final String id; + final int gridXStart; + final int gridYStart; + final int gridXEnd; + final int gridYEnd; + final double efficiency; + + const Conveyor({ + required this.id, + required this.gridXStart, + required this.gridYStart, + required this.gridXEnd, + required this.gridYEnd, + required this.efficiency, + }); + + Conveyor copyWith({...}) { + return Conveyor(...); + } + + @override + bool operator ==(Object other) => ...; + + @override + int get hashCode => ...; +} +``` + +--- + +## Performance Considerations + +### Index Strategy (Firestore) + +For efficient queries, create indexes on: +- `players.createdAt` (user listing) +- `players.economy.lastModified` (sync detection) + +### Hive Optimization + +- Use TypeID adapters for custom objects +- Keep box size reasonable (split if > 1MB) +- Don't serialize unnecessary fields + +### Data Size + +**Target:** < 500KB per player (uncompressed) + +| Component | Typical Size | +|-----------|--------------| +| Buildings (50 max) | ~50 KB | +| Inventory (20 resources) | ~5 KB | +| Metadata | ~1 KB | +| **Total** | **~56 KB** | + +--- + +## Query Examples + +### Get Current Player Economy + +```dart +// From Firestore +final doc = await FirebaseFirestore.instance + .collection('players') + .doc(playerId) + .collection('economy') + .doc('current') + .get(); + +// From Hive +final economy = hiveBox.get(playerId) as PlayerEconomy; +``` + +### Get All Buildings + +```dart +// From economy object (local) +final buildings = economy.buildings; + +// From Firestore (if stored separately) +final snapshot = await FirebaseFirestore.instance + .collection('players/$playerId/buildings') + .get(); +``` + +--- + +## Last Updated + +- Date: 2025-12-02 +- Schema Version: 1 +- Firestore Paths: Finalized +- Hive Structure: Finalized diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..ce4b243 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,331 @@ +# FantasyFactio / Trade Factory Masters - AI Assistant Guide + + + +## Quick Facts + +| Aspect | Value | +|--------|-------| +| **Project Name** | Trade Factory Masters | +| **Repository** | FantasyFactio | +| **Type** | Mobile Game (Flutter/Flame) | +| **Primary Tech Stack** | Flutter 3.16+, Flame 1.33.0, Dart 3.2 | +| **State Management** | Riverpod 3.0 | +| **Backend** | Firebase (Auth, Firestore, Analytics) | +| **Local Storage** | Hive | +| **Architecture** | Clean Architecture (Domain, Data, Presentation, Game Engine layers) | +| **Target Platform** | Mobile (Android primary, iOS secondary), Desktop planned Month 6-7 | +| **Performance Target** | 60 FPS on budget Android (Snapdragon 660) | +| **Current Status** | Epic 1 Completed (with bugs), Epic 2+ in Planning | +| **Overall Progress** | ~16% (47 SP / 289 SP MVP scope) | +| **Current Branch** | `claude/project-status-display-01WgeBaEE9s5pXkKZraeZEwN` | + +--- + +## Documentation Index + +### Critical AI-Optimized Files (.claude/) + +These files are designed to be read by AI first - they contain condensed, structured information: + +| File | Purpose | When to Read | +|------|---------|--------------| +| [.claude/FILE-MAP.md](.claude/FILE-MAP.md) | Index of all code files by category | Before any code work | +| [.claude/TABLES.md](.claude/TABLES.md) | Database schema and entity relationships | When implementing data features | +| [.claude/PATTERNS.md](.claude/PATTERNS.md) | Code patterns, conventions, examples | When writing new code | +| [.claude/PROMPTS.md](.claude/PROMPTS.md) | Ready-to-use task prompts | When structuring work | + +### Human-Readable Documentation Structure (docs/) + +``` +docs/ +├── 00-START-HERE.md ← First read for humans +├── BMAD-STRUCTURE.md ← How docs are organized +├── 1-BASELINE/ +│ ├── product/ +│ │ ├── prd-v1.0.md ← Requirements +│ │ ├── product-brief.md ← Vision & market gap +│ │ └── market-research.md ← Competitive analysis +│ └── architecture/ +│ ├── system-architecture.md ← Technical design +│ ├── database-schema.md ← Entity models +│ └── tech-decisions.md ← Why these choices +│ +├── 2-MANAGEMENT/ +│ ├── project-status.md ← Current state +│ ├── MVP-TODO.md ← What's left +│ └── epics/ +│ ├── epic-00-project-setup.md +│ ├── epic-01-core-gameplay.md +│ └── ...epic-02-12... +│ +├── 4-DEVELOPMENT/ +│ ├── SETUP.md ← How to set up dev environment +│ ├── DEVELOPMENT.md ← Dev guidelines & workflow +│ └── TROUBLESHOOTING.md ← Common issues +│ +└── 5-ARCHIVE/ + └── [deprecated docs from 2025-11-17] +``` + +--- + +## Code Structure + +### Main Directories + +``` +trade_factory_masters/lib/ +├── main.dart ← App entry point +├── domain/ ← Business logic (Framework-independent) +│ ├── core/ ← Shared domain types (Result, Either) +│ ├── entities/ ← Building, Resource, PlayerEconomy +│ └── usecases/ ← CollectResources, UpgradeBuilding +├── game/ ← Game engine layer (Flame) +│ ├── camera/ ← GridCamera, zoom system +│ └── components/ ← BuildingComponent, GridComponent +├── data/ ← Data persistence +│ ├── models/ ← JSON serializable data classes +│ ├── repositories/ ← Hive + Firebase implementations +│ └── datasources/ ← Local (Hive) and remote (Firebase) +└── presentation/ ← Flutter UI (if exists) + +test/ ← Unit tests +integration_test/ ← Integration tests +``` + +### Current Implementation Status + +| Layer | Status | Key Files | +|-------|--------|-----------| +| **Domain** | ✅ Complete (8 files) | entities/, usecases/, core/ | +| **Game Engine** | ✅ Complete | camera/, components/ | +| **Data** | ⚠️ Partial | models/, datasources/ (Hive working, Firebase untested) | +| **Presentation** | ⏳ Planned | Not yet implemented | +| **Tests** | ⚠️ Partial | Unit tests: ✅, Integration tests: ❌ (won't compile) | + +--- + +## Known Issues & Bugs (Epic 1) + +**CRITICAL - Must Fix Before Epic 2:** + +1. **Integration Test Won't Compile** - Bug #1 + - Location: `integration_test/core_gameplay_loop_test.dart` (lines 167, 278, 326, 388) + - Issue: Using parameter name `buildingId` instead of `building` + - Impact: Cannot run integration tests + - Fix: Change parameter name from `buildingId` to `building` + +2. **Resource Inventory Logic Broken** - Bug #2 + - Location: `lib/domain/entities/player_economy.dart` (lines 52-56) + - Issue: `addResource()` returns unchanged economy if resource doesn't exist (contradicts docs) + - Impact: Resources won't be added to inventory, core gameplay loop breaks + - Fix: Create new Resource if not in inventory, add to inventory + - Severity: CRITICAL - blocks core gameplay + +3. **Type Cast Syntax Error** - Bug #8 + - Location: `lib/main.dart` (line 325) + - Issue: `(metrics['cullRate'] as double * 100)` - incorrect precedence + - Fix: Add parentheses: `((metrics['cullRate'] as double) * 100)` + +**MEDIUM - Should Fix:** + +4. Camera animation TODO (incomplete feature) +5. Hardcoded values in main.dart (should be constants) +6. Firebase not optional (should have fallback) + +**Full details:** See `/docs/2-MANAGEMENT/EPIC-1-ISSUES.md` + +--- + +## Current Project Phase + +### ✅ COMPLETED +- **Phase 1-3 (Planning):** Full discovery, PRD, architecture, UX design +- **Epic 1:** All stories coded, but with bugs (see Known Issues above) + +### ⏳ IN PROGRESS +- **Documentation Reorganization:** Moving to BMAD V6 structure +- **Bug Fixes:** Critical Epic 1 bugs need to be fixed + +### ⏳ READY TO START +- **Epic 2 (Tier 1 Economy):** 26 SP, tech context complete +- **Epic 5 (Mobile-First UX):** 29 SP, tech context complete +- **Epic 8 (Ethical F2P):** 23 SP, tech context complete + +--- + +## MVP Scope & Timeline + +**Total MVP:** 170 Story Points across 8 sprints + +| Sprint | Epic(s) | SP | Status | +|--------|---------|----|----| +| Sprint 1 | EPIC-00, EPIC-01 | 47 SP | ✅ Complete (with bugs) | +| Sprint 2-3 | EPIC-02 (Tier 1 Economy) | 26 SP | ⏳ Ready | +| Sprint 4-5 | EPIC-03 (Automation) | 42 SP | 📋 Planning | +| Sprint 6-7 | EPIC-04 (Offline) | 26 SP | 📋 Planning | +| Sprint 8 | EPIC-05, EPIC-08 | 33 SP | 📋 Planning | + +**Velocity:** 25 SP/week (solo dev, adjusted for Flame learning curve) + +--- + +## How to Work on This Project + +### Before Starting Any Task + +1. **Read this file first** (CLAUDE.md) - you're reading it now ✓ +2. **Check project status** - Read `docs/2-MANAGEMENT/project-status.md` +3. **Review task details** - Open epic file in `docs/2-MANAGEMENT/epics/epic-NN.md` +4. **Check code patterns** - Review `.claude/PATTERNS.md` before writing code + +### When Implementing a Story + +1. Create a **fresh chat** (important for avoiding AI hallucinations) +2. Read the epic story details +3. Use patterns from `.claude/PATTERNS.md` +4. After coding, update `.claude/FILE-MAP.md` if new files created +5. Update epic file with status: ✅ Done +6. Update `docs/2-MANAGEMENT/project-status.md` with progress + +### When Fixing Bugs + +1. Specify **exact file:line number** of bug +2. Include **expected vs actual behavior** +3. Test after fix: `flutter test` for unit tests +4. Check: `flutter test integration_test/` for integration tests (once fixed) + +### When Adding Features + +- Follow naming conventions from `.claude/PATTERNS.md` +- Keep Clean Architecture separation (domain/ stays framework-independent) +- Add unit tests in `test/` directory +- Update FILE-MAP.md with new files/classes + +--- + +## Conventions + +### Naming + +| Element | Format | Example | +|---------|--------|---------| +| Files | snake_case | `player_economy.dart` | +| Classes | PascalCase | `PlayerEconomy`, `BuildingComponent` | +| Functions | camelCase | `getBuilding()`, `addResource()` | +| Constants | UPPER_SNAKE_CASE | `MAX_GRID_WIDTH = 50` | +| Enums | PascalCase | `ResourceType.tier1` | + +### File Organization + +- Entity files: `lib/domain/entities/{entity_name}.dart` +- UseCase files: `lib/domain/usecases/{usecase_name}_usecase.dart` +- Component files: `lib/game/components/{component_name}_component.dart` +- Test files: mirror lib structure in `test/` and `integration_test/` + +### Commit Messages + +Format: `type: description` + +``` +feat: Add CollectResources use case +fix: Fix resource inventory logic bug +docs: Update project documentation +refactor: Extract hardcoded values to constants +test: Add unit tests for PlayerEconomy +``` + +--- + +## Quick Commands + +```bash +# Setup development environment +flutter pub get +flutter pub run build_runner build + +# Run the app (hot reload enabled) +flutter run + +# Run all unit tests +flutter test + +# Run integration tests (after fixing compilation errors) +flutter test integration_test/ + +# Code analysis +flutter analyze + +# Format code +dart format lib/ + +# Build APK for Android +flutter build apk + +# Build iOS (requires macOS) +flutter build ios +``` + +--- + +## AI Instructions + +### Reading Strategy (Minimize Tokens) + +1. **Always start with CLAUDE.md** (this file) - gives you instant context +2. **Use .claude/* files** - condensed, AI-optimized information +3. **Go to detailed docs only if needed** - most work doesn't need reading all of docs/ +4. **Check FILE-MAP.md before code search** - faster than glob patterns + +### Documentation Accuracy + +- ⚠️ **KNOWN INCONSISTENCY:** The sprint-status.yaml shows Epic 1 stories as "backlog", but completion-report.md claims they're "done". This is a documentation bug - the stories ARE implemented (but with bugs). +- Check `.claude/KNOWN-ISSUES.md` before assuming something is missing + +### When Stuck + +1. Check `.claude/PATTERNS.md` - does this problem have a solved pattern? +2. Check existing code - search for similar implementations +3. Re-read the relevant epic file - maybe you missed a detail +4. Ask user directly - better than guessing + +--- + +## Multi-Model Workflow (For Project Maintainers) + +If using different Claude models: + +| Task | Recommended Model | Why | +|------|-------------------|-----| +| Planning, architecture | Opus | Deep analysis, long-context | +| Implementation (per story) | Sonnet | Fast, accurate at code | +| Quick fixes, review | Haiku | Speed + cost efficiency | +| Documentation | Sonnet | Balance of speed & quality | + +**Critical:** Use fresh chat for each story to avoid hallucinations. + +--- + +## Resources + +### Key Documents +- **Market & Vision:** `/docs/1-BASELINE/product/product-brief.md` +- **Requirements:** `/docs/1-BASELINE/product/prd-v1.0.md` +- **Architecture:** `/docs/1-BASELINE/architecture/system-architecture.md` +- **Epic Details:** `/docs/2-MANAGEMENT/epics/epic-{N}.md` + +### External References +- Flame Documentation: https://flame-engine.org/ +- Flutter Documentation: https://flutter.dev/docs +- Firebase Docs: https://firebase.google.com/docs +- Riverpod Guide: https://riverpod.dev/ + +--- + +## Last Updated + +- **Date:** 2025-12-02 +- **Status:** Documentation Reorganization in Progress +- **Next Update:** After Bug Fixes & Epic 2 Planning +- **By:** Claude (BMAD Documentation Agent) diff --git a/docs/00-START-HERE.md b/docs/00-START-HERE.md new file mode 100644 index 0000000..d1ecc69 --- /dev/null +++ b/docs/00-START-HERE.md @@ -0,0 +1,318 @@ +# Trade Factory Masters - START HERE + +Welcome! This is your guide to the FantasyFactio project. + +--- + +## 🚀 Quick Start (5 minutes) + +### For Developers + +1. **Read this:** You're reading it! ✓ +2. **Read next:** `/CLAUDE.md` (in project root) - AI-friendly overview +3. **Get latest status:** `/docs/2-MANAGEMENT/project-status.md` +4. **Setup environment:** See "Development Setup" below + +### For Project Managers / Stakeholders + +1. **Quick Facts:** `/CLAUDE.md` (Quick Facts table) +2. **Current Status:** `/docs/2-MANAGEMENT/project-status.md` +3. **What's Done/TODO:** `/docs/2-MANAGEMENT/MVP-TODO.md` +4. **Epic Details:** `/docs/2-MANAGEMENT/epics/epic-*.md` + +--- + +## 📚 Documentation Structure + +``` +Root +├── CLAUDE.md ← AI Assistant Guide +├── README.md ← Project overview +│ +├── .claude/ ← AI-optimized docs +│ ├── FILE-MAP.md ← Code file index +│ ├── TABLES.md ← Database schema +│ ├── PATTERNS.md ← Code patterns +│ └── PROMPTS.md ← Task templates +│ +└── docs/ ← Human-readable docs + ├── 00-START-HERE.md ← This file + ├── BMAD-STRUCTURE.md ← How docs organized + │ + ├── 1-BASELINE/ ← Requirements & Design + │ ├── product/ + │ │ ├── prd-v1.0.md + │ │ ├── product-brief.md + │ │ └── market-research.md + │ └── architecture/ + │ └── system-architecture.md + │ + ├── 2-MANAGEMENT/ ← Status & Tracking + │ ├── project-status.md + │ ├── MVP-TODO.md + │ ├── EPIC-1-ISSUES.md ← Bug tracker + │ └── epics/ + │ ├── epic-00-project-setup.md + │ ├── epic-01-core-gameplay.md + │ └── ...epic-02-12... + │ + ├── 4-DEVELOPMENT/ ← Developer guides + │ ├── SETUP.md ← Environment setup + │ ├── DEVELOPMENT.md ← Dev guidelines + │ └── TROUBLESHOOTING.md + │ + └── 5-ARCHIVE/ ← Old docs + └── [deprecated files] +``` + +--- + +## 🎯 Current Status at a Glance + +| Aspect | Status | Details | +|--------|--------|---------| +| **Overall** | 🔴 Epic 1 Buggy | 47/289 SP (16%), but critical bugs found | +| **Epic 1** | ❌ NOT READY | Code complete, but 3 critical bugs block testing | +| **Epic 2-12** | ⏳ PLANNED | 8 epics ready for implementation | +| **Documentation** | ✅ Reorganized | New BMAD V6 structure in place | + +**Bottom Line:** Planning complete, Epic 1 needs bug fixes before Epic 2 can start. + +--- + +## 🔧 Development Setup + +### Prerequisites + +- Flutter 3.16+ +- Dart 3.2+ +- Android SDK / Xcode (for iOS) +- Git + +### Installation + +```bash +# Clone repository +git clone +cd FantasyFactio + +# Switch to development branch +git checkout claude/project-status-display-01WgeBaEE9s5pXkKZraeZEwN + +# Install dependencies +cd trade_factory_masters +flutter pub get +flutter pub run build_runner build + +# Run the app (hot reload enabled) +flutter run +``` + +### First Time Development Check + +```bash +# Verify setup +flutter doctor + +# Run tests +flutter test + +# Check code quality +flutter analyze +``` + +See `/docs/4-DEVELOPMENT/SETUP.md` for detailed setup guide. + +--- + +## 🐛 Known Issues + +**CRITICAL - Epic 1 Bugs:** +1. Integration tests won't compile (parameter name mismatch) +2. Resource inventory logic broken (resources won't be added) +3. Type cast syntax error in main.dart + +👉 **See:** `/docs/2-MANAGEMENT/EPIC-1-ISSUES.md` for full details and fixes + +--- + +## 📖 Documentation by Role + +### 👨‍💻 Developer Working on Code + +1. Read: `CLAUDE.md` (full guide for AI) +2. Reference: `.claude/FILE-MAP.md` (find files quickly) +3. Code: Use `.claude/PATTERNS.md` (follow patterns) +4. Test: `flutter test` and verify results +5. Commit: Use `.claude/PROMPTS.md` for message format + +**Quick Links:** +- Code Structure: `.claude/FILE-MAP.md` +- How to Code: `.claude/PATTERNS.md` +- Where to Find Things: `.claude/FILE-MAP.md` + +### 🎬 Product Manager / Scrum Master + +1. Read: `/docs/2-MANAGEMENT/project-status.md` (current status) +2. Review: `/docs/2-MANAGEMENT/MVP-TODO.md` (what's left) +3. Epic Details: `/docs/2-MANAGEMENT/epics/epic-N.md` (specific epics) +4. Issues: `/docs/2-MANAGEMENT/EPIC-1-ISSUES.md` (blockers) + +**Key Metrics:** +- Total Scope: 289 Story Points (MVP) +- Completed: 47 SP (Epic 1, with bugs) +- Remaining: 242 SP +- Velocity: 25 SP/week (solo dev) +- Timeline: ~8 weeks to MVP + +### 🏗️ Architect / Tech Lead + +1. Read: `CLAUDE.md` (Quick Facts) +2. Design: `/docs/1-BASELINE/architecture/system-architecture.md` +3. Data: `.claude/TABLES.md` (schema) +4. Code: `.claude/PATTERNS.md` (standards) +5. Issues: `/docs/2-MANAGEMENT/EPIC-1-ISSUES.md` (technical debt) + +**Architecture Decisions:** +- Framework: Flutter 3.16+ +- Game Engine: Flame 1.33.0 +- State Management: Riverpod 3.0 +- Backend: Firebase +- Storage: Hive (local), Firestore (cloud) +- Pattern: Clean Architecture + DDD + +--- + +## 🚦 Next Steps (After Bug Fixes) + +### Immediate (This Week) + +1. **Fix Critical Epic 1 Bugs** (1-2 hours) + - See `/docs/2-MANAGEMENT/EPIC-1-ISSUES.md` for fixes + - Run all tests to verify + +2. **Plan Epic 2 Implementation** (2-3 hours) + - Read: `/docs/2-MANAGEMENT/epics/epic-02-tier-1-economy.md` + - Technical context already exists + +### Soon (Next 1-2 Weeks) + +1. **Implement Epic 2 Stories** (26 SP, ~2 weeks) + - Start with Building Definitions (STORY-02.1) + - Follow Sprint 2 planning + +2. **Parallel: Epic Context Documentation** (Ongoing) + - Complete tech contexts for Epic 3-6 + - Prepare Sprint 3 planning + +--- + +## 📞 Getting Help + +### Common Questions + +**Q: How do I run the app?** +A: `flutter run` in the `trade_factory_masters/` directory + +**Q: How do I run tests?** +A: `flutter test` (unit) or `flutter test integration_test/` (integration) + +**Q: Where are the bugs documented?** +A: `/docs/2-MANAGEMENT/EPIC-1-ISSUES.md` + +**Q: What should I work on next?** +A: Check `/docs/2-MANAGEMENT/project-status.md` for priorities + +**Q: How do I follow code patterns?** +A: See `.claude/PATTERNS.md` for examples + +### Troubleshooting + +- **Builds failing?** → `/docs/4-DEVELOPMENT/TROUBLESHOOTING.md` +- **Tests not running?** → Check Flutter/Dart versions, run `flutter doctor` +- **Firebase issues?** → Check `lib/main.dart` initialization + +--- + +## 📊 Project Metrics + +| Metric | Value | Notes | +|--------|-------|-------| +| **Total Stories** | 68 | Across 12 epics | +| **Total Story Points** | 289 SP | MVP scope | +| **Completed** | 47 SP (16%) | Epic 1 (with bugs) | +| **Estimated Velocity** | 25 SP/week | Solo developer | +| **MVP Timeline** | 8 weeks | Should complete by ~mid-2026 | +| **Test Coverage** | ~70-80 tests | Unit tests mostly complete | + +--- + +## 🎓 Learning Resources + +### Project-Specific +- Architecture: `/docs/1-BASELINE/architecture/system-architecture.md` +- Business Logic: `/docs/1-BASELINE/product/prd-v1.0.md` +- Game Design: `/docs/1-BASELINE/product/product-brief.md` + +### External +- Flutter: https://flutter.dev/docs +- Flame: https://flame-engine.org/ +- Firebase: https://firebase.google.com/docs +- Riverpod: https://riverpod.dev/ + +--- + +## 📝 How to Update Documentation + +1. Identify the right file (see structure above) +2. Use patterns from existing docs +3. Add AI-INDEX comment at top of .md files +4. Update "Last Updated" date +5. Reference related docs where relevant + +See `BMAD-STRUCTURE.md` for detailed guidelines. + +--- + +## 🔗 Key Links + +| What | Where | Purpose | +|------|-------|---------| +| **AI Guide** | `/CLAUDE.md` | Everything an AI needs to know | +| **File Index** | `.claude/FILE-MAP.md` | Find any code file | +| **Code Patterns** | `.claude/PATTERNS.md` | How to write code | +| **Current Status** | `docs/2-MANAGEMENT/project-status.md` | What's done/in progress | +| **Bugs** | `docs/2-MANAGEMENT/EPIC-1-ISSUES.md` | Known issues & fixes | +| **Epic Details** | `docs/2-MANAGEMENT/epics/` | Specific work items | + +--- + +## 👤 Project Ownership + +- **Lead Developer:** Mariusz (CoderMariusz) +- **AI Assistant:** Claude (BMAD Documentation Agent) +- **Git Branch:** `claude/project-status-display-01WgeBaEE9s5pXkKZraeZEwN` + +--- + +## 📅 Timeline + +| Date | Milestone | +|------|-----------| +| 2025-11-23 | ✅ Epic 1 Completion (with bugs) | +| 2025-12-02 | 🔄 Documentation Reorganization | +| TBD | ⏳ Epic 1 Bug Fixes | +| TBD | ⏳ Epic 2 Implementation (Tier 1 Economy) | +| TBD | ⏳ MVP Release | + +--- + +## Questions? + +- Check the relevant section above +- Search for your question in the FAQ +- Review the epic files for specific features +- Check TROUBLESHOOTING.md for common issues + +**Last Updated:** 2025-12-02 +**Next Review:** After Epic 1 bug fixes diff --git a/docs/2-MANAGEMENT/EPIC-1-ISSUES.md b/docs/2-MANAGEMENT/EPIC-1-ISSUES.md new file mode 100644 index 0000000..f3d58a7 --- /dev/null +++ b/docs/2-MANAGEMENT/EPIC-1-ISSUES.md @@ -0,0 +1,530 @@ +# Epic 1 - Issues & Bug Report + + + +**Project:** Trade Factory Masters +**Date:** 2025-12-02 +**Status:** 🔴 CRITICAL - Blocking Epic Completion +**Reviewer:** Claude (Deep Dive Analysis) + +--- + +## Executive Summary + +Despite completion report claiming "100% done, all tests passing", deep code analysis found **3 critical bugs** and **6 medium issues** that prevent core gameplay from working. + +**Status:** ❌ **NOT PRODUCTION READY** - requires fixes before proceeding to Epic 2 + +| Severity | Count | Impact | +|----------|-------|--------| +| 🔴 CRITICAL | 3 | Gameplay breaks, tests fail | +| 🟠 MEDIUM | 6 | Code quality, missing features | +| 🟡 LOW | 3 | Maintainability | + +--- + +## Critical Issues (Must Fix) + +### Bug #1: Integration Test Won't Compile + +**File:** `integration_test/core_gameplay_loop_test.dart` +**Lines:** 167, 278, 326, 388 +**Severity:** 🔴 CRITICAL + +**Issue:** +Integration tests use wrong parameter name: + +```dart +// ❌ WRONG (current code): +buildingId: testBuilding.id, + +// ✅ CORRECT (expected): +building: testBuilding, +``` + +**Why It's Broken:** +- Method signature in `UpgradeBuilding.execute()` expects `building: Building` parameter +- Test passes `buildingId: String` parameter +- Parameter mismatch causes compilation error +- Integration test cannot run at all + +**Current Error:** +``` +The named parameter 'buildingId' isn't defined. +``` + +**Impact:** +- Cannot verify if gameplay actually works +- Integration test suite incomplete +- Claim "integration tests pass" is FALSE + +**Fix Instructions:** + +1. Open `integration_test/core_gameplay_loop_test.dart` +2. Find all instances of `buildingId:` (should find 4) +3. For each instance, replace: + ```dart + buildingId: testBuilding.id, // Line 167 + buildingId: expensiveBuilding.id, // Line 278 + buildingId: maxLevelBuilding.id, // Line 326 + buildingId: currentEconomy.buildings.first.id, // Line 388 + ``` + + With: + ```dart + building: testBuilding, + building: expensiveBuilding, + building: maxLevelBuilding, + building: currentEconomy.buildings.first, + ``` + +4. Verify: `flutter test integration_test/core_gameplay_loop_test.dart` + +**Effort:** 5 minutes +**Risk:** Very Low (parameter name only) + +--- + +### Bug #2: Resource Inventory Logic Broken + +**File:** `lib/domain/entities/player_economy.dart` +**Lines:** 52-56 +**Severity:** 🔴 CRITICAL + +**Issue:** +The `addResource()` method contradicts its documentation: + +```dart +/// If resource doesn't exist in inventory, creates it ← DOCS SAY THIS +PlayerEconomy addResource(String resourceId, int amountToAdd) { + if (!inventory.containsKey(resourceId)) { + return this; // ❌ BUG: Returns unchanged instead of creating! + } + // ... rest of method +} +``` + +**Why It's Broken:** +1. Documentation says: "Creates resource if doesn't exist" +2. Code actually does: Returns unchanged economy +3. When `CollectResourcesUseCase` tries to add resources to empty inventory: + - Inventory is initially `{}` + - `addResource('wood', 50)` called + - Check: `inventory.containsKey('wood')` → false + - Returns unchanged economy → **resources are LOST** +4. Player collects nothing, gameplay breaks + +**Real-World Impact:** +- Core gameplay loop: COLLECT → UPGRADE +- Collection phase fails silently +- Resources never appear in inventory +- Upgrade phase can't happen (no resources) +- **Game is unplayable** + +**Expected Behavior:** + +```dart +PlayerEconomy addResource(String resourceId, int amountToAdd) { + if (!inventory.containsKey(resourceId)) { + // CREATE new resource if doesn't exist + final newResource = Resource( + id: resourceId, + displayName: resourceId, // Should come from config + type: ResourceType.tier1, + amount: amountToAdd, + maxCapacity: 1000, + iconPath: 'assets/images/resources/$resourceId.png', + ); + final updatedInventory = Map.from(inventory); + updatedInventory[resourceId] = newResource; + return copyWith(inventory: updatedInventory); + } + + // Otherwise, add to existing + final existing = inventory[resourceId]!; + final newAmount = min( + existing.amount + amountToAdd, + existing.maxCapacity, + ); + final updated = existing.copyWith(amount: newAmount); + final updatedInventory = Map.from(inventory); + updatedInventory[resourceId] = updated; + return copyWith(inventory: updatedInventory); +} +``` + +**Fix Instructions:** + +1. Open `lib/domain/entities/player_economy.dart` +2. Locate `addResource()` method (lines 52-56) +3. Replace the logic with code above +4. Add tests: + ```dart + test('addResource creates new resource if not in inventory', () { + final empty = PlayerEconomy(inventory: {}); + final result = empty.addResource('wood', 50); + + expect(result.inventory.containsKey('wood'), true); + expect(result.inventory['wood']!.amount, 50); + }); + + test('addResource updates existing resource', () { + final initial = PlayerEconomy(inventory: { + 'wood': Resource(amount: 30, ...) + }); + final result = initial.addResource('wood', 20); + + expect(result.inventory['wood']!.amount, 50); + }); + ``` + +5. Run: `flutter test test/domain/entities/player_economy_test.dart` + +**Effort:** 30 minutes (logic + tests) +**Risk:** Medium (core domain logic - need thorough testing) + +--- + +### Bug #3: Type Cast Syntax Error + +**File:** `lib/main.dart` +**Line:** 325 +**Severity:** 🔴 CRITICAL + +**Issue:** +Incorrect operator precedence in cast expression: + +```dart +// ❌ WRONG: +final cullRate = (metrics['cullRate'] as double * 100).toStringAsFixed(1); + +// ✅ CORRECT: +final cullRate = ((metrics['cullRate'] as double) * 100).toStringAsFixed(1); +``` + +**Why It's Wrong:** +- Syntax: `(expr as Type op operand)` is invalid +- Should be: `((expr as Type) op operand)` +- Missing parentheses causes type error or runtime crash + +**Potential Error:** +``` +The '-' operator cannot be applied to type cast. +``` + +**Fix Instructions:** + +1. Open `lib/main.dart` at line 325 +2. Find: + ```dart + (metrics['cullRate'] as double * 100) + ``` +3. Replace with: + ```dart + ((metrics['cullRate'] as double) * 100) + ``` + +4. Run: `flutter analyze` to verify + +**Effort:** 2 minutes +**Risk:** Very Low (syntax fix) + +--- + +## Medium Issues (Should Fix) + +### Issue #4: Incomplete Camera Animation + +**File:** `lib/game/camera/grid_camera.dart` +**Line:** 302 +**Severity:** 🟠 MEDIUM + +**Status:** ⚠️ Partially works (snaps instead of animates) + +**Issue:** +```dart +void moveTo(Vector2 position, {bool animate = false}) { + if (animate) { + // TODO: Implement smooth camera movement animation + // For now, just snap to position +``` + +**Current Behavior:** +- Camera movement works but snaps instantly +- API exposes `animate` parameter but doesn't use it +- Documented in architecture but not implemented + +**Impact:** Low - gameplay works, just less polished + +**Fix:** +1. Implement smooth tweening animation +2. Use Flame's animation system or Tween +3. Estimated effort: 20 minutes +4. Can defer to Epic 3 (UI Polish) + +--- + +### Issue #5: Hardcoded Configuration Values + +**File:** `lib/main.dart` +**Lines:** 68-88 + +**Issue:** +Grid and camera configuration hardcoded in main.dart: + +```dart +// ❌ HARDCODED: +const GridConfig( + gridWidth: 50, + gridHeight: 50, + tileWidth: 64.0, + tileHeight: 32.0, + showGridLines: true, +); + +const GridCameraConfig( + minZoom: 0.3, + maxZoom: 2.0, + zoomTransitionDuration: 0.3, + panSpeed: 1.0, +); +``` + +**Impact:** Medium - Technical debt +- Hard to adjust game balance +- No single source of truth for config +- Difficult to test different configs + +**Fix:** +1. Create `lib/config/game_config.dart` +2. Define constants there +3. Import and use in main.dart +4. Estimated effort: 15 minutes + +--- + +### Issue #6: Firebase Not Optional + +**File:** `lib/main.dart` +**Lines:** 34-45 + +**Issue:** +```dart +// No try-catch around Firebase init +await Firebase.initializeApp( + options: DefaultFirebaseOptions.currentPlatform, +); +``` + +**Problem:** +- App crashes if Firebase isn't configured +- Can't test without Firebase setup +- No offline-first fallback + +**Impact:** Medium - Development friction +- Local testing harder +- CI/CD pipeline may fail without secrets + +**Fix:** +1. Wrap Firebase init in try-catch +2. Fallback to local-only mode if fails +3. Estimated effort: 20 minutes + +--- + +### Issue #7: Documentation Inconsistency + +**File:** `docs/sprint-artifacts/sprint-status.yaml` + +**Issue:** +Sprint status shows all Epic 1 stories as `backlog`, but completion report claims `done`: + +```yaml +# In sprint-status.yaml: +epic-01: backlog +01-1-building-entity: backlog +01-2-resource-entity: backlog +... +``` + +But completion report says: "All 12 stories completed, 100% done" + +**Impact:** Low - Confusion only +- New developers may re-implement done work +- Status tracking is inaccurate + +**Fix:** +1. Update `sprint-status.yaml` to show stories as `done` (once bugs are fixed) +2. Add note explaining the bugs found + +--- + +### Issue #8: Unsafe Type Casts + +**File:** `lib/game/components/building_component.dart` (if present) + +**Issue:** +Magic numbers without named constants: + +```dart +// ❌ Magic numbers: +final pulseAlpha = (0.5 + 0.5 * (now % 2.0 / 2.0)); +canvas.drawCircle( + Offset(size.x / 2 - 5, -size.y / 2 + 5), // Hardcoded offsets + 4, // Hardcoded radius + ... +); +``` + +**Impact:** Low - Readability + +**Fix:** +1. Extract constants: + ```dart + static const double PULSE_MIN_ALPHA = 0.5; + static const double PULSE_AMPLITUDE = 0.5; + static const double INDICATOR_OFFSET = 5.0; + static const double INDICATOR_RADIUS = 4.0; + ``` +2. Use in code +3. Estimated effort: 10 minutes + +--- + +## Testing Status + +### Current Test Coverage + +| Test Suite | Status | Notes | +|-----------|--------|-------| +| Unit Tests | ✅ ~70-80 tests | Most pass, depends on Bug #2 fix | +| Integration Tests | ❌ Won't Compile | Bug #1 blocks all integration tests | +| Widget Tests | ⏳ Minimal | Basic placeholder test only | + +### Test Verification Strategy + +**After fixing critical bugs:** + +```bash +# 1. Fix Bug #1 - Integration test compilation +flutter test integration_test/core_gameplay_loop_test.dart + +# 2. Fix Bug #2 - Resource logic +flutter test test/domain/entities/player_economy_test.dart + +# 3. Fix Bug #3 - Type cast +flutter analyze + +# 4. Run all tests +flutter test +``` + +--- + +## Fix Priority & Timeline + +### Immediate (Must Do Before Epic 2) + +| Bug | Effort | Risk | Impact | Priority | +|-----|--------|------|--------|----------| +| #1 - Integration test | 5 min | Very Low | CRITICAL | P0 | +| #2 - Resource logic | 30 min | Medium | CRITICAL | P0 | +| #3 - Type cast | 2 min | Very Low | CRITICAL | P0 | + +**Total Effort:** ~37 minutes +**Estimated Time:** 1 hour (with testing) + +### Should-Do (Before Release) + +| Issue | Effort | Risk | Impact | Priority | +|-------|--------|------|--------|----------| +| #4 - Camera animation | 20 min | Low | Low | P2 | +| #5 - Hardcoded config | 15 min | Low | Medium | P1 | +| #6 - Firebase optional | 20 min | Medium | Medium | P1 | +| #7 - Doc consistency | 10 min | Very Low | Low | P3 | +| #8 - Magic numbers | 10 min | Very Low | Low | P3 | + +**Total Effort:** ~75 minutes +**Can defer to Epic 2 sprint if needed** + +--- + +## Recommended Action Plan + +### Phase 1: Critical Bug Fixes (1 hour) + +1. ✅ Fix Bug #1 (5 min) +2. ✅ Fix Bug #2 (30 min) +3. ✅ Fix Bug #3 (2 min) +4. ✅ Run all tests (15 min) +5. ✅ Commit: `fix: critical Epic 1 bug fixes` + +### Phase 2: Medium Issues (1.5 hours) + +After Phase 1 tests pass: + +1. ✅ Fix Issue #5 (hardcoded config) - 15 min +2. ✅ Fix Issue #6 (Firebase optional) - 20 min +3. ✅ Fix Issue #7 (doc consistency) - 10 min +4. ✅ Add Issue #4, #8 to backlog for Epic 3 +5. ✅ Run full test suite +6. ✅ Commit: `refactor: improve code quality` + +### Phase 3: Documentation Update + +1. Update CLAUDE.md (remove from Known Issues once fixed) +2. Update FILE-MAP.md status +3. Update project-status.md +4. Update sprint-status.yaml + +--- + +## How to Track Fixes + +After each fix: + +1. Update this file: change ✅ marker when done +2. Update `.claude/FILE-MAP.md` status column +3. Test: run `flutter test` +4. Commit with clear message +5. Update `docs/2-MANAGEMENT/project-status.md` + +--- + +## Verification Checklist + +Before moving to Epic 2: + +- [ ] Bug #1 fixed and integration test compiles +- [ ] Bug #2 fixed and resource collection works +- [ ] Bug #3 fixed and code analyzes clean +- [ ] All unit tests pass (flutter test) +- [ ] All integration tests pass +- [ ] No warnings from flutter analyze +- [ ] Documentation updated +- [ ] Commits pushed to branch + +--- + +## Related Documents + +- 📄 Deep dive analysis: See CLAUDE.md "Known Issues" section +- 📄 Code patterns: `.claude/PATTERNS.md` +- 📄 File locations: `.claude/FILE-MAP.md` +- 📄 Epic 1 completion report: `docs/sprint-artifacts/epic-1-completion-report.md` + +--- + +## Status Updates + +| Date | Status | Notes | +|------|--------|-------| +| 2025-12-02 | 🔴 CREATED | Deep dive analysis complete, bugs documented | +| TBD | ⏳ IN PROGRESS | Fixes being implemented | +| TBD | ✅ RESOLVED | All critical bugs fixed, tests passing | + +--- + +**Document Owner:** Claude (Code Quality Agent) +**Last Updated:** 2025-12-02 +**Next Review:** After bug fixes complete diff --git a/docs/2-MANAGEMENT/EPIC-2-DEEP-DIVE.md b/docs/2-MANAGEMENT/EPIC-2-DEEP-DIVE.md new file mode 100644 index 0000000..da33cf7 --- /dev/null +++ b/docs/2-MANAGEMENT/EPIC-2-DEEP-DIVE.md @@ -0,0 +1,613 @@ +# Epic 2 Deep Dive Analysis - Błędy, Niezgodności, Pytania + + + +**Date:** 2025-12-02 +**Analyzer:** Claude (Code Quality Agent) +**Scope:** Complete Epic 2 documentation review +**Status:** 🔴 CRITICAL ISSUES FOUND - See below + +--- + +## Executive Summary + +Przeanalizowałem 3 dokumenty Epic 2: +1. `tech-spec-epic-02.md` (840 lines) +2. `sprint-planning-epic-2.md` (730 lines) +3. `epics-stories-trade-factory-masters-2025-11-17.md` (200 lines) + +**Znalazłem:** +- 🔴 **3 CRITICAL błędy ekonomiczne** (mogą całkowicie złamać balans gry) +- 🟠 **7 MEDIUM niezgodności** między dokumentami +- 🟡 **9 LOW pytań wymagających wyjaśnienia** + +--- + +## 🔴 CRITICAL ISSUES (Muszą być naprawione) + +### Critical Issue #1: SPRZECZNA Specyfikacja Zasobów + +**Problem:** Liczba zasobów jest różna w każdym dokumencie! + +**tech-spec-epic-02.md:** +``` +Line 33-37: "7 typów zasobów, 5 w Tier 1" +- Podstawowe: Wood, Ore, Food (3) +- Średniozaawansowane: Bars (1) +- Zaawansowane: Tools (1) +- Tier 2: Circuits, Machines (2 - ale "nie implementowane w tym epiku") +TOTAL = 7? Ale czemu Food jest jeśli: +``` + +**sprint-planning-epic-2.md:** +``` +Line 18: "7 zasobów (Wood, Ore, Bars, Tools, Stone, Clay, Bricks)" +CAŁKOWICIE INNE zasoby!!! + +List zasobów z lines 18: +1. Wood +2. Ore +3. Bars +4. Tools +5. Stone ← NIE MA W TECH SPEC! +6. Clay ← NIE MA W TECH SPEC! +7. Bricks ← NIE MA W TECH SPEC! + +A Food, Circuits, Machines??? Zniknęły! +``` + +**Resource Definitions w tech-spec (lines 209-227):** +```dart +class ResourceDefinitions { + static final Map tier1 = { + 'wood': ..., + 'ore': ..., + // ... 'Food, Bars, Tools' mentioned but NOT in example + }; +} +``` + +**❓ PYTANIA:** + +1. **Które zasoby są rzeczywiście w Tier 1?** + - Tech spec mówi: Wood, Ore, Food, Bars, Tools (5 zasobów) + - Sprint planning mówi: Wood, Ore, Bars, Tools, Stone, Clay, Bricks (7 zasobów) + - **Która specyfikacja jest prawidłowa?** + +2. **Co z Food?** + - Tech spec wymienia Food jako "Podstawowe" (produkuje Farm) + - Sprint planning zupełnie nie wspomina Food + - Czy Food powinno być w grze czy nie? + +3. **Stone, Clay, Bricks?** + - Pojawia się w sprint planning ale **nigdzie nie ma ich definicji w tech spec** + - Które budynki je produkują? + - Jakie mają ceny? + - Do czego służą? + +**Impact:** 🔴 CRITICAL +- Jeśli zasoby się zmienią, wszystkie ceny ekonomiczne będą błędne +- Jeśli brakuje zasobów w tech spec, ci devloprzy będą mieć niekompletne specyfikacje +- Unit testy będą testować złe zasoby + +**Fix Required:** Uzgodnij listę zasobów raz na zawsze i uaktualnij oba dokumenty. + +--- + +### Critical Issue #2: Sprzeczne Ceny Zasobów + +**Scenariusz 1: Tech Spec (lines 216-225)** + +```dart +'wood': baseMarketPrice: 5, +'ore': baseMarketPrice: 7, +'food': baseMarketPrice: 4, +'bars': baseMarketPrice: 15, +'tools': baseMarketPrice: 40, +``` + +**Buy Price = basePrice × 1.2:** +- Wood: 5 × 1.2 = **6 gold** +- Ore: 7 × 1.2 = **8.4g** (czy rounding do 8 czy 9?) +- Bars: 15 × 1.2 = **18g** +- Tools: 40 × 1.2 = **48g** + +**Sell Price = basePrice × 0.8:** +- Wood: 5 × 0.8 = **4 gold** +- Ore: 7 × 0.8 = **5.6g** (czy rounding do 5 czy 6?) +- Bars: 15 × 0.8 = **12g** +- Tools: 40 × 0.8 = **32g** + +**Scenariusz 2: Sprint Planning (lines 133)** + +``` +Wood 5g, Ore 7g, Bars 15g, Tools 30g, Stone 3g, Clay 4g, Bricks 12g +``` + +**SPRZECZNOŚĆ:** Tools to 40g w tech spec ale 30g w sprint planning! + +**MarketTransaction Use Case (tech-spec, lines 284):** +```dart +final buyPrice = (resource.baseMarketPrice * 1.2).toInt(); +``` + +**❓ PYTANIE: Jak zaokrąglać ułamkowe ceny?** + +Przykład: Ore 7 × 1.2 = 8.4g +- `.toInt()` zwróci 8g +- Ale co jeśli chcemy 8g czy 9g? + +**Ryzyko:** 🔴 CRITICAL +- Jeśli Tools = 30g vs 40g, cała ekonomia zmienia się +- Zaokrąglanie może spowodować arbitrage loops: + - Jeśli Buy price = 8g, Sell price = 6g + - A jakiś crafting daje profit = mogą być pętle arbitrażu + +--- + +### Critical Issue #3: Sprzeczna Produkcja Zasobów + +**Tech Spec mówi (lines 26-31, lines 196-200):** + +``` +Lumbermill - produkuje Wood (1 Wood/min) +Mine - produkuje Ore (1 Ore/min) +Farm - produkuje Food (1 Food/min) +Smelter - przetwarza Wood + Ore → Bars (0.5 Bars/min) +Workshop - przetwarza 2 Bars + 1 Ore → Tools (0.33 Tools/min) +``` + +**Sprint Planning mówi (line 95):** + +``` +Produkcja zbalansowana (1 Wood/min = 1 Ore/min = 0.5 Bars/min) +``` + +**Ale nigdzie nie ma specyfikacji jak pracują Smelter + Workshop!** + +**❓ PYTANIA:** + +1. **Smelter production rate - co to znaczy?** + - "0.5 Bars/min" - to jaki jest input rate? + - Czy to znaczy: "Potrzebuję 2 Wood + 2 Ore żeby dostać 1 Bars w ciągu 2 minut?" + - Czy "Potrzebuję 1 Wood + 1 Ore żeby dostać 0.5 Bars per minute?" + +2. **Workshop - 2 Bars + 1 Ore → 0.33 Tools/min** + - Ile czasu trwa przetworzenie? + - Czy to "per minute" czy "całkowity rate"? + - Czy potrzebuję 2 Bar + 1 Ore per craftingu? + +3. **Jak gracz transportuje zasoby między budynkami?** + - Tech spec mówi "Manualne przenoszenie zasobów jest wymagane w Tier 1" (line 633) + - Ale nigdzie nie ma specyfikacji MECHANIKI transportu! + - Czy to "drag & drop", "tap & select", "conveyor system"? + - **Conveyory są w EPIC-03, nie EPIC-02 - więc jak to działa bez nich???** + +--- + +## 🟠 MEDIUM Issues (Poważne niezgodności) + +### Medium Issue #4: Storage Capacity vs Production + +**Tech Spec (lines 199, 261):** +```dart +storageCapacity: 10, // Dla Lumbermill +``` + +**Ale:** +- Lumbermill produkuje 1 Wood/min +- W ciągu 10 minut zupełnie się zapełni +- Potem gracz będzie zmuszony sprzedawać co 10 minut +- **Czy to jest UX design czy bug?** + +**❓ PYTANIE:** Czy storage capacity (10) jest celowe, czy powinno być większe (np. 100)? + +--- + +### Medium Issue #5: Building Definitions brakuje kluczowych informacji + +**Tech Spec (lines 189-204):** +```dart +static final Map tier1 = { + BuildingType.lumbermill: BuildingDefinition( + type: BuildingType.lumbermill, + displayName: 'Lumbermill', + description: 'Produkuje Wood z lasów', + costs: BuildingCosts(construction: 100, upgradeTier1: [120, 140, 160, 180]), + // ... production config + ), +}; +``` + +**Ale brakuje:** +1. **Grid size** - czy Lumbermill to 2×2 czy 3×3 tiles? + - Tech spec mówi (line 602): "64×64px dla 2×2 buildings, 96×96px dla 3×3 buildings" + - Ale które budynki jakie rozmiary mają? + +2. **Upgrade formula validation** + - Costs: [120, 140, 160, 180] - to liniowe? + - Tech spec mówi (line 48): "Koszty liniowe: cost × level" + - Ale [120, 140, 160, 180] to NIE jest liniowe! + - To powinno być: [120, 240, 360, 480] jeśli базис = 120 + +3. **Production formula mismatch** + - Tech spec (line 126-127): + ```dart + double get productionRate => + production.baseRate * (1 + (level - 1) * 0.2); + ``` + - Level 1: 1.0x, Level 2: 1.2x, Level 3: 1.4x ✅ + - **ALE Building definitions w lines 195 nie pokazują jakiś będą production config!** + +--- + +### Medium Issue #6: NPC Market - brakuje ključnych features + +**Tech Spec (lines 39-43):** +``` +- ✅ Stałe ceny (Buy Price = basePrice × 1.2, Sell Price = basePrice × 0.8) +- ✅ Interfejs z zakładkami BUY/SELL +- ✅ Slider do wyboru ilości (1-100) +- ✅ Transakcje z walidacją +``` + +**Sprint Planning (lines 157-182):** +``` +- [BUY] [SELL] tabs +- Resource list with prices +- Slider for quantity +``` + +**ALE:** + +1. **Brakuje UI elementów:** + - Jak wygląda "Close" button? + - Czy to bottom sheet czy fullscreen? + - Jak animuje się? (Slide up, fade in, etc.) + - **Tech spec nie specyfikuje!** + +2. **Brakuje edge cases:** + - Co jeśli gracz nie ma żadnych zasobów do sprzedania? + - Co jeśli gracz nie ma żadnego złota do kupienia? + - Czy buttony są disabled czy hidden? + - **Nie ma specyfikacji!** + +3. **Brakuje feedback:** + - Czy jest toast notification po transakcji? + - Czy jest haptic feedback? (Tech spec mówi yes, linia 164) + - Czy jest floating text animation? + - **Sprint planning nie specyfikuje!** + +--- + +### Medium Issue #7: Economic Balance Test - Nierealistyczne założenia + +**Tech Spec (lines 649-652):** +``` +AC-5: Economic Balance +- [ ] Gracz może zarobić 1000 gold w 30 minut gameplay +- [ ] Kupowanie wszystkich inputów → strata +- [ ] Produkcja własnych inputów → zysk +- [ ] Nie ma arbitrage loops +``` + +**Sprint Planning (lines 330-351):** +```dart +test('Player earns 1000g in 30 minutes (Tier 1)', () { + // Minute 0: Build Lumbermill (100g) → 400g left + // Minute 5: Collect 5 Wood, sell for 20g → 420g + // ... simulate 30 minutes + expect(economy.gold, greaterThanOrEqualTo(1000)); +}); +``` + +**❓ PYTANIE: Czy to jest realistyczne?** + +**Scenario:** +- Starting gold: 500g +- Build Lumbermill: -100g (gold = 400) +- Lumbermill produces 1 Wood/min × 5 min = 5 Wood +- Sell 5 Wood @ 4g each = +20g (gold = 420) + +**Do osiągnąć 1000g potrzebujesz +580g.** + +- Jeśli sprzedajesz 5 Wood co 5 minut = +20g co 5 minut +- Potrzebujesz 580 ÷ 20 = 29 × 5 minut = **145 minut (2.4 godziny!)** + +**Ale test mówi "30 minut"! To niemożliwe!** + +**Czy to powinno być:** +- 1000g w 2+ godziny? (realistyczne) +- Czy zasoby powinny być droższe? (np. Wood = 10g nie 4g) +- Czy gracz powinien zarabiać szybciej? + +--- + +### Medium Issue #8: Building Placement Logic - incomplete + +**Tech Spec (lines 277-302):** +```dart +class BuildingPlacementSystem { + bool isValidPlacement(...) { + // Check grid bounds + // Check occupied tiles + return !existingBuildings.any((b) => b.gridPosition == gridPosition); + } +} +``` + +**ALE:** + +1. **Brakuje:** + - Czy można budować na krawędzi gridu (x=49)? + - Czy można budować w pozycji (0,0)? + - Czy jest safe zone blisko startu? + +2. **Grid size inconsistency:** + - Tech spec mówi (line 50): "50×50 tiles" + - Ale czy to 50×50 valid placements czy 50×50 tiles gdzie każdy zajmuje 2×2 lub 3×3? + - **Nie ma jasności!** + +3. **10 Building Limit:** + - Tech spec mówi (line 715): "Limit 10 budynków w Tier 1" + - Sprint planning mówi (line 272): "10 building limit (Tier 1) enforced" + - **ALE: Z 50×50 gridem i 10 budynkami można mieć maksimum ~20-30% occupancy!** + - Czy to jest celowe? Czy powinno być więcej budynków? + +--- + +## 🟡 LOW Priority Questions + +### Question #9: Farm - co to robi? + +- Tech spec wymienia Farm produkuje Food (line 29) +- Sprint planning nie wspomina Food +- **Pytanie: Czy Food jest używany gdziekolwiek?** + - Czy to jest tylko na sprzedaż? + - Czy pracownicy je jedzą (ale workers są w Tier 2)? + - Czy powinno być usunięte z Tier 1? + +--- + +### Question #10: Market Building - co to robi? + +- Tech spec wymienia "Market" jako building (line 92) +- **ALE nigdzie nie ma specyfikacji co robi!** + - Czy to jest where NPC Market appears? + - Czy gracz musi go zbudować żeby mieć dostęp do Market? + - Czy to coś innego? + +--- + +### Question #11: Upgrade costs formula error + +**Tech Spec mówi (line 48):** +``` +Koszty liniowe: cost × level +``` + +**Ale Building Definitions pokazuje (line 195):** +``` +costs: BuildingCosts(construction: 100, upgradeTier1: [120, 140, 160, 180]) +``` + +**To jest [120, 140, 160, 180] - czy to jest:** +- Liniowe: 120, 240, 360, 480? (NO - to co jest w array) +- Lub: 120+20, 140+20, 160+20, 180+20? (to co jest w array) + +**❓ Która formuła jest prawidłowa?** + +```dart +// Opcja A: costs[level] = costs[level-1] + 20 +cost = baseCost + (level * incremental) // Liniowe +// For level 1-5: 120, 140, 160, 180, 200 + +// Opcja B: costs[level] = costs[level] from array +// For level 1-5: 120, 140, 160, 180, ??? (brakuje 5 levelu!) + +// Opcja C: costs[level] = baseCost × level +// For level 1-5: 120, 240, 360, 480, 600 +``` + +--- + +### Question #12: MarketTransaction rounding errors + +**Tech Spec (lines 284, 304):** +```dart +final buyPrice = (resource.baseMarketPrice * 1.2).toInt(); +final sellPrice = (resource.baseMarketPrice * 0.8).toInt(); +``` + +**Problem: `.toInt()` truncates, not rounds!** + +Example: Ore (7g) +- buyPrice = (7 × 1.2).toInt() = 8.4.toInt() = **8g** (lost 0.4g) +- sellPrice = (7 × 0.8).toInt() = 5.6.toInt() = **5g** (lost 0.6g) + +**Cumulative error over many transactions:** +- Sell 100 Ore @ 5.6g each = 560g +- But code gives 5g × 100 = 500g +- **Lost 60g!** + +**❓ Pytanie: Czy to jest celowe czy bug?** +- Może should be `.round()` zamiast `.toInt()`? +- Lub keep prices w integers (Wood=5, Ore=8, itd.)? + +--- + +### Question #13: CollectResourcesUseCase - nie uwzględnia inputów + +**Tech Spec mówi (line 243-272):** +```dart +class CollectResourcesUseCase { + Result execute(...) { + // Calculate produced + final produced = (building.productionRate * minutesElapsed).toInt(); + } +} +``` + +**ALE co z budynkami wymagającymi inputów?** +- Smelter wymaga Wood + Ore +- Workshop wymaga Bars + Ore +- **Ale CollectResourcesUseCase nie sprawdza czy są inputy!** + +**❓ Pytanie: Czy to będzie implementowane w Story-02.4?** +- Czy gracz manualnie musi transportować zasoby do Smelter? +- Czy Smelter automatycznie bierze z inventory? +- Czy użytkownik musi mieć zasoby na hand a potem "craft" button? + +--- + +### Question #14: Production rate formula for upgraded buildings + +**Tech Spec mówi (line 126-127):** +```dart +double get productionRate => + production.baseRate * (1 + (level - 1) * 0.2); +``` + +**Ale nigdzie nie specyfikuje jak collectResourcesUseCase aktualizuje building.lastCollected po upgrade!** + +**Scenariusz:** +1. Level 1 Lumbermill: baseRate = 1.0/min +2. Upgreide to Level 2: baseRate = 1.2/min +3. Collect now? + +**❓ Pytanie:** +- Czy upgrade resetuje timer? (tak - sensowne) +- Czy upgrade zwraca zasoby które zostały w starym rate? (fair mechanic?) +- Czy nowy rate obowiązuje do natychmiast? + +--- + +### Question #15: Grid position representation + +**Tech Spec (lines 119, 165):** +```dart +final Point gridPosition; // (x, y) na gridzie 50×50 +``` + +**Sprint Planning (lines 275-279):** +```dart +if (gridPosition.x < 0 || gridPosition.x >= 50) return false; +if (gridPosition.y < 0 || gridPosition.y >= 50) return false; +``` + +**❓ Pytania:** +- Czy gridy są 0-indexed (0-49) czy 1-indexed (1-50)? +- Tech spec mówi "50×50 grid" - czy to 2500 tiles czy 2500 cells? +- Czy Point to best reprezentacja czy powinno być custom GridPosition? + +--- + +## 📊 Podsumowanie Issues + +| # | Title | Severity | Category | Fix Time | Depends On | +|---|-------|----------|----------|----------|-----------| +| 1 | Resource mismatch (5 vs 7) | 🔴 CRITICAL | Spec | 30 min | Decision | +| 2 | Tools price (30g vs 40g) | 🔴 CRITICAL | Spec | 15 min | Decision | +| 3 | Smelter/Workshop production unclear | 🔴 CRITICAL | Spec | 30 min | Design | +| 4 | Storage capacity 10 (too small?) | 🟠 MEDIUM | Design | 15 min | Playtest | +| 5 | Building definitions incomplete | 🟠 MEDIUM | Spec | 30 min | Completion | +| 6 | NPC Market UI incomplete | 🟠 MEDIUM | Spec | 20 min | Design | +| 7 | Economic balance (1000g in 30m?) | 🟠 MEDIUM | Balance | 1-2 hours | Math | +| 8 | Building placement logic | 🟠 MEDIUM | Spec | 20 min | Clarification | +| 9 | Farm resource purpose | 🟡 LOW | Spec | 5 min | Decision | +| 10 | Market building role | 🟡 LOW | Spec | 10 min | Design | +| 11 | Upgrade costs formula | 🟡 LOW | Spec | 10 min | Clarification | +| 12 | Price rounding errors | 🟡 LOW | Code | 20 min | Implementation | +| 13 | Smelter inputs handling | 🟡 LOW | Spec | 30 min | Design | +| 14 | Production rate updates | 🟡 LOW | Spec | 10 min | Clarification | +| 15 | Grid position representation | 🟡 LOW | Tech | 15 min | Decision | + +--- + +## ⚠️ RECOMMENDATIONS + +### Immediate Actions (Before Starting Epic 2) + +1. **Align Resource List** (CRITICAL) + - Decide: 5 resources (Wood, Ore, Food, Bars, Tools) vs 7 resources (Wood, Ore, Bars, Tools, Stone, Clay, Bricks)? + - Update BOTH documents + - Create ResourceDefinitions class with ALL resources + prices + +2. **Verify Economic Balance** (CRITICAL) + - Calculate: Can player really earn 1000g in 30 minutes? + - If not: adjust production rates or selling prices + - Run simulation test BEFORE starting implementation + +3. **Complete Building Definitions** (CRITICAL) + - Specify: Grid size (2×2 or 3×3) for each building + - Specify: Production config (inputs, rates) for Smelter + Workshop + - Clarify: How does manual resource transport work? + +4. **Fix Upgrade Costs** (MEDIUM) + - Use consistent formula: either level-based array OR linear formula + - Currently inconsistent between spec and code example + +### Questions for Product Manager + +1. **Farm Resource (Food):** + - Is Food a real resource or should it be removed? + - What game purpose does it serve? + +2. **Market Building:** + - Is this just flavor text or an actual gameplay mechanic? + - Does player need to BUILD Market to access trading? + +3. **10 Building Limit:** + - Is this realistic for a 50×50 grid? + - Should we increase to 20-30? + +4. **Stone, Clay, Bricks:** + - Why appear in sprint-planning but not in tech-spec? + - Are these Tier 2 resources accidentally included? + +5. **1000g in 30 minutes:** + - Is this target realistic with current rates? + - Or should we adjust production/selling prices? + +--- + +## 🔗 Related Documents + +- `/docs/sprint-artifacts/tech-spec-epic-02.md` - Technical specification +- `/docs/sprint-planning-epic-2.md` - Sprint planning with stories +- `/docs/epics-stories-trade-factory-masters-2025-11-17.md` - Story definitions + +--- + +## Next Steps + +### For You (Mariusz) + +Please review this report and: +1. Clarify the resource list (5 vs 7) +2. Decide on Tools pricing (30g vs 40g) +3. Explain Smelter/Workshop production mechanics +4. Confirm if economic balance is achievable + +### For Me (Claude) + +Once you clarify these points, I can: +1. Create corrected Epic 2 specification +2. Identify any remaining inconsistencies +3. Generate implementation-ready story details +4. Create comprehensive acceptance criteria + +--- + +## Status + +🔴 **BLOCKED** on clarifications +⏳ **READY TO PROCEED** once critical questions answered + +**Estimated Fix Time:** 1-2 hours to resolve all critical issues + +--- + +**Document Owner:** Code Quality Review +**Last Updated:** 2025-12-02 +**Next Review:** After answers to critical questions diff --git a/docs/2-MANAGEMENT/project-status.md b/docs/2-MANAGEMENT/project-status.md new file mode 100644 index 0000000..ac50f1c --- /dev/null +++ b/docs/2-MANAGEMENT/project-status.md @@ -0,0 +1,359 @@ +# Project Status - Trade Factory Masters + + + +**Project:** FantasyFactio (Trade Factory Masters) +**Date:** 2025-12-02 +**Overall Progress:** 🔴 16% (47/289 SP) - Epic 1 Complete But Buggy +**Current Phase:** 🔄 Bug Fix & Documentation Reorganization + +--- + +## Executive Summary + +**Status:** Epic 1 is implemented but contains **3 critical bugs** that prevent core gameplay from working. Documentation has been reorganized to BMAD V6 structure. + +**Action Items:** +1. ⚠️ **URGENT:** Fix critical Epic 1 bugs (1-2 hours) +2. ✅ Documentation reorganized to BMAD V6 +3. ⏳ Ready to start Epic 2 after bug fixes + +--- + +## Quick Metrics + +| Metric | Value | Status | +|--------|-------|--------| +| **Overall Progress** | 47/289 SP (16%) | 🔄 On schedule | +| **Completed Epics** | 1/12 (Epic 1) | ⚠️ With bugs | +| **Current Sprint** | Sprint 1 (Complete) | ⏳ Awaiting fixes | +| **Test Coverage** | ~70-80 tests | ⚠️ Integration tests blocked | +| **Blockers** | 3 CRITICAL | 🔴 Must fix | +| **Documentation** | BMAD V6 Complete | ✅ Reorganized | + +--- + +## Phase Status + +| Phase | Status | Notes | +|-------|--------|-------| +| **Phase 1: Analysis** | ✅ Complete | Full discovery (18,448 lines) | +| **Phase 2: Planning** | ✅ Complete | 12 epics, 68 stories, 289 SP backlog | +| **Phase 3: Solutioning** | ✅ Complete | Architecture + UX design finalized | +| **Phase 4: Implementation** | 🔄 In Progress | Epic 1 coded (with bugs), awaiting fixes | + +--- + +## Epic Progress + +| Epic | Name | SP | Status | Notes | +|------|------|----|----|-------| +| **EPIC-00** | Project Setup | 13 | ✅ Done (buggy) | Flutter + Firebase + CI/CD setup | +| **EPIC-01** | Core Gameplay | 34 | ✅ Done (buggy) | Grid system, building mechanics (3 bugs) | +| **EPIC-02** | Tier 1 Economy | 26 | ⏳ Ready | Tech context complete, ready to start | +| **EPIC-03** | Automation | 42 | 📋 Planning | Tech context in progress | +| **EPIC-04** | Offline Production | 26 | 📋 Planning | Tech context in progress | +| **EPIC-05** | Mobile-First UX | 29 | ⏳ Ready | Tech context complete | +| **EPIC-06** | Progression System | 18 | 📋 Planning | Tech context in progress | +| **EPIC-07** | Tutorial | 21 | 📋 Planning | Low priority | +| **EPIC-08** | F2P Monetization | 23 | ⏳ Ready | Tech context complete | +| **EPIC-09** | Firebase Backend | 24 | 📋 Planning | Infrastructure | +| **EPIC-10** | Analytics | 13 | 📋 Planning | Metrics & tracking | +| **EPIC-11** | Testing & Quality | 20 | 📋 Planning | CI/CD enhancement | + +**Legend:** ✅ Done | 🔄 In Progress | ⏳ Ready to Start | 📋 Planned | ❌ Blocked + +--- + +## Critical Blockers + +### 🔴 Blocker #1: Integration Test Won't Compile + +**Location:** `integration_test/core_gameplay_loop_test.dart` +**Impact:** Cannot verify if gameplay works +**Fix Time:** 5 minutes +**Status:** 🔴 BLOCKING EPIC 1 COMPLETION + +See: `/docs/2-MANAGEMENT/EPIC-1-ISSUES.md` - Bug #1 + +### 🔴 Blocker #2: Resource Inventory Logic Broken + +**Location:** `lib/domain/entities/player_economy.dart` +**Impact:** Resources won't be added to inventory, core gameplay fails +**Fix Time:** 30 minutes +**Status:** 🔴 BLOCKING EPIC 1 COMPLETION + +See: `/docs/2-MANAGEMENT/EPIC-1-ISSUES.md` - Bug #2 + +### 🔴 Blocker #3: Type Cast Syntax Error + +**Location:** `lib/main.dart:325` +**Impact:** Code won't compile or crashes at runtime +**Fix Time:** 2 minutes +**Status:** 🔴 BLOCKING EPIC 1 COMPLETION + +See: `/docs/2-MANAGEMENT/EPIC-1-ISSUES.md` - Bug #3 + +--- + +## Velocity & Timeline + +### Solo Developer Velocity + +- **Target Velocity:** 25 SP/week (30 hours/week productive work) +- **Realistic Rate:** 1 SP = 4-5 hours +- **Current Velocity:** Pending (Epic 1 blocked) + +### MVP Timeline + +**Total Scope:** 170 SP (8 weeks at 25 SP/week) + +| Sprint | Epics | SP | Status | Timeline | +|--------|-------|----|----|----------| +| Sprint 1 | EPIC-00, EPIC-01 | 47 | ⏳ Fixing bugs | Week 1 | +| Sprint 2 | EPIC-02 | 26 | ⏳ Ready | Weeks 2-3 | +| Sprint 3 | EPIC-03 (part 1) | 25 | 📋 Planned | Weeks 4-5 | +| Sprint 4 | EPIC-03 (part 2), EPIC-04 | 28 | 📋 Planned | Weeks 6-7 | +| Sprint 5 | EPIC-05, EPIC-08 | 33 | 📋 Planned | Weeks 8-9 | +| Sprint 6 | EPIC-06, EPIC-10 | 22 | 📋 Planned | Weeks 10-11 | +| Sprint 7 | EPIC-09, EPIC-07 | 37 | 📋 Planned | Weeks 12+ | + +**MVP Expected Completion:** ~8-9 weeks (with buffer) + +--- + +## Current Sprint: Sprint 1 (Bug Fixes) + +**Duration:** 2025-12-02 onwards +**Focus:** Fix Epic 1 critical bugs +**Capacity:** 37 SP (bug fixes) + +### Sprint Goals + +- [x] Deep dive analysis of Epic 1 +- [x] Document all issues and fixes +- [ ] Fix Bug #1 (5 min) +- [ ] Fix Bug #2 (30 min) +- [ ] Fix Bug #3 (2 min) +- [ ] Run complete test suite +- [ ] Verify integration tests pass +- [ ] Commit and push fixes + +### Next Sprint: Sprint 2 (Epic 2) + +**Planned Start:** After Sprint 1 fixes complete +**Epic:** EPIC-02 - Tier 1 Economy +**Scope:** 26 SP (~2-3 weeks) +**Stories:** +1. STORY-02.1: Building Definitions (8 SP) +2. STORY-02.2: Resource Definitions (6 SP) +3. STORY-02.3: NPC Market UI (6 SP) +4. STORY-02.4: Market Transactions (3 SP) +5. STORY-02.5: Building Placement (2 SP) +6. STORY-02.6: Economic Balance (1 SP) + +--- + +## Module Progress + +### Game Engine (Flame) + +| Component | Status | Coverage | Notes | +|-----------|--------|----------|-------| +| Grid System (50×50) | ✅ Complete | High | Isometric, spatial culling working | +| Camera (zoom/pan) | ✅ Complete | High | Animation TODO (low priority) | +| Building Component | ✅ Complete | High | Sprite rendering, tap detection | +| Tap Detection | ✅ Complete | High | Working correctly | + +### Domain Layer + +| Component | Status | Coverage | Notes | +|-----------|--------|----------|-------| +| Building Entity | ✅ Complete | ✅ Tested | Immutable, copyWith pattern | +| Resource Entity | ✅ Complete | ✅ Tested | Inventory capacity managed | +| PlayerEconomy | ✅ Complete | ⚠️ Broken | Bug #2: addResource() broken logic | +| CollectResources UseCase | ✅ Complete | ⚠️ Blocked | Depends on Bug #2 fix | +| UpgradeBuilding UseCase | ✅ Complete | ✅ Tested | Logic works, tests have param bug | + +### Data Layer + +| Component | Status | Coverage | Notes | +|-----------|--------|----------|-------| +| Hive Storage | ✅ Complete | ⚠️ Minimal | Adapter registration working | +| Firebase Auth | ✅ Complete | ⚠️ Untested | Setup done, not tested in CLI | +| Firestore | ⏳ Partial | ❌ Not tested | Schema designed, implementation pending | + +### Testing + +| Test Type | Count | Status | Pass Rate | +|-----------|-------|--------|-----------| +| Unit Tests | ~70-80 | ⏳ Mostly pass | ~95% (Bug #2 blocks some) | +| Integration Tests | 1 suite | ❌ Won't compile | 0% (Bug #1 blocks) | +| Widget Tests | Minimal | ⏳ Placeholder | - | + +--- + +## Documentation Status + +### BMAD V6 Reorganization ✅ Complete + +| Section | Status | Files | +|---------|--------|-------| +| **Root Files** | ✅ Done | CLAUDE.md, START-HERE.md | +| **.claude/** | ✅ Done | FILE-MAP.md, TABLES.md, PATTERNS.md, PROMPTS.md | +| **1-BASELINE/product/** | ✅ Done | PRD, product-brief, market-research | +| **1-BASELINE/architecture/** | ✅ Done | System architecture, tech decisions | +| **2-MANAGEMENT/** | ✅ Done | project-status, MVP-TODO, EPIC-1-ISSUES | +| **2-MANAGEMENT/epics/** | ⏳ Partial | EPIC-00, EPIC-01 current; rest need updates | +| **4-DEVELOPMENT/** | ⏳ Partial | Need SETUP.md, DEVELOPMENT.md | +| **5-ARCHIVE/** | ⏳ Ready | Old docs can be moved | + +--- + +## Known Issues Summary + +### Critical (Must Fix) +- Bug #1: Integration test compilation (5 min fix) +- Bug #2: Resource inventory logic (30 min fix) +- Bug #3: Type cast syntax (2 min fix) + +### Medium (Should Fix) +- Incomplete camera animation +- Hardcoded configuration values +- Firebase not optional +- Documentation inconsistencies + +### Low (Nice to Fix) +- Magic numbers without constants +- Performance optimization opportunities + +**Full Details:** `/docs/2-MANAGEMENT/EPIC-1-ISSUES.md` + +--- + +## Risks & Mitigation + +| Risk | Probability | Impact | Mitigation | +|------|-----------|--------|-----------| +| Firebase costs exceed budget | Medium | High | Set up cost alerts, optimize queries | +| Flame engine learning curve | Medium | Medium | Deep dive completed, patterns established | +| Performance on low-end devices | Medium | High | Profile early, optimize rendering | +| Team bandwidth | Low | High | Currently solo dev, scaling planned for Epic 6+ | +| Scope creep | Low | High | Strict MVP backlog, feature gates for future | + +--- + +## Recent Changes + +### 2025-12-02: Documentation Reorganization +- ✅ Created CLAUDE.md (AI entry point) +- ✅ Reorganized docs/ to BMAD V6 +- ✅ Created .claude/ with 4 key files (FILE-MAP, TABLES, PATTERNS, PROMPTS) +- ✅ Deep dive analysis of Epic 1 completed +- ✅ 9 issues documented in EPIC-1-ISSUES.md +- ✅ Created START-HERE.md for humans +- ✅ Created BMAD-STRUCTURE.md for documentation guidelines + +### 2025-11-23: Epic 1 Completion (with bugs) +- ✅ All 12 stories coded +- ✅ Unit tests created +- ⚠️ Integration tests have compilation errors +- ⚠️ Bugs found during documentation review + +### 2025-11-17: Sprint Planning +- ✅ 12 epics defined (68 stories) +- ✅ PRD finalized +- ✅ Architecture designed +- ✅ UX flows designed + +--- + +## Stakeholder Summary + +### For Developers +- Read `/CLAUDE.md` for complete guide +- Check `.claude/FILE-MAP.md` to find code +- Reference `.claude/PATTERNS.md` for examples +- **IMMEDIATE:** Fix 3 critical bugs in EPIC-1-ISSUES.md + +### For Product Manager +- **Status:** Epic 1 needs bug fixes, then Epic 2 ready +- **Timeline:** MVP on track (8-9 weeks total) +- **Blockers:** 3 critical bugs (1-2 hours to fix) +- **Next:** Epic 2 planning (Tier 1 Economy - 26 SP) + +### For Stakeholders +- **Progress:** 16% complete (Epic 1 of 12) +- **Quality:** Documentation improved, bugs identified +- **Timeline:** On schedule pending bug fixes +- **Risk:** Low (solo dev, small scope) + +--- + +## Action Items + +### Immediate (This Week) + +- [ ] Fix Bug #1 - Integration test parameter +- [ ] Fix Bug #2 - Resource inventory logic +- [ ] Fix Bug #3 - Type cast syntax +- [ ] Verify all tests pass +- [ ] Push fixes to branch + +### This Sprint (Sprint 1) + +- [ ] Complete bug fixes +- [ ] Update EPIC-01 retrospective +- [ ] Plan Epic 2 in detail +- [ ] Prepare Sprint 2 backlog + +### Next Sprint (Sprint 2) + +- [ ] Implement STORY-02.1: Building Definitions +- [ ] Implement STORY-02.2: Resource Definitions +- [ ] Continue with remaining EPIC-02 stories + +--- + +## Key Documents + +| What | Where | +|------|-------| +| AI Guide | `/CLAUDE.md` | +| File Index | `.claude/FILE-MAP.md` | +| Code Patterns | `.claude/PATTERNS.md` | +| Issues | `/docs/2-MANAGEMENT/EPIC-1-ISSUES.md` | +| Epic Details | `/docs/2-MANAGEMENT/epics/epic-*.md` | +| Backlog | `/docs/2-MANAGEMENT/MVP-TODO.md` | + +--- + +## Metrics to Track + +**Weekly Updates:** +- Story points completed +- Bugs found/fixed +- Test coverage % +- Code quality score (flutter analyze) +- Performance metrics (FPS, memory) + +**Monthly Updates:** +- Velocity trend +- Epic progress +- Risk assessment +- Stakeholder communication + +--- + +## Next Review + +- **Date:** 2025-12-09 (after bug fixes) +- **Focus:** Epic 1 bug verification, Epic 2 planning +- **Audience:** Dev team, Product Manager + +--- + +**Document Owner:** Project Manager (Claude) +**Last Updated:** 2025-12-02 +**Status:** 🟡 IN PROGRESS - Awaiting bug fixes +**Next Update:** After Sprint 1 bug fixes complete diff --git a/docs/BMAD-STRUCTURE.md b/docs/BMAD-STRUCTURE.md new file mode 100644 index 0000000..d086e86 --- /dev/null +++ b/docs/BMAD-STRUCTURE.md @@ -0,0 +1,520 @@ +# BMAD V6 Documentation Structure + + + +**Project:** Trade Factory Masters +**Documentation Version:** BMAD V6 +**Last Updated:** 2025-12-02 + +--- + +## What is BMAD? + +**BMAD** = **B**aseline **M**anagement **A**rchitecture **D**esign + +It's an enterprise methodology for organizing project documentation that works well with AI-assisted development. Key principles: + +1. **Phased documentation** - aligns with project phases +2. **Clear ownership** - each document has a purpose +3. **AI-optimized** - separate files for humans and AI +4. **Scalable** - works for projects of any size + +--- + +## Directory Structure + +``` +project/ +├── CLAUDE.md ← Entry point for AI +├── .claude/ ← AI-optimized docs +│ ├── FILE-MAP.md ← Code index +│ ├── TABLES.md ← Data schema +│ ├── PATTERNS.md ← Code patterns +│ └── PROMPTS.md ← Task templates +│ +└── docs/ ← Human-readable docs + ├── 00-START-HERE.md ← First read (this file is guide) + ├── BMAD-STRUCTURE.md ← This document + │ + ├── 1-BASELINE/ ← Phase 1-2: Analysis & Planning + │ ├── product/ ← Product documentation + │ │ ├── prd-v1.0.md ← Product Requirements Document + │ │ ├── product-brief.md ← Vision & market + │ │ └── market-research.md ← Competitive analysis + │ │ + │ └── architecture/ ← Technical documentation + │ ├── system-architecture.md ← System design + │ ├── database-schema.md ← Data models (if detailed) + │ └── tech-decisions.md ← ADRs, why we chose what + │ + ├── 2-MANAGEMENT/ ← Phase 3-4: Planning & Execution + │ ├── project-status.md ← Current state, progress + │ ├── MVP-TODO.md ← Remaining work + │ │ + │ └── epics/ ← Epic & story files + │ ├── epic-00-project-setup.md + │ ├── epic-01-core-gameplay.md + │ ├── epic-02-tier-1-economy.md + │ └── ...epic-03-12... + │ + ├── 3-ARCHITECTURE/ ← Deep technical details (optional) + │ ├── state-management.md + │ ├── game-engine-design.md + │ └── performance-tuning.md + │ + ├── 4-DEVELOPMENT/ ← Phase 4: Implementation guides + │ ├── SETUP.md ← Environment setup + │ ├── DEVELOPMENT.md ← Dev guidelines + │ ├── WORKFLOW.md ← Daily workflow + │ └── TROUBLESHOOTING.md ← Common issues + │ + └── 5-ARCHIVE/ ← Deprecated docs (don't delete!) + ├── old-prd-2025-11-17.md + ├── old-architecture.md + └── ...other old versions... +``` + +--- + +## File Purpose & Content Guidelines + +### .claude/ - AI-Optimized Documentation + +These files are designed for AI to read first. **Keep them concise and structured.** + +| File | Purpose | Format | Audience | +|------|---------|--------|----------| +| **FILE-MAP.md** | Index of all code files by category | Tables + short descriptions | AI reading code | +| **TABLES.md** | Database schema, data models | Tables + examples | AI writing data code | +| **PATTERNS.md** | Code patterns, conventions | Code examples + explanation | AI writing features | +| **PROMPTS.md** | Task templates and workflows | Markdown templates | AI starting new work | + +**Key Rule:** These files should be readable in <5 minutes by AI. + +--- + +### docs/1-BASELINE/ - Requirements & Architecture + +**When:** Completed during Phase 1-2 (Analysis & Planning) +**Who Owns:** Product Manager, Architect +**Who Uses:** Developers (reference), AI (understanding context) + +#### docs/1-BASELINE/product/ + +**prd-v1.0.md** - Product Requirements Document +- What the product does +- Who uses it +- Why it's valuable +- Feature list with acceptance criteria +- Out of scope items +- Success metrics + +**product-brief.md** - Vision & Market +- Product vision +- Market gap / opportunity +- Competitive landscape +- Revenue model +- Key assumptions + +**market-research.md** - Market Analysis +- Market size +- Target audience +- Competitor analysis +- Pricing analysis +- Regulatory considerations + +#### docs/1-BASELINE/architecture/ + +**system-architecture.md** - Technical Design +- High-level architecture diagram +- Technology choices +- Data flow +- Performance targets +- Security model + +**database-schema.md** (if detailed) - Data Models +- Entity definitions +- Relationships +- Constraints +- Firestore structure +- Migration strategy + +**tech-decisions.md** - Architecture Decision Records (ADRs) +- Decision made +- Context/problem +- Options considered +- Decision + reasoning +- Consequences + +--- + +### docs/2-MANAGEMENT/ - Status & Tracking + +**When:** Created during Phase 3 (Planning) & updated during Phase 4 (Execution) +**Who Owns:** Project Manager / Scrum Master +**Who Uses:** Everyone (developers, managers, stakeholders) +**Update Frequency:** Weekly (or per sprint) + +#### project-status.md + +**Purpose:** Single source of truth for project status + +**Content:** +- Current phase and sprint +- Metrics (% complete, story points, velocity) +- Module/epic progress breakdown +- Current blockers +- Next sprint priorities +- Recent changes +- Risk assessment + +**Format:** Markdown with tables and progress indicators + +**Update:** Weekly by PM/SM + +#### MVP-TODO.md + +**Purpose:** High-level remaining work + +**Content:** +- Grouped by epic +- Story count and points per epic +- Status indicators +- Dependencies +- Estimated timeline + +**Format:** Nested lists or tables + +#### EPIC-1-ISSUES.md (Example) + +**Purpose:** Bug tracking and issue resolution (one per epic if issues exist) + +**Content:** +- List of critical bugs with details +- Severity and impact +- Fix instructions +- Timeline for fixes + +#### epics/ + +**epic-NN-{name}.md** - Epic Definition & Stories + +**Purpose:** Container for all stories in an epic + +**Content:** +- Epic overview +- High-level goals +- Complete story list (each with AC, implementation notes) +- Epic status +- Retrospective (after completion) + +**Format:** See "Epic & Story Format" below + +--- + +### docs/4-DEVELOPMENT/ - Developer Guides + +**When:** Created before development starts, updated as needed +**Who Owns:** Tech Lead / Lead Developer +**Who Uses:** Developers (daily reference) +**Update Frequency:** As needed + +**SETUP.md** - Environment Setup +- Prerequisites +- Installation steps +- First-time setup checklist +- Verification steps + +**DEVELOPMENT.md** - Development Guidelines +- Coding standards +- Git workflow (branching, commits) +- Code review process +- Testing requirements +- Documentation requirements + +**WORKFLOW.md** - Daily Workflow (Optional) +- How to start a day's work +- How to pick a story +- How to run tests +- How to commit and push +- How to wrap up + +**TROUBLESHOOTING.md** - Common Issues +- Build errors and solutions +- Test failures and debugging +- Firebase setup issues +- Performance problems +- Deployment issues + +--- + +### docs/5-ARCHIVE/ - Deprecated Documentation + +**Purpose:** Keep old versions for historical reference + +**When to Archive:** +- Documentation is superseded by newer version +- Feature is deprecated +- Plan changed and doc no longer relevant + +**Example:** +``` +5-ARCHIVE/ +├── prd-2025-11-17-v0.9.md ← Old version +├── architecture-old.md ← Replaced by new version +└── brainstorm-results.md ← Session output, not live doc +``` + +**Important:** Never delete old docs! Archive them. + +--- + +## Epic & Story Format (BMAD Compatible) + +### Epic File Format + +```markdown +# Epic {N}: {Name} + +**Epic ID:** EPIC-0{N} +**Sprint(s):** Sprint {X}-{Y} +**Story Points:** {total} +**Status:** 🔄 In Progress | ⏳ Planned | ✅ Done +**Priority:** P0 (Critical) | P1 (High) | P2 (Nice-to-have) + +## Overview +{1-3 paragraph description of epic} + +## Business Value +{Why this epic matters} + +## Acceptance Criteria (Epic Level) +- [ ] {Epic AC 1} +- [ ] {Epic AC 2} + +## Dependencies +- {Epic X.Y if dependent on another epic} +- {External dependency if any} + +## Stories + +### Story {N}.1: {Name} +**Status:** ⏳ Planned | 🔄 In Progress | ✅ Done +**Story Points:** {SP} +**Technical Notes:** {Implementation hints} + +As a {user type} +I want {action} +So that {benefit} + +#### Acceptance Criteria +- [ ] {AC1} +- [ ] {AC2} + +#### Files to Create/Modify +- lib/path/file.dart +- test/path/file_test.dart + +### Story {N}.2: {Name} +... + +## Technical Context +{Architectural decisions for this epic} + +## Known Issues +{If any issues found during implementation} + +## Retrospective (After Completion) +**Completed:** {date} +**Actual SP:** {how many delivered} +**Velocity Notes:** {was it faster/slower than expected, why} +**Learnings:** {what we learned} +**Deferred Items:** {what didn't make it} +``` + +--- + +## File Naming Conventions + +| Content Type | Format | Example | +|--------------|--------|---------| +| Product doc | `{topic}-v{version}.md` | `prd-v1.0.md` | +| Architecture | `{topic}.md` | `system-architecture.md` | +| Epic | `epic-{NN}-{name}.md` | `epic-02-tier-1-economy.md` | +| Status | `{type}-status.md` | `project-status.md` | +| Guide | `{TOPIC}.md` (CAPS) | `SETUP.md`, `DEVELOPMENT.md` | +| Archive | Original name | `prd-2025-11-17.md` | + +--- + +## Content Guidelines + +### Keep It Concise + +- **For humans:** 2-5 pages max per document +- **For AI:** Condensed tables, bullet points +- **Long docs:** Split into multiple files + +### Link Between Documents + +Use relative links: +```markdown +See [details](../1-BASELINE/product/prd-v1.0.md) +Read [patterns](./.claude/PATTERNS.md) +``` + +### Use Consistent Formatting + +- Headings: # H1, ## H2, ### H3 (no more than H4) +- Lists: Use `-` for bullets, `1.` for numbered +- Tables: Use markdown tables, 4-column max for readability +- Code: Use triple backticks with language specified + +### Add AI Index + +Every doc should start with: +```markdown + +``` + +**Example:** +```markdown + +``` + +This helps AI find relevant docs quickly. + +### Always Include + +- Title (H1) +- AI-INDEX comment (if doc is referenced by code) +- Last Updated date (footer) +- Links to related docs + +--- + +## Update Strategy + +### During Development + +- **project-status.md:** Update after each sprint (weekly) +- **Epic files:** Update story status as work progresses +- **FILE-MAP.md:** Update when new files created +- **PATTERNS.md:** Update when new patterns established + +### After Each Epic + +1. Update epic file with retrospective +2. Update project-status.md with metrics +3. Archive any deprecated docs +4. Review all docs for accuracy + +### When Making Major Changes + +1. Don't delete old docs - archive them +2. Create new version if significant change +3. Update cross-references in other docs +4. Update this BMAD-STRUCTURE.md if structure changed + +--- + +## Common Mistakes to Avoid + +❌ **DON'T:** +- Keep docs in scattered locations +- Use outdated versions (always use latest) +- Delete old docs (archive instead) +- Add too much detail (keep it scannable) +- Forget to update docs during development +- Use vague status indicators (use icons: ✅ 🔄 ⏳ ❌) + +✅ **DO:** +- Follow the structure above +- Update docs regularly (weekly) +- Archive old versions +- Use clear headings and tables +- Cross-link between documents +- Include concrete examples +- Update "Last Updated" date + +--- + +## Tools & Templates + +### AI-Friendly Search + +For AI to find docs quickly: +1. Use AI-INDEX comments +2. Maintain FILE-MAP.md current +3. Keep related docs in same folder +4. Use consistent naming + +### Human-Friendly Navigation + +For humans to find docs: +1. Use clear folder names +2. Maintain README in each folder (optional) +3. Link from START-HERE +4. Keep folder depth < 3 levels + +--- + +## Checklist: Setting Up Documentation + +### Initial Setup + +- [ ] Create folder structure (as shown above) +- [ ] Create 00-START-HERE.md +- [ ] Create BMAD-STRUCTURE.md (this file) +- [ ] Create .claude/ folder with 4 files +- [ ] Create CLAUDE.md in root +- [ ] Create 1-BASELINE/ with product and architecture + +### During Development + +- [ ] Create 2-MANAGEMENT/ with status files +- [ ] Add epic files as epics are defined +- [ ] Create 4-DEVELOPMENT/ guides +- [ ] Update project-status.md weekly +- [ ] Add issues files if bugs found + +### After Each Milestone + +- [ ] Update project-status.md with metrics +- [ ] Archive old docs to 5-ARCHIVE/ +- [ ] Review all links (fix any broken) +- [ ] Update CLAUDE.md if needed + +--- + +## FAQ + +**Q: Should all documentation be in docs/?** +A: Yes, except CLAUDE.md (in root) and .claude/ (in root). Everything else goes in docs/. + +**Q: How often should I update documents?** +A: Weekly for status docs, as-needed for others. Update immediately if info changes. + +**Q: Can I delete old documents?** +A: No! Archive them in 5-ARCHIVE/. They're useful for history. + +**Q: What if I need a document type not listed here?** +A: Add it! Just make sure it fits in a logical folder and follows the guidelines. + +**Q: How detailed should architecture documents be?** +A: Include enough detail for a developer to understand implementation. Too much detail → keep in code comments. + +--- + +## Resources + +- **BMAD Method:** Enterprise methodology for documentation +- **This Project:** FantasyFactio uses BMAD V6 +- **For Examples:** See docs/ folder in this project +- **For AI:** Read CLAUDE.md for AI-optimized guidelines + +--- + +**Document Owner:** Claude (BMAD Documentation Agent) +**Last Updated:** 2025-12-02 +**Version:** BMAD V6 - Release 1.0