Path: redb-route/redb.Route.Llm/Engine/Storage/IConversationStore.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/Storage/IConversationStore.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; using redb.Route.Llm.Providers; namespace redb.Route.Llm.Engine.Storage; /// /// Persists conversation transcripts so that an agent run can be resumed, /// branched, or replayed offline. The contract is intentionally tree-shaped: /// every message has an optional parent identifier, which lets callers branch /// from any node — required to model regenerate / parallel tool-calls / what-if /// flows. The flat "append-only history" pattern falls out naturally when the /// caller always passes the previously-appended message id as parentId. /// /// The optional exchange parameter on every method carries the current /// route exchange when the call originates from inside a route pipeline. /// REDB-backed implementations resolve a per-exchange IRedbService /// (and its named siblings via ) through /// IRouteContext.GetRedbService(name, exchange), which already manages /// per-exchange scopes and disposal. In-memory implementations ignore it. /// Without an exchange a redb-backed implementation opens a redb scope of its own for the call. That scope joins an /// ambient (a , a /// route's .Transacted()) as every redb connection does, but not a transaction begun on the context's shared /// IRedbService (ExecuteAtomicAsync, BeginTransaction), which it does not see: pass the exchange, /// or use a TransactionScope, when the call must commit or roll back with that work. In-memory implementations /// take part in no transaction. /// /// public interface IConversationStore { /// /// Appends as a child of /// (or as the root when is null) and returns the /// new message identifier. /// Task AppendAsync( string conversationId, string? parentId, LlmMessage message, ConversationMessageMeta meta, IExchange? exchange = null, CancellationToken ct = default); /// /// Loads the linear path from the conversation root to . /// Passing null returns the path to the most-recently-appended leaf. /// Task> LoadPathAsync( string conversationId, string? leafId = null, IExchange? exchange = null, CancellationToken ct = default); /// /// Loads the full tree for the conversation (every branch). Used for /// observability dashboards and eval replays — NOT for hot-path requests. /// Task> LoadTreeAsync( string conversationId, IExchange? exchange = null, CancellationToken ct = default); } /// Queryable metadata that lives on the message node — hoisted from /// the message body so that index-friendly filters (date range, role, /// iteration) can run without scanning the full payload. public sealed class ConversationMessageMeta { /// Wall-clock timestamp the message was appended. public DateTime CreatedAtUtc { get; init; } = DateTime.UtcNow; /// Agent iteration index (1-based) that produced the message; 0 for the user prompt. public int Iteration { get; init; } /// Provider id ("openai", "anthropic", ...) — null for non-provider messages. public string? ProviderId { get; init; } /// Model id as resolved at the time of the call. public string? ModelId { get; init; } /// Stop reason for assistant messages. public LlmStopReason? StopReason { get; init; } /// Token usage attributed to this turn. public LlmUsage Usage { get; init; } = LlmUsage.Empty; /// Tool-use id when the message is a tool result. public string? ToolUseId { get; init; } /// /// Effective sampling temperature passed to the provider for the call /// that produced this assistant message; null on user / tool-result rows. /// public double? Temperature { get; init; } /// Effective max-output-tokens cap; null on non-assistant rows. public int? MaxTokens { get; init; } /// Effective top-p value; null on non-assistant rows. public double? TopP { get; init; } /// Prompt-template name resolved at call time (FK into PromptTemplateProps). public string? PromptTemplateName { get; init; } /// Prompt-template version paired with . public string? PromptTemplateVersion { get; init; } /// /// Stable hash of the tool-capabilities set exposed to the model on this /// call. Allows auditors to detect tool-surface drift across runs. /// public string? ToolSetHash { get; init; } /// /// Opaque provider-side fingerprint identifying the backend configuration /// that served the call (OpenAI's system_fingerprint). Null when the /// provider does not surface one. /// public string? ProviderSystemFingerprint { get; init; } /// /// Stable identifier of the principal that initiated the agent turn that /// produced this row. The same value is stamped on every row of the turn /// (system / user / tool / assistant) so audit queries always have a /// consistent subject. Captured pre-call; null when no principal is wired. /// public string? UserId { get; init; } /// /// Free-form audit tags captured pre-call from the fluent /// .Audit(k,v) builder and / or llm.audit.<name> headers. /// The same snapshot is stamped on every row of the turn. Null / empty /// when no tags are wired. /// public IReadOnlyDictionary? AuditTags { get; init; } /// /// Connection-factory alias used for this call (LlmConnectionFactory.Name) — /// the operator-chosen profile name. Audits the *intent* on top of /// / . /// public string? FactoryName { get; init; } /// /// Effective base URL set on the connection factory. Null when the /// factory used the provider's built-in default endpoint. /// public string? BaseUrl { get; init; } /// /// Provider-issued response identifier (top-level id on /// OpenAI / Anthropic / xAI / Together). Null on non-assistant rows. /// public string? ProviderResponseId { get; init; } /// /// Wall-clock time (milliseconds) the provider spent producing the /// assistant turn this row belongs to. Null on non-assistant rows. /// public long? LatencyMs { get; init; } /// /// Stable, non-secret fingerprint of the API key used for the call — /// SHA-256 of the key, first 16 hex chars. Null when the factory exposes /// no ApiKey. /// public string? ApiKeyFingerprint { get; init; } /// /// How many times the route framework retried the inbound exchange before /// the call succeeded. Read from /// exchange.Properties["RetryAttempt"] (set by /// RetryProcessor) with fallbacks to /// exchange.In.Headers["CamelRedeliveryCounter"] /// (OnExceptionProcessor) and /// exchange.In.Headers["CamelDeadLetterRedeliveryCount"] /// (DeadLetterProcessor). Null on first / only delivery. /// public int? RetryCount { get; init; } } /// A persisted conversation message with its tree placement and metadata. public sealed class ConversationMessage { /// Store-assigned message id. public required string Id { get; init; } /// Parent message id; null for the root. public string? ParentId { get; init; } /// Conversation this message belongs to. public required string ConversationId { get; init; } /// Persisted message payload. public required LlmMessage Message { get; init; } /// Metadata captured at append time. public required ConversationMessageMeta Meta { get; init; } } /// /// In-memory conversation store — suitable for unit tests and demos. /// Replace with the redb-backed implementation in redb.Route.Llm.Storage.Redb. /// public sealed class InMemoryConversationStore : IConversationStore { private readonly ConcurrentDictionary> _byConversation = new(); /// public Task AppendAsync(string conversationId, string? parentId, LlmMessage message, ConversationMessageMeta meta, IExchange? exchange = null, CancellationToken ct = default) { var id = Guid.NewGuid().ToString("N"); var node = new ConversationMessage { Id = id, ParentId = parentId, ConversationId = conversationId, Message = message, Meta = meta }; var bucket = _byConversation.GetOrAdd(conversationId, _ => new List()); lock (bucket) bucket.Add(node); return Task.FromResult(id); } /// public Task> LoadPathAsync(string conversationId, string? leafId = null, IExchange? exchange = null, CancellationToken ct = default) { if (!_byConversation.TryGetValue(conversationId, out var bucket)) return Task.FromResult>([]); ConversationMessage[] snapshot; lock (bucket) snapshot = bucket.ToArray(); var leaf = leafId is null ? snapshot.LastOrDefault() : snapshot.FirstOrDefault(m => m.Id == leafId); if (leaf is null) return Task.FromResult>([]); var byId = snapshot.ToDictionary(m => m.Id); var path = new List(); var cursor = leaf; while (cursor is not null) { path.Add(cursor); cursor = cursor.ParentId is { } pid && byId.TryGetValue(pid, out var parent) ? parent : null; } path.Reverse(); return Task.FromResult>(path); } /// public Task> LoadTreeAsync(string conversationId, IExchange? exchange = null, CancellationToken ct = default) { if (!_byConversation.TryGetValue(conversationId, out var bucket)) return Task.FromResult>([]); lock (bucket) return Task.FromResult>(bucket.ToArray()); } }