state

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 30, 2026 License: Apache-2.0 Imports: 8 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

crucible/state

The pure, abstract state machine kernel of the Crucible suite.

Status: scaffolding. This module is a buildable, empty placeholder. Phase 1 (Kernel Core + serializable IR + host registry) is pending per the roadmap. No types or logic have landed yet.

Import path: github.com/stablekernel/crucible/state

What it is

state is a portable, domain-agnostic state machine kernel, generic over state, event, and context types. It knows nothing about any particular application domain, so the same machine definition runs unchanged from a unit test, a synchronous request handler, and an asynchronous event consumer.

It is the extreme end of the suite's thin-seams philosophy: stdlib-only, no injected IO, no forced dependencies. A tiny dependency graph is a tiny attack surface.

Highlights
  • Pure-function step semantics — firing an event returns (newState, effects, trace) with no IO; the caller dispatches the effects.
  • Serializable definition IR — the canonical machine is pure data, lossless to and from JSON. Guards, actions, and effects are named references with serializable params, bound to a host-provided registry.
  • Two front-ends, one IR — a Go DSL and a future visual editor emit the same IR; a machine authored in code and one loaded from JSON are the same machine.
  • Foundry vocabulary — Forge, Temper, Quench, Cast, Fire, Assay.
  • Functional options everywhere, Trace-first observability, injected clock/ID seams for determinism.

Stability

Stability label: experimental (pre-v1, scaffolding).

Roadmap

Phase 1 (Kernel Core + IR + registry) → Phase 2 (HSM) → Phase 3 (Path Planning) → Phase 4 (Visualization) → Phase 5 (Conformance).

Design rationale and the full roadmap live on the GitHub Discussions board under the State Machine category. See the Overview & Roadmap and Kernel Core discussions.

License

Apache-2.0. See the repository LICENSE and NOTICE.

Documentation

Overview

Package state is the pure, abstract state machine kernel of the Crucible suite — a portable, domain-agnostic engine for forging event-driven services in Go.

Import path: github.com/stablekernel/crucible/state

What this kernel is

state is an abstract, domain-agnostic state machine kernel built once and usable everywhere. It is generic over state, event, and context types (conceptually Machine[S, E, C]) and knows nothing about any particular application domain. The same machine definition runs unchanged from a unit test, a synchronous request handler, and an asynchronous event consumer.

The kernel is stdlib-only. It imports only the Go standard library and performs no injected IO. This is the extreme end of the suite's "thin seams, no-op defaults, no forced dependencies" philosophy: a tiny dependency graph is a tiny attack surface, and the kernel stays a clean, extractable unit forever. The stdlib-only boundary is enforced mechanically by an import-graph test.

Pure-function step semantics

Firing an event returns (newState, effects, trace) without performing any IO. The caller dispatches the effects however it likes — publish to a broker, write to a store, call an RPC. Effects are abstract at the kernel (the kernel never inspects the payload) and concrete at your domain layer. This is what makes one machine usable across tests, handlers, and consumers without change.

The definition IR is the spec

The canonical machine is a serializable definition IR: pure data, lossless to and from JSON. Behavior is not embedded as closures in the IR; every guard, action, and effect is a named reference with serializable params, bound to host-provided implementations through a registry at freeze time. Binding fails loudly if any reference does not resolve.

This is the config/implementation split, borrowed from xstate: structure is dual-authored (code or, eventually, a visual UI) while behavior is always code, surfaced to authors as a named palette. The Go DSL and a future UI are two front-ends that emit the same IR; a machine authored in Go and a machine loaded from JSON are the same machine.

Foundry vocabulary

The lifecycle API uses a small "foundry" verb vocabulary. The noun stays plain — the type is a Machine — only the verbs are themed:

  • Forge — open the builder DSL.
  • Temper — optional, non-failing dev-time diagnostics pass (lint / static analysis), chainable before Quench.
  • Quench — freeze the definition into an immutable Machine; the always-call finalizer that binds refs and panics on misconfiguration.
  • Cast — pour a running instance from the machine.
  • Fire — send an event to an instance and advance it.
  • Assay — check that an externally-constructed entity is legally in a given state.

Operations that favor discoverability over metaphor stay plain: PlanPath, Requirements, Trace, and the To*/LoadFromJSON serializers.

Design

The public API follows the suite's functional-options convention: every public constructor and operation takes a variadic option tail. Required inputs stay positional; everything optional or extensible is an option; a zero-option call reads clean. New capability arrives as a new option — additive-only, never a signature or breaking change. The kernel idiom is fail-fast by default, with resilience and aggregation available opt-in via options.

