scsh 1.9.0

Scoped Skills Helper — preflight a git repo and run its scoped skills in ephemeral containers.
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
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
//! Container-runtime discovery and the in-memory build/run plan.
//!
//! Everything here is pure and side-effect-free except [`which`] / [`detect_runtime`],
//! which only read `$PATH`. The actual process spawning lives in `main.rs`, which
//! keeps this module easy to unit-test without a container runtime installed.

use std::ffi::OsStr;
use std::path::{Path, PathBuf};

use crate::config::Harness;

/// A located container runtime executable.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Runtime {
  pub name: String,
  pub path: PathBuf,
}

/// Candidate runtimes, in the order scsh tries them. Apple's `container` is
/// preferred on macOS; Docker is the primary everywhere; Podman is the fallback.
pub fn runtime_candidates(is_macos: bool) -> &'static [&'static str] {
  if is_macos {
    &["container", "docker", "podman"]
  } else {
    &["docker", "podman"]
  }
}

/// Find the first available runtime for the current OS. If `SCSH_RUNTIME` is set
/// (and non-empty), it overrides detection — scsh uses exactly that runtime when
/// it is on `PATH`. This is handy when the auto-picked runtime can't bind-mount
/// the clone (e.g. snap-packaged Docker is confined away from `/tmp`, so a
/// `SCSH_RUNTIME=podman` override is needed there).
pub fn detect_runtime() -> Option<Runtime> {
  if let Some(name) = std::env::var_os("SCSH_RUNTIME") {
    let name = name.to_string_lossy().into_owned();
    if !name.is_empty() {
      return which(&name).map(|path| Runtime { name, path });
    }
  }
  let path = std::env::var_os("PATH").unwrap_or_default();
  detect_runtime_in(cfg!(target_os = "macos"), &path)
}

/// Testable core of [`detect_runtime`]: search `path` for the OS's candidates.
///
/// Auto-detection additionally avoids a **snap-packaged Docker**: it is
/// AppArmor-confined away from the system temp dir, so it can't bind-mount the
/// per-run clone (the container would see an empty `/home/agent` and the skill's
/// opencode would crash with `EACCES`). When the preferred runtime is a snap
/// Docker *and* another runtime is available, scsh picks the other one instead.
/// An explicit `SCSH_RUNTIME` still forces any choice (see [`detect_runtime`]).
pub fn detect_runtime_in(is_macos: bool, path: &OsStr) -> Option<Runtime> {
  let found: Vec<Runtime> = runtime_candidates(is_macos)
    .iter()
    .filter_map(|&name| which_in(name, path).map(|p| Runtime { name: name.to_string(), path: p }))
    .collect();
  let snap_docker_first = matches!(found.first(), Some(r) if r.name == "docker" && is_snap_confined(&r.path));
  if snap_docker_first {
    if let Some(other) = found.iter().find(|r| r.name != "docker") {
      return Some(other.clone());
    }
  }
  found.into_iter().next()
}

/// Whether an executable path is inside a snap mount (e.g. `/snap/bin/docker`).
/// Snap-packaged Docker can't reach the system temp dir, which is where scsh
/// puts each run's clone, so the container sees nothing mounted.
pub fn is_snap_confined(path: &Path) -> bool {
  path.to_string_lossy().contains("/snap/")
}

/// Resolve an executable on `$PATH` (like the `which` command).
pub fn which(cmd: &str) -> Option<PathBuf> {
  let path = std::env::var_os("PATH")?;
  which_in(cmd, &path)
}

/// Testable core of [`which`]: search the given `path` value.
pub fn which_in(cmd: &str, path: &OsStr) -> Option<PathBuf> {
  if cmd.contains('/') {
    let p = PathBuf::from(cmd);
    return is_executable(&p).then_some(p);
  }
  for dir in std::env::split_paths(path) {
    if dir.as_os_str().is_empty() {
      continue;
    }
    let candidate = dir.join(cmd);
    if is_executable(&candidate) {
      return Some(candidate);
    }
  }
  None
}

#[cfg(unix)]
fn is_executable(p: &Path) -> bool {
  use std::os::unix::fs::PermissionsExt;
  match std::fs::metadata(p) {
    Ok(m) => m.is_file() && (m.permissions().mode() & 0o111 != 0),
    Err(_) => false,
  }
}

#[cfg(not(unix))]
fn is_executable(p: &Path) -> bool {
  std::fs::metadata(p).map(|m| m.is_file()).unwrap_or(false)
}

/// The tag of the harness-specific image scsh builds.
pub fn image_tag(harness: Harness) -> String {
  match harness {
    Harness::Opencode => "scsh-opencode:latest".to_string(),
    Harness::Claude => "scsh-claude:latest".to_string(),
  }
}

/// The Dockerfile build `--target` for a harness image.
pub fn image_target(harness: Harness) -> &'static str {
  match harness {
    Harness::Opencode => "scsh-opencode",
    Harness::Claude => "scsh-claude",
  }
}

/// In-container path where the host's Claude Code config dir is bind-mounted.
pub const CLAUDE_CONFIG_MOUNT: &str = "/home/agent/.claude";

/// In-container path for the forwarded `~/.claude.json`.
pub const CLAUDE_JSON_MOUNT: &str = "/home/agent/.claude.json";

/// Run-dir-relative path where scsh copies forwarded Claude auth before a run (gitignored `tmp/`).
pub const CLAUDE_AUTH_REL: &str = "tmp/.claude-auth";

/// In-container path where opencode reads `auth.json` (`$XDG_DATA_HOME/opencode/auth.json` in the
/// image). scsh bind-mounts the host's `~/.local/share/opencode/auth.json` here when that file
/// exists — required for third-party opencode providers (e.g. Nebius GLM) that authenticate via
/// the host login rather than a built-in model route.
pub const OPENCODE_AUTH_MOUNT: &str = "/home/agent/repo/tmp/.xdg-data/opencode/auth.json";

/// Run-dir-relative tree where scsh copies forwarded opencode auth/config before a run.
pub const OPENCODE_FORWARD_REL: &str = "tmp/.opencode-forward";

/// In-container paths for forwarded opencode config (`$XDG_CONFIG_HOME/opencode/` on the host).
/// Custom providers (e.g. Nebius GLM) are declared here; auth.json alone is not enough.
/// scsh copies these from the host into each run clone (parallel runs cannot safely share one
/// host bind-mount on Apple Containers).
pub const OPENCODE_CONFIG_JSON_MOUNT: &str = "/home/agent/.config/opencode/opencode.json";
pub const OPENCODE_CONFIG_JSONC_MOUNT: &str = "/home/agent/.config/opencode/opencode.jsonc";

/// Host env var for long-lived Claude OAuth (`claude setup-token`).
pub const CLAUDE_OAUTH_TOKEN_ENV: &str = "CLAUDE_CODE_OAUTH_TOKEN";

/// Absolute path the repo clone is bind-mounted at, and the image's WORKDIR (where the harness
/// starts). Deliberately a *subdirectory* of the agent user's home (`/home/agent`), not the
/// home itself: the harness and its tools scribble into `$HOME` (`~/.cache`, `~/.config`,
/// `~/.npm`, …), so keeping the clone one level down keeps that scratch out of the repo's
/// working tree. The home is set in the image (see `src/Dockerfile`).
pub const AGENT_REPO: &str = "/home/agent/repo";

/// opencode's data dir (`XDG_DATA_HOME`), RELATIVE to the repo, where scsh drops the forwarded
/// credential. It lives under the gitignored `tmp/`, so neither the auth nor opencode's own
/// session data ever shows up as an untracked file. The image sets `XDG_DATA_HOME` to
/// [`AGENT_REPO`]`/`this.
pub const AGENT_XDG_DATA_REL: &str = "tmp/.xdg-data";

/// Per-run log path the harness tees every line of its output to, RELATIVE to the repo. It
/// lives under the gitignored `tmp/` (so it is never an untracked file); on the host it is
/// therefore `<run_dir>/tmp/scsh-run.log`, where the full intra-container output can be read.
pub const RUN_LOG_REL: &str = "tmp/scsh-run.log";

/// The env var (set in the generated image) that carries the in-container log
/// path the harness command tees its output to.
pub const RUN_LOG_VAR: &str = "SCSH_RUN_LOG";

/// The Dockerfile scsh builds every skill container from. The source of truth is the
/// sibling [`src/Dockerfile`](./Dockerfile) — a static, platform-agnostic file embedded at
/// compile time. It needs no Rust-side substitution: UID/GID/TZ are `ARG`s passed as build
/// args, and every architecture-specific download resolves the target arch *inside* the
/// build (`dpkg --print-architecture` -> amd64|arm64), so the one file builds on x86_64 and
/// arm64 alike. The image is generic (opencode + a dev toolchain + a non-root `agent` user,
/// no skill `CMD`), so it serves every skill; `main.rs` streams it to the builder's stdin.
pub fn dockerfile() -> String {
  include_str!("Dockerfile").to_string()
}

/// The builder host's IANA timezone (e.g. `Europe/Berlin`), baked into the image so a skill's
/// timestamps match the machine that built it. Tries `$TZ`, then the `/etc/localtime` symlink
/// target, then `/etc/timezone`; falls back to `UTC`.
pub fn host_timezone() -> String {
  if let Ok(tz) = std::env::var("TZ") {
    let tz = tz.trim();
    if !tz.is_empty() {
      return tz.to_string();
    }
  }
  if let Ok(target) = std::fs::read_link("/etc/localtime") {
    let s = target.to_string_lossy();
    if let Some(idx) = s.find("zoneinfo/") {
      let tz = s[idx + "zoneinfo/".len()..].trim_matches('/');
      if !tz.is_empty() {
        return tz.to_string();
      }
    }
  }
  if let Ok(contents) = std::fs::read_to_string("/etc/timezone") {
    let tz = contents.trim();
    if !tz.is_empty() {
      return tz.to_string();
    }
  }
  "UTC".to_string()
}

/// Whether harness commands include verbose/progress flags. On by default for scsh
/// runs (headless — the live board and `tmp/scsh-run.log` need turn-by-turn output).
/// Opt out with `SCSH_QUIET=1`.
pub fn harness_verbose_enabled() -> bool {
  !matches!(std::env::var("SCSH_QUIET").ok().as_deref(), Some("1") | Some("true"))
}

