Skip to content
Source on GitHub (opens in a new tab)
import "github.com/barevoidco/zelk/core/store"

Package store defines the LogStore port: where session logs and their outputs are kept.

A session is an append-only log of events. Appends are atomic batches, guarded by optimistic concurrency (the caller states the sequence number it expects the log to end at) and by lease fencing (a holder that has lost the session’s lease can’t write). Hosts bring their own store or use one of zelk’s: store/mem for tests and ephemeral sessions, store/file for local durable sessions. Every implementation runs the conformance kit in store/storetest.

Inbox keeps observer occurrences outside the session log without requiring a lease. Pending durably seals payloads before returning them for admission; Trim follows log acknowledgment. Both bounds and immutability are enforced.

const MaxBatchBytes = 8 << 20

MaxBatchBytes is the largest batch every LogStore must accept, counted as the total size of its events encoded with event.Encode. Writers split what they record into batches of at most this size; a store may accept more.

const MaxSessionIDLen = event.MaxSessionIDLen

MaxSessionIDLen is the longest session ID, in bytes.

const VersionMediaType = "application/octet-stream"

VersionMediaType is the media type of every checkpoint version’s reference: a version is a file’s bytes, whatever the file holds.

var (
// ErrCorrupt reports damaged log or blob contents that cannot be read.
// Logs written by another event version report event.ErrUnsupportedVersion instead.
ErrCorrupt = errors.New("corrupt log or blob")
// ErrDeleted reports an attempt to continue a tombstoned session.
ErrDeleted = event.ErrSessionDeleted
// ErrConflict is returned by Append when the log doesn't end at the
// expected sequence number: another append got there first, or the
// caller's view of the log is out of date.
ErrConflict = errors.New("log does not end at the expected sequence number")
// ErrFenced is returned by Append when the lease token is stale: a
// newer holder has written the session, or the token is for another
// session.
ErrFenced = errors.New("lease token is stale")
// ErrAmbiguous marks an Append error after which the store can't tell
// whether the batch was written, for example a database commit that
// timed out. Only stores whose reads stay authoritative after such a
// failure may return it. The caller then reads the log from
// expectSeq+1 and compares what it finds with the batch: the same
// events mean the append landed, none mean it didn't, anything else is
// a conflict (docs/design/durability.md).
ErrAmbiguous = errors.New("append outcome unknown")
// ErrNotFound is returned by BlobStore.Get for a blob it doesn't have.
ErrNotFound = errors.New("blob not found")
)
var ErrInboxEnded = errors.New("source inbox has ended")

ErrInboxEnded reports an append after a terminal occurrence was recorded. The terminal marker survives trimming, so observation cannot resume by accident.

var ErrInboxFull = errors.New("inbox is full of exposed occurrences")

ErrInboxFull reports a bound that cannot be met without changing an exposed occurrence. Trim acknowledged occurrences before appending again.

func EncodeBatch(session string, expectSeq uint64, token lease.Token, evs []event.Event) ([][]byte, error)

EncodeBatch performs the checks every Append makes before touching storage, and encodes the events with event.Encode: the batch is not empty, token is for the session, and evs are numbered expectSeq+1, expectSeq+2 and so on. Running it first means a bad batch leaves no trace. It doesn’t check the log’s current end or the token’s fence, which need the store’s state.

func SortSessions(infos []SessionInfo)

SortSessions orders infos as Catalog.Sessions yields them: most recently updated first, then by ID.

func ValidateSessionID(id string) error

ValidateSessionID reports whether id is a session ID every store accepts: 1 to MaxSessionIDLen bytes of valid UTF-8 without control characters, so it prints safely in logs and errors. IDs are compared exactly; a store that maps them to names on a case-insensitive medium must keep IDs that differ only in case apart.

type BlobStore interface {
// Put stores data, durably, among the session's outputs and returns
// its reference. Putting the same content again is harmless and
// returns the same reference.
Put(ctx context.Context, session string, data []byte, mediaType string) (blob.Ref, error)
// Get returns the session's output whose digest is ref.Digest, checked
// against it, or ErrNotFound. The digest alone finds it; the ref's
// size and media type, which describe the content, aren't needed. A
// malformed digest is an error, not ErrNotFound.
Get(ctx context.Context, session string, ref blob.Ref) ([]byte, error)
// Copy gives session to, durably, every output session from holds. A
// fork copies its source's outputs so it can read them after the
// source is gone. Copying from a session with no outputs succeeds.
Copy(ctx context.Context, from, to string) error
}

BlobStore keeps each session’s outputs: content too large for its log, such as long command output, fetched pages and the files of skills it loaded (docs/design/retention.md). Outputs are content-addressed within a session and owned by it alone: one session never reads another’s, and removing a session removes its outputs. Implementations must be safe for concurrent use.

type Catalog interface {
// Sessions yields every session whose log holds an event, most
// recently updated first. A log never written, such as one Adopt
// prepared for a session that was then never started, isn't listed. A
// session whose log can't be read is yielded with its ID and the
// error, and optionally a trustworthy Updated storage modification
// time (zero if unknown), and the listing goes on; any other failure ends it.
Sessions(ctx context.Context) iter.Seq2[SessionInfo, error]
}

Catalog lists the sessions a store holds. A LogStore may implement it; a host asserts for it.

type FileHistory interface {
// PutVersion stores data, durably, in the session's history and
// returns its reference. Putting the same content again is harmless.
PutVersion(ctx context.Context, session string, data []byte) (blob.Ref, error)
// GetVersion returns the session's version whose digest is ref.Digest,
// checked against it, or ErrNotFound.
GetVersion(ctx context.Context, session string, ref blob.Ref) ([]byte, error)
// PruneVersions removes the session's versions whose digests keep
// rejects.
PruneVersions(ctx context.Context, session string, keep func(digest string) bool) error
// DropHistory removes every version of the session. Dropping a
// history that holds nothing succeeds.
DropHistory(ctx context.Context, session string) error
}

FileHistory keeps each session’s checkpoint versions: the old contents of files the session’s tools changed (docs/design/checkpoints.md). Versions are content-addressed within a session and owned by it alone, so dropping one session’s history never touches another’s. A LogStore may implement it; a host asserts for it. Implementations must be safe for concurrent use. The session’s lease holder is the only writer.

type Inbox interface {
// Head returns the last assigned number, including trimmed occurrences.
// It performs no mutation or sealing; zero means nothing was appended.
Head(ctx context.Context, session, source string) (uint64, error)
// Append assigns one more than the last successful append's number. At a
// bound it folds unexposed suffix entries into the newest payload, retaining
// the newest text and accumulating folded/missed counts. It never changes
// exposed entries. The caller retains ownership of its input.
Append(ctx context.Context, session, source string, occurrence Occurrence) error
// Pending returns occurrences numbered after after, in order. It seals them
// durably before returning an independent snapshot, even across reopen.
Pending(ctx context.Context, session, source string, after uint64) ([]Occurrence, error)
// Trim removes sealed occurrences through an acknowledged number. It is
// idempotent and retains numbering; an unexposed/future cursor is refused.
Trim(ctx context.Context, session, source string, through uint64) error
}

Inbox keeps bounded per-source occurrences outside the session log. It is safe for concurrent use, including observers without the session lease. Pending durably seals everything it returns: admission retries see identical payloads until Trim. At most 64 occurrences and 256 KiB of text are pending per source. A full exposed queue reports ErrInboxFull instead of changing a possibly admitted payload. Observers must retain a refused append themselves.

type InboxStore interface {
// Inbox returns the store-backed observer inbox.
Inbox() Inbox
}

InboxStore is the optional inbox capability of a LogStore. Inbox uses a separate receiver because LogStore already has an Append method.

