ready-active-safe 0.1.3

Lifecycle engine for externally driven systems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
# User Guide

A practical guide to modeling system lifecycles with `ready-active-safe`.

This crate is a lifecycle engine, not a general purpose state machine framework.
It is meant for systems that start up, run, shut down, and recover.

## The Mental Model

Five things to know before writing code:

1. **Mode** — an operational phase (Ready, Active, Safe), not an arbitrary state.
2. **Machine** — a pure function: `(mode, event) → Decision`. No I/O, no mutation.
3. **Decision** — plain data: an optional mode change + zero or more commands.
4. **Runtime** — your code. It owns the current mode, feeds events, executes commands.
5. **Policy** — an external guard that can deny transitions before they apply.

```text
Event --> Machine::on_event(mode, event) --> Decision
                                                |-- ModeChange (optional)
                                                +-- Commands (Vec<C>)
```

The machine never performs side effects. It tells the runtime *what* to do.
The runtime decides *how* and *when* to do it.

## Quick Start

Add the crate:

```sh
cargo add ready-active-safe
```

For `no_std` core types:

```sh
cargo add ready-active-safe --no-default-features
```

Write a machine as a plain `match (mode, event)`:

```rust
use ready_active_safe::prelude::*;

#[derive(Debug, Clone, PartialEq, Eq)]
enum Mode {
    Ready,
    Active,
    Safe,
}

#[derive(Debug)]
enum Event {
    Start,
    Stop,
    Fault,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum Command {
    Initialize,
    BeginProcessing,
    Shutdown,
}

struct System;

impl Machine for System {
    type Mode = Mode;
    type Event = Event;
    type Command = Command;

    fn initial_mode(&self) -> Mode {
        Mode::Ready
    }

    fn on_event(&self, mode: &Mode, event: &Event) -> Decision<Mode, Command> {
        use Command::*;
        use Event::*;
        use Mode::*;

        match (mode, event) {
            (Ready, Start) => transition(Active)
                .emit_all([Initialize, BeginProcessing]),
            (Active, Stop | Fault) => transition(Safe)
                .emit(Shutdown),
            _ => ignore(),
        }
    }
}

let system = System;
let mut mode = system.initial_mode();

let d = system.decide(&mode, &Event::Start);
assert_eq!(d.target_mode(), Some(&Mode::Active));
assert_eq!(d.commands(), &[Command::Initialize, Command::BeginProcessing]);

let d = system.decide(&Mode::Active, &Event::Fault);
assert_eq!(d.target_mode(), Some(&Mode::Safe));
```

That is the whole pattern.
The machine is pure, so it is easy to test.
The runtime stays outside the crate, so you can plug it into whatever environment you run in.

## Decisions

A `Decision` answers two questions:

1. Should we change mode?
2. What commands should the runtime run?

Three factory functions cover every case:

- **`transition(target)`** — move to a new mode
- **`stay()`** — remain in the current mode (event was processed, no change needed)
- **`ignore()`** — remain in the current mode (event is not relevant here)

`stay()` and `ignore()` produce identical decisions. The distinction is intent:
use `stay()` when the event was handled, and `ignore()` in catch-all arms to
signal that silence is by design, not an oversight.

```rust
use ready_active_safe::prelude::*;

// Stay in current mode
let _: Decision<&str, &str> = stay();

// Transition to a new mode
let _: Decision<&str, &str> = transition("active");

// Stay with a command
let _: Decision<&str, &str> = stay().emit("log_heartbeat");

// Transition with a command
let _: Decision<&str, &str> = transition("safe").emit("flush_buffers");

// Transition with multiple commands
let _: Decision<&str, &str> = transition("active")
    .emit_all(["initialize", "begin"]);

// Catch-all: deliberately ignore unmatched events
let _: Decision<&str, &str> = ignore();
```

### Predicates

Check what a decision does without inspecting the internals:

```rust
use ready_active_safe::prelude::*;

let d: Decision<&str, ()> = transition("active");
assert!(d.is_transition());

let d: Decision<&str, ()> = stay();
assert!(d.is_stay());
```

### stay vs ignore in practice

Use `ignore()` in catch-all arms to signal that silence is deliberate:

