{"messages":[{"content":"You are a constitutional council ranking individual git commits for ownership allocation.\n\nCompare these two commits. Decide which contributed more lasting value to the project.\n\nJudge substance, not spectacle:\n- Prefer correct, lasting design and real bugfixes over churn, formatting, renames, or generated noise.\n- Prefer clarity and necessity over sheer line count. A small precise change can beat a large diffuse one.\n- Do not favor a side merely because its patch is longer or noisier.\n- Weight what the change does for the project, not the contributor's name.\n\nReturn ONLY a JSON object: {\"winner\": \"A\" or \"B\", \"ratio\": \"N:M\", \"explanation\": \"...\"}\nThe explanation must cite concrete differences in the patches (1-3 sentences).\n\nSide A — contributor: tommy-mor\nSide A — commit message:\n[5db58b98] Improve vote pair selection for spanning trees and rank refinement.\n\nPrefer attaching unranked items to established components before comparing\nisolates, then zip down adjacent rank-centrality pairs once the pool is fully\nconnected, skipping pairs that already have votes.\n\nCo-authored-by: Cursor \n\nSide A — unified diff (full patch):\ndiff --git a/server/src/pair.rs b/server/src/pair.rs\nindex 54b5d2417e9dba04ed8df422156e274c2b2f76b2..c14de4b0502c8b5a17cddf3746077739d56e03e0 100644\n--- a/server/src/pair.rs\n+++ b/server/src/pair.rs\n@@ -3,13 +3,21 @@\n //! Pair selection prefers **bridge** votes — comparisons between items in\n //! different connected components of the voted-pairs graph — so the pool\n //! merges into one ranking group before refining within it.\n+//!\n+//! Among unvoted bridges, prefer merging established voted components, then\n+//! attaching a never-voted child to an established component, and only then\n+//! comparing two never-voted children (so the voted graph grows as one tree).\n+//!\n+//! Once every pool child sits in one voted component, refinement **zips** down\n+//! the rank-centrality order: prefer 1 vs 2, then 2 vs 3, and so on, skipping\n+//! pairs that already have a vote.\n \n use rand::seq::SliceRandom;\n use std::collections::{HashMap, HashSet};\n \n use crate::{\n path_types::ItemId,\n- ranking::connected_components_from_voted_pairs,\n+ ranking::{connected_components_from_voted_pairs, ranked_items},\n reducer::{GlobalTree, GroupState},\n };\n \n@@ -28,36 +36,77 @@ fn pair_is_voted(group: &GroupState, a: &ItemId, b: &ItemId) -> bool {\n group.voted_pairs.contains(&(i, j))\n }\n \n-/// Component id per pool item: voted-pairs graph components plus one id per\n-/// never-voted child.\n-fn component_ids(group: &GroupState, pool: &[ItemId]) -> HashMap {\n+/// Voted-pairs layout for pool items: component id per item plus which ids are\n+/// multi-node voted components (ranked groups in the UI).\n+struct ComponentLayout {\n+ ids: HashMap,\n+ established: HashSet,\n+}\n+\n+fn component_layout(group: &GroupState, pool: &[ItemId]) -> ComponentLayout {\n let n = group.idx_to_item.len();\n let (comps, isolates) =\n connected_components_from_voted_pairs(n, group.voted_pairs.iter().copied());\n \n- let mut out: HashMap = HashMap::new();\n+ let mut established = HashSet::new();\n+ let mut ids: HashMap = HashMap::new();\n for (comp_idx, comp) in comps.iter().enumerate() {\n+ if comp.len() >= 2 {\n+ established.insert(comp_idx);\n+ }\n for &idx in comp {\n if idx < n {\n- out.insert(group.idx_to_item[idx].clone(), comp_idx);\n+ ids.insert(group.idx_to_item[idx].clone(), comp_idx);\n }\n }\n }\n let mut next = comps.len();\n for &idx in &isolates {\n if idx < n {\n- out.insert(group.idx_to_item[idx].clone(), next);\n+ ids.insert(group.idx_to_item[idx].clone(), next);\n next += 1;\n }\n }\n for item in pool {\n- out.entry(item.clone()).or_insert_with(|| {\n+ ids.entry(item.clone()).or_insert_with(|| {\n let id = next;\n next += 1;\n id\n });\n }\n- out\n+ ComponentLayout { ids, established }\n+}\n+\n+/// Every pool child shares one multi-node voted component (spanning tree phase done).\n+fn pool_fully_connected(layout: &ComponentLayout, pool: &[ItemId]) -> bool {\n+ if pool.len() < 2 {\n+ return false;\n+ }\n+ let mut comp_id = None;\n+ for item in pool {\n+ let Some(id) = layout.ids.get(item) else {\n+ return false;\n+ };\n+ if !layout.established.contains(id) {\n+ return false;\n+ }\n+ match comp_id {\n+ None => comp_id = Some(*id),\n+ Some(expected) if expected == *id => {}\n+ _ => return false,\n+ }\n+ }\n+ comp_id.is_some()\n+}\n+\n+/// Pool children that appear in `group`, sorted best rank first.\n+fn ranked_pool_order(group: &GroupState, pool: &[ItemId]) -> Vec {\n+ let pool_set: HashSet<_> = pool.iter().collect();\n+ ranked_items(group)\n+ .into_iter()\n+ .map(|r| r.item)\n+ .filter(|id| pool_set.contains(id))\n+ .collect()\n }\n \n #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]\n@@ -72,19 +121,108 @@ enum PairPriority {\n WithinVoted = 3,\n }\n \n-fn pair_priority(\n+/// Tie-break among unvoted bridge pairs.\n+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]\n+enum BridgeSubPriority {\n+ /// Both endpoints lie in established (multi-node) voted components.\n+ MergeEstablished = 0,\n+ /// One established component member and one never-voted child.\n+ AttachIsolate = 1,\n+ /// Two never-voted children (separate singleton components).\n+ IsolatePair = 2,\n+}\n+\n+/// Tie-break among within-component pairs once the pool is one connected group.\n+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]\n+struct WithinSubPriority {\n+ /// 1 = adjacent ranks (i vs i+1); larger = farther apart in the order.\n+ rank_gap: usize,\n+ /// min rank index of the two — zip from the top (1 vs 2 before 2 vs 3).\n+ zip_index: usize,\n+}\n+\n+const WITHIN_SUB_WORST: WithinSubPriority = WithinSubPriority {\n+ rank_gap: usize::MAX,\n+ zip_index: usize::MAX,\n+};\n+\n+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]\n+struct PairSortKey {\n+ priority: PairPriority,\n+ bridge_sub: BridgeSubPriority,\n+ within_sub: WithinSubPriority,\n+}\n+\n+fn item_in_established(layout: &ComponentLayout, item: &ItemId) -> bool {\n+ layout\n+ .ids\n+ .get(item)\n+ .is_some_and(|id| layout.established.contains(id))\n+}\n+\n+fn bridge_sub_priority(layout: &ComponentLayout, a: &ItemId, b: &ItemId) -> BridgeSubPriority {\n+ let a_est = item_in_established(layout, a);\n+ let b_est = item_in_established(layout, b);\n+ match (a_est, b_est) {\n+ (true, true) => BridgeSubPriority::MergeEstablished,\n+ (true, false) | (false, true) => BridgeSubPriority::AttachIsolate,\n+ (false, false) => BridgeSubPriority::IsolatePair,\n+ }\n+}\n+\n+fn within_sub_priority(\n+ group: &GroupState,\n+ pool: &[ItemId],\n+ layout: &ComponentLayout,\n+ a: &ItemId,\n+ b: &ItemId,\n+) -> WithinSubPriority {\n+ if !pool_fully_connected(layout, pool) {\n+ return WITHIN_SUB_WORST;\n+ }\n+ let order = ranked_pool_order(group, pool);\n+ let (Some(i), Some(j)) = (order.iter().position(|x| x == a), order.iter().position(|x| x == b))\n+ else {\n+ return WITHIN_SUB_WORST;\n+ };\n+ WithinSubPriority {\n+ rank_gap: i.abs_diff(j),\n+ zip_index: i.min(j),\n+ }\n+}\n+\n+fn pair_sort_key(\n group: &GroupState,\n- components: &HashMap,\n+ pool: &[ItemId],\n+ layout: &ComponentLayout,\n a: &ItemId,\n b: &ItemId,\n-) -> PairPriority {\n+) -> PairSortKey {\n let voted = pair_is_voted(group, a, b);\n- let bridge = components.get(a) != components.get(b);\n- match (bridge, voted) {\n+ let bridge = layout.ids.get(a) != layout.ids.get(b);\n+ let priority = match (bridge, voted) {\n (true, false) => PairPriority::BridgeUnvoted,\n (false, false) => PairPriority::WithinUnvoted,\n (true, true) => PairPriority::BridgeVoted,\n (false, true) => PairPriority::WithinVoted,\n+ };\n+ let bridge_sub = if priority == PairPriority::BridgeUnvoted {\n+ bridge_sub_priority(layout, a, b)\n+ } else {\n+ BridgeSubPriority::MergeEstablished\n+ };\n+ let within_sub = if matches!(\n+ priority,\n+ PairPriority::WithinUnvoted | PairPriority::WithinVoted\n+ ) {\n+ within_sub_priority(group, pool, layout, a, b)\n+ } else {\n+ WITHIN_SUB_WORST\n+ };\n+ PairSortKey {\n+ priority,\n+ bridge_sub,\n+ within_sub,\n }\n }\n \n@@ -109,9 +247,12 @@ fn candidate_pairs(pool: &[ItemId], exclude: Option<(&ItemId, &ItemId)>) -> Vec<\n \n /// Pick the next pair to vote on within `pool`.\n ///\n-/// 1. Prefer unvoted **bridge** pairs (connect separate ranking components).\n-/// 2. Then unvoted within-component pairs (refinement).\n-/// 3. Then already-voted pairs (re-compare).\n+/// 1. Prefer unvoted **bridge** pairs (connect separate ranking components),\n+/// with sub-priority: merge established components, attach an isolate to\n+/// established, then compare two isolates.\n+/// 2. Then unvoted within-component pairs; when the pool is one connected group,\n+/// prefer adjacent ranks (1 vs 2, 2 vs 3, …) in order, skipping voted pairs.\n+/// 3. Then already-voted pairs (re-compare), with the same zip ordering.\n pub fn suggest_next_pair_in_pool(\n group: &GroupState,\n pool: &[ItemId],\n@@ -121,15 +262,15 @@ pub fn suggest_next_pair_in_pool(\n if candidates.is_empty() {\n return None;\n }\n- let components = component_ids(group, pool);\n+ let layout = component_layout(group, pool);\n let best = candidates\n .iter()\n- .map(|(a, b)| (pair_priority(group, &components, a, b), (a, b)))\n- .min_by_key(|(p, _)| *p)?\n+ .map(|(a, b)| (pair_sort_key(group, pool, &layout, a, b), (a, b)))\n+ .min_by_key(|(k, _)| *k)?\n .0;\n let best_pairs: Vec<(ItemId, ItemId)> = candidates\n .into_iter()\n- .filter(|(a, b)| pair_priority(group, &components, a, b) == best)\n+ .filter(|(a, b)| pair_sort_key(group, pool, &layout, a, b) == best)\n .collect();\n best_pairs.choose(&mut rand::thread_rng()).cloned()\n }\n@@ -303,6 +444,38 @@ mod tests {\n assert!(from_ab && from_cd, \"expected bridge pair, got {:?}\", chosen);\n }\n \n+ #[test]\n+ fn suggest_prefers_attach_over_isolate_pair_among_many_unranked() {\n+ let parent = ItemId::parse(\"reddit.com/r/rust\").unwrap();\n+ let mut tree = seed_children(\n+ &parent,\n+ &[\n+ \"reddit.com/r/rust/a\",\n+ \"reddit.com/r/rust/b\",\n+ \"reddit.com/r/rust/c\",\n+ \"reddit.com/r/rust/d\",\n+ \"reddit.com/r/rust/e\",\n+ ],\n+ );\n+ let ab =\n+ VoteData::from_recorded(1, \"reddit.com/r/rust/a\", \"reddit.com/r/rust/b\", 2, 1).unwrap();\n+ tree.apply_vote(&parent, ab);\n+ let group = tree.get(&parent).unwrap().local_ranking.clone();\n+ let pool = children_of(&tree, &parent);\n+ let pair = suggest_next_pair_in_pool(&group, &pool, None).unwrap();\n+ let chosen = pair_set(&pair);\n+ let from_ab =\n+ chosen.contains(\"reddit.com/r/rust/a\") || chosen.contains(\"reddit.com/r/rust/b\");\n+ let from_cde = chosen.contains(\"reddit.com/r/rust/c\")\n+ || chosen.contains(\"reddit.com/r/rust/d\")\n+ || chosen.contains(\"reddit.com/r/rust/e\");\n+ assert!(\n+ from_ab && from_cde,\n+ \"expected ranked+unranked attach, got {:?}\",\n+ chosen\n+ );\n+ }\n+\n #[test]\n fn suggest_connects_isolate_to_existing_component() {\n let parent = ItemId::parse(\"reddit.com/r/rust\").unwrap();\n@@ -325,6 +498,65 @@ mod tests {\n assert!(chosen.contains(\"reddit.com/r/rust/a\") || chosen.contains(\"reddit.com/r/rust/b\"));\n }\n \n+ #[test]\n+ fn suggest_zips_adjacent_ranks_when_tree_complete() {\n+ let parent = ItemId::parse(\"reddit.com/r/rust\").unwrap();\n+ let mut tree = seed_children(\n+ &parent,\n+ &[\n+ \"reddit.com/r/rust/a\",\n+ \"reddit.com/r/rust/b\",\n+ \"reddit.com/r/rust/c\",\n+ ],\n+ );\n+ // Star at a connects all three; b-c is the only unvoted adjacent pair left.\n+ for (a, b, l, r) in [\n+ (\"reddit.com/r/rust/a\", \"reddit.com/r/rust/b\", 3, 1),\n+ (\"reddit.com/r/rust/a\", \"reddit.com/r/rust/c\", 2, 1),\n+ ] {\n+ let v = VoteData::from_recorded(1, a, b, l, r).unwrap();\n+ tree.apply_vote(&parent, v);\n+ }\n+ let group = tree.get(&parent).unwrap().local_ranking.clone();\n+ let pool = children_of(&tree, &parent);\n+ let pair = suggest_next_pair_in_pool(&group, &pool, None).unwrap();\n+ let chosen = pair_set(&pair);\n+ // a-b and a-c voted; b-c is the only unvoted adjacent pair in rank order.\n+ assert!(chosen.contains(\"reddit.com/r/rust/b\"));\n+ assert!(chosen.contains(\"reddit.com/r/rust/c\"));\n+ }\n+\n+ #[test]\n+ fn suggest_zip_prefers_1v2_before_2v3_when_both_unvoted() {\n+ let parent = ItemId::parse(\"reddit.com/r/rust\").unwrap();\n+ let mut tree = seed_children(\n+ &parent,\n+ &[\n+ \"reddit.com/r/rust/a\",\n+ \"reddit.com/r/rust/b\",\n+ \"reddit.com/r/rust/c\",\n+ \"reddit.com/r/rust/d\",\n+ ],\n+ );\n+ // Hub at c connects all four; leave rank-adjacent a-b and b-c unvoted.\n+ for (a, b, l, r) in [\n+ (\"reddit.com/r/rust/c\", \"reddit.com/r/rust/d\", 3, 1),\n+ (\"reddit.com/r/rust/b\", \"reddit.com/r/rust/c\", 2, 1),\n+ (\"reddit.com/r/rust/a\", \"reddit.com/r/rust/c\", 2, 1),\n+ ] {\n+ let v = VoteData::from_recorded(1, a, b, l, r).unwrap();\n+ tree.apply_vote(&parent, v);\n+ }\n+ let group = tree.get(&parent).unwrap().local_ranking.clone();\n+ let pool = children_of(&tree, &parent);\n+ assert!(pool_fully_connected(&component_layout(&group, &pool), &pool));\n+ let pair = suggest_next_pair_in_pool(&group, &pool, None).unwrap();\n+ let chosen = pair_set(&pair);\n+ // Top adjacent unvoted edge should be a-b (zip index 0), not b-c (index 1).\n+ assert!(chosen.contains(\"reddit.com/r/rust/a\"));\n+ assert!(chosen.contains(\"reddit.com/r/rust/b\"));\n+ }\n+\n #[test]\n fn resolve_pair_picks_from_pool() {\n let parent = ItemId::parse(\"reddit.com/r/rust\").unwrap();\n\n\nSide B — contributor: tommy-mor\nSide B — commit message:\n[8f69c309] Require Reddit OAuth when credentials are set and refresh on 401/403.\n\nAvoid falling back to the public www.reddit.com API from cloud IPs, which\nreturns Reddit's network-security block page. Also pin SORTER2_BASE_URL in fly.toml.\n\nCo-authored-by: Cursor \n\nSide B — unified diff (full patch):\ndiff --git a/fly.toml b/fly.toml\nindex f0c6a39f643c204987debc177234d95a8ef44b65..ca7e0088a7efd7d58d29d808f8d89080b2bff233 100644\n--- a/fly.toml\n+++ b/fly.toml\n@@ -5,6 +5,7 @@ primary_region = \"iad\"\n dockerfile = \"Dockerfile\"\n \n [env]\n+ SORTER2_BASE_URL = \"https://reddit.sorter.social\"\n SORTER2_DATA_DIR = \"/data\"\n SORTER2_EVENT_LOG = \"/data/events.jsonl\"\n PORT = \"8080\"\ndiff --git a/server/src/reddit.rs b/server/src/reddit.rs\nindex a874814f8927192ee62cab2d0db1efd27dcd57b7..f409764c1e1f36216f1b08107043c2eab905694c 100644\n--- a/server/src/reddit.rs\n+++ b/server/src/reddit.rs\n@@ -283,26 +283,35 @@ async fn reddit_worker(\n );\n tokio::time::sleep(current_delay).await;\n \n- if let Some(c) = &creds {\n- oauth = ensure_oauth_token(&client, &oauth_token_base, c, oauth.take()).await;\n- }\n-\n- let token = oauth.as_ref().map(|t| t.access_token.as_str());\n- let fetch_base = if token.is_some() {\n- tracing::debug!(\n- item = %fetch_id,\n- base = %oauth_api_base,\n- \"reddit fetch using OAuth bearer\"\n- );\n- &oauth_api_base\n- } else {\n- &api_base\n- };\n- let url = match kind {\n- FetchKind::SelfEntity => map_item_to_reddit_api(&fetch_id, fetch_base),\n- FetchKind::Children => map_children_url(&fetch_id, fetch_base),\n+ let outcome = match &creds {\n+ Some(c) => {\n+ // OAuth is required when credentials are configured — never fall\n+ // back to the public www.reddit.com JSON endpoints (cloud IPs\n+ // get blocked with a 403 HTML interstitial).\n+ fetch_with_oauth(\n+ &client,\n+ &oauth_token_base,\n+ &oauth_api_base,\n+ c,\n+ &mut oauth,\n+ &fetch_id,\n+ kind,\n+ )\n+ .await\n+ }\n+ None => {\n+ let url = match kind {\n+ FetchKind::SelfEntity => map_item_to_reddit_api(&fetch_id, &api_base),\n+ FetchKind::Children => map_children_url(&fetch_id, &api_base),\n+ };\n+ match do_fetch(&client, &url, &fetch_id, None).await {\n+ Ok(FetchOutcome::AuthRejected { status, detail }) => {\n+ Err(format!(\"Reddit API {status}: {detail}\"))\n+ }\n+ other => other,\n+ }\n+ }\n };\n- let outcome = do_fetch(&client, &url, &fetch_id, token).await;\n \n match outcome {\n Ok(FetchOutcome::Payload(payload)) => {\n@@ -342,6 +351,12 @@ async fn reddit_worker(\n current_delay = (current_delay * 2).min(Duration::from_secs(60));\n notify(done, FetchJobResult::RateLimited { reset_secs });\n }\n+ Ok(FetchOutcome::AuthRejected { status, detail }) => {\n+ let e = format!(\"Reddit API {status}: {detail}\");\n+ tracing::warn!(item = %fetch_id, err = %e, \"reddit fetch auth rejected\");\n+ current_delay = (current_delay * 2).min(Duration::from_secs(60));\n+ notify(done, FetchJobResult::Failed(e));\n+ }\n Err(e) => {\n tracing::warn!(item = %fetch_id, err = %e, \"reddit fetch failed\");\n current_delay = (current_delay * 2).min(Duration::from_secs(60));\n@@ -357,6 +372,60 @@ enum FetchOutcome {\n Payload(Value),\n NotFound,\n RateLimited { reset_secs: u64 },\n+ /// Bearer rejected — caller should drop the cached token and retry once.\n+ AuthRejected { status: StatusCode, detail: String },\n+}\n+\n+async fn fetch_with_oauth(\n+ client: &Client,\n+ oauth_token_base: &str,\n+ oauth_api_base: &str,\n+ creds: &RedditCredentials,\n+ oauth: &mut Option,\n+ fetch_id: &ItemId,\n+ kind: FetchKind,\n+) -> Result {\n+ for attempt in 0..2 {\n+ let force_refresh = attempt > 0;\n+ *oauth = Some(\n+ ensure_oauth_token(client, oauth_token_base, creds, oauth.take(), force_refresh)\n+ .await?,\n+ );\n+ let token = oauth\n+ .as_ref()\n+ .expect(\"token set above\")\n+ .access_token\n+ .clone();\n+\n+ tracing::debug!(\n+ item = %fetch_id,\n+ base = %oauth_api_base,\n+ attempt,\n+ \"reddit fetch using OAuth bearer\"\n+ );\n+\n+ let url = match kind {\n+ FetchKind::SelfEntity => map_item_to_reddit_api(fetch_id, oauth_api_base),\n+ FetchKind::Children => map_children_url(fetch_id, oauth_api_base),\n+ };\n+ match do_fetch(client, &url, fetch_id, Some(&token)).await? {\n+ FetchOutcome::AuthRejected { status, detail } if attempt == 0 => {\n+ tracing::warn!(\n+ item = %fetch_id,\n+ %status,\n+ %detail,\n+ \"reddit OAuth rejected; refreshing token and retrying\"\n+ );\n+ *oauth = None;\n+ continue;\n+ }\n+ FetchOutcome::AuthRejected { status, detail } => {\n+ return Err(format!(\"Reddit API {status}: {detail}\"));\n+ }\n+ other => return Ok(other),\n+ }\n+ }\n+ unreachable!(\"loop always returns\")\n }\n \n async fn ensure_oauth_token(\n@@ -364,35 +433,35 @@ async fn ensure_oauth_token(\n oauth_base: &str,\n creds: &RedditCredentials,\n existing: Option,\n-) -> Option {\n- if let Some(t) = existing {\n- if Instant::now() < t.expires_at - Duration::from_secs(60) {\n- tracing::debug!(\"reddit OAuth token still valid\");\n- return Some(t);\n+ force_refresh: bool,\n+) -> Result {\n+ if !force_refresh {\n+ if let Some(t) = existing {\n+ if Instant::now() < t.expires_at - Duration::from_secs(60) {\n+ tracing::debug!(\"reddit OAuth token still valid\");\n+ return Ok(t);\n+ }\n }\n }\n \n let url = format!(\"{}/api/v1/access_token\", oauth_base.trim_end_matches('/'));\n- tracing::debug!(%url, \"reddit OAuth token request\");\n+ tracing::debug!(%url, force_refresh, \"reddit OAuth token request\");\n \n let resp = client\n .post(&url)\n .basic_auth(&creds.client_id, Some(&creds.client_secret))\n .form(&[(\"grant_type\", \"client_credentials\")])\n .send()\n- .await;\n-\n- let resp = match resp {\n- Ok(r) => r,\n- Err(e) => {\n- tracing::warn!(\"reddit OAuth token request failed: {e}\");\n- return None;\n- }\n- };\n+ .await\n+ .map_err(|e| format!(\"Reddit OAuth token request failed: {e}\"))?;\n \n if !resp.status().is_success() {\n- tracing::warn!(\"reddit OAuth token HTTP {}\", resp.status());\n- return None;\n+ let status = resp.status();\n+ let body = resp.text().await.unwrap_or_default();\n+ return Err(format!(\n+ \"Reddit OAuth token HTTP {status}: {}\",\n+ truncate_for_error(&body)\n+ ));\n }\n \n #[derive(Deserialize)]\n@@ -401,21 +470,40 @@ async fn ensure_oauth_token(\n expires_in: u64,\n }\n \n- let body: TokenResponse = match resp.json().await {\n- Ok(b) => b,\n- Err(e) => {\n- tracing::warn!(\"reddit OAuth token parse failed: {e}\");\n- return None;\n- }\n- };\n+ let body: TokenResponse = resp\n+ .json()\n+ .await\n+ .map_err(|e| format!(\"Reddit OAuth token parse failed: {e}\"))?;\n \n- tracing::debug!(expires_in = body.expires_in, \"reddit OAuth token acquired\");\n- Some(OAuthToken {\n+ tracing::info!(expires_in = body.expires_in, \"reddit OAuth token acquired\");\n+ Ok(OAuthToken {\n access_token: body.access_token,\n expires_at: Instant::now() + Duration::from_secs(body.expires_in),\n })\n }\n \n+fn truncate_for_error(body: &str) -> String {\n+ let compact: String = body.split_whitespace().collect::>().join(\" \");\n+ if compact.is_empty() {\n+ return \"(empty body)\".into();\n+ }\n+ // Prefer the human-readable block message over dumping Reddit's CSS.\n+ if let Some(idx) = compact.find(\"You've been blocked\") {\n+ let slice: String = compact.chars().skip(idx).take(160).collect();\n+ return if compact.chars().count() > idx + 160 {\n+ format!(\"{slice}…\")\n+ } else {\n+ slice\n+ };\n+ }\n+ let chars: String = compact.chars().take(200).collect();\n+ if compact.chars().count() > 200 {\n+ format!(\"{chars}…\")\n+ } else {\n+ chars\n+ }\n+}\n+\n async fn do_fetch(\n client: &Client,\n url: &str,\n@@ -460,15 +548,16 @@ async fn do_fetch(\n \n if !status.is_success() {\n let body = resp.text().await.unwrap_or_default();\n+ let detail = truncate_for_error(&body);\n tracing::debug!(\n item = %id,\n %status,\n body_len = body.len(),\n- body_prefix = %body.chars().take(240).collect::(),\n+ %detail,\n \"reddit non-success body\"\n );\n if status == StatusCode::FORBIDDEN || status == StatusCode::UNAUTHORIZED {\n- return Err(format!(\"Reddit API {status}: {body}\"));\n+ return Ok(FetchOutcome::AuthRejected { status, detail });\n }\n return Ok(FetchOutcome::NotFound);\n }\n@@ -716,6 +805,15 @@ fn reddit_direct_image_url(url: &str) -> bool {\n mod tests {\n use super::*;\n \n+ #[test]\n+ fn truncate_error_prefers_block_message() {\n+ let html = r#\"
You've been blocked by network security. To continue, log in
\"#;\n+ let msg = truncate_for_error(html);\n+ assert!(msg.starts_with(\"You've been blocked\"));\n+ assert!(msg.len() < 200);\n+ assert!(!msg.contains(\".x{color\"));\n+ }\n+\n #[test]\n fn map_subreddit_about_url() {\n let id = ItemId::from_url(\"https://reddit.com/r/rust\").unwrap();\n","role":"user"}],"model":"openai/gpt-chat-latest"}