File size: 59,813 Bytes
f832168
921ac44
 
a154b17
f832168
e88f3ac
 
921ac44
 
71621a0
db3606c
71621a0
 
 
 
 
 
 
 
e88f3ac
 
 
 
 
f832168
 
 
 
e88f3ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f832168
28d1903
 
 
 
 
 
f832168
 
 
 
 
 
 
 
28d1903
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f832168
 
 
 
 
 
 
71621a0
 
 
f832168
 
 
 
 
 
 
 
 
 
 
 
db3606c
f832168
28d1903
f832168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28d1903
 
 
 
 
 
 
 
f832168
 
 
71621a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f832168
 
 
 
 
 
 
 
 
 
beba61f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f832168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71621a0
 
 
 
 
 
 
 
 
 
 
 
 
f832168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28d1903
f832168
 
 
 
 
 
28d1903
f832168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28d1903
 
 
 
 
 
 
4fd59bc
28d1903
 
 
 
 
 
 
 
f832168
 
 
 
 
 
 
 
 
 
 
 
 
 
28d1903
f832168
 
 
 
 
 
 
 
 
1bfa806
 
 
 
 
f832168
 
 
db3606c
 
 
 
 
 
f832168
 
 
 
 
 
 
 
 
 
 
71621a0
 
 
db3606c
f832168
 
acee2f6
f832168
 
 
 
 
 
acee2f6
f832168
 
 
 
 
28d1903
f832168
 
e32709c
 
 
 
 
f832168
e88f3ac
e32709c
f832168
 
 
 
 
 
 
beba61f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db3606c
 
 
 
 
 
 
 
 
 
 
 
 
 
1bfa806
db3606c
 
 
 
1bfa806
 
 
 
 
 
db3606c
 
 
 
 
1bfa806
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db3606c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98fbb29
f832168
 
98fbb29
f832168
 
 
28d1903
98fbb29
f832168
 
 
 
 
 
 
 
28d1903
 
 
 
 
 
98fbb29
28d1903
 
 
 
 
 
 
 
 
 
 
 
 
 
98fbb29
28d1903
 
 
 
 
 
 
 
 
 
4fd59bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f832168
 
 
28d1903
f832168
 
 
e88f3ac
f832168
98fbb29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f832168
 
 
 
 
 
 
 
 
 
 
 
28d1903
 
 
f832168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28d1903
 
 
 
f832168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28d1903
f832168
 
 
 
 
 
 
 
 
 
 
 
e88f3ac
f832168
 
e32709c
 
 
f832168
acee2f6
 
f832168
 
 
 
 
 
 
 
 
 
71621a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f832168
 
 
 
 
a154b17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db3606c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1bfa806
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f832168
28d1903
 
 
 
 
 
f832168
 
 
 
28d1903
 
 
f832168
 
 
 
28d1903
 
 
 
 
 
 
 
 
f832168
 
 
 
 
 
 
 
 
71621a0
f832168
 
 
 
 
 
 
db3606c
f832168
28d1903
f832168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28d1903
 
 
 
 
 
 
 
f832168
 
 
e32709c
f832168
 
 
 
 
 
 
 
 
e32709c
f832168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28d1903
f832168
28d1903
f832168
 
 
 
acee2f6
f832168
 
acee2f6
28d1903
f832168
 
 
 
 
 
1bfa806
 
 
 
 
f832168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28d1903
 
 
 
 
4fd59bc
 
 
 
28d1903
 
 
 
f832168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
921ac44
f832168
 
 
 
 
 
 
 
28d1903
f832168
 
 
 
 
 
 
 
 
 
28d1903
 
 
f832168
 
 
 
 
 
 
 
71621a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f832168
e32709c
f832168
 
 
921ac44
f832168
 
 
 
 
 
 
 
 
 
28d1903
f832168
 
 
 
71621a0
 
 
f832168
 
 
 
 
921ac44
 
 
f832168
 
 
 
 
 
 
 
 
 
28d1903
f832168
 
e32709c
 
de33f30
 
e32709c
 
f832168
 
e32709c
1bfa806
f832168
 
 
 
db3606c
 
1bfa806
 
a154b17
1bfa806
 
 
 
 
 
 
 
 
db3606c
 
 
 
 
 
 
 
 
 
1bfa806
 
 
 
 
 
 
 
 
 
 
db3606c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f832168
 
98fbb29
f832168
 
98fbb29
f832168
 
 
28d1903
98fbb29
f832168
 
 
 
 
 
 
 
28d1903
 
 
 
 
 
98fbb29
28d1903
 
 
 
 
 
 
 
 
 
 
 
 
 
98fbb29
28d1903
 
 
 
 
 
 
 
 
 
4fd59bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f832168
 
 
 
 
28d1903
f832168
 
 
 
 
98fbb29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f832168
 
 
 
 
 
 
 
 
 
 
 
28d1903
 
 
f832168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28d1903
 
 
 
f832168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28d1903
f832168
 
 
 
 
 
 
 
e32709c
f832168
 
e32709c
f832168
e32709c
 
 
 
 
 
 
f832168
 
71621a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f832168
 
 
 
 
71621a0
 
f832168
 
28d1903
e32709c
 
 
 
 
 
f832168
e32709c
f832168
 
 
28d1903
 
 
f832168
de33f30
 
 
 
 
 
beba61f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f832168
 
 
 
 
 
 
 
 
 
 
 
 
 
921ac44
f832168
 
921ac44
f832168
 
 
 
 
 
 
921ac44
 
f832168
921ac44
 
 
 
 
 
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
import os
import shutil
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path

import pytest

FCC_COMMANDS = (
    "fcc-desktop",
    "fcc-server",
    "fcc-claude",
    "fcc-codex",
    "fcc-pi",
    "fcc-init",
    "free-claude-code",
)


def _repo_root() -> Path:
    return Path(__file__).resolve().parents[2]


def _write_executable(path: Path, text: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text, encoding="utf-8")
    path.chmod(0o755)


def _braced_body(text: str, declaration: str) -> str:
    start = text.index(declaration)
    brace_start = text.index("{", start)
    depth = 0
    for index, char in enumerate(text[brace_start:], start=brace_start):
        if char == "{":
            depth += 1
        elif char == "}":
            depth -= 1
            if depth == 0:
                return text[brace_start + 1 : index]
    raise AssertionError(f"Unclosed function body for {declaration}")


def _posix_command(name: str) -> str:
    help_output = (
        '    echo "  --extension, -e <path>  Load an extension"\n'
        '    echo "  --models <patterns>     Scope models"'
        if name == "pi"
        else "    :"
    )
    return f"""#!/bin/sh
echo "{name}:$*" >> "$CALL_LOG"
if [ "$FAIL_STEP" = "{name}-verify" ]; then
    exit 31
fi
if [ "${{1:-}}" = "--version" ]; then
    echo "{name} 1.0.0"
fi
if [ "${{1:-}}" = "--help" ]; then
{help_output}
fi
"""


def _posix_npm_command() -> str:
    return """#!/bin/sh
echo "npm:$*" >> "$CALL_LOG"
if [ "${1:-}" = "prefix" ] && [ "${2:-}" = "-g" ]; then
    printf '%s\n' "$FAKE_NPM_PREFIX"
    exit 0
fi
if [ "${1:-}" = "config" ] && [ "${2:-}" = "get" ] && [ "${3:-}" = "prefix" ]; then
    printf '%s\n' "$FAKE_NPM_PREFIX"
    exit 0
fi
exit 71
"""


def _posix_uv_command(version: str) -> str:
    return f"""#!/bin/sh
echo "uv:$*" >> "$CALL_LOG"
if [ "${{1:-}}" = "--version" ]; then
    if [ "${{FCC_RUNNING_PHASE:-}}" = "late" ]; then
        : > "$FCC_PROCESS_MARKER"
    fi
    if [ "$FAIL_STEP" = "uv-verify" ]; then
        exit 32
    fi
    echo "uv {version}"
    exit 0
fi
if [ "${{1:-}}" = "tool" ] && [ "${{2:-}}" = "install" ]; then
    if [ "$FAIL_STEP" = "fcc-install" ]; then
        exit 33
    fi
    mkdir -p "$FAKE_TOOL_BIN"
    cp "$FAKE_FIXTURES/fcc-command.sh" "$FAKE_TOOL_BIN/fcc-server"
    cp "$FAKE_FIXTURES/fcc-command.sh" "$FAKE_TOOL_BIN/fcc-desktop"
    cp "$FAKE_FIXTURES/fcc-command.sh" "$FAKE_TOOL_BIN/fcc-claude"
    cp "$FAKE_FIXTURES/fcc-command.sh" "$FAKE_TOOL_BIN/fcc-pi"
    if [ "$FAIL_STEP" != "fcc-missing" ]; then
        cp "$FAKE_FIXTURES/fcc-command.sh" "$FAKE_TOOL_BIN/fcc-codex"
    fi
    chmod +x "$FAKE_TOOL_BIN"/fcc-*
    exit 0
fi
if [ "${{1:-}}" = "tool" ] && [ "${{2:-}}" = "update-shell" ]; then
    if [ "$FAIL_STEP" = "path-update" ]; then
        exit 34
    fi
    exit 0
fi
if [ "${{1:-}}" = "tool" ] && [ "${{2:-}}" = "dir" ] && [ "${{3:-}}" = "--bin" ]; then
    printf '%s\n' "$FAKE_TOOL_BIN"
    exit 0
fi
exit 35
"""


