Skip to content

Core HTTP and replay middleware contracts

The core package includes HTTP adapters that your PHP application can mount around an engine. ExecKernelHttpMiddleware handles live session operations; ReplayHttpMiddleware reads historical evidence and reconstructs or reevaluates it. They accept the core’s lightweight HttpRequest and return HttpResponse objects.

These are components to compose into a host application. The independent HTTP API is a separate Slim application with its own routes, DTOs, persistence and deployment access layer.

Surface Routes or callable entry Required host responsibilities
Core live HTTP middleware Start, next/navigate, resume and delete under /execkernel/session. Engine, graph loader, core session store, HTTP adaptation and access policy.
Core replay middleware Export, full replay, partial replay and comparison under /api/replay. Replay engine, evidence/report store, graph loader and optional numeric-ID resolver.
Independent API Six session/graph operations, including inspect and status. Its own configured application and deployment. See its separate reference.
Core scenario controller ExecKernelController::handleNext(array $payload): array. Explicit benchmark scenario files and a store. This method does not register an HTTP route.

Application/api/public/index.php in the core is a fixture entry point: it loads test bootstrap code and a benchmark graph, constructs a fresh in-memory session store and delegates to the live middleware. It neither mounts replay nor provides a persistent production service. Route composition and store lifetime belong to the host that integrates these components.

Both objects are in ExecKernel\Application\Api\Middleware.

Type Constructor and methods
HttpRequest __construct(string $method, string $path, array $body = [], array $query = [], array $headers = []). Getters: getMethod(): string, getPath(): string, getBody(): array, getQuery(): array, getHeaders(): array.
HttpResponse __construct(int $status, array $body). Getters: getStatus(): int, getBody(): array, getHeaders(): array; serialization: toJson(): string.

These adapters are framework-independent rather than PSR-15 middleware implementations. Your host parses the actual HTTP request, validates its JSON wire representation and supplies decoded body/query/header arrays. The DTO itself does not decode JSON or detect duplicate raw JSON keys. Use the returned status, headers and JSON body when writing the response.

HttpResponse supplies Content-Type: application/json and, when its body contains trace_id, X-Trace-Id. Invalid trace values are replaced. toJson() preserves fractional numbers and throws on JSON encoding failure.

ExecKernelHttpMiddleware takes these constructor parameters, in order:

Parameter Type and default
engine Required core ExecKernel.
loader Required GraphLoaderInterface.
sessionStore Required core SessionStoreInterface.
normalizer HttpRequestNormalizer = new HttpRequestNormalizer().
validator FlowRequestValidator = new FlowRequestValidator().
responses ?FlowHttpResponseFactory = null; constructs the standard factory with the engine and ErrorHttpMapper.
versionValidator ?SdkApiCompatibilityValidator = null.
logger ?ExecKernelLoggerInterface = null; defaults to a null logger.
metricsCollector ?MetricsAdapterInterface = null; defaults to a null collector.

The dispatch entry is handle(HttpRequest $request): HttpResponse. Public start, next, resume and destroy methods have the same request/response signature. Direct start/next/resume calls validate their operation payload but do not perform handle’s route/method dispatch; the host must route them correctly. Direct destroy still normalizes and checks the delete route.

handle normalizes method case and trailing slashes, then dispatches:

Method and path Consumed fields
POST /execkernel/session/start Required flow; optional context, lang, session_id, timestamp.
POST /execkernel/session/next Required session_id, edge_id; optional context, timestamp.
POST /execkernel/session/navigate Alias of next with the same fields.
POST /execkernel/session/resume Required session_id; optional lang, timestamp.
DELETE /execkernel/session/{session_id} Path session ID; a body ID, if supplied, must agree.
Field Boundary rule
flow String or integer; a string must be non-empty after trimming for the check. The validator does not impose the independent API’s positive-integer rule. The loader must resolve it.
session_id Non-empty string without leading/trailing whitespace. Start may omit it or use null, generating bin2hex(random_bytes(10)).
edge_id PHP integer from the decoded request; numeric strings are rejected.
context PHP array; default []. The engine’s context policy then validates keys, values and limits. Explicit null is invalid.
lang Optional string or null. Start/resume use explicit language, graph default or the first allowed language.
timestamp Optional integer or null. Null lets the engine supply its time; the engine still enforces its state/time rules.

Next loads the saved session and uses the graph’s default/first allowed language; it does not consume lang or persist a start-time presentation language. Resume regenerates presentation without writing a replacement state. This differs from the independent API, which stores the start language in its API snapshot.

Delete decodes its single path segment with rawurldecode, rejects malformed percent escapes and conflicting body identity, then calls the store’s delete. Unknown methods/paths through this middleware produce an input error, HTTP 400 / EK-INPUT-400. There are no inspect or status routes here.

Operation Success body, HTTP 200
Start / next / navigate session_id, state, payload, trace_id and boolean persisted.
Resume session_id, state, payload and trace_id.
Delete session_id, deleted: true and trace_id.

