# Session History API
Session History is the sole caller-facing durable session store. It owns
active-session creation and discovery, lifecycle records, ordered commands,
durable stop requests, pending session objects, and completion integration. It
delegates the cohesive box/event state machine, exact context projection,
replay, and mechanically synchronized mutable `Session` implementation, then
re-exports that API under the original paths, including caller-supplied
transient projection footer lines and the structured native-resume result.
Existing callers do not depend on the implementation package directly.
The append-only completion catalog and the active/completed read model are
owned by a focused leaf component. Session History retains lifecycle ordering,
live-file cleanup, session locking, and its established public types. This
library has no HTTP, Kweb transaction, provider-network, credential, or
process-execution boundary.
## Store
```rust
pub struct Config {
pub directory: std::path::PathBuf,
pub completed_list: std::path::PathBuf,
pub provider_cost_compatibility: Option<ProviderCostCompatibility>,
}
pub struct ProviderCostCompatibility {
pub session_model: fn(&serde_json::Value) -> Option<String>,
pub estimator: chatend::ProviderCostEstimator,
}
impl SessionHistory {
pub fn open(config: Config) -> anyhow::Result<SessionHistory>;
pub fn health(&self) -> Result<(), Error>;
}
```
`open` creates private directories and the completed-list file when absent. At
startup it validates active control journals, repairs only incomplete final
records, rejects complete corruption, and compacts superseded typed control
records without modifying session logs or pending objects. Completion-catalog
creation synchronizes a new file and its directory entry.
Keep one cheaply cloneable store per persistence root. Same-process mutations
are serialized per session. Clones also serialize completion-catalog reads and
writes. Independent processes are not coordinated.
`health` reads and validates the complete completion catalog. Its work and peak
memory are proportional to catalog bytes and decoded receipts. It performs no
network I/O, retries, timeout, or truncation.
## Creation and discovery
```rust
pub struct NewSession {
pub kind: chatend::SessionKind,
pub created_at: String,
pub effective_context_tokens: u64,
pub channel: serde_json::Value,
}
pub struct RegisterSession {
pub id: String,
pub started_at: String,
pub state: serde_json::Value,
}
pub struct StartSession {
pub idempotency_id: String,
pub started_at: String,
pub session_type: String,
pub duration_minutes: Option<f64>,
pub custom_prompt: Option<String>,
}
pub struct NewIngressSession {
pub idempotency_id: String,
pub started_at: String,
pub source_session_type: String,
pub kind: chatend::SessionKind,
pub effective_context_tokens: u64,
pub text: String,
pub metadata: serde_json::Value,
}
pub struct LaunchSession {
pub session_id: String,
pub started_at: String,
pub effective_context_tokens: u64,
pub channel: serde_json::Value,
pub state: serde_json::Value,
pub initial_message: serde_json::Value,
}
pub struct SessionLaunch {
pub session_id: String,
pub command_id: String,
}
pub struct SessionRecord {
pub id: String,
pub phase: String,
pub started_at: String,
pub updated_at: String,
pub state: serde_json::Value,
pub provenance_id: Option<String>,
pub version: i64,
pub last_user_message_at: Option<String>,
pub ended_at: Option<String>,
pub ingress_failure_count: i64,
pub ingress_failures: serde_json::Value,
pub ingress_next_attempt_at: Option<String>,
pub summary: bool,
}
pub struct Created<T> {
pub value: T,
pub created: bool,
}
impl SessionHistory {
pub fn create_session(&self, input: NewSession) -> anyhow::Result<Session>;
pub fn open_session(
&self,
metadata: chatend::SessionMetadata,
) -> anyhow::Result<Session>;
pub fn open_session_with_provider_model(
&self,
metadata: chatend::SessionMetadata,
provider_model: Option<&str>,
) -> anyhow::Result<Session>;
pub async fn register(
&self,
input: RegisterSession,
) -> Result<SessionRecord, Error>;
pub async fn start(
&self,
input: StartSession,
) -> Result<Created<SessionRecord>, Error>;
pub async fn enqueue_ingress(
&self,
input: NewIngressSession,
) -> Result<Created<SessionRecord>, Error>;
pub async fn launch_session(
&self,
input: LaunchSession,
) -> Result<SessionLaunch, Error>;
pub async fn list(&self) -> Result<Vec<SessionRecord>, Error>;
pub async fn get(&self, id: &str) -> Result<SessionRecord, Error>;
pub fn legacy_provider_cost_summary_for_archive(
&self,
archive: &serde_json::Value,
session_state: Option<&serde_json::Value>,
) -> anyhow::Result<Option<chatend::ProviderCostSummary>>;
}
```
`create_session` creates a log with a library-assigned ID; `register` later
attaches lifecycle control. `start` creates log and control together.
`enqueue_ingress` stores source text before exposing `ingress_pending`.
Idempotent calls report replay through `Created::created`.
`launch_session` accepts a caller-supplied stable child-session UUID, an RFC
3339 creation time, an effective context-token value, arbitrary JSON channel
metadata, an ordinary-conversation state object, and the complete JSON payload
for one initial message command. The command ID is UUIDv5 with the child UUID
as namespace and the exact name bytes
`kennedy.launch-session.initial-command.v1`. The operation returns only the
stable session and command IDs and never starts or waits for inference.
All terminal input defects are rejected before filesystem mutation. Under the
same per-session same-process lock used by other mutations, the operation
reconciles the log, control journal, deterministic sequence-one `message`
command, and active lifecycle. A cold launch durably creates or reconciles the
log and control journal, appends and synchronizes the one initial command, then
appends and synchronizes lifecycle last. Control state without its log is a
conflict and is never reconstructed or deleted. A partial launch continues
only when every durable part already present exactly matches the requested
ordinary-conversation metadata, state, deterministic command, and lifecycle.
There is no rollback deletion.
An exact active replay returns the same IDs without appending. Reusing the
child UUID with a different creation time, metadata, state, command payload,
command identity, lifecycle, or provenance is a conflict and overwrites
nothing. A completion receipt for the same child UUID replays only when its
session type is `conversation` and its creation time matches; otherwise it
conflicts. Concurrent identical calls converge on one child and identical
results. Concurrent conflicting calls have one winner and stable conflicts.
Lifecycle-less commands are not listed, claimable, or completable.
Launch reconciliation reads the completion catalog, one session log, and one
control projection. Work is O(completion-catalog bytes plus that session's log
bytes, events, and control records), with peak memory proportional to those
decoded values. A cold path creates one log and one control journal and appends
at most one command and one lifecycle record. Replays append only missing exact
parts. There are no provider calls, network operations, retries, timeouts,
polling waits, arbitrary input caps, or output truncation. Local completion
time depends on filesystem append and synchronization performance, so no
hardware-independent latency is promised.
Active phases are `active`, `ingress_pending`, `ingress_in_progress`, and
`ingress_failed`; completed receipts project as `complete`. `list` returns
active summaries and completed receipts newest-updated first. Active discovery
reads only small control journals, ignores a listed transcript when its
control journal is absent or has no lifecycle, and never opens or replays
transcript logs. Active summaries retain the bounded first user message plus
current box and event counts when a lifecycle checkpoint supplied them; legacy
records may return those fields as null. `get` accepts an active session ID or
completed archive object ID.
Full active reads replay and checksum-validate the log and, when durable
Chatend metadata exists, materialize `boxes`, `context`, `chatendText`,
`chatendTextSource`, and `structuredMaterial`. The newest normalized provider
submission supplies exact text plus provider/model/reasoning, instruction,
tool, round, and time material. A session without that event receives its
current replayed text with source `reconstructed` and null structured material.
The same fields are projected beneath `historyIngress` when that is the active
context. Other presentation-sized checkpoint fields are not retained in
control state.
Provider-cost compatibility never rewrites archives. It returns `None` when
disabled or for a valid metadata-free legacy session-log archive.
## Commands, stops, and objects
```rust
pub struct NewCommand {
pub idempotency_id: String,
pub kind: String,
pub payload: serde_json::Value,
}
pub struct SessionCommand {
pub id: String,
pub conversation_id: String,
pub sequence: i64,
pub kind: String,
pub payload: serde_json::Value,
pub status: String,
pub cancel_requested: bool,
pub outcome: Option<serde_json::Value>,
pub created_at: String,
pub processing_started_at: Option<String>,
pub completed_at: Option<String>,
pub idempotency_id: String,
}
pub struct CommandOutcome {
pub outcome: serde_json::Value,
}
pub struct NewStopRequest {
pub idempotency_id: String,
pub scope: String,
}
pub struct NewCurrentWorkStop {
pub idempotency_id: String,
}
pub struct SessionStopRequest {
pub id: String,
pub session_id: String,
pub scope: String,
pub status: String,
pub outcome: Option<serde_json::Value>,
pub requested_at: String,
pub completed_at: Option<String>,
pub idempotency_id: String,
}
pub struct StopOutcome {
pub outcome: serde_json::Value,
}
pub struct NewObject {
pub file_name: Option<String>,
pub media_type: String,
pub bytes: Vec<u8>,
}
pub struct StoredObject {
pub file_name: String,
pub media_type: String,
pub bytes: Vec<u8>,
}
impl SessionHistory {
pub async fn enqueue(
&self,
id: &str,
input: NewCommand,
) -> Result<Created<SessionCommand>, Error>;
pub async fn command_heads(&self) -> Result<Vec<SessionCommand>, Error>;
pub async fn claim_command(&self, id: &str) -> Result<SessionCommand, Error>;
pub async fn complete_command(
&self,
id: &str,
outcome: CommandOutcome,
) -> Result<SessionCommand, Error>;
pub async fn request_stop(
&self,
id: &str,
input: NewStopRequest,
) -> Result<Created<SessionStopRequest>, Error>;
pub async fn request_current_work_stop(
&self,
id: &str,
input: NewCurrentWorkStop,
) -> Result<Created<SessionStopRequest>, Error>;
pub fn listen_for_stop(&self, id: &str) -> Result<StopListener, Error>;
pub async fn stop_heads(&self) -> Result<Vec<SessionStopRequest>, Error>;
pub async fn complete_stop(
&self,
id: &str,
outcome: StopOutcome,
) -> Result<SessionStopRequest, Error>;
pub async fn stage_object(
&self,
id: &str,
object: NewObject,
) -> Result<String, Error>;
pub fn object(
&self,
id: &str,
pending_id: &str,
) -> Result<StoredObject, Error>;
}
impl StopListener {
pub async fn requested(&self);
}
```
Commands are ordered per active session; only the earliest unfinished command
is claimable. Enqueue is idempotent. Statuses are `pending`, `processing`, and
`complete`. `command_heads` and `stop_heads` project lifecycle-bearing control
journals directly; queue polling does not open or replay transcript logs.
Stop scopes are `turn`, `session`, and `self-time-run`. Stops do not advance
the lifecycle version. A turn stop marks the earliest unfinished `message` or
`retry` command for cancellation. `request_current_work_stop` derives scope
from durable phase and session kind. A listener created after a durable pending
request observes it.
Object staging requires an active session with no unfinished command. It
returns `pending:N`; `object` returns verified owned bytes and sanitized
metadata.
## Lifecycle and completion
```rust
pub struct Checkpoint {
pub expected_version: i64,
pub state: serde_json::Value,
pub user_activity: bool,
}
pub struct ExpectedVersion {
pub expected_version: i64,
}
pub struct StartIngress {
pub expected_version: i64,
pub provenance_id: String,
}
pub struct IngressFailure {
pub expected_version: i64,
pub stage: String,
pub code: Option<String>,
pub message: String,
pub rounds_used: Option<u64>,
pub context_tokens: Option<u64>,
pub context_window_tokens: Option<u64>,
}
pub struct RetryIngress {
pub expected_version: i64,
pub state: serde_json::Value,
}
impl SessionHistory {
pub async fn checkpoint(
&self,
id: &str,
input: Checkpoint,
) -> Result<SessionRecord, Error>;
pub async fn request_ingress(
&self,
id: &str,
input: Checkpoint,
) -> Result<SessionRecord, Error>;
pub async fn start_ingress(
&self,
id: &str,
input: StartIngress,
) -> Result<SessionRecord, Error>;
pub async fn complete_ingress(
&self,
id: &str,
input: ExpectedVersion,
) -> Result<SessionRecord, Error>;
pub async fn fail_ingress(
&self,
id: &str,
input: IngressFailure,
) -> Result<SessionRecord, Error>;
pub async fn retry_ingress(
&self,
id: &str,
input: RetryIngress,
) -> Result<SessionRecord, Error>;
pub async fn release_interrupted_ingress(&self)
-> Result<Vec<String>, Error>;
pub async fn complete(
&self,
id: &str,
input: Checkpoint,
) -> Result<SessionRecord, Error>;
}
```
`expected_version` is optimistic concurrency control. Every ingress failure is
terminal and remains in `ingress_failed` until the user explicitly retries;
there is no automatic retry delay or attempt budget. Only five concise
failures are retained. Manual retry returns the lifecycle to
`ingress_pending`, clears the prior `historyIngress` working snapshot, and
preserves source state plus failure diagnostics. Startup repair moves an
abandoned `ingress_in_progress` claim to `ingress_failed` with an
`ingress_interrupted` diagnostic rather than resuming it automatically.
Completion requires a permanent `sessionObjectId` in the supplied state or its
`historyIngress`. The embedding application commits Kweb first.
```rust
pub struct RecordCompletion {
pub session_object_id: String,
pub commit_receipt: Option<CompletionReceipt>,
pub session_id: Option<String>,
pub session_type: Option<String>,
pub created_at: Option<String>,
}
pub struct CompletionReceipt {
pub transaction_id: Option<String>,
pub session_object_id: String,
pub session_id: Option<String>,
pub session_type: Option<String>,
pub created_at: Option<String>,
pub committed_at: Option<String>,
pub ingress_source: Option<serde_json::Value>,
pub node_ids: std::collections::BTreeMap<String, String>,
pub object_ids: std::collections::BTreeMap<String, String>,
}
impl SessionHistory {
pub async fn record_completion(
&self,
input: RecordCompletion,
) -> Result<(), Error>;
}
```
The receipt is appended, flushed, and synchronized before live cleanup. When a
session ID is supplied, successful receipt persistence is followed by deletion
of its log, pending objects, and control journal. Historical one-ID lines
remain readable. The first receipt for a session-object ID wins; a duplicate
does not replace it. Catalog reads and records are O(file bytes plus decoded
receipts), with memory proportional to decoded receipts. A new receipt performs
one append, one flush, and one file-data synchronization. There are no retries,
timeouts, network operations, receipt-count caps, or truncation.
## Mutable Session and re-exported Chatend API
`Session` remains opaque through this facade and is created or reopened only
through `SessionHistory`. Mutations synchronize durable log data before
updating memory.
```rust
impl Session {
pub fn id(&self) -> &str;
pub fn state(&self) -> &chatend::Chatend;
pub fn objects(
&self,
) -> &std::collections::BTreeMap<
chatend::PendingId,
chatend::ObjectLocation,
>;
pub fn archive_bytes(&self) -> anyhow::Result<Vec<u8>>;
pub fn is_sealed(&self) -> bool;
pub fn seal(&mut self) -> anyhow::Result<()>;
pub fn repair_unfinished_tools(
&mut self,
recorded_at: impl Into<String>,
) -> anyhow::Result<Vec<chatend::EventId>>;
pub fn mark_completed(&mut self, session_object_id: String);
pub fn configure_context(
&mut self,
kind: chatend::SessionKind,
effective_context_tokens: u64,
);
pub fn create_box(
&mut self,
recorded_at: impl Into<String>,
name: impl Into<String>,
owner: chatend::BoxOwner,
content: chatend::BoxContent,
) -> anyhow::Result<chatend::BoxId>;
pub fn update_box(
&mut self,
recorded_at: impl Into<String>,
box_id: chatend::BoxId,
content: chatend::BoxContent,
) -> anyhow::Result<Option<chatend::EventId>>;
pub fn dehydrate_boxes(
&mut self,
recorded_at: impl Into<String>,
box_ids: &[chatend::BoxId],
) -> anyhow::Result<Vec<chatend::EventId>>;
pub fn summarize_box(
&mut self,
recorded_at: impl Into<String>,
box_id: chatend::BoxId,
text: impl Into<String>,
) -> anyhow::Result<chatend::EventId>;
pub fn rehydrate_box(
&mut self,
recorded_at: impl Into<String>,
box_id: chatend::BoxId,
) -> anyhow::Result<chatend::EventId>;
pub fn retire_box(
&mut self,
recorded_at: impl Into<String>,
box_id: chatend::BoxId,
) -> anyhow::Result<chatend::EventId>;
pub fn allocate_pending_node(
&mut self,
recorded_at: impl Into<String>,
) -> anyhow::Result<chatend::PendingId>;
pub fn stage_object(
&mut self,
recorded_at: impl Into<String>,
media_type: impl Into<String>,
file_name: Option<String>,
transport: serde_json::Value,
bytes: &[u8],
) -> anyhow::Result<chatend::PendingId>;
pub fn read_object(
&mut self,
id: &chatend::PendingId,
) -> anyhow::Result<Vec<u8>>;
pub fn prepare_provider_resume(
&mut self,
recorded_at: impl Into<String>,
synchronized_after: chatend::EventId,
ingress_time: Option<(u64, bool)>,
) -> anyhow::Result<chatend::PreparedProviderResume>;
pub fn prepare_provider_resume_markers(
&mut self,
recorded_at: impl Into<String>,
synchronized_after: chatend::EventId,
ingress_time: Option<(u64, bool)>,
) -> anyhow::Result<Vec<String>>;
pub fn record(
&mut self,
recorded_at: impl Into<String>,
kind: chatend::EventKind,
) -> anyhow::Result<chatend::EventId>;
pub fn commit_events(
&mut self,
recorded_at: impl Into<String>,
events: Vec<chatend::Event>,
) -> anyhow::Result<()>;
pub fn apply_tool_slots(
&mut self,
recorded_at: impl Into<String>,
tool_instance: impl Into<String>,
slots: Vec<chatend::ToolSlotInput>,
) -> anyhow::Result<Vec<chatend::EventId>>;
pub fn apply_tool_slots_with_layout(
&mut self,
recorded_at: impl Into<String>,
tool_instance: impl Into<String>,
slots: Vec<chatend::ToolSlotInput>,
layout_slots: &[String],
) -> anyhow::Result<Vec<chatend::EventId>>;
pub fn apply_box_representations(
&mut self,
recorded_at: impl Into<String>,
desired: &std::collections::BTreeMap<
chatend::BoxId,
chatend::BoxRepresentation,
>,
) -> anyhow::Result<Vec<chatend::EventId>>;
}
```
`seal` rejects unfinished tools; `repair_unfinished_tools` durably closes
interrupted invocations. Pending object payloads are bounded by
`chatend::MAX_OBJECT_BYTES` individually and in aggregate.
`prepare_provider_resume` commits any due provider-visible markers once and
returns `PreparedProviderResume`, whose `marker_lines` are the newly committed
lines and whose optional `thread_reset_reason` is the exact projection-rewrite
reason. `prepare_provider_resume_markers` remains the source-compatible
marker-only wrapper and performs no second transition.
The public `chatend` module re-exports these items without wrapping or changing
their type identity:
- Constants: `FORMAT_VERSION`, `MAX_OBJECT_BYTES`, and
`ESTIMATED_BYTES_PER_TOKEN`.
- Identifiers and session metadata: `EventId`, `BoxId`, `PendingId`,
`SessionKind`, and `SessionMetadata`.
- Box and event state: `BoxOwner`, `BoxContent`, `Representation`,
`BoxRepresentation`, `CanonicalRevision`, `BoxState`, `PendingKind`,
`EventKind`, `Event`, and `Transition`.
- Pending-object and tool state: `ObjectMetadata`, `ObjectLocation`,
`ToolSlot`, `ToolState`, `ToolSlotInput`, `ProviderToolDefinition`, and
`ProviderContext`.
- Projection and accounting: `Chatend`, `ProjectionItem`,
`ContextProjection`, `PreparedProviderProjection`,
`PreparedProviderResume`, `CacheExpectation`, `SessionStatus`,
`ProviderTokenUsage`, `ProviderMetering`, `ProviderCostEstimate`,
`ProviderCostEstimator`, `ProviderCostSummary`, and `estimate_tokens`.
- The opaque mutable `Session` type.
Their complete fields, variants, methods, serialization contracts, and replay
invariants are owned by the matching Chatend consumer contract. `PendingId`
supports `from_event`, `parse`, and `number`; `BoxContent` supports `text` and
`use_concise_header`; `BoxState` supports `stale`. `Chatend` exposes event and
box lookup, active boxes, context limits, projection previews, `projection`,
and `render`. `ContextProjection::render` returns exact model input and
`estimate_tokens` returns the crate estimate. Superseded box occurrences render
`[box updated]`; user and Kennedy message headers retain timestamps.
## Errors
```rust
pub enum ErrorKind {
InvalidInput,
NotFound,
Conflict,
Storage,
}
pub struct Error {
pub kind: ErrorKind,
pub message: String,
}
impl ErrorKind {
pub fn code(self) -> &'static str;
}
```
Codes are `invalid_request`, `not_found`, `state_conflict`, and
`internal_error`. Store opening and opaque `Session` operations use
`anyhow::Error`; typed lifecycle operations use `Error`. Storage details are
logged and callers receive a generic storage message.