xonecas.io
60255
Zn

Zoea-Nova / commit f7ab37c

feat(core): add context composition helpers

- selectPromptSource: priority-based prompt selection
  (commander direct → commander broadcast → swarm broadcast → nudge)
- extractLatestToolLoop: most recent tool-call + results extraction

Both helpers:
- Handle all edge cases (nil/empty inputs, no matches)
- Pure functions with no mutations
- Comprehensive unit test coverage
- O(n) time complexity

Phase 2 complete - ready for Phase 3 integration.

xonecas2026-02-07 f7ab37c9aa960e6d5e7ed9cc669910008de00df5 parent 98fa0a9

2 files changed

internal/core/mysis.go+107−0
@@ -1264,6 +1264,113 @@ func (m *Mysis) setIdle(reason string) {
12641264 a.releaseCurrentAccount()
12651265 }
12661266
1267+// selectPromptSource chooses the prompt source memory by priority:
1268+// 1. Most recent commander direct message (source="direct")
1269+// 2. Last commander broadcast (source="broadcast", sender_id="")
1270+// 3. Last swarm broadcast (source="broadcast", sender_id!=commander)
1271+// 4. Return nil if none found (caller will generate synthetic nudge)
1272+//
1273+// The commander is identified by empty sender_id in broadcasts.
1274+// Memories are expected to be ordered newest-first (from getContextMemories).
1275+func (m *Mysis) selectPromptSource(memories []*store.Memory) *store.Memory {
1276+ if len(memories) == 0 {
1277+ return nil
1278+ }
1279+
1280+ // Track most recent broadcast from commander (sender_id="") and swarm (sender_id!="")
1281+ var lastCommanderBroadcast *store.Memory
1282+ var lastSwarmBroadcast *store.Memory
1283+
1284+ // Scan memories in order (newest first)
1285+ for _, mem := range memories {
1286+ // Skip non-user messages
1287+ if mem.Role != store.MemoryRoleUser {
1288+ continue
1289+ }
1290+
1291+ // Priority 1: Commander direct message (highest priority)
1292+ if mem.Source == store.MemorySourceDirect {
1293+ return mem
1294+ }
1295+
1296+ // Track broadcasts by sender
1297+ if mem.Source == store.MemorySourceBroadcast {
1298+ if mem.SenderID == "" {
1299+ // Commander broadcast (empty sender_id)
1300+ if lastCommanderBroadcast == nil {
1301+ lastCommanderBroadcast = mem
1302+ }
1303+ } else {
1304+ // Swarm broadcast (non-empty sender_id)
1305+ if lastSwarmBroadcast == nil {
1306+ lastSwarmBroadcast = mem
1307+ }
1308+ }
1309+ }
1310+ }
1311+
1312+ // Priority 2: Last commander broadcast
1313+ if lastCommanderBroadcast != nil {
1314+ return lastCommanderBroadcast
1315+ }
1316+
1317+ // Priority 3: Last swarm broadcast
1318+ if lastSwarmBroadcast != nil {
1319+ return lastSwarmBroadcast
1320+ }
1321+
1322+ // Priority 4: No prompt source found - return nil for synthetic nudge
1323+ return nil
1324+}
1325+
1326+// extractLatestToolLoop finds the most recent tool-call message (assistant role
1327+// with tool_calls) and returns it plus all subsequent tool results.
1328+//
1329+// Returns: [tool-call-message, result1, result2, ...] or empty slice if no tool loop found.
1330+//
1331+// The function scans memories backwards from the end (since GetRecentMemories returns
1332+// chronological order: oldest first, newest last) to find the most recent tool call.
1333+func (m *Mysis) extractLatestToolLoop(memories []*store.Memory) []*store.Memory {
1334+ if len(memories) == 0 {
1335+ return nil
1336+ }
1337+
1338+ // Scan backwards from the end (newest first) to find the most recent tool call
1339+ toolCallIdx := -1
1340+ for i := len(memories) - 1; i >= 0; i-- {
1341+ mem := memories[i]
1342+ if mem.Role == store.MemoryRoleAssistant &&
1343+ strings.HasPrefix(mem.Content, constants.ToolCallStoragePrefix) {
1344+ toolCallIdx = i
1345+ break
1346+ }
1347+ }
1348+
1349+ // No tool calls found
1350+ if toolCallIdx == -1 {
1351+ return nil
1352+ }
1353+
1354+ // Collect the tool call message and all subsequent tool results
1355+ result := make([]*store.Memory, 0, 4) // Pre-allocate for typical case (1 call + 2-3 results)
1356+ result = append(result, memories[toolCallIdx])
1357+
1358+ // Scan forward (later in time) for consecutive tool results
1359+ for i := toolCallIdx + 1; i < len(memories); i++ {
1360+ mem := memories[i]
1361+
1362+ // Only collect tool role messages
1363+ if mem.Role == store.MemoryRoleTool {
1364+ result = append(result, mem)
1365+ } else {
1366+ // Stop at first non-tool message (end of loop)
1367+ break
1368+ }
1369+ }
1370+
1371+ return result
1372+}
1373+
12671374 // getContextMemories returns memories for LLM context: system prompt + recent messages.
12681375 // This keeps context small for faster inference while preserving essential information.
12691376 // Compacts repeated snapshot tool results to prefer recent state.
internal/core/mysis_test.go+208−0
@@ -794,6 +794,214 @@ func TestContextPromptSourcePriority(t *testing.T) {
794794 }
795795 }
796796
797+func TestSelectPromptSourceHelper(t *testing.T) {
798+ s, bus, cleanup := setupMysisTest(t)
799+ defer cleanup()
800+
801+ stored, err := s.CreateMysis("helper-test", "mock", "test-model", 0.7)
802+ if err != nil {
803+ t.Fatalf("CreateMysis() error: %v", err)
804+ }
805+
806+ mock := provider.NewMock("mock", "response")
807+ mysis := NewMysis(stored.ID, stored.Name, stored.CreatedAt, mock, s, bus)
808+
809+ tests := []struct {
810+ name string
811+ memories []*store.Memory
812+ expectedSource store.MemorySource
813+ expectedSender string
814+ expectNil bool
815+ }{
816+ {
817+ name: "nil_memories",
818+ memories: nil,
819+ expectNil: true,
820+ },
821+ {
822+ name: "empty_memories",
823+ memories: []*store.Memory{},
824+ expectNil: true,
825+ },
826+ {
827+ name: "only_system_messages",
828+ memories: []*store.Memory{
829+ {Role: store.MemoryRoleSystem, Source: store.MemorySourceSystem, Content: "System"},
830+ {Role: store.MemoryRoleAssistant, Source: store.MemorySourceLLM, Content: "Response"},
831+ },
832+ expectNil: true,
833+ },
834+ {
835+ name: "direct_message_priority",
836+ memories: []*store.Memory{
837+ {Role: store.MemoryRoleUser, Source: store.MemorySourceDirect, Content: "Direct", SenderID: "cmd"},
838+ {Role: store.MemoryRoleUser, Source: store.MemorySourceBroadcast, Content: "Broadcast", SenderID: ""},
839+ },
840+ expectedSource: store.MemorySourceDirect,
841+ expectedSender: "cmd",
842+ },
843+ {
844+ name: "commander_broadcast_when_no_direct",
845+ memories: []*store.Memory{
846+ {Role: store.MemoryRoleUser, Source: store.MemorySourceBroadcast, Content: "Commander broadcast", SenderID: ""},
847+ {Role: store.MemoryRoleUser, Source: store.MemorySourceBroadcast, Content: "Swarm broadcast", SenderID: "mysis-1"},
848+ },
849+ expectedSource: store.MemorySourceBroadcast,
850+ expectedSender: "",
851+ },
852+ {
853+ name: "swarm_broadcast_when_no_commander",
854+ memories: []*store.Memory{
855+ {Role: store.MemoryRoleUser, Source: store.MemorySourceBroadcast, Content: "Swarm broadcast 1", SenderID: "mysis-1"},
856+ {Role: store.MemoryRoleUser, Source: store.MemorySourceBroadcast, Content: "Swarm broadcast 2", SenderID: "mysis-2"},
857+ },
858+ expectedSource: store.MemorySourceBroadcast,
859+ expectedSender: "mysis-1",
860+ },
861+ }
862+
863+ for _, tt := range tests {
864+ t.Run(tt.name, func(t *testing.T) {
865+ result := mysis.selectPromptSource(tt.memories)
866+
867+ if tt.expectNil {
868+ if result != nil {
869+ t.Errorf("expected nil, got %+v", result)
870+ }
871+ return
872+ }
873+
874+ if result == nil {
875+ t.Fatal("expected non-nil result, got nil")
876+ }
877+
878+ if result.Source != tt.expectedSource {
879+ t.Errorf("expected source=%s, got %s", tt.expectedSource, result.Source)
880+ }
881+
882+ if result.SenderID != tt.expectedSender {
883+ t.Errorf("expected sender_id=%s, got %s", tt.expectedSender, result.SenderID)
884+ }
885+ })
886+ }
887+}
888+
889+func TestExtractLatestToolLoopHelper(t *testing.T) {
890+ s, bus, cleanup := setupMysisTest(t)
891+ defer cleanup()
892+
893+ stored, err := s.CreateMysis("helper-test", "mock", "test-model", 0.7)
894+ if err != nil {
895+ t.Fatalf("CreateMysis() error: %v", err)
896+ }
897+
898+ mock := provider.NewMock("mock", "response")
899+ mysis := NewMysis(stored.ID, stored.Name, stored.CreatedAt, mock, s, bus)
900+
901+ tests := []struct {
902+ name string
903+ memories []*store.Memory
904+ expectedCount int
905+ expectNil bool
906+ }{
907+ {
908+ name: "nil_memories",
909+ memories: nil,
910+ expectNil: true,
911+ },
912+ {
913+ name: "empty_memories",
914+ memories: []*store.Memory{},
915+ expectNil: true,
916+ },
917+ {
918+ name: "no_tool_calls",
919+ memories: []*store.Memory{
920+ {Role: store.MemoryRoleSystem, Content: "System"},
921+ {Role: store.MemoryRoleUser, Content: "User message"},
922+ {Role: store.MemoryRoleAssistant, Content: "Text response"},
923+ },
924+ expectNil: true,
925+ },
926+ {
927+ name: "single_tool_call_with_results",
928+ memories: []*store.Memory{
929+ {Role: store.MemoryRoleSystem, Content: "System"},
930+ {Role: store.MemoryRoleUser, Content: "User"},
931+ {Role: store.MemoryRoleAssistant, Content: "[TOOL_CALLS]call_1:get_status:{}"},
932+ {Role: store.MemoryRoleTool, Content: "call_1:status result"},
933+ },
934+ expectedCount: 2, // 1 tool call + 1 result
935+ },
936+ {
937+ name: "tool_call_with_no_results_yet",
938+ memories: []*store.Memory{
939+ {Role: store.MemoryRoleSystem, Content: "System"},
940+ {Role: store.MemoryRoleUser, Content: "User"},
941+ {Role: store.MemoryRoleAssistant, Content: "[TOOL_CALLS]call_1:get_status:{}"},
942+ },
943+ expectedCount: 1, // Just the tool call
944+ },
945+ {
946+ name: "multiple_loops_returns_most_recent",
947+ memories: []*store.Memory{
948+ {Role: store.MemoryRoleSystem, Content: "System"},
949+ {Role: store.MemoryRoleAssistant, Content: "[TOOL_CALLS]call_old:get_status:{}"},
950+ {Role: store.MemoryRoleTool, Content: "call_old:old result"},
951+ {Role: store.MemoryRoleAssistant, Content: "[TOOL_CALLS]call_new:get_poi:{}"},
952+ {Role: store.MemoryRoleTool, Content: "call_new:new result"},
953+ },
954+ expectedCount: 2, // Most recent loop only
955+ },
956+ {
957+ name: "tool_call_with_multiple_results",
958+ memories: []*store.Memory{
959+ {Role: store.MemoryRoleAssistant, Content: "[TOOL_CALLS]call_1:get_status:{}|call_2:get_system:{}"},
960+ {Role: store.MemoryRoleTool, Content: "call_1:result 1"},
961+ {Role: store.MemoryRoleTool, Content: "call_2:result 2"},
962+ },
963+ expectedCount: 3, // 1 tool call message + 2 results
964+ },
965+ }
966+
967+ for _, tt := range tests {
968+ t.Run(tt.name, func(t *testing.T) {
969+ result := mysis.extractLatestToolLoop(tt.memories)
970+
971+ if tt.expectNil {
972+ if result != nil {
973+ t.Errorf("expected nil, got %d memories", len(result))
974+ }
975+ return
976+ }
977+
978+ if len(result) != tt.expectedCount {
979+ t.Errorf("expected %d memories, got %d", tt.expectedCount, len(result))
980+ for i, m := range result {
981+ t.Logf(" result[%d]: role=%s content=%.50s", i, m.Role, m.Content)
982+ }
983+ }
984+
985+ // Verify first is tool call
986+ if len(result) > 0 {
987+ if result[0].Role != store.MemoryRoleAssistant {
988+ t.Errorf("first memory should be assistant, got %s", result[0].Role)
989+ }
990+ if !strings.HasPrefix(result[0].Content, "[TOOL_CALLS]") {
991+ t.Errorf("first memory should have tool calls prefix")
992+ }
993+ }
994+
995+ // Verify rest are tool results
996+ for i := 1; i < len(result); i++ {
997+ if result[i].Role != store.MemoryRoleTool {
998+ t.Errorf("memory[%d] should be tool result, got %s", i, result[i].Role)
999+ }
1000+ }
1001+ })
1002+ }
1003+}
1004+
7971005 func TestMysisContextCompactionNonSnapshot(t *testing.T) {
7981006 s, bus, cleanup := setupMysisTest(t)
7991007 defer cleanup()