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: [a888d56c] refactor: centralize path identity in slug-types Move canonicalization and CanonicalItemUrl into types::paths with GardenItemUrl, ForumThreadUrl, and TildeOntologyPath for JSON hrefs. Server canonical_path and path_types re-export slug-types; RPC and validation build hrefs via those types instead of string helpers. Made-with: Cursor Side A — unified diff (full patch): diff --git a/server/src/api/helpers.rs b/server/src/api/helpers.rs index 9b71491e9f9efc44a2a4beba09be8f64bd2ff2ee..03b3e77911ccd662bec8635345dafe2593cf242e 100644 --- a/server/src/api/helpers.rs +++ b/server/src/api/helpers.rs @@ -4,12 +4,12 @@ use axum::{ Json, }; use sha2::{Digest, Sha256}; +use slug_types::paths::{CanonicalItemUrl, GardenItemUrl}; use slug_types::*; use std::collections::HashMap; use crate::{ canonical_path::canonicalize_item, - path_types::CanonicalItemUrl, ranking::connected_components_from_voted_pairs, }; @@ -30,64 +30,6 @@ pub fn now_ms() -> i64 { t.as_millis() as i64 } -/// Serialize a canonical item for JSON: absolute URLs stay as-is; bare paths get a `/` prefix. -pub fn item_path_for_api(item: &str) -> String { - if item.starts_with("http://") || item.starts_with("https://") { - item.to_string() - } else { - format!("/{}", item) - } -} - -/// Same as [`item_path_for_api`], but for private rooms ontology items are prefixed with -/// `/r/{short}/{slug}` so the URL matches the web app (`/r/…/~/…` routes). -pub fn item_path_for_api_in_room(item: &str, room_wire: &str) -> String { - let room = room_wire.trim(); - if room.is_empty() || room == "public" { - return item_path_for_api(item); - } - let Some((short, slug)) = room.split_once('/') else { - return item_path_for_api(item); - }; - if short.is_empty() || slug.is_empty() { - return item_path_for_api(item); - } - let Some(c) = CanonicalItemUrl::parse(item) else { - return item_path_for_api(item); - }; - let root = CanonicalItemUrl::ontology_root(); - let item_norm = c.as_str().trim_end_matches('/'); - let root_norm = root.as_str().trim_end_matches('/'); - if let Some(tail) = c.tilde_tail() { - return if tail.is_empty() { - format!("https://slug.social/r/{short}/{slug}/~") - } else { - format!("https://slug.social/r/{short}/{slug}/~/{}", tail) - }; - } - if item_norm == root_norm { - return format!("https://slug.social/r/{short}/{slug}/~"); - } - item_path_for_api(item) -} - -/// Absolute thread URL for forum JSON (`/t/…` vs `/r/…/t/…`). -pub fn forum_thread_web_url(room_wire: &str, thread_tag: &str) -> String { - let room = room_wire.trim(); - let tag = thread_tag.trim().trim_start_matches('#'); - if room.is_empty() || room == "public" { - format!("https://slug.social/t/{tag}") - } else if let Some((short, slug)) = room.split_once('/') { - if short.is_empty() || slug.is_empty() { - format!("https://slug.social/t/{tag}") - } else { - format!("https://slug.social/r/{short}/{slug}/t/{tag}") - } - } else { - format!("https://slug.social/t/{tag}") - } -} - /// Resolve an item path as a first-class canonical path. pub fn resolve_item(item: &str) -> Result { let canonical = canonicalize_item(item); @@ -109,14 +51,12 @@ pub fn parse_parent_specs(parent: Option<&String>) -> Vec { } /// Apply offset+limit pagination to the flattened component rankings. -/// Items are flattened in component order (largest component first), then unranked last. -/// Returns (components, unranked_items) after the window. pub fn paginate_rankings( components: Vec, - unranked_items: Vec, + unranked_items: Vec, offset: usize, limit: Option, -) -> (Vec, Vec) { +) -> (Vec, Vec) { let mut remaining_skip = offset; let mut remaining_take = limit.unwrap_or(usize::MAX); let mut out_components: Vec = Vec::new(); @@ -141,7 +81,7 @@ pub fn paginate_rankings( }); } - let out_unranked: Vec = if remaining_take > 0 { + let out_unranked: Vec = if remaining_take > 0 { unranked_items .into_iter() .skip(remaining_skip) @@ -183,11 +123,9 @@ pub fn is_pair_voted(group: &crate::reducer::GroupState, a: &str, b: &str) -> bo group.voted_pairs.contains(&(i, j)) } -/// Compute graph connectivity stats for a set of items within the ranking group. pub fn compute_connectivity_stats(group: &crate::reducer::GroupState, pool: &[String]) -> ConnectivityStats { let n = pool.len(); - // Map pool items to global indices (items not yet in the group get no index) let global_idxs: Vec> = pool .iter() .map(|it| { @@ -197,7 +135,6 @@ pub fn compute_connectivity_stats(group: &crate::reducer::GroupState, pool: &[St .collect(); let present: Vec = global_idxs.iter().filter_map(|x| *x).collect(); - // Build local index mapping for items that exist in the ranking group let global_to_local: HashMap = present .iter() .enumerate() @@ -213,7 +150,6 @@ pub fn compute_connectivity_stats(group: &crate::reducer::GroupState, pool: &[St }), ); - // Items not in the ranking group at all are also isolates let items_not_in_group = global_idxs.iter().filter(|x| x.is_none()).count(); let num_components = comps.len() + isolates.len() + items_not_in_group; @@ -237,52 +173,3 @@ pub fn vote_touches_path(a: &str, b: &str, parent_canon: &str) -> bool { let under = |item: &str| item == parent_canon || item.starts_with(&format!("{}/", parent_canon)); under(a) || under(b) } - -#[cfg(test)] -mod wire_url_tests { - use super::{forum_thread_web_url, item_path_for_api_in_room}; - - #[test] - fn public_room_unchanged() { - let u = "https://slug.social/~/a/b"; - assert_eq!(item_path_for_api_in_room(u, "public"), u); - } - - #[test] - fn private_room_prefixes_ontology() { - assert_eq!( - item_path_for_api_in_room("https://slug.social/~/topic/x", "9ab12cd/my-room"), - "https://slug.social/r/9ab12cd/my-room/~/topic/x" - ); - } - - #[test] - fn private_room_ontology_root() { - assert_eq!( - item_path_for_api_in_room("https://slug.social/~", "9ab12cd/my-room"), - "https://slug.social/r/9ab12cd/my-room/~" - ); - assert_eq!( - item_path_for_api_in_room("https://slug.social/~/", "9ab12cd/my-room"), - "https://slug.social/r/9ab12cd/my-room/~" - ); - } - - #[test] - fn external_url_untouched_in_private_room() { - let u = "https://example.com/z"; - assert_eq!(item_path_for_api_in_room(u, "9ab12cd/my-room"), u); - } - - #[test] - fn forum_web_public_vs_room() { - assert_eq!( - forum_thread_web_url("public", "debate"), - "https://slug.social/t/debate" - ); - assert_eq!( - forum_thread_web_url("9ab12cd/my-room", "#debate"), - "https://slug.social/r/9ab12cd/my-room/t/debate" - ); - } -} diff --git a/server/src/api/mod.rs b/server/src/api/mod.rs index 042aa248305f9362a3be78f9eea2a5abf6ba707a..cf22cb0129366c3aed031bc86f3197a4321cb806 100644 --- a/server/src/api/mod.rs +++ b/server/src/api/mod.rs @@ -24,8 +24,7 @@ pub use auth::{ pub use helpers::{ api_error, compute_connectivity_stats, is_pair_voted, now_ms, paginate_rankings, - parse_parent_specs, pick_random_distinct, sha256_hex, resolve_item, vote_touches_path, - item_path_for_api, + parse_parent_specs, pick_random_distinct, resolve_item, sha256_hex, vote_touches_path, }; pub use rpc::handle_rpc_batch; diff --git a/server/src/api/rpc.rs b/server/src/api/rpc.rs index 5b91f5836625eedbb1cd9423168046e3fb576c17..5f7d50188f1381267402f2e57e671234ef5db2fd 100644 --- a/server/src/api/rpc.rs +++ b/server/src/api/rpc.rs @@ -8,6 +8,7 @@ use axum::{ Json, }; use rand::seq::SliceRandom; +use slug_types::paths::{ForumThreadUrl, GardenItemUrl, TildeOntologyPath}; use slug_types::*; use crate::{ @@ -27,9 +28,8 @@ use crate::{ use super::auth::verify_bearer_principal; use super::helpers::{ - compute_connectivity_stats, forum_thread_web_url, is_pair_voted, item_path_for_api, - item_path_for_api_in_room, now_ms, paginate_rankings, parse_parent_specs, pick_random_distinct, - resolve_item, vote_touches_path, + compute_connectivity_stats, is_pair_voted, now_ms, paginate_rankings, parse_parent_specs, + pick_random_distinct, resolve_item, vote_touches_path, }; use super::validate::{normalize_room_and_thread, validate_ingest_document}; @@ -184,7 +184,7 @@ fn compute_scope_rank_changes( }; if changed { changes.push(RankChange { - item: item_path_for_api_in_room(&item, room_wire), + item: GardenItemUrl::from_storage_str(&item, room_wire), before: b, after: a, }); @@ -206,7 +206,7 @@ fn compute_scope_rank_changes( parent: if parent.is_empty() { "/".to_string() } else { - item_path_for_api_in_room(parent, room_wire) + GardenItemUrl::from_storage_str(parent, room_wire).into_inner() }, changes, }) @@ -302,7 +302,7 @@ fn build_rank_response_for_content( .ranked .into_iter() .map(|r| RankRow { - item: item_path_for_api_in_room(r.item.as_str(), room_wire), + item: GardenItemUrl::from_stored(&r.item, room_wire), percent: if want_percent { Some((r.score / max_score) * 100.0) } else { @@ -315,10 +315,10 @@ fn build_rank_response_for_content( }) .collect(); - let prefixed_unranked: Vec = rankings + let prefixed_unranked: Vec = rankings .unranked_items .into_iter() - .map(|s| item_path_for_api_in_room(s.as_str(), room_wire)) + .map(|s| GardenItemUrl::from_stored(&s, room_wire)) .collect(); let (components, unranked_items) = if offset > 0 || limit.is_some() { @@ -537,13 +537,13 @@ async fn rpc_post( ( "npx slugsocial public garden pair".to_string(), "npx slugsocial public garden rank".to_string(), - forum_thread_web_url("public", &thread_id), + ForumThreadUrl::from_room_tag("public", &thread_id), ) } else { ( format!("npx slugsocial private {room_key} garden pair"), format!("npx slugsocial private {room_key} garden rank"), - forum_thread_web_url(&room_key, &thread_id), + ForumThreadUrl::from_room_tag(&room_key, &thread_id), ) }; @@ -664,7 +664,7 @@ async fn rpc_check( .ranked .into_iter() .map(|r| RankRow { - item: item_path_for_api_in_room(r.item.as_str(), &room_key), + item: GardenItemUrl::from_stored(&r.item, &room_key), score: r.score, percent: None, }) @@ -672,12 +672,12 @@ async fn rpc_check( }) .collect(); CheckScopeRanking { - parent: item_path_for_api_in_room(parent.as_str(), &room_key), + parent: GardenItemUrl::from_stored(parent, &room_key).into_inner(), components, unranked_items: scoped .unranked_items .into_iter() - .map(|it| item_path_for_api_in_room(it.as_str(), &room_key)) + .map(|it| GardenItemUrl::from_stored(&it, &room_key)) .collect(), } }) @@ -687,13 +687,13 @@ async fn rpc_check( vec![ "npx slugsocial public forum post --delegate ".to_string(), "npx slugsocial public forum list".to_string(), - forum_thread_web_url("public", &thread_id), + ForumThreadUrl::from_room_tag("public", &thread_id).into_inner(), ] } else { vec![ format!("npx slugsocial private {room_key} forum post --delegate "), format!("npx slugsocial private {room_key} forum list"), - forum_thread_web_url(&room_key, &thread_id), + ForumThreadUrl::from_room_tag(&room_key, &thread_id).into_inner(), ] }; @@ -717,7 +717,7 @@ fn rpc_list_forum_threads(reduced: &ReducerState, room: &str) -> ThreadsResponse .map(|((_, tag), ts)| ThreadSummary { thread: format!("#{tag}"), last_activity_ts: ts.last_activity_ts, - web: forum_thread_web_url(room, tag), + web: ForumThreadUrl::from_room_tag(room, tag), }) .collect(); out.sort_by(|a, b| b.last_activity_ts.cmp(&a.last_activity_ts)); @@ -885,7 +885,7 @@ fn rpc_search(reduced: &ReducerState, q: &str, limit: usize, principal: Option<& } if score > 0 { scored_items.push((score, SearchItemHit { - path: item_path_for_api(item.as_str()), + path: GardenItemUrl::from_storage_str(item.as_str(), "public"), body: content.item_bodies.get(item).map(|b| snippet_around(b, &words, 120)), })); } @@ -1058,8 +1058,8 @@ async fn rpc_get_pair(state: &AppState, room: String, parent_path: String) -> Re .collect(); let cs = compute_connectivity_stats(&content.ranking_group, &pool); Ok(RpcResult::Pair(PairResponse { - left: item_path_for_api_in_room(&left, &room), - right: item_path_for_api_in_room(&right, &room), + left: GardenItemUrl::from_storage_str(&left, &room), + right: GardenItemUrl::from_storage_str(&right, &room), left_body: lb, right_body: rb, threads: th, @@ -1137,7 +1137,7 @@ pub async fn handle_rpc_batch( if !content.items.contains(&item) { line_err( "item not found", - Some(format!("{} does not exist", item_path_for_api_in_room(&item_str, &room))), + Some(format!("{} does not exist", GardenItemUrl::from_storage_str(&item_str, &room))), ) } else { const MAX_ITEM_BODY: usize = 10_000; @@ -1160,7 +1160,7 @@ pub async fn handle_rpc_batch( .map(|s| s.iter().cloned().collect()) .unwrap_or_default(); line_ok(RpcResult::GardenItem(ItemResponse { - item: item_path_for_api_in_room(&item_str, &room), + item: GardenItemUrl::from_storage_str(&item_str, &room), body, truncated, body_len, @@ -1554,7 +1554,7 @@ pub async fn handle_rpc_batch( for r in items { let pct = want_percent.then(|| ((r.score - bot) / range * 100.0).clamp(0.0, 100.0)); ranked.push(RankRow { - item: item_path_for_api_in_room(r.item.as_str(), &room), + item: GardenItemUrl::from_storage_str(r.item.as_str(), &room), score: r.score, percent: pct, }); @@ -1574,7 +1574,7 @@ pub async fn handle_rpc_batch( let page: Vec = ranked .into_iter() .chain(unranked.into_iter().map(|it| RankRow { - item: item_path_for_api_in_room(&it, &room), + item: GardenItemUrl::from_storage_str(&it, &room), score: 0.0, percent: want_percent.then_some(0.0), })) @@ -1618,7 +1618,7 @@ pub async fn handle_rpc_batch( if !content.items.contains(&item) { line_err( "item not found", - Some(format!("{} does not exist", item_path_for_api_in_room(&item_str, &room))), + Some(format!("{} does not exist", GardenItemUrl::from_storage_str(&item_str, &room))), ) } else { let votes: Vec = content @@ -1629,8 +1629,8 @@ pub async fn handle_rpc_batch( .take(limit) .map(|v| VoteRow { ts: v.ts, - a: item_path_for_api_in_room(v.a.as_str(), &room), - b: item_path_for_api_in_room(v.b.as_str(), &room), + a: GardenItemUrl::from_stored(&v.a, &room), + b: GardenItemUrl::from_stored(&v.b, &room), ratio: format!("{}:{}", v.ratio_left, v.ratio_right), actor: Some(v.principal.clone()), body: v.body.clone(), @@ -1640,7 +1640,7 @@ pub async fn handle_rpc_batch( }) .unwrap_or_default(); line_ok(RpcResult::Matchup(MatchupResponse { - item: item_path_for_api_in_room(&item_str, &room), + item: GardenItemUrl::from_storage_str(&item_str, &room), votes, })) } @@ -1667,8 +1667,8 @@ pub async fn handle_rpc_batch( if a == item_str || b == item_str { Some(VoteRow { ts: e.ts, - a: item_path_for_api_in_room(&a, &room), - b: item_path_for_api_in_room(&b, &room), + a: GardenItemUrl::from_storage_str(&a, &room), + b: GardenItemUrl::from_storage_str(&b, &room), ratio: format!("{}:{}", ratio_left, ratio_right), actor: reduced.ingests_by_id.get(&e.post_id).map(|ing| ing.principal.clone()), body: explanation, @@ -1704,7 +1704,7 @@ pub async fn handle_rpc_batch( } }).collect(); line_ok(RpcResult::RankHistory(RankHistoryResponse { - item: item_path_for_api_in_room(&item_str, &room), + item: GardenItemUrl::from_storage_str(&item_str, &room), history, })) } @@ -1716,17 +1716,13 @@ pub async fn handle_rpc_batch( } else { let content = content_for_room(&reduced, &room); let parents: HashSet<&str> = content.item_children.keys().map(|s| s.as_str()).collect(); - let mut paths: Vec = content + let mut paths: Vec = content .items .iter() .filter(|p| !parents.contains(p.as_str())) - .map(|p| p.as_str().to_string()) - .collect(); - paths.sort(); - let paths: Vec = paths - .into_iter() - .map(|p| item_path_for_api_in_room(&p, &room)) + .map(|p| GardenItemUrl::from_stored(p, &room)) .collect(); + paths.sort_by(|a, b| a.as_str().cmp(b.as_str())); line_ok(RpcResult::Leaves(LeavesResponse { paths })) } }, @@ -1743,24 +1739,13 @@ pub async fn handle_rpc_batch( let mut v: Vec = roots.iter() .map(|path| { let children = content.item_children.get(path.as_str()).map(|s| s.len()).unwrap_or(0); - let path_label = CanonicalItemUrl::parse(path.as_str()) - .and_then(|c| { - c.tilde_tail().map(|t| { - if t.is_empty() { - "~/".to_string() - } else { - format!("~/{}", t) - } - }) - }) - .unwrap_or_else(|| path.to_string()); PathSummary { - path: path_label, + path: TildeOntologyPath::from_stored(path), children, - web: item_path_for_api_in_room(path.as_str(), &room), + web: GardenItemUrl::from_stored(path, &room), } }).collect(); - v.sort_by(|a, b| a.path.cmp(&b.path)); + v.sort_by(|a, b| a.path.as_str().cmp(b.path.as_str())); v }) .unwrap_or_default(); @@ -1790,8 +1775,8 @@ pub async fn handle_rpc_batch( .take(limit) .map(|v| VoteRow { ts: v.ts, - a: item_path_for_api_in_room(v.a.as_str(), &room), - b: item_path_for_api_in_room(v.b.as_str(), &room), + a: GardenItemUrl::from_stored(&v.a, &room), + b: GardenItemUrl::from_stored(&v.b, &room), ratio: format!("{}:{}", v.ratio_left, v.ratio_right), actor: Some(v.principal.clone()), body: v.body.clone(), diff --git a/server/src/api/validate.rs b/server/src/api/validate.rs index 27150577982f52cbd6d11bb93654dc3d4cf75cc5..a51c783ee9785569b5a44c0b1572471fe00d174b 100644 --- a/server/src/api/validate.rs +++ b/server/src/api/validate.rs @@ -7,8 +7,9 @@ use crate::{ path_types::CanonicalItemUrl, reducer::{ReducerState, ScopeId}, }; +use slug_types::paths::GardenItemUrl; -use super::helpers::{item_path_for_api, resolve_item}; +use super::helpers::resolve_item; #[derive(Debug)] pub struct ValidatedIngest { @@ -22,6 +23,10 @@ pub fn validate_ingest_document( text: &str, scope: &ScopeId, ) -> Result)> { + let room_wire = match scope { + ScopeId::Public => "public", + ScopeId::Room(r) => r.as_str(), + }; let public_content = reduced.public(); let scoped_content = match scope { ScopeId::Public => None, @@ -61,14 +66,14 @@ pub fn validate_ingest_document( let Some(body_text) = body else { return Err(( StatusCode::BAD_REQUEST, - format!("item missing body: {}", item_path_for_api(&item)), + format!("item missing body: {}", GardenItemUrl::from_storage_str(&item, room_wire)), Some("items must be declared with bodies, e.g. `~/path/item { ... }`".to_string()), )); }; if body_text.trim().is_empty() { return Err(( StatusCode::BAD_REQUEST, - format!("item body is empty: {}", item_path_for_api(&item)), + format!("item body is empty: {}", GardenItemUrl::from_storage_str(&item, room_wire)), Some("write at least one sentence inside `{ ... }`".to_string()), )); } @@ -101,7 +106,7 @@ pub fn validate_ingest_document( let key = CanonicalItemUrl((*it).clone()); !defined_in_doc.contains(*it) && !item_exists(&key) }) - .map(|it| item_path_for_api(it)) + .map(|it| GardenItemUrl::from_storage_str(it, room_wire).into_inner()) .collect(); if !missing.is_empty() { return Err(( @@ -119,7 +124,7 @@ pub fn validate_ingest_document( let key = CanonicalItemUrl((*it).clone()); !defined_in_doc.contains(*it) && !body_exists(&key) }) - .map(|it| item_path_for_api(it)) + .map(|it| GardenItemUrl::from_storage_str(it, room_wire).into_inner()) .collect(); if !missing_body.is_empty() { return Err(( diff --git a/server/src/canonical_path.rs b/server/src/canonical_path.rs index 5c0febe883d8b3978a25896ed0d71df8509a8717..8a1998025121838b0867f8c5ddbd28aea41a23d2 100644 --- a/server/src/canonical_path.rs +++ b/server/src/canonical_path.rs @@ -1,92 +1,3 @@ -//! Normalization for thread tags and ontology item URLs (DSL ↔ stored canonical form). -//! Not event types — see `events` and `path_types`. +//! Re-exports — implementations live in `slug-types` (`paths` module). -/// Thread / public tag: stored without leading `#`, lowercase. -pub fn canonicalize_tag(input: &str) -> String { - input.trim().trim_start_matches('#').to_lowercase() -} - -/// Ontology item reference → canonical absolute URL on the slug host. -pub fn canonicalize_item(input: &str) -> String { - let s = input.trim(); - if s.is_empty() { - return String::new(); - } - - if let Some(rest) = s.strip_prefix("https://") { - let (host, tail) = rest.split_once('/').map_or((rest, ""), |(h, t)| (h, t)); - let host = host.trim().to_lowercase(); - if tail.is_empty() { - return format!("https://{}", host); - } else { - return format!("https://{}/{}", host, tail); - } - } - if let Some(rest) = s.strip_prefix("http://") { - let (host, tail) = rest.split_once('/').map_or((rest, ""), |(h, t)| (h, t)); - let host = host.trim().to_lowercase(); - if tail.is_empty() { - return format!("http://{}", host); - } else { - return format!("http://{}/{}", host, tail); - } - } - - let is_tilde = s.starts_with("~/"); - let rest = s.strip_prefix("~/").or_else(|| s.strip_prefix("/")).unwrap_or(s); - - let tail = rest - .split('/') - .filter_map(|seg| { - let t = seg.trim(); - if t.is_empty() { - None - } else { - Some(t.to_lowercase()) - } - }) - .collect::>() - .join("/"); - - if is_tilde { - format!("https://slug.social/~/{}", tail) - } else if tail.is_empty() { - "https://slug.social".to_string() - } else { - format!("https://slug.social/{}", tail) - } -} - -pub fn item_path_segments(input: &str) -> Vec { - let canonical = canonicalize_item(input); - if canonical.is_empty() { - return vec![]; - } - - if let Some(rest) = canonical.strip_prefix("https://") { - let (host, tail) = rest.split_once('/').map_or((rest, ""), |(h, t)| (h, t)); - let mut out = vec![format!("https://{}", host)]; - out.extend(tail.split('/').filter(|s| !s.is_empty()).map(|s| s.to_string())); - return out; - } - if let Some(rest) = canonical.strip_prefix("http://") { - let (host, tail) = rest.split_once('/').map_or((rest, ""), |(h, t)| (h, t)); - let mut out = vec![format!("http://{}", host)]; - out.extend(tail.split('/').filter(|s| !s.is_empty()).map(|s| s.to_string())); - return out; - } - - canonical - .split('/') - .filter(|s| !s.is_empty()) - .map(|s| s.to_string()) - .collect() -} - -pub fn item_parent_path(input: &str) -> Option { - let segs = item_path_segments(input); - if segs.len() <= 1 { - return None; - } - Some(segs[..segs.len() - 1].join("/")) -} +pub use slug_types::paths::{canonicalize_item, canonicalize_tag, item_parent_path, item_path_segments}; diff --git a/server/src/html/forum.rs b/server/src/html/forum.rs index ab7970feca47a4431ddc19dab2c8186180b78413..f789e347dc136f8ffd356f4492f0bd76cea04bf0 100644 --- a/server/src/html/forum.rs +++ b/server/src/html/forum.rs @@ -697,7 +697,7 @@ async fn thread_view_inner( let offset = q.offset.unwrap_or(0); let page_ids: Vec = all_ids.into_iter().skip(offset).take(PAGE_SIZE).collect(); - let (display_ingests, subtitle) = { + let (display_ingests, _subtitle) = { let reduced = state.reduced.read().await; let ingests = page_ids .iter() diff --git a/server/src/path_types.rs b/server/src/path_types.rs index cad58cac7da948f92d6ea2a5587d917ab21d57ea..4c8075bbd488f1b9a5eda9e03ced83f6238c6d5e 100644 --- a/server/src/path_types.rs +++ b/server/src/path_types.rs @@ -1,260 +1,3 @@ -//! Path representation types. -//! -//! The codebase currently treats item identifiers as strings in a few different -//! encodings: -//! - user/DSL input like `~/a/b` -//! - canonical item URLs like `https://slug.social/~/a/b` -//! - relative paths within a rooted tree view (e.g. `llms/openai` under a root) -//! -//! This module adds lightweight newtypes so code can be explicit about what it -//! expects without changing core storage formats. -//! -//! **Storage vs wire:** [`CanonicalItemUrl`] values are shared across scopes -//! (`https://slug.social/~/…`); which [`crate::reducer::ContentState`] they live in -//! is determined by scope, not by embedding the room id in the string. For JSON/RPC -//! and browser links in a private room, use [`crate::api::helpers::item_path_for_api_in_room`] -//! so ontology items become `https://slug.social/r/{short}/{slug}/~/…`. +//! Re-exports — implementations live in `slug-types` (`paths` module). -use std::borrow::Borrow; -use std::fmt; - -use serde::{Deserialize, Serialize}; - -use crate::canonical_path::canonicalize_item; - -/// Canonical item identifier as produced by `canonical_path::canonicalize_item`. -/// -/// In practice this is usually: -/// - `https://slug.social/~/...` for ontology items, or -/// - `https://...` / `http://...` for URL items. -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] -pub struct CanonicalItemUrl(pub String); - -impl CanonicalItemUrl { - pub fn parse(input: &str) -> Option { - let c = canonicalize_item(input); - if c.is_empty() { - None - } else { - Some(Self(c)) - } - } - - pub fn as_str(&self) -> &str { - &self.0 - } - - /// Returns the `~/...` tail for ontology items (`https://slug.social/~/...`). - pub fn tilde_tail(&self) -> Option<&str> { - self.0.strip_prefix("https://slug.social/~/") - } - - /// Returns the final non-empty `/`-separated segment of the path. - /// - /// `https://slug.social/~/a/b/c` → `"c"` - /// `https://slug.social/~/a` → `"a"` - pub fn last_segment(&self) -> &str { - self.0 - .rsplit('/') - .find(|s| !s.is_empty()) - .unwrap_or(self.0.as_str()) - } - - /// The ontology root key as stored in `item_children`: `"https://slug.social/~"`. - /// Use this (not `parse("~/")`) when looking up top-level children. - pub fn ontology_root() -> Self { - Self("https://slug.social/~".to_string()) - } - - /// Returns the parent of this canonical item URL by stripping the last - /// path segment, or `None` if there is no parent (already at root). - /// - /// `https://slug.social/~/a/b/c` → `Some("https://slug.social/~/a/b")` - /// `https://slug.social/~/a` → `Some("https://slug.social/~")` - /// `https://slug.social/~/` → `None` (tilde root) - pub fn parent(&self) -> Option { - // tilde_tail() is None for non-ontology URLs and "" for the root ~/ - if self.tilde_tail().map(|t| t.is_empty()).unwrap_or(true) { - return None; - } - // Strip everything from the last '/' onwards. - let last_slash = self.0.rfind('/')?; - let parent_str = &self.0[..last_slash]; - if parent_str.is_empty() { - None - } else { - Some(Self(parent_str.to_string())) - } - } - - /// Segments of an ontology path suitable for breadcrumb rendering. - /// Strips the `https://slug.social` prefix and returns the `~/…` parts. - /// - /// `https://slug.social/~/a/b` → `["~", "a", "b"]` - /// `https://slug.social/~/` → `["~"]` - pub fn tilde_segments(&self) -> Vec<&str> { - match self.tilde_tail() { - Some(tail) if !tail.is_empty() => { - std::iter::once("~") - .chain(tail.split('/').filter(|s| !s.is_empty())) - .collect() - } - Some(_) => vec!["~"], - None => vec![], - } - } -} - -impl fmt::Display for CanonicalItemUrl { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - self.0.fmt(f) - } -} - -/// Allow `HashMap` to be searched by `&str`. -impl Borrow for CanonicalItemUrl { - fn borrow(&self) -> &str { - &self.0 - } -} - -impl PartialEq for CanonicalItemUrl { - fn eq(&self, other: &str) -> bool { - self.0 == other - } -} - -impl PartialEq<&str> for CanonicalItemUrl { - fn eq(&self, other: &&str) -> bool { - self.0 == *other - } -} - -impl PartialEq for CanonicalItemUrl { - fn eq(&self, other: &String) -> bool { - &self.0 == other - } -} - -/// A `~/...` input path (as used in the DSL and UX). -/// -/// This is not canonicalized; it is a presentation/input form. -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] -pub struct TildePath(pub String); - -impl TildePath { - pub fn new(input: &str) -> Option { - let s = input.trim(); - if s.starts_with("~/") && s.len() > 2 { - Some(Self(s.to_string())) - } else if s == "~/" { - Some(Self("~/".to_string())) - } else { - None - } - } - - pub fn as_str(&self) -> &str { - &self.0 - } - - pub fn canonicalize(&self) -> Option { - CanonicalItemUrl::parse(&self.0) - } -} - -impl fmt::Display for TildePath { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - self.0.fmt(f) - } -} - -/// A path relative to a chosen root in a tree UI. -/// -/// This is intended for compact state encodings (blobs). It must be joined to a -/// root `CanonicalItemUrl` (typically an ontology root) to become a full item. -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] -pub struct RelativePath(pub String); - -impl RelativePath { - pub fn new(input: &str) -> Option { - let s = input.trim().trim_matches('/'); - if s.is_empty() { - Some(Self(String::new())) - } else { - // Keep this permissive: the DSL parser is the main gatekeeper. - Some(Self(s.to_string())) - } - } - - pub fn as_str(&self) -> &str { - &self.0 - } - - /// Join this relative path under a canonical ontology root - /// (`https://slug.social/~/...`) to form a canonical item URL. - pub fn join_under_ontology_root(&self, root: &CanonicalItemUrl) -> Option { - let base = root.tilde_tail()?; - // base is the tail after https://slug.social/~/, e.g. "models" or "models/llms" - let joined = if base.is_empty() { - if self.0.is_empty() { - "~/".to_string() - } else { - format!("~/{}", self.0) - } - } else if self.0.is_empty() { - format!("~/{}", base) - } else { - format!("~/{}/{}", base.trim_end_matches('/'), self.0) - }; - CanonicalItemUrl::parse(&joined) - } -} - -impl fmt::Display for RelativePath { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - self.0.fmt(f) - } -} - - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn canonical_parent_deep() { - let c = CanonicalItemUrl::parse("~/a/b/c").unwrap(); - assert_eq!(c.parent().unwrap().as_str(), "https://slug.social/~/a/b"); - } - - #[test] - fn canonical_parent_one_level() { - let c = CanonicalItemUrl::parse("~/a").unwrap(); - assert_eq!(c.parent().unwrap().as_str(), "https://slug.social/~"); - } - - #[test] - fn canonical_parent_root_is_none() { - let root = CanonicalItemUrl::parse("~/").unwrap(); - assert!(root.parent().is_none()); - } - - #[test] - fn tilde_segments_deep() { - let c = CanonicalItemUrl::parse("~/a/b").unwrap(); - assert_eq!(c.tilde_segments(), vec!["~", "a", "b"]); - } - - #[test] - fn tilde_segments_root() { - let c = CanonicalItemUrl::parse("~/").unwrap(); - assert_eq!(c.tilde_segments(), vec!["~"]); - } - - #[test] - fn tilde_segments_non_ontology_is_empty() { - let c = CanonicalItemUrl::parse("https://example.com/foo").unwrap(); - assert_eq!(c.tilde_segments(), Vec::<&str>::new()); - } -} +pub use slug_types::paths::{CanonicalItemUrl, RelativePath, TildePath}; diff --git a/types/src/lib.rs b/types/src/lib.rs index c1cde3b783d03b02783385b5f07659fb112aae3e..5fc867bf2af84c2ca63fa1cdd03413110ad784a3 100644 --- a/types/src/lib.rs +++ b/types/src/lib.rs @@ -1,7 +1,13 @@ use serde::{Deserialize, Serialize}; +pub mod paths; pub mod timeago; +pub use paths::{ + canonicalize_item, canonicalize_tag, item_parent_path, item_path_segments, CanonicalItemUrl, + ForumThreadUrl, GardenItemUrl, RelativePath, TildeOntologyPath, TildePath, +}; + #[derive(Debug, Serialize, Deserialize)] pub struct ApiError { pub ok: bool, @@ -12,7 +18,7 @@ pub struct ApiError { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RankRow { - pub item: String, + pub item: GardenItemUrl, pub score: f64, /// Normalized score as a percentage of the top item (0–100). Present when ?percent=true. #[serde(skip_serializing_if = "Option::is_none")] @@ -43,7 +49,7 @@ pub struct RankComponent { #[derive(Debug, Serialize, Deserialize)] pub struct RankResponse { pub components: Vec, - pub unranked_items: Vec, + pub unranked_items: Vec, } /// Graph connectivity stats for a scope, returned with pair suggestions. @@ -63,8 +69,8 @@ pub struct ConnectivityStats { #[derive(Debug, Serialize, Deserialize)] pub struct PairResponse { - pub left: String, - pub right: String, + pub left: GardenItemUrl, + pub right: GardenItemUrl, pub left_body: Option, pub right_body: Option, /// Thread tags that discuss either item (connective tissue to forum). @@ -79,7 +85,7 @@ pub struct PairResponse { pub struct NextMoves { pub pair: String, pub rank: String, - pub web: String, + pub web: ForumThreadUrl, } #[derive(Debug, Serialize, Deserialize)] @@ -90,14 +96,14 @@ pub struct PathsResponse { /// Leaf items only (no children). For search / "full path list" — does not scale, works for now. #[derive(Debug, Serialize, Deserialize)] pub struct LeavesResponse { - pub paths: Vec, + pub paths: Vec, } #[derive(Debug, Serialize, Deserialize)] pub struct PathSummary { - pub path: String, + pub path: TildeOntologyPath, pub children: usize, - pub web: String, + pub web: GardenItemUrl, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -109,7 +115,7 @@ pub struct ThreadsResponse { pub struct ThreadSummary { pub thread: String, pub last_activity_ts: i64, - pub web: String, + pub web: ForumThreadUrl, } #[derive(Debug, Serialize, Deserialize)] @@ -178,7 +184,7 @@ pub struct IngestRow { #[derive(Debug, Serialize, Deserialize)] pub struct ItemResponse { - pub item: String, + pub item: GardenItemUrl, pub body: Option, /// True when the body was truncated due to size. Fetch with `?full=true` for the complete body. #[serde(default, skip_serializing_if = "std::ops::Not::not")] @@ -201,15 +207,15 @@ pub struct RecentVotesResponse { /// Vote history for one item (matchup: wins/losses + thread per vote). #[derive(Debug, Serialize, Deserialize)] pub struct MatchupResponse { - pub item: String, + pub item: GardenItemUrl, pub votes: Vec, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct VoteRow { pub ts: i64, - pub a: String, - pub b: String, + pub a: GardenItemUrl, + pub b: GardenItemUrl, pub ratio: String, /// Principal username when present (stored form, no `@`). pub actor: Option, @@ -510,7 +516,7 @@ pub struct RankPosition { /// How one item's rank changed after a vote. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RankChange { - pub item: String, + pub item: GardenItemUrl, /// Position before the vote. None = was unranked (no voted connections in this scope). pub before: Option, /// Position after the vote. None = became unranked (e.g. component split, unlikely). @@ -544,7 +550,7 @@ pub struct CheckScopeRanking { /// Parent scope path (e.g. "/models" or "/" for root). pub parent: String, pub components: Vec, - pub unranked_items: Vec, + pub unranked_items: Vec, } #[derive(Debug, Serialize, Deserialize)] @@ -567,7 +573,7 @@ pub struct SearchResponse { #[derive(Debug, Serialize, Deserialize)] pub struct SearchItemHit { - pub path: String, + pub path: GardenItemUrl, #[serde(skip_serializing_if = "Option::is_none")] pub body: Option, } @@ -614,7 +620,7 @@ pub struct RankHistoryRow { #[derive(Debug, Serialize, Deserialize)] pub struct RankHistoryResponse { - pub item: String, + pub item: GardenItemUrl, pub history: Vec, } diff --git a/types/src/paths.rs b/types/src/paths.rs new file mode 100644 index 0000000000000000000000000000000000000000..2950a7502255927583fbacdfd2adb700f0b0c221 --- /dev/null +++ b/types/src/paths.rs @@ -0,0 +1,498 @@ +//! Canonical paths, storage ids, and JSON href newtypes. All normalization and +//! room-aware URL rules for items live here. + +use std::borrow::Borrow; +use std::fmt; + +use serde::{Deserialize, Serialize}; + +// --------------------------------------------------------------------------- +// Normalization (moved from server `canonical_path`) +// --------------------------------------------------------------------------- + +/// Thread / public tag: stored without leading `#`, lowercase. +pub fn canonicalize_tag(input: &str) -> String { + input.trim().trim_start_matches('#').to_lowercase() +} + +/// Ontology item reference → canonical absolute URL on the slug host. +pub fn canonicalize_item(input: &str) -> String { + let s = input.trim(); + if s.is_empty() { + return String::new(); + } + + if let Some(rest) = s.strip_prefix("https://") { + let (host, tail) = rest.split_once('/').map_or((rest, ""), |(h, t)| (h, t)); + let host = host.trim().to_lowercase(); + if tail.is_empty() { + return format!("https://{}", host); + } else { + return format!("https://{}/{}", host, tail); + } + } + if let Some(rest) = s.strip_prefix("http://") { + let (host, tail) = rest.split_once('/').map_or((rest, ""), |(h, t)| (h, t)); + let host = host.trim().to_lowercase(); + if tail.is_empty() { + return format!("http://{}", host); + } else { + return format!("http://{}/{}", host, tail); + } + } + + let is_tilde = s.starts_with("~/"); + let rest = s.strip_prefix("~/").or_else(|| s.strip_prefix("/")).unwrap_or(s); + + let tail = rest + .split('/') + .filter_map(|seg| { + let t = seg.trim(); + if t.is_empty() { + None + } else { + Some(t.to_lowercase()) + } + }) + .collect::>() + .join("/"); + + if is_tilde { + format!("https://slug.social/~/{}", tail) + } else if tail.is_empty() { + "https://slug.social".to_string() + } else { + format!("https://slug.social/{}", tail) + } +} + +pub fn item_path_segments(input: &str) -> Vec { + let canonical = canonicalize_item(input); + if canonical.is_empty() { + return vec![]; + } + + if let Some(rest) = canonical.strip_prefix("https://") { + let (host, tail) = rest.split_once('/').map_or((rest, ""), |(h, t)| (h, t)); + let mut out = vec![format!("https://{}", host)]; + out.extend(tail.split('/').filter(|s| !s.is_empty()).map(|s| s.to_string())); + return out; + } + if let Some(rest) = canonical.strip_prefix("http://") { + let (host, tail) = rest.split_once('/').map_or((rest, ""), |(h, t)| (h, t)); + let mut out = vec![format!("http://{}", host)]; + out.extend(tail.split('/').filter(|s| !s.is_empty()).map(|s| s.to_string())); + return out; + } + + canonical + .split('/') + .filter(|s| !s.is_empty()) + .map(|s| s.to_string()) + .collect() +} + +pub fn item_parent_path(input: &str) -> Option { + let segs = item_path_segments(input); + if segs.len() <= 1 { + return None; + } + Some(segs[..segs.len() - 1].join("/")) +} + +// --------------------------------------------------------------------------- +// Storage + input path newtypes +// --------------------------------------------------------------------------- + +/// Canonical item identifier as produced by [`canonicalize_item`]. +/// +/// Shared across all scopes; room is not embedded. Usually +/// `https://slug.social/~/…` or an external `http(s)://…` URL item. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub struct CanonicalItemUrl(pub String); + +impl CanonicalItemUrl { + pub fn parse(input: &str) -> Option { + let c = canonicalize_item(input); + if c.is_empty() { + None + } else { + Some(Self(c)) + } + } + + pub fn as_str(&self) -> &str { + &self.0 + } + + pub fn tilde_tail(&self) -> Option<&str> { + self.0.strip_prefix("https://slug.social/~/") + } + + pub fn last_segment(&self) -> &str { + self.0 + .rsplit('/') + .find(|s| !s.is_empty()) + .unwrap_or(self.0.as_str()) + } + + pub fn ontology_root() -> Self { + Self("https://slug.social/~".to_string()) + } + + pub fn parent(&self) -> Option { + if self.tilde_tail().map(|t| t.is_empty()).unwrap_or(true) { + return None; + } + let last_slash = self.0.rfind('/')?; + let parent_str = &self.0[..last_slash]; + if parent_str.is_empty() { + None + } else { + Some(Self(parent_str.to_string())) + } + } + + pub fn tilde_segments(&self) -> Vec<&str> { + match self.tilde_tail() { + Some(tail) if !tail.is_empty() => { + std::iter::once("~") + .chain(tail.split('/').filter(|s| !s.is_empty())) + .collect() + } + Some(_) => vec!["~"], + None => vec![], + } + } + + /// `~/…` list label for ontology items (paths index, CLI). + pub fn tilde_list_label(&self) -> TildeOntologyPath { + TildeOntologyPath::from_stored(self) + } + + /// Absolute href for JSON/RPC and browsers for this stored id in `room`. + pub fn json_href(&self, room_wire: &str) -> GardenItemUrl { + GardenItemUrl::from_stored(self, room_wire) + } +} + +impl fmt::Display for CanonicalItemUrl { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +impl Borrow for CanonicalItemUrl { + fn borrow(&self) -> &str { + &self.0 + } +} + +impl PartialEq for CanonicalItemUrl { + fn eq(&self, other: &str) -> bool { + self.0 == other + } +} + +impl PartialEq<&str> for CanonicalItemUrl { + fn eq(&self, other: &&str) -> bool { + self.0 == *other + } +} + +impl PartialEq for CanonicalItemUrl { + fn eq(&self, other: &String) -> bool { + &self.0 == other + } +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub struct TildePath(pub String); + +impl TildePath { + pub fn new(input: &str) -> Option { + let s = input.trim(); + if s.starts_with("~/") && s.len() > 2 { + Some(Self(s.to_string())) + } else if s == "~/" { + Some(Self("~/".to_string())) + } else { + None + } + } + + pub fn as_str(&self) -> &str { + &self.0 + } + + pub fn canonicalize(&self) -> Option { + CanonicalItemUrl::parse(&self.0) + } +} + +impl fmt::Display for TildePath { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub struct RelativePath(pub String); + +impl RelativePath { + pub fn new(input: &str) -> Option { + let s = input.trim().trim_matches('/'); + if s.is_empty() { + Some(Self(String::new())) + } else { + Some(Self(s.to_string())) + } + } + + pub fn as_str(&self) -> &str { + &self.0 + } + + pub fn join_under_ontology_root(&self, root: &CanonicalItemUrl) -> Option { + let base = root.tilde_tail()?; + let joined = if base.is_empty() { + if self.0.is_empty() { + "~/".to_string() + } else { + format!("~/{}", self.0) + } + } else if self.0.is_empty() { + format!("~/{}", base) + } else { + format!("~/{}/{}", base.trim_end_matches('/'), self.0) + }; + CanonicalItemUrl::parse(&joined) + } +} + +impl fmt::Display for RelativePath { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +// --------------------------------------------------------------------------- +// Wire / JSON: correct-by-construction hrefs +// --------------------------------------------------------------------------- + +fn api_path_or_url(item: &str) -> String { + if item.starts_with("http://") || item.starts_with("https://") { + item.to_string() + } else { + format!("/{}", item) + } +} + +/// Ontology item as serialized in JSON (absolute URL or `/`-prefixed path). +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(transparent)] +pub struct GardenItemUrl(pub String); + +impl GardenItemUrl { + pub fn as_str(&self) -> &str { + &self.0 + } + + pub fn into_inner(self) -> String { + self.0 + } + + /// Stored canonical id + RPC `room` field (`"public"` or `"short/slug"`). + pub fn from_stored(stored: &CanonicalItemUrl, room_wire: &str) -> Self { + Self(garden_href_string(stored.as_str(), room_wire)) + } + + /// Like [`Self::from_stored`] but accepts a string that may already be canonical. + pub fn from_storage_str(stored: &str, room_wire: &str) -> Self { + Self(garden_href_string(stored, room_wire)) + } +} + +impl fmt::Display for GardenItemUrl { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +fn garden_href_string(item: &str, room_wire: &str) -> String { + let room = room_wire.trim(); + if room.is_empty() || room == "public" { + return api_path_or_url(item); + } + let Some((short, slug)) = room.split_once('/') else { + return api_path_or_url(item); + }; + if short.is_empty() || slug.is_empty() { + return api_path_or_url(item); + } + let Some(c) = CanonicalItemUrl::parse(item) else { + return api_path_or_url(item); + }; + let root = CanonicalItemUrl::ontology_root(); + let item_norm = c.as_str().trim_end_matches('/'); + let root_norm = root.as_str().trim_end_matches('/'); + if let Some(tail) = c.tilde_tail() { + return if tail.is_empty() { + format!("https://slug.social/r/{short}/{slug}/~") + } else { + format!("https://slug.social/r/{short}/{slug}/~/{}", tail) + }; + } + if item_norm == root_norm { + return format!("https://slug.social/r/{short}/{slug}/~"); + } + api_path_or_url(item) +} + +/// Forum thread URL for JSON (`/t/…` or `/r/…/t/…` on slug.social). +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(transparent)] +pub struct ForumThreadUrl(pub String); + +impl ForumThreadUrl { + pub fn as_str(&self) -> &str { + &self.0 + } + + pub fn into_inner(self) -> String { + self.0 + } + + pub fn from_room_tag(room_wire: &str, thread_tag: &str) -> Self { + let room = room_wire.trim(); + let tag = thread_tag.trim().trim_start_matches('#'); + Self(if room.is_empty() || room == "public" { + format!("https://slug.social/t/{tag}") + } else if let Some((short, slug)) = room.split_once('/') { + if short.is_empty() || slug.is_empty() { + format!("https://slug.social/t/{tag}") + } else { + format!("https://slug.social/r/{short}/{slug}/t/{tag}") + } + } else { + format!("https://slug.social/t/{tag}") + }) + } +} + +impl fmt::Display for ForumThreadUrl { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +/// `~/a/b` style path for list UIs (paths index `path` field). +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(transparent)] +pub struct TildeOntologyPath(pub String); + +impl TildeOntologyPath { + pub fn from_stored(c: &CanonicalItemUrl) -> Self { + let s = match c.tilde_tail() { + Some(tail) if !tail.is_empty() => format!("~/{}", tail), + Some(_) => "~/".to_string(), + None => c.to_string(), + }; + Self(s) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl fmt::Display for TildeOntologyPath { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn canonical_parent_deep() { + let c = CanonicalItemUrl::parse("~/a/b/c").unwrap(); + assert_eq!(c.parent().unwrap().as_str(), "https://slug.social/~/a/b"); + } + + #[test] + fn canonical_parent_one_level() { + let c = CanonicalItemUrl::parse("~/a").unwrap(); + assert_eq!(c.parent().unwrap().as_str(), "https://slug.social/~"); + } + + #[test] + fn canonical_parent_root_is_none() { + let root = CanonicalItemUrl::parse("~/").unwrap(); + assert!(root.parent().is_none()); + } + + #[test] + fn tilde_segments_deep() { + let c = CanonicalItemUrl::parse("~/a/b").unwrap(); + assert_eq!(c.tilde_segments(), vec!["~", "a", "b"]); + } + + #[test] + fn tilde_segments_root() { + let c = CanonicalItemUrl::parse("~/").unwrap(); + assert_eq!(c.tilde_segments(), vec!["~"]); + } + + #[test] + fn tilde_segments_non_ontology_is_empty() { + let c = CanonicalItemUrl::parse("https://example.com/foo").unwrap(); + assert_eq!(c.tilde_segments(), Vec::<&str>::new()); + } + + #[test] + fn garden_public_passthrough_https() { + let u = "https://slug.social/~/a/b"; + assert_eq!(GardenItemUrl::from_storage_str(u, "public").as_str(), u); + } + + #[test] + fn garden_private_room_prefixes_ontology() { + assert_eq!( + GardenItemUrl::from_storage_str("https://slug.social/~/topic/x", "9ab12cd/my-room").as_str(), + "https://slug.social/r/9ab12cd/my-room/~/topic/x" + ); + } + + #[test] + fn garden_private_room_ontology_root() { + assert_eq!( + GardenItemUrl::from_storage_str("https://slug.social/~", "9ab12cd/my-room").as_str(), + "https://slug.social/r/9ab12cd/my-room/~" + ); + assert_eq!( + GardenItemUrl::from_storage_str("https://slug.social/~/", "9ab12cd/my-room").as_str(), + "https://slug.social/r/9ab12cd/my-room/~" + ); + } + + #[test] + fn garden_external_url_untouched_in_private_room() { + let u = "https://example.com/z"; + assert_eq!(GardenItemUrl::from_storage_str(u, "9ab12cd/my-room").as_str(), u); + } + + #[test] + fn forum_web_public_vs_room() { + assert_eq!( + ForumThreadUrl::from_room_tag("public", "debate").as_str(), + "https://slug.social/t/debate" + ); + assert_eq!( + ForumThreadUrl::from_room_tag("9ab12cd/my-room", "#debate").as_str(), + "https://slug.social/r/9ab12cd/my-room/t/debate" + ); + } +} Side B — contributor: tommy-mor Side B — commit message: [6bda2635] Use title-first items and explanation-first votes (#135) * Require block-first sorter DSL statements Co-authored-by: tommy * Use title-first items with explanation-first votes Co-authored-by: tommy * Update garden vote test DSL fixtures Co-authored-by: tommy * Update browser vote DSL payloads Co-authored-by: tommy --------- Co-authored-by: Cursor Agent Side B — unified diff (full patch): diff --git a/cli/DSL.txt b/cli/DSL.txt index 18f69ef25f01583fddf9fc90e077bb2c3fa72bb6..c9b12bf0edaf73ad252f0a202b7fe61e311df50a 100644 --- a/cli/DSL.txt +++ b/cli/DSL.txt @@ -18,9 +18,20 @@ Blank lines are preserved to maintain paragraph structure. ~/item/a {itembody} ~/python { A high-level scripting language } -~/item/a > ~/python { Item A is better because of X. } -~/python 3:1 ~/go { Python's ecosystem is much richer than Go's. } -https://example.com/lang = ~/go { They are equally good in this context. } +{ +Item A is better because of X. +} +~/item/a > ~/python + +{ +Python's ecosystem is much richer than Go's. +} +~/python 3:1 ~/go + +{ +They are equally good in this context. +} +https://example.com/lang = ~/go ``` SYNTAX RULES @@ -35,7 +46,7 @@ Starts a thread. Tag allows alphanumeric, `-`, `_`, and `/`. Subtitle max 100 ch ~/ { description } ``` Defines an ontology item (garden layer). Paths can be nested (e.g. `~/languages/python`). -A leading `/` alone is **not** allowed in the DSL — use `~/` only. Descriptions (bodies) are wrapped in `{}`. Can be adjacent (e.g. `~/arrived{ready}`). +A leading `/` alone is **not** allowed in the DSL — use `~/` only. Descriptions (bodies) are wrapped in `{}` and follow the item path. ```sorter https://example.com/item { description } @@ -46,7 +57,10 @@ Canonicalization rules for URLs: - `~/` and `https://slug.social/~/` map to the same local item path. ```sorter - { required explanation } +{ +required explanation +} + ``` Compares two items. The explanation is REQUIRED. Comparisons: @@ -65,7 +79,8 @@ When writing bodies or explanations, you can use braces `{}` and code blocks wit 3. Single braces: { ... } ```sorter -~/code { Here is a block: ```def foo(): return {"a": 1}``` } +{ Here is a block: ```def foo(): return {"a": 1}``` } +~/code ``` STYLE diff --git a/cli/GUIDE.sorter b/cli/GUIDE.sorter index 7ea1c2649cb4a323b46f0bf389025079a9c9ab43..86accba72ecea547215d947fb6552e0ead25687c 100644 --- a/cli/GUIDE.sorter +++ b/cli/GUIDE.sorter @@ -83,7 +83,8 @@ Item definitions (attaches a description to an item): ~/thread/item { description } Comparisons: - ~/thread/item-a 3:1 ~/thread/item-b { reasoning } + { reasoning } + ~/thread/item-a 3:1 ~/thread/item-b Ratio formats: 3:1 left is 3x better than right @@ -95,8 +96,7 @@ Shorthand: < means 1:2 (right is better) = means 1:1 (equal) -Bodies can attach without whitespace: - ~/thread/item{Description here} +Item bodies follow the item path. Vote explanations come first; the comparison is the verdict line. } You can write any prose in your posts. These won't be part of the garden but only the thread. @@ -165,7 +165,8 @@ npx slugsocial public forum post languages --delegate '7a3b9c2d-1234-5678-90ab-c ~/languages/python { A high-level language focused on readability. } ~/languages/rust { A systems language focused on safety and performance. } -~/languages/python 2:1 ~/languages/rust { Python has simpler syntax for beginners - fewer symbols, explicit over implicit. Rust's borrow checker adds cognitive load even for simple programs. Both are readable once learned, but Python's learning curve is gentler. } +{ Python has simpler syntax for beginners - fewer symbols, explicit over implicit. Rust's borrow checker adds cognitive load even for simple programs. Both are readable once learned, but Python's learning curve is gentler. } +~/languages/python 2:1 ~/languages/rust EOF # See current ranking diff --git a/ideas/single-thread.md b/ideas/single-thread.md index 86230fe6119c31045c21dbfcb12311b323c02fa8..0efb7199524cc3b308b1922c03e3a99193e4586c 100644 --- a/ideas/single-thread.md +++ b/ideas/single-thread.md @@ -15,7 +15,8 @@ Previously a `.sorter` document could scatter `#tags` throughout: ~/languages/rust {A systems language.} #tools ~/tools/cargo {Rust's build system.} -~/languages/rust 2:1 ~/tools/cargo {Rust is more foundational than its tooling.} +{Rust is more foundational than its tooling.} +~/languages/rust 2:1 ~/tools/cargo ``` The system would fan the ingest into both `#languages` and `#tools` — the same diff --git a/server/src/api/mod.rs b/server/src/api/mod.rs index 9f3c1cc21c2ae157c024a447980a97e190c8f066..920e967b47852ea82fa61b84c457ae3582dd9800 100644 --- a/server/src/api/mod.rs +++ b/server/src/api/mod.rs @@ -72,16 +72,16 @@ mod tests { apply_ingest( &mut reduced, 1, - "~/t/a {a}\n~/t/b {b}\n~/t/a 2:1 ~/t/b {because}\n", + "~/t/a {a}\n~/t/b {b}\n{because}\n~/t/a 2:1 ~/t/b\n", ); - let text = "~/t/a 1:1 ~/t/b {equal}\n"; + let text = "{equal}\n~/t/a 1:1 ~/t/b\n"; validate_ingest_document(&reduced, text, &crate::reducer::ScopeId::Public).unwrap(); } #[test] fn validate_ingest_document_rejects_vote_on_undefined_item() { let reduced = ReducerState::default(); - let text = "~/t/a {x}\n~/t/b 1:1 ~/t/missing {why}\n"; + let text = "~/t/a {x}\n{why}\n~/t/b 1:1 ~/t/missing\n"; let err = validate_ingest_document(&reduced, text, &crate::reducer::ScopeId::Public).unwrap_err(); assert_eq!(err.0, StatusCode::BAD_REQUEST); assert!(err.1.contains("undefined item")); diff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs index 696e7b3605e2e68aee0351116c494c2958506add..7cbda3876451687aa7a55547fc06bbe86ac9d260 100644 --- a/server/src/api/ui_html.rs +++ b/server/src/api/ui_html.rs @@ -222,13 +222,13 @@ async fn dispatch_ui_action( } let text = format!( - "@{}\n{} {}:{} {} {{\n{}\n}}\n", + "@{}\n{{\n{}\n}}\n{} {}:{} {}\n", crate::api::auth::WEB_BROWSER_AGENT, + exp, left_id.as_str(), rl, rr, - right_id.as_str(), - exp + right_id.as_str() ); match rpc_post_with_bearer(state, &session.bearer, room.clone(), thread_tag.clone(), text).await { diff --git a/server/src/dsl.rs b/server/src/dsl.rs index 7962342bd023b3b5061a684d84d4ab164134b111..def8b497c71567016a522648b9630d7038163e41 100644 --- a/server/src/dsl.rs +++ b/server/src/dsl.rs @@ -11,16 +11,21 @@ pub struct Document { /// A single statement in the DSL (or prose when using `parse_full`). #[derive(Debug, Clone, PartialEq, Eq)] pub enum Stmt { - Item { title: String, body: Option }, + Item { + title: String, + body: Option, + }, Vote { item1: String, item2: String, ratio_left: i32, ratio_right: i32, - /// Required non-empty explanation (from trailing `{ ... }`). + /// Required non-empty explanation (from leading `{ ... }`). explanation: String, }, - Prose { text: String }, + Prose { + text: String, + }, } #[derive(Debug, thiserror::Error)] @@ -391,71 +396,46 @@ fn parse_comparison_at(s: &str, i: usize) -> Option<((i32, i32), usize)> { Some(((left, right), j)) } -fn parse_item_statement(stripped: &str, masker: &BlockMasker) -> Result { - // item: ("~/" | "https://..." | "http://...") item_ref body? - // vote: same for both operands. - // - // Important: body token can be adjacent to the item name (no whitespace), - // e.g. "~/arrived{...}" -> "~/arrived__BLOCK_x__". - let s = stripped; - let bytes = s.as_bytes(); - if bytes.is_empty() { - return Err(DslError::Parse("missing item statement".to_string())); +fn parse_block_prefixed_statement( + block_token: &str, + tail: &str, + masker: &BlockMasker, +) -> Result { + // vote: block item_ref comparison item_ref + let s = tail.trim_start(); + if s.is_empty() { + return Err(DslError::Parse( + "missing vote statement after leading explanation block".to_string(), + )); } let (item1, j) = parse_item_name_at(s, 0).ok_or_else(|| DslError::Parse("invalid item name".to_string()))?; + let explanation = masker.extract_body(block_token); + let mut i = skip_ws(s, j); - // Either we have: - // - immediate/whitespace block token => Item - // - comparison => Vote - // - whitespace then block token => Item - // - whitespace then comparison => Vote - let i = skip_ws(s, j); - - // If next is end or a block token => Item. if i >= s.len() { - return Ok(Stmt::Item { - title: item1, - body: None, - }); - } - if let Some((tok, end)) = parse_block_token_at(s, i) { - let body = masker.extract_body(&tok); - let tail = s[end..].trim(); - if !tail.is_empty() { - return Err(DslError::Parse("extra tokens after item".to_string())); - } - return Ok(Stmt::Item { - title: item1, - body: Some(body), - }); + return Err(DslError::Parse( + "leading `{ ... }` blocks are vote explanations; item bodies belong after item paths" + .to_string(), + )); } - // Otherwise parse comparison then "/item2" then REQUIRED body. - let ((ratio_left, ratio_right), mut k) = parse_comparison_at(s, i) + let ((ratio_left, ratio_right), k) = parse_comparison_at(s, i) .ok_or_else(|| DslError::Parse(format!("invalid comparison near: {}", &s[i..])))?; if ratio_left == 0 && ratio_right == 0 { return Err(DslError::Parse( "vote ratio 0:0 is invalid; use 1:1 for a tie or omit the vote".to_string(), )); } - k = skip_ws(s, k); - let (item2, mut m) = parse_item_name_at(s, k) + i = skip_ws(s, k); + let (item2, m) = parse_item_name_at(s, i) .ok_or_else(|| DslError::Parse("invalid rhs item name".to_string()))?; - m = skip_ws(s, m); - - let Some((tok, end)) = parse_block_token_at(s, m) else { - return Err(DslError::Parse( - "missing vote explanation (add a trailing `{ ... }`)".to_string(), - )); - }; - let explanation = masker.extract_body(&tok); + i = skip_ws(s, m); if explanation.trim().is_empty() { return Err(DslError::Parse("empty vote explanation".to_string())); } - m = end; - let tail = s[m..].trim(); + let tail = s[i..].trim(); if !tail.is_empty() { return Err(DslError::Parse("extra tokens after vote".to_string())); } @@ -469,6 +449,35 @@ fn parse_item_statement(stripped: &str, masker: &BlockMasker) -> Result Result { + let (item1, j) = + parse_item_name_at(stripped, 0).ok_or_else(|| DslError::Parse("invalid item name".to_string()))?; + let i = skip_ws(stripped, j); + + if i >= stripped.len() { + return Ok(Stmt::Item { + title: item1, + body: None, + }); + } + + if let Some((tok, end)) = parse_block_token_at(stripped, i) { + let body = masker.extract_body(&tok); + let tail = stripped[end..].trim(); + if !tail.is_empty() { + return Err(DslError::Parse("extra tokens after item".to_string())); + } + return Ok(Stmt::Item { + title: item1, + body: Some(body), + }); + } + + Err(DslError::Parse( + "vote explanations must start with a `{ ... }` block before the comparison".to_string(), + )) +} + fn parse_line(masked_line: &str, masker: &BlockMasker) -> Result, DslError> { let stripped = masked_line.trim_start(); if stripped.is_empty() { @@ -477,27 +486,28 @@ fn parse_line(masked_line: &str, masker: &BlockMasker) -> Result, DslE let first = stripped.chars().next().unwrap(); match first { '#' => Err(DslError::Parse("not a DSL line".to_string())), - ':' => Err(DslError::Parse( - "leading ':' is not supported".to_string(), - )), + ':' => Err(DslError::Parse("leading ':' is not supported".to_string())), '@' => Err(DslError::Parse("not a DSL line".to_string())), + '_' => { + let Some((tok, end)) = parse_block_token_at(stripped, 0) else { + return Err(DslError::Parse("not a DSL line".to_string())); + }; + parse_block_prefixed_statement(&tok, &stripped[end..], masker).map(|stmt| vec![stmt]) + } '/' => Err(DslError::Parse( - "item paths must use `~/` (e.g. `~/languages/python`), not a leading `/`" - .to_string(), + "item paths must use `~/` (e.g. `~/languages/python`), not a leading `/`".to_string(), )), - '~' => { - Ok(vec![parse_item_statement(stripped, masker)?]) - } + '~' => Ok(vec![parse_item_definition_statement(stripped, masker)?]), 'h' => { if stripped.starts_with("https://") || stripped.starts_with("http://") { - Ok(vec![parse_item_statement(stripped, masker)?]) + Ok(vec![parse_item_definition_statement(stripped, masker)?]) } else { Err(DslError::Parse("not a DSL line".to_string())) } } '-' => { if stripped.starts_with("-/") { - Ok(vec![parse_item_statement(stripped, masker)?]) + Ok(vec![parse_item_definition_statement(stripped, masker)?]) } else { Err(DslError::Parse("not a DSL line".to_string())) } @@ -516,6 +526,7 @@ pub fn parse_full(text: &str) -> Result { let (masker, masked) = mask_all(BlockMasker::new(), text); let mut statements: Vec = Vec::new(); let mut prose_buffer: Vec<&str> = Vec::new(); + let mut pending_block: Option = None; let flush_prose = |buf: &mut Vec<&str>, out: &mut Vec, masker: &BlockMasker| { if buf.is_empty() { @@ -529,11 +540,29 @@ pub fn parse_full(text: &str) -> Result { for line in masked.split('\n') { let stripped = line.trim_start(); + if let Some(tok) = pending_block.as_ref() { + if stripped.is_empty() { + continue; + } + if stripped.starts_with("-/") + || stripped.starts_with("~/") + || stripped.starts_with("https://") + || stripped.starts_with("http://") + { + statements.push(parse_block_prefixed_statement(tok, stripped, &masker)?); + pending_block = None; + continue; + } + return Err(DslError::Parse( + "expected vote statement after leading explanation block".to_string(), + )); + } + if !stripped.is_empty() && (stripped.starts_with("-/") || { let c = stripped.chars().next().unwrap(); - ":/!~".contains(c) + ":/!~_".contains(c) } || stripped.starts_with("https://") || stripped.starts_with("http://")) @@ -541,6 +570,13 @@ pub fn parse_full(text: &str) -> Result { // Flush prose buffer first flush_prose(&mut prose_buffer, &mut statements, &masker); + if let Some((tok, end)) = parse_block_token_at(stripped, 0) { + if stripped[end..].trim().is_empty() { + pending_block = Some(tok); + continue; + } + } + // Parse DSL line; DSL statements are not prose, so errors should propagate. statements.extend(parse_line(line, &masker)?); } else { @@ -548,6 +584,12 @@ pub fn parse_full(text: &str) -> Result { } } + if pending_block.is_some() { + return Err(DslError::Parse( + "missing vote statement after leading explanation block".to_string(), + )); + } + // Final flush flush_prose(&mut prose_buffer, &mut statements, &masker); @@ -592,7 +634,7 @@ mod tests { #[test] fn parse_vote_ratio_and_symbols() { - let d1 = parse_full("~/a 3:1 ~/b {because}").unwrap(); + let d1 = parse_full("{because}\n~/a 3:1 ~/b").unwrap(); assert_eq!( d1.statements, vec![Stmt::Vote { @@ -604,7 +646,7 @@ mod tests { }] ); - let d2 = parse_full("~/a > ~/b {because}").unwrap(); + let d2 = parse_full("{because}\n~/a > ~/b").unwrap(); assert_eq!( d2.statements, vec![Stmt::Vote { @@ -616,7 +658,7 @@ mod tests { }] ); - let d3 = parse_full("~/a = ~/b {because}").unwrap(); + let d3 = parse_full("{because}\n~/a = ~/b").unwrap(); assert_eq!( d3.statements, vec![Stmt::Vote { @@ -631,7 +673,7 @@ mod tests { #[test] fn parse_vote_rejects_zero_zero_ratio() { - let err = parse_full("~/a 0:0 ~/b {tie placeholder}").unwrap_err(); + let err = parse_full("{tie placeholder}\n~/a 0:0 ~/b").unwrap_err(); let msg = match err { DslError::Parse(m) => m, }; @@ -667,8 +709,8 @@ mod tests { } #[test] - fn parse_vote_with_attached_body_without_space() { - let input = "~/a 2:1 ~/b{because}"; + fn parse_vote_with_attached_explanation_without_space() { + let input = "{because}~/a 2:1 ~/b"; let doc = parse_full(input).unwrap(); assert_eq!( doc.statements, @@ -697,7 +739,7 @@ mod tests { #[test] fn parse_nested_path_vote() { - let input = "~/whitepaper/a 3:1 ~/whitepaper/b { because }"; + let input = "{ because }\n~/whitepaper/a 3:1 ~/whitepaper/b"; let doc = parse_full(input).unwrap(); assert_eq!( doc.statements, @@ -718,7 +760,10 @@ mod tests { let result = parse_full(input); assert!(result.is_err(), "expected parse error for {input:?}"); assert!( - result.unwrap_err().to_string().contains("leading ':' is not supported"), + result + .unwrap_err() + .to_string() + .contains("leading ':' is not supported"), "wrong error for {input:?}" ); } @@ -741,7 +786,35 @@ mod tests { let result = parse_full(input); assert!(result.is_err(), "vote without explanation should fail"); let err_msg = result.unwrap_err().to_string(); - assert!(err_msg.contains("missing vote explanation"), "error: {}", err_msg); + assert!( + err_msg.contains("vote explanations must start"), + "error: {}", + err_msg + ); + } + + #[test] + fn parse_full_rejects_legacy_trailing_explanation_vote() { + let result = parse_full("~/a 2:1 ~/b {because}"); + assert!(result.is_err(), "legacy vote syntax should fail"); + let err_msg = result.unwrap_err().to_string(); + assert!( + err_msg.contains("vote explanations must start"), + "error: {}", + err_msg + ); + } + + #[test] + fn parse_full_rejects_block_first_item_body() { + let result = parse_full("{body}\n~/a"); + assert!(result.is_err(), "block-first item body syntax should fail"); + let err_msg = result.unwrap_err().to_string(); + assert!( + err_msg.contains("item bodies belong after item paths"), + "error: {}", + err_msg + ); } #[test] @@ -771,7 +844,7 @@ mod tests { #[test] fn parse_url_vote_statement() { - let input = "https://slug.social/~/music/a 3:1 https://slug.social/~/music/b { because }"; + let input = "{ because }\nhttps://slug.social/~/music/a 3:1 https://slug.social/~/music/b"; let doc = parse_full(input).unwrap(); assert_eq!( doc.statements, @@ -785,5 +858,3 @@ mod tests { ); } } - - diff --git a/server/src/html/editor.rs b/server/src/html/editor.rs index 8ff58326eb75806eeec3937f088fa977c7f3886e..216b144a4acef09d0addddd1528e5323433ac832 100644 --- a/server/src/html/editor.rs +++ b/server/src/html/editor.rs @@ -39,7 +39,7 @@ pub async fn editor_page(State(state): State, jar: CookieJar, uri: Uri p class="muted" { "write DSL, see what happens. nothing is saved." } div class="editor-container" { textarea id="editor-input" rows="12" cols="80" - 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 }" + placeholder="your-uuid:rig:provider/model\n#your-thread\n\n{ description }\n~/path/item-a\n{ description }\n~/path/item-b\n\n{ reasoning }\n~/path/item-a 3:1 ~/path/item-b" autocomplete="off" autofocus {} div id="editor-status" class="muted" { "type to check…" } div id="editor-results" {} diff --git a/server/src/html/garden.rs b/server/src/html/garden.rs index 9e08307e636ce7984766168db1187f84b8635201..86b4c184724910bb464682b9025d19ce6cd2050d 100644 --- a/server/src/html/garden.rs +++ b/server/src/html/garden.rs @@ -1454,8 +1454,8 @@ mod tests { ~/topic {root}\n\ ~/topic/a {alpha}\n\ ~/topic/b {beta}\n\ - ~/topic/a 1:9 ~/topic/b {weak for a}\n\ - ~/topic/a 8:2 ~/topic/b {strong for a}\n", + {weak for a}\n ~/topic/a 1:9 ~/topic/b\n\ + {strong for a}\n ~/topic/a 8:2 ~/topic/b\n", ); let content = content_for_garden_view(&reduced, &ScopeId::Public); let page_left = ItemId::parse("~/topic/a").unwrap().normalized_storage(); @@ -1483,8 +1483,10 @@ mod tests { ~/topic {root}\n\ ~/topic/a {alpha}\n\ ~/topic/b {beta}\n\ - ~/topic/a 3:2 ~/topic/b {first vote}\n\ - ~/topic/b 2:3 ~/topic/a {second vote}\n", + {first vote}\n\ + ~/topic/a 3:2 ~/topic/b\n\ + {second vote}\n\ + ~/topic/b 2:3 ~/topic/a\n", ); let content = content_for_garden_view(&reduced, &ScopeId::Public); let a = ItemId::parse("~/topic/a").unwrap().normalized_storage(); @@ -1525,7 +1527,7 @@ mod tests { ~/topic/a {alpha}\n\ ~/topic/b {beta}\n\ ~/topic/c {gamma}\n\ - ~/topic/a 2:1 ~/topic/b {a beats b}\n", + {a beats b}\n ~/topic/a 2:1 ~/topic/b\n", ); let model = build_item_page_view_model(&reduced, &ScopeId::Public, "~/topic/a"); @@ -1545,7 +1547,7 @@ mod tests { ~/topic {root}\n\ ~/topic/a {alpha}\n\ ~/topic/b {beta}\n\ - ~/topic/a 3:1 ~/topic/b {a beats b}\n\ + {a beats b}\n ~/topic/a 3:1 ~/topic/b\n\ ~/topic/kid1 {k1}\n\ ~/topic/kid2 {k2}\n\ ~/topic/kid1/leaf {leaf}\n", @@ -1616,7 +1618,7 @@ mod tests { 1, "9ab12cd/my-room", "@00000000-0000-0000-0000-000000000000:test:local/test\n\ - ~/a {a}\n~/b {b}\n~/a 2:1 ~/b {because}\n", + ~/a {a}\n~/b {b}\n{because}\n~/a 2:1 ~/b\n", ); use crate::path_types::ItemId; let root = ItemId::ontology_root(); diff --git a/server/tests/basic.rs b/server/tests/basic.rs index 4a4faa73e2f0338fc541237104d99ea05b3e599a..2f17ce91091745ce1b5ebd1575248565df3b3514 100644 --- a/server/tests/basic.rs +++ b/server/tests/basic.rs @@ -31,7 +31,7 @@ fn ingest_event(ts: i64, raw: &str) -> Event { fn vote_doc(tag: &str, a: &str, b: &str, left: i32, right: i32) -> String { format!( - "~/{tag}/{a} {{body a}}\n~/{tag}/{b} {{body b}}\n~/{tag}/{a} {left}:{right} ~/{tag}/{b} {{because test}}\n" + "~/{tag}/{a} {{body a}}\n~/{tag}/{b} {{body b}}\n{{because test}}\n~/{tag}/{a} {left}:{right} ~/{tag}/{b}\n" ) } @@ -47,7 +47,7 @@ fn reducer_external_namespace_ranking() { "@00000000-0000-0000-0000-000000000000:test:local/test\n\ -/github.com/iss/1 { one }\n\ -/github.com/iss/2 { two }\n\ - -/github.com/iss/1 2:1 -/github.com/iss/2 { because }\n", + { because }\n -/github.com/iss/1 2:1 -/github.com/iss/2\n", )); let content = state.public(); @@ -77,9 +77,9 @@ fn reducer_and_ranking_linear_chain() { let mut state = ReducerState::default(); // First ingest: define items + vote a > b. - state.apply_event(ingest_event(1, "~/t/a {a}\n~/t/b {b}\n~/t/a 3:1 ~/t/b {because}\n")); + state.apply_event(ingest_event(1, "~/t/a {a}\n~/t/b {b}\n{because}\n~/t/a 3:1 ~/t/b\n")); // Second ingest: define c + vote b > c. - state.apply_event(ingest_event(2, "~/t/c {c}\n~/t/b 3:1 ~/t/c {because}\n")); + state.apply_event(ingest_event(2, "~/t/c {c}\n{because}\n~/t/b 3:1 ~/t/c\n")); let mut group = state.public().ranking_group.clone(); let ranked = ranked_items(&mut group, 20000, 1e-9); @@ -96,15 +96,15 @@ fn reducer_canonicalizes_identifiers() { // Mix of formats across ingests (case + sigils). state.apply_event(ingest_event( 1, - "~/Tag/Item-A {x}\n~/Tag/Item-B {y}\n~/Tag/Item-A 2:1 ~/Tag/Item-B {because}\n", + "~/Tag/Item-A {x}\n~/Tag/Item-B {y}\n{because}\n~/Tag/Item-A 2:1 ~/Tag/Item-B\n", )); state.apply_event(ingest_event( 2, - "~/TAG/ITEM-A 2:1 ~/TAG/ITEM-B {because}\n", + "{because}\n~/TAG/ITEM-A 2:1 ~/TAG/ITEM-B\n", )); state.apply_event(ingest_event( 3, - "~/tag/item-a 2:1 ~/tag/item-b {because}\n", + "{because}\n~/tag/item-a 2:1 ~/tag/item-b\n", )); assert_eq!(state.public().ranking_group.idx_to_item.len(), 2); // Should dedupe to 2 items @@ -135,7 +135,7 @@ fn reducer_handles_item_and_body_from_ingest() { fn reducer_indexes_item_threads_and_vote_thread() { let mut state = ReducerState::default(); // Thread routing is metadata (ingest.thread_tag), not parsed from raw. - let mut ev = match ingest_event(1, "~/sorts/insertion { O(n^2) }\n~/sorts/mergesort { O(n log n) }\n~/sorts/insertion 3:1 ~/sorts/mergesort { simpler for small n }\n") { + let mut ev = match ingest_event(1, "~/sorts/insertion { O(n^2) }\n~/sorts/mergesort { O(n log n) }\n{ simpler for small n }\n~/sorts/insertion 3:1 ~/sorts/mergesort\n") { Event::Ingest(i) => i, _ => unreachable!(), }; @@ -175,11 +175,11 @@ fn reducer_clamps_score_bounds() { let mut state = ReducerState::default(); state.apply_event(ingest_event( 1, - "@00000000-0000-0000-0000-000000000000:test:local/test\n~/t/a {a}\n~/t/b {b}\n~/t/a 1000:1 ~/t/b {huge}\n", + "@00000000-0000-0000-0000-000000000000:test:local/test\n~/t/a {a}\n~/t/b {b}\n{huge}\n~/t/a 1000:1 ~/t/b\n", )); state.apply_event(ingest_event( 2, - "@00000000-0000-0000-0000-000000000000:test:local/test\n~/t/a 1:1000 ~/t/b {huge}\n", + "@00000000-0000-0000-0000-000000000000:test:local/test\n{huge}\n~/t/a 1:1000 ~/t/b\n", )); assert_eq!(state.public().ranking_group.idx_to_item.len(), 2); // Should still work, scores clamped internally @@ -195,15 +195,15 @@ fn ranking_cycle_is_nearly_equal() { let mut state = ReducerState::default(); state.apply_event(ingest_event( 1, - "@00000000-0000-0000-0000-000000000000:test:local/test\n~/rps/rock {r}\n~/rps/scissors {s}\n~/rps/rock 3:1 ~/rps/scissors {because}\n", + "@00000000-0000-0000-0000-000000000000:test:local/test\n~/rps/rock {r}\n~/rps/scissors {s}\n{because}\n~/rps/rock 3:1 ~/rps/scissors\n", )); state.apply_event(ingest_event( 2, - "@00000000-0000-0000-0000-000000000000:test:local/test\n~/rps/paper {p}\n~/rps/scissors 3:1 ~/rps/paper {because}\n", + "@00000000-0000-0000-0000-000000000000:test:local/test\n~/rps/paper {p}\n{because}\n~/rps/scissors 3:1 ~/rps/paper\n", )); state.apply_event(ingest_event( 3, - "@00000000-0000-0000-0000-000000000000:test:local/test\n~/rps/paper 3:1 ~/rps/rock {because}\n", + "@00000000-0000-0000-0000-000000000000:test:local/test\n{because}\n~/rps/paper 3:1 ~/rps/rock\n", )); let mut group = state.public().ranking_group.clone(); @@ -233,7 +233,7 @@ fn ranking_dominant_item_wins() { let mut state = ReducerState::default(); state.apply_event(ingest_event( 1, - "@00000000-0000-0000-0000-000000000000:test:local/test\n~/t/champion {c}\n~/t/b {b}\n~/t/c {c}\n~/t/d {d}\n~/t/champion 10:1 ~/t/b {because}\n~/t/champion 10:1 ~/t/c {because}\n~/t/champion 10:1 ~/t/d {because}\n~/t/b 2:1 ~/t/c {because}\n~/t/c 2:1 ~/t/d {because}\n", + "@00000000-0000-0000-0000-000000000000:test:local/test\n~/t/champion {c}\n~/t/b {b}\n~/t/c {c}\n~/t/d {d}\n{because}\n~/t/champion 10:1 ~/t/b\n{because}\n~/t/champion 10:1 ~/t/c\n{because}\n~/t/champion 10:1 ~/t/d\n{because}\n~/t/b 2:1 ~/t/c\n{because}\n~/t/c 2:1 ~/t/d\n", )); let mut group = state.public().ranking_group.clone(); @@ -248,7 +248,7 @@ fn ranking_neutral_votes_produce_equal_scores() { let mut state = ReducerState::default(); state.apply_event(ingest_event( 1, - "@00000000-0000-0000-0000-000000000000:test:local/test\n~/t/a {a}\n~/t/b {b}\n~/t/c {c}\n~/t/a 1:1 ~/t/b {neutral}\n~/t/b 1:1 ~/t/c {neutral}\n~/t/c 1:1 ~/t/a {neutral}\n", + "@00000000-0000-0000-0000-000000000000:test:local/test\n~/t/a {a}\n~/t/b {b}\n~/t/c {c}\n{neutral}\n~/t/a 1:1 ~/t/b\n{neutral}\n~/t/b 1:1 ~/t/c\n{neutral}\n~/t/c 1:1 ~/t/a\n", )); let mut group = state.public().ranking_group.clone(); @@ -301,8 +301,8 @@ async fn event_log_append_and_load() { let log = EventLog::new(log_path); let events = vec![ - ingest_event(1, "~/a {x}\n~/b {y}\n~/a 2:1 ~/b {because}\n"), - ingest_event(2, "~/b 3:1 ~/c {because}\n"), + ingest_event(1, "~/a {x}\n~/b {y}\n{because}\n~/a 2:1 ~/b\n"), + ingest_event(2, "{because}\n~/b 3:1 ~/c\n"), ]; for ev in &events { @@ -323,7 +323,7 @@ async fn event_log_handles_corrupt_lines() { let log = EventLog::new(&log_path); // Write valid events using the log itself, then manually corrupt one line. - log.append(&ingest_event(1, "~/a {x}\n~/b {y}\n~/a 2:1 ~/b {because}\n")) + log.append(&ingest_event(1, "~/a {x}\n~/b {y}\n{because}\n~/a 2:1 ~/b\n")) .await .unwrap(); @@ -332,7 +332,7 @@ async fn event_log_handles_corrupt_lines() { let mut f = fs::OpenOptions::new().append(true).open(&log_path).unwrap(); writeln!(f, "not json at all").unwrap(); - log.append(&ingest_event(2, "~/b 3:1 ~/c {because}\n")) + log.append(&ingest_event(2, "{because}\n~/b 3:1 ~/c\n")) .await .unwrap(); @@ -351,7 +351,7 @@ async fn event_log_creates_parent_dirs() { let log_path = tmp.path().join("subdir").join("nested").join("events.jsonl"); let log = EventLog::new(&log_path); - log.append(&ingest_event(1, "~/a {x}\n~/b {y}\n~/a 2:1 ~/b {because}\n")) + log.append(&ingest_event(1, "~/a {x}\n~/b {y}\n{because}\n~/a 2:1 ~/b\n")) .await .unwrap(); assert!(log_path.exists()); @@ -379,7 +379,7 @@ async fn full_workflow_reducer_and_ranking() { state.apply_event(ingest_event( 1, - "~/langs/rust {Systems language}\n~/langs/go {Simple concurrency}\n~/langs/rust 3:1 ~/langs/go {because}\n", + "~/langs/rust {Systems language}\n~/langs/go {Simple concurrency}\n{because}\n~/langs/rust 3:1 ~/langs/go\n", )); let mut group = state.public().ranking_group.clone(); @@ -452,21 +452,21 @@ fn ranking_repeated_votes_normalized() { let mut state_once = ReducerState::default(); state_once.apply_event(ingest_event( 1, - "~/norm/a {a}\n~/norm/b {b}\n~/norm/a 3:1 ~/norm/b {vote}\n", + "~/norm/a {a}\n~/norm/b {b}\n{vote}\n~/norm/a 3:1 ~/norm/b\n", )); let mut state_many = ReducerState::default(); state_many.apply_event(ingest_event( 1, - "~/norm/a {a}\n~/norm/b {b}\n~/norm/a 3:1 ~/norm/b {vote1}\n", + "~/norm/a {a}\n~/norm/b {b}\n{vote1}\n~/norm/a 3:1 ~/norm/b\n", )); state_many.apply_event(ingest_event( 2, - "~/norm/a 3:1 ~/norm/b {vote2}\n", + "{vote2}\n~/norm/a 3:1 ~/norm/b\n", )); state_many.apply_event(ingest_event( 3, - "~/norm/a 3:1 ~/norm/b {vote3}\n", + "{vote3}\n~/norm/a 3:1 ~/norm/b\n", )); let mut group_once = state_once.public().ranking_group.clone(); @@ -508,7 +508,7 @@ fn reducer_malformed_ingest_is_skipped_no_panic() { #[test] fn dsl_parse_rejects_zero_zero_vote_ratio() { let err = slugsocial_server::dsl::parse_full( - "~/t/a {a}\n~/t/b {b}\n~/t/a 0:0 ~/t/b {zero}\n", + "~/t/a {a}\n~/t/b {b}\n{zero}\n~/t/a 0:0 ~/t/b\n", ) .expect_err("0:0 vote must be rejected by the parser"); let msg = match err { @@ -522,7 +522,7 @@ fn dsl_parse_rejects_zero_zero_vote_ratio() { let mut state = ReducerState::default(); state.apply_event(ingest_event( 1, - "~/t/a {a}\n~/t/b {b}\n~/t/a 0:0 ~/t/b {zero}\n", + "~/t/a {a}\n~/t/b {b}\n{zero}\n~/t/a 0:0 ~/t/b\n", )); let content = state.public(); assert!( @@ -620,7 +620,7 @@ fn ranking_convergence_tolerance_triggers_early_exit() { let mut state = ReducerState::default(); state.apply_event(ingest_event( 1, - "~/t/a {a}\n~/t/b {b}\n~/t/a 3:1 ~/t/b {because}\n", + "~/t/a {a}\n~/t/b {b}\n{because}\n~/t/a 3:1 ~/t/b\n", )); let mut group = state.public().ranking_group.clone(); // Very tight tolerance but huge max_iters — should still converge fast @@ -742,7 +742,7 @@ fn test_thread_timestamp_bump() { #[test] fn test_thread_id_is_used_for_votes_and_indexes() { let mut state = ReducerState::default(); - let mut ev = match ingest_event(1, "~/t/a {a}\n~/t/b {b}\n~/t/a 2:1 ~/t/b {reason}\n") { + let mut ev = match ingest_event(1, "~/t/a {a}\n~/t/b {b}\n{reason}\n~/t/a 2:1 ~/t/b\n") { Event::Ingest(i) => i, _ => unreachable!(), }; @@ -770,7 +770,7 @@ fn test_rank_history_created_for_voted_items() { let mut state = ReducerState::default(); state.apply_event(ingest_event( 1, - "~/t/a {a}\n~/t/b {b}\n~/t/a 3:1 ~/t/b {reason}\n", + "~/t/a {a}\n~/t/b {b}\n{reason}\n~/t/a 3:1 ~/t/b\n", )); assert!( state.public().rank_history.contains_key(&item_id("https://slug.social/~/t/a")), @@ -800,7 +800,7 @@ fn test_rank_history_first_entry_delta_zero() { let mut state = ReducerState::default(); state.apply_event(ingest_event( 1, - "~/t/a {a}\n~/t/b {b}\n~/t/a 3:1 ~/t/b {reason}\n", + "~/t/a {a}\n~/t/b {b}\n{reason}\n~/t/a 3:1 ~/t/b\n", )); let history_a = state.public().rank_history.get(&item_id("https://slug.social/~/t/a")).unwrap(); assert_eq!(history_a.len(), 1); diff --git a/server/tests/dsl_fixtures.rs b/server/tests/dsl_fixtures.rs index 2446da86447508b36b7a7dfb112b35cc5a4cc1e6..62f3fa14adc8203562338bf75f9310b99bacbb43 100644 --- a/server/tests/dsl_fixtures.rs +++ b/server/tests/dsl_fixtures.rs @@ -28,7 +28,7 @@ fn parses_tutorial_fixture_with_prose() { #[test] fn parses_big_book_fixture_with_attached_bodies() { - // This doc heavily uses the "~/name{...}" style with no whitespace. + // This doc heavily uses the "{...}\n~/name" style with no whitespace. let doc = dsl::parse_full(BIG_BOOK).expect("parse_full should succeed"); let mut items = 0usize; @@ -55,7 +55,7 @@ fn parses_big_book_fixture_with_attached_bodies() { #[test] fn parses_external_dash_vote_line() { - let doc = dsl::parse_full("-/domain.com/a 2:1 -/domain.com/b { reason }").unwrap(); + let doc = dsl::parse_full("{ reason }\n-/domain.com/a 2:1 -/domain.com/b").unwrap(); assert_eq!( doc.statements, vec![dsl::Stmt::Vote { diff --git a/server/tests/fixtures/big-book.sorter b/server/tests/fixtures/big-book.sorter index 7b3ce871d4f56210d48ecbf6f1ca33371d89eda9..3472f18c6d2e7fdd608b5936d34301480498cf40 100644 --- a/server/tests/fixtures/big-book.sorter +++ b/server/tests/fixtures/big-book.sorter @@ -1,10 +1,10 @@ #Big-Book -~/big-book/arrived{ +~/big-book/arrived { I had arrived. } -~/big-book/how-it-works{ +~/big-book/how-it-works { Rarely have we seen a person fail who has thoroughly followed our path. Those who do not recover are people who cannot or will not completely give @@ -58,7 +58,7 @@ lives. (b) That probably no human power could have relieved our alcoholism. } -~/big-book/run-the-show{ +~/big-book/run-the-show { The first requirement is that we be convinced that any life run on self-will can hardly be a success. On that basis we are almost always in collision with something or somebody, even though our motives are good. @@ -94,7 +94,7 @@ all and is locked up. Whatever our protestations, are not most of us concerned with ourselves, our resentments, or our self-pity? } -~/big-book/god-director{ +~/big-book/god-director { This is the how and why of it. First of all, we had to quit playing God. It didn’t work. Next, we decided that hereafter in this drama of life, God was @@ -126,7 +126,7 @@ were ready; that we could at last abandon ourselves utterly to Him. } -~/big-book/dubious-luxury{ +~/big-book/dubious-luxury { But with the alcoholic, whose hope is the maintenance and growth of a spiritual experience, this business of resentment is infinitely grave. We @@ -139,7 +139,7 @@ poison. } -~/big-book/sick-mans-prayer{ +~/big-book/sick-mans-prayer { This was our course: We realized that the people who wronged us were perhaps spiritually sick. HOW IT WORKS 67 Though we did not like their @@ -151,7 +151,7 @@ him? God save me from being angry. Thy will be done.’’ } -~/big-book/fear-calamity-serenity{ +~/big-book/fear-calamity-serenity { Notice that the word “fear’’ is bracketed alongside the difficulties with Mr. Brown, Mrs. Jones, the employer, and the wife. This short word somehow diff --git a/server/tests/fixtures/tutorial.sorter b/server/tests/fixtures/tutorial.sorter index d8228c3a2986fbeb08817ebdedd4f61cfa6ee724..60b4dc92d5212703df65e70949f7251cd5a85c3d 100644 --- a/server/tests/fixtures/tutorial.sorter +++ b/server/tests/fixtures/tutorial.sorter @@ -15,9 +15,9 @@ subsequent items will be catalogued in the index under this context. We are in a tag, now let's declare an item. -~/alphabet/a +~/alphabet/a {the letter a} -~/alphabet/b +~/alphabet/b {the letter b} The prefix `~/` denotes, when the first characters on a line, the beginning of the title of an ontology item (the garden layer). @@ -25,7 +25,8 @@ Now we have two discrete, addressable items. Imagine two dots floating on a 2d plane. Now let's draw a line segment between the two dots. -~/alphabet/a 2:1 ~/alphabet/b {a edges out b in this ranking} +{a edges out b in this ranking} +~/alphabet/a 2:1 ~/alphabet/b We have asserted that ~/alphabet/a wins over ~/alphabet/b, winning 66% of that matchup. @@ -35,12 +36,13 @@ From this assertion we derive the ranking: 2) ~/alphabet/b If we were to send this email right now, we could view the ranking at -https://slug.social/~/alphabet +the URL https://slug.social/~/alphabet Easy enough. -~/alphabet/c +~/alphabet/c {the letter c} -~/alphabet/a 3:1 ~/alphabet/c {a strongly preferred to c here} +{a strongly preferred to c here} +~/alphabet/a 3:1 ~/alphabet/c Now the ranking is 1) ~/alphabet/a @@ -102,20 +104,24 @@ Sorter is proprietary, trying to become a venture scale business. Now we have six dots swimming around. Lets order them. truth -~/sorter-properties/collective = ~/sorter-properties/asynchronous {roughly equally important} -~/sorter-properties/asynchronous = ~/sorter-properties/precise {roughly equally important} -~/sorter-properties/precise = ~/sorter-properties/transitive {roughly equally important} +{roughly equally important} +~/sorter-properties/collective = ~/sorter-properties/asynchronous +{roughly equally important} +~/sorter-properties/asynchronous = ~/sorter-properties/precise +{roughly equally important} +~/sorter-properties/precise = ~/sorter-properties/transitive All equally, absolutely true. -~/sorter-properties/asynchronous 10:1 ~/sorter-properties/new { +{ Sorter is certainly asynchronous. There have been many explorations of the core sorter idea. Pairwise comparisons have been studied for decades. Conjoint analysis. HotOrNot. Sorter is just one iteration of the human desire to rank things collectively } +~/sorter-properties/asynchronous 10:1 ~/sorter-properties/new -~/sorter-properties/new 100:1 ~/sorter-properties/proprietary { +{ There are some new things about sorter. The backwards compatible with prose syntax. The synthesis of email-first, rank-centrality, and social platform. So @@ -124,6 +130,7 @@ But sorter is absolutely not ~/sorter-properties/proprietary. Sorter is open sou github.com/sortersocial/index Therefore, ~/sorter-properties/proprietary is banished 100:1 to the false end of the spectrum. } +~/sorter-properties/new 100:1 ~/sorter-properties/proprietary In sorter, there are no binaries. Everything is a spectrum, including truth. @@ -131,11 +138,17 @@ truth. The most important thing, in my mind, about sorter is that it’s collective. important -~/sorter-properties/collective 100:20 ~/sorter-properties/asynchronous { sorter would still be cool if it was -live } -~/sorter-properties/collective 100:90 ~/sorter-properties/precise { precise thinking is good too } -~/sorter-properties/collective 100:90 ~/sorter-properties/transitive { transitivity enables collectivity } -~/sorter-properties/collective 100:10 ~/sorter-properties/new { other iterations of sorter were good too } +{ +sorter would still be cool if it was +live +} +~/sorter-properties/collective 100:20 ~/sorter-properties/asynchronous +{ precise thinking is good too } +~/sorter-properties/collective 100:90 ~/sorter-properties/precise +{ transitivity enables collectivity } +~/sorter-properties/collective 100:90 ~/sorter-properties/transitive +{ other iterations of sorter were good too } +~/sorter-properties/collective 100:10 ~/sorter-properties/new Any other person could add to or vote on #sorter-properties, this is just diff --git a/server/tests/integration.rs b/server/tests/integration.rs index bd10fd2a6ef06ac1a23de790a54ad5aa0065a472..e96d11c820c3bbaa8bb55ad11636397ef225e55a 100644 --- a/server/tests/integration.rs +++ b/server/tests/integration.rs @@ -673,7 +673,7 @@ async fn test_private_room_post_links_use_private_garden_routes() { let rpc = ui_post_ingest_rpc( &room_id, "garden-thread", - "~/secret/item {classified}\n~/secret/other {other body}\n~/secret/item 3:1 ~/secret/other {because}\n", + "~/secret/item {classified}\n~/secret/other {other body}\n{because}\n~/secret/item 3:1 ~/secret/other\n", ); let post = client .post(format!("http://{addr}/ui")) @@ -734,7 +734,7 @@ async fn test_private_room_garden_root_lists_top_level_tilde_children() { let rpc = ui_post_ingest_rpc( &room_id, "ing", - "~/test1 {wow}\n~/test2 {wow2}\n~/test1 2:1 ~/test2 {because}\n", + "~/test1 {wow}\n~/test2 {wow2}\n{because}\n~/test1 2:1 ~/test2\n", ); let post = client .post(format!("http://{addr}/ui")) @@ -1003,7 +1003,7 @@ async fn test_post_redact_removes_garden_and_marks_thread() { "room": "public", "thread_tag": "redact-test", "delegate": "00000000-0000-0000-0000-000000000000:test:local/test", - "text": "~/del-a {a}\n~/del-b {b}\n~/del-a 2:1 ~/del-b {vote line}\n", + "text": "~/del-a {a}\n~/del-b {b}\n{vote line}\n~/del-a 2:1 ~/del-b\n", "return_rank_diff": false } }]), @@ -1123,7 +1123,7 @@ async fn test_vote_endpoint() { "room": "public", "thread_tag": "cli", "delegate": "00000000-0000-0000-0000-000000000000:test:local/test", - "text": "~/clap {cli parser}\n~/argh {cli parser}\n~/clap 3:1 ~/argh {because clap is more full-featured}\n", + "text": "~/clap {cli parser}\n~/argh {cli parser}\n{because clap is more full-featured}\n~/clap 3:1 ~/argh\n", "return_rank_diff": true } }]); @@ -1144,7 +1144,7 @@ async fn test_rank_endpoint() { "room": "public", "thread_tag": "langs", "delegate": "00000000-0000-0000-0000-000000000000:test:local/test", - "text": "~/rust {systems}\n~/go {concurrency}\n~/rust 3:1 ~/go {because i prefer rust for systems work}\n", + "text": "~/rust {systems}\n~/go {concurrency}\n{because i prefer rust for systems work}\n~/rust 3:1 ~/go\n", "return_rank_diff": false } }]); @@ -1178,7 +1178,7 @@ async fn test_check_endpoint_does_not_commit() { let check_batch = serde_json::json!([{ "Check": { "room": "public", - "text": "~/a {x}\n~/b {y}\n~/a 2:1 ~/b {because}\n", + "text": "~/a {x}\n~/b {y}\n{because}\n~/a 2:1 ~/b\n", } }]); let resp_body = rpc_batch(&client, addr, None, check_batch).await; @@ -1217,7 +1217,7 @@ async fn test_garden_item_pair_matchup_include_threads() { "room": "public", "thread_tag": "sorting-hat", "delegate": "00000000-0000-0000-0000-000000000000:test:local/test", - "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", + "text": "~/sorts/insertion { O(n^2) }\n~/sorts/mergesort { O(n log n) }\n{ simpler for small n }\n~/sorts/insertion 3:1 ~/sorts/mergesort\n", "return_rank_diff": false } }]); @@ -1473,7 +1473,7 @@ async fn test_rank_history() { ingest( "00000000-0000-0000-0000-000000000001:rig:test/model", - "~/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", + "~/hist/rust { systems }\n~/hist/python { scripting }\n~/hist/go { concurrency }\n{ ownership over gc }\n~/hist/rust 3:1 ~/hist/python\n{ performance over simplicity }\n~/hist/rust 2:1 ~/hist/go\n", ) .await; @@ -1506,7 +1506,7 @@ async fn test_rank_history() { ingest( "00000000-0000-0000-0000-000000000002:rig:test/model", - "~/hist/python 3:1 ~/hist/go { dynamic typing is worth it }\n", + "{ dynamic typing is worth it }\n~/hist/python 3:1 ~/hist/go\n", ) .await; @@ -1571,7 +1571,7 @@ async fn pair_returns_connectivity_stats() { "room": "public", "thread_tag": "connectivity-test", "delegate": "00000000-0000-0000-0000-000000000001:testrig:test/model", - "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", + "text": "~/conn/a { item a }\n~/conn/b { item b }\n~/conn/c { item c }\n~/conn/d { item d }\n{ a is better }\n~/conn/a 3:1 ~/conn/b\n", "return_rank_diff": false } }]); @@ -1605,7 +1605,7 @@ async fn pair_returns_connectivity_stats() { "room": "public", "thread_tag": "connectivity-test", "delegate": "00000000-0000-0000-0000-000000000001:testrig:test/model", - "text": "~/conn/c 2:1 ~/conn/a { c beats a }\n", + "text": "{ c beats a }\n~/conn/c 2:1 ~/conn/a\n", "return_rank_diff": false } }]); diff --git a/test/browser_garden_pin.clj b/test/browser_garden_pin.clj index 98c086d5647207f3ac72dbb9cbc13488c030eef1..d4fa9ed60b45e872ec60e29307cfa61bcd9dd6b2 100644 --- a/test/browser_garden_pin.clj +++ b/test/browser_garden_pin.clj @@ -60,7 +60,8 @@ raw (str "# " thread-tag "\n\n" "~/gp-pin-a {alpha}\n" "~/gp-pin-b {beta}\n" - "~/gp-pin-a 2:1 ~/gp-pin-b {pin test vote}\n") + "{pin test vote}\n" + "~/gp-pin-a 2:1 ~/gp-pin-b\n") post-resp (oauth/http-post-json (str base-url "/api/v0/rpc") [{"Post" {"room" "public" diff --git a/test/browser_post_redact.clj b/test/browser_post_redact.clj index f8f5fad7c0579f57e68744647465b9dcce1d4802..bf1af0230bc7c8228f947087d4f22d51d5189a5d 100644 --- a/test/browser_post_redact.clj +++ b/test/browser_post_redact.clj @@ -60,7 +60,7 @@ raw (str "# " thread-tag "\n\n" "~/tomb-a {tomb item a}\n" "~/tomb-b {tomb item b}\n" - "~/tomb-a 2:1 ~/tomb-b {browser redact vote}\n") + "{browser redact vote}\n~/tomb-a 2:1 ~/tomb-b\n") post-resp (oauth/http-post-json (str base-url "/api/v0/rpc") [{"Post" {"room" "public" diff --git a/test/browser_public_garden.clj b/test/browser_public_garden.clj index 7bea08e1cf2c8f5b1a94b0640a46e9ba5607b19b..5dd49f1f70c870e25a2a9f5348f0bdb85647e897 100644 --- a/test/browser_public_garden.clj +++ b/test/browser_public_garden.clj @@ -51,7 +51,7 @@ "~/br-pub-a {alpha}\n" "~/br-pub-b {beta}\n" "~/br-pub-c {gamma}\n" - "~/br-pub-a 2:1 ~/br-pub-b {browser regression vote}\n") + "{browser regression vote}\n~/br-pub-a 2:1 ~/br-pub-b\n") post-resp (oauth/http-post-json (str base-url "/api/v0/rpc") [{"Post" {"room" "public" diff --git a/test/browser_redact_thread_index.clj b/test/browser_redact_thread_index.clj index 88a86fb9844fcf78df85e59f21f2e37f27df96a5..39958a85d4de10f284166f4561bc6ada2332b304 100644 --- a/test/browser_redact_thread_index.clj +++ b/test/browser_redact_thread_index.clj @@ -63,11 +63,11 @@ text-first (str "# " thread-tag "\n\n" "~/rix/a {alpha}\n" "~/rix/b {beta}\n" - "~/rix/a 2:1 ~/rix/b {browser redact thread idx post one}\n") + "{browser redact thread idx post one}\n~/rix/a 2:1 ~/rix/b\n") text-second (str "# " thread-tag "\n\n" "~/rix/c {gamma}\n" "~/rix/d {delta}\n" - "~/rix/c 2:1 ~/rix/d {browser redact thread idx post two}\n") + "{browser redact thread idx post two}\n~/rix/c 2:1 ~/rix/d\n") _ (is (true? (get-in (json/parse-string (:body (oauth/http-post-json (str base-url "/api/v0/rpc") diff --git a/test/browser_vote_compare.clj b/test/browser_vote_compare.clj index 839482d12963f130a2063f2212a6b922b2d229e1..f97a4a45e89c388f093694a1bf296f674bcb377a 100644 --- a/test/browser_vote_compare.clj +++ b/test/browser_vote_compare.clj @@ -53,7 +53,8 @@ raw (str "# " thread-tag "\n\n" "~/gp-vote-a {one}\n" "~/gp-vote-b {two}\n" - "~/gp-vote-a 1:1 ~/gp-vote-b {seed edge vote}\n") + "{seed edge vote}\n" + "~/gp-vote-a 1:1 ~/gp-vote-b\n") post-resp (oauth/http-post-json (str base-url "/api/v0/rpc") [{"Post" {"room" "public" diff --git a/test/grants.clj b/test/grants.clj index 12846c6259c2c8f0395668d49155ee22c8abfcd5..055e0a94a7fd90d58f234f643ae8998956ef9939 100644 --- a/test/grants.clj +++ b/test/grants.clj @@ -125,14 +125,15 @@ (println "\nalice posts items + vote to private room…") (is (rpc-line-ok? (:parsed (ingest! base-url alice-token room-id "main" "00000000-0000-0000-0000-000000000001:test:local/dev" - "~/fruits/apple { A crisp red apple. }\n~/fruits/banana { A yellow banana. }\n~/fruits/apple > ~/fruits/banana { apples are better }"))) + "~/fruits/apple { A crisp red apple. }\n~/fruits/banana { A yellow banana. }\n{ apples are better }\n~/fruits/apple > ~/fruits/banana"))) "alice vote in private room succeeds") ;; Bob (View + Post, no Vote) tries to vote. (println "\nbob (no Vote) tries to vote…") (is (not (rpc-line-ok? (:parsed (ingest! base-url bob-token room-id "main" "00000000-0000-0000-0000-000000000002:test:local/dev" - "~/fruits/apple > ~/fruits/banana { bob's take }")))) + "{ bob's take } +~/fruits/apple > ~/fruits/banana")))) "bob without Vote gets RPC failure") ;; Alice grants bob Vote. @@ -144,7 +145,8 @@ (println "\nbob (View + Post + Vote) votes…") (is (rpc-line-ok? (:parsed (ingest! base-url bob-token room-id "main" "00000000-0000-0000-0000-000000000002:test:local/dev" - "~/fruits/apple > ~/fruits/banana { bob's take }"))) + "{ bob's take } +~/fruits/apple > ~/fruits/banana"))) "bob with Vote succeeds")) (finally diff --git a/test/integration.clj b/test/integration.clj index 81261c7f2e0487666ef849f523fe91b2c005e6cd..5530bf9f4533f7f548e47599b5fe33f9be567309 100644 --- a/test/integration.clj +++ b/test/integration.clj @@ -39,19 +39,23 @@ "#integration-test" "" "~/languages/python { General-purpose, dynamically typed }" - "~/languages/rust { Systems language with ownership model }" - "~/languages/go { Compiled, garbage-collected, simple concurrency }" + "~/languages/rust { Systems language with ownership model }" + "~/languages/go { Compiled, garbage-collected, simple concurrency }" "" - "~/languages/rust 3:1 ~/languages/python { Rust has stronger type safety }" - "~/languages/rust 2:1 ~/languages/go { Ownership beats GC for systems work }" - "~/languages/python 2:1 ~/languages/go { Python's ecosystem is broader }"])) + "{ Rust has stronger type safety } +~/languages/rust 3:1 ~/languages/python" + "{ Ownership beats GC for systems work } +~/languages/rust 2:1 ~/languages/go" + "{ Python's ecosystem is broader } +~/languages/python 2:1 ~/languages/go"])) (def sorter-doc-2 (str/join "\n" [actor-2 "#integration-test" "" - "~/languages/go 2:1 ~/languages/python { Go deploys as a single binary, simpler ops }"])) + "{ Go deploys as a single binary, simpler ops } +~/languages/go 2:1 ~/languages/python"])) (def external-sorter-doc (str/join "\n" @@ -61,7 +65,8 @@ "-/github.com/iss/1 { issue one }" "-/github.com/iss/2 { issue two }" "" - "-/github.com/iss/1 2:1 -/github.com/iss/2 { triage order }"])) + "{ triage order } +-/github.com/iss/1 2:1 -/github.com/iss/2"])) (def check-doc-disconnected (str/join "\n" @@ -73,8 +78,10 @@ "~/disc/c { c }" "~/disc/d { d }" "" - "~/disc/a 2:1 ~/disc/b { first component }" - "~/disc/c 2:1 ~/disc/d { second component }"])) + "{ first component } +~/disc/a 2:1 ~/disc/b" + "{ second component } +~/disc/c 2:1 ~/disc/d"])) ;; --------------------------------------------------------------------------- ;; main flow (linear integration) @@ -291,8 +298,10 @@ (bind two-vote-doc (str/join "\n" ["@00000000-0000-0000-0000-000000000003:integration:local/test" "#integration-test" - "~/languages/rust 4:1 ~/languages/python { type safety }" - "~/languages/rust 3:1 ~/languages/go { zero-cost abstractions }"])) + "{ type safety } +~/languages/rust 4:1 ~/languages/python" + "{ zero-cost abstractions } +~/languages/rust 3:1 ~/languages/go"])) (bind hist-ingest (common/run-cli cli-bin base-url ["public" "forum" "post" "integration-test" "--json" "--delegate" "00000000-0000-0000-0000-000000000000:cli:local/dev"] :input two-vote-doc :extra-env token-env)) (is (zero? (:exit hist-ingest)) (str "two-vote ingest exits 0 (err: " (:err hist-ingest) ")")) diff --git a/test/walkthrough_fixture.clj b/test/walkthrough_fixture.clj index f7eb1cacca0317129e9baf68fa4f4e33356ad70f..fb7f4ee8c996e7b4ffb55e225f73f3266feda220 100644 --- a/test/walkthrough_fixture.clj +++ b/test/walkthrough_fixture.clj @@ -49,7 +49,7 @@ "capabilities" ["view" "post" "vote" "add_item"]}}])) (let [wall-text (str "Walkthrough seed — multi-paragraph stress test.\n\n" "Second paragraph: the garden holds ~/secret/item and ~/secret/other. " - "Votes like ~/secret/item 3:1 ~/secret/other {because} should still parse.\n\n" + "Votes like {because}\\n~/secret/item 3:1 ~/secret/other should parse.\n\n" "Third block: lorem-style filler so wrapping and vertical rhythm are obvious. " "We want enough prose that the thread view scrolls and pre blocks show overflow " "behavior (long lines, slug links, embed URLs) without looking like toy data.\n\n" @@ -58,7 +58,7 @@ "https://open.spotify.com/track/4iV5W9uYEdYUVa79Axb7U9 https://www.youtube.com/watch?v=dQw4w9WgXcQ\n\n" "~/secret/item {classified}\n" "~/secret/other {secondary}\n" - "~/secret/item 3:1 ~/secret/other {because}\n") + "{because}\n~/secret/item 3:1 ~/secret/other\n") rpc (json/generate-string {:action "post_ingest" :room room-id