@dataclass
class PosixHarness:
    root: Path
    bin_dir: Path
    fixtures: Path
    tool_bin: Path
    log: Path
    env: dict[str, str]

    def add_client(self, name: str) -> None:
        _write_executable(self.bin_dir / name, _posix_command(name))

    def add_unrelated_pi(self) -> None:
        _write_executable(self.bin_dir / "pi", _posix_command("unrelated-pi"))

    def add_npm_prefix(self, prefix: Path) -> None:
        prefix.mkdir(parents=True)
        self.env["FAKE_NPM_PREFIX"] = str(prefix)
        _write_executable(self.bin_dir / "npm", _posix_npm_command())

    def add_uv(self, version: str) -> None:
        _write_executable(self.bin_dir / "uv", _posix_uv_command(version))

    def use_process_list_fallback(self, process_line: str) -> None:
        fallback_bin = self.root / "fallback-bin"
        fallback_bin.mkdir()
        _write_executable(
            fallback_bin / "ps",
            """#!/bin/sh
printf '%s\n' "$FCC_PS_OUTPUT"
""",
        )
        awk = shutil.which("awk", path=self.env["PATH"])
        if awk is None:
            pytest.skip("awk is required for the POSIX process fallback scenario")
        shutil.copy2(awk, fallback_bin / "awk")
        self.env["FCC_PS_OUTPUT"] = process_line
        self.env["PATH"] = str(fallback_bin)

    def run(self, *args: str, fail_step: str = "") -> subprocess.CompletedProcess[str]:
        env = self.env | {"FAIL_STEP": fail_step}
        return subprocess.run(
            ["/bin/sh", str(_repo_root() / "scripts" / "install.sh"), *args],
            check=False,
            capture_output=True,
            text=True,
            env=env,
        )

    def run_interactive(
        self,
        answers: str,
        *args: str,
        fail_step: str = "",
    ) -> subprocess.CompletedProcess[str]:
        import errno
        import pty
        import select
        import time

        env = self.env | {
            "FAIL_STEP": fail_step,
            "FCC_INSTALLER": str(_repo_root() / "scripts" / "install.sh"),
        }
        command = [
            "/bin/sh",
            "-c",
            'cat "$FCC_INSTALLER" | /bin/sh -s -- "$@"',
            "fcc-installer",
            *args,
        ]
        fork = vars(pty)["fork"]
        wait_without_blocking = vars(os)["WNOHANG"]
        child_pid, master_fd = fork()
        if child_pid == 0:
            os.execve(command[0], command, env)

        output = bytearray()
        status: int | None = None
        deadline = time.monotonic() + 30
        try:
            os.write(master_fd, answers.encode())
            while status is None:
                readable, _, _ = select.select([master_fd], [], [], 0.1)
                if readable:
                    try:
                        output.extend(os.read(master_fd, 65536))
                    except OSError as error:
                        if error.errno != errno.EIO:
                            raise

                waited_pid, wait_status = os.waitpid(child_pid, wait_without_blocking)
                if waited_pid == child_pid:
                    status = wait_status
                elif time.monotonic() >= deadline:
                    os.kill(child_pid, 9)
                    os.waitpid(child_pid, 0)
                    raise AssertionError("Interactive installer did not finish")

            while True:
                readable, _, _ = select.select([master_fd], [], [], 0)
                if not readable:
                    break
                try:
                    output.extend(os.read(master_fd, 65536))
                except OSError as error:
                    if error.errno == errno.EIO:
                        break
                    raise
        finally:
            os.close(master_fd)

        assert status is not None
        return subprocess.CompletedProcess(
            command,
            os.waitstatus_to_exitcode(status),
            output.decode(errors="replace"),
            "",
        )

    def calls(self) -> list[str]:
        if not self.log.exists():
            return []
        return self.log.read_text(encoding="utf-8").splitlines()


@pytest.fixture
def posix_harness(tmp_path: Path) -> PosixHarness:
    if os.name == "nt":
        pytest.skip("POSIX installer scenarios run on POSIX hosts")

    bin_dir = tmp_path / "bin"
    fixtures = tmp_path / "fixtures"
    tool_bin = tmp_path / "tool-bin"
    home = tmp_path / "home"
    log = tmp_path / "calls.log"
    for path in (bin_dir, fixtures, tool_bin, home):
        path.mkdir(parents=True)

    _write_executable(
        bin_dir / "pgrep",
        """#!/bin/sh
[ -n "${FCC_RUNNING_COMMAND:-}" ] || exit 1
if [ "${FCC_RUNNING_PHASE:-early}" = "late" ] && [ ! -e "$FCC_PROCESS_MARKER" ]; then
    exit 1
fi
case "$*" in
    *"$FCC_RUNNING_COMMAND"*) printf '4242\n'; exit 0 ;;
    *) exit 1 ;;
esac
""",
    )
    _write_executable(
        bin_dir / "curl",
        """#!/bin/sh
url=""
output=""
while [ "$#" -gt 0 ]; do
    case "$1" in
        -o)
            shift
            output=$1
            ;;
        http*)
            url=$1
            ;;
    esac
    shift
done
echo "download:$url" >> "$CALL_LOG"
case "$url:$FAIL_STEP" in
    *claude.ai*:claude-download|*chatgpt.com*:codex-download|*pi.dev*:pi-download|*astral.sh*:uv-download)
        exit 41
        ;;
esac
case "$url" in
    *claude.ai*) source="$FAKE_FIXTURES/claude-installer.sh" ;;
    *chatgpt.com*) source="$FAKE_FIXTURES/codex-installer.sh" ;;
    *pi.dev*) source="$FAKE_FIXTURES/pi-installer.sh" ;;
    *astral.sh*) source="$FAKE_FIXTURES/uv-installer.sh" ;;
    *) exit 42 ;;
esac
cp "$source" "$output"
""",
    )
    _write_executable(
        fixtures / "claude-installer.sh",
        """#!/bin/sh
echo "claude-install" >> "$CALL_LOG"
[ "$FAIL_STEP" = "claude-install" ] && exit 21
mkdir -p "$HOME/.local/bin"
cp "$FAKE_FIXTURES/claude-command.sh" "$HOME/.local/bin/claude"
chmod +x "$HOME/.local/bin/claude"
""",
    )
    _write_executable(
        fixtures / "codex-installer.sh",
        """#!/bin/sh
echo "codex-install:$CODEX_NON_INTERACTIVE" >> "$CALL_LOG"
[ "$FAIL_STEP" = "codex-install" ] && exit 22
mkdir -p "$HOME/.local/bin"
cp "$FAKE_FIXTURES/codex-command.sh" "$HOME/.local/bin/codex"
chmod +x "$HOME/.local/bin/codex"
""",
    )
    _write_executable(
        fixtures / "pi-installer.sh",
        """#!/bin/sh
echo "pi-install" >> "$CALL_LOG"
[ "$FAIL_STEP" = "pi-install" ] && exit 24
[ "$FAIL_STEP" = "pi-skip" ] && exit 0
if [ -n "${FAKE_NPM_PREFIX:-}" ]; then
    pi_bin="$FAKE_NPM_PREFIX/bin"
else
    pi_bin="$HOME/.local/bin"
fi
mkdir -p "$pi_bin"
cp "$FAKE_FIXTURES/pi-command.sh" "$pi_bin/pi"
chmod +x "$pi_bin/pi"
""",
    )
    _write_executable(
        fixtures / "uv-installer.sh",
        """#!/bin/sh
echo "uv-install" >> "$CALL_LOG"
[ "$FAIL_STEP" = "uv-install" ] && exit 23
mkdir -p "$HOME/.local/bin"
cp "$FAKE_FIXTURES/uv-command.sh" "$HOME/.local/bin/uv"
chmod +x "$HOME/.local/bin/uv"
""",
    )
    _write_executable(fixtures / "claude-command.sh", _posix_command("claude"))
    _write_executable(fixtures / "codex-command.sh", _posix_command("codex"))
    _write_executable(fixtures / "pi-command.sh", _posix_command("pi"))
    _write_executable(fixtures / "uv-command.sh", _posix_uv_command("0.11.28"))
    _write_executable(
        fixtures / "fcc-command.sh",
        """#!/bin/sh
name=${0##*/}
echo "$name:$*" >> "$CALL_LOG"
if [ "$FAIL_STEP" = "fcc-verify" ]; then
    exit 36
fi
if [ "$name" = "fcc-desktop" ] && [ "${1:-}" = "--export-icon" ]; then
    [ "$FAIL_STEP" = "desktop-icon-export" ] && exit 37
    mkdir -p "$(dirname "$2")"
    printf 'fake icon\n' > "$2"
fi
if [ "$name" = "fcc-server" ] && [ "${1:-}" = "--version" ]; then
    echo "free-claude-code 3.5.18"
fi
""",
    )
    _write_executable(
        bin_dir / "uname",
        """#!/bin/sh
printf '%s\n' "${FAKE_UNAME:-Linux}"
""",
    )

    env = os.environ.copy()
    env.update(
        {
            "PATH": f"{bin_dir}:/usr/bin:/bin",
            "HOME": str(home),
            "CALL_LOG": str(log),
            "FAKE_FIXTURES": str(fixtures),
            "FAKE_TOOL_BIN": str(tool_bin),
            "FCC_PROCESS_MARKER": str(tmp_path / "fcc-process-ready"),
            "FCC_RUNNING_COMMAND": "",
            "FCC_RUNNING_PHASE": "early",
            "FAKE_UNAME": "Linux",
            "FAIL_STEP": "",
        }
    )
    env.pop("XDG_BIN_HOME", None)
    return PosixHarness(tmp_path, bin_dir, fixtures, tool_bin, log, env)


