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.
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.
| 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.
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.
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 or openai.responses.reasoning.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.
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. Filesystem 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.
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.