opencrabs 0.3.13

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Install with: cargo install opencrabs
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
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
//! Comprehensive tests for profile management — multi-instance isolation.
//!
//! Tests cover: name validation, token hashing, registry CRUD, profile lifecycle,
//! token-lock isolation, export/import, and edge cases.
//!
//! IMPORTANT: Filesystem CRUD tests that write to `~/.opencrabs/profiles.toml`
//! are combined into single sequential functions to prevent concurrent write
//! corruption. In-memory tests remain separate since they don't share state.

use std::fs;
use std::path::PathBuf;
use std::sync::{Mutex, OnceLock};

use crate::config::profile::{
    ProfileEntry, ProfileRegistry, acquire_token_lock, active_profile, base_opencrabs_dir,
    create_profile, delete_profile, export_profile, hash_token, import_profile, list_profiles,
    migrate_profile, release_all_locks, release_token_lock, resolve_profile_home,
    set_active_profile, validate_profile_name,
};

/// Global mutex to serialize all tests that write to ~/.opencrabs/profiles.toml.
/// Without this, parallel test execution corrupts the shared TOML file.
/// Uses unwrap_or_else to recover from poisoned state (prior test panic).
fn fs_lock() -> std::sync::MutexGuard<'static, ()> {
    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
    LOCK.get_or_init(|| Mutex::new(()))
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

// ─── Name Validation ─────────────────────────────────────────────────

#[test]
fn valid_profile_names() {
    assert!(validate_profile_name("hermes").is_ok());
    assert!(validate_profile_name("my-profile").is_ok());
    assert!(validate_profile_name("test_123").is_ok());
    assert!(validate_profile_name("a").is_ok());
    assert!(validate_profile_name("UPPERCASE").is_ok());
    assert!(validate_profile_name("MiXeD-CaSe_99").is_ok());
    assert!(validate_profile_name("x".repeat(64).as_str()).is_ok());
}

#[test]
fn invalid_profile_name_default() {
    let err = validate_profile_name("default").unwrap_err();
    assert!(err.to_string().contains("reserved"));
}

#[test]
fn invalid_profile_name_empty() {
    let err = validate_profile_name("").unwrap_err();
    assert!(err.to_string().contains("1-64"));
}

#[test]
fn invalid_profile_name_too_long() {
    let long = "x".repeat(65);
    let err = validate_profile_name(&long).unwrap_err();
    assert!(err.to_string().contains("1-64"));
}

#[test]
fn invalid_profile_name_spaces() {
    let err = validate_profile_name("has spaces").unwrap_err();
    assert!(err.to_string().contains("alphanumeric"));
}

#[test]
fn invalid_profile_name_slashes() {
    assert!(validate_profile_name("has/slash").is_err());
    assert!(validate_profile_name("back\\slash").is_err());
}

#[test]
fn invalid_profile_name_special_chars() {
    assert!(validate_profile_name("name@here").is_err());
    assert!(validate_profile_name("name.dot").is_err());
    assert!(validate_profile_name("name!bang").is_err());
    assert!(validate_profile_name("name#hash").is_err());
    assert!(validate_profile_name("emoji🦀").is_err());
}

#[test]
fn validate_boundary_length_names() {
    assert!(validate_profile_name("x").is_ok());
    assert!(validate_profile_name(&"a".repeat(64)).is_ok());
    assert!(validate_profile_name(&"a".repeat(65)).is_err());
}

// ─── Token Hashing ───────────────────────────────────────────────────

#[test]
fn hash_token_deterministic() {
    let h1 = hash_token("bot123:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw");
    let h2 = hash_token("bot123:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw");
    assert_eq!(h1, h2);
}

#[test]
fn hash_token_different_inputs() {
    let h1 = hash_token("token_a");
    let h2 = hash_token("token_b");
    assert_ne!(h1, h2);
}

#[test]
fn hash_token_fixed_length() {
    assert_eq!(hash_token("short").len(), 16);
    assert_eq!(hash_token("a".repeat(1000).as_str()).len(), 16);
    assert_eq!(hash_token("").len(), 16);
}

#[test]
fn hash_token_hex_chars_only() {
    let h = hash_token("anything");
    assert!(h.chars().all(|c| c.is_ascii_hexdigit()));
}

#[test]
fn hash_token_empty_string() {
    let h = hash_token("");
    assert_eq!(h.len(), 16);
    assert!(h.chars().all(|c| c.is_ascii_hexdigit()));
}

#[test]
fn hash_token_unicode() {
    let h = hash_token("🦀🦀🦀");
    assert_eq!(h.len(), 16);
}

// ─── Profile Registry (In-Memory) ───────────────────────────────────
// These tests use in-memory registry instances — no filesystem contention.

#[test]
fn registry_default_is_empty() {
    let reg = ProfileRegistry::default();
    assert!(reg.profiles.is_empty());
}

#[test]
fn registry_register_single() {
    let mut reg = ProfileRegistry::default();
    reg.register("hermes", Some("Messenger of the gods"));
    assert!(reg.profiles.contains_key("hermes"));
    assert_eq!(reg.profiles["hermes"].name, "hermes");
    assert_eq!(
        reg.profiles["hermes"].description.as_deref(),
        Some("Messenger of the gods")
    );
    assert!(!reg.profiles["hermes"].created_at.is_empty());
    assert!(reg.profiles["hermes"].last_used.is_none());
}

#[test]
fn registry_register_no_description() {
    let mut reg = ProfileRegistry::default();
    reg.register("scout", None);
    assert!(reg.profiles["scout"].description.is_none());
}

#[test]
fn registry_register_multiple() {
    let mut reg = ProfileRegistry::default();
    reg.register("alpha", Some("First"));
    reg.register("beta", Some("Second"));
    reg.register("gamma", None);
    assert_eq!(reg.profiles.len(), 3);
}

#[test]
fn registry_register_overwrites_duplicate() {
    let mut reg = ProfileRegistry::default();
    reg.register("hermes", Some("v1"));
    let created_v1 = reg.profiles["hermes"].created_at.clone();

    reg.register("hermes", Some("v2"));
    assert_eq!(reg.profiles["hermes"].description.as_deref(), Some("v2"));
    assert_ne!(reg.profiles["hermes"].created_at, created_v1);
}

