selfware 0.6.0

Your personal AI workshop — software you own, software that lasts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
use super::*;
use crate::api::types::{ToolCall, ToolFunction};
use crate::config::{Config, ExecutionMode};
use crate::errors::AgentError;
use crate::testing::mock_api::{MockLlmServer, MockToolCall};
use crate::tool_parser::parse_tool_calls;
use loop_control::{AgentLoop, AgentState};

// =========================================================================
// Test 1: Agent State Transitions
// =========================================================================

#[test]
fn test_agent_state_transitions_idle_to_planning() {
    // AgentLoop starts in Planning state (not Idle, as there's no Idle state)
    let mut loop_ctrl = AgentLoop::new(100);

    // First state should be Planning
    let state = loop_ctrl.next_state();
    assert!(matches!(state, Some(AgentState::Planning)));

    // Transition to Executing
    loop_ctrl.set_state(AgentState::Executing { step: 0 });
    let state = loop_ctrl.next_state();
    assert!(matches!(state, Some(AgentState::Executing { step: 0 })));
}

#[test]
fn test_agent_state_transitions_planning_to_executing() {
    let mut loop_ctrl = AgentLoop::new(100);

    // Start in Planning
    let _ = loop_ctrl.next_state();
    assert!(matches!(loop_ctrl.next_state(), Some(AgentState::Planning)));

    // Transition to Executing with step 0
    loop_ctrl.set_state(AgentState::Executing { step: 0 });
    let state = loop_ctrl.next_state();
    match state {
        Some(AgentState::Executing { step }) => assert_eq!(step, 0),
        _ => panic!("Expected Executing state with step 0"),
    }
}

#[test]
fn test_agent_state_transitions_executing_to_completed() {
    let mut loop_ctrl = AgentLoop::new(100);

    // Start execution
    loop_ctrl.set_state(AgentState::Executing { step: 0 });
    let _ = loop_ctrl.next_state();

    // Simulate task completion
    loop_ctrl.set_state(AgentState::Completed);
    let state = loop_ctrl.next_state();
    assert!(matches!(state, Some(AgentState::Completed)));
}

#[test]
fn test_agent_state_transitions_executing_to_error_recovery() {
    let mut loop_ctrl = AgentLoop::new(100);

    // Start execution
    loop_ctrl.set_state(AgentState::Executing { step: 0 });
    let _ = loop_ctrl.next_state();

    // Simulate error
    loop_ctrl.set_state(AgentState::ErrorRecovery {
        error: "Tool execution failed".to_string(),
    });
    let state = loop_ctrl.next_state();
    match state {
        Some(AgentState::ErrorRecovery { error }) => {
            assert_eq!(error, "Tool execution failed");
        }
        _ => panic!("Expected ErrorRecovery state"),
    }
}

#[test]
fn test_agent_state_full_lifecycle() {
    let mut loop_ctrl = AgentLoop::new(100);

    // Planning -> Executing -> Error -> Recovery -> Executing -> Completed
    assert!(matches!(loop_ctrl.next_state(), Some(AgentState::Planning)));

    loop_ctrl.set_state(AgentState::Executing { step: 0 });
    assert!(matches!(
        loop_ctrl.next_state(),
        Some(AgentState::Executing { .. })
    ));

    loop_ctrl.set_state(AgentState::ErrorRecovery {
        error: "test".to_string(),
    });
    assert!(matches!(
        loop_ctrl.next_state(),
        Some(AgentState::ErrorRecovery { .. })
    ));

    loop_ctrl.set_state(AgentState::Executing { step: 1 });
    assert!(matches!(
        loop_ctrl.next_state(),
        Some(AgentState::Executing { step: 1 })
    ));

    loop_ctrl.set_state(AgentState::Completed);
    assert!(matches!(
        loop_ctrl.next_state(),
        Some(AgentState::Completed)
    ));
}

// =========================================================================
// Test 2: Tool Call Handling with Mock Data
// =========================================================================

fn create_mock_tool_call(name: &str, args: &str) -> ToolCall {
    ToolCall {
        id: format!("call_{}", uuid::Uuid::new_v4()),
        call_type: "function".to_string(),
        function: ToolFunction {
            name: name.to_string(),
            arguments: args.to_string(),
        },
    }
}

fn mock_agent_config(endpoint: String, streaming: bool) -> Config {
    Config {
        endpoint,
        model: "mock-model".to_string(),
        // Set context_length high enough that max_context_tokens doesn't become 0
        // after subtracting max_tokens and safety margin
        context_length: 500_000,
        max_tokens: 8192,
        agent: crate::config::AgentConfig {
            max_iterations: 8,
            step_timeout_secs: 30,
            streaming,
            native_function_calling: false,
            min_completion_steps: 0,
            require_verification_before_completion: false,
            ..Default::default()
        },
        // Use permissive safety config to avoid path-validation issues on Windows
        // where backslash separators and UNC prefix paths can confuse glob matching.
        safety: crate::config::SafetyConfig {
            allowed_paths: vec!["./**".to_string(), "/**".to_string()],
            ..Default::default()
        },
        execution_mode: crate::config::ExecutionMode::Yolo,
        ..Default::default()
    }
}

