skilllite-agent 0.1.15

SkillLite Agent: LLM-powered tool loop, extensions, chat
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
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
//! Tests for the builtin tools module.

use super::*;

/// 测试启动时禁用审计,避免 edit 操作污染真实 audit 日志。
#[ctor::ctor]
fn disable_audit_in_tests() {
    std::env::set_var("SKILLLITE_AUDIT_DISABLED", "1");
}

#[test]
fn test_search_replace_first_occurrence() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "hello world\nhello again\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "old_string": "hello world",
        "new_string": "hi world",
        "replace_all": false
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result
        .content
        .contains("Successfully replaced 1 occurrence"));
    assert!(result.content.contains("\"first_changed_line\": 1"));
    assert!(result.content.contains("\"changed\": true"));

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert_eq!(content, "hi world\nhello again\n");
}

#[test]
fn test_search_replace_requires_unique_match_by_default() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "hello world\nhello again\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "old_string": "hello",
        "new_string": "hi"
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(result.is_error);
    assert!(result
        .content
        .contains("requires a unique match by default"));
}

#[test]
fn test_search_replace_all() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "foo bar foo baz foo\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "old_string": "foo",
        "new_string": "qux",
        "replace_all": true
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result
        .content
        .contains("Successfully replaced 3 occurrence"));

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert_eq!(content, "qux bar qux baz qux\n");
}

#[test]
fn test_search_replace_old_string_not_found() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "hello world\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "old_string": "xyz",
        "new_string": "abc"
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(result.is_error);
    assert!(result.content.contains("old_string not found"));
}

#[test]
fn test_search_replace_blocks_sensitive_path() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let env_path = workspace.join(".env");
    std::fs::write(&env_path, "KEY=value\n").unwrap();

    let args = serde_json::json!({
        "path": ".env",
        "old_string": "KEY=value",
        "new_string": "KEY=modified"
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(result.is_error);
    assert!(result.content.contains("Blocked"));
}

#[test]
fn test_search_replace_normalize_whitespace_trailing() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "hello world  \nnext line\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "old_string": "hello world",
        "new_string": "hi",
        "normalize_whitespace": true
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(!result.is_error);

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert_eq!(content, "hi\nnext line\n");
}

#[test]
fn test_search_replace_normalize_whitespace_replace_all() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "foo \nbar \nbaz\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "old_string": "bar",
        "new_string": "qux",
        "replace_all": true,
        "normalize_whitespace": true
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(!result.is_error);

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert_eq!(content, "foo \nqux\nbaz\n");
}

#[test]
fn test_search_replace_normalize_whitespace_literal_replacement() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "price: 100\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "old_string": "price: 100",
        "new_string": "price: $200",
        "normalize_whitespace": true
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(!result.is_error);

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert_eq!(content, "price: $200\n");
}

#[test]
fn test_search_replace_output_directory() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let output_dir = workspace.join("output");
    std::fs::create_dir_all(&output_dir).unwrap();
    let file_path = output_dir.join("index.html");
    std::fs::write(&file_path, "<title>Old Title</title>").unwrap();

    let args = serde_json::json!({
        "path": "output/index.html",
        "old_string": "Old Title",
        "new_string": "New Title"
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(!result.is_error);

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert_eq!(content, "<title>New Title</title>");
}

#[test]
fn test_preview_edit_does_not_write_file() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "alpha beta\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "old_string": "alpha",
        "new_string": "gamma"
    });
    let result = execute_builtin_tool("preview_edit", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("Preview edit"));
    assert!(result.content.contains("\"changed\": true"));
    assert!(result.content.contains("\"diff_excerpt\""));

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert_eq!(content, "alpha beta\n");
}

// ─── P0: read_file line numbers + range ─────────────────────────────

#[test]
fn test_read_file_with_line_numbers() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "line1\nline2\nline3\n").unwrap();

    let args = serde_json::json!({ "path": "test.txt" });
    let result = execute_builtin_tool("read_file", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("1|line1"));
    assert!(result.content.contains("2|line2"));
    assert!(result.content.contains("3|line3"));
}

