Files
agentik/storage-core
subochev 4ad59d5f5d
ci / JVM build + tests (push) Has been cancelled
release / Publish KMP libraries → caffeine Nexus (release) Successful in 32s
feat(events): EventStore + AllEvent unified stream + replay endpoints
EventStore (persistent event log) и AllEvent (sealed wrapper для
третьего типа подписки — ВСЕ events в одном потоке). Touches 7 modules.

Архитектура:
  Producer (ChatAgent + ConversationEvents) → EventStore + SharedFlow
  ↓                                            ↓
  Live SSE (cold, no replay)         Replay endpoints (cursor-based)

(1) :storage-core — EventStore interface
  - append(record): idempotent по record.id (INSERT OR IGNORE)
  - query(conversationId?, afterId?, limit): пагинированный catchup
  - pruneOlderThan(instant): TTL cleanup
  - count(): maintenance метрика
  - @Serializable EventRecord(id, conversationId?, createdAt, type, payload)
  - enum EventType: AGENT_*/CONVERSATION_* (forward-compat fallback)
  - StorageBundle дополнен eventStore: EventStore? = null (backward-compat)

(2) :storage-inmemory — InMemoryEventStore
  - Thread-safe (Mutex), binarySearch для упорядоченной вставки
  - Записи сортируются по createdAt ASC, ties по id ASC (стабильно)
  - Idempotency по id (повторный append no-op)

(3) :storage-sqlite — SqliteEventStore
  - sqldelight schema: agent_event (id PK, conversation_id?, created_at,
    type, payload BLOB) + 2 индекса (conversation_id+created_at,
    created_at)
  - Миграция v3: CREATE TABLE IF NOT EXISTS (additive)
  - 5 запросов: insert, queryGlobal, queryByConv, pruneOlderThan, count
  - Forward-compat: неизвестный EventType в БД → fallback AGENT_CREATED
    (чтобы старые клиенты не падали на новых enum values)
  - Добавлен в SqliteStores (open/inMemory + asBundle())

(4) :standalone — Producer wiring
  - ChatAgent.persistAgentEvent() — fire-and-forget append при каждом
    AgentEvent (Created/Deleted/Renamed)
  - ConversationEvents — персистит в EventStore при каждом tryEmit/emit
    (концертный случай от connect disconnect)
  - ChatAgent.allEvents() — merge agent-events + snapshot всех живых
    диалогов в единый Flow<AllEvent>

(5) :proto — AllEvent sealed interface
  - AllEvent.Agent(date, event: AgentEvent)
  - AllEvent.Conversation(date, conversationId, event: Event)
  - Agent.allEvents(after): Flow<AllEvent> — третий тип подписки
    (в дополнение к events() и Conversation.events)

(6) :server — Endpoints
  - GET /events/all — SSE поток AllEvent (cold)
  - GET /events/replay?after_id=&limit= — пагинированный catchup
    (503 если EventStore не сконфигурирован)
  - GET /conversations/{id}/events/replay?after_id=&limit= — то же per-conv
  - Module.kt принимает eventStore: EventStore? параметром

(7) :client — Client API
  - AgentClient.allEvents(after) — подписка на /events/all SSE
  - AgentClient.replayAllEvents(afterId, limit) — catchup /events/replay
  - AgentClient.replayConversationEvents(convId, afterId, limit)
  - EventRecordDto — wire-зеркало EventRecord (клиент не зависит
    от :storage-core, определяет DTO локально; формат совместим с
    серверным JSON)

Тесты: 22 новых теста (12 InMemory + 10 Sqlite), все зелёные.
Все три слоя синхронизированы: proto contract + standalone impl +
server endpoint + client API.
2026-09-20 02:51:58 +03:00
..

:storage-core — контракт хранилища (KMP, jvm + native)

Что это

Интерфейсы persistence-уровня для :standalone:

  • MessageStore — append-only история сообщений по диалогу.
  • WorkingMemoryStore — rolling buffer текущего хода (AssistantMessage, ToolExchange, UserMessage, system-prompt) для fast-recovery при reconnect/relance.
  • ConversationStore — метаданные диалогов (id, title, model, timestamps).
  • ReflectionStore — LLM-reflections (свободная форма заметок хранителя).

Решает: позволяет запустить агента на Android-in-memory, на desktop-SQLite, или на production-SQLite, не переписывая логику. Контракт минимален и async-friendly.

Где используется

  • :storage-inmemory — для тестов и Android.
  • :storage-sqlite — прод (Desktop / server / однодесктопный Android-development).

Как подключить

kotlin {
    sourceSets.commonMain.dependencies {
        api("pw.binom.agentik:storage-core:0.1.0")
    }
}

Версии

gradle/libs.versions.toml → [versions] agentik-storage-core.

Что в API

interface MessageStore {
    suspend fun append(conversationId: String, message: Message): Unit
    suspend fun after(conversationId: String, instant: Instant, limit: Int = 100): List<Message>
}

interface WorkingMemoryStore {
    suspend fun save(conv: String, entry: WorkingMemoryEntry): Unit
    fun load(conv: String): Flow<WorkingMemoryEntry>   // cold flow
    suspend fun clear(conv: String): Unit
}

sealed interface WorkingMemoryEntry {
    val id: String
    val date: Instant
    class UserMessage(...) : WorkingMemoryEntry
    class AssistantMessage(...) : WorkingMemoryEntry
    class ToolExchange(val toolName: String, val toolArgsJson: String, val resultText: String, val wasCancelled: Boolean) : WorkingMemoryEntry
    class SystemPrompt(...) : WorkingMemoryEntry
}

Тесты

Контрактные тесты (общие для всех имплементаций) — в :storage-sqlite и :storage-inmemory.

Чего здесь НЕТ

  • Никакого HTTP / SSE.
  • Никакой конкретной БД. Backend'ы в :storage-*.

Текущий статус

Используется продакшеном. Контракт зафиксирован после interrupt-имплементации (см. INTERRUPT-DESIGN.md).