#[tokio::test]
#[cfg_attr(
    target_os = "windows",
    ignore = "mock TCP server unreliable under heavy parallelism on Windows CI"
)]
async fn test_agent_run_task_e2e_tool_workflow_with_mock_api() {
    let _g = crate::test_support::ExecGuard::hold();
    let server = MockLlmServer::builder()
        .with_response(
            r#"<tool>
<name>file_read</name>
<arguments>{"path":"./Cargo.toml"}</arguments>
</tool>"#,
        )
        .with_response("Task complete: read finished.")
        .build()
        .await;

    let config = mock_agent_config(format!("{}/v1", server.url()), false);
    let mut agent = Agent::new(config).await.unwrap();

    let result = agent.run_task("Read Cargo.toml and finish").await;
    assert!(
        result.is_ok(),
        "run_task should succeed with mock API: {:?}",
        result.err()
    );
    assert!(
        agent
            .messages
            .iter()
            .any(|m| m.content.contains("<tool_result>")),
        "agent should have executed at least one tool call"
    );
    assert!(
        agent
            .file_tracker
            .context_files
            .iter()
            .any(|p| p.ends_with("Cargo.toml")),
        "file_read should add Cargo.toml to context tracking"
    );
    assert!(agent.last_assistant_response.contains("Task complete"));

    server.stop().await;
}

#[tokio::test]
#[ignore = "mock server does not support SSE streaming; test needs updated mock server or a real streaming endpoint"]
#[cfg_attr(
    target_os = "windows",
    ignore = "mock TCP server unreliable under heavy parallelism on Windows CI"
)]
async fn test_agent_run_task_streaming_fallback_to_non_streaming() {
    let server = MockLlmServer::builder()
        .with_error(503, r#"{"error":"temporary stream failure"}"#)
        .with_tool_calls(vec![MockToolCall {
            id: "call_1".to_string(),
            name: "file_read".to_string(),
            arguments: r#"{"path":"Cargo.toml"}"#.to_string(),
        }])
        .with_response("Fallback completed successfully.")
        .build()
        .await;

    let config = mock_agent_config(format!("{}/v1", server.url()), true);
    let mut agent = Agent::new(config).await.unwrap();

    let result = agent.run_task("Respond with a short completion").await;
    assert!(
        result.is_ok(),
        "run_task should recover by falling back to non-streaming chat: {:?}",
        result.err()
    );
    assert!(agent.last_assistant_response.contains("Fallback completed"));

    server.stop().await;
}

#[tokio::test]
#[cfg_attr(
    target_os = "windows",
    ignore = "mock TCP server unreliable under heavy parallelism on Windows CI"
)]
async fn test_agent_run_task_repeated_invalid_tool_calls_are_suppressed() {
    let server = MockLlmServer::builder()
        .with_response(
            r#"<tool>
<name>shell_exec</name>
<arguments>{}</arguments>
</tool>"#,
        )
        .with_response(
            r#"<tool>
<name>shell_exec</name>
<arguments>{}</arguments>
</tool>"#,
        )
        .with_response("Recovered and completed without repeating the bad tool call.")
        .build()
        .await;

    let config = mock_agent_config(format!("{}/v1", server.url()), false);
    let mut agent = Agent::new(config).await.unwrap();

    let result = agent.run_task("Run a shell command correctly").await;
    assert!(
        result.is_ok(),
        "run_task should recover after repeated invalid tool calls: {:?}",
        result.err()
    );
    assert!(agent
        .last_assistant_response
        .contains("Recovered and completed"));
    assert!(
        agent.messages.iter().any(|message| {
            message.role == "user"
                && message.content.text().contains("RETRY SUPPRESSED")
                && message.content.text().contains("`command`")
        }),
        "agent should suppress the repeated invalid tool call"
    );

    server.stop().await;
}

#[test]
fn test_tool_call_parsing_xml_format() {
    let content = r#"
        Let me read that file for you.

        <tool>
        <name>file_read</name>
        <arguments>{"path": "./src/main.rs"}</arguments>
        </tool>
        "#;

    let result = parse_tool_calls(content);
    assert_eq!(result.tool_calls.len(), 1);
    assert_eq!(result.tool_calls[0].tool_name, "file_read");

    let args = &result.tool_calls[0].arguments;
    assert_eq!(args["path"], "./src/main.rs");
}

