{"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[88577c56] reconfigure\n\nSide A — unified diff (full patch):\ndiff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs\nindex c4ab9d65c7b3cd42a5b4d093ba429993c101e9a8..82b2aa51d21ada1d0d849d3ddfc3a81e4241d861 100644\n--- a/server/src/api/ui_html.rs\n+++ b/server/src/api/ui_html.rs\n@@ -9,7 +9,9 @@ use crate::{\n html::{js_string_literal, ranking_panel, JsBuilder},\n parser::parse_reddit_url,\n parser_render::navigate_panel,\n- state::AppState,\n+ path_types::ItemId,\n+ reddit::ensure_partial_tree,\n+ state::{parse_item_param, AppState},\n ui_action::{parse_html_ui_from_form, HtmlUiAction},\n };\n \n@@ -25,6 +27,10 @@ fn ui_js_warn(msg: &str) -> Response {\n .unwrap()\n }\n \n+fn parent_from_scope(scope: &str) -> ItemId {\n+ parse_item_param(scope)\n+}\n+\n pub async fn post_ui_html(\n State(state): State,\n Form(form): Form>,\n@@ -42,24 +48,36 @@ pub async fn post_ui_html(\n ratio_right,\n scope,\n } => {\n+ let parent = parent_from_scope(&scope);\n if let Err(e) = state\n- .record_vote(&scope, &a, &b, ratio_left, ratio_right)\n+ .record_vote(&parent, &a, &b, ratio_left, ratio_right)\n .await\n {\n return ui_js_warn(&e).into_response();\n }\n- let scope = crate::state::normalize_scope(&scope);\n- let groups = state.groups.read().await;\n+ let tree = state.tree.read().await;\n let empty = crate::reducer::GroupState::new();\n- let group = groups.get(&scope).unwrap_or(&empty);\n- let panel = ranking_panel(&scope, group);\n+ let group = tree\n+ .get(&parent)\n+ .map(|n| &n.local_ranking)\n+ .unwrap_or(&empty);\n+ let panel = ranking_panel(&parent, group);\n JsBuilder::new()\n .morph_selector(\"#ranking-panel\", panel)\n .into_response()\n }\n HtmlUiAction::ParseQuery { query } => match parse_reddit_url(&query) {\n- Ok(subreddit) => {\n- let dest = format!(\"/?sub={subreddit}\");\n+ Ok(item) => {\n+ {\n+ let mut tree = state.tree.write().await;\n+ ensure_partial_tree(&mut tree, &item);\n+ }\n+ let _ = state.ensure_node(&item).await;\n+ let dest = if item.is_root() {\n+ \"/\".to_string()\n+ } else {\n+ format!(\"/?item={}\", item.as_str())\n+ };\n JsBuilder::new()\n .raw(&format!(\n \"window.location.href={};\",\ndiff --git a/server/src/events.rs b/server/src/events.rs\nindex a862370fc840ffe02184a11c578e18239cc9474d..ed5be6b13b9d46e838831d6ce0f96f569b401730 100644\n--- a/server/src/events.rs\n+++ b/server/src/events.rs\n@@ -5,8 +5,8 @@ use serde::{Deserialize, Serialize};\n pub enum Event {\n /// Page view recorded (path → counter in views.json).\n ViewRecorded { path: String, ts: i64 },\n- /// Pairwise comparison vote (replayed into the scope's [`crate::reducer::GroupState`] on boot).\n- /// `scope` is the ranking subject (e.g. a subreddit); empty string is the default/global scope.\n+ /// Pairwise comparison vote (replayed into the parent node's [`crate::reducer::GroupState`] on boot).\n+ /// `scope` is the parent [`crate::path_types::ItemId`] string; empty string is the tree root.\n VoteRecorded {\n ts: i64,\n a: String,\n@@ -16,4 +16,6 @@ pub enum Event {\n #[serde(default)]\n scope: String,\n },\n+ /// Register a node path in the fractal tree (no external fetch).\n+ NodeEnsured { id: String },\n }\ndiff --git a/server/src/html/mod.rs b/server/src/html/mod.rs\nindex 9650d333d29c4ac94ceb407aee3ee00399c7f40b..c973cb718ac74b95570dabea76e24459417790b9 100644\n--- a/server/src/html/mod.rs\n+++ b/server/src/html/mod.rs\n@@ -12,9 +12,10 @@ use serde::Deserialize;\n use crate::{\n form_template::template_json_compact,\n parser_render::navigate_panel,\n+ path_types::ItemId,\n ranking::{top_bottom, RankedItem},\n- reducer::GroupState,\n- state::{normalize_scope, AppState},\n+ reducer::{GroupState, NodeState},\n+ state::{parse_item_param, AppState},\n ui_action::UI_RPC_FIELD,\n };\n \n@@ -216,6 +217,48 @@ fn layout(title: &str, body: Markup, views: u64, theme: &str, theme_next: &str)\n }\n }\n \n+fn item_href(id: &ItemId) -> String {\n+ if id.is_root() {\n+ \"/\".to_string()\n+ } else {\n+ format!(\"/?item={}\", id.as_str())\n+ }\n+}\n+\n+fn segment_label(seg: &str) -> &str {\n+ seg\n+}\n+\n+/// Generic breadcrumb trail from an [`ItemId`] path.\n+pub fn breadcrumb_path(item: &ItemId) -> Markup {\n+ html! {\n+ nav class=\"breadcrumbs\" aria-label=\"Breadcrumb\" {\n+ a href=\"/\" { \"Internet\" }\n+ @for path in item.breadcrumb_paths() {\n+ @let seg = path.segments().last().map_or(\"\", |v| *v);\n+ span class=\"separator\" { \" / \" }\n+ a href=(item_href(&path)) { (segment_label(seg)) }\n+ }\n+ }\n+ }\n+}\n+\n+fn entity_panel(node: &NodeState) -> Markup {\n+ html! {\n+ @if let Some(data) = &node.data {\n+ section id=\"entity-panel\" class=\"demo-panel entity-card\" {\n+ h2 { (data.title) }\n+ @if let Some(author) = &data.author {\n+ p class=\"muted small\" { \"by \" (author) }\n+ }\n+ @if let Some(body) = &data.body_html {\n+ div class=\"entity-body\" { (maud::PreEscaped(body)) }\n+ }\n+ }\n+ }\n+ }\n+}\n+\n fn rank_list(label: &str, items: &[RankedItem], start_rank: usize) -> Markup {\n html! {\n @if !items.is_empty() {\n@@ -224,7 +267,9 @@ fn rank_list(label: &str, items: &[RankedItem], start_rank: usize) -> Markup {\n @for (i, r) in items.iter().enumerate() {\n li {\n span class=\"rank-num\" { (start_rank + i) \". \" }\n- strong { (r.item.as_str()) }\n+ a href=(item_href(&r.item)) {\n+ strong { (display_label(&r.item)) }\n+ }\n span class=\"muted\" {\n \" — \"\n ({ format!(\"{:.1}%\", r.score * 100.0) })\n@@ -236,23 +281,30 @@ fn rank_list(label: &str, items: &[RankedItem], start_rank: usize) -> Markup {\n }\n }\n \n-pub fn ranking_panel(scope: &str, group: &GroupState) -> Markup {\n+fn display_label(id: &ItemId) -> String {\n+ id.segments()\n+ .last()\n+ .map_or(\"Internet\", |v| *v)\n+ .to_string()\n+}\n+\n+pub fn ranking_panel(item: &ItemId, group: &GroupState) -> Markup {\n let total = group.idx_to_item.len();\n let (top, bottom) = top_bottom(group, 8);\n html! {\n section id=\"ranking-panel\" class=\"demo-panel\" {\n h2 {\n \"Ranking\"\n- @if !scope.is_empty() {\n- \" — \" span class=\"scope-name\" { \"r/\" (scope) }\n+ @if !item.is_root() {\n+ \" — \" span class=\"scope-name\" { (item.as_str()) }\n }\n }\n @if total == 0 {\n p class=\"muted\" {\n- @if scope.is_empty() {\n+ @if item.is_root() {\n \"No votes yet — compare two items below.\"\n } @else {\n- \"No votes yet for r/\" (scope) \" — compare two items below to start the ranking.\"\n+ \"No votes yet for \" (item.as_str()) \" — compare two items below to start the ranking.\"\n }\n }\n } @else {\n@@ -266,7 +318,8 @@ pub fn ranking_panel(scope: &str, group: &GroupState) -> Markup {\n }\n }\n \n-pub fn vote_panel(scope: &str) -> Markup {\n+pub fn vote_panel(parent: &ItemId) -> Markup {\n+ let parent_str = parent.as_str();\n let rpc = template_json_compact(&serde_json::json!({\n \"action\": \"record_vote\",\n \"a\": {\"$form\": \"item_a\"},\n@@ -280,16 +333,17 @@ pub fn vote_panel(scope: &str) -> Markup {\n section id=\"vote-panel\" class=\"demo-panel\" {\n h2 { \"Compare\" }\n p class=\"muted small\" {\n- @if scope.is_empty() {\n+ @if parent.is_root() {\n \"Left item wins at 2:1. Votes append to the JSONL log and update rank centrality.\"\n } @else {\n- \"Ranking \" span class=\"scope-name\" { \"r/\" (scope) }\n+ \"Ranking children of \"\n+ span class=\"scope-name\" { (parent_str) }\n \". Left item wins at 2:1; each vote updates this ranking.\"\n }\n }\n form method=\"post\" action=\"/ui\" id=\"vote-form\" {\n input type=\"hidden\" name=(UI_RPC_FIELD) value=(rpc);\n- input type=\"hidden\" name=\"scope\" value=(scope);\n+ input type=\"hidden\" name=\"scope\" value=(parent_str);\n div class=\"vote-fields\" {\n label {\n \"Left (wins) \"\n@@ -329,17 +383,30 @@ pub async fn home(\n let views = state.views.get_views(&path);\n let theme = theme_from_jar(&jar);\n let theme_next = theme_next_from_uri(&uri);\n- let scope = normalize_scope(&query_param(&uri, \"sub\").unwrap_or_default());\n \n- let groups = state.groups.read().await;\n- let empty = GroupState::new();\n- let group = groups.get(&scope).unwrap_or(&empty);\n+ let item_raw = query_param(&uri, \"item\")\n+ .or_else(|| query_param(&uri, \"sub\").map(|sub| {\n+ if sub.is_empty() {\n+ String::new()\n+ } else {\n+ format!(\"reddit.com/r/{sub}\")\n+ }\n+ }))\n+ .unwrap_or_default();\n+ let item = parse_item_param(&item_raw);\n+\n+ let tree = state.tree.read().await;\n+ let empty_node = NodeState::default();\n+ let node = tree.get(&item).unwrap_or(&empty_node);\n+ let group = &node.local_ranking;\n \n let body = html! {\n h1 { \"sorter2\" }\n+ (breadcrumb_path(&item))\n (navigate_panel(\"\", None))\n- (vote_panel(&scope))\n- (ranking_panel(&scope, group))\n+ (entity_panel(node))\n+ (vote_panel(&item))\n+ (ranking_panel(&item, group))\n };\n layout(\"sorter2\", body, views, theme, &theme_next)\n }\ndiff --git a/server/src/journal.rs b/server/src/journal.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..b02ca025683621470ffdf8cd85cf9b85c56d024d\n--- /dev/null\n+++ b/server/src/journal.rs\n@@ -0,0 +1,89 @@\n+use std::sync::Arc;\n+\n+use tokio::sync::{mpsc, oneshot, RwLock};\n+\n+use crate::{\n+ event_log::EventLog,\n+ events::Event,\n+ path_types::ItemId,\n+ reducer::{GlobalTree, VoteData},\n+};\n+\n+pub struct JournalCommand {\n+ pub parent: ItemId,\n+ pub vote: VoteData,\n+ pub event: Event,\n+ pub reply: oneshot::Sender>,\n+}\n+\n+#[derive(Clone)]\n+pub struct JournalClient {\n+ tx: mpsc::Sender,\n+}\n+\n+impl JournalClient {\n+ pub fn spawn(tree: Arc>, event_log: Arc) -> Self {\n+ let (tx, rx) = mpsc::channel(64);\n+ tokio::spawn(journal_worker(rx, tree, event_log));\n+ Self { tx }\n+ }\n+\n+ pub async fn record_vote(\n+ &self,\n+ parent: ItemId,\n+ vote: VoteData,\n+ event: Event,\n+ ) -> Result<(), String> {\n+ let (reply, rx) = oneshot::channel();\n+ self.tx\n+ .send(JournalCommand {\n+ parent,\n+ vote,\n+ event,\n+ reply,\n+ })\n+ .await\n+ .map_err(|_| \"journal worker stopped\".to_string())?;\n+ rx.await\n+ .map_err(|_| \"journal worker stopped\".to_string())?\n+ }\n+}\n+\n+async fn journal_worker(\n+ mut rx: mpsc::Receiver,\n+ tree: Arc>,\n+ event_log: Arc,\n+) {\n+ while let Some(first) = rx.recv().await {\n+ let mut batch = vec![first];\n+ while let Ok(more) = rx.try_recv() {\n+ batch.push(more);\n+ }\n+\n+ let mut disk_err: Option = None;\n+ for cmd in &batch {\n+ if let Err(e) = event_log.append(&cmd.event).await {\n+ disk_err = Some(e.to_string());\n+ break;\n+ }\n+ }\n+\n+ if let Some(err) = disk_err {\n+ for cmd in batch {\n+ let _ = cmd.reply.send(Err(err.clone()));\n+ }\n+ continue;\n+ }\n+\n+ {\n+ let mut w = tree.write().await;\n+ for cmd in &batch {\n+ w.apply_vote(&cmd.parent, cmd.vote.clone());\n+ }\n+ }\n+\n+ for cmd in batch {\n+ let _ = cmd.reply.send(Ok(()));\n+ }\n+ }\n+}\ndiff --git a/server/src/lib.rs b/server/src/lib.rs\nindex de8bca48cbf689cad22337883e7791966e7c4919..14e7cfbc38feb5d07aff859b64bce6e2ec45cf91 100644\n--- a/server/src/lib.rs\n+++ b/server/src/lib.rs\n@@ -7,8 +7,9 @@ pub mod parser;\n pub mod parser_render;\n pub mod path_types;\n pub mod ranking;\n+pub mod reddit;\n pub mod reducer;\n-pub mod settlement;\n+pub mod journal;\n pub mod state;\n pub mod ui_action;\n pub mod views;\ndiff --git a/server/src/parser.rs b/server/src/parser.rs\nindex 50571a59f0d3ece1e2538f88e00ef46ec40ea545..51aa0e0f982546aab68bd5e1ca0cb726e88b3f50 100644\n--- a/server/src/parser.rs\n+++ b/server/src/parser.rs\n@@ -1,47 +1,18 @@\n-//! Extract a subreddit name from a pasted Reddit URL or path.\n+//! Extract a canonical [`crate::path_types::ItemId`] from a pasted Reddit URL or path.\n \n-pub fn parse_reddit_url(query: &str) -> Result {\n+use crate::path_types::ItemId;\n+\n+pub fn parse_reddit_url(query: &str) -> Result {\n let q = query.trim();\n if q.is_empty() {\n return Err(\"Paste a Reddit URL or r/subreddit path\".into());\n }\n \n- if let Some(sub) = subreddit_after_prefix(q, \"r/\") {\n- return Ok(sub);\n- }\n-\n- if let Some(sub) = subreddit_from_path_segment(q, \"/r/\") {\n- return Ok(sub);\n+ if let Some(id) = ItemId::from_url(q) {\n+ return Ok(id);\n }\n \n- Err(\"Could not find a subreddit in that URL\".into())\n-}\n-\n-fn subreddit_after_prefix(text: &str, prefix: &str) -> Option {\n- let rest = text.strip_prefix(prefix)?;\n- let sub = rest.split(['/', '?', '#']).next()?.trim();\n- valid_subreddit(sub)\n-}\n-\n-fn subreddit_from_path_segment(text: &str, needle: &str) -> Option {\n- let idx = text.find(needle)?;\n- let rest = &text[idx + needle.len()..];\n- let sub = rest.split(['/', '?', '#']).next()?.trim();\n- valid_subreddit(sub)\n-}\n-\n-fn valid_subreddit(name: &str) -> Option {\n- if name.is_empty() {\n- return None;\n- }\n- if name\n- .chars()\n- .all(|c| c.is_ascii_alphanumeric() || c == '_')\n- {\n- Some(name.to_ascii_lowercase())\n- } else {\n- None\n- }\n+ Err(\"Could not parse that Reddit URL\".into())\n }\n \n #[cfg(test)]\n@@ -50,34 +21,37 @@ mod tests {\n \n #[test]\n fn parses_short_path() {\n- assert_eq!(parse_reddit_url(\"r/rust\").unwrap(), \"rust\");\n- }\n-\n- #[test]\n- fn parses_path_with_trailing_slash() {\n- assert_eq!(parse_reddit_url(\"r/rust/\").unwrap(), \"rust\");\n+ assert_eq!(\n+ parse_reddit_url(\"r/rust\").unwrap().as_str(),\n+ \"reddit.com/r/rust\"\n+ );\n }\n \n #[test]\n fn parses_full_url() {\n assert_eq!(\n- parse_reddit_url(\"https://www.reddit.com/r/programming/hot\").unwrap(),\n- \"programming\"\n+ parse_reddit_url(\"https://www.reddit.com/r/programming/hot\")\n+ .unwrap()\n+ .as_str(),\n+ \"reddit.com/r/programming\"\n );\n }\n \n #[test]\n- fn parses_url_without_scheme() {\n+ fn parses_post_url() {\n+ let id = parse_reddit_url(\n+ \"https://old.reddit.com/r/AmItheAsshole/comments/1trnvdl/aita_for_cancelling/\",\n+ )\n+ .unwrap();\n assert_eq!(\n- parse_reddit_url(\"reddit.com/r/AskReddit\").unwrap(),\n- \"askreddit\"\n+ id.as_str(),\n+ \"reddit.com/r/amitheasshole/comments/1trnvdl\"\n );\n }\n \n #[test]\n fn rejects_empty() {\n assert!(parse_reddit_url(\"\").is_err());\n- assert!(parse_reddit_url(\" \").is_err());\n }\n \n #[test]\ndiff --git a/server/src/parser_render.rs b/server/src/parser_render.rs\nindex f2341afe21476b689a536137798d97277211a962..acf2e7403f4238291677ef0c79d5766302ea78cf 100644\n--- a/server/src/parser_render.rs\n+++ b/server/src/parser_render.rs\n@@ -21,7 +21,7 @@ pub fn navigate_panel(query: &str, error: Option<&str>) -> Markup {\n p class=\"muted small\" {\n \"Paste a Reddit URL or \"\n code { \"r/subreddit\" }\n- \" path, then click Go to rank that subreddit.\"\n+ \" path. Breadcrumb links drill down the tree; rankings apply to each node's children.\"\n }\n form method=\"post\" action=\"/ui\" id=\"parser-form\" {\n textarea\ndiff --git a/server/src/path_types.rs b/server/src/path_types.rs\nindex 1cdc96a25b1954f11aaf955203e2b9907b578366..b5c41444f7bcd4d8d289ed3af464bc3f14d0df99 100644\n--- a/server/src/path_types.rs\n+++ b/server/src/path_types.rs\n@@ -1,11 +1,13 @@\n use serde::{Deserialize, Serialize};\n use std::fmt;\n \n-/// Stable item key for votes and rankings (opaque string for now).\n-#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]\n+/// Canonical hierarchical identity for any URL/path in the fractal tree.\n+#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Default)]\n pub struct ItemId(String);\n \n impl ItemId {\n+ /// Parse an already-canonical path (no URL normalization). Empty string is invalid here;\n+ /// use [`Self::root`] for the tree root.\n pub fn parse(s: &str) -> Option {\n let t = s.trim();\n if t.is_empty() {\n@@ -14,13 +16,170 @@ impl ItemId {\n Some(Self(t.to_string()))\n }\n \n+ /// Build an opaque item key (legacy demo votes, non-URL items).\n pub fn opaque(s: impl Into) -> Self {\n Self(s.into())\n }\n \n+ /// Root of the internet tree (empty path).\n+ pub fn root() -> Self {\n+ Self(String::new())\n+ }\n+\n+ pub fn is_root(&self) -> bool {\n+ self.0.is_empty()\n+ }\n+\n pub fn as_str(&self) -> &str {\n &self.0\n }\n+\n+ /// Creates a canonical ID from a raw URL or path. Normalizes domains and\n+ /// trims tracking query params.\n+ pub fn from_url(raw_url: &str) -> Option {\n+ Self::canonicalize(raw_url).map(Self)\n+ }\n+\n+ /// Map legacy scope keys (`\"\"`, `\"rust\"`) to fractal parent nodes.\n+ pub fn from_legacy_scope(raw: &str) -> Self {\n+ let s = raw.trim();\n+ if s.is_empty() {\n+ return Self::root();\n+ }\n+ Self(format!(\"reddit.com/r/{s}\"))\n+ }\n+\n+ /// Extract the parent, e.g. `reddit.com/r/aww/comments/1trnvdl` →\n+ /// `reddit.com/r/aww`.\n+ pub fn parent(&self) -> Option {\n+ if self.0.is_empty() {\n+ return None;\n+ }\n+\n+ let parts: Vec<&str> = self.0.trim_end_matches('/').split('/').collect();\n+ if parts.len() <= 1 {\n+ return None;\n+ }\n+\n+ if self.0.contains(\"/comments/\") {\n+ return Some(Self(parts[..parts.len().saturating_sub(2)].join(\"/\")));\n+ }\n+\n+ Some(Self(parts[..parts.len() - 1].join(\"/\")))\n+ }\n+\n+ pub fn segments(&self) -> Vec<&str> {\n+ self.0.split('/').filter(|s| !s.is_empty()).collect()\n+ }\n+\n+ /// Cumulative paths for breadcrumb rendering, e.g.\n+ /// `reddit.com/r/movies` → `[\"reddit.com\", \"reddit.com/r\", \"reddit.com/r/movies\"]`.\n+ pub fn breadcrumb_paths(&self) -> Vec {\n+ let segs = self.segments();\n+ let mut paths = Vec::with_capacity(segs.len());\n+ let mut current = String::new();\n+ for seg in segs {\n+ if current.is_empty() {\n+ current = seg.to_string();\n+ } else {\n+ current.push('/');\n+ current.push_str(seg);\n+ }\n+ paths.push(ItemId(current.clone()));\n+ }\n+ paths\n+ }\n+\n+ fn canonicalize(raw: &str) -> Option {\n+ let s = raw.trim();\n+ if s.is_empty() {\n+ return None;\n+ }\n+\n+ let owned = if let Some(rest) = s.strip_prefix(\"r/\") {\n+ format!(\"reddit.com/r/{rest}\")\n+ } else if let Some(rest) = s.strip_prefix(\"/r/\") {\n+ format!(\"reddit.com/r/{rest}\")\n+ } else {\n+ s.to_string()\n+ };\n+\n+ let (host_path, _query) = split_query(&owned);\n+ let host_path = host_path.trim_end_matches('/');\n+\n+ let path = if host_path.contains(\"://\") {\n+ parse_url_host_path(host_path)?\n+ } else if host_path.starts_with(\"reddit.com\") || host_path.starts_with(\"www.reddit.com\") {\n+ normalize_reddit_host_path(host_path)\n+ } else if host_path.contains('/') {\n+ host_path.to_string()\n+ } else {\n+ return None;\n+ };\n+\n+ Some(normalize_reddit_path(&path))\n+ }\n+}\n+\n+fn split_query(s: &str) -> (&str, Option<&str>) {\n+ if let Some((path, q)) = s.split_once('?') {\n+ (path, Some(q))\n+ } else {\n+ (s, None)\n+ }\n+}\n+\n+fn parse_url_host_path(url: &str) -> Option {\n+ let rest = url\n+ .strip_prefix(\"https://\")\n+ .or_else(|| url.strip_prefix(\"http://\"))\n+ .unwrap_or(url);\n+ let (host, path) = rest.split_once('/').unwrap_or((rest, \"\"));\n+ let host = normalize_host(host);\n+ if path.is_empty() {\n+ Some(host)\n+ } else {\n+ Some(format!(\"{host}/{path}\"))\n+ }\n+}\n+\n+fn normalize_host(host: &str) -> String {\n+ let h = host\n+ .strip_prefix(\"www.\")\n+ .unwrap_or(host)\n+ .to_ascii_lowercase();\n+ if h == \"old.reddit.com\" || h == \"new.reddit.com\" || h == \"reddit.com\" {\n+ \"reddit.com\".to_string()\n+ } else {\n+ h\n+ }\n+}\n+\n+fn normalize_reddit_host_path(s: &str) -> String {\n+ let (host, path) = s.split_once('/').unwrap_or((s, \"\"));\n+ let host = normalize_host(host);\n+ if path.is_empty() {\n+ host\n+ } else {\n+ format!(\"{host}/{path}\")\n+ }\n+}\n+\n+/// Lowercase subreddit segment, drop listing suffixes, drop title slug after post id.\n+fn normalize_reddit_path(path: &str) -> String {\n+ let mut parts: Vec = path.split('/').map(str::to_string).collect();\n+ if parts.len() >= 3 && parts[1] == \"r\" {\n+ parts[2] = parts[2].to_ascii_lowercase();\n+ }\n+ if let Some(i) = parts.iter().position(|p| p == \"comments\") {\n+ if parts.len() > i + 2 {\n+ parts.truncate(i + 2);\n+ }\n+ } else if parts.len() > 3 && parts.get(1).map(|s| s.as_str()) == Some(\"r\") {\n+ // reddit.com/r/{sub}/hot → reddit.com/r/{sub}\n+ parts.truncate(3);\n+ }\n+ parts.join(\"/\")\n }\n \n impl fmt::Display for ItemId {\n@@ -28,3 +187,69 @@ impl fmt::Display for ItemId {\n f.write_str(&self.0)\n }\n }\n+\n+#[cfg(test)]\n+mod tests {\n+ use super::*;\n+\n+ #[test]\n+ fn from_url_normalizes_reddit_domains() {\n+ let id = ItemId::from_url(\n+ \"https://old.reddit.com/r/AmItheAsshole/comments/1trnvdl/aita_for_cancelling/\",\n+ )\n+ .unwrap();\n+ assert_eq!(\n+ id.as_str(),\n+ \"reddit.com/r/amitheasshole/comments/1trnvdl\"\n+ );\n+ }\n+\n+ #[test]\n+ fn from_url_strips_query() {\n+ let id = ItemId::from_url(\"https://www.reddit.com/r/rust/?sort=top\").unwrap();\n+ assert_eq!(id.as_str(), \"reddit.com/r/rust\");\n+ }\n+\n+ #[test]\n+ fn from_url_short_path() {\n+ assert_eq!(\n+ ItemId::from_url(\"r/rust\").unwrap().as_str(),\n+ \"reddit.com/r/rust\"\n+ );\n+ }\n+\n+ #[test]\n+ fn parent_of_post_is_subreddit() {\n+ let id = ItemId::parse(\"reddit.com/r/aww/comments/1trnvdl\").unwrap();\n+ assert_eq!(\n+ id.parent().unwrap().as_str(),\n+ \"reddit.com/r/aww\"\n+ );\n+ }\n+\n+ #[test]\n+ fn parent_of_subreddit_is_r_segment() {\n+ let id = ItemId::parse(\"reddit.com/r/movies\").unwrap();\n+ assert_eq!(id.parent().unwrap().as_str(), \"reddit.com/r\");\n+ }\n+\n+ #[test]\n+ fn breadcrumb_paths() {\n+ let id = ItemId::parse(\"reddit.com/r/movies\").unwrap();\n+ let crumbs = id.breadcrumb_paths();\n+ let paths: Vec<_> = crumbs.iter().map(|p| p.as_str()).collect();\n+ assert_eq!(\n+ paths,\n+ vec![\"reddit.com\", \"reddit.com/r\", \"reddit.com/r/movies\"]\n+ );\n+ }\n+\n+ #[test]\n+ fn legacy_scope_maps_to_reddit_sub() {\n+ assert_eq!(\n+ ItemId::from_legacy_scope(\"rust\").as_str(),\n+ \"reddit.com/r/rust\"\n+ );\n+ assert!(ItemId::from_legacy_scope(\"\").is_root());\n+ }\n+}\ndiff --git a/server/src/reddit.rs b/server/src/reddit.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..d203dca09245daf869b3aa942898447700ae69fb\n--- /dev/null\n+++ b/server/src/reddit.rs\n@@ -0,0 +1,21 @@\n+//! Reddit API import (async, decoupled from UI request path).\n+\n+use crate::{\n+ path_types::ItemId,\n+ reducer::{EntityData, GlobalTree},\n+};\n+\n+/// Bootstrap blank nodes along a URL path so breadcrumbs and voting work before fetch.\n+pub fn ensure_partial_tree(tree: &mut GlobalTree, id: &ItemId) {\n+ tree.ensure_path(id);\n+}\n+\n+/// Placeholder for Reddit JSON import. Returns entity data when implemented.\n+pub async fn fetch_reddit_entity(_id: &ItemId) -> Option {\n+ None\n+}\n+\n+/// Apply fetched entity data to a node (called from async worker).\n+pub fn apply_entity(tree: &mut GlobalTree, id: &ItemId, data: EntityData) {\n+ tree.set_entity_data(id, data);\n+}\ndiff --git a/server/src/reducer.rs b/server/src/reducer.rs\nindex 8d28353e1f2a67e71b7d17a2041a0988150f3245..077f700bf00ddefe18ffd004bb5288bdc7c4adaf 100644\n--- a/server/src/reducer.rs\n+++ b/server/src/reducer.rs\n@@ -115,6 +115,96 @@ impl GroupState {\n }\n }\n \n+/// Structured data imported from Reddit or elsewhere.\n+#[derive(Debug, Clone, Serialize, Deserialize)]\n+pub struct EntityData {\n+ pub title: String,\n+ pub author: Option,\n+ pub body_html: Option,\n+ pub thumb_url: Option,\n+}\n+\n+/// One node in the fractal tree: entity + ranked children.\n+#[derive(Debug, Clone, Default)]\n+pub struct NodeState {\n+ pub id: ItemId,\n+ pub data: Option,\n+ pub children: HashSet,\n+ pub local_ranking: GroupState,\n+}\n+\n+impl NodeState {\n+ fn new(id: ItemId) -> Self {\n+ Self {\n+ id,\n+ ..Default::default()\n+ }\n+ }\n+}\n+\n+/// Global fractal graph: every URL is both an item and a ranking scope for its children.\n+#[derive(Default)]\n+pub struct GlobalTree {\n+ pub nodes: HashMap,\n+}\n+\n+impl GlobalTree {\n+ pub fn new() -> Self {\n+ let mut tree = Self::default();\n+ tree.ensure_node(&ItemId::root());\n+ tree\n+ }\n+\n+ pub fn ensure_node(&mut self, id: &ItemId) -> &mut NodeState {\n+ if !self.nodes.contains_key(id) {\n+ self.nodes.insert(id.clone(), NodeState::new(id.clone()));\n+ }\n+ self.nodes.get_mut(id).expect(\"node just inserted\")\n+ }\n+\n+ /// Register a node and wire parent→child links along the canonical path.\n+ pub fn ensure_path(&mut self, id: &ItemId) {\n+ if id.is_root() {\n+ self.ensure_node(id);\n+ return;\n+ }\n+ self.ensure_node(&ItemId::root());\n+ for path in id.breadcrumb_paths() {\n+ self.ensure_node(&path);\n+ if let Some(parent) = path.parent() {\n+ self.ensure_node(&parent);\n+ if let Some(p) = self.nodes.get_mut(&parent) {\n+ p.children.insert(path.clone());\n+ }\n+ } else if let Some(r) = self.nodes.get_mut(&ItemId::root()) {\n+ r.children.insert(path.clone());\n+ }\n+ }\n+ }\n+\n+ pub fn get(&self, id: &ItemId) -> Option<&NodeState> {\n+ self.nodes.get(id)\n+ }\n+\n+ pub fn apply_vote(&mut self, parent: &ItemId, vote: VoteData) {\n+ self.ensure_path(parent);\n+ self.ensure_path(&vote.a);\n+ self.ensure_path(&vote.b);\n+ if let Some(node) = self.nodes.get_mut(parent) {\n+ node.children.insert(vote.a.clone());\n+ node.children.insert(vote.b.clone());\n+ node.local_ranking.apply_vote(vote);\n+ }\n+ }\n+\n+ pub fn set_entity_data(&mut self, id: &ItemId, data: EntityData) {\n+ self.ensure_path(id);\n+ if let Some(node) = self.nodes.get_mut(id) {\n+ node.data = Some(data);\n+ }\n+ }\n+}\n+\n #[cfg(test)]\n mod from_recorded_tests {\n use super::*;\n@@ -125,7 +215,20 @@ mod from_recorded_tests {\n }\n \n #[test]\n- fn rejects_empty() {\n+ fn rejects_empty_pair() {\n assert!(VoteData::from_recorded(1, \"\", \"b\", 2, 1).is_none());\n }\n+\n+ #[test]\n+ fn ensure_path_wires_children() {\n+ let mut tree = GlobalTree::new();\n+ let id = ItemId::parse(\"reddit.com/r/rust\").unwrap();\n+ tree.ensure_path(&id);\n+ let root = tree.get(&ItemId::root()).unwrap();\n+ assert!(root.children.contains(&ItemId::parse(\"reddit.com\").unwrap()));\n+ let reddit = tree.get(&ItemId::parse(\"reddit.com\").unwrap()).unwrap();\n+ assert!(reddit.children.contains(&ItemId::parse(\"reddit.com/r\").unwrap()));\n+ let sub = tree.get(&id).unwrap();\n+ assert_eq!(sub.id, id);\n+ }\n }\ndiff --git a/server/src/settlement.rs b/server/src/settlement.rs\ndeleted file mode 100644\nindex 7a44495512b7f788239b8aeefbbd0a83656eeac6..0000000000000000000000000000000000000000\n--- a/server/src/settlement.rs\n+++ /dev/null\n@@ -1,94 +0,0 @@\n-use std::collections::HashMap;\n-use std::sync::Arc;\n-\n-use tokio::sync::{mpsc, oneshot, RwLock};\n-\n-use crate::{\n- event_log::EventLog,\n- events::Event,\n- reducer::{GroupState, VoteData},\n-};\n-\n-/// Per-scope ranking state, keyed by scope (e.g. subreddit; \"\" is the default scope).\n-pub type GroupMap = HashMap;\n-\n-pub struct SettlementCommand {\n- pub scope: String,\n- pub vote: VoteData,\n- pub event: Event,\n- pub reply: oneshot::Sender>,\n-}\n-\n-#[derive(Clone)]\n-pub struct SettlementClient {\n- tx: mpsc::Sender,\n-}\n-\n-impl SettlementClient {\n- pub fn spawn(groups: Arc>, event_log: Arc) -> Self {\n- let (tx, rx) = mpsc::channel(64);\n- tokio::spawn(settlement_worker(rx, groups, event_log));\n- Self { tx }\n- }\n-\n- pub async fn record_vote(\n- &self,\n- scope: String,\n- vote: VoteData,\n- event: Event,\n- ) -> Result<(), String> {\n- let (reply, rx) = oneshot::channel();\n- self.tx\n- .send(SettlementCommand {\n- scope,\n- vote,\n- event,\n- reply,\n- })\n- .await\n- .map_err(|_| \"settlement worker stopped\".to_string())?;\n- rx.await\n- .map_err(|_| \"settlement worker stopped\".to_string())?\n- }\n-}\n-\n-async fn settlement_worker(\n- mut rx: mpsc::Receiver,\n- groups: Arc>,\n- event_log: Arc,\n-) {\n- while let Some(first) = rx.recv().await {\n- let mut batch = vec![first];\n- while let Ok(more) = rx.try_recv() {\n- batch.push(more);\n- }\n-\n- let mut disk_err: Option = None;\n- for cmd in &batch {\n- if let Err(e) = event_log.append(&cmd.event).await {\n- disk_err = Some(e.to_string());\n- break;\n- }\n- }\n-\n- if let Some(err) = disk_err {\n- for cmd in batch {\n- let _ = cmd.reply.send(Err(err.clone()));\n- }\n- continue;\n- }\n-\n- {\n- let mut w = groups.write().await;\n- for cmd in &batch {\n- w.entry(cmd.scope.clone())\n- .or_default()\n- .apply_vote(cmd.vote.clone());\n- }\n- }\n-\n- for cmd in batch {\n- let _ = cmd.reply.send(Ok(()));\n- }\n- }\n-}\ndiff --git a/server/src/state.rs b/server/src/state.rs\nindex 2d9e5226057f8615897aac48bce947643a230fb4..cc1722f5a5bf4d415f2327ea585c488a15a75592 100644\n--- a/server/src/state.rs\n+++ b/server/src/state.rs\n@@ -1,4 +1,3 @@\n-use std::collections::HashMap;\n use std::sync::Arc;\n \n use tokio::sync::RwLock;\n@@ -6,14 +5,22 @@ use tokio::sync::RwLock;\n use crate::{\n event_log::EventLog,\n events::Event,\n- reducer::VoteData,\n- settlement::{GroupMap, SettlementClient},\n+ path_types::ItemId,\n+ reducer::{GlobalTree, VoteData},\n+ journal::JournalClient,\n views::ViewStore,\n };\n \n-/// Normalize a raw ranking subject into a scope key: strip an optional `r/`\n-/// prefix, keep only `[a-z0-9_]`, lowercase, and cap the length. Empty string\n-/// is the default/global scope.\n+/// Parse `?item=` query value into a canonical node id.\n+pub fn parse_item_param(raw: &str) -> ItemId {\n+ let s = raw.trim();\n+ if s.is_empty() {\n+ return ItemId::root();\n+ }\n+ ItemId::from_url(s).or_else(|| ItemId::parse(s)).unwrap_or_else(|| ItemId::opaque(s))\n+}\n+\n+/// Legacy: normalize raw ranking subject into a scope key for old event replay.\n pub fn normalize_scope(raw: &str) -> String {\n let s = raw.trim();\n let s = s\n@@ -27,6 +34,14 @@ pub fn normalize_scope(raw: &str) -> String {\n .collect()\n }\n \n+fn parent_from_event_scope(scope: &str) -> ItemId {\n+ if scope.contains('/') {\n+ ItemId::parse(scope).unwrap_or_else(|| ItemId::from_legacy_scope(scope))\n+ } else {\n+ ItemId::from_legacy_scope(scope)\n+ }\n+}\n+\n #[derive(Clone)]\n pub struct AppConfig {\n pub data_dir: String,\n@@ -56,8 +71,8 @@ pub struct AppState {\n pub cfg: Arc,\n pub event_log: Arc,\n pub views: ViewStore,\n- pub groups: Arc>,\n- settlement: SettlementClient,\n+ pub tree: Arc>,\n+ journal: JournalClient,\n }\n \n impl AppState {\n@@ -66,7 +81,7 @@ impl AppState {\n let views_path = format!(\"{}/views.json\", cfg.data_dir);\n let views = ViewStore::new(&views_path);\n \n- let mut groups: GroupMap = HashMap::new();\n+ let mut tree = GlobalTree::new();\n if let Ok((events, _)) = event_log.load_all().await {\n for ev in events {\n match ev {\n@@ -81,29 +96,45 @@ impl AppState {\n if let Some(vote) =\n VoteData::from_recorded(ts, &a, &b, ratio_left, ratio_right)\n {\n- groups.entry(scope).or_default().apply_vote(vote);\n+ let parent = parent_from_event_scope(&scope);\n+ tree.apply_vote(&parent, vote);\n }\n }\n Event::ViewRecorded { .. } => {}\n+ Event::NodeEnsured { id } => {\n+ if let Some(parsed) = ItemId::parse(&id).or_else(|| ItemId::from_url(&id)) {\n+ tree.ensure_path(&parsed);\n+ }\n+ }\n }\n }\n }\n \n- let groups = Arc::new(RwLock::new(groups));\n- let settlement = SettlementClient::spawn(groups.clone(), event_log.clone());\n+ let tree = Arc::new(RwLock::new(tree));\n+ let journal = JournalClient::spawn(tree.clone(), event_log.clone());\n \n Self {\n cfg: Arc::new(cfg),\n event_log,\n views,\n- groups,\n- settlement,\n+ tree,\n+ journal,\n }\n }\n \n+ pub async fn ensure_node(&self, id: &ItemId) -> Result<(), String> {\n+ let event = Event::NodeEnsured {\n+ id: id.as_str().to_string(),\n+ };\n+ self.event_log.append(&event).await.map_err(|e| e.to_string())?;\n+ let mut w = self.tree.write().await;\n+ w.ensure_path(id);\n+ Ok(())\n+ }\n+\n pub async fn record_vote(\n &self,\n- scope: &str,\n+ parent: &ItemId,\n a: &str,\n b: &str,\n ratio_left: i32,\n@@ -113,23 +144,24 @@ impl AppState {\n let vote = VoteData::from_recorded(ts, a, b, ratio_left, ratio_right)\n .ok_or_else(|| \"invalid vote: need two distinct non-empty items\".to_string())?;\n \n- let scope = normalize_scope(scope);\n let event = Event::VoteRecorded {\n ts,\n a: vote.a.as_str().to_string(),\n b: vote.b.as_str().to_string(),\n ratio_left: vote.ratio_left,\n ratio_right: vote.ratio_right,\n- scope: scope.clone(),\n+ scope: parent.as_str().to_string(),\n };\n \n- self.settlement.record_vote(scope, vote, event).await\n+ self.journal\n+ .record_vote(parent.clone(), vote, event)\n+ .await\n }\n }\n \n #[cfg(test)]\n mod tests {\n- use super::normalize_scope;\n+ use super::{normalize_scope, parse_item_param};\n \n #[test]\n fn normalize_scope_strips_prefix_and_lowercases() {\n@@ -138,4 +170,15 @@ mod tests {\n assert_eq!(normalize_scope(\"r/web_dev!!\"), \"web_dev\");\n assert_eq!(normalize_scope(\"\"), \"\");\n }\n+\n+ #[test]\n+ fn parse_item_param_from_url() {\n+ let id = parse_item_param(\"https://reddit.com/r/rust\");\n+ assert_eq!(id.as_str(), \"reddit.com/r/rust\");\n+ }\n+\n+ #[test]\n+ fn parse_item_param_empty_is_root() {\n+ assert!(parse_item_param(\"\").is_root());\n+ }\n }\ndiff --git a/server/src/ui_action.rs b/server/src/ui_action.rs\nindex 0e030b3448b8e45acbe49d2de47ea26372445c54..d798874d1d94c0dfee59ec1ff703f9ee6ef432c0 100644\n--- a/server/src/ui_action.rs\n+++ b/server/src/ui_action.rs\n@@ -18,7 +18,7 @@ pub enum HtmlUiAction {\n b: String,\n ratio_left: i32,\n ratio_right: i32,\n- /// Ranking subject (e.g. a subreddit). Empty string = default/global scope.\n+ /// Parent node [`ItemId`] string; empty = tree root.\n #[serde(default)]\n scope: String,\n },\ndiff --git a/server/static/theme_default.css b/server/static/theme_default.css\nindex 6ad0ac712bbc840bedee60f613794de9385fbbd1..1bf8ac7a25207336c019f93cd4119bd0e06229f0 100644\n--- a/server/static/theme_default.css\n+++ b/server/static/theme_default.css\n@@ -137,6 +137,38 @@ code {\n margin-top: 0.5rem;\n }\n \n+.breadcrumbs {\n+ font-size: 0.875rem;\n+ margin-bottom: 1rem;\n+ color: var(--muted);\n+}\n+\n+.breadcrumbs a {\n+ color: var(--accent);\n+ text-decoration: none;\n+}\n+\n+.breadcrumbs a:hover {\n+ text-decoration: underline;\n+}\n+\n+.breadcrumbs .separator {\n+ color: var(--muted);\n+}\n+\n+.rank-list a {\n+ color: var(--accent);\n+ text-decoration: none;\n+}\n+\n+.rank-list a:hover {\n+ text-decoration: underline;\n+}\n+\n+.entity-card h2 {\n+ margin-top: 0;\n+}\n+\n .scope-name {\n color: var(--accent);\n font-weight: 600;\ndiff --git a/server/tests/integration_ui.rs b/server/tests/integration_ui.rs\nindex afeeee24e32f2d7f1d852ca96ac799fac8bce665..f7ac9c26bf9f9277ad5f5708603224c095165fb8 100644\n--- a/server/tests/integration_ui.rs\n+++ b/server/tests/integration_ui.rs\n@@ -2,7 +2,7 @@ use std::collections::HashMap;\n use std::net::SocketAddr;\n \n use axum::Router;\n-use sorter2_server::{create_app, create_app_state, state::AppConfig, ui_action::UI_RPC_FIELD};\n+use sorter2_server::{create_app, create_app_state, path_types::ItemId, state::AppConfig, ui_action::UI_RPC_FIELD};\n use tempfile::TempDir;\n use tokio::net::TcpListener;\n \n@@ -63,9 +63,9 @@ async fn post_ui_record_vote_morphs_ranking_and_persists() {\n port: 0,\n };\n let state = create_app_state(cfg).await;\n- let groups = state.groups.read().await;\n- let group = groups.get(\"\").expect(\"default scope group after replay\");\n- let ranked = sorter2_server::ranking::ranked_items(group);\n+ let tree = state.tree.read().await;\n+ let root = tree.get(&ItemId::root()).expect(\"root node after replay\");\n+ let ranked = sorter2_server::ranking::ranked_items(&root.local_ranking);\n assert_eq!(ranked.len(), 2);\n assert_eq!(ranked[0].item.as_str(), \"alpha\");\n }\n@@ -93,5 +93,5 @@ async fn post_ui_parse_query_redirects_to_subreddit() {\n .unwrap();\n \n assert!(body.contains(\"window.location.href\"));\n- assert!(body.contains(\"/?sub=rust\"));\n+ assert!(body.contains(\"/?item=reddit.com/r/rust\"));\n }\n\n\nSide B — contributor: tommy-mor\nSide B — commit message:\n[7caef802] room ui wired up again\n\nSide B — unified diff (full patch):\ndiff --git a/Cargo.lock b/Cargo.lock\nindex e31485f28717993a13e1c4caf7be15b43a97573e..8be6ff8677700ce0a56d4a53b221e25c2bb70507 100644\n--- a/Cargo.lock\n+++ b/Cargo.lock\n@@ -158,6 +158,7 @@ dependencies = [\n \"axum\",\n \"axum-core\",\n \"bytes\",\n+ \"cookie\",\n \"fastrand\",\n \"futures-util\",\n \"http\",\n@@ -300,6 +301,17 @@ version = \"1.0.4\"\n source = \"registry+https://github.com/rust-lang/crates.io-index\"\n checksum = \"b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75\"\n \n+[[package]]\n+name = \"cookie\"\n+version = \"0.18.1\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747\"\n+dependencies = [\n+ \"percent-encoding\",\n+ \"time\",\n+ \"version_check\",\n+]\n+\n [[package]]\n name = \"core-foundation\"\n version = \"0.9.4\"\ndiff --git a/plan2.md b/plan2.md\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..1587cbe558eb0a98fbce78566bf5f93b18100e54\n--- /dev/null\n+++ b/plan2.md\n@@ -0,0 +1,190 @@\n+This is a phenomenal synthesis. You stripped away the exact parts of `evaleval` that don't scale to a multi-tenant web application (string-splicing `eval` and in-memory nonce OCAP tracking) and kept the parts that make development lightning fast (embedded declarative payloads, single endpoint routing, and Javascript AST responses). \n+\n+You are entirely right about the **AST substitution in Rust**. Walking a `serde_json::Value` tree to find `{\"$form\": \"field_name\"}` and swapping the node for a String isn't a hack—in Rust, it’s just a completely standard recursive enum visitor. \n+\n+Let’s lock in this exact architecture. It is cohesive, secure, and incredibly ergonomic.\n+\n+Here is what the code actually looks like to execute this vision.\n+\n+---\n+\n+### 1. The Safe AST Substitution\n+\n+This is the exact function that runs in the Web handler before giving the payload to the RPC engine. Because it operates on the JSON AST *before* deserialization, it's 100% immune to injection.\n+\n+```rust\n+use serde_json::Value;\n+use std::collections::HashMap;\n+\n+/// Recursively walk the JSON AST and replace {\"$form\": \"key\"} with the actual form string.\n+fn substitute_form_vars(val: &mut Value, form_data: &HashMap) {\n+ match val {\n+ Value::Object(map) => {\n+ // Is this the magic placeholder node? {\"$form\": \"input_name\"}\n+ if map.len() == 1 && map.contains_key(\"$form\") {\n+ if let Some(field_name) = map.get(\"$form\").and_then(|v| v.as_str()) {\n+ let submitted_text = form_data.get(field_name).map(|s| s.as_str()).unwrap_or(\"\");\n+ *val = Value::String(submitted_text.to_string());\n+ return;\n+ }\n+ }\n+ // Otherwise, keep walking the object\n+ for v in map.values_mut() {\n+ substitute_form_vars(v, form_data);\n+ }\n+ }\n+ Value::Array(arr) => {\n+ // Walk arrays\n+ for v in arr.iter_mut() {\n+ substitute_form_vars(v, form_data);\n+ }\n+ }\n+ _ => {} // Primitives stay as is\n+ }\n+}\n+```\n+**Why this rules:** You can write a single, hidden HTML input: \n+``\n+When the form submits, the backend safely turns it into standard RPC input.\n+\n+---\n+\n+### 2. The Unified Core RPC Layer\n+\n+You keep exactly one execution layer that strictly enforces your domain constraints (ACLs). Whether the command originated from a CLI script or a web form, they all hit this choke point:\n+\n+```rust\n+// Core execute function, decoupled from HTTP\n+pub async fn execute_rpc(\n+ state: &ReducerState, \n+ principal: &Principal, \n+ command: RpcCommand\n+) -> Result {\n+ match command {\n+ RpcCommand::Ingest { space, text } => {\n+ // ACLs are checked RIGHT HERE, universally.\n+ if !state.user_has_cap(&space, principal, ThreadCapability::Post) {\n+ return Err(ApiError::Forbidden(\"No post access in this space\".to_string()));\n+ }\n+ // Do the write, apply events...\n+ Ok(RpcResponse::IngestOk { ... })\n+ }\n+ // ...\n+ }\n+}\n+```\n+\n+---\n+\n+### 3. The `DomPatch` Builder Pattern\n+\n+You prefer the Builder pattern over a macro for the response mapping. I agree—builders are far easier for your IDE to autocomplete, and easier to compose dynamically (e.g., iterating over a list of items to append).\n+\n+```rust\n+pub struct DomPatch {\n+ js: String,\n+}\n+\n+impl DomPatch {\n+ pub fn new() -> Self {\n+ Self { js: String::new() }\n+ }\n+\n+ /// Morphs an element using Idiomorph\n+ pub fn morph(mut self, selector: &str, html: &str) -> Self {\n+ let safe_html = serde_json::to_string(html).expect(\"string escaping failed\");\n+ self.js.push_str(&format!(\n+ \"Idiomorph.morph(document.querySelector('{}'), {}, {{morphStyle: 'innerHTML'}});\\n\", \n+ selector, safe_html\n+ ));\n+ self\n+ }\n+\n+ /// Appends raw HTML to an element\n+ pub fn append(mut self, selector: &str, html: &str) -> Self {\n+ let safe_html = serde_json::to_string(html).unwrap();\n+ self.js.push_str(&format!(\n+ \"document.querySelector('{}')?.insertAdjacentHTML('beforeend', {});\\n\", \n+ selector, safe_html\n+ ));\n+ self\n+ }\n+\n+ /// Executes raw javascript\n+ pub fn eval(mut self, code: &str) -> Self {\n+ self.js.push_str(code);\n+ self.js.push('\\n');\n+ self\n+ }\n+\n+ /// Consumes the builder into an HTTP Response with the right content-type\n+ pub fn into_response(self) -> impl axum::response::IntoResponse {\n+ (\n+ axum::http::StatusCode::OK, \n+ [(axum::http::header::CONTENT_TYPE, \"text/javascript\")], \n+ self.js\n+ )\n+ }\n+}\n+```\n+\n+---\n+\n+### 4. The Single Web Handler (`POST /ui/action`)\n+\n+With the pipeline defined, you only ever have to write **one** `POST` handler for the entire Web UI.\n+\n+```rust\n+pub async fn handle_web_action(\n+ State(state): State,\n+ headers: HeaderMap,\n+ Form(form_data): Form>, // Captures everything dynamically\n+) -> impl IntoResponse {\n+ // 1. Authenticate using Bearer / Cookie exactly like the CLI\n+ let principal = match extract_web_session(&headers, &state) {\n+ Ok(p) => p,\n+ Err(_) => return DomPatch::new().eval(\"window.location = '/auth/login';\").into_response(),\n+ };\n+\n+ // 2. Decode the Base64 JSON\n+ let b64 = form_data.get(\"__rpc__\").expect(\"Missing RPC payload in form\");\n+ let decoded = base64::decode(b64).expect(\"Bad b64\");\n+ let mut json_ast: Value = serde_json::from_slice(&decoded).expect(\"Bad JSON\");\n+\n+ // 3. Do AST Substitution!\n+ substitute_form_vars(&mut json_ast, &form_data);\n+\n+ // 4. Parse it strongly into the RPC enum\n+ let command: RpcCommand = serde_json::from_value(json_ast).expect(\"Invalid RpcCommand\");\n+\n+ // 5. Pass it to the core execute function (authz + mutation happens here)\n+ match execute_rpc(&state.reduced.read().await, &principal, command).await {\n+ Ok(RpcResponse::IngestOk { new_ranks }) => {\n+ // Translate the RpcResponse to UI JS snippets\n+ DomPatch::new()\n+ .morph(\"#rank-container\", &render_ranking(&new_ranks))\n+ .eval(\"document.getElementById('ingest-form').reset();\")\n+ .into_response()\n+ }\n+ Ok(_) => DomPatch::new().eval(\"console.log('Action complete');\").into_response(),\n+ Err(e) => {\n+ // Reconcile errors\n+ DomPatch::new()\n+ .morph(\"#error-banner\", &format!(\"
{}
\", e.message()))\n+ .into_response()\n+ }\n+ }\n+}\n+```\n+\n+### The Verdict on the Grand Architecture\n+\n+By combining:\n+1. The **Domain-Driven Asymmetry** (Spaces contain Gardens & Threads)\n+2. The **Core RPC Logic** (1 executor, `Vec`, strict ACL checks)\n+3. The **Single Web Form Controller** (b64 embedded, `substitute_form_vars()`)\n+4. The **Javascript DomPatch Builder**\n+\n+You have constructed an application architecture that gives you absolute security and data integrity for your CLI AI Agents, while keeping the absolute peak hackability, form simplicity, and lightning-fast JS UI diffing of your `evaleval` Python framework. \n+\n+I'm sold. It is clean, it is uniquely fitted to the mechanics of Rust (`serde`, `enums`), and it solves the URL routing fatigue problem beautifully. This is the exact way to build `slug.social` v2.\n\\ No newline at end of file\ndiff --git a/server/Cargo.toml b/server/Cargo.toml\nindex d527f86532c2856e29f9c6265e54c7235fdf0a8c..18c45777d662b71dc309e1daa4ddb2944da9759d 100644\n--- a/server/Cargo.toml\n+++ b/server/Cargo.toml\n@@ -6,7 +6,7 @@ license = \"MIT\"\n \n [dependencies]\n axum = { version = \"0.7\", features = [\"macros\"] }\n-axum-extra = { version = \"0.9\", features = [\"query\"] }\n+axum-extra = { version = \"0.9\", features = [\"query\", \"cookie\"] }\n bytes = \"1.11.1\" # pin: RUSTSEC-2026-0007\n tokio = { version = \"1\", features = [\"rt-multi-thread\", \"macros\", \"signal\", \"fs\", \"io-util\"] }\n tokio-stream = { version = \"0.1\", features = [\"sync\"] }\ndiff --git a/server/src/api/auth.rs b/server/src/api/auth.rs\nindex b45ba39419c84af8bf2333fc9b7d47e98525c45f..2524a3ffcb5ea9ef6259cb9bb0bf12119bd840d2 100644\n--- a/server/src/api/auth.rs\n+++ b/server/src/api/auth.rs\n@@ -1,9 +1,11 @@\n use axum::{\n+ body::Body,\n extract::{Path, Query, State},\n- http::{HeaderMap, StatusCode},\n- response::{IntoResponse, Redirect},\n+ http::{header, HeaderMap, HeaderValue, StatusCode},\n+ response::{IntoResponse, Redirect, Response},\n Form, Json,\n };\n+use axum_extra::extract::cookie::CookieJar;\n use base64::Engine;\n use serde::Deserialize;\n use slug_types::{PendingSessionPollResponse, PendingSessionStartRequest, PendingSessionStartResponse, WhoamiResponse};\n@@ -13,14 +15,47 @@ use tokio::sync::RwLock;\n use crate::{\n api::helpers::{api_error, now_ms, sha256_hex},\n events::{Event, GrantAdded, TokenIssued, UserRegistered},\n- identity::{parse_agent, parse_username},\n html::{auth_complete_page, auth_signed_in_fragment, choose_username_error_fragment, choose_username_page},\n+ identity::{parse_agent, parse_username},\n+ reducer::ReducerState,\n state::{AppState, PendingSession},\n };\n \n /// Delegate id for browser users who land via `/join/inv_…` (no CLI agent).\n const INVITE_BROWSER_AGENT: &str = \"00000000-0000-0000-0000-000000000000:invite:web/join\";\n \n+/// Agent id for `/login` browser OAuth (no CLI); must pass [`parse_agent`].\n+const WEB_BROWSER_AGENT: &str = \"00000000-0000-0000-0000-000000000001:social:web/browser\";\n+\n+/// HttpOnly cookie storing the same `slug_*` bearer string the CLI uses.\n+pub const SLUG_SESSION_COOKIE: &str = \"slug_session\";\n+\n+/// `Set-Cookie` header value (full attribute string).\n+pub fn session_cookie_header_value(bearer: &str) -> HeaderValue {\n+ let s = format!(\n+ \"{SLUG_SESSION_COOKIE}={bearer}; Path=/; HttpOnly; SameSite=Lax; Max-Age=31536000\"\n+ );\n+ HeaderValue::from_str(&s).expect(\"session cookie value must be ASCII\")\n+}\n+\n+/// Resolve the signed-in username from `Authorization: Bearer` or `slug_session` cookie.\n+pub fn optional_principal(headers: &HeaderMap, jar: &CookieJar, reduced: &ReducerState) -> Option {\n+ if let Ok(u) = verify_bearer_principal(headers, reduced) {\n+ return Some(u);\n+ }\n+ let c = jar.get(SLUG_SESSION_COOKIE)?;\n+ verify_token(reduced, c.value()).ok()\n+}\n+\n+fn redirect_with_session_cookie(public_url: &str, path_and_query: &str, bearer: &str) -> Response {\n+ Response::builder()\n+ .status(StatusCode::TEMPORARY_REDIRECT)\n+ .header(header::LOCATION, format!(\"{public_url}{path_and_query}\"))\n+ .header(header::SET_COOKIE, session_cookie_header_value(bearer))\n+ .body(Body::empty())\n+ .unwrap()\n+}\n+\n async fn apply_invite_redemption(state: &AppState, invite_token: &str, grantee_username: &str) -> Result<(), String> {\n let now = now_ms();\n let ga = {\n@@ -306,8 +341,9 @@ pub async fn get_auth_callback(Query(q): Query, State(state):\n tracing::warn!(error = %e, \"invite redemption skipped after oauth\");\n }\n }\n+ let cookie_bearer = bearer.clone();\n s.complete = Some((username, bearer));\n- return Redirect::temporary(&format!(\"{public_url}/auth/complete\")).into_response();\n+ return redirect_with_session_cookie(&public_url, \"/\", &cookie_bearer).into_response();\n }\n }\n \n@@ -418,7 +454,47 @@ pub async fn post_choose_username(\n s.complete = Some((canon_user.clone(), bearer.clone()));\n }\n \n- auth_signed_in_fragment().into_response()\n+ Response::builder()\n+ .status(StatusCode::OK)\n+ .header(header::CONTENT_TYPE, \"text/html; charset=utf-8\")\n+ .header(header::SET_COOKIE, session_cookie_header_value(&bearer))\n+ .body(Body::from(auth_signed_in_fragment().into_string()))\n+ .unwrap()\n+ .into_response()\n+}\n+\n+/// Start a browser-only OAuth flow (no CLI polling). Sets session cookie on success.\n+pub async fn get_web_login(State(state): State) -> impl IntoResponse {\n+ let session = format!(\"p_{}\", uuid::Uuid::new_v4().simple());\n+ let s = PendingSession {\n+ agent: WEB_BROWSER_AGENT.to_string(),\n+ created_ts: now_ms(),\n+ provider: None,\n+ provider_id: None,\n+ redeem_invite: None,\n+ complete: None,\n+ };\n+ state.pending_sessions.write().await.insert(session.clone(), s);\n+ let public_url = std::env::var(\"SLUG_PUBLIC_URL\").unwrap_or_else(|_| \"http://127.0.0.1:8080\".to_string());\n+ Redirect::temporary(&format!(\n+ \"{public_url}/auth/login?session={}\",\n+ urlencoding::encode(&session)\n+ ))\n+ .into_response()\n+}\n+\n+pub async fn get_logout() -> impl IntoResponse {\n+ let clear = format!(\"{SLUG_SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0\");\n+ Response::builder()\n+ .status(StatusCode::TEMPORARY_REDIRECT)\n+ .header(header::LOCATION, \"/\")\n+ .header(\n+ header::SET_COOKIE,\n+ HeaderValue::from_str(&clear).expect(\"static cookie clears\"),\n+ )\n+ .body(Body::empty())\n+ .unwrap()\n+ .into_response()\n }\n \n pub async fn post_pending_session(\ndiff --git a/server/src/api/mod.rs b/server/src/api/mod.rs\nindex cb031aecebad1107dfa2898a98fb6084b28ba6e9..5320345a33bbb7b5ab769696a31f70347d019c3e 100644\n--- a/server/src/api/mod.rs\n+++ b/server/src/api/mod.rs\n@@ -1,7 +1,9 @@\n mod auth;\n mod helpers;\n mod rpc;\n+mod stream;\n mod validate;\n+mod web_post;\n \n pub use auth::{\n get_join_invite,\n@@ -13,6 +15,11 @@ pub use auth::{\n get_auth_callback,\n get_auth_complete,\n get_choose_username,\n+ get_web_login,\n+ get_logout,\n+ optional_principal,\n+ session_cookie_header_value,\n+ SLUG_SESSION_COOKIE,\n };\n \n pub use helpers::{\n@@ -23,8 +30,12 @@ pub use helpers::{\n \n pub use rpc::handle_rpc_batch;\n \n+pub use stream::{get_html_stream, get_stream};\n+\n pub use validate::{normalize_room_and_thread, validate_ingest_document, ValidatedIngest};\n \n+pub use web_post::post_web_ingest;\n+\n #[cfg(test)]\n mod tests {\n use super::*;\ndiff --git a/server/src/api/rpc.rs b/server/src/api/rpc.rs\nindex 7d384e938a526bdf6aa04d1bf21a54d3fcb57d7e..231bf7381cf804144efd0521970b72dd8ffd4213 100644\n--- a/server/src/api/rpc.rs\n+++ b/server/src/api/rpc.rs\n@@ -407,6 +407,22 @@ async fn rpc_post(\n })\n }\n \n+/// Post forum content using a raw bearer token (CLI `Authorization` header or browser session cookie).\n+pub async fn rpc_post_with_bearer(\n+ state: &AppState,\n+ bearer_token: &str,\n+ room: String,\n+ thread_tag: String,\n+ text: String,\n+) -> Result {\n+ use axum::http::{header, HeaderMap, HeaderValue};\n+ let mut headers = HeaderMap::new();\n+ let hv = HeaderValue::from_str(&format!(\"Bearer {bearer_token}\"))\n+ .map_err(|_| (\"invalid session token\".into(), None))?;\n+ headers.insert(header::AUTHORIZATION, hv);\n+ rpc_post(state, &headers, room, thread_tag, None, text, false).await\n+}\n+\n async fn rpc_check(\n state: &AppState,\n _room: String,\ndiff --git a/server/src/api/web_post.rs b/server/src/api/web_post.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..d7a5780c02281a60d29f27d17b291d6df5580606\n--- /dev/null\n+++ b/server/src/api/web_post.rs\n@@ -0,0 +1,107 @@\n+use axum::{\n+ extract::State,\n+ http::{HeaderMap, StatusCode},\n+ response::{Html, IntoResponse, Redirect},\n+ Form,\n+};\n+use axum_extra::extract::cookie::CookieJar;\n+use serde::Deserialize;\n+use slug_types::RpcResult;\n+\n+use crate::{\n+ api::{\n+ auth::{optional_principal, SLUG_SESSION_COOKIE},\n+ rpc::rpc_post_with_bearer,\n+ },\n+ canonical_path::canonicalize_tag,\n+ html::layout,\n+ state::AppState,\n+};\n+\n+#[derive(Debug, Deserialize)]\n+pub struct WebPostForm {\n+ pub room: String,\n+ pub thread_tag: String,\n+ pub text: String,\n+}\n+\n+fn post_redirect_location(room: &str, thread_tag: &str) -> String {\n+ let tag = canonicalize_tag(thread_tag);\n+ if room.trim() == \"public\" {\n+ format!(\"/t/{tag}\")\n+ } else {\n+ let room = room.trim();\n+ let Some((a, b)) = room.split_once('/') else {\n+ return \"/\".to_string();\n+ };\n+ format!(\"/r/{a}/{b}/{tag}\")\n+ }\n+}\n+\n+pub async fn post_web_ingest(\n+ State(state): State,\n+ headers: HeaderMap,\n+ jar: CookieJar,\n+ Form(form): Form,\n+) -> impl IntoResponse {\n+ let reduced = state.reduced.read().await;\n+ let Some(username) = optional_principal(&headers, &jar, &reduced) else {\n+ drop(reduced);\n+ return Redirect::temporary(\"/login\").into_response();\n+ };\n+\n+ let bearer = headers\n+ .get(axum::http::header::AUTHORIZATION)\n+ .and_then(|v| v.to_str().ok())\n+ .and_then(|s| s.strip_prefix(\"Bearer \").map(|t| t.trim().to_string()))\n+ .or_else(|| jar.get(SLUG_SESSION_COOKIE).map(|c| c.value().to_string()));\n+\n+ drop(reduced);\n+\n+ let Some(bearer) = bearer else {\n+ return Redirect::temporary(\"/login\").into_response();\n+ };\n+\n+ let room = form.room.trim().to_string();\n+ let thread_tag = form.thread_tag.trim().to_string();\n+ let text = form.text.clone();\n+\n+ if text.trim().is_empty() {\n+ return error_page(\n+ \"empty post\",\n+ \"Write something in the text area (DSL / prose).\",\n+ &username,\n+ )\n+ .into_response();\n+ }\n+\n+ match rpc_post_with_bearer(&state, &bearer, room.clone(), thread_tag.clone(), text).await {\n+ Ok(RpcResult::PostOk { .. }) => {\n+ Redirect::to(&post_redirect_location(&room, &thread_tag)).into_response()\n+ }\n+ Ok(_) => error_page(\"unexpected response\", \"Post did not return PostOk.\", &username).into_response(),\n+ Err((msg, hint)) => error_page(\n+ &msg,\n+ hint.as_deref().unwrap_or(\"\"),\n+ &username,\n+ )\n+ .into_response(),\n+ }\n+}\n+\n+fn error_page(title: &str, detail: &str, user: &str) -> impl IntoResponse {\n+ use maud::html;\n+ let body = html! {\n+ nav class=\"breadcrumb\" {\n+ a href=\"/\" { \"slug.social\" }\n+ }\n+ h1 { \"could not post\" }\n+ p { (title) }\n+ @if !detail.is_empty() {\n+ pre class=\"muted\" { (detail) }\n+ }\n+ p class=\"muted\" { \"signed in as @\" (user) \" · \" a href=\"/\" { \"home\" } }\n+ };\n+ let page = layout(\"post error — slug.social\", \"view-thread\", body, None);\n+ (StatusCode::BAD_REQUEST, Html(page.into_string()))\n+}\ndiff --git a/server/src/html/forum.rs b/server/src/html/forum.rs\nindex 228a120065dbacd8a308ba6e8bfc6ab111877c4b..8dfcd6b23a18e1571c4f0b3b60c865fa8f576f2f 100644\n--- a/server/src/html/forum.rs\n+++ b/server/src/html/forum.rs\n@@ -1,21 +1,24 @@\n use axum::{\n extract::{Path, Query, State},\n- http::{header, StatusCode},\n+ http::{header, HeaderMap, StatusCode},\n response::{Html, IntoResponse, Response},\n };\n-use serde::Deserialize;\n+use axum_extra::extract::cookie::CookieJar;\n use maud::{html, Markup};\n+use serde::Deserialize;\n \n use crate::{\n+ api::optional_principal,\n canonical_path::canonicalize_tag,\n+ events::ThreadCapability,\n reducer::{ReducerState, ScopeId},\n state::AppState,\n timeago,\n };\n \n use super::{\n- authorship_address, bc_threads, cli_panel, layout, now_ms,\n- recency_class, render_linkified_with_embeds,\n+ authorship_address, bc_segment, bc_threads, cli_panel, layout, now_ms, recency_class,\n+ render_linkified_with_embeds,\n };\n \n #[derive(Clone)]\n@@ -26,17 +29,72 @@ struct ThreadRow {\n ingests: usize,\n }\n \n-/// Collect thread rows from reducer state (unsorted).\n-fn collect_thread_rows(reduced: &ReducerState, now: i64) -> Vec {\n+/// URL prefix for thread pages: public `/t/…` or room `/r/{short}/{slug}/…`.\n+#[derive(Clone)]\n+pub struct ThreadNav {\n+ pub room_wire: String,\n+ scope: ScopeId,\n+ path_prefix: String,\n+}\n+\n+impl ThreadNav {\n+ pub fn public() -> Self {\n+ Self {\n+ room_wire: \"public\".into(),\n+ scope: ScopeId::Public,\n+ path_prefix: \"/t\".into(),\n+ }\n+ }\n+\n+ /// `room_id` wire form `shortid/slug`.\n+ pub fn from_room_id(room_id: &str) -> Option {\n+ let (short, slug) = room_id.split_once('/')?;\n+ if short.is_empty() || slug.is_empty() {\n+ return None;\n+ }\n+ Some(Self {\n+ room_wire: room_id.to_string(),\n+ scope: ScopeId::Room(room_id.to_string()),\n+ path_prefix: format!(\"/r/{short}/{slug}\"),\n+ })\n+ }\n+\n+ fn scope(&self) -> ScopeId {\n+ self.scope.clone()\n+ }\n+\n+ fn thread_url(&self, tag: &str) -> String {\n+ format!(\"{}/{}\", self.path_prefix, tag)\n+ }\n+\n+ fn thread_page_url(&self, tag: &str, offset: usize) -> String {\n+ let base = self.thread_url(tag);\n+ if offset == 0 {\n+ base\n+ } else {\n+ format!(\"{base}?offset={offset}\")\n+ }\n+ }\n+\n+ fn post_url(&self, tag: &str, idx: usize) -> String {\n+ format!(\"{}/{}/{}\", self.path_prefix, tag, idx)\n+ }\n+\n+ fn expand_url(&self, tag: &str, idx: usize) -> String {\n+ format!(\"{}/{}/{}/expand\", self.path_prefix, tag, idx)\n+ }\n+}\n+\n+fn collect_thread_rows_for_scope(reduced: &ReducerState, scope: &ScopeId, now: i64) -> Vec {\n let _ = now;\n reduced\n .forum_threads\n .iter()\n- .filter(|((scope, _), _)| scope == &ScopeId::Public)\n+ .filter(|((s, _), _)| s == scope)\n .map(|((_, tag), thread)| {\n let ingests = reduced\n .ingests_by_scope_thread\n- .get(&(ScopeId::Public, tag.clone()))\n+ .get(&(scope.clone(), tag.clone()))\n .map(|q| q.len())\n .unwrap_or(0);\n ThreadRow {\n@@ -49,16 +107,46 @@ fn collect_thread_rows(reduced: &ReducerState, now: i64) -> Vec {\n .collect()\n }\n \n-/// Render the thread feed div (id=\"thread-feed\"). Used by both index() and SSE broadcast.\n-fn render_thread_feed(rows: &[ThreadRow], now: i64) -> Markup {\n+fn rooms_for_user(reduced: &ReducerState, username: &str) -> Vec {\n+ let mut v: Vec = reduced\n+ .grants\n+ .iter()\n+ .filter(|(rid, m)| reduced.rooms.contains(*rid) && m.contains_key(username))\n+ .map(|(rid, _)| rid.clone())\n+ .collect();\n+ v.sort();\n+ v\n+}\n+\n+fn user_can_view_room(reduced: &ReducerState, room_id: &str, username: Option<&str>) -> bool {\n+ if !reduced.rooms.contains(room_id) {\n+ return false;\n+ }\n+ let Some(u) = username else {\n+ return false;\n+ };\n+ reduced.user_has_cap(room_id, u, ThreadCapability::View)\n+ || reduced.user_has_cap(room_id, u, ThreadCapability::Post)\n+ || reduced.user_has_cap(room_id, u, ThreadCapability::Manage)\n+}\n+\n+fn user_can_post_room(reduced: &ReducerState, room_id: &str, username: &str) -> bool {\n+ reduced.user_has_cap(room_id, username, ThreadCapability::Post)\n+}\n+\n+/// `feed_id` is e.g. `thread-feed` (public bump list, SSE) or `room-thread-feed`.\n+fn render_thread_feed(nav: Option<&ThreadNav>, feed_id: &str, rows: &[ThreadRow], now: i64) -> Markup {\n html! {\n- div id=\"thread-feed\" {\n+ div id=(feed_id) {\n @if rows.is_empty() {\n p class=\"muted\" { \"no threads yet\" }\n } @else {\n ul class=\"thread-feed\" {\n @for r in rows {\n- @let thread_href = format!(\"/t/{}\", r.tag);\n+ @let thread_href = nav\n+ .as_ref()\n+ .map(|n| n.thread_url(&r.tag))\n+ .unwrap_or_else(|| format!(\"/t/{}\", r.tag));\n @let hover = timeago::rfc3339_utc(r.last_ts);\n @let ago = timeago::timeago(now, r.last_ts);\n @let age_cls = recency_class(now, r.last_ts);\n@@ -83,36 +171,148 @@ fn render_thread_feed(rows: &[ThreadRow], now: i64) -> Markup {\n }\n }\n \n+fn auth_strip(\n+ headers: &HeaderMap,\n+ jar: &CookieJar,\n+ reduced: &ReducerState,\n+) -> Markup {\n+ match optional_principal(headers, jar, reduced) {\n+ Some(u) => html! {\n+ p class=\"muted auth-strip\" {\n+ \"@\" (u)\n+ \" · \"\n+ a href=\"/logout\" { \"log out\" }\n+ }\n+ },\n+ None => html! {\n+ p class=\"muted auth-strip\" {\n+ a href=\"/login\" { \"log in\" }\n+ }\n+ },\n+ }\n+}\n+\n+fn bc_room(nav: &ThreadNav, room_slug: &str, thread_tag: Option<&str>) -> Markup {\n+ html! {\n+ a href=\"/\" { \"slug.social\" }\n+ @if let Some(t) = thread_tag {\n+ (bc_segment(\n+ &format!(\"r / {room_slug}\"),\n+ &nav.path_prefix,\n+ false,\n+ ))\n+ (bc_segment(&format!(\"#{t}\"), &nav.thread_url(t), true))\n+ } @else {\n+ (bc_segment(\n+ &format!(\"r / {room_slug}\"),\n+ &nav.path_prefix,\n+ true,\n+ ))\n+ }\n+ }\n+}\n+\n+fn compose_form(nav: &ThreadNav, thread_tag: &str, show: bool) -> Markup {\n+ if !show {\n+ return html! {};\n+ }\n+ html! {\n+ section class=\"compose\" {\n+ h3 { \"reply\" }\n+ p class=\"muted\" { \"Uses the same ingest DSL as the CLI. You must be logged in.\" }\n+ form method=\"POST\" action=\"/post\" {\n+ input type=\"hidden\" name=\"room\" value=(nav.room_wire.clone());\n+ input type=\"hidden\" name=\"thread_tag\" value=(thread_tag);\n+ textarea name=\"text\" rows=\"8\" cols=\"80\" placeholder=\"prose or ~/items and votes…\" {}\n+ p {\n+ button type=\"submit\" { \"post\" }\n+ }\n+ }\n+ }\n+ }\n+}\n+\n+fn new_thread_form_public(show: bool) -> Markup {\n+ if !show {\n+ return html! {};\n+ }\n+ html! {\n+ section class=\"compose\" {\n+ h3 { \"new public thread\" }\n+ p class=\"muted\" { \"Set thread tag and body. Example: start with a title line or use the CLI-shaped DSL.\" }\n+ form method=\"POST\" action=\"/post\" {\n+ input type=\"hidden\" name=\"room\" value=\"public\";\n+ label for=\"new-thread-tag\" { \"thread tag\" }\n+ input type=\"text\" id=\"new-thread-tag\" name=\"thread_tag\" pattern=\"[a-z0-9_\\\\-]{1,64}\" placeholder=\"my-topic\";\n+ label for=\"new-thread-text\" { \"text\" }\n+ textarea id=\"new-thread-text\" name=\"text\" rows=\"6\" placeholder=\"#my-topic\\n\\nYour first post…\" {}\n+ p { button type=\"submit\" { \"create / post\" } }\n+ }\n+ }\n+ }\n+}\n \n-/// Returns the current thread feed HTML fragment for SSE broadcast.\n-/// selector: `#thread-feed`\n+/// Returns the current public thread feed HTML fragment for SSE (`#thread-feed`).\n pub async fn thread_feed_html(state: &AppState) -> String {\n let now = now_ms();\n+ let nav = ThreadNav::public();\n let mut rows = {\n let reduced = state.reduced.read().await;\n- collect_thread_rows(&reduced, now)\n+ collect_thread_rows_for_scope(&reduced, &ScopeId::Public, now)\n };\n rows.sort_by(|a, b| b.last_ts.cmp(&a.last_ts));\n- render_thread_feed(&rows, now).into_string()\n+ render_thread_feed(Some(&nav), \"thread-feed\", &rows, now).into_string()\n }\n \n-pub async fn index(State(state): State) -> impl IntoResponse {\n+/// Home: private rooms (signed-in), then public bump-ordered threads.\n+pub async fn home(\n+ State(state): State,\n+ headers: HeaderMap,\n+ jar: CookieJar,\n+) -> impl IntoResponse {\n let now = now_ms();\n- let mut rows: Vec = {\n- let reduced = state.reduced.read().await;\n- collect_thread_rows(&reduced, now)\n- };\n- // Bump order: most recently active first.\n- rows.sort_by(|a, b| b.last_ts.cmp(&a.last_ts));\n+ let reduced = state.reduced.read().await;\n+ let user = optional_principal(&headers, &jar, &reduced);\n+ let room_ids = user\n+ .as_ref()\n+ .map(|u| rooms_for_user(&reduced, u))\n+ .unwrap_or_default();\n+ let mut public_rows = collect_thread_rows_for_scope(&reduced, &ScopeId::Public, now);\n+ drop(reduced);\n+ public_rows.sort_by(|a, b| b.last_ts.cmp(&a.last_ts));\n+\n+ let nav = ThreadNav::public();\n+ let reduced_read = state.reduced.read().await;\n+ let strip = auth_strip(&headers, &jar, &reduced_read);\n+ let show_forms = user.is_some();\n+ drop(reduced_read);\n \n let page = layout(\n \"slug.social\",\n \"view-thread\",\n html! {\n+ (strip)\n nav class=\"breadcrumb\" { (bc_threads(None)) }\n+ @if !room_ids.is_empty() {\n+ h2 { \"your rooms\" }\n+ ul class=\"thread-feed\" {\n+ @for rid in &room_ids {\n+ @if let Some(nav_r) = ThreadNav::from_room_id(rid) {\n+ @let slug = if let Some((_, s)) = rid.split_once('/') { s } else { rid.as_str() };\n+ li {\n+ a href=(nav_r.path_prefix) {\n+ (slug)\n+ span class=\"muted\" { \" · \" (rid) }\n+ }\n+ }\n+ }\n+ }\n+ }\n+ }\n+ h2 { \"public threads\" }\n p class=\"muted\" { \"dark = time-ordered · light = vote-ranked\" }\n- h2 { \"threads\" }\n- (render_thread_feed(&rows, now))\n+ (render_thread_feed(Some(&nav), \"thread-feed\", &public_rows, now))\n+ (new_thread_form_public(show_forms))\n (cli_panel(\"npx slugsocial forum\"))\n },\n None,\n@@ -127,9 +327,13 @@ pub struct ThreadViewQuery {\n \n const PAGE_SIZE: usize = 10;\n \n-fn render_thread_paginator(tag: &str, offset: usize, total: usize, top: bool) -> Markup {\n+fn render_thread_paginator(nav: &ThreadNav, tag: &str, offset: usize, total: usize, top: bool) -> Markup {\n let newer_offset = offset.checked_add(PAGE_SIZE).filter(|&o| o < total);\n- let older_offset = if offset > 0 { Some(offset.saturating_sub(PAGE_SIZE)) } else { None };\n+ let older_offset = if offset > 0 {\n+ Some(offset.saturating_sub(PAGE_SIZE))\n+ } else {\n+ None\n+ };\n let latest_offset = total.saturating_sub(PAGE_SIZE);\n let on_latest = offset >= latest_offset;\n let (id, scroll_href, scroll_label) = if top {\n@@ -141,7 +345,7 @@ fn render_thread_paginator(tag: &str, offset: usize, total: usize, top: bool) ->\n div class=\"thread-paginator\" id=(id) {\n a href=(scroll_href) class=\"post-nav-btn\" { (scroll_label) }\n @if let Some(o) = older_offset {\n- a href=(format!(\"/t/{tag}?offset={o}\")) class=\"post-nav-btn\" { \"← older\" }\n+ a href=(nav.thread_page_url(tag, o)) class=\"post-nav-btn\" { \"← older\" }\n } @else {\n span class=\"post-nav-btn disabled\" { \"← older\" }\n }\n@@ -149,37 +353,38 @@ fn render_thread_paginator(tag: &str, offset: usize, total: usize, top: bool) ->\n (offset + 1) \"–\" (total.min(offset + PAGE_SIZE)) \" / \" (total)\n }\n @if let Some(o) = newer_offset {\n- a href=(format!(\"/t/{tag}?offset={o}\")) class=\"post-nav-btn\" { \"newer →\" }\n+ a href=(nav.thread_page_url(tag, o)) class=\"post-nav-btn\" { \"newer →\" }\n } @else {\n span class=\"post-nav-btn disabled\" { \"newer →\" }\n }\n @if !on_latest {\n- a href=(format!(\"/t/{tag}?offset={latest_offset}\")) class=\"post-nav-btn\" { \"latest\" }\n+ a href=(nav.thread_page_url(tag, latest_offset)) class=\"post-nav-btn\" { \"latest\" }\n }\n }\n }\n }\n \n-/// Thread view — `/t/:tag` — dark, paginated.\n-pub async fn thread_view(\n- State(state): State,\n- Path(tag): Path,\n- Query(q): Query,\n+async fn thread_view_inner(\n+ state: AppState,\n+ tag: String,\n+ q: ThreadViewQuery,\n+ nav: ThreadNav,\n+ headers: HeaderMap,\n+ jar: CookieJar,\n ) -> impl IntoResponse {\n let tag = canonicalize_tag(&tag);\n+ let scope = nav.scope();\n \n- // Newest-first queue → chronological for the page.\n let all_ids: Vec = {\n let reduced = state.reduced.read().await;\n reduced\n .ingests_by_scope_thread\n- .get(&(ScopeId::Public, tag.clone()))\n+ .get(&(scope.clone(), tag.clone()))\n .map(|q| q.iter().rev().cloned().collect())\n .unwrap_or_default()\n };\n \n let total = all_ids.len();\n- // Default: first page (oldest posts first, like a book).\n let offset = q.offset.unwrap_or(0);\n let page_ids: Vec = all_ids.into_iter().skip(offset).take(PAGE_SIZE).collect();\n \n@@ -189,18 +394,49 @@ pub async fn thread_view(\n .iter()\n .filter_map(|id| reduced.ingests_by_id.get(id).cloned())\n .collect::>();\n- let subtitle: Option = None;\n- (ingests, subtitle)\n+ (ingests, None::)\n+ };\n+\n+ let reduced = state.reduced.read().await;\n+ let user = optional_principal(&headers, &jar, &reduced);\n+ let sc = nav.scope();\n+ let show_compose = match &sc {\n+ ScopeId::Public => user.is_some(),\n+ ScopeId::Room(rid) => user\n+ .as_ref()\n+ .map(|u| user_can_post_room(&reduced, rid, u))\n+ .unwrap_or(false),\n };\n+ let strip = auth_strip(&headers, &jar, &reduced);\n+ drop(reduced);\n \n let now = now_ms();\n- let paginator_top = render_thread_paginator(&tag, offset, total, true);\n- let paginator_bot = render_thread_paginator(&tag, offset, total, false);\n+ let paginator_top = render_thread_paginator(&nav, &tag, offset, total, true);\n+ let paginator_bot = render_thread_paginator(&nav, &tag, offset, total, false);\n+\n+ let bc: Markup = match &sc {\n+ ScopeId::Public => bc_threads(Some(&tag)),\n+ ScopeId::Room(rid) => {\n+ let slug = if let Some((_, s)) = rid.split_once('/') {\n+ s\n+ } else {\n+ rid.as_str()\n+ };\n+ bc_room(&nav, slug, Some(&tag))\n+ }\n+ };\n+\n+ let cli = match &sc {\n+ ScopeId::Public => format!(\"npx slugsocial forum {tag}\"),\n+ ScopeId::Room(r) => format!(\"npx slugsocial private {r} forum {tag}\"),\n+ };\n+\n let page = layout(\n &format!(\"#{tag}\"),\n \"view-thread\",\n html! {\n- nav class=\"breadcrumb\" { (bc_threads(Some(&tag))) }\n+ (strip)\n+ nav class=\"breadcrumb\" { (bc) }\n h2 { \"#\" (tag) @if let Some(sub) = &subtitle { \": \" (sub) } }\n p class=\"muted\" { \"top=oldest · bottom=newest\" }\n @if display_ingests.is_empty() {\n@@ -209,7 +445,7 @@ pub async fn thread_view(\n (paginator_top)\n @for (i, ing) in display_ingests.iter().enumerate() {\n @let post_idx = offset + i;\n- @let post_href = format!(\"/t/{tag}/{post_idx}\");\n+ @let post_href = nav.post_url(&tag, post_idx);\n @let hover = timeago::rfc3339_utc(ing.ts);\n @let ago = timeago::timeago(now, ing.ts);\n @let truncated = ing.raw.len() > 2000;\n@@ -222,8 +458,9 @@ pub async fn thread_view(\n }\n (render_linkified_with_embeds(display_body))\n @if truncated {\n+ @let exp = nav.expand_url(&tag, post_idx);\n a href=\"#\" class=\"show-full-link\"\n- onclick=(format!(\"fetch('/t/{tag}/{post_idx}/expand').then(r=>r.text()).then(eval);return false\")) {\n+ onclick=(format!(\"fetch('{exp}').then(r=>r.text()).then(eval);return false\")) {\n \"[show full post]\"\n }\n }\n@@ -231,34 +468,171 @@ pub async fn thread_view(\n }\n (paginator_bot)\n }\n- (cli_panel(&format!(\"npx slugsocial forum {tag}\")))\n+ (compose_form(&nav, &tag, show_compose))\n+ (cli_panel(&cli))\n },\n None,\n );\n Html(page.into_string()).into_response()\n }\n \n-/// Single-post view — `/t/:tag/:index` — shows one ingest at full length.\n-pub async fn thread_post_view(\n+/// Thread view — `/t/:tag`\n+pub async fn thread_view(\n State(state): State,\n- Path((tag, index_str)): Path<(String, String)>,\n+ Path(tag): Path,\n+ Query(q): Query,\n+ headers: HeaderMap,\n+ jar: CookieJar,\n ) -> impl IntoResponse {\n- let tag = canonicalize_tag(&tag);\n+ thread_view_inner(state, tag, q, ThreadNav::public(), headers, jar).await\n+}\n+\n+/// Room thread — `/r/:short/:slug/:tag`\n+pub async fn room_thread_view(\n+ State(state): State,\n+ Path((room_short, room_slug, tag)): Path<(String, String, String)>,\n+ Query(q): Query,\n+ headers: HeaderMap,\n+ jar: CookieJar,\n+) -> impl IntoResponse {\n+ let room_id = format!(\"{room_short}/{room_slug}\");\n+ let reduced = state.reduced.read().await;\n+ let user = optional_principal(&headers, &jar, &reduced);\n+ if !user_can_view_room(&reduced, &room_id, user.as_deref()) {\n+ drop(reduced);\n+ return room_forbidden_page().into_response();\n+ }\n+ drop(reduced);\n+ let Some(nav) = ThreadNav::from_room_id(&room_id) else {\n+ return (StatusCode::NOT_FOUND, \"bad room path\").into_response();\n+ };\n+ thread_view_inner(state, tag, q, nav, headers, jar)\n+ .await\n+ .into_response()\n+}\n+\n+fn room_forbidden_page() -> impl IntoResponse {\n+ let body = html! {\n+ nav class=\"breadcrumb\" { a href=\"/\" { \"slug.social\" } }\n+ h1 { \"private room\" }\n+ p { \"Log in with an account that has been granted access to this room.\" }\n+ p { a href=\"/login\" { \"log in\" } \" · \" a href=\"/\" { \"home\" } }\n+ };\n+ let page = layout(\"private room — slug.social\", \"view-thread\", body, None);\n+ (StatusCode::FORBIDDEN, Html(page.into_string()))\n+}\n+\n+/// Private room index — `/r/:short/:slug`\n+pub async fn room_page(\n+ State(state): State,\n+ Path((room_short, room_slug)): Path<(String, String)>,\n+ headers: HeaderMap,\n+ jar: CookieJar,\n+) -> impl IntoResponse {\n+ let room_id = format!(\"{room_short}/{room_slug}\");\n let now = now_ms();\n+ let reduced = state.reduced.read().await;\n+ if !reduced.rooms.contains(&room_id) {\n+ drop(reduced);\n+ return (StatusCode::NOT_FOUND, \"room not found\").into_response();\n+ }\n+ let user = optional_principal(&headers, &jar, &reduced);\n+ if !user_can_view_room(&reduced, &room_id, user.as_deref()) {\n+ drop(reduced);\n+ return room_forbidden_page().into_response();\n+ }\n+ let scope = ScopeId::Room(room_id.clone());\n+ let mut rows = collect_thread_rows_for_scope(&reduced, &scope, now);\n+ let strip = auth_strip(&headers, &jar, &reduced);\n+ let show_new = user\n+ .as_ref()\n+ .map(|u| user_can_post_room(&reduced, &room_id, u))\n+ .unwrap_or(false);\n+ drop(reduced);\n+ rows.sort_by(|a, b| b.last_ts.cmp(&a.last_ts));\n+\n+ let Some(nav) = ThreadNav::from_room_id(&room_id) else {\n+ return (StatusCode::NOT_FOUND, \"room not found\").into_response();\n+ };\n+ let slug_display = room_slug.as_str();\n+ let cli = format!(\"npx slugsocial private {room_id} forum\");\n+\n+ let page = layout(\n+ &format!(\"room {slug_display} — slug.social\"),\n+ \"view-thread\",\n+ html! {\n+ (strip)\n+ nav class=\"breadcrumb\" { (bc_room(&nav, slug_display, None)) }\n+ h2 { (slug_display) }\n+ p class=\"muted\" { (room_id) }\n+ h3 { \"threads\" }\n+ (render_thread_feed(Some(&nav), \"room-thread-feed\", &rows, now))\n+ @if show_new {\n+ (new_thread_form_for_room(&nav, show_new))\n+ }\n+ (cli_panel(&cli))\n+ },\n+ None,\n+ );\n+ Html(page.into_string()).into_response()\n+}\n+\n+fn new_thread_form_for_room(nav: &ThreadNav, show: bool) -> Markup {\n+ if !show {\n+ return html! {};\n+ }\n+ html! {\n+ section class=\"compose\" {\n+ h3 { \"new thread in this room\" }\n+ form method=\"POST\" action=\"/post\" {\n+ input type=\"hidden\" name=\"room\" value=(nav.room_wire.clone());\n+ label for=\"room-new-tag\" { \"thread tag\" }\n+ input type=\"text\" id=\"room-new-tag\" name=\"thread_tag\" pattern=\"[a-z0-9_\\\\-]{1,64}\" required;\n+ textarea name=\"text\" rows=\"6\" placeholder=\"First post body…\" required {}\n+ p { button type=\"submit\" { \"post\" } }\n+ }\n+ }\n+ }\n+}\n+\n+async fn thread_post_view_inner(\n+ state: AppState,\n+ tag: String,\n+ index_str: String,\n+ nav: ThreadNav,\n+) -> impl IntoResponse {\n+ let tag = canonicalize_tag(&tag);\n let index: usize = index_str.parse().unwrap_or(0);\n+ let scope = nav.scope();\n+ let now = now_ms();\n let (ing, subtitle) = {\n let reduced = state.reduced.read().await;\n- let ing = reduced.ingests_by_scope_thread.get(&(ScopeId::Public, tag.clone()))\n+ let ing = reduced\n+ .ingests_by_scope_thread\n+ .get(&(scope.clone(), tag.clone()))\n .and_then(|q| q.iter().rev().nth(index))\n .and_then(|id| reduced.ingests_by_id.get(id).cloned());\n- let subtitle: Option = None;\n- (ing, subtitle)\n+ (ing, None::)\n };\n+\n+ let sc = nav.scope();\n+ let bc: Markup = match &sc {\n+ ScopeId::Public => bc_threads(Some(&tag)),\n+ ScopeId::Room(rid) => {\n+ let slug = if let Some((_, s)) = rid.split_once('/') {\n+ s\n+ } else {\n+ rid.as_str()\n+ };\n+ bc_room(&nav, slug, Some(&tag))\n+ }\n+ };\n+\n let page = layout(\n &format!(\"#{tag} / post #{index}\"),\n \"view-thread\",\n html! {\n- nav class=\"breadcrumb\" { (bc_threads(Some(&tag))) }\n+ nav class=\"breadcrumb\" { (bc) }\n h2 { \"#\" (tag) @if let Some(sub) = &subtitle { \": \" (sub) } \" / post #\" (index) }\n @if let Some(ing) = ing {\n @let hover = timeago::rfc3339_utc(ing.ts);\n@@ -280,21 +654,51 @@ pub async fn thread_post_view(\n Html(page.into_string()).into_response()\n }\n \n-/// Inline expand handler — `/t/:tag/:id/expand`\n-/// Returns a JS snippet that morphs the truncated post into its full version.\n-pub async fn thread_post_expand(\n+pub async fn thread_post_view(\n State(state): State,\n Path((tag, index_str)): Path<(String, String)>,\n+) -> impl IntoResponse {\n+ thread_post_view_inner(state, tag, index_str, ThreadNav::public()).await\n+}\n+\n+pub async fn room_thread_post_view(\n+ State(state): State,\n+ Path((room_short, room_slug, tag, index_str)): Path<(String, String, String, String)>,\n+ headers: HeaderMap,\n+ jar: CookieJar,\n+) -> impl IntoResponse {\n+ let room_id = format!(\"{room_short}/{room_slug}\");\n+ let reduced = state.reduced.read().await;\n+ let user = optional_principal(&headers, &jar, &reduced);\n+ if !user_can_view_room(&reduced, &room_id, user.as_deref()) {\n+ drop(reduced);\n+ return room_forbidden_page().into_response();\n+ }\n+ drop(reduced);\n+ let Some(nav) = ThreadNav::from_room_id(&room_id) else {\n+ return (StatusCode::NOT_FOUND, \"bad room path\").into_response();\n+ };\n+ thread_post_view_inner(state, tag, index_str, nav)\n+ .await\n+ .into_response()\n+}\n+\n+async fn thread_post_expand_inner(\n+ state: AppState,\n+ tag: String,\n+ index_str: String,\n+ nav: ThreadNav,\n ) -> impl IntoResponse {\n let tag = canonicalize_tag(&tag);\n let index: usize = index_str.parse().unwrap_or(0);\n let now = now_ms();\n+ let scope = nav.scope();\n \n let ing = {\n let reduced = state.reduced.read().await;\n reduced\n .ingests_by_scope_thread\n- .get(&(ScopeId::Public, tag.clone()))\n+ .get(&(scope.clone(), tag.clone()))\n .and_then(|q| q.iter().rev().nth(index))\n .and_then(|id| reduced.ingests_by_id.get(id).cloned())\n };\n@@ -303,7 +707,7 @@ pub async fn thread_post_expand(\n return (StatusCode::NOT_FOUND, \"post not found\").into_response();\n };\n \n- let post_href = format!(\"/t/{tag}/{index}\");\n+ let post_href = nav.post_url(&tag, index);\n let hover = timeago::rfc3339_utc(ing.ts);\n let ago = timeago::timeago(now, ing.ts);\n \n@@ -319,7 +723,6 @@ pub async fn thread_post_expand(\n };\n \n let full_html_str = full_html.into_string();\n- // Escape backticks and backslashes for JS template literal\n let escaped = full_html_str\n .replace('\\\\', \"\\\\\\\\\")\n .replace('`', \"\\\\`\")\n@@ -334,7 +737,36 @@ pub async fn thread_post_expand(\n Response::builder()\n .status(StatusCode::OK)\n .header(header::CONTENT_TYPE, \"text/javascript; charset=utf-8\")\n- .body(js)\n+ .body(axum::body::Body::from(js))\n .unwrap()\n .into_response()\n }\n+\n+pub async fn thread_post_expand(\n+ State(state): State,\n+ Path((tag, index_str)): Path<(String, String)>,\n+) -> impl IntoResponse {\n+ thread_post_expand_inner(state, tag, index_str, ThreadNav::public()).await\n+}\n+\n+pub async fn room_thread_post_expand(\n+ State(state): State,\n+ Path((room_short, room_slug, tag, index_str)): Path<(String, String, String, String)>,\n+ headers: HeaderMap,\n+ jar: CookieJar,\n+) -> impl IntoResponse {\n+ let room_id = format!(\"{room_short}/{room_slug}\");\n+ let reduced = state.reduced.read().await;\n+ let user = optional_principal(&headers, &jar, &reduced);\n+ if !user_can_view_room(&reduced, &room_id, user.as_deref()) {\n+ drop(reduced);\n+ return (StatusCode::FORBIDDEN, \"forbidden\").into_response();\n+ }\n+ drop(reduced);\n+ let Some(nav) = ThreadNav::from_room_id(&room_id) else {\n+ return (StatusCode::NOT_FOUND, \"not found\").into_response();\n+ };\n+ thread_post_expand_inner(state, tag, index_str, nav)\n+ .await\n+ .into_response()\n+}\ndiff --git a/server/src/html/mod.rs b/server/src/html/mod.rs\nindex 9c5af9654c7010d2cdb100e4cf63ba63e77c8c57..26e86124aae7cd878c92e1dc927e19d9fd2feaba 100644\n--- a/server/src/html/mod.rs\n+++ b/server/src/html/mod.rs\n@@ -16,7 +16,10 @@ use breadcrumb_path::OntologyPath;\n \n pub use auth::{auth_complete_page, auth_signed_in_fragment, choose_username_error_fragment, choose_username_page};\n pub use editor::{editor_check, editor_page};\n-pub use forum::{index, thread_feed_html, thread_post_expand, thread_post_view, thread_view};\n+pub use forum::{\n+ home, room_page, room_thread_post_expand, room_thread_post_view, room_thread_view, thread_feed_html,\n+ thread_post_expand, thread_post_view, thread_view,\n+};\n pub use garden::{garden_index, ontology_path};\n pub use search::{search_page, search_results_fragment};\n \ndiff --git a/server/src/lib.rs b/server/src/lib.rs\nindex bf2f73d4d0f26a357961e88c52c3b4f72626af81..b074cc31b94f23d1d566513392d7da3c02653c97 100644\n--- a/server/src/lib.rs\n+++ b/server/src/lib.rs\n@@ -16,7 +16,7 @@ pub mod state;\n pub mod timeago;\n \n use axum::Router;\n-use axum::routing::post;\n+use axum::routing::{get, post};\n use tower_http::trace::TraceLayer;\n \n use crate::state::AppState;\n@@ -25,17 +25,48 @@ pub use reducer::ReducerState;\n \n pub fn create_app(state: AppState) -> Router {\n Router::new()\n- .route(\"/healthz\", axum::routing::get(|| async { \"ok\" }))\n- .route(\"/static/:filename\", axum::routing::get(crate::html::serve_theme_css))\n- .route(\"/join/:token\", axum::routing::get(api::get_join_invite))\n- .route(\"/auth/login\", axum::routing::get(api::get_auth_login))\n- .route(\"/auth/callback\", axum::routing::get(api::get_auth_callback))\n- .route(\"/auth/complete\", axum::routing::get(api::get_auth_complete))\n- .route(\"/auth/choose-username\", axum::routing::get(api::get_choose_username))\n- .route(\"/auth/choose-username\", axum::routing::post(api::post_choose_username))\n- .route(\"/api/v0/pending-session\", axum::routing::post(api::post_pending_session))\n- .route(\"/api/v0/pending-session/:id\", axum::routing::get(api::get_pending_session))\n- .route(\"/api/v0/whoami\", axum::routing::get(api::get_whoami))\n+ .route(\"/healthz\", get(|| async { \"ok\" }))\n+ .route(\"/static/:filename\", get(crate::html::serve_theme_css))\n+ .route(\"/\", get(crate::html::home))\n+ .route(\"/login\", get(api::get_web_login))\n+ .route(\"/logout\", get(api::get_logout))\n+ .route(\"/post\", post(api::post_web_ingest))\n+ .route(\"/sse\", get(api::get_html_stream))\n+ .route(\"/stream\", get(api::get_stream))\n+ .route(\"/search\", get(crate::html::search_page))\n+ .route(\"/search/results\", get(crate::html::search_results_fragment))\n+ .route(\"/try\", get(crate::html::editor_page))\n+ .route(\"/try/check\", post(crate::html::editor_check))\n+ .route(\"/~\", get(crate::html::garden_index))\n+ .route(\"/~/*path\", get(crate::html::ontology_path))\n+ .route(\n+ \"/t/:tag/:index/expand\",\n+ get(crate::html::thread_post_expand),\n+ )\n+ .route(\"/t/:tag/:index\", get(crate::html::thread_post_view))\n+ .route(\"/t/:tag\", get(crate::html::thread_view))\n+ .route(\n+ \"/r/:room_short/:room_slug/:thread_tag/:index/expand\",\n+ get(crate::html::room_thread_post_expand),\n+ )\n+ .route(\n+ \"/r/:room_short/:room_slug/:thread_tag/:index\",\n+ get(crate::html::room_thread_post_view),\n+ )\n+ .route(\n+ \"/r/:room_short/:room_slug/:thread_tag\",\n+ get(crate::html::room_thread_view),\n+ )\n+ .route(\"/r/:room_short/:room_slug\", get(crate::html::room_page))\n+ .route(\"/join/:token\", get(api::get_join_invite))\n+ .route(\"/auth/login\", get(api::get_auth_login))\n+ .route(\"/auth/callback\", get(api::get_auth_callback))\n+ .route(\"/auth/complete\", get(api::get_auth_complete))\n+ .route(\"/auth/choose-username\", get(api::get_choose_username))\n+ .route(\"/auth/choose-username\", post(api::post_choose_username))\n+ .route(\"/api/v0/pending-session\", post(api::post_pending_session))\n+ .route(\"/api/v0/pending-session/:id\", get(api::get_pending_session))\n+ .route(\"/api/v0/whoami\", get(api::get_whoami))\n .route(\"/api/v0/rpc\", post(api::handle_rpc_batch))\n .with_state(state)\n .layer(TraceLayer::new_for_http())\n","role":"user"}],"model":"~anthropic/claude-sonnet-latest"}