ag-agent 0.22.1

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
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
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
//! Native harness configuration unit tests covering model listing, provider
//! registration, sign-in, environments, and session storage.

use std::collections::BTreeMap;
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use ag_contracts::{
    AgentDefinitionPrompt, AgentRequestKind, ContextCompaction, ExecutionPolicy, HostCacheSharing,
    PermissionMode, ReasoningLevel, ResponseStyle, SpeedMode, TurnContinuation, TurnRequest,
};
use ag_harness::catalog::ModelId;
use ag_harness::lifecycle::LifecycleEvent;
use ag_harness::model::{
    ModelCapabilities, ModelClient, ModelMetadata, ModelProfile, ModelRegistry, ModelRequest,
    ReasoningEffort,
};
use ag_harness::provider::{AnthropicConfig, CostTier, ModelConfiguration, ModelProvider};
use ag_harness::recovery::ExecutionIdentity;
use ag_harness::store::{MemoryStore, SessionStore};
use ag_harness::{Harness, HarnessBuildError, Model};
use ag_protocol::ProtocolRequestProfile;
use ag_session::{AgentModel, HarnessModelOption, HarnessModelStatus, ModelCost, ServedModel};
use serde_json::{Value, json};
use sha2::{Digest as _, Sha256};
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

use super::{
    FALLBACK_MODEL_PROFILE, HarnessContext, ModelSelection, NativeHarnessConfig, ResumeOnlyModel,
    RunOptions, bash_environment, chatgpt_auth_file, configuration_status, harness_models,
    model_cost, output_schema, provider_display_name, reasoning_effort, repository,
    running_context_window, unicode_environment,
};
use crate::agent::model_profile;
use crate::agent::native::sandbox::{CommandSandbox, SESSION_SANDBOX};

#[test]
/// Asks for the base URL of a keyed provider without a default endpoint,
/// such as Qwen, while Kimi's default endpoint needs none.
fn configuration_status_requires_a_base_url_only_without_a_default() {
    // Arrange
    let environment = environment(&[("DASHSCOPE_API_KEY", "key"), ("KIMI_API_KEY", "key")]);

    // Act
    let qwen = configuration_status(ModelProvider::Qwen, &environment, |_| false);
    let kimi = configuration_status(ModelProvider::Kimi, &environment, |_| false);

    // Assert
    assert_eq!(
        qwen,
        HarnessModelStatus::MissingConfiguration("DASHSCOPE_BASE_URL")
    );
    assert_eq!(kimi, HarnessModelStatus::Ready);
}

#[test]
/// Asks for a missing base URL before a missing key, so that saving a key
/// never marks ready a provider that still cannot serve requests.
fn configuration_status_asks_for_the_base_url_before_the_key() {
    // Arrange
    let without_url = environment(&[]);
    let with_url = environment(&[("DASHSCOPE_BASE_URL", "https://dashscope.test/v1")]);

    // Act
    let missing_both = configuration_status(ModelProvider::Qwen, &without_url, |_| false);
    let missing_key = configuration_status(ModelProvider::Qwen, &with_url, |_| false);

    // Assert
    assert_eq!(
        missing_both,
        HarnessModelStatus::MissingConfiguration("DASHSCOPE_BASE_URL")
    );
    assert_eq!(missing_key, HarnessModelStatus::ApiKeyRequired("qwen"));
}

#[test]
/// Locates Agentty's `ChatGPT` sign-in from the named file, then its data
/// directory, then the home directory.
fn chatgpt_auth_file_prefers_the_named_file_then_agentty_root_then_home() {
    // Arrange
    let named = environment(&[
        ("CHATGPT_AUTH_FILE", "/tmp/sign-in.json"),
        ("AGENTTY_ROOT", "/data/agentty"),
    ]);
    let root = environment(&[
        ("CHATGPT_AUTH_FILE", " "),
        ("AGENTTY_ROOT", "/data/agentty"),
    ]);
    // A data directory is used as given, as `agentty`'s `home.rs` reads it.
    let spaced_root = environment(&[("AGENTTY_ROOT", "/data ")]);
    let home = environment(&[("AGENTTY_ROOT", ""), ("HOME", "/home/user")]);

    // Act
    let locations = [
        chatgpt_auth_file(&named),
        chatgpt_auth_file(&root),
        chatgpt_auth_file(&spaced_root),
        chatgpt_auth_file(&home),
        chatgpt_auth_file(&BTreeMap::new()),
    ];

    // Assert
    assert_eq!(
        locations,
        [
            Some(PathBuf::from("/tmp/sign-in.json")),
            Some(PathBuf::from("/data/agentty/auth/chatgpt.json")),
            Some(PathBuf::from("/data /auth/chatgpt.json")),
            Some(PathBuf::from("/home/user/.agentty/auth/chatgpt.json")),
            None,
        ]
    );
}

#[test]
/// Registers a `ChatGPT` model from the sign-in under `AGENTTY_ROOT` alone,
/// since the harness keeps no default credential location.
fn chatgpt_registry_reads_the_sign_in_under_agentty_root() {
    // Arrange
    let (directory, auth_file) = signed_in_auth_file();
    let root = tempfile::tempdir().expect("data root");
    std::fs::create_dir_all(root.path().join("auth")).expect("auth directory");
    std::fs::copy(&auth_file, root.path().join("auth/chatgpt.json")).expect("sign-in");
    drop(directory);
    let root_value = root.path().to_str().expect("UTF-8 path");
    let environment = environment(&[("AGENTTY_ROOT", root_value)]);
    let selection =
        ModelSelection::resolve("chatgpt/gpt-6.1-sol", &environment).expect("served model");

    // Act
    let registry = selection.registry(&environment, None);

    // Assert
    let registry = registry.expect("registry");
    let registration = registry.resolve(&selection.key()).expect("registration");
    assert_eq!(registration.identity().revision(), "agentty-native-2");
}

#[test]
/// Summarizes on the requested model only when it is another harness model
/// that is ready now and declares structured output; every other request
/// falls back to the session's model.
fn summary_model_falls_back_to_the_session_model() {
    // Arrange
    let environment = environment(&[
        ("DASHSCOPE_API_KEY", "key"),
        ("DASHSCOPE_BASE_URL", "http://qwen"),
        ("MODEL_API_KEY", "key"),
        ("OPENAI_API_KEY", "sk-key"),
        ("CHATGPT_AUTH_FILE", "/tmp/chatgpt.json"),
    ]);
    let session = ModelSelection::resolve("muse-spark-1.3", &environment).expect("session");
    let cases: [(Option<&str>, bool, Option<&str>); 10] = [
        // Unset: the session model compacts.
        (None, true, None),
        // A ready model with structured output compacts.
        (Some("gpt-5.6-terra"), false, Some("openai/gpt-5.6-terra")),
        // Credentials missing.
        (Some("claude-haiku-5-5"), true, None),
        // Ready, but without structured output.
        (Some("qwen3.8-flash"), true, None),
        // A local server's model declares no structured output.
        (Some("openai-compatible/qwen3:latest"), true, None),
        // The session's own model.
        (Some("muse-spark-1.3"), true, None),
        // A model no harness provider serves, such as an agent CLI's.
        (Some("gemini-4-argon"), true, None),
        (Some(""), true, None),
        // A sign-in provider compacts only while signed in.
        (Some("chatgpt/gpt-6-luna"), false, None),
        (Some("chatgpt/gpt-6-luna"), true, Some("chatgpt/gpt-6-luna")),
    ];

    for (requested, signed_in, expected) in cases {
        // Act
        let summary = session.summary_model(requested, &environment, |_| signed_in);

        // Assert
        assert_eq!(
            summary.as_ref().map(ModelSelection::key).as_deref(),
            expected,
            "{requested:?}"
        );
    }
}