Observability is Trace-first: the structured Trace is the canonical surface, recording matched transitions, guard and policy evaluations, emitted effects, and the outcome as pure data. An optional WithLogger(*slog.Logger) (no-op by default) is the only logging seam; the kernel never logs unless asked and never imports a third-party logger. Determinism is preserved by injecting time and identifier seams rather than calling time.Now or rand directly.

As a library, the kernel never exits the process — it never calls os.Exit or log.Fatal on an operational error. Panics are reserved strictly for programmer error at construction time (Quench).

Status

The kernel implements the Forge/Temper/Quench build path, Cast/Fire pure step semantics with guards, actions, typed errors and an always-recorded Trace, Assay/Requirements, PlanPath (BFS), FireSeq/FireEach batch helpers, and lossless ToJSON/LoadFromJSON/Provide round-trip.

Hierarchical and orthogonal states extend the same surface: a state may declare nested substates with an initial child (compound states) or parallel regions (orthogonal states). Events resolve child-first and bubble to ancestors; orthogonal regions each receive the event and resolve independently; transitions run the standard exit/entry cascade across the hierarchy; and final states drive done-event completion, including the all-regions-final join for parallel states. The hierarchy serializes, so a nested machine round-trips through JSON losslessly.

Invoked services, the actor model, history states, and the after-scheduler runtime are reserved-but-inert and not yet implemented.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ActionCtx

type ActionCtx[C any] struct {
	Entity C
	Params map[string]any
}

ActionCtx is passed to a bound action function at run time.

type ActionFn

type ActionFn[C any] func(ctx ActionCtx[C]) (Effect, error)

ActionFn produces an effect (or error) for a transition.

type AssayError

type AssayError struct {
	Failures []RequirementFailure
}

AssayError aggregates one or more failing requirements found by Assay.

func (*AssayError) Error

func (e *AssayError) Error() string

type AssayOption

type AssayOption func(*assayConfig)

AssayOption configures Assay.

func WithAggregate

func WithAggregate() AssayOption

WithAggregate makes Assay collect all failing requirements in one pass.

type BatchResult

type BatchResult[S comparable] struct {
	Steps []FireResult[S]
	Trace Trace
	Err   error
}

BatchResult is the result of a batch fire (FireSeq / FireEach).

type Builder

type Builder[S comparable, E comparable, C any] struct {
	// contains filtered or unexported fields
}

Builder is the Forge DSL front-end. It builds the IR and registers implementations by name.

func Forge

func Forge[S comparable, E comparable, C any](name string, opts ...ForgeOption) *Builder[S, E, C]

Forge opens a builder.

Example

ExampleForge builds a document-approval machine with the Forge DSL and fires a single event, showing the resulting state and the effect the transition emitted.

m := buildDocMachine()
doc := &Document{Status: Draft}
res := m.Cast(doc).Fire(context.Background(), Submit)

fmt.Println("state:", res.NewState)
fmt.Println("effects:", res.Effects)
Output:
state: Submitted
effects: [{submitted}]

func (*Builder[S, E, C]) Action

func (b *Builder[S, E, C]) Action(name string, fn ActionFn[C]) *Builder[S, E, C]

Action registers a named action into the builder's palette.

func (*Builder[S, E, C]) CurrentStateFn

func (b *Builder[S, E, C]) CurrentStateFn(fn func(C) S) *Builder[S, E, C]

CurrentStateFn declares how to derive an instance's current state.

func (*Builder[S, E, C]) Do

func (b *Builder[S, E, C]) Do(actionName string, params ...map[string]any) *Builder[S, E, C]

Do attaches a named action ref with params to the most-recent transition.

func (*Builder[S, E, C]) EndRegion

func (b *Builder[S, E, C]) EndRegion() *Builder[S, E, C]

EndRegion closes the most-recent Region block.

func (*Builder[S, E, C]) EndSuperState

func (b *Builder[S, E, C]) EndSuperState() *Builder[S, E, C]

EndSuperState closes the most-recent SuperState block.

func (*Builder[S, E, C]) Final

func (b *Builder[S, E, C]) Final() *Builder[S, E, C]

Final marks the most-recent state as terminal.

func (*Builder[S, E, C]) GoTo

func (b *Builder[S, E, C]) GoTo(to S) *Builder[S, E, C]

GoTo sets the target of the most-recent transition.

func (*Builder[S, E, C]) Guard

