You are a constitutional council ranking individual git commits for ownership allocation. Compare these two commits. Decide which contributed more lasting value to the project. Judge substance, not spectacle: - Prefer correct, lasting design and real bugfixes over churn, formatting, renames, or generated noise. - Prefer clarity and necessity over sheer line count. A small precise change can beat a large diffuse one. - Do not favor a side merely because its patch is longer or noisier. - Weight what the change does for the project, not the contributor's name. Return ONLY a JSON object: {"winner": "A" or "B", "ratio": "N:M", "explanation": "..."} The explanation must cite concrete differences in the patches (1-3 sentences). Side A — contributor: tommy-mor Side A — commit message: [52f5c51c] Add Reddit OAuth linking and make UUID the only account identity. OAuth providers only attach to a session UUID (first link creates the principal); linked providers stay private on the account page. Co-authored-by: Cursor Side A — unified diff (full patch): diff --git a/AGENTS.md b/AGENTS.md index 6e0fd8ebb65d665c9c1438e3275971d62b98fd95..e9cc3173dbeb21ad0fc090ca7b407b027c7820a9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -35,8 +35,11 @@ Environment variables (defaults in `server/src/state.rs`): - `SORTER2_DATA_DIR` — default `./data` (created on startup) - `SORTER2_EVENT_LOG` — default `{data_dir}/events.jsonl` - `SORTER2_BASE_URL` — public origin (also drives Secure cookies when `https://`) -- `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET` — GitHub OAuth (optional; login disabled if unset) -- `SORTER2_ALLOW_MOCK_OAUTH=1` — allow `mock_user` on `/auth/github` (tests only) +- `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET` — GitHub OAuth linking (optional) +- `REDDIT_CLIENT_ID` / `REDDIT_CLIENT_SECRET` (or `REDDIT_APP_*`) — Reddit API import + OAuth linking (optional) +- `SORTER2_ALLOW_MOCK_OAUTH=1` — allow `mock_user` on `/auth/github` and `/auth/reddit` (tests only) + +Identity: UUID is canonical. OAuth providers only *link* to a UUID (first link creates the principal). Linked providers are private to the account owner. Health check: `GET /healthz` → `ok`. diff --git a/server/src/auth/mod.rs b/server/src/auth/mod.rs index 5906f93b13853421e96a3c37bc9d8202a47842bf..c706ae8045a811e5941f5f6c72da88f42a403a82 100644 --- a/server/src/auth/mod.rs +++ b/server/src/auth/mod.rs @@ -1,4 +1,8 @@ -//! GitHub OAuth login, session cookies, and vote actor resolution. +//! OAuth linking, session cookies, and vote actor resolution. +//! +//! Canonical identity is a UUID. OAuth providers only *link* to that UUID +//! (first link creates the principal; later links attach while logged in). +//! Which providers are linked is private to the account owner. pub mod config; pub mod identity; @@ -22,7 +26,9 @@ use crate::{ form_template::template_json_compact, html::layout, state::AppState, - storage_schema::{oauth_link_owner, pseudonym_owner, Store, StoreFields}, + storage_schema::{ + linked_providers_for_uuid, oauth_link_owner, pseudonym_owner, Store, StoreFields, + }, ui_action::UI_RPC_FIELD, }; @@ -53,10 +59,12 @@ fn new_actor_uuid() -> String { pub struct LoginQuery { #[serde(default)] pub return_to: Option, + #[serde(default)] + pub error: Option, } #[derive(Debug, Deserialize)] -pub struct GitHubStartQuery { +pub struct OAuthStartQuery { #[serde(default)] pub return_to: Option, #[serde(default)] @@ -72,15 +80,22 @@ fn return_from_query_or_jar(jar: &CookieJar, query: Option<&str>) -> String { .unwrap_or_else(|| "/".to_string()) } -fn oauth_providers(base_url: &str, return_to: &str) -> Vec<(&'static str, String)> { +/// Available OAuth link targets: `(provider_key, label, start_href)`. +fn oauth_providers(base_url: &str, return_to: &str) -> Vec<(&'static str, &'static str, String)> { let mut out = Vec::new(); + let enc = urlencoding::encode(return_to); if oauth::GitHubConfig::from_env(base_url).is_some() { out.push(( - "GitHub", - format!( - "/auth/github?return_to={}", - urlencoding::encode(return_to) - ), + "github", + oauth::provider_label("github"), + format!("/auth/github?return_to={enc}"), + )); + } + if oauth::RedditConfig::from_env(base_url).is_some() { + out.push(( + "reddit", + oauth::provider_label("reddit"), + format!("/auth/reddit?return_to={enc}"), )); } out @@ -125,23 +140,41 @@ fn alias_claim_forms(return_to: &str, submit_label: &str) -> Result Markup { +fn login_error_message(code: Option<&str>) -> Option<&'static str> { + match code { + Some("oauth_taken") => { + Some("that OAuth account is already linked to a different sorter2 account") + } + Some("oauth_failed") => Some("OAuth failed — try again"), + _ => None, + } +} + +fn signed_out_body( + providers: &[(&str, &str, String)], + error: Option<&str>, +) -> Markup { html! { main class="panel login-page" { section class="login-section" { h1 { "sign in" } - p class="muted" { "link an account to vote under a lasting alias" } + p class="muted" { + "link an OAuth account to create your identity, then claim an alias to vote" + } + @if let Some(msg) = login_error_message(error) { + p class="alias-bad" data-testid="login-error" { (msg) } + } @if providers.is_empty() { p class="muted" { - "OAuth is not configured. Set GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET." + "OAuth is not configured. Set GitHub and/or Reddit client credentials." } } @else { ul class="oauth-provider-list" { - @for (name, href) in providers { + @for (key, label, href) in providers { li { a href=(href) class="btn-primary oauth-provider" - data-testid=(format!("oauth-{}", name.to_lowercase())) { - (format!("Continue with {name}")) + data-testid=(format!("oauth-{key}")) { + (format!("Link {label}")) } } } @@ -156,7 +189,10 @@ fn signed_out_body(providers: &[(&str, String)]) -> Markup { fn account_body( actor: &session::SessionActor, aliases: &[String], - providers: &[(&str, String)], + // Provider keys already linked to this UUID (private). + linked: &[String], + // Providers available to link: not yet attached. + unlinkable: &[(&str, &str, String)], claim_forms: Markup, ) -> Markup { let current = actor.pseudonym.trim(); @@ -212,16 +248,29 @@ fn account_body( (claim_forms) } - @if !providers.is_empty() { - section class="login-section" { - h2 { "linked sign-in" } - p class="muted small" { "sign in again with the same provider to return to this account" } + section class="login-section" { + h2 { "linked sign-in" } + p class="muted small" { + "private to you — linking more providers raises trust weight without publishing which accounts you use" + } + @if linked.is_empty() { + p class="muted" data-testid="linked-providers-empty" { "none yet" } + } @else { + ul class="linked-provider-list" data-testid="linked-providers" { + @for key in linked { + li data-testid=(format!("linked-{key}")) { + (oauth::provider_label(key)) + } + } + } + } + @if !unlinkable.is_empty() { ul class="oauth-provider-list" { - @for (name, href) in providers { + @for (key, label, href) in unlinkable { li { a href=(href) class="btn-secondary oauth-provider" - data-testid=(format!("oauth-relink-{}", name.to_lowercase())) { - (format!("Re-link {name}")) + data-testid=(format!("oauth-link-{key}")) { + (format!("Link {label}")) } } } @@ -243,12 +292,21 @@ fn account_body( fn login_body( session: Option<&session::SessionActor>, aliases: &[String], - providers: &[(&str, String)], + linked: &[String], + providers: &[(&str, &str, String)], claim_forms: Option, + error: Option<&str>, ) -> Markup { match (session, claim_forms) { - (Some(actor), Some(forms)) => account_body(actor, aliases, providers, forms), - _ => signed_out_body(providers), + (Some(actor), Some(forms)) => { + let unlinkable: Vec<_> = providers + .iter() + .filter(|(key, _, _)| !linked.iter().any(|p| p == key)) + .cloned() + .collect(); + account_body(actor, aliases, linked, &unlinkable, forms) + } + _ => signed_out_body(providers, error), } } @@ -268,6 +326,10 @@ pub async fn login_page( .as_ref() .map(|s| alias_list(db, &s.uuid)) .unwrap_or_default(); + let linked = session + .as_ref() + .map(|s| linked_providers_for_uuid(db, &s.uuid).unwrap_or_default()) + .unwrap_or_default(); let providers = oauth_providers(&base_url_from_env(state.cfg.port), &return_to); let claim_forms = if session.is_some() { @@ -282,7 +344,14 @@ pub async fn login_page( } else { "login · sorter2" }, - login_body(session.as_ref(), &aliases, &providers, claim_forms), + login_body( + session.as_ref(), + &aliases, + &linked, + &providers, + claim_forms, + query.error.as_deref(), + ), state.views.get_views("/login"), session .as_ref() @@ -302,7 +371,6 @@ pub async fn alias_page( let db = state.projection_store.db(); let session = session::load_valid_session(db, &session_id).ok_or(StatusCode::UNAUTHORIZED)?; if session::session_has_pseudonym(&session) { - // Already onboarded — manage aliases on the account page. return Ok(Redirect::to("/login").into_response()); } @@ -331,7 +399,7 @@ pub async fn alias_page( pub async fn github_start( State(state): State, jar: CookieJar, - Query(query): Query, + Query(query): Query, ) -> Result { let cfg = oauth::GitHubConfig::from_env(&base_url_from_env(state.cfg.port)) .ok_or(StatusCode::SERVICE_UNAVAILABLE)?; @@ -342,7 +410,28 @@ pub async fn github_start( } else { None }; - let url = oauth::authorize_url(&cfg, &state_token, mock_user); + let url = oauth::github_authorize_url(&cfg, &state_token, mock_user); + let jar = jar + .add(session::oauth_state_cookie_value(&state_token)) + .add(session::auth_return_cookie_value(&return_to)); + Ok((jar, Redirect::temporary(&url)).into_response()) +} + +pub async fn reddit_start( + State(state): State, + jar: CookieJar, + Query(query): Query, +) -> Result { + let cfg = oauth::RedditConfig::from_env(&base_url_from_env(state.cfg.port)) + .ok_or(StatusCode::SERVICE_UNAVAILABLE)?; + let return_to = return_from_query_or_jar(&jar, query.return_to.as_deref()); + let state_token = session::new_oauth_state(); + let mock_user = if config::mock_oauth_allowed() { + query.mock_user.as_deref() + } else { + None + }; + let url = oauth::reddit_authorize_url(&cfg, &state_token, mock_user); let jar = jar .add(session::oauth_state_cookie_value(&state_token)) .add(session::auth_return_cookie_value(&return_to)); @@ -355,6 +444,13 @@ pub struct OAuthCallbackQuery { pub state: String, } +/// Link `provider:provider_id` to a UUID. +/// +/// - Logged in + new provider → attach to session UUID +/// - Logged in + already ours → no-op +/// - Logged in + owned by someone else → conflict +/// - Logged out + known link → resume that UUID +/// - Logged out + unknown → create principal + first link async fn finish_oauth_login( state: &AppState, jar: CookieJar, @@ -364,11 +460,41 @@ async fn finish_oauth_login( let db = state.projection_store.db(); let return_to = return_from_query_or_jar(&jar, None); - let uuid = match oauth_link_owner(db, provider, &provider_id) - .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? - { - Some(existing) => existing, - None => { + let existing_owner = oauth_link_owner(db, provider, &provider_id) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + let session_uuid = session::session_id_from_jar(&jar) + .as_deref() + .and_then(|id| session::load_valid_session(db, id)) + .map(|s| s.uuid); + let linking_while_logged_in = session_uuid.is_some(); + + let uuid = match (session_uuid, existing_owner) { + (Some(session_uuid), Some(owner)) if owner == session_uuid => session_uuid, + (Some(_), Some(_)) => { + return Ok(( + jar.add(session::clear_oauth_state_cookie()), + "/login?error=oauth_taken".into(), + )); + } + (Some(session_uuid), None) => { + let ts = now_ms(); + state + .append_identity_events(vec![Event::OauthLinked { + uuid: session_uuid.clone(), + provider: provider.to_string(), + provider_id, + ts, + }]) + .await + .map_err(|e| { + tracing::warn!(err = %e, "oauth link append failed"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + session_uuid + } + (None, Some(owner)) => owner, + (None, None) => { let uuid = new_actor_uuid(); let ts = now_ms(); state @@ -409,6 +535,9 @@ async fn finish_oauth_login( "/login/alias?return_to={}", urlencoding::encode(&return_to) ) + } else if linking_while_logged_in { + // Additional link while already in an account → stay on account page. + "/login".to_string() } else { return_to }; @@ -434,22 +563,57 @@ pub async fn github_callback( .build() .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - let token = oauth::exchange_code(&client, &cfg, &query.code) + let token = oauth::github_exchange_code(&client, &cfg, &query.code) .await .map_err(|e| { tracing::warn!(err = %e, "github oauth token exchange failed"); StatusCode::BAD_GATEWAY })?; - let user = oauth::fetch_user(&client, &cfg.api_base, &token) + let user = oauth::github_fetch_user(&client, &cfg.api_base, &token) .await .map_err(|e| { tracing::warn!(err = %e, "github user fetch failed"); StatusCode::BAD_GATEWAY })?; - let provider = "github"; - let provider_id = oauth::provider_id(&user); - let (jar, dest) = finish_oauth_login(&state, jar, provider, provider_id).await?; + let (jar, dest) = + finish_oauth_login(&state, jar, "github", oauth::github_provider_id(&user)).await?; + Ok((jar, Redirect::to(&dest)).into_response()) +} + +pub async fn reddit_callback( + State(state): State, + jar: CookieJar, + Query(query): Query, +) -> Result { + let cfg = oauth::RedditConfig::from_env(&base_url_from_env(state.cfg.port)) + .ok_or(StatusCode::SERVICE_UNAVAILABLE)?; + + let expected_state = session::oauth_state_from_jar(&jar).ok_or(StatusCode::BAD_REQUEST)?; + if expected_state != query.state { + return Err(StatusCode::BAD_REQUEST); + } + + let client = Client::builder() + .timeout(std::time::Duration::from_secs(15)) + .build() + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + let token = oauth::reddit_exchange_code(&client, &cfg, &query.code) + .await + .map_err(|e| { + tracing::warn!(err = %e, "reddit oauth token exchange failed"); + StatusCode::BAD_GATEWAY + })?; + let user = oauth::reddit_fetch_user(&client, &cfg, &token) + .await + .map_err(|e| { + tracing::warn!(err = %e, "reddit user fetch failed"); + StatusCode::BAD_GATEWAY + })?; + + let (jar, dest) = + finish_oauth_login(&state, jar, "reddit", oauth::reddit_provider_id(&user)).await?; Ok((jar, Redirect::to(&dest)).into_response()) } diff --git a/server/src/auth/oauth.rs b/server/src/auth/oauth.rs index b80078fee0c5acd905b9125d29454e46c4e0d066..369b1527d9032cf312a07819279e0f988ef4a36e 100644 --- a/server/src/auth/oauth.rs +++ b/server/src/auth/oauth.rs @@ -1,8 +1,15 @@ -//! GitHub OAuth (raw reqwest, same style as reddit.rs). +//! OAuth providers (GitHub + Reddit). Provider accounts only *link* to a UUID; +//! the UUID is the canonical identity. Which providers are linked is private. use reqwest::Client; use serde::Deserialize; +use crate::reddit::{ + default_user_agent, reddit_oauth_api_base, reddit_oauth_token_base, +}; + +// ── GitHub ────────────────────────────────────────────────────────────────── + #[derive(Debug, Clone)] pub struct GitHubConfig { pub client_id: String, @@ -40,7 +47,7 @@ impl GitHubConfig { } #[derive(Debug, Deserialize)] -struct TokenResponse { +struct GitHubTokenResponse { access_token: String, } @@ -50,7 +57,7 @@ pub struct GitHubUser { pub login: String, } -pub fn authorize_url(cfg: &GitHubConfig, state: &str, mock_user: Option<&str>) -> String { +pub fn github_authorize_url(cfg: &GitHubConfig, state: &str, mock_user: Option<&str>) -> String { let mut url = format!( "{}/login/oauth/authorize?client_id={}&redirect_uri={}&scope=read:user&state={}", cfg.oauth_base.trim_end_matches('/'), @@ -65,7 +72,7 @@ pub fn authorize_url(cfg: &GitHubConfig, state: &str, mock_user: Option<&str>) - url } -pub async fn exchange_code( +pub async fn github_exchange_code( client: &Client, cfg: &GitHubConfig, code: &str, @@ -90,14 +97,14 @@ pub async fn exchange_code( return Err(format!("github token HTTP {}", resp.status())); } - let body: TokenResponse = resp + let body: GitHubTokenResponse = resp .json() .await .map_err(|e| format!("github token parse failed: {e}"))?; Ok(body.access_token) } -pub async fn fetch_user( +pub async fn github_fetch_user( client: &Client, api_base: &str, access_token: &str, @@ -120,10 +127,149 @@ pub async fn fetch_user( .map_err(|e| format!("github user parse failed: {e}")) } -pub fn provider_id(user: &GitHubUser) -> String { +pub fn github_provider_id(user: &GitHubUser) -> String { user.id.to_string() } +// ── Reddit ────────────────────────────────────────────────────────────────── + +#[derive(Debug, Clone)] +pub struct RedditConfig { + pub client_id: String, + pub client_secret: String, + pub redirect_uri: String, + /// Host for `/api/v1/authorize` (www.reddit.com in production). + pub authorize_base: String, + /// Host for `POST /api/v1/access_token`. + pub token_base: String, + /// Host for bearer `GET /api/v1/me` (oauth.reddit.com). + pub api_base: String, + pub user_agent: String, +} + +/// Authorize page base; defaults to the same host as token POSTs. +pub fn reddit_authorize_base() -> String { + std::env::var("REDDIT_OAUTH_AUTHORIZE_BASE") + .or_else(|_| std::env::var("REDDIT_OAUTH_BASE")) + .unwrap_or_else(|_| "https://www.reddit.com".into()) +} + +impl RedditConfig { + pub fn from_env(base_url: &str) -> Option { + let client_id = std::env::var("REDDIT_CLIENT_ID") + .or_else(|_| std::env::var("REDDIT_APP_ID")) + .ok()?; + let client_secret = std::env::var("REDDIT_CLIENT_SECRET") + .or_else(|_| std::env::var("REDDIT_APP_SECRET")) + .ok()?; + if client_id.is_empty() || client_secret.is_empty() { + return None; + } + let base = base_url.trim_end_matches('/'); + Some(Self { + client_id, + client_secret, + redirect_uri: format!("{base}/auth/reddit/callback"), + authorize_base: reddit_authorize_base(), + token_base: reddit_oauth_token_base(), + api_base: reddit_oauth_api_base(), + user_agent: default_user_agent(), + }) + } +} + +#[derive(Debug, Deserialize)] +struct RedditTokenResponse { + access_token: String, +} + +#[derive(Debug, Deserialize)] +pub struct RedditUser { + /// Stable id (`t2_…`); never use `name` as identity. + pub id: String, + pub name: String, +} + +pub fn reddit_authorize_url(cfg: &RedditConfig, state: &str, mock_user: Option<&str>) -> String { + let mut url = format!( + "{}/api/v1/authorize?client_id={}&response_type=code&state={}&redirect_uri={}&duration=temporary&scope=identity", + cfg.authorize_base.trim_end_matches('/'), + urlencoding::encode(&cfg.client_id), + urlencoding::encode(state), + urlencoding::encode(&cfg.redirect_uri), + ); + if let Some(user) = mock_user { + url.push_str("&mock_user="); + url.push_str(&urlencoding::encode(user)); + } + url +} + +pub async fn reddit_exchange_code( + client: &Client, + cfg: &RedditConfig, + code: &str, +) -> Result { + let resp = client + .post(format!( + "{}/api/v1/access_token", + cfg.token_base.trim_end_matches('/') + )) + .header("User-Agent", &cfg.user_agent) + .basic_auth(&cfg.client_id, Some(&cfg.client_secret)) + .form(&[ + ("grant_type", "authorization_code"), + ("code", code), + ("redirect_uri", cfg.redirect_uri.as_str()), + ]) + .send() + .await + .map_err(|e| format!("reddit token request failed: {e}"))?; + + if !resp.status().is_success() { + let status = resp.status(); + let body = resp.text().await.unwrap_or_default(); + return Err(format!("reddit token HTTP {status}: {body}")); + } + + let body: RedditTokenResponse = resp + .json() + .await + .map_err(|e| format!("reddit token parse failed: {e}"))?; + Ok(body.access_token) +} + +pub async fn reddit_fetch_user( + client: &Client, + cfg: &RedditConfig, + access_token: &str, +) -> Result { + let resp = client + .get(format!( + "{}/api/v1/me", + cfg.api_base.trim_end_matches('/') + )) + .header("User-Agent", &cfg.user_agent) + .bearer_auth(access_token) + .send() + .await + .map_err(|e| format!("reddit user request failed: {e}"))?; + + if !resp.status().is_success() { + return Err(format!("reddit user HTTP {}", resp.status())); + } + + resp.json() + .await + .map_err(|e| format!("reddit user parse failed: {e}")) +} + +pub fn reddit_provider_id(user: &RedditUser) -> String { + user.id.clone() +} + +// ── Shared helpers ────────────────────────────────────────────────────────── + pub fn validate_pseudonym(raw: &str) -> Result { let trimmed = raw.trim(); if trimmed.is_empty() { @@ -144,3 +290,12 @@ pub fn validate_pseudonym(raw: &str) -> Result { pub fn sanitize_pseudonym(login: &str) -> String { validate_pseudonym(login).unwrap_or_else(|_| "user".to_string()) } + +/// Display name for a provider key (`github` → `GitHub`). Never show provider ids. +pub fn provider_label(provider: &str) -> &'static str { + match provider { + "github" => "GitHub", + "reddit" => "Reddit", + _ => "OAuth", + } +} diff --git a/server/src/lib.rs b/server/src/lib.rs index 84f2565b105fb302241b949af64bd5e49916eab2..0d948af1457504fdbd34d0b14261f65ac58da0ec 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -47,6 +47,8 @@ pub fn create_app(state: AppState) -> Router { .route("/login/alias", get(crate::auth::alias_page)) .route("/auth/github", get(crate::auth::github_start)) .route("/auth/github/callback", get(crate::auth::github_callback)) + .route("/auth/reddit", get(crate::auth::reddit_start)) + .route("/auth/reddit/callback", get(crate::auth::reddit_callback)) .route("/auth/logout", post(crate::auth::logout)) .route("/auth/switch", post(crate::auth::switch_pseudonym)) .route("/ui", post(crate::api::ui_html::post_ui_html)) diff --git a/server/src/projection_apply.rs b/server/src/projection_apply.rs index 4fb4b48ee0a53b7f673fae0c9731eed5acc33332..f50458c2ff3c447a3cfd28adb298e6883a2da4e9 100644 --- a/server/src/projection_apply.rs +++ b/server/src/projection_apply.rs @@ -4,6 +4,8 @@ //! child links, recent-vote appends) plus a cursor advance, all committed in //! one atomic `DisableWal` batch. +use std::collections::HashMap; + use crate::{ event_log::EventLogError, events::{Event, EventRecord}, @@ -44,6 +46,8 @@ pub fn apply_records( let db = projection_store.db(); let mut batch = db.batch(); let mut last_seq = 0u64; + // Weight reads must see earlier writes in this same batch. + let mut pending_weights: HashMap = HashMap::new(); for record in records { match &record.event { @@ -85,6 +89,7 @@ pub fn apply_records( ensure_path_writes(&mut batch, &parsed); } Event::PrincipalCreated { uuid, .. } => { + pending_weights.insert(uuid.clone(), BASE_TRUST_WEIGHT); batch.write( Store::root() .user_weights() @@ -112,17 +117,25 @@ pub fn apply_records( } } else { batch.write(Store::root().oauth_links().key(&link_key).set(uuid)); - let current = Store::root() - .user_weights() - .key(&uuid.clone()) - .get(db) - .map_err(|e| EventLogError::Apply(e.to_string()))? + let current = pending_weights + .get(uuid) + .copied() + .or_else(|| { + Store::root() + .user_weights() + .key(&uuid.clone()) + .get(db) + .ok() + .flatten() + }) .unwrap_or(BASE_TRUST_WEIGHT); + let next = trust_weight_after_link(current); + pending_weights.insert(uuid.clone(), next); batch.write( Store::root() .user_weights() .key(&uuid.clone()) - .set(&trust_weight_after_link(current)), + .set(&next), ); } } @@ -205,6 +218,15 @@ mod tests { ), record( 3, + Event::OauthLinked { + uuid: uuid.into(), + provider: "reddit".into(), + provider_id: "t2_abc".into(), + ts, + }, + ), + record( + 4, Event::PseudonymClaimed { uuid: uuid.into(), pseudonym: "octocat".into(), @@ -219,8 +241,12 @@ mod tests { oauth_link_owner(store.db(), "github", "42").unwrap(), Some(uuid.to_string()) ); + assert_eq!( + crate::storage_schema::linked_providers_for_uuid(store.db(), uuid).unwrap(), + vec!["github".to_string(), "reddit".to_string()] + ); assert_eq!(resolve_actor_uuid(store.db(), "octocat").unwrap(), uuid); - assert_eq!(user_trust_weight(store.db(), uuid).unwrap(), 1.5); + assert_eq!(user_trust_weight(store.db(), uuid).unwrap(), 2.0); let aliases = Store::root() .user_pseudonyms() .key(&uuid.to_string()) diff --git a/server/src/storage_schema.rs b/server/src/storage_schema.rs index b942810afd96d3bf01b7765718303a39be4ef8d2..dac6f8e6080e3f5683c24dbb8861f5a981d456c4 100644 --- a/server/src/storage_schema.rs +++ b/server/src/storage_schema.rs @@ -103,6 +103,25 @@ pub fn oauth_link_owner(db: &Db, provider: &str, provider_id: &str) -> durable:: .get(db) } +/// Provider names linked to a UUID (`github`, `reddit`, …). Private — for the +/// account owner's page only; never expose which providers are linked publicly. +pub fn linked_providers_for_uuid(db: &Db, uuid: &str) -> durable::Result> { + let mut providers = Vec::new(); + for (key, owner) in Store::root().oauth_links().iter(db)? { + if owner != uuid { + continue; + } + let Some((provider, _)) = key.split_once(':') else { + continue; + }; + if !providers.iter().any(|p| p == provider) { + providers.push(provider.to_string()); + } + } + providers.sort(); + Ok(providers) +} + pub const RECENT_VOTES_CAP: u64 = 200; fn id_key(id: &ItemId) -> String { diff --git a/test/support/harness.clj b/test/support/harness.clj index 4505ece5aa193e826ca61c52f1467d252080d66b..741024aab1d14269e225791189633287980ae2e4 100644 --- a/test/support/harness.clj +++ b/test/support/harness.clj @@ -48,12 +48,15 @@ "GITHUB_CLIENT_SECRET" "test-secret" "GITHUB_OAUTH_BASE" (str "http://127.0.0.1:" oauth-port) "GITHUB_API_BASE" (str "http://127.0.0.1:" oauth-port) + ;; Reddit import fixtures + Reddit OAuth on reddit-port. "REDDIT_API_BASE" (str "http://127.0.0.1:" reddit-port) + "REDDIT_CLIENT_ID" "test-reddit" + "REDDIT_CLIENT_SECRET" "test-reddit-secret" "REDDIT_OAUTH_BASE" (str "http://127.0.0.1:" reddit-port) - "REDDIT_CLIENT_ID" "" - "REDDIT_CLIENT_SECRET" "" - "REDDIT_APP_ID" "" - "REDDIT_APP_SECRET" ""})) + "REDDIT_OAUTH_AUTHORIZE_BASE" (str "http://127.0.0.1:" reddit-port) + "REDDIT_OAUTH_TOKEN_BASE" (str "http://127.0.0.1:" reddit-port) + "REDDIT_OAUTH_API_BASE" (str "http://127.0.0.1:" reddit-port) + "REDDIT_USER_AGENT" "web:sorter2-test:v0 (by /u/test)"})) (defn with-auth-servers "Start mock Reddit + mock OAuth + release sorter2-server. diff --git a/test/support/mock_oauth.clj b/test/support/mock_oauth.clj index 909d7a7be8b159ea54a122d69c46af3db3318118..5ba7e9be3cf6d2226648e9609a09ed45f306930f 100644 --- a/test/support/mock_oauth.clj +++ b/test/support/mock_oauth.clj @@ -1,5 +1,5 @@ (ns test.support.mock-oauth - "In-process HTTP stub for GitHub OAuth (authorize, token, /user)." + "In-process HTTP stub for GitHub + Reddit OAuth (authorize, token, user)." (:require [clojure.string :as str]) (:import [com.sun.net.httpserver HttpServer HttpHandler HttpExchange] [java.net InetSocketAddress URLDecoder])) @@ -12,11 +12,14 @@ (URLDecoder/decode (or v "") "UTF-8")))) (str/split query #"&")))) -(defn- parse-mock-user [raw] +(defn- parse-mock-user + "GitHub-style `id:login` (numeric id). Reddit-style `t2_xxx:name`." + [raw] (let [s (or raw "1002:newbie") [id login] (str/split s #":" 2)] - {:id (Long/parseLong id) - :login (or login "newbie")})) + {:id id + :login (or login "newbie") + :numeric? (re-matches #"\d+" id)})) (defn- send-json [^HttpExchange ex status body] (let [bytes (.getBytes body "UTF-8")] @@ -31,9 +34,10 @@ (.sendResponseHeaders ex 302 -1) (.close (.getResponseBody ex))) -(defn- read-form-code [^HttpExchange ex] +(defn- read-form [^HttpExchange ex] (let [body (slurp (.getInputStream ex))] - (query-param body "code"))) + {:code (query-param body "code") + :grant (query-param body "grant_type")})) (defn- bearer-token [^HttpExchange ex] (some-> (.getRequestHeaders ex) @@ -44,8 +48,18 @@ (when (str/starts-with? token "mock:") (parse-mock-user (subs token 5)))) +(defn- authorize-redirect [exchange query] + (let [redirect-uri (query-param query "redirect_uri") + state (query-param query "state") + mock-user (query-param query "mock_user") + user (parse-mock-user mock-user) + code (str "mock:" (:id user) ":" (:login user)) + loc (str redirect-uri "?code=" (java.net.URLEncoder/encode code "UTF-8") + "&state=" (java.net.URLEncoder/encode state "UTF-8"))] + (send-redirect exchange loc))) + (defn start-mock-oauth - "Start mock GitHub OAuth on `port`. Returns a zero-arg `stop` function." + "Start mock GitHub + Reddit OAuth on `port`. Returns a zero-arg `stop` function." [port] (let [server (HttpServer/create (InetSocketAddress. "127.0.0.1" port) 0) handler @@ -53,28 +67,45 @@ (handle [^HttpExchange exchange] (let [uri (.getRequestURI exchange) path (.getPath uri) - query (.getQuery uri)] + query (.getQuery uri) + method (.getRequestMethod exchange)] (cond + ;; GitHub authorize (str/ends-with? path "/login/oauth/authorize") - (let [redirect-uri (query-param query "redirect_uri") - state (query-param query "state") - mock-user (query-param query "mock_user") - user (parse-mock-user mock-user) - code (str "mock:" (:id user) ":" (:login user)) - loc (str redirect-uri "?code=" (java.net.URLEncoder/encode code "UTF-8") - "&state=" (java.net.URLEncoder/encode state "UTF-8"))] - (send-redirect exchange loc)) + (authorize-redirect exchange query) + + ;; Reddit authorize + (str/ends-with? path "/api/v1/authorize") + (authorize-redirect exchange query) - (str/ends-with? path "/login/oauth/access_token") - (let [code (or (read-form-code exchange) "mock:1002:newbie")] + ;; GitHub token + (and (= method "POST") (str/ends-with? path "/login/oauth/access_token")) + (let [code (or (:code (read-form exchange)) "mock:1002:newbie")] (send-json exchange 200 (str "{\"access_token\":\"" code "\",\"token_type\":\"bearer\"}"))) + ;; Reddit token (client_credentials for import + authorization_code for login) + (and (= method "POST") (str/ends-with? path "/api/v1/access_token")) + (let [form (read-form exchange) + grant (or (:grant form) "") + code (or (:code form) "mock:t2_test:redditor")] + (if (= grant "client_credentials") + (send-json exchange 200 "{\"access_token\":\"app-token\",\"token_type\":\"bearer\",\"expires_in\":3600}") + (send-json exchange 200 (str "{\"access_token\":\"" code "\",\"token_type\":\"bearer\",\"expires_in\":3600}")))) + + ;; GitHub user (= path "/user") (let [token (bearer-token exchange) - user (or (parse-token-user token) {:id 1002 :login "newbie"})] + user (or (parse-token-user token) {:id "1002" :login "newbie" :numeric? true})] (send-json exchange 200 (str "{\"id\":" (:id user) ",\"login\":\"" (:login user) "\"}"))) + ;; Reddit /api/v1/me + (str/ends-with? path "/api/v1/me") + (let [token (bearer-token exchange) + user (or (parse-token-user token) {:id "t2_test" :login "redditor"})] + (send-json exchange 200 + (str "{\"id\":\"" (:id user) "\",\"name\":\"" (:login user) "\"}"))) + :else (send-json exchange 404 "{\"error\":\"not found\"}")))))] (.createContext server "/" handler) diff --git a/test/support/mock_reddit.clj b/test/support/mock_reddit.clj index 5efa92db3e1f79b8f423a2f1adcbda959123c1ad..a630cf0938722193e9af88382d60e777ff371be4 100644 --- a/test/support/mock_reddit.clj +++ b/test/support/mock_reddit.clj @@ -1,14 +1,56 @@ (ns test.support.mock-reddit - "In-process HTTP stub for Reddit API fixtures (`test/fixtures/reddit/`)." + "In-process HTTP stub for Reddit API fixtures + OAuth login endpoints." (:require [clojure.java.io :as io] [clojure.string :as str]) (:import [com.sun.net.httpserver HttpServer HttpHandler HttpExchange] - [java.net InetSocketAddress])) + [java.net InetSocketAddress URLDecoder])) (defn fixtures-dir ([] (fixtures-dir (System/getProperty "user.dir"))) ([root] (str root "/test/fixtures/reddit"))) +(defn- query-param [query key] + (when query + (some (fn [pair] + (let [[k v] (str/split pair "=" 2)] + (when (= k key) + (URLDecoder/decode (or v "") "UTF-8")))) + (str/split query #"&")))) + +(defn- parse-mock-user [raw] + (let [s (or raw "t2_test:redditor") + [id login] (str/split s #":" 2)] + {:id id :login (or login "redditor")})) + +(defn- send-bytes [^HttpExchange ex status ^bytes body content-type] + (.set (.getResponseHeaders ex) "Content-Type" content-type) + (.sendResponseHeaders ex status (alength body)) + (doto (.getResponseBody ex) + (.write body) + (.close))) + +(defn- send-json [^HttpExchange ex status body] + (send-bytes ex status (.getBytes body "UTF-8") "application/json")) + +(defn- send-redirect [^HttpExchange ex location] + (.set (.getResponseHeaders ex) "Location" location) + (.sendResponseHeaders ex 302 -1) + (.close (.getResponseBody ex))) + +(defn- read-form [^HttpExchange ex] + (let [body (slurp (.getInputStream ex))] + {:code (query-param body "code") + :grant (query-param body "grant_type")})) + +(defn- bearer-token [^HttpExchange ex] + (some-> (.getRequestHeaders ex) + (.getFirst "Authorization") + (str/replace #"^[Bb]earer " ""))) + +(defn- parse-token-user [token] + (when (str/starts-with? token "mock:") + (parse-mock-user (subs token 5)))) + (defn start-mock-reddit "Start a mock Reddit API on `port`. Returns a zero-arg `stop` function." ([port] (start-mock-reddit port (fixtures-dir))) @@ -19,15 +61,38 @@ handler (proxy [HttpHandler] [] (handle [^HttpExchange exchange] - ;; `/r//about.json` → subreddit entity; `/r/.json` → listing. - (let [path (.getPath (.getRequestURI exchange)) - body (if (str/includes? path "/about") - about - listing)] - (.sendResponseHeaders exchange 200 (alength body)) - (let [out (.getResponseBody exchange)] - (.write out body) - (.close out)))))] + (let [uri (.getRequestURI exchange) + path (.getPath uri) + query (.getQuery uri) + method (.getRequestMethod exchange)] + (cond + (str/ends-with? path "/api/v1/authorize") + (let [redirect-uri (query-param query "redirect_uri") + state (query-param query "state") + user (parse-mock-user (query-param query "mock_user")) + code (str "mock:" (:id user) ":" (:login user)) + loc (str redirect-uri "?code=" (java.net.URLEncoder/encode code "UTF-8") + "&state=" (java.net.URLEncoder/encode state "UTF-8"))] + (send-redirect exchange loc)) + + (and (= method "POST") (str/ends-with? path "/api/v1/access_token")) + (let [form (read-form exchange) + grant (or (:grant form) "") + code (or (:code form) "mock:t2_test:redditor")] + (if (= grant "client_credentials") + (send-json exchange 200 "{\"access_token\":\"app-token\",\"token_type\":\"bearer\",\"expires_in\":3600}") + (send-json exchange 200 (str "{\"access_token\":\"" code "\",\"token_type\":\"bearer\",\"expires_in\":3600}")))) + + (str/ends-with? path "/api/v1/me") + (let [user (or (parse-token-user (bearer-token exchange)) + {:id "t2_test" :login "redditor"})] + (send-json exchange 200 + (str "{\"id\":\"" (:id user) "\",\"name\":\"" (:login user) "\"}"))) + + ;; `/r//about.json` → subreddit entity; `/r/.json` → listing. + :else + (let [body (if (str/includes? path "/about") about listing)] + (send-bytes exchange 200 body "application/json"))))))] (.createContext server "/" handler) (.setExecutor server nil) (.start server) Side B — contributor: tommy-mor Side B — commit message: [23c8134e] Fix /-/ external garden index; resolvers/ + GitHub import cards (#150) * Fix external garden root listing; add resolvers/ with GitHub cards The public and room external index pages queried children of a bogus https://./ parent, so /-/ always looked empty. Collect host-only https roots from all Web items and item_children edges so ghost parents from add_child_edge appear. Move GitHub resolver into server/src/resolvers/ with default_external.rs and a try_render_resolver_item_body hook. Resolver ingests now store slug-github-card fenced JSON; render_item_body_in_scope shows a small GitHub article card (with legacy support for schema-less json fences on github.com URLs). Styling in theme_default.css; agents.md updated. Co-authored-by: tommy * Vote compare: GitHub cards in columns, layout CSS, tests Pass item_bodies into vote_compare_item_card for linkified tooltips on non-card bodies; clone item_bodies before dropping reducer read guard. Add layout rules so rich cards sit in the grid corners (default + retro). Unit test on vote_compare_item_card; integration GET /vote/compare with ingested slug-github-card bodies. agents.md clarifies compare columns. Co-authored-by: tommy --------- Co-authored-by: Cursor Agent Side B — unified diff (full patch): diff --git a/agents.md b/agents.md index 7508234d9b04223d0e64cfe69fedbebd06a256b5..d8b801e454fdf37e7ac6038b91a69f83b0746d59 100644 --- a/agents.md +++ b/agents.md @@ -42,7 +42,7 @@ Strict **CSP** that blocks `eval` would break the current app. Other projects ma - **`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. -- **`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. +- **`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.
     
     - **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.
     
    diff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs
    index 4b0214d18b173cd506d09176104f461dc4c4f208..c9eb8e242072e41fcf70da838bdf02dd4c838db8 100644
    --- a/server/src/api/ui_html.rs
    +++ b/server/src/api/ui_html.rs
    @@ -18,7 +18,7 @@ use crate::{
             rpc::{rpc_post_redact, rpc_post_with_bearer, rpc_room_delete},
         },
         canonical_path::canonicalize_tag,
    -    external_resolver::resolve_github_children,
    +    resolvers::resolve_github_children,
         html::vote_compare_post_success_js,
         html::{
             external_resolver_status_markup, fragment_new_thread_slot, login_to_post_hint_markup,
    diff --git a/server/src/external_resolver.rs b/server/src/external_resolver.rs
    deleted file mode 100644
    index a5812250fed7613950b5417f396f886a55fafccf..0000000000000000000000000000000000000000
    --- a/server/src/external_resolver.rs
    +++ /dev/null
    @@ -1,630 +0,0 @@
    -use async_trait::async_trait;
    -use serde_json::Value;
    -use tokio::sync::oneshot;
    -
    -use crate::{path_types::ItemId, state::AppState, write_cmd::WriteCmd};
    -
    -const GITHUB_SYSTEM_PRINCIPAL: &str = "system:github-resolver";
    -const GITHUB_RESOLVER_COOLDOWN_MS: i64 = 15_000;
    -const GITHUB_MAX_PAGES: usize = 3;
    -
    -fn now_ms() -> i64 {
    -    use std::time::{SystemTime, UNIX_EPOCH};
    -    SystemTime::now()
    -        .duration_since(UNIX_EPOCH)
    -        .unwrap_or_default()
    -        .as_millis() as i64
    -}
    -
    -#[derive(Debug, Clone, PartialEq, Eq)]
    -pub struct ResolvedChild {
    -    pub url: String,
    -    pub title: String,
    -    pub body: Option,
    -}
    -
    -#[async_trait]
    -pub trait ExternalResolver: Send + Sync {
    -    /// e.g. `"github.com"`
    -    fn domain_match(&self) -> &'static str;
    -
    -    /// Normalizes URLs (e.g. stripping fragments); extend per-domain later.
    -    fn normalize(&self, path: &str) -> String;
    -
    -    /// Fetches body when missing; GitHub hook lands here in a follow-up.
    -    async fn fetch_body(&self, item: &ItemId) -> Result;
    -}
    -
    -#[derive(Clone)]
    -pub struct GitHubResolver {
    -    client: reqwest::Client,
    -    api_base_url: String,
    -    token: Option,
    -}
    -
    -impl GitHubResolver {
    -    pub fn from_env() -> Self {
    -        let api_base_url = std::env::var("SLUG_GITHUB_API_BASE_URL")
    -            .ok()
    -            .filter(|s| !s.trim().is_empty())
    -            .unwrap_or_else(|| "https://api.github.com".to_string());
    -        let token = std::env::var("SLUG_GITHUB_TOKEN")
    -            .ok()
    -            .filter(|s| !s.trim().is_empty());
    -        Self {
    -            client: reqwest::Client::new(),
    -            api_base_url: api_base_url.trim_end_matches('/').to_string(),
    -            token,
    -        }
    -    }
    -
    -    pub fn can_resolve_children(&self, item: &ItemId) -> bool {
    -        github_segments(item).is_some()
    -    }
    -
    -    pub async fn list_children(&self, item: &ItemId) -> Result, String> {
    -        let segments = github_segments(item).ok_or_else(|| "not a GitHub URL".to_string())?;
    -        match segments.as_slice() {
    -            [] => Ok(vec![]),
    -            [owner] => self.list_repos(owner).await,
    -            [owner, repo] => Ok(github_repo_sections(owner, repo)),
    -            [owner, repo, section] if section == "issues" => self.list_issues(owner, repo).await,
    -            [owner, repo, section] if section == "pulls" => self.list_pulls(owner, repo).await,
    -            [owner, repo, section] if section == "commits" => self.list_commits(owner, repo).await,
    -            [owner, repo, section] if section == "releases" => {
    -                self.list_releases(owner, repo).await
    -            }
    -            _ => Ok(vec![]),
    -        }
    -    }
    -
    -    async fn get_json(&self, path: &str) -> Result {
    -        let url = format!("{}/{}", self.api_base_url, path.trim_start_matches('/'));
    -        let mut req = self
    -            .client
    -            .get(url)
    -            .header(reqwest::header::USER_AGENT, "slugsocial-github-resolver");
    -        if let Some(token) = &self.token {
    -            req = req.bearer_auth(token);
    -        }
    -        let resp = req
    -            .send()
    -            .await
    -            .map_err(|e| format!("GitHub request failed: {e}"))?;
    -        let status = resp.status();
    -        if !status.is_success() {
    -            return Err(format!("GitHub request returned {status}"));
    -        }
    -        resp.json::()
    -            .await
    -            .map_err(|e| format!("GitHub response JSON failed: {e}"))
    -    }
    -
    -    async fn get_json_array_pages(&self, path: &str) -> Result, String> {
    -        let sep = if path.contains('?') { '&' } else { '?' };
    -        let mut out = Vec::new();
    -        for page in 1..=GITHUB_MAX_PAGES {
    -            let value = self.get_json(&format!("{path}{sep}page={page}")).await?;
    -            let arr = value
    -                .as_array()
    -                .ok_or_else(|| "GitHub paged response was not an array".to_string())?;
    -            let n = arr.len();
    -            out.extend(arr.iter().cloned());
    -            if n < 100 {
    -                break;
    -            }
    -        }
    -        Ok(out)
    -    }
    -
    -    async fn list_repos(&self, owner: &str) -> Result, String> {
    -        let arr = self
    -            .get_json_array_pages(&format!(
    -                "/users/{owner}/repos?per_page=100&sort=updated&type=owner"
    -            ))
    -            .await?;
    -        let mut out = Vec::new();
    -        for repo in &arr {
    -            let name = repo
    -                .get("name")
    -                .and_then(|v| v.as_str())
    -                .unwrap_or_default();
    -            if name.is_empty() {
    -                continue;
    -            }
    -            let full_name = repo
    -                .get("full_name")
    -                .and_then(|v| v.as_str())
    -                .map(|s| s.to_ascii_lowercase())
    -                .unwrap_or_else(|| format!("{owner}/{name}").to_ascii_lowercase());
    -            out.push(ResolvedChild {
    -                url: format!("https://github.com/{full_name}"),
    -                title: full_name.clone(),
    -                body: Some(github_repo_body(repo)),
    -            });
    -        }
    -        out.sort_by(|a, b| a.url.cmp(&b.url));
    -        Ok(out)
    -    }
    -
    -    async fn list_issues(&self, owner: &str, repo: &str) -> Result, String> {
    -        let arr = self
    -            .get_json_array_pages(&format!(
    -                "/repos/{owner}/{repo}/issues?state=open&per_page=100"
    -            ))
    -            .await?;
    -        let mut out = Vec::new();
    -        for issue in &arr {
    -            if issue.get("pull_request").is_some() {
    -                continue;
    -            }
    -            let Some(number) = issue.get("number").and_then(|v| v.as_i64()) else {
    -                continue;
    -            };
    -            let title = issue
    -                .get("title")
    -                .and_then(|v| v.as_str())
    -                .unwrap_or("Untitled issue");
    -            out.push(ResolvedChild {
    -                url: format!("https://github.com/{owner}/{repo}/issues/{number}"),
    -                title: format!("#{number} {title}"),
    -                body: Some(github_issue_body(issue, "issue")),
    -            });
    -        }
    -        out.sort_by(|a, b| a.url.cmp(&b.url));
    -        Ok(out)
    -    }
    -
    -    async fn list_pulls(&self, owner: &str, repo: &str) -> Result, String> {
    -        let arr = self
    -            .get_json_array_pages(&format!(
    -                "/repos/{owner}/{repo}/pulls?state=open&per_page=100"
    -            ))
    -            .await?;
    -        let mut out = Vec::new();
    -        for pull in &arr {
    -            let Some(number) = pull.get("number").and_then(|v| v.as_i64()) else {
    -                continue;
    -            };
    -            let title = pull
    -                .get("title")
    -                .and_then(|v| v.as_str())
    -                .unwrap_or("Untitled pull request");
    -            out.push(ResolvedChild {
    -                url: format!("https://github.com/{owner}/{repo}/pulls/{number}"),
    -                title: format!("#{number} {title}"),
    -                body: Some(github_issue_body(pull, "pull request")),
    -            });
    -        }
    -        out.sort_by(|a, b| a.url.cmp(&b.url));
    -        Ok(out)
    -    }
    -
    -    async fn list_commits(&self, owner: &str, repo: &str) -> Result, String> {
    -        let arr = self
    -            .get_json_array_pages(&format!("/repos/{owner}/{repo}/commits?per_page=100"))
    -            .await?;
    -        let mut out = Vec::new();
    -        for commit in &arr {
    -            let Some(sha) = github_string(commit, "sha") else {
    -                continue;
    -            };
    -            let short = sha.chars().take(7).collect::();
    -            let title = commit
    -                .get("commit")
    -                .and_then(|c| c.get("message"))
    -                .and_then(|v| v.as_str())
    -                .and_then(|m| m.lines().next())
    -                .filter(|s| !s.trim().is_empty())
    -                .unwrap_or("commit");
    -            let url = github_string(commit, "html_url")
    -                .map(|s| s.to_string())
    -                .unwrap_or_else(|| format!("https://github.com/{owner}/{repo}/commit/{sha}"));
    -            out.push(ResolvedChild {
    -                url,
    -                title: format!("{short} {title}"),
    -                body: Some(github_commit_body(commit)),
    -            });
    -        }
    -        out.sort_by(|a, b| a.url.cmp(&b.url));
    -        Ok(out)
    -    }
    -
    -    async fn list_releases(&self, owner: &str, repo: &str) -> Result, String> {
    -        let arr = self
    -            .get_json_array_pages(&format!("/repos/{owner}/{repo}/releases?per_page=100"))
    -            .await?;
    -        let mut out = Vec::new();
    -        for release in &arr {
    -            let Some(tag) = github_string(release, "tag_name") else {
    -                continue;
    -            };
    -            let title = github_string(release, "name").unwrap_or(tag);
    -            let url = github_string(release, "html_url")
    -                .map(|s| s.to_string())
    -                .unwrap_or_else(|| format!("https://github.com/{owner}/{repo}/releases/tag/{tag}"));
    -            out.push(ResolvedChild {
    -                url,
    -                title: title.to_string(),
    -                body: Some(github_release_body(release)),
    -            });
    -        }
    -        out.sort_by(|a, b| a.url.cmp(&b.url));
    -        Ok(out)
    -    }
    -}
    -
    -fn github_segments(item: &ItemId) -> Option> {
    -    let url = url::Url::parse(item.as_str()).ok()?;
    -    if url.host_str()?.eq_ignore_ascii_case("github.com") {
    -        Some(
    -            url.path_segments()
    -                .map(|segments| {
    -                    segments
    -                        .filter(|s| !s.is_empty())
    -                        .map(|s| s.to_ascii_lowercase())
    -                        .collect::>()
    -                })
    -                .unwrap_or_default(),
    -        )
    -    } else {
    -        None
    -    }
    -}
    -
    -fn github_repo_sections(owner: &str, repo: &str) -> Vec {
    -    [
    -        ("issues", "GitHub issues for this repository."),
    -        ("pulls", "GitHub pull requests for this repository."),
    -        ("commits", "GitHub commits for this repository."),
    -        ("releases", "GitHub releases for this repository."),
    -    ]
    -    .into_iter()
    -    .map(|(section, body)| ResolvedChild {
    -        url: format!("https://github.com/{owner}/{repo}/{section}"),
    -        title: section.to_string(),
    -        body: Some(body.to_string()),
    -    })
    -    .collect()
    -}
    -
    -fn resolver_thread_tag(item: &ItemId) -> String {
    -    let tail = item
    -        .display_path()
    -        .trim_start_matches("-/")
    -        .replace('/', ":")
    -        .replace('?', ":");
    -    format!("import:{tail}")
    -}
    -
    -fn sanitize_body(s: &str) -> String {
    -    s.replace('{', "(")
    -        .replace('}', ")")
    -        .replace("```", "` ` `")
    -        .chars()
    -        .take(4_000)
    -        .collect()
    -}
    -
    -fn github_string<'a>(value: &'a Value, key: &str) -> Option<&'a str> {
    -    value
    -        .get(key)
    -        .and_then(|v| v.as_str())
    -        .filter(|s| !s.trim().is_empty())
    -}
    -
    -fn github_user_login(value: &Value) -> Option<&str> {
    -    value
    -        .get("user")
    -        .and_then(|u| u.get("login"))
    -        .and_then(|v| v.as_str())
    -        .filter(|s| !s.trim().is_empty())
    -}
    -
    -fn github_labels(value: &Value) -> Vec {
    -    value
    -        .get("labels")
    -        .and_then(|v| v.as_array())
    -        .into_iter()
    -        .flat_map(|labels| labels.iter())
    -        .filter_map(|label| label.get("name").and_then(|v| v.as_str()))
    -        .filter(|name| !name.trim().is_empty())
    -        .map(|name| name.to_string())
    -        .collect()
    -}
    -
    -fn github_repo_body(repo: &Value) -> String {
    -    let full_name = github_string(repo, "full_name")
    -        .or_else(|| github_string(repo, "name"))
    -        .unwrap_or("GitHub repository");
    -    let mut lines = vec![full_name.to_string()];
    -    if let Some(desc) = github_string(repo, "description") {
    -        lines.push(String::new());
    -        lines.push(desc.to_string());
    -    }
    -    if let Some(url) = github_string(repo, "html_url") {
    -        lines.push(String::new());
    -        lines.push(format!("Source: {url}"));
    -    }
    -    if let Some(lang) = github_string(repo, "language") {
    -        lines.push(format!("Language: {lang}"));
    -    }
    -    lines.join("\n")
    -}
    -
    -fn github_issue_body(issue: &Value, kind: &str) -> String {
    -    let number = issue
    -        .get("number")
    -        .and_then(|v| v.as_i64())
    -        .map(|n| format!("#{n} "))
    -        .unwrap_or_default();
    -    let title = github_string(issue, "title").unwrap_or("Untitled");
    -    let state = github_string(issue, "state").unwrap_or("unknown");
    -    let mut lines = vec![format!("{kind} {number}{title}")];
    -    lines.push(format!("State: {state}"));
    -    if let Some(author) = github_user_login(issue) {
    -        lines.push(format!("Author: @{author}"));
    -    }
    -    let labels = github_labels(issue);
    -    if !labels.is_empty() {
    -        lines.push(format!("Labels: {}", labels.join(", ")));
    -    }
    -    if let Some(url) = github_string(issue, "html_url") {
    -        lines.push(format!("Source: {url}"));
    -    }
    -    if let Some(body) = github_string(issue, "body") {
    -        lines.push(String::new());
    -        lines.push(body.to_string());
    -    }
    -    lines.join("\n")
    -}
    -
    -fn github_commit_body(commit: &Value) -> String {
    -    let sha = github_string(commit, "sha").unwrap_or("unknown");
    -    let short = sha.chars().take(7).collect::();
    -    let commit_obj = commit.get("commit");
    -    let message = commit_obj
    -        .and_then(|c| c.get("message"))
    -        .and_then(|v| v.as_str())
    -        .unwrap_or("commit");
    -    let mut lines = vec![format!("commit {short}")];
    -    if let Some(author) = commit_obj
    -        .and_then(|c| c.get("author"))
    -        .and_then(|a| a.get("name"))
    -        .and_then(|v| v.as_str())
    -        .filter(|s| !s.trim().is_empty())
    -    {
    -        lines.push(format!("Author: {author}"));
    -    }
    -    if let Some(login) = github_user_login(commit) {
    -        lines.push(format!("GitHub user: @{login}"));
    -    }
    -    if let Some(date) = commit_obj
    -        .and_then(|c| c.get("author"))
    -        .and_then(|a| a.get("date"))
    -        .and_then(|v| v.as_str())
    -    {
    -        lines.push(format!("Date: {date}"));
    -    }
    -    if let Some(url) = github_string(commit, "html_url") {
    -        lines.push(format!("Source: {url}"));
    -    }
    -    lines.push(String::new());
    -    lines.push(message.to_string());
    -    lines.join("\n")
    -}
    -
    -fn github_release_body(release: &Value) -> String {
    -    let tag = github_string(release, "tag_name").unwrap_or("untagged");
    -    let title = github_string(release, "name").unwrap_or(tag);
    -    let mut lines = vec![format!("release {title}")];
    -    lines.push(format!("Tag: {tag}"));
    -    if release
    -        .get("draft")
    -        .and_then(|v| v.as_bool())
    -        .unwrap_or(false)
    -    {
    -        lines.push("Draft: yes".to_string());
    -    }
    -    if release
    -        .get("prerelease")
    -        .and_then(|v| v.as_bool())
    -        .unwrap_or(false)
    -    {
    -        lines.push("Prerelease: yes".to_string());
    -    }
    -    if let Some(author) = github_user_login(release) {
    -        lines.push(format!("Author: @{author}"));
    -    }
    -    if let Some(published) = github_string(release, "published_at") {
    -        lines.push(format!("Published: {published}"));
    -    }
    -    if let Some(url) = github_string(release, "html_url") {
    -        lines.push(format!("Source: {url}"));
    -    }
    -    if let Some(body) = github_string(release, "body") {
    -        lines.push(String::new());
    -        lines.push(body.to_string());
    -    }
    -    lines.join("\n")
    -}
    -
    -fn children_to_dsl(children: &[ResolvedChild]) -> String {
    -    let mut out = String::new();
    -    for child in children {
    -        let body = child
    -            .body
    -            .as_deref()
    -            .filter(|s| !s.trim().is_empty())
    -            .unwrap_or(child.title.as_str());
    -        if body.trim_start().starts_with("```") {
    -            out.push_str(&format!("{} {{\n{}\n}}\n\n", child.url, body.trim()));
    -        } else {
    -            out.push_str(&format!(
    -                "{} {{\n{}\n}}\n\n",
    -                child.url,
    -                sanitize_body(body)
    -            ));
    -        }
    -    }
    -    out
    -}
    -
    -pub async fn resolve_github_children(
    -    state: &AppState,
    -    room: &str,
    -    item: &ItemId,
    -) -> Result {
    -    if !state.github_resolver.can_resolve_children(item) {
    -        return Err("no GitHub resolver for this item".to_string());
    -    }
    -
    -    let key = format!("github:{}:{}", room.trim(), item.as_str());
    -    let now = now_ms();
    -    {
    -        let mut runs = state.resolver_runs.write().await;
    -        if let Some(last) = runs.get(&key) {
    -            let remaining = GITHUB_RESOLVER_COOLDOWN_MS - (now - *last);
    -            if remaining > 0 {
    -                return Err(format!(
    -                    "GitHub resolver cooldown: try again in {}s",
    -                    (remaining + 999) / 1000
    -                ));
    -            }
    -        }
    -        runs.insert(key, now);
    -    }
    -
    -    let children = state.github_resolver.list_children(item).await?;
    -    if children.is_empty() {
    -        return Ok(0);
    -    }
    -    let text = children_to_dsl(&children);
    -    let thread_tag = resolver_thread_tag(item);
    -    let (tx, rx) = oneshot::channel();
    -    state
    -        .write_tx
    -        .send(WriteCmd::SystemIngest {
    -            room: room.to_string(),
    -            thread_tag,
    -            text,
    -            principal: GITHUB_SYSTEM_PRINCIPAL.to_string(),
    -            reply: tx,
    -        })
    -        .await
    -        .map_err(|_| "writer unavailable".to_string())?;
    -    rx.await
    -        .map_err(|_| "writer dropped".to_string())?
    -        .map_err(|(msg, hint)| hint.map_or(msg.clone(), |h| format!("{msg}: {h}")))?;
    -    Ok(children.len())
    -}
    -
    -/// Placeholder until other domain-specific resolvers exist.
    -pub struct DefaultExternalResolver;
    -
    -#[async_trait]
    -impl ExternalResolver for DefaultExternalResolver {
    -    fn domain_match(&self) -> &'static str {
    -        ""
    -    }
    -
    -    fn normalize(&self, path: &str) -> String {
    -        path.to_string()
    -    }
    -
    -    async fn fetch_body(&self, _item: &ItemId) -> Result {
    -        Err("external fetch not implemented".to_string())
    -    }
    -}
    -
    -#[cfg(test)]
    -mod tests {
    -    use super::*;
    -
    -    #[test]
    -    fn github_segments_parse_normalized_url() {
    -        let item = ItemId::parse("https://github.com/Sortersocial/Slug/issues").unwrap();
    -        assert_eq!(
    -            github_segments(&item),
    -            Some(vec![
    -                "sortersocial".to_string(),
    -                "slug".to_string(),
    -                "issues".to_string()
    -            ])
    -        );
    -    }
    -
    -    #[test]
    -    fn repo_sections_are_direct_children() {
    -        let sections = github_repo_sections("sortersocial", "slug");
    -        let urls: Vec = sections.into_iter().map(|c| c.url).collect();
    -        assert!(urls.contains(&"https://github.com/sortersocial/slug/issues".to_string()));
    -        assert!(urls.contains(&"https://github.com/sortersocial/slug/pulls".to_string()));
    -    }
    -
    -    #[test]
    -    fn children_to_dsl_contains_item_bodies() {
    -        let dsl = children_to_dsl(&[ResolvedChild {
    -            url: "https://github.com/o/r/issues/1".into(),
    -            title: "#1 title".into(),
    -            body: Some("body with {braces}".into()),
    -        }]);
    -        assert!(dsl.contains("https://github.com/o/r/issues/1"));
    -        assert!(dsl.contains("body with (braces)"));
    -    }
    -
    -    #[test]
    -    fn children_to_dsl_preserves_fenced_json_bodies() {
    -        let dsl = children_to_dsl(&[ResolvedChild {
    -            url: "https://github.com/o/r/issues/1".into(),
    -            title: "#1 title".into(),
    -            body: Some("```json\n{\"test\": true}\n```".into()),
    -        }]);
    -        assert!(dsl.contains("https://github.com/o/r/issues/1 {\n```json"));
    -        assert!(dsl.contains("{\"test\": true}"));
    -        assert!(dsl.contains("```\n}\n"));
    -    }
    -
    -    #[test]
    -    fn github_issue_body_is_readable_text_not_json_dump() {
    -        let issue = serde_json::json!({
    -            "number": 12,
    -            "title": "Render children",
    -            "state": "open",
    -            "html_url": "https://github.com/o/r/issues/12",
    -            "user": {"login": "octo"},
    -            "labels": [{"name": "bug"}],
    -            "body": "The issue body."
    -        });
    -        let body = github_issue_body(&issue, "issue");
    -        assert!(body.contains("issue #12 Render children"));
    -        assert!(body.contains("Author: @octo"));
    -        assert!(body.contains("The issue body."));
    -        assert!(!body.trim_start().starts_with("```json"));
    -    }
    -
    -    #[test]
    -    fn github_commit_and_release_bodies_are_readable() {
    -        let commit = serde_json::json!({
    -            "sha": "abcdef123456",
    -            "html_url": "https://github.com/o/r/commit/abcdef123456",
    -            "author": {"login": "octo"},
    -            "commit": {
    -                "message": "Fix vote page\n\nDetails here.",
    -                "author": {"name": "Octo Dev", "date": "2026-05-17T00:00:00Z"}
    -            }
    -        });
    -        let release = serde_json::json!({
    -            "tag_name": "v1.2.3",
    -            "name": "Release 1.2.3",
    -            "html_url": "https://github.com/o/r/releases/tag/v1.2.3",
    -            "author": {"login": "octo"},
    -            "prerelease": true,
    -            "body": "Release notes."
    -        });
    -        assert!(github_commit_body(&commit).contains("commit abcdef1"));
    -        assert!(github_commit_body(&commit).contains("Fix vote page"));
    -        assert!(github_release_body(&release).contains("release Release 1.2.3"));
    -        assert!(github_release_body(&release).contains("Prerelease: yes"));
    -    }
    -}
    diff --git a/server/src/html/garden.rs b/server/src/html/garden.rs
    index 9ca66e7c5860d428e95abf5df518fc1e7b4f6332..e2dc6e5529d4a3126723d0dea75931d0738b6c83 100644
    --- a/server/src/html/garden.rs
    +++ b/server/src/html/garden.rs
    @@ -7,7 +7,7 @@ use axum_extra::extract::cookie::CookieJar;
     use maud::html;
     use serde::Deserialize;
     use serde_json::json;
    -use std::collections::HashSet;
    +use std::collections::{HashMap, HashSet};
     
     use base64::{engine::general_purpose::URL_SAFE_NO_PAD as B64_ENGINE, Engine as _};
     
    @@ -21,8 +21,8 @@ use crate::{
         path_types::ItemId,
         reducer::{ContentState, ReducerState, ScopeId},
         scope_rank::{
    -        build_children_rankings, build_rankings_for_item_set, resolve_scope_recursive,
    -        suggest_next_pair_in_pool, ChildrenRankings,
    +        build_children_rankings, build_rankings_for_item_set, external_root_host_items,
    +        resolve_scope_recursive, suggest_next_pair_in_pool, ChildrenRankings,
         },
         state::AppState,
         timeago,
    @@ -33,7 +33,7 @@ use super::{
         breadcrumb_path::{ExternalOntologyPath, OntologyPath},
         cli_panel,
         forum::ThreadNav,
    -    layout, layout_full_bleed_chromeless, now_ms, ratio_pct, render_linkified_with_embeds_in_scope,
    +    layout, layout_full_bleed_chromeless, now_ms, ratio_pct, render_item_body_in_scope,
         theme_from_jar, theme_next_from_uri,
     };
     
    @@ -358,6 +358,7 @@ fn vote_compare_item_card(
         item: &ItemId,
         body: Option<&String>,
         side_class: &str,
    +    item_bodies: Option<&HashMap>,
     ) -> maud::Markup {
         html! {
             div class=(format!("vote-compare-side {side_class}")) {
    @@ -366,10 +367,10 @@ fn vote_compare_item_card(
                 }
                 @if let Some(body) = body.filter(|b| !b.trim().is_empty()) {
                     div class="vote-compare-item-body" {
    -                    (render_linkified_with_embeds_in_scope(
    +                    (render_item_body_in_scope(
                             body,
                             nav.garden_root_url(),
    -                        None,
    +                        item_bodies,
                         ))
                     }
                 } @else {
    @@ -678,10 +679,11 @@ pub async fn external_garden_index(
     ) -> impl IntoResponse {
         let nav = ThreadNav::public();
         let ext_path = ExternalOntologyPath::from_input("");
    -    let parent = ItemId::parse("https://.").unwrap();
         let child_rankings = {
             let reduced = state.reduced.read().await;
    -        build_children_rankings(reduced.public(), &parent)
    +        let content = reduced.public();
    +        let hosts = external_root_host_items(content);
    +        build_rankings_for_item_set(content, &hosts)
         };
     
         let url_key = canonical_view_url(&uri);
    @@ -812,9 +814,11 @@ pub async fn room_external_garden_index(
             return room_not_found_page(&jar, &uri).into_response();
         }
         let ext_path = ExternalOntologyPath::from_input("");
    -    let parent = ItemId::parse("https://.").unwrap();
    -    let child_rankings =
    -        build_children_rankings(content_for_garden_view(&reduced, &nav.scope()), &parent);
    +    let child_rankings = {
    +        let content = content_for_garden_view(&reduced, &nav.scope());
    +        let hosts = external_root_host_items(content);
    +        build_rankings_for_item_set(content, &hosts)
    +    };
         drop(reduced);
     
         let url_key = canonical_view_url(&uri);
    @@ -1334,7 +1338,7 @@ async fn render_scope_view(
                     }
                     @if let Some(body) = &model.body {
                         div class="ont-item-content" {
    -                        (render_linkified_with_embeds_in_scope(
    +                        (render_item_body_in_scope(
                                 body,
                                 nav.garden_root_url(),
                                 Some(&scope_content.item_bodies),
    @@ -1592,6 +1596,7 @@ async fn vote_compare_inner(
         let edge_history = vote_edge_history_markup(content, &left, &right);
         let left_body = content.item_bodies.get(&left).cloned();
         let right_body = content.item_bodies.get(&right).cloned();
    +    let item_bodies_for_cards = content.item_bodies.clone();
         let next_pair = suggest_next_vote_pair(content, &left, &right);
         drop(reduced);
     
    @@ -1623,9 +1628,21 @@ async fn vote_compare_inner(
         section class="vote-compare-shell" {
             h2 { "compare" }
             div class="vote-compare-pair" {
    -            (vote_compare_item_card(&nav, &left, left_body.as_ref(), "vote-compare-left"))
    +            (vote_compare_item_card(
    +                &nav,
    +                &left,
    +                left_body.as_ref(),
    +                "vote-compare-left",
    +                Some(&item_bodies_for_cards),
    +            ))
                 span class="vote-compare-vs" { "vs" }
    -            (vote_compare_item_card(&nav, &right, right_body.as_ref(), "vote-compare-right"))
    +            (vote_compare_item_card(
    +                &nav,
    +                &right,
    +                right_body.as_ref(),
    +                "vote-compare-right",
    +                Some(&item_bodies_for_cards),
    +            ))
             }
             (vote_compare_nav_markup(&nav, next_pair.as_ref(), &left, &right, q.thread.as_deref()))
             div id="vote-edge-history-region" {
    @@ -2020,6 +2037,40 @@ mod tests {
             assert!(items.contains("https://slug.social/~/topic/b"));
         }
     
    +    #[test]
    +    fn vote_compare_item_card_renders_github_import_markup() {
    +        use crate::html::forum::ThreadNav;
    +        use super::vote_compare_item_card;
    +        use crate::path_types::ItemId;
    +
    +        let nav = ThreadNav::public();
    +        let item = ItemId::parse("https://github.com/o/r/issues/1").unwrap();
    +        let json = serde_json::json!({
    +            "v": 1,
    +            "schema": "slug_github_import",
    +            "kind": "issue",
    +            "url": "https://github.com/o/r/issues/1",
    +            "headline": "#1 Compare card",
    +            "sublines": ["State: open"],
    +        });
    +        let body = format!("```slug-github-card\n{}\n```", json.to_string());
    +        let html = vote_compare_item_card(
    +            &nav,
    +            &item,
    +            Some(&body),
    +            "vote-compare-left",
    +            None,
    +        )
    +        .into_string();
    +        assert!(
    +            html.contains("github-import-card"),
    +            "expected rich GitHub card markup, got: {html}"
    +        );
    +        assert!(html.contains("item-body-rich"));
    +        assert!(html.contains("vote-compare-left"));
    +        assert!(html.contains("#1 Compare card"));
    +    }
    +
         #[test]
         fn external_source_href_maps_youtube_path_identity_back_to_watch_url() {
             assert_eq!(
    diff --git a/server/src/html/mod.rs b/server/src/html/mod.rs
    index a1b929625acbd5298c0cf62f3ca0892079edcb2a..3b23e19a8b35aa4c0b0480e29de7d46ad57ab276 100644
    --- a/server/src/html/mod.rs
    +++ b/server/src/html/mod.rs
    @@ -793,6 +793,20 @@ pub(super) fn render_linkified_with_embeds_in_scope(
         }
     }
     
    +/// Item page / thread body: resolver-specific rich HTML, else linkified `
    ` + media embeds.
    +pub(super) fn render_item_body_in_scope(
    +    raw: &str,
    +    garden_prefix: &str,
    +    item_bodies: Option<&HashMap>,
    +) -> Markup {
    +    if let Some(m) = crate::resolvers::try_render_resolver_item_body(raw) {
    +        return html! {
    +            div class="item-body-rich" { (m) }
    +        };
    +    }
    +    render_linkified_with_embeds_in_scope(raw, garden_prefix, item_bodies)
    +}
    +
     /// CLI strings are embedded in a single-quoted JS literal; they must never need escaping.
     fn assert_cli_panel_cmd_js_single_quote_safe(s: &str) {
         assert!(
    diff --git a/server/src/lib.rs b/server/src/lib.rs
    index 84e94bbec144eae77de68482385941cd2c5845eb..c1d477d21aea03aff00e6f0689b0b4379d0d68d2 100644
    --- a/server/src/lib.rs
    +++ b/server/src/lib.rs
    @@ -5,7 +5,7 @@ pub mod canonical_path;
     pub mod dsl;
     pub mod event_log;
     pub mod events;
    -pub mod external_resolver;
    +pub mod resolvers;
     pub mod form_template;
     pub mod html;
     pub mod identity;
    @@ -51,7 +51,7 @@ pub fn create_app_state(cfg: AppConfig) -> AppState {
             write_tx,
             views,
             resolver_runs: Arc::new(RwLock::new(HashMap::new())),
    -        github_resolver: Arc::new(crate::external_resolver::GitHubResolver::from_env()),
    +        github_resolver: Arc::new(crate::resolvers::GitHubResolver::from_env()),
         };
         tokio::spawn(crate::api::write_actor::writer_actor(
             write_rx,
    diff --git a/server/src/resolvers/default_external.rs b/server/src/resolvers/default_external.rs
    new file mode 100644
    index 0000000000000000000000000000000000000000..d37c222abcee3c20b22189b2822da9e9a6ff0515
    --- /dev/null
    +++ b/server/src/resolvers/default_external.rs
    @@ -0,0 +1,22 @@
    +use async_trait::async_trait;
    +
    +use crate::path_types::ItemId;
    +use super::github::ExternalResolver;
    +
    +/// Placeholder until other domain-specific resolvers exist.
    +pub struct DefaultExternalResolver;
    +
    +#[async_trait]
    +impl ExternalResolver for DefaultExternalResolver {
    +    fn domain_match(&self) -> &'static str {
    +        ""
    +    }
    +
    +    fn normalize(&self, path: &str) -> String {
    +        path.to_string()
    +    }
    +
    +    async fn fetch_body(&self, _item: &ItemId) -> Result {
    +        Err("external fetch not implemented".to_string())
    +    }
    +}
    diff --git a/server/src/resolvers/github.rs b/server/src/resolvers/github.rs
    new file mode 100644
    index 0000000000000000000000000000000000000000..5a9c0c38ff01ca5894f7dc62c1008371dacb0cf1
    --- /dev/null
    +++ b/server/src/resolvers/github.rs
    @@ -0,0 +1,755 @@
    +use async_trait::async_trait;
    +use maud::html;
    +use serde::{Deserialize, Serialize};
    +use serde_json::Value;
    +use tokio::sync::oneshot;
    +
    +use crate::{path_types::ItemId, state::AppState, write_cmd::WriteCmd};
    +
    +pub const SLUG_GITHUB_SCHEMA: &str = "slug_github_import";
    +
    +const GITHUB_SYSTEM_PRINCIPAL: &str = "system:github-resolver";
    +const GITHUB_RESOLVER_COOLDOWN_MS: i64 = 15_000;
    +const GITHUB_MAX_PAGES: usize = 3;
    +
    +fn now_ms() -> i64 {
    +    use std::time::{SystemTime, UNIX_EPOCH};
    +    SystemTime::now()
    +        .duration_since(UNIX_EPOCH)
    +        .unwrap_or_default()
    +        .as_millis() as i64
    +}
    +
    +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
    +#[serde(rename_all = "snake_case")]
    +pub enum GithubImportKind {
    +    Repo,
    +    RepoSection,
    +    Issue,
    +    Pull,
    +    Commit,
    +    Release,
    +}
    +
    +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
    +pub struct GithubImportCard {
    +    pub v: u32,
    +    #[serde(default)]
    +    pub schema: String,
    +    pub kind: GithubImportKind,
    +    pub url: String,
    +    pub headline: String,
    +    #[serde(default)]
    +    pub sublines: Vec,
    +    #[serde(default)]
    +    pub excerpt: Option,
    +}
    +
    +impl GithubImportCard {
    +    fn new(kind: GithubImportKind, url: String, headline: String) -> Self {
    +        Self {
    +            v: 1,
    +            schema: SLUG_GITHUB_SCHEMA.to_string(),
    +            kind,
    +            url,
    +            headline,
    +            sublines: Vec::new(),
    +            excerpt: None,
    +        }
    +    }
    +}
    +
    +#[derive(Debug, Clone, PartialEq, Eq)]
    +pub struct ResolvedChild {
    +    pub url: String,
    +    pub title: String,
    +    pub card: GithubImportCard,
    +}
    +
    +#[async_trait]
    +pub trait ExternalResolver: Send + Sync {
    +    /// e.g. `"github.com"`
    +    fn domain_match(&self) -> &'static str;
    +
    +    /// Normalizes URLs (e.g. stripping fragments); extend per-domain later.
    +    fn normalize(&self, path: &str) -> String;
    +
    +    /// Fetches body when missing; GitHub hook lands here in a follow-up.
    +    async fn fetch_body(&self, item: &ItemId) -> Result;
    +}
    +
    +#[derive(Clone)]
    +pub struct GitHubResolver {
    +    client: reqwest::Client,
    +    api_base_url: String,
    +    token: Option,
    +}
    +
    +impl GitHubResolver {
    +    pub fn from_env() -> Self {
    +        let api_base_url = std::env::var("SLUG_GITHUB_API_BASE_URL")
    +            .ok()
    +            .filter(|s| !s.trim().is_empty())
    +            .unwrap_or_else(|| "https://api.github.com".to_string());
    +        let token = std::env::var("SLUG_GITHUB_TOKEN")
    +            .ok()
    +            .filter(|s| !s.trim().is_empty());
    +        Self {
    +            client: reqwest::Client::new(),
    +            api_base_url: api_base_url.trim_end_matches('/').to_string(),
    +            token,
    +        }
    +    }
    +
    +    pub fn can_resolve_children(&self, item: &ItemId) -> bool {
    +        github_segments(item).is_some()
    +    }
    +
    +    pub async fn list_children(&self, item: &ItemId) -> Result, String> {
    +        let segments = github_segments(item).ok_or_else(|| "not a GitHub URL".to_string())?;
    +        match segments.as_slice() {
    +            [] => Ok(vec![]),
    +            [owner] => self.list_repos(owner).await,
    +            [owner, repo] => Ok(github_repo_sections(owner, repo)),
    +            [owner, repo, section] if section == "issues" => self.list_issues(owner, repo).await,
    +            [owner, repo, section] if section == "pulls" => self.list_pulls(owner, repo).await,
    +            [owner, repo, section] if section == "commits" => self.list_commits(owner, repo).await,
    +            [owner, repo, section] if section == "releases" => {
    +                self.list_releases(owner, repo).await
    +            }
    +            _ => Ok(vec![]),
    +        }
    +    }
    +
    +    async fn get_json(&self, path: &str) -> Result {
    +        let url = format!("{}/{}", self.api_base_url, path.trim_start_matches('/'));
    +        let mut req = self
    +            .client
    +            .get(url)
    +            .header(reqwest::header::USER_AGENT, "slugsocial-github-resolver");
    +        if let Some(token) = &self.token {
    +            req = req.bearer_auth(token);
    +        }
    +        let resp = req
    +            .send()
    +            .await
    +            .map_err(|e| format!("GitHub request failed: {e}"))?;
    +        let status = resp.status();
    +        if !status.is_success() {
    +            return Err(format!("GitHub request returned {status}"));
    +        }
    +        resp.json::()
    +            .await
    +            .map_err(|e| format!("GitHub response JSON failed: {e}"))
    +    }
    +
    +    async fn get_json_array_pages(&self, path: &str) -> Result, String> {
    +        let sep = if path.contains('?') { '&' } else { '?' };
    +        let mut out = Vec::new();
    +        for page in 1..=GITHUB_MAX_PAGES {
    +            let value = self.get_json(&format!("{path}{sep}page={page}")).await?;
    +            let arr = value
    +                .as_array()
    +                .ok_or_else(|| "GitHub paged response was not an array".to_string())?;
    +            let n = arr.len();
    +            out.extend(arr.iter().cloned());
    +            if n < 100 {
    +                break;
    +            }
    +        }
    +        Ok(out)
    +    }
    +
    +    async fn list_repos(&self, owner: &str) -> Result, String> {
    +        let arr = self
    +            .get_json_array_pages(&format!(
    +                "/users/{owner}/repos?per_page=100&sort=updated&type=owner"
    +            ))
    +            .await?;
    +        let mut out = Vec::new();
    +        for repo in &arr {
    +            let name = repo
    +                .get("name")
    +                .and_then(|v| v.as_str())
    +                .unwrap_or_default();
    +            if name.is_empty() {
    +                continue;
    +            }
    +            let full_name = repo
    +                .get("full_name")
    +                .and_then(|v| v.as_str())
    +                .map(|s| s.to_ascii_lowercase())
    +                .unwrap_or_else(|| format!("{owner}/{name}").to_ascii_lowercase());
    +            let url = format!("https://github.com/{full_name}");
    +            let mut card = card_for_repo(repo, &url);
    +            card.headline = full_name.clone();
    +            out.push(ResolvedChild {
    +                url,
    +                title: full_name,
    +                card,
    +            });
    +        }
    +        out.sort_by(|a, b| a.url.cmp(&b.url));
    +        Ok(out)
    +    }
    +
    +    async fn list_issues(&self, owner: &str, repo: &str) -> Result, String> {
    +        let arr = self
    +            .get_json_array_pages(&format!(
    +                "/repos/{owner}/{repo}/issues?state=open&per_page=100"
    +            ))
    +            .await?;
    +        let mut out = Vec::new();
    +        for issue in &arr {
    +            if issue.get("pull_request").is_some() {
    +                continue;
    +            }
    +            let Some(number) = issue.get("number").and_then(|v| v.as_i64()) else {
    +                continue;
    +            };
    +            let title = issue
    +                .get("title")
    +                .and_then(|v| v.as_str())
    +                .unwrap_or("Untitled issue");
    +            let url = format!("https://github.com/{owner}/{repo}/issues/{number}");
    +            let card = card_for_issue(issue, &url, GithubImportKind::Issue);
    +            out.push(ResolvedChild {
    +                url: url.clone(),
    +                title: format!("#{number} {title}"),
    +                card,
    +            });
    +        }
    +        out.sort_by(|a, b| a.url.cmp(&b.url));
    +        Ok(out)
    +    }
    +
    +    async fn list_pulls(&self, owner: &str, repo: &str) -> Result, String> {
    +        let arr = self
    +            .get_json_array_pages(&format!(
    +                "/repos/{owner}/{repo}/pulls?state=open&per_page=100"
    +            ))
    +            .await?;
    +        let mut out = Vec::new();
    +        for pull in &arr {
    +            let Some(number) = pull.get("number").and_then(|v| v.as_i64()) else {
    +                continue;
    +            };
    +            let title = pull
    +                .get("title")
    +                .and_then(|v| v.as_str())
    +                .unwrap_or("Untitled pull request");
    +            let url = format!("https://github.com/{owner}/{repo}/pulls/{number}");
    +            let card = card_for_issue(pull, &url, GithubImportKind::Pull);
    +            out.push(ResolvedChild {
    +                url: url.clone(),
    +                title: format!("#{number} {title}"),
    +                card,
    +            });
    +        }
    +        out.sort_by(|a, b| a.url.cmp(&b.url));
    +        Ok(out)
    +    }
    +
    +    async fn list_commits(&self, owner: &str, repo: &str) -> Result, String> {
    +        let arr = self
    +            .get_json_array_pages(&format!("/repos/{owner}/{repo}/commits?per_page=100"))
    +            .await?;
    +        let mut out = Vec::new();
    +        for commit in &arr {
    +            let Some(sha) = github_string(commit, "sha") else {
    +                continue;
    +            };
    +            let short = sha.chars().take(7).collect::();
    +            let title = commit
    +                .get("commit")
    +                .and_then(|c| c.get("message"))
    +                .and_then(|v| v.as_str())
    +                .and_then(|m| m.lines().next())
    +                .filter(|s| !s.trim().is_empty())
    +                .unwrap_or("commit");
    +            let url = github_string(commit, "html_url")
    +                .map(|s| s.to_string())
    +                .unwrap_or_else(|| format!("https://github.com/{owner}/{repo}/commit/{sha}"));
    +            let card = card_for_commit(commit, &url, &short, title);
    +            out.push(ResolvedChild {
    +                url: url.clone(),
    +                title: format!("{short} {title}"),
    +                card,
    +            });
    +        }
    +        out.sort_by(|a, b| a.url.cmp(&b.url));
    +        Ok(out)
    +    }
    +
    +    async fn list_releases(&self, owner: &str, repo: &str) -> Result, String> {
    +        let arr = self
    +            .get_json_array_pages(&format!("/repos/{owner}/{repo}/releases?per_page=100"))
    +            .await?;
    +        let mut out = Vec::new();
    +        for release in &arr {
    +            let Some(tag) = github_string(release, "tag_name") else {
    +                continue;
    +            };
    +            let title = github_string(release, "name").unwrap_or(tag);
    +            let url = github_string(release, "html_url")
    +                .map(|s| s.to_string())
    +                .unwrap_or_else(|| format!("https://github.com/{owner}/{repo}/releases/tag/{tag}"));
    +            let card = card_for_release(release, &url, title);
    +            out.push(ResolvedChild {
    +                url: url.clone(),
    +                title: title.to_string(),
    +                card,
    +            });
    +        }
    +        out.sort_by(|a, b| a.url.cmp(&b.url));
    +        Ok(out)
    +    }
    +}
    +
    +fn github_segments(item: &ItemId) -> Option> {
    +    let url = url::Url::parse(item.as_str()).ok()?;
    +    if url.host_str()?.eq_ignore_ascii_case("github.com") {
    +        Some(
    +            url.path_segments()
    +                .map(|segments| {
    +                    segments
    +                        .filter(|s| !s.is_empty())
    +                        .map(|s| s.to_ascii_lowercase())
    +                        .collect::>()
    +                })
    +                .unwrap_or_default(),
    +        )
    +    } else {
    +        None
    +    }
    +}
    +
    +fn title_case_segment(seg: &str) -> String {
    +    let mut c = seg.chars();
    +    match c.next() {
    +        None => String::new(),
    +        Some(f) => f.to_uppercase().chain(c).collect(),
    +    }
    +}
    +
    +fn github_repo_sections(owner: &str, repo: &str) -> Vec {
    +    [
    +        ("issues", "GitHub issues for this repository."),
    +        ("pulls", "GitHub pull requests for this repository."),
    +        ("commits", "GitHub commits for this repository."),
    +        ("releases", "GitHub releases for this repository."),
    +    ]
    +    .into_iter()
    +    .map(|(section, blurb)| {
    +        let url = format!("https://github.com/{owner}/{repo}/{section}");
    +        let mut card = GithubImportCard::new(
    +            GithubImportKind::RepoSection,
    +            url.clone(),
    +            format!("{owner}/{repo} — {}", title_case_segment(section)),
    +        );
    +        card.excerpt = Some(blurb.to_string());
    +        ResolvedChild {
    +            url,
    +            title: section.to_string(),
    +            card,
    +        }
    +    })
    +    .collect()
    +}
    +
    +fn resolver_thread_tag(item: &ItemId) -> String {
    +    let tail = item
    +        .display_path()
    +        .trim_start_matches("-/")
    +        .replace('/', ":")
    +        .replace('?', ":");
    +    format!("import:{tail}")
    +}
    +
    +fn children_to_dsl(children: &[ResolvedChild]) -> String {
    +    let mut out = String::new();
    +    for child in children {
    +        let json = serde_json::to_string(&child.card).unwrap_or_else(|_| "{}".to_string());
    +        let inner = format!("```slug-github-card\n{json}\n```");
    +        out.push_str(&format!("{} {{\n{}\n}}\n\n", child.url, inner));
    +    }
    +    out
    +}
    +
    +fn card_for_repo(repo: &Value, fallback_url: &str) -> GithubImportCard {
    +    let url = github_string(repo, "html_url")
    +        .map(|s| s.to_string())
    +        .filter(|s| !s.is_empty())
    +        .unwrap_or_else(|| fallback_url.to_string());
    +    let full_name = github_string(repo, "full_name")
    +        .or_else(|| github_string(repo, "name"))
    +        .unwrap_or("repository");
    +    let mut card = GithubImportCard::new(GithubImportKind::Repo, url, full_name.to_string());
    +    if let Some(lang) = github_string(repo, "language") {
    +        card.sublines.push(format!("Language: {lang}"));
    +    }
    +    if let Some(desc) = github_string(repo, "description") {
    +        card.excerpt = Some(desc.to_string());
    +    }
    +    card
    +}
    +
    +fn excerpt_from_github_body(body: Option<&str>) -> Option {
    +    let b = body?.trim();
    +    if b.is_empty() {
    +        return None;
    +    }
    +    let max = 1200usize;
    +    if b.len() <= max {
    +        Some(b.to_string())
    +    } else {
    +        Some(format!("{}…", b.chars().take(max).collect::()))
    +    }
    +}
    +
    +fn card_for_issue(v: &Value, url: &str, kind: GithubImportKind) -> GithubImportCard {
    +    let number = v.get("number").and_then(|n| n.as_i64());
    +    let title = github_string(v, "title").unwrap_or("Untitled");
    +    let state = github_string(v, "state").unwrap_or("unknown");
    +    let headline = match number {
    +        Some(n) => format!("#{n} {title}"),
    +        None => title.to_string(),
    +    };
    +    let mut card = GithubImportCard::new(kind, url.to_string(), headline);
    +    card.sublines.push(format!("State: {state}"));
    +    if let Some(a) = github_user_login(v) {
    +        card.sublines.push(format!("Author: @{a}"));
    +    }
    +    let labels = github_labels(v);
    +    if !labels.is_empty() {
    +        card.sublines
    +            .push(format!("Labels: {}", labels.join(", ")));
    +    }
    +    card.excerpt = excerpt_from_github_body(github_string(v, "body"));
    +    card
    +}
    +
    +fn card_for_commit(v: &Value, url: &str, short_sha: &str, subject: &str) -> GithubImportCard {
    +    let headline = format!("{short_sha} {subject}");
    +    let mut card = GithubImportCard::new(GithubImportKind::Commit, url.to_string(), headline);
    +    if let Some(name) = v
    +        .get("commit")
    +        .and_then(|c| c.get("author"))
    +        .and_then(|a| a.get("name"))
    +        .and_then(|n| n.as_str())
    +        .filter(|s| !s.trim().is_empty())
    +    {
    +        card.sublines.push(format!("Author: {name}"));
    +    }
    +    if let Some(login) = github_user_login(v) {
    +        card.sublines.push(format!("GitHub: @{login}"));
    +    }
    +    if let Some(date) = v
    +        .get("commit")
    +        .and_then(|c| c.get("author"))
    +        .and_then(|a| a.get("date"))
    +        .and_then(|d| d.as_str())
    +    {
    +        card.sublines.push(format!("Date: {date}"));
    +    }
    +    if let Some(msg) = v
    +        .get("commit")
    +        .and_then(|c| c.get("message"))
    +        .and_then(|m| m.as_str())
    +    {
    +        card.excerpt = excerpt_from_github_body(Some(msg));
    +    }
    +    card
    +}
    +
    +fn card_for_release(v: &Value, url: &str, title: &str) -> GithubImportCard {
    +    let tag = github_string(v, "tag_name").unwrap_or("untagged");
    +    let mut card = GithubImportCard::new(
    +        GithubImportKind::Release,
    +        url.to_string(),
    +        format!("Release — {title}"),
    +    );
    +    card.sublines.push(format!("Tag: {tag}"));
    +    if v.get("draft").and_then(|b| b.as_bool()).unwrap_or(false) {
    +        card.sublines.push("Draft: yes".to_string());
    +    }
    +    if v.get("prerelease")
    +        .and_then(|b| b.as_bool())
    +        .unwrap_or(false)
    +    {
    +        card.sublines.push("Prerelease: yes".to_string());
    +    }
    +    if let Some(a) = github_user_login(v) {
    +        card.sublines.push(format!("Author: @{a}"));
    +    }
    +    if let Some(pub_at) = github_string(v, "published_at") {
    +        card.sublines.push(format!("Published: {pub_at}"));
    +    }
    +    card.excerpt = excerpt_from_github_body(github_string(v, "body"));
    +    card
    +}
    +
    +fn github_string<'a>(value: &'a Value, key: &str) -> Option<&'a str> {
    +    value
    +        .get(key)
    +        .and_then(|v| v.as_str())
    +        .filter(|s| !s.trim().is_empty())
    +}
    +
    +fn github_user_login(value: &Value) -> Option<&str> {
    +    value
    +        .get("user")
    +        .and_then(|u| u.get("login"))
    +        .and_then(|v| v.as_str())
    +        .filter(|s| !s.trim().is_empty())
    +}
    +
    +fn github_labels(value: &Value) -> Vec {
    +    value
    +        .get("labels")
    +        .and_then(|v| v.as_array())
    +        .into_iter()
    +        .flat_map(|labels| labels.iter())
    +        .filter_map(|label| label.get("name").and_then(|v| v.as_str()))
    +        .filter(|name| !name.trim().is_empty())
    +        .map(|name| name.to_string())
    +        .collect()
    +}
    +
    +pub async fn resolve_github_children(
    +    state: &AppState,
    +    room: &str,
    +    item: &ItemId,
    +) -> Result {
    +    if !state.github_resolver.can_resolve_children(item) {
    +        return Err("no GitHub resolver for this item".to_string());
    +    }
    +
    +    let key = format!("github:{}:{}", room.trim(), item.as_str());
    +    let now = now_ms();
    +    {
    +        let mut runs = state.resolver_runs.write().await;
    +        if let Some(last) = runs.get(&key) {
    +            let remaining = GITHUB_RESOLVER_COOLDOWN_MS - (now - *last);
    +            if remaining > 0 {
    +                return Err(format!(
    +                    "GitHub resolver cooldown: try again in {}s",
    +                    (remaining + 999) / 1000
    +                ));
    +            }
    +        }
    +        runs.insert(key, now);
    +    }
    +
    +    let children = state.github_resolver.list_children(item).await?;
    +    if children.is_empty() {
    +        return Ok(0);
    +    }
    +    let text = children_to_dsl(&children);
    +    let thread_tag = resolver_thread_tag(item);
    +    let (tx, rx) = oneshot::channel();
    +    state
    +        .write_tx
    +        .send(WriteCmd::SystemIngest {
    +            room: room.to_string(),
    +            thread_tag,
    +            text,
    +            principal: GITHUB_SYSTEM_PRINCIPAL.to_string(),
    +            reply: tx,
    +        })
    +        .await
    +        .map_err(|_| "writer unavailable".to_string())?;
    +    rx.await
    +        .map_err(|_| "writer dropped".to_string())?
    +        .map_err(|(msg, hint)| hint.map_or(msg.clone(), |h| format!("{msg}: {h}")))?;
    +    Ok(children.len())
    +}
    +
    +fn extract_fence<'a>(body: &'a str, lang: &str) -> Option<&'a str> {
    +    let b = body.trim();
    +    let prefix = format!("```{lang}");
    +    let rest = b.strip_prefix(prefix.as_str())?;
    +    let rest = rest
    +        .strip_prefix('\n')
    +        .or_else(|| rest.strip_prefix('\r'))
    +        .unwrap_or(rest);
    +    let end = rest.find("\n```")?;
    +    Some(rest[..end].trim())
    +}
    +
    +fn parse_github_import_from_body(body: &str) -> Option {
    +    let trimmed = body.trim();
    +    if let Some(json) = extract_fence(trimmed, "slug-github-card") {
    +        let c: GithubImportCard = serde_json::from_str(json).ok()?;
    +        return (c.v == 1 && (c.schema.is_empty() || c.schema == SLUG_GITHUB_SCHEMA)).then_some(c);
    +    }
    +    if let Some(json) = extract_fence(trimmed, "json") {
    +        if let Ok(c) = serde_json::from_str::(json) {
    +            if c.v == 1
    +                && (c.schema == SLUG_GITHUB_SCHEMA
    +                    || (c.schema.is_empty() && c.url.contains("github.com")))
    +            {
    +                return Some(c);
    +            }
    +        }
    +    }
    +    if trimmed.starts_with('{') {
    +        let c: GithubImportCard = serde_json::from_str(trimmed).ok()?;
    +        return (c.v == 1
    +            && (c.schema == SLUG_GITHUB_SCHEMA
    +                || (c.schema.is_empty() && c.url.contains("github.com"))))
    +        .then_some(c);
    +    }
    +    None
    +}
    +
    +fn kind_badge(kind: &GithubImportKind) -> &'static str {
    +    match kind {
    +        GithubImportKind::Repo => "GitHub · repository",
    +        GithubImportKind::RepoSection => "GitHub · tree",
    +        GithubImportKind::Issue => "GitHub · issue",
    +        GithubImportKind::Pull => "GitHub · pull request",
    +        GithubImportKind::Commit => "GitHub · commit",
    +        GithubImportKind::Release => "GitHub · release",
    +    }
    +}
    +
    +fn render_github_card(card: &GithubImportCard) -> maud::Markup {
    +    html! {
    +        article.github-import-card {
    +            header.github-import-card__hdr {
    +                span class="github-import-card__badge" { (kind_badge(&card.kind)) }
    +                h3.github-import-card__title { (card.headline.as_str()) }
    +            }
    +            @if !card.sublines.is_empty() {
    +                ul.github-import-card__meta {
    +                    @for line in &card.sublines {
    +                        li { (line.as_str()) }
    +                    }
    +                }
    +            }
    +            @if let Some(ex) = &card.excerpt {
    +                div.github-import-card__excerpt {
    +                    @for block in ex.split("\n\n") {
    +                        @if !block.trim().is_empty() {
    +                            p { (block) }
    +                        }
    +                    }
    +                }
    +            }
    +            p.github-import-card__link {
    +                a href=(card.url.as_str()) rel="noopener noreferrer" target="_blank" {
    +                    "Open on GitHub"
    +                }
    +            }
    +        }
    +    }
    +}
    +
    +/// Rich HTML for bodies that contain a [`GithubImportCard`] fence (or equivalent JSON).
    +pub fn try_render_github_import_markup(raw: &str) -> Option {
    +    let card = parse_github_import_from_body(raw)?;
    +    Some(render_github_card(&card))
    +}
    +
    +#[async_trait]
    +impl ExternalResolver for GitHubResolver {
    +    fn domain_match(&self) -> &'static str {
    +        "github.com"
    +    }
    +
    +    fn normalize(&self, path: &str) -> String {
    +        path.to_string()
    +    }
    +
    +    async fn fetch_body(&self, _item: &ItemId) -> Result {
    +        Err("GitHub fetch_body not implemented".to_string())
    +    }
    +}
    +
    +#[cfg(test)]
    +mod tests {
    +    use super::*;
    +
    +    #[test]
    +    fn github_segments_parse_normalized_url() {
    +        let item = ItemId::parse("https://github.com/Sortersocial/Slug/issues").unwrap();
    +        assert_eq!(
    +            github_segments(&item),
    +            Some(vec![
    +                "sortersocial".to_string(),
    +                "slug".to_string(),
    +                "issues".to_string()
    +            ])
    +        );
    +    }
    +
    +    #[test]
    +    fn repo_sections_are_direct_children() {
    +        let sections = github_repo_sections("sortersocial", "slug");
    +        let urls: Vec = sections.into_iter().map(|c| c.url).collect();
    +        assert!(urls.contains(&"https://github.com/sortersocial/slug/issues".to_string()));
    +        assert!(urls.contains(&"https://github.com/sortersocial/slug/pulls".to_string()));
    +    }
    +
    +    #[test]
    +    fn children_to_dsl_wraps_slug_github_card() {
    +        let dsl = children_to_dsl(&[ResolvedChild {
    +            url: "https://github.com/o/r/issues/1".into(),
    +            title: "#1 title".into(),
    +            card: GithubImportCard::new(
    +                GithubImportKind::Issue,
    +                "https://github.com/o/r/issues/1".into(),
    +                "#1 title".into(),
    +            ),
    +        }]);
    +        assert!(dsl.contains("https://github.com/o/r/issues/1"));
    +        assert!(dsl.contains("```slug-github-card"));
    +        assert!(dsl.contains("\"schema\":\"slug_github_import\""));
    +    }
    +
    +    #[test]
    +    fn parse_accepts_slug_github_fence() {
    +        let card = GithubImportCard::new(
    +            GithubImportKind::Repo,
    +            "https://github.com/o/r".into(),
    +            "o/r".into(),
    +        );
    +        let body = format!("```slug-github-card\n{}\n```\n", serde_json::to_string(&card).unwrap());
    +        let parsed = parse_github_import_from_body(&body).expect("parses");
    +        assert_eq!(parsed, card);
    +    }
    +
    +    #[test]
    +    fn parse_accepts_schema_json_fence() {
    +        let card = GithubImportCard::new(
    +            GithubImportKind::Issue,
    +            "https://github.com/o/r/issues/2".into(),
    +            "#2 hi".into(),
    +        );
    +        let json = serde_json::to_string(&card).unwrap();
    +        let body = format!("```json\n{json}\n```");
    +        let parsed = parse_github_import_from_body(&body).expect("parses json fence");
    +        assert_eq!(parsed.headline, "#2 hi");
    +    }
    +
    +    #[test]
    +    fn issue_card_includes_author_and_excerpt() {
    +        let issue = serde_json::json!({
    +            "number": 12,
    +            "title": "Render children",
    +            "state": "open",
    +            "html_url": "https://github.com/o/r/issues/12",
    +            "user": {"login": "octo"},
    +            "labels": [{"name": "bug"}],
    +            "body": "The issue body."
    +        });
    +        let card = card_for_issue(
    +            &issue,
    +            "https://github.com/o/r/issues/12",
    +            GithubImportKind::Issue,
    +        );
    +        assert!(card.sublines.iter().any(|l| l.contains("@octo")));
    +        assert_eq!(card.excerpt.as_deref(), Some("The issue body.").as_deref());
    +    }
    +}
    diff --git a/server/src/resolvers/mod.rs b/server/src/resolvers/mod.rs
    new file mode 100644
    index 0000000000000000000000000000000000000000..3e4caad081acdd2f89cba9f661de43996d6470f3
    --- /dev/null
    +++ b/server/src/resolvers/mod.rs
    @@ -0,0 +1,18 @@
    +//! Domain resolvers (GitHub, …) and matching HTML renderers for imported item bodies.
    +//!
    +//! Resolver output is ingested as DSL; bodies may embed a `slug-github-card` fenced JSON
    +//! envelope that [`crate::html::render_item_body_in_scope`] renders instead of a raw `
    `.
    +
    +pub mod github;
    +pub mod default_external;
    +
    +pub use default_external::DefaultExternalResolver;
    +pub use github::{
    +    resolve_github_children, try_render_github_import_markup, ExternalResolver, GitHubResolver,
    +    GithubImportCard, GithubImportKind, ResolvedChild,
    +};
    +
    +/// Extension point: add more `try_render_*` calls here as new resolvers ship.
    +pub fn try_render_resolver_item_body(raw: &str) -> Option {
    +    github::try_render_github_import_markup(raw)
    +}
    diff --git a/server/src/scope_rank.rs b/server/src/scope_rank.rs
    index 06c560b8eff09b34896d3935d3917fb28f602bc6..2361b2be5ae6b8e1813b6b7ebd5bbf317429b6ad 100644
    --- a/server/src/scope_rank.rs
    +++ b/server/src/scope_rank.rs
    @@ -162,6 +162,45 @@ pub fn build_children_rankings(content: &ContentState, parent: &ItemId) -> Child
         build_rankings_for_item_set(content, &items)
     }
     
    +/// Host-only `https://…` roots for the external garden index (`/-/`).
    +///
    +/// Includes every `https://host` ancestor of any [`ItemId::Web`] item that appears in
    +/// `content.items`, as a parent key in `item_children`, or as a child in `item_children`
    +/// (so implied “ghost” parents created only via [`ReducerState::add_child_edge`] still show up).
    +pub fn external_root_host_items(content: &ContentState) -> Vec {
    +    let mut hosts: HashSet = HashSet::new();
    +
    +    let mut consider = |id: ItemId| {
    +        let id = id.normalized_storage();
    +        if !matches!(&id, ItemId::Web(_)) {
    +            return;
    +        }
    +        let mut cur = id;
    +        while let Some(p) = cur.parent() {
    +            cur = p.normalized_storage();
    +        }
    +        if matches!(cur, ItemId::Web(_)) {
    +            hosts.insert(cur);
    +        }
    +    };
    +
    +    for it in &content.items {
    +        consider(it.clone());
    +    }
    +    for parent in content.item_children.keys() {
    +        consider(parent.clone());
    +    }
    +    for set in content.item_children.values() {
    +        for ch in set {
    +            consider(ch.clone());
    +        }
    +    }
    +
    +    let mut out: Vec = hosts.into_iter().collect();
    +    out.sort();
    +    out
    +}
    +
     pub fn is_pair_voted_in_group(group: &GroupState, a: &ItemId, b: &ItemId) -> bool {
         let Some(&a_idx) = group.item_to_idx.get(a) else {
             return false;
    @@ -305,4 +344,29 @@ mod tests {
             assert!(next.0 == c || next.1 == c);
             assert_ne!(canonical_pair(&next.0, &next.1), canonical_pair(&a, &b));
         }
    +
    +    #[test]
    +    fn external_root_hosts_include_ghost_chain_hosts() {
    +        use crate::reducer::ContentState;
    +        let gh = ItemId::parse("https://github.com").unwrap();
    +        let org = ItemId::parse("https://github.com/org").unwrap();
    +        let repo = ItemId::parse("https://github.com/org/rep").unwrap();
    +        let mut item_children: HashMap> = HashMap::new();
    +        item_children.entry(gh.clone()).or_default().insert(org.clone());
    +        item_children.entry(org.clone()).or_default().insert(repo.clone());
    +        let mut items = HashSet::new();
    +        items.insert(repo.clone());
    +        let content = ContentState {
    +            ranking_group: crate::reducer::GroupState::new(),
    +            items,
    +            item_bodies: HashMap::new(),
    +            item_children,
    +            item_votes: HashMap::new(),
    +            item_snippets: HashMap::new(),
    +            item_threads: HashMap::new(),
    +            rank_history: HashMap::new(),
    +        };
    +        let roots = external_root_host_items(&content);
    +        assert_eq!(roots, vec![gh]);
    +    }
     }
    diff --git a/server/src/state.rs b/server/src/state.rs
    index 48298e2e66456268d23a6462536eb32bfeb5f29b..648ab5304764a329fcabbbbcd3782b94e3e005a8 100644
    --- a/server/src/state.rs
    +++ b/server/src/state.rs
    @@ -4,7 +4,7 @@ use std::sync::Arc;
     use tokio::sync::{broadcast, mpsc, RwLock};
     
     use crate::{
    -    event_log::EventLog, events::ThreadCapability, external_resolver::GitHubResolver,
    +    event_log::EventLog, events::ThreadCapability, resolvers::GitHubResolver,
         reducer::ReducerState, write_cmd::WriteCmd,
     };
     
    diff --git a/server/static/theme_default.css b/server/static/theme_default.css
    index 184e11a590e7019773f7f0abfa41e79161556c71..7ea5f502f9b0b6341ce56d60ae883479070760d6 100644
    --- a/server/static/theme_default.css
    +++ b/server/static/theme_default.css
    @@ -1023,6 +1023,23 @@ body.view-vote-compare .vote-compare-shell > h2 {
       line-height: 1.35;
       padding: 8px 10px;
     }
    +.vote-compare-item-body .item-body-rich {
    +  min-width: 0;
    +  text-align: start;
    +}
    +.vote-compare-right .vote-compare-item-body .item-body-rich {
    +  display: flex;
    +  flex-direction: column;
    +  align-items: flex-end;
    +}
    +.vote-compare-item-body .item-body-rich article.github-import-card {
    +  box-sizing: border-box;
    +  width: 100%;
    +  max-width: min(100%, 420px);
    +}
    +.vote-compare-right .vote-compare-item-body .item-body-rich article.github-import-card {
    +  margin-left: auto;
    +}
     .vote-compare-item-body-empty {
       font-size: 12px;
       margin: 8px 0 0;
    @@ -1675,3 +1692,47 @@ body.view-ontology-light .rank-history-cause {
     body.view-ontology-light .rank-history-vote {
       margin-top: 6px;
     }
    +
    +/* GitHub resolver import cards (rich bodies on -/ garden + vote compare) */
    +article.github-import-card {
    +  border: 1px solid var(--lo);
    +  background: var(--g2);
    +  border-radius: 6px;
    +  padding: 12px 14px;
    +  margin: 8px 0;
    +  max-width: 100%;
    +}
    +.github-import-card__hdr {
    +  margin-bottom: 6px;
    +}
    +.github-import-card__badge {
    +  display: block;
    +  font-size: 0.78em;
    +  color: var(--muted);
    +  margin-bottom: 4px;
    +}
    +.github-import-card__title {
    +  margin: 0;
    +  font-size: 1.05em;
    +  font-weight: 600;
    +}
    +ul.github-import-card__meta {
    +  margin: 8px 0 0 1.1em;
    +  padding: 0;
    +  font-size: 0.9em;
    +}
    +.github-import-card__meta li {
    +  margin: 2px 0;
    +}
    +.github-import-card__excerpt {
    +  margin-top: 10px;
    +  font-size: 0.92em;
    +  white-space: pre-wrap;
    +}
    +.github-import-card__excerpt p {
    +  margin: 6px 0;
    +}
    +.github-import-card__link {
    +  margin-top: 12px;
    +  font-size: 0.95em;
    +}
    diff --git a/server/static/theme_retro.css b/server/static/theme_retro.css
    index 6747f59eb1ec5c335029fe92d4e5c55b3125a210..d366be6fc8e8fcbc8122b8954b1e356ee36e6bc9 100644
    --- a/server/static/theme_retro.css
    +++ b/server/static/theme_retro.css
    @@ -278,3 +278,20 @@ body.view-ontology .vote-compare-item-body pre {
       border: 1px solid #ccc;
       padding: 0.5rem 0.65rem;
     }
    +body.view-ontology .vote-compare-item-body .item-body-rich {
    +  min-width: 0;
    +  text-align: start;
    +}
    +body.view-ontology .vote-compare-right .vote-compare-item-body .item-body-rich {
    +  display: flex;
    +  flex-direction: column;
    +  align-items: flex-end;
    +}
    +body.view-ontology .vote-compare-item-body .item-body-rich article.github-import-card {
    +  box-sizing: border-box;
    +  width: 100%;
    +  max-width: min(100%, 420px);
    +}
    +body.view-ontology .vote-compare-right .vote-compare-item-body .item-body-rich article.github-import-card {
    +  margin-left: auto;
    +}
    diff --git a/server/static/theme_retro_craft.css b/server/static/theme_retro_craft.css
    index 55d984a6dd70ebeadeca7baef86b844955f1d78c..d5bc384437f05f001924630947457d416772e950 100644
    --- a/server/static/theme_retro_craft.css
    +++ b/server/static/theme_retro_craft.css
    @@ -907,6 +907,23 @@ body.view-ontology .vote-compare-item-body pre {
       line-height: 1.35;
       padding: 0.55rem 0.65rem;
     }
    +body.view-ontology .vote-compare-item-body .item-body-rich {
    +  min-width: 0;
    +  text-align: start;
    +}
    +body.view-ontology .vote-compare-right .vote-compare-item-body .item-body-rich {
    +  display: flex;
    +  flex-direction: column;
    +  align-items: flex-end;
    +}
    +body.view-ontology .vote-compare-item-body .item-body-rich article.github-import-card {
    +  box-sizing: border-box;
    +  width: 100%;
    +  max-width: min(100%, 420px);
    +}
    +body.view-ontology .vote-compare-right .vote-compare-item-body .item-body-rich article.github-import-card {
    +  margin-left: auto;
    +}
     body.view-ontology .vote-compare-item-body-empty {
       font-size: 0.78rem;
       margin: 0.45rem 0 0;
    diff --git a/server/tests/integration.rs b/server/tests/integration.rs
    index fb0b9335440181d4d50104d37926b0b2eeeb602a..d979000292b6a39db7c7b54f2b804adb9cd39369 100644
    --- a/server/tests/integration.rs
    +++ b/server/tests/integration.rs
    @@ -3,7 +3,7 @@ use sha2::{Digest, Sha256};
     use slug_types::{room_route_segment, ItemId};
     use slugsocial_server::{
         event_log::EventLog,
    -    events::{Event, TokenIssued, UserRegistered},
    +    events::{Event, Ingest, TokenIssued, UserRegistered},
         middleware::canonical_view_url,
         spawn_writer_actor_for_test,
         state::{AppConfig, AppState},
    @@ -1614,6 +1614,71 @@ async fn test_view_counts_increment_and_display() {
         );
     }
     
    +#[tokio::test]
    +async fn test_vote_compare_renders_github_import_cards() {
    +    let (addr, _tmp, _log, state, _handle) = create_test_server_with_state().await;
    +    let client = reqwest::Client::new();
    +
    +    let raw = "@00000000-0000-0000-0000-000000000000:test:local/test\n\
    +https://github.com/ghvotehi/a/issues/9 {\n\
    +```slug-github-card\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\
    +https://github.com/ghvotehi/a/issues/10 {\n\
    +```slug-github-card\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";
    +
    +    {
    +        let mut w = state.reduced.write().await;
    +        w.apply_event(Event::Ingest(Ingest {
    +            ts: 10,
    +            id: "ing-vote-github-cards".to_string(),
    +            raw: raw.to_string(),
    +            principal: "testuser".to_string(),
    +            delegate: Some(
    +                "00000000-0000-0000-0000-000000000000:test:local/test".to_string(),
    +            ),
    +            room_id: "public".to_string(),
    +            thread_tag: "gh-vote-cards".to_string(),
    +        }));
    +    }
    +
    +    let left = ItemId::parse("https://github.com/ghvotehi/a/issues/9")
    +        .unwrap()
    +        .normalized_storage()
    +        .to_storage_string();
    +    let right = ItemId::parse("https://github.com/ghvotehi/a/issues/10")
    +        .unwrap()
    +        .normalized_storage()
    +        .to_storage_string();
    +    let q = format!(
    +        "/vote/compare?left={}&right={}",
    +        urlencoding::encode(&left),
    +        urlencoding::encode(&right)
    +    );
    +    let resp = client
    +        .get(format!("http://{addr}{q}"))
    +        .send()
    +        .await
    +        .unwrap();
    +    assert!(resp.status().is_success(), "{}", resp.status());
    +    let body = resp.text().await.unwrap();
    +    let n_cards = body.matches("github-import-card").count();
    +    assert!(
    +        n_cards >= 2,
    +        "expected two GitHub import cards on vote compare, count={n_cards}, snippet={}",
    +        body.chars().take(1500).collect::()
    +    );
    +    assert!(body.contains("vote-compare-left"));
    +    assert!(body.contains("vote-compare-right"));
    +    assert!(body.contains("#9 Left corner"));
    +    assert!(body.contains("#10 Right corner"));
    +}
    +
     #[tokio::test]
     async fn test_search_handles_multibyte_unicode() {
         // HTML search pages are offline during the auth-v3 refactor.