#[test]
/// Names a model as users pick it: `ChatGPT` plan and local server models
/// with their provider, other cataloged models bare, and unknown keys as
/// given.
fn model_ids_keep_the_provider_users_pick_them_by() {
    // Arrange
    let keys = [
        "chatgpt/gpt-6-luna",
        "openai/gpt-6-luna",
        "openai-compatible/qwen3:latest",
        "muse/muse-spark-1.3",
        "host/unknown",
    ];

    // Act
    let ids = keys.map(ModelSelection::model_id_of);

    // Assert
    assert_eq!(
        ids,
        [
            "chatgpt/gpt-6-luna",
            "gpt-6-luna",
            "openai-compatible/qwen3:latest",
            "muse-spark-1.3",
            "host/unknown",
        ]
    );
}

#[test]
/// Builds a harness that summarizes on a usable summary model, and one that
/// summarizes on its own model when the summary model's client cannot be
/// built or a session refuses it, without failing either.
fn harness_summarizes_on_a_usable_summary_model() {
    // Arrange
    let worktree = tempfile::tempdir().expect("worktree");
    let real_path = std::env::var("PATH").expect("test PATH should be set");
    let keyed = environment(&[
        ("MODEL_API_KEY", "key"),
        ("OPENAI_API_KEY", "sk-key"),
        ("PATH", &real_path),
    ]);
    let unkeyed_summary = environment(&[("MODEL_API_KEY", "key"), ("PATH", &real_path)]);
    let repository = repository(worktree.path(), &keyed).expect("repository");
    let session = ModelSelection::resolve("muse-spark-1.3", &keyed).expect("session");
    let summary = ModelSelection::resolve("gpt-5.6-terra", &keyed).expect("summary");
    let context = |environment| HarnessContext {
        compacts: true,
        environment,
        reasoning_level: ReasoningLevel::Medium,
        repository: &repository,
        running_context_window: None,
        sandbox: SESSION_SANDBOX,
        summary_model: Some(&summary),
    };

    // Act
    let summarizing = session.harness(&context(&keyed), |_: LifecycleEvent| {});
    let unsummarized = session.harness(&context(&unkeyed_summary), |_: LifecycleEvent| {});
    let mut refused = false;
    context(&keyed).apply_summary_model(|_| {
        refused = true;

        Err(HarnessBuildError::ModelRequired.into())
    });
    let unlisted = ModelSelection::resolve("openai-compatible/local", &keyed)
        .expect("served model")
        .summary_entry(&keyed);

    // Assert
    let summarizing = summarizing.expect("harness with a summary model");
    let unsummarized = unsummarized.expect("harness without a summary model");
    assert_eq!(
        summarizing.summary_model().map(ModelId::as_str),
        Some("openai/gpt-5.6-terra")
    );
    assert_eq!(unsummarized.summary_model(), None);
    assert!(refused);
    let key = |harness: &Harness| {
        harness
            .model_registration()
            .map(|registration| registration.identity().key().to_string())
    };
    // The summary model never changes the recorded registration.
    assert_eq!(key(&summarizing).as_deref(), Some("muse/muse-spark-1.3"));
    assert_eq!(key(&unsummarized), key(&summarizing));
    assert!(
        unlisted
            .err()
            .is_some_and(|error| error.contains("does not list")),
    );
}

/// Builds an environment snapshot from string pairs.
fn environment(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
    pairs
        .iter()
        .map(|(name, value)| ((*name).to_string(), (*value).to_string()))
        .collect()
}

/// Returns the served model `name`.
fn served(name: &str) -> AgentModel {
    AgentModel::OpenAiCompatible(ServedModel::new(name).expect("served name"))
}

/// Returns a base URL on a port nothing listens on.
fn unreachable_base_url() -> String {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("free port");
    let address = listener.local_addr().expect("address");

    format!("http://{address}/v1")
}

/// Writes a stored `ChatGPT` sign-in and returns its directory and file path.
fn signed_in_auth_file() -> (tempfile::TempDir, String) {
    let directory = tempfile::tempdir().expect("auth directory");
    let auth_file = directory.path().join("chatgpt.json");
    let credentials = json!({
        "access_token": "access",
        "client_id": "client",
        "email": null,
        "expires_at": u64::MAX,
        "ext_agent_host_id": "host",
        "id_token": "id",
        "refresh_token": "refresh",
        "scopes": []
    });
    std::fs::write(&auth_file, credentials.to_string()).expect("credential file");
    let auth_file = auth_file.to_str().expect("UTF-8 path").to_string();

    (directory, auth_file)
}

/// Mounts Ollama's `/api/ps` reporting `qwen3:latest` loaded with `window`.
async fn mount_loaded_window(server: &MockServer, window: u64) {
    Mock::given(method("GET"))
        .and(path("/api/ps"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "models": [{"name": "qwen3:latest", "context_length": window}]
        })))
        .mount(server)
        .await;
}

#[tokio::test]
/// Lists the configured local model first, then every paid catalog model with
/// the variable its provider still needs.
async fn harness_models_list_local_then_paid_models_with_their_status() {
    // Arrange
    let environment = environment(&[
        ("KIMI_API_KEY", "key"),
        ("MODEL_API_KEY", "key"),
        ("OPENAI_COMPATIBLE_BASE_URL", &unreachable_base_url()),
        ("OPENAI_COMPATIBLE_MODEL", " qwen3:latest "),
    ]);

    // Act
    let options = harness_models(&environment, |_| false).await;

    // Assert
    let summary = options
        .iter()
        .map(|option| (option.model, option.cost, option.status))
        .collect::<Vec<_>>();
    let anthropic = HarnessModelStatus::ApiKeyRequired("anthropic");
    let dashscope = HarnessModelStatus::MissingConfiguration("DASHSCOPE_BASE_URL");
    let openai = HarnessModelStatus::ApiKeyRequired("openai");
    let ready = HarnessModelStatus::Ready;
    let sign_in = HarnessModelStatus::SignInRequired("ag-harness login chatgpt");
    assert_eq!(
        summary,
        vec![
            (served("qwen3:latest"), ModelCost::Local, ready),
            (AgentModel::MuseSpark13, ModelCost::Standard, ready),
            (AgentModel::MuseSpark13Contributor, ModelCost::Cheap, ready),
            // Kimi defaults to Moonshot AI's international endpoint.
            (AgentModel::KimiK3, ModelCost::Premium, ready),
            (AgentModel::KimiK26, ModelCost::Standard, ready),
            (AgentModel::Qwen38Max, ModelCost::Standard, dashscope),
            (AgentModel::QwenPlus, ModelCost::Cheap, dashscope),
            (AgentModel::Qwen38Flash, ModelCost::Cheap, dashscope),
            (AgentModel::Qwen37Flash, ModelCost::Cheap, dashscope),
            (AgentModel::ChatGptGpt61Sol, ModelCost::Plan, sign_in),
            (AgentModel::ChatGptGpt61Terra, ModelCost::Plan, sign_in),
            (AgentModel::ChatGptGpt6Astra, ModelCost::Plan, sign_in),
            (AgentModel::ChatGptGpt6Sol, ModelCost::Plan, sign_in),
            (AgentModel::ChatGptGpt6Luna, ModelCost::Plan, sign_in),
            (AgentModel::ChatGptGpt56Sol, ModelCost::Plan, sign_in),
            (AgentModel::ChatGptGpt56Terra, ModelCost::Plan, sign_in),
            (AgentModel::ChatGptGpt56Luna, ModelCost::Plan, sign_in),
            (AgentModel::Gpt61Sol, ModelCost::Standard, openai),
            (AgentModel::Gpt6Astra, ModelCost::Premium, openai),
            (AgentModel::Gpt6Luna, ModelCost::Cheap, openai),
            (AgentModel::Gpt56Terra, ModelCost::Standard, openai),
            (AgentModel::ClaudeSonnet55, ModelCost::Standard, anthropic),
            (AgentModel::ClaudeOpus55, ModelCost::Premium, anthropic),
            (AgentModel::ClaudeFable52, ModelCost::Premium, anthropic),
            (AgentModel::ClaudeHaiku55, ModelCost::Cheap, anthropic),
        ]
    );
    assert_eq!(options[0].provider, "OpenAI-compatible server");
    assert_eq!(options[1].provider, "Muse");
    assert_eq!(options[3].provider, "Kimi");
    assert_eq!(options[5].provider, "Qwen");
    assert_eq!(options[9].provider, "ChatGPT plan");
    assert_eq!(options[17].provider, "OpenAI");
    let sonnet = options
        .iter()
        .find(|option| option.model == AgentModel::ClaudeSonnet55)
        .expect("Claude Sonnet is listed");
    assert_eq!(sonnet.provider, "Anthropic");
    // Only Muse's contributor tier lets the provider train on prompts.
    assert_eq!(
        options
            .iter()
            .filter(|option| option.trains_on_prompts)
            .map(|option| option.model)
            .collect::<Vec<_>>(),
        [AgentModel::MuseSpark13Contributor]
    );
    // The harness catalog declares the ChatGPT-plan windows.
    assert_eq!(options[9].context_window, Some(500_000));
    // The harness catalog declares the Qwen flash window, and Agentty its
    // fitted Qwen3.8-Max and Qwen-Plus profiles.
    assert_eq!(options[7].context_window, Some(1_000_000));
    assert_eq!(options[5].context_window, Some(1_000_000));
    assert_eq!(options[6].context_window, Some(1_000_000));
    // The harness catalog declares the Muse and Kimi windows.
    assert_eq!(options[1].context_window, Some(1_048_576));
    assert_eq!(options[4].context_window, Some(262_144));
    // Shared Codex models show the window the harness runs them with.
    assert_eq!(
        options[17].context_window,
        ModelProvider::OpenAi
            .declared_profile("gpt-6.1-sol", |_| Err(std::env::VarError::NotPresent))
            .expect("OpenAI profiles read no environment")
            .map(ModelProfile::context_window_tokens)
    );
}