func (b *Builder[S, E, C]) Guard(name string, fn GuardFn[C]) *Builder[S, E, C]

Guard registers a named guard into the builder's palette.

func (*Builder[S, E, C]) Initial

func (b *Builder[S, E, C]) Initial(name S) *Builder[S, E, C]

Initial sets the entry state. At the top level it sets the machine's initial state; inside a SuperState or Region block it sets that block's initial child.

func (*Builder[S, E, C]) On

func (b *Builder[S, E, C]) On(event E) *Builder[S, E, C]

On sets the triggering event of the most-recent transition. When no transition is currently open — or the open one already has its event set (a completed `.On(...).GoTo(...)` clause) — On opens a fresh transition from the most-recent state. This lets the hierarchical DSL read `.SubState(X).On(e1).GoTo(Y).On(e2).GoTo(Z)` and `.SubState(X).On(e).GoTo(Y)` without an explicit Transition call.

func (*Builder[S, E, C]) OnDone

func (b *Builder[S, E, C]) OnDone(actionName string, params ...map[string]any) *Builder[S, E, C]

OnDone attaches a named done-action ref to the most-recent state. It runs when the state completes — a compound state when its active leaf is final, a parallel state when every region is final.

func (*Builder[S, E, C]) OnEntry

func (b *Builder[S, E, C]) OnEntry(actionName string, params ...map[string]any) *Builder[S, E, C]

OnEntry attaches a named entry-action ref to the most-recent state.

func (*Builder[S, E, C]) OnExit

func (b *Builder[S, E, C]) OnExit(actionName string, params ...map[string]any) *Builder[S, E, C]

OnExit attaches a named exit-action ref to the most-recent state.

func (*Builder[S, E, C]) OwnedBy

func (b *Builder[S, E, C]) OwnedBy(owner string) *Builder[S, E, C]

OwnedBy tags the most-recent state's ownership.

func (*Builder[S, E, C]) Quench

func (b *Builder[S, E, C]) Quench(opts ...QuenchOption) *Machine[S, E, C]

Quench binds refs, lints, and freezes into an immutable Machine. It panics on any misconfiguration (programmer error) with a file:line pointer.

func (*Builder[S, E, C]) Region

func (b *Builder[S, E, C]) Region(name string) *Builder[S, E, C]

Region opens an orthogonal region inside the current SuperState block. States declared until the matching EndRegion belong to the region, and Initial names the region's initial state.

func (*Builder[S, E, C]) Requires

func (b *Builder[S, E, C]) Requires(req Requirement[C]) *Builder[S, E, C]

Requires attaches a requirement to the most-recent state.

func (*Builder[S, E, C]) State

func (b *Builder[S, E, C]) State(name S) *Builder[S, E, C]

State declares a state node. Inside a SuperState or Region block it declares a substate of that block (equivalent to SubState); at the top level it declares a top-level state.

func (*Builder[S, E, C]) SubState

func (b *Builder[S, E, C]) SubState(name S) *Builder[S, E, C]

SubState declares a substate of the current SuperState or Region block.

func (*Builder[S, E, C]) SuperState

func (b *Builder[S, E, C]) SuperState(name S) *Builder[S, E, C]

SuperState declares a compound (hierarchical) state and opens its block. The substates declared until the matching EndSuperState become its children, and Initial inside the block names the child entered when the superstate is entered.

func (*Builder[S, E, C]) Temper

func (b *Builder[S, E, C]) Temper(opts ...TemperOption) []Diagnostic

Temper runs a non-failing diagnostics pass over the builder's current definition, returning the same findings Quench would panic on — as data.

func (*Builder[S, E, C]) Transition

func (b *Builder[S, E, C]) Transition(from S) *Builder[S, E, C]

Transition opens a new edge from the given state.

func (*Builder[S, E, C]) Use

func (b *Builder[S, E, C]) Use(mw ...Middleware[S, E, C]) *Builder[S, E, C]

Use installs middleware that wraps every Fire.

func (*Builder[S, E, C]) WaitMode

func (b *Builder[S, E, C]) WaitMode(m WaitMode) *Builder[S, E, C]

WaitMode tags the most-recent transition's synchronization mode.

func (*Builder[S, E, C]) When

func (b *Builder[S, E, C]) When(guardName string, params ...map[string]any) *Builder[S, E, C]

When attaches a named guard ref with params to the most-recent transition.

type CastOption

type CastOption[S comparable] func(*castConfig[S])

CastOption configures Cast.