#[test]
fn registry_touch_updates_last_used() {
    let mut reg = ProfileRegistry::default();
    reg.register("hermes", None);
    assert!(reg.profiles["hermes"].last_used.is_none());

    reg.touch("hermes");
    assert!(reg.profiles["hermes"].last_used.is_some());
}

#[test]
fn registry_touch_nonexistent_is_noop() {
    let mut reg = ProfileRegistry::default();
    reg.touch("ghost");
    assert!(reg.profiles.is_empty());
}

#[test]
fn registry_serde_roundtrip() {
    let mut reg = ProfileRegistry::default();
    reg.register("hermes", Some("Test profile"));
    reg.register("scout", None);
    reg.touch("hermes");

    let serialized = toml::to_string_pretty(&reg).unwrap();
    let deserialized: ProfileRegistry = toml::from_str(&serialized).unwrap();

    assert_eq!(deserialized.profiles.len(), 2);
    assert!(deserialized.profiles.contains_key("hermes"));
    assert!(deserialized.profiles.contains_key("scout"));
    assert!(deserialized.profiles["hermes"].last_used.is_some());
    assert_eq!(
        deserialized.profiles["hermes"].description.as_deref(),
        Some("Test profile")
    );
}

#[test]
fn registry_serde_empty() {
    let reg = ProfileRegistry::default();
    let serialized = toml::to_string_pretty(&reg).unwrap();
    let deserialized: ProfileRegistry = toml::from_str(&serialized).unwrap();
    assert!(deserialized.profiles.is_empty());
}

#[test]
fn registry_deserialized_from_toml_string() {
    let toml_str = r#"
[profiles.hermes]
name = "hermes"
description = "Messenger"
created_at = "2026-03-31T00:00:00Z"

[profiles.scout]
name = "scout"
created_at = "2026-03-31T00:00:00Z"
"#;
    let reg: ProfileRegistry = toml::from_str(toml_str).unwrap();
    assert_eq!(reg.profiles.len(), 2);
    assert_eq!(
        reg.profiles["hermes"].description.as_deref(),
        Some("Messenger")
    );
    assert!(reg.profiles["scout"].description.is_none());
}

// ─── Profile Entry Serde ────────────────────────────────────────────

#[test]
fn profile_entry_json_roundtrip() {
    let entry = ProfileEntry {
        name: "test".to_string(),
        description: Some("desc".to_string()),
        created_at: "2026-03-31T00:00:00Z".to_string(),
        last_used: Some("2026-03-31T01:00:00Z".to_string()),
    };

    let json = serde_json::to_string(&entry).unwrap();
    let deserialized: ProfileEntry = serde_json::from_str(&json).unwrap();
    assert_eq!(deserialized.name, "test");
    assert_eq!(deserialized.description.as_deref(), Some("desc"));
    assert_eq!(
        deserialized.last_used.as_deref(),
        Some("2026-03-31T01:00:00Z")
    );
}

#[test]
fn profile_entry_optional_fields() {
    let entry = ProfileEntry {
        name: "minimal".to_string(),
        description: None,
        created_at: "2026-01-01T00:00:00Z".to_string(),
        last_used: None,
    };
    assert!(entry.description.is_none());
    assert!(entry.last_used.is_none());
}

// ─── Path Resolution ─────────────────────────────────────────────────

#[test]
fn base_dir_ends_with_opencrabs() {
    let base = base_opencrabs_dir();
    assert!(base.ends_with(".opencrabs"));
}

#[test]
fn base_dir_is_absolute() {
    let base = base_opencrabs_dir();
    assert!(base.is_absolute());
}

// ─── Error Messages ──────────────────────────────────────────────────

#[test]
fn delete_default_profile_fails() {
    let err = delete_profile("default").unwrap_err();
    assert!(err.to_string().contains("cannot delete"));
}

#[test]
fn delete_nonexistent_profile_fails() {
    let err = delete_profile("_nonexistent_profile_xyz").unwrap_err();
    assert!(err.to_string().contains("does not exist"));
}

#[test]
fn export_nonexistent_profile_fails() {
    let archive = std::env::temp_dir().join("_test_nonexistent_export.tar.gz");
    let err = export_profile("_definitely_not_a_profile", &archive).unwrap_err();
    assert!(err.to_string().contains("does not exist"));
}

#[test]
fn import_nonexistent_archive_fails() {
    let err = import_profile(&PathBuf::from("/tmp/_nonexistent_archive.tar.gz")).unwrap_err();
    assert!(err.to_string().contains("not found"));
}

// ─── Registry Filesystem (Read-Only) ────────────────────────────────

#[test]
fn registry_load_from_real_path() {
    let _guard = fs_lock();
    // Should not error regardless of host state
    let loaded = ProfileRegistry::load().unwrap_or_default();
    let _ = loaded.profiles.len();
}

#[test]
fn list_profiles_always_includes_default() {
    let _guard = fs_lock();
    let profiles = list_profiles().unwrap();
    assert!(!profiles.is_empty());
    assert_eq!(profiles[0].name, "default");
    assert!(
        profiles[0]
            .description
            .as_deref()
            .unwrap()
            .contains("Default")
    );
}

// ─── Profile CRUD (Filesystem — Sequential) ─────────────────────────
// Everything that writes to ~/.opencrabs/ (profiles.toml, locks/, profiles/)
// runs inside ONE test function to prevent concurrent corruption from
// parallel test execution.

