tickflow-py 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. tickflow_py-0.1.0/LICENSE +21 -0
  2. tickflow_py-0.1.0/PKG-INFO +565 -0
  3. tickflow_py-0.1.0/README.md +543 -0
  4. tickflow_py-0.1.0/pyproject.toml +31 -0
  5. tickflow_py-0.1.0/setup.cfg +4 -0
  6. tickflow_py-0.1.0/tests/test_async.py +173 -0
  7. tickflow_py-0.1.0/tests/test_audit_switch.py +120 -0
  8. tickflow_py-0.1.0/tests/test_checker.py +174 -0
  9. tickflow_py-0.1.0/tests/test_checkpoints.py +263 -0
  10. tickflow_py-0.1.0/tests/test_engine.py +161 -0
  11. tickflow_py-0.1.0/tests/test_failure.py +110 -0
  12. tickflow_py-0.1.0/tests/test_fireable.py +120 -0
  13. tickflow_py-0.1.0/tests/test_hooks.py +147 -0
  14. tickflow_py-0.1.0/tests/test_loop.py +124 -0
  15. tickflow_py-0.1.0/tests/test_node_state.py +132 -0
  16. tickflow_py-0.1.0/tests/test_parser.py +118 -0
  17. tickflow_py-0.1.0/tests/test_persistence.py +281 -0
  18. tickflow_py-0.1.0/tests/test_remap.py +348 -0
  19. tickflow_py-0.1.0/tests/test_snapshot.py +197 -0
  20. tickflow_py-0.1.0/tests/test_status.py +93 -0
  21. tickflow_py-0.1.0/tests/test_storage_window.py +465 -0
  22. tickflow_py-0.1.0/tests/test_visualization.py +103 -0
  23. tickflow_py-0.1.0/tickflow/__init__.py +79 -0
  24. tickflow_py-0.1.0/tickflow/__main__.py +6 -0
  25. tickflow_py-0.1.0/tickflow/async_runner.py +247 -0
  26. tickflow_py-0.1.0/tickflow/checker.py +294 -0
  27. tickflow_py-0.1.0/tickflow/cli.py +161 -0
  28. tickflow_py-0.1.0/tickflow/engine.py +306 -0
  29. tickflow_py-0.1.0/tickflow/ir.py +209 -0
  30. tickflow_py-0.1.0/tickflow/parser.py +273 -0
  31. tickflow_py-0.1.0/tickflow/persistence.py +597 -0
  32. tickflow_py-0.1.0/tickflow/registry.py +103 -0
  33. tickflow_py-0.1.0/tickflow/runner.py +579 -0
  34. tickflow_py-0.1.0/tickflow/state.py +498 -0
  35. tickflow_py-0.1.0/tickflow/views.py +140 -0
  36. tickflow_py-0.1.0/tickflow_py.egg-info/PKG-INFO +565 -0
  37. tickflow_py-0.1.0/tickflow_py.egg-info/SOURCES.txt +37 -0
  38. tickflow_py-0.1.0/tickflow_py.egg-info/dependency_links.txt +1 -0
  39. tickflow_py-0.1.0/tickflow_py.egg-info/top_level.txt +1 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MountLynx
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,565 @@
1
+ Metadata-Version: 2.4
2
+ Name: tickflow-py
3
+ Version: 0.1.0
4
+ Summary: A small Petri-style workflow control framework
5
+ Author: MountLynx
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/MountLynx/tickflow
8
+ Keywords: petri,workflow,graph,state-machine,flow
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Software Development :: Libraries
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Dynamic: license-file
22
+
23
+ # tickflow
24
+
25
+ A small Petri-style workflow control framework for building short, auditable,
26
+ reversible flows. You describe the graph in a mermaid-like syntax; the engine
27
+ runs it as synchronous Petri-net *steps* over a boolean slot marking, with
28
+ all runtime state centralized in `RunState` — making snapshots, pause, rewind,
29
+ and replay cheap.
30
+
31
+ > Is this a state machine? No — it's a **Petri net** (specifically a marked
32
+ > graph with AND/OR joins). A finite state machine is the degenerate case
33
+ > where exactly one token is live in the whole net at any time. `tickflow`
34
+ > supports multiple concurrent starts, AND-joins (wait for all upstream),
35
+ > OR-joins (fire on any upstream), and cycles — none of which plain FSMs
36
+ > express natively. See [Design notes](#design-notes).
37
+
38
+ ## Quick start
39
+
40
+ ```bash
41
+ python -m tickflow run examples/counter_loop.txt -b examples/counter_loop_beh.py
42
+ ```
43
+
44
+ The graph file declares **structure only**; a Python "behaviours" file
45
+ registers the actual body/guard callables on `tickflow.registry`.
46
+
47
+ ### Graph syntax
48
+
49
+ ```
50
+ [A]-->B # A is a start node; plain edge A→B (always True)
51
+ B--|g1|-->C # guarded edge: slot is True iff guard g1(view) is True
52
+ B--|g1|-->A # cycle / loop-back edge
53
+ C.inputs: A, B[2] # C reads A (latest_before) and B's 2nd fire (1-based)
54
+ C.body: compute_c # C's body is the registered callable compute_c
55
+ C.join: OR # override join (AND is the default)
56
+ ```
57
+
58
+ - `[A]` marks a **start node**. Multiple starts are allowed and fire
59
+ concurrently at tick 0.
60
+ - `-->` is a plain data-flow edge: it always writes `True` into the
61
+ downstream slot when its source fires.
62
+ - `--|name|-->` is a guarded edge: it writes `guard(view)` (so a failing
63
+ guard writes **`False`**, an explicit clobber — a stale `True` from a
64
+ previous iteration can never leak into a loop).
65
+ - `node.inputs:` and `node.body:` lines bind behaviour. Both are optional
66
+ (default body = identity/echo; default inputs = every producer, each with
67
+ `latest_before`). `inputs` may reference non-producer nodes (e.g. `A[k]`
68
+ to pin A's k-th fire) as long as the referenced node is **upstream** in
69
+ the graph (has a directed path to the consumer).
70
+ - `#` starts a comment.
71
+
72
+ ### Behaviours file
73
+
74
+ ```python
75
+ from tickflow import registry
76
+ from tickflow.views import Missing
77
+
78
+ @registry.body("incr")
79
+ def incr(v):
80
+ return v.A.value + 1 # v.A is the resolved value of producer A
81
+
82
+ @registry.guard("cont_lt3")
83
+ def cont(v):
84
+ return v.B.value < 3 # guard on edge out of B sees B's output
85
+ ```
86
+
87
+ A body or guard receives a `DictView`: `v.A` (or `v["A"]`) resolves the
88
+ declared producer per the node's input policy. `v.A.value` is the bare value;
89
+ `v.A.k` is the fire index used (or `None` for `latest_before`). A producer
90
+ with no qualifying fire yet yields the `Missing` sentinel (falsy).
91
+
92
+ ## Architecture
93
+
94
+ ### RunState — single source of truth
95
+
96
+ All runtime state lives in `RunState`, organized in three internal layers
97
+ with distinct responsibilities:
98
+
99
+ ```
100
+ RunState
101
+ _edges dict[node, list[(tick, output)]] windowed (last 2 fires/node), for resolve()
102
+ _state dict[node, dict] current mutable state per node, O(1)
103
+ _records list[NodeState] audit in memory: keep_records AND no persistent backend
104
+ ```
105
+
106
+ - **`_edges`** — windowed fast-lookup index for `resolve()`: only the last two
107
+ firings per node stay in memory; older firings live in the backend. Memory
108
+ usage is O(nodes × 2 × output size), independent of how many times a node fired.
109
+ - **`_state`** — current mutable state per node (what bodies write via
110
+ `view.state`). Always maintained, O(1) access. Replaces the old
111
+ `Marking.node_state`.
112
+ - **`_records`** — full `NodeState` records in memory. Maintained only when
113
+ `keep_records=True` **and** no persistent backend. With a backend (the
114
+ default), the audit lives on disk and `audit()` queries it.
115
+
116
+ Derived artefacts are extracted from these three layers — or from the
117
+ backend when one is attached:
118
+
119
+ | Query | Source (persistent backend) | Source (NullBackend) |
120
+ |-------|-----------------------------|----------------------|
121
+ | `resolve(latest)` — input resolution | `_edges` window (O(1), zero I/O) | `_edges` window (same) |
122
+ | `resolve(index)` — k-th fire | window first, then `backend.firing_at` | window; outside → `Missing` |
123
+ | `firings_of()` — output history | `backend.firings_of` (full) | `_edges` window |
124
+ | `audit()` — full audit log | `backend.list_firings` | `_records` (keep_records) |
125
+ | `to_snapshot_data()` — snapshot | window + state (+ `fire_counts`) | same |
126
+
127
+ ### NodeState — one firing, all data
128
+
129
+ ```python
130
+ @dataclass
131
+ class NodeState:
132
+ tick: int # which tick
133
+ node: str # which node
134
+ inputs: dict[str, Any] # resolved input values
135
+ output: Any # body return value
136
+ edges_fired: list[tuple[...]] # downstream edge results (filled in Phase B)
137
+ status: "ok" | "failed" | "aborted"
138
+ error: str | None
139
+ mutable_state: dict[str, Any] # node state after body ran
140
+ ```
141
+
142
+ This is the **single source of truth** for everything that happened to a node
143
+ at a given tick. It replaces the old `Firing` class (same fields, unified
144
+ ownership).
145
+
146
+ ### Memory-saving mode
147
+
148
+ ```python
149
+ rn = Runner(graph, registry, keep_records=False)
150
+ ```
151
+
152
+ When `keep_records=False`, `_records` is not populated — saving memory — but
153
+ `_edges` and `_state` are still maintained. Input resolution and node mutable
154
+ state work correctly regardless of this switch. The snapshot omits the
155
+ `"records"` key. Backend persistence (firings, snapshots) is unaffected.
156
+
157
+ By default (`backend=None`) the Runner creates a temporary SQLite backend in
158
+ the system temp dir, auto-generates a `session_id`, and removes the database
159
+ file when the Runner is garbage-collected — so persistence, audit, checkpoints
160
+ and `A[k]` index reads work out of the box. Pass `NullBackend()` explicitly
161
+ for a zero-I/O in-memory run, or a concrete backend for a persistent one.
162
+
163
+ ## Semantics
164
+
165
+ ### The model
166
+
167
+ The engine is a **pure function**:
168
+
169
+ ```
170
+ tick: (marking_t, run_state, t) -> (marking_{t+1}, firings_t)
171
+ ```
172
+
173
+ Only two mutable state containers exist:
174
+ - **marking** — `dict[(dst, src), bool]`, one boolean *slot* per incoming
175
+ edge, plus a set of *armed* start nodes (one-shot).
176
+ - **run_state** — `RunState` instance (windowed history, state, audit).
177
+
178
+ There is no hidden in-flight state. That's what makes snapshots cheap.
179
+
180
+ ### A tick
181
+
182
+ 1. Compute the set of *fireable* nodes: a node fires iff
183
+ - it is an armed start (fires once, then disarmed), **or**
184
+ - its join predicate holds over its input slots: `all` for AND, `any`
185
+ for OR.
186
+ 2. Each fireable node fires concurrently: its body reads inputs
187
+ (`latest_before(t)` — strictly prior ticks, so peers can't see each
188
+ other's same-tick writes), its output is recorded in `RunState`, and its
189
+ input slots are consumed (reset to `False`).
190
+ 3. After all fires, each fired node's out-edges write into downstream slots:
191
+ plain edges write `True`, guarded edges write `guard(view)`.
192
+
193
+ ### Input policies
194
+
195
+ - **`latest`** (default): the producer's most recent fire with `tick < t`.
196
+ This is the marking-consistent read — a node cannot see a peer's same-tick
197
+ write. In a loop, this means "the previous iteration's output".
198
+ - **`A[k]`** (index): the producer's `k`-th fire overall (1-based),
199
+ independent of tick. For cross-iteration pinning and audit replays.
200
+
201
+ A producer with no qualifying fire yields `Missing` (falsy); bodies are
202
+ expected to handle it.
203
+
204
+ Inputs may reference nodes that are not direct producers (no edge into the
205
+ consumer), e.g. `C.inputs: A[1]` where A is upstream of C via a longer path.
206
+ This is valid as long as A has a directed path to C (so A fires before C).
207
+
208
+ ### Joins
209
+
210
+ - **AND-join** (default): fire iff *all* input slots are `True`. Use for
211
+ "wait for all upstream".
212
+ - **OR-join**: fire iff *≥1* input slot is `True`. Declare with
213
+ `node.join: OR`. Use when a node has multiple producers but should fire on
214
+ any one (e.g. a node that's both a loop member and seeded by a one-shot
215
+ start).
216
+
217
+ ### Deadlock detection
218
+
219
+ If an AND-join `M` has ≥2 producers lying on **mutually-exclusive branches**
220
+ of an XOR-splitter `B` (a node with ≥2 guarded out-edges), `M` would
221
+ deadlock: each fire of `B` sets at most one branch's slots `True`, so `M`
222
+ waits forever for the other half. The checker flags this and (in the CLI)
223
+ prompts to promote `M` to OR-join. OR-joins don't deadlock here because the
224
+ synchronous step semantics make the "≥1 slot" predicate decidable — no
225
+ "will more tokens arrive?" question (the open Petri-net OR-join problem).
226
+
227
+ ```python
228
+ from tickflow import parse, check, promote
229
+ g = parse(text, registry=r)
230
+ for s in check(g): # list[DeadlockSuggestion]
231
+ promote(s, g) # flips s.node.join to "OR"
232
+ ```
233
+
234
+ Constructing a `Runner` with unresolved suggestions raises `DeadlockError`
235
+ (no silent deadlocks).
236
+
237
+ ### Static warnings (parse time)
238
+
239
+ The parser emits warnings for common pitfalls:
240
+
241
+ | Warning | Condition |
242
+ |---------|-----------|
243
+ | Consumer reads from bodyless producer | `C.inputs` references a node with no body — C will receive `None` |
244
+ | Non-producer input | `C.inputs` references a node not connected by an edge — resolves via history, not token flow |
245
+ | Unguarded cycle | A cycle has no guarded edge — will loop forever |
246
+
247
+ At runtime, the engine warns when a node returning `Failure` has guarded
248
+ out-edges (guards are never evaluated for failed nodes — all out-edges
249
+ write `False`).
250
+
251
+ ## Snapshot, pause, rewind
252
+
253
+ ```python
254
+ rn = Runner(graph, registry)
255
+ rn.run_until_idle(max_ticks=100, pause_at={5}) # stop before tick 5
256
+ snap = rn.snapshot() # JSON-able dict
257
+ rn.run_until_idle(max_ticks=100) # finish
258
+ rn.restore(snap) # rewind to tick 5
259
+ rn.run_until_idle(max_ticks=100) # replay (identical if bodies pure)
260
+ ```
261
+
262
+ - **`snapshot()`** returns `{"tick", "marking", "run_state", "status",
263
+ "cancel_reason", "fireable"}` — pure JSON. `run_state` contains `edges`
264
+ (windowed output index), `state` (mutable state per node), and `records`
265
+ (in-memory audit, populated only when `keep_records=True` and no backend).
266
+ - **`restore(snap)`** rewinds: sets tick/marking/run_state/status from `snap`.
267
+ RunState records with `tick >= snap["tick"]` are dropped. A restored
268
+ terminal status (ABORTED/CANCELLED/FAILED) is reset to IDLE so the run can
269
+ resume.
270
+ - **`pause_at={n}`** stops at the tick boundary before tick `n` — no
271
+ half-fired state to save.
272
+ - **Branching / what-if**: `copy.deepcopy(snap)` and `restore` into separate
273
+ Runners. The library doesn't maintain a timeline forest.
274
+ - **`to_json()` / `from_json()`** serialize the full state as a single JSON
275
+ object. The graph and registry are *not* stored — supply them on reload.
276
+
277
+ **Body purity**: bodies should be pure functions of their input view (state
278
+ writes aside). If a body is non-pure, restore-then-replay may diverge from the
279
+ original run (the audit log still records what originally happened).
280
+
281
+ ## Failure, status, and control
282
+
283
+ ### Failure (body error signalling)
284
+
285
+ A body may return `Failure(error, type=...)` instead of a normal value:
286
+
287
+ ```python
288
+ from tickflow import Failure
289
+
290
+ @registry.body("call_llm")
291
+ def call_llm(v):
292
+ try:
293
+ return llm_client.chat(...)
294
+ except NetworkError as e:
295
+ return Failure(str(e), type="infrastructure") # halts the run
296
+ except ParseError as e:
297
+ return Failure(str(e), type="llm") # downstream skipped
298
+ ```
299
+
300
+ - **`type="llm"`** (default): a logical/recoverable failure. The node's
301
+ out-edges write `False`, so downstream AND-joins don't fire (= "upstream
302
+ failed, skip downstream"). The run continues.
303
+ - **`type="infrastructure"`**: an unrecoverable failure. Out-edges write
304
+ `False` **and** the runner enters `ABORTED`, halting all further ticks.
305
+
306
+ A `Failure` is still recorded in `RunState` and the audit log with
307
+ `NodeState.status` (`"failed"` / `"aborted"`) and `NodeState.error`.
308
+
309
+ > **Important**: a failed node writes `False` to **all** out-edges —
310
+ > guarded edges are not evaluated. To implement controllable routing
311
+ > (e.g. retry on failure), have the body return a result dict and let the
312
+ > guard inspect the output value, rather than returning `Failure`.
313
+
314
+ ### RunStatus
315
+
316
+ `Runner.status` is a `RunStatus` enum:
317
+
318
+ | Status | Meaning |
319
+ |--------|---------|
320
+ | `IDLE` | quiescent (nothing fired last tick, or never started) |
321
+ | `RUNNING` | a tick fired (transient; becomes IDLE/terminal next) |
322
+ | `ABORTED` | an infrastructure `Failure` occurred; halted |
323
+ | `CANCELLED` | `cancel()` was called; halted |
324
+ | `FAILED` | (reserved) all nodes failed and nothing fireable |
325
+
326
+ ```python
327
+ rn.cancel("user requested") # -> CANCELLED; ticks become no-ops
328
+ rn.is_idle() # status == IDLE
329
+ rn.is_terminal() # ABORTED/CANCELLED/FAILED, or IDLE with nothing pending
330
+ rn.reset() # clear a non-RUNNING status back to IDLE
331
+ ```
332
+
333
+ ### Node state (`view.state`)
334
+
335
+ Each node has a mutable state dict managed by `RunState` (so it participates
336
+ in snapshots/restore) and is visible to guards. Bodies read/write their own
337
+ state; guards receive a read-only view:
338
+
339
+ ```python
340
+ @registry.body("retryable")
341
+ def retryable(v):
342
+ v.state["attempts"] = v.state.get("attempts", 0) + 1
343
+ return {"ok": v.state["attempts"] >= 3, "attempt": v.state["attempts"]}
344
+
345
+ @registry.guard("should_retry")
346
+ def should_retry(v):
347
+ out = v.B.value
348
+ return isinstance(out, dict) and not out.get("ok") and v.state.get("attempts", 0) < 3
349
+ ```
350
+
351
+ This is how a retry self-loop is expressed: the body tracks `attempts` in
352
+ state, returns a result dict, and the guard checks both the result and the
353
+ state to decide whether to loop.
354
+
355
+ ## Hooks (the observer seam)
356
+
357
+ `on_fire` / `on_tick_end` / `on_tick_start` are the single seam between
358
+ tickflow and the outside world (events, record stores, progress). They fire
359
+ on every node fire / tick end / tick start. Hook exceptions are logged and
360
+ swallowed so a misbehaving observer can't corrupt the run.
361
+
362
+ ```python
363
+ rn.on_fire(lambda ns: event_bus.emit(ns.node, ns.output))
364
+ rn.on_tick_start(lambda tick, fireable: ui.highlight(fireable))
365
+ rn.on_tick_end(lambda tick, firings: db.save(tick, rn.snapshot()))
366
+ ```
367
+
368
+ The `AsyncRunner` accepts async hooks (`async def`).
369
+
370
+ ## Persistence backend
371
+
372
+ A `Runner` constructed with `backend=...` and `session_id=...` persists,
373
+ at the end of every tick: each `NodeState` (the process record) and a full
374
+ snapshot at the new tick index.
375
+
376
+ ```python
377
+ from tickflow import JsonBackend
378
+
379
+ be = JsonBackend("tickflow/sessions")
380
+ rn = Runner(graph, registry, backend=be, session_id="sess-1")
381
+ rn.run_until_idle(max_ticks=100)
382
+
383
+ # Later / elsewhere: resume from the latest persisted tick.
384
+ snap = be.load_snapshot("sess-1", be.latest_tick("sess-1"))
385
+ rn2 = Runner(graph, registry)
386
+ rn2.restore(snap)
387
+ ```
388
+
389
+ - **`Backend`** (Protocol): `save_snapshot` / `load_snapshot` / `latest_tick`
390
+ / `list_snapshots` / `save_firing` / `list_firings` / `save_checkpoint` /
391
+ `list_checkpoints` / `load_checkpoint`.
392
+ - **`JsonBackend(storage_dir)`**: one dir per session, `tick_<N>.json` +
393
+ `firings.jsonl` + `checkpoints.json`. Default; human-inspectable.
394
+ - **`SqliteBackend(db_path)`**: single SQLite file with `snapshots` /
395
+ `firings` / `checkpoints` tables. Better for high tick-throughput.
396
+ - **`NullBackend`**: in-memory, for tests.
397
+
398
+ ### Named checkpoints
399
+
400
+ Layered on the backend:
401
+
402
+ ```python
403
+ rn.checkpoint("after_prep") # save current state under a label
404
+ rn.list_checkpoints() # [(label, tick), ...]
405
+ rn.rollback_to("after_prep") # restore to that checkpoint
406
+ ```
407
+
408
+ ### Graph remap (hot-swap graph structure)
409
+
410
+ After a rollback, you can replace the graph structure and/or registry before
411
+ resuming:
412
+
413
+ ```python
414
+ rn.rollback_to("safe_point")
415
+ rn.remap_graph(new_graph, registry=new_registry)
416
+ rn.run_until_idle(max_ticks=100)
417
+ ```
418
+
419
+ Slots that exist in both graphs keep their current value; new slots start
420
+ `False`; removed slots are discarded. `RunState` is filtered to keep only
421
+ nodes present in the new graph.
422
+
423
+ ## AsyncRunner
424
+
425
+ For graphs whose bodies do IO (LLM calls, HTTP, DB), use `AsyncRunner`.
426
+ Bodies and guards may be `async def`; fireable nodes fire **concurrently**
427
+ within a tick via `asyncio.gather`. Semantics are identical to the sync
428
+ `Runner`.
429
+
430
+ ```python
431
+ from tickflow.async_runner import AsyncRunner
432
+
433
+ @registry.body("harness")
434
+ async def harness(v):
435
+ return await llm_client.chat(prompt=v.seed.value)
436
+
437
+ rn = AsyncRunner(graph, registry, backend=be, session_id="sess-1")
438
+ await rn.run_until_idle(max_ticks=100)
439
+ ```
440
+
441
+ Sync and async bodies/guards may be mixed in the same graph. `Runner` and
442
+ `AsyncRunner` share all state-management logic via `_BaseRunner`.
443
+
444
+ ## Visualization & front-end integration
445
+
446
+ ### Static graph export
447
+
448
+ ```python
449
+ graph.to_dict() # JSON-able {nodes, edges, starts} for front-end rendering
450
+ graph.to_mermaid() # mermaid "graph TD" text (READMEs / debuggers)
451
+ ```
452
+
453
+ `to_dict()` includes derived `producers` per node so the front-end doesn't
454
+ recompute adjacency. `to_mermaid()` renders start nodes with stadium shape
455
+ `([name])`, plain edges `A --> B`, guarded edges `A -->|g| B`.
456
+
457
+ ### Fireable preview & node state
458
+
459
+ ```python
460
+ rn.fireable() # [node names] that would fire on the next tick
461
+ rn.node_states() # {node: {state dict}} — read-only copy (e.g. attempts)
462
+ ```
463
+
464
+ `fireable()` is computed identically to the engine's internal check, so it
465
+ exactly predicts the next `tick()`. `node_states()` returns copies from
466
+ `RunState.all_mutable_states()`.
467
+
468
+ ### Tick lifecycle hooks
469
+
470
+ ```
471
+ on_tick_start(tick, fireable[]) # before any node fires this tick
472
+ → engine runs (body/guard execute)
473
+ → on_fire(ns) × N # after each node fires (receives NodeState)
474
+ on_tick_end(tick, firings[]) # after all fires committed
475
+ ```
476
+
477
+ ### Audit log
478
+
479
+ ```python
480
+ for ns in rn.audit_log(): # list[NodeState]
481
+ print(f"t{ns.tick} {ns.node}: {ns.inputs} → {ns.output} [{ns.status}]")
482
+
483
+ rn.audit_json() # JSON string
484
+ ```
485
+
486
+ Each `NodeState` record includes `inputs` (what the body read), `output`
487
+ (what it returned), `edges_fired` (how tokens propagated), `status`, `error`,
488
+ and `mutable_state` (node state snapshot after the body ran).
489
+
490
+ ## CLI
491
+
492
+ ```
493
+ python -m tickflow run graph.txt -b beh.py [--max-ticks N] [--pause-at T ...]
494
+ python -m tickflow step graph.txt -b beh.py [--from-snapshot snap.json] --ticks N
495
+ python -m tickflow snapshot graph.txt -b beh.py --out snap.json [--max-ticks N]
496
+ python -m tickflow audit run.json
497
+ ```
498
+
499
+ Deadlock suggestions: use `--auto-promote` to accept all, or `--no-promote`
500
+ to reject (and error). In non-interactive environments (CI, scripts), the
501
+ CLI defaults to erroring out with guidance — no hanging on stdin.
502
+
503
+ ## Examples
504
+
505
+ | Example | Description |
506
+ |---------|-------------|
507
+ | `counter_loop` | Counter that loops while < 3, then stops. Cycles + terminating guard + OR-join. |
508
+ | `xor_merge` | XOR branch feeding a Merge. Checker flags AND-join deadlock → promote to OR. |
509
+ | `retry_loop` | Retry with `view.state` counter. Guard reads both output and state. |
510
+ | `fan_out` | Parallel workers + AND-join merge. Three branches fire concurrently. |
511
+ | `pipeline` | Three-stage pipe with `A[k]` index policy pinning A's first fire. |
512
+ | `state_machine` | Approval workflow: submit → review → approve/reject → done. XOR-splitter. |
513
+ | `checkpoint_restore` | Full workflow: checkpoint → rollback → remap → resume. Python script. |
514
+ | `keep_records_false` | Memory-saving mode demo: no audit, but state persists. Python script. |
515
+
516
+ ## Design notes
517
+
518
+ **Why Petri net, not FSM?** The original design — a boolean slot per
519
+ incoming edge, AND over slots to fire, consume-on-fire, produce-into-
520
+ downstream — is exactly a marked graph (a Petri net subclass). An FSM is the
521
+ special case with exactly one live token; `tickflow` allows multiple
522
+ concurrent starts and AND/OR joins, which FSMs don't express natively.
523
+ Cycles (loops) are natural in Petri nets and forbidden in DAG schedulers.
524
+
525
+ **Why synchronous steps?** It makes the OR-join decidable (no "could more
526
+ tokens arrive?" question) and makes snapshots a trivial JSON dict — there's
527
+ no in-flight partial firing to save, so pause lands cleanly on tick
528
+ boundaries.
529
+
530
+ **Why three-layer RunState?** The old design had `History`, `audit` list, and
531
+ `Marking.node_state` as three separate, partially redundant structures. The
532
+ three-layer `RunState` (`_edges` + `_state` + `_records`) unifies them under
533
+ one owner with clear responsibilities. `_edges` and `_state` are always
534
+ maintained (engine needs them); `_records` (detailed audit) is gated on
535
+ `keep_records` and the absence of a persistent backend.
536
+
537
+ **What's deliberately out of scope:** inclusive/XOR-join syntax beyond OR;
538
+ distributed/multi-worker scheduling; a built-in timeline forest (use
539
+ `deepcopy`); LLM token streaming (that's a harness/EventBus concern — tickflow
540
+ records at node granularity).
541
+
542
+ ## Project layout
543
+
544
+ ```
545
+ tickflow/
546
+ ir.py Node, Edge, Graph, InputPolicy, Failure
547
+ parser.py mermaid-like text → Graph (with static warnings)
548
+ checker.py deadlock detection, OR-join promotion, unguarded cycle detection
549
+ state.py NodeState, RunState — single source of truth for all runtime data
550
+ engine.py Marking, tick (pure function), join logic
551
+ runner.py Runner, _BaseRunner (shared sync/async logic)
552
+ async_runner.py AsyncRunner (async bodies, concurrent firing)
553
+ registry.py body/guard registration
554
+ views.py DictView, Resolved, Missing
555
+ persistence.py Backend protocol, JsonBackend, SqliteBackend, NullBackend
556
+ cli.py python -m tickflow ...
557
+ tests/ 17 files, 163 tests
558
+ examples/ 8 examples (6 graph + 2 Python scripts)
559
+ ```
560
+
561
+ ## Running the tests
562
+
563
+ ```bash
564
+ python -m pytest tests/ -q
565
+ ```