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 ¶
- type ActionCtx
- type ActionFn
- type AssayError
- type AssayOption
- type BatchResult
- type Builder
- func (b *Builder[S, E, C]) Action(name string, fn ActionFn[C]) *Builder[S, E, C]
- func (b *Builder[S, E, C]) CurrentStateFn(fn func(C) S) *Builder[S, E, C]
- func (b *Builder[S, E, C]) Do(actionName string, params ...map[string]any) *Builder[S, E, C]
- func (b *Builder[S, E, C]) EndRegion() *Builder[S, E, C]
- func (b *Builder[S, E, C]) EndSuperState() *Builder[S, E, C]
- func (b *Builder[S, E, C]) Final() *Builder[S, E, C]
- func (b *Builder[S, E, C]) GoTo(to S) *Builder[S, E, C]
- func (b *Builder[S, E, C]) Guard(name string, fn GuardFn[C]) *Builder[S, E, C]
- func (b *Builder[S, E, C]) Initial(name S) *Builder[S, E, C]
- func (b *Builder[S, E, C]) On(event E) *Builder[S, E, C]
- func (b *Builder[S, E, C]) OnDone(actionName string, params ...map[string]any) *Builder[S, E, C]
- func (b *Builder[S, E, C]) OnEntry(actionName string, params ...map[string]any) *Builder[S, E, C]
- func (b *Builder[S, E, C]) OnExit(actionName string, params ...map[string]any) *Builder[S, E, C]
- func (b *Builder[S, E, C]) OwnedBy(owner string) *Builder[S, E, C]
- func (b *Builder[S, E, C]) Quench(opts ...QuenchOption) *Machine[S, E, C]
- func (b *Builder[S, E, C]) Region(name string) *Builder[S, E, C]
- func (b *Builder[S, E, C]) Requires(req Requirement[C]) *Builder[S, E, C]
- func (b *Builder[S, E, C]) State(name S) *Builder[S, E, C]
- func (b *Builder[S, E, C]) SubState(name S) *Builder[S, E, C]
- func (b *Builder[S, E, C]) SuperState(name S) *Builder[S, E, C]
- func (b *Builder[S, E, C]) Temper(opts ...TemperOption) []Diagnostic
- func (b *Builder[S, E, C]) Transition(from S) *Builder[S, E, C]
- func (b *Builder[S, E, C]) Use(mw ...Middleware[S, E, C]) *Builder[S, E, C]
- func (b *Builder[S, E, C]) WaitMode(m WaitMode) *Builder[S, E, C]
- func (b *Builder[S, E, C]) When(guardName string, params ...map[string]any) *Builder[S, E, C]
- type CastOption
- type Diagnostic
- type Effect
- type ErrActionFailed
- type ErrGuardFailed
- type ErrGuardPanic
- type ErrInvalidTransition
- type ErrNoInitialState
- type ErrNoPath
- type ErrPolicyDenied
- type ErrUnboundRef
- type ErrUndeclaredState
- type FireFunc
- type FireOption
- type FireResult
- type ForgeOption
- type GuardCtx
- type GuardFn
- type HistoryType
- type IR
- type Instance
- func (i *Instance[S, E, C]) Configuration() []S
- func (i *Instance[S, E, C]) Current() S
- func (i *Instance[S, E, C]) Entity() C
- func (i *Instance[S, E, C]) Fire(ctx context.Context, event E, opts ...FireOption) FireResult[S]
- func (i *Instance[S, E, C]) FireSeq(ctx context.Context, events []E, opts ...FireOption) BatchResult[S]
- func (i *Instance[S, E, C]) History() []Trace
- type LoadOption
- type Machine
- func (m *Machine[S, E, C]) Assay(s S, entity C, opts ...AssayOption) error
- func (m *Machine[S, E, C]) Cast(entity C, opts ...CastOption[S]) *Instance[S, E, C]
- func (m *Machine[S, E, C]) Name() string
- func (m *Machine[S, E, C]) PlanPath(from, to S, entity C, opts ...PlanOption) ([]E, error)
- func (m *Machine[S, E, C]) Requirements(s S) []Requirement[C]
- func (m *Machine[S, E, C]) ToDOT(opts ...VizOption) string
- func (m *Machine[S, E, C]) ToJSON(opts ...ToJSONOption) ([]byte, error)
- func (m *Machine[S, E, C]) ToMermaid(opts ...VizOption) string
- type Middleware
- type MultiRegionErr
- type Outcome
- type P
- type PlanOption
- type ProvideOption
- type QuenchOption
- type Ref
- type Region
- type Registry
- type Requirement
- type RequirementFailure
- type State
- type TemperOption
- type ToJSONOption
- type Trace
- type Transition
- type VizOption
- type WaitMode
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
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]) CurrentStateFn ¶
CurrentStateFn declares how to derive an instance's current state.
func (*Builder[S, E, C]) Do ¶
Do attaches a named action ref with params to the most-recent transition.
func (*Builder[S, E, C]) EndSuperState ¶
EndSuperState closes the most-recent SuperState block.
func (*Builder[S, E, C]) Initial ¶
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 ¶
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 ¶
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 ¶
OnEntry attaches a named entry-action ref to the most-recent state.
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 ¶
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 ¶
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 ¶
SubState declares a substate of the current SuperState or Region block.
func (*Builder[S, E, C]) SuperState ¶
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 ¶
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.
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 ¶
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 ¶
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 ¶
ErrGuardFailed is returned when a named guard returned false.
func (*ErrGuardFailed) Error ¶
func (e *ErrGuardFailed) Error() string
type ErrGuardPanic ¶
ErrGuardPanic is returned when a guard panicked and was recovered.
func (*ErrGuardPanic) Error ¶
func (e *ErrGuardPanic) Error() string
type ErrInvalidTransition ¶
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 ErrPolicyDenied ¶
ErrPolicyDenied is returned when a policy returned Deny.
func (*ErrPolicyDenied) Error ¶
func (e *ErrPolicyDenied) Error() string
type ErrUnboundRef ¶
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 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
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]) 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 ¶
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 ¶
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 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 ¶
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 ¶
NewRegistry returns an empty host registry.
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 ¶
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 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).