# How Magnitude Uses event-core for Its Event-Sourced Architecture

> Magnitude leverages event-core for its event-sourced architecture, enabling immutable logs, deterministic projections, and replay for robust state management. Discover how it works.

- Repository: [Magnitude/magnitude](https://github.com/magnitudedev/magnitude)
- Tags: architecture
- Published: 2026-09-06

---

**Magnitude implements event sourcing through the `event-core` package, which provides immutable event logs, deterministic projections, and replay capabilities that power the entire system's state management.**

The `magnitudedev/magnitude` repository builds its state architecture on a foundation where every change is captured as an immutable event. Rather than mutating state directly, Magnitude appends events to a log and derives current state through pure functional projections. This pattern enables debugging, auditability, and time-travel queries across CLI and web interfaces.

## Core Components of the event-core Package

The `event-core` package in `packages/event-core/src/` defines four essential abstractions that the rest of Magnitude consumes.

### EventLog: The Immutable Append-Only Store

The **`EventLog`** interface in [`packages/event-core/src/EventLog.ts`](https://github.com/magnitudedev/magnitude/blob/main/packages/event-core/src/EventLog.ts) provides the lowest-level primitive: an append-only sequence of events. Each event carries a type identifier, payload, and timestamp. The implementation guarantees that events are never modified or deleted—only appended.

```typescript
// Example event structure
{
  type: "UserCommand",
  payload: { command: "list-tasks", args: [] },
  timestamp: "2024-01-15T10:30:00Z"
}

```

### SessionEventLog: Per-Session Isolation

The **`SessionEventLog`** in [`packages/event-core/src/SessionEventLog.ts`](https://github.com/magnitudedev/magnitude/blob/main/packages/event-core/src/SessionEventLog.ts) wraps the global `EventLog` to provide isolated views for individual user sessions. When a CLI session starts or a web connection opens, Magnitude instantiates a session-scoped log via `SessionEventLog.make()`.

This design allows concurrent users to operate without cross-session data leakage while sharing the same underlying storage infrastructure. The session log is the primary interface that domain packages interact with.

### Projection: Pure State Folds

**Projections** in [`packages/event-core/src/Projection.ts`](https://github.com/magnitudedev/magnitude/blob/main/packages/event-core/src/Projection.ts) are deterministic functions that reduce a stream of events into a specific state shape. Magnitude uses projections to build queryable views like window state, task graphs, and user profiles.

A projection defines:
- `init`: The initial state value
- `fold`: A pure function `(state, event) => newState`

Because projections are pure, the same event stream always produces identical state—enabling reliable caching and debugging.

### Replay: Time-Travel and Recovery

The **`Replay`** module in [`packages/event-Core/src/Replay.ts`](https://github.com/magnitudedev/magnitude/blob/main/packages/event-Core/src/Replay.ts) provides utilities to reconstruct any projection at any point in the event stream. Methods like `Replay.at(log, index, projection)` return the projection state as-of a specific event index.

This powers Magnitude's `bun session` CLI tooling for debugging and audit scenarios.

## How Magnitude Packages Consume event-core

The repository's other packages integrate `event-core` through a consistent pattern: subscribe to session logs, maintain projections, and expose state through Effect-TS services.

### Session Initialization

When Magnitude boots a CLI or web session, the bootstrap code creates a `SessionEventLog`:

```typescript
import * as SessionLog from '@magnitudedev/event-core/SessionLog';

const sessionLog = SessionLog.make({ sessionId: "sess-1234" });

```

All subsequent operations—RPC calls, agent actions, UI updates—append events to this log rather than mutating shared mutable state.

### Domain-Specific Projections

Packages like `agent`, `client-common`, and `acn` define their own projections in files such as [`packages/agent/src/ProjectionDefinitions.ts`](https://github.com/magnitudedev/magnitude/blob/main/packages/agent/src/ProjectionDefinitions.ts). Common projection types include:

- **`Window`**: Tracks the visible message window
- **`TaskGraph`**: Maintains the current task decomposition
- **`Turn`**: Records conversation turns
- **`Display`**: Manages UI rendering state

Each projection subscribes to the session log and caches its computed state for fast access.

### Effect-TS Service Integration

Magnitude exposes all projections as **Effect-TS services** using `Context.Tag`. This allows the dependency injection system to wire projections into query layers without additional RPC overhead.

```typescript
import * as T from "effect";
import * as SessionLog from "@magnitudedev/event-core/SessionLog";

export const SessionLogTag = T.Tag<SessionLog.Service>();

export const makeSessionLog = T.effect((env) =>
  SessionLogTag.of(SessionLog.make({ sessionId: env.sessionId }))
);

```

Downstream modules access the log through:

```typescript
const log = T.serviceWith(SessionLogTag, (svc) => svc);

```

The [`packages/client-common/src/operations/SyncState.ts`](https://github.com/magnitudedev/magnitude/blob/main/packages/client-common/src/operations/SyncState.ts) file demonstrates how client code queries these projections without triggering network requests—it simply reads from the locally cached projection state.

### Persistence and Recovery

The `daemon-management` layer handles SQLite persistence of raw event logs. On process restart, `event-core` replays the persisted log through all registered projections, restoring exact pre-shutdown state.

This replay process uses the deterministic guarantee: because projections are pure folds, replaying the same events always reconstructs identical state.

## Guarantees Provided by event-core

The `event-core` architecture enforces several critical properties across Magnitude:

- **Immutability**: Events are append-only; no mutation or deletion paths exist
- **Deterministic replay**: Pure projections yield identical state for identical event streams
- **Point-in-time queries**: `Replay.at()` enables debugging and audit scenarios
- **Session isolation**: `SessionEventLog` prevents cross-session data leakage

The design document at [`design/storage/session-event-log.md`](https://github.com/magnitudedev/magnitude/blob/main/design/storage/session-event-log.md) formalizes additional contracts including `replaySafe` and `atMostOnce` delivery guarantees, plus event versioning policies that maintain compatibility as the system evolves.

## Code Examples

### Appending Events and Building Projections

```typescript
// Append a user command event
await sessionLog.append({
  type: "UserCommand",
  payload: { command: "list-tasks", args: [] },
  timestamp: new Date(),
});

// Define a task list projection
import * as Projection from '@magnitudedev/event-core/Projection';

type TaskList = { tasks: string[] };

const taskListProjection = Projection.make<TaskList>({
  init: { tasks: [] },
  fold: (state, ev) => {
    if (ev.type === "TaskCreated") {
      return { tasks: [...state.tasks, ev.payload.id] };
    }
    return state;
  },
});

// Subscribe and query
sessionLog.subscribe(taskListProjection);
const currentTasks = taskListProjection.current; // { tasks: [...] }

```

### Point-in-Time Replay for Debugging

```typescript
import * as Replay from '@magnitudedev/event-core/Replay';
import * as SessionLog from '@magnitudedev/event-core/SessionLog';

const persistedLog = await SessionLog.loadFromFile("sessions/sess-1234.log");

// Reconstruct Window state at event 42
const windowAt42 = Replay.at(persistedLog, 42, WindowProjection);
console.log(windowAt42);

```

## Summary

- **`event-core` provides the foundational abstractions**—`EventLog`, `SessionEventLog`, `Projection`, and `Replay`—that enable Magnitude's event-sourced architecture
- **State is derived, not mutated**: All changes flow through immutable event logs into pure projections
- **Effect-TS integration** exposes projections as services, eliminating RPC overhead for state queries
- **Persistence and recovery** rely on deterministic replay to restore exact system state after restarts
- **Session isolation** ensures multi-user safety without sacrificing shared storage efficiency

## Frequently Asked Questions

### What is event sourcing in Magnitude's architecture?

Event sourcing means that Magnitude stores every state change as an immutable event in a log rather than updating a mutable database record. Current state is always computed by replaying events through pure projection functions. This approach enables complete audit trails, debugging via time-travel, and reliable recovery from crashes.

### How does SessionEventLog differ from the base EventLog?

`SessionEventLog` provides a filtered, isolated view of the global `EventLog` scoped to a single user session. While the underlying storage may be shared, each session sees only its own events. This prevents data leakage between concurrent users while maintaining the performance benefits of unified storage management in the `daemon-management` layer.

### Why does Magnitude use Effect-TS with event-core?

Effect-TS provides a typed, composable effect system that integrates naturally with `event-core`'s functional design. By exposing projections as `Context.Tag` services, Magnitude achieves dependency injection without runtime overhead—queries against projections occur in-process without network round-trips, as implemented in [`packages/client-common/src/operations/SyncState.ts`](https://github.com/magnitudedev/magnitude/blob/main/packages/client-common/src/operations/SyncState.ts).

### Can projections be rebuilt for historical debugging?

Yes. The `Replay` module in [`packages/event-core/src/Replay.ts`](https://github.com/magnitudedev/magnitude/blob/main/packages/event-core/src/Replay.ts) provides `Replay.at()` to reconstruct any projection at any historical point. This powers the `bun session` CLI tooling and enables developers to inspect exact system state at the moment of bugs or unexpected behavior.