{"messages":[{"content":"You are a constitutional council ranking individual git commits for ownership allocation.\n\nCompare these two commits. Decide which contributed more lasting value to the project.\n\nJudge substance, not spectacle:\n- Prefer correct, lasting design and real bugfixes over churn, formatting, renames, or generated noise.\n- Prefer clarity and necessity over sheer line count. A small precise change can beat a large diffuse one.\n- Do not favor a side merely because its patch is longer or noisier.\n- Weight what the change does for the project, not the contributor's name.\n\nReturn ONLY a JSON object: {\"winner\": \"A\" or \"B\", \"ratio\": \"N:M\", \"explanation\": \"...\"}\nThe explanation must cite concrete differences in the patches (1-3 sentences).\n\nSide A — contributor: tommy-mor\nSide A — commit message:\n[80ad7753] refactor: split canonical_path and identity; strict wire identity without @\n\n- Add canonical_path.rs (tag + item URL normalization) and identity.rs\n (parse_username/parse_agent; reject @ in API input).\n- Slim events.rs to event types only; reducer applies no identity rewriting.\n- JSON APIs return stored-form usernames and agent ids; HTML keeps @/@@ for display.\n- Optional delegate on ingest; CLI and tests use naked uuid:rig:model.\n\nMade-with: Cursor\n\nSide A — unified diff (full patch):\ndiff --git a/cli/src/main.rs b/cli/src/main.rs\nindex 5ac8e289f2b7a366b5959d9338d02f9b546f408a..630c5dea1f78c0ec9bc53e6b96234a0dc75bb705 100644\n--- a/cli/src/main.rs\n+++ b/cli/src/main.rs\n@@ -61,8 +61,8 @@ enum Command {\n /// Example: --before 2026-06-01\n #[arg(long, value_name = \"DATE_OR_MS\")]\n before: Option,\n- /// Filter to posts from this actor (UUID prefix match).\n- /// Example: --actor 4d9d6173\n+ /// Filter to posts from this principal username (prefix match, stored form).\n+ /// Example: --actor alice\n #[arg(long, value_name = \"PREFIX\")]\n actor: Option,\n /// Fetch a single post by its ingest ID (from --json output).\n@@ -75,9 +75,8 @@ enum Command {\n ///\n /// SYNTAX:\n ///\n- /// Actor (required, once per document):\n- /// @::\n- /// Example: @7a3b9c2d-1234-5678-90ab-cdef12345678:claudecode:anthropic/claude-sonnet\n+ /// Identity: human comes from the bearer token; optional AI delegate from `--delegate`\n+ /// (`uuid:rig:provider/model`). The document body is DSL only (items, votes, prose) — no `@` lines.\n ///\n /// Thread (required, once per document):\n /// #thread-tag\n@@ -109,7 +108,7 @@ enum Command {\n /// Example: ~/python > ~/rust { Python's simpler syntax reduces learning curve. }\n ///\n /// Prose (optional, anywhere):\n- /// Any line that doesn't start with @, #, or ~ is prose.\n+ /// Any line that doesn't start with # or ~ (or `http`) is prose.\n /// Prose is displayed in thread context but does not affect rankings or items.\n /// Use prose to write blog posts, reasoning, or notes within your ingest.\n ///\n@@ -125,8 +124,7 @@ enum Command {\n /// EXAMPLES:\n ///\n /// # From heredoc (recommended for agents)\n- /// npx slugsocial ingest << 'EOF'\n- /// @7a3b9c2d-1234-5678-90ab-cdef12345678:claudecode:anthropic/claude-sonnet\n+ /// npx slugsocial ingest --delegate '7a3b9c2d-1234-5678-90ab-cdef12345678:claudecode:anthropic/claude-sonnet' << 'EOF'\n /// #languages: Python vs Rust for systems programming\n ///\n /// ~/languages/python { A high-level language with simple syntax and rich ecosystem. }\n@@ -153,14 +151,9 @@ enum Command {\n /// Thread identifier (public tag like \"languages\", without #).\n #[arg(long, env = \"SLUG_THREAD\", default_value = \"public\", value_name = \"THREAD\")]\n thread: String,\n- /// Agent delegate identity (request form), e.g. @@uuid:rig:provider/model\n- #[arg(\n- long,\n- env = \"SLUG_DELEGATE\",\n- default_value = \"@@00000000-0000-0000-0000-000000000000:cli:local/dev\",\n- value_name = \"DELEGATE\"\n- )]\n- delegate: String,\n+ /// Agent delegate `uuid:rig:provider/model`. Omit for human-only ingests.\n+ #[arg(long, env = \"SLUG_DELEGATE\", value_name = \"DELEGATE\")]\n+ delegate: Option,\n /// Output as JSON for agent parsing\n #[arg(long)]\n json: bool,\n@@ -174,14 +167,9 @@ enum Command {\n /// Thread identifier (public tag like \"languages\", without #).\n #[arg(long, env = \"SLUG_THREAD\", default_value = \"public\", value_name = \"THREAD\")]\n thread: String,\n- /// Agent delegate identity (request form), e.g. @@uuid:rig:provider/model\n- #[arg(\n- long,\n- env = \"SLUG_DELEGATE\",\n- default_value = \"@@00000000-0000-0000-0000-000000000000:cli:local/dev\",\n- value_name = \"DELEGATE\"\n- )]\n- delegate: String,\n+ /// Agent delegate `uuid:rig:provider/model`. Omit for human-only ingests.\n+ #[arg(long, env = \"SLUG_DELEGATE\", value_name = \"DELEGATE\")]\n+ delegate: Option,\n /// Output as JSON for agent parsing\n #[arg(long)]\n json: bool,\n@@ -193,10 +181,10 @@ enum Command {\n /// Useful for agents to catch up on activity after a context reset.\n ///\n /// Examples:\n- /// npx slugsocial feed @::\n- /// npx slugsocial feed @:: --since 2026-01-01\n+ /// npx slugsocial feed tommy\n+ /// npx slugsocial feed tommy --since 2026-01-01\n Feed {\n- /// Actor identifier (@uuid:rig:model)\n+ /// Principal username (stored form)\n #[arg(value_name = \"ACTOR\")]\n actor: String,\n /// Override the lower bound. Accepts Unix ms or YYYY-MM-DD.\n@@ -455,7 +443,7 @@ fn print_rank_history_response(resp: &slug_types::RankHistoryResponse) {\n label,\n );\n for v in &e.caused_by {\n- println!(\" {} {} {} {}\", v.a, v.ratio, v.b, v.actor.as_deref().map(|a| format!(\" (@{})\", a)).unwrap_or_default());\n+ println!(\" {} {} {} {}\", v.a, v.ratio, v.b, v.actor.as_deref().map(|a| format!(\" ({})\", a)).unwrap_or_default());\n if !v.body.is_empty() {\n println!(\" {}\", v.body.lines().next().unwrap_or(&v.body).trim());\n }\n@@ -1116,7 +1104,7 @@ async fn main() -> Result<()> {\n IdentityCmd::Start { rig, model, json } => {\n let client = http_client()?;\n let uuid = uuid::Uuid::new_v4().to_string();\n- let delegate = format!(\"@@{}:{}:{}\", uuid, rig, model);\n+ let delegate = format!(\"{uuid}:{rig}:{model}\");\n \n let start: PendingSessionStartResponse = expect_json(\n client\ndiff --git a/server/src/api/auth.rs b/server/src/api/auth.rs\nindex cb0faa29b834931e2c2b2f5c174c875e2e2e9346..995ce4a61d29b024c399c656134f541ecfd880cf 100644\n--- a/server/src/api/auth.rs\n+++ b/server/src/api/auth.rs\n@@ -12,10 +12,8 @@ use tokio::sync::RwLock;\n \n use crate::{\n api::helpers::{api_error, now_ms, sha256_hex},\n- events::{\n- canonicalize_username, validate_agent_format, validate_username,\n- Event, TokenIssued, UserRegistered,\n- },\n+ events::{Event, TokenIssued, UserRegistered},\n+ identity::{parse_agent, parse_username},\n html::{auth_complete_page, auth_signed_in_fragment, choose_username_error_fragment, choose_username_page},\n state::{AppState, PendingSession},\n };\n@@ -77,9 +75,9 @@ fn verify_token(reduced: &crate::reducer::ReducerState, bearer: &str) -> Result<\n Ok(username)\n }\n \n-fn issue_token_for_user(username: &str) -> (String, TokenIssued, String) {\n- // Returns: (bearer, event, canonical_username)\n- let canonical_user = canonicalize_username(username);\n+/// `stored_username` must already be in persisted shape (lowercase slug, no `@`).\n+fn issue_token_for_user(stored_username: &str) -> (String, TokenIssued) {\n+ let username = stored_username.to_string();\n let token_id = {\n let mut id = String::new();\n let alphabet = b\"abcdefghijklmnopqrstuvwxyz0123456789\";\n@@ -103,13 +101,13 @@ fn issue_token_for_user(username: &str) -> (String, TokenIssued, String) {\n let bearer = format!(\"slug_{token_id}_{secret}\");\n let event = TokenIssued {\n ts: now_ms(),\n- username: canonical_user.clone(),\n+ username: username.clone(),\n token_id,\n token_hash,\n salt,\n issued_via: \"oauth\".to_string(),\n };\n- (bearer, event, canonical_user)\n+ (bearer, event)\n }\n \n #[derive(Debug, Deserialize)]\n@@ -207,7 +205,7 @@ pub async fn get_auth_callback(Query(q): Query, State(state):\n s.provider = Some(\"google\".to_string());\n s.provider_id = Some(sub.clone());\n if let Some(username) = existing {\n- let (bearer, token_event, canon_user) = issue_token_for_user(&username);\n+ let (bearer, token_event) = issue_token_for_user(&username);\n // append token event\n let ev = Event::TokenIssued(token_event);\n if let Err(err) = state.event_log.append(&ev).await {\n@@ -217,7 +215,7 @@ pub async fn get_auth_callback(Query(q): Query, State(state):\n let mut reduced = reduced_arc.write().await;\n reduced.apply_event(ev);\n }\n- s.complete = Some((canon_user, bearer));\n+ s.complete = Some((username, bearer));\n return Redirect::temporary(&format!(\"{public_url}/auth/complete\")).into_response();\n }\n }\n@@ -251,9 +249,10 @@ pub async fn post_choose_username(\n State(state): State,\n Form(form): Form,\n ) -> impl IntoResponse {\n- if let Err(msg) = validate_username(&form.username) {\n- return api_error(StatusCode::BAD_REQUEST, \"invalid username\", Some(msg)).into_response();\n- }\n+ let canon_user = match parse_username(&form.username) {\n+ Ok(u) => u,\n+ Err(msg) => return api_error(StatusCode::BAD_REQUEST, \"invalid username\", Some(msg)).into_response(),\n+ };\n \n let sessions = pending_sessions(&state);\n let (provider, provider_id, agent) = {\n@@ -270,7 +269,7 @@ pub async fn post_choose_username(\n (provider, provider_id, s.agent.clone())\n };\n \n- if let Err(msg) = validate_agent_format(&agent) {\n+ if let Err(msg) = parse_agent(&agent) {\n return api_error(StatusCode::BAD_REQUEST, \"invalid agent format\", Some(msg)).into_response();\n }\n \n@@ -280,7 +279,7 @@ pub async fn post_choose_username(\n if reduced.users_by_provider.contains_key(&provider_key) {\n return api_error(StatusCode::CONFLICT, \"provider already registered\", None).into_response();\n }\n- if reduced.users_by_provider.values().any(|u| u == &canonicalize_username(&form.username)) {\n+ if reduced.users_by_provider.values().any(|u| u == &canon_user) {\n drop(reduced);\n return choose_username_error_fragment(&form.session, \"that username is taken — try another\").into_response();\n }\n@@ -288,12 +287,12 @@ pub async fn post_choose_username(\n \n let ur = Event::UserRegistered(UserRegistered {\n ts: now_ms(),\n- username: canonicalize_username(&form.username),\n+ username: canon_user.clone(),\n provider: provider.to_lowercase(),\n provider_id: provider_id.clone(),\n });\n \n- let (bearer, ti, canon_user) = issue_token_for_user(&form.username);\n+ let (bearer, ti) = issue_token_for_user(&canon_user);\n let ti_ev = Event::TokenIssued(ti);\n \n // Persist events.\n@@ -325,15 +324,18 @@ pub async fn post_pending_session(\n State(state): State,\n Json(req): Json,\n ) -> impl IntoResponse {\n- if let Err(msg) = validate_agent_format(&req.agent) {\n- return api_error(StatusCode::BAD_REQUEST, \"invalid agent format\", Some(msg)).into_response();\n- }\n+ let agent_naked = match parse_agent(&req.agent) {\n+ Ok(a) => a,\n+ Err(msg) => {\n+ return api_error(StatusCode::BAD_REQUEST, \"invalid agent format\", Some(msg)).into_response();\n+ }\n+ };\n let session = format!(\"p_{}\", uuid::Uuid::new_v4().simple());\n let public_url = std::env::var(\"SLUG_PUBLIC_URL\").unwrap_or_else(|_| \"http://127.0.0.1:8080\".to_string());\n let login_url = format!(\"{public_url}/auth/login?session={}\", urlencoding::encode(&session));\n let poll_url = format!(\"/api/v0/pending-session/{}\", session);\n let s = PendingSession {\n- agent: req.agent.clone(),\n+ agent: agent_naked,\n created_ts: now_ms(),\n provider: None,\n provider_id: None,\n@@ -359,7 +361,7 @@ pub async fn get_pending_session(\n return api_error(StatusCode::NOT_FOUND, \"unknown session\", None).into_response();\n };\n let (complete, user, token) = match &s.complete {\n- Some((u, t)) => (true, Some(format!(\"@{}\", u)), Some(t.clone())),\n+ Some((u, t)) => (true, Some(u.clone()), Some(t.clone())),\n None => (false, None, None),\n };\n Json(PendingSessionPollResponse {\n@@ -388,7 +390,7 @@ pub async fn get_whoami(State(state): State, headers: HeaderMap) -> im\n };\n let agents_bound = reduced.agent_bindings.values().filter(|u| *u == &username).count();\n Json(WhoamiResponse {\n- user: format!(\"@{}\", username),\n+ user: username,\n agents_bound,\n })\n .into_response()\ndiff --git a/server/src/api/feed.rs b/server/src/api/feed.rs\nindex f665d34aef12f2bd6e71d1fb4a3d0b4d509aa775..983b7397a846bd540b6baf3773dd54c55ade4c45 100644\n--- a/server/src/api/feed.rs\n+++ b/server/src/api/feed.rs\n@@ -1,11 +1,12 @@\n use axum::{\n extract::{Query, State},\n+ http::StatusCode,\n response::IntoResponse,\n Json,\n };\n use serde::Deserialize;\n \n-use crate::{events::canonicalize_username, state::AppState};\n+use crate::{api::helpers::api_error, identity::parse_username, state::AppState};\n \n // ============================================================================\n // Feed -- global reverse-chronological ingest stream since a cutoff\n@@ -32,7 +33,12 @@ pub async fn get_feed(\n \n let reduced_arc = state.reduced.clone();\n let reduced = reduced_arc.read().await;\n- let actor = canonicalize_username(&q.actor);\n+ let actor = match parse_username(&q.actor) {\n+ Ok(u) => u,\n+ Err(msg) => {\n+ return api_error(StatusCode::BAD_REQUEST, \"invalid actor\", Some(msg)).into_response();\n+ }\n+ };\n let since = q.since.or_else(|| reduced.actor_last_post_ts.get(&actor).copied());\n let cutoff = since.unwrap_or(0);\n let limit = q.limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT);\n@@ -65,7 +71,7 @@ pub async fn get_feed(\n .collect();\n \n Json(slug_types::FeedResponse {\n- actor: format!(\"@{}\", actor),\n+ actor,\n since,\n posts,\n total,\ndiff --git a/server/src/api/forum.rs b/server/src/api/forum.rs\nindex cf134e97a3aa9f2cea5efcf5bfa2564b9fc2ea46..ab6f3ec4936979fed9b3a9c47bef609610c751dd 100644\n--- a/server/src/api/forum.rs\n+++ b/server/src/api/forum.rs\n@@ -8,7 +8,8 @@ use serde::Deserialize;\n use slug_types::*;\n \n use crate::{\n- events::canonicalize_tag,\n+ canonical_path::canonicalize_tag,\n+ identity::parse_username,\n state::AppState,\n };\n \n@@ -46,7 +47,7 @@ pub struct ThreadDetailQuery {\n pub since: Option,\n /// Only posts strictly before this Unix ms timestamp.\n pub before: Option,\n- /// Filter to posts whose actor starts with this prefix (UUID prefix or full actor string).\n+ /// Filter to posts whose principal username starts with this prefix (stored form, no `@`).\n pub actor: Option,\n /// Return the single post with this ingest ID.\n pub post_id: Option,\n@@ -56,6 +57,13 @@ pub struct ThreadDetailQuery {\n pub async fn get_thread(State(state): State, Query(q): Query) -> impl IntoResponse {\n let reduced_arc = state.reduced.clone();\n let tag = canonicalize_tag(&q.tag);\n+ let actor_prefix = match q.actor.as_deref().map(str::trim) {\n+ None | Some(\"\") => String::new(),\n+ Some(s) => match parse_username(s) {\n+ Ok(u) => u,\n+ Err(msg) => return api_error(StatusCode::BAD_REQUEST, \"invalid actor filter\", Some(msg)).into_response(),\n+ },\n+ };\n let reduced = reduced_arc.read().await;\n \n // Single post lookup by ingest ID -- return full body untruncated.\n@@ -72,7 +80,7 @@ pub async fn get_thread(State(state): State, Query(q): Query, Query(q): Query = all_ids\n .into_iter()\n .enumerate()\n@@ -119,7 +126,7 @@ pub async fn get_thread(State(state): State, Query(q): Query = match &req.delegate {\n+ None => None,\n+ Some(s) if s.trim().is_empty() => None,\n+ Some(s) => match parse_agent(s) {\n+ Ok(d) => Some(d),\n+ Err(msg) => {\n+ drop(reduced);\n+ return api_error(StatusCode::BAD_REQUEST, \"invalid delegate format\", Some(msg))\n+ .into_response();\n+ }\n+ },\n+ };\n let thread_id = canonicalize_tag(&req.thread);\n \n let principal = match verify_bearer_principal(&headers, &reduced) {\n@@ -290,36 +296,43 @@ pub async fn post_ingest(\n }\n }\n \n- match reduced.agent_bindings.get(&delegate) {\n- Some(u) if u != &principal => {\n- drop(reduced);\n- return api_error(\n- StatusCode::FORBIDDEN,\n- \"delegate already bound to another user\",\n- None,\n- )\n- .into_response();\n+ if let Some(ref d) = delegate {\n+ match reduced.agent_bindings.get(d) {\n+ Some(u) if u != &principal => {\n+ drop(reduced);\n+ return api_error(\n+ StatusCode::FORBIDDEN,\n+ \"delegate already bound to another user\",\n+ None,\n+ )\n+ .into_response();\n+ }\n+ _ => {}\n }\n- _ => {}\n }\n- let need_agent_bind = reduced.agent_bindings.get(&delegate).is_none();\n+ let need_agent_bind = delegate\n+ .as_ref()\n+ .map(|d| reduced.agent_bindings.get(d).is_none())\n+ .unwrap_or(false);\n drop(reduced);\n \n let mut events_appended: usize = 0;\n \n if need_agent_bind {\n- let ab = Event::AgentBound(AgentBound {\n- ts: now_ms(),\n- agent: delegate.clone(),\n- username: principal.clone(),\n- });\n- if let Err(err) = event_log.append(&ab).await {\n- return api_error(StatusCode::INTERNAL_SERVER_ERROR, format!(\"{err}\"), None);\n- }\n- events_appended += 1;\n- {\n- let mut reduced = reduced_arc.write().await;\n- reduced.apply_event(ab);\n+ if let Some(agent_id) = delegate.clone() {\n+ let ab = Event::AgentBound(AgentBound {\n+ ts: now_ms(),\n+ agent: agent_id,\n+ username: principal.clone(),\n+ });\n+ if let Err(err) = event_log.append(&ab).await {\n+ return api_error(StatusCode::INTERNAL_SERVER_ERROR, format!(\"{err}\"), None);\n+ }\n+ events_appended += 1;\n+ {\n+ let mut reduced = reduced_arc.write().await;\n+ reduced.apply_event(ab);\n+ }\n }\n }\n \n@@ -413,12 +426,18 @@ pub async fn post_check(\n };\n drop(reduced);\n \n- if let Err(msg) = validate_agent_format(&req.delegate) {\n- return api_error(StatusCode::BAD_REQUEST, \"invalid delegate format\", Some(msg)).into_response();\n- }\n- let delegate = canonicalize_agent(&req.delegate);\n+ let delegate: Option = match &req.delegate {\n+ None => None,\n+ Some(s) if s.trim().is_empty() => None,\n+ Some(s) => match parse_agent(s) {\n+ Ok(d) => Some(d),\n+ Err(msg) => {\n+ return api_error(StatusCode::BAD_REQUEST, \"invalid delegate format\", Some(msg)).into_response();\n+ }\n+ },\n+ };\n let thread_id = canonicalize_tag(&req.thread);\n- let principal = canonicalize_username(\"placeholder\");\n+ let principal = \"placeholder\".to_string();\n \n let event = Event::Ingest(Ingest {\n ts: v.ts,\ndiff --git a/server/src/api/mod.rs b/server/src/api/mod.rs\nindex f1d5c139b875c268cc46c3085c332d8de31b092e..f42e907775645166c60aeae2d98c5855223a71be 100644\n--- a/server/src/api/mod.rs\n+++ b/server/src/api/mod.rs\n@@ -65,7 +65,7 @@ mod tests {\n id: format!(\"test-{ts}\"),\n raw: raw.to_string(),\n principal: \"test\".to_string(),\n- delegate: \"@00000000-0000-0000-0000-000000000000:test:local/test\".to_string(),\n+ delegate: Some(\"00000000-0000-0000-0000-000000000000:test:local/test\".to_string()),\n thread_id: \"t\".to_string(),\n }));\n }\ndiff --git a/server/src/api/rank.rs b/server/src/api/rank.rs\nindex 059095bb512096da5e9699ff9c4b92cb7de7fa1c..f2d348280ec4d70a32044601964cb5dc9382d9d7 100644\n--- a/server/src/api/rank.rs\n+++ b/server/src/api/rank.rs\n@@ -226,7 +226,7 @@ pub async fn get_rank_history(\n let reduced = reduced_arc.read().await;\n let content = reduced.public();\n \n- let item_str = crate::events::canonicalize_item(&q.item);\n+ let item_str = crate::canonical_path::canonicalize_item(&q.item);\n let item = CanonicalItemUrl(item_str.clone());\n \n let entries = content.rank_history.get(&item).cloned().unwrap_or_default();\n@@ -238,15 +238,15 @@ pub async fn get_rank_history(\n .map(|doc| {\n doc.statements.into_iter().filter_map(|s| {\n if let crate::dsl::Stmt::Vote { item1, item2, ratio_left, ratio_right, explanation } = s {\n- let a = crate::events::canonicalize_item(&item1);\n- let b = crate::events::canonicalize_item(&item2);\n+ let a = crate::canonical_path::canonicalize_item(&item1);\n+ let b = crate::canonical_path::canonicalize_item(&item2);\n if a == item_str || b == item_str {\n Some(VoteRow {\n ts: e.ts,\n a: item_path_for_api(&a),\n b: item_path_for_api(&b),\n ratio: format!(\"{}:{}\", ratio_left, ratio_right),\n- actor: reduced.ingests_by_id.get(&e.post_id).map(|ing| format!(\"@{}\", ing.principal)),\n+ actor: reduced.ingests_by_id.get(&e.post_id).map(|ing| ing.principal.clone()),\n body: explanation,\n thread: Some(format!(\"#{}\", e.thread)),\n })\ndiff --git a/server/src/api/search.rs b/server/src/api/search.rs\nindex 8028c3117b9b22460fb9677ca969741f6849d2d0..87621e6e4210a28c7802bb941200788f28518940 100644\n--- a/server/src/api/search.rs\n+++ b/server/src/api/search.rs\n@@ -119,7 +119,7 @@ pub async fn get_search(\n .unwrap_or_else(|| \"#unknown\".to_string());\n scored_posts.push((score, ingest.ts, slug_types::SearchPostHit {\n thread,\n- actor: format!(\"@{}\", ingest.principal),\n+ actor: ingest.principal.clone(),\n snippet: snippet_around(&ingest.raw, &words, 160),\n ts: ingest.ts,\n }));\ndiff --git a/server/src/api/thread.rs b/server/src/api/thread.rs\nindex 576b0b5be2767b0c6cba5e0701e4ffc9f215029d..be6ef446e316fef352a7eef5b35b40583dca4442 100644\n--- a/server/src/api/thread.rs\n+++ b/server/src/api/thread.rs\n@@ -8,9 +8,8 @@ use serde::{Deserialize, Serialize};\n \n use crate::{\n api::helpers::{api_error, now_ms},\n- events::{\n- canonicalize_username, Event, GrantAdded, ThreadCapability, ThreadCreated, ThreadVisibility,\n- },\n+ events::{Event, GrantAdded, ThreadCapability, ThreadCreated, ThreadVisibility},\n+ identity::parse_username,\n state::AppState,\n };\n use super::auth::verify_bearer_principal;\n@@ -150,10 +149,10 @@ pub async fn post_thread_grants(\n return api_error(StatusCode::FORBIDDEN, \"requires Manage capability\", None).into_response();\n }\n \n- let target = canonicalize_username(&req.username);\n- if target.is_empty() {\n- return api_error(StatusCode::BAD_REQUEST, \"invalid username\", None).into_response();\n- }\n+ let target = match parse_username(&req.username) {\n+ Ok(u) => u,\n+ Err(msg) => return api_error(StatusCode::BAD_REQUEST, \"invalid username\", Some(msg)).into_response(),\n+ };\n if !reduced.users_by_provider.values().any(|u| u == &target) {\n return api_error(StatusCode::NOT_FOUND, format!(\"user @{target} not found\"), None).into_response();\n }\ndiff --git a/server/src/canonical_path.rs b/server/src/canonical_path.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..5c0febe883d8b3978a25896ed0d71df8509a8717\n--- /dev/null\n+++ b/server/src/canonical_path.rs\n@@ -0,0 +1,92 @@\n+//! Normalization for thread tags and ontology item URLs (DSL ↔ stored canonical form).\n+//! Not event types — see `events` and `path_types`.\n+\n+/// Thread / public tag: stored without leading `#`, lowercase.\n+pub fn canonicalize_tag(input: &str) -> String {\n+ input.trim().trim_start_matches('#').to_lowercase()\n+}\n+\n+/// Ontology item reference → canonical absolute URL on the slug host.\n+pub fn canonicalize_item(input: &str) -> String {\n+ let s = input.trim();\n+ if s.is_empty() {\n+ return String::new();\n+ }\n+\n+ if let Some(rest) = s.strip_prefix(\"https://\") {\n+ let (host, tail) = rest.split_once('/').map_or((rest, \"\"), |(h, t)| (h, t));\n+ let host = host.trim().to_lowercase();\n+ if tail.is_empty() {\n+ return format!(\"https://{}\", host);\n+ } else {\n+ return format!(\"https://{}/{}\", host, tail);\n+ }\n+ }\n+ if let Some(rest) = s.strip_prefix(\"http://\") {\n+ let (host, tail) = rest.split_once('/').map_or((rest, \"\"), |(h, t)| (h, t));\n+ let host = host.trim().to_lowercase();\n+ if tail.is_empty() {\n+ return format!(\"http://{}\", host);\n+ } else {\n+ return format!(\"http://{}/{}\", host, tail);\n+ }\n+ }\n+\n+ let is_tilde = s.starts_with(\"~/\");\n+ let rest = s.strip_prefix(\"~/\").or_else(|| s.strip_prefix(\"/\")).unwrap_or(s);\n+\n+ let tail = rest\n+ .split('/')\n+ .filter_map(|seg| {\n+ let t = seg.trim();\n+ if t.is_empty() {\n+ None\n+ } else {\n+ Some(t.to_lowercase())\n+ }\n+ })\n+ .collect::>()\n+ .join(\"/\");\n+\n+ if is_tilde {\n+ format!(\"https://slug.social/~/{}\", tail)\n+ } else if tail.is_empty() {\n+ \"https://slug.social\".to_string()\n+ } else {\n+ format!(\"https://slug.social/{}\", tail)\n+ }\n+}\n+\n+pub fn item_path_segments(input: &str) -> Vec {\n+ let canonical = canonicalize_item(input);\n+ if canonical.is_empty() {\n+ return vec![];\n+ }\n+\n+ if let Some(rest) = canonical.strip_prefix(\"https://\") {\n+ let (host, tail) = rest.split_once('/').map_or((rest, \"\"), |(h, t)| (h, t));\n+ let mut out = vec![format!(\"https://{}\", host)];\n+ out.extend(tail.split('/').filter(|s| !s.is_empty()).map(|s| s.to_string()));\n+ return out;\n+ }\n+ if let Some(rest) = canonical.strip_prefix(\"http://\") {\n+ let (host, tail) = rest.split_once('/').map_or((rest, \"\"), |(h, t)| (h, t));\n+ let mut out = vec![format!(\"http://{}\", host)];\n+ out.extend(tail.split('/').filter(|s| !s.is_empty()).map(|s| s.to_string()));\n+ return out;\n+ }\n+\n+ canonical\n+ .split('/')\n+ .filter(|s| !s.is_empty())\n+ .map(|s| s.to_string())\n+ .collect()\n+}\n+\n+pub fn item_parent_path(input: &str) -> Option {\n+ let segs = item_path_segments(input);\n+ if segs.len() <= 1 {\n+ return None;\n+ }\n+ Some(segs[..segs.len() - 1].join(\"/\"))\n+}\ndiff --git a/server/src/events.rs b/server/src/events.rs\nindex 7775e59974a521f5fea9361a600802898d05c6ab..26edac7505ce4e67a042a5511113efba5fea4950 100644\n--- a/server/src/events.rs\n+++ b/server/src/events.rs\n@@ -1,150 +1,5 @@\n use serde::{Deserialize, Serialize};\n \n-/// Canonical identifiers stored without sigils.\n-/// - tags are stored without leading '#'\n-/// - items are stored without leading '/'\n-pub fn canonicalize_tag(input: &str) -> String {\n- input.trim().trim_start_matches('#').to_lowercase()\n-}\n-\n-pub fn canonicalize_item(input: &str) -> String {\n- let s = input.trim();\n- if s.is_empty() {\n- return String::new();\n- }\n-\n- if let Some(rest) = s.strip_prefix(\"https://\") {\n- let (host, tail) = rest.split_once('/').map_or((rest, \"\"), |(h, t)| (h, t));\n- let host = host.trim().to_lowercase();\n- if tail.is_empty() {\n- return format!(\"https://{}\", host);\n- } else {\n- return format!(\"https://{}/{}\", host, tail);\n- }\n- }\n- if let Some(rest) = s.strip_prefix(\"http://\") {\n- let (host, tail) = rest.split_once('/').map_or((rest, \"\"), |(h, t)| (h, t));\n- let host = host.trim().to_lowercase();\n- if tail.is_empty() {\n- return format!(\"http://{}\", host);\n- } else {\n- return format!(\"http://{}/{}\", host, tail);\n- }\n- }\n-\n- let is_tilde = s.starts_with(\"~/\");\n- let rest = s.strip_prefix(\"~/\").or_else(|| s.strip_prefix(\"/\")).unwrap_or(s);\n-\n- let tail = rest\n- .split('/')\n- .filter_map(|seg| {\n- let t = seg.trim();\n- if t.is_empty() {\n- None\n- } else {\n- Some(t.to_lowercase())\n- }\n- })\n- .collect::>()\n- .join(\"/\");\n-\n- if is_tilde {\n- format!(\"https://slug.social/~/{}\", tail)\n- } else if tail.is_empty() {\n- \"https://slug.social\".to_string()\n- } else {\n- format!(\"https://slug.social/{}\", tail)\n- }\n-}\n-\n-pub fn item_path_segments(input: &str) -> Vec {\n- let canonical = canonicalize_item(input);\n- if canonical.is_empty() {\n- return vec![];\n- }\n-\n- if let Some(rest) = canonical.strip_prefix(\"https://\") {\n- let (host, tail) = rest.split_once('/').map_or((rest, \"\"), |(h, t)| (h, t));\n- let mut out = vec![format!(\"https://{}\", host)];\n- out.extend(tail.split('/').filter(|s| !s.is_empty()).map(|s| s.to_string()));\n- return out;\n- }\n- if let Some(rest) = canonical.strip_prefix(\"http://\") {\n- let (host, tail) = rest.split_once('/').map_or((rest, \"\"), |(h, t)| (h, t));\n- let mut out = vec![format!(\"http://{}\", host)];\n- out.extend(tail.split('/').filter(|s| !s.is_empty()).map(|s| s.to_string()));\n- return out;\n- }\n-\n- // Should be unreachable since all canonical items are now URLs\n- canonical\n- .split('/')\n- .filter(|s| !s.is_empty())\n- .map(|s| s.to_string())\n- .collect()\n-}\n-\n-pub fn item_parent_path(input: &str) -> Option {\n- let segs = item_path_segments(input);\n- if segs.len() <= 1 {\n- return None;\n- }\n- Some(segs[..segs.len() - 1].join(\"/\"))\n-}\n-\n-/// Canonical username stored without leading '@'.\n-pub fn canonicalize_username(input: &str) -> String {\n- input.trim().trim_start_matches('@').to_lowercase()\n-}\n-\n-/// Validate username: lowercase alphanumeric + '-' '_' only; length 1-32.\n-pub fn validate_username(username: &str) -> Result<(), String> {\n- let u = canonicalize_username(username);\n- if u.is_empty() || u.len() > 32 {\n- return Err(\"username must be 1-32 characters\".to_string());\n- }\n- if !u\n- .chars()\n- .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')\n- {\n- return Err(\"username must be lowercase alphanumeric with '-' or '_' only\".to_string());\n- }\n- Ok(())\n-}\n-\n-/// Canonical agent identity stored with single leading '@'.\n-///\n-/// Request/display form is `@@uuid:rig:provider/model` but we store `@uuid:rig:provider/model`.\n-pub fn canonicalize_agent(input: &str) -> String {\n- let s = input.trim();\n- let s = s.strip_prefix(\"@@\").or_else(|| s.strip_prefix('@')).unwrap_or(s);\n- format!(\"@{}\", s.to_lowercase())\n-}\n-\n-/// Validate agent format: @@::\n-pub fn validate_agent_format(agent: &str) -> Result<(), String> {\n- let a = agent.trim();\n- if !a.starts_with(\"@@\") && !a.starts_with('@') {\n- return Err(\"agent must start with @@\".to_string());\n- }\n- let a = a.strip_prefix(\"@@\").or_else(|| a.strip_prefix('@')).unwrap_or(a);\n- let parts: Vec<&str> = a.split(':').collect();\n- if parts.len() != 3 {\n- return Err(\"agent must be @@::\".to_string());\n- }\n- let (uuid_part, rig_part, model_part) = (parts[0], parts[1], parts[2]);\n- if uuid::Uuid::parse_str(uuid_part).is_err() {\n- return Err(\"agent uuid must be a valid UUID v4\".to_string());\n- }\n- if rig_part.trim().is_empty() {\n- return Err(\"agent rig must be non-empty\".to_string());\n- }\n- if !model_part.contains('/') {\n- return Err(\"agent model must be \".to_string());\n- }\n- Ok(())\n-}\n-\n #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]\n #[serde(rename_all = \"snake_case\")]\n pub enum ThreadVisibility {\n@@ -236,10 +91,11 @@ pub struct Ingest {\n pub id: String,\n /// Raw DSL+prose body only (no identity/routing metadata).\n pub raw: String,\n- /// Human principal username (no leading '@').\n+ /// Human principal username (wire and storage: no `@`).\n pub principal: String,\n- /// Delegate agent identity (canonical stored with single leading '@').\n- pub delegate: String,\n+ /// AI delegate id `uuid:rig:model` (wire and storage: no `@`). Omitted when absent.\n+ #[serde(default, skip_serializing_if = \"Option::is_none\")]\n+ pub delegate: Option,\n /// Thread identifier: public tag (e.g. \"languages\") or private id/slug (e.g. \"a7f2k9x/project-review\").\n pub thread_id: String,\n }\n@@ -247,5 +103,3 @@ pub struct Ingest {\n fn generate_id() -> String {\n uuid::Uuid::new_v4().to_string()\n }\n-\n-\ndiff --git a/server/src/html/editor.rs b/server/src/html/editor.rs\nindex 1d2c4be7eef4cc437cacddd0949307895f3ef018..4f206a0a895b47592df7669cd8d2fb4d83286fe7 100644\n--- a/server/src/html/editor.rs\n+++ b/server/src/html/editor.rs\n@@ -33,7 +33,7 @@ pub async fn editor_page() -> impl IntoResponse {\n p class=\"muted\" { \"write DSL, see what happens. nothing is saved.\" }\n div class=\"editor-container\" {\n textarea id=\"editor-input\" rows=\"12\" cols=\"80\"\n- placeholder=\"@your-uuid:rig:provider/model\\n#your-thread\\n\\n~/path/item-a { description }\\n~/path/item-b { description }\\n\\n~/path/item-a 3:1 ~/path/item-b { reasoning }\"\n+ placeholder=\"your-uuid:rig:provider/model\\n#your-thread\\n\\n~/path/item-a { description }\\n~/path/item-b { description }\\n\\n~/path/item-a 3:1 ~/path/item-b { reasoning }\"\n autocomplete=\"off\" autofocus {}\n div id=\"editor-status\" class=\"muted\" { \"type to check…\" }\n div id=\"editor-results\" {}\n@@ -110,7 +110,7 @@ pub async fn editor_check(\n id: uuid::Uuid::new_v4().to_string(),\n raw: form.text.clone(),\n principal: String::new(),\n- delegate: String::new(),\n+ delegate: None,\n thread_id: String::new(),\n });\n let mut simulated = { reduced_arc.read().await.clone() };\ndiff --git a/server/src/html/forum.rs b/server/src/html/forum.rs\nindex d40cc6398aaf3b2348d91498b5b3a80ed593e55c..a4e17ddf0064b08dfa221c964ccaa0eb99948b5b 100644\n--- a/server/src/html/forum.rs\n+++ b/server/src/html/forum.rs\n@@ -7,14 +7,14 @@ use serde::Deserialize;\n use maud::{html, Markup};\n \n use crate::{\n- events::canonicalize_tag,\n+ canonical_path::canonicalize_tag,\n reducer::ReducerState,\n state::AppState,\n timeago,\n };\n \n use super::{\n- actor_label, bc_threads, cli_panel, layout, now_ms,\n+ authorship_address, bc_threads, cli_panel, layout, now_ms,\n recency_class, render_linkified_with_embeds,\n };\n \n@@ -260,7 +260,7 @@ pub async fn thread_post_view(\n @let ago = timeago::timeago(now, ing.ts);\n div class=\"ingest-entry\" data-ingest-id=(ing.id) {\n div class=\"ingest-meta muted\" title=(hover) {\n- span class=\"address\" { \"@\" (actor_label(&ing.delegate)) }\n+ span class=\"address\" { (authorship_address(&ing.principal, &ing.delegate)) }\n \" · \"\n (ago)\n }\ndiff --git a/server/src/html/garden.rs b/server/src/html/garden.rs\nindex bddd90aa6eb288c0c97bb08f472e2934fd2fe67a..dcd7f0d4a2d7b602026b643c564d212cb084ff9f 100644\n--- a/server/src/html/garden.rs\n+++ b/server/src/html/garden.rs\n@@ -5,7 +5,7 @@ use axum::{\n use maud::html;\n \n use crate::{\n- events::canonicalize_item,\n+ canonical_path::canonicalize_item,\n path_types::CanonicalItemUrl,\n ranking::{connected_components_from_voted_pairs, ranked_items_subset},\n scope_rank::{build_children_rankings, ChildrenRankings},\n@@ -14,7 +14,7 @@ use crate::{\n };\n \n use super::{\n- actor_label, bc_path, cli_panel, layout, now_ms, ratio_pct, render_linkified_with_embeds,\n+ authorship_address, bc_path, cli_panel, layout, now_ms, ratio_pct, render_linkified_with_embeds,\n breadcrumb_path::OntologyPath,\n };\n \n@@ -204,8 +204,8 @@ fn build_rank_history(\n .map(|doc| {\n doc.statements.into_iter().filter_map(|s| {\n if let crate::dsl::Stmt::Vote { item1, item2, ratio_left, ratio_right, explanation } = s {\n- let a_str = crate::events::canonicalize_item(&item1);\n- let b_str = crate::events::canonicalize_item(&item2);\n+ let a_str = crate::canonical_path::canonicalize_item(&item1);\n+ let b_str = crate::canonical_path::canonicalize_item(&item2);\n if a_str == item || b_str == item {\n Some(crate::reducer::VoteData {\n ts: e.ts,\n@@ -216,9 +216,7 @@ fn build_rank_history(\n principal: reduced.ingests_by_id.get(&e.post_id)\n .map(|ing| ing.principal.clone())\n .unwrap_or_default(),\n- delegate: reduced.ingests_by_id.get(&e.post_id)\n- .map(|ing| ing.delegate.clone())\n- .unwrap_or_default(),\n+ delegate: reduced.ingests_by_id.get(&e.post_id).and_then(|ing| ing.delegate.clone()),\n thread_id: e.thread.clone(),\n })\n } else { None }\n@@ -331,7 +329,7 @@ async fn render_scope_view(state: AppState, path: OntologyPath) -> axum::respons\n @let right_class = if v.b.as_str() == model.item { \"ratio-right current\" } else { \"ratio-right\" };\n div class=\"ont-vote-entry\" {\n div class=\"ont-vote-meta\" title=(hover) {\n- span class=\"address\" { \"@\" (actor_label(&v.delegate)) }\n+ span class=\"address\" { (authorship_address(&v.principal, &v.delegate)) }\n \" · \"\n (ago)\n }\n@@ -482,7 +480,7 @@ mod tests {\n id: format!(\"ing-{ts}\"),\n raw: raw.to_string(),\n principal: \"testuser\".to_string(),\n- delegate: \"@00000000-0000-0000-0000-000000000000:test:local/test\".to_string(),\n+ delegate: Some(\"00000000-0000-0000-0000-000000000000:test:local/test\".to_string()),\n thread_id: String::new(),\n }));\n }\ndiff --git a/server/src/html/mod.rs b/server/src/html/mod.rs\nindex 8b48a25cce79f0eefc7e29849e1a667cae4c7986..82c5993fabfeaf2ea8b9034bccaef37924100264 100644\n--- a/server/src/html/mod.rs\n+++ b/server/src/html/mod.rs\n@@ -238,9 +238,9 @@ pub(super) fn bc_threads(thread_tag: Option<&str>) -> Markup {\n }\n }\n \n-/// Input is canonicalized without leading '@' (usually uuid:rig:provider/model).\n-pub(super) fn actor_label(actor: &str) -> String {\n- let a = actor.trim_start_matches('@').trim();\n+/// Short display label for a stored agent id (`uuid:rig:model`, no `@`).\n+pub(super) fn actor_label(agent_naked: &str) -> String {\n+ let a = agent_naked.trim();\n let parts: Vec<&str> = a.split(':').collect();\n if parts.len() >= 3 {\n let rig = parts[1].trim();\n@@ -258,6 +258,13 @@ pub(super) fn actor_label(actor: &str) -> String {\n a.to_string()\n }\n \n+/// HTML attribution only: human `@name`, or agent `@@uuid8:rig:model` when a delegate is present.\n+pub(super) fn authorship_address(principal: &str, delegate: &Option) -> String {\n+ match delegate {\n+ Some(d) => format!(\"@@{}\", actor_label(d)),\n+ None => format!(\"@{}\", principal),\n+ }\n+}\n \n /// Escape HTML special chars for safe injection.\n fn escape_html(s: &str) -> String {\ndiff --git a/server/src/html/search.rs b/server/src/html/search.rs\nindex f56f31546b4870d41e594d0e3ac2a4b50ba831b8..df5cb0a59ff72956f4bc94e53b86ab8337452817 100644\n--- a/server/src/html/search.rs\n+++ b/server/src/html/search.rs\n@@ -11,7 +11,7 @@ use crate::{\n timeago,\n };\n \n-use super::{actor_label, bc_segment, cli_panel, layout, now_ms};\n+use super::{authorship_address, bc_segment, cli_panel, layout, now_ms};\n \n /// Escape HTML special chars for safe injection.\n fn escape_html(s: &str) -> String {\n@@ -44,7 +44,8 @@ struct ThreadRow {\n \n struct PostRow {\n thread: String,\n- actor: String,\n+ /// Pre-formatted attribution string for display (includes `@` / `@@` from `authorship_address`).\n+ actor_display: String,\n text: String,\n ts: i64,\n }\n@@ -151,7 +152,7 @@ fn search(state: &ReducerState, q: &str, limit: usize) -> SearchResults {\n .unwrap_or_else(|| \"unknown\".to_string());\n scored_posts.push((score, PostRow {\n thread,\n- actor: ingest.principal.clone(),\n+ actor_display: authorship_address(&ingest.principal, &ingest.delegate),\n text: ingest.raw.clone(),\n ts: ingest.ts,\n }));\n@@ -321,7 +322,7 @@ fn render_search_results(results: &SearchResults, query: &str) -> Markup {\n li {\n div class=\"search-post-meta muted\" {\n a href=(format!(\"/t/{}\", r.thread)) { \"#\" (r.thread) }\n- \" · \" (actor_label(&r.actor))\n+ \" · \" (r.actor_display)\n \" · \" (timeago::timeago(now, r.ts))\n }\n div class=\"search-snippet\" {\ndiff --git a/server/src/html/tree.rs b/server/src/html/tree.rs\nindex 568a08edbb548291ab6f03b46c79cdcb4b432468..339f69af3b3279918a97b1dced62e4e3e0b528e3 100644\n--- a/server/src/html/tree.rs\n+++ b/server/src/html/tree.rs\n@@ -13,7 +13,7 @@ use serde::{Deserialize, Serialize};\n use std::collections::BTreeSet;\n \n use crate::{\n- events::canonicalize_item,\n+ canonical_path::canonicalize_item,\n path_types::{CanonicalItemUrl, RelativePath},\n scope_rank::ChildrenRankings,\n state::AppState,\n@@ -702,7 +702,8 @@ pub async fn tree_select(\n mod tests {\n use super::*;\n \n- use crate::events::{canonicalize_item, Event, Ingest};\n+ use crate::canonical_path::canonicalize_item;\n+ use crate::events::{Event, Ingest};\n use crate::reducer::ReducerState;\n \n fn ingest(raw: &str) -> Event {\n@@ -711,7 +712,7 @@ mod tests {\n id: \"test-ingest\".to_string(),\n raw: raw.to_string(),\n principal: \"tester\".to_string(),\n- delegate: String::new(),\n+ delegate: None,\n thread_id: String::new(),\n })\n }\n@@ -789,9 +790,9 @@ mod tests {\n fn reducer_parent_key_for_tilde_items_is_without_trailing_slash() {\n // This is the reducer invariant that the tree view must match.\n let item = canonicalize_item(\"~/alphabet/a\");\n- assert_eq!(crate::events::item_parent_path(&item).unwrap(), \"https://slug.social/~/alphabet\");\n+ assert_eq!(crate::canonical_path::item_parent_path(&item).unwrap(), \"https://slug.social/~/alphabet\");\n let item2 = canonicalize_item(\"~/a\");\n- assert_eq!(crate::events::item_parent_path(&item2).unwrap(), \"https://slug.social/~\");\n+ assert_eq!(crate::canonical_path::item_parent_path(&item2).unwrap(), \"https://slug.social/~\");\n }\n \n #[test]\ndiff --git a/server/src/identity.rs b/server/src/identity.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..ad654ae813f8f6fe6323746e2544250687d3d47f\n--- /dev/null\n+++ b/server/src/identity.rs\n@@ -0,0 +1,66 @@\n+//! Usernames and agent delegate ids. Wire JSON and query params use **stored form only** (no `@` / `@@`).\n+//! The HTTP layer validates here; the reducer does not rewrite identity. For humans, `@name` / `@@agent`\n+//! appear only in HTML (see `html::authorship_address`).\n+\n+/// Parse username from query/body: trim, lowercase. `@` is not allowed (use `tommy`, not `@tommy`).\n+pub fn parse_username(input: &str) -> Result {\n+ let s = input.trim();\n+ if s.is_empty() {\n+ return Err(\"username must not be empty\".to_string());\n+ }\n+ if s.contains('@') {\n+ return Err(\n+ \"username must not contain '@' — use stored form (e.g. `tommy`)\".to_string(),\n+ );\n+ }\n+ let u = s.to_lowercase();\n+ validate_username_naked(&u)?;\n+ Ok(u)\n+}\n+\n+fn validate_username_naked(u: &str) -> Result<(), String> {\n+ if u.len() > 32 {\n+ return Err(\"username must be 1-32 characters\".to_string());\n+ }\n+ if !u\n+ .chars()\n+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')\n+ {\n+ return Err(\"username must be lowercase alphanumeric with '-' or '_' only\".to_string());\n+ }\n+ Ok(())\n+}\n+\n+/// Parse agent id: trim, lowercase. Must be `uuid:rig:provider/model` with no `@`.\n+pub fn parse_agent(input: &str) -> Result {\n+ let s = input.trim();\n+ if s.is_empty() {\n+ return Err(\"agent id must not be empty\".to_string());\n+ }\n+ if s.contains('@') {\n+ return Err(\n+ \"agent id must not contain '@' — use `uuid:rig:provider/model`\".to_string(),\n+ );\n+ }\n+ let a = s.to_lowercase();\n+ validate_agent_naked(&a)?;\n+ Ok(a)\n+}\n+\n+fn validate_agent_naked(a: &str) -> Result<(), String> {\n+ let parts: Vec<&str> = a.split(':').collect();\n+ if parts.len() != 3 {\n+ return Err(\"agent must be ::\".to_string());\n+ }\n+ let (uuid_part, rig_part, model_part) = (parts[0], parts[1], parts[2]);\n+ if uuid::Uuid::parse_str(uuid_part).is_err() {\n+ return Err(\"agent uuid must be a valid UUID v4\".to_string());\n+ }\n+ if rig_part.trim().is_empty() {\n+ return Err(\"agent rig must be non-empty\".to_string());\n+ }\n+ if !model_part.contains('/') {\n+ return Err(\"agent model must be \".to_string());\n+ }\n+ Ok(())\n+}\ndiff --git a/server/src/lib.rs b/server/src/lib.rs\nindex 1820b0dd9cd2d0b6ce05789e3225e0d86a3d357a..173fbdd6b3f23c062a200b268d04491d5e030b3f 100644\n--- a/server/src/lib.rs\n+++ b/server/src/lib.rs\n@@ -1,10 +1,12 @@\n #[macro_use]\n pub mod paths;\n pub mod api;\n+pub mod canonical_path;\n pub mod dsl;\n pub mod html;\n pub mod event_log;\n pub mod events;\n+pub mod identity;\n pub mod middleware;\n pub mod path_types;\n pub mod ranking;\ndiff --git a/server/src/path_types.rs b/server/src/path_types.rs\nindex 5a903de4f8309b6c3874e2cd70f2eb5650fd50a8..997597f6659c1ba2092bc5348e393bf7a8fa7ae0 100644\n--- a/server/src/path_types.rs\n+++ b/server/src/path_types.rs\n@@ -14,9 +14,9 @@ use std::fmt;\n \n use serde::{Deserialize, Serialize};\n \n-use crate::events::canonicalize_item;\n+use crate::canonical_path::canonicalize_item;\n \n-/// Canonical item identifier as produced by `events::canonicalize_item`.\n+/// Canonical item identifier as produced by `canonical_path::canonicalize_item`.\n ///\n /// In practice this is usually:\n /// - `https://slug.social/~/...` for ontology items, or\ndiff --git a/server/src/ranking.rs b/server/src/ranking.rs\nindex 70119611473a430113429eafb6d92b2bf96a3eb5..f70da0d076da2ba8f0abb5a4415babae1c2305f9 100644\n--- a/server/src/ranking.rs\n+++ b/server/src/ranking.rs\n@@ -265,7 +265,7 @@ mod tests {\n ratio_right: r,\n body: \"because\".to_string(),\n principal: \"test\".to_string(),\n- delegate: \"@00000000-0000-0000-0000-000000000000:test:local/test\".to_string(),\n+ delegate: Some(\"00000000-0000-0000-0000-000000000000:test:local/test\".to_string()),\n thread_id: \"untagged\".to_string(),\n }\n }\ndiff --git a/server/src/reducer.rs b/server/src/reducer.rs\nindex 9ab063a340e228edaa8967ec35762809fccd5d3a..550bcda1a1068df13908d19484d86ad46d65ddf1 100644\n--- a/server/src/reducer.rs\n+++ b/server/src/reducer.rs\n@@ -2,7 +2,8 @@ use std::collections::{HashMap, HashSet, VecDeque};\n \n use serde::{Deserialize, Serialize};\n \n-use crate::events::{canonicalize_agent, canonicalize_tag, canonicalize_username, Event, Ingest, ThreadCapability};\n+use crate::canonical_path::canonicalize_tag;\n+use crate::events::{Event, Ingest, ThreadCapability};\n use crate::path_types::CanonicalItemUrl;\n \n #[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]\n@@ -21,10 +22,10 @@ pub struct VoteData {\n pub ratio_left: i32,\n pub ratio_right: i32,\n pub body: String,\n- /// Human principal username (no leading '@').\n+ /// Human principal username (no `@` in stored events).\n pub principal: String,\n- /// Agent delegate identity (stored with single leading '@').\n- pub delegate: String,\n+ /// AI delegate id, if any (no `@` in stored events).\n+ pub delegate: Option,\n /// Thread id where this vote was cast (public tag or private id/slug).\n pub thread_id: String,\n }\n@@ -99,8 +100,6 @@ impl GroupState {\n pub fn apply_vote(&mut self, mut vote: VoteData) {\n vote.a = CanonicalItemUrl::parse(vote.a.as_str()).unwrap_or(vote.a);\n vote.b = CanonicalItemUrl::parse(vote.b.as_str()).unwrap_or(vote.b);\n- vote.principal = canonicalize_username(&vote.principal);\n- vote.delegate = canonicalize_agent(&vote.delegate);\n vote.thread_id = canonicalize_tag(&vote.thread_id);\n if vote.ratio_left < 0 {\n vote.ratio_left = 0;\n@@ -189,7 +188,7 @@ pub struct ReducerState {\n pub users_by_provider: HashMap<(String, String), String>,\n /// token_id -> (username, salt, token_hash)\n pub tokens_by_id: HashMap,\n- /// agent delegate (canonical '@...') -> username\n+ /// agent id (naked `uuid:rig:model`) -> username\n pub agent_bindings: HashMap,\n \n pub ingests_by_id: HashMap,\n@@ -330,26 +329,27 @@ impl ReducerState {\n pub fn apply_event(&mut self, event: Event) {\n match event {\n Event::UserRegistered(ur) => {\n- let username = canonicalize_username(&ur.username);\n- self.users_by_provider\n- .insert((ur.provider.to_lowercase(), ur.provider_id.clone()), username);\n+ self.users_by_provider.insert(\n+ (ur.provider.to_lowercase(), ur.provider_id.clone()),\n+ ur.username,\n+ );\n }\n Event::TokenIssued(ti) => {\n- let username = canonicalize_username(&ti.username);\n- self.tokens_by_id\n- .insert(ti.token_id.clone(), (username, ti.salt.clone(), ti.token_hash.clone()));\n+ self.tokens_by_id.insert(\n+ ti.token_id.clone(),\n+ (ti.username, ti.salt.clone(), ti.token_hash.clone()),\n+ );\n }\n Event::AgentBound(ab) => {\n- let username = canonicalize_username(&ab.username);\n- let agent = canonicalize_agent(&ab.agent);\n- self.agent_bindings.insert(agent, username);\n+ if ab.agent.is_empty() {\n+ return;\n+ }\n+ self.agent_bindings.insert(ab.agent, ab.username);\n }\n Event::ThreadCreated(tc) => {\n self.threads.entry(tc.thread_id.clone()).or_default().visibility = tc.visibility;\n }\n Event::Ingest(mut ing) => {\n- ing.principal = canonicalize_username(&ing.principal);\n- ing.delegate = canonicalize_agent(&ing.delegate);\n ing.thread_id = canonicalize_tag(&ing.thread_id);\n \n self.ingests_by_id.insert(ing.id.clone(), ing.clone());\n@@ -528,7 +528,7 @@ impl ReducerState {\n let caps = self.grants\n .entry(ga.thread_id)\n .or_default()\n- .entry(canonicalize_username(&ga.username))\n+ .entry(ga.username)\n .or_default();\n for cap in ga.capabilities {\n caps.insert(cap);\n@@ -536,7 +536,7 @@ impl ReducerState {\n }\n Event::GrantRevoked(gr) => {\n if let Some(thread_grants) = self.grants.get_mut(&gr.thread_id) {\n- let username = canonicalize_username(&gr.username);\n+ let username = gr.username;\n if let Some(caps) = thread_grants.get_mut(&username) {\n for cap in &gr.capabilities {\n caps.remove(cap);\ndiff --git a/server/tests/basic.rs b/server/tests/basic.rs\nindex 8d7dd87d327c969ad953ecaa6b021a03e4d1842e..21cacd3049c9f5a307e75eefd5ebfc7bf0097b5d 100644\n--- a/server/tests/basic.rs\n+++ b/server/tests/basic.rs\n@@ -1,6 +1,7 @@\n use slugsocial_server::{\n event_log::EventLog,\n- events::{canonicalize_item, canonicalize_tag, Event, Ingest},\n+ canonical_path::{canonicalize_item, canonicalize_tag},\n+ events::{Event, Ingest},\n ranking::ranked_items,\n reducer::{GroupState, ReducerState},\n };\n@@ -15,7 +16,7 @@ fn ingest_event(ts: i64, raw: &str) -> Event {\n id: format!(\"test-{ts}\"),\n raw: raw.to_string(),\n principal: \"test\".to_string(),\n- delegate: \"@@00000000-0000-0000-0000-000000000000:test:local/test\".to_string(),\n+ delegate: Some(\"00000000-0000-0000-0000-000000000000:test:local/test\".to_string()),\n thread_id: \"t\".to_string(),\n })\n }\n@@ -491,7 +492,7 @@ fn reducer_negative_ratio_clamped_to_zero() {\n ratio_right: -3,\n body: \"negative\".to_string(),\n principal: \"test\".to_string(),\n- delegate: \"@@00000000-0000-0000-0000-000000000000:test:local/test\".to_string(),\n+ delegate: Some(\"00000000-0000-0000-0000-000000000000:test:local/test\".to_string()),\n thread_id: \"t\".to_string(),\n });\n assert_eq!(group.idx_to_item.len(), 2);\ndiff --git a/server/tests/integration.rs b/server/tests/integration.rs\nindex 24ef464631cd269889b8bb751ef0e90289443e97..eaa25f2c5cc21df3096d9b8f54c060c83207bfd6 100644\n--- a/server/tests/integration.rs\n+++ b/server/tests/integration.rs\n@@ -87,7 +87,7 @@ async fn test_ingest_actor_with_colons_is_detected_and_validated() {\n // Old archive style: agent includes colons but UUID is only a prefix (invalid).\n // We should detect the agent line, then fail with \"invalid agent format\".\n let ingest_payload = serde_json::json!({\n- \"delegate\": \"@@aec1e31c:claudecode:anthropic/claude-sonnet-4.5\",\n+ \"delegate\": \"aec1e31c:claudecode:anthropic/claude-sonnet-4.5\",\n \"thread\": \"t\",\n \"text\": \"~/x {x}\\n\",\n });\n@@ -108,6 +108,26 @@ async fn test_ingest_actor_with_colons_is_detected_and_validated() {\n hint.to_lowercase().contains(\"uuid\"),\n \"hint should mention uuid, got: {hint}\"\n );\n+\n+ let at_payload = serde_json::json!({\n+ \"delegate\": \"@00000000-0000-0000-0000-000000000000:test:local/test\",\n+ \"thread\": \"t\",\n+ \"text\": \"~/x {x}\\n\",\n+ });\n+ let at_resp = client\n+ .post(&format!(\"http://{}/api/v0/ingest\", addr))\n+ .header(\"Authorization\", format!(\"Bearer {}\", test_bearer()))\n+ .json(&at_payload)\n+ .send()\n+ .await\n+ .unwrap();\n+ assert_eq!(at_resp.status(), reqwest::StatusCode::BAD_REQUEST);\n+ let at_body: serde_json::Value = at_resp.json().await.unwrap();\n+ let at_hint = at_body[\"hint\"].as_str().unwrap_or_default();\n+ assert!(\n+ at_hint.contains('@'),\n+ \"hint should reject '@' in delegate, got: {at_hint}\"\n+ );\n }\n \n #[tokio::test]\n@@ -117,7 +137,7 @@ async fn test_vote_endpoint() {\n \n // /api/v0/vote was removed; all votes are submitted via ingest.\n let ingest_payload = serde_json::json!({\n- \"delegate\": \"@@00000000-0000-0000-0000-000000000000:test:local/test\",\n+ \"delegate\": \"00000000-0000-0000-0000-000000000000:test:local/test\",\n \"thread\": \"cli\",\n \"text\": \"~/clap {cli parser}\\n~/argh {cli parser}\\n~/clap 3:1 ~/argh {because clap is more full-featured}\\n\",\n });\n@@ -143,7 +163,7 @@ async fn test_rank_endpoint() {\n \n // Ingest items + vote (vote endpoint removed).\n let ingest_payload = serde_json::json!({\n- \"delegate\": \"@@00000000-0000-0000-0000-000000000000:test:local/test\",\n+ \"delegate\": \"00000000-0000-0000-0000-000000000000:test:local/test\",\n \"thread\": \"langs\",\n \"text\": \"~/rust {systems}\\n~/go {concurrency}\\n~/rust 3:1 ~/go {because i prefer rust for systems work}\\n\",\n });\n@@ -180,7 +200,7 @@ async fn test_check_endpoint_does_not_commit() {\n let client = reqwest::Client::new();\n \n let check_payload = serde_json::json!({\n- \"delegate\": \"@@00000000-0000-0000-0000-000000000000:test:local/test\",\n+ \"delegate\": \"00000000-0000-0000-0000-000000000000:test:local/test\",\n \"thread\": \"t\",\n \"text\": \"~/a {x}\\n~/b {y}\\n~/a 2:1 ~/b {because}\\n\",\n });\n@@ -220,7 +240,7 @@ async fn test_garden_item_pair_matchup_include_threads() {\n \n // Ingest with thread_id metadata so item_threads and vote.thread_id are populated.\n let ingest_payload = serde_json::json!({\n- \"delegate\": \"@@00000000-0000-0000-0000-000000000000:test:local/test\",\n+ \"delegate\": \"00000000-0000-0000-0000-000000000000:test:local/test\",\n \"thread\": \"sorting-hat\",\n \"text\": \"~/sorts/insertion { O(n^2) }\\n~/sorts/mergesort { O(n log n) }\\n~/sorts/insertion 3:1 ~/sorts/mergesort { simpler for small n }\\n\",\n });\n@@ -324,7 +344,7 @@ async fn test_rank_history() {\n // First ingest: rust vs python — two votes on rust in one doc (the multi-vote case).\n ingest(\n serde_json::json!({\n- \"delegate\": \"@@00000000-0000-0000-0000-000000000001:rig:test/model\",\n+ \"delegate\": \"00000000-0000-0000-0000-000000000001:rig:test/model\",\n \"thread\": \"hist-test\",\n \"text\": \"~/hist/rust { systems }\\n~/hist/python { scripting }\\n~/hist/go { concurrency }\\n~/hist/rust 3:1 ~/hist/python { ownership over gc }\\n~/hist/rust 2:1 ~/hist/go { performance over simplicity }\\n\",\n }),\n@@ -354,7 +374,7 @@ async fn test_rank_history() {\n // Second ingest: python beats go — rust not directly touched, so python gets a new entry.\n ingest(\n serde_json::json!({\n- \"delegate\": \"@@00000000-0000-0000-0000-000000000002:rig:test/model\",\n+ \"delegate\": \"00000000-0000-0000-0000-000000000002:rig:test/model\",\n \"thread\": \"hist-test\",\n \"text\": \"~/hist/python 3:1 ~/hist/go { dynamic typing is worth it }\\n\",\n }),\n@@ -404,7 +424,7 @@ async fn pair_returns_connectivity_stats() {\n \n // Ingest 4 items with 1 vote (a vs b), leaving c and d as isolates.\n let doc = serde_json::json!({\n- \"delegate\": \"@@00000000-0000-0000-0000-000000000001:testrig:test/model\",\n+ \"delegate\": \"00000000-0000-0000-0000-000000000001:testrig:test/model\",\n \"thread\": \"connectivity-test\",\n \"text\": \"~/conn/a { item a }\\n~/conn/b { item b }\\n~/conn/c { item c }\\n~/conn/d { item d }\\n~/conn/a 3:1 ~/conn/b { a is better }\\n\",\n });\n@@ -438,7 +458,7 @@ async fn pair_returns_connectivity_stats() {\n \n // Add a vote connecting c to a — should reduce components.\n let doc2 = serde_json::json!({\n- \"delegate\": \"@@00000000-0000-0000-0000-000000000001:testrig:test/model\",\n+ \"delegate\": \"00000000-0000-0000-0000-000000000001:testrig:test/model\",\n \"thread\": \"connectivity-test\",\n \"text\": \"~/conn/c 2:1 ~/conn/a { c beats a }\\n\",\n });\ndiff --git a/test/auth.bb b/test/auth.bb\nindex b54ea509aafd2d5ee85877665982d7fc00cd8b20..611e04f1806ef81d678a91f499597fe55f691dd7 100644\n--- a/test/auth.bb\n+++ b/test/auth.bb\n@@ -155,7 +155,7 @@\n \n (println \"\\nstarting pending session…\")\n (let [start-resp (http-post-json (str base-url \"/api/v0/pending-session\")\n- {:agent \"@@00000000-0000-0000-0000-000000000000:bb:local/dev\"})\n+ {:agent \"00000000-0000-0000-0000-000000000000:bb:local/dev\"})\n _ (assert! (= 200 (:status start-resp)) \"pending-session start returns 200\")\n start-json (json/parse-string (:body start-resp) true)]\n (assert! (clojure.string/starts-with? (:session start-json) \"p_\") \"session id has p_ prefix\")\ndiff --git a/test/grants.bb b/test/grants.bb\nindex 962ff01cdc25d6d6977cc9a810c404918c20856d..f72799ae6fe099f48bdf316deee07f15882e9d45 100644\n--- a/test/grants.bb\n+++ b/test/grants.bb\n@@ -187,11 +187,11 @@\n ;; Register two users. The mock google cycles through google-user-alice then google-user-bob.\n (println \"\\nregistering alice…\")\n (let [alice-token (register-user base-url\n- \"@@00000000-0000-0000-0000-000000000001:test:local/dev\"\n+ \"00000000-0000-0000-0000-000000000001:test:local/dev\"\n \"alice\")\n _ (println \"registering bob…\")\n bob-token (register-user base-url\n- \"@@00000000-0000-0000-0000-000000000002:test:local/dev\"\n+ \"00000000-0000-0000-0000-000000000002:test:local/dev\"\n \"bob\")\n \n ;; Alice creates a private thread.\n@@ -206,14 +206,14 @@\n ;; Alice (owner) can post prose to her own private thread.\n (println \"\\nalice posts prose to her private thread…\")\n (assert! (= 200 (:status (ingest! base-url alice-token thread-id\n- \"@@00000000-0000-0000-0000-000000000001:test:local/dev\"\n+ \"00000000-0000-0000-0000-000000000001:test:local/dev\"\n \"Hello from alice.\")))\n \"alice prose post succeeds\")\n \n ;; Bob has no grants at all — should get 403.\n (println \"\\nbob (no grants) tries to post prose…\")\n (assert! (= 403 (:status (ingest! base-url bob-token thread-id\n- \"@@00000000-0000-0000-0000-000000000002:test:local/dev\"\n+ \"00000000-0000-0000-0000-000000000002:test:local/dev\"\n \"Hello from bob, unauthorized.\")))\n \"bob without grants gets 403\")\n \n@@ -226,7 +226,7 @@\n \n (println \"\\nbob (View only) tries to post prose…\")\n (assert! (= 403 (:status (ingest! base-url bob-token thread-id\n- \"@@00000000-0000-0000-0000-000000000002:test:local/dev\"\n+ \"00000000-0000-0000-0000-000000000002:test:local/dev\"\n \"Hello from bob, view only.\")))\n \"bob with View but no Post gets 403\")\n \n@@ -239,21 +239,21 @@\n \n (println \"\\nbob (View + Post) posts prose…\")\n (assert! (= 200 (:status (ingest! base-url bob-token thread-id\n- \"@@00000000-0000-0000-0000-000000000002:test:local/dev\"\n+ \"00000000-0000-0000-0000-000000000002:test:local/dev\"\n \"Hello from bob, now authorised.\")))\n \"bob with View + Post succeeds for prose\")\n \n ;; Alice defines two items and votes on them in the private thread.\n (println \"\\nalice posts items + vote to private thread…\")\n (assert! (= 200 (:status (ingest! base-url alice-token thread-id\n- \"@@00000000-0000-0000-0000-000000000001:test:local/dev\"\n+ \"00000000-0000-0000-0000-000000000001:test:local/dev\"\n \"~/fruits/apple { A crisp red apple. }\\n~/fruits/banana { A yellow banana. }\\n~/fruits/apple > ~/fruits/banana { apples are better }\")))\n \"alice vote in private thread succeeds\")\n \n ;; Bob (View + Post, no Vote) tries to vote — should be 403.\n (println \"\\nbob (no Vote) tries to vote…\")\n (assert! (= 403 (:status (ingest! base-url bob-token thread-id\n- \"@@00000000-0000-0000-0000-000000000002:test:local/dev\"\n+ \"00000000-0000-0000-0000-000000000002:test:local/dev\"\n \"~/fruits/apple > ~/fruits/banana { bob's take }\")))\n \"bob without Vote gets 403\")\n \n@@ -266,7 +266,7 @@\n \n (println \"\\nbob (View + Post + Vote) votes…\")\n (assert! (= 200 (:status (ingest! base-url bob-token thread-id\n- \"@@00000000-0000-0000-0000-000000000002:test:local/dev\"\n+ \"00000000-0000-0000-0000-000000000002:test:local/dev\"\n \"~/fruits/apple > ~/fruits/banana { bob's take }\")))\n \"bob with Vote succeeds\"))\n \ndiff --git a/test/integration.bb b/test/integration.bb\nindex 93db8f3102b1b3a05f3c4bd2cc9f348072fe54cc..4ff5d625840be3bf5e4162cef107a3cbd45aec4d 100644\n--- a/test/integration.bb\n+++ b/test/integration.bb\n@@ -166,7 +166,7 @@\n \n ;; 3. ingest via CLI (bearer required)\n (println \"\\ningesting .sorter document via CLI…\")\n- (bind ingest1-result (common/run-cli cli-bin base-url [\"ingest\" \"--json\" \"--thread\" \"integration-test\"] :input sorter-doc :extra-env token-env))\n+ (bind ingest1-result (common/run-cli cli-bin base-url [\"ingest\" \"--json\" \"--thread\" \"integration-test\" \"--delegate\" \"00000000-0000-0000-0000-000000000000:cli:local/dev\"] :input sorter-doc :extra-env token-env))\n (assert! (zero? (:exit ingest1-result)) \"cli ingest exits 0\")\n (bind ingest1-resp (json/parse-string (:out ingest1-result) true))\n (assert! (:ok ingest1-resp) \"ingest response ok=true\")\n@@ -237,7 +237,7 @@\n \"#integration-test\"\n \"~/languages/rust 4:1 ~/languages/python { type safety }\"\n \"~/languages/rust 3:1 ~/languages/go { zero-cost abstractions }\"]))\n- (bind hist-ingest (common/run-cli cli-bin base-url [\"ingest\" \"--json\" \"--thread\" \"integration-test\"] :input two-vote-doc :extra-env token-env))\n+ (bind hist-ingest (common/run-cli cli-bin base-url [\"ingest\" \"--json\" \"--thread\" \"integration-test\" \"--delegate\" \"00000000-0000-0000-0000-000000000000:cli:local/dev\"] :input two-vote-doc :extra-env token-env))\n (assert! (zero? (:exit hist-ingest))\n (str \"two-vote ingest exits 0 (err: \" (:err hist-ingest) \")\"))\n \ndiff --git a/test/oauth.bb b/test/oauth.bb\nindex f94583ee0f6fedfc023564ed7ee3a2986adcf660..84679e1a4adbe100dfe7e7d64a2c6270b023d275 100644\n--- a/test/oauth.bb\n+++ b/test/oauth.bb\n@@ -85,11 +85,11 @@\n stop-fn (http/run-server handler {:port port})]\n {:stop-fn stop-fn :port port}))\n \n-(def ^:private default-agent \"@@00000000-0000-0000-0000-000000000000:cli:local/dev\")\n+(def ^:private default-agent \"00000000-0000-0000-0000-000000000000:cli:local/dev\")\n \n (defn fetch-bearer-token!\n \"Simulate browser OAuth + username choice; returns `slug_…` bearer token.\n- Agent must match CLI default `SLUG_DELEGATE` for ingest binding.\"\n+ Ingest `--delegate` must match this agent string for `AgentBound` on first write.\"\n [base-url & {:keys [username agent] :or {username \"intuser\" agent default-agent}}]\n (let [start-resp (http-post-json (str base-url \"/api/v0/pending-session\")\n {:agent agent})]\ndiff --git a/types/src/lib.rs b/types/src/lib.rs\nindex a62822a36463c68fde6c5fc1aa9e4273c82ca0c8..92e6d122d573ea225f8fb86c548a81b3454425ad 100644\n--- a/types/src/lib.rs\n+++ b/types/src/lib.rs\n@@ -138,7 +138,7 @@ pub struct PostRow {\n /// Chronological index within the thread (0 = oldest).\n pub index: usize,\n pub ts: i64,\n- /// Self-declared actor (`@uuid:rig:model`).\n+ /// Principal username (stored form, no `@`).\n pub actor: String,\n pub body: String,\n pub truncated: bool,\n@@ -186,6 +186,7 @@ pub struct VoteRow {\n pub a: String,\n pub b: String,\n pub ratio: String,\n+ /// Principal username when present (stored form, no `@`).\n pub actor: Option,\n pub body: String,\n /// Thread where this vote was cast (e.g. \"#sorting-hat\").\n@@ -196,6 +197,7 @@ pub struct VoteRow {\n /// Response for the feed endpoint — all ingests since a cutoff, newest first.\n #[derive(Debug, Serialize, Deserialize)]\n pub struct FeedResponse {\n+ /// Principal username this feed is scoped to (stored form, no `@`).\n pub actor: String,\n /// The lower-bound timestamp used (actor's last ingest, ms). None if actor has never posted.\n #[serde(default, skip_serializing_if = \"Option::is_none\")]\n@@ -222,8 +224,9 @@ pub struct FeedPost {\n pub struct IngestRequest {\n /// Thread identifier: public tag (e.g. \"languages\") or private id/slug (e.g. \"a7f2k9x/project-review\").\n pub thread: String,\n- /// Agent delegate identity in request form (e.g. \"@@uuid:rig:provider/model\").\n- pub delegate: String,\n+ /// Delegate id: `uuid:rig:provider/model` (no `@`). Omit for human-only ingests.\n+ #[serde(default, skip_serializing_if = \"Option::is_none\")]\n+ pub delegate: Option,\n /// DSL+prose body only.\n pub text: String,\n }\n@@ -231,7 +234,7 @@ pub struct IngestRequest {\n /// Start a browser-based OAuth login flow for a CLI agent.\n #[derive(Debug, Serialize, Deserialize)]\n pub struct PendingSessionStartRequest {\n- /// Agent delegate identity in request form (e.g. \"@@uuid:rig:provider/model\").\n+ /// Delegate id: `uuid:rig:provider/model` (no `@`).\n pub agent: String,\n }\n \n@@ -255,6 +258,7 @@ pub struct PendingSessionPollResponse {\n \n #[derive(Debug, Serialize, Deserialize)]\n pub struct WhoamiResponse {\n+ /// Username (stored form, no `@`).\n pub user: String,\n pub agents_bound: usize,\n }\n\n\nSide B — contributor: tommy-mor\nSide B — commit message:\n[880eb778] Harden auth: fail-closed votes, mock OAuth gate, Secure cookies.\n\nAlso show the current alias in the top nav and pin durable by rev.\n\nCo-authored-by: Cursor \n\nSide B — unified diff (full patch):\ndiff --git a/AGENTS.md b/AGENTS.md\nindex babb889d6fbfb1fa7176c9e6b7544ae17b61dd2e..6e0fd8ebb65d665c9c1438e3275971d62b98fd95 100644\n--- a/AGENTS.md\n+++ b/AGENTS.md\n@@ -10,11 +10,11 @@ Single Rust web app **`sorter2-server`**: pairwise voting, rank-centrality ranki\n \n - **Bootstrap script**: `./scripts/cursor-env-install.sh` (also run via `.cursor/environment.json` on Cloud Agent boot) installs Playwright Chromium, Babashka, bbin, `clj-paren-repair`, and warms the RocksDB build.\n - **Rust 1.88+** is required (`rust-toolchain.toml`). The Cloud Dockerfile and `cursor-env-install.sh` install **rustup** 1.88.0 first so `cargo` works while Playwright/Clojure bootstrap continues. Do not rely on `/usr/local/cargo` (often missing or stale).\n-- **RocksDB / `durable`**: Ubuntu’s default `c++` is often **clang** without libc++ headers. Set **`CXX=g++`** and **`RUSTFLAGS=\"-C linker=g++\"`** (or `CC=gcc`) before `cargo build` / `cargo test` — both are set in the bootstrap script and `.cursor/environment.json`.\n+- **RocksDB / `durable`**: `durable` is an external git dependency (`tommy-mor/durable`, pinned by rev in `server/Cargo.toml`). Ubuntu’s default `c++` is often **clang** without libc++ headers. Set **`CXX=g++`** and **`RUSTFLAGS=\"-C linker=g++\"`** (or `CC=gcc`) before `cargo build` / `cargo test` — both are set in the bootstrap script and `.cursor/environment.json`.\n - **System packages** for builds: `build-essential`, `g++`, `clang`, `libclang-dev`, `pkg-config`, `libssl-dev`, `openjdk-21-jre-headless` (for `reqwest` / OpenSSL, `librocksdb-sys`, `zstd-sys` / bindgen, and **bbin** / Clojure JVM). The bootstrap sets **`JAVA_HOME`** when Java is present.\n - **Clojure CLI 1.12.0.1530** (used in CI): install from https://clojure.org/guides/install_clojure — needed for `./scripts/clj-test.sh` / Kaocha tests.\n - **Babashka / bbin / clj-paren-repair**: installed by `cursor-env-install.sh` into `~/.local/bin` (bb tasks in `bb.edn`, delimiter repair for Clojure edits).\n-- **Playwright** (Spel browser tests in `test/vote_compare.clj`): Chromium via `clojure -M -e \"(com.microsoft.playwright.CLI/main ...)\"` — run once after clone or use the bootstrap script.\n+- **Playwright** (Spel browser tests in `test/vote_compare.clj` / `test/auth_login.clj`): Chromium via `clojure -M -e \"(com.microsoft.playwright.CLI/main ...)\"` — run once after clone or use the bootstrap script.\n \n ### Commands (see also `TEST.sh`)\n \n@@ -34,13 +34,17 @@ Environment variables (defaults in `server/src/state.rs`):\n - `PORT` — default `8080`\n - `SORTER2_DATA_DIR` — default `./data` (created on startup)\n - `SORTER2_EVENT_LOG` — default `{data_dir}/events.jsonl`\n+- `SORTER2_BASE_URL` — public origin (also drives Secure cookies when `https://`)\n+- `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET` — GitHub OAuth (optional; login disabled if unset)\n+- `SORTER2_ALLOW_MOCK_OAUTH=1` — allow `mock_user` on `/auth/github` (tests only)\n \n Health check: `GET /healthz` → `ok`.\n \n-Core UI flow: `POST /ui` with form field `__rpc__` (JSON). Example vote:\n+Core UI flow: `POST /ui` with form field `__rpc__` (JSON). Votes require a session cookie (sign in via `/login`). Example vote:\n \n ```bash\n curl -sf -X POST http://127.0.0.1:8080/ui \\\n+ --cookie \"sorter2_session=...\" \\\n --data-urlencode '__rpc__={\"action\":\"record_vote\",\"a\":\"alpha\",\"b\":\"beta\",\"ratio_left\":2,\"ratio_right\":1}'\n ```\n \ndiff --git a/Cargo.lock b/Cargo.lock\nindex aa02997ad85777195f135bfd9456bcee0fc9a590..1f8690f3e486d099577a32c2ece48caf57ea7160 100644\n--- a/Cargo.lock\n+++ b/Cargo.lock\n@@ -414,7 +414,7 @@ dependencies = [\n [[package]]\n name = \"durable\"\n version = \"0.2.0\"\n-source = \"git+https://github.com/tommy-mor/durable.git?branch=main#a6c14eaa809693140eea0c22b07ef24d8e74adaf\"\n+source = \"git+https://github.com/tommy-mor/durable.git?rev=a6c14eaa809693140eea0c22b07ef24d8e74adaf#a6c14eaa809693140eea0c22b07ef24d8e74adaf\"\n dependencies = [\n \"ciborium\",\n \"durable-derive\",\n@@ -426,7 +426,7 @@ dependencies = [\n [[package]]\n name = \"durable-derive\"\n version = \"0.2.0\"\n-source = \"git+https://github.com/tommy-mor/durable.git?branch=main#a6c14eaa809693140eea0c22b07ef24d8e74adaf\"\n+source = \"git+https://github.com/tommy-mor/durable.git?rev=a6c14eaa809693140eea0c22b07ef24d8e74adaf#a6c14eaa809693140eea0c22b07ef24d8e74adaf\"\n dependencies = [\n \"proc-macro2\",\n \"quote\",\ndiff --git a/server/Cargo.toml b/server/Cargo.toml\nindex dfa39beddecfa37dcdeaa602cb30f4b547528fbb..bd88687fb0ba47d68f2c08eb5e11d0e08b7c4398 100644\n--- a/server/Cargo.toml\n+++ b/server/Cargo.toml\n@@ -25,7 +25,7 @@ futures-util = { version = \"0.3\", default-features = false, features = [\"std\"] }\n rand = \"0.8\"\n urlencoding = \"2\"\n url = \"2\"\n-durable = { git = \"https://github.com/tommy-mor/durable.git\", branch = \"main\" }\n+durable = { git = \"https://github.com/tommy-mor/durable.git\", rev = \"a6c14eaa809693140eea0c22b07ef24d8e74adaf\" }\n \n [dev-dependencies]\n reqwest = { version = \"0.12\", features = [\"json\"] }\ndiff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs\nindex b86581b1f337650564274254d840e8a75b49524d..9da62ffbed07eb28729aa3160bf33b07ce0d7945 100644\n--- a/server/src/api/ui_html.rs\n+++ b/server/src/api/ui_html.rs\n@@ -71,10 +71,16 @@ pub async fn post_ui_html(\n return resp;\n }\n let parent = parent_from_scope(&scope);\n- let actor = resolve_vote_actor(\n+ let actor = match resolve_vote_actor(\n state.projection_store.db(),\n session_id_from_jar(&jar).as_deref(),\n- );\n+ ) {\n+ Ok(actor) => actor,\n+ Err(_) => {\n+ return vote_auth_redirect(&state, &jar)\n+ .unwrap_or_else(|| login_redirect_js().into_response());\n+ }\n+ };\n if let Err(e) = state\n .record_vote(&parent, &a, &b, ratio_left, ratio_right, &actor)\n .await\ndiff --git a/server/src/auth/config.rs b/server/src/auth/config.rs\nindex a1f042c655bf3e5234eeb87a7d889f64592807fb..a5976af9a52ea207b35ae87bd1fe927c47a477ca 100644\n--- a/server/src/auth/config.rs\n+++ b/server/src/auth/config.rs\n@@ -1,9 +1,42 @@\n pub const AUTH_RETURN_COOKIE: &str = \"sorter2_auth_return\";\n \n+/// Allow `mock_user` on `/auth/github` (test harness only).\n+pub fn mock_oauth_allowed() -> bool {\n+ matches!(\n+ std::env::var(\"SORTER2_ALLOW_MOCK_OAUTH\").as_deref(),\n+ Ok(\"1\") | Ok(\"true\") | Ok(\"TRUE\")\n+ )\n+}\n+\n+/// Set the Secure flag on auth cookies when serving over HTTPS.\n+pub fn cookies_secure() -> bool {\n+ std::env::var(\"SORTER2_BASE_URL\")\n+ .map(|u| u.starts_with(\"https://\"))\n+ .unwrap_or(false)\n+}\n+\n pub fn sanitize_return_to(raw: &str) -> String {\n let s = raw.trim();\n- if s.is_empty() || !s.starts_with('/') || s.starts_with(\"//\") {\n+ if s.is_empty() || !s.starts_with('/') || s.starts_with(\"//\") || s.starts_with(\"/\\\\\") {\n+ return \"/\".to_string();\n+ }\n+ // Reject scheme-relative and protocol-smuggling forms.\n+ if s.contains(\"://\") || s.contains('\\\\') {\n return \"/\".to_string();\n }\n s.to_string()\n }\n+\n+#[cfg(test)]\n+mod tests {\n+ use super::*;\n+\n+ #[test]\n+ fn sanitize_return_to_blocks_open_redirects() {\n+ assert_eq!(sanitize_return_to(\"\"), \"/\");\n+ assert_eq!(sanitize_return_to(\"//evil.com\"), \"/\");\n+ assert_eq!(sanitize_return_to(\"/\\\\evil.com\"), \"/\");\n+ assert_eq!(sanitize_return_to(\"https://evil.com\"), \"/\");\n+ assert_eq!(sanitize_return_to(\"/vote?parent=x\"), \"/vote?parent=x\");\n+ }\n+}\ndiff --git a/server/src/auth/mod.rs b/server/src/auth/mod.rs\nindex 5ed535ba199fa736f0048c32623b14c3b1e5de2d..d4a85ef52c15dc35148e4c743f0d646cbbdb056d 100644\n--- a/server/src/auth/mod.rs\n+++ b/server/src/auth/mod.rs\n@@ -26,7 +26,7 @@ use crate::{\n ui_action::UI_RPC_FIELD,\n };\n \n-pub use session::{resolve_vote_actor, session_id_from_jar, VoteActor};\n+pub use session::{nav_pseudonym, resolve_vote_actor, session_id_from_jar, VoteActor};\n \n pub fn base_url_from_env(port: u16) -> String {\n std::env::var(\"SORTER2_BASE_URL\")\n@@ -168,6 +168,10 @@ pub async fn login_page(\n \"login · sorter2\",\n login_body(session.as_ref(), &aliases, &providers),\n state.views.get_views(\"/login\"),\n+ session\n+ .as_ref()\n+ .filter(|s| !s.pseudonym.trim().is_empty())\n+ .map(|s| s.pseudonym.as_str()),\n );\n (jar, Html(markup.into_string())).into_response()\n }\n@@ -222,6 +226,7 @@ pub async fn alias_page(\n \"choose alias · sorter2\",\n body,\n state.views.get_views(\"/login/alias\"),\n+ None,\n )\n .into_string(),\n )\n@@ -237,7 +242,12 @@ pub async fn github_start(\n .ok_or(StatusCode::SERVICE_UNAVAILABLE)?;\n let return_to = return_from_query_or_jar(&jar, query.return_to.as_deref());\n let state_token = session::new_oauth_state();\n- let url = oauth::authorize_url(&cfg, &state_token, query.mock_user.as_deref());\n+ let mock_user = if config::mock_oauth_allowed() {\n+ query.mock_user.as_deref()\n+ } else {\n+ None\n+ };\n+ let url = oauth::authorize_url(&cfg, &state_token, mock_user);\n let jar = jar\n .add(session::oauth_state_cookie_value(&state_token))\n .add(session::auth_return_cookie_value(&return_to));\ndiff --git a/server/src/auth/session.rs b/server/src/auth/session.rs\nindex 09659240b9455c6fca12db5652e1d31cf8c2acfc..41df030ded3abcafc0ab3887ab769adf103f9aa0 100644\n--- a/server/src/auth/session.rs\n+++ b/server/src/auth/session.rs\n@@ -5,7 +5,7 @@ use durable::{Db, Durability};\n use rand::Rng;\n \n use crate::{\n- auth::config::AUTH_RETURN_COOKIE,\n+ auth::config::{self, AUTH_RETURN_COOKIE},\n fetch::now_ms,\n identity::{DEFAULT_ACTOR_UUID, DEFAULT_PSEUDONYM},\n storage_dto::{SessionDataV1, SESSION_DATA_VERSION},\n@@ -37,6 +37,7 @@ pub struct VoteActor {\n }\n \n impl VoteActor {\n+ /// Test / bench helper: seed votes as the default pseudonym without a session.\n pub fn anon() -> Self {\n Self {\n pseudonym: DEFAULT_PSEUDONYM.to_string(),\n@@ -70,20 +71,51 @@ fn hex_encode(bytes: &[u8]) -> String {\n bytes.iter().map(|b| format!(\"{b:02x}\")).collect()\n }\n \n-pub fn resolve_vote_actor(db: &Db, session_id: Option<&str>) -> VoteActor {\n- let Some(session_id) = session_id else {\n- return VoteActor::anon();\n- };\n- let Ok(Some(session)) = load_session(db, session_id) else {\n- return VoteActor::anon();\n- };\n- if session.expires_at <= now_ms() {\n- return VoteActor::anon();\n+fn build_cookie(name: &'static str, value: String) -> Cookie<'static> {\n+ let mut builder = Cookie::build((name, value))\n+ .http_only(true)\n+ .same_site(SameSite::Lax)\n+ .path(\"/\");\n+ if config::cookies_secure() {\n+ builder = builder.secure(true);\n+ }\n+ builder.build()\n+}\n+\n+fn clear_cookie(name: &'static str) -> Cookie<'static> {\n+ let mut builder = Cookie::build((name, \"\"))\n+ .http_only(true)\n+ .same_site(SameSite::Lax)\n+ .path(\"/\")\n+ .removal();\n+ if config::cookies_secure() {\n+ builder = builder.secure(true);\n+ }\n+ builder.build()\n+}\n+\n+/// Resolve the vote actor from a live session. Fail-closed: never falls back to anon.\n+pub fn resolve_vote_actor(db: &Db, session_id: Option<&str>) -> Result {\n+ let session_id = session_id.ok_or(\"sign in to vote\")?;\n+ let session = load_valid_session(db, session_id).ok_or(\"session expired\")?;\n+ if !session_has_pseudonym(&session) {\n+ return Err(\"choose an alias first\");\n }\n let trust_weight = user_trust_weight(db, &session.uuid).unwrap_or(1.0);\n- VoteActor {\n+ Ok(VoteActor {\n pseudonym: session.current_pseudonym,\n trust_weight,\n+ })\n+}\n+\n+/// Display name for the top nav, if any session is active.\n+pub fn nav_pseudonym(db: &Db, jar: &CookieJar) -> Option {\n+ let session_id = session_id_from_jar(jar)?;\n+ let session = load_valid_session(db, &session_id)?;\n+ if session_has_pseudonym(&session) {\n+ Some(session.current_pseudonym)\n+ } else {\n+ None\n }\n }\n \n@@ -151,54 +183,27 @@ pub fn destroy_session(db: &Db, session_id: &str) -> Result<(), String> {\n }\n \n pub fn session_cookie_value(session_id: &str) -> Cookie<'static> {\n- Cookie::build((SESSION_COOKIE, session_id.to_string()))\n- .http_only(true)\n- .same_site(SameSite::Lax)\n- .path(\"/\")\n- .build()\n+ build_cookie(SESSION_COOKIE, session_id.to_string())\n }\n \n pub fn clear_session_cookie() -> Cookie<'static> {\n- Cookie::build((SESSION_COOKIE, \"\"))\n- .http_only(true)\n- .same_site(SameSite::Lax)\n- .path(\"/\")\n- .removal()\n- .build()\n+ clear_cookie(SESSION_COOKIE)\n }\n \n pub fn oauth_state_cookie_value(state: &str) -> Cookie<'static> {\n- Cookie::build((OAUTH_STATE_COOKIE, state.to_string()))\n- .http_only(true)\n- .same_site(SameSite::Lax)\n- .path(\"/\")\n- .build()\n+ build_cookie(OAUTH_STATE_COOKIE, state.to_string())\n }\n \n pub fn clear_oauth_state_cookie() -> Cookie<'static> {\n- Cookie::build((OAUTH_STATE_COOKIE, \"\"))\n- .http_only(true)\n- .same_site(SameSite::Lax)\n- .path(\"/\")\n- .removal()\n- .build()\n+ clear_cookie(OAUTH_STATE_COOKIE)\n }\n \n pub fn auth_return_cookie_value(return_to: &str) -> Cookie<'static> {\n- Cookie::build((AUTH_RETURN_COOKIE, return_to.to_string()))\n- .http_only(true)\n- .same_site(SameSite::Lax)\n- .path(\"/\")\n- .build()\n+ build_cookie(AUTH_RETURN_COOKIE, return_to.to_string())\n }\n \n pub fn clear_auth_return_cookie() -> Cookie<'static> {\n- Cookie::build((AUTH_RETURN_COOKIE, \"\"))\n- .http_only(true)\n- .same_site(SameSite::Lax)\n- .path(\"/\")\n- .removal()\n- .build()\n+ clear_cookie(AUTH_RETURN_COOKIE)\n }\n \n pub fn auth_return_from_jar(jar: &CookieJar) -> Option {\n@@ -213,28 +218,35 @@ pub fn oauth_state_from_jar(jar: &CookieJar) -> Option {\n jar.get(OAUTH_STATE_COOKIE).map(|c| c.value().to_string())\n }\n \n-pub fn actor_uuid_for_vote(db: &Db, session_id: Option<&str>) -> String {\n- let Some(session_id) = session_id else {\n- return DEFAULT_ACTOR_UUID.to_string();\n- };\n- load_session(db, session_id)\n- .ok()\n- .flatten()\n- .filter(|s| s.expires_at > now_ms())\n- .map(|s| s.uuid)\n- .unwrap_or_else(|| DEFAULT_ACTOR_UUID.to_string())\n-}\n-\n #[cfg(test)]\n mod tests {\n use super::*;\n \n #[test]\n- fn missing_session_falls_back_to_anon() {\n+ fn missing_session_is_error() {\n+ let dir = tempfile::tempdir().unwrap();\n+ let db = Db::open(dir.path()).unwrap();\n+ assert_eq!(resolve_vote_actor(&db, None).unwrap_err(), \"sign in to vote\");\n+ }\n+\n+ #[test]\n+ fn session_without_pseudonym_is_error() {\n+ let dir = tempfile::tempdir().unwrap();\n+ let db = Db::open(dir.path()).unwrap();\n+ let (id, _) = create_session(&db, DEFAULT_ACTOR_UUID, \"\").unwrap();\n+ assert_eq!(\n+ resolve_vote_actor(&db, Some(&id)).unwrap_err(),\n+ \"choose an alias first\"\n+ );\n+ }\n+\n+ #[test]\n+ fn session_with_pseudonym_resolves() {\n let dir = tempfile::tempdir().unwrap();\n let db = Db::open(dir.path()).unwrap();\n- let actor = resolve_vote_actor(&db, None);\n- assert_eq!(actor.pseudonym, DEFAULT_PSEUDONYM);\n+ let (id, _) = create_session(&db, DEFAULT_ACTOR_UUID, \"alice\").unwrap();\n+ let actor = resolve_vote_actor(&db, Some(&id)).unwrap();\n+ assert_eq!(actor.pseudonym, \"alice\");\n assert_eq!(actor.trust_weight, 1.0);\n }\n }\ndiff --git a/server/src/html/mod.rs b/server/src/html/mod.rs\nindex 46d18b87f1313bf0aeb29955d18f291961057509..3cc3d7bdf55b5cb5d009600f4ade1fcd201a410b 100644\n--- a/server/src/html/mod.rs\n+++ b/server/src/html/mod.rs\n@@ -4,11 +4,13 @@ use axum::{\n http::{header, StatusCode, Uri},\n response::{IntoResponse, Response},\n };\n+use axum_extra::extract::cookie::CookieJar;\n use maud::{html, Markup, DOCTYPE};\n \n use std::collections::HashSet;\n \n use crate::{\n+ auth::nav_pseudonym,\n fetch::html::entity_section,\n form_template::template_json_compact,\n path_types::ItemId,\n@@ -126,7 +128,7 @@ pub fn now_ms() -> i64 {\n t.as_millis() as i64\n }\n \n-pub(crate) fn layout(title: &str, body: Markup, views: u64) -> Markup {\n+pub(crate) fn layout(title: &str, body: Markup, views: u64, nav_user: Option<&str>) -> Markup {\n let ver = asset_version();\n let css_href = format!(\"/static/sorter.css?v={ver}\");\n let js_src = format!(\"/static/sorter_ui.js?v={ver}\");\n@@ -145,7 +147,15 @@ pub(crate) fn layout(title: &str, body: Markup, views: u64) -> Markup {\n span class=\"view-meta muted\" { (views) \" views\" }\n }\n nav class=\"top-nav\" {\n- a href=\"/login\" { \"login\" }\n+ @if let Some(name) = nav_user {\n+ span class=\"top-nav-user\" data-testid=\"nav-user\" { (name) }\n+ a href=\"/login\" { \"account\" }\n+ form class=\"top-nav-logout\" method=\"post\" action=\"/auth/logout\" data-navigate=\"full\" {\n+ button type=\"submit\" data-testid=\"nav-logout\" { \"log out\" }\n+ }\n+ } @else {\n+ a href=\"/login\" data-testid=\"nav-login\" { \"login\" }\n+ }\n }\n div id=\"errors\" {}\n (body)\n@@ -481,10 +491,11 @@ pub fn input_panel(query: &str, error: Option<&str>) -> Markup {\n }\n }\n \n-async fn item_page(state: AppState, uri: Uri, item: ItemId) -> Markup {\n+async fn item_page(state: AppState, uri: Uri, item: ItemId, jar: CookieJar) -> Markup {\n let path = uri.path().to_string();\n state.views.increment(path.clone());\n let views = state.views.get_views(&path);\n+ let nav_user = nav_pseudonym(state.projection_store.db(), &jar);\n \n let tree = state\n .scope_tree(&item)\n@@ -513,16 +524,24 @@ async fn item_page(state: AppState, uri: Uri, item: ItemId) -> Markup {\n (ranking_panel(&item, node, &tree))\n }\n };\n- layout(\"sorter2\", body, views)\n+ layout(\"sorter2\", body, views, nav_user.as_deref())\n }\n \n-pub async fn home(State(state): State, uri: Uri) -> impl IntoResponse {\n- item_page(state, uri, ItemId::root()).await\n+pub async fn home(\n+ State(state): State,\n+ jar: CookieJar,\n+ uri: Uri,\n+) -> impl IntoResponse {\n+ item_page(state, uri, ItemId::root(), jar).await\n }\n \n-pub async fn browse(State(state): State, uri: Uri) -> impl IntoResponse {\n+pub async fn browse(\n+ State(state): State,\n+ jar: CookieJar,\n+ uri: Uri,\n+) -> impl IntoResponse {\n let item = ItemId::from_browse_uri(uri.path()).unwrap_or(ItemId::root());\n- item_page(state, uri, item).await\n+ item_page(state, uri, item, jar).await\n }\n \n #[cfg(test)]\ndiff --git a/server/src/html/vote.rs b/server/src/html/vote.rs\nindex 3aa00c417c89a9cab3417c650b50ed7c73f08e20..cadbec188b17a48a63b269c0e2fa2ea8ffedd7ed 100644\n--- a/server/src/html/vote.rs\n+++ b/server/src/html/vote.rs\n@@ -4,11 +4,13 @@ use axum::{\n extract::{Query, State},\n response::{Html, IntoResponse},\n };\n+use axum_extra::extract::cookie::CookieJar;\n use maud::{html, Markup};\n use serde::Deserialize;\n use std::collections::HashSet;\n \n use crate::{\n+ auth::nav_pseudonym,\n fetch::html::entity_section,\n form_template::template_json_compact,\n html::{ranking_panel_with_highlights, scope_theme_style, JsBuilder},\n@@ -262,6 +264,7 @@ fn suggest_next(\n \n pub async fn vote_page(\n State(state): State,\n+ jar: CookieJar,\n Query(q): Query,\n ) -> impl IntoResponse {\n let parent = parse_item_param(&q.parent);\n@@ -329,8 +332,9 @@ pub async fn vote_page(\n let path = format!(\"/vote?parent={}\", urlencoding::encode(parent.as_str()));\n state.views.increment(path.clone());\n let views = state.views.get_views(&path);\n+ let nav_user = nav_pseudonym(state.projection_store.db(), &jar);\n \n- Html(layout(&title, body, views).into_string()).into_response()\n+ Html(layout(&title, body, views, nav_user.as_deref()).into_string()).into_response()\n }\n \n #[cfg(test)]\ndiff --git a/server/static/sorter.css b/server/static/sorter.css\nindex e66a1e6c1acc473c8ff1ddb1e16e75a82d33741c..257280b6b490c65222e580a325b77351cac6cc6b 100644\n--- a/server/static/sorter.css\n+++ b/server/static/sorter.css\n@@ -34,6 +34,47 @@ body {\n font-size: 0.75rem;\n }\n \n+.top-nav {\n+ display: flex;\n+ align-items: center;\n+ justify-content: flex-end;\n+ gap: 0.75rem;\n+ padding: 0.5rem 1rem;\n+ font-size: 0.875rem;\n+}\n+\n+.top-nav a {\n+ color: var(--muted);\n+ text-decoration: none;\n+}\n+\n+.top-nav a:hover {\n+ color: var(--fg);\n+}\n+\n+.top-nav-user {\n+ color: var(--fg);\n+ font-weight: 600;\n+}\n+\n+.top-nav-logout {\n+ display: inline;\n+ margin: 0;\n+}\n+\n+.top-nav-logout button {\n+ background: none;\n+ border: none;\n+ padding: 0;\n+ color: var(--muted);\n+ font: inherit;\n+ cursor: pointer;\n+}\n+\n+.top-nav-logout button:hover {\n+ color: var(--fg);\n+}\n+\n .btn-primary {\n background: var(--accent);\n color: var(--accent-fg, #0f1115);\ndiff --git a/test/support/harness.clj b/test/support/harness.clj\nindex 3f05951f418258642dcacb4a10ccccc8bfbe8748..4505ece5aa193e826ca61c52f1467d252080d66b 100644\n--- a/test/support/harness.clj\n+++ b/test/support/harness.clj\n@@ -43,6 +43,7 @@\n \"SORTER2_VIEWS_LOG\" (str data-dir \"/views.jsonl\")\n \"PORT\" (str app-port)\n \"SORTER2_BASE_URL\" (str \"http://127.0.0.1:\" app-port)\n+ \"SORTER2_ALLOW_MOCK_OAUTH\" \"1\"\n \"GITHUB_CLIENT_ID\" \"test-client\"\n \"GITHUB_CLIENT_SECRET\" \"test-secret\"\n \"GITHUB_OAUTH_BASE\" (str \"http://127.0.0.1:\" oauth-port)\n","role":"user"}],"model":"~anthropic/claude-sonnet-latest"}