Skip to content

Core PHP interfaces and public types

The PHP core executes a loaded Graph against a SessionState and returns the state and payload that your application uses. This reference groups its entry points and value types by that boundary. The embedding guide develops their composition; the PHP SDK is a separate client interface.

Type Namespace Application responsibility
ExecKernelFactory ExecKernel\Infrastructure\Engine Supply optional adapters and policies, then call build().
ExecKernel, EngineResult ExecKernel\Domain\Engine Supply a graph, operation inputs and session state; consume the result.
ExecKernelFacade ExecKernel\Application Supply an engine and loader; use graph identifiers with start, next and resume.
GraphLoaderInterface and graph value types ExecKernel\Domain\Graph Load or construct a graph before execution.
Context, History, SessionState ExecKernel\Domain\Session Carry application data, traversal history and the current position.
SessionStoreInterface and persistence results ExecKernel\SessionStore Save, restore and delete state through a selected store.

The engine has no store constructor argument. A returned EngineResult is a calculated result; your application or an adapter coordinates persistence and event publication.

ExecKernelFactory::build(): ExecKernel has no required arguments. All parameters below accept null by default except customRules, which defaults to []. Named arguments make the chosen dependencies visible:

use ExecKernel\Infrastructure\Engine\ExecKernelFactory;
use ExecKernel\Domain\Session\SessionExpirationPolicy;
$engine = (new ExecKernelFactory())->build(
sessionExpirationPolicy: new SessionExpirationPolicy(ttl: 3600),
);

This sets the core session expiration policy. It does not configure a database retention period or an HTTP deployment.

Parameter Accepted type Purpose
customRules array<string, string> Custom rule names mapped to their handler identifiers.
eventBridge EventBridgeInterface External event bridge.
pluginRegistry PluginRegistry Registered rules and output hooks.
timeProvider TimeProvider Evaluation time when an operation omits its timestamp.
dateTimeEvaluator DateTimeEvaluator Temporal condition evaluation.
stopwatch StopwatchInterface Elapsed-duration measurement.
sessionTtlSeconds int TTL fallback when no expiration policy is supplied.
sessionExpirationPolicy SessionExpirationPolicy TTL, idle TTL and absolute expiration.
debugPayloadBuilder DebugPayloadBuilder Detailed payload generation when debug: true is requested.
logger LoggerAdapterInterface Runtime logging.
traceEmitter TraceAdapterInterface Runtime tracing.
errorTelemetryEmitter ErrorTelemetryEmitterInterface Error telemetry.
auditLogger AuditLoggerInterface Audit records.
metricsCollector MetricsAdapterInterface Runtime metrics.
sessionLock SessionLockInterface Session lock used by operations that acquire it.
stateVersioning StateVersioningInterface State hash calculation and verification.
historyOverflowPolicy HistoryOverflowPolicy History overflow handling.
sandboxDriver SandboxDriverInterface Custom handler execution.
sessionIntegrity SessionIntegrityInterface State integrity signing and verification.
securityPolicy FlowSecurityPolicy Language, transition and state restrictions.
payloadSanitizer PayloadSanitizerInterface Sanitation of supported display fields.
versionUpgradePolicy SessionVersionUpgradePolicyInterface Decision when graph/session versions differ.

Engine and time types are in Domain\Engine; session types in Domain\Session; security types in Domain\Security; observability adapters in Observability; the upgrade interface in Domain\Versioning, all under ExecKernel\. Configuration, defaults and limits specifies the effective fallback for each component.

Direct construction requires Navigator, PayloadBuilder and FlowEventsDispatcher. The navigator, its evaluator and cycle breaker, and the engine must share the same dispatcher; inconsistent composition throws InvalidArgumentException. Prefer the factory unless your application needs to compose those components explicitly.

The following signatures belong to ExecKernel\Domain\Engine\ExecKernel. Graph, Context and SessionState refer to the namespaces above.

