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
//! Turning a playset selection into one launch's frozen load order.
//!
//! [`plan`] is pure: given the game identity, the manifests available in the
//! store, and the user's selection, it resolves versions, checks
//! compatibility, orders plugins by their declared dependencies and ordering
//! constraints, and reports every problem it finds. It performs no I/O and
//! never loads a DLL. The loader executes exactly what it returns; it does not
//! re-order anything itself.
//!
//! Shared DLL basenames require known digests, including each entry DLL;
//! missing digests are conservatively refused. Artifact-backed previews use
//! [`super::deployment::resolve`] to supply verified digests and the same
//! resolution launch uses.

use super::manifest::{Kind, Manifest, Phase};
use semver::Version;
use std::collections::{BTreeMap, BTreeSet};

/// The ABI major versions this Foch build's host can load.
pub const SUPPORTED_ABI_MAJOR: &[u32] = &[1];

/// The platform tuple of the only target this build supports.
pub const WINDOWS_X64: &str = "windows-x86_64";

/// The game a plan targets.
#[derive(Clone, Debug)]
pub struct GameIdentity {
	pub game: String,
	pub version: Version,
	pub platform: String,
}

/// Normalize an EU4 launcher version string (for example `v1.37.5.0`) to a
/// semver `Version`: drop a leading `v` and keep the first three numeric
/// components, filling missing ones with zero.
pub fn parse_game_version(raw: &str) -> Option<Version> {
	let trimmed = raw.trim().trim_start_matches(['v', 'V']);
	let mut parts = trimmed.split('.').map(|part| part.trim());
	let mut numbers = [0u64; 3];
	for slot in &mut numbers {
		match parts.next() {
			Some(part) => *slot = part.parse().ok()?,
			None => break,
		}
	}
	Some(Version::new(numbers[0], numbers[1], numbers[2]))
}

/// One plugin the user selected for a playset.
#[derive(Clone, Debug)]
pub struct Selection {
	pub id: String,
	/// The exact version the playset pinned.
	pub version: Version,
	pub enabled: bool,
	/// Configuration values, already validated against the manifest schema.
	pub config: serde_json::Value,
}

/// A resolved plugin in load order.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Resolved {
	pub id: String,
	pub version: Version,
	pub kind: Kind,
	pub phase: Phase,
}

/// A problem that keeps a plan from being launchable, or a warning.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Diagnostic {
	/// An enabled plugin id appears more than once in the input selection.
	DuplicateSelection { id: String },
	/// The selected version is not in the store.
	Missing { id: String, version: Version },
	/// Platform or game version is out of the declared range.
	Incompatible { id: String, reason: String },
	/// A native plugin's ABI major is not supported by this host.
	UnsupportedAbi { id: String, abi_major: u32 },
	/// A required dependency is absent, disabled, or version-mismatched.
	Dependency {
		id: String,
		requires: String,
		reason: String,
	},
	/// Two enabled plugins declare a mutual conflict.
	Conflict {
		id: String,
		with: String,
		reason: Option<String>,
	},
	/// Ordering constraints form a cycle.
	Cycle { ids: Vec<String> },
	/// Two plugins ship a file at the same install-relative path with
	/// different contents; the process would load only one.
	FileCollision { path: String, ids: Vec<String> },
}

/// The outcome of planning: the order to load, plus every diagnostic. The plan
/// is launchable only when `errors` is empty.
#[derive(Clone, Debug, Default)]
pub struct Resolution {
	pub order: Vec<Resolved>,
	pub errors: Vec<Diagnostic>,
	pub warnings: Vec<Diagnostic>,
}

impl Resolution {
	pub fn is_launchable(&self) -> bool {
		self.errors.is_empty()
	}
}