def test_install_sh_fresh_install_is_verified(posix_harness: PosixHarness) -> None:
    result = posix_harness.run()

    assert result.returncode == 0, result.stderr
    assert "Free Claude Code is installed and verified." in result.stdout
    calls = posix_harness.calls()
    assert calls.index("claude-install") < calls.index("claude:--version")
    assert calls.index("codex-install:1") < calls.index("codex:--version")
    assert calls.index("pi-install") < calls.index("pi:--version")
    assert calls.index("uv-install") < calls.index("uv:--version")
    assert any(
        call.startswith(
            "uv:tool install --force --refresh-package free-claude-code "
            "--python 3.14.0 free-claude-code @ "
            "https://github.com/Alishahryar1/free-claude-code/archive/refs/heads/main.zip"
        )
        for call in calls
    )
    assert not any(call.startswith("git:") for call in calls)
    assert calls[-3:] == [
        "uv:tool update-shell",
        "uv:tool dir --bin",
        "fcc-server:--version",
    ]


def test_install_sh_reprompts_then_installs_only_selected_agent(
    posix_harness: PosixHarness,
) -> None:
    result = posix_harness.run_interactive("n\nn\nn\nn\ny\nn\n")

    assert result.returncode == 0, result.stdout
    assert "Select at least one coding agent." in result.stdout
    assert "Run Codex with: fcc-codex" in result.stdout
    assert "Run Claude Code with: fcc-claude" not in result.stdout
    assert "Run Pi with: fcc-pi" not in result.stdout
    calls = posix_harness.calls()
    assert "codex-install:1" in calls
    assert not any("claude.ai" in call for call in calls)
    assert not any("pi.dev" in call for call in calls)


def test_install_sh_rejects_uninstalled_only_selection(
    posix_harness: PosixHarness,
) -> None:
    result = posix_harness.run_interactive("n\nn\ny\n", fail_step="pi-skip")

    assert result.returncode != 0
    assert "No selected coding agent was installed." in result.stdout
    assert not any("astral.sh" in call for call in posix_harness.calls())


