B is a small, focused correctness fix (enforcing valid vote ratio bounds across DSL parser, UI handler, and reducer) with targeted regression tests and a real behavioral improvement preventing degenerate/invalid votes. A is a large mechanical refactor moving code into a new types module with newtypes wrapping strings, which improves type-safety/organization but is mostly churn (renames, re-exports, moved tests) without fixing any bug or changing runtime behavior, and risks regressions across many call sites for marginal clarity gains.
constitution · epochs · watch · epoch 3
c_5e9a63e9d276 (tommy-mor) vs c_55666fe32c48 (tommy-mor)
download prompt · raw event · cmp_579e6d12072a1c
council reasoning
B enforces a real ranking invariant (both ratio sides ≥ 1 and ≤ 100) in the DSL parser, UI POST path, and reducer (dropping zero-side votes instead of normalizing 0:0→1:1), with unit and integration regression tests. A mostly relocates existing canonicalize/path helpers into slug-types and wraps API strings in GardenItemUrl/ForumThreadUrl/TildeOntologyPath—useful structure, but largely mechanical re-export and call-site rewiring without fixing domain behavior. A precise multi-layer correctness fix outlasts diffuse type centralization alone.
Side A performs a substantial architectural refactor by moving canonicalization, path identity, and room-aware URL generation into shared `slug_types::paths` newtypes (`GardenItemUrl`, `ForumThreadUrl`, `TildeOntologyPath`) and updating API/RPC types to use those abstractions instead of ad hoc string helpers. Side B is a valuable correctness fix that consistently enforces vote ratio bounds (both sides 1–100) across the parser, UI, reducer, and tests, but its scope is a targeted validation improvement rather than a foundational API and type-system redesign.
sides
A — c_5e9a63e9d276 (tommy-mor)
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
diff preview
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<String, String> {
let canonical = canonicalize_item(item);
@@ -109,14 +51,12 @@ pub fn parse_parent_specs(parent: Option<&String>) -> Vec<String> {
}
/// 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<RankComponent>,
- unranked_items: Vec<String>,
+ unranked_items: Vec<GardenItemUrl>,
offset: usize,
limit: Option<usize>,
-) -> (Vec<RankComponent>, Vec<String>) {
+) -> (Vec<RankComponent>, Vec<GardenItemUrl>) {
let mut remaining_skip = offset;
let mut remaining_take = limit.unwrap_or(usize::MAX);
let mut out_components: Vec<RankComponent> = Vec::new();
@@ -141,7 +81,7 @@ pub fn paginate_rankings(
});
}
- let out_unranked: Vec<String> = if remaining_take > 0 {
+ let out_unranked: Vec<GardenItemUrl> = 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<Option<usize>> = pool
.iter()
.map(|it| {
@@ -197,7 +135,6 @@ pub fn compute_connectivity_stats(group: &crate::reducer::GroupState, pool: &[St
.collect();
let present: Vec<usize> = 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<usize, usize> = 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<String> = rankings
+ let prefixed_unranked: Vec<GardenItemUrl> = 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 <TAG> --delegate <uuid:rig:
… preview truncated; 46,249 characters omittedB — c_55666fe32c48 (tommy-mor)
message
[aa0b175c] Enforce vote ratio constraints: both sides ≥ 1, max 100. Zero on either side produces no valid graph edge; ratios above 100 add no meaningful signal. Enforce in the DSL parser, browser POST handler, and reducer guard. Update browser pool test to use 99:1 instead of 100:0. Add unit and integration regression tests. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
diff preview
diff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs
index b79efdb4d52bd445a67f38cbfd61d3507d2b3014..bc8a0130b434cc7880a4bf16eb9237080c4aa383 100644
--- a/server/src/api/ui_html.rs
+++ b/server/src/api/ui_html.rs
@@ -243,11 +243,23 @@ async fn dispatch_ui_action(
let pool_id = pool.as_deref().and_then(|p| {
crate::path_types::ItemId::parse(p.trim()).map(|i| i.normalized_storage())
});
- let mut rl = ratio_left.trim().parse::<i32>().unwrap_or(0).max(0);
- let mut rr = ratio_right.trim().parse::<i32>().unwrap_or(0).max(0);
- if rl == 0 && rr == 0 {
- rl = 1;
- rr = 1;
+ let rl = ratio_left.trim().parse::<i32>().unwrap_or(0).max(0);
+ let rr = ratio_right.trim().parse::<i32>().unwrap_or(0).max(0);
+ if rl == 0 || rr == 0 {
+ return form_js_error(
+ err_tgt.as_ref(),
+ "invalid ratio",
+ "Both ratio sides must be ≥ 1.",
+ )
+ .into_response();
+ }
+ if rl > 100 || rr > 100 {
+ return form_js_error(
+ err_tgt.as_ref(),
+ "invalid ratio",
+ "Ratio sides must be ≤ 100.",
+ )
+ .into_response();
}
let text = format!(
diff --git a/server/src/dsl.rs b/server/src/dsl.rs
index faa8aac6616bc6ea2b102d08ae999c01a716ef6e..338feacc579a92bed291867cc0f2f62462737462 100644
--- a/server/src/dsl.rs
+++ b/server/src/dsl.rs
@@ -545,9 +545,14 @@ fn parse_block_prefixed_statement(
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 {
+ 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(),
+ "vote ratio sides must be ≥ 1; use 1:1 for a tie or omit the vote".to_string(),
+ ));
+ }
+ if ratio_left > 100 || ratio_right > 100 {
+ return Err(DslError::Parse(
+ "vote ratio sides must be ≤ 100".to_string(),
));
}
i = skip_ws(s, k);
@@ -929,11 +934,50 @@ mod tests {
let err = parse_full("{tie placeholder}\n~/a 0:0 ~/b").unwrap_err();
let DslError::Parse(msg) = err;
assert!(
- msg.contains("0:0"),
- "expected 0:0 rejection message, got: {msg}"
+ msg.contains("≥ 1"),
+ "expected zero-side rejection message, got: {msg}"
);
}
+ #[test]
+ fn parse_vote_rejects_left_zero_ratio() {
+ let err = parse_full("{prefer b}\n~/a 0:5 ~/b").unwrap_err();
+ let DslError::Parse(msg) = err;
+ assert!(
+ msg.contains("≥ 1"),
+ "expected zero-side rejection message, got: {msg}"
+ );
+ }
+
+ #[test]
+ fn parse_vote_rejects_right_zero_ratio() {
+ let err = parse_full("{prefer a}\n~/a 5:0 ~/b").unwrap_err();
+ let DslError::Parse(msg) = err;
+ assert!(
+ msg.contains("≥ 1"),
+ "expected zero-side rejection message, got: {msg}"
+ );
+ }
+
+ #[test]
+ fn parse_vote_rejects_over_max_ratio() {
+ let err = parse_full("{prefer a strongly}\n~/a 101:1 ~/b").unwrap_err();
+ let DslError::Parse(msg) = err;
+ assert!(
+ msg.contains("≤ 100"),
+ "expected max ratio rejection message, got: {msg}"
+ );
+ }
+
+ #[test]
+ fn parse_vote_accepts_max_ratio() {
+ let doc = parse_full("{prefer a}\n~/a 100:1 ~/b").unwrap();
+ assert!(matches!(
+ doc.statements.last(),
+ Some(Stmt::Vote { ratio_left: 100, ratio_right: 1, .. })
+ ));
+ }
+
#[test]
fn parse_full_interleaves_prose() {
let input = "hello\n#tag\nworld";
diff --git a/server/src/reducer.rs b/server/src/reducer.rs
index e949e8e092297eedd5c20c131f16ef0121f329b3..6841d35cfc9de2389f340a22b8a45acb335e36c3 100644
--- a/server/src/reducer.rs
+++ b/server/src/reducer.rs
@@ -119,11 +119,11 @@ impl GroupState {
let (i, j) = if a_idx < b_idx { (a_idx, b_idx) } else { (b_idx, a_idx) };
self.voted_pairs.insert((i, j));
- let mut w_a = vote.ratio_left.max(0) as f64;
- let mut w_b = vote.ratio_right.max(0) as f64;
- if w_a == 0.0 && w_b == 0.0 {
- w_a = 1.0;
- w_b = 1.0;
+ let w_a = vote.ratio_left as f64;
+ let w_b = vote.ratio_right as f64;
+ if w_a == 0.0 || w_b == 0.0 {
+ // Zero on either side produces no valid edge; drop the vote.
+ return;
}
self.add_edge_weight(b_idx, a_idx, w_a);
diff --git a/server/tests/basic.rs b/server/tests/basic.rs
index 9d83e7a97e2c7494790db17c4b5b30c181705026..cc8c1a0d139f3722ba6ecd13dd001c65be835b67 100644
--- a/server/tests/basic.rs
+++ b/server/tests/basic.rs
@@ -175,14 +175,14 @@ 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{huge}\n~/t/a 1000:1 ~/t/b\n",
+ "@00000000-0000-0000-0000-000000000000:test:local/test\n~/t/a {a}\n~/t/b {b}\n{huge}\n~/t/a 100:1 ~/t/b\n",
));
state.apply_event(ingest_event(
2,
- "@00000000-0000-0000-0000-000000000000:test:local/test\n{huge}\n~/t/a 1:1000 ~/t/b\n",
+ "@00000000-0000-0000-0000-000000000000:test:local/test\n{huge}\n~/t/a 1:100 ~/t/b\n",
));
- assert_eq!(state.public().ranking_group.idx_to_item.len(), 2); // Should still work, scores clamped internally
+ assert_eq!(state.public().ranking_group.idx_to_item.len(), 2); // Should still work, scores handled internally
}
// ============================================================================
@@ -513,8 +513,8 @@ fn dsl_parse_rejects_zero_zero_vote_ratio() {
.expect_err("0:0 vote must be rejected by the parser");
let slugsocial_server::dsl::DslError::Parse(msg) = err;
assert!(
- msg.contains("0:0"),
- "expected message about invalid 0:0 ratio, got: {msg}"
+ msg.contains("≥ 1"),
+ "expected message about invalid zero ratio, got: {msg}"
);
let mut state = ReducerState::default();
@@ -533,7 +533,7 @@ fn dsl_parse_rejects_zero_zero_vote_ratio() {
#[test]
fn reducer_negative_ratio_clamped_to_zero() {
let _state = ReducerState::default();
- // GroupState::apply_vote clamps negatives to 0, then 0:0 -> 1:1
+ // GroupState::apply_vote clamps negatives to 0; when either side is 0 the vote is dropped.
let mut group = GroupState::new();
group.apply_vote(slugsocial_server::reducer::VoteData {
ts: 1,
@@ -546,12 +546,12 @@ fn reducer_negative_ratio_clamped_to_zero() {
delegate: Some("00000000-0000-0000-0000-000000000000:test:local/test".to_string()),
thread_tag: "t".to_string(),
});
+ // Items are registered, but the zero-clamped vote produces no edges.
assert_eq!(group.idx_to_item.len(), 2);
- // Both edges should exist (negatives clamped to 0, then 0:0 -> 1:1)
let a_idx = group.item_to_idx[&item_id("https://slug.social/~/t/a")];
let b_idx = group.item_to_idx[&item_id("https://slug.social/~/t/b")];
- assert!(group.edges.contains_key(&(a_idx, b_idx)));
- assert!(group.edges.contains_key(&(b_idx, a_idx)));
+ assert!(!group.edges.contains_key(&(a_idx, b_idx)));
+ assert!(!group.edges.contains_key(&(b_idx, a_idx)));
}
diff --git a/server/tests/integration_ui.rs b/server/tests/integration_ui.rs
index 23db7b5672418d5bb0ab7529e05ef1f89e59062a..09c5481f039d59efb617a82bafcc432a186e2d30 100644
--- a/server/tests/integration_ui.rs
+++ b/server/tests/integration_ui.rs
@@ -256,3 +256,96 @@ async fn test_sse_public_thread_morph_includes_post_body_not_thread_not_found()
);
}
+fn ui_vote_compare_post_rpc(
+ room: &str,
+ thread_tag: &str,
+ left: &str,
+ right: &str,
+ ratio_left: &str,
+ ratio_right: &str,
+ explanation: &str,
+) -> String {
+ serde_json::json!({
+ "action": "vote_compare_post",
+ "room": room,
+ "thread_tag": thread_tag,
+ "left_item": left,
+ "right_item": right,
+ "ratio_left": ratio_left,
+ "ratio_right": ratio_right,
+ "explanation": explanation,
+ "next": "/vote",
+ })
+ .to_string()
+}
+
+#[tokio::test]
+async fn test_vote_compare_post_rejects_zero_left_ratio() {
+ let (addr, _tmp, _log, _handle) = create_test_server().await;
+ let client = reqwest::Client::new();
+ let bearer = test_bearer();
+
+ let rpc = ui_vote_compare_post_rpc("public", "test-vote", "~/a", "~/b", "0", "5", "prefer b");
+ let resp = client
+ .post(format!("http://{addr}/ui"))
+ .header("Authorization", format!("Bearer {bearer}"))
+ .form(&[("__rpc__", rpc.as_str())])
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(resp.status(), reqwest::StatusCode::OK);
+ let js = resp.text().await.unwrap();
+ assert!(
+ js.contains("invalid ratio") || js.contains("≥ 1"),
+ "expected zero-ratio rejection, got: {js}"
+ );
+}
+
+#[tokio::test]
+async fn test_vote_compare_post_rejects_zero_right_ratio() {
+ let (addr, _tmp, _log, _handle) = create_test_server().await;
+ let client = reqwest::Client::new();
+ let bearer = test_bearer();
+
+ let rpc = ui_vote_compare_post_rpc("public", "test-vote", "~/a", "~/b", "5", "0", "prefer a");
+ let resp = client
+ .post(format!("http://{addr}/ui"))
+ .header("Authorization", format!("Bearer {bearer}"))
+ .form(&[("__rpc__", rpc.as_str())])
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(resp.status(), reqwest::StatusCode::OK);
+ let js = resp.text().await.unwrap();
+ assert!(
+ js.contains("invalid ratio") || js.contains("≥ 1"),
+ "expected zero-ratio rejection, got: {js}"
+ );
+}
+
+#[tokio::test]
+async fn test_vote_compare_post_rejects_over_max_ratio() {
+ let (addr, _tmp, _log, _handle) = create_test_server().await;
+ let client = reqwest::Client::new();
+ let bearer = test_bearer();
+
+ let rpc =
+ ui_vote_compare_post_rpc("public", "test-vote", "~/a", "~/b", "101", "1", "prefer a");
+ let resp = client
+ .post(format!("http://{addr}/ui"))
+ .header("Authorization", format!("Bearer {bearer}"))
+ .form(&[("__rpc__", rpc.as_str())])
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(resp.status(), reqwest::StatusCode::OK);
+ let js = resp.text().await.unwrap();
+ assert!(
+ js.contains("invalid ratio") || js.contains("≤ 100"),
+ "expected over-max ratio rejection, got: {js}"
+ );
+}
+
diff --git a/test/browser_vote_pool.clj b/test/browser_vote_pool.clj
index 23d0bd80b02bd8b1b48853454bed02793296550e..738608801027d1e662660b5d6c830b4ccd07c434 100644
--- a/test/browser_vote_pool.clj
+++ b/test/browser_vote_pool.clj
@@ -38,8 +38,8 @@
;; Set the hidden ratio inputs so the alphabetically-earlier item wins.
(defn- set-ratio! [pg left-text right-text]
(let [[rl rr] (if (neg? (compare (leaf left-text) (leaf right-text)))
- [100 0] ; left is earlier → prefer left
- [0 100])] ; right is earlier → prefer right
+ [99 1] ; left is earlier → prefer left
+ [1 99])] ; right is earlier → prefer right
(page/evaluate pg (str "document.getElementById('vote-ratio-left').value='" rl "'"))
(page/evaluate pg (str "document.getElementById('vote-ratio-right').value='" rr "'"))))
Hardlinks — judgments / attempts / prompt
judgments
attempts
Prompt text is loaded only by the download route.