foch 0.0.1

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
//! Kernel-neutral per-file dependency graph.
//!
//! DAG-driven N-way merge base resolution (see
//! `docs/dag-merge-design.md`). This module owns dependency topology only;
//! [`super::dag_pipeline`] schedules kernel-specific state construction and
//! joins.
//!
//! Scope of this file:
//! * Build a mod-level dependency DAG from declared `descriptor.mod`
//!   dependencies, resolved against [`ModIdentityIndex`].
//! * Detect cycles via Tarjan's SCC and break them deterministically by
//!   playlist position.
//! * Restrict the global DAG to the subset of mods shipping a particular
//!   file (`induced_file_dag`), lifting edges through skipped nodes.
//! * Apply `replace_path` semantics: drop earlier contributors under the
//!   replaced prefix and mark the replacing contributor in the file DAG.
//! * Expose deterministic ancestry levels for the shared DAG walker.

#![allow(dead_code)]

use std::collections::{BTreeSet, HashMap, HashSet};

use crate::model::{GamePath, GamePathBuf, ModCandidate};
use crate::playset::dependency::ModIdentityIndex;
use crate::project::DepOverride;

use crate::input::ResolvedInputContributor;

// ---------------------------------------------------------------------------
// Identifiers
// ---------------------------------------------------------------------------

/// Stable identifier for a mod within a single DAG. Currently the same
/// `mod_id` string `ModCandidate` exposes (typically the steam id, or a
/// synthesized id for local mods). Wrapping it as a newtype keeps the API
/// honest: a `ModId` is never confused with an arbitrary `String`.
#[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct ModId(pub String);

impl ModId {
	pub fn as_str(&self) -> &str {
		&self.0
	}
}

impl From<&str> for ModId {
	fn from(s: &str) -> Self {
		Self(s.to_string())
	}
}

impl From<String> for ModId {
	fn from(s: String) -> Self {
		Self(s)
	}
}

// ---------------------------------------------------------------------------
// Diagnostics
// ---------------------------------------------------------------------------

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DagDiagnosticSeverity {
	Warning,
	Info,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DagDiagnosticKind {
	/// `mod_id` declared a dep string that does not resolve in the playset.
	MissingDependency { mod_id: ModId, dep_token: String },
	/// A cycle was detected; lists the mods involved (in topo input order).
	DependencyCycle { members: Vec<ModId> },
	/// An edge was removed to break a cycle.
	BrokenCycleEdge { child: ModId, parent: ModId },
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DagDiagnostic {
	pub severity: DagDiagnosticSeverity,
	pub kind: DagDiagnosticKind,
}

// ---------------------------------------------------------------------------
// ModDag (mod-level)
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, Default)]
pub struct ModDag {
	/// Child → parents (in declaration order, deduplicated).
	parents: HashMap<ModId, Vec<ModId>>,
	/// Parent → children (deterministic order = playlist position of the
	/// child).
	children: HashMap<ModId, Vec<ModId>>,
	/// Topological order (parents before children).
	topo: Vec<ModId>,
	/// Playset position for each mod (stable break tiebreak).
	position: HashMap<ModId, usize>,
	/// Mods declared a dep that wasn't in the playset (collected for
	/// diagnostics; the dep is treated as absent for DAG purposes).
	missing_deps: Vec<(ModId, String)>,
	/// The directories each mod's `replace_path` declares.
	replace_paths: HashMap<ModId, Vec<GamePathBuf>>,
}

impl ModDag {
	pub fn parents_of(&self, mod_id: &ModId) -> &[ModId] {
		self.parents
			.get(mod_id)
			.map(|v| v.as_slice())
			.unwrap_or(&[])
	}

	pub fn children_of(&self, mod_id: &ModId) -> &[ModId] {
		self.children
			.get(mod_id)
			.map(|v| v.as_slice())
			.unwrap_or(&[])
	}

	pub fn topo(&self) -> &[ModId] {
		&self.topo
	}

	pub fn missing_deps(&self) -> &[(ModId, String)] {
		&self.missing_deps
	}

	pub fn position(&self, mod_id: &ModId) -> Option<usize> {
		self.position.get(mod_id).copied()
	}

	pub fn replace_paths(&self, mod_id: &ModId) -> &[GamePathBuf] {
		self.replace_paths
			.get(mod_id)
			.map(|v| v.as_slice())
			.unwrap_or(&[])
	}
}

// ---------------------------------------------------------------------------
// build_mod_dag
// ---------------------------------------------------------------------------