#[test]
fn test_read_file_with_range() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "aaa\nbbb\nccc\nddd\neee\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "start_line": 2,
        "end_line": 4
    });
    let result = execute_builtin_tool("read_file", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("2|bbb"));
    assert!(result.content.contains("3|ccc"));
    assert!(result.content.contains("4|ddd"));
    assert!(!result.content.contains("1|aaa"));
    assert!(!result.content.contains("5|eee"));
    assert!(result.content.contains("[Showing lines 2-4 of 5 total]"));
}

#[test]
fn test_read_file_range_beyond_end() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "only\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "start_line": 100
    });
    let result = execute_builtin_tool("read_file", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("File has 1 lines"));
}

// ─── P0: read_file blocks .env/.key/.git/config,其他文件过滤敏感信息 ───

#[test]
fn test_read_file_blocks_sensitive_paths() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    std::fs::write(workspace.join(".env"), "API_KEY=sk-secret\n").unwrap();
    std::fs::write(workspace.join("secret.key"), "private key").unwrap();
    std::fs::write(workspace.join("cert.pem"), "cert").unwrap();

    for path in [".env", "secret.key", "cert.pem"] {
        let args = serde_json::json!({ "path": path });
        let result = execute_builtin_tool("read_file", &args.to_string(), workspace, None);
        assert!(result.is_error);
        assert!(result.content.contains("Blocked: reading sensitive file"));
        assert!(result.content.contains(path));
    }
}

#[test]
fn test_read_file_redacts_sensitive_in_other_files() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    std::fs::write(
        workspace.join("config.json"),
        r#"{"api_key": "sk-secret123", "model": "gpt4", "password": "mypwd"}"#,
    )
    .unwrap();
    std::fs::write(
        workspace.join("README.md"),
        "Setup: set API_KEY=sk-abcdefghij1234567890 in your env\n",
    )
    .unwrap();

    let args = serde_json::json!({ "path": "config.json" });
    let result = execute_builtin_tool("read_file", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains(r#""api_key": "[REDACTED]""#));
    assert!(result.content.contains(r#""password": "[REDACTED]""#));
    assert!(result.content.contains(r#""model": "gpt4"#));
    assert!(result.content.contains("Sensitive values"));

    let args2 = serde_json::json!({ "path": "README.md" });
    let result2 = execute_builtin_tool("read_file", &args2.to_string(), workspace, None);
    assert!(!result2.is_error);
    // API_KEY=xxx 被脱敏为 API_KEY=[REDACTED],或 sk-xxx 被脱敏为 sk-[REDACTED]
    assert!(
        result2.content.contains("API_KEY=[REDACTED]") || result2.content.contains("sk-[REDACTED]"),
        "expected sensitive value redaction, got: {}",
        result2.content
    );
}

// ─── P0: insert_lines ───────────────────────────────────────────────

#[test]
fn test_insert_lines_at_beginning() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "line1\nline2\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "line": 0,
        "content": "inserted"
    });
    let result = execute_builtin_tool("insert_lines", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("Successfully inserted"));

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert_eq!(content, "inserted\nline1\nline2\n");
}

#[test]
fn test_insert_lines_in_middle() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "line1\nline2\nline3\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "line": 1,
        "content": "new_line"
    });
    let result = execute_builtin_tool("insert_lines", &args.to_string(), workspace, None);
    assert!(!result.is_error);

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert_eq!(content, "line1\nnew_line\nline2\nline3\n");
}

#[test]
fn test_insert_lines_at_end() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "line1\nline2\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "line": 2,
        "content": "last_line"
    });
    let result = execute_builtin_tool("insert_lines", &args.to_string(), workspace, None);
    assert!(!result.is_error);

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert_eq!(content, "line1\nline2\nlast_line\n");
}

#[test]
fn test_insert_lines_multiline_content() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "aaa\nbbb\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "line": 1,
        "content": "x1\nx2\nx3"
    });
    let result = execute_builtin_tool("insert_lines", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("\"lines_inserted\": 3"));

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert_eq!(content, "aaa\nx1\nx2\nx3\nbbb\n");
}

