statum-graph 0.7.0

Static graph export for Statum machine introspection
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
# statum-graph

`statum-graph` exports static machine topology directly from
`statum::MachineIntrospection::GRAPH`.

It is authoritative only for machine-local structure:

- machine identity
- states
- transition sites
- exact legal targets
- graph roots derivable from the static graph itself

For linked-build codebase export, `statum-graph` can also combine every linked
compiled machine family, legacy direct payload links, declared validator-entry
surfaces, direct-construction availability per state, and exact relation
records inferred from supported type syntax, `#[via(...)]` declarations, and
nominal `#[machine_ref(...)]` declarations. That codebase view is still static
only. It does not model runtime-selected branches or orchestration order
across machines. Validator node labels come from the impl self type as written
in source and are display-only, not canonical Rust type identity.
Method-level `#[cfg]` and `#[cfg_attr]` on validator methods are rejected at
the macro layer. `include!()`-generated validator impls are also rejected. In
v1, exact direct-type relations recurse only through canonical absolute carrier
paths such as `::core::option::Option<...>` and
`::core::result::Result<..., E>`, and direct machine targets must use explicit
`crate::`, `self::`, `super::`, or absolute paths instead of imported aliases
or bare names. Transition-parameter direct targets, `#[via(...)]` inner
targets, and `#[machine_ref(...)]` declarations resolve against the linked
codebase view through compiler-resolved concrete machine type identity, so
public machine re-exports remain exact there instead of depending on
source-path guessing. State-payload and machine-field direct targets still rely
on the canonical linked path surface, so those surfaces do not currently
promote public machine re-exports into exact relations.

## Install

```toml
[dependencies]
statum = "0.7.0"
statum-graph = "0.7.0"
```

## Example

```rust
use statum::{machine, state, transition};
use statum_graph::{render, MachineDoc};

#[state]
enum FlowState {
    Draft,
    Review,
    Accepted,
    Rejected,
}

#[machine]
struct Flow<FlowState> {}

#[transition]
impl Flow<Draft> {
    fn submit(self) -> Flow<Review> {
        self.transition()
    }
}

#[transition]
impl Flow<Review> {
    fn decide(
        self,
        accept: bool,
    ) -> ::core::result::Result<Flow<Accepted>, Flow<Rejected>> {
        if accept {
            Ok(self.accept())
        } else {
            Err(self.reject())
        }
    }

    fn accept(self) -> Flow<Accepted> {
        self.transition()
    }

    fn reject(self) -> Flow<Rejected> {
        self.transition()
    }
}

let doc = MachineDoc::from_machine::<Flow<Draft>>();
let mermaid = render::mermaid(&doc);

assert!(mermaid.contains("s1 -->|decide| s2"));
assert!(mermaid.contains("s1 -->|decide| s3"));
```

## Mermaid Output

The renderer returns ordinary Mermaid flowchart text:

```text
graph TD
    s0["Draft"]
    s1["Review"]
    s2["Accepted"]
    s3["Rejected"]

    s0 -->|submit| s1
    s1 -->|accept| s2
    s1 -->|decide| s2
    s1 -->|decide| s3
    s1 -->|reject| s3
```

The output is deterministic for one validated `MachineDoc`, so it works well
for snapshot tests, generated docs, and CLI output.

## Canonical Export Model

`MachineDoc` is the validated typed graph surface. `ExportDoc` is the stable
renderer-facing model built from that graph:

```rust
# use statum::{machine, state, transition};
# use statum_graph::MachineDoc;
# #[state]
# enum FlowState {
#     Draft,
#     Review,
#     Accepted,
# }
# #[machine]
# struct Flow<FlowState> {}
# #[transition]
# impl Flow<Draft> {
#     fn submit(self) -> Flow<Review> {
#         self.transition()
#     }
# }
# #[transition]
# impl Flow<Review> {
#     fn accept(self) -> Flow<Accepted> {
#         self.transition()
#     }
# }
let doc = MachineDoc::from_machine::<Flow<Draft>>();
let export = doc.export();

assert_eq!(export.states()[0].index, 0);
assert_eq!(export.transitions()[0].method_name, "submit");
```

If you have matching `MachinePresentation` metadata, join it onto the export
surface before rendering:

```rust
# use statum::{machine, state, transition};
# use statum_graph::{render, MachineDoc};
# #[state]
# enum PresentedState {
#     #[present(label = "Queued")]
#     Queued,
#     Done,
# }
# #[machine]
# #[present(label = "Presented Flow")]
# struct PresentedFlow<PresentedState> {}
# #[transition]
# impl PresentedFlow<Queued> {
#     #[present(label = "Finish")]
#     fn finish(self) -> PresentedFlow<Done> {
#         self.transition()
#     }
# }
let doc = MachineDoc::from_machine::<PresentedFlow<Queued>>();
let export = doc.export_with_presentation(&presented_flow::PRESENTATION)?;

assert_eq!(export.machine().label, Some("Presented Flow"));
assert_eq!(render::mermaid(&export).contains("Finish"), true);
# Ok::<(), statum_graph::ExportDocError>(())
```