/// The shell command a harness runs *inside the container* for one skill.
pub fn harness_command(harness: Harness, model: Option<&str>, skill_source: &str, result: &str) -> String {
  harness_command_verbose(harness, model, skill_source, result, harness_verbose_enabled())
}

fn harness_command_verbose(
  harness: Harness, model: Option<&str>, skill_source: &str, result: &str, verbose: bool,
) -> String {
  match harness {
    Harness::Opencode => {
      let instruction = format!(
        "run skill {skill_source}. Follow .skills/{skill_source}/SKILL.md exactly. \
         Write the required result file to {result} (also available as the SCSH_RESULT environment variable). \
         Do not git fetch, pull, push, or clone — scsh preloaded a full local clone; use only refs already present."
      );
      let mut cmd = String::from("opencode");
      if let Some(m) = model {
        cmd.push(' ');
        cmd.push_str("-m ");
        cmd.push_str(&shell_quote(m));
      }
      if verbose {
        cmd.push_str(" --print-logs --log-level INFO");
      }
      cmd.push_str(" run ");
      cmd.push_str(&shell_quote(&instruction));
      format!("{cmd} 2>&1 | tee \"${RUN_LOG_VAR}\"")
    }
    Harness::Claude => {
      let prompt = format!(
        "Run the skill defined in .skills/{skill_source}/SKILL.md. Follow its instructions exactly. \
         Write the required result file to {result} (also available as the SCSH_RESULT environment variable). \
         Do not git fetch, pull, push, or clone — scsh preloaded a full local clone; use only refs already present."
      );
      let mut cmd = String::from("claude -p ");
      cmd.push_str(&shell_quote(&prompt));
      cmd.push_str(" --permission-mode bypassPermissions --no-session-persistence");
      if verbose {
        cmd.push_str(" --verbose");
      }
      if let Some(m) = model {
        cmd.push_str(" --model ");
        cmd.push_str(&shell_quote(m));
      }
      format!("{cmd} 2>&1 | tee \"${RUN_LOG_VAR}\"")
    }
  }
}

/// How a given runtime accepts the generated Dockerfile.
///
/// docker and podman read it from stdin (`build … -`), which keeps it fully
/// in-memory and dodges build-context path confinement (e.g. snap-packaged
/// Docker can't read `/tmp`). Apple's `container` has no stdin build mode — it
/// requires a context directory — so for it scsh writes the in-memory Dockerfile
/// to an ephemeral context dir that is removed right after the build.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BuildMethod {
  Stdin,
  ContextDir,
}

/// The filename scsh writes inside the ephemeral context dir (the universal
/// default Dockerfile name, so no `-f` flag is needed).
pub const CONTEXT_DOCKERFILE_NAME: &str = "Dockerfile";

/// Pick the build method for a runtime.
pub fn build_method(runtime: &str) -> BuildMethod {
  if runtime == "container" {
    BuildMethod::ContextDir
  } else {
    BuildMethod::Stdin
  }
}

/// OCI label scsh stamps on every harness image at build time. Compared on later runs
/// to skip rebuilding when the embedded Dockerfile and build args are unchanged.
pub const BUILD_FINGERPRINT_LABEL: &str = "scsh.build.fingerprint";

/// The `--build-arg` pair that pins the agent's UID/GID to the host user's.
fn build_args(uid: u32, gid: u32, tz: &str) -> Vec<String> {
  vec![
    "--build-arg".into(),
    format!("AGENT_UID={uid}"),
    "--build-arg".into(),
    format!("AGENT_GID={gid}"),
    "--build-arg".into(),
    format!("TZ={tz}"),
  ]
}

fn build_labels(fingerprint: &str) -> Vec<String> {
  vec!["--label".into(), format!("{BUILD_FINGERPRINT_LABEL}={fingerprint}")]
}

/// Deterministic sha256 over the Dockerfile, `--target`, and the build args that affect the image.
pub fn image_build_fingerprint(dockerfile: &str, target: &str, uid: u32, gid: u32, tz: &str) -> String {
  let blob = format!("target={target}\nuid={uid}\ngid={gid}\ntz={tz}\n---\n{dockerfile}");
  crate::sha256::sha256_hex(blob.as_bytes())
}

/// Read the fingerprint label from an existing harness image, if present.
pub fn image_inspect_fingerprint(runtime: &str, tag: &str) -> Option<String> {
  use std::process::Command;
  let out = if runtime == "container" {
    Command::new("container").args(["image", "inspect", tag]).output().ok()?
  } else {
    let format = format!(r#"{{{{index .Config.Labels "{BUILD_FINGERPRINT_LABEL}"}}}}"#);
    Command::new(runtime).args(["image", "inspect", tag, "--format", &format]).output().ok()?
  };
  if !out.status.success() {
    return None;
  }
  let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
  if runtime == "container" {
    parse_label_from_container_inspect(&s, BUILD_FINGERPRINT_LABEL)
  } else if s.is_empty() {
    None
  } else {
    Some(s)
  }
}

/// True when `tag` exists and carries the expected build fingerprint (skip rebuild).
pub fn image_is_up_to_date(runtime: &str, tag: &str, fingerprint: &str) -> bool {
  image_inspect_fingerprint(runtime, tag).as_deref() == Some(fingerprint)
}

fn parse_label_from_container_inspect(json: &str, key: &str) -> Option<String> {
  let needle = format!(r#""{key}":""#);
  let start = json.find(&needle)? + needle.len();
  let rest = &json[start..];
  let end = rest.find('"')?;
  Some(rest[..end].to_string())
}

/// Build argv for the stdin method: the Dockerfile is sent on stdin (`-`).
pub fn build_command_stdin(
  runtime: &str, tag: &str, target: &str, uid: u32, gid: u32, tz: &str, fingerprint: &str,
) -> Vec<String> {
  let mut v = vec![runtime.into(), "build".into(), "-t".into(), tag.into(), "--target".into(), target.into()];
  v.extend(build_args(uid, gid, tz));
  v.extend(build_labels(fingerprint));
  v.push("-".into());
  v
}

pub fn build_command_context(
  runtime: &str, tag: &str, target: &str, context_dir: &str, uid: u32, gid: u32, tz: &str, fingerprint: &str,
) -> Vec<String> {
  let mut v = vec![runtime.into(), "build".into(), "-t".into(), tag.into(), "--target".into(), target.into()];
  v.extend(build_args(uid, gid, tz));
  v.extend(build_labels(fingerprint));
  v.push(context_dir.into());
  v
}

/// One harness image scsh may build from the shared Dockerfile.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImageBuildSpec {
  pub harness: Harness,
  pub tag: String,
  pub target: String,
  pub fingerprint: String,
}

pub fn image_build_spec(harness: Harness, dockerfile: &str, uid: u32, gid: u32, tz: &str) -> ImageBuildSpec {
  let target = image_target(harness);
  ImageBuildSpec {
    harness,
    tag: image_tag(harness),
    target: target.to_string(),
    fingerprint: image_build_fingerprint(dockerfile, target, uid, gid, tz),
  }
}

/// True when the runtime exposes `buildx bake` (multi-target build in one command).
pub fn runtime_supports_bake(runtime: &str) -> bool {
  std::process::Command::new(runtime)
    .args(["buildx", "version"])
    .stdout(std::process::Stdio::null())
    .stderr(std::process::Stdio::null())
    .status()
    .map(|s| s.success())
    .unwrap_or(false)
}

/// Build argv for one `buildx bake` that tags every listed harness target.
pub fn build_command_bake(runtime: &str, bake_targets: &[String]) -> Vec<String> {
  let mut v = vec![runtime.into(), "buildx".into(), "bake".into(), "--load".into(), "-f".into(), "-".into()];
  v.extend(bake_targets.iter().cloned());
  v
}

/// JSON bake definition: one context dir, multiple Dockerfile `--target`s sharing `scsh-base`.
pub fn bake_definition_json(context_dir: &str, specs: &[ImageBuildSpec], uid: u32, gid: u32, tz: &str) -> String {
  use crate::json::quote;
  let mut entries = Vec::with_capacity(specs.len());
  for spec in specs {
    entries.push(format!(
      r#"    {}: {{
      "context": {},
      "dockerfile": "Dockerfile",
      "target": {},
      "tags": [{}],
      "args": {{
        "AGENT_UID": "{uid}",
        "AGENT_GID": "{gid}",
        "TZ": {}
      }},
      "labels": {{
        {}: {}
      }}
    }}"#,
      quote(&spec.target),
      quote(context_dir),
      quote(&spec.target),
      quote(&spec.tag),
      quote(tz),
      quote(BUILD_FINGERPRINT_LABEL),
      quote(&spec.fingerprint),
    ));
  }
  format!("{{\n  \"target\": {{\n{}\n  }}\n}}", entries.join(",\n"))
}

/// How the caller repo reaches the container.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RepoMountMode {
  /// Linux-friendly path: bind-mount the host run dir at [`AGENT_REPO`].
  Full,
  /// macOS Apple Container: repo is cloned inside the container from a host git daemon;
  /// only the gitignored `tmp/` tree is bind-mounted for results and forwarded auth.
  TmpOnly,
}

/// Run argv: run the freshly built image, removing the container afterwards. For
/// rootless podman, `--userns=keep-id` maps the host UID to the same UID inside the
/// container so the `agent` user can read/write the mount; docker (and Apple
/// `container`) map the UID directly and need no such flag.
pub fn run_command(
  runtime: &str, tag: &str, run_dir: &str, name: &str, env: &[(String, String)], volumes: &[(&str, &str)],
  command: &str, repo_mount: RepoMountMode,
) -> Vec<String> {
  let mut v = vec![runtime.into(), "run".into(), "--rm".into(), "--name".into(), name.into()];
  if runtime == "podman" {
    v.push("--userns=keep-id".into());
  }
  for (key, value) in env {
    v.push("-e".into());
    v.push(format!("{key}={value}"));
  }
  for (host, mount) in volumes {
    v.push("-v".into());
    v.push(format!("{host}:{mount}"));
  }
  match repo_mount {
    RepoMountMode::Full => {
      v.push("-v".into());
      v.push(format!("{run_dir}:{AGENT_REPO}"));
    }
    RepoMountMode::TmpOnly => {
      v.push("-v".into());
      v.push(format!("{run_dir}/tmp:{AGENT_REPO}/tmp"));
    }
  }
  v.push(tag.into());
  v.push("/bin/sh".into());
  v.push("-c".into());
  v.push(command.into());
  v
}