type LogStore interface {
// Append atomically adds evs to the session's log: either all of them
// are stored or none are, and readers never see part of a batch. The
// log must currently end at expectSeq (0 for an empty log) and evs must
// be numbered expectSeq+1, expectSeq+2 and so on; otherwise Append
// returns ErrConflict or an error describing the bad numbering. Append
// returns nil only once the batch is durable, as far as the store
// promises durability. A batch of up to MaxBatchBytes must be
// accepted. The store doesn't keep evs; the caller may
// change them afterwards.
//
// Fencing: the caller must hold the session's lease, and token is its
// proof. A store refuses, with ErrFenced, a token for another session
// and a token older than the newest one it has accepted for the
// session while open; whether it remembers fences across restarts is
// up to the store. Keeping two processes from writing one session at
// once is the lease's job, and a store may add its own guard: the file
// store's writer lock.
Append(ctx context.Context, session string, expectSeq uint64, token lease.Token, evs ...event.Event) error
// Adopt prepares the log for a new lease holder (docs/design/durability.md,
// L11): it makes everything the log holds durable, records token's
// fence as Append does (refusing an older one with ErrFenced), and
// returns the sequence number of the log's last event, 0 for a
// session never written. A driver adopts a log before folding it and
// folds only up to the returned sequence number, so it never decides
// anything from a batch another writer wrote but never made durable.
Adopt(ctx context.Context, session string, token lease.Token) (uint64, error)
// Read yields the session's events with sequence numbers from fromSeq
// on, in order. A session that was never written yields nothing. If
// reading fails, Read yields the error and stops. The caller owns the
// events it is given and may stop iterating at any time.
Read(ctx context.Context, session string, fromSeq uint64) iter.Seq2[event.Event, error]
// Blobs returns the store of the sessions' outputs: content too large
// for their logs.
Blobs() BlobStore
}

LogStore keeps session logs and their blobs. Implementations must be safe for concurrent use.

type Occurrence struct {
// Number is assigned by Append and survives Trim.
Number uint64 `json:"number"`
// Payload contains the fixed text and folded/missed counts.
Payload event.OccurrencePayload `json:"payload"`
}

Occurrence is an observer’s fixed payload and its store-assigned number. Append requires Number and Payload.Folded to be zero. Folding replaces only unexposed occurrences with a new numbered payload counting the replacements.

type Remover interface {
// RemoveSession removes everything the session holds: its outputs,
// its inbox, its file history and, last, its log with the store's bookkeeping for
// it. So a removal cut short leaves a log for the next attempt to
// find. token is the caller's lease token for the session; one older
// than the newest the store has accepted for it is refused with
// ErrFenced. Removing a session that holds nothing succeeds.
// Removal must not require decoding the log: unreadable sessions can
// be removed under the same fencing rules. Afterwards the ID is unused,
// as if never written.
RemoveSession(ctx context.Context, session string, token lease.Token) error
// Leftovers yields the IDs of sessions that hold outputs or file
// history or inbox storage but no log, such as what a fork cut short by a crash left.
Leftovers(ctx context.Context) iter.Seq2[string, error]
}

Remover removes whole sessions (docs/design/retention.md). A LogStore may implement it; a host asserts for it. Implementations must be safe for concurrent use.

type SessionInfo struct {
ID string
// Created and Updated are the times of the log's first and last
// events. For an unreadable log, Updated may instead be a trustworthy
// last storage modification time (the file store uses the log's mtime).
// It must be zero if unknown; a partially decoded event time is not
// sufficient to expire an unreadable log.
Created time.Time
Updated time.Time
// Seq is the sequence number of the log's last event.
Seq uint64
// Title is the session's name, from its last SetTitle command; empty
// if it has none.
Title string
// Tags are sorted session labels; Deleted marks a durable tombstone.
Tags []string
Deleted bool
// Workspace is the session configuration's workspace root, as its
// latest configuration and committed workspace move record it.
Workspace string
// MovingTo is the root of a workspace move the session has prepared
// and not yet handed off, or "" (docs/design/transitions.md). Where
// the session continues is MovingTo if set, else Workspace.
MovingTo string
// ForkedFrom is the session this one was forked from, if it was.
ForkedFrom string
// AgentType is the subagent type of a subagent's session, "" for a
// conversation, which a host offers to resume.
AgentType string
// Sources says the session has created a wake source, which may be
// live: a host dispatching wakes reads only these sessions' logs
// (docs/design/wakes.md, Who dispatches). Ending a source doesn't clear it.
Sources bool
}

SessionInfo describes a stored session, for a session picker.

func List(ctx context.Context, c Catalog) (infos []SessionInfo, unreadable int, err error)

List collects the sessions c lists that can be read, in its order, and counts those whose log can’t be, such as logs another version of zelk wrote: one of those doesn’t keep a host from offering the rest. A failure of the listing itself is returned.

func Summarize(ctx context.Context, logs LogStore, prev SessionInfo) (SessionInfo, error)

Summarize brings prev, a summary of session prev.ID up to event prev.Seq, up to the log’s end by reading only the events after it; a zero prev with an ID reads the whole log. Stores implement Catalog with it, caching what it returns.