#[test]
fn test_tool_call_parsing_multiple_tools() {
    let content = r#"
        I'll check the git status and read a file.

        <tool>
        <name>git_status</name>
        <arguments>{}</arguments>
        </tool>

        <tool>
        <name>file_read</name>
        <arguments>{"path": "Cargo.toml"}</arguments>
        </tool>
        "#;

    let result = parse_tool_calls(content);
    assert_eq!(result.tool_calls.len(), 2);
    assert_eq!(result.tool_calls[0].tool_name, "git_status");
    assert_eq!(result.tool_calls[1].tool_name, "file_read");
}

#[test]
fn test_tool_call_with_complex_arguments() {
    let content = r#"
        <tool>
        <name>file_edit</name>
        <arguments>{
            "path": "./src/lib.rs",
            "old_str": "fn old_function() {\n    println!(\"old\");\n}",
            "new_str": "fn new_function() {\n    println!(\"new\");\n}"
        }</arguments>
        </tool>
        "#;

    let result = parse_tool_calls(content);
    assert_eq!(result.tool_calls.len(), 1);
    assert_eq!(result.tool_calls[0].tool_name, "file_edit");

    let args = &result.tool_calls[0].arguments;
    assert!(args["old_str"].as_str().unwrap().contains("old_function"));
    assert!(args["new_str"].as_str().unwrap().contains("new_function"));
}

#[test]
fn test_tool_call_no_tools_in_content() {
    let content = "This is just a regular response without any tool calls.";

    let result = parse_tool_calls(content);
    assert!(result.tool_calls.is_empty());
    assert!(!result.text_content.is_empty());
}