Conditional core stores are used when they advertise support: start uses create-if-absent and next saves with the hash of the state loaded by the middleware. Client-supplied state or expected-revision fields are not a replacement for that stored state.

A store can explicitly report persisted: false. The middleware returns that flag with the computed result and discards deferred success events. When persistence is confirmed, it verifies the returned state’s content and publishes those events. Thrown or inconsistent save results become dependency errors. Both SDKs reject a remote session reply that explicitly says persistence was not confirmed.

The live middleware obtains its trace ID from a valid version-00 traceparent first, then X-Trace-Id, otherwise generates one. Logger and metrics failures are contained. The middleware itself does not add authentication or a rate limiter.

The optional version validator reads X-ExecKernel-Api-Version or X-Api-Version, and X-ExecKernel-Sdk-Version or X-Sdk-Version. It also reads body api_version and sdk_version. Contradictory or malformed declarations are input errors. When both versions exist, the compatibility matrix is checked; an incompatible pair produces EK-VERSION-100, HTTP 400.

Recognizing a version prefix in the validator does not register a versioned route in the normalizer. The supplied SDK clients do not send these declarations automatically. Replay does not use this validator; its version fields identify historical evidence or the target graph. See Version compatibility matrix.

ReplayHttpMiddleware has the following constructor:

Parameter Type and default
replayEngine Required ExecKernel\Replay\ReplayEngine.
sessionStore Required ExecKernel\Application\Api\Replay\ReplaySessionStoreInterface.
graphLoader Required GraphLoaderInterface.
engine Required core ExecKernel for constructor compatibility/default response factory.
graphCodeResolver ?GraphCodeResolverInterface = null.
responses ?ReplayHttpResponseFactory = null.
validator ?ReplayRequestValidator = null.
exporter ?DebugReplayExporter = null.

Its public entry is handle(HttpRequest $request): HttpResponse. The evidence store is a different interface from the live session store:

loadDebugReplayTrace(string $sessionId): ?array
loadStateExport(string $sessionId): ?array
saveComparisonReport(string $sessionId, array $report): void
loadComparisonReport(string $sessionId): ?array

These are interface signatures. Your implementation supplies historical evidence, stores comparison reports and owns their durability, concurrency and retention. GraphCodeResolverInterface::resolveGraphCode(int $flowId): string resolves a numeric target selector when reevaluation requires it.

Strict replay reconstructs the trace without loading a target graph. Through this middleware it has no historical graph object, so the evidence level is trace_consistency and terminal verification can be null. Reevaluation loads the selected target and checks it against the requested identity. Neither operation updates a live session. Comparison additionally writes a report and requires an exact readback, including its unique report ID, before acknowledging success.

Method and path Operation
GET /api/replay/{session_id} Export a complete trace or an inspection window. Query only; a non-empty body is rejected.
POST /api/replay/session/{session_id} Replay the complete stored source. Body only; query fields and range selectors are rejected.
POST /api/replay/partial Replay a selected inclusive window. Requires body session_id, start_step and end_step.
POST /api/replay/compare Reevaluate against a target and confirm a comparison report. Requires body session_id.

A path ID must occupy one segment. A body/query session_id supplied alongside the path must match. Replay uses the path value supplied in HttpRequest; the host controls any prior URL decoding. Unknown routes/methods produce a malformed-request error.

Field Accepted value
step One non-negative representable integer or decimal-digit string.
range String start-end; bounds are inclusive and non-negative, and start must not exceed end.
mode Optional strict or reeval string. Validated but does not execute replay or change the export operation.

step and range are mutually exclusive. Export rejects execution selectors start_step, end_step and replay_mode. It validates the complete trace before selecting rows. A filtered result has export_scope: "inspection_window" and window metadata; it is a view for inspection, not a standalone executable trace. The unfiltered result has export_scope: "full_trace".

Field Type, default and meaning
replay_mode strict by default for session/partial. Compare always uses reeval and rejects another explicit value.
source_kind debug_trace by default; state_export_scenario requires reevaluation.
graph_code Optional non-empty string target selector. In reevaluation it takes precedence over an explicit flow_id.
flow_id Optional JSON integer. Used through the resolver when no explicit graph code selects the target.
graph_version, dsl_version, engine_version Optional non-empty identity strings. In strict mode supplied values must agree with the historical source; in reevaluation graph/DSL identities are checked against the loaded target.
start_step, end_step Optional non-negative integers or decimal-digit strings. Both required for partial; forbidden on the full-session route; optional on compare.
overrides Object with only optional context. Context overrides use string keys; omitted/null context means no overrides. A non-empty override is rejected in strict mode.
allow_side_effects, allow_webhooks Optional booleans or null. True is rejected by this HTTP boundary. Omission, null or false does not enable effects.