#[test]
fn filesystem_operations_sequential() {
    let _guard = fs_lock();
    let pid = std::process::id();
    let lock_dir = base_opencrabs_dir().join("locks");
    fs::create_dir_all(&lock_dir).unwrap();

    // ══════════════════════════════════════════════════════════════════
    // Part 1: Profile CRUD lifecycle
    // ══════════════════════════════════════════════════════════════════
    let name = "_test_fs_seq";
    let profile_dir = base_opencrabs_dir().join("profiles").join(name);

    // Clean slate
    let _ = fs::remove_dir_all(&profile_dir);
    let mut reg = ProfileRegistry::load().unwrap_or_default();
    reg.profiles.remove(name);
    let _ = reg.save();

    // Create
    let path = create_profile(name, Some("sequential test")).unwrap();
    assert!(path.exists(), "profile directory should be created");
    assert!(path.join("memory").exists(), "memory subdir should exist");
    assert!(path.join("logs").exists(), "logs subdir should exist");

    // Verify in registry
    let reg = ProfileRegistry::load().unwrap_or_default();
    assert!(reg.profiles.contains_key(name), "should be in registry");

    // Duplicate create fails
    let err = create_profile(name, None).unwrap_err();
    assert!(err.to_string().contains("already exists"));

    // List includes it
    let profiles = list_profiles().unwrap();
    let found = profiles.iter().any(|p| p.name == name);
    assert!(found, "should appear in list");

    // Delete
    delete_profile(name).unwrap();
    assert!(!path.exists(), "directory gone after delete");

    let reg = ProfileRegistry::load().unwrap_or_default();
    assert!(!reg.profiles.contains_key(name), "removed from registry");

    // Delete again fails
    let err = delete_profile(name).unwrap_err();
    assert!(err.to_string().contains("does not exist"));

    // ══════════════════════════════════════════════════════════════════
    // Part 2: Export/Import roundtrip
    // ══════════════════════════════════════════════════════════════════
    let exp_name = "_test_fs_exp";
    let exp_dir = base_opencrabs_dir().join("profiles").join(exp_name);
    let archive = std::env::temp_dir().join(format!("_test_fs_export_{}.tar.gz", pid));

    let _ = fs::remove_dir_all(&exp_dir);
    let _ = fs::remove_file(&archive);
    let mut reg = ProfileRegistry::load().unwrap_or_default();
    reg.profiles.remove(exp_name);
    let _ = reg.save();

    // Create with content
    let dir = create_profile(exp_name, Some("export test")).unwrap();
    fs::write(dir.join("config.toml"), "[agent]\ncontext_limit = 42000").unwrap();
    fs::write(dir.join("memory").join("note.md"), "remember this").unwrap();

    // Export
    export_profile(exp_name, &archive).unwrap();
    assert!(archive.exists(), "archive created");
    assert!(archive.metadata().unwrap().len() > 0, "archive non-empty");

    // Delete
    delete_profile(exp_name).unwrap();
    assert!(!dir.exists());

    // Import
    let imported = import_profile(&archive).unwrap();
    assert_eq!(imported, exp_name);

    // Verify content survived
    let reimported = base_opencrabs_dir().join("profiles").join(exp_name);
    assert!(reimported.exists());
    let config = fs::read_to_string(reimported.join("config.toml")).unwrap();
    assert!(config.contains("context_limit = 42000"));
    let note = fs::read_to_string(reimported.join("memory").join("note.md")).unwrap();
    assert_eq!(note, "remember this");

    // Registry has it
    let reg = ProfileRegistry::load().unwrap_or_default();
    assert!(reg.profiles.contains_key(exp_name));

    // Clean up
    let _ = delete_profile(exp_name);
    let _ = fs::remove_file(&archive);

    // Export default profile
    let default_archive =
        std::env::temp_dir().join(format!("_test_fs_default_export_{}.tar.gz", pid));
    let _ = fs::remove_file(&default_archive);
    // Retry once for transient IO (concurrent dir mutations under ~/.opencrabs/)
    let result = export_profile("default", &default_archive)
        .or_else(|_| export_profile("default", &default_archive));
    if result.is_ok() {
        assert!(default_archive.exists());
    }
    let _ = fs::remove_file(&default_archive);

    // ══════════════════════════════════════════════════════════════════
    // Part 3: Token locks
    // ══════════════════════════════════════════════════════════════════

    // Basic acquire and release
    let ch1 = "_test_fs_lk1";
    let th1 = hash_token("fs_lock_1");
    release_token_lock(ch1, &th1);

    acquire_token_lock(ch1, &th1).unwrap();
    let lf1 = lock_dir.join(format!("{}_{}.lock", ch1, th1));
    assert!(lf1.exists(), "lock file created");

    let contents = fs::read_to_string(&lf1).unwrap();
    assert!(contents.contains(&pid.to_string()), "contains our PID");

    // Format: "profile:pid"
    let parts: Vec<&str> = contents.splitn(2, ':').collect();
    assert_eq!(parts.len(), 2, "lock file should be 'profile:pid' format");
    // active_profile() may return a name set by another test's OnceLock
    // Just verify the profile field is non-empty and PID matches
    assert!(!parts[0].is_empty(), "profile name should not be empty");
    assert_eq!(parts[1], pid.to_string());

    release_token_lock(ch1, &th1);
    assert!(!lf1.exists(), "lock file removed after release");

    // Re-acquire same lock (same PID, same profile)
    let ch2 = "_test_fs_lk2";
    let th2 = hash_token("fs_lock_2");
    release_token_lock(ch2, &th2);
    acquire_token_lock(ch2, &th2).unwrap();
    acquire_token_lock(ch2, &th2).unwrap(); // same PID overwrite
    release_token_lock(ch2, &th2);

    // Stale lock from dead PID
    let ch3 = "_test_fs_lk3";
    let th3 = hash_token("fs_lock_3");
    let stale = lock_dir.join(format!("{}_{}.lock", ch3, th3));
    fs::write(&stale, "default:999999999").unwrap();
    acquire_token_lock(ch3, &th3).unwrap();
    let contents = fs::read_to_string(&stale).unwrap();
    assert!(contents.contains(&pid.to_string()));
    release_token_lock(ch3, &th3);

    // Different channels, same token hash
    let th_multi = hash_token("multi_ch");
    let ch_a = "_test_fs_mca";
    let ch_b = "_test_fs_mcb";
    release_token_lock(ch_a, &th_multi);
    release_token_lock(ch_b, &th_multi);
    acquire_token_lock(ch_a, &th_multi).unwrap();
    acquire_token_lock(ch_b, &th_multi).unwrap();
    let la = lock_dir.join(format!("{}_{}.lock", ch_a, th_multi));
    let lb = lock_dir.join(format!("{}_{}.lock", ch_b, th_multi));
    assert!(la.exists());
    assert!(lb.exists());

    // release_all_locks cleans our locks
    release_all_locks();
    assert!(!la.exists(), "release_all cleaned lock a");
    assert!(!lb.exists(), "release_all cleaned lock b");

    // release_all preserves other profiles' locks
    let th_other = hash_token("other_profile_tok");
    let other_lock = lock_dir.join(format!("_test_fs_other_{}.lock", th_other));
    fs::write(&other_lock, "other_profile:999999999").unwrap();
    release_all_locks();
    assert!(other_lock.exists(), "other profile's lock preserved");
    let _ = fs::remove_file(&other_lock);

    // Release nonexistent lock is noop
    release_token_lock("_nonexistent_channel", "0000000000000000");
}