#[test]
fn test_mock_tool_call_creation() {
    let call = create_mock_tool_call("shell_exec", r#"{"command": "ls -la"}"#);
    assert_eq!(call.function.name, "shell_exec");
    assert!(call.function.arguments.contains("ls -la"));
    assert_eq!(call.call_type, "function");
    assert!(call.id.starts_with("call_"));
}

// =========================================================================
// Test 3: Error Recovery Scenarios
// =========================================================================

#[test]
fn test_error_recovery_state_preserves_error_message() {
    let mut loop_ctrl = AgentLoop::new(100);

    let error_message = "Connection timeout while calling external API";
    loop_ctrl.set_state(AgentState::ErrorRecovery {
        error: error_message.to_string(),
    });

    let state = loop_ctrl.next_state();
    match state {
        Some(AgentState::ErrorRecovery { error }) => {
            assert_eq!(error, error_message);
        }
        _ => panic!("Expected ErrorRecovery state"),
    }
}

#[test]
fn test_error_recovery_transitions_back_to_executing() {
    let mut loop_ctrl = AgentLoop::new(100);

    // Enter error recovery
    loop_ctrl.set_state(AgentState::ErrorRecovery {
        error: "some error".to_string(),
    });
    let _ = loop_ctrl.next_state();

    // Transition back to executing after recovery
    let current_step = loop_ctrl.current_step();
    loop_ctrl.set_state(AgentState::Executing { step: current_step });
    let state = loop_ctrl.next_state();
    assert!(matches!(state, Some(AgentState::Executing { .. })));
}

#[test]
fn test_error_recovery_can_transition_to_failed() {
    let mut loop_ctrl = AgentLoop::new(100);

    // Enter error recovery
    loop_ctrl.set_state(AgentState::ErrorRecovery {
        error: "unrecoverable error".to_string(),
    });
    let _ = loop_ctrl.next_state();

    // If recovery fails, transition to Failed
    loop_ctrl.set_state(AgentState::Failed {
        reason: "Max retries exceeded".to_string(),
    });
    let state = loop_ctrl.next_state();
    match state {
        Some(AgentState::Failed { reason }) => {
            assert_eq!(reason, "Max retries exceeded");
        }
        _ => panic!("Expected Failed state"),
    }
}

#[test]
fn test_confirmation_error_detection() {
    // Case 1: Wrapped in SelfwareError::Agent
    let error = crate::errors::SelfwareError::Agent(AgentError::ConfirmationRequired {
        tool_name: "shell_exec".to_string(),
    });
    let anyhow_error: anyhow::Error = error.into();
    assert!(is_confirmation_error(&anyhow_error));

    // Case 2: AgentError returned directly into anyhow (as in execution.rs non-interactive path)
    let direct_error: anyhow::Error = AgentError::ConfirmationRequired {
        tool_name: "shell_exec".to_string(),
    }
    .into();
    assert!(is_confirmation_error(&direct_error));
}

#[test]
fn test_non_confirmation_error_detection() {
    let error = anyhow::anyhow!("Some other error");
    assert!(!is_confirmation_error(&error));
}

// =========================================================================
// Test 4: Context Compression Triggers
// =========================================================================

#[test]
fn test_context_compressor_threshold_calculation() {
    let compressor = ContextCompressor::new(100000);
    // Threshold is 85% of budget
    assert!(!compressor.should_compress(&[]));

    // Create messages that exceed threshold
    let mut large_messages = vec![Message::system("System prompt")];
    for _ in 0..100 {
        large_messages.push(Message::user("x".repeat(1000)));
    }

    // With 100 messages of ~1000 chars each, this should trigger compression
    let compressor_small = ContextCompressor::new(10000);
    assert!(compressor_small.should_compress(&large_messages));
}

#[test]
fn test_context_compressor_estimate_tokens() {
    let compressor = ContextCompressor::new(100000);

    let messages = vec![
        Message::system("You are a helpful assistant"),
        Message::user("Hello, how are you?"),
        Message::assistant("I'm doing well, thank you!"),
    ];

    let estimate = compressor.estimate_tokens(&messages);
    // Should have reasonable estimate (overhead + content tokens)
    assert!(estimate > 10); // 3 messages with short content
    assert!(estimate < 500); // Shouldn't be too high for short messages
}

#[test]
fn test_context_compressor_code_content_factor() {
    let compressor = ContextCompressor::new(100000);

    // Code content (with braces) uses factor 3
    let code_msg = vec![Message::user("fn main() { println!(\"hello\"); }")];

    // Plain text uses factor 4
    let text_msg = vec![Message::user("This is plain text content")];

    let code_estimate = compressor.estimate_tokens(&code_msg);
    let text_estimate = compressor.estimate_tokens(&text_msg);

    // Both should produce positive estimates
    assert!(code_estimate > 0);
    assert!(text_estimate > 0);
}

#[test]
fn test_hard_compress_preserves_structure() {
    let compressor = ContextCompressor::new(100000);

    let messages = vec![
        Message::system("system prompt"),
        Message::user("question 1"),
        Message::assistant("answer 1"),
        Message::user("question 2"),
        Message::assistant("answer 2"),
        Message::user("recent question"),
    ];

    let compressed = compressor.hard_compress(&messages);

    // Should preserve system message
    assert_eq!(compressed[0].role, "system");

    // Should end with user message
    let last = compressed.last().unwrap();
    assert_eq!(last.role, "user");
}

// =========================================================================
// Test 5: Execution Mode and Tool Confirmation
// =========================================================================

#[test]
fn test_execution_mode_normal_needs_confirmation() {
    let config = Config {
        execution_mode: ExecutionMode::Normal,
        ..Default::default()
    };

    // In normal mode, most tools need confirmation
    // Safe tools (read-only) don't need confirmation
    let safe_tools = [
        "file_read",
        "directory_tree",
        "glob_find",
        "grep_search",
        "symbol_search",
        "tool_search",
        "git_status",
        "git_diff",
    ];

    for tool in &safe_tools {
        // Safe tools shouldn't need confirmation even in normal mode
        assert!(
            !needs_confirmation_for_tool(&config, tool),
            "{} should not need confirmation",
            tool
        );
    }

    // Dangerous tools need confirmation in normal mode
    let dangerous_tools = ["shell_exec", "file_write", "git_commit"];
    for tool in &dangerous_tools {
        assert!(
            needs_confirmation_for_tool(&config, tool),
            "{} should need confirmation",
            tool
        );
    }

    // tool_search is read-only and should not need confirmation
    assert!(
        !needs_confirmation_for_tool(&config, "tool_search"),
        "tool_search should not need confirmation"
    );
}

#[test]
fn test_execution_mode_yolo_no_confirmation() {
    let config = Config {
        execution_mode: ExecutionMode::Yolo,
        ..Default::default()
    };

    // In YOLO mode, nothing needs confirmation
    let all_tools = [
        "file_read",
        "file_write",
        "shell_exec",
        "git_commit",
        "cargo_test",
    ];

    for tool in &all_tools {
        assert!(
            !needs_confirmation_for_tool(&config, tool),
            "{} should not need confirmation in YOLO mode",
            tool
        );
    }
}

#[test]
fn test_execution_mode_auto_edit_file_ops() {
    let config = Config {
        execution_mode: ExecutionMode::AutoEdit,
        ..Default::default()
    };

    // Auto-edit mode auto-approves file operations
    assert!(!needs_confirmation_for_tool(&config, "file_write"));
    assert!(!needs_confirmation_for_tool(&config, "file_edit"));

    // But still asks for other operations
    assert!(needs_confirmation_for_tool(&config, "shell_exec"));
    assert!(needs_confirmation_for_tool(&config, "git_commit"));
}

#[test]
fn test_execution_mode_cycle() {
    let mut mode = ExecutionMode::Normal;

    // Normal -> AutoEdit
    mode = cycle_mode(mode);
    assert_eq!(mode, ExecutionMode::AutoEdit);

    // AutoEdit -> Yolo
    mode = cycle_mode(mode);
    assert_eq!(mode, ExecutionMode::Yolo);

    // Yolo -> Normal
    mode = cycle_mode(mode);
    assert_eq!(mode, ExecutionMode::Normal);
}

// Helper function to check confirmation without full Agent
fn needs_confirmation_for_tool(config: &Config, tool_name: &str) -> bool {
    let safe_tools = [
        "file_read",
        "directory_tree",
        "glob_find",
        "grep_search",
        "symbol_search",
        "tool_search",
        "git_status",
        "git_diff",
    ];

    if safe_tools.contains(&tool_name) {
        return false;
    }

    if matches!(
        config.execution_mode,
        ExecutionMode::Yolo | ExecutionMode::Daemon
    ) {
        return false;
    }

    // Check config's require_confirmation list
    if config
        .safety
        .require_confirmation
        .iter()
        .any(|t| t == tool_name)
    {
        return true;
    }

    match config.execution_mode {
        ExecutionMode::Yolo | ExecutionMode::Daemon => false,
        ExecutionMode::AutoEdit => !matches!(
            tool_name,
            "file_write" | "file_edit" | "directory_tree" | "glob_find"
        ),
        ExecutionMode::Normal => !safe_tools.contains(&tool_name),
    }
}

// Helper function to cycle execution mode
fn cycle_mode(mode: ExecutionMode) -> ExecutionMode {
    match mode {
        ExecutionMode::Normal => ExecutionMode::AutoEdit,
        ExecutionMode::AutoEdit => ExecutionMode::Yolo,
        ExecutionMode::Yolo => ExecutionMode::Normal,
        ExecutionMode::Daemon => ExecutionMode::Normal,
    }
}

// =========================================================================
// Additional Edge Case Tests
// =========================================================================

#[test]
fn test_agent_error_display() {
    let error = AgentError::ConfirmationRequired {
        tool_name: "dangerous_tool".to_string(),
    };
    let display = format!("{}", error);
    assert!(display.contains("dangerous_tool"));
    assert!(display.contains("requires confirmation"));
}

#[test]
fn test_max_iterations_triggers_failure() {
    let mut loop_ctrl = AgentLoop::new(3);

    // Planning turn does not consume an iteration slot.
    loop_ctrl.next_state(); // Planning
    loop_ctrl
        .transition_to(AgentState::Executing { step: 0 })
        .unwrap();

    // Use up all 3 execution iterations
    loop_ctrl.next_state(); // 1
    loop_ctrl.next_state(); // 2
    loop_ctrl.next_state(); // 3

    // Next should fail
    let state = loop_ctrl.next_state();
    assert!(matches!(
        state,
        Some(AgentState::Failed { reason }) if reason.contains("Max iterations")
    ));
}

#[test]
fn test_step_increment_updates_state() {
    let mut loop_ctrl = AgentLoop::new(100);

    assert_eq!(loop_ctrl.current_step(), 0);

    loop_ctrl.increment_step().unwrap();
    assert_eq!(loop_ctrl.current_step(), 1);

    // State should be updated to Executing with new step
    let state = loop_ctrl.next_state();
    match state {
        Some(AgentState::Executing { step }) => assert_eq!(step, 1),
        _ => panic!("Expected Executing state with step 1"),
    }
}

#[test]
fn test_tool_call_with_invalid_json_uses_fallback() {
    let content = r#"
        <tool>
        <name>file_read</name>
        <arguments>this is not valid json</arguments>
        </tool>
        "#;

    let result = parse_tool_calls(content);
    // Parser uses fallback - wraps invalid JSON in {"input": "..."}
    assert_eq!(result.tool_calls.len(), 1);
    assert_eq!(result.tool_calls[0].tool_name, "file_read");
    // The fallback wraps plain text in {"input": "..."}
    assert!(result.tool_calls[0].arguments.get("input").is_some());
}

#[test]
fn test_agent_state_clone() {
    let state = AgentState::Executing { step: 5 };
    let cloned = state.clone();

    match cloned {
        AgentState::Executing { step } => assert_eq!(step, 5),
        _ => panic!("Clone should preserve state type and data"),
    }
}

#[test]
fn test_agent_state_debug() {
    let state = AgentState::ErrorRecovery {
        error: "test error".to_string(),
    };
    let debug_str = format!("{:?}", state);

    assert!(debug_str.contains("ErrorRecovery"));
    assert!(debug_str.contains("test error"));
}

#[test]
fn test_infer_task_type() {
    assert_eq!(
        Agent::infer_task_type("Please review this PR"),
        "code_review"
    );
    assert_eq!(Agent::infer_task_type("Fix this bug"), "bug_fix");
    assert_eq!(Agent::infer_task_type("Write tests for module"), "testing");
}

#[test]
fn test_classify_error_type() {
    assert_eq!(Agent::classify_error_type("request timed out"), "timeout");
    assert_eq!(
        Agent::classify_error_type("permission denied"),
        "permission"
    );
    assert_eq!(
        Agent::classify_error_type("Invalid JSON in response"),
        "parsing"
    );
}

#[test]
fn test_outcome_quality_mapping() {
    assert_eq!(Agent::outcome_quality(Outcome::Success), 1.0);
    assert_eq!(Agent::outcome_quality(Outcome::Partial), 0.65);
    assert_eq!(Agent::outcome_quality(Outcome::Failure), 0.0);
    assert_eq!(Agent::outcome_quality(Outcome::Abandoned), 0.2);
}

// =========================================================================
// trim_message_history tests
// =========================================================================

/// Helper that mirrors `Agent::trim_message_history` logic so we can
/// verify the algorithm without constructing a full Agent instance.
fn trim_messages(messages: &mut Vec<Message>, max_tokens: usize) {
    let total: usize = messages
        .iter()
        .map(|m| crate::token_count::estimate_tokens_with_overhead(m.content.text(), 4))
        .sum();
    if total <= max_tokens {
        return;
    }

    let token_counts: Vec<usize> = messages
        .iter()
        .map(|m| crate::token_count::estimate_tokens_with_overhead(m.content.text(), 4))
        .collect();

    let mut remaining = total;
    let mut keep = vec![true; messages.len()];
    for (i, tokens) in token_counts.iter().enumerate() {
        if remaining <= max_tokens {
            break;
        }
        if messages[i].role != "system" {
            keep[i] = false;
            remaining -= tokens;
        }
    }

    let mut idx = 0;
    messages.retain(|_| {
        let k = keep[idx];
        idx += 1;
        k
    });
}

#[test]
fn test_trim_message_history_no_trim_needed() {
    let mut msgs = vec![
        Message::system("sys"),
        Message::user("hi"),
        Message::assistant("hello"),
    ];
    let before_len = msgs.len();
    trim_messages(&mut msgs, 100_000);
    assert_eq!(msgs.len(), before_len);
}

#[test]
fn test_trim_message_history_removes_oldest_non_system() {
    // Use long messages so the total clearly exceeds a small budget.
    let long = "x".repeat(500);
    let mut msgs = vec![
        Message::system("system prompt"),
        Message::user(&long),
        Message::assistant(&long),
        Message::user(&long),
        Message::assistant(&long),
    ];

    // Budget of 20 tokens forces almost everything to be trimmed.
    trim_messages(&mut msgs, 20);

    // System message must survive.
    assert_eq!(msgs[0].role, "system");
    // At least some non-system messages should have been removed.
    assert!(msgs.len() < 5);
}

#[test]
fn test_trim_message_history_preserves_system_only() {
    let mut msgs = vec![
        Message::system("system prompt"),
        Message::user("big message ".repeat(5000)),
    ];

    // Very tiny budget: should remove the user message but keep system
    trim_messages(&mut msgs, 30);

    assert_eq!(msgs.len(), 1);
    assert_eq!(msgs[0].role, "system");
}

// =========================================================================
// Progress emitter integration tests (#1)
// =========================================================================

#[tokio::test]
#[cfg_attr(
    target_os = "windows",
    ignore = "mock TCP server unreliable under heavy parallelism on Windows CI"
)]
async fn test_progress_emitter_receives_task_completed_event() {
    use std::sync::Arc;
    let server = MockLlmServer::builder()
        .with_response("All done.")
        .build()
        .await;

    let config = mock_agent_config(format!("{}/v1", server.url()), false);
    let recorder = Arc::new(super::progress::RecordingProgressEmitter::new());
    let mut agent = Agent::new(config)
        .await
        .unwrap()
        .with_progress_emitter(recorder.clone());

    let _ = agent.run_task("Just answer immediately").await;
    let kinds = recorder.kinds();
    assert!(
        kinds.contains(&"step_started"),
        "expected step_started in {:?}",
        kinds
    );
    assert!(
        kinds.contains(&"task_completed") || kinds.contains(&"task_failed"),
        "expected a terminal task_* event in {:?}",
        kinds
    );
    server.stop().await;
}

