Schritt 3 von 13 - Etwa 40 Min.
Lab 02 - Durable sessions
Time: about 40 minutes. You will: store every conversation in an append-only event log, so the assistant remembers you after a restart and recovers cleanly from a crash.
Why
After lab 01, Steward can use tools, but quitting the chat erases everything. Saving the message list to a file looks like the fix. It is half of one. A real assistant also has to answer:
- What if the process dies in the middle of a turn, after the model asked for a tool but before the tool ran?
- What if it dies in the middle of writing a line?
- Which turn crashed, why, and what did this conversation cost?
- How do you start a fresh conversation without losing the old one?
Concepts
Log events, not just messages
Each session is a JSON Lines file. Every line is one typed event:
{"v":1,"ts":"...","type":"session_started","sessionId":"20261122-101500-ab12","key":"steward:main"}
{"v":1,"ts":"...","type":"turn_started","turnId":"turn-0001","channel":"terminal"}
{"v":1,"ts":"...","type":"message","turnId":"turn-0001","message":{"role":"user","content":"..."}}
{"v":1,"ts":"...","type":"message","turnId":"turn-0001","message":{"role":"assistant","content":[...]}}
{"v":1,"ts":"...","type":"turn_completed","turnId":"turn-0001","stop":"end_turn","model":"...","usage":{...}}Messages are only one event type. Turn boundaries tell a finished turn from an interrupted one,
and usage is recorded per turn. The message list sent to the model is rebuilt from the log
every time a session opens. The API keeps no conversation for you: each request sends the whole
messages list (Using the Messages API), so this
log is the only copy.
Append-only, for two reasons
- Crash safety. A crash can only damage the line being written. Earlier lines are never touched, so they cannot be corrupted by a later write.
- The model requires it. Current Claude models check that earlier turns are sent back unchanged (thinking blocks are tied to the exact conversation that produced them). Rewriting history, even to "clean it up", breaks that check. So the log never edits; it only adds.
Each append is flushed to disk before it returns (fdatasync in src/sessions/event-log.ts), so
an event reported as written survives kill -9 or a power cut.
Recovery without deleting anything
When a session opens, it repairs what a crash may have left:
| Found on open | Repair (all appends) |
|---|---|
| Last line has no newline (a torn write) | End the line; the reader skips it and reports it |
A turn started, with no turn_completed or turn_interrupted |
Append turn_interrupted |
That turn has a tool_use with no tool_result |
Append an error tool_result first ("did not run") |
| A user message that never got an answer | Nothing to append; it merges with the next user message |
The error tool_result matters: the API rejects a conversation in which a tool_use has no
matching tool_result in the next user message
(Handle tool calls). The merge in the last row
happens when the message list is built (src/core/messages.ts), the same way every time, so the
bytes sent to the model are stable.
Session keys and session ids
A key names a conversation slot: steward:main is "all my direct messages". An id names
one log file. /new keeps the key and starts a new id; the old file stays on disk as it was.
sessions/index.json maps keys to ids and is replaced atomically (write a temp file, then rename),
so a crash leaves either the old index or the new one, never half of each.
Build
src/sessions/events.ts- the event types, validated with Zod when read.src/sessions/event-log.ts-append(open, write,datasync, close),read(skips and reports bad lines), andsealTornTail.src/core/messages.ts-mergeConsecutiveUserMessages, used both when the log is rebuilt and inside the turn loop, so both send the same bytes.src/sessions/session.ts-Session.openruns recovery;messages()rebuilds the conversation;interruptTurncloses open tool calls and ends a turn.src/sessions/session-store.ts- keys, ids, the index,open,rotate,list.src/core/assistant.ts- wires a session to the turn loop. Every message is written the moment it exists. Simplified fromreply(),runAndRecord(), andguard():
const turnId = await session.startTurn(options.channel);
try {
const result = await runTurn({
...this.deps,
history: session.messages(),
userMessage: { role: 'user', content: text },
onMessage: (message) => session.addMessage(turnId, message), // written immediately
});
await session.completeTurn(turnId, { stop: result.stop, model, usage: result.usage });
return result;
} catch (err) {
await session.interruptTurn(turnId, reason); // closes open tool calls, then ends the turn
throw err;
}Run
pnpm steward chatyou> My exam is CCA-F on 2027-01-15, and my weakest domain is context management.
you> /quitStart it again and ask What is my weakest domain?. The banner shows how many earlier messages
were loaded. Then look at the log:
pnpm steward sessions
pnpm steward showBreak it
Cancel mid-turn. Ask something long and press Ctrl+C while it answers. The process is still alive, so it closes the turn itself:
pnpm steward showlists aturn_interruptedevent with the reasoncancelled by the owner.Crash mid-turn. Ask something that needs a tool (
How many days until my exam?) and, while it answers, kill the process from another terminal so it gets no chance to clean up:pkill -9 -f "src/cli.ts chat"Start
pnpm steward chatagain: the banner reportsRecovery: turn-000N was interrupted last time, andpnpm steward showlists the appendedturn_interruptedevent (plus an errortool_resultif a tool call was open when it died).Torn write. Append half a line to the session file by hand, then start the chat:
printf '{"v":1,"ts":"2026-' >> ~/.steward/sessions/<session-id>.jsonl pnpm steward chatThe banner reports
closed a torn last line in the log; 1 unreadable line(s) skipped, and the conversation continues.
Check
pnpm lab 02The checkpoint proves: a new process sees the old conversation; earlier bytes of the log never
change (the old file is an exact prefix of the new one); a crash with an open tool call is
repaired once and only once; a torn line is sealed and skipped; an unanswered user message merges
with the next; /new keeps the old log; usage adds up across turns; sessions opened in parallel
keep every index entry; peek reads without writing; channels map to keys by scope; an unknown
event is reported, not dropped silently; and the real steward chat reads every piped line and
releases its lock when the input ends.
Exercises
- Add a
steward replaycommand that prints only the conversation (user and assistant text) of a session, for review before an exam. - Add
--scope per-channeltochatand usesessionKey()to give each channel its own conversation. Which scope suits a study coach better, and why? - Two processes appending to one log would interleave their turns. Start
steward chatin two terminals: the second refuses to start, because one process owns the data folder (the lock from lab 12). Then read how lab 08's per-session queue keeps turns in order inside one process.
Claude API docs
- Using the Messages API - the request carries the whole conversation, every time.
- Handle tool calls - why every
tool_useneeds atool_result, even after a crash. - Context windows - the rebuilt message list is what fills the window.
- Effective context engineering - state an agent keeps outside the model.
Exam connection
CCA-F - Context Management & Reliability. Session state, recovery from partial failures, and why history must be preserved exactly are reliability questions the exam asks in many forms. Practice this domain on CertLabPro, or on the go with the CertLabPro app.
Previous: Lab 01 - Next: Lab 03 - Context assembly and caching