{"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[a888d56c] refactor: centralize path identity in slug-types\n\nMove canonicalization and CanonicalItemUrl into types::paths with\nGardenItemUrl, ForumThreadUrl, and TildeOntologyPath for JSON hrefs.\nServer canonical_path and path_types re-export slug-types; RPC and\nvalidation build hrefs via those types instead of string helpers.\n\nMade-with: Cursor\n\nSide A — unified diff (full patch):\ndiff --git a/server/src/api/helpers.rs b/server/src/api/helpers.rs\nindex 9b71491e9f9efc44a2a4beba09be8f64bd2ff2ee..03b3e77911ccd662bec8635345dafe2593cf242e 100644\n--- a/server/src/api/helpers.rs\n+++ b/server/src/api/helpers.rs\n@@ -4,12 +4,12 @@ use axum::{\n Json,\n };\n use sha2::{Digest, Sha256};\n+use slug_types::paths::{CanonicalItemUrl, GardenItemUrl};\n use slug_types::*;\n use std::collections::HashMap;\n \n use crate::{\n canonical_path::canonicalize_item,\n- path_types::CanonicalItemUrl,\n ranking::connected_components_from_voted_pairs,\n };\n \n@@ -30,64 +30,6 @@ pub fn now_ms() -> i64 {\n t.as_millis() as i64\n }\n \n-/// Serialize a canonical item for JSON: absolute URLs stay as-is; bare paths get a `/` prefix.\n-pub fn item_path_for_api(item: &str) -> String {\n- if item.starts_with(\"http://\") || item.starts_with(\"https://\") {\n- item.to_string()\n- } else {\n- format!(\"/{}\", item)\n- }\n-}\n-\n-/// Same as [`item_path_for_api`], but for private rooms ontology items are prefixed with\n-/// `/r/{short}/{slug}` so the URL matches the web app (`/r/…/~/…` routes).\n-pub fn item_path_for_api_in_room(item: &str, room_wire: &str) -> String {\n- let room = room_wire.trim();\n- if room.is_empty() || room == \"public\" {\n- return item_path_for_api(item);\n- }\n- let Some((short, slug)) = room.split_once('/') else {\n- return item_path_for_api(item);\n- };\n- if short.is_empty() || slug.is_empty() {\n- return item_path_for_api(item);\n- }\n- let Some(c) = CanonicalItemUrl::parse(item) else {\n- return item_path_for_api(item);\n- };\n- let root = CanonicalItemUrl::ontology_root();\n- let item_norm = c.as_str().trim_end_matches('/');\n- let root_norm = root.as_str().trim_end_matches('/');\n- if let Some(tail) = c.tilde_tail() {\n- return if tail.is_empty() {\n- format!(\"https://slug.social/r/{short}/{slug}/~\")\n- } else {\n- format!(\"https://slug.social/r/{short}/{slug}/~/{}\", tail)\n- };\n- }\n- if item_norm == root_norm {\n- return format!(\"https://slug.social/r/{short}/{slug}/~\");\n- }\n- item_path_for_api(item)\n-}\n-\n-/// Absolute thread URL for forum JSON (`/t/…` vs `/r/…/t/…`).\n-pub fn forum_thread_web_url(room_wire: &str, thread_tag: &str) -> String {\n- let room = room_wire.trim();\n- let tag = thread_tag.trim().trim_start_matches('#');\n- if room.is_empty() || room == \"public\" {\n- format!(\"https://slug.social/t/{tag}\")\n- } else if let Some((short, slug)) = room.split_once('/') {\n- if short.is_empty() || slug.is_empty() {\n- format!(\"https://slug.social/t/{tag}\")\n- } else {\n- format!(\"https://slug.social/r/{short}/{slug}/t/{tag}\")\n- }\n- } else {\n- format!(\"https://slug.social/t/{tag}\")\n- }\n-}\n-\n /// Resolve an item path as a first-class canonical path.\n pub fn resolve_item(item: &str) -> Result {\n let canonical = canonicalize_item(item);\n@@ -109,14 +51,12 @@ pub fn parse_parent_specs(parent: Option<&String>) -> Vec {\n }\n \n /// Apply offset+limit pagination to the flattened component rankings.\n-/// Items are flattened in component order (largest component first), then unranked last.\n-/// Returns (components, unranked_items) after the window.\n pub fn paginate_rankings(\n components: Vec,\n- unranked_items: Vec,\n+ unranked_items: Vec,\n offset: usize,\n limit: Option,\n-) -> (Vec, Vec) {\n+) -> (Vec, Vec) {\n let mut remaining_skip = offset;\n let mut remaining_take = limit.unwrap_or(usize::MAX);\n let mut out_components: Vec = Vec::new();\n@@ -141,7 +81,7 @@ pub fn paginate_rankings(\n });\n }\n \n- let out_unranked: Vec = if remaining_take > 0 {\n+ let out_unranked: Vec = if remaining_take > 0 {\n unranked_items\n .into_iter()\n .skip(remaining_skip)\n@@ -183,11 +123,9 @@ pub fn is_pair_voted(group: &crate::reducer::GroupState, a: &str, b: &str) -> bo\n group.voted_pairs.contains(&(i, j))\n }\n \n-/// Compute graph connectivity stats for a set of items within the ranking group.\n pub fn compute_connectivity_stats(group: &crate::reducer::GroupState, pool: &[String]) -> ConnectivityStats {\n let n = pool.len();\n \n- // Map pool items to global indices (items not yet in the group get no index)\n let global_idxs: Vec> = pool\n .iter()\n .map(|it| {\n@@ -197,7 +135,6 @@ pub fn compute_connectivity_stats(group: &crate::reducer::GroupState, pool: &[St\n .collect();\n let present: Vec = global_idxs.iter().filter_map(|x| *x).collect();\n \n- // Build local index mapping for items that exist in the ranking group\n let global_to_local: HashMap = present\n .iter()\n .enumerate()\n@@ -213,7 +150,6 @@ pub fn compute_connectivity_stats(group: &crate::reducer::GroupState, pool: &[St\n }),\n );\n \n- // Items not in the ranking group at all are also isolates\n let items_not_in_group = global_idxs.iter().filter(|x| x.is_none()).count();\n \n let num_components = comps.len() + isolates.len() + items_not_in_group;\n@@ -237,52 +173,3 @@ pub fn vote_touches_path(a: &str, b: &str, parent_canon: &str) -> bool {\n let under = |item: &str| item == parent_canon || item.starts_with(&format!(\"{}/\", parent_canon));\n under(a) || under(b)\n }\n-\n-#[cfg(test)]\n-mod wire_url_tests {\n- use super::{forum_thread_web_url, item_path_for_api_in_room};\n-\n- #[test]\n- fn public_room_unchanged() {\n- let u = \"https://slug.social/~/a/b\";\n- assert_eq!(item_path_for_api_in_room(u, \"public\"), u);\n- }\n-\n- #[test]\n- fn private_room_prefixes_ontology() {\n- assert_eq!(\n- item_path_for_api_in_room(\"https://slug.social/~/topic/x\", \"9ab12cd/my-room\"),\n- \"https://slug.social/r/9ab12cd/my-room/~/topic/x\"\n- );\n- }\n-\n- #[test]\n- fn private_room_ontology_root() {\n- assert_eq!(\n- item_path_for_api_in_room(\"https://slug.social/~\", \"9ab12cd/my-room\"),\n- \"https://slug.social/r/9ab12cd/my-room/~\"\n- );\n- assert_eq!(\n- item_path_for_api_in_room(\"https://slug.social/~/\", \"9ab12cd/my-room\"),\n- \"https://slug.social/r/9ab12cd/my-room/~\"\n- );\n- }\n-\n- #[test]\n- fn external_url_untouched_in_private_room() {\n- let u = \"https://example.com/z\";\n- assert_eq!(item_path_for_api_in_room(u, \"9ab12cd/my-room\"), u);\n- }\n-\n- #[test]\n- fn forum_web_public_vs_room() {\n- assert_eq!(\n- forum_thread_web_url(\"public\", \"debate\"),\n- \"https://slug.social/t/debate\"\n- );\n- assert_eq!(\n- forum_thread_web_url(\"9ab12cd/my-room\", \"#debate\"),\n- \"https://slug.social/r/9ab12cd/my-room/t/debate\"\n- );\n- }\n-}\ndiff --git a/server/src/api/mod.rs b/server/src/api/mod.rs\nindex 042aa248305f9362a3be78f9eea2a5abf6ba707a..cf22cb0129366c3aed031bc86f3197a4321cb806 100644\n--- a/server/src/api/mod.rs\n+++ b/server/src/api/mod.rs\n@@ -24,8 +24,7 @@ pub use auth::{\n \n pub use helpers::{\n api_error, compute_connectivity_stats, is_pair_voted, now_ms, paginate_rankings,\n- parse_parent_specs, pick_random_distinct, sha256_hex, resolve_item, vote_touches_path,\n- item_path_for_api,\n+ parse_parent_specs, pick_random_distinct, resolve_item, sha256_hex, vote_touches_path,\n };\n \n pub use rpc::handle_rpc_batch;\ndiff --git a/server/src/api/rpc.rs b/server/src/api/rpc.rs\nindex 5b91f5836625eedbb1cd9423168046e3fb576c17..5f7d50188f1381267402f2e57e671234ef5db2fd 100644\n--- a/server/src/api/rpc.rs\n+++ b/server/src/api/rpc.rs\n@@ -8,6 +8,7 @@ use axum::{\n Json,\n };\n use rand::seq::SliceRandom;\n+use slug_types::paths::{ForumThreadUrl, GardenItemUrl, TildeOntologyPath};\n use slug_types::*;\n \n use crate::{\n@@ -27,9 +28,8 @@ use crate::{\n \n use super::auth::verify_bearer_principal;\n use super::helpers::{\n- compute_connectivity_stats, forum_thread_web_url, is_pair_voted, item_path_for_api,\n- item_path_for_api_in_room, now_ms, paginate_rankings, parse_parent_specs, pick_random_distinct,\n- resolve_item, vote_touches_path,\n+ compute_connectivity_stats, is_pair_voted, now_ms, paginate_rankings, parse_parent_specs,\n+ pick_random_distinct, resolve_item, vote_touches_path,\n };\n use super::validate::{normalize_room_and_thread, validate_ingest_document};\n \n@@ -184,7 +184,7 @@ fn compute_scope_rank_changes(\n };\n if changed {\n changes.push(RankChange {\n- item: item_path_for_api_in_room(&item, room_wire),\n+ item: GardenItemUrl::from_storage_str(&item, room_wire),\n before: b,\n after: a,\n });\n@@ -206,7 +206,7 @@ fn compute_scope_rank_changes(\n parent: if parent.is_empty() {\n \"/\".to_string()\n } else {\n- item_path_for_api_in_room(parent, room_wire)\n+ GardenItemUrl::from_storage_str(parent, room_wire).into_inner()\n },\n changes,\n })\n@@ -302,7 +302,7 @@ fn build_rank_response_for_content(\n .ranked\n .into_iter()\n .map(|r| RankRow {\n- item: item_path_for_api_in_room(r.item.as_str(), room_wire),\n+ item: GardenItemUrl::from_stored(&r.item, room_wire),\n percent: if want_percent {\n Some((r.score / max_score) * 100.0)\n } else {\n@@ -315,10 +315,10 @@ fn build_rank_response_for_content(\n })\n .collect();\n \n- let prefixed_unranked: Vec = rankings\n+ let prefixed_unranked: Vec = rankings\n .unranked_items\n .into_iter()\n- .map(|s| item_path_for_api_in_room(s.as_str(), room_wire))\n+ .map(|s| GardenItemUrl::from_stored(&s, room_wire))\n .collect();\n \n let (components, unranked_items) = if offset > 0 || limit.is_some() {\n@@ -537,13 +537,13 @@ async fn rpc_post(\n (\n \"npx slugsocial public garden pair\".to_string(),\n \"npx slugsocial public garden rank\".to_string(),\n- forum_thread_web_url(\"public\", &thread_id),\n+ ForumThreadUrl::from_room_tag(\"public\", &thread_id),\n )\n } else {\n (\n format!(\"npx slugsocial private {room_key} garden pair\"),\n format!(\"npx slugsocial private {room_key} garden rank\"),\n- forum_thread_web_url(&room_key, &thread_id),\n+ ForumThreadUrl::from_room_tag(&room_key, &thread_id),\n )\n };\n \n@@ -664,7 +664,7 @@ async fn rpc_check(\n .ranked\n .into_iter()\n .map(|r| RankRow {\n- item: item_path_for_api_in_room(r.item.as_str(), &room_key),\n+ item: GardenItemUrl::from_stored(&r.item, &room_key),\n score: r.score,\n percent: None,\n })\n@@ -672,12 +672,12 @@ async fn rpc_check(\n })\n .collect();\n CheckScopeRanking {\n- parent: item_path_for_api_in_room(parent.as_str(), &room_key),\n+ parent: GardenItemUrl::from_stored(parent, &room_key).into_inner(),\n components,\n unranked_items: scoped\n .unranked_items\n .into_iter()\n- .map(|it| item_path_for_api_in_room(it.as_str(), &room_key))\n+ .map(|it| GardenItemUrl::from_stored(&it, &room_key))\n .collect(),\n }\n })\n@@ -687,13 +687,13 @@ async fn rpc_check(\n vec![\n \"npx slugsocial public forum post --delegate \".to_string(),\n \"npx slugsocial public forum list\".to_string(),\n- forum_thread_web_url(\"public\", &thread_id),\n+ ForumThreadUrl::from_room_tag(\"public\", &thread_id).into_inner(),\n ]\n } else {\n vec![\n format!(\"npx slugsocial private {room_key} forum post --delegate \"),\n format!(\"npx slugsocial private {room_key} forum list\"),\n- forum_thread_web_url(&room_key, &thread_id),\n+ ForumThreadUrl::from_room_tag(&room_key, &thread_id).into_inner(),\n ]\n };\n \n@@ -717,7 +717,7 @@ fn rpc_list_forum_threads(reduced: &ReducerState, room: &str) -> ThreadsResponse\n .map(|((_, tag), ts)| ThreadSummary {\n thread: format!(\"#{tag}\"),\n last_activity_ts: ts.last_activity_ts,\n- web: forum_thread_web_url(room, tag),\n+ web: ForumThreadUrl::from_room_tag(room, tag),\n })\n .collect();\n out.sort_by(|a, b| b.last_activity_ts.cmp(&a.last_activity_ts));\n@@ -885,7 +885,7 @@ fn rpc_search(reduced: &ReducerState, q: &str, limit: usize, principal: Option<&\n }\n if score > 0 {\n scored_items.push((score, SearchItemHit {\n- path: item_path_for_api(item.as_str()),\n+ path: GardenItemUrl::from_storage_str(item.as_str(), \"public\"),\n body: content.item_bodies.get(item).map(|b| snippet_around(b, &words, 120)),\n }));\n }\n@@ -1058,8 +1058,8 @@ async fn rpc_get_pair(state: &AppState, room: String, parent_path: String) -> Re\n .collect();\n let cs = compute_connectivity_stats(&content.ranking_group, &pool);\n Ok(RpcResult::Pair(PairResponse {\n- left: item_path_for_api_in_room(&left, &room),\n- right: item_path_for_api_in_room(&right, &room),\n+ left: GardenItemUrl::from_storage_str(&left, &room),\n+ right: GardenItemUrl::from_storage_str(&right, &room),\n left_body: lb,\n right_body: rb,\n threads: th,\n@@ -1137,7 +1137,7 @@ pub async fn handle_rpc_batch(\n if !content.items.contains(&item) {\n line_err(\n \"item not found\",\n- Some(format!(\"{} does not exist\", item_path_for_api_in_room(&item_str, &room))),\n+ Some(format!(\"{} does not exist\", GardenItemUrl::from_storage_str(&item_str, &room))),\n )\n } else {\n const MAX_ITEM_BODY: usize = 10_000;\n@@ -1160,7 +1160,7 @@ pub async fn handle_rpc_batch(\n .map(|s| s.iter().cloned().collect())\n .unwrap_or_default();\n line_ok(RpcResult::GardenItem(ItemResponse {\n- item: item_path_for_api_in_room(&item_str, &room),\n+ item: GardenItemUrl::from_storage_str(&item_str, &room),\n body,\n truncated,\n body_len,\n@@ -1554,7 +1554,7 @@ pub async fn handle_rpc_batch(\n for r in items {\n let pct = want_percent.then(|| ((r.score - bot) / range * 100.0).clamp(0.0, 100.0));\n ranked.push(RankRow {\n- item: item_path_for_api_in_room(r.item.as_str(), &room),\n+ item: GardenItemUrl::from_storage_str(r.item.as_str(), &room),\n score: r.score,\n percent: pct,\n });\n@@ -1574,7 +1574,7 @@ pub async fn handle_rpc_batch(\n let page: Vec = ranked\n .into_iter()\n .chain(unranked.into_iter().map(|it| RankRow {\n- item: item_path_for_api_in_room(&it, &room),\n+ item: GardenItemUrl::from_storage_str(&it, &room),\n score: 0.0,\n percent: want_percent.then_some(0.0),\n }))\n@@ -1618,7 +1618,7 @@ pub async fn handle_rpc_batch(\n if !content.items.contains(&item) {\n line_err(\n \"item not found\",\n- Some(format!(\"{} does not exist\", item_path_for_api_in_room(&item_str, &room))),\n+ Some(format!(\"{} does not exist\", GardenItemUrl::from_storage_str(&item_str, &room))),\n )\n } else {\n let votes: Vec = content\n@@ -1629,8 +1629,8 @@ pub async fn handle_rpc_batch(\n .take(limit)\n .map(|v| VoteRow {\n ts: v.ts,\n- a: item_path_for_api_in_room(v.a.as_str(), &room),\n- b: item_path_for_api_in_room(v.b.as_str(), &room),\n+ a: GardenItemUrl::from_stored(&v.a, &room),\n+ b: GardenItemUrl::from_stored(&v.b, &room),\n ratio: format!(\"{}:{}\", v.ratio_left, v.ratio_right),\n actor: Some(v.principal.clone()),\n body: v.body.clone(),\n@@ -1640,7 +1640,7 @@ pub async fn handle_rpc_batch(\n })\n .unwrap_or_default();\n line_ok(RpcResult::Matchup(MatchupResponse {\n- item: item_path_for_api_in_room(&item_str, &room),\n+ item: GardenItemUrl::from_storage_str(&item_str, &room),\n votes,\n }))\n }\n@@ -1667,8 +1667,8 @@ pub async fn handle_rpc_batch(\n if a == item_str || b == item_str {\n Some(VoteRow {\n ts: e.ts,\n- a: item_path_for_api_in_room(&a, &room),\n- b: item_path_for_api_in_room(&b, &room),\n+ a: GardenItemUrl::from_storage_str(&a, &room),\n+ b: GardenItemUrl::from_storage_str(&b, &room),\n ratio: format!(\"{}:{}\", ratio_left, ratio_right),\n actor: reduced.ingests_by_id.get(&e.post_id).map(|ing| ing.principal.clone()),\n body: explanation,\n@@ -1704,7 +1704,7 @@ pub async fn handle_rpc_batch(\n }\n }).collect();\n line_ok(RpcResult::RankHistory(RankHistoryResponse {\n- item: item_path_for_api_in_room(&item_str, &room),\n+ item: GardenItemUrl::from_storage_str(&item_str, &room),\n history,\n }))\n }\n@@ -1716,17 +1716,13 @@ pub async fn handle_rpc_batch(\n } else {\n let content = content_for_room(&reduced, &room);\n let parents: HashSet<&str> = content.item_children.keys().map(|s| s.as_str()).collect();\n- let mut paths: Vec = content\n+ let mut paths: Vec = content\n .items\n .iter()\n .filter(|p| !parents.contains(p.as_str()))\n- .map(|p| p.as_str().to_string())\n- .collect();\n- paths.sort();\n- let paths: Vec = paths\n- .into_iter()\n- .map(|p| item_path_for_api_in_room(&p, &room))\n+ .map(|p| GardenItemUrl::from_stored(p, &room))\n .collect();\n+ paths.sort_by(|a, b| a.as_str().cmp(b.as_str()));\n line_ok(RpcResult::Leaves(LeavesResponse { paths }))\n }\n },\n@@ -1743,24 +1739,13 @@ pub async fn handle_rpc_batch(\n let mut v: Vec = roots.iter()\n .map(|path| {\n let children = content.item_children.get(path.as_str()).map(|s| s.len()).unwrap_or(0);\n- let path_label = CanonicalItemUrl::parse(path.as_str())\n- .and_then(|c| {\n- c.tilde_tail().map(|t| {\n- if t.is_empty() {\n- \"~/\".to_string()\n- } else {\n- format!(\"~/{}\", t)\n- }\n- })\n- })\n- .unwrap_or_else(|| path.to_string());\n PathSummary {\n- path: path_label,\n+ path: TildeOntologyPath::from_stored(path),\n children,\n- web: item_path_for_api_in_room(path.as_str(), &room),\n+ web: GardenItemUrl::from_stored(path, &room),\n }\n }).collect();\n- v.sort_by(|a, b| a.path.cmp(&b.path));\n+ v.sort_by(|a, b| a.path.as_str().cmp(b.path.as_str()));\n v\n })\n .unwrap_or_default();\n@@ -1790,8 +1775,8 @@ pub async fn handle_rpc_batch(\n .take(limit)\n .map(|v| VoteRow {\n ts: v.ts,\n- a: item_path_for_api_in_room(v.a.as_str(), &room),\n- b: item_path_for_api_in_room(v.b.as_str(), &room),\n+ a: GardenItemUrl::from_stored(&v.a, &room),\n+ b: GardenItemUrl::from_stored(&v.b, &room),\n ratio: format!(\"{}:{}\", v.ratio_left, v.ratio_right),\n actor: Some(v.principal.clone()),\n body: v.body.clone(),\ndiff --git a/server/src/api/validate.rs b/server/src/api/validate.rs\nindex 27150577982f52cbd6d11bb93654dc3d4cf75cc5..a51c783ee9785569b5a44c0b1572471fe00d174b 100644\n--- a/server/src/api/validate.rs\n+++ b/server/src/api/validate.rs\n@@ -7,8 +7,9 @@ use crate::{\n path_types::CanonicalItemUrl,\n reducer::{ReducerState, ScopeId},\n };\n+use slug_types::paths::GardenItemUrl;\n \n-use super::helpers::{item_path_for_api, resolve_item};\n+use super::helpers::resolve_item;\n \n #[derive(Debug)]\n pub struct ValidatedIngest {\n@@ -22,6 +23,10 @@ pub fn validate_ingest_document(\n text: &str,\n scope: &ScopeId,\n ) -> Result)> {\n+ let room_wire = match scope {\n+ ScopeId::Public => \"public\",\n+ ScopeId::Room(r) => r.as_str(),\n+ };\n let public_content = reduced.public();\n let scoped_content = match scope {\n ScopeId::Public => None,\n@@ -61,14 +66,14 @@ pub fn validate_ingest_document(\n let Some(body_text) = body else {\n return Err((\n StatusCode::BAD_REQUEST,\n- format!(\"item missing body: {}\", item_path_for_api(&item)),\n+ format!(\"item missing body: {}\", GardenItemUrl::from_storage_str(&item, room_wire)),\n Some(\"items must be declared with bodies, e.g. `~/path/item { ... }`\".to_string()),\n ));\n };\n if body_text.trim().is_empty() {\n return Err((\n StatusCode::BAD_REQUEST,\n- format!(\"item body is empty: {}\", item_path_for_api(&item)),\n+ format!(\"item body is empty: {}\", GardenItemUrl::from_storage_str(&item, room_wire)),\n Some(\"write at least one sentence inside `{ ... }`\".to_string()),\n ));\n }\n@@ -101,7 +106,7 @@ pub fn validate_ingest_document(\n let key = CanonicalItemUrl((*it).clone());\n !defined_in_doc.contains(*it) && !item_exists(&key)\n })\n- .map(|it| item_path_for_api(it))\n+ .map(|it| GardenItemUrl::from_storage_str(it, room_wire).into_inner())\n .collect();\n if !missing.is_empty() {\n return Err((\n@@ -119,7 +124,7 @@ pub fn validate_ingest_document(\n let key = CanonicalItemUrl((*it).clone());\n !defined_in_doc.contains(*it) && !body_exists(&key)\n })\n- .map(|it| item_path_for_api(it))\n+ .map(|it| GardenItemUrl::from_storage_str(it, room_wire).into_inner())\n .collect();\n if !missing_body.is_empty() {\n return Err((\ndiff --git a/server/src/canonical_path.rs b/server/src/canonical_path.rs\nindex 5c0febe883d8b3978a25896ed0d71df8509a8717..8a1998025121838b0867f8c5ddbd28aea41a23d2 100644\n--- a/server/src/canonical_path.rs\n+++ b/server/src/canonical_path.rs\n@@ -1,92 +1,3 @@\n-//! Normalization for thread tags and ontology item URLs (DSL ↔ stored canonical form).\n-//! Not event types — see `events` and `path_types`.\n+//! Re-exports — implementations live in `slug-types` (`paths` module).\n \n-/// Thread / public tag: stored without leading `#`, lowercase.\n-pub fn canonicalize_tag(input: &str) -> String {\n- input.trim().trim_start_matches('#').to_lowercase()\n-}\n-\n-/// Ontology item reference → canonical absolute URL on the slug host.\n-pub fn canonicalize_item(input: &str) -> String {\n- let s = input.trim();\n- if s.is_empty() {\n- return String::new();\n- }\n-\n- if let Some(rest) = s.strip_prefix(\"https://\") {\n- let (host, tail) = rest.split_once('/').map_or((rest, \"\"), |(h, t)| (h, t));\n- let host = host.trim().to_lowercase();\n- if tail.is_empty() {\n- return format!(\"https://{}\", host);\n- } else {\n- return format!(\"https://{}/{}\", host, tail);\n- }\n- }\n- if let Some(rest) = s.strip_prefix(\"http://\") {\n- let (host, tail) = rest.split_once('/').map_or((rest, \"\"), |(h, t)| (h, t));\n- let host = host.trim().to_lowercase();\n- if tail.is_empty() {\n- return format!(\"http://{}\", host);\n- } else {\n- return format!(\"http://{}/{}\", host, tail);\n- }\n- }\n-\n- let is_tilde = s.starts_with(\"~/\");\n- let rest = s.strip_prefix(\"~/\").or_else(|| s.strip_prefix(\"/\")).unwrap_or(s);\n-\n- let tail = rest\n- .split('/')\n- .filter_map(|seg| {\n- let t = seg.trim();\n- if t.is_empty() {\n- None\n- } else {\n- Some(t.to_lowercase())\n- }\n- })\n- .collect::>()\n- .join(\"/\");\n-\n- if is_tilde {\n- format!(\"https://slug.social/~/{}\", tail)\n- } else if tail.is_empty() {\n- \"https://slug.social\".to_string()\n- } else {\n- format!(\"https://slug.social/{}\", tail)\n- }\n-}\n-\n-pub fn item_path_segments(input: &str) -> Vec {\n- let canonical = canonicalize_item(input);\n- if canonical.is_empty() {\n- return vec![];\n- }\n-\n- if let Some(rest) = canonical.strip_prefix(\"https://\") {\n- let (host, tail) = rest.split_once('/').map_or((rest, \"\"), |(h, t)| (h, t));\n- let mut out = vec![format!(\"https://{}\", host)];\n- out.extend(tail.split('/').filter(|s| !s.is_empty()).map(|s| s.to_string()));\n- return out;\n- }\n- if let Some(rest) = canonical.strip_prefix(\"http://\") {\n- let (host, tail) = rest.split_once('/').map_or((rest, \"\"), |(h, t)| (h, t));\n- let mut out = vec![format!(\"http://{}\", host)];\n- out.extend(tail.split('/').filter(|s| !s.is_empty()).map(|s| s.to_string()));\n- return out;\n- }\n-\n- canonical\n- .split('/')\n- .filter(|s| !s.is_empty())\n- .map(|s| s.to_string())\n- .collect()\n-}\n-\n-pub fn item_parent_path(input: &str) -> Option {\n- let segs = item_path_segments(input);\n- if segs.len() <= 1 {\n- return None;\n- }\n- Some(segs[..segs.len() - 1].join(\"/\"))\n-}\n+pub use slug_types::paths::{canonicalize_item, canonicalize_tag, item_parent_path, item_path_segments};\ndiff --git a/server/src/html/forum.rs b/server/src/html/forum.rs\nindex ab7970feca47a4431ddc19dab2c8186180b78413..f789e347dc136f8ffd356f4492f0bd76cea04bf0 100644\n--- a/server/src/html/forum.rs\n+++ b/server/src/html/forum.rs\n@@ -697,7 +697,7 @@ async fn thread_view_inner(\n let offset = q.offset.unwrap_or(0);\n let page_ids: Vec = all_ids.into_iter().skip(offset).take(PAGE_SIZE).collect();\n \n- let (display_ingests, subtitle) = {\n+ let (display_ingests, _subtitle) = {\n let reduced = state.reduced.read().await;\n let ingests = page_ids\n .iter()\ndiff --git a/server/src/path_types.rs b/server/src/path_types.rs\nindex cad58cac7da948f92d6ea2a5587d917ab21d57ea..4c8075bbd488f1b9a5eda9e03ced83f6238c6d5e 100644\n--- a/server/src/path_types.rs\n+++ b/server/src/path_types.rs\n@@ -1,260 +1,3 @@\n-//! Path representation types.\n-//!\n-//! The codebase currently treats item identifiers as strings in a few different\n-//! encodings:\n-//! - user/DSL input like `~/a/b`\n-//! - canonical item URLs like `https://slug.social/~/a/b`\n-//! - relative paths within a rooted tree view (e.g. `llms/openai` under a root)\n-//!\n-//! This module adds lightweight newtypes so code can be explicit about what it\n-//! expects without changing core storage formats.\n-//!\n-//! **Storage vs wire:** [`CanonicalItemUrl`] values are shared across scopes\n-//! (`https://slug.social/~/…`); which [`crate::reducer::ContentState`] they live in\n-//! is determined by scope, not by embedding the room id in the string. For JSON/RPC\n-//! and browser links in a private room, use [`crate::api::helpers::item_path_for_api_in_room`]\n-//! so ontology items become `https://slug.social/r/{short}/{slug}/~/…`.\n+//! Re-exports — implementations live in `slug-types` (`paths` module).\n \n-use std::borrow::Borrow;\n-use std::fmt;\n-\n-use serde::{Deserialize, Serialize};\n-\n-use crate::canonical_path::canonicalize_item;\n-\n-/// Canonical item identifier as produced by `canonical_path::canonicalize_item`.\n-///\n-/// In practice this is usually:\n-/// - `https://slug.social/~/...` for ontology items, or\n-/// - `https://...` / `http://...` for URL items.\n-#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]\n-pub struct CanonicalItemUrl(pub String);\n-\n-impl CanonicalItemUrl {\n- pub fn parse(input: &str) -> Option {\n- let c = canonicalize_item(input);\n- if c.is_empty() {\n- None\n- } else {\n- Some(Self(c))\n- }\n- }\n-\n- pub fn as_str(&self) -> &str {\n- &self.0\n- }\n-\n- /// Returns the `~/...` tail for ontology items (`https://slug.social/~/...`).\n- pub fn tilde_tail(&self) -> Option<&str> {\n- self.0.strip_prefix(\"https://slug.social/~/\")\n- }\n-\n- /// Returns the final non-empty `/`-separated segment of the path.\n- ///\n- /// `https://slug.social/~/a/b/c` → `\"c\"`\n- /// `https://slug.social/~/a` → `\"a\"`\n- pub fn last_segment(&self) -> &str {\n- self.0\n- .rsplit('/')\n- .find(|s| !s.is_empty())\n- .unwrap_or(self.0.as_str())\n- }\n-\n- /// The ontology root key as stored in `item_children`: `\"https://slug.social/~\"`.\n- /// Use this (not `parse(\"~/\")`) when looking up top-level children.\n- pub fn ontology_root() -> Self {\n- Self(\"https://slug.social/~\".to_string())\n- }\n-\n- /// Returns the parent of this canonical item URL by stripping the last\n- /// path segment, or `None` if there is no parent (already at root).\n- ///\n- /// `https://slug.social/~/a/b/c` → `Some(\"https://slug.social/~/a/b\")`\n- /// `https://slug.social/~/a` → `Some(\"https://slug.social/~\")`\n- /// `https://slug.social/~/` → `None` (tilde root)\n- pub fn parent(&self) -> Option {\n- // tilde_tail() is None for non-ontology URLs and \"\" for the root ~/\n- if self.tilde_tail().map(|t| t.is_empty()).unwrap_or(true) {\n- return None;\n- }\n- // Strip everything from the last '/' onwards.\n- let last_slash = self.0.rfind('/')?;\n- let parent_str = &self.0[..last_slash];\n- if parent_str.is_empty() {\n- None\n- } else {\n- Some(Self(parent_str.to_string()))\n- }\n- }\n-\n- /// Segments of an ontology path suitable for breadcrumb rendering.\n- /// Strips the `https://slug.social` prefix and returns the `~/…` parts.\n- ///\n- /// `https://slug.social/~/a/b` → `[\"~\", \"a\", \"b\"]`\n- /// `https://slug.social/~/` → `[\"~\"]`\n- pub fn tilde_segments(&self) -> Vec<&str> {\n- match self.tilde_tail() {\n- Some(tail) if !tail.is_empty() => {\n- std::iter::once(\"~\")\n- .chain(tail.split('/').filter(|s| !s.is_empty()))\n- .collect()\n- }\n- Some(_) => vec![\"~\"],\n- None => vec![],\n- }\n- }\n-}\n-\n-impl fmt::Display for CanonicalItemUrl {\n- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n- self.0.fmt(f)\n- }\n-}\n-\n-/// Allow `HashMap` to be searched by `&str`.\n-impl Borrow for CanonicalItemUrl {\n- fn borrow(&self) -> &str {\n- &self.0\n- }\n-}\n-\n-impl PartialEq for CanonicalItemUrl {\n- fn eq(&self, other: &str) -> bool {\n- self.0 == other\n- }\n-}\n-\n-impl PartialEq<&str> for CanonicalItemUrl {\n- fn eq(&self, other: &&str) -> bool {\n- self.0 == *other\n- }\n-}\n-\n-impl PartialEq for CanonicalItemUrl {\n- fn eq(&self, other: &String) -> bool {\n- &self.0 == other\n- }\n-}\n-\n-/// A `~/...` input path (as used in the DSL and UX).\n-///\n-/// This is not canonicalized; it is a presentation/input form.\n-#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]\n-pub struct TildePath(pub String);\n-\n-impl TildePath {\n- pub fn new(input: &str) -> Option {\n- let s = input.trim();\n- if s.starts_with(\"~/\") && s.len() > 2 {\n- Some(Self(s.to_string()))\n- } else if s == \"~/\" {\n- Some(Self(\"~/\".to_string()))\n- } else {\n- None\n- }\n- }\n-\n- pub fn as_str(&self) -> &str {\n- &self.0\n- }\n-\n- pub fn canonicalize(&self) -> Option {\n- CanonicalItemUrl::parse(&self.0)\n- }\n-}\n-\n-impl fmt::Display for TildePath {\n- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n- self.0.fmt(f)\n- }\n-}\n-\n-/// A path relative to a chosen root in a tree UI.\n-///\n-/// This is intended for compact state encodings (blobs). It must be joined to a\n-/// root `CanonicalItemUrl` (typically an ontology root) to become a full item.\n-#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]\n-pub struct RelativePath(pub String);\n-\n-impl RelativePath {\n- pub fn new(input: &str) -> Option {\n- let s = input.trim().trim_matches('/');\n- if s.is_empty() {\n- Some(Self(String::new()))\n- } else {\n- // Keep this permissive: the DSL parser is the main gatekeeper.\n- Some(Self(s.to_string()))\n- }\n- }\n-\n- pub fn as_str(&self) -> &str {\n- &self.0\n- }\n-\n- /// Join this relative path under a canonical ontology root\n- /// (`https://slug.social/~/...`) to form a canonical item URL.\n- pub fn join_under_ontology_root(&self, root: &CanonicalItemUrl) -> Option {\n- let base = root.tilde_tail()?;\n- // base is the tail after https://slug.social/~/, e.g. \"models\" or \"models/llms\"\n- let joined = if base.is_empty() {\n- if self.0.is_empty() {\n- \"~/\".to_string()\n- } else {\n- format!(\"~/{}\", self.0)\n- }\n- } else if self.0.is_empty() {\n- format!(\"~/{}\", base)\n- } else {\n- format!(\"~/{}/{}\", base.trim_end_matches('/'), self.0)\n- };\n- CanonicalItemUrl::parse(&joined)\n- }\n-}\n-\n-impl fmt::Display for RelativePath {\n- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n- self.0.fmt(f)\n- }\n-}\n-\n-\n-#[cfg(test)]\n-mod tests {\n- use super::*;\n-\n- #[test]\n- fn canonical_parent_deep() {\n- let c = CanonicalItemUrl::parse(\"~/a/b/c\").unwrap();\n- assert_eq!(c.parent().unwrap().as_str(), \"https://slug.social/~/a/b\");\n- }\n-\n- #[test]\n- fn canonical_parent_one_level() {\n- let c = CanonicalItemUrl::parse(\"~/a\").unwrap();\n- assert_eq!(c.parent().unwrap().as_str(), \"https://slug.social/~\");\n- }\n-\n- #[test]\n- fn canonical_parent_root_is_none() {\n- let root = CanonicalItemUrl::parse(\"~/\").unwrap();\n- assert!(root.parent().is_none());\n- }\n-\n- #[test]\n- fn tilde_segments_deep() {\n- let c = CanonicalItemUrl::parse(\"~/a/b\").unwrap();\n- assert_eq!(c.tilde_segments(), vec![\"~\", \"a\", \"b\"]);\n- }\n-\n- #[test]\n- fn tilde_segments_root() {\n- let c = CanonicalItemUrl::parse(\"~/\").unwrap();\n- assert_eq!(c.tilde_segments(), vec![\"~\"]);\n- }\n-\n- #[test]\n- fn tilde_segments_non_ontology_is_empty() {\n- let c = CanonicalItemUrl::parse(\"https://example.com/foo\").unwrap();\n- assert_eq!(c.tilde_segments(), Vec::<&str>::new());\n- }\n-}\n+pub use slug_types::paths::{CanonicalItemUrl, RelativePath, TildePath};\ndiff --git a/types/src/lib.rs b/types/src/lib.rs\nindex c1cde3b783d03b02783385b5f07659fb112aae3e..5fc867bf2af84c2ca63fa1cdd03413110ad784a3 100644\n--- a/types/src/lib.rs\n+++ b/types/src/lib.rs\n@@ -1,7 +1,13 @@\n use serde::{Deserialize, Serialize};\n \n+pub mod paths;\n pub mod timeago;\n \n+pub use paths::{\n+ canonicalize_item, canonicalize_tag, item_parent_path, item_path_segments, CanonicalItemUrl,\n+ ForumThreadUrl, GardenItemUrl, RelativePath, TildeOntologyPath, TildePath,\n+};\n+\n #[derive(Debug, Serialize, Deserialize)]\n pub struct ApiError {\n pub ok: bool,\n@@ -12,7 +18,7 @@ pub struct ApiError {\n \n #[derive(Debug, Clone, Serialize, Deserialize)]\n pub struct RankRow {\n- pub item: String,\n+ pub item: GardenItemUrl,\n pub score: f64,\n /// Normalized score as a percentage of the top item (0–100). Present when ?percent=true.\n #[serde(skip_serializing_if = \"Option::is_none\")]\n@@ -43,7 +49,7 @@ pub struct RankComponent {\n #[derive(Debug, Serialize, Deserialize)]\n pub struct RankResponse {\n pub components: Vec,\n- pub unranked_items: Vec,\n+ pub unranked_items: Vec,\n }\n \n /// Graph connectivity stats for a scope, returned with pair suggestions.\n@@ -63,8 +69,8 @@ pub struct ConnectivityStats {\n \n #[derive(Debug, Serialize, Deserialize)]\n pub struct PairResponse {\n- pub left: String,\n- pub right: String,\n+ pub left: GardenItemUrl,\n+ pub right: GardenItemUrl,\n pub left_body: Option,\n pub right_body: Option,\n /// Thread tags that discuss either item (connective tissue to forum).\n@@ -79,7 +85,7 @@ pub struct PairResponse {\n pub struct NextMoves {\n pub pair: String,\n pub rank: String,\n- pub web: String,\n+ pub web: ForumThreadUrl,\n }\n \n #[derive(Debug, Serialize, Deserialize)]\n@@ -90,14 +96,14 @@ pub struct PathsResponse {\n /// Leaf items only (no children). For search / \"full path list\" — does not scale, works for now.\n #[derive(Debug, Serialize, Deserialize)]\n pub struct LeavesResponse {\n- pub paths: Vec,\n+ pub paths: Vec,\n }\n \n #[derive(Debug, Serialize, Deserialize)]\n pub struct PathSummary {\n- pub path: String,\n+ pub path: TildeOntologyPath,\n pub children: usize,\n- pub web: String,\n+ pub web: GardenItemUrl,\n }\n \n #[derive(Debug, Clone, Serialize, Deserialize)]\n@@ -109,7 +115,7 @@ pub struct ThreadsResponse {\n pub struct ThreadSummary {\n pub thread: String,\n pub last_activity_ts: i64,\n- pub web: String,\n+ pub web: ForumThreadUrl,\n }\n \n #[derive(Debug, Serialize, Deserialize)]\n@@ -178,7 +184,7 @@ pub struct IngestRow {\n \n #[derive(Debug, Serialize, Deserialize)]\n pub struct ItemResponse {\n- pub item: String,\n+ pub item: GardenItemUrl,\n pub body: Option,\n /// True when the body was truncated due to size. Fetch with `?full=true` for the complete body.\n #[serde(default, skip_serializing_if = \"std::ops::Not::not\")]\n@@ -201,15 +207,15 @@ pub struct RecentVotesResponse {\n /// Vote history for one item (matchup: wins/losses + thread per vote).\n #[derive(Debug, Serialize, Deserialize)]\n pub struct MatchupResponse {\n- pub item: String,\n+ pub item: GardenItemUrl,\n pub votes: Vec,\n }\n \n #[derive(Debug, Clone, Serialize, Deserialize)]\n pub struct VoteRow {\n pub ts: i64,\n- pub a: String,\n- pub b: String,\n+ pub a: GardenItemUrl,\n+ pub b: GardenItemUrl,\n pub ratio: String,\n /// Principal username when present (stored form, no `@`).\n pub actor: Option,\n@@ -510,7 +516,7 @@ pub struct RankPosition {\n /// How one item's rank changed after a vote.\n #[derive(Debug, Clone, Serialize, Deserialize)]\n pub struct RankChange {\n- pub item: String,\n+ pub item: GardenItemUrl,\n /// Position before the vote. None = was unranked (no voted connections in this scope).\n pub before: Option,\n /// Position after the vote. None = became unranked (e.g. component split, unlikely).\n@@ -544,7 +550,7 @@ pub struct CheckScopeRanking {\n /// Parent scope path (e.g. \"/models\" or \"/\" for root).\n pub parent: String,\n pub components: Vec,\n- pub unranked_items: Vec,\n+ pub unranked_items: Vec,\n }\n \n #[derive(Debug, Serialize, Deserialize)]\n@@ -567,7 +573,7 @@ pub struct SearchResponse {\n \n #[derive(Debug, Serialize, Deserialize)]\n pub struct SearchItemHit {\n- pub path: String,\n+ pub path: GardenItemUrl,\n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub body: Option,\n }\n@@ -614,7 +620,7 @@ pub struct RankHistoryRow {\n \n #[derive(Debug, Serialize, Deserialize)]\n pub struct RankHistoryResponse {\n- pub item: String,\n+ pub item: GardenItemUrl,\n pub history: Vec,\n }\n \ndiff --git a/types/src/paths.rs b/types/src/paths.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..2950a7502255927583fbacdfd2adb700f0b0c221\n--- /dev/null\n+++ b/types/src/paths.rs\n@@ -0,0 +1,498 @@\n+//! Canonical paths, storage ids, and JSON href newtypes. All normalization and\n+//! room-aware URL rules for items live here.\n+\n+use std::borrow::Borrow;\n+use std::fmt;\n+\n+use serde::{Deserialize, Serialize};\n+\n+// ---------------------------------------------------------------------------\n+// Normalization (moved from server `canonical_path`)\n+// ---------------------------------------------------------------------------\n+\n+/// Thread / public tag: stored without leading `#`, lowercase.\n+pub fn canonicalize_tag(input: &str) -> String {\n+ input.trim().trim_start_matches('#').to_lowercase()\n+}\n+\n+/// Ontology item reference → canonical absolute URL on the slug host.\n+pub fn canonicalize_item(input: &str) -> String {\n+ let s = input.trim();\n+ if s.is_empty() {\n+ return String::new();\n+ }\n+\n+ if let Some(rest) = s.strip_prefix(\"https://\") {\n+ let (host, tail) = rest.split_once('/').map_or((rest, \"\"), |(h, t)| (h, t));\n+ let host = host.trim().to_lowercase();\n+ if tail.is_empty() {\n+ return format!(\"https://{}\", host);\n+ } else {\n+ return format!(\"https://{}/{}\", host, tail);\n+ }\n+ }\n+ if let Some(rest) = s.strip_prefix(\"http://\") {\n+ let (host, tail) = rest.split_once('/').map_or((rest, \"\"), |(h, t)| (h, t));\n+ let host = host.trim().to_lowercase();\n+ if tail.is_empty() {\n+ return format!(\"http://{}\", host);\n+ } else {\n+ return format!(\"http://{}/{}\", host, tail);\n+ }\n+ }\n+\n+ let is_tilde = s.starts_with(\"~/\");\n+ let rest = s.strip_prefix(\"~/\").or_else(|| s.strip_prefix(\"/\")).unwrap_or(s);\n+\n+ let tail = rest\n+ .split('/')\n+ .filter_map(|seg| {\n+ let t = seg.trim();\n+ if t.is_empty() {\n+ None\n+ } else {\n+ Some(t.to_lowercase())\n+ }\n+ })\n+ .collect::>()\n+ .join(\"/\");\n+\n+ if is_tilde {\n+ format!(\"https://slug.social/~/{}\", tail)\n+ } else if tail.is_empty() {\n+ \"https://slug.social\".to_string()\n+ } else {\n+ format!(\"https://slug.social/{}\", tail)\n+ }\n+}\n+\n+pub fn item_path_segments(input: &str) -> Vec {\n+ let canonical = canonicalize_item(input);\n+ if canonical.is_empty() {\n+ return vec![];\n+ }\n+\n+ if let Some(rest) = canonical.strip_prefix(\"https://\") {\n+ let (host, tail) = rest.split_once('/').map_or((rest, \"\"), |(h, t)| (h, t));\n+ let mut out = vec![format!(\"https://{}\", host)];\n+ out.extend(tail.split('/').filter(|s| !s.is_empty()).map(|s| s.to_string()));\n+ return out;\n+ }\n+ if let Some(rest) = canonical.strip_prefix(\"http://\") {\n+ let (host, tail) = rest.split_once('/').map_or((rest, \"\"), |(h, t)| (h, t));\n+ let mut out = vec![format!(\"http://{}\", host)];\n+ out.extend(tail.split('/').filter(|s| !s.is_empty()).map(|s| s.to_string()));\n+ return out;\n+ }\n+\n+ canonical\n+ .split('/')\n+ .filter(|s| !s.is_empty())\n+ .map(|s| s.to_string())\n+ .collect()\n+}\n+\n+pub fn item_parent_path(input: &str) -> Option {\n+ let segs = item_path_segments(input);\n+ if segs.len() <= 1 {\n+ return None;\n+ }\n+ Some(segs[..segs.len() - 1].join(\"/\"))\n+}\n+\n+// ---------------------------------------------------------------------------\n+// Storage + input path newtypes\n+// ---------------------------------------------------------------------------\n+\n+/// Canonical item identifier as produced by [`canonicalize_item`].\n+///\n+/// Shared across all scopes; room is not embedded. Usually\n+/// `https://slug.social/~/…` or an external `http(s)://…` URL item.\n+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]\n+pub struct CanonicalItemUrl(pub String);\n+\n+impl CanonicalItemUrl {\n+ pub fn parse(input: &str) -> Option {\n+ let c = canonicalize_item(input);\n+ if c.is_empty() {\n+ None\n+ } else {\n+ Some(Self(c))\n+ }\n+ }\n+\n+ pub fn as_str(&self) -> &str {\n+ &self.0\n+ }\n+\n+ pub fn tilde_tail(&self) -> Option<&str> {\n+ self.0.strip_prefix(\"https://slug.social/~/\")\n+ }\n+\n+ pub fn last_segment(&self) -> &str {\n+ self.0\n+ .rsplit('/')\n+ .find(|s| !s.is_empty())\n+ .unwrap_or(self.0.as_str())\n+ }\n+\n+ pub fn ontology_root() -> Self {\n+ Self(\"https://slug.social/~\".to_string())\n+ }\n+\n+ pub fn parent(&self) -> Option {\n+ if self.tilde_tail().map(|t| t.is_empty()).unwrap_or(true) {\n+ return None;\n+ }\n+ let last_slash = self.0.rfind('/')?;\n+ let parent_str = &self.0[..last_slash];\n+ if parent_str.is_empty() {\n+ None\n+ } else {\n+ Some(Self(parent_str.to_string()))\n+ }\n+ }\n+\n+ pub fn tilde_segments(&self) -> Vec<&str> {\n+ match self.tilde_tail() {\n+ Some(tail) if !tail.is_empty() => {\n+ std::iter::once(\"~\")\n+ .chain(tail.split('/').filter(|s| !s.is_empty()))\n+ .collect()\n+ }\n+ Some(_) => vec![\"~\"],\n+ None => vec![],\n+ }\n+ }\n+\n+ /// `~/…` list label for ontology items (paths index, CLI).\n+ pub fn tilde_list_label(&self) -> TildeOntologyPath {\n+ TildeOntologyPath::from_stored(self)\n+ }\n+\n+ /// Absolute href for JSON/RPC and browsers for this stored id in `room`.\n+ pub fn json_href(&self, room_wire: &str) -> GardenItemUrl {\n+ GardenItemUrl::from_stored(self, room_wire)\n+ }\n+}\n+\n+impl fmt::Display for CanonicalItemUrl {\n+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n+ self.0.fmt(f)\n+ }\n+}\n+\n+impl Borrow for CanonicalItemUrl {\n+ fn borrow(&self) -> &str {\n+ &self.0\n+ }\n+}\n+\n+impl PartialEq for CanonicalItemUrl {\n+ fn eq(&self, other: &str) -> bool {\n+ self.0 == other\n+ }\n+}\n+\n+impl PartialEq<&str> for CanonicalItemUrl {\n+ fn eq(&self, other: &&str) -> bool {\n+ self.0 == *other\n+ }\n+}\n+\n+impl PartialEq for CanonicalItemUrl {\n+ fn eq(&self, other: &String) -> bool {\n+ &self.0 == other\n+ }\n+}\n+\n+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]\n+pub struct TildePath(pub String);\n+\n+impl TildePath {\n+ pub fn new(input: &str) -> Option {\n+ let s = input.trim();\n+ if s.starts_with(\"~/\") && s.len() > 2 {\n+ Some(Self(s.to_string()))\n+ } else if s == \"~/\" {\n+ Some(Self(\"~/\".to_string()))\n+ } else {\n+ None\n+ }\n+ }\n+\n+ pub fn as_str(&self) -> &str {\n+ &self.0\n+ }\n+\n+ pub fn canonicalize(&self) -> Option {\n+ CanonicalItemUrl::parse(&self.0)\n+ }\n+}\n+\n+impl fmt::Display for TildePath {\n+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n+ self.0.fmt(f)\n+ }\n+}\n+\n+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]\n+pub struct RelativePath(pub String);\n+\n+impl RelativePath {\n+ pub fn new(input: &str) -> Option {\n+ let s = input.trim().trim_matches('/');\n+ if s.is_empty() {\n+ Some(Self(String::new()))\n+ } else {\n+ Some(Self(s.to_string()))\n+ }\n+ }\n+\n+ pub fn as_str(&self) -> &str {\n+ &self.0\n+ }\n+\n+ pub fn join_under_ontology_root(&self, root: &CanonicalItemUrl) -> Option {\n+ let base = root.tilde_tail()?;\n+ let joined = if base.is_empty() {\n+ if self.0.is_empty() {\n+ \"~/\".to_string()\n+ } else {\n+ format!(\"~/{}\", self.0)\n+ }\n+ } else if self.0.is_empty() {\n+ format!(\"~/{}\", base)\n+ } else {\n+ format!(\"~/{}/{}\", base.trim_end_matches('/'), self.0)\n+ };\n+ CanonicalItemUrl::parse(&joined)\n+ }\n+}\n+\n+impl fmt::Display for RelativePath {\n+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n+ self.0.fmt(f)\n+ }\n+}\n+\n+// ---------------------------------------------------------------------------\n+// Wire / JSON: correct-by-construction hrefs\n+// ---------------------------------------------------------------------------\n+\n+fn api_path_or_url(item: &str) -> String {\n+ if item.starts_with(\"http://\") || item.starts_with(\"https://\") {\n+ item.to_string()\n+ } else {\n+ format!(\"/{}\", item)\n+ }\n+}\n+\n+/// Ontology item as serialized in JSON (absolute URL or `/`-prefixed path).\n+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]\n+#[serde(transparent)]\n+pub struct GardenItemUrl(pub String);\n+\n+impl GardenItemUrl {\n+ pub fn as_str(&self) -> &str {\n+ &self.0\n+ }\n+\n+ pub fn into_inner(self) -> String {\n+ self.0\n+ }\n+\n+ /// Stored canonical id + RPC `room` field (`\"public\"` or `\"short/slug\"`).\n+ pub fn from_stored(stored: &CanonicalItemUrl, room_wire: &str) -> Self {\n+ Self(garden_href_string(stored.as_str(), room_wire))\n+ }\n+\n+ /// Like [`Self::from_stored`] but accepts a string that may already be canonical.\n+ pub fn from_storage_str(stored: &str, room_wire: &str) -> Self {\n+ Self(garden_href_string(stored, room_wire))\n+ }\n+}\n+\n+impl fmt::Display for GardenItemUrl {\n+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n+ self.0.fmt(f)\n+ }\n+}\n+\n+fn garden_href_string(item: &str, room_wire: &str) -> String {\n+ let room = room_wire.trim();\n+ if room.is_empty() || room == \"public\" {\n+ return api_path_or_url(item);\n+ }\n+ let Some((short, slug)) = room.split_once('/') else {\n+ return api_path_or_url(item);\n+ };\n+ if short.is_empty() || slug.is_empty() {\n+ return api_path_or_url(item);\n+ }\n+ let Some(c) = CanonicalItemUrl::parse(item) else {\n+ return api_path_or_url(item);\n+ };\n+ let root = CanonicalItemUrl::ontology_root();\n+ let item_norm = c.as_str().trim_end_matches('/');\n+ let root_norm = root.as_str().trim_end_matches('/');\n+ if let Some(tail) = c.tilde_tail() {\n+ return if tail.is_empty() {\n+ format!(\"https://slug.social/r/{short}/{slug}/~\")\n+ } else {\n+ format!(\"https://slug.social/r/{short}/{slug}/~/{}\", tail)\n+ };\n+ }\n+ if item_norm == root_norm {\n+ return format!(\"https://slug.social/r/{short}/{slug}/~\");\n+ }\n+ api_path_or_url(item)\n+}\n+\n+/// Forum thread URL for JSON (`/t/…` or `/r/…/t/…` on slug.social).\n+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]\n+#[serde(transparent)]\n+pub struct ForumThreadUrl(pub String);\n+\n+impl ForumThreadUrl {\n+ pub fn as_str(&self) -> &str {\n+ &self.0\n+ }\n+\n+ pub fn into_inner(self) -> String {\n+ self.0\n+ }\n+\n+ pub fn from_room_tag(room_wire: &str, thread_tag: &str) -> Self {\n+ let room = room_wire.trim();\n+ let tag = thread_tag.trim().trim_start_matches('#');\n+ Self(if room.is_empty() || room == \"public\" {\n+ format!(\"https://slug.social/t/{tag}\")\n+ } else if let Some((short, slug)) = room.split_once('/') {\n+ if short.is_empty() || slug.is_empty() {\n+ format!(\"https://slug.social/t/{tag}\")\n+ } else {\n+ format!(\"https://slug.social/r/{short}/{slug}/t/{tag}\")\n+ }\n+ } else {\n+ format!(\"https://slug.social/t/{tag}\")\n+ })\n+ }\n+}\n+\n+impl fmt::Display for ForumThreadUrl {\n+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n+ self.0.fmt(f)\n+ }\n+}\n+\n+/// `~/a/b` style path for list UIs (paths index `path` field).\n+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]\n+#[serde(transparent)]\n+pub struct TildeOntologyPath(pub String);\n+\n+impl TildeOntologyPath {\n+ pub fn from_stored(c: &CanonicalItemUrl) -> Self {\n+ let s = match c.tilde_tail() {\n+ Some(tail) if !tail.is_empty() => format!(\"~/{}\", tail),\n+ Some(_) => \"~/\".to_string(),\n+ None => c.to_string(),\n+ };\n+ Self(s)\n+ }\n+\n+ pub fn as_str(&self) -> &str {\n+ &self.0\n+ }\n+}\n+\n+impl fmt::Display for TildeOntologyPath {\n+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n+ self.0.fmt(f)\n+ }\n+}\n+\n+#[cfg(test)]\n+mod tests {\n+ use super::*;\n+\n+ #[test]\n+ fn canonical_parent_deep() {\n+ let c = CanonicalItemUrl::parse(\"~/a/b/c\").unwrap();\n+ assert_eq!(c.parent().unwrap().as_str(), \"https://slug.social/~/a/b\");\n+ }\n+\n+ #[test]\n+ fn canonical_parent_one_level() {\n+ let c = CanonicalItemUrl::parse(\"~/a\").unwrap();\n+ assert_eq!(c.parent().unwrap().as_str(), \"https://slug.social/~\");\n+ }\n+\n+ #[test]\n+ fn canonical_parent_root_is_none() {\n+ let root = CanonicalItemUrl::parse(\"~/\").unwrap();\n+ assert!(root.parent().is_none());\n+ }\n+\n+ #[test]\n+ fn tilde_segments_deep() {\n+ let c = CanonicalItemUrl::parse(\"~/a/b\").unwrap();\n+ assert_eq!(c.tilde_segments(), vec![\"~\", \"a\", \"b\"]);\n+ }\n+\n+ #[test]\n+ fn tilde_segments_root() {\n+ let c = CanonicalItemUrl::parse(\"~/\").unwrap();\n+ assert_eq!(c.tilde_segments(), vec![\"~\"]);\n+ }\n+\n+ #[test]\n+ fn tilde_segments_non_ontology_is_empty() {\n+ let c = CanonicalItemUrl::parse(\"https://example.com/foo\").unwrap();\n+ assert_eq!(c.tilde_segments(), Vec::<&str>::new());\n+ }\n+\n+ #[test]\n+ fn garden_public_passthrough_https() {\n+ let u = \"https://slug.social/~/a/b\";\n+ assert_eq!(GardenItemUrl::from_storage_str(u, \"public\").as_str(), u);\n+ }\n+\n+ #[test]\n+ fn garden_private_room_prefixes_ontology() {\n+ assert_eq!(\n+ GardenItemUrl::from_storage_str(\"https://slug.social/~/topic/x\", \"9ab12cd/my-room\").as_str(),\n+ \"https://slug.social/r/9ab12cd/my-room/~/topic/x\"\n+ );\n+ }\n+\n+ #[test]\n+ fn garden_private_room_ontology_root() {\n+ assert_eq!(\n+ GardenItemUrl::from_storage_str(\"https://slug.social/~\", \"9ab12cd/my-room\").as_str(),\n+ \"https://slug.social/r/9ab12cd/my-room/~\"\n+ );\n+ assert_eq!(\n+ GardenItemUrl::from_storage_str(\"https://slug.social/~/\", \"9ab12cd/my-room\").as_str(),\n+ \"https://slug.social/r/9ab12cd/my-room/~\"\n+ );\n+ }\n+\n+ #[test]\n+ fn garden_external_url_untouched_in_private_room() {\n+ let u = \"https://example.com/z\";\n+ assert_eq!(GardenItemUrl::from_storage_str(u, \"9ab12cd/my-room\").as_str(), u);\n+ }\n+\n+ #[test]\n+ fn forum_web_public_vs_room() {\n+ assert_eq!(\n+ ForumThreadUrl::from_room_tag(\"public\", \"debate\").as_str(),\n+ \"https://slug.social/t/debate\"\n+ );\n+ assert_eq!(\n+ ForumThreadUrl::from_room_tag(\"9ab12cd/my-room\", \"#debate\").as_str(),\n+ \"https://slug.social/r/9ab12cd/my-room/t/debate\"\n+ );\n+ }\n+}\n\n\nSide B — contributor: tommy-mor\nSide B — commit message:\n[88577c56] reconfigure\n\nSide B — unified diff (full patch):\ndiff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs\nindex c4ab9d65c7b3cd42a5b4d093ba429993c101e9a8..82b2aa51d21ada1d0d849d3ddfc3a81e4241d861 100644\n--- a/server/src/api/ui_html.rs\n+++ b/server/src/api/ui_html.rs\n@@ -9,7 +9,9 @@ use crate::{\n html::{js_string_literal, ranking_panel, JsBuilder},\n parser::parse_reddit_url,\n parser_render::navigate_panel,\n- state::AppState,\n+ path_types::ItemId,\n+ reddit::ensure_partial_tree,\n+ state::{parse_item_param, AppState},\n ui_action::{parse_html_ui_from_form, HtmlUiAction},\n };\n \n@@ -25,6 +27,10 @@ fn ui_js_warn(msg: &str) -> Response {\n .unwrap()\n }\n \n+fn parent_from_scope(scope: &str) -> ItemId {\n+ parse_item_param(scope)\n+}\n+\n pub async fn post_ui_html(\n State(state): State,\n Form(form): Form>,\n@@ -42,24 +48,36 @@ pub async fn post_ui_html(\n ratio_right,\n scope,\n } => {\n+ let parent = parent_from_scope(&scope);\n if let Err(e) = state\n- .record_vote(&scope, &a, &b, ratio_left, ratio_right)\n+ .record_vote(&parent, &a, &b, ratio_left, ratio_right)\n .await\n {\n return ui_js_warn(&e).into_response();\n }\n- let scope = crate::state::normalize_scope(&scope);\n- let groups = state.groups.read().await;\n+ let tree = state.tree.read().await;\n let empty = crate::reducer::GroupState::new();\n- let group = groups.get(&scope).unwrap_or(&empty);\n- let panel = ranking_panel(&scope, group);\n+ let group = tree\n+ .get(&parent)\n+ .map(|n| &n.local_ranking)\n+ .unwrap_or(&empty);\n+ let panel = ranking_panel(&parent, group);\n JsBuilder::new()\n .morph_selector(\"#ranking-panel\", panel)\n .into_response()\n }\n HtmlUiAction::ParseQuery { query } => match parse_reddit_url(&query) {\n- Ok(subreddit) => {\n- let dest = format!(\"/?sub={subreddit}\");\n+ Ok(item) => {\n+ {\n+ let mut tree = state.tree.write().await;\n+ ensure_partial_tree(&mut tree, &item);\n+ }\n+ let _ = state.ensure_node(&item).await;\n+ let dest = if item.is_root() {\n+ \"/\".to_string()\n+ } else {\n+ format!(\"/?item={}\", item.as_str())\n+ };\n JsBuilder::new()\n .raw(&format!(\n \"window.location.href={};\",\ndiff --git a/server/src/events.rs b/server/src/events.rs\nindex a862370fc840ffe02184a11c578e18239cc9474d..ed5be6b13b9d46e838831d6ce0f96f569b401730 100644\n--- a/server/src/events.rs\n+++ b/server/src/events.rs\n@@ -5,8 +5,8 @@ use serde::{Deserialize, Serialize};\n pub enum Event {\n /// Page view recorded (path → counter in views.json).\n ViewRecorded { path: String, ts: i64 },\n- /// Pairwise comparison vote (replayed into the scope's [`crate::reducer::GroupState`] on boot).\n- /// `scope` is the ranking subject (e.g. a subreddit); empty string is the default/global scope.\n+ /// Pairwise comparison vote (replayed into the parent node's [`crate::reducer::GroupState`] on boot).\n+ /// `scope` is the parent [`crate::path_types::ItemId`] string; empty string is the tree root.\n VoteRecorded {\n ts: i64,\n a: String,\n@@ -16,4 +16,6 @@ pub enum Event {\n #[serde(default)]\n scope: String,\n },\n+ /// Register a node path in the fractal tree (no external fetch).\n+ NodeEnsured { id: String },\n }\ndiff --git a/server/src/html/mod.rs b/server/src/html/mod.rs\nindex 9650d333d29c4ac94ceb407aee3ee00399c7f40b..c973cb718ac74b95570dabea76e24459417790b9 100644\n--- a/server/src/html/mod.rs\n+++ b/server/src/html/mod.rs\n@@ -12,9 +12,10 @@ use serde::Deserialize;\n use crate::{\n form_template::template_json_compact,\n parser_render::navigate_panel,\n+ path_types::ItemId,\n ranking::{top_bottom, RankedItem},\n- reducer::GroupState,\n- state::{normalize_scope, AppState},\n+ reducer::{GroupState, NodeState},\n+ state::{parse_item_param, AppState},\n ui_action::UI_RPC_FIELD,\n };\n \n@@ -216,6 +217,48 @@ fn layout(title: &str, body: Markup, views: u64, theme: &str, theme_next: &str)\n }\n }\n \n+fn item_href(id: &ItemId) -> String {\n+ if id.is_root() {\n+ \"/\".to_string()\n+ } else {\n+ format!(\"/?item={}\", id.as_str())\n+ }\n+}\n+\n+fn segment_label(seg: &str) -> &str {\n+ seg\n+}\n+\n+/// Generic breadcrumb trail from an [`ItemId`] path.\n+pub fn breadcrumb_path(item: &ItemId) -> Markup {\n+ html! {\n+ nav class=\"breadcrumbs\" aria-label=\"Breadcrumb\" {\n+ a href=\"/\" { \"Internet\" }\n+ @for path in item.breadcrumb_paths() {\n+ @let seg = path.segments().last().map_or(\"\", |v| *v);\n+ span class=\"separator\" { \" / \" }\n+ a href=(item_href(&path)) { (segment_label(seg)) }\n+ }\n+ }\n+ }\n+}\n+\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+ h2 { (data.title) }\n+ @if let Some(author) = &data.author {\n+ p class=\"muted small\" { \"by \" (author) }\n+ }\n+ @if let Some(body) = &data.body_html {\n+ div class=\"entity-body\" { (maud::PreEscaped(body)) }\n+ }\n+ }\n+ }\n+ }\n+}\n+\n fn rank_list(label: &str, items: &[RankedItem], start_rank: usize) -> Markup {\n html! {\n @if !items.is_empty() {\n@@ -224,7 +267,9 @@ fn rank_list(label: &str, items: &[RankedItem], start_rank: usize) -> Markup {\n @for (i, r) in items.iter().enumerate() {\n li {\n span class=\"rank-num\" { (start_rank + i) \". \" }\n- strong { (r.item.as_str()) }\n+ a href=(item_href(&r.item)) {\n+ strong { (display_label(&r.item)) }\n+ }\n span class=\"muted\" {\n \" — \"\n ({ format!(\"{:.1}%\", r.score * 100.0) })\n@@ -236,23 +281,30 @@ fn rank_list(label: &str, items: &[RankedItem], start_rank: usize) -> Markup {\n }\n }\n \n-pub fn ranking_panel(scope: &str, group: &GroupState) -> Markup {\n+fn display_label(id: &ItemId) -> String {\n+ id.segments()\n+ .last()\n+ .map_or(\"Internet\", |v| *v)\n+ .to_string()\n+}\n+\n+pub fn ranking_panel(item: &ItemId, group: &GroupState) -> Markup {\n let total = group.idx_to_item.len();\n let (top, bottom) = top_bottom(group, 8);\n html! {\n section id=\"ranking-panel\" class=\"demo-panel\" {\n h2 {\n \"Ranking\"\n- @if !scope.is_empty() {\n- \" — \" span class=\"scope-name\" { \"r/\" (scope) }\n+ @if !item.is_root() {\n+ \" — \" span class=\"scope-name\" { (item.as_str()) }\n }\n }\n @if total == 0 {\n p class=\"muted\" {\n- @if scope.is_empty() {\n+ @if item.is_root() {\n \"No votes yet — compare two items below.\"\n } @else {\n- \"No votes yet for r/\" (scope) \" — compare two items below to start the ranking.\"\n+ \"No votes yet for \" (item.as_str()) \" — compare two items below to start the ranking.\"\n }\n }\n } @else {\n@@ -266,7 +318,8 @@ pub fn ranking_panel(scope: &str, group: &GroupState) -> Markup {\n }\n }\n \n-pub fn vote_panel(scope: &str) -> Markup {\n+pub fn vote_panel(parent: &ItemId) -> Markup {\n+ let parent_str = parent.as_str();\n let rpc = template_json_compact(&serde_json::json!({\n \"action\": \"record_vote\",\n \"a\": {\"$form\": \"item_a\"},\n@@ -280,16 +333,17 @@ pub fn vote_panel(scope: &str) -> Markup {\n section id=\"vote-panel\" class=\"demo-panel\" {\n h2 { \"Compare\" }\n p class=\"muted small\" {\n- @if scope.is_empty() {\n+ @if parent.is_root() {\n \"Left item wins at 2:1. Votes append to the JSONL log and update rank centrality.\"\n } @else {\n- \"Ranking \" span class=\"scope-name\" { \"r/\" (scope) }\n+ \"Ranking children of \"\n+ span class=\"scope-name\" { (parent_str) }\n \". Left item wins at 2:1; each vote updates this ranking.\"\n }\n }\n form method=\"post\" action=\"/ui\" id=\"vote-form\" {\n input type=\"hidden\" name=(UI_RPC_FIELD) value=(rpc);\n- input type=\"hidden\" name=\"scope\" value=(scope);\n+ input type=\"hidden\" name=\"scope\" value=(parent_str);\n div class=\"vote-fields\" {\n label {\n \"Left (wins) \"\n@@ -329,17 +383,30 @@ pub async fn home(\n let views = state.views.get_views(&path);\n let theme = theme_from_jar(&jar);\n let theme_next = theme_next_from_uri(&uri);\n- let scope = normalize_scope(&query_param(&uri, \"sub\").unwrap_or_default());\n \n- let groups = state.groups.read().await;\n- let empty = GroupState::new();\n- let group = groups.get(&scope).unwrap_or(&empty);\n+ let item_raw = query_param(&uri, \"item\")\n+ .or_else(|| query_param(&uri, \"sub\").map(|sub| {\n+ if sub.is_empty() {\n+ String::new()\n+ } else {\n+ format!(\"reddit.com/r/{sub}\")\n+ }\n+ }))\n+ .unwrap_or_default();\n+ let item = parse_item_param(&item_raw);\n+\n+ let tree = state.tree.read().await;\n+ let empty_node = NodeState::default();\n+ let node = tree.get(&item).unwrap_or(&empty_node);\n+ let group = &node.local_ranking;\n \n let body = html! {\n h1 { \"sorter2\" }\n+ (breadcrumb_path(&item))\n (navigate_panel(\"\", None))\n- (vote_panel(&scope))\n- (ranking_panel(&scope, group))\n+ (entity_panel(node))\n+ (vote_panel(&item))\n+ (ranking_panel(&item, group))\n };\n layout(\"sorter2\", body, views, theme, &theme_next)\n }\ndiff --git a/server/src/journal.rs b/server/src/journal.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..b02ca025683621470ffdf8cd85cf9b85c56d024d\n--- /dev/null\n+++ b/server/src/journal.rs\n@@ -0,0 +1,89 @@\n+use std::sync::Arc;\n+\n+use tokio::sync::{mpsc, oneshot, RwLock};\n+\n+use crate::{\n+ event_log::EventLog,\n+ events::Event,\n+ path_types::ItemId,\n+ reducer::{GlobalTree, VoteData},\n+};\n+\n+pub struct JournalCommand {\n+ pub parent: ItemId,\n+ pub vote: VoteData,\n+ pub event: Event,\n+ pub reply: oneshot::Sender>,\n+}\n+\n+#[derive(Clone)]\n+pub struct JournalClient {\n+ tx: mpsc::Sender,\n+}\n+\n+impl JournalClient {\n+ pub fn spawn(tree: Arc>, event_log: Arc) -> Self {\n+ let (tx, rx) = mpsc::channel(64);\n+ tokio::spawn(journal_worker(rx, tree, event_log));\n+ Self { tx }\n+ }\n+\n+ pub async fn record_vote(\n+ &self,\n+ parent: ItemId,\n+ vote: VoteData,\n+ event: Event,\n+ ) -> Result<(), String> {\n+ let (reply, rx) = oneshot::channel();\n+ self.tx\n+ .send(JournalCommand {\n+ parent,\n+ vote,\n+ event,\n+ reply,\n+ })\n+ .await\n+ .map_err(|_| \"journal worker stopped\".to_string())?;\n+ rx.await\n+ .map_err(|_| \"journal worker stopped\".to_string())?\n+ }\n+}\n+\n+async fn journal_worker(\n+ mut rx: mpsc::Receiver,\n+ tree: Arc>,\n+ event_log: Arc,\n+) {\n+ while let Some(first) = rx.recv().await {\n+ let mut batch = vec![first];\n+ while let Ok(more) = rx.try_recv() {\n+ batch.push(more);\n+ }\n+\n+ let mut disk_err: Option = None;\n+ for cmd in &batch {\n+ if let Err(e) = event_log.append(&cmd.event).await {\n+ disk_err = Some(e.to_string());\n+ break;\n+ }\n+ }\n+\n+ if let Some(err) = disk_err {\n+ for cmd in batch {\n+ let _ = cmd.reply.send(Err(err.clone()));\n+ }\n+ continue;\n+ }\n+\n+ {\n+ let mut w = tree.write().await;\n+ for cmd in &batch {\n+ w.apply_vote(&cmd.parent, cmd.vote.clone());\n+ }\n+ }\n+\n+ for cmd in batch {\n+ let _ = cmd.reply.send(Ok(()));\n+ }\n+ }\n+}\ndiff --git a/server/src/lib.rs b/server/src/lib.rs\nindex de8bca48cbf689cad22337883e7791966e7c4919..14e7cfbc38feb5d07aff859b64bce6e2ec45cf91 100644\n--- a/server/src/lib.rs\n+++ b/server/src/lib.rs\n@@ -7,8 +7,9 @@ pub mod parser;\n pub mod parser_render;\n pub mod path_types;\n pub mod ranking;\n+pub mod reddit;\n pub mod reducer;\n-pub mod settlement;\n+pub mod journal;\n pub mod state;\n pub mod ui_action;\n pub mod views;\ndiff --git a/server/src/parser.rs b/server/src/parser.rs\nindex 50571a59f0d3ece1e2538f88e00ef46ec40ea545..51aa0e0f982546aab68bd5e1ca0cb726e88b3f50 100644\n--- a/server/src/parser.rs\n+++ b/server/src/parser.rs\n@@ -1,47 +1,18 @@\n-//! Extract a subreddit name from a pasted Reddit URL or path.\n+//! Extract a canonical [`crate::path_types::ItemId`] from a pasted Reddit URL or path.\n \n-pub fn parse_reddit_url(query: &str) -> Result {\n+use crate::path_types::ItemId;\n+\n+pub fn parse_reddit_url(query: &str) -> Result {\n let q = query.trim();\n if q.is_empty() {\n return Err(\"Paste a Reddit URL or r/subreddit path\".into());\n }\n \n- if let Some(sub) = subreddit_after_prefix(q, \"r/\") {\n- return Ok(sub);\n- }\n-\n- if let Some(sub) = subreddit_from_path_segment(q, \"/r/\") {\n- return Ok(sub);\n+ if let Some(id) = ItemId::from_url(q) {\n+ return Ok(id);\n }\n \n- Err(\"Could not find a subreddit in that URL\".into())\n-}\n-\n-fn subreddit_after_prefix(text: &str, prefix: &str) -> Option {\n- let rest = text.strip_prefix(prefix)?;\n- let sub = rest.split(['/', '?', '#']).next()?.trim();\n- valid_subreddit(sub)\n-}\n-\n-fn subreddit_from_path_segment(text: &str, needle: &str) -> Option {\n- let idx = text.find(needle)?;\n- let rest = &text[idx + needle.len()..];\n- let sub = rest.split(['/', '?', '#']).next()?.trim();\n- valid_subreddit(sub)\n-}\n-\n-fn valid_subreddit(name: &str) -> Option {\n- if name.is_empty() {\n- return None;\n- }\n- if name\n- .chars()\n- .all(|c| c.is_ascii_alphanumeric() || c == '_')\n- {\n- Some(name.to_ascii_lowercase())\n- } else {\n- None\n- }\n+ Err(\"Could not parse that Reddit URL\".into())\n }\n \n #[cfg(test)]\n@@ -50,34 +21,37 @@ mod tests {\n \n #[test]\n fn parses_short_path() {\n- assert_eq!(parse_reddit_url(\"r/rust\").unwrap(), \"rust\");\n- }\n-\n- #[test]\n- fn parses_path_with_trailing_slash() {\n- assert_eq!(parse_reddit_url(\"r/rust/\").unwrap(), \"rust\");\n+ assert_eq!(\n+ parse_reddit_url(\"r/rust\").unwrap().as_str(),\n+ \"reddit.com/r/rust\"\n+ );\n }\n \n #[test]\n fn parses_full_url() {\n assert_eq!(\n- parse_reddit_url(\"https://www.reddit.com/r/programming/hot\").unwrap(),\n- \"programming\"\n+ parse_reddit_url(\"https://www.reddit.com/r/programming/hot\")\n+ .unwrap()\n+ .as_str(),\n+ \"reddit.com/r/programming\"\n );\n }\n \n #[test]\n- fn parses_url_without_scheme() {\n+ fn parses_post_url() {\n+ let id = parse_reddit_url(\n+ \"https://old.reddit.com/r/AmItheAsshole/comments/1trnvdl/aita_for_cancelling/\",\n+ )\n+ .unwrap();\n assert_eq!(\n- parse_reddit_url(\"reddit.com/r/AskReddit\").unwrap(),\n- \"askreddit\"\n+ id.as_str(),\n+ \"reddit.com/r/amitheasshole/comments/1trnvdl\"\n );\n }\n \n #[test]\n fn rejects_empty() {\n assert!(parse_reddit_url(\"\").is_err());\n- assert!(parse_reddit_url(\" \").is_err());\n }\n \n #[test]\ndiff --git a/server/src/parser_render.rs b/server/src/parser_render.rs\nindex f2341afe21476b689a536137798d97277211a962..acf2e7403f4238291677ef0c79d5766302ea78cf 100644\n--- a/server/src/parser_render.rs\n+++ b/server/src/parser_render.rs\n@@ -21,7 +21,7 @@ pub fn navigate_panel(query: &str, error: Option<&str>) -> Markup {\n p class=\"muted small\" {\n \"Paste a Reddit URL or \"\n code { \"r/subreddit\" }\n- \" path, then click Go to rank that subreddit.\"\n+ \" path. Breadcrumb links drill down the tree; rankings apply to each node's children.\"\n }\n form method=\"post\" action=\"/ui\" id=\"parser-form\" {\n textarea\ndiff --git a/server/src/path_types.rs b/server/src/path_types.rs\nindex 1cdc96a25b1954f11aaf955203e2b9907b578366..b5c41444f7bcd4d8d289ed3af464bc3f14d0df99 100644\n--- a/server/src/path_types.rs\n+++ b/server/src/path_types.rs\n@@ -1,11 +1,13 @@\n use serde::{Deserialize, Serialize};\n use std::fmt;\n \n-/// Stable item key for votes and rankings (opaque string for now).\n-#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]\n+/// Canonical hierarchical identity for any URL/path in the fractal tree.\n+#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Default)]\n pub struct ItemId(String);\n \n impl ItemId {\n+ /// Parse an already-canonical path (no URL normalization). Empty string is invalid here;\n+ /// use [`Self::root`] for the tree root.\n pub fn parse(s: &str) -> Option {\n let t = s.trim();\n if t.is_empty() {\n@@ -14,13 +16,170 @@ impl ItemId {\n Some(Self(t.to_string()))\n }\n \n+ /// Build an opaque item key (legacy demo votes, non-URL items).\n pub fn opaque(s: impl Into) -> Self {\n Self(s.into())\n }\n \n+ /// Root of the internet tree (empty path).\n+ pub fn root() -> Self {\n+ Self(String::new())\n+ }\n+\n+ pub fn is_root(&self) -> bool {\n+ self.0.is_empty()\n+ }\n+\n pub fn as_str(&self) -> &str {\n &self.0\n }\n+\n+ /// Creates a canonical ID from a raw URL or path. Normalizes domains and\n+ /// trims tracking query params.\n+ pub fn from_url(raw_url: &str) -> Option {\n+ Self::canonicalize(raw_url).map(Self)\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+ if s.is_empty() {\n+ return Self::root();\n+ }\n+ Self(format!(\"reddit.com/r/{s}\"))\n+ }\n+\n+ /// Extract the parent, e.g. `reddit.com/r/aww/comments/1trnvdl` →\n+ /// `reddit.com/r/aww`.\n+ pub fn parent(&self) -> Option {\n+ if self.0.is_empty() {\n+ return None;\n+ }\n+\n+ let parts: Vec<&str> = self.0.trim_end_matches('/').split('/').collect();\n+ if parts.len() <= 1 {\n+ return None;\n+ }\n+\n+ if self.0.contains(\"/comments/\") {\n+ return Some(Self(parts[..parts.len().saturating_sub(2)].join(\"/\")));\n+ }\n+\n+ Some(Self(parts[..parts.len() - 1].join(\"/\")))\n+ }\n+\n+ pub fn segments(&self) -> Vec<&str> {\n+ self.0.split('/').filter(|s| !s.is_empty()).collect()\n+ }\n+\n+ /// Cumulative paths for breadcrumb rendering, e.g.\n+ /// `reddit.com/r/movies` → `[\"reddit.com\", \"reddit.com/r\", \"reddit.com/r/movies\"]`.\n+ pub fn breadcrumb_paths(&self) -> Vec {\n+ let segs = self.segments();\n+ let mut paths = Vec::with_capacity(segs.len());\n+ let mut current = String::new();\n+ for seg in segs {\n+ if current.is_empty() {\n+ current = seg.to_string();\n+ } else {\n+ current.push('/');\n+ current.push_str(seg);\n+ }\n+ paths.push(ItemId(current.clone()));\n+ }\n+ paths\n+ }\n+\n+ fn canonicalize(raw: &str) -> Option {\n+ let s = raw.trim();\n+ if s.is_empty() {\n+ return None;\n+ }\n+\n+ let owned = if let Some(rest) = s.strip_prefix(\"r/\") {\n+ format!(\"reddit.com/r/{rest}\")\n+ } else if let Some(rest) = s.strip_prefix(\"/r/\") {\n+ format!(\"reddit.com/r/{rest}\")\n+ } else {\n+ s.to_string()\n+ };\n+\n+ let (host_path, _query) = split_query(&owned);\n+ let host_path = host_path.trim_end_matches('/');\n+\n+ let path = if host_path.contains(\"://\") {\n+ parse_url_host_path(host_path)?\n+ } else if host_path.starts_with(\"reddit.com\") || host_path.starts_with(\"www.reddit.com\") {\n+ normalize_reddit_host_path(host_path)\n+ } else if host_path.contains('/') {\n+ host_path.to_string()\n+ } else {\n+ return None;\n+ };\n+\n+ Some(normalize_reddit_path(&path))\n+ }\n+}\n+\n+fn split_query(s: &str) -> (&str, Option<&str>) {\n+ if let Some((path, q)) = s.split_once('?') {\n+ (path, Some(q))\n+ } else {\n+ (s, None)\n+ }\n+}\n+\n+fn parse_url_host_path(url: &str) -> Option {\n+ let rest = url\n+ .strip_prefix(\"https://\")\n+ .or_else(|| url.strip_prefix(\"http://\"))\n+ .unwrap_or(url);\n+ let (host, path) = rest.split_once('/').unwrap_or((rest, \"\"));\n+ let host = normalize_host(host);\n+ if path.is_empty() {\n+ Some(host)\n+ } else {\n+ Some(format!(\"{host}/{path}\"))\n+ }\n+}\n+\n+fn normalize_host(host: &str) -> String {\n+ let h = host\n+ .strip_prefix(\"www.\")\n+ .unwrap_or(host)\n+ .to_ascii_lowercase();\n+ if h == \"old.reddit.com\" || h == \"new.reddit.com\" || h == \"reddit.com\" {\n+ \"reddit.com\".to_string()\n+ } else {\n+ h\n+ }\n+}\n+\n+fn normalize_reddit_host_path(s: &str) -> String {\n+ let (host, path) = s.split_once('/').unwrap_or((s, \"\"));\n+ let host = normalize_host(host);\n+ if path.is_empty() {\n+ host\n+ } else {\n+ format!(\"{host}/{path}\")\n+ }\n+}\n+\n+/// Lowercase subreddit segment, drop listing suffixes, drop title slug after post id.\n+fn normalize_reddit_path(path: &str) -> String {\n+ let mut parts: Vec = path.split('/').map(str::to_string).collect();\n+ if parts.len() >= 3 && parts[1] == \"r\" {\n+ parts[2] = parts[2].to_ascii_lowercase();\n+ }\n+ if let Some(i) = parts.iter().position(|p| p == \"comments\") {\n+ if parts.len() > i + 2 {\n+ parts.truncate(i + 2);\n+ }\n+ } else if parts.len() > 3 && parts.get(1).map(|s| s.as_str()) == Some(\"r\") {\n+ // reddit.com/r/{sub}/hot → reddit.com/r/{sub}\n+ parts.truncate(3);\n+ }\n+ parts.join(\"/\")\n }\n \n impl fmt::Display for ItemId {\n@@ -28,3 +187,69 @@ impl fmt::Display for ItemId {\n f.write_str(&self.0)\n }\n }\n+\n+#[cfg(test)]\n+mod tests {\n+ use super::*;\n+\n+ #[test]\n+ fn from_url_normalizes_reddit_domains() {\n+ let id = ItemId::from_url(\n+ \"https://old.reddit.com/r/AmItheAsshole/comments/1trnvdl/aita_for_cancelling/\",\n+ )\n+ .unwrap();\n+ assert_eq!(\n+ id.as_str(),\n+ \"reddit.com/r/amitheasshole/comments/1trnvdl\"\n+ );\n+ }\n+\n+ #[test]\n+ fn from_url_strips_query() {\n+ let id = ItemId::from_url(\"https://www.reddit.com/r/rust/?sort=top\").unwrap();\n+ assert_eq!(id.as_str(), \"reddit.com/r/rust\");\n+ }\n+\n+ #[test]\n+ fn from_url_short_path() {\n+ assert_eq!(\n+ ItemId::from_url(\"r/rust\").unwrap().as_str(),\n+ \"reddit.com/r/rust\"\n+ );\n+ }\n+\n+ #[test]\n+ fn parent_of_post_is_subreddit() {\n+ let id = ItemId::parse(\"reddit.com/r/aww/comments/1trnvdl\").unwrap();\n+ assert_eq!(\n+ id.parent().unwrap().as_str(),\n+ \"reddit.com/r/aww\"\n+ );\n+ }\n+\n+ #[test]\n+ fn parent_of_subreddit_is_r_segment() {\n+ let id = ItemId::parse(\"reddit.com/r/movies\").unwrap();\n+ assert_eq!(id.parent().unwrap().as_str(), \"reddit.com/r\");\n+ }\n+\n+ #[test]\n+ fn breadcrumb_paths() {\n+ let id = ItemId::parse(\"reddit.com/r/movies\").unwrap();\n+ let crumbs = id.breadcrumb_paths();\n+ let paths: Vec<_> = crumbs.iter().map(|p| p.as_str()).collect();\n+ assert_eq!(\n+ paths,\n+ vec![\"reddit.com\", \"reddit.com/r\", \"reddit.com/r/movies\"]\n+ );\n+ }\n+\n+ #[test]\n+ fn legacy_scope_maps_to_reddit_sub() {\n+ assert_eq!(\n+ ItemId::from_legacy_scope(\"rust\").as_str(),\n+ \"reddit.com/r/rust\"\n+ );\n+ assert!(ItemId::from_legacy_scope(\"\").is_root());\n+ }\n+}\ndiff --git a/server/src/reddit.rs b/server/src/reddit.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..d203dca09245daf869b3aa942898447700ae69fb\n--- /dev/null\n+++ b/server/src/reddit.rs\n@@ -0,0 +1,21 @@\n+//! Reddit API import (async, decoupled from UI request path).\n+\n+use crate::{\n+ path_types::ItemId,\n+ reducer::{EntityData, GlobalTree},\n+};\n+\n+/// Bootstrap blank nodes along a URL path so breadcrumbs and voting work before fetch.\n+pub fn ensure_partial_tree(tree: &mut GlobalTree, id: &ItemId) {\n+ tree.ensure_path(id);\n+}\n+\n+/// Placeholder for Reddit JSON import. Returns entity data when implemented.\n+pub async fn fetch_reddit_entity(_id: &ItemId) -> Option {\n+ None\n+}\n+\n+/// Apply fetched entity data to a node (called from async worker).\n+pub fn apply_entity(tree: &mut GlobalTree, id: &ItemId, data: EntityData) {\n+ tree.set_entity_data(id, data);\n+}\ndiff --git a/server/src/reducer.rs b/server/src/reducer.rs\nindex 8d28353e1f2a67e71b7d17a2041a0988150f3245..077f700bf00ddefe18ffd004bb5288bdc7c4adaf 100644\n--- a/server/src/reducer.rs\n+++ b/server/src/reducer.rs\n@@ -115,6 +115,96 @@ impl GroupState {\n }\n }\n \n+/// Structured data imported from Reddit or elsewhere.\n+#[derive(Debug, Clone, Serialize, Deserialize)]\n+pub struct EntityData {\n+ pub title: String,\n+ pub author: Option,\n+ pub body_html: Option,\n+ pub thumb_url: Option,\n+}\n+\n+/// One node in the fractal tree: entity + ranked children.\n+#[derive(Debug, Clone, Default)]\n+pub struct NodeState {\n+ pub id: ItemId,\n+ pub data: Option,\n+ pub children: HashSet,\n+ pub local_ranking: GroupState,\n+}\n+\n+impl NodeState {\n+ fn new(id: ItemId) -> Self {\n+ Self {\n+ id,\n+ ..Default::default()\n+ }\n+ }\n+}\n+\n+/// Global fractal graph: every URL is both an item and a ranking scope for its children.\n+#[derive(Default)]\n+pub struct GlobalTree {\n+ pub nodes: HashMap,\n+}\n+\n+impl GlobalTree {\n+ pub fn new() -> Self {\n+ let mut tree = Self::default();\n+ tree.ensure_node(&ItemId::root());\n+ tree\n+ }\n+\n+ pub fn ensure_node(&mut self, id: &ItemId) -> &mut NodeState {\n+ if !self.nodes.contains_key(id) {\n+ self.nodes.insert(id.clone(), NodeState::new(id.clone()));\n+ }\n+ self.nodes.get_mut(id).expect(\"node just inserted\")\n+ }\n+\n+ /// Register a node and wire parent→child links along the canonical path.\n+ pub fn ensure_path(&mut self, id: &ItemId) {\n+ if id.is_root() {\n+ self.ensure_node(id);\n+ return;\n+ }\n+ self.ensure_node(&ItemId::root());\n+ for path in id.breadcrumb_paths() {\n+ self.ensure_node(&path);\n+ if let Some(parent) = path.parent() {\n+ self.ensure_node(&parent);\n+ if let Some(p) = self.nodes.get_mut(&parent) {\n+ p.children.insert(path.clone());\n+ }\n+ } else if let Some(r) = self.nodes.get_mut(&ItemId::root()) {\n+ r.children.insert(path.clone());\n+ }\n+ }\n+ }\n+\n+ pub fn get(&self, id: &ItemId) -> Option<&NodeState> {\n+ self.nodes.get(id)\n+ }\n+\n+ pub fn apply_vote(&mut self, parent: &ItemId, vote: VoteData) {\n+ self.ensure_path(parent);\n+ self.ensure_path(&vote.a);\n+ self.ensure_path(&vote.b);\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);\n+ }\n+ }\n+\n+ pub fn set_entity_data(&mut self, id: &ItemId, data: EntityData) {\n+ self.ensure_path(id);\n+ if let Some(node) = self.nodes.get_mut(id) {\n+ node.data = Some(data);\n+ }\n+ }\n+}\n+\n #[cfg(test)]\n mod from_recorded_tests {\n use super::*;\n@@ -125,7 +215,20 @@ mod from_recorded_tests {\n }\n \n #[test]\n- fn rejects_empty() {\n+ fn rejects_empty_pair() {\n assert!(VoteData::from_recorded(1, \"\", \"b\", 2, 1).is_none());\n }\n+\n+ #[test]\n+ fn ensure_path_wires_children() {\n+ let mut tree = GlobalTree::new();\n+ let id = ItemId::parse(\"reddit.com/r/rust\").unwrap();\n+ tree.ensure_path(&id);\n+ let root = tree.get(&ItemId::root()).unwrap();\n+ assert!(root.children.contains(&ItemId::parse(\"reddit.com\").unwrap()));\n+ let reddit = tree.get(&ItemId::parse(\"reddit.com\").unwrap()).unwrap();\n+ assert!(reddit.children.contains(&ItemId::parse(\"reddit.com/r\").unwrap()));\n+ let sub = tree.get(&id).unwrap();\n+ assert_eq!(sub.id, id);\n+ }\n }\ndiff --git a/server/src/settlement.rs b/server/src/settlement.rs\ndeleted file mode 100644\nindex 7a44495512b7f788239b8aeefbbd0a83656eeac6..0000000000000000000000000000000000000000\n--- a/server/src/settlement.rs\n+++ /dev/null\n@@ -1,94 +0,0 @@\n-use std::collections::HashMap;\n-use std::sync::Arc;\n-\n-use tokio::sync::{mpsc, oneshot, RwLock};\n-\n-use crate::{\n- event_log::EventLog,\n- events::Event,\n- reducer::{GroupState, VoteData},\n-};\n-\n-/// Per-scope ranking state, keyed by scope (e.g. subreddit; \"\" is the default scope).\n-pub type GroupMap = HashMap;\n-\n-pub struct SettlementCommand {\n- pub scope: String,\n- pub vote: VoteData,\n- pub event: Event,\n- pub reply: oneshot::Sender>,\n-}\n-\n-#[derive(Clone)]\n-pub struct SettlementClient {\n- tx: mpsc::Sender,\n-}\n-\n-impl SettlementClient {\n- pub fn spawn(groups: Arc>, event_log: Arc) -> Self {\n- let (tx, rx) = mpsc::channel(64);\n- tokio::spawn(settlement_worker(rx, groups, event_log));\n- Self { tx }\n- }\n-\n- pub async fn record_vote(\n- &self,\n- scope: String,\n- vote: VoteData,\n- event: Event,\n- ) -> Result<(), String> {\n- let (reply, rx) = oneshot::channel();\n- self.tx\n- .send(SettlementCommand {\n- scope,\n- vote,\n- event,\n- reply,\n- })\n- .await\n- .map_err(|_| \"settlement worker stopped\".to_string())?;\n- rx.await\n- .map_err(|_| \"settlement worker stopped\".to_string())?\n- }\n-}\n-\n-async fn settlement_worker(\n- mut rx: mpsc::Receiver,\n- groups: Arc>,\n- event_log: Arc,\n-) {\n- while let Some(first) = rx.recv().await {\n- let mut batch = vec![first];\n- while let Ok(more) = rx.try_recv() {\n- batch.push(more);\n- }\n-\n- let mut disk_err: Option = None;\n- for cmd in &batch {\n- if let Err(e) = event_log.append(&cmd.event).await {\n- disk_err = Some(e.to_string());\n- break;\n- }\n- }\n-\n- if let Some(err) = disk_err {\n- for cmd in batch {\n- let _ = cmd.reply.send(Err(err.clone()));\n- }\n- continue;\n- }\n-\n- {\n- let mut w = groups.write().await;\n- for cmd in &batch {\n- w.entry(cmd.scope.clone())\n- .or_default()\n- .apply_vote(cmd.vote.clone());\n- }\n- }\n-\n- for cmd in batch {\n- let _ = cmd.reply.send(Ok(()));\n- }\n- }\n-}\ndiff --git a/server/src/state.rs b/server/src/state.rs\nindex 2d9e5226057f8615897aac48bce947643a230fb4..cc1722f5a5bf4d415f2327ea585c488a15a75592 100644\n--- a/server/src/state.rs\n+++ b/server/src/state.rs\n@@ -1,4 +1,3 @@\n-use std::collections::HashMap;\n use std::sync::Arc;\n \n use tokio::sync::RwLock;\n@@ -6,14 +5,22 @@ use tokio::sync::RwLock;\n use crate::{\n event_log::EventLog,\n events::Event,\n- reducer::VoteData,\n- settlement::{GroupMap, SettlementClient},\n+ path_types::ItemId,\n+ reducer::{GlobalTree, VoteData},\n+ journal::JournalClient,\n views::ViewStore,\n };\n \n-/// Normalize a raw ranking subject into a scope key: strip an optional `r/`\n-/// prefix, keep only `[a-z0-9_]`, lowercase, and cap the length. Empty string\n-/// is the default/global scope.\n+/// Parse `?item=` query value into a canonical node id.\n+pub fn parse_item_param(raw: &str) -> ItemId {\n+ let s = raw.trim();\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+}\n+\n+/// Legacy: normalize raw ranking subject into a scope key for old event replay.\n pub fn normalize_scope(raw: &str) -> String {\n let s = raw.trim();\n let s = s\n@@ -27,6 +34,14 @@ pub fn normalize_scope(raw: &str) -> String {\n .collect()\n }\n \n+fn parent_from_event_scope(scope: &str) -> ItemId {\n+ if scope.contains('/') {\n+ ItemId::parse(scope).unwrap_or_else(|| ItemId::from_legacy_scope(scope))\n+ } else {\n+ ItemId::from_legacy_scope(scope)\n+ }\n+}\n+\n #[derive(Clone)]\n pub struct AppConfig {\n pub data_dir: String,\n@@ -56,8 +71,8 @@ pub struct AppState {\n pub cfg: Arc,\n pub event_log: Arc,\n pub views: ViewStore,\n- pub groups: Arc>,\n- settlement: SettlementClient,\n+ pub tree: Arc>,\n+ journal: JournalClient,\n }\n \n impl AppState {\n@@ -66,7 +81,7 @@ impl AppState {\n let views_path = format!(\"{}/views.json\", cfg.data_dir);\n let views = ViewStore::new(&views_path);\n \n- let mut groups: GroupMap = HashMap::new();\n+ let mut tree = GlobalTree::new();\n if let Ok((events, _)) = event_log.load_all().await {\n for ev in events {\n match ev {\n@@ -81,29 +96,45 @@ impl AppState {\n if let Some(vote) =\n VoteData::from_recorded(ts, &a, &b, ratio_left, ratio_right)\n {\n- groups.entry(scope).or_default().apply_vote(vote);\n+ let parent = parent_from_event_scope(&scope);\n+ tree.apply_vote(&parent, vote);\n }\n }\n Event::ViewRecorded { .. } => {}\n+ Event::NodeEnsured { id } => {\n+ if let Some(parsed) = ItemId::parse(&id).or_else(|| ItemId::from_url(&id)) {\n+ tree.ensure_path(&parsed);\n+ }\n+ }\n }\n }\n }\n \n- let groups = Arc::new(RwLock::new(groups));\n- let settlement = SettlementClient::spawn(groups.clone(), event_log.clone());\n+ let tree = Arc::new(RwLock::new(tree));\n+ let journal = JournalClient::spawn(tree.clone(), event_log.clone());\n \n Self {\n cfg: Arc::new(cfg),\n event_log,\n views,\n- groups,\n- settlement,\n+ tree,\n+ journal,\n }\n }\n \n+ pub async fn ensure_node(&self, id: &ItemId) -> Result<(), String> {\n+ let event = Event::NodeEnsured {\n+ id: id.as_str().to_string(),\n+ };\n+ self.event_log.append(&event).await.map_err(|e| e.to_string())?;\n+ let mut w = self.tree.write().await;\n+ w.ensure_path(id);\n+ Ok(())\n+ }\n+\n pub async fn record_vote(\n &self,\n- scope: &str,\n+ parent: &ItemId,\n a: &str,\n b: &str,\n ratio_left: i32,\n@@ -113,23 +144,24 @@ impl AppState {\n let vote = VoteData::from_recorded(ts, a, b, ratio_left, ratio_right)\n .ok_or_else(|| \"invalid vote: need two distinct non-empty items\".to_string())?;\n \n- let scope = normalize_scope(scope);\n let event = Event::VoteRecorded {\n ts,\n a: vote.a.as_str().to_string(),\n b: vote.b.as_str().to_string(),\n ratio_left: vote.ratio_left,\n ratio_right: vote.ratio_right,\n- scope: scope.clone(),\n+ scope: parent.as_str().to_string(),\n };\n \n- self.settlement.record_vote(scope, vote, event).await\n+ self.journal\n+ .record_vote(parent.clone(), vote, event)\n+ .await\n }\n }\n \n #[cfg(test)]\n mod tests {\n- use super::normalize_scope;\n+ use super::{normalize_scope, parse_item_param};\n \n #[test]\n fn normalize_scope_strips_prefix_and_lowercases() {\n@@ -138,4 +170,15 @@ mod tests {\n assert_eq!(normalize_scope(\"r/web_dev!!\"), \"web_dev\");\n assert_eq!(normalize_scope(\"\"), \"\");\n }\n+\n+ #[test]\n+ fn parse_item_param_from_url() {\n+ let id = parse_item_param(\"https://reddit.com/r/rust\");\n+ assert_eq!(id.as_str(), \"reddit.com/r/rust\");\n+ }\n+\n+ #[test]\n+ fn parse_item_param_empty_is_root() {\n+ assert!(parse_item_param(\"\").is_root());\n+ }\n }\ndiff --git a/server/src/ui_action.rs b/server/src/ui_action.rs\nindex 0e030b3448b8e45acbe49d2de47ea26372445c54..d798874d1d94c0dfee59ec1ff703f9ee6ef432c0 100644\n--- a/server/src/ui_action.rs\n+++ b/server/src/ui_action.rs\n@@ -18,7 +18,7 @@ pub enum HtmlUiAction {\n b: String,\n ratio_left: i32,\n ratio_right: i32,\n- /// Ranking subject (e.g. a subreddit). Empty string = default/global scope.\n+ /// Parent node [`ItemId`] string; empty = tree root.\n #[serde(default)]\n scope: String,\n },\ndiff --git a/server/static/theme_default.css b/server/static/theme_default.css\nindex 6ad0ac712bbc840bedee60f613794de9385fbbd1..1bf8ac7a25207336c019f93cd4119bd0e06229f0 100644\n--- a/server/static/theme_default.css\n+++ b/server/static/theme_default.css\n@@ -137,6 +137,38 @@ code {\n margin-top: 0.5rem;\n }\n \n+.breadcrumbs {\n+ font-size: 0.875rem;\n+ margin-bottom: 1rem;\n+ color: var(--muted);\n+}\n+\n+.breadcrumbs a {\n+ color: var(--accent);\n+ text-decoration: none;\n+}\n+\n+.breadcrumbs a:hover {\n+ text-decoration: underline;\n+}\n+\n+.breadcrumbs .separator {\n+ color: var(--muted);\n+}\n+\n+.rank-list a {\n+ color: var(--accent);\n+ text-decoration: none;\n+}\n+\n+.rank-list a:hover {\n+ text-decoration: underline;\n+}\n+\n+.entity-card h2 {\n+ margin-top: 0;\n+}\n+\n .scope-name {\n color: var(--accent);\n font-weight: 600;\ndiff --git a/server/tests/integration_ui.rs b/server/tests/integration_ui.rs\nindex afeeee24e32f2d7f1d852ca96ac799fac8bce665..f7ac9c26bf9f9277ad5f5708603224c095165fb8 100644\n--- a/server/tests/integration_ui.rs\n+++ b/server/tests/integration_ui.rs\n@@ -2,7 +2,7 @@ use std::collections::HashMap;\n use std::net::SocketAddr;\n \n use axum::Router;\n-use sorter2_server::{create_app, create_app_state, state::AppConfig, ui_action::UI_RPC_FIELD};\n+use sorter2_server::{create_app, create_app_state, path_types::ItemId, state::AppConfig, ui_action::UI_RPC_FIELD};\n use tempfile::TempDir;\n use tokio::net::TcpListener;\n \n@@ -63,9 +63,9 @@ async fn post_ui_record_vote_morphs_ranking_and_persists() {\n port: 0,\n };\n let state = create_app_state(cfg).await;\n- let groups = state.groups.read().await;\n- let group = groups.get(\"\").expect(\"default scope group after replay\");\n- let ranked = sorter2_server::ranking::ranked_items(group);\n+ let tree = state.tree.read().await;\n+ let root = tree.get(&ItemId::root()).expect(\"root node after replay\");\n+ let ranked = sorter2_server::ranking::ranked_items(&root.local_ranking);\n assert_eq!(ranked.len(), 2);\n assert_eq!(ranked[0].item.as_str(), \"alpha\");\n }\n@@ -93,5 +93,5 @@ async fn post_ui_parse_query_redirects_to_subreddit() {\n .unwrap();\n \n assert!(body.contains(\"window.location.href\"));\n- assert!(body.contains(\"/?sub=rust\"));\n+ assert!(body.contains(\"/?item=reddit.com/r/rust\"));\n }\n","role":"user"}],"model":"~anthropic/claude-sonnet-latest"}