diff --git a/.agents/skills/cpp-pro/SKILL.md b/.agents/skills/cpp-pro/SKILL.md deleted file mode 100644 index 79107d0..0000000 --- a/.agents/skills/cpp-pro/SKILL.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -name: cpp-pro -description: Use when building C++ applications requiring modern C++20/23 features, template metaprogramming, or high-performance systems. Invoke for concepts, ranges, coroutines, SIMD optimization, memory management. -license: MIT -metadata: - author: https://github.com/Jeffallan - version: "1.0.0" - domain: language - triggers: C++, C++20, C++23, modern C++, template metaprogramming, systems programming, performance optimization, SIMD, memory management, CMake - role: specialist - scope: implementation - output-format: code - related-skills: rust-engineer, embedded-systems ---- - -# C++ Pro - -Senior C++ developer with deep expertise in modern C++20/23, systems programming, high-performance computing, and zero-overhead abstractions. - -## Role Definition - -You are a senior C++ engineer with 15+ years of systems programming experience. You specialize in modern C++20/23, template metaprogramming, performance optimization, and building production-grade systems with emphasis on safety, efficiency, and maintainability. You follow C++ Core Guidelines and leverage cutting-edge language features. - -## When to Use This Skill - -- Building high-performance C++ applications -- Implementing template metaprogramming solutions -- Optimizing memory-critical systems -- Developing concurrent and parallel algorithms -- Creating custom allocators and memory pools -- Systems programming and embedded development - -## Core Workflow - -1. **Analyze architecture** - Review build system, compiler flags, performance requirements -2. **Design with concepts** - Create type-safe interfaces using C++20 concepts -3. **Implement zero-cost** - Apply RAII, constexpr, and zero-overhead abstractions -4. **Verify quality** - Run sanitizers, static analysis, and performance benchmarks -5. **Optimize** - Profile, measure, and apply targeted optimizations - -## Reference Guide - -Load detailed guidance based on context: - -| Topic | Reference | Load When | -|-------|-----------|-----------| -| Modern C++ Features | `references/modern-cpp.md` | C++20/23 features, concepts, ranges, coroutines | -| Template Metaprogramming | `references/templates.md` | Variadic templates, SFINAE, type traits, CRTP | -| Memory & Performance | `references/memory-performance.md` | Allocators, SIMD, cache optimization, move semantics | -| Concurrency | `references/concurrency.md` | Atomics, lock-free structures, thread pools, coroutines | -| Build & Tooling | `references/build-tooling.md` | CMake, sanitizers, static analysis, testing | - -## Constraints - -### MUST DO -- Follow C++ Core Guidelines -- Use concepts for template constraints -- Apply RAII universally -- Use `auto` with type deduction -- Prefer `std::unique_ptr` and `std::shared_ptr` -- Enable all compiler warnings (-Wall -Wextra -Wpedantic) -- Run AddressSanitizer and UndefinedBehaviorSanitizer -- Write const-correct code - -### MUST NOT DO -- Use raw `new`/`delete` (prefer smart pointers) -- Ignore compiler warnings -- Use C-style casts (use static_cast, etc.) -- Mix exception and error code patterns inconsistently -- Write non-const-correct code -- Use `using namespace std` in headers -- Ignore undefined behavior -- Skip move semantics for expensive types - -## Output Templates - -When implementing C++ features, provide: -1. Header file with interfaces and templates -2. Implementation file (when needed) -3. CMakeLists.txt updates (if applicable) -4. Test file demonstrating usage -5. Brief explanation of design decisions and performance characteristics - -## Knowledge Reference - -C++20/23, concepts, ranges, coroutines, modules, template metaprogramming, SFINAE, type traits, CRTP, smart pointers, custom allocators, move semantics, RAII, SIMD, atomics, lock-free programming, CMake, Conan, sanitizers, clang-tidy, cppcheck, Catch2, GoogleTest diff --git a/.agents/skills/cpp-pro/references/concurrency.md b/.agents/skills/cpp-pro/references/concurrency.md deleted file mode 100644 index 2eedf19..0000000 --- a/.agents/skills/cpp-pro/references/concurrency.md +++ /dev/null @@ -1,437 +0,0 @@ -# Concurrency and Parallel Programming - -## Atomics and Memory Ordering - -```cpp -#include -#include - -// Basic atomics -std::atomic counter{0}; -std::atomic flag{false}; - -// Memory ordering -void producer(std::atomic& data, std::atomic& ready) { - data.store(42, std::memory_order_relaxed); - ready.store(true, std::memory_order_release); // Release barrier -} - -void consumer(std::atomic& data, std::atomic& ready) { - while (!ready.load(std::memory_order_acquire)) { // Acquire barrier - std::this_thread::yield(); - } - int value = data.load(std::memory_order_relaxed); -} - -// Compare-and-swap -bool try_acquire_lock(std::atomic& lock) { - bool expected = false; - return lock.compare_exchange_strong(expected, true, - std::memory_order_acquire, - std::memory_order_relaxed); -} - -// Fetch-and-add -int increment_counter(std::atomic& counter) { - return counter.fetch_add(1, std::memory_order_relaxed); -} -``` - -## Lock-Free Data Structures - -```cpp -#include -#include - -// Lock-free stack -template -class LockFreeStack { - struct Node { - T data; - Node* next; - Node(const T& value) : data(value), next(nullptr) {} - }; - - std::atomic head_{nullptr}; - -public: - void push(const T& value) { - Node* new_node = new Node(value); - new_node->next = head_.load(std::memory_order_relaxed); - - while (!head_.compare_exchange_weak(new_node->next, new_node, - std::memory_order_release, - std::memory_order_relaxed)) { - // Retry with updated head - } - } - - bool pop(T& result) { - Node* old_head = head_.load(std::memory_order_relaxed); - - while (old_head && - !head_.compare_exchange_weak(old_head, old_head->next, - std::memory_order_acquire, - std::memory_order_relaxed)) { - // Retry - } - - if (old_head) { - result = old_head->data; - delete old_head; // Note: ABA problem exists - return true; - } - return false; - } -}; - -// Lock-free queue (single producer, single consumer) -template -class SPSCQueue { - std::array buffer_; - alignas(64) std::atomic head_{0}; - alignas(64) std::atomic tail_{0}; - -public: - bool push(const T& item) { - size_t head = head_.load(std::memory_order_relaxed); - size_t next_head = (head + 1) % Size; - - if (next_head == tail_.load(std::memory_order_acquire)) { - return false; // Queue full - } - - buffer_[head] = item; - head_.store(next_head, std::memory_order_release); - return true; - } - - bool pop(T& item) { - size_t tail = tail_.load(std::memory_order_relaxed); - - if (tail == head_.load(std::memory_order_acquire)) { - return false; // Queue empty - } - - item = buffer_[tail]; - tail_.store((tail + 1) % Size, std::memory_order_release); - return true; - } -}; -``` - -## Thread Pool - -```cpp -#include -#include -#include -#include -#include -#include - -class ThreadPool { - std::vector workers_; - std::queue> tasks_; - std::mutex queue_mutex_; - std::condition_variable condition_; - bool stop_ = false; - -public: - ThreadPool(size_t num_threads) { - for (size_t i = 0; i < num_threads; ++i) { - workers_.emplace_back([this] { - while (true) { - std::function task; - - { - std::unique_lock lock(queue_mutex_); - condition_.wait(lock, [this] { - return stop_ || !tasks_.empty(); - }); - - if (stop_ && tasks_.empty()) { - return; - } - - task = std::move(tasks_.front()); - tasks_.pop(); - } - - task(); - } - }); - } - } - - ~ThreadPool() { - { - std::unique_lock lock(queue_mutex_); - stop_ = true; - } - condition_.notify_all(); - for (auto& worker : workers_) { - worker.join(); - } - } - - template - auto enqueue(F&& f, Args&&... args) - -> std::future> { - - using return_type = typename std::invoke_result_t; - - auto task = std::make_shared>( - std::bind(std::forward(f), std::forward(args)...) - ); - - std::future result = task->get_future(); - - { - std::unique_lock lock(queue_mutex_); - if (stop_) { - throw std::runtime_error("enqueue on stopped ThreadPool"); - } - tasks_.emplace([task]() { (*task)(); }); - } - - condition_.notify_one(); - return result; - } -}; -``` - -## Parallel STL Algorithms - -```cpp -#include -#include -#include -#include - -void parallel_algorithms_demo() { - std::vector vec(1'000'000); - std::iota(vec.begin(), vec.end(), 0); - - // Parallel sort - std::sort(std::execution::par, vec.begin(), vec.end()); - - // Parallel for_each - std::for_each(std::execution::par_unseq, vec.begin(), vec.end(), - [](int& x) { x *= 2; }); - - // Parallel transform - std::vector result(vec.size()); - std::transform(std::execution::par, vec.begin(), vec.end(), - result.begin(), [](int x) { return x * x; }); - - // Parallel reduce - int sum = std::reduce(std::execution::par, vec.begin(), vec.end()); - - // Parallel transform_reduce (map-reduce) - int sum_of_squares = std::transform_reduce( - std::execution::par, - vec.begin(), vec.end(), - 0, - std::plus<>(), - [](int x) { return x * x; } - ); -} -``` - -## Synchronization Primitives - -```cpp -#include -#include -#include - -// Mutex types -std::mutex mtx; -std::recursive_mutex rec_mtx; -std::timed_mutex timed_mtx; -std::shared_mutex shared_mtx; - -// RAII locks -void exclusive_access() { - std::lock_guard lock(mtx); - // Critical section -} - -void unique_lock_example() { - std::unique_lock lock(mtx); - // Can unlock and relock - lock.unlock(); - // Do some work - lock.lock(); -} - -// Reader-writer lock -class SharedData { - mutable std::shared_mutex mutex_; - std::string data_; - -public: - std::string read() const { - std::shared_lock lock(mutex_); - return data_; - } - - void write(std::string new_data) { - std::unique_lock lock(mutex_); - data_ = std::move(new_data); - } -}; - -// Condition variable -class Queue { - std::queue queue_; - std::mutex mutex_; - std::condition_variable cv_; - -public: - void push(int value) { - { - std::lock_guard lock(mutex_); - queue_.push(value); - } - cv_.notify_one(); - } - - int pop() { - std::unique_lock lock(mutex_); - cv_.wait(lock, [this] { return !queue_.empty(); }); - int value = queue_.front(); - queue_.pop(); - return value; - } -}; - -// std::scoped_lock - multiple mutexes -std::mutex mtx1, mtx2; - -void transfer(Account& from, Account& to, int amount) { - std::scoped_lock lock(from.mutex, to.mutex); // Deadlock-free - from.balance -= amount; - to.balance += amount; -} -``` - -## Async and Futures - -```cpp -#include - -// std::async -auto future = std::async(std::launch::async, []() { - return expensive_computation(); -}); - -// Get result (blocks until ready) -auto result = future.get(); - -// Promise and future -void producer(std::promise promise) { - int value = compute_value(); - promise.set_value(value); -} - -void consumer(std::future future) { - int value = future.get(); -} - -std::promise promise; -std::future future = promise.get_future(); - -std::thread producer_thread(producer, std::move(promise)); -std::thread consumer_thread(consumer, std::move(future)); - -// Packaged task -std::packaged_task task([](int a, int b) { - return a + b; -}); - -std::future task_future = task.get_future(); -std::thread task_thread(std::move(task), 5, 3); - -int sum = task_future.get(); // 8 -task_thread.join(); -``` - -## Coroutine-Based Concurrency - -```cpp -#include -#include - -// Async task coroutine -template -struct AsyncTask { - struct promise_type { - std::optional value; - std::exception_ptr exception; - - AsyncTask get_return_object() { - return AsyncTask{ - std::coroutine_handle::from_promise(*this) - }; - } - - std::suspend_never initial_suspend() { return {}; } - std::suspend_always final_suspend() noexcept { return {}; } - - void return_value(T v) { - value = std::move(v); - } - - void unhandled_exception() { - exception = std::current_exception(); - } - }; - - std::coroutine_handle handle; - - AsyncTask(std::coroutine_handle h) : handle(h) {} - ~AsyncTask() { if (handle) handle.destroy(); } - - T get() { - if (!handle.done()) { - handle.resume(); - } - - if (handle.promise().exception) { - std::rethrow_exception(handle.promise().exception); - } - - return *handle.promise().value; - } -}; - -// Usage -AsyncTask async_compute() { - co_return 42; -} -``` - -## Quick Reference - -| Primitive | Use Case | Performance | -|-----------|----------|-------------| -| std::atomic | Simple shared state | Lock-free | -| std::mutex | Exclusive access | Kernel call | -| std::shared_mutex | Read-heavy workload | Better than mutex | -| Lock-free structures | High contention | Best throughput | -| Thread pool | Task parallelism | Avoid thread overhead | -| Parallel STL | Data parallelism | Automatic scaling | -| std::async | Simple async tasks | Thread pool | -| Coroutines | Async I/O | Minimal overhead | - -## Memory Ordering Guide - -| Ordering | Guarantees | Use Case | -|----------|-----------|----------| -| relaxed | No synchronization | Counters | -| acquire | Load barrier | Consumer | -| release | Store barrier | Producer | -| acq_rel | Both | RMW operations | -| seq_cst | Total order | Default | diff --git a/.agents/skills/cpp-pro/references/memory-performance.md b/.agents/skills/cpp-pro/references/memory-performance.md deleted file mode 100644 index c60b49d..0000000 --- a/.agents/skills/cpp-pro/references/memory-performance.md +++ /dev/null @@ -1,397 +0,0 @@ -# Memory Management & Performance - -## Smart Pointers - -```cpp -#include - -// unique_ptr - exclusive ownership -auto create_resource() { - return std::make_unique("data"); -} - -// shared_ptr - reference counting -std::shared_ptr shared = std::make_shared(42); -std::weak_ptr weak = shared; // Non-owning reference - -// Custom deleters -auto file_deleter = [](FILE* fp) { if (fp) fclose(fp); }; -std::unique_ptr file( - fopen("data.txt", "r"), - file_deleter -); - -// enable_shared_from_this -class Node : public std::enable_shared_from_this { -public: - std::shared_ptr get_shared() { - return shared_from_this(); - } -}; -``` - -## Custom Allocators - -```cpp -#include -#include - -// Pool allocator for fixed-size objects -template -class PoolAllocator { - struct Block { - alignas(T) std::byte data[sizeof(T)]; - Block* next; - }; - - Block pool_[PoolSize]; - Block* free_list_ = nullptr; - -public: - using value_type = T; - - PoolAllocator() { - // Initialize free list - for (size_t i = 0; i < PoolSize - 1; ++i) { - pool_[i].next = &pool_[i + 1]; - } - pool_[PoolSize - 1].next = nullptr; - free_list_ = &pool_[0]; - } - - T* allocate(size_t n) { - if (n != 1 || !free_list_) { - throw std::bad_alloc(); - } - Block* block = free_list_; - free_list_ = free_list_->next; - return reinterpret_cast(block->data); - } - - void deallocate(T* p, size_t n) { - if (n != 1) return; - Block* block = reinterpret_cast(p); - block->next = free_list_; - free_list_ = block; - } -}; - -// Usage -std::vector> vec; - -// Arena allocator - bump allocator -class Arena { - std::byte* buffer_; - size_t size_; - size_t offset_ = 0; - -public: - Arena(size_t size) : size_(size) { - buffer_ = new std::byte[size]; - } - - ~Arena() { - delete[] buffer_; - } - - template - T* allocate(size_t n = 1) { - size_t alignment = alignof(T); - size_t space = size_ - offset_; - void* ptr = buffer_ + offset_; - - if (std::align(alignment, sizeof(T) * n, ptr, space)) { - offset_ = size_ - space + sizeof(T) * n; - return static_cast(ptr); - } - - throw std::bad_alloc(); - } - - void reset() { - offset_ = 0; - } -}; -``` - -## Move Semantics - -```cpp -#include -#include - -class Buffer { - size_t size_; - char* data_; - -public: - // Constructor - Buffer(size_t size) : size_(size), data_(new char[size]) {} - - // Destructor - ~Buffer() { delete[] data_; } - - // Copy constructor - Buffer(const Buffer& other) : size_(other.size_), data_(new char[size_]) { - std::copy(other.data_, other.data_ + size_, data_); - } - - // Copy assignment - Buffer& operator=(const Buffer& other) { - if (this != &other) { - delete[] data_; - size_ = other.size_; - data_ = new char[size_]; - std::copy(other.data_, other.data_ + size_, data_); - } - return *this; - } - - // Move constructor - Buffer(Buffer&& other) noexcept - : size_(other.size_), data_(other.data_) { - other.size_ = 0; - other.data_ = nullptr; - } - - // Move assignment - Buffer& operator=(Buffer&& other) noexcept { - if (this != &other) { - delete[] data_; - size_ = other.size_; - data_ = other.data_; - other.size_ = 0; - other.data_ = nullptr; - } - return *this; - } -}; - -// Perfect forwarding -template -void wrapper(T&& arg) { - process(std::forward(arg)); // Preserves lvalue/rvalue -} -``` - -## SIMD Optimization - -```cpp -#include // AVX/AVX2 -#include - -// Vectorized sum using AVX2 -float simd_sum(const float* data, size_t size) { - __m256 sum_vec = _mm256_setzero_ps(); - - size_t i = 0; - // Process 8 floats at a time - for (; i + 8 <= size; i += 8) { - __m256 vec = _mm256_loadu_ps(&data[i]); - sum_vec = _mm256_add_ps(sum_vec, vec); - } - - // Horizontal sum - alignas(32) float temp[8]; - _mm256_store_ps(temp, sum_vec); - float result = 0.0f; - for (int j = 0; j < 8; ++j) { - result += temp[j]; - } - - // Handle remaining elements - for (; i < size; ++i) { - result += data[i]; - } - - return result; -} - -// Vectorized multiply-add -void fma_operation(float* result, const float* a, const float* b, - const float* c, size_t size) { - for (size_t i = 0; i + 8 <= size; i += 8) { - __m256 va = _mm256_loadu_ps(&a[i]); - __m256 vb = _mm256_loadu_ps(&b[i]); - __m256 vc = _mm256_loadu_ps(&c[i]); - - // result[i] = a[i] * b[i] + c[i] - __m256 vr = _mm256_fmadd_ps(va, vb, vc); - _mm256_storeu_ps(&result[i], vr); - } -} -``` - -## Cache-Friendly Design - -```cpp -// Structure of Arrays (SoA) - better cache locality -struct ParticlesAoS { - struct Particle { - float x, y, z; - float vx, vy, vz; - }; - std::vector particles; -}; - -struct ParticlesSoA { - std::vector x, y, z; - std::vector vx, vy, vz; - - void update_positions(float dt) { - // All x coordinates are contiguous - better cache usage - for (size_t i = 0; i < x.size(); ++i) { - x[i] += vx[i] * dt; - y[i] += vy[i] * dt; - z[i] += vz[i] * dt; - } - } -}; - -// Cache line padding to avoid false sharing -struct alignas(64) CacheLinePadded { - std::atomic counter; - char padding[64 - sizeof(std::atomic)]; -}; - -// Prefetching -void process_with_prefetch(const int* data, size_t size) { - for (size_t i = 0; i < size; ++i) { - // Prefetch data for next iteration - if (i + 8 < size) { - __builtin_prefetch(&data[i + 8], 0, 1); - } - // Process current data - process(data[i]); - } -} -``` - -## Memory Pool - -```cpp -#include -#include - -template -class MemoryPool { - struct Chunk { - alignas(T) std::byte data[sizeof(T) * ChunkSize]; - }; - - std::vector> chunks_; - std::vector free_list_; - size_t current_chunk_offset_ = ChunkSize; - -public: - T* allocate() { - if (!free_list_.empty()) { - T* ptr = free_list_.back(); - free_list_.pop_back(); - return ptr; - } - - if (current_chunk_offset_ >= ChunkSize) { - chunks_.push_back(std::make_unique()); - current_chunk_offset_ = 0; - } - - Chunk* chunk = chunks_.back().get(); - T* ptr = reinterpret_cast( - &chunk->data[sizeof(T) * current_chunk_offset_++] - ); - return ptr; - } - - void deallocate(T* ptr) { - free_list_.push_back(ptr); - } - - template - T* construct(Args&&... args) { - T* ptr = allocate(); - new (ptr) T(std::forward(args)...); - return ptr; - } - - void destroy(T* ptr) { - ptr->~T(); - deallocate(ptr); - } -}; -``` - -## Copy Elision and RVO - -```cpp -// Return Value Optimization (RVO) -std::vector create_vector() { - std::vector vec{1, 2, 3, 4, 5}; - return vec; // RVO applies, no copy/move -} - -// Named Return Value Optimization (NRVO) -std::string build_string(bool condition) { - std::string result; - if (condition) { - result = "condition true"; - } else { - result = "condition false"; - } - return result; // NRVO may apply -} - -// Guaranteed copy elision (C++17) -struct NonMovable { - NonMovable() = default; - NonMovable(const NonMovable&) = delete; - NonMovable(NonMovable&&) = delete; -}; - -NonMovable create() { - return NonMovable{}; // Guaranteed no copy/move in C++17 -} - -auto obj = create(); // OK in C++17 -``` - -## Alignment and Memory Layout - -```cpp -#include - -// Control alignment -struct alignas(64) CacheAligned { - int data[16]; -}; - -// Check alignment -static_assert(alignof(CacheAligned) == 64); - -// Aligned allocation -void* aligned_alloc_wrapper(size_t alignment, size_t size) { - void* ptr = nullptr; - if (posix_memalign(&ptr, alignment, size) != 0) { - throw std::bad_alloc(); - } - return ptr; -} - -// Placement new with alignment -alignas(32) std::byte buffer[sizeof(Data)]; -Data* obj = new (buffer) Data(); -obj->~Data(); // Manual destruction needed -``` - -## Quick Reference - -| Technique | Use Case | Benefit | -|-----------|----------|---------| -| Smart Pointers | Ownership management | Memory safety | -| Move Semantics | Avoid copies | Performance | -| Custom Allocators | Specialized allocation | Speed + control | -| SIMD | Parallel computation | 4-8x speedup | -| SoA Layout | Sequential access | Cache efficiency | -| Memory Pools | Frequent alloc/dealloc | Reduced fragmentation | -| Alignment | SIMD/cache optimization | Performance | -| RVO/NRVO | Return objects | Zero-copy | diff --git a/.agents/skills/cpp-pro/references/modern-cpp.md b/.agents/skills/cpp-pro/references/modern-cpp.md deleted file mode 100644 index 1a541fb..0000000 --- a/.agents/skills/cpp-pro/references/modern-cpp.md +++ /dev/null @@ -1,304 +0,0 @@ -# Modern C++20/23 Features - -## Concepts and Constraints - -```cpp -#include - -// Define custom concepts -template -concept Numeric = std::integral || std::floating_point; - -template -concept Hashable = requires(T a) { - { std::hash{}(a) } -> std::convertible_to; -}; - -template -concept Container = requires(T c) { - typename T::value_type; - typename T::iterator; - { c.begin() } -> std::same_as; - { c.end() } -> std::same_as; - { c.size() } -> std::convertible_to; -}; - -// Use concepts for function constraints -template -T add(T a, T b) { - return a + b; -} - -// Concept-based overloading -template -void process(T value) { - std::cout << "Processing integer: " << value << '\n'; -} - -template -void process(T value) { - std::cout << "Processing float: " << value << '\n'; -} -``` - -## Ranges and Views - -```cpp -#include -#include -#include - -// Ranges-based algorithms -std::vector numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - -// Filter, transform, take - all lazy evaluation -auto result = numbers - | std::views::filter([](int n) { return n % 2 == 0; }) - | std::views::transform([](int n) { return n * n; }) - | std::views::take(3); - -// Copy to vector only when needed -std::vector materialized(result.begin(), result.end()); - -// Custom range adaptor -auto is_even = [](int n) { return n % 2 == 0; }; -auto square = [](int n) { return n * n; }; - -auto pipeline = std::views::filter(is_even) - | std::views::transform(square); - -auto processed = numbers | pipeline; -``` - -## Coroutines - -```cpp -#include -#include -#include - -// Generator coroutine -template -struct Generator { - struct promise_type { - T current_value; - - auto get_return_object() { - return Generator{std::coroutine_handle::from_promise(*this)}; - } - - std::suspend_always initial_suspend() { return {}; } - std::suspend_always final_suspend() noexcept { return {}; } - - std::suspend_always yield_value(T value) { - current_value = value; - return {}; - } - - void return_void() {} - void unhandled_exception() { std::terminate(); } - }; - - std::coroutine_handle handle; - - Generator(std::coroutine_handle h) : handle(h) {} - ~Generator() { if (handle) handle.destroy(); } - - bool move_next() { - handle.resume(); - return !handle.done(); - } - - T current_value() { - return handle.promise().current_value; - } -}; - -// Usage -Generator fibonacci() { - int a = 0, b = 1; - while (true) { - co_yield a; - auto next = a + b; - a = b; - b = next; - } -} - -// Async coroutine -#include - -struct Task { - struct promise_type { - Task get_return_object() { - return Task{std::coroutine_handle::from_promise(*this)}; - } - std::suspend_never initial_suspend() { return {}; } - std::suspend_never final_suspend() noexcept { return {}; } - void return_void() {} - void unhandled_exception() {} - }; - - std::coroutine_handle handle; -}; - -Task async_operation() { - std::cout << "Starting async work\n"; - co_await std::suspend_always{}; - std::cout << "Resuming async work\n"; -} -``` - -## Three-Way Comparison (Spaceship) - -```cpp -#include - -struct Point { - int x, y; - - // Auto-generate all comparison operators - auto operator<=>(const Point&) const = default; -}; - -// Custom spaceship operator -struct Version { - int major, minor, patch; - - std::strong_ordering operator<=>(const Version& other) const { - if (auto cmp = major <=> other.major; cmp != 0) return cmp; - if (auto cmp = minor <=> other.minor; cmp != 0) return cmp; - return patch <=> other.patch; - } - - bool operator==(const Version& other) const = default; -}; -``` - -## Designated Initializers - -```cpp -struct Config { - std::string host = "localhost"; - int port = 8080; - bool ssl_enabled = false; - int timeout_ms = 5000; -}; - -// C++20 designated initializers -Config cfg { - .host = "example.com", - .port = 443, - .ssl_enabled = true - // timeout_ms uses default -}; -``` - -## Modules (C++20) - -```cpp -// math.cppm - module interface -export module math; - -export namespace math { - template - T add(T a, T b) { - return a + b; - } - - class Calculator { - public: - int multiply(int a, int b); - }; -} - -// Implementation -module math; - -int math::Calculator::multiply(int a, int b) { - return a * b; -} - -// Usage in other files -import math; - -int main() { - auto result = math::add(5, 3); - math::Calculator calc; - auto product = calc.multiply(4, 7); -} -``` - -## constexpr Enhancements - -```cpp -#include -#include -#include - -// C++20: constexpr std::string and std::vector -constexpr auto compute_at_compile_time() { - std::vector vec{1, 2, 3, 4, 5}; - std::ranges::reverse(vec); - return vec[0]; // Returns 5 -} - -constexpr int value = compute_at_compile_time(); - -// constexpr virtual functions (C++20) -struct Base { - constexpr virtual int get_value() const { return 42; } - constexpr virtual ~Base() = default; -}; - -struct Derived : Base { - constexpr int get_value() const override { return 100; } -}; -``` - -## std::format (C++20) - -```cpp -#include -#include - -int main() { - std::string msg = std::format("Hello, {}!", "World"); - - // Positional arguments - auto text = std::format("{1} {0}", "World", "Hello"); - - // Formatting options - double pi = 3.14159265; - auto formatted = std::format("Pi: {:.2f}", pi); // "Pi: 3.14" - - // Custom types - struct Point { int x, y; }; -} - -// Custom formatter -template<> -struct std::formatter { - constexpr auto parse(format_parse_context& ctx) { - return ctx.begin(); - } - - auto format(const Point& p, format_context& ctx) const { - return std::format_to(ctx.out(), "({}, {})", p.x, p.y); - } -}; -``` - -## Quick Reference - -| Feature | C++17 | C++20 | C++23 | -|---------|-------|-------|-------| -| Concepts | - | ✓ | ✓ | -| Ranges | - | ✓ | ✓ | -| Coroutines | - | ✓ | ✓ | -| Modules | - | ✓ | ✓ | -| Spaceship | - | ✓ | ✓ | -| std::format | - | ✓ | ✓ | -| std::expected | - | - | ✓ | -| std::print | - | - | ✓ | -| Deducing this | - | - | ✓ | diff --git a/.agents/skills/cpp-pro/references/templates.md b/.agents/skills/cpp-pro/references/templates.md deleted file mode 100644 index 1b3f2e6..0000000 --- a/.agents/skills/cpp-pro/references/templates.md +++ /dev/null @@ -1,357 +0,0 @@ -# Template Metaprogramming - -## Variadic Templates - -```cpp -#include -#include - -// Fold expressions (C++17) -template -auto sum(Args... args) { - return (args + ...); // Unary right fold -} - -template -void print(Args&&... args) { - ((std::cout << args << ' '), ...); // Binary left fold - std::cout << '\n'; -} - -// Recursive variadic template -template -void log(T&& value) { - std::cout << value << '\n'; -} - -template -void log(T&& first, Args&&... rest) { - std::cout << first << ", "; - log(std::forward(rest)...); -} - -// Parameter pack expansion -template -struct TypeList { - static constexpr size_t size = sizeof...(Types); -}; - -template -auto make_tuple_advanced(Args&&... args) { - return std::tuple...>(std::forward(args)...); -} -``` - -## SFINAE and if constexpr - -```cpp -#include - -// SFINAE with std::enable_if (older style) -template -std::enable_if_t, T> -double_value(T value) { - return value * 2; -} - -template -std::enable_if_t, T> -double_value(T value) { - return value * 2.0; -} - -// Modern: if constexpr (C++17) -template -auto process(T value) { - if constexpr (std::is_integral_v) { - return value * 2; - } else if constexpr (std::is_floating_point_v) { - return value * 2.0; - } else { - return value; - } -} - -// Detection idiom -template -struct has_serialize : std::false_type {}; - -template -struct has_serialize().serialize())>> - : std::true_type {}; - -template -constexpr bool has_serialize_v = has_serialize::value; - -// Use with if constexpr -template -void save(const T& obj) { - if constexpr (has_serialize_v) { - obj.serialize(); - } else { - // Default serialization - } -} -``` - -## Type Traits - -```cpp -#include - -// Custom type traits -template -struct remove_all_pointers { - using type = T; -}; - -template -struct remove_all_pointers { - using type = typename remove_all_pointers::type; -}; - -template -using remove_all_pointers_t = typename remove_all_pointers::type; - -// Conditional types -template -struct conditional_type { - using type = T; -}; - -template -struct conditional_type { - using type = F; -}; - -// Compile-time type selection -template -struct best_integral_type { - using type = std::conditional_t>>; -}; - -// Check for member functions -template -struct has_reserve : std::false_type {}; - -template -struct has_reserve().reserve(size_t{}))>> - : std::true_type {}; -``` - -## CRTP (Curiously Recurring Template Pattern) - -```cpp -// Static polymorphism with CRTP -template -class Shape { -public: - double area() const { - return static_cast(this)->area_impl(); - } - - void draw() const { - static_cast(this)->draw_impl(); - } -}; - -class Circle : public Shape { - double radius_; -public: - Circle(double r) : radius_(r) {} - - double area_impl() const { - return 3.14159 * radius_ * radius_; - } - - void draw_impl() const { - std::cout << "Drawing circle\n"; - } -}; - -class Rectangle : public Shape { - double width_, height_; -public: - Rectangle(double w, double h) : width_(w), height_(h) {} - - double area_impl() const { - return width_ * height_; - } - - void draw_impl() const { - std::cout << "Drawing rectangle\n"; - } -}; - -// CRTP for mixin capabilities -template -class Printable { -public: - void print() const { - std::cout << static_cast(this)->to_string() << '\n'; - } -}; - -class User : public Printable { - std::string name_; -public: - User(std::string name) : name_(std::move(name)) {} - - std::string to_string() const { - return "User: " + name_; - } -}; -``` - -## Template Template Parameters - -```cpp -#include -#include -#include - -// Template template parameter -template class Container> -class Stack { - Container> data_; - -public: - void push(const T& value) { - data_.push_back(value); - } - - T pop() { - T value = data_.back(); - data_.pop_back(); - return value; - } - - size_t size() const { - return data_.size(); - } -}; - -// Usage with different containers -Stack vector_stack; -Stack deque_stack; -Stack list_stack; -``` - -## Compile-Time Computation - -```cpp -#include - -// Compile-time factorial -constexpr int factorial(int n) { - return n <= 1 ? 1 : n * factorial(n - 1); -} - -constexpr int fact_5 = factorial(5); // Computed at compile time - -// Compile-time prime checking -constexpr bool is_prime(int n) { - if (n < 2) return false; - for (int i = 2; i * i <= n; ++i) { - if (n % i == 0) return false; - } - return true; -} - -// Generate compile-time array of primes -template -constexpr auto generate_primes() { - std::array primes{}; - int count = 0; - int candidate = 2; - - while (count < N) { - if (is_prime(candidate)) { - primes[count++] = candidate; - } - ++candidate; - } - - return primes; -} - -constexpr auto first_10_primes = generate_primes<10>(); -``` - -## Expression Templates - -```cpp -// Lazy evaluation with expression templates -template -class VecExpression { -public: - double operator[](size_t i) const { - return static_cast(*this)[i]; - } - - size_t size() const { - return static_cast(*this).size(); - } -}; - -class Vec : public VecExpression { - std::vector data_; - -public: - Vec(size_t n) : data_(n) {} - - double operator[](size_t i) const { return data_[i]; } - double& operator[](size_t i) { return data_[i]; } - size_t size() const { return data_.size(); } - - // Evaluate expression template - template - Vec& operator=(const VecExpression& expr) { - for (size_t i = 0; i < size(); ++i) { - data_[i] = expr[i]; - } - return *this; - } -}; - -// Binary operation expression -template -class VecSum : public VecExpression> { - const E1& lhs_; - const E2& rhs_; - -public: - VecSum(const E1& lhs, const E2& rhs) : lhs_(lhs), rhs_(rhs) {} - - double operator[](size_t i) const { - return lhs_[i] + rhs_[i]; - } - - size_t size() const { return lhs_.size(); } -}; - -// Operator overload -template -VecSum operator+(const VecExpression& lhs, - const VecExpression& rhs) { - return VecSum(static_cast(lhs), - static_cast(rhs)); -} - -// Usage: a = b + c + d (no temporaries created!) -``` - -## Quick Reference - -| Technique | Use Case | Performance | -|-----------|----------|-------------| -| Variadic Templates | Variable arguments | Zero overhead | -| SFINAE | Conditional compilation | Compile-time | -| if constexpr | Type-based branching | Zero overhead | -| CRTP | Static polymorphism | No vtable cost | -| Expression Templates | Lazy evaluation | Eliminates temps | -| Type Traits | Type introspection | Compile-time | -| Fold Expressions | Parameter pack ops | Optimal | -| Template Specialization | Type-specific impl | Zero overhead | diff --git a/.gitignore b/.gitignore index 7130fa1..e8ebd77 100644 --- a/.gitignore +++ b/.gitignore @@ -4,12 +4,9 @@ release /dist/ __pycache__/ *.py[cod] -.claude .cache .idea -AGENTS.md .vscode -.opencode/ # Independently cloned component repositories. Their immutable release # revisions are recorded in components.lock.json. diff --git a/.opencode/plans/phase0_state_foundation.md b/.opencode/plans/phase0_state_foundation.md deleted file mode 100644 index b23b61b..0000000 --- a/.opencode/plans/phase0_state_foundation.md +++ /dev/null @@ -1,646 +0,0 @@ -# Phase 0: Decoupled State Management Foundation - Implementation Plan - -## Overview - -Build the foundation for decoupled state management where: -- **Plugin** never knows Core's internal state structure -- **Core** handles all serialization/deserialization internally -- **State format can change** without Plugin rebuilds -- **10 versions backward compatibility** with graceful degradation - -## Architecture - -``` -EchoionApi (stable interface) -├── ICoreInterface.hpp - Add state management methods -└── SerializedState.hpp - Opaque blob type - -EchoionCore (internal implementation) -├── StateSerializer.hpp/cpp - Versioned serialization using glaze -├── StateMigration.hpp/cpp - Migration between versions -├── StateV0.hpp, StateV1.hpp, ... - Version-specific state structures -└── Core.cpp - Implement state capture/restore - -EchoionPlugin (unchanged except CoreLoader) -└── CoreLoader.cpp - Use opaque blobs, no state parsing -``` - -## Files to Create/Modify - -### 1. EchoionApi Changes - -**File**: `EchoionApi/include/echoion/api/interfaces/CoreInterface.hpp` - -Add to `ICoreInterface`: -```cpp -// State management - opaque to caller -virtual Api::SerializedState saveState() = 0; -virtual Api::Result restoreState(const Api::SerializedState& state) = 0; - -// Version info -virtual uint32_t getStateFormatVersion() const = 0; -virtual bool canRestoreStateVersion(uint32_t version) const = 0; -``` - -**File**: `EchoionApi/include/echoion/api/base/SerializedState.hpp` (NEW) - -```cpp -#pragma once -#include -#include -#include - -namespace Echoion::Api { - -// Opaque state blob - contents are internal to Core -struct SerializedState { - std::vector data; // Serialized state data (JSON using glaze) - uint32_t version = 0; // Format version (for logging/debugging only) - std::string timestamp; // ISO 8601 timestamp when saved - - bool empty() const { return data.empty(); } - size_t size() const { return data.size(); } -}; - -// Constants -constexpr uint32_t MAX_SUPPORTED_STATE_VERSION_AGE = 10; // Support 10 versions back -constexpr uint32_t STATE_VERSION_NONE = 0; - -} // namespace Echoion::Api -``` - -### 2. EchoionCore Changes - -**File**: `EchoionCore/include/echoion/core/state/StateSerializer.hpp` (NEW) - -```cpp -#pragma once -#include "echoion/core/state/StateVersions.hpp" -#include -#include -#include -#include -#include - -namespace Echoion::Core { - -class StateSerializer { -public: - // Current version being used - static constexpr uint32_t CURRENT_VERSION = 1; - - // Serialize current state to opaque blob - static Api::SerializedState serialize(const StateV1& state); - - // Deserialize blob to current version (handles migration) - static Api::Result deserialize(const Api::SerializedState& blob); - - // Check if version is supported - static bool isVersionSupported(uint32_t version); - - // Get supported version range - static uint32_t getMinimumSupportedVersion(); - static uint32_t getCurrentVersion(); - -private: - // Migration functions - static Api::Result migrateToV1(const StateV0& old); - - // Extract version from JSON blob - static uint32_t extractVersion(const std::string& jsonStr); -}; - -} // namespace Echoion::Core -``` - -**File**: `EchoionCore/include/echoion/core/state/StateVersions.hpp` (NEW) - -```cpp -#pragma once -#include -#include -#include -#include -#include - -namespace Echoion::Core { - -// State V0 - Initial version (placeholder for future) -struct StateV0 { - // Minimal state for testing migration - std::vector trackIds; - float volume = 0.5f; -}; - -// State V1 - Current version -struct StateV1 { - // Playback state - struct PlaybackState { - Api::TrackInfo currentTrack; - std::chrono::milliseconds position{0}; - bool isPlaying = false; - bool isPaused = false; - float volume = 0.5f; - bool shuffle = false; - bool repeat = false; - }; - - // Queue entry with metadata - struct QueueEntryState { - Api::TrackInfo track; - uint64_t queueId = 0; - std::string addedBy; // Nickname or UID - std::string addedAt; // ISO 8601 - }; - - // Session state for RPC clients - struct SessionState { - uint64_t clientId = 0; - std::string authToken; - std::string lastActivity; // ISO 8601 - }; - - // Main state - std::optional playback; - std::vector queue; - std::vector sessions; - - // Version info - uint32_t version = 1; - std::string savedAt; // ISO 8601 -}; - -} // namespace Echoion::Core - -// Glaze JSON reflection for StateV1 -// (Add in StateVersions.cpp or at end of header) -template <> -struct glz::meta { - using T = Echoion::Core::StateV1; - static constexpr auto value = object( - "playback", &T::playback, - "queue", &T::queue, - "sessions", &T::sessions, - "version", &T::version, - "savedAt", &T::savedAt - ); -}; -``` - -**File**: `EchoionCore/include/echoion/core/state/StateMigration.hpp` (NEW) - -```cpp -#pragma once -#include "echoion/core/state/StateVersions.hpp" -#include -#include - -namespace Echoion::Core { - -// Handles migration between state versions -class StateMigration { -public: - // Migrate from any old version to current - static Api::Result migrate(uint32_t fromVersion, const std::string& jsonData); - - // Specific migrations - static StateV1 fromV0(const StateV0& v0); - - // Check if migration path exists - static bool canMigrate(uint32_t fromVersion); - -private: - // Migration chain: V0 -> V1 -> V2 -> ... - // Each version only knows how to migrate from previous -}; - -} // namespace Echoion::Core -``` - -**File**: `EchoionCore/src/state/StateSerializer.cpp` (NEW) - -```cpp -#include "echoion/core/state/StateSerializer.hpp" -#include "echoion/core/Logger.hpp" -#include - -namespace Echoion::Core { - -Api::SerializedState StateSerializer::serialize(const StateV1& state) { - // Serialize to JSON using glaze - std::string jsonStr; - auto ec = glz::write_json(state, jsonStr); - - if (ec) { - ECHOION_LOG_ERROR(std::format("Failed to serialize state: {}", - glz::format_error(ec, jsonStr))); - return Api::SerializedState{}; - } - - // Convert to binary blob - std::vector data(jsonStr.begin(), jsonStr.end()); - - return Api::SerializedState{ - .data = std::move(data), - .version = CURRENT_VERSION, - .timestamp = getCurrentTimestampISO8601() - }; -} - -Api::Result StateSerializer::deserialize(const Api::SerializedState& blob) { - if (blob.data.empty()) { - return std::unexpected(Api::Error( - Api::ErrorCode::InvalidArgument, - "Empty state blob" - )); - } - - // Convert blob to string - std::string jsonStr(blob.data.begin(), blob.data.end()); - - // Extract version - uint32_t dataVersion = extractVersion(jsonStr); - - ECHOION_LOG_INFO(std::format("Deserializing state version {}", dataVersion)); - - // Check if version is supported - if (!isVersionSupported(dataVersion)) { - if (dataVersion > CURRENT_VERSION) { - return std::unexpected(Api::Error( - Api::ErrorCode::IncompatibleVersion, - std::format("State version {} is from a newer Core. " - "Please update/restart to load this state.", - dataVersion) - )); - } else { - return std::unexpected(Api::Error( - Api::ErrorCode::IncompatibleVersion, - std::format("State version {} is too old. " - "Maximum supported age is {} versions.", - dataVersion, Api::MAX_SUPPORTED_STATE_VERSION_AGE) - )); - } - } - - // If current version, parse directly - if (dataVersion == CURRENT_VERSION) { - StateV1 state; - auto ec = glz::read_json(state, jsonStr); - - if (ec) { - return std::unexpected(Api::Error( - Api::ErrorCode::ParseError, - std::format("Failed to parse state: {}", - glz::format_error(ec, jsonStr)) - )); - } - - return state; - } - - // Otherwise, migrate - return StateMigration::migrate(dataVersion, jsonStr); -} - -bool StateSerializer::isVersionSupported(uint32_t version) { - if (version > CURRENT_VERSION) { - return false; // Future version - } - - uint32_t minVersion = getMinimumSupportedVersion(); - return version >= minVersion && version <= CURRENT_VERSION; -} - -uint32_t StateSerializer::getMinimumSupportedVersion() { - // Support 10 versions back, but not below 1 - return (CURRENT_VERSION > Api::MAX_SUPPORTED_STATE_VERSION_AGE) - ? CURRENT_VERSION - Api::MAX_SUPPORTED_STATE_VERSION_AGE - : 1; -} - -uint32_t StateSerializer::getCurrentVersion() { - return CURRENT_VERSION; -} - -uint32_t StateSerializer::extractVersion(const std::string& jsonStr) { - // Quick extraction without full parse - // Look for "version": N pattern - size_t pos = jsonStr.find("\"version\""); - if (pos != std::string::npos) { - pos = jsonStr.find(':', pos); - if (pos != std::string::npos) { - // Skip whitespace - pos++; - while (pos < jsonStr.size() && std::isspace(jsonStr[pos])) { - pos++; - } - // Parse number - if (pos < jsonStr.size() && std::isdigit(jsonStr[pos])) { - return static_cast(std::stoul(jsonStr.substr(pos))); - } - } - } - - // Default to 0 (unknown/legacy) - return 0; -} - -} // namespace Echoion::Core -``` - -**File**: `EchoionCore/src/state/StateMigration.cpp` (NEW) - -```cpp -#include "echoion/core/state/StateMigration.hpp" -#include "echoion/core/Logger.hpp" -#include -#include - -namespace Echoion::Core { - -Api::Result StateMigration::migrate(uint32_t fromVersion, const std::string& jsonData) { - ECHOION_LOG_INFO(std::format("Migrating state from version {} to {}", - fromVersion, StateSerializer::CURRENT_VERSION)); - - // Migration chain: fromVersion -> ... -> CURRENT_VERSION - // For now, only V0 -> V1 is implemented - // Future: V1 -> V2, V2 -> V3, etc. - - if (fromVersion == 0) { - StateV0 v0; - auto ec = glz::read_json(v0, jsonData); - if (ec) { - return std::unexpected(Api::Error( - Api::ErrorCode::ParseError, - "Failed to parse V0 state" - )); - } - return fromV0(v0); - } - - // Add more migrations here as versions evolve - // if (fromVersion == 1) { return fromV1(...); } - - return std::unexpected(Api::Error( - Api::ErrorCode::IncompatibleVersion, - std::format("No migration path from version {}", fromVersion) - )); -} - -StateV1 StateMigration::fromV0(const StateV0& v0) { - StateV1 v1; - - // Migrate queue - for (const auto& trackId : v0.trackIds) { - StateV1::QueueEntryState entry; - entry.track.id = trackId; - entry.track.title = "Unknown"; - entry.track.artist = "Unknown"; - v1.queue.push_back(std::move(entry)); - } - - // Migrate playback state - if (!v1.queue.empty()) { - StateV1::PlaybackState playback; - playback.currentTrack = v1.queue[0].track; - playback.volume = v0.volume; - v1.playback = std::move(playback); - } - - v1.version = 1; - v1.savedAt = getCurrentTimestampISO8601(); - - return v1; -} - -bool StateMigration::canMigrate(uint32_t fromVersion) { - return fromVersion >= StateSerializer::getMinimumSupportedVersion() && - fromVersion < StateSerializer::CURRENT_VERSION; -} - -} // namespace Echoion::Core -``` - -### 3. Core.cpp Modifications - -**File**: `EchoionCore/src/Core.cpp` - -Add state management implementation: - -```cpp -// Add includes -#include "echoion/core/state/StateSerializer.hpp" -#include "echoion/core/state/StateVersions.hpp" - -// Add to Core class implementation: - -Api::SerializedState Core::saveState() { - ECHOION_LOG_INFO("Saving Core state..."); - - StateV1 state; - - // Capture current playback state - if (currentTrack_.has_value()) { - StateV1::PlaybackState playback; - playback.currentTrack = currentTrack_->track; - playback.position = currentTrack_->position; - playback.isPlaying = isPlaying_; - playback.isPaused = isPaused_; - playback.volume = volume_; - playback.shuffle = shuffle_; - playback.repeat = repeat_; - state.playback = std::move(playback); - } - - // Capture queue - auto queueResult = musicManager_->getQueue(); - if (queueResult) { - for (const auto& entry : *queueResult) { - StateV1::QueueEntryState entryState; - entryState.track = entry.track; - entryState.queueId = entry.queueId; - entryState.addedBy = entry.addedBy; - entryState.addedAt = formatTimestamp(entry.addedAt); - state.queue.push_back(std::move(entryState)); - } - } - - // Capture sessions (from session manager) - // ... session capture code ... - - // Serialize - auto blob = StateSerializer::serialize(state); - - ECHOION_LOG_INFO(std::format("State saved: version={}, size={} bytes", - blob.version, blob.size())); - - return blob; -} - -Api::Result Core::restoreState(const Api::SerializedState& state) { - ECHOION_LOG_INFO(std::format("Restoring Core state: version={}", state.version)); - - auto result = StateSerializer::deserialize(state); - if (!result) { - return std::unexpected(result.error()); - } - - const StateV1& stateData = *result; - - // Restore playback - if (stateData.playback.has_value()) { - // Restore track, position, volume, etc. - // ... restoration code ... - } - - // Restore queue - for (const auto& entry : stateData.queue) { - // Add to music manager queue - // ... queue restoration ... - } - - // Restore sessions - // ... session restoration ... - - ECHOION_LOG_INFO("State restored successfully"); - return {}; -} - -uint32_t Core::getStateFormatVersion() const { - return StateSerializer::CURRENT_VERSION; -} - -bool Core::canRestoreStateVersion(uint32_t version) const { - return StateSerializer::isVersionSupported(version); -} -``` - -### 4. CoreLoader.cpp Modifications - -**File**: `EchoionPlugin/src/CoreLoader.cpp` - -Update hot reload to use opaque blobs: - -```cpp -Api::Result CoreLoader::hotReload(const std::filesystem::path& newLibraryPath) { - std::lock_guard lock(mutex_); - - if (!loaded_) { - return std::unexpected(Api::Error(Api::ErrorCode::NotFound, - "No core loaded to reload")); - } - - hotReloading_ = true; - - ECHOION_LOG_INFO("Starting hot reload with decoupled state..."); - - // Step 1: Save state as opaque blob (Plugin doesn't know contents) - Api::SerializedState stateBlob; - if (core_) { - stateBlob = core_->saveState(); - ECHOION_LOG_INFO(std::format("Saved state: version={}, size={} bytes", - stateBlob.version, stateBlob.size())); - } - - // Step 2: Unload old Core - auto unloadResult = unloadLibraryInternal(); - if (!unloadResult) { - hotReloading_ = false; - return unloadResult; - } - - // Step 3: Load new Core - auto targetPath = newLibraryPath.empty() ? currentLibraryPath_ : newLibraryPath; - - if (!std::filesystem::exists(targetPath)) { - hotReloading_ = false; - return std::unexpected(Api::Error( - Api::ErrorCode::NotFound, - std::format("New library not found: {}", targetPath.string()))); - } - - // ... (existing temp file copying code) ... - - auto loadResult = loadLibraryInternal(tempLibraryPath_); - if (!loadResult) { - hotReloading_ = false; - return loadResult; - } - - // Step 4: Restore state (Core handles migration internally) - if (!stateBlob.empty()) { - auto coreVersion = core_->getStateFormatVersion(); - auto stateVersion = stateBlob.version; - - ECHOION_LOG_INFO(std::format("Restoring state v{} to Core v{}", - stateVersion, coreVersion)); - - if (core_->canRestoreStateVersion(stateVersion)) { - auto restoreResult = core_->restoreState(stateBlob); - if (!restoreResult) { - ECHOION_LOG_ERROR(std::format("Failed to restore state: {}", - restoreResult.error().message)); - - // Check if it's a version issue - if (restoreResult.error().code == Api::ErrorCode::IncompatibleVersion) { - // Signal user to update/restart - ECHOION_LOG_WARNING("State version incompatible. " - "User needs to update/restart."); - // Optionally: notify through plugin interface - } - - // Continue with empty state - graceful degradation - } else { - ECHOION_LOG_INFO("State restored successfully"); - } - } else { - ECHOION_LOG_WARNING(std::format( - "Cannot restore state v{} in Core v{}. " - "Version age exceeds maximum supported ({} versions).", - stateVersion, coreVersion, Api::MAX_SUPPORTED_STATE_VERSION_AGE)); - // Continue with empty state - } - } - - currentLibraryPath_ = targetPath; - hotReloading_ = false; - - ECHOION_LOG_INFO("Hot reload complete"); - return {}; -} -``` - -## Implementation Order - -1. **Create Api types** (SerializedState.hpp) -2. **Update ICoreInterface** (add state methods) -3. **Create StateVersions.hpp** (StateV0, StateV1 structures) -4. **Create StateSerializer** (serialize/deserialize) -5. **Create StateMigration** (V0 -> V1 migration) -6. **Update Core.cpp** (implement saveState/restoreState) -7. **Update CoreLoader.cpp** (use opaque blobs) -8. **Test** (save/restore, migration, version limits) - -## Testing Checklist - -- [ ] Save state creates valid JSON blob -- [ ] Restore state works for current version -- [ ] Migration V0 -> V1 works correctly -- [ ] Version 11 versions old is rejected with clear message -- [ ] Version from future signals user to update/restart -- [ ] Empty state blob handled gracefully -- [ ] Corrupted state handled gracefully (don't crash) -- [ ] Hot reload preserves state across Core reload -- [ ] State survives 100 hot reloads without corruption - -## Success Criteria - -1. ✅ Plugin never inspects state blob contents -2. ✅ State format can change without Plugin rebuild -3. ✅ 10 versions backward compatibility -4. ✅ Clear signal to user when version > 10 versions old -5. ✅ Clear signal when state is from future version -6. ✅ Graceful degradation on errors -7. ✅ Uses only glaze (no new dependencies) - -Ready to start implementation? \ No newline at end of file diff --git a/.opencode/plans/robustness_plan.md b/.opencode/plans/robustness_plan.md deleted file mode 100644 index bb4327c..0000000 --- a/.opencode/plans/robustness_plan.md +++ /dev/null @@ -1,513 +0,0 @@ -# Echoion Robustness Improvement Plan - -## Executive Summary - -This plan addresses robustness for 100+ concurrent users on 4core/8GB hardware while maintaining the TeamSpeak plugin architecture with weekly hot-reload capability. - -**Key Architectural Principle**: Plugin and Core are completely decoupled. Core manages its own state serialization/deserialization internally. Plugin only handles opaque state blobs. - -**Dependencies**: Uses only existing dependencies (glaze, Boost, TBB, etc.). No new dependencies required. - -## Current Pain Points - -### 1. Connection Handling (Critical) -- **Issue**: Thread-per-client model creates unlimited threads (RpcServer.cpp:167-196) -- **Risk**: Resource exhaustion with 100+ users -- **Impact**: System instability, crashes - -### 2. No Resource Limits -- **Issue**: No memory/CPU limits, unbounded queue growth -- **Risk**: OOM kills, audio dropouts -- **Impact**: Service degradation for all users - -### 3. Missing Circuit Breakers -- **Issue**: yt-dlp failures cascade (no failure isolation) -- **Risk**: Repeated failed requests consume resources -- **Impact**: Bot becomes unresponsive - -### 4. Race Conditions -- **Issue**: Queue modifications lack proper synchronization -- **Risk**: Data corruption, crashes -- **Impact**: Inconsistent state - -### 5. No Health Monitoring -- **Issue**: No self-diagnostics or automatic recovery -- **Risk**: Silent failures accumulate -- **Impact**: Extended downtime - -## Decoupled State Management Architecture - -The key insight: **Plugin should never know what state Core needs to save**. Core handles all serialization internally using versioned formats. - -``` -┌─────────────────────────────────────────────────────────────────────┐ -│ TeamSpeak Client │ -│ ┌───────────────────────────────────────────────────────────────┐ │ -│ │ EchoionPlugin (.ts plugin) │ │ -│ │ │ │ -│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │ │ -│ │ │ Plugin │ │ Health │ │ StateManager │ │ │ -│ │ │ Interface │ │ Monitor │ │ (Opaque Blob) │ │ │ -│ │ └──────────────┘ └──────────────┘ └──────────────────────┘ │ │ -│ │ │ │ -│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │ │ -│ │ │ CoreLoader │ │ Connection │ │ Watchdog │ │ │ -│ │ │ (Hot Reload) │ │ Pool │ │ (Heartbeat) │ │ │ -│ │ └──────────────┘ └──────────────┘ └──────────────────────┘ │ │ -│ │ │ │ -│ │ Plugin ONLY knows: │ │ -│ │ - Core exports: saveState() -> opaque blob │ │ -│ │ - Core exports: restoreState(blob) -> success/failure │ │ -│ │ - Plugin stores blob temporarily, passes it back │ │ -│ │ - Plugin NEVER parses or inspects blob contents │ │ -│ │ │ │ -│ └───────────────────────────────────────────────────────────────┘ │ -└─────────────────────────────────────────────────────────────────────┘ - │ - │ dylib::library (hot reloadable) - │ - ▼ -┌─────────────────────────────────────────────────────────────────────┐ -│ EchoionCore (.ts library) │ -│ ┌───────────────────────────────────────────────────────────────┐ │ -│ │ │ │ -│ │ Core Internally Manages: │ │ -│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │ │ -│ │ │ StateVersion │ │ Migration │ │ StateSerializer │ │ │ -│ │ │ (v1, v2) │ │ Engine │ │ (glaze JSON) │ │ │ -│ │ └──────────────┘ └──────────────┘ └──────────────────────┘ │ │ -│ │ │ │ -│ │ State Format can change without Plugin rebuild: │ │ -│ │ - Old Core saves state v1 │ │ -│ │ - New Core loads state v1, migrates to v2 internally │ │ -│ │ - Plugin just passes the blob through │ │ -│ │ │ │ -│ └───────────────────────────────────────────────────────────────┘ │ -│ │ -│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ -│ │ Core │ │ RPC │ │ Resource │ │ -│ │ (Main) │◄─┤ Server │ │ Manager │ │ -│ └──────────────┘ └──────────────┘ └──────────────┘ │ -│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ -│ │ MusicManager │ │ YtDlpMgr │ │ Session │ │ -│ │ │ │ (Circuit │ │ Manager │ │ -│ │ │ │ Breaker) │ │ │ │ -│ └──────────────┘ └──────────────┘ └──────────────┘ │ -└─────────────────────────────────────────────────────────────────────┘ -``` - -## Decoupled State Management Design - -### Core Interface (Stable API) - -```cpp -// EchoionApi - Stable interface, never changes -class ICoreInterface { -public: - // State management - opaque to Plugin - virtual Api::SerializedState saveState() = 0; - virtual Api::Result restoreState(const Api::SerializedState& state) = 0; - - // Version info for compatibility - virtual uint32_t getStateFormatVersion() = 0; - virtual bool canRestoreStateVersion(uint32_t version) = 0; -}; - -// SerializedState is just an opaque blob -namespace Api { - struct SerializedState { - std::vector data; // Plugin never inspects this - uint32_t version; // Format version for logging only - std::string timestamp; // ISO 8601 for debugging - }; -} -``` - -### Core Internal State Management (Can Change Freely) - -Uses **glaze** (already available) for JSON serialization: - -```cpp -// EchoionCore - Internal implementation, can change anytime -class Core : public ICoreInterface { -private: - // Current state format version - static constexpr uint32_t CURRENT_STATE_VERSION = 2; - - // Internal state structure - can change without affecting Plugin - struct StateV2 { - std::vector queue; - std::optional currentTrack; - float volume; - // ... new fields can be added anytime - }; - - // Migration support for backward compatibility - class StateMigration { - public: - static StateV2 migrateFromV1(const glz::json_t& v1Data); - static StateV2 migrateFromV0(const glz::json_t& v0Data); - }; - -public: - Api::SerializedState saveState() override { - StateV2 currentState = captureCurrentState(); - - // Serialize to JSON using glaze (already available) - std::string jsonState; - auto ec = glz::write_json(currentState, jsonState); - if (ec) { - // Handle error - return Api::SerializedState{}; - } - - // Convert to binary blob - std::vector data(jsonState.begin(), jsonState.end()); - - return Api::SerializedState{ - .data = std::move(data), - .version = CURRENT_STATE_VERSION, - .timestamp = getCurrentTimestamp() - }; - } - - Api::Result restoreState(const Api::SerializedState& state) override { - // Convert blob back to string - std::string jsonStr(state.data.begin(), state.data.end()); - - // Parse version from JSON using glaze - uint32_t dataVersion = extractVersion(jsonStr); - - // Migrate if needed (all handled internally) - if (dataVersion == CURRENT_STATE_VERSION) { - // Direct parse - StateV2 restoredState; - auto ec = glz::read_json(restoredState, jsonStr); - if (ec) { - return std::unexpected(Api::Error( - Api::ErrorCode::ParseError, - "Failed to parse state" - )); - } - applyState(restoredState); - } else if (dataVersion == 1) { - // Parse as V1, then migrate - StateV1 v1State; - auto ec = glz::read_json(v1State, jsonStr); - if (ec) { - return std::unexpected(Api::Error( - Api::ErrorCode::ParseError, - "Failed to parse V1 state" - )); - } - StateV2 migrated = StateMigration::migrateFromV1(v1State); - applyState(migrated); - } else { - return std::unexpected(Api::Error( - Api::ErrorCode::IncompatibleVersion, - std::format("Cannot restore state version {} (current: {})", - dataVersion, CURRENT_STATE_VERSION) - )); - } - - return {}; - } -}; -``` - -### Plugin State Management (Simple Pass-Through) - -```cpp -// EchoionPlugin - Never touches state internals -class CoreLoader { -public: - Api::Result hotReload(const std::filesystem::path& newLibraryPath) { - // 1. Ask Core to save its state (opaque blob) - Api::SerializedState state; - if (core_) { - state = core_->saveState(); - logInfo(std::format("Saved state: version={}, size={} bytes", - state.version, state.data.size())); - } - - // 2. Unload old Core - auto unloadResult = unloadLibraryInternal(); - if (!unloadResult) return unloadResult; - - // 3. Load new Core - auto loadResult = loadLibraryInternal(newLibraryPath); - if (!loadResult) return loadResult; - - // 4. Ask new Core to restore state (it handles migration internally) - if (!state.data.empty()) { - auto coreVersion = core_->getStateFormatVersion(); - auto stateVersion = state.version; - - if (core_->canRestoreStateVersion(stateVersion)) { - auto restoreResult = core_->restoreState(state); - if (!restoreResult) { - logError(std::format("Failed to restore state v{} to Core v{}", - stateVersion, coreVersion)); - // Continue with empty state - graceful degradation - } else { - logInfo("State restored successfully"); - } - } else { - logWarning(std::format("Cannot restore state v{} in Core v{}", - stateVersion, coreVersion)); - // Continue with empty state - } - } - - return {}; - } -}; -``` - -### State Format Evolution Example - -```cpp -// Week 1: StateV1 -struct StateV1 { - std::vector queue; - float volume; -}; - -// Week 2: StateV2 (added new field) -struct StateV2 { - std::vector queue; - float volume; - bool shuffleMode; // NEW FIELD - - static V2 migrateFromV1(const V1& v1) { - return V2{ - .queue = v1.queue, - .volume = v1.volume, - .shuffleMode = false // Default for migrated states - }; - } -}; - -// Week 3: StateV3 (changed structure) -struct StateV3 { - struct Playlist { - std::vector tracks; - uint32_t currentIndex; - }; - - Playlist playlist; // Changed from flat queue - PlaybackSettings settings; // Grouped settings - - static V3 migrateFromV2(const V2& v2) { - return V3{ - .playlist = {.tracks = v2.queue, .currentIndex = 0}, - .settings = {.volume = v2.volume, .shuffle = v2.shuffleMode} - }; - } -}; - -// Plugin never needs to know about these changes! -``` - -## Implementation Phases - -### Phase 0: Decoupled State Management Foundation (Week 0) -**Goal**: Establish the decoupled architecture before other improvements - -**New Components**: -1. **StateSerializer.hpp/cpp** (Core) - Versioned state serialization using glaze -2. **StateMigration.hpp/cpp** (Core) - Migration between versions -3. Update **ICoreInterface.hpp** (Api) - Add state management methods -4. Refactor **Core.cpp** - Implement internal state management -5. Refactor **CoreLoader.cpp** - Use opaque state blobs - -**Key Design Decisions**: -- State format uses glaze JSON (already available, high performance) -- Version stored in JSON for easy inspection -- Migration chain: V0 -> V1 -> V2 -> V3 (each version only knows previous) -- Graceful degradation: if migration fails, start fresh (don't crash) - -### Phase 1: Connection Pool & Rate Limiting (Week 1) -**Goal**: Handle 100+ concurrent RPC connections safely - -**Components**: -1. **ConnectionPool.hpp/cpp** - Fixed-size worker thread pool (16 workers) -2. **RateLimiter.hpp/cpp** - Token bucket per client IP (30 req/min, burst 10) -3. Update **RpcServer.cpp** - Integrate connection pool - -**Dependencies**: Uses Boost.Asio (already available) - -### Phase 2: Resource Management (Week 1-2) -**Goal**: Prevent resource exhaustion on 4core/8GB - -**Components**: -1. **ResourceMonitor.hpp/cpp** - Track memory/CPU usage -2. Update **MusicManager.cpp** - Queue limits (500 tracks), memory caps -3. Update **YtDlpManager.cpp** - Limit concurrent operations (4 max) - -**Dependencies**: Uses standard library + TBB (already available) - -### Phase 3: Circuit Breakers & Fault Isolation (Week 2) -**Goal**: Prevent cascading failures - -**Components**: -1. **CircuitBreaker.hpp/cpp** - Generic circuit breaker pattern -2. Update **YtDlpManager.cpp** - Add circuit breaker (5 failures = 60s cooldown) -3. Update **NetworkClient.cpp** - Circuit breaker for HTTP calls - -**Dependencies**: Uses standard library only (chrono, atomic) - -### Phase 4: Session Management (Week 2-3) -**Goal**: Support 100+ users with proper session handling - -**Components**: -1. **SessionManager.hpp/cpp** - Track authenticated sessions (max 150) -2. Update **RpcServer.cpp** - Integrate session management -3. Sessions automatically included in Core's state blob (no Plugin changes!) - -**Dependencies**: Uses glaze (already available) + standard library - -### Phase 5: Health Monitoring & Self-Healing (Week 3) -**Goal**: Automatic recovery from failures - -**Components**: -1. **HealthMonitor.hpp/cpp** - System health checks (every 5s) -2. **Watchdog.hpp/cpp** - Detect hangs (15s timeout) -3. Update **Plugin.cpp** - Integrate health monitoring - -**Dependencies**: Uses standard library + Boost.Asio (already available) - -### Phase 6: Enhanced yt-dlp Management (Week 3-4) -**Goal**: Reliable auto-updates with fallback - -**Components**: -1. Update **YtDlpManager.cpp** - Background updates, atomic swap -2. **UpdateScheduler.hpp/cpp** - Weekly update scheduling (configurable window) - -**Dependencies**: Uses standard library only - -## Configuration Summary - -```json -{ - "robustness": { - "stateManagement": { - "format": "glaze_json", - "maxStateSizeMB": 10, - "migration": { - "maxVersionsBackward": 5, - "gracefulDegradation": true - } - }, - "rpc": { - "maxConnections": 150, - "workerThreads": 16, - "rateLimitRequestsPerMinute": 30, - "rateLimitBurst": 10, - "connectionTimeoutMs": 30000, - "sessionTimeoutMs": 3600000 - }, - "resourceLimits": { - "maxQueueSize": 500, - "maxMemoryMB": 1024, - "maxYtDlpConcurrent": 4, - "maxAudioBufferMB": 256, - "enableMemoryPressureHandling": true, - "memoryPressureThresholdMB": 768 - }, - "circuitBreaker": { - "ytDlpFailureThreshold": 5, - "ytDlpResetTimeoutMs": 60000, - "networkFailureThreshold": 3, - "networkResetTimeoutMs": 30000 - }, - "healthMonitor": { - "checkIntervalMs": 5000, - "unhealthyThresholdMs": 30000, - "enableAutoRecovery": true, - "maxConsecutiveRecoveries": 3 - }, - "watchdog": { - "heartbeatIntervalMs": 5000, - "timeoutMs": 15000, - "enableAutoReload": true - }, - "ytDlp": { - "autoUpdate": true, - "updateIntervalDays": 7, - "updateTimeWindow": "02:00-04:00", - "enableFallbackMirrors": true, - "requestTimeoutMs": 30000, - "enableRequestDeduplication": true - } - } -} -``` - -## Dependencies Used - -All dependencies are already in your project: - -1. **glaze** - JSON serialization for state management -2. **Boost.Asio/Beast** - Connection pool, RPC server -3. **Boost.UUID** - Session IDs -4. **TBB** - Parallel algorithms for resource monitoring -5. **standard library** - Circuit breakers, rate limiters, health monitoring - -**No new dependencies required!** - -## Benefits of Decoupled State Management - -1. **Plugin Stability**: Plugin code never changes when Core state format changes -2. **Rapid Iteration**: Modify Core state structure without rebuilding Plugin -3. **Backward Compatibility**: Old states automatically migrate to new format -4. **Forward Compatibility**: Can detect if state is from future version -5. **Debugging**: State blobs can be saved to disk and inspected manually (JSON) -6. **Testing**: Easy to create test states for specific scenarios -7. **Performance**: Uses glaze (high-performance JSON library you already have) - -## Hot-Reload Flow with Decoupled State - -``` -1. Core V1 running, users connected, music playing - │ - ▼ -2. Developer builds Core V2 (new state format) - │ - ▼ -3. File watcher detects new .ts library - │ - ▼ -4. Plugin asks Core V1: saveState() - Core V1 serializes internal state to blob (format V1) - │ - ▼ -5. Plugin unloads Core V1, loads Core V2 - │ - ▼ -6. Plugin asks Core V2: restoreState(blob V1) - Core V2 internally migrates V1 -> V2 - Users stay connected, queue preserved - │ - ▼ -7. Core V2 running with migrated state - Zero downtime, zero Plugin changes -``` - -## Success Metrics - -- **Uptime**: >99.9% -- **Concurrent Users**: 100+ without degradation -- **Memory**: Stable <1GB under load -- **Recovery Time**: <5s from failure -- **Hot-Reload**: Zero user impact, zero Plugin rebuilds -- **State Migration**: 100% success rate for versions within 5 releases - -## Next Steps - -1. **Review this updated plan** - Does the decoupled state approach meet your needs? -2. **State format preferences** - glaze JSON OK, or prefer binary (using std::vector with custom format)? -3. **Migration depth** - Support 5 versions back, or more/less? -4. **Start implementation** - Begin with Phase 0 (state management foundation)? - -The decoupled architecture means you can iterate on Core weekly without ever touching Plugin code again, and we're only using dependencies you already have!