/// Resolve and order the enabled selection against the store.
pub fn plan(
	game: &GameIdentity,
	store: &BTreeMap<String, BTreeMap<Version, Manifest>>,
	selection: &[Selection],
) -> Resolution {
	let mut resolution = Resolution::default();
	let mut seen = BTreeSet::new();
	let mut duplicates = BTreeSet::new();
	for item in selection.iter().filter(|item| item.enabled) {
		if !seen.insert(item.id.clone()) {
			duplicates.insert(item.id.clone());
		}
	}
	for id in &duplicates {
		resolution
			.errors
			.push(Diagnostic::DuplicateSelection { id: id.clone() });
	}

	// Resolve each enabled selection to its manifest, collecting hard errors.
	let mut resolved: BTreeMap<String, &Manifest> = BTreeMap::new();
	for item in selection
		.iter()
		.filter(|item| item.enabled && !duplicates.contains(&item.id))
	{
		let Some(versions) = store.get(&item.id) else {
			resolution.errors.push(Diagnostic::Missing {
				id: item.id.clone(),
				version: item.version.clone(),
			});
			continue;
		};
		let Some(manifest) = versions.get(&item.version) else {
			resolution.errors.push(Diagnostic::Missing {
				id: item.id.clone(),
				version: item.version.clone(),
			});
			continue;
		};
		if let Some(reason) = incompatibility(game, manifest) {
			resolution.errors.push(Diagnostic::Incompatible {
				id: item.id.clone(),
				reason,
			});
			continue;
		}
		if manifest.entry.kind == Kind::Native
			&& let Some(abi) = manifest.target.abi_major
			&& !SUPPORTED_ABI_MAJOR.contains(&abi)
		{
			resolution.errors.push(Diagnostic::UnsupportedAbi {
				id: item.id.clone(),
				abi_major: abi,
			});
			continue;
		}
		resolved.insert(item.id.clone(), manifest);
	}

	check_dependencies(&resolved, &mut resolution);
	check_conflicts(&resolved, &mut resolution);
	check_file_collisions(&resolved, &mut resolution);

	// Drop plugins whose dependencies failed before ordering, so a dependent
	// of a missing dependency is never placed in the order.
	let mut usable: BTreeMap<String, &Manifest> = resolved
		.iter()
		.filter(|(id, _)| !has_blocking_error(&resolution, id))
		.map(|(id, manifest)| (id.clone(), *manifest))
		.collect();
	// Removing one unusable plugin can invalidate its dependents in turn.
	// Reach the dependency closure before ordering; independent plugins stay.
	loop {
		let before = usable.len();
		check_dependencies(&usable, &mut resolution);
		usable.retain(|id, _| !has_blocking_error(&resolution, id));
		if usable.len() == before {
			break;
		}
	}

	match order(&usable) {
		Ok(order) => {
			for pair in order.windows(2) {
				if pair[0].phase > pair[1].phase {
					resolution.errors.push(Diagnostic::Incompatible {
						id: pair[1].id.clone(),
						reason: "ordering requires a later startup phase before an earlier one"
							.into(),
					});
				}
			}
			resolution.order = order;
		}
		Err(cycle) => resolution.errors.push(Diagnostic::Cycle { ids: cycle }),
	}
	resolution
}

fn incompatibility(game: &GameIdentity, manifest: &Manifest) -> Option<String> {
	if manifest.target.game != game.game {
		return Some(format!(
			"declares game {}, not {}",
			manifest.target.game, game.game
		));
	}
	if manifest.target.platform != game.platform {
		return Some(format!(
			"declares platform {}, not {}",
			manifest.target.platform, game.platform
		));
	}
	if !manifest.target.game_versions.matches(&game.version) {
		return Some(format!(
			"declares game versions {}, which excludes {}",
			manifest.target.game_versions, game.version
		));
	}
	None
}

fn check_dependencies(resolved: &BTreeMap<String, &Manifest>, resolution: &mut Resolution) {
	for (id, manifest) in resolved {
		for dependency in &manifest.depends {
			let requires = format!("{} {}", dependency.id, dependency.version);
			match resolved.get(&dependency.id) {
				None => resolution.errors.push(Diagnostic::Dependency {
					id: id.clone(),
					requires,
					reason: "not enabled or not resolvable".into(),
				}),
				Some(dependency_manifest) => {
					if !dependency
						.version
						.matches(&dependency_manifest.plugin.version)
					{
						resolution.errors.push(Diagnostic::Dependency {
							id: id.clone(),
							requires,
							reason: format!(
								"resolved {} does not satisfy the requirement",
								dependency_manifest.plugin.version
							),
						});
					}
				}
			}
		}
	}
}

