Skip to content

Conversation

@MineForeman
Copy link
Owner

Summary

  • Fixed game lockup issue that occurred when player movement was blocked
  • Implemented comprehensive keystroke logging for better debugging
  • Fixed multiple combat and inventory system bugs

Changes

Bug Fixes

  • Movement lockup fix: Added immediate movement processing after queueing to prevent turn freezing
  • Duplicate combat messages: Removed redundant logging in combat update loop
  • Combat after death: Added dead entity removal after combat processing
  • Dropped items invisible: Fixed event processing and component restoration for dropped items
  • Invisible monsters in corridors: Fixed FOV propagation to render system

New Features

  • Input logging system: Complete keystroke logging with action mapping to veyrm_input.log
  • Inventory key bindings: Context-aware lowercase key support (d/D for drop, e/E/x/X for examine)

Test Plan

  • Verified movement no longer locks up when blocked
  • Confirmed combat messages appear only once
  • Tested that dead entities cannot attack
  • Verified dropped items appear on map
  • Checked monsters are visible in corridors
  • Tested inventory key bindings work with lowercase
  • Verified input logging captures all keystrokes

🤖 Generated with Claude Code

NRF and others added 23 commits September 15, 2025 06:14
- Document modern C++ patterns and RAII principles
- Emphasize composition over inheritance
- Include Rule of Zero/Five guidelines
- Add smart pointer usage patterns
- Document const-correctness and move semantics
- Provide code examples and anti-patterns
- Include refactoring checklists for legacy code
- Phase 1: Critical memory safety improvements
- Phase 2: Architecture modernization with ECS
- Phase 3: Performance optimizations with move semantics
- Phase 4: API improvements and const-correctness
- Phase 5: Testing and documentation
- Detailed task breakdowns and success metrics
- Risk mitigation strategies and rollout schedule
- Replace unsafe void* user_data with type-safe std::variant
- Use std::shared_ptr<MonsterAIData> for RAII memory management
- Update MonsterAI to use new type-safe interface
- Add comprehensive memory safety tests
- Maintain backward compatibility with deprecated methods
- All tests passing (1786 assertions in 135 test cases)

This eliminates an entire class of memory bugs and provides
compile-time type safety for AI data management.
- Convert Room* to const Room* for observer pattern clarity
- Add getCurrentRoom/setCurrentRoom accessor methods
- Document ownership semantics (Map owns rooms)
- Update tests to use new type-safe API
- All tests passing (1779 assertions)

Observer pointers are appropriate here since Map clearly
owns the rooms and outlives any room references.
- Add test_entity_memory_safety.cpp to test suite
- Test type-safe AI data access
- Test ownership and lifetime management
- Test const-correctness
- Test legacy compatibility
- All tests passing: 1802 assertions in 137 test cases

Memory safety refactoring validated with comprehensive testing.
- Remove deprecated ai_data_pool completely
- Eliminate legacy getUserData/setUserData methods
- Convert Room* to const Room* for safety
- All AI data now owned by entities via RAII

Phase 1 Complete: Critical Memory Safety ✅
- No raw pointers (except const observers)
- No manual memory management
- Type safety throughout
- All tests passing (1806 assertions)
- Create component-based Entity Component System
- Implement core components:
  - PositionComponent for movement/location
  - RenderableComponent for visual representation
  - HealthComponent for damage/healing
  - CombatComponent for combat stats
- Type-safe component management with templates
- Comprehensive test suite (101 new assertions)
- All tests passing (1907 total assertions)

This provides the foundation for migrating from
inheritance-based entities to composition-based ECS.
- Create EntityBuilder with fluent interface
- Implement PlayerFactory, MonsterFactoryECS, ItemFactoryECS
- Add EntityAdapter for legacy<->ECS conversion
- Bidirectional sync between systems
- Type detection for entity classification
- Comprehensive test coverage (85 new assertions)
- All tests passing (1992 total assertions)

This provides a safe migration path from inheritance
to composition-based architecture.
Replaces bridge dependencies with native ECS implementations:
- Add native CombatSystem with queue-based attack processing
- Add native AISystem with multiple behavior patterns (aggressive, defensive, wandering)
- Add AIComponent to all monster entities with configurable behaviors
- Update GameWorld to use native systems instead of bridges
- Fix CMakeLists.txt structure to avoid duplicate symbols (veyrm_core library)
- Update all component member access patterns for consistency
- Add comprehensive tests for new ECS systems

