This directory contains comprehensive real-world examples demonstrating the capabilities of the OttoChain state machine framework. Each example showcases different patterns, complexities, and use cases for building JSON-encoded deterministic state machines.
These examples demonstrate that OttoChain's state machine infrastructure can model complex, real-world workflows entirely through JSON configuration without custom state machine code. Each example is fully implemented, tested, and demonstrates specific advanced features.
- Complete workflows from simple games to complex multi-party systems
- JSON-encoded machines showing zero-code deployment patterns
- Advanced features like cross-machine triggers, parent-child spawning, and broadcast coordination
- Real-world patterns applicable to logistics, healthcare, finance, and governance
- Test implementations demonstrating verification approaches
| Feature | Tic-Tac-Toe | Fuel Logistics | Clinical Trial | Real Estate | Riverdale Economy |
|---|---|---|---|---|---|
| State Machines | 1 | 4 | 6 | 8 | 6 types (17 instances) |
| Total States | 4 | 23 | 47 | 58 | 37 (across types) |
| Participants | 2 | 5 | 6 | 8 | 13 active participants |
| Complexity | ⭐ Simple | ⭐⭐ Moderate | ⭐⭐⭐ Complex | ⭐⭐⭐ Complex | ⭐⭐⭐⭐ Very Complex |
| Script Pattern | ✅ Yes (game state) | ❌ No | ❌ No | ❌ No | ❌ No |
| Cross-Machine Triggers | ❌ No | ✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes (15+ types) |
| Multiple Guards | ❌ No | ❌ No | ✅ Yes (5 outcomes) | ✅ Yes (3 outcomes) | ✅ Yes |
| Bi-directional Transitions | ❌ No | ❌ No | ✅ Yes | ✅ Yes | ❌ No |
| Broadcast Triggers | ❌ No | ❌ No | ❌ No | ❌ No | ✅ Yes (tax, rates, stress tests) |
| Parent-Child Spawning | ❌ No | ❌ No | ❌ No | ❌ No | ✅ Yes (auctions) |
| Self-Transitions | ✅ Yes (playing) | ❌ No | ❌ No | ✅ Yes (3 types) | ✅ Yes (multiple) |
| Structured Outputs | ✅ Yes (game_completed) | ✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes |
| Use Case | Game/Tutorial | Supply Chain | Healthcare | Real Estate/Finance | Economic Ecosystem |
Complexity: ⭐⭐ Moderate State Machines: 4 Participants: 5
A supply chain workflow demonstrating fuel delivery contracts with real-time GPS tracking, quality inspections, and supplier approval processes.
- GPS location tracking with geofencing violations
- Quality inspection workflows with pass/fail gates
- Supplier approval with vetting process
- Contract lifecycle from draft through completion
- Cross-machine triggers for shipment tracking
Supplier Approval → Contract Creation → GPS Tracking →
Quality Inspection → Delivery → Payment
Complexity: ⭐⭐⭐ Complex State Machines: 6 Participants: 6
A Phase III clinical trial workflow demonstrating multi-party coordination, adverse event handling, and regulatory compliance with multiple guards on single events.
- Multiple guards on same event (5 outcomes from lab results)
- Bi-directional transitions (pause/resume workflows)
- Cross-machine dependencies (4 machines checked for contingencies)
- Adverse event monitoring with escalation
- Regulatory oversight and approval
- Insurance claims processing
Recruitment → Enrollment → Active Trial → Lab Processing →
Adverse Event Monitoring → Regulatory Review → Completion
Complexity: ⭐⭐⭐ Complex State Machines: 8 Participants: 8
A complete real estate transaction from listing through purchase, mortgage servicing, potential default, foreclosure, and REO (bank-owned property).
- Multiple self-transitions on same state (payment/servicing/sale)
- Bi-directional recovery paths (delinquency cure)
- Complex multi-machine guards (4 contingencies)
- Conditional earnest money disbursement
- Mortgage servicing with secondary market transfers
- Foreclosure and REO workflows
- Long-term asset lifecycle management
Listing → Offer → Contract → Contingencies → Closing → Ownership
↓
Mortgage
↓
(If default) → Foreclosure → REO → Re-list
Complexity: ⭐⭐⭐⭐ Very Complex State Machine Types: 6 Machine Instances: 17 (+ dynamic children) Participants: 13
A complete economic ecosystem simulation with manufacturing, retail, banking, consumers, monetary policy, and governance demonstrating the most advanced features.
- 17 machine instances across 6 types
- Broadcast triggers (tax collection to 11 machines, rate policy to 3 banks)
- Parent-child spawning (dynamic auction machines)
- System-wide coordination (stress testing, emergency lending)
- Complex dependency graphs
- Economic cascades (loan defaults affecting entire system)
- Computed payloads (interest rate calculations)
- Multi-party marketplaces
Raw Materials → Manufacturer → Retailer → Consumer
↓
Bank Loans
↓
Federal Reserve (Monetary Policy)
↓
Governance (Tax Collection)
Complexity: ⭐ Simple State Machines: 1 Participants: 2 Total States: 4
A two-player game demonstrating the oracle-centric architecture pattern where the script acts as the game engine and the state machine orchestrates the game lifecycle.
Script (Game Engine):
- Holds complete game state (board, moves, players)
- Enforces game rules and move validation
- Detects win/draw conditions automatically
- Maintains move history
- 6 methods: initialize, makeMove, checkWinner, getBoard, resetGame, cancelGame
State Machine (Lifecycle Orchestrator):
- Manages game phases: setup → playing → finished/cancelled
- Calls oracle methods via
_oracleCall - Guards check oracle state for transitions
- Self-transitions during gameplay
- Minimal state - delegates game logic to oracle
This separation demonstrates a key architectural pattern: oracle holds state and logic, state machine orchestrates lifecycle.
4 states managing game lifecycle:
setup- Initial state, waiting for playersplaying- Game active (self-transitions during moves)finished- Game completed (win/draw) - final statecancelled- Game cancelled - final state
- Oracle-Centric Pattern - Oracle is the single source of truth for game state
- Oracle Method Dispatch - Single script with 6 methods handling all game logic
- Validation in Oracle - Move validation happens in oracle, not state machine
- Self-Transitions - State machine stays in
playingduring move sequences - Multiple Guards - Same event (
make_move) transitions to different states based on oracle status - Win Detection - Oracle checks all 8 winning patterns deterministically
- Reset Support - Clear board for new round without recreating machines
- Structured Outputs - Emit
game_completedoutput on finish
setup → playing (self-transitions) → finished/cancelled
│ ↑
│ └── make_move events ───────┘
│
└──→ _oracleCall(makeMove)
- Oracle validates move
- Updates board state
- Checks win/draw
- Returns result
- Foundational pattern - Oracle-centric architecture scales to complex logic
- Familiar domain - Everyone understands tic-tac-toe rules
- Clean separation - State vs. lifecycle management clearly delineated
- Core concepts - Oracle calls, guards, self-transitions, validation patterns
- Complete example - Shows oracle creation, invocation, and state updates
- Well tested - Full test suite demonstrating all scenarios
What: One machine's transition triggers an event on another machine.
Examples:
- Fuel: GPS tracker triggers contract shipment events
- Clinical: Visit completion triggers lab sample processing
- Real Estate: Property closing triggers mortgage activation
- Riverdale: Supply chain (retailer → manufacturer → retailer)
Use Cases: Coordinating multi-party workflows, supply chains, financial transactions
What: Single event can transition to multiple different states based on complex conditions.
Examples:
- Clinical Trial: Lab
completeevent → 5 possible outcomes (passed, questionable, failed, critical, retest_required) based on quality, contamination, and biomarker levels - Real Estate: Inspection
approveevent → 3 outcomes (passed, passed_with_repairs, failed) based on issue count and repair agreement
Use Cases: Complex decision trees, quality assessment, risk evaluation
What: Ability to transition back and forth between states for pause/resume or error recovery.
Examples:
- Clinical Trial: Patient
active⇄paused,adverse_event→active(if resolved) - Real Estate: Mortgage
current⇄delinquent_30⇄delinquent_60(cure with payment)
Use Cases: Pause/resume workflows, error recovery, delinquency management
What: One machine triggers events on multiple machines simultaneously.
Examples:
- Riverdale: Governance tax collection triggers
pay_taxeson 11 machines (4 manufacturers, 4 retailers, 3 consumers) - Riverdale: Federal Reserve rate adjustment triggers
rate_adjustmenton 3 banks - Riverdale: Stress test initiation triggers
fed_directiveon all banks
Use Cases: System-wide policy changes, regulatory coordination, mass notifications
What: Dynamic creation of child state machines with independent lifecycles.
Examples:
- Riverdale: Consumer listing item spawns Auction child machine
- Child completes lifecycle:
listed→bid_received→sold - Child completion triggers parent's
sale_completedevent
Use Cases: Dynamic marketplaces, temporary workflows, auction systems, job scheduling
What: Events that don't change state but modify internal data.
Examples:
- Real Estate: Mortgage
current→currentwith three different events:make_payment: Updates balance, increments paymentCounttransfer_servicing: Changes servicer, preserves balancesell_loan: Changes owner, records sale price
- Riverdale: Manufacturer states allowing
pay_taxeswithout state change
Use Cases: Continuous operations, payment processing, servicing transfers
What: Formatted output generation for external systems (webhooks, emails, reports).
Examples:
- Fuel: Geofencing alerts, shipment notifications
- Clinical Trial: Regulatory reports, enrollment webhooks
- Real Estate: Legal notices (foreclosure), payment disbursements
- Riverdale: Credit reports, audit findings, regulatory notices
Use Cases: External system integration, notifications, compliance reporting
- New to State Machines? → Start with Tic-Tac-Toe
- Supply Chain Use Cases? → Check out Fuel Logistics
- Healthcare/Compliance? → Explore Clinical Trial
- Financial Services? → Study Real Estate
- Complex Ecosystems? → Dive into Riverdale Economy
Tic-Tac-Toe (basics)
↓
Fuel Logistics (cross-machine triggers, basic workflows)
↓
Clinical Trial (multiple guards, bi-directional transitions)
↓
Real Estate (self-transitions, complex guards, long-term lifecycle)
↓
Riverdale Economy (broadcast triggers, parent-child spawning, full ecosystem)
All examples have comprehensive test implementations:
- Fuel Logistics:
modules/shared-data/src/test/scala/xyz/kd5ujc/shared_data/examples/FuelLogisticsStateMachineSuite.scala - Clinical Trial:
modules/shared-data/src/test/scala/xyz/kd5ujc/shared_data/examples/ClinicalTrialStateMachineSuite.scala - Real Estate:
modules/shared-data/src/test/scala/xyz/kd5ujc/shared_data/examples/RealEstateStateMachineSuite.scala - Riverdale Economy:
modules/shared-data/src/test/scala/xyz/kd5ujc/shared_data/examples/RiverdaleEconomyStateMachineSuite.scala - Tic-Tac-Toe:
modules/shared-data/src/test/scala/xyz/kd5ujc/shared_data/examples/TicTacToeGameSuite.scala
- Zero-Code Deployment: All machines are JSON-encoded, no custom code required
- Composability: Mix and match patterns across different domains
- Versioning: Workflow rules can evolve without code changes
- Auditability: Complete machine logic visible in JSON definitions
- Portability: Definitions transferable across environments
- Validation: Schema-validated at startup
When adding new examples:
- Follow the established documentation structure
- Include state diagrams (both
.dotsource and rendered.png) - Provide comprehensive test implementations
- Document key features and patterns demonstrated
- Add to comparison matrices in this README
- Include workflow examples and sequence diagrams
For questions or suggestions, please open an issue or submit a pull request.
- State Machine Design Guide - Best practices for designing state machines
- API Reference - HTTP API documentation
- Architecture Overview - System architecture
- Deployment Guide - Deploying state machine workflows
All examples are fully implemented, tested, and production-ready. The JSON-encoded approach demonstrates that complex, real-world workflows can be modeled without writing custom state machine code.