#[tokio::test]
/// Marks ChatGPT-plan models ready once the credential file the environment
/// locates exists, and asks for sign-in otherwise.
async fn harness_models_report_the_chatgpt_sign_in() {
    // Arrange
    let environment = environment(&[
        ("CHATGPT_AUTH_FILE", "/credentials/chatgpt.json"),
        ("OPENAI_COMPATIBLE_BASE_URL", &unreachable_base_url()),
    ]);
    let plan_statuses = |options: Vec<HarnessModelOption>| {
        options
            .into_iter()
            .filter(|option| option.cost == ModelCost::Plan)
            .map(|option| option.status)
            .collect::<Vec<_>>()
    };

    // Act
    let signed_in = harness_models(&environment, |path| {
        path == Path::new("/credentials/chatgpt.json")
    })
    .await;
    let signed_out = harness_models(&environment, |_| false).await;

    // Assert
    assert_eq!(plan_statuses(signed_in), [HarnessModelStatus::Ready; 8]);
    assert_eq!(
        plan_statuses(signed_out),
        [HarnessModelStatus::SignInRequired("ag-harness login chatgpt"); 8]
    );
}

#[test]
/// Names every provider the way users know it.
fn providers_have_display_names() {
    // Arrange, Act, Assert
    assert_eq!(
        ModelProvider::all()
            .iter()
            .map(|provider| provider_display_name(*provider))
            .collect::<Vec<_>>(),
        [
            "Muse",
            "Kimi",
            "Qwen",
            "OpenAI",
            "ChatGPT plan",
            "Anthropic",
            "OpenAI-compatible server"
        ]
    );
}

#[test]
/// Shows every catalog price class as the matching model cost.
fn catalog_cost_tiers_map_to_model_costs() {
    // Arrange
    let tiers = [
        CostTier::Local,
        CostTier::Plan,
        CostTier::Cheap,
        CostTier::Standard,
        CostTier::Premium,
    ];

    // Act
    let costs = tiers.map(model_cost);

    // Assert
    assert_eq!(
        costs,
        [
            ModelCost::Local,
            ModelCost::Plan,
            ModelCost::Cheap,
            ModelCost::Standard,
            ModelCost::Premium
        ]
    );
}

#[tokio::test]
/// Lists every model a reachable Ollama serves once, marking models without
/// tool calls, and keeps its reported windows.
async fn harness_models_list_discovered_ollama_models() {
    // Arrange
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/tags"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"models": [
            {
                "name": "qwen3:latest",
                "details": {"context_length": 40960},
                "capabilities": ["completion", "tools"]
            },
            {
                "name": "gemma:latest",
                "details": {"context_length": 8192},
                "capabilities": ["completion"]
            }
        ]})))
        .mount(&server)
        .await;
    mount_loaded_window(&server, 4096).await;
    let environment = environment(&[
        (
            "OPENAI_COMPATIBLE_BASE_URL",
            &format!("{}/v1", server.uri()),
        ),
        ("OPENAI_COMPATIBLE_MODEL", "qwen3:latest"),
    ]);

    // Act
    let options = harness_models(&environment, |_| false).await;

    // Assert
    let local = options
        .iter()
        .filter(|option| !option.cost.is_paid())
        .collect::<Vec<_>>();
    assert_eq!(local.len(), 2);
    assert_eq!(local[0].model, served("qwen3:latest"));
    assert_eq!(local[0].provider, "Ollama");
    assert_eq!(local[0].status, HarnessModelStatus::Ready);
    assert_eq!(local[0].context_window, Some(40_960));
    assert_eq!(local[0].loaded_context_window, Some(4096));
    assert_eq!(local[1].model, served("gemma:latest"));
    assert_eq!(local[1].status, HarnessModelStatus::NoToolSupport);
}

#[tokio::test]
/// Sizes a local turn to the window the server runs and refuses a window
/// that would silently drop conversation history.
async fn running_context_window_checks_the_local_server() {
    // Arrange
    let roomy = MockServer::start().await;
    mount_loaded_window(&roomy, 32_768).await;
    let cramped = MockServer::start().await;
    mount_loaded_window(&cramped, 4096).await;
    let base_url = |server: &MockServer| {
        environment(&[(
            "OPENAI_COMPATIBLE_BASE_URL",
            &format!("{}/v1", server.uri()),
        )])
    };
    let local = ModelSelection::resolve("openai-compatible/qwen3:latest", &environment(&[]))
        .expect("served model");
    let hosted = ModelSelection::resolve("kimi-k3", &environment(&[])).expect("kimi-k3");
    let unreachable = environment(&[("OPENAI_COMPATIBLE_BASE_URL", &unreachable_base_url())]);

    // Act
    let roomy_window = running_context_window(&local, &base_url(&roomy)).await;
    let cramped_window = running_context_window(&local, &base_url(&cramped)).await;
    let hosted_window = running_context_window(&hosted, &environment(&[])).await;
    let unreachable_window = running_context_window(&local, &unreachable).await;

    // Assert
    assert_eq!(roomy_window, Ok(Some(32_768)));
    let error = cramped_window.expect_err("a 4,096-token window is too small");
    assert!(error.contains("4096-token context window"), "{error}");
    assert!(error.contains("OLLAMA_CONTEXT_LENGTH=32768"), "{error}");
    assert_eq!(hosted_window, Ok(None));
    assert_eq!(unreachable_window, Ok(None));
}