#[test]
fn test_insert_lines_beyond_end_fails() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "line1\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "line": 99,
        "content": "nope"
    });
    let result = execute_builtin_tool("insert_lines", &args.to_string(), workspace, None);
    assert!(result.is_error);
    assert!(result.content.contains("beyond end of file"));
}

#[test]
fn test_insert_lines_no_trailing_newline() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "hello\nworld").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "line": 2,
        "content": "end"
    });
    let result = execute_builtin_tool("insert_lines", &args.to_string(), workspace, None);
    assert!(!result.is_error);

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert_eq!(content, "hello\nworld\nend\n");
}

// ─── P0: search_replace dry_run ─────────────────────────────────────

#[test]
fn test_search_replace_dry_run_no_write() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "alpha beta\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "old_string": "alpha",
        "new_string": "gamma",
        "dry_run": true
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("Preview edit"));
    assert!(result.content.contains("no changes written"));
    assert!(result.content.contains("\"match_type\": \"exact\""));

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert_eq!(content, "alpha beta\n");
}

// ─── P0: match_type in result ───────────────────────────────────────

#[test]
fn test_search_replace_match_type_exact() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "hello world\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "old_string": "hello world",
        "new_string": "hi world"
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("\"match_type\": \"exact\""));
}

// ─── P0: fuzzy match — whitespace (Level 2) ─────────────────────────

#[test]
fn test_fuzzy_match_indent_difference() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.rs");
    std::fs::write(
        &file_path,
        "fn main() {\n    let x = 1;\n    let y = 2;\n}\n",
    )
    .unwrap();

    // old_string has 2-space indent instead of 4-space; multi-line prevents substring match
    let args = serde_json::json!({
        "path": "test.rs",
        "old_string": "  let x = 1;\n  let y = 2;",
        "new_string": "    let a = 10;\n    let b = 20;"
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(!result.is_error, "Error: {}", result.content);
    assert!(result
        .content
        .contains("\"match_type\": \"whitespace_fuzzy\""));

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert!(content.contains("let a = 10"));
    assert!(content.contains("let b = 20"));
}

#[test]
fn test_fuzzy_match_trailing_whitespace_auto() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    // File has trailing spaces on the line
    std::fs::write(&file_path, "hello world   \nnext\n").unwrap();

    // old_string without trailing spaces — exact match fails because
    // "hello world" is a substring of "hello world   ", but let's
    // test the multi-line case
    let args = serde_json::json!({
        "path": "test.txt",
        "old_string": "hello world   \nnext",
        "new_string": "hi\nnext"
    });
    // Exact match succeeds here (substring match)
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("\"match_type\": \"exact\""));
}

#[test]
fn test_fuzzy_match_multiline_indent() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.py");
    std::fs::write(
        &file_path,
        "def foo():\n    x = 1\n    y = 2\n    return x + y\n",
    )
    .unwrap();

    // old_string has no indentation
    let args = serde_json::json!({
        "path": "test.py",
        "old_string": "x = 1\ny = 2",
        "new_string": "    a = 10\n    b = 20"
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result
        .content
        .contains("\"match_type\": \"whitespace_fuzzy\""));

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert!(content.contains("    a = 10\n    b = 20"));
}

// ─── P0: fuzzy match — blank lines (Level 3) ────────────────────────

#[test]
fn test_fuzzy_match_blank_line_difference() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    // Content has an extra blank line between the two lines
    std::fs::write(&file_path, "aaa\n\nbbb\nccc\n").unwrap();

    // old_string without the blank line
    let args = serde_json::json!({
        "path": "test.txt",
        "old_string": "aaa\nbbb",
        "new_string": "xxx\nyyy"
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result
        .content
        .contains("\"match_type\": \"blank_line_fuzzy\""));

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert!(content.starts_with("xxx\nyyy"));
}

// ─── P0: fuzzy match — Levenshtein similarity (Level 4) ─────────────