Key improvements:
- Monsters now have intelligent AI behaviors
- Combat is fully ECS-based without legacy dependencies
- Pathfinding with BFS for smarter enemy movement
- All 2125 test assertions pass
- ECS demo successfully shows legacy to ECS migration

This completes ~85% of Phase 2 architecture modernization.
Remaining work: event system, performance optimization, save/load integration.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
- Created DataLoader singleton for loading monsters and items from JSON
- Restructured monsters.json and items.json with ECS component structure
- Replaced hardcoded EntityFactory templates with data-driven approach
- Added 10 monster templates and 19 item templates
- Updated entity_factory.cpp to use DataLoader instead of hardcoded values
- Added comprehensive test suite for data loading functionality
- All data loader tests passing successfully

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
- Update MonsterFactory to handle both old and new JSON formats
- Update ItemFactory to handle component-based JSON structure
- Add missing monster species (gutter_rat, cave_spider, orc_rookling)
- Fix test failures caused by JSON assertion errors
- Tests now pass: 131/135 (up from crash on startup)

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
- Initialize ECS world in GameManager constructor
- Load ECS data from DataLoader alongside legacy factories
- Set use_ecs flag to true on startup
- Game now runs with full ECS system activated
- All ECS systems (movement, combat, AI, inventory) now active
- Maintains backward compatibility with legacy systems
- Tests: 131/135 passing (same as before)
- Gameplay verified working with map rendering and player movement

The ECS transformation is now complete and active!

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
- Update item type mapping to handle 'currency' as GOLD type
- Fix item manager to use 'gold' instead of 'gold_coins'
- Update monster integration tests for new monster count (13 species)
- Fix test expectations to match actual monster stats from JSON
- Replace 'kobold' references with 'goblin' in tests
- Update ECS integration test to expect enabled ECS by default

All tests now passing: 135/135 ✅

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
MAJOR CHANGE: ECS is now the authoritative system!

Changes made:
- ECS update loop now returns early, skipping legacy updates
- Monster updates use ECS when enabled, skip legacy MonsterAI
- Player/monster creation only happens in ECS mode (no dual creation)
- Removed bridge synchronization overhead
- Legacy systems only run when ECS is explicitly disabled

Results:
- Game runs entirely on ECS systems when use_ecs=true
- Legacy path preserved for compatibility (when use_ecs=false)
- All tests passing (162/162)
- No performance degradation observed

The ECS transformation is now complete - the game runs primarily
on the Entity Component System architecture!

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
- Add ECS movement processing in game_screen when ECS mode is enabled
- Sync ECS player position to deprecated position variables immediately
- Add getPlayerEntity() method to GameWorld
- Update CLAUDE.md to clarify no vi-style keys

Note: Player movement still not fully working - position updates but @ symbol doesn't move on screen. Need further investigation.

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
- Add debug output to ECS movement system and GameWorld
- Sync ECS player position to deprecated variables after movement
- Player position appears stuck, input not reaching movement handler

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
- Input is correctly reaching handlePlayerMovement
- ECS processPlayerAction is being called
- But player_id is 0 - no player entity exists in ECS
- The actual compiled file is game_world_full.cpp not game_world.cpp
- Need to ensure player entity is created in ECS on game start

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
- Merged game_world_full.cpp into game_world.cpp
- Merged inventory_system_full.cpp into inventory_system.cpp
- Updated CMakeLists.txt to use regular files
- Removed _full files to avoid confusion
- Debug output still shows player_id=0 issue to fix

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
- Fixed movement coordinate bug where deltas were incorrectly passed as absolute positions
- Removed debug output (cout statements) that were causing screen flickering
- Redesigned status bar to use 2 lines with horizontal separator for better readability
- Updated help screen with comprehensive list of all keybindings organized by category
- Player @ symbol now moves correctly in ECS mode
- Full position coordinates now visible in status bar

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
Major cleanup removing legacy compatibility code:

Bridge Classes Removed:
- EntityManagerBridge, CombatSystemBridge, RendererBridge
- All bridge sync code and references
- Bridge test files

Renderer Updates:
- Replace EntityManager::getVisibleEntities() with ECS RenderSystem
- Remove legacy renderEntities() method
- Direct integration with ecs::RenderSystem::renderToGrid()
- ECS entities now render correctly (items, monsters, etc.)

Game Manager Fixes:
- Remove dual legacy+ECS player creation in ECS mode
- Fix FOV system to use ECS player position
- Skip legacy spawning and combat when in ECS mode

