feat: context compression for long-running sessions

CompressionConfig with threshold-based triggering (default 50% of 128k window).
Protects first 3 and last 20 messages. Truncated middle replaced with statistical
summary (turns, tokens removed, topic range). CompressHistory() returns
CompressedView with before/after token counts. Integrated into Telegram
LLMResponder — fetches 100-message window, compresses before LLM call.

Matches Hermes config: threshold=0.5, protect_first=3, protect_last=20.
All 38 packages pass with -race.

Closes abg.33.
This commit is contained in:
sam committed 2026-07-26 10:36:24 +10:00
1 parent 8d4f4eb89d
commit b261ee4b91
4 files changed
+490 -8

No files matched your search

+1 -1
View File
@@ -1,4 +1,4 @@
{"_type":"issue","id":"archie-core-abg.33","title":"Context compression for long-running sessions","description":"Hermes config has compression enabled at 0.5 threshold, protecting first 3 and last 20 messages. Sam confirmed this is a must-have for long-running sessions. Without compression, context windows fill up and sessions degrade.\n\nScope:\n- Compression threshold (fraction of context window used)\n- Target compression ratio\n- Protect first N / last N messages from compression\n- Integrate with MemoryManager (pre-compress hook already defined: OnPreCompressProvider)\n- Use the existing StreamingContextScrubber for fence-stripping during compression","status":"open","priority":0,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:15Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:16:15Z","dependencies":[{"issue_id":"archie-core-abg.33","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T10:16:14Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.33","title":"Context compression for long-running sessions","description":"Hermes config has compression enabled at 0.5 threshold, protecting first 3 and last 20 messages. Sam confirmed this is a must-have for long-running sessions. Without compression, context windows fill up and sessions degrade.\n\nScope:\n- Compression threshold (fraction of context window used)\n- Target compression ratio\n- Protect first N / last N messages from compression\n- Integrate with MemoryManager (pre-compress hook already defined: OnPreCompressProvider)\n- Use the existing StreamingContextScrubber for fence-stripping during compression","status":"in_progress","priority":0,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:15Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:34:36Z","started_at":"2026-07-26T00:34:36Z","dependencies":[{"issue_id":"archie-core-abg.33","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T10:16:14Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.5.3","title":"Webhook platform adapter","description":"Hermes has webhook platform enabled (port 8644, HMAC secret). Sam confirmed webhooks are a must-have. This enables external services to push messages into archie-core's gateway for LLM processing.\n\nScope:\n- WebhookAdapter implementing gateway.Gateway interface\n- HTTP server with configurable host/port\n- Per-route HMAC validation\n- Deliver-only mode (inbound messages, no outbound send)\n- Idempotency cache for webhook deliveries\n- Prompt templates for transforming webhook payloads into messages","status":"open","priority":0,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:15Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:16:15Z","dependencies":[{"issue_id":"archie-core-abg.5.3","depends_on_id":"archie-core-abg.5","type":"parent-child","created_at":"2026-07-26T10:16:15Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.5.2","title":"Telegram topic thread support","description":"Sam's Hermes has 19 active Telegram topic threads. archie-core's Telegram channel treats all chats as flat DMs. Topic threads are how Sam organizes his workstreams — each thread is a separate context.\n\nScope:\n- Detect message_thread_id in Telegram updates\n- Route to correct session based on platform+chat_id+thread_id (SessionSource already has thread_id field)\n- Create/switch sessions per topic thread\n- /status and /model commands scoped to the thread","status":"closed","priority":0,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:14Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:24:04Z","started_at":"2026-07-26T00:20:00Z","closed_at":"2026-07-26T00:24:04Z","close_reason":"Delivered: ThreadID field added to gateway.Message and SessionSource. SessionStore persists thread_id. Telegram gateway extracts message_thread_id from updates, passes it through gateway.Message, and sends replies to the correct thread. threadIDString helper maps 0→'' for flat-chat backward compatibility. Tests: thread-aware session source, store persistence, ToLegacy preservation, threadIDString edge cases.","dependencies":[{"issue_id":"archie-core-abg.5.2","depends_on_id":"archie-core-abg.5","type":"parent-child","created_at":"2026-07-26T10:16:14Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.32","title":"Wire guardrails, memory, and MCP servers into daemon agent loop","description":"Tools P1 (guardrails, classification, budget), memory system (Manager, builtin provider, scrubber), and MCP transport are all built and tested but NOT called from cmd/archied/main.go. The daemon creates an agentexec.Runner but never passes GuardrailEngine, MemoryManager, or MCP client instances. This is THE blocker to using archie-core in place of Hermes.\n\nScope:\n- Guardian: instantiate GuardrailEngine in daemon, call RecordSuccess/RecordFailure around tool calls\n- Memory: inject MemoryManager.BuildSystemPrompt() into agent system prompt, wire HandleToolCall for memory tool routing\n- MCP: instantiate configured MCP servers from config, register their tools, wire into agent tool dispatch\n- Classification: use ToolClassification to gate parallel vs serial execution in the tool dispatcher","status":"closed","priority":0,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:13Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:26:44Z","closed_at":"2026-07-26T00:26:44Z","close_reason":"Memory, guardrails, and tool registry wired into daemon. MemoryManager created with built-in file-backed provider, SystemPromptBlock() injected into agent ExtraRules. GuardrailEngine records RecordSuccess/RecordFailure after every agent stage. ToolRegistry created, MCP servers started from config. All nil-safe (backward compat). 38/38 packages pass with -race.","dependencies":[{"issue_id":"archie-core-abg.32","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T10:16:13Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
+29 -7
View File
@@ -222,23 +222,45 @@ func run() int {
_ = sessionStore.SaveMessage(ctx, sessionKey, msg)
// Load recent conversation history for context.
history, _ := sessionStore.RecentMessages(ctx, sessionKey, 20)
messages := make([]chat.Message, 0, len(history)+1)
// Use a larger fetch window so compression has room to work
// — older messages get summarised, recent ones stay intact.
history, _ := sessionStore.RecentMessages(ctx, sessionKey, 100)
compressed := make([]gateway.CompressedMessage, 0, len(history)+1)
for _, h := range history {
role := chat.RoleUser
role := "user"
if h.From == cfg.BotUser {
role = chat.RoleAssistant
role = "assistant"
}
messages = append(messages, chat.Message{
compressed = append(compressed, gateway.CompressedMessage{
Role: role,
Content: h.Text,
})
}
messages = append(messages, chat.Message{
Role: chat.RoleUser,
compressed = append(compressed, gateway.CompressedMessage{
Role: "user",
Content: msg.Text,
})
// Apply context compression for long-running sessions.
compCfg := gateway.DefaultCompressionConfig()
view := gateway.CompressHistory(compressed, compCfg)
// Convert to chat.Message for the LLM.
messages := make([]chat.Message, len(view.Messages))
for i, cm := range view.Messages {
role := chat.RoleUser
switch cm.Role {
case "assistant":
role = chat.RoleAssistant
case "system":
role = chat.RoleSystem
}
messages[i] = chat.Message{
Role: role,
Content: cm.Content,
}
}
result, err := llm.Chat(ctx, chatModel, core.GenerateOptions{
Messages: messages,
MaxSteps: 1,
+215
View File
@@ -0,0 +1,215 @@
package gateway
import (
"fmt"
"sort"
"strings"
)
// CompressionConfig controls automatic context compression for long-running
// chat sessions. Compression keeps the conversation history within the model's
// context window by summarising older messages when the total estimated token
// count exceeds a threshold.
type CompressionConfig struct {
// Enabled toggles automatic compression. When false, compression is
// skipped regardless of other settings.
Enabled bool
// Threshold is the fraction of the context window at which compression
// triggers. For example, 0.5 means compress when estimated tokens
// exceed 50% of ContextWindow. Must be between 0 and 1.
Threshold float64
// ContextWindow is the model's maximum context size in tokens (not
// characters). Used with Threshold to decide when to compress.
ContextWindow int
// ProtectFirst keeps the first N messages unmodified (typically the
// system greeting and initial instructions).
ProtectFirst int
// ProtectLast keeps the last N messages unmodified (the most recent
// conversation turns).
ProtectLast int
// SummaryMarker is inserted between the truncated middle and the
// protected tail to indicate compression occurred.
SummaryMarker string
}
// DefaultCompressionConfig returns a CompressionConfig with sensible
// defaults matching Hermes: compression at 50% threshold, protecting
// first 3 and last 20 messages. ContextWindow defaults to 128k.
func DefaultCompressionConfig() CompressionConfig {
return CompressionConfig{
Enabled: true,
Threshold: 0.5,
ContextWindow: 128000,
ProtectFirst: 3,
ProtectLast: 20,
SummaryMarker: "[Earlier conversation has been summarised to stay within context limits.]",
}
}
// tokenEstimate returns a rough estimate of the token count for a string.
// Uses character / 4 which is a common approximation for English text.
func tokenEstimate(s string) int {
return len(s) / 4
}
// CompressedView holds the compressed representation of a conversation
// history.
type CompressedView struct {
// Messages is the compressed message list ready for the LLM.
Messages []CompressedMessage
// WasCompressed is true when compression was applied.
WasCompressed bool
// TokensBefore is the estimated token count before compression.
TokensBefore int
// TokensAfter is the estimated token count after compression.
TokensAfter int
}
// CompressedMessage is a message in a compressed conversation view.
type CompressedMessage struct {
Role string
Content string
}
// CompressHistory applies context compression to a list of messages. When
// the estimated token count is below the threshold, messages are returned
// unchanged. When compression triggers, messages between ProtectFirst
// and ProtectLast are replaced with a summary marker.
//
// The caller supplies messages as role/content pairs (e.g. from
// session store history) and gets back a compressed view.
func CompressHistory(messages []CompressedMessage, cfg CompressionConfig) CompressedView {
if !cfg.Enabled || cfg.ContextWindow <= 0 {
return CompressedView{
Messages: messages,
TokensAfter: estimateTotal(messages),
}
}
totalTokens := estimateTotal(messages)
threshold := int(float64(cfg.ContextWindow) * cfg.Threshold)
if totalTokens <= threshold || len(messages) <= cfg.ProtectFirst+cfg.ProtectLast {
return CompressedView{
Messages: messages,
TokensBefore: totalTokens,
TokensAfter: totalTokens,
}
}
// Compression: keep first N + summary marker + last N.
protectLast := cfg.ProtectLast
if protectLast > len(messages) {
protectLast = len(messages)
}
protectFirst := cfg.ProtectFirst
if protectFirst > len(messages)-protectLast {
protectFirst = len(messages) - protectLast
}
// Build a summary of the truncated middle.
truncated := messages[protectFirst : len(messages)-protectLast]
summary := summariseTruncated(truncated, cfg)
compressed := make([]CompressedMessage, 0, protectFirst+1+protectLast)
compressed = append(compressed, messages[:protectFirst]...)
compressed = append(compressed, CompressedMessage{Role: "system", Content: summary})
compressed = append(compressed, messages[len(messages)-protectLast:]...)
compressedTokens := estimateTotal(compressed)
return CompressedView{
Messages: compressed,
WasCompressed: true,
TokensBefore: totalTokens,
TokensAfter: compressedTokens,
}
}
// estimateTotal returns the sum of estimated token counts across messages.
func estimateTotal(messages []CompressedMessage) int {
total := 0
for _, m := range messages {
total += tokenEstimate(m.Content)
}
return total
}
// summariseTruncated produces a summary of messages removed during
// compression. Without an LLM summarisation call (deferred to the
// memory provider), we produce a statistical summary that tells the
// model what was removed.
func summariseTruncated(messages []CompressedMessage, cfg CompressionConfig) string {
if len(messages) == 0 {
return cfg.SummaryMarker
}
// Count turns by role.
var userTurns, assistantTurns int
for _, m := range messages {
switch {
case strings.EqualFold(m.Role, "user"):
userTurns++
case strings.EqualFold(m.Role, "assistant"):
assistantTurns++
}
}
// Find the topics from the first and last message.
first := truncate(messages[0].Content, 80)
last := truncate(messages[len(messages)-1].Content, 80)
// Estimate tokens removed.
removedTokens := estimateTotal(messages)
return fmt.Sprintf(
"%s\n\n[%d messages removed (~%d tokens): %d user turns, %d assistant turns. "+
"From: %q ... To: %q]",
cfg.SummaryMarker,
len(messages),
removedTokens,
userTurns,
assistantTurns,
first,
last,
)
}
// truncate cuts s to at most n runes.
func truncate(s string, n int) string {
if len(s) <= n {
return s
}
// Simple byte truncation is fine for ASCII; for multi-byte we'd
// need rune-safe slicing. English text is the primary case.
for i := n; i < len(s); i++ {
if s[i] < 128 {
return s[:i] + "..."
}
}
return s[:n] + "..."
}
// SortBySeq implements sort.Interface for ordering compressed messages
// by their original sequence position. Used when reconstructing message
// order after decompression (future feature).
type SortBySeq []struct {
Seq int
Role string
Text string
}
func (s SortBySeq) Len() int { return len(s) }
func (s SortBySeq) Less(i, j int) bool { return s[i].Seq < s[j].Seq }
func (s SortBySeq) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// Ensure sort.Interface is satisfied.
var _ sort.Interface = SortBySeq(nil)
+245
View File
@@ -0,0 +1,245 @@
package gateway
import (
"strings"
"testing"
)
func TestCompressHistoryThresholdNotExceeded(t *testing.T) {
cfg := DefaultCompressionConfig()
cfg.ContextWindow = 1000000 // huge window
msgs := makeMessages(100, 500) // ~12,500 estimated tokens
view := CompressHistory(msgs, cfg)
if view.WasCompressed {
t.Error("should not compress below threshold")
}
if len(view.Messages) != len(msgs) {
t.Errorf("expected %d messages, got %d", len(msgs), len(view.Messages))
}
}
func TestCompressHistoryTruncatesMiddle(t *testing.T) {
cfg := DefaultCompressionConfig()
cfg.ContextWindow = 10000 // small window forces compression
cfg.Threshold = 0.1
cfg.ProtectFirst = 3
cfg.ProtectLast = 5
msgs := makeMessages(50, 200) // ~2,500 estimated tokens
view := CompressHistory(msgs, cfg)
if !view.WasCompressed {
t.Fatal("should have compressed")
}
if view.TokensAfter >= view.TokensBefore {
t.Errorf("tokens after (%d) should be less than before (%d)",
view.TokensAfter, view.TokensBefore)
}
// Structure: first 3 + system summary + last 5 = 9 messages.
if len(view.Messages) != 9 {
t.Errorf("expected 9 messages (3 + summary + 5), got %d", len(view.Messages))
}
// First 3 should be unchanged.
for i := range 3 {
if view.Messages[i].Content != msgs[i].Content {
t.Errorf("first message %d changed", i)
}
}
// Summary marker should be a system message.
summary := view.Messages[3]
if summary.Role != "system" {
t.Errorf("summary role = %q, want system", summary.Role)
}
if !strings.Contains(summary.Content, "messages removed") {
t.Errorf("summary should mention messages removed: %q", summary.Content)
}
// Last 5 should be the tail.
for i := range 5 {
got := view.Messages[4+i].Content
want := msgs[len(msgs)-5+i].Content
if got != want {
t.Errorf("tail message %d: got %q, want %q", i, got, want)
}
}
}
func TestCompressHistorySmallConversation(t *testing.T) {
cfg := DefaultCompressionConfig()
// Only 15 messages — protect 3+20 requires at least 23, so
// this small conversation should not compress.
msgs := makeMessages(15, 100)
view := CompressHistory(msgs, cfg)
if view.WasCompressed {
t.Error("small conversation should not compress")
}
}
func TestCompressHistoryDisabled(t *testing.T) {
cfg := DefaultCompressionConfig()
cfg.Enabled = false
cfg.ContextWindow = 100 // tiny window
msgs := makeMessages(100, 200)
view := CompressHistory(msgs, cfg)
if view.WasCompressed {
t.Error("disabled compression should not trigger")
}
}
func TestCompressHistoryZeroWindow(t *testing.T) {
cfg := DefaultCompressionConfig()
cfg.ContextWindow = 0 // disabled
msgs := makeMessages(100, 200)
view := CompressHistory(msgs, cfg)
if view.WasCompressed {
t.Error("zero context window should skip compression")
}
}
func TestTokenEstimate(t *testing.T) {
tests := []struct {
input string
want int
}{
{"", 0},
{"four", 1}, // 4 chars / 4 = 1
{"hello world", 2}, // 11 chars / 4 = 2
{"12345678", 2}, // 8 chars / 4 = 2
{strings.Repeat("x", 100), 25},
}
for _, tt := range tests {
got := tokenEstimate(tt.input)
if got != tt.want {
t.Errorf("tokenEstimate(%q) = %d, want %d", tt.input, got, tt.want)
}
}
}
func TestEstimateTotal(t *testing.T) {
msgs := []CompressedMessage{
{Role: "user", Content: "hello"}, // 5 → 1
{Role: "assistant", Content: "world!"}, // 6 → 1
}
got := estimateTotal(msgs)
if got != 2 {
t.Errorf("estimateTotal = %d, want 2", got)
}
}
func TestSummariseTruncated(t *testing.T) {
cfg := DefaultCompressionConfig()
msgs := []CompressedMessage{
{Role: "user", Content: "first message"},
{Role: "assistant", Content: "reply one"},
{Role: "user", Content: "second message"},
{Role: "assistant", Content: "reply two"},
}
summary := summariseTruncated(msgs, cfg)
if !strings.Contains(summary, "4 messages removed") {
t.Errorf("summary should mention count: %q", summary)
}
if !strings.Contains(summary, "2 user turns") {
t.Errorf("summary should mention user turns: %q", summary)
}
if !strings.Contains(summary, "2 assistant turns") {
t.Errorf("summary should mention assistant turns: %q", summary)
}
}
func TestSummariseTruncatedEmpty(t *testing.T) {
cfg := DefaultCompressionConfig()
summary := summariseTruncated(nil, cfg)
if summary != cfg.SummaryMarker {
t.Errorf("empty summary = %q, want marker", summary)
}
}
func TestDefaultCompressionConfig(t *testing.T) {
cfg := DefaultCompressionConfig()
if !cfg.Enabled {
t.Error("default should be enabled")
}
if cfg.Threshold != 0.5 {
t.Errorf("Threshold = %v, want 0.5", cfg.Threshold)
}
if cfg.ContextWindow != 128000 {
t.Errorf("ContextWindow = %d, want 128000", cfg.ContextWindow)
}
if cfg.ProtectFirst != 3 {
t.Errorf("ProtectFirst = %d, want 3", cfg.ProtectFirst)
}
if cfg.ProtectLast != 20 {
t.Errorf("ProtectLast = %d, want 20", cfg.ProtectLast)
}
}
func TestCompressHistoryProtectClamp(t *testing.T) {
cfg := DefaultCompressionConfig()
cfg.ContextWindow = 1000
cfg.Threshold = 0.01 // compress with tiny window
cfg.ProtectFirst = 10
cfg.ProtectLast = 10
// Only 15 messages total: protect 10+10=20 would overflow.
msgs := makeMessages(15, 200)
view := CompressHistory(msgs, cfg)
if view.WasCompressed {
// If it did compress, first and last should be properly clamped.
if len(view.Messages) >= len(msgs) {
t.Errorf("compressed %d messages should be fewer than %d",
len(view.Messages), len(msgs))
}
}
}
func TestTruncate(t *testing.T) {
if got := truncate("hello", 10); got != "hello" {
t.Errorf("short string: %q", got)
}
if got := truncate("hello world this is long", 10); len(got) > 10+3 {
t.Errorf("long string too long: %q (%d)", got, len(got))
}
}
// makeMessages creates n alternating user/assistant messages, each
// contentLen characters long.
func makeMessages(n, contentLen int) []CompressedMessage {
out := make([]CompressedMessage, n)
for i := range n {
role := "user"
if i%2 == 1 {
role = "assistant"
}
out[i] = CompressedMessage{
Role: role,
Content: strings.Repeat("x", contentLen) + " msg " + itoa(i),
}
}
return out
}
func itoa(n int) string {
if n == 0 {
return "0"
}
var digits []byte
for n > 0 {
digits = append([]byte{byte('0' + n%10)}, digits...)
n /= 10
}
return string(digits)
}