#[test]
/// Registers a served model with the window its server runs.
fn openai_compatible_registration_uses_the_running_window() {
    // Arrange
    let selection = ModelSelection::resolve("openai-compatible/qwen3:latest", &environment(&[]))
        .expect("served model");

    // Act
    let registry = selection
        .registry(&environment(&[]), Some(20_000))
        .expect("registry");

    // Assert
    let registration = registry.resolve(&selection.key()).expect("registration");
    assert_eq!(
        registration.capabilities().profile.context_window_tokens(),
        20_000
    );
}

#[test]
/// Resolves `openai-compatible` to the served model the environment names
/// and recorded keys for any served model.
fn openai_compatible_selection_names_the_served_model() {
    // Arrange
    let configured = environment(&[("OPENAI_COMPATIBLE_MODEL", " qwen3:latest ")]);

    // Act
    let selection = ModelSelection::resolve("openai-compatible", &configured)
        .expect("a named served model should resolve");
    let chosen = ModelSelection::resolve("openai-compatible/llama3:8b", &configured)
        .expect("a chosen served model should resolve");
    let missing = ModelSelection::resolve("openai-compatible", &environment(&[]))
        .expect_err("an unnamed served model should fail");

    // Assert
    assert_eq!(selection.key(), "openai-compatible/qwen3:latest");
    assert_eq!(chosen.key(), "openai-compatible/llama3:8b");
    assert_eq!(
        ModelSelection::from_key("openai-compatible/llama3.3:70b").map(|other| other.key()),
        Some("openai-compatible/llama3.3:70b".to_string())
    );
    assert_eq!(ModelSelection::from_key("openai-compatible/ "), None);
    assert!(missing.contains("OPENAI_COMPATIBLE_MODEL"), "{missing}");
    assert!(missing.contains("before starting Agentty"), "{missing}");
}

#[test]
/// Registers the OpenAI-compatible model with the profile the environment
/// declares and tool calls but no image input, without an API key, and
/// reports invalid declarations.
fn openai_compatible_registration_uses_the_declared_profile() {
    // Arrange
    let configured = environment(&[
        ("OPENAI_COMPATIBLE_MODEL", "qwen3:latest"),
        ("OPENAI_COMPATIBLE_CONTEXT_WINDOW", "40960"),
    ]);
    let invalid_window = environment(&[
        ("OPENAI_COMPATIBLE_MODEL", "qwen3:latest"),
        ("OPENAI_COMPATIBLE_CONTEXT_WINDOW", "lots"),
    ]);
    let selection =
        ModelSelection::resolve("openai-compatible", &configured).expect("served model");

    // Act
    let registry = selection.registry(&configured, None).expect("registry");
    let invalid = selection
        .registry(&invalid_window, None)
        .err()
        .expect("an invalid window should fail");

    // Assert
    let registration = registry.resolve(&selection.key()).expect("registration");
    assert_eq!(
        registration.capabilities().profile.context_window_tokens(),
        40_960
    );
    assert!(registration.capabilities().tool_calls);
    assert!(!registration.capabilities().image_input);
    assert_eq!(
        registration
            .metadata()
            .as_ref()
            .map(ModelMetadata::provider),
        Some("openai_compatible")
    );
    assert!(
        invalid.starts_with("Invalid harness model profile"),
        "{invalid}"
    );
}

#[test]
/// Names the model and endpoint variables, not an optional key, when a
/// keyless provider cannot be configured.
fn openai_compatible_configuration_failures_name_the_model_and_endpoint() {
    // Arrange
    let blank = ModelSelection {
        model: " ".to_string(),
        provider: ModelProvider::OpenAiCompatible,
    };

    // Act
    let error = blank
        .registry(&environment(&[]), None)
        .err()
        .expect("a blank served model should fail");

    // Assert
    assert!(
        error.contains("Check OPENAI_COMPATIBLE_MODEL and OPENAI_COMPATIBLE_BASE_URL"),
        "{error}"
    );
    assert!(!error.contains("OPENAI_COMPATIBLE_API_KEY"), "{error}");
}

#[test]
/// Skips variables whose name or value is not valid Unicode instead of
/// panicking.
fn unicode_environment_skips_invalid_variables() {
    // Arrange
    let invalid = || OsString::from_vec(vec![0x66, 0x6f, 0xff]);
    let variables = [
        (OsString::from("MODEL_API_KEY"), OsString::from("key")),
        (OsString::from("LATIN1_VALUE"), invalid()),
        (invalid(), OsString::from("value")),
    ];

    // Act
    let environment = unicode_environment(variables);

    // Assert
    assert_eq!(
        environment,
        BTreeMap::from([("MODEL_API_KEY".to_string(), "key".to_string())])
    );
}

#[tokio::test]
/// Reports the recorded identity without credentials and refuses requests.
async fn resume_only_model_never_sends_requests() {
    // Arrange
    let metadata = ModelConfiguration::new(ModelProvider::Kimi, "kimi-k3")
        .base_url("http://127.0.0.1:9")
        .client_from_environment(|_| Ok("key".to_string()))
        .expect("kimi client")
        .metadata()
        .clone();
    let model = ResumeOnlyModel {
        metadata: metadata.clone(),
    };
    let schema = output_schema(ProtocolRequestProfile::UtilityPrompt).expect("schema");

    // Act
    let error = Model::complete(&model, ModelRequest::new("Hi", schema))
        .await
        .expect_err("resume-only model must not complete");

    // Assert
    assert_eq!(Model::metadata(&model), Some(metadata));
    assert!(error.to_string().contains("can only resume"), "{error}");
}

#[test]
/// Resolves catalog models and rejects mismatched registration keys.
fn model_selection_round_trips_registration_keys() {
    // Arrange
    let selection =
        ModelSelection::resolve("kimi-k3", &environment(&[])).expect("kimi-k3 should resolve");

    // Act
    let key = selection.key();

    // Assert
    assert_eq!(key, "kimi/kimi-k3");
    assert_eq!(ModelSelection::from_key(&key), Some(selection));
    assert_eq!(ModelSelection::from_key("kimi-k3"), None);
    assert_eq!(ModelSelection::from_key("qwen/kimi-k3"), None);
    assert!(ModelSelection::resolve("claude-unlisted", &environment(&[])).is_err());
}

#[test]
/// Routes `chatgpt/<model>` ids only to the `ChatGPT` plan and bare ids only to
/// API-billed providers, so neither silently stands in for the other.
fn chatgpt_selection_never_shares_ids_with_openai() {
    // Arrange
    let environment = environment(&[]);

    // Act
    let plan = ModelSelection::resolve("chatgpt/gpt-6.1-sol", &environment)
        .expect("a plan model should resolve");
    let api =
        ModelSelection::resolve("gpt-6.1-sol", &environment).expect("an API model should resolve");
    let plan_only_bare = ModelSelection::resolve("gpt-6.1-terra", &environment);
    let unknown_plan = ModelSelection::resolve("chatgpt/kimi-k3", &environment);

    // Assert
    assert_eq!(plan.provider, ModelProvider::ChatGpt);
    assert_eq!(plan.model, "gpt-6.1-sol");
    assert_eq!(plan.key(), "chatgpt/gpt-6.1-sol");
    assert_eq!(api.provider, ModelProvider::OpenAi);
    assert_eq!(api.key(), "openai/gpt-6.1-sol");
    assert!(plan_only_bare.is_err());
    assert_eq!(
        unknown_plan,
        Err("The harness does not serve model `chatgpt/kimi-k3`.".to_string())
    );
    assert_eq!(ModelSelection::from_key(&plan.key()), Some(plan));
    assert_eq!(ModelSelection::from_key(&api.key()), Some(api));
    assert_eq!(ModelSelection::from_key("openai/gpt-6.1-terra"), None);
    assert_eq!(ModelSelection::from_key("chatgpt/kimi-k3"), None);
}

