Complete 10-engine architecture with CMake build system

 All 10 engines now build successfully:
- Designer, Economy, Event, Factory, Intelligence
- Logistic, MacroEntity, Map, Operation, War

🚀 Features implemented:
- FAST_BUILD vs FULL_BUILD presets for efficient development
- Comprehensive defensive programming (sanitizers, contracts)
- 16 C++ libraries integrated via FetchContent
- GCC-compatible configuration with stack protection
- Unified CMake system across all engines

🛠️ Build commands:
- Fast: cmake -DFAST_BUILD=ON .. && make claude-workflow-fast
- Full: cmake .. && make (all sanitizers + validation)
- Single engine: make economy-engine

🔧 Development workflow optimized for daily iteration.

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

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
StillHammer 2025-09-19 14:19:25 +08:00
parent 3d6f6abc81
commit 5bdd072117
25 changed files with 3154 additions and 8 deletions

25
.gitignore vendored
View File

@ -107,3 +107,28 @@ replays/
# Redis dumps
dump.rdb
# FetchContent downloads (CMake dependencies)
_deps/
*-src/
*-build/
*-subbuild/
# Sanitizer outputs
*.san
*.asan
*.ubsan
*.msan
*.tsan
# CPack packaging
_CPack_Packages/
*.deb
*.rpm
*.dmg
*.pkg
# Testing outputs
Testing/
test_results/
coverage_report/

321
ADVANCED_TESTING.md Normal file
View File