func WithInitialState

func WithInitialState[S comparable](s S) CastOption[S]

WithInitialState supplies the instance's starting state explicitly. Use it when the machine declares no CurrentStateFn (i.e. the current state cannot be derived from the entity). When both are present, the explicit initial state takes precedence over CurrentStateFn.

type Diagnostic

type Diagnostic struct {
	Severity string
	Message  string
	SrcFile  string
	SrcLine  int
}

Diagnostic is a non-failing finding from Temper.

type Effect

type Effect = any

Effect is an abstract, domain-defined payload. The kernel never inspects it.

type ErrActionFailed

type ErrActionFailed struct {
	TransitionName string
	ActionName     string
	Cause          error
}

ErrActionFailed wraps a bound action that returned an error during emission.

func (*ErrActionFailed) Error

func (e *ErrActionFailed) Error() string

func (*ErrActionFailed) Unwrap

func (e *ErrActionFailed) Unwrap() error

type ErrGuardFailed

type ErrGuardFailed struct {
	GuardName string
	Reason    string
}

ErrGuardFailed is returned when a named guard returned false.

func (*ErrGuardFailed) Error

func (e *ErrGuardFailed) Error() string

type ErrGuardPanic

type ErrGuardPanic struct {
	GuardName string
	Recovered any
}

ErrGuardPanic is returned when a guard panicked and was recovered.

func (*ErrGuardPanic) Error

func (e *ErrGuardPanic) Error() string

type ErrInvalidTransition

type ErrInvalidTransition struct {
	From   string
	To     string
	Event  string
	Reason string
}

ErrInvalidTransition is returned when no transition matched (current, event), or all matching transitions had failing guards.

func (*ErrInvalidTransition) Error

func (e *ErrInvalidTransition) Error() string

type ErrNoInitialState

type ErrNoInitialState struct {
	Machine string
}

ErrNoInitialState is returned/panicked by Cast when neither a CurrentStateFn is declared on the machine nor an explicit initial state is supplied via WithInitialState — there is no way to derive the instance's starting state. This is a programmer error, consistent with Quench's panic-on-misuse posture.

func (*ErrNoInitialState) Error

func (e *ErrNoInitialState) Error() string

type ErrNoPath

type ErrNoPath struct {
	From string
	To   string
}

ErrNoPath is returned by PlanPath when no event sequence connects from->to.

func (*ErrNoPath) Error

func (e *ErrNoPath) Error() string

type ErrPolicyDenied

type ErrPolicyDenied struct {
	PolicyName string
	Reason     string
}

ErrPolicyDenied is returned when a policy returned Deny.

func (*ErrPolicyDenied) Error

func (e *ErrPolicyDenied) Error() string

type ErrUnboundRef

type ErrUnboundRef struct {
	Kind string // "guard" | "action" | "effect"
	Name string
}

ErrUnboundRef is returned when a guard/action/effect ref in the IR did not resolve against the registry (raised at Quench / Provide).

func (*ErrUnboundRef) Error

func (e *ErrUnboundRef) Error() string

type ErrUndeclaredState

type ErrUndeclaredState struct {
	State string
}

ErrUndeclaredState is returned when a state value was never declared.

func (*ErrUndeclaredState) Error

func (e *ErrUndeclaredState) Error() string

type FireFunc

type FireFunc[S comparable, E comparable, C any] func(ctx context.Context, event E) FireResult[S]

FireFunc is the inner step the middleware chain wraps.

type FireOption

type FireOption func(*fireConfig)

FireOption configures Fire / FireSeq / FireEach.

func CollectAll

func CollectAll() FireOption

CollectAll makes a batch fire run every step and gather all errors instead of stopping at the first.

type FireResult

type FireResult[S comparable] struct {
	NewState S
	Effects  []Effect
	Trace    Trace
	Err      error
}

FireResult is the result of a single Fire.

func FireEach

func FireEach[S comparable, E comparable, C any](
	ctx context.Context, instances []*Instance[S, E, C], event E, opts ...FireOption,
) []FireResult[S]

FireEach fans one event across an explicit set of instances, preserving per-instance attribution.

type ForgeOption

type ForgeOption func(*forgeConfig)

ForgeOption configures Forge.

type GuardCtx

type GuardCtx[C any] struct {
	Entity C
	Params map[string]any
}

GuardCtx is passed to a bound guard function at run time.

type GuardFn

type GuardFn[C any] func(ctx GuardCtx[C]) bool

GuardFn is a pure predicate on the entity.

