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
use std::fmt;

use serde::{Deserialize, Serialize};
use thiserror::Error;

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct RevisionId(u16);

impl RevisionId {
	pub const BASE: Self = Self(0);
	pub const LEFT: Self = Self(1);
	#[cfg(test)]
	pub const RIGHT: Self = Self(2);

	pub const fn new(value: u16) -> Self {
		Self(value)
	}

	pub const fn get(self) -> u16 {
		self.0
	}
}

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct NodeId(u32);

impl NodeId {
	pub const fn new(value: u32) -> Self {
		Self(value)
	}

	pub const fn get(self) -> u32 {
		self.0
	}
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ChildOrder {
	#[default]
	Ordered,
	Commutative,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ChildCardinality {
	#[default]
	Many,
	ExactlyOne,
}

#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SemanticKeyScope {
	Global,
	Parent,
}

#[derive(
	Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize,
)]
#[serde(rename_all = "snake_case")]
pub enum SemanticKeyMatchMode {
	#[default]
	Identity,
	OrderedSimilarity,
	OrderedSimilarityWithPosition,
}

/// Whether a semantic key may establish correspondence directly between two
/// sibling revisions or must be connected by an existing matcher seed.
#[derive(
	Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize,
)]
#[serde(rename_all = "snake_case")]
pub enum SemanticKeyLineage {
	#[default]
	Unrestricted,
	/// In a seeded comparison, retain matches inside this keyed subtree only
	/// when the keyed roots themselves are connected by the seed.
	Seeded,
}

#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct SemanticKey {
	pub scope: SemanticKeyScope,
	pub namespace: String,
	pub value: String,
	pub match_mode: SemanticKeyMatchMode,
	#[serde(default)]
	pub lineage: SemanticKeyLineage,
}

impl SemanticKey {
	pub fn new(namespace: impl Into<String>, value: impl Into<String>) -> Self {
		Self {
			scope: SemanticKeyScope::Global,
			namespace: namespace.into(),
			value: value.into(),
			match_mode: SemanticKeyMatchMode::Identity,
			lineage: SemanticKeyLineage::Unrestricted,
		}
	}

	pub fn parent_scoped(namespace: impl Into<String>, value: impl Into<String>) -> Self {
		Self {
			scope: SemanticKeyScope::Parent,
			namespace: namespace.into(),
			value: value.into(),
			match_mode: SemanticKeyMatchMode::Identity,
			lineage: SemanticKeyLineage::Unrestricted,
		}
	}

	pub fn parent_scoped_ordered_similarity(
		namespace: impl Into<String>,
		value: impl Into<String>,
	) -> Self {
		Self {
			scope: SemanticKeyScope::Parent,
			namespace: namespace.into(),
			value: value.into(),
			match_mode: SemanticKeyMatchMode::OrderedSimilarity,
			lineage: SemanticKeyLineage::Unrestricted,
		}
	}

	pub fn parent_scoped_ordered_similarity_with_position(
		namespace: impl Into<String>,
		value: impl Into<String>,
	) -> Self {
		Self {
			scope: SemanticKeyScope::Parent,
			namespace: namespace.into(),
			value: value.into(),
			match_mode: SemanticKeyMatchMode::OrderedSimilarityWithPosition,
			lineage: SemanticKeyLineage::Unrestricted,
		}
	}

	pub fn requiring_seeded_lineage(mut self) -> Self {
		self.lineage = SemanticKeyLineage::Seeded;
		self
	}
}

#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct SubtreeHash([u8; 32]);

impl SubtreeHash {
	pub const fn as_bytes(&self) -> &[u8; 32] {
		&self.0
	}
}

impl fmt::Debug for SubtreeHash {
	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(formatter, "{}", self)
	}
}

impl fmt::Display for SubtreeHash {
	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
		for byte in self.0 {
			write!(formatter, "{byte:02x}")?;
		}
		Ok(())
	}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TreeNode {
	pub kind: String,
	pub value: Option<String>,
	pub anchor: Option<SemanticKey>,
	pub signature: Option<String>,
	pub child_order: ChildOrder,
	pub child_cardinality: ChildCardinality,
	pub children: Vec<TreeNode>,
}