#[test]
fn test_fuzzy_match_similarity() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(
        &file_path,
        "fn calculate_total(items: &[Item]) -> f64 {\n    items.iter().map(|i| i.price).sum()\n}\n",
    )
    .unwrap();

    // old_string has a minor typo / difference (calculate_totl instead of calculate_total)
    let args = serde_json::json!({
        "path": "test.txt",
        "old_string": "fn calculate_totl(items: &[Item]) -> f64 {\n    items.iter().map(|i| i.price).sum()\n}",
        "new_string": "fn calculate_total(items: &[Item]) -> u64 {\n    items.iter().map(|i| i.price as u64).sum()\n}"
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("similarity("));

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert!(content.contains("-> u64"));
}

#[test]
fn test_fuzzy_match_low_similarity_fails() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "completely different content here\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "old_string": "nothing even close to matching this at all",
        "new_string": "replacement"
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(result.is_error);
    assert!(result.content.contains("old_string not found"));
}

// ─── P0: insert_lines blocks sensitive paths ────────────────────────

#[test]
fn test_insert_lines_blocks_sensitive_path() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let env_path = workspace.join(".env");
    std::fs::write(&env_path, "KEY=value\n").unwrap();

    let args = serde_json::json!({
        "path": ".env",
        "line": 0,
        "content": "INJECTED=bad"
    });
    let result = execute_builtin_tool("insert_lines", &args.to_string(), workspace, None);
    assert!(result.is_error);
    assert!(result.content.contains("Blocked"));
}

// ─── Phase II: grep_files ────────────────────────────────────────────

#[test]
fn test_grep_files_basic_match() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    std::fs::write(workspace.join("a.txt"), "hello world\nfoo bar\n").unwrap();
    std::fs::write(workspace.join("b.txt"), "hello rust\nbaz\n").unwrap();

    let args = serde_json::json!({ "pattern": "hello" });
    let result = execute_builtin_tool("grep_files", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("a.txt:1:hello world"));
    assert!(result.content.contains("b.txt:1:hello rust"));
    assert!(result.content.contains("2 match(es) in 2 file(s)"));
}

#[test]
fn test_grep_files_regex_pattern() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    std::fs::write(
        workspace.join("code.rs"),
        "fn main() {\n    let x = 42;\n}\n",
    )
    .unwrap();

    let args = serde_json::json!({ "pattern": r"fn\s+\w+" });
    let result = execute_builtin_tool("grep_files", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("code.rs:1:fn main()"));
}

#[test]
fn test_grep_files_include_filter() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    std::fs::write(workspace.join("a.rs"), "match_me\n").unwrap();
    std::fs::write(workspace.join("b.py"), "match_me\n").unwrap();

    let args = serde_json::json!({ "pattern": "match_me", "include": "*.rs" });
    let result = execute_builtin_tool("grep_files", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("a.rs:1:match_me"));
    assert!(!result.content.contains("b.py"));
}

#[test]
fn test_grep_files_no_match() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    std::fs::write(workspace.join("a.txt"), "hello\n").unwrap();

    let args = serde_json::json!({ "pattern": "xyz_not_here" });
    let result = execute_builtin_tool("grep_files", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("No matches found"));
}

#[test]
fn test_grep_files_skips_git_dir() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let git_dir = workspace.join(".git");
    std::fs::create_dir_all(&git_dir).unwrap();
    std::fs::write(git_dir.join("config"), "find_me\n").unwrap();
    std::fs::write(workspace.join("src.txt"), "find_me\n").unwrap();

    let args = serde_json::json!({ "pattern": "find_me" });
    let result = execute_builtin_tool("grep_files", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("src.txt"));
    assert!(!result.content.contains(".git"));
}

#[test]
fn test_grep_files_recursive() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let sub = workspace.join("sub").join("deep");
    std::fs::create_dir_all(&sub).unwrap();
    std::fs::write(sub.join("nested.txt"), "deep_match\n").unwrap();

    let args = serde_json::json!({ "pattern": "deep_match" });
    let result = execute_builtin_tool("grep_files", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("sub/deep/nested.txt:1:deep_match"));
}