/// Build the mod-level dependency DAG from `mods` (sorted by playlist
/// position). Returns the DAG plus diagnostics for missing deps and cycles.
pub fn build_mod_dag(mods: &[ModCandidate]) -> (ModDag, Vec<DagDiagnostic>) {
	let identity = ModIdentityIndex::from_mods(mods);
	let mut diagnostics = Vec::new();

	let ids: Vec<ModId> = mods.iter().map(|m| ModId(m.mod_id.clone())).collect();
	let mut position: HashMap<ModId, usize> = HashMap::new();
	for (idx, id) in ids.iter().enumerate() {
		position.insert(id.clone(), idx);
	}

	let mut parents: HashMap<ModId, Vec<ModId>> = HashMap::new();
	let mut missing_deps: Vec<(ModId, String)> = Vec::new();
	let mut replace_paths: HashMap<ModId, Vec<GamePathBuf>> = HashMap::new();

	for (idx, candidate) in mods.iter().enumerate() {
		let me = ids[idx].clone();
		let descriptor = match candidate.descriptor.as_ref() {
			Some(d) => d,
			None => {
				parents.entry(me.clone()).or_default();
				continue;
			}
		};

		// Resolve declared deps.
		let mut my_parents: Vec<ModId> = Vec::new();
		let mut seen: HashSet<ModId> = HashSet::new();
		for dep_token in &descriptor.dependencies {
			match identity.lookup(dep_token) {
				Some(parent_idx) if parent_idx != idx => {
					let parent_id = ids[parent_idx].clone();
					if seen.insert(parent_id.clone()) {
						my_parents.push(parent_id);
					}
				}
				Some(_) => {
					// Self-dep: silently drop (not actionable).
				}
				None => {
					diagnostics.push(DagDiagnostic {
						severity: DagDiagnosticSeverity::Warning,
						kind: DagDiagnosticKind::MissingDependency {
							mod_id: me.clone(),
							dep_token: dep_token.clone(),
						},
					});
					missing_deps.push((me.clone(), dep_token.clone()));
				}
			}
		}
		parents.insert(me.clone(), my_parents);

		if !descriptor.replace_path.is_empty() {
			replace_paths.insert(me.clone(), descriptor.replace_path.clone());
		}
	}

	// Cycle detection + deterministic break.
	break_cycles(&ids, &mut parents, &position, &mut diagnostics);

	// Build children (deterministic by playlist position).
	let mut children: HashMap<ModId, Vec<ModId>> = HashMap::new();
	for child in &ids {
		for parent in parents.get(child).cloned().unwrap_or_default() {
			children.entry(parent).or_default().push(child.clone());
		}
	}
	for v in children.values_mut() {
		v.sort_by_key(|c| position.get(c).copied().unwrap_or(usize::MAX));
		v.dedup();
	}

	// Topological sort using Kahn's algorithm with deterministic ordering by
	// playlist position.
	let topo = topo_sort(&ids, &parents);

	let dag = ModDag {
		parents,
		children,
		topo,
		position,
		missing_deps,
		replace_paths,
	};
	(dag, diagnostics)
}

/// Tarjan SCC: find any cycle, then drop the edge whose *child* has the
/// highest playlist position (loaded latest). Repeat until acyclic.
fn break_cycles(
	ids: &[ModId],
	parents: &mut HashMap<ModId, Vec<ModId>>,
	position: &HashMap<ModId, usize>,
	diagnostics: &mut Vec<DagDiagnostic>,
) {
	loop {
		let sccs = tarjan_sccs(ids, parents);
		// A cycle is any SCC of size ≥ 2, or a self-loop (size 1 with edge
		// to itself — already filtered in build_mod_dag, but defensive).
		let cyclic_scc = sccs.into_iter().find(|s| {
			s.len() > 1
				|| s.iter()
					.any(|m| parents.get(m).is_some_and(|ps| ps.contains(m)))
		});
		let scc = match cyclic_scc {
			Some(s) => s,
			None => return,
		};

		diagnostics.push(DagDiagnostic {
			severity: DagDiagnosticSeverity::Warning,
			kind: DagDiagnosticKind::DependencyCycle {
				members: scc.clone(),
			},
		});

		// Find the child with the highest position whose parents contain a
		// member of the SCC. Drop that edge (child → parent).
		let scc_set: HashSet<&ModId> = scc.iter().collect();
		let mut victim: Option<(ModId, ModId)> = None;
		let mut victim_pos: usize = 0;
		for child in &scc {
			if let Some(ps) = parents.get(child) {
				for p in ps {
					if scc_set.contains(p) {
						let pos = position.get(child).copied().unwrap_or(0);
						if victim.is_none() || pos > victim_pos {
							victim = Some((child.clone(), p.clone()));
							victim_pos = pos;
						}
					}
				}
			}
		}

		let (child, parent) = match victim {
			Some(v) => v,
			None => return, // shouldn't happen
		};

		if let Some(ps) = parents.get_mut(&child) {
			ps.retain(|p| p != &parent);
		}
		diagnostics.push(DagDiagnostic {
			severity: DagDiagnosticSeverity::Info,
			kind: DagDiagnosticKind::BrokenCycleEdge { child, parent },
		});
	}
}

/// Tarjan's SCC algorithm. Iteration order over `ids` is deterministic
/// (= playlist position).
fn tarjan_sccs(ids: &[ModId], parents: &HashMap<ModId, Vec<ModId>>) -> Vec<Vec<ModId>> {
	struct State<'a> {
		index_counter: usize,
		stack: Vec<&'a ModId>,
		on_stack: HashSet<&'a ModId>,
		index: HashMap<&'a ModId, usize>,
		lowlink: HashMap<&'a ModId, usize>,
		sccs: Vec<Vec<ModId>>,
	}

	fn strongconnect<'a>(
		v: &'a ModId,
		state: &mut State<'a>,
		parents: &'a HashMap<ModId, Vec<ModId>>,
	) {
		state.index.insert(v, state.index_counter);
		state.lowlink.insert(v, state.index_counter);
		state.index_counter += 1;
		state.stack.push(v);
		state.on_stack.insert(v);

		if let Some(ps) = parents.get(v) {
			for w in ps {
				if !state.index.contains_key(w) {
					strongconnect(w, state, parents);
					let wl = state.lowlink[w];
					let vl = state.lowlink[v];
					state.lowlink.insert(v, vl.min(wl));
				} else if state.on_stack.contains(w) {
					let widx = state.index[w];
					let vl = state.lowlink[v];
					state.lowlink.insert(v, vl.min(widx));
				}
			}
		}

		if state.lowlink[v] == state.index[v] {
			let mut scc: Vec<ModId> = Vec::new();
			while let Some(w) = state.stack.pop() {
				state.on_stack.remove(w);
				scc.push(w.clone());
				if w == v {
					break;
				}
			}
			state.sccs.push(scc);
		}
	}

	let mut state = State {
		index_counter: 0,
		stack: Vec::new(),
		on_stack: HashSet::new(),
		index: HashMap::new(),
		lowlink: HashMap::new(),
		sccs: Vec::new(),
	};

	for v in ids {
		if !state.index.contains_key(v) {
			strongconnect(v, &mut state, parents);
		}
	}
	state.sccs
}

