{"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[08565bea] Tokenize prose refs for garden URL links (#147)\n\n* Tokenize prose refs for garden URL links\n\nCo-authored-by: tommy \n\n* Stop prose URLs at line boundaries\n\nCo-authored-by: tommy \n\n* Require braced DSL item bodies\n\nCo-authored-by: tommy \n\n---------\n\nCo-authored-by: Cursor Agent \n\nSide A — unified diff (full patch):\ndiff --git a/server/src/dsl.rs b/server/src/dsl.rs\nindex 4203c2f59dd8825d7a91513c4023f3ccd37f1efc..b3c785674560a0b42a7f4c3aa13d80cd350f485b 100644\n--- a/server/src/dsl.rs\n+++ b/server/src/dsl.rs\n@@ -1,7 +1,5 @@\n use std::collections::HashMap;\n \n-use rand::Rng;\n-\n /// Parsed DSL document.\n #[derive(Debug, Clone, PartialEq, Eq)]\n pub struct Document {\n@@ -39,31 +37,57 @@ pub enum DslError {\n /// Matches the legacy Python parser behavior:\n /// - Supports toggle markers (open == close), e.g. ```...```\n /// - Supports nested markers (open != close), e.g. { ... { ... } ... }\n+#[derive(Debug, Clone, Copy, PartialEq, Eq)]\n+pub enum BlockKind {\n+ CodeFence,\n+ DoubleBrace,\n+ Brace,\n+}\n+\n+#[derive(Debug, Clone, PartialEq, Eq)]\n+struct MaskedBlock {\n+ kind: BlockKind,\n+}\n+\n #[derive(Debug, Default, Clone)]\n pub struct BlockMasker {\n pub replacements: HashMap,\n+ blocks: HashMap,\n+ next_id: u32,\n }\n \n impl BlockMasker {\n pub fn new() -> Self {\n Self {\n replacements: HashMap::new(),\n+ blocks: HashMap::new(),\n+ next_id: 0,\n }\n }\n \n- fn new_token(&mut self) -> String {\n- let mut rng = rand::thread_rng();\n- let n: u32 = rng.gen();\n- let token = format!(\"__BLOCK_{:08x}__\", n);\n- // Extremely unlikely collision; if it happens, regenerate.\n- if self.replacements.contains_key(&token) {\n- return self.new_token();\n+ fn new_token(&mut self, haystack: &str) -> String {\n+ loop {\n+ let token = format!(\"__BLOCK_{:08x}__\", self.next_id);\n+ self.next_id = self.next_id.wrapping_add(1);\n+ if !self.replacements.contains_key(&token) && !haystack.contains(&token) {\n+ return token;\n+ }\n }\n- token\n }\n \n /// Replace outermost balanced blocks with tokens.\n pub fn mask(&mut self, text: &str, open_marker: &str, close_marker: &str) -> String {\n+ self.mask_kind(text, open_marker, close_marker, BlockKind::Brace)\n+ }\n+\n+ /// Replace outermost balanced blocks with typed deterministic tokens.\n+ pub fn mask_kind(\n+ &mut self,\n+ text: &str,\n+ open_marker: &str,\n+ close_marker: &str,\n+ kind: BlockKind,\n+ ) -> String {\n if text.is_empty() {\n return text.to_string();\n }\n@@ -97,9 +121,10 @@ impl BlockMasker {\n // Found end of outermost block\n let s = start_idx.max(0) as usize;\n let original_block = &text[s..i];\n- let token = self.new_token();\n+ let token = self.new_token(text);\n self.replacements\n .insert(token.clone(), original_block.to_string());\n+ self.blocks.insert(token.clone(), MaskedBlock { kind });\n result_parts.push(token);\n current_idx = i;\n }\n@@ -176,13 +201,22 @@ impl BlockMasker {\n }\n token.to_string()\n }\n+\n+ pub fn block_kind(&self, token: &str) -> Option {\n+ self.blocks.get(token).map(|b| b.kind)\n+ }\n }\n \n fn mask_all(mut masker: BlockMasker, text: &str) -> (BlockMasker, String) {\n // Mask hierarchy: Code -> Double Brace -> Single Brace.\n- let t = masker.mask(text, \"```\", \"```\");\n- let t = masker.mask(&t, \"{{\", \"}}\");\n- let t = masker.mask(&t, \"{\", \"}\");\n+ let t = masker.mask_kind(text, \"```\", \"```\", BlockKind::CodeFence);\n+ let t = masker.mask_kind(&t, \"{{\", \"}}\", BlockKind::DoubleBrace);\n+ let t = masker.mask_kind(&t, \"{\", \"}\", BlockKind::Brace);\n+ (masker, t)\n+}\n+\n+fn mask_code_fences(mut masker: BlockMasker, text: &str) -> (BlockMasker, String) {\n+ let t = masker.mask_kind(text, \"```\", \"```\", BlockKind::CodeFence);\n (masker, t)\n }\n \n@@ -253,7 +287,34 @@ fn skip_ws(s: &str, mut i: usize) -> usize {\n i\n }\n \n-fn parse_item_name_at(s: &str, i: usize) -> Option<(String, usize)> {\n+#[derive(Debug, Clone, PartialEq, Eq)]\n+pub enum ProseToken {\n+ Text(String),\n+ ItemRef(String),\n+}\n+\n+fn trim_prose_item_ref_end(s: &str, mut end: usize) -> usize {\n+ while end > 0 {\n+ let Some((idx, c)) = s[..end].char_indices().next_back() else {\n+ break;\n+ };\n+ if matches!(\n+ c,\n+ '.' | ',' | ';' | ':' | '!' | '?' | ')' | ']' | '}' | '\"' | '\\''\n+ ) {\n+ end = idx;\n+ } else {\n+ break;\n+ }\n+ }\n+ end\n+}\n+\n+fn parse_item_name_at_with_mode(\n+ s: &str,\n+ i: usize,\n+ trim_trailing_punctuation: bool,\n+) -> Option<(String, usize)> {\n let bytes = s.as_bytes();\n if i >= bytes.len() {\n return None;\n@@ -263,6 +324,9 @@ fn parse_item_name_at(s: &str, i: usize) -> Option<(String, usize)> {\n if s[i..].starts_with(\"https://\") || s[i..].starts_with(\"http://\") {\n let mut j = i;\n while j < bytes.len() {\n+ if trim_trailing_punctuation && bytes[j] == b'\\n' {\n+ break;\n+ }\n if bytes[j..].starts_with(b\"__BLOCK_\") || is_ws_byte(bytes[j]) {\n break;\n }\n@@ -271,6 +335,12 @@ fn parse_item_name_at(s: &str, i: usize) -> Option<(String, usize)> {\n if j <= i {\n return None;\n }\n+ if trim_trailing_punctuation {\n+ j = trim_prose_item_ref_end(s, j);\n+ if j <= i {\n+ return None;\n+ }\n+ }\n return Some((s[i..j].to_string(), j));\n }\n \n@@ -296,6 +366,12 @@ fn parse_item_name_at(s: &str, i: usize) -> Option<(String, usize)> {\n if j <= i + 2 {\n return None;\n }\n+ if trim_trailing_punctuation {\n+ j = trim_prose_item_ref_end(s, j);\n+ if j <= i + 2 {\n+ return None;\n+ }\n+ }\n let raw = &s[i..j];\n if !is_item_name(raw) {\n return None;\n@@ -336,6 +412,46 @@ fn parse_item_name_at(s: &str, i: usize) -> Option<(String, usize)> {\n Some((format!(\"~/{}\", name), j))\n }\n \n+fn parse_item_name_at(s: &str, i: usize) -> Option<(String, usize)> {\n+ parse_item_name_at_with_mode(s, i, false)\n+}\n+\n+pub fn parse_prose_item_ref_at(s: &str, i: usize) -> Option<(String, usize)> {\n+ parse_item_name_at_with_mode(s, i, true)\n+}\n+\n+pub fn tokenize_prose_item_refs(text: &str) -> Vec {\n+ if text.is_empty() {\n+ return Vec::new();\n+ }\n+ let (masker, masked) = mask_code_fences(BlockMasker::new(), text);\n+ let mut tokens = Vec::new();\n+ let mut text_start = 0usize;\n+ let mut i = 0usize;\n+\n+ while i < masked.len() {\n+ if let Some((raw, end)) = parse_prose_item_ref_at(&masked, i) {\n+ if text_start < i {\n+ tokens.push(ProseToken::Text(masker.unmask(&masked[text_start..i])));\n+ }\n+ tokens.push(ProseToken::ItemRef(masker.unmask(&raw)));\n+ i = end;\n+ text_start = i;\n+ continue;\n+ }\n+\n+ let Some((_, c)) = masked[i..].char_indices().next() else {\n+ break;\n+ };\n+ i += c.len_utf8();\n+ }\n+\n+ if text_start < masked.len() {\n+ tokens.push(ProseToken::Text(masker.unmask(&masked[text_start..])));\n+ }\n+ tokens\n+}\n+\n fn parse_block_token_at(s: &str, i: usize) -> Option<(String, usize)> {\n let bytes = s.as_bytes();\n if i >= bytes.len() {\n@@ -401,6 +517,12 @@ fn parse_block_prefixed_statement(\n tail: &str,\n masker: &BlockMasker,\n ) -> Result {\n+ if masker.block_kind(block_token) == Some(BlockKind::CodeFence) {\n+ return Err(DslError::Parse(\n+ \"vote explanations must use `{ ... }`; code fences belong inside body blocks\"\n+ .to_string(),\n+ ));\n+ }\n // vote: block item_ref comparison item_ref\n let s = tail.trim_start();\n if s.is_empty() {\n@@ -462,6 +584,11 @@ fn parse_item_definition_statement(stripped: &str, masker: &BlockMasker) -> Resu\n }\n \n if let Some((tok, end)) = parse_block_token_at(stripped, i) {\n+ if masker.block_kind(&tok) == Some(BlockKind::CodeFence) {\n+ return Err(DslError::Parse(\n+ \"item bodies must use `{ ... }`; code fences belong inside body blocks\".to_string(),\n+ ));\n+ }\n let body = masker.extract_body(&tok);\n let tail = stripped[end..].trim();\n if !tail.is_empty() {\n@@ -572,6 +699,10 @@ pub fn parse_full(text: &str) -> Result {\n \n if let Some((tok, end)) = parse_block_token_at(stripped, 0) {\n if stripped[end..].trim().is_empty() {\n+ if masker.block_kind(&tok) == Some(BlockKind::CodeFence) {\n+ prose_buffer.push(line);\n+ continue;\n+ }\n pending_block = Some(tok);\n continue;\n }\n@@ -619,6 +750,70 @@ mod tests {\n assert_eq!(roundtrip, input);\n }\n \n+ #[test]\n+ fn blockmasker_tokens_are_deterministic_and_typed() {\n+ let input = \"x ```code``` y {body}\";\n+ let (masker, masked) = mask_all(BlockMasker::new(), input);\n+ assert!(masked.contains(\"__BLOCK_00000000__\"));\n+ assert!(masked.contains(\"__BLOCK_00000001__\"));\n+ assert_eq!(\n+ masker.block_kind(\"__BLOCK_00000000__\"),\n+ Some(BlockKind::CodeFence)\n+ );\n+ assert_eq!(\n+ masker.block_kind(\"__BLOCK_00000001__\"),\n+ Some(BlockKind::Brace)\n+ );\n+ assert_eq!(masker.unmask(&masked), input);\n+ }\n+\n+ #[test]\n+ fn prose_tokenizer_finds_tilde_dash_and_raw_url_refs() {\n+ let tokens =\n+ tokenize_prose_item_refs(\"see ~/a/b then -/example.com/x and https://Example.com/A/B.\");\n+ assert_eq!(\n+ tokens,\n+ vec![\n+ ProseToken::Text(\"see \".to_string()),\n+ ProseToken::ItemRef(\"~/a/b\".to_string()),\n+ ProseToken::Text(\" then \".to_string()),\n+ ProseToken::ItemRef(\"-/example.com/x\".to_string()),\n+ ProseToken::Text(\" and \".to_string()),\n+ ProseToken::ItemRef(\"https://Example.com/A/B\".to_string()),\n+ ProseToken::Text(\".\".to_string()),\n+ ]\n+ );\n+ }\n+\n+ #[test]\n+ fn prose_tokenizer_stops_raw_urls_at_newlines() {\n+ let tokens = tokenize_prose_item_refs(\"https://example.com/a/b.\\n-/example.com/a/b\");\n+ assert_eq!(\n+ tokens,\n+ vec![\n+ ProseToken::ItemRef(\"https://example.com/a/b\".to_string()),\n+ ProseToken::Text(\".\\n\".to_string()),\n+ ProseToken::ItemRef(\"-/example.com/a/b\".to_string()),\n+ ]\n+ );\n+ }\n+\n+ #[test]\n+ fn prose_tokenizer_does_not_linkify_inside_code_fences() {\n+ let tokens = tokenize_prose_item_refs(\n+ \"before ```json\\n{\\\"url\\\":\\\"https://example.com\\\"}\\n``` after ~/x\",\n+ );\n+ assert_eq!(\n+ tokens,\n+ vec![\n+ ProseToken::Text(\n+ \"before ```json\\n{\\\"url\\\":\\\"https://example.com\\\"}\\n``` after \".to_string()\n+ ),\n+ ProseToken::ItemRef(\"~/x\".to_string()),\n+ ]\n+ );\n+ }\n+\n #[test]\n fn parse_item_with_body_strips_outer_braces() {\n let input = \"~/rust { Systems language }\";\n@@ -633,8 +828,8 @@ mod tests {\n }\n \n #[test]\n- fn parse_item_with_fenced_json_body_preserves_braces() {\n- let input = \"~/item/in/url ```json\\n{\\\"test\\\": true}\\n```\";\n+ fn parse_item_with_braced_fenced_json_body_preserves_braces() {\n+ let input = \"~/item/in/url {\\n```json\\n{\\\"test\\\": true}\\n```\\n}\";\n let doc = parse_full(input).unwrap();\n assert_eq!(\n doc.statements,\n@@ -645,6 +840,51 @@ mod tests {\n );\n }\n \n+ #[test]\n+ fn parse_rejects_singleton_fenced_json_item_body() {\n+ let input = \"~/item/in/url ```json\\n{\\\"test\\\": true}\\n```\";\n+ let err = parse_full(input).unwrap_err().to_string();\n+ assert!(\n+ err.contains(\"item bodies must use\"),\n+ \"unexpected error: {err}\"\n+ );\n+ }\n+\n+ #[test]\n+ fn parse_keeps_standalone_code_fence_as_prose() {\n+ let input = \"```json\\n{\\\"test\\\": true}\\n```\";\n+ let doc = parse_full(input).unwrap();\n+ assert_eq!(\n+ doc.statements,\n+ vec![Stmt::Prose {\n+ text: input.to_string(),\n+ }]\n+ );\n+ }\n+\n+ #[test]\n+ fn parse_rejects_code_fence_vote_explanation() {\n+ let input = \"```json\\n{\\\"why\\\": true}\\n```\\n~/a 2:1 ~/b\";\n+ let err = parse_full(input).unwrap_err().to_string();\n+ assert!(\n+ err.contains(\"vote explanations must start\"),\n+ \"unexpected error: {err}\"\n+ );\n+ }\n+\n+ #[test]\n+ fn parse_raw_url_item_with_braced_fenced_json_body() {\n+ let input = \"https://example.com/itembody/slug {\\n```json\\n{\\\"test\\\": true}\\n```\\n}\";\n+ let doc = parse_full(input).unwrap();\n+ assert_eq!(\n+ doc.statements,\n+ vec![Stmt::Item {\n+ title: \"https://example.com/itembody/slug\".to_string(),\n+ body: Some(\"```json\\n{\\\"test\\\": true}\\n```\".to_string()),\n+ }]\n+ );\n+ }\n+\n #[test]\n fn parse_vote_ratio_and_symbols() {\n let d1 = parse_full(\"{because}\\n~/a 3:1 ~/b\").unwrap();\ndiff --git a/server/src/external_resolver.rs b/server/src/external_resolver.rs\nindex 8481f1fbff1c4265da182a225f539f97d6829002..04bc3de32b6df1aefe197d942db67de2cbdbde4f 100644\n--- a/server/src/external_resolver.rs\n+++ b/server/src/external_resolver.rs\n@@ -256,7 +256,7 @@ fn children_to_dsl(children: &[ResolvedChild]) -> String {\n .filter(|s| !s.trim().is_empty())\n .unwrap_or(child.title.as_str());\n if body.trim_start().starts_with(\"```\") {\n- out.push_str(&format!(\"{} {}\\n\\n\", child.url, body.trim()));\n+ out.push_str(&format!(\"{} {{\\n{}\\n}}\\n\\n\", child.url, body.trim()));\n } else {\n out.push_str(&format!(\n \"{} {{\\n{}\\n}}\\n\\n\",\n@@ -378,7 +378,8 @@ mod tests {\n title: \"#1 title\".into(),\n body: Some(\"```json\\n{\\\"test\\\": true}\\n```\".into()),\n }]);\n- assert!(dsl.contains(\"https://github.com/o/r/issues/1 ```json\"));\n+ assert!(dsl.contains(\"https://github.com/o/r/issues/1 {\\n```json\"));\n assert!(dsl.contains(\"{\\\"test\\\": true}\"));\n+ assert!(dsl.contains(\"```\\n}\\n\"));\n }\n }\ndiff --git a/server/src/html/breadcrumb_path.rs b/server/src/html/breadcrumb_path.rs\nindex 3e949ce2cb70de3f024f46af773a93f3f8852260..e48612d7d3c4df52c161499a11865d4caca607aa 100644\n--- a/server/src/html/breadcrumb_path.rs\n+++ b/server/src/html/breadcrumb_path.rs\n@@ -88,16 +88,12 @@ impl ExternalOntologyPath {\n .filter(|x| !x.is_empty())\n .map(|x| x.to_string())\n .collect();\n- let segments = if segments == [\".\"] {\n- vec![]\n- } else {\n- segments\n- };\n+ let segments = if segments == [\".\"] { vec![] } else { segments };\n Self { item, segments }\n }\n \n pub(super) fn is_root(&self) -> bool {\n- self.segments.len() <= 1\n+ self.segments.is_empty()\n }\n \n pub(super) fn segments(&self) -> &[String] {\n@@ -108,3 +104,28 @@ impl ExternalOntologyPath {\n self.item.as_str()\n }\n }\n+\n+#[cfg(test)]\n+mod tests {\n+ use super::*;\n+\n+ #[test]\n+ fn external_root_and_host_paths_are_distinct() {\n+ let root = ExternalOntologyPath::from_input(\"\");\n+ assert!(root.is_root());\n+ assert!(root.segments().is_empty());\n+\n+ let host = ExternalOntologyPath::from_input(\"example.com\");\n+ assert!(!host.is_root());\n+ assert_eq!(host.segments(), &[\"example.com\".to_string()]);\n+ }\n+\n+ #[test]\n+ fn external_path_keeps_each_url_segment_for_breadcrumbs() {\n+ let path = ExternalOntologyPath::from_input(\"https://example.com/a/b\");\n+ assert_eq!(\n+ path.segments(),\n+ &[\"example.com\".to_string(), \"a\".to_string(), \"b\".to_string()]\n+ );\n+ }\n+}\ndiff --git a/server/src/html/mod.rs b/server/src/html/mod.rs\nindex 8876a1a00a16ee3bf7a371f7a5ca27b5862b62cc..d5877eeb3632ed5d770f23a04cb4d1881209bc74 100644\n--- a/server/src/html/mod.rs\n+++ b/server/src/html/mod.rs\n@@ -20,27 +20,30 @@ mod search;\n pub mod ui_action;\n use breadcrumb_path::{ExternalOntologyPath, OntologyPath};\n \n-pub use auth::{auth_complete_page, auth_signed_in_fragment, choose_username_error_fragment, choose_username_page};\n+pub use auth::{\n+ auth_complete_page, auth_signed_in_fragment, choose_username_error_fragment,\n+ choose_username_page,\n+};\n pub use editor::{editor_check, editor_page};\n pub use forum::{\n home, room_page, room_thread_post_view, room_thread_view, thread_feed_html,\n thread_feed_html_for_room, thread_feed_region_markup, thread_post_view, thread_view, ThreadNav,\n };\n \n+pub use forum::user_profile_page;\n pub(crate) use forum::{\n fragment_new_thread_slot, login_to_post_hint_markup, room_members_section_markup,\n thread_ui_collapse_redacted_post, thread_ui_expand_post_full, thread_ui_expand_redacted_post,\n user_can_post_room, user_can_view_room,\n };\n+pub(crate) use garden::{encode_pin_cookie_value, vote_compare_post_success_js, GARDEN_PIN_COOKIE};\n pub use garden::{\n external_garden_index, external_ontology_path, garden_index, ontology_path,\n- room_external_garden_index, room_external_ontology_path, room_garden_index,\n- room_ontology_path, room_vote_compare_page, vote_compare_page,\n+ room_external_garden_index, room_external_ontology_path, room_garden_index, room_ontology_path,\n+ room_vote_compare_page, vote_compare_page,\n };\n-pub(crate) use garden::{encode_pin_cookie_value, vote_compare_post_success_js, GARDEN_PIN_COOKIE};\n pub use routing::RouteContext;\n pub use search::{search_page, search_results_fragment};\n-pub use forum::user_profile_page;\n pub use ui_action::{parse_html_ui_from_form, HtmlUiAction, HtmlUiParseError, UI_RPC_FIELD};\n \n /// Public profile URL path for a stored username (no `@`).\n@@ -107,8 +110,8 @@ pub struct ThemeForm {\n pub async fn post_theme(Form(form): Form) -> impl IntoResponse {\n let theme = normalize_theme(&form.theme);\n let next = sanitize_theme_next(form.next.as_deref());\n- let loc = HeaderValue::try_from(next.as_str())\n- .unwrap_or_else(|_| HeaderValue::from_static(\"/\"));\n+ let loc =\n+ HeaderValue::try_from(next.as_str()).unwrap_or_else(|_| HeaderValue::from_static(\"/\"));\n Response::builder()\n .status(StatusCode::SEE_OTHER)\n .header(header::LOCATION, loc)\n@@ -179,7 +182,9 @@ pub(crate) struct JsQueryBuilder {\n \n impl JsBuilder {\n pub(crate) fn new() -> Self {\n- Self { snippets: Vec::new() }\n+ Self {\n+ snippets: Vec::new(),\n+ }\n }\n \n pub(crate) fn morph_selector(self, selector: &str, markup: Markup) -> Self {\n@@ -195,7 +200,12 @@ impl JsBuilder {\n self.qs(selector).morph_inner(markup)\n }\n \n- pub(crate) fn morph_expr(mut self, expr: &str, markup: Markup, morph_style: Option<&str>) -> Self {\n+ pub(crate) fn morph_expr(\n+ mut self,\n+ expr: &str,\n+ markup: Markup,\n+ morph_style: Option<&str>,\n+ ) -> Self {\n let html = js_string_literal(&markup.into_string());\n let opts = morph_style\n .map(|style| format!(\", {{morphStyle: {}}}\", js_string_literal(style)))\n@@ -217,7 +227,11 @@ impl JsBuilder {\n self.qs(&format!(\"#{id}\"))\n }\n \n- pub(crate) fn if_current_path_matches(mut self, path: &str, f: impl FnOnce(JsBuilder) -> JsBuilder) -> Self {\n+ pub(crate) fn if_current_path_matches(\n+ mut self,\n+ path: &str,\n+ f: impl FnOnce(JsBuilder) -> JsBuilder,\n+ ) -> Self {\n let inner = f(JsBuilder::new()).build();\n self.snippets.push(format!(\n \"var __slugHere = window.location.pathname + window.location.search; var __slugPath = {path}; if (__slugHere === __slugPath || __slugHere.indexOf(__slugPath + '?') === 0) {{ {inner} }}\",\n@@ -226,7 +240,11 @@ impl JsBuilder {\n self\n }\n \n- pub(crate) fn if_current_path_not_matches(mut self, path: &str, f: impl FnOnce(JsBuilder) -> JsBuilder) -> Self {\n+ pub(crate) fn if_current_path_not_matches(\n+ mut self,\n+ path: &str,\n+ f: impl FnOnce(JsBuilder) -> JsBuilder,\n+ ) -> Self {\n let inner = f(JsBuilder::new()).build();\n self.snippets.push(format!(\n \"var __slugHere = window.location.pathname + window.location.search; var __slugPath = {path}; if (!(__slugHere === __slugPath || __slugHere.indexOf(__slugPath + '?') === 0)) {{ {inner} }}\",\n@@ -301,7 +319,17 @@ pub(super) fn layout(\n garden_room_wire: Option<&str>,\n garden_path_prefix: Option<&str>,\n ) -> Markup {\n- layout_embed_controls(title, view, body, views, theme, theme_next, garden_room_wire, garden_path_prefix, true)\n+ layout_embed_controls(\n+ title,\n+ view,\n+ body,\n+ views,\n+ theme,\n+ theme_next,\n+ garden_room_wire,\n+ garden_path_prefix,\n+ true,\n+ )\n }\n \n /// Minimal document shell: no bottom controls, no garden HUD data attributes (`data-garden-room` /\n@@ -315,15 +343,7 @@ pub(super) fn layout_full_bleed_chromeless(\n theme_next: &str,\n ) -> Markup {\n layout_embed_controls(\n- title,\n- view,\n- body,\n- views,\n- theme,\n- theme_next,\n- None,\n- None,\n- false,\n+ title, view, body, views, theme, theme_next, None, None, false,\n )\n }\n \n@@ -545,7 +565,58 @@ fn item_body_title_snippet(body: &str) -> Option {\n Some(format!(\"{truncated}{ellipsis}\"))\n }\n \n-/// Replace ~/path slugs in raw text with clickable links.\n+fn garden_href_for_item_ref(\n+ raw_ref: &str,\n+ garden_prefix: &str,\n+) -> Option<(crate::path_types::ItemId, String)> {\n+ let key = slug_types::canonicalize_item(raw_ref);\n+ let id = crate::path_types::ItemId::parse(&key)?;\n+ let href = if let Some(tail) = id.tilde_tail() {\n+ if tail.is_empty() {\n+ garden_prefix.trim_end_matches('/').to_string()\n+ } else {\n+ format!(\"{}/{}\", garden_prefix.trim_end_matches('/'), tail)\n+ }\n+ } else if id.as_str().starts_with(\"https://\") || id.as_str().starts_with(\"http://\") {\n+ let display = id.display_path();\n+ let rest = display.strip_prefix(\"-/\").unwrap_or(display.as_str());\n+ let ext_prefix = format!(\"{}-\", garden_prefix.trim_end_matches('~'));\n+ format!(\"{}/{}\", ext_prefix, rest)\n+ } else {\n+ return None;\n+ };\n+ Some((id, href))\n+}\n+\n+fn push_item_ref_anchor(\n+ out: &mut String,\n+ raw_ref: &str,\n+ garden_prefix: &str,\n+ item_bodies: Option<&HashMap>,\n+) -> bool {\n+ let Some((id, href)) = garden_href_for_item_ref(raw_ref, garden_prefix) else {\n+ return false;\n+ };\n+ out.push_str(r#\"');\n+ out.push_str(&escape_html(raw_ref));\n+ out.push_str(\"\");\n+ true\n+}\n+\n+/// Replace item refs in raw prose with clickable garden links.\n ///\n /// When `item_bodies` is set, matching ontology items get a `title` attribute with a truncated\n /// body preview for native browser tooltips (forum posts, item pages).\n@@ -554,53 +625,16 @@ pub(super) fn linkify_slugs_with_prefix(\n garden_prefix: &str,\n item_bodies: Option<&HashMap>,\n ) -> String {\n- let escaped = escape_html(raw);\n- let mut out = String::with_capacity(escaped.len() + 64);\n- let mut i = 0;\n- let s = escaped.as_str();\n- while i < s.len() {\n- let rest = &s[i..];\n- if let Some(after_tilde) = rest.strip_prefix(\"~/\") {\n- let path_len = after_tilde\n- .chars()\n- .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-' || *c == '/')\n- .map(|c| c.len_utf8())\n- .sum::();\n- if path_len > 0 {\n- let path = &after_tilde[..path_len];\n- out.push_str(r#\" out.push_str(&escape_html(&text)),\n+ crate::dsl::ProseToken::ItemRef(raw_ref) => {\n+ if !push_item_ref_anchor(&mut out, &raw_ref, garden_prefix, item_bodies) {\n+ out.push_str(&escape_html(&raw_ref));\n }\n- out.push('>');\n- out.push_str(\"~/\");\n- out.push_str(path);\n- out.push_str(\"\");\n- i += 2 + path_len;\n- continue;\n }\n }\n- if let Some((j, c)) = rest.char_indices().next() {\n- out.push(c);\n- i += j + c.len_utf8();\n- } else {\n- break;\n- }\n }\n out\n }\n@@ -638,7 +672,13 @@ fn spotify_embed_src(url: &str) -> Option {\n if !(host == \"open.spotify.com\" || host == \"www.open.spotify.com\") {\n return None;\n }\n- let path = tail.split('#').next().unwrap_or(tail).split('?').next().unwrap_or(tail);\n+ let path = tail\n+ .split('#')\n+ .next()\n+ .unwrap_or(tail)\n+ .split('?')\n+ .next()\n+ .unwrap_or(tail);\n let mut segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();\n if segs.first().is_some_and(|s| s.starts_with(\"intl-\")) {\n segs.remove(0);\n@@ -670,8 +710,16 @@ fn youtube_embed_src(url: &str) -> Option {\n let host = host.to_lowercase();\n \n let video_id = if host == \"youtu.be\" || host == \"www.youtu.be\" {\n- clean_media_id(tail.split(['?', '#']).next().unwrap_or(tail).trim_matches('/'))\n- } else if matches!(host.as_str(), \"youtube.com\" | \"www.youtube.com\" | \"m.youtube.com\" | \"music.youtube.com\") {\n+ clean_media_id(\n+ tail.split(['?', '#'])\n+ .next()\n+ .unwrap_or(tail)\n+ .trim_matches('/'),\n+ )\n+ } else if matches!(\n+ host.as_str(),\n+ \"youtube.com\" | \"www.youtube.com\" | \"m.youtube.com\" | \"music.youtube.com\"\n+ ) {\n let path = format!(\"/{}\", tail.split('#').next().unwrap_or(tail));\n if path.starts_with(\"/watch\") {\n clean_media_id(&query_param(url, \"v\")?)\n@@ -745,10 +793,7 @@ pub(super) fn render_linkified_with_embeds_in_scope(\n /// CLI strings are embedded in a single-quoted JS literal; they must never need escaping.\n fn assert_cli_panel_cmd_js_single_quote_safe(s: &str) {\n assert!(\n- !s.contains('\\\\')\n- && !s.contains('\\'')\n- && !s.contains('\\n')\n- && !s.contains('\\r'),\n+ !s.contains('\\\\') && !s.contains('\\'') && !s.contains('\\n') && !s.contains('\\r'),\n \"cli_panel cmd must not contain `\\\\`, `'`, or newlines (got {s:?})\"\n );\n }\n@@ -805,15 +850,40 @@ mod linkify_title_tests {\n let mut bodies = HashMap::new();\n let key = ItemId::parse(&slug_types::canonicalize_item(\"~/foo/bar\")).unwrap();\n bodies.insert(key, \"Hello world\\nline\".to_string());\n- let html = linkify_slugs_with_prefix(\n- \"see ~/foo/bar ok\",\n- \"/r/x/~\",\n- Some(&bodies),\n- );\n+ let html = linkify_slugs_with_prefix(\"see ~/foo/bar ok\", \"/r/x/~\", Some(&bodies));\n assert!(html.contains(\"title=\\\"Hello world line\\\"\"));\n assert!(html.contains(\"href=\\\"/r/x/~/foo/bar\\\"\"));\n }\n \n+ #[test]\n+ fn raw_url_links_to_public_external_garden_page() {\n+ let html = linkify_slugs_with_prefix(\"see https://example.com/z.\", \"/~\", None);\n+ assert!(html\n+ .contains(r#\"https://example.com/z.\"#));\n+ }\n+\n+ #[test]\n+ fn dash_ref_links_to_room_external_garden_page_with_title() {\n+ let mut bodies = HashMap::new();\n+ let key = ItemId::parse(&slug_types::canonicalize_item(\"-/example.com/z\")).unwrap();\n+ bodies.insert(key, \"External body\\npreview\".to_string());\n+ let html =\n+ linkify_slugs_with_prefix(\"see -/example.com/z\", \"/r/9ab12cdroom/~\", Some(&bodies));\n+ assert!(html.contains(r#\"href=\"/r/9ab12cdroom/-/example.com/z\"\"#));\n+ assert!(html.contains(r#\"title=\"External body preview\"\"#));\n+ }\n+\n+ #[test]\n+ fn code_fence_urls_are_not_linkified() {\n+ let html = linkify_slugs_with_prefix(\n+ \"```json\\n{\\\"url\\\":\\\"https://example.com/z\\\"}\\n```\\nthen https://example.com/a\",\n+ \"/~\",\n+ None,\n+ );\n+ assert!(!html.contains(r#\"href=\"/-/example.com/z\"\"#));\n+ assert!(html.contains(r#\"href=\"/-/example.com/a\"\"#));\n+ }\n+\n #[test]\n fn no_title_when_body_missing_or_empty() {\n let html = linkify_slugs_with_prefix(\"x ~/a/b y\", \"/~\", Some(&HashMap::new()));\n\n\nSide B — contributor: tommy-mor\nSide B — commit message:\n[23c8134e] Fix /-/ external garden index; resolvers/ + GitHub import cards (#150)\n\n* Fix external garden root listing; add resolvers/ with GitHub cards\n\nThe public and room external index pages queried children of a bogus\nhttps://./ parent, so /-/ always looked empty. Collect host-only https\nroots from all Web items and item_children edges so ghost parents from\nadd_child_edge appear.\n\nMove GitHub resolver into server/src/resolvers/ with default_external.rs\nand a try_render_resolver_item_body hook. Resolver ingests now store\nslug-github-card fenced JSON; render_item_body_in_scope shows a small\nGitHub article card (with legacy support for schema-less json fences on\ngithub.com URLs). Styling in theme_default.css; agents.md updated.\n\nCo-authored-by: tommy \n\n* Vote compare: GitHub cards in columns, layout CSS, tests\n\nPass item_bodies into vote_compare_item_card for linkified tooltips on\nnon-card bodies; clone item_bodies before dropping reducer read guard.\n\nAdd layout rules so rich cards sit in the grid corners (default + retro).\n\nUnit test on vote_compare_item_card; integration GET /vote/compare with\ningested slug-github-card bodies. agents.md clarifies compare columns.\n\nCo-authored-by: tommy \n\n---------\n\nCo-authored-by: Cursor Agent \n\nSide B — unified diff (full patch):\ndiff --git a/agents.md b/agents.md\nindex 7508234d9b04223d0e64cfe69fedbebd06a256b5..d8b801e454fdf37e7ac6038b91a69f83b0746d59 100644\n--- a/agents.md\n+++ b/agents.md\n@@ -42,7 +42,7 @@ Strict **CSP** that blocks `eval` would break the current app. Other projects ma\n \n - **`VoteComparePost`:** On success returns **`text/javascript`** that **morphs** **`#vote-edge-history-region`** (recomputed **`
    `** — ratios match **`left`/`right`** query order, bullets, sorted by strength toward **`left`** then newer) and **`.vote-compare-nav`** (fresh next-pair link). The compare **`GET`** page uses **`layout_full_bleed_chromeless`** (no breadcrumbs, no **`#controls`**, no **`slug-pin-hud`**; **`view-vote-compare-fullscreen`** full-width **`body`**). **`__rpc__`** carries **`form_action: \"/ui\"`**; **`thread_tag`** and ratio fields come from the same form as **`$form`** holes.\n \n-- **`ResolveExternal`:** GitHub resolver buttons are browser actions through **`POST /ui`**. Success responses morph **`#external-resolver-status`** then redirect to the sanitized shareable **`GET`** page so imported children render through the normal page path; errors morph the same status region. Resolver results are durable system ingests, while cooldown state is RAM-only.\n+- **`ResolveExternal`:** GitHub resolver buttons are browser actions through **`POST /ui`**. Success responses morph **`#external-resolver-status`** then redirect to the sanitized shareable **`GET`** page so imported children render through the normal page path; errors morph the same status region. Resolver results are durable system ingests, while cooldown state is RAM-only. Implementation lives under **`server/src/resolvers/`** (GitHub resolver + import card JSON); ontology item pages and the **`GET /vote/compare`** left/right columns use **`render_item_body_in_scope`** in **`server/src/html/mod.rs`**, which calls **`server/src/resolvers/mod.rs::try_render_resolver_item_body`** before falling back to the usual **`
    `** linkified view.\n \n - **Garden pin / compare voting:** Cookie **`slug_garden_pin`** via **`set_garden_pin`**. Pairwise UI: **`GET /vote/compare?…`** / **`GET /r/:room_key/vote/compare?…`** (fullscreen **`GET`** page: no HUD; other garden pages). HUD (**`#slug-pin-hud`**): only when **`layout`** passes garden metadata on **`body`**; the label is **`POST /ui`** **`set_garden_pin`** **`clear:true`** (**`slug_ui.js`**), not a permalink to the item.\n \ndiff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs\nindex 4b0214d18b173cd506d09176104f461dc4c4f208..c9eb8e242072e41fcf70da838bdf02dd4c838db8 100644\n--- a/server/src/api/ui_html.rs\n+++ b/server/src/api/ui_html.rs\n@@ -18,7 +18,7 @@ use crate::{\n         rpc::{rpc_post_redact, rpc_post_with_bearer, rpc_room_delete},\n     },\n     canonical_path::canonicalize_tag,\n-    external_resolver::resolve_github_children,\n+    resolvers::resolve_github_children,\n     html::vote_compare_post_success_js,\n     html::{\n         external_resolver_status_markup, fragment_new_thread_slot, login_to_post_hint_markup,\ndiff --git a/server/src/external_resolver.rs b/server/src/external_resolver.rs\ndeleted file mode 100644\nindex a5812250fed7613950b5417f396f886a55fafccf..0000000000000000000000000000000000000000\n--- a/server/src/external_resolver.rs\n+++ /dev/null\n@@ -1,630 +0,0 @@\n-use async_trait::async_trait;\n-use serde_json::Value;\n-use tokio::sync::oneshot;\n-\n-use crate::{path_types::ItemId, state::AppState, write_cmd::WriteCmd};\n-\n-const GITHUB_SYSTEM_PRINCIPAL: &str = \"system:github-resolver\";\n-const GITHUB_RESOLVER_COOLDOWN_MS: i64 = 15_000;\n-const GITHUB_MAX_PAGES: usize = 3;\n-\n-fn now_ms() -> i64 {\n-    use std::time::{SystemTime, UNIX_EPOCH};\n-    SystemTime::now()\n-        .duration_since(UNIX_EPOCH)\n-        .unwrap_or_default()\n-        .as_millis() as i64\n-}\n-\n-#[derive(Debug, Clone, PartialEq, Eq)]\n-pub struct ResolvedChild {\n-    pub url: String,\n-    pub title: String,\n-    pub body: Option,\n-}\n-\n-#[async_trait]\n-pub trait ExternalResolver: Send + Sync {\n-    /// e.g. `\"github.com\"`\n-    fn domain_match(&self) -> &'static str;\n-\n-    /// Normalizes URLs (e.g. stripping fragments); extend per-domain later.\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, item: &ItemId) -> Result;\n-}\n-\n-#[derive(Clone)]\n-pub struct GitHubResolver {\n-    client: reqwest::Client,\n-    api_base_url: String,\n-    token: Option,\n-}\n-\n-impl GitHubResolver {\n-    pub fn from_env() -> Self {\n-        let api_base_url = std::env::var(\"SLUG_GITHUB_API_BASE_URL\")\n-            .ok()\n-            .filter(|s| !s.trim().is_empty())\n-            .unwrap_or_else(|| \"https://api.github.com\".to_string());\n-        let token = std::env::var(\"SLUG_GITHUB_TOKEN\")\n-            .ok()\n-            .filter(|s| !s.trim().is_empty());\n-        Self {\n-            client: reqwest::Client::new(),\n-            api_base_url: api_base_url.trim_end_matches('/').to_string(),\n-            token,\n-        }\n-    }\n-\n-    pub fn can_resolve_children(&self, item: &ItemId) -> bool {\n-        github_segments(item).is_some()\n-    }\n-\n-    pub async fn list_children(&self, item: &ItemId) -> Result, String> {\n-        let segments = github_segments(item).ok_or_else(|| \"not a GitHub URL\".to_string())?;\n-        match segments.as_slice() {\n-            [] => Ok(vec![]),\n-            [owner] => self.list_repos(owner).await,\n-            [owner, repo] => Ok(github_repo_sections(owner, repo)),\n-            [owner, repo, section] if section == \"issues\" => self.list_issues(owner, repo).await,\n-            [owner, repo, section] if section == \"pulls\" => self.list_pulls(owner, repo).await,\n-            [owner, repo, section] if section == \"commits\" => self.list_commits(owner, repo).await,\n-            [owner, repo, section] if section == \"releases\" => {\n-                self.list_releases(owner, repo).await\n-            }\n-            _ => Ok(vec![]),\n-        }\n-    }\n-\n-    async fn get_json(&self, path: &str) -> Result {\n-        let url = format!(\"{}/{}\", self.api_base_url, path.trim_start_matches('/'));\n-        let mut req = self\n-            .client\n-            .get(url)\n-            .header(reqwest::header::USER_AGENT, \"slugsocial-github-resolver\");\n-        if let Some(token) = &self.token {\n-            req = req.bearer_auth(token);\n-        }\n-        let resp = req\n-            .send()\n-            .await\n-            .map_err(|e| format!(\"GitHub request failed: {e}\"))?;\n-        let status = resp.status();\n-        if !status.is_success() {\n-            return Err(format!(\"GitHub request returned {status}\"));\n-        }\n-        resp.json::()\n-            .await\n-            .map_err(|e| format!(\"GitHub response JSON failed: {e}\"))\n-    }\n-\n-    async fn get_json_array_pages(&self, path: &str) -> Result, String> {\n-        let sep = if path.contains('?') { '&' } else { '?' };\n-        let mut out = Vec::new();\n-        for page in 1..=GITHUB_MAX_PAGES {\n-            let value = self.get_json(&format!(\"{path}{sep}page={page}\")).await?;\n-            let arr = value\n-                .as_array()\n-                .ok_or_else(|| \"GitHub paged response was not an array\".to_string())?;\n-            let n = arr.len();\n-            out.extend(arr.iter().cloned());\n-            if n < 100 {\n-                break;\n-            }\n-        }\n-        Ok(out)\n-    }\n-\n-    async fn list_repos(&self, owner: &str) -> Result, String> {\n-        let arr = self\n-            .get_json_array_pages(&format!(\n-                \"/users/{owner}/repos?per_page=100&sort=updated&type=owner\"\n-            ))\n-            .await?;\n-        let mut out = Vec::new();\n-        for repo in &arr {\n-            let name = repo\n-                .get(\"name\")\n-                .and_then(|v| v.as_str())\n-                .unwrap_or_default();\n-            if name.is_empty() {\n-                continue;\n-            }\n-            let full_name = repo\n-                .get(\"full_name\")\n-                .and_then(|v| v.as_str())\n-                .map(|s| s.to_ascii_lowercase())\n-                .unwrap_or_else(|| format!(\"{owner}/{name}\").to_ascii_lowercase());\n-            out.push(ResolvedChild {\n-                url: format!(\"https://github.com/{full_name}\"),\n-                title: full_name.clone(),\n-                body: Some(github_repo_body(repo)),\n-            });\n-        }\n-        out.sort_by(|a, b| a.url.cmp(&b.url));\n-        Ok(out)\n-    }\n-\n-    async fn list_issues(&self, owner: &str, repo: &str) -> Result, String> {\n-        let arr = self\n-            .get_json_array_pages(&format!(\n-                \"/repos/{owner}/{repo}/issues?state=open&per_page=100\"\n-            ))\n-            .await?;\n-        let mut out = Vec::new();\n-        for issue in &arr {\n-            if issue.get(\"pull_request\").is_some() {\n-                continue;\n-            }\n-            let Some(number) = issue.get(\"number\").and_then(|v| v.as_i64()) else {\n-                continue;\n-            };\n-            let title = issue\n-                .get(\"title\")\n-                .and_then(|v| v.as_str())\n-                .unwrap_or(\"Untitled issue\");\n-            out.push(ResolvedChild {\n-                url: format!(\"https://github.com/{owner}/{repo}/issues/{number}\"),\n-                title: format!(\"#{number} {title}\"),\n-                body: Some(github_issue_body(issue, \"issue\")),\n-            });\n-        }\n-        out.sort_by(|a, b| a.url.cmp(&b.url));\n-        Ok(out)\n-    }\n-\n-    async fn list_pulls(&self, owner: &str, repo: &str) -> Result, String> {\n-        let arr = self\n-            .get_json_array_pages(&format!(\n-                \"/repos/{owner}/{repo}/pulls?state=open&per_page=100\"\n-            ))\n-            .await?;\n-        let mut out = Vec::new();\n-        for pull in &arr {\n-            let Some(number) = pull.get(\"number\").and_then(|v| v.as_i64()) else {\n-                continue;\n-            };\n-            let title = pull\n-                .get(\"title\")\n-                .and_then(|v| v.as_str())\n-                .unwrap_or(\"Untitled pull request\");\n-            out.push(ResolvedChild {\n-                url: format!(\"https://github.com/{owner}/{repo}/pulls/{number}\"),\n-                title: format!(\"#{number} {title}\"),\n-                body: Some(github_issue_body(pull, \"pull request\")),\n-            });\n-        }\n-        out.sort_by(|a, b| a.url.cmp(&b.url));\n-        Ok(out)\n-    }\n-\n-    async fn list_commits(&self, owner: &str, repo: &str) -> Result, String> {\n-        let arr = self\n-            .get_json_array_pages(&format!(\"/repos/{owner}/{repo}/commits?per_page=100\"))\n-            .await?;\n-        let mut out = Vec::new();\n-        for commit in &arr {\n-            let Some(sha) = github_string(commit, \"sha\") else {\n-                continue;\n-            };\n-            let short = sha.chars().take(7).collect::();\n-            let title = commit\n-                .get(\"commit\")\n-                .and_then(|c| c.get(\"message\"))\n-                .and_then(|v| v.as_str())\n-                .and_then(|m| m.lines().next())\n-                .filter(|s| !s.trim().is_empty())\n-                .unwrap_or(\"commit\");\n-            let url = github_string(commit, \"html_url\")\n-                .map(|s| s.to_string())\n-                .unwrap_or_else(|| format!(\"https://github.com/{owner}/{repo}/commit/{sha}\"));\n-            out.push(ResolvedChild {\n-                url,\n-                title: format!(\"{short} {title}\"),\n-                body: Some(github_commit_body(commit)),\n-            });\n-        }\n-        out.sort_by(|a, b| a.url.cmp(&b.url));\n-        Ok(out)\n-    }\n-\n-    async fn list_releases(&self, owner: &str, repo: &str) -> Result, String> {\n-        let arr = self\n-            .get_json_array_pages(&format!(\"/repos/{owner}/{repo}/releases?per_page=100\"))\n-            .await?;\n-        let mut out = Vec::new();\n-        for release in &arr {\n-            let Some(tag) = github_string(release, \"tag_name\") else {\n-                continue;\n-            };\n-            let title = github_string(release, \"name\").unwrap_or(tag);\n-            let url = github_string(release, \"html_url\")\n-                .map(|s| s.to_string())\n-                .unwrap_or_else(|| format!(\"https://github.com/{owner}/{repo}/releases/tag/{tag}\"));\n-            out.push(ResolvedChild {\n-                url,\n-                title: title.to_string(),\n-                body: Some(github_release_body(release)),\n-            });\n-        }\n-        out.sort_by(|a, b| a.url.cmp(&b.url));\n-        Ok(out)\n-    }\n-}\n-\n-fn github_segments(item: &ItemId) -> Option> {\n-    let url = url::Url::parse(item.as_str()).ok()?;\n-    if url.host_str()?.eq_ignore_ascii_case(\"github.com\") {\n-        Some(\n-            url.path_segments()\n-                .map(|segments| {\n-                    segments\n-                        .filter(|s| !s.is_empty())\n-                        .map(|s| s.to_ascii_lowercase())\n-                        .collect::>()\n-                })\n-                .unwrap_or_default(),\n-        )\n-    } else {\n-        None\n-    }\n-}\n-\n-fn github_repo_sections(owner: &str, repo: &str) -> Vec {\n-    [\n-        (\"issues\", \"GitHub issues for this repository.\"),\n-        (\"pulls\", \"GitHub pull requests for this repository.\"),\n-        (\"commits\", \"GitHub commits for this repository.\"),\n-        (\"releases\", \"GitHub releases for this repository.\"),\n-    ]\n-    .into_iter()\n-    .map(|(section, body)| ResolvedChild {\n-        url: format!(\"https://github.com/{owner}/{repo}/{section}\"),\n-        title: section.to_string(),\n-        body: Some(body.to_string()),\n-    })\n-    .collect()\n-}\n-\n-fn resolver_thread_tag(item: &ItemId) -> String {\n-    let tail = item\n-        .display_path()\n-        .trim_start_matches(\"-/\")\n-        .replace('/', \":\")\n-        .replace('?', \":\");\n-    format!(\"import:{tail}\")\n-}\n-\n-fn sanitize_body(s: &str) -> String {\n-    s.replace('{', \"(\")\n-        .replace('}', \")\")\n-        .replace(\"```\", \"` ` `\")\n-        .chars()\n-        .take(4_000)\n-        .collect()\n-}\n-\n-fn github_string<'a>(value: &'a Value, key: &str) -> Option<&'a str> {\n-    value\n-        .get(key)\n-        .and_then(|v| v.as_str())\n-        .filter(|s| !s.trim().is_empty())\n-}\n-\n-fn github_user_login(value: &Value) -> Option<&str> {\n-    value\n-        .get(\"user\")\n-        .and_then(|u| u.get(\"login\"))\n-        .and_then(|v| v.as_str())\n-        .filter(|s| !s.trim().is_empty())\n-}\n-\n-fn github_labels(value: &Value) -> Vec {\n-    value\n-        .get(\"labels\")\n-        .and_then(|v| v.as_array())\n-        .into_iter()\n-        .flat_map(|labels| labels.iter())\n-        .filter_map(|label| label.get(\"name\").and_then(|v| v.as_str()))\n-        .filter(|name| !name.trim().is_empty())\n-        .map(|name| name.to_string())\n-        .collect()\n-}\n-\n-fn github_repo_body(repo: &Value) -> String {\n-    let full_name = github_string(repo, \"full_name\")\n-        .or_else(|| github_string(repo, \"name\"))\n-        .unwrap_or(\"GitHub repository\");\n-    let mut lines = vec![full_name.to_string()];\n-    if let Some(desc) = github_string(repo, \"description\") {\n-        lines.push(String::new());\n-        lines.push(desc.to_string());\n-    }\n-    if let Some(url) = github_string(repo, \"html_url\") {\n-        lines.push(String::new());\n-        lines.push(format!(\"Source: {url}\"));\n-    }\n-    if let Some(lang) = github_string(repo, \"language\") {\n-        lines.push(format!(\"Language: {lang}\"));\n-    }\n-    lines.join(\"\\n\")\n-}\n-\n-fn github_issue_body(issue: &Value, kind: &str) -> String {\n-    let number = issue\n-        .get(\"number\")\n-        .and_then(|v| v.as_i64())\n-        .map(|n| format!(\"#{n} \"))\n-        .unwrap_or_default();\n-    let title = github_string(issue, \"title\").unwrap_or(\"Untitled\");\n-    let state = github_string(issue, \"state\").unwrap_or(\"unknown\");\n-    let mut lines = vec![format!(\"{kind} {number}{title}\")];\n-    lines.push(format!(\"State: {state}\"));\n-    if let Some(author) = github_user_login(issue) {\n-        lines.push(format!(\"Author: @{author}\"));\n-    }\n-    let labels = github_labels(issue);\n-    if !labels.is_empty() {\n-        lines.push(format!(\"Labels: {}\", labels.join(\", \")));\n-    }\n-    if let Some(url) = github_string(issue, \"html_url\") {\n-        lines.push(format!(\"Source: {url}\"));\n-    }\n-    if let Some(body) = github_string(issue, \"body\") {\n-        lines.push(String::new());\n-        lines.push(body.to_string());\n-    }\n-    lines.join(\"\\n\")\n-}\n-\n-fn github_commit_body(commit: &Value) -> String {\n-    let sha = github_string(commit, \"sha\").unwrap_or(\"unknown\");\n-    let short = sha.chars().take(7).collect::();\n-    let commit_obj = commit.get(\"commit\");\n-    let message = commit_obj\n-        .and_then(|c| c.get(\"message\"))\n-        .and_then(|v| v.as_str())\n-        .unwrap_or(\"commit\");\n-    let mut lines = vec![format!(\"commit {short}\")];\n-    if let Some(author) = commit_obj\n-        .and_then(|c| c.get(\"author\"))\n-        .and_then(|a| a.get(\"name\"))\n-        .and_then(|v| v.as_str())\n-        .filter(|s| !s.trim().is_empty())\n-    {\n-        lines.push(format!(\"Author: {author}\"));\n-    }\n-    if let Some(login) = github_user_login(commit) {\n-        lines.push(format!(\"GitHub user: @{login}\"));\n-    }\n-    if let Some(date) = commit_obj\n-        .and_then(|c| c.get(\"author\"))\n-        .and_then(|a| a.get(\"date\"))\n-        .and_then(|v| v.as_str())\n-    {\n-        lines.push(format!(\"Date: {date}\"));\n-    }\n-    if let Some(url) = github_string(commit, \"html_url\") {\n-        lines.push(format!(\"Source: {url}\"));\n-    }\n-    lines.push(String::new());\n-    lines.push(message.to_string());\n-    lines.join(\"\\n\")\n-}\n-\n-fn github_release_body(release: &Value) -> String {\n-    let tag = github_string(release, \"tag_name\").unwrap_or(\"untagged\");\n-    let title = github_string(release, \"name\").unwrap_or(tag);\n-    let mut lines = vec![format!(\"release {title}\")];\n-    lines.push(format!(\"Tag: {tag}\"));\n-    if release\n-        .get(\"draft\")\n-        .and_then(|v| v.as_bool())\n-        .unwrap_or(false)\n-    {\n-        lines.push(\"Draft: yes\".to_string());\n-    }\n-    if release\n-        .get(\"prerelease\")\n-        .and_then(|v| v.as_bool())\n-        .unwrap_or(false)\n-    {\n-        lines.push(\"Prerelease: yes\".to_string());\n-    }\n-    if let Some(author) = github_user_login(release) {\n-        lines.push(format!(\"Author: @{author}\"));\n-    }\n-    if let Some(published) = github_string(release, \"published_at\") {\n-        lines.push(format!(\"Published: {published}\"));\n-    }\n-    if let Some(url) = github_string(release, \"html_url\") {\n-        lines.push(format!(\"Source: {url}\"));\n-    }\n-    if let Some(body) = github_string(release, \"body\") {\n-        lines.push(String::new());\n-        lines.push(body.to_string());\n-    }\n-    lines.join(\"\\n\")\n-}\n-\n-fn children_to_dsl(children: &[ResolvedChild]) -> String {\n-    let mut out = String::new();\n-    for child in children {\n-        let body = child\n-            .body\n-            .as_deref()\n-            .filter(|s| !s.trim().is_empty())\n-            .unwrap_or(child.title.as_str());\n-        if body.trim_start().starts_with(\"```\") {\n-            out.push_str(&format!(\"{} {{\\n{}\\n}}\\n\\n\", child.url, body.trim()));\n-        } else {\n-            out.push_str(&format!(\n-                \"{} {{\\n{}\\n}}\\n\\n\",\n-                child.url,\n-                sanitize_body(body)\n-            ));\n-        }\n-    }\n-    out\n-}\n-\n-pub async fn resolve_github_children(\n-    state: &AppState,\n-    room: &str,\n-    item: &ItemId,\n-) -> Result {\n-    if !state.github_resolver.can_resolve_children(item) {\n-        return Err(\"no GitHub resolver for this item\".to_string());\n-    }\n-\n-    let key = format!(\"github:{}:{}\", room.trim(), item.as_str());\n-    let now = now_ms();\n-    {\n-        let mut runs = state.resolver_runs.write().await;\n-        if let Some(last) = runs.get(&key) {\n-            let remaining = GITHUB_RESOLVER_COOLDOWN_MS - (now - *last);\n-            if remaining > 0 {\n-                return Err(format!(\n-                    \"GitHub resolver cooldown: try again in {}s\",\n-                    (remaining + 999) / 1000\n-                ));\n-            }\n-        }\n-        runs.insert(key, now);\n-    }\n-\n-    let children = state.github_resolver.list_children(item).await?;\n-    if children.is_empty() {\n-        return Ok(0);\n-    }\n-    let text = children_to_dsl(&children);\n-    let thread_tag = resolver_thread_tag(item);\n-    let (tx, rx) = oneshot::channel();\n-    state\n-        .write_tx\n-        .send(WriteCmd::SystemIngest {\n-            room: room.to_string(),\n-            thread_tag,\n-            text,\n-            principal: GITHUB_SYSTEM_PRINCIPAL.to_string(),\n-            reply: tx,\n-        })\n-        .await\n-        .map_err(|_| \"writer unavailable\".to_string())?;\n-    rx.await\n-        .map_err(|_| \"writer dropped\".to_string())?\n-        .map_err(|(msg, hint)| hint.map_or(msg.clone(), |h| format!(\"{msg}: {h}\")))?;\n-    Ok(children.len())\n-}\n-\n-/// Placeholder until other domain-specific resolvers exist.\n-pub struct DefaultExternalResolver;\n-\n-#[async_trait]\n-impl ExternalResolver for DefaultExternalResolver {\n-    fn domain_match(&self) -> &'static str {\n-        \"\"\n-    }\n-\n-    fn normalize(&self, path: &str) -> String {\n-        path.to_string()\n-    }\n-\n-    async fn fetch_body(&self, _item: &ItemId) -> Result {\n-        Err(\"external fetch not implemented\".to_string())\n-    }\n-}\n-\n-#[cfg(test)]\n-mod tests {\n-    use super::*;\n-\n-    #[test]\n-    fn github_segments_parse_normalized_url() {\n-        let item = ItemId::parse(\"https://github.com/Sortersocial/Slug/issues\").unwrap();\n-        assert_eq!(\n-            github_segments(&item),\n-            Some(vec![\n-                \"sortersocial\".to_string(),\n-                \"slug\".to_string(),\n-                \"issues\".to_string()\n-            ])\n-        );\n-    }\n-\n-    #[test]\n-    fn repo_sections_are_direct_children() {\n-        let sections = github_repo_sections(\"sortersocial\", \"slug\");\n-        let urls: Vec = sections.into_iter().map(|c| c.url).collect();\n-        assert!(urls.contains(&\"https://github.com/sortersocial/slug/issues\".to_string()));\n-        assert!(urls.contains(&\"https://github.com/sortersocial/slug/pulls\".to_string()));\n-    }\n-\n-    #[test]\n-    fn children_to_dsl_contains_item_bodies() {\n-        let dsl = children_to_dsl(&[ResolvedChild {\n-            url: \"https://github.com/o/r/issues/1\".into(),\n-            title: \"#1 title\".into(),\n-            body: Some(\"body with {braces}\".into()),\n-        }]);\n-        assert!(dsl.contains(\"https://github.com/o/r/issues/1\"));\n-        assert!(dsl.contains(\"body with (braces)\"));\n-    }\n-\n-    #[test]\n-    fn children_to_dsl_preserves_fenced_json_bodies() {\n-        let dsl = children_to_dsl(&[ResolvedChild {\n-            url: \"https://github.com/o/r/issues/1\".into(),\n-            title: \"#1 title\".into(),\n-            body: Some(\"```json\\n{\\\"test\\\": true}\\n```\".into()),\n-        }]);\n-        assert!(dsl.contains(\"https://github.com/o/r/issues/1 {\\n```json\"));\n-        assert!(dsl.contains(\"{\\\"test\\\": true}\"));\n-        assert!(dsl.contains(\"```\\n}\\n\"));\n-    }\n-\n-    #[test]\n-    fn github_issue_body_is_readable_text_not_json_dump() {\n-        let issue = serde_json::json!({\n-            \"number\": 12,\n-            \"title\": \"Render children\",\n-            \"state\": \"open\",\n-            \"html_url\": \"https://github.com/o/r/issues/12\",\n-            \"user\": {\"login\": \"octo\"},\n-            \"labels\": [{\"name\": \"bug\"}],\n-            \"body\": \"The issue body.\"\n-        });\n-        let body = github_issue_body(&issue, \"issue\");\n-        assert!(body.contains(\"issue #12 Render children\"));\n-        assert!(body.contains(\"Author: @octo\"));\n-        assert!(body.contains(\"The issue body.\"));\n-        assert!(!body.trim_start().starts_with(\"```json\"));\n-    }\n-\n-    #[test]\n-    fn github_commit_and_release_bodies_are_readable() {\n-        let commit = serde_json::json!({\n-            \"sha\": \"abcdef123456\",\n-            \"html_url\": \"https://github.com/o/r/commit/abcdef123456\",\n-            \"author\": {\"login\": \"octo\"},\n-            \"commit\": {\n-                \"message\": \"Fix vote page\\n\\nDetails here.\",\n-                \"author\": {\"name\": \"Octo Dev\", \"date\": \"2026-05-17T00:00:00Z\"}\n-            }\n-        });\n-        let release = serde_json::json!({\n-            \"tag_name\": \"v1.2.3\",\n-            \"name\": \"Release 1.2.3\",\n-            \"html_url\": \"https://github.com/o/r/releases/tag/v1.2.3\",\n-            \"author\": {\"login\": \"octo\"},\n-            \"prerelease\": true,\n-            \"body\": \"Release notes.\"\n-        });\n-        assert!(github_commit_body(&commit).contains(\"commit abcdef1\"));\n-        assert!(github_commit_body(&commit).contains(\"Fix vote page\"));\n-        assert!(github_release_body(&release).contains(\"release Release 1.2.3\"));\n-        assert!(github_release_body(&release).contains(\"Prerelease: yes\"));\n-    }\n-}\ndiff --git a/server/src/html/garden.rs b/server/src/html/garden.rs\nindex 9ca66e7c5860d428e95abf5df518fc1e7b4f6332..e2dc6e5529d4a3126723d0dea75931d0738b6c83 100644\n--- a/server/src/html/garden.rs\n+++ b/server/src/html/garden.rs\n@@ -7,7 +7,7 @@ use axum_extra::extract::cookie::CookieJar;\n use maud::html;\n use serde::Deserialize;\n use serde_json::json;\n-use std::collections::HashSet;\n+use std::collections::{HashMap, HashSet};\n \n use base64::{engine::general_purpose::URL_SAFE_NO_PAD as B64_ENGINE, Engine as _};\n \n@@ -21,8 +21,8 @@ use crate::{\n     path_types::ItemId,\n     reducer::{ContentState, ReducerState, ScopeId},\n     scope_rank::{\n-        build_children_rankings, build_rankings_for_item_set, resolve_scope_recursive,\n-        suggest_next_pair_in_pool, ChildrenRankings,\n+        build_children_rankings, build_rankings_for_item_set, external_root_host_items,\n+        resolve_scope_recursive, suggest_next_pair_in_pool, ChildrenRankings,\n     },\n     state::AppState,\n     timeago,\n@@ -33,7 +33,7 @@ use super::{\n     breadcrumb_path::{ExternalOntologyPath, OntologyPath},\n     cli_panel,\n     forum::ThreadNav,\n-    layout, layout_full_bleed_chromeless, now_ms, ratio_pct, render_linkified_with_embeds_in_scope,\n+    layout, layout_full_bleed_chromeless, now_ms, ratio_pct, render_item_body_in_scope,\n     theme_from_jar, theme_next_from_uri,\n };\n \n@@ -358,6 +358,7 @@ fn vote_compare_item_card(\n     item: &ItemId,\n     body: Option<&String>,\n     side_class: &str,\n+    item_bodies: Option<&HashMap>,\n ) -> maud::Markup {\n     html! {\n         div class=(format!(\"vote-compare-side {side_class}\")) {\n@@ -366,10 +367,10 @@ fn vote_compare_item_card(\n             }\n             @if let Some(body) = body.filter(|b| !b.trim().is_empty()) {\n                 div class=\"vote-compare-item-body\" {\n-                    (render_linkified_with_embeds_in_scope(\n+                    (render_item_body_in_scope(\n                         body,\n                         nav.garden_root_url(),\n-                        None,\n+                        item_bodies,\n                     ))\n                 }\n             } @else {\n@@ -678,10 +679,11 @@ pub async fn external_garden_index(\n ) -> impl IntoResponse {\n     let nav = ThreadNav::public();\n     let ext_path = ExternalOntologyPath::from_input(\"\");\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+        let content = reduced.public();\n+        let hosts = external_root_host_items(content);\n+        build_rankings_for_item_set(content, &hosts)\n     };\n \n     let url_key = canonical_view_url(&uri);\n@@ -812,9 +814,11 @@ 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 = ItemId::parse(\"https://.\").unwrap();\n-    let child_rankings =\n-        build_children_rankings(content_for_garden_view(&reduced, &nav.scope()), &parent);\n+    let child_rankings = {\n+        let content = content_for_garden_view(&reduced, &nav.scope());\n+        let hosts = external_root_host_items(content);\n+        build_rankings_for_item_set(content, &hosts)\n+    };\n     drop(reduced);\n \n     let url_key = canonical_view_url(&uri);\n@@ -1334,7 +1338,7 @@ async fn render_scope_view(\n                 }\n                 @if let Some(body) = &model.body {\n                     div class=\"ont-item-content\" {\n-                        (render_linkified_with_embeds_in_scope(\n+                        (render_item_body_in_scope(\n                             body,\n                             nav.garden_root_url(),\n                             Some(&scope_content.item_bodies),\n@@ -1592,6 +1596,7 @@ async fn vote_compare_inner(\n     let edge_history = vote_edge_history_markup(content, &left, &right);\n     let left_body = content.item_bodies.get(&left).cloned();\n     let right_body = content.item_bodies.get(&right).cloned();\n+    let item_bodies_for_cards = content.item_bodies.clone();\n     let next_pair = suggest_next_vote_pair(content, &left, &right);\n     drop(reduced);\n \n@@ -1623,9 +1628,21 @@ async fn vote_compare_inner(\n     section class=\"vote-compare-shell\" {\n         h2 { \"compare\" }\n         div class=\"vote-compare-pair\" {\n-            (vote_compare_item_card(&nav, &left, left_body.as_ref(), \"vote-compare-left\"))\n+            (vote_compare_item_card(\n+                &nav,\n+                &left,\n+                left_body.as_ref(),\n+                \"vote-compare-left\",\n+                Some(&item_bodies_for_cards),\n+            ))\n             span class=\"vote-compare-vs\" { \"vs\" }\n-            (vote_compare_item_card(&nav, &right, right_body.as_ref(), \"vote-compare-right\"))\n+            (vote_compare_item_card(\n+                &nav,\n+                &right,\n+                right_body.as_ref(),\n+                \"vote-compare-right\",\n+                Some(&item_bodies_for_cards),\n+            ))\n         }\n         (vote_compare_nav_markup(&nav, next_pair.as_ref(), &left, &right, q.thread.as_deref()))\n         div id=\"vote-edge-history-region\" {\n@@ -2020,6 +2037,40 @@ mod tests {\n         assert!(items.contains(\"https://slug.social/~/topic/b\"));\n     }\n \n+    #[test]\n+    fn vote_compare_item_card_renders_github_import_markup() {\n+        use crate::html::forum::ThreadNav;\n+        use super::vote_compare_item_card;\n+        use crate::path_types::ItemId;\n+\n+        let nav = ThreadNav::public();\n+        let item = ItemId::parse(\"https://github.com/o/r/issues/1\").unwrap();\n+        let json = serde_json::json!({\n+            \"v\": 1,\n+            \"schema\": \"slug_github_import\",\n+            \"kind\": \"issue\",\n+            \"url\": \"https://github.com/o/r/issues/1\",\n+            \"headline\": \"#1 Compare card\",\n+            \"sublines\": [\"State: open\"],\n+        });\n+        let body = format!(\"```slug-github-card\\n{}\\n```\", json.to_string());\n+        let html = vote_compare_item_card(\n+            &nav,\n+            &item,\n+            Some(&body),\n+            \"vote-compare-left\",\n+            None,\n+        )\n+        .into_string();\n+        assert!(\n+            html.contains(\"github-import-card\"),\n+            \"expected rich GitHub card markup, got: {html}\"\n+        );\n+        assert!(html.contains(\"item-body-rich\"));\n+        assert!(html.contains(\"vote-compare-left\"));\n+        assert!(html.contains(\"#1 Compare card\"));\n+    }\n+\n     #[test]\n     fn external_source_href_maps_youtube_path_identity_back_to_watch_url() {\n         assert_eq!(\ndiff --git a/server/src/html/mod.rs b/server/src/html/mod.rs\nindex a1b929625acbd5298c0cf62f3ca0892079edcb2a..3b23e19a8b35aa4c0b0480e29de7d46ad57ab276 100644\n--- a/server/src/html/mod.rs\n+++ b/server/src/html/mod.rs\n@@ -793,6 +793,20 @@ pub(super) fn render_linkified_with_embeds_in_scope(\n     }\n }\n \n+/// Item page / thread body: resolver-specific rich HTML, else linkified `
    ` + media embeds.\n+pub(super) fn render_item_body_in_scope(\n+    raw: &str,\n+    garden_prefix: &str,\n+    item_bodies: Option<&HashMap>,\n+) -> Markup {\n+    if let Some(m) = crate::resolvers::try_render_resolver_item_body(raw) {\n+        return html! {\n+            div class=\"item-body-rich\" { (m) }\n+        };\n+    }\n+    render_linkified_with_embeds_in_scope(raw, garden_prefix, item_bodies)\n+}\n+\n /// CLI strings are embedded in a single-quoted JS literal; they must never need escaping.\n fn assert_cli_panel_cmd_js_single_quote_safe(s: &str) {\n     assert!(\ndiff --git a/server/src/lib.rs b/server/src/lib.rs\nindex 84e94bbec144eae77de68482385941cd2c5845eb..c1d477d21aea03aff00e6f0689b0b4379d0d68d2 100644\n--- a/server/src/lib.rs\n+++ b/server/src/lib.rs\n@@ -5,7 +5,7 @@ pub mod canonical_path;\n pub mod dsl;\n pub mod event_log;\n pub mod events;\n-pub mod external_resolver;\n+pub mod resolvers;\n pub mod form_template;\n pub mod html;\n pub mod identity;\n@@ -51,7 +51,7 @@ pub fn create_app_state(cfg: AppConfig) -> AppState {\n         write_tx,\n         views,\n         resolver_runs: Arc::new(RwLock::new(HashMap::new())),\n-        github_resolver: Arc::new(crate::external_resolver::GitHubResolver::from_env()),\n+        github_resolver: Arc::new(crate::resolvers::GitHubResolver::from_env()),\n     };\n     tokio::spawn(crate::api::write_actor::writer_actor(\n         write_rx,\ndiff --git a/server/src/resolvers/default_external.rs b/server/src/resolvers/default_external.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..d37c222abcee3c20b22189b2822da9e9a6ff0515\n--- /dev/null\n+++ b/server/src/resolvers/default_external.rs\n@@ -0,0 +1,22 @@\n+use async_trait::async_trait;\n+\n+use crate::path_types::ItemId;\n+use super::github::ExternalResolver;\n+\n+/// Placeholder until other domain-specific resolvers exist.\n+pub struct DefaultExternalResolver;\n+\n+#[async_trait]\n+impl ExternalResolver for DefaultExternalResolver {\n+    fn domain_match(&self) -> &'static str {\n+        \"\"\n+    }\n+\n+    fn normalize(&self, path: &str) -> String {\n+        path.to_string()\n+    }\n+\n+    async fn fetch_body(&self, _item: &ItemId) -> Result {\n+        Err(\"external fetch not implemented\".to_string())\n+    }\n+}\ndiff --git a/server/src/resolvers/github.rs b/server/src/resolvers/github.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..5a9c0c38ff01ca5894f7dc62c1008371dacb0cf1\n--- /dev/null\n+++ b/server/src/resolvers/github.rs\n@@ -0,0 +1,755 @@\n+use async_trait::async_trait;\n+use maud::html;\n+use serde::{Deserialize, Serialize};\n+use serde_json::Value;\n+use tokio::sync::oneshot;\n+\n+use crate::{path_types::ItemId, state::AppState, write_cmd::WriteCmd};\n+\n+pub const SLUG_GITHUB_SCHEMA: &str = \"slug_github_import\";\n+\n+const GITHUB_SYSTEM_PRINCIPAL: &str = \"system:github-resolver\";\n+const GITHUB_RESOLVER_COOLDOWN_MS: i64 = 15_000;\n+const GITHUB_MAX_PAGES: usize = 3;\n+\n+fn now_ms() -> i64 {\n+    use std::time::{SystemTime, UNIX_EPOCH};\n+    SystemTime::now()\n+        .duration_since(UNIX_EPOCH)\n+        .unwrap_or_default()\n+        .as_millis() as i64\n+}\n+\n+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]\n+#[serde(rename_all = \"snake_case\")]\n+pub enum GithubImportKind {\n+    Repo,\n+    RepoSection,\n+    Issue,\n+    Pull,\n+    Commit,\n+    Release,\n+}\n+\n+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]\n+pub struct GithubImportCard {\n+    pub v: u32,\n+    #[serde(default)]\n+    pub schema: String,\n+    pub kind: GithubImportKind,\n+    pub url: String,\n+    pub headline: String,\n+    #[serde(default)]\n+    pub sublines: Vec,\n+    #[serde(default)]\n+    pub excerpt: Option,\n+}\n+\n+impl GithubImportCard {\n+    fn new(kind: GithubImportKind, url: String, headline: String) -> Self {\n+        Self {\n+            v: 1,\n+            schema: SLUG_GITHUB_SCHEMA.to_string(),\n+            kind,\n+            url,\n+            headline,\n+            sublines: Vec::new(),\n+            excerpt: None,\n+        }\n+    }\n+}\n+\n+#[derive(Debug, Clone, PartialEq, Eq)]\n+pub struct ResolvedChild {\n+    pub url: String,\n+    pub title: String,\n+    pub card: GithubImportCard,\n+}\n+\n+#[async_trait]\n+pub trait ExternalResolver: Send + Sync {\n+    /// e.g. `\"github.com\"`\n+    fn domain_match(&self) -> &'static str;\n+\n+    /// Normalizes URLs (e.g. stripping fragments); extend per-domain later.\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, item: &ItemId) -> Result;\n+}\n+\n+#[derive(Clone)]\n+pub struct GitHubResolver {\n+    client: reqwest::Client,\n+    api_base_url: String,\n+    token: Option,\n+}\n+\n+impl GitHubResolver {\n+    pub fn from_env() -> Self {\n+        let api_base_url = std::env::var(\"SLUG_GITHUB_API_BASE_URL\")\n+            .ok()\n+            .filter(|s| !s.trim().is_empty())\n+            .unwrap_or_else(|| \"https://api.github.com\".to_string());\n+        let token = std::env::var(\"SLUG_GITHUB_TOKEN\")\n+            .ok()\n+            .filter(|s| !s.trim().is_empty());\n+        Self {\n+            client: reqwest::Client::new(),\n+            api_base_url: api_base_url.trim_end_matches('/').to_string(),\n+            token,\n+        }\n+    }\n+\n+    pub fn can_resolve_children(&self, item: &ItemId) -> bool {\n+        github_segments(item).is_some()\n+    }\n+\n+    pub async fn list_children(&self, item: &ItemId) -> Result, String> {\n+        let segments = github_segments(item).ok_or_else(|| \"not a GitHub URL\".to_string())?;\n+        match segments.as_slice() {\n+            [] => Ok(vec![]),\n+            [owner] => self.list_repos(owner).await,\n+            [owner, repo] => Ok(github_repo_sections(owner, repo)),\n+            [owner, repo, section] if section == \"issues\" => self.list_issues(owner, repo).await,\n+            [owner, repo, section] if section == \"pulls\" => self.list_pulls(owner, repo).await,\n+            [owner, repo, section] if section == \"commits\" => self.list_commits(owner, repo).await,\n+            [owner, repo, section] if section == \"releases\" => {\n+                self.list_releases(owner, repo).await\n+            }\n+            _ => Ok(vec![]),\n+        }\n+    }\n+\n+    async fn get_json(&self, path: &str) -> Result {\n+        let url = format!(\"{}/{}\", self.api_base_url, path.trim_start_matches('/'));\n+        let mut req = self\n+            .client\n+            .get(url)\n+            .header(reqwest::header::USER_AGENT, \"slugsocial-github-resolver\");\n+        if let Some(token) = &self.token {\n+            req = req.bearer_auth(token);\n+        }\n+        let resp = req\n+            .send()\n+            .await\n+            .map_err(|e| format!(\"GitHub request failed: {e}\"))?;\n+        let status = resp.status();\n+        if !status.is_success() {\n+            return Err(format!(\"GitHub request returned {status}\"));\n+        }\n+        resp.json::()\n+            .await\n+            .map_err(|e| format!(\"GitHub response JSON failed: {e}\"))\n+    }\n+\n+    async fn get_json_array_pages(&self, path: &str) -> Result, String> {\n+        let sep = if path.contains('?') { '&' } else { '?' };\n+        let mut out = Vec::new();\n+        for page in 1..=GITHUB_MAX_PAGES {\n+            let value = self.get_json(&format!(\"{path}{sep}page={page}\")).await?;\n+            let arr = value\n+                .as_array()\n+                .ok_or_else(|| \"GitHub paged response was not an array\".to_string())?;\n+            let n = arr.len();\n+            out.extend(arr.iter().cloned());\n+            if n < 100 {\n+                break;\n+            }\n+        }\n+        Ok(out)\n+    }\n+\n+    async fn list_repos(&self, owner: &str) -> Result, String> {\n+        let arr = self\n+            .get_json_array_pages(&format!(\n+                \"/users/{owner}/repos?per_page=100&sort=updated&type=owner\"\n+            ))\n+            .await?;\n+        let mut out = Vec::new();\n+        for repo in &arr {\n+            let name = repo\n+                .get(\"name\")\n+                .and_then(|v| v.as_str())\n+                .unwrap_or_default();\n+            if name.is_empty() {\n+                continue;\n+            }\n+            let full_name = repo\n+                .get(\"full_name\")\n+                .and_then(|v| v.as_str())\n+                .map(|s| s.to_ascii_lowercase())\n+                .unwrap_or_else(|| format!(\"{owner}/{name}\").to_ascii_lowercase());\n+            let url = format!(\"https://github.com/{full_name}\");\n+            let mut card = card_for_repo(repo, &url);\n+            card.headline = full_name.clone();\n+            out.push(ResolvedChild {\n+                url,\n+                title: full_name,\n+                card,\n+            });\n+        }\n+        out.sort_by(|a, b| a.url.cmp(&b.url));\n+        Ok(out)\n+    }\n+\n+    async fn list_issues(&self, owner: &str, repo: &str) -> Result, String> {\n+        let arr = self\n+            .get_json_array_pages(&format!(\n+                \"/repos/{owner}/{repo}/issues?state=open&per_page=100\"\n+            ))\n+            .await?;\n+        let mut out = Vec::new();\n+        for issue in &arr {\n+            if issue.get(\"pull_request\").is_some() {\n+                continue;\n+            }\n+            let Some(number) = issue.get(\"number\").and_then(|v| v.as_i64()) else {\n+                continue;\n+            };\n+            let title = issue\n+                .get(\"title\")\n+                .and_then(|v| v.as_str())\n+                .unwrap_or(\"Untitled issue\");\n+            let url = format!(\"https://github.com/{owner}/{repo}/issues/{number}\");\n+            let card = card_for_issue(issue, &url, GithubImportKind::Issue);\n+            out.push(ResolvedChild {\n+                url: url.clone(),\n+                title: format!(\"#{number} {title}\"),\n+                card,\n+            });\n+        }\n+        out.sort_by(|a, b| a.url.cmp(&b.url));\n+        Ok(out)\n+    }\n+\n+    async fn list_pulls(&self, owner: &str, repo: &str) -> Result, String> {\n+        let arr = self\n+            .get_json_array_pages(&format!(\n+                \"/repos/{owner}/{repo}/pulls?state=open&per_page=100\"\n+            ))\n+            .await?;\n+        let mut out = Vec::new();\n+        for pull in &arr {\n+            let Some(number) = pull.get(\"number\").and_then(|v| v.as_i64()) else {\n+                continue;\n+            };\n+            let title = pull\n+                .get(\"title\")\n+                .and_then(|v| v.as_str())\n+                .unwrap_or(\"Untitled pull request\");\n+            let url = format!(\"https://github.com/{owner}/{repo}/pulls/{number}\");\n+            let card = card_for_issue(pull, &url, GithubImportKind::Pull);\n+            out.push(ResolvedChild {\n+                url: url.clone(),\n+                title: format!(\"#{number} {title}\"),\n+                card,\n+            });\n+        }\n+        out.sort_by(|a, b| a.url.cmp(&b.url));\n+        Ok(out)\n+    }\n+\n+    async fn list_commits(&self, owner: &str, repo: &str) -> Result, String> {\n+        let arr = self\n+            .get_json_array_pages(&format!(\"/repos/{owner}/{repo}/commits?per_page=100\"))\n+            .await?;\n+        let mut out = Vec::new();\n+        for commit in &arr {\n+            let Some(sha) = github_string(commit, \"sha\") else {\n+                continue;\n+            };\n+            let short = sha.chars().take(7).collect::();\n+            let title = commit\n+                .get(\"commit\")\n+                .and_then(|c| c.get(\"message\"))\n+                .and_then(|v| v.as_str())\n+                .and_then(|m| m.lines().next())\n+                .filter(|s| !s.trim().is_empty())\n+                .unwrap_or(\"commit\");\n+            let url = github_string(commit, \"html_url\")\n+                .map(|s| s.to_string())\n+                .unwrap_or_else(|| format!(\"https://github.com/{owner}/{repo}/commit/{sha}\"));\n+            let card = card_for_commit(commit, &url, &short, title);\n+            out.push(ResolvedChild {\n+                url: url.clone(),\n+                title: format!(\"{short} {title}\"),\n+                card,\n+            });\n+        }\n+        out.sort_by(|a, b| a.url.cmp(&b.url));\n+        Ok(out)\n+    }\n+\n+    async fn list_releases(&self, owner: &str, repo: &str) -> Result, String> {\n+        let arr = self\n+            .get_json_array_pages(&format!(\"/repos/{owner}/{repo}/releases?per_page=100\"))\n+            .await?;\n+        let mut out = Vec::new();\n+        for release in &arr {\n+            let Some(tag) = github_string(release, \"tag_name\") else {\n+                continue;\n+            };\n+            let title = github_string(release, \"name\").unwrap_or(tag);\n+            let url = github_string(release, \"html_url\")\n+                .map(|s| s.to_string())\n+                .unwrap_or_else(|| format!(\"https://github.com/{owner}/{repo}/releases/tag/{tag}\"));\n+            let card = card_for_release(release, &url, title);\n+            out.push(ResolvedChild {\n+                url: url.clone(),\n+                title: title.to_string(),\n+                card,\n+            });\n+        }\n+        out.sort_by(|a, b| a.url.cmp(&b.url));\n+        Ok(out)\n+    }\n+}\n+\n+fn github_segments(item: &ItemId) -> Option> {\n+    let url = url::Url::parse(item.as_str()).ok()?;\n+    if url.host_str()?.eq_ignore_ascii_case(\"github.com\") {\n+        Some(\n+            url.path_segments()\n+                .map(|segments| {\n+                    segments\n+                        .filter(|s| !s.is_empty())\n+                        .map(|s| s.to_ascii_lowercase())\n+                        .collect::>()\n+                })\n+                .unwrap_or_default(),\n+        )\n+    } else {\n+        None\n+    }\n+}\n+\n+fn title_case_segment(seg: &str) -> String {\n+    let mut c = seg.chars();\n+    match c.next() {\n+        None => String::new(),\n+        Some(f) => f.to_uppercase().chain(c).collect(),\n+    }\n+}\n+\n+fn github_repo_sections(owner: &str, repo: &str) -> Vec {\n+    [\n+        (\"issues\", \"GitHub issues for this repository.\"),\n+        (\"pulls\", \"GitHub pull requests for this repository.\"),\n+        (\"commits\", \"GitHub commits for this repository.\"),\n+        (\"releases\", \"GitHub releases for this repository.\"),\n+    ]\n+    .into_iter()\n+    .map(|(section, blurb)| {\n+        let url = format!(\"https://github.com/{owner}/{repo}/{section}\");\n+        let mut card = GithubImportCard::new(\n+            GithubImportKind::RepoSection,\n+            url.clone(),\n+            format!(\"{owner}/{repo} — {}\", title_case_segment(section)),\n+        );\n+        card.excerpt = Some(blurb.to_string());\n+        ResolvedChild {\n+            url,\n+            title: section.to_string(),\n+            card,\n+        }\n+    })\n+    .collect()\n+}\n+\n+fn resolver_thread_tag(item: &ItemId) -> String {\n+    let tail = item\n+        .display_path()\n+        .trim_start_matches(\"-/\")\n+        .replace('/', \":\")\n+        .replace('?', \":\");\n+    format!(\"import:{tail}\")\n+}\n+\n+fn children_to_dsl(children: &[ResolvedChild]) -> String {\n+    let mut out = String::new();\n+    for child in children {\n+        let json = serde_json::to_string(&child.card).unwrap_or_else(|_| \"{}\".to_string());\n+        let inner = format!(\"```slug-github-card\\n{json}\\n```\");\n+        out.push_str(&format!(\"{} {{\\n{}\\n}}\\n\\n\", child.url, inner));\n+    }\n+    out\n+}\n+\n+fn card_for_repo(repo: &Value, fallback_url: &str) -> GithubImportCard {\n+    let url = github_string(repo, \"html_url\")\n+        .map(|s| s.to_string())\n+        .filter(|s| !s.is_empty())\n+        .unwrap_or_else(|| fallback_url.to_string());\n+    let full_name = github_string(repo, \"full_name\")\n+        .or_else(|| github_string(repo, \"name\"))\n+        .unwrap_or(\"repository\");\n+    let mut card = GithubImportCard::new(GithubImportKind::Repo, url, full_name.to_string());\n+    if let Some(lang) = github_string(repo, \"language\") {\n+        card.sublines.push(format!(\"Language: {lang}\"));\n+    }\n+    if let Some(desc) = github_string(repo, \"description\") {\n+        card.excerpt = Some(desc.to_string());\n+    }\n+    card\n+}\n+\n+fn excerpt_from_github_body(body: Option<&str>) -> Option {\n+    let b = body?.trim();\n+    if b.is_empty() {\n+        return None;\n+    }\n+    let max = 1200usize;\n+    if b.len() <= max {\n+        Some(b.to_string())\n+    } else {\n+        Some(format!(\"{}…\", b.chars().take(max).collect::()))\n+    }\n+}\n+\n+fn card_for_issue(v: &Value, url: &str, kind: GithubImportKind) -> GithubImportCard {\n+    let number = v.get(\"number\").and_then(|n| n.as_i64());\n+    let title = github_string(v, \"title\").unwrap_or(\"Untitled\");\n+    let state = github_string(v, \"state\").unwrap_or(\"unknown\");\n+    let headline = match number {\n+        Some(n) => format!(\"#{n} {title}\"),\n+        None => title.to_string(),\n+    };\n+    let mut card = GithubImportCard::new(kind, url.to_string(), headline);\n+    card.sublines.push(format!(\"State: {state}\"));\n+    if let Some(a) = github_user_login(v) {\n+        card.sublines.push(format!(\"Author: @{a}\"));\n+    }\n+    let labels = github_labels(v);\n+    if !labels.is_empty() {\n+        card.sublines\n+            .push(format!(\"Labels: {}\", labels.join(\", \")));\n+    }\n+    card.excerpt = excerpt_from_github_body(github_string(v, \"body\"));\n+    card\n+}\n+\n+fn card_for_commit(v: &Value, url: &str, short_sha: &str, subject: &str) -> GithubImportCard {\n+    let headline = format!(\"{short_sha} {subject}\");\n+    let mut card = GithubImportCard::new(GithubImportKind::Commit, url.to_string(), headline);\n+    if let Some(name) = v\n+        .get(\"commit\")\n+        .and_then(|c| c.get(\"author\"))\n+        .and_then(|a| a.get(\"name\"))\n+        .and_then(|n| n.as_str())\n+        .filter(|s| !s.trim().is_empty())\n+    {\n+        card.sublines.push(format!(\"Author: {name}\"));\n+    }\n+    if let Some(login) = github_user_login(v) {\n+        card.sublines.push(format!(\"GitHub: @{login}\"));\n+    }\n+    if let Some(date) = v\n+        .get(\"commit\")\n+        .and_then(|c| c.get(\"author\"))\n+        .and_then(|a| a.get(\"date\"))\n+        .and_then(|d| d.as_str())\n+    {\n+        card.sublines.push(format!(\"Date: {date}\"));\n+    }\n+    if let Some(msg) = v\n+        .get(\"commit\")\n+        .and_then(|c| c.get(\"message\"))\n+        .and_then(|m| m.as_str())\n+    {\n+        card.excerpt = excerpt_from_github_body(Some(msg));\n+    }\n+    card\n+}\n+\n+fn card_for_release(v: &Value, url: &str, title: &str) -> GithubImportCard {\n+    let tag = github_string(v, \"tag_name\").unwrap_or(\"untagged\");\n+    let mut card = GithubImportCard::new(\n+        GithubImportKind::Release,\n+        url.to_string(),\n+        format!(\"Release — {title}\"),\n+    );\n+    card.sublines.push(format!(\"Tag: {tag}\"));\n+    if v.get(\"draft\").and_then(|b| b.as_bool()).unwrap_or(false) {\n+        card.sublines.push(\"Draft: yes\".to_string());\n+    }\n+    if v.get(\"prerelease\")\n+        .and_then(|b| b.as_bool())\n+        .unwrap_or(false)\n+    {\n+        card.sublines.push(\"Prerelease: yes\".to_string());\n+    }\n+    if let Some(a) = github_user_login(v) {\n+        card.sublines.push(format!(\"Author: @{a}\"));\n+    }\n+    if let Some(pub_at) = github_string(v, \"published_at\") {\n+        card.sublines.push(format!(\"Published: {pub_at}\"));\n+    }\n+    card.excerpt = excerpt_from_github_body(github_string(v, \"body\"));\n+    card\n+}\n+\n+fn github_string<'a>(value: &'a Value, key: &str) -> Option<&'a str> {\n+    value\n+        .get(key)\n+        .and_then(|v| v.as_str())\n+        .filter(|s| !s.trim().is_empty())\n+}\n+\n+fn github_user_login(value: &Value) -> Option<&str> {\n+    value\n+        .get(\"user\")\n+        .and_then(|u| u.get(\"login\"))\n+        .and_then(|v| v.as_str())\n+        .filter(|s| !s.trim().is_empty())\n+}\n+\n+fn github_labels(value: &Value) -> Vec {\n+    value\n+        .get(\"labels\")\n+        .and_then(|v| v.as_array())\n+        .into_iter()\n+        .flat_map(|labels| labels.iter())\n+        .filter_map(|label| label.get(\"name\").and_then(|v| v.as_str()))\n+        .filter(|name| !name.trim().is_empty())\n+        .map(|name| name.to_string())\n+        .collect()\n+}\n+\n+pub async fn resolve_github_children(\n+    state: &AppState,\n+    room: &str,\n+    item: &ItemId,\n+) -> Result {\n+    if !state.github_resolver.can_resolve_children(item) {\n+        return Err(\"no GitHub resolver for this item\".to_string());\n+    }\n+\n+    let key = format!(\"github:{}:{}\", room.trim(), item.as_str());\n+    let now = now_ms();\n+    {\n+        let mut runs = state.resolver_runs.write().await;\n+        if let Some(last) = runs.get(&key) {\n+            let remaining = GITHUB_RESOLVER_COOLDOWN_MS - (now - *last);\n+            if remaining > 0 {\n+                return Err(format!(\n+                    \"GitHub resolver cooldown: try again in {}s\",\n+                    (remaining + 999) / 1000\n+                ));\n+            }\n+        }\n+        runs.insert(key, now);\n+    }\n+\n+    let children = state.github_resolver.list_children(item).await?;\n+    if children.is_empty() {\n+        return Ok(0);\n+    }\n+    let text = children_to_dsl(&children);\n+    let thread_tag = resolver_thread_tag(item);\n+    let (tx, rx) = oneshot::channel();\n+    state\n+        .write_tx\n+        .send(WriteCmd::SystemIngest {\n+            room: room.to_string(),\n+            thread_tag,\n+            text,\n+            principal: GITHUB_SYSTEM_PRINCIPAL.to_string(),\n+            reply: tx,\n+        })\n+        .await\n+        .map_err(|_| \"writer unavailable\".to_string())?;\n+    rx.await\n+        .map_err(|_| \"writer dropped\".to_string())?\n+        .map_err(|(msg, hint)| hint.map_or(msg.clone(), |h| format!(\"{msg}: {h}\")))?;\n+    Ok(children.len())\n+}\n+\n+fn extract_fence<'a>(body: &'a str, lang: &str) -> Option<&'a str> {\n+    let b = body.trim();\n+    let prefix = format!(\"```{lang}\");\n+    let rest = b.strip_prefix(prefix.as_str())?;\n+    let rest = rest\n+        .strip_prefix('\\n')\n+        .or_else(|| rest.strip_prefix('\\r'))\n+        .unwrap_or(rest);\n+    let end = rest.find(\"\\n```\")?;\n+    Some(rest[..end].trim())\n+}\n+\n+fn parse_github_import_from_body(body: &str) -> Option {\n+    let trimmed = body.trim();\n+    if let Some(json) = extract_fence(trimmed, \"slug-github-card\") {\n+        let c: GithubImportCard = serde_json::from_str(json).ok()?;\n+        return (c.v == 1 && (c.schema.is_empty() || c.schema == SLUG_GITHUB_SCHEMA)).then_some(c);\n+    }\n+    if let Some(json) = extract_fence(trimmed, \"json\") {\n+        if let Ok(c) = serde_json::from_str::(json) {\n+            if c.v == 1\n+                && (c.schema == SLUG_GITHUB_SCHEMA\n+                    || (c.schema.is_empty() && c.url.contains(\"github.com\")))\n+            {\n+                return Some(c);\n+            }\n+        }\n+    }\n+    if trimmed.starts_with('{') {\n+        let c: GithubImportCard = serde_json::from_str(trimmed).ok()?;\n+        return (c.v == 1\n+            && (c.schema == SLUG_GITHUB_SCHEMA\n+                || (c.schema.is_empty() && c.url.contains(\"github.com\"))))\n+        .then_some(c);\n+    }\n+    None\n+}\n+\n+fn kind_badge(kind: &GithubImportKind) -> &'static str {\n+    match kind {\n+        GithubImportKind::Repo => \"GitHub · repository\",\n+        GithubImportKind::RepoSection => \"GitHub · tree\",\n+        GithubImportKind::Issue => \"GitHub · issue\",\n+        GithubImportKind::Pull => \"GitHub · pull request\",\n+        GithubImportKind::Commit => \"GitHub · commit\",\n+        GithubImportKind::Release => \"GitHub · release\",\n+    }\n+}\n+\n+fn render_github_card(card: &GithubImportCard) -> maud::Markup {\n+    html! {\n+        article.github-import-card {\n+            header.github-import-card__hdr {\n+                span class=\"github-import-card__badge\" { (kind_badge(&card.kind)) }\n+                h3.github-import-card__title { (card.headline.as_str()) }\n+            }\n+            @if !card.sublines.is_empty() {\n+                ul.github-import-card__meta {\n+                    @for line in &card.sublines {\n+                        li { (line.as_str()) }\n+                    }\n+                }\n+            }\n+            @if let Some(ex) = &card.excerpt {\n+                div.github-import-card__excerpt {\n+                    @for block in ex.split(\"\\n\\n\") {\n+                        @if !block.trim().is_empty() {\n+                            p { (block) }\n+                        }\n+                    }\n+                }\n+            }\n+            p.github-import-card__link {\n+                a href=(card.url.as_str()) rel=\"noopener noreferrer\" target=\"_blank\" {\n+                    \"Open on GitHub\"\n+                }\n+            }\n+        }\n+    }\n+}\n+\n+/// Rich HTML for bodies that contain a [`GithubImportCard`] fence (or equivalent JSON).\n+pub fn try_render_github_import_markup(raw: &str) -> Option {\n+    let card = parse_github_import_from_body(raw)?;\n+    Some(render_github_card(&card))\n+}\n+\n+#[async_trait]\n+impl ExternalResolver for GitHubResolver {\n+    fn domain_match(&self) -> &'static str {\n+        \"github.com\"\n+    }\n+\n+    fn normalize(&self, path: &str) -> String {\n+        path.to_string()\n+    }\n+\n+    async fn fetch_body(&self, _item: &ItemId) -> Result {\n+        Err(\"GitHub fetch_body not implemented\".to_string())\n+    }\n+}\n+\n+#[cfg(test)]\n+mod tests {\n+    use super::*;\n+\n+    #[test]\n+    fn github_segments_parse_normalized_url() {\n+        let item = ItemId::parse(\"https://github.com/Sortersocial/Slug/issues\").unwrap();\n+        assert_eq!(\n+            github_segments(&item),\n+            Some(vec![\n+                \"sortersocial\".to_string(),\n+                \"slug\".to_string(),\n+                \"issues\".to_string()\n+            ])\n+        );\n+    }\n+\n+    #[test]\n+    fn repo_sections_are_direct_children() {\n+        let sections = github_repo_sections(\"sortersocial\", \"slug\");\n+        let urls: Vec = sections.into_iter().map(|c| c.url).collect();\n+        assert!(urls.contains(&\"https://github.com/sortersocial/slug/issues\".to_string()));\n+        assert!(urls.contains(&\"https://github.com/sortersocial/slug/pulls\".to_string()));\n+    }\n+\n+    #[test]\n+    fn children_to_dsl_wraps_slug_github_card() {\n+        let dsl = children_to_dsl(&[ResolvedChild {\n+            url: \"https://github.com/o/r/issues/1\".into(),\n+            title: \"#1 title\".into(),\n+            card: GithubImportCard::new(\n+                GithubImportKind::Issue,\n+                \"https://github.com/o/r/issues/1\".into(),\n+                \"#1 title\".into(),\n+            ),\n+        }]);\n+        assert!(dsl.contains(\"https://github.com/o/r/issues/1\"));\n+        assert!(dsl.contains(\"```slug-github-card\"));\n+        assert!(dsl.contains(\"\\\"schema\\\":\\\"slug_github_import\\\"\"));\n+    }\n+\n+    #[test]\n+    fn parse_accepts_slug_github_fence() {\n+        let card = GithubImportCard::new(\n+            GithubImportKind::Repo,\n+            \"https://github.com/o/r\".into(),\n+            \"o/r\".into(),\n+        );\n+        let body = format!(\"```slug-github-card\\n{}\\n```\\n\", serde_json::to_string(&card).unwrap());\n+        let parsed = parse_github_import_from_body(&body).expect(\"parses\");\n+        assert_eq!(parsed, card);\n+    }\n+\n+    #[test]\n+    fn parse_accepts_schema_json_fence() {\n+        let card = GithubImportCard::new(\n+            GithubImportKind::Issue,\n+            \"https://github.com/o/r/issues/2\".into(),\n+            \"#2 hi\".into(),\n+        );\n+        let json = serde_json::to_string(&card).unwrap();\n+        let body = format!(\"```json\\n{json}\\n```\");\n+        let parsed = parse_github_import_from_body(&body).expect(\"parses json fence\");\n+        assert_eq!(parsed.headline, \"#2 hi\");\n+    }\n+\n+    #[test]\n+    fn issue_card_includes_author_and_excerpt() {\n+        let issue = serde_json::json!({\n+            \"number\": 12,\n+            \"title\": \"Render children\",\n+            \"state\": \"open\",\n+            \"html_url\": \"https://github.com/o/r/issues/12\",\n+            \"user\": {\"login\": \"octo\"},\n+            \"labels\": [{\"name\": \"bug\"}],\n+            \"body\": \"The issue body.\"\n+        });\n+        let card = card_for_issue(\n+            &issue,\n+            \"https://github.com/o/r/issues/12\",\n+            GithubImportKind::Issue,\n+        );\n+        assert!(card.sublines.iter().any(|l| l.contains(\"@octo\")));\n+        assert_eq!(card.excerpt.as_deref(), Some(\"The issue body.\").as_deref());\n+    }\n+}\ndiff --git a/server/src/resolvers/mod.rs b/server/src/resolvers/mod.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..3e4caad081acdd2f89cba9f661de43996d6470f3\n--- /dev/null\n+++ b/server/src/resolvers/mod.rs\n@@ -0,0 +1,18 @@\n+//! Domain resolvers (GitHub, …) and matching HTML renderers for imported item bodies.\n+//!\n+//! Resolver output is ingested as DSL; bodies may embed a `slug-github-card` fenced JSON\n+//! envelope that [`crate::html::render_item_body_in_scope`] renders instead of a raw `
    `.\n+\n+pub mod github;\n+pub mod default_external;\n+\n+pub use default_external::DefaultExternalResolver;\n+pub use github::{\n+    resolve_github_children, try_render_github_import_markup, ExternalResolver, GitHubResolver,\n+    GithubImportCard, GithubImportKind, ResolvedChild,\n+};\n+\n+/// Extension point: add more `try_render_*` calls here as new resolvers ship.\n+pub fn try_render_resolver_item_body(raw: &str) -> Option {\n+    github::try_render_github_import_markup(raw)\n+}\ndiff --git a/server/src/scope_rank.rs b/server/src/scope_rank.rs\nindex 06c560b8eff09b34896d3935d3917fb28f602bc6..2361b2be5ae6b8e1813b6b7ebd5bbf317429b6ad 100644\n--- a/server/src/scope_rank.rs\n+++ b/server/src/scope_rank.rs\n@@ -162,6 +162,45 @@ pub fn build_children_rankings(content: &ContentState, parent: &ItemId) -> Child\n     build_rankings_for_item_set(content, &items)\n }\n \n+/// Host-only `https://…` roots for the external garden index (`/-/`).\n+///\n+/// Includes every `https://host` ancestor of any [`ItemId::Web`] item that appears in\n+/// `content.items`, as a parent key in `item_children`, or as a child in `item_children`\n+/// (so implied “ghost” parents created only via [`ReducerState::add_child_edge`] still show up).\n+pub fn external_root_host_items(content: &ContentState) -> Vec {\n+    let mut hosts: HashSet = HashSet::new();\n+\n+    let mut consider = |id: ItemId| {\n+        let id = id.normalized_storage();\n+        if !matches!(&id, ItemId::Web(_)) {\n+            return;\n+        }\n+        let mut cur = id;\n+        while let Some(p) = cur.parent() {\n+            cur = p.normalized_storage();\n+        }\n+        if matches!(cur, ItemId::Web(_)) {\n+            hosts.insert(cur);\n+        }\n+    };\n+\n+    for it in &content.items {\n+        consider(it.clone());\n+    }\n+    for parent in content.item_children.keys() {\n+        consider(parent.clone());\n+    }\n+    for set in content.item_children.values() {\n+        for ch in set {\n+            consider(ch.clone());\n+        }\n+    }\n+\n+    let mut out: Vec = hosts.into_iter().collect();\n+    out.sort();\n+    out\n+}\n+\n pub fn is_pair_voted_in_group(group: &GroupState, a: &ItemId, b: &ItemId) -> bool {\n     let Some(&a_idx) = group.item_to_idx.get(a) else {\n         return false;\n@@ -305,4 +344,29 @@ mod tests {\n         assert!(next.0 == c || next.1 == c);\n         assert_ne!(canonical_pair(&next.0, &next.1), canonical_pair(&a, &b));\n     }\n+\n+    #[test]\n+    fn external_root_hosts_include_ghost_chain_hosts() {\n+        use crate::reducer::ContentState;\n+        let gh = ItemId::parse(\"https://github.com\").unwrap();\n+        let org = ItemId::parse(\"https://github.com/org\").unwrap();\n+        let repo = ItemId::parse(\"https://github.com/org/rep\").unwrap();\n+        let mut item_children: HashMap> = HashMap::new();\n+        item_children.entry(gh.clone()).or_default().insert(org.clone());\n+        item_children.entry(org.clone()).or_default().insert(repo.clone());\n+        let mut items = HashSet::new();\n+        items.insert(repo.clone());\n+        let content = ContentState {\n+            ranking_group: crate::reducer::GroupState::new(),\n+            items,\n+            item_bodies: HashMap::new(),\n+            item_children,\n+            item_votes: HashMap::new(),\n+            item_snippets: HashMap::new(),\n+            item_threads: HashMap::new(),\n+            rank_history: HashMap::new(),\n+        };\n+        let roots = external_root_host_items(&content);\n+        assert_eq!(roots, vec![gh]);\n+    }\n }\ndiff --git a/server/src/state.rs b/server/src/state.rs\nindex 48298e2e66456268d23a6462536eb32bfeb5f29b..648ab5304764a329fcabbbbcd3782b94e3e005a8 100644\n--- a/server/src/state.rs\n+++ b/server/src/state.rs\n@@ -4,7 +4,7 @@ use std::sync::Arc;\n use tokio::sync::{broadcast, mpsc, RwLock};\n \n use crate::{\n-    event_log::EventLog, events::ThreadCapability, external_resolver::GitHubResolver,\n+    event_log::EventLog, events::ThreadCapability, resolvers::GitHubResolver,\n     reducer::ReducerState, write_cmd::WriteCmd,\n };\n \ndiff --git a/server/static/theme_default.css b/server/static/theme_default.css\nindex 184e11a590e7019773f7f0abfa41e79161556c71..7ea5f502f9b0b6341ce56d60ae883479070760d6 100644\n--- a/server/static/theme_default.css\n+++ b/server/static/theme_default.css\n@@ -1023,6 +1023,23 @@ body.view-vote-compare .vote-compare-shell > h2 {\n   line-height: 1.35;\n   padding: 8px 10px;\n }\n+.vote-compare-item-body .item-body-rich {\n+  min-width: 0;\n+  text-align: start;\n+}\n+.vote-compare-right .vote-compare-item-body .item-body-rich {\n+  display: flex;\n+  flex-direction: column;\n+  align-items: flex-end;\n+}\n+.vote-compare-item-body .item-body-rich article.github-import-card {\n+  box-sizing: border-box;\n+  width: 100%;\n+  max-width: min(100%, 420px);\n+}\n+.vote-compare-right .vote-compare-item-body .item-body-rich article.github-import-card {\n+  margin-left: auto;\n+}\n .vote-compare-item-body-empty {\n   font-size: 12px;\n   margin: 8px 0 0;\n@@ -1675,3 +1692,47 @@ body.view-ontology-light .rank-history-cause {\n body.view-ontology-light .rank-history-vote {\n   margin-top: 6px;\n }\n+\n+/* GitHub resolver import cards (rich bodies on -/ garden + vote compare) */\n+article.github-import-card {\n+  border: 1px solid var(--lo);\n+  background: var(--g2);\n+  border-radius: 6px;\n+  padding: 12px 14px;\n+  margin: 8px 0;\n+  max-width: 100%;\n+}\n+.github-import-card__hdr {\n+  margin-bottom: 6px;\n+}\n+.github-import-card__badge {\n+  display: block;\n+  font-size: 0.78em;\n+  color: var(--muted);\n+  margin-bottom: 4px;\n+}\n+.github-import-card__title {\n+  margin: 0;\n+  font-size: 1.05em;\n+  font-weight: 600;\n+}\n+ul.github-import-card__meta {\n+  margin: 8px 0 0 1.1em;\n+  padding: 0;\n+  font-size: 0.9em;\n+}\n+.github-import-card__meta li {\n+  margin: 2px 0;\n+}\n+.github-import-card__excerpt {\n+  margin-top: 10px;\n+  font-size: 0.92em;\n+  white-space: pre-wrap;\n+}\n+.github-import-card__excerpt p {\n+  margin: 6px 0;\n+}\n+.github-import-card__link {\n+  margin-top: 12px;\n+  font-size: 0.95em;\n+}\ndiff --git a/server/static/theme_retro.css b/server/static/theme_retro.css\nindex 6747f59eb1ec5c335029fe92d4e5c55b3125a210..d366be6fc8e8fcbc8122b8954b1e356ee36e6bc9 100644\n--- a/server/static/theme_retro.css\n+++ b/server/static/theme_retro.css\n@@ -278,3 +278,20 @@ body.view-ontology .vote-compare-item-body pre {\n   border: 1px solid #ccc;\n   padding: 0.5rem 0.65rem;\n }\n+body.view-ontology .vote-compare-item-body .item-body-rich {\n+  min-width: 0;\n+  text-align: start;\n+}\n+body.view-ontology .vote-compare-right .vote-compare-item-body .item-body-rich {\n+  display: flex;\n+  flex-direction: column;\n+  align-items: flex-end;\n+}\n+body.view-ontology .vote-compare-item-body .item-body-rich article.github-import-card {\n+  box-sizing: border-box;\n+  width: 100%;\n+  max-width: min(100%, 420px);\n+}\n+body.view-ontology .vote-compare-right .vote-compare-item-body .item-body-rich article.github-import-card {\n+  margin-left: auto;\n+}\ndiff --git a/server/static/theme_retro_craft.css b/server/static/theme_retro_craft.css\nindex 55d984a6dd70ebeadeca7baef86b844955f1d78c..d5bc384437f05f001924630947457d416772e950 100644\n--- a/server/static/theme_retro_craft.css\n+++ b/server/static/theme_retro_craft.css\n@@ -907,6 +907,23 @@ body.view-ontology .vote-compare-item-body pre {\n   line-height: 1.35;\n   padding: 0.55rem 0.65rem;\n }\n+body.view-ontology .vote-compare-item-body .item-body-rich {\n+  min-width: 0;\n+  text-align: start;\n+}\n+body.view-ontology .vote-compare-right .vote-compare-item-body .item-body-rich {\n+  display: flex;\n+  flex-direction: column;\n+  align-items: flex-end;\n+}\n+body.view-ontology .vote-compare-item-body .item-body-rich article.github-import-card {\n+  box-sizing: border-box;\n+  width: 100%;\n+  max-width: min(100%, 420px);\n+}\n+body.view-ontology .vote-compare-right .vote-compare-item-body .item-body-rich article.github-import-card {\n+  margin-left: auto;\n+}\n body.view-ontology .vote-compare-item-body-empty {\n   font-size: 0.78rem;\n   margin: 0.45rem 0 0;\ndiff --git a/server/tests/integration.rs b/server/tests/integration.rs\nindex fb0b9335440181d4d50104d37926b0b2eeeb602a..d979000292b6a39db7c7b54f2b804adb9cd39369 100644\n--- a/server/tests/integration.rs\n+++ b/server/tests/integration.rs\n@@ -3,7 +3,7 @@ use sha2::{Digest, Sha256};\n use slug_types::{room_route_segment, ItemId};\n use slugsocial_server::{\n     event_log::EventLog,\n-    events::{Event, TokenIssued, UserRegistered},\n+    events::{Event, Ingest, TokenIssued, UserRegistered},\n     middleware::canonical_view_url,\n     spawn_writer_actor_for_test,\n     state::{AppConfig, AppState},\n@@ -1614,6 +1614,71 @@ async fn test_view_counts_increment_and_display() {\n     );\n }\n \n+#[tokio::test]\n+async fn test_vote_compare_renders_github_import_cards() {\n+    let (addr, _tmp, _log, state, _handle) = create_test_server_with_state().await;\n+    let client = reqwest::Client::new();\n+\n+    let raw = \"@00000000-0000-0000-0000-000000000000:test:local/test\\n\\\n+https://github.com/ghvotehi/a/issues/9 {\\n\\\n+```slug-github-card\\n\\\n+{\\\"v\\\":1,\\\"schema\\\":\\\"slug_github_import\\\",\\\"kind\\\":\\\"issue\\\",\\\"url\\\":\\\"https://github.com/ghvotehi/a/issues/9\\\",\\\"headline\\\":\\\"#9 Left corner\\\",\\\"sublines\\\":[\\\"State: open\\\"]}\\n\\\n+```\\n\\\n+}\\n\\\n+\\n\\\n+https://github.com/ghvotehi/a/issues/10 {\\n\\\n+```slug-github-card\\n\\\n+{\\\"v\\\":1,\\\"schema\\\":\\\"slug_github_import\\\",\\\"kind\\\":\\\"issue\\\",\\\"url\\\":\\\"https://github.com/ghvotehi/a/issues/10\\\",\\\"headline\\\":\\\"#10 Right corner\\\",\\\"sublines\\\":[\\\"State: open\\\"]}\\n\\\n+```\\n\\\n+}\\n\";\n+\n+    {\n+        let mut w = state.reduced.write().await;\n+        w.apply_event(Event::Ingest(Ingest {\n+            ts: 10,\n+            id: \"ing-vote-github-cards\".to_string(),\n+            raw: raw.to_string(),\n+            principal: \"testuser\".to_string(),\n+            delegate: Some(\n+                \"00000000-0000-0000-0000-000000000000:test:local/test\".to_string(),\n+            ),\n+            room_id: \"public\".to_string(),\n+            thread_tag: \"gh-vote-cards\".to_string(),\n+        }));\n+    }\n+\n+    let left = ItemId::parse(\"https://github.com/ghvotehi/a/issues/9\")\n+        .unwrap()\n+        .normalized_storage()\n+        .to_storage_string();\n+    let right = ItemId::parse(\"https://github.com/ghvotehi/a/issues/10\")\n+        .unwrap()\n+        .normalized_storage()\n+        .to_storage_string();\n+    let q = format!(\n+        \"/vote/compare?left={}&right={}\",\n+        urlencoding::encode(&left),\n+        urlencoding::encode(&right)\n+    );\n+    let resp = client\n+        .get(format!(\"http://{addr}{q}\"))\n+        .send()\n+        .await\n+        .unwrap();\n+    assert!(resp.status().is_success(), \"{}\", resp.status());\n+    let body = resp.text().await.unwrap();\n+    let n_cards = body.matches(\"github-import-card\").count();\n+    assert!(\n+        n_cards >= 2,\n+        \"expected two GitHub import cards on vote compare, count={n_cards}, snippet={}\",\n+        body.chars().take(1500).collect::()\n+    );\n+    assert!(body.contains(\"vote-compare-left\"));\n+    assert!(body.contains(\"vote-compare-right\"));\n+    assert!(body.contains(\"#9 Left corner\"));\n+    assert!(body.contains(\"#10 Right corner\"));\n+}\n+\n #[tokio::test]\n async fn test_search_handles_multibyte_unicode() {\n     // HTML search pages are offline during the auth-v3 refactor.\n","role":"user"}],"model":"~anthropic/claude-sonnet-latest"}