foch 0.0.2

EU4 mod analysis and merge toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
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
use std::collections::{BTreeMap, HashMap, HashSet};
use std::error::Error;
use std::ffi::{OsStr, OsString};
use std::fs;
use std::io::{self, BufRead, BufReader, IsTerminal, Write};
use std::path::{Path, PathBuf};

use crate::model::{GamePath, GamePathBuf, HandlerResolutionRecord};
use crate::project::{DepOverride, ResolutionDecision, ResolutionEntry, ResolutionMap};
use toml_edit::{ArrayOfTables, DocumentMut, Item, Table, value};

use crate::merge::conflict_view::ConflictView;
use crate::merge::dag::ModDag;

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum ConflictViewRequirement {
	/// The handler always returns an unrecorded defer decision.
	DeferWithoutView,
	/// The handler only needs stable identity and contributor metadata.
	Metadata,
	/// The handler needs rendered vanilla/candidate snippets.
	Full,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ConflictMetadataCandidate {
	pub mod_id: String,
	pub precedence: usize,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ConflictMetadataView {
	/// The output file the conflict is in.
	pub file_path: GamePathBuf,
	pub address_path: Vec<String>,
	pub address_key: String,
	pub conflict_id: String,
	pub reason: String,
	pub candidates: Vec<ConflictMetadataCandidate>,
}

impl From<&ConflictView> for ConflictMetadataView {
	fn from(view: &ConflictView) -> Self {
		Self {
			file_path: view.file_path.clone(),
			address_path: view.address_path.clone(),
			address_key: view.address_key.clone(),
			conflict_id: view.conflict_id.clone(),
			reason: view.reason.clone(),
			candidates: view
				.candidates
				.iter()
				.map(|candidate| ConflictMetadataCandidate {
					mod_id: candidate.mod_id.clone(),
					precedence: candidate.precedence,
				})
				.collect(),
		}
	}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum MetadataConflictDecision {
	Decision(ConflictDecision),
	NeedsFullView,
}

impl From<ConflictDecision> for MetadataConflictDecision {
	fn from(decision: ConflictDecision) -> Self {
		Self::Decision(decision)
	}
}

pub trait ConflictHandler {
	fn on_conflict(&mut self, view: &ConflictView) -> ConflictDecision;

	/// Declare the cheapest view that preserves this handler's behavior.
	///
	/// External handlers default to `Full`; opting into `Metadata` also requires
	/// implementing `on_conflict_metadata`.
	fn conflict_view_requirement(&self) -> ConflictViewRequirement {
		ConflictViewRequirement::Full
	}

	fn on_conflict_metadata(&mut self, _view: &ConflictMetadataView) -> MetadataConflictDecision {
		panic!("metadata-capable conflict handler must implement on_conflict_metadata")
	}

	fn set_conflict_progress(&mut self, _current: usize, _total: usize) {}

	fn set_deferred_so_far(&mut self, _count: usize) {}
}

fn unique_candidate_index(view: &ConflictMetadataView, mod_id: &str) -> Option<usize> {
	let mut matches = view
		.candidates
		.iter()
		.enumerate()
		.filter(|(_, candidate)| candidate.mod_id == mod_id)
		.map(|(index, _)| index);
	let candidate = matches.next()?;
	matches.next().is_none().then_some(candidate)
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum ConflictDecision {
	/// Pick one exact candidate from the `ConflictView` passed to the handler.
	PickCandidate {
		candidate: usize,
		record: Option<HandlerResolutionRecord>,
	},
	/// Use this external file's content (handled at materialize time).
	UseFile(PathBuf),
	/// Use bytes frozen from a configured external file during analysis.
	UseFrozenFile(PathBuf),
	/// Keep whatever already exists at output dir (handled at materialize time).
	KeepExisting,
	/// Defer — log to report, leave for later resolution, optionally recording a handler-specific report entry.
	Defer {
		record: Option<HandlerResolutionRecord>,
	},
	/// Abort the merge.
	Abort,
}

/// Default handler: always defer, reproducing the current behavior.
pub struct DeferHandler;

impl ConflictHandler for DeferHandler {
	fn on_conflict(&mut self, _: &ConflictView) -> ConflictDecision {
		ConflictDecision::Defer { record: None }
	}

	fn conflict_view_requirement(&self) -> ConflictViewRequirement {
		ConflictViewRequirement::DeferWithoutView
	}
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub(crate) struct DepResolutionGraph {
	parents: HashMap<String, Vec<String>>,
}

impl DepResolutionGraph {
	pub(crate) fn from_mod_dag(mod_dag: &ModDag, dep_overrides: &[DepOverride]) -> Self {
		let ignored_edges: HashSet<(String, String)> = dep_overrides
			.iter()
			.map(|item| (item.mod_id.clone(), item.dep_id.clone()))
			.collect();
		let parents = mod_dag
			.topo()
			.iter()
			.map(|mod_id| {
				let child = mod_id.as_str().to_string();
				let parents = mod_dag
					.parents_of(mod_id)
					.iter()
					.filter(|parent| {
						!ignored_edges.contains(&(child.clone(), parent.as_str().to_string()))
					})
					.map(|parent| parent.as_str().to_string())
					.collect();
				(child, parents)
			})
			.collect();
		Self { parents }
	}

	#[cfg(test)]
	fn from_edges(edges: &[(&str, &str)]) -> Self {
		let mut parents: HashMap<String, Vec<String>> = HashMap::new();
		for (child, parent) in edges {
			parents
				.entry((*child).to_string())
				.or_default()
				.push((*parent).to_string());
			parents.entry((*parent).to_string()).or_default();
		}
		Self { parents }
	}

	fn direct_depends_on(&self, downstream: &str, upstream: &str) -> bool {
		self.parents
			.get(downstream)
			.is_some_and(|parents| parents.iter().any(|parent| parent == upstream))
	}

	fn depends_on(&self, downstream: &str, upstream: &str) -> bool {
		let mut seen = HashSet::new();
		let mut stack = self.parents.get(downstream).cloned().unwrap_or_default();
		while let Some(parent) = stack.pop() {
			if !seen.insert(parent.clone()) {
				continue;
			}
			if parent == upstream {
				return true;
			}
			if let Some(grandparents) = self.parents.get(&parent) {
				stack.extend(grandparents.iter().cloned());
			}
		}
		false
	}
}

/// Single-threaded only: holds &mut self per-conflict via the ConflictHandler trait.
/// The merge engine drives this serially; do NOT share across threads.
pub(crate) struct DepImpliesResolutionHandler {
	current_file: GamePathBuf,
	dep_graph: DepResolutionGraph,
}

impl DepImpliesResolutionHandler {
	pub(crate) fn from_mod_dag(
		current_file: GamePathBuf,
		mod_dag: &ModDag,
		dep_overrides: &[DepOverride],
	) -> Self {
		Self::new(
			current_file,
			DepResolutionGraph::from_mod_dag(mod_dag, dep_overrides),
		)
	}

	pub(crate) fn new(current_file: GamePathBuf, dep_graph: DepResolutionGraph) -> Self {
		Self {
			current_file,
			dep_graph,
		}
	}

	fn conflict_mods(&self, view: &ConflictMetadataView) -> Vec<String> {
		let mut seen = HashSet::new();
		view.candidates
			.iter()
			.filter_map(|candidate| {
				if seen.insert(candidate.mod_id.clone()) {
					Some(candidate.mod_id.clone())
				} else {
					None
				}
			})
			.collect()
	}

	fn cycle_pair(&self, mods: &[String]) -> Option<(String, String)> {
		for (index, left) in mods.iter().enumerate() {
			for right in mods.iter().skip(index + 1) {
				if self.dep_graph.depends_on(left, right) && self.dep_graph.depends_on(right, left)
				{
					return Some((left.clone(), right.clone()));
				}
			}
		}
		None
	}

	fn winner(&self, mods: &[String]) -> Option<String> {
		if mods.len() < 2 {
			return None;
		}
		if let Some((left, right)) = self.cycle_pair(mods) {
			eprintln!(
				"[foch] dep_implied skipped for {}: dependency cycle between {} and {}",
				self.current_file, left, right
			);
			return None;
		}

		let winners: Vec<_> = mods
			.iter()
			.filter(|candidate| {
				let candidate = candidate.as_str();
				mods.iter().all(|other| {
					other.as_str() == candidate || self.dep_graph.depends_on(candidate, other)
				})
			})
			.cloned()
			.collect();
		if winners.len() == 1 {
			winners.into_iter().next()
		} else {
			None
		}
	}

	fn rationale(&self, winner: &str, mods: &[String]) -> String {
		for other in mods.iter().filter(|other| other.as_str() != winner) {
			if self.dep_graph.direct_depends_on(winner, other) {
				return format!("mod {winner} declares dep on {other}");
			}
		}
		for other in mods.iter().filter(|other| other.as_str() != winner) {
			if self.dep_graph.depends_on(winner, other) {
				return format!("mod {winner} transitively depends on {other}");
			}
		}
		format!("mod {winner} is downstream of all conflicting contributors")
	}

	fn decide(&mut self, view: &ConflictMetadataView) -> ConflictDecision {
		let mods = self.conflict_mods(view);
		let Some(winner) = self.winner(&mods) else {
			return ConflictDecision::Defer { record: None };
		};
		let Some(candidate) = unique_candidate_index(view, &winner) else {
			return ConflictDecision::Defer { record: None };
		};
		let rationale = self.rationale(&winner, &mods);
		ConflictDecision::PickCandidate {
			candidate,
			record: Some(HandlerResolutionRecord {
				path: view.file_path.clone(),
				action: "dep_implied".to_string(),
				source: Some(winner),
				rationale: Some(rationale),
			}),
		}
	}
}

impl ConflictHandler for DepImpliesResolutionHandler {
	fn on_conflict(&mut self, view: &ConflictView) -> ConflictDecision {
		self.decide(&ConflictMetadataView::from(view))
	}

	fn conflict_view_requirement(&self) -> ConflictViewRequirement {
		ConflictViewRequirement::Metadata
	}

	fn on_conflict_metadata(&mut self, view: &ConflictMetadataView) -> MetadataConflictDecision {
		self.decide(view).into()
	}
}

pub(crate) struct PriorityBoostResolutionHandler<'a> {
	boosts: &'a BTreeMap<String, i32>,
}

impl<'a> PriorityBoostResolutionHandler<'a> {
	pub(crate) fn new(boosts: &'a BTreeMap<String, i32>) -> Self {
		Self { boosts }
	}

	fn winner(&self, view: &ConflictMetadataView) -> Option<(usize, String, usize)> {
		let (winner_index, winner) = view.candidates.iter().enumerate().max_by(
			|(left_index, left), (right_index, right)| {
				left.precedence
					.cmp(&right.precedence)
					.then_with(|| left.mod_id.cmp(&right.mod_id))
					.then_with(|| left_index.cmp(right_index))
			},
		)?;
		if self.boosts.get(&winner.mod_id).copied().unwrap_or(0) == 0 {
			return None;
		}
		let tied_winners = view
			.candidates
			.iter()
			.filter(|candidate| candidate.precedence == winner.precedence)
			.count();
		if tied_winners != 1 {
			return None;
		}
		Some((winner_index, winner.mod_id.clone(), winner.precedence))
	}

	fn decide(&mut self, view: &ConflictMetadataView) -> ConflictDecision {
		let Some((candidate, winner, precedence)) = self.winner(view) else {
			return ConflictDecision::Defer { record: None };
		};
		let mod_ids: Vec<&str> = view
			.candidates
			.iter()
			.map(|candidate| candidate.mod_id.as_str())
			.collect();
		ConflictDecision::PickCandidate {
			candidate,
			record: Some(HandlerResolutionRecord {
				path: view.file_path.clone(),
				action: "priority_boost".to_string(),
				source: Some(winner.clone()),
				rationale: Some(format!(
					"priority_boost made `{winner}` the unique highest-precedence contributor ({precedence}) among [{}]",
					mod_ids.join(", ")
				)),
			}),
		}
	}
}

impl<'a> ConflictHandler for PriorityBoostResolutionHandler<'a> {
	fn on_conflict(&mut self, view: &ConflictView) -> ConflictDecision {
		self.decide(&ConflictMetadataView::from(view))
	}

	fn conflict_view_requirement(&self) -> ConflictViewRequirement {
		ConflictViewRequirement::Metadata
	}

	fn on_conflict_metadata(&mut self, view: &ConflictMetadataView) -> MetadataConflictDecision {
		self.decide(view).into()
	}
}

/// Single-threaded only: holds &mut self per-conflict via current_conflict_index/total_conflicts.
/// The merge engine drives this serially; do NOT share across threads.
pub struct LookupHandler<'a> {
	pub map: &'a ResolutionMap,
	/// The output file being merged, which file and pattern resolutions are
	/// looked up by. Every view this handler decides is a conflict in it.
	current_file: GamePathBuf,
	current_conflict_index: usize,
	total_conflicts: usize,
}

impl<'a> LookupHandler<'a> {
	#[cfg(test)]
	pub(crate) fn new(map: &'a ResolutionMap, file: GamePathBuf) -> Self {
		Self::with_display_names(map, file, HashMap::new())
	}

	pub(crate) fn with_display_names(
		map: &'a ResolutionMap,
		file: GamePathBuf,
		_mod_displayname_lookup: HashMap<String, String>,
	) -> Self {
		Self {
			map,
			current_file: file,
			current_conflict_index: 1,
			total_conflicts: 1,
		}
	}

	fn matching_resolution<'view>(
		&'view self,
		view: &'view ConflictMetadataView,
	) -> Option<&'view ResolutionDecision> {
		let address_path = view.address_path.join("/");
		let lookup_file: &GamePath = &self.current_file;
		let leaf_address = if address_path.is_empty() {
			view.address_key.clone()
		} else {
			format!("{address_path}/{}", view.address_key)
		};
		self.map
			.by_conflict_id
			.get(&view.conflict_id)
			.or_else(|| self.map.by_file.get(lookup_file))
			.or_else(|| {
				self.map
					.pattern_rules
					.iter()
					.find(|rule| rule.matches(lookup_file, &leaf_address))
					.map(|rule| &rule.decision)
			})
	}

	fn decide_metadata(&mut self, view: &ConflictMetadataView) -> ConflictDecision {
		match self.matching_resolution(view) {
			Some(ResolutionDecision::PreferCandidate(candidate)) => view
				.candidates
				.get(*candidate)
				.map(|_| ConflictDecision::PickCandidate {
					candidate: *candidate,
					record: None,
				})
				.unwrap_or(ConflictDecision::Defer { record: None }),
			Some(ResolutionDecision::PreferMod(mod_id)) => unique_candidate_index(view, mod_id)
				.map(|candidate| ConflictDecision::PickCandidate {
					candidate,
					record: None,
				})
				.unwrap_or(ConflictDecision::Defer { record: None }),
			Some(ResolutionDecision::UseFile(path)) => {
				ConflictDecision::UseFrozenFile(path.clone())
			}
			Some(ResolutionDecision::UseLiveFile(path)) => ConflictDecision::UseFile(path.clone()),
			Some(ResolutionDecision::KeepExisting) => ConflictDecision::KeepExisting,
			Some(ResolutionDecision::Handler(_)) => {
				unreachable!("named handlers require a full conflict view")
			}
			None => {
				log_cwt_suggestion_on_miss(
					&self.current_file,
					&view.address_path,
					&view.address_key,
				);
				ConflictDecision::Defer { record: None }
			}
		}
	}
}

fn log_cwt_suggestion_on_miss(current_file: &GamePath, address_path: &[String], address_key: &str) {
	let ast_path = if address_path.is_empty() {
		vec![address_key]
	} else {
		address_path.iter().map(String::as_str).collect::<Vec<_>>()
	};
	let Some(suggestion) =
		crate::game::eu4::cwt::merge::suggest_for_conflict(current_file, &ast_path)
	else {
		return;
	};
	tracing::info!(
		target: "foch_merge_cwt_suggest",
		file = %current_file,
		ast_path = %ast_path.join("/"),
		suggested_identity_source = ?suggestion.suggested_identity_source,
		suggested_block_policy = ?suggestion.suggested_block_policy,
		schema_provenance = %suggestion.schema_provenance,
		"cwt merge suggestion"
	);
}

impl<'a> ConflictHandler for LookupHandler<'a> {
	fn on_conflict(&mut self, view: &ConflictView) -> ConflictDecision {
		let metadata = ConflictMetadataView::from(view);
		if let Some(ResolutionDecision::Handler(name)) = self.matching_resolution(&metadata) {
			crate::merge::handler_registry::dispatch(name, view)
		} else {
			self.decide_metadata(&metadata)
		}
	}

	fn conflict_view_requirement(&self) -> ConflictViewRequirement {
		ConflictViewRequirement::Metadata
	}

	fn on_conflict_metadata(&mut self, view: &ConflictMetadataView) -> MetadataConflictDecision {
		if matches!(
			self.matching_resolution(view),
			Some(ResolutionDecision::Handler(_))
		) {
			MetadataConflictDecision::NeedsFullView
		} else {
			self.decide_metadata(view).into()
		}
	}

	fn set_conflict_progress(&mut self, current: usize, total: usize) {
		self.current_conflict_index = current;
		self.total_conflicts = total;
	}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub(crate) struct FilesystemConfigWriter {
	path: PathBuf,
}

impl FilesystemConfigWriter {
	pub(crate) fn new(path: PathBuf) -> Self {
		Self { path }
	}

	/// The sibling the next content is staged at before it is renamed over
	/// the config: `.<name>.<pid>.tmp`, with the config's name extended as it
	/// is, never re-spelled as text.
	fn temporary_path(&self) -> PathBuf {
		let parent = self.path.parent().unwrap_or_else(|| Path::new("."));
		let mut name = OsString::from(".");
		name.push(self.path.file_name().unwrap_or(OsStr::new("foch.toml")));
		name.push(format!(".{}.tmp", std::process::id()));
		parent.join(name)
	}

	fn append_resolution(&self, mut entry: ResolutionEntry) -> Result<(), Box<dyn Error>> {
		// A file chosen during this run was read relative to the working
		// directory, but the config reads a relative `use_file` from its own
		// directory. Record the absolute path so both name the same file.
		if let Some(use_file) = entry.use_file.as_mut()
			&& use_file.is_relative()
		{
			*use_file = std::path::absolute(&*use_file)?;
		}
		if let Some(parent) = self
			.path
			.parent()
			.filter(|parent| !parent.as_os_str().is_empty())
		{
			fs::create_dir_all(parent)?;
		}

		let content = match fs::read_to_string(&self.path) {
			Ok(content) => content,
			Err(err) if err.kind() == io::ErrorKind::NotFound => String::new(),
			Err(err) => return Err(Box::new(err)),
		};
		if !content.trim().is_empty() {
			content.parse::<DocumentMut>()?;
		}

		let mut next_content = content;
		if !next_content.is_empty() && !next_content.ends_with('\n') {
			next_content.push('\n');
		}
		if !next_content.is_empty() && !next_content.ends_with("\n\n") {
			next_content.push('\n');
		}
		next_content.push_str(&render_resolution_entry(&entry)?);
		if !next_content.ends_with('\n') {
			next_content.push('\n');
		}

		let temp_path = self.temporary_path();
		fs::write(&temp_path, next_content.as_bytes())?;
		if let Err(err) = fs::rename(&temp_path, &self.path) {
			let _ = fs::remove_file(&temp_path);
			return Err(Box::new(err));
		}
		Ok(())
	}
}

/// Single-threaded only: holds &mut self per-conflict via prompt progress,
/// deferred counters, and stdio handles. The merge engine drives this serially;
/// do NOT share across threads.
pub struct InteractiveCliHandler {
	input: Box<dyn BufRead>,
	stderr: Box<dyn Write>,
	tty_available: Option<bool>,
	current_conflict_index: usize,
	total_conflicts: usize,
	deferred_so_far: usize,
}

impl InteractiveCliHandler {
	pub fn new() -> Self {
		Self {
			input: Box::new(BufReader::new(io::stdin())),
			stderr: Box::new(io::stderr()),
			tty_available: None,
			current_conflict_index: 1,
			total_conflicts: 1,
			deferred_so_far: 0,
		}
	}

	#[cfg(test)]
	fn with_io(input: Box<dyn BufRead>, stderr: Box<dyn Write>, tty_available: bool) -> Self {
		Self {
			input,
			stderr,
			tty_available: Some(tty_available),
			current_conflict_index: 1,
			total_conflicts: 1,
			deferred_so_far: 0,
		}
	}

	fn stdin_stderr_are_tty(&self) -> bool {
		self.tty_available
			.unwrap_or_else(|| io::stdin().is_terminal() && io::stderr().is_terminal())
	}

	fn write_conflict_summary(&mut self, view: &ConflictView) {
		let address_path = view.address_path.join("/");
		let _ = writeln!(
			self.stderr,
			"[foch] unresolved structural merge conflict (conflict {}/{}) ({} deferred)",
			self.current_conflict_index, self.total_conflicts, self.deferred_so_far
		);
		let _ = writeln!(self.stderr, "  file: {}", view.file_path);
		let _ = writeln!(
			self.stderr,
			"  address: {address_path}/{}",
			view.address_key
		);
		let _ = writeln!(self.stderr, "  conflict_id: {}", view.conflict_id);
		let _ = writeln!(self.stderr, "  reason: {}", view.reason);
		if let Some(snippet) = &view.vanilla_snippet {
			let _ = writeln!(self.stderr, "  vanilla:");
			for line in snippet.lines().take(20) {
				let _ = writeln!(self.stderr, "      {line}");
			}
		}
		let _ = writeln!(self.stderr, "  candidates:");
		for (index, candidate) in view.candidates.iter().enumerate() {
			let _ = writeln!(
				self.stderr,
				"    [{}] {} (precedence {})",
				index + 1,
				candidate.mod_id,
				candidate.precedence
			);
			self.write_candidate_patch(candidate);
		}
	}

	fn write_candidate_patch(&mut self, candidate: &crate::merge::conflict_view::CandidateView) {
		for summary in &candidate.change_summary {
			let _ = writeln!(self.stderr, "      {summary}");
		}
		let lines: Vec<&str> = candidate.candidate_rendered.lines().collect();
		for line in lines.iter().take(20) {
			let _ = writeln!(self.stderr, "      {line}");
		}
		let remaining = lines.len().saturating_sub(20);
		if remaining > 0 {
			let _ = writeln!(self.stderr, "      ... ({remaining} more lines)");
		}
	}

	fn write_prompt(&mut self, view: &ConflictView) {
		let mut choices = view
			.candidates
			.iter()
			.enumerate()
			.map(|(index, candidate)| format!("[{}] {}", index + 1, candidate.mod_id))
			.collect::<Vec<_>>();
		choices.extend([
			"[d] defer".to_string(),
			"[s] use file path".to_string(),
			"[k] keep existing".to_string(),
			"[q] abort".to_string(),
		]);
		let _ = write!(self.stderr, "{}\nchoice> ", choices.join(" / "));
		let _ = self.stderr.flush();
	}

	fn read_trimmed_line(&mut self) -> Option<String> {
		let mut line = String::new();
		match self.input.read_line(&mut line) {
			Ok(0) => None,
			Ok(_) => Some(line.trim().to_string()),
			Err(err) => {
				let _ = writeln!(
					self.stderr,
					"[foch] failed to read interactive choice: {err}"
				);
				None
			}
		}
	}

	fn prompt_for_external_path(&mut self) -> Option<PathBuf> {
		let _ = write!(self.stderr, "path> ");
		let _ = self.stderr.flush();
		let value = self.read_trimmed_line()?;
		if value.is_empty() {
			None
		} else {
			Some(PathBuf::from(value))
		}
	}
}

impl Default for InteractiveCliHandler {
	fn default() -> Self {
		Self::new()
	}
}

impl ConflictHandler for InteractiveCliHandler {
	fn on_conflict(&mut self, view: &ConflictView) -> ConflictDecision {
		if !self.stdin_stderr_are_tty() {
			let _ = writeln!(
				self.stderr,
				"[foch] interactive mode could not be entered because stdin/stderr is not a TTY; downgrading to defer"
			);
			return ConflictDecision::Defer { record: None };
		}

		self.write_conflict_summary(view);

		for attempt in 1..=3 {
			self.write_prompt(view);
			let Some(choice) = self.read_trimmed_line() else {
				return ConflictDecision::Defer { record: None };
			};
			let choice = choice.to_ascii_lowercase();
			match choice.as_str() {
				"d" | "defer" => return ConflictDecision::Defer { record: None },
				"q" | "quit" | "abort" => return ConflictDecision::Abort,
				"k" | "keep" => return ConflictDecision::KeepExisting,
				"s" | "file" | "use-file" => {
					if let Some(path) = self.prompt_for_external_path() {
						return ConflictDecision::UseFile(path);
					}
				}
				_ => {
					if let Ok(index) = choice.parse::<usize>()
						&& let Some(candidate) = index
							.checked_sub(1)
							.filter(|index| view.candidates.get(*index).is_some())
					{
						return ConflictDecision::PickCandidate {
							candidate,
							record: None,
						};
					}
				}
			}
			if attempt < 3 {
				let _ = writeln!(self.stderr, "[foch] invalid choice; please try again");
			}
		}

		let _ = writeln!(
			self.stderr,
			"[foch] invalid choice limit reached; deferring conflict"
		);
		ConflictDecision::Defer { record: None }
	}

	fn set_conflict_progress(&mut self, current: usize, total: usize) {
		self.current_conflict_index = current;
		self.total_conflicts = total;
	}

	fn set_deferred_so_far(&mut self, count: usize) {
		self.deferred_so_far = count;
	}
}

/// Chain combinator: returns the second handler's decision when the first defers.
/// Single-threaded only: holds &mut self per-conflict while forwarding mutable
/// state into child handlers. The merge engine drives this serially; do NOT share
/// across threads.
pub struct ChainHandler<H1: ConflictHandler, H2: ConflictHandler> {
	pub first: H1,
	pub second: H2,
}

fn on_conflict_without_full_view(
	handler: &mut dyn ConflictHandler,
	view: &ConflictMetadataView,
) -> MetadataConflictDecision {
	match handler.conflict_view_requirement() {
		ConflictViewRequirement::DeferWithoutView => {
			ConflictDecision::Defer { record: None }.into()
		}
		ConflictViewRequirement::Metadata => handler.on_conflict_metadata(view),
		ConflictViewRequirement::Full => MetadataConflictDecision::NeedsFullView,
	}
}

impl<H1: ConflictHandler, H2: ConflictHandler> ConflictHandler for ChainHandler<H1, H2> {
	fn on_conflict(&mut self, view: &ConflictView) -> ConflictDecision {
		match self.first.on_conflict(view) {
			ConflictDecision::Defer { record: None } => self.second.on_conflict(view),
			other => other,
		}
	}

	fn conflict_view_requirement(&self) -> ConflictViewRequirement {
		if self.first.conflict_view_requirement() == ConflictViewRequirement::DeferWithoutView
			&& self.second.conflict_view_requirement() == ConflictViewRequirement::DeferWithoutView
		{
			ConflictViewRequirement::DeferWithoutView
		} else {
			ConflictViewRequirement::Metadata
		}
	}

	fn on_conflict_metadata(&mut self, view: &ConflictMetadataView) -> MetadataConflictDecision {
		match on_conflict_without_full_view(&mut self.first, view) {
			MetadataConflictDecision::Decision(ConflictDecision::Defer { record: None }) => {
				on_conflict_without_full_view(&mut self.second, view)
			}
			other => other,
		}
	}

	fn set_conflict_progress(&mut self, current: usize, total: usize) {
		self.first.set_conflict_progress(current, total);
		self.second.set_conflict_progress(current, total);
	}

	fn set_deferred_so_far(&mut self, count: usize) {
		self.first.set_deferred_so_far(count);
		self.second.set_deferred_so_far(count);
	}
}

pub(crate) fn resolution_entry_for_decision(
	view: &ConflictView,
	current_file: &GamePath,
	conflict_id: &str,
	decision: &ConflictDecision,
) -> Option<ResolutionEntry> {
	match decision {
		ConflictDecision::PickCandidate { candidate, .. } => Some(ResolutionEntry {
			file: None,
			conflict_id: Some(conflict_id.to_string()),
			mod_id: None,
			r#match: None,
			prefer_mod: None,
			prefer_candidate: Some(
				view.candidates
					.get(*candidate)
					.and_then(|_| candidate.checked_add(1))?,
			),
			use_file: None,
			keep_existing: None,
			priority_boost: None,
			handler: None,
			policy: None,
		}),
		ConflictDecision::UseFile(path) | ConflictDecision::UseFrozenFile(path) => {
			Some(ResolutionEntry {
				file: None,
				conflict_id: Some(conflict_id.to_string()),
				mod_id: None,
				r#match: None,
				prefer_mod: None,
				prefer_candidate: None,
				use_file: Some(path.clone()),
				keep_existing: None,
				priority_boost: None,
				handler: None,
				policy: None,
			})
		}
		ConflictDecision::KeepExisting => Some(ResolutionEntry {
			file: Some(current_file.to_owned()),
			conflict_id: None,
			mod_id: None,
			r#match: None,
			prefer_mod: None,
			prefer_candidate: None,
			use_file: None,
			keep_existing: Some(true),
			priority_boost: None,
			handler: None,
			policy: None,
		}),
		ConflictDecision::Defer { .. } | ConflictDecision::Abort => None,
	}
}

/// Outcome from prompting the user about a single surviving conflict.
#[derive(Debug, Clone)]
pub enum PromptOutcomeKind {
	Picked(ResolutionDecision),
	Deferred,
}

#[derive(Debug, Clone)]
pub struct PromptOutcome {
	pub conflict_id: String,
	pub kind: PromptOutcomeKind,
}

/// Result of running the post-pass interactive resolver.
#[derive(Debug, Clone, Default)]
pub struct PromptSurvivorsResult {
	pub outcomes: Vec<PromptOutcome>,
	pub aborted: bool,
}

/// Prompts the user interactively for each surviving conflict (the post-pass
/// path: only invoked once the merge engine has finished and downstream
/// overrides have already pruned transient conflicts). Persists every Picked
/// decision to foch.toml as a side effect.
///
/// The returned outcomes carry the resolution-map decision the caller should
/// fold into the in-memory map before re-running the merge engine. If the user
/// aborts, `aborted` is set and any outcomes already collected are returned.
pub fn prompt_survivors_and_persist(
	target_path: &GamePath,
	survivors: &[ConflictView],
	handler: &mut dyn ConflictHandler,
	config_path: &Path,
) -> PromptSurvivorsResult {
	let total = survivors.len();
	let mut deferred_so_far = 0usize;
	let mut result = PromptSurvivorsResult::default();
	let config_writer = FilesystemConfigWriter::new(config_path.to_path_buf());
	for (idx, view) in survivors.iter().enumerate() {
		let current = idx + 1;
		let conflict_id = view.conflict_id.clone();
		handler.set_conflict_progress(current, total);
		handler.set_deferred_so_far(deferred_so_far);
		let decision = handler.on_conflict(view);
		if let Some(entry) =
			resolution_entry_for_decision(view, target_path, &view.conflict_id, &decision)
			&& let Err(err) = config_writer.append_resolution(entry)
		{
			eprintln!("[foch] failed to persist interactive resolution: {err}");
			result.aborted = true;
			break;
		}
		match decision {
			ConflictDecision::PickCandidate { candidate, .. } => {
				if view.candidates.get(candidate).is_some() {
					result.outcomes.push(PromptOutcome {
						conflict_id,
						kind: PromptOutcomeKind::Picked(ResolutionDecision::PreferCandidate(
							candidate,
						)),
					});
				} else {
					result.outcomes.push(PromptOutcome {
						conflict_id,
						kind: PromptOutcomeKind::Deferred,
					});
					deferred_so_far += 1;
				}
			}
			ConflictDecision::UseFile(path) => result.outcomes.push(PromptOutcome {
				conflict_id,
				kind: PromptOutcomeKind::Picked(ResolutionDecision::UseLiveFile(path)),
			}),
			ConflictDecision::UseFrozenFile(path) => result.outcomes.push(PromptOutcome {
				conflict_id,
				kind: PromptOutcomeKind::Picked(ResolutionDecision::UseFile(path)),
			}),
			ConflictDecision::KeepExisting => result.outcomes.push(PromptOutcome {
				conflict_id,
				kind: PromptOutcomeKind::Picked(ResolutionDecision::KeepExisting),
			}),
			ConflictDecision::Defer { .. } => {
				result.outcomes.push(PromptOutcome {
					conflict_id,
					kind: PromptOutcomeKind::Deferred,
				});
				deferred_so_far += 1;
			}
			ConflictDecision::Abort => {
				result.aborted = true;
				break;
			}
		}
	}
	result
}

/// One `[[resolutions]]` table. `file` is written as the game path's
/// canonical text and `use_file` as the host path's own text, never folded:
/// on Unix a `\` is part of a name. A `use_file` that is not UTF-8 has no
/// TOML text, which is an error rather than a lossy name for another file.
fn render_resolution_entry(entry: &ResolutionEntry) -> Result<String, io::Error> {
	let mut table = Table::new();
	if let Some(file) = &entry.file {
		table["file"] = value(file.as_str());
	}
	if let Some(conflict_id) = &entry.conflict_id {
		table["conflict_id"] = value(conflict_id.clone());
	}
	if let Some(mod_id) = &entry.mod_id {
		table["mod"] = value(mod_id.clone());
	}
	if let Some(prefer_mod) = &entry.prefer_mod {
		table["prefer_mod"] = value(prefer_mod.clone());
	}
	if let Some(prefer_candidate) = entry.prefer_candidate {
		table["prefer_candidate"] = value(
			i64::try_from(prefer_candidate).expect("candidate index exceeds TOML integer range"),
		);
	}
	if let Some(use_file) = &entry.use_file {
		let text = use_file.to_str().ok_or_else(|| {
			io::Error::new(
				io::ErrorKind::InvalidData,
				format!(
					"use_file {} is not valid UTF-8 and cannot be written to a foch config",
					use_file.display()
				),
			)
		})?;
		table["use_file"] = value(text);
	}
	if let Some(keep_existing) = entry.keep_existing {
		table["keep_existing"] = value(keep_existing);
	}
	if let Some(priority_boost) = entry.priority_boost {
		table["priority_boost"] = value(i64::from(priority_boost));
	}

	let mut resolutions = ArrayOfTables::new();
	resolutions.push(table);
	let mut doc = DocumentMut::new();
	doc["resolutions"] = Item::ArrayOfTables(resolutions);
	Ok(doc.to_string())
}

#[cfg(test)]
mod tests {
	use std::cell::Cell;
	use std::collections::BTreeMap;
	use std::io::Cursor;
	use std::path::PathBuf;
	use std::rc::Rc;
	use std::time::{SystemTime, UNIX_EPOCH};

	use crate::model::ModCandidate;
	use crate::playset::PlaysetEntry;
	use crate::playset::descriptor::ModDescriptor;
	use crate::project::compute_conflict_id;

	use super::*;
	use crate::merge::conflict_view::CandidateView;

	struct TestAddress {
		path: Vec<String>,
		key: String,
	}

	struct TestConflict {
		candidates: Vec<(String, usize)>,
		reason: String,
	}

	fn game_path(text: &str) -> GamePathBuf {
		GamePathBuf::parse(text).expect("valid game path")
	}

	fn address() -> TestAddress {
		TestAddress {
			path: vec!["root".to_string(), "event".to_string()],
			key: "id".to_string(),
		}
	}

	fn conflict() -> TestConflict {
		TestConflict {
			candidates: Vec::new(),
			reason: "test conflict".to_string(),
		}
	}

	fn conflict_with_patches() -> TestConflict {
		conflict_with_mods(&[("mod_a", 1, "alpha"), ("mod_b", 2, "beta")])
	}

	fn conflict_with_mods(mods: &[(&str, usize, &str)]) -> TestConflict {
		TestConflict {
			candidates: mods
				.iter()
				.map(|(mod_id, precedence, _)| ((*mod_id).to_string(), *precedence))
				.collect(),
			reason: "mods disagree".to_string(),
		}
	}

	fn view_for(file: &str, address: &TestAddress, conflict: &TestConflict) -> ConflictView {
		ConflictView {
			file_path: game_path(file),
			address_path: address.path.clone(),
			address_key: address.key.clone(),
			conflict_id: compute_conflict_id(
				&game_path(file),
				&address.path.join("/"),
				&address.key,
			),
			reason: conflict.reason.clone(),
			vanilla_snippet: None,
			candidates: conflict
				.candidates
				.iter()
				.map(|(mod_id, precedence)| CandidateView {
					mod_id: mod_id.clone(),
					mod_display_name: mod_id.clone(),
					precedence: *precedence,
					change_summary: Vec::new(),
					candidate_rendered: String::new(),
				})
				.collect(),
		}
	}

	fn dep_handler(edges: &[(&str, &str)]) -> DepImpliesResolutionHandler {
		DepImpliesResolutionHandler::new(
			game_path("common/ideas/dep.txt"),
			DepResolutionGraph::from_edges(edges),
		)
	}

	fn assert_dep_pick(decision: ConflictDecision, expected_mod: &str, expected_rationale: &str) {
		match decision {
			ConflictDecision::PickCandidate {
				candidate,
				record: Some(record),
			} => {
				assert_eq!(candidate, 0);
				assert_eq!(record.path.as_str(), "common/ideas/dep.txt");
				assert_eq!(record.action, "dep_implied");
				assert_eq!(record.source.as_deref(), Some(expected_mod));
				assert_eq!(record.rationale.as_deref(), Some(expected_rationale));
			}
			other => panic!("expected dep-implied pick, got {other:?}"),
		}
	}

	fn mod_candidate(mod_id: &str, name: &str, dependencies: &[&str]) -> ModCandidate {
		ModCandidate {
			entry: PlaysetEntry {
				steam_id: Some(mod_id.to_string()),
				..PlaysetEntry::default()
			},
			mod_id: mod_id.to_string(),
			root_path: None,
			descriptor_path: None,
			descriptor: Some(ModDescriptor {
				name: name.to_string(),
				dependencies: dependencies.iter().map(|dep| (*dep).to_string()).collect(),
				..ModDescriptor::default()
			}),
			workshop_identity: None,
			descriptor_error: None,
			files: Vec::new(),
		}
	}

	fn handler_with_input(input: &str, tty_available: bool) -> InteractiveCliHandler {
		InteractiveCliHandler::with_io(
			Box::new(Cursor::new(input.as_bytes().to_vec())),
			Box::new(io::sink()),
			tty_available,
		)
	}

	#[derive(Clone, Default)]
	struct CountingHandler {
		calls: Rc<Cell<usize>>,
	}

	impl ConflictHandler for CountingHandler {
		fn on_conflict(&mut self, _: &ConflictView) -> ConflictDecision {
			self.calls.set(self.calls.get() + 1);
			ConflictDecision::PickCandidate {
				candidate: 1,
				record: None,
			}
		}
	}

	struct RecordedDeferHandler;

	impl ConflictHandler for RecordedDeferHandler {
		fn on_conflict(&mut self, view: &ConflictView) -> ConflictDecision {
			ConflictDecision::Defer {
				record: Some(HandlerResolutionRecord {
					path: view.file_path.clone(),
					action: "defer".to_string(),
					source: None,
					rationale: Some("matched DSL handler=defer rule".to_string()),
				}),
			}
		}
	}

	#[test]
	fn lookup_handler_replays_generic_patch_address_conflict_id() {
		let current_file = game_path("events/PirateEvents.txt");
		let conflict_id = compute_conflict_id(&current_file, "root/event", "id");
		let mut by_conflict_id = BTreeMap::new();
		by_conflict_id.insert(
			conflict_id,
			ResolutionDecision::PreferMod("mod_a".to_string()),
		);
		let map = ResolutionMap {
			by_conflict_id,
			..ResolutionMap::default()
		};
		let mut handler = LookupHandler::new(&map, current_file);

		let decision = handler.on_conflict(&view_for(
			"events/PirateEvents.txt",
			&address(),
			&conflict_with_patches(),
		));

		assert_eq!(
			decision,
			ConflictDecision::PickCandidate {
				candidate: 0,
				record: None
			}
		);
	}

	#[test]
	fn lookup_handler_prefers_the_exact_view_id_then_file_then_pattern() {
		let current_file = game_path("events/PirateEvents.txt");
		let address = address();
		let conflict = conflict_with_patches();
		let address_conflict_id =
			compute_conflict_id(&current_file, &address.path.join("/"), &address.key);
		let mut view = view_for("events/PirateEvents.txt", &address, &conflict);
		view.conflict_id = "a".repeat(64);

		let exact_map = ResolutionMap {
			by_conflict_id: BTreeMap::from([
				(
					view.conflict_id.clone(),
					ResolutionDecision::PreferMod("mod_b".to_string()),
				),
				(
					address_conflict_id.clone(),
					ResolutionDecision::PreferMod("mod_a".to_string()),
				),
			]),
			by_file: BTreeMap::from([(
				current_file.clone(),
				ResolutionDecision::PreferMod("mod_a".to_string()),
			)]),
			..ResolutionMap::default()
		};
		assert_eq!(
			LookupHandler::new(&exact_map, current_file.clone()).on_conflict(&view),
			ConflictDecision::PickCandidate {
				candidate: 1,
				record: None,
			},
			"the exact view id must beat an address-derived id and the file rule",
		);

		let address_only_map = ResolutionMap {
			by_conflict_id: BTreeMap::from([(
				address_conflict_id.clone(),
				ResolutionDecision::PreferMod("mod_a".to_string()),
			)]),
			..ResolutionMap::default()
		};
		assert_eq!(
			LookupHandler::new(&address_only_map, current_file.clone()).on_conflict(&view),
			ConflictDecision::Defer { record: None },
			"an address-derived id must not select a semantic candidate sequence",
		);

		// An address-patch view is a conflict in the file being merged, and its
		// id is derived from that file and the address. A resolution recorded
		// under that id is the exact match, found before the file rule.
		let address_view = view_for("events/PirateEvents.txt", &address, &conflict);
		assert_eq!(address_view.conflict_id, address_conflict_id);
		let address_map = ResolutionMap {
			by_conflict_id: BTreeMap::from([(
				address_conflict_id,
				ResolutionDecision::PreferMod("mod_a".to_string()),
			)]),
			by_file: BTreeMap::from([(
				current_file.clone(),
				ResolutionDecision::PreferMod("mod_b".to_string()),
			)]),
			..ResolutionMap::default()
		};
		assert_eq!(
			LookupHandler::new(&address_map, current_file.clone()).on_conflict(&address_view),
			ConflictDecision::PickCandidate {
				candidate: 0,
				record: None,
			},
			"an address-patch view's own id must beat the file rule",
		);

		let (file_matcher, leaf_matcher) =
			crate::project::parse_match_dsl("events/**").expect("compile test pattern");
		let file_map = ResolutionMap {
			by_file: BTreeMap::from([(
				current_file.clone(),
				ResolutionDecision::PreferMod("mod_b".to_string()),
			)]),
			pattern_rules: vec![crate::project::PatternRule {
				dsl: "events/**".to_string(),
				file_matcher,
				leaf_matcher,
				decision: ResolutionDecision::PreferMod("mod_a".to_string()),
			}],
			..ResolutionMap::default()
		};
		assert_eq!(
			LookupHandler::new(&file_map, current_file).on_conflict(&view),
			ConflictDecision::PickCandidate {
				candidate: 1,
				record: None,
			},
			"the legacy miss must preserve file-over-pattern precedence",
		);
	}

	#[test]
	fn lookup_handler_returns_defer_on_miss() {
		let map = ResolutionMap::default();
		let mut handler = LookupHandler::new(&map, game_path("events/PirateEvents.txt"));

		let decision = handler.on_conflict(&view_for(
			"events/PirateEvents.txt",
			&address(),
			&conflict(),
		));

		assert_eq!(decision, ConflictDecision::Defer { record: None });
	}

	#[test]
	fn lookup_handler_requests_full_view_only_after_a_named_handler_matches() {
		let current_file = game_path("events/PirateEvents.txt");
		let map = ResolutionMap {
			by_file: BTreeMap::from([(
				current_file.clone(),
				ResolutionDecision::Handler("defer".to_string()),
			)]),
			..ResolutionMap::default()
		};
		let mut handler = LookupHandler::new(&map, current_file);

		assert_eq!(
			handler.conflict_view_requirement(),
			ConflictViewRequirement::Metadata,
		);
		let view = view_for(
			"events/PirateEvents.txt",
			&address(),
			&conflict_with_patches(),
		);
		assert_eq!(
			handler.on_conflict_metadata(&ConflictMetadataView::from(&view)),
			MetadataConflictDecision::NeedsFullView,
		);
	}

	#[test]
	fn lookup_handler_defers_when_prefer_mod_is_not_an_exact_candidate() {
		let current_file = game_path("events/PirateEvents.txt");
		let conflict_id = compute_conflict_id(&current_file, "root/event", "id");
		let map = ResolutionMap {
			by_conflict_id: BTreeMap::from([(
				conflict_id,
				ResolutionDecision::PreferMod("same_mod".to_string()),
			)]),
			..ResolutionMap::default()
		};
		let conflict = conflict_with_mods(&[("same_mod", 1, "alpha"), ("same_mod", 2, "beta")]);
		let mut handler = LookupHandler::new(&map, current_file);

		let decision =
			handler.on_conflict(&view_for("events/PirateEvents.txt", &address(), &conflict));

		assert_eq!(decision, ConflictDecision::Defer { record: None });
	}

	#[test]
	fn lookup_handler_replays_exact_candidate_when_mod_ids_repeat() {
		let current_file = game_path("events/PirateEvents.txt");
		let conflict_id = compute_conflict_id(&current_file, "root/event", "id");
		let map = ResolutionMap {
			by_conflict_id: BTreeMap::from([(conflict_id, ResolutionDecision::PreferCandidate(1))]),
			..ResolutionMap::default()
		};
		let conflict = conflict_with_mods(&[("same_mod", 1, "alpha"), ("same_mod", 2, "beta")]);
		let mut handler = LookupHandler::new(&map, current_file);

		let decision =
			handler.on_conflict(&view_for("events/PirateEvents.txt", &address(), &conflict));

		assert_eq!(
			decision,
			ConflictDecision::PickCandidate {
				candidate: 1,
				record: None,
			}
		);
	}

	#[test]
	fn lookup_handler_chained_with_defer_uses_resolution_then_defers() {
		let current_file = game_path("events/PirateEvents.txt");
		let conflict_id = compute_conflict_id(&current_file, "root/event", "id");
		let mut by_conflict_id = BTreeMap::new();
		by_conflict_id.insert(
			conflict_id,
			ResolutionDecision::PreferMod("mod_a".to_string()),
		);
		let map = ResolutionMap {
			by_conflict_id,
			..ResolutionMap::default()
		};
		let mut handler = ChainHandler {
			first: LookupHandler::new(&map, current_file),
			second: DeferHandler,
		};
		let miss = TestAddress {
			path: vec!["root".to_string(), "event".to_string()],
			key: "other".to_string(),
		};
		assert_eq!(
			handler.conflict_view_requirement(),
			ConflictViewRequirement::Metadata,
		);

		let resolved_view = view_for(
			"events/PirateEvents.txt",
			&address(),
			&conflict_with_patches(),
		);
		let deferred_view = view_for("events/PirateEvents.txt", &miss, &conflict());
		let resolved = handler.on_conflict_metadata(&ConflictMetadataView::from(&resolved_view));
		let deferred = handler.on_conflict_metadata(&ConflictMetadataView::from(&deferred_view));

		assert_eq!(
			resolved,
			MetadataConflictDecision::Decision(ConflictDecision::PickCandidate {
				candidate: 0,
				record: None
			})
		);
		assert_eq!(
			deferred,
			MetadataConflictDecision::Decision(ConflictDecision::Defer { record: None })
		);
	}

	#[test]
	fn chain_handler_does_not_fall_through_recorded_defer() {
		let calls = Rc::new(Cell::new(0));
		let mut handler = ChainHandler {
			first: RecordedDeferHandler,
			second: CountingHandler {
				calls: Rc::clone(&calls),
			},
		};

		let decision = handler.on_conflict(&view_for(
			"events/PirateEvents.txt",
			&address(),
			&conflict(),
		));

		match decision {
			ConflictDecision::Defer {
				record: Some(record),
			} => assert_eq!(record.action, "defer"),
			other => panic!("expected recorded defer, got {other:?}"),
		}
		assert_eq!(calls.get(), 0);
	}

	#[test]
	fn dep_implies_resolution_picks_two_mod_downstream() {
		let mut handler = dep_handler(&[("mod_a", "mod_b")]);

		let decision = handler.on_conflict(&view_for(
			"common/ideas/dep.txt",
			&address(),
			&conflict_with_patches(),
		));

		assert_dep_pick(decision, "mod_a", "mod mod_a declares dep on mod_b");
	}

	#[test]
	fn dep_implies_resolution_picks_downstream_over_two_upstreams() {
		let mut handler = dep_handler(&[("mod_a", "mod_b"), ("mod_a", "mod_c")]);
		let conflict = conflict_with_mods(&[
			("mod_a", 3, "alpha"),
			("mod_b", 1, "beta"),
			("mod_c", 2, "gamma"),
		]);

		let decision =
			handler.on_conflict(&view_for("common/ideas/dep.txt", &address(), &conflict));

		assert_dep_pick(decision, "mod_a", "mod mod_a declares dep on mod_b");
	}

	#[test]
	fn dep_implies_resolution_picks_most_downstream_in_chain() {
		let mut handler =
			dep_handler(&[("mod_a", "mod_b"), ("mod_a", "mod_c"), ("mod_b", "mod_c")]);
		let conflict = conflict_with_mods(&[
			("mod_a", 3, "alpha"),
			("mod_b", 2, "beta"),
			("mod_c", 1, "gamma"),
		]);

		let decision =
			handler.on_conflict(&view_for("common/ideas/dep.txt", &address(), &conflict));

		assert_dep_pick(decision, "mod_a", "mod mod_a declares dep on mod_b");
	}

	#[test]
	fn dep_implies_resolution_defers_independent_mods() {
		let mut handler = dep_handler(&[]);

		let decision = handler.on_conflict(&view_for(
			"common/ideas/dep.txt",
			&address(),
			&conflict_with_patches(),
		));

		assert_eq!(decision, ConflictDecision::Defer { record: None });
	}

	#[test]
	fn dep_implies_resolution_defers_when_any_contributor_is_independent() {
		let mut handler = dep_handler(&[("mod_a", "mod_b")]);
		let conflict = conflict_with_mods(&[
			("mod_a", 3, "alpha"),
			("mod_b", 1, "beta"),
			("mod_c", 2, "gamma"),
		]);

		let decision =
			handler.on_conflict(&view_for("common/ideas/dep.txt", &address(), &conflict));

		assert_eq!(decision, ConflictDecision::Defer { record: None });
	}

	#[test]
	fn dep_implies_resolution_defers_on_cycle() {
		let mut handler = dep_handler(&[("mod_a", "mod_b"), ("mod_b", "mod_a")]);

		let decision = handler.on_conflict(&view_for(
			"common/ideas/dep.txt",
			&address(),
			&conflict_with_patches(),
		));

		assert_eq!(decision, ConflictDecision::Defer { record: None });
	}

	#[test]
	fn dep_implies_resolution_respects_dep_overrides() {
		let mods = vec![
			mod_candidate("mod_b", "Mod B", &[]),
			mod_candidate("mod_a", "Mod A", &["Mod B"]),
		];
		let (dag, diagnostics) = crate::merge::dag::build_mod_dag(&mods);
		assert!(diagnostics.is_empty());
		let graph = DepResolutionGraph::from_mod_dag(
			&dag,
			&[crate::project::DepOverride::new("mod_a", "mod_b")],
		);
		let mut handler =
			DepImpliesResolutionHandler::new(game_path("common/ideas/dep.txt"), graph);

		let decision = handler.on_conflict(&view_for(
			"common/ideas/dep.txt",
			&address(),
			&conflict_with_patches(),
		));

		assert_eq!(decision, ConflictDecision::Defer { record: None });
	}

	#[test]
	fn interactive_handler_returns_defer_on_non_tty() {
		let mut handler = handler_with_input("1\n", false);

		let decision = handler.on_conflict(&view_for(
			"events/PirateEvents.txt",
			&address(),
			&conflict_with_patches(),
		));

		assert_eq!(decision, ConflictDecision::Defer { record: None });
	}

	#[test]
	fn interactive_handler_returns_exact_candidate_on_user_choice() {
		let mut handler = handler_with_input("2\n", true);

		let decision = handler.on_conflict(&view_for(
			"events/PirateEvents.txt",
			&address(),
			&conflict_with_patches(),
		));

		assert_eq!(
			decision,
			ConflictDecision::PickCandidate {
				candidate: 1,
				record: None
			}
		);
	}

	#[test]
	fn prompt_survivors_persists_resolution_to_config_writer() {
		let root = project_test_dir("prompt_survivors_persists_resolution_to_config_writer");
		let config_path = root.join("foch.toml");
		let current_file = game_path("events/PirateEvents.txt");
		let mut handler = handler_with_input("1\n", true);
		let survivor_address = address();
		let survivor_conflict = conflict_with_patches();
		let survivors = vec![view_for(
			"events/PirateEvents.txt",
			&survivor_address,
			&survivor_conflict,
		)];

		let result =
			prompt_survivors_and_persist(&current_file, &survivors, &mut handler, &config_path);

		assert!(!result.aborted);
		assert_eq!(result.outcomes.len(), 1);
		let content = fs::read_to_string(&config_path).expect("read config");
		assert!(content.contains("[[resolutions]]"));
		assert!(content.contains("prefer_candidate = 1"));
		assert!(content.contains(&compute_conflict_id(&current_file, "root/event", "id")));
	}

	fn keep_existing_entry(file: &str) -> ResolutionEntry {
		ResolutionEntry {
			file: Some(game_path(file)),
			conflict_id: None,
			mod_id: None,
			r#match: None,
			prefer_mod: None,
			prefer_candidate: None,
			use_file: None,
			keep_existing: Some(true),
			priority_boost: None,
			handler: None,
			policy: None,
		}
	}

	/// A persisted resolution reads back as the entry that was written: the
	/// game path as its canonical text, and a host `use_file` exactly as
	/// spelled. Off Windows a `\` is part of a name, so folding it into `/`
	/// would name a different file.
	#[test]
	fn rendered_resolutions_read_back_unchanged() {
		let use_file = ResolutionEntry {
			file: None,
			conflict_id: Some("abc12345".to_string()),
			use_file: Some(PathBuf::from(r"manual\Pirate Events.txt")),
			keep_existing: None,
			..keep_existing_entry("events/PirateEvents.txt")
		};
		for entry in [
			keep_existing_entry("history/countries/FRA - France.txt"),
			use_file,
		] {
			let rendered = render_resolution_entry(&entry).expect("render");
			let read_back = crate::project::Project::from_toml_str(&rendered)
				.expect("parse rendered resolution")
				.resolutions;
			assert_eq!(read_back, [entry], "{rendered}");
		}
	}

	/// TOML text is UTF-8, so a `use_file` whose name is not has no spelling.
	#[cfg(unix)]
	#[test]
	fn a_use_file_that_is_not_utf8_is_not_written() {
		// In-memory path: some filesystems refuse to create this name.
		use std::ffi::OsStr;
		use std::os::unix::ffi::OsStrExt;

		let entry = ResolutionEntry {
			file: None,
			conflict_id: Some("abc12345".to_string()),
			use_file: Some(PathBuf::from(OsStr::from_bytes(b"manual/\xff.txt"))),
			keep_existing: None,
			..keep_existing_entry("events/PirateEvents.txt")
		};
		let error = render_resolution_entry(&entry).expect_err("non-UTF-8 use_file");
		assert_eq!(error.kind(), io::ErrorKind::InvalidData);
	}

	#[test]
	fn interactive_handler_returns_keep_existing_on_user_choice_k() {
		let mut handler = handler_with_input("k\n", true);

		let decision = handler.on_conflict(&view_for(
			"events/PirateEvents.txt",
			&address(),
			&conflict_with_patches(),
		));

		assert_eq!(decision, ConflictDecision::KeepExisting);
	}

	#[test]
	fn interactive_handler_invalid_input_eventually_defers() {
		let mut handler = handler_with_input("x\ny\n0\n", true);

		let decision = handler.on_conflict(&view_for(
			"events/PirateEvents.txt",
			&address(),
			&conflict_with_patches(),
		));

		assert_eq!(decision, ConflictDecision::Defer { record: None });
	}

	#[test]
	fn interactive_handler_returns_use_file_resolution() {
		let mut handler = handler_with_input("s\nresolutions/PirateEvents.txt\n", true);

		let decision = handler.on_conflict(&view_for(
			"events/PirateEvents.txt",
			&address(),
			&conflict_with_patches(),
		));

		assert_eq!(
			decision,
			ConflictDecision::UseFile(PathBuf::from("resolutions/PirateEvents.txt"))
		);
	}

	#[test]
	fn merge_command_with_interactive_handler_chains_handlers_correctly() {
		let current_file = game_path("events/PirateEvents.txt");
		let conflict_id = compute_conflict_id(&current_file, "root/event", "id");
		let mut by_conflict_id = BTreeMap::new();
		by_conflict_id.insert(
			conflict_id,
			ResolutionDecision::PreferMod("mod_a".to_string()),
		);
		let map = ResolutionMap {
			by_conflict_id,
			..ResolutionMap::default()
		};
		let calls = Rc::new(Cell::new(0));
		let interactive = CountingHandler {
			calls: Rc::clone(&calls),
		};
		let mut handler = ChainHandler {
			first: LookupHandler::new(&map, current_file),
			second: ChainHandler {
				first: interactive,
				second: DeferHandler,
			},
		};

		let decision = handler.on_conflict(&view_for(
			"events/PirateEvents.txt",
			&address(),
			&conflict_with_patches(),
		));

		assert_eq!(
			decision,
			ConflictDecision::PickCandidate {
				candidate: 0,
				record: None
			}
		);
		assert_eq!(
			calls.get(),
			0,
			"lookup hit should not invoke interactive handler"
		);
	}

	#[test]
	fn filesystem_config_writer_appends_resolution_without_dropping_existing_content() {
		let root = project_test_dir("filesystem_config_writer_appends_resolution");
		let path = root.join("foch.toml");
		fs::create_dir_all(&root).expect("create test dir");
		fs::write(
			&path,
			r#"# keep this comment

[[overrides]]
mod = "a"
dep = "b"
"#,
		)
		.expect("write config");
		let writer = FilesystemConfigWriter::new(path.clone());

		writer
			.append_resolution(ResolutionEntry {
				file: None,
				conflict_id: Some("abc12345".to_string()),
				mod_id: None,
				r#match: None,
				prefer_mod: Some("mod_a".to_string()),
				prefer_candidate: None,
				use_file: None,
				keep_existing: None,
				priority_boost: None,
				handler: None,
				policy: None,
			})
			.expect("append resolution");

		let content = fs::read_to_string(&path).expect("read config");
		assert!(content.contains("# keep this comment"));
		assert!(content.contains("[[overrides]]"));
		assert!(content.contains("[[resolutions]]"));
		assert!(content.contains(r#"conflict_id = "abc12345""#));
		assert!(content.contains(r#"prefer_mod = "mod_a""#));
		let parsed = crate::project::Project::from_toml_str(&content).expect("parse config");
		assert_eq!(parsed.resolutions.len(), 1);
	}

	/// A file picked during the run was read relative to the working
	/// directory. The config would read the same text from its own directory,
	/// so the recorded `use_file` is absolute and reloads to the picked file.
	#[test]
	fn filesystem_config_writer_records_a_relative_use_file_as_absolute() {
		let root = project_test_dir("filesystem_config_writer_records_absolute_use_file");
		let path = root.join("nested").join("foch.toml");
		let picked = PathBuf::from("resolutions").join("PirateEvents.txt");
		FilesystemConfigWriter::new(path.clone())
			.append_resolution(ResolutionEntry {
				file: None,
				conflict_id: Some("abc12345".to_string()),
				mod_id: None,
				r#match: None,
				prefer_mod: None,
				prefer_candidate: None,
				use_file: Some(picked.clone()),
				keep_existing: None,
				priority_boost: None,
				handler: None,
				policy: None,
			})
			.expect("append resolution");

		let reloaded = crate::project::Project::load_from_path(&path).expect("reload config");
		assert_eq!(
			reloaded.resolutions[0].use_file,
			Some(std::path::absolute(&picked).expect("absolute picked path"))
		);
	}

	/// A config's staging sibling extends its name as it is: two configs
	/// whose names are not UTF-8 are staged apart, not both at a
	/// `.foch.toml` sibling. In memory: some filesystems refuse such names.
	#[cfg(unix)]
	#[test]
	fn config_staging_keeps_a_name_that_is_not_utf8() {
		use std::os::unix::ffi::OsStrExt;

		let directory = Path::new("/projects/merge");
		let first = FilesystemConfigWriter::new(directory.join(OsStr::from_bytes(b"a\xff.toml")))
			.temporary_path();
		let second = FilesystemConfigWriter::new(directory.join(OsStr::from_bytes(b"b\xff.toml")))
			.temporary_path();
		let pid = std::process::id();
		assert_eq!(
			first,
			directory.join(OsStr::from_bytes(
				&[&b".a\xff.toml."[..], format!("{pid}.tmp").as_bytes()].concat()
			))
		);
		assert_ne!(first, second);
		assert_eq!(
			FilesystemConfigWriter::new(directory.join("foch.toml")).temporary_path(),
			directory.join(format!(".foch.toml.{pid}.tmp"))
		);
	}

	fn project_test_dir(name: &str) -> PathBuf {
		let nanos = SystemTime::now()
			.duration_since(UNIX_EPOCH)
			.expect("clock after epoch")
			.as_nanos();
		std::env::current_dir()
			.expect("current dir")
			.join("target")
			.join("foch-tests")
			.join(format!("{name}-{}-{nanos}", std::process::id()))
	}
}