/// Kahn's algorithm with stable ordering = playlist position.
fn topo_sort(ids: &[ModId], parents: &HashMap<ModId, Vec<ModId>>) -> Vec<ModId> {
	// in-degree = number of parents. Nodes with zero parents go first.
	let mut indeg: HashMap<&ModId, usize> = HashMap::new();
	for id in ids {
		indeg.insert(id, parents.get(id).map(|p| p.len()).unwrap_or(0));
	}
	// children index for the iteration.
	let mut child_index: HashMap<&ModId, Vec<&ModId>> = HashMap::new();
	for id in ids {
		if let Some(ps) = parents.get(id) {
			for p in ps {
				child_index.entry(p).or_default().push(id);
			}
		}
	}

	let mut ready: Vec<&ModId> = ids.iter().filter(|id| indeg[id] == 0).collect();
	let mut out: Vec<ModId> = Vec::with_capacity(ids.len());
	while !ready.is_empty() {
		// Stable: pop the lowest playlist position.
		ready.sort_by_key(|id| ids.iter().position(|x| x == *id).unwrap_or(usize::MAX));
		let next = ready.remove(0);
		out.push(next.clone());
		if let Some(cs) = child_index.get(next) {
			for c in cs {
				let e = indeg.get_mut(c).expect("child indeg present");
				*e -= 1;
				if *e == 0 {
					ready.push(*c);
				}
			}
		}
	}
	// If the graph still has cycles (shouldn't after break_cycles), append
	// the leftover in playlist order so callers still get every node.
	if out.len() < ids.len() {
		let placed: HashSet<ModId> = out.iter().cloned().collect();
		for id in ids {
			if !placed.contains(id) {
				out.push(id.clone());
			}
		}
	}
	out
}

// ---------------------------------------------------------------------------
// FileDag (per-file induced subgraph)
// ---------------------------------------------------------------------------

#[derive(Clone, Debug)]
pub struct FileDag {
	pub file_path: GamePathBuf,
	/// Contributing mods in playlist order (after replace_path filtering).
	contributors: Vec<ModId>,
	contributor_set: HashSet<ModId>,
	/// Per-mod parents (lifted ancestor closure restricted to contributors).
	parents: HashMap<ModId, Vec<ModId>>,
	/// Mods whose per-file base is forced empty by their own replace_path.
	replace_path_owners: HashSet<ModId>,
	position: HashMap<ModId, usize>,
}

impl FileDag {
	/// A DAG for `file_path` with no contributors.
	#[cfg(test)]
	pub(crate) fn empty(file_path: GamePathBuf) -> Self {
		Self {
			file_path,
			contributors: Vec::new(),
			contributor_set: HashSet::new(),
			parents: HashMap::new(),
			replace_path_owners: HashSet::new(),
			position: HashMap::new(),
		}
	}

	pub fn file_path(&self) -> &GamePath {
		&self.file_path
	}
	pub fn contributors(&self) -> &[ModId] {
		&self.contributors
	}
	pub fn parents_of(&self, mod_id: &ModId) -> &[ModId] {
		self.parents
			.get(mod_id)
			.map(|v| v.as_slice())
			.unwrap_or(&[])
	}
	pub fn ancestors_of(&self, mod_id: &ModId) -> Vec<ModId> {
		let mut out = Vec::new();
		let mut seen = HashSet::new();
		self.collect_ancestors(mod_id, &mut seen, &mut out);
		out.sort_by_key(|m| self.precedence_of(m));
		out.dedup();
		out
	}
	fn collect_ancestors(&self, mod_id: &ModId, seen: &mut HashSet<ModId>, out: &mut Vec<ModId>) {
		for parent in self.parents_of(mod_id) {
			if seen.insert(parent.clone()) {
				self.collect_ancestors(parent, seen, out);
				out.push(parent.clone());
			}
		}
	}
	pub fn precedence_of(&self, mod_id: &ModId) -> usize {
		self.position.get(mod_id).copied().unwrap_or(usize::MAX)
	}
	pub fn ships(&self, mod_id: &ModId) -> bool {
		self.contributor_set.contains(mod_id)
	}
	pub fn replaces_path(&self, mod_id: &ModId) -> bool {
		self.replace_path_owners.contains(mod_id)
	}
	pub fn has_replace_path_owner(&self) -> bool {
		!self.replace_path_owners.is_empty()
	}
}

pub(crate) fn topo_levels(parents: &BTreeSet<ModId>, file_dag: &FileDag) -> Vec<Vec<ModId>> {
	if parents.is_empty() {
		return Vec::new();
	}

	let parent_set: HashSet<ModId> = parents.iter().cloned().collect();
	let mut indegree: HashMap<ModId, usize> =
		parents.iter().cloned().map(|parent| (parent, 0)).collect();
	let mut children: HashMap<ModId, Vec<ModId>> = HashMap::new();

	for child in parents {
		for ancestor in file_dag.ancestors_of(child) {
			if !parent_set.contains(&ancestor) {
				continue;
			}
			children
				.entry(ancestor.clone())
				.or_default()
				.push(child.clone());
			*indegree
				.get_mut(child)
				.expect("all parent nodes have indegree slots") += 1;
		}
	}

	for children in children.values_mut() {
		children.sort_by_key(|child| file_dag.precedence_of(child));
		children.dedup();
	}

	let mut ready: Vec<ModId> = parents
		.iter()
		.filter(|parent| indegree.get(*parent).copied().unwrap_or(0) == 0)
		.cloned()
		.collect();
	ready.sort_by_key(|parent| file_dag.precedence_of(parent));

	let mut levels = Vec::new();
	let mut placed: HashSet<ModId> = HashSet::new();
	while !ready.is_empty() {
		let level = ready;
		for parent in &level {
			placed.insert(parent.clone());
		}

		let mut next = Vec::new();
		for parent in &level {
			if let Some(children) = children.get(parent) {
				for child in children {
					let child_indegree = indegree
						.get_mut(child)
						.expect("child nodes have indegree slots");
					*child_indegree -= 1;
					if *child_indegree == 0 {
						next.push(child.clone());
					}
				}
			}
		}
		next.sort_by_key(|parent| file_dag.precedence_of(parent));
		next.dedup();
		levels.push(level);
		ready = next;
	}

	if placed.len() < parents.len() {
		let mut leftover: Vec<ModId> = parents
			.iter()
			.filter(|parent| !placed.contains(*parent))
			.cloned()
			.collect();
		leftover.sort_by_key(|parent| file_dag.precedence_of(parent));
		levels.push(leftover);
	}

	levels
}