Presentation metadata can change labels and descriptions, but the structure
still comes from `MachineIntrospection::GRAPH`.

## Other Renderers

The same `ExportDoc` drives every built-in renderer:

```rust
# use statum::{machine, state, transition};
# use statum_graph::{render, MachineDoc};
# #[state]
# enum FlowState {
#     Draft,
#     Done,
# }
# #[machine]
# struct Flow<FlowState> {}
# #[transition]
# impl Flow<Draft> {
#     fn finish(self) -> Flow<Done> {
#         self.transition()
#     }
# }
let doc = MachineDoc::from_machine::<Flow<Draft>>();
let export = doc.export();

let mermaid = render::mermaid(&export);
let dot = render::dot(&export);
let plantuml = render::plantuml(&export);
let json = render::json(&export);

assert!(mermaid.contains("graph TD"));
assert!(dot.contains("digraph"));
assert!(plantuml.contains("@startuml"));
assert!(json.contains("\"transitions\""));
```

The JSON renderer is stable and pretty-printed. It exports machine identity,
states, transition sites, exact legal targets, roots, and optional labels and
descriptions. It does not serialize arbitrary typed `metadata` payloads from
`MachinePresentation`; those stay application-owned unless you define a
separate serialization contract.

## Codebase Export

If you want one combined graph for the linked build instead of one machine at a
time, use `CodebaseDoc`:

```rust
# use statum::{machine, state, transition};
# use statum_graph::CodebaseDoc;
# mod task {
#     use statum::{machine, state, transition};
#     #[state]
#     pub enum State {
#         Idle,
#         Running,
#     }
#     #[machine]
#     pub struct Machine<State> {}
#     #[transition]
#     impl Machine<Idle> {
#         fn start(self) -> Machine<Running> {
#             self.transition()
#         }
#     }
# }
# mod workflow {
#     use super::task;
#     use statum::{machine, state, transition};
#     #[state]
#     pub enum State {
#         Draft,
#         InProgress(super::task::Machine<super::task::Running>),
#     }
#     #[machine]
#     pub struct Machine<State> {}
#     #[transition]
#     impl Machine<Draft> {
#         fn start(
#             self,
#             task: super::task::Machine<super::task::Running>,
#         ) -> Machine<InProgress> {
#             self.transition_with(task)
#         }
#     }
# }
let codebase = CodebaseDoc::linked()?;

assert!(codebase.machines().len() >= 2);
assert!(!codebase.links().is_empty());
assert!(!codebase.relations().is_empty());
# Ok::<(), statum_graph::CodebaseDocError>(())
```

Render or write the combined document through `statum_graph::codebase::render`:

```rust
# use statum_graph::{CodebaseDoc, codebase::render};
# let doc = CodebaseDoc::linked()?;
let mermaid = render::mermaid(&doc);
let paths = render::write_all_to_dir(&doc, "out", "codebase")?;

assert!(mermaid.contains("graph TD"));
assert_eq!(paths.len(), 4);
# Ok::<(), Box<dyn std::error::Error>>(())
```

The codebase view is based on the linked compiled build, not a source scan.
Legacy `links()` come only from direct machine-like payload types written in
state data, including named fields. The richer exact `relations()` surface also
covers machine fields, transition parameters, `#[via(...)]` declarations, and
nominal opaque reference types declared once with `#[machine_ref(...)]`. In
v1, `#[machine_ref(...)]` supports nominal structs and tuple structs only;
plain type aliases are rejected. Exact direct-type relations recurse only
through canonical absolute carrier paths such as `::core::option::Option<...>`
and `::core::result::Result<..., E>`, and direct machine targets must use
explicit `crate::`, `self::`, `super::`, or absolute paths. Exact target
resolution for transition-parameter direct targets, `#[via(...)]` inner
targets, and `#[machine_ref(...)]` declarations uses compiler-resolved
concrete machine type identity, so public machine re-exports still join the
right machine family in `CodebaseDoc`. State-payload and machine-field direct
targets still rely on the canonical linked path surface, so those surfaces do
not currently promote public machine re-exports into exact relations.
Validator-entry
nodes come only from compiled `#[validators]` impls and represent declared
rebuild surfaces such as `DbRow::into_machine()`, not runtime match outcomes.
All exact surfaces fail closed on malformed or ambiguous linked metadata.
Transition-body orchestration, runtime composition, primitive ids with no
typed wrapper, and terminal-state semantics are intentionally out of scope.

`#[via(...)]` is the exact relation surface for “this parent transition depends
on this exact child transition route.” For example, if one transition takes
`crate::PaymentMachine<crate::Captured>` and also declares
`#[via(self::payment_machine::via::Capture)]`,
`CodebaseDoc` can say both:

- the parent transition depends on the child being in `Captured`
- the parent transition can depend on `PaymentMachine<Authorized>::capture`

