Add async/resilience/reflection primitives + FSM v2 rewrite

A round of new universal capabilities (all generic — templated/reflection
based, no app coupling), verified by the test suite (1103 passing):

Data reflection:
- Reflect.hpp now (de)serializes chrono::duration, chrono::time_point,
  std::variant (tagged), std::array, and non-string-keyed std::map;
  Meta.hpp gains is_time_point_v et al.

Async:
- EventBus gains Mode::Async (worker-thread dispatch + flush()).
- ThreadPool gains a bounded queue, try_submit(), and rejection stats.

New modules / containers:
- Resilience: TokenBucket, KeyedRateLimiter<Key>, CircuitBreaker,
  ResourceMonitor.
- Containers: BufferPool<T> (size-class buffer reuse) and Cache<K,V>
  (per-entry TTL, LRU/LFU/FIFO eviction, hit/miss stats).
- System: process/CPU/memory metrics (Metrics.hpp) and a streaming
  Process API.

Plus FSM v2 (typed Success/Failure, sub-machines, parallel regions,
history states, deferred events), Configuration/Logging reflection
helpers, and the accompanying test suites.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 4.8 committed 2026-06-22 15:45:16 +03:00
1 parent 43b5a81504
commit 80293ee56f
93 files changed
+8500 -3312

No files matched your search