pub fn opencode_auth_in(xdg_data_home: Option<&OsStr>, home: Option<&OsStr>) -> Option<PathBuf> {
  let base = match xdg_data_home {
    Some(x) if !x.is_empty() => PathBuf::from(x),
    _ => PathBuf::from(home?).join(".local").join("share"),
  };
  Some(base.join("opencode").join("auth.json"))
}

/// Host opencode config dir (`$XDG_CONFIG_HOME/opencode` or `~/.config/opencode`).
pub fn opencode_config_dir(xdg_config_home: Option<&OsStr>, home: Option<&OsStr>) -> Option<PathBuf> {
  let base = match xdg_config_home {
    Some(x) if !x.is_empty() => PathBuf::from(x),
    _ => PathBuf::from(home?).join(".config"),
  };
  Some(base.join("opencode"))
}

pub fn opencode_config_json_in(xdg_config_home: Option<&OsStr>, home: Option<&OsStr>) -> Option<PathBuf> {
  let path = opencode_config_dir(xdg_config_home, home)?.join("opencode.json");
  path.is_file().then_some(path)
}

pub fn opencode_config_jsonc_in(xdg_config_home: Option<&OsStr>, home: Option<&OsStr>) -> Option<PathBuf> {
  let path = opencode_config_dir(xdg_config_home, home)?.join("opencode.jsonc");
  path.is_file().then_some(path)
}

pub fn opencode_auth_ready() -> bool {
  opencode_auth_in(std::env::var_os("XDG_DATA_HOME").as_deref(), std::env::var_os("HOME").as_deref())
    .is_some_and(|p| p.is_file())
}

pub fn claude_oauth_token() -> Option<String> {
  std::env::var(CLAUDE_OAUTH_TOKEN_ENV).ok().filter(|s| !s.is_empty())
}

fn claude_credentials_file_on_host() -> Option<PathBuf> {
  let home = std::env::var_os("HOME")?;
  let path = PathBuf::from(home).join(".claude").join(".credentials.json");
  path.is_file().then_some(path)
}

/// Whether the host has credentials containers can use: `CLAUDE_CODE_OAUTH_TOKEN` or
/// `~/.claude/.credentials.json`.
pub fn claude_container_auth_ready() -> bool {
  claude_oauth_token().is_some() || claude_credentials_file_on_host().is_some()
}

pub fn check_harness_host(harness: Harness) -> Result<(), String> {
  match harness {
    Harness::Opencode => {
      if opencode_auth_ready() {
        Ok(())
      } else {
        Err("opencode harness unavailable (auth not found at ~/.local/share/opencode/auth.json — run `opencode auth login`)".into())
      }
    }
    Harness::Claude => {
      if claude_container_auth_ready() {
        Ok(())
      } else {
        Err(
          "claude harness unavailable (CLAUDE_CODE_OAUTH_TOKEN is not set and ~/.claude/.credentials.json was not found \
           — run `claude setup-token`, then export CLAUDE_CODE_OAUTH_TOKEN in your shell)"
            .into(),
        )
      }
    }
  }
}

/// Host-side opencode model list, loaded once per `scsh run` when needed.
pub struct OpencodeModelProbe {
  available: Option<std::collections::HashSet<String>>,
}

impl OpencodeModelProbe {
  /// Run `opencode models <provider>` for each provider required by **selected** skills'
  /// explicit opencode models (profile-scoped — not every model in `.scsh.yml`).
  pub fn for_selected(skills: &[crate::config::ResolvedInvocation]) -> Self {
    let requested = requested_opencode_models(skills);
    if requested.is_empty() {
      return Self { available: None };
    }
    if which("opencode").is_none() || !opencode_auth_ready() {
      return Self { available: None };
    }
    Self { available: Some(load_opencode_models_for(&requested).unwrap_or_default()) }
  }

  pub fn check_model(&self, model: &str) -> Result<(), String> {
    match &self.available {
      Some(set) if set.contains(model) => Ok(()),
      Some(_) => Err(format!("opencode model '{model}' not listed by `opencode models` on this host")),
      None => Ok(()),
    }
  }
}

/// Explicit opencode `model:` values on selected invocations (deduplicated).
fn requested_opencode_models(skills: &[crate::config::ResolvedInvocation]) -> std::collections::HashSet<String> {
  skills
    .iter()
    .filter(|s| s.harness == Harness::Opencode)
    .filter_map(|s| s.model.as_deref())
    .map(str::to_string)
    .collect()
}

/// Provider segment of an opencode model id (`openai/gpt-5.5` → `openai`).
fn opencode_model_provider(model: &str) -> &str {
  model.split('/').next().unwrap_or(model)
}

/// Unique providers for a set of requested model ids, stable order.
fn opencode_providers_for_models(models: &std::collections::HashSet<String>) -> Vec<String> {
  let mut providers: Vec<String> = models.iter().map(|m| opencode_model_provider(m).to_string()).collect();
  providers.sort_unstable();
  providers.dedup();
  providers
}

/// Harness auth plus, for opencode skills with an explicit `model:`, a host `opencode models` check.
pub fn check_skill_host(harness: Harness, model: Option<&str>, probe: &OpencodeModelProbe) -> Result<(), String> {
  check_harness_host(harness)?;
  if harness == Harness::Opencode {
    if let Some(m) = model {
      probe.check_model(m)?;
    }
  }
  Ok(())
}

fn load_opencode_models_for(
  requested: &std::collections::HashSet<String>,
) -> Result<std::collections::HashSet<String>, String> {
  let mut all = std::collections::HashSet::new();
  for provider in opencode_providers_for_models(requested) {
    let output = std::process::Command::new("opencode")
      .args(["models", &provider])
      .output()
      .map_err(|e| format!("could not run `opencode models {provider}`: {e}"))?;
    if !output.status.success() {
      let stderr = String::from_utf8_lossy(&output.stderr);
      let detail = stderr.trim();
      let msg =
        if detail.is_empty() { format!("opencode models {provider} exited with an error") } else { detail.to_string() };
      return Err(msg);
    }
    all.extend(parse_opencode_models(&String::from_utf8_lossy(&output.stdout)));
  }
  Ok(all)
}

fn parse_opencode_models(stdout: &str) -> std::collections::HashSet<String> {
  stdout.lines().map(|line| line.trim()).filter(|line| !line.is_empty()).map(|line| line.to_string()).collect()
}

/// Host opencode paths for `scsh list --verbose` (real runs copy into the run clone first).
pub fn opencode_host_mounts() -> Vec<(String, String)> {
  opencode_host_mounts_from(
    std::env::var_os("XDG_DATA_HOME").as_deref(),
    std::env::var_os("XDG_CONFIG_HOME").as_deref(),
    std::env::var_os("HOME").as_deref(),
  )
}

pub fn opencode_host_mounts_from(
  xdg_data_home: Option<&OsStr>, xdg_config_home: Option<&OsStr>, home: Option<&OsStr>,
) -> Vec<(String, String)> {
  let mut out = Vec::new();
  if let Some(auth) = opencode_auth_in(xdg_data_home, home).filter(|p| p.is_file()) {
    out.push((auth.to_string_lossy().into_owned(), OPENCODE_AUTH_MOUNT.to_string()));
  }
  if let Some(cfg) = opencode_config_json_in(xdg_config_home, home) {
    out.push((cfg.to_string_lossy().into_owned(), OPENCODE_CONFIG_JSON_MOUNT.to_string()));
  }
  if let Some(cfg) = opencode_config_jsonc_in(xdg_config_home, home) {
    out.push((cfg.to_string_lossy().into_owned(), OPENCODE_CONFIG_JSONC_MOUNT.to_string()));
  }
  out
}

/// Bind-mount opencode auth/config copied into a run clone.
pub fn opencode_forward_mounts(forward_root: &Path) -> Vec<(String, String)> {
  let mut out = Vec::new();
  let auth = forward_root.join("xdg/opencode/auth.json");
  if auth.is_file() {
    out.push((auth.to_string_lossy().into_owned(), OPENCODE_AUTH_MOUNT.to_string()));
  }
  let json = forward_root.join("config/opencode/opencode.json");
  if json.is_file() {
    out.push((json.to_string_lossy().into_owned(), OPENCODE_CONFIG_JSON_MOUNT.to_string()));
  }
  let jsonc = forward_root.join("config/opencode/opencode.jsonc");
  if jsonc.is_file() {
    out.push((jsonc.to_string_lossy().into_owned(), OPENCODE_CONFIG_JSONC_MOUNT.to_string()));
  }
  out
}

/// Volume mounts for forwarded Claude auth copied into `auth_root` (under a run dir).
pub fn claude_auth_mounts(auth_root: &Path) -> Vec<(String, String)> {
  let mut out = Vec::new();
  let claude_dir = auth_root.join(".claude");
  if claude_dir.is_dir() {
    out.push((claude_dir.to_string_lossy().into_owned(), CLAUDE_CONFIG_MOUNT.to_string()));
  }
  let claude_json = auth_root.join(".claude.json");
  if claude_json.is_file() {
    out.push((claude_json.to_string_lossy().into_owned(), CLAUDE_JSON_MOUNT.to_string()));
  }
  out
}

/// Volume mounts shown by `scsh list --verbose` (host paths; real runs use the same bind-mounts).
pub fn harness_volumes(harness: Harness) -> Vec<(String, String)> {
  match harness {
    Harness::Opencode => opencode_host_mounts(),
    Harness::Claude => {
      let Some(home) = std::env::var_os("HOME") else {
        return Vec::new();
      };
      let home = PathBuf::from(home);
      let mut out = Vec::new();
      let claude_dir = home.join(".claude");
      if claude_dir.is_dir() {
        out.push((claude_dir.to_string_lossy().into_owned(), CLAUDE_CONFIG_MOUNT.to_string()));
      }
      let claude_json = home.join(".claude.json");
      if claude_json.is_file() {
        out.push((claude_json.to_string_lossy().into_owned(), CLAUDE_JSON_MOUNT.to_string()));
      }
      out
    }
  }
}