fn check_conflicts(resolved: &BTreeMap<String, &Manifest>, resolution: &mut Resolution) {
	let mut reported = BTreeSet::new();
	for (id, manifest) in resolved {
		for conflict in &manifest.conflicts {
			if let Some(other) = resolved.get(&conflict.id)
				&& conflict.version.matches(&other.plugin.version)
			{
				let pair = if id < &conflict.id {
					(id, &conflict.id)
				} else {
					(&conflict.id, id)
				};
				if reported.insert(pair) {
					resolution.errors.push(Diagnostic::Conflict {
						id: id.clone(),
						with: conflict.id.clone(),
						reason: conflict.reason.clone(),
					});
				}
			}
		}
	}
}

fn check_file_collisions(resolved: &BTreeMap<String, &Manifest>, resolution: &mut Resolution) {
	// Windows reuses already loaded modules by basename. Entry DLLs must be
	// distinct even with identical bytes: their init/configuration is per id.
	let mut entry_names: BTreeMap<String, Vec<String>> = BTreeMap::new();
	for (id, manifest) in resolved {
		entry_names
			.entry(
				manifest
					.entry
					.path
					.rsplit(['/', '\\'])
					.next()
					.unwrap_or_default()
					.to_lowercase(),
			)
			.or_default()
			.push(id.clone());
	}
	for (path, ids) in entry_names {
		if ids.len() > 1 {
			resolution
				.errors
				.push(Diagnostic::FileCollision { path, ids });
		}
	}
	// Loaded DLL basename -> normalized digest -> declaring plugin ids.
	// An undeclared entry digest is unknown: it cannot prove compatibility
	// with another DLL sharing its basename. Deployment supplies real digests.
	let mut by_path: BTreeMap<String, BTreeMap<Option<String>, BTreeSet<&str>>> = BTreeMap::new();
	for (id, manifest) in resolved {
		let entry_path = manifest.entry.path.replace('\\', "/");
		let entry_digest = manifest
			.files
			.iter()
			.find(|file| {
				file.path
					.replace('\\', "/")
					.eq_ignore_ascii_case(&entry_path)
			})
			.map(|file| file.sha256.to_ascii_lowercase());
		by_path
			.entry(entry_path.rsplit('/').next().unwrap().to_ascii_lowercase())
			.or_default()
			.entry(entry_digest)
			.or_default()
			.insert(id.as_str());
		for file in &manifest.files {
			if !file.path.to_ascii_lowercase().ends_with(".dll") {
				continue;
			}
			let name = file
				.path
				.rsplit(['/', '\\'])
				.next()
				.unwrap()
				.to_ascii_lowercase();
			by_path
				.entry(name)
				.or_default()
				.entry(Some(file.sha256.to_ascii_lowercase()))
				.or_default()
				.insert(id.as_str());
		}
	}
	for (path, digests) in by_path {
		if digests.len() > 1 {
			let mut ids: BTreeSet<&str> = BTreeSet::new();
			for owners in digests.values() {
				ids.extend(owners.iter().copied());
			}
			resolution.errors.push(Diagnostic::FileCollision {
				path: path.to_string(),
				ids: ids.into_iter().map(str::to_string).collect(),
			});
		}
	}
}

fn has_blocking_error(resolution: &Resolution, id: &str) -> bool {
	resolution.errors.iter().any(|diagnostic| match diagnostic {
		Diagnostic::DuplicateSelection { id: who } | Diagnostic::Dependency { id: who, .. } => {
			who == id
		}
		Diagnostic::Conflict { id: a, with: b, .. } => a == id || b == id,
		Diagnostic::FileCollision { ids, .. } => ids.iter().any(|who| who == id),
		_ => false,
	})
}