#[test]
/// Asks for sign-in, not an API key, when the `ChatGPT` plan has none stored.
fn chatgpt_registration_without_sign_in_names_the_login_command() {
    // Arrange
    let directory = tempfile::tempdir().expect("auth directory");
    let missing = directory.path().join("chatgpt.json");
    let environment = environment(&[("CHATGPT_AUTH_FILE", missing.to_str().expect("UTF-8"))]);
    let selection =
        ModelSelection::resolve("chatgpt/gpt-6-luna", &environment).expect("plan model");

    // Act
    let error = selection
        .registry(&environment, None)
        .err()
        .expect("a missing sign-in should fail");

    // Assert
    assert!(
        error.starts_with("Cannot use harness model `gpt-6-luna`"),
        "{error}"
    );
    assert!(
        error.ends_with("Run `ag-harness login chatgpt`, then retry."),
        "{error}"
    );
    assert!(!error.contains("OPENAI_API_KEY"), "{error}");
}

#[test]
/// Resumes a ChatGPT-plan session without a stored sign-in.
fn chatgpt_resume_only_harness_needs_no_sign_in() {
    // Arrange
    let worktree = tempfile::tempdir().expect("worktree");
    let real_path = std::env::var("PATH").expect("test PATH should be set");
    let environment = environment(&[("PATH", &real_path)]);
    let repository = repository(worktree.path(), &environment).expect("repository");
    let selection =
        ModelSelection::resolve("chatgpt/gpt-6.1-sol", &environment).expect("plan model");
    let context = HarnessContext {
        compacts: false,
        sandbox: SESSION_SANDBOX,
        summary_model: None,
        environment: &environment,
        reasoning_level: ReasoningLevel::Medium,
        repository: &repository,
        running_context_window: None,
    };

    // Act
    let harness = selection.resume_only_harness(&context, |_: LifecycleEvent| {});

    // Assert
    let harness = harness.expect("resume-only harness");
    let registration = harness.model_registration().expect("registration");
    assert_eq!(registration.identity().key(), "chatgpt/gpt-6.1-sol");
    assert_eq!(registration.identity().revision(), "agentty-native-2");
    assert!(registration.capabilities().tool_calls);
}

#[test]
/// Registers each served model under the current revision with its declared
/// context profile: the provider catalog's where it declares one, Agentty's
/// for the others, and the conservative fallback for uncataloged models.
/// Every model declares tool calls, and all but the text-only Qwen3.7-Flash
/// declare image input.
fn registrations_declare_revision_profiles_and_capabilities() {
    // Arrange
    let (_directory, auth_file) = signed_in_auth_file();
    let environment = environment(&[
        ("DASHSCOPE_API_KEY", "key"),
        ("DASHSCOPE_BASE_URL", "http://qwen"),
        ("ANTHROPIC_API_KEY", "key"),
        ("KIMI_API_KEY", "key"),
        ("KIMI_BASE_URL", "http://kimi"),
        ("MODEL_API_KEY", "key"),
        ("OPENAI_API_KEY", "sk-key"),
        ("CHATGPT_AUTH_FILE", &auth_file),
    ]);
    let models = ModelProvider::all().iter().flat_map(|provider| {
        provider
            .known_models()
            .iter()
            .map(move |model| (*provider, *model))
    });

    // Act / Assert
    for (provider, model) in models {
        let id = if provider == ModelProvider::ChatGpt {
            format!("chatgpt/{model}")
        } else {
            model.to_string()
        };
        let selection = ModelSelection::resolve(&id, &environment).expect("served model");
        let registry = selection.registry(&environment, None).expect("registry");
        let registration = registry.resolve(&selection.key()).expect("registration");
        // The harness catalog's own profile wins over Agentty's fitted one.
        let expected = provider
            .declared_profile(model, |_| Err(std::env::VarError::NotPresent))
            .expect("hosted catalog profiles read no environment")
            .or_else(|| {
                AgentModel::parse_persisted(&id)
                    .ok()
                    .and_then(model_profile::declared)
            })
            .unwrap_or(FALLBACK_MODEL_PROFILE);
        assert_eq!(registration.identity().key(), selection.key());
        assert_eq!(registration.identity().revision(), "agentty-native-2");
        let spec = registration.catalog_spec().expect("catalog entry");
        assert_eq!(spec.id().as_str(), selection.key());
        assert_eq!(
            (spec.pricing(), spec.max_output(), spec.max_concurrency()),
            (None, None, None),
            "runs stay unpriced and unmetered"
        );
        assert_eq!(registration.capabilities().profile, expected, "{model}");
        assert!(registration.capabilities().tool_calls, "{model}");
        assert_eq!(
            registration.capabilities().image_input,
            model != "qwen3.7-flash",
            "{model}"
        );
    }
    let sol = ModelSelection::resolve("gpt-6.1-sol", &environment).expect("served model");
    let sol_registry = sol.registry(&environment, None).expect("registry");
    let sol_profile = sol_registry
        .resolve("openai/gpt-6.1-sol")
        .expect("registration")
        .capabilities()
        .profile;
    assert_ne!(
        Some(sol_profile),
        model_profile::declared(AgentModel::Gpt61Sol),
        "the harness must not reuse the Codex app-server compaction profile"
    );
    assert_eq!(FALLBACK_MODEL_PROFILE.context_window_tokens(), 128_000);
    assert_eq!(FALLBACK_MODEL_PROFILE.reserved_tokens(), 49_673);
    assert_eq!(FALLBACK_MODEL_PROFILE.input_token_budget(), 78_327);
}

#[tokio::test]
/// Places each session database in its own directory and rejects paths.
async fn session_database_uses_one_directory_per_session() {
    // Arrange
    let data_root = tempfile::tempdir().expect("data root");
    let config = NativeHarnessConfig::new(data_root.path().to_path_buf());

    // Act
    let database = config.session_database("session-1").await;

    // Assert
    assert_eq!(
        database,
        Ok(data_root.path().join("session-1").join("harness.db"))
    );
    assert!(data_root.path().join("session-1").is_dir());
    for invalid in ["", ".", "..", "a/b", "a\\b"] {
        assert!(config.session_database(invalid).await.is_err(), "{invalid}");
    }
    assert!(!config.environment().is_empty());
}

#[tokio::test]
/// Reports a session directory that cannot be created.
async fn session_database_reports_directory_failures() {
    // Arrange
    let data_root = tempfile::NamedTempFile::new().expect("file in place of a directory");
    let config = NativeHarnessConfig::new(data_root.path().to_path_buf());

    // Act
    let database = config.session_database("session-1").await;

    // Assert
    assert!(
        database
            .expect_err("a file root should fail")
            .contains("Failed to create the harness session directory")
    );
}

#[test]
/// Grants essentials first and withholds provider keys and endpoints.
fn bash_environment_orders_essentials_and_drops_provider_variables() {
    // Arrange
    let environment = environment(&[
        ("AAA", "first"),
        ("ANTHROPIC_API_KEY", "secret"),
        ("ANTHROPIC_BASE_URL", "https://proxy.example/v1"),
        ("CHATGPT_AUTH_FILE", "/home/test/chatgpt.json"),
        ("CLAUDE_CODE_OAUTH_TOKEN", "secret"),
        ("DASHSCOPE_API_KEY", "secret"),
        ("HOME", "/home/test"),
        ("KIMI_BASE_URL", "http://kimi"),
        ("MODEL_API_KEY", "secret"),
        ("OPENAI_API_KEY", "secret"),
        ("OPENAI_BASE_URL", "https://proxy.example/v1"),
        ("OPENAI_COMPATIBLE_API_KEY", "secret"),
        ("PATH", "/usr/bin"),
    ]);

    // Act
    let granted = bash_environment(&environment)
        .into_iter()
        .map(|(name, _)| name.as_str())
        .collect::<Vec<_>>();

    // Assert
    assert_eq!(granted, ["PATH", "HOME", "AAA"]);
}