// ─── Migration Tests ─────────────────────────────────────────────────

#[test]
fn migrate_same_profile_errors() {
    let err = migrate_profile("default", "default", false);
    assert!(err.is_err());
    assert!(
        err.unwrap_err()
            .to_string()
            .contains("source and destination profiles are the same")
    );
}

#[test]
fn migrate_nonexistent_source_errors() {
    let err = migrate_profile("_test_migrate_no_src", "default", false);
    assert!(err.is_err());
    assert!(err.unwrap_err().to_string().contains("does not exist"));
}

#[test]
fn migrate_nonexistent_destination_errors() {
    let err = migrate_profile("default", "_test_migrate_no_dst", false);
    assert!(err.is_err());
    assert!(err.unwrap_err().to_string().contains("does not exist"));
}

#[test]
fn migrate_profile_copies_md_and_toml_files() {
    let _guard = fs_lock();
    let base = crate::config::profile::base_opencrabs_dir();
    let src_name = "_test_migrate_src";
    let dst_name = "_test_migrate_dst";
    let src_dir = base.join("profiles").join(src_name);
    let dst_dir = base.join("profiles").join(dst_name);

    // Cleanup from previous runs
    let _ = fs::remove_dir_all(&src_dir);
    let _ = fs::remove_dir_all(&dst_dir);
    let mut reg = ProfileRegistry::load().unwrap_or_default();
    reg.profiles.remove(src_name);
    reg.profiles.remove(dst_name);
    let _ = reg.save();

    // Create both profiles
    create_profile(src_name, Some("source")).unwrap();
    create_profile(dst_name, Some("destination")).unwrap();

    // Populate source with brain files and config
    fs::write(src_dir.join("SOUL.md"), "# Source Soul").unwrap();
    fs::write(src_dir.join("IDENTITY.md"), "# Source Identity").unwrap();
    fs::write(src_dir.join("config.toml"), "[general]\nname = \"source\"").unwrap();
    fs::write(src_dir.join("keys.toml"), "[keys]\nsecret = \"abc\"").unwrap();
    fs::create_dir_all(src_dir.join("memory")).unwrap();
    fs::write(src_dir.join("memory").join("note.md"), "# A memory").unwrap();

    // Files that should NOT migrate
    fs::write(src_dir.join("layout.json"), "{}").unwrap();
    fs::write(src_dir.join("profiles.toml"), "skip").unwrap();
    fs::write(src_dir.join("random.txt"), "not a toml or md").unwrap();

    // Migrate
    let migrated = migrate_profile(src_name, dst_name, false).unwrap();

    // Verify correct files were copied
    assert!(dst_dir.join("SOUL.md").exists());
    assert!(dst_dir.join("IDENTITY.md").exists());
    assert!(dst_dir.join("config.toml").exists());
    assert!(dst_dir.join("keys.toml").exists());
    assert!(dst_dir.join("memory").join("note.md").exists());

    // Verify content matches
    assert_eq!(
        fs::read_to_string(dst_dir.join("SOUL.md")).unwrap(),
        "# Source Soul"
    );
    assert_eq!(
        fs::read_to_string(dst_dir.join("memory").join("note.md")).unwrap(),
        "# A memory"
    );

    // Verify skipped files
    assert!(!dst_dir.join("layout.json").exists());
    assert!(!dst_dir.join("random.txt").exists());
    // profiles.toml in dst should not be the source's "skip" content
    assert!(!dst_dir.join("profiles.toml").exists());

    assert!(migrated.contains(&"SOUL.md".to_string()));
    assert!(migrated.contains(&"IDENTITY.md".to_string()));
    assert!(migrated.contains(&"config.toml".to_string()));
    assert!(migrated.contains(&"keys.toml".to_string()));
    assert!(migrated.contains(&"memory/note.md".to_string()));
    assert_eq!(migrated.len(), 5);

    // Cleanup
    let _ = fs::remove_dir_all(&src_dir);
    let _ = fs::remove_dir_all(&dst_dir);
    let mut reg = ProfileRegistry::load().unwrap_or_default();
    reg.profiles.remove(src_name);
    reg.profiles.remove(dst_name);
    let _ = reg.save();
}

#[test]
fn migrate_profile_skips_existing_without_force() {
    let _guard = fs_lock();
    let base = crate::config::profile::base_opencrabs_dir();
    let src_name = "_test_migrate_skip_src";
    let dst_name = "_test_migrate_skip_dst";
    let src_dir = base.join("profiles").join(src_name);
    let dst_dir = base.join("profiles").join(dst_name);

    let _ = fs::remove_dir_all(&src_dir);
    let _ = fs::remove_dir_all(&dst_dir);
    let mut reg = ProfileRegistry::load().unwrap_or_default();
    reg.profiles.remove(src_name);
    reg.profiles.remove(dst_name);
    let _ = reg.save();

    create_profile(src_name, None).unwrap();
    create_profile(dst_name, None).unwrap();

    // Source has a file
    fs::write(src_dir.join("SOUL.md"), "source content").unwrap();
    // Destination already has the same file
    fs::write(dst_dir.join("SOUL.md"), "existing content").unwrap();

    // Migrate without force — should skip
    let migrated = migrate_profile(src_name, dst_name, false).unwrap();
    assert!(
        migrated.is_empty(),
        "should skip existing files without --force"
    );
    assert_eq!(
        fs::read_to_string(dst_dir.join("SOUL.md")).unwrap(),
        "existing content",
        "original content preserved"
    );

    // Migrate with force — should overwrite
    let migrated = migrate_profile(src_name, dst_name, true).unwrap();
    assert_eq!(migrated.len(), 1);
    assert_eq!(
        fs::read_to_string(dst_dir.join("SOUL.md")).unwrap(),
        "source content",
        "overwritten with source"
    );

    let _ = fs::remove_dir_all(&src_dir);
    let _ = fs::remove_dir_all(&dst_dir);
    let mut reg = ProfileRegistry::load().unwrap_or_default();
    reg.profiles.remove(src_name);
    reg.profiles.remove(dst_name);
    let _ = reg.save();
}