impl TreeNode {
	#[cfg(test)]
	pub fn branch(kind: impl Into<String>, children: Vec<Self>) -> Self {
		Self {
			kind: kind.into(),
			value: None,
			anchor: None,
			signature: None,
			child_order: ChildOrder::Ordered,
			child_cardinality: ChildCardinality::Many,
			children,
		}
	}

	pub fn leaf(kind: impl Into<String>, value: impl Into<String>) -> Self {
		Self {
			kind: kind.into(),
			value: Some(value.into()),
			anchor: None,
			signature: None,
			child_order: ChildOrder::Ordered,
			child_cardinality: ChildCardinality::Many,
			children: Vec::new(),
		}
	}

	#[cfg(test)]
	pub fn with_anchor(mut self, namespace: impl Into<String>, value: impl Into<String>) -> Self {
		self.anchor = Some(SemanticKey::new(namespace, value));
		self
	}

	#[cfg(test)]
	pub fn with_parent_scoped_anchor(
		mut self,
		namespace: impl Into<String>,
		value: impl Into<String>,
	) -> Self {
		self.anchor = Some(SemanticKey::parent_scoped(namespace, value));
		self
	}

	#[cfg(test)]
	pub fn with_parent_scoped_ordered_similarity_anchor(
		mut self,
		namespace: impl Into<String>,
		value: impl Into<String>,
	) -> Self {
		self.anchor = Some(SemanticKey::parent_scoped_ordered_similarity(
			namespace, value,
		));
		self
	}

	#[cfg(test)]
	pub fn with_parent_scoped_ordered_similarity_position_anchor(
		mut self,
		namespace: impl Into<String>,
		value: impl Into<String>,
	) -> Self {
		self.anchor = Some(SemanticKey::parent_scoped_ordered_similarity_with_position(
			namespace, value,
		));
		self
	}

	#[cfg(test)]
	pub fn with_signature(mut self, signature: impl Into<String>) -> Self {
		self.signature = Some(signature.into());
		self
	}

	#[cfg(test)]
	pub const fn with_child_order(mut self, child_order: ChildOrder) -> Self {
		self.child_order = child_order;
		self
	}

