{"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[239f4693] Point body/matchup 404s at garden children when path is a scope\n\ngarden body ~/portraits 404s with a bare does-not-exist hint even\nthough garden children -- portraits ranks 22 members. When the leaf is\nabsent from items but has scope members, the hint now names the scope,\nits child count, and the exact children command to run.\n\nSide A — unified diff (full patch):\ndiff --git a/server/src/api/rpc.rs b/server/src/api/rpc.rs\nindex 83cd06182ce4d0139f4d7fb77965acd938d50f4f..a8b960491de845fa876da7ad9bd3204766ff4999 100644\n--- a/server/src/api/rpc.rs\n+++ b/server/src/api/rpc.rs\n@@ -1065,13 +1065,31 @@ pub async fn dispatch_rpc(state: &AppState, headers: &HeaderMap, cmd: RpcCommand\n .unwrap_or_else(|| ItemId::opaque(item_str.clone()));\n let item_str = item.as_str().to_string();\n if !content.items.contains(&item) {\n- line_err(\n- \"item not found\",\n- Some(format!(\n- \"{} does not exist\",\n- GardenItemUrl::from_storage_str(&item_str, &room)\n- )),\n- )\n+ let members = content.members_of(&item);\n+ if !members.is_empty() {\n+ let leaf = item.last_segment();\n+ let children_cmd = if room == \"public\" {\n+ format!(\"npx slugsocial@latest public garden children -- {leaf}\")\n+ } else {\n+ format!(\"npx slugsocial@latest private {room} garden children -- {leaf}\")\n+ };\n+ line_err(\n+ \"item not found\",\n+ Some(format!(\n+ \"{} is a scope with {} children, not an item with a body (folder paths are scopes, not vote targets); rank them with: {children_cmd}\",\n+ GardenItemUrl::from_storage_str(&item_str, &room),\n+ members.len(),\n+ )),\n+ )\n+ } else {\n+ line_err(\n+ \"item not found\",\n+ Some(format!(\n+ \"{} does not exist\",\n+ GardenItemUrl::from_storage_str(&item_str, &room)\n+ )),\n+ )\n+ }\n } else {\n let want_full = full.unwrap_or(false);\n let (body, truncated, body_len) = match content.item_bodies.get(&item) {\n@@ -1505,13 +1523,31 @@ pub async fn dispatch_rpc(state: &AppState, headers: &HeaderMap, cmd: RpcCommand\n let item_str = item.as_str().to_string();\n let limit = limit.unwrap_or(50).clamp(1, 200);\n if !content.items.contains(&item) {\n- line_err(\n- \"item not found\",\n- Some(format!(\n- \"{} does not exist\",\n- GardenItemUrl::from_storage_str(&item_str, &room)\n- )),\n- )\n+ let members = content.members_of(&item);\n+ if !members.is_empty() {\n+ let leaf = item.last_segment();\n+ let children_cmd = if room == \"public\" {\n+ format!(\"npx slugsocial@latest public garden children -- {leaf}\")\n+ } else {\n+ format!(\"npx slugsocial@latest private {room} garden children -- {leaf}\")\n+ };\n+ line_err(\n+ \"item not found\",\n+ Some(format!(\n+ \"{} is a scope with {} children, not an item with vote history (folder paths are scopes, not vote targets); rank them with: {children_cmd}\",\n+ GardenItemUrl::from_storage_str(&item_str, &room),\n+ members.len(),\n+ )),\n+ )\n+ } else {\n+ line_err(\n+ \"item not found\",\n+ Some(format!(\n+ \"{} does not exist\",\n+ GardenItemUrl::from_storage_str(&item_str, &room)\n+ )),\n+ )\n+ }\n } else {\n let votes: Vec = content\n .item_votes\n\n\nSide B — contributor: tommy-mor\nSide B — commit message:\n[279ebd55] Add score-history replay at ?v=history (the sorter-proof chart, grown up)\n\nScope pages now carry an always-visible bar above the ranked children\nthat links \"open the replay →\" once >=2 members carry >=2 member<->member\nvote events (empty state + vote link until then; childless leaves stay\nclean). The replay is a query-param view of the scope page itself:\n\n- ?v=history serves a one-HTML-file React app — the sorter-proof\n \"Ranking Replay 2\" stack verbatim (CDN React 18 UMD + babel-standalone\n + Chart.js + React Query, inline JSX): autoplay/scrub/speed controls,\n hue-rotated tension-0.4 lines, current-rankings + unsorted legend,\n 5s polling, and the clickable comparison matrix whose cells open the\n full vote reasoning.\n- ?v=history.json serves {criteria, items, history[], final_matrix}.\n Each step re-solves the scope's member<->member vote graph through the\n reducer's own kernel (GroupState::apply_vote -> rank_partition) — one\n honest solve per event, never scores mixed from different solves.\n- Vote dedupe takes each vote once from the smaller endpoint's\n item_votes list; repeated same-pair votes still add. Matrix weights\n are pairwise win shares with quoted reasoning.\n- Capped at 240 events / 64 members. Room-scoped and external scope\n pages get the same view via the render_scope_view branch.\n\nagents.md updated. Rust: 412/412. Kaocha: 24 tests, 631 assertions, 0 failures.\n\nSide B — unified diff (full patch):\ndiff --git a/agents.md b/agents.md\nindex 188a63c9383d84b6f2ed188d7bbf40f31afe2794..4f42d4bd48d8aa0728ea692c2420f2af5b6e81d9 100644\n--- a/agents.md\n+++ b/agents.md\n@@ -76,6 +76,8 @@ Strict **CSP** that blocks `eval` would break the current app. Other projects ma\n \n - **Aspect sub-scopes:** A `:slug` / `:slug {prompt}` / bare `:` statement is parse-derived from ingest text (no event-schema change, no new write path). Votes under an aspect go to a ranking group keyed `(scope_item, aspect)` where `scope_item` is a shared active-membership scope of both vote items; the canonical `ranking_group` and `rank_position_cache` stay aspect-free. Garden parent/item pages (`render_scope_view`, public `~/`) and the `/try` editor preview list aspect sections **below** the canonical ranking when that scope has aspect votes (heading `:{slug}`, optional prompt). No `?aspect=` routes or default-aspect redirects. CLI `garden children --aspect` / `garden rank --aspect` and MCP `get_rank.aspect` are opt-in reads via `GetGardenRank.aspect`. Prompts live on `ContentState.aspect_prompts` per `(room scope, slug)`. `parent_path` in those reads resolves to its leaf item (`~/x/luke` → `~luke`).\n \n+- **Garden score-history replay (`?v=history`):** Scope pages carry an always-visible `ont-history-link` bar above the ranked children table (`score_history_link_panel` in `server/src/html/garden/replay.rs`): with sufficient history (≥2 members and ≥2 member↔member vote events) it links **\"open the replay →\"**; otherwise an empty state (\"score history draws itself once two or more members carry votes\") plus a vote-on-children link when ≥2 children exist. Childless leaf pages render no bar. The replay is a **query-param view of the scope page** (branched in `render_scope_view`): `?v=history` serves a one-HTML-file React app — the sorter-proof \"Ranking Replay 2\" stack verbatim (CDN React 18 UMD + babel-standalone + Chart.js + React Query, inline JSX; autoplay/scrub/speed controls, hue-rotated `tension: 0.4` lines, current-rankings + unsorted legend, clickable comparison matrix with reasoning dialog, 5s polling) bound to a fixed data URL via `window.SLUG_REPLAY` — and `?v=history.json` serves the payload `{criteria, items, history[], final_matrix}` built from `ContentState`: per-event snapshots **re-solve the scope's member↔member vote graph through the reducer's own kernel** (`GroupState::apply_vote` + `rank_partition`), one honest solve per vote event (cap 240 events / 64 members); comparisons and matrix cells quote vote reasonings from `item_votes` (matrix `weight` = pairwise win share in percent). Bar CSS lives in the `Garden score-history replay link` block of every theme.\n+\n - **Garden page flow and edge anchors:** `~/` item pages read top → bottom as **parents (↑ `member of` card) → body → children (↓ ranked table)**. A blue **flow gradient** on the left edge descends parents (full blue) → hero (mid) → children (grey) — see the `GARDEN HIERARCHY` block in each of `theme_default.css`, `theme_retro_craft.css`, and `theme_retro.css`; garden hierarchy CSS (including the structural flex that keeps per-edge vote/§ links off parent titles) must exist in every theme that styles ontology pages. Every containment edge has a fragment URL: `#edge--in-` on the child's page (each parent row links its scope vote pool as the vote home, plus a `§` permalink), and `#item-` on ranked/unranked rows of the parent scope page (`aspect--` prefixed in aspect tables). Weight footnotes show totals only (`containment N · border M`); path sugar is not distinguished in the UI.\n \n - **Browser auth redirects:** `/login`, `/join/:token`, `/auth/login`, and `/auth/choose-username` may carry **`next`** (or legacy **`redirect`**) as a **safe local path only**. The value is stored on the RAM-only pending session and applied after OAuth / username selection.\ndiff --git a/server/src/html/garden/mod.rs b/server/src/html/garden/mod.rs\nindex 3dd3b7730834f26bce1caf156ff74a4e35cffbf6..49408de6adcfc2aefc9337b41d2eecb5d75e7d83 100644\n--- a/server/src/html/garden/mod.rs\n+++ b/server/src/html/garden/mod.rs\n@@ -8,6 +8,7 @@ mod item;\n mod item_page;\n mod pin;\n mod render;\n+mod replay;\n mod routes;\n mod vote;\n \ndiff --git a/server/src/html/garden/render.rs b/server/src/html/garden/render.rs\nindex 2260efcac3a5efc6b971b586e449300ecb5c7a4d..83e46cf83da440fa1816bd0736a6db846eb7150c 100644\n--- a/server/src/html/garden/render.rs\n+++ b/server/src/html/garden/render.rs\n@@ -30,6 +30,10 @@ use super::{\n build_item_page_view_model, fragment_slug, item_relations_markup, AspectRankingView,\n },\n pin::{child_row_pin_or_vote, ont_pin_vote_controls, pinned_item_from_jar},\n+ replay::{\n+ replay_history_json_response, replay_mode_from_uri, replay_page_response,\n+ score_history_link_panel, ReplayMode,\n+ },\n vote::vote_pool_href,\n };\n \n@@ -132,6 +136,15 @@ pub(super) async fn render_scope_view(\n let child_depth = child_depth_from_uri(&uri);\n let model = build_item_page_view_model(&reduced, &scope, browse.item(), child_depth);\n let scope_content = content_for_garden_view(&reduced, &scope);\n+ // The replay is a query-param view of the scope page itself: `?v=history`\n+ // serves the one-file React app, `?v=history.json` its data payload.\n+ match replay_mode_from_uri(&uri) {\n+ Some(ReplayMode::Page) => return replay_page_response(&nav, &model.item),\n+ Some(ReplayMode::Data) => {\n+ return replay_history_json_response(scope_content, &model.child_rankings, &model.item);\n+ }\n+ None => {}\n+ }\n let thread_href = |tag: &str| nav.thread_url(tag);\n let external_empty_body = browse.is_external() && model.body.is_none();\n let cli_path_arg = item_display_path(&model.item);\n@@ -329,6 +342,19 @@ pub(super) async fn render_scope_view(\n @if model.child_rankings.component_rankings.is_empty() {\n p class=\"muted\" { \"no voted pairs yet in this scope\" }\n }\n+ @if let Some(panel) = score_history_link_panel(\n+ scope_content,\n+ &model.child_rankings,\n+ &nav,\n+ &model.item,\n+ if total_children >= 2 {\n+ Some(vote_pool_href(&nav, &model.item))\n+ } else {\n+ None\n+ },\n+ ) {\n+ (panel)\n+ }\n (ont_ranking_lists_markup(\n &model.child_rankings,\n &nav,\ndiff --git a/server/src/html/garden/replay.rs b/server/src/html/garden/replay.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..826cee280f381506805122c01af1aa648bc193f4\n--- /dev/null\n+++ b/server/src/html/garden/replay.rs\n@@ -0,0 +1,956 @@\n+//! Score-history replay: the sorter-proof \"Ranking Replay 2\" experience —\n+//! one-HTML-file React app (CDN React 18 + babel-standalone + Chart.js +\n+//! React Query, inline JSX) served as a query-param view of any scope page.\n+//!\n+//! - `GET /~/?v=history` → the replay app (its own full page)\n+//! - `GET /~/?v=history.json` → the sorter-proof-shaped data payload\n+//! `{criteria, items, history[], final_matrix}` built from `ContentState`:\n+//! per-event snapshots **re-solve the scope's member↔member vote graph**\n+//! through the reducer's own kernel (`GroupState::apply_vote` →\n+//! `rank_partition`), one honest solve per vote event — never scores mixed\n+//! from different solves the way per-item rank-history carry-forward would\n+//! mix them. Comparisons and matrix cells quote vote reasonings from\n+//! `item_votes`.\n+//!\n+//! The flat scope page links here via [`score_history_link_panel`], which is\n+//! always visible on scopes with members (empty state until history suffices).\n+\n+use std::collections::{BTreeMap, HashMap, HashSet};\n+\n+use axum::http::Uri;\n+use axum::response::{Html, IntoResponse};\n+use maud::{html, Markup};\n+use serde::Serialize;\n+\n+use crate::html::ThreadNav;\n+use crate::path_types::ItemId;\n+use crate::reducer::{ContentState, VoteData};\n+use crate::scope_rank::ChildrenRankings;\n+\n+use super::item::{item_display_path, item_href};\n+\n+/// Most vote events replayed (recent window when history is longer).\n+const MAX_EVENTS: usize = 240;\n+/// Most members in the replay (chart datasets and matrix rows alike).\n+const MAX_MEMBERS: usize = 64;\n+\n+/// Which replay response a `?v=` query selects.\n+#[derive(Debug, Clone, Copy, PartialEq, Eq)]\n+pub(super) enum ReplayMode {\n+ /// `?v=history` — the app page.\n+ Page,\n+ /// `?v=history.json` — the data payload the app polls.\n+ Data,\n+}\n+\n+pub(super) fn replay_mode_from_uri(uri: &Uri) -> Option {\n+ uri.query()\n+ .into_iter()\n+ .flat_map(|q| q.split('&'))\n+ .find_map(|pair| pair.strip_prefix(\"v=\"))\n+ .and_then(|v| match v {\n+ \"history\" => Some(ReplayMode::Page),\n+ \"history.json\" => Some(ReplayMode::Data),\n+ _ => None,\n+ })\n+}\n+\n+#[derive(Debug, Clone, Serialize)]\n+pub(super) struct ReplayRanked {\n+ item: String,\n+ score: f64,\n+}\n+\n+#[derive(Debug, Clone, Serialize)]\n+pub(super) struct ReplayComparison {\n+ left: String,\n+ right: String,\n+ score: f64,\n+ explanation: String,\n+}\n+\n+#[derive(Debug, Clone, Serialize)]\n+pub(super) struct ReplayStep {\n+ timestamp: i64,\n+ comparison: ReplayComparison,\n+ current_rankings: Vec,\n+ unsorted_items: Vec,\n+}\n+\n+#[derive(Debug, Clone, Serialize)]\n+pub(super) struct MatrixDetails {\n+ score: f64,\n+ explanation: String,\n+}\n+\n+#[derive(Debug, Clone, Serialize, Default)]\n+pub(super) struct MatrixCell {\n+ #[serde(skip_serializing_if = \"is_zero_weight\")]\n+ weight: f64,\n+ #[serde(skip_serializing_if = \"Option::is_none\")]\n+ details: Option,\n+}\n+\n+fn is_zero_weight(w: &f64) -> bool {\n+ *w == 0.0\n+}\n+\n+#[derive(Debug, Clone, Serialize)]\n+pub(super) struct ReplayData {\n+ criteria: String,\n+ items: Vec,\n+ history: Vec,\n+ final_matrix: Vec>,\n+ /// Members omitted from the replay (over [`MAX_MEMBERS`]).\n+ truncated_members: usize,\n+ /// False when there is not enough history to chart (panel shows the\n+ /// empty state instead of the replay link).\n+ #[serde(skip_serializing)]\n+ sufficient: bool,\n+}\n+\n+/// `Forward: a / ---- / b / REASONING: body` — the sorter-proof explanation card.\n+fn format_vote_explanation(content_label: &impl Fn(&ItemId) -> String, v: &VoteData) -> String {\n+ format!(\n+ \"Forward: {}\\n---------\\n{}\\n\\nREASONING:\\n{}\",\n+ content_label(&v.a),\n+ content_label(&v.b),\n+ if v.body.trim().is_empty() {\n+ \"(no reasoning recorded)\"\n+ } else {\n+ v.body.trim()\n+ }\n+ )\n+}\n+\n+/// Signed log-ratio scaled like the prototype's comparison scores\n+/// (3:1 → +11.0, 3:2 → +4.1, 1:2 → −6.9, 1:1 → 0.0).\n+fn vote_score(ratio_left: i32, ratio_right: i32) -> f64 {\n+ let l = (ratio_left.max(1)) as f64;\n+ let r = (ratio_right.max(1)) as f64;\n+ let v = (l / r).ln() * 10.0;\n+ (v * 10.0).round() / 10.0\n+}\n+\n+/// Build the replay payload for one scope, or `None` when the scope has no\n+/// members at all (childless leaf pages get neither panel nor replay).\n+pub(super) fn build_replay(\n+ content: &ContentState,\n+ rankings: &ChildrenRankings,\n+ scope_item: &str,\n+) -> Option {\n+ // Members in display order: ranked across components, then unranked.\n+ let mut members: Vec = rankings\n+ .component_rankings\n+ .iter()\n+ .flat_map(|c| c.ranked.iter().map(|r| r.item.ontology_leaf()))\n+ .collect();\n+ members.extend(rankings.unranked_items.iter().map(|i| i.ontology_leaf()));\n+ let mut seen = HashSet::new();\n+ members.retain(|m| seen.insert(m.clone()));\n+ if members.is_empty() {\n+ return None;\n+ }\n+\n+ let total_members = members.len();\n+ let truncated_members = total_members.saturating_sub(MAX_MEMBERS);\n+ members.truncate(MAX_MEMBERS);\n+ let member_set: HashSet<&ItemId> = members.iter().collect();\n+ let label_of = |item: &ItemId| item_display_path(item.as_str());\n+ let leaf = ItemId::parse(scope_item)\n+ .map(|id| id.ontology_leaf())\n+ .unwrap_or_else(|| ItemId::opaque(scope_item.to_string()));\n+ let criteria = content\n+ .item_bodies\n+ .get(&leaf)\n+ .map(|b| b.trim().to_string())\n+ .filter(|b| !b.is_empty())\n+ .unwrap_or_else(|| format!(\"members of {}\", item_display_path(scope_item)));\n+\n+ // Member↔member canonical votes, each counted once: a vote is recorded in\n+ // both endpoints' `item_votes` lists, so we take it only from the smaller\n+ // endpoint's list (multiple votes on the same pair stay distinct events).\n+ let mut votes_by_ts: BTreeMap> = BTreeMap::new();\n+ for m in &members {\n+ if let Some(vs) = content.item_votes.get(m) {\n+ for v in vs {\n+ let lo = if v.a <= v.b { &v.a } else { &v.b };\n+ if lo == m && member_set.contains(&v.a) && member_set.contains(&v.b) {\n+ votes_by_ts.entry(v.ts).or_default().push(v);\n+ }\n+ }\n+ }\n+ }\n+ let all_steps: Vec = votes_by_ts.keys().copied().collect();\n+ let steps: &[i64] = if all_steps.len() > MAX_EVENTS {\n+ &all_steps[all_steps.len() - MAX_EVENTS..]\n+ } else {\n+ &all_steps\n+ };\n+ let sufficient = members.len() >= 2 && steps.len() >= 2;\n+\n+ // Replay the scope's own vote graph through the same kernel the reducer\n+ // uses (`GroupState::apply_vote` → `rank_partition`), solving after every\n+ // event so each snapshot is one honest solve — never scores mixed from\n+ // different solves the way per-item rank-history carry-forward would be.\n+ let mut group = crate::reducer::GroupState::new();\n+ let mut history: Vec = Vec::with_capacity(steps.len());\n+ for &ts in steps {\n+ if let Some(step_votes) = votes_by_ts.get(&ts) {\n+ for v in step_votes {\n+ group.apply_vote((*v).clone());\n+ }\n+ }\n+ let (mut comps, _) = crate::ranking::connected_components_from_voted_pairs(\n+ group.idx_to_item.len(),\n+ group.voted_pairs.iter().copied(),\n+ );\n+ comps.sort_by_key(|b| std::cmp::Reverse(b.len()));\n+ let mut scores: HashMap = HashMap::new();\n+ for ranked in crate::ranking::rank_partition(&group, &comps, 10000, 1e-8) {\n+ for r in ranked {\n+ scores.insert(r.item, r.score);\n+ }\n+ }\n+ let mut current_rankings = Vec::new();\n+ let mut unsorted_items = Vec::new();\n+ for m in &members {\n+ match scores.get(m) {\n+ Some(&score) => current_rankings.push(ReplayRanked {\n+ item: label_of(m),\n+ score,\n+ }),\n+ None => unsorted_items.push(label_of(m)),\n+ }\n+ }\n+ let step_votes = votes_by_ts.get(&ts).cloned().unwrap_or_default();\n+ let comparison = match step_votes.first() {\n+ Some(v) => ReplayComparison {\n+ left: label_of(&v.a),\n+ right: label_of(&v.b),\n+ score: vote_score(v.ratio_left, v.ratio_right),\n+ explanation: step_votes\n+ .iter()\n+ .map(|v| format_vote_explanation(&label_of, v))\n+ .collect::>()\n+ .join(\"\\n\\n---\\n\\n\"),\n+ },\n+ None => ReplayComparison {\n+ left: String::new(),\n+ right: String::new(),\n+ score: 0.0,\n+ explanation: \"no votes on this scope's members in this event\".to_string(),\n+ },\n+ };\n+ history.push(ReplayStep {\n+ timestamp: ts,\n+ comparison,\n+ current_rankings,\n+ unsorted_items,\n+ });\n+ }\n+\n+ // Pairwise matrix over members: win share + quoted reasoning per edge.\n+ let n = members.len();\n+ let mut final_matrix: Vec> = vec![vec![MatrixCell::default(); n]; n];\n+ for (i, mi) in members.iter().enumerate() {\n+ let Some(votes) = content.item_votes.get(mi) else {\n+ continue;\n+ };\n+ for (j, mj) in members.iter().enumerate() {\n+ if i == j {\n+ continue;\n+ }\n+ let edge: Vec<&VoteData> = votes\n+ .iter()\n+ .filter(|v| {\n+ (&v.a == mi && &v.b == mj) || (&v.a == mj && &v.b == mi)\n+ })\n+ .collect();\n+ if edge.is_empty() {\n+ continue;\n+ }\n+ let shares: Vec = edge\n+ .iter()\n+ .map(|v| {\n+ let l = v.ratio_left.max(1) as f64;\n+ let r = v.ratio_right.max(1) as f64;\n+ if &v.a == mi {\n+ l / (l + r)\n+ } else {\n+ r / (l + r)\n+ }\n+ })\n+ .collect();\n+ let mean = shares.iter().sum::() / shares.len() as f64;\n+ let clamped = mean.clamp(0.01, 0.99);\n+ final_matrix[i][j] = MatrixCell {\n+ weight: (mean * 1000.0).round() / 10.0,\n+ details: Some(MatrixDetails {\n+ score: (((clamped / (1.0 - clamped)).ln() * 10.0) * 10.0).round() / 10.0,\n+ explanation: edge\n+ .iter()\n+ .map(|v| format_vote_explanation(&label_of, v))\n+ .collect::>()\n+ .join(\"\\n\\n---\\n\\n\"),\n+ }),\n+ };\n+ }\n+ }\n+\n+ Some(ReplayData {\n+ criteria,\n+ items: members.iter().map(label_of).collect(),\n+ history,\n+ final_matrix,\n+ truncated_members,\n+ sufficient,\n+ })\n+}\n+\n+/// The `?v=history.json` payload.\n+pub(super) fn replay_history_json_response(\n+ content: &ContentState,\n+ rankings: &ChildrenRankings,\n+ scope_item: &str,\n+) -> axum::response::Response {\n+ match build_replay(content, rankings, scope_item) {\n+ Some(data) => axum::Json(serde_json::to_value(data).expect(\"replay serializes\"))\n+ .into_response(),\n+ None => (\n+ axum::http::StatusCode::NOT_FOUND,\n+ \"no members in this scope\",\n+ )\n+ .into_response(),\n+ }\n+}\n+\n+/// HTML-escape for the page ``.\n+fn esc(s: &str) -> String {\n+ s.replace('&', \"&\")\n+ .replace('<', \"<\")\n+ .replace('>', \">\")\n+ .replace('\"', \""\")\n+}\n+\n+/// The `?v=history` page: one HTML file, the sorter-proof stack verbatim.\n+pub(super) fn replay_page_response(nav: &ThreadNav, scope_item: &str) -> axum::response::Response {\n+ let display = item_display_path(scope_item);\n+ let back_href = item_href(scope_item, nav);\n+ let config = serde_json::json!({\n+ \"dataUrl\": format!(\"{back_href}?v=history.json\"),\n+ \"backHref\": back_href,\n+ \"backLabel\": display,\n+ });\n+ // serde_json does not escape '<' — keep the config safe inside <script>.\n+ let config = config.to_string().replace(\"</\", \"<\\\\/\");\n+ let page = REPLAY_HTML\n+ .replace(\"__SLUG_TITLE__\", &esc(&format!(\"{display} · score history\")))\n+ .replace(\"__SLUG_CONFIG__\", &config);\n+ Html(page).into_response()\n+}\n+\n+/// The flat-page link bar: always visible on scopes with members. Links to\n+/// `?v=history` when history suffices; otherwise an empty state naming what\n+/// it waits for (plus a vote link when there are at least two children).\n+pub(super) fn score_history_link_panel(\n+ content: &ContentState,\n+ rankings: &ChildrenRankings,\n+ nav: &ThreadNav,\n+ scope_item: &str,\n+ vote_href: Option<String>,\n+) -> Option<Markup> {\n+ let data = build_replay(content, rankings, scope_item)?;\n+ let replay_href = format!(\"{}?v=history\", item_href(scope_item, nav));\n+ Some(if data.sufficient {\n+ html! {\n+ div class=\"ont-history-link\" {\n+ span class=\"ont-history-link-meta muted\" {\n+ \"score history · \"\n+ (data.items.len())\n+ \" members · \"\n+ (data.history.len())\n+ \" vote events\"\n+ }\n+ \" \"\n+ a class=\"ont-history-link-open\" href=(replay_href) { \"open the replay →\" }\n+ }\n+ }\n+ } else {\n+ html! {\n+ div class=\"ont-history-link ont-history-empty\" {\n+ span class=\"muted\" {\n+ \"score history draws itself once two or more members carry votes\"\n+ }\n+ @if let Some(href) = &vote_href {\n+ \" — \"\n+ a class=\"ont-vote-children-btn\" href=(href.as_str()) { \"vote on children\" }\n+ }\n+ }\n+ }\n+ })\n+}\n+\n+/// The replay app. Stack, styles, chart config, controls, matrix, and dialog\n+/// are the sorter-proof \"Ranking Replay 2\" file adapted only to bind to a\n+/// fixed data URL (`window.SLUG_REPLAY`) instead of the file picker, plus a\n+/// back link and an empty-history state.\n+const REPLAY_HTML: &str = r##\"<!DOCTYPE html>\n+<html>\n+<head>\n+ <meta charset=\"UTF-8\">\n+ <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n+ <title>__SLUG_TITLE__\n+\n+ \n+ \n+ \n+ \n+ \n+ \n+\n+ \n+ \n+ \n+ \n+\n+\n+\n+
\n+ \n+\n+ \n+\n+\n+\"##;\n+\n+#[cfg(test)]\n+mod tests {\n+ use super::*;\n+ use crate::ranking::RankedItem;\n+ use crate::scope_rank::ScopedComponent;\n+\n+ fn vote(ts: i64, a: &ItemId, b: &ItemId, l: i32, r: i32, body: &str) -> VoteData {\n+ VoteData {\n+ ts,\n+ a: a.clone(),\n+ b: b.clone(),\n+ ratio_left: l,\n+ ratio_right: r,\n+ body: body.to_string(),\n+ principal: \"dev\".to_string(),\n+ delegate: None,\n+ thread_tag: \"t\".to_string(),\n+ }\n+ }\n+\n+ fn leaf(name: &str) -> ItemId {\n+ ItemId::parse(name).expect(\"leaf parses\")\n+ }\n+\n+ fn rankings_for(names: &[&str], unranked: &[&str]) -> ChildrenRankings {\n+ ChildrenRankings {\n+ component_rankings: vec![ScopedComponent {\n+ pairs: names.len().saturating_sub(1),\n+ ranked: names\n+ .iter()\n+ .enumerate()\n+ .map(|(i, n)| RankedItem {\n+ item: leaf(n),\n+ score: 1.0 / (i + 1) as f64,\n+ })\n+ .collect(),\n+ }],\n+ unranked_items: unranked.iter().map(|n| leaf(n)).collect(),\n+ }\n+ }\n+\n+ /// Record each vote in both endpoints' lists, exactly like the reducer.\n+ fn content_with_votes(votes: Vec) -> ContentState {\n+ let mut content = ContentState::default();\n+ for v in votes {\n+ content.item_votes.entry(v.a.clone()).or_default().push_front(v.clone());\n+ content.item_votes.entry(v.b.clone()).or_default().push_front(v);\n+ }\n+ content\n+ }\n+\n+ fn score_of(step: &ReplayStep, item: &str) -> Option {\n+ step.current_rankings\n+ .iter()\n+ .find(|r| r.item == item)\n+ .map(|r| r.score)\n+ }\n+\n+ #[test]\n+ fn childless_scope_builds_nothing() {\n+ let content = ContentState::default();\n+ let rankings = rankings_for(&[], &[]);\n+ assert!(build_replay(&content, &rankings, \"~scope\").is_none());\n+ }\n+\n+ #[test]\n+ fn single_event_is_not_yet_a_replay() {\n+ let content = content_with_votes(vec![vote(1, &leaf(\"~a\"), &leaf(\"~b\"), 2, 1, \"a over b\")]);\n+ let rankings = rankings_for(&[\"~a\", \"~b\"], &[]);\n+ let data = build_replay(&content, &rankings, \"~scope\").expect(\"builds\");\n+ assert!(!data.sufficient, \"one vote event is not a replay\");\n+ assert_eq!(data.history.len(), 1);\n+ }\n+\n+ #[test]\n+ fn snapshots_are_fresh_solves_and_laggards_stay_unsorted() {\n+ let content = content_with_votes(vec![\n+ vote(1, &leaf(\"~a\"), &leaf(\"~b\"), 2, 1, \"a over b\"),\n+ vote(2, &leaf(\"~b\"), &leaf(\"~c\"), 2, 1, \"b over c\"),\n+ vote(3, &leaf(\"~a\"), &leaf(\"~c\"), 3, 1, \"a over c\"),\n+ ]);\n+ let rankings = rankings_for(&[\"~a\", \"~b\", \"~c\"], &[]);\n+ let data = build_replay(&content, &rankings, \"~scope\").expect(\"builds\");\n+ assert!(data.sufficient);\n+ assert_eq!(data.history.len(), 3);\n+\n+ // Step 0: only the first pair is connected; the third item waits unsorted.\n+ let step0 = &data.history[0];\n+ assert_eq!(step0.unsorted_items, vec![\"~/c\".to_string()]);\n+ let (a0, b0) = (score_of(step0, \"~/a\").unwrap(), score_of(step0, \"~/b\").unwrap());\n+ assert!(a0 > b0, \"2:1 winner leads the fresh solve\");\n+ assert!((a0 + b0 - 1.0).abs() < 0.05, \"component mass sums to one\");\n+ assert!((data.history[0].comparison.score - 6.9).abs() < 0.05);\n+\n+ // Final step: the whole chain solved, order follows the vote directions.\n+ let last = data.history.last().unwrap();\n+ assert!(last.unsorted_items.is_empty());\n+ let (a, b, c) = (\n+ score_of(last, \"~/a\").unwrap(),\n+ score_of(last, \"~/b\").unwrap(),\n+ score_of(last, \"~/c\").unwrap(),\n+ );\n+ assert!(a > b && b > c, \"a > b > c after the full replay: {a} {b} {c}\");\n+ }\n+\n+ #[test]\n+ fn matrix_weight_and_reasoning_and_dedupe() {\n+ // Two votes on the same pair must both count (the kernel adds them),\n+ // while the mirror copy in the opponent's list must not double them.\n+ let content = content_with_votes(vec![\n+ vote(1, &leaf(\"~a\"), &leaf(\"~b\"), 3, 1, \"a clearly outranks b\"),\n+ vote(2, &leaf(\"~a\"), &leaf(\"~b\"), 2, 1, \"a still outranks b\"),\n+ ]);\n+ let rankings = rankings_for(&[\"~a\", \"~b\"], &[]);\n+ let data = build_replay(&content, &rankings, \"~scope\").expect(\"builds\");\n+ assert_eq!(data.history.len(), 2, \"two events, no dedupe collapse\");\n+\n+ // mean(75%, 66.7%) win share for a over b.\n+ let ab = &data.final_matrix[0][1];\n+ assert!((ab.weight - 70.8).abs() < 0.1, \"weight: {}\", ab.weight);\n+ let details = ab.details.as_ref().expect(\"details\");\n+ assert_eq!(\n+ details.explanation.matches(\"REASONING:\").count(),\n+ 2,\n+ \"both votes quoted\"\n+ );\n+ assert!(details.explanation.contains(\"a clearly outranks b\"));\n+ }\n+\n+ #[test]\n+ fn member_and_event_caps_bite() {\n+ let mut votes = Vec::new();\n+ for t in 0..300 {\n+ votes.push(vote(t, &leaf(\"~m00\"), &leaf(\"~m01\"), 2, 1, \"again\"));\n+ }\n+ let content = content_with_votes(votes);\n+ let names: Vec = (0..70).map(|i| format!(\"~m{i:02}\")).collect();\n+ let refs: Vec<&str> = names.iter().map(String::as_str).collect();\n+ let rankings = rankings_for(&refs, &[]);\n+ let data = build_replay(&content, &rankings, \"~scope\").expect(\"builds\");\n+ assert_eq!(data.items.len(), MAX_MEMBERS);\n+ assert_eq!(data.truncated_members, 70 - MAX_MEMBERS);\n+ assert_eq!(data.history.len(), MAX_EVENTS);\n+ assert_eq!(data.final_matrix.len(), MAX_MEMBERS);\n+ }\n+\n+ #[test]\n+ fn replay_mode_parsing() {\n+ let page: Uri = \"/~/topic?v=history\".parse().unwrap();\n+ assert_eq!(replay_mode_from_uri(&page), Some(ReplayMode::Page));\n+ let data: Uri = \"/~/topic?v=history.json\".parse().unwrap();\n+ assert_eq!(replay_mode_from_uri(&data), Some(ReplayMode::Data));\n+ let depth: Uri = \"/~/topic?depth=2\".parse().unwrap();\n+ assert_eq!(replay_mode_from_uri(&depth), None);\n+ let both: Uri = \"/~/topic?depth=2&v=history\".parse().unwrap();\n+ assert_eq!(replay_mode_from_uri(&both), Some(ReplayMode::Page));\n+ }\n+}\ndiff --git a/server/static/theme_default.css b/server/static/theme_default.css\nindex 25ebde9ecbb7469b33f7baa338609d092b45d0b7..cc6c6b0ce72184c8053b12bff5fa50e5911d1fd4 100644\n--- a/server/static/theme_default.css\n+++ b/server/static/theme_default.css\n@@ -1905,6 +1905,22 @@ body.view-ontology-light .rank-history-vote {\n margin-top: 6px;\n }\n \n+/* Garden score-history replay link (the replay lives at ?v=history) */\n+body.view-ontology .ont-history-link {\n+ background: var(--g2);\n+ border: 1px solid var(--lo);\n+ box-sizing: border-box;\n+ font-size: 0.85em;\n+ margin: 6px 0;\n+ max-width: 100%;\n+ padding: 6px 10px;\n+ width: 100%;\n+}\n+body.view-ontology .ont-history-link-open {\n+ color: var(--link);\n+ font-weight: 600;\n+}\n+\n /* GitHub resolver import cards (rich bodies on -/ garden + vote compare) */\n article.import-card {\n border: 1px solid var(--lo);\ndiff --git a/server/static/theme_retro.css b/server/static/theme_retro.css\nindex 87e298c53d1603dc99c6e3a519aa880a849c63e4..d1ecf3ecbc2e42d9f1d2d5718423782f68c8ccbe 100644\n--- a/server/static/theme_retro.css\n+++ b/server/static/theme_retro.css\n@@ -539,6 +539,22 @@ body.view-ontology .vote-open-links {\n white-space: nowrap;\n }\n \n+/* Garden score-history replay link (the replay lives at ?v=history) */\n+body.view-ontology .ont-history-link {\n+ background: #faf8f3;\n+ border: 1px solid #ccc;\n+ box-sizing: border-box;\n+ font-size: 0.85em;\n+ margin: 6px 0;\n+ max-width: 100%;\n+ padding: 6px 10px;\n+ width: 100%;\n+}\n+body.view-ontology .ont-history-link-open {\n+ color: #23a;\n+ font-weight: 600;\n+}\n+\n /* ================================================================\n GARDEN HIERARCHY — parents ↑ / self / children ↓ (paper context).\n Lean retro version of the same system in the other themes:\ndiff --git a/server/static/theme_retro_craft.css b/server/static/theme_retro_craft.css\nindex 8f59d62e30a47760fe4ccd3f51c144d752b00539..21c7a5eb80fc7f6c9cefc32562e44a810ed42a53 100644\n--- a/server/static/theme_retro_craft.css\n+++ b/server/static/theme_retro_craft.css\n@@ -518,6 +518,22 @@ body.view-ontology-light .ont-tab.is-active {\n color: #1a1814;\n }\n \n+/* Garden score-history replay link (the replay lives at ?v=history) */\n+body.view-ontology .ont-history-link {\n+ background: #f7f3eb;\n+ border: 1px solid #c8c4bc;\n+ box-sizing: border-box;\n+ font-size: 0.85em;\n+ margin: 6px 0;\n+ max-width: 100%;\n+ padding: 6px 10px;\n+ width: 100%;\n+}\n+body.view-ontology .ont-history-link-open {\n+ color: #1a4a8c;\n+ font-weight: 600;\n+}\n+\n nav.breadcrumb.ont-sibling-nav {\n margin-top: 0;\n width: 100%;\ndiff --git a/server/tests/integration_html.rs b/server/tests/integration_html.rs\nindex 9ebf1c033c1c63a221c9dc2d3adbf575089a06e2..07b3032b567eabec2dc253b098e9b5fc4e5bfea2 100644\n--- a/server/tests/integration_html.rs\n+++ b/server/tests/integration_html.rs\n@@ -791,3 +791,203 @@ async fn test_legacy_arena_channel_page_resolve_form_targets_canonical() {\n \"/-/https://www.are.na/channel/my-chan\"\n );\n }\n+\n+#[tokio::test]\n+async fn test_scope_page_links_to_history_replay() {\n+ let (addr, _tmp, _log, _handle) = create_test_server().await;\n+ let client = reqwest::Client::new();\n+ let bearer = test_bearer();\n+ let post = |delegate: &str, text: &str| {\n+ let client = client.clone();\n+ let bearer = bearer.clone();\n+ let text = text.to_string();\n+ let delegate = delegate.to_string();\n+ async move {\n+ rpc_batch(\n+ &client,\n+ addr,\n+ Some(&bearer),\n+ serde_json::json!([{\n+ \"Post\": {\n+ \"room\": \"public\",\n+ \"thread_tag\": \"chart-test\",\n+ \"delegate\": delegate,\n+ \"text\": text,\n+ \"return_rank_diff\": false\n+ }\n+ }]),\n+ )\n+ .await\n+ }\n+ };\n+\n+ post(\n+ \"00000000-0000-0000-0000-000000000001:rig:test/model\",\n+ \"~/chart/alpha { first }\\n~/chart/beta { second }\\n~/chart/gamma { third }\\n{ alpha over beta }\\n~/chart/alpha 2:1 ~/chart/beta\\n\",\n+ )\n+ .await;\n+ post(\n+ \"00000000-0000-0000-0000-000000000002:rig:test/model\",\n+ \"{ beta over gamma }\\n~/chart/beta 2:1 ~/chart/gamma\\n\",\n+ )\n+ .await;\n+ post(\n+ \"00000000-0000-0000-0000-000000000003:rig:test/model\",\n+ \"{ alpha over gamma }\\n~/chart/alpha 3:1 ~/chart/gamma\\n\",\n+ )\n+ .await;\n+\n+ // The flat scope page links to the replay view.\n+ let body = client\n+ .get(format!(\"http://{addr}/~/chart\"))\n+ .send()\n+ .await\n+ .unwrap()\n+ .text()\n+ .await\n+ .unwrap();\n+ assert!(\n+ body.contains(\"open the replay\"),\n+ \"flat page links the replay: {}\",\n+ body.chars().take(3000).collect::()\n+ );\n+ assert!(body.contains(\"/~/chart?v=history\"));\n+\n+ // The replay page is the one-file sorter-proof React stack, bound to its data URL.\n+ let page = client\n+ .get(format!(\"http://{addr}/~/chart?v=history\"))\n+ .send()\n+ .await\n+ .unwrap();\n+ assert!(page.status().is_success(), \"{}\", page.status());\n+ let page = page.text().await.unwrap();\n+ for needle in [\n+ \"text/babel\",\n+ \"chart.js\",\n+ \"react-query\",\n+ \"SLUG_REPLAY\",\n+ \"/~/chart?v=history.json\",\n+ \"Comparison Matrix\",\n+ ] {\n+ assert!(\n+ page.contains(needle),\n+ \"replay page should contain {needle}\"\n+ );\n+ }\n+\n+ // The data payload is sorter-proof-shaped.\n+ let data: serde_json::Value = client\n+ .get(format!(\"http://{addr}/~/chart?v=history.json\"))\n+ .send()\n+ .await\n+ .unwrap()\n+ .json()\n+ .await\n+ .unwrap();\n+ let items = data[\"items\"].as_array().unwrap();\n+ assert_eq!(items.len(), 3);\n+ assert!(items.iter().any(|i| i == \"~/alpha\"));\n+ let history = data[\"history\"].as_array().unwrap();\n+ assert!(\n+ history.len() >= 2,\n+ \"three posts produce at least two vote events\"\n+ );\n+ let step0 = &history[0];\n+ assert!(step0[\"timestamp\"].is_i64());\n+ assert!(step0[\"current_rankings\"].is_array());\n+ assert!(step0[\"unsorted_items\"].is_array());\n+ assert!(\n+ step0[\"unsorted_items\"]\n+ .as_array()\n+ .unwrap()\n+ .iter()\n+ .any(|i| i == \"~/gamma\"),\n+ \"gamma waits unsorted until its first vote\"\n+ );\n+ assert!(step0[\"comparison\"][\"explanation\"].is_string());\n+ // alpha 2:1 beta → alpha's row shows a 66.7% win share over beta.\n+ let matrix = data[\"final_matrix\"].as_array().unwrap();\n+ assert_eq!(matrix.len(), 3);\n+ let w = matrix[0][1][\"weight\"].as_f64().unwrap();\n+ assert!((w - 66.7).abs() < 0.05, \"alpha row vs beta: {w}\");\n+ assert!(matrix[0][1][\"details\"][\"explanation\"]\n+ .as_str()\n+ .unwrap()\n+ .contains(\"REASONING:\"));\n+ assert!(data[\"criteria\"].is_string());\n+}\n+\n+#[tokio::test]\n+async fn test_scope_page_without_history_shows_empty_replay_state() {\n+ let (addr, _tmp, _log, _handle) = create_test_server().await;\n+ let client = reqwest::Client::new();\n+ let bearer = test_bearer();\n+ rpc_batch(\n+ &client,\n+ addr,\n+ Some(&bearer),\n+ serde_json::json!([{\n+ \"Post\": {\n+ \"room\": \"public\",\n+ \"thread_tag\": \"chartless-test\",\n+ \"delegate\": \"00000000-0000-0000-0000-000000000009:rig:test/model\",\n+ \"text\": \"~/solo/lonely { no votes yet }\\n\",\n+ \"return_rank_diff\": false\n+ }\n+ }]),\n+ )\n+ .await;\n+\n+ // One unranked member: the bar stays visible as an empty state, no replay link.\n+ let body = client\n+ .get(format!(\"http://{addr}/~/solo\"))\n+ .send()\n+ .await\n+ .unwrap()\n+ .text()\n+ .await\n+ .unwrap();\n+ assert!(\n+ body.contains(\"ont-history-empty\"),\n+ \"scope with members but no vote history should render the empty state\"\n+ );\n+ assert!(\n+ body.contains(\"score history draws itself\"),\n+ \"empty state should say what it waits for\"\n+ );\n+ assert!(\n+ !body.contains(\"open the replay\"),\n+ \"no replay link before history suffices\"\n+ );\n+\n+ // Its replay JSON is well-formed but event-free.\n+ let data: serde_json::Value = client\n+ .get(format!(\"http://{addr}/~/solo?v=history.json\"))\n+ .send()\n+ .await\n+ .unwrap()\n+ .json()\n+ .await\n+ .unwrap();\n+ assert_eq!(data[\"history\"].as_array().unwrap().len(), 0);\n+\n+ // A childless leaf: no bar, and its data view 404s.\n+ let leaf_body = client\n+ .get(format!(\"http://{addr}/~/lonely\"))\n+ .send()\n+ .await\n+ .unwrap()\n+ .text()\n+ .await\n+ .unwrap();\n+ assert!(\n+ !leaf_body.contains(\"ont-history-link\"),\n+ \"childless leaf page should not render the replay bar\"\n+ );\n+ let missing = client\n+ .get(format!(\"http://{addr}/~/lonely?v=history.json\"))\n+ .send()\n+ .await\n+ .unwrap();\n+ assert_eq!(missing.status(), reqwest::StatusCode::NOT_FOUND);\n+}\n","role":"user"}],"model":"openai/gpt-chat-latest"}