/// Render an argv as a copy-pasteable shell command (for `scsh list --verbose`).
pub fn shell_join(args: &[String]) -> String {
  args.iter().map(|a| shell_quote(a)).collect::<Vec<_>>().join(" ")
}

fn shell_quote(s: &str) -> String {
  let safe = !s.is_empty()
    && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '/' | ':' | '=' | '+'));
  if safe {
    s.to_string()
  } else {
    format!("'{}'", s.replace('\'', r"'\''"))
  }
}

// ---------------------------------------------------------------------------
// UTC timestamps and the /tmp run-dir / backup names
// ---------------------------------------------------------------------------

/// Convert a count of days since 1970-01-01 to a `(year, month, day)` triple in
/// the proleptic Gregorian calendar — Howard Hinnant's `civil_from_days`. This
/// is what lets scsh format a UTC timestamp with only the standard library.
fn civil_from_days(z: i64) -> (i64, u32, u32) {
  let z = z + 719_468;
  let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
  let doe = z - era * 146_097; // [0, 146096]
  let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399]
  let y = yoe + era * 400;
  let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
  let mp = (5 * doy + 2) / 153; // [0, 11]
  let d = (doy - (153 * mp + 2) / 5 + 1) as u32; // [1, 31]
  let m = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32; // [1, 12]
  (if m <= 2 { y + 1 } else { y }, m, d)
}

/// Format Unix `epoch_secs` as a UTC `YYYYMMDD-HHMMSS` stamp (no separators
/// beyond the dash), matching scsh's run-dir and backup naming convention.
pub fn format_utc_timestamp(epoch_secs: u64) -> String {
  let days = (epoch_secs / 86_400) as i64;
  let tod = epoch_secs % 86_400;
  let (h, mi, s) = (tod / 3600, (tod % 3600) / 60, tod % 60);
  let (y, m, d) = civil_from_days(days);
  format!("{y:04}{m:02}{d:02}-{h:02}{mi:02}{s:02}")
}

/// Apple Containers (and Docker's normative pattern) cap container IDs at 64 characters.
pub const CONTAINER_ID_MAX_LEN: usize = 64;

/// Six lowercase `[a-z]` letters — the Apple-container run-dir stamp in place of UTC time.
pub fn random_nonce_6() -> String {
  let mut buf = [0u8; 6];
  let filled =
    std::fs::File::open("/dev/urandom").and_then(|mut f| std::io::Read::read_exact(&mut f, &mut buf)).is_ok();
  if !filled {
    let nanos =
      std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0) as u64;
    let seed = nanos ^ ((std::process::id() as u64) << 32);
    for (i, b) in buf.iter_mut().enumerate() {
      *b = ((seed.wrapping_mul(1_103_515_245).wrapping_add(i as u64)) % 26) as u8;
    }
  }
  buf.iter().map(|b| (b'a' + (b % 26)) as char).collect()
}

/// Shorten `s` to at most `max_len` by keeping the start and end with `..` in the middle.
pub fn truncate_middle(s: &str, max_len: usize) -> String {
  if max_len == 0 {
    return String::new();
  }
  if s.len() <= max_len {
    return s.to_string();
  }
  if max_len <= 2 {
    return s.chars().take(max_len).collect();
  }
  let keep = max_len - 2;
  let first_k = keep.div_ceil(2);
  let last_n = keep / 2;
  let bytes = s.as_bytes();
  let first = &s[..first_k];
  let last = std::str::from_utf8(&bytes[bytes.len() - last_n..]).unwrap_or("");
  format!("{first}..{last}")
}

fn apple_container_run_dir_name_with_nonce(skill: &str, nonce: &str) -> String {
  let prefix = format!("scsh-{nonce}-run-");
  let budget = CONTAINER_ID_MAX_LEN.saturating_sub(prefix.len());
  let skill_part = truncate_middle(skill, budget);
  format!("{prefix}{skill_part}")
}

/// Whether `name` looks like a per-run scratch dir under `/tmp` (UTC stamp or Apple nonce).
pub fn is_scsh_run_dir_name(name: &str) -> bool {
  if !name.starts_with("scsh-") {
    return false;
  }
  if name.contains("-utc-run-") {
    return true;
  }
  let rest = match name.strip_prefix("scsh-") {
    Some(r) => r,
    None => return false,
  };
  let (nonce, _) = match rest.split_once("-run-") {
    Some(pair) => pair,
    None => return false,
  };
  nonce.len() == 6 && nonce.chars().all(|c| c.is_ascii_lowercase())
}

/// Name of the per-run scratch directory created under `/tmp`.
///
/// Docker/podman: `scsh-YYYYMMDD-HHMMSS-utc-run-<skill>`.
/// Apple `container`: `scsh-<nonce>-run-<skill>` (≤ [`CONTAINER_ID_MAX_LEN`] chars; the skill
/// segment is middle-truncated with `..` when needed).
pub fn run_dir_name(epoch_secs: u64, skill: &str, runtime: &str) -> String {
  let skill = sanitize_component(skill);
  if runtime == "container" {
    apple_container_run_dir_name_with_nonce(&skill, &random_nonce_6())
  } else {
    format!("scsh-{}-utc-run-{}", format_utc_timestamp(epoch_secs), skill)
  }
}

/// Name an existing file is moved to before scsh overwrites it with a fresh
/// result: `<name>.bak.YYYYMMDD-HHMMSS-utc`.
pub fn backup_name(file_name: &str, epoch_secs: u64) -> String {
  format!("{file_name}.bak.{}-utc", format_utc_timestamp(epoch_secs))
}

/// Sanitize a skill name into a filesystem-safe path component (lowercased,
/// non-`[a-z0-9._-]` mapped to `-`, edges trimmed). Empty input becomes `skill`.
/// Also used for the `scsh/incoming/<skill>-…` branch names (the same charset is a
/// valid git ref component).
pub fn sanitize_component(s: &str) -> String {
  let mapped: String = s
    .chars()
    .map(|c| {
      let c = c.to_ascii_lowercase();
      if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
        c
      } else {
        '-'
      }
    })
    .collect();
  let trimmed = mapped.trim_matches(|c| matches!(c, '.' | '_' | '-'));
  if trimmed.is_empty() {
    "skill".to_string()
  } else {
    trimmed.to_string()
  }
}

// ---------------------------------------------------------------------------
// Repo sync: host push IN, host fetch OUT (never GitHub from inside the container)
// ---------------------------------------------------------------------------

/// Bare repo directory name under a run dir — host `git push` target for push IN.
pub const TRANSPORT_BARE: &str = "transport.git";

/// Bare repo directory name under a run dir — container `git push` target for pull OUT.
pub const PULL_BARE: &str = "pull.git";

/// Container env: optional override for the host address of the per-run `git daemon`.
/// When unset, the container entry resolves it from `ip route` (default gateway).
pub const GIT_TRANSPORT_HOST_ENV: &str = "SCSH_GIT_HOST";

/// Container env: port for the per-run `git daemon`.
pub const GIT_TRANSPORT_PORT_ENV: &str = "SCSH_GIT_PORT";

/// Shell snippet run inside the container: host IP for the per-run git daemon.
/// Uses the container's default-route gateway (vmnet bridge on Apple Container).
/// `SCSH_GIT_HOST` overrides when set.
pub const GIT_TRANSPORT_HOST_SHELL: &str =
  "host=${SCSH_GIT_HOST:-$(ip -4 route show default 2>/dev/null | awk '{print $3; exit}')}";

/// Shell guard: fail fast when the gateway cannot be determined.
pub const GIT_TRANSPORT_HOST_GUARD: &str =
  "[ -n \"$host\" ] || { echo \"scsh: could not determine host gateway for git transport (set SCSH_GIT_HOST)\" >&2; exit 1; }";

/// Whether scsh moves git state via local push/fetch + git daemon instead of bind-mounting
/// `.git` across macOS→Linux (Apple Container). On macOS Apple Container this is always
/// enabled — bind-mounting `.git` corrupts objects. Elsewhere override with `SCSH_GIT_TRANSPORT=0|1`.
pub fn uses_git_transport(runtime: &str) -> bool {
  if cfg!(target_os = "macos") && runtime == "container" {
    return true;
  }
  match std::env::var("SCSH_GIT_TRANSPORT").ok().as_deref() {
    Some("0") | Some("false") => false,
    Some("1") | Some("true") => true,
    _ => false,
  }
}

/// Pick a free TCP port on all interfaces for a short-lived `git daemon`.
pub fn pick_ephemeral_port() -> Result<u16, String> {
  use std::net::TcpListener;
  let listener = TcpListener::bind("0.0.0.0:0").map_err(|e| format!("could not bind an ephemeral port: {e}"))?;
  listener.local_addr().map(|a| a.port()).map_err(|e| format!("could not read ephemeral port: {e}"))
}

/// `git clone` argv: host-side push IN when bind-mounting (Linux host → Linux container).
pub fn clone_command(src: &str, dst: &str) -> Vec<String> {
  vec!["git".into(), "clone".into(), src.into(), dst.into()]
}

/// `git fsck` argv: verify clone integrity after host-side push IN / clone.
pub fn fsck_command(repo: &str) -> Vec<String> {
  vec!["git".into(), "-C".into(), repo.into(), "fsck".into(), "--no-progress".into()]
}

/// Create an empty bare repository at `path` (parent dirs created as needed).
pub fn init_bare_repo(path: &Path) -> Result<(), String> {
  if path.is_dir() {
    return Ok(());
  }
  if let Some(parent) = path.parent() {
    std::fs::create_dir_all(parent).map_err(|e| format!("could not create {}: {e}", parent.display()))?;
  }
  use std::process::Command;
  Command::new("git")
    .args(["init", "--bare"])
    .arg(path)
    .stdout(std::process::Stdio::null())
    .stderr(std::process::Stdio::null())
    .status()
    .map(|s| s.success())
    .unwrap_or(false)
    .then_some(())
    .ok_or_else(|| format!("git init --bare failed for {}", path.display()))
}