#[test]
fn migrate_from_default_profile_works() {
    let _guard = fs_lock();
    let base = crate::config::profile::base_opencrabs_dir();
    let dst_name = "_test_migrate_from_default";
    let dst_dir = base.join("profiles").join(dst_name);

    let _ = fs::remove_dir_all(&dst_dir);
    let mut reg = ProfileRegistry::load().unwrap_or_default();
    reg.profiles.remove(dst_name);
    let _ = reg.save();

    create_profile(dst_name, None).unwrap();

    // Default profile should have at least some .md or .toml files
    // Migrate from default — should succeed and find files
    let result = migrate_profile("default", dst_name, false);
    assert!(result.is_ok(), "migrate from default should succeed");

    let _ = fs::remove_dir_all(&dst_dir);
    let mut reg = ProfileRegistry::load().unwrap_or_default();
    reg.profiles.remove(dst_name);
    let _ = reg.save();
}

// ─── Profile Home Resolution ────────────────────────────────────────

#[test]
fn resolve_profile_home_default_is_base_dir() {
    // Without any active profile set, resolve_profile_home falls back to env var.
    // If OPENCRABS_PROFILE is unset, it returns the base ~/.opencrabs/ dir.
    // We can't test set_active_profile() here because OnceLock is global and
    // may already be set by CLI or another test. Test the env var path instead.
    let base = base_opencrabs_dir();
    let home = resolve_profile_home();

    // Either it's the base dir (default) or a profiles/<name> subdir
    // (if OnceLock or env var is set). Both are valid.
    assert!(
        home == base || home.starts_with(base.join("profiles")),
        "home {:?} should be base {:?} or a profiles subdir",
        home,
        base
    );
}

#[test]
fn resolve_profile_home_env_var_override() {
    // Test that OPENCRABS_PROFILE env var resolves to the right path.
    // We can't actually set it because it would affect other tests running
    // concurrently, so we verify the logic by checking the resolved path
    // structure matches what we'd expect.
    let base = base_opencrabs_dir();
    let expected_hermes = base.join("profiles").join("hermes");

    // The path should be constructable from base + profiles + name
    assert!(expected_hermes.ends_with("profiles/hermes"));
    assert!(expected_hermes.starts_with(&base));
}

#[test]
fn active_profile_returns_none_or_valid() {
    // active_profile() should return None (default) or a valid profile name.
    // It's set once via OnceLock, so the value depends on how the test runner
    // was invoked (with or without -p flag).
    match active_profile() {
        None => {} // default profile, totally valid
        Some(name) => {
            assert!(!name.is_empty(), "active profile name should not be empty");
            assert!(
                validate_profile_name(name).is_ok(),
                "active profile name should be valid"
            );
        }
    }
}

// ─── Profile Isolation ──────────────────────────────────────────────

#[test]
fn profiles_have_completely_separate_directories() {
    let _guard = fs_lock();
    let base = base_opencrabs_dir();
    let name_a = "_test_iso_alpha";
    let name_b = "_test_iso_beta";
    let dir_a = base.join("profiles").join(name_a);
    let dir_b = base.join("profiles").join(name_b);

    // Cleanup
    let _ = fs::remove_dir_all(&dir_a);
    let _ = fs::remove_dir_all(&dir_b);
    let mut reg = ProfileRegistry::load().unwrap_or_default();
    reg.profiles.remove(name_a);
    reg.profiles.remove(name_b);
    let _ = reg.save();

    // Create both profiles
    create_profile(name_a, Some("Alpha")).unwrap();
    create_profile(name_b, Some("Beta")).unwrap();

    // Write different content to each
    fs::write(dir_a.join("SOUL.md"), "I am Alpha").unwrap();
    fs::write(dir_b.join("SOUL.md"), "I am Beta").unwrap();
    fs::write(dir_a.join("config.toml"), "[general]\nname = \"alpha\"").unwrap();
    fs::write(dir_b.join("config.toml"), "[general]\nname = \"beta\"").unwrap();
    fs::create_dir_all(dir_a.join("memory")).unwrap();
    fs::create_dir_all(dir_b.join("memory")).unwrap();
    fs::write(dir_a.join("memory").join("fact.md"), "alpha fact").unwrap();
    fs::write(dir_b.join("memory").join("fact.md"), "beta fact").unwrap();

    // Verify complete isolation — each profile has its own data
    assert_eq!(
        fs::read_to_string(dir_a.join("SOUL.md")).unwrap(),
        "I am Alpha"
    );
    assert_eq!(
        fs::read_to_string(dir_b.join("SOUL.md")).unwrap(),
        "I am Beta"
    );
    assert_eq!(
        fs::read_to_string(dir_a.join("config.toml")).unwrap(),
        "[general]\nname = \"alpha\""
    );
    assert_eq!(
        fs::read_to_string(dir_b.join("config.toml")).unwrap(),
        "[general]\nname = \"beta\""
    );
    assert_eq!(
        fs::read_to_string(dir_a.join("memory/fact.md")).unwrap(),
        "alpha fact"
    );
    assert_eq!(
        fs::read_to_string(dir_b.join("memory/fact.md")).unwrap(),
        "beta fact"
    );

    // Modifying one profile doesn't affect the other
    fs::write(dir_a.join("SOUL.md"), "Alpha changed").unwrap();
    assert_eq!(
        fs::read_to_string(dir_b.join("SOUL.md")).unwrap(),
        "I am Beta"
    );

    // Deleting one profile doesn't affect the other
    delete_profile(name_a).unwrap();
    assert!(!dir_a.exists());
    assert!(dir_b.exists());
    assert_eq!(
        fs::read_to_string(dir_b.join("SOUL.md")).unwrap(),
        "I am Beta"
    );

    // Cleanup
    let _ = fs::remove_dir_all(&dir_b);
    let mut reg = ProfileRegistry::load().unwrap_or_default();
    reg.profiles.remove(name_a);
    reg.profiles.remove(name_b);
    let _ = reg.save();
}