#[tokio::test]
#[cfg_attr(
    target_os = "windows",
    ignore = "mock TCP server unreliable under heavy parallelism on Windows CI"
)]
async fn test_progress_emitter_records_tool_call_started_and_completed() {
    use std::sync::Arc;
    let server = MockLlmServer::builder()
        .with_response(
            r#"<tool>
<name>file_read</name>
<arguments>{"path":"./Cargo.toml"}</arguments>
</tool>"#,
        )
        .with_response("Done.")
        .build()
        .await;

    let config = mock_agent_config(format!("{}/v1", server.url()), false);
    let recorder = Arc::new(super::progress::RecordingProgressEmitter::new());
    let mut agent = Agent::new(config)
        .await
        .unwrap()
        .with_progress_emitter(recorder.clone());

    let _ = agent.run_task("Read Cargo.toml and finish").await;
    let kinds = recorder.kinds();
    assert!(
        kinds.contains(&"tool_call_started"),
        "expected tool_call_started in {:?}",
        kinds
    );
    assert!(
        kinds.contains(&"tool_call_completed"),
        "expected tool_call_completed in {:?}",
        kinds
    );
    server.stop().await;
}

#[tokio::test]
async fn test_agent_new_rejects_tiny_context_budget() {
    // The output reservation is clamped to what the context window can hold
    // (Config::derive_context_budget), so Agent::new only refuses when the
    // window itself is too small to keep even the minimal conversation
    // floor: context_length=2048 leaves 2048 - 0 - 409 = 1639 < 2048.
    let config = Config {
        endpoint: "http://localhost:0/v1".to_string(),
        model: "mock-model".to_string(),
        context_length: 2048,
        max_tokens: 2048,
        ..Default::default()
    };
    let err = match Agent::new(config).await {
        Ok(_) => panic!("expected Agent::new to fail for tiny context budget"),
        Err(e) => e,
    };
    assert!(
        err.to_string().contains("max_context_tokens too small"),
        "unexpected error: {}",
        err
    );
}

