diff --git a/agents.md b/agents.md index 4f42d4bd48d8aa0728ea692c2420f2af5b6e81d9..c12c7dd0bb81dbf97f2ce5b9427b1af5ca98eafc 100644 --- a/agents.md +++ b/agents.md @@ -78,6 +78,8 @@ Strict **CSP** that blocks `eval` would break the current app. Other projects ma - **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. +- **`?by=` garden fork:** Both the flat scope page and the replay accept a voter filter (`voter_from_uri` in `server/src/html/garden/replay.rs`; matches the vote's human principal or full delegate string). The flat page re-solves its ranked children from a graph holding only that voter's canonical votes (`filtered_group_by_voter` + `build_children_rankings_in_group` in `server/src/scope_rank.rs`) and shows a "filtered: only votes by X · show all" notice; the replay payload carries the filter through its votes and exposes it as the `voter` field, and the link bar preserves it into the `?v=history&by=` URL. Aspect sections and the rest of the page stay canonical. + - **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/render.rs b/server/src/html/garden/render.rs index 83e46cf83da440fa1816bd0736a6db846eb7150c..5cff1492fa19ae1e8d53efc7b64036e2c45e854c 100644 --- a/server/src/html/garden/render.rs +++ b/server/src/html/garden/render.rs @@ -32,7 +32,7 @@ use super::{ 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, + score_history_link_panel, voter_from_uri, ReplayMode, }, vote::vote_pool_href, }; @@ -134,17 +134,35 @@ pub(super) async fn render_scope_view( let pin_ref = pinned_item_from_jar(&jar); let reduced = state.reduced.read().await; let child_depth = child_depth_from_uri(&uri); - let model = build_item_page_view_model(&reduced, &scope, browse.item(), child_depth); + let mut model = build_item_page_view_model(&reduced, &scope, browse.item(), child_depth); let scope_content = content_for_garden_view(&reduced, &scope); + let voter = voter_from_uri(&uri); // 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::Page) => { + return replay_page_response(&nav, &model.item, voter.as_deref()); + } Some(ReplayMode::Data) => { - return replay_history_json_response(scope_content, &model.child_rankings, &model.item); + return replay_history_json_response( + scope_content, + &model.child_rankings, + &model.item, + voter.as_deref(), + ); } None => {} } + // `?by=` forks the flat page too: the ranked children table re-solves from + // a graph holding only that voter's canonical votes. + if let Some(v) = &voter { + let filtered = crate::scope_rank::filtered_group_by_voter(scope_content, v); + let parent = ItemId::parse(&model.item) + .map(|id| id.ontology_leaf()) + .unwrap_or_else(|| ItemId::opaque(model.item.clone())); + model.child_rankings = + crate::scope_rank::build_children_rankings_in_group(scope_content, &parent, &filtered); + } 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); @@ -339,6 +357,14 @@ pub(super) async fn render_scope_view( } } } + @if let Some(v) = &voter { + div class="ont-voter-filter" { + "filtered: only votes by " + strong { (v) } + " · " + a href=(item_href(&model.item, &nav)) { "show all" } + } + } @if model.child_rankings.component_rankings.is_empty() { p class="muted" { "no voted pairs yet in this scope" } } @@ -352,6 +378,7 @@ pub(super) async fn render_scope_view( } else { None }, + voter.as_deref(), ) { (panel) } diff --git a/server/src/html/garden/replay.rs b/server/src/html/garden/replay.rs index 826cee280f381506805122c01af1aa648bc193f4..8594c69318fc5bd3676c5681e582890662c16db3 100644 --- a/server/src/html/garden/replay.rs +++ b/server/src/html/garden/replay.rs @@ -55,6 +55,17 @@ pub(super) fn replay_mode_from_uri(uri: &Uri) -> Option { }) } +/// The `?by=` voter filter: fork the garden to one voter's canonical votes. +/// Matches the vote's human principal or its full delegate string. +pub(super) fn voter_from_uri(uri: &Uri) -> Option { + uri.query() + .into_iter() + .flat_map(|q| q.split('&')) + .find_map(|pair| pair.strip_prefix("by=")) + .and_then(|v| urlencoding::decode(v).ok().map(|s| s.into_owned())) + .filter(|s| !s.is_empty()) +} + #[derive(Debug, Clone, Serialize)] pub(super) struct ReplayRanked { item: String, @@ -103,6 +114,9 @@ pub(super) struct ReplayData { final_matrix: Vec>, /// Members omitted from the replay (over [`MAX_MEMBERS`]). truncated_members: usize, + /// The `?by=` voter this replay is filtered to, if any. + #[serde(skip_serializing_if = "Option::is_none")] + voter: Option, /// False when there is not enough history to chart (panel shows the /// empty state instead of the replay link). #[serde(skip_serializing)] @@ -134,10 +148,12 @@ fn vote_score(ratio_left: i32, ratio_right: i32) -> f64 { /// 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). +/// `voter` (the `?by=` filter) forks the replay to one voter's votes. pub(super) fn build_replay( content: &ContentState, rankings: &ChildrenRankings, scope_item: &str, + voter: Option<&str>, ) -> Option { // Members in display order: ranked across components, then unranked. let mut members: Vec = rankings @@ -176,6 +192,11 @@ pub(super) fn build_replay( 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) { + if let Some(voter) = voter { + if v.principal != voter && v.delegate.as_deref() != Some(voter) { + continue; + } + } votes_by_ts.entry(v.ts).or_default().push(v); } } @@ -304,17 +325,19 @@ pub(super) fn build_replay( history, final_matrix, truncated_members, + voter: voter.map(str::to_string), sufficient, }) } -/// The `?v=history.json` payload. +/// The `?v=history.json` payload (`?by=` forks to one voter's votes). pub(super) fn replay_history_json_response( content: &ContentState, rankings: &ChildrenRankings, scope_item: &str, + voter: Option<&str>, ) -> axum::response::Response { - match build_replay(content, rankings, scope_item) { + match build_replay(content, rankings, scope_item, voter) { Some(data) => axum::Json(serde_json::to_value(data).expect("replay serializes")) .into_response(), None => ( @@ -334,11 +357,18 @@ fn esc(s: &str) -> String { } /// 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 { +pub(super) fn replay_page_response( + nav: &ThreadNav, + scope_item: &str, + voter: Option<&str>, +) -> axum::response::Response { let display = item_display_path(scope_item); let back_href = item_href(scope_item, nav); + let by_query = voter + .map(|v| format!("&by={}", urlencoding::encode(v))) + .unwrap_or_default(); let config = serde_json::json!({ - "dataUrl": format!("{back_href}?v=history.json"), + "dataUrl": format!("{back_href}?v=history.json{by_query}"), "backHref": back_href, "backLabel": display, }); @@ -353,15 +383,20 @@ pub(super) fn replay_page_response(nav: &ThreadNav, scope_item: &str) -> axum::r /// 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). +/// `voter` (the `?by=` filter) forks the counts and carries into the link. pub(super) fn score_history_link_panel( content: &ContentState, rankings: &ChildrenRankings, nav: &ThreadNav, scope_item: &str, vote_href: Option, + voter: Option<&str>, ) -> Option { - let data = build_replay(content, rankings, scope_item)?; - let replay_href = format!("{}?v=history", item_href(scope_item, nav)); + let data = build_replay(content, rankings, scope_item, voter)?; + let by_query = voter + .map(|v| format!("&by={}", urlencoding::encode(v))) + .unwrap_or_default(); + let replay_href = format!("{}?v=history{}", item_href(scope_item, nav), by_query); Some(if data.sufficient { html! { div class="ont-history-link" { @@ -653,6 +688,7 @@ const REPLAY_HTML: &str = r##" {topbar}
{data.criteria} + {data.voter ? ` · filtered by ${data.voter}` : ''} {data.truncated_members > 0 ? ` · top ${data.items.length} of ${data.items.length + data.truncated_members} members` : ''}
@@ -858,14 +894,14 @@ mod tests { fn childless_scope_builds_nothing() { let content = ContentState::default(); let rankings = rankings_for(&[], &[]); - assert!(build_replay(&content, &rankings, "~scope").is_none()); + assert!(build_replay(&content, &rankings, "~scope", None).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"); + let data = build_replay(&content, &rankings, "~scope", None).expect("builds"); assert!(!data.sufficient, "one vote event is not a replay"); assert_eq!(data.history.len(), 1); } @@ -878,7 +914,7 @@ mod tests { 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"); + let data = build_replay(&content, &rankings, "~scope", None).expect("builds"); assert!(data.sufficient); assert_eq!(data.history.len(), 3); @@ -910,7 +946,7 @@ mod tests { 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"); + let data = build_replay(&content, &rankings, "~scope", None).expect("builds"); assert_eq!(data.history.len(), 2, "two events, no dedupe collapse"); // mean(75%, 66.7%) win share for a over b. @@ -935,13 +971,44 @@ mod tests { 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"); + let data = build_replay(&content, &rankings, "~scope", None).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 voter_filter_forks_the_replay() { + let mut alice_vote = vote(1, &leaf("~a"), &leaf("~b"), 3, 1, "alice loves a"); + alice_vote.principal = "alice".to_string(); + let mut bob_vote = vote(2, &leaf("~b"), &leaf("~a"), 3, 1, "bob loves b"); + bob_vote.principal = "bob".to_string(); + let content = content_with_votes(vec![alice_vote, bob_vote]); + let rankings = rankings_for(&["~a", "~b"], &[]); + + let canon = build_replay(&content, &rankings, "~scope", None).expect("builds"); + assert_eq!(canon.history.len(), 2, "both votes in the canonical replay"); + assert!(canon.voter.is_none()); + + let alice = build_replay(&content, &rankings, "~scope", Some("alice")).expect("builds"); + assert_eq!(alice.voter.as_deref(), Some("alice")); + assert_eq!(alice.history.len(), 1, "only alice's vote survives"); + let a = score_of(&alice.history[0], "~/a").unwrap(); + let b = score_of(&alice.history[0], "~/b").unwrap(); + assert!(a > b, "alice's fork crowns a"); + + let bob = build_replay(&content, &rankings, "~scope", Some("bob")).expect("builds"); + let a = score_of(&bob.history[0], "~/a").unwrap(); + let b = score_of(&bob.history[0], "~/b").unwrap(); + assert!(b > a, "bob's fork crowns b"); + + let nobody = + build_replay(&content, &rankings, "~scope", Some("mallory")).expect("builds"); + assert!(nobody.history.is_empty(), "unknown voter gets an empty replay"); + assert!(!nobody.sufficient); + } + #[test] fn replay_mode_parsing() { let page: Uri = "/~/topic?v=history".parse().unwrap(); diff --git a/server/src/scope_rank.rs b/server/src/scope_rank.rs index 60cf81f133ed9fee09ab6ef357773aec926e1f9d..86471902409b4a065031debf0f05300ae07bffe8 100644 --- a/server/src/scope_rank.rs +++ b/server/src/scope_rank.rs @@ -210,6 +210,29 @@ pub fn build_children_rankings_in_group( build_rankings_for_group_and_items(group, &items) } +/// Rebuild a vote graph containing only one voter's canonical votes. +/// +/// `voter` matches the vote's human principal or its full delegate string. +/// Each vote is recorded in both endpoints' `item_votes` lists; taking it from +/// the smaller endpoint's list counts it once while keeping repeated +/// same-pair votes (they add — the kernel accumulates edges, so application +/// order does not matter for the final graph). +pub fn filtered_group_by_voter(content: &ContentState, voter: &str) -> GroupState { + let mut group = GroupState::new(); + for (item, votes) in &content.item_votes { + for v in votes { + let lo = if v.a <= v.b { &v.a } else { &v.b }; + if lo != item { + continue; + } + if v.principal == voter || v.delegate.as_deref() == Some(voter) { + group.apply_vote(v.clone()); + } + } + } + group +} + /// Host-only `https://…` roots for the external garden index (`/-/`). /// /// Includes every `https://host` ancestor of any [`ItemId::Web`] item that appears in diff --git a/server/static/theme_default.css b/server/static/theme_default.css index cc6c6b0ce72184c8053b12bff5fa50e5911d1fd4..f1d636861ef9addfe6d54f00a9983b3191f16fcc 100644 --- a/server/static/theme_default.css +++ b/server/static/theme_default.css @@ -1920,6 +1920,16 @@ body.view-ontology .ont-history-link-open { color: var(--link); font-weight: 600; } +body.view-ontology .ont-voter-filter { + 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%; +} /* GitHub resolver import cards (rich bodies on -/ garden + vote compare) */ article.import-card { diff --git a/server/static/theme_retro.css b/server/static/theme_retro.css index d1ecf3ecbc2e42d9f1d2d5718423782f68c8ccbe..8c2b3143889c9f1afbc29c8862094a949541e739 100644 --- a/server/static/theme_retro.css +++ b/server/static/theme_retro.css @@ -554,6 +554,16 @@ body.view-ontology .ont-history-link-open { color: #23a; font-weight: 600; } +body.view-ontology .ont-voter-filter { + 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%; +} /* ================================================================ GARDEN HIERARCHY — parents ↑ / self / children ↓ (paper context). diff --git a/server/static/theme_retro_craft.css b/server/static/theme_retro_craft.css index 21c7a5eb80fc7f6c9cefc32562e44a810ed42a53..22509c08300a1db9b3fe78d6fdd3b9fbb8d0babe 100644 --- a/server/static/theme_retro_craft.css +++ b/server/static/theme_retro_craft.css @@ -533,6 +533,16 @@ body.view-ontology .ont-history-link-open { color: #1a4a8c; font-weight: 600; } +body.view-ontology .ont-voter-filter { + 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%; +} nav.breadcrumb.ont-sibling-nav { margin-top: 0; diff --git a/server/tests/integration_html.rs b/server/tests/integration_html.rs index 07b3032b567eabec2dc253b098e9b5fc4e5bfea2..b73e787ad0ad144cf9f7edc20a56b1fb40a9610f 100644 --- a/server/tests/integration_html.rs +++ b/server/tests/integration_html.rs @@ -991,3 +991,111 @@ async fn test_scope_page_without_history_shows_empty_replay_state() { .unwrap(); assert_eq!(missing.status(), reqwest::StatusCode::NOT_FOUND); } + +#[tokio::test] +async fn test_scope_page_by_voter_forks_rankings_and_replay() { + let (addr, _tmp, _log, state, _handle) = create_test_server_with_state().await; + let client = reqwest::Client::new(); + let alice = seed_test_identity(&state, "alice", "alicetok", "secret").await; + let bob = seed_test_identity(&state, "bob", "bobtok", "secret").await; + let post = |bearer: &str, delegate: &str, text: &str| { + let client = client.clone(); + let bearer = bearer.to_string(); + let delegate = delegate.to_string(); + let text = text.to_string(); + async move { + rpc_batch( + &client, + addr, + Some(&bearer), + serde_json::json!([{ + "Post": { + "room": "public", + "thread_tag": "fork-test", + "delegate": delegate, + "text": text, + "return_rank_diff": false + } + }]), + ) + .await + } + }; + + post( + &alice, + "00000000-0000-0000-0000-00000000000a:rig:test/model", + "~/fork/alpha { a }\n~/fork/beta { b }\n~/fork/gamma { c }\n{ alice prefers alpha }\n~/fork/alpha 3:1 ~/fork/beta\n", + ) + .await; + post( + &alice, + "00000000-0000-0000-0000-00000000000a:rig:test/model", + "{ alpha clears gamma too }\n~/fork/alpha 2:1 ~/fork/gamma\n", + ) + .await; + post( + &bob, + "00000000-0000-0000-0000-00000000000b:rig:test/model", + "{ bob prefers beta }\n~/fork/beta 3:1 ~/fork/alpha\n", + ) + .await; + + let get_body = |url: String| { + let client = client.clone(); + async move { client.get(url).send().await.unwrap().text().await.unwrap() } + }; + + // Alice's fork: only her vote counts, alpha leads. + let body = get_body(format!("http://{addr}/~/fork?by=alice")).await; + assert!(body.contains("filtered: only votes by"), "{body}"); + assert!(body.contains("alice")); + let (ia, ib) = (body.find("/~/alpha"), body.find("/~/beta")); + assert!(ia.is_some() && ib.is_some() && ia < ib, "alice's fork crowns alpha"); + + // Bob's fork: beta leads. + let body = get_body(format!("http://{addr}/~/fork?by=bob")).await; + let (ia, ib) = (body.find("/~/alpha"), body.find("/~/beta")); + assert!(ia.is_some() && ib.is_some() && ib < ia, "bob's fork crowns beta"); + + // An unknown voter empties the table but keeps the notice. + let body = get_body(format!("http://{addr}/~/fork?by=mallory")).await; + assert!(body.contains("filtered: only votes by")); + assert!(body.contains("no voted pairs yet in this scope")); + + // The replay honors the fork and names the voter. + let data: serde_json::Value = client + .get(format!("http://{addr}/~/fork?v=history.json&by=alice")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(data["voter"].as_str().unwrap(), "alice"); + let history = data["history"].as_array().unwrap(); + assert_eq!(history.len(), 2, "only alice's vote events survive"); + let rankings = history[1]["current_rankings"].as_array().unwrap(); + let score = |item: &str| { + rankings + .iter() + .find(|r| r["item"] == item) + .and_then(|r| r["score"].as_f64()) + .unwrap() + }; + assert!(score("~/alpha") > score("~/beta"), "alice's replay crowns alpha"); + + let data: serde_json::Value = client + .get(format!("http://{addr}/~/fork?v=history.json&by=mallory")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(data["history"].as_array().unwrap().len(), 0); + + // The link bar carries the filter into the replay URL (`&` escapes in hrefs). + let body = get_body(format!("http://{addr}/~/fork?by=alice")).await; + assert!(body.contains("/~/fork?v=history&by=alice")); +}