Skip to content

Events and runtime listeners

An event reports something that happened during an engine operation: a session started, a condition was evaluated, or navigation reached another node. A listener is application code that subscribes to an event and receives its data when the event is published. You can use one to update an activity summary, maintain a tracking view, or connect another integration.

Choosing the event matters. An evaluation can belong to an attempt that eventually fails; a result notification says that the engine completed the operation. To show session progress, this guide listens to result events and explains how to coordinate their publication with your application’s storage.

We will reuse the learning-path graph from JSON and YAML graph definitions. At node 10, the application offers a guide through edge 101 and a practice exercise through edge 102. Choosing the guide reaches terminal node 20. We will add a summary showing the session’s node and screen type after starting or choosing.

The graph continues to define the route and its outputs. The summary belongs to the application and is built from received events. The figure illustrates one way to display it: ExecKernel supplies data, and your application decides how to present it.

The application summary changes from the initial node to the terminal after the guide is selected.

RuntimeEventListenerInterface requires a subscribe() method. The engine passes its FlowEventsDispatcher, the component that manages subscriptions and distributes events. The following class listens for session starts and visits resulting from a choice, restricted to one graph code.

<?php
declare(strict_types=1);
namespace App\Extensions;
use ExecKernel\Domain\Engine\FlowEventsDispatcher;
use ExecKernel\Domain\Engine\RuntimeEventListenerInterface;
final class ActivitySummaryListener implements RuntimeEventListenerInterface
{
private array $summaries = [];
public function __construct(private readonly string $graphCode) {}
public function subscribe(FlowEventsDispatcher $dispatcher): void
{
$record = function (array $event): void {
$sessionId = $event['session_id'] ?? null;
if (!is_string($sessionId)) {
return;
}
$this->summaries[$sessionId] = [
'node' => $event['node'],
'payload_type' => $event['payload_type'],
'operation' => $event['operation_kind'],
];
};
$dispatcher->onGraph('runtime.session_started', $this->graphCode, $record);
$dispatcher->onGraph('runtime.node_visited', $this->graphCode, $record);
}
public function latest(string $sessionId): ?array
{
return $this->summaries[$sessionId] ?? null;
}
}

onGraph() prevents events from other graphs on the same engine from reaching this summary. Inside the callback, session_id keeps each session’s summary separate. The example supplies a session ID when calling the engine; the listener skips events without one.

We retain only node, payload_type, and operation_kind. The summary exposes the last field as operation, a name chosen by our application. Starting emits runtime.session_started; completing a choice emits runtime.node_visited. Their data lets the application replace the previous summary without treating intermediate evaluations as progress.

Load the graph and attach the listener before running operations. Make the class available through your application’s autoloader or an explicit require, as these downloads do.

require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/ActivitySummaryListener.php';
use App\Extensions\ActivitySummaryListener;
use ExecKernel\Infrastructure\Engine\ExecKernelFactory;
use ExecKernel\Infrastructure\Loader\JsonGraphLoader;
$graph = (new JsonGraphLoader())->load(__DIR__ . '/learning-path.json');
$engine = (new ExecKernelFactory())->build();
$activity = new ActivitySummaryListener('learning-path');
$engine->attachRuntimeListener($activity);

This connection applies to that $engine instance. Your application retains the same $activity object that receives events so it can read the summary.

Now start the session and choose the guide. The timestamps are explicit example inputs one second apart; the code does not wait.

$start = $engine->start(
$graph, 'en', sessionId: 'activity-demo', timestamp: 1796374800,
);
$before = $activity->latest('activity-demo');
$chosen = $engine->choose(
$graph, $start->state, 101, 'en',
sessionId: 'activity-demo', timestamp: 1796374801,
);
$after = $activity->latest('activity-demo');

The complete example produces these values:

{
"before": {
"node": 10,
"payload_type": "node",
"operation": "start"
},
"after": {
"node": 20,
"payload_type": "terminal",
"operation": "choose"
},
"current_node": 20
}

$before describes the initial node, and $after describes the terminal. Your controller can include $after in the response used by the interface, or your presentation layer can read latest() directly. The listener retains its data in memory for the lifetime of the object. To read it from another request or process, your application needs to store it.

Download ActivitySummaryListener.php, events-listeners.php, and learning-path.json. Place these files in your project root, alongside the vendor/ directory of an application that already uses ExecKernel. The script loads vendor/autoload.php from that root.

You can register a callback directly with $engine->on(...) or group subscriptions in a class like the one above. Scope methods are available on both the engine and the dispatcher supplied to subscribe().

Method Events received by the callback
on($event, $listener) That event name across operations on the instance.
onGraph($event, $graphCode, $listener) That event when the graph code matches.
onFlow($event, $flowId, $listener) That event when it carries the specified numeric flow ID.
onSession($event, $sessionId, $listener) That event for one particular session.

Subscriptions accumulate. If you register the same action globally and for a graph, an event matching both can invoke it twice. The summary needs only a graph subscription and a key per session. To follow one known session, onSession() may be more convenient. Register these connections before starting an operation.

By default, start() and choose() publish the completed operation’s events before returning the result. This supports the example above, but completing the calculation does not mean your application has saved the state.

If the summary must reflect only changes confirmed in storage, use deferEvents: true. The result includes a RuntimeEventBatch: a batch waiting to be published. In this fragment, $state is the starting state and $save is an application function that saves the new state and returns successfully only after storage confirms it.

$result = $engine->choose(
$graph, $state, 101, 'en',
sessionId: $sessionId,
timestamp: $timestamp,
deferEvents: true,
);
try {
$save($sessionId, $result->state);
} catch (\Throwable $failure) {
$result->eventBatch->discard();
throw $failure;
}
$result->eventBatch->publish();

While the batch is pending, the listener retains the previous summary. After saving and calling publish(), it receives the new result. If saving fails, discard() discards the batch and the summary stays unchanged. Execution lifecycle and confirmed state explains this boundary.

A batch can be consumed only once: a second publication returns false. It lives in memory. If the process ends after saving but before publishing, no durable delivery remains pending. If your application must recover from that gap, it also needs to retain the delivery work. Webhook delivery, retries and queues discusses that responsibility for HTTP notifications.

When an engine operation fails, its result events are not published. Diagnostic events from the attempt can still be published. This is why the summary listens to runtime.node_visited rather than a condition evaluation.

Callbacks run synchronously during publication. If one throws, the dispatcher isolates the failure and continues with later listeners; it does not revert the calculated state. Your summary may be stale, so your application must decide how to record or recover from the failure. When wiring the dispatcher directly, onDeliveryFailure() lets you observe the channel, event, and exception class.

Use a listener to react to a result. To prevent a transition, express that decision as a condition, as described in Creating custom rules. To reuse this listener when constructing engines, continue with Plugin architecture and lifecycle. The event catalogue provides the complete names and contracts.