Player rendering now works correctly in full ECS mode with proper FOV.
All entities (items, monsters) render through ECS RenderSystem.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit removes a significant portion of the legacy entity system as part of the migration to a pure ECS architecture.

## Removed Legacy Components:
- Monster class and all references
- MonsterFactory and MonsterAI systems
- CombatSystem (legacy version)
- ItemFactory and ItemManager
- SpawnManager
- EntityAdapter (bridge class)
- All legacy entity test files

## ECS Improvements:
- Added PlayerComponent for player-specific data (level, exp, gold)
- Updated PlayerFactory to create full ECS player entities
- Fixed ECS combat system to properly log results
- Updated game_screen to work without legacy Player class
- Player movement now works entirely through ECS

## Documentation:
- Created LEGACY_REMOVAL_PLAN.md to track systematic removal
- Updated CLAUDE.md with current project instructions
- Fixed markdown linting issues in documentation

## Current State:
- Game runs with ECS-only player (no legacy Player created)
- All tests passing (1454 assertions in 118 test cases)
- Player movement, combat, and rendering work through ECS
- Item.h/cpp and Player.h/cpp remain for inventory compatibility

## Next Steps:
- Migrate status bar to read from ECS components
- Update inventory UI to use ECS InventoryComponent
- Remove Player and Entity base classes
- Complete transition to pure ECS architecture

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
Major cleanup removing all legacy inheritance-based systems:

Removed files:
- Entity base class (entity.h/cpp)
- EntityManager (entity_manager.h/cpp)
- Player class (player.h/cpp)
- Item class (item.h/cpp)
- Inventory class (inventory.h/cpp)
- Associated test files for Item and Inventory

Changes:
- Updated CMakeLists.txt to remove legacy source files
- Cleaned up forward declarations of removed classes
- Modified inventory_renderer to work without Item class
- Updated all includes and references to legacy systems
- Fixed compilation errors from removed dependencies

The ECS migration is now structurally complete with only player
position/health fields remaining as deprecated but active.

All tests pass (1308 assertions) and game runs without errors.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
- Fix game lockup after blocked movement attempts
  - Add immediate movement processing after queueing player actions
  - Ensure turn properly completes on blocked moves

- Implement comprehensive keystroke logging
  - Add input log file (veyrm_input.log) for debugging
  - Log all keystrokes with action mapping
  - Add context-aware inventory key logging

- Fix duplicate combat messages
  - Remove redundant combat logging in update loop
  - Consolidate logging in processAttack function

- Fix combat after death issue
  - Add removeDeadEntities() call after combat processing
  - Prevent dead entities from continuing to attack

- Fix dropped items not appearing on map
  - Add immediate event processing after drop action
  - Restore position component to dropped items
  - Fix event subscription for drop events in GameWorld

- Fix invisible monsters in corridors
  - Update RenderSystem FOV grid when FOV is calculated
  - Ensure FOV properly propagates to rendering system

- Add inventory-specific key bindings
  - Support lowercase d/D for drop, e/E/x/X for examine
  - Make bindings screen-specific, not global
  - Log inventory key actions for debugging

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@claude
Copy link

claude bot commented Sep 16, 2025

Claude finished @MineForeman's task —— View job


Code Review Complete

Summary

This is a substantial and well-executed pull request that addresses critical gameplay bugs while introducing comprehensive input logging. The architectural transition to ECS appears solid with good separation of concerns.

🔍 Code Quality & Best Practices

Strengths

  • Well-documented code: Comprehensive Doxygen comments throughout ECS system
  • Clean architecture: Proper ECS separation with components, systems, and entities
  • Consistent patterns: Good use of RAII, const correctness, and modern C++ features
  • Defensive programming: Proper null checks and validation in critical paths

⚠️ Areas for Improvement

  • Deep call stacks: Some functions like GameWorld::processQueue() could benefit from decomposition
  • Include organization: Mixed global/namespace includes could be standardized
  • Error handling: Some functions return bool for success/failure but don't provide error details

🐛 Bug Fixes Analysis

Well-Addressed Issues

  1. Movement lockup fix (src/ecs/movement_system.cpp:39): Immediate processing prevents turn freeze
  2. Combat after death (src/ecs/combat_system.cpp:25): Proper dead entity handling
  3. Invisible items fix (src/ecs/game_world.cpp:94): Event system restores position components correctly

🔍 Potential Issues

  • Input command queuing (include/ecs/input_system.h:58): Queue could grow unbounded without rate limiting
  • Entity lookup performance (src/ecs/movement_system.cpp:109): Linear search through entities for each lookup