// =========================================================================
// apply_recovery_action — RecoveryAction runtime application
// =========================================================================

#[tokio::test]
#[cfg_attr(
    target_os = "windows",
    ignore = "mock TCP server unreliable on Windows CI"
)]
#[cfg(feature = "resilience")]
async fn test_apply_recovery_action_fallback_switches_endpoint() {
    let server = MockLlmServer::builder().with_response("done").build().await;
    let remote_endpoint = format!("{}/v1", server.url());
    let config = Config {
        endpoint: remote_endpoint.clone(),
        model: "mock-model".to_string(),
        context_length: 500_000,
        max_tokens: 8192,
        ..Default::default()
    };
    let mut agent = Agent::new(config).await.unwrap();

    let target = "http://localhost:11434/v1".to_string();
    let action = crate::self_healing::RecoveryDirective::Action(
        crate::self_healing::RecoveryAction::Fallback {
            target: target.clone(),
        },
    );
    let result = agent.apply_recovery_action(&action).await;
    assert!(result.is_ok(), "apply_recovery_action should succeed");
    assert!(
        result.unwrap(),
        "apply_recovery_action should return Ok(true) for a different endpoint"
    );
    assert_eq!(
        agent.config.endpoint, target,
        "endpoint should have been switched to the fallback target"
    );
    server.stop().await;
}