#[test]
fn test_grep_files_invalid_regex() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();

    let args = serde_json::json!({ "pattern": "[invalid" });
    let result = execute_builtin_tool("grep_files", &args.to_string(), workspace, None);
    assert!(result.is_error);
    assert!(result.content.contains("Invalid regex"));
}

// ─── Phase II: auto-backup ───────────────────────────────────────────

#[test]
fn test_search_replace_creates_backup() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "original content\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "old_string": "original",
        "new_string": "modified"
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("\"backup\""));
    assert!(result.content.contains("edit-backups"));
}

#[test]
fn test_insert_lines_creates_backup() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "line1\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "line": 0,
        "content": "prepended"
    });
    let result = execute_builtin_tool("insert_lines", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("\"backup\""));
    assert!(result.content.contains("edit-backups"));
}

#[test]
fn test_dry_run_no_backup() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "alpha beta\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "old_string": "alpha",
        "new_string": "gamma",
        "dry_run": true
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("\"backup\": null"));
}

// ─── Phase II: syntax validation ─────────────────────────────────────

#[test]
fn test_validation_warns_on_invalid_json() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("data.json");
    std::fs::write(&file_path, "{\"key\": \"value\"}\n").unwrap();

    let _args = serde_json::json!({
        "path": "data.json",
        "old_string": "\"value\"",
        "new_string": "\"value\""
    });
    let args2 = serde_json::json!({
        "path": "data.json",
        "old_string": "{\"key\": \"value\"}",
        "new_string": "{\"key\": \"value\""
    });
    let result = execute_builtin_tool("search_replace", &args2.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("JSON syntax warning"));
}

#[test]
fn test_validation_warns_on_unmatched_bracket() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("code.rs");
    std::fs::write(&file_path, "fn main() {\n    println!(\"hi\");\n}\n").unwrap();

    let args = serde_json::json!({
        "path": "code.rs",
        "old_string": "fn main() {\n    println!(\"hi\");\n}",
        "new_string": "fn main() {\n    println!(\"hi\");\n"
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("validation_warning"));
    assert!(result.content.contains("Unclosed"));
}

#[test]
fn test_validation_no_warning_on_valid_code() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("code.rs");
    std::fs::write(&file_path, "fn foo() {\n    1 + 2\n}\n").unwrap();

    let args = serde_json::json!({
        "path": "code.rs",
        "old_string": "1 + 2",
        "new_string": "3 + 4"
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("\"validation_warning\": null"));
}

#[test]
fn test_search_replace_multibyte_content_no_panic() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("readme.md");
    let chinese_content = "# 项目说明\n\n**轻量级 AI Agent 安全引擎**,内置原生系统级沙箱,零依赖,本地执行。\n\n## 功能特性\n\n- 🔒 安全沙箱\n- 🚀 高性能\n- 📦 零依赖\n";
    std::fs::write(&file_path, chinese_content).unwrap();

    let args = serde_json::json!({
        "path": "readme.md",
        "old_string": "**轻量级 AI Agent 安全引擎**,内置原生系统级沙箱,零依赖,本地执行。",
        "new_string": "**A lightweight AI Agent secure engine** with built-in sandbox, zero deps."
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(!result.is_error, "Error: {}", result.content);
    assert!(result.content.contains("\"match_type\": \"exact\""));

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert!(content.contains("lightweight AI Agent"));
}

#[test]
fn test_validation_warns_on_invalid_yaml() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("config.yaml");
    std::fs::write(&file_path, "key: value\nnested:\n  a: 1\n").unwrap();

    let args = serde_json::json!({
        "path": "config.yaml",
        "old_string": "nested:\n  a: 1",
        "new_string": "nested:\n  a: 1\n  b: [unclosed"
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(!result.is_error);
    assert!(result.content.contains("YAML syntax warning") || result.content.contains("Unclosed"));
}

// ─── Phase III: edit failure smart hints ─────────────────────────────

#[test]
fn test_failure_hint_shows_closest_match_context() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.rs");
    std::fs::write(
        &file_path,
        "fn main() {\n    println!(\"hello world\");\n    let x = 42;\n}\n",
    )
    .unwrap();

    let args = serde_json::json!({
        "path": "test.rs",
        "old_string": "completely_unrelated_string_that_wont_match_anything_at_all_xyz"
    ,   "new_string": "replacement"
    });
    let result = execute_builtin_tool("search_replace", &args.to_string(), workspace, None);
    assert!(result.is_error);
    assert!(result.content.contains("Closest match found at line"));
    assert!(result.content.contains("similarity:"));
    assert!(result.content.contains("Tip:"));
}

// ─── Phase III: insert_lines indent awareness ───────────────────────

#[test]
fn test_insert_lines_auto_indent() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.rs");
    std::fs::write(
        &file_path,
        "fn main() {\n    let x = 1;\n    let y = 2;\n}\n",
    )
    .unwrap();

    let args = serde_json::json!({
        "path": "test.rs",
        "line": 2,
        "content": "let z = 3;"
    });
    let result = execute_builtin_tool("insert_lines", &args.to_string(), workspace, None);
    assert!(!result.is_error);

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert!(
        content.contains("    let z = 3;"),
        "Expected auto-indented line, got:\n{}",
        content
    );
}