type HistoryType

type HistoryType int

HistoryType is the reserved drop-in surface for shallow/deep history states.

const (
	HistoryNone HistoryType = iota
	HistoryShallow
	HistoryDeep
)

History kinds. HistoryNone is the v1 default (no history); shallow and deep are reserved for the deferred history-state feature.

type IR

type IR[S comparable, E comparable, C any] struct {
	Name       string           `json:"name"`
	States     []State[S, E, C] `json:"states,omitempty"`
	Initial    S                `json:"initial"`
	HasInitial bool             `json:"hasInitial"`
}

IR is the serializable definition produced and consumed by the data front-end. It is the canonical machine: pure, lossless data. Behavior lives in a host registry and is referenced by name (via Ref), never embedded, so the IR round-trips to and from JSON without losing structure or bindings' identity.

Non-serializable concerns — CurrentStateFn, requirement predicates, and middleware — are pure-runtime and are intentionally absent from the IR; a machine rehydrated from JSON is Cast from an explicit state and bound to a registry via Provide.

func LoadFromJSON

func LoadFromJSON[S comparable, E comparable, C any](b []byte, opts ...LoadOption) (*IR[S, E, C], error)

LoadFromJSON rehydrates an IR from JSON.

func (*IR[S, E, C]) Provide

func (ir *IR[S, E, C]) Provide(reg *Registry[C], opts ...ProvideOption) *Builder[S, E, C]

Provide binds every Ref in the IR against the host registry and returns a Builder ready to Quench. Refs that do not resolve are surfaced at Quench as the typed *ErrUnboundRef (the same failure the DSL raises for an unregistered ref), so a UI/JSON-authored machine and a DSL-authored machine fail identically.

type Instance

type Instance[S comparable, E comparable, C any] struct {
	// contains filtered or unexported fields
}

Instance binds a Machine to one entity and carries trace history.

func (*Instance[S, E, C]) Configuration

func (i *Instance[S, E, C]) Configuration() []S

Configuration returns all currently-active leaves, in declaration order. len == 1 for a flat or single-spine machine; len == N when N regions are active in parallel.

func (*Instance[S, E, C]) Current

func (i *Instance[S, E, C]) Current() S

Current returns the primary (first) active leaf — the common "what state am I really in?" answer, back-compatible with flat machines.

func (*Instance[S, E, C]) Entity

func (i *Instance[S, E, C]) Entity() C

Entity returns the entity this instance is bound to.

func (*Instance[S, E, C]) Fire

func (i *Instance[S, E, C]) Fire(ctx context.Context, event E, opts ...FireOption) FireResult[S]

Fire runs the full transition pipeline for a single event.

func (*Instance[S, E, C]) FireSeq

func (i *Instance[S, E, C]) FireSeq(ctx context.Context, events []E, opts ...FireOption) BatchResult[S]

FireSeq drives a sequence of events into one instance, threading intermediate state and merging the per-step traces into one ordered Trace.

Example

ExampleInstance_FireSeq drives a machine through a sequence of events, walking a document from Draft to Published in one batch.

m := buildDocMachine()
doc := &Document{Status: Draft, ReviewerID: strptr("rev-1")}
batch := m.Cast(doc).FireSeq(context.Background(), []DocEvent{Submit, Approve, Publish})

fmt.Println("steps:", len(batch.Steps))
fmt.Println("final:", batch.Steps[len(batch.Steps)-1].NewState)
Output:
steps: 3
final: Published

func (*Instance[S, E, C]) History

func (i *Instance[S, E, C]) History() []Trace

History returns the ordered traces recorded on this instance.

type LoadOption

type LoadOption func(*loadConfig)

LoadOption configures LoadFromJSON.

type Machine

type Machine[S comparable, E comparable, C any] struct {
	// contains filtered or unexported fields
}

Machine is the immutable, Quenched definition.

func (*Machine[S, E, C]) Assay

func (m *Machine[S, E, C]) Assay(s S, entity C, opts ...AssayOption) error

Assay checks that an externally-constructed entity legally satisfies a state's declarative requirements, without firing. The default mode is fail-fast (the returned *AssayError carries the first failure); WithAggregate collects every failure in one pass. The error type is uniform across modes.

Example

ExampleMachine_Assay checks an externally-built entity against a state's declarative requirements without firing a transition.

m := buildDocMachine()

missing := m.Assay(Approved, &Document{Status: Approved})
ok := m.Assay(Approved, &Document{Status: Approved, ReviewerID: strptr("rev-1")})