```rust
use ready_active_safe::prelude::*;

# #[derive(Debug, Clone, PartialEq, Eq)]
# enum Mode { Ready, Active }
# #[derive(Debug)]
# enum Event { Start, Ping }
# struct System;
# impl Machine for System {
#     type Mode = Mode;
#     type Event = Event;
#     type Command = ();
#     fn initial_mode(&self) -> Mode { Mode::Ready }
fn on_event(&self, mode: &Mode, event: &Event) -> Decision<Mode, ()> {
    match (mode, event) {
        (Mode::Ready, Event::Start) => transition(Mode::Active),
        _ => ignore(), // deliberate: these events need no response
    }
}
# }
```

## Applying Decisions

In a runtime loop you usually:

1. Ask the machine for a decision
2. Apply the decision to your current mode
3. Run the commands

`Decision::apply` extracts the target mode and commands, consuming the decision.

```rust
use ready_active_safe::prelude::*;

let mode = "ready";
let decision: Decision<&str, &str> = transition("active").emit("initialize");

let (mode, commands) = decision.apply(mode);
assert_eq!(mode, "active");
assert_eq!(commands, vec!["initialize"]);
```

A typical runtime loop:

```rust
use ready_active_safe::prelude::*;

# #[derive(Debug, Clone, PartialEq, Eq)]
# enum Mode { Ready, Active, Safe }
# #[derive(Debug)]
# enum Event { Start, Stop }
# #[derive(Debug, Clone, PartialEq, Eq)]
# enum Command { Init, Halt }
# struct System;
# impl Machine for System {
#     type Mode = Mode;
#     type Event = Event;
#     type Command = Command;
#     fn initial_mode(&self) -> Mode { Mode::Ready }
#     fn on_event(&self, mode: &Mode, event: &Event) -> Decision<Mode, Command> {
#         match (mode, event) {
#             (Mode::Ready, Event::Start) => transition(Mode::Active).emit(Command::Init),
#             (Mode::Active, Event::Stop) => transition(Mode::Safe).emit(Command::Halt),
#             _ => ignore(),
#         }
#     }
# }
let system = System;
let mut mode = system.initial_mode();
let events = [Event::Start, Event::Stop];

for event in &events {
    let decision = system.decide(&mode, event);
    let (next_mode, commands) = decision.apply(mode);
    mode = next_mode;
    // dispatch commands to your runtime here
}
```

## Runtime (Runner)

If you enable the `runtime` feature (included in the default `full` feature set),
you can use `ready_active_safe::runtime::Runner` as a tiny reference loop
that owns the current mode, feeds events, applies mode changes, and returns commands.

```rust
use ready_active_safe::prelude::*;
use ready_active_safe::runtime::Runner;

# #[derive(Debug, Clone, PartialEq, Eq)]
# enum Mode { Ready, Active }
# #[derive(Debug)]
# enum Event { Start }
# #[derive(Debug, Clone, PartialEq, Eq)]
# enum Command { Init }
# struct System;
# impl Machine for System {
#     type Mode = Mode;
#     type Event = Event;
#     type Command = Command;
#     fn initial_mode(&self) -> Mode { Mode::Ready }
#     fn on_event(&self, mode: &Mode, event: &Event) -> Decision<Mode, Command> {
#         match (mode, event) {
#             (Mode::Ready, Event::Start) => transition(Mode::Active).emit(Command::Init),
#             _ => ignore(),
#         }
#     }
# }
let system = System;
let mut runner = Runner::new(&system);

let commands = runner.feed(&Event::Start);
assert_eq!(runner.mode(), &Mode::Active);
assert_eq!(commands, vec![Command::Init]);
```

## Policies

Sometimes a transition is valid in the machine but should be blocked in
certain deployments — for example, a safety-critical system that must
never skip the Ready phase. Policies enforce these rules externally,
without cluttering your `match` arms.

```rust
use ready_active_safe::prelude::*;

#[derive(Debug, Clone, PartialEq, Eq)]
enum Mode {
    Ready,
    Active,
    Safe,
}

struct ForwardOnly;

impl Policy<Mode> for ForwardOnly {
    fn is_allowed(&self, from: &Mode, to: &Mode) -> bool {
        matches!(
            (from, to),
            (Mode::Ready, Mode::Active) | (Mode::Active, Mode::Safe)
        )
    }
}

let policy = ForwardOnly;

assert!(policy.is_allowed(&Mode::Ready, &Mode::Active));
assert!(!policy.is_allowed(&Mode::Safe, &Mode::Ready));
```

If the policy denies the transition, the runtime does not change the mode.
It can return a `LifecycleError::TransitionDenied` instead.

### Built-In Policies