#[test]
/// Keeps tool-critical variables within the harness grant limit when the host
/// environment exceeds it.
fn bash_environment_prioritizes_tool_variables_in_large_environments() {
    // Arrange
    let mut environment = (0..100)
        .map(|index| (format!("AAA_{index:03}"), "value".to_string()))
        .collect::<BTreeMap<_, _>>();
    environment.insert("SSH_AUTH_SOCK".to_string(), "/tmp/agent.sock".to_string());
    environment.insert("XDG_CACHE_HOME".to_string(), "/tmp/cache".to_string());

    // Act
    let granted = bash_environment(&environment)
        .into_iter()
        .map(|(name, _)| name.as_str())
        .collect::<Vec<_>>();

    // Assert
    assert_eq!(granted[..2], ["SSH_AUTH_SOCK", "XDG_CACHE_HOME"]);
    assert_eq!(granted.len(), 102);
}

/// Returns a session turn request for `folder`.
fn session_request(folder: &Path) -> TurnRequest {
    TurnRequest {
        context_compaction: ContextCompaction::Off,
        execution_policy: ExecutionPolicy::default(),
        continuation: TurnContinuation::fresh(),
        folder: folder.to_path_buf(),
        host_caches: HostCacheSharing::PerSession,
        main_checkout_root: None,
        model: "muse-spark-1.3".to_string(),
        permission_mode: PermissionMode::AutoEdit,
        agent_profile: AgentDefinitionPrompt::default(),
        prompt: "Commit".into(),
        provider_call_budget: None,
        reasoning_level: ReasoningLevel::default(),
        request_kind: AgentRequestKind::SessionStart,
        response_style: ResponseStyle::default(),
        speed_mode: SpeedMode::default(),
    }
}

#[tokio::test]
/// Gives each session one stable temporary directory beside its harness
/// database, and rejects invalid session ids.
async fn session_sandbox_keeps_one_temporary_directory_per_session() {
    // Arrange
    let data_root = tempfile::tempdir().expect("data root");
    let workspace = tempfile::tempdir().expect("workspace");
    let config = NativeHarnessConfig::new(data_root.path().to_path_buf());
    let host_home = tempfile::tempdir().expect("host home");
    let environment =
        BTreeMap::from([("HOME".to_string(), host_home.path().display().to_string())]);
    let request = session_request(workspace.path());

    // Act
    let first = config
        .session_sandbox("session-1", &request, &environment)
        .await;
    let second = config
        .session_sandbox("session-1", &request, &environment)
        .await;
    let other = config
        .session_sandbox("session-2", &request, &environment)
        .await;
    let invalid = config.session_sandbox("a/b", &request, &environment).await;
    let sharing = TurnRequest {
        host_caches: HostCacheSharing::Shared,
        ..session_request(workspace.path())
    };
    let shared = config
        .session_sandbox("session-1", &sharing, &environment)
        .await;

    // Assert
    let policy = |sandbox: CommandSandbox| {
        RunOptions::new(
            ProtocolRequestProfile::SessionTurn,
            PermissionMode::AutoEdit,
            &environment,
            &sandbox,
        )
        .expect("options")
        .bash
    };
    let first = policy(first.expect("first sandbox"));
    assert_eq!(first, policy(second.expect("second sandbox")));
    assert_ne!(first, policy(other.expect("other session sandbox")));
    assert!(data_root.path().join("session-1/tmp/cargo").is_dir());
    assert!(invalid.is_err());
    // Sharing the host's caches keeps the directory and changes the
    // policy revision, since the cache variables name other places.
    let shared = format!("{:?}", policy(shared.expect("shared sandbox")));
    assert!(
        shared.contains("agentty-native-sandbox-1-host-caches"),
        "{shared}"
    );
    assert!(!format!("{first:?}").contains("host-caches"));
}

#[tokio::test]
/// Gives each utility prompt a fresh temporary directory, removed when the
/// prompt ends; the first prompt of a process removes those an earlier
/// process left behind; a data root that cannot hold one is reported.
async fn utility_sandbox_creates_a_temporary_directory_per_prompt() {
    // Arrange
    let data_root = tempfile::tempdir().expect("data root");
    let stale = data_root.path().join(".utility/run-stale");
    std::fs::create_dir_all(&stale).expect("stale directory");
    let workspace = tempfile::tempdir().expect("workspace");
    let config = NativeHarnessConfig::new(data_root.path().to_path_buf());
    let file_root = tempfile::NamedTempFile::new().expect("file in place of a directory");
    let unusable = NativeHarnessConfig::new(file_root.path().to_path_buf());
    let environment = BTreeMap::new();

    // Act
    let (_sandbox, first) = config
        .utility_sandbox(workspace.path(), &environment)
        .await
        .expect("first utility sandbox");
    std::fs::create_dir_all(&stale).expect("directory of a running prompt");
    let (_sandbox, second) = config
        .utility_sandbox(workspace.path(), &environment)
        .await
        .expect("second utility sandbox");
    let failure = unusable
        .utility_sandbox(workspace.path(), &environment)
        .await;

    // Assert
    let first_path = first.path().to_path_buf();
    assert_eq!(
        first_path.parent(),
        Some(data_root.path().join(".utility").as_path())
    );
    assert_ne!(first_path, second.path());
    assert!(stale.is_dir(), "only the first prompt of a process sweeps");
    drop(first);
    assert!(!first_path.exists());
    assert!(
        failure
            .err()
            .expect("a file root should fail")
            .contains("Failed to create the harness temporary directory")
    );
}

#[tokio::test]
/// Reports a session temporary directory that cannot be created.
async fn session_sandbox_reports_temporary_directory_failures() {
    // Arrange
    let data_root = tempfile::tempdir().expect("data root");
    let workspace = tempfile::tempdir().expect("workspace");
    std::fs::create_dir_all(data_root.path().join("session-1")).expect("session directory");
    std::fs::write(data_root.path().join("session-1/tmp"), "").expect("file in place");
    let config = NativeHarnessConfig::new(data_root.path().to_path_buf());

    // Act
    let failure = config
        .session_sandbox(
            "session-1",
            &session_request(workspace.path()),
            &BTreeMap::new(),
        )
        .await;

    // Assert
    assert!(
        failure
            .err()
            .expect("a file in place of the directory should fail")
            .contains("Failed to create the harness temporary directory")
    );
}

#[tokio::test]
/// Copies from the Cargo cache of the session's project, kept under the
/// host's cache root and keyed by the main checkout, into the session's
/// `CARGO_HOME`, and copies nothing for a host that keeps no cache.
async fn session_sandbox_copies_from_the_project_cargo_cache() {
    // Arrange
    let data_root = tempfile::tempdir().expect("data root");
    let cache_root = tempfile::tempdir().expect("cache root");
    let workspace = tempfile::tempdir().expect("workspace");
    let main_checkout = Path::new("/projects/main");
    let key = hex::encode(Sha256::digest(main_checkout.as_os_str().as_encoded_bytes()));
    let cache = cache_root.path().join(&key[..32]);
    let archive = "registry/cache/index.crates.io-1/leaf-1.0.0.crate";
    std::fs::create_dir_all(cache.join("home/registry/cache/index.crates.io-1")).expect("cache");
    std::fs::write(cache.join("home").join(archive), "crate").expect("archive");
    std::fs::write(
        cache.join("generation"),
        format!("agentty-cargo-cache 3\n1\nvariant\nfile {archive}\n"),
    )
    .expect("generation");
    std::fs::write(
        workspace.path().join("Cargo.lock"),
        format!(
            "version = 4\n\n[[package]]\nname = \"leaf\"\nversion = \"1.0.0\"\nsource = \
             \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"{}\"\n",
            hex::encode(Sha256::digest("crate"))
        ),
    )
    .expect("lockfile");
    let without_cache = NativeHarnessConfig::new(data_root.path().to_path_buf());
    let config = without_cache
        .clone()
        .with_trusted_cargo_cache(cache_root.path().to_path_buf());
    let environment = BTreeMap::new();
    let copy = data_root.path().join("session-1/tmp/cargo").join(archive);
    let mut request = session_request(workspace.path());
    request.main_checkout_root = Some(main_checkout.to_path_buf());

    // Act
    without_cache
        .session_sandbox("session-1", &request, &environment)
        .await
        .expect("sandbox without cache");
    let copied_without_cache = copy.exists();
    config
        .session_sandbox("session-1", &request, &environment)
        .await
        .expect("sandbox");

    // Assert
    assert!(!copied_without_cache);
    assert_eq!(
        std::fs::read_to_string(&copy).expect("copied archive"),
        "crate"
    );
    assert!(std::fs::symlink_metadata(&copy).expect("copy").is_file());
}