This improves exact relation detail without inferring a protocol-stage graph.
Compatible same-name attested producer routes are grouped deterministically
when they emit distinct route marker types, and the exact relation detail
surfaces the matching producer transition list instead of rejecting that shape
outright.
For a runnable example that also asserts the linked relation basis, see
[`statum-examples/src/toy_demos/17-attested-composition.rs`](../statum-examples/src/toy_demos/17-attested-composition.rs).
Graph backends mark directly constructible states with a ` [build]` suffix and
derive cross-machine summary edges from exact `relations()`. Downstream
consumers can use `machine_relation_groups()`, inbound and outbound relation
lookup helpers, and `relation_detail()` to drive exact navigation without
re-deriving relation semantics. The codebase surface also carries source
rustdoc separately as `docs` on machines, states, transitions, and validator
entries. Use `#[present(description = ...)]` for concise UI copy and outer
rustdoc comments (`///`) for fuller inspector and `codebase.json` detail.

If you do not want to hand-write a runner crate, install
`cargo-statum-graph` and point it at an existing library package:

```text
cargo statum-graph export \
  /path/to/workspace
```

That command synthesizes the runner internally and writes the same four-file
bundle into the workspace root without requiring exporter code in the target
crate. Use `--out-dir` to override the destination or `--package` to narrow a
multi-package workspace to one library crate.

## Writing Files

You can also write one file directly:

```rust
# use statum::{machine, state, transition};
# use statum_graph::{render, MachineDoc};
# #[state]
# enum FlowState {
#     Draft,
#     Done,
# }
# #[machine]
# struct Flow<FlowState> {}
# #[transition]
# impl Flow<Draft> {
#     fn finish(self) -> Flow<Done> {
#         self.transition()
#     }
# }
let doc = MachineDoc::from_machine::<Flow<Draft>>();
render::Format::Mermaid.write_to(&doc, "out/flow.mmd")?;
# Ok::<(), std::io::Error>(())
```

Or write the whole built-in bundle with standard extensions:

```rust
# use statum::{machine, state, transition};
# use statum_graph::{render, MachineDoc};
# #[state]
# enum FlowState {
#     Draft,
#     Done,
# }
# #[machine]
# struct Flow<FlowState> {}
# #[transition]
# impl Flow<Draft> {
#     fn finish(self) -> Flow<Done> {
#         self.transition()
#     }
# }
let doc = MachineDoc::from_machine::<Flow<Draft>>();
let paths = render::write_all_to_dir(&doc, "out", "flow")?;

assert_eq!(paths.len(), 4);
# Ok::<(), std::io::Error>(())
```

## Traversing A Graph

`MachineDoc` gives you the machine descriptor, the state list, the transition
sites, and the root states:

```rust
# use statum::{machine, state, transition};
# use statum_graph::MachineDoc;
# #[state]
# enum FlowState {
#     Draft,
#     Review,
#     Accepted,
#     Rejected,
# }
# #[machine]
# struct Flow<FlowState> {}
# #[transition]
# impl Flow<Draft> {
#     fn submit(self) -> Flow<Review> {
#         self.transition()
#     }
# }
# #[transition]
# impl Flow<Review> {
#     fn accept(self) -> Flow<Accepted> {
#         self.transition()
#     }
#     fn reject(self) -> Flow<Rejected> {
#         self.transition()
#     }
# }
let doc = MachineDoc::from_machine::<Flow<Draft>>();

assert!(doc.machine().rust_type_path.ends_with("Flow"));
assert_eq!(
    doc.roots()
        .map(|state| state.descriptor.rust_name)
        .collect::<Vec<_>>(),
    vec!["Draft"]
);
assert_eq!(
    doc.states()
        .iter()
        .map(|state| state.descriptor.rust_name)
        .collect::<Vec<_>>(),
    vec!["Draft", "Review", "Accepted", "Rejected"]
);
assert_eq!(
    doc.edges()
        .iter()
        .map(|edge| edge.descriptor.method_name)
        .collect::<Vec<_>>(),
    vec!["submit", "accept", "reject"]
);
```

Use `doc.state(id)` when you need to map a transition target id back to the
exported state descriptor.

## Choosing An Entry Point

Use `MachineDoc::from_machine::<M>()` when the graph comes from a real Statum
machine type. That is the normal entry point for application code, test
assertions, and generated documentation.

Use `MachineDoc::try_from_graph(...)` when you already have a
`statum::MachineGraph` and want `statum-graph` to validate it before rendering
or traversal. This is mainly for external graph producers, tests, and tooling
adapters.

`try_from_graph(...)` rejects malformed graphs instead of guessing:

- empty state lists
- duplicate state ids
- duplicate transition ids
- duplicate transition sites for one `(source state, method name)` pair
- missing source states
- missing target states
- empty target sets
- duplicate target states within one transition

The error surface is `MachineDocError`.

If you join presentation metadata onto a validated machine graph, malformed
presentation overlays fail closed with `ExportDocError` instead of picking a
best-effort winner.

## Scope

`statum-graph` exports static machine-local topology. It does not tell you
which branch ran in one execution, how multiple machines were orchestrated at
runtime, or how machine data changed over time. For those use cases, pair the
static graph with explicit runtime events or snapshots from the application.