start(
Graph $graph, string $lang, ?Context $context = null,
bool $debug = false, ?string $sessionId = null, ?int $timestamp = null,
bool $deferEvents = false, ?string $operationId = null,
): EngineResult
choose(
Graph $graph, SessionState $state, int $edgeId, string $lang,
?Context $contextUpdates = null, bool $debug = false,
?string $sessionId = null, ?int $timestamp = null,
?string $expectedStateHash = null, bool $deferEvents = false,
?string $operationId = null,
): EngineResult
resume(
Graph $graph, SessionState $state, string $lang, bool $debug = false,
?string $sessionId = null, ?int $timestamp = null,
bool $deferEvents = false, ?string $operationId = null,
): EngineResult
getPayload(
Graph $graph, SessionState $state, string $lang, bool $debug = false,
?int $timestamp = null, ?Context $contextUpdates = null,
?string $operationId = null,
): array
Operation State and result
start Starts at graph.rootNodeId. Creates context and history, then returns the current payload.
choose Applies a candidate context update and validates the selected edge before returning the next state and payload. The input state remains the caller’s previous value.
resume Checks graph/session compatibility and expiration, then returns the current state and a regenerated payload without choosing an edge. An upgrade policy can resolve a graph matching the session revision; changing the serialized state is rejected with EK-GRAPH-060 and reason revision_change_requires_confirmed_transition.
getPayload Builds a preview using the supplied state and optional candidate context. Returns only the payload, so candidate updates are not a returned replacement state. It publishes its collected events.

timestamp is Unix time in seconds. An explicit value takes precedence over the configured clock. sessionId supplies operation correlation and, where used, lock/integrity context; the core does not generate a persisted session record from it. operationId identifies the collected event operation.

For choose, expectedStateHash is checked through the configured versioning adapter. It does not turn a separate database write into an atomic compare-and-swap. Coordinate the write through the session store contract.

deferEvents: true returns the collected RuntimeEventBatch without publishing it immediately. With the default false, the engine publishes before returning. Use the event catalogue when coordinating publication with persistence.

EngineResult exposes readonly state: SessionState, payload: array<string, mixed> and eventBatch: ?RuntimeEventBatch = null. The payload describes a decision node or terminal output; the state carries the execution position.

This fragment assumes $graph is an already loaded graph whose allowed languages include en:

use ExecKernel\Domain\Session\Context;
$result = $engine->start(
graph: $graph,
lang: 'en',
context: new Context(['eligible' => false]),
timestamp: 1700000000,
);
$stateToKeep = $result->state;
$payloadForYourApplication = $result->payload;

Your application renders the payload and retains the returned state for the next operation. Payload fields are listed in Node and terminal payloads.

An unknown language can raise UnknownLanguageException; a missing node, NodeNotFoundException; forbidden navigation, InvalidEdgeException or ForbiddenEdgeException; incompatible revisions, VersionCompatibilityException. Lock, integrity, context and performance policies can also reject an operation. See the error catalogue for codes and details.

ExecKernelFacade::__construct(ExecKernel $engine, GraphLoaderInterface $loader) binds loading to execution.

Signature Behavior
start(int|string $graphCode, array|Context|null $initialContext = null, ?ContextValidationPolicy $contextPolicy = null): EngineResult Loads the graph, converts an array to Context and starts with its default language. An existing Context retains its own policy.
next(int|string $graphCode, SessionState $state, int $edgeId): EngineResult Loads the graph, verifies the state’s graph code and delegates to choose.
resume(int|string $graphCode, SessionState $state): EngineResult Loads the graph, verifies the state’s graph code and regenerates the payload.

The language is graph.defaultLang ?? ''. These facade methods do not expose per-call language, timestamps, context updates on next, session IDs or deferred events. Use the underlying engine when your application needs those inputs. The facade neither saves the result nor supplies a session store.

GraphLoaderInterface::load(string|int $graphCode): Graph returns a fully loaded graph. The accepted identifier form and source lookup belong to its implementation; loaders and repositories explains the choices.

Graph requires string $graphCode, array $nodesById and int $rootNodeId. Its remaining constructor fields are:

Field Default Contents
graphId null Optional legacy numeric correlation; graphCode is canonical identity.
edgesFrom [] Origin node ID → array of Edge.
labelsByEdge [] Edge ID → language → EdgeLabel.
metadataByNode [] Node ID → language → Metadata.
outputsByNode [] Node ID → array of TerminalOutput.
conditionsByEdge [] Edge ID → array of Condition or declarative condition arrays.
defaultLang null Optional default language.
allowedLangs [] Array of language strings.
graphWebhooks, webhooksByNode, webhooksByEdge [] Graph-level list and node/edge-indexed webhook lists.
graphVersion, dslVersion, schemaVersion null Optional version strings.

