@@ -1,6 +1,8 @@
11 package core
22
33 import (
4+ "context"
5+ "encoding/json"
46 "errors"
57 "fmt"
68 "path/filepath"
@@ -675,7 +677,7 @@ func TestZoeaListMysesCompaction(t *testing.T) {
675677 }
676678 }
677679
678-func TestContextPromptSourcePriority(t *testing.T) {
680+func TestGetContextMemories_CurrentTurnBoundary(t *testing.T) {
679681 s, bus, cleanup := setupMysisTest(t)
680682 defer cleanup()
681683
@@ -699,7 +701,7 @@ func TestContextPromptSourcePriority(t *testing.T) {
699701 expectedSender string
700702 }{
701703 {
702- name: "most_recent_message_defines_turn",
704+ name: "current_turn_start",
703705 setupMemories: func() {
704706 // Add system prompt
705707 s.AddMemory(stored.ID, store.MemoryRoleSystem, store.MemorySourceSystem, "System prompt", "", "")
@@ -707,7 +709,7 @@ func TestContextPromptSourcePriority(t *testing.T) {
707709 s.AddMemory(stored.ID, store.MemoryRoleUser, store.MemorySourceDirect, "Commander direct message", "", commanderID)
708710 // Add commander broadcast (middle)
709711 s.AddMemory(stored.ID, store.MemoryRoleUser, store.MemorySourceBroadcast, "Commander broadcast", "", commanderID)
710- // Add swarm broadcast (most recent - this defines the current turn)
712+ // Add swarm broadcast (most recent - this starts the current turn)
711713 s.AddMemory(stored.ID, store.MemoryRoleUser, store.MemorySourceBroadcast, "Swarm broadcast", "", swarmMysisID)
712714 },
713715 expectedSource: store.MemorySourceBroadcast,
@@ -768,14 +770,14 @@ func TestContextPromptSourcePriority(t *testing.T) {
768770 t.Fatalf("getContextMemories() error: %v", err)
769771 }
770772
771- // Find the prompt source in the returned memories
773+ // Find the current turn boundary in the returned memories
772774 // With turn-aware composition, the current turn starts at the most recent user prompt.
773- // The first user message in the result is the turn boundary.
775+ // The first user message in the result marks the turn boundary.
774776 var foundPromptSource *store.Memory
775777 for _, m := range memories {
776778 if m.Role == store.MemoryRoleUser {
777779 foundPromptSource = m
778- break // Take the first user message as the prompt source
780+ break // Take the first user message as the turn boundary
779781 }
780782 }
781783
@@ -795,9 +797,9 @@ func TestContextPromptSourcePriority(t *testing.T) {
795797 t.Error("expected nudge content to be non-empty")
796798 }
797799 } else {
798- // Should find the correct prompt source
800+ // Should find the correct turn boundary
799801 if foundPromptSource == nil {
800- t.Fatal("expected to find a prompt source, but got none")
802+ t.Fatal("expected to find a turn boundary, but got none")
801803 }
802804
803805 if foundPromptSource.Source != tt.expectedSource {
@@ -1639,6 +1641,206 @@ func TestCanAcceptMessages(t *testing.T) {
16391641 }
16401642 }
16411643
1644+// TestExecuteToolCall_ErrorPaths tests error handling in executeToolCall
1645+func TestExecuteToolCall_ErrorPaths(t *testing.T) {
1646+ s, bus, cleanup := setupMysisTest(t)
1647+ defer cleanup()
1648+
1649+ t.Run("nil_mcp_proxy", func(t *testing.T) {
1650+ stored, _ := s.CreateMysis("nil-proxy-test", "mock", "test-model", 0.7)
1651+ mock := provider.NewMock("mock", "response")
1652+ mysis := NewMysis(stored.ID, stored.Name, stored.CreatedAt, mock, s, bus)
1653+
1654+ // Call executeToolCall with nil proxy
1655+ tc := provider.ToolCall{
1656+ ID: "call_1",
1657+ Name: "test_tool",
1658+ Arguments: json.RawMessage(`{}`),
1659+ }
1660+
1661+ result, err := mysis.executeToolCall(context.Background(), nil, tc)
1662+
1663+ // Should return error result (not error), as per MCP design
1664+ if err != nil {
1665+ t.Errorf("expected no error, got %v", err)
1666+ }
1667+ if result == nil {
1668+ t.Fatal("expected result, got nil")
1669+ }
1670+ if !result.IsError {
1671+ t.Error("expected IsError=true when proxy is nil")
1672+ }
1673+ if !strings.Contains(result.Content[0].Text, "MCP not configured") {
1674+ t.Errorf("expected 'MCP not configured' error, got: %s", result.Content[0].Text)
1675+ }
1676+ })
1677+
1678+ t.Run("tool_call_timeout", func(t *testing.T) {
1679+ stored, _ := s.CreateMysis("timeout-test", "mock", "test-model", 0.7)
1680+ mock := provider.NewMock("mock", "response")
1681+ mysis := NewMysis(stored.ID, stored.Name, stored.CreatedAt, mock, s, bus)
1682+
1683+ // Create a context with very short timeout
1684+ ctx, cancel := context.WithTimeout(context.Background(), 1*time.Nanosecond)
1685+ defer cancel()
1686+ time.Sleep(10 * time.Millisecond) // Ensure timeout fires
1687+
1688+ proxy := mcp.NewProxy(nil)
1689+ tc := provider.ToolCall{
1690+ ID: "call_1",
1691+ Name: "get_status",
1692+ Arguments: json.RawMessage(`{}`),
1693+ }
1694+
1695+ result, err := mysis.executeToolCall(ctx, proxy, tc)
1696+
1697+ // When tool is not found, MCP returns an error result (not an error)
1698+ // This is testing that executeToolCall handles missing tools gracefully
1699+ if err != nil {
1700+ t.Errorf("expected no error (tool not found returns error result), got: %v", err)
1701+ }
1702+ if result == nil {
1703+ t.Fatal("expected result, got nil")
1704+ }
1705+ if !result.IsError {
1706+ t.Error("expected IsError=true for tool not found")
1707+ }
1708+ })
1709+
1710+ t.Run("invalid_tool_arguments", func(t *testing.T) {
1711+ stored, _ := s.CreateMysis("invalid-args-test", "mock", "test-model", 0.7)
1712+ mock := provider.NewMock("mock", "response")
1713+ mysis := NewMysis(stored.ID, stored.Name, stored.CreatedAt, mock, s, bus)
1714+
1715+ proxy := mcp.NewProxy(nil)
1716+ // Register a tool that validates arguments
1717+ proxy.RegisterTool(
1718+ mcp.Tool{
1719+ Name: "strict_tool",
1720+ Description: "Tool with strict arg validation",
1721+ InputSchema: json.RawMessage(`{"type":"object","properties":{"required_field":{"type":"string"}},"required":["required_field"]}`),
1722+ },
1723+ func(ctx context.Context, args json.RawMessage) (*mcp.ToolResult, error) {
1724+ var params struct {
1725+ RequiredField string `json:"required_field"`
1726+ }
1727+ if err := json.Unmarshal(args, ¶ms); err != nil {
1728+ return &mcp.ToolResult{
1729+ Content: []mcp.ContentBlock{{Type: "text", Text: "invalid JSON"}},
1730+ IsError: true,
1731+ }, nil
1732+ }
1733+ if params.RequiredField == "" {
1734+ return &mcp.ToolResult{
1735+ Content: []mcp.ContentBlock{{Type: "text", Text: "missing required_field"}},
1736+ IsError: true,
1737+ }, nil
1738+ }
1739+ return &mcp.ToolResult{
1740+ Content: []mcp.ContentBlock{{Type: "text", Text: "success"}},
1741+ }, nil
1742+ },
1743+ )
1744+
1745+ tc := provider.ToolCall{
1746+ ID: "call_1",
1747+ Name: "strict_tool",
1748+ Arguments: json.RawMessage(`{}`), // Missing required field
1749+ }
1750+
1751+ result, err := mysis.executeToolCall(context.Background(), proxy, tc)
1752+
1753+ if err != nil {
1754+ t.Errorf("expected no error, got %v", err)
1755+ }
1756+ if result == nil {
1757+ t.Fatal("expected result, got nil")
1758+ }
1759+ if !result.IsError {
1760+ t.Error("expected IsError=true for invalid arguments")
1761+ }
1762+ })
1763+
1764+ t.Run("mcp_call_tool_error", func(t *testing.T) {
1765+ stored, _ := s.CreateMysis("mcp-error-test", "mock", "test-model", 0.7)
1766+ mock := provider.NewMock("mock", "response")
1767+ mysis := NewMysis(stored.ID, stored.Name, stored.CreatedAt, mock, s, bus)
1768+
1769+ proxy := mcp.NewProxy(nil)
1770+ // Register a tool that returns an error
1771+ proxy.RegisterTool(
1772+ mcp.Tool{
1773+ Name: "error_tool",
1774+ Description: "Tool that fails",
1775+ InputSchema: json.RawMessage(`{"type":"object","properties":{}}`),
1776+ },
1777+ func(ctx context.Context, args json.RawMessage) (*mcp.ToolResult, error) {
1778+ return nil, fmt.Errorf("tool execution failed")
1779+ },
1780+ )
1781+
1782+ tc := provider.ToolCall{
1783+ ID: "call_1",
1784+ Name: "error_tool",
1785+ Arguments: json.RawMessage(`{}`),
1786+ }
1787+
1788+ result, err := mysis.executeToolCall(context.Background(), proxy, tc)
1789+
1790+ // executeToolCall should propagate the error
1791+ if err == nil {
1792+ t.Error("expected error from tool execution")
1793+ }
1794+ if !strings.Contains(err.Error(), "tool execution failed") {
1795+ t.Errorf("expected 'tool execution failed' error, got: %v", err)
1796+ }
1797+ // Result should be nil when handler returns error
1798+ if result != nil {
1799+ t.Errorf("expected nil result on error, got: %v", result)
1800+ }
1801+ })
1802+
1803+ t.Run("tool_result_parsing_with_empty_content", func(t *testing.T) {
1804+ stored, _ := s.CreateMysis("parse-test", "mock", "test-model", 0.7)
1805+ mock := provider.NewMock("mock", "response")
1806+ mysis := NewMysis(stored.ID, stored.Name, stored.CreatedAt, mock, s, bus)
1807+
1808+ proxy := mcp.NewProxy(nil)
1809+ // Register a tool that returns empty content
1810+ proxy.RegisterTool(
1811+ mcp.Tool{
1812+ Name: "empty_tool",
1813+ Description: "Tool with empty result",
1814+ InputSchema: json.RawMessage(`{"type":"object","properties":{}}`),
1815+ },
1816+ func(ctx context.Context, args json.RawMessage) (*mcp.ToolResult, error) {
1817+ return &mcp.ToolResult{
1818+ Content: []mcp.ContentBlock{}, // Empty content
1819+ }, nil
1820+ },
1821+ )
1822+
1823+ tc := provider.ToolCall{
1824+ ID: "call_1",
1825+ Name: "empty_tool",
1826+ Arguments: json.RawMessage(`{}`),
1827+ }
1828+
1829+ result, err := mysis.executeToolCall(context.Background(), proxy, tc)
1830+
1831+ if err != nil {
1832+ t.Errorf("expected no error, got %v", err)
1833+ }
1834+ if result == nil {
1835+ t.Fatal("expected result, got nil")
1836+ }
1837+ // Should handle empty content gracefully
1838+ if result.IsError {
1839+ t.Error("empty content should not be an error")
1840+ }
1841+ })
1842+}
1843+
16421844 func TestSendEphemeralMessage_IdleState(t *testing.T) {
16431845 s, bus, cleanup := setupMysisTest(t)
16441846 defer cleanup()
@@ -2121,3 +2323,114 @@ func TestGetContextMemories_OnlyHistoricalTurns(t *testing.T) {
21212323 t.Error("Expected historical user message to be included as current turn")
21222324 }
21232325 }
2326+
2327+// TestMysisName verifies the Name getter returns the mysis name.
2328+func TestMysisName(t *testing.T) {
2329+ s, bus, cleanup := setupMysisTest(t)
2330+ defer cleanup()
2331+
2332+ mock := provider.NewMock("mock", "response")
2333+
2334+ expectedName := "test-mysis-name"
2335+ stored, err := s.CreateMysis(expectedName, "mock", "mock-model", 0.7)
2336+ if err != nil {
2337+ t.Fatalf("CreateMysis() error: %v", err)
2338+ }
2339+
2340+ mysis := NewMysis(stored.ID, stored.Name, stored.CreatedAt, mock, s, bus)
2341+
2342+ if got := mysis.Name(); got != expectedName {
2343+ t.Errorf("Name() = %q, want %q", got, expectedName)
2344+ }
2345+}
2346+
2347+// TestMysisCreatedAt verifies the CreatedAt getter returns the creation timestamp.
2348+func TestMysisCreatedAt(t *testing.T) {
2349+ s, bus, cleanup := setupMysisTest(t)
2350+ defer cleanup()
2351+
2352+ mock := provider.NewMock("mock", "response")
2353+
2354+ beforeCreate := time.Now().Add(-time.Second)
2355+ stored, err := s.CreateMysis("test-mysis-time", "mock", "mock-model", 0.7)
2356+ if err != nil {
2357+ t.Fatalf("CreateMysis() error: %v", err)
2358+ }
2359+ afterCreate := time.Now().Add(time.Second)
2360+
2361+ mysis := NewMysis(stored.ID, stored.Name, stored.CreatedAt, mock, s, bus)
2362+
2363+ got := mysis.CreatedAt()
2364+ if got.Before(beforeCreate) || got.After(afterCreate) {
2365+ t.Errorf("CreatedAt() = %v, want between %v and %v", got, beforeCreate, afterCreate)
2366+ }
2367+}
2368+
2369+// TestBuildSystemPrompt_EdgeCases tests buildSystemPrompt error handling
2370+func TestBuildSystemPrompt_EdgeCases(t *testing.T) {
2371+ s, bus, cleanup := setupMysisTest(t)
2372+ defer cleanup()
2373+
2374+ t.Run("no_broadcasts_fallback", func(t *testing.T) {
2375+ stored, _ := s.CreateMysis("no-broadcasts", "mock", "test-model", 0.7)
2376+ mock := provider.NewMock("mock", "response")
2377+ mysis := NewMysis(stored.ID, stored.Name, stored.CreatedAt, mock, s, bus)
2378+
2379+ // Build system prompt with no broadcasts
2380+ prompt := mysis.buildSystemPrompt()
2381+
2382+ // Should contain fallback message
2383+ if !strings.Contains(prompt, "No commander directives yet") {
2384+ t.Error("expected fallback message when no broadcasts")
2385+ }
2386+ if !strings.Contains(prompt, "Grow more powerful while awaiting instructions") {
2387+ t.Error("expected fallback message when no broadcasts")
2388+ }
2389+ // Should still contain base SystemPrompt content
2390+ if !strings.Contains(prompt, "SpaceMolt") {
2391+ t.Error("expected base system prompt content")
2392+ }
2393+ })
2394+
2395+ t.Run("broadcast_with_unknown_sender", func(t *testing.T) {
2396+ stored, _ := s.CreateMysis("unknown-sender", "mock", "test-model", 0.7)
2397+ mock := provider.NewMock("mock", "response")
2398+ mysis := NewMysis(stored.ID, stored.Name, stored.CreatedAt, mock, s, bus)
2399+
2400+ // Add a broadcast with a non-existent sender ID
2401+ s.AddMemory("nonexistent-mysis-id", store.MemoryRoleUser, store.MemorySourceBroadcast, "Test broadcast", "", "nonexistent-mysis-id")
2402+
2403+ prompt := mysis.buildSystemPrompt()
2404+
2405+ // Should handle unknown sender gracefully
2406+ if !strings.Contains(prompt, "Unknown") {
2407+ t.Error("expected 'Unknown' sender name for non-existent sender")
2408+ }
2409+ // Should still include broadcast content
2410+ if !strings.Contains(prompt, "Test broadcast") {
2411+ t.Error("expected broadcast content in prompt")
2412+ }
2413+ })
2414+
2415+ t.Run("broadcast_with_valid_sender", func(t *testing.T) {
2416+ sender, _ := s.CreateMysis("sender-mysis", "mock", "test-model", 0.7)
2417+ receiver, _ := s.CreateMysis("receiver-mysis", "mock", "test-model", 0.7)
2418+
2419+ mock := provider.NewMock("mock", "response")
2420+ receiverMysis := NewMysis(receiver.ID, receiver.Name, receiver.CreatedAt, mock, s, bus)
2421+
2422+ // Add a broadcast from sender
2423+ s.AddMemory(receiver.ID, store.MemoryRoleUser, store.MemorySourceBroadcast, "Attack coordinates: X=100, Y=200", "", sender.ID)
2424+
2425+ prompt := receiverMysis.buildSystemPrompt()
2426+
2427+ // Should include sender name
2428+ if !strings.Contains(prompt, "sender-mysis") {
2429+ t.Error("expected sender name in prompt")
Cut short: this commit's diff is over 1000 lines.