Execution rejects export selectors step, range and mode. Other unspecified fields are not a supported extension contract; the validator is not a blanket unknown-field rejection mechanism.

For reevaluation, target selection uses an explicit graph code, otherwise an explicit numeric flow ID through the resolver, otherwise historical graph identity. Strict mode checks historical identity instead of loading a target. A state-export scenario also requires fixed-clock scenario evidence and a window starting at zero; it cannot supply a missing historical prefix.

State export and replay contracts defines source formats, reconstructed prefixes, target evaluation and the meaning of divergence.

The examples reuse the expense-review evidence from Replay: session expense-example has two recorded selections, edge 101 from node 10 to 20 and edge 102 to terminal 30. The final recorded amount is 120. The host’s replay store must already return that trace; target reevaluation loads its graph definition.

Operation Minimal request data for that evidence
Export second step GET /api/replay/expense-example?range=1-1 with an empty body.
Full strict replay POST /api/replay/session/expense-example with {"replay_mode":"strict"}.
Partial strict replay POST /api/replay/partial with {"session_id":"expense-example","start_step":1,"end_step":1}.
Compare original target POST /api/replay/compare with {"session_id":"expense-example","graph_code":"expense-review","engine_version":"0.2.0","allow_side_effects":false,"allow_webhooks":false}.

Export returns {trace_id, replay}. Execution returns these fields:

Group Fields and meaning
Always trace_id: string, session_id: string, mode: string, final_node_id: int, final_context: array, steps: list, divergences: list, has_divergences: bool.
Evidence result When an evidence level exists: evidence_level, nullable terminal_verified and final_timestamp, nullable reconstructed_history.
Target reevaluation When a target exists: target_graph_code, nullable target graph/DSL/engine versions, attempted_step_count, completed_step_count, time_basis, historical_comparison_complete and nullable stop_reason.
Confirmed comparison report_id: string and report_write_confirmed: true.
Source metadata source_kind, source_hash, source graph/flow/version fields, window, source_step_count, source_evidence_level, override_keys, comparison_scope and uncompared_alternative_outcomes.

A step row contains step_number, node_before, node_after, selected_edge, available_edges, context_diff, timestamp and evaluated_conditions. A divergence contains step_number, type, expected, actual and details.

For the full strict example, the result is node 30, final context {"amount":120}, no divergences, evidence level trace_consistency and terminal_verified: null. Partial replay of step 1 returns the same final node while reconstructing the prefix history. Compare uses reeval, returns target metadata and a confirmed report. A 200 response may contain divergences or an early stop; inspect the result fields rather than treating HTTP success as equivalence.

The complete core HTTP exchanges include full responses for these four operations and live start/next/resume/navigate/delete, plus rejected requests. The live examples use the same graph with their own core-reference session and explicit timestamps; they do not overwrite the historical trace.

Core responses preserve the domain code as error.ek_code. They also return a catalog-based message, severity, a filtered context, nullable hint, HTTP status and trace identifier. For example, putting range selectors on the full-session replay route returns:

{
"error": {
"ek_code": "EK-API-001",
"message": "Request inválida.",
"severity": "BLOCKER",
"context": [],
"hint": null,
"http": 400,
"trace_id": "3f930e212f99f985"
},
"trace_id": "3f930e212f99f985",
"session_id": "expense-example"
}
Failure Typical code/status
Live route/input validation EK-INPUT-400 / 400.
Malformed replay input or selector EK-API-001 / 400.
Required replay field absent EK-API-002 / 400.
Missing/inconsistent replay evidence or forbidden replay effects EK-REPLAY-001 / 400.
Incompatible declared SDK/API pair in live middleware EK-VERSION-100 / 400.
Unconfirmed comparison-report write EK-SYS-002 / 500, with report_write_confirmed: false in error context.

ErrorHttpMapper uses its explicit map, then the domain exception’s valid HTTP status; EK-SYS-* and EK-INT-* are server errors. Other throwables map to 500. Live errors use the engine’s error conversion with filtered public data. Replay errors use catalog-only responses and do not dispatch errors through live engine observers.

Replay generates a fresh trace ID rather than adopting incoming trace headers. The independent API uses a different envelope, error.code/message/details, and remaps several domain codes. Use Error codes and exceptions when interpreting failures across surfaces.

ExecKernel\Application\Api\Controllers\ExecKernelController takes ExecKernel $engine, string $projectRoot and core SessionStoreInterface $sessionStore. Its handleNext(array $payload): array returns {status, body} and loads only benchmark scenarios S1–S5 from the supplied project root.

Its separate ExecKernelRequest::fromArray consumes required session, edge, scenario, lang and timestamp, plus persist: bool = false. Numeric edge/timestamp values are cast to integers; this differs from the live middleware’s strict integer fields. It can start a missing state and select an edge within one call, returning {session, payload}. This controller and its scenario data are an additional adapter contract, not another route of the independent API or an alternative spelling of /execkernel/session/next.