#[tokio::test]
#[cfg_attr(
    target_os = "windows",
    ignore = "mock TCP server unreliable on Windows CI"
)]
#[cfg(feature = "resilience")]
async fn test_apply_recovery_action_fallback_same_endpoint_returns_false() {
    let server = MockLlmServer::builder().with_response("done").build().await;
    let endpoint = format!("{}/v1", server.url());
    let config = Config {
        endpoint: endpoint.clone(),
        model: "mock-model".to_string(),
        context_length: 500_000,
        max_tokens: 8192,
        ..Default::default()
    };
    let mut agent = Agent::new(config).await.unwrap();

    let action = crate::self_healing::RecoveryDirective::Action(
        crate::self_healing::RecoveryAction::Fallback {
            target: endpoint.clone(),
        },
    );
    let result = agent.apply_recovery_action(&action).await;
    assert!(result.is_ok(), "apply_recovery_action should succeed");
    assert!(
        !result.unwrap(),
        "apply_recovery_action should return Ok(false) when target equals current"
    );
    assert_eq!(
        agent.config.endpoint, endpoint,
        "endpoint should be unchanged"
    );
    server.stop().await;
}

// =========================================================================
// apply_recovery_action — CompressContext directive
// =========================================================================

#[tokio::test]
#[cfg_attr(
    target_os = "windows",
    ignore = "mock TCP server unreliable on Windows CI"
)]
#[cfg(feature = "resilience")]
async fn test_apply_recovery_action_compress_context() {
    let server = MockLlmServer::builder().with_response("done").build().await;
    let config = Config {
        endpoint: format!("{}/v1", server.url()),
        model: "mock-model".to_string(),
        context_length: 500_000,
        max_tokens: 8192,
        ..Default::default()
    };
    let mut agent = Agent::new(config).await.unwrap();

    // Populate messages so compression has something to work on.
    agent
        .messages
        .push(Message::system("system prompt sentinel"));
    agent
        .messages
        .push(Message::user("original task description here"));
    for i in 0..20 {
        agent.messages.push(Message::user(format!(
            "history message {i} with enough words to cost some tokens for the estimator"
        )));
        agent.messages.push(Message::assistant(format!(
            "reply {i} acknowledging the work is progressing"
        )));
    }
    let before_len = agent.messages.len();

    let directive = crate::self_healing::RecoveryDirective::CompressContext { target_tokens: 1 };
    let result = agent.apply_recovery_action(&directive).await;
    assert!(
        result.is_ok(),
        "CompressContext should not error: {:?}",
        result.err()
    );
    assert!(result.unwrap(), "CompressContext should return Ok(true)");
    // Compression should have reduced message count.
    assert!(
        agent.messages.len() < before_len,
        "message count should decrease after compression: before={}, after={}",
        before_len,
        agent.messages.len()
    );
    server.stop().await;
}