/// Host push IN: mirror every local `refs/heads/*` branch into the bare transport repo.
/// Code-review prep uses `git branch -f main <base>`; pushing heads (not stale
/// `refs/remotes/origin/*`) ensures `origin/main..HEAD` resolves inside the container.
pub fn push_transport_refs(root: &Path, bare: &Path) -> Result<(), String> {
  init_bare_repo(bare)?;
  let bare_s = bare.to_string_lossy();
  let Some(heads) = git_stdout(root, &["for-each-ref", "--format=%(refname)", "refs/heads"]) else {
    return Err(format!("could not read local branches in {}", root.display()));
  };
  let mut pushed = false;
  for line in heads.lines() {
    let refname = line.trim();
    if refname.is_empty() {
      continue;
    }
    let spec = format!("{refname}:{refname}");
    if !git_ok(root, &["push", "--quiet", &bare_s, &spec]) {
      return Err(format!("git push {refname} to {} failed", bare.display()));
    }
    pushed = true;
  }
  if !pushed {
    return Err(format!("no local branches to push from {}", root.display()));
  }
  if let Some(branch) = git_stdout(root, &["rev-parse", "--abbrev-ref", "HEAD"]) {
    let branch = branch.trim();
    if !branch.is_empty() && branch != "HEAD" {
      let head_ref = format!("refs/heads/{branch}");
      if !git_bare_ok(bare, &["symbolic-ref", "HEAD", &head_ref]) {
        return Err(format!("could not set HEAD on {}", bare.display()));
      }
    }
  }
  Ok(())
}

/// Path scsh fetches commits from after a run: the run clone, or `pull.git` when git transport
/// moved the repo only inside the container.
pub fn commits_fetch_path(run_dir: &Path) -> PathBuf {
  let pull = run_dir.join(PULL_BARE);
  if pull.is_dir() {
    pull
  } else {
    run_dir.to_path_buf()
  }
}

/// Shell wrapper run inside the container before the harness: clone from the host git daemon,
/// materialize `origin/*` locals, optionally set commit identity, run the harness, optionally
/// push commits back to the host bare `pull.git`.
pub fn git_transport_entry(harness: &str, push_commits: bool, commit_name: &str, commit_email: &str) -> String {
  let mut script = format!(
    "set -e\n\
     {host_shell}\n\
     {host_guard}\n\
     git clone \"git://${{host}}:${{{port}}}/transport.git\" /home/agent/.scsh-clone\n\
     (cd /home/agent/.scsh-clone && tar -cf - .) | (cd {repo} && tar -xf -)\n\
     rm -rf /home/agent/.scsh-clone\n\
     cd {repo}\n\
     git rev-parse --verify origin/main >/dev/null 2>&1 || {{ echo \"scsh: origin/main missing after git transport clone (point local main at the review base)\" >&2; exit 1; }}\n\
     cur=$(git rev-parse --abbrev-ref HEAD)\n\
     for ref in $(git for-each-ref --format='%(refname:short)' refs/remotes/origin); do\n\
       branch=${{ref#origin/}}\n\
       [ \"$branch\" = HEAD ] && continue\n\
       [ \"$branch\" = \"$cur\" ] && continue\n\
       git branch --force \"$branch\" \"origin/$branch\" >/dev/null 2>&1 || true\n\
     done\n",
    host_shell = GIT_TRANSPORT_HOST_SHELL,
    host_guard = GIT_TRANSPORT_HOST_GUARD,
    port = GIT_TRANSPORT_PORT_ENV,
    repo = AGENT_REPO,
  );
  if push_commits {
    script.push_str(&format!(
      "git config user.email {}\ngit config user.name {}\n",
      shell_quote(commit_email),
      shell_quote(commit_name),
    ));
  }
  script.push_str(harness);
  if push_commits {
    script.push_str("\ngit push \"git://${host}:${SCSH_GIT_PORT}/pull.git\" HEAD");
  }
  script
}

fn git_ok(dir: &Path, args: &[&str]) -> bool {
  use std::process::Command;
  Command::new("git")
    .arg("-C")
    .arg(dir)
    .args(args)
    .stdout(std::process::Stdio::null())
    .stderr(std::process::Stdio::null())
    .status()
    .map(|s| s.success())
    .unwrap_or(false)
}

fn git_bare_ok(bare: &Path, args: &[&str]) -> bool {
  use std::process::Command;
  Command::new("git")
    .arg("--git-dir")
    .arg(bare)
    .args(args)
    .stdout(std::process::Stdio::null())
    .stderr(std::process::Stdio::null())
    .status()
    .map(|s| s.success())
    .unwrap_or(false)
}

fn git_stdout(dir: &Path, args: &[&str]) -> Option<String> {
  use std::process::Command;
  let out = Command::new("git").arg("-C").arg(dir).args(args).output().ok()?;
  out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned())
}

/// Given the lines of `git for-each-ref --format='%(refname:short)'
/// refs/remotes/origin` and the clone's current branch, return the local branch
/// names to create so every remote branch becomes a local one. `origin/HEAD`
/// (the symbolic default pointer) and the already-checked-out branch are skipped.
pub fn local_branches_to_create(for_each_ref: &str, current_branch: &str) -> Vec<String> {
  let mut out = Vec::new();
  for line in for_each_ref.lines() {
    let line = line.trim();
    let branch = match line.strip_prefix("origin/") {
      Some(b) => b,
      None => continue,
    };
    if branch == "HEAD" || branch == current_branch || branch.is_empty() {
      continue;
    }
    if !out.iter().any(|b: &String| b == branch) {
      out.push(branch.to_string());
    }
  }
  out
}

#[cfg(test)]
mod tests {
  use super::*;
  use std::ffi::OsString;
  use std::sync::atomic::{AtomicUsize, Ordering};

  static COUNTER: AtomicUsize = AtomicUsize::new(0);

  fn tmp(tag: &str) -> PathBuf {
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
    let mut p = std::env::temp_dir();
    p.push(format!("scsh-ut-{tag}-{}-{nanos}-{n}", std::process::id()));
    std::fs::create_dir_all(&p).unwrap();
    p
  }

  #[cfg(unix)]
  fn make_exec(p: &Path) {
    use std::os::unix::fs::PermissionsExt;
    std::fs::write(p, "#!/bin/sh\n").unwrap();
    let mut perms = std::fs::metadata(p).unwrap().permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(p, perms).unwrap();
  }

  #[test]
  fn candidates_depend_on_os() {
    assert_eq!(runtime_candidates(true), &["container", "docker", "podman"]);
    assert_eq!(runtime_candidates(false), &["docker", "podman"]);
  }

  #[cfg(unix)]
  #[test]
  fn which_in_finds_executable_only() {
    let d = tmp("which");
    let exe = d.join("mytool");
    make_exec(&exe);
    let plain = d.join("notexe");
    std::fs::write(&plain, "data").unwrap();
    let path = OsString::from(d.to_str().unwrap());
    assert_eq!(which_in("mytool", &path), Some(exe));
    assert_eq!(which_in("notexe", &path), None);
    assert_eq!(which_in("missing", &path), None);
  }

  #[cfg(unix)]
  #[test]
  fn detect_prefers_docker_on_linux() {
    let d = tmp("detect-linux");
    make_exec(&d.join("docker"));
    make_exec(&d.join("podman"));
    let path = OsString::from(d.to_str().unwrap());
    assert_eq!(detect_runtime_in(false, &path).unwrap().name, "docker");
  }

  #[cfg(unix)]
  #[test]
  fn detect_falls_back_to_podman() {
    let d = tmp("detect-podman");
    make_exec(&d.join("podman"));
    let path = OsString::from(d.to_str().unwrap());
    assert_eq!(detect_runtime_in(false, &path).unwrap().name, "podman");
  }

  #[cfg(unix)]
  #[test]
  fn detect_prefers_apple_container_on_macos() {
    let d = tmp("detect-macos");
    make_exec(&d.join("container"));
    make_exec(&d.join("docker"));
    let path = OsString::from(d.to_str().unwrap());
    assert_eq!(detect_runtime_in(true, &path).unwrap().name, "container");
  }

  #[cfg(unix)]
  #[test]
  fn detect_none_when_empty() {
    let d = tmp("detect-empty");
    let path = OsString::from(d.to_str().unwrap());
    assert!(detect_runtime_in(false, &path).is_none());
  }

  #[test]
  fn snap_confined_paths_are_detected() {
    assert!(is_snap_confined(Path::new("/snap/bin/docker")));
    assert!(!is_snap_confined(Path::new("/usr/bin/docker")));
    assert!(!is_snap_confined(Path::new("/usr/local/bin/podman")));
  }

  #[cfg(unix)]
  #[test]
  fn detect_skips_snap_docker_for_another_runtime() {
    let d = tmp("detect-confined");
    std::fs::create_dir_all(d.join("snap/bin")).unwrap();
    std::fs::create_dir_all(d.join("bin")).unwrap();
    make_exec(&d.join("snap/bin/docker")); // snap-confined docker, first on PATH
    make_exec(&d.join("bin/podman"));
    let path = OsString::from(format!("{}:{}", d.join("snap/bin").display(), d.join("bin").display()));
    // docker is preferred by order but snap-confined → podman wins.
    assert_eq!(detect_runtime_in(false, &path).unwrap().name, "podman");
    // ...but a snap docker is still better than nothing when it's the only runtime.
    let only = OsString::from(d.join("snap/bin").to_str().unwrap());
    assert_eq!(detect_runtime_in(false, &only).unwrap().name, "docker");
  }

  #[test]
  fn image_tags_are_per_harness() {
    assert_eq!(image_tag(Harness::Opencode), "scsh-opencode:latest");
    assert_eq!(image_tag(Harness::Claude), "scsh-claude:latest");
  }

  #[test]
  fn dockerfile_has_shared_base_and_two_harness_targets() {
    let df = dockerfile();
    assert!(df.contains("FROM debian:bookworm-slim AS scsh-base"));
    assert!(df.contains("FROM scsh-base AS scsh-opencode"));
    assert!(df.contains("FROM scsh-base AS scsh-claude"));
    assert!(df.contains("npm install -g opencode-ai"));
    assert!(df.contains("npm install -g @anthropic-ai/claude-code"));
    assert!(!df.contains("CMD ["));
    assert!(df.contains("ENV SCSH_RUN_LOG=/home/agent/repo/tmp/scsh-run.log"));
    assert!(df.contains("ENV SCSH=1"));
  }

  #[test]
  fn dockerfile_opencode_stage_has_unattended_env() {
    let df = dockerfile();
    assert!(df.contains("ENV OPENCODE_YOLO=true"));
    assert!(df.contains("opencode --version"));
  }

  #[test]
  fn dockerfile_claude_stage_verifies_cli() {
    assert!(dockerfile().contains("claude --version"));
  }

  #[test]
  fn dockerfile_bakes_the_toolchain_and_excludes_java() {
    let df = dockerfile();
    for tool in [
      "python3",
      "python3-venv",
      "perl",
      "gawk",
      "build-essential",
      "pkg-config",
      "cmake",
      "jq",
      "sqlite3",
      "postgresql-client",
      "protobuf-compiler",
      "shellcheck",
      "git-lfs",
      "openssh-client",
      "iputils-ping",
      "traceroute",
      "netcat-openbsd",
      "astral-sh/uv",
      "mikefarah/yq",
      "dl.k8s.io",
      "cli.github.com",
      "go.dev/dl",
      "sh.rustup.rs",
      "awscli-exe-linux",
      "google-cloud-cli",
    ] {
      assert!(df.contains(tool), "image should install {tool}");
    }
    // Java is deliberately NOT installed (see the README).
    let lower = df.to_lowercase();
    assert!(!lower.contains("openjdk") && !lower.contains("-jdk") && !lower.contains("-jre"), "no Java by design");
    // UTF-8 locale + the builder host's timezone (a build arg).
    assert!(df.contains("ENV LANG=C.UTF-8"));
    assert!(df.contains("ARG TZ=UTC") && df.contains("ENV TZ=${TZ}"));
    // The Go/Rust toolchains the agent uses are on PATH.
    assert!(df.contains("/usr/local/go/bin") && df.contains("/usr/local/cargo/bin"));
  }

  #[test]
  fn dockerfile_is_platform_agnostic() {
    let df = dockerfile();
    // Every architecture-specific layer resolves the target arch at build time rather than
    // hardcoding one — uv/yq/kubectl/gh, Go, AWS, and gcloud each detect it.
    assert!(
      df.matches("dpkg --print-architecture").count() >= 4,
      "each arch-specific layer must resolve arch at build time"
    );
    // Both architecture families are mapped (Debian arch + the vendors' arch spellings).
    for token in ["amd64", "arm64", "x86_64", "aarch64"] {
      assert!(df.contains(token), "arch mapping must cover {token}");
    }
    // gcloud's arm tarball is spelled `-arm`, not `-arm64`.
    assert!(df.contains("google-cloud-cli-linux-${gclarch}"), "gcloud download must be arch-parameterized");
    // No download URL may pin a single architecture.
    for bad in [
      "uv-x86_64-unknown-linux-gnu",
      "yq_linux_amd64",
      "linux/amd64/kubectl",
      "linux-amd64.tar.gz",
      "awscli-exe-linux-x86_64.zip",
      "google-cloud-cli-linux-x86_64.tar.gz",
    ] {
      assert!(!df.contains(bad), "download URL must not hardcode an architecture: {bad}");
    }
  }

  #[test]
  fn dockerfile_matches_the_path_constants() {
    // The embedded Dockerfile is the source of truth, but it must stay consistent with the
    // Rust-side constants other code uses (the repo mount/WORKDIR, the XDG data dir scsh drops
    // the credential into, and the per-run log path).
    let df = dockerfile();
    assert!(df.contains(&format!("WORKDIR {AGENT_REPO}")), "WORKDIR must match AGENT_REPO");
    assert!(
      df.contains(&format!("ENV XDG_DATA_HOME={AGENT_REPO}/{AGENT_XDG_DATA_REL}")),
      "XDG_DATA_HOME must match AGENT_REPO/AGENT_XDG_DATA_REL"
    );
    assert!(
      df.contains(&format!("ENV {RUN_LOG_VAR}={AGENT_REPO}/{RUN_LOG_REL}")),
      "Dockerfile run-log ENV must match RUN_LOG_VAR and RUN_LOG_REL"
    );
  }

  #[test]
  fn dockerfile_keeps_home_separate_from_the_repo_mount() {
    // The repo is mounted at /home/agent/repo while $HOME stays /home/agent, so the harness's
    // home-dir scratch (caches/config) never lands in the cloned repo's working tree.
    let df = dockerfile();
    assert!(df.contains("ENV HOME=/home/agent"), "HOME must be the agent's home");
    assert!(df.contains(&format!("WORKDIR {AGENT_REPO}")));
    assert_ne!("/home/agent", AGENT_REPO, "the mount must not be the home dir");
    assert!(AGENT_REPO.starts_with("/home/agent/"), "the repo mount lives under the home dir");
    // The forwarded credential and the run log both live under the gitignored tmp/.
    assert!(AGENT_XDG_DATA_REL.starts_with("tmp/") && RUN_LOG_REL.starts_with("tmp/"));
  }

  #[test]
  fn dockerfile_creates_agent_user_and_runs_as_it() {
    let df = dockerfile();
    assert!(df.contains("ARG AGENT_UID=1000"));
    assert!(df.contains("ARG AGENT_GID=1000"));
    assert!(df.contains("WORKDIR /home/agent/repo"));
    assert!(df.contains("\nUSER agent\n"));
    // The agent user is created before the image switches to it.
    let agent_at = df.find("-d /home/agent").expect("agent-user layer");
    let user_at = df.find("\nUSER agent\n").expect("a USER layer");
    assert!(agent_at < user_at, "the agent user must exist before USER agent");
  }

  #[test]
  fn harness_command_builds_opencode_invocation() {
    let cmd = harness_command_verbose(Harness::Opencode, Some("openai/gpt-5.5"), "add", "tmp/add.json", true);
    assert!(cmd.starts_with("opencode -m openai/gpt-5.5"));
    assert!(cmd.contains(" --print-logs --log-level INFO run "));
    assert!(cmd.contains("run skill add"));
    assert!(cmd.contains("tmp/add.json"));
    assert!(cmd.contains("SCSH_RESULT"));
    assert!(cmd.contains("preloaded"));
    assert!(cmd.ends_with("2>&1 | tee \"$SCSH_RUN_LOG\""));
    let cmd = harness_command_verbose(Harness::Opencode, None, "multiply", "tmp/mul.json", true);
    assert!(cmd.starts_with("opencode --print-logs --log-level INFO run "));
    assert!(cmd.contains("tmp/mul.json"));
    let quiet = harness_command_verbose(Harness::Opencode, None, "multiply", "tmp/mul.json", false);
    assert!(quiet.starts_with("opencode run "));
    assert!(!quiet.contains("--print-logs"));
  }

  #[test]
  fn harness_command_builds_claude_invocation() {
    let cmd =
      harness_command_verbose(Harness::Claude, Some("sonnet"), "add", "tmp/add_claude_sonnet_4_6_result.json", true);
    assert!(cmd.contains(".skills/add/SKILL.md"));
    assert!(cmd.contains(" --verbose --model sonnet"));
    assert!(cmd.contains("tee \"$SCSH_RUN_LOG\""));
    let quiet = harness_command_verbose(Harness::Claude, Some("sonnet"), "add", "tmp/add.json", false);
    assert!(!quiet.contains(" --verbose"));
  }

  #[test]
  fn harness_verbose_disabled_when_scsh_quiet() {
    let key = "SCSH_QUIET";
    let prev = std::env::var_os(key);
    std::env::set_var(key, "1");
    assert!(!harness_verbose_enabled());
    match prev {
      Some(v) => std::env::set_var(key, v),
      None => std::env::remove_var(key),
    }
  }

  #[test]
  fn build_method_depends_on_runtime() {
    assert_eq!(build_method("container"), BuildMethod::ContextDir);
    assert_eq!(build_method("docker"), BuildMethod::Stdin);
    assert_eq!(build_method("podman"), BuildMethod::Stdin);
  }

  #[test]
  fn bake_definition_json_lists_every_target() {
    let df = dockerfile();
    let specs = vec![
      image_build_spec(Harness::Opencode, &df, 501, 20, "UTC"),
      image_build_spec(Harness::Claude, &df, 501, 20, "UTC"),
    ];
    let json = bake_definition_json("/tmp/ctx", &specs, 501, 20, "UTC");
    assert!(json.contains("\"scsh-opencode\""));
    assert!(json.contains("\"scsh-claude\""));
    assert!(json.contains("\"scsh-opencode:latest\""));
    assert!(json.contains("\"scsh-claude:latest\""));
    assert!(json.contains("\"/tmp/ctx\""));
  }

  #[test]
  fn build_command_bake_names_each_target() {
    let cmd = build_command_bake("docker", &["scsh-opencode".into(), "scsh-claude".into()]);
    let want: Vec<String> = vec![
      "docker".into(),
      "buildx".into(),
      "bake".into(),
      "--load".into(),
      "-f".into(),
      "-".into(),
      "scsh-opencode".into(),
      "scsh-claude".into(),
    ];
    assert_eq!(cmd, want);
  }

  #[test]
  fn image_build_fingerprint_is_stable_and_target_specific() {
    let df = dockerfile();
    let a = image_build_fingerprint(&df, "scsh-opencode", 501, 20, "UTC");
    let b = image_build_fingerprint(&df, "scsh-opencode", 501, 20, "UTC");
    let c = image_build_fingerprint(&df, "scsh-claude", 501, 20, "UTC");
    assert_eq!(a, b);
    assert_ne!(a, c);
    assert_eq!(a.len(), 64);
  }

  #[test]
  fn parse_label_from_container_inspect_json() {
    let json =
      r#"{"variants":[{"config":{"config":{"Labels":{"scsh.generated":"true","scsh.build.fingerprint":"abc123"}}}}}]"#;
    assert_eq!(parse_label_from_container_inspect(json, BUILD_FINGERPRINT_LABEL).as_deref(), Some("abc123"));
    assert!(parse_label_from_container_inspect(json, "missing").is_none());
  }

