{"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[2bc302c3] refactor\n\nSide A — unified diff (full patch):\ndiff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs\nindex 06001212820101e0cc953d3687dea64f85e60787..d2f9769108def7ca2c5857aec8b4319426188a66 100644\n--- a/server/src/api/ui_html.rs\n+++ b/server/src/api/ui_html.rs\n@@ -47,7 +47,7 @@ pub async fn post_ui_html(\n ratio_left,\n ratio_right,\n scope,\n- next,\n+ vote_compare,\n } => {\n let parent = parent_from_scope(&scope);\n if let Err(e) = state\n@@ -57,14 +57,12 @@ pub async fn post_ui_html(\n return ui_js_warn(&e).into_response();\n }\n let tree = state.tree.read().await;\n- if !next.trim().is_empty() {\n+ if vote_compare {\n+ let left = parse_item_param(&a);\n+ let right = parse_item_param(&b);\n+ let morph = crate::html::vote::vote_recorded_morph(&tree, &parent, &left, &right);\n drop(tree);\n- return JsBuilder::new()\n- .raw(&format!(\n- \"window.location.href={};\",\n- js_string_literal(next.trim())\n- ))\n- .into_response();\n+ return morph.into_response();\n }\n let empty = crate::reducer::NodeState::default();\n let node = tree.get(&parent).unwrap_or(&empty);\n@@ -137,7 +135,7 @@ mod tests {\n ratio_left: 3,\n ratio_right: 1,\n scope: String::new(),\n- next: String::new(),\n+ vote_compare: false,\n }\n );\n }\ndiff --git a/server/src/html/mod.rs b/server/src/html/mod.rs\nindex 61cdbc094819ddedb755572c59456ec0d6617619..cd578a5fea46a9a1d49e238d08a80c2caf18708d 100644\n--- a/server/src/html/mod.rs\n+++ b/server/src/html/mod.rs\n@@ -65,6 +65,15 @@ impl JsBuilder {\n self\n }\n \n+ pub(crate) fn morph_inner_selector(mut self, selector: &str, markup: Markup) -> Self {\n+ let html = js_string_literal(&markup.into_string());\n+ self.snippets.push(format!(\n+ \"var __el = document.querySelector({sel}); if (__el) {{ Idiomorph.morph(__el, {html}, {{ morphStyle: 'innerHTML' }}); }}\",\n+ sel = js_string_literal(selector),\n+ ));\n+ self\n+ }\n+\n pub(crate) fn raw(mut self, js: &str) -> Self {\n if !js.is_empty() {\n self.snippets.push(js.to_string());\ndiff --git a/server/src/html/vote.rs b/server/src/html/vote.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..89ed621ad861214e147add2062224fc4137ff8ad\n--- /dev/null\n+++ b/server/src/html/vote.rs\n@@ -0,0 +1,306 @@\n+//! Pairwise vote UI — `/vote?parent=` with optional `left` / `right`.\n+\n+use axum::{\n+ extract::{Query, State},\n+ response::{Html, IntoResponse},\n+};\n+use maud::{html, Markup};\n+use serde::Deserialize;\n+\n+use crate::{\n+ form_template::template_json_compact,\n+ html::JsBuilder,\n+ pair::{children_of, resolve_pair, suggest_next_pair_in_pool},\n+ path_types::ItemId,\n+ reducer::{GlobalTree, GroupState, NodeState, VoteData},\n+ state::{parse_item_param, AppState},\n+ ui_action::UI_RPC_FIELD,\n+};\n+\n+use super::{breadcrumb_path, item_href, layout};\n+\n+#[derive(Debug, Deserialize)]\n+pub struct VoteQuery {\n+ pub parent: String,\n+ #[serde(default)]\n+ pub left: Option,\n+ #[serde(default)]\n+ pub right: Option,\n+}\n+\n+pub fn vote_href(parent: &ItemId) -> String {\n+ format!(\n+ \"/vote?parent={}\",\n+ urlencoding::encode(parent.as_str())\n+ )\n+}\n+\n+fn vote_compare_href(parent: &ItemId, left: &ItemId, right: &ItemId) -> String {\n+ format!(\n+ \"/vote?parent={}&left={}&right={}\",\n+ urlencoding::encode(parent.as_str()),\n+ urlencoding::encode(left.as_str()),\n+ urlencoding::encode(right.as_str()),\n+ )\n+}\n+\n+fn display_label(id: &ItemId) -> String {\n+ id.segments()\n+ .last()\n+ .map_or(\"item\".into(), |v| v.to_string())\n+}\n+\n+fn child_title(tree: &GlobalTree, id: &ItemId) -> String {\n+ tree.get(id)\n+ .and_then(|n| n.data.as_ref())\n+ .map(|d| d.title.clone())\n+ .unwrap_or_else(|| display_label(id))\n+}\n+\n+fn ratio_pct(ratio_left: i32, ratio_right: i32) -> f64 {\n+ let l = ratio_left.max(0) as f64;\n+ let r = ratio_right.max(0) as f64;\n+ let sum = l + r;\n+ if sum <= 0.0 {\n+ 50.0\n+ } else {\n+ (l / sum) * 100.0\n+ }\n+}\n+\n+fn ratios_for_page(v: &VoteData, page_left: &ItemId, page_right: &ItemId) -> (i32, i32) {\n+ match (v.a.as_str(), v.b.as_str()) {\n+ (a, b) if a == page_left.as_str() && b == page_right.as_str() => {\n+ (v.ratio_left, v.ratio_right)\n+ }\n+ (a, b) if a == page_right.as_str() && b == page_left.as_str() => {\n+ (v.ratio_right, v.ratio_left)\n+ }\n+ _ => (v.ratio_left, v.ratio_right),\n+ }\n+}\n+\n+fn edge_votes(group: &GroupState, left: &ItemId, right: &ItemId) -> Vec {\n+ group\n+ .recent_votes\n+ .iter()\n+ .filter(|v| {\n+ (v.a.as_str() == left.as_str() && v.b.as_str() == right.as_str())\n+ || (v.a.as_str() == right.as_str() && v.b.as_str() == left.as_str())\n+ })\n+ .cloned()\n+ .collect()\n+}\n+\n+fn vote_edge_history(tree: &GlobalTree, group: &GroupState, left: &ItemId, right: &ItemId) -> Markup {\n+ let mut votes = edge_votes(group, 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+ html! {\n+ @if votes.is_empty() {\n+ p class=\"muted vote-edge-empty\" { \"no votes on this pair yet\" }\n+ } @else {\n+ h3 class=\"vote-edge-history-title\" {\n+ \"votes on this pair\"\n+ span class=\"vote-edge-history-axis muted\" { \" · \" (legend_left) \" : \" (legend_right) }\n+ }\n+ ul class=\"vote-edge-history\" {\n+ @for v in &votes {\n+ @let (r_left, r_right) = ratios_for_page(v, left, right);\n+ @let pct = ratio_pct(r_left, r_right);\n+ li class=\"vote-edge-history-row\" {\n+ div class=\"vote-edge-meta\" {\n+ span class=\"vote-edge-ratio\" { (format!(\"{}:{}\", r_left, r_right)) }\n+ }\n+ div class=\"ratio-bar vote-edge-bar\" aria-hidden=\"true\" {\n+ div class=\"ratio-left\" style={(format!(\"width: {:.3}%;\", pct))} {}\n+ div class=\"ratio-right\" style={(format!(\"width: {:.3}%;\", 100.0 - pct))} {}\n+ }\n+ }\n+ }\n+ }\n+ }\n+ }\n+}\n+\n+fn vote_back_nav(parent: &ItemId) -> Markup {\n+ html! {\n+ div class=\"vote-compare-nav\" {\n+ a class=\"vote-compare-back muted\" href=(item_href(parent)) { \"← back to \" (display_label(parent)) }\n+ }\n+ }\n+}\n+\n+fn vote_compare_actions(parent: &ItemId, next: Option<&(ItemId, ItemId)>) -> Markup {\n+ let next_href = next.map(|(l, r)| vote_compare_href(parent, l, r));\n+ html! {\n+ div id=\"vote-compare-actions\" class=\"vote-compare-actions\" {\n+ button type=\"submit\" class=\"btn-primary\" data-testid=\"vote-post\" { \"post vote\" }\n+ @if let Some(href) = &next_href {\n+ a class=\"btn-secondary vote-compare-next\" data-testid=\"vote-next-pair\" href=(href) { \"next pair\" }\n+ } @else {\n+ span class=\"btn-secondary vote-compare-next is-disabled\" { \"no next pair\" }\n+ }\n+ }\n+ }\n+}\n+\n+/// After recording a vote on the compare page: refresh edge history and next-pair link.\n+pub(crate) fn vote_recorded_morph(\n+ tree: &GlobalTree,\n+ parent: &ItemId,\n+ left: &ItemId,\n+ right: &ItemId,\n+) -> JsBuilder {\n+ let pool = children_of(tree, parent);\n+ let empty = NodeState::default();\n+ let group = tree\n+ .get(parent)\n+ .unwrap_or(&empty)\n+ .local_ranking\n+ .clone();\n+ let edge_history = vote_edge_history(tree, &group, left, right);\n+ let next_pair = suggest_next(&group, left, right, &pool);\n+ let actions = vote_compare_actions(parent, next_pair.as_ref());\n+ JsBuilder::new()\n+ .morph_inner_selector(\"#vote-edge-history-region\", edge_history)\n+ .morph_selector(\"#vote-compare-actions\", actions)\n+}\n+\n+fn vote_compare_item_card(tree: &GlobalTree, item: &ItemId, side_class: &str) -> Markup {\n+ let href = item_href(item);\n+ let title = child_title(tree, item);\n+ html! {\n+ div class=(format!(\"vote-compare-side {side_class}\")) {\n+ a class=(format!(\"vote-compare-item {side_class}\")) href=(href) {\n+ @if let Some(row) = crate::render::reddit::child_row_markup(tree, item, &href) {\n+ (row)\n+ } @else {\n+ strong { (title) }\n+ }\n+ }\n+ @if let Some(node) = tree.get(item) {\n+ @if crate::render::reddit::is_reddit_post(item) {\n+ @if let Some(data) = &node.data {\n+ @if let Some(src) = data.image_url.as_ref().or(data.thumb_url.as_ref()) {\n+ figure class=\"vote-compare-figure\" {\n+ img class=\"vote-compare-image\" src=(src) alt=\"\" loading=\"lazy\";\n+ }\n+ }\n+ @if let Some(author) = &data.author {\n+ p class=\"muted small\" { \"by \" (author) }\n+ }\n+ }\n+ } @else if let Some(data) = &node.data {\n+ @if let Some(body) = &data.body_html {\n+ div class=\"vote-compare-item-body\" {\n+ (maud::PreEscaped(body))\n+ }\n+ }\n+ }\n+ }\n+ }\n+ }\n+}\n+\n+\n+fn suggest_next(group: &GroupState, left: &ItemId, right: &ItemId, pool: &[ItemId]) -> Option<(ItemId, ItemId)> {\n+ suggest_next_pair_in_pool(group, pool, Some((left, right)))\n+}\n+\n+pub async fn vote_page(\n+ State(state): State,\n+ Query(q): Query,\n+) -> impl IntoResponse {\n+ let parent = parse_item_param(&q.parent);\n+ let left_param = q.left.as_deref().map(parse_item_param);\n+ let right_param = q.right.as_deref().map(parse_item_param);\n+\n+ let tree = state.tree.read().await;\n+ let empty = NodeState::default();\n+ let parent_node = tree.get(&parent).unwrap_or(&empty);\n+\n+ let (left, right) = match resolve_pair(\n+ &tree,\n+ &parent,\n+ left_param.as_ref(),\n+ right_param.as_ref(),\n+ ) {\n+ Ok(p) => p,\n+ Err(e) => {\n+ let (msg, status) = e.status_message();\n+ return (status, msg).into_response();\n+ }\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+\n+ let rpc_json = template_json_compact(&serde_json::json!({\n+ \"action\": \"record_vote\",\n+ \"a\": left.as_str(),\n+ \"b\": right.as_str(),\n+ \"ratio_left\": {\"$form:i32\": \"ratio_left\"},\n+ \"ratio_right\": {\"$form:i32\": \"ratio_right\"},\n+ \"scope\": parent.as_str(),\n+ \"vote_compare\": true,\n+ }))\n+ .expect(\"vote rpc json\");\n+\n+ let title = format!(\n+ \"vote — {} vs {}\",\n+ child_title(&tree, &left),\n+ child_title(&tree, &right)\n+ );\n+\n+ let body = html! {\n+ section class=\"vote-compare-shell\" {\n+ h1 { \"compare\" }\n+ (breadcrumb_path(&parent))\n+ p class=\"muted vote-compare-scope\" {\n+ \"ranking children of \"\n+ a href=(item_href(&parent)) { (child_title(&tree, &parent)) }\n+ }\n+ div class=\"vote-compare-pair\" {\n+ (vote_compare_item_card(&tree, &left, \"vote-compare-left\"))\n+ span class=\"vote-compare-vs\" { \"vs\" }\n+ (vote_compare_item_card(&tree, &right, \"vote-compare-right\"))\n+ }\n+ (vote_back_nav(&parent))\n+ div id=\"vote-edge-history-region\" {\n+ (edge_history)\n+ }\n+ form id=\"vote-compare-form\" method=\"POST\" action=\"/ui\" {\n+ input type=\"hidden\" name=(UI_RPC_FIELD) value=(rpc_json);\n+ input type=\"hidden\" name=\"ratio_left\" id=\"vote-ratio-left\" value=\"50\";\n+ input type=\"hidden\" name=\"ratio_right\" id=\"vote-ratio-right\" value=\"50\";\n+ label class=\"vote-compare-slider-label\" {\n+ span id=\"vote-slider-left-label\" { (child_title(&tree, &left)) }\n+ input type=\"range\" id=\"vote-preference-slider\" min=\"0\" max=\"100\" value=\"50\"\n+ aria-valuemin=\"0\" aria-valuemax=\"100\";\n+ span id=\"vote-slider-right-label\" { (child_title(&tree, &right)) }\n+ }\n+ (vote_compare_actions(&parent, next_pair.as_ref()))\n+ }\n+ }\n+ };\n+\n+ drop(tree);\n+\n+ let path = format!(\"/vote?parent={}\", urlencoding::encode(parent.as_str()));\n+ state.views.increment(path.clone());\n+ let views = state.views.get_views(&path);\n+\n+ Html(\n+ layout(\n+ &title,\n+ body,\n+ views,\n+ )\n+ .into_string(),\n+ )\n+ .into_response()\n+}\ndiff --git a/server/src/pair.rs b/server/src/pair.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..606ffa51038a57ffacf335aa48bdb1185f8483fb\n--- /dev/null\n+++ b/server/src/pair.rs\n@@ -0,0 +1,340 @@\n+//! Pick two children of a parent scope for pairwise voting.\n+//!\n+//! Pair selection prefers **bridge** votes — comparisons between items in\n+//! different connected components of the voted-pairs graph — so the pool\n+//! merges into one ranking group before refining within it.\n+\n+use rand::seq::SliceRandom;\n+use std::collections::{HashMap, HashSet};\n+\n+use crate::{\n+ path_types::ItemId,\n+ ranking::connected_components_from_voted_pairs,\n+ reducer::{GlobalTree, GroupState},\n+};\n+\n+fn pairs_match(a: &ItemId, b: &ItemId, x: &ItemId, y: &ItemId) -> bool {\n+ (a == x && b == y) || (a == y && b == x)\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+/// Component id per pool item: voted-pairs graph components plus one id per\n+/// never-voted child.\n+fn component_ids(group: &GroupState, pool: &[ItemId]) -> HashMap {\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+\n+ let mut out: HashMap = HashMap::new();\n+ for (comp_idx, comp) in comps.iter().enumerate() {\n+ for &idx in comp {\n+ if idx < n {\n+ out.insert(group.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+ out.insert(group.idx_to_item[idx].clone(), next);\n+ next += 1;\n+ }\n+ }\n+ for item in pool {\n+ out.entry(item.clone()).or_insert_with(|| {\n+ let id = next;\n+ next += 1;\n+ id\n+ });\n+ }\n+ out\n+}\n+\n+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]\n+enum PairPriority {\n+ /// Unvoted edge between two components — grows the ranking group.\n+ BridgeUnvoted = 0,\n+ /// Unvoted edge inside one component — refines order.\n+ WithinUnvoted = 1,\n+ /// Re-vote across components (rare once merged).\n+ BridgeVoted = 2,\n+ /// Re-vote within a component.\n+ WithinVoted = 3,\n+}\n+\n+fn pair_priority(\n+ group: &GroupState,\n+ components: &HashMap,\n+ a: &ItemId,\n+ b: &ItemId,\n+) -> PairPriority {\n+ let voted = pair_is_voted(group, a, b);\n+ let bridge = components.get(a) != components.get(b);\n+ match (bridge, voted) {\n+ (true, false) => PairPriority::BridgeUnvoted,\n+ (false, false) => PairPriority::WithinUnvoted,\n+ (true, true) => PairPriority::BridgeVoted,\n+ (false, true) => PairPriority::WithinVoted,\n+ }\n+}\n+\n+/// All unordered pairs from `pool`, optionally skipping `exclude`.\n+fn candidate_pairs(\n+ pool: &[ItemId],\n+ exclude: Option<(&ItemId, &ItemId)>,\n+) -> Vec<(ItemId, ItemId)> {\n+ let mut out = Vec::new();\n+ for i in 0..pool.len() {\n+ for j in (i + 1)..pool.len() {\n+ let a = &pool[i];\n+ let b = &pool[j];\n+ if a == b {\n+ continue;\n+ }\n+ if exclude.is_some_and(|(x, y)| pairs_match(a, b, x, y)) {\n+ continue;\n+ }\n+ out.push((a.clone(), b.clone()));\n+ }\n+ }\n+ out\n+}\n+\n+/// Pick the next pair to vote on within `pool`.\n+///\n+/// 1. Prefer unvoted **bridge** pairs (connect separate ranking components).\n+/// 2. Then unvoted within-component pairs (refinement).\n+/// 3. Then already-voted pairs (re-compare).\n+pub fn suggest_next_pair_in_pool(\n+ group: &GroupState,\n+ pool: &[ItemId],\n+ exclude: Option<(&ItemId, &ItemId)>,\n+) -> Option<(ItemId, ItemId)> {\n+ let candidates = candidate_pairs(pool, exclude);\n+ if candidates.is_empty() {\n+ return None;\n+ }\n+ let components = component_ids(group, pool);\n+ let best = candidates\n+ .iter()\n+ .map(|(a, b)| (pair_priority(group, &components, a, b), (a, b)))\n+ .min_by_key(|(p, _)| *p)?\n+ .0;\n+ let best_pairs: Vec<(ItemId, ItemId)> = candidates\n+ .into_iter()\n+ .filter(|(a, b)| pair_priority(group, &components, a, b) == best)\n+ .collect();\n+ best_pairs.choose(&mut rand::thread_rng()).cloned()\n+}\n+\n+/// Random distinct pair from `children` (legacy pair.rs behavior).\n+pub fn random_pair(children: &[ItemId]) -> Option<(ItemId, ItemId)> {\n+ if children.len() < 2 {\n+ return None;\n+ }\n+ let left = children.choose(&mut rand::thread_rng())?;\n+ let mut right = children.choose(&mut rand::thread_rng())?;\n+ let mut guard = 0;\n+ while left == right && guard < 32 {\n+ right = children.choose(&mut rand::thread_rng())?;\n+ guard += 1;\n+ }\n+ if left == right {\n+ return None;\n+ }\n+ Some((left.clone(), right.clone()))\n+}\n+\n+/// Sorted children of `parent` from the global tree.\n+pub fn children_of(tree: &GlobalTree, parent: &ItemId) -> Vec {\n+ let Some(node) = tree.get(parent) else {\n+ return Vec::new();\n+ };\n+ let mut children: Vec = node.children.iter().cloned().collect();\n+ children.sort_by(|a, b| a.as_str().cmp(b.as_str()));\n+ children\n+}\n+\n+/// Resolve a pair to compare under `parent`.\n+pub fn resolve_pair(\n+ tree: &GlobalTree,\n+ parent: &ItemId,\n+ left: Option<&ItemId>,\n+ right: Option<&ItemId>,\n+) -> Result<(ItemId, ItemId), PairError> {\n+ let children = children_of(tree, parent);\n+ if children.len() < 2 {\n+ return Err(PairError::TooFewChildren);\n+ }\n+ let child_set: HashSet<_> = children.iter().collect();\n+\n+ match (left, right) {\n+ (Some(l), Some(r)) => {\n+ if l == r {\n+ return Err(PairError::SameItem);\n+ }\n+ if !child_set.contains(l) || !child_set.contains(r) {\n+ return Err(PairError::NotChild);\n+ }\n+ Ok((l.clone(), r.clone()))\n+ }\n+ (None, None) => {\n+ let group = tree\n+ .get(parent)\n+ .map(|n| &n.local_ranking)\n+ .cloned()\n+ .unwrap_or_default();\n+ suggest_next_pair_in_pool(&group, &children, None).ok_or(PairError::NoPair)\n+ }\n+ _ => Err(PairError::IncompletePair),\n+ }\n+}\n+\n+#[derive(Debug, Clone, PartialEq, Eq)]\n+pub enum PairError {\n+ TooFewChildren,\n+ SameItem,\n+ NotChild,\n+ IncompletePair,\n+ NoPair,\n+}\n+\n+impl PairError {\n+ pub fn status_message(&self) -> (&'static str, axum::http::StatusCode) {\n+ match self {\n+ Self::TooFewChildren => (\n+ \"parent needs at least 2 children to vote\",\n+ axum::http::StatusCode::BAD_REQUEST,\n+ ),\n+ Self::SameItem => (\n+ \"left and right must differ\",\n+ axum::http::StatusCode::BAD_REQUEST,\n+ ),\n+ Self::NotChild => (\n+ \"left and right must be children of parent\",\n+ axum::http::StatusCode::BAD_REQUEST,\n+ ),\n+ Self::IncompletePair => (\n+ \"provide both left and right, or neither\",\n+ axum::http::StatusCode::BAD_REQUEST,\n+ ),\n+ Self::NoPair => (\n+ \"no pair available\",\n+ axum::http::StatusCode::BAD_REQUEST,\n+ ),\n+ }\n+ }\n+}\n+\n+#[cfg(test)]\n+mod tests {\n+ use super::*;\n+ use crate::reducer::{GlobalTree, VoteData};\n+\n+ fn seed_children(parent: &ItemId, ids: &[&str]) -> GlobalTree {\n+ let mut tree = GlobalTree::new();\n+ tree.ensure_path(parent);\n+ for id in ids {\n+ let child = ItemId::parse(id).unwrap();\n+ tree.ensure_path(&child);\n+ if let Some(p) = tree.nodes.get_mut(parent) {\n+ p.children.insert(child);\n+ }\n+ }\n+ tree\n+ }\n+\n+ fn pair_set(pair: &(ItemId, ItemId)) -> HashSet<&str> {\n+ [pair.0.as_str(), pair.1.as_str()].into_iter().collect()\n+ }\n+\n+ #[test]\n+ fn suggest_prefers_unvoted_pair() {\n+ let parent = ItemId::parse(\"reddit.com/r/rust\").unwrap();\n+ let mut tree = seed_children(\n+ &parent,\n+ &[\n+ \"reddit.com/r/rust/a\",\n+ \"reddit.com/r/rust/b\",\n+ \"reddit.com/r/rust/c\",\n+ ],\n+ );\n+ let vote =\n+ VoteData::from_recorded(1, \"reddit.com/r/rust/a\", \"reddit.com/r/rust/b\", 2, 1).unwrap();\n+ tree.apply_vote(&parent, vote);\n+ let group = tree.get(&parent).unwrap().local_ranking.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() == \"reddit.com/r/rust/a\" && r.as_str() == \"reddit.com/r/rust/b\")\n+ || (l.as_str() == \"reddit.com/r/rust/b\" && r.as_str() == \"reddit.com/r/rust/a\");\n+ assert!(!voted_ab);\n+ }\n+\n+ #[test]\n+ fn suggest_bridges_separate_components() {\n+ let parent = ItemId::parse(\"reddit.com/r/rust\").unwrap();\n+ let mut tree = seed_children(\n+ &parent,\n+ &[\n+ \"reddit.com/r/rust/a\",\n+ \"reddit.com/r/rust/b\",\n+ \"reddit.com/r/rust/c\",\n+ \"reddit.com/r/rust/d\",\n+ ],\n+ );\n+ let ab = VoteData::from_recorded(1, \"reddit.com/r/rust/a\", \"reddit.com/r/rust/b\", 2, 1).unwrap();\n+ let cd = VoteData::from_recorded(2, \"reddit.com/r/rust/c\", \"reddit.com/r/rust/d\", 2, 1).unwrap();\n+ tree.apply_vote(&parent, ab);\n+ tree.apply_vote(&parent, cd);\n+ let group = tree.get(&parent).unwrap().local_ranking.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+ let from_ab = chosen.contains(\"reddit.com/r/rust/a\") || chosen.contains(\"reddit.com/r/rust/b\");\n+ let from_cd = chosen.contains(\"reddit.com/r/rust/c\") || chosen.contains(\"reddit.com/r/rust/d\");\n+ assert!(from_ab && from_cd, \"expected bridge pair, got {:?}\", chosen);\n+ }\n+\n+ #[test]\n+ fn suggest_connects_isolate_to_existing_component() {\n+ let parent = ItemId::parse(\"reddit.com/r/rust\").unwrap();\n+ let mut tree = seed_children(\n+ &parent,\n+ &[\n+ \"reddit.com/r/rust/a\",\n+ \"reddit.com/r/rust/b\",\n+ \"reddit.com/r/rust/c\",\n+ ],\n+ );\n+ let ab = VoteData::from_recorded(1, \"reddit.com/r/rust/a\", \"reddit.com/r/rust/b\", 2, 1).unwrap();\n+ tree.apply_vote(&parent, ab);\n+ let group = tree.get(&parent).unwrap().local_ranking.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+ assert!(chosen.contains(\"reddit.com/r/rust/c\"));\n+ assert!(chosen.contains(\"reddit.com/r/rust/a\") || chosen.contains(\"reddit.com/r/rust/b\"));\n+ }\n+\n+ #[test]\n+ fn resolve_pair_picks_from_pool() {\n+ let parent = ItemId::parse(\"reddit.com/r/rust\").unwrap();\n+ let tree = seed_children(&parent, &[\"reddit.com/r/rust/a\", \"reddit.com/r/rust/b\"]);\n+ let pair = resolve_pair(&tree, &parent, None, None).unwrap();\n+ let pool: HashSet<_> = [\"reddit.com/r/rust/a\", \"reddit.com/r/rust/b\"]\n+ .into_iter()\n+ .collect();\n+ assert!(pool.contains(pair.0.as_str()));\n+ assert!(pool.contains(pair.1.as_str()));\n+ }\n+}\ndiff --git a/server/src/path_types.rs b/server/src/path_types.rs\nindex 12dce9888f5cd4e1a0974d12d6468368d0f775b9..a0d1a028b8bd3c5d1c714dea3ec597d1ac39e1bc 100644\n--- a/server/src/path_types.rs\n+++ b/server/src/path_types.rs\n@@ -40,6 +40,22 @@ impl ItemId {\n Self::canonicalize(raw_url).map(Self)\n }\n \n+ /// Normalize strings from forms, events, and Reddit imports into the same\n+ /// stored id shape (e.g. drop post title slug after comment id).\n+ pub fn from_storage(s: &str) -> Option {\n+ let t = s.trim();\n+ if t.is_empty() {\n+ return None;\n+ }\n+ if t.contains(\"://\") || t.starts_with(\"r/\") {\n+ return Self::from_url(t).or_else(|| Self::parse(t));\n+ }\n+ if t.starts_with(\"reddit.com/\") && t.contains(\"/comments/\") {\n+ return Self::from_url(t).or_else(|| Self::parse(t));\n+ }\n+ Self::parse(t).or_else(|| Self::from_url(t))\n+ }\n+\n /// Map legacy scope keys (`\"\"`, `\"rust\"`) to fractal parent nodes.\n pub fn from_legacy_scope(raw: &str) -> Self {\n let s = raw.trim();\n@@ -324,6 +340,12 @@ mod tests {\n assert_eq!(id.as_str(), \"reddit.com/r/amitheasshole\");\n }\n \n+ #[test]\n+ fn from_storage_strips_post_title_slug() {\n+ let id = ItemId::from_storage(\"reddit.com/r/rust/comments/aaa/announcing_rust_199\").unwrap();\n+ assert_eq!(id.as_str(), \"reddit.com/r/rust/comments/aaa\");\n+ }\n+\n #[test]\n fn from_browse_uri_strips_prefix() {\n let id = ItemId::from_browse_uri(\"/~/https://reddit.com/r/rust\").unwrap();\ndiff --git a/server/src/reddit.rs b/server/src/reddit.rs\nindex 1168ec2afc77c092514eec91b513bac301cbe225..626454e5a2f638734193b5190a2beea286af85b6 100644\n--- a/server/src/reddit.rs\n+++ b/server/src/reddit.rs\n@@ -567,7 +567,7 @@ fn parse_children(_parent: &ItemId, payload: &Value) -> Vec<(ItemId, Value)> {\n _ => continue,\n };\n let path = format!(\"reddit.com{}\", permalink.trim_end_matches('/'));\n- if let Some(id) = ItemId::parse(&path) {\n+ if let Some(id) = ItemId::from_storage(&path) {\n out.push((id, child.clone()));\n }\n }\ndiff --git a/server/src/reducer.rs b/server/src/reducer.rs\nindex 336e78b77d3ab59361b89af5c9868e13da4ac962..fc23f41137d7df33997afe19c533505c250cc305 100644\n--- a/server/src/reducer.rs\n+++ b/server/src/reducer.rs\n@@ -28,8 +28,8 @@ impl VoteData {\n ratio_left: i32,\n ratio_right: i32,\n ) -> Option {\n- let a = ItemId::parse(a)?;\n- let b = ItemId::parse(b)?;\n+ let a = ItemId::from_storage(a)?;\n+ let b = ItemId::from_storage(b)?;\n if a == b {\n return None;\n }\n@@ -85,8 +85,8 @@ impl GroupState {\n }\n \n pub fn apply_vote(&mut self, mut vote: VoteData) {\n- vote.a = ItemId::parse(vote.a.as_str()).unwrap_or_else(|| vote.a.clone());\n- vote.b = ItemId::parse(vote.b.as_str()).unwrap_or_else(|| vote.b.clone());\n+ vote.a = ItemId::from_storage(vote.a.as_str()).unwrap_or(vote.a.clone());\n+ vote.b = ItemId::from_storage(vote.b.as_str()).unwrap_or(vote.b.clone());\n if vote.ratio_left < 0 {\n vote.ratio_left = 0;\n }\ndiff --git a/server/src/state.rs b/server/src/state.rs\nindex d238701208a1c708b94a778a6a2e1891a678ecbc..4c3008e73cc74d8483a2064a0a280e73d82a01ec 100644\n--- a/server/src/state.rs\n+++ b/server/src/state.rs\n@@ -18,7 +18,7 @@ pub fn parse_item_param(raw: &str) -> ItemId {\n if s.is_empty() {\n return ItemId::root();\n }\n- ItemId::from_url(s).or_else(|| ItemId::parse(s)).unwrap_or_else(|| ItemId::opaque(s))\n+ ItemId::from_storage(s).unwrap_or_else(|| ItemId::opaque(s))\n }\n \n /// Legacy: normalize raw ranking subject into a scope key for old event replay.\ndiff --git a/server/src/ui_action.rs b/server/src/ui_action.rs\nindex 53581e1362bfcc5dfb4ae3069c41ea6f7be41437..237411a689fb10ad1b7022ea66aee1969c7507ec 100644\n--- a/server/src/ui_action.rs\n+++ b/server/src/ui_action.rs\n@@ -31,9 +31,9 @@ pub enum HtmlUiAction {\n /// Parent node [`ItemId`] string; empty = tree root.\n #[serde(default)]\n scope: String,\n- /// After vote, navigate here (vote compare page).\n+ /// Posted from `/vote` compare UI — morph edge history in place.\n #[serde(default)]\n- next: String,\n+ vote_compare: bool,\n },\n /// Parse pasted Reddit URL/path; redirect to subreddit ranking on success.\n ParseQuery {\n@@ -98,7 +98,7 @@ mod tests {\n ratio_left: 60,\n ratio_right: 40,\n scope: \"parent\".into(),\n- next: String::new(),\n+ vote_compare: false,\n }\n );\n }\n@@ -129,7 +129,7 @@ mod tests {\n ratio_left: 2,\n ratio_right: 1,\n scope: \"amitheasshole\".into(),\n- next: String::new(),\n+ vote_compare: false,\n }\n );\n }\n@@ -156,7 +156,7 @@ mod tests {\n ratio_left: 2,\n ratio_right: 1,\n scope: String::new(),\n- next: String::new(),\n+ vote_compare: false,\n }\n );\n }\ndiff --git a/server/static/sorter.css b/server/static/sorter.css\nindex 3c2cec5cb5094013387147c621d75bd341bc06cc..b95718ce463b200a5667d3014dac2119836a0bef 100644\n--- a/server/static/sorter.css\n+++ b/server/static/sorter.css\n@@ -289,11 +289,27 @@ h1 {\n }\n \n .vote-compare-nav {\n+ margin: 1rem 0 0.5rem;\n+}\n+\n+.vote-compare-actions {\n display: flex;\n- justify-content: space-between;\n+ flex-wrap: wrap;\n align-items: center;\n- gap: 1rem;\n- margin: 1rem 0;\n+ gap: 0.75rem;\n+ margin-top: 0.5rem;\n+}\n+\n+.vote-compare-actions .btn-secondary {\n+ margin-top: 0;\n+ display: inline-block;\n+ text-decoration: none;\n+ line-height: 1.4;\n+}\n+\n+.vote-compare-actions .vote-compare-next.is-disabled {\n+ opacity: 0.6;\n+ cursor: default;\n }\n \n .vote-compare-next {\ndiff --git a/server/static/sorter_ui.js b/server/static/sorter_ui.js\nindex c8d7c3ef2413399ced7898a7edb3e7a2c8e16163..ab15d27f508cc6f5fbca9d8926fd0ca26d64857b 100644\n--- a/server/static/sorter_ui.js\n+++ b/server/static/sorter_ui.js\n@@ -104,11 +104,10 @@\n if (f.getAttribute('data-navigate') === 'full') return;\n e.preventDefault();\n await postUiForm(f);\n- if (f.id === 'vote-form' || f.id === 'vote-compare-form') {\n+ if (f.id === 'vote-form') {\n f.reset();\n- var slider = f.querySelector('#vote-preference-slider');\n- if (slider) slider.value = '50';\n- initVoteSlider();\n+ var firstField = f.querySelector('input[type=\"text\"]');\n+ if (firstField) firstField.focus();\n }\n });\n }\ndiff --git a/server/tests/integration_ui.rs b/server/tests/integration_ui.rs\nindex df7d9ab357531c5146d0b326c149fdaa6b531a4a..56d2db313b313ffce07eff38a8ccdaa2fbb9498f 100644\n--- a/server/tests/integration_ui.rs\n+++ b/server/tests/integration_ui.rs\n@@ -25,6 +25,53 @@ async fn start_test_server() -> (SocketAddr, TempDir) {\n (addr, tmp)\n }\n \n+#[tokio::test]\n+async fn post_ui_vote_compare_morphs_edge_history() {\n+ let (addr, _tmp) = start_test_server().await;\n+ let parent = \"reddit.com/r/rust\";\n+ let a = \"reddit.com/r/rust/comments/aaa/announcing_rust_199\";\n+ let b = \"reddit.com/r/rust/comments/bbb/what_are_you_working_on\";\n+\n+ let rpc = serde_json::json!({\n+ \"action\": \"record_vote\",\n+ \"a\": a,\n+ \"b\": b,\n+ \"ratio_left\": {\"$form:i32\": \"ratio_left\"},\n+ \"ratio_right\": {\"$form:i32\": \"ratio_right\"},\n+ \"scope\": parent,\n+ \"vote_compare\": true,\n+ })\n+ .to_string();\n+ let mut form = HashMap::new();\n+ form.insert(UI_RPC_FIELD.to_string(), rpc);\n+ form.insert(\"ratio_left\".into(), \"70\".into());\n+ form.insert(\"ratio_right\".into(), \"30\".into());\n+\n+ let client = reqwest::Client::new();\n+ let body = client\n+ .post(format!(\"http://{addr}/ui\"))\n+ .form(&form)\n+ .send()\n+ .await\n+ .unwrap()\n+ .text()\n+ .await\n+ .unwrap();\n+\n+ assert!(\n+ body.contains(\"vote-edge-history\"),\n+ \"expected edge history morph, got: {body}\"\n+ );\n+ assert!(\n+ body.contains(\"70:30\"),\n+ \"expected recorded ratio in morph, got: {body}\"\n+ );\n+ assert!(\n+ !body.contains(\"no votes on this pair yet\"),\n+ \"should not show empty edge history after vote, got: {body}\"\n+ );\n+}\n+\n #[tokio::test]\n async fn post_ui_record_vote_morphs_ranking_and_persists() {\n let (addr, tmp) = start_test_server().await;\ndiff --git a/test/reddit_import.clj b/test/reddit_import.clj\nindex 45a2a19f20799d77e84d8aa64735ab5e7e45f97c..b476488526252c13fd73bdda76e5201678e4a714 100644\n--- a/test/reddit_import.clj\n+++ b/test/reddit_import.clj\n@@ -2,9 +2,8 @@\n (:require [babashka.process :as process]\n [clojure.java.io :as io]\n [clojure.string :as str]\n- [clojure.test :refer [deftest is testing]])\n- (:import [com.sun.net.httpserver HttpServer HttpHandler HttpExchange]\n- [java.net InetSocketAddress]))\n+ [clojure.test :refer [deftest is testing]]\n+ [test.support.mock-reddit :as mock-reddit]))\n \n (defn- repo-root []\n (.getCanonicalPath (io/file (System/getProperty \"user.dir\"))))\n@@ -13,29 +12,6 @@\n (with-open [s (java.net.ServerSocket. 0)]\n (.getLocalPort s)))\n \n-(defn- start-mock-reddit [port fixtures-dir]\n- (let [about (.getBytes (slurp (io/file fixtures-dir \"r_rust_about.json\")) \"UTF-8\")\n- listing (.getBytes (slurp (io/file fixtures-dir \"r_rust_listing.json\")) \"UTF-8\")\n- server (HttpServer/create (InetSocketAddress. \"127.0.0.1\" port) 0)\n- handler\n- (proxy [HttpHandler] []\n- (handle [^HttpExchange exchange]\n- ;; Route by path: `/r//about.json` is the subreddit entity,\n- ;; `/r/.json` is the children listing.\n- (let [path (.getPath (.getRequestURI exchange))\n- body (if (str/includes? path \"/about\")\n- about\n- listing)]\n- (.sendResponseHeaders exchange 200 (alength body))\n- (let [out (.getResponseBody exchange)]\n- (.write out body)\n- (.close out)))))]\n- (.createContext server \"/\" handler)\n- (.setExecutor server nil)\n- (.start server)\n- (fn stop []\n- (.stop server 0))))\n-\n (defn- wait-health [base-url ms]\n (let [deadline (+ (System/currentTimeMillis) ms)\n url (str base-url \"/healthz\")]\n@@ -100,7 +76,7 @@\n (deftest reddit-fetch-via-mock-api\n (testing \"Fetch more queues import; event log stores full payload; page shows title\"\n (let [root (repo-root)\n- fixtures (str root \"/test/fixtures/reddit\")\n+ fixtures (mock-reddit/fixtures-dir root)\n data-dir (.getAbsolutePath\n (doto (io/file (System/getProperty \"java.io.tmpdir\")\n (str \"sorter2-reddit-\" (System/currentTimeMillis)))\n@@ -110,7 +86,7 @@\n reddit-base (str \"http://127.0.0.1:\" reddit-port)\n app-base (str \"http://127.0.0.1:\" app-port)\n bin (str root \"/target/release/sorter2-server\")\n- stop-mock (start-mock-reddit reddit-port fixtures)]\n+ stop-mock (mock-reddit/start-mock-reddit reddit-port fixtures)]\n (try\n (is (zero? (:exit (process/shell {:dir root}\n \"cargo\" \"build\" \"--release\" \"--package\" \"sorter2-server\")))\ndiff --git a/test/support/mock_reddit.clj b/test/support/mock_reddit.clj\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..5efa92db3e1f79b8f423a2f1adcbda959123c1ad\n--- /dev/null\n+++ b/test/support/mock_reddit.clj\n@@ -0,0 +1,35 @@\n+(ns test.support.mock-reddit\n+ \"In-process HTTP stub for Reddit API fixtures (`test/fixtures/reddit/`).\"\n+ (:require [clojure.java.io :as io]\n+ [clojure.string :as str])\n+ (:import [com.sun.net.httpserver HttpServer HttpHandler HttpExchange]\n+ [java.net InetSocketAddress]))\n+\n+(defn fixtures-dir\n+ ([] (fixtures-dir (System/getProperty \"user.dir\")))\n+ ([root] (str root \"/test/fixtures/reddit\")))\n+\n+(defn start-mock-reddit\n+ \"Start a mock Reddit API on `port`. Returns a zero-arg `stop` function.\"\n+ ([port] (start-mock-reddit port (fixtures-dir)))\n+ ([port dir]\n+ (let [about (.getBytes (slurp (io/file dir \"r_rust_about.json\")) \"UTF-8\")\n+ listing (.getBytes (slurp (io/file dir \"r_rust_listing.json\")) \"UTF-8\")\n+ server (HttpServer/create (InetSocketAddress. \"127.0.0.1\" port) 0)\n+ handler\n+ (proxy [HttpHandler] []\n+ (handle [^HttpExchange exchange]\n+ ;; `/r//about.json` → subreddit entity; `/r/.json` → listing.\n+ (let [path (.getPath (.getRequestURI exchange))\n+ body (if (str/includes? path \"/about\")\n+ about\n+ listing)]\n+ (.sendResponseHeaders exchange 200 (alength body))\n+ (let [out (.getResponseBody exchange)]\n+ (.write out body)\n+ (.close out)))))]\n+ (.createContext server \"/\" handler)\n+ (.setExecutor server nil)\n+ (.start server)\n+ (fn stop []\n+ (.stop server 0)))))\ndiff --git a/test/vote_compare.clj b/test/vote_compare.clj\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..fbc00281e466a1ba0833193c7b96fa30aeb45a5c\n--- /dev/null\n+++ b/test/vote_compare.clj\n@@ -0,0 +1,101 @@\n+(ns test.vote-compare\n+ (:require [babashka.process :as process]\n+ [clojure.java.io :as io]\n+ [clojure.string :as str]\n+ [clojure.test :refer [deftest is testing]]\n+ [com.blockether.spel.core :as core]\n+ [com.blockether.spel.locator :as loc]\n+ [com.blockether.spel.page :as page]\n+ [test.support.mock-reddit :as mock-reddit])\n+ (:import [java.net URLEncoder]))\n+\n+(defn- repo-root []\n+ (.getCanonicalPath (io/file (System/getProperty \"user.dir\"))))\n+\n+(defn- pick-port []\n+ (with-open [s (java.net.ServerSocket. 0)]\n+ (.getLocalPort s)))\n+\n+(defn- wait-health [base-url ms]\n+ (let [deadline (+ (System/currentTimeMillis) ms)\n+ url (str base-url \"/healthz\")]\n+ (loop []\n+ (let [resp (try\n+ (process/shell {:out :string :err :string}\n+ \"curl\" \"-sf\" url)\n+ (catch Exception _ nil))]\n+ (if (and resp (zero? (:exit resp)) (= \"ok\" (str/trim (:out resp \"\"))))\n+ true\n+ (if (< (System/currentTimeMillis) deadline)\n+ (do (Thread/sleep 200) (recur))\n+ false))))))\n+\n+(defn- curl-fetch-children [base item]\n+ (process/shell {:out :string :err :string}\n+ \"curl\" \"-sfN\" \"--max-time\" \"20\"\n+ \"-X\" \"POST\" (str base \"/ui\")\n+ \"--data-urlencode\"\n+ (str \"__rpc__={\\\"action\\\":\\\"fetch_entity\\\",\\\"item\\\":\\\"\" item\n+ \"\\\",\\\"kind\\\":\\\"children\\\"}\")))\n+\n+(defn- vote-page-url [base parent]\n+ (str base \"/vote?parent=\"\n+ (URLEncoder/encode parent \"UTF-8\")))\n+\n+(deftest vote-compare-shows-recorded-vote-after-post\n+ (testing \"post vote on /vote morphs edge history (mock Reddit children seeded)\"\n+ (let [root (repo-root)\n+ fixtures (mock-reddit/fixtures-dir root)\n+ data-dir (.getAbsolutePath\n+ (doto (io/file (System/getProperty \"java.io.tmpdir\")\n+ (str \"sorter2-vote-\" (System/currentTimeMillis)))\n+ (.mkdirs)))\n+ reddit-port (pick-port)\n+ app-port (pick-port)\n+ reddit-base (str \"http://127.0.0.1:\" reddit-port)\n+ app-base (str \"http://127.0.0.1:\" app-port)\n+ bin (str root \"/target/release/sorter2-server\")\n+ stop-mock (mock-reddit/start-mock-reddit reddit-port fixtures)]\n+ (try\n+ (is (zero? (:exit (process/shell {:dir root}\n+ \"cargo\" \"build\" \"--release\" \"--package\" \"sorter2-server\")))\n+ \"release build succeeds\")\n+ (let [proc (process/process {:dir root\n+ :env (into (into {} (System/getenv))\n+ {\"SORTER2_SKIP_DOTENV\" \"1\"\n+ \"SORTER2_DATA_DIR\" data-dir\n+ \"SORTER2_EVENT_LOG\" (str data-dir \"/events.jsonl\")\n+ \"PORT\" (str app-port)\n+ \"REDDIT_API_BASE\" reddit-base\n+ \"REDDIT_OAUTH_BASE\" reddit-base\n+ \"REDDIT_CLIENT_ID\" \"\"\n+ \"REDDIT_CLIENT_SECRET\" \"\"\n+ \"REDDIT_APP_ID\" \"\"\n+ \"REDDIT_APP_SECRET\" \"\"})\n+ :out :string\n+ :err :string}\n+ bin)]\n+ (try\n+ (is (wait-health app-base 20000) \"app healthz\")\n+ (let [fetch (curl-fetch-children app-base \"reddit.com/r/rust\")]\n+ (is (zero? (:exit fetch)) \"fetch posts via mock Reddit\")\n+ (is (str/includes? (:out fetch) \"Idiomorph.morph\")))\n+ (core/with-testing-page [pg]\n+ (page/navigate pg (vote-page-url app-base \"reddit.com/r/rust\"))\n+ (page/wait-for-selector pg \"#vote-compare-form\")\n+ (let [before (loc/text-content (page/locator pg \"#vote-edge-history-region\"))]\n+ (is (str/includes? before \"no votes on this pair yet\")\n+ \"empty edge history before first vote\"))\n+ (loc/click (page/get-by-test-id pg \"vote-post\"))\n+ (page/wait-for-selector pg \".vote-edge-history-title\")\n+ (let [after (loc/text-content (page/locator pg \"#vote-edge-history-region\"))]\n+ (is (str/includes? after \"votes on this pair\")\n+ \"shows edge history title after vote\")\n+ (is (str/includes? after \"50:50\")\n+ \"shows submitted ratio after vote\")\n+ (is (not (str/includes? after \"no votes on this pair yet\"))\n+ \"does not revert to empty edge history\")))\n+ (finally\n+ (process/destroy proc))))\n+ (finally\n+ (stop-mock))))))\n\n\nSide B — contributor: tommy-mor\nSide B — commit message:\n[40b975bf] nice\n\nSide B — unified diff (full patch):\ndiff --git a/Cargo.lock b/Cargo.lock\nindex 266e876bb7ccbe788beb1d5bd53ad5b45ee5825b..2cea973082716e761ef6f5dd5886acc08ff9aac0 100644\n--- a/Cargo.lock\n+++ b/Cargo.lock\n@@ -222,6 +222,12 @@ dependencies = [\n \"syn\",\n ]\n \n+[[package]]\n+name = \"dotenvy\"\n+version = \"0.15.7\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b\"\n+\n [[package]]\n name = \"encoding_rs\"\n version = \"0.8.35\"\n@@ -1238,6 +1244,7 @@ version = \"0.0.1\"\n dependencies = [\n \"axum\",\n \"axum-extra\",\n+ \"dotenvy\",\n \"maud\",\n \"reqwest\",\n \"serde\",\ndiff --git a/server/Cargo.toml b/server/Cargo.toml\nindex 4677fedcb45292eebebe7e9cf6ce2f5738f18ddf..bd600138b613bd0f546bdec217a5334cdcb20aa5 100644\n--- a/server/Cargo.toml\n+++ b/server/Cargo.toml\n@@ -17,6 +17,7 @@ tower-http = { version = \"0.5\", features = [\"trace\"] }\n tracing = \"0.1\"\n tracing-subscriber = { version = \"0.3\", features = [\"env-filter\"] }\n reqwest = { version = \"0.12\", features = [\"json\"] }\n+dotenvy = \"0.15\"\n \n [dev-dependencies]\n reqwest = { version = \"0.12\", features = [\"json\"] }\ndiff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs\nindex d2024bd4582bcc8482b461b2ba4fedbd8bff7c66..b33a84e8bb5e817b26592868d88090e6d664d950 100644\n--- a/server/src/api/ui_html.rs\n+++ b/server/src/api/ui_html.rs\n@@ -6,7 +6,7 @@ use axum::{\n use std::collections::HashMap;\n \n use crate::{\n- html::{input_panel, js_string_literal, ranking_panel, JsBuilder},\n+ html::{entity_section, input_panel, js_string_literal, ranking_panel, JsBuilder},\n parser::parse_reddit_url,\n path_types::ItemId,\n reddit::ensure_partial_tree,\n@@ -87,6 +87,20 @@ pub async fn post_ui_html(\n .into_response()\n }\n },\n+ HtmlUiAction::FetchEntity { item } => {\n+ let id = parse_item_param(&item);\n+ if id.is_root() {\n+ return ui_js_warn(\"nothing to fetch for the root\").into_response();\n+ }\n+ state.queue_entity_fetch(id.clone());\n+ let tree = state.tree.read().await;\n+ let empty = crate::reducer::NodeState::default();\n+ let node = tree.get(&id).unwrap_or(&empty);\n+ let panel = entity_section(&id, node, true);\n+ JsBuilder::new()\n+ .morph_selector(\"#entity-section\", panel)\n+ .into_response()\n+ },\n }\n }\n \ndiff --git a/server/src/events.rs b/server/src/events.rs\nindex ed5be6b13b9d46e838831d6ce0f96f569b401730..07ce24b5e56cf72b0b442c3c3241efbf6c3b006a 100644\n--- a/server/src/events.rs\n+++ b/server/src/events.rs\n@@ -1,4 +1,5 @@\n use serde::{Deserialize, Serialize};\n+use serde_json::Value;\n \n #[derive(Debug, Clone, Serialize, Deserialize)]\n #[serde(tag = \"type\", rename_all = \"snake_case\")]\n@@ -18,4 +19,10 @@ pub enum Event {\n },\n /// Register a node path in the fractal tree (no external fetch).\n NodeEnsured { id: String },\n+ /// Full upstream API payload for a node (domain-specific view derived at replay/render time).\n+ EntityImported {\n+ id: String,\n+ ts: i64,\n+ payload: Value,\n+ },\n }\ndiff --git a/server/src/html/mod.rs b/server/src/html/mod.rs\nindex df6505021d9f446c2b453e20e3eb3cf696a111f9..caf1309c8d93b47104499c57f9cc35ee7631fbb9 100644\n--- a/server/src/html/mod.rs\n+++ b/server/src/html/mod.rs\n@@ -10,6 +10,7 @@ use crate::{\n form_template::template_json_compact,\n path_types::ItemId,\n ranking::{top_bottom, RankedItem},\n+ reddit::is_fetchable,\n reducer::{GroupState, NodeState},\n state::AppState,\n ui_action::UI_RPC_FIELD,\n@@ -151,7 +152,7 @@ pub fn breadcrumb_path(item: &ItemId) -> Markup {\n fn entity_panel(node: &NodeState) -> Markup {\n html! {\n @if let Some(data) = &node.data {\n- section id=\"entity-panel\" class=\"demo-panel entity-card\" {\n+ div id=\"entity-panel\" class=\"entity-card\" {\n h2 { (data.title) }\n @if let Some(author) = &data.author {\n p class=\"muted small\" { \"by \" (author) }\n@@ -164,6 +165,42 @@ fn entity_panel(node: &NodeState) -> Markup {\n }\n }\n \n+/// Reddit/API import control — only shown on fetchable pages; never auto-fires.\n+pub fn fetch_entity_panel(item: &ItemId, has_data: bool, fetching: bool) -> Markup {\n+ if !is_fetchable(item) {\n+ return html! {};\n+ }\n+ let label = if fetching {\n+ \"Fetching…\"\n+ } else if has_data {\n+ \"Fetch more\"\n+ } else {\n+ \"Fetch from Reddit\"\n+ };\n+ let rpc = template_json_compact(&serde_json::json!({\n+ \"action\": \"fetch_entity\",\n+ \"item\": item.as_str(),\n+ }))\n+ .expect(\"fetch_entity rpc template\");\n+ html! {\n+ form method=\"post\" action=\"/ui\" id=\"fetch-entity-form\" class=\"fetch-entity-form\" {\n+ input type=\"hidden\" name=(UI_RPC_FIELD) value=(rpc);\n+ button type=\"submit\" class=\"btn-secondary\" disabled=(fetching) { (label) }\n+ }\n+ }\n+}\n+\n+/// Entity card + explicit fetch control (morphed as `#entity-section`).\n+pub fn entity_section(item: &ItemId, node: &NodeState, fetching: bool) -> Markup {\n+ let has_data = node.data.is_some();\n+ html! {\n+ section id=\"entity-section\" class=\"demo-panel\" {\n+ (entity_panel(node))\n+ (fetch_entity_panel(item, has_data, fetching))\n+ }\n+ }\n+}\n+\n fn rank_list(label: &str, items: &[RankedItem], start_rank: usize) -> Markup {\n html! {\n @if !items.is_empty() {\n@@ -260,7 +297,7 @@ async fn item_page(state: AppState, uri: Uri, item: ItemId) -> Markup {\n h1 { \"sorter\" }\n (input_panel(\"\", None))\n (breadcrumb_path(&item))\n- (entity_panel(node))\n+ (entity_section(&item, node, false))\n (ranking_panel(&item, group))\n };\n layout(\"sorter2\", body, views)\n@@ -272,16 +309,5 @@ pub async fn home(State(state): State, uri: Uri) -> impl IntoResponse\n \n pub async fn browse(State(state): State, uri: Uri) -> impl IntoResponse {\n let item = ItemId::from_browse_uri(uri.path()).unwrap_or(ItemId::root());\n- if item.as_str().starts_with(\"reddit.com\") {\n- let needs_fetch = {\n- let tree = state.tree.read().await;\n- tree.get(&item)\n- .map(|n| n.data.is_none())\n- .unwrap_or(true)\n- };\n- if needs_fetch {\n- state.reddit.request_fetch(item.clone());\n- }\n- }\n item_page(state, uri, item).await\n }\ndiff --git a/server/src/main.rs b/server/src/main.rs\nindex c22ec6c9f5358e5ec99fb83210dc351938505a93..1f0cddc39302b35b0cd6a6219f44c9d59202facf 100644\n--- a/server/src/main.rs\n+++ b/server/src/main.rs\n@@ -2,6 +2,10 @@ use sorter2_server::state::AppConfig;\n \n #[tokio::main]\n async fn main() -> Result<(), Box> {\n+ if std::env::var(\"SORTER2_SKIP_DOTENV\").is_err() {\n+ let _ = dotenvy::dotenv();\n+ }\n+\n tracing_subscriber::fmt()\n .with_env_filter(\n tracing_subscriber::EnvFilter::try_from_default_env()\ndiff --git a/server/src/reddit.rs b/server/src/reddit.rs\nindex 90053ad03b1d7c8e94f325dd4ee64c2b4f7da900..ff0f01e57b18af878eb5be3efc47204a7673589d 100644\n--- a/server/src/reddit.rs\n+++ b/server/src/reddit.rs\n@@ -6,11 +6,15 @@ use std::time::{Duration, Instant};\n \n use reqwest::{header, Client, StatusCode};\n use serde::Deserialize;\n+use serde_json::Value;\n use tokio::sync::{mpsc, RwLock};\n \n use crate::{\n+ event_log::EventLog,\n+ events::Event,\n+ html::now_ms,\n path_types::ItemId,\n- reducer::{EntityData, GlobalTree},\n+ reducer::GlobalTree,\n };\n \n /// Bootstrap blank nodes along a URL path so breadcrumbs and voting work before fetch.\n@@ -20,6 +24,8 @@ pub fn ensure_partial_tree(tree: &mut GlobalTree, id: &ItemId) {\n \n pub struct RedditCommand {\n pub id: ItemId,\n+ /// User-initiated fetch bypasses the in-memory \"recently fetched\" cache.\n+ pub force: bool,\n }\n \n #[derive(Clone)]\n@@ -33,19 +39,31 @@ struct RedditCredentials {\n client_secret: String,\n }\n \n+#[derive(Clone)]\n+pub struct RedditApiConfig {\n+ pub api_base: String,\n+ pub oauth_base: String,\n+ pub user_agent: String,\n+ creds: Option,\n+}\n+\n struct OAuthToken {\n access_token: String,\n expires_at: Instant,\n }\n \n impl RedditBroker {\n- pub fn spawn(tree: Arc>, user_agent: &str) -> Self {\n+ pub fn spawn(\n+ tree: Arc>,\n+ event_log: Arc,\n+ config: RedditApiConfig,\n+ ) -> Self {\n let (tx, rx) = mpsc::channel(100);\n \n let mut headers = header::HeaderMap::new();\n headers.insert(\n header::USER_AGENT,\n- header::HeaderValue::from_str(user_agent).expect(\"valid user agent\"),\n+ header::HeaderValue::from_str(&config.user_agent).expect(\"valid user agent\"),\n );\n \n let client = Client::builder()\n@@ -54,22 +72,38 @@ impl RedditBroker {\n .build()\n .expect(\"reqwest client\");\n \n- let creds = RedditCredentials::from_env();\n- tokio::spawn(reddit_worker(rx, tree, client, creds));\n+ tokio::spawn(reddit_worker(rx, tree, event_log, client, config));\n \n Self { tx }\n }\n \n- /// Fire-and-forget: queue a fetch; worker updates the tree when done.\n- pub fn request_fetch(&self, id: ItemId) {\n- let _ = self.tx.try_send(RedditCommand { id });\n+ /// Queue a fetch; drops when the channel is full (backpressure).\n+ pub fn request_fetch(&self, id: ItemId, force: bool) {\n+ let _ = self.tx.try_send(RedditCommand { id, force });\n+ }\n+}\n+\n+impl RedditApiConfig {\n+ pub fn from_env() -> Self {\n+ Self {\n+ api_base: reddit_api_base(),\n+ oauth_base: reddit_oauth_base(),\n+ user_agent: default_user_agent(),\n+ creds: RedditCredentials::from_env(),\n+ }\n }\n }\n \n impl RedditCredentials {\n+ /// Reddit's OAuth docs call these \"client id\" and \"client secret\"; the app\n+ /// registration UI often labels them \"app id\" / \"app secret\" — same values.\n fn from_env() -> Option {\n- let client_id = std::env::var(\"REDDIT_CLIENT_ID\").ok()?;\n- let client_secret = std::env::var(\"REDDIT_CLIENT_SECRET\").ok()?;\n+ let client_id = std::env::var(\"REDDIT_CLIENT_ID\")\n+ .or_else(|_| std::env::var(\"REDDIT_APP_ID\"))\n+ .ok()?;\n+ let client_secret = std::env::var(\"REDDIT_CLIENT_SECRET\")\n+ .or_else(|_| std::env::var(\"REDDIT_APP_SECRET\"))\n+ .ok()?;\n if client_id.is_empty() || client_secret.is_empty() {\n return None;\n }\n@@ -80,29 +114,63 @@ impl RedditCredentials {\n }\n }\n \n+pub fn reddit_api_base() -> String {\n+ std::env::var(\"REDDIT_API_BASE\").unwrap_or_else(|_| \"https://www.reddit.com\".into())\n+}\n+\n+pub fn reddit_oauth_base() -> String {\n+ std::env::var(\"REDDIT_OAUTH_BASE\").unwrap_or_else(|_| \"https://www.reddit.com\".into())\n+}\n+\n pub fn default_user_agent() -> String {\n std::env::var(\"REDDIT_USER_AGENT\").unwrap_or_else(|_| {\n \"web:sorter2.social:v0.0.1 (by /u/sorter2)\".to_string()\n })\n }\n \n+/// True when this node can be loaded from the Reddit JSON API.\n+pub fn is_fetchable(id: &ItemId) -> bool {\n+ !map_item_to_reddit_api(id, \"https://example.com\").is_empty()\n+}\n+\n+/// Derive UI-facing fields from a stored payload (Reddit-specific when under reddit.com).\n+pub fn entity_view_from_payload(id: &ItemId, payload: &Value) -> Option {\n+ if id.as_str().starts_with(\"reddit.com\") {\n+ return parse_reddit_view(id, payload);\n+ }\n+ None\n+}\n+\n+/// Apply a full API payload to the in-memory tree (view derived for known domains).\n+pub fn apply_entity_import(tree: &mut GlobalTree, id: &ItemId, payload: Value) {\n+ let view = entity_view_from_payload(id, &payload);\n+ tree.apply_entity_raw(id, payload, view);\n+}\n+\n async fn reddit_worker(\n mut rx: mpsc::Receiver,\n tree: Arc>,\n+ event_log: Arc,\n client: Client,\n- creds: Option,\n+ config: RedditApiConfig,\n ) {\n let mut in_flight = HashSet::new();\n let mut recently_fetched: HashMap = HashMap::new();\n let mut current_delay = Duration::from_secs(1);\n let mut oauth: Option = None;\n let cache_ttl = Duration::from_secs(300);\n+ let creds = config.creds.clone();\n+ let api_base = config.api_base.clone();\n+ let oauth_base = config.oauth_base.clone();\n \n while let Some(cmd) = rx.recv().await {\n let now = Instant::now();\n recently_fetched.retain(|_, t| now.duration_since(*t) < cache_ttl);\n \n- if in_flight.contains(&cmd.id) || recently_fetched.contains_key(&cmd.id) {\n+ if in_flight.contains(&cmd.id) {\n+ continue;\n+ }\n+ if !cmd.force && recently_fetched.contains_key(&cmd.id) {\n continue;\n }\n \n@@ -112,18 +180,26 @@ async fn reddit_worker(\n tokio::time::sleep(current_delay).await;\n \n if let Some(c) = &creds {\n- oauth = ensure_oauth_token(&client, c, oauth.take()).await;\n+ oauth = ensure_oauth_token(&client, &oauth_base, c, oauth.take()).await;\n }\n \n let token = oauth.as_ref().map(|t| t.access_token.as_str());\n- let use_oauth = token.is_some();\n \n- match do_fetch(&client, &fetch_id, use_oauth, token).await {\n- Ok(FetchOutcome::Entity(data)) => {\n- let mut w = tree.write().await;\n- w.set_entity_data(&fetch_id, data);\n- recently_fetched.insert(fetch_id.clone(), Instant::now());\n- current_delay = Duration::from_millis(600);\n+ match do_fetch(&client, &api_base, &fetch_id, token).await {\n+ Ok(FetchOutcome::Payload(payload)) => {\n+ let ts = now_ms();\n+ let event = Event::EntityImported {\n+ id: fetch_id.as_str().to_string(),\n+ ts,\n+ payload: payload.clone(),\n+ };\n+ if let Err(e) = event_log.append(&event).await {\n+ tracing::warn!(\"event log append failed for {}: {}\", fetch_id, e);\n+ } else {\n+ apply_entity_import(&mut *tree.write().await, &fetch_id, payload);\n+ recently_fetched.insert(fetch_id.clone(), Instant::now());\n+ current_delay = Duration::from_millis(600);\n+ }\n }\n Ok(FetchOutcome::NotFound) => {\n recently_fetched.insert(fetch_id.clone(), Instant::now());\n@@ -149,13 +225,14 @@ async fn reddit_worker(\n }\n \n enum FetchOutcome {\n- Entity(EntityData),\n+ Payload(Value),\n NotFound,\n RateLimited { reset_secs: u64 },\n }\n \n async fn ensure_oauth_token(\n client: &Client,\n+ oauth_base: &str,\n creds: &RedditCredentials,\n existing: Option,\n ) -> Option {\n@@ -165,8 +242,13 @@ async fn ensure_oauth_token(\n }\n }\n \n+ let url = format!(\n+ \"{}/api/v1/access_token\",\n+ oauth_base.trim_end_matches('/')\n+ );\n+\n let resp = client\n- .post(\"https://www.reddit.com/api/v1/access_token\")\n+ .post(&url)\n .basic_auth(&creds.client_id, Some(&creds.client_secret))\n .form(&[(\"grant_type\", \"client_credentials\")])\n .send()\n@@ -207,11 +289,11 @@ async fn ensure_oauth_token(\n \n async fn do_fetch(\n client: &Client,\n+ api_base: &str,\n id: &ItemId,\n- use_oauth: bool,\n bearer: Option<&str>,\n ) -> Result {\n- let url = map_item_to_reddit_api(id, use_oauth);\n+ let url = map_item_to_reddit_api(id, api_base);\n if url.is_empty() {\n return Ok(FetchOutcome::NotFound);\n }\n@@ -241,10 +323,8 @@ async fn do_fetch(\n return Ok(FetchOutcome::RateLimited { reset_secs: reset });\n }\n \n- let bytes = resp.bytes().await.map_err(|e| e.to_string())?;\n- Ok(parse_reddit_json(id, &bytes)\n- .map(FetchOutcome::Entity)\n- .unwrap_or(FetchOutcome::NotFound))\n+ let payload: Value = resp.json().await.map_err(|e| e.to_string())?;\n+ Ok(FetchOutcome::Payload(payload))\n }\n \n fn rate_limit_remaining(resp: &reqwest::Response) -> Option {\n@@ -264,18 +344,14 @@ fn rate_limit_reset_secs(resp: &reqwest::Response) -> u64 {\n .unwrap_or(5)\n }\n \n-/// Map canonical item id to Reddit JSON API URL.\n-pub fn map_item_to_reddit_api(id: &ItemId, oauth: bool) -> String {\n+/// Map canonical item id to a Reddit JSON API URL under `api_base`.\n+pub fn map_item_to_reddit_api(id: &ItemId, api_base: &str) -> String {\n let path = id.as_str();\n if !path.starts_with(\"reddit.com/\") && path != \"reddit.com\" {\n return String::new();\n }\n \n- let base = if oauth {\n- \"https://oauth.reddit.com\"\n- } else {\n- \"https://www.reddit.com\"\n- };\n+ let base = api_base.trim_end_matches('/');\n \n let segments: Vec<&str> = path.split('/').collect();\n \n@@ -293,18 +369,17 @@ pub fn map_item_to_reddit_api(id: &ItemId, oauth: bool) -> String {\n String::new()\n }\n \n-fn parse_reddit_json(id: &ItemId, bytes: &[u8]) -> Option {\n- let v: serde_json::Value = serde_json::from_slice(bytes).ok()?;\n+fn parse_reddit_view(id: &ItemId, v: &Value) -> Option {\n let segments: Vec<&str> = id.as_str().split('/').collect();\n \n if segments.iter().any(|&p| p == \"comments\") {\n- parse_post_listing(&v)\n+ parse_post_listing(v)\n } else {\n- parse_subreddit_about(&v)\n+ parse_subreddit_about(v)\n }\n }\n \n-fn parse_subreddit_about(v: &serde_json::Value) -> Option {\n+fn parse_subreddit_about(v: &Value) -> Option {\n let data = v.get(\"data\")?;\n let title = data\n .get(\"title\")\n@@ -323,7 +398,7 @@ fn parse_subreddit_about(v: &serde_json::Value) -> Option {\n .filter(|s| !s.is_empty())\n .map(|s| s.to_string());\n \n- Some(EntityData {\n+ Some(crate::reducer::EntityData {\n title,\n author: None,\n body_html,\n@@ -331,10 +406,9 @@ fn parse_subreddit_about(v: &serde_json::Value) -> Option {\n })\n }\n \n-fn parse_post_listing(v: &serde_json::Value) -> Option {\n+fn parse_post_listing(v: &Value) -> Option {\n let listing = v.as_array()?.first()?;\n- let child = listing\n- .pointer(\"/data/children/0/data\")?;\n+ let child = listing.pointer(\"/data/children/0/data\")?;\n let title = child.get(\"title\")?.as_str()?.to_string();\n let author = child\n .get(\"author\")\n@@ -352,7 +426,7 @@ fn parse_post_listing(v: &serde_json::Value) -> Option {\n .filter(|s| s.starts_with(\"http\"))\n .map(|s| s.to_string());\n \n- Some(EntityData {\n+ Some(crate::reducer::EntityData {\n title,\n author,\n body_html,\n@@ -368,48 +442,51 @@ mod tests {\n fn map_subreddit_about_url() {\n let id = ItemId::parse(\"reddit.com/r/rust\").unwrap();\n assert_eq!(\n- map_item_to_reddit_api(&id, false),\n+ map_item_to_reddit_api(&id, \"https://www.reddit.com\"),\n \"https://www.reddit.com/r/rust/about.json?raw_json=1\"\n );\n assert_eq!(\n- map_item_to_reddit_api(&id, true),\n- \"https://oauth.reddit.com/r/rust/about.json?raw_json=1\"\n+ map_item_to_reddit_api(&id, \"http://127.0.0.1:9999\"),\n+ \"http://127.0.0.1:9999/r/rust/about.json?raw_json=1\"\n );\n }\n \n #[test]\n fn map_post_url() {\n- let id =\n- ItemId::parse(\"reddit.com/r/amitheasshole/comments/1trnvdl\").unwrap();\n+ let id = ItemId::parse(\"reddit.com/r/amitheasshole/comments/1trnvdl\").unwrap();\n assert_eq!(\n- map_item_to_reddit_api(&id, false),\n+ map_item_to_reddit_api(&id, \"https://www.reddit.com\"),\n \"https://www.reddit.com/r/amitheasshole/comments/1trnvdl.json?raw_json=1\"\n );\n }\n \n #[test]\n- fn map_non_reddit_empty() {\n- let id = ItemId::opaque(\"example.com/foo\");\n- assert!(map_item_to_reddit_api(&id, false).is_empty());\n+ fn is_fetchable_reddit_sub() {\n+ let id = ItemId::parse(\"reddit.com/r/rust\").unwrap();\n+ assert!(is_fetchable(&id));\n+ assert!(!is_fetchable(&ItemId::opaque(\"example.com/x\")));\n }\n \n #[test]\n fn parse_subreddit_fixture() {\n- let json = r#\"{\"kind\":\"t5\",\"data\":{\"title\":\"Rust\",\"display_name\":\"rust\",\"public_description\":\"systems\"}}\"#;\n- let entity = parse_reddit_json(\n+ let json = include_str!(\"../../test/fixtures/reddit/r_rust_about.json\");\n+ let v: Value = serde_json::from_str(json).unwrap();\n+ let entity = entity_view_from_payload(\n &ItemId::parse(\"reddit.com/r/rust\").unwrap(),\n- json.as_bytes(),\n+ &v,\n )\n .unwrap();\n- assert_eq!(entity.title, \"Rust\");\n+ assert_eq!(entity.title, \"The Rust Programming Language\");\n+ assert!(entity.body_html.as_ref().is_some_and(|b| b.contains(\"Rust\")));\n }\n \n #[test]\n fn parse_post_fixture() {\n let json = r#\"[{\"kind\":\"Listing\",\"data\":{\"children\":[{\"kind\":\"t3\",\"data\":{\"title\":\"AITA\",\"author\":\"op\",\"selftext_html\":\"<p>hi</p>\",\"thumbnail\":\"https://b.thumbs.redditmedia.com/x.jpg\"}}]}}]\"#;\n- let entity = parse_reddit_json(\n+ let v: Value = serde_json::from_str(json).unwrap();\n+ let entity = entity_view_from_payload(\n &ItemId::parse(\"reddit.com/r/x/comments/abc\").unwrap(),\n- json.as_bytes(),\n+ &v,\n )\n .unwrap();\n assert_eq!(entity.title, \"AITA\");\ndiff --git a/server/src/reducer.rs b/server/src/reducer.rs\nindex 077f700bf00ddefe18ffd004bb5288bdc7c4adaf..60db81a562e3590775012573225a76ba82a14563 100644\n--- a/server/src/reducer.rs\n+++ b/server/src/reducer.rs\n@@ -1,6 +1,7 @@\n use std::collections::{HashMap, HashSet, VecDeque};\n \n use serde::{Deserialize, Serialize};\n+use serde_json::Value;\n \n use crate::path_types::ItemId;\n \n@@ -128,6 +129,9 @@ pub struct EntityData {\n #[derive(Debug, Clone, Default)]\n pub struct NodeState {\n pub id: ItemId,\n+ /// Full imported API JSON (persisted in the event log).\n+ pub entity_raw: Option,\n+ /// Domain-specific view derived from `entity_raw` (e.g. Reddit title/author).\n pub data: Option,\n pub children: HashSet,\n pub local_ranking: GroupState,\n@@ -197,10 +201,11 @@ impl GlobalTree {\n }\n }\n \n- pub fn set_entity_data(&mut self, id: &ItemId, data: EntityData) {\n+ pub fn apply_entity_raw(&mut self, id: &ItemId, payload: Value, view: Option) {\n self.ensure_path(id);\n if let Some(node) = self.nodes.get_mut(id) {\n- node.data = Some(data);\n+ node.entity_raw = Some(payload);\n+ node.data = view;\n }\n }\n }\ndiff --git a/server/src/state.rs b/server/src/state.rs\nindex 8c03aa60c15aee803a534439400b69935b1a3d84..d71d1079a8f486cdab15795384aef0b81b32544d 100644\n--- a/server/src/state.rs\n+++ b/server/src/state.rs\n@@ -7,7 +7,7 @@ use crate::{\n events::Event,\n journal::JournalClient,\n path_types::ItemId,\n- reddit::{default_user_agent, RedditBroker},\n+ reddit::{apply_entity_import, RedditApiConfig, RedditBroker},\n reducer::{GlobalTree, VoteData},\n views::ViewStore,\n };\n@@ -108,13 +108,18 @@ impl AppState {\n tree.ensure_path(&parsed);\n }\n }\n+ Event::EntityImported { id, payload, .. } => {\n+ if let Some(parsed) = ItemId::parse(&id).or_else(|| ItemId::from_url(&id)) {\n+ apply_entity_import(&mut tree, &parsed, payload);\n+ }\n+ }\n }\n }\n }\n \n let tree = Arc::new(RwLock::new(tree));\n let journal = JournalClient::spawn(tree.clone(), event_log.clone());\n- let reddit = RedditBroker::spawn(tree.clone(), &default_user_agent());\n+ let reddit = RedditBroker::spawn(tree.clone(), event_log.clone(), RedditApiConfig::from_env());\n \n Self {\n cfg: Arc::new(cfg),\n@@ -135,10 +140,14 @@ impl AppState {\n let mut w = self.tree.write().await;\n w.ensure_path(id);\n }\n- self.reddit.request_fetch(id.clone());\n Ok(())\n }\n \n+ /// User-initiated Reddit/API import (via \"Fetch more\" — never on paste or navigate).\n+ pub fn queue_entity_fetch(&self, id: ItemId) {\n+ self.reddit.request_fetch(id, true);\n+ }\n+\n pub async fn record_vote(\n &self,\n parent: &ItemId,\n@@ -169,6 +178,44 @@ impl AppState {\n #[cfg(test)]\n mod tests {\n use super::{normalize_scope, parse_item_param};\n+ use crate::{\n+ event_log::EventLog,\n+ events::Event,\n+ path_types::ItemId,\n+ reddit::apply_entity_import,\n+ reducer::GlobalTree,\n+ };\n+ use serde_json::json;\n+\n+ #[tokio::test]\n+ async fn replay_entity_imported_restores_view() {\n+ let tmp = tempfile::tempdir().unwrap();\n+ let log_path = tmp.path().join(\"events.jsonl\");\n+ let log = EventLog::new(log_path.to_string_lossy().into_owned());\n+ let payload = json!({\"kind\":\"t5\",\"data\":{\"title\":\"Rust\",\"display_name\":\"rust\"}});\n+ log.append(&Event::EntityImported {\n+ id: \"reddit.com/r/rust\".into(),\n+ ts: 1,\n+ payload: payload.clone(),\n+ })\n+ .await\n+ .unwrap();\n+\n+ let mut tree = GlobalTree::new();\n+ let (events, _) = log.load_all().await.unwrap();\n+ for ev in events {\n+ if let Event::EntityImported { id, payload, .. } = ev {\n+ let parsed = ItemId::parse(&id).unwrap();\n+ apply_entity_import(&mut tree, &parsed, payload);\n+ }\n+ }\n+ let node = tree.get(&ItemId::parse(\"reddit.com/r/rust\").unwrap()).unwrap();\n+ assert_eq!(node.data.as_ref().unwrap().title, \"Rust\");\n+ assert_eq!(\n+ node.entity_raw.as_ref().unwrap()[\"data\"][\"display_name\"],\n+ \"rust\"\n+ );\n+ }\n \n #[test]\n fn normalize_scope_strips_prefix_and_lowercases() {\ndiff --git a/server/src/ui_action.rs b/server/src/ui_action.rs\nindex d798874d1d94c0dfee59ec1ff703f9ee6ef432c0..3d6a49a2a3fb950752827efe1f5a049308f09baf 100644\n--- a/server/src/ui_action.rs\n+++ b/server/src/ui_action.rs\n@@ -26,6 +26,10 @@ pub enum HtmlUiAction {\n ParseQuery {\n query: String,\n },\n+ /// Fetch upstream entity data for the current page (explicit user action only).\n+ FetchEntity {\n+ item: String,\n+ },\n }\n \n #[derive(Debug, Error)]\ndiff --git a/server/static/sorter.css b/server/static/sorter.css\nindex 36f68d415cea33c8562d5d02c0c9d4c5b225a782..1f9f5158414902d43a380dd899232c70d8cf5d63 100644\n--- a/server/static/sorter.css\n+++ b/server/static/sorter.css\n@@ -52,6 +52,25 @@ body {\n filter: brightness(1.1);\n }\n \n+.btn-secondary {\n+ background: transparent;\n+ color: var(--accent);\n+ border: 1px solid var(--border);\n+ padding: 0.4rem 0.85rem;\n+ font-size: 0.9rem;\n+ cursor: pointer;\n+ margin-top: 0.75rem;\n+}\n+\n+.btn-secondary:disabled {\n+ opacity: 0.6;\n+ cursor: wait;\n+}\n+\n+.fetch-entity-form {\n+ margin-top: 0.5rem;\n+}\n+\n code {\n font-size: 0.85em;\n background: var(--bg);\ndiff --git a/test/fixtures/reddit/r_rust_about.json b/test/fixtures/reddit/r_rust_about.json\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..bb7fd74ab00d63356d9b672a775996ed155b984d\n--- /dev/null\n+++ b/test/fixtures/reddit/r_rust_about.json\n@@ -0,0 +1,21 @@\n+{\n+ \"kind\": \"t5\",\n+ \"data\": {\n+ \"user_flair_background_color\": null,\n+ \"submit_text_html\": null,\n+ \"banner_img\": \"\",\n+ \"user_is_banned\": null,\n+ \"wiki_enabled\": true,\n+ \"show_media\": true,\n+ \"id\": \"2qh0i\",\n+ \"display_name\": \"rust\",\n+ \"title\": \"The Rust Programming Language\",\n+ \"public_description\": \"A place for all things related to the Rust programming language.\",\n+ \"public_description_html\": \"<!-- SC_OFF --><div class=\\\"md\\\"><p>A place for all things related to the Rust programming language.</p>\\n</div><!-- SC_ON -->\",\n+ \"icon_img\": \"https://styles.redditmedia.com/t5_2qh0i/styles/communityIcon_kfqpknb2j6j51.png\",\n+ \"community_icon\": \"https://styles.redditmedia.com/t5_2qh0i/styles/communityIcon_kfqpknb2j6j51.png\",\n+ \"subscribers\": 350000,\n+ \"active_user_count\": 1200,\n+ \"over18\": false\n+ }\n+}\ndiff --git a/test/reddit_import.clj b/test/reddit_import.clj\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..54edaedeef08718c8f184d6aa468d8e6415068c7\n--- /dev/null\n+++ b/test/reddit_import.clj\n@@ -0,0 +1,116 @@\n+(ns test.reddit-import\n+ (:require [babashka.process :as process]\n+ [clojure.java.io :as io]\n+ [clojure.string :as str]\n+ [clojure.test :refer [deftest is testing]])\n+ (:import [com.sun.net.httpserver HttpServer HttpHandler HttpExchange]\n+ [java.net InetSocketAddress]))\n+\n+(defn- repo-root []\n+ (.getCanonicalPath (io/file (System/getProperty \"user.dir\"))))\n+\n+(defn- pick-port []\n+ (with-open [s (java.net.ServerSocket. 0)]\n+ (.getLocalPort s)))\n+\n+(defn- start-mock-reddit [port fixtures-dir]\n+ (let [fixture (io/file fixtures-dir \"r_rust_about.json\")\n+ body (.getBytes (slurp fixture) \"UTF-8\")\n+ server (HttpServer/create (InetSocketAddress. \"127.0.0.1\" port) 0)\n+ handler\n+ (proxy [HttpHandler] []\n+ (handle [^HttpExchange exchange]\n+ (.sendResponseHeaders exchange 200 (alength body))\n+ (let [out (.getResponseBody exchange)]\n+ (.write out body)\n+ (.close out))))]\n+ (.createContext server \"/\" handler)\n+ (.setExecutor server nil)\n+ (.start server)\n+ (fn stop []\n+ (.stop server 0))))\n+\n+(defn- wait-health [base-url ms]\n+ (let [deadline (+ (System/currentTimeMillis) ms)\n+ url (str base-url \"/healthz\")]\n+ (loop []\n+ (let [resp (try\n+ (process/shell {:out :string :err :string}\n+ \"curl\" \"-sf\" url)\n+ (catch Exception _ nil))]\n+ (if (and resp (zero? (:exit resp)) (= \"ok\" (str/trim (:out resp \"\"))))\n+ true\n+ (if (< (System/currentTimeMillis) deadline)\n+ (do (Thread/sleep 200) (recur))\n+ false))))))\n+\n+(defn- curl-post-ui [base rpc-json]\n+ (process/shell {:out :string :err :string}\n+ \"curl\" \"-sf\" \"-X\" \"POST\" (str base \"/ui\")\n+ \"--data-urlencode\" (str \"__rpc__=\" rpc-json)))\n+\n+(defn- wait-event-log [path ms]\n+ (let [deadline (+ (System/currentTimeMillis) ms)]\n+ (loop []\n+ (if (.exists (io/file path))\n+ true\n+ (if (< (System/currentTimeMillis) deadline)\n+ (do (Thread/sleep 200) (recur))\n+ false)))))\n+\n+(deftest reddit-fetch-via-mock-api\n+ (testing \"Fetch more queues import; event log stores full payload; page shows title\"\n+ (let [root (repo-root)\n+ fixtures (str root \"/test/fixtures/reddit\")\n+ data-dir (.getAbsolutePath\n+ (doto (io/file (System/getProperty \"java.io.tmpdir\")\n+ (str \"sorter2-reddit-\" (System/currentTimeMillis)))\n+ (.mkdirs)))\n+ reddit-port (pick-port)\n+ app-port (pick-port)\n+ reddit-base (str \"http://127.0.0.1:\" reddit-port)\n+ app-base (str \"http://127.0.0.1:\" app-port)\n+ bin (str root \"/target/release/sorter2-server\")\n+ stop-mock (start-mock-reddit reddit-port fixtures)]\n+ (try\n+ (is (zero? (:exit (process/shell {:dir root}\n+ \"cargo\" \"build\" \"--release\" \"--package\" \"sorter2-server\")))\n+ \"release build succeeds\")\n+ (let [proc (process/process {:dir root\n+ :env (into (into {} (System/getenv))\n+ {\"SORTER2_SKIP_DOTENV\" \"1\"\n+ \"SORTER2_DATA_DIR\" data-dir\n+ \"SORTER2_EVENT_LOG\" (str data-dir \"/events.jsonl\")\n+ \"PORT\" (str app-port)\n+ \"REDDIT_API_BASE\" reddit-base\n+ \"REDDIT_OAUTH_BASE\" reddit-base\n+ \"REDDIT_CLIENT_ID\" \"\"\n+ \"REDDIT_CLIENT_SECRET\" \"\"\n+ \"REDDIT_APP_ID\" \"\"\n+ \"REDDIT_APP_SECRET\" \"\"})\n+ :out :string\n+ :err :string}\n+ bin)]\n+ (try\n+ (is (wait-health app-base 20000) \"app healthz\")\n+ (let [browse-url (str app-base \"/~/https://reddit.com/r/rust\")\n+ before (:out (process/shell {:out :string :err :string}\n+ \"curl\" \"-sf\" browse-url))]\n+ (is (str/includes? before \"Fetch from Reddit\"))\n+ (is (not (str/includes? before \"The Rust Programming Language\")))\n+ (let [rpc \"{\\\"action\\\":\\\"fetch_entity\\\",\\\"item\\\":\\\"reddit.com/r/rust\\\"}\"\n+ post (curl-post-ui app-base rpc)\n+ log-path (str data-dir \"/events.jsonl\")]\n+ (is (zero? (:exit post)) \"fetch_entity POST succeeds\")\n+ (is (wait-event-log log-path 10000) \"event log written\")\n+ (let [after (:out (process/shell {:out :string :err :string}\n+ \"curl\" \"-sf\" browse-url))\n+ log (slurp (io/file log-path))]\n+ (is (str/includes? after \"The Rust Programming Language\"))\n+ (is (str/includes? log \"\\\"type\\\":\\\"entity_imported\\\"\"))\n+ (is (str/includes? log \"\\\"subscribers\\\":350000\"))\n+ (is (str/includes? log \"\\\"display_name\\\":\\\"rust\\\"\")))))\n+ (finally\n+ (process/destroy proc))))\n+ (finally\n+ (stop-mock))))))\n","role":"user"}],"model":"~anthropic/claude-sonnet-latest"}