#[test]
/// Withholds credential-like variables from commands, whatever their case,
/// and keeps ordinary ones.
fn bash_environment_drops_credentials() {
    // Arrange
    let credentials = [
        "AWS_ACCESS_KEY_ID",
        "AWS_PROFILE",
        "CARGO_REGISTRY_TOKEN",
        "DATABASE_URL",
        "GEMINI_API_KEY",
        "GH_TOKEN",
        "GITHUB_TOKEN",
        "GITLAB_TOKEN",
        "GOOGLE_API_KEY",
        "HF_TOKEN",
        "NPM_TOKEN",
        "SENTRY_DSN",
        "app_secret",
        "DB_PASSWORD",
        "SMTP_PASSWD",
        "GOOGLE_APPLICATION_CREDENTIALS",
    ];
    let kept = [
        "CARGO_TARGET_DIR",
        "EDITOR",
        "KEYBOARD_LAYOUT",
        "SSH_AUTH_SOCK",
    ];
    let environment = credentials
        .iter()
        .chain(&kept)
        .map(|name| (name.to_string(), "value".to_string()))
        .collect::<BTreeMap<_, _>>();

    // Act
    let granted = bash_environment(&environment)
        .into_iter()
        .map(|(name, _)| name.as_str())
        .collect::<Vec<_>>();

    // Assert
    assert_eq!(
        granted,
        [
            "SSH_AUTH_SOCK",
            "CARGO_TARGET_DIR",
            "EDITOR",
            "KEYBOARD_LAYOUT"
        ]
    );
}

#[test]
/// Grants the sandbox's own `TMPDIR` and tool caches in place of the host's.
fn bash_policies_replace_host_temporary_and_cache_directories() {
    // Arrange
    let sandbox = CommandSandbox::new(
        Path::new("/data-root"),
        PathBuf::from("/data-root/session-1/tmp"),
        &BTreeMap::new(),
    );
    let host = environment(&[
        ("CARGO_HOME", "/home/test/.cargo"),
        ("PATH", "/usr/bin"),
        ("TMPDIR", "/tmp/host"),
        ("XDG_CACHE_HOME", "/home/test/.cache"),
    ]);
    let without_host_values = environment(&[("PATH", "/usr/bin")]);
    let policy = |environment: &BTreeMap<String, String>| {
        RunOptions::new(
            ProtocolRequestProfile::SessionTurn,
            PermissionMode::AutoEdit,
            environment,
            &sandbox,
        )
        .expect("options")
        .bash
    };

    // Act
    let with_host = policy(&host);
    let without_host = policy(&without_host_values);

    // Assert
    assert_eq!(with_host, without_host);
}

#[test]
/// Skips variables beyond the harness grant limit instead of failing.
fn run_options_tolerate_oversized_environments() {
    // Arrange
    let environment = (0..100)
        .map(|index| (format!("VAR_{index:03}"), "value".to_string()))
        .collect::<BTreeMap<_, _>>();
    let sandbox = CommandSandbox::new(
        Path::new("/data-root"),
        PathBuf::from("/data-root/session-1/tmp"),
        &environment,
    );

    // Act
    let edit = RunOptions::new(
        ProtocolRequestProfile::SessionTurn,
        PermissionMode::AutoEdit,
        &environment,
        &sandbox,
    );
    let read_only = RunOptions::new(
        ProtocolRequestProfile::SessionTurn,
        PermissionMode::ReadOnly,
        &environment,
        &sandbox,
    );

    // Assert
    let edit = edit.expect("edit options should build");
    assert!(edit.bash.is_some());
    assert_eq!(
        edit.tools.names().collect::<Vec<_>>(),
        ["read", "write", "bash"]
    );
    let read_only = read_only.expect("read-only options should build");
    assert!(read_only.bash.is_none());
    assert_eq!(read_only.tools.names().collect::<Vec<_>>(), ["read"]);
    assert!(output_schema(ProtocolRequestProfile::UtilityPrompt).is_ok());
}

#[test]
/// Finds the first usable absolute Git and reports invalid worktrees.
fn repository_resolves_git_from_path() {
    // Arrange
    let worktree = tempfile::tempdir().expect("worktree");
    let real_path = std::env::var("PATH").expect("test PATH should be set");
    let with_decoys = environment(&[(
        "PATH",
        &format!("relative/bin:/nonexistent-agentty-bin:{real_path}"),
    )]);

    // Act
    let found = repository(worktree.path(), &with_decoys);
    let missing_git = repository(worktree.path(), &environment(&[("PATH", "/nonexistent")]));
    let missing_root = repository(
        &PathBuf::from("/nonexistent-agentty-worktree"),
        &environment(&[("PATH", &real_path)]),
    );

    // Assert
    assert!(found.is_ok(), "{found:?}");
    assert_eq!(
        missing_git.err(),
        Some("The harness needs a Git executable on PATH.".to_string())
    );
    assert!(
        missing_root
            .expect_err("missing worktree should fail")
            .starts_with("Invalid harness worktree")
    );
}

#[test]
/// Maps every reasoning level to the matching harness effort.
fn reasoning_levels_map_one_to_one() {
    // Arrange
    let cases = [
        (ReasoningLevel::Low, ReasoningEffort::Low),
        (ReasoningLevel::Medium, ReasoningEffort::Medium),
        (ReasoningLevel::High, ReasoningEffort::High),
        (ReasoningLevel::XHigh, ReasoningEffort::XHigh),
        (ReasoningLevel::Max, ReasoningEffort::Max),
    ];

    // Act / Assert
    for (level, effort) in cases {
        assert_eq!(reasoning_effort(level), effort);
    }
}

#[test]
/// Serves Claude ids shared with the Claude Code backend through the
/// Anthropic provider, under an `anthropic/<model>` key, and without
/// credentials when only resuming.
fn claude_models_register_on_the_anthropic_provider() {
    // Arrange
    let worktree = tempfile::tempdir().expect("worktree");
    let real_path = std::env::var("PATH").expect("test PATH should be set");
    let keyed = environment(&[("ANTHROPIC_API_KEY", "key"), ("PATH", &real_path)]);
    let unkeyed = environment(&[("PATH", &real_path)]);
    let repository = repository(worktree.path(), &unkeyed).expect("repository");
    let context = HarnessContext {
        compacts: false,
        sandbox: SESSION_SANDBOX,
        summary_model: None,
        environment: &unkeyed,
        reasoning_level: ReasoningLevel::Medium,
        repository: &repository,
        running_context_window: None,
    };

    // Act
    let selection = ModelSelection::resolve("claude-opus-5-5", &keyed).expect("served model");
    let registry = selection.registry(&keyed, None).expect("registry");
    let missing_key = selection.registry(&unkeyed, None);
    let resume_only = selection.resume_only_harness(&context, |_: LifecycleEvent| {});

    // Assert
    assert_eq!(selection.key(), "anthropic/claude-opus-5-5");
    assert_eq!(
        ModelSelection::from_key("anthropic/claude-opus-5-5").as_ref(),
        Some(&selection)
    );
    assert_eq!(ModelSelection::from_key("anthropic/claude-unlisted"), None);
    let registration = registry
        .resolve("anthropic/claude-opus-5-5")
        .expect("registration");
    assert_eq!(registration.identity().revision(), "agentty-native-2");
    assert_eq!(
        registration.capabilities().profile.context_window_tokens(),
        1_000_000
    );
    assert!(registration.capabilities().image_input);
    let error = missing_key.err().expect("a missing key should be reported");
    assert!(
        error.ends_with("Pick the model with `/model` to paste its API key, then retry."),
        "{error}"
    );
    let resume_only = resume_only.expect("resume-only harness");
    let registration = resume_only.model_registration().expect("registration");
    assert_eq!(registration.identity().key(), "anthropic/claude-opus-5-5");
}