🔒 Security Concerns

⚠️ Input Logging Security

  • Keystroke logging (src/input_handler.cpp:61): All keystrokes logged to veyrm_input.log
    • Risk: Could capture sensitive data if passwords/secrets entered
    • Recommendation: Add filtering for sensitive contexts or implement log rotation
  • Log file permissions: No evidence of restricted file permissions for log files
  • Memory safety: ECS system uses smart pointers appropriately, reducing memory corruption risks

🔍 Injection Risks

  • JSON parsing (data/monsters.json, data/items.json): Need validation to prevent malformed data attacks
  • File path handling: Log file paths appear to be hardcoded, reducing path traversal risk

Performance Considerations

Good Patterns

  • System priorities (include/ecs/input_system.h:134): Proper system ordering for performance
  • Component pools: ECS uses efficient component storage patterns
  • Move semantics: Appropriate use of std::move in entity transfers

⚠️ Performance Concerns

  • Entity iteration: Multiple linear searches through entity vectors per frame
  • String operations: Heavy string construction in logging paths (src/input_handler.cpp:62)
  • Memory allocations: Frequent queue operations in movement system

💡 Recommendations

  1. Consider entity indexing/hashing for faster lookups
  2. Implement log level filtering to reduce string operations
  3. Profile frame time to identify bottlenecks

🧪 Test Coverage

Well-Covered Areas

  • Input system tests (tests/test_input_handler.cpp): Good coverage of key bindings
  • ECS integration tests (tests/test_ecs_integration.cpp): Component interaction testing
  • Map generation tests: Multiple test files for map validation

Missing Coverage

  • Input logging functionality: No tests for keystroke logging feature
  • Event system: Drop events and other ECS events lack dedicated tests
  • Error paths: Limited testing of failure scenarios in combat/movement

📝 Test Requirement Compliance

  • CLAUDE.md requirement: "ALL tests must pass before marking any task complete"
  • Status: Unable to verify test execution due to tool permissions
  • Recommendation: Ensure ./build.sh test passes before merge

🔄 Architecture Assessment

ECS Implementation

  • Clean separation: Components are data-only, systems contain logic
  • Proper dependencies: Systems properly inject dependencies via constructor
  • Event system: Good decoupling through event-driven architecture

🏗️ Migration Quality

  • Legacy removal: Old entity/monster/item classes properly removed
  • Bridge elimination: Monster AI and spawn manager bridges cleaned up
  • Consistent patterns: New ECS code follows established patterns

📊 Overall Assessment

🎯 Recommendation: APPROVE with Minor Changes

This PR successfully addresses the critical gameplay issues while introducing valuable debugging capabilities. The code quality is high and the architectural improvements are solid. The few concerns identified are minor and don't block the core functionality.

🔄 Suggested Pre-Merge Actions

  1. Add input filtering to prevent sensitive data logging
  2. Verify all tests pass with ./build.sh test
  3. Consider adding tests for the new input logging feature
  4. Review log file permissions and rotation policies

📈 Future Considerations

  • Performance profiling of entity lookup patterns
  • Comprehensive error handling strategy
  • Security audit of logging subsystem

Great work on this substantial refactoring while maintaining stability! 🚀


- Fixed EntityID to int conversion warnings in event.h
- Fixed parameter shadowing class members in ai_system.h and equipment_system.h
- Fixed size_t to int conversions in fov.cpp and entity_factory.cpp
- Added explicit static_cast for all implicit conversions

All tests pass locally on macOS. These changes fix the CI build failures on Windows.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@claude
Copy link

claude bot commented Sep 16, 2025

Claude finished @MineForeman's task —— View job


Comprehensive Pull Request Review

I've conducted a thorough analysis of this substantial PR covering 100 files with 16,593 additions and 7,736 deletions. Here's my comprehensive feedback on the requested areas:

Review Checklist:

  • Analyze code quality and best practices
  • Identify potential bugs or issues
  • Evaluate performance considerations
  • Assess security concerns
  • Review test coverage
  • Provide constructive feedback and recommendations

🔍 Code Quality & Best Practices

Strengths

  • Excellent ECS Architecture: Clean separation between components, systems, and entities with proper dependency injection
  • Comprehensive Doxygen Documentation: Well-documented classes and methods throughout the ECS system
  • Modern C++ Patterns: Good use of smart pointers, RAII, const correctness, and [[maybe_unused]] attributes
  • Consistent Naming: Clear naming conventions across components and systems
  • Proper Component Design: Components are data-only with systems containing logic

