Inferensys

Prompt

Workflow State Transition Scenario Prompt

A production-ready prompt playbook for QA engineers and product teams to generate exhaustive Gherkin scenarios covering valid transitions, invalid transitions, guard conditions, side effects, and rollback behavior from state machine definitions.
Wide-angle shot of a modern WeWork open floor plan with creative walls covered in AI system architecture diagrams, product team collaborating in standing desk area with industrial lighting.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the ideal conditions, required inputs, and clear boundaries for using the Workflow State Transition Scenario Prompt.

Use this prompt when you have a defined state machine, status workflow, or entity lifecycle and need executable Gherkin scenarios that verify every transition, guard condition, and side effect. This prompt is designed for QA engineers, SDETs, and product teams who must ensure that no invalid state transition is possible and that every valid transition produces the correct side effects. The prompt assumes you can provide a state diagram, transition table, or structured description of states, events, guards, and actions.

The prompt is not suitable for undefined workflows, purely sequential processes without branching, or systems where state is not explicitly modeled. If your workflow lacks clear state definitions, guard conditions, or side-effect descriptions, the model will hallucinate transitions or produce non-verifiable scenarios. Before using this prompt, confirm that you have a source of truth—such as a state diagram, a transition matrix, or a structured specification—that enumerates allowed and disallowed transitions. The prompt works best when you can supply concrete artifacts like a list of states, the events that trigger transitions, the conditions that must be true for a transition to fire, and the actions the system performs as a result.

For high-risk domains such as payments, healthcare, or access control, always pair the generated scenarios with human review and a coverage checklist. The model may miss implicit transitions, concurrency edge cases, or rollback paths that are not explicitly documented in your input. After generating scenarios, validate that every state has defined entry and exit criteria, every guard condition is tested, and every invalid transition is explicitly prohibited. If your state machine includes timer-based transitions, asynchronous callbacks, or compensating actions, supplement this prompt with the Race Condition Scenario Generation Prompt or the Retry and Recovery Scenario Generation Prompt to achieve full coverage.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Workflow State Transition Scenario Prompt delivers value and where it falls short. Use these cards to decide if this prompt fits your current testing context.

01

Strong Fit: Stateful Feature Testing

Use when: your system under test has explicit states, status fields, or lifecycle phases with documented transitions. The prompt excels at generating exhaustive transition coverage from a state machine definition. Avoid when: the workflow is purely linear with no branching or state re-entry.

02

Weak Fit: Stateless CRUD Operations

Risk: applying this prompt to simple create-read-update-delete operations produces over-specified scenarios with artificial state machines. Guardrail: use the API Behavior Contract Extraction prompt instead for stateless endpoints. Reserve this prompt for entities with lifecycle semantics.

03

Required Input: State Machine Definition

What to watch: the prompt needs an explicit state machine diagram, table, or description listing valid states, transitions, guard conditions, and side effects. Without this, the model invents plausible but incorrect transitions. Guardrail: provide a structured state-transition matrix as [INPUT] before generating scenarios.

04

Operational Risk: Undocumented Implicit States

Risk: production systems often have implicit intermediate states (e.g., 'processing', 'pending_retry') not captured in documentation. Generated scenarios will miss these, creating coverage gaps. Guardrail: pair this prompt with log analysis or code inspection to surface hidden states before scenario generation.

05

Strong Fit: Compliance Audit Preparation

Use when: you need to demonstrate to auditors that every state transition has defined entry criteria, exit criteria, and guard conditions. The prompt produces traceable Gherkin scenarios that map directly to regulatory requirements. Avoid when: the audit requires only happy-path coverage.

06

Weak Fit: Real-Time or Event-Driven Systems

Risk: event-sourced or streaming systems where state is derived from event sequences rather than stored as a discrete field may not map cleanly to the prompt's state-machine model. Guardrail: for event-driven architectures, use the Race Condition Scenario Generation Prompt instead, and treat state as a projection for validation assertions.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt for generating Gherkin scenarios that validate state machine and lifecycle transition behavior.

This prompt template is designed to be pasted directly into your AI harness. It instructs the model to act as a QA architect specializing in stateful system behavior. The model will analyze a provided state machine specification and produce a comprehensive set of Gherkin scenarios. The core value is in systematically covering not just the 'happy path' transitions, but also invalid transitions, guard conditions, and side effects that are often missed in manual test design.

text
You are a QA architect specializing in stateful system behavior. Your task is to generate a comprehensive set of Gherkin scenarios from a state machine specification.

# SPECIFICATION
[STATE_MACHINE_SPECIFICATION]

# OUTPUT SCHEMA
Produce a single JSON object with a "scenarios" array. Each object must have:
- "scenario_name": (string) A clear, descriptive title.
- "feature": (string) The feature or component under test.
- "scenario_type": (string) One of: "happy_path", "invalid_transition", "guard_condition", "side_effect", "rollback".
- "gherkin_text": (string) The complete Gherkin scenario, including tags like @happy-path or @invalid.
- "covered_states": (array of strings) The states involved in this scenario.
- "risk_notes": (string) A brief note on what could be missed if this scenario is not tested.

# CONSTRAINTS
- Ensure every state defined in the specification has at least one scenario covering its entry and exit criteria.
- For every valid transition, generate at least one happy-path scenario.
- For every valid transition, generate at least one invalid-transition scenario that attempts it from a wrong state.
- Explicitly test all guard conditions (e.g., `[is_paid]`, `[has_permission]`).
- Include scenarios for side effects like audit logs, emails, or external API calls.
- If the specification implies a rollback or cancellation path, generate a rollback scenario.
- Use clear, descriptive `Given`, `When`, `Then` steps. Use `Examples` tables for data-driven guard conditions.

# RISK LEVEL
[HIGH_RISK_WORKFLOW]

To adapt this prompt, replace the [STATE_MACHINE_SPECIFICATION] placeholder with your actual state machine definition. This can be a mermaid.js diagram, a structured table of states and transitions, or a detailed textual description. The [HIGH_RISK_WORKFLOW] placeholder should be replaced with a boolean (true or false). When set to true, the model will add an extra layer of caution, explicitly flagging scenarios that require human review before automation, such as those involving financial transactions or irreversible data mutations. After generation, validate the output JSON against the defined schema and review the risk_notes for each scenario to prioritize your testing efforts.

IMPLEMENTATION TABLE

Prompt Variables

Each placeholder must be populated for reliable output. Validation notes describe what the model needs to interpret the input correctly.

PlaceholderPurposeExampleValidation Notes

[STATE_MACHINE_DEFINITION]

Defines the full set of states, valid transitions, and guard conditions for the workflow

Order lifecycle: PENDING -> CONFIRMED -> SHIPPED -> DELIVERED. Guard: SHIPPED requires tracking_number

Must be parseable as a directed graph. Check that every state has at least one entry and one exit transition, or is explicitly marked as terminal/initial

[TRANSITION_TRIGGERS]

Specifies the events, API calls, or conditions that initiate each state change

CONFIRMED triggered by payment_success webhook; SHIPPED triggered by POST /orders/{id}/ship

Each trigger must map to exactly one source state. Validate that no trigger is orphaned or maps to multiple source states without explicit context

[SIDE_EFFECTS_CATALOG]

Lists the expected side effects for each transition, such as notifications, audit logs, or external API calls

SHIPPED transition fires email_service.send_tracking, audit_service.log, inventory_service.decrement

Each side effect must include the target system and payload. Check for missing rollback side effects on compensating transitions

[GUARD_CONDITIONS]

Defines the boolean conditions that must be true for a transition to be allowed

SHIPPED guard: order.payment_status == 'PAID' AND order.tracking_number IS NOT NULL

Each guard must reference fields present in the state context. Validate that guard expressions are evaluable and do not reference undefined attributes

[INVALID_TRANSITION_LIST]

Explicitly lists transitions that must be rejected, even if they appear structurally possible

DELIVERED -> CANCELLED is forbidden; PENDING -> DELIVERED is forbidden without intermediate states

Each invalid transition must have a documented reason. Check that the list covers all skip-level transitions and reverse transitions that violate business rules

[ROLLBACK_BEHAVIOR]

Describes what happens when a transition fails mid-execution after side effects have started

If inventory_service.decrement fails during SHIPPED, rollback tracking_number assignment and return order to CONFIRMED

Each rollback rule must specify the target state and which side effects are reversed. Validate that compensating actions are idempotent where possible

[STATE_CONTEXT_SCHEMA]

Defines the data fields available in each state, including required, optional, and computed attributes

CONFIRMED state context: {payment_id: string, amount: decimal, payment_method: string, confirmed_at: timestamp}

Schema must be valid JSON Schema or equivalent. Check that fields required by guard conditions exist in the state context for the relevant transition

[TIMEOUT_AND_ESCALATION_RULES]

Specifies time-based constraints on state residency and escalation paths for stuck states

PENDING state times out after 30 minutes, escalates to EXPIRED; SHIPPED state times out after 14 days, escalates to DELIVERED

Each timeout rule must include the source state, duration, and target state. Validate that timeout targets are valid states in the machine definition

PROMPT PLAYBOOK

Implementation Harness Notes

Wire this prompt into your test generation pipeline with validation, retry logic, and audit logging.

This prompt is designed to be called programmatically from a test management system or CI pipeline, not as a one-off chat interaction. The core integration contract is simple: your system provides a state machine definition as a structured object, and the prompt returns a set of Gherkin scenarios. To make this reliable in production, you must treat the prompt as a deterministic function with well-defined inputs, outputs, and error modes. Store the state machine definition as a versioned JSON or YAML file in your test repository and inject it into the [STATE_MACHINE_DEFINITION] placeholder at generation time. The definition must include states, transitions, guard conditions, side effects, and entry/exit criteria for every state. If your state machine is defined in a visual tool or a different format, preprocess it into the expected schema before calling the prompt.

Validation and retry logic are the most critical parts of the harness. Before committing generated scenarios to your feature files, validate the output against a Gherkin parser such as gherkin-lint or the @cucumber/gherkin library. The parser should confirm that every scenario is syntactically valid and that all referenced states and transitions exist in the input state machine definition. If the model produces scenarios that reference undefined states or transitions, do not silently discard them. Instead, append the validation error to the next request as a [PREVIOUS_VALIDATION_ERRORS] field and ask the model to correct only the failing scenarios. Limit retries to a maximum of three attempts; if validation still fails after three corrections, log the failure, flag the run for human review, and fall back to the last known good scenario set. For high-risk domains such as payments, access control, or healthcare workflows, require human approval on the first generation of any new state machine. Subsequent regenerations for the same machine can be gated on a diff review only, comparing the new scenario set against the previously approved version.

Logging and auditability turn this prompt from a black box into an observable system component. Log every generation run with at minimum: the prompt version (a SHA or semantic version stored alongside the template), the input state machine hash (SHA-256 of the normalized definition), the output scenario count, the validation pass/fail status, the retry count, and the model version used. Store these logs in your test management system or CI artifacts so you can trace any scenario back to its generation context. If you use multiple models for cost or latency reasons, note that smaller models may struggle with complex guard condition logic; route state machines with more than 15 transitions or nested conditionals to a more capable model. Finally, never let generated scenarios bypass your existing code review process. The prompt accelerates scenario authoring, but the output is a candidate artifact that must earn its place in your test suite through the same review gates as human-written specifications.

IMPLEMENTATION TABLE

Expected Output Contract

Validate the model's output against this contract before accepting it into the test management system. Each field must pass the specified validation rule.

Field or ElementType or FormatRequiredValidation Rule

scenario_id

string

Matches pattern: [STATE_TRANSITION]-[SEQ_NUM] e.g., ORDER-001

feature_title

string

Non-empty string; must contain the name of the state machine under test

scenario_type

enum: valid_transition | invalid_transition | guard_condition | side_effect | rollback

Must be one of the five allowed enum values

gherkin_scenario

multiline string

Must parse as valid Gherkin with Given, When, Then steps; no missing keywords

source_state

string

Must match a state defined in the provided [STATE_MACHINE_DEFINITION]

target_state

string or null

Must match a state in [STATE_MACHINE_DEFINITION]; null only allowed for invalid_transition scenarios

guard_conditions

array of strings

If present, each string must reference a condition defined in [GUARD_RULES]; empty array allowed

expected_side_effects

array of objects with {type, description, verification_query}

If present, each object must have all three keys; type must be from [SIDE_EFFECT_TYPES]

rollback_target_state

string or null

Required when scenario_type is rollback; must match a state in [STATE_MACHINE_DEFINITION]; null otherwise

traceability_tag

string

Must reference a requirement ID from [REQUIREMENT_IDS]; format: @REQ-[ID]

PRACTICAL GUARDRAILS

Common Failure Modes

State transition prompts fail in predictable ways when the model hallucinates transitions, ignores guard conditions, or loses track of state. Here are the most common production failure modes and how to guard against them.

01

Hallucinated Transitions

What to watch: The model invents a transition that doesn't exist in the state machine spec, such as jumping from DRAFT directly to ARCHIVED without passing through REVIEWED. This is the most common failure mode when the state machine is described in prose rather than enumerated explicitly. Guardrail: Include the full transition matrix as a structured table in the prompt. Validate every generated scenario against the allowed transition list before accepting the output.

02

Missing Guard Conditions

