Apache Maka Session and Turn Lifecycle: A Complete Guide
Apache Maka models every interaction as a Session containing ordered Turns, with deterministic persistence through SQLite-backed SessionTodo documents and a Session Turn Protocol that guarantees consistent read-only views and safe hand-off between the Runtime Host and clients.
Apache Maka orchestrates AI interactions through a rigorous lifecycle architecture where every conversation exists as a Session with an immutable history of Turns. The design separates authority between the Runtime Host—which owns all state mutations—and read-only clients like the Desktop UI. Understanding these lifecycles is essential for developers building extensions or debugging conversation flows in apache/maka.
Session Lifecycle in Apache Maka
The session lifecycle governs how SessionTodo documents are created, persisted, branched, and destroyed while maintaining ACID guarantees through SQLite storage.
Session Creation and Persistence
When the Runtime Host instantiates a new session, it immediately persists an empty SessionTodo document—the canonical current-state object—in SQLite. The first read operation (todo_read or session.todo.query) returns this empty list without triggering a write. Subsequent modifications replace the entire document atomically via todo_write, ensuring that read-only clients receive immutable snapshots that never change mid-render.
Session Copy and Branch Operations
Copying sessions—whether through branches, historic cuts, or side-conversations—initializes the target session's SessionTodo before the session is published. According to docs/session-todo-lifecycle.md:
- Ordinary branches copy the source's current todo list
- Historic cuts create an empty todo document to start fresh
Both operations execute within single SQLite transactions to maintain idempotency and prevent partial state corruption.
Archiving, Removal, and Backup
Archiving preserves the SessionTodo document unchanged for future reference, while session deletion purges the todo document entirely to prevent stale work from resurfacing. Backup and restore operations preserve both non-empty and empty-initialized documents. Restoring a pre-upgrade backup discards any edits made after the backup; live rollback is unsupported.
Turn Lifecycle and the Session Turn Protocol
Individual interactions follow the Session Turn Protocol defined in packages/runtime-host/src/protocol/session-turns.ts, expressing each user prompt and model response as a Turn with distinct lifecycle phases.
Contribution Gathering and Merging
The Runtime Host aggregates per-turn contributions—including message status, prompt previews, tool results, and abort notes—into SessionTurnContribution objects. When multiple contributions arrive for the same turn, the host calls mergeSessionTurnContributions to combine them with latest-state-wins semantics. This merging ensures deterministic resolution of race conditions before projection.
Projection and Status Inference
Contributions undergo projection for two purposes:
- Wire transmission via
projectSessionTurnContributionForWire - Internal record construction via
projectSessionTurnContributionforTurnRecordobjects
Status inference operates automatically when no explicit turn_state message exists. The system derives the turn status from four boolean flags: hasAssistantMessage, hasToolResult, hasFailedToolResult, and hasAbortNote.
Querying Turns and Landmarks
Clients request turn slices through session.turns.query, with input decoded by decodeSessionTurnsQueryInput and results validated by decodeSessionTurnsQueryResult. Optional turn landmarks—key points within conversations for quick navigation—are accessible via session.turn_landmarks.query. Both operations are specified in SESSION_TURNS_OPERATION_SPECS within the turn protocol file.
Implementation Details and Key Files
The lifecycle implementation spans multiple packages in the apache/maka repository:
packages/runtime-host/src/protocol/session-turns.ts— Core protocol definitions, validation schemas, encoding/decoding functions, and operation specificationsdocs/session-todo-lifecycle.md— Canonical documentation for SessionTodo state machine behaviorpackages/storage/src/session-todo-store.ts— SQLite persistence layer for todo documentspackages/runtime-host/src/server/session-todo-coordinator.ts— Host-side coordination logic between storage and protocol layerspackages/runtime/src/session-turn-tools.ts— Model-facing utilities for turn manipulation
Practical Examples
// SessionTodo: read & write operations
import { todo_read, todo_write } from '@maka/runtime';
// Read the current todo list (read-only UI)
const todo = await todo_read({ sessionId: 'my-session' });
// Replace the whole todo list atomically
await todo_write({
sessionId: 'my-session',
todos: [
{ content: 'review design', status: 'pending' },
{ content: 'run tests', status: 'in_progress' },
],
});
// Turn query example
import { sessionTurnsQuery } from '@maka/runtime';
// Request the first 20 turn contributions
const result = await sessionTurnsQuery({
sessionId: 'my-session',
throughSequence: null,
position: 0,
maxContributions: 20,
});
for (const contrib of result.contributions) {
console.log(`Turn ${contrib.turnId} – status: ${contrib.latestState?.message.status ?? 'unknown'}`);
}
// Merging contributions (internal host operation)
import { mergeSessionTurnContributions } from '@maka/runtime-host';
// Merge partial contributions for the same turn
const merged = mergeSessionTurnContributions(contribA, contribB);
// Result reflects latest state and aggregated flags
Summary
- Durability — All state persists in SQLite and survives host crashes through atomic
SessionTododocuments - Determinism — Reads return immutable snapshots;
todo_writereplaces entire documents atomically to prevent mid-render changes - Consistency — The Runtime Host serves as the sole authority, broadcasting invalidation signals to read-only clients rather than sharing mutable state
- Isolation — Turn-level contributions merge safely via
mergeSessionTurnContributions, with late-arriving data after navigation rejected at the protocol level
Frequently Asked Questions
What is the difference between a Session and a Turn in Apache Maka?
A Session is a conversation container with a persisted SessionTodo document representing the current work state, while a Turn represents a single user prompt and model response cycle tracked through the Session Turn Protocol. Sessions manage long-lived persistence; Turns manage granular interaction history.
How does Apache Maka handle concurrent modifications to turn contributions?
The Runtime Host resolves conflicts using mergeSessionTurnContributions with latest-state-wins semantics. This function aggregates flags and statuses deterministically within a single SQLite transaction, ensuring that race conditions between tool results, abort signals, and assistant messages never corrupt the final turn state.
What happens to SessionTodo documents when a session is branched?
Ordinary branches copy the source session's current todo list into the new session, while historic cuts initialize an empty todo document. Both operations occur in atomic SQLite transactions as specified in docs/session-todo-lifecycle.md, guaranteeing that branching is idempotent even if retried after partial failure.
Why is the Runtime Host the sole authority for session state?
Centralizing authority in the Runtime Host eliminates distributed state conflicts between the CLI, Desktop UI, and background processes. Clients remain read-only, receiving invalidation signals after each commit rather than holding local state, which ensures that all users see consistent snapshots even during rapid sequential modifications.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →