bitrouter 1.0.0-alpha.31

BitRouter: an LLM API router. CLI + assembly library.
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
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
//! Unified coding-agent **harness catalog** — the single source of truth for
//! how BitRouter finds, launches, and routes each supported harness.
//!
//! A harness is drivable in either of two facets:
//!
//! - **interactive** (`bro launch`) — the harness's own native TUI
//!   (`claude`, `codex`, `opencode`, `pi`, `hermes`, `openclaw`, `grok`,
//!   `agy`), launched as a child with its LLM traffic pointed at the daemon —
//!   by env/args where that suffices, otherwise through a synthesized config
//!   file ([`Harness::launch_overlay`]); the human drives it directly.
//! - **ACP** (`bro spawn`) — a headless ACP adapter
//!   (`@agentclientprotocol/claude-agent-acp`, …) driven as a sub-agent by a
//!   program.
//!
//! This module keeps the shared routing knowledge in one catalog. Interactive
//! launches render [`Routing`] through native CLI/config surfaces. Maintained
//! ACP adapters render a [`HarnessEndpointPlan`] through their documented
//! launch fallback and then apply that same plan through ACP provider setup;
//! other adapters retain the catalog's legacy env/args behavior.

/// BitRouter's own API-key env var (`brk_…`). When set, it is forwarded to the
/// harness as the gateway bearer credential.
pub const BITROUTER_API_KEY_ENV: &str = "BITROUTER_API_KEY";

/// Placeholder credential injected when no real key is available. Ignored by
/// the daemon under `skip_auth: true` (the `bro init` default); the
/// harness merely needs *some* credential to start.
pub const PLACEHOLDER_API_KEY: &str = "bitrouter-local";

use anyhow::Context;

/// One catalog harness. Keyed by [`id`](Self::id), which is the ACP-facet
/// id used under `agents:` in `bitrouter.yaml` and by `bro agents`.
#[derive(Debug, Clone, Copy)]
pub struct Harness {
    /// Catalog / ACP-config id (e.g. `claude-acp`). Also the `agents install`
    /// key.
    pub id: &'static str,
    /// One-line human description (shown in `agents list`).
    pub description: &'static str,
    /// Upstream project URL — the source of the recommended invocation.
    pub project_url: &'static str,
    /// The ACP major version this agent's registry entry declares. The
    /// conformance suite's handshake tier checks the negotiated version
    /// against it.
    pub acp_protocol_version: u32,
    /// The ACP adapter invocation (`command` + `args`) for `bro spawn`,
    /// when the harness has one. `None` for interactive-only harnesses
    /// (grok, antigravity) — they have no headless ACP adapter today.
    pub acp_command: Option<&'static str>,
    /// Args passed to [`acp_command`](Self::acp_command).
    pub acp_args: &'static [&'static str],
    /// A substring that identifies this harness inside a configured agent's
    /// invocation (command or any arg) — used to map a user-renamed
    /// `agents:` entry back to its catalog routing (invocation matching, so
    /// the YAML key carries no semantics). Usually the adapter package name.
    pub package_marker: &'static str,
    /// The interactive native-TUI binary for `bro launch`, when the
    /// harness has one. `None` for adapter-only harnesses (gemini).
    pub interactive_binary: Option<&'static str>,
    /// How this harness's LLM traffic is pointed at the daemon.
    pub routing: Routing,
}

/// How a harness's LLM traffic is redirected to the BitRouter gateway. One
/// value per harness, applied identically to both facets.
#[derive(Debug, Clone, Copy)]
pub enum Routing {
    /// Env-var redirection: set `base_url_env` to the gateway URL and
    /// `auth_env` to the bearer credential (BitRouter's inbound scheme is
    /// `Authorization: Bearer`; never a provider `x-api-key` var). Optional
    /// `model_env` pins the model; `extra` carries fixed vars the redirect
    /// needs. Used by claude-code-acp (and interactive Claude Code) and,
    /// best-effort, gemini-cli.
    Env {
        /// Var the harness reads its gateway base URL from.
        base_url_env: &'static str,
        /// Var the harness turns into the gateway credential.
        auth_env: &'static str,
        /// Whether the harness sends `auth_env` as `Authorization: Bearer`
        /// (BitRouter's inbound scheme). `false` means a provider-native
        /// header the daemon's auth hook rejects under `skip_auth: false`
        /// (e.g. gemini's `x-goog-api-key`) — routing then only works under
        /// `skip_auth: true`, and callers warn when auth is required.
        bearer_auth: bool,
        /// Var that pins the model, when the harness supports one.
        model_env: Option<&'static str>,
        /// Fixed vars required for the redirect to take effect.
        extra: &'static [(&'static str, &'static str)],
    },
    /// Codex `-c` one-shot config overrides (codex-acp forwards argv to codex
    /// core, so the same overrides work for both facets). The gateway must
    /// speak the OpenAI **Responses** API — pinned codex builds dropped
    /// `wire_api = "chat"`.
    CodexArgs,
    /// Config-file synthesis: the harness exposes neither a base-URL variable
    /// nor a CLI override, so routing writes a config into a per-launch
    /// directory and points the harness at it. The shape is registry data
    /// ([`crate::config_synthesis`]), which is why one variant covers
    /// opencode, pi, hermes and openclaw. There is no pure env/args overlay —
    /// headless spawn launches direct with a note; the interactive facet
    /// synthesizes via [`Harness::launch_overlay`].
    ConfigFile(&'static crate::config_synthesis::ConfigSynthesis),
    /// No gateway redirection, by design: the harness IS a subscription
    /// client whose session the daemon itself borrows as a provider (grok →
    /// `supergrok`, agy → `google-ai`) — routing it through the daemon would
    /// loop back to the same backend on the same credential. It launches
    /// with its own auth; `--model` forwards as the harness's native flag.
    OwnAuth,
}

/// The child-process overrides a [`Routing`] contributes: env vars to set
/// (injection wins over inherited/config env) and args to append to the
/// harness invocation.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RoutingOverlay {
    /// Env vars to set on the child (each overrides any inherited value).
    pub env: Vec<(String, String)>,
    /// Args appended to the harness invocation.
    pub args: Vec<String>,
}

/// Wire protocol advertised to an ACP adapter through its provider endpoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HarnessProtocol {
    /// Anthropic Messages-compatible endpoint.
    Anthropic,
    /// OpenAI Responses-compatible endpoint.
    OpenAi,
}

impl HarnessProtocol {
    /// ACP provider protocol identifier.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Anthropic => "anthropic",
            Self::OpenAi => "openai",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EndpointFallback {
    Claude,
    Codex,
}

/// Process-scoped BitRouter endpoint configuration for a maintained ACP
/// adapter.
///
/// The controller applies this plan through ACP provider configuration when
/// the adapter advertises that capability. [`Self::fallback_overlay`] renders
/// the same plan through the adapter's documented environment fallback, so a
/// pinned adapter that loses provider support still routes deterministically.
#[derive(Clone, PartialEq, Eq)]
pub struct HarnessEndpointPlan {
    /// Catalog harness id included in every routed request.
    pub harness_id: &'static str,
    /// Exact upstream adapter package.
    pub adapter_package: &'static str,
    /// Exact upstream adapter version.
    pub adapter_version: &'static str,
    /// Adapter-native provider id selected through ACP.
    pub provider_id: &'static str,
    /// Model API protocol exposed by BitRouter for this adapter.
    pub protocol: HarnessProtocol,
    /// Adapter-facing endpoint base URL.
    pub base_url: String,
    /// Optional logical model pin.
    pub model: Option<String>,
    /// HTTP headers passed to the adapter endpoint. Names are canonicalized
    /// to lower case so observability and routing parse one stable shape.
    pub headers: std::collections::BTreeMap<String, String>,
    auth: String,
    fallback: EndpointFallback,
}

impl std::fmt::Debug for HarnessEndpointPlan {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("HarnessEndpointPlan")
            .field("harness_id", &self.harness_id)
            .field("adapter_package", &self.adapter_package)
            .field("adapter_version", &self.adapter_version)
            .field("provider_id", &self.provider_id)
            .field("protocol", &self.protocol)
            .field("base_url", &self.base_url)
            .field("model", &self.model)
            .field("header_names", &self.headers.keys().collect::<Vec<_>>())
            .field("auth", &"[REDACTED]")
            .field("fallback", &self.fallback)
            .finish()
    }
}

impl HarnessEndpointPlan {
    /// Render the documented process-environment fallback for this exact
    /// adapter version. No routing configuration is added to adapter argv.
    pub fn fallback_overlay(&self) -> anyhow::Result<RoutingOverlay> {
        let static_headers = self
            .headers
            .iter()
            .filter(|(name, _)| name.as_str() != "authorization")
            .map(|(name, value)| (name.clone(), value.clone()))
            .collect::<std::collections::BTreeMap<_, _>>();

        match self.fallback {
            EndpointFallback::Claude => {
                let mut env = vec![
                    ("ANTHROPIC_BASE_URL".to_string(), self.base_url.clone()),
                    ("ANTHROPIC_AUTH_TOKEN".to_string(), self.auth.clone()),
                    (
                        "ANTHROPIC_CUSTOM_HEADERS".to_string(),
                        static_headers
                            .iter()
                            .map(|(name, value)| format!("{name}: {value}"))
                            .collect::<Vec<_>>()
                            .join("\n"),
                    ),
                ];
                if let Some(model) = &self.model {
                    env.push(("ANTHROPIC_MODEL".to_string(), model.clone()));
                }
                Ok(RoutingOverlay {
                    env,
                    args: Vec::new(),
                })
            }
            EndpointFallback::Codex => {
                let provider = serde_json::json!({
                    "name": "BitRouter",
                    "base_url": self.base_url,
                    "wire_api": "responses",
                    "env_key": BITROUTER_API_KEY_ENV,
                    "http_headers": static_headers,
                });
                let mut config = serde_json::json!({
                    "model_provider": "bitrouter",
                    "model_providers": { "bitrouter": provider },
                });
                if let Some(model) = &self.model {
                    config["model"] = serde_json::Value::String(model.clone());
                }
                let encoded = serde_json::to_string(&config)
                    .context("serializing the Codex ACP endpoint fallback")?;
                Ok(RoutingOverlay {
                    env: vec![
                        (BITROUTER_API_KEY_ENV.to_string(), self.auth.clone()),
                        ("CODEX_CONFIG".to_string(), encoded),
                        ("MODEL_PROVIDER".to_string(), "bitrouter".to_string()),
                    ],
                    args: Vec::new(),
                })
            }
        }
    }
}

// The ACP half of the catalog, generated by `build.rs` from
// `dist/registry/agents.json`. Adding or changing an ACP agent is a PR against
// `registry/`, not against this file.
include!(concat!(env!("OUT_DIR"), "/catalog_generated.rs"));

/// Every supported harness speaks ACP. Native subscription clients may still
/// supply provider credentials, but are not agent entries.
pub static CATALOG: &[Harness] = ACP_CATALOG;

/// Look up a harness by its catalog id.
pub fn by_id(id: &str) -> Option<&'static Harness> {
    CATALOG.iter().find(|h| h.id == id)
}

/// Look up a harness by its interactive binary name (`launch` uses this to
/// share the ACP-side routing knowledge).
pub fn by_interactive_binary(binary: &str) -> Option<&'static Harness> {
    CATALOG
        .iter()
        .find(|h| h.interactive_binary == Some(binary))
}

/// Match a configured agent's invocation back to a catalog harness by its
/// [`package_marker`](Harness::package_marker), so routing follows the
/// *invocation*, not the user-chosen YAML key. Checks the command and every
/// arg for the marker substring.
pub fn match_invocation(command: &str, args: &[String]) -> Option<&'static Harness> {
    let catalog_match = CATALOG.iter().find(|h| {
        command.contains(h.package_marker) || args.iter().any(|a| a.contains(h.package_marker))
    });
    catalog_match.or_else(|| {
        let legacy_claude = command.contains("claude-code-acp")
            || args.iter().any(|arg| arg.contains("claude-code-acp"));
        if legacy_claude {
            by_id("claude-acp")
        } else {
            None
        }
    })
}

impl Harness {
    /// Exact maintained ACP adapter identity for controller diagnostics.
    ///
    /// `None` means the catalog entry has no pinned, provider-configurable ACP
    /// adapter contract yet. Callers must identify such invocations as
    /// configured/custom rather than attributing them to a maintained pin.
    pub fn maintained_adapter_identity(&self) -> Option<(&'static str, &'static str)> {
        match self.id {
            "claude-acp" => Some(("@agentclientprotocol/claude-agent-acp", "0.75.1")),
            "codex-acp" => Some(("@agentclientprotocol/codex-acp", "1.10.0")),
            _ => None,
        }
    }

    /// Whether a configured invocation uses this catalog entry's exact
    /// maintained adapter pin.
    pub fn uses_maintained_adapter(&self, command: &str, args: &[String]) -> bool {
        let Some((package, version)) = self.maintained_adapter_identity() else {
            return false;
        };
        let exact = format!("{package}@{version}");
        command == exact || args.iter().any(|arg| arg == &exact)
    }

    /// Build the controller's process-scoped endpoint plan for a maintained
    /// ACP adapter. Other catalog entries keep their existing launch routing
    /// until their provider contracts are pinned and tested.
    pub fn endpoint_plan(
        &self,
        base_url: &str,
        auth: &str,
        model: Option<&str>,
        controller_id: &str,
    ) -> Option<HarnessEndpointPlan> {
        let mut headers = std::collections::BTreeMap::from([
            ("authorization".to_string(), format!("Bearer {auth}")),
            (
                "x-bitrouter-controller-id".to_string(),
                controller_id.to_string(),
            ),
            ("x-bitrouter-harness".to_string(), self.id.to_string()),
        ]);
        // Keep construction explicit: any future header added here becomes a
        // reviewed part of the router/controller contract.
        headers.retain(|name, value| !name.is_empty() && !value.is_empty());

        let (adapter_package, adapter_version) = self.maintained_adapter_identity()?;
        let (provider_id, protocol, base_url, fallback) = match self.id {
            "claude-acp" => (
                "main",
                HarnessProtocol::Anthropic,
                base_url.trim_end_matches('/').to_string(),
                EndpointFallback::Claude,
            ),
            "codex-acp" => (
                "openai",
                HarnessProtocol::OpenAi,
                v1_base_url(base_url),
                EndpointFallback::Codex,
            ),
            _ => return None,
        };

        Some(HarnessEndpointPlan {
            harness_id: self.id,
            adapter_package,
            adapter_version,
            provider_id,
            protocol,
            base_url,
            model: model.map(str::to_string),
            headers,
            auth: auth.to_string(),
            fallback,
        })
    }

    /// Compute the child-process overlay that routes this harness's LLM
    /// traffic through `base_url`, authenticating with `auth` (already
    /// resolved by precedence — see [`resolve_gateway_auth`]). `model` pins
    /// the model when the harness supports it. Returns an empty overlay for
    /// harnesses env/args can't route ([`ConfigFile`](Routing::ConfigFile) /
    /// [`OwnAuth`](Routing::OwnAuth)
    /// — the caller warns and runs direct; see [`env_args_routable`](Self::env_args_routable)).
    pub fn routing_overlay(
        &self,
        base_url: &str,
        auth: &str,
        model: Option<&str>,
    ) -> RoutingOverlay {
        match &self.routing {
            Routing::Env {
                base_url_env,
                auth_env,
                model_env,
                extra,
                ..
            } => {
                let mut env = vec![
                    ((*base_url_env).to_string(), base_url.to_string()),
                    ((*auth_env).to_string(), auth.to_string()),
                ];
                for (k, v) in *extra {
                    env.push(((*k).to_string(), (*v).to_string()));
                }
                if let (Some(var), Some(m)) = (model_env, model) {
                    env.push(((*var).to_string(), m.to_string()));
                }
                RoutingOverlay {
                    env,
                    args: Vec::new(),
                }
            }
            Routing::CodexArgs => codex_overlay(base_url, auth, model),
            // Config-synthesis harnesses have no pure env/args overlay —
            // callers that can't synthesize launch direct (and say so) —
            // and own-auth harnesses are never redirected at all.
            Routing::ConfigFile(_) | Routing::OwnAuth => RoutingOverlay::default(),
        }
    }

    /// Pin only the model while preserving the agent's own provider and
    /// subscription authority. Used by explicitly direct ACP sessions.
    pub fn direct_model_overlay(&self, model: &str) -> RoutingOverlay {
        match &self.routing {
            Routing::Env {
                model_env: Some(model_env),
                ..
            } => RoutingOverlay {
                env: vec![((*model_env).to_string(), model.to_string())],
                args: Vec::new(),
            },
            Routing::CodexArgs => RoutingOverlay {
                env: Vec::new(),
                args: vec!["-c".to_string(), codex_config_string("model", model)],
            },
            Routing::Env {
                model_env: None, ..
            }
            | Routing::ConfigFile(_)
            | Routing::OwnAuth => RoutingOverlay::default(),
        }
    }

    /// Whether this harness routes through pure env/args injection (the
    /// headless-spawn facet). Config-synthesis harnesses (opencode, pi)
    /// route only through [`Self::launch_overlay`] — headless callers launch
    /// them direct
    /// with a note.
    pub fn env_args_routable(&self) -> bool {
        matches!(self.routing, Routing::Env { .. } | Routing::CodexArgs)
    }

    /// Whether the harness sends its gateway credential as `Authorization:
    /// Bearer` (BitRouter's inbound scheme). `false` means a provider-native
    /// header the daemon rejects under `skip_auth: false` (gemini). Codex's
    /// `env_key` path is Bearer, so non-`Env` routings are bearer-compatible.
    pub fn auth_is_bearer(&self) -> bool {
        match self.routing {
            Routing::Env { bearer_auth, .. } => bearer_auth,
            _ => true,
        }
    }

    /// Whether `--model` can be applied to this harness on the pure
    /// env/args path (the headless-spawn / direct-pin facet). Config-synthesis
    /// harnesses pin their model through [`Self::launch_overlay`] instead, so
    /// an interactive caller must
    /// not read this as "cannot pin".
    pub fn supports_model_pin(&self) -> bool {
        match self.routing {
            Routing::Env { model_env, .. } => model_env.is_some(),
            Routing::CodexArgs => true,
            Routing::ConfigFile(_) | Routing::OwnAuth => false,
        }
    }

    /// Whether `bro launch` will run this harness: exactly those with an
    /// [`interactive_binary`](Self::interactive_binary).
    ///
    /// The cut to four ids was made when `launch` also promised a *hosted
    /// terminal*, and that promise was the expensive one — an emulator has to
    /// be verified per harness against upstream releases nobody here controls.
    /// With hosting gone `launch` promises only what the overlay already gives
    /// every interactive entry in the catalog: it execs the binary with the
    /// routing overlay applied, and states before handover what the harness
    /// actually got (see [`Self::injects_mcp`], which is a real per-harness
    /// ceiling and stays one).
    ///
    /// `grok` and `agy` are launchable *and* remain **providers** — the daemon
    /// borrows their subscription sessions to serve other requests. Their own
    /// traffic is unrouted and unmetered, which the startup line says.
    pub fn launch_supported(&self) -> bool {
        self.interactive_binary.is_some()
    }

    /// Whether [`Self::launch_overlay`] can inject MCP servers (the
    /// `bitrouter_tools` gateway) into this harness.
    ///
    /// This is a *ceiling of the harness*, not of BitRouter: `pi` and
    /// `openclaw` expose no MCP mechanism to inject into, and the own-auth
    /// clients are not routed at all. `launch` states it before handover so a
    /// user does not discover the gap when the tools simply aren't there.
    ///
    /// Kept in lockstep with `launch_overlay` by
    /// `injects_mcp_matches_the_launch_overlay` — the predicate is declarative,
    /// and the test proves it agrees with what the overlay actually does.
    pub fn injects_mcp(&self) -> bool {
        match &self.routing {
            // Whether a synthesized config has somewhere to put MCP servers is
            // part of its registry shape, so this follows the data.
            Routing::ConfigFile(synthesis) => {
                !matches!(synthesis.mcp, crate::config_synthesis::McpShape::None)
            }
            // claude's `--mcp-config` file and codex's `-c mcp_servers.*`
            // overrides are compiled MCP injection layered on env/args
            // routing, so they stay named here.
            Routing::Env { .. } | Routing::CodexArgs => {
                matches!(self.id, "claude-acp" | "codex-acp")
            }
            Routing::OwnAuth => false,
        }
    }

    /// This harness's config-file synthesis, when routing uses one.
    pub fn config_synthesis(&self) -> Option<&'static crate::config_synthesis::ConfigSynthesis> {
        match self.routing {
            Routing::ConfigFile(synthesis) => Some(synthesis),
            _ => None,
        }
    }

    /// Interactive-launch overlay (`bro launch`): the full routing
    /// overlay for *any* interactive harness — including the ones env/args
    /// cannot route, whose config files are synthesized under `state_dir`
    /// (opencode's `OPENCODE_CONFIG`, pi's `PI_CODING_AGENT_DIR`, hermes's
    /// `HERMES_HOME`, openclaw's profile) — plus injection of the `mcp`
    /// gateway servers, where the harness has an MCP mechanism.
    ///
    /// `catalog` is the daemon's advertised model ids; it fills the
    /// synthesized providers' model lists so the harness's own model picker
    /// shows what the daemon can serve. `model` pins the model (and becomes
    /// the synthesized default); when absent, the first catalog entry is the
    /// default. Own-auth harnesses (grok, agy) are never redirected — they
    /// only get `--model` as their native flag.
    ///
    /// MCP injection rides the *same* synthesized artifact as routing for the
    /// config-file harnesses (one `OPENCODE_CONFIG` JSON, one
    /// `HERMES_HOME/config.yaml`), so the two facets cannot be layered into
    /// separate methods — an empty `mcp` is simply a launch with no gateways.
    /// `pi`, `openclaw`, `grok`, and `antigravity` have no injectable MCP
    /// mechanism at all and ignore `mcp` entirely.
    pub fn launch_overlay(
        &self,
        base_url: &str,
        auth: &str,
        model: Option<&str>,
        catalog: &[String],
        mcp: &[McpServer],
        state_dir: &std::path::Path,
    ) -> anyhow::Result<RoutingOverlay> {
        // Harnesses that env/args cannot route synthesize a config file. The
        // shape rides the routing itself, as registry data; the rendered bytes
        // are pinned by `rendered_config_bytes_match_the_golden_fixtures`.
        if let Routing::ConfigFile(synthesis) = &self.routing {
            return synthesis.render(base_url, auth, model, catalog, mcp, state_dir);
        }
        match self.id {
            // Claude Code loads extra MCP servers from `--mcp-config <file>`.
            // Stdio entries are `{command, args}`; HTTP entries need an
            // explicit `"type": "http"` (a `url` without `type` is a hard
            // error) plus a `headers` object.
            "claude-acp" => {
                let mut overlay = self.routing_overlay(base_url, auth, model);
                if !mcp.is_empty() {
                    std::fs::create_dir_all(state_dir)
                        .with_context(|| format!("creating {}", state_dir.display()))?;
                    let path = state_dir.join("mcp.json");
                    let mut servers = serde_json::Map::new();
                    for s in mcp {
                        let entry = match &s.transport {
                            McpTransport::Stdio { command, args } => {
                                serde_json::json!({ "command": command, "args": args })
                            }
                            McpTransport::Http { url, headers } => serde_json::json!({
                                "type": "http",
                                "url": url,
                                "headers": headers_map(headers),
                            }),
                        };
                        servers.insert(s.name.clone(), entry);
                    }
                    let config = serde_json::json!({ "mcpServers": servers });
                    std::fs::write(&path, serde_json::to_string_pretty(&config)?)
                        .context("writing claude MCP config")?;
                    overlay
                        .args
                        .extend(["--mcp-config".to_string(), path.display().to_string()]);
                }
                Ok(overlay)
            }
            // codex takes MCP servers as `-c mcp_servers.*` TOML overrides.
            // `url` presence selects the streamable-HTTP transport (codex
            // 0.144+); auth rides `http_headers.<Name>` overrides.
            "codex-acp" => {
                let mut overlay = self.routing_overlay(base_url, auth, model);
                for s in mcp {
                    match &s.transport {
                        McpTransport::Stdio { command, args } => {
                            let items: Vec<String> = args.iter().map(|a| toml_string(a)).collect();
                            overlay.args.extend([
                                "-c".to_string(),
                                format!("mcp_servers.{}.command={}", s.name, toml_string(command)),
                                "-c".to_string(),
                                format!("mcp_servers.{}.args=[{}]", s.name, items.join(",")),
                            ]);
                        }
                        McpTransport::Http { url, headers } => {
                            overlay.args.extend([
                                "-c".to_string(),
                                format!("mcp_servers.{}.url={}", s.name, toml_string(url)),
                            ]);
                            for (name, value) in headers {
                                overlay.args.extend([
                                    "-c".to_string(),
                                    format!(
                                        "mcp_servers.{}.http_headers.{}={}",
                                        s.name,
                                        name,
                                        toml_string(value)
                                    ),
                                ]);
                            }
                        }
                    }
                }
                Ok(overlay)
            }
            // Own-auth harnesses (grok, agy): no redirection, no MCP
            // mechanism we can inject non-invasively — hosted with their own
            // subscription auth; `--model` forwards as their native flag.
            "grok" => Ok(RoutingOverlay {
                env: Vec::new(),
                args: model
                    .map(|m| vec!["-m".to_string(), m.to_string()])
                    .unwrap_or_default(),
            }),
            "antigravity" => Ok(RoutingOverlay {
                env: Vec::new(),
                args: model
                    .map(|m| vec!["--model".to_string(), m.to_string()])
                    .unwrap_or_default(),
            }),
            // Unknown interactive harness: routing only, no MCP mechanism.
            _ => Ok(self.routing_overlay(base_url, auth, model)),
        }
    }
}

/// An MCP server to inject into a launched harness — the gateway servers
/// (`bitrouter_tools`, see `crate::gateways`).
#[derive(Debug, Clone)]
pub struct McpServer {
    /// Server name as the harness will list it (e.g. `bitrouter_tools`).
    pub name: String,
    /// How the harness dials it.
    pub transport: McpTransport,
}

/// How a harness dials an injected MCP server. Headers are an ordered list
/// (not a map) so synthesized configs and `-c` overrides stay deterministic.
#[derive(Debug, Clone)]
pub enum McpTransport {
    /// Spawn `command` with `args` and exchange JSON-RPC over stdio.
    Stdio { command: String, args: Vec<String> },
    /// Streamable HTTP at `url`, sending the static request `headers`
    /// (e.g. `Authorization`) on every call.
    Http {
        url: String,
        headers: Vec<(String, String)>,
    },
}

/// Render ordered header pairs as the JSON object shape harness config files
/// expect (`{"Authorization": "Bearer …"}`).
pub(crate) fn headers_map(
    headers: &[(String, String)],
) -> serde_json::Map<String, serde_json::Value> {
    headers
        .iter()
        .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
        .collect()
}

/// Resolve the gateway credential by precedence: a real `BITROUTER_API_KEY`
/// (`brk_…`) when exported, else the local placeholder. Returns `None` only
/// when `require_key` is set (daemon auth is on) and no real key is present —
/// the caller then fails fast (`SPAWN_SPEC` §5.4).
pub fn resolve_gateway_auth(bitrouter_key: Option<String>, require_key: bool) -> Option<String> {
    match bitrouter_key {
        Some(key) => Some(key),
        None if require_key => None,
        None => Some(PLACEHOLDER_API_KEY.to_string()),
    }
}

/// The Codex `-c` provider-override overlay. Mirrors the interactive
/// `bro launch` codex wiring so both facets route identically.
fn codex_overlay(base_url: &str, auth: &str, model: Option<&str>) -> RoutingOverlay {
    let mut env = Vec::new();
    let mut args = vec![
        "-c".to_string(),
        codex_config_string("model_provider", "bitrouter"),
        "-c".to_string(),
        codex_config_string("model_providers.bitrouter.name", "BitRouter"),
        "-c".to_string(),
        codex_config_string("model_providers.bitrouter.base_url", &v1_base_url(base_url)),
        "-c".to_string(),
        codex_config_string("model_providers.bitrouter.wire_api", "responses"),
    ];

    // Real key → env_key indirection (keeps the secret out of argv/process
    // listing); placeholder → inline experimental_bearer_token.
    if auth == PLACEHOLDER_API_KEY {
        args.push("-c".to_string());
        args.push(codex_config_string(
            "model_providers.bitrouter.experimental_bearer_token",
            PLACEHOLDER_API_KEY,
        ));
    } else {
        env.push((BITROUTER_API_KEY_ENV.to_string(), auth.to_string()));
        args.push("-c".to_string());
        args.push(codex_config_string(
            "model_providers.bitrouter.env_key",
            BITROUTER_API_KEY_ENV,
        ));
    }

    if let Some(m) = model {
        args.push("-c".to_string());
        args.push(codex_config_string("model", m));
    }

    RoutingOverlay { env, args }
}

/// `/v1`-suffixed base URL — the shape codex custom providers, opencode's
/// openai-compatible provider, and pi's `baseUrl` all expect.
pub(crate) fn v1_base_url(base_url: &str) -> String {
    let trimmed = base_url.trim_end_matches('/');
    if trimmed.ends_with("/v1") {
        trimmed.to_string()
    } else {
        format!("{trimmed}/v1")
    }
}

fn codex_config_string(key: &str, value: &str) -> String {
    format!("{key}={}", toml_string(value))
}