⚠️ Areas for Improvement

  • Include Organization: Mix of global and namespace includes could be standardized (src/ecs/game_world.cpp:6-33)
  • Deep Call Stacks: Some functions like GameWorld::processQueue() could benefit from decomposition
  • Inconsistent Error Handling: Some functions return bool for success/failure without error details

🐛 Potential Bugs & Issues

Critical Fixes Implemented

  1. Movement lockup fix (src/ecs/movement_system.cpp:39): Immediate processing prevents turn freeze ✅
  2. Combat after death (src/ecs/combat_system.cpp:25): Proper dead entity removal ✅
  3. Invisible items fix (src/ecs/game_world.cpp:94): Event system restores position components ✅

⚠️ Potential Issues Identified

  • Input Queue Growth (include/ecs/input_system.h:58): Command queue could grow unbounded without rate limiting
  • Entity Lookup Performance (src/ecs/movement_system.cpp:109): Linear search through entities for each lookup
  • Shared Pointer Safety (src/ecs/combat_system.cpp:220): Non-owning shared_ptr creation with custom deleter could be risky

Performance Considerations

Good Patterns

  • System Priorities (include/ecs/input_system.h:134): Proper system ordering for optimal performance
  • Component Pools: ECS uses efficient component storage patterns
  • Move Semantics: Appropriate use of std::move in entity transfers

⚠️ Performance Concerns

  • Multiple Entity Iterations: Systems perform linear searches through entity vectors each frame
  • String Operations: Heavy string construction in logging paths (src/input_handler.cpp:62)
  • Memory Allocations: Frequent queue operations in movement system could cause allocations

💡 Recommendations

  1. Consider entity indexing/spatial hashing for faster position-based lookups
  2. Implement log level filtering to reduce string operations
  3. Profile frame time to identify actual bottlenecks

🔒 Security Concerns

⚠️ Input Logging Security Risk

  • Comprehensive Keystroke Logging (src/input_handler.cpp:61): ALL keystrokes logged to veyrm_input.log
    • Risk: Could inadvertently capture sensitive data if passwords/secrets entered
    • Recommendation: Add filtering for sensitive contexts or implement log rotation
  • Log File Permissions: No evidence of restricted file permissions for sensitive log files

Good Security Practices

  • Memory Safety: ECS system uses smart pointers appropriately, reducing memory corruption risks
  • Input Validation: JSON parsing appears to have proper structure validation
  • No Injection Risks: File paths are hardcoded, reducing path traversal vulnerabilities

🔧 Security Recommendations

  1. Add log file rotation and permission restrictions
  2. Implement input filtering to prevent logging sensitive data
  3. Consider adding data validation for JSON configuration files

🧪 Test Coverage Assessment

Well-Covered Areas

  • Input System: tests/test_input_handler.cpp covers key bindings and mappings
  • ECS Integration: tests/test_ecs_integration.cpp tests component interactions
  • Core Systems: Multiple test files for map generation, FOV, and data loading

Missing Coverage

  • Input Logging Feature: No tests for the new keystroke logging functionality
  • Event System: Drop events and ECS event handling lack dedicated tests
  • Error Paths: Limited testing of failure scenarios in combat/movement systems
  • Security: No tests for log file permissions or input filtering

📝 Test Compliance

  • CLAUDE.md Requirement: "ALL tests must pass before marking any task complete"
  • Status: Cannot verify test execution due to review-only context
  • Recommendation: Ensure ./build.sh test passes before merge

📊 Overall Assessment

🎯 Recommendation: APPROVE with Minor Security Enhancements

This is an excellent PR that successfully addresses critical gameplay issues while introducing valuable debugging capabilities. The architectural migration to ECS is well-executed with high code quality.

🔄 Pre-Merge Recommendations

  1. Security: Add input filtering to prevent sensitive data logging
  2. Testing: Verify all tests pass with ./build.sh test
  3. Documentation: Consider adding tests for the new input logging feature
  4. Performance: Review entity lookup patterns if performance issues arise

📈 Future Considerations

  • Performance profiling of entity search patterns
  • Comprehensive security audit of logging subsystem
  • Enhanced error handling strategy across systems

Excellent work on this substantial refactoring while maintaining system stability! 🚀


@MineForeman MineForeman merged commit 4f3b9b0 into main Sep 16, 2025
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants