Search by

adachsoft / workflow

Arkadiusz Adach

Lightweight, extensible PHP workflow engine with plugin-based steps, context isolation, debugging and nested workflow support

Package info

gitlab.com/a.adach/Workflow

Issues

pkg:composer/adachsoft/workflow

Statistics

Installs: 175

Dependents: 6

Suggesters: 0

Stars: 0

v7.5.0 2026-11-23 19:40 UTC

README

Simple, plugin-based workflow engine for PHP with branch-first step contracts, context-based data flow, and built-in payload schema validation.

Requirements

  • PHP 8.2+
  • adachsoft/collection ^3.0

Installation

composer require adachsoft/workflow

Overview

The library provides a single WorkflowRunnerInterface for creating, executing, and controlling workflow runs. It is built around three central contracts:

  • WorkflowDefinitionRepositoryInterface
  • WorkflowRunRepositoryInterface
  • StepRegistryInterface

Select normal or debug execution with WorkflowRunModeEnum in a StartRunRequestDto. WorkflowRunnerBuilder supplies in-memory defaults and supports caller-provided repositories and a step registry.

Static data-flow validation (without executing steps) is available through:

  • WorkflowFlowValidatorInterface
  • WorkflowFlowValidatorBuilder

Main Concepts

Step (branch-first)

A workflow step implements StepInterface and exposes metadata through #[StepType]:

  • inputSchema - expected step input
  • configSchema - expected step config
  • branches - declared execution branches and output schemas

A step returns StepResultDto::branch('<branch_name>', $output).

The engine resolves the next workflow step from current step config[<branch_name>] (after config_map resolution) for non-terminal branches.

Workflow definition

A workflow definition is represented by WorkflowDefinitionVo and stores:

  • named workflow steps as PayloadVo entries
  • an explicit workflow-level input_schema
  • an optional workflow-level output_schema that validates the final output of every terminal branch

The first defined key is treated as the entry step.

Workflow run

A workflow run is represented by AdachSoft\Workflow\Run\WorkflowRunVo and stores:

  • current step, output, and per-run context (WorkflowRunContextVo)
  • lifecycle status and execution mode, start/update timestamps, optional error, and suspension details
  • an optional parentRunId for nested runs

The original run input is placed in the context; there is no separate run input field.

Payload

PayloadVo is an immutable value object used for step input, step config, and step output.

Data flow between steps

A step returns only its own output. The engine never forwards that output as the next step input.

The only carrier of data between steps is run context, declared in the workflow definition:

  • start() writes the workflow payload into run context (not into the first step input)
  • output_map copies selected step output fields into context
  • input_map builds the next step input from context (and literals)
  • config_map can overlay step config from context, including branch targets

Every step that needs data — including the first step — must declare input_map.

Example definition with input_schema, input_map, and output_map:

use AdachSoft\Workflow\Engine\PayloadVo;
use AdachSoft\Workflow\Engine\WorkflowDefinitionVo;
use AdachSoft\Workflow\Enum\SchemaPhaseEnum;
use AdachSoft\Workflow\Schema\PayloadSchemaVo;

$definitionRepository->save(new WorkflowDefinitionVo('example', [
    'append' => new PayloadVo([
        'type' => 'append_message',
        'config' => new PayloadVo([
            'message' => 'processed',
            'on_next' => 'finish',
        ]),
        'input_map' => new PayloadVo([
            'messages' => '$context.messages',
        ]),
        'output_map' => new PayloadVo([
            'messages' => '$context.messages',
        ]),
    ]),
    'finish' => new PayloadVo([
        'type' => 'finish',
        'config' => PayloadVo::empty(),
        'input_map' => new PayloadVo([
            'messages' => '$context.messages',
        ]),
    ]),
], PayloadSchemaVo::fromArray([
    'messages' => [
        'type' => 'array',
        'required' => true,
        'description' => 'Initial messages',
    ],
], SchemaPhaseEnum::Input)));

Schema Validation

The workflow runner validates payloads in these phases:

  • Workflow input (StartRunRequestDto::input vs workflow input_schema) - strict mode (unknown keys are rejected)
  • Step input (before execution) - permissive mode (extra keys allowed)
  • Step config (before execution) - strict mode
  • Step output (after execution, per selected branch) - strict mode
  • Workflow output (after a terminal step) - strict mode when output_schema is declared

Validation errors raise SchemaValidationException.

Branch contract violations can raise:

  • UnknownBranchException
  • BranchTargetMissingException

Workflow output schema

WorkflowDefinitionVo accepts an optional outputSchema using the SchemaPhaseEnum::Output phase. When it is null, the workflow has no workflow-level output contract. An explicit empty output schema is different: it permits no output fields. At runtime, each terminal step result is validated strictly against this schema before the run becomes SUCCEEDED.

The static flow validator also checks that every reachable terminal branch declares the required workflow output fields with compatible types, requiredness, and nullability, and declares no extra fields.

Nested input_map references

input_map resolves $context.* references recursively inside nested objects and arrays, so it can build a structured payload for a sub-workflow:

{
  "input_map": {
    "payload": {
      "prompt": "$context.prompt",
      "models_config_file": "$context.models_config_file",
      "count": "$context.count"
    }
  }
}

Nested payload values keep their object or array representation while their references are resolved. A nested PayloadVo remains a PayloadVo. Missing or null references are omitted from objects and removed from lists (with list indexes re-numbered); nested empty objects remain present. Literal values are unchanged, associative-array keys are preserved, and this recursive behavior applies only to input_map, not config_map or output_map.

Config value resolvers

Applications can resolve string references in the top-level step configuration by implementing ConfigValueResolverInterface and passing the adapter to WorkflowRunnerBuilder. For example, a step configuration can contain "api_key": "env('NAME')". The workflow runner does not interpret the reference syntax or value source. Without an adapter, the default resolver leaves values unchanged. Resolution happens after config_map; nested configuration values are not resolved.

use AdachSoft\Workflow\Builder\WorkflowRunnerBuilder;
use AdachSoft\Workflow\Contracts\ConfigValueResolverInterface;
use AdachSoft\Workflow\Exception\ConfigValueResolutionException;

final readonly class EnvironmentConfigValueResolver implements ConfigValueResolverInterface
{
    public function resolve(string $value): string
    {
        if (preg_match("/^env\\('([^']+)'\\)$/", $value, $matches) !== 1) {
            return $value;
        }

        $resolved = getenv($matches[1]);
        if ($resolved === false) {
            throw new ConfigValueResolutionException('Environment variable is unavailable');
        }

        return $resolved;
    }
}

$workflowRunner = WorkflowRunnerBuilder::create()
    ->withConfigValueResolver(new EnvironmentConfigValueResolver())
    ->build();

Adapters must not include resolved values in exception messages.

Secret references

Workflow input and step outputs can contain named secret references using the syntax ${secret:NAME}, where NAME matches [A-Z][A-Z0-9_]*. References may occupy a whole string or appear inside a larger string, and a string may contain multiple references.

Implement SecretResolverInterface::resolve(string $name): string and configure it with WorkflowRunnerBuilder::withSecretResolver():

$workflowRunner = WorkflowRunnerBuilder::create()
    ->withSecretResolver($secretResolver)
    ->build();

With a resolver configured, references in mapped step input are resolved in memory immediately before the step executes. Resolved values are masked back to their references before run context, run output, errors, last-step execution data, suspension or resume payloads, step logs, and nested-run input are persisted or emitted. A secret value must contain at least eight bytes; shorter values are rejected with SecretResolutionException to avoid masking collisions. Resolution errors identify the secret name and must not include a secret value.

Without a configured secret resolver, references remain unchanged, preserving the existing behavior. The secret vault does not resolve step configuration values: configuration continues to use ConfigValueResolverInterface and its configured application adapter.

Static flow validation

WorkflowFlowValidatorBuilder analyzes a workflow graph without executing steps. It reports missing required inputs, unknown $context. references, unreachable steps, unknown step types, terminal branch outputs that do not match the workflow output_schema, and related contract issues.

use AdachSoft\Workflow\Validation\WorkflowFlowValidatorBuilder;

$flowValidator = WorkflowFlowValidatorBuilder::create()
    ->withWorkflowDefinitionRepository($definitionRepository)
    ->withStepRegistry($stepRegistry)
    ->build();

$result = $flowValidator->validate('example');

if (!$result->valid) {
    foreach ($result->violations as $violation) {
        // $violation->stepName, $violation->code, $violation->message
    }
}

Basic Usage

use AdachSoft\Workflow\Attribute\StepType;
use AdachSoft\Workflow\Builder\WorkflowRunnerBuilder;
use AdachSoft\Workflow\Run\ExecutionOptionsDto;
use AdachSoft\Workflow\Run\StartRunRequestDto;
use AdachSoft\Workflow\Contracts\StepInterface;
use AdachSoft\Workflow\Engine\PayloadVo;
use AdachSoft\Workflow\Engine\StepContextDto;
use AdachSoft\Workflow\Engine\StepResultDto;
use AdachSoft\Workflow\Engine\WorkflowDefinitionVo;
use AdachSoft\Workflow\Enum\SchemaPhaseEnum;
use AdachSoft\Workflow\Registry\InMemoryStepRegistry;
use AdachSoft\Workflow\Repository\InMemoryWorkflowDefinitionRepository;
use AdachSoft\Workflow\Repository\InMemoryWorkflowRunRepository;
use AdachSoft\Workflow\Schema\PayloadSchemaVo;

#[StepType(
    type: 'append_message',
    description: 'Appends configured message',
    inputSchema: [
        'messages' => ['type' => 'array', 'required' => true, 'description' => 'Current messages'],
    ],
    configSchema: [
        'message' => ['type' => 'string', 'required' => true, 'description' => 'Message to append'],
        'on_next' => ['type' => 'string', 'required' => true, 'description' => 'Next step name'],
    ],
    branches: [
        'on_next' => [
            'description' => 'Continue workflow',
            'terminal' => false,
            'outputSchema' => [
                'messages' => ['type' => 'array', 'required' => true, 'description' => 'Updated messages'],
            ],
        ],
    ],
)]
final class AppendMessageStep implements StepInterface
{
    public function execute(StepContextDto $stepContextDto): StepResultDto
    {
        $messages = $stepContextDto->input->get('messages');
        $message = $stepContextDto->config->get('message');

        if (!is_array($messages) || !is_string($message)) {
            return StepResultDto::branch('on_next', new PayloadVo(['messages' => []]));
        }

        $messages[] = $message;

        return StepResultDto::branch('on_next', new PayloadVo([
            'messages' => $messages,
        ]));
    }
}

#[StepType(
    type: 'finish',
    description: 'Finishes workflow',
    inputSchema: [
        'messages' => ['type' => 'array', 'required' => true, 'description' => 'Final messages'],
    ],
    branches: [
        'end' => [
            'description' => 'Finish run',
            'terminal' => true,
            'outputSchema' => [
                'status' => ['type' => 'string', 'required' => true, 'description' => 'Final status'],
                'messages' => ['type' => 'array', 'required' => true, 'description' => 'Final messages'],
            ],
        ],
    ],
)]
final class FinishStep implements StepInterface
{
    public function execute(StepContextDto $stepContextDto): StepResultDto
    {
        return StepResultDto::branch('end', new PayloadVo([
            'status' => 'done',
            'messages' => $stepContextDto->input->get('messages'),
        ]));
    }
}

$stepRegistry = new InMemoryStepRegistry();
$stepRegistry->register(AppendMessageStep::class);
$stepRegistry->register(FinishStep::class);

$definitionRepository = new InMemoryWorkflowDefinitionRepository();
$runRepository = new InMemoryWorkflowRunRepository();

$workflowRunner = WorkflowRunnerBuilder::create()
    ->withStepRegistry($stepRegistry)
    ->withWorkflowDefinitionRepository($definitionRepository)
    ->withWorkflowRunRepository($runRepository)
    ->build();

$definitionRepository->save(new WorkflowDefinitionVo('example', [
    'append' => new PayloadVo([
        'type' => 'append_message',
        'config' => new PayloadVo([
            'message' => 'processed',
            'on_next' => 'finish',
        ]),
        'input_map' => new PayloadVo([
            'messages' => '$context.messages',
        ]),
        'output_map' => new PayloadVo([
            'messages' => '$context.messages',
        ]),
    ]),
    'finish' => new PayloadVo([
        'type' => 'finish',
        'config' => PayloadVo::empty(),
        'input_map' => new PayloadVo([
            'messages' => '$context.messages',
        ]),
    ]),
], PayloadSchemaVo::fromArray([
    'messages' => ['type' => 'array', 'required' => true, 'description' => 'Initial messages'],
], SchemaPhaseEnum::Input)));

$run = $workflowRunner->start(
    new StartRunRequestDto(
        workflowId: 'example',
        input: new PayloadVo(['messages' => ['created']]),
    ),
    ExecutionOptionsDto::nonInteractive(),
);

Builders

WorkflowRunnerBuilder creates a runner with in-memory defaults or with caller-provided repositories, a step registry, and optional adapters.

use AdachSoft\Workflow\Builder\WorkflowRunnerBuilder;

$workflowRunner = WorkflowRunnerBuilder::create()
    ->withStandardSteps()
    ->build();

Create runners only through the builder. Do not instantiate WorkflowRunner or WorkflowFlowValidator directly.

Built-in Steps

The package currently provides these built-in steps in src/Steps:

  • RunWorkflowStep - runs another workflow, suspends its parent while the child is suspended, and forwards the child's final output when it declares output_schema
  • SleepStep - pauses execution for configured seconds
  • TakeNextListItemStep (take_next_list_item) - removes the first item from a list and returns the remaining items

Iterating over a list

take_next_list_item requires a list in items and configured on_item and on_empty targets. Its on_item branch outputs item and remaining_items; its non-terminal on_empty branch outputs remaining_items as an empty list. Route on_item to a processing step that loops back to take_next_item, and route on_empty to a terminal step.

$steps = [
    'take_next_item' => new PayloadVo([
        'type' => 'take_next_list_item',
        'config' => new PayloadVo([
            'on_item' => 'process_item',
            'on_empty' => 'finish',
        ]),
        'input_map' => new PayloadVo([
            'items' => '$context.queue',
        ]),
        'output_map' => new PayloadVo([
            'item' => '$context.current_item',
            'remaining_items' => '$context.queue',
        ]),
    ]),
    'process_item' => new PayloadVo([
        'type' => 'process_item', // Application-defined step.
        'config' => new PayloadVo([
            'on_next' => 'take_next_item',
        ]),
        'input_map' => new PayloadVo([
            'item' => '$context.current_item',
        ]),
    ]),
    'finish' => new PayloadVo([
        'type' => 'finish', // Application-defined terminal step.
        'config' => PayloadVo::empty(),
    ]),
];

The workflow input schema must declare queue as an array; the step also checks at runtime that items is a list (array_is_list).

Sub-workflow output

RunWorkflowStep starts the child through the same runner. If the child suspends, the parent suspends while awaiting that child and resumes automatically when the child reaches a terminal status. The step returns an empty on_next output when the child has no output_schema. When config.workflow_id selects a child statically and that child declares output_schema, the effective on_next branch schema is derived from the child definition and the child's final output becomes the step output. The parent can then use output_map to pass those fields into its own context.

Selecting the child dynamically through config_map remains supported for children without output_schema. A dynamically selected child that declares output_schema is not supported in this release and fails strict branch-output validation with SchemaValidationException.

Builders can register built-in steps for you:

$workflowRunner = WorkflowRunnerBuilder::create()
    ->withStandardSteps()
    ->build();

Run modes and stepping

A single runner handles normal and debug runs. A request in WorkflowRunModeEnum::DEBUG creates a paused run without executing a step. Set StartRunRequestDto::startStep to begin at a selected step; this replaces DebugEngine::startFrom().

use AdachSoft\Workflow\Run\ExecutionOptionsDto;
use AdachSoft\Workflow\Run\StartRunRequestDto;
use AdachSoft\Workflow\Run\WorkflowRunModeEnum;

$options = ExecutionOptionsDto::nonInteractive();
$debugRun = $workflowRunner->start(
    new StartRunRequestDto(
        workflowId: 'example',
        input: $payload,
        mode: WorkflowRunModeEnum::DEBUG,
        startStep: 'review',
    ),
    $options,
);

$debugRun = $workflowRunner->step($debugRun->runId, $options); // Advance exactly one step.
$debugRun = $workflowRunner->continue($debugRun->runId, $options); // Advance until completion or suspension.

step() advances a paused run by one step. continue() advances it until it succeeds or suspends. pause() pauses a running run and returns its updated state. cancel($runId, $reason) cancels a paused or suspended run. Use get($runId) to retrieve the current state. The old debug resume() advanced exactly one step; use step() for that behavior. The runner's resume() is for a suspended run and requires a ResumeSignalDto.

The run's lastStepExecution contains the latest debug step's name, resolved input, and output. Its branch is nullable: it is null when that step suspended. The record is null before a debug step executes and is not an execution history.

Step execution history

Configure a StepExecutionRecorderInterface with WorkflowRunnerBuilder::withStepExecutionRecorder() to retain a record for every step invocation and resume. InMemoryStepExecutionHistory is a ready-to-use recorder that also implements StepExecutionHistoryQueryInterface:

use AdachSoft\Workflow\Builder\WorkflowRunnerBuilder;
use AdachSoft\Workflow\Repository\InMemoryStepExecutionHistory;

$history = new InMemoryStepExecutionHistory();
$workflowRunner = WorkflowRunnerBuilder::create()
    ->withStepExecutionRecorder($history)
    ->build();

$stepExecutions = $history->findByRunId($runId);

Each StepExecutionRecordDto contains the run and workflow IDs, a one-based sequence number, step name and type, status, selected branch, input and output payloads, optional error, start and finish timestamps, and durationMs(). A returned branch is COMPLETED; a suspended step is SUSPENDED and gets another record as COMPLETED when resumed; an execution exception is FAILED.

The executor assigns sequence numbers. If the configured recorder also implements StepExecutionHistoryQueryInterface, its nextSequence() supplies the next number, allowing a recorder to continue an existing history. For a recorder implementing only StepExecutionRecorderInterface, the executor tracks the sequence for the lifetime of that runner. Implement both contracts when a custom recorder must continue sequences across runner instances.

When secret resolution is configured, recorded input, output, and error messages are masked before they reach the recorder. Recording is best-effort: a recorder exception does not interrupt workflow execution. With no recorder configured, step history is not retained. WorkflowRunVo::lastStepExecution continues to expose only the latest debug step.

Run lifecycle

WorkflowRunVo::status() returns a WorkflowRunStatusEnum. The complete lifecycle is available through $run->lifecycle, including status, mode, startedAt, updatedAt, error, and suspension. Terminal statuses are SUCCEEDED, FAILED, and CANCELLED; waiting statuses are PAUSED and SUSPENDED.

Starting state or eventOperationResult
New NORMAL runstart()Executes synchronously; returns SUCCEEDED or SUSPENDED. Execution failures are saved as FAILED before the original exception is thrown.
New DEBUG runstart()Starts as PAUSED without executing a step.
RUNNINGpause()PAUSED.
RUNNINGStep returns a non-terminal branchRemains RUNNING while the runner continues.
RUNNINGStep returns a terminal branchSUCCEEDED.
RUNNINGStep returns a suspensionSUSPENDED.
PAUSEDstep()Executes one step; the run pauses again, succeeds, suspends, or fails.
PAUSEDcontinue()Executes until success, suspension, or failure.
SUSPENDEDresume($runId, $signal, $options)Resumes the step; debug mode stops after one resumed step, while normal mode runs until success or another suspension.
PAUSED or SUSPENDEDcancel($runId, $reason)CANCELLED.

A terminal run cannot transition again. A run's execution mode remains NORMAL or DEBUG; debug behavior is not stored in a separate debug-state object.

Suspending and resuming

A step that can wait must implement ResumableStepInterface. Its execute() can return StepResultDto::suspend(new SuspensionDto(...)); its resume(StepContextDto $stepContextDto, ResumeSignalDto $resumeSignalDto) returns a branch result or another suspension. A suspension stores its reason, optional deadline, allowed decisions, awaited child run ID, and payload. The resuming step receives a signal, so include any data it needs in the signal payload or run context.

ResumeSignalDto provides decision(), timeout(), and childRunFinished() factories. For example:

use AdachSoft\Workflow\Run\ExecutionOptionsDto;
use AdachSoft\Workflow\Run\ResumeSignalDto;

$run = $workflowRunner->resume(
    $run->runId,
    ResumeSignalDto::decision('approve', actor: 'reviewer-7'),
    ExecutionOptionsDto::nonInteractive(),
);

The standard await_decision step suspends for approve or reject and routes a timeout to its own branch. Register it with WorkflowRunnerBuilder::withStandardSteps(). Its step configuration uses these keys:

use AdachSoft\Workflow\Engine\PayloadVo;

'approval' => new PayloadVo([
    'type' => 'await_decision',
    'config' => new PayloadVo([
        'reason' => 'Approval is required.',
        'timeout_seconds' => 3600,
        'on_approve' => 'approved',
        'on_reject' => 'rejected',
        'on_timeout' => 'timed_out',
    ]),
]),

timeout_seconds is optional and, when supplied, must be a positive integer. All three branch-target settings are required. A decision signal can include an actor and payload; timeout handling uses ResumeSignalDto::timeout(). A timeout signal is accepted only after the suspension deadline has passed.

To supply a timeout dynamically, map timeout_seconds from workflow context; a non-null input value overrides config, while null falls back to config:

'approval' => new PayloadVo([
    'type' => 'await_decision',
    'config' => new PayloadVo([
        'reason' => 'Approval is required.',
        'timeout_seconds' => 3600,
        'on_approve' => 'approved',
        'on_reject' => 'rejected',
        'on_timeout' => 'timed_out',
    ]),
    'input_map' => new PayloadVo([
        'timeout_seconds' => '$context.review_timeout_seconds',
    ]),
]),

Nested workflows that wait

RunWorkflowStep starts the child through the same runner and sets the child's parentRunId. If the child suspends, the parent also suspends with the child run ID as its awaited run. When the child becomes terminal, ParentRunNotifier automatically resumes the matching parent with the child's terminal status and output. A failed or cancelled child causes the waiting parent to fail.

WorkflowRunnerBuilder::withStandardSteps() wires RunWorkflowStep with the configured runner and workflow-definition repository. Configure a PSR-3 logger with withLogger() to receive parent-resume failures; the default is NullLogger:

use AdachSoft\Workflow\Builder\WorkflowRunnerBuilder;

$workflowRunner = WorkflowRunnerBuilder::create()
    ->withWorkflowDefinitionRepository($definitionRepository)
    ->withWorkflowRunRepository($runRepository)
    ->withStepRegistry($stepRegistry)
    ->withStandardSteps()
    ->withLogger($logger)
    ->build();

Expired suspensions

ExpiredSuspensionResumer queries suspended runs with an expired deadline and resumes each with a timeout signal. Provide a runner, a WorkflowRunQueryInterface, and a ClockInterface:

use AdachSoft\Workflow\Run\ExecutionOptionsDto;
use AdachSoft\Workflow\Runner\ExpiredSuspensionResumer;

$resumer = new ExpiredSuspensionResumer($workflowRunner, $runQuery, $clock);
$report = $resumer->resumeExpired(ExecutionOptionsDto::nonInteractive(), limit: 100);

The query's deadlineBefore filter is set from the supplied clock. The report lists successfully resumed run IDs and per-run failures. The library does not schedule this resumer or provide locking: running it periodically and coordinating locks is the application's responsibility.

Step logging

Steps can emit messages through the nullable StepContextDto::$logger property. Each StepContextDto also exposes workflowId, runId, and stepName so a step can correlate its work with the current workflow execution. Implement the package-owned StepLoggerInterface to connect messages to an application-selected destination; the engine does not require PSR-3 or another logging dependency.

use AdachSoft\Workflow\Contracts\StepLoggerInterface;

final class ApplicationStepLogger implements StepLoggerInterface
{
    public function log(string $message, array $context = []): void
    {
        // Send the message and data to the application's chosen destination.
    }
}

$stepContextDto->logger?->log('Processing item', ['item_id' => 42]);

Pass the channel and optional step logger through ExecutionOptionsDto:

use AdachSoft\Workflow\Run\ExecutionOptionsDto;
use AdachSoft\Workflow\Run\ResumeSignalDto;
use AdachSoft\Workflow\Run\StartRunRequestDto;

$options = new ExecutionOptionsDto($interactionChannel, $logger);
$workflowRunner->start(new StartRunRequestDto('example', $payload), $options);
$workflowRunner->step($runId, $options);
$workflowRunner->continue($runId, $options);
$workflowRunner->resume($runId, ResumeSignalDto::decision('approve'), $options);

For each emitted message, the receiver gets the unchanged message and a context with exactly these keys:

  • workflow_id - identifier of the workflow executing the step
  • run_id - identifier of that workflow run
  • step_name - name of the executing step
  • data - the original array supplied to StepLoggerInterface::log(); an omitted context is an empty array

The logger is scoped to the current step and call. Nested workflows forward the receiver automatically, and their records contain the child workflow's identifiers. Delivery is synchronous, so a step's message can be received before that step throws. The engine does not buffer logs or add them to run state or history, and it does not automatically log inputs, configuration, or exceptions. Steps control the messages and data they emit; avoid placing secrets or other sensitive data in logs.

Migration note: Version 7.0.0 replaces the separate engine APIs and changes workflow-run persistence. See UPGRADE-7.0.md for the breaking API and repository migrations.

Interaction channel

InteractionChannelInterface is the required bidirectional port between interactive workflow steps and their users. Applications provide transport adapters, such as a console or a WebSocket connection; the library does not provide transport-specific adapters.

  • write($data) sends a raw data fragment without adding a newline or formatting it.
  • read($timeoutSeconds) waits for at most the given number of seconds and returns a data fragment (which may include a newline), or null when no data arrives or the channel is closed.
  • isClosed() reports whether the user can no longer send data, for example after EOF or disconnection.
  • isInteractive() reports whether an interactive user is available through the channel.

Pass the channel inside ExecutionOptionsDto to WorkflowRunnerInterface::start(), step(), continue(), or resume(). Steps implementing InteractiveStepInterface receive it through executeInteractive(StepContextDto $stepContextDto, InteractionChannelInterface $interactionChannel); ordinary steps continue to use StepInterface::execute(). Options apply to that execution call only, so different steps can use different user sessions.

Use ExecutionOptionsDto::nonInteractive() when starting a workflow that has no interactive user. RunWorkflowStep forwards its parent's interaction channel to nested workflows. The channel is not stored in WorkflowRunVo or persisted by the run repository.

Inside executeInteractive(), a step can communicate with the user like this:

$interactionChannel->write('Enter a value: ');
$userInput = $interactionChannel->read(30.0);

Step Metadata

The registry can expose all registered step definitions via StepRegistryInterface::getAllDefinitions().

This returns StepDefinitionCollection and can be serialized using collection export methods.

Design Notes

  • The workflow runner depends on contracts for repositories and the step registry.
  • Normal workflow execution is synchronous and continues until the run succeeds or suspends.
  • Debug-mode runs start paused and can advance one step at a time.
  • Public API uses immutable value objects and collections.
  • Step metadata and branch contracts are centralized in #[StepType].
  • Input/config/output validation is integrated into runtime execution.
  • Data between steps travels only through run context and declared maps.

Development

Available Composer scripts:

composer test
composer phpstan
composer cs-fix
composer cs-check