The crate ships with two policies so you do not have to write boilerplate:

```rust
use ready_active_safe::prelude::*;

// AllowAll permits every transition — ideal for tests
let policy = AllowAll;
assert!(policy.is_allowed(&"ready", &"active"));

// DenyAll denies every transition — for testing enforcement
let policy = DenyAll;
assert!(!policy.is_allowed(&"ready", &"active"));
```

Use `AllowAll` in tests where you do not care about transition restrictions.
Use `DenyAll` to verify that your runtime correctly handles denial.

## Errors

When a policy denies a transition, your runtime can surface a `LifecycleError`:

```rust
use ready_active_safe::LifecycleError;

let err: LifecycleError<&str> = LifecycleError::TransitionDenied {
    from: "safe",
    to: "ready",
    reason: "backward transitions are not allowed",
};

assert_eq!(
    err.to_string(),
    "transition denied from safe to ready: backward transitions are not allowed",
);
```

`LifecycleError` is `#[non_exhaustive]`, so keep a wildcard arm when matching:

```rust
use ready_active_safe::LifecycleError;

fn handle_error(err: LifecycleError<String>) -> String {
    match err {
        LifecycleError::TransitionDenied { from, to, reason } => {
            format!("denied: {from} -> {to} ({reason})")
        }
        _ => String::from("unknown lifecycle error"),
    }
}
```

## Testing

The crate provides assertion macros with clear failure messages.

### assert_transitions_to!

```rust
use ready_active_safe::prelude::*;
use ready_active_safe::assert_transitions_to;

let d: Decision<&str, ()> = transition("active");
assert_transitions_to!(d, "active");
```

If the decision stays instead of transitioning, the failure message says:
`"expected transition to "active", but decision stays in current mode"`

### assert_stays!

```rust
use ready_active_safe::prelude::*;
use ready_active_safe::assert_stays;

let d: Decision<&str, ()> = stay();
assert_stays!(d);
```

### assert_emits!

```rust
use ready_active_safe::prelude::*;
use ready_active_safe::assert_emits;

let d: Decision<(), &str> = stay().emit("init").emit("begin");
assert_emits!(d, ["init", "begin"]);

// Also works with no commands
let d: Decision<(), &str> = stay();
assert_emits!(d, []);
```

### Testing a Machine

Combine the macros for a complete test:

```rust
use ready_active_safe::prelude::*;
use ready_active_safe::{assert_transitions_to, assert_stays, assert_emits};

#[derive(Debug, Clone, PartialEq, Eq)]
enum Mode { Ready, Active, Safe }

#[derive(Debug, Clone, PartialEq, Eq)]
enum Event { Start, Stop }

#[derive(Debug, Clone, PartialEq, Eq)]
enum Command { Init }

struct System;

impl Machine for System {
    type Mode = Mode;
    type Event = Event;
    type Command = Command;

    fn initial_mode(&self) -> Mode { Mode::Ready }

    fn on_event(&self, mode: &Mode, event: &Event) -> Decision<Mode, Command> {
        match (mode, event) {
            (Mode::Ready, Event::Start) => transition(Mode::Active).emit(Command::Init),
            (Mode::Active, Event::Stop) => transition(Mode::Safe),
            _ => ignore(),
        }
    }
}

let system = System;

// Test initial mode
assert_eq!(system.initial_mode(), Mode::Ready);

// Test forward transition
let d = system.decide(&Mode::Ready, &Event::Start);
assert_transitions_to!(d, Mode::Active);
assert_emits!(d, [Command::Init]);

// Test unmatched event
let d = system.decide(&Mode::Safe, &Event::Start);
assert_stays!(d);
```

## Time

The base `Machine` trait does not include a clock parameter.
Time enters through events — your runtime emits tick or timeout events,
and the machine decides based on them.

The `time` feature provides `Clock`, `Instant`, and `Deadline` types.
`ManualClock` makes time deterministic in tests; `SystemClock` uses real
monotonic time in production.

```rust
use ready_active_safe::prelude::*;
use ready_active_safe::time::{Clock, Deadline, Instant, ManualClock};
use core::time::Duration;

// ManualClock: you control time, perfect for tests
let clock = ManualClock::new(Instant::from_nanos(0));
let deadline = Deadline::at(Instant::from_nanos(1_000_000_000)); // 1 second

assert!(!deadline.is_expired(clock.now()));

clock.advance(Duration::from_millis(500));
assert!(!deadline.is_expired(clock.now()));

clock.advance(Duration::from_millis(500));
assert!(deadline.is_expired(clock.now()));
```