#[test]
/// Declares Muse's key, revision, tool calls, and image input.
fn muse_registration_declares_its_identity_and_capabilities() {
    // Arrange
    let environment = environment(&[("MODEL_API_KEY", "key")]);
    let selection = ModelSelection::resolve("muse-spark-1.3", &environment).expect("served model");

    // Act
    let registry = selection.registry(&environment, None).expect("registry");

    // Assert
    let registration = registry
        .resolve("muse/muse-spark-1.3")
        .expect("registration");
    assert_eq!(registration.identity().revision(), "agentty-native-2");
    assert!(registration.capabilities().tool_calls);
    assert!(registration.capabilities().image_input);
}

#[tokio::test]
/// Resumes a session recorded on the hand-built registration of earlier
/// releases, which declared the same `provider/model` key, revision, and
/// capabilities the catalog registration now derives.
async fn sessions_recorded_on_manual_registrations_resume_on_catalog_registrations() {
    // Arrange
    let environment = environment(&[("KIMI_API_KEY", "key"), ("KIMI_BASE_URL", "http://kimi")]);
    let selection = ModelSelection::resolve("kimi-k3", &environment).expect("served model");
    let registry = selection.registry(&environment, None).expect("registry");
    let current = registry.resolve("kimi/kimi-k3").expect("registration");
    // Earlier releases declared the provider catalog's profile for Kimi K3.
    let recorded_profile = ModelProvider::Kimi
        .declared_profile("kimi-k3", |_| Err(std::env::VarError::NotPresent))
        .expect("hosted catalog profiles read no environment")
        .expect("Kimi K3 declares a profile");
    let capabilities = ModelCapabilities::new(recorded_profile)
        .with_image_input(true)
        .with_tool_calls(true);
    let mut recorded = ModelRegistry::new();
    recorded
        .register(
            ExecutionIdentity::new("kimi/kimi-k3", "agentty-native-2").expect("identity"),
            ResumeOnlyModel {
                metadata: current.metadata().expect("metadata"),
            },
            capabilities,
        )
        .expect("recorded registration");
    let store: Arc<dyn SessionStore> = Arc::new(MemoryStore::new());
    Harness::from_registry(&recorded, "kimi/kimi-k3")
        .expect("recorded harness")
        .store(Arc::clone(&store))
        .session(
            "recorded",
            output_schema(ProtocolRequestProfile::SessionTurn).expect("schema"),
        )
        .create()
        .await
        .expect("recorded session");

    // Act
    let resumed = Harness::from_registry(&registry, &selection.key())
        .expect("harness")
        .store(store)
        .resume("recorded")
        .await;

    // Assert
    assert_eq!(
        current.identity(),
        recorded
            .resolve("kimi/kimi-k3")
            .expect("recorded")
            .identity()
    );
    assert_eq!(current.capabilities(), capabilities);
    resumed.expect("the catalog registration resumes the recorded session");
}

#[tokio::test]
/// Sends every protocol schema to Claude using only the JSON Schema keywords
/// its structured outputs accept, which the API otherwise answers with a
/// `400`.
async fn protocol_schemas_send_only_keywords_claude_accepts() {
    for profile in [
        ProtocolRequestProfile::FocusedReview,
        ProtocolRequestProfile::GraphProposal,
        ProtocolRequestProfile::ReviewMetadata,
        ProtocolRequestProfile::SessionTurn,
        ProtocolRequestProfile::UtilityPrompt,
    ] {
        // Arrange
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/messages"))
            .respond_with(ResponseTemplate::new(400).set_body_json(json!({})))
            .mount(&server)
            .await;
        let client = ModelClient::anthropic(AnthropicConfig {
            api_key: "claude-key".to_string(),
            base_url: format!("{}/v1", server.uri()),
            model: "claude-haiku-5-5".to_string(),
        })
        .expect("client");
        let schema = output_schema(profile).expect("schema");

        // Act
        let _rejected = client.complete(ModelRequest::new("Answer", schema)).await;

        // Assert
        let requests = server.received_requests().await.expect("recording");
        let body: Value = requests[0].body_json().expect("JSON request body");
        assert_claude_accepts(
            &body["output_config"]["format"]["schema"],
            &format!("{profile:?}"),
        );
    }
}

/// Asserts that `schema`, found at `at`, uses only the keywords, values, and
/// combinator shapes Anthropic documents as supported for structured
/// outputs: an `anyOf` only beside annotations, and no `allOf` of two or
/// more schemas where one directly holds `$ref`, `anyOf`, or `allOf`.
fn assert_claude_accepts(schema: &Value, at: &str) {
    const ANY_OF_SIBLINGS: [&str; 6] = [
        "$defs",
        "anyOf",
        "default",
        "definitions",
        "description",
        "title",
    ];
    const FORMATS: [&str; 10] = [
        "date",
        "date-time",
        "duration",
        "email",
        "hostname",
        "ipv4",
        "ipv6",
        "time",
        "uri",
        "uuid",
    ];
    let Some(object) = schema.as_object() else {
        return;
    };
    if object.contains_key("anyOf") {
        let siblings: Vec<_> = object
            .keys()
            .filter(|keyword| !ANY_OF_SIBLINGS.contains(&keyword.as_str()))
            .collect();
        assert!(siblings.is_empty(), "{at}: `anyOf` beside {siblings:?}");
    }
    if let Some(branches) = object
        .get("allOf")
        .and_then(Value::as_array)
        .filter(|branches| branches.len() > 1)
    {
        assert!(
            branches.iter().all(|branch| ["$ref", "anyOf", "allOf"]
                .iter()
                .all(|keyword| branch.get(keyword).is_none())),
            "{at}: `allOf` of several schemas holds `$ref`, `anyOf`, or `allOf`"
        );
    }
    for (keyword, value) in object {
        let at = format!("{at}/{keyword}");
        match keyword.as_str() {
            "$defs" | "definitions" | "properties" => {
                for (name, nested) in value.as_object().expect("schema map") {
                    assert_claude_accepts(nested, &format!("{at}/{name}"));
                }
            }
            "allOf" | "anyOf" => {
                for (index, nested) in value.as_array().expect("schema list").iter().enumerate() {
                    assert_claude_accepts(nested, &format!("{at}/{index}"));
                }
            }
            "items" => assert_claude_accepts(value, &at),
            "additionalProperties" => assert_eq!(value, &json!(false), "{at}"),
            "format" => assert!(
                value
                    .as_str()
                    .is_some_and(|format| FORMATS.contains(&format)),
                "{at}: {value}"
            ),
            "minItems" => assert!(value.as_u64().is_some_and(|items| items <= 1), "{at}"),
            other => assert!(
                [
                    "$ref",
                    "const",
                    "default",
                    "description",
                    "enum",
                    "pattern",
                    "required",
                    "title",
                    "type"
                ]
                .contains(&other),
                "Claude structured outputs reject `{at}`"
            ),
        }
    }
}