diff --git a/agents.md b/agents.md index 188a63c9383d84b6f2ed188d7bbf40f31afe2794..4f42d4bd48d8aa0728ea692c2420f2af5b6e81d9 100644 --- a/agents.md +++ b/agents.md @@ -76,6 +76,8 @@ Strict **CSP** that blocks `eval` would break the current app. Other projects ma - **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`). +- **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. + - **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. - **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. diff --git a/server/src/html/garden/mod.rs b/server/src/html/garden/mod.rs index 3dd3b7730834f26bce1caf156ff74a4e35cffbf6..49408de6adcfc2aefc9337b41d2eecb5d75e7d83 100644 --- a/server/src/html/garden/mod.rs +++ b/server/src/html/garden/mod.rs @@ -8,6 +8,7 @@ mod item; mod item_page; mod pin; mod render; +mod replay; mod routes; mod vote; diff --git a/server/src/html/garden/render.rs b/server/src/html/garden/render.rs index 2260efcac3a5efc6b971b586e449300ecb5c7a4d..83e46cf83da440fa1816bd0736a6db846eb7150c 100644 --- a/server/src/html/garden/render.rs +++ b/server/src/html/garden/render.rs @@ -30,6 +30,10 @@ use super::{ build_item_page_view_model, fragment_slug, item_relations_markup, AspectRankingView, }, pin::{child_row_pin_or_vote, ont_pin_vote_controls, pinned_item_from_jar}, + replay::{ + replay_history_json_response, replay_mode_from_uri, replay_page_response, + score_history_link_panel, ReplayMode, + }, vote::vote_pool_href, }; @@ -132,6 +136,15 @@ pub(super) async fn render_scope_view( let child_depth = child_depth_from_uri(&uri); let model = build_item_page_view_model(&reduced, &scope, browse.item(), child_depth); let scope_content = content_for_garden_view(&reduced, &scope); + // The replay is a query-param view of the scope page itself: `?v=history` + // serves the one-file React app, `?v=history.json` its data payload. + match replay_mode_from_uri(&uri) { + Some(ReplayMode::Page) => return replay_page_response(&nav, &model.item), + Some(ReplayMode::Data) => { + return replay_history_json_response(scope_content, &model.child_rankings, &model.item); + } + None => {} + } let thread_href = |tag: &str| nav.thread_url(tag); let external_empty_body = browse.is_external() && model.body.is_none(); let cli_path_arg = item_display_path(&model.item); @@ -329,6 +342,19 @@ pub(super) async fn render_scope_view( @if model.child_rankings.component_rankings.is_empty() { p class="muted" { "no voted pairs yet in this scope" } } + @if let Some(panel) = score_history_link_panel( + scope_content, + &model.child_rankings, + &nav, + &model.item, + if total_children >= 2 { + Some(vote_pool_href(&nav, &model.item)) + } else { + None + }, + ) { + (panel) + } (ont_ranking_lists_markup( &model.child_rankings, &nav, diff --git a/server/src/html/garden/replay.rs b/server/src/html/garden/replay.rs new file mode 100644 index 0000000000000000000000000000000000000000..826cee280f381506805122c01af1aa648bc193f4 --- /dev/null +++ b/server/src/html/garden/replay.rs @@ -0,0 +1,956 @@ +//! Score-history replay: the sorter-proof "Ranking Replay 2" experience — +//! one-HTML-file React app (CDN React 18 + babel-standalone + Chart.js + +//! React Query, inline JSX) served as a query-param view of any scope page. +//! +//! - `GET /~/?v=history` → the replay app (its own full page) +//! - `GET /~/?v=history.json` → the sorter-proof-shaped data 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 — never scores mixed +//! from different solves the way per-item rank-history carry-forward would +//! mix them. Comparisons and matrix cells quote vote reasonings from +//! `item_votes`. +//! +//! The flat scope page links here via [`score_history_link_panel`], which is +//! always visible on scopes with members (empty state until history suffices). + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use axum::http::Uri; +use axum::response::{Html, IntoResponse}; +use maud::{html, Markup}; +use serde::Serialize; + +use crate::html::ThreadNav; +use crate::path_types::ItemId; +use crate::reducer::{ContentState, VoteData}; +use crate::scope_rank::ChildrenRankings; + +use super::item::{item_display_path, item_href}; + +/// Most vote events replayed (recent window when history is longer). +const MAX_EVENTS: usize = 240; +/// Most members in the replay (chart datasets and matrix rows alike). +const MAX_MEMBERS: usize = 64; + +/// Which replay response a `?v=` query selects. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum ReplayMode { + /// `?v=history` — the app page. + Page, + /// `?v=history.json` — the data payload the app polls. + Data, +} + +pub(super) fn replay_mode_from_uri(uri: &Uri) -> Option { + uri.query() + .into_iter() + .flat_map(|q| q.split('&')) + .find_map(|pair| pair.strip_prefix("v=")) + .and_then(|v| match v { + "history" => Some(ReplayMode::Page), + "history.json" => Some(ReplayMode::Data), + _ => None, + }) +} + +#[derive(Debug, Clone, Serialize)] +pub(super) struct ReplayRanked { + item: String, + score: f64, +} + +#[derive(Debug, Clone, Serialize)] +pub(super) struct ReplayComparison { + left: String, + right: String, + score: f64, + explanation: String, +} + +#[derive(Debug, Clone, Serialize)] +pub(super) struct ReplayStep { + timestamp: i64, + comparison: ReplayComparison, + current_rankings: Vec, + unsorted_items: Vec, +} + +#[derive(Debug, Clone, Serialize)] +pub(super) struct MatrixDetails { + score: f64, + explanation: String, +} + +#[derive(Debug, Clone, Serialize, Default)] +pub(super) struct MatrixCell { + #[serde(skip_serializing_if = "is_zero_weight")] + weight: f64, + #[serde(skip_serializing_if = "Option::is_none")] + details: Option, +} + +fn is_zero_weight(w: &f64) -> bool { + *w == 0.0 +} + +#[derive(Debug, Clone, Serialize)] +pub(super) struct ReplayData { + criteria: String, + items: Vec, + history: Vec, + final_matrix: Vec>, + /// Members omitted from the replay (over [`MAX_MEMBERS`]). + truncated_members: usize, + /// False when there is not enough history to chart (panel shows the + /// empty state instead of the replay link). + #[serde(skip_serializing)] + sufficient: bool, +} + +/// `Forward: a / ---- / b / REASONING: body` — the sorter-proof explanation card. +fn format_vote_explanation(content_label: &impl Fn(&ItemId) -> String, v: &VoteData) -> String { + format!( + "Forward: {}\n---------\n{}\n\nREASONING:\n{}", + content_label(&v.a), + content_label(&v.b), + if v.body.trim().is_empty() { + "(no reasoning recorded)" + } else { + v.body.trim() + } + ) +} + +/// Signed log-ratio scaled like the prototype's comparison scores +/// (3:1 → +11.0, 3:2 → +4.1, 1:2 → −6.9, 1:1 → 0.0). +fn vote_score(ratio_left: i32, ratio_right: i32) -> f64 { + let l = (ratio_left.max(1)) as f64; + let r = (ratio_right.max(1)) as f64; + let v = (l / r).ln() * 10.0; + (v * 10.0).round() / 10.0 +} + +/// Build the replay payload for one scope, or `None` when the scope has no +/// members at all (childless leaf pages get neither panel nor replay). +pub(super) fn build_replay( + content: &ContentState, + rankings: &ChildrenRankings, + scope_item: &str, +) -> Option { + // Members in display order: ranked across components, then unranked. + let mut members: Vec = rankings + .component_rankings + .iter() + .flat_map(|c| c.ranked.iter().map(|r| r.item.ontology_leaf())) + .collect(); + members.extend(rankings.unranked_items.iter().map(|i| i.ontology_leaf())); + let mut seen = HashSet::new(); + members.retain(|m| seen.insert(m.clone())); + if members.is_empty() { + return None; + } + + let total_members = members.len(); + let truncated_members = total_members.saturating_sub(MAX_MEMBERS); + members.truncate(MAX_MEMBERS); + let member_set: HashSet<&ItemId> = members.iter().collect(); + let label_of = |item: &ItemId| item_display_path(item.as_str()); + let leaf = ItemId::parse(scope_item) + .map(|id| id.ontology_leaf()) + .unwrap_or_else(|| ItemId::opaque(scope_item.to_string())); + let criteria = content + .item_bodies + .get(&leaf) + .map(|b| b.trim().to_string()) + .filter(|b| !b.is_empty()) + .unwrap_or_else(|| format!("members of {}", item_display_path(scope_item))); + + // Member↔member canonical votes, each counted once: a vote is recorded in + // both endpoints' `item_votes` lists, so we take it only from the smaller + // endpoint's list (multiple votes on the same pair stay distinct events). + let mut votes_by_ts: BTreeMap> = BTreeMap::new(); + for m in &members { + if let Some(vs) = content.item_votes.get(m) { + for v in vs { + let lo = if v.a <= v.b { &v.a } else { &v.b }; + if lo == m && member_set.contains(&v.a) && member_set.contains(&v.b) { + votes_by_ts.entry(v.ts).or_default().push(v); + } + } + } + } + let all_steps: Vec = votes_by_ts.keys().copied().collect(); + let steps: &[i64] = if all_steps.len() > MAX_EVENTS { + &all_steps[all_steps.len() - MAX_EVENTS..] + } else { + &all_steps + }; + let sufficient = members.len() >= 2 && steps.len() >= 2; + + // Replay the scope's own vote graph through the same kernel the reducer + // uses (`GroupState::apply_vote` → `rank_partition`), solving after every + // event so each snapshot is one honest solve — never scores mixed from + // different solves the way per-item rank-history carry-forward would be. + let mut group = crate::reducer::GroupState::new(); + let mut history: Vec = Vec::with_capacity(steps.len()); + for &ts in steps { + if let Some(step_votes) = votes_by_ts.get(&ts) { + for v in step_votes { + group.apply_vote((*v).clone()); + } + } + let (mut comps, _) = crate::ranking::connected_components_from_voted_pairs( + group.idx_to_item.len(), + group.voted_pairs.iter().copied(), + ); + comps.sort_by_key(|b| std::cmp::Reverse(b.len())); + let mut scores: HashMap = HashMap::new(); + for ranked in crate::ranking::rank_partition(&group, &comps, 10000, 1e-8) { + for r in ranked { + scores.insert(r.item, r.score); + } + } + let mut current_rankings = Vec::new(); + let mut unsorted_items = Vec::new(); + for m in &members { + match scores.get(m) { + Some(&score) => current_rankings.push(ReplayRanked { + item: label_of(m), + score, + }), + None => unsorted_items.push(label_of(m)), + } + } + let step_votes = votes_by_ts.get(&ts).cloned().unwrap_or_default(); + let comparison = match step_votes.first() { + Some(v) => ReplayComparison { + left: label_of(&v.a), + right: label_of(&v.b), + score: vote_score(v.ratio_left, v.ratio_right), + explanation: step_votes + .iter() + .map(|v| format_vote_explanation(&label_of, v)) + .collect::>() + .join("\n\n---\n\n"), + }, + None => ReplayComparison { + left: String::new(), + right: String::new(), + score: 0.0, + explanation: "no votes on this scope's members in this event".to_string(), + }, + }; + history.push(ReplayStep { + timestamp: ts, + comparison, + current_rankings, + unsorted_items, + }); + } + + // Pairwise matrix over members: win share + quoted reasoning per edge. + let n = members.len(); + let mut final_matrix: Vec> = vec![vec![MatrixCell::default(); n]; n]; + for (i, mi) in members.iter().enumerate() { + let Some(votes) = content.item_votes.get(mi) else { + continue; + }; + for (j, mj) in members.iter().enumerate() { + if i == j { + continue; + } + let edge: Vec<&VoteData> = votes + .iter() + .filter(|v| { + (&v.a == mi && &v.b == mj) || (&v.a == mj && &v.b == mi) + }) + .collect(); + if edge.is_empty() { + continue; + } + let shares: Vec = edge + .iter() + .map(|v| { + let l = v.ratio_left.max(1) as f64; + let r = v.ratio_right.max(1) as f64; + if &v.a == mi { + l / (l + r) + } else { + r / (l + r) + } + }) + .collect(); + let mean = shares.iter().sum::() / shares.len() as f64; + let clamped = mean.clamp(0.01, 0.99); + final_matrix[i][j] = MatrixCell { + weight: (mean * 1000.0).round() / 10.0, + details: Some(MatrixDetails { + score: (((clamped / (1.0 - clamped)).ln() * 10.0) * 10.0).round() / 10.0, + explanation: edge + .iter() + .map(|v| format_vote_explanation(&label_of, v)) + .collect::>() + .join("\n\n---\n\n"), + }), + }; + } + } + + Some(ReplayData { + criteria, + items: members.iter().map(label_of).collect(), + history, + final_matrix, + truncated_members, + sufficient, + }) +} + +/// The `?v=history.json` payload. +pub(super) fn replay_history_json_response( + content: &ContentState, + rankings: &ChildrenRankings, + scope_item: &str, +) -> axum::response::Response { + match build_replay(content, rankings, scope_item) { + Some(data) => axum::Json(serde_json::to_value(data).expect("replay serializes")) + .into_response(), + None => ( + axum::http::StatusCode::NOT_FOUND, + "no members in this scope", + ) + .into_response(), + } +} + +/// HTML-escape for the page ``. +fn esc(s: &str) -> String { + s.replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) +} + +/// The `?v=history` page: one HTML file, the sorter-proof stack verbatim. +pub(super) fn replay_page_response(nav: &ThreadNav, scope_item: &str) -> axum::response::Response { + let display = item_display_path(scope_item); + let back_href = item_href(scope_item, nav); + let config = serde_json::json!({ + "dataUrl": format!("{back_href}?v=history.json"), + "backHref": back_href, + "backLabel": display, + }); + // serde_json does not escape '<' — keep the config safe inside <script>. + let config = config.to_string().replace("</", "<\\/"); + let page = REPLAY_HTML + .replace("__SLUG_TITLE__", &esc(&format!("{display} · score history"))) + .replace("__SLUG_CONFIG__", &config); + Html(page).into_response() +} + +/// The flat-page link bar: always visible on scopes with members. Links to +/// `?v=history` when history suffices; otherwise an empty state naming what +/// it waits for (plus a vote link when there are at least two children). +pub(super) fn score_history_link_panel( + content: &ContentState, + rankings: &ChildrenRankings, + nav: &ThreadNav, + scope_item: &str, + vote_href: Option<String>, +) -> Option<Markup> { + let data = build_replay(content, rankings, scope_item)?; + let replay_href = format!("{}?v=history", item_href(scope_item, nav)); + Some(if data.sufficient { + html! { + div class="ont-history-link" { + span class="ont-history-link-meta muted" { + "score history · " + (data.items.len()) + " members · " + (data.history.len()) + " vote events" + } + " " + a class="ont-history-link-open" href=(replay_href) { "open the replay →" } + } + } + } else { + html! { + div class="ont-history-link ont-history-empty" { + span class="muted" { + "score history draws itself once two or more members carry votes" + } + @if let Some(href) = &vote_href { + " — " + a class="ont-vote-children-btn" href=(href.as_str()) { "vote on children" } + } + } + } + }) +} + +/// The replay app. Stack, styles, chart config, controls, matrix, and dialog +/// are the sorter-proof "Ranking Replay 2" file adapted only to bind to a +/// fixed data URL (`window.SLUG_REPLAY`) instead of the file picker, plus a +/// back link and an empty-history state. +const REPLAY_HTML: &str = r##"<!DOCTYPE html> +<html> +<head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1"> + <title>__SLUG_TITLE__ + + + + + + + + + + + + + + + +
+ + + + + +"##; + +#[cfg(test)] +mod tests { + use super::*; + use crate::ranking::RankedItem; + use crate::scope_rank::ScopedComponent; + + fn vote(ts: i64, a: &ItemId, b: &ItemId, l: i32, r: i32, body: &str) -> VoteData { + VoteData { + ts, + a: a.clone(), + b: b.clone(), + ratio_left: l, + ratio_right: r, + body: body.to_string(), + principal: "dev".to_string(), + delegate: None, + thread_tag: "t".to_string(), + } + } + + fn leaf(name: &str) -> ItemId { + ItemId::parse(name).expect("leaf parses") + } + + fn rankings_for(names: &[&str], unranked: &[&str]) -> ChildrenRankings { + ChildrenRankings { + component_rankings: vec![ScopedComponent { + pairs: names.len().saturating_sub(1), + ranked: names + .iter() + .enumerate() + .map(|(i, n)| RankedItem { + item: leaf(n), + score: 1.0 / (i + 1) as f64, + }) + .collect(), + }], + unranked_items: unranked.iter().map(|n| leaf(n)).collect(), + } + } + + /// Record each vote in both endpoints' lists, exactly like the reducer. + fn content_with_votes(votes: Vec) -> ContentState { + let mut content = ContentState::default(); + for v in votes { + content.item_votes.entry(v.a.clone()).or_default().push_front(v.clone()); + content.item_votes.entry(v.b.clone()).or_default().push_front(v); + } + content + } + + fn score_of(step: &ReplayStep, item: &str) -> Option { + step.current_rankings + .iter() + .find(|r| r.item == item) + .map(|r| r.score) + } + + #[test] + fn childless_scope_builds_nothing() { + let content = ContentState::default(); + let rankings = rankings_for(&[], &[]); + assert!(build_replay(&content, &rankings, "~scope").is_none()); + } + + #[test] + fn single_event_is_not_yet_a_replay() { + let content = content_with_votes(vec![vote(1, &leaf("~a"), &leaf("~b"), 2, 1, "a over b")]); + let rankings = rankings_for(&["~a", "~b"], &[]); + let data = build_replay(&content, &rankings, "~scope").expect("builds"); + assert!(!data.sufficient, "one vote event is not a replay"); + assert_eq!(data.history.len(), 1); + } + + #[test] + fn snapshots_are_fresh_solves_and_laggards_stay_unsorted() { + let content = content_with_votes(vec![ + vote(1, &leaf("~a"), &leaf("~b"), 2, 1, "a over b"), + vote(2, &leaf("~b"), &leaf("~c"), 2, 1, "b over c"), + vote(3, &leaf("~a"), &leaf("~c"), 3, 1, "a over c"), + ]); + let rankings = rankings_for(&["~a", "~b", "~c"], &[]); + let data = build_replay(&content, &rankings, "~scope").expect("builds"); + assert!(data.sufficient); + assert_eq!(data.history.len(), 3); + + // Step 0: only the first pair is connected; the third item waits unsorted. + let step0 = &data.history[0]; + assert_eq!(step0.unsorted_items, vec!["~/c".to_string()]); + let (a0, b0) = (score_of(step0, "~/a").unwrap(), score_of(step0, "~/b").unwrap()); + assert!(a0 > b0, "2:1 winner leads the fresh solve"); + assert!((a0 + b0 - 1.0).abs() < 0.05, "component mass sums to one"); + assert!((data.history[0].comparison.score - 6.9).abs() < 0.05); + + // Final step: the whole chain solved, order follows the vote directions. + let last = data.history.last().unwrap(); + assert!(last.unsorted_items.is_empty()); + let (a, b, c) = ( + score_of(last, "~/a").unwrap(), + score_of(last, "~/b").unwrap(), + score_of(last, "~/c").unwrap(), + ); + assert!(a > b && b > c, "a > b > c after the full replay: {a} {b} {c}"); + } + + #[test] + fn matrix_weight_and_reasoning_and_dedupe() { + // Two votes on the same pair must both count (the kernel adds them), + // while the mirror copy in the opponent's list must not double them. + let content = content_with_votes(vec![ + vote(1, &leaf("~a"), &leaf("~b"), 3, 1, "a clearly outranks b"), + vote(2, &leaf("~a"), &leaf("~b"), 2, 1, "a still outranks b"), + ]); + let rankings = rankings_for(&["~a", "~b"], &[]); + let data = build_replay(&content, &rankings, "~scope").expect("builds"); + assert_eq!(data.history.len(), 2, "two events, no dedupe collapse"); + + // mean(75%, 66.7%) win share for a over b. + let ab = &data.final_matrix[0][1]; + assert!((ab.weight - 70.8).abs() < 0.1, "weight: {}", ab.weight); + let details = ab.details.as_ref().expect("details"); + assert_eq!( + details.explanation.matches("REASONING:").count(), + 2, + "both votes quoted" + ); + assert!(details.explanation.contains("a clearly outranks b")); + } + + #[test] + fn member_and_event_caps_bite() { + let mut votes = Vec::new(); + for t in 0..300 { + votes.push(vote(t, &leaf("~m00"), &leaf("~m01"), 2, 1, "again")); + } + let content = content_with_votes(votes); + let names: Vec = (0..70).map(|i| format!("~m{i:02}")).collect(); + let refs: Vec<&str> = names.iter().map(String::as_str).collect(); + let rankings = rankings_for(&refs, &[]); + let data = build_replay(&content, &rankings, "~scope").expect("builds"); + assert_eq!(data.items.len(), MAX_MEMBERS); + assert_eq!(data.truncated_members, 70 - MAX_MEMBERS); + assert_eq!(data.history.len(), MAX_EVENTS); + assert_eq!(data.final_matrix.len(), MAX_MEMBERS); + } + + #[test] + fn replay_mode_parsing() { + let page: Uri = "/~/topic?v=history".parse().unwrap(); + assert_eq!(replay_mode_from_uri(&page), Some(ReplayMode::Page)); + let data: Uri = "/~/topic?v=history.json".parse().unwrap(); + assert_eq!(replay_mode_from_uri(&data), Some(ReplayMode::Data)); + let depth: Uri = "/~/topic?depth=2".parse().unwrap(); + assert_eq!(replay_mode_from_uri(&depth), None); + let both: Uri = "/~/topic?depth=2&v=history".parse().unwrap(); + assert_eq!(replay_mode_from_uri(&both), Some(ReplayMode::Page)); + } +} diff --git a/server/static/theme_default.css b/server/static/theme_default.css index 25ebde9ecbb7469b33f7baa338609d092b45d0b7..cc6c6b0ce72184c8053b12bff5fa50e5911d1fd4 100644 --- a/server/static/theme_default.css +++ b/server/static/theme_default.css @@ -1905,6 +1905,22 @@ body.view-ontology-light .rank-history-vote { margin-top: 6px; } +/* Garden score-history replay link (the replay lives at ?v=history) */ +body.view-ontology .ont-history-link { + background: var(--g2); + border: 1px solid var(--lo); + box-sizing: border-box; + font-size: 0.85em; + margin: 6px 0; + max-width: 100%; + padding: 6px 10px; + width: 100%; +} +body.view-ontology .ont-history-link-open { + color: var(--link); + font-weight: 600; +} + /* GitHub resolver import cards (rich bodies on -/ garden + vote compare) */ article.import-card { border: 1px solid var(--lo); diff --git a/server/static/theme_retro.css b/server/static/theme_retro.css index 87e298c53d1603dc99c6e3a519aa880a849c63e4..d1ecf3ecbc2e42d9f1d2d5718423782f68c8ccbe 100644 --- a/server/static/theme_retro.css +++ b/server/static/theme_retro.css @@ -539,6 +539,22 @@ body.view-ontology .vote-open-links { white-space: nowrap; } +/* Garden score-history replay link (the replay lives at ?v=history) */ +body.view-ontology .ont-history-link { + background: #faf8f3; + border: 1px solid #ccc; + box-sizing: border-box; + font-size: 0.85em; + margin: 6px 0; + max-width: 100%; + padding: 6px 10px; + width: 100%; +} +body.view-ontology .ont-history-link-open { + color: #23a; + font-weight: 600; +} + /* ================================================================ GARDEN HIERARCHY — parents ↑ / self / children ↓ (paper context). Lean retro version of the same system in the other themes: diff --git a/server/static/theme_retro_craft.css b/server/static/theme_retro_craft.css index 8f59d62e30a47760fe4ccd3f51c144d752b00539..21c7a5eb80fc7f6c9cefc32562e44a810ed42a53 100644 --- a/server/static/theme_retro_craft.css +++ b/server/static/theme_retro_craft.css @@ -518,6 +518,22 @@ body.view-ontology-light .ont-tab.is-active { color: #1a1814; } +/* Garden score-history replay link (the replay lives at ?v=history) */ +body.view-ontology .ont-history-link { + background: #f7f3eb; + border: 1px solid #c8c4bc; + box-sizing: border-box; + font-size: 0.85em; + margin: 6px 0; + max-width: 100%; + padding: 6px 10px; + width: 100%; +} +body.view-ontology .ont-history-link-open { + color: #1a4a8c; + font-weight: 600; +} + nav.breadcrumb.ont-sibling-nav { margin-top: 0; width: 100%; diff --git a/server/tests/integration_html.rs b/server/tests/integration_html.rs index 9ebf1c033c1c63a221c9dc2d3adbf575089a06e2..07b3032b567eabec2dc253b098e9b5fc4e5bfea2 100644 --- a/server/tests/integration_html.rs +++ b/server/tests/integration_html.rs @@ -791,3 +791,203 @@ async fn test_legacy_arena_channel_page_resolve_form_targets_canonical() { "/-/https://www.are.na/channel/my-chan" ); } + +#[tokio::test] +async fn test_scope_page_links_to_history_replay() { + let (addr, _tmp, _log, _handle) = create_test_server().await; + let client = reqwest::Client::new(); + let bearer = test_bearer(); + let post = |delegate: &str, text: &str| { + let client = client.clone(); + let bearer = bearer.clone(); + let text = text.to_string(); + let delegate = delegate.to_string(); + async move { + rpc_batch( + &client, + addr, + Some(&bearer), + serde_json::json!([{ + "Post": { + "room": "public", + "thread_tag": "chart-test", + "delegate": delegate, + "text": text, + "return_rank_diff": false + } + }]), + ) + .await + } + }; + + post( + "00000000-0000-0000-0000-000000000001:rig:test/model", + "~/chart/alpha { first }\n~/chart/beta { second }\n~/chart/gamma { third }\n{ alpha over beta }\n~/chart/alpha 2:1 ~/chart/beta\n", + ) + .await; + post( + "00000000-0000-0000-0000-000000000002:rig:test/model", + "{ beta over gamma }\n~/chart/beta 2:1 ~/chart/gamma\n", + ) + .await; + post( + "00000000-0000-0000-0000-000000000003:rig:test/model", + "{ alpha over gamma }\n~/chart/alpha 3:1 ~/chart/gamma\n", + ) + .await; + + // The flat scope page links to the replay view. + let body = client + .get(format!("http://{addr}/~/chart")) + .send() + .await + .unwrap() + .text() + .await + .unwrap(); + assert!( + body.contains("open the replay"), + "flat page links the replay: {}", + body.chars().take(3000).collect::() + ); + assert!(body.contains("/~/chart?v=history")); + + // The replay page is the one-file sorter-proof React stack, bound to its data URL. + let page = client + .get(format!("http://{addr}/~/chart?v=history")) + .send() + .await + .unwrap(); + assert!(page.status().is_success(), "{}", page.status()); + let page = page.text().await.unwrap(); + for needle in [ + "text/babel", + "chart.js", + "react-query", + "SLUG_REPLAY", + "/~/chart?v=history.json", + "Comparison Matrix", + ] { + assert!( + page.contains(needle), + "replay page should contain {needle}" + ); + } + + // The data payload is sorter-proof-shaped. + let data: serde_json::Value = client + .get(format!("http://{addr}/~/chart?v=history.json")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + let items = data["items"].as_array().unwrap(); + assert_eq!(items.len(), 3); + assert!(items.iter().any(|i| i == "~/alpha")); + let history = data["history"].as_array().unwrap(); + assert!( + history.len() >= 2, + "three posts produce at least two vote events" + ); + let step0 = &history[0]; + assert!(step0["timestamp"].is_i64()); + assert!(step0["current_rankings"].is_array()); + assert!(step0["unsorted_items"].is_array()); + assert!( + step0["unsorted_items"] + .as_array() + .unwrap() + .iter() + .any(|i| i == "~/gamma"), + "gamma waits unsorted until its first vote" + ); + assert!(step0["comparison"]["explanation"].is_string()); + // alpha 2:1 beta → alpha's row shows a 66.7% win share over beta. + let matrix = data["final_matrix"].as_array().unwrap(); + assert_eq!(matrix.len(), 3); + let w = matrix[0][1]["weight"].as_f64().unwrap(); + assert!((w - 66.7).abs() < 0.05, "alpha row vs beta: {w}"); + assert!(matrix[0][1]["details"]["explanation"] + .as_str() + .unwrap() + .contains("REASONING:")); + assert!(data["criteria"].is_string()); +} + +#[tokio::test] +async fn test_scope_page_without_history_shows_empty_replay_state() { + let (addr, _tmp, _log, _handle) = create_test_server().await; + let client = reqwest::Client::new(); + let bearer = test_bearer(); + rpc_batch( + &client, + addr, + Some(&bearer), + serde_json::json!([{ + "Post": { + "room": "public", + "thread_tag": "chartless-test", + "delegate": "00000000-0000-0000-0000-000000000009:rig:test/model", + "text": "~/solo/lonely { no votes yet }\n", + "return_rank_diff": false + } + }]), + ) + .await; + + // One unranked member: the bar stays visible as an empty state, no replay link. + let body = client + .get(format!("http://{addr}/~/solo")) + .send() + .await + .unwrap() + .text() + .await + .unwrap(); + assert!( + body.contains("ont-history-empty"), + "scope with members but no vote history should render the empty state" + ); + assert!( + body.contains("score history draws itself"), + "empty state should say what it waits for" + ); + assert!( + !body.contains("open the replay"), + "no replay link before history suffices" + ); + + // Its replay JSON is well-formed but event-free. + let data: serde_json::Value = client + .get(format!("http://{addr}/~/solo?v=history.json")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(data["history"].as_array().unwrap().len(), 0); + + // A childless leaf: no bar, and its data view 404s. + let leaf_body = client + .get(format!("http://{addr}/~/lonely")) + .send() + .await + .unwrap() + .text() + .await + .unwrap(); + assert!( + !leaf_body.contains("ont-history-link"), + "childless leaf page should not render the replay bar" + ); + let missing = client + .get(format!("http://{addr}/~/lonely?v=history.json")) + .send() + .await + .unwrap(); + assert_eq!(missing.status(), reqwest::StatusCode::NOT_FOUND); +}