  #[test]
  fn commands_have_expected_shape() {
    let fp = image_build_fingerprint("FROM scratch", "scsh-opencode", 1006, 1007, "Europe/Berlin");
    let label = format!("{BUILD_FINGERPRINT_LABEL}={fp}");
    assert_eq!(
      build_command_stdin("docker", "scsh-opencode:latest", "scsh-opencode", 1006, 1007, "Europe/Berlin", &fp),
      vec![
        "docker".into(),
        "build".into(),
        "-t".into(),
        "scsh-opencode:latest".into(),
        "--target".into(),
        "scsh-opencode".into(),
        "--build-arg".into(),
        "AGENT_UID=1006".into(),
        "--build-arg".into(),
        "AGENT_GID=1007".into(),
        "--build-arg".into(),
        "TZ=Europe/Berlin".into(),
        "--label".into(),
        label,
        "-".into(),
      ]
    );
    assert_eq!(
      run_command(
        "docker",
        "scsh-opencode:latest",
        "/tmp/run",
        "run-s",
        &[],
        &[],
        "opencode run 'run skill s'",
        RepoMountMode::Full,
      ),
      vec![
        "docker",
        "run",
        "--rm",
        "--name",
        "run-s",
        "-v",
        "/tmp/run:/home/agent/repo",
        "scsh-opencode:latest",
        "/bin/sh",
        "-c",
        "opencode run 'run skill s'"
      ]
    );
    assert_eq!(
      run_command(
        "container",
        "scsh-opencode:latest",
        "/tmp/run",
        "run-s",
        &[],
        &[],
        "git clone",
        RepoMountMode::TmpOnly,
      ),
      vec![
        "container",
        "run",
        "--rm",
        "--name",
        "run-s",
        "-v",
        "/tmp/run/tmp:/home/agent/repo/tmp",
        "scsh-opencode:latest",
        "/bin/sh",
        "-c",
        "git clone"
      ]
    );
    assert_eq!(
      run_command(
        "podman",
        "scsh-claude:latest",
        "/tmp/run",
        "run-s",
        &[],
        &[("/home/u/.claude", "/home/agent/.claude:ro")],
        "claude -p hi",
        RepoMountMode::Full,
      ),
      vec![
        "podman",
        "run",
        "--rm",
        "--name",
        "run-s",
        "--userns=keep-id",
        "-v",
        "/home/u/.claude:/home/agent/.claude:ro",
        "-v",
        "/tmp/run:/home/agent/repo",
        "scsh-claude:latest",
        "/bin/sh",
        "-c",
        "claude -p hi"
      ]
    );
    assert_eq!(
      run_command(
        "docker",
        "scsh-opencode:latest",
        "/tmp/run",
        "run-s",
        &[],
        &[("/home/u/.local/share/opencode/auth.json", OPENCODE_AUTH_MOUNT)],
        "opencode run 'run skill s'",
        RepoMountMode::Full,
      ),
      vec![
        "docker",
        "run",
        "--rm",
        "--name",
        "run-s",
        "-v",
        "/home/u/.local/share/opencode/auth.json:/home/agent/repo/tmp/.xdg-data/opencode/auth.json",
        "-v",
        "/tmp/run:/home/agent/repo",
        "scsh-opencode:latest",
        "/bin/sh",
        "-c",
        "opencode run 'run skill s'"
      ]
    );
  }