fmt.Println("missing reviewer:", missing != nil)
fmt.Println("with reviewer:", ok)
Output:
missing reviewer: true
with reviewer: <nil>

func (*Machine[S, E, C]) Cast

func (m *Machine[S, E, C]) Cast(entity C, opts ...CastOption[S]) *Instance[S, E, C]

Cast pours a fresh running instance from the machine, binding it to the given entity. The instance's starting state is derived from the entity via the machine's CurrentStateFn; if no CurrentStateFn was declared, an explicit initial state must be supplied via WithInitialState. When both are present, WithInitialState wins. With neither, Cast panics with *ErrNoInitialState — a programmer error, consistent with Quench's panic-on-misuse posture.

The entity value is held on the Instance and supplied to guards and actions at Fire time; it is never threaded through context.

Example (Hierarchical)

ExampleMachine_Cast_hierarchical enters a hierarchical machine: casting into a compound state descends to its initial child, so the job starts in Starting under the Running superstate.

m := buildJobMachine()
job := &Job{Status: Queued}
inst := m.Cast(job)
res := inst.Fire(context.Background(), Enqueue)

fmt.Println("state:", res.NewState)
Output:
state: Starting

func (*Machine[S, E, C]) Name

func (m *Machine[S, E, C]) Name() string

Name returns the machine name.

func (*Machine[S, E, C]) PlanPath

func (m *Machine[S, E, C]) PlanPath(from, to S, entity C, opts ...PlanOption) ([]E, error)

PlanPath returns the shortest event sequence that drives an instance from the `from` state to the `to` state, found by breadth-first search over the static transition graph. Guards are honored against the supplied entity, so the returned path is one the entity can actually traverse. The entity is never mutated. ErrNoPath is returned when no sequence connects from->to.

Example

ExampleMachine_PlanPath finds the shortest event sequence that drives a document from Draft to Published, honoring guards against the entity.

m := buildDocMachine()
doc := &Document{Status: Draft, ReviewerID: strptr("rev-1")}
path, err := m.PlanPath(Draft, Published, doc)

fmt.Println("err:", err)
fmt.Println("steps:", len(path))
Output:
err: <nil>
steps: 3

func (*Machine[S, E, C]) Requirements

func (m *Machine[S, E, C]) Requirements(s S) []Requirement[C]

Requirements returns the declarative requirements for a state, or nil if the state declares none (or is undeclared).

func (*Machine[S, E, C]) ToDOT

func (m *Machine[S, E, C]) ToDOT(opts ...VizOption) string

ToDOT renders the machine as GraphViz DOT for richer SVG output — slides, docs sites, and large hierarchical machines where Mermaid grows unreadable.

Compound and parallel states become subgraph clusters, final states draw a double border, owners encode as node fillcolor, and the layout defaults to rankdir=LR (well suited to lifecycles).

func (*Machine[S, E, C]) ToJSON

func (m *Machine[S, E, C]) ToJSON(opts ...ToJSONOption) ([]byte, error)

ToJSON serializes the machine's IR losslessly.

Example

ExampleMachine_ToJSON serializes a machine's IR and reports that the canonical definition round-trips: loading the JSON and reserializing yields identical bytes.

m := buildDocMachine()
data, _ := m.ToJSON()

ir, _ := state.LoadFromJSON[DocState, DocEvent, *Document](data)
m2 := ir.Provide(docRegistry()).Quench()
data2, _ := m2.ToJSON()

fmt.Println("stable:", string(data) == string(data2))
Output:
stable: true

func (*Machine[S, E, C]) ToMermaid

func (m *Machine[S, E, C]) ToMermaid(opts ...VizOption) string

ToMermaid renders the machine as a GitHub-renderable Mermaid stateDiagram-v2.

Transitions render as labeled edges (Event, with guards as a bracketed suffix); the initial state is reached from the [*] start marker and final states point back to [*]. Compound states render as nested state blocks and parallel states use the -- region divider. Owner tags render as classDef color-coding, since stateDiagram-v2 has no native swim lanes.

Example

ExampleMachine_ToMermaid renders a hierarchical machine as a Mermaid stateDiagram-v2: the initial marker, the Running superstate as a nested block with its own initial child, the cross-cutting Cancel transition, and the final-state markers.

