{"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[3b3d5873] item refactor\n\nSide A — unified diff (full patch):\ndiff --git a/plan.md b/plan.md\ndeleted file mode 100644\nindex 00d6867a1e0ed144a16a020ea037f685ce646c73..0000000000000000000000000000000000000000\n--- a/plan.md\n+++ /dev/null\n@@ -1,155 +0,0 @@\n-# Plan: `ItemId` + `RouteContext` (identity vs hrefs)\n-\n-This document is for **the next agent** to continue the refactor without re-deriving context from chat. It supersedes ad-hoc notes: treat it as the checklist of record until the work lands and this file is deleted or trimmed.\n-\n-## Goal\n-\n-- **Identity** (what lives in the reducer graph, votes, indexes) becomes a **structural `ItemId` enum** in `slug-types`, not a canonical `String` / `CanonicalItemUrl` newtype.\n-- **Presentation** (tilde / dash display, breadcrumbs) derives from `ItemId` via explicit methods, not string stripping.\n-- **Routing** (browser `href`s for public vs room) goes through **`RouteContext`** (started in `server/src/html/routing.rs`) so Maud/handlers do not stitch `/r/…` vs `/~` ad hoc.\n-\n-**Non-goals for v1 of the migration:** backward-compatible JSONL or dual-read of old canonical strings in the event log (project has accepted breaking changes). If you reintroduce compat, document it here.\n-\n-## Current state (as of this plan)\n-\n-- **`CanonicalItemUrl`** (`types/src/paths.rs`): newtype around `String`; `parse` / `parent` / `display_path` / `tilde_tail` / etc. Reducer `ContentState`, `VoteData`, ranking, RPC, search, garden, breadcrumbs all use it or `String` keys derived from it.\n-- **`ThreadNav`** (`server/src/html/forum/nav.rs`): encodes scope prefixes for threads and garden URLs; **`RouteContext`** now wraps `ThreadNav` (`server/src/html/routing.rs`, re-exported from `server/src/html/mod.rs`) but **most HTML still takes `&ThreadNav` directly** — migration incomplete.\n-- **URL normalization** lives in `types/src/url_normalize.rs` + `canonicalize_item` / `finalize_external_identity_url` in `paths.rs` (YouTube, sorted query params, room path `room_route_segment` in `paths.rs`).\n-- **Room HTTP paths** are `/r/{short}{slug}` (fused segment); wire **`room_id`** remains `short/slug` for RPC/events.\n-\n-## Target architecture\n-\n-### `ItemId` (types)\n-\n-Suggested shape (adjust after profiling `Ord` / `Hash` / serde size):\n-\n-```text\n-ItemId::Root — tilde ontology root (today `SLUG_TILDE_ONTOLOGY_ROOT`)\n-ItemId::Local { segments } — slug.social ~/… path as Vec (lowercase segments, non-empty for non-root)\n-ItemId::External { url: Url } — normalized `url::Url` (crate `url` already in `slug-types`)\n-```\n-\n-**API surface (minimum):**\n-\n-- `ItemId::parse(&str) -> Option` — single entry from DSL / user input / legacy wire (internally may call `canonicalize_item` + structured split).\n-- `ItemId::to_wire_url(&self) -> String` — only for **external** boundaries if needed (HTTP fetch, rare assertions); avoid using as the primary key once maps use `ItemId`.\n-- `parent`, `display_path`, `tilde_tail` / `tilde_http_tail`, `tilde_segments`, `last_segment`, `normalized_storage` — port from `CanonicalItemUrl`.\n-- **`Ord` + `Hash` + `Eq`** stable for `BTreeSet` / `HashMap` (see `write_actor` scope-rank snapshots).\n-- **`Serialize` / `Deserialize`** — decide **tagged JSON** for any persisted or API-carried structs (e.g. `VoteData` in tests). If RPC must stay stringy for clients, use a **DTO layer** that converts `ItemId` ↔ wire at the boundary only.\n-\n-**Remove:** `CanonicalItemUrl` type and all `path_types::CanonicalItemUrl` / `slug_types::paths::CanonicalItemUrl` exports once call sites are migrated. **`Borrow`** on the old newtype goes away; update `nav!` / any code that assumed map keys borrowed as `str`.\n-\n-### `RouteContext` (server HTML)\n-\n-- **File:** `server/src/html/routing.rs` — **`RouteContext(ThreadNav)`** with `item_href`, `item_href_raw`, `thread_url`, `garden_root_url`, `room_url`, `From`/`Into` `ThreadNav`.\n-- **Direction:** new code and refactored Maud should take **`&RouteContext`** (or owned where appropriate) instead of `&ThreadNav` when building links. Long term, **`item_href(&ItemId)`** should not parse strings — it should pattern-match `ItemId` and append tilde tail or `/-/…` external tail using the same rules as today’s `ThreadNav::garden_item_url`.\n-\n-### Axum / garden routes\n-\n-- **No** single catch-all route (explicit decision): keep the existing router layout in `server/src/lib.rs`.\n-- Room routes stay **`/r/:room_key/...`** with `room_key` fused; parsing via `slug_types::room_id_from_route_segment` / `room_route_segment` in `paths.rs`.\n-\n-## Phased execution (recommended order)\n-\n-### Phase 0 — Preconditions (quick)\n-\n-1. Read **`AGENTS.md`** (UI contract, durability matrix, `RpcCommand` vs `HtmlUiAction`).\n-2. Run **`cargo test --workspace`** and **`./scripts/clj-test.sh`** on clean `main` before large diffs; repeat after each phase.\n-\n-### Phase 1 — `ItemId` in `slug-types` (no server yet)\n-\n-1. Add **`ItemId`** (new file e.g. `types/src/item_id.rs` **or** inline at bottom of `paths.rs` — see **Module cycle** below).\n-2. Implement **`ItemId::parse`** using existing **`canonicalize_item`** + normalization; port **`CanonicalItemUrl`** methods to **`ItemId`** with tests ported from `paths.rs` `#[cfg(test)] mod tests`.\n-3. **`GardenItemUrl::from_stored(&ItemId, room_wire)`** (and thread helpers) — build absolute hrefs from structure, not from re-parsing a canonical string.\n-4. **`TildeHttpPathTail::to_item_id`** (rename from `to_canonical`) / **`tilde_http_path_to_item_id`**.\n-5. **`TildeOntologyPath::from_stored(&ItemId)`**.\n-6. Export **`ItemId`** from **`types/src/lib.rs`**; update **`server/src/path_types.rs`** re-exports.\n-7. **Delete `CanonicalItemUrl`** and fix all **in-crate** references in `types` only until `cargo test` passes for `slug-types`.\n-\n-**Module cycle trap:** `item_id.rs` must not `use crate::paths::{...}` if `paths.rs` also imports `ItemId` for `GardenItemUrl` in the same module. **Fix one of:**\n-\n-- **A)** Put `ItemId` **inside `paths.rs`** below `canonicalize_item` / helpers (simplest, large file), or \n-- **B)** Split **`canonicalize_item`** (+ dash host helpers + `finalize_external_identity_url`) into **`types/src/item_wire.rs`**, then `paths.rs` + `item_id.rs` both depend on `item_wire` only (cleaner, more files).\n-\n-### Phase 2 — Reducer + ranking (server core)\n-\n-1. **`server/src/reducer.rs`**: `ContentState` / `GroupState` / **`VoteData`** — replace **`CanonicalItemUrl`** with **`ItemId`** on all maps, sets, deques, vectors.\n-2. **`apply_vote`**: normalize `a`/`b` via **`ItemId::parse`** or **`ItemId`**-aware logic (remove string round-trip).\n-3. **`apply_ingest_to_content`**: **`dsl`** still yields strings for item titles in statements; normalize to **`ItemId`** at ingest boundary via **`ItemId::parse`** once per item.\n-4. **`server/src/ranking.rs`**, **`server/src/scope_rank.rs`**, **`server/src/api/write_actor.rs`** (including **`BTreeSet`** ordering), **`server/src/api/validate.rs`**, **`server/src/api/helpers.rs`** — propagate **`ItemId`**.\n-5. **`server/tests/basic.rs`** and any reducer tests constructing **`VoteData`** — use **`ItemId::parse(...).unwrap()`** or helpers.\n-\n-### Phase 3 — RPC + search + external resolver\n-\n-1. **`server/src/api/rpc.rs`**: rank/pair/matchup/search payloads; today many paths use **`GardenItemUrl::from_storage_str(item.as_str(), …)`** — switch to **`ItemId`** + **`GardenItemUrl::from_stored(&item_id, …)`** (or equivalent).\n-2. **`server/src/html/search.rs`**: scoring uses item path strings — derive from **`ItemId::display_path`** / **`to_wire_url`** only at the scoring boundary if needed.\n-3. **`server/src/external_resolver.rs`**: take **`&ItemId`** or **`ItemId::external_url()`** instead of **`&CanonicalItemUrl`**.\n-\n-### Phase 4 — HTML / Maud\n-\n-1. **`ThreadNav::garden_item_url`**: overload or replace with **`garden_item_href(&self, item: &ItemId)`** (no `CanonicalItemUrl::parse` inside).\n-2. **`RouteContext`**: extend **`item_href(&ItemId)`**; migrate call sites from **`ThreadNav`** to **`RouteContext`** where only link-building is needed (keep **`ThreadNav`** where scope / auth helpers need the full struct).\n-3. **`server/src/html/garden.rs`**, **`breadcrumb_path.rs`**, **`forum/*`**, **`editor.rs`**: replace **`CanonicalItemUrl`** with **`ItemId`**; breadcrumbs should walk **`ItemId::parent`** without string `rsplit`.\n-4. **`types` JSON types** (`RankRow`, etc.): decide whether **`GardenItemUrl`** stays string for JSON or becomes a structured field; keep **one** wire format for the public API.\n-\n-### Phase 5 — Cleanup + docs\n-\n-1. Remove dead **`canonical_path`** / **`breadcrumb_path`** string logic if fully superseded.\n-2. Update **`AGENTS.md`** if durability, `POST /ui`, or command surfaces change.\n-3. Delete or shrink **`plan.md`** when done.\n-\n-## File / symbol checklist (non-exhaustive — grep-driven)\n-\n-Run periodically:\n-\n-```bash\n-rg \"CanonicalItemUrl\" -g'*.rs'\n-rg \"path_types::CanonicalItemUrl\" -g'*.rs'\n-rg \"tilde_http_path_to_canonical\" -g'*.rs'\n-```\n-\n-**High-touch files (from prior exploration):**\n-\n-| Area | Files |\n-|------|--------|\n-| Types | `types/src/paths.rs`, `types/src/lib.rs`, `types/src/url_normalize.rs`, (optional) `types/src/item_id.rs`, `types/src/item_wire.rs` |\n-| Server re-exports | `server/src/path_types.rs`, `server/src/canonical_path.rs` |\n-| Reducer / ingest | `server/src/reducer.rs`, `server/src/dsl.rs` (parse output types if changed) |\n-| Ranking | `server/src/ranking.rs`, `server/src/scope_rank.rs` |\n-| Writer / RPC | `server/src/api/write_actor.rs`, `server/src/api/rpc.rs`, `server/src/api/helpers.rs`, `server/src/api/validate.rs` |\n-| HTML | `server/src/html/garden.rs`, `server/src/html/breadcrumb_path.rs`, `server/src/html/forum/nav.rs`, `server/src/html/routing.rs`, `server/src/html/search.rs`, `server/src/html/editor.rs`, `server/src/html/forum/ingest.rs`, … |\n-| Tests | `server/tests/basic.rs`, `server/tests/integration.rs`, `types/src/paths.rs` tests, Clojure under `test/` if URLs/assertions mention canonical shapes |\n-\n-## Events / JSONL\n-\n-- **`Ingest`** events store **`raw` DSL** only — no change required for item identity inside the event.\n-- If any future event type stores item ids as strings, migrate to **structured `ItemId` serde** or accept string only at the event boundary with immediate parse into **`ItemId`** on `apply_event`.\n-\n-## `nav!` macro (`server/src/paths.rs`)\n-\n-- Macros use **`keypath($key)`** with **`.clone()`** — **`ItemId`** must be **`Clone`** (already for enums). Remove any reliance on **`Borrow`** for map keys.\n-\n-## Testing gate\n-\n-After each phase:\n-\n-```bash\n-cargo test --workspace\n-./scripts/clj-test.sh\n-```\n-\n-## Risks / gotchas\n-\n-1. **`Ord` on `ItemId`**: must match prior **`CanonicalItemUrl`** / `String` ordering wherever **`BTreeSet`** is used (e.g. deterministic scope-rank snapshots in **`write_actor`**).\n-2. **External `ItemId`**: **`Url`** equality / hashing — normalization is already centralized in **`url_normalize`**; ensure **`ItemId::parse`** always inserts normalized **`Url`** into **`External`**.\n-3. **Fake parent URLs** in garden (e.g. **`https://.`** for external root ranking): find all **`parse(\"https://.\")`** style hacks and express as **`ItemId`** or a dedicated sentinel.\n-4. **Serde**: tests and any RPC clients that snapshot JSON may need expectation updates if **`VoteData`** shape changes.\n-\n-## Optional follow-ups (not blocking `ItemId`)\n-\n-- More **domain normalizers** in **`url_normalize.rs`** (e.g. `music.youtube.com`, Spotify, etc.).\n-- **Room wire** vs **HTTP segment** helpers already in **`paths.rs`** (`ROOM_SHORT_ID_LEN`, `room_route_segment`, `room_id_from_route_segment`).\n-\n----\n-\n-**End state criteria:** `rg CanonicalItemUrl` returns nothing; reducer maps use **`ItemId`**; HTML link generation for items goes through **`RouteContext` + `ItemId`**; tests and Kaocha green.\ndiff --git a/server/src/api/helpers.rs b/server/src/api/helpers.rs\nindex 1b291db83df7364a026f2e147e0a29a70a399371..8cd23a02fa5219d6aa375e766e6b2bd2c7bb7dfb 100644\n--- a/server/src/api/helpers.rs\n+++ b/server/src/api/helpers.rs\n@@ -4,7 +4,8 @@ use axum::{\n Json,\n };\n use sha2::{Digest, Sha256};\n-use slug_types::paths::{CanonicalItemUrl, GardenItemUrl};\n+use slug_types::paths::GardenItemUrl;\n+use slug_types::ItemId;\n use slug_types::*;\n use std::collections::HashMap;\n \n@@ -31,12 +32,12 @@ pub fn now_ms() -> i64 {\n }\n \n /// Resolve DSL/user input to a stored canonical item id.\n-pub fn resolve_item(item: &str) -> Result {\n+pub fn resolve_item(item: &str) -> Result {\n let canonical = canonicalize_item(item);\n if canonical.is_empty() {\n return Err(format!(\"empty item path: `{}`\", item));\n }\n- Ok(CanonicalItemUrl(canonical))\n+ ItemId::parse(&canonical).ok_or_else(|| format!(\"invalid item path: `{}`\", item))\n }\n \n pub fn parse_parent_specs(parent: Option<&String>) -> Vec {\n@@ -94,7 +95,7 @@ pub fn paginate_rankings(\n (out_components, out_unranked)\n }\n \n-pub fn pick_random_distinct_canonical(items: &[CanonicalItemUrl]) -> Option<(CanonicalItemUrl, CanonicalItemUrl)> {\n+pub fn pick_random_distinct_canonical(items: &[ItemId]) -> Option<(ItemId, ItemId)> {\n use rand::seq::SliceRandom;\n if items.len() < 2 {\n return None;\n@@ -115,15 +116,15 @@ pub fn pick_random_distinct_canonical(items: &[CanonicalItemUrl]) -> Option<(Can\n }\n \n pub fn is_pair_voted(group: &crate::reducer::GroupState, a: &str, b: &str) -> bool {\n- let a_key = CanonicalItemUrl(a.to_string());\n- let b_key = CanonicalItemUrl(b.to_string());\n+ let a_key = ItemId::parse(a).unwrap_or_else(|| ItemId::opaque(a.to_string()));\n+ let b_key = ItemId::parse(b).unwrap_or_else(|| ItemId::opaque(b.to_string()));\n let Some(&a_idx) = group.item_to_idx.get(&a_key) else { return false; };\n let Some(&b_idx) = group.item_to_idx.get(&b_key) else { return false; };\n let (i, j) = if a_idx < b_idx { (a_idx, b_idx) } else { (b_idx, a_idx) };\n group.voted_pairs.contains(&(i, j))\n }\n \n-pub fn compute_connectivity_stats(group: &crate::reducer::GroupState, pool: &[CanonicalItemUrl]) -> ConnectivityStats {\n+pub fn compute_connectivity_stats(group: &crate::reducer::GroupState, pool: &[ItemId]) -> ConnectivityStats {\n let n = pool.len();\n \n let global_idxs: Vec> = pool\ndiff --git a/server/src/api/rpc.rs b/server/src/api/rpc.rs\nindex 0ff2d701dd1e8661f58abd55672cd91280e9491e..079d96eb6f1d717c203b1d4aec09f3916384b919 100644\n--- a/server/src/api/rpc.rs\n+++ b/server/src/api/rpc.rs\n@@ -17,7 +17,7 @@ use crate::{\n dsl,\n events::{Event, Ingest, ThreadCapability},\n identity::{parse_agent, parse_username},\n- path_types::CanonicalItemUrl,\n+ path_types::ItemId,\n ranking::{connected_components_from_voted_pairs, ranked_items_subset},\n reducer::{scope_from_room_wire, ReducerState, ScopeId},\n state::{AppState, InviteState},\n@@ -150,7 +150,7 @@ fn build_rank_response_for_content(\n \n if !is_global && !specs.is_empty() {\n let none_exist = specs.iter().all(|spec| {\n- let Some(canon) = CanonicalItemUrl::parse(spec) else { return true };\n+ let Some(canon) = ItemId::parse(spec) else { return true };\n !content.items.contains(&canon) && !content.item_children.contains_key(&canon)\n });\n if none_exist {\n@@ -163,10 +163,10 @@ fn build_rank_response_for_content(\n \n let depth = depth.max(1);\n let rankings = if is_global {\n- let all_items: Vec = content.items.iter().cloned().collect();\n+ let all_items: Vec = content.items.iter().cloned().collect();\n crate::scope_rank::build_rankings_for_item_set(content, &all_items)\n } else if specs.is_empty() {\n- crate::scope_rank::build_children_rankings(content, &CanonicalItemUrl::ontology_root())\n+ crate::scope_rank::build_children_rankings(content, &ItemId::ontology_root())\n } else if depth > 1 {\n let items = crate::scope_rank::resolve_scope_recursive(content, &specs, depth);\n crate::scope_rank::build_rankings_for_item_set(content, &items)\n@@ -359,8 +359,8 @@ async fn rpc_check(\n let mut simulated = { reduced_arc.read().await.clone() };\n simulated.apply_event(event);\n \n- let voted_parents: Vec = {\n- let mut parents: HashSet = HashSet::new();\n+ let voted_parents: Vec = {\n+ let mut parents: HashSet = HashSet::new();\n for s in &v.doc.statements {\n if let dsl::Stmt::Vote { item1, item2, .. } = s {\n if let (Ok(a), Ok(b)) = (resolve_item(item1), resolve_item(item2)) {\n@@ -369,7 +369,7 @@ async fn rpc_check(\n }\n }\n }\n- let mut out: Vec = parents.into_iter().collect();\n+ let mut out: Vec = parents.into_iter().collect();\n out.sort();\n out\n };\n@@ -695,7 +695,7 @@ fn rpc_search(reduced: &ReducerState, q: &str, limit: usize, principal: Option<&\n async fn rpc_get_pair(state: &AppState, room: String, parent_path: String) -> Result {\n let scope = scope_from_room_wire(&room);\n let reduced_arc = state.reduced.clone();\n- let pool: Vec = {\n+ let pool: Vec = {\n let reduced = reduced_arc.read().await;\n let content = content_for_room(&reduced, &room);\n let tmp = if parent_path.trim().is_empty() {\n@@ -716,7 +716,7 @@ async fn rpc_get_pair(state: &AppState, room: String, parent_path: String) -> Re\n Some(\"add items via ingest\".into()),\n ));\n }\n- let selected: Option<(CanonicalItemUrl, CanonicalItemUrl)> = {\n+ let selected: Option<(ItemId, ItemId)> = {\n let mut reduced = reduced_arc.write().await;\n let content = reduced.content.entry(scope.clone()).or_default();\n let group = &mut content.ranking_group;\n@@ -729,16 +729,16 @@ async fn rpc_get_pair(state: &AppState, room: String, parent_path: String) -> Re\n .filter_map(|it| group.item_to_idx.get(it).copied())\n .collect();\n let ranked = ranked_items_subset(group, &idxs, 10000, 1e-8);\n- let ranked_set: HashSet = ranked.iter().map(|r| r.item.clone()).collect();\n- let unsorted: Vec = pool\n+ let ranked_set: HashSet = ranked.iter().map(|r| r.item.clone()).collect();\n+ let unsorted: Vec = pool\n .iter()\n .filter(|it| !ranked_set.contains(*it))\n .cloned()\n .collect();\n- let mut pick: Option<(CanonicalItemUrl, CanonicalItemUrl)> = None;\n+ let mut pick: Option<(ItemId, ItemId)> = None;\n if !unsorted.is_empty() {\n if let Some(left) = unsorted.choose(&mut rng).cloned() {\n- let mut candidates: Vec = if !ranked.is_empty() {\n+ let mut candidates: Vec = if !ranked.is_empty() {\n ranked.iter().map(|r| r.item.clone()).collect()\n } else {\n pool.clone()\n@@ -865,7 +865,7 @@ pub async fn handle_rpc_batch(\n } else {\n let content = content_for_room(&reduced, &room);\n let item_str = canonicalize_item(&item_path);\n- let item = CanonicalItemUrl(item_str.clone());\n+ let item = ItemId::parse(&item_str).unwrap_or_else(|| ItemId::opaque(item_str.clone()));\n if !content.items.contains(&item) {\n line_err(\n \"item not found\",\n@@ -1212,7 +1212,7 @@ pub async fn handle_rpc_batch(\n }\n \n let ranked_total = ranked.len();\n- let mut unranked: Vec = content\n+ let mut unranked: Vec = content\n .items\n .iter()\n .filter(|it| !group.item_to_idx.contains_key(*it))\n@@ -1263,7 +1263,7 @@ pub async fn handle_rpc_batch(\n } else {\n let content = content_for_room(&reduced, &room);\n let item_str = canonicalize_item(&item_path);\n- let item = CanonicalItemUrl(item_str.clone());\n+ let item = ItemId::parse(&item_str).unwrap_or_else(|| ItemId::opaque(item_str.clone()));\n let limit = limit.unwrap_or(50).clamp(1, 200);\n if !content.items.contains(&item) {\n line_err(\n@@ -1304,7 +1304,7 @@ pub async fn handle_rpc_batch(\n let content = content_for_room(&reduced, &room);\n let scope = scope_from_room_wire(&room);\n let item_str = canonicalize_item(&item_path);\n- let item = CanonicalItemUrl(item_str.clone());\n+ let item = ItemId::parse(&item_str).unwrap_or_else(|| ItemId::opaque(item_str.clone()));\n let entries = content.rank_history.get(&item).cloned().unwrap_or_default();\n let history: Vec = entries.iter().map(|e| {\n let caused_by: Vec = reduced.ingests_by_id.get(&e.post_id)\n@@ -1361,7 +1361,11 @@ pub async fn handle_rpc_batch(\n line_err(e, h)\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 parents: HashSet = content\n+ .item_children\n+ .keys()\n+ .map(|k| k.to_storage_string())\n+ .collect();\n let mut paths: Vec = content\n .items\n .iter()\n@@ -1380,11 +1384,11 @@ pub async fn handle_rpc_batch(\n let content = content_for_room(&reduced, &room);\n let out: Vec = content\n .item_children\n- .get(&CanonicalItemUrl::ontology_root())\n+ .get(&ItemId::ontology_root())\n .map(|roots| {\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 children = content.item_children.get(path).map(|s| s.len()).unwrap_or(0);\n PathSummary {\n path: TildeOntologyPath::from_stored(path),\n children,\ndiff --git a/server/src/api/validate.rs b/server/src/api/validate.rs\nindex 3c7aa80fd485cf247231fe5c5c7e6fea62f22534..3f657a88ef9328a31e3e29c3bc3bd32bec6fd7a1 100644\n--- a/server/src/api/validate.rs\n+++ b/server/src/api/validate.rs\n@@ -4,7 +4,7 @@ use std::collections::HashSet;\n use crate::{\n canonical_path::canonicalize_tag,\n dsl,\n- path_types::CanonicalItemUrl,\n+ path_types::ItemId,\n reducer::{ReducerState, ScopeId},\n };\n use slug_types::paths::GardenItemUrl;\n@@ -32,11 +32,11 @@ pub fn validate_ingest_document(\n ScopeId::Public => None,\n _ => reduced.content_for_scope(scope),\n };\n- let item_exists = |key: &CanonicalItemUrl| {\n+ let item_exists = |key: &ItemId| {\n scoped_content.map(|c| c.items.contains(key)).unwrap_or(false)\n || public_content.items.contains(key)\n };\n- let body_exists = |key: &CanonicalItemUrl| {\n+ let body_exists = |key: &ItemId| {\n scoped_content.map(|c| c.item_bodies.contains_key(key)).unwrap_or(false)\n || public_content.item_bodies.contains_key(key)\n };\n@@ -52,7 +52,7 @@ pub fn validate_ingest_document(\n };\n \n let ts = super::helpers::now_ms();\n- let mut defined_in_doc: HashSet = HashSet::new();\n+ let mut defined_in_doc: HashSet = HashSet::new();\n \n for s in &doc.statements {\n match s {\ndiff --git a/server/src/api/write_actor.rs b/server/src/api/write_actor.rs\nindex f9c3b8bd3fbf8fcb9c035e1a1572fef0b08fa8a9..3e96b015def54921962f74b4cd884808ff6c3bcc 100644\n--- a/server/src/api/write_actor.rs\n+++ b/server/src/api/write_actor.rs\n@@ -10,7 +10,7 @@ use crate::{\n events::{AgentBound, Event, GrantAdded, Ingest, PostRedacted, RoomDeleted, UserRegistered},\n html::JsBuilder,\n identity::parse_agent,\n- path_types::CanonicalItemUrl,\n+ path_types::ItemId,\n reducer::{scope_from_room_wire, ReducerState, ScopeId},\n state::AppState,\n write_cmd::WriteCmd,\n@@ -90,7 +90,7 @@ async fn broadcast_web_refresh(state: &AppState, room_key: &str, thread_id: &str\n }\n \n fn compute_scope_rank_changes(\n- parent: &CanonicalItemUrl,\n+ parent: &ItemId,\n before: &crate::scope_rank::ChildrenRankings,\n after: &crate::scope_rank::ChildrenRankings,\n room_wire: &str,\n@@ -99,7 +99,7 @@ fn compute_scope_rank_changes(\n use std::collections::BTreeSet;\n fn build_positions(\n rankings: &crate::scope_rank::ChildrenRankings,\n- ) -> HashMap> {\n+ ) -> HashMap> {\n let mut map = HashMap::new();\n for comp in &rankings.component_rankings {\n let total = comp.ranked.len();\n@@ -116,7 +116,7 @@ fn compute_scope_rank_changes(\n let before_pos = build_positions(before);\n let after_pos = build_positions(after);\n \n- let all_items: BTreeSet = before_pos\n+ let all_items: BTreeSet = before_pos\n .keys()\n .cloned()\n .chain(after_pos.keys().cloned())\n@@ -287,8 +287,8 @@ pub async fn writer_actor(mut rx: mpsc::Receiver, state: AppState) {\n .map(|d| reduced.agent_bindings.get(d).is_none())\n .unwrap_or(false);\n \n- let voted_parent_scopes: Vec = {\n- let mut parents: HashSet = HashSet::new();\n+ let voted_parent_scopes: Vec = {\n+ let mut parents: HashSet = HashSet::new();\n for s in &v.doc.statements {\n if let dsl::Stmt::Vote { item1, item2, .. } = s {\n if let (Ok(a), Ok(b)) = (resolve_item(item1), resolve_item(item2)) {\n@@ -301,12 +301,12 @@ pub async fn writer_actor(mut rx: mpsc::Receiver, state: AppState) {\n }\n }\n }\n- let mut out: Vec = parents.into_iter().collect();\n+ let mut out: Vec = parents.into_iter().collect();\n out.sort();\n out\n };\n \n- let pre_rankings: HashMap =\n+ let pre_rankings: HashMap =\n if !voted_parent_scopes.is_empty() {\n let content = content_for_room(&reduced, &room_key);\n voted_parent_scopes\ndiff --git a/server/src/external_resolver.rs b/server/src/external_resolver.rs\nindex 87409c4cab5f1930d2cd075f3417fa824fd791c7..6f5c982a627f9f620f0e3be0ba0cb92a3d7d4bb7 100644\n--- a/server/src/external_resolver.rs\n+++ b/server/src/external_resolver.rs\n@@ -1,6 +1,6 @@\n use async_trait::async_trait;\n \n-use crate::path_types::CanonicalItemUrl;\n+use crate::path_types::ItemId;\n \n #[async_trait]\n pub trait ExternalResolver: Send + Sync {\n@@ -11,7 +11,7 @@ pub trait ExternalResolver: Send + Sync {\n fn normalize(&self, path: &str) -> String;\n \n /// Fetches body when missing; GitHub hook lands here in a follow-up.\n- async fn fetch_body(&self, canonical_url: &CanonicalItemUrl) -> Result;\n+ async fn fetch_body(&self, canonical_url: &ItemId) -> Result;\n }\n \n /// Placeholder until domain-specific resolvers exist.\n@@ -27,7 +27,7 @@ impl ExternalResolver for DefaultExternalResolver {\n path.to_string()\n }\n \n- async fn fetch_body(&self, _canonical_url: &CanonicalItemUrl) -> Result {\n+ async fn fetch_body(&self, _canonical_url: &ItemId) -> Result {\n Err(\"external fetch not implemented\".to_string())\n }\n }\ndiff --git a/server/src/html/breadcrumb_path.rs b/server/src/html/breadcrumb_path.rs\nindex c8a3937923161a6ff248bd77e87eff0dc6fe9ab0..5743a98753f579c70e10961278469afd7cb9ddcf 100644\n--- a/server/src/html/breadcrumb_path.rs\n+++ b/server/src/html/breadcrumb_path.rs\n@@ -1,8 +1,8 @@\n-use crate::path_types::{tilde_http_path_to_canonical, CanonicalItemUrl};\n+use crate::path_types::{tilde_http_path_to_item_id, ItemId};\n \n /// Semantic view of an ontology path for rendering and routing decisions.\n pub(super) struct OntologyPath {\n- canonical: CanonicalItemUrl,\n+ canonical: ItemId,\n /// Breadcrumb segments: for `~/a/b` this is `[\"a\", \"b\"]` (leading `~` rendered separately).\n segments: Vec,\n }\n@@ -11,11 +11,11 @@ impl OntologyPath {\n /// Path is the `*path` segment from `/~/*path` (e.g. `topic/a`). Always treat it as under `~/`\n /// so it canonicalizes to `https://slug.social/~/…`, not the non-tilde site path.\n pub(super) fn from_input(path: &str) -> Self {\n- let canonical = tilde_http_path_to_canonical(path);\n+ let canonical = tilde_http_path_to_item_id(path);\n Self::from_canonical(canonical)\n }\n \n- pub(super) fn from_canonical(canonical: CanonicalItemUrl) -> Self {\n+ pub(super) fn from_canonical(canonical: ItemId) -> Self {\n // tilde_segments() returns [\"~\", \"a\", \"b\"] but bc_path() renders \"~\" itself,\n // so we skip the leading \"~\" segment here.\n let segments = canonical\n@@ -28,7 +28,7 @@ impl OntologyPath {\n }\n \n pub(super) fn root() -> Self {\n- Self::from_canonical(CanonicalItemUrl::ontology_root())\n+ Self::from_canonical(ItemId::ontology_root())\n }\n \n pub(super) fn is_root(&self) -> bool {\n@@ -56,7 +56,7 @@ impl OntologyPath {\n \n /// External `https://host/…` items addressed as `/-/host/…` in the URL bar.\n pub(super) struct ExternalOntologyPath {\n- canonical: CanonicalItemUrl,\n+ canonical: ItemId,\n /// e.g. `[\"github.com\", \"org\", \"repo\", \"issues\"]`\n segments: Vec,\n }\n@@ -71,13 +71,13 @@ impl ExternalOntologyPath {\n } else {\n format!(\"-/{}\", p.trim_start_matches('/'))\n };\n- let Some(canonical) = CanonicalItemUrl::parse(&raw) else {\n- return Self::from_canonical(CanonicalItemUrl(\"https://.\".to_string()));\n+ let Some(canonical) = ItemId::parse(&raw) else {\n+ return Self::from_canonical(ItemId::opaque(\"https://.\".to_string()));\n };\n Self::from_canonical(canonical)\n }\n \n- pub(super) fn from_canonical(canonical: CanonicalItemUrl) -> Self {\n+ pub(super) fn from_canonical(canonical: ItemId) -> Self {\n let s = canonical.as_str();\n let rest = s\n .strip_prefix(\"https://\")\ndiff --git a/server/src/html/editor.rs b/server/src/html/editor.rs\nindex 80657ac0df9b4bb67e4cdacca296f70267840bd1..c76417acd7a164fda23537cd4e7fb9f1f1dcd895 100644\n--- a/server/src/html/editor.rs\n+++ b/server/src/html/editor.rs\n@@ -97,7 +97,7 @@ pub async fn editor_check(\n simulated.apply_event(event);\n \n // Collect voted parent scopes.\n- let voted_parents: Vec = {\n+ let voted_parents: Vec = {\n let mut parents = std::collections::HashSet::new();\n for s in &v.doc.statements {\n if let crate::dsl::Stmt::Vote { item1, item2, .. } = s {\n@@ -107,7 +107,7 @@ pub async fn editor_check(\n }\n }\n }\n- let mut out: Vec = parents.into_iter().collect();\n+ let mut out: Vec = parents.into_iter().collect();\n out.sort();\n out\n };\ndiff --git a/server/src/html/forum/nav.rs b/server/src/html/forum/nav.rs\nindex 48fe11e46731670874ff8b6b05baa6f09ae0b7e4..7ca5b491f38104ec8c81db43a95c59da00abd8c4 100644\n--- a/server/src/html/forum/nav.rs\n+++ b/server/src/html/forum/nav.rs\n@@ -52,9 +52,14 @@ impl ThreadNav {\n }\n \n pub(crate) fn garden_item_url(&self, item: &str) -> String {\n- let Some(c) = crate::path_types::CanonicalItemUrl::parse(item) else {\n+ let Some(c) = crate::path_types::ItemId::parse(item) else {\n return format!(\"{}/{}\", self.garden_path_prefix, canonicalize_item(item));\n };\n+ self.garden_item_href(&c)\n+ }\n+\n+ /// Relative href for a structured [`crate::path_types::ItemId`] in this scope’s garden.\n+ pub(crate) fn garden_item_href(&self, c: &crate::path_types::ItemId) -> String {\n if let Some(tail) = c.tilde_tail().map(str::to_owned) {\n format!(\"{}/{}\", self.garden_path_prefix, tail)\n } else if c.as_str().starts_with(\"http://\") || c.as_str().starts_with(\"https://\") {\n@@ -63,7 +68,7 @@ impl ThreadNav {\n let ext_prefix = format!(\"{}-\", self.garden_path_prefix.trim_end_matches('~'));\n format!(\"{}/{}\", ext_prefix, rest)\n } else {\n- format!(\"{}/{}\", self.garden_path_prefix, canonicalize_item(item))\n+ format!(\"{}/{}\", self.garden_path_prefix, canonicalize_item(c.as_str()))\n }\n }\n \ndiff --git a/server/src/html/garden.rs b/server/src/html/garden.rs\nindex e615dd356bcf634232d85610c0a26235ead125fd..2af9ac5bfdee1630883e6f8257883baeafcb5a44 100644\n--- a/server/src/html/garden.rs\n+++ b/server/src/html/garden.rs\n@@ -10,7 +10,7 @@ use crate::{\n api::optional_principal,\n canonical_path::canonicalize_item,\n events::ThreadCapability,\n- path_types::CanonicalItemUrl,\n+ path_types::ItemId,\n reducer::{ContentState, ReducerState, ScopeId},\n ranking::{connected_components_from_voted_pairs, ranked_items_subset},\n scope_rank::{build_children_rankings, ChildrenRankings},\n@@ -27,7 +27,7 @@ use super::{\n \n /// Display path for an item: `~/…` or `-/…` form.\n fn item_display_path(item: &str) -> String {\n- CanonicalItemUrl::parse(item)\n+ ItemId::parse(item)\n .map(|c| c.display_path())\n .unwrap_or_else(|| canonicalize_item(item))\n }\n@@ -159,7 +159,7 @@ pub async fn garden_index(\n let nav = ThreadNav::public();\n let child_rankings = {\n let reduced = state.reduced.read().await;\n- build_children_rankings(reduced.public(), &CanonicalItemUrl::ontology_root())\n+ build_children_rankings(reduced.public(), &ItemId::ontology_root())\n };\n \n let page = layout(\n@@ -236,7 +236,7 @@ pub async fn external_garden_index(\n ) -> impl IntoResponse {\n let nav = ThreadNav::public();\n let ext_path = ExternalOntologyPath::from_input(\"\");\n- let parent = CanonicalItemUrl::parse(\"https://.\").unwrap();\n+ let parent = ItemId::parse(\"https://.\").unwrap();\n let child_rankings = {\n let reduced = state.reduced.read().await;\n build_children_rankings(reduced.public(), &parent)\n@@ -365,7 +365,7 @@ pub async fn room_external_garden_index(\n return room_not_found_page(&jar, &uri).into_response();\n }\n let ext_path = ExternalOntologyPath::from_input(\"\");\n- let parent = CanonicalItemUrl::parse(\"https://.\").unwrap();\n+ let parent = ItemId::parse(\"https://.\").unwrap();\n let child_rankings = build_children_rankings(\n content_for_garden_view(&reduced, &nav.scope()),\n &parent,\n@@ -509,13 +509,13 @@ struct ItemPageViewModel {\n fn build_sibling_rank(\n reduced: &crate::reducer::ReducerState,\n scope: &ScopeId,\n- item: &CanonicalItemUrl,\n+ item: &ItemId,\n ) -> Option {\n let item = item.clone().normalized_storage();\n let content = content_for_garden_view(reduced, scope);\n let group = &content.ranking_group;\n let parent = item.parent()?.normalized_storage();\n- let siblings: Vec = content\n+ let siblings: Vec = content\n .item_children\n .get(&parent)\n .map(|s| s.iter().cloned().collect())\n@@ -574,7 +574,7 @@ fn build_rank_history(\n item: &str,\n ) -> Vec {\n let content = content_for_garden_view(reduced, scope);\n- let item_key = CanonicalItemUrl(item.to_string());\n+ let item_key = ItemId::parse(item).unwrap_or_else(|| ItemId::opaque(item.to_string()));\n let entries = match content.rank_history.get(&item_key) {\n None => return vec![],\n Some(e) => e,\n@@ -592,8 +592,8 @@ fn build_rank_history(\n if a_str == item || b_str == item {\n Some(crate::reducer::VoteData {\n ts: e.ts,\n- a: CanonicalItemUrl(a_str),\n- b: CanonicalItemUrl(b_str),\n+ a: ItemId::parse(&a_str).unwrap_or_else(|| ItemId::opaque(a_str)),\n+ b: ItemId::parse(&b_str).unwrap_or_else(|| ItemId::opaque(b_str)),\n ratio_left, ratio_right,\n body: explanation,\n principal: reduced.ingests_by_id.get(&e.post_id)\n@@ -629,8 +629,8 @@ fn build_item_page_view_model(\n item: &str,\n ) -> ItemPageViewModel {\n let content = content_for_garden_view(reduced, scope);\n- let item_key = CanonicalItemUrl::parse(item)\n- .unwrap_or_else(|| CanonicalItemUrl::parse(\"~/\").unwrap())\n+ let item_key = ItemId::parse(item)\n+ .unwrap_or_else(|| ItemId::parse(\"~/\").unwrap())\n .normalized_storage();\n let item_has_parent = item_key.parent().is_some();\n let child_rankings = build_children_rankings(content, &item_key);\n@@ -925,10 +925,10 @@ mod tests {\n .map(|r| r.item.as_str())\n .collect();\n assert_eq!(names, vec![\"https://slug.social/~/topic/a\", \"https://slug.social/~/topic/b\"]);\n- use crate::path_types::CanonicalItemUrl;\n+ use crate::path_types::ItemId;\n assert!(\n- model.child_rankings.unranked_items.contains(&CanonicalItemUrl(\"https://slug.social/~/topic/kid1\".to_string()))\n- || model.child_rankings.unranked_items.contains(&CanonicalItemUrl(\"https://slug.social/~/topic/kid2\".to_string()))\n+ model.child_rankings.unranked_items.contains(&ItemId::parse(\"https://slug.social/~/topic/kid1\").unwrap())\n+ || model.child_rankings.unranked_items.contains(&ItemId::parse(\"https://slug.social/~/topic/kid2\").unwrap())\n );\n }\n \n@@ -941,8 +941,8 @@ mod tests {\n \"9ab12cd/my-room\",\n \"@00000000-0000-0000-0000-000000000000:test:local/test\\n~/t1 {a}\\n~/t2 {b}\\n\",\n );\n- use crate::path_types::CanonicalItemUrl;\n- let root = CanonicalItemUrl::ontology_root();\n+ use crate::path_types::ItemId;\n+ let root = ItemId::ontology_root();\n let model = build_item_page_view_model(\n &reduced,\n &ScopeId::Room(\"9ab12cd/my-room\".to_string()),\n@@ -971,8 +971,8 @@ mod tests {\n \"@00000000-0000-0000-0000-000000000000:test:local/test\\n\\\n ~/a {a}\\n~/b {b}\\n~/a 2:1 ~/b {because}\\n\",\n );\n- use crate::path_types::CanonicalItemUrl;\n- let root = CanonicalItemUrl::ontology_root();\n+ use crate::path_types::ItemId;\n+ let root = ItemId::ontology_root();\n let model = build_item_page_view_model(\n &reduced,\n &ScopeId::Room(\"9ab12cd/my-room\".to_string()),\ndiff --git a/server/src/html/routing.rs b/server/src/html/routing.rs\nindex 13e9ae0cbe32d454e34a7737edf8234d2a558502..df545a8195aa97484ef0012cff31d802ac67d9df 100644\n--- a/server/src/html/routing.rs\n+++ b/server/src/html/routing.rs\n@@ -4,7 +4,7 @@\n //! Prefer `RouteContext::item_href` / [`RouteContext::thread_url`] in new Maud over stitching\n //! `/r/…` vs `/~` manually. Call sites can migrate incrementally from passing `&ThreadNav`.\n \n-use crate::path_types::CanonicalItemUrl;\n+use crate::path_types::ItemId;\n \n use super::forum::ThreadNav;\n \n@@ -32,9 +32,9 @@ impl RouteContext {\n self.0\n }\n \n- /// Relative path for a stored canonical item in this scope’s garden.\n- pub fn item_href(&self, item: &CanonicalItemUrl) -> String {\n- self.0.garden_item_url(item.as_str())\n+ /// Relative path for a stored item in this scope’s garden.\n+ pub fn item_href(&self, item: &ItemId) -> String {\n+ self.0.garden_item_href(item)\n }\n \n /// Same as [`Self::item_href`] but parses `item` first (raw DSL / user paste).\ndiff --git a/server/src/path_types.rs b/server/src/path_types.rs\nindex 361a9d446c9043cbdea5f060db2e8633c2fd9bf9..a6e0b90a1aaead0bc1f7e0f4c5296506edf3f7ac 100644\n--- a/server/src/path_types.rs\n+++ b/server/src/path_types.rs\n@@ -1,5 +1,6 @@\n-//! Re-exports — implementations live in `slug-types` (`paths` module).\n+//! Re-exports — implementations live in `slug-types` (`paths` / `item_id` modules).\n \n+pub use slug_types::ItemId;\n pub use slug_types::paths::{\n- tilde_http_path_to_canonical, CanonicalItemUrl, RelativePath, TildeHttpPathTail, TildePath,\n+ tilde_http_path_to_item_id, RelativePath, TildeHttpPathTail, TildePath,\n };\ndiff --git a/server/src/ranking.rs b/server/src/ranking.rs\nindex b24e80ddd5f34b4e454bb81b541e8f54bd97a541..3710c9f64437f5bef3b2121905b6f3bcb7611047 100644\n--- a/server/src/ranking.rs\n+++ b/server/src/ranking.rs\n@@ -1,11 +1,11 @@\n use std::collections::HashMap;\n \n-use crate::path_types::CanonicalItemUrl;\n+use crate::path_types::ItemId;\n use crate::reducer::GroupState;\n \n #[derive(Debug, Clone)]\n pub struct RankedItem {\n- pub item: CanonicalItemUrl,\n+ pub item: ItemId,\n pub score: f64,\n }\n \n@@ -239,7 +239,7 @@ pub fn group_summary_scores(\n group: &mut GroupState,\n max_iters: usize,\n tol: f64,\n-) -> HashMap {\n+) -> HashMap {\n ranked_items(group, max_iters, tol)\n .into_iter()\n .map(|r| (r.item, r.score))\n@@ -256,11 +256,11 @@ mod tests {\n }\n \n fn vote(ts: i64, a: &str, b: &str, l: i32, r: i32) -> VoteData {\n- use crate::path_types::CanonicalItemUrl;\n+ use crate::path_types::ItemId;\n VoteData {\n ts,\n- a: CanonicalItemUrl(a.to_string()),\n- b: CanonicalItemUrl(b.to_string()),\n+ a: ItemId::parse(a).unwrap(),\n+ b: ItemId::parse(b).unwrap(),\n ratio_left: l,\n ratio_right: r,\n body: \"because\".to_string(),\ndiff --git a/server/src/reducer.rs b/server/src/reducer.rs\nindex a8651994f2c062af25b6ad792a014dcc083296f9..cd11a5391de8e36b1c3bb6c9b8067ceba0878e31 100644\n--- a/server/src/reducer.rs\n+++ b/server/src/reducer.rs\n@@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};\n use crate::canonical_path::canonicalize_tag;\n use crate::dsl;\n use crate::events::{Event, Ingest, ThreadCapability};\n-use crate::path_types::CanonicalItemUrl;\n+use crate::path_types::ItemId;\n \n #[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]\n pub enum ScopeId {\n@@ -27,8 +27,8 @@ pub fn scope_from_room_wire(room: &str) -> ScopeId {\n #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]\n pub struct VoteData {\n pub ts: i64,\n- pub a: CanonicalItemUrl,\n- pub b: CanonicalItemUrl,\n+ pub a: ItemId,\n+ pub b: ItemId,\n pub ratio_left: i32,\n pub ratio_right: i32,\n pub body: String,\n@@ -40,8 +40,8 @@ pub struct VoteData {\n \n #[derive(Debug, Clone)]\n pub struct GroupState {\n- pub item_to_idx: HashMap,\n- pub idx_to_item: Vec,\n+ pub item_to_idx: HashMap,\n+ pub idx_to_item: Vec,\n \n /// Aggregated directed edge weights: (src_idx, dst_idx) -> weight.\n pub edges: HashMap<(usize, usize), f64>,\n@@ -72,7 +72,7 @@ impl GroupState {\n }\n }\n \n- fn ensure_item(&mut self, item: &CanonicalItemUrl) -> usize {\n+ fn ensure_item(&mut self, item: &ItemId) -> usize {\n if let Some(&idx) = self.item_to_idx.get(item) {\n return idx;\n }\n@@ -85,11 +85,11 @@ impl GroupState {\n \n /// Public test helper: insert an item into the group without a vote (for unit tests).\n pub fn ensure_item_pub(&mut self, item: &str) -> usize {\n- if let Some(canon) = CanonicalItemUrl::parse(item) {\n+ if let Some(canon) = ItemId::parse(item) {\n self.ensure_item(&canon)\n } else {\n // Fallback: treat as raw canonical string\n- let canon = CanonicalItemUrl(item.to_string());\n+ let canon = ItemId::opaque(item.to_string());\n self.ensure_item(&canon)\n }\n }\n@@ -103,8 +103,8 @@ impl GroupState {\n }\n \n pub fn apply_vote(&mut self, mut vote: VoteData) {\n- vote.a = CanonicalItemUrl::parse(vote.a.as_str()).unwrap_or(vote.a);\n- vote.b = CanonicalItemUrl::parse(vote.b.as_str()).unwrap_or(vote.b);\n+ vote.a = ItemId::parse(vote.a.as_str()).unwrap_or_else(|| vote.a.clone());\n+ vote.b = ItemId::parse(vote.b.as_str()).unwrap_or_else(|| vote.b.clone());\n vote.thread_tag = canonicalize_tag(&vote.thread_tag);\n if vote.ratio_left < 0 {\n vote.ratio_left = 0;\n@@ -210,18 +210,18 @@ impl Default for ForumThreadState {\n #[derive(Debug, Clone, Default)]\n pub struct ContentState {\n pub ranking_group: GroupState,\n- pub items: HashSet,\n- pub item_bodies: HashMap,\n+ pub items: HashSet,\n+ pub item_bodies: HashMap,\n /// Parent canonical URL -> direct children.\n- pub item_children: HashMap>,\n+ pub item_children: HashMap>,\n /// Per-item vote history (most recent first).\n- pub item_votes: HashMap>,\n+ pub item_votes: HashMap>,\n /// Per-item ingest references (most recent first).\n- pub item_snippets: HashMap>,\n+ pub item_snippets: HashMap>,\n /// Item path -> threads that mention or vote on this item.\n- pub item_threads: HashMap>,\n+ pub item_threads: HashMap>,\n /// Per-item rank history, oldest first.\n- pub rank_history: HashMap>,\n+ pub rank_history: HashMap>,\n }\n \n #[derive(Debug, Clone)]\n@@ -351,7 +351,7 @@ impl ReducerState {\n /// For `a/b/c/d` this creates: `a/b/c→d`, `a/b→a/b/c`, `a→a/b`, `\"\"→a`.\n /// Stops early when an intermediate is already registered (its ancestors must be too).\n /// @e2bdefa9-a6fa-4725-b0a2-c0b09d95bb20:claudecode:anthropic/claude-opus-4\n- fn add_child_edge(content: &mut ContentState, item: &CanonicalItemUrl) {\n+ fn add_child_edge(content: &mut ContentState, item: &ItemId) {\n let mut child = item.clone();\n loop {\n let Some(parent) = child.parent() else { break };\n@@ -366,16 +366,16 @@ impl ReducerState {\n }\n \n /// Resolve an item path as a first-class canonical path.\n- fn normalize_item(item: &str) -> Option {\n- CanonicalItemUrl::parse(item)\n+ fn normalize_item(item: &str) -> Option {\n+ ItemId::parse(item)\n }\n \n /// 1-indexed rank of `item` within its connected component in the parent scope.\n /// 0 if the item has no votes connecting it to siblings (unranked).\n fn scope_rank_of(\n group: &GroupState,\n- item: &CanonicalItemUrl,\n- item_children: &HashMap>,\n+ item: &ItemId,\n+ item_children: &HashMap>,\n ) -> usize {\n let scope = match item.parent() {\n Some(p) => p,\n@@ -421,7 +421,7 @@ impl ReducerState {\n /// 1-indexed position of `item` in the component-aware global flat list.\n /// Components sorted largest-first; items ranked within each component.\n /// 0 if the item is not in the ranking group.\n- fn global_rank_of(group: &GroupState, item: &CanonicalItemUrl) -> usize {\n+ fn global_rank_of(group: &GroupState, item: &ItemId) -> usize {\n if !group.item_to_idx.contains_key(item) {\n return 0;\n }\n@@ -448,7 +448,7 @@ impl ReducerState {\n let doc = dsl::parse_full(&ing.raw).map_err(|_| ())?;\n let canonical_thread = canonicalize_tag(&ing.thread_tag);\n \n- let voted_items: Vec = doc\n+ let voted_items: Vec = doc\n .statements\n .iter()\n .filter_map(|s| {\n@@ -467,7 +467,7 @@ impl ReducerState {\n let principal = ing.principal.clone();\n let delegate = ing.delegate.clone();\n \n- let before: HashMap = if !voted_items.is_empty() {\n+ let before: HashMap = if !voted_items.is_empty() {\n crate::ranking::compute_group_ranking(&mut content.ranking_group, 10000, 1e-8);\n voted_items\n .iter()\n@@ -485,7 +485,7 @@ impl ReducerState {\n HashMap::new()\n };\n \n- let mut ingest_items: HashSet = HashSet::new();\n+ let mut ingest_items: HashSet = HashSet::new();\n \n for stmt in doc.statements {\n match stmt {\ndiff --git a/server/src/scope_rank.rs b/server/src/scope_rank.rs\nindex d656b2f0a0a3623ca6b234b746beaaca8ae6017d..4fdaae150c74ec5162c2accc06d4cc778ad79914 100644\n--- a/server/src/scope_rank.rs\n+++ b/server/src/scope_rank.rs\n@@ -3,7 +3,7 @@\n \n use std::collections::{HashMap, HashSet};\n \n-use crate::path_types::CanonicalItemUrl;\n+use crate::path_types::ItemId;\n use crate::ranking::{connected_components_from_voted_pairs, ranked_items_subset, RankedItem};\n use crate::reducer::ContentState;\n \n@@ -17,12 +17,12 @@ pub struct ScopedComponent {\n pub struct ChildrenRankings {\n pub component_rankings: Vec,\n /// Items in scope with no rank (no votes connecting them to others in this scope).\n- pub unranked_items: Vec,\n+ pub unranked_items: Vec,\n }\n \n /// Resolve one scope spec (literal path) to direct children of that parent. No wildcards.\n-fn resolve_one_scope(content: &ContentState, spec: &str) -> HashSet {\n- let Some(parent) = CanonicalItemUrl::parse(spec.trim()) else {\n+fn resolve_one_scope(content: &ContentState, spec: &str) -> HashSet {\n+ let Some(parent) = ItemId::parse(spec.trim()) else {\n return HashSet::new();\n };\n content\n@@ -36,12 +36,12 @@ fn resolve_one_scope(content: &ContentState, spec: &str) -> HashSet Vec {\n+pub fn resolve_scope(content: &ContentState, specs: &[String]) -> Vec {\n let mut set = HashSet::new();\n for spec in specs {\n set.extend(resolve_one_scope(content, spec));\n }\n- let mut out: Vec = set.into_iter().collect();\n+ let mut out: Vec = set.into_iter().collect();\n out.sort();\n out\n }\n@@ -49,18 +49,18 @@ pub fn resolve_scope(content: &ContentState, specs: &[String]) -> Vec Vec {\n+pub fn resolve_scope_recursive(content: &ContentState, specs: &[String], depth: usize) -> Vec {\n if depth == 0 {\n return vec![];\n }\n- let mut visited: HashSet = HashSet::new();\n- let mut frontier: Vec = specs\n+ let mut visited: HashSet = HashSet::new();\n+ let mut frontier: Vec = specs\n .iter()\n- .filter_map(|s| CanonicalItemUrl::parse(s))\n+ .filter_map(|s| ItemId::parse(s))\n .collect();\n \n for _level in 0..depth {\n- let mut next_frontier: Vec = Vec::new();\n+ let mut next_frontier: Vec = Vec::new();\n for parent in &frontier {\n if let Some(children) = content.item_children.get(parent) {\n for child in children {\n@@ -76,16 +76,16 @@ pub fn resolve_scope_recursive(content: &ContentState, specs: &[String], depth:\n frontier = next_frontier;\n }\n \n- let mut out: Vec = visited.into_iter().collect();\n+ let mut out: Vec = visited.into_iter().collect();\n out.sort();\n out\n }\n \n /// Build connected-component rankings for an explicit set of item paths.\n /// Use this when scope comes from multiple parents (resolve_scope).\n-pub fn build_rankings_for_item_set(content: &ContentState, items_in_scope: &[CanonicalItemUrl]) -> ChildrenRankings {\n+pub fn build_rankings_for_item_set(content: &ContentState, items_in_scope: &[ItemId]) -> ChildrenRankings {\n let group = &content.ranking_group;\n- let mut items_in_scope: Vec = items_in_scope.to_vec();\n+ let mut items_in_scope: Vec = items_in_scope.to_vec();\n items_in_scope.sort();\n \n let scoped_idxs: Vec = items_in_scope\n@@ -127,7 +127,7 @@ pub fn build_rankings_for_item_set(content: &ContentState, items_in_scope: &[Can\n })\n .collect();\n \n- let mut unranked_items: Vec = isolate_local_idxs\n+ let mut unranked_items: Vec = isolate_local_idxs\n .into_iter()\n .filter_map(|li| local_to_global.get(li).copied())\n .filter_map(|idx| group.idx_to_item.get(idx).cloned())\n@@ -148,9 +148,9 @@ pub fn build_rankings_for_item_set(content: &ContentState, items_in_scope: &[Can\n \n /// Build connected-component rankings for direct children of parent_scope.\n /// Matches the HTML garden view: multiple components, isolates, no-vote items.\n-pub fn build_children_rankings(content: &ContentState, parent: &CanonicalItemUrl) -> ChildrenRankings {\n+pub fn build_children_rankings(content: &ContentState, parent: &ItemId) -> ChildrenRankings {\n let parent = parent.clone().normalized_storage();\n- let items: Vec = content\n+ let items: Vec = content\n .item_children\n .get(&parent)\n .map(|s| s.iter().cloned().collect())\n@@ -164,10 +164,13 @@ mod tests {\n use std::collections::{HashMap, HashSet};\n \n fn content_with_children(edges: &[(&str, &[&str])]) -> ContentState {\n- let mut item_children: HashMap> = HashMap::new();\n+ let mut item_children: HashMap> = HashMap::new();\n for (parent, children) in edges {\n- let parent = CanonicalItemUrl((*parent).to_string());\n- let set: HashSet = children.iter().map(|s| CanonicalItemUrl((*s).to_string())).collect();\n+ let parent = ItemId::parse(parent).unwrap();\n+ let set: HashSet = children\n+ .iter()\n+ .map(|s| ItemId::parse(s).unwrap())\n+ .collect();\n item_children.insert(parent, set);\n }\n ContentState {\n@@ -189,8 +192,8 @@ mod tests {\n ]);\n let out = resolve_one_scope(&content, \"models\");\n assert_eq!(out.len(), 2);\n- assert!(out.contains(&CanonicalItemUrl(\"https://slug.social/models/x\".to_string())));\n- assert!(out.contains(&CanonicalItemUrl(\"https://slug.social/models/y\".to_string())));\n+ assert!(out.contains(&ItemId::parse(\"https://slug.social/models/x\").unwrap()));\n+ assert!(out.contains(&ItemId::parse(\"https://slug.social/models/y\").unwrap()));\n }\n \n #[test]\n@@ -201,9 +204,9 @@ mod tests {\n ]);\n let out = resolve_scope(&content, &[\"a\".into(), \"b\".into()]);\n assert_eq!(out.len(), 4);\n- assert!(out.contains(&CanonicalItemUrl(\"https://slug.social/a/1\".to_string())));\n- assert!(out.contains(&CanonicalItemUrl(\"https://slug.social/a/2\".to_string())));\n- assert!(out.contains(&CanonicalItemUrl(\"https://slug.social/b/1\".to_string())));\n- assert!(out.contains(&CanonicalItemUrl(\"https://slug.social/b/2\".to_string())));\n+ assert!(out.contains(&ItemId::parse(\"https://slug.social/a/1\").unwrap()));\n+ assert!(out.contains(&ItemId::parse(\"https://slug.social/a/2\").unwrap()));\n+ assert!(out.contains(&ItemId::parse(\"https://slug.social/b/1\").unwrap()));\n+ assert!(out.contains(&ItemId::parse(\"https://slug.social/b/2\").unwrap()));\n }\n }\ndiff --git a/server/tests/basic.rs b/server/tests/basic.rs\nindex 17db86894f18d6b542d2943f4cedb0572b247171..c8efea2976e20b443d78a5d4c3b244bc4f2fd6da 100644\n--- a/server/tests/basic.rs\n+++ b/server/tests/basic.rs\n@@ -7,8 +7,15 @@ use slugsocial_server::{\n };\n \n \n+use slugsocial_server::path_types::ItemId;\n+\n use tempfile::TempDir;\n \n+#[inline]\n+fn item_id(s: &str) -> ItemId {\n+ ItemId::parse(s).unwrap()\n+}\n+\n fn ingest_event(ts: i64, raw: &str) -> Event {\n Event::Ingest(Ingest {\n ts,\n@@ -47,7 +54,7 @@ fn reducer_external_namespace_ranking() {\n let g = &content.ranking_group;\n assert_eq!(g.idx_to_item.len(), 2);\n \n- let parent = slugsocial_server::path_types::CanonicalItemUrl::parse(\"https://github.com/iss\").unwrap();\n+ let parent = slugsocial_server::path_types::ItemId::parse(\"https://github.com/iss\").unwrap();\n let children = slugsocial_server::scope_rank::build_children_rankings(content, &parent);\n assert_eq!(children.component_rankings.len(), 1);\n let names: Vec<&str> = children.component_rankings[0]\n@@ -77,9 +84,9 @@ fn reducer_and_ranking_linear_chain() {\n let mut group = state.public().ranking_group.clone();\n let ranked = ranked_items(&mut group, 20000, 1e-9);\n assert_eq!(ranked.len(), 3);\n- assert_eq!(ranked[0].item, \"https://slug.social/~/t/a\");\n- assert_eq!(ranked[1].item, \"https://slug.social/~/t/b\");\n- assert_eq!(ranked[2].item, \"https://slug.social/~/t/c\");\n+ assert_eq!(ranked[0].item.as_str(), \"https://slug.social/~/t/a\");\n+ assert_eq!(ranked[1].item.as_str(), \"https://slug.social/~/t/b\");\n+ assert_eq!(ranked[2].item.as_str(), \"https://slug.social/~/t/c\");\n }\n \n #[test]\n@@ -112,15 +119,15 @@ fn reducer_handles_item_and_body_from_ingest() {\n ));\n \n let content = state.public();\n- assert!(content.items.contains(\"https://slug.social/~/t/test-item\"));\n+ assert!(content.items.contains(&item_id(\"https://slug.social/~/t/test-item\")));\n assert_eq!(\n- content.item_bodies.get(\"https://slug.social/~/t/test-item\"),\n+ content.item_bodies.get(&item_id(\"https://slug.social/~/t/test-item\")),\n Some(&\"Description here\".to_string())\n );\n assert!(content\n .item_children\n- .get(\"https://slug.social/~/t\")\n- .map(|c| c.contains(\"https://slug.social/~/t/test-item\"))\n+ .get(&item_id(\"https://slug.social/~/t\"))\n+ .map(|c| c.contains(&item_id(\"https://slug.social/~/t/test-item\")))\n .unwrap_or(false));\n }\n \n@@ -136,12 +143,12 @@ fn reducer_indexes_item_threads_and_vote_thread() {\n state.apply_event(Event::Ingest(ev));\n \n let content = state.public();\n- let threads_for_insertion = content.item_threads.get(\"https://slug.social/~/sorts/insertion\").unwrap();\n+ let threads_for_insertion = content.item_threads.get(&item_id(\"https://slug.social/~/sorts/insertion\")).unwrap();\n assert!(threads_for_insertion.contains(\"sorting-hat\"));\n- let threads_for_mergesort = content.item_threads.get(\"https://slug.social/~/sorts/mergesort\").unwrap();\n+ let threads_for_mergesort = content.item_threads.get(&item_id(\"https://slug.social/~/sorts/mergesort\")).unwrap();\n assert!(threads_for_mergesort.contains(\"sorting-hat\"));\n \n- let vote = content.item_votes.get(\"https://slug.social/~/sorts/insertion\").unwrap().front().unwrap();\n+ let vote = content.item_votes.get(&item_id(\"https://slug.social/~/sorts/insertion\")).unwrap().front().unwrap();\n assert_eq!(vote.thread_tag, \"sorting-hat\");\n }\n \n@@ -155,8 +162,8 @@ fn reducer_aggregates_multiple_votes() {\n }\n \n let group = &state.public().ranking_group;\n- let a_idx = group.item_to_idx[\"https://slug.social/~/t/a\"];\n- let b_idx = group.item_to_idx[\"https://slug.social/~/t/b\"];\n+ let a_idx = group.item_to_idx[&item_id(\"https://slug.social/~/t/a\")];\n+ let b_idx = group.item_to_idx[&item_id(\"https://slug.social/~/t/b\")];\n \n // Should have accumulated edge weights in both directions.\n assert!(group.edges.contains_key(&(a_idx, b_idx)));\n@@ -232,7 +239,7 @@ fn ranking_dominant_item_wins() {\n let mut group = state.public().ranking_group.clone();\n let ranked = ranked_items(&mut group, 20000, 1e-9);\n \n- assert_eq!(ranked[0].item, \"https://slug.social/~/t/champion\");\n+ assert_eq!(ranked[0].item.as_str(), \"https://slug.social/~/t/champion\");\n assert!(ranked[0].score > ranked[1].score);\n }\n \n@@ -379,7 +386,7 @@ async fn full_workflow_reducer_and_ranking() {\n let ranked = ranked_items(&mut group, 20000, 1e-9);\n \n assert_eq!(ranked.len(), 2);\n- assert_eq!(ranked[0].item, \"https://slug.social/~/langs/rust\"); // Should win\n+ assert_eq!(ranked[0].item.as_str(), \"https://slug.social/~/langs/rust\"); // Should win\n assert!(ranked[0].score > ranked[1].score);\n }\n \n@@ -395,27 +402,27 @@ fn reducer_materializes_ancestor_path_segments() {\n \n // The intermediate path \"https://slug.social/~/ai-models/anthropic\" should appear as a child of \"https://slug.social/~/ai-models\".\n let content = state.public();\n- let ai_models_children = content.item_children.get(\"https://slug.social/~/ai-models\").expect(\"ai-models should have children\");\n+ let ai_models_children = content.item_children.get(&item_id(\"https://slug.social/~/ai-models\")).expect(\"ai-models should have children\");\n assert!(\n- ai_models_children.contains(\"https://slug.social/~/ai-models/anthropic\"),\n+ ai_models_children.contains(&item_id(\"https://slug.social/~/ai-models/anthropic\")),\n \"ai-models/anthropic should be a child of ai-models\"\n );\n \n // The leaf items should still be children of \"https://slug.social/~/ai-models/anthropic\".\n- let anthropic_children = content.item_children.get(\"https://slug.social/~/ai-models/anthropic\").expect(\"ai-models/anthropic should have children\");\n- assert!(anthropic_children.contains(\"https://slug.social/~/ai-models/anthropic/claude-opus\"));\n- assert!(anthropic_children.contains(\"https://slug.social/~/ai-models/anthropic/claude-sonnet\"));\n+ let anthropic_children = content.item_children.get(&item_id(\"https://slug.social/~/ai-models/anthropic\")).expect(\"ai-models/anthropic should have children\");\n+ assert!(anthropic_children.contains(&item_id(\"https://slug.social/~/ai-models/anthropic/claude-opus\")));\n+ assert!(anthropic_children.contains(&item_id(\"https://slug.social/~/ai-models/anthropic/claude-sonnet\")));\n \n // Root should contain \"https://slug.social/~/ai-models\".\n- let root_children = content.item_children.get(\"https://slug.social/~\").expect(\"root should have children\");\n- assert!(root_children.contains(\"https://slug.social/~/ai-models\"));\n+ let root_children = content.item_children.get(&item_id(\"https://slug.social/~\")).expect(\"root should have children\");\n+ assert!(root_children.contains(&item_id(\"https://slug.social/~/ai-models\")));\n \n // The phantom intermediates should NOT be in the items set (they weren't explicitly created).\n- assert!(!content.items.contains(\"https://slug.social/~/ai-models\"));\n- assert!(!content.items.contains(\"https://slug.social/~/ai-models/anthropic\"));\n+ assert!(!content.items.contains(&item_id(\"https://slug.social/~/ai-models\")));\n+ assert!(!content.items.contains(&item_id(\"https://slug.social/~/ai-models/anthropic\")));\n // But the leaf items should be.\n- assert!(content.items.contains(\"https://slug.social/~/ai-models/anthropic/claude-opus\"));\n- assert!(content.items.contains(\"https://slug.social/~/ai-models/anthropic/claude-sonnet\"));\n+ assert!(content.items.contains(&item_id(\"https://slug.social/~/ai-models/anthropic/claude-opus\")));\n+ assert!(content.items.contains(&item_id(\"https://slug.social/~/ai-models/anthropic/claude-sonnet\")));\n }\n \n #[test]\n@@ -469,9 +476,9 @@ fn ranking_repeated_votes_normalized() {\n \n // Same winner regardless of how many times voted.\n assert_eq!(ranked_once[0].item, ranked_many[0].item);\n- assert_eq!(ranked_once[0].item, \"https://slug.social/~/norm/a\");\n+ assert_eq!(ranked_once[0].item.as_str(), \"https://slug.social/~/norm/a\");\n assert_eq!(ranked_once[1].item, ranked_many[1].item);\n- assert_eq!(ranked_once[1].item, \"https://slug.social/~/norm/b\");\n+ assert_eq!(ranked_once[1].item.as_str(), \"https://slug.social/~/norm/b\");\n \n // Scores should be identical (normalization makes repeated votes idempotent).\n let eps = 1e-6;\n@@ -506,8 +513,8 @@ fn reducer_zero_zero_vote_ratio_normalizes_to_one_one() {\n \"~/t/a {a}\\n~/t/b {b}\\n~/t/a 0:0 ~/t/b {zero}\\n\",\n ));\n let group = &state.public().ranking_group;\n- let a_idx = group.item_to_idx[\"https://slug.social/~/t/a\"];\n- let b_idx = group.item_to_idx[\"https://slug.social/~/t/b\"];\n+ let a_idx = group.item_to_idx[&item_id(\"https://slug.social/~/t/a\")];\n+ let b_idx = group.item_to_idx[&item_id(\"https://slug.social/~/t/b\")];\n // 0:0 should normalize to 1:1 — both directions should have weight\n assert!(group.edges.contains_key(&(a_idx, b_idx)));\n assert!(group.edges.contains_key(&(b_idx, a_idx)));\n@@ -523,8 +530,8 @@ fn reducer_negative_ratio_clamped_to_zero() {\n let mut group = GroupState::new();\n group.apply_vote(slugsocial_server::reducer::VoteData {\n ts: 1,\n- a: slugsocial_server::path_types::CanonicalItemUrl(\"https://slug.social/~/t/a\".to_string()),\n- b: slugsocial_server::path_types::CanonicalItemUrl(\"https://slug.social/~/t/b\".to_string()),\n+ a: slugsocial_server::path_types::ItemId::parse(\"https://slug.social/~/t/a\").unwrap(),\n+ b: slugsocial_server::path_types::ItemId::parse(\"https://slug.social/~/t/b\").unwrap(),\n ratio_left: -5,\n ratio_right: -3,\n body: \"negative\".to_string(),\n@@ -534,8 +541,8 @@ fn reducer_negative_ratio_clamped_to_zero() {\n });\n assert_eq!(group.idx_to_item.len(), 2);\n // Both edges should exist (negatives clamped to 0, then 0:0 -> 1:1)\n- let a_idx = group.item_to_idx[\"https://slug.social/~/t/a\"];\n- let b_idx = group.item_to_idx[\"https://slug.social/~/t/b\"];\n+ let a_idx = group.item_to_idx[&item_id(\"https://slug.social/~/t/a\")];\n+ let b_idx = group.item_to_idx[&item_id(\"https://slug.social/~/t/b\")];\n assert!(group.edges.contains_key(&(a_idx, b_idx)));\n assert!(group.edges.contains_key(&(b_idx, a_idx)));\n }\n@@ -553,24 +560,24 @@ fn reducer_deep_path_ancestor_materialization_four_levels() {\n let content = state.public();\n let tilde_scope = content\n .item_children\n- .get(\"https://slug.social/~\")\n+ .get(&item_id(\"https://slug.social/~\"))\n .expect(\"~/ scope should have children\");\n- assert!(tilde_scope.contains(\"https://slug.social/~/a\"));\n+ assert!(tilde_scope.contains(&item_id(\"https://slug.social/~/a\")));\n \n- let a_children = content.item_children.get(\"https://slug.social/~/a\").expect(\"a should have children\");\n- assert!(a_children.contains(\"https://slug.social/~/a/b\"));\n+ let a_children = content.item_children.get(&item_id(\"https://slug.social/~/a\")).expect(\"a should have children\");\n+ assert!(a_children.contains(&item_id(\"https://slug.social/~/a/b\")));\n \n- let ab_children = content.item_children.get(\"https://slug.social/~/a/b\").expect(\"a/b should have children\");\n- assert!(ab_children.contains(\"https://slug.social/~/a/b/c\"));\n+ let ab_children = content.item_children.get(&item_id(\"https://slug.social/~/a/b\")).expect(\"a/b should have children\");\n+ assert!(ab_children.contains(&item_id(\"https://slug.social/~/a/b/c\")));\n \n- let abc_children = content.item_children.get(\"https://slug.social/~/a/b/c\").expect(\"a/b/c should have children\");\n- assert!(abc_children.contains(\"https://slug.social/~/a/b/c/d\"));\n+ let abc_children = content.item_children.get(&item_id(\"https://slug.social/~/a/b/c\")).expect(\"a/b/c should have children\");\n+ assert!(abc_children.contains(&item_id(\"https://slug.social/~/a/b/c/d\")));\n \n // Only the leaf should be in items set\n- assert!(content.items.contains(\"https://slug.social/~/a/b/c/d\"));\n- assert!(!content.items.contains(\"https://slug.social/~/a\"));\n- assert!(!content.items.contains(\"https://slug.social/~/a/b\"));\n- assert!(!content.items.contains(\"https://slug.social/~/a/b/c\"));\n+ assert!(content.items.contains(&item_id(\"https://slug.social/~/a/b/c/d\")));\n+ assert!(!content.items.contains(&item_id(\"https://slug.social/~/a\")));\n+ assert!(!content.items.contains(&item_id(\"https://slug.social/~/a/b\")));\n+ assert!(!content.items.contains(&item_id(\"https://slug.social/~/a/b/c\")));\n }\n \n // ============================================================================\n@@ -610,7 +617,7 @@ fn ranking_convergence_tolerance_triggers_early_exit() {\n // Very tight tolerance but huge max_iters — should still converge fast\n let ranked = ranked_items(&mut group, 1_000_000, 1e-15);\n assert_eq!(ranked.len(), 2);\n- assert_eq!(ranked[0].item, \"https://slug.social/~/t/a\");\n+ assert_eq!(ranked[0].item.as_str(), \"https://slug.social/~/t/a\");\n }\n \n // ============================================================================\n@@ -624,14 +631,14 @@ fn test_item_body_overwrite() {\n 1,\n \"~/t/x {first}\\n\",\n ));\n- assert_eq!(state.public().item_bodies.get(\"https://slug.social/~/t/x\"), Some(&\"first\".to_string()));\n+ assert_eq!(state.public().item_bodies.get(&item_id(\"https://slug.social/~/t/x\")), Some(&\"first\".to_string()));\n \n state.apply_event(ingest_event(\n 2,\n \"~/t/x {second}\\n\",\n ));\n assert_eq!(\n- state.public().item_bodies.get(\"https://slug.social/~/t/x\"),\n+ state.public().item_bodies.get(&item_id(\"https://slug.social/~/t/x\")),\n Some(&\"second\".to_string()),\n \"last writer should win for item bodies\"\n );\n@@ -645,9 +652,9 @@ fn test_empty_body_not_stored() {\n \"~/t/blank { }\\n\",\n ));\n let content = state.public();\n- assert!(content.items.contains(\"https://slug.social/~/t/blank\"), \"item should exist\");\n+ assert!(content.items.contains(&item_id(\"https://slug.social/~/t/blank\")), \"item should exist\");\n assert!(\n- !content.item_bodies.contains_key(\"https://slug.social/~/t/blank\"),\n+ !content.item_bodies.contains_key(&item_id(\"https://slug.social/~/t/blank\")),\n \"whitespace-only body should not be stored\"\n );\n }\n@@ -664,7 +671,7 @@ fn test_duplicate_items_across_ingests() {\n \"~/t/dup {second}\\n\",\n ));\n let content = state.public();\n- let count = content.items.iter().filter(|i| *i == \"https://slug.social/~/t/dup\").count();\n+ let count = content.items.iter().filter(|i| i.as_str() == \"https://slug.social/~/t/dup\").count();\n assert_eq!(count, 1, \"items set should deduplicate across ingests\");\n }\n \n@@ -736,7 +743,7 @@ fn test_thread_id_is_used_for_votes_and_indexes() {\n let content = state.public();\n let vote = content\n .item_votes\n- .get(\"https://slug.social/~/t/a\")\n+ .get(&item_id(\"https://slug.social/~/t/a\"))\n .unwrap()\n .front()\n .unwrap();\n@@ -745,7 +752,7 @@ fn test_thread_id_is_used_for_votes_and_indexes() {\n assert!(state\n .public()\n .item_threads\n- .get(\"https://slug.social/~/t/a\")\n+ .get(&item_id(\"https://slug.social/~/t/a\"))\n .is_some_and(|threads| threads.contains(\"first\")));\n }\n \n@@ -757,11 +764,11 @@ fn test_rank_history_created_for_voted_items() {\n \"~/t/a {a}\\n~/t/b {b}\\n~/t/a 3:1 ~/t/b {reason}\\n\",\n ));\n assert!(\n- state.public().rank_history.contains_key(\"https://slug.social/~/t/a\"),\n+ state.public().rank_history.contains_key(&item_id(\"https://slug.social/~/t/a\")),\n \"rank_history should have entry for voted item a\"\n );\n assert!(\n- state.public().rank_history.contains_key(\"https://slug.social/~/t/b\"),\n+ state.public().rank_history.contains_key(&item_id(\"https://slug.social/~/t/b\")),\n \"rank_history should have entry for voted item b\"\n );\n }\n@@ -774,7 +781,7 @@ fn test_rank_history_not_created_for_unvoted_items() {\n \"~/t/c {just a definition}\\n\",\n ));\n assert!(\n- !state.public().rank_history.contains_key(\"https://slug.social/~/t/c\"),\n+ !state.public().rank_history.contains_key(&item_id(\"https://slug.social/~/t/c\")),\n \"rank_history should NOT have entry for item with no votes\"\n );\n }\n@@ -786,7 +793,7 @@ fn test_rank_history_first_entry_delta_zero() {\n 1,\n \"~/t/a {a}\\n~/t/b {b}\\n~/t/a 3:1 ~/t/b {reason}\\n\",\n ));\n- let history_a = state.public().rank_history.get(\"https://slug.social/~/t/a\").unwrap();\n+ let history_a = state.public().rank_history.get(&item_id(\"https://slug.social/~/t/a\")).unwrap();\n assert_eq!(history_a.len(), 1);\n assert_eq!(\n history_a[0].scope_rank_delta, 0,\ndiff --git a/types/src/item_id.rs b/types/src/item_id.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..5fe9fad39c0d58e546c0a0162eba4348d64e0865\n--- /dev/null\n+++ b/types/src/item_id.rs\n@@ -0,0 +1,225 @@\n+//! Structural item identity for the reducer graph and ranking (vs presentation-only strings).\n+\n+use std::cmp::Ordering;\n+use std::fmt;\n+\n+use serde::{Deserialize, Deserializer, Serialize, Serializer};\n+\n+use crate::item_wire::{\n+ canonicalize_item, external_display_dash_prefix, normalize_slug_ontology_storage_url,\n+ SLUG_TILDE_ONTOLOGY_ROOT,\n+};\n+\n+/// Structural key for items in [`slug_types`] and the server reducer.\n+///\n+/// Wire / JSON uses the same single string as the former canonical item URL (via serde).\n+#[derive(Debug, Clone, Hash, PartialEq, Eq)]\n+pub enum ItemId {\n+ /// Tilde ontology root (`~/`); storage [`SLUG_TILDE_ONTOLOGY_ROOT`].\n+ Root,\n+ /// `https://slug.social/~/…` (non-root; normalized trailing path).\n+ Local(String),\n+ /// Normalized `http(s)://…` storage form, including non-`~/` paths on `slug.social`.\n+ Web(String),\n+ /// Raw key material that did not round-trip through [`Self::parse`] (historical edge case).\n+ Opaque(String),\n+}\n+\n+impl ItemId {\n+ pub fn parse(input: &str) -> Option {\n+ let c = normalize_slug_ontology_storage_url(&canonicalize_item(input));\n+ if c.is_empty() {\n+ return None;\n+ }\n+ if c == SLUG_TILDE_ONTOLOGY_ROOT {\n+ return Some(Self::Root);\n+ }\n+ if c.starts_with(\"https://slug.social/~/\") && c != SLUG_TILDE_ONTOLOGY_ROOT {\n+ return Some(Self::Local(c));\n+ }\n+ Some(Self::Web(c))\n+ }\n+\n+ /// Same as the old `ensure_item` fallback: use `s` verbatim as the map key.\n+ pub fn opaque(raw: String) -> Self {\n+ Self::Opaque(raw)\n+ }\n+\n+ pub fn ontology_root() -> Self {\n+ Self::Root\n+ }\n+\n+ /// Collapses legacy slug ontology root spellings so [`std::collections::HashMap`] keys match the graph.\n+ pub fn normalized_storage(self) -> Self {\n+ Self::parse(self.as_str()).unwrap_or(self)\n+ }\n+\n+ pub fn as_str(&self) -> &str {\n+ match self {\n+ ItemId::Root => SLUG_TILDE_ONTOLOGY_ROOT,\n+ ItemId::Local(s) | ItemId::Web(s) | ItemId::Opaque(s) => s,\n+ }\n+ }\n+\n+ pub fn to_storage_string(&self) -> String {\n+ self.as_str().to_string()\n+ }\n+\n+ pub fn tilde_tail(&self) -> Option<&str> {\n+ match self {\n+ ItemId::Root => Some(\"\"),\n+ ItemId::Local(s) => s.strip_prefix(\"https://slug.social/~/\"),\n+ ItemId::Web(s) | ItemId::Opaque(s) => {\n+ if let Some(tail) = s.strip_prefix(\"https://slug.social/~/\") {\n+ return Some(tail);\n+ }\n+ if s == SLUG_TILDE_ONTOLOGY_ROOT || s == \"https://slug.social/~/\" {\n+ return Some(\"\");\n+ }\n+ None\n+ }\n+ }\n+ }\n+\n+ /// HTTP garden tail after `~/` (empty at ontology root), or `None` if not under tilde ontology.\n+ pub fn tilde_http_tail(&self) -> Option {\n+ self.tilde_tail().map(str::to_owned)\n+ }\n+\n+ pub fn last_segment(&self) -> &str {\n+ let s = self.as_str();\n+ s.rsplit('/').find(|x| !x.is_empty()).unwrap_or(s)\n+ }\n+\n+ pub fn parent(&self) -> Option {\n+ match self {\n+ ItemId::Root => None,\n+ ItemId::Local(s) => {\n+ if s == SLUG_TILDE_ONTOLOGY_ROOT || s == \"https://slug.social/~/\" {\n+ return None;\n+ }\n+ let last_slash = s.rfind('/')?;\n+ let parent_str = &s[..last_slash];\n+ if parent_str.is_empty() {\n+ None\n+ } else {\n+ Self::parse(parent_str)\n+ }\n+ }\n+ ItemId::Web(s) | ItemId::Opaque(s) => {\n+ if s == SLUG_TILDE_ONTOLOGY_ROOT || s == \"https://slug.social/~/\" {\n+ return None;\n+ }\n+ if let Some(rest) = s.strip_prefix(\"https://slug.social/~/\") {\n+ if rest.is_empty() {\n+ return None;\n+ }\n+ let last_slash = s.rfind('/')?;\n+ let parent_str = &s[..last_slash];\n+ Self::parse(parent_str)\n+ } else if s.starts_with(\"https://\") {\n+ let rest = s.strip_prefix(\"https://\").unwrap();\n+ Self::parent_http_url(\"https://\", rest)\n+ } else if s.starts_with(\"http://\") {\n+ let rest = s.strip_prefix(\"http://\").unwrap();\n+ Self::parent_http_url(\"http://\", rest)\n+ } else {\n+ None\n+ }\n+ }\n+ }\n+ }\n+\n+ fn parent_http_url(scheme: &'static str, rest: &str) -> Option {\n+ let (host, path) = rest.split_once('/').map_or((rest, \"\"), |(h, p)| (h, p));\n+ let host = host.trim();\n+ let path = path.trim_end_matches('/');\n+ if path.is_empty() {\n+ return None;\n+ }\n+ let parent_path = path.rsplit_once('/').map(|(p, _)| p).unwrap_or(\"\");\n+ if parent_path.is_empty() {\n+ Self::parse(&format!(\"{scheme}{}\", host))\n+ } else {\n+ Self::parse(&format!(\"{scheme}{}/{}\", host, parent_path))\n+ }\n+ }\n+\n+ /// `-/` representation for external `https://…` items, `~/…` for slug ontology, else unchanged.\n+ pub fn display_path(&self) -> String {\n+ if let Some(tail) = self.tilde_tail() {\n+ if tail.is_empty() {\n+ return \"~/\".to_string();\n+ }\n+ return format!(\"~/{}\", tail);\n+ }\n+ let s = self.as_str();\n+ if let Some(tail) = s.strip_prefix(\"https://\") {\n+ if tail.starts_with(\"slug.social\") {\n+ return s.to_string();\n+ }\n+ return external_display_dash_prefix(tail);\n+ }\n+ if let Some(tail) = s.strip_prefix(\"http://\") {\n+ if tail.starts_with(\"slug.social\") {\n+ return s.to_string();\n+ }\n+ return external_display_dash_prefix(tail);\n+ }\n+ s.to_string()\n+ }\n+\n+ pub fn tilde_segments(&self) -> Vec<&str> {\n+ match self.tilde_tail() {\n+ Some(tail) if !tail.is_empty() => std::iter::once(\"~\")\n+ .chain(tail.split('/').filter(|s| !s.is_empty()))\n+ .collect(),\n+ Some(_) => vec![\"~\"],\n+ None => vec![],\n+ }\n+ }\n+\n+ /// Normalized URL string for HTTP fetch boundaries (external identities).\n+ pub fn to_wire_url(&self) -> String {\n+ self.to_storage_string()\n+ }\n+}\n+\n+impl PartialOrd for ItemId {\n+ fn partial_cmp(&self, other: &Self) -> Option {\n+ Some(self.cmp(other))\n+ }\n+}\n+\n+impl Ord for ItemId {\n+ fn cmp(&self, other: &Self) -> Ordering {\n+ self.as_str().cmp(other.as_str())\n+ }\n+}\n+\n+impl fmt::Display for ItemId {\n+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n+ self.as_str().fmt(f)\n+ }\n+}\n+\n+impl Serialize for ItemId {\n+ fn serialize(&self, serializer: S) -> Result\n+ where\n+ S: Serializer,\n+ {\n+ self.as_str().serialize(serializer)\n+ }\n+}\n+\n+impl<'de> Deserialize<'de> for ItemId {\n+ fn deserialize(deserializer: D) -> Result\n+ where\n+ D: Deserializer<'de>,\n+ {\n+ let s = String::deserialize(deserializer)?;\n+ ItemId::parse(&s).ok_or_else(|| {\n+ serde::de::Error::custom(format!(\"invalid item id: {s:?}\"))\n+ })\n+ }\n+}\ndiff --git a/types/src/item_wire.rs b/types/src/item_wire.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..20e3e7df77a74713c146c7e7222a809173723c7d\n--- /dev/null\n+++ b/types/src/item_wire.rs\n@@ -0,0 +1,184 @@\n+//! Wire normalization for item identity strings (`canonicalize_item`, path segments).\n+//! Split from `paths` so [`crate::item_id::ItemId`] can depend on this without import cycles.\n+\n+use crate::url_normalize::{host_preserves_dash_path_case, normalize_http_identity_url};\n+\n+/// Canonical absolute URL for the tilde ontology **root** (`~/` in UI).\n+pub const SLUG_TILDE_ONTOLOGY_ROOT: &str = \"https://slug.social/~\";\n+\n+/// Collapse legacy or parser variants of the ontology root to [`SLUG_TILDE_ONTOLOGY_ROOT`].\n+pub fn normalize_slug_ontology_storage_url(s: &str) -> String {\n+ if s == \"https://slug.social/~/\" {\n+ SLUG_TILDE_ONTOLOGY_ROOT.to_string()\n+ } else {\n+ s.to_string()\n+ }\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+ if s.is_empty() {\n+ return String::new();\n+ }\n+\n+ if let Some(rest) = s.strip_prefix(\"-/\") {\n+ let (host, tail) = rest\n+ .split_once('/')\n+ .map_or((rest, \"\"), |(h, t)| (h, t));\n+ let host = host.trim().to_lowercase();\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+ finalize_external_identity_url(format!(\"https://{}\", host))\n+ } else {\n+ let path = tail\n+ .trim_start_matches('/')\n+ .trim_end_matches('/')\n+ .split('/')\n+ .filter_map(|seg| {\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+ 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+ return finalize_external_identity_url(if tail.is_empty() {\n+ format!(\"https://{}\", host)\n+ } else {\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+ return finalize_external_identity_url(if tail.is_empty() {\n+ format!(\"http://{}\", host)\n+ } else {\n+ 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+ if tail.is_empty() {\n+ return SLUG_TILDE_ONTOLOGY_ROOT.to_string();\n+ }\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+pub(crate) fn external_display_dash_prefix(host_and_path: &str) -> String {\n+ let (host, path) = host_and_path\n+ .split_once('/')\n+ .map_or((host_and_path, \"\"), |(h, p)| (h, p));\n+ let host = host.trim().to_lowercase();\n+ let path = path\n+ .trim_end_matches('/')\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+ if path.is_empty() {\n+ format!(\"-/{}\", host)\n+ } else {\n+ format!(\"-/{}\", format!(\"{}/{}\", host, path))\n+ }\n+}\ndiff --git a/types/src/lib.rs b/types/src/lib.rs\nindex ceaa574cd32b7e7eb397c9a3191fcbc037b8c606..05bcfcfbf48f1dc7a4c05e32055bd12eb5cfd623 100644\n--- a/types/src/lib.rs\n+++ b/types/src/lib.rs\n@@ -1,14 +1,20 @@\n use serde::{Deserialize, Serialize};\n \n pub mod url_normalize;\n+pub mod item_wire;\n+pub mod item_id;\n pub mod paths;\n pub mod timeago;\n \n+pub use item_id::ItemId;\n+pub use item_wire::{\n+ canonicalize_item, item_parent_path, item_path_segments, normalize_slug_ontology_storage_url,\n+ SLUG_TILDE_ONTOLOGY_ROOT,\n+};\n pub use paths::{\n- canonicalize_item, canonicalize_tag, item_parent_path, item_path_segments, normalize_slug_ontology_storage_url,\n- CanonicalItemUrl, ForumThreadUrl, GardenItemUrl, RelativePath, SLUG_TILDE_ONTOLOGY_ROOT,\n+ canonicalize_tag, ForumThreadUrl, GardenItemUrl, RelativePath,\n room_id_from_route_segment, room_route_segment, ROOM_SHORT_ID_LEN,\n- TildeHttpPathTail, TildeOntologyPath, TildePath, tilde_http_path_to_canonical,\n+ TildeHttpPathTail, TildeOntologyPath, TildePath, tilde_http_path_to_item_id,\n };\n pub use url_normalize::normalize_http_identity_url;\n \ndiff --git a/types/src/paths.rs b/types/src/paths.rs\nindex 5c60e762c2ca74d79c74237097d5bcc02ba74af2..a1d066d83e7fbcefc27707dd682e54dbcec1cc56 100644\n--- a/types/src/paths.rs\n+++ b/types/src/paths.rs\n@@ -3,37 +3,23 @@\n //!\n //! ## String kinds (parse in this module only)\n //!\n-//! - **[`canonicalize_item`] / [`CanonicalItemUrl`]** — graph storage key and DSL form; tilde\n+//! - **[`canonicalize_item`] / [`crate::ItemId`]** — 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/{short}{slug}/~/…` (the `*path` segment).\n //! - **`-/…` wire form** — external items; see [`canonicalize_item`] dash branch.\n //! - **[`GardenItemUrl`], [`ForumThreadUrl`]** — JSON / browser href surfaces.\n //! - **[`ROOM_SHORT_ID_LEN`] / [`room_route_segment`]** — `/r/{short}{slug}` vs wire `short/slug`.\n \n-use std::borrow::Borrow;\n use std::fmt;\n use std::ops::Deref;\n \n use serde::{Deserialize, Serialize};\n \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-\n-/// Canonical absolute URL for the tilde ontology **root** (`~/` in UI). Used as the\n-/// `item_children` parent key for top-level items and must match [`CanonicalItemUrl::ontology_root`].\n-pub const SLUG_TILDE_ONTOLOGY_ROOT: &str = \"https://slug.social/~\";\n-\n-/// Collapse legacy or parser variants of the ontology root to [`SLUG_TILDE_ONTOLOGY_ROOT`].\n-pub fn normalize_slug_ontology_storage_url(s: &str) -> String {\n- if s == \"https://slug.social/~/\" {\n- SLUG_TILDE_ONTOLOGY_ROOT.to_string()\n- } else {\n- s.to_string()\n- }\n-}\n+use crate::item_id::ItemId;\n+pub use crate::item_wire::{\n+ canonicalize_item, item_parent_path, item_path_segments, normalize_slug_ontology_storage_url,\n+ SLUG_TILDE_ONTOLOGY_ROOT,\n+};\n \n // ---------------------------------------------------------------------------\n // Private room HTTP path (`/r/{short}{slug}`; wire id remains `short/slug`)\n@@ -84,310 +70,10 @@ 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- if s.is_empty() {\n- return String::new();\n- }\n-\n- // External scope: `-/host/path` is the universal alias for `https://host/path`.\n- if let Some(rest) = s.strip_prefix(\"-/\") {\n- let (host, tail) = rest\n- .split_once('/')\n- .map_or((rest, \"\"), |(h, t)| (h, t));\n- let host = host.trim().to_lowercase();\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- finalize_external_identity_url(format!(\"https://{}\", host))\n- } else {\n- let path = tail\n- .trim_start_matches('/')\n- .trim_end_matches('/')\n- .split('/')\n- .filter_map(|seg| {\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- 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- return finalize_external_identity_url(if tail.is_empty() {\n- format!(\"https://{}\", host)\n- } else {\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- return finalize_external_identity_url(if tail.is_empty() {\n- format!(\"http://{}\", host)\n- } else {\n- 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- if tail.is_empty() {\n- return SLUG_TILDE_ONTOLOGY_ROOT.to_string();\n- }\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-fn external_display_dash_prefix(host_and_path: &str) -> String {\n- let (host, path) = host_and_path\n- .split_once('/')\n- .map_or((host_and_path, \"\"), |(h, p)| (h, p));\n- let host = host.trim().to_lowercase();\n- let path = path\n- .trim_end_matches('/')\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- if path.is_empty() {\n- format!(\"-/{}\", host)\n- } else {\n- format!(\"-/{}\", format!(\"{}/{}\", host, path))\n- }\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(normalize_slug_ontology_storage_url(&c)))\n- }\n- }\n-\n- pub fn as_str(&self) -> &str {\n- &self.0\n- }\n-\n- /// Collapses legacy slug ontology root spellings so [`HashMap`] keys match the reducer graph.\n- pub fn normalized_storage(self) -> Self {\n- Self(normalize_slug_ontology_storage_url(self.as_str()))\n- }\n-\n- pub fn tilde_tail(&self) -> Option<&str> {\n- if let Some(tail) = self.0.strip_prefix(\"https://slug.social/~/\") {\n- return Some(tail);\n- }\n- if self.0 == SLUG_TILDE_ONTOLOGY_ROOT || self.0 == \"https://slug.social/~/\" {\n- return Some(\"\");\n- }\n- None\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(SLUG_TILDE_ONTOLOGY_ROOT.to_string())\n- }\n-\n- pub fn parent(&self) -> Option {\n- if self.tilde_tail().is_some() {\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- } else if let Some(rest) = self.0.strip_prefix(\"https://\") {\n- Self::parent_http_url(\"https://\", rest)\n- } else if let Some(rest) = self.0.strip_prefix(\"http://\") {\n- Self::parent_http_url(\"http://\", rest)\n- } else {\n- None\n- }\n- }\n-\n- fn parent_http_url(scheme: &'static str, rest: &str) -> Option {\n- let (host, path) = rest.split_once('/').map_or((rest, \"\"), |(h, p)| (h, p));\n- let host = host.trim();\n- let path = path.trim_end_matches('/');\n- if path.is_empty() {\n- return None;\n- }\n- let parent_path = path.rsplit_once('/').map(|(p, _)| p).unwrap_or(\"\");\n- if parent_path.is_empty() {\n- Some(Self(format!(\"{scheme}{}\", host)))\n- } else {\n- Some(Self(format!(\"{scheme}{}/{}\", host, parent_path)))\n- }\n- }\n-\n- /// `-/` representation for external `https://…` items, `~/…` for slug ontology, else unchanged.\n- pub fn display_path(&self) -> String {\n- if let Some(tail) = self.tilde_tail() {\n- if tail.is_empty() {\n- return \"~/\".to_string();\n- }\n- return format!(\"~/{}\", tail);\n- }\n- if let Some(tail) = self.0.strip_prefix(\"https://\") {\n- if tail.starts_with(\"slug.social\") {\n- self.0.clone()\n- } else {\n- external_display_dash_prefix(tail)\n- }\n- } else if let Some(tail) = self.0.strip_prefix(\"http://\") {\n- if tail.starts_with(\"slug.social\") {\n- self.0.clone()\n- } else {\n- external_display_dash_prefix(tail)\n- }\n- } else {\n- self.0.clone()\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 /// 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@@ -401,13 +87,13 @@ impl TildeHttpPathTail {\n &self.0\n }\n \n- pub fn to_canonical(&self) -> CanonicalItemUrl {\n- tilde_http_path_to_canonical(self.as_str())\n+ pub fn to_item_id(&self) -> ItemId {\n+ tilde_http_path_to_item_id(self.as_str())\n }\n }\n \n-/// Map the router's tilde tail (e.g. `topic/a`, or empty for root) to a [`CanonicalItemUrl`].\n-pub fn tilde_http_path_to_canonical(path_segment: &str) -> CanonicalItemUrl {\n+/// Map the router's tilde tail (e.g. `topic/a`, or empty for root) to an [`ItemId`].\n+pub fn tilde_http_path_to_item_id(path_segment: &str) -> ItemId {\n let p = path_segment.trim_start_matches('/');\n let raw = if p.starts_with(\"http://\") || p.starts_with(\"https://\") {\n p.to_string()\n@@ -416,37 +102,7 @@ pub fn tilde_http_path_to_canonical(path_segment: &str) -> CanonicalItemUrl {\n } else {\n format!(\"~/{}\", p)\n };\n- CanonicalItemUrl::parse(&raw).unwrap_or_else(|| CanonicalItemUrl::ontology_root())\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+ ItemId::parse(&raw).unwrap_or_else(ItemId::ontology_root)\n }\n \n #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]\n@@ -468,8 +124,8 @@ impl TildePath {\n &self.0\n }\n \n- pub fn canonicalize(&self) -> Option {\n- CanonicalItemUrl::parse(&self.0)\n+ pub fn canonicalize(&self) -> Option {\n+ ItemId::parse(&self.0)\n }\n }\n \n@@ -496,7 +152,7 @@ impl RelativePath {\n &self.0\n }\n \n- pub fn join_under_ontology_root(&self, root: &CanonicalItemUrl) -> Option {\n+ pub fn join_under_ontology_root(&self, root: &ItemId) -> Option {\n let base = root.tilde_tail()?;\n let joined = if base.is_empty() {\n if self.0.is_empty() {\n@@ -509,7 +165,7 @@ impl RelativePath {\n } else {\n format!(\"~/{}/{}\", base.trim_end_matches('/'), self.0)\n };\n- CanonicalItemUrl::parse(&joined)\n+ ItemId::parse(&joined)\n }\n }\n \n@@ -545,14 +201,17 @@ impl GardenItemUrl {\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+ /// Stored item id + RPC `room` field (`\"public\"` or `\"short/slug\"`).\n+ pub fn from_stored(stored: &ItemId, room_wire: &str) -> Self {\n+ Self(garden_href_string(stored, 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+ let Some(id) = ItemId::parse(stored) else {\n+ return Self(api_path_or_url(stored));\n+ };\n+ Self(garden_href_string(&id, room_wire))\n }\n }\n \n@@ -570,18 +229,15 @@ impl Deref for GardenItemUrl {\n }\n }\n \n-fn garden_href_string(item: &str, room_wire: &str) -> String {\n+fn garden_href_string(c: &ItemId, 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+ return api_path_or_url(c.as_str());\n }\n let Some(room_seg) = room_route_segment(room) else {\n- return api_path_or_url(item);\n- };\n- let Some(c) = CanonicalItemUrl::parse(item) else {\n- return api_path_or_url(item);\n+ return api_path_or_url(c.as_str());\n };\n- let root = CanonicalItemUrl::ontology_root();\n+ let root = ItemId::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@@ -600,7 +256,7 @@ fn garden_href_string(item: &str, room_wire: &str) -> String {\n let tail = tail.strip_prefix(\"-/\").unwrap_or(tail.as_str());\n return format!(\"https://slug.social/r/{room_seg}/-/{tail}\");\n }\n- api_path_or_url(item)\n+ api_path_or_url(c.as_str())\n }\n \n /// Forum thread URL for JSON (`/t/…` or `/r/…/t/…` on slug.social).\n@@ -650,7 +306,7 @@ impl Deref for ForumThreadUrl {\n pub struct TildeOntologyPath(pub String);\n \n impl TildeOntologyPath {\n- pub fn from_stored(c: &CanonicalItemUrl) -> Self {\n+ pub fn from_stored(c: &ItemId) -> Self {\n Self(c.display_path())\n }\n \n@@ -679,22 +335,22 @@ mod tests {\n \n #[test]\n fn canonical_parent_deep() {\n- let c = CanonicalItemUrl::parse(\"~/a/b/c\").unwrap();\n+ let c = ItemId::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+ let c = ItemId::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+ let root = ItemId::parse(\"~/\").unwrap();\n assert!(root.parent().is_none());\n assert_eq!(root.as_str(), SLUG_TILDE_ONTOLOGY_ROOT);\n- assert_eq!(root, CanonicalItemUrl::ontology_root());\n+ assert_eq!(root, ItemId::ontology_root());\n }\n \n #[test]\n@@ -705,49 +361,49 @@ mod tests {\n SLUG_TILDE_ONTOLOGY_ROOT.to_string()\n );\n assert_eq!(\n- CanonicalItemUrl::parse(\"https://slug.social/~/\")\n+ ItemId::parse(\"https://slug.social/~/\")\n .unwrap()\n .as_str(),\n SLUG_TILDE_ONTOLOGY_ROOT\n );\n- let legacy = CanonicalItemUrl(\"https://slug.social/~/\".to_string());\n+ let legacy = ItemId::opaque(\"https://slug.social/~/\".to_string());\n assert_eq!(legacy.normalized_storage().as_str(), SLUG_TILDE_ONTOLOGY_ROOT);\n }\n \n #[test]\n fn tilde_http_path_tail_maps_router_segment() {\n assert_eq!(\n- TildeHttpPathTail::new(\"\").to_canonical(),\n- CanonicalItemUrl::ontology_root()\n+ TildeHttpPathTail::new(\"\").to_item_id(),\n+ ItemId::ontology_root()\n );\n assert_eq!(\n- tilde_http_path_to_canonical(\"topic/x\").as_str(),\n+ tilde_http_path_to_item_id(\"topic/x\").as_str(),\n \"https://slug.social/~/topic/x\"\n );\n }\n \n #[test]\n fn display_path_slug_ontology_root() {\n- let r = CanonicalItemUrl::ontology_root();\n+ let r = ItemId::ontology_root();\n assert_eq!(r.display_path(), \"~/\");\n assert_eq!(r.tilde_tail(), Some(\"\"));\n }\n \n #[test]\n fn tilde_segments_deep() {\n- let c = CanonicalItemUrl::parse(\"~/a/b\").unwrap();\n+ let c = ItemId::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+ let c = ItemId::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+ let c = ItemId::parse(\"https://example.com/foo\").unwrap();\n assert_eq!(c.tilde_segments(), Vec::<&str>::new());\n }\n \n@@ -831,28 +487,28 @@ mod tests {\n }\n \n #[test]\n- fn canonical_item_url_parent_external_strips_last_segment() {\n- let c = CanonicalItemUrl::parse(\"https://spotify.com/track/1\").unwrap();\n+ fn item_id_parent_external_strips_last_segment() {\n+ let c = ItemId::parse(\"https://spotify.com/track/1\").unwrap();\n assert_eq!(\n c.parent().unwrap().as_str(),\n \"https://spotify.com/track\"\n );\n assert_eq!(\n- CanonicalItemUrl::parse(\"https://github.com/iss/1\")\n+ ItemId::parse(\"https://github.com/iss/1\")\n .unwrap()\n .parent()\n .unwrap()\n .as_str(),\n \"https://github.com/iss\"\n );\n- assert!(CanonicalItemUrl::parse(\"https://github.com\").unwrap().parent().is_none());\n+ assert!(ItemId::parse(\"https://github.com\").unwrap().parent().is_none());\n }\n \n #[test]\n fn display_path_roundtrips_dash_and_tilde() {\n- let ext = CanonicalItemUrl::parse(\"https://GitHub.com/org/Issue\").unwrap();\n+ let ext = ItemId::parse(\"https://GitHub.com/org/Issue\").unwrap();\n assert_eq!(ext.display_path(), \"-/github.com/org/issue\");\n- let tilde = CanonicalItemUrl::parse(\"~/Rust/Doc\").unwrap();\n+ let tilde = ItemId::parse(\"~/Rust/Doc\").unwrap();\n assert_eq!(tilde.display_path(), \"~/rust/doc\");\n }\n \n\n\nSide B — contributor: tommy-mor\nSide B — commit message:\n[52f5c51c] Add Reddit OAuth linking and make UUID the only account identity.\n\nOAuth providers only attach to a session UUID (first link creates the\nprincipal); linked providers stay private on the account page.\n\nCo-authored-by: Cursor \n\nSide B — unified diff (full patch):\ndiff --git a/AGENTS.md b/AGENTS.md\nindex 6e0fd8ebb65d665c9c1438e3275971d62b98fd95..e9cc3173dbeb21ad0fc090ca7b407b027c7820a9 100644\n--- a/AGENTS.md\n+++ b/AGENTS.md\n@@ -35,8 +35,11 @@ Environment variables (defaults in `server/src/state.rs`):\n - `SORTER2_DATA_DIR` — default `./data` (created on startup)\n - `SORTER2_EVENT_LOG` — default `{data_dir}/events.jsonl`\n - `SORTER2_BASE_URL` — public origin (also drives Secure cookies when `https://`)\n-- `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET` — GitHub OAuth (optional; login disabled if unset)\n-- `SORTER2_ALLOW_MOCK_OAUTH=1` — allow `mock_user` on `/auth/github` (tests only)\n+- `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET` — GitHub OAuth linking (optional)\n+- `REDDIT_CLIENT_ID` / `REDDIT_CLIENT_SECRET` (or `REDDIT_APP_*`) — Reddit API import + OAuth linking (optional)\n+- `SORTER2_ALLOW_MOCK_OAUTH=1` — allow `mock_user` on `/auth/github` and `/auth/reddit` (tests only)\n+\n+Identity: UUID is canonical. OAuth providers only *link* to a UUID (first link creates the principal). Linked providers are private to the account owner.\n \n Health check: `GET /healthz` → `ok`.\n \ndiff --git a/server/src/auth/mod.rs b/server/src/auth/mod.rs\nindex 5906f93b13853421e96a3c37bc9d8202a47842bf..c706ae8045a811e5941f5f6c72da88f42a403a82 100644\n--- a/server/src/auth/mod.rs\n+++ b/server/src/auth/mod.rs\n@@ -1,4 +1,8 @@\n-//! GitHub OAuth login, session cookies, and vote actor resolution.\n+//! OAuth linking, session cookies, and vote actor resolution.\n+//!\n+//! Canonical identity is a UUID. OAuth providers only *link* to that UUID\n+//! (first link creates the principal; later links attach while logged in).\n+//! Which providers are linked is private to the account owner.\n \n pub mod config;\n pub mod identity;\n@@ -22,7 +26,9 @@ use crate::{\n form_template::template_json_compact,\n html::layout,\n state::AppState,\n- storage_schema::{oauth_link_owner, pseudonym_owner, Store, StoreFields},\n+ storage_schema::{\n+ linked_providers_for_uuid, oauth_link_owner, pseudonym_owner, Store, StoreFields,\n+ },\n ui_action::UI_RPC_FIELD,\n };\n \n@@ -53,10 +59,12 @@ fn new_actor_uuid() -> String {\n pub struct LoginQuery {\n #[serde(default)]\n pub return_to: Option,\n+ #[serde(default)]\n+ pub error: Option,\n }\n \n #[derive(Debug, Deserialize)]\n-pub struct GitHubStartQuery {\n+pub struct OAuthStartQuery {\n #[serde(default)]\n pub return_to: Option,\n #[serde(default)]\n@@ -72,15 +80,22 @@ fn return_from_query_or_jar(jar: &CookieJar, query: Option<&str>) -> String {\n .unwrap_or_else(|| \"/\".to_string())\n }\n \n-fn oauth_providers(base_url: &str, return_to: &str) -> Vec<(&'static str, String)> {\n+/// Available OAuth link targets: `(provider_key, label, start_href)`.\n+fn oauth_providers(base_url: &str, return_to: &str) -> Vec<(&'static str, &'static str, String)> {\n let mut out = Vec::new();\n+ let enc = urlencoding::encode(return_to);\n if oauth::GitHubConfig::from_env(base_url).is_some() {\n out.push((\n- \"GitHub\",\n- format!(\n- \"/auth/github?return_to={}\",\n- urlencoding::encode(return_to)\n- ),\n+ \"github\",\n+ oauth::provider_label(\"github\"),\n+ format!(\"/auth/github?return_to={enc}\"),\n+ ));\n+ }\n+ if oauth::RedditConfig::from_env(base_url).is_some() {\n+ out.push((\n+ \"reddit\",\n+ oauth::provider_label(\"reddit\"),\n+ format!(\"/auth/reddit?return_to={enc}\"),\n ));\n }\n out\n@@ -125,23 +140,41 @@ fn alias_claim_forms(return_to: &str, submit_label: &str) -> Result Markup {\n+fn login_error_message(code: Option<&str>) -> Option<&'static str> {\n+ match code {\n+ Some(\"oauth_taken\") => {\n+ Some(\"that OAuth account is already linked to a different sorter2 account\")\n+ }\n+ Some(\"oauth_failed\") => Some(\"OAuth failed — try again\"),\n+ _ => None,\n+ }\n+}\n+\n+fn signed_out_body(\n+ providers: &[(&str, &str, String)],\n+ error: Option<&str>,\n+) -> Markup {\n html! {\n main class=\"panel login-page\" {\n section class=\"login-section\" {\n h1 { \"sign in\" }\n- p class=\"muted\" { \"link an account to vote under a lasting alias\" }\n+ p class=\"muted\" {\n+ \"link an OAuth account to create your identity, then claim an alias to vote\"\n+ }\n+ @if let Some(msg) = login_error_message(error) {\n+ p class=\"alias-bad\" data-testid=\"login-error\" { (msg) }\n+ }\n @if providers.is_empty() {\n p class=\"muted\" {\n- \"OAuth is not configured. Set GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET.\"\n+ \"OAuth is not configured. Set GitHub and/or Reddit client credentials.\"\n }\n } @else {\n ul class=\"oauth-provider-list\" {\n- @for (name, href) in providers {\n+ @for (key, label, href) in providers {\n li {\n a href=(href) class=\"btn-primary oauth-provider\"\n- data-testid=(format!(\"oauth-{}\", name.to_lowercase())) {\n- (format!(\"Continue with {name}\"))\n+ data-testid=(format!(\"oauth-{key}\")) {\n+ (format!(\"Link {label}\"))\n }\n }\n }\n@@ -156,7 +189,10 @@ fn signed_out_body(providers: &[(&str, String)]) -> Markup {\n fn account_body(\n actor: &session::SessionActor,\n aliases: &[String],\n- providers: &[(&str, String)],\n+ // Provider keys already linked to this UUID (private).\n+ linked: &[String],\n+ // Providers available to link: not yet attached.\n+ unlinkable: &[(&str, &str, String)],\n claim_forms: Markup,\n ) -> Markup {\n let current = actor.pseudonym.trim();\n@@ -212,16 +248,29 @@ fn account_body(\n (claim_forms)\n }\n \n- @if !providers.is_empty() {\n- section class=\"login-section\" {\n- h2 { \"linked sign-in\" }\n- p class=\"muted small\" { \"sign in again with the same provider to return to this account\" }\n+ section class=\"login-section\" {\n+ h2 { \"linked sign-in\" }\n+ p class=\"muted small\" {\n+ \"private to you — linking more providers raises trust weight without publishing which accounts you use\"\n+ }\n+ @if linked.is_empty() {\n+ p class=\"muted\" data-testid=\"linked-providers-empty\" { \"none yet\" }\n+ } @else {\n+ ul class=\"linked-provider-list\" data-testid=\"linked-providers\" {\n+ @for key in linked {\n+ li data-testid=(format!(\"linked-{key}\")) {\n+ (oauth::provider_label(key))\n+ }\n+ }\n+ }\n+ }\n+ @if !unlinkable.is_empty() {\n ul class=\"oauth-provider-list\" {\n- @for (name, href) in providers {\n+ @for (key, label, href) in unlinkable {\n li {\n a href=(href) class=\"btn-secondary oauth-provider\"\n- data-testid=(format!(\"oauth-relink-{}\", name.to_lowercase())) {\n- (format!(\"Re-link {name}\"))\n+ data-testid=(format!(\"oauth-link-{key}\")) {\n+ (format!(\"Link {label}\"))\n }\n }\n }\n@@ -243,12 +292,21 @@ fn account_body(\n fn login_body(\n session: Option<&session::SessionActor>,\n aliases: &[String],\n- providers: &[(&str, String)],\n+ linked: &[String],\n+ providers: &[(&str, &str, String)],\n claim_forms: Option,\n+ error: Option<&str>,\n ) -> Markup {\n match (session, claim_forms) {\n- (Some(actor), Some(forms)) => account_body(actor, aliases, providers, forms),\n- _ => signed_out_body(providers),\n+ (Some(actor), Some(forms)) => {\n+ let unlinkable: Vec<_> = providers\n+ .iter()\n+ .filter(|(key, _, _)| !linked.iter().any(|p| p == key))\n+ .cloned()\n+ .collect();\n+ account_body(actor, aliases, linked, &unlinkable, forms)\n+ }\n+ _ => signed_out_body(providers, error),\n }\n }\n \n@@ -268,6 +326,10 @@ pub async fn login_page(\n .as_ref()\n .map(|s| alias_list(db, &s.uuid))\n .unwrap_or_default();\n+ let linked = session\n+ .as_ref()\n+ .map(|s| linked_providers_for_uuid(db, &s.uuid).unwrap_or_default())\n+ .unwrap_or_default();\n let providers = oauth_providers(&base_url_from_env(state.cfg.port), &return_to);\n \n let claim_forms = if session.is_some() {\n@@ -282,7 +344,14 @@ pub async fn login_page(\n } else {\n \"login · sorter2\"\n },\n- login_body(session.as_ref(), &aliases, &providers, claim_forms),\n+ login_body(\n+ session.as_ref(),\n+ &aliases,\n+ &linked,\n+ &providers,\n+ claim_forms,\n+ query.error.as_deref(),\n+ ),\n state.views.get_views(\"/login\"),\n session\n .as_ref()\n@@ -302,7 +371,6 @@ pub async fn alias_page(\n let db = state.projection_store.db();\n let session = session::load_valid_session(db, &session_id).ok_or(StatusCode::UNAUTHORIZED)?;\n if session::session_has_pseudonym(&session) {\n- // Already onboarded — manage aliases on the account page.\n return Ok(Redirect::to(\"/login\").into_response());\n }\n \n@@ -331,7 +399,7 @@ pub async fn alias_page(\n pub async fn github_start(\n State(state): State,\n jar: CookieJar,\n- Query(query): Query,\n+ Query(query): Query,\n ) -> Result {\n let cfg = oauth::GitHubConfig::from_env(&base_url_from_env(state.cfg.port))\n .ok_or(StatusCode::SERVICE_UNAVAILABLE)?;\n@@ -342,7 +410,28 @@ pub async fn github_start(\n } else {\n None\n };\n- let url = oauth::authorize_url(&cfg, &state_token, mock_user);\n+ let url = oauth::github_authorize_url(&cfg, &state_token, mock_user);\n+ let jar = jar\n+ .add(session::oauth_state_cookie_value(&state_token))\n+ .add(session::auth_return_cookie_value(&return_to));\n+ Ok((jar, Redirect::temporary(&url)).into_response())\n+}\n+\n+pub async fn reddit_start(\n+ State(state): State,\n+ jar: CookieJar,\n+ Query(query): Query,\n+) -> Result {\n+ let cfg = oauth::RedditConfig::from_env(&base_url_from_env(state.cfg.port))\n+ .ok_or(StatusCode::SERVICE_UNAVAILABLE)?;\n+ let return_to = return_from_query_or_jar(&jar, query.return_to.as_deref());\n+ let state_token = session::new_oauth_state();\n+ let mock_user = if config::mock_oauth_allowed() {\n+ query.mock_user.as_deref()\n+ } else {\n+ None\n+ };\n+ let url = oauth::reddit_authorize_url(&cfg, &state_token, mock_user);\n let jar = jar\n .add(session::oauth_state_cookie_value(&state_token))\n .add(session::auth_return_cookie_value(&return_to));\n@@ -355,6 +444,13 @@ pub struct OAuthCallbackQuery {\n pub state: String,\n }\n \n+/// Link `provider:provider_id` to a UUID.\n+///\n+/// - Logged in + new provider → attach to session UUID\n+/// - Logged in + already ours → no-op\n+/// - Logged in + owned by someone else → conflict\n+/// - Logged out + known link → resume that UUID\n+/// - Logged out + unknown → create principal + first link\n async fn finish_oauth_login(\n state: &AppState,\n jar: CookieJar,\n@@ -364,11 +460,41 @@ async fn finish_oauth_login(\n let db = state.projection_store.db();\n let return_to = return_from_query_or_jar(&jar, None);\n \n- let uuid = match oauth_link_owner(db, provider, &provider_id)\n- .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?\n- {\n- Some(existing) => existing,\n- None => {\n+ let existing_owner = oauth_link_owner(db, provider, &provider_id)\n+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;\n+\n+ let session_uuid = session::session_id_from_jar(&jar)\n+ .as_deref()\n+ .and_then(|id| session::load_valid_session(db, id))\n+ .map(|s| s.uuid);\n+ let linking_while_logged_in = session_uuid.is_some();\n+\n+ let uuid = match (session_uuid, existing_owner) {\n+ (Some(session_uuid), Some(owner)) if owner == session_uuid => session_uuid,\n+ (Some(_), Some(_)) => {\n+ return Ok((\n+ jar.add(session::clear_oauth_state_cookie()),\n+ \"/login?error=oauth_taken\".into(),\n+ ));\n+ }\n+ (Some(session_uuid), None) => {\n+ let ts = now_ms();\n+ state\n+ .append_identity_events(vec![Event::OauthLinked {\n+ uuid: session_uuid.clone(),\n+ provider: provider.to_string(),\n+ provider_id,\n+ ts,\n+ }])\n+ .await\n+ .map_err(|e| {\n+ tracing::warn!(err = %e, \"oauth link append failed\");\n+ StatusCode::INTERNAL_SERVER_ERROR\n+ })?;\n+ session_uuid\n+ }\n+ (None, Some(owner)) => owner,\n+ (None, None) => {\n let uuid = new_actor_uuid();\n let ts = now_ms();\n state\n@@ -409,6 +535,9 @@ async fn finish_oauth_login(\n \"/login/alias?return_to={}\",\n urlencoding::encode(&return_to)\n )\n+ } else if linking_while_logged_in {\n+ // Additional link while already in an account → stay on account page.\n+ \"/login\".to_string()\n } else {\n return_to\n };\n@@ -434,22 +563,57 @@ pub async fn github_callback(\n .build()\n .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;\n \n- let token = oauth::exchange_code(&client, &cfg, &query.code)\n+ let token = oauth::github_exchange_code(&client, &cfg, &query.code)\n .await\n .map_err(|e| {\n tracing::warn!(err = %e, \"github oauth token exchange failed\");\n StatusCode::BAD_GATEWAY\n })?;\n- let user = oauth::fetch_user(&client, &cfg.api_base, &token)\n+ let user = oauth::github_fetch_user(&client, &cfg.api_base, &token)\n .await\n .map_err(|e| {\n tracing::warn!(err = %e, \"github user fetch failed\");\n StatusCode::BAD_GATEWAY\n })?;\n \n- let provider = \"github\";\n- let provider_id = oauth::provider_id(&user);\n- let (jar, dest) = finish_oauth_login(&state, jar, provider, provider_id).await?;\n+ let (jar, dest) =\n+ finish_oauth_login(&state, jar, \"github\", oauth::github_provider_id(&user)).await?;\n+ Ok((jar, Redirect::to(&dest)).into_response())\n+}\n+\n+pub async fn reddit_callback(\n+ State(state): State,\n+ jar: CookieJar,\n+ Query(query): Query,\n+) -> Result {\n+ let cfg = oauth::RedditConfig::from_env(&base_url_from_env(state.cfg.port))\n+ .ok_or(StatusCode::SERVICE_UNAVAILABLE)?;\n+\n+ let expected_state = session::oauth_state_from_jar(&jar).ok_or(StatusCode::BAD_REQUEST)?;\n+ if expected_state != query.state {\n+ return Err(StatusCode::BAD_REQUEST);\n+ }\n+\n+ let client = Client::builder()\n+ .timeout(std::time::Duration::from_secs(15))\n+ .build()\n+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;\n+\n+ let token = oauth::reddit_exchange_code(&client, &cfg, &query.code)\n+ .await\n+ .map_err(|e| {\n+ tracing::warn!(err = %e, \"reddit oauth token exchange failed\");\n+ StatusCode::BAD_GATEWAY\n+ })?;\n+ let user = oauth::reddit_fetch_user(&client, &cfg, &token)\n+ .await\n+ .map_err(|e| {\n+ tracing::warn!(err = %e, \"reddit user fetch failed\");\n+ StatusCode::BAD_GATEWAY\n+ })?;\n+\n+ let (jar, dest) =\n+ finish_oauth_login(&state, jar, \"reddit\", oauth::reddit_provider_id(&user)).await?;\n Ok((jar, Redirect::to(&dest)).into_response())\n }\n \ndiff --git a/server/src/auth/oauth.rs b/server/src/auth/oauth.rs\nindex b80078fee0c5acd905b9125d29454e46c4e0d066..369b1527d9032cf312a07819279e0f988ef4a36e 100644\n--- a/server/src/auth/oauth.rs\n+++ b/server/src/auth/oauth.rs\n@@ -1,8 +1,15 @@\n-//! GitHub OAuth (raw reqwest, same style as reddit.rs).\n+//! OAuth providers (GitHub + Reddit). Provider accounts only *link* to a UUID;\n+//! the UUID is the canonical identity. Which providers are linked is private.\n \n use reqwest::Client;\n use serde::Deserialize;\n \n+use crate::reddit::{\n+ default_user_agent, reddit_oauth_api_base, reddit_oauth_token_base,\n+};\n+\n+// ── GitHub ──────────────────────────────────────────────────────────────────\n+\n #[derive(Debug, Clone)]\n pub struct GitHubConfig {\n pub client_id: String,\n@@ -40,7 +47,7 @@ impl GitHubConfig {\n }\n \n #[derive(Debug, Deserialize)]\n-struct TokenResponse {\n+struct GitHubTokenResponse {\n access_token: String,\n }\n \n@@ -50,7 +57,7 @@ pub struct GitHubUser {\n pub login: String,\n }\n \n-pub fn authorize_url(cfg: &GitHubConfig, state: &str, mock_user: Option<&str>) -> String {\n+pub fn github_authorize_url(cfg: &GitHubConfig, state: &str, mock_user: Option<&str>) -> String {\n let mut url = format!(\n \"{}/login/oauth/authorize?client_id={}&redirect_uri={}&scope=read:user&state={}\",\n cfg.oauth_base.trim_end_matches('/'),\n@@ -65,7 +72,7 @@ pub fn authorize_url(cfg: &GitHubConfig, state: &str, mock_user: Option<&str>) -\n url\n }\n \n-pub async fn exchange_code(\n+pub async fn github_exchange_code(\n client: &Client,\n cfg: &GitHubConfig,\n code: &str,\n@@ -90,14 +97,14 @@ pub async fn exchange_code(\n return Err(format!(\"github token HTTP {}\", resp.status()));\n }\n \n- let body: TokenResponse = resp\n+ let body: GitHubTokenResponse = resp\n .json()\n .await\n .map_err(|e| format!(\"github token parse failed: {e}\"))?;\n Ok(body.access_token)\n }\n \n-pub async fn fetch_user(\n+pub async fn github_fetch_user(\n client: &Client,\n api_base: &str,\n access_token: &str,\n@@ -120,10 +127,149 @@ pub async fn fetch_user(\n .map_err(|e| format!(\"github user parse failed: {e}\"))\n }\n \n-pub fn provider_id(user: &GitHubUser) -> String {\n+pub fn github_provider_id(user: &GitHubUser) -> String {\n user.id.to_string()\n }\n \n+// ── Reddit ──────────────────────────────────────────────────────────────────\n+\n+#[derive(Debug, Clone)]\n+pub struct RedditConfig {\n+ pub client_id: String,\n+ pub client_secret: String,\n+ pub redirect_uri: String,\n+ /// Host for `/api/v1/authorize` (www.reddit.com in production).\n+ pub authorize_base: String,\n+ /// Host for `POST /api/v1/access_token`.\n+ pub token_base: String,\n+ /// Host for bearer `GET /api/v1/me` (oauth.reddit.com).\n+ pub api_base: String,\n+ pub user_agent: String,\n+}\n+\n+/// Authorize page base; defaults to the same host as token POSTs.\n+pub fn reddit_authorize_base() -> String {\n+ std::env::var(\"REDDIT_OAUTH_AUTHORIZE_BASE\")\n+ .or_else(|_| std::env::var(\"REDDIT_OAUTH_BASE\"))\n+ .unwrap_or_else(|_| \"https://www.reddit.com\".into())\n+}\n+\n+impl RedditConfig {\n+ pub fn from_env(base_url: &str) -> Option {\n+ let client_id = std::env::var(\"REDDIT_CLIENT_ID\")\n+ .or_else(|_| std::env::var(\"REDDIT_APP_ID\"))\n+ .ok()?;\n+ let client_secret = std::env::var(\"REDDIT_CLIENT_SECRET\")\n+ .or_else(|_| std::env::var(\"REDDIT_APP_SECRET\"))\n+ .ok()?;\n+ if client_id.is_empty() || client_secret.is_empty() {\n+ return None;\n+ }\n+ let base = base_url.trim_end_matches('/');\n+ Some(Self {\n+ client_id,\n+ client_secret,\n+ redirect_uri: format!(\"{base}/auth/reddit/callback\"),\n+ authorize_base: reddit_authorize_base(),\n+ token_base: reddit_oauth_token_base(),\n+ api_base: reddit_oauth_api_base(),\n+ user_agent: default_user_agent(),\n+ })\n+ }\n+}\n+\n+#[derive(Debug, Deserialize)]\n+struct RedditTokenResponse {\n+ access_token: String,\n+}\n+\n+#[derive(Debug, Deserialize)]\n+pub struct RedditUser {\n+ /// Stable id (`t2_…`); never use `name` as identity.\n+ pub id: String,\n+ pub name: String,\n+}\n+\n+pub fn reddit_authorize_url(cfg: &RedditConfig, state: &str, mock_user: Option<&str>) -> String {\n+ let mut url = format!(\n+ \"{}/api/v1/authorize?client_id={}&response_type=code&state={}&redirect_uri={}&duration=temporary&scope=identity\",\n+ cfg.authorize_base.trim_end_matches('/'),\n+ urlencoding::encode(&cfg.client_id),\n+ urlencoding::encode(state),\n+ urlencoding::encode(&cfg.redirect_uri),\n+ );\n+ if let Some(user) = mock_user {\n+ url.push_str(\"&mock_user=\");\n+ url.push_str(&urlencoding::encode(user));\n+ }\n+ url\n+}\n+\n+pub async fn reddit_exchange_code(\n+ client: &Client,\n+ cfg: &RedditConfig,\n+ code: &str,\n+) -> Result {\n+ let resp = client\n+ .post(format!(\n+ \"{}/api/v1/access_token\",\n+ cfg.token_base.trim_end_matches('/')\n+ ))\n+ .header(\"User-Agent\", &cfg.user_agent)\n+ .basic_auth(&cfg.client_id, Some(&cfg.client_secret))\n+ .form(&[\n+ (\"grant_type\", \"authorization_code\"),\n+ (\"code\", code),\n+ (\"redirect_uri\", cfg.redirect_uri.as_str()),\n+ ])\n+ .send()\n+ .await\n+ .map_err(|e| format!(\"reddit token request failed: {e}\"))?;\n+\n+ if !resp.status().is_success() {\n+ let status = resp.status();\n+ let body = resp.text().await.unwrap_or_default();\n+ return Err(format!(\"reddit token HTTP {status}: {body}\"));\n+ }\n+\n+ let body: RedditTokenResponse = resp\n+ .json()\n+ .await\n+ .map_err(|e| format!(\"reddit token parse failed: {e}\"))?;\n+ Ok(body.access_token)\n+}\n+\n+pub async fn reddit_fetch_user(\n+ client: &Client,\n+ cfg: &RedditConfig,\n+ access_token: &str,\n+) -> Result {\n+ let resp = client\n+ .get(format!(\n+ \"{}/api/v1/me\",\n+ cfg.api_base.trim_end_matches('/')\n+ ))\n+ .header(\"User-Agent\", &cfg.user_agent)\n+ .bearer_auth(access_token)\n+ .send()\n+ .await\n+ .map_err(|e| format!(\"reddit user request failed: {e}\"))?;\n+\n+ if !resp.status().is_success() {\n+ return Err(format!(\"reddit user HTTP {}\", resp.status()));\n+ }\n+\n+ resp.json()\n+ .await\n+ .map_err(|e| format!(\"reddit user parse failed: {e}\"))\n+}\n+\n+pub fn reddit_provider_id(user: &RedditUser) -> String {\n+ user.id.clone()\n+}\n+\n+// ── Shared helpers ──────────────────────────────────────────────────────────\n+\n pub fn validate_pseudonym(raw: &str) -> Result {\n let trimmed = raw.trim();\n if trimmed.is_empty() {\n@@ -144,3 +290,12 @@ pub fn validate_pseudonym(raw: &str) -> Result {\n pub fn sanitize_pseudonym(login: &str) -> String {\n validate_pseudonym(login).unwrap_or_else(|_| \"user\".to_string())\n }\n+\n+/// Display name for a provider key (`github` → `GitHub`). Never show provider ids.\n+pub fn provider_label(provider: &str) -> &'static str {\n+ match provider {\n+ \"github\" => \"GitHub\",\n+ \"reddit\" => \"Reddit\",\n+ _ => \"OAuth\",\n+ }\n+}\ndiff --git a/server/src/lib.rs b/server/src/lib.rs\nindex 84f2565b105fb302241b949af64bd5e49916eab2..0d948af1457504fdbd34d0b14261f65ac58da0ec 100644\n--- a/server/src/lib.rs\n+++ b/server/src/lib.rs\n@@ -47,6 +47,8 @@ pub fn create_app(state: AppState) -> Router {\n .route(\"/login/alias\", get(crate::auth::alias_page))\n .route(\"/auth/github\", get(crate::auth::github_start))\n .route(\"/auth/github/callback\", get(crate::auth::github_callback))\n+ .route(\"/auth/reddit\", get(crate::auth::reddit_start))\n+ .route(\"/auth/reddit/callback\", get(crate::auth::reddit_callback))\n .route(\"/auth/logout\", post(crate::auth::logout))\n .route(\"/auth/switch\", post(crate::auth::switch_pseudonym))\n .route(\"/ui\", post(crate::api::ui_html::post_ui_html))\ndiff --git a/server/src/projection_apply.rs b/server/src/projection_apply.rs\nindex 4fb4b48ee0a53b7f673fae0c9731eed5acc33332..f50458c2ff3c447a3cfd28adb298e6883a2da4e9 100644\n--- a/server/src/projection_apply.rs\n+++ b/server/src/projection_apply.rs\n@@ -4,6 +4,8 @@\n //! child links, recent-vote appends) plus a cursor advance, all committed in\n //! one atomic `DisableWal` batch.\n \n+use std::collections::HashMap;\n+\n use crate::{\n event_log::EventLogError,\n events::{Event, EventRecord},\n@@ -44,6 +46,8 @@ pub fn apply_records(\n let db = projection_store.db();\n let mut batch = db.batch();\n let mut last_seq = 0u64;\n+ // Weight reads must see earlier writes in this same batch.\n+ let mut pending_weights: HashMap = HashMap::new();\n \n for record in records {\n match &record.event {\n@@ -85,6 +89,7 @@ pub fn apply_records(\n ensure_path_writes(&mut batch, &parsed);\n }\n Event::PrincipalCreated { uuid, .. } => {\n+ pending_weights.insert(uuid.clone(), BASE_TRUST_WEIGHT);\n batch.write(\n Store::root()\n .user_weights()\n@@ -112,17 +117,25 @@ pub fn apply_records(\n }\n } else {\n batch.write(Store::root().oauth_links().key(&link_key).set(uuid));\n- let current = Store::root()\n- .user_weights()\n- .key(&uuid.clone())\n- .get(db)\n- .map_err(|e| EventLogError::Apply(e.to_string()))?\n+ let current = pending_weights\n+ .get(uuid)\n+ .copied()\n+ .or_else(|| {\n+ Store::root()\n+ .user_weights()\n+ .key(&uuid.clone())\n+ .get(db)\n+ .ok()\n+ .flatten()\n+ })\n .unwrap_or(BASE_TRUST_WEIGHT);\n+ let next = trust_weight_after_link(current);\n+ pending_weights.insert(uuid.clone(), next);\n batch.write(\n Store::root()\n .user_weights()\n .key(&uuid.clone())\n- .set(&trust_weight_after_link(current)),\n+ .set(&next),\n );\n }\n }\n@@ -205,6 +218,15 @@ mod tests {\n ),\n record(\n 3,\n+ Event::OauthLinked {\n+ uuid: uuid.into(),\n+ provider: \"reddit\".into(),\n+ provider_id: \"t2_abc\".into(),\n+ ts,\n+ },\n+ ),\n+ record(\n+ 4,\n Event::PseudonymClaimed {\n uuid: uuid.into(),\n pseudonym: \"octocat\".into(),\n@@ -219,8 +241,12 @@ mod tests {\n oauth_link_owner(store.db(), \"github\", \"42\").unwrap(),\n Some(uuid.to_string())\n );\n+ assert_eq!(\n+ crate::storage_schema::linked_providers_for_uuid(store.db(), uuid).unwrap(),\n+ vec![\"github\".to_string(), \"reddit\".to_string()]\n+ );\n assert_eq!(resolve_actor_uuid(store.db(), \"octocat\").unwrap(), uuid);\n- assert_eq!(user_trust_weight(store.db(), uuid).unwrap(), 1.5);\n+ assert_eq!(user_trust_weight(store.db(), uuid).unwrap(), 2.0);\n let aliases = Store::root()\n .user_pseudonyms()\n .key(&uuid.to_string())\ndiff --git a/server/src/storage_schema.rs b/server/src/storage_schema.rs\nindex b942810afd96d3bf01b7765718303a39be4ef8d2..dac6f8e6080e3f5683c24dbb8861f5a981d456c4 100644\n--- a/server/src/storage_schema.rs\n+++ b/server/src/storage_schema.rs\n@@ -103,6 +103,25 @@ pub fn oauth_link_owner(db: &Db, provider: &str, provider_id: &str) -> durable::\n .get(db)\n }\n \n+/// Provider names linked to a UUID (`github`, `reddit`, …). Private — for the\n+/// account owner's page only; never expose which providers are linked publicly.\n+pub fn linked_providers_for_uuid(db: &Db, uuid: &str) -> durable::Result> {\n+ let mut providers = Vec::new();\n+ for (key, owner) in Store::root().oauth_links().iter(db)? {\n+ if owner != uuid {\n+ continue;\n+ }\n+ let Some((provider, _)) = key.split_once(':') else {\n+ continue;\n+ };\n+ if !providers.iter().any(|p| p == provider) {\n+ providers.push(provider.to_string());\n+ }\n+ }\n+ providers.sort();\n+ Ok(providers)\n+}\n+\n pub const RECENT_VOTES_CAP: u64 = 200;\n \n fn id_key(id: &ItemId) -> String {\ndiff --git a/test/support/harness.clj b/test/support/harness.clj\nindex 4505ece5aa193e826ca61c52f1467d252080d66b..741024aab1d14269e225791189633287980ae2e4 100644\n--- a/test/support/harness.clj\n+++ b/test/support/harness.clj\n@@ -48,12 +48,15 @@\n \"GITHUB_CLIENT_SECRET\" \"test-secret\"\n \"GITHUB_OAUTH_BASE\" (str \"http://127.0.0.1:\" oauth-port)\n \"GITHUB_API_BASE\" (str \"http://127.0.0.1:\" oauth-port)\n+ ;; Reddit import fixtures + Reddit OAuth on reddit-port.\n \"REDDIT_API_BASE\" (str \"http://127.0.0.1:\" reddit-port)\n+ \"REDDIT_CLIENT_ID\" \"test-reddit\"\n+ \"REDDIT_CLIENT_SECRET\" \"test-reddit-secret\"\n \"REDDIT_OAUTH_BASE\" (str \"http://127.0.0.1:\" reddit-port)\n- \"REDDIT_CLIENT_ID\" \"\"\n- \"REDDIT_CLIENT_SECRET\" \"\"\n- \"REDDIT_APP_ID\" \"\"\n- \"REDDIT_APP_SECRET\" \"\"}))\n+ \"REDDIT_OAUTH_AUTHORIZE_BASE\" (str \"http://127.0.0.1:\" reddit-port)\n+ \"REDDIT_OAUTH_TOKEN_BASE\" (str \"http://127.0.0.1:\" reddit-port)\n+ \"REDDIT_OAUTH_API_BASE\" (str \"http://127.0.0.1:\" reddit-port)\n+ \"REDDIT_USER_AGENT\" \"web:sorter2-test:v0 (by /u/test)\"}))\n \n (defn with-auth-servers\n \"Start mock Reddit + mock OAuth + release sorter2-server.\ndiff --git a/test/support/mock_oauth.clj b/test/support/mock_oauth.clj\nindex 909d7a7be8b159ea54a122d69c46af3db3318118..5ba7e9be3cf6d2226648e9609a09ed45f306930f 100644\n--- a/test/support/mock_oauth.clj\n+++ b/test/support/mock_oauth.clj\n@@ -1,5 +1,5 @@\n (ns test.support.mock-oauth\n- \"In-process HTTP stub for GitHub OAuth (authorize, token, /user).\"\n+ \"In-process HTTP stub for GitHub + Reddit OAuth (authorize, token, user).\"\n (:require [clojure.string :as str])\n (:import [com.sun.net.httpserver HttpServer HttpHandler HttpExchange]\n [java.net InetSocketAddress URLDecoder]))\n@@ -12,11 +12,14 @@\n (URLDecoder/decode (or v \"\") \"UTF-8\"))))\n (str/split query #\"&\"))))\n \n-(defn- parse-mock-user [raw]\n+(defn- parse-mock-user\n+ \"GitHub-style `id:login` (numeric id). Reddit-style `t2_xxx:name`.\"\n+ [raw]\n (let [s (or raw \"1002:newbie\")\n [id login] (str/split s #\":\" 2)]\n- {:id (Long/parseLong id)\n- :login (or login \"newbie\")}))\n+ {:id id\n+ :login (or login \"newbie\")\n+ :numeric? (re-matches #\"\\d+\" id)}))\n \n (defn- send-json [^HttpExchange ex status body]\n (let [bytes (.getBytes body \"UTF-8\")]\n@@ -31,9 +34,10 @@\n (.sendResponseHeaders ex 302 -1)\n (.close (.getResponseBody ex)))\n \n-(defn- read-form-code [^HttpExchange ex]\n+(defn- read-form [^HttpExchange ex]\n (let [body (slurp (.getInputStream ex))]\n- (query-param body \"code\")))\n+ {:code (query-param body \"code\")\n+ :grant (query-param body \"grant_type\")}))\n \n (defn- bearer-token [^HttpExchange ex]\n (some-> (.getRequestHeaders ex)\n@@ -44,8 +48,18 @@\n (when (str/starts-with? token \"mock:\")\n (parse-mock-user (subs token 5))))\n \n+(defn- authorize-redirect [exchange query]\n+ (let [redirect-uri (query-param query \"redirect_uri\")\n+ state (query-param query \"state\")\n+ mock-user (query-param query \"mock_user\")\n+ user (parse-mock-user mock-user)\n+ code (str \"mock:\" (:id user) \":\" (:login user))\n+ loc (str redirect-uri \"?code=\" (java.net.URLEncoder/encode code \"UTF-8\")\n+ \"&state=\" (java.net.URLEncoder/encode state \"UTF-8\"))]\n+ (send-redirect exchange loc)))\n+\n (defn start-mock-oauth\n- \"Start mock GitHub OAuth on `port`. Returns a zero-arg `stop` function.\"\n+ \"Start mock GitHub + Reddit OAuth on `port`. Returns a zero-arg `stop` function.\"\n [port]\n (let [server (HttpServer/create (InetSocketAddress. \"127.0.0.1\" port) 0)\n handler\n@@ -53,28 +67,45 @@\n (handle [^HttpExchange exchange]\n (let [uri (.getRequestURI exchange)\n path (.getPath uri)\n- query (.getQuery uri)]\n+ query (.getQuery uri)\n+ method (.getRequestMethod exchange)]\n (cond\n+ ;; GitHub authorize\n (str/ends-with? path \"/login/oauth/authorize\")\n- (let [redirect-uri (query-param query \"redirect_uri\")\n- state (query-param query \"state\")\n- mock-user (query-param query \"mock_user\")\n- user (parse-mock-user mock-user)\n- code (str \"mock:\" (:id user) \":\" (:login user))\n- loc (str redirect-uri \"?code=\" (java.net.URLEncoder/encode code \"UTF-8\")\n- \"&state=\" (java.net.URLEncoder/encode state \"UTF-8\"))]\n- (send-redirect exchange loc))\n+ (authorize-redirect exchange query)\n+\n+ ;; Reddit authorize\n+ (str/ends-with? path \"/api/v1/authorize\")\n+ (authorize-redirect exchange query)\n \n- (str/ends-with? path \"/login/oauth/access_token\")\n- (let [code (or (read-form-code exchange) \"mock:1002:newbie\")]\n+ ;; GitHub token\n+ (and (= method \"POST\") (str/ends-with? path \"/login/oauth/access_token\"))\n+ (let [code (or (:code (read-form exchange)) \"mock:1002:newbie\")]\n (send-json exchange 200 (str \"{\\\"access_token\\\":\\\"\" code \"\\\",\\\"token_type\\\":\\\"bearer\\\"}\")))\n \n+ ;; Reddit token (client_credentials for import + authorization_code for login)\n+ (and (= method \"POST\") (str/ends-with? path \"/api/v1/access_token\"))\n+ (let [form (read-form exchange)\n+ grant (or (:grant form) \"\")\n+ code (or (:code form) \"mock:t2_test:redditor\")]\n+ (if (= grant \"client_credentials\")\n+ (send-json exchange 200 \"{\\\"access_token\\\":\\\"app-token\\\",\\\"token_type\\\":\\\"bearer\\\",\\\"expires_in\\\":3600}\")\n+ (send-json exchange 200 (str \"{\\\"access_token\\\":\\\"\" code \"\\\",\\\"token_type\\\":\\\"bearer\\\",\\\"expires_in\\\":3600}\"))))\n+\n+ ;; GitHub user\n (= path \"/user\")\n (let [token (bearer-token exchange)\n- user (or (parse-token-user token) {:id 1002 :login \"newbie\"})]\n+ user (or (parse-token-user token) {:id \"1002\" :login \"newbie\" :numeric? true})]\n (send-json exchange 200\n (str \"{\\\"id\\\":\" (:id user) \",\\\"login\\\":\\\"\" (:login user) \"\\\"}\")))\n \n+ ;; Reddit /api/v1/me\n+ (str/ends-with? path \"/api/v1/me\")\n+ (let [token (bearer-token exchange)\n+ user (or (parse-token-user token) {:id \"t2_test\" :login \"redditor\"})]\n+ (send-json exchange 200\n+ (str \"{\\\"id\\\":\\\"\" (:id user) \"\\\",\\\"name\\\":\\\"\" (:login user) \"\\\"}\")))\n+\n :else\n (send-json exchange 404 \"{\\\"error\\\":\\\"not found\\\"}\")))))]\n (.createContext server \"/\" handler)\ndiff --git a/test/support/mock_reddit.clj b/test/support/mock_reddit.clj\nindex 5efa92db3e1f79b8f423a2f1adcbda959123c1ad..a630cf0938722193e9af88382d60e777ff371be4 100644\n--- a/test/support/mock_reddit.clj\n+++ b/test/support/mock_reddit.clj\n@@ -1,14 +1,56 @@\n (ns test.support.mock-reddit\n- \"In-process HTTP stub for Reddit API fixtures (`test/fixtures/reddit/`).\"\n+ \"In-process HTTP stub for Reddit API fixtures + OAuth login endpoints.\"\n (:require [clojure.java.io :as io]\n [clojure.string :as str])\n (:import [com.sun.net.httpserver HttpServer HttpHandler HttpExchange]\n- [java.net InetSocketAddress]))\n+ [java.net InetSocketAddress URLDecoder]))\n \n (defn fixtures-dir\n ([] (fixtures-dir (System/getProperty \"user.dir\")))\n ([root] (str root \"/test/fixtures/reddit\")))\n \n+(defn- query-param [query key]\n+ (when query\n+ (some (fn [pair]\n+ (let [[k v] (str/split pair \"=\" 2)]\n+ (when (= k key)\n+ (URLDecoder/decode (or v \"\") \"UTF-8\"))))\n+ (str/split query #\"&\"))))\n+\n+(defn- parse-mock-user [raw]\n+ (let [s (or raw \"t2_test:redditor\")\n+ [id login] (str/split s #\":\" 2)]\n+ {:id id :login (or login \"redditor\")}))\n+\n+(defn- send-bytes [^HttpExchange ex status ^bytes body content-type]\n+ (.set (.getResponseHeaders ex) \"Content-Type\" content-type)\n+ (.sendResponseHeaders ex status (alength body))\n+ (doto (.getResponseBody ex)\n+ (.write body)\n+ (.close)))\n+\n+(defn- send-json [^HttpExchange ex status body]\n+ (send-bytes ex status (.getBytes body \"UTF-8\") \"application/json\"))\n+\n+(defn- send-redirect [^HttpExchange ex location]\n+ (.set (.getResponseHeaders ex) \"Location\" location)\n+ (.sendResponseHeaders ex 302 -1)\n+ (.close (.getResponseBody ex)))\n+\n+(defn- read-form [^HttpExchange ex]\n+ (let [body (slurp (.getInputStream ex))]\n+ {:code (query-param body \"code\")\n+ :grant (query-param body \"grant_type\")}))\n+\n+(defn- bearer-token [^HttpExchange ex]\n+ (some-> (.getRequestHeaders ex)\n+ (.getFirst \"Authorization\")\n+ (str/replace #\"^[Bb]earer \" \"\")))\n+\n+(defn- parse-token-user [token]\n+ (when (str/starts-with? token \"mock:\")\n+ (parse-mock-user (subs token 5))))\n+\n (defn start-mock-reddit\n \"Start a mock Reddit API on `port`. Returns a zero-arg `stop` function.\"\n ([port] (start-mock-reddit port (fixtures-dir)))\n@@ -19,15 +61,38 @@\n handler\n (proxy [HttpHandler] []\n (handle [^HttpExchange exchange]\n- ;; `/r//about.json` → subreddit entity; `/r/.json` → listing.\n- (let [path (.getPath (.getRequestURI exchange))\n- body (if (str/includes? path \"/about\")\n- about\n- listing)]\n- (.sendResponseHeaders exchange 200 (alength body))\n- (let [out (.getResponseBody exchange)]\n- (.write out body)\n- (.close out)))))]\n+ (let [uri (.getRequestURI exchange)\n+ path (.getPath uri)\n+ query (.getQuery uri)\n+ method (.getRequestMethod exchange)]\n+ (cond\n+ (str/ends-with? path \"/api/v1/authorize\")\n+ (let [redirect-uri (query-param query \"redirect_uri\")\n+ state (query-param query \"state\")\n+ user (parse-mock-user (query-param query \"mock_user\"))\n+ code (str \"mock:\" (:id user) \":\" (:login user))\n+ loc (str redirect-uri \"?code=\" (java.net.URLEncoder/encode code \"UTF-8\")\n+ \"&state=\" (java.net.URLEncoder/encode state \"UTF-8\"))]\n+ (send-redirect exchange loc))\n+\n+ (and (= method \"POST\") (str/ends-with? path \"/api/v1/access_token\"))\n+ (let [form (read-form exchange)\n+ grant (or (:grant form) \"\")\n+ code (or (:code form) \"mock:t2_test:redditor\")]\n+ (if (= grant \"client_credentials\")\n+ (send-json exchange 200 \"{\\\"access_token\\\":\\\"app-token\\\",\\\"token_type\\\":\\\"bearer\\\",\\\"expires_in\\\":3600}\")\n+ (send-json exchange 200 (str \"{\\\"access_token\\\":\\\"\" code \"\\\",\\\"token_type\\\":\\\"bearer\\\",\\\"expires_in\\\":3600}\"))))\n+\n+ (str/ends-with? path \"/api/v1/me\")\n+ (let [user (or (parse-token-user (bearer-token exchange))\n+ {:id \"t2_test\" :login \"redditor\"})]\n+ (send-json exchange 200\n+ (str \"{\\\"id\\\":\\\"\" (:id user) \"\\\",\\\"name\\\":\\\"\" (:login user) \"\\\"}\")))\n+\n+ ;; `/r//about.json` → subreddit entity; `/r/.json` → listing.\n+ :else\n+ (let [body (if (str/includes? path \"/about\") about listing)]\n+ (send-bytes exchange 200 body \"application/json\"))))))]\n (.createContext server \"/\" handler)\n (.setExecutor server nil)\n (.start server)\n","role":"user"}],"model":"~x-ai/grok-latest"}