A machine that uses time typically receives it through its event type:

```rust
use ready_active_safe::prelude::*;
use ready_active_safe::time::{Clock, Instant, ManualClock};

#[derive(Debug, Clone, PartialEq, Eq)]
enum Mode { Ready, Active, TimedOut }

#[derive(Debug)]
enum Event {
    Start,
    Tick(Instant),
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum Command { Begin }

struct System { timeout: Instant }

impl Machine for System {
    type Mode = Mode;
    type Event = Event;
    type Command = Command;

    fn initial_mode(&self) -> Mode { Mode::Ready }

    fn on_event(&self, mode: &Mode, event: &Event) -> Decision<Mode, Command> {
        match (mode, event) {
            (Mode::Ready, Event::Start) => transition(Mode::Active).emit(Command::Begin),
            (Mode::Active, Event::Tick(now)) if *now >= self.timeout => {
                transition(Mode::TimedOut)
            }
            _ => ignore(),
        }
    }
}

// Test with deterministic time
let system = System { timeout: Instant::from_nanos(5_000_000_000) };
let clock = ManualClock::new(Instant::from_nanos(0));

let d = system.decide(&Mode::Active, &Event::Tick(clock.now()));
assert!(d.is_stay()); // not timed out yet

clock.advance(core::time::Duration::from_secs(6));
let d = system.decide(&Mode::Active, &Event::Tick(clock.now()));
assert_eq!(d.target_mode(), Some(&Mode::TimedOut)); // expired
```

## Journal

If you enable the `journal` feature, you can record transitions as data so you can replay
and audit what happened. The journal is an observer: it does not modify decisions.

```rust
use ready_active_safe::prelude::*;
use ready_active_safe::journal::InMemoryJournal;

#[derive(Debug, Clone, PartialEq, Eq)]
enum Mode { Ready, Active }

#[derive(Debug, Clone)]
enum Event { Start }

#[derive(Debug, Clone, PartialEq, Eq)]
enum Command { Init }

struct System;

impl Machine for System {
    type Mode = Mode;
    type Event = Event;
    type Command = Command;

    fn initial_mode(&self) -> Mode { Mode::Ready }

    fn on_event(&self, mode: &Mode, event: &Event) -> Decision<Mode, Command> {
        match (mode, event) {
            (Mode::Ready, Event::Start) => transition(Mode::Active).emit(Command::Init),
            _ => ignore(),
        }
    }
}

let system = System;
let mut mode = system.initial_mode();
let mut journal = InMemoryJournal::new();

let event = Event::Start;
let decision = system.decide(&mode, &event);
let (next_mode, commands) = decision.clone().apply(mode.clone());

journal.record_step(&mode, &next_mode, &event, decision.commands());
mode = next_mode;

assert_eq!(mode, Mode::Active);
assert_eq!(commands, vec![Command::Init]);
assert_eq!(journal.len(), 1);

let replay_mode = journal.replay(&system, system.initial_mode()).unwrap();
assert_eq!(replay_mode, Mode::Active);
```

## Feature Flags Reference

### Selecting Features

```toml
# Full feature set (default)
ready-active-safe = "0.1"

# Core types only, no_std compatible
ready-active-safe = { version = "0.1", default-features = false }

# Core types + time (no_std compatible)
ready-active-safe = { version = "0.1", default-features = false, features = ["time"] }

# Standard library + runtime (no journal)
ready-active-safe = { version = "0.1", default-features = false, features = ["runtime"] }
```

### Feature Dependency Graph

```text
full -----> std
       |--> runtime -----> std
       |--> time
       |--> journal -----> std
```

### Compatibility Matrix

| Configuration                  | `no_std` | `alloc` Required | Available Types                               |
|--------------------------------|----------|------------------|-----------------------------------------------|
| `--no-default-features`        | Yes      | Yes              | `Machine`, `Decision`, `ModeChange`, `Policy`, `AllowAll`, `DenyAll`, `LifecycleError`, macros |
| `--features time`              | Yes      | Yes              | Above + `time` module                         |
| `--features std`               | No       | Yes              | Above + `std::error::Error` impls             |
| `--features runtime`           | No       | Yes              | Above + `std` + `runtime` module              |
| `--features journal`           | No       | Yes              | Above + `std` + `journal` module              |
| `--all-features` or default    | No       | Yes              | Everything                                    |