Add context management: notepad, sliding window, cache reuse, windowed GUI

Per-session notepad: agent-curated labelled entries via the notepad tool
(set/remove/clear), injected as a pinned <NOTEPAD> section above DIALOG,
char-budgeted with a consolidate ceiling, exposed in a read-only GUI panel.

Sliding DIALOG window (src/window.rs): retains recent messages by count in
two tiers (MAIN_AREA=40 + BUFFER=10), append-only while the buffer fills so
the prompt prefix stays byte-stable for KV reuse, then stepped hysteresis
eviction snapping to user-turn boundaries (never splits a tool exchange).
window_start persisted per session; full history never deleted.

Engine prefix-cache reuse: leave DIALOG open (a moving </DIALOG> closer broke
the engine prompt_ckpt_prefix every user turn, forcing full re-prefill);
surface usage.cached_tokens as a GUI badge; fix the PerfMeter prefill gauge to
gauge over non-cached tokens; add a static sliding-window marker after the
opener so the model knows older turns are omitted.

Stats clarity: distinguish the current inference context (last_prompt_tokens,
new "Contesto attuale" card) from the cumulative lifetime token total
(relabeled "Token cumulativi ... su tutti i turni"); /api/stats carries both.

Windowed browser transcript: GET /api/sessions/{id}/messages returns only the
retained window (SQL-filtered by window_start, never loads the full history)
plus the total count, wrapped as {messages, window_start, total}; the GUI shows
a banner noting older turns are preserved server-side. Full-chat export deferred.

Settings: the session scope re-reads the persisted instance fresh from the store
(like the general scope already did), fixing a stale-cache display that looked
like the session System Prompt was not being kept.

Docs (README) refreshed; 158 tests + 3 ignored green, clippy and fmt clean.
This commit is contained in:
adm committed 2026-11-26 03:12:23 +01:00
1 parent 7c945890f4
commit 0ce84581a4
20 files changed
+1412 -118

No files matched your search

+103 -11
View File
@@ -96,13 +96,19 @@ offline, same-origin so no CORS). It is a thin client over a **session-aware API
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 history.
`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, prompt/completion/total tokens, tool calls), per-session and per-day
breakdowns, plus live engine status and a since-startup decode/prefill speed gauge.
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.
@@ -137,8 +143,17 @@ 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 wraps the real role messages
(history + new turn) so the engine keeps its turn structure. Every turn carries a
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
@@ -155,10 +170,16 @@ 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, token-weighted **decode
speed** and prefill speed since startup, total/prompt/completion 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. `GET /api/stats`
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
@@ -270,14 +291,18 @@ later adaptation round.
## Status
Working and tested (140 tests, plus 3 real-file tests run on demand). Text, images,
Working and tested (158 tests, plus 3 real-file tests run on demand). Text, images,
the full client-side tool loop, the Anthropic endpoint, the web GUI (session
context, streaming, stats, **file/image upload**, 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.
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.
Not yet implemented (honest gaps): forced `tool_choice` (`required` / named function
returns a clear 400), multi-slot batching, logprobs / structured output, automatic
@@ -340,6 +365,73 @@ Candidates under evaluation — the concrete engine / embedder / store choice is
the same seam: the team's Qdrant (used by Iris) and the planned ArangoDB
(documents + vectors + search).
### 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 = 40` recent messages always kept) plus a
**buffer** (`BUFFER = 10` 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 (40 main + 10 buffer); 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.
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 suspended semantic vector memory above; a simpler lexical recall over the
retained SQLite history can come first.
### Client surfaces (under consideration, not scheduled)
Protocol-first: harden and version the existing client contract (session/turn JSON