/// Configuration for `replace_path` semantics. The merge CLI exposes the
/// all-mods override as `--ignore-replace-path`.
#[derive(Clone, Debug, Default)]
pub enum IgnoreReplacePath {
	#[default]
	None,
	Mods(HashSet<ModId>),
	All,
}

impl IgnoreReplacePath {
	fn applies_to(&self, mod_id: &ModId) -> bool {
		match self {
			IgnoreReplacePath::None => false,
			IgnoreReplacePath::All => true,
			IgnoreReplacePath::Mods(ms) => ms.contains(mod_id),
		}
	}
}

/// Build the per-file induced subgraph. `contributors` is the file
/// inventory entry (already sorted by precedence; base-game and synthetic
/// base entries are filtered out by the caller — they are *not* part of
/// the DAG node set).
pub fn induced_file_dag(
	global: &ModDag,
	file_path: &GamePath,
	contributors: &[ResolvedInputContributor],
	ignore: &IgnoreReplacePath,
) -> FileDag {
	induced_file_dag_with_overrides(global, file_path, contributors, ignore, &[])
}

pub fn induced_file_dag_with_overrides(
	global: &ModDag,
	file_path: &GamePath,
	contributors: &[ResolvedInputContributor],
	ignore: &IgnoreReplacePath,
	dep_overrides: &[DepOverride],
) -> FileDag {
	// Initial contributor list (mod ids only — base-game/synthetic dropped).
	let mut active: Vec<(ModId, usize)> = contributors
		.iter()
		.filter(|c| !c.is_base_game && !c.is_synthetic_base)
		.map(|c| (ModId(c.mod_id.clone()), c.precedence))
		.collect();
	active.sort_by_key(|(_, p)| *p);

	// Apply replace_path filtering: for any mod M in `active` that owns a
	// replace_path covering file_path, drop earlier-precedence contributors.
	// Higher-precedence contributors stay (loader semantics).
	let mut replace_path_owners: HashSet<ModId> = HashSet::new();
	let mut drop_before: Option<usize> = None;
	for (mid, prec) in &active {
		if ignore.applies_to(mid) {
			continue;
		}
		if global
			.replace_paths(mid)
			.iter()
			.any(|prefix| file_path.starts_with(prefix))
		{
			replace_path_owners.insert(mid.clone());
			// Drop everything with strictly lower precedence than `prec`
			// from active. Track the highest such cut-off.
			drop_before = Some(drop_before.map_or(*prec, |c| c.max(*prec)));
		}
	}
	if let Some(cutoff) = drop_before {
		active.retain(|(mid, prec)| *prec >= cutoff || replace_path_owners.contains(mid));
	}

	let contributor_set: HashSet<ModId> = active.iter().map(|(m, _)| m.clone()).collect();
	let contributors_ordered: Vec<ModId> = active.iter().map(|(m, _)| m.clone()).collect();
	let mut position: HashMap<ModId, usize> = HashMap::new();
	for (m, precedence) in &active {
		position.insert(m.clone(), *precedence);
	}

	// Lift edges through skipped (non-contributing) ancestors.
	let dep_override_set = DepOverrideSet::new(dep_overrides);
	let mut parents: HashMap<ModId, Vec<ModId>> = HashMap::new();
	for child in &contributors_ordered {
		if replace_path_owners.contains(child) {
			// Replace_path means "fresh start" — no parents.
			parents.insert(child.clone(), Vec::new());
			continue;
		}
		let lifted = lift_ancestor_edges(global, child, &contributor_set, &dep_override_set);
		parents.insert(child.clone(), lifted);
	}

	FileDag {
		file_path: file_path.to_owned(),
		contributors: contributors_ordered,
		contributor_set,
		parents,
		replace_path_owners,
		position,
	}
}

#[derive(Clone, Debug, Default)]
struct DepOverrideSet {
	edges: HashSet<(ModId, ModId)>,
}

impl DepOverrideSet {
	fn new(overrides: &[DepOverride]) -> Self {
		Self {
			edges: overrides
				.iter()
				.map(|item| (ModId(item.mod_id.clone()), ModId(item.dep_id.clone())))
				.collect(),
		}
	}

	fn contains(&self, child: &ModId, parent: &ModId) -> bool {
		self.edges.contains(&(child.clone(), parent.clone()))
	}
}

