@@ -379,3 +379,244 @@ func TestContextCompressionPreservesToolCallPairs(t *testing.T) {
379379 }
380380 }
381381 }
382+
383+// TestLoopContextSlice tests the new loop-based context composition.
384+// According to the loop context composition design, getContextMemories should return:
385+// - System prompt
386+// - Selected prompt source (commander direct → last commander broadcast → last swarm broadcast → nudge)
387+// - ONLY the most recent tool-call message and its tool results
388+//
389+// This test creates multiple tool loops and verifies that older loops are excluded.
390+func TestLoopContextSlice(t *testing.T) {
391+ s, bus, cleanup := setupMysisTest(t)
392+ defer cleanup()
393+
394+ stored, err := s.CreateMysis("loop-slice-test", "mock", "test-model", 0.7)
395+ if err != nil {
396+ t.Fatalf("CreateMysis() error: %v", err)
397+ }
398+
399+ // Step 1: Add system prompt
400+ err = s.AddMemory(stored.ID, store.MemoryRoleSystem, store.MemorySourceSystem,
401+ "You are a test mysis", "", "")
402+ if err != nil {
403+ t.Fatalf("AddMemory system: %v", err)
404+ }
405+
406+ // Step 2: Add commander direct message (prompt source)
407+ err = s.AddMemory(stored.ID, store.MemoryRoleUser, store.MemorySourceDirect,
408+ "Mine some ore", "", "commander-id")
409+ if err != nil {
410+ t.Fatalf("AddMemory commander direct: %v", err)
411+ }
412+
413+ // Step 3: Create FIRST tool loop (OLD - should be excluded)
414+ // Assistant message with tool call
415+ firstLoopToolCall := constants.ToolCallStoragePrefix +
416+ "call_loop1_1:get_status:{}" + constants.ToolCallStorageRecordDelimiter +
417+ "call_loop1_2:get_system:{}"
418+ err = s.AddMemory(stored.ID, store.MemoryRoleAssistant, store.MemorySourceLLM,
419+ firstLoopToolCall, "", "")
420+ if err != nil {
421+ t.Fatalf("AddMemory first loop tool call: %v", err)
422+ }
423+
424+ // Tool results for first loop
425+ err = s.AddMemory(stored.ID, store.MemoryRoleTool, store.MemorySourceTool,
426+ "call_loop1_1"+constants.ToolCallStorageFieldDelimiter+"status result 1", "", "")
427+ if err != nil {
428+ t.Fatalf("AddMemory first loop result 1: %v", err)
429+ }
430+ err = s.AddMemory(stored.ID, store.MemoryRoleTool, store.MemorySourceTool,
431+ "call_loop1_2"+constants.ToolCallStorageFieldDelimiter+"system result 1", "", "")
432+ if err != nil {
433+ t.Fatalf("AddMemory first loop result 2: %v", err)
434+ }
435+
436+ // Step 4: Create SECOND tool loop (OLD - should be excluded)
437+ secondLoopToolCall := constants.ToolCallStoragePrefix +
438+ "call_loop2_1:get_poi:{}" + constants.ToolCallStorageRecordDelimiter +
439+ "call_loop2_2:mine:{}"
440+ err = s.AddMemory(stored.ID, store.MemoryRoleAssistant, store.MemorySourceLLM,
441+ secondLoopToolCall, "", "")
442+ if err != nil {
443+ t.Fatalf("AddMemory second loop tool call: %v", err)
444+ }
445+
446+ err = s.AddMemory(stored.ID, store.MemoryRoleTool, store.MemorySourceTool,
447+ "call_loop2_1"+constants.ToolCallStorageFieldDelimiter+"poi result 2", "", "")
448+ if err != nil {
449+ t.Fatalf("AddMemory second loop result 1: %v", err)
450+ }
451+ err = s.AddMemory(stored.ID, store.MemoryRoleTool, store.MemorySourceTool,
452+ "call_loop2_2"+constants.ToolCallStorageFieldDelimiter+"mine result 2", "", "")
453+ if err != nil {
454+ t.Fatalf("AddMemory second loop result 2: %v", err)
455+ }
456+
457+ // Step 5: Create THIRD tool loop (CURRENT - should be included)
458+ thirdLoopToolCall := constants.ToolCallStoragePrefix +
459+ "call_loop3_1:get_notifications:{}" + constants.ToolCallStorageRecordDelimiter +
460+ "call_loop3_2:get_cargo:{}"
461+ err = s.AddMemory(stored.ID, store.MemoryRoleAssistant, store.MemorySourceLLM,
462+ thirdLoopToolCall, "", "")
463+ if err != nil {
464+ t.Fatalf("AddMemory third loop tool call: %v", err)
465+ }
466+
467+ err = s.AddMemory(stored.ID, store.MemoryRoleTool, store.MemorySourceTool,
468+ "call_loop3_1"+constants.ToolCallStorageFieldDelimiter+"notifications result 3", "", "")
469+ if err != nil {
470+ t.Fatalf("AddMemory third loop result 1: %v", err)
471+ }
472+ err = s.AddMemory(stored.ID, store.MemoryRoleTool, store.MemorySourceTool,
473+ "call_loop3_2"+constants.ToolCallStorageFieldDelimiter+"cargo result 3", "", "")
474+ if err != nil {
475+ t.Fatalf("AddMemory third loop result 2: %v", err)
476+ }
477+
478+ // Step 6: Get context memories
479+ mysis := &Mysis{
480+ id: stored.ID,
481+ name: stored.Name,
482+ store: s,
483+ bus: bus,
484+ }
485+
486+ memories, err := mysis.getContextMemories()
487+ if err != nil {
488+ t.Fatalf("getContextMemories() error: %v", err)
489+ }
490+
491+ // Step 7: Assertions
492+ // Expected: system prompt + commander direct + ONLY third loop (1 assistant + 2 tool results)
493+ // Total: 5 memories
494+ expectedCount := 5
495+ if len(memories) != expectedCount {
496+ t.Errorf("Expected %d memories in context, got %d", expectedCount, len(memories))
497+ t.Logf("This test SHOULD fail initially - getContextMemories doesn't implement loop slicing yet")
498+ for i, m := range memories {
499+ contentPreview := m.Content
500+ if len(contentPreview) > 50 {
501+ contentPreview = contentPreview[:50] + "..."
502+ }
503+ t.Logf(" Memory[%d]: role=%s source=%s content=%s", i, m.Role, m.Source, contentPreview)
504+ }
505+ }
506+
507+ // ASSERTION 1: System prompt should be present
508+ if memories[0].Role != store.MemoryRoleSystem {
509+ t.Errorf("Expected first memory to be system prompt, got role=%s", memories[0].Role)
510+ }
511+
512+ // ASSERTION 2: Commander direct prompt should be present
513+ if memories[1].Role != store.MemoryRoleUser || memories[1].Source != store.MemorySourceDirect {
514+ t.Errorf("Expected second memory to be commander direct, got role=%s source=%s",
515+ memories[1].Role, memories[1].Source)
516+ }
517+
518+ // ASSERTION 3: Only third loop tool calls should be present
519+ foundLoop1Calls := false
520+ foundLoop2Calls := false
521+ foundLoop3Calls := false
522+
523+ for _, mem := range memories {
524+ if mem.Role == store.MemoryRoleAssistant && strings.Contains(mem.Content, constants.ToolCallStoragePrefix) {
525+ if strings.Contains(mem.Content, "call_loop1_1") || strings.Contains(mem.Content, "call_loop1_2") {
526+ foundLoop1Calls = true
527+ }
528+ if strings.Contains(mem.Content, "call_loop2_1") || strings.Contains(mem.Content, "call_loop2_2") {
529+ foundLoop2Calls = true
530+ }
531+ if strings.Contains(mem.Content, "call_loop3_1") || strings.Contains(mem.Content, "call_loop3_2") {
532+ foundLoop3Calls = true
533+ }
534+ }
535+ }
536+
537+ if foundLoop1Calls {
538+ t.Errorf("First tool loop calls should be excluded from context (too old)")
539+ }
540+ if foundLoop2Calls {
541+ t.Errorf("Second tool loop calls should be excluded from context (too old)")
542+ }
543+ if !foundLoop3Calls {
544+ t.Errorf("Third tool loop calls should be included in context (most recent)")
545+ }
546+
547+ // ASSERTION 4: Only third loop tool results should be present
548+ foundLoop1Results := false
549+ foundLoop2Results := false
550+ foundLoop3Results := false
551+
552+ for _, mem := range memories {
553+ if mem.Role == store.MemoryRoleTool {
554+ if strings.Contains(mem.Content, "call_loop1_1") || strings.Contains(mem.Content, "call_loop1_2") {
555+ foundLoop1Results = true
556+ }
557+ if strings.Contains(mem.Content, "call_loop2_1") || strings.Contains(mem.Content, "call_loop2_2") {
558+ foundLoop2Results = true
559+ }
560+ if strings.Contains(mem.Content, "call_loop3_1") || strings.Contains(mem.Content, "call_loop3_2") {
561+ foundLoop3Results = true
562+ }
563+ }
564+ }
565+
566+ if foundLoop1Results {
567+ t.Errorf("First tool loop results should be excluded from context")
568+ }
569+ if foundLoop2Results {
570+ t.Errorf("Second tool loop results should be excluded from context")
571+ }
572+ if !foundLoop3Results {
573+ t.Errorf("Third tool loop results should be included in context")
574+ }
575+
576+ // ASSERTION 5: Verify no orphaned tool results (all results have matching calls)
577+ validToolCalls := mysis.collectValidToolCallIDs(memories)
578+ for _, mem := range memories {
579+ if mem.Role == store.MemoryRoleTool {
580+ // Extract tool call ID from result
581+ idx := len(mem.Content)
582+ for i, ch := range mem.Content {
583+ if ch == ':' {
584+ idx = i
585+ break
586+ }
587+ }
588+ if idx > 0 && idx < len(mem.Content) {
589+ toolCallID := mem.Content[:idx]
590+ if !validToolCalls[toolCallID] {
591+ t.Errorf("Found orphaned tool result for call_id=%s (no matching tool call)", toolCallID)
592+ }
593+ }
594+ }
595+ }
596+
597+ // ASSERTION 6: Verify all expected results from loop 3 are present
598+ expectedResults := map[string]bool{
599+ "call_loop3_1": false,
600+ "call_loop3_2": false,
601+ }
602+ for _, mem := range memories {
603+ if mem.Role == store.MemoryRoleTool {
604+ parts := strings.Split(mem.Content, constants.ToolCallStorageFieldDelimiter)
605+ if len(parts) > 0 {
606+ callID := parts[0]
607+ if _, exists := expectedResults[callID]; exists {
608+ expectedResults[callID] = true
609+ }
610+ }
611+ }
612+ }
613+ for callID, found := range expectedResults {
614+ if !found {
615+ t.Errorf("Expected tool result for %s not found in context", callID)
616+ }
617+ }
618+
619+ t.Logf("Total memories in full history: 11 (system + prompt + 3 loops)")
620+ t.Logf("Total memories in context: %d", len(memories))
621+ t.Logf("Expected context: 5 (system + prompt + last loop)")
622+}