{"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[02cd761c] Make ranked child group pin icons clickable to unpin.\n\nLets users clear the garden pin from the ranked child groups list via the same POST /ui set_garden_pin flow as the HUD and item header.\n\nCo-authored-by: Cursor \n\nSide A β€” unified diff (full patch):\ndiff --git a/server/src/html/garden/pin.rs b/server/src/html/garden/pin.rs\nindex 1820d7fe7ee167ecbf5ad5124f23b2ab92ffb01f..b7ea92bbe67d6d499915edb607a3a0b36178d7f6 100644\n--- a/server/src/html/garden/pin.rs\n+++ b/server/src/html/garden/pin.rs\n@@ -101,6 +101,7 @@ pub(super) fn child_row_pin_or_vote(\n row_item: &ItemId,\n pinned_room_and_item: Option<&(String, ItemId)>,\n scope_content: &ContentState,\n+ next_path: &str,\n ) -> maud::Markup {\n let pin_matches_scope = pinned_room_and_item\n .map(|(r, _)| r == nav.room_wire.as_str())\n@@ -108,12 +109,25 @@ pub(super) fn child_row_pin_or_vote(\n let pinned_item = pinned_room_and_item\n .filter(|_| pin_matches_scope)\n .map(|(_, i)| i);\n+ let unpin_rpc = template_json_compact(&json!({\n+ \"action\": \"set_garden_pin\",\n+ \"clear\": true,\n+ \"room_wire\": \"\",\n+ \"next\": next_path,\n+ \"form_action\": \"/ui\",\n+ }))\n+ .expect(\"unpin rpc json\");\n \n html! {\n @if let Some(pi) = pinned_item {\n span class=\"ont-garden-child-actions\" data-garden-room=(nav.room_wire.as_str()) {\n @if pi == row_item {\n- span class=\"ont-garden-pinned-here\" title=\"Pinned\" aria-label=\"Pinned\" { \"πŸ“Œ\" }\n+ form method=\"POST\" action=\"/ui\" data-navigate=\"full\" class=\"ont-garden-pin-form\" {\n+ input type=\"hidden\" name=(UI_RPC_FIELD) value=(unpin_rpc);\n+ button type=\"submit\" class=\"ont-garden-pin-ico ont-garden-pin-ico-active\" title=\"Unpin\" aria-label=\"Unpin from HUD\" {\n+ span class=\"ont-garden-pin-glyph\" aria-hidden=\"true\" { \"πŸ“Œ\" }\n+ }\n+ }\n } @else {\n @let nv = edge_vote_count_for_pair(scope_content, pi, row_item);\n @let tip = format!(\ndiff --git a/server/src/html/garden/render.rs b/server/src/html/garden/render.rs\nindex bd8cbce059ee789de6e8dc9b6f69f54beee2f994..7bfaadc0786b734db8973c53b82296a188d26e22 100644\n--- a/server/src/html/garden/render.rs\n+++ b/server/src/html/garden/render.rs\n@@ -216,7 +216,7 @@ pub(super) async fn render_scope_view(\n @let item_url = item_href(r.item.as_str(), &nav);\n @let score_str = format!(\"{:.3}\", r.score);\n li data-garden-item=(r.item.as_str()) {\n- (child_row_pin_or_vote(&nav, &r.item, pin_ref.as_ref(), scope_content))\n+ (child_row_pin_or_vote(&nav, &r.item, pin_ref.as_ref(), scope_content, &next_for_pin))\n a class=\"item-link\" href=(item_url) { code { (item_display_path(r.item.as_str())) } }\n span class=\"ont-rank-score\" { (score_str) }\n }\n@@ -232,7 +232,7 @@ pub(super) async fn render_scope_view(\n ul class=\"ont-group-list\" {\n @for name in &model.child_rankings.unranked_items {\n li data-garden-item=(name.as_str()) {\n- (child_row_pin_or_vote(&nav, name, pin_ref.as_ref(), scope_content))\n+ (child_row_pin_or_vote(&nav, name, pin_ref.as_ref(), scope_content, &next_for_pin))\n @let href = item_href(name.as_str(), &nav);\n a class=\"item-link\" href=(href) { code { (item_display_path(name.as_str())) } }\n }\ndiff --git a/server/static/theme_default.css b/server/static/theme_default.css\nindex 2dabf3a7094cecd89d0c9674d27efe30cd01c010..b846ab86cb6eb5fb56be87efb054fb8b18082583 100644\n--- a/server/static/theme_default.css\n+++ b/server/static/theme_default.css\n@@ -891,8 +891,7 @@ button.ont-pin-btn-active {\n vertical-align: middle;\n }\n button.ont-garden-pin-ico,\n-a.ont-garden-vote-ico,\n-span.ont-garden-pinned-here {\n+a.ont-garden-vote-ico {\n font-size: 13px;\n line-height: 1;\n padding: 2px 6px;\n@@ -910,6 +909,11 @@ span.ont-garden-pinned-here {\n align-items: center;\n justify-content: center;\n }\n+form.ont-garden-pin-form {\n+ display: inline;\n+ margin: 0;\n+ padding: 0;\n+}\n a.ont-garden-vote-ico {\n gap: 4px;\n }\n@@ -925,10 +929,14 @@ a.ont-garden-vote-ico:hover {\n span.ont-garden-vote-glyph {\n line-height: 1;\n }\n-span.ont-garden-pinned-here {\n+button.ont-garden-pin-ico-active {\n border-color: var(--link);\n color: var(--signal);\n- cursor: default;\n+ background: color-mix(in srgb, var(--link) 12%, var(--g3));\n+}\n+button.ont-garden-pin-ico-active:hover {\n+ color: var(--signal);\n+ background: color-mix(in srgb, var(--link) 18%, var(--g4));\n }\n button.ont-garden-pin-ico:focus-visible {\n outline: 2px solid var(--link);\ndiff --git a/server/static/theme_retro_craft.css b/server/static/theme_retro_craft.css\nindex bdd9031b82154a5019782e6dcb8bf7589fafce09..5d4954812ad43f2ee7e63c71c7f0ae0b3e3fc95b 100644\n--- a/server/static/theme_retro_craft.css\n+++ b/server/static/theme_retro_craft.css\n@@ -711,8 +711,7 @@ body.view-ontology span.ont-garden-vote-glyph {\n line-height: 1;\n }\n body.view-ontology button.ont-garden-pin-ico,\n-body.view-ontology a.ont-garden-vote-ico,\n-body.view-ontology span.ont-garden-pinned-here {\n+body.view-ontology a.ont-garden-vote-ico {\n font-size: 0.95rem;\n line-height: 1;\n padding: 0.1rem 0.35rem;\n@@ -732,10 +731,14 @@ body.view-ontology a.ont-garden-vote-ico:hover {\n border-color: #a68e6b;\n background: #ebe6dc;\n }\n-body.view-ontology span.ont-garden-pinned-here {\n+body.view-ontology button.ont-garden-pin-ico-active {\n border-color: #1a4a8c;\n background: color-mix(in srgb, #1a4a8c 10%, #f7f3eb);\n- cursor: default;\n+ color: #0d2d5c;\n+}\n+body.view-ontology button.ont-garden-pin-ico-active:hover {\n+ border-color: #a68e6b;\n+ background: color-mix(in srgb, #1a4a8c 14%, #ebe6dc);\n }\n body.view-ontology form.ont-garden-pin-form {\n display: inline;\ndiff --git a/test/browser_garden_pin.clj b/test/browser_garden_pin.clj\nindex d4fa9ed60b45e872ec60e29307cfa61bcd9dd6b2..579976f4c2493a149f9eba081862ca07919f4fe9 100644\n--- a/test/browser_garden_pin.clj\n+++ b/test/browser_garden_pin.clj\n@@ -58,10 +58,11 @@\n (let [alice-token (oauth/fetch-bearer-token! base-url :username \"alice\")\n thread-tag \"browser-garden-pin\"\n raw (str \"# \" thread-tag \"\\n\\n\"\n- \"~/gp-pin-a {alpha}\\n\"\n- \"~/gp-pin-b {beta}\\n\"\n+ \"~/gp-parent {parent}\\n\"\n+ \"~/gp-parent/pin-a {alpha}\\n\"\n+ \"~/gp-parent/pin-b {beta}\\n\"\n \"{pin test vote}\\n\"\n- \"~/gp-pin-a 2:1 ~/gp-pin-b\\n\")\n+ \"~/gp-parent/pin-a 2:1 ~/gp-parent/pin-b\\n\")\n post-resp (oauth/http-post-json\n (str base-url \"/api/v0/rpc\")\n [{\"Post\" {\"room\" \"public\"\n@@ -77,23 +78,43 @@\n (core/with-page [pg (core/new-page-from-context ctx)]\n (page/navigate pg (str base-url \"/login\"))\n (is (wait-for-text pg \"body\" \"@alice\" 15000) \"alice session after login\")\n- (page/navigate pg (str base-url \"/~/gp-pin-a\"))\n- (is (wait-for-text pg \".ont-item-shell\" \"~/gp-pin-a\" 15000) \"on item a page\")\n+ (page/navigate pg (str base-url \"/~/gp-parent/pin-a\"))\n+ (is (wait-for-text pg \".ont-item-shell\" \"~/gp-parent/pin-a\" 15000) \"on item a page\")\n ;; Native form POST /ui (data-navigate=full) β€” not fetch/eval\n (locator/click (page/locator pg \".ont-item-pin-zone form.ont-pin-form button[type=submit]\"))\n- (is (wait-for-text pg \"#slug-pin-hud\" \"gp-pin-a\" 15000)\n+ (is (wait-for-text pg \"#slug-pin-hud\" \"gp-parent/pin-a\" 15000)\n \"HUD shows pinned item label after redirect\")\n- (page/navigate pg (str base-url \"/~/gp-pin-b\"))\n- (is (wait-for-text pg \".ont-item-shell\" \"~/gp-pin-b\" 15000) \"on item b page\")\n+ (page/navigate pg (str base-url \"/~/gp-parent/pin-b\"))\n+ (is (wait-for-text pg \".ont-item-shell\" \"~/gp-parent/pin-b\" 15000) \"on item b page\")\n (is (wait-for-text pg \"a.ont-vote-compare-btn\" \"vote\" 10000)\n \"vote link visible vs pinned item\")\n- ;; HUD clears pin (POST set_garden_pin clear), not navigate to item\n+ ;; Unpin from ranked child groups on parent page\n+ (page/navigate pg (str base-url \"/~/gp-parent\"))\n+ (is (wait-for-text pg \".ont-tab-panel-children\" \"ranked child groups\" 15000)\n+ \"parent page shows ranked child groups\")\n+ (is (wait-for-text pg \".ont-ranking-list button.ont-garden-pin-ico-active\" \"πŸ“Œ\" 10000)\n+ \"pinned row shows active pin in ranked list\")\n+ (locator/click (page/locator pg \".ont-ranking-list button.ont-garden-pin-ico-active\"))\n+ (is (wait-for-absence-substr pg \"#slug-pin-hud\" \"gp-parent/pin-a\" 15000)\n+ \"HUD clears after unpin from ranked child list\")\n+ (is (wait-for-absence-substr pg \".ont-ranking-list\" \"ont-garden-vote-ico\" 10000)\n+ \"vote icons removed from ranked list after unpin\")\n+ (page/navigate pg (str base-url \"/~/gp-parent/pin-b\"))\n+ (is (wait-for-text pg \".ont-item-shell\" \"~/gp-parent/pin-b\" 15000) \"on item b page again\")\n+ (is (wait-for-absence-substr pg \"body\" \"ont-vote-compare-btn\" 15000)\n+ \"compare vote CTA removed after ranked-list unpin\")\n+ ;; HUD unpin still works from item page context\n+ (page/navigate pg (str base-url \"/~/gp-parent/pin-a\"))\n+ (locator/click (page/locator pg \".ont-item-pin-zone form.ont-pin-form button[type=submit]\"))\n+ (is (wait-for-text pg \"#slug-pin-hud\" \"gp-parent/pin-a\" 15000)\n+ \"re-pin from item page for HUD unpin test\")\n+ (page/navigate pg (str base-url \"/~/gp-parent/pin-b\"))\n (locator/click (page/locator pg \"#slug-pin-hud button.slug-pin-hud-unpin-btn\"))\n- (is (wait-for-absence-substr pg \"#slug-pin-hud\" \"gp-pin-a\" 15000)\n+ (is (wait-for-absence-substr pg \"#slug-pin-hud\" \"gp-parent/pin-a\" 15000)\n \"HUD clears after unpin from HUD button\")\n (is (wait-for-absence-substr pg \"body\" \"ont-vote-compare-btn\" 15000)\n \"compare vote CTA removed after HUD unpin on same reload\")\n- (is (str/includes? (or (page/url pg) \"\") \"/~/gp-pin-b\")\n+ (is (str/includes? (or (page/url pg) \"\") \"/~/gp-parent/pin-b\")\n \"still on item b after HUD unpin\"))))))\n \n (finally\n\n\nSide B β€” contributor: tommy-mor\nSide B β€” commit message:\n[3b3d5873] item refactor\n\nSide B β€” 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","role":"user"}],"model":"openai/gpt-chat-latest"}