# How System State Is Projected from the Runtime Event Log in Apache Maka

> Learn how Apache Maka projects system state from its Runtime Event Log. Discover how this immutable ledger drives model history, UI views, and recovery data.

- Repository: [The Apache Software Foundation/maka](https://github.com/apache/maka)
- Tags: internals
- Published: 2026-08-26

---

**Apache Maka treats the Runtime Event Log as the immutable source of truth, computing all system states—including model history, UI views, and recovery data—as deterministic projections over this ordered ledger.**

Apache Maka is an open-source agent runtime that abandons mutable state in favor of an append-only event ledger. Every fact produced during an agent’s execution—from model messages to tool calls—is captured in the **Runtime Event Log**, ensuring that **system state projected from the Runtime Event Log** remains deterministic and reproducible across all consumers.

## The Core Projection Model

In [`docs/architecture/runtime-core-architecture-draft.md`](https://github.com/apache/maka/blob/main/docs/architecture/runtime-core-architecture-draft.md) (lines 71-84), the architecture defines the fundamental relationship:

```

State(t) = Project(RuntimeEvents[0..t], policy, runtime configuration)

```

Here, `RuntimeEvents[0..t]` represents the immutable slice of the log up to time *t*. The **Project** function applies a specific policy—such as model-history or UI rendering rules—to materialize a concrete state. Because the log is append-only, any projection can be recomputed at any point, enabling reproducible state reconstruction and semantic replay.

### Immutable Facts as the Source of Truth

According to the source code, the Runtime Event Log stores every fact produced during execution: model messages, tool calls, permission actions, usage records, and termination facts. Unlike traditional systems that update mutable objects in place, Maka persists each `RuntimeEvent` to a durable ledger before exposing data to consumers. This design guarantees that `State(t)` is always a pure function of the event history rather than incidental memory state.

## Projection Pathways in Apache Maka

The runtime supports multiple projection policies that consume the same log but serve different consumers. Each pathway is implemented as a distinct policy function applied to the immutable event stream.

### Model-History Projection

The `RuntimeKernel` uses this projection to build the sequence of messages, thinking traces, and tool calls sent to the next LLM request. Located conceptually in the model-history projection logic referenced in the architecture diagram (lines 84-92), this pathway selects non-partial, model-visible events and assembles them into the prompt payload. When the kernel needs to initiate a new turn, it invokes this projector to prepare the context window.

### UI and Session Projection

UI components such as `LiveTurnProjection` and `TranscriptProjection` consume the log to render the chat interface. In [`packages/ui/src/transcript-projection.ts`](https://github.com/apache/maka/blob/main/packages/ui/src/transcript-projection.ts), the `createTranscriptProjection()` function reconciles turn identities and overlays live-turn data onto the stored ledger. This produces a UI-ready array of `TurnViewModel` objects that the desktop or TUI renders without mutating the underlying events.

### Terminal Fact and Run State

The `AgentRun` class (in [`packages/runtime/src/agent-run.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/agent-run.ts)) projects a durable "run-ended" fact that marks completion status—success, failure, or abort. This projection writes terminal state back to the ledger, creating a boundary that recovery logic can use to determine where execution stopped.

### Recovery and Repair Projection

When restarting after a crash, the restart logic re-reads the durable portion of the log and rebuilds the `AgentRun` envelope. This projection re-hydrates facts without requiring external checkpoints because the complete execution history is available in the ledger.

### Context Selection and Compaction

For providers with token limits, `ContextBudget` policies project a trimmed subset of the log that satisfies provider constraints while preserving required semantics. This compaction projection ensures the model-history fits within context windows without losing critical dependencies.

## Orchestrating the Projection Pipeline

The transition from raw backend events to projected states follows a strict five-step orchestration defined in the runtime core:

1. **Entry Point** – `SessionManager.sendMessage()` delegates to `RuntimeKernel.startTurn()` (architecture guide lines 77-84), initiating a new execution turn.

2. **Event Mapping** – `RuntimeKernel` creates an `AgentRun` instance and subscribes to the backend stream. Each backend `SessionEvent` is mapped to a canonical `RuntimeEvent` via [`packages/runtime/src/session-event-runtime-mapper.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/session-event-runtime-mapper.ts).

3. **Durable Logging** – Before exposing any data to callers, `AgentRun` writes every `RuntimeEvent` to the persistent ledger (architecture guide lines 31-38). This ensures durability before side effects occur.

4. **UI Consumption** – UI layers build views by feeding the log into projection functions such as `createTranscriptProjection()`, which handles incremental slices and live-turn overlays.

5. **Model Preparation** – When the next LLM request is required, `RuntimeKernel` invokes the model-history projector, selecting relevant events and assembling the prompt payload.

This pipeline guarantees that all consumers—from the model provider to the desktop interface—operate on identical event sourcing.

## Implementation Examples

The following TypeScript patterns demonstrate how client code interacts with the projection system:

```typescript
// Model-history projection for the next LLM call
import { RuntimeKernel } from '@maka/runtime';
import { buildModelHistory } from '@maka/runtime/model-history-projection';

async function nextModelRequest(kernel: RuntimeKernel, sessionId: string) {
  // Retrieve the ordered RuntimeEvent ledger for the session
  const events = await kernel.getRuntimeEvents(sessionId);
  const modelHistory = buildModelHistory(events); // selects non-partial, model-visible facts
  return modelHistory; // array of messages ready for the provider
}

```

```typescript
// UI transcript projection used by the desktop interface
import { createTranscriptProjection } from '@maka/ui/transcript-projection';

const proj = createTranscriptProjection();
const turnViews = proj.project({
  sessionId: 'sess-123',
  messages: storedMessages,           // raw StoredMessage[] from SQLite
  liveTurn: currentLiveTurn,         // optional live-turn overlay
});
/* turnViews contains UI-ready TurnViewModel objects—each turn
   retains identity unless its projected value changed. */

```

## Key Source Files

Understanding the projection architecture requires familiarity with these specific modules:

- **[`docs/architecture/runtime-core-architecture-draft.md`](https://github.com/apache/maka/blob/main/docs/architecture/runtime-core-architecture-draft.md)** – Defines the projection model, State(t) formula, and architectural diagrams (lines 27-33, 71-92).
- **[`packages/runtime/src/runtime-kernel.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/runtime-kernel.ts)** – Orchestrates turn execution, creates `AgentRun`, and drives the projection pipeline.
- **[`packages/runtime/src/session-event-runtime-mapper.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/session-event-runtime-mapper.ts)** – Maps backend `SessionEvent`s to canonical `RuntimeEvent` log entries.
- **[`packages/runtime/src/agent-run.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/agent-run.ts)** – Persists `RuntimeEvent`s and provides the durable run envelope for recovery projections.
- **[`packages/ui/src/transcript-projection.ts`](https://github.com/apache/maka/blob/main/packages/ui/src/transcript-projection.ts)** – Implements the UI projection that transforms the ledger into rendered transcripts.

## Summary

- **Immutable Ledger**: The Runtime Event Log in Apache Maka serves as the single source of truth for all execution facts.
- **Deterministic Projections**: System state at any time *t* is computed as `Project(RuntimeEvents[0..t], policy, config)`, enabling reproducible reconstruction.
- **Multiple Policies**: The same log feeds diverse projections including model-history, UI transcripts, terminal run states, and recovery views.
- **Orchestrated Durability**: Events are persisted in `AgentRun` before consumption, ensuring crash recovery via log replay.
- **Context Efficiency**: Compaction policies project trimmed log subsets that respect provider token limits while preserving execution semantics.

## Frequently Asked Questions

### What makes the Runtime Event Log immutable in Apache Maka?

Immutability is enforced by the write path in [`packages/runtime/src/agent-run.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/agent-run.ts), which appends each `RuntimeEvent` to a persistent ledger before exposing the corresponding `SessionEvent` to any consumer. Once written, events are never updated or deleted, allowing projections to treat the log as an immutable history.

### How does Maka recover system state after a crash?

Recovery uses the durable portion of the Runtime Event Log. The restart logic reads the ledger and rebuilds the `AgentRun` envelope by re-executing the projection functions over the stored events. Because state is a pure function of the log, the system reconstructs the exact pre-crash state without external checkpoint files.

### What is the difference between a SessionEvent and a RuntimeEvent?

`SessionEvent` represents the backend stream payload, while `RuntimeEvent` is the canonical, normalized form stored in the ledger. The [`session-event-runtime-mapper.ts`](https://github.com/apache/maka/blob/main/session-event-runtime-mapper.ts) module performs the transformation, ensuring that internal projections consume a consistent schema regardless of backend protocol changes.

### How does context compaction preserve semantics when trimming the log?

The `ContextBudget` policy implements a semantic projection that selects a subset of `RuntimeEvent`s satisfying provider token limits. Rather than arbitrary truncation, this projection applies rules that preserve dependency chains—such as keeping tool results linked to their calls—ensuring the model-history remains coherent even when shortened.