{"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[5ca518f6] url refactor\n\nSide A — unified diff (full patch):\ndiff --git a/Cargo.lock b/Cargo.lock\nindex 67a09a3b54f778fa7e857fdd589c3ed9c92e1322..ad7e4fe6d4ba2f2b033916194c1ef1ed873f1d46 100644\n--- a/Cargo.lock\n+++ b/Cargo.lock\n@@ -1757,6 +1757,7 @@ name = \"slug-types\"\n version = \"0.1.0\"\n dependencies = [\n \"serde\",\n+ \"url\",\n ]\n \n [[package]]\n@@ -2272,6 +2273,7 @@ dependencies = [\n \"idna\",\n \"percent-encoding\",\n \"serde\",\n+ \"serde_derive\",\n ]\n \n [[package]]\ndiff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs\nindex 606f7d6f97a4428efb90d1e0d544934c861fc4c5..cd3e0f0afd972d9ad9e7e4b92c5fa4c22bb8f620 100644\n--- a/server/src/api/ui_html.rs\n+++ b/server/src/api/ui_html.rs\n@@ -270,10 +270,10 @@ fn post_redirect_location(room: &str, thread_tag: &str) -> String {\n format!(\"/t/{tag}\")\n } else {\n let room = room.trim();\n- let Some((a, b)) = room.split_once('/') else {\n+ let Some(seg) = slug_types::room_route_segment(room) else {\n return \"/\".to_string();\n };\n- format!(\"/r/{a}/{b}/t/{tag}\")\n+ format!(\"/r/{seg}/t/{tag}\")\n }\n }\n \ndiff --git a/server/src/api/write_actor.rs b/server/src/api/write_actor.rs\nindex cb78d2f3f95b1bc163c1fb064d1d5f657e18000f..f9c3b8bd3fbf8fcb9c035e1a1572fef0b08fa8a9 100644\n--- a/server/src/api/write_actor.rs\n+++ b/server/src/api/write_actor.rs\n@@ -19,13 +19,15 @@ use crate::{\n use super::auth::{issue_token_for_user, verify_token};\n use super::helpers::{now_ms, resolve_item};\n use super::validate::{normalize_room_and_thread, validate_ingest_document};\n-use slug_types::RpcResult;\n+use slug_types::{room_route_segment, RpcResult, ROOM_SHORT_ID_LEN};\n \n fn gen_short_id() -> String {\n use rand::Rng;\n const ALPHABET: &[u8] = b\"0123456789abcdefghijklmnopqrstuvwxyz\";\n let mut rng = rand::thread_rng();\n- (0..7).map(|_| ALPHABET[rng.gen_range(0..ALPHABET.len())] as char).collect()\n+ (0..ROOM_SHORT_ID_LEN)\n+ .map(|_| ALPHABET[rng.gen_range(0..ALPHABET.len())] as char)\n+ .collect()\n }\n \n fn parse_capability(s: &str) -> Result {\n@@ -55,8 +57,8 @@ async fn broadcast_web_refresh(state: &AppState, room_key: &str, thread_id: &str\n let feed_id = if room_key == \"public\" { \"thread-feed\" } else { \"room-thread-feed\" };\n let thread_url = if room_key == \"public\" {\n format!(\"/t/{thread_id}\")\n- } else if let Some((short, slug)) = room_key.split_once('/') {\n- format!(\"/r/{short}/{slug}/t/{thread_id}\")\n+ } else if let Some(seg) = room_route_segment(room_key) {\n+ format!(\"/r/{seg}/t/{thread_id}\")\n } else {\n format!(\"/t/{thread_id}\")\n };\n@@ -78,8 +80,8 @@ async fn broadcast_web_refresh(state: &AppState, room_key: &str, thread_id: &str\n let js = builder.build();\n let mut path_prefixes = vec![if room_key == \"public\" {\n \"/\".to_string()\n- } else if let Some((short, slug)) = room_key.split_once('/') {\n- format!(\"/r/{short}/{slug}\")\n+ } else if let Some(seg) = room_route_segment(room_key) {\n+ format!(\"/r/{seg}\")\n } else {\n \"/\".to_string()\n }];\ndiff --git a/server/src/html/forum/nav.rs b/server/src/html/forum/nav.rs\nindex 0ee33d91160fc5542817b5e3e9ab4fee1d0e600f..48fe11e46731670874ff8b6b05baa6f09ae0b7e4 100644\n--- a/server/src/html/forum/nav.rs\n+++ b/server/src/html/forum/nav.rs\n@@ -1,7 +1,8 @@\n use crate::canonical_path::canonicalize_item;\n use crate::reducer::ScopeId;\n+use slug_types::room_route_segment;\n \n-/// URL helpers for public `/t/…` and private room threads `/r/{short}/{slug}/t/…`.\n+/// URL helpers for public `/t/…` and private room threads `/r/{short}{slug}/t/…`.\n #[derive(Clone)]\n pub struct ThreadNav {\n pub room_wire: String,\n@@ -22,18 +23,15 @@ impl ThreadNav {\n }\n }\n \n- /// `room_id` wire form `shortid/slug`.\n+ /// `room_id` wire form `shortid/slug` (HTTP uses [`slug_types::room_route_segment`]).\n pub(crate) fn from_room_id(room_id: &str) -> Option {\n- let (short, slug) = room_id.split_once('/')?;\n- if short.is_empty() || slug.is_empty() {\n- return None;\n- }\n+ let room_seg = room_route_segment(room_id)?;\n Some(Self {\n room_wire: room_id.to_string(),\n scope: ScopeId::Room(room_id.to_string()),\n- room_path: format!(\"/r/{short}/{slug}\"),\n- thread_path_prefix: format!(\"/r/{short}/{slug}/t\"),\n- garden_path_prefix: format!(\"/r/{short}/{slug}/~\"),\n+ room_path: format!(\"/r/{room_seg}\"),\n+ thread_path_prefix: format!(\"/r/{room_seg}/t\"),\n+ garden_path_prefix: format!(\"/r/{room_seg}/~\"),\n })\n }\n \ndiff --git a/server/src/html/forum/post_single.rs b/server/src/html/forum/post_single.rs\nindex c316f8f836df9d4ef9c05ebd9e54f699540e6d72..473747b3da3d4d7a54b5e0c63165d2533df643e1 100644\n--- a/server/src/html/forum/post_single.rs\n+++ b/server/src/html/forum/post_single.rs\n@@ -93,12 +93,14 @@ pub async fn thread_post_view(\n \n pub async fn room_thread_post_view(\n State(state): State,\n- Path((room_short, room_slug, tag, index_str)): Path<(String, String, String, String)>,\n+ Path((room_key, tag, index_str)): Path<(String, String, String)>,\n headers: HeaderMap,\n jar: CookieJar,\n uri: Uri,\n ) -> impl IntoResponse {\n- let room_id = format!(\"{room_short}/{room_slug}\");\n+ let Some(room_id) = slug_types::room_id_from_route_segment(&room_key) else {\n+ return (StatusCode::NOT_FOUND, \"bad room path\").into_response();\n+ };\n let reduced = state.reduced.read().await;\n let user = optional_principal(&headers, &jar, &reduced);\n if !user_can_view_room(&reduced, &room_id, user.as_deref()) {\ndiff --git a/server/src/html/forum/views.rs b/server/src/html/forum/views.rs\nindex be5df1745ef580891a167c23c3dd6c06f804f295..1ec421f84335cbfe7f9db775b73a8ed24b197174 100644\n--- a/server/src/html/forum/views.rs\n+++ b/server/src/html/forum/views.rs\n@@ -183,16 +183,18 @@ pub async fn thread_view(\n thread_view_inner(state, tag, q, ThreadNav::public(), headers, jar, uri).await\n }\n \n-/// Room thread — `/r/:short/:slug/t/:tag`\n+/// Room thread — `/r/:room_key/t/:tag` (`room_key` = `{short}{slug}`).\n pub async fn room_thread_view(\n State(state): State,\n- Path((room_short, room_slug, tag)): Path<(String, String, String)>,\n+ Path((room_key, tag)): Path<(String, String)>,\n Query(q): Query,\n headers: HeaderMap,\n jar: CookieJar,\n uri: Uri,\n ) -> impl IntoResponse {\n- let room_id = format!(\"{room_short}/{room_slug}\");\n+ let Some(room_id) = slug_types::room_id_from_route_segment(&room_key) else {\n+ return (StatusCode::NOT_FOUND, \"bad room path\").into_response();\n+ };\n let reduced = state.reduced.read().await;\n let user = optional_principal(&headers, &jar, &reduced);\n if !user_can_view_room(&reduced, &room_id, user.as_deref()) {\n@@ -226,15 +228,17 @@ pub(super) fn room_not_found_page(jar: &CookieJar, uri: &Uri) -> impl IntoRespon\n (StatusCode::NOT_FOUND, Html(page.into_string()))\n }\n \n-/// Private room index — `/r/:short/:slug`\n+/// Private room index — `/r/:room_key`\n pub async fn room_page(\n State(state): State,\n- Path((room_short, room_slug)): Path<(String, String)>,\n+ Path(room_key): Path,\n headers: HeaderMap,\n jar: CookieJar,\n uri: Uri,\n ) -> impl IntoResponse {\n- let room_id = format!(\"{room_short}/{room_slug}\");\n+ let Some(room_id) = slug_types::room_id_from_route_segment(&room_key) else {\n+ return (StatusCode::NOT_FOUND, \"room not found\").into_response();\n+ };\n let now = now_ms();\n let reduced = state.reduced.read().await;\n if !reduced.rooms.contains(&room_id) {\n@@ -266,7 +270,10 @@ pub async fn room_page(\n let audit_cli = format!(\"npx slugsocial private {room_id} audit\");\n drop(reduced);\n \n- let slug_display = room_slug.as_str();\n+ let slug_display = room_id\n+ .split_once('/')\n+ .map(|(_, slug)| slug)\n+ .unwrap_or(room_id.as_str());\n let page = layout(\n &format!(\"room {slug_display} — slug.social\"),\n \"view-thread\",\ndiff --git a/server/src/html/garden.rs b/server/src/html/garden.rs\nindex 423f23fd8c9ad7b7f454d6ea7a9a7607a4c9c5b9..e615dd356bcf634232d85610c0a26235ead125fd 100644\n--- a/server/src/html/garden.rs\n+++ b/server/src/html/garden.rs\n@@ -309,12 +309,14 @@ pub async fn external_ontology_path(\n \n pub async fn room_garden_index(\n State(state): State,\n- Path((room_short, room_slug)): Path<(String, String)>,\n+ Path(room_key): Path,\n headers: HeaderMap,\n jar: CookieJar,\n uri: Uri,\n ) -> impl IntoResponse {\n- let room_id = format!(\"{room_short}/{room_slug}\");\n+ let Some(room_id) = slug_types::room_id_from_route_segment(&room_key) else {\n+ return (StatusCode::NOT_FOUND, \"bad room path\").into_response();\n+ };\n let Some(nav) = ThreadNav::from_room_id(&room_id) else {\n return (StatusCode::NOT_FOUND, \"bad room path\").into_response();\n };\n@@ -341,12 +343,14 @@ pub async fn room_garden_index(\n \n pub async fn room_external_garden_index(\n State(state): State,\n- Path((room_short, room_slug)): Path<(String, String)>,\n+ Path(room_key): Path,\n headers: HeaderMap,\n jar: CookieJar,\n uri: Uri,\n ) -> impl IntoResponse {\n- let room_id = format!(\"{room_short}/{room_slug}\");\n+ let Some(room_id) = slug_types::room_id_from_route_segment(&room_key) else {\n+ return (StatusCode::NOT_FOUND, \"bad room path\").into_response();\n+ };\n let Some(nav) = ThreadNav::from_room_id(&room_id) else {\n return (StatusCode::NOT_FOUND, \"bad room path\").into_response();\n };\n@@ -416,12 +420,14 @@ pub async fn room_external_garden_index(\n \n pub async fn room_external_ontology_path(\n State(state): State,\n- Path((room_short, room_slug, path)): Path<(String, String, String)>,\n+ Path((room_key, path)): Path<(String, String)>,\n headers: HeaderMap,\n jar: CookieJar,\n uri: Uri,\n ) -> impl IntoResponse {\n- let room_id = format!(\"{room_short}/{room_slug}\");\n+ let Some(room_id) = slug_types::room_id_from_route_segment(&room_key) else {\n+ return (StatusCode::NOT_FOUND, \"bad room path\").into_response();\n+ };\n let Some(nav) = ThreadNav::from_room_id(&room_id) else {\n return (StatusCode::NOT_FOUND, \"bad room path\").into_response();\n };\n@@ -442,12 +448,14 @@ pub async fn room_external_ontology_path(\n \n pub async fn room_ontology_path(\n State(state): State,\n- Path((room_short, room_slug, path)): Path<(String, String, String)>,\n+ Path((room_key, path)): Path<(String, String)>,\n headers: HeaderMap,\n jar: CookieJar,\n uri: Uri,\n ) -> impl IntoResponse {\n- let room_id = format!(\"{room_short}/{room_slug}\");\n+ let Some(room_id) = slug_types::room_id_from_route_segment(&room_key) else {\n+ return (StatusCode::NOT_FOUND, \"bad room path\").into_response();\n+ };\n let Some(nav) = ThreadNav::from_room_id(&room_id) else {\n return (StatusCode::NOT_FOUND, \"bad room path\").into_response();\n };\ndiff --git a/server/src/html/search.rs b/server/src/html/search.rs\nindex 43e6ebf36cf0fe72c96f0f9d850bea51ac094c43..f01732f7edb32c68fcc10c39545c8f56476adb27 100644\n--- a/server/src/html/search.rs\n+++ b/server/src/html/search.rs\n@@ -351,8 +351,8 @@ fn render_search_results(results: &SearchResults, query: &str) -> Markup {\n ul class=\"search-posts\" {\n @for r in &results.posts {\n @let (post_href, post_label) = if let Some((room, tag)) = r.thread.split_once(\"/#\") {\n- if let Some((short, slug)) = room.split_once('/') {\n- (format!(\"/r/{short}/{slug}/t/{tag}\"), format!(\"{room}/#{tag}\"))\n+ if let Some(seg) = slug_types::room_route_segment(room) {\n+ (format!(\"/r/{seg}/t/{tag}\"), format!(\"{room}/#{tag}\"))\n } else {\n (\"/\".to_string(), r.thread.clone())\n }\ndiff --git a/server/src/lib.rs b/server/src/lib.rs\nindex 9e69c3f4a153527caa77b00ad101aca94b425995..71032f9a0b556097d90f3b403c677e0c86429ee4 100644\n--- a/server/src/lib.rs\n+++ b/server/src/lib.rs\n@@ -79,30 +79,30 @@ pub fn create_app(state: AppState) -> Router {\n .route(\"/~/*path\", get(crate::html::ontology_path))\n .route(\"/-\", get(crate::html::external_garden_index))\n .route(\"/-/*path\", get(crate::html::external_ontology_path))\n- .route(\"/r/:room_short/:room_slug/~\", get(crate::html::room_garden_index))\n+ .route(\"/r/:room_key/~\", get(crate::html::room_garden_index))\n .route(\n- \"/r/:room_short/:room_slug/~/*path\",\n+ \"/r/:room_key/~/*path\",\n get(crate::html::room_ontology_path),\n )\n .route(\n- \"/r/:room_short/:room_slug/-\",\n+ \"/r/:room_key/-\",\n get(crate::html::room_external_garden_index),\n )\n .route(\n- \"/r/:room_short/:room_slug/-/*path\",\n+ \"/r/:room_key/-/*path\",\n get(crate::html::room_external_ontology_path),\n )\n .route(\"/t/:tag/:index\", get(crate::html::thread_post_view))\n .route(\"/t/:tag\", get(crate::html::thread_view))\n .route(\n- \"/r/:room_short/:room_slug/t/:thread_tag/:index\",\n+ \"/r/:room_key/t/:thread_tag/:index\",\n get(crate::html::room_thread_post_view),\n )\n .route(\n- \"/r/:room_short/:room_slug/t/:thread_tag\",\n+ \"/r/:room_key/t/:thread_tag\",\n get(crate::html::room_thread_view),\n )\n- .route(\"/r/:room_short/:room_slug\", get(crate::html::room_page))\n+ .route(\"/r/:room_key\", get(crate::html::room_page))\n .route(\"/join/:token\", get(api::get_join_invite))\n .route(\"/auth/login\", get(api::get_auth_login))\n .route(\"/auth/callback\", get(api::get_auth_callback))\ndiff --git a/server/tests/integration.rs b/server/tests/integration.rs\nindex 515c691d04ef3f1f4bdfa8ee911360a43fd2b26e..feb73d475b3fc635d7f16c329d4600718c7472ba 100644\n--- a/server/tests/integration.rs\n+++ b/server/tests/integration.rs\n@@ -1,4 +1,5 @@\n use sha2::{Digest, Sha256};\n+use slug_types::room_route_segment;\n use slugsocial_server::{\n event_log::EventLog,\n events::{Event, TokenIssued, UserRegistered},\n@@ -607,7 +608,7 @@ async fn test_private_room_thread_urls_use_t_segment() {\n .as_str()\n .unwrap()\n .to_string();\n- let (room_short, room_slug) = room_id.split_once('/').unwrap();\n+ let room_seg = room_route_segment(&room_id).unwrap();\n \n let rpc = ui_post_ingest_rpc(&room_id, \"main-thread\", \"private post via web\");\n let post = client\n@@ -626,7 +627,7 @@ async fn test_private_room_thread_urls_use_t_segment() {\n Some(\"text/javascript; charset=utf-8\")\n );\n let post_js = post.text().await.unwrap();\n- let location = format!(\"/r/{room_short}/{room_slug}/t/main-thread\");\n+ let location = format!(\"/r/{room_seg}/t/main-thread\");\n assert!(post_js.contains(&format!(\"window.location = {:?};\", location)));\n assert!(post_js.contains(\"#room-thread-feed\"));\n assert!(post_js.contains(\"#thread-feed-region\"));\n@@ -665,7 +666,7 @@ async fn test_private_room_post_links_use_private_garden_routes() {\n .as_str()\n .unwrap()\n .to_string();\n- let (room_short, room_slug) = room_id.split_once('/').unwrap();\n+ let room_seg = room_route_segment(&room_id).unwrap();\n \n let rpc = ui_post_ingest_rpc(\n &room_id,\n@@ -682,18 +683,18 @@ async fn test_private_room_post_links_use_private_garden_routes() {\n assert_eq!(post.status(), reqwest::StatusCode::OK);\n \n let thread_page = client\n- .get(format!(\"http://{addr}/r/{room_short}/{room_slug}/t/garden-thread\"))\n+ .get(format!(\"http://{addr}/r/{room_seg}/t/garden-thread\"))\n .header(\"Authorization\", format!(\"Bearer {bearer}\"))\n .send()\n .await\n .unwrap();\n assert!(thread_page.status().is_success());\n let body = thread_page.text().await.unwrap();\n- assert!(body.contains(&format!(\"/r/{room_short}/{room_slug}/~/secret/item\")));\n+ assert!(body.contains(&format!(\"/r/{room_seg}/~/secret/item\")));\n assert!(!body.contains(\"href=\\\"/~/secret/item\\\"\"));\n \n let garden_page = client\n- .get(format!(\"http://{addr}/r/{room_short}/{room_slug}/~/secret/item\"))\n+ .get(format!(\"http://{addr}/r/{room_seg}/~/secret/item\"))\n .header(\"Authorization\", format!(\"Bearer {bearer}\"))\n .send()\n .await\n@@ -701,7 +702,7 @@ async fn test_private_room_post_links_use_private_garden_routes() {\n assert!(garden_page.status().is_success());\n let garden_body = garden_page.text().await.unwrap();\n assert!(garden_body.contains(\"classified\"));\n- assert!(garden_body.contains(&format!(\"/r/{room_short}/{room_slug}/t/garden-thread\")));\n+ assert!(garden_body.contains(&format!(\"/r/{room_seg}/t/garden-thread\")));\n }\n \n #[tokio::test]\n@@ -726,7 +727,7 @@ async fn test_private_room_garden_root_lists_top_level_tilde_children() {\n .as_str()\n .unwrap()\n .to_string();\n- let (room_short, room_slug) = room_id.split_once('/').unwrap();\n+ let room_seg = room_route_segment(&room_id).unwrap();\n \n let rpc = ui_post_ingest_rpc(\n &room_id,\n@@ -743,7 +744,7 @@ async fn test_private_room_garden_root_lists_top_level_tilde_children() {\n assert_eq!(post.status(), reqwest::StatusCode::OK);\n \n let root_page = client\n- .get(format!(\"http://{addr}/r/{room_short}/{room_slug}/~\"))\n+ .get(format!(\"http://{addr}/r/{room_seg}/~\"))\n .header(\"Authorization\", format!(\"Bearer {bearer}\"))\n .send()\n .await\n@@ -782,10 +783,10 @@ async fn test_empty_private_room_garden_returns_404() {\n .as_str()\n .unwrap()\n .to_string();\n- let (room_short, room_slug) = room_id.split_once('/').unwrap();\n+ let room_seg = room_route_segment(&room_id).unwrap();\n \n let root = client\n- .get(format!(\"http://{addr}/r/{room_short}/{room_slug}/~\"))\n+ .get(format!(\"http://{addr}/r/{room_seg}/~\"))\n .header(\"Authorization\", format!(\"Bearer {bearer}\"))\n .send()\n .await\n@@ -896,8 +897,8 @@ async fn test_sse_stream_emits_evalable_js_after_post() {\n .as_str()\n .unwrap()\n .to_string();\n- let (room_short, room_slug) = room_id.split_once('/').unwrap();\n- let room_path = format!(\"/r/{room_short}/{room_slug}\");\n+ let room_seg = room_route_segment(&room_id).unwrap();\n+ let room_path = format!(\"/r/{room_seg}\");\n \n let sse_resp = client\n .get(format!(\"http://{addr}/sse?path={}\", urlencoding::encode(&room_path)))\ndiff --git a/test/browser_room_delete.clj b/test/browser_room_delete.clj\nindex 833e3f8aa7f850b60ee59742736143cbf101a07d..764ecaa674798a61c1ffca3859f2a56a91a0e97e 100644\n--- a/test/browser_room_delete.clj\n+++ b/test/browser_room_delete.clj\n@@ -54,7 +54,7 @@\n room-id (get-in create-json [\"results\" 0 \"result\" \"RoomCreated\" \"room_id\"])\n _ (is (string? room-id) \"room id present\")\n [room-short room-slug] (str/split room-id #\"/\" 2)\n- room-path (str \"/r/\" room-short \"/\" room-slug)]\n+ room-path (str \"/r/\" room-short room-slug)]\n (core/with-playwright [pw]\n (core/with-browser [browser (core/launch-chromium pw {:headless true :channel \"chrome\"})]\n (core/with-context [ctx (core/new-context browser)]\ndiff --git a/test/browser_sse.clj b/test/browser_sse.clj\nindex 8bb064dbc2dc0feb6caaa67f520a461645958277..678399b79f78ff48b5e77342fa21e69992393834 100644\n--- a/test/browser_sse.clj\n+++ b/test/browser_sse.clj\n@@ -77,7 +77,7 @@\n (login-user! bob-pg base-url \"bob\")\n \n (let [[room-short room-slug] (str/split room-id #\"/\" 2)\n- room-url (str base-url \"/r/\" room-short \"/\" room-slug)\n+ room-url (str base-url \"/r/\" room-short room-slug)\n thread-url (str room-url \"/t/sse-thread\")]\n ;; Object under test: slug_ui.js intercepts POST /ui, evals JS, morphs\n ;; #new-thread-ui-slot (expand compose), then post_ingest redirects to thread.\ndiff --git a/test/walkthrough_fixture.clj b/test/walkthrough_fixture.clj\nindex a487ff1ef8548580577914fb33f321586859c9af..f7eb1cacca0317129e9baf68fa4f4e33356ad70f 100644\n--- a/test/walkthrough_fixture.clj\n+++ b/test/walkthrough_fixture.clj\n@@ -88,9 +88,9 @@\n :room {:id room-id\n :short room-short\n :slug room-slug\n- :url (str base-url \"/r/\" room-short \"/\" room-slug)\n- :thread_url (str base-url \"/r/\" room-short \"/\" room-slug \"/t/walkthrough-thread\")\n- :garden_url (str base-url \"/r/\" room-short \"/\" room-slug \"/~/secret/item\")}}))\n+ :url (str base-url \"/r/\" room-short room-slug)\n+ :thread_url (str base-url \"/r/\" room-short room-slug \"/t/walkthrough-thread\")\n+ :garden_url (str base-url \"/r/\" room-short room-slug \"/~/secret/item\")}}))\n \n (defn- rebase-fixture-summary [saved current-base-url current-google-url current-data-dir]\n (let [inner (:summary saved)\n@@ -103,9 +103,9 @@\n :data_dir (str current-data-dir)\n :summary (assoc inner\n :room (assoc room\n- :url (str current-base-url \"/r/\" rs \"/\" lg)\n- :thread_url (str current-base-url \"/r/\" rs \"/\" lg \"/t/walkthrough-thread\")\n- :garden_url (str current-base-url \"/r/\" rs \"/\" lg \"/~/secret/item\"))))))\n+ :url (str current-base-url \"/r/\" rs lg)\n+ :thread_url (str current-base-url \"/r/\" rs lg \"/t/walkthrough-thread\")\n+ :garden_url (str current-base-url \"/r/\" rs lg \"/~/secret/item\"))))))\n \n (defn- fixture-log-present? [data-dir]\n (let [p (fs/path data-dir \"events.jsonl\")]\ndiff --git a/types/Cargo.toml b/types/Cargo.toml\nindex 1ed06d483ac7c126516bce27f90e7639c2dfe370..5dc3becf238f23243313dff0484c682a7b225737 100644\n--- a/types/Cargo.toml\n+++ b/types/Cargo.toml\n@@ -5,3 +5,4 @@ edition = \"2021\"\n \n [dependencies]\n serde = { version = \"1.0\", features = [\"derive\"] }\n+url = { version = \"2.5\", features = [\"serde\"] }\ndiff --git a/types/src/lib.rs b/types/src/lib.rs\nindex fce1b5fa5e259a4b86a11cb4d4f7cc9bec3a0aa1..516cf935f15fca97081b39b988da5be894c67725 100644\n--- a/types/src/lib.rs\n+++ b/types/src/lib.rs\n@@ -1,5 +1,7 @@\n use serde::{Deserialize, Serialize};\n \n+pub mod room_route;\n+pub mod url_normalize;\n pub mod paths;\n pub mod timeago;\n \n@@ -8,6 +10,8 @@ pub use paths::{\n CanonicalItemUrl, ForumThreadUrl, GardenItemUrl, RelativePath, SLUG_TILDE_ONTOLOGY_ROOT,\n TildeHttpPathTail, TildeOntologyPath, TildePath, tilde_http_path_to_canonical,\n };\n+pub use room_route::{room_id_from_route_segment, room_route_segment, ROOM_SHORT_ID_LEN};\n+pub use url_normalize::normalize_http_identity_url;\n \n /// Max characters returned for a garden item body unless `full=true` / `--full` (API + CLI).\n pub const MAX_ITEM_BODY_PREVIEW_CHARS: usize = 100_000;\n@@ -657,3 +661,6 @@ pub struct VoteResponse {\n pub ranking: Vec,\n pub next: NextMoves,\n }\n+\n+#[cfg(test)]\n+mod url_identity_tests;\ndiff --git a/types/src/paths.rs b/types/src/paths.rs\nindex 8971f599a7ebcf399f60c306d35ee28d0f581194..98787a5fb481a1599556564bbbbd1d54dc693fc3 100644\n--- a/types/src/paths.rs\n+++ b/types/src/paths.rs\n@@ -5,7 +5,7 @@\n //!\n //! - **[`canonicalize_item`] / [`CanonicalItemUrl`]** — graph storage key and DSL form; tilde\n //! ontology root is always [`SLUG_TILDE_ONTOLOGY_ROOT`] (no `…/~/` trailing slash only).\n-//! - **[`TildeHttpPathTail`]** — capture from `GET /~/*path` or `…/r/…/~/…` (the `*path` segment).\n+//! - **[`TildeHttpPathTail`]** — capture from `GET /~/*path` or `…/r/{short}{slug}/~/…` (the `*path` segment).\n //! - **`-/…` wire form** — external items; see [`canonicalize_item`] dash branch.\n //! - **[`GardenItemUrl`], [`ForumThreadUrl`]** — JSON / browser href surfaces.\n \n@@ -15,6 +15,9 @@ use std::ops::Deref;\n \n use serde::{Deserialize, Serialize};\n \n+use crate::room_route::room_route_segment;\n+use crate::url_normalize::{host_preserves_dash_path_case, normalize_http_identity_url};\n+\n // ---------------------------------------------------------------------------\n // Slug tilde ontology (single storage form for `~/`)\n // ---------------------------------------------------------------------------\n@@ -41,6 +44,29 @@ pub fn canonicalize_tag(input: &str) -> String {\n input.trim().trim_start_matches('#').to_lowercase()\n }\n \n+fn finalize_external_identity_url(s: String) -> String {\n+ if s.starts_with(\"https://slug.social/\") {\n+ return s;\n+ }\n+ let normalized = normalize_http_identity_url(&s).unwrap_or_else(|| s.clone());\n+ strip_redundant_root_slash(&normalized).unwrap_or(normalized)\n+}\n+\n+/// `url::Url` serializes bare hosts with a `/` path; we keep host-only items slash-free for stable\n+/// keys matching the pre-normalizer spellings.\n+fn strip_redundant_root_slash(s: &str) -> Option {\n+ let u = url::Url::parse(s).ok()?;\n+ if u.path() == \"/\" && u.query().is_none() && u.fragment().is_none() {\n+ let scheme = u.scheme();\n+ let host = u.host_str()?;\n+ return Some(match u.port() {\n+ Some(p) => format!(\"{scheme}://{host}:{p}\"),\n+ None => format!(\"{scheme}://{host}\"),\n+ });\n+ }\n+ None\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@@ -57,8 +83,9 @@ pub fn canonicalize_item(input: &str) -> String {\n if host.is_empty() {\n return String::new();\n }\n+ let preserve_case = host_preserves_dash_path_case(&host);\n return if tail.is_empty() {\n- format!(\"https://{}\", host)\n+ finalize_external_identity_url(format!(\"https://{}\", host))\n } else {\n let path = tail\n .trim_start_matches('/')\n@@ -68,33 +95,35 @@ pub fn canonicalize_item(input: &str) -> String {\n let t = seg.trim();\n if t.is_empty() {\n None\n+ } else if preserve_case {\n+ Some(t.to_string())\n } else {\n Some(t.to_lowercase())\n }\n })\n .collect::>()\n .join(\"/\");\n- format!(\"https://{}/{}\", host, path)\n+ finalize_external_identity_url(format!(\"https://{}/{}\", host, path))\n };\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+ return finalize_external_identity_url(if tail.is_empty() {\n+ format!(\"https://{}\", host)\n } else {\n- return format!(\"https://{}/{}\", host, tail);\n- }\n+ 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+ return finalize_external_identity_url(if tail.is_empty() {\n+ format!(\"http://{}\", host)\n } else {\n- return format!(\"http://{}/{}\", host, tail);\n- }\n+ format!(\"http://{}/{}\", host, tail)\n+ });\n }\n \n let is_tilde = s.starts_with(\"~/\");\n@@ -319,7 +348,7 @@ impl CanonicalItemUrl {\n }\n }\n \n-/// HTTP route capture: path segment after `~/` in `GET /~/*path` or `…/r/…/~/…` (empty = ontology root).\n+/// HTTP route capture: path segment after `~/` in `GET /~/*path` or `…/r/{short}{slug}/~/…` (empty = ontology root).\n #[derive(Debug, Clone, PartialEq, Eq, Hash)]\n pub struct TildeHttpPathTail(pub String);\n \n@@ -506,12 +535,9 @@ fn garden_href_string(item: &str, room_wire: &str) -> String {\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+ let Some(room_seg) = room_route_segment(room) 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@@ -520,19 +546,19 @@ fn garden_href_string(item: &str, room_wire: &str) -> String {\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+ format!(\"https://slug.social/r/{room_seg}/~\")\n } else {\n- format!(\"https://slug.social/r/{short}/{slug}/~/{}\", tail)\n+ format!(\"https://slug.social/r/{room_seg}/~/{}\", tail)\n };\n }\n if item_norm == root_norm {\n- return format!(\"https://slug.social/r/{short}/{slug}/~\");\n+ return format!(\"https://slug.social/r/{room_seg}/~\");\n }\n // External http(s) items use the same `/-/…` namespace under the room garden.\n if c.as_str().starts_with(\"https://\") || c.as_str().starts_with(\"http://\") {\n let tail = c.display_path();\n let tail = tail.strip_prefix(\"-/\").unwrap_or(tail.as_str());\n- return format!(\"https://slug.social/r/{short}/{slug}/-/{tail}\");\n+ return format!(\"https://slug.social/r/{room_seg}/-/{tail}\");\n }\n api_path_or_url(item)\n }\n@@ -556,12 +582,8 @@ impl ForumThreadUrl {\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 if let Some(room_seg) = room_route_segment(room) {\n+ format!(\"https://slug.social/r/{room_seg}/t/{tag}\")\n } else {\n format!(\"https://slug.social/t/{tag}\")\n })\n@@ -706,7 +728,7 @@ mod tests {\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+ \"https://slug.social/r/9ab12cdmy-room/~/topic/x\"\n );\n }\n \n@@ -714,11 +736,11 @@ mod tests {\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+ \"https://slug.social/r/9ab12cdmy-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+ \"https://slug.social/r/9ab12cdmy-room/~\"\n );\n }\n \n@@ -727,7 +749,7 @@ mod tests {\n let u = \"https://example.com/z\";\n assert_eq!(\n GardenItemUrl::from_storage_str(u, \"9ab12cd/my-room\").as_str(),\n- \"https://slug.social/r/9ab12cd/my-room/-/example.com/z\"\n+ \"https://slug.social/r/9ab12cdmy-room/-/example.com/z\"\n );\n }\n \n@@ -739,7 +761,19 @@ mod tests {\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+ \"https://slug.social/r/9ab12cdmy-room/t/debate\"\n+ );\n+ }\n+\n+ #[test]\n+ fn canonicalize_youtube_short_links() {\n+ assert_eq!(\n+ canonicalize_item(\"https://youtu.be/dQw4w9WgXcQ\"),\n+ \"https://www.youtube.com/watch?v=dQw4w9WgXcQ\"\n+ );\n+ assert_eq!(\n+ canonicalize_item(\"-/youtu.be/dQw4w9WgXcQ\"),\n+ \"https://www.youtube.com/watch?v=dQw4w9WgXcQ\"\n );\n }\n \ndiff --git a/types/src/room_route.rs b/types/src/room_route.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..4f4780c88e30f2b28e2cfcd7aee713d39dbd1c66\n--- /dev/null\n+++ b/types/src/room_route.rs\n@@ -0,0 +1,56 @@\n+//! HTTP path encoding for private rooms: `/r/{short}{slug}` (short is fixed width).\n+\n+/// Byte length of the random `short` segment in `short/slug` room ids.\n+/// Must match room creation (`gen_short_id`) and [`super::paths`][] URL builders.\n+pub const ROOM_SHORT_ID_LEN: usize = 7;\n+\n+/// `ab12cde/my-room` → `ab12cdemy-room` for a single `/r/…` path segment.\n+pub fn room_route_segment(room_id: &str) -> Option {\n+ let (short, slug) = room_id.split_once('/')?;\n+ if short.len() != ROOM_SHORT_ID_LEN || short.is_empty() || slug.is_empty() {\n+ return None;\n+ }\n+ if !short\n+ .bytes()\n+ .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'z'))\n+ {\n+ return None;\n+ }\n+ Some(format!(\"{short}{slug}\"))\n+}\n+\n+/// `/r/{short}{slug}` path segment → `short/slug` wire id (inverse of [`room_route_segment`]).\n+pub fn room_id_from_route_segment(seg: &str) -> Option {\n+ if seg.len() <= ROOM_SHORT_ID_LEN {\n+ return None;\n+ }\n+ let (short, slug) = seg.split_at(ROOM_SHORT_ID_LEN);\n+ if short.is_empty() || slug.is_empty() {\n+ return None;\n+ }\n+ if !short\n+ .bytes()\n+ .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'z'))\n+ {\n+ return None;\n+ }\n+ Some(format!(\"{short}/{slug}\"))\n+}\n+\n+#[cfg(test)]\n+mod tests {\n+ use super::*;\n+\n+ #[test]\n+ fn round_trip_room_segment() {\n+ let id = \"9ab12cd/my-room\";\n+ let seg = room_route_segment(id).unwrap();\n+ assert_eq!(seg, \"9ab12cdmy-room\");\n+ assert_eq!(room_id_from_route_segment(&seg).as_deref(), Some(id));\n+ }\n+\n+ #[test]\n+ fn too_short_segment_rejected() {\n+ assert!(room_id_from_route_segment(\"9ab12cd\").is_none());\n+ }\n+}\ndiff --git a/types/src/url_identity_tests.rs b/types/src/url_identity_tests.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..e2ff0a9a64a88049e31f20979c703777df6a9b65\n--- /dev/null\n+++ b/types/src/url_identity_tests.rs\n@@ -0,0 +1,126 @@\n+//! How `url::Url` behaves as `HashMap` keys (`Eq` + `Hash`).\n+//!\n+//! If `ItemId::External` stores `Url`, these tests are the contract you are buying into\n+//! (or the baseline before you add a custom normalization layer).\n+\n+use std::collections::HashMap;\n+use std::hash::{Hash, Hasher};\n+use url::Url;\n+\n+fn hash_one(url: &Url) -> u64 {\n+ let mut h = std::collections::hash_map::DefaultHasher::new();\n+ url.hash(&mut h);\n+ h.finish()\n+}\n+\n+#[test]\n+fn identical_parse_strings_are_eq_and_share_hash_bucket() {\n+ let a = Url::parse(\"https://example.com/path\").unwrap();\n+ let b = Url::parse(\"https://example.com/path\").unwrap();\n+ assert_eq!(a, b);\n+ assert_eq!(hash_one(&a), hash_one(&b));\n+\n+ let mut m: HashMap = HashMap::new();\n+ m.insert(a, 1);\n+ *m.entry(b).or_default() += 10;\n+ assert_eq!(m.len(), 1);\n+ assert_eq!(m[&Url::parse(\"https://example.com/path\").unwrap()], 11);\n+}\n+\n+#[test]\n+fn host_is_ascii_lowercase_in_eq() {\n+ let lower = Url::parse(\"https://examplE.com/\").unwrap();\n+ let upper = Url::parse(\"https://EXAMPLE.com/\").unwrap();\n+ assert_eq!(lower, upper);\n+ assert_eq!(hash_one(&lower), hash_one(&upper));\n+}\n+\n+#[test]\n+fn path_space_normalizes_to_percent_encoding_so_forms_merge() {\n+ let encoded = Url::parse(\"https://example.com/a%20b\").unwrap();\n+ let decoded = Url::parse(\"https://example.com/a b\").unwrap();\n+ // Parser normalizes both to the same internal path (`/a%20b`).\n+ assert_eq!(encoded, decoded);\n+ assert_eq!(hash_one(&encoded), hash_one(&decoded));\n+\n+ let mut m: HashMap = HashMap::new();\n+ m.insert(encoded, \"first\");\n+ assert_eq!(m.insert(decoded, \"second\"), Some(\"first\"));\n+ assert_eq!(m.len(), 1);\n+ assert_eq!(m.values().next().copied(), Some(\"second\"));\n+}\n+\n+#[test]\n+fn encoded_slash_in_segment_stays_distinct_from_real_path_separator() {\n+ let encoded = Url::parse(\"https://example.com/a%2Fb\").unwrap();\n+ let real_slash = Url::parse(\"https://example.com/a/b\").unwrap();\n+ assert_ne!(encoded, real_slash);\n+ assert_ne!(hash_one(&encoded), hash_one(&real_slash));\n+}\n+\n+#[test]\n+fn trailing_slash_on_path_is_significant_for_eq() {\n+ let with_slash = Url::parse(\"https://example.com/foo/\").unwrap();\n+ let no_slash = Url::parse(\"https://example.com/foo\").unwrap();\n+ assert_ne!(with_slash, no_slash);\n+ assert_ne!(hash_one(&with_slash), hash_one(&no_slash));\n+}\n+\n+#[test]\n+fn default_http_port_80_is_normalized_in_representation() {\n+ let explicit = Url::parse(\"http://example.com:80/\").unwrap();\n+ let implicit = Url::parse(\"http://example.com/\").unwrap();\n+ assert_eq!(explicit, implicit);\n+ assert_eq!(hash_one(&explicit), hash_one(&implicit));\n+}\n+\n+#[test]\n+fn default_https_port_443_is_normalized() {\n+ let explicit = Url::parse(\"https://example.com:443/foo\").unwrap();\n+ let implicit = Url::parse(\"https://example.com/foo\").unwrap();\n+ assert_eq!(explicit, implicit);\n+}\n+\n+#[test]\n+fn non_default_port_is_part_of_identity() {\n+ let a = Url::parse(\"https://example.com:444/\").unwrap();\n+ let b = Url::parse(\"https://example.com:445/\").unwrap();\n+ assert_ne!(a, b);\n+}\n+\n+#[test]\n+fn empty_path_vs_slash_only_path_may_differ() {\n+ let root = Url::parse(\"https://example.com\").unwrap();\n+ let slash = Url::parse(\"https://example.com/\").unwrap();\n+ // Both serialize to `https://example.com/` in practice for this crate — verify.\n+ assert_eq!(root, slash, \"document: root and trailing-slash-only merge for this parser\");\n+}\n+\n+#[test]\n+fn scheme_case_is_normalized_to_lowercase() {\n+ let lower = Url::parse(\"https://example.com/\").unwrap();\n+ let upper = Url::parse(\"HTTPS://example.com/\").unwrap();\n+ assert_eq!(lower, upper);\n+}\n+\n+#[test]\n+fn fragment_is_part_of_eq_and_hash() {\n+ let no_frag = Url::parse(\"https://example.com/a\").unwrap();\n+ let frag = Url::parse(\"https://example.com/a#section\").unwrap();\n+ assert_ne!(\n+ no_frag, frag,\n+ \"#fragment is included in PartialEq — anchors are different HashMap keys\"\n+ );\n+ assert_ne!(hash_one(&no_frag), hash_one(&frag));\n+}\n+\n+#[test]\n+fn query_order_and_encoding_can_split_identity() {\n+ let a = Url::parse(\"https://example.com/?b=2&a=1\").unwrap();\n+ let b = Url::parse(\"https://example.com/?a=1&b=2\").unwrap();\n+ assert_ne!(a, b, \"query pairs order is preserved in serialization\");\n+\n+ let plus = Url::parse(\"https://example.com/?q=a+b\").unwrap();\n+ let encoded = Url::parse(\"https://example.com/?q=a%20b\").unwrap();\n+ assert_ne!(plus, encoded, \"space as + vs %20 — different keys unless normalized\");\n+}\ndiff --git a/types/src/url_normalize.rs b/types/src/url_normalize.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..d5bc913f33ad29cd0cd1c7158e28e4fefdbf5f5d\n--- /dev/null\n+++ b/types/src/url_normalize.rs\n@@ -0,0 +1,234 @@\n+//! Normalization for external `http(s)://` item identity (not slug tilde ontology).\n+//!\n+//! Policy (intentional, extend here as new domains need treatment):\n+//! - Query pairs sorted lexicographically by **lowercased** key, then value.\n+//! - YouTube family → stable `www.youtube.com` shapes where possible.\n+\n+use url::Url;\n+\n+/// Whether `-/` → `https://…` path segments should keep original casing (YouTube video IDs are\n+/// case-sensitive).\n+pub(crate) fn host_preserves_dash_path_case(host: &str) -> bool {\n+ let h = host.trim().to_ascii_lowercase();\n+ let h = h.strip_prefix(\"www.\").unwrap_or(h.as_str());\n+ matches!(\n+ h,\n+ \"youtu.be\" | \"youtube.com\" | \"m.youtube.com\" | \"music.youtube.com\"\n+ )\n+}\n+\n+/// Normalize external http(s) URLs for stable [`super::paths::canonicalize_item`] output.\n+pub fn normalize_http_identity_url(s: &str) -> Option {\n+ let mut u = Url::parse(s).ok()?;\n+ if !matches!(u.scheme(), \"http\" | \"https\") {\n+ return None;\n+ }\n+ rewrite_youtube(&mut u);\n+ sort_query_pairs(&mut u);\n+ Some(u.to_string())\n+}\n+\n+fn base_host(host: &str) -> String {\n+ let lower = host.to_ascii_lowercase();\n+ lower\n+ .strip_prefix(\"www.\")\n+ .unwrap_or(lower.as_str())\n+ .to_string()\n+}\n+\n+fn rewrite_youtube(u: &mut Url) {\n+ let Some(host_raw) = u.host_str() else {\n+ return;\n+ };\n+ let base = base_host(host_raw);\n+ let path = u.path().to_string();\n+\n+ match base.as_str() {\n+ \"youtu.be\" => {\n+ let id = path.trim_start_matches('/').split('/').next().unwrap_or(\"\").to_string();\n+ if id.is_empty() {\n+ return;\n+ }\n+ let saved: Vec<(String, String)> = u.query_pairs().into_owned().collect();\n+ let Ok(mut out) = Url::parse(&format!(\"https://www.youtube.com/watch?v={id}\")) else {\n+ return;\n+ };\n+ {\n+ let mut q = out.query_pairs_mut();\n+ for (k, v) in saved {\n+ if k.eq_ignore_ascii_case(\"v\") {\n+ continue;\n+ }\n+ q.append_pair(&k, &v);\n+ }\n+ }\n+ *u = out;\n+ }\n+ \"youtube.com\" | \"m.youtube.com\" => {\n+ if base == \"m.youtube.com\" {\n+ let _ = u.set_host(Some(\"www.youtube.com\"));\n+ }\n+ if path.starts_with(\"/embed/\") {\n+ let id = path\n+ .strip_prefix(\"/embed/\")\n+ .unwrap_or(\"\")\n+ .trim_matches('/')\n+ .split('/')\n+ .next()\n+ .unwrap_or(\"\")\n+ .to_string();\n+ if id.is_empty() {\n+ return;\n+ }\n+ let saved: Vec<(String, String)> = u.query_pairs().into_owned().collect();\n+ let Ok(mut out) = Url::parse(&format!(\"https://www.youtube.com/watch?v={id}\"))\n+ else {\n+ return;\n+ };\n+ {\n+ let mut q = out.query_pairs_mut();\n+ for (k, v) in saved {\n+ if k.eq_ignore_ascii_case(\"v\") {\n+ continue;\n+ }\n+ q.append_pair(&k, &v);\n+ }\n+ }\n+ *u = out;\n+ return;\n+ }\n+ if path.starts_with(\"/v/\") {\n+ let id = path\n+ .strip_prefix(\"/v/\")\n+ .unwrap_or(\"\")\n+ .trim_matches('/')\n+ .split('/')\n+ .next()\n+ .unwrap_or(\"\")\n+ .to_string();\n+ if id.is_empty() {\n+ return;\n+ }\n+ let saved: Vec<(String, String)> = u.query_pairs().into_owned().collect();\n+ let Ok(mut out) = Url::parse(&format!(\"https://www.youtube.com/watch?v={id}\"))\n+ else {\n+ return;\n+ };\n+ {\n+ let mut q = out.query_pairs_mut();\n+ for (k, v) in saved {\n+ if k.eq_ignore_ascii_case(\"v\") {\n+ continue;\n+ }\n+ q.append_pair(&k, &v);\n+ }\n+ }\n+ *u = out;\n+ return;\n+ }\n+ if path.starts_with(\"/watch\") {\n+ let _ = u.set_host(Some(\"www.youtube.com\"));\n+ return;\n+ }\n+ if path.starts_with(\"/shorts/\") {\n+ let id = path\n+ .strip_prefix(\"/shorts/\")\n+ .unwrap_or(\"\")\n+ .trim_matches('/')\n+ .split('/')\n+ .next()\n+ .unwrap_or(\"\")\n+ .to_string();\n+ if id.is_empty() {\n+ return;\n+ }\n+ let saved: Vec<(String, String)> = u.query_pairs().into_owned().collect();\n+ let Ok(mut out) = Url::parse(&format!(\"https://www.youtube.com/shorts/{id}\"))\n+ else {\n+ return;\n+ };\n+ {\n+ let mut q = out.query_pairs_mut();\n+ for (k, v) in saved {\n+ q.append_pair(&k, &v);\n+ }\n+ }\n+ *u = out;\n+ return;\n+ }\n+ let _ = u.set_host(Some(\"www.youtube.com\"));\n+ }\n+ \"music.youtube.com\" => {}\n+ _ => {}\n+ }\n+}\n+\n+fn sort_query_pairs(u: &mut Url) {\n+ let pairs: Vec<(String, String)> = u.query_pairs().into_owned().collect();\n+ if pairs.is_empty() {\n+ u.set_query(None);\n+ return;\n+ }\n+ let mut pairs = pairs;\n+ pairs.sort_by(|a, b| {\n+ a.0.to_ascii_lowercase()\n+ .cmp(&b.0.to_ascii_lowercase())\n+ .then_with(|| a.1.cmp(&b.1))\n+ });\n+ u.set_query(None);\n+ {\n+ let mut q = u.query_pairs_mut();\n+ for (k, v) in pairs {\n+ q.append_pair(&k, &v);\n+ }\n+ }\n+}\n+\n+#[cfg(test)]\n+mod tests {\n+ use super::*;\n+\n+ #[test]\n+ fn youtube_youtu_be_to_watch() {\n+ assert_eq!(\n+ normalize_http_identity_url(\"https://youtu.be/dQw4w9WgXcQ\").as_deref(),\n+ Some(\"https://www.youtube.com/watch?v=dQw4w9WgXcQ\")\n+ );\n+ }\n+\n+ #[test]\n+ fn youtube_watch_query_sorted() {\n+ assert_eq!(\n+ normalize_http_identity_url(\"https://youtube.com/watch?v=Z&a=1&b=2\").as_deref(),\n+ Some(\"https://www.youtube.com/watch?a=1&b=2&v=Z\")\n+ );\n+ assert_eq!(\n+ normalize_http_identity_url(\"https://youtube.com/watch?b=2&a=1&v=Z\").as_deref(),\n+ Some(\"https://www.youtube.com/watch?a=1&b=2&v=Z\")\n+ );\n+ }\n+\n+ #[test]\n+ fn youtube_embed_to_watch() {\n+ assert_eq!(\n+ normalize_http_identity_url(\"https://www.youtube.com/embed/dQw4w9WgXcQ\").as_deref(),\n+ Some(\"https://www.youtube.com/watch?v=dQw4w9WgXcQ\")\n+ );\n+ }\n+\n+ #[test]\n+ fn youtube_shorts_host() {\n+ assert_eq!(\n+ normalize_http_identity_url(\"https://youtube.com/shorts/AbCdEfGhIjK\").as_deref(),\n+ Some(\"https://www.youtube.com/shorts/AbCdEfGhIjK\")\n+ );\n+ }\n+\n+ #[test]\n+ fn arbitrary_query_sorted() {\n+ assert_eq!(\n+ normalize_http_identity_url(\"https://example.com/x?z=1&a=2\").as_deref(),\n+ Some(\"https://example.com/x?a=2&z=1\")\n+ );\n+ }\n+}\n\n\nSide B — contributor: tommy-mor\nSide B — 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 B — 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","role":"user"}],"model":"openai/gpt-chat-latest"}