/// Quote a value as a TOML basic string for a `-c key=value` override.
fn toml_string(value: &str) -> String {
    let mut out = String::with_capacity(value.len() + 2);
    out.push('"');
    for ch in value.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            other => out.push(other),
        }
    }
    out.push('"');
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(serde::Deserialize)]
    #[serde(rename_all = "camelCase")]
    struct AdapterContract {
        harness_id: String,
        package: String,
        version: String,
        git_head: String,
        provider_id: String,
        protocol: String,
        fallback_env: Vec<String>,
        native_identity_headers: Vec<String>,
    }

    fn adapter_contracts() -> anyhow::Result<Vec<AdapterContract>> {
        Ok(vec![
            serde_json::from_str(include_str!(
                "../tests/fixtures/acp_adapters/claude-agent-acp-0.75.1.json"
            ))?,
            serde_json::from_str(include_str!(
                "../tests/fixtures/acp_adapters/codex-acp-1.10.0.json"
            ))?,
        ])
    }

    // ===== the registry/catalog split (AGENT_REGISTRY_SPEC §13) =====
    //
    // `ACP_CATALOG` is generated from `dist/registry/agents.json`, so a test
    // comparing the two would only prove that `build.rs` ran. What is worth
    // pinning is the invariant the split rests on: registry membership follows
    // having an ACP adapter, and the harnesses held back are exactly the ones
    // with nothing to route.

    #[test]
    fn registry_membership_follows_having_an_acp_adapter() {
        // Non-vacuity: a `build.rs` that silently emitted nothing would
        // otherwise satisfy everything below.
        // Non-vacuity only — deliberately not a count, so retiring an agent
        // stays a registry-only change.
        assert!(
            !ACP_CATALOG.is_empty(),
            "the generated catalog is empty — did build.rs read dist/registry?"
        );
        for harness in ACP_CATALOG {
            assert!(
                harness.acp_command.is_some(),
                "{}: a registry agent must have an ACP invocation",
                harness.id
            );
        }
        assert!(by_id("grok").is_none());
        assert!(by_id("antigravity").is_none());
    }

    #[test]
    fn config_file_routing_reaches_its_synthesis_through_the_catalog() {
        // The four synthesized harnesses carry their shape as registry data,
        // so the routing itself is the lookup — there is no id table left.
        for id in ["opencode", "pi-acp", "hermes-acp", "openclaw"] {
            let harness = by_id(id).expect("catalog entry");
            let synthesis = harness
                .config_synthesis()
                .unwrap_or_else(|| panic!("{id} should route through a config file"));
            assert!(
                !synthesis.file.is_empty(),
                "{id} synthesis names no config file"
            );
        }
        assert!(
            by_id("claude-acp")
                .expect("catalog")
                .config_synthesis()
                .is_none()
        );
    }

    #[test]
    fn catalog_ids_are_unique() {
        let mut ids: Vec<_> = CATALOG.iter().map(|h| h.id).collect();
        ids.sort_unstable();
        let before = ids.len();
        ids.dedup();
        assert_eq!(before, ids.len(), "catalog ids must be unique");
    }

    #[test]
    fn maintained_acp_adapters_are_exactly_pinned() -> anyhow::Result<()> {
        let claude = by_id("claude-acp")
            .ok_or_else(|| anyhow::anyhow!("claude-acp missing from catalog"))?;
        assert_eq!(
            claude.acp_args,
            &["-y", "@agentclientprotocol/claude-agent-acp@0.75.1"]
        );
        assert_eq!(
            claude.project_url,
            "https://github.com/agentclientprotocol/claude-agent-acp"
        );
        assert_eq!(claude.package_marker, "claude-agent-acp");

        let codex =
            by_id("codex-acp").ok_or_else(|| anyhow::anyhow!("codex-acp missing from catalog"))?;
        assert_eq!(
            codex.acp_args,
            &["-y", "@agentclientprotocol/codex-acp@1.10.0"]
        );
        Ok(())
    }

    #[test]
    fn maintained_provider_contract_requires_the_exact_invocation_pin() -> anyhow::Result<()> {
        let claude = by_id("claude-acp")
            .ok_or_else(|| anyhow::anyhow!("claude-acp missing from catalog"))?;
        assert!(claude.uses_maintained_adapter(
            "npx",
            &["@agentclientprotocol/claude-agent-acp@0.75.1".to_string()]
        ));
        assert!(!claude.uses_maintained_adapter(
            "npx",
            &["@agentclientprotocol/claude-agent-acp@0.69.0".to_string()]
        ));
        assert!(!claude.uses_maintained_adapter(
            "npx",
            &["@agentclientprotocol/claude-agent-acp@0.75.1-tampered".to_string()]
        ));
        assert!(!claude.uses_maintained_adapter(
            "npx",
            &["@zed-industries/claude-code-acp@latest".to_string()]
        ));
        Ok(())
    }

    #[test]
    fn endpoint_plan_matches_the_pinned_adapter_contracts() -> anyhow::Result<()> {
        for contract in adapter_contracts()? {
            let harness = by_id(&contract.harness_id)
                .ok_or_else(|| anyhow::anyhow!("missing harness {}", contract.harness_id))?;
            let plan = harness
                .endpoint_plan(
                    "http://127.0.0.1:4356/",
                    "brk_test",
                    Some("logical/model"),
                    "controller-test",
                )
                .ok_or_else(|| anyhow::anyhow!("missing endpoint plan"))?;

            assert_eq!(plan.provider_id, contract.provider_id);
            assert_eq!(plan.protocol.as_str(), contract.protocol);
            assert_eq!(plan.model.as_deref(), Some("logical/model"));
            assert_eq!(
                plan.headers.get("authorization").map(String::as_str),
                Some("Bearer brk_test")
            );
            assert_eq!(
                plan.headers
                    .get("x-bitrouter-controller-id")
                    .map(String::as_str),
                Some("controller-test")
            );
            assert_eq!(
                plan.headers.get("x-bitrouter-harness").map(String::as_str),
                Some(contract.harness_id.as_str())
            );

            let package_spec = format!("{}@{}", contract.package, contract.version);
            assert!(harness.acp_args.contains(&package_spec.as_str()));
            assert_eq!(contract.git_head.len(), 40);
            assert!(!contract.native_identity_headers.is_empty());
        }
        Ok(())
    }

    #[test]
    fn endpoint_plan_renders_documented_adapter_fallbacks() -> anyhow::Result<()> {
        for contract in adapter_contracts()? {
            let harness = by_id(&contract.harness_id)
                .ok_or_else(|| anyhow::anyhow!("missing harness {}", contract.harness_id))?;
            let plan = harness
                .endpoint_plan(
                    "http://127.0.0.1:4356",
                    "brk_test",
                    Some("logical/model"),
                    "controller-test",
                )
                .ok_or_else(|| anyhow::anyhow!("missing endpoint plan"))?;
            let overlay = plan.fallback_overlay()?;
            let env: std::collections::HashMap<_, _> = overlay.env.into_iter().collect();

            for key in contract.fallback_env {
                assert!(
                    env.contains_key(&key),
                    "{} missing {key}",
                    contract.harness_id
                );
            }
            assert!(
                overlay.args.is_empty(),
                "{} used ACP CLI args",
                contract.harness_id
            );

            match contract.harness_id.as_str() {
                "claude-acp" => {
                    assert_eq!(
                        env.get("ANTHROPIC_BASE_URL").map(String::as_str),
                        Some("http://127.0.0.1:4356")
                    );
                    let custom = env
                        .get("ANTHROPIC_CUSTOM_HEADERS")
                        .ok_or_else(|| anyhow::anyhow!("missing Claude custom headers"))?;
                    assert!(custom.contains("x-bitrouter-controller-id: controller-test"));
                    assert!(custom.contains("x-bitrouter-harness: claude-acp"));
                    assert!(!custom.to_ascii_lowercase().contains("authorization"));
                }
                "codex-acp" => {
                    assert_eq!(
                        env.get("MODEL_PROVIDER").map(String::as_str),
                        Some("bitrouter")
                    );
                    let config: serde_json::Value = serde_json::from_str(
                        env.get("CODEX_CONFIG")
                            .ok_or_else(|| anyhow::anyhow!("missing Codex config"))?,
                    )?;
                    assert_eq!(config["model_provider"], "bitrouter");
                    assert_eq!(
                        config["model_providers"]["bitrouter"]["base_url"],
                        "http://127.0.0.1:4356/v1"
                    );
                    assert_eq!(
                        config["model_providers"]["bitrouter"]["wire_api"],
                        "responses"
                    );
                    assert_eq!(config["model"], "logical/model");
                }
                other => return Err(anyhow::anyhow!("unexpected contract {other}")),
            }
        }
        Ok(())
    }

    #[test]
    fn by_interactive_binary_finds_the_launchable_harnesses() {
        assert_eq!(by_interactive_binary("claude").unwrap().id, "claude-acp");
        assert_eq!(by_interactive_binary("codex").unwrap().id, "codex-acp");
        assert_eq!(by_interactive_binary("opencode").unwrap().id, "opencode");
        assert_eq!(by_interactive_binary("pi").unwrap().id, "pi-acp");
        assert_eq!(by_interactive_binary("hermes").unwrap().id, "hermes-acp");
        assert_eq!(by_interactive_binary("openclaw").unwrap().id, "openclaw");
        assert!(by_interactive_binary("grok").is_none());
        assert!(by_interactive_binary("agy").is_none());
        assert!(by_interactive_binary("gemini").is_none());
    }

    #[test]
    fn match_invocation_maps_renamed_key_by_package_marker() {
        // A user-renamed entry ("my-claude") still maps to claude-acp routing.
        let h = match_invocation(
            "npx",
            &[
                "-y".to_string(),
                "@agentclientprotocol/claude-agent-acp@0.75.1".to_string(),
            ],
        )
        .expect("matches claude-acp");
        assert_eq!(h.id, "claude-acp");
    }

    #[test]
    fn match_invocation_keeps_legacy_claude_adapter_configs_routable() -> anyhow::Result<()> {
        let harness = match_invocation(
            "npx",
            &[
                "-y".to_string(),
                "@zed-industries/claude-code-acp@latest".to_string(),
            ],
        )
        .ok_or_else(|| anyhow::anyhow!("legacy Claude adapter no longer catalog-matches"))?;
        assert_eq!(harness.id, "claude-acp");
        Ok(())
    }

    #[test]
    fn endpoint_plan_debug_redacts_credentials() -> anyhow::Result<()> {
        let harness =
            by_id("codex-acp").ok_or_else(|| anyhow::anyhow!("codex-acp missing from catalog"))?;
        let plan = harness
            .endpoint_plan("http://127.0.0.1:4356", "brk_secret", None, "brc_test")
            .ok_or_else(|| anyhow::anyhow!("Codex endpoint plan missing"))?;
        let debug = format!("{plan:?}");
        assert!(!debug.contains("brk_secret"), "credential leaked: {debug}");
        assert!(debug.contains("[REDACTED]"));
        Ok(())
    }

    #[test]
    fn match_invocation_none_for_unknown_command() {
        assert!(match_invocation("./my-custom-agent", &[]).is_none());
    }

    #[test]
    fn match_invocation_matches_globally_installed_binary_command() {
        // A `command: claude-agent-acp` (npm -g binary) must catalog-match the
        // same as the pinned npx package form.
        assert_eq!(
            match_invocation("claude-agent-acp", &[]).unwrap().id,
            "claude-acp"
        );
        assert_eq!(
            match_invocation("gemini-cli", &[]).unwrap().id,
            "gemini-cli"
        );
        assert_eq!(match_invocation("codex-acp", &[]).unwrap().id, "codex-acp");
    }

    #[test]
    fn catalog_markers_are_mutually_non_substrings() {
        // A false-positive would mis-route one harness as another.
        for a in CATALOG.iter() {
            for b in CATALOG.iter() {
                if a.id != b.id {
                    assert!(
                        !a.package_marker.contains(b.package_marker),
                        "marker '{}' contains '{}'",
                        a.package_marker,
                        b.package_marker
                    );
                }
            }
        }
    }

    #[test]
    fn auth_is_bearer_flags_gemini_as_non_bearer() {
        assert!(by_id("claude-acp").unwrap().auth_is_bearer());
        assert!(by_id("codex-acp").unwrap().auth_is_bearer());
        assert!(!by_id("gemini-cli").unwrap().auth_is_bearer());
    }

    #[test]
    fn supports_model_pin_reflects_catalog() {
        assert!(by_id("claude-acp").unwrap().supports_model_pin());
        assert!(by_id("codex-acp").unwrap().supports_model_pin());
        assert!(by_id("gemini-cli").unwrap().supports_model_pin());
        assert!(!by_id("pi-acp").unwrap().supports_model_pin());
    }

    #[test]
    fn claude_overlay_sets_base_url_and_bearer_token() {
        let h = by_id("claude-acp").unwrap();
        let o = h.routing_overlay("http://127.0.0.1:4356", "brk_real", None);
        assert!(o.env.contains(&(
            "ANTHROPIC_BASE_URL".to_string(),
            "http://127.0.0.1:4356".to_string()
        )));
        assert!(
            o.env
                .contains(&("ANTHROPIC_AUTH_TOKEN".to_string(), "brk_real".to_string()))
        );
        // Never the x-api-key var.
        assert!(o.env.iter().all(|(k, _)| k != "ANTHROPIC_API_KEY"));
        assert!(o.args.is_empty());
    }

    #[test]
    fn claude_overlay_pins_model_when_given() {
        let h = by_id("claude-acp").unwrap();
        let o = h.routing_overlay("http://x:1", "t", Some("claude-sonnet-5"));
        assert!(
            o.env
                .contains(&("ANTHROPIC_MODEL".to_string(), "claude-sonnet-5".to_string()))
        );
        // Absent when no model requested.
        let o2 = h.routing_overlay("http://x:1", "t", None);
        assert!(o2.env.iter().all(|(k, _)| k != "ANTHROPIC_MODEL"));
    }

    #[test]
    fn codex_overlay_routes_responses_to_v1_and_uses_env_key_for_real_key() {
        let h = by_id("codex-acp").unwrap();
        let o = h.routing_overlay("http://127.0.0.1:4356", "brk_real", None);
        assert!(o.args.contains(&"model_provider=\"bitrouter\"".to_string()));
        assert!(o.args.contains(
            &"model_providers.bitrouter.base_url=\"http://127.0.0.1:4356/v1\"".to_string()
        ));
        assert!(
            o.args
                .contains(&"model_providers.bitrouter.wire_api=\"responses\"".to_string())
        );
        assert!(
            o.args
                .contains(&"model_providers.bitrouter.env_key=\"BITROUTER_API_KEY\"".to_string())
        );
        assert!(
            o.env
                .contains(&("BITROUTER_API_KEY".to_string(), "brk_real".to_string()))
        );
        assert!(
            o.args
                .iter()
                .all(|a| !a.contains("experimental_bearer_token"))
        );
    }

    #[test]
    fn codex_overlay_uses_inline_token_for_placeholder() {
        let h = by_id("codex-acp").unwrap();
        let o = h.routing_overlay("http://127.0.0.1:4356", PLACEHOLDER_API_KEY, None);
        assert!(o.args.contains(
            &"model_providers.bitrouter.experimental_bearer_token=\"bitrouter-local\"".to_string()
        ));
        assert!(o.env.iter().all(|(k, _)| k != "BITROUTER_API_KEY"));
    }

    #[test]
    fn codex_overlay_pins_model() {
        let h = by_id("codex-acp").unwrap();
        let o = h.routing_overlay("http://x:1", PLACEHOLDER_API_KEY, Some("gpt-5.2"));
        assert!(o.args.contains(&"model=\"gpt-5.2\"".to_string()));
    }

    #[test]
    fn direct_model_overlay_pins_without_changing_provider_authority() -> anyhow::Result<()> {
        let codex = by_id("codex-acp")
            .ok_or_else(|| anyhow::anyhow!("codex-acp harness is unavailable"))?;
        let overlay = codex.direct_model_overlay("gpt-5.6");
        assert!(overlay.args.contains(&"model=\"gpt-5.6\"".to_string()));
        assert!(
            overlay
                .args
                .iter()
                .all(|arg| !arg.contains("model_provider"))
        );
        assert!(overlay.env.is_empty());

        let claude = by_id("claude-acp")
            .ok_or_else(|| anyhow::anyhow!("claude-acp harness is unavailable"))?;
        let overlay = claude.direct_model_overlay("claude-opus-5");
        assert_eq!(
            overlay.env,
            vec![("ANTHROPIC_MODEL".into(), "claude-opus-5".into())]
        );
        assert!(overlay.args.is_empty());
        Ok(())
    }

    #[test]
    fn config_synthesis_harnesses_have_no_pure_overlay() {
        for id in ["pi-acp", "opencode"] {
            let h = by_id(id).unwrap();
            assert!(!h.env_args_routable(), "{id} routes by synthesis only");
            assert_eq!(
                h.routing_overlay("http://x:1", "t", None),
                RoutingOverlay::default(),
                "{id}"
            );
        }
        assert!(by_id("claude-acp").unwrap().env_args_routable());
        assert!(by_id("codex-acp").unwrap().env_args_routable());
    }

    // ── Launch overlays (config synthesis + MCP injection). ──

    fn mcp() -> McpServer {
        McpServer {
            name: "bitrouter_stdio".into(),
            transport: McpTransport::Stdio {
                command: "/bin/bitrouter".into(),
                args: vec!["mcp".into(), "serve".into()],
            },
        }
    }

    /// An HTTP gateway server (the `bitrouter_tools` shape) for the
    /// synthesizer tests.
    fn tools() -> McpServer {
        McpServer {
            name: "bitrouter_tools".into(),
            transport: McpTransport::Http {
                url: "http://127.0.0.1:4356/mcp".into(),
                headers: vec![("Authorization".into(), "Bearer tok".into())],
            },
        }
    }

    #[test]
    fn claude_launch_overlay_writes_mcp_config_and_flag() {
        let dir = tempfile::tempdir().expect("tempdir");
        let h = by_id("claude-acp").unwrap();
        let o = h
            .launch_overlay("http://x:1", "t", None, &[], &[mcp(), tools()], dir.path())
            .expect("overlay");
        assert_eq!(o.args[0], "--mcp-config");
        let config: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&o.args[1]).expect("config written"))
                .expect("json");
        // Stdio entry: bare command/args.
        assert_eq!(
            config["mcpServers"]["bitrouter_stdio"]["command"],
            "/bin/bitrouter"
        );
        assert_eq!(config["mcpServers"]["bitrouter_stdio"]["args"][1], "serve");
        // HTTP entry: explicit type (a url without type is a hard error in
        // Claude Code) plus the auth header as an object.
        let tools = &config["mcpServers"]["bitrouter_tools"];
        assert_eq!(tools["type"], "http");
        assert_eq!(tools["url"], "http://127.0.0.1:4356/mcp");
        assert_eq!(tools["headers"]["Authorization"], "Bearer tok");
        // Routing env comes through unchanged.
        assert!(o.env.iter().any(|(k, _)| k == "ANTHROPIC_BASE_URL"));
    }

    #[test]
    fn codex_launch_overlay_appends_mcp_toml_overrides() {
        let dir = tempfile::tempdir().expect("tempdir");
        let h = by_id("codex-acp").unwrap();
        let o = h
            .launch_overlay("http://x:1", "t", None, &[], &[mcp(), tools()], dir.path())
            .expect("overlay");
        assert!(
            o.args
                .contains(&"mcp_servers.bitrouter_stdio.command=\"/bin/bitrouter\"".to_string()),
            "{:?}",
            o.args
        );
        assert!(
            o.args
                .contains(&"mcp_servers.bitrouter_stdio.args=[\"mcp\",\"serve\"]".to_string()),
            "{:?}",
            o.args
        );
        // HTTP entry: url selects the streamable-HTTP transport, auth rides
        // http_headers.
        assert!(
            o.args.contains(
                &"mcp_servers.bitrouter_tools.url=\"http://127.0.0.1:4356/mcp\"".to_string()
            ),
            "{:?}",
            o.args
        );
        assert!(
            o.args.contains(
                &"mcp_servers.bitrouter_tools.http_headers.Authorization=\"Bearer tok\""
                    .to_string()
            ),
            "{:?}",
            o.args
        );
    }

    #[test]
    fn hermes_launch_overlay_synthesizes_home_dir() {
        let dir = tempfile::tempdir().expect("tempdir");
        let h = by_id("hermes-acp").unwrap();
        let o = h
            .launch_overlay(
                "http://127.0.0.1:4356",
                "tok",
                Some("supergrok:grok-4.5"),
                &[],
                &[mcp(), tools()],
                dir.path(),
            )
            .expect("overlay");
        assert!(o.args.is_empty(), "hermes routes purely by config");
        let env: std::collections::HashMap<_, _> = o.env.iter().cloned().collect();
        assert_eq!(env["CUSTOM_API_KEY"], "tok");
        let home = std::path::PathBuf::from(&env["HERMES_HOME"]);
        // JSON body in config.yaml — YAML 1.2 parses JSON, no yaml dep needed.
        let config: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(home.join("config.yaml")).expect("read"))
                .expect("json");
        assert_eq!(config["model"]["provider"], "custom");
        assert_eq!(config["model"]["base_url"], "http://127.0.0.1:4356/v1");
        assert_eq!(config["model"]["default"], "supergrok:grok-4.5");
        assert_eq!(
            config["mcp_servers"]["bitrouter_stdio"]["command"],
            "/bin/bitrouter"
        );
        // HTTP entry: url presence selects the transport; auth is a header.
        let tools = &config["mcp_servers"]["bitrouter_tools"];
        assert_eq!(tools["url"], "http://127.0.0.1:4356/mcp");
        assert_eq!(tools["headers"]["Authorization"], "Bearer tok");
        assert!(tools.get("command").is_none(), "http entry has no command");
    }

    #[test]
    fn openclaw_launch_overlay_synthesizes_profile() {
        let dir = tempfile::tempdir().expect("tempdir");
        let h = by_id("openclaw").unwrap();
        let o = h
            .launch_overlay(
                "http://127.0.0.1:4356",
                "tok",
                Some("supergrok:grok-4.5"),
                &["x-ai/grok-4.5".to_string()],
                &[],
                dir.path(),
            )
            .expect("overlay");
        assert_eq!(
            o.args,
            vec!["tui".to_string(), "--local".to_string()],
            "embedded runtime, no gateway"
        );
        let env: std::collections::HashMap<_, _> = o.env.iter().cloned().collect();
        let config: serde_json::Value = serde_json::from_str(
            &std::fs::read_to_string(&env["OPENCLAW_CONFIG_PATH"]).expect("read"),
        )
        .expect("json");
        let provider = &config["models"]["providers"]["bitrouter"];
        assert_eq!(provider["baseUrl"], "http://127.0.0.1:4356/v1");
        assert_eq!(provider["apiKey"], "tok");
        assert_eq!(provider["api"], "openai-completions");
        // Full model entries (config validation rejects bare ids), pinned
        // model first and default.
        assert_eq!(provider["models"][0]["id"], "supergrok:grok-4.5");
        assert_eq!(provider["models"][1]["id"], "x-ai/grok-4.5");
        assert!(provider["models"][0]["cost"].is_object());
        assert_eq!(
            config["agents"]["defaults"]["model"],
            "bitrouter/supergrok:grok-4.5"
        );
        assert!(env.contains_key("OPENCLAW_STATE_DIR"));
    }

    #[test]
    fn opencode_launch_overlay_synthesizes_one_config_file() {
        let dir = tempfile::tempdir().expect("tempdir");
        let h = by_id("opencode").unwrap();
        let catalog = vec!["x-ai/grok-4.5".to_string()];
        let o = h
            .launch_overlay(
                "http://127.0.0.1:4356",
                "tok",
                Some("supergrok:grok-4.5"),
                &catalog,
                &[mcp(), tools()],
                dir.path(),
            )
            .expect("overlay");
        let (key, path) = &o.env[0];
        assert_eq!(key, "OPENCODE_CONFIG");
        assert!(o.args.is_empty(), "opencode routes purely by config file");
        let config: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(path).expect("written")).expect("json");
        assert_eq!(
            config["provider"]["bitrouter"]["options"]["baseURL"],
            "http://127.0.0.1:4356/v1"
        );
        // The pinned model is the default and joins the catalog list.
        assert_eq!(config["model"], "bitrouter/supergrok:grok-4.5");
        assert!(config["provider"]["bitrouter"]["models"]["supergrok:grok-4.5"].is_object());
        assert!(config["provider"]["bitrouter"]["models"]["x-ai/grok-4.5"].is_object());
        // The MCP bridge rides the same file, command+args folded into one
        // invocation array.
        assert_eq!(config["mcp"]["bitrouter_stdio"]["type"], "local");
        assert_eq!(
            config["mcp"]["bitrouter_stdio"]["command"][0],
            "/bin/bitrouter"
        );
        // HTTP entry: opencode's remote type with the auth header.
        let tools = &config["mcp"]["bitrouter_tools"];
        assert_eq!(tools["type"], "remote");
        assert_eq!(tools["url"], "http://127.0.0.1:4356/mcp");
        assert_eq!(tools["enabled"], true);
        assert_eq!(tools["headers"]["Authorization"], "Bearer tok");
    }

    #[test]
    fn opencode_overlay_defaults_model_to_catalog_head() {
        let dir = tempfile::tempdir().expect("tempdir");
        let h = by_id("opencode").unwrap();
        let catalog = vec!["a/one".to_string(), "b/two".to_string()];
        let o = h
            .launch_overlay("http://x:1", "t", None, &catalog, &[], dir.path())
            .expect("overlay");
        let config: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&o.env[0].1).expect("written"))
                .expect("json");
        assert_eq!(config["model"], "bitrouter/a/one");
        assert!(config.get("mcp").is_none(), "no servers requested");
    }

    #[test]
    fn pi_launch_overlay_synthesizes_agent_dir_and_flags() {
        let dir = tempfile::tempdir().expect("tempdir");
        let h = by_id("pi-acp").unwrap();
        let catalog = vec!["x-ai/grok-4.5".to_string()];
        let o = h
            .launch_overlay(
                "http://127.0.0.1:4356",
                "tok",
                Some("supergrok:grok-4.5"),
                &catalog,
                &[mcp(), tools()], // pi has no MCP mechanism — ignored
                dir.path(),
            )
            .expect("overlay");
        let (key, agent_dir) = &o.env[0];
        assert_eq!(key, "PI_CODING_AGENT_DIR");
        let models: serde_json::Value = serde_json::from_str(
            &std::fs::read_to_string(std::path::Path::new(agent_dir).join("models.json"))
                .expect("models.json written"),
        )
        .expect("json");
        let provider = &models["providers"]["bitrouter"];
        assert_eq!(provider["baseUrl"], "http://127.0.0.1:4356/v1");
        assert_eq!(provider["api"], "openai-completions");
        assert_eq!(provider["apiKey"], "tok");
        // Catalog + the pinned model, deduped.
        assert_eq!(provider["models"][0]["id"], "x-ai/grok-4.5");
        assert_eq!(provider["models"][1]["id"], "supergrok:grok-4.5");
        assert_eq!(
            o.args,
            vec!["--provider", "bitrouter", "--model", "supergrok:grok-4.5"]
        );
    }

    #[test]
    fn pi_overlay_without_any_model_selects_nothing() {
        let dir = tempfile::tempdir().expect("tempdir");
        let h = by_id("pi-acp").unwrap();
        let o = h
            .launch_overlay("http://x:1", "t", None, &[], &[], dir.path())
            .expect("overlay");
        assert!(
            o.args.is_empty(),
            "no routable model — pi keeps its own defaults"
        );
    }

    // ── Launch overlays (`bro launch` facet with no gateways wired). ──

    #[test]
    fn opencode_launch_overlay_routes_to_the_gateway_without_mcp() {
        let dir = tempfile::tempdir().expect("tempdir");
        let h = by_id("opencode").unwrap();
        let catalog = vec!["x-ai/grok-4.5".to_string()];
        let o = h
            .launch_overlay(
                "http://127.0.0.1:4356",
                "tok",
                None,
                &catalog,
                &[],
                dir.path(),
            )
            .expect("overlay");
        let (key, path) = &o.env[0];
        assert_eq!(key, "OPENCODE_CONFIG");
        let config: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(path).expect("written")).expect("json");
        assert_eq!(
            config["provider"]["bitrouter"]["options"]["baseURL"],
            "http://127.0.0.1:4356/v1"
        );
        assert_eq!(config["provider"]["bitrouter"]["options"]["apiKey"], "tok");
        assert_eq!(config["model"], "bitrouter/x-ai/grok-4.5");
        // No gateways passed in — no `mcp` block synthesized.
        assert!(config.get("mcp").is_none(), "no servers, no mcp block");
    }

    #[test]
    fn pi_launch_overlay_pins_the_requested_model() {
        let dir = tempfile::tempdir().expect("tempdir");
        let h = by_id("pi-acp").unwrap();
        let catalog = vec!["x-ai/grok-4.5".to_string()];
        let o = h
            .launch_overlay(
                "http://127.0.0.1:4356",
                "tok",
                Some("supergrok:grok-4.5"),
                &catalog,
                &[],
                dir.path(),
            )
            .expect("overlay");
        // `supports_model_pin()` is false for pi (no env/args path), yet the
        // synthesis path pins the model — an interactive caller must not warn.
        assert!(!h.supports_model_pin());
        assert_eq!(
            o.args,
            vec!["--provider", "bitrouter", "--model", "supergrok:grok-4.5"]
        );
        let (key, agent_dir) = &o.env[0];
        assert_eq!(key, "PI_CODING_AGENT_DIR");
        let models: serde_json::Value = serde_json::from_str(
            &std::fs::read_to_string(std::path::Path::new(agent_dir).join("models.json"))
                .expect("models.json written"),
        )
        .expect("json");
        let provider = &models["providers"]["bitrouter"];
        assert_eq!(provider["baseUrl"], "http://127.0.0.1:4356/v1");
        assert_eq!(provider["models"][1]["id"], "supergrok:grok-4.5");
    }

    #[test]
    fn claude_launch_overlay_injects_no_mcp_config_flag() {
        let dir = tempfile::tempdir().expect("tempdir");
        for id in ["claude-acp", "codex-acp"] {
            let h = by_id(id).unwrap();
            let o = h
                .launch_overlay("http://x:1", "t", None, &[], &[], dir.path())
                .expect("overlay");
            assert_eq!(
                o,
                h.routing_overlay("http://x:1", "t", None),
                "{id}: launch with no gateways is the plain routing overlay"
            );
            assert!(
                o.args.iter().all(|a| !a.contains("mcp")),
                "{id}: no MCP injection"
            );
        }
    }

    #[test]
    fn gateway_injection_is_the_only_difference_the_servers_make() {
        // One synthesis, one method: passing gateway servers adds their
        // injection and changes nothing else about the routing overlay.
        for id in ["claude-acp", "codex-acp", "opencode", "hermes-acp"] {
            let h = by_id(id).unwrap();
            let a = tempfile::tempdir().expect("tempdir");
            let b = tempfile::tempdir().expect("tempdir");
            let bare = h
                .launch_overlay("http://x:1", "t", Some("m"), &[], &[], a.path())
                .expect("bare overlay");
            let with_gateways = h
                .launch_overlay("http://x:1", "t", Some("m"), &[], &[mcp()], b.path())
                .expect("gateway overlay");
            // Paths differ by state dir; compare env keys.
            let keys = |o: &RoutingOverlay| -> Vec<String> {
                o.env.iter().map(|(k, _)| k.clone()).collect()
            };
            assert_eq!(keys(&bare), keys(&with_gateways), "{id}");
            assert!(
                with_gateways.args.len() >= bare.args.len(),
                "{id}: injection only ever adds args"
            );
        }
    }

    /// Every file written under `dir`, as `relative path → contents`, with
    /// `dir`'s own path scrubbed out so two runs in different tempdirs
    /// compare equal.
    fn synthesized(dir: &std::path::Path) -> Vec<(String, String)> {
        fn walk(root: &std::path::Path, at: &std::path::Path, out: &mut Vec<(String, String)>) {
            let Ok(entries) = std::fs::read_dir(at) else {
                return;
            };
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_dir() {
                    walk(root, &path, out);
                } else if let (Ok(rel), Ok(body)) =
                    (path.strip_prefix(root), std::fs::read_to_string(&path))
                {
                    out.push((rel.display().to_string(), body));
                }
            }
        }
        let mut out = Vec::new();
        walk(dir, dir, &mut out);
        for (_, body) in &mut out {
            *body = body.replace(&dir.display().to_string(), "<STATE_DIR>");
        }
        out.sort();
        out
    }

    #[test]
    fn injects_mcp_matches_the_launch_overlay() {
        // The startup line (#796) tells the user whether the gateways reached
        // the harness. `injects_mcp` is the declarative answer; this proves it
        // agrees with what `launch_overlay` actually does — including for the
        // config-synthesis harnesses, whose injection lands inside a written
        // file rather than in the overlay itself.
        for h in CATALOG.iter().filter(|h| h.interactive_binary.is_some()) {
            let bare_dir = tempfile::tempdir().expect("tempdir");
            let with_dir = tempfile::tempdir().expect("tempdir");
            let scrub = |args: Vec<String>, dir: &std::path::Path| -> Vec<String> {
                args.into_iter()
                    .map(|a| a.replace(&dir.display().to_string(), "<STATE_DIR>"))
                    .collect()
            };
            let bare = h
                .launch_overlay("http://x:1", "t", Some("m"), &[], &[], bare_dir.path())
                .expect("bare overlay");
            let with = h
                .launch_overlay("http://x:1", "t", Some("m"), &[], &[mcp()], with_dir.path())
                .expect("gateway overlay");

            let differs = scrub(bare.args, bare_dir.path()) != scrub(with.args, with_dir.path())
                || synthesized(bare_dir.path()) != synthesized(with_dir.path());

            assert_eq!(
                differs,
                h.injects_mcp(),
                "{}: injects_mcp() says {} but the overlay {} when gateways are supplied",
                h.id,
                h.injects_mcp(),
                if differs { "changed" } else { "did not change" },
            );
        }
    }

    #[test]
    fn resolve_gateway_auth_precedence() {
        // Real key wins.
        assert_eq!(
            resolve_gateway_auth(Some("brk_x".into()), false).as_deref(),
            Some("brk_x")
        );
        // No key, auth off → placeholder.
        assert_eq!(
            resolve_gateway_auth(None, false).as_deref(),
            Some(PLACEHOLDER_API_KEY)
        );
        // No key, auth required → None (caller fails fast).
        assert_eq!(resolve_gateway_auth(None, true), None);
        // Real key satisfies required auth.
        assert_eq!(
            resolve_gateway_auth(Some("brk_x".into()), true).as_deref(),
            Some("brk_x")
        );
    }
}