{"messages":[{"content":"You are a constitutional council ranking individual git commits for ownership allocation.\n\nCompare these two commits. Decide which contributed more lasting value to the project.\n\nJudge substance, not spectacle:\n- Prefer correct, lasting design and real bugfixes over churn, formatting, renames, or generated noise.\n- Prefer clarity and necessity over sheer line count. A small precise change can beat a large diffuse one.\n- Do not favor a side merely because its patch is longer or noisier.\n- Weight what the change does for the project, not the contributor's name.\n\nReturn ONLY a JSON object: {\"winner\": \"A\" or \"B\", \"ratio\": \"N:M\", \"explanation\": \"...\"}\nThe explanation must cite concrete differences in the patches (1-3 sentences).\n\nSide A — contributor: tommy-mor\nSide A — commit message:\n[af73743d] Replace GroupState with ScopeVotes and derive edges at ranking time.\n\nStore only uuid_votes and recent_votes per scope; rank centrality and pair logic rebuild edge weights on demand instead of maintaining cached state.\n\nCo-authored-by: Cursor \n\nSide A — unified diff (full patch):\ndiff --git a/server/src/events.rs b/server/src/events.rs\nindex 8a166d49b4f26835fbc2b58cb1f4bdbf002763b8..015208311f6c5c23a0e8aab068d002a69c89c4e1 100644\n--- a/server/src/events.rs\n+++ b/server/src/events.rs\n@@ -43,7 +43,7 @@ pub enum ViewEvent {\n #[derive(Debug, Clone, Serialize, Deserialize)]\n #[serde(tag = \"type\", rename_all = \"snake_case\")]\n pub enum Event {\n- /// Pairwise comparison vote (replayed into the parent node's [`crate::reducer::GroupState`] on boot).\n+ /// Pairwise comparison vote (replayed into the parent node's [`crate::reducer::ScopeVotes`] on boot).\n /// `scope` is the parent [`crate::path_types::ItemId`] string; empty string is the tree root.\n VoteRecorded {\n ts: i64,\ndiff --git a/server/src/html/mod.rs b/server/src/html/mod.rs\nindex 4eff2e19ed4d303ff8e80c1eabd8a15b4990e643..1e2e7a06856d8a62378741aaf5ed94a4ffed337e 100644\n--- a/server/src/html/mod.rs\n+++ b/server/src/html/mod.rs\n@@ -13,7 +13,7 @@ use crate::{\n form_template::template_json_compact,\n path_types::ItemId,\n ranking::{\n- connected_components_from_voted_pairs, ranked_items_subset, RankedItem, MAX_ITERS, TOL,\n+ ranked_items_subset, scope_components, RankedItem, MAX_ITERS, TOL,\n },\n reducer::{GlobalTree, NodeState},\n state::AppState,\n@@ -397,10 +397,9 @@ pub fn ranking_panel_with_highlights(\n tree: &GlobalTree,\n highlighted: &HashSet,\n ) -> Markup {\n- let group = &node.local_ranking;\n- let n = group.idx_to_item.len();\n- let (comps, _isolates) =\n- connected_components_from_voted_pairs(n, group.voted_pairs.iter().copied());\n+ let scope = &node.votes;\n+ let (comps, _isolates, _) =\n+ scope_components(scope);\n \n // Each connected component of voted items is its own ranking; isolated and\n // never-voted children fall into the \"unranked\" bucket below.\n@@ -410,7 +409,7 @@ pub fn ranking_panel_with_highlights(\n if comp.len() < 2 {\n continue;\n }\n- let ranked = ranked_items_subset(group, comp, MAX_ITERS, TOL);\n+ let ranked = ranked_items_subset(scope, comp, MAX_ITERS, TOL);\n for r in &ranked {\n ranked_ids.insert(r.item.clone());\n }\ndiff --git a/server/src/html/vote.rs b/server/src/html/vote.rs\nindex bf82aef3ad9c5f4e9e877c47dab27beb29a80b8f..3aa00c417c89a9cab3417c650b50ed7c73f08e20 100644\n--- a/server/src/html/vote.rs\n+++ b/server/src/html/vote.rs\n@@ -14,7 +14,7 @@ use crate::{\n html::{ranking_panel_with_highlights, scope_theme_style, JsBuilder},\n pair::{children_of, resolve_pair, suggest_next_pair_in_pool},\n path_types::ItemId,\n- reducer::{GlobalTree, GroupState, NodeState, VoteData},\n+ reducer::{GlobalTree, NodeState, ScopeVotes, VoteData},\n state::{parse_item_param, AppState},\n ui_action::UI_RPC_FIELD,\n };\n@@ -68,8 +68,8 @@ fn ratios_for_page(v: &VoteData, page_left: &ItemId, page_right: &ItemId) -> (i3\n }\n }\n \n-fn edge_votes(group: &GroupState, left: &ItemId, right: &ItemId) -> Vec {\n- group\n+fn edge_votes(scope: &ScopeVotes, left: &ItemId, right: &ItemId) -> Vec {\n+ scope\n .recent_votes\n .iter()\n .filter(|v| {\n@@ -113,11 +113,11 @@ fn slider_value_from_ratios(r_left: i32, r_right: i32) -> i32 {\n \n fn vote_edge_history(\n tree: &GlobalTree,\n- group: &GroupState,\n+ scope: &ScopeVotes,\n left: &ItemId,\n right: &ItemId,\n ) -> Markup {\n- let mut votes = edge_votes(group, left, right);\n+ let mut votes = edge_votes(scope, left, right);\n votes.sort_by(|a, b| b.ts.cmp(&a.ts));\n let legend_left = child_title(tree, left);\n let legend_right = child_title(tree, right);\n@@ -228,9 +228,9 @@ pub(crate) fn vote_recorded_morph(\n ) -> JsBuilder {\n let pool = children_of(tree, parent);\n let empty = NodeState::default();\n- let group = tree.get(parent).unwrap_or(&empty).local_ranking.clone();\n- let edge_history = vote_edge_history(tree, &group, left, right);\n- let next_pair = suggest_next(&group, left, right, &pool);\n+ let scope = tree.get(parent).unwrap_or(&empty).votes.clone();\n+ let edge_history = vote_edge_history(tree, &scope, left, right);\n+ let next_pair = suggest_next(&scope, left, right, &pool);\n let actions = vote_compare_actions(parent, next_pair.as_ref());\n let sidebar = vote_ranking_sidebar(tree, parent, left, right);\n JsBuilder::new()\n@@ -252,12 +252,12 @@ fn vote_compare_item_card(tree: &GlobalTree, item: &ItemId, side_class: &str) ->\n }\n \n fn suggest_next(\n- group: &GroupState,\n+ scope: &ScopeVotes,\n left: &ItemId,\n right: &ItemId,\n pool: &[ItemId],\n ) -> Option<(ItemId, ItemId)> {\n- suggest_next_pair_in_pool(group, pool, Some((left, right)))\n+ suggest_next_pair_in_pool(scope, pool, Some((left, right)))\n }\n \n pub async fn vote_page(\n@@ -284,9 +284,9 @@ pub async fn vote_page(\n };\n \n let pool = children_of(&tree, &parent);\n- let group = &parent_node.local_ranking;\n- let next_pair = suggest_next(group, &left, &right, &pool);\n- let edge_history = vote_edge_history(&tree, group, &left, &right);\n+ let scope = &parent_node.votes;\n+ let next_pair = suggest_next(&scope, &left, &right, &pool);\n+ let edge_history = vote_edge_history(&tree, &scope, &left, &right);\n \n let rpc_json = template_json_compact(&serde_json::json!({\n \"action\": \"record_vote\",\n@@ -388,8 +388,8 @@ mod polarity_tests {\n let mut tree = GlobalTree::new();\n tree.apply_vote(&parent, vote, TEST_ACTOR_UUID);\n \n- let group = &tree.get(&parent).unwrap().local_ranking;\n- let ranked = ranked_items(group);\n+ let scope = &tree.get(&parent).unwrap().votes;\n+ let ranked = ranked_items(scope);\n assert_eq!(\n ranked[0].item, left,\n \"left item should rank first when ratio favours the left\"\ndiff --git a/server/src/pair.rs b/server/src/pair.rs\nindex 42a1b1eb2adf16730d34d0fe23c13d5a75d7ba27..9873295c51526726089875bbfd2f97d7faa91872 100644\n--- a/server/src/pair.rs\n+++ b/server/src/pair.rs\n@@ -11,8 +11,8 @@ use std::collections::{HashMap, HashSet};\n \n use crate::{\n path_types::ItemId,\n- ranking::{connected_components_from_voted_pairs, ranked_items},\n- reducer::{GlobalTree, GroupState},\n+ ranking::{pair_is_voted, ranked_items, scope_components},\n+ reducer::{GlobalTree, ScopeVotes},\n };\n \n fn pairs_match(a: &ItemId, b: &ItemId, x: &ItemId, y: &ItemId) -> bool {\n@@ -23,26 +23,15 @@ fn pair_excluded(a: &ItemId, b: &ItemId, exclude: Option<(&ItemId, &ItemId)>) ->\n exclude.is_some_and(|(x, y)| pairs_match(a, b, x, y))\n }\n \n-fn pair_is_voted(group: &GroupState, a: &ItemId, b: &ItemId) -> bool {\n- let Some(&ai) = group.item_to_idx.get(a) else {\n- return false;\n- };\n- let Some(&bi) = group.item_to_idx.get(b) else {\n- return false;\n- };\n- let (i, j) = if ai < bi { (ai, bi) } else { (bi, ai) };\n- group.voted_pairs.contains(&(i, j))\n-}\n \n struct ComponentLayout {\n ids: HashMap,\n established: HashSet,\n }\n \n-fn component_layout(group: &GroupState, pool: &[ItemId]) -> ComponentLayout {\n- let n = group.idx_to_item.len();\n- let (comps, isolates) =\n- connected_components_from_voted_pairs(n, group.voted_pairs.iter().copied());\n+fn component_layout(scope: &ScopeVotes, pool: &[ItemId]) -> ComponentLayout {\n+ let (comps, isolates, idx_to_item) = scope_components(scope);\n+ let n = idx_to_item.len();\n \n let mut established = HashSet::new();\n let mut ids: HashMap = HashMap::new();\n@@ -52,14 +41,14 @@ fn component_layout(group: &GroupState, pool: &[ItemId]) -> ComponentLayout {\n }\n for &idx in comp {\n if idx < n {\n- ids.insert(group.idx_to_item[idx].clone(), comp_idx);\n+ ids.insert(idx_to_item[idx].clone(), comp_idx);\n }\n }\n }\n let mut next = comps.len();\n for &idx in &isolates {\n if idx < n {\n- ids.insert(group.idx_to_item[idx].clone(), next);\n+ ids.insert(idx_to_item[idx].clone(), next);\n next += 1;\n }\n }\n@@ -121,7 +110,7 @@ fn established_groups_in_pool<'a>(\n groups\n }\n \n-fn ranked_pool_order(group: &GroupState, pool: &[ItemId]) -> Vec {\n+fn ranked_pool_order(group: &ScopeVotes, pool: &[ItemId]) -> Vec {\n let pool_set: HashSet<_> = pool.iter().collect();\n ranked_items(group)\n .into_iter()\n@@ -132,7 +121,7 @@ fn ranked_pool_order(group: &GroupState, pool: &[ItemId]) -> Vec {\n \n /// Walk 1↔2, 2↔3, …; optional `require_unvoted` skips voted edges.\n fn zip_adjacent_pair(\n- group: &GroupState,\n+ group: &ScopeVotes,\n order: &[ItemId],\n exclude: Option<(&ItemId, &ItemId)>,\n require_unvoted: bool,\n@@ -153,7 +142,7 @@ fn zip_adjacent_pair(\n \n /// Grow the voted graph toward one component (no rank centrality).\n fn suggest_grow_pair(\n- group: &GroupState,\n+ group: &ScopeVotes,\n pool: &[ItemId],\n layout: &ComponentLayout,\n exclude: Option<(&ItemId, &ItemId)>,\n@@ -216,7 +205,7 @@ fn suggest_grow_pair(\n \n /// Pick the next pair to vote on within `pool`.\n pub fn suggest_next_pair_in_pool(\n- group: &GroupState,\n+ group: &ScopeVotes,\n pool: &[ItemId],\n exclude: Option<(&ItemId, &ItemId)>,\n ) -> Option<(ItemId, ItemId)> {\n@@ -315,7 +304,7 @@ pub fn resolve_pair(\n (None, None) => {\n let group = tree\n .get(parent)\n- .map(|n| &n.local_ranking)\n+ .map(|n| &n.votes)\n .cloned()\n .unwrap_or_default();\n suggest_next_pair_in_pool(&group, &children, None).ok_or(PairError::NoPair)\n@@ -398,7 +387,7 @@ mod tests {\n \"https://reddit.com/r/rust/b\",\n ],\n );\n- let group = tree.get(&parent).unwrap().local_ranking.clone();\n+ let group = tree.get(&parent).unwrap().votes.clone();\n let pool = children_of(&tree, &parent);\n assert!(!pair_is_voted(&group, &pool[0], &pool[1]));\n assert!(suggest_next_pair_in_pool(&group, &pool, None).is_some());\n@@ -417,7 +406,7 @@ mod tests {\n );\n let vote = test_vote(1, \"https://reddit.com/r/rust/a\", \"https://reddit.com/r/rust/b\", 2, 1);\n apply(&mut tree, &parent, vote);\n- let group = tree.get(&parent).unwrap().local_ranking.clone();\n+ let group = tree.get(&parent).unwrap().votes.clone();\n let pool = children_of(&tree, &parent);\n let (l, r) = suggest_next_pair_in_pool(&group, &pool, None).unwrap();\n let voted_ab = (l.as_str() == \"https://reddit.com/r/rust/a\" && r.as_str() == \"https://reddit.com/r/rust/b\")\n@@ -441,7 +430,7 @@ mod tests {\n let cd = test_vote(2, \"https://reddit.com/r/rust/c\", \"https://reddit.com/r/rust/d\", 2, 1);\n apply(&mut tree, &parent, ab);\n apply(&mut tree, &parent, cd);\n- let group = tree.get(&parent).unwrap().local_ranking.clone();\n+ let group = tree.get(&parent).unwrap().votes.clone();\n let pool = children_of(&tree, &parent);\n let pair = suggest_next_pair_in_pool(&group, &pool, None).unwrap();\n let chosen = pair_set(&pair);\n@@ -467,7 +456,7 @@ mod tests {\n );\n let ab = test_vote(1, \"https://reddit.com/r/rust/a\", \"https://reddit.com/r/rust/b\", 2, 1);\n apply(&mut tree, &parent, ab);\n- let group = tree.get(&parent).unwrap().local_ranking.clone();\n+ let group = tree.get(&parent).unwrap().votes.clone();\n let pool = children_of(&tree, &parent);\n let pair = suggest_next_pair_in_pool(&group, &pool, None).unwrap();\n let chosen = pair_set(&pair);\n@@ -496,7 +485,7 @@ mod tests {\n );\n let ab = test_vote(1, \"https://reddit.com/r/rust/a\", \"https://reddit.com/r/rust/b\", 2, 1);\n apply(&mut tree, &parent, ab);\n- let group = tree.get(&parent).unwrap().local_ranking.clone();\n+ let group = tree.get(&parent).unwrap().votes.clone();\n let pool = children_of(&tree, &parent);\n let pair = suggest_next_pair_in_pool(&group, &pool, None).unwrap();\n let chosen = pair_set(&pair);\n@@ -522,7 +511,7 @@ mod tests {\n let v = test_vote(1, a, b, l, r);\n apply(&mut tree, &parent, v);\n }\n- let group = tree.get(&parent).unwrap().local_ranking.clone();\n+ let group = tree.get(&parent).unwrap().votes.clone();\n let pool = children_of(&tree, &parent);\n let pair = suggest_next_pair_in_pool(&group, &pool, None).unwrap();\n let chosen = pair_set(&pair);\n@@ -550,7 +539,7 @@ mod tests {\n let v = test_vote(1, a, b, l, r);\n apply(&mut tree, &parent, v);\n }\n- let group = tree.get(&parent).unwrap().local_ranking.clone();\n+ let group = tree.get(&parent).unwrap().votes.clone();\n let pool = children_of(&tree, &parent);\n let pair = suggest_next_pair_in_pool(&group, &pool, None).unwrap();\n let chosen = pair_set(&pair);\ndiff --git a/server/src/projection_store.rs b/server/src/projection_store.rs\nindex 27fc0bb0519d9f035dceec1fc8b0fa74b00b6b40..8c1a466183a96173fe52b144fb67c2454b715fbd 100644\n--- a/server/src/projection_store.rs\n+++ b/server/src/projection_store.rs\n@@ -214,7 +214,7 @@ mod tests {\n \n let loaded = store.load_tree().unwrap();\n let root = loaded.get(&ItemId::root()).unwrap();\n- assert_eq!(root.local_ranking.idx_to_item.len(), 2);\n+ assert_eq!(crate::ranking::ranked_items(&root.votes).len(), 2);\n assert!(root.children.contains(&ItemId::opaque(\"alpha\")));\n }\n \ndiff --git a/server/src/ranking.rs b/server/src/ranking.rs\nindex 1fc3298d2b2864e9711cd262a034677e45c7090c..cc4de6da11b02135e5e6b1d2a68646cb77870b9d 100644\n--- a/server/src/ranking.rs\n+++ b/server/src/ranking.rs\n@@ -1,7 +1,7 @@\n-use std::collections::{HashMap, HashSet};\n+use std::collections::{BTreeSet, HashMap, HashSet};\n \n use crate::path_types::ItemId;\n-use crate::reducer::GroupState;\n+use crate::reducer::{canonical_pair_ids, ScopeVotes};\n \n #[derive(Debug, Clone)]\n pub struct RankedItem {\n@@ -9,15 +9,76 @@ pub struct RankedItem {\n pub score: f64,\n }\n \n-/// Power-iteration cap and convergence tolerance for rank centrality.\n pub const MAX_ITERS: usize = 10_000;\n pub const TOL: f64 = 1e-8;\n \n-/// Compute connected components over the voted-pairs graph (treated as undirected).\n-///\n-/// Returns:\n-/// - `components`: each component is a sorted list of node indices, excluding isolates.\n-/// - `isolates`: sorted list of node indices with degree 0 (no voted pairs).\n+pub fn item_index(scope: &ScopeVotes) -> (HashMap, Vec) {\n+ let mut item_strs: BTreeSet = BTreeSet::new();\n+ for vote in scope.uuid_votes.values() {\n+ item_strs.insert(vote.a.as_str().to_string());\n+ item_strs.insert(vote.b.as_str().to_string());\n+ }\n+ let mut idx_to_item: Vec = Vec::with_capacity(item_strs.len());\n+ let mut item_to_idx: HashMap = HashMap::with_capacity(item_strs.len());\n+ for s in item_strs {\n+ let id = ItemId::from_storage(&s).unwrap_or_else(|| ItemId::opaque(&s));\n+ let idx = idx_to_item.len();\n+ item_to_idx.insert(id.clone(), idx);\n+ idx_to_item.push(id);\n+ }\n+ (item_to_idx, idx_to_item)\n+}\n+\n+pub fn edges_from_scope(scope: &ScopeVotes) -> HashMap<(usize, usize), f64> {\n+ let (item_to_idx, _) = item_index(scope);\n+ let mut edges: HashMap<(usize, usize), f64> = HashMap::new();\n+ for vote in scope.uuid_votes.values() {\n+ let Some(&ai) = item_to_idx.get(&vote.a) else {\n+ continue;\n+ };\n+ let Some(&bi) = item_to_idx.get(&vote.b) else {\n+ continue;\n+ };\n+ let w_a = vote.ratio_left as f64 * vote.trust_weight;\n+ let w_b = vote.ratio_right as f64 * vote.trust_weight;\n+ if w_a > 0.0 {\n+ *edges.entry((bi, ai)).or_insert(0.0) += w_a;\n+ }\n+ if w_b > 0.0 {\n+ *edges.entry((ai, bi)).or_insert(0.0) += w_b;\n+ }\n+ }\n+ edges\n+}\n+\n+pub fn edge_weight_sum(scope: &ScopeVotes) -> f64 {\n+ edges_from_scope(scope).values().sum()\n+}\n+\n+pub fn voted_pair_indices(scope: &ScopeVotes) -> HashSet<(usize, usize)> {\n+ let (item_to_idx, _) = item_index(scope);\n+ let mut pairs = HashSet::new();\n+ for vote in scope.uuid_votes.values() {\n+ let Some(&ai) = item_to_idx.get(&vote.a) else {\n+ continue;\n+ };\n+ let Some(&bi) = item_to_idx.get(&vote.b) else {\n+ continue;\n+ };\n+ let (i, j) = if ai < bi { (ai, bi) } else { (bi, ai) };\n+ pairs.insert((i, j));\n+ }\n+ pairs\n+}\n+\n+pub fn pair_is_voted(scope: &ScopeVotes, a: &ItemId, b: &ItemId) -> bool {\n+ let (lo, hi) = canonical_pair_ids(a, b);\n+ scope\n+ .uuid_votes\n+ .keys()\n+ .any(|(_, l, h)| l == &lo && h == &hi)\n+}\n+\n pub fn connected_components_from_voted_pairs(\n n: usize,\n voted_pairs: impl Iterator,\n@@ -63,20 +124,25 @@ pub fn connected_components_from_voted_pairs(\n (comps, isolates)\n }\n \n-/// Compute rank-centrality scores for the whole group and return items sorted\n-/// by score (descending). Recomputed fresh from the edge set on every call —\n-/// there is no score cache.\n-pub fn ranked_items(group: &GroupState) -> Vec {\n- let n = group.idx_to_item.len();\n- let scores =\n- compute_scores_from_edges(n, group.edges.iter().map(|(&k, &w)| (k, w)), MAX_ITERS, TOL);\n+pub fn scope_components(scope: &ScopeVotes) -> (Vec>, Vec, Vec) {\n+ let (_, idx_to_item) = item_index(scope);\n+ let n = idx_to_item.len();\n+ let pairs = voted_pair_indices(scope);\n+ let (comps, isolates) = connected_components_from_voted_pairs(n, pairs.into_iter());\n+ (comps, isolates, idx_to_item)\n+}\n \n- let mut items: Vec = group\n- .idx_to_item\n- .iter()\n+pub fn ranked_items(scope: &ScopeVotes) -> Vec {\n+ let (_, idx_to_item) = item_index(scope);\n+ let n = idx_to_item.len();\n+ let edges = edges_from_scope(scope);\n+ let scores = compute_scores_from_edges(n, edges.into_iter(), MAX_ITERS, TOL);\n+\n+ let mut items: Vec = idx_to_item\n+ .into_iter()\n .enumerate()\n .map(|(i, item)| RankedItem {\n- item: item.clone(),\n+ item,\n score: *scores.get(i).unwrap_or(&0.0),\n })\n .collect();\n@@ -89,11 +155,8 @@ pub fn ranked_items(group: &GroupState) -> Vec {\n items\n }\n \n-/// Highest- and lowest-ranked items for a group. Returns up to `k` items from\n-/// each end with no overlap. If the group has `2*k` items or fewer, `top` holds\n-/// the full ranking and `bottom` is empty (so nothing is shown twice).\n-pub fn top_bottom(group: &GroupState, k: usize) -> (Vec, Vec) {\n- let items = ranked_items(group);\n+pub fn top_bottom(scope: &ScopeVotes, k: usize) -> (Vec, Vec) {\n+ let items = ranked_items(scope);\n if k == 0 || items.len() <= 2 * k {\n return (items, Vec::new());\n }\n@@ -115,7 +178,6 @@ pub fn compute_scores_from_edges(\n return vec![1.0];\n }\n \n- // Collect raw edges into a map for pairwise normalization.\n let mut raw: HashMap<(usize, usize), f64> = HashMap::new();\n for ((src, dst), w) in edges {\n if src >= n || dst >= n || w <= 0.0 {\n@@ -124,9 +186,6 @@ pub fn compute_scores_from_edges(\n *raw.entry((src, dst)).or_insert(0.0) += w;\n }\n \n- // Pairwise normalization: a_ij = A_ij / (A_ij + A_ji).\n- // This ensures repeated votes on the same pair don't inflate influence\n- // beyond what the ratio implies.\n let keys: Vec<(usize, usize)> = raw.keys().copied().collect();\n let mut normalized: HashMap<(usize, usize), f64> = HashMap::new();\n for (i, j) in keys {\n@@ -145,17 +204,6 @@ pub fn compute_scores_from_edges(\n }\n }\n \n- // Rank Centrality (Negahban, Oh, Shah 2012, §3.1):\n- // P_ij = (1/d_max) * A_ij for i ≠ j compared\n- // P_ii = 1 - (1/d_max) * Σ_k A_ik\n- // where d_i is the *degree* (number of distinct neighbors compared) and\n- // d_max = max_i d_i. Using the unweighted degree — not the sum of\n- // pairwise-normalized weights — is what guarantees aperiodicity: it\n- // forces P_ii > 0 for every non-maximum-degree node, and for max-degree\n- // nodes whenever any neighbor weight is below 1 (i.e. not a unanimous\n- // loss). Without this, regular comparison graphs (e.g. a pure star at\n- // ratio 2:1) produce a bipartite chain that oscillates instead of\n- // converging — see issue #146.\n let mut out_edges: Vec> = vec![Vec::new(); n];\n let mut neighbors: Vec> = vec![HashSet::new(); n];\n \n@@ -213,11 +261,8 @@ pub fn compute_scores_from_edges(\n scores\n }\n \n-/// Rank-centrality within a subset of items (an induced subgraph), using the group's aggregated edges.\n-///\n-/// `idxs` are indices into `group.idx_to_item`. The returned items use the original item names.\n pub fn ranked_items_subset(\n- group: &GroupState,\n+ scope: &ScopeVotes,\n idxs: &[usize],\n max_iters: usize,\n tol: f64,\n@@ -226,13 +271,15 @@ pub fn ranked_items_subset(\n return vec![];\n }\n \n- // Map original idx -> compact idx [0..m)\n+ let (_, idx_to_item) = item_index(scope);\n+ let edges = edges_from_scope(scope);\n+\n let mut map: HashMap = HashMap::with_capacity(idxs.len());\n for (j, &i) in idxs.iter().enumerate() {\n map.insert(i, j);\n }\n \n- let edges_iter = group.edges.iter().filter_map(|(&(src, dst), &w)| {\n+ let edges_iter = edges.into_iter().filter_map(|((src, dst), w)| {\n let s = *map.get(&src)?;\n let d = *map.get(&dst)?;\n Some(((s, d), w))\n@@ -240,12 +287,11 @@ pub fn ranked_items_subset(\n \n let scores = compute_scores_from_edges(idxs.len(), edges_iter, max_iters, tol);\n \n- // Filter out entries where idx_to_item doesn't have the slot (shouldn't happen, but be safe).\n let mut items: Vec = idxs\n .iter()\n .enumerate()\n .filter_map(|(j, &orig)| {\n- let item = group.idx_to_item.get(orig)?.clone();\n+ let item = idx_to_item.get(orig)?.clone();\n Some(RankedItem {\n item,\n score: *scores.get(j).unwrap_or(&0.0),\n@@ -261,8 +307,8 @@ pub fn ranked_items_subset(\n items\n }\n \n-pub fn group_summary_scores(group: &GroupState) -> HashMap {\n- ranked_items(group)\n+pub fn group_summary_scores(scope: &ScopeVotes) -> HashMap {\n+ ranked_items(scope)\n .into_iter()\n .map(|r| (r.item, r.score))\n .collect()\n@@ -274,32 +320,26 @@ mod tests {\n use crate::identity::{DEFAULT_PSEUDONYM, TEST_ACTOR_UUID};\n use crate::reducer::VoteData;\n \n- fn mk_group() -> GroupState {\n- GroupState::new()\n+ fn mk_scope() -> ScopeVotes {\n+ ScopeVotes::default()\n }\n \n fn vote(ts: i64, a: &str, b: &str, l: i32, r: i32) -> VoteData {\n VoteData::from_event(ts, a, b, l, r, DEFAULT_PSEUDONYM.to_string(), 1.0).unwrap()\n }\n \n- fn apply(g: &mut GroupState, v: VoteData) {\n- g.apply_vote(v, TEST_ACTOR_UUID);\n+ fn apply(scope: &mut ScopeVotes, v: VoteData) {\n+ scope.apply_vote(v, TEST_ACTOR_UUID);\n }\n \n- /// Regression for issue #146: pure forward star at default `>` ratio (2:1).\n- /// Under the old (sum-of-weights) divisor every node had P_ii = 0 and the\n- /// chain was bipartite; power iteration oscillated and returned the\n- /// uniform initial distribution after an even number of steps. Using the\n- /// paper's degree-based d_max gives every node a positive self-loop and\n- /// the chain converges to the correct stationary distribution.\n #[test]\n fn star_topology_winner_at_top_via_subset() {\n- let mut g = mk_group();\n- g.apply_vote(vote(1, \"zebra\", \"alpha\", 2, 1), TEST_ACTOR_UUID);\n- g.apply_vote(vote(2, \"zebra\", \"beta\", 2, 1), TEST_ACTOR_UUID);\n+ let mut scope = mk_scope();\n+ apply(&mut scope, vote(1, \"zebra\", \"alpha\", 2, 1));\n+ apply(&mut scope, vote(2, \"zebra\", \"beta\", 2, 1));\n \n- let mut items: Vec<(usize, String)> = g\n- .idx_to_item\n+ let (_, idx_to_item) = item_index(&scope);\n+ let mut items: Vec<(usize, String)> = idx_to_item\n .iter()\n .enumerate()\n .map(|(i, it)| (i, it.as_str().to_string()))\n@@ -307,78 +347,51 @@ mod tests {\n items.sort_by(|a, b| a.1.cmp(&b.1));\n let idxs: Vec = items.iter().map(|(i, _)| *i).collect();\n \n- let ranked = ranked_items_subset(&g, &idxs, 10000, 1e-8);\n- for r in &ranked {\n- eprintln!(\"{}: {}\", r.item.as_str(), r.score);\n- }\n- assert_eq!(\n- ranked[0].item.as_str(),\n- \"zebra\",\n- \"zebra won both votes and should rank #1\"\n- );\n+ let ranked = ranked_items_subset(&scope, &idxs, 10000, 1e-8);\n+ assert_eq!(ranked[0].item.as_str(), \"zebra\");\n }\n \n #[test]\n fn top_bottom_splits_ends_without_overlap() {\n- let mut g = mk_group();\n- // Chain a > b > c > d > e > f so ranks are well separated.\n+ let mut scope = mk_scope();\n for (hi, lo) in [(\"a\", \"b\"), (\"b\", \"c\"), (\"c\", \"d\"), (\"d\", \"e\"), (\"e\", \"f\")] {\n- apply(&mut g, vote(1, hi, lo, 2, 1));\n+ apply(&mut scope, vote(1, hi, lo, 2, 1));\n }\n- let (top, bottom) = top_bottom(&g, 2);\n+ let (top, bottom) = top_bottom(&scope, 2);\n assert_eq!(top.len(), 2);\n assert_eq!(bottom.len(), 2);\n- // No overlap between the two ends.\n for t in &top {\n assert!(bottom.iter().all(|b| b.item != t.item));\n }\n- // Best item ranks above the worst item.\n assert!(top[0].score >= bottom[bottom.len() - 1].score);\n }\n \n #[test]\n fn top_bottom_small_group_has_empty_bottom() {\n- let mut g = mk_group();\n- apply(&mut g, vote(1, \"a\", \"b\", 2, 1));\n- let (top, bottom) = top_bottom(&g, 5);\n+ let mut scope = mk_scope();\n+ apply(&mut scope, vote(1, \"a\", \"b\", 2, 1));\n+ let (top, bottom) = top_bottom(&scope, 5);\n assert_eq!(top.len(), 2);\n assert!(bottom.is_empty());\n }\n \n #[test]\n fn connected_components_split_disconnected_pairs() {\n- let mut g = mk_group();\n- // Two disconnected edges: (a,b) and (c,d)\n- apply(&mut g, vote(1, \"a\", \"b\", 3, 1));\n- apply(&mut g, vote(2, \"c\", \"d\", 3, 1));\n-\n- let n = g.idx_to_item.len();\n- let (mut comps, isolates) =\n- connected_components_from_voted_pairs(n, g.voted_pairs.iter().copied());\n+ let mut scope = mk_scope();\n+ apply(&mut scope, vote(1, \"a\", \"b\", 3, 1));\n+ apply(&mut scope, vote(2, \"c\", \"d\", 3, 1));\n+\n+ let (_, idx_to_item) = item_index(&scope);\n+ let (mut comps, isolates, _) = scope_components(&scope);\n assert!(isolates.is_empty());\n- // Order-independent: sort components by their item names for stable assert.\n comps.sort_by_key(|c| {\n c.iter()\n- .map(|&i| g.idx_to_item[i].clone())\n+ .map(|&i| idx_to_item[i].clone())\n .collect::>()\n });\n assert_eq!(comps.len(), 2);\n- let comp0 = comps[0]\n- .iter()\n- .map(|&i| g.idx_to_item[i].as_str())\n- .collect::>();\n- let comp1 = comps[1]\n- .iter()\n- .map(|&i| g.idx_to_item[i].as_str())\n- .collect::>();\n- assert_eq!(comp0, vec![\"a\", \"b\"]);\n- assert_eq!(comp1, vec![\"c\", \"d\"]);\n }\n \n- /// A random spanning tree over 26 items needs only n−1 = 25 pairwise votes.\n- /// When each vote uses the \"perfect\" ratio (strength left : strength right =\n- /// (idx_left+1) : (idx_right+1)), rank centrality recovers the true order.\n- /// See `rank-eric.py` (Eric's demo of Negahban–Oh–Shah rank centrality).\n #[test]\n fn twenty_five_random_votes_perfect_ratios_sort_alphabet() {\n use rand::seq::SliceRandom;\n@@ -390,13 +403,13 @@ mod tests {\n let mut perm: Vec = (0..N).collect();\n perm.shuffle(&mut rng);\n \n- let mut g = mk_group();\n+ let mut scope = mk_scope();\n for k in 1..N {\n let i = *perm[..k].choose(&mut rng).unwrap();\n let j = perm[k];\n let (a, b) = (letters[i], letters[j]);\n apply(\n- &mut g,\n+ &mut scope,\n vote(\n k as i64,\n &a.to_string(),\n@@ -407,34 +420,25 @@ mod tests {\n );\n }\n \n- let ranked = ranked_items(&g);\n+ let ranked = ranked_items(&scope);\n assert_eq!(ranked.len(), N);\n for (rank, item) in ranked.iter().enumerate() {\n let expected = char::from(b'a' + (N - 1 - rank) as u8);\n- assert_eq!(\n- item.item.as_str(),\n- expected.to_string(),\n- \"rank {rank}: expected '{expected}', got '{}'\",\n- item.item.as_str()\n- );\n+ assert_eq!(item.item.as_str(), expected.to_string());\n }\n }\n \n #[test]\n fn subset_ranking_ranks_within_component_only() {\n- let mut g = mk_group();\n- apply(&mut g, vote(1, \"a\", \"b\", 3, 1)); // a > b\n- apply(&mut g, vote(2, \"c\", \"d\", 1, 4)); // d > c\n-\n- let (comps, _) = connected_components_from_voted_pairs(\n- g.idx_to_item.len(),\n- g.voted_pairs.iter().copied(),\n- );\n+ let mut scope = mk_scope();\n+ apply(&mut scope, vote(1, \"a\", \"b\", 3, 1));\n+ apply(&mut scope, vote(2, \"c\", \"d\", 1, 4));\n+\n+ let (comps, _, _) = scope_components(&scope);\n assert_eq!(comps.len(), 2);\n \n- // Rank each component and ensure winner is first within that component.\n for comp in comps {\n- let ranked = ranked_items_subset(&g, &comp, 10000, 1e-8);\n+ let ranked = ranked_items_subset(&scope, &comp, 10000, 1e-8);\n assert_eq!(ranked.len(), 2);\n let names = ranked.iter().map(|r| r.item.as_str()).collect::>();\n if names.contains(&\"a\") {\ndiff --git a/server/src/reducer.rs b/server/src/reducer.rs\nindex 8c4c9f83635cbcbb037d680dbae2aa99cb2dc785..e6d8c8d2fe763f4928cfbd7c300c8d9768968a3f 100644\n--- a/server/src/reducer.rs\n+++ b/server/src/reducer.rs\n@@ -4,6 +4,24 @@ use serde::{Deserialize, Serialize};\n \n use crate::path_types::ItemId;\n \n+/// `(actor_uuid, min_item_id, max_item_id)` — one vote slot per human per pair.\n+pub type UuidVoteKey = (String, String, String);\n+\n+pub fn canonical_pair_ids(a: &ItemId, b: &ItemId) -> (String, String) {\n+ let ak = a.as_str().to_string();\n+ let bk = b.as_str().to_string();\n+ if ak <= bk {\n+ (ak, bk)\n+ } else {\n+ (bk, ak)\n+ }\n+}\n+\n+pub fn uuid_vote_key(actor_uuid: &str, a: &ItemId, b: &ItemId) -> UuidVoteKey {\n+ let (lo, hi) = canonical_pair_ids(a, b);\n+ (actor_uuid.to_string(), lo, hi)\n+}\n+\n /// Parsed pairwise vote (internal representation).\n #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]\n pub struct VoteData {\n@@ -44,118 +62,20 @@ impl VoteData {\n }\n }\n \n+/// Votes cast within one ranking scope (parent node). Edges and rankings are\n+/// derived on demand from [`Self::uuid_votes`].\n #[derive(Debug, Clone, Default, Serialize, Deserialize)]\n-pub struct GroupState {\n- pub item_to_idx: HashMap,\n- pub idx_to_item: Vec,\n- pub edges: HashMap<(usize, usize), f64>,\n- pub voted_pairs: HashSet<(usize, usize)>,\n- /// Latest vote per `(actor_uuid, min_idx, max_idx)` — Sybil dedup anchor.\n- pub uuid_votes: HashMap<(String, usize, usize), VoteData>,\n+pub struct ScopeVotes {\n+ pub uuid_votes: HashMap,\n pub recent_votes: Vec,\n }\n \n-impl GroupState {\n- pub fn new() -> Self {\n- Self {\n- item_to_idx: HashMap::new(),\n- idx_to_item: Vec::new(),\n- edges: HashMap::new(),\n- voted_pairs: HashSet::new(),\n- uuid_votes: HashMap::new(),\n- recent_votes: Vec::new(),\n- }\n- }\n-\n- fn ensure_item(&mut self, item: &ItemId) -> usize {\n- if let Some(&idx) = self.item_to_idx.get(item) {\n- return idx;\n- }\n- let idx = self.idx_to_item.len();\n- self.idx_to_item.push(item.clone());\n- self.item_to_idx.insert(item.clone(), idx);\n- idx\n- }\n-\n- fn add_edge_weight(&mut self, src: usize, dst: usize, w: f64) {\n- if w <= 0.0 {\n- return;\n- }\n- *self.edges.entry((src, dst)).or_insert(0.0) += w;\n- }\n-\n- fn subtract_edge_weight(&mut self, src: usize, dst: usize, w: f64) {\n- if w <= 0.0 {\n- return;\n- }\n- if let Some(entry) = self.edges.get_mut(&(src, dst)) {\n- *entry -= w;\n- if *entry <= 0.0 {\n- self.edges.remove(&(src, dst));\n- }\n- }\n- }\n-\n- fn apply_weights(&mut self, vote: &VoteData, a_idx: usize, b_idx: usize) {\n- let w_a = vote.ratio_left as f64 * vote.trust_weight;\n- let w_b = vote.ratio_right as f64 * vote.trust_weight;\n- let (i, j) = if a_idx < b_idx {\n- (a_idx, b_idx)\n- } else {\n- (b_idx, a_idx)\n- };\n- self.voted_pairs.insert((i, j));\n- self.add_edge_weight(b_idx, a_idx, w_a);\n- self.add_edge_weight(a_idx, b_idx, w_b);\n- }\n-\n- fn rollback_weights(&mut self, vote: &VoteData) {\n- let a_idx = match self.item_to_idx.get(&vote.a) {\n- Some(&i) => i,\n- None => return,\n- };\n- let b_idx = match self.item_to_idx.get(&vote.b) {\n- Some(&i) => i,\n- None => return,\n- };\n- let w_a = vote.ratio_left as f64 * vote.trust_weight;\n- let w_b = vote.ratio_right as f64 * vote.trust_weight;\n- self.subtract_edge_weight(b_idx, a_idx, w_a);\n- self.subtract_edge_weight(a_idx, b_idx, w_b);\n- }\n-\n- /// Apply a validated vote, deduplicating by `actor_uuid` per unordered pair.\n+impl ScopeVotes {\n pub fn apply_vote(&mut self, vote: VoteData, actor_uuid: &str) {\n- let a_idx = self.ensure_item(&vote.a);\n- let b_idx = self.ensure_item(&vote.b);\n- let (i, j) = if a_idx < b_idx {\n- (a_idx, b_idx)\n- } else {\n- (b_idx, a_idx)\n- };\n-\n- let dedupe_key = (actor_uuid.to_string(), i, j);\n- if let Some(old) = self.uuid_votes.get(&dedupe_key).cloned() {\n- self.rollback_weights(&old);\n- }\n-\n- self.apply_weights(&vote, a_idx, b_idx);\n- self.uuid_votes.insert(dedupe_key, vote.clone());\n+ let key = uuid_vote_key(actor_uuid, &vote.a, &vote.b);\n+ self.uuid_votes.insert(key, vote.clone());\n self.recent_votes.push(vote);\n }\n-\n- /// Rebuild edge weights from deduped uuid votes (load path — no rollback).\n- pub fn ingest_uuid_vote(&mut self, vote: VoteData, actor_uuid: &str) {\n- let a_idx = self.ensure_item(&vote.a);\n- let b_idx = self.ensure_item(&vote.b);\n- let (i, j) = if a_idx < b_idx {\n- (a_idx, b_idx)\n- } else {\n- (b_idx, a_idx)\n- };\n- self.apply_weights(&vote, a_idx, b_idx);\n- self.uuid_votes.insert((actor_uuid.to_string(), i, j), vote);\n- }\n }\n \n /// Structured data imported from Reddit or elsewhere.\n@@ -179,7 +99,7 @@ pub struct NodeState {\n /// Ephemeral display view (Reddit title/author/etc.; not event-logged).\n pub data: Option,\n pub children: HashSet,\n- pub local_ranking: GroupState,\n+ pub votes: ScopeVotes,\n }\n \n impl NodeState {\n@@ -242,7 +162,7 @@ impl GlobalTree {\n if let Some(node) = self.nodes.get_mut(parent) {\n node.children.insert(vote.a.clone());\n node.children.insert(vote.b.clone());\n- node.local_ranking.apply_vote(vote, actor_uuid);\n+ node.votes.apply_vote(vote, actor_uuid);\n }\n }\n \n@@ -276,6 +196,7 @@ impl GlobalTree {\n #[cfg(test)]\n mod tests {\n use super::*;\n+ use crate::ranking::edge_weight_sum;\n \n fn vote(ts: i64, a: &str, b: &str, l: i32, r: i32, pseudonym: &str) -> VoteData {\n VoteData {\n@@ -310,26 +231,23 @@ mod tests {\n \n #[test]\n fn same_uuid_replaces_prior_vote_on_pair() {\n- let mut g = GroupState::new();\n+ let mut scope = ScopeVotes::default();\n let uuid = \"u1\";\n- g.apply_vote(vote(1, \"a\", \"b\", 2, 1, \"alice\"), uuid);\n- let first_total: f64 = g.edges.values().sum();\n- assert_eq!(first_total, 3.0);\n+ scope.apply_vote(vote(1, \"a\", \"b\", 2, 1, \"alice\"), uuid);\n+ assert_eq!(edge_weight_sum(&scope), 3.0);\n \n- g.apply_vote(vote(2, \"a\", \"b\", 0, 1, \"bob\"), uuid);\n- let second_total: f64 = g.edges.values().sum();\n- assert_eq!(second_total, 1.0);\n- assert_eq!(g.uuid_votes.len(), 1);\n+ scope.apply_vote(vote(2, \"a\", \"b\", 0, 1, \"bob\"), uuid);\n+ assert_eq!(edge_weight_sum(&scope), 1.0);\n+ assert_eq!(scope.uuid_votes.len(), 1);\n }\n \n #[test]\n fn different_uuids_both_count() {\n- let mut g = GroupState::new();\n- g.apply_vote(vote(1, \"a\", \"b\", 2, 1, \"alice\"), \"u1\");\n- g.apply_vote(vote(2, \"a\", \"b\", 0, 1, \"bob\"), \"u2\");\n- let total: f64 = g.edges.values().sum();\n- assert_eq!(total, 4.0);\n- assert_eq!(g.uuid_votes.len(), 2);\n+ let mut scope = ScopeVotes::default();\n+ scope.apply_vote(vote(1, \"a\", \"b\", 2, 1, \"alice\"), \"u1\");\n+ scope.apply_vote(vote(2, \"a\", \"b\", 0, 1, \"bob\"), \"u2\");\n+ assert_eq!(edge_weight_sum(&scope), 4.0);\n+ assert_eq!(scope.uuid_votes.len(), 2);\n }\n \n #[test]\ndiff --git a/server/src/state.rs b/server/src/state.rs\nindex 8dabc93e95c39cbe18d69596dee79683b384ef86..dcb82ff4beeaac8f0820de0e0131ca1f6bd81dcc 100644\n--- a/server/src/state.rs\n+++ b/server/src/state.rs\n@@ -269,7 +269,7 @@ mod tests {\n use super::{normalize_scope, parse_item_param, AppConfig, AppState};\n use crate::{\n event_log::EventLog, events::Event, path_types::ItemId, projection_apply,\n- projection_store::ProjectionStore, reducer::EntityData,\n+ projection_store::ProjectionStore, ranking::edge_weight_sum, reducer::EntityData,\n };\n \n fn event_record(seq: u64, event: Event) -> crate::events::EventRecord {\n@@ -442,7 +442,7 @@ mod tests {\n assert_eq!(projection_store.last_applied_event_count().unwrap(), 1);\n let first = projection_store.scope_tree(&ItemId::root()).unwrap();\n let first_root = first.get(&ItemId::root()).unwrap();\n- let first_edge_total: f64 = first_root.local_ranking.edges.values().sum();\n+ let first_edge_total = edge_weight_sum(&first_root.votes);\n assert_eq!(first_edge_total, 3.0);\n \n super::catch_up_projection(&log, &projection_store)\n@@ -451,7 +451,7 @@ mod tests {\n assert_eq!(projection_store.last_applied_event_count().unwrap(), 1);\n let second = projection_store.scope_tree(&ItemId::root()).unwrap();\n let second_root = second.get(&ItemId::root()).unwrap();\n- let second_edge_total: f64 = second_root.local_ranking.edges.values().sum();\n+ let second_edge_total = edge_weight_sum(&second_root.votes);\n assert_eq!(second_edge_total, first_edge_total);\n }\n \n@@ -529,9 +529,8 @@ mod tests {\n let root = projected.get(&ItemId::root()).unwrap();\n assert!(root.children.contains(&ItemId::parse(\"alpha\").unwrap()));\n assert!(root.children.contains(&ItemId::parse(\"beta\").unwrap()));\n- assert_eq!(root.local_ranking.idx_to_item.len(), 2);\n- let edge_total: f64 = root.local_ranking.edges.values().sum();\n- assert_eq!(edge_total, 3.0);\n+ assert_eq!(crate::ranking::ranked_items(&root.votes).len(), 2);\n+ assert_eq!(edge_weight_sum(&root.votes), 3.0);\n }\n \n #[tokio::test]\n@@ -620,7 +619,7 @@ mod tests {\n let root = tree.get(&ItemId::root()).unwrap();\n assert!(root.children.contains(&ItemId::parse(\"beta\").unwrap()));\n assert!(root.children.contains(&ItemId::parse(\"gamma\").unwrap()));\n- assert_eq!(root.local_ranking.idx_to_item.len(), 3);\n+ assert_eq!(crate::ranking::ranked_items(&root.votes).len(), 3);\n }\n \n #[test]\ndiff --git a/server/src/storage_schema.rs b/server/src/storage_schema.rs\nindex 67c9f4ab2e1865f8da81b6735dd2a05b87e5e366..fe2671b876f3df77fdfd402dbc845ff1eb3512cd 100644\n--- a/server/src/storage_schema.rs\n+++ b/server/src/storage_schema.rs\n@@ -3,86 +3,53 @@\n //!\n //! Votes are stored as deduped `uuid_votes` entries plus an append-only\n //! `recent_votes` audit list. Edge weights for rank centrality are derived\n-//! from `uuid_votes` on read, not incrementally merged in RocksDB.\n+//! from `uuid_votes` on read, not stored in RocksDB.\n \n-use std::collections::{HashSet};\n+use std::collections::HashSet;\n \n use durable::{Batch, Db, Durable, Leaf, List, Map};\n \n use crate::{\n path_types::ItemId,\n- reducer::{EntityData, GroupState, NodeState, VoteData},\n+ reducer::{EntityData, NodeState, ScopeVotes, VoteData, UuidVoteKey, uuid_vote_key},\n storage_dto::{\n decode_entity_data, decode_vote, encode_entity_data, encode_vote, parse_stored_id,\n StoredEntityDataV1, StoredVoteV1,\n },\n };\n \n-/// `(actor_uuid, min_item_id, max_item_id)` — one vote slot per human per pair.\n-pub type UuidVoteKey = (String, String, String);\n-\n /// One node in the fractal tree, exploded into precisely-updatable collections.\n #[derive(Durable)]\n #[allow(dead_code)]\n pub struct NodeSchema {\n- /// Presence marker (a node \"exists\" once ensured/voted/imported).\n pub present: Leaf,\n- /// Domain-specific derived view (Reddit title/author/…); absent => None.\n pub data: Leaf,\n- /// Child ids (a set; value is always `true`).\n pub children: Map>,\n- /// Latest vote per actor per unordered pair; edges are derived from this on read.\n pub uuid_votes: Map>,\n- /// Recent votes, append-only oldest-first (cap applied on read).\n pub recent_votes: List>,\n- /// When ephemeral Reddit display content was last fetched (ms); absent after eviction.\n pub fetched_at: Leaf,\n }\n \n-/// The single database root: nodes, identity maps, view counts, and metadata.\n #[derive(Durable)]\n #[allow(dead_code)]\n pub struct Store {\n pub nodes: Map,\n- /// Global pseudonym → actor UUID (Sybil dedup anchor).\n pub pseudonyms: Map>,\n pub proj_meta: Map>,\n pub view_counts: Map>,\n pub view_meta: Map>,\n }\n \n-/// Max recent votes returned when loading a node (query-time cap only).\n pub const RECENT_VOTES_CAP: u64 = 200;\n \n fn id_key(id: &ItemId) -> String {\n id.as_str().to_string()\n }\n \n-fn pair_keys(a: &ItemId, b: &ItemId) -> (String, String) {\n- let ak = id_key(a);\n- let bk = id_key(b);\n- if ak <= bk {\n- (ak, bk)\n- } else {\n- (bk, ak)\n- }\n-}\n-\n-pub fn uuid_vote_key(actor_uuid: &str, a: &ItemId, b: &ItemId) -> UuidVoteKey {\n- let (lo, hi) = pair_keys(a, b);\n- (actor_uuid.to_string(), lo, hi)\n-}\n-\n-/// Path to a node by id.\n pub fn node(id: &ItemId) -> durable::Path {\n Store::root().nodes().key(&id_key(id))\n }\n \n-// ---------------------------------------------------------------------------\n-// Reconstruction (durable -> in-memory)\n-// ---------------------------------------------------------------------------\n-\n-/// Reconstruct a node's in-memory state, or `None` if the node does not exist.\n pub fn load_node_state(db: &Db, id: &ItemId) -> durable::Result> {\n let np = node(id);\n let present = np.present().get(db)?.unwrap_or(false);\n@@ -100,47 +67,39 @@ pub fn load_node_state(db: &Db, id: &ItemId) -> durable::Result) -> durable::Result {\n- let mut group = GroupState::new();\n+fn load_scope_votes(db: &Db, np: &durable::Path) -> durable::Result {\n+ let mut votes = ScopeVotes::default();\n \n for (key, stored) in np.uuid_votes().iter(db)? {\n- let (actor_uuid, _lo, _hi) = key;\n let vote = decode_vote(stored).map_err(durable::Error::Deserialize)?;\n- group.ingest_uuid_vote(vote, &actor_uuid);\n+ votes.uuid_votes.insert(key, vote);\n }\n \n let stored = np.recent_votes().iter(db)?;\n let cap = RECENT_VOTES_CAP as usize;\n let start = stored.len().saturating_sub(cap);\n- group.recent_votes = stored[start..]\n+ votes.recent_votes = stored[start..]\n .iter()\n .map(|s| decode_vote(s.clone()).map_err(durable::Error::Deserialize))\n .collect::, _>>()?;\n \n- Ok(group)\n+ Ok(votes)\n }\n \n fn parse_storage_id(s: &str) -> durable::Result {\n parse_stored_id(s).map_err(durable::Error::Deserialize)\n }\n \n-// ---------------------------------------------------------------------------\n-// Write helpers (event -> reified point updates on a batch)\n-// ---------------------------------------------------------------------------\n-\n-/// Wire a node and its ancestors into the tree exactly like\n-/// [`crate::reducer::GlobalTree::ensure_path`]: set presence and parent→child\n-/// links along the canonical breadcrumb path.\n pub fn ensure_path_writes(batch: &mut Batch, id: &ItemId) {\n let root = ItemId::root();\n batch.write(node(&root).present().set(&true));\n@@ -161,7 +120,6 @@ pub fn ensure_path_writes(batch: &mut Batch, id: &ItemId) {\n }\n }\n \n-/// Reified writes for a validated vote under `parent`.\n pub fn vote_writes(\n batch: &mut Batch,\n parent: &ItemId,\n@@ -182,14 +140,12 @@ pub fn vote_writes(\n Ok(())\n }\n \n-/// Reified writes for ephemeral Reddit display content (not event-logged).\n pub fn entity_content_writes(batch: &mut Batch, id: &ItemId, view: &EntityData, fetched_at: i64) {\n ensure_path_writes(batch, id);\n batch.write(node(id).data().set(&encode_entity_data(view)));\n batch.write(node(id).fetched_at().set(&fetched_at));\n }\n \n-/// Clear cached display content for one node (structure/votes are untouched).\n pub fn entity_content_clear_writes(batch: &mut Batch, id: &ItemId) {\n batch.write(node(id).data().delete());\n batch.write(node(id).fetched_at().delete());\n@@ -199,6 +155,7 @@ pub fn entity_content_clear_writes(batch: &mut Batch, id: &ItemId) {\n mod tests {\n use super::*;\n use crate::identity::{seed_default_pseudonym, DEFAULT_ACTOR_UUID, DEFAULT_PSEUDONYM};\n+ use crate::ranking::edge_weight_sum;\n \n fn sample_vote(ts: i64, a: &str, b: &str, l: i32, r: i32) -> VoteData {\n VoteData {\n@@ -213,7 +170,7 @@ mod tests {\n }\n \n #[test]\n- fn vote_roundtrip_reconstructs_group_state() {\n+ fn vote_roundtrip_reconstructs_ranking() {\n let dir = tempfile::tempdir().unwrap();\n let db = Db::open(dir.path()).unwrap();\n seed_default_pseudonym(&db).unwrap();\n@@ -225,11 +182,8 @@ mod tests {\n batch.commit().unwrap();\n \n let node_state = load_node_state(&db, &parent).unwrap().unwrap();\n- let g = &node_state.local_ranking;\n- assert_eq!(g.idx_to_item.len(), 2);\n- let edge_total: f64 = g.edges.values().sum();\n- assert_eq!(edge_total, 3.0);\n- assert_eq!(g.recent_votes.len(), 1);\n+ assert_eq!(edge_weight_sum(&node_state.votes), 3.0);\n+ assert_eq!(node_state.votes.recent_votes.len(), 1);\n assert!(node_state.children.contains(&ItemId::opaque(\"alpha\")));\n assert!(node_state.children.contains(&ItemId::opaque(\"beta\")));\n }\n@@ -263,10 +217,9 @@ mod tests {\n .unwrap();\n batch.commit().unwrap();\n \n- let g = &load_node_state(&db, &parent).unwrap().unwrap().local_ranking;\n- let edge_total: f64 = g.edges.values().sum();\n- assert_eq!(edge_total, 1.0);\n- assert_eq!(g.uuid_votes.len(), 1);\n+ let votes = &load_node_state(&db, &parent).unwrap().unwrap().votes;\n+ assert_eq!(edge_weight_sum(votes), 1.0);\n+ assert_eq!(votes.uuid_votes.len(), 1);\n }\n \n #[test]\n@@ -293,15 +246,8 @@ mod tests {\n );\n \n let node_state = load_node_state(&db, &parent).unwrap().unwrap();\n- assert_eq!(node_state.local_ranking.recent_votes.len(), RECENT_VOTES_CAP as usize);\n- assert_eq!(\n- node_state\n- .local_ranking\n- .recent_votes\n- .first()\n- .map(|v| v.ts),\n- Some(10)\n- );\n+ assert_eq!(node_state.votes.recent_votes.len(), RECENT_VOTES_CAP as usize);\n+ assert_eq!(node_state.votes.recent_votes.first().map(|v| v.ts), Some(10));\n }\n \n #[test]\ndiff --git a/server/tests/integration_ui.rs b/server/tests/integration_ui.rs\nindex cc7a16d756673b95ba336f2d6130eaf40908cc60..40e4cfe1eec36dad29a075fb01aefb4dffd856d0 100644\n--- a/server/tests/integration_ui.rs\n+++ b/server/tests/integration_ui.rs\n@@ -132,7 +132,7 @@ async fn post_ui_record_vote_morphs_ranking_and_persists() {\n let state = create_app_state(cfg).await;\n let tree = state.scope_tree(&ItemId::root()).unwrap();\n let root = tree.get(&ItemId::root()).expect(\"root node after replay\");\n- let ranked = sorter2_server::ranking::ranked_items(&root.local_ranking);\n+ let ranked = sorter2_server::ranking::ranked_items(&root.votes);\n assert_eq!(ranked.len(), 2);\n assert_eq!(ranked[0].item.as_str(), \"alpha\");\n }\n\n\nSide B — contributor: tommy-mor\nSide B — commit message:\n[15e1037a] url stuff\n\nSide B — unified diff (full patch):\ndiff --git a/server/src/url_rules/graph.rs b/server/src/url_rules/graph.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..f7ac0f9a551a1727cb2f9294778c283b9885b147\n--- /dev/null\n+++ b/server/src/url_rules/graph.rs\n@@ -0,0 +1,831 @@\n+//! Semantic URL graph: DFA traversal on host + path, query in context, generic fallback.\n+\n+use std::collections::HashMap;\n+use std::sync::OnceLock;\n+\n+use url::Url;\n+\n+use super::graph_builder::GraphBuilder;\n+use super::parse::{normalize_match_host, strip_tracking_query, UrlParts};\n+\n+#[derive(Debug, Clone, Default)]\n+pub struct Context {\n+ pub vars: HashMap,\n+ pub query: HashMap,\n+}\n+\n+pub type CanonicalFn = fn(&Context) -> Option;\n+\n+#[derive(Clone, Copy)]\n+pub enum EdgePattern {\n+ Literal(&'static str),\n+ Variable(&'static str),\n+ /// Absorb any trailing segment without leaving this node (e.g. post title slug).\n+ AbsorbAny,\n+ /// Absorb segment when `cond(seg)` (e.g. subreddit listing suffix).\n+ AbsorbIf(fn(&str) -> bool),\n+}\n+\n+pub struct Edge {\n+ pub pattern: EdgePattern,\n+ pub target: &'static str,\n+}\n+\n+pub struct Node {\n+ pub edges: Vec,\n+ pub canonical: CanonicalFn,\n+ pub parent: Option<&'static str>,\n+}\n+\n+impl Node {\n+ pub(crate) fn empty() -> Self {\n+ Self {\n+ edges: Vec::new(),\n+ canonical: |_| None,\n+ parent: None,\n+ }\n+ }\n+}\n+\n+pub struct Graph {\n+ pub nodes: HashMap<&'static str, Node>,\n+}\n+\n+static GRAPH: OnceLock = OnceLock::new();\n+\n+pub fn graph() -> &'static Graph {\n+ GRAPH.get_or_init(build_graph)\n+}\n+\n+impl Graph {\n+ pub fn resolve_canonical(&self, parts: &UrlParts) -> Option {\n+ let mut query = parts.query.clone();\n+ strip_tracking_query(&mut query);\n+ let mut ctx = Context {\n+ vars: HashMap::new(),\n+ query,\n+ };\n+\n+ if let Some(node_id) = self.traverse(parts, &mut ctx) {\n+ if let Some(canon) = (self.nodes.get(node_id)?.canonical)(&ctx) {\n+ return Some(canon);\n+ }\n+ }\n+ Some(generic_canonical(parts))\n+ }\n+\n+ pub fn breadcrumbs(&self, parts: &UrlParts) -> Vec {\n+ let mut query = parts.query.clone();\n+ strip_tracking_query(&mut query);\n+ let mut ctx = Context {\n+ vars: HashMap::new(),\n+ query,\n+ };\n+\n+ if let Some(mut node_id) = self.traverse(parts, &mut ctx) {\n+ let mut paths = Vec::new();\n+ loop {\n+ let node = match self.nodes.get(node_id) {\n+ Some(n) => n,\n+ None => break,\n+ };\n+ if let Some(url) = (node.canonical)(&ctx) {\n+ if paths.last() != Some(&url) {\n+ paths.push(url);\n+ }\n+ }\n+ match node.parent {\n+ Some(p) => node_id = p,\n+ None => break,\n+ }\n+ }\n+ paths.reverse();\n+ if !paths.is_empty() {\n+ return paths;\n+ }\n+ }\n+ generic_breadcrumbs(parts)\n+ }\n+\n+ fn traverse(&self, parts: &UrlParts, ctx: &mut Context) -> Option<&'static str> {\n+ let host = parts.match_host();\n+ let mut node_id = match host.as_str() {\n+ \"reddit.com\" => \"reddit_root\",\n+ \"youtube.com\" => \"youtube_root\",\n+ \"youtu.be\" => \"youtu_be_entry\",\n+ _ => return None,\n+ };\n+\n+ let segs: Vec<&str> = parts.path_segments.iter().map(String::as_str).collect();\n+ let mut i = 0;\n+ while i < segs.len() {\n+ let seg = segs[i];\n+ match self.follow_edge(node_id, seg, ctx) {\n+ Ok(next) => {\n+ node_id = next;\n+ i += 1;\n+ }\n+ Err(()) => {\n+ if self.try_absorb(node_id, seg) {\n+ i += 1;\n+ continue;\n+ }\n+ return None;\n+ }\n+ }\n+ }\n+ Some(node_id)\n+ }\n+\n+ fn follow_edge(\n+ &self,\n+ node_id: &'static str,\n+ seg: &str,\n+ ctx: &mut Context,\n+ ) -> Result<&'static str, ()> {\n+ let node = self.nodes.get(node_id).ok_or(())?;\n+ for edge in &node.edges {\n+ match edge.pattern {\n+ EdgePattern::Literal(lit) if lit == seg => return Ok(edge.target),\n+ EdgePattern::Variable(name) => {\n+ ctx.vars.insert(name.to_string(), seg.to_string());\n+ return Ok(edge.target);\n+ }\n+ EdgePattern::AbsorbAny\n+ | EdgePattern::AbsorbIf(_)\n+ | EdgePattern::Literal(_)\n+ | EdgePattern::Variable(_) => {}\n+ }\n+ }\n+ Err(())\n+ }\n+\n+ fn try_absorb(&self, node_id: &'static str, seg: &str) -> bool {\n+ let node = match self.nodes.get(node_id) {\n+ Some(n) => n,\n+ None => return false,\n+ };\n+ for edge in &node.edges {\n+ match edge.pattern {\n+ EdgePattern::AbsorbAny => return true,\n+ EdgePattern::AbsorbIf(cond) if cond(seg) => return true,\n+ EdgePattern::AbsorbIf(_) | EdgePattern::Literal(_) | EdgePattern::Variable(_) => {}\n+ }\n+ }\n+ false\n+ }\n+\n+ /// Test hook: terminal graph node and captured context after traversal.\n+ #[cfg(test)]\n+ pub fn traverse_terminal(&self, parts: &UrlParts) -> Option<(&'static str, Context)> {\n+ let mut query = parts.query.clone();\n+ strip_tracking_query(&mut query);\n+ let mut ctx = Context {\n+ vars: HashMap::new(),\n+ query,\n+ };\n+ let node = self.traverse(parts, &mut ctx)?;\n+ Some((node, ctx))\n+ }\n+}\n+\n+fn is_reddit_listing_suffix(seg: &str) -> bool {\n+ matches!(seg, \"hot\" | \"top\" | \"new\" | \"rising\" | \"controversial\")\n+}\n+\n+/// Percent-encode a path or query fragment so `&`, `?`, etc. cannot break URL structure.\n+fn enc(s: &str) -> String {\n+ urlencoding::encode(s).into_owned()\n+}\n+\n+// --- Canonical formatters ---\n+\n+fn canon_reddit_root(_: &Context) -> Option {\n+ Some(\"https://reddit.com\".to_string())\n+}\n+\n+fn canon_reddit_r_hub(_: &Context) -> Option {\n+ Some(\"https://reddit.com/r\".to_string())\n+}\n+\n+fn canon_reddit_subreddit(ctx: &Context) -> Option {\n+ let sub = ctx.vars.get(\"subreddit\")?;\n+ Some(format!(\n+ \"https://reddit.com/r/{}\",\n+ enc(&sub.to_ascii_lowercase())\n+ ))\n+}\n+\n+fn canon_reddit_post(ctx: &Context) -> Option {\n+ let sub = ctx.vars.get(\"subreddit\")?.to_ascii_lowercase();\n+ let id = ctx.vars.get(\"post_id\")?;\n+ Some(format!(\n+ \"https://reddit.com/r/{}/comments/{}\",\n+ enc(&sub),\n+ enc(id)\n+ ))\n+}\n+\n+fn canon_youtube_root(_: &Context) -> Option {\n+ Some(\"https://youtube.com\".to_string())\n+}\n+\n+fn canon_youtube_watch(ctx: &Context) -> Option {\n+ let v = ctx\n+ .query\n+ .get(\"v\")\n+ .or_else(|| ctx.vars.get(\"video_id\"))?;\n+ Some(format!(\"https://youtube.com/watch?v={}\", enc(v)))\n+}\n+\n+fn canon_youtu_be(ctx: &Context) -> Option {\n+ let v = ctx.vars.get(\"vid_id\")?;\n+ Some(format!(\"https://youtube.com/watch?v={}\", enc(v)))\n+}\n+\n+pub fn build_graph() -> Graph {\n+ GraphBuilder::new()\n+ .node(\"reddit_root\")\n+ .canonical(canon_reddit_root)\n+ .edge(EdgePattern::Literal(\"r\"), \"reddit_r_hub\")\n+ .node(\"reddit_r_hub\")\n+ .parent(\"reddit_root\")\n+ .canonical(canon_reddit_r_hub)\n+ .edge(EdgePattern::Variable(\"subreddit\"), \"reddit_subreddit\")\n+ .node(\"reddit_subreddit\")\n+ .parent(\"reddit_r_hub\")\n+ .canonical(canon_reddit_subreddit)\n+ .edge(\n+ EdgePattern::AbsorbIf(is_reddit_listing_suffix),\n+ \"reddit_subreddit\",\n+ )\n+ .edge(EdgePattern::Literal(\"comments\"), \"reddit_comments_gate\")\n+ .node(\"reddit_comments_gate\")\n+ .parent(\"reddit_subreddit\")\n+ .canonical(canon_reddit_subreddit)\n+ .edge(EdgePattern::Variable(\"post_id\"), \"reddit_post\")\n+ .node(\"reddit_post\")\n+ .parent(\"reddit_subreddit\")\n+ .canonical(canon_reddit_post)\n+ .edge(EdgePattern::AbsorbAny, \"reddit_post\")\n+ .node(\"youtube_root\")\n+ .canonical(canon_youtube_root)\n+ .edge(EdgePattern::Literal(\"watch\"), \"youtube_watch\")\n+ .edge(EdgePattern::Literal(\"shorts\"), \"youtube_shorts_gate\")\n+ .node(\"youtube_watch\")\n+ .parent(\"youtube_root\")\n+ .canonical(canon_youtube_watch)\n+ .node(\"youtube_shorts_gate\")\n+ .parent(\"youtube_root\")\n+ .canonical(canon_youtube_root)\n+ .edge(EdgePattern::Variable(\"video_id\"), \"youtube_watch\")\n+ .node(\"youtu_be_entry\")\n+ .canonical(canon_youtube_root)\n+ .edge(EdgePattern::Variable(\"vid_id\"), \"youtu_be_video\")\n+ .node(\"youtu_be_video\")\n+ .parent(\"youtube_root\")\n+ .canonical(canon_youtu_be)\n+ .build()\n+}\n+\n+// --- Generic internet fallback ---\n+\n+pub fn generic_canonical(parts: &UrlParts) -> String {\n+ let host = normalize_match_host(&parts.host);\n+ let path_segments: Vec = parts.path_segments.clone();\n+ let mut query = parts.query.clone();\n+ strip_tracking_query(&mut query);\n+\n+ let mut url = if path_segments.is_empty() {\n+ Url::parse(&format!(\"https://{host}\"))\n+ .unwrap_or_else(|_| Url::parse(\"https://invalid\").unwrap())\n+ } else {\n+ let path = format!(\"/{}\", path_segments.join(\"/\"));\n+ Url::parse(&format!(\"https://{host}{path}\"))\n+ .unwrap_or_else(|_| Url::parse(\"https://invalid\").unwrap())\n+ };\n+\n+ if !query.is_empty() {\n+ let mut pairs: Vec<_> = query.iter().collect();\n+ pairs.sort_by(|a, b| a.0.cmp(b.0));\n+ url.query_pairs_mut().clear();\n+ for (k, v) in pairs {\n+ url.query_pairs_mut().append_pair(k, v);\n+ }\n+ }\n+\n+ let mut s = url.to_string();\n+ if path_segments.is_empty() {\n+ s = s.trim_end_matches('/').to_string();\n+ }\n+ s\n+}\n+\n+pub fn generic_breadcrumbs(parts: &UrlParts) -> Vec {\n+ let host = normalize_match_host(&parts.host);\n+ let n = parts.path_segments.len();\n+ let mut out = Vec::new();\n+\n+ let base = generic_canonical(&UrlParts {\n+ scheme: \"https\".to_string(),\n+ host: host.clone(),\n+ path_segments: vec![],\n+ query: HashMap::new(),\n+ });\n+ out.push(base);\n+\n+ for i in 0..n {\n+ let segs: Vec = parts.path_segments[..=i].to_vec();\n+ let url = generic_canonical(&UrlParts {\n+ scheme: \"https\".to_string(),\n+ host: host.clone(),\n+ path_segments: segs,\n+ query: HashMap::new(),\n+ });\n+ if out.last() != Some(&url) {\n+ out.push(url);\n+ }\n+ }\n+ out\n+}\n+\n+#[cfg(test)]\n+mod tests {\n+ use super::*;\n+ use crate::url_rules::parse::test_parts;\n+\n+ fn g() -> &'static Graph {\n+ graph()\n+ }\n+\n+ fn canon(parts: &UrlParts) -> String {\n+ g().resolve_canonical(parts).unwrap()\n+ }\n+\n+ fn crumbs(parts: &UrlParts) -> Vec {\n+ g().breadcrumbs(parts)\n+ }\n+\n+ fn terminal(parts: &UrlParts) -> Option<&'static str> {\n+ g().traverse_terminal(parts).map(|(n, _)| n)\n+ }\n+\n+ fn vars(parts: &UrlParts) -> HashMap {\n+ g().traverse_terminal(parts)\n+ .map(|(_, c)| c.vars)\n+ .unwrap_or_default()\n+ }\n+\n+ #[test]\n+ fn youtu_be_malicious_segment_encoded_not_injected() {\n+ let p = test_parts(\"youtu.be\", &[\"abc&t=1\"], &[]);\n+ assert_eq!(canon(&p), \"https://youtube.com/watch?v=abc%26t%3D1\");\n+ assert!(!canon(&p).contains(\"abc&t=1\"));\n+ }\n+\n+ #[test]\n+ fn youtube_query_v_encoded() {\n+ let p = test_parts(\"youtube.com\", &[\"watch\"], &[(\"v\", \"a&b=c\")]);\n+ assert_eq!(canon(&p), \"https://youtube.com/watch?v=a%26b%3Dc\");\n+ }\n+\n+ #[test]\n+ fn absorb_patterns_live_on_edges_not_in_engine() {\n+ let g = build_graph();\n+ let sub = g.nodes.get(\"reddit_subreddit\").unwrap();\n+ assert!(sub\n+ .edges\n+ .iter()\n+ .any(|e| matches!(e.pattern, EdgePattern::AbsorbIf(_))));\n+ let post = g.nodes.get(\"reddit_post\").unwrap();\n+ assert!(post\n+ .edges\n+ .iter()\n+ .any(|e| matches!(e.pattern, EdgePattern::AbsorbAny)));\n+ }\n+\n+ #[test]\n+ fn builder_rejects_missing_parent() {\n+ let result = std::panic::catch_unwind(|| {\n+ GraphBuilder::new()\n+ .node(\"orphan\")\n+ .parent(\"nonexistent_parent\")\n+ .build();\n+ });\n+ assert!(result.is_err());\n+ }\n+\n+ #[test]\n+ fn generic_canonical_forces_https_and_strips_www() {\n+ let p = test_parts(\"www.example.com\", &[\"blog\", \"post\"], &[]);\n+ assert_eq!(canon(&p), \"https://example.com/blog/post\");\n+ }\n+\n+ #[test]\n+ fn generic_canonical_sorts_query_keys() {\n+ let p = test_parts(\"example.com\", &[\"search\"], &[(\"q\", \"rust\"), (\"page\", \"2\")]);\n+ assert_eq!(canon(&p), \"https://example.com/search?page=2&q=rust\");\n+ }\n+\n+ #[test]\n+ fn generic_canonical_strips_tracking_from_query() {\n+ let p = test_parts(\n+ \"news.ycombinator.com\",\n+ &[\"item\"],\n+ &[(\"id\", \"1\"), (\"utm_medium\", \"social\")],\n+ );\n+ assert_eq!(canon(&p), \"https://news.ycombinator.com/item?id=1\");\n+ }\n+\n+ #[test]\n+ fn generic_breadcrumbs_cumulative_path() {\n+ let p = test_parts(\"paulgraham.com\", &[\"articles\", \"lisp.html\"], &[]);\n+ assert_eq!(\n+ crumbs(&p),\n+ vec![\n+ \"https://paulgraham.com\",\n+ \"https://paulgraham.com/articles\",\n+ \"https://paulgraham.com/articles/lisp.html\"\n+ ]\n+ );\n+ }\n+\n+ #[test]\n+ fn generic_breadcrumbs_domain_only() {\n+ let p = test_parts(\"example.com\", &[], &[]);\n+ assert_eq!(crumbs(&p), vec![\"https://example.com\"]);\n+ }\n+\n+ #[test]\n+ fn unknown_host_uses_generic_not_graph() {\n+ let p = test_parts(\"hackernews.com\", &[\"item\", \"123\"], &[]);\n+ assert_eq!(terminal(&p), None);\n+ assert_eq!(canon(&p), \"https://hackernews.com/item/123\");\n+ }\n+\n+ #[test]\n+ fn traverse_captures_subreddit_variable() {\n+ let p = test_parts(\"reddit.com\", &[\"r\", \"Rust\"], &[]);\n+ assert_eq!(terminal(&p), Some(\"reddit_subreddit\"));\n+ assert_eq!(vars(&p).get(\"subreddit\").map(String::as_str), Some(\"Rust\"));\n+ }\n+\n+ #[test]\n+ fn traverse_captures_post_id() {\n+ let p = test_parts(\"reddit.com\", &[\"r\", \"aww\", \"comments\", \"abc123\"], &[]);\n+ assert_eq!(terminal(&p), Some(\"reddit_post\"));\n+ assert_eq!(vars(&p).get(\"post_id\").map(String::as_str), Some(\"abc123\"));\n+ }\n+\n+ #[test]\n+ fn traverse_absorbs_listing_suffix_stays_on_subreddit() {\n+ let p = test_parts(\"reddit.com\", &[\"r\", \"rust\", \"hot\"], &[]);\n+ assert_eq!(terminal(&p), Some(\"reddit_subreddit\"));\n+ assert_eq!(canon(&p), \"https://reddit.com/r/rust\");\n+ }\n+\n+ #[test]\n+ fn traverse_absorbs_all_listing_suffixes() {\n+ for suffix in [\"hot\", \"top\", \"new\", \"rising\", \"controversial\"] {\n+ let p = test_parts(\"reddit.com\", &[\"r\", \"test\", suffix], &[]);\n+ assert_eq!(terminal(&p), Some(\"reddit_subreddit\"), \"suffix {suffix}\");\n+ assert_eq!(canon(&p), \"https://reddit.com/r/test\", \"suffix {suffix}\");\n+ }\n+ }\n+\n+ #[test]\n+ fn traverse_absorbs_post_title_slug() {\n+ let p = test_parts(\n+ \"reddit.com\",\n+ &[\"r\", \"rust\", \"comments\", \"aaa\", \"my_great_post_title\"],\n+ &[],\n+ );\n+ assert_eq!(terminal(&p), Some(\"reddit_post\"));\n+ assert_eq!(canon(&p), \"https://reddit.com/r/rust/comments/aaa\");\n+ }\n+\n+ #[test]\n+ fn traverse_unknown_segment_falls_back_to_generic() {\n+ let p = test_parts(\"reddit.com\", &[\"r\", \"rust\", \"wiki\", \"faq\"], &[]);\n+ assert_eq!(terminal(&p), None);\n+ assert_eq!(canon(&p), \"https://reddit.com/r/rust/wiki/faq\");\n+ }\n+\n+ #[test]\n+ fn traverse_youtube_watch_requires_v_in_query() {\n+ let p = test_parts(\"youtube.com\", &[\"watch\"], &[(\"v\", \"xyz\")]);\n+ assert_eq!(terminal(&p), Some(\"youtube_watch\"));\n+ }\n+\n+ #[test]\n+ fn traverse_youtu_be_captures_vid_id() {\n+ let p = test_parts(\"youtu.be\", &[\"dQw4w9WgXcQ\"], &[]);\n+ assert_eq!(terminal(&p), Some(\"youtu_be_video\"));\n+ assert_eq!(vars(&p).get(\"vid_id\").map(String::as_str), Some(\"dQw4w9WgXcQ\"));\n+ }\n+\n+ #[test]\n+ fn traverse_shorts_sets_video_id_var() {\n+ let p = test_parts(\"youtube.com\", &[\"shorts\", \"abc99\"], &[]);\n+ assert_eq!(terminal(&p), Some(\"youtube_watch\"));\n+ assert_eq!(vars(&p).get(\"video_id\").map(String::as_str), Some(\"abc99\"));\n+ }\n+\n+ #[test]\n+ fn reddit_domain_canonical() {\n+ let p = test_parts(\"reddit.com\", &[], &[]);\n+ assert_eq!(canon(&p), \"https://reddit.com\");\n+ }\n+\n+ #[test]\n+ fn reddit_r_hub_canonical() {\n+ let p = test_parts(\"reddit.com\", &[\"r\"], &[]);\n+ assert_eq!(terminal(&p), Some(\"reddit_r_hub\"));\n+ assert_eq!(canon(&p), \"https://reddit.com/r\");\n+ }\n+\n+ #[test]\n+ fn reddit_subreddit_lowercases_name() {\n+ let p = test_parts(\"reddit.com\", &[\"r\", \"AmITheAsshole\"], &[]);\n+ assert_eq!(canon(&p), \"https://reddit.com/r/amitheasshole\");\n+ }\n+\n+ #[test]\n+ fn reddit_host_aliases_old_new_www() {\n+ for host in [\"old.reddit.com\", \"new.reddit.com\", \"www.reddit.com\"] {\n+ let p = test_parts(host, &[\"r\", \"rust\"], &[]);\n+ assert_eq!(canon(&p), \"https://reddit.com/r/rust\", \"host {host}\");\n+ }\n+ }\n+\n+ #[test]\n+ fn reddit_post_strips_slug_and_query() {\n+ let p = test_parts(\n+ \"old.reddit.com\",\n+ &[\"r\", \"Rust\", \"comments\", \"1abc\", \"title_slug_here\"],\n+ &[(\"sort\", \"new\")],\n+ );\n+ assert_eq!(canon(&p), \"https://reddit.com/r/rust/comments/1abc\");\n+ }\n+\n+ #[test]\n+ fn reddit_post_multiple_slugs_absorbed() {\n+ let p = test_parts(\n+ \"reddit.com\",\n+ &[\"r\", \"x\", \"comments\", \"id1\", \"slug1\", \"extra\"],\n+ &[],\n+ );\n+ assert_eq!(canon(&p), \"https://reddit.com/r/x/comments/id1\");\n+ }\n+\n+ #[test]\n+ fn reddit_listing_with_query_only() {\n+ let p = test_parts(\"www.reddit.com\", &[\"r\", \"programming\"], &[(\"sort\", \"top\")]);\n+ assert_eq!(canon(&p), \"https://reddit.com/r/programming\");\n+ }\n+\n+ #[test]\n+ fn reddit_subreddit_breadcrumbs_include_r_hub() {\n+ let p = test_parts(\"reddit.com\", &[\"r\", \"movies\"], &[]);\n+ assert_eq!(\n+ crumbs(&p),\n+ vec![\n+ \"https://reddit.com\",\n+ \"https://reddit.com/r\",\n+ \"https://reddit.com/r/movies\"\n+ ]\n+ );\n+ }\n+\n+ #[test]\n+ fn reddit_post_breadcrumbs_skip_comments_node() {\n+ let p = test_parts(\"reddit.com\", &[\"r\", \"aww\", \"comments\", \"1trnvdl\"], &[]);\n+ let c = crumbs(&p);\n+ assert!(!c.iter().any(|u| u.ends_with(\"/comments\")));\n+ assert_eq!(\n+ c.last().map(String::as_str),\n+ Some(\"https://reddit.com/r/aww/comments/1trnvdl\")\n+ );\n+ assert!(c.contains(&\"https://reddit.com/r/aww\".to_string()));\n+ }\n+\n+ #[test]\n+ fn reddit_post_parent_is_subreddit_not_comments() {\n+ let p = test_parts(\"reddit.com\", &[\"r\", \"aww\", \"comments\", \"1trnvdl\"], &[]);\n+ let c = crumbs(&p);\n+ let parent = c.get(c.len() - 2).unwrap();\n+ assert_eq!(parent, \"https://reddit.com/r/aww\");\n+ }\n+\n+ #[test]\n+ fn reddit_domain_parent_is_none_in_breadcrumb_chain() {\n+ let p = test_parts(\"reddit.com\", &[], &[]);\n+ assert_eq!(crumbs(&p), vec![\"https://reddit.com\"]);\n+ }\n+\n+ #[test]\n+ fn youtube_watch_canonical_uses_v_only() {\n+ let p = test_parts(\"youtube.com\", &[\"watch\"], &[(\"v\", \"abc\"), (\"t\", \"99\")]);\n+ assert_eq!(canon(&p), \"https://youtube.com/watch?v=abc\");\n+ }\n+\n+ #[test]\n+ fn youtube_query_order_independent() {\n+ let a = test_parts(\"youtube.com\", &[\"watch\"], &[(\"v\", \"abc\"), (\"t\", \"4\")]);\n+ let b = test_parts(\"youtube.com\", &[\"watch\"], &[(\"t\", \"4\"), (\"v\", \"abc\")]);\n+ assert_eq!(canon(&a), canon(&b));\n+ }\n+\n+ #[test]\n+ fn youtube_host_aliases() {\n+ for host in [\"www.youtube.com\", \"m.youtube.com\"] {\n+ let p = test_parts(host, &[\"watch\"], &[(\"v\", \"x\")]);\n+ assert_eq!(canon(&p), \"https://youtube.com/watch?v=x\", \"host {host}\");\n+ }\n+ }\n+\n+ #[test]\n+ fn youtube_shorts_canonical_matches_watch() {\n+ let shorts = test_parts(\"youtube.com\", &[\"shorts\", \"vid123\"], &[]);\n+ let watch = test_parts(\"youtube.com\", &[\"watch\"], &[(\"v\", \"vid123\")]);\n+ assert_eq!(canon(&shorts), canon(&watch));\n+ assert_eq!(canon(&shorts), \"https://youtube.com/watch?v=vid123\");\n+ }\n+\n+ #[test]\n+ fn youtu_be_matches_youtube_watch() {\n+ let be = test_parts(\"youtu.be\", &[\"dQw4w9WgXcQ\"], &[]);\n+ let watch = test_parts(\"youtube.com\", &[\"watch\"], &[(\"v\", \"dQw4w9WgXcQ\")]);\n+ assert_eq!(canon(&be), canon(&watch));\n+ }\n+\n+ #[test]\n+ fn youtube_breadcrumbs_domain_then_watch() {\n+ let p = test_parts(\"youtube.com\", &[\"watch\"], &[(\"v\", \"abc\")]);\n+ assert_eq!(\n+ crumbs(&p),\n+ vec![\"https://youtube.com\", \"https://youtube.com/watch?v=abc\"]\n+ );\n+ }\n+\n+ #[test]\n+ fn youtu_be_breadcrumbs_include_youtube_domain() {\n+ let p = test_parts(\"youtu.be\", &[\"abc\"], &[]);\n+ let c = crumbs(&p);\n+ assert_eq!(c.first().map(String::as_str), Some(\"https://youtube.com\"));\n+ assert_eq!(\n+ c.last().map(String::as_str),\n+ Some(\"https://youtube.com/watch?v=abc\")\n+ );\n+ }\n+\n+ #[test]\n+ fn parsed_urls_match_hand_built_parts() {\n+ let raw = \"https://www.reddit.com/r/rust/comments/aaa/title/?utm=x\";\n+ let parsed = UrlParts::parse(raw).unwrap();\n+ let hand = test_parts(\n+ \"www.reddit.com\",\n+ &[\"r\", \"rust\", \"comments\", \"aaa\", \"title\"],\n+ &[(\"utm\", \"x\")],\n+ );\n+ assert_eq!(canon(&parsed), canon(&hand));\n+ }\n+\n+ #[test]\n+ fn equivalence_cluster_youtube_formats() {\n+ let urls = [\n+ \"https://youtu.be/abc123\",\n+ \"https://www.youtube.com/watch?v=abc123\",\n+ \"https://youtube.com/watch?v=abc123&t=1\",\n+ \"https://m.youtube.com/watch?t=1&v=abc123\",\n+ ];\n+ let canonical: Vec<_> = urls\n+ .iter()\n+ .map(|u| canon(&UrlParts::parse(u).unwrap()))\n+ .collect();\n+ assert!(canonical.iter().all(|c| *c == \"https://youtube.com/watch?v=abc123\"));\n+ }\n+\n+ #[test]\n+ fn equivalence_cluster_reddit_post_formats() {\n+ let urls = [\n+ \"https://old.reddit.com/r/Rust/comments/aaa/slug/\",\n+ \"reddit.com/r/rust/comments/aaa/other_slug\",\n+ \"https://reddit.com/r/RUST/comments/aaa\",\n+ ];\n+ let canonical: Vec<_> = urls\n+ .iter()\n+ .map(|u| canon(&UrlParts::parse(u).unwrap()))\n+ .collect();\n+ assert!(\n+ canonical\n+ .iter()\n+ .all(|c| *c == \"https://reddit.com/r/rust/comments/aaa\")\n+ );\n+ }\n+\n+ #[test]\n+ fn graph_nodes_all_have_valid_parent_links() {\n+ let g = build_graph();\n+ for (id, node) in &g.nodes {\n+ if let Some(parent) = node.parent {\n+ assert!(g.nodes.contains_key(parent), \"node {id} parent {parent}\");\n+ }\n+ }\n+ }\n+\n+ #[test]\n+ fn graph_terminal_canonical_always_succeeds_for_reddit_paths() {\n+ let cases: &[(&[&str], &str)] = &[\n+ (&[\"r\", \"rust\"], \"https://reddit.com/r/rust\"),\n+ (\n+ &[\"r\", \"rust\", \"comments\", \"x\"],\n+ \"https://reddit.com/r/rust/comments/x\",\n+ ),\n+ ];\n+ for (segs, want) in cases {\n+ let p = test_parts(\"reddit.com\", segs, &[]);\n+ assert_eq!(canon(&p), *want);\n+ }\n+ }\n+\n+ #[test]\n+ fn breadcrumb_parent_walk_matches_parent_url_semantics() {\n+ let p = test_parts(\"reddit.com\", &[\"r\", \"aww\", \"comments\", \"id1\"], &[]);\n+ let c = crumbs(&p);\n+ assert_eq!(c.len(), 4);\n+ assert_eq!(\n+ c.get(c.len() - 2).map(String::as_str),\n+ Some(\"https://reddit.com/r/aww\")\n+ );\n+ }\n+\n+ #[test]\n+ fn youtube_watch_without_v_falls_back_to_generic() {\n+ let p = test_parts(\"youtube.com\", &[\"watch\"], &[]);\n+ assert_eq!(terminal(&p), Some(\"youtube_watch\"));\n+ assert_eq!(canon(&p), \"https://youtube.com/watch\");\n+ }\n+\n+ #[test]\n+ fn reddit_only_comments_path_stops_at_gate() {\n+ let p = test_parts(\"reddit.com\", &[\"r\", \"rust\", \"comments\"], &[]);\n+ assert_eq!(terminal(&p), Some(\"reddit_comments_gate\"));\n+ assert_eq!(canon(&p), \"https://reddit.com/r/rust\");\n+ }\n+\n+ #[test]\n+ fn generic_deep_path_many_segments() {\n+ let segs: Vec<&str> = (0..10)\n+ .map(|i| match i {\n+ 0 => \"a\",\n+ 1 => \"b\",\n+ 2 => \"c\",\n+ 3 => \"d\",\n+ 4 => \"e\",\n+ 5 => \"f\",\n+ 6 => \"g\",\n+ 7 => \"h\",\n+ 8 => \"i\",\n+ _ => \"j\",\n+ })\n+ .collect();\n+ let p = test_parts(\"site.com\", &segs, &[]);\n+ assert_eq!(crumbs(&p).len(), 11);\n+ }\n+\n+ #[test]\n+ fn traverse_literal_r_required_for_subreddit() {\n+ let p = test_parts(\"reddit.com\", &[\"rust\"], &[]);\n+ assert_eq!(terminal(&p), None);\n+ }\n+\n+ #[test]\n+ fn http_scheme_upgraded_via_generic_fallback_host() {\n+ let parsed = UrlParts::parse(\"http://example.com/page\").unwrap();\n+ assert_eq!(canon(&parsed), \"https://example.com/page\");\n+ }\n+\n+ #[test]\n+ fn each_graph_node_canonical_is_invokable() {\n+ let g = build_graph();\n+ let empty = Context::default();\n+ for (id, node) in &g.nodes {\n+ let _ = (node.canonical)(&empty);\n+ let _ = id;\n+ }\n+ }\n+\n+ #[test]\n+ fn reddit_double_listing_suffix_both_absorbed() {\n+ let p = test_parts(\"reddit.com\", &[\"r\", \"rust\", \"hot\", \"new\"], &[]);\n+ assert_eq!(terminal(&p), Some(\"reddit_subreddit\"));\n+ assert_eq!(canon(&p), \"https://reddit.com/r/rust\");\n+ }\n+\n+ #[test]\n+ fn youtu_be_empty_path_stays_at_entry() {\n+ let p = test_parts(\"youtu.be\", &[], &[]);\n+ assert_eq!(terminal(&p), Some(\"youtu_be_entry\"));\n+ }\n+}\ndiff --git a/server/src/url_rules/graph_builder.rs b/server/src/url_rules/graph_builder.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..243204ad5ca514fff459057956080cacb5bf38e2\n--- /dev/null\n+++ b/server/src/url_rules/graph_builder.rs\n@@ -0,0 +1,73 @@\n+//! Declarative construction of the URL graph with build-time link validation.\n+\n+use std::collections::HashMap;\n+\n+use super::graph::{CanonicalFn, Edge, EdgePattern, Graph, Node};\n+\n+pub struct GraphBuilder {\n+ nodes: HashMap<&'static str, Node>,\n+ current: Option<&'static str>,\n+}\n+\n+impl GraphBuilder {\n+ pub fn new() -> Self {\n+ Self {\n+ nodes: HashMap::new(),\n+ current: None,\n+ }\n+ }\n+\n+ pub fn node(mut self, id: &'static str) -> Self {\n+ self.nodes.entry(id).or_insert_with(Node::empty);\n+ self.current = Some(id);\n+ self\n+ }\n+\n+ pub fn canonical(mut self, f: CanonicalFn) -> Self {\n+ let id = self.current.expect(\"canonical() without node()\");\n+ self.nodes.get_mut(id).expect(\"node missing\").canonical = f;\n+ self\n+ }\n+\n+ pub fn parent(mut self, parent_id: &'static str) -> Self {\n+ let id = self.current.expect(\"parent() without node()\");\n+ self.nodes.get_mut(id).expect(\"node missing\").parent = Some(parent_id);\n+ self\n+ }\n+\n+ pub fn edge(mut self, pattern: EdgePattern, target: &'static str) -> Self {\n+ let id = self.current.expect(\"edge() without node()\");\n+ self.nodes\n+ .get_mut(id)\n+ .expect(\"node missing\")\n+ .edges\n+ .push(Edge { pattern, target });\n+ self\n+ }\n+\n+ pub fn build(self) -> Graph {\n+ for (id, node) in &self.nodes {\n+ if let Some(parent) = node.parent {\n+ assert!(\n+ self.nodes.contains_key(parent),\n+ \"node {id}: parent {parent} does not exist\"\n+ );\n+ }\n+ for edge in &node.edges {\n+ if !matches!(\n+ edge.pattern,\n+ EdgePattern::AbsorbAny | EdgePattern::AbsorbIf(_)\n+ ) {\n+ assert!(\n+ self.nodes.contains_key(edge.target),\n+ \"node {id}: edge target {} does not exist\",\n+ edge.target\n+ );\n+ }\n+ }\n+ }\n+ Graph {\n+ nodes: self.nodes,\n+ }\n+ }\n+}\ndiff --git a/server/src/url_rules/mod.rs b/server/src/url_rules/mod.rs\nindex 9e1445346ce77a49dd6a7e7713bf9c57aef353cc..ba4ac662acc7bd4d50ee34613eb7eb6fccbfb17b 100644\n--- a/server/src/url_rules/mod.rs\n+++ b/server/src/url_rules/mod.rs\n@@ -1,6 +1,7 @@\n //! URL canonicalization and hierarchy via a semantic graph (DFA + generic fallback).\n \n mod graph;\n+mod graph_builder;\n mod parse;\n mod registry;\n \ndiff --git a/server/src/url_rules/parse.rs b/server/src/url_rules/parse.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..19d0c82feb718817168b8b445fcbfa39cf6aa6ba\n--- /dev/null\n+++ b/server/src/url_rules/parse.rs\n@@ -0,0 +1,169 @@\n+//! Parse raw strings into host, path segments, and query (order-independent).\n+\n+use std::collections::HashMap;\n+\n+use url::Url;\n+\n+#[derive(Debug, Clone)]\n+pub struct UrlParts {\n+ pub scheme: String,\n+ pub host: String,\n+ pub path_segments: Vec,\n+ pub query: HashMap,\n+}\n+\n+impl UrlParts {\n+ pub fn parse(raw: &str) -> Option {\n+ let trimmed = raw.trim();\n+ if trimmed.is_empty() {\n+ return None;\n+ }\n+\n+ let with_scheme = if trimmed.contains(\"://\") {\n+ trimmed.to_string()\n+ } else if trimmed.starts_with(\"r/\") || trimmed.starts_with(\"/r/\") {\n+ let rest = trimmed.trim_start_matches('/').trim_start_matches(\"r/\");\n+ format!(\"https://reddit.com/r/{rest}\")\n+ } else if trimmed.contains('.') && !trimmed.starts_with('/') {\n+ format!(\"https://{trimmed}\")\n+ } else {\n+ trimmed.to_string()\n+ };\n+\n+ let url = Url::parse(&with_scheme).ok()?;\n+ let host = url.host_str()?.to_string();\n+ let path_segments: Vec = url\n+ .path_segments()\n+ .map(|segs| segs.filter(|s| !s.is_empty()).map(str::to_string).collect())\n+ .unwrap_or_default();\n+\n+ let mut query = HashMap::new();\n+ for (k, v) in url.query_pairs() {\n+ query.insert(k.into_owned(), v.into_owned());\n+ }\n+\n+ Some(Self {\n+ scheme: url.scheme().to_string(),\n+ path_segments,\n+ query,\n+ host,\n+ })\n+ }\n+\n+ /// Host normalized for graph entry matching (lowercase, aliases).\n+ pub fn match_host(&self) -> String {\n+ normalize_match_host(&self.host)\n+ }\n+}\n+\n+pub fn normalize_match_host(host: &str) -> String {\n+ let h = host\n+ .strip_prefix(\"www.\")\n+ .unwrap_or(host)\n+ .to_ascii_lowercase();\n+ match h.as_str() {\n+ \"old.reddit.com\" | \"new.reddit.com\" => \"reddit.com\".to_string(),\n+ \"m.youtube.com\" => \"youtube.com\".to_string(),\n+ _ => h,\n+ }\n+}\n+\n+pub fn strip_tracking_query(query: &mut HashMap) {\n+ query.retain(|k, _| {\n+ let lower = k.to_ascii_lowercase();\n+ !(lower.starts_with(\"utm_\")\n+ || matches!(\n+ lower.as_str(),\n+ \"fbclid\" | \"gclid\" | \"ref\" | \"ref_src\" | \"ref_source\" | \"mc_cid\" | \"mc_eid\"\n+ ))\n+ });\n+}\n+\n+#[cfg(test)]\n+pub(crate) fn test_parts(host: &str, segs: &[&str], query: &[(&str, &str)]) -> UrlParts {\n+ UrlParts {\n+ scheme: \"https\".to_string(),\n+ host: host.to_string(),\n+ path_segments: segs.iter().map(|s| (*s).to_string()).collect(),\n+ query: query\n+ .iter()\n+ .map(|(k, v)| (k.to_string(), v.to_string()))\n+ .collect(),\n+ }\n+}\n+\n+#[cfg(test)]\n+mod tests {\n+ use super::*;\n+\n+ #[test]\n+ fn parse_full_url_splits_host_path_query() {\n+ let p = UrlParts::parse(\"https://www.youtube.com/watch?v=abc&t=4\").unwrap();\n+ assert_eq!(p.host, \"www.youtube.com\");\n+ assert_eq!(p.path_segments, vec![\"watch\"]);\n+ assert_eq!(p.query.get(\"v\").map(String::as_str), Some(\"abc\"));\n+ assert_eq!(p.query.get(\"t\").map(String::as_str), Some(\"4\"));\n+ }\n+\n+ #[test]\n+ fn parse_r_shortcut_expands_to_reddit() {\n+ let p = UrlParts::parse(\"r/rust\").unwrap();\n+ assert_eq!(p.match_host(), \"reddit.com\");\n+ assert_eq!(p.path_segments, vec![\"r\", \"rust\"]);\n+ }\n+\n+ #[test]\n+ fn parse_slash_r_shortcut() {\n+ let p = UrlParts::parse(\"/r/aww\").unwrap();\n+ assert_eq!(p.path_segments, vec![\"r\", \"aww\"]);\n+ }\n+\n+ #[test]\n+ fn parse_schemeless_host_path() {\n+ let p = UrlParts::parse(\"reddit.com/r/rust/comments/aaa/slug\").unwrap();\n+ assert_eq!(p.match_host(), \"reddit.com\");\n+ assert_eq!(\n+ p.path_segments,\n+ vec![\"r\", \"rust\", \"comments\", \"aaa\", \"slug\"]\n+ );\n+ }\n+\n+ #[test]\n+ fn parse_empty_returns_none() {\n+ assert!(UrlParts::parse(\"\").is_none());\n+ assert!(UrlParts::parse(\" \").is_none());\n+ }\n+\n+ #[test]\n+ fn normalize_match_host_reddit_aliases() {\n+ assert_eq!(normalize_match_host(\"old.reddit.com\"), \"reddit.com\");\n+ assert_eq!(normalize_match_host(\"NEW.reddit.com\"), \"reddit.com\");\n+ assert_eq!(normalize_match_host(\"www.reddit.com\"), \"reddit.com\");\n+ }\n+\n+ #[test]\n+ fn normalize_match_host_youtube_aliases() {\n+ assert_eq!(normalize_match_host(\"m.youtube.com\"), \"youtube.com\");\n+ assert_eq!(normalize_match_host(\"www.youtube.com\"), \"youtube.com\");\n+ }\n+\n+ #[test]\n+ fn strip_tracking_query_removes_known_params() {\n+ let mut q = HashMap::from([\n+ (\"v\".into(), \"1\".into()),\n+ (\"utm_source\".into(), \"x\".into()),\n+ (\"fbclid\".into(), \"y\".into()),\n+ (\"ref\".into(), \"z\".into()),\n+ ]);\n+ strip_tracking_query(&mut q);\n+ assert_eq!(q.len(), 1);\n+ assert_eq!(q.get(\"v\").map(String::as_str), Some(\"1\"));\n+ }\n+\n+ #[test]\n+ fn strip_tracking_query_utm_prefix() {\n+ let mut q = HashMap::from([(\"utm_campaign\".into(), \"email\".into())]);\n+ strip_tracking_query(&mut q);\n+ assert!(q.is_empty());\n+ }\n+}\ndiff --git a/server/src/url_rules/registry_tests.rs b/server/src/url_rules/registry_tests.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..7b76b550f808f590e011469fdae02adf603b43d2\n--- /dev/null\n+++ b/server/src/url_rules/registry_tests.rs\n@@ -0,0 +1,195 @@\n+//! End-to-end tests for the public registry API (`canonicalize_raw`, breadcrumbs, parent).\n+\n+use super::registry::{\n+ canonicalize_raw, looks_like_url, navigable_breadcrumbs, parent_url, resolve_id,\n+};\n+\n+fn canon(raw: &str) -> String {\n+ canonicalize_raw(raw).unwrap().canonical\n+}\n+\n+#[test]\n+fn looks_like_url_positive_cases() {\n+ for raw in [\n+ \"https://reddit.com/r/rust\",\n+ \"r/rust\",\n+ \"/r/aww\",\n+ \"reddit.com/r/x\",\n+ \"www.example.com/path\",\n+ \"youtu.be/abc\",\n+ ] {\n+ assert!(looks_like_url(raw), \"{raw}\");\n+ }\n+}\n+\n+#[test]\n+fn looks_like_url_negative_cases() {\n+ for raw in [\"alpha\", \"beta\", \"\", \"hello world\", \"no-dots\"] {\n+ assert!(!looks_like_url(raw), \"{raw}\");\n+ }\n+}\n+\n+#[test]\n+fn resolve_id_matches_canonicalize_raw() {\n+ let raw = \"https://youtu.be/xyz\";\n+ assert_eq!(\n+ resolve_id(raw).as_deref(),\n+ Some(canon(raw).as_str())\n+ );\n+}\n+\n+#[test]\n+fn canonicalize_empty_returns_none() {\n+ assert!(canonicalize_raw(\"\").is_none());\n+}\n+\n+#[test]\n+fn alias_when_slug_stripped() {\n+ let r = canonicalize_raw(\n+ \"https://reddit.com/r/rust/comments/aaa/very_long_title_slug\",\n+ )\n+ .unwrap();\n+ assert_eq!(r.canonical, \"https://reddit.com/r/rust/comments/aaa\");\n+ assert!(r.alias_of.is_some());\n+}\n+\n+#[test]\n+fn alias_none_when_already_canonical() {\n+ let raw = \"https://reddit.com/r/rust\";\n+ let r = canonicalize_raw(raw).unwrap();\n+ assert_eq!(r.canonical, raw);\n+ assert!(r.alias_of.is_none());\n+}\n+\n+#[test]\n+fn parent_url_subreddit_under_r_hub() {\n+ assert_eq!(\n+ parent_url(\"https://reddit.com/r/movies\").as_deref(),\n+ Some(\"https://reddit.com/r\")\n+ );\n+}\n+\n+#[test]\n+fn parent_url_domain_has_none() {\n+ assert_eq!(parent_url(\"https://reddit.com\").as_deref(), None);\n+}\n+\n+#[test]\n+fn parent_url_generic_site() {\n+ assert_eq!(\n+ parent_url(\"https://example.com/a/b\").as_deref(),\n+ Some(\"https://example.com/a\")\n+ );\n+}\n+\n+#[test]\n+fn breadcrumbs_from_canonical_string_roundtrip() {\n+ let id = \"https://reddit.com/r/golang/comments/abc123\";\n+ let crumbs = navigable_breadcrumbs(id);\n+ assert_eq!(crumbs.last().map(String::as_str), Some(id));\n+}\n+\n+// --- Table: Reddit raw URLs → canonical ---\n+\n+#[test]\n+fn reddit_canonical_matrix() {\n+ let cases: &[(&str, &str)] = &[\n+ (\"r/rust\", \"https://reddit.com/r/rust\"),\n+ (\"/r/aww\", \"https://reddit.com/r/aww\"),\n+ (\"https://reddit.com/r/rust\", \"https://reddit.com/r/rust\"),\n+ (\n+ \"https://www.reddit.com/r/programming/new\",\n+ \"https://reddit.com/r/programming\",\n+ ),\n+ (\n+ \"https://old.reddit.com/r/test/comments/xyz/slug/\",\n+ \"https://reddit.com/r/test/comments/xyz\",\n+ ),\n+ (\n+ \"reddit.com/r/Movies/comments/abc/Title_Case_Slug\",\n+ \"https://reddit.com/r/movies/comments/abc\",\n+ ),\n+ ];\n+ for (raw, want) in cases {\n+ assert_eq!(canon(raw), *want, \"raw={raw}\");\n+ }\n+}\n+\n+// --- Table: YouTube raw URLs → canonical ---\n+\n+#[test]\n+fn youtube_canonical_matrix() {\n+ let cases: &[(&str, &str)] = &[\n+ (\n+ \"https://youtube.com/watch?v=abc\",\n+ \"https://youtube.com/watch?v=abc\",\n+ ),\n+ (\n+ \"https://www.youtube.com/watch?v=abc&t=1&feature=share\",\n+ \"https://youtube.com/watch?v=abc\",\n+ ),\n+ (\"https://youtu.be/abc\", \"https://youtube.com/watch?v=abc\"),\n+ (\n+ \"https://youtube.com/shorts/abc\",\n+ \"https://youtube.com/watch?v=abc\",\n+ ),\n+ ];\n+ for (raw, want) in cases {\n+ assert_eq!(canon(raw), *want, \"raw={raw}\");\n+ }\n+}\n+\n+// --- Table: generic sites ---\n+\n+#[test]\n+fn generic_canonical_matrix() {\n+ let cases: &[(&str, &str)] = &[\n+ (\n+ \"https://news.ycombinator.com/item?id=38472\",\n+ \"https://news.ycombinator.com/item?id=38472\",\n+ ),\n+ (\n+ \"https://www.github.com/rust-lang/rust/issues/1?utm_source=x\",\n+ \"https://github.com/rust-lang/rust/issues/1\",\n+ ),\n+ (\"https://example.com\", \"https://example.com\"),\n+ ];\n+ for (raw, want) in cases {\n+ assert_eq!(canon(raw), *want, \"raw={raw}\");\n+ }\n+}\n+\n+// --- Phantom /comments/ regression (sorter2-specific) ---\n+\n+#[test]\n+fn phantom_comments_not_in_breadcrumbs_for_post() {\n+ let crumbs = navigable_breadcrumbs(\"https://reddit.com/r/rust/comments/aaa\");\n+ assert!(!crumbs.iter().any(|c| c.ends_with(\"/comments\")));\n+}\n+\n+#[test]\n+fn phantom_comments_not_sibling_of_subreddit_in_breadcrumb_chain() {\n+ let crumbs = navigable_breadcrumbs(\"https://reddit.com/r/rust/comments/aaa\");\n+ let subs: Vec<_> = crumbs\n+ .iter()\n+ .filter(|c| c.contains(\"/r/rust\") && !c.contains(\"/comments/\"))\n+ .collect();\n+ assert_eq!(subs, vec![\"https://reddit.com/r/rust\"]);\n+}\n+\n+// --- Distinct items must stay distinct ---\n+\n+#[test]\n+fn different_posts_different_canonical() {\n+ let a = canon(\"https://reddit.com/r/rust/comments/aaa\");\n+ let b = canon(\"https://reddit.com/r/rust/comments/bbb\");\n+ assert_ne!(a, b);\n+}\n+\n+#[test]\n+fn different_subreddits_different_canonical() {\n+ assert_ne!(\n+ canon(\"https://reddit.com/r/rust\"),\n+ canon(\"https://reddit.com/r/golang\")\n+ );\n+}\n","role":"user"}],"model":"openai/gpt-chat-latest"}