	#[cfg(test)]
	pub const fn with_child_cardinality(mut self, child_cardinality: ChildCardinality) -> Self {
		self.child_cardinality = child_cardinality;
		self
	}
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct NormalizedNode {
	pub kind: String,
	pub value: Option<String>,
	pub anchor: Option<SemanticKey>,
	pub signature: Option<String>,
	/// Stable semantic components inherited from anchored/value-bearing
	/// ancestors. Scalar values themselves never participate in this path.
	pub policy_path: Vec<String>,
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub scalar_reducer_path: Option<Vec<String>>,
	#[serde(default, skip_serializing_if = "Vec::is_empty")]
	pub scalar_reducer_inputs: Vec<(RevisionId, String)>,
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub scalar_reducer_output: Option<String>,
	pub child_order: ChildOrder,
	pub child_cardinality: ChildCardinality,
	pub parent: Option<NodeId>,
	pub children: Vec<NodeId>,
	pub subtree_hash: SubtreeHash,
	pub height: u32,
	pub descendant_count: u32,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct NormalizedTree {
	root: NodeId,
	nodes: Vec<NormalizedNode>,
}

#[derive(Clone, Debug, Error, Eq, PartialEq)]
pub enum TreeError {
	#[error("normalized tree contains too many nodes")]
	TooManyNodes,
	#[error("node `{kind}` requires exactly one child, found {actual}")]
	InvalidChildCardinality { kind: String, actual: usize },
	#[error("node {0:?} is outside the normalized tree")]
	UnknownNode(NodeId),
	#[cfg(test)]
	#[error("node `{kind}` is not a scalar leaf")]
	InvalidScalarSynthesis { kind: String },
}

impl NormalizedTree {
	pub fn from_root(root: TreeNode) -> Result<Self, TreeError> {
		let mut nodes = Vec::new();
		let root = flatten_node(root, None, &[], &mut nodes)?;
		Ok(Self { root, nodes })
	}

	pub const fn root(&self) -> NodeId {
		self.root
	}

	pub fn node(&self, id: NodeId) -> Result<&NormalizedNode, TreeError> {
		self.nodes
			.get(id.get() as usize)
			.ok_or(TreeError::UnknownNode(id))
	}

	pub fn nodes(&self) -> impl ExactSizeIterator<Item = (NodeId, &NormalizedNode)> {
		self.nodes
			.iter()
			.enumerate()
			.map(|(index, node)| (NodeId::new(index as u32), node))
	}

	pub fn len(&self) -> usize {
		self.nodes.len()
	}

	pub fn semantically_equivalent(&self, other: &Self) -> bool {
		equivalent_subtrees(self, self.root, other, other.root)
	}

	#[cfg(test)]
	pub fn to_debug_json(&self) -> Result<String, serde_json::Error> {
		serde_json::to_string_pretty(self)
	}

	pub(crate) fn record_scalar_synthesis(
		&mut self,
		id: NodeId,
		reducer_path: Vec<String>,
		inputs: Vec<(RevisionId, String)>,
		output: String,
	) -> Result<(), TreeError> {
		let node = self
			.nodes
			.get_mut(id.get() as usize)
			.ok_or(TreeError::UnknownNode(id))?;
		node.scalar_reducer_path = Some(reducer_path);
		node.scalar_reducer_inputs = inputs;
		node.scalar_reducer_output = Some(output);
		Ok(())
	}

	#[cfg(test)]
	pub fn synthesize_scalar_value(
		&mut self,
		id: NodeId,
		value: String,
		reducer_path: Vec<String>,
		inputs: Vec<(RevisionId, String)>,
	) -> Result<(), TreeError> {
		let node = self
			.nodes
			.get_mut(id.get() as usize)
			.ok_or(TreeError::UnknownNode(id))?;
		if !node.children.is_empty() || node.value.is_none() {
			return Err(TreeError::InvalidScalarSynthesis {
				kind: node.kind.clone(),
			});
		}
		node.value = Some(value.clone());
		node.scalar_reducer_path = Some(reducer_path);
		node.scalar_reducer_inputs = inputs;
		node.scalar_reducer_output = Some(value);
		self.recompute_summaries();
		Ok(())
	}

	#[cfg(test)]
	fn recompute_summaries(&mut self) {
		for index in (0..self.nodes.len()).rev() {
			let id = NodeId::new(index as u32);
			let children = self.nodes[index].children.clone();
			let (subtree_hash, height, descendant_count) =
				summarize_node(id, &children, &self.nodes);
			let node = &mut self.nodes[index];
			node.subtree_hash = subtree_hash;
			node.height = height;
			node.descendant_count = descendant_count;
		}
	}
}

fn equivalent_subtrees(
	left_tree: &NormalizedTree,
	left_id: NodeId,
	right_tree: &NormalizedTree,
	right_id: NodeId,
) -> bool {
	let left = left_tree
		.node(left_id)
		.expect("semantic equivalence receives a node from the left tree");
	let right = right_tree
		.node(right_id)
		.expect("semantic equivalence receives a node from the right tree");
	if left.kind != right.kind
		|| left.value != right.value
		|| left.anchor != right.anchor
		|| left.signature != right.signature
		|| left.child_order != right.child_order
		|| left.child_cardinality != right.child_cardinality
		|| left.children.len() != right.children.len()
	{
		return false;
	}
	match left.child_order {
		ChildOrder::Ordered => left
			.children
			.iter()
			.zip(&right.children)
			.all(|(left, right)| equivalent_subtrees(left_tree, *left, right_tree, *right)),
		ChildOrder::Commutative => {
			let mut matched = vec![false; right.children.len()];
			left.children.iter().all(|left_child| {
				right
					.children
					.iter()
					.enumerate()
					.find(|(index, right_child)| {
						!matched[*index]
							&& left_tree
								.node(*left_child)
								.expect("left child belongs to its tree")
								.subtree_hash == right_tree
								.node(**right_child)
								.expect("right child belongs to its tree")
								.subtree_hash && equivalent_subtrees(
							left_tree,
							*left_child,
							right_tree,
							**right_child,
						)
					})
					.is_some_and(|(index, _)| {
						matched[index] = true;
						true
					})
			})
		}
	}
}

fn flatten_node(
	node: TreeNode,
	parent: Option<NodeId>,
	parent_policy_path: &[String],
	nodes: &mut Vec<NormalizedNode>,
) -> Result<NodeId, TreeError> {
	let id = NodeId::new(u32::try_from(nodes.len()).map_err(|_| TreeError::TooManyNodes)?);
	let TreeNode {
		kind,
		value,
		anchor,
		signature,
		child_order,
		child_cardinality,
		children,
	} = node;
	let mut policy_path = parent_policy_path.to_vec();
	if let Some(component) = anchor
		.as_ref()
		.map(|anchor| anchor.value.as_str())
		.or_else(|| (!children.is_empty()).then_some(value.as_deref()).flatten())
	{
		policy_path.push(component.to_string());
	}
	if child_cardinality == ChildCardinality::ExactlyOne && children.len() != 1 {
		return Err(TreeError::InvalidChildCardinality {
			kind,
			actual: children.len(),
		});
	}
	nodes.push(NormalizedNode {
		kind,
		value,
		anchor,
		signature,
		policy_path: policy_path.clone(),
		scalar_reducer_path: None,
		scalar_reducer_inputs: Vec::new(),
		scalar_reducer_output: None,
		child_order,
		child_cardinality,
		parent,
		children: Vec::with_capacity(children.len()),
		subtree_hash: SubtreeHash([0; 32]),
		height: 0,
		descendant_count: 0,
	});
	let child_ids = children
		.into_iter()
		.map(|child| flatten_node(child, Some(id), &policy_path, nodes))
		.collect::<Result<Vec<_>, _>>()?;
	let (subtree_hash, height, descendant_count) = summarize_node(id, &child_ids, nodes);
	let stored = &mut nodes[id.get() as usize];
	stored.children = child_ids;
	stored.subtree_hash = subtree_hash;
	stored.height = height;
	stored.descendant_count = descendant_count;
	Ok(id)
}

fn summarize_node(
	id: NodeId,
	children: &[NodeId],
	nodes: &[NormalizedNode],
) -> (SubtreeHash, u32, u32) {
	let node = &nodes[id.get() as usize];
	let mut hasher = blake3::Hasher::new();
	hasher.update(b"foch-normalized-tree-v1\0");
	hash_field(&mut hasher, node.kind.as_bytes());
	hash_optional_field(&mut hasher, node.value.as_deref());
	hash_optional_field(
		&mut hasher,
		node.anchor.as_ref().map(|anchor| anchor.namespace.as_str()),
	);
	hash_optional_field(
		&mut hasher,
		node.anchor.as_ref().map(|anchor| anchor.value.as_str()),
	);
	if let Some(anchor) = &node.anchor {
		hasher.update(&[match anchor.scope {
			SemanticKeyScope::Global => 0,
			SemanticKeyScope::Parent => 1,
		}]);
	}
	hash_optional_field(&mut hasher, node.signature.as_deref());
	hasher.update(&[match node.child_order {
		ChildOrder::Ordered => 0,
		ChildOrder::Commutative => 1,
	}]);
	hasher.update(&[match node.child_cardinality {
		ChildCardinality::Many => 0,
		ChildCardinality::ExactlyOne => 1,
	}]);
	let mut child_hashes = children
		.iter()
		.map(|child| nodes[child.get() as usize].subtree_hash)
		.collect::<Vec<_>>();
	if node.child_order == ChildOrder::Commutative {
		child_hashes.sort_unstable();
	}
	for hash in child_hashes {
		hasher.update(hash.as_bytes());
	}
	let height = children
		.iter()
		.map(|child| nodes[child.get() as usize].height)
		.max()
		.map_or(0, |height| height.saturating_add(1));
	let descendant_count = children.iter().fold(0u32, |total, child| {
		total
			.saturating_add(1)
			.saturating_add(nodes[child.get() as usize].descendant_count)
	});
	(
		SubtreeHash(*hasher.finalize().as_bytes()),
		height,
		descendant_count,
	)
}

fn hash_optional_field(hasher: &mut blake3::Hasher, value: Option<&str>) {
	match value {
		Some(value) => {
			hasher.update(&[1]);
			hash_field(hasher, value.as_bytes());
		}
		None => {
			hasher.update(&[0]);
		}
	}
}

fn hash_field(hasher: &mut blake3::Hasher, value: &[u8]) {
	hasher.update(&(value.len() as u64).to_le_bytes());
	hasher.update(value);
}

#[cfg(test)]
mod tests {
	use super::*;

	fn sample_tree() -> TreeNode {
		TreeNode::branch(
			"root",
			vec![
				TreeNode::leaf("scalar", "one").with_anchor("field", "a"),
				TreeNode::branch("block", vec![TreeNode::leaf("scalar", "two")]),
			],
		)
	}

	#[test]
	fn normalized_tree_uses_preorder_ids_and_parent_links() {
		let tree = NormalizedTree::from_root(sample_tree()).unwrap();

		assert_eq!(tree.root(), NodeId::new(0));
		assert_eq!(tree.len(), 4);
		assert_eq!(
			tree.node(NodeId::new(1)).unwrap().parent,
			Some(NodeId::new(0))
		);
		assert_eq!(
			tree.node(NodeId::new(3)).unwrap().parent,
			Some(NodeId::new(2))
		);
		assert_eq!(tree.node(NodeId::new(0)).unwrap().height, 2);
		assert_eq!(tree.node(NodeId::new(0)).unwrap().descendant_count, 3);
	}

	#[test]
	fn semantic_equivalence_respects_declared_child_order() {
		let children = || vec![TreeNode::leaf("field", "a"), TreeNode::leaf("field", "b")];
		let ordered = NormalizedTree::from_root(TreeNode::branch("root", children())).unwrap();
		let ordered_reversed = NormalizedTree::from_root(TreeNode::branch(
			"root",
			children().into_iter().rev().collect(),
		))
		.unwrap();
		let commutative = NormalizedTree::from_root(
			TreeNode::branch("root", children()).with_child_order(ChildOrder::Commutative),
		)
		.unwrap();
		let commutative_reversed = NormalizedTree::from_root(
			TreeNode::branch("root", children().into_iter().rev().collect())
				.with_child_order(ChildOrder::Commutative),
		)
		.unwrap();

		assert!(!ordered.semantically_equivalent(&ordered_reversed));
		assert!(commutative.semantically_equivalent(&commutative_reversed));
	}

	#[test]
	fn normalized_nodes_expose_stable_semantic_policy_paths() {
		let scalar_field = |value: &str| {
			let mut field = TreeNode::branch(
				"clausewitz.assignment:province_trade_power_modifier",
				vec![TreeNode::leaf("clausewitz.scalar.number", value)],
			)
			.with_child_cardinality(ChildCardinality::ExactlyOne);
			field.value = Some("province_trade_power_modifier".to_string());
			field
		};
		let trade_good = |value: &str| {
			let mut definition = TreeNode::branch(
				"clausewitz.assignment:cloves",
				vec![TreeNode::branch(
					"clausewitz.block:cloves",
					vec![scalar_field(value)],
				)],
			);
			definition.value = Some("cloves".to_string());
			TreeNode::branch("clausewitz.file", vec![definition])
		};
		let left = NormalizedTree::from_root(trade_good(".2")).unwrap();
		let right = NormalizedTree::from_root(trade_good(".1")).unwrap();
		let left_scalar = left
			.nodes()
			.find(|(_, node)| node.kind == "clausewitz.scalar.number")
			.unwrap()
			.1;
		let right_scalar = right
			.nodes()
			.find(|(_, node)| node.kind == "clausewitz.scalar.number")
			.unwrap()
			.1;

		assert_eq!(
			left_scalar.policy_path,
			vec!["cloves", "province_trade_power_modifier"]
		);
		assert_eq!(left_scalar.policy_path, right_scalar.policy_path);
	}

	#[test]
	fn normalized_hashes_are_repeatable_and_content_sensitive() {
		let first = NormalizedTree::from_root(sample_tree()).unwrap();
		let second = NormalizedTree::from_root(sample_tree()).unwrap();
		let changed = NormalizedTree::from_root(TreeNode::branch(
			"root",
			vec![TreeNode::leaf("scalar", "changed")],
		))
		.unwrap();

		assert_eq!(
			first.node(first.root()).unwrap().subtree_hash,
			second.node(second.root()).unwrap().subtree_hash
		);
		assert_ne!(
			first.node(first.root()).unwrap().subtree_hash,
			changed.node(changed.root()).unwrap().subtree_hash
		);
	}

	#[test]
	fn scalar_synthesis_updates_value_evidence_and_ancestor_hashes() {
		let mut tree = NormalizedTree::from_root(sample_tree()).unwrap();
		let scalar = NodeId::new(1);
		let original_root_hash = tree.node(tree.root()).unwrap().subtree_hash;

		tree.synthesize_scalar_value(
			scalar,
			"merged".to_string(),
			vec!["a".to_string()],
			vec![
				(RevisionId::new(1), "left".to_string()),
				(RevisionId::new(2), "right".to_string()),
			],
		)
		.unwrap();

		let node = tree.node(scalar).unwrap();
		assert_eq!(node.value.as_deref(), Some("merged"));
		assert_eq!(node.scalar_reducer_output.as_deref(), Some("merged"));
		assert_eq!(node.scalar_reducer_inputs.len(), 2);
		assert_ne!(
			tree.node(tree.root()).unwrap().subtree_hash,
			original_root_hash
		);
	}

	#[test]
	fn commutative_hash_ignores_child_order_but_ordered_hash_does_not() {
		let children = vec![TreeNode::leaf("scalar", "a"), TreeNode::leaf("scalar", "b")];
		let reversed = vec![TreeNode::leaf("scalar", "b"), TreeNode::leaf("scalar", "a")];
		let commutative = NormalizedTree::from_root(
			TreeNode::branch("root", children.clone()).with_child_order(ChildOrder::Commutative),
		)
		.unwrap();
		let commutative_reversed = NormalizedTree::from_root(
			TreeNode::branch("root", reversed.clone()).with_child_order(ChildOrder::Commutative),
		)
		.unwrap();
		let ordered = NormalizedTree::from_root(TreeNode::branch("root", children)).unwrap();
		let ordered_reversed =
			NormalizedTree::from_root(TreeNode::branch("root", reversed)).unwrap();

		assert_eq!(
			commutative.node(commutative.root()).unwrap().subtree_hash,
			commutative_reversed
				.node(commutative_reversed.root())
				.unwrap()
				.subtree_hash
		);
		assert_ne!(
			ordered.node(ordered.root()).unwrap().subtree_hash,
			ordered_reversed
				.node(ordered_reversed.root())
				.unwrap()
				.subtree_hash
		);
	}

	#[test]
	fn exactly_one_cardinality_rejects_invalid_source_trees() {
		for children in [
			Vec::new(),
			vec![
				TreeNode::leaf("value", "one"),
				TreeNode::leaf("value", "two"),
			],
		] {
			let error = NormalizedTree::from_root(
				TreeNode::branch("slot", children)
					.with_child_cardinality(ChildCardinality::ExactlyOne),
			)
			.expect_err("an exactly-one node must contain one child");
			assert!(matches!(
				error,
				TreeError::InvalidChildCardinality { kind, .. } if kind == "slot"
			));
		}
	}

	#[test]
	fn cardinality_participates_in_the_structural_hash() {
		let child = || TreeNode::leaf("value", "same");
		let many = NormalizedTree::from_root(TreeNode::branch("slot", vec![child()])).unwrap();
		let exactly_one = NormalizedTree::from_root(
			TreeNode::branch("slot", vec![child()])
				.with_child_cardinality(ChildCardinality::ExactlyOne),
		)
		.unwrap();

		assert_ne!(
			many.node(many.root()).unwrap().subtree_hash,
			exactly_one.node(exactly_one.root()).unwrap().subtree_hash
		);
	}

	#[test]
	fn debug_json_is_stable() {
		let first = NormalizedTree::from_root(sample_tree())
			.unwrap()
			.to_debug_json()
			.unwrap();
		let second = NormalizedTree::from_root(sample_tree())
			.unwrap()
			.to_debug_json()
			.unwrap();

		assert_eq!(first, second);
	}
}