fmt.Println(buildJobMachine().ToMermaid())
Output:
stateDiagram-v2
    [*] --> Queued
    state Running {
        [*] --> Running__Starting
        Running__Starting
        Running__Executing
        Running__Starting --> Running__Executing: Begin
    }
    JobDone --> [*]
    Canceled --> [*]
    Queued --> Running: Enqueue
    Running --> Canceled: Cancel
    Running__Executing --> JobDone: Finish
    classDef owner_Scheduler fill:#f0d9ff
    classDef owner_Worker fill:#d9f2f2
    class Queued owner_Scheduler
    class Running owner_Worker

type Middleware

type Middleware[S comparable, E comparable, C any] func(next FireFunc[S, E, C]) FireFunc[S, E, C]

Middleware wraps a Fire, outside-in.

type MultiRegionErr

type MultiRegionErr struct {
	Errors []error
}

MultiRegionErr aggregates the errors raised by more than one orthogonal region firing on a single event. Its Unwrap returns each region's error so errors.As finds any region's typed error.

func (*MultiRegionErr) Error

func (e *MultiRegionErr) Error() string

func (*MultiRegionErr) Unwrap

func (e *MultiRegionErr) Unwrap() []error

Unwrap exposes the per-region errors for errors.As / errors.Is traversal.

type Outcome

type Outcome int

Outcome classifies the result recorded in a Trace.

const (
	OutcomeSuccess Outcome = iota
	OutcomeInvalidTransition
	OutcomeGuardFailed
	OutcomeGuardPanic
	OutcomePolicyDenied
	OutcomeEffectError
)

Outcomes recorded in a Trace, one per Fire: success or the specific failure class that stopped the transition.

type P

type P = map[string]any

P is a convenience alias for serializable params attached to a named Ref.

type PlanOption

type PlanOption func(*planConfig)

PlanOption configures PlanPath.

type ProvideOption

type ProvideOption func(*provideConfig)

ProvideOption configures Provide.

type QuenchOption

type QuenchOption func(*quenchConfig)

QuenchOption configures Quench.

func Strict

func Strict() QuenchOption

Strict makes Quench reject any lint warning, not just hard errors.

type Ref

type Ref struct {
	Name   string         `json:"name"`
	Params map[string]any `json:"params,omitempty"`
}

Ref is a named reference to a host-provided implementation plus serializable params. The IR carries Refs; the registry binds Name -> func at Provide/Quench time.

type Region

type Region[S comparable, E comparable, C any] struct {
	Name         string           `json:"name"`
	States       []State[S, E, C] `json:"states,omitempty"`
	InitialChild *S               `json:"initialChild,omitempty"`
}

Region is one orthogonal region of a parallel state: a self-contained set of substates with its own initial child. When the owning parallel state is active, every region is active simultaneously, each tracking its own leaf.

type Registry

type Registry[C any] struct {
	// contains filtered or unexported fields
}

Registry holds the host behavior palette, by name.

func NewRegistry

func NewRegistry[C any]() *Registry[C]

NewRegistry returns an empty host registry.

func (*Registry[C]) Action

func (r *Registry[C]) Action(name string, fn ActionFn[C]) *Registry[C]

Action registers a named action implementation.

func (*Registry[C]) Guard

func (r *Registry[C]) Guard(name string, fn GuardFn[C]) *Registry[C]

Guard registers a named guard implementation.

type Requirement

type Requirement[C any] struct {
	Name      string
	Predicate func(C) bool
	Setter    func(C) // optional: mutate a zero entity to satisfy Predicate
}

Requirement is a declarative condition for a state, used by Assay.

type RequirementFailure

type RequirementFailure struct {
	Name   string
	Reason string
}

RequirementFailure records one unmet requirement.

type State

type State[S comparable, E comparable, C any] struct {
	Name        S                     `json:"name"`
	OwnedBy     string                `json:"ownedBy,omitempty"`
	Transitions []Transition[S, E, C] `json:"transitions,omitempty"`

	OnEntry []Ref `json:"onEntry,omitempty"`
	OnExit  []Ref `json:"onExit,omitempty"`
	IsFinal bool  `json:"isFinal,omitempty"`
	OnDone  []Ref `json:"onDone,omitempty"`

	// Hierarchy. Children holds the nested substates of a compound state, and
	// InitialChild names the substate entered transitively when the compound
	// state is entered. Both serialize, so the hierarchy round-trips through
	// JSON. Parent is a runtime-only back-pointer rebuilt after Quench/Provide.
	Children     []State[S, E, C] `json:"children,omitempty"`
	InitialChild *S               `json:"initialChild,omitempty"`

	// Regions holds the orthogonal regions of a parallel state. Mutually
	// exclusive with Children/InitialChild.
	Regions []Region[S, E, C] `json:"regions,omitempty"`

	// Reserved drop-in surface.
	HistoryType HistoryType     `json:"historyType,omitempty"`
	Invoke      []Ref           `json:"invoke,omitempty"`
	Parent      *State[S, E, C] `json:"-"`
}