#[test]
fn token_lock_prevents_same_token_reuse() {
    let _guard = fs_lock();
    let base = base_opencrabs_dir();
    let locks_dir = base.join("locks");
    let channel = "_test_iso_telegram";
    let token_hash = hash_token("shared-bot-token-12345");

    // Cleanup stale locks
    release_token_lock(channel, &token_hash);

    // Current profile acquires the lock
    let result = acquire_token_lock(channel, &token_hash);
    assert!(result.is_ok(), "should acquire the lock");

    // Verify lock file exists with correct content
    let lock_path = locks_dir.join(format!("{}_{}.lock", channel, token_hash));
    assert!(lock_path.exists());
    let content = fs::read_to_string(&lock_path).unwrap();
    let current_profile = active_profile().unwrap_or("default");
    assert!(
        content.contains(current_profile),
        "lock should contain profile name"
    );
    assert!(
        content.contains(&std::process::id().to_string()),
        "lock should contain PID"
    );

    // Same profile, same PID — re-acquiring should succeed (overwrite)
    let result = acquire_token_lock(channel, &token_hash);
    assert!(result.is_ok(), "same profile+PID should re-acquire");

    // Simulate a foreign lock — write a different profile with OUR PID.
    // On Windows CI, OpenProcess may fail for our own PID in restricted
    // environments, causing is_pid_alive to return false (stale lock path).
    // We only assert rejection when the platform can actually detect alive PIDs.
    let our_pid = std::process::id();
    fs::write(&lock_path, format!("foreign_profile:{our_pid}")).unwrap();
    let result = acquire_token_lock(channel, &token_hash);
    if let Err(e) = result {
        // Platform correctly detected alive foreign PID — verify error message
        let err_msg = e.to_string();
        assert!(
            err_msg.contains("foreign_profile"),
            "error should mention blocking profile: {}",
            err_msg
        );
    } else {
        // Platform couldn't verify PID is alive (e.g. Windows CI restrictions),
        // so lock was treated as stale and overwritten — acceptable behavior.
        eprintln!(
            "NOTE: is_pid_alive({}) returned false on this platform, stale-lock path taken",
            our_pid
        );
    }

    // Simulate a stale foreign lock — dead PID
    fs::write(&lock_path, "dead_profile:999999").unwrap();
    let result = acquire_token_lock(channel, &token_hash);
    assert!(result.is_ok(), "should acquire — stale lock from dead PID");

    // Cleanup
    release_token_lock(channel, &token_hash);
}

#[test]
fn different_tokens_same_channel_no_conflict() {
    let _guard = fs_lock();
    let channel = "_test_iso_noconflict";
    let hash_a = hash_token("bot-token-aaa");
    let hash_b = hash_token("bot-token-bbb");

    // Cleanup
    release_token_lock(channel, &hash_a);
    release_token_lock(channel, &hash_b);

    // Two different token hashes on the same channel — no conflict
    assert!(acquire_token_lock(channel, &hash_a).is_ok());
    assert!(acquire_token_lock(channel, &hash_b).is_ok());

    // Both should have their own lock files
    let base = base_opencrabs_dir();
    let locks_dir = base.join("locks");
    assert!(
        locks_dir
            .join(format!("{}_{}.lock", channel, hash_a))
            .exists()
    );
    assert!(
        locks_dir
            .join(format!("{}_{}.lock", channel, hash_b))
            .exists()
    );

    // Cleanup
    release_token_lock(channel, &hash_a);
    release_token_lock(channel, &hash_b);
}

#[test]
fn default_profile_isolation_from_named_profiles() {
    let _guard = fs_lock();
    // The default profile (root ~/.opencrabs/) should not interfere with
    // named profiles under ~/.opencrabs/profiles/<name>/
    let base = base_opencrabs_dir();
    let named = "_test_iso_vs_default";
    let named_dir = base.join("profiles").join(named);

    // Cleanup
    let _ = fs::remove_dir_all(&named_dir);
    let mut reg = ProfileRegistry::load().unwrap_or_default();
    reg.profiles.remove(named);
    let _ = reg.save();

    create_profile(named, Some("isolated from default")).unwrap();

    // Named profile has its own directory separate from root
    assert!(named_dir.exists());
    assert_ne!(named_dir, base, "named profile dir must differ from base");

    // Writing to named profile doesn't touch default's files
    fs::write(named_dir.join("IDENTITY.md"), "# Named Profile").unwrap();
    // Default profile's IDENTITY.md (if it exists) should be unchanged
    if base.join("IDENTITY.md").exists() {
        let default_content = fs::read_to_string(base.join("IDENTITY.md")).unwrap();
        assert_ne!(default_content, "# Named Profile");
    }

    // Cleanup
    let _ = fs::remove_dir_all(&named_dir);
    let mut reg = ProfileRegistry::load().unwrap_or_default();
    reg.profiles.remove(named);
    let _ = reg.save();
}

// ─── Concurrent Profile Access ───────────────────────────────────────

#[test]
fn concurrent_writes_to_separate_profiles_are_isolated() {
    // Hold lock for entire test — setup and cleanup both touch shared profiles.toml.
    // The concurrent threads only write to separate profile directories, not the registry.
    use std::thread;
    let _lock = fs_lock();

    let base = base_opencrabs_dir();
    let name_a = "_test_conc_alpha";
    let name_b = "_test_conc_beta";
    let dir_a = base.join("profiles").join(name_a);
    let dir_b = base.join("profiles").join(name_b);

    // Force-clean any stale state
    let _ = delete_profile(name_a);
    let _ = delete_profile(name_b);

    create_profile(name_a, Some("concurrent alpha")).unwrap();
    create_profile(name_b, Some("concurrent beta")).unwrap();

    let dir_a_clone = dir_a.clone();
    let dir_b_clone = dir_b.clone();

    // Spawn two threads writing to different profiles simultaneously
    let handle_a = thread::spawn(move || {
        for i in 0..50 {
            let content = format!("alpha iteration {}", i);
            fs::write(dir_a_clone.join("SOUL.md"), &content).unwrap();
            fs::write(
                dir_a_clone.join("config.toml"),
                format!("[gen]\niter = {}", i),
            )
            .unwrap();
        }
        fs::read_to_string(dir_a_clone.join("SOUL.md")).unwrap()
    });

    let handle_b = thread::spawn(move || {
        for i in 0..50 {
            let content = format!("beta iteration {}", i);
            fs::write(dir_b_clone.join("SOUL.md"), &content).unwrap();
            fs::write(
                dir_b_clone.join("config.toml"),
                format!("[gen]\niter = {}", i),
            )
            .unwrap();
        }
        fs::read_to_string(dir_b_clone.join("SOUL.md")).unwrap()
    });

    let result_a = handle_a.join().unwrap();
    let result_b = handle_b.join().unwrap();

    // Each profile has its own final state — no cross-contamination
    assert!(result_a.starts_with("alpha"), "alpha got: {}", result_a);
    assert!(result_b.starts_with("beta"), "beta got: {}", result_b);

    // Final verification: SOUL.md files have profile-specific content
    let soul_a = fs::read_to_string(dir_a.join("SOUL.md")).unwrap();
    let soul_b = fs::read_to_string(dir_b.join("SOUL.md")).unwrap();
    assert!(
        soul_a.contains("alpha"),
        "alpha soul should contain 'alpha'"
    );
    assert!(soul_b.contains("beta"), "beta soul should contain 'beta'");
    assert_ne!(soul_a, soul_b, "profile souls should be distinct");

    // Cleanup
    let _ = fs::remove_dir_all(&dir_a);
    let _ = fs::remove_dir_all(&dir_b);
    let mut reg = ProfileRegistry::load().unwrap_or_default();
    reg.profiles.remove(name_a);
    reg.profiles.remove(name_b);
    let _ = reg.save();
}

