- :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. Подключение = следующий шаг.
Добавлена собственная авторизация по токену. Это ОТДЕЛЬНАЯ подсистема:
библиотека A2A (pw.binom.a2a) имеет свой независимый token, общих типов
и общей логики не вводится.
Поведение по умолчанию не меняется: token = null -> авторизация выключена,
сервер открыт (обратная совместимость), CLI/TUI не затронуты.
Сервер (:server):
- новый route-scoped плагин BearerTokenPlugin (BearerTokenConfig);
- agentikAgent(agent, path, token) ставит плагин на всё поддерево /agentik,
когда token != null; иначе плагин не устанавливается;
- при несовпадении заголовка Authorization: Bearer <token> -> 401 Unauthorized;
- /health всегда открыт (liveness для балансировщика).
Клиент (:client):
- defaultAgentikHttpClient(token) навешивает Authorization: Bearer <token>
через DefaultRequest на весь HttpClient -> накрывает все 10 вызовов и оба SSE;
- AgentikAgent(id, baseUrl, token, httpClient) — token необязательный,
9 существующих мест создания агента не тронуты.
Standalone:
- AgentSection.authToken (env AGENTIK_TOKEN) -> /agentik;
- AgentSection.a2aToken (env AGENTIK_A2A_TOKEN) -> /a2a;
- два независимых значения, связи между ними нет.
Тесты: BearerTokenTest (5), BearerHeaderTest (3) — 401 без токена и с чужим,
200 с верным, /health открыт, null -> открыто. Мутационная проверка пройдена.
- ci.yml/release.yml: LANG/LC_ALL=C.UTF-8 — иначе Kotlin-компилятор падает
с InvalidPathException на именах тестов с типографским тире (LANG=C → ASCII)
- имена тестов: типографское тире U+2014 заменено на ASCII-дефис (16 шт)
- release.yml переведён на общий composite-action subochev/devops/publish@main
(как у asr-kmp/litert-kmp/embedder-kmp); версия = имя тега релиза
Standalone refactor — modularity + correctness improvements after
STANDALONE-REVIEW findings. Touches ~30 files. Build green, 178 tests pass.
(1) Module extractions — generic components out of :standalone:
• :llm-tools (new KMP module, package pw.binom.agentik.llm.tools)
- LlmReflector, SkillMiner, LlmMemoryReviewer, LiteLlmContextCompactor
- Parsers: ReflectionParser, SkillMiningParser, ReviewDecisionParser
- Prompts: ReflectionPrompts, SkillMiningPrompts, ReviewPrompts
• :mcp-bridge (new JVM module, package pw.binom.agentik.mcp.bridge)
- McpConfig, McpRegistry, McpLiteToolAdapter
• NamedTool moved from :standalone to :agent-toolsets/commonMain
- Generic (name + LiteTool) wrapper, used by both :mcp-bridge
and :standalone's tool dispatcher
:standalone loses ~1400 lines, depends on the two new modules.
(2) Background work → event-driven (no more interval-polling):
• New :standalone/agent/BackgroundEvents.kt — internal event bus:
- ToolCallEvent.Succeeded/Failed (emitted by ToolDispatcher after invoke)
- CompactionEvent.Triggered (emitted by CompactionCoordinator pre-delete)
- ConversationLifecycleEvent.Closing (emitted by ConversationLoop.close)
• BackgroundScheduler rewritten as event subscriber:
- On Closing: final reflection + skill mining (last-chance extraction)
- On Compaction (turnsToDelete > 10): skill mining (debounced 60s)
- On ToolFailure x2 in 60s window: reflection (debounced 5min)
- Dropped: maybeScheduleReview/Reflection/SkillMining (interval-based)
- Dropped config: memoryReviewInterval, reflectionInterval, skillMiningInterval
• ToolDispatcher emits ToolCallEvent after each invoke.
• CompactionCoordinator emits CompactionEvent before workingMemory.compact().
• ConversationLoop.close() emits Closing BEFORE agentScope.cancel() so the
subscription gets to run final reflection/mining.
Net effect: typical 30-turn conversation runs ~38 LLM calls (was: 30 main +
3 review + 3 reflection + 2 mining). With event-driven, review/mining only fire
when their triggers actually make sense (compaction about to delete, or
conversation closing).
(3) AppConfig single source of truth:
• Replaces AgentikConfig + LlmConfig.fromEnv + McpConfig.fromEnv with one
AppConfig.fromEnv() that reads all ~25 env vars in a single pass.
• Sections: AgentSection, LlmSection, McpSection, MemorySection,
EmbeddingSection, ReflectionSection, SkillMiningSection, DebugSection.
• OPENAI_CONTEXT_WINDOW / AGENTIK_GOOGLE_CONTEXT_WINDOW no longer
read twice (was a bug per STANDALONE-REVIEW E3).
(4) Other fixes inherited from earlier waves:
• Hardening — size caps on user-input boundaries:
MAX_MEMORY_CONTENT_LEN=32KB, MAX_SKILL_BODY_LEN=64KB,
MAX_MCP_CONFIG_BYTES=1MB, MAX_A2A_REPLY_LEN=10MB, MAX_PORT=65535,
blank-rejection in LlmConfig.requireEnv, URL/command validation.
• Single scope — :standalone/agent/ConversationLoop has one
agentScope (was: scope + backgroundScope).
• liteConvRef race fix — capture-then-use pattern replaces !!-after-read;
close() + runTurn.finally race on LiteConv JNI handled via
AtomicReference.getAndSet.
• SkillMiner.maxTurns / LlmReflector.maxTurns exposed as public (needed
by BackgroundScheduler for prompt sizing).
• Tests: MemoryWiringTest updated for new compaction-triggered review
behavior; all parser/test imports updated for new packages.
Test results: 178/178 in :standalone, 36/36 in :agent-toolsets — all green.
PlantUML diagrams for future agent architecture (Android, multi-user
chat, sub-agents, A2A):
- 01-module-layers.md — целевая модульная структура
- 02-agent-composition.md — AgentBuilder DSL + MemoryBackend.exposesTools()
- 03-multi-user-chat.md — mention-detection sequence
- 04-sub-agents.md — spawnChild + Flow<SubAgentEvent> + A2A
- 05-android-stack.md — что меняется на Android vs Standalone
Каждый .md включает пред-рендеренный SVG (показывается во всех markdown
viewers без PlantUML plugin) + PlantUML source в code block (для
редактирования). SVG нужен потому что PlantUML требует Graphviz dot
для рендеринга — без него IntelliJ/VSCode выдают ошибку.
Регенерация SVG после правки PlantUML-source:
docker run --rm -v "$PWD:/work" plantuml/plantuml -tsvg /work/docs/diagrams/*.md
- conv-ls/new/show/delete/rename -> вложенные под agentik-cli conv
- ConvCommand — Subcommand-родитель, регистрирует 5 дочерних
команд в init { subcommands(...) }
- ConvSubcommand(name, description) extends AgentikSubcommand —
базовый класс для всех conv-подкоманд (наследует --server/--id)
Два гоччаса kotlinx.cli 0.3.6 которые пришлось обойти:
1. parent.execute() вызывается ПОСЛЕ leaf.execute() всегда когда
leaf достигнут через parent. Если parent делает что-то в
execute() — вывод дублируется после каждой дочерней команды.
Фикс: ConvCommand.execute() = Unit (no-op). Дочерние команды
смотрятся через 'agentik-cli conv --help'.
2. По умолчанию 'conv new --server ...' парсится как
conv[--server ...] + позиционный arg 'new' на уровне
родителя, и дочерняя команда не запускается. Фикс:
ArgParser(strictSubcommandOptionsOrder = true) — все аргументы
после имени subcommand передаются в его парсер.
Smoke (linuxX64 kexe + JVM fatjar): conv ls/new/rename/show/delete
+ msgs/send/interrupt/info работают.
- Добавил нативные таргеты с реальной реализацией (не stub-ы):
- linuxX64 kexe ~5 МБ — собран, запускается, проходит
smoke против 192.168.76.166 (--help, info, conv-ls,
conv-new, send со стримом response-events, AGENTIK_SERVER
env-переменная).
- mingwX64 .exe ~6 МБ — собирается через кросс-компиляцию с Linux.
- macosX64 / macosArm64 — на Linux-хосте не линкуются (нужен
macOS-раннер, Apple Mach-O), но target-объявления + entryPoint
валидны.
- entryPoint на K/N — FQN без 'Kt': pw.binom.agentik.cli.main
(на JVM по-прежнему AgentikCliKt через mainClass.set).
- platformEnv: expect/actual split. Native actual — getenv()
из platform.posix через kotlinx.cinterop, помеченный
@OptIn(ExperimentalForeignApi::class).
- linuxArm64 у :agentik-cli отсутствует — kotlinx.cli 0.3.6 не
публикует klib для linuxArm64. У :client linuxArm64 сохранён
(асимметрия допустима: :client нужен только :agentik-cli,
который на linuxArm64 не работает).
- README обновлён: target matrix, env-vars, native entry-point,
платформенные детали.