State is a node in the machine graph.

A state is one of three shapes: a leaf (no Children, no Regions), a compound (hierarchical) state declaring Children plus an InitialChild, or a parallel state declaring Regions. A state is never both compound and parallel.

type TemperOption

type TemperOption func(*temperConfig)

TemperOption configures Temper.

type ToJSONOption

type ToJSONOption func(*toJSONConfig)

ToJSONOption configures ToJSON.

func WithoutSrcPos

func WithoutSrcPos() ToJSONOption

WithoutSrcPos omits the diagnostic source-position fields (srcFile/srcLine) from the serialized IR. Source positions are captured from the builder via runtime.Caller, so they carry the absolute filesystem path of the worktree that authored the machine — which makes them non-portable across checkouts. They are diagnostic-only metadata ("defined at machine.go:84" tooltips) and have no effect on loading or behavior, so stripping them yields a stable, position-independent serialization. Use it for committed goldens and any interchange that must be byte-identical regardless of where it was generated.

type Trace

type Trace struct {
	Machine            string                     `json:"machine,omitempty"`
	Event              string                     `json:"event,omitempty"`
	FromState          string                     `json:"fromState,omitempty"`
	SelectedTransition *Transition[any, any, any] `json:"-"`
	GuardsEvaluated    []string                   `json:"guardsEvaluated,omitempty"`
	PoliciesEvaluated  []string                   `json:"policiesEvaluated,omitempty"`
	EffectsEmitted     []string                   `json:"effectsEmitted,omitempty"`
	Microsteps         []string                   `json:"microsteps,omitempty"`

	// MatchedAt names the state whose transition actually fired. For a flat
	// machine it equals FromState; for an HSM it may be an ancestor reached by
	// the child-first bubble.
	MatchedAt string `json:"matchedAt,omitempty"`
	// ExitedStates and EnteredStates record the transition's exit/entry cascade
	// in execution order (exit innermost-first, entry outermost-first).
	ExitedStates  []string `json:"exitedStates,omitempty"`
	EnteredStates []string `json:"enteredStates,omitempty"`

	Outcome Outcome `json:"outcome"`
}

Trace is the kernel's canonical observability surface — pure data recorded on every Fire.

type Transition

type Transition[S comparable, E comparable, C any] struct {
	From S `json:"from"`
	To   S `json:"to"`
	On   E `json:"on"`

	Guards   []Ref    `json:"guards,omitempty"`
	Effects  []Ref    `json:"effects,omitempty"`
	WaitMode WaitMode `json:"waitMode,omitempty"`

	Internal  bool           `json:"internal,omitempty"`
	EventLess bool           `json:"eventLess,omitempty"`
	After     *time.Duration `json:"after,omitempty"`

	SrcFile string `json:"srcFile,omitempty"`
	SrcLine int    `json:"srcLine,omitempty"`
	// contains filtered or unexported fields
}

Transition is a directed edge.

type VizOption

type VizOption func(*vizConfig)

VizOption configures the ToMermaid and ToDOT renderers.

func LeftToRight

func LeftToRight() VizOption

LeftToRight lays the diagram out left-to-right (Mermaid direction LR, DOT rankdir=LR).

func TopToBottom

func TopToBottom() VizOption

TopToBottom lays the diagram out top-to-bottom (Mermaid default, DOT rankdir=TB).

func WithoutGuards

func WithoutGuards() VizOption

WithoutGuards omits the bracketed guard annotations from transition labels.

func WithoutOwners

func WithoutOwners() VizOption

WithoutOwners omits owner color-coding (Mermaid classDef / DOT fillcolor).

type WaitMode

type WaitMode int

WaitMode tags a transition's synchronization expectation. The kernel only stores the tag; the consumer acts on it.

const (
	SyncReply WaitMode = iota
	FireAndForget
	ValidatePoll
)

Wait modes. SyncReply awaits a reply, FireAndForget emits and moves on, and ValidatePoll signals the consumer to poll the entity (re-running Assay) until it validates.

Directories

Path Synopsis
Package conformance proves that a state machine behaves correctly.
Package conformance proves that a state machine behaves correctly.
expr module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL