Files
strata-ctl/README.md
T
adm f74d53e446 memory: per-session semantic memory (strata-memory crate, Qdrant Edge + BGE-M3)
remember/recall/forget agent tools, one-way opt-in latch with embedder gate, fail-open Store-authoritative design, keyword fallback, model-id rebuild, GUI toggle + i18n; docs updated; split-debuginfo=unpacked
2026-11-30 11:37:48 +01:00

531 lines
32 KiB
Markdown

# strata-ctl
A Rust control layer for the [Strata](https://github.com/Niko1221/Strata) inference
engine: an OpenAI-compatible HTTP API that drives the engine over its native line
protocol.
`strata-ctl` is a from-scratch **Rust rewrite of Strata's control framework** (the
Python "serve" layer that sits between HTTP clients and the C++ inference engine).
It is not a fork of the engine itself: the engine stays the upstream C++ binary
(`strata-inkling`); this project replaces the layer that supervises it and exposes
it to the network.
## Why Rust?
We believe Rust is a much better fit than Python for a process meant to run
**stably, unattended, on a server** for long periods:
- **Memory safety without a garbage collector** — no GC pauses, no reference-count
cycles leaking over weeks of uptime, no interpreter runtime to babysit.
- **Predictable latency and throughput** — compiled, no GIL, async I/O on `tokio`
with explicit control over blocking work.
- **Fearless concurrency** — the compiler enforces the ownership rules that keep a
shared, long-lived engine supervisor honest under concurrent requests.
- **A single self-contained binary** — trivial to deploy, supervise (systemd) and
reproduce; no virtualenv, no dependency drift at runtime.
The original Python layer remains the **behavioral specification**: this rewrite
aims to match what it does on the wire, while being a more dependable thing to
leave running on a server.
## Relationship to Strata
- **Strata** — "Run powerful AI on your own computer. Chat, code and work with
images, locally." Free, open source (MIT), by **Niko1221** and the Strata
contributors: <https://github.com/Niko1221/Strata>.
- This project targets Strata's **Inkling** engine (`strata-inkling`, the
`inkling2_loop` architecture) and its in-process Vision. The API layer is built
behind a model-agnostic `Formatter` seam, so other dialects can be added later.
- All credit for the engine, the model format and the original control-layer
behavior goes to the Strata project and its author. `strata-ctl` is an
independent reimplementation of the control layer only.
## Features
OpenAI-compatible endpoints:
- `POST /v1/chat/completions` — streaming (SSE) and non-streaming.
- `GET /v1/models`, `GET /health`.
Anthropic-compatible endpoint:
- `POST /v1/messages` — the Anthropic Messages API (streaming + non-streaming),
translated onto the same engine: `system`, text/image/thinking/tool_use/
tool_result content blocks, tools (`input_schema`), `tool_choice`, sampling and
`stop_sequences`. Responses use Anthropic content blocks and `stop_reason`
(`end_turn` / `max_tokens` / `tool_use`); streaming emits the
`message_start` / `content_block_*` / `message_delta` / `message_stop` sequence.
Behavior implemented and validated against the real Inkling engine:
- **Chain-of-thought separation** — thinking is streamed live as
`reasoning_content`, distinct from the answer `content`.
- **Images** — OpenAI / Responses / Anthropic image parts (base64 data URLs,
http(s) URLs, local paths) are materialized and handed to the engine's
in-process Vision; unsupported formats are normalized to PNG.
- **Tool calling** — structured OpenAI `tool_calls` in the llama.cpp `--jinja`
style: the server renders tool declarations and parses the model's calls;
**execution is client-side** (the server never runs tools).
- **Stop sequences** — incremental matching with hold-back, so a stop string split
across streaming deltas is still caught.
- **Abort on client disconnect** — generation is stopped when the SSE client goes
away, freeing the engine for the next request.
- **Sampling** — per-request knobs override config defaults field-by-field
(`temperature`, `top_p`, `top_k`, `min_p`, penalties, `seed`); `top_k = 0` is
treated as "disabled", not greedy.
Operational hardening:
- Graceful shutdown on **SIGINT and SIGTERM**; the engine is signalled without
blocking on an in-flight request.
- Configurable startup and silence-watchdog timeouts.
- Optional **API key** auth (`Authorization: Bearer <key>` or `x-api-key`) and a
**Host allowlist** (`allowed_hosts`, DNS-rebinding protection); `/health` stays
open. A warning is logged when binding a non-loopback address with no key set.
- Blocking image I/O runs off the async event loop; temp files are cleaned on every
exit path; image fetches have a timeout, a size cap and a basic SSRF guard.
## Web GUI
A minimal, **mobile-first** chat GUI is served by the same binary at `GET /` (assets
under `/assets/...`, embedded via `rust-embed` — no Node, no build step, works
offline, same-origin so no CORS). It is a thin client over a **session-aware API**:
- `GET /` — the chat shell (responsive: an off-canvas session drawer on phones, a
persistent sidebar on wide screens with a **drag-resizable separator** between the
session list and the chat — width clamped and persisted; streaming answers with a
collapsible "thinking" panel; touch-friendly targets and safe-area insets).
- `POST /api/sessions`, `GET /api/sessions`, `GET/PATCH/DELETE /api/sessions/{id}`,
`GET /api/sessions/{id}/messages` — session CRUD and the **sliding-window**
transcript: the same recent messages the model sees (filtered in SQL by the
persisted `window_start`), wrapped as `{messages, window_start, total}` so the
GUI can flag older turns as omitted-but-preserved. The full history is never
shipped to the browser.
- `POST /api/sessions/{id}/chat` — append a turn; the server loads the stored
context, runs inference (streaming SSE or not) and persists the new turns with
their token usage.
- `GET /api/stats` — the stats dashboard payload: persistent totals (sessions,
messages, cumulative prompt/completion/total tokens, tool calls), the current
inference context (`last_prompt_tokens`, the latest turn's prompt), per-session
and per-day breakdowns, plus live engine status and a since-startup
decode/prefill speed gauge.
- `GET/PUT /api/settings/defaults` — the global default settings template.
- `POST /api/uploads` — store an uploaded file (base64) in the shared upload dir;
returns metadata (kind, token count, path). Attach the returned id to a chat turn.
- `GET /api/sessions/{id}/download?path=…&name=…` — serve a file the agent shared
via `share_file` as an attachment (`application/octet-stream`,
`Content-Disposition: attachment`, `X-Content-Type-Options: nosniff`). The path is
re-validated server-side against the session's allowed roots (see **Agent mode**);
an out-of-bounds path is a 400, an unknown session a 404 — no bytes leak.
- `PATCH /api/sessions/{id}` — rename (only before the first interaction) and/or
replace the session's own settings instance.
**Rendering.** Assistant replies are rendered server-side from Markdown to
sanitized HTML (`src/render.rs`, `pulldown-cmark` + `pulldown-latex`): headings,
lists, tables, code, links and **LaTeX math** (`$…$` inline, `$$…$$` block)
compiled to native **MathML** — no client-side math library, no Node. Raw HTML in
model output is escaped and link/image URLs are scheme-filtered
(`http`/`https`/`mailto`/relative), so a reply can never inject script. The
rendered HTML travels as `content_html` beside the raw text in `GET …/messages`
and in the agent `final` event; the GUI injects it via `innerHTML` **only for
assistant bubbles**, while user text stays plain `textContent`.
**Settings & identity.** Each session owns a *settings instance* (system prompt,
notes, sampling) snapshotted from the global defaults at creation
(**copy-on-create**): editing a session affects only it, editing the defaults
affects only *future* sessions — no retroactive surprises. The user jots the
chat's purpose in **notes**. The framework assigns an evocative name (a curated
word list); it is editable only before the first interaction, then **immutable**.
At that first interaction a personal workspace folder is created
(`~/.strata-ctl/sessions/<name>/`, under the configurable `workspace_root`) and a
structural identity reminder ("your name is …, your personal folder is …") is
prepended to the model's context — not an editable setting. The GUI exposes all of
this in a ⚙️ settings panel (per-session or general).
**Context composition.** A dedicated **context compositor** (`src/context.rs`)
assembles the model prompt from named sections delimited by `<NAME>…</NAME>`,
each closed by its tag plus a blank line so boundaries are explicit. The static
sections — `SYSTEM_PROMPT` (identity + speaker convention + the session's system
prompt) and `TOOL_USE` (a compact tool manual) — live in the SQLite
`context_sections` table: seeded, editable without recompiling, and extensible by
adding a row. The interactive `DIALOG` region opens with `<DIALOG>` and is left
**open** (no trailing closer) around the real role messages (history + new turn),
so the engine keeps its turn structure. The open tail is deliberate: a moving
`</DIALOG>` after the last user turn shifts every turn and breaks the engine's
prefix checkpoint (`RESUME`), forcing a full re-prefill; leaving DIALOG open keeps
the prompt prefix byte-stable so the engine reuses its cached KV and only the
newest exchange is prefilled. The engine's `RESUME` cache-hit count is surfaced
per turn as `usage.cached_tokens` (the GUI badge). A **static marker** right after
the `<DIALOG>` opener tells the model it is viewing a sliding window (older turns
omitted; the first visible turn is not necessarily the chat's first message) — being
static, it keeps the prefix cache-stable. Every turn carries a
prompt-only `[SPEAKER: name - YYYY-MM-DD HH:MM]` provenance stamp in the server's
local time — framework metadata for the model, **never shown in the browser**: any
tag the model echoes back is stripped from stored/displayed content and from
history before re-tagging, breaking the duplication loop.
**Uploads.** The 📎 button attaches files and images. Bytes land in a single
**shared** store (`~/.strata-ctl/uploads/`, filename converted to a uuid keeping the
extension); nothing is bulk-injected into context. Content is classified by
*sniffing* (not extension) and routed: **images** go through the Vision bridge
(pixels, not a path); **small text** (≤ ~2000 tokens, measured with the model's own
tokenizer) is inlined; **large text and binaries** are handed to the agent as a path
with a reminder to inspect them selectively via `shell_exec` — binaries never enter
the context directly. The `shell_exec` output cap is a second safety net.
**Statistics.** The "Statistiche" button opens a live dashboard over the
*persistent* history — our angle on the reference's ephemeral request monitor:
overview cards (engine model / context window / idle-busy, **current context** —
the latest turn's prompt size, i.e. what we actually send to inference now —
token-weighted **decode speed** and prefill speed since startup, **cumulative**
prompt/completion/total tokens, sessions, messages, tool calls), a **daily token
chart** (stacked prompt/completion per UTC day) and a **per-session breakdown**
with relative token-share bars. The cumulative prompt total is a *lifetime*
counter, **not** the context size: every turn re-sends the whole retained window,
so summing per-turn `prompt_tokens` re-counts that window each turn (and includes
the cache-resumed prefix); the dedicated **current-context** card
(`last_prompt_tokens`) reports the actual inference context instead. `GET /api/stats`
returns the store aggregates plus a live engine status and an in-memory performance
gauge (token-weighted over the requests served since startup, from the engine's
`DONE` timings); the view polls every 2s while open. History totals survive
restarts; the speed gauge resets with the process.
The standard `/v1` API stays **stateless**; conversation context lives server-side
in an embedded **SQLite** database (default `~/.strata-ctl/data/sessions.db`,
override with `db_path`). Storage sits behind a `Store` trait so it can be swapped
(the planned direction is **ArangoDB**, multi-model: KV / documents / graphs / vector
indexes) or complemented by another DBMS for advanced analytics later, without
touching the API or the GUI. This is the foundation for multi-session, statistics and
advanced settings to grow on top.
**Framework root.** All persistent state lives under `~/.strata-ctl/` (the Linux
user's home; override with `workspace_root`), separated by content type:
`sessions/<name>/` (agent workspace folders), `data/` (the SQLite database),
`uploads/` (uploaded files), `memory/` (the rebuildable semantic index). A legacy
DB at `~/.config/strata-ctl/sessions.db` is
copied into `data/` once on first run (the original is left in place).
## Agent mode
The GUI model can **act**, not just chat. The core tools are **always on** — there
is no toggle, because the framework could not function without them. The agent's tool
surface is small and deliberate: **`shell_exec`** (a shell is universal: file ops,
programs, system inspection, web via curl, git, …), **`notepad`** (agent-curated
persistent memory, see below) and **`share_file`** (hand the user a download link
for a file on its filesystem, see below). A session that opts into **semantic
memory** additionally gets `remember` / `recall` / `forget` (see **Semantic vector
memory** below). A bounded server-side loop drives
`model → shell_exec → result → model → … → final answer`, persisting the whole
trajectory and streaming progress events — `delta` (the model's thinking and final
answer, token by token), `tool_call` / `tool_result` (every command and its output
inline) and `final` — so the wait is always visible progress, **observability without
a confirmation gate**.
Safety is an **environment boundary, not a per-tool sandbox**: `shell_exec` always
runs via `bash -lc` on whatever machine the framework runs on, starting in the
session's **personal folder** by default (override with `cwd`), with a timeout and
an output cap. There is deliberately **no host-vs-container tool split** — if you
want stronger protection, run *strata-ctl itself* inside a container, a VM or an
isolated machine; the agent then only ever sees that environment. Execution sits
behind a `ShellRunner` trait (useful for tests and alternate runners), with no
per-call confirmation gate and no separate "isolated" tool backend.
**Sharing a file (`share_file`).** When the agent produces a file the user should
be able to download, it calls `share_file(path, name?)`; the tool returns a
same-origin Markdown link (`[name](/api/sessions/{id}/download?path=…)`) the model
pastes into its reply, and the GUI renders it as a download chip. This is the
outbound complement to uploads. The safety boundary is **containment, not trust**:
a shared path must canonicalize inside one of two allowed roots — the session's
**personal folder** or the shared **`uploads/`** dir — so `..` traversal and symlink
escapes are refused, only regular files are served, and a **64 MiB** cap applies.
The download endpoint re-validates independently (author ≠ verifier): it never
trusts the tool's earlier check, forces `Content-Disposition: attachment` +
`application/octet-stream` + `nosniff` (no inline rendering of model-chosen bytes),
and returns a bare 400 on any out-of-bounds path without leaking existence or bytes.
## Architecture
```
shared JSON config ──► InklingFormatter ──► Engine supervisor ──► axum HTTP API
(tolerant) tokenizer + chat line protocol /v1/...
template + dialect (GEN/T/DONE/STOP)
```
- `config` — tolerant loader for the shared `strata-inkling.json`: it reads what it
understands and ignores every other key, so one file can drive several tools.
- `inkling` — the model dialect: HF `tokenizers` (o200k BPE) wrapper, MiniJinja chat
template, the channel-token state machine, and the image bridge.
- `engine` — a pure protocol parser plus a supervisor that owns the child process,
serializes requests on its single control stream, and handles STOP/drain/QUIT.
- `api` — request/response types, the `Formatter`/`Decoder` seam, the completion
service (stream + non-stream), the axum router, the session-aware GUI API and the
embedded web assets.
- `store` — the persistent session/context store: a `Store` trait with a bundled
SQLite implementation (WAL), used by the GUI API.
- `context` — the context compositor: builds the model prompt from named SQLite
sections (`SYSTEM_PROMPT`, `TOOL_USE`) plus the `DIALOG` region, applying
per-turn `[SPEAKER]` provenance (prompt-only).
- `render` — server-side Markdown → sanitized HTML with LaTeX → native MathML
(`pulldown-cmark` + `pulldown-latex`) for assistant replies.
- `agent` — the bounded server-side tool loop: `shell_exec`, `notepad`,
`share_file`, MCP connectors and the per-session memory tools.
- `memory` — the semantic memory service: the authoritative `Store` plus a
rebuildable vector index, kept in step and fail-open. Backed by the
**`strata-memory`** workspace crate (swappable `Embedder` trait, HTTP BGE-M3
client, embedded Qdrant Edge index).
## Building and running
Requires a Rust toolchain and a built Strata engine binary (`strata-inkling`).
```sh
cargo build --release
# Print the launch plan resolved from the config (default):
./target/release/strata-ctl --config /path/to/strata-inkling.json
# Start the engine and serve the API:
./target/release/strata-ctl --serve --config /path/to/strata-inkling.json
# overrides: --host 127.0.0.1 --port 8095
```
The default config path is `~/.config/strata-inkling/strata-inkling.json`. Logging
uses `tracing`; set `RUST_LOG` to control verbosity (default `info`).
### Configuration
The config is the same JSON the other Strata tools use. Keys acted on here include
`exe`, `args`, `cwd`, `tokenizer`, `model_name`, `host`, `port`, `reasoning_effort`,
`max_new` (default generation budget, see below), `sampling`, `api_key`,
`allowed_hosts`, `db_path` (GUI session database), `workspace_root` (framework
root), `system_prompt` (general default), `language` (UI/prompt catalog, default
`it`), `memory_embedder_url` (semantic-memory embedder endpoint, default the free
Altair instance), and the optional `startup_timeout_secs` / `silence_timeout_secs`.
Everything else (`arch`, `mcp_servers`, `cors_origins`, …) is preserved untouched and reported
as ignored — unknown keys never break startup.
**Generation budget (`max_new`).** When neither the request nor the session sets
`max_tokens`, generation is capped at `max_new` tokens (config, default **16384**).
Reasoning and answer share this ceiling: it was raised from 2048 because extended
chain-of-thought was being truncated mid-reasoning (`finish_reason: length`, empty
answer). The model still stops early at EOS, so the larger cap only matters when it
would otherwise run out; a per-session/per-request `max_tokens` still overrides it.
### Localization (i18n)
User-facing strings are externalized into embedded per-language catalogs and
looked up by key with `{placeholder}` interpolation:
- **Backend** (`src/i18n.rs`): `locales/<lang>.json`, `t(key, params)`, language
from the `language` config key (default `it`), English fallback then the key.
- **Frontend** (`web/assets/locales/<lang>.json`): `t(key, params)` for dynamic
strings and `data-i18n` attributes for static HTML; language follows the browser.
Convention: new code routes user-facing strings (and model-facing prompts such as
the identity reminder) through the catalog. Wire-protocol fields, JSON keys and
identifiers are **never** translated. Existing hardcoded strings are migrated in a
later adaptation round.
## Status
Working and tested (238 tests passing; 6 ignored tests exercise the real engine,
embedder or files and run on demand). Text, images,
the full client-side tool loop, the Anthropic endpoint, the web GUI (session
context, streaming, stats, **file/image upload**, **file download** (`share_file`
→ containment-checked attachment endpoint), assistant **Markdown/LaTeX
rendering** with native MathML) and **agent mode** (the model using `shell_exec`
on the host) have been validated live against the real Inkling engine. The
**context compositor** (named sections stored in SQLite — `SYSTEM_PROMPT` /
`TOOL_USE` / `DIALOG`) and prompt-only **[SPEAKER] provenance** are in place,
verified against the real chat template. A per-session **notepad** (agent-curated
`<NOTEPAD>` entries via the `notepad` tool) and a **sliding DIALOG window**
(message-count main area + buffer headroom, stepped KV-cache-friendly eviction at
turn boundaries, `window_start` persisted per session, full history never deleted)
are implemented and dogfooded live. Per-session **semantic memory**
(`remember` / `recall` / `forget` over an embedded Qdrant Edge index with BGE-M3
embeddings) is implemented and validated live against the Altair embedder. A
best-effort **cache pre-warm** (`GEN 0` over
the next turn's shared prefix during idle GPU time) hides the re-prefill on a
pending window rotation **or a notepad change** (pre-warm-on-change: the model
always sees a fresh notepad, no frozen header, no schema migration). The joint
`GEN 0 → RESUME` measurement on HIP (`examples/prewarm_bench.rs`) **passed**:
`cached_tokens == L == 385`, only the 35 new user tokens prefilled.
The cache-reuse correctness is also **formally verified**: `proofs/auto_ckpt.lean`
is a core-only Lean 4 model of the prefix-cache restore rule, kernel-checked
(`lean proofs/auto_ckpt.lean`, no `sorryAx`). It proves that selecting a checkpoint
at depth `s ≤ lcp` restores exactly the prompt's first `s` tokens (so recomputing
only the delta is bit-identical), that a divergence at `p` invalidates deeper
snapshots, and that a `GEN 0` over a prefix makes the next turn `RESUME` the whole
prefix. `examples/prefix_measure.rs` measures the real static prefix from the live
SQLite sessions (≈1135 tokens per session, 575 of them `tool_declare`; only ≈589
shared cross-session, since `SYSTEM_PROMPT` leads with the session identity). The
agreed next engine-side step is **automatic multi-level prefix checkpointing**
(`--auto-ckpt`: a per-slot snapshot pool + exact-`lcp` restore at every `GEN`,
opt-in and protocol-transparent). strata-ctl needs no change for it, provided the
pool retains the exact end-of-prefill checkpoint so `RESUME == L` still holds.
Not yet implemented (honest gaps): forced `tool_choice` (`required` / named function
returns a clear 400), multi-slot batching, logprobs / structured output, automatic
engine restart after a crash, a full SSRF guard against DNS rebinding, and the
OpenAI Responses native endpoint. The Anthropic adapter covers the core cases but
not yet the `defer_loading` / `tool_addition` / `tool_reference` tool machinery, the
thinking `budget_tokens` mapping, or prompt-cache token accounting. Base/host agent
mode, per-session settings (copy-on-create), session notes, immutable names,
personal workspace folders and file/image upload (shared store, token-based
routing, images via Vision) work. Per-tool host/container sandboxing was
**deliberately dropped**: protection comes from where you run the framework
(container / VM / isolated host), not from a second tool backend.
## Roadmap
### Semantic vector memory — implemented
The agent has long-term **semantic memory**: explicit `remember` / `recall` /
`forget` tools backed by dense-vector search, shipped as the `strata-memory`
workspace crate plus the control-layer seam (`src/memory.rs`). The ratified
choices:
- **Embedder: BGE-M3 dense (1024-d)** via the team's `vetta-embedder` over HTTP
(`memory_embedder_url`, default the free Altair instance at
`http://192.168.50.18:8091`; C++/ggml, no Python/ONNX, no model bundled). The
`Embedder` trait keeps the backend swappable — an in-process embedder can
replace HTTP later without touching callers. Chosen after a live **fitness
probe** (representative memory corpus, labeled positive/negative queries:
top-1 20/20, MRR 1.000, clean positive/negative separation), which also
calibrated the default recall threshold to **0.45** cosine.
- **Index: Qdrant Edge** (`qdrant-edge`, embedded in-process — no server, single
binary preserved) under `~/.strata-ctl/memory/`. The SQLite `Store` stays
**authoritative**: the shard is a disposable semantic layer, rebuilt from the
Store whenever the persisted model-id sidecar (`strata_model.json`) mismatches
the current embedder — swapping embedders never mixes incompatible vectors.
- **Fail-open.** `remember` persists to the Store first; if the embedder is
unreachable, indexing is deferred and reconciled on the next open. `recall`
falls back to a keyword scan of the Store, so memory stays useful offline.
Vectors never leave the service — the model sees text + score only.
- **Per-session, one-way opt-in.** Memory is off by default (casual chat needs
none); each session's memories are **scoped to its id** — recall and forget
never cross sessions. Enabling it (GUI checkbox or `PATCH /api/sessions/{id}`)
is an **irreversible latch** like `name_locked`, so indexed memories are never
silently orphaned, and it requires the embedder to be reachable. The memory
tools are declared to the model only on memory-enabled sessions.
Still on the roadmap for memory:
- **Common / cross-session memory.** A shared scope on top of the per-session
one, when the isolation model has proven itself in use.
- **Layered directives.** An always-on **common core** (knowledge lifecycle:
recall when relevant, record durable lessons, verify against current evidence,
one topic per memory, prune duplicates) plus **enable-able domain guideline
packs** (coding, research/docs, radio/logs, planning, …) that the user — or the
agent itself, observably — switches on per need. A pack is not just prose: it
carries structured config (categories/tags, chunking strategy, retrieval
filters/boosts, exposed tools) so the same general engine serves specialized
retrieval. Packs integrate with the per-session settings (copy-on-create) and
never override the core (core > pack). For now the tool guidance lives in the
tool declarations themselves; a dedicated prompt section will follow the
model's own feedback from real use.
- **One general engine + one general embedder** stays the rule: a single
multilingual, domain-agnostic embedding model and a single vector engine must
decently cover any need; specialization lives *above* the index, never in a
second engine or model.
### Sliding context window + per-session notepad
Both are **implemented and validated live**: the per-session notepad (store,
`notepad` tool, `<NOTEPAD>` injection, read-only GUI panel) and the **sliding
DIALOG window** (`src/window.rs`). The compositor no longer injects the full
history: `window::select` retains the most recent messages **by count**, in two
tiers — a **main area** (`MAIN_AREA = 30` recent messages always kept) plus a
**buffer** (`BUFFER = 20` messages of headroom above it). The cut lands on
**user-turn boundaries**, so a `tool_call`/`tool_result` pair is never split, and
the full history stays in SQLite (evicted turns remain recallable).
Eviction is **stepped, with hysteresis** — the "buffer fills → cleared → new
buffer" cycle: while the retained count is at most `MAIN_AREA + BUFFER` the window
is **append-only** (new turns join the tail), so the prompt prefix is byte-identical
turn-to-turn and the engine reuses its cached KV. When occupancy crosses
`MAIN_AREA + BUFFER` the buffer is **cleared**: the start advances in chunks to
user-turn boundaries down to `MAIN_AREA`, amortizing one re-prefill over several
append-only turns, and a new buffer starts filling. The chosen start id is persisted
per session (`sessions.window_start`, idempotent migration) and respected on the
next turn. The counts are a starting point (30 main + 20 buffer, same 50 cap);
the wider buffer halves the rotation frequency (fewer re-prefills) at the cost of
a lower post-rotation floor, and both will shrink at regime. A **total-size
(char/token) cut** is deliberately deferred — it interacts
with the stepped anchor and is not as simple as a second cap; the notepad preserves
what matters beyond the window.
The **browser sees the same window**: `GET …/messages` returns only the retained
suffix (SQL-filtered by `window_start`, so a months-long history — potentially tens
of millions of tokens — is never loaded whole or shipped to the client), plus the
total count so the GUI shows a banner noting older turns are preserved server-side.
A full-chat export/download command is deferred; the live view is windowed by design.
The inference path (`session_chat`) loads the same SQL-filtered subset
(`message_window`), so a turn never reads the whole history either — both the
browser and the model are bounded to the retained window.
To survive what slides out, each session has a **notepad**: a small,
agent-curated set of **labelled entries** (`key → short text`, e.g. `goal`,
`state`, `decision:…`, `pitfall:…`, `ref:…`) persisted per-session behind the
`Store` trait and injected as a pinned `<NOTEPAD>` section **immediately above `DIALOG`**,
always visible; its usage instructions live in the `TOOL_USE` section (the tool
manual), not in the notepad block itself. One action-based tool (`notepad(action=set|remove|clear,
key, text?)`) upserts/removes by key — idempotent, no shifting numeric indices.
Compact single-line block, deterministic order, a **soft size budget** (chars,
per-entry and total caps) with a hard ceiling that asks the agent to consolidate.
Design stance — **importance, not recency**: no silent FIFO eviction, no age-based
decay. strata-ctl sessions are **persistent (no expiry)** and the agent is
**reactive** — it runs only on external input, with no autonomous background
curator (unlike Iris's recap/dreamer). The notepad is therefore the **resume
anchor** across idle gaps, restarts and the sliding window: a goal set on turn 1
must survive weeks, and the agent itself decides what to keep, in-turn. Guidance
steers *what* to pin (goal, decisions + rationale, state/next step, constraints,
pitfalls, key paths) and what not (logs/long documents → future recall;
single-task ephemera → history). A read-only GUI panel exposes each session's
notepad for observability.
Section order is already driven by the `context_sections.position` column, so a
natural extension is to let the **agent itself choose the layout**: it is the
consumer that sees the sections, so it can ask to reorder them (persisted as
positions). Ordering applies to the pinned sections above `DIALOG`, which stays
the tail; it is deliberate and persisted, not per-turn, to keep the KV-cache
prefix stable.
Deferred: a total-size (char/token) cut on the dialog window (the message-count
policy ships first), common/cross-session memories, a working-memory reference area
(content addressed but kept out of the prompt budget), auto-curation. **Automatic
recap is out of scope**: summarizing what slides out needs an autonomous background
agent, whereas strata-ctl is reactive — the agent-curated notepad plus deterministic
truncation cover the resume anchor without a curator. The deep-retrieval complement
is the semantic vector memory above (implemented); a simpler lexical recall over
the retained SQLite history can still come as a lighter addition.
### Client surfaces (under consideration, not scheduled)
Protocol-first: harden and version the existing client contract (session/turn JSON
+ SSE, uploads, stats, settings) and give non-browser clients real auth, then build
every surface as a client/adapter of that one contract — the web GUI already is one.
- **External agents (MCP preferred):** an MCP server adapter (`rmcp`; stdio for local
harnesses, streamable-HTTP on the existing axum router for remote) exposing a small
closed tool set mirroring the GUI: session create/list/send/history/rename/delete,
settings get/set, stats, upload. `session.send` returns the final answer + tool
trajectory + usage (MCP is request/response); live token streaming stays a GUI /
HTTP-SSE feature, with optional MCP progress notifications.
- **Human clients (web GUI, Android):** the same JSON contract over HTTP + SSE — not
MCP. One core, two wire adapters: MCP JSON-RPC for agents, HTTP/SSE for humans.
Android's cheapest first step is an installable PWA / thin WebView shell over the
existing mobile-first GUI; native Kotlin/Compose only for native capabilities
(notifications, share intents, offline).
## License and credits
MIT — full text in [LICENSE](LICENSE). strata-ctl is an original Rust
implementation, not a copy of upstream code: its copyright is Federico's.
The Strata engine it drives remains Niko1221's MIT work.
- **Strata** engine and original control layer: Niko1221 and the Strata
contributors — <https://github.com/Niko1221/Strata>.
- **strata-ctl** (this Rust control layer): Federico (`iz0eyj`).