docs/pkg/service/session.md
pkg/service/session durable storage
This package owns SQLite-backed roots, leaves, turns, content/attachments,
leaf metadata, history/context projections, cleanup, and vacuum. Daemon routing
belongs to service; model execution to
service/agent.
Layout and model
The daemon opens StateDir()/ez-agent.db, enables WAL and foreign keys, runs
migrations, and manages adjacent blobs/. Schema v2 contains the v1 tables
roots, leaves, turns, turn_content, and leaf_config, plus the sparse
proprietary_thinking_data extension described below. Existing v1 databases
migrate on open; new databases run both migrations. Unsupported newer versions
and inconsistent v2 shapes are rejected. The schema is owned by
migration.go; storage operations by
storage.go; projections by tree.go; hydration by hydrate.go.
After migrations, every open initializes service_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL) in service_meta.go.
This is startup initialization, not a migration: PRAGMA user_version stays
2, and the internal table is not client properties, configuration or credentials.
Its node_id row identifies this service database: a missing row gets n_
plus twelve lowercase hexadecimal digits in one transaction, with contending
initializers retrying within five seconds. Malformed stored values or other
failures fail startup rather than replacing the identity. Storage.NodeID()
returns it. It is a lookup identity, not authentication, and is distinct from
the installation host_id. Ready service hello_ack replies and inner
external-provider hello frames expose the same stored identity; consumers
may ignore it, and older peers can omit it.
A leaf tip selects one reachable parent chain. Appending advances the tip;
forking requires a sent source in the same root. Shared sent ancestors survive
sibling rollback. Turn states and content kinds are admitted by protocol and
orchestration, not a closed enum inferred from storage constants. Agent-run
terminal classification belongs to service/agent; storage persists
it as ordinary turn metadata.
The leaf_files leaf-config key is excluded from new-root and fork defaults;
it remains ordinary opaque leaf config when explicitly edited afterward.
Remembered model information
Explicit model selection and execution save informational values in existing leaf config:
| Key | Value |
|---|---|
model_info_ref | The selected model reference when information was saved. |
model_info_model | The resolved provider/model or source/provider/model identity. |
model_max_context | Last-known effective maximum context in tokens, as a decimal string. Zero means unknown. |
model_access_source | Last reported authentication/access source, using the existing access_source labels. |
These are not provider configuration or admission policy. Selection and execution
save them; model discovery, leaf-stats, and snapshot reads do not write
properties, including during CLI preflight. Discovery can still publish the
cache-backed source to subscribed clients before the first message. They are available through get_leaf_config,
list_leaf_config, and list_leaves.metadata_keys
without loading an Agent or contacting a model host. They survive unload and
restart, have no expiry, and do not change leaf/root activity timestamps.
The maximum is separate from current context-token occupancy.
RememberLeafModelInfo merges partial updates under the leaf storage lock.
A missing source or unknown maximum preserves that field for the same resolved
model; an explicit unknown source replaces it. A different resolved model
starts a new record rather than borrowing the old model's values, even when the
new catalog is cold. The new identity/reference replaces the old record with
zero maximum and empty source until information becomes available. Idle source
projection uses known configuration or cached catalog data, with the saved
record as fallback. No schema or outer JSONL fields are added.
| 1 | root |
| 2 | turn A <- turn B <- turn C |
| 3 | ^ ^ |
| 4 | leaf-1 leaf-2 tip |
Rewind moves one leaf pointer to an earlier ancestor; it does not delete turns or alter another leaf's pointer.
Live runtime projection
The service keeps one physical SQLite connection at a time. Each physical
connection creates a private TEMP leaf_runtime table with leaf_id and
status. Loaded leaves have idle, running, aborting or background
rows. Admission reservations override idle/background state to running and
also create a running row for unloaded or closed leaves. Unloaded and closed
leaves without reservations have no row. This is not a persistent schema
change and does not change user_version. External audit connections do not
have this table and cannot use it to observe live service state.
State transitions enqueue reconciliation without doing SQLite work under the
Agent mutex. One worker locks before capturing the full current service view,
then replaces the table in one transaction under that update lock. A transition
during reconciliation queues another pass. Status capture recomputes admission
and background overrides rather than applying event deltas. Read queries do
not take the update lock, wait for queued reconciliation, or rebuild the table.
They can observe the previous committed snapshot while an update is pending.
list_cwd reports known reconciliation errors until a later update succeeds.
The storage connector initializes TEMP state before admitting SQL on each
physical connection, including replacements opened by database/sql. It
repopulates from the latest reconciled in-memory status map. There is no
separate reconnect loop. A newly opened service storage starts with no loaded
leaves. JSONL client reconnects do not recreate database TEMP state.
ListCwdInfos joins this maintained table with persisted roots and leaves in
one statement. Only non-temporary leaves with a canonical turn contribute to
CWD inclusion, counts and activity timestamps. Forks with inherited history
qualify; empty leaves and roots without qualifying leaves do not. ListCwds
uses the same filter. Missing filesystem paths are still included.
CWD summaries count running, aborting and background leaves as active and use
the current time while any qualifying leaf is active. Otherwise, activity is
the maximum qualifying leaf updated_at. The separate list_leaves.is_active
filter remains execution-only, selecting running and aborting leaves regardless
of temporary status or history.
ListLeavesWithRuntimeMetadata, used by list_leaves, joins the same table
and defaults missing rows to unloaded. Root/CWD filtering and requested
metadata retain their existing semantics. Ordinary storage leaf queries do not
attach projected status. The projection is for read-only presentation only.
Leaf stats retain live capture so state remains paired with queue, access source,
timing and outcome data. Transition-triggered leaf_updated notifications also
retain ordered live capture rather than publishing a possibly older projection.
Admission, deletion, eviction, abort, replacement and cleanup checks continue to
use authoritative live state.
History and context
TreeWalk projects sent model-message kinds, excludes service-owned error turns,
and stops at a virtual root. BuildContextWithTurnIDs uses the same predicate
for IDs and context. ListHistory follows one leaf through ready/sent turns;
ListTurnTree reports every physical branch in a root. The internal
BuildProviderContext additionally loads native batches by source turn ID,
without exposing them in ordinary projections.
The existing context-token statistic follows the active canonical turn chain.
An assistant's valid other_meta.provider_context_tokens is a replacement
occupancy snapshot, including zero. A later provider usage measurement can
supersede it. Without a snapshot, legacy usage and interrupted-request
estimation are unchanged. Snapshots are not inflated by the interrupted-request
estimate and do not contribute to cumulative usage.
A failure with semantic assistant output retains its snapshot on that assistant.
A failure without semantic output uses the existing error-turn translation and
does not persist a new snapshot; the prior context measurement remains in effect.
The snapshot uses the existing additional-metadata object and follows its normal
other_meta projection. No metadata keys are redacted. Error-turn projections
remain unchanged.
Attachment chunk reads
Storage.ReadAttachmentChunk selects a stored attachment by turn ID and its
zero-based position in meta_files. Filenames are not selectors, so duplicate
filenames remain distinct. The service exposes this through the requester-only
get_attachment_chunk RPC; it never broadcasts chunks to leaf subscribers.
Requests require nonempty turn_id and request_id, an attachment index and
offset of at least zero, and a length from 1 through 98,304 decoded bytes.
Responses base64-encode the requested bytes for both UTF-8 and binary files.
Offsets count bytes, not characters. The returned length is the smaller of the
requested length and the remaining bytes; size is the actual full file size.
An offset exactly at EOF succeeds with empty data and eof: true. An offset
beyond EOF reports attachment_range_error. Unknown turns report
turn_not_found; absent attachment indices report attachment_not_found.
Malformed requests report parse_error. Missing or corrupt stored blobs,
malformed metadata and size mismatches report internal_error. Legacy entries
without a size in their metadata or payload entry use the actual payload size;
a present but incorrect size is corruption.
Attachments remain zlib-compressed JSON arrays with no schema change. Chunk reads reserve the storage connection through lookup and file open, coordinating with blob cleanup, then release it before decompression or sending a response. The open descriptor preserves an in-flight read if cleanup unlinks the blob. The reader parses one JSON file entry at a time and decodes base64 through a stream, retaining only the requested decoded range. It still reads the complete compressed array to check its structure and checksum, and validates the entire selected payload. The JSON decoder still materializes encoded payload strings; this format does not provide random-access reads.
Assistant response labels
Assistant other_meta.response_labels is an optional list of friendly names,
for example ["Blue", "Future friendly label"]. It is provider-neutral display
metadata, not a request selection or a copy of a provider response. Absent, null,
and empty lists have no badges. The agent archives labels with tool_calls and
tools_available; finalization and later service-owned exit_message updates
preserve them in the existing turns.other_meta JSON column. Ordinary turn reads
and reloads expose that metadata through the existing other_meta string.
Labels do not change model identity, model context, or provider-native thinking.
Rewind compare-and-swap
Storage.RewindLeaf(leafID, currentTipTurnID, newTipTurnID) transactionally
compares and moves the tip. The expected tip must match exactly. The new tip must
be a proper ancestor in the same parent chain; "" selects the root boundary
before the first turn.
Rewind changes only the leaf tip and timestamps. It never deletes descendants or
changes sibling leaves. ErrLeafTipChanged reports stale expected tips;
ErrRewindTargetNotAncestor covers the current tip, siblings, other roots, and
unknown targets. Agent-side idle/replay admission belongs to
service/agent.
Write and reference safety
- Validate complete batches before committing rows or blobs.
- Ordinary persistence rejects unresolved content references. Trusted virtual-root insertion verifies same-root references transactionally. Explicit content wins; otherwise an empty reference reuses source storage, including attachments.
- Virtual roots are physical context boundaries, not provider messages. Generated history stays before a held draft, which remains the canonical tip/anchor.
- Pending-turn hydration validates same-root references and clears synthetic
references before use. Ingress rules belong to
turn_validation.go.
Virtual-root boundary metadata
Storage.CreateVirtualRoot(leafID, reason, pending, metadata, mutation...)
accepts metadata map[string]any after the pending turns. The JSONL request
carries an optional JSON object, not a JSON-encoded string. Storage serializes
it into the boundary turn's existing turns.other_meta column; returned
turn_content.other_meta remains a JSON-encoded string. Nil, JSON null, and
empty objects retain the default stored {}. Malformed or non-object wire
metadata is rejected, as is a supplied top-level exit_message, even if null.
Boundary metadata commits atomically with the boundary, pending turns, and
leaf-tip mutation. It is not copied onto pending turns or a held draft.
A failure leaves the prior history and tip unchanged. The new turns never
inherit native thinking. The RPC contract is in pkg/ezagentapi.
Manual and automatic builtin compaction supply
{"continuation":true,"pivot_turn_id":"..."}. The flag marks continued source
history; the pivot identifies the last source turn summarized, inclusive.
It is not the generated summary or first retained turn. The boundary's
physical parent remains the old tip, or the old sent tip before a held draft,
not the pivot. The human-readable reason is unchanged. The daemon stores
extension values without interpreting consumer semantics; it adds no version,
mode, or anchor metadata.
No virtual-root or rewind feature changes the database schema or
PRAGMA user_version.
How is provider-native thinking stored?
proprietary_thinking_data holds zero or one batch per assistant turn
(turn_id is unique and cascades on turn deletion), with an exact-row id, a
format (anthropic.thinking.v1, openai.responses.reasoning.v1 or
claude_code.thinking.v1), the ordered
payload_json, and reserved extra_fields (written as {} and ignored). The
format records what was captured, independent of provider name or model, which
remain provenance on the turn.
FinalizeAssistantTurnWithNative validates the batch (supported format, nonempty
array, usable items; errors never echo payload values) and saves it with the
assistant finalization in one transaction, replacing any earlier batch under a
fresh row ID. DeleteNativeThinking deletes exact (turn, row) pairs, so a delayed
rejection cannot remove a newer replacement. BuildProviderContext is the only
reader: it adds a left join on turns.id to the same turn read that produces the
messages, returning native batches keyed by source turn. It never joins by
content or copied-from references, and the ordinary TreeWalk, history, turn
JSON, and other_meta projections neither load nor expose the payloads.
Compaction, minification, and other synthetic or copied turns get new IDs and never inherit a batch; the original turns' rows survive for leaves still using them. Payloads exist in SQLite, WAL, and backups; deletion is logical, not secure erasure.
Claude Code captures use a versioned envelope containing the actual native records
for one completed API message and its canonical-prefix digest. Transcript UUIDs,
session IDs, signed thinking and redacted blocks stay inside that private payload.
Storage validates the envelope only, not opaque thinking or signatures. Native-only
assistant messages use the existing finalization transaction without inventing
readable content. Runtime output confirmations remain in the loaded provider owner,
not in other_meta. See native bridges.
Cleanup and metadata
Leaf deletion does not immediately delete its root. Startup repairs transient state and managed blobs. Empty-leaf cleanup removes explicitly transient roots without persistent leaves and stale empty/temp leaves. Vacuum removes leafless roots and optional aged data; deep vacuum also prunes old dead tips. Blob cleanup follows committed database state and stays inside managed non-symlink blob paths.
Bulk orphan-content cleanup finds unused hashes through the existing content-ID and turn-reference indexes, then deletes only matching content rows. A no-op sweep scans the narrow indexes rather than the table containing message bodies. Shared content remains live until its last turn reference is removed. Cleanup remains synchronous; the schema and retention rules are unchanged.
leaf_config stores opaque conventions such as session_origin, parent_leaf,
active_tools, and active_plugins. parent_leaf is presentation grouping,
not turn ancestry, root ownership, authorization, or workflow control. Consumers
must tolerate absent, stale, cyclic, malformed, and unknown metadata.
ListLeavesWithMetadata returns only explicitly requested keys.
Leaf-owned files
leaf_files.go implements storage
for the leaf_files attach operation. Registrations are a JSON list
of file_id, key, and path descriptors in the existing leaf_files config
value. Read registrations through GetLeafConfig. Paths must be canonical
absolute descendants of leaf-files/ beside the database, including nested
paths in manually edited config. Rooted cleanup rejects symlink traversal outside
that directory.
AttachLeafFile(leafID, key) returns the existing descriptor for a key or
atomically registers a new one within the Storage instance. The key is not a
path. Unsafe bytes are percent-encoded in the generated filename, and a bounded
suffix retains distinctive endings such as .ezagent-ruby-state. Attach creates
the managed directory if needed, but never creates, stats, writes, or replaces
the payload. A missing payload does not remove its registration. Owners manage
all payload I/O, atomic writes, and any content locking. Storage does not
interpret or reset Ruby state.
Generic config mutations remain opaque and accept whole-list replacement or key deletion. A committed replacement is authoritative, even if stale; detaching does not unlink. Only current registrations are cleaned on leaf deletion. Detached files and unregistered client temporary files are not scanned or recovered by storage. Duplicate references are allowed, even across leaves; first cleanup wins and later cleanup tolerates a missing file.
Explicit deletion and both startup deletion paths remove registered payloads
before removing leaf rows. On Linux, deletion takes the registered
lock.ezagent-ruby-state flock before cleanup and holds it through the database
commit. It keeps that lock pathname linked until commit, then unlinks it before
releasing the flock. This serializes Ruby state writes with deletion, including
temporary-leaf cleanup. If the lock is held, explicit deletion reports
leaf_busy and startup cleanup skips that leaf. Updates or deletion of the
leaf_files config also acquire the existing state lock before changing the
registration, including metadata updates; they fail while a state write holds
the lock. Registration reads must not acquire the per-leaf mutex while holding
the flock. After commit, a lock unlink
failure is logged and deletion remains successful. A stale caller can still
recreate an empty lock file after deletion; its post-lock registration check
rejects payload writes. Registration, reserved-key config edits, and deletion
share an in-memory per-leaf lock within the daemon's Storage instance. Turn
creation and alert metadata mutations use the same coordination during startup
cleanup. The in-memory lock does not coordinate separate Storage handles or
processes. Client payload writes are coordinated only by the Ruby state flock
exception described above. Normal daemon startup runs cleanup before admitting
requests.
Cleanup closes database reads before filesystem removal and opens its deletion transaction afterward. Neither the single pooled connection nor SQLite's writer reservation spans unlink, so another leaf can write during a slow removal. Startup cleanup rechecks each selected leaf under its lock and commits deletion one leaf at a time. It removes transient roots only after they have no leaves; a leaf added after selection is not swept up without file cleanup. A batch can therefore make partial progress before an error. Pre-transaction cleanup errors retain the failing leaf's row. A later database failure can retain a row whose files have already been removed; retry tolerates that absence. Malformed registrations or unsafe paths block cleanup until corrected through ordinary config edits.
Cleanup uses an opened managed-directory handle, refuses a symlinked managed directory, and never recursively removes directories. A registered symlink is unlinked itself without following its target. This is not a writer lease or a sandbox: a client holding a path can still race deletion. Persistent conversations retain registrations across reopen and unload, including before their first turn. Explicitly temporary leaves still expire; empty persistent leaves without intentional state remain subject to startup cleanup. Bash output buffers remain separate cache files.
Inbox alert lifecycle
leaf_alerts.go stores inbox alert
state in existing leaf_config rows, without schema or wire changes.
alert_time is a UTC RFC3339Nano string. alert_idle is enabled only when its
value equals true, ignoring case but not trimming whitespace. Idle conversion
leaves false, empty, and malformed values unchanged.
Alert policy lives in clients, using the public leaf metadata API. The TUI
composer arms with one update_leaf_meta call that sets alert_idle=true and
clears alert_time, which also settles existing Inbox attention. A prompt arms
before it is sent. A steer arms after the service accepts it. If either
submission returns an immediate error, the TUI sets alert_time to now through
a separate metadata update, leaving alert_idle unchanged. This puts the leaf
in Inbox even when no run started. The draft and submission error remain
visible; failure of the attention write is reported separately.
The steer ordering is deliberate. Arming before sending would let the previous run finish and consume the alert before the steer reaches the service. The steer would then start a new activation with no alert armed for its completion. After acceptance, either the steer is queued in the running activation, where it prevents normal completion until processed, or it has started a new activation on an idle leaf. Successful completion then requires a model request that includes the steer, normally leaving ample time for the metadata write.
This is not an atomic completion guarantee. A slow remote connection or stalled client combined with a very fast model could delay the metadata write until after the steered run finishes. A fast error or abort can also finish before the write. In those cases, the late write clears any completion timestamp and leaves the alert armed for the next idle transition instead. This limited edge case is accepted in preference to the pre-send race with the previous run's completion.
Generic prompt and steer admission never arm or clear alerts. Ruby scripts and other API clients opt in by setting the same leaf parameters. Accepted input, tool results, replay, and recovered drafts record activity without changing alert policy; the next idle transition still consumes any armed alert.
Storage.RecordLeafActivityContext(ctx, leafID, active) accepts the service
lifecycle's activity classification: running, background, and aborting are
active. It transactionally saves the reserved internal _service_active marker
for active leaves, even when no idle alert is armed. This lets an alert armed
during a run take effect when that run ends. Missing leaves return
ErrLeafNotFound.
Service admission reservations and provisional Agent activations do not create activity markers. They defer idle conversion of an existing marker until all reservations and real work drain. The marker stays durable across Agent replacement and Close so that replacement or startup recovery can finish it.
An inactive observation removes an existing marker. If alert_idle is enabled,
the same transaction removes that key and overwrites alert_time with the
current UTC RFC3339Nano timestamp. Otherwise it preserves both alert keys.
Without a marker, an inactive observation does not consume an armed alert or
change an existing timestamp. Marker presence, not its value, identifies prior
activity.
Storage.RecoverLeafAlerts() is startup-only and must run before activity
admission. In one transaction it applies the same idle conversion to every
marked leaf and clears every marker, including markers on leaves with disabled
or absent alerts. It returns the number of recovered markers, not the number
of converted alerts. All conversions use one recovery timestamp. A failure
rolls back the entire operation and returns a zero count. Repeating recovery
after success leaves unmarked alerts unchanged. Storage does not observe service
lifecycle or invoke recovery itself; those calls belong to the service.
Before disconnecting capability owners during normal shutdown,
Storage.FreezeLeafAlerts() stops idle conversions, preserving markers for the
next startup. New activity can still record a marker during shutdown. Empty
persistent leaves with alert timestamps, enabled idle alerts, or interrupted
activity survive startup cleanup. Explicitly temporary leaves still expire.
Stats read cuts and attachment work
GetLeafStatsSnapshot captures leaf fields, root cwd, reachable turn count,
usage, and context-estimation inputs in one SQLite read transaction. It selects
usage/state/stop metadata, user file-size metadata, and byte lengths rather than
full content, thinking, file paths, or provider-native batches. It closes rows
and commits before JSON parsing and token estimation. The returned durable
fields still describe that one read cut, even if another writer changes the
leaf before the transaction finishes. Runtime and progress fields remain
independent process-local observations added by the service afterward.
Parent-chain helpers append IDs tip-first and reverse once, rather than copying the growing prefix for every ancestor. They retain root-to-tip order, virtual root boundaries, missing-parent handling, and cycle rejection. Storage keeps its single connection; these changes shorten ownership rather than hiding waits with a larger pool.
Validated attachment batches prepare hashes, JSON, and compressed bytes before opening write transactions. Managed-path checks and final file publication stay inside the transaction with reference insertion, preserving the existing publication order while CPU work moves earlier. Draft reads copy compressed attachment bytes while rows hold the single connection, then close rows before decompression and validation. Post-commit cleanup reserves that same connection, so it cannot unlink while draft rows are copying bytes. Startup reconciliation collects its stable live references and closes rows before disk inspection; its SQL and recovery order are unchanged.
Post-commit attachment cleanup treats harvested paths as candidates, not proof
that a file is still unreferenced. It reserves the single Storage connection,
checks current turn_content.file_ref ownership, and holds the reservation
through managed-path validation and unlink. Any current content row retains the
file, even if that row has no turn yet. If another leaf republishes the same
content-addressed attachment first, cleanup sees its committed reference and
skips unlink. If cleanup reserves the connection first, publication waits and
recreates the file after removal, before committing its reference. All existing
post-commit cleanup callers share this helper; their committed deletion and
cleanup-error behavior is unchanged.
This coordination applies to operations through one Storage and depends on
its single-connection pool. It does not coordinate independent database handles,
other processes, or hostile filesystem replacement. Startup reconciliation must
still run before write admission. Returned turn snapshots do not pin attachment
files after their database reads finish; a later legitimate deletion can remove
those files before an out-of-transaction consumer reads them.
stats_test.go covers byte/file-size estimates, synthetic abort exclusion,
virtual boundaries, draft cumulative usage, single-connection cancellation, and
an independent WAL writer changing fields after capture without mixing the read
cut. attachment_lifetime_test.go covers stale cleanup after reference recreation
and a publisher waiting until unlink finishes. Existing attachment and
maintenance regressions cover publication, reference reuse, rollback, and
managed-path safety.
The selected read/admission paths preserve session.ErrLeafNotFound as a typed
cause: GetLeaf, GetLeafContext, GetLeafTip, GetLeafStatsSnapshot and its
context variant, and UpdateLeafName. Their public error presentation remains
leaf not found: <id>. Callers should use errors.Is, not text matching, to
separate missing input from an unexpected database failure. This is an internal
classification change, not a new response code or JSONL field.
Pending user-turn context
Optional PendingTurn.steer survives in-memory queue and plugin handoffs but
has no separate stored field. The mode plugin preserves its meaning as a
leading turn-type="steer" text annotation. User advanced.other_meta may
contain validated free-form JSON object text, including the
background bash completion convention.
It persists in existing other_meta without a new stored kind or schema change.
Approval boundary and authority
Any table, column, index, trigger, migration, startup SQL, persistence model, or
PRAGMA user_version change requires explicit user approval. Migration and its
version update commit atomically.
Exact behavior is in storage.go, tree.go, migration.go, native_thinking.go,
and their storage, migration, native-thinking, usage, and deep-vacuum tests.
Wire validation belongs to pkg/protocol. Service handlers map
wire requests to storage; service/agent owns draft admission,
pipeline release, and provider context use.