+65 -27
View File
@@ -34,7 +34,7 @@ VoidLibrary is a C++26 modular shared library organized as **umbrella modules**
| Module | Type | Contents |
|---|---|---|
| `Core` | INTERFACE | Scope, Lazy, Counted, Flags, Hash, Bits, Uuid, TypeList, TypeMap, Variant |
| `Core` | INTERFACE | **Meta** (shared reflection layer), Scope, Lazy, Counted, Flags, Hash, Bits, Uuid, TypeList, TypeMap, Variant |
| `Functional` | INTERFACE | Pipeline (+Curry, +Memo), Either (+Opt), Result, Retry |
| `Containers` | INTERFACE | Ring, Pool, PriorityQueue, LRU, Trie, Graph, DisjointSet, Bitset, Interval |
| `Math` | INTERFACE | Vec/Mat, Matrix, Numeric, Random, Histogram |
@@ -53,6 +53,23 @@ VoidLibrary is a C++26 modular shared library organized as **umbrella modules**
`include/Void/Detail/` (e.g. `Enum.hpp` — P2996 enum reflection) is not a module; it is header-only and reachable from every module via the shared include root.
### Reflection layer (`Void::Meta`, `include/Void/Core/Meta.hpp`)
The single shared C++26 P2996 layer the whole codebase reflects through. Header-only, in `Core`:
- **Shape traits (one source):** `is_optional_v`, `is_vector_v`, `is_string_map_v`, `is_duration_v`, `Leaf`, `Struct` — the trait sets that used to be duplicated in `Data/Reflect.hpp` and `Configuration/Bind.hpp` now live here.
- **Member walk:** `members_v<T>` (the one `nonstatic_data_members_of` + `define_static_array`), `field_count<T>()`, `field_names<T>()`, `for_each_field(obj, fn)`, `type_name<T>()`.
- **Annotations:** `Str` (a *value-based fixed-capacity string* — annotation payloads can't be `std::string_view`/`const char*`, which aren't structural), `has_annotation<Tag>(member)`, `annotation_of<Tag>(member)`. **Member annotations work; enumerator annotations do not parse in this GCC** (so enum labels stay identifier-based).
- **Generic algorithms:** `equal`/`compare`/`hash` (member-folded, recursive) and `repr` (formatter → `.format()` → reflected `Type{a: 1, …}`). `Functional/Detail/Repr.hpp` is now a thin alias over `Meta::repr`.
- **Enum utilities (extend `Detail/Enum.hpp`):** `enum_name`/`enum_parse`/`enum_cast` (re-exported) plus `enum_count<E>`, `enum_values<E>()`, `enum_entries<E>()`.
**Annotation vocabularies** (small structs over `Meta::Str`, used as `[[= ns::Tag{…}]]`):
- `Json::Rename{"k"}` / `Json::Skip` / `Json::Required` / `Json::Flatten` (`Data/Reflect.hpp`).
- `Configuration::Key{"k"}` / `Configuration::Required` (`Bind.hpp`).
- `Argparse::Short{'v'}` / `Help{"…"}` / `Name{"…"}` / `Positional` (`Argparse.hpp`).
- `Fsm::entry` (FSM entry designation).
**Other reflective consumers:** `Data/Csv.hpp` maps a flat struct to/from a CSV `Row` (`header_row<T>()`, `to_row`, `from_row`); `Logging::FieldScope::from(struct)` reflects a struct's fields into structured log fields; `Core/Flags.hpp` renders/parses a flag set by enumerator name (`Flags::to_string`/`parse` via `enum_entries`); `Containers/Debug.hpp` `debug_dump(range)` renders elements via `repr`; `Service::interface_name<I>()` gives a reflected default service name; the FSM `entry` marker now goes through `Meta::has_annotation`. Non-aggregate structs (e.g. `Math::Vec3`) reflect for read (`repr`/`equal`/`hash`) via `Meta` even though they're excluded from the aggregate-only JSON path; aggregates like `Semver::Version` are JSON-reflectable directly.
### Module system
`cmake/Module.cmake` defines `void_add_module(NAME ...)`. The root `CMakeLists.txt` auto-discovers every subdirectory under `src/` and calls it (or includes the dir's `module.cmake` if present), then calls `void_finalize_modules()`. A module with only headers becomes an `INTERFACE` library; one with `.cpp` sources becomes `SHARED` — except `Testing`, which is special-cased to `STATIC`.
@@ -82,29 +99,51 @@ All tests compile into **one binary**, `build/tests/VoidTests` (registered as th
#### Writing a test
Tests are free functions (or methods on a `Void::Testing::Fixture` subclass) returning `Void::Testing::Test` or `Void::Testing::DisabledTest` (both aliases for `void`). **Never write the registration code yourself** — `cmake/VoidTestScanner.cmake` parses each `.cpp` at configure time, generates `*.void_tests.cpp` shims with `Void::Testing::Detail::test_registrar` calls, and rewrites the original source to `HEADER_FILE_ONLY`.
The primary model is a **reflection-based suite** (`Void/Testing/Suite.hpp`):
derive a struct from `Void::Testing::Suite<YourSuite>` (CRTP). Every public,
0-argument member returning `Void::Testing::Test`/`DisabledTest` (both `void`) —
except `setup`/`teardown` — is auto-registered by reflecting the struct. **No
macros, no CMake scan, no registrar line, no instance**: a `[[gnu::used]]` static
in the base forces registration at program start, even though the suite is never
constructed for its own sake. Metadata is **annotations** (reuse `Meta::Str`):
```cpp
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Testing/Suite.hpp>
Void::Testing::Test addition() { Void::Testing::expect_eq(1 + 1, 2); }
// @tag integration, database
Void::Testing::Test db_query() { Void::Testing::expect(true); }
// @skip "Feature #42 not implemented"
Void::Testing::DisabledTest broken() { Void::Testing::fail("not ready"); }
namespace {
struct MathTests : Void::Testing::Suite<MathTests> {
void setup() {} // optional, per-test
Void::Testing::Test addition() { Void::Testing::expect_eq(1 + 1, 2); }
[[= Void::Testing::tag("integration")]] Void::Testing::Test db() { /*…*/ }
[[= Void::Testing::skip("Feature #42")]] Void::Testing::Test wip() { /*…*/ }
};
}
```
Fixture-based tests work the same way — declare a class derived from `Void::Testing::Fixture`, override `setup()`/`teardown()`, and write methods returning `Test`/`DisabledTest`.
- Suite label = the struct's name; override with `[[= Testing::name("Math")]]` on the struct.
- `[[= Testing::tag("x")]]` (repeatable) attaches tags; `[[= Testing::skip("reason")]]` disables a test (replaces `DisabledTest` + `@skip`).
- `setup()`/`teardown()` run around each test method (fresh instance per test) — the reflection-discovered replacement for the old `Fixture` base. File/line come from `std::meta::source_location_of`.
Comment metadata (immediately preceding the function):
- `// @tag a, b, c` — attaches tags.
- `// @skip <reason>` — marks the test skipped with a reason; quoted or unquoted strings both work. `DisabledTest` implies `@skip "disabled"` if no explicit reason is given.
- Any non-comment, non-empty line resets the accumulated tags/skip — keep the comment block adjacent to the function.
Global-namespace reflection ICEs this GCC and an `#include` can't be namespace-wrapped, so tests must live in a *named* struct — hence the CRTP `Suite` wrapper rather than bare free functions.
The sweep in `cmake/VoidTesting.cmake` auto-applies the scan to every executable that transitively links `Void::Testing`. To opt a target out, set the `VOID_TESTING_NO_AUTO_SCAN` property; to opt in explicitly (e.g. for a target that doesn't link `Void::Testing` directly), call `void_add_tests(<target>)`.
**Scanner (permanent fallback).** Free-function tests
(`Void::Testing::Test name()` with `// @tag`/`// @skip` comments) are still
picked up by `cmake/VoidTestScanner.cmake`, which generates `*.void_tests.cpp`
shims (the original `.cpp` is `HEADER_FILE_ONLY`). This path is **kept as a
fallback** — both for compilers without `<meta>` and for tests written in the
old free-function style. The two models coexist with no migration required: a
`Suite`-only file produces an empty shim and self-registers via reflection (the
scanner always emits a valid `#include` of the source), while free-function files
register through the scanner. Use `Suite` for new tests; existing free-function
files keep working as-is.
**Mock reflection** (`Void/TestingMock/Reflect.hpp`): `method_names<I>()` lists an
interface's virtual methods; `covers<Mock, I>()` is a compile-time check that a
hand-written mock implements all of `I`. Full auto-mock (synthesizing the virtual
overrides) is **not possible** here — `<meta>` has `define_aggregate` (it can
generate a `MockFunction<Sig>` member per virtual) but no code injection for the
override bodies, so `MockFunction<Sig>` members are still wired up by hand.
### Logging
@@ -134,7 +173,7 @@ Other key points:
### Configuration module
`Configuration::Config`: flat string store with dotted keys. Sources (overlay-composable, last wins): `from_env`, `from_env_prefix("APP_")` (`__`→`.`, lowercased), `from_file` (KEY=VALUE), `from_ini`, `from_json` (flattened), `from_args` (`--key=value`). Typed access `get_as<T>` / `get_or_as<T>` (numbers, bool spellings, enums by name via reflection, chrono durations like "250ms"). `subtree(prefix)` strips a prefix. `Bind.hpp`: `bind<T>(cfg, prefix)` fills an aggregate via P2996 (defaults = schema). `Watch.hpp`: `ConfigWatch` reloads a file on change with per-key diff (debounced polling via `FileSystem::FileWatcher` in `System`).
`Configuration::Config`: flat string store with dotted keys. Sources (overlay-composable, last wins): `from_env`, `from_env_prefix("APP_")` (`__`→`.`, lowercased), `from_file` (KEY=VALUE), `from_ini`, `from_json` (flattened), `from_args` (`--key=value`). Typed access `get_as<T>` / `get_or_as<T>` (numbers, bool spellings, enums by name via reflection, chrono durations like "250ms"). `subtree(prefix)` strips a prefix. `Bind.hpp`: `bind<T>(cfg, prefix)` fills an aggregate via `Void::Meta` (defaults = schema); members may carry `[[= Configuration::Key{"…"}]]` (key override) / `[[= Configuration::Required{}]]` (error if absent). `Argparse.hpp` also offers reflective `parse<Opts>(argc, argv)` — define an options struct, annotate fields (`arg::Short`/`Help`/`Name`/`Positional`), parse straight into it (bool→flag, string→option w/ default, optional<string>→option) — alongside the fluent `Parser`. `Watch.hpp`: `ConfigWatch` reloads a file on change with per-key diff (debounced polling via `FileSystem::FileWatcher` in `System`).
### Service module
@@ -147,32 +186,31 @@ Other key points:
### Fsm module (inheritance + coroutine workflow)
`Void::Fsm::Machine<Derived>` (CRTP) — derive it; declare states as nested structs deriving the **single** base `State`. There is no statechart/event-graph; states drive themselves.
`Void::Fsm::Machine<Derived>` (CRTP) — derive it. Declare the states as a nested struct of forward declarations, `struct States { struct First; struct Second; … };`, each deriving the **single** base `State`; **realise them out-of-line** (typically in a `.cpp`: `struct M::States::First : M::State { Coro::Task<StateKey>> run(){…} };`). The base **auto-registers** them by reflecting `members_of(^^States)` — the first declared state is the initial one unless `using Initial = States::S;`. There is no statechart/event-graph and **no declarative transition table**: states drive themselves and handle events imperatively. Define the constructor out-of-line, after the realisations, so the states are complete when the base registers them.
**One `State`, signature-inferred roles.** There is one base class; the engine infers what each state does **purely from member signatures** via P2996 (`Detail/Roles.hpp`) — no `override`, no framework-mandated names:
- **entry** — a member returning `Step`/`Coro::Task<Step>` with no params (`Task<Step> run()`); a **startup-entry** overload takes the launch data (`Task<Step> run(Cfg)`), used when reached via `startMachine` (data routed there, not the constructor).
- **reactive** — a member taking `TransitionBuilder&` (`void transitions(TransitionBuilder& on)`); the engine runs its declared table.
- **continuation handlers** — two members distinguished by parameter type, `ok(ChildSuccess auto s)` / `no(ChildFailure auto f)` (`s.value`/`f.value` are the sub's typed Success/Failure); the engine picks by the launched sub's outcome.
- **entry** — a member returning `State`/`Coro::Task<StateKey>>` with no params (`Task<State> run()`); a **startup-entry** overload takes the launch data (`Task<State> run(Cfg)`), used when reached via `startMachine` (data routed there, not the constructor). Events are awaited imperatively in the entry (`co_await await_event<E>()`). The nullary `run()` and the startup overload `run(Cfg)` coexist: the overload is chosen when the machine is launched with data (`startMachine<…>(cfg)`), the nullary entry otherwise. When several members match the entry signature, the one annotated `[[= Void::Fsm::entry]]` wins; unannotated, the first-declared match is used.
- **continuation handlers** — two members distinguished by parameter type, `ok(ChildSuccess s)` / `no(ChildFailure f)`; the sub's typed Success/Failure rides type-erased in the result struct and is read with `s.as<T>()`/`f.as<T>()` (`ChildSuccess`/`ChildFailure` are concrete types, no `auto`). The engine picks by the launched sub's outcome.
Mechanics: at `add<S>()` a `Detail::make_driver<S>()` reflection thunk is stored (reactive table vs entry, chosen by whether `S` has a `TransitionBuilder&` member); `drive()` calls the thunk. `startMachine<Sub, Next>(data…)` (knows `Sub`, `Next`, and the data types) builds a `Launch` step carrying a launcher (runs `Sub`, injecting `data` into its initial state's startup-entry) and a dispatcher (`Detail::dispatch_result<Next, Sub>`) that builds `ChildSuccessBox<…>`/`ChildFailureBox<…>` and calls `Next`'s matching handler. The reflection selectors must **not** be coroutines (`template for` + member splicing fails inside a coroutine body in this GCC build), so they `return` a `Task<Step>` (wrapping plain `Step` via `ready_task`). The discovery is invocability-based — **no parameter-type reflection (P3096)**.
Mechanics: at `add<S>()` a `Detail::make_driver<S>()` reflection thunk (runs the entry) is stored; `drive()` calls the thunk. State-list reflection lives in `Detail/StateList.hpp` (`register_states_from`, `FirstStateOf`/`InitialStateOf`, `states_contains` for the `next<S>()` / `startMachine<,Next>` compile-time target check). `startMachine<Sub, Next>(data…)` (knows `Sub`, `Next`, and the data types) builds a `Launch` step carrying a launcher (runs `Sub`, injecting `data` into its initial state's startup-entry) and a dispatcher (`Detail::dispatch_result<Next, Sub>`) that wraps the sub's outcome in a type-erased `ChildSuccess`/`ChildFailure` (value in a `std::any`, read via `.as<T>()`) and calls `Next`'s matching handler. The reflection selectors must **not** be coroutines (`template for` + member splicing fails inside a coroutine body in this GCC build), so they `return` a `Task<State>` (wrapping plain `State` via `ready_task`). The discovery is invocability-based — **no parameter-type reflection (P3096)**. Machine-level entry/exit are overridable virtuals `on_machine_enter()`/`on_machine_exit()`; per-state entry/exit are the state's own `on_enter()`/`on_exit()`.
**Typed results.** A machine declares its result types as nested types *reflected by name* — `struct Success {…}` (or `using Success = int;`) and `struct Failure {…}`, each defaulting to `void`. `Outcome = std::expected<Success, Failure>` (a void failure becomes `std::monostate`); `succeed(Success{…})` / `fail(Failure{…})` carry them (nullary when void). Engine/system faults (no initial state, jump to an unregistered state, a state with no entry) are a **separate `FsmError` channel** — `status()==Faulted`, `system_error()` returns the `FsmError`, never the typed `Failure`. Because `Derived` is incomplete at CRTP base instantiation, the engine stores outcomes type-erased and rebuilds the typed `Outcome` in `wait()`/`run_blocking()` (function templates defaulted on `Derived`); `Detail::SuccessOf`/`FailureOf<Derived>` resolve the nested types by plain name lookup (`Detail/Result.hpp`).
Header layout (include `<Void/Fsm/Fsm.hpp>` — a thin umbrella): `Machine.hpp` (the `Machine<Derived>` template + `States<>`, the single nested `State` base, lifecycle, events, nesting, persistence); `Detail/Roles.hpp` (the signature-inference: `ChildSuccess`/`ChildFailure` concepts + boxes, `invoke_entry`/`invoke_startup`/`invoke_handler`/`dispatch_result`/`make_driver`/`has_transitions`); `Detail/Result.hpp` (`SuccessOf`/`FailureOf`/`OutcomeOf<Derived>`); `Detail/Reactive.hpp` (the declarative transition DSL as standalone `Detail::TransitionBuilder`/`EventClause`/`AfterClause`/`TransitionTable<Derived>` templates); `Detail/Awaiter.hpp` (one `Detail::EventAwaiter` behind `make_event_awaiter`, used by all `await_*`); `Detail/Introspect.hpp` (`StateInfo`/`EdgeInfo` + `to_mermaid`); `Detail/Engine.{hpp,cpp}` (the non-template `ExecutionContext` + `StateBase` — only `on_enter`/`on_exit` remain virtual); `Detail/TypeName.hpp` (`type_name<T>()`).
Header layout (include `<Void/Fsm/Fsm.hpp>` — a thin umbrella): `Machine.hpp` (the `Machine<Derived>` template, the single nested `State` base, lifecycle, events, nesting, persistence); `Detail/StateList.hpp` (state-list reflection over the nested `struct States`: `register_states_from`, `FirstStateOf`/`InitialStateOf`, `states_contains`); `Detail/Roles.hpp` (the signature-inference: `ChildSuccess`/`ChildFailure` result structs, the `entry` annotation marker, `invoke_entry`/`invoke_startup`/`invoke_handler`/`dispatch_result`/`make_driver`); `Detail/Result.hpp` (`SuccessOf`/`FailureOf`/`OutcomeOf<Derived>`); `Detail/Awaiter.hpp` (one `Detail::EventAwaiter` behind `make_event_awaiter`, used by all `await_*`); `Detail/Introspect.hpp` (`StateInfo` + node-level `to_mermaid`); `Detail/Engine.{hpp,cpp}` (the non-template `ExecutionContext` + `StateBase` — only `on_enter`/`on_exit` remain virtual); `Detail/TypeName.hpp` (`type_name<T>()`).
- **Async by default**: a non-template `Detail::ExecutionContext` (`src/Fsm/Engine.cpp`) owns one `Async::ManualExecutor` + worker thread + a lock-free MPSC event queue + a typed event mailbox. A single consumer (worker, or the embedder via `pump()` when `MachineOptions{.own_worker=false}`) touches all mutable state, so state code is lock-free/single-threaded. `start()`/`run_blocking()`/`wait()` for worker mode; `pump()` for embedder mode (deterministic tests).
- **Events**: `co_await await_event<E>()` consumes the oldest queued `E` (typed mailbox), suspending until one arrives; `post<E>(e)` is lock-free from any thread.
- **Nesting**: `co_await run_child<Sub>(args...)` runs a child on the *same* executor (shared events + services) and yields its `Outcome` (`std::expected<R, FsmError>`) — the imperative form, branch on it yourself.
- **Sub-machine continuations (declarative)**: `co_return startMachine<Sub, Next>(args...)` launches `Sub` (constructed from `args`, on the shared executor/events/services), then enters `Next` and the engine **finds on its own which method to call** — `Next` derives `Continue<Sub::result_type>` and the engine dispatches to `on_success(R)` or `on_failure(FsmError)` by the outcome (a `Continue<void>` takes a nullary `on_success()`). `Next` must derive `Continue<R>` (a `static_assert` enforces it) and be in `States<>`. A `Continue` handler may itself return another `startMachine` (chaining) or any normal `Step`. Mechanics: a `Step::Kind::Launch` carries the target + a type-erased launcher; `drive()` runs it, stashes the `LaunchResult`, and the entered state's `resume()` (overridden by `Continue<R>`) dispatches — a plain state entered with a pending result just `run()`s.
- **Sub-machine continuations (declarative)**: `co_return startMachine<Sub, Next>(args...)` launches `Sub` (constructed from `args`, on the shared executor/events/services), then enters `Next` and the engine **finds on its own which method to call** — `Next` derives `Continue<Sub::result_type>` and the engine dispatches to `on_success(R)` or `on_failure(FsmError)` by the outcome (a `Continue<void>` takes a nullary `on_success()`). `Next` must derive `Continue<R>` (a `static_assert` enforces it) and be in `States<>`. A continuation handler may itself return another `startMachine` (chaining) or any normal `State`. `Next` must be in `States{…}` (compile-time checked). Mechanics: a `State::Kind::Launch` carries the target + a type-erased launcher; `drive()` runs it, stashes the `LaunchResult`, and the entered state's bound dispatcher routes it to the matching `ok`/`no` handler — a plain state entered with no pending result just runs its entry.
- **Parallel / orthogonal regions**: `co_await run_parallel<A, B, …>()` runs several sub-machines concurrently on the shared executor (interleaved — when one parks on an event, another runs; **multi-waiter mailbox**) and joins **all**, yielding `std::tuple<A::Outcome, …>`. `run_parallel_any<…>()` resolves on the **first** to finish → `std::variant<…::Outcome…>`; losers keep running cooperatively (not preemptible), so they're kept alive by the spawned tasks until they finish — a loser parked forever leaks its frame until the machine stops. Children are default-constructed and share events/services. Join uses a small latch coroutine (`Async::spawn` + a completion counter); single-consumer ⇒ no lock.
- **Composite sub-states (hierarchy)**: `co_await run_region<Sub>()` is `run_child` with introspection — the calling state's `on_enter`/`on_exit` wrap the child region, and the parent's `state_path()` reports the parent→child chain (`{Composite, …child leaf}`) while it runs. Map the child's `Outcome` to a sibling transition (`r ? next<Done>() : next<Recover>()`). Parent-level multi-event handling via `co_await await_any<E1, E2, …>()` → `std::variant<Es...>` (e.g. a region waits for `Tick` or `Cancel` at one level). Coroutines aren't preemptible mid-flight, so child cancellation is **cooperative**: the region awaits a shared `Cancel` event (events route to the deepest awaiter) and returns a failing `Outcome` the parent maps — no frame is abandoned.
- **Dynamic**: `add<S>()` / `add_if<S>(cond)`; `next<unregistered>` fails; `has_state<S>()` lets a state branch.
- **Direct control**: fluent `send(e1, e2, …)` (variadic `post`); free in-state jumps via `goto_state<S>()` (any registered state, no declared transition); external `jump<S>()` applied at the next transition boundary (race-safe, non-preemptive — a running state isn't interrupted); lifecycle `reset()` / `restart()` / `restart_at<S>()` and `pause()` / `resume()` (paused = worker stops draining, posted events buffer); Idle-only mutation `remove<S>()` / `set_initial<S>()` / `replace<S, T>()`.
- **Services**: `set_services(registry)`; `state.service<I>()` resolves through the injected context.
- **Observation**: `current_state()` is a lock-free atomic-index read of an immutable name table (P2996 `identifier_of`, fallback to indexed names). `state_path()` is the same but appends an active `run_region` child's path — consumer-consistent (read it from within the machine or once settled; deterministic in `pump()` mode).
- **Reactive DSL extras**: `on.defer<E>()` holds event `E` while in the state and re-posts it after the next transition (UML deferred events) instead of dropping it; `on.enter(fn)` / `on.exit(fn)` are entry/exit actions run by the reactive loop; `on.event<E>().internal(fn)` handles `E` (runs `fn`) **without** leaving the state (no exit/enter/transition).
- **Introspection**: `describe()` lists registered states (name, reactive?, initial?) plus the transitions declared by reactive states (event/target names, guard-present); imperative `run()`-chosen edges aren't statically knowable so those states are edgeless nodes. `to_mermaid()` renders a `stateDiagram-v2` string.
- **Error policies / middleware**: state helpers `delay(d)`, `with_retry(times, backoff, attempt)` (retries a `Coro::Task<bool>` sub-step), `next_or<Fallback>(step)` (route a failing `Step` to a fallback state). `add_interceptor({before(Transition), after(state_name)})` runs ordered hooks around each transition; `observe(fn)` is the single read-only observer.
- **Event idioms (all imperative)**: timeout — `co_await await_event_for<E>(d)` (→ `optional`, `nullopt` on timeout) or `delay(d)`; multi-event — `co_await await_any<A, B>()` → `std::variant<A,B>`; guard — a plain `if` after the await; internal/self transition — a `for(;;)` loop in the entry that handles events without returning (or `next<Self>()`); **deferred events are automatic** — the typed mailbox buffers any event a state doesn't await, so a later state consumes it (nothing is dropped, no `defer` declaration needed).
- **Introspection**: `describe()` lists registered states (name, initial?). Transitions are chosen imperatively inside each entry and aren't statically knowable, so the description is **node-level** — `to_mermaid()` renders a `stateDiagram-v2` string with the initial marker plus one node per state (no edges).
- **Error policies / middleware**: state helpers `delay(d)`, `with_retry(times, backoff, attempt)` (retries a `Coro::Task<bool>` sub-step), `next_or<Fallback>(step)` (route a failing `State` to a fallback state). `add_interceptor({before(Transition), after(state_name)})` runs ordered hooks around each transition; `observe(fn)` is the single read-only observer.
- **Persistence**: `serialize()` → `{state name, on_serialize data}`; `restore()` on an un-started machine resumes at the named state (override `on_serialize`/`on_restore` for derived data, reflection-JSON friendly).
- Hot-plug + state-saving are re-expressed via services: plugins provide `IService` impls; `PluginServiceBinding` swaps the registry entry on reload (state migrated by the plugin's v2 ABI), so running FSMs pick up the new impl on the next `service<I>()` call without being patched.