  #[test]
  fn opencode_forward_mounts_maps_copied_tree() {
    let base = std::env::temp_dir().join(format!("scsh-opencode-forward-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&base);
    std::fs::create_dir_all(base.join("xdg/opencode")).unwrap();
    std::fs::create_dir_all(base.join("config/opencode")).unwrap();
    std::fs::write(base.join("xdg/opencode/auth.json"), "{}").unwrap();
    std::fs::write(base.join("config/opencode/opencode.json"), "{}").unwrap();
    let mounts = opencode_forward_mounts(&base);
    assert_eq!(mounts.len(), 2);
    assert_eq!(mounts[0].1, OPENCODE_AUTH_MOUNT);
    assert_eq!(mounts[1].1, OPENCODE_CONFIG_JSON_MOUNT);
    let _ = std::fs::remove_dir_all(&base);
  }

  #[test]
  fn opencode_host_mounts_empty_when_nothing_on_host() {
    assert!(opencode_host_mounts_from(None, None, None).is_empty());
  }

  #[test]
  fn run_command_forwards_env_as_e_flags() {
    let env = vec![("A".to_string(), "20".to_string()), ("B".to_string(), "22".to_string())];
    assert_eq!(
      run_command(
        "docker",
        "scsh-opencode:latest",
        "/tmp/run",
        "run-s",
        &env,
        &[],
        "opencode run 'run skill s'",
        RepoMountMode::Full,
      ),
      vec![
        "docker",
        "run",
        "--rm",
        "--name",
        "run-s",
        "-e",
        "A=20",
        "-e",
        "B=22",
        "-v",
        "/tmp/run:/home/agent/repo",
        "scsh-opencode:latest",
        "/bin/sh",
        "-c",
        "opencode run 'run skill s'"
      ]
    );
  }

  #[test]
  fn clone_command_is_a_full_local_clone() {
    assert_eq!(clone_command("/repo", "/tmp/dst"), vec!["git", "clone", "/repo", "/tmp/dst"]);
  }

  #[test]
  fn fsck_command_checks_clone_integrity() {
    assert_eq!(fsck_command("/tmp/dst"), vec!["git", "-C", "/tmp/dst", "fsck", "--no-progress"]);
  }

  #[test]
  fn uses_git_transport_on_macos_apple_container_only() {
    let prev = std::env::var("SCSH_GIT_TRANSPORT").ok();
    std::env::remove_var("SCSH_GIT_TRANSPORT");
    if cfg!(target_os = "macos") {
      assert!(uses_git_transport("container"));
    } else {
      assert!(!uses_git_transport("container"));
    }
    assert!(!uses_git_transport("docker"));
    std::env::set_var("SCSH_GIT_TRANSPORT", "0");
    if cfg!(target_os = "macos") {
      assert!(uses_git_transport("container"), "Apple Container always uses git transport");
    } else {
      assert!(!uses_git_transport("container"));
    }
    std::env::set_var("SCSH_GIT_TRANSPORT", "1");
    assert!(uses_git_transport("docker"));
    match prev {
      Some(v) => std::env::set_var("SCSH_GIT_TRANSPORT", v),
      None => std::env::remove_var("SCSH_GIT_TRANSPORT"),
    }
  }

  #[test]
  fn push_transport_refs_maps_origin_branches_to_heads() {
    use std::process::Command;
    let tmp = std::env::temp_dir().join(format!("scsh-push-transport-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&tmp);
    std::fs::create_dir_all(&tmp).unwrap();
    let root = tmp.join("root");
    let bare = tmp.join("bare.git");
    Command::new("git").args(["init", "-q"]).arg(&root).status().unwrap();
    Command::new("git").args(["-C"]).arg(&root).args(["config", "user.email", "t@example.com"]).status().unwrap();
    Command::new("git").args(["-C"]).arg(&root).args(["config", "user.name", "t"]).status().unwrap();
    std::fs::write(root.join("f"), "x").unwrap();
    Command::new("git").args(["-C"]).arg(&root).args(["add", "f"]).status().unwrap();
    Command::new("git").args(["-C"]).arg(&root).args(["commit", "-qm", "init"]).status().unwrap();
    Command::new("git").args(["-C"]).arg(&root).args(["branch", "-M", "main"]).status().unwrap();
    Command::new("git")
      .args(["-C"])
      .arg(&root)
      .args(["remote", "add", "origin", "https://example.invalid/scsh.git"])
      .status()
      .unwrap();
    Command::new("git")
      .args(["-C"])
      .arg(&root)
      .args(["update-ref", "refs/remotes/origin/main", "HEAD"])
      .status()
      .unwrap();
    std::fs::write(root.join("f"), "y").unwrap();
    Command::new("git").args(["-C"]).arg(&root).args(["add", "f"]).status().unwrap();
    Command::new("git").args(["-C"]).arg(&root).args(["commit", "-qm", "feature"]).status().unwrap();
    Command::new("git").args(["-C"]).arg(&root).args(["checkout", "-q", "-b", "feature"]).status().unwrap();
    push_transport_refs(&root, &bare).unwrap();
    let show = Command::new("git").args(["-C"]).arg(&bare).args(["show-ref"]).output().unwrap();
    let refs = String::from_utf8_lossy(&show.stdout);
    assert!(refs.contains("refs/heads/main"), "expected refs/heads/main in bare, got:\n{refs}");
    assert!(refs.contains("refs/heads/feature"), "expected feature branch in bare, got:\n{refs}");
    assert!(!refs.contains("refs/remotes/origin/main"), "bare should not store remote-tracking refs:\n{refs}");
    let _ = std::fs::remove_dir_all(&tmp);
  }

  #[test]
  fn push_transport_refs_uses_local_main_not_stale_origin() {
    use std::process::Command;
    let tmp = std::env::temp_dir().join(format!("scsh-push-main-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&tmp);
    std::fs::create_dir_all(&tmp).unwrap();
    let root = tmp.join("root");
    let bare = tmp.join("bare.git");
    let work = tmp.join("work");
    Command::new("git").args(["init", "-q"]).arg(&root).status().unwrap();
    Command::new("git").args(["-C"]).arg(&root).args(["config", "user.email", "t@example.com"]).status().unwrap();
    Command::new("git").args(["-C"]).arg(&root).args(["config", "user.name", "t"]).status().unwrap();
    std::fs::write(root.join("f"), "stale").unwrap();
    Command::new("git").args(["-C"]).arg(&root).args(["add", "f"]).status().unwrap();
    Command::new("git").args(["-C"]).arg(&root).args(["commit", "-qm", "stale"]).status().unwrap();
    let stale = Command::new("git").args(["-C"]).arg(&root).args(["rev-parse", "HEAD"]).output().unwrap();
    let stale = String::from_utf8_lossy(&stale.stdout).trim().to_string();
    std::fs::write(root.join("f"), "base").unwrap();
    Command::new("git").args(["-C"]).arg(&root).args(["add", "f"]).status().unwrap();
    Command::new("git").args(["-C"]).arg(&root).args(["commit", "-qm", "base"]).status().unwrap();
    let base_sha = Command::new("git").args(["-C"]).arg(&root).args(["rev-parse", "HEAD"]).output().unwrap();
    let base_sha = String::from_utf8_lossy(&base_sha.stdout).trim().to_string();
    Command::new("git").args(["-C"]).arg(&root).args(["branch", "-M", "main"]).status().unwrap();
    Command::new("git")
      .args(["-C"])
      .arg(&root)
      .args(["remote", "add", "origin", "https://example.invalid/scsh.git"])
      .status()
      .unwrap();
    Command::new("git")
      .args(["-C"])
      .arg(&root)
      .args(["update-ref", "refs/remotes/origin/main", &stale])
      .status()
      .unwrap();
    std::fs::write(root.join("f"), "feature").unwrap();
    Command::new("git").args(["-C"]).arg(&root).args(["add", "f"]).status().unwrap();
    Command::new("git").args(["-C"]).arg(&root).args(["commit", "-qm", "feature"]).status().unwrap();
    Command::new("git").args(["-C"]).arg(&root).args(["checkout", "-q", "-b", "feature"]).status().unwrap();
    Command::new("git").args(["-C"]).arg(&root).args(["branch", "-f", "main", &base_sha]).status().unwrap();
    push_transport_refs(&root, &bare).unwrap();
    Command::new("git").args(["clone", "-q"]).arg(&bare).arg(&work).status().unwrap();
    let origin_main = Command::new("git").args(["-C"]).arg(&work).args(["rev-parse", "origin/main"]).output().unwrap();
    let origin_main = String::from_utf8_lossy(&origin_main.stdout).trim().to_string();
    assert_eq!(origin_main, base_sha, "origin/main must match force-updated local main");
    assert_ne!(origin_main, stale, "must not use stale refs/remotes/origin/main");
    let _ = std::fs::remove_dir_all(&tmp);
  }

  #[test]
  fn git_transport_entry_clones_before_harness() {
    let entry = git_transport_entry("echo hi", false, "bot", "bot@example.com");
    assert!(entry.contains("ip -4 route show default"));
    assert!(entry.contains("git clone"));
    assert!(entry.contains("transport.git"));
    assert!(entry.contains("origin/main missing after git transport clone"));
    assert!(entry.contains("echo hi"));
    assert!(!entry.contains("pull.git"));
    let entry = git_transport_entry("echo hi", true, "bot", "bot@example.com");
    assert!(entry.contains("pull.git"));
    assert!(entry.contains("user.email"));
  }

  #[test]
  fn opencode_model_provider_is_first_path_segment() {
    assert_eq!(opencode_model_provider("openai/gpt-5.5"), "openai");
    assert_eq!(opencode_model_provider("nebius-glm/zai-org/GLM-5.2"), "nebius-glm");
    assert_eq!(opencode_model_provider("standalone"), "standalone");
  }

  #[test]
  fn opencode_providers_for_models_dedupes_and_sorts() {
    let models = std::collections::HashSet::from([
      "openai/gpt-5.5".into(),
      "openai/gpt-5.4-mini-fast".into(),
      "nebius-glm/zai-org/GLM-5.2".into(),
    ]);
    assert_eq!(opencode_providers_for_models(&models), vec!["nebius-glm".to_string(), "openai".to_string()]);
  }

  #[test]
  fn requested_opencode_models_collects_explicit_models_from_selection() {
    let skills = vec![
      crate::config::ResolvedInvocation {
        name: "a".into(),
        skill_source: "add".into(),
        harness: Harness::Opencode,
        model: Some("openai/gpt-5.5".into()),
        profile: None,
        commits: false,
        timeout: None,
        env: vec![],
        result: "tmp/a.json".into(),
      },
      crate::config::ResolvedInvocation {
        name: "b".into(),
        skill_source: "add".into(),
        harness: Harness::Claude,
        model: Some("sonnet".into()),
        profile: None,
        commits: false,
        timeout: None,
        env: vec![],
        result: "tmp/b.json".into(),
      },
      crate::config::ResolvedInvocation {
        name: "c".into(),
        skill_source: "add".into(),
        harness: Harness::Opencode,
        model: None,
        profile: None,
        commits: false,
        timeout: None,
        env: vec![],
        result: "tmp/c.json".into(),
      },
    ];
    let set = requested_opencode_models(&skills);
    assert_eq!(set.len(), 1);
    assert!(set.contains("openai/gpt-5.5"));
  }

  #[test]
  fn parse_opencode_models_collects_trimmed_lines() {
    let set = parse_opencode_models("openai/gpt-5.5\n\nnebius-glm/zai-org/GLM-5.2\n");
    assert_eq!(set.len(), 2);
    assert!(set.contains("openai/gpt-5.5"));
    assert!(set.contains("nebius-glm/zai-org/GLM-5.2"));
  }

  #[test]
  fn opencode_model_probe_checks_listed_models() {
    let probe = OpencodeModelProbe { available: Some(std::collections::HashSet::from(["openai/gpt-5.5".into()])) };
    assert!(probe.check_model("openai/gpt-5.5").is_ok());
    let err = probe.check_model("openai/other").unwrap_err();
    assert!(err.contains("openai/other"));
    assert!(err.contains("opencode models"));
  }

  #[test]
  fn opencode_model_probe_skips_when_not_loaded() {
    let probe = OpencodeModelProbe { available: None };
    assert!(probe.check_model("any/model").is_ok());
  }

  #[test]
  fn opencode_model_probe_rejects_when_model_list_empty() {
    let probe = OpencodeModelProbe { available: Some(std::collections::HashSet::new()) };
    assert!(probe.check_model("openai/anything").is_err());
  }

  #[test]
  fn opencode_model_probe_for_selected_skips_without_explicit_models() {
    let skills = vec![crate::config::ResolvedInvocation {
      name: "add".into(),
      skill_source: "add".into(),
      harness: Harness::Opencode,
      model: None,
      profile: None,
      commits: false,
      timeout: None,
      env: vec![],
      result: "tmp/add.json".into(),
    }];
    let probe = OpencodeModelProbe::for_selected(&skills);
    assert!(probe.check_model("openai/anything").is_ok());
  }

  #[test]
  fn claude_container_auth_accepts_oauth_token_env() {
    let key = CLAUDE_OAUTH_TOKEN_ENV;
    let prev = std::env::var_os(key);
    std::env::set_var(key, "test-token");
    assert!(claude_container_auth_ready());
    match prev {
      Some(v) => std::env::set_var(key, v),
      None => std::env::remove_var(key),
    }
  }

  #[test]
  fn check_claude_harness_errors_without_token_or_credentials_file() {
    let key = CLAUDE_OAUTH_TOKEN_ENV;
    let prev = std::env::var_os(key);
    std::env::remove_var(key);
    let err = check_harness_host(Harness::Claude).unwrap_err();
    assert!(err.contains("CLAUDE_CODE_OAUTH_TOKEN"));
    assert!(err.contains("setup-token"));
    match prev {
      Some(v) => std::env::set_var(key, v),
      None => std::env::remove_var(key),
    }
  }

  #[test]
  fn utc_timestamp_formats_known_epochs() {
    assert_eq!(format_utc_timestamp(0), "19700101-000000");
    assert_eq!(format_utc_timestamp(1_700_000_000), "20231114-221320");
  }

  #[test]
  fn run_dir_and_backup_names() {
    assert_eq!(run_dir_name(1_700_000_000, "add", "docker"), "scsh-20231114-221320-utc-run-add");
    // skill names are sanitized for the filesystem.
    assert_eq!(run_dir_name(0, "My Skill!", "docker"), "scsh-19700101-000000-utc-run-my-skill");
    assert_eq!(backup_name("add_result.json", 1_700_000_000), "add_result.json.bak.20231114-221320-utc");
  }

  #[test]
  fn truncate_middle_keeps_ends() {
    assert_eq!(truncate_middle("abcdef", 6), "abcdef");
    assert_eq!(truncate_middle("abcdefgh", 6), "ab..gh");
    assert_eq!(truncate_middle("abcdefgh", 5), "ab..h");
  }

  #[test]
  fn apple_container_run_dir_fits_long_reviewer_names() {
    let skill = "reviewability-reviewer-opencode-glm-5.2";
    let name = apple_container_run_dir_name_with_nonce(skill, "abcdef");
    assert_eq!(name, "scsh-abcdef-run-reviewability-reviewer-opencode-glm-5.2");
    assert!(name.len() <= CONTAINER_ID_MAX_LEN);
    assert!(is_scsh_run_dir_name(&name));
  }

  #[test]
  fn apple_container_run_dir_middle_truncates_when_needed() {
    let skill = "a".repeat(80);
    let name = apple_container_run_dir_name_with_nonce(&skill, "abcdef");
    assert!(name.len() <= CONTAINER_ID_MAX_LEN);
    assert!(name.contains(".."));
    assert!(name.starts_with("scsh-abcdef-run-"));
    assert!(is_scsh_run_dir_name(&name));
  }

  #[test]
  fn is_scsh_run_dir_name_recognizes_both_formats() {
    assert!(is_scsh_run_dir_name("scsh-20231114-221320-utc-run-add"));
    assert!(is_scsh_run_dir_name("scsh-abcdef-run-add"));
    assert!(!is_scsh_run_dir_name("scsh-installskills-1-2"));
    assert!(!is_scsh_run_dir_name("scsh-abcdefg-run-add"));
  }

  #[test]
  fn branch_materialization_skips_head_and_current() {
    let refs = "origin/HEAD\norigin/main\norigin/feature-x\norigin/release\n";
    assert_eq!(local_branches_to_create(refs, "main"), vec!["feature-x", "release"]);
    // nothing to create when only HEAD and the current branch exist.
    assert!(local_branches_to_create("origin/HEAD\norigin/main\n", "main").is_empty());
  }

  #[test]
  fn shell_join_quotes_when_needed() {
    assert_eq!(shell_join(&["docker".into(), "build".into()]), "docker build");
    assert_eq!(shell_join(&["a b".into()]), "'a b'");
  }
}