#[test]
fn test_insert_lines_no_indent_when_content_already_indented() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.py");
    std::fs::write(&file_path, "def foo():\n    x = 1\n").unwrap();

    let args = serde_json::json!({
        "path": "test.py",
        "line": 1,
        "content": "    y = 2"
    });
    let result = execute_builtin_tool("insert_lines", &args.to_string(), workspace, None);
    assert!(!result.is_error);

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert!(
        content.contains("    y = 2") && !content.contains("        y = 2"),
        "Should NOT double-indent already-indented content, got:\n{}",
        content
    );
}

#[test]
fn test_insert_lines_no_indent_at_top_level() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.txt");
    std::fs::write(&file_path, "line1\nline2\n").unwrap();

    let args = serde_json::json!({
        "path": "test.txt",
        "line": 1,
        "content": "new_line"
    });
    let result = execute_builtin_tool("insert_lines", &args.to_string(), workspace, None);
    assert!(!result.is_error);

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert_eq!(content, "line1\nnew_line\nline2\n");
}

#[test]
fn test_insert_lines_multiline_auto_indent() {
    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let file_path = workspace.join("test.rs");
    std::fs::write(&file_path, "fn main() {\n    let x = 1;\n}\n").unwrap();

    let args = serde_json::json!({
        "path": "test.rs",
        "line": 1,
        "content": "let y = 2;\nlet z = 3;"
    });
    let result = execute_builtin_tool("insert_lines", &args.to_string(), workspace, None);
    assert!(!result.is_error);

    let content = std::fs::read_to_string(&file_path).unwrap();
    assert!(content.contains("    let y = 2;\n    let z = 3;"));
}

// ─── Phase III: run_command output truncation ───────────────────────

#[test]
fn test_run_command_truncation() {
    use super::run_command;
    let long_output = "x".repeat(10000);
    let truncated = run_command::truncate_command_output_for_test(&long_output);
    assert!(truncated.len() < long_output.len());
    assert!(truncated.contains("preview truncated"));
    assert!(truncated.contains("10000 total chars"));
}

#[test]
fn test_run_command_no_truncation_short() {
    use super::run_command;
    let short = "hello world";
    let result = run_command::truncate_command_output_for_test(short);
    assert_eq!(result, short);
}

// ─── run_command blocks sensitive file read ────────────────────────────────

#[tokio::test]
async fn test_run_command_blocks_cat_env() {
    use super::run_command;
    use crate::types::SilentEventSink;

    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    std::fs::write(workspace.join(".env"), "API_KEY=sk-secret\n").unwrap();

    let mut sink = SilentEventSink;
    let args = serde_json::json!({ "command": "cat .env" });
    let result = run_command::execute_run_command(&args, workspace, &mut sink).await;
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(err.to_string().contains("Blocked"));
    assert!(err.to_string().contains("sensitive file"));
}