/// Topologically order the usable plugins. Edges: a hard dependency and a
/// `load_after` both make this plugin come later; `load_before` is the mirror.
/// Unicode is pinned first among ties by sorting the ready set by id, which
/// also makes the output deterministic. Returns the ids in a cycle on failure.
fn order(usable: &BTreeMap<String, &Manifest>) -> Result<Vec<Resolved>, Vec<String>> {
	// Build "must come after" edges only among plugins that are present.
	let mut after: BTreeMap<&str, BTreeSet<&str>> = usable
		.keys()
		.map(|id| (id.as_str(), BTreeSet::new()))
		.collect();
	for (id, manifest) in usable {
		let here = id.as_str();
		for dependency in &manifest.depends {
			if usable.contains_key(&dependency.id) {
				after.get_mut(here).unwrap().insert(dependency.id.as_str());
			}
		}
		for other in &manifest.load_after {
			if usable.contains_key(other) {
				after.get_mut(here).unwrap().insert(other.as_str());
			}
		}
		for other in &manifest.load_before {
			if let Some(edges) = after.get_mut(other.as_str()) {
				edges.insert(here);
			}
		}
	}

	// Kahn's algorithm, picking the smallest ready id for a stable order.
	let mut remaining: BTreeMap<&str, usize> =
		after.iter().map(|(id, deps)| (*id, deps.len())).collect();
	let mut order = Vec::new();
	while !remaining.is_empty() {
		let Some(next) = remaining
			.iter()
			.filter(|&(_, &count)| count == 0)
			.map(|(id, _)| *id)
			.min_by_key(|id| (usable[*id].entry.phase, *id))
		else {
			let mut cycle: Vec<String> = remaining.keys().map(|id| id.to_string()).collect();
			cycle.sort();
			return Err(cycle);
		};
		remaining.remove(next);
		for (other, deps) in &after {
			if deps.contains(next) && remaining.contains_key(other) {
				*remaining.get_mut(other).unwrap() -= 1;
			}
		}
		let manifest = usable[next];
		order.push(Resolved {
			id: next.to_string(),
			version: manifest.plugin.version.clone(),
			kind: manifest.entry.kind.clone(),
			phase: manifest.entry.phase,
		});
	}
	Ok(order)
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::plugin::manifest::Manifest;

	fn manifest(id: &str, version: &str, body: &str) -> Manifest {
		// `body` is placed at the root, before any table header, so bare keys
		// (load_after/load_before) and `[[depends]]`/`[[conflicts]]`/`[[files]]`
		// arrays all attach to the root table rather than `[entry]`.
		let text = format!(
			r#"
schema = 1
{body}
[plugin]
id = "{id}"
name = "{id}"
version = "{version}"
[target]
platform = "windows-x86_64"
game = "eu4"
game_versions = "=1.37.5"
abi_major = 1
[entry]
kind = "native"
path = "{id}.dll"
phase = "deferred"
"#
		);
		Manifest::parse(&text).unwrap()
	}

	fn store(manifests: Vec<Manifest>) -> BTreeMap<String, BTreeMap<Version, Manifest>> {
		let mut store: BTreeMap<String, BTreeMap<Version, Manifest>> = BTreeMap::new();
		for manifest in manifests {
			store
				.entry(manifest.plugin.id.clone())
				.or_default()
				.insert(manifest.plugin.version.clone(), manifest);
		}
		store
	}

	fn game() -> GameIdentity {
		GameIdentity {
			game: "eu4".into(),
			version: Version::parse("1.37.5").unwrap(),
			platform: "windows-x86_64".into(),
		}
	}

	fn select(id: &str, version: &str) -> Selection {
		Selection {
			id: id.into(),
			version: Version::parse(version).unwrap(),
			enabled: true,
			config: serde_json::Value::Null,
		}
	}

	#[test]
	fn duplicate_enabled_ids_are_rejected_independently_of_input_order() {
		let store = store(vec![
			manifest("duplicate", "1.0.0", ""),
			manifest("duplicate", "2.0.0", ""),
			manifest("leaf", "1.0.0", "[[depends]]\nid='duplicate'\nversion='*'"),
			manifest("independent", "1.0.0", ""),
		]);
		for second_version in ["1.0.0", "2.0.0"] {
			let mut choices = vec![
				select("duplicate", "1.0.0"),
				select("duplicate", second_version),
				select("duplicate", "1.0.0"),
				select("leaf", "1.0.0"),
				select("independent", "1.0.0"),
			];
			let forward = plan(&game(), &store, &choices);
			assert!(!forward.is_launchable(), "accepted repeated enabled IDs");
			assert_eq!(
				forward
					.errors
					.iter()
					.filter(
						|error| matches!(error, Diagnostic::DuplicateSelection { id } if id == "duplicate")
					)
					.count(),
				1
			);
			assert_eq!(
				forward
					.order
					.iter()
					.map(|item| item.id.as_str())
					.collect::<Vec<_>>(),
				["independent"]
			);
			choices.reverse();
			let reversed = plan(&game(), &store, &choices);
			assert_eq!(forward.order, reversed.order);
			assert_eq!(forward.errors, reversed.errors);
		}
		let mut disabled = select("duplicate", "2.0.0");
		disabled.enabled = false;
		let resolution = plan(&game(), &store, &[select("duplicate", "1.0.0"), disabled]);
		assert!(resolution.is_launchable());
		assert_eq!(resolution.order.len(), 1);
		assert_eq!(resolution.order[0].version, Version::new(1, 0, 0));
	}

	#[test]
	fn orders_dependencies_before_dependents() {
		let store = store(vec![
			manifest("base", "1.0.0", ""),
			manifest(
				"leaf",
				"1.0.0",
				"[[depends]]\nid = \"base\"\nversion = \"^1\"",
			),
		]);
		let resolution = plan(
			&game(),
			&store,
			&[select("leaf", "1.0.0"), select("base", "1.0.0")],
		);
		assert!(resolution.is_launchable());
		let ids: Vec<&str> = resolution.order.iter().map(|r| r.id.as_str()).collect();
		assert_eq!(ids, ["base", "leaf"]);
	}

	#[test]
	fn missing_dependency_drops_the_dependent() {
		let store = store(vec![manifest(
			"leaf",
			"1.0.0",
			"[[depends]]\nid = \"base\"\nversion = \"*\"",
		)]);
		let resolution = plan(&game(), &store, &[select("leaf", "1.0.0")]);
		assert!(!resolution.is_launchable());
		assert!(resolution.order.is_empty());
		assert!(matches!(
			resolution.errors[0],
			Diagnostic::Dependency { .. }
		));
	}

	#[test]
	fn unusable_dependencies_drop_every_transitive_dependent() {
		for problem in ["missing", "version", "abi", "conflict"] {
			let base_requirement = if problem == "version" { "^2" } else { "*" };
			let mut manifests = vec![
				manifest("a", "1.0.0", "[[depends]]\nid='b'\nversion='*'"),
				manifest(
					"b",
					"1.0.0",
					&format!("[[depends]]\nid='c'\nversion='{base_requirement}'"),
				),
				manifest("independent", "1.0.0", ""),
			];
			if problem != "missing" {
				let mut base = manifest(
					"c",
					"1.0.0",
					if problem == "conflict" {
						"[[conflicts]]\nid='other'\nversion='*'"
					} else {
						""
					},
				);
				if problem == "abi" {
					base.target.abi_major = Some(2);
				}
				manifests.push(base);
			}
			if problem == "conflict" {
				manifests.push(manifest("other", "1.0.0", ""));
			}
			let selected: Vec<_> = manifests
				.iter()
				.map(|manifest| select(&manifest.plugin.id, "1.0.0"))
				.collect();
			let resolution = plan(&game(), &store(manifests), &selected);
			assert!(!resolution.is_launchable(), "{problem}");
			assert!(
				!resolution
					.order
					.iter()
					.any(|plugin| plugin.id == "a" || plugin.id == "b"),
				"{problem}: {resolution:?}"
			);
			assert!(
				resolution
					.order
					.iter()
					.any(|plugin| plugin.id == "independent"),
				"{problem}"
			);
			assert!(
				resolution
					.errors
					.iter()
					.any(|error| matches!(error, Diagnostic::Dependency {id, ..} if id == "a")),
				"{problem}: {resolution:?}"
			);
		}
	}

	#[test]
	fn dependency_version_must_match() {
		let store = store(vec![
			manifest("base", "1.0.0", ""),
			manifest(
				"leaf",
				"1.0.0",
				"[[depends]]\nid = \"base\"\nversion = \"^2\"",
			),
		]);
		let resolution = plan(
			&game(),
			&store,
			&[select("base", "1.0.0"), select("leaf", "1.0.0")],
		);
		assert!(!resolution.is_launchable());
	}

	#[test]
	fn declared_conflicts_are_reported_once() {
		let store = store(vec![
			manifest(
				"a",
				"1.0.0",
				"[[conflicts]]\nid = \"b\"\nversion = \"*\"\nreason = \"same hook\"",
			),
			manifest("b", "1.0.0", "[[conflicts]]\nid = \"a\"\nversion = \"*\""),
		]);
		let resolution = plan(
			&game(),
			&store,
			&[select("a", "1.0.0"), select("b", "1.0.0")],
		);
		let conflicts = resolution
			.errors
			.iter()
			.filter(|d| matches!(d, Diagnostic::Conflict { .. }))
			.count();
		assert_eq!(conflicts, 1);
	}

	#[test]
	fn cycles_are_detected() {
		let store = store(vec![
			manifest("a", "1.0.0", "load_after = [\"b\"]"),
			manifest("b", "1.0.0", "load_after = [\"a\"]"),
		]);
		let resolution = plan(
			&game(),
			&store,
			&[select("a", "1.0.0"), select("b", "1.0.0")],
		);
		assert!(matches!(resolution.errors[0], Diagnostic::Cycle { .. }));
	}

	#[test]
	fn incompatible_game_version_is_rejected() {
		let store = store(vec![manifest("a", "1.0.0", "")]);
		let mut game = game();
		game.version = Version::parse("1.38.0").unwrap();
		let resolution = plan(&game, &store, &[select("a", "1.0.0")]);
		assert!(matches!(
			resolution.errors[0],
			Diagnostic::Incompatible { .. }
		));
	}

	#[test]
	fn disabled_selections_are_ignored() {
		let store = store(vec![manifest("a", "1.0.0", "")]);
		let mut item = select("a", "1.0.0");
		item.enabled = false;
		let resolution = plan(&game(), &store, &[item]);
		assert!(resolution.is_launchable());
		assert!(resolution.order.is_empty());
	}

	#[test]
	fn parses_eu4_launcher_versions() {
		assert_eq!(
			parse_game_version("v1.37.5.0"),
			Some(Version::new(1, 37, 5))
		);
		assert_eq!(parse_game_version("1.37"), Some(Version::new(1, 37, 0)));
		assert_eq!(parse_game_version("garbage"), None);
	}

	#[test]
	fn same_file_different_digest_collides() {
		let a = manifest(
			"a",
			"1.0.0",
			"[[files]]\npath = \"plugins/shared.dll\"\nsha256 = \"aa\"",
		);
		let b = manifest(
			"b",
			"1.0.0",
			"[[files]]\npath = \"plugins/shared.dll\"\nsha256 = \"bb\"",
		);
		let store = store(vec![a, b]);
		let resolution = plan(
			&game(),
			&store,
			&[select("a", "1.0.0"), select("b", "1.0.0")],
		);
		assert!(
			resolution
				.errors
				.iter()
				.any(|d| matches!(d, Diagnostic::FileCollision { .. }))
		);
	}

	#[test]
	fn startup_phases_take_precedence_and_impossible_constraints_are_refused() {
		let deferred = manifest("a-deferred", "1.0.0", "");
		let mut entry = manifest("z-entry", "1.0.0", "");
		entry.entry.phase = Phase::Entry;
		let selections = [select("a-deferred", "1.0.0"), select("z-entry", "1.0.0")];
		let ordered = plan(
			&game(),
			&store(vec![deferred.clone(), entry.clone()]),
			&selections,
		);
		assert!(ordered.is_launchable());
		assert_eq!(ordered.order[0].id, "z-entry");
		entry.load_after.push("a-deferred".into());
		assert!(!plan(&game(), &store(vec![deferred, entry]), &selections).is_launchable());
	}

	#[test]
	fn dll_basename_collisions_apply_across_different_package_directories() {
		let a = manifest(
			"a",
			"1.0.0",
			"[[files]]\npath=\"one/util.dll\"\nsha256=\"aa\"",
		);
		let b = manifest(
			"b",
			"1.0.0",
			"[[files]]\npath=\"two/UTIL.DLL\"\nsha256=\"bb\"",
		);
		assert!(
			!plan(
				&game(),
				&store(vec![a, b]),
				&[select("a", "1.0.0"), select("b", "1.0.0")]
			)
			.is_launchable()
		);
	}

	#[test]
	fn identical_entry_names_are_refused_but_identical_dependencies_are_allowed() {
		let a = manifest(
			"a",
			"1.0.0",
			"[[files]]\npath=\"shared.dll\"\nsha256=\"aa\"",
		);
		let mut b = manifest(
			"b",
			"1.0.0",
			"[[files]]\npath=\"shared.dll\"\nsha256=\"aa\"",
		);
		let selections = [select("a", "1.0.0"), select("b", "1.0.0")];
		assert!(plan(&game(), &store(vec![a.clone(), b.clone()]), &selections).is_launchable());
		b.entry.path = format!("other/{}", a.entry.path.to_uppercase());
		assert!(!plan(&game(), &store(vec![a, b]), &selections).is_launchable());
	}

	#[test]
	fn digest_letter_case_does_not_create_a_dependency_collision() {
		let a = manifest(
			"a",
			"1.0.0",
			"[[files]]\npath=\"one/shared.dll\"\nsha256=\"aa\"",
		);
		let b = manifest(
			"b",
			"1.0.0",
			"[[files]]\npath=\"two/SHARED.DLL\"\nsha256=\"AA\"",
		);
		assert!(
			plan(
				&game(),
				&store(vec![a, b]),
				&[select("a", "1.0.0"), select("b", "1.0.0")]
			)
			.is_launchable()
		);
	}

	#[test]
	fn an_unlisted_entry_cannot_alias_another_plugins_dependency() {
		let a = manifest("a", "1.0.0", "");
		let b = manifest(
			"b",
			"1.0.0",
			"[[files]]\npath=\"dependency/A.DLL\"\nsha256=\"bb\"",
		);
		let resolution = plan(
			&game(),
			&store(vec![a, b]),
			&[select("a", "1.0.0"), select("b", "1.0.0")],
		);
		assert!(!resolution.is_launchable());
		assert!(resolution.errors.iter().any(|error| matches!(error, Diagnostic::FileCollision { path, ids } if path == "a.dll" && ids == &["a", "b"])));
	}

	#[test]
	fn one_way_conflicts_are_enforced_in_both_lexical_directions() {
		let a = manifest("a", "1.0.0", "");
		let z = manifest("z", "1.0.0", "[[conflicts]]\nid=\"a\"\nversion=\"*\"");
		let resolution = plan(
			&game(),
			&store(vec![a, z]),
			&[select("a", "1.0.0"), select("z", "1.0.0")],
		);
		assert!(!resolution.is_launchable());
		assert_eq!(
			resolution
				.errors
				.iter()
				.filter(|d| matches!(d, Diagnostic::Conflict { .. }))
				.count(),
			1
		);
	}
}