- proto: Agent.info (AgentInfo: name/description/usefulness) — человекочитаемое
имя отдельно от opaque id; сериализация и тесты
- server: GET {path} отдаёт Agent.info; GET /conversations/{id}/record —
ConversationRecord без handle'а (для клиентского кэша после AgentEvent.Created)
- outbox: Event.Working — первый event хода, эмитится из Conversation.send()
до LLM-цикла и turnLock, чтобы UI показал спиннер сразу
- standalone: AGENTIK_NAME/AGENTIK_DESCRIPTION/AGENTIK_USEFULNESS → AgentInfo
- client: AgentClient.create eagerly фетчит info (GET {baseUrl})
- client: HttpConversationStore.get читает /record (ConversationRecord,
а не ConversationSnapshot — рассинхрон типов)
- client: noReadTimeout() на POST /conversations/{id}/messages — сервер отвечает
по завершении всего хода агента (реально 0.5–144 с), дефолтные 15 с рвали
живую реплику на клиенте
- journal-api: ConversationRecord @Serializable
- ksqlite 0.1.3 → 0.1.4
- .gitignore: runtime-данные standalone-агента и hs_err-дампы
ksqlite 0.1.3 опубликован в Maven Central — POM/module-metadata/jar все
на месте. Поднят в шести модулях (vector-index-ksqlite, journal-ksqlite,
context-ksqlite, reflection-ksqlite, standalone, memory-md-vector);
комментарии про 0.1.2 в build.gradle.kts обновлены.
Расширение :journal-api: добавлены два count-метода (total + count after
cursor) в интерфейс JournalStore — реализованы в :journal-ksqlite /
:journal-inmemory. Над ними добавлены HTTP-endpoint'ы
GET /journal/conversations/{id}/count
GET /journal/conversations/{id}/count?after=
(объединены в один маршрут с опциональным параметром) и HTTP-клиент
HttpJournalStore.count/concount. Сервер-фасад расширен тестом
JournalRoutesCountTest (5 кейсов через embedded CIO + реальный
InMemoryJournalStore).
:server:jvmTest 10/0, :standalone:jvmTest 129/0, :journal-ksqlite:jvmTest 25/0,
:journal-inmemory:jvmTest 19/0. jvmTest агрегат 425/0/0.
- :journal-inmemory — added iosX64/iosArm64/iosSimulatorArm64 to the
target set so :storage-inmemory (which now depends on it) can build
for iOS. Pure `MutableMap`+`Mutex` impl, no I/O, fully portable.
- client/README.md — new «Кэш списка бесед» section:
- shows `agent.conversationStore` as the read-only entry point;
- demonstrates the «remote.listFlow → local.upsert + outbox.agentEvents
→ local apply» pattern (Created/Renamed/Touched/Deleted);
- notes that the cache is built into `AgentikAgent` by default;
- mentions `wrapWithLocalConversationCache` for custom stores (SQLite/JSON);
- points to `agentikHttpClient(...).raw` as the escape-hatch for clients
that want direct HTTP.
Also adds `HttpConversationStore.kt` to the index (the file existed on
disk but wasn't `git add`ed in the previous commit).
Adds `agent.conversationStore` (read-only view on `conversation` table) to
the :proto Agent interface, plus `agent.renameConversation(id, title?)`
command. Client-side cache in :client is built from a snapshot
(`remote.listFlow(0)` → `local.upsert(...)`) + live updates via
`outbox.agentEvents()` (Created/Deleted/Renamed/Touched).
Changes:
- :journal-api — split `ConversationStore` (read-only: get/list) and
`MutableConversationStore` (CRUD: upsert/delete/rename/touch);
`ConversationStore` gained `listFlow` (cold-flow paging via `list`).
- :outbox-api — `AgentEvent.Touched(date, id, updatedAt)` event so
client cache stays fresh after `send()` (which bumps `updatedAt`).
- :proto.Agent — added `conversationStore: ConversationStore` property,
added `renameConversation(id, title?): Instant?` command, removed
`getConversations(offset, limit)` (now: `conversationStore.list(...)`).
- :server — `GET /conversations` now returns `List<ConversationRecord>`
(lightweight metadata, no handle/image-support flags); `PATCH
/conversations/{id}` uses `agent.renameConversation` and returns
the updated `ConversationRecord`.
- :journal-inmemory — expanded targets to jvm+macos+linux+mingw (matches
:client); moved `InMemoryMutableConversationStore` here from
:storage-inmemory so :client can use it without pulling ios targets.
- :storage-inmemory — depends on :journal-inmemory.
- :storage-ksqlite — pre-staged rename `KsqliteConversationStore` →
`KsqliteMutableConversationStore` to match the new interface split.
- :standalone — `ChatAgent` exposes `conversationStore` as a read-only
view of its `mutableConversationStore`; emits `AgentEvent.Touched`
after each `send()` (after `conversationStore.touch(id, ts)`).
- :client — new `HttpConversationStore` (read-only HTTP impl);
`AgentikAgent` wraps the agent with `wrapWithLocalConversationCache`
so the client sees an in-memory cache (snapshot + outbox events)
instead of direct HTTP. Cache scope + HttpClient + background job
all cancelled in `agent.close()`.
- :client/README — new «Кэш списка бесед» section with the
`listFlow → upsert` / `agentEvents → apply` pattern and a note that
`conversationStore` is read-only (writes only via Agent commands).
All 96 jvmTest tasks green.
CI red on tag 10 release #1983: client:compileCommonMainKotlinMetadata
and :compileKotlinLinuxArm64 both failed with:
e: ReconnectingOutbox.kt:154 Unresolved reference 'Volatile'
e: ReconnectingOutbox.kt:227 Unresolved reference 'Math'
@Volatile is JVM-only annotation; java.lang.Math is JVM-only API. On
linuxArm64/macosArm64 they don't resolve.
Fix:
- @Volatile private var lastSeen: Instant? → AtomicReference<Instant?>
(kotlin.concurrent.atomics, same module as the AtomicBoolean already
used for ). .load() / .store() / @OptIn(ExperimentalAtomicApi::class).
- Math.pow(m, e) → m.pow(e) via kotlin.math.pow import.
commonMain stays KMP-clean; jvmTest green (95 tasks); linuxX64 / linuxArm64
/ mingwX64 / macosX64 / macosArm64 compile green.
Android-client review item 8: AgentikAgent(id, baseUrl, engineFactory,
token) constructor was well-documented per parameter but lacked guidance
on what client must persist locally. AgentSettingsRepository rejected —
UI frameworks persist settings differently (JSON file, Keychain, Android
DataStore, NSUserDefaults), lib doesn't impose format.
KDoc on AgentikAgent now contains table of {clientId, baseUrl, token}
with where each comes from and the critical constraint that clientId
must be generated once on first install (UUID.randomUUID().toString())
and never changed — otherwise log multiplexing on the server breaks.
client/README.md 'persistence' section mirrors this for offline reading
with a minimal JSON example.
KDoc-only change. No code, no API surface.
Three protocol-level changes from Android-client review (items 1-3, 5-6):
1) toolName denormalization in ToolResult (3 layers):
- :outbox-api/Event.ToolResult: +toolName: String? = null
- :journal-api/MessageRecord.ToolResult: +toolName: String? = null
- :proto/Message.ToolResult: +toolName: String? = null
- :storage-ksqlite, :journal-ksqlite ResultPayload codec: +toolName
- :standalone/ToolDispatcher, ConversationLoop: thread toolName = call.name
Nullable + default = backward-compat for already-persisted histories
and existing clients.
2) Drop proto/Event.kt, AgentEvent.kt, CommonEvent.kt typealiases.
is proto.Event.End failed with 'Unresolved reference End' (alias
loses nested-class access). Use pw.binom.agentik.outbox.{Event,
AgentEvent, CommonEvent} directly everywhere — :proto already has
api(:outbox-api), the package is visible to consumers, no shim
needed. 21 files rewired, 3 files deleted.
3) Rename Event.ToolResult.id → toolCallId (option B per user).
In :outbox-api Event.ToolResult.id == Event.ToolCall.id (one value,
one name); the persistent journal keeps MessageRecord.ToolResult.id
as its own PK + toolCallId as FK to the call — different semantics,
left untouched. Fixed ToolDispatcher bug: emitted id = resultId
while KDoc claimed id == ToolCall.id; now emits toolCallId = callId.
4) Remove Conversation.events() from :proto; OutboxStore is sole event source.
Conversation is a pure per-conversation abstraction (send/getMessages/
rename/close). Live events only via agent.outbox.conversationEvents/
agentEvents/events. HTTP route /conversations/{id}/events stays for
wire-compat but routes through outbox internally (map { it.event }).
jvmTest green (95 tasks).
ci.yml пытался собрать :agentik-cli:shadowJar, но проект
закомментирован в settings.gradle.kts. Это ломало build-jvm job
с 'project agentik-cli not found'. Убираем шаг.
Дополнительно: text-embedding-kmp 4 → 5 (v4 в caffeine имел только
jvm+android варианты — native-resolve падал в :memory-md-vector). v5
содержит полный набор klib'ов (linuxX64/Arm64, mingwX64, macosX64/Arm64,
iosX64/Arm64/SimulatorArm64).
- :memory-md-vector (KMP jvm+linuxX64+mingwX64): .md-файлы как source of
truth, векторный индекс (sqlite-vec) как derived cache. reconcile()
на старте: orphan-cleanup + content-hash-gated re-embed. Гибридный
скор 0.7*vector + 0.3*keyword. Заменяет EmbeddingProvider на
KMP-TextEmbeddingExecutor из :memory-api.
- :reflection-api: новый 4-й API-модуль (Reflection, ReflectionStore,
ReflectionEvent). Зависит только от :memory-api.
- :journal-api получил ConversationRecord/ConversationStore/Ids (бывший
:message-store-api, полностью удалён). :outbox-api получил Event,
CommonEvent, AgentEvent (бывший :event-store).
- :memory-api получил MemoryVectorIndex + NoteMatches +
TextEmbeddingExecutor (suspend-обёртка над TextEmbeddingExtractor).
- :memory-vector KMP-цели достигнуты через commonMain-only TextEmbedding-
Executor, EmbeddingProvider выпилен; :memory-md-vector тянет
text-embedding-api транзитивно через :memory-api.
- :standalone flatten в commonMain/commonTest завершён (тесты из jvmTest
переехали в commonTest). Включён optional деп :memory-md-vector через
AGENTIK_MEMORY_BACKEND=md-vector.
jvmTest: 96 задач, 407 тестов, 0 падений.
ksqlite 0.1.2 опубликован в Maven Central (был только в локальном ~/.m2);
text-embedding-kmp v4 — в caffeine Nexus (поддержка нативных целей):
jvm, android, linuxX64/Arm64, macosX64/Arm64, iosX64/Arm64/SimulatorArm64.
Без этих апдейтов CI release-пайплайн падал с unresolved-dependencies
на любом свежем коммите после acc7237e5 (введение ksqlite).
Дополнительно: игнорируем локальный opencode config.json.
- Replaced `EmbeddingProvider` with cross-platform `TextEmbeddingExecutor` for native target compatibility.
- Introduced `:memory-md-vector` module combining vector-cache and `.md` file-based memory systems (`hybrid` backend).
- Updated `SiglipEmbeddingProvider` to use KMP `TextEmbeddingExtractor` and streamlined compatibility via `asExecutor`.
- Added hybrid memory backend to `standalone`, supporting `.md` reconciliation with vector-cache for semantic
- `AgentikAgent` now accepts `engineFactory` and an optional `token` to create an internal `HttpClient`, handling all configuration (JSON, Bearer).
- Removed `applyAgentikDefaults` and replaced it with `agentikHttpClient` for `HttpClient` creation with consistent settings.
- Updated `Agent` to implement `AutoCloseable`, ensuring proper resource closure with `agent.close()`.
- Adjusted tests, docs, and examples to align with the new `AgentikAgent` API.
- Introduced a new `:journal-inmemory` module implementing `:journal-api` with an in-memory backend.
- Added `InMemoryJournalStore` for concurrent append, list, and clear operations using `Mutex` and `MutableList`.
- Use cases include tests, dev mode, embedded scenarios, and client-side in-process caching.
- Integrated the module into the project setup and documented usage in `:client/README.md`.
- Added comprehensive
- Removed `:message-store-api` module and associated classes (ConversationStore, ReflectionStore, Ids, etc.).
- Migrated reusable components to `:journal-api` (conversation-related) and `:reflection-api` (reflection-related).
- Updated imports and module dependencies across all projects to reflect new structure.
- Adjusted build scripts and tests for compatibility with the new APIs.
- Added `HttpJournalStore` as an HTTP-backed implementation of `JournalStore` for read-only access to the audit log.
- Integrated `GET /journal/conversations/{id}/messages` endpoint to fetch conversation transcripts with full payloads.
- Updated `AgentClient` to expose `HttpJournalStore` as the `journal` property.
- Adjusted `HttpEventStore` to align with updated endpoint structure (`/outbox/events`).
- Replaced usages of `:message-store-api` and `:working-memory-api` with `:journal-api`, `:outbox-api`, and `:context-api`.
- Deprecated legacy `EventStore` and `MessageStore` interfaces, added `typealias` for backward compatibility.
- Updated imports across all modules with references to `:journal-api` and `:outbox-api`.
- Introduced `journalRoutes` and `outboxRoutes` in `:server` for audit log and live event stream endpoints.
- Adjusted `Agent` to expose read-only `journal` and `outbox` stores for improved modularity and clarity.
- Removed legacy Event and AgentEvent definitions from `:proto`, migrated to `:outbox-api`.
- Storage-related modules have been updated to support the new APIs consistently.
- Introduced a new `:context-ksqlite` module implementing `:context-api` with Ksqlite backend.
- Added a minimal schema (working_memory table + 2 indexes) for runtime context store: lightweight, excludes conversation/message/reflection tables, which are handled in separate modules.
- Initial version supports JVM, Linux, and Windows builds; migrates schema using SQLite PRAGMA.
- Includes fully autonomous in-memory schema migration and tests to validate operations like append, list, clear, and compact.
- Partial duplication of `:storage-ksqlite/KsqliteWorkingMemoryStore`; consumers will migrate incrementally.
- Introduced `MutableMessageStore` for producers with an `append` operation, separate from read-only `MessageStore`.
- Updated all consumers and implementations to use the appropriate interface (`read-only` for observers, `mutable` for producers).
- Improves modularity and ensures compile-time guarantees against unintended write operations in the audit log.
- Extracted `TurnTokens`, `MessageOrigin`, and `MessageEvent` into standalone files.
- Simplified `MessageContext` by externalizing `MessageOrigin`.
- Improves modularity and code maintainability for append-only audit logs.
- Remove agentikHttpClient(engineFactory: HttpClientEngineFactory<T>, ...)
factory from :client; the typed factory parameter pulled engine-specific
config (HttpClientConfig<T>.engine { ... }) and made the library's
factory API look engine-coupled even though the factory itself was
engine-agnostic.
- KDoc and SseTimeout no longer reference CIO as the canonical example.
- :client still exports applyAgentikDefaults(HttpClientConfig<*>) extension;
consumers build HttpClient themselves with their chosen engine.
- :agentik-cli/defaultCliHttpClient updated to construct HttpClient(CIO)
itself and apply agentik defaults inline; CIO-specific config
(requestTimeout = 0) stays in the same block.
- Remove legacy pw.binom.agentik.messageStore.events.EventStore (EventRecord,
EventType) and all three impls (in-memory, sqlite, ksqlite) + tests + .sq
- Drop :storage-bundle module entirely; ChatAgent / ChatConversation /
ConversationLoop / DebugRoutes now take stores individually
(conversationStore, messageStore, workingMemoryStore, reflectionStore,
eventStore) instead of StorageBundle
- Delete server endpoints /events/replay and /conversations/{id}/events/replay;
Route.agentikAgent no longer takes eventStore param
- Add :client/HttpEventStore implementing :event-store/EventStore over HTTP:
events() -> GET /events/all, agentEvents() -> GET /events,
conversationEvents(convId) -> GET /conversations/{id}/events;
exposed via AgentClient.eventStore
- :event-store: add macosX64/macosArm64/linuxArm64 targets to match :client KMP
- :working-memory-api: drop api dep on :message-store-api (no longer needed)
- :storage-{inmemory,sqlite,ksqlite}: drop deps on :storage-bundle
Выделяет append-only message log в отдельный KMP-модуль.
Цель — разделить ДВЕ сущности по своей природе:
:message-log-api — append-only audit log (User/Assistant/ToolCall/
ToolResult/Error). Никаких update, только insert + read.
Это иммутабельная история диалога.
:working-memory-api — mutable runtime context (compact, summary, WM order).
Live state. Compaction-логика.
Раньше оба жили в :message-store-api, что:
- смешивало контракты: append-only audit vs mutable runtime;
- делало невозможным лёгкого клиента который читает только audit log
без WM-runtime зависимости;
- затрудняло compaction-логике жить в одном модуле с audit-записью.
Миграция:
- В :message-log-api переехали: Content, MessageRecord, MessageStore,
MessageContext (с MessageOrigin), MessageEvent, TokenStats, TurnTokens,
helpers (encode/decodeBodyPayload, MessageBodyPayload, BodyDecoded).
Пакет pw.binom.agentik.messageLog.
- В :message-store-api остались: ConversationStore, ConversationRecord,
ReflectionStore, Ids, legacy events.EventStore (paginated replay).
Пакет pw.binom.agentik.messageStore.
- :working-memory-api: обновил deps (api → :message-log-api для Content/MessageContext).
- 23 consumer-файла обновлены (FQN renames).
- storage-sqlite/ksqlite: убраны недостижимые ветки Summary/System
(эти synthetic records живут ТОЛЬКО в :working-memory-api, не попадают
в audit log :message-log-api).
Файлы:
+ :message-log-api (5 файлов, ~280 строк)
- :message-store-api (5 файлов, ~430 строк)
~ 23 файла обновлены
Совместимость схем не меняется. Все 5 storage impl'ов (3 backend × 5 store)
работают на тех же таблицах.
Первый concrete impl :event-store. ConcurrentLinkedDeque + eviction на
каждом append (amortized O(1) при стабильном размере буфера).
Контракт (по требованию пользователя):
- maxMessages: Int? — nullable, NO default (явный null = unlimited)
- ttl: Duration? — nullable, NO default (явный null = forever)
- оба null → store forever
- любой non-null → соответствующий eviction policy
Eviction:
- evictExpired(): pollFirst пока head.date < (now - ttl)
- evictOverCapacity(): pollFirst пока size > maxMessages
- обе вызываются синхронно на каждом append
Live tail: MutableSharedFlow(capacity=4096, DROP_OLDEST).
Producer никогда не блокируется — slow subscriber получает свежие события,
за полным покрытием — fallback в :message-store-api.
Tests (13):
- append stores all (both null)
- maxMessages cap evicts
- ttl evicts older than threshold
- both policies apply together (cap=2 + ttl=100ms, a/b/c appends)
- events(null) replays buffer then collects live
- events(after) catches up + live
- earliestEventDate (oldest + empty buffer = now)
- conversationEvents/agentEvents фильтры (default impl в :event-store)
- close clears buffer
- negative maxMessages throws at construction
internal helper snapshot() для тестов — production code использует
events()/events(after) для доступа к буферу.
KMP: jvm + linuxX64 + mingwX64.
Методы conversationEvents() и agentEvents() теперь default в интерфейсе:
реализуют фильтрацию через [events] + filterIsInstance.
Зачем:
- Минимальный контракт для impl — достаточно реализовать только events().
- InMemoryEventStore и любой новый backend получают работающие
specialized views автоматически, без копипасты filterIsInstance.
- Persistent impl'ы (SQL/ksqlite) могут override'нуть для эффективности
(WHERE conversation_id = ? — не тянуть все events в память), но
контракт корректен и без override.
Семантика идентична:
- conversationEvents(after, null) = events().filterIsInstance<Conversation>()
- conversationEvents(after, "c-1") = events()...filter { it.conversationId == "c-1" }
- agentEvents(after) = events().filterIsInstance<Agent>()
Imports добавлены: kotlinx.coroutines.flow.filter, filterIsInstance.
Расширяет EventStore тремя вариантами подписки (вместо одного events()):
- events(after) → Flow<CommonEvent>
весь поток (микс Agent + Conversation)
- conversationEvents(after, conversationId?)
→ Flow<CommonEvent.Conversation>
опциональный фильтр по conversationId (null = все диалоги)
- agentEvents(after)
→ Flow<CommonEvent.Agent>
только lifecycle (Created/Deleted/Renamed)
Типизированные subtype'ы вместо Flow<CommonEvent> + .filterIsInstance:
- compile-time safety на клиенте (нет cast'ов в CommonEvent.Conversation)
- persistent impl'ы могут делать WHERE conversation_id = ? на уровне БД
Соответствует HTTP-маршрутам в :server:
- GET /events/all ↔ events(after)
- GET /conversations/{id}/events ↔ conversationEvents(after, id)
- GET /events (только agent lifecycle) ↔ agentEvents(after)
README обновлён — таблица caller→method показывает маппинг.
Совместимость: signals не сломаны (добавление, не изменение).
Документирует:
- Три принципа дизайна (TTL внутри, catchup+live в одном Flow,
read-only контракт для observer'ов)
- Архитектуру двухуровневого хранилища событий со схемой
- Reconnect pattern с gap detection
- API EventStore + MutableEventStore (когда какой использовать)
- Таблица: какой caller принимает какой интерфейс
- Текущее состояние: interfaces готовы, implementations в работе
- Зависимости (минимальные: :proto + kotlinx-coroutines)
В том же стиле что и :agent-toolsets/README.md.
Разделяет интерфейс на read-only (EventStore) и write (MutableEventStore).
EventStore (read-only, для consumer'ов):
- events(after: Instant?): Flow<CommonEvent>
- earliestEventDate(): Instant
- close()
MutableEventStore : EventStore (для producer'ов):
- + append(event: CommonEvent)
- suspend, не идемпотентный, может быть silently evicted
Зачем:
- Consumer'ы (server SSE, admin dashboard, parent agents) принимают
EventStore — compile-time гарантия что они не могут писать в store.
- Producer'ы (ChatAgent, sub-agents, A2A-bridge) принимают MutableEventStore.
- Тесты могут использовать EventStore без опасности случайной модификации.
Миграция:
- :event-store пока без implementations, поэтому ничего не сломалось.
- Когда добавим InMemoryEventStore — он будет реализовывать оба
(MutableEventStore = EventStore + append). Подписки получают только
read-only projection через приведение типа.
Также: импорт обновлён AllEvent → CommonEvent (по rename в :proto).
Заменяет generic Event envelope (id, date, payload) на типизированный AllEvent
из :proto. EventStore теперь:
- append(event: AllEvent)
- events(after: Instant?): Flow<AllEvent>
- earliestEventDate(): Instant
Изменения:
- :event-store теперь зависит от :proto (api dependency).
- Event.kt удалён — AllEvent уже живёт в :proto и несёт date, conversationId,
typed envelope (Agent или Conversation variant).
- Generic opaque payload выкинут — typesafety до самого storage.
- append НЕ идемпотентен (AllEvent не имеет уникального id, два retry
дадут дубликат). Документировано: для exactly-once использовать catchup
через :message-store-api (там есть монотонный id).
В KDoc примере reconnect убран лишний null-check у earliestEventDate
(теперь всегда non-null).
Миграция (когда будем интегрировать):
Producer в :standalone перестаёт делать двойную работу
(MutableSharedFlow + persistAgentEvent). Вместо этого — один
eventStore.append(allEvent). Caller'ы SSE будут делать
store.events(after) → Flow<AllEvent>, без ручной конвертации.
Build green на JVM.
Раньше возвращал Instant? — null для пустого буфера. Клиенту приходилось
проверять if (earliest != null && ...) — легко ошибиться.
Теперь всегда Instant. Если буфер пуст, возвращает Clock.System.now()
на момент вызова. Это убирает nullable + сохраняет семантически корректное
поведение:
- Клиент может безопасно сделать store.events(earliest) → получит только
live event'ы, без ложного catchup.
- Если бы возвращали null/DISTANT_PAST/null-check, клиент мог бы ошибочно
подписаться на несуществующий catchup-диапазон.
Edge case (в KDoc): клиент, подключившийся ДО первого event'а, получает
earliest ≈ now. Его lastSeen < earliest → адаптируется в первом poll'е.
Изменение breaking — но :event-store ещё не имеет implementations и
никакие consumer'ы не используют этот метод.
Выделяет bounded-tail event log в отдельный KMP-модуль. Это **новый
контракт** (не замена :message-store-api/events/EventStore — тот пока жив).
**Двухуровневое хранилище событий**:
1. :event-store (этот PR) — короткий bounded tail, авто-TTL.
Для live SSE и recent replay (catchup после короткого disconnect).
2. :message-store-api (MessageStore) — полный audit log, никогда не
эвиктится. Source of truth для длинного disconnect / audit query.
**API**:
- append(Event) — put, идемпотентный по id
- events(after: Instant?): Flow<Event> — catchup + live в одном Flow
- earliestEventDate(): Instant? — для gap detection у клиента
**Чего НЕТ в API** (by design):
- delete/prune методов — TTL/cap eviction полностью на стороне impl.
Caller'ы не должны забыть вызвать cleanup (single source of truth).
- conversationId / type в Event — opaque payload, тип envelope'а
решает producer.
Пока interfaces only — implementations (InMemoryEventStore, persistent)
появятся в следующих коммитах. Никаких изменений в существующем
EventStore в :message-store-api, чтобы не ломать зависимости.
KMP targets: jvm + linuxX64 + mingwX64 (Apple auto-disabled на Linux).
Modules:
+ :event-store — новый, commonMain only, ~150 строк
Разделяет монолитный :storage-core на 3 модуля с чёткими границами:
:message-store-api — MessageStore, ReflectionStore, EventStore, ConversationStore +
Content, Payload, MessageContext, Ids, MessageEvent
(audit log + event stream)
:working-memory-api — WorkingMemoryStore + WorkingMemoryEntry
(runtime context с compaction)
:storage-bundle — StorageBundle агрегатор, зависит от обоих
(только для server-side runtime)
Пакеты:
pw.binom.agentik.storage.* → УДАЛЕНО
pw.binom.agentik.messageStore.* — append-only API
pw.binom.agentik.messageStore.events.* — EventStore + EventRecord
pw.binom.agentik.workingMemory.* — WM API
pw.binom.agentik.storageBundle.* — aggregator
Зачем:
- Тонкий клиент может подтянуть ТОЛЬКО :message-store-api (~15KB, нет
compaction-логики, нет MessageStore+WorkingMemoryStore cross-deps).
- Android-agent в будущем подключит :message-store-api для audit log,
серверный runtime — :storage-bundle со всем.
- Компиляционные границы защищают от случайной зависимости от WM
в read-only клиентах (раньше один :storage-core не давал такой
гарантии).
Миграция:
- Имплементации (:storage-inmemory, :storage-sqlite, :storage-ksqlite)
обновили package + добавили deps на оба API модуля + :storage-bundle.
- Тесты из :storage-core (PersistenceTest, SqliteStoresMigrationTest,
TokenStatsTest) переехали в :standalone, получили testImplementation
на оба API модуля и импорты новых типов.
- 52 файла в :standalone, :agent-toolsets, :llm-tools, :server, :client,
:agentik-cli обновили FQN.
- :storage-core удалён.
Совместимость схем не меняется — все 5 impl'ов (3 backend × 5 store) хранят
данные в тех же таблицах, миграция между Sqlite и Ksqlite возможна через SQL dump.
Тесты:
standalone 178 ✅
agent-toolsets 36 ✅
storage-inmemory 47 ✅
storage-sqlite 17 ✅ (включая переехавшие persistence/* + tokenStats)
storage-ksqlite 36 ✅
---
Total: 314 tests, 0 failures
mutex в kotlinx.coroutines НЕ reentrant — при вызове get() изнутри withLock
получаем deadlock. ConversationStore.delete() и rename() использовали именно
этот паттерн для проверки существования.
Fixed: заменил на raw SELECT 1 FROM conversation WHERE id=? и
SELECT updated_at FROM conversation WHERE id=? — те же проверки, без
повторного взятия mutex.
Discovered by full-test-suite run: 3 tests in KsqliteConversationStoreTest
были в UncompletedCoroutinesError (UncompletedCoroutinesError после 1 минуты
ожидания), хотя отдельный прогон EventStore (где нет вызовов get() внутри
mutex) проходил. После фикса все 36 тестов проходят:
- KsqliteEventStoreTest (11)
- KsqliteConversationStoreTest (9)
- KsqliteMessageStoreTest (5)
- KsqliteWorkingMemoryStoreTest (5)
- KsqliteReflectionStoreTest (6)
Расширяет :storage-ksqlite (ранее только EventStore) — все 5 store'ов из
:storage-core теперь имеют ksqlite-имплементацию с теми же контрактами:
- KsqliteConversationStore (CRUD диалогов, каскадный delete messages+WM)
- KsqliteMessageStore (audit log, listAll + tokenStats через encode/decode)
- KsqliteWorkingMemoryStore (compaction с транзакцией, max order_idx)
- KsqliteReflectionStore (insert/listRecent/listForConversation/deleteOlderThan + events flow)
- KsqliteEventStore (replay-after-disconnect, INSERT OR REPLACE)
Схемы таблиц полностью идентичны :storage-sqlite (conversation, message,
working_memory, reflection, agent_event) — данные совместимы между двумя
backend'ами, можно мигрировать через SQL dump.
MessageCodecs.kt — hand-rolled encode/decode для MessageRecord ↔ payload_json.
Скопирован из :storage-sqlite где helpers были private; в :storage-ksqlite
свой набор, синхронизация — ответственность разработчика (см. KDoc).
KsqliteStores.kt — фабрика open(path) / inMemory(name), возвращает bundle
из 5 store'ов + SQLiteConnection. Аналог SqliteStores.open/inMemory.
Encoding helpers (CallPayload/ResultPayload/ErrorPayload, encodeStringArray
для Reflection.weakSpots) продублированы — alternative это вынести в
:storage-core, но это пока YAGNI.
Тесты:
- KsqliteEventStoreTest — 11 tests ✅ (passes на JVM и linuxX64)
- KsqliteConversationStoreTest — 9 tests ✅
- KsqliteMessageStoreTest — 5 tests ✅
- KsqliteWorkingMemoryStoreTest — 5 tests ✅
- KsqliteReflectionStoreTest — 6 tests ✅
Build verified: компилируется на JVM и linuxX64. nativeMain-deps
(kotlin-logging) перенесены в jvmMain т.к. KMP-артефакта нет.
Известные проблемы:
- gradle test runner иногда не финализирует XML-результаты на Linux FS
(in-progress-results-generic*.bin остаются). Тесты при этом проходят
(видно в отчёте build/reports/tests/jvmTest/*.html), но счётчик
tests="N" в XML не аггрегируется.
- Storage bundle в KsqliteStores возвращает StorageBundle (KMP),
но стандартный app wiring пока не подключает его — :standalone
использует SqliteStores. Подключение = следующий шаг.