The graph exposes readonly indexed collections, including edgesById built from edgesFrom. Its constructor requires an existing nonterminal root and checks index consistency, duplicate identifiers and references. Schema import performs further validation; direct object construction and importing are distinct entry points.

Value type Constructor
Node (int $id, bool $isTerminal = false)
Edge (int $id, int $fromNode, int $toNode)
EdgeLabel (int $edgeId, string $lang, string $text, ?string $description = null, ?array $extras = null)
Metadata (int $id, int $nodeId, string $lang, string $title, ?string $subtitle = null, ?string $description = null, ?array $extras = null)
TerminalOutput (?int $nodeId = null, string $type = '', ?string $url = null, ?string $label = null, ?string $openBehavior = null, ?string $lang = null, ?string $content = null)
Condition (string $rule, array $params = [], ?string $version = null)

EdgeLabel rejects an empty text. TerminalOutput rejects an empty type despite its constructor default, and a non-null blank label. Condition rejects an empty rule, blank version and non-declarative parameters. Descriptive arrays are snapshotted. The graph schema specifies the portable representation; programmatic construction shows a complete graph.

Context::__construct(array $values = [], ?ContextValidationPolicy $policy = null) validates the application values. get(string $key, mixed $default = null): mixed reads a value; all() and toArray() return the array. with(string $key, mixed $value): self and merge(Context $other): self return new contexts. Merge keeps the receiving context’s policy and lets the other context replace matching keys.

$original = new Context(['eligible' => false]);
$updated = $original->with('eligible', true);
// $original->get('eligible') is false.
// $updated->get('eligible') is true.

History(array $edges = [], array $nodes = [], ?HistoryOverflowPolicy $overflowPolicy = null) records integer identifiers. withEdge and withNode return a new history; hasEdge, hasNode, edges and nodes inspect it.

SessionState requires graphCode, currentNodeId, Context, History and three integer timestamps: createdAt, updatedAt and lastTransitionAt. Optional graphVersion, dslVersion and flowId default to null. Its constructor rejects blank graph identity or inconsistent timestamp order. Serialization, integrity and the withNode/withContext/withHistory operations are specified in Session state and serialization contracts.

Store signature Contract
save(string $sessionId, SessionState $state): SessionPersistenceResult Returns the resulting state and whether it was persisted.
load(string $sessionId): ?SessionState Returns state or null when unavailable.
delete(string $sessionId): void Removes the stored state according to the implementation.
supportsConditionalWrites(): bool Optional ConditionalSessionStoreInterface capability.
getStateHash(SessionState $state): string Computes the conditional store’s state token.
saveWithExpectedHash(string $sessionId, SessionState $state, ?string $expectedHash): SessionPersistenceResult A non-null token must match the persisted state.
createIfAbsent(string $sessionId, SessionState $state): SessionPersistenceResult Commits only if the session key is still absent.

SessionPersistenceResult exposes readonly state, persisted: bool, stateHash: ?string = null and warnings: array = []. Check persisted before telling a user that a session was saved. Conditional operations require a cooperating implementation and lock/provider; persistence modes explains their operational guarantees.

The engine exposes on(string $event, callable $listener): void, onGraph(string $event, string $graphCode, callable $listener): void, onFlow(string $event, int $flowId, callable $listener): void and onSession(string $event, string $sessionId, callable $listener): void. attachRuntimeListener(RuntimeEventListenerInterface $listener) and addMonitor(RuntimeMonitorInterface $monitor) also return void. Listener envelopes and registration contracts are in the event catalogue and extension reference.

resolveSessionGraph(Graph $graph, SessionState $state): Graph applies the configured compatibility/upgrade decision and returns the resolved graph. It does not persist an upgraded session.

toErrorResponse(Throwable $exception, ?int $flowId = null, ?string $sessionId = null, ?int $timestamp = null): array creates the core error envelope and emits error observations. It does not create an HTTP response. The error reference distinguishes that envelope from SDK errors and the standalone API.