#[tokio::test]
async fn test_run_command_streams_output_and_returns_summary() {
    use super::run_command;
    use crate::types::EventSink;

    struct CaptureSink {
        started: Vec<String>,
        outputs: Vec<(String, String)>,
        finished: Vec<(bool, i32, u64)>,
    }

    impl EventSink for CaptureSink {
        fn on_text(&mut self, _text: &str) {}
        fn on_tool_call(&mut self, _name: &str, _arguments: &str) {}
        fn on_tool_result(&mut self, _name: &str, _result: &str, _is_error: bool) {}
        fn on_command_started(&mut self, command: &str) {
            self.started.push(command.to_string());
        }
        fn on_command_output(&mut self, stream: &str, chunk: &str) {
            self.outputs.push((stream.to_string(), chunk.to_string()));
        }
        fn on_command_finished(&mut self, success: bool, exit_code: i32, duration_ms: u64) {
            self.finished.push((success, exit_code, duration_ms));
        }
        fn on_confirmation_request(&mut self, _prompt: &str) -> bool {
            true
        }
    }

    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let args = serde_json::json!({
        "command": "printf 'hello\\n'; printf 'warn\\n' 1>&2"
    });
    let mut sink = CaptureSink {
        started: Vec::new(),
        outputs: Vec::new(),
        finished: Vec::new(),
    };

    let outcome = run_command::execute_run_command(&args, workspace, &mut sink)
        .await
        .unwrap();
    let result = outcome.content;

    assert_eq!(sink.started.len(), 1);
    assert_eq!(sink.started[0], "printf 'hello\\n'; printf 'warn\\n' 1>&2");
    assert!(sink
        .outputs
        .iter()
        .any(|(stream, chunk)| stream == "stdout" && chunk == "hello"));
    assert!(sink
        .outputs
        .iter()
        .any(|(stream, chunk)| stream == "stderr" && chunk == "warn"));
    assert_eq!(sink.finished.len(), 1);
    assert!(sink.finished[0].0);
    assert_eq!(sink.finished[0].1, 0);
    assert!(!outcome.is_error);
    assert!(!outcome.counts_as_failure);
    assert!(result.contains("Output streamed to execution log."));
    assert!(result.contains("[stderr]"));
    assert!(!result.contains("[stdout]\nhello"));
}

#[tokio::test]
async fn test_run_command_success_preview_is_compact() {
    use super::run_command;
    use crate::types::SilentEventSink;

    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let args = serde_json::json!({
        "command": "printf 'line1\\nline2\\nline3\\nline4\\n'"
    });
    let mut sink = SilentEventSink;

    let outcome = run_command::execute_run_command(&args, workspace, &mut sink)
        .await
        .unwrap();
    let result = outcome.content;

    assert!(!outcome.is_error);
    assert!(!outcome.counts_as_failure);
    assert!(result.contains("[stdout tail]"));
    assert!(result.contains("line3"));
    assert!(result.contains("line4"));
    assert!(!result.contains("line1"));
    assert!(!result.contains("line2"));
}

#[test]
fn test_run_command_timeout_outcome_is_structured_failure() {
    use super::run_command;

    let outcome = run_command::timeout_outcome_for_test();

    assert!(outcome.is_error);
    assert!(outcome.counts_as_failure);
    assert!(outcome.content.contains("Command execution timeout"));
}

#[tokio::test]
async fn test_execute_async_builtin_run_command_marks_nonzero_exit_as_error() {
    use crate::types::SilentEventSink;

    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let arguments = serde_json::json!({
        "command": "echo ok && false"
    })
    .to_string();
    let mut sink = SilentEventSink;

    let result = execute_async_builtin_tool("run_command", &arguments, workspace, &mut sink).await;

    assert!(result.is_error);
    assert!(!result.counts_as_failure);
    assert!(result.content.contains("Command failed (exit 1)."));
}

