xonecas.io
60255
Zn

Zoea-Nova / commit 470d781

feat(core): add context compression with sliding window

Agents now send only recent messages (MaxContextMessages=20) plus the
system prompt to the LLM, keeping inference fast. Full conversation
history remains in SQLite and is searchable via new MCP tools.

Changes:
- Add getContextMemories() for sliding window context assembly
- Add GetSystemMemory(), GetRecentMemories() store methods
- Add SearchMemories(), SearchBroadcasts() for history retrieval
- Add zoea_search_messages, zoea_search_broadcasts MCP tools
- Add SendMessageAsync/BroadcastAsync for non-blocking messaging
- Add turnMu to prevent concurrent agentic turns
- Add 30-second nudge loop to encourage agent autonomy
- Store agent lifecycle context for proper cancellation
- Improve system prompt with structured decision framework

xonecas2026-02-04 470d781c7afff7be1845799086f32152ede73c53 parent 9cc2606

5 files changed

documentation/CONTEXT_COMPRESSION.md+165−0
@@ -0,0 +1,165 @@
1+# Context Compression
2+
3+Agents in Zoea Nova use a sliding window approach to manage LLM context size. Instead of sending the entire conversation history to the LLM on each turn, agents send only recent messages plus the system prompt. This keeps inference fast while agents retain access to older memories through search tools.
4+
5+## Design
6+
7+### The Problem
8+
9+Without compression, agent context grows unbounded:
10+- Each tool call adds multiple messages (request + result)
11+- SpaceMolt gameplay involves frequent tool use (mining, trading, navigation)
12+- Large contexts slow inference and increase costs
13+- Eventually hits provider token limits
14+
15+### The Solution
16+
17+```
18+┌─────────────────────────────────────────────────────┐
19+│ LLM Context │
20+├─────────────────────────────────────────────────────┤
21+│ System Prompt (always included) │
22+├─────────────────────────────────────────────────────┤
23+│ Recent Messages (last 20) │
24+│ - User messages │
25+│ - Assistant responses │
26+│ - Tool calls and results │
27+└─────────────────────────────────────────────────────┘
28+
29+┌─────────────────────────────────────────────────────┐
30+│ Full Memory (SQLite) │
31+├─────────────────────────────────────────────────────┤
32+│ All messages since agent creation │
33+│ Searchable via zoea_search_messages tool │
34+└─────────────────────────────────────────────────────┘
35+```
36+
37+## Implementation
38+
39+### Constants
40+
41+```go
42+// internal/core/agent.go
43+
44+// MaxContextMessages limits how many recent messages to include in LLM context.
45+// Value chosen to cover ~2 server ticks worth of activity.
46+const MaxContextMessages = 20
47+```
48+
49+### Context Assembly
50+
51+The `getContextMemories()` method assembles context for each LLM call:
52+
53+1. Fetch the N most recent memories from SQLite
54+2. Fetch the system prompt (first system message for the agent)
55+3. If system prompt isn't already in recent memories, prepend it
56+4. Return the assembled context
57+
58+```go
59+func (a *Agent) getContextMemories() ([]*store.Memory, error) {
60+ recent, err := a.store.GetRecentMemories(a.id, MaxContextMessages)
61+ if err != nil {
62+ return nil, err
63+ }
64+
65+ system, err := a.store.GetSystemMemory(a.id)
66+ if err != nil {
67+ // No system prompt - use recent memories only
68+ return recent, nil
69+ }
70+
71+ // Check if system prompt is already first
72+ if len(recent) > 0 && recent[0].ID == system.ID {
73+ return recent, nil
74+ }
75+
76+ // Prepend system prompt
77+ result := make([]*store.Memory, 0, len(recent)+1)
78+ result = append(result, system)
79+ result = append(result, recent...)
80+ return result, nil
81+}
82+```
83+
84+### Store Methods
85+
86+```go
87+// internal/store/memories.go
88+
89+// GetSystemMemory retrieves the initial system prompt for an agent.
90+func (s *Store) GetSystemMemory(agentID string) (*Memory, error)
91+
92+// GetRecentMemories retrieves the most recent N memories for an agent.
93+func (s *Store) GetRecentMemories(agentID string, limit int) ([]*Memory, error)
94+
95+// SearchMemories searches memories by content text (case-sensitive).
96+func (s *Store) SearchMemories(agentID, query string, limit int) ([]*Memory, error)
97+
98+// SearchBroadcasts searches broadcast messages by content text (case-sensitive).
99+func (s *Store) SearchBroadcasts(query string, limit int) ([]*BroadcastMessage, error)
100+```
101+
102+## Search Tools
103+
104+Agents can retrieve older memories using MCP tools exposed through the orchestrator:
105+
106+### zoea_search_messages
107+
108+Search an agent's past messages by text content.
109+
110+```json
111+{
112+ "agent_id": "abc123",
113+ "query": "iron ore",
114+ "limit": 20
115+}
116+```
117+
118+Returns matching messages with role, source, content, and timestamp.
119+
120+### zoea_search_broadcasts
121+
122+Search past swarm broadcasts by text content.
123+
124+```json
125+{
126+ "query": "enemy spotted",
127+ "limit": 20
128+}
129+```
130+
131+Returns matching broadcasts with content and timestamp.
132+
133+## System Prompt Guidance
134+
135+The system prompt instructs agents to use their captain's log for persistent memory:
136+
137+```
138+## Memory
139+Use captain's log (captains_log_add) to remember:
140+- Your password (CRITICAL)
141+- Discovered systems and their resources
142+- Player encounters (friendly or hostile)
143+- Current objectives and plans
144+```
145+
146+This encourages agents to externalize important information to the game's built-in note system, which persists across context windows.
147+
148+## Tradeoffs
149+
150+| Aspect | Benefit | Cost |
151+|--------|---------|------|
152+| Inference speed | Faster responses with smaller context | May lose relevant older context |
153+| Token costs | Lower per-request costs | Search queries add overhead |
154+| Memory access | Full history searchable | Requires explicit search |
155+| Coherence | Recent context always available | Long-term plans may be forgotten |
156+
157+## Tuning
158+
159+The `MaxContextMessages` constant can be adjusted based on:
160+
161+- **Model context window**: Larger models can handle more messages
162+- **Gameplay pace**: Faster tick rates may need larger windows
163+- **Tool call frequency**: Heavy tool use fills context faster
164+
165+Current value of 20 messages covers approximately 2 server ticks of typical gameplay activity.
internal/core/agent.go+149−22
@@ -14,27 +14,68 @@ import (
1414 )
1515
1616 // SystemPrompt is the initial prompt sent to every agent when they first start.
17-const SystemPrompt = `You are an AI agent playing SpaceMolt, an online multiplayer game.
18-
19-You have function calling capabilities. Use the tools provided to interact with the game.
20-
21-When you start, explore the available tools to understand what actions you can take. Register or login, then play the game - interact with other players and explore.
22-
23-Play indefinitely and provide updates to the user about your progress. If you encounter errors, try different approaches.
17+const SystemPrompt = `You are an autonomous AI pilot in SpaceMolt. Think for yourself. Adapt. Survive.
18+
19+## Bootstrap Sequence
20+1. get_status → Am I logged in?
21+2. If no session: register (pick a name, empire="solarian") → SAVE THE PASSWORD
22+3. If returning: login with saved credentials
23+4. Assess: get_system, get_poi, get_nearby, get_cargo
24+
25+## Decision Framework
26+Before each action, consider:
27+- **Safety:** What's the police_level? Who's nearby? Am I in danger?
28+- **Resources:** What's in my cargo? How much fuel? Hull status?
29+- **Opportunity:** Can I mine here? Trade? Explore?
30+- **Goals:** What am I trying to achieve right now?
31+
32+## Action Priority
33+1. **Survival** - If hull low: dock and repair. If fuel low: refuel.
34+2. **Income** - Mine, trade, complete missions. Credits = options.
35+3. **Progression** - Skills train passively. Mining → mining skill. Trading → trading skill.
36+4. **Exploration** - Discover new systems. First discovery = 500 credits + XP.
37+
38+## Situational Responses
39+- **Attacked?** Fight back, flee, or cloak (if you have the module)
40+- **Found a wreck?** Loot it (loot_wreck) or salvage it (salvage_wreck)
41+- **See a pilotless ship?** Opportunity to attack without retaliation
42+- **Low on options?** Check missions (get_missions) for direction
43+
44+## Memory
45+Use captain's log (captains_log_add) to remember:
46+- Your password (CRITICAL)
47+- Discovered systems and their resources
48+- Player encounters (friendly or hostile)
49+- Current objectives and plans
2450
2551 ## Swarm Coordination
52+You're part of a swarm. Use zoea_* tools to:
53+- zoea_list_agents, zoea_swarm_status: See swarm state
54+- zoea_send_message: Direct message a specific agent
55+- zoea_broadcast: Message all running agents
56+- zoea_search_messages: Search your past messages by text
57+- zoea_search_broadcasts: Search past swarm broadcasts by text
58+- Report threats and opportunities
59+- Request assistance
60+- Coordinate territory
2661
27-You are part of a swarm of AI agents. You can coordinate with other agents using these tools:
62+## Thinking Style
63+Keep your reasoning brief - decide and act, don't over-analyze.
2864
29-- zoea_list_agents: See all agents in the swarm and their status
30-- zoea_get_agent: Get details about a specific agent
31-- zoea_swarm_status: Get overall swarm statistics
32-- zoea_send_message: Send a message to another agent
33-- zoea_broadcast: Send a message to all running agents`
65+No hand-holding. Figure it out. Adapt or die.`
3466
3567 // MaxToolIterations limits the number of tool call loops to prevent infinite loops.
3668 const MaxToolIterations = 10
3769
70+// MaxContextMessages limits how many recent messages to include in LLM context.
71+// This keeps context small for faster inference while agents can use search tools
72+// to retrieve older memories when needed. Value chosen to cover ~2 server ticks
73+// worth of activity (each tick may involve multiple tool calls).
74+const MaxContextMessages = 20
75+
76+// ContinuePrompt is sent to agents when they finish a turn to encourage autonomy.
77+const ContinuePrompt = "Turn complete. What is your next move? If you are waiting for something, describe what and why. Otherwise, continue your mission."
78+
3879 // Agent represents a single AI agent in the swarm.
3980 type Agent struct {
4081 mu sync.RWMutex
@@ -48,8 +89,12 @@ type Agent struct {
4889 mcp *mcp.Proxy
4990
5091 state AgentState
92+ ctx context.Context
5193 cancel context.CancelFunc
5294
95+ // turnMu ensures only one agentic turn runs at a time.
96+ turnMu sync.Mutex
97+
5398 // For runtime tracking
5499 lastError error
55100 }
@@ -135,6 +180,7 @@ func (a *Agent) Start() error {
135180 a.lastError = nil
136181
137182 ctx, cancel := context.WithCancel(context.Background())
183+ a.ctx = ctx
138184 a.cancel = cancel
139185 a.mu.Unlock()
140186
@@ -159,6 +205,9 @@ func (a *Agent) Start() error {
159205 // Start the processing goroutine
160206 go a.run(ctx)
161207
208+ // Trigger initial turn to encourage autonomy
209+ go a.SendMessage(ContinuePrompt, store.MemorySourceSystem)
210+
162211 return nil
163212 }
164213
@@ -172,8 +221,16 @@ func (a *Agent) Stop() error {
172221
173222 if a.cancel != nil {
174223 a.cancel()
175- a.cancel = nil
176224 }
225+ a.mu.Unlock()
226+
227+ // Wait for current turn to finish
228+ a.turnMu.Lock()
229+ defer a.turnMu.Unlock()
230+
231+ a.mu.Lock()
232+ a.cancel = nil
233+ a.ctx = nil
177234
178235 oldState := a.state
179236 a.state = AgentStateStopped
@@ -194,6 +251,9 @@ func (a *Agent) Stop() error {
194251 // This implements the agentic loop with tool calling support.
195252 // The source parameter indicates whether this is a direct or broadcast message.
196253 func (a *Agent) SendMessage(content string, source store.MemorySource) error {
254+ a.turnMu.Lock()
255+ defer a.turnMu.Unlock()
256+
197257 a.mu.RLock()
198258 state := a.state
199259 p := a.provider
@@ -204,8 +264,14 @@ func (a *Agent) SendMessage(content string, source store.MemorySource) error {
204264 return fmt.Errorf("agent not running")
205265 }
206266
207- // Store the user message
208- if _, err := a.store.AddMemory(a.id, store.MemoryRoleUser, source, content); err != nil {
267+ // Determine role based on source
268+ role := store.MemoryRoleUser
269+ if source == store.MemorySourceSystem {
270+ role = store.MemoryRoleSystem
271+ }
272+
273+ // Store the message
274+ if _, err := a.store.AddMemory(a.id, role, source, content); err != nil {
209275 return fmt.Errorf("store message: %w", err)
210276 }
211277
@@ -214,12 +280,20 @@ func (a *Agent) SendMessage(content string, source store.MemorySource) error {
214280 Type: EventAgentMessage,
215281 AgentID: a.id,
216282 AgentName: a.name,
217- Data: MessageData{Role: "user", Content: content},
283+ Data: MessageData{Role: string(role), Content: content},
218284 Timestamp: time.Now(),
219285 })
220286
221287 // Create context for the entire conversation turn
222- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
288+ a.mu.RLock()
289+ parentCtx := a.ctx
290+ a.mu.RUnlock()
291+
292+ if parentCtx == nil {
293+ parentCtx = context.Background()
294+ }
295+
296+ ctx, cancel := context.WithTimeout(parentCtx, 5*time.Minute)
223297 defer cancel()
224298
225299 // Get available tools from MCP proxy
@@ -269,9 +343,10 @@ func (a *Agent) SendMessage(content string, source store.MemorySource) error {
269343
270344 // Agentic loop: keep calling LLM until we get a final text response
271345 for iteration := 0; iteration < MaxToolIterations; iteration++ {
272- // Get conversation history
273- memories, err := a.store.GetMemories(a.id)
346+ // Get recent conversation history (keeps context small for faster inference)
347+ memories, err := a.getContextMemories()
274348 if err != nil {
349+ a.setError(err)
275350 return fmt.Errorf("get memories: %w", err)
276351 }
277352
@@ -311,6 +386,7 @@ func (a *Agent) SendMessage(content string, source store.MemorySource) error {
311386 // Store the assistant's tool call request
312387 toolCallJSON := a.formatToolCallsForStorage(response.ToolCalls)
313388 if _, err := a.store.AddMemory(a.id, store.MemoryRoleAssistant, store.MemorySourceLLM, toolCallJSON); err != nil {
389+ a.setError(err)
314390 return fmt.Errorf("store tool call: %w", err)
315391 }
316392
@@ -342,6 +418,7 @@ func (a *Agent) SendMessage(content string, source store.MemorySource) error {
342418 // Store the tool result
343419 resultContent := a.formatToolResult(tc.ID, tc.Name, result, execErr)
344420 if _, err := a.store.AddMemory(a.id, store.MemoryRoleTool, store.MemorySourceTool, resultContent); err != nil {
421+ a.setError(err)
345422 return fmt.Errorf("store tool result: %w", err)
346423 }
347424
@@ -367,6 +444,7 @@ func (a *Agent) SendMessage(content string, source store.MemorySource) error {
367444
368445 // Store the assistant response
369446 if _, err := a.store.AddMemory(a.id, store.MemoryRoleAssistant, store.MemorySourceLLM, finalResponse); err != nil {
447+ a.setError(err)
370448 return fmt.Errorf("store response: %w", err)
371449 }
372450
@@ -528,10 +606,59 @@ func (a *Agent) setError(err error) {
528606 })
529607 }
530608
609+// getContextMemories returns memories for LLM context: system prompt + recent messages.
610+// This keeps context small for faster inference while preserving essential information.
611+func (a *Agent) getContextMemories() ([]*store.Memory, error) {
612+ // Get recent memories (limited for performance)
613+ recent, err := a.store.GetRecentMemories(a.id, MaxContextMessages)
614+ if err != nil {
615+ return nil, err
616+ }
617+
618+ // Always try to fetch the system prompt and prepend it if not already first
619+ system, err := a.store.GetSystemMemory(a.id)
620+ if err != nil {
621+ // No system prompt found - this is okay, just use recent memories
622+ return recent, nil
623+ }
624+
625+ // Check if system prompt is already the first message
626+ if len(recent) > 0 && recent[0].ID == system.ID {
627+ return recent, nil
628+ }
629+
630+ // Prepend system prompt to recent memories
631+ result := make([]*store.Memory, 0, len(recent)+1)
632+ result = append(result, system)
633+ result = append(result, recent...)
634+ return result, nil
635+}
636+
531637 // run is the agent's main processing loop.
532638 func (a *Agent) run(ctx context.Context) {
533- <-ctx.Done()
534- // Context cancelled, agent stopped
639+ // Ticker to nudge the agent if it's idle
640+ ticker := time.NewTicker(30 * time.Second)
641+ defer ticker.Stop()
642+
643+ for {
644+ select {
645+ case <-ctx.Done():
646+ return
647+ case <-ticker.C:
648+ // Only nudge if the agent is running and not already in a turn
649+ a.mu.RLock()
650+ isRunning := a.state == AgentStateRunning
651+ a.mu.RUnlock()
652+
653+ if isRunning {
654+ // Only nudge if not already in a turn
655+ if a.turnMu.TryLock() {
656+ a.turnMu.Unlock()
657+ go a.SendMessage(ContinuePrompt, store.MemorySourceSystem)
658+ }
659+ }
660+ }
661+ }
535662 }
536663
537664 func (a *Agent) emitStateChange(oldState, newState AgentState) {
internal/core/commander.go+61−6
@@ -130,14 +130,14 @@ func (c *Commander) DeleteAgent(id string, purgeMemories bool) error {
130130 return fmt.Errorf("agent not found: %s", id)
131131 }
132132
133- // Stop if running
133+ delete(c.agents, id)
134+ c.mu.Unlock()
135+
136+ // Stop if running (outside of commander lock to avoid deadlock)
134137 if agent.State() == AgentStateRunning {
135138 agent.Stop()
136139 }
137140
138- delete(c.agents, id)
139- c.mu.Unlock()
140-
141141 // Delete from store (memories cascade)
142142 if err := c.store.DeleteAgent(id); err != nil {
143143 return fmt.Errorf("delete agent from store: %w", err)
@@ -241,7 +241,7 @@ func (c *Commander) ConfigureAgent(id, providerName string) error {
241241 return nil
242242 }
243243
244-// SendMessage sends a message to a specific agent.
244+// SendMessage sends a message to a specific agent (synchronous).
245245 func (c *Commander) SendMessage(id, content string) error {
246246 agent, err := c.GetAgent(id)
247247 if err != nil {
@@ -250,7 +250,25 @@ func (c *Commander) SendMessage(id, content string) error {
250250 return agent.SendMessage(content, store.MemorySourceDirect)
251251 }
252252
253-// Broadcast sends a message to all running agents.
253+// SendMessageAsync sends a message to a specific agent without waiting for processing.
254+// Returns immediately after validating the agent exists and is running.
255+func (c *Commander) SendMessageAsync(id, content string) error {
256+ agent, err := c.GetAgent(id)
257+ if err != nil {
258+ return err
259+ }
260+ if agent.State() != AgentStateRunning {
261+ return fmt.Errorf("agent not running")
262+ }
263+ go func() {
264+ if err := agent.SendMessage(content, store.MemorySourceDirect); err != nil {
265+ // Error is published to bus by agent.SendMessage
266+ }
267+ }()
268+ return nil
269+}
270+
271+// Broadcast sends a message to all running agents (synchronous).
254272 func (c *Commander) Broadcast(content string) error {
255273 c.mu.RLock()
256274 agents := make([]*Agent, 0)
@@ -286,6 +304,43 @@ func (c *Commander) Broadcast(content string) error {
286304 return nil
287305 }
288306
307+// BroadcastAsync sends a message to all running agents without waiting for processing.
308+// Returns immediately after validating at least one agent is running.
309+func (c *Commander) BroadcastAsync(content string) error {
310+ c.mu.RLock()
311+ agents := make([]*Agent, 0)
312+ for _, a := range c.agents {
313+ if a.State() == AgentStateRunning {
314+ agents = append(agents, a)
315+ }
316+ }
317+ c.mu.RUnlock()
318+
319+ // Check if any agents are running
320+ if len(agents) == 0 {
321+ return fmt.Errorf("no running agents to receive broadcast")
322+ }
323+
324+ // Emit broadcast event
325+ c.bus.Publish(Event{
326+ Type: EventBroadcast,
327+ Data: MessageData{Role: "user", Content: content},
328+ Timestamp: time.Now(),
329+ })
330+
331+ // Send to each agent asynchronously
332+ for _, a := range agents {
333+ agent := a // capture for goroutine
334+ go func() {
335+ if err := agent.SendMessage(content, store.MemorySourceBroadcast); err != nil {
336+ // Error is published to bus by agent.SendMessage
337+ }
338+ }()
339+ }
340+
341+ return nil
342+}
343+
289344 // StopAll stops all running agents.
290345 func (c *Commander) StopAll() {
291346 c.mu.RLock()
internal/mcp/tools.go+147−7
@@ -15,6 +15,20 @@ type AgentInfo struct {
1515 LastError error
1616 }
1717
18+// SearchResult represents a search result from memory.
19+type SearchResult struct {
20+ Role string
21+ Source string
22+ Content string
23+ CreatedAt string
24+}
25+
26+// BroadcastResult represents a broadcast search result.
27+type BroadcastResult struct {
28+ Content string
29+ CreatedAt string
30+}
31+
1832 // Orchestrator defines the interface for swarm orchestration.
1933 // This interface breaks the import cycle between mcp and core packages.
2034 type Orchestrator interface {
@@ -22,8 +36,10 @@ type Orchestrator interface {
2236 GetAgent(id string) (AgentInfo, error)
2337 AgentCount() int
2438 MaxAgents() int
25- SendMessage(agentID, message string) error
26- Broadcast(message string) error
39+ SendMessageAsync(agentID, message string) error
40+ BroadcastAsync(message string) error
41+ SearchMessages(agentID, query string, limit int) ([]SearchResult, error)
42+ SearchBroadcasts(query string, limit int) ([]BroadcastResult, error)
2743 }
2844
2945 // RegisterOrchestratorTools registers the internal orchestration tools with the proxy.
@@ -171,7 +187,7 @@ func RegisterOrchestratorTools(proxy *Proxy, orchestrator Orchestrator) {
171187 }, nil
172188 }
173189
174- if err := orchestrator.SendMessage(params.AgentID, params.Message); err != nil {
190+ if err := orchestrator.SendMessageAsync(params.AgentID, params.Message); err != nil {
175191 return &ToolResult{
176192 Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("failed to send message: %v", err)}},
177193 IsError: true,
@@ -179,7 +195,7 @@ func RegisterOrchestratorTools(proxy *Proxy, orchestrator Orchestrator) {
179195 }
180196
181197 return &ToolResult{
182- Content: []ContentBlock{{Type: "text", Text: "message sent successfully"}},
198+ Content: []ContentBlock{{Type: "text", Text: "message queued for delivery"}},
183199 }, nil
184200 },
185201 )
@@ -208,15 +224,139 @@ func RegisterOrchestratorTools(proxy *Proxy, orchestrator Orchestrator) {
208224 }, nil
209225 }
210226
211- if err := orchestrator.Broadcast(params.Message); err != nil {
227+ if err := orchestrator.BroadcastAsync(params.Message); err != nil {
212228 return &ToolResult{
213- Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("broadcast partially failed: %v", err)}},
229+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("broadcast failed: %v", err)}},
214230 IsError: true,
215231 }, nil
216232 }
217233
218234 return &ToolResult{
219- Content: []ContentBlock{{Type: "text", Text: "broadcast sent successfully"}},
235+ Content: []ContentBlock{{Type: "text", Text: "broadcast queued for delivery to all running agents"}},
236+ }, nil
237+ },
238+ )
239+
240+ // Search messages tool
241+ proxy.RegisterTool(
242+ Tool{
243+ Name: "zoea_search_messages",
244+ Description: "Search your past messages (direct messages, responses, tool results) by text content",
245+ InputSchema: json.RawMessage(`{
246+ "type": "object",
247+ "properties": {
248+ "agent_id": {"type": "string", "description": "The ID of the agent whose messages to search"},
249+ "query": {"type": "string", "description": "Text to search for in message content"},
250+ "limit": {"type": "integer", "description": "Maximum results to return (default 20, max 100)"}
251+ },
252+ "required": ["agent_id", "query"]
253+ }`),
254+ },
255+ func(ctx context.Context, args json.RawMessage) (*ToolResult, error) {
256+ var params struct {
257+ AgentID string `json:"agent_id"`
258+ Query string `json:"query"`
259+ Limit int `json:"limit"`
260+ }
261+ if err := json.Unmarshal(args, &params); err != nil {
262+ return &ToolResult{
263+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("invalid arguments: %v", err)}},
264+ IsError: true,
265+ }, nil
266+ }
267+
268+ if params.Query == "" {
269+ return &ToolResult{
270+ Content: []ContentBlock{{Type: "text", Text: "query cannot be empty"}},
271+ IsError: true,
272+ }, nil
273+ }
274+
275+ limit := params.Limit
276+ if limit <= 0 {
277+ limit = 20
278+ } else if limit > 100 {
279+ limit = 100
280+ }
281+
282+ results, err := orchestrator.SearchMessages(params.AgentID, params.Query, limit)
283+ if err != nil {
284+ return &ToolResult{
285+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("search failed: %v", err)}},
286+ IsError: true,
287+ }, nil
288+ }
289+
290+ if len(results) == 0 {
291+ return &ToolResult{
292+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("no messages found matching '%s'", params.Query)}},
293+ }, nil
294+ }
295+
296+ data, _ := json.MarshalIndent(results, "", " ")
297+ return &ToolResult{
298+ Content: []ContentBlock{{Type: "text", Text: string(data)}},
299+ }, nil
300+ },
301+ )
302+
303+ // Search broadcasts tool
304+ proxy.RegisterTool(
305+ Tool{
306+ Name: "zoea_search_broadcasts",
307+ Description: "Search past swarm broadcasts by text content",
308+ InputSchema: json.RawMessage(`{
309+ "type": "object",
310+ "properties": {
311+ "query": {"type": "string", "description": "Text to search for in broadcast content"},
312+ "limit": {"type": "integer", "description": "Maximum results to return (default 20, max 100)"}
313+ },
314+ "required": ["query"]
315+ }`),
316+ },
317+ func(ctx context.Context, args json.RawMessage) (*ToolResult, error) {
318+ var params struct {
319+ Query string `json:"query"`
320+ Limit int `json:"limit"`
321+ }
322+ if err := json.Unmarshal(args, &params); err != nil {
323+ return &ToolResult{
324+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("invalid arguments: %v", err)}},
325+ IsError: true,
326+ }, nil
327+ }
328+
329+ if params.Query == "" {
330+ return &ToolResult{
331+ Content: []ContentBlock{{Type: "text", Text: "query cannot be empty"}},
332+ IsError: true,
333+ }, nil
334+ }
335+
336+ limit := params.Limit
337+ if limit <= 0 {
338+ limit = 20
339+ } else if limit > 100 {
340+ limit = 100
341+ }
342+
343+ results, err := orchestrator.SearchBroadcasts(params.Query, limit)
344+ if err != nil {
345+ return &ToolResult{
346+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("search failed: %v", err)}},
347+ IsError: true,
348+ }, nil
349+ }
350+
351+ if len(results) == 0 {
352+ return &ToolResult{
353+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("no broadcasts found matching '%s'", params.Query)}},
354+ }, nil
355+ }
356+
357+ data, _ := json.MarshalIndent(results, "", " ")
358+ return &ToolResult{
359+ Content: []ContentBlock{{Type: "text", Text: string(data)}},
220360 }, nil
221361 },
222362 )
internal/store/memories.go+88−0
@@ -84,6 +84,22 @@ func (s *Store) GetMemories(agentID string) ([]*Memory, error) {
8484 return memories, rows.Err()
8585 }
8686
87+// GetSystemMemory retrieves the initial system prompt for an agent.
88+func (s *Store) GetSystemMemory(agentID string) (*Memory, error) {
89+ var m Memory
90+ err := s.db.QueryRow(`
91+ SELECT id, agent_id, role, source, content, created_at
92+ FROM memories
93+ WHERE agent_id = ? AND role = 'system' AND source = 'system'
94+ ORDER BY created_at ASC
95+ LIMIT 1
96+ `, agentID).Scan(&m.ID, &m.AgentID, &m.Role, &m.Source, &m.Content, &m.CreatedAt)
97+ if err != nil {
98+ return nil, err
99+ }
100+ return &m, nil
101+}
102+
87103 // GetRecentMemories retrieves the most recent N memories for an agent.
88104 func (s *Store) GetRecentMemories(agentID string, limit int) ([]*Memory, error) {
89105 rows, err := s.db.Query(`
@@ -178,3 +194,75 @@ func (s *Store) GetRecentBroadcasts(limit int) ([]*BroadcastMessage, error) {
178194
179195 return messages, rows.Err()
180196 }
197+
198+// SearchMemories searches memories for an agent by content text.
199+// Returns memories where content contains the query string (case-sensitive).
200+func (s *Store) SearchMemories(agentID, query string, limit int) ([]*Memory, error) {
201+ rows, err := s.db.Query(`
202+ SELECT id, agent_id, role, source, content, created_at
203+ FROM memories
204+ WHERE agent_id = ? AND content LIKE '%' || ? || '%'
205+ ORDER BY created_at DESC
206+ LIMIT ?
207+ `, agentID, query, limit)
208+ if err != nil {
209+ return nil, fmt.Errorf("search memories: %w", err)
210+ }
211+ defer rows.Close()
212+
213+ var memories []*Memory
214+ for rows.Next() {
215+ var m Memory
216+ if err := rows.Scan(&m.ID, &m.AgentID, &m.Role, &m.Source, &m.Content, &m.CreatedAt); err != nil {
217+ return nil, fmt.Errorf("scan memory: %w", err)
218+ }
219+ memories = append(memories, &m)
220+ }
221+
222+ // Reverse to get chronological order (oldest first)
223+ for i, j := 0, len(memories)-1; i < j; i, j = i+1, j-1 {
224+ memories[i], memories[j] = memories[j], memories[i]
225+ }
226+
227+ return memories, rows.Err()
228+}
229+
230+// SearchBroadcasts searches unique broadcast messages by content text.
231+// Returns broadcasts where content contains the query string (case-sensitive).
232+func (s *Store) SearchBroadcasts(query string, limit int) ([]*BroadcastMessage, error) {
233+ rows, err := s.db.Query(`
234+ SELECT content, MAX(created_at) as created_at
235+ FROM memories
236+ WHERE source = 'broadcast' AND content LIKE '%' || ? || '%'
237+ GROUP BY content
238+ ORDER BY created_at DESC
239+ LIMIT ?
240+ `, query, limit)
241+ if err != nil {
242+ return nil, fmt.Errorf("search broadcasts: %w", err)
243+ }
244+ defer rows.Close()
245+
246+ var messages []*BroadcastMessage
247+ for rows.Next() {
248+ var content, createdAtStr string
249+ if err := rows.Scan(&content, &createdAtStr); err != nil {
250+ return nil, fmt.Errorf("scan broadcast: %w", err)
251+ }
252+ createdAt, _ := time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", createdAtStr)
253+ if createdAt.IsZero() {
254+ createdAt, _ = time.Parse(time.RFC3339Nano, createdAtStr)
255+ }
256+ messages = append(messages, &BroadcastMessage{
257+ Content: content,
258+ CreatedAt: createdAt,
259+ })
260+ }
261+
262+ // Reverse to get chronological order (oldest first)
263+ for i, j := 0, len(messages)-1; i < j; i, j = i+1, j-1 {
264+ messages[i], messages[j] = messages[j], messages[i]
265+ }
266+
267+ return messages, rows.Err()
268+}