// ─── Export/Import with Nested Memory ────────────────────────────────

#[test]
fn export_import_preserves_nested_memory_directories() {
    let _guard = fs_lock();
    let base = base_opencrabs_dir();
    let src_name = "_test_nested_export_src";
    let src_dir = base.join("profiles").join(src_name);
    let export_path = std::env::temp_dir().join("_test_nested_export.tar.gz");

    // Cleanup
    let _ = fs::remove_dir_all(&src_dir);
    let _ = fs::remove_file(&export_path);
    let mut reg = ProfileRegistry::load().unwrap_or_default();
    reg.profiles.remove(src_name);
    let _ = reg.save();

    create_profile(src_name, Some("nested export test")).unwrap();

    // Create deeply nested memory structure
    let deep_dir = src_dir.join("memory").join("projects").join("opencrabs");
    fs::create_dir_all(&deep_dir).unwrap();
    fs::write(src_dir.join("memory").join("user.md"), "# User prefs").unwrap();
    fs::write(
        src_dir.join("memory").join("projects").join("index.md"),
        "# Projects",
    )
    .unwrap();
    fs::write(deep_dir.join("architecture.md"), "# Architecture notes").unwrap();
    fs::write(deep_dir.join("decisions.md"), "# ADRs").unwrap();

    // Also add regular brain files
    fs::write(src_dir.join("SOUL.md"), "# Deep soul").unwrap();
    fs::write(src_dir.join("config.toml"), "[test]\nnested = true").unwrap();

    // Export
    export_profile(src_name, &export_path).unwrap();
    assert!(export_path.exists());
    assert!(export_path.metadata().unwrap().len() > 0);

    // Delete the source profile
    delete_profile(src_name).unwrap();
    assert!(!src_dir.exists());

    // Import — import_profile extracts the profile name from the archive
    // The archive was created from src_name, so it imports as src_name
    let imported_name = import_profile(&export_path).unwrap();
    let imported_dir = base.join("profiles").join(&imported_name);
    assert!(imported_dir.exists());

    // Verify all nested files survived the roundtrip
    assert_eq!(
        fs::read_to_string(imported_dir.join("SOUL.md")).unwrap(),
        "# Deep soul"
    );
    assert_eq!(
        fs::read_to_string(imported_dir.join("memory").join("user.md")).unwrap(),
        "# User prefs"
    );
    assert_eq!(
        fs::read_to_string(
            imported_dir
                .join("memory")
                .join("projects")
                .join("index.md")
        )
        .unwrap(),
        "# Projects"
    );
    assert_eq!(
        fs::read_to_string(
            imported_dir
                .join("memory")
                .join("projects")
                .join("opencrabs")
                .join("architecture.md")
        )
        .unwrap(),
        "# Architecture notes"
    );
    assert_eq!(
        fs::read_to_string(
            imported_dir
                .join("memory")
                .join("projects")
                .join("opencrabs")
                .join("decisions.md")
        )
        .unwrap(),
        "# ADRs"
    );

    // Cleanup
    let _ = fs::remove_dir_all(&imported_dir);
    let _ = fs::remove_file(&export_path);
    let mut reg = ProfileRegistry::load().unwrap_or_default();
    reg.profiles.remove(src_name);
    reg.profiles.remove(&imported_name);
    let _ = reg.save();
}

// ─── Profile Home Resolution Edge Cases ──────────────────────────────

#[test]
fn explicit_default_name_resolves_to_base_dir() {
    // When "default" is explicitly passed, it should resolve to ~/.opencrabs/
    // not ~/.opencrabs/profiles/default/
    let base = base_opencrabs_dir();

    // The resolve logic: if profile_name is None or "default", return base
    // This tests the contract — "default" is the root, not a subdirectory
    // "default" profile should NOT create a subdirectory — it uses the base
    let _default_would_be = base.join("profiles").join("default");

    // Validate that "default" is rejected as a profile name
    assert!(
        validate_profile_name("default").is_err(),
        "\"default\" is reserved and cannot be created as a named profile"
    );
}

#[test]
fn profile_directories_never_overlap() {
    let base = base_opencrabs_dir();

    // Default profile home
    let default_home = base.clone();

    // Named profile homes
    let hermes_home = base.join("profiles").join("hermes");
    let scout_home = base.join("profiles").join("scout");

    // No profile home is a prefix of another (prevents accidental nesting)
    assert!(!hermes_home.starts_with(&scout_home));
    assert!(!scout_home.starts_with(&hermes_home));

    // Named profiles are always under profiles/ subdir, never at root
    assert!(hermes_home.starts_with(base.join("profiles")));
    assert!(scout_home.starts_with(base.join("profiles")));

    // Default home is the base — named profiles are children, not siblings
    assert!(!hermes_home.starts_with(default_home.join("config.toml")));
}

// ─── Additional Profile Tests ────────────────────────────────────────

#[test]
fn test_resolve_profile_home_returns_valid_path() {
    // Verify resolve_profile_home returns a path rooted in base_opencrabs_dir.
    // We do NOT test env var mutation here — std::env::set_var is UB in
    // multi-threaded contexts (Rust 2024) and causes flaky failures on CI.
    let base = base_opencrabs_dir();
    let home = resolve_profile_home();

    // Home must be either the base dir (default profile) or a profiles subdir
    assert!(
        home == base || home.starts_with(base.join("profiles")),
        "home {:?} should be base {:?} or a profiles subdir",
        home,
        base
    );
}