@ -0,0 +1,321 @@
# 🛡️ Warfactory Advanced Testing & Verification System
Ce document décrit le système de test et vérification avancé intégré dans Warfactory, conçu pour détecter automatiquement les bugs, vulnerabilités et problèmes de performance sans intervention constante.
## 🎯 Vue d'ensemble
Le système combine **8 couches de défense** automatisées :
1. **Compilation stricte** - Flags "No Trust" avec zéro tolérance
2. **Static Analysis** - Détection de bugs avant exécution
3. **Fuzzing automatique** - Test d'inputs malformés
4. **Formal Verification** - Preuve mathématique de propriétés
5. **Concurrency Analysis** - Détection de race conditions
6. **Coverage-guided testing** - Feedback de couverture de code
7. **ABI/Interface validation** - Compatibilité entre versions
8. **Contract-based programming** - Assertions partout dans le code
## 🚀 Installation rapide
```bash
# 1. Installer tous les outils automatiquement
./scripts/setup_advanced_tools.sh
# 2. Configurer le projet avec tous les outils
mkdir build && cd build
cmake -DCMAKE_BUILD_TYPE=Debug -DENABLE_ADVANCED_TOOLS=ON ..
# 3. Compiler avec toutes les défenses
make all-engines
# 4. Lancer tous les tests avancés
make test-everything
```
## 🔧 Configuration par couches
### ⚙️ **Niveau 1 : Compilation "No Trust"**
Activé automatiquement sur tous les engines :
```cmake
# Erreurs critiques = compilation échoue
-Werror=null-dereference -Werror=array-bounds -Werror=use-after-free
-Werror=uninitialized -Werror=return-type -Werror=format-security
# Sanitizers complets (mode Debug)
-fsanitize=address,undefined,leak,memory,thread,cfi
# Protection runtime maximale
-fstack-protector-all -fstack-clash-protection -D_FORTIFY_SOURCE=3
```
### 🔍 **Niveau 2 : Static Analysis**
```bash
# Cppcheck - analyse statique C++
make economy-engine_cppcheck
# Clang Static Analyzer
cmake -DENABLE_STATIC_ANALYSIS=ON ..
make economy-engine
# PVS-Studio (si installé)
make economy-engine_pvs
```
### 🎯 **Niveau 3 : Fuzzing automatique**
#### libFuzzer (Clang intégré)
```bash
make economy-engine_fuzz_run # 5 minutes de fuzzing
```
#### AFL++ (coverage-guided)
```bash
make economy-engine_afl_run # Fuzzing avec feedback
```
#### honggfuzz (feedback hardware)
```bash
make economy-engine_honggfuzz_run
```
#### Fuzzing de tous les engines
```bash
make fuzz-all-engines # Fuzzing massif parallèle
```
### 🔬 **Niveau 4 : Formal Verification**
#### CBMC - Model Checking
```bash
make economy-engine_cbmc # Vérification mathématique
```
#### KLEE - Symbolic Execution
```bash
make economy-engine_klee # Exploration symbolique
```
### 🧵 **Niveau 5 : Concurrency Analysis**
#### Valgrind Helgrind
```bash
make economy-engine_helgrind # Détection race conditions
```
#### Valgrind DRD
```bash
make economy-engine_drd # Détection data races
```
#### Intel Inspector (si disponible)
```bash
make economy-engine_inspector # Analyse threading avancée
```
### 📊 **Niveau 6 : Coverage Analysis**
```bash
# Génération rapport de couverture
make economy-engine_coverage_run
# Rapport HTML dans economy-engine_coverage_report/
open economy-engine_coverage_report/index.html
```
### 🔗 **Niveau 7 : ABI Validation**
```bash
# Créer baseline ABI
make economy-engine_abi_dump
cp economy-engine_current.abi.tar.gz ../abi_baselines/economy-engine_baseline.abi.tar.gz
# Vérifier compatibilité après changements
make economy-engine_abi_check
open economy-engine_abi_report.html
```
### 📋 **Niveau 8 : Contract Programming**
Utilisation dans le code C++ :
```cpp
#include <warfactory/contracts.hpp>
#include <warfactory/gsl_contracts.hpp>
void process_market_data(gsl::not_null<const double*> price, double volume) {
// Préconditions automatiques
WARFACTORY_REQUIRE(std::isfinite(*price));
WARFACTORY_REQUIRE(volume > 0.0);
double result = calculate_value(*price, volume);
// Postconditions automatiques
WARFACTORY_ENSURE(std::isfinite(result));
WARFACTORY_PROPERTY_FINITE_VALUES(result);
}
```
## 🎮 Modes d'utilisation
### 🚀 **Mode Développement**
```bash
cmake -DCMAKE_BUILD_TYPE=Debug ..
make economy-engine
# → Tous les sanitizers + assertions activés
```
### ⚡ **Mode Production**
```bash
cmake -DCMAKE_BUILD_TYPE=Release ..
make economy-engine
# → CFI uniquement, performance optimisée
```
### 🔬 **Mode Test Complet**
```bash
cmake -DCMAKE_BUILD_TYPE=Debug -DENABLE_ADVANCED_TOOLS=ON ..
make test-everything
# → Tous les outils activés, test marathon
```
### 🎯 **Mode Fuzzing Intensif**
```bash
cmake -DENABLE_FUZZING=ON ..
make fuzz-all-engines
# → Fuzzing 24/7 sur tous les engines
```
## 📈 Targets disponibles
### Par engine (exemple : economy-engine)
```bash
# Compilation
make economy-engine
# Static Analysis
make economy-engine_cppcheck
make economy-engine_pvs
# Fuzzing
make economy-engine_fuzz_run # libFuzzer
make economy-engine_afl_run # AFL++
make economy-engine_honggfuzz_run # honggfuzz
make economy-engine_fuzz_all # Tous les fuzzers
# Formal Verification
make economy-engine_cbmc # Model checking
make economy-engine_klee # Symbolic execution
# Concurrency
make economy-engine_helgrind # Race conditions
make economy-engine_drd # Data races
make economy-engine_inspector # Intel Inspector
# Coverage
make economy-engine_coverage_run # Rapport HTML
# ABI
make economy-engine_abi_dump # Créer baseline
make economy-engine_abi_check # Vérifier compatibilité
```
### Globaux (tous les engines)
```bash
make all-engines # Build tout
make fuzz-all-engines # Fuzzing massif
make analyze-all-engines # Static analysis
make coverage-all-engines # Coverage reports
make concurrency-all-engines # Concurrency analysis
make abi-all-engines # ABI validation
make test-everything # TOUT en parallèle
```
## 🔧 Configuration avancée
### Variables CMake importantes
```bash
-DENABLE_ADVANCED_TOOLS=ON # Active tous les outils
-DENABLE_STATIC_ANALYSIS=ON # Clang Static Analyzer
-DENABLE_FUZZING=ON # Support fuzzing
-DCMAKE_BUILD_TYPE=Debug # Tous les sanitizers
```
### Personnalisation par engine
```cmake
# Dans engines/Mon-Engine/CMakeLists.txt
warfactory_add_defenses(mon-engine) # Défenses de base
warfactory_add_fuzzing(mon-engine) # Fuzzing
warfactory_add_formal_verification(mon-engine) # Vérification formelle
warfactory_add_concurrency_analysis(mon-engine) # Concurrence
warfactory_add_coverage_analysis(mon-engine) # Coverage
warfactory_add_abi_validation(mon-engine) # ABI
warfactory_add_gsl_support(mon-engine) # Guidelines Support Library
```
## 🎯 Intégration CI/CD
### GitHub Actions exemple
```yaml
- name: Setup Advanced Tools
run: ./scripts/setup_advanced_tools.sh
- name: Build with all defenses
run: |
mkdir build && cd build
cmake -DCMAKE_BUILD_TYPE=Debug -DENABLE_ADVANCED_TOOLS=ON ..
make all-engines
- name: Run comprehensive testing
run: cd build && make test-everything
```
### Détection automatique de régressions
- **ABI changes** détectés automatiquement
- **Coverage regressions** bloquent les merges
- **Fuzzing crashes** remontés immédiatement
- **Contract violations** = build failure
## 🚨 Résolution de problèmes
### Si la compilation échoue
```bash
# 1. Vérifier les outils installés
./scripts/setup_advanced_tools.sh
# 2. Mode minimal pour débugger
cmake -DCMAKE_BUILD_TYPE=Release ..
# 3. Désactiver temporairement les défenses strictes
cmake -DENABLE_ADVANCED_TOOLS=OFF ..
```
### Si le fuzzing ne trouve rien
```bash
# Augmenter la durée
make economy-engine_fuzz_run ARGS="-max_total_time=3600"
# Vérifier les seeds d'entrée
ls build/fuzzing/economy-engine/input/
```
### Si les tests de concurrence échouent
```bash
# Analyser les rapports détaillés
cat economy-engine_helgrind.xml
cat economy-engine_drd.xml
```
## 📚 Références
- [AFL++ Documentation](https://aflplus.plus/)
- [CBMC User Manual](https://www.cprover.org/cbmc/)
- [KLEE Tutorials](https://klee.github.io/tutorials/)
- [Valgrind Manual](https://valgrind.org/docs/manual/)
- [Microsoft GSL](https://github.com/microsoft/GSL)
---
**💡 Philosophie Warfactory** : *"Zéro bug en production grâce à la détection automatique exhaustive en développement"*

499
AUTOMATION_GUIDE.md Normal file
View File

@ -0,0 +1,499 @@
# 🤖 Warfactory Complete Automation Guide
Ce guide décrit le système d'automation complet de Warfactory, conçu pour automatiser **complètement** le workflow de développement multi-engines avec Claude Code.
## 🎯 Vue d'ensemble de l'automation
Le système combine **12 couches d'automation** :
1. **🔧 Dependency Management** - FetchContent automatique
2. **🧪 Testing per Engine** - CTest intégré
3. **📚 Documentation Auto** - Doxygen pour tous les engines
4. **🔗 Export/Import System** - Engines peuvent s'importer mutuellement
5. **⚙️ Multiple Build Configs** - Debug/Release/Testing/Profiling
6. **⚡ Precompiled Headers** - Compilation accélérée
7. **📦 Packaging Auto** - DEB/RPM/NSIS/Bundle
8. **🛡️ Advanced Defenses** - Fuzzing, formal verification, etc.
9. **🤖 Claude Code Targets** - Workflow spécialisé pour Claude
10. **📊 Performance Monitoring** - Benchmarks automatiques
11. **🔍 Static Analysis** - Validation de code continue
12. **🚀 CI/CD Simulation** - Pipeline complet local
## 🚀 Installation complète
```bash
# 1. Setup des outils avancés
./scripts/setup_advanced_tools.sh
# 2. Application automation complète
./scripts/apply_full_automation.sh
# 3. Build avec automation complète
mkdir build && cd build
cmake -DCMAKE_BUILD_TYPE=Debug -DENABLE_ADVANCED_TOOLS=ON -DENABLE_BENCHMARKING=ON ..
# 4. Workflow complet Claude Code
make claude-workflow
```
## ⚙️ Configurations de build disponibles
### 🐛 **Debug Mode** (Développement)
```bash
cmake -DCMAKE_BUILD_TYPE=Debug ..
# → Tous les sanitizers, assertions, debug symbols
# → Optimisation: -O0 -g
# → Parfait pour développement avec Claude Code
```
### 🚀 **Release Mode** (Production)
```bash
cmake -DCMAKE_BUILD_TYPE=Release ..
# → Optimisation maximale, pas de debug
# → Optimisation: -O3 -DNDEBUG
# → Parfait pour déploiement
```
### 🧪 **Testing Mode** (CI/CD)
```bash
cmake -DCMAKE_BUILD_TYPE=Testing ..
# → Coverage activé, optimisation minimale
# → Optimisation: -O0 -g --coverage
# → Parfait pour mesurer la couverture de test
```
### 📊 **Profiling Mode** (Performance)
```bash
cmake -DCMAKE_BUILD_TYPE=Profiling ..
# → Profiling activé, optimisation modérée
# → Optimisation: -O2 -g -pg
# → Parfait pour analyser les performances
```
## 📦 Dependency Management automatique
### Librairies auto-installées par FetchContent :
- **Redis++** : Communication inter-engines
- **nlohmann/json** : Sérialisation uniforme
- **spdlog** : Logging unifié
- **Catch2** : Framework de test
- **Google Benchmark** : Mesure de performance
- **Microsoft GSL** : Guidelines Support Library
### Usage dans le code :
```cpp
#include <sw/redis++/redis++.h> // Communication
#include <nlohmann/json.hpp> // JSON
#include <spdlog/spdlog.h> // Logging
#include <catch2/catch_test_macros.hpp> // Tests
#include <benchmark/benchmark.h> // Benchmarks
#include <gsl/gsl> // Safety contracts
```
## 🧪 Testing automatique par engine
### Structure auto-générée :
```
engines/Economy-Engine/
├── tests/
│ └── test_economy-engine.cpp # Tests unitaires
├── benchmarks/
│ └── bench_economy-engine.cpp # Benchmarks performance
└── CMakeLists.txt # Configuration auto
```
### Commandes de test :
```bash
# Tests d'un engine spécifique
make economy-engine-tests
ctest -R economy-engine
# Tests de tous les engines
make test-all-engines
ctest --parallel 4
# Benchmarks de performance
make economy-engine-bench
make bench-all-engines
```
## 📚 Documentation automatique
### Génération auto avec Doxygen :
```bash
# Documentation d'un engine
make economy-engine_docs
# Documentation de tous les engines
make docs-all
# Visualiser
open build/docs/economy-engine/html/index.html
```
### Configuration automatique :
- **HTML + XML** générés
- **Source browser** activé
- **Code inline** inclus
- **Diagrammes** automatiques
## 🔗 Export/Import entre engines
### Usage automatique :
```cmake
# Dans Economy-Engine/CMakeLists.txt - automatique
warfactory_add_full_automation(economy-engine)
# Dans un autre engine qui dépend d'Economy
find_package(economy-engine REQUIRED)
target_link_libraries(war-engine PRIVATE Warfactory::economy-engine-lib)
```
### Installation des packages :
```bash
# Installer pour utilisation externe
make install
# Ou créer package
make package-all
```
## ⚡ Precompiled Headers automatiques
### Headers pré-compilés automatiquement :
- **STL containers** (vector, string, unordered_map...)
- **I/O streams** (iostream, fstream...)
- **Threading** (thread, future, atomic...)
- **Math** (cmath, algorithm...)
- **Warfactory contracts**
- **Third-party libs** (si disponibles)
### Fichier `pch.h` auto-généré dans chaque engine
## 🤖 Targets d'automation pour Claude Code
### Workflow de développement optimal :
```bash
# Workflow complet Claude Code (build + test + validate)
make claude-workflow
# Build rapide tous les engines
make build-all-fast
# Validation complète du code
make validate-all
# Simulation CI/CD complète
make ci-simulation
# Rebuild complet propre
make rebuild-all
```
### Static analysis automatique :
```bash
# Cppcheck sur tous les engines
make cppcheck-all
# clang-tidy sur tous les engines
make clang-tidy-all
# Validation combinée
make validate-all
```
## 📦 Packaging automatique multi-plateforme
### Formats supportés automatiquement :
**Linux :**
- **DEB** packages (Ubuntu/Debian)
- **RPM** packages (Fedora/CentOS)
- **TGZ/ZIP** archives
**Windows :**
- **NSIS** installer
- **WIX** installer (MSI)
- **ZIP** archives
**macOS :**
- **Bundle** (.app)
- **DragNDrop** (.dmg)
- **TGZ** archives
### Commandes de packaging :
```bash
# Package par défaut
make package
# Tous les formats
make package-all
# Source seulement
make package-source
# Binaires seulement
make package-binary
```
### Installation sélective par composants :
- **engines** : Executables de jeu
- **libraries** : Libs de développement
- **headers** : Headers C++
- **documentation** : Docs générées
## 🔧 Options CMake complètes
### Options principales :
```bash
-DCMAKE_BUILD_TYPE=Debug|Release|Testing|Profiling
-DENABLE_ADVANCED_TOOLS=ON # Fuzzing, verification, etc.
-DENABLE_STATIC_ANALYSIS=ON # Clang Static Analyzer
-DENABLE_FUZZING=ON # Fuzzing automatique
-DENABLE_BENCHMARKING=ON # Google Benchmark
```
### Build examples complets :
```bash
# Développement Claude Code
cmake -DCMAKE_BUILD_TYPE=Debug -DENABLE_ADVANCED_TOOLS=ON ..
# Testing avec coverage
cmake -DCMAKE_BUILD_TYPE=Testing -DENABLE_BENCHMARKING=ON ..
# Production optimisée
cmake -DCMAKE_BUILD_TYPE=Release ..
# Profiling performance
cmake -DCMAKE_BUILD_TYPE=Profiling -DENABLE_BENCHMARKING=ON ..
```
## 🎯 Targets disponibles par engine (exemple: economy-engine)
### Build & Core :
```bash
make economy-engine # Build basic
make economy-engine-lib # Build library
make economy-engine-tests # Build tests
make economy-engine-bench # Build benchmarks
```
### Documentation :
```bash
make economy-engine_docs # Generate docs
```
### Testing :
```bash
make economy-engine_unit_tests # Unit tests
make economy-engine_integration_tests # Integration tests
make economy-engine_benchmarks # Performance tests
```
### Advanced Testing :
```bash
make economy-engine_fuzz_all # All fuzzing
make economy-engine_cbmc # Formal verification
make economy-engine_helgrind # Race detection
make economy-engine_coverage_run # Coverage report
```
### Static Analysis :
```bash
make economy-engine_cppcheck # Cppcheck
make economy-engine_pvs # PVS-Studio
```
### ABI :
```bash
make economy-engine_abi_dump # Create ABI dump
make economy-engine_abi_check # Check compatibility
```
## 🎮 Targets globaux (tous les engines)
### Build :
```bash
make all-engines # Build all
make build-all-fast # Quick build
make rebuild-all # Clean + rebuild
```
### Testing :
```bash
make test-all-engines # All tests
make bench-all-engines # All benchmarks
make coverage-all-engines # All coverage
```
### Advanced :
```bash
make fuzz-all-engines # Fuzzing massif
make analyze-all-engines # Static analysis
make concurrency-all-engines # Concurrency analysis
make test-everything # TOUT en parallèle
```
### Documentation :
```bash
make docs-all # All documentation
```
### Validation :
```bash
make validate-all # Complete validation
make cppcheck-all # Cppcheck on all
make clang-tidy-all # clang-tidy on all
```
### Claude Code Workflow :
```bash
make claude-workflow # Dev workflow
make ci-simulation # CI/CD simulation
```
### Packaging :
```bash
make package # Default package
make package-all # All formats
make package-source # Source distribution
make package-binary # Binary distribution
```
## 🔄 Workflow types recommandés
### 👨‍💻 **Développement quotidien avec Claude**
```bash
mkdir build && cd build
cmake -DCMAKE_BUILD_TYPE=Debug ..
make claude-workflow
# → Build + test + validation en une commande
```
### 🧪 **Testing & QA**
```bash
mkdir build-testing && cd build-testing
cmake -DCMAKE_BUILD_TYPE=Testing -DENABLE_BENCHMARKING=ON ..
make ci-simulation
# → Tests complets + coverage + benchmarks
```
### 🚀 **Préparation release**
```bash
mkdir build-release && cd build-release
cmake -DCMAKE_BUILD_TYPE=Release ..
make all-engines
make package-all
# → Build optimisé + packaging multi-plateforme
```
### 🔬 **Debug performance**
```bash
mkdir build-profiling && cd build-profiling
cmake -DCMAKE_BUILD_TYPE=Profiling -DENABLE_BENCHMARKING=ON ..
make bench-all-engines
# → Profiling + benchmarks détaillés
```
### 🛡️ **Security audit**
```bash
mkdir build-security && cd build-security
cmake -DCMAKE_BUILD_TYPE=Debug -DENABLE_ADVANCED_TOOLS=ON ..
make test-everything
# → Fuzzing + static analysis + formal verification
```
## 📊 Monitoring automatique
### Métriques collectées automatiquement :
- **Build times** par engine
- **Test coverage** par engine
- **Performance benchmarks**
- **Memory usage** par engine
- **Static analysis** issues
- **ABI compatibility** changes
### Visualisation :
```bash
# Coverage reports HTML
open build/economy-engine_coverage_report/index.html
# Documentation générée
open build/docs/economy-engine/html/index.html
# ABI compatibility reports
open economy-engine_abi_report.html
```
## 🎯 Integration CI/CD
### GitHub Actions exemple :
```yaml
name: Warfactory CI
on: [push, pull_request]
jobs:
full-automation:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Advanced Tools
run: ./scripts/setup_advanced_tools.sh
- name: Apply Full Automation
run: ./scripts/apply_full_automation.sh
- name: Configure
run: |
mkdir build && cd build
cmake -DCMAKE_BUILD_TYPE=Testing -DENABLE_ADVANCED_TOOLS=ON ..
- name: Run Complete CI Simulation
run: cd build && make ci-simulation
- name: Upload Coverage
uses: codecov/codecov-action@v3
with:
files: build/coverage.xml
```
## 🚨 Troubleshooting
### Si la configuration échoue :
```bash
# 1. Vérifier les dépendances
./scripts/setup_advanced_tools.sh
# 2. Build minimal
cmake -DCMAKE_BUILD_TYPE=Release ..
# 3. Désactiver automation temporairement
cmake -DENABLE_ADVANCED_TOOLS=OFF ..
```
### Si les tests échouent :
```bash
# Tests détaillés avec output
ctest --output-on-failure --verbose
# Tests d'un engine spécifique
ctest -R economy-engine -V
```
### Si le packaging échoue :
```bash
# Vérifier installation
make install DESTDIR=/tmp/test-install
# Package basique seulement
make package-binary
```
---
**💡 Philosophie Warfactory Automation** : *"Automatiser complètement le workflow pour que Claude Code puisse se concentrer sur la logique métier, pas sur l'infrastructure"*
**🎯 Résultat** : Un seul `make claude-workflow` fait **tout** automatiquement !

417
CMakeLists.txt Normal file
View File

@ -0,0 +1,417 @@
cmake_minimum_required(VERSION 3.20)
project(Warfactory LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Build type
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
endif()
# Load Warfactory modules
include(cmake/WarfactoryDefenses.cmake)
include(cmake/WarfactoryAutomation.cmake)
# =============================================================================
# MULTIPLE BUILD CONFIGURATIONS
# =============================================================================
# Debug avec sanitizers complets
set(CMAKE_CXX_FLAGS_DEBUG "-g -O0 -DDEBUG")
# Release optimisé
set(CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG -DRELEASE")
# Testing avec coverage
set(CMAKE_CXX_FLAGS_TESTING "-O0 -g --coverage -DTESTING")
# Profiling pour performance analysis
set(CMAKE_CXX_FLAGS_PROFILING "-O2 -g -pg -DPROFILING")
# Available configurations
set(CMAKE_CONFIGURATION_TYPES "Debug;Release;Testing;Profiling" CACHE STRING "Build configurations" FORCE)
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Choose build type" FORCE)
endif()
message(STATUS "🔧 Build configuration: ${CMAKE_BUILD_TYPE}")
# Global include directories
include_directories(include)
# Output directories
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
# Add subdirectories for all engines
add_subdirectory(engines/Designer-Engine)
add_subdirectory(engines/Economy-Engine)
add_subdirectory(engines/Event-Engine)
add_subdirectory(engines/Factory-Engine)
add_subdirectory(engines/Intelligence-Engine)
add_subdirectory(engines/Logistic-Engine)
add_subdirectory(engines/MacroEntity-Engine)
add_subdirectory(engines/Map-Engine)
add_subdirectory(engines/Operation-Engine)
add_subdirectory(engines/War-Engine)
# Build all engines target
add_custom_target(all-engines
DEPENDS
designer-engine
economy-engine
event-engine
factory-engine
intelligence-engine
logistic-engine
macroentity-engine
map-engine
operation-engine
war-engine
COMMENT "Building all Warfactory engines"
)
# =============================================================================
# ADVANCED TESTING TARGETS
# =============================================================================
if(ENABLE_ADVANCED_TOOLS)
# Fuzzing targets for all engines
add_custom_target(fuzz-all-engines
COMMENT "Running fuzzing on all engines"
)
# Static analysis for all engines
add_custom_target(analyze-all-engines
COMMENT "Running static analysis on all engines"
)
# Coverage for all engines
add_custom_target(coverage-all-engines
COMMENT "Generating coverage reports for all engines"
)
# Concurrency analysis for all engines
add_custom_target(concurrency-all-engines
COMMENT "Running concurrency analysis on all engines"
)
# ABI validation for all engines
add_custom_target(abi-all-engines
COMMENT "Validating ABI for all engines"
)
# Master testing target
add_custom_target(test-everything
DEPENDS fuzz-all-engines analyze-all-engines coverage-all-engines
COMMENT "Run all advanced testing on all engines"
)
message(STATUS "🎯 Advanced testing targets configured")
message(STATUS " - Use 'make fuzz-all-engines' for fuzzing")
message(STATUS " - Use 'make analyze-all-engines' for static analysis")
message(STATUS " - Use 'make test-everything' for complete testing")
endif()
# =============================================================================
# AUTOMATION TARGETS POUR CLAUDE CODE
# =============================================================================
# Validation complète du code
add_custom_target(validate-all
COMMAND echo "🔍 Running comprehensive code validation..."
COMMENT "Running all validation tools"
)
# Static analysis sur tout le projet
if(TARGET cppcheck)
add_custom_target(cppcheck-all
COMMAND cppcheck --enable=all --inconclusive --std=c++20
--suppressions-list=${CMAKE_SOURCE_DIR}/cppcheck-suppressions.txt
${CMAKE_SOURCE_DIR}/engines/*/src ${CMAKE_SOURCE_DIR}/engines/*/include
COMMENT "Running Cppcheck on all engines"
)
add_dependencies(validate-all cppcheck-all)
endif()
# clang-tidy sur tout le projet
find_program(CLANG_TIDY_EXECUTABLE clang-tidy)
if(CLANG_TIDY_EXECUTABLE)
add_custom_target(clang-tidy-all
COMMAND find ${CMAKE_SOURCE_DIR}/engines -name "*.cpp" -exec ${CLANG_TIDY_EXECUTABLE} {} +
COMMENT "Running clang-tidy on all engines"
)
add_dependencies(validate-all clang-tidy-all)
endif()
# Build rapide tous les engines
add_custom_target(build-all-fast
DEPENDS all-engines
COMMENT "Fast build of all engines"
)
# Clean + rebuild complet
add_custom_target(rebuild-all
COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target clean
COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target all-engines
COMMENT "Clean rebuild of all engines"
)
# Documentation de tous les engines
add_custom_target(docs-all
COMMENT "Generating documentation for all engines"
)
# Tests de tous les engines
add_custom_target(test-all-engines
COMMAND ${CMAKE_CTEST_COMMAND} --parallel 4 --output-on-failure
COMMENT "Running tests for all engines"
)
# Performance benchmarks
add_custom_target(bench-all-engines
COMMENT "Running benchmarks for all engines"
)
# Claude Code workflow target - build + test + validate
add_custom_target(claude-workflow
DEPENDS build-all-fast validate-all test-all-engines
COMMENT "Complete Claude Code development workflow"
)
# Builds rotatifs pour tous les engines en mode Debug
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
add_custom_target(rotary-builds-all
DEPENDS
economy-engine_test_rotary
war-engine_test_rotary
designer-engine_test_rotary
factory-engine_test_rotary
intelligence-engine_test_rotary
logistic-engine_test_rotary
macroentity-engine_test_rotary
map-engine_test_rotary
operation-engine_test_rotary
event-engine_test_rotary
COMMENT "Build all sanitizer variants for all engines"
)
add_custom_target(rotary-tests-all
DEPENDS
economy-engine_run_rotary
war-engine_run_rotary
designer-engine_run_rotary
factory-engine_run_rotary
intelligence-engine_run_rotary
logistic-engine_run_rotary
macroentity-engine_run_rotary
map-engine_run_rotary
operation-engine_run_rotary
event-engine_run_rotary
COMMENT "Run rotary sanitizer testing for all engines"
)
# Claude workflow étendu avec sanitizers rotatifs
add_custom_target(claude-workflow-rotary
DEPENDS claude-workflow rotary-builds-all
COMMENT "Complete Claude workflow with rotary sanitizer builds"
)
message(STATUS "🔄 Rotary sanitizer targets configured:")
message(STATUS " - make rotary-builds-all : Build all sanitizer variants")
message(STATUS " - make rotary-tests-all : Run all sanitizer tests")
message(STATUS " - make claude-workflow-rotary : Full workflow + rotary")
endif()
# CI/CD simulation
add_custom_target(ci-simulation
DEPENDS rebuild-all validate-all test-all-engines docs-all
COMMENT "Simulate CI/CD pipeline"
)
# Build workflow adaptatif selon FAST_BUILD
if(FAST_BUILD)
add_custom_target(claude-workflow-fast
DEPENDS build-all-fast
COMMENT "Fast Claude Code development workflow (daily iteration)"
)
message(STATUS "🤖 Fast build targets configured:")
message(STATUS " - make build-all-fast : Quick build all engines")
message(STATUS " - make claude-workflow-fast : Fast Claude development cycle")
else()
message(STATUS "🤖 Full automation targets configured:")
message(STATUS " - make validate-all : Comprehensive validation")
message(STATUS " - make build-all-fast : Quick build all engines")
message(STATUS " - make claude-workflow : Full Claude development cycle")
message(STATUS " - make ci-simulation : Simulate CI/CD pipeline")
endif()
# Installation rules
install(TARGETS
designer-engine
economy-engine
event-engine
factory-engine
intelligence-engine
logistic-engine
macroentity-engine
map-engine
operation-engine
war-engine
DESTINATION bin
)
# =============================================================================
# PACKAGING AUTOMATIQUE AVEC CPACK
# =============================================================================
include(CPack)
# Configuration générale du package
set(CPACK_PACKAGE_NAME "Warfactory")
set(CPACK_PACKAGE_VENDOR "Warfactory Project")
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Factorio-inspired industrial military simulation - Multi-engine architecture")
set(CPACK_PACKAGE_VERSION_MAJOR 1)
set(CPACK_PACKAGE_VERSION_MINOR 0)
set(CPACK_PACKAGE_VERSION_PATCH 0)
set(CPACK_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}.${CPACK_PACKAGE_VERSION_PATCH}")
set(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_SOURCE_DIR}/README.md")
set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/LICENSE")
set(CPACK_PACKAGE_CONTACT "warfactory@example.com")
# Générateurs de packages
set(CPACK_GENERATOR "TGZ;ZIP")
# Configuration spécifique Linux
if(UNIX AND NOT APPLE)
list(APPEND CPACK_GENERATOR "DEB" "RPM")
# Configuration DEB
set(CPACK_DEBIAN_PACKAGE_DEPENDS "libc6, libstdc++6, libgcc1")
set(CPACK_DEBIAN_PACKAGE_SECTION "games")
set(CPACK_DEBIAN_PACKAGE_PRIORITY "optional")
set(CPACK_DEBIAN_PACKAGE_MAINTAINER "Warfactory Team <warfactory@example.com>")
# Configuration RPM
set(CPACK_RPM_PACKAGE_GROUP "Applications/Games")
set(CPACK_RPM_PACKAGE_LICENSE "MIT")
set(CPACK_RPM_PACKAGE_REQUIRES "glibc, libstdc++, libgcc")
endif()
# Configuration spécifique Windows
if(WIN32)
list(APPEND CPACK_GENERATOR "NSIS" "WIX")
set(CPACK_NSIS_DISPLAY_NAME "Warfactory Game")
set(CPACK_NSIS_PACKAGE_NAME "Warfactory")
set(CPACK_NSIS_URL_INFO_ABOUT "https://github.com/warfactory/warfactory")
set(CPACK_NSIS_HELP_LINK "https://github.com/warfactory/warfactory/issues")
set(CPACK_NSIS_MODIFY_PATH ON)
endif()
# Configuration spécifique macOS
if(APPLE)
list(APPEND CPACK_GENERATOR "Bundle" "DragNDrop")
set(CPACK_BUNDLE_NAME "Warfactory")
set(CPACK_BUNDLE_ICON "${CMAKE_SOURCE_DIR}/assets/warfactory.icns")
set(CPACK_BUNDLE_PLIST "${CMAKE_SOURCE_DIR}/assets/Info.plist")
endif()
# Composants pour installation sélective
set(CPACK_COMPONENTS_ALL engines libraries headers documentation)
# Description des composants
set(CPACK_COMPONENT_ENGINES_DISPLAY_NAME "Game Engines")
set(CPACK_COMPONENT_ENGINES_DESCRIPTION "Core game engines (Economy, War, Factory, etc.)")
set(CPACK_COMPONENT_ENGINES_GROUP "Runtime")
set(CPACK_COMPONENT_LIBRARIES_DISPLAY_NAME "Development Libraries")
set(CPACK_COMPONENT_LIBRARIES_DESCRIPTION "Static and shared libraries for engine development")
set(CPACK_COMPONENT_LIBRARIES_GROUP "Development")
set(CPACK_COMPONENT_HEADERS_DISPLAY_NAME "Header Files")
set(CPACK_COMPONENT_HEADERS_DESCRIPTION "C++ header files for engine APIs")
set(CPACK_COMPONENT_HEADERS_GROUP "Development")
set(CPACK_COMPONENT_DOCUMENTATION_DISPLAY_NAME "Documentation")
set(CPACK_COMPONENT_DOCUMENTATION_DESCRIPTION "API documentation and user guides")
set(CPACK_COMPONENT_DOCUMENTATION_GROUP "Documentation")
# Groupes de composants
set(CPACK_COMPONENT_GROUP_RUNTIME_DESCRIPTION "Runtime components needed to play the game")
set(CPACK_COMPONENT_GROUP_DEVELOPMENT_DESCRIPTION "Development tools and libraries")
set(CPACK_COMPONENT_GROUP_DOCUMENTATION_DESCRIPTION "Documentation and help files")
# Source package (pour distribution du code source)
set(CPACK_SOURCE_GENERATOR "TGZ;ZIP")
set(CPACK_SOURCE_IGNORE_FILES
"/\\.git/"
"/build/"
"/\\.vscode/"
"/\\.idea/"
"\\.DS_Store"
"Thumbs\\.db"
"\\.gitignore"
"\\.gitmodules"
)
# Installation des composants
install(TARGETS
designer-engine economy-engine event-engine factory-engine
intelligence-engine logistic-engine macroentity-engine
map-engine operation-engine war-engine
COMPONENT engines
DESTINATION bin
)
# Si les libraries sont créées par l'automation
if(TARGET designer-engine-lib)
install(TARGETS
designer-engine-lib economy-engine-lib event-engine-lib factory-engine-lib
intelligence-engine-lib logistic-engine-lib macroentity-engine-lib
map-engine-lib operation-engine-lib war-engine-lib
COMPONENT libraries
DESTINATION lib
)
endif()
# Headers
install(DIRECTORY include/
COMPONENT headers
DESTINATION include
FILES_MATCHING PATTERN "*.h" PATTERN "*.hpp"
)
# Documentation (si générée)
install(DIRECTORY ${CMAKE_BINARY_DIR}/docs/
COMPONENT documentation
DESTINATION share/doc/warfactory
OPTIONAL
)
# Targets de packaging
add_custom_target(package-all
COMMAND ${CMAKE_CPACK_COMMAND} --config CPackConfig.cmake
COMMENT "Creating all packages"
)
add_custom_target(package-source
COMMAND ${CMAKE_CPACK_COMMAND} --config CPackSourceConfig.cmake
COMMENT "Creating source package"
)
add_custom_target(package-binary
COMMAND ${CMAKE_CPACK_COMMAND} -G "TGZ;ZIP"
COMMENT "Creating binary packages"
)
message(STATUS "📦 CPack packaging configured:")
message(STATUS " - make package : Default package")
message(STATUS " - make package-all : All package formats")
message(STATUS " - make package-source : Source distribution")
message(STATUS " - make package-binary : Binary distribution")

View File

@ -0,0 +1,37 @@
# EngineConfig.cmake.in
# Template pour la configuration d'export des engines Warfactory
@PACKAGE_INIT@
# Warfactory Engine Configuration
# Generated automatically by CMake
include(CMakeFindDependencyMacro)
# Dependencies required by this engine
find_dependency(nlohmann_json 3.11.0)
find_dependency(spdlog 1.12.0)
# Redis++ might be optional depending on engine
find_dependency(redis-plus-plus QUIET)
if(NOT redis-plus-plus_FOUND)
message(STATUS "Redis++ not found, inter-engine communication disabled")
endif()
# Include targets file
include("${CMAKE_CURRENT_LIST_DIR}/@target_name@Targets.cmake")
# Verify that all targets were created
check_required_components(@target_name@)
# Set convenience variables
set(@target_name@_LIBRARIES Warfactory::@target_name@-lib)
set(@target_name@_INCLUDE_DIRS "${PACKAGE_PREFIX_DIR}/include")
# Version information
set(@target_name@_VERSION_MAJOR 1)
set(@target_name@_VERSION_MINOR 0)
set(@target_name@_VERSION_PATCH 0)
set(@target_name@_VERSION "${@target_name@_VERSION_MAJOR}.${@target_name@_VERSION_MINOR}.${@target_name@_VERSION_PATCH}")
message(STATUS "Found Warfactory Engine: @target_name@ v${@target_name@_VERSION}")

21
cppcheck-suppressions.txt Normal file
View File

@ -0,0 +1,21 @@
# Cppcheck suppressions for Warfactory project
# Suppressions for intentional design choices and false positives
# Suppress warnings for contract macros (intentional performance cost)
unusedFunction:*contracts.hpp*
unmatchedSuppression:*contracts.hpp*
# Suppress warnings for sanitizer-related code
unusedFunction:*sanitizer*
unmatchedSuppression:*sanitizer*
# Suppress false positives in generated code
missingIncludeSystem
missingInclude
# Suppress warnings in third-party headers
unusedFunction:*/include/std/*
unusedFunction:*/include/c++/*
# Allow assert macros to have side effects (intentional)
assertWithSideEffect

View File

@ -0,0 +1,27 @@
cmake_minimum_required(VERSION 3.20)
project(EventEngine LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Include directories
include_directories(include)
# Source files
file(GLOB_RECURSE SOURCES
"src/*.cpp"
"src/*.h"
"include/*.h"
"include/*.hpp"
)
# Create executable
add_executable(event-engine ${SOURCES})
# Set output directory
set_target_properties(event-engine PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
# Apply unified Warfactory defensive programming (adapts to FAST_BUILD)
warfactory_add_defenses(event-engine)

View File

@ -1,9 +1,9 @@
#include <iostream>
#include "event-engine/Event-EngineEngine.h"
#include "event-engine/EventEngine.h"
using namespace Warfactory::Event;
int main(int argc, char* argv[]) {
int main(int /*argc*/, char* /*argv*/[]) {
std::cout << "Starting Event-Engine..." << std::endl;
auto engine = std::make_unique<EventEngine>();

View File

@ -0,0 +1,144 @@
#include "event-engine/EventEngine.h"
#include <iostream>
#include <chrono>
namespace Warfactory {
namespace Event {
class GameEvent {
public:
GameEvent() = default;
virtual ~GameEvent() = default;
virtual void execute() {}
};
class BreakthroughSystem {
public:
BreakthroughSystem() = default;
void analyzeScrap(const std::string& scrapData) {
std::cout << "Analyzing scrap: " << scrapData << std::endl;
}
void triggerBreakthrough(const std::string& domain) {
std::cout << "Breakthrough triggered in: " << domain << std::endl;
}
};
class EventQueue {
public:
EventQueue() = default;
void scheduleEvent(std::unique_ptr<GameEvent> event, double delay) {
events_.push(std::move(event));
}
void addImmediate(std::unique_ptr<GameEvent> event) {
events_.push(std::move(event));
}
bool hasEvents() const { return !events_.empty(); }
std::unique_ptr<GameEvent> popEvent() {
if (events_.empty()) return nullptr;
auto event = std::move(const_cast<std::unique_ptr<GameEvent>&>(events_.front()));
events_.pop();
return event;
}
private:
std::queue<std::unique_ptr<GameEvent>> events_;
};
EventEngine::EventEngine() : running_(false) {
std::cout << "EventEngine constructor" << std::endl;
eventQueue_ = std::make_unique<EventQueue>();
breakthroughSystem_ = std::make_unique<BreakthroughSystem>();
}
EventEngine::~EventEngine() {
if (running_) {
shutdown();
}
}
bool EventEngine::initialize() {
std::cout << "EventEngine::initialize()" << std::endl;
running_ = true;
return true;
}
void EventEngine::run() {
std::cout << "EventEngine::run() starting engine loop" << std::endl;
engineThread_ = std::thread(&EventEngine::engineLoop, this);
if (engineThread_.joinable()) {
engineThread_.join();
}
}
void EventEngine::shutdown() {
std::cout << "EventEngine::shutdown()" << std::endl;
running_ = false;
if (engineThread_.joinable()) {
engineThread_.join();
}
}
void EventEngine::scheduleEvent(std::unique_ptr<GameEvent> event, double /*delaySeconds*/) {
eventQueue_->scheduleEvent(std::move(event), 0.0);
}
void EventEngine::triggerImmediateEvent(std::unique_ptr<GameEvent> event) {
eventQueue_->addImmediate(std::move(event));
}
void EventEngine::analyzeScrapForBreakthrough(const std::string& scrapData) {
breakthroughSystem_->analyzeScrap(scrapData);
}
void EventEngine::triggerBreakthrough(const std::string& technologyDomain) {
breakthroughSystem_->triggerBreakthrough(technologyDomain);
}
void EventEngine::generateRandomEvent() {
std::cout << "Generating random global event" << std::endl;
}
void EventEngine::processScheduledEvents() {
while (eventQueue_->hasEvents()) {
auto event = eventQueue_->popEvent();
if (event) {
event->execute();
}
}
}
void EventEngine::engineLoop() {
auto lastUpdate = std::chrono::steady_clock::now();
while (running_) {
auto now = std::chrono::steady_clock::now();
auto deltaTime = std::chrono::duration<double>(now - lastUpdate).count();
if (deltaTime >= 1.0/60.0) {
updateEventQueue();
dispatchEvents();
processScheduledEvents();
sendEvents();
receiveEventTriggers();
lastUpdate = now;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
void EventEngine::updateEventQueue() {
}
void EventEngine::dispatchEvents() {
}
void EventEngine::sendEvents() {
}
void EventEngine::receiveEventTriggers() {
}
} // namespace Event
} // namespace Warfactory

View File

@ -0,0 +1,27 @@
cmake_minimum_required(VERSION 3.20)
project(FactoryEngine LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Include directories
include_directories(include)
# Source files
file(GLOB_RECURSE SOURCES
"src/*.cpp"
"src/*.h"
"include/*.h"
"include/*.hpp"
)
# Create executable
add_executable(factory-engine ${SOURCES})
# Set output directory
set_target_properties(factory-engine PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
# Apply unified Warfactory defensive programming (adapts to FAST_BUILD)
warfactory_add_defenses(factory-engine)

View File

@ -3,7 +3,7 @@
using namespace Warfactory::Factory;
int main(int argc, char* argv[]) {
int main(int /*argc*/, char* /*argv*/[]) {
std::cout << "Starting Factory Engine..." << std::endl;
auto engine = std::make_unique<FactoryEngine>();

View File

@ -0,0 +1,122 @@
#include "factory/FactoryEngine.h"
#include <iostream>
#include <chrono>
namespace Warfactory {
namespace Factory {
class ProductionLine {
public:
ProductionLine(int id) : id_(id) {}
int getId() const { return id_; }
void update() {}
private:
int id_;
};
class Belt {
public:
Belt() = default;
};
class Assembler {
public:
Assembler() = default;
};
FactoryEngine::FactoryEngine()
: running_(false), tickRate_(60.0) {
std::cout << "FactoryEngine constructor" << std::endl;
}
FactoryEngine::~FactoryEngine() {
if (running_) {
shutdown();
}
}
bool FactoryEngine::initialize() {
std::cout << "FactoryEngine::initialize()" << std::endl;
running_ = true;
return true;
}
void FactoryEngine::run() {
std::cout << "FactoryEngine::run() starting engine loop" << std::endl;
engineThread_ = std::thread(&FactoryEngine::engineLoop, this);
if (engineThread_.joinable()) {
engineThread_.join();
}
}
void FactoryEngine::shutdown() {
std::cout << "FactoryEngine::shutdown()" << std::endl;
running_ = false;
if (engineThread_.joinable()) {
engineThread_.join();
}
}
void FactoryEngine::addProductionLine(std::unique_ptr<ProductionLine> line) {
std::cout << "Adding production line: " << line->getId() << std::endl;
productionLines_.push_back(std::move(line));
}
void FactoryEngine::removeProductionLine(int lineId) {
auto it = std::remove_if(productionLines_.begin(), productionLines_.end(),
[lineId](const std::unique_ptr<ProductionLine>& line) {
return line->getId() == lineId;
});
productionLines_.erase(it, productionLines_.end());
}
void FactoryEngine::startProduction() {
std::cout << "Starting production" << std::endl;
}
void FactoryEngine::stopProduction() {
std::cout << "Stopping production" << std::endl;
}
void FactoryEngine::pauseProduction() {
std::cout << "Pausing production" << std::endl;
}
void FactoryEngine::engineLoop() {
auto lastUpdate = std::chrono::steady_clock::now();
while (running_) {
auto now = std::chrono::steady_clock::now();
auto deltaTime = std::chrono::duration<double>(now - lastUpdate).count();
if (deltaTime >= 1.0/60.0) {
updateProduction();
processInputOutput();
sendProductionData();
receiveOrders();
lastUpdate = now;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
void FactoryEngine::updateProduction() {
for (auto& line : productionLines_) {
line->update();
}
}
void FactoryEngine::processInputOutput() {
}
void FactoryEngine::sendProductionData() {
}
void FactoryEngine::receiveOrders() {
}
} // namespace Factory
} // namespace Warfactory

View File

@ -0,0 +1,27 @@
cmake_minimum_required(VERSION 3.20)
project(LogisticEngine LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Include directories
include_directories(include)
# Source files
file(GLOB_RECURSE SOURCES
"src/*.cpp"
"src/*.h"
"include/*.h"
"include/*.hpp"
)
# Create executable
add_executable(logistic-engine ${SOURCES})
# Set output directory
set_target_properties(logistic-engine PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
# Apply unified Warfactory defensive programming (adapts to FAST_BUILD)
warfactory_add_defenses(logistic-engine)

View File

@ -1,9 +1,9 @@
#include <iostream>
#include "logistic-engine/Logistic-EngineEngine.h"
#include "logistic-engine/LogisticEngine.h"
using namespace Warfactory::Logistic;
int main(int argc, char* argv[]) {
int main(int /*argc*/, char* /*argv*/[]) {
std::cout << "Starting Logistic-Engine..." << std::endl;
auto engine = std::make_unique<LogisticEngine>();

View File

@ -0,0 +1,156 @@
#include "logistic-engine/LogisticEngine.h"
#include <iostream>
#include <chrono>
namespace Warfactory {
namespace Logistic {
class Convoy {
public:
Convoy(const std::string& id) : id_(id) {}
std::string getId() const { return id_; }
void update() {}
private:
std::string id_;
};
class Route {
public:
Route(const std::string& id) : id_(id), secure_(true) {}
std::string getId() const { return id_; }
void setWaypoints(const std::vector<std::pair<int,int>>& waypoints) {
waypoints_ = waypoints;
}
void setVulnerable(bool vulnerable) { secure_ = !vulnerable; }
bool isSecure() const { return secure_; }
private:
std::string id_;
std::vector<std::pair<int,int>> waypoints_;
bool secure_;
};
class SupplyChain {
public:
SupplyChain(const std::string& id) : id_(id) {}
std::string getId() const { return id_; }
void setSites(const std::vector<int>& sites) { sites_ = sites; }
private:
std::string id_;
std::vector<int> sites_;
};
LogisticEngine::LogisticEngine() : running_(false) {
std::cout << "LogisticEngine constructor" << std::endl;
}
LogisticEngine::~LogisticEngine() {
if (running_) {
shutdown();
}
}
bool LogisticEngine::initialize() {
std::cout << "LogisticEngine::initialize()" << std::endl;
running_ = true;
return true;
}
void LogisticEngine::run() {
std::cout << "LogisticEngine::run() starting engine loop" << std::endl;
engineThread_ = std::thread(&LogisticEngine::engineLoop, this);
if (engineThread_.joinable()) {
engineThread_.join();
}
}
void LogisticEngine::shutdown() {
std::cout << "LogisticEngine::shutdown()" << std::endl;
running_ = false;
if (engineThread_.joinable()) {
engineThread_.join();
}
}
void LogisticEngine::createSupplyChain(const std::string& chainId, const std::vector<int>& sites) {
auto chain = std::make_unique<SupplyChain>(chainId);
chain->setSites(sites);
supplyChains_[chainId] = std::move(chain);
std::cout << "Created supply chain: " << chainId << std::endl;
}
void LogisticEngine::updateRoute(const std::string& routeId, const std::vector<std::pair<int,int>>& waypoints) {
auto it = routes_.find(routeId);
if (it != routes_.end()) {
it->second->setWaypoints(waypoints);
} else {
auto route = std::make_unique<Route>(routeId);
route->setWaypoints(waypoints);
routes_[routeId] = std::move(route);
}
std::cout << "Updated route: " << routeId << std::endl;
}
void LogisticEngine::dispatchConvoy(const std::string& convoyId, const std::string& routeId) {
auto convoy = std::make_unique<Convoy>(convoyId);
convoys_[convoyId] = std::move(convoy);
std::cout << "Dispatched convoy " << convoyId << " on route " << routeId << std::endl;
}
void LogisticEngine::trackConvoyProgress(const std::string& convoyId) {
auto it = convoys_.find(convoyId);
if (it != convoys_.end()) {
std::cout << "Tracking convoy: " << convoyId << std::endl;
}
}
void LogisticEngine::markInfrastructureVulnerable(const std::string& routeId, bool vulnerable) {
auto it = routes_.find(routeId);
if (it != routes_.end()) {
it->second->setVulnerable(vulnerable);
std::cout << "Route " << routeId << " marked as " << (vulnerable ? "vulnerable" : "secure") << std::endl;
}
}
bool LogisticEngine::isRouteSecure(const std::string& routeId) const {
auto it = routes_.find(routeId);
return (it != routes_.end()) ? it->second->isSecure() : false;
}
void LogisticEngine::engineLoop() {
auto lastUpdate = std::chrono::steady_clock::now();
while (running_) {
auto now = std::chrono::steady_clock::now();
auto deltaTime = std::chrono::duration<double>(now - lastUpdate).count();
if (deltaTime >= 1.0/60.0) {
updateConvoys();
optimizeRoutes();
sendLogisticData();
receiveTransportRequests();
lastUpdate = now;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
void LogisticEngine::updateConvoys() {
for (auto& [id, convoy] : convoys_) {
convoy->update();
}
}
void LogisticEngine::optimizeRoutes() {
}
void LogisticEngine::sendLogisticData() {
}
void LogisticEngine::receiveTransportRequests() {
}
} // namespace Logistic
} // namespace Warfactory

View File

@ -0,0 +1,27 @@
cmake_minimum_required(VERSION 3.20)
project(OperationEngine LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Include directories
include_directories(include)
# Source files
file(GLOB_RECURSE SOURCES
"src/*.cpp"
"src/*.h"
"include/*.h"
"include/*.hpp"
)
# Create executable
add_executable(operation-engine ${SOURCES})
# Set output directory
set_target_properties(operation-engine PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
# Apply unified Warfactory defensive programming (adapts to FAST_BUILD)
warfactory_add_defenses(operation-engine)

View File

@ -3,6 +3,7 @@
#include <memory>
#include <vector>
#include <thread>
#include <string>
namespace Warfactory {
namespace Operation {

View File

@ -1,9 +1,9 @@
#include <iostream>
#include "operation-engine/Operation-EngineEngine.h"
#include "operation-engine/OperationEngine.h"
using namespace Warfactory::Operation;
int main(int argc, char* argv[]) {
int main(int /*argc*/, char* /*argv*/[]) {
std::cout << "Starting Operation-Engine..." << std::endl;
auto engine = std::make_unique<OperationEngine>();

View File

@ -0,0 +1,150 @@
#include "operation-engine/OperationEngine.h"
#include <iostream>
#include <chrono>
#include <unordered_map>
namespace Warfactory {
namespace Operation {
class AIGeneral {
public:
AIGeneral(const std::string& id) : id_(id), skillLevel_(1.0) {}
std::string getId() const { return id_; }
void adaptFromResult(bool success) {
if (success) {
skillLevel_ += 0.1;
} else {
skillLevel_ = std::max(0.1, skillLevel_ - 0.05);
}
std::cout << "AI General " << id_ << " skill updated to: " << skillLevel_ << std::endl;
}
double getSkillLevel() const { return skillLevel_; }
private:
std::string id_;
double skillLevel_;
};
class StrategicPlanner {
public:
StrategicPlanner() = default;
void createOperation(const std::string& operationId, const std::string& type) {
operations_[operationId] = type;
std::cout << "Created operation " << operationId << " of type: " << type << std::endl;
}
void processDecisions() {}
private:
std::unordered_map<std::string, std::string> operations_;
};
class DoctrineSystem {
public:
DoctrineSystem() = default;
void updateDoctrine(const std::string& companyId, const std::string& lessons) {
doctrines_[companyId] = lessons;
std::cout << "Updated doctrine for company " << companyId << ": " << lessons << std::endl;
}
void analyzeBattleReports(const std::vector<std::string>& reports) {
std::cout << "Analyzing " << reports.size() << " battle reports for doctrine improvements" << std::endl;
}
private:
std::unordered_map<std::string, std::string> doctrines_;
};
OperationEngine::OperationEngine() : running_(false) {
std::cout << "OperationEngine constructor" << std::endl;
planner_ = std::make_unique<StrategicPlanner>();
doctrines_ = std::make_unique<DoctrineSystem>();
}
OperationEngine::~OperationEngine() {
if (running_) {
shutdown();
}
}
bool OperationEngine::initialize() {
std::cout << "OperationEngine::initialize()" << std::endl;
running_ = true;
return true;
}
void OperationEngine::run() {
std::cout << "OperationEngine::run() starting engine loop" << std::endl;
engineThread_ = std::thread(&OperationEngine::engineLoop, this);
if (engineThread_.joinable()) {
engineThread_.join();
}
}
void OperationEngine::shutdown() {
std::cout << "OperationEngine::shutdown()" << std::endl;
running_ = false;
if (engineThread_.joinable()) {
engineThread_.join();
}
}
void OperationEngine::createOperation(const std::string& operationId, const std::string& type) {
planner_->createOperation(operationId, type);
}
void OperationEngine::assignGeneral(const std::string& /*operationId*/, std::unique_ptr<AIGeneral> general) {
std::cout << "Assigned general " << general->getId() << " to operation" << std::endl;
generals_.push_back(std::move(general));
}
void OperationEngine::adaptBehaviorFromResults(const std::string& generalId, bool success) {
for (auto& general : generals_) {
if (general->getId() == generalId) {
general->adaptFromResult(success);
break;
}
}
}
void OperationEngine::updateDoctrine(const std::string& companyId, const std::string& lessons) {
doctrines_->updateDoctrine(companyId, lessons);
}
void OperationEngine::analyzeBattleReports(const std::vector<std::string>& reports) {
doctrines_->analyzeBattleReports(reports);
}
void OperationEngine::engineLoop() {
auto lastUpdate = std::chrono::steady_clock::now();
while (running_) {
auto now = std::chrono::steady_clock::now();
auto deltaTime = std::chrono::duration<double>(now - lastUpdate).count();
if (deltaTime >= 1.0/60.0) {
processStrategicDecisions();
adaptAIBehavior();
sendOrders();
receiveBattleReports();
lastUpdate = now;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
void OperationEngine::processStrategicDecisions() {
planner_->processDecisions();
}
void OperationEngine::adaptAIBehavior() {
for (auto& general : generals_) {
}
}
void OperationEngine::sendOrders() {
}
void OperationEngine::receiveBattleReports() {
}
} // namespace Operation
} // namespace Warfactory

View File

@ -0,0 +1,205 @@
#include <warfactory/contracts.hpp>
#include <vector>
#include <memory>
#include <cmath>
// =============================================================================
// EXEMPLE D'UTILISATION DES DÉFENSES WARFACTORY
// =============================================================================
namespace warfactory::examples {
// =============================================================================
// ECONOMIC ENGINE EXAMPLE
// =============================================================================
class Market {
private:
std::vector<double> prices_;
double total_volume_ = 0.0;
public:
// Constructor avec contracts
explicit Market(size_t initial_capacity) {
WARFACTORY_REQUIRE(initial_capacity > 0);
prices_.reserve(initial_capacity);
WARFACTORY_ENSURE(prices_.capacity() >= initial_capacity);
WARFACTORY_INVARIANT(total_volume_ == 0.0);
}
// Ajouter un prix au marché (peut être négatif !)
void add_price(double price, double volume) {
WARFACTORY_REQUIRE_NOT_NULL(&prices_);
WARFACTORY_REQUIRE(std::isfinite(price));
WARFACTORY_REQUIRE(std::isfinite(volume));
WARFACTORY_REQUIRE(volume > 0.0); // Volume doit être positif par contre
double old_total = total_volume_;
prices_.push_back(price);
total_volume_ += volume;
WARFACTORY_ENSURE(prices_.size() > 0);
WARFACTORY_ENSURE(std::isfinite(total_volume_));
WARFACTORY_ENSURE(total_volume_ == old_total + volume);
WARFACTORY_INVARIANT(check_invariants());
}
// Calculer prix moyen pondéré
double weighted_average_price() const {
WARFACTORY_REQUIRE(!prices_.empty());
WARFACTORY_REQUIRE(total_volume_ > 0.0);
double weighted_sum = 0.0;
double volume_per_price = total_volume_ / prices_.size();
for (double price : prices_) {
WARFACTORY_PROPERTY_FINITE_VALUES(price);
weighted_sum += price * volume_per_price;
}
double result = weighted_sum / total_volume_;
WARFACTORY_ENSURE_NOT_NULL(&result);
WARFACTORY_ENSURE(std::isfinite(result));
return result;
}
// Exemple de fail-fast sur condition impossible
void process_transaction(double amount) {
WARFACTORY_REQUIRE(std::isfinite(amount));
if (amount == 0.0) {
// Transaction vide, juste ignorer
return;
}
// Condition qui ne devrait jamais arriver
if (std::isnan(amount) || std::isinf(amount)) {
WARFACTORY_FAIL_FAST_IF(true); // Crash immédiat
}
// Traitement normal...
total_volume_ += std::abs(amount);
WARFACTORY_INVARIANT(check_invariants());
}
private:
bool check_invariants() const {
return std::isfinite(total_volume_) &&
total_volume_ >= 0.0 &&
prices_.size() < 1000000; // Limite raisonnable
}
};
// =============================================================================
// FACTORY ENGINE EXAMPLE
// =============================================================================
class Production {
private:
std::vector<double> inputs_;
std::vector<double> outputs_;
public:
void add_production_step(const std::vector<double>& inputs,
const std::vector<double>& outputs) {
WARFACTORY_REQUIRE(!inputs.empty());
WARFACTORY_REQUIRE(!outputs.empty());
WARFACTORY_REQUIRE(inputs.size() == outputs.size());
double total_input = 0.0;
double total_output = 0.0;
for (size_t i = 0; i < inputs.size(); ++i) {
WARFACTORY_REQUIRE(std::isfinite(inputs[i]));
WARFACTORY_REQUIRE(std::isfinite(outputs[i]));
WARFACTORY_REQUIRE(inputs[i] >= 0.0); // Les inputs sont non-négatifs
WARFACTORY_REQUIRE(outputs[i] >= 0.0); // Les outputs aussi
total_input += inputs[i];
total_output += outputs[i];
inputs_.push_back(inputs[i]);
outputs_.push_back(outputs[i]);
}
// Conservation de masse (avec tolérance)
WARFACTORY_PROPERTY_CONSERVATION_OF_MASS(total_input, total_output);
WARFACTORY_ENSURE(inputs_.size() == outputs_.size());
WARFACTORY_INVARIANT(!inputs_.empty() && !outputs_.empty());
}
};
// =============================================================================
// PROPERTY-BASED TESTING EXAMPLE
// =============================================================================
// Test que toutes les valeurs restent finies
WARFACTORY_PROPERTY(market_values_always_finite, Market& market, double price, double volume) {
if (volume <= 0.0) return; // Skip invalid volumes
if (!std::isfinite(price) || !std::isfinite(volume)) return; // Skip invalid inputs
market.add_price(price, volume);
// Property: Le prix moyen doit toujours être fini
if (!market.weighted_average_price()) {
WARFACTORY_UNREACHABLE(); // Ne devrait jamais arriver
}
double avg = market.weighted_average_price();
WARFACTORY_PROPERTY_FINITE_VALUES(avg);
}
// Test de conservation de masse
WARFACTORY_PROPERTY(production_conserves_mass, Production& prod) {
std::vector<double> inputs = {10.0, 5.0, 2.0};
std::vector<double> outputs = {8.0, 6.0, 3.0}; // Total égal
// Cette propriété devrait passer
prod.add_production_step(inputs, outputs);
}
} // namespace warfactory::examples
// =============================================================================
// MAIN EXAMPLE
// =============================================================================
int main() {
try {
using namespace warfactory::examples;
// Test du marché avec prix négatifs (subventions)
Market market(100);
market.add_price(150.0, 10.0); // Prix normal
market.add_price(-50.0, 5.0); // Subvention !
market.add_price(200.0, 15.0); // Prix élevé
double avg = market.weighted_average_price();
printf("Prix moyen pondéré: %.2f (avec subventions)\n", avg);
// Test de production
Production prod;
std::vector<double> inputs = {100.0, 50.0};
std::vector<double> outputs = {75.0, 75.0}; // Conservation parfaite
prod.add_production_step(inputs, outputs);
printf("Production ajoutée avec conservation de masse\n");
return 0;
} catch (const warfactory::contracts::ContractViolation& e) {
fprintf(stderr, "CONTRACT VIOLATION: %s\n", e.what());
return 1;
} catch (const std::exception& e) {
fprintf(stderr, "ERROR: %s\n", e.what());
return 1;
}
}

View File

@ -0,0 +1,229 @@
#pragma once
#include <cassert>
#include <stdexcept>
#include <string_view>
#include <source_location>
#include <cmath>
// =============================================================================
// WARFACTORY CONTRACT-BASED PROGRAMMING
// Simulation des contracts C++20 + fail-fast patterns
// =============================================================================
namespace warfactory::contracts {
// =============================================================================
// CONTRACT VIOLATION HANDLING
// =============================================================================
class ContractViolation : public std::logic_error {
public:
ContractViolation(const std::string& message,
const std::source_location& location = std::source_location::current())
: std::logic_error(format_message(message, location)) {}
private:
static std::string format_message(const std::string& message,
const std::source_location& location) {
return std::string("CONTRACT VIOLATION: ") + message +
" at " + location.file_name() + ":" + std::to_string(location.line());
}
};
// =============================================================================
// FAIL-FAST MACROS
// =============================================================================
#ifdef WARFACTORY_FAIL_FAST
// Terminate immédiatement sur condition impossible
#define WARFACTORY_UNREACHABLE() \
do { \
fprintf(stderr, "UNREACHABLE CODE at %s:%d\n", __FILE__, __LINE__); \
std::terminate(); \
} while(0)
// Crash immédiat vs corruption silencieuse
#define WARFACTORY_FAIL_FAST_IF(condition) \
do { \
if (__builtin_expect(!!(condition), 0)) { \
fprintf(stderr, "FAIL-FAST TRIGGERED: %s at %s:%d\n", #condition, __FILE__, __LINE__); \
std::terminate(); \
} \
} while(0)
#else
#define WARFACTORY_UNREACHABLE() ((void)0)
#define WARFACTORY_FAIL_FAST_IF(condition) ((void)0)
#endif
// =============================================================================
// PRECONDITIONS
// =============================================================================
#ifdef WARFACTORY_PRECONDITION_ENABLED
#define WARFACTORY_PRECONDITION(condition, message) \
do { \
if (__builtin_expect(!(condition), 0)) { \
throw warfactory::contracts::ContractViolation( \
"PRECONDITION FAILED: " #condition " - " message); \
} \
} while(0)
#define WARFACTORY_REQUIRE(condition) \
WARFACTORY_PRECONDITION(condition, "Requirement not met")
#define WARFACTORY_REQUIRE_NOT_NULL(ptr) \
WARFACTORY_PRECONDITION((ptr) != nullptr, "Pointer must not be null")
#define WARFACTORY_REQUIRE_IN_RANGE(value, min, max) \
WARFACTORY_PRECONDITION((value) >= (min) && (value) <= (max), "Value must be in range")
#else
#define WARFACTORY_PRECONDITION(condition, message) ((void)0)
#define WARFACTORY_REQUIRE(condition) ((void)0)
#define WARFACTORY_REQUIRE_NOT_NULL(ptr) ((void)0)
#define WARFACTORY_REQUIRE_IN_RANGE(value, min, max) ((void)0)
#endif
// =============================================================================
// POSTCONDITIONS
// =============================================================================
#ifdef WARFACTORY_POSTCONDITION_ENABLED
#define WARFACTORY_POSTCONDITION(condition, message) \
do { \
if (__builtin_expect(!(condition), 0)) { \
throw warfactory::contracts::ContractViolation( \
"POSTCONDITION FAILED: " #condition " - " message); \
} \
} while(0)
#define WARFACTORY_ENSURE(condition) \
WARFACTORY_POSTCONDITION(condition, "Postcondition not met")
#define WARFACTORY_ENSURE_NOT_NULL(ptr) \
WARFACTORY_POSTCONDITION((ptr) != nullptr, "Return value must not be null")
#else
#define WARFACTORY_POSTCONDITION(condition, message) ((void)0)
#define WARFACTORY_ENSURE(condition) ((void)0)
#define WARFACTORY_ENSURE_NOT_NULL(ptr) ((void)0)
#endif
// =============================================================================
// INVARIANTS
// =============================================================================
#ifdef WARFACTORY_ASSERT_ENABLED
#define WARFACTORY_ASSERT(condition, message) \
do { \
if (__builtin_expect(!(condition), 0)) { \
throw warfactory::contracts::ContractViolation( \
"ASSERTION FAILED: " #condition " - " message); \
} \
} while(0)
#define WARFACTORY_INVARIANT(condition) \
WARFACTORY_ASSERT(condition, "Class invariant violated")
#else
#define WARFACTORY_ASSERT(condition, message) ((void)0)
#define WARFACTORY_INVARIANT(condition) ((void)0)
#endif
// =============================================================================
// INPUT/OUTPUT VALIDATION
// =============================================================================
#ifdef WARFACTORY_VALIDATE_ALL_INPUTS
#define WARFACTORY_VALIDATE_INPUT(condition, message) \
WARFACTORY_PRECONDITION(condition, "INPUT VALIDATION: " message)
#define WARFACTORY_VALIDATE_JSON_SCHEMA(json, schema) \
do { \
if (!validate_json_against_schema(json, schema)) { \
throw warfactory::contracts::ContractViolation("JSON schema validation failed"); \
} \
} while(0)
#else
#define WARFACTORY_VALIDATE_INPUT(condition, message) ((void)0)
#define WARFACTORY_VALIDATE_JSON_SCHEMA(json, schema) ((void)0)
#endif
#ifdef WARFACTORY_VALIDATE_ALL_OUTPUTS
#define WARFACTORY_VALIDATE_OUTPUT(condition, message) \
WARFACTORY_POSTCONDITION(condition, "OUTPUT VALIDATION: " message)
#else
#define WARFACTORY_VALIDATE_OUTPUT(condition, message) ((void)0)
#endif
// =============================================================================
// PROPERTY-BASED TESTING MACROS
// =============================================================================
#ifdef WARFACTORY_PROPERTY_TESTING
#define WARFACTORY_PROPERTY(name, ...) \
namespace { \
struct Property_##name { \
static void test(__VA_ARGS__); \
}; \
} \
void Property_##name::test(__VA_ARGS__)
#define WARFACTORY_CHECK_PROPERTY(condition) \
do { \
if (!(condition)) { \
throw std::runtime_error("Property violation: " #condition); \
} \
} while(0)
// Propriétés communes pour le business domain
#define WARFACTORY_PROPERTY_CONSERVATION_OF_MASS(input, output) \
WARFACTORY_CHECK_PROPERTY(std::abs((input) - (output)) < 1e-6)
#define WARFACTORY_PROPERTY_FINITE_VALUES(value) \
WARFACTORY_CHECK_PROPERTY(std::isfinite(value))
#else
#define WARFACTORY_PROPERTY(name, ...)
#define WARFACTORY_CHECK_PROPERTY(condition) ((void)0)
#define WARFACTORY_PROPERTY_CONSERVATION_OF_MASS(input, output) ((void)0)
#define WARFACTORY_PROPERTY_FINITE_VALUES(value) ((void)0)
#endif
} // namespace warfactory::contracts
// =============================================================================
// HELPER FUNCTIONS FOR RUNTIME VALIDATION
// =============================================================================
namespace warfactory::validation {
// JSON Schema validation placeholder
inline bool validate_json_against_schema(const std::string& json, const std::string& schema) {
// TODO: Intégrer avec nlohmann::json validator ou équivalent
return true; // Placeholder
}
// Runtime health checks
inline void perform_health_check() {
// TODO: Vérifier état des engines, mémoire, etc.
}
// Memory usage monitoring
inline size_t get_current_memory_usage() {
// TODO: Implémenter monitoring mémoire
return 0; // Placeholder
}
} // namespace warfactory::validation

View File

@ -0,0 +1,192 @@
#pragma once
// Guidelines Support Library integration pour Warfactory
// Contracts automatiques et safety guarantees
#ifdef GSL_THROW_ON_CONTRACT_VIOLATION
#include <gsl/gsl>
#else
// Fallback lightweight implementation
namespace gsl {
template<typename T>
class not_null {
T ptr_;
public:
constexpr not_null(T ptr) : ptr_(ptr) {
if (ptr == nullptr) {
std::terminate(); // Fail-fast
}
}
constexpr T get() const { return ptr_; }
constexpr operator T() const { return ptr_; }
constexpr T operator->() const { return ptr_; }
constexpr auto operator*() const { return *ptr_; }
};
template<typename T>
class span {
T* data_;
size_t size_;
public:
constexpr span(T* data, size_t size) : data_(data), size_(size) {}
constexpr T* data() const { return data_; }
constexpr size_t size() const { return size_; }
constexpr T& operator[](size_t idx) const {
if (idx >= size_) std::terminate();
return data_[idx];
}
};
}
#endif
#include <warfactory/contracts.hpp>
namespace warfactory::gsl_integration {
// =============================================================================
// ENHANCED CONTRACTS WITH GSL
// =============================================================================
// Wrapper pour fonctions qui ne peuvent pas retourner null
template<typename T>
using non_null_result = gsl::not_null<T>;
// Safe array access avec bounds checking
template<typename T>
using safe_array = gsl::span<T>;
// =============================================================================
// EXAMPLES FOR WARFACTORY ENGINES
// =============================================================================
class SafeMarketData {
private:
std::vector<double> prices_;
public:
// Function qui garantit un pointeur non-null
non_null_result<const double*> get_price_ptr(size_t index) const {
WARFACTORY_REQUIRE(index < prices_.size());
const double* ptr = &prices_[index];
WARFACTORY_ENSURE_NOT_NULL(ptr);
return gsl::not_null<const double*>(ptr); // Compile-time guarantee
}
// Safe array access avec GSL span
safe_array<const double> get_prices_view() const {
if (prices_.empty()) {
WARFACTORY_FAIL_FAST_IF(true); // Empty view serait dangereux
}
return gsl::span<const double>(prices_.data(), prices_.size());
}
// GSL contracts combinés avec nos contracts Warfactory
void add_price_safe(gsl::not_null<const double*> price_ptr, double volume) {
WARFACTORY_REQUIRE(std::isfinite(*price_ptr));
WARFACTORY_REQUIRE(std::isfinite(volume));
WARFACTORY_REQUIRE(volume > 0.0);
// GSL garantit que price_ptr n'est pas null
prices_.push_back(*price_ptr);
WARFACTORY_ENSURE(!prices_.empty());
WARFACTORY_PROPERTY_FINITE_VALUES(prices_.back());
}
};
// =============================================================================
// FACTORY PRODUCTION WITH GSL SAFETY
// =============================================================================
class SafeProduction {
public:
struct ProductionStep {
gsl::span<const double> inputs;
gsl::span<double> outputs;
// GSL contract: inputs et outputs même taille
ProductionStep(gsl::span<const double> in, gsl::span<double> out)
: inputs(in), outputs(out) {
if (inputs.size() != outputs.size()) {
WARFACTORY_FAIL_FAST_IF(true);
}
}
};
void process_production_step(const ProductionStep& step) {
WARFACTORY_REQUIRE(step.inputs.size() > 0);
WARFACTORY_REQUIRE(step.outputs.size() > 0);
double total_input = 0.0;
double total_output = 0.0;
// GSL span garantit les bounds checks
for (size_t i = 0; i < step.inputs.size(); ++i) {
const double input = step.inputs[i]; // Bounds check automatique
double& output = step.outputs[i]; // Bounds check automatique
WARFACTORY_PROPERTY_FINITE_VALUES(input);
WARFACTORY_REQUIRE(input >= 0.0);
// Simulation de transformation
output = input * 0.9; // 10% loss
total_input += input;
total_output += output;
WARFACTORY_PROPERTY_FINITE_VALUES(output);
}
// Conservation de masse avec tolérance
WARFACTORY_PROPERTY_CONSERVATION_OF_MASS(total_input, total_output * 1.111); // +10% tolerance
}
};
// =============================================================================
// FUZZING TARGET FUNCTIONS
// =============================================================================
// Function spécialement conçue pour fuzzing avec GSL safety
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
if (size < sizeof(double) * 2) {
return 0; // Input trop petit
}
try {
// Convert raw bytes to doubles safely
gsl::span<const uint8_t> input_data(data, size);
if (input_data.size() >= sizeof(double) * 2) {
// Extract two doubles from fuzzer input
double price, volume;
std::memcpy(&price, input_data.data(), sizeof(double));
std::memcpy(&volume, input_data.data() + sizeof(double), sizeof(double));
// Test our market with fuzzer input
SafeMarketData market;
// GSL + Contracts will catch invalid inputs
if (std::isfinite(price) && std::isfinite(volume) && volume > 0.0) {
market.add_price_safe(gsl::not_null<const double*>(&price), volume);
auto view = market.get_prices_view();
if (view.size() > 0) {
auto price_ptr = market.get_price_ptr(0);
WARFACTORY_PROPERTY_FINITE_VALUES(*price_ptr);
}
}
}
return 0; // Success
} catch (const warfactory::contracts::ContractViolation&) {
return 0; // Expected contract violation
} catch (...) {
return 1; // Unexpected error - fuzzer should explore this
}
}
} // namespace warfactory::gsl_integration

View File

@ -0,0 +1,67 @@
#!/bin/bash
# Script pour appliquer les défenses Warfactory à tous les engines
# Usage: ./scripts/apply_defenses_to_all_engines.sh
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
echo "🛡️ Applying Warfactory defenses to all engines..."
# Liste des engines
ENGINES=(
"Designer-Engine"
"Event-Engine"
"Factory-Engine"
"Intelligence-Engine"
"Logistic-Engine"
"MacroEntity-Engine"
"Map-Engine"
"Operation-Engine"
"War-Engine"
)
# Template pour les défenses
DEFENSE_TEMPLATE='# Apply comprehensive Warfactory defensive programming
warfactory_add_defenses(ENGINE_NAME)
warfactory_add_cppcheck(ENGINE_NAME)
warfactory_add_pvs_studio(ENGINE_NAME)
warfactory_add_property_testing(ENGINE_NAME)
# Engine-specific "No Trust" configuration'
for engine in "${ENGINES[@]}"; do
echo " Processing $engine..."
# Nom du target (en minuscules avec tirets)
target_name=$(echo "$engine" | tr '[:upper:]' '[:lower:]')
cmake_file="$PROJECT_ROOT/engines/$engine/CMakeLists.txt"
if [[ -f "$cmake_file" ]]; then
# Remplacer le commentaire "Configuration \"No Trust\"" par notre template
defense_block=$(echo "$DEFENSE_TEMPLATE" | sed "s/ENGINE_NAME/$target_name/g")
# Utiliser sed pour remplacer la ligne de commentaire
sed -i "s|# Configuration \"No Trust\" pour Claude Code|$defense_block|" "$cmake_file"
echo "$engine updated"
else
echo " ⚠️ $cmake_file not found"
fi
done
echo "🛡️ All engines updated with Warfactory defenses!"
echo ""
echo "Available build options:"
echo " -DENABLE_STATIC_ANALYSIS=ON : Enable Clang Static Analyzer"
echo " -DENABLE_FUZZING=ON : Enable fuzzing infrastructure"
echo " -DCMAKE_BUILD_TYPE=Debug : Enable all sanitizers"
echo ""
echo "Usage examples:"
echo " mkdir build && cd build"
echo " cmake -DCMAKE_BUILD_TYPE=Debug -DENABLE_STATIC_ANALYSIS=ON .."
echo " make economy-engine"
echo " make economy-engine_cppcheck # Run static analysis"

View File

@ -0,0 +1,191 @@
#!/bin/bash
# Script pour appliquer l'automation complète à tous les engines
# Usage: ./scripts/apply_full_automation.sh
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
echo "🤖 Applying full automation to all Warfactory engines..."
# Liste des engines
ENGINES=(
"Designer-Engine"
"Economy-Engine"
"Event-Engine"
"Factory-Engine"
"Intelligence-Engine"
"Logistic-Engine"
"MacroEntity-Engine"
"Map-Engine"
"Operation-Engine"
"War-Engine"
)
# Template pour automation complète
AUTOMATION_TEMPLATE='# Apply comprehensive Warfactory automation
warfactory_add_full_automation(ENGINE_NAME)
# Engine-specific "No Trust" configuration'
for engine in "${ENGINES[@]}"; do
echo " Processing $engine..."
# Nom du target (en minuscules avec tirets)
target_name=$(echo "$engine" | tr '[:upper:]' '[:lower:]')
cmake_file="$PROJECT_ROOT/engines/$engine/CMakeLists.txt"
if [[ -f "$cmake_file" ]]; then
# Remplacer la ligne warfactory_add_defenses par automation complète
sed -i "s|^warfactory_add_defenses.*|$AUTOMATION_TEMPLATE|" "$cmake_file"
# Substituer le nom du target
sed -i "s/ENGINE_NAME/$target_name/g" "$cmake_file"
# Créer répertoires de test et benchmark si ils n'existent pas
engine_dir="$PROJECT_ROOT/engines/$engine"
mkdir -p "$engine_dir/tests"
mkdir -p "$engine_dir/benchmarks"
# Créer exemple de test si pas existant
test_file="$engine_dir/tests/test_$target_name.cpp"
if [[ ! -f "$test_file" ]]; then
cat > "$test_file" << 'EOF'
#include <catch2/catch_test_macros.hpp>
#include <warfactory/contracts.hpp>
// Tests unitaires automatiques pour ENGINE_NAME
// Générés par Warfactory automation
TEST_CASE("ENGINE_NAME basic functionality", "[ENGINE_NAME]") {
SECTION("Engine initialization") {
// TODO: Test engine creation and initialization
REQUIRE(true); // Placeholder
}
SECTION("Contract validation") {
// Test des contracts Warfactory
WARFACTORY_PROPERTY_FINITE_VALUES(42.0);
REQUIRE(std::isfinite(42.0));
}
SECTION("Error handling") {
// Test fail-fast patterns
REQUIRE_NOTHROW(WARFACTORY_REQUIRE(true));
}
}
TEST_CASE("ENGINE_NAME integration tests", "[ENGINE_NAME][integration]") {
SECTION("Inter-engine communication") {
// TODO: Test communication with other engines
REQUIRE(true); // Placeholder
}
SECTION("Performance requirements") {
// TODO: Test performance requirements
REQUIRE(true); // Placeholder
}
}
TEST_CASE("ENGINE_NAME property-based tests", "[ENGINE_NAME][property]") {
SECTION("Conservation properties") {
// Test des propriétés mathématiques
double input = 100.0;
double output = input * 0.9; // 10% loss exemple
WARFACTORY_PROPERTY_FINITE_VALUES(input);
WARFACTORY_PROPERTY_FINITE_VALUES(output);
REQUIRE(output <= input); // Output never exceeds input
}
}
EOF
# Remplacer ENGINE_NAME par le vrai nom
sed -i "s/ENGINE_NAME/$target_name/g" "$test_file"
fi
# Créer exemple de benchmark si pas existant
bench_file="$engine_dir/benchmarks/bench_$target_name.cpp"
if [[ ! -f "$bench_file" ]]; then
cat > "$bench_file" << 'EOF'
#include <benchmark/benchmark.h>
#include <warfactory/contracts.hpp>
// Benchmarks automatiques pour ENGINE_NAME
// Générés par Warfactory automation
static void BM_ENGINE_NAME_BasicOperation(benchmark::State& state) {
for (auto _ : state) {
// TODO: Benchmark core operation
WARFACTORY_PROPERTY_FINITE_VALUES(42.0);
benchmark::DoNotOptimize(42.0);
}
state.SetComplexityN(state.range(0));
}
BENCHMARK(BM_ENGINE_NAME_BasicOperation)
->Range(8, 8<<10)
->Complexity(benchmark::oN);
static void BM_ENGINE_NAME_MemoryAllocation(benchmark::State& state) {
for (auto _ : state) {
// TODO: Benchmark memory operations
std::vector<double> data(state.range(0));
benchmark::DoNotOptimize(data);
}
state.SetBytesProcessed(int64_t(state.iterations()) *
int64_t(state.range(0)) * sizeof(double));
}
BENCHMARK(BM_ENGINE_NAME_MemoryAllocation)
->Range(1<<10, 1<<18)
->Unit(benchmark::kMillisecond);
BENCHMARK_MAIN();
EOF
# Remplacer ENGINE_NAME par le vrai nom
sed -i "s/ENGINE_NAME/$target_name/g" "$bench_file"
fi
echo "$engine updated with full automation"
else
echo " ⚠️ $cmake_file not found"
fi
done
echo ""
echo "🤖 Full automation applied to all engines!"
echo ""
echo "📋 What was configured:"
echo " ✓ FetchContent dependency management (Redis++, JSON, spdlog, Catch2)"
echo " ✓ CTest integration with per-engine test suites"
echo " ✓ Doxygen documentation generation"
echo " ✓ Engine export/import system for inter-engine dependencies"
echo " ✓ Multiple build configurations (Debug, Release, Testing, Profiling)"
echo " ✓ Precompiled headers for faster compilation"
echo " ✓ CPack packaging (DEB, RPM, NSIS, etc.)"
echo " ✓ Automation targets for Claude Code workflow"
echo " ✓ Test files and benchmark templates generated"
echo ""
echo "🚀 Usage examples:"
echo " mkdir build && cd build"
echo ""
echo " # Full automation build:"
echo " cmake -DCMAKE_BUILD_TYPE=Debug -DENABLE_ADVANCED_TOOLS=ON -DENABLE_BENCHMARKING=ON .."
echo " make claude-workflow"
echo ""
echo " # Testing build:"
echo " cmake -DCMAKE_BUILD_TYPE=Testing .."
echo " make test-all-engines"
echo ""
echo " # Documentation:"
echo " make docs-all"
echo ""
echo " # Packaging:"
echo " make package-all"
echo ""
echo " # CI/CD simulation:"
echo " make ci-simulation"

View File

@ -0,0 +1,261 @@
#!/bin/bash
# Script d'installation pour tous les outils avancés Warfactory
# Installe fuzzing, formal verification, concurrency analysis, etc.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
echo "🔧 Setting up Warfactory Advanced Tools..."
echo ""
# Detect OS
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
OS="linux"
DISTRO=$(lsb_release -si 2>/dev/null || echo "Unknown")
elif [[ "$OSTYPE" == "darwin"* ]]; then
OS="macos"
else
echo "❌ Unsupported OS: $OSTYPE"
exit 1
fi
echo "🖥️ Detected OS: $OS"
echo ""
# =============================================================================
# FUZZING TOOLS
# =============================================================================
echo "🔍 Installing Fuzzing Tools..."
# AFL++
if ! command -v afl-fuzz &> /dev/null; then
echo " Installing AFL++..."
if [[ "$OS" == "linux" ]]; then
if [[ "$DISTRO" == "Ubuntu" ]] || [[ "$DISTRO" == "Debian" ]]; then
sudo apt-get update
sudo apt-get install -y afl++
elif [[ "$DISTRO" == "Fedora" ]] || [[ "$DISTRO" == "CentOS" ]]; then
sudo dnf install -y afl
else
# Build from source
git clone https://github.com/AFLplusplus/AFLplusplus.git /tmp/aflplusplus
cd /tmp/aflplusplus
make all
sudo make install
fi
elif [[ "$OS" == "macos" ]]; then
brew install afl++
fi
echo " ✓ AFL++ installed"
else
echo " ✓ AFL++ already installed"
fi
# honggfuzz
if ! command -v honggfuzz &> /dev/null; then
echo " Installing honggfuzz..."
if [[ "$OS" == "linux" ]]; then
if [[ "$DISTRO" == "Ubuntu" ]] || [[ "$DISTRO" == "Debian" ]]; then
sudo apt-get install -y honggfuzz
else
# Build from source
git clone https://github.com/google/honggfuzz.git /tmp/honggfuzz
cd /tmp/honggfuzz
make
sudo make install
fi
elif [[ "$OS" == "macos" ]]; then
brew install honggfuzz
fi
echo " ✓ honggfuzz installed"
else
echo " ✓ honggfuzz already installed"
fi
# =============================================================================
# FORMAL VERIFICATION TOOLS
# =============================================================================
echo ""
echo "🔬 Installing Formal Verification Tools..."
# CBMC
if ! command -v cbmc &> /dev/null; then
echo " Installing CBMC..."
if [[ "$OS" == "linux" ]]; then
if [[ "$DISTRO" == "Ubuntu" ]] || [[ "$DISTRO" == "Debian" ]]; then
sudo apt-get install -y cbmc
else
# Download binary release
CBMC_VERSION="5.95.1"
wget "https://github.com/diffblue/cbmc/releases/download/cbmc-${CBMC_VERSION}/cbmc-${CBMC_VERSION}-linux-64.tgz" -O /tmp/cbmc.tgz
cd /tmp
tar -xzf cbmc.tgz
sudo cp cbmc-*/bin/* /usr/local/bin/
fi
elif [[ "$OS" == "macos" ]]; then
brew install cbmc
fi
echo " ✓ CBMC installed"
else
echo " ✓ CBMC already installed"
fi
# KLEE (plus complexe, nécessite LLVM)
if ! command -v klee &> /dev/null; then
echo " Installing KLEE..."
if [[ "$OS" == "linux" ]]; then
# KLEE is complex to build, use Docker image instead
echo " 📦 KLEE will use Docker image (recommended)"
echo " Run: docker pull klee/klee"
echo " Usage: docker run --rm -v \$(pwd):/tmp klee/klee klee /tmp/your_file.bc"
elif [[ "$OS" == "macos" ]]; then
echo " 📦 KLEE installation on macOS requires manual setup"
echo " See: https://klee.github.io/build-llvm9/"
fi
else
echo " ✓ KLEE already installed"
fi
# =============================================================================
# STATIC ANALYSIS TOOLS
# =============================================================================
echo ""
echo "🔍 Installing Static Analysis Tools..."
# Cppcheck
if ! command -v cppcheck &> /dev/null; then
echo " Installing Cppcheck..."
if [[ "$OS" == "linux" ]]; then
if [[ "$DISTRO" == "Ubuntu" ]] || [[ "$DISTRO" == "Debian" ]]; then
sudo apt-get install -y cppcheck
elif [[ "$DISTRO" == "Fedora" ]] || [[ "$DISTRO" == "CentOS" ]]; then
sudo dnf install -y cppcheck
fi
elif [[ "$OS" == "macos" ]]; then
brew install cppcheck
fi
echo " ✓ Cppcheck installed"
else
echo " ✓ Cppcheck already installed"
fi
# ABI compliance checker
if ! command -v abi-compliance-checker &> /dev/null; then
echo " Installing ABI Compliance Checker..."
if [[ "$OS" == "linux" ]]; then
if [[ "$DISTRO" == "Ubuntu" ]] || [[ "$DISTRO" == "Debian" ]]; then
sudo apt-get install -y abi-compliance-checker
else
# Install from source
git clone https://github.com/lvc/abi-compliance-checker.git /tmp/abi-checker
cd /tmp/abi-checker
sudo make install prefix=/usr/local
fi
elif [[ "$OS" == "macos" ]]; then
# Build from source
git clone https://github.com/lvc/abi-compliance-checker.git /tmp/abi-checker
cd /tmp/abi-checker
sudo make install prefix=/usr/local
fi
echo " ✓ ABI Compliance Checker installed"
else
echo " ✓ ABI Compliance Checker already installed"
fi
# =============================================================================
# CONCURRENCY ANALYSIS TOOLS
# =============================================================================
echo ""
echo "🧵 Installing Concurrency Analysis Tools..."
# Valgrind
if ! command -v valgrind &> /dev/null; then
echo " Installing Valgrind..."
if [[ "$OS" == "linux" ]]; then
if [[ "$DISTRO" == "Ubuntu" ]] || [[ "$DISTRO" == "Debian" ]]; then
sudo apt-get install -y valgrind
elif [[ "$DISTRO" == "Fedora" ]] || [[ "$DISTRO" == "CentOS" ]]; then
sudo dnf install -y valgrind
fi
elif [[ "$OS" == "macos" ]]; then
brew install --HEAD valgrind
fi
echo " ✓ Valgrind installed"
else
echo " ✓ Valgrind already installed"
fi
# =============================================================================
# GUIDELINES SUPPORT LIBRARY
# =============================================================================
echo ""
echo "📋 Setting up Guidelines Support Library..."
GSL_DIR="$PROJECT_ROOT/third_party/gsl"
if [[ ! -d "$GSL_DIR" ]]; then
echo " Cloning Microsoft GSL..."
git clone https://github.com/microsoft/GSL.git "$GSL_DIR"
echo " ✓ GSL cloned to third_party/gsl"
else
echo " ✓ GSL already available"
fi
# =============================================================================
# VERIFICATION
# =============================================================================
echo ""
echo "✅ Verifying installations..."
TOOLS=(
"afl-fuzz:AFL++"
"honggfuzz:honggfuzz"
"cbmc:CBMC"
"cppcheck:Cppcheck"
"valgrind:Valgrind"
"abi-compliance-checker:ABI Checker"
"clang:Clang (for libFuzzer)"
"llvm-profdata:LLVM tools"
)
for tool_info in "${TOOLS[@]}"; do
tool="${tool_info%:*}"
name="${tool_info#*:}"
if command -v "$tool" &> /dev/null; then
echo "$name: $(which $tool)"
else
echo "$name: not found"
fi
done
echo ""
echo "🎯 Setup complete!"
echo ""
echo "📖 Usage examples:"
echo " mkdir build && cd build"
echo " cmake -DCMAKE_BUILD_TYPE=Debug -DENABLE_ADVANCED_TOOLS=ON .."
echo " make economy-engine"
echo ""
echo "🔍 Run fuzzing:"
echo " make economy-engine_fuzz_all"
echo ""
echo "🔬 Run formal verification:"
echo " make economy-engine_cbmc"
echo ""
echo "🧵 Run concurrency analysis:"
echo " make economy-engine_helgrind"
echo ""
echo "📊 Generate coverage report:"
echo " make economy-engine_coverage_run"
echo ""
echo "🔗 Check ABI compatibility:"
echo " make economy-engine_abi_check"