Stateful Flows & Statecharts
A stateful API test may need a create request to affect a later read or action. Gostly separates the recorded response library, which replays saved exchanges, from a resource store that holds identified resource bodies and a statechart engine that applies configured lifecycle rules. This guide explains their setup, serving order and limits. To decide which transitions and reset conditions your test needs, start with the order lifecycle exercise.
Worked exercise
Test an order lifecycleCreate/read/cancel assertions, response origin, rejection, reset and isolation checks.
The problem: POST then GET-by-id
A saved create response does not by itself create mutable API state. A later read of a new id can miss the recorded library; a canned GET can also keep returning an old value after an action. For example, a fixture library with no matching read might produce:
POST /charges → 201 { "id": "ch_9fA2", "status": "created", ... }
GET /charges/ch_9fA2 → 404 ← the recording never saw ch_9fA2The resource store can link a captured resource to later reads. A bound statechart supplies the allowed actions and state changes — such as capture, refund, ship or cancel. These are configured test rules, not inferred business logic or a reconstruction of the upstream database. A fixed or empty response remains sufficient when the test does not need a relationship between requests.
Where it sits in the match cascade
In MOCK mode, the linked-resource and statechart paths follow session replay and exact recorded matches, and precede structural matching and the AI response cache:
Session replay
For requests outside a named episode, an active session can serve its in-memory captured exchange before the recorded library. This live session state ends on restart.
Exact match
Method + URI + request-body hash matches a recorded entry.
Resource store
A supported GET-by-id can return the stored resource body as a 200, with X-Ghost-Resource: true.
Statechart transition
A supported POST or PATCH action can advance a bound machine and return the resource with X-Ghost-Transition: <new-state>.
Smart swap
URI path parameters normalised to templates (/users/{id}) and matched structurally.
AI response cache
After structural matching, an enabled cache can serve a previously generated response. Optional background generation is separate from this serving order; see the match cascade linked below.
Recorded matches can shadow state
The resource store — linking create to read
During LEARN, the proxy attempts resource capture from successful JSON POST/PUT responses on recognized collection-shaped routes. The response needs an extractable id. The store keys the body by service, collection and id; named episodes add their own namespace. When the resource path answers a later GET /collection/{id}, it returns the stored body as a 200. Route recognition is heuristic, so this does not make arbitrary REST endpoints into a database.
Id extraction tries an explicit field hint first, then id, _id, and {singular}_id (e.g. charge_id for a charges collection). It recurses into nested objects a few levels deep, so Stripe-style envelopes like data.attributes.id resolve. A string id is used as-is; a numeric id is stringified for autoincrement APIs.
POST /charges → 201 { "id": "ch_9fA2", "status": "created", "amount": 4200 }
GET /charges/ch_9fA2 → 200 { "id": "ch_9fA2", "status": "created", "amount": 4200 }
X-Ghost-Resource: trueOrdinary resources are held in agent memory with best-effort JSONL persistence on the data volume. Named episode resources are ephemeral and are not written to those ordinary resource files. A proxy restart ends live episodes and snapshots; written journals and artifacts can remain. The captured status is metadata: a resource GET returns 200 even when the original create returned 201. Restart, scenario reset and deletion are different operations; none should be treated as a general reset of the application or its database.
An ordinary replayed POST does not automatically create a mutable resource. For a create in MOCK, use the documented episode-create contract: it requires an explicit opt-in, supported identity fields and a paired same-service GET fixture, and returns a newly issued id. Read and act on that returned id rather than the template fixture id.
Read API — operator visibility
GET /v1/resources/{service_id} and GET /v1/resources/{service_id}/{collection}/{resource_id}; the dashboard shows it on the per-service detail page. Admin DELETE on the single-resource path tombstones that mirror row. It does not delete agent memory or JSONL, implement a business API DELETE, reset a scenario, or guarantee a subsequent application GET returns 404.The statechart engine
A captured resource can be bound to a statechart: a state machine modelling a resource lifecycle. A chart can be flat, or use nested states, parallel regions, history and guards (see Nested states, regions, history and guards below). At capture time, a matching collection name can bind the resource to a loaded machine — for example, charges to charge — beginning at the chart's initial state. Unmodified bundled machines require Bundled lifecycles to be on; authored charts can bind independently of that toggle. A saved definition or imported response alone does not establish a resource binding. Supported state-changing request forms are:
POST /collection/{id}/{action} — the action is the last path segment, e.g. POST /charges/ch_9fA2/capture.
PATCH /collection/{id} with a JSON body { "action": "capture" } — the action is read from the body.
When this path handles a valid action, it advances the bound chart and returns 200 with X-Ghost-Transition: <new-state>. Simple status projection rewrites the configured existing top-level string field (default status; a chart can use stage or phase). It does not implement generic PATCH merging or the real service's payment, inventory or other side effects.
By default, an action unavailable in the current state leaves it unchanged and falls through to later serving behavior. A chart can set "on_unhandled": "reject": a declared chart action unavailable from the current state then returns 409 with error: invalid_transition, the current state and event, and X-Gostly-Statechart-Refusal: invalid_transition. An action name the chart never declares still falls through. A repeated cancel needs this explicit rejection policy if the test expects 409.
# charge starts in "created"
POST /charges/ch_9fA2/capture → 200 { ..., "status": "captured" }
X-Ghost-Transition: captured
POST /charges/ch_9fA2/refund → 200 { ..., "status": "refunded" }
X-Ghost-Transition: refunded
# refund is only valid from "captured" — from "created" it no-ops
PATCH /charges/ch_other { "action": "refund" } → falls throughApplying a transition changes the resource state rather than the chart definition. Nested states, regions, history and guards apply only to charts that declare them. Read the resource after an action and check its provenance; a successful action response alone does not establish the read-after-write relationship.
Bundled fixtures
Five bundled lifecycle fixtures provide starting models for billing and commerce. They are off by default. Enable the Bundled lifecycles workspace setting before capturing matching resources, then confirm their bindings. This setting is separate from chart-definition management permissions. Existing captures do not acquire a binding merely because the toggle changes. Authored charts can bind separately from the bundled toggle. These fixture actions change modeled state; a delete or cancel event is not generic database deletion:
chargecreated → capture → captured → refund → refunded; created → void → voided.
customeractive ⇄ suspend / reactivate ⇄ suspended; either → delete → deleted.
invoicedraft → finalize → open → pay → paid → refund → refunded; void / uncollectible branches.
orderpending → pay → paid → ship → shipped → deliver → delivered; cancel / refund / return branches.
subscriptiontrialing → activate → active ⇄ pause / resume ⇄ paused; any active phase → cancel → cancelled.
A machine is a JSON document: an id, an initial state, an optional status_field, and a states map where each state lists its outgoing action → target transitions. The charge fixture:
{
"id": "charge",
"initial": "created",
"status_field": "status",
"states": {
"created": { "transitions": { "capture": "captured", "void": "voided" } },
"captured": { "transitions": { "refund": "refunded" } },
"refunded": { "transitions": {} },
"voided": { "transitions": {} }
}
}Nested states, regions, history and guards
A chart that declares "format": 2 keeps the field names above and adds structure. The proxy validates every such chart before it loads it, and refuses a chart it cannot run instead of loading part of it.
- Nested states. A state can contain its own
statesandinitial. An event goes to the innermost active state first and moves up to the nearest parent that handles it, so onecancelon a parent covers every child. A state with"type": "final"has no transitions of its own; a final state at the top level ends the resource's lifecycle. - Parallel regions. Every child of a
"type": "parallel"state is a region. All regions are active at once on one resource and move independently. The status field carries one region's state; other regions can be written to fields of their own. - History. A
"type": "history"state, shallow or deep, re-enters its parent where the resource last left it. - Guards and actions. A transition can be an object with a
guard, or an ordered list of them; the first alternative whose guard passes is taken. A guard is a declarative condition, not script. It compares values from the request body (event), the stored resource (resource), chart variables (ctx) or the current time, and can test which state is active. A guard never fails with an error: a comparison that reads a missing field is false,lt/le/gt/gebetween a number and a string is false, andeq/netreat a number and a string as different values. Actions can update chart variables, change a field of the stored body, or raise an internal event. - Timers. A state can leave on its own after a delay (
after, in milliseconds).
The request body is the event payload for both request shapes above. A body that is empty or not JSON, such as a form-encoded one, gives guards no payload. If no alternative's guard passes, the action is treated like one that isn't valid in the current state.
This illustrative charge chart allows a refund only up to the captured amount. The trace below assumes bound resources, no earlier matching fixture and the stated captured amounts:
{
"format": 2,
"id": "charge",
"initial": "created",
"status_field": "status",
"states": {
"created": { "transitions": { "capture": "captured" } },
"captured": { "transitions": { "refund": [
{ "guard": { "le": [ { "event": "/amount" }, { "resource": "/amount" } ] },
"target": "refunded" }
] } },
"refunded": { "type": "final" }
}
}# both charges were captured with "amount": 4200
POST /charges/ch_9fA2/refund { "amount": 1000 } → 200 { ..., "status": "refunded" }
X-Ghost-Transition: refunded
POST /charges/ch_other/refund { "amount": 9000 } → guard is false: falls throughPer-tenant overrides & the editor
Statechart management checks the effective sequences capability on the license. Standard licenses include it from Pro; signed per-key feature values control access. With the appropriate credentials and permissions, use the dashboard graph editor or the /v1/statecharts management API to override a fixture, author a machine, or import/export a chart:
GET /v1/statechartsMerged catalog: bundled fixtures plus this tenant's overrides and custom machines, each tagged bundled / overridden / custom.
GET /v1/statecharts/{id}Full graph for one machine. A tenant override row wins over the bundled fixture.
PATCH /v1/statecharts/{id}Upsert an override for a bundled id, or update an existing custom machine. Submit the full chart definition.
POST /v1/statechartsCreate a new custom machine. 409 if the id collides with a bundled fixture (use PATCH to override that) or an existing custom machine.
DELETE /v1/statecharts/{id}Remove an override (revert to the bundled fixture) or delete a custom machine entirely.
GET /v1/statecharts/{id}/resourcesControl-plane resources bound to this machine, aggregated by state for the dashboard's heat-map overlay.
POST /v1/statecharts/importTranslate an SCXML document or an XState JSON machine into a draft chart and check it with the proxy's validator. Stores nothing; save the draft with POST or PATCH. Parallel regions and history are not translated yet.
GET /v1/statecharts/{id}/export?format=scxmlThe chart as an SCXML document. A chart with parallel regions or history cannot be exported yet.
Management validates and saves the full definition, then materializes the tenant override file under statechart-overrides/<tenant>/<id>.json and attempts a proxy reload. Tenant overrides take precedence over bundled ids. Inspect validation and agent_reloaded results, then verify the intended chart is serving and the resource is bound before running the case. A saved definition can remain when the proxy has not acknowledged the reload.
Editing and serving are separate checks
POST /v1/statecharts or PATCH /v1/statecharts/{id}, starting from the editor's Copy JSON if useful. The interchange translators have separate limits below.Modeling a multi-step flow
To model a lifecycle the bundled fixtures don't cover — say a shipment that moves through ordered → in_transit → delivered and tracks its state in a stage field — author a custom machine. Name the status field your API actually uses. This simple example projects state into an existing top-level string stage field; it declares no actions that alter other fields.
POST /v1/statecharts
X-API-Key: $GHOST_API_KEY
Content-Type: application/json
{
"definition": {
"id": "shipment",
"initial": "ordered",
"status_field": "stage",
"states": {
"ordered": { "transitions": { "ship": "in_transit" } },
"in_transit": { "transitions": { "deliver": "delivered" } },
"delivered": { "transitions": {} }
}
}
}The following is an illustrative expected flow, assuming the chart is loaded before resource capture, the resource is bound, and no earlier exact fixture answers the reads or actions. A LEARN capture can supply the resource; a MOCK create instead needs the episode-create contract. Use the returned id and assert the resource/transition headers:
POST /shipments → 201 { "id": "shp_1", "stage": "ordered" }
POST /shipments/shp_1/ship → 200 { "id": "shp_1", "stage": "in_transit" }
POST /shipments/shp_1/deliver → 200 { "id": "shp_1", "stage": "delivered" }
GET /shipments/shp_1 → 200 { "id": "shp_1", "stage": "delivered" }Import prepares fixtures, not a business database
Observability
When the resource or transition path answers, it emits the corresponding header below. Assert that provenance together with the returned id, state and fields that should remain unchanged. An earlier recorded response can have a successful status without exercising either path:
X-Ghost-Resource: trueA stored resource body was served back on a GET-by-id.
X-Ghost-Transition: <state>A statechart action advanced the resource; the value is the new state.
For a rejection test, assert a declared action that is unavailable from the current state, explicit on_unhandled: "reject", the 409 refusal and a subsequent unchanged resource read. Test a second scenario independently; do not infer isolation from status codes or expect every unknown id to return 404, because later structural matching may answer.
Scope & limits
- Interchange has limits. Native chart JSON and the dashboard editor support nested states, parallel regions and history. Import and export (a subset of SCXML, and XState JSON for import) do not translate parallel regions or history, so retain the native chart definition for those structures. Guards read the request body only when it is JSON.
- State owners and isolation differ. Tenant-scoped chart management, episode-scoped API resources and application/database state are separate boundaries. Use a named scenario and reviewed baseline for repeat tests, check reset completion, and keep the latest returned ids. Reset restores scenario state, not proxy configuration or the application database; ordinary best-effort persistence is not a transaction or concurrency guarantee. See the security model for API tenant enforcement.
- HTTP resource actions. The supported action shapes above model resource lifecycles; they do not supply arbitrary REST CRUD or cross-service transactions. WebSocket frame capture, when explicitly enabled, is for observability and does not replay frames or drive these HTTP transitions.
- Bundled fixtures start off. Enable them deliberately before capture and inspect the binding. Statecharts management uses the effective
sequenceslicense capability. The dashboard and/v1/statechartsAPI support definition editing; import and export are API-only. Changing a definition or serving configuration requires a new reviewed scenario baseline.