#[test]
fn test_set_and_get_active_profile() {
    // OnceLock can only be set once per process. Attempt to set it to None
    // (default profile) to avoid corrupting other tests that check for "default".
    // If already set by CLI or another test, we just verify the current value.
    let result = set_active_profile(None);

    match result {
        Ok(()) => {
            // We successfully set it to None — active_profile should return None
            assert_eq!(
                active_profile(),
                None,
                "active_profile should return None for default"
            );
        }
        Err(_) => {
            // Already set by another test or CLI — just verify it returns something valid
            let current = active_profile();
            // It's either None (default) or a valid profile name
            if let Some(name) = current {
                assert!(!name.is_empty(), "active profile name should not be empty");
            }
        }
    }
}

#[test]
fn test_concurrent_profile_writes() {
    use std::thread;

    let _guard = fs_lock();
    let base = base_opencrabs_dir();
    let names: Vec<String> = (0..5).map(|i| format!("_test_concurrent_{}", i)).collect();

    // Cleanup from previous runs
    for name in &names {
        let dir = base.join("profiles").join(name);
        let _ = fs::remove_dir_all(&dir);
    }
    let mut reg = ProfileRegistry::load().unwrap_or_default();
    for name in &names {
        reg.profiles.remove(name.as_str());
    }
    let _ = reg.save();

    // Create all 5 profiles sequentially (create_profile writes to shared
    // profiles.toml and cannot safely run concurrently)
    for name in &names {
        create_profile(name, Some("concurrent test")).unwrap();
    }

    // Spawn 5 threads, each writing to its own profile directory concurrently
    let handles: Vec<_> = names
        .iter()
        .map(|name| {
            let dir = base.join("profiles").join(name);
            let name = name.clone();
            thread::spawn(move || {
                for i in 0..20 {
                    let content = format!("{} iteration {}", name, i);
                    fs::write(dir.join("SOUL.md"), &content).unwrap();
                }
                name
            })
        })
        .collect();

    // Wait for all threads to complete
    for handle in handles {
        handle.join().unwrap();
    }

    // Verify all 5 directories exist and have been written to
    for name in &names {
        let dir = base.join("profiles").join(name);
        assert!(dir.exists(), "profile directory for {} should exist", name);
        assert!(
            dir.join("memory").exists(),
            "memory subdir for {} should exist",
            name
        );
        let content = fs::read_to_string(dir.join("SOUL.md")).unwrap();
        assert!(
            content.starts_with(name),
            "SOUL.md for {} should start with profile name, got: {}",
            name,
            content
        );
    }

    // Cleanup all 5
    for name in &names {
        let _ = delete_profile(name);
    }
    let mut reg = ProfileRegistry::load().unwrap_or_default();
    for name in &names {
        reg.profiles.remove(name.as_str());
    }
    let _ = reg.save();
}

#[test]
fn test_export_import_nested_memory() {
    let _guard = fs_lock();
    let base = base_opencrabs_dir();
    let name = "_test_exp_imp_nested";
    let profile_dir = base.join("profiles").join(name);
    let archive = std::env::temp_dir().join(format!(
        "_test_exp_imp_nested_{}.tar.gz",
        std::process::id()
    ));

    // Cleanup
    let _ = fs::remove_dir_all(&profile_dir);
    let _ = fs::remove_file(&archive);
    let mut reg = ProfileRegistry::load().unwrap_or_default();
    reg.profiles.remove(name);
    let _ = reg.save();

    // Create profile with deeply nested memory structure
    create_profile(name, Some("nested memory test")).unwrap();
    let deep_dir = profile_dir.join("memory").join("sub").join("deep");
    fs::create_dir_all(&deep_dir).unwrap();
    fs::write(deep_dir.join("note.md"), "deeply nested content").unwrap();

    // Export
    export_profile(name, &archive).unwrap();
    assert!(archive.exists(), "archive should be created");

    // Delete the profile
    delete_profile(name).unwrap();
    assert!(
        !profile_dir.exists(),
        "profile dir should be gone after delete"
    );

    // Import
    let imported_name = import_profile(&archive).unwrap();
    assert_eq!(imported_name, name);

    // Verify the nested file exists with correct content
    let reimported_dir = base.join("profiles").join(&imported_name);
    let reimported_note = reimported_dir
        .join("memory")
        .join("sub")
        .join("deep")
        .join("note.md");
    assert!(
        reimported_note.exists(),
        "nested note.md should survive export/import roundtrip"
    );
    assert_eq!(
        fs::read_to_string(&reimported_note).unwrap(),
        "deeply nested content",
        "nested file content should be preserved"
    );

    // Cleanup
    let _ = delete_profile(name);
    let _ = fs::remove_file(&archive);
    let mut reg = ProfileRegistry::load().unwrap_or_default();
    reg.profiles.remove(name);
    reg.profiles.remove(&imported_name);
    let _ = reg.save();
}

#[test]
fn test_resolve_profile_home_default_explicit() {
    // "default" is reserved — resolve_profile_home should return the base
    // ~/.opencrabs/ path, NOT ~/.opencrabs/profiles/default/
    let base = base_opencrabs_dir();

    // "default" is rejected as a profile name (it's reserved)
    assert!(
        validate_profile_name("default").is_err(),
        "\"default\" should be a reserved name"
    );

    // The base path should NOT have a profiles/default/ component
    let would_be_wrong = base.join("profiles").join("default");

    // resolve_profile_home with no active profile and no env var returns base
    let original_env = std::env::var("OPENCRABS_PROFILE").ok();
    unsafe { std::env::remove_var("OPENCRABS_PROFILE") };

    let home = resolve_profile_home();

    // If OnceLock hasn't been set, home should be exactly base (not profiles/default/)
    match active_profile() {
        None => {
            assert_eq!(
                home, base,
                "with no active profile, resolve_profile_home should return base dir"
            );
            assert_ne!(
                home, would_be_wrong,
                "should NOT resolve to profiles/default/"
            );
        }
        Some(_) => {
            // OnceLock is set — can't test the None path, but verify it's not profiles/default/
            assert_ne!(
                home, would_be_wrong,
                "should never resolve to profiles/default/"
            );
        }
    }

    // Restore env var
    if let Some(val) = original_env {
        unsafe { std::env::set_var("OPENCRABS_PROFILE", val) };
    }
}