def test_install_sh_creates_native_macos_app_and_desktop_link(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.env["FAKE_UNAME"] = "Darwin"
    tool_bin = posix_harness.root / "tool's bin"
    posix_harness.env["FAKE_TOOL_BIN"] = str(tool_bin)

    result = posix_harness.run()

    assert result.returncode == 0, result.stderr
    app = posix_harness.root / "home" / "Applications" / "Free Claude Code.app"
    plist = app / "Contents" / "Info.plist"
    owner_file = app / "Contents" / ".free-claude-code-owner"
    launcher = app / "Contents" / "MacOS" / "fcc-desktop"
    icon = app / "Contents" / "Resources" / "AppIcon.icns"
    desktop_link = posix_harness.root / "home" / "Desktop" / "Free Claude Code.app"
    assert owner_file.read_text(encoding="utf-8").strip() == (
        "io.github.alishahryar1.free-claude-code"
    )
    plist_text = plist.read_text(encoding="utf-8")
    assert "<key>CFBundleIconFile</key>" in plist_text
    assert "<string>AppIcon</string>" in plist_text
    assert "<key>LSUIElement</key>" in plist_text
    assert "<key>LSMultipleInstancesProhibited</key>" in plist_text
    assert icon.read_bytes() == b"fake icon\n"
    assert launcher.stat().st_mode & 0o111
    expected_command = str(tool_bin / "fcc-desktop").replace("'", "'\\''")
    assert f"exec '{expected_command}'" in launcher.read_text(encoding="utf-8")
    assert desktop_link.is_symlink()
    assert desktop_link.readlink() == app
    assert any(
        call == f"fcc-desktop:--export-icon {icon}" for call in posix_harness.calls()
    )


def test_install_sh_stops_if_macos_icon_export_fails(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.env["FAKE_UNAME"] = "Darwin"

    result = posix_harness.run(fail_step="desktop-icon-export")

    assert result.returncode != 0
    assert "Command failed with exit code 37" in result.stderr
    assert not (
        posix_harness.root / "home" / "Desktop" / "Free Claude Code.app"
    ).exists()


def test_install_sh_rejects_unowned_macos_app_bundle(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.env["FAKE_UNAME"] = "Darwin"
    app = posix_harness.root / "home" / "Applications" / "Free Claude Code.app"
    contents = app / "Contents"
    contents.mkdir(parents=True)
    plist = contents / "Info.plist"
    plist.write_text("foreign app", encoding="utf-8")

    result = posix_harness.run()

    assert result.returncode != 0
    assert "not managed by Free Claude Code" in result.stderr
    assert plist.read_text(encoding="utf-8") == "foreign app"
    assert not (contents / ".free-claude-code-owner").exists()


def test_install_sh_preserves_unrelated_macos_desktop_link(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.env["FAKE_UNAME"] = "Darwin"
    desktop = posix_harness.root / "home" / "Desktop"
    desktop.mkdir()
    unrelated = posix_harness.root / "Unrelated.app"
    unrelated.mkdir()
    desktop_link = desktop / "Free Claude Code.app"
    desktop_link.symlink_to(unrelated, target_is_directory=True)

    result = posix_harness.run()

    assert result.returncode == 0, result.stderr
    assert "non-FCC link" in result.stdout
    assert desktop_link.readlink() == unrelated


@pytest.mark.parametrize("uv_version", ("0.11.16", "0.11.16+build.1"))
def test_install_sh_preserves_valid_existing_tools(
    posix_harness: PosixHarness,
    uv_version: str,
) -> None:
    posix_harness.add_client("claude")
    posix_harness.add_client("codex")
    posix_harness.add_client("pi")
    posix_harness.add_uv(uv_version)

    result = posix_harness.run()

    assert result.returncode == 0, result.stderr
    assert not any(call.startswith("download:") for call in posix_harness.calls())
    assert "leaving it unchanged" in result.stdout


def test_install_sh_replaces_unrelated_pi_command(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.add_client("claude")
    posix_harness.add_client("codex")
    posix_harness.add_unrelated_pi()
    posix_harness.add_uv("0.11.16")

    result = posix_harness.run()

    assert result.returncode == 0, result.stderr
    assert "is not Pi Coding Agent; installing Pi" in result.stdout
    assert "pi-install" in posix_harness.calls()


def test_install_sh_discovers_custom_pi_npm_prefix(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.add_client("claude")
    posix_harness.add_client("codex")
    posix_harness.add_npm_prefix(posix_harness.root / "custom-npm")
    posix_harness.add_uv("0.11.16")

    result = posix_harness.run()

    assert result.returncode == 0, result.stderr
    calls = posix_harness.calls()
    assert "npm:prefix -g" in calls
    assert "pi:--help" in calls
    assert "pi:--version" in calls


def test_install_sh_continues_when_pi_is_not_installed(
    posix_harness: PosixHarness,
) -> None:
    result = posix_harness.run(fail_step="pi-skip")

    assert result.returncode == 0, result.stderr
    assert "Pi was not installed; continuing without it." in result.stdout
    assert "Run Pi with: fcc-pi" not in result.stdout
    calls = posix_harness.calls()
    assert "pi-install" in calls
    assert not any(call.startswith("pi:") for call in calls)
    assert "uv-install" in calls
    assert "fcc-server:--version" in calls


def test_install_sh_continues_when_unrelated_pi_is_unchanged(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.add_unrelated_pi()

    result = posix_harness.run(fail_step="pi-skip")

    assert result.returncode == 0, result.stderr
    assert "Pi was not installed; continuing without it." in result.stdout
    assert "Run Pi with: fcc-pi" not in result.stdout
    calls = posix_harness.calls()
    assert "unrelated-pi:--help" in calls
    assert "unrelated-pi:--version" not in calls
    assert "fcc-server:--version" in calls


def test_install_sh_continues_when_pi_resolution_changes_to_unrelated_command(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.add_unrelated_pi()
    npm_prefix = posix_harness.root / "custom-npm"
    posix_harness.add_npm_prefix(npm_prefix)
    _write_executable(
        npm_prefix / "bin" / "pi",
        _posix_command("other-unrelated-pi"),
    )

    result = posix_harness.run(fail_step="pi-skip")

    assert result.returncode == 0, result.stderr
    assert "Pi was not installed; continuing without it." in result.stdout
    assert "Run Pi with: fcc-pi" not in result.stdout
    calls = posix_harness.calls()
    assert "other-unrelated-pi:--help" in calls
    assert "other-unrelated-pi:--version" not in calls
    assert "fcc-server:--version" in calls


def test_install_sh_replaces_obsolete_uv(posix_harness: PosixHarness) -> None:
    posix_harness.add_client("claude")
    posix_harness.add_client("codex")
    posix_harness.add_client("pi")
    posix_harness.add_uv("0.5.9")

    result = posix_harness.run()

    assert result.returncode == 0, result.stderr
    assert "uv 0.5.9 does not satisfy stable >=0.11.16" in result.stdout
    assert "uv-install" in posix_harness.calls()


@pytest.mark.parametrize("version", ("0.11.16-alpha.1", "0.12.0-rc.1"))
def test_install_sh_replaces_prerelease_uv(
    posix_harness: PosixHarness,
    version: str,
) -> None:
    posix_harness.add_client("claude")
    posix_harness.add_client("codex")
    posix_harness.add_client("pi")
    posix_harness.add_uv(version)

    result = posix_harness.run()

    assert result.returncode == 0, result.stderr
    assert f"uv {version} does not satisfy stable >=0.11.16" in result.stdout
    assert "uv-install" in posix_harness.calls()


@pytest.mark.parametrize(
    "failure",
    [
        "claude-download",
        "claude-install",
        "claude-verify",
        "codex-download",
        "codex-install",
        "codex-verify",
        "pi-download",
        "pi-install",
        "pi-verify",
        "uv-download",
        "uv-install",
        "uv-verify",
        "fcc-install",
        "path-update",
        "fcc-missing",
        "fcc-verify",
    ],
)
def test_install_sh_stops_without_success_on_each_failure(
    posix_harness: PosixHarness,
    failure: str,
) -> None:
    result = posix_harness.run(fail_step=failure)

    assert result.returncode != 0
    assert "Free Claude Code is installed and verified." not in result.stdout
    forbidden = {
        "claude-download": "claude-install",
        "claude-install": "claude:--version",
        "claude-verify": "chatgpt.com",
        "codex-download": "codex-install",
        "codex-install": "codex:--version",
        "codex-verify": "pi.dev",
        "pi-download": "pi-install",
        "pi-install": "pi:--version",
        "pi-verify": "astral.sh",
        "uv-download": "uv-install",
        "uv-install": "uv:--version",
        "uv-verify": "uv:tool install",
        "fcc-install": "uv:tool update-shell",
        "path-update": "uv:tool dir --bin",
        "fcc-missing": "fcc-server:--version",
    }.get(failure)
    if forbidden is not None:
        assert not any(forbidden in call for call in posix_harness.calls())


def test_install_sh_dry_run_never_executes_commands(
    posix_harness: PosixHarness,
) -> None:
    result = posix_harness.run("--dry-run")

    assert result.returncode == 0, result.stderr
    assert posix_harness.calls() == []
    assert "Dry run complete. No changes were made." in result.stdout
    assert "Free Claude Code is installed and verified." not in result.stdout


def test_install_sh_rejects_broken_existing_client_without_replacing_it(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.add_client("claude")

    result = posix_harness.run(fail_step="claude-verify")

    assert result.returncode != 0
    assert not any(call.startswith("download:") for call in posix_harness.calls())


def test_install_sh_rejects_unparseable_existing_uv(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.add_client("claude")
    posix_harness.add_client("codex")
    posix_harness.add_client("pi")
    posix_harness.add_uv("not-a-version")

    result = posix_harness.run()

    assert result.returncode != 0
    assert not any("astral.sh" in call for call in posix_harness.calls())


def test_install_sh_voice_flags_only_change_fcc_spec(
    posix_harness: PosixHarness,
) -> None:
    result = posix_harness.run("--voice-all", "--torch-backend", "cu130")

    assert result.returncode == 0, result.stderr
    assert any(
        "--torch-backend cu130 free-claude-code[voice,voice_local] @ "
        "https://github.com/Alishahryar1/free-claude-code/archive/refs/heads/main.zip"
        in call
        for call in posix_harness.calls()
    )


def test_install_sh_rejects_invalid_options_before_mutation(
    posix_harness: PosixHarness,
) -> None:
    result = posix_harness.run("--torch-backend", "cu130")

    assert result.returncode != 0
    assert posix_harness.calls() == []


@pytest.mark.parametrize("command_name", FCC_COMMANDS)
def test_install_sh_rejects_running_fcc_before_mutation(
    posix_harness: PosixHarness,
    command_name: str,
) -> None:
    posix_harness.env["FCC_RUNNING_COMMAND"] = command_name

    result = posix_harness.run()

    assert result.returncode != 0
    assert posix_harness.calls() == []
    assert f"{command_name} (PID 4242)" in result.stderr


def test_install_sh_rechecks_for_fcc_process_before_tool_replacement(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.add_client("claude")
    posix_harness.add_client("codex")
    posix_harness.add_client("pi")
    posix_harness.add_uv("0.11.16")
    posix_harness.env["FCC_RUNNING_COMMAND"] = "fcc-server"
    posix_harness.env["FCC_RUNNING_PHASE"] = "late"

    result = posix_harness.run()

    assert result.returncode != 0
    assert "fcc-server (PID 4242)" in result.stderr
    assert not any(call.startswith("uv:tool install") for call in posix_harness.calls())


def test_install_sh_ignores_similarly_named_process(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.env["FCC_RUNNING_COMMAND"] = "fcc-server-helper"

    result = posix_harness.run()

    assert result.returncode == 0, result.stderr


@pytest.mark.parametrize(
    ("command_name", "process_args"),
    (
        ("free-claude-code", "/home/user/.local/bin/free-claude-code"),
        ("fcc-server", "/usr/bin/python3 /home/user/.local/bin/fcc-server"),
    ),
)
def test_install_sh_process_fallback_reads_full_command_line(
    posix_harness: PosixHarness,
    command_name: str,
    process_args: str,
) -> None:
    posix_harness.use_process_list_fallback(f"4242 {process_args}")

    result = posix_harness.run()

    assert result.returncode != 0
    assert posix_harness.calls() == []
    assert f"{command_name} (PID 4242)" in result.stderr


def _powershells() -> tuple[str, ...]:
    candidates = (shutil.which("pwsh"), shutil.which("powershell"))
    return tuple(dict.fromkeys(path for path in candidates if path is not None))


def test_install_ps1_waits_for_gui_icon_export() -> None:
    installer = (_repo_root() / "scripts" / "install.ps1").read_text(encoding="utf-8")
    body = _braced_body(installer, "function Export-FccDesktopIcon")

    assert "Start-Process" in body
    assert "-WindowStyle Hidden" in body
    assert "-Wait" in body
    assert "-PassThru" in body
    assert "$process.ExitCode" in body


@pytest.mark.parametrize(
    "powershell",
    _powershells() or (None,),
    ids=lambda path: Path(path).name if path is not None else "unavailable",
)
def test_install_ps1_gui_icon_export_completes_before_returning(
    powershell: str | None,
    tmp_path: Path,
) -> None:
    if powershell is None or os.name != "nt":
        pytest.skip("PowerShell GUI process behavior runs on Windows hosts")

    installer = (_repo_root() / "scripts" / "install.ps1").read_text(encoding="utf-8")
    function_declarations = (
        "function Format-Argument",
        "function Format-Command",
        "function Export-FccDesktopIcon",
    )
    functions = "\n".join(
        f"{declaration} {{{_braced_body(installer, declaration)}}}"
        for declaration in function_declarations
    )
    installed_desktop_command = Path(sys.executable).with_name("fcc-desktop.exe")
    desktop_command = tmp_path / "icon-exporter.exe"
    shutil.copy2(installed_desktop_command, desktop_command)
    destination = tmp_path / "profile with spaces" / ".fcc" / "app-icon.ico"
    env = os.environ | {
        "FCC_TEST_DESKTOP_COMMAND": str(desktop_command),
        "FCC_TEST_ICON_PATH": str(destination),
    }
    script = "\n".join(
        (
            '$ErrorActionPreference = "Stop"',
            "$DryRun = $false",
            functions,
            (
                "Export-FccDesktopIcon "
                "-DesktopCommand $env:FCC_TEST_DESKTOP_COMMAND "
                "-IconPath $env:FCC_TEST_ICON_PATH"
            ),
        )
    )

    completed = subprocess.run(
        [powershell, "-NoProfile", "-Command", script],
        check=False,
        capture_output=True,
        text=True,
        env=env,
    )

    assert completed.returncode == 0, completed.stderr
    assert (
        destination.read_bytes()
        == (
            _repo_root() / "src" / "free_claude_code" / "assets" / "app-icon.ico"
        ).read_bytes()
    )


def _create_windows_shortcut(
    powershell: str,
    shortcut_path: Path,
    target_path: Path,
) -> None:
    shortcut_path.parent.mkdir(parents=True, exist_ok=True)
    env = os.environ | {
        "FCC_TEST_SHORTCUT": str(shortcut_path),
        "FCC_TEST_TARGET": str(target_path),
    }
    subprocess.run(
        [
            powershell,
            "-NoProfile",
            "-Command",
            (
                "$shell = New-Object -ComObject WScript.Shell; "
                "$shortcut = $shell.CreateShortcut($env:FCC_TEST_SHORTCUT); "
                "$shortcut.TargetPath = $env:FCC_TEST_TARGET; "
                "$shortcut.Save()"
            ),
        ],
        check=True,
        capture_output=True,
        text=True,
        env=env,
    )


def _windows_shortcut_icon(powershell: str, shortcut_path: Path) -> str:
    env = os.environ | {"FCC_TEST_SHORTCUT": str(shortcut_path)}
    completed = subprocess.run(
        [
            powershell,
            "-NoProfile",
            "-Command",
            (
                "$shell = New-Object -ComObject WScript.Shell; "
                "$shortcut = $shell.CreateShortcut($env:FCC_TEST_SHORTCUT); "
                "[Console]::Out.Write($shortcut.IconLocation)"
            ),
        ],
        check=True,
        capture_output=True,
        text=True,
        env=env,
    )
    return completed.stdout


def _batch_client(name: str) -> str:
    help_output = (
        "echo   --extension, -e ^<path^>  Load an extension\n"
        "echo   --models ^<patterns^>     Scope models"
        if name == "pi"
        else "rem no product help"
    )
    return f"""@echo off
echo {name}:%*>>"%CALL_LOG%"
if "%FAIL_STEP%"=="{name}-verify" exit /b 51
if "%1"=="--version" echo {name} 1.0.0
if "%1"=="--help" (
{help_output}
)
exit /b 0
"""


def _batch_npm() -> str:
    return r"""@echo off
echo npm:%*>>"%CALL_LOG%"
if "%1"=="prefix" if "%2"=="-g" echo %FAKE_NPM_PREFIX%& exit /b 0
if "%1"=="config" if "%2"=="get" if "%3"=="prefix" echo %FAKE_NPM_PREFIX%& exit /b 0
exit /b 71
"""


def _batch_uv(version: str) -> str:
    return rf"""@echo off
echo uv:%*>>"%CALL_LOG%"
if "%1"=="--version" goto version
if "%1"=="tool" if "%2"=="install" goto install
if "%1"=="tool" if "%2"=="update-shell" goto update_shell
if "%1"=="tool" if "%2"=="dir" if "%3"=="--bin" goto tool_bin
exit /b 59
:version
if "%FCC_RUNNING_PHASE%"=="late" type nul > "%FCC_PROCESS_MARKER%"
if "%FAIL_STEP%"=="uv-verify" exit /b 52
echo uv {version}
exit /b 0
:install
if "%FAIL_STEP%"=="fcc-install" exit /b 53
if not exist "%FAKE_TOOL_BIN%" mkdir "%FAKE_TOOL_BIN%"
copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%FAKE_TOOL_BIN%\fcc-server.cmd" >nul
copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%FAKE_TOOL_BIN%\fcc-desktop.cmd" >nul
copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%FAKE_TOOL_BIN%\fcc-claude.cmd" >nul
copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%FAKE_TOOL_BIN%\fcc-pi.cmd" >nul
if not "%FAIL_STEP%"=="fcc-missing" copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%FAKE_TOOL_BIN%\fcc-codex.cmd" >nul
exit /b 0
:update_shell
if "%FAIL_STEP%"=="path-update" exit /b 54
exit /b 0
:tool_bin
echo %FAKE_TOOL_BIN%
exit /b 0
"""


@dataclass
class PowerShellHarness:
    root: Path
    bin_dir: Path
    fixtures: Path
    tool_bin: Path
    log: Path
    env: dict[str, str]
    powershell: str
    wrapper: Path

    def add_client(self, name: str) -> None:
        _write_executable(self.bin_dir / f"{name}.cmd", _batch_client(name))

    def add_unrelated_pi(self) -> None:
        _write_executable(self.bin_dir / "pi.cmd", _batch_client("unrelated-pi"))

    def add_npm_prefix(self, prefix: Path) -> None:
        prefix.mkdir(parents=True)
        self.env["FAKE_NPM_PREFIX"] = str(prefix)
        _write_executable(self.bin_dir / "npm.cmd", _batch_npm())

    def add_uv(self, version: str) -> None:
        _write_executable(self.bin_dir / "uv.cmd", _batch_uv(version))

    def run(self, *args: str, fail_step: str = "") -> subprocess.CompletedProcess[str]:
        env = self.env | {"FAIL_STEP": fail_step}
        return subprocess.run(
            [
                self.powershell,
                "-NoProfile",
                "-ExecutionPolicy",
                "Bypass",
                "-File",
                str(self.wrapper),
                *args,
            ],
            check=False,
            capture_output=True,
            text=True,
            env=env,
        )

    def calls(self) -> list[str]:
        if not self.log.exists():
            return []
        return self.log.read_text(encoding="utf-8").splitlines()


@pytest.fixture(
    params=_powershells() or (None,),
    ids=lambda path: Path(path).name if path is not None else "unavailable",
)
def powershell_harness(
    tmp_path: Path,
    request: pytest.FixtureRequest,
) -> PowerShellHarness:
    powershell = request.param
    if powershell is None or os.name != "nt":
        pytest.skip("PowerShell installer scenarios run on Windows hosts")

    bin_dir = tmp_path / "bin"
    fixtures = tmp_path / "fixtures"
    tool_bin = tmp_path / "tool-bin"
    home = tmp_path / "home"
    local_app_data = tmp_path / "local-app-data"
    app_data = tmp_path / "app-data"
    log = tmp_path / "calls.log"
    for path in (bin_dir, fixtures, tool_bin, home, local_app_data, app_data):
        path.mkdir(parents=True)

    (fixtures / "claude-command.cmd").write_text(
        _batch_client("claude"), encoding="utf-8"
    )
    (fixtures / "codex-command.cmd").write_text(
        _batch_client("codex"), encoding="utf-8"
    )
    (fixtures / "pi-command.cmd").write_text(_batch_client("pi"), encoding="utf-8")
    (fixtures / "uv-command.cmd").write_text(_batch_uv("0.11.28"), encoding="utf-8")
    (fixtures / "fcc-command.cmd").write_text(
        """@echo off
for %%I in ("%~f0") do set "FCC_NAME=%%~nI"
echo %FCC_NAME%:%*>>"%CALL_LOG%"
if "%FAIL_STEP%"=="fcc-verify" exit /b 55
if "%FCC_NAME%"=="fcc-desktop" if "%1"=="--export-icon" if "%FAIL_STEP%"=="desktop-icon-export" exit /b 56
if "%FCC_NAME%"=="fcc-desktop" if "%1"=="--export-icon" (
    if not exist "%~dp2" mkdir "%~dp2"
    echo fake icon>"%~2"
)
if "%FCC_NAME%"=="fcc-server" if "%1"=="--version" echo free-claude-code 3.5.18
exit /b 0
""",
        encoding="utf-8",
    )
    (fixtures / "claude-installer.ps1").write_text(
        r"""if ($env:FAIL_STEP -eq "claude-install") { exit 61 }
$bin = Join-Path $env:USERPROFILE ".local\bin"
New-Item -ItemType Directory -Force -Path $bin | Out-Null
Copy-Item (Join-Path $env:FAKE_FIXTURES "claude-command.cmd") (Join-Path $bin "claude.cmd") -Force
Add-Content -LiteralPath $env:CALL_LOG -Value "claude-install"
""",
        encoding="utf-8",
    )
    (fixtures / "codex-installer.ps1").write_text(
        r"""if ($env:FAIL_STEP -eq "codex-install") { exit 62 }
$bin = Join-Path $env:LOCALAPPDATA "Programs\OpenAI\Codex\bin"
New-Item -ItemType Directory -Force -Path $bin | Out-Null
Copy-Item (Join-Path $env:FAKE_FIXTURES "codex-command.cmd") (Join-Path $bin "codex.cmd") -Force
Add-Content -LiteralPath $env:CALL_LOG -Value "codex-install:$env:CODEX_NON_INTERACTIVE"
""",
        encoding="utf-8",
    )
    (fixtures / "pi-installer.ps1").write_text(
        r"""if ($env:FAIL_STEP -eq "pi-install") { exit 64 }
if ($env:FAIL_STEP -eq "pi-skip") {
    Add-Content -LiteralPath $env:CALL_LOG -Value "pi-install"
    return
}
$bin = if ($env:FAKE_NPM_PREFIX) { $env:FAKE_NPM_PREFIX } else { Join-Path $env:APPDATA "npm" }
New-Item -ItemType Directory -Force -Path $bin | Out-Null
Copy-Item (Join-Path $env:FAKE_FIXTURES "pi-command.cmd") (Join-Path $bin "pi.cmd") -Force
Add-Content -LiteralPath $env:CALL_LOG -Value "pi-install"
""",
        encoding="utf-8",
    )
    (fixtures / "uv-installer.ps1").write_text(
        r"""if ($env:FAIL_STEP -eq "uv-install") { exit 63 }
$bin = Join-Path $env:USERPROFILE ".local\bin"
New-Item -ItemType Directory -Force -Path $bin | Out-Null
Copy-Item (Join-Path $env:FAKE_FIXTURES "uv-command.cmd") (Join-Path $bin "uv.cmd") -Force
Add-Content -LiteralPath $env:CALL_LOG -Value "uv-install"
""",
        encoding="utf-8",
    )

    wrapper = tmp_path / "run-installer.ps1"
    wrapper.write_text(
        """Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
function Invoke-RestMethod {
    [CmdletBinding()]
    param([string] $Uri, [string] $OutFile)

    Add-Content -LiteralPath $env:CALL_LOG -Value "download:$Uri"
    if (
        ($env:FAIL_STEP -eq "claude-download" -and $Uri.Contains("claude.ai")) -or
        ($env:FAIL_STEP -eq "codex-download" -and $Uri.Contains("chatgpt.com")) -or
        ($env:FAIL_STEP -eq "pi-download" -and $Uri.Contains("pi.dev")) -or
        ($env:FAIL_STEP -eq "uv-download" -and $Uri.Contains("astral.sh"))
    ) {
        throw "simulated download failure"
    }
    if ($Uri.Contains("claude.ai")) {
        $source = Join-Path $env:FAKE_FIXTURES "claude-installer.ps1"
    }
    elseif ($Uri.Contains("chatgpt.com")) {
        $source = Join-Path $env:FAKE_FIXTURES "codex-installer.ps1"
    }
    elseif ($Uri.Contains("pi.dev")) {
        $source = Join-Path $env:FAKE_FIXTURES "pi-installer.ps1"
    }
    elseif ($Uri.Contains("astral.sh")) {
        $source = Join-Path $env:FAKE_FIXTURES "uv-installer.ps1"
    }
    else {
        throw "unexpected installer URL: $Uri"
    }
    Copy-Item -LiteralPath $source -Destination $OutFile -Force
}
function Get-Process {
    [CmdletBinding()]
    param([string[]] $Name)

    if ([string]::IsNullOrWhiteSpace($env:FCC_RUNNING_COMMAND)) {
        return
    }
    if (
        $env:FCC_RUNNING_PHASE -eq "late" -and
        -not (Test-Path -LiteralPath $env:FCC_PROCESS_MARKER)
    ) {
        return
    }
    foreach ($requestedName in $Name) {
        if ($requestedName -eq $env:FCC_RUNNING_COMMAND) {
            [pscustomobject] @{ Id = 4242; ProcessName = $requestedName }
        }
    }
}
$installer = [scriptblock]::Create([IO.File]::ReadAllText($env:FCC_INSTALLER))
& $installer @args
""",
        encoding="utf-8",
    )

    system_root = os.environ["SYSTEMROOT"]
    env = os.environ.copy()
    env.update(
        {
            "PATH": os.pathsep.join(
                [str(bin_dir), str(Path(system_root) / "System32"), system_root]
            ),
            "PATHEXT": ".COM;.EXE;.BAT;.CMD",
            "USERPROFILE": str(home),
            "LOCALAPPDATA": str(local_app_data),
            "APPDATA": str(app_data),
            "CALL_LOG": str(log),
            "FAKE_FIXTURES": str(fixtures),
            "FAKE_TOOL_BIN": str(tool_bin),
            "FCC_INSTALLER": str(_repo_root() / "scripts" / "install.ps1"),
            "FCC_PROCESS_MARKER": str(tmp_path / "fcc-process-ready"),
            "FCC_RUNNING_COMMAND": "",
            "FCC_RUNNING_PHASE": "early",
            "FAIL_STEP": "",
        }
    )
    return PowerShellHarness(
        tmp_path, bin_dir, fixtures, tool_bin, log, env, powershell, wrapper
    )


def test_install_ps1_fresh_install_is_verified(
    powershell_harness: PowerShellHarness,
) -> None:
    result = powershell_harness.run()

    assert result.returncode == 0, result.stderr
    assert "Free Claude Code is installed and verified." in result.stdout
    calls = powershell_harness.calls()
    assert calls.index("claude-install") < calls.index("claude:--version")
    assert calls.index("codex-install:1") < calls.index("codex:--version")
    assert calls.index("pi-install") < calls.index("pi:--version")
    assert calls.index("uv-install") < calls.index("uv:--version")
    assert any(
        call.startswith(
            "uv:tool install --force --refresh-package free-claude-code "
            "--python cpython-3.14.0-windows-x86_64-none "
            '"free-claude-code @ '
            'https://github.com/Alishahryar1/free-claude-code/archive/refs/heads/main.zip"'
        )
        for call in calls
    )
    assert not any(call.startswith("git:") for call in calls)
    assert calls[-4:-1] == [
        "uv:tool update-shell",
        "uv:tool dir --bin",
        "fcc-server:--version",
    ]
    home = Path(powershell_harness.env["USERPROFILE"])
    app_data = Path(powershell_harness.env["APPDATA"])
    icon = home / ".fcc" / "app-icon.ico"
    assert icon.read_text(encoding="utf-8").strip() == "fake icon"
    assert calls[-1] == f'fcc-desktop:--export-icon "{icon}"'
    desktop_shortcut = home / "Desktop" / "Free Claude Code.lnk"
    assert desktop_shortcut.is_file()
    assert (
        _windows_shortcut_icon(
            powershell_harness.powershell,
            desktop_shortcut,
        )
        == f"{icon},0"
    )
    assert (
        app_data
        / "Microsoft"
        / "Windows"
        / "Start Menu"
        / "Programs"
        / "Free Claude Code.lnk"
    ).is_file()


def test_install_ps1_stops_if_windows_icon_export_fails(
    powershell_harness: PowerShellHarness,
) -> None:
    result = powershell_harness.run(fail_step="desktop-icon-export")

    assert result.returncode != 0
    assert "Command failed with exit code 56" in result.stderr
    home = Path(powershell_harness.env["USERPROFILE"])
    assert not (home / "Desktop" / "Free Claude Code.lnk").exists()


def test_install_ps1_preserves_unowned_desktop_shortcut(
    powershell_harness: PowerShellHarness,
) -> None:
    desktop_shortcut = (
        Path(powershell_harness.env["USERPROFILE"]) / "Desktop" / "Free Claude Code.lnk"
    )
    unrelated_target = powershell_harness.root / "unrelated.cmd"
    unrelated_target.write_text("@echo off\n", encoding="utf-8")
    _create_windows_shortcut(
        powershell_harness.powershell,
        desktop_shortcut,
        unrelated_target,
    )
    original_shortcut = desktop_shortcut.read_bytes()

    result = powershell_harness.run()

    assert result.returncode == 0, result.stderr
    assert "not managed by Free Claude Code" in result.stdout
    assert desktop_shortcut.read_bytes() == original_shortcut


@pytest.mark.parametrize("uv_version", ("0.11.16", "0.11.16+build.1"))
def test_install_ps1_preserves_valid_existing_tools(
    powershell_harness: PowerShellHarness,
    uv_version: str,
) -> None:
    powershell_harness.add_client("claude")
    powershell_harness.add_client("codex")
    powershell_harness.add_client("pi")
    powershell_harness.add_uv(uv_version)

    result = powershell_harness.run()

    assert result.returncode == 0, result.stderr
    assert not any(call.startswith("download:") for call in powershell_harness.calls())
    assert "leaving it unchanged" in result.stdout


def test_install_ps1_replaces_unrelated_pi_command(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_client("claude")
    powershell_harness.add_client("codex")
    powershell_harness.add_unrelated_pi()
    powershell_harness.add_uv("0.11.16")

    result = powershell_harness.run()

    assert result.returncode == 0, result.stderr
    assert "is not Pi Coding Agent; installing Pi" in result.stdout
    assert "pi-install" in powershell_harness.calls()


def test_install_ps1_discovers_custom_pi_npm_prefix(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_client("claude")
    powershell_harness.add_client("codex")
    powershell_harness.add_npm_prefix(powershell_harness.root / "custom-npm")
    powershell_harness.add_uv("0.11.16")

    result = powershell_harness.run()

    assert result.returncode == 0, result.stderr
    calls = powershell_harness.calls()
    assert "npm:prefix -g" in calls
    assert "pi:--help" in calls
    assert "pi:--version" in calls


def test_install_ps1_continues_when_pi_is_not_installed(
    powershell_harness: PowerShellHarness,
) -> None:
    result = powershell_harness.run(fail_step="pi-skip")

    assert result.returncode == 0, result.stderr
    assert "Pi was not installed; continuing without it." in result.stdout
    assert "Run Pi with: fcc-pi" not in result.stdout
    calls = powershell_harness.calls()
    assert "pi-install" in calls
    assert not any(call.startswith("pi:") for call in calls)
    assert "uv-install" in calls
    assert "fcc-server:--version" in calls


def test_install_ps1_continues_when_unrelated_pi_is_unchanged(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_unrelated_pi()

    result = powershell_harness.run(fail_step="pi-skip")

    assert result.returncode == 0, result.stderr
    assert "Pi was not installed; continuing without it." in result.stdout
    assert "Run Pi with: fcc-pi" not in result.stdout
    calls = powershell_harness.calls()
    assert "unrelated-pi:--help" in calls
    assert "unrelated-pi:--version" not in calls
    assert "fcc-server:--version" in calls


def test_install_ps1_continues_when_pi_resolution_changes_to_unrelated_command(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_unrelated_pi()
    npm_prefix = powershell_harness.root / "custom-npm"
    powershell_harness.add_npm_prefix(npm_prefix)
    _write_executable(
        npm_prefix / "pi.cmd",
        _batch_client("other-unrelated-pi"),
    )

    result = powershell_harness.run(fail_step="pi-skip")

    assert result.returncode == 0, result.stderr
    assert "Pi was not installed; continuing without it." in result.stdout
    assert "Run Pi with: fcc-pi" not in result.stdout
    calls = powershell_harness.calls()
    assert "other-unrelated-pi:--help" in calls
    assert "other-unrelated-pi:--version" not in calls
    assert "fcc-server:--version" in calls


def test_install_ps1_replaces_obsolete_uv(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_client("claude")
    powershell_harness.add_client("codex")
    powershell_harness.add_client("pi")
    powershell_harness.add_uv("0.5.9")

    result = powershell_harness.run()

    assert result.returncode == 0, result.stderr
    assert "uv 0.5.9 does not satisfy stable >=0.11.16" in result.stdout
    assert "uv-install" in powershell_harness.calls()


@pytest.mark.parametrize("version", ("0.11.16-alpha.1", "0.12.0-rc.1"))
def test_install_ps1_replaces_prerelease_uv(
    powershell_harness: PowerShellHarness,
    version: str,
) -> None:
    powershell_harness.add_client("claude")
    powershell_harness.add_client("codex")
    powershell_harness.add_client("pi")
    powershell_harness.add_uv(version)

    result = powershell_harness.run()

    assert result.returncode == 0, result.stderr
    assert f"uv {version} does not satisfy stable >=0.11.16" in result.stdout
    assert "uv-install" in powershell_harness.calls()


@pytest.mark.parametrize(
    "failure",
    [
        "claude-download",
        "claude-install",
        "claude-verify",
        "codex-download",
        "codex-install",
        "codex-verify",
        "pi-download",
        "pi-install",
        "pi-verify",
        "uv-download",
        "uv-install",
        "uv-verify",
        "fcc-install",
        "path-update",
        "fcc-missing",
        "fcc-verify",
    ],
)
def test_install_ps1_stops_without_success_on_each_failure(
    powershell_harness: PowerShellHarness,
    failure: str,
) -> None:
    result = powershell_harness.run(fail_step=failure)

    assert result.returncode != 0
    assert "Free Claude Code is installed and verified." not in result.stdout
    forbidden = {
        "claude-download": "claude-install",
        "claude-install": "claude:--version",
        "claude-verify": "chatgpt.com",
        "codex-download": "codex-install",
        "codex-install": "codex:--version",
        "codex-verify": "pi.dev",
        "pi-download": "pi-install",
        "pi-install": "pi:--version",
        "pi-verify": "astral.sh",
        "uv-download": "uv-install",
        "uv-install": "uv:--version",
        "uv-verify": "uv:tool install",
        "fcc-install": "uv:tool update-shell",
        "path-update": "uv:tool dir --bin",
        "fcc-missing": "fcc-server:--version",
    }.get(failure)
    if forbidden is not None:
        assert not any(forbidden in call for call in powershell_harness.calls())


def test_install_ps1_dry_run_never_executes_commands(
    powershell_harness: PowerShellHarness,
) -> None:
    result = subprocess.run(
        [
            powershell_harness.powershell,
            "-NoProfile",
            "-ExecutionPolicy",
            "Bypass",
            "-File",
            str(_repo_root() / "scripts" / "install.ps1"),
            "-DryRun",
        ],
        check=False,
        capture_output=True,
        text=True,
        env=powershell_harness.env,
    )

    assert result.returncode == 0, result.stderr
    assert powershell_harness.calls() == []
    assert "Dry run complete. No changes were made." in result.stdout
    assert "Free Claude Code is installed and verified." not in result.stdout


def test_install_ps1_rejects_broken_existing_client_without_replacing_it(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_client("claude")

    result = powershell_harness.run(fail_step="claude-verify")

    assert result.returncode != 0
    assert not any(call.startswith("download:") for call in powershell_harness.calls())


def test_install_ps1_rejects_unparseable_existing_uv(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_client("claude")
    powershell_harness.add_client("codex")
    powershell_harness.add_client("pi")
    powershell_harness.add_uv("not-a-version")

    result = powershell_harness.run()

    assert result.returncode != 0
    assert not any("astral.sh" in call for call in powershell_harness.calls())


def test_install_ps1_voice_flags_only_change_fcc_spec(
    powershell_harness: PowerShellHarness,
) -> None:
    result = powershell_harness.run("-VoiceAll", "-TorchBackend", "cu130")

    assert result.returncode == 0, result.stderr
    assert any(
        '--torch-backend cu130 "free-claude-code[voice,voice_local] @ '
        'https://github.com/Alishahryar1/free-claude-code/archive/refs/heads/main.zip"'
        in call
        for call in powershell_harness.calls()
    )


@pytest.mark.parametrize("command_name", FCC_COMMANDS)
def test_install_ps1_rejects_running_fcc_before_mutation(
    powershell_harness: PowerShellHarness,
    command_name: str,
) -> None:
    powershell_harness.env["FCC_RUNNING_COMMAND"] = command_name

    result = powershell_harness.run()

    assert result.returncode != 0
    assert powershell_harness.calls() == []
    assert f"{command_name} (PID 4242)" in result.stderr


def test_install_ps1_rechecks_for_fcc_process_before_tool_replacement(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_client("claude")
    powershell_harness.add_client("codex")
    powershell_harness.add_client("pi")
    powershell_harness.add_uv("0.11.16")
    powershell_harness.env["FCC_RUNNING_COMMAND"] = "fcc-server"
    powershell_harness.env["FCC_RUNNING_PHASE"] = "late"

    result = powershell_harness.run()

    assert result.returncode != 0
    assert "fcc-server (PID 4242)" in result.stderr
    assert not any(
        call.startswith("uv:tool install") for call in powershell_harness.calls()
    )


def test_install_ps1_ignores_similarly_named_process(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.env["FCC_RUNNING_COMMAND"] = "fcc-server-helper"

    result = powershell_harness.run()

    assert result.returncode == 0, result.stderr


def test_installers_use_native_clients_and_single_python_selection() -> None:
    shell = (_repo_root() / "scripts" / "install.sh").read_text(encoding="utf-8")
    powershell = (_repo_root() / "scripts" / "install.ps1").read_text(encoding="utf-8")

    for text in (shell, powershell):
        for command_name in FCC_COMMANDS:
            assert command_name in text
        assert "@anthropic-ai/claude-code" not in text
        assert "@openai/codex" not in text
        assert "@earendil-works/pi-coding-agent" not in text
        assert "git+" not in text
        assert "git --version" not in text
        assert (
            "https://github.com/Alishahryar1/free-claude-code/archive/refs/heads/main.zip"
            in text
        )
        assert "python install" not in text
        assert "--refresh-package" in text
        assert "tool update-shell" in text
        assert "--python" in text

    assert "https://pi.dev/install.sh" in shell
    assert "https://pi.dev/install.ps1" in powershell


def test_install_ps1_uses_x64_python_for_windows_arm_compatibility() -> None:
    powershell = (_repo_root() / "scripts" / "install.ps1").read_text(encoding="utf-8")

    assert '$PythonRequest = "cpython-3.14.0-windows-x86_64-none"' in powershell


@pytest.mark.parametrize("powershell", _powershells())
def test_install_ps1_rejects_invalid_download_before_execution(
    powershell: str,
) -> None:
    text = (_repo_root() / "scripts" / "install.ps1").read_text(encoding="utf-8")
    body = _braced_body(text, "function Invoke-DownloadedPowerShellInstaller")
    script = f"""Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$DryRun = $false
function Format-Argument {{ param([string] $Value) return $Value }}
function Invoke-RestMethod {{
    [CmdletBinding()]
    param([string] $Uri, [string] $OutFile)
    [IO.File]::WriteAllText($OutFile, "<style>div#box {{")
}}
function Get-PowerShellExecutable {{ throw "invalid installer reached execution" }}
function Invoke-DownloadedPowerShellInstaller {{{body}}}
Invoke-DownloadedPowerShellInstaller `
    -Url "https://example.test/install.ps1" `
    -Name "Example"
"""

    result = subprocess.run(
        [powershell, "-NoProfile", "-Command", script],
        check=False,
        capture_output=True,
        text=True,
    )

    assert result.returncode != 0
    assert (
        "Example installer from 'https://example.test/install.ps1' is not valid PowerShell"
        in result.stderr
    )
    assert "network proxy or filter" in result.stderr
    assert "invalid installer reached execution" not in result.stderr


@pytest.mark.parametrize("powershell", _powershells())
@pytest.mark.parametrize(
    ("answers", "expected", "expected_messages"),
    [
        (("", "", ""), "True,True,True", ()),
        (
            ("maybe", "n", "n", "n", "n", "y", "n"),
            "False,True,False",
            ("Please answer Y or N.", "Select at least one coding agent."),
        ),
    ],
)
def test_install_ps1_selects_at_least_one_coding_agent(
    powershell: str,
    answers: tuple[str, ...],
    expected: str,
    expected_messages: tuple[str, ...],
) -> None:
    text = (_repo_root() / "scripts" / "install.ps1").read_text(encoding="utf-8")
    read_yes_no = _braced_body(text, "function Read-YesNo")
    select_agents = _braced_body(text, "function Select-CodingAgents")
    answer_array = ", ".join(repr(answer) for answer in answers)
    script = f"""Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$script:Answers = @({answer_array})
$script:AnswerIndex = 0
$script:InstallClaudeCode = $true
$script:InstallCodex = $true
$script:InstallPi = $true
function Read-Host {{
    param([string] $Prompt)
    $answer = $script:Answers[$script:AnswerIndex]
    $script:AnswerIndex += 1
    return $answer
}}
function Read-YesNo {{{read_yes_no}}}
function Select-CodingAgents {{{select_agents}}}
Select-CodingAgents
Write-Output "selection:$($script:InstallClaudeCode),$($script:InstallCodex),$($script:InstallPi)"
"""

    result = subprocess.run(
        [powershell, "-NoProfile", "-Command", script],
        check=False,
        capture_output=True,
        text=True,
    )

    assert result.returncode == 0, result.stderr
    assert f"selection:{expected}" in result.stdout
    for message in expected_messages:
        assert message in result.stdout


@pytest.mark.parametrize("powershell", _powershells())
def test_install_ps1_runs_only_selected_coding_agents(powershell: str) -> None:
    text = (_repo_root() / "scripts" / "install.ps1").read_text(encoding="utf-8")
    body = _braced_body(text, "function Ensure-SelectedCodingAgents")
    script = f"""Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$script:InstallClaudeCode = $false
$script:InstallCodex = $true
$script:InstallPi = $false
$script:PiAvailable = $false
$script:Calls = @()
function Write-Step {{ param([string] $Message) }}
function Ensure-ClaudeCode {{ $script:Calls += "claude" }}
function Ensure-Codex {{ $script:Calls += "codex" }}
function Ensure-Pi {{ $script:Calls += "pi"; $script:PiAvailable = $true }}
function Ensure-SelectedCodingAgents {{{body}}}
Ensure-SelectedCodingAgents
Write-Output "calls:$($script:Calls -join ',')"
"""

    result = subprocess.run(
        [powershell, "-NoProfile", "-Command", script],
        check=False,
        capture_output=True,
        text=True,
    )

    assert result.returncode == 0, result.stderr
    assert "calls:codex" in result.stdout


@pytest.mark.parametrize("powershell", _powershells())
def test_install_ps1_rejects_uninstalled_only_selection(powershell: str) -> None:
    text = (_repo_root() / "scripts" / "install.ps1").read_text(encoding="utf-8")
    body = _braced_body(text, "function Ensure-SelectedCodingAgents")
    script = f"""Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$script:InstallClaudeCode = $false
$script:InstallCodex = $false
$script:InstallPi = $true
$script:PiAvailable = $false
function Write-Step {{ param([string] $Message) }}
function Ensure-ClaudeCode {{ }}
function Ensure-Codex {{ }}
function Ensure-Pi {{ }}
function Ensure-SelectedCodingAgents {{{body}}}
Ensure-SelectedCodingAgents
"""

    result = subprocess.run(
        [powershell, "-NoProfile", "-Command", script],
        check=False,
        capture_output=True,
        text=True,
    )

    assert result.returncode != 0
    assert "No selected coding agent was installed." in result.stderr


@pytest.mark.parametrize("powershell", _powershells())
def test_install_ps1_falls_back_when_pshome_executable_is_unavailable(
    tmp_path: Path,
    powershell: str,
) -> None:
    text = (_repo_root() / "scripts" / "install.ps1").read_text(encoding="utf-8")
    body = _braced_body(text, "function Get-PowerShellExecutable")
    fallback = tmp_path / "fallback" / "powershell.exe"
    script = tmp_path / "test-powershell-resolution.ps1"
    script.write_text(
        f"""Set-StrictMode -Version Latest
function Get-ApplicationCommand {{
    param([string] $Name)
    return [pscustomobject] @{{ Source = {str(fallback)!r} }}
}}
function Get-PowerShellExecutable {{
{body}
}}
$resolved = Get-PowerShellExecutable -PowerShellHome {str(tmp_path / "missing")!r}
if ($resolved -ne {str(fallback)!r}) {{
    throw "Unexpected fallback: $resolved"
}}
""",
        encoding="utf-8",
    )

    result = subprocess.run(
        [powershell, "-NoProfile", "-File", str(script)],
        check=False,
        capture_output=True,
        text=True,
    )

    assert result.returncode == 0, result.stderr