// =========================================================================
// apply_recovery_action — ReloadCredentials directive
// =========================================================================

#[tokio::test]
#[cfg_attr(
    target_os = "windows",
    ignore = "mock TCP server unreliable on Windows CI"
)]
#[cfg(feature = "resilience")]
async fn test_apply_recovery_action_reload_credentials_with_env() {
    let server = MockLlmServer::builder().with_response("done").build().await;
    let config = Config {
        endpoint: format!("{}/v1", server.url()),
        model: "mock-model".to_string(),
        context_length: 500_000,
        max_tokens: 8192,
        ..Default::default()
    };
    let mut agent = Agent::new(config).await.unwrap();

    // Set a temporary env var so the reload finds a key (serialized + auto-restored).
    let env = crate::test_support::EnvGuard::capture(&["SELFWARE_API_KEY"]);
    env.set("SELFWARE_API_KEY", "test-reload-credentials-directive-key");

    let directive = crate::self_healing::RecoveryDirective::ReloadCredentials;
    let result = agent.apply_recovery_action(&directive).await;
    assert!(
        result.is_ok(),
        "ReloadCredentials should not error: {:?}",
        result.err()
    );
    assert!(
        result.unwrap(),
        "ReloadCredentials should return Ok(true) when a key is found"
    );
    // The config should now have the key set.
    assert!(
        agent.config.api_key.is_some(),
        "config.api_key should be set after reload"
    );
    assert_eq!(
        agent.config.api_key.as_ref().unwrap().expose(),
        "test-reload-credentials-directive-key"
    );

    server.stop().await;
}

#[tokio::test]
#[cfg_attr(
    target_os = "windows",
    ignore = "mock TCP server unreliable on Windows CI"
)]
#[cfg(feature = "resilience")]
async fn test_apply_recovery_action_reload_credentials_no_key_returns_false() {
    let server = MockLlmServer::builder().with_response("done").build().await;
    let config = Config {
        endpoint: format!("{}/v1", server.url()),
        model: "mock-model".to_string(),
        context_length: 500_000,
        max_tokens: 8192,
        ..Default::default()
    };
    let mut agent = Agent::new(config).await.unwrap();

    // Ensure no env var is set (serialized + auto-restored). The keyring may
    // or may not have a key; if it does, the result will be Ok(true) which is
    // also valid. We just verify the call doesn't error.
    let _env = crate::test_support::EnvGuard::capture(&["SELFWARE_API_KEY"]);
    std::env::remove_var("SELFWARE_API_KEY");

    let directive = crate::self_healing::RecoveryDirective::ReloadCredentials;
    let result = agent.apply_recovery_action(&directive).await;
    assert!(
        result.is_ok(),
        "ReloadCredentials should not error: {:?}",
        result.err()
    );

    server.stop().await;
}

// =========================================================================
// Test: clear_conversation resets the model context
// =========================================================================

#[tokio::test]
async fn clear_conversation_keeps_only_system_prompt() {
    let server = MockLlmServer::builder().with_response("ok").build().await;
    let config = mock_agent_config(format!("{}/v1", server.url()), false);
    let mut agent = Agent::new(config).await.expect("agent::new");
    let before = agent.messages.len();
    agent
        .messages
        .push(Message::user("remember: my name is Bob"));
    agent.messages.push(Message::assistant("Noted."));
    agent.last_assistant_response = "Noted.".to_string();
    assert!(agent.messages.len() > before);

    agent.clear_conversation();

    assert_eq!(
        agent.messages.len(),
        1,
        "only the system prompt should remain"
    );
    assert_eq!(agent.messages[0].role, "system");
    assert!(agent.last_assistant_response.is_empty());
    server.stop().await;
}