#[tokio::test]
async fn test_execute_async_builtin_run_command_marks_zero_exit_as_success() {
    use crate::types::SilentEventSink;

    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let arguments = serde_json::json!({
        "command": "echo ok"
    })
    .to_string();
    let mut sink = SilentEventSink;

    let result = execute_async_builtin_tool("run_command", &arguments, workspace, &mut sink).await;

    assert!(!result.is_error);
    assert!(!result.counts_as_failure);
    assert!(result.content.contains("Command succeeded (exit 0)."));
}

#[test]
fn test_preview_server_emits_started_and_ready_events() {
    use super::preview;
    use crate::types::EventSink;

    struct CaptureSink {
        preview_started: Vec<(String, u16)>,
        preview_ready: Vec<(String, u16)>,
        preview_failed: Vec<String>,
    }

    impl EventSink for CaptureSink {
        fn on_text(&mut self, _text: &str) {}
        fn on_tool_call(&mut self, _name: &str, _arguments: &str) {}
        fn on_tool_result(&mut self, _name: &str, _result: &str, _is_error: bool) {}
        fn on_confirmation_request(&mut self, _prompt: &str) -> bool {
            true
        }
        fn on_preview_started(&mut self, path: &str, port: u16) {
            self.preview_started.push((path.to_string(), port));
        }
        fn on_preview_ready(&mut self, url: &str, port: u16) {
            self.preview_ready.push((url.to_string(), port));
        }
        fn on_preview_failed(&mut self, message: &str) {
            self.preview_failed.push(message.to_string());
        }
    }

    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    let serve_dir = workspace.join("site");
    std::fs::create_dir_all(&serve_dir).unwrap();
    std::fs::write(serve_dir.join("index.html"), "<h1>ok</h1>").unwrap();

    let free_port = {
        let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
        listener.local_addr().unwrap().port()
    };
    let args = serde_json::json!({
        "path": "site",
        "port": free_port,
        "open_browser": false
    });
    let mut sink = CaptureSink {
        preview_started: Vec::new(),
        preview_ready: Vec::new(),
        preview_failed: Vec::new(),
    };

    let result = preview::execute_preview_server(&args, workspace, &mut sink).unwrap();

    assert!(result.contains("Preview server started at"));
    assert_eq!(sink.preview_started.len(), 1);
    assert_eq!(sink.preview_ready.len(), 1);
    assert!(sink.preview_failed.is_empty());
}

#[tokio::test]
async fn test_delegate_to_swarm_emits_started_and_failed_when_unconfigured() {
    use super::delegate_swarm;
    use crate::types::EventSink;

    struct CaptureSink {
        swarm_started: Vec<String>,
        swarm_progress: Vec<String>,
        swarm_failed: Vec<String>,
    }

    impl EventSink for CaptureSink {
        fn on_text(&mut self, _text: &str) {}
        fn on_tool_call(&mut self, _name: &str, _arguments: &str) {}
        fn on_tool_result(&mut self, _name: &str, _result: &str, _is_error: bool) {}
        fn on_confirmation_request(&mut self, _prompt: &str) -> bool {
            true
        }
        fn on_swarm_started(&mut self, description: &str) {
            self.swarm_started.push(description.to_string());
        }
        fn on_swarm_progress(&mut self, status: &str) {
            self.swarm_progress.push(status.to_string());
        }
        fn on_swarm_failed(&mut self, message: &str) {
            self.swarm_failed.push(message.to_string());
        }
    }

    let tmp = tempfile::tempdir().unwrap();
    let workspace = tmp.path();
    std::env::remove_var(delegate_swarm::SWARM_URL_ENV);
    let args = serde_json::json!({
        "description": "delegate quick summary"
    });
    let mut sink = CaptureSink {
        swarm_started: Vec::new(),
        swarm_progress: Vec::new(),
        swarm_failed: Vec::new(),
    };

    let result = delegate_swarm::execute_delegate_to_swarm(&args, workspace, &mut sink)
        .await
        .unwrap();

    assert!(result.contains("Swarm not configured"));
    assert_eq!(
        sink.swarm_started,
        vec!["delegate quick summary".to_string()]
    );
    assert!(sink.swarm_progress.is_empty());
    assert_eq!(sink.swarm_failed.len(), 1);
}