/// Walk up `child`'s ancestors in the global DAG. For each ancestor that is
/// also a contributor, record it as a (lifted) parent and stop. For
/// non-contributing ancestors, recurse through *their* parents — this
/// implements the transitive ancestor closure restricted to `members`.
fn lift_ancestor_edges(
	global: &ModDag,
	child: &ModId,
	members: &HashSet<ModId>,
	dep_overrides: &DepOverrideSet,
) -> Vec<ModId> {
	let mut out: Vec<ModId> = Vec::new();
	let mut seen: HashSet<ModId> = HashSet::new();
	let mut stack: Vec<(ModId, ModId)> = global
		.parents_of(child)
		.iter()
		.cloned()
		.map(|parent| (child.clone(), parent))
		.collect();
	while let Some((edge_child, parent)) = stack.pop() {
		if dep_overrides.contains(&edge_child, &parent) {
			continue;
		}
		if !seen.insert(parent.clone()) {
			continue;
		}
		if members.contains(&parent) {
			out.push(parent);
		} else {
			for grandparent in global.parents_of(&parent) {
				stack.push((parent.clone(), grandparent.clone()));
			}
		}
	}
	// Deterministic ordering: by topo position in `global`.
	let topo_pos: HashMap<&ModId, usize> = global
		.topo()
		.iter()
		.enumerate()
		.map(|(i, m)| (m, i))
		.collect();
	out.sort_by_key(|m| topo_pos.get(m).copied().unwrap_or(usize::MAX));
	out.dedup();
	out
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
	use super::*;
	use crate::playset::PlaysetEntry;
	use crate::playset::descriptor::ModDescriptor;
	use std::path::PathBuf;

	fn mod_with(
		mod_id: &str,
		name: &str,
		dependencies: Vec<&str>,
		replace_path: Vec<&str>,
	) -> ModCandidate {
		let descriptor = ModDescriptor {
			name: name.to_string(),
			dependencies: dependencies.into_iter().map(str::to_string).collect(),
			replace_path: replace_path
				.into_iter()
				.map(|path| GamePathBuf::parse(path).expect("valid game path"))
				.collect(),
			..ModDescriptor::default()
		};
		let entry = PlaysetEntry {
			steam_id: Some(mod_id.to_string()),
			..PlaysetEntry::default()
		};
		ModCandidate {
			entry,
			mod_id: mod_id.to_string(),
			root_path: None,
			descriptor_path: None,
			descriptor: Some(descriptor),
			workshop_identity: None,
			descriptor_error: None,
			files: Vec::new(),
		}
	}

	fn mid(s: &str) -> ModId {
		ModId(s.to_string())
	}

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

	fn file_contributor(mod_id: &str, precedence: usize) -> ResolvedInputContributor {
		ResolvedInputContributor {
			mod_id: mod_id.to_string(),
			root_path: PathBuf::from(format!("/mods/{mod_id}")),
			relative_path: crate::model::GamePathBuf::parse("common/foo.txt")
				.expect("valid game path"),
			precedence,
			is_base_game: false,
			is_synthetic_base: false,
			parse_ok_hint: None,
			mod_hash: Some(format!("hash-{mod_id}")),
		}
	}

	// -----------------------------------------------------------------------
	// Design §F.1 cases
	// -----------------------------------------------------------------------

	#[test]
	fn independent_mods_have_no_file_parents() {
		let mods = vec![
			mod_with("a", "A", vec![], vec![]),
			mod_with("b", "B", vec![], vec![]),
			mod_with("c", "C", vec![], vec![]),
		];
		let (dag, diags) = build_mod_dag(&mods);
		assert!(diags.is_empty());
		assert_eq!(dag.parents_of(&mid("a")), &[] as &[ModId]);
		assert_eq!(dag.parents_of(&mid("b")), &[] as &[ModId]);
		assert_eq!(dag.parents_of(&mid("c")), &[] as &[ModId]);

		let contribs = vec![
			file_contributor("a", 1),
			file_contributor("b", 2),
			file_contributor("c", 3),
		];
		let fdag = induced_file_dag(
			&dag,
			game_path("common/foo.txt"),
			&contribs,
			&IgnoreReplacePath::None,
		);
		for m in ["a", "b", "c"] {
			assert!(fdag.parents_of(&mid(m)).is_empty(), "{m}");
			assert!(fdag.ancestors_of(&mid(m)).is_empty(), "{m}");
		}
	}

	#[test]
	fn single_dep() {
		let mods = vec![
			mod_with("a", "A", vec![], vec![]),
			mod_with("b", "B", vec!["A"], vec![]),
		];
		let (dag, diags) = build_mod_dag(&mods);
		assert!(diags.is_empty());
		assert_eq!(dag.parents_of(&mid("b")), &[mid("a")]);
		assert_eq!(dag.children_of(&mid("a")), &[mid("b")]);

		let contribs = vec![file_contributor("a", 1), file_contributor("b", 2)];
		let fdag = induced_file_dag(
			&dag,
			game_path("common/foo.txt"),
			&contribs,
			&IgnoreReplacePath::None,
		);
		assert!(fdag.parents_of(&mid("a")).is_empty());
		assert_eq!(fdag.parents_of(&mid("b")), &[mid("a")]);
		assert_eq!(fdag.ancestors_of(&mid("b")), vec![mid("a")]);
	}

	#[test]
	fn dep_override_drops_file_edge_and_restores_vanilla_base() {
		let mods = vec![
			mod_with("a", "A", vec![], vec![]),
			mod_with("b", "B", vec!["A"], vec![]),
			mod_with("c", "C", vec![], vec![]),
		];
		let (dag, diags) = build_mod_dag(&mods);
		assert!(diags.is_empty());
		assert_eq!(dag.parents_of(&mid("b")), &[mid("a")]);

		let contribs = vec![
			file_contributor("a", 1),
			file_contributor("b", 2),
			file_contributor("c", 3),
		];
		let overrides = vec![DepOverride::new("b", "a")];
		let fdag = induced_file_dag_with_overrides(
			&dag,
			game_path("common/foo.txt"),
			&contribs,
			&IgnoreReplacePath::None,
			&overrides,
		);

		assert_eq!(fdag.parents_of(&mid("b")), &[] as &[ModId]);
		assert!(fdag.ancestors_of(&mid("b")).is_empty());
	}

	#[test]
	fn two_deps_diamond() {
		let mods = vec![
			mod_with("a", "A", vec![], vec![]),
			mod_with("b", "B", vec![], vec![]),
			mod_with("d", "D", vec!["A", "B"], vec![]),
		];
		let (dag, diags) = build_mod_dag(&mods);
		assert!(diags.is_empty());
		// D's parents are A and B (in declaration order).
		assert_eq!(dag.parents_of(&mid("d")), &[mid("a"), mid("b")]);

		let contribs = vec![
			file_contributor("a", 1),
			file_contributor("b", 2),
			file_contributor("d", 3),
		];
		let fdag = induced_file_dag(
			&dag,
			game_path("common/foo.txt"),
			&contribs,
			&IgnoreReplacePath::None,
		);
		assert_eq!(fdag.parents_of(&mid("d")), &[mid("a"), mid("b")]);
		assert_eq!(fdag.ancestors_of(&mid("d")), vec![mid("a"), mid("b")]);
	}

	#[test]
	fn transitive_chain() {
		let mods = vec![
			mod_with("a", "A", vec![], vec![]),
			mod_with("b", "B", vec!["A"], vec![]),
			mod_with("c", "C", vec!["B"], vec![]),
		];
		let (dag, diags) = build_mod_dag(&mods);
		assert!(diags.is_empty());
		// Topo order respects parents-before-children.
		let topo = dag.topo();
		let pos = |m: &str| topo.iter().position(|x| x == &mid(m)).unwrap();
		assert!(pos("a") < pos("b"));
		assert!(pos("b") < pos("c"));

		// Per-file: C's induced parents include only B (direct); A is
		// transitive through B and not a direct parent in the file DAG.
		let contribs = vec![
			file_contributor("a", 1),
			file_contributor("b", 2),
			file_contributor("c", 3),
		];
		let fdag = induced_file_dag(
			&dag,
			game_path("common/foo.txt"),
			&contribs,
			&IgnoreReplacePath::None,
		);
		assert_eq!(fdag.parents_of(&mid("c")), &[mid("b")]);
		assert_eq!(fdag.parents_of(&mid("b")), &[mid("a")]);
		assert_eq!(fdag.parents_of(&mid("a")), &[] as &[ModId]);
	}

	#[test]
	fn cycle_break() {
		let mods = vec![
			mod_with("a", "A", vec!["B"], vec![]),
			mod_with("b", "B", vec!["A"], vec![]),
		];
		let (dag, diags) = build_mod_dag(&mods);
		// Diagnostics should contain a cycle warning + a break-edge info.
		let has_cycle = diags
			.iter()
			.any(|d| matches!(d.kind, DagDiagnosticKind::DependencyCycle { .. }));
		let has_break = diags
			.iter()
			.any(|d| matches!(d.kind, DagDiagnosticKind::BrokenCycleEdge { .. }));
		assert!(has_cycle, "expected cycle diagnostic, got {:?}", diags);
		assert!(
			has_break,
			"expected broken-edge diagnostic, got {:?}",
			diags
		);
		// The higher-position child (b) is the victim → the edge B→A is
		// dropped, leaving A→B intact.
		assert_eq!(dag.parents_of(&mid("a")), &[mid("b")]);
		assert_eq!(dag.parents_of(&mid("b")), &[] as &[ModId]);
	}

	#[test]
	fn dep_not_in_playset() {
		let mods = vec![mod_with("b", "B", vec!["Ghost"], vec![])];
		let (dag, diags) = build_mod_dag(&mods);
		assert!(matches!(
			diags[0].kind,
			DagDiagnosticKind::MissingDependency { .. }
		));
		assert_eq!(dag.parents_of(&mid("b")), &[] as &[ModId]);
		assert_eq!(dag.missing_deps().len(), 1);
	}

	#[test]
	fn dep_does_not_ship_file() {
		// B depends on A; only B ships the file.
		let mods = vec![
			mod_with("a", "A", vec![], vec![]),
			mod_with("b", "B", vec!["A"], vec![]),
		];
		let (dag, _diags) = build_mod_dag(&mods);
		// Only B is in the file inventory.
		let contribs = vec![file_contributor("b", 2)];
		let fdag = induced_file_dag(
			&dag,
			game_path("common/foo.txt"),
			&contribs,
			&IgnoreReplacePath::None,
		);
		// A is not a contributor → B's per-file parents are empty →
		// the shared DAG walker starts B from the root state.
		assert_eq!(fdag.parents_of(&mid("b")), &[] as &[ModId]);
		assert!(fdag.ancestors_of(&mid("b")).is_empty());
	}

	#[test]
	fn replace_path_drops_priors() {
		// C declares replace_path="common"; A and B (earlier precedence)
		// also ship common/foo.txt → they're dropped.
		let mods = vec![
			mod_with("a", "A", vec![], vec![]),
			mod_with("b", "B", vec![], vec![]),
			mod_with("c", "C", vec![], vec!["common"]),
		];
		let (dag, _diags) = build_mod_dag(&mods);
		let contribs = vec![
			file_contributor("a", 1),
			file_contributor("b", 2),
			file_contributor("c", 3),
		];
		let fdag = induced_file_dag(
			&dag,
			game_path("common/foo.txt"),
			&contribs,
			&IgnoreReplacePath::None,
		);
		// Only C remains as a contributor.
		assert_eq!(fdag.contributors(), &[mid("c")]);
		assert!(fdag.replaces_path(&mid("c")));
		assert!(fdag.parents_of(&mid("c")).is_empty());
	}

	#[test]
	fn replace_path_ignored_when_overridden() {
		let mods = vec![
			mod_with("a", "A", vec![], vec![]),
			mod_with("b", "B", vec![], vec![]),
			mod_with("c", "C", vec![], vec!["common"]),
		];
		let (dag, _diags) = build_mod_dag(&mods);
		let contribs = vec![
			file_contributor("a", 1),
			file_contributor("b", 2),
			file_contributor("c", 3),
		];
		// All replace_path overrides → priors stay.
		let fdag = induced_file_dag(
			&dag,
			game_path("common/foo.txt"),
			&contribs,
			&IgnoreReplacePath::All,
		);
		assert_eq!(fdag.contributors(), &[mid("a"), mid("b"), mid("c")]);
		assert!(!fdag.replaces_path(&mid("c")));
	}

	#[test]
	fn name_alternates() {
		// B declares two names; both resolve. (Here only one is present
		// in the playset; the other is a missing-dep diagnostic.)
		let mods = vec![
			mod_with("me_new", "Missions Expanded", vec![], vec![]),
			mod_with(
				"b",
				"B",
				vec!["Missions Expanded", "Missions Expanded (old)"],
				vec![],
			),
		];
		let (dag, diags) = build_mod_dag(&mods);
		assert_eq!(dag.parents_of(&mid("b")), &[mid("me_new")]);
		// The "(old)" alternate is missing → one diagnostic.
		assert_eq!(
			diags
				.iter()
				.filter(|d| matches!(d.kind, DagDiagnosticKind::MissingDependency { .. }))
				.count(),
			1
		);

		// Now both alternates present → both edges, deduped if same target.
		let mods = vec![
			mod_with("me_new", "Missions Expanded", vec![], vec![]),
			mod_with("me_old", "Missions Expanded (old)", vec![], vec![]),
			mod_with(
				"b",
				"B",
				vec!["Missions Expanded", "Missions Expanded (old)"],
				vec![],
			),
		];
		let (dag, _) = build_mod_dag(&mods);
		assert_eq!(dag.parents_of(&mid("b")), &[mid("me_new"), mid("me_old")]);
	}

	#[test]
	fn chain_regression_achievements() {
		// Reproduces the 371-conflict pattern: mod_a (Europa Expanded) ships
		// achievements.txt, mod_b independently ships an effectively-vanilla
		// achievements.txt, and there is no declared dep between them.
		// A linear chain forces mod_b to inherit mod_a and creates 371 phantom
		// removes. The file DAG keeps both contributors independent.
		let mods = vec![
			mod_with("ee", "Europa Expanded", vec![], vec![]),
			mod_with("bx", "Independent Mod B", vec![], vec![]),
		];
		let (dag, diags) = build_mod_dag(&mods);
		assert!(diags.is_empty());
		let contribs = vec![file_contributor("ee", 1), file_contributor("bx", 2)];
		let fdag = induced_file_dag(
			&dag,
			game_path("common/achievements.txt"),
			&contribs,
			&IgnoreReplacePath::None,
		);
		assert!(fdag.parents_of(&mid("ee")).is_empty());
		assert!(fdag.parents_of(&mid("bx")).is_empty());
		assert!(fdag.ancestors_of(&mid("bx")).is_empty());
	}

	#[test]
	fn ancestors_include_transitive_file_parents() {
		let mods = vec![
			mod_with("a", "A", vec![], vec![]),
			mod_with("b", "B", vec!["A"], vec![]),
			mod_with("c", "C", vec!["B"], vec![]),
		];
		let (dag, diags) = build_mod_dag(&mods);
		assert!(diags.is_empty());
		let contribs = vec![
			file_contributor("a", 1),
			file_contributor("b", 2),
			file_contributor("c", 3),
		];
		let fdag = induced_file_dag(
			&dag,
			game_path("common/foo.txt"),
			&contribs,
			&IgnoreReplacePath::None,
		);
		assert_eq!(fdag.ancestors_of(&mid("c")), vec![mid("a"), mid("b")]);
	}

	#[test]
	fn diamond_ancestors_include_shared_ancestor_once() {
		let mods = vec![
			mod_with("a", "A", vec![], vec![]),
			mod_with("b", "B", vec!["A"], vec![]),
			mod_with("c", "C", vec!["A"], vec![]),
			mod_with("d", "D", vec!["B", "C"], vec![]),
		];
		let (dag, diags) = build_mod_dag(&mods);
		assert!(diags.is_empty());
		let contribs = vec![
			file_contributor("a", 1),
			file_contributor("b", 2),
			file_contributor("c", 3),
			file_contributor("d", 4),
		];
		let fdag = induced_file_dag(
			&dag,
			game_path("common/foo.txt"),
			&contribs,
			&IgnoreReplacePath::None,
		);
		assert_eq!(
			fdag.ancestors_of(&mid("d")),
			vec![mid("a"), mid("b"), mid("c")]
		);
	}

	#[test]
	fn file_edges_lift_through_dependency_that_does_not_ship_the_file() {
		let mods = vec![
			mod_with("a", "A", vec![], vec![]),
			mod_with("b", "B", vec!["A"], vec![]),
			mod_with("c", "C", vec!["B"], vec![]),
		];
		let (dag, diags) = build_mod_dag(&mods);
		assert!(diags.is_empty());
		let contribs = vec![file_contributor("a", 1), file_contributor("c", 3)];
		let fdag = induced_file_dag(
			&dag,
			game_path("common/foo.txt"),
			&contribs,
			&IgnoreReplacePath::None,
		);
		assert_eq!(fdag.parents_of(&mid("c")), &[mid("a")]);
		assert_eq!(fdag.ancestors_of(&mid("c")), vec![mid("a")]);
	}

	#[test]
	fn replace_path_parent_becomes_the_file_dag_root() {
		let mods = vec![
			mod_with("a", "A", vec![], vec![]),
			mod_with("b", "B", vec!["A"], vec!["common"]),
			mod_with("c", "C", vec!["B"], vec![]),
		];
		let (dag, diags) = build_mod_dag(&mods);
		assert!(diags.is_empty());
		let contribs = vec![
			file_contributor("a", 1),
			file_contributor("b", 2),
			file_contributor("c", 3),
		];
		let fdag = induced_file_dag(
			&dag,
			game_path("common/foo.txt"),
			&contribs,
			&IgnoreReplacePath::None,
		);
		assert_eq!(fdag.contributors(), &[mid("b"), mid("c")]);
		assert!(fdag.replaces_path(&mid("b")));
		assert!(fdag.parents_of(&mid("b")).is_empty());
		assert_eq!(fdag.parents_of(&mid("c")), &[mid("b")]);
	}

	#[test]
	fn ignore_replace_path_restores_pruned_file_ancestry() {
		let mods = vec![
			mod_with("a", "A", vec![], vec![]),
			mod_with("b", "B", vec!["A"], vec!["common"]),
			mod_with("c", "C", vec!["B"], vec![]),
		];
		let (dag, diags) = build_mod_dag(&mods);
		assert!(diags.is_empty());
		let contribs = vec![
			file_contributor("a", 1),
			file_contributor("b", 2),
			file_contributor("c", 3),
		];
		let fdag = induced_file_dag(
			&dag,
			game_path("common/foo.txt"),
			&contribs,
			&IgnoreReplacePath::All,
		);
		assert_eq!(fdag.contributors(), &[mid("a"), mid("b"), mid("c")]);
		assert!(!fdag.replaces_path(&mid("b")));
		assert_eq!(fdag.ancestors_of(&mid("c")), vec![mid("a"), mid("b")]);
	}

	#[test]
	fn topo_levels_order_a_pure_chain_sequentially() {
		let mods = vec![
			mod_with("a", "A", vec![], vec![]),
			mod_with("b", "B", vec!["A"], vec![]),
			mod_with("c", "C", vec!["B"], vec![]),
		];
		let (dag, diags) = build_mod_dag(&mods);
		assert!(diags.is_empty());
		let contribs = vec![
			file_contributor("a", 1),
			file_contributor("b", 2),
			file_contributor("c", 3),
		];
		let fdag = induced_file_dag(
			&dag,
			game_path("common/foo.txt"),
			&contribs,
			&IgnoreReplacePath::None,
		);
		let parents = BTreeSet::from([mid("a"), mid("b"), mid("c")]);
		assert_eq!(
			topo_levels(&parents, &fdag),
			vec![vec![mid("a")], vec![mid("b")], vec![mid("c")]]
		);
	}

	#[test]
	fn topo_levels_group_a_pure_antichain() {
		let mods = vec![
			mod_with("a", "A", vec![], vec![]),
			mod_with("b", "B", vec![], vec![]),
			mod_with("c", "C", vec![], vec![]),
		];
		let (dag, diags) = build_mod_dag(&mods);
		assert!(diags.is_empty());
		let contribs = vec![
			file_contributor("a", 1),
			file_contributor("b", 2),
			file_contributor("c", 3),
		];
		let fdag = induced_file_dag(
			&dag,
			game_path("common/foo.txt"),
			&contribs,
			&IgnoreReplacePath::None,
		);
		let parents = BTreeSet::from([mid("c"), mid("a"), mid("b")]);
		assert_eq!(
			topo_levels(&parents, &fdag),
			vec![vec![mid("a"), mid("b"), mid("c")]]
		);
	}

	#[test]
	fn topo_levels_diamond_groups_shared_ancestor_then_siblings() {
		let mods = vec![
			mod_with("a", "A", vec![], vec![]),
			mod_with("b", "B", vec!["A"], vec![]),
			mod_with("c", "C", vec!["A"], vec![]),
			mod_with("d", "D", vec!["B", "C"], vec![]),
		];
		let (dag, diags) = build_mod_dag(&mods);
		assert!(diags.is_empty());
		let contribs = vec![
			file_contributor("a", 1),
			file_contributor("b", 2),
			file_contributor("c", 3),
			file_contributor("d", 4),
		];
		let fdag = induced_file_dag(
			&dag,
			game_path("common/foo.txt"),
			&contribs,
			&IgnoreReplacePath::None,
		);
		let parents = BTreeSet::from([mid("a"), mid("b"), mid("c")]);
		assert_eq!(
			topo_levels(&parents, &fdag),
			vec![vec![mid("a")], vec![mid("b"), mid("c")]]
		);
	}

	#[test]
	fn deterministic_ordering_across_runs() {
		// Build a non-trivial DAG twice in identical order; the topo and
		// children lists must match exactly (no HashMap iteration leaking
		// into output).
		let make_mods = || {
			vec![
				mod_with("a", "A", vec![], vec![]),
				mod_with("b", "B", vec!["A"], vec![]),
				mod_with("c", "C", vec!["A"], vec![]),
				mod_with("d", "D", vec!["B", "C"], vec![]),
			]
		};
		let (dag1, _) = build_mod_dag(&make_mods());
		let (dag2, _) = build_mod_dag(&make_mods());
		assert_eq!(dag1.topo(), dag2.topo());
		for m in [mid("a"), mid("b"), mid("c"), mid("d")] {
			assert_eq!(dag1.parents_of(&m), dag2.parents_of(&m));
			assert_eq!(dag1.children_of(&m), dag2.children_of(&m));
		}
		// children_of(A) must be deterministic [B, C] (playlist order).
		assert_eq!(dag1.children_of(&mid("a")), &[mid("b"), mid("c")]);

		// Same FileDag determinism.
		let mods = make_mods();
		let (dag, _) = build_mod_dag(&mods);
		let contribs = vec![
			file_contributor("a", 1),
			file_contributor("b", 2),
			file_contributor("c", 3),
			file_contributor("d", 4),
		];
		let f1 = induced_file_dag(
			&dag,
			game_path("common/foo.txt"),
			&contribs,
			&IgnoreReplacePath::None,
		);
		let f2 = induced_file_dag(
			&dag,
			game_path("common/foo.txt"),
			&contribs,
			&IgnoreReplacePath::None,
		);
		assert_eq!(f1.contributors(), f2.contributors());
		for m in [mid("a"), mid("b"), mid("c"), mid("d")] {
			assert_eq!(f1.parents_of(&m), f2.parents_of(&m));
		}
	}

	/// A mod's `replace_path` drops earlier contributors of every file in the
	/// directory it names and below, compared by whole components, and of
	/// nothing else.
	#[test]
	fn replace_path_owns_the_files_in_and_below_its_directory_only() {
		let mods = vec![
			mod_with("a", "A", vec![], vec![]),
			mod_with("b", "B", vec![], vec!["common/ideas"]),
		];
		let (dag, _) = build_mod_dag(&mods);
		let contribs = vec![file_contributor("a", 1), file_contributor("b", 2)];
		for (file, owned) in [
			("common/ideas/x.txt", true),
			("common/ideas/nested/x.txt", true),
			("common/ideas", true),
			("common/ideas_extra/x.txt", false),
			("common/idea/x.txt", false),
		] {
			let fdag = induced_file_dag(&dag, game_path(file), &contribs, &IgnoreReplacePath::None);
			assert_eq!(fdag.replaces_path(&mid("b")), owned, "{file}");
			assert_eq!(fdag.ships(&mid("a")), !owned, "{file}");
		}
	}
}