What to watch: The model generates a valid transition but omits the guard condition that gates it, such as allowing APPROVED without checking that all required sign-offs exist. The scenario looks correct but won't catch real bugs. Guardrail: Require guard conditions as explicit AND clauses in the WHEN step. Add a post-generation check that every guarded transition in the spec has at least one scenario testing the guard-failure case.

03

Silent State Drift in Multi-Step Scenarios

What to watch: In scenarios with multiple transitions, the model loses track of the current state mid-scenario and generates steps that assume an earlier or later state than what the previous step actually produced. This creates scenarios that can't be executed sequentially. Guardrail: Require each THEN step to explicitly restate the new current state. Use a validator that traces state changes step-by-step and flags any step that references a state not produced by the prior transition.

04

Side Effect Omission

What to watch: The model generates the state change but ignores required side effects such as audit log entries, notification triggers, timestamp updates, or downstream system calls. The scenario passes but the implementation is incomplete. Guardrail: Include a side-effect checklist in the prompt template. Require each transition scenario to include a THEN clause for every documented side effect. Add an eval that cross-references generated scenarios against the side-effect specification.

05

Invalid Transition Not Tested

What to watch: The model generates only happy-path valid transitions and skips the invalid transition cases entirely. The resulting test suite has zero coverage for transition rejection logic, which is where most production bugs live. Guardrail: Explicitly require at least one negative scenario per state that attempts an invalid transition and expects rejection. Use a coverage checker that verifies every state has both valid-exit and invalid-exit-attempt scenarios.

06

Terminal State Re-Entry

What to watch: The model generates a scenario where a terminal state like CLOSED, DELETED, or EXPIRED transitions to another state. Terminal states by definition have no valid exits, but the model may treat them like any other state. Guardrail: Mark terminal states explicitly in the prompt with a TERMINAL: true flag. Add a validation rule that rejects any scenario where a terminal state appears in a GIVEN clause followed by a WHEN transition attempt that isn't explicitly testing terminal-state immutability.

IMPLEMENTATION TABLE

Evaluation Rubric

Score each output against these criteria before accepting it into your test suite. Run this rubric on every generation and set a minimum pass threshold of 85%.

CriterionPass StandardFailure SignalTest Method

State Coverage

Every state from [STATE_MACHINE_DEFINITION] appears in at least one scenario

Missing states in generated scenarios; state count mismatch

Parse all Given/Then state references; diff against input state list

Valid Transition Accuracy

All transitions defined in [VALID_TRANSITIONS] are represented with correct preconditions

Generated scenario uses wrong precondition or invents transition not in source

Extract transition tuples from scenarios; compare to input transition table

Invalid Transition Blocking

Every invalid transition from [INVALID_TRANSITIONS] has a corresponding negative scenario with expected rejection

No scenario for a documented invalid transition; scenario expects success instead of rejection

Map each invalid transition to at least one scenario with Then step asserting error or rejection

Guard Condition Enforcement

Each guard condition from [GUARD_CONDITIONS] appears in at least one scenario with both satisfied and unsatisfied variants

Guard condition never tested; only happy-path guard satisfaction covered

Search scenario steps for guard condition names; verify both Given guard-is-met and Given guard-is-not-met variants exist

Side Effect Verification

Every side effect listed in [SIDE_EFFECTS] is asserted in the Then steps of the transition that triggers it

Side effect mentioned in source but no Then step checks for it in generated output

Extract side effect list from input; grep Then steps for matching assertions

Rollback Behavior

Any transition marked with rollback in [ROLLBACK_TRANSITIONS] has a scenario covering failure-during-transition and state reversion

Rollback transition present but no failure-injection scenario or no Then step asserting original state

Identify rollback-flagged transitions; verify existence of Given failure-occurs-during variant with Then state-is-original-state

Gherkin Syntax Validity

All scenarios parse without syntax errors; keywords Given, When, Then, And, But used correctly

Parser rejects scenario; missing When step; Then before When

Run Gherkin parser on output; flag parse errors

Traceability Completeness

Every scenario includes a tag or comment referencing the source requirement, state, or transition ID from [SOURCE_IDS]

Untagged scenario with no traceability to input specification

Check each scenario for @tag or #comment containing a source ID from input

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single state machine diagram or text description. Skip strict schema enforcement and focus on generating the core Gherkin scenarios. Accept plain-text output and review manually.

Watch for

  • Missing guard conditions on transitions
  • States without defined entry or exit criteria
  • Overly broad [CONSTRAINTS] that produce generic scenarios
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.