constitution · epochs · watch · epoch 3

comparison

c_af08bd851e49 (tommy-mor) vs c_48edc893c5b0 (tommy-mor)

download prompt · raw event · cmp_775c0ed9286efb

council reasoning

~anthropic/claude-sonnet-latest · winner A · 6:4 · permalink

Side A ships a complete, tested feature (pairwise vote-compare page with a principled next-pair/bridge-selection algorithm in pair.rs), fixes a real correctness bug in ItemId normalization (from_storage) that ripples through reducer/reddit import, and improves test infra (extracted mock-reddit support, new Clojure e2e test) — all backed by unit and integration tests. Side B mainly stands up generic plumbing (form_template holes, ui_action enum, /ui route) for existing forum actions, which is useful scaffolding but smaller in scope and lower-stakes than A's working feature plus bugfix.

~x-ai/grok-latest · winner A · 2:1 · permalink

A ships lasting product design: bridge-aware pair selection in pair.rs with tests, the /vote compare page and post-vote morph path, plus ItemId::from_storage canonicalization used in Reddit import and votes. B is valuable plumbing (form_template holes, HtmlUiAction, POST /ui wrappers and expand-form morphs) but mostly routing/refactor of existing ingest/redact flows rather than new core behavior.

openai/gpt-chat-latest · winner A · 5:2 · permalink

Side A delivers substantial end-user functionality and infrastructure: it adds a full pairwise voting page, intelligent pair selection based on connected components, in-place UI morphing after votes, ID normalization via `ItemId::from_storage`, and corresponding integration/tests. Side B mainly introduces a generic `/ui` endpoint and form-template mechanism, refactors existing web-post handlers for reuse, and adds lazy expansion of new-thread forms; while useful architectural work, it is less directly impactful than the new voting workflow and correctness improvements in Side A.

sides

A — c_af08bd851e49 (tommy-mor)

message

[2bc302c3] refactor

diff preview

diff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs
index 06001212820101e0cc953d3687dea64f85e60787..d2f9769108def7ca2c5857aec8b4319426188a66 100644
--- a/server/src/api/ui_html.rs
+++ b/server/src/api/ui_html.rs
@@ -47,7 +47,7 @@ pub async fn post_ui_html(
             ratio_left,
             ratio_right,
             scope,
-            next,
+            vote_compare,
         } => {
             let parent = parent_from_scope(&scope);
             if let Err(e) = state
@@ -57,14 +57,12 @@ pub async fn post_ui_html(
                 return ui_js_warn(&e).into_response();
             }
             let tree = state.tree.read().await;
-            if !next.trim().is_empty() {
+            if vote_compare {
+                let left = parse_item_param(&a);
+                let right = parse_item_param(&b);
+                let morph = crate::html::vote::vote_recorded_morph(&tree, &parent, &left, &right);
                 drop(tree);
-                return JsBuilder::new()
-                    .raw(&format!(
-                        "window.location.href={};",
-                        js_string_literal(next.trim())
-                    ))
-                    .into_response();
+                return morph.into_response();
             }
             let empty = crate::reducer::NodeState::default();
             let node = tree.get(&parent).unwrap_or(&empty);
@@ -137,7 +135,7 @@ mod tests {
                 ratio_left: 3,
                 ratio_right: 1,
                 scope: String::new(),
-                next: String::new(),
+                vote_compare: false,
             }
         );
     }
diff --git a/server/src/html/mod.rs b/server/src/html/mod.rs
index 61cdbc094819ddedb755572c59456ec0d6617619..cd578a5fea46a9a1d49e238d08a80c2caf18708d 100644
--- a/server/src/html/mod.rs
+++ b/server/src/html/mod.rs
@@ -65,6 +65,15 @@ impl JsBuilder {
         self
     }
 
+    pub(crate) fn morph_inner_selector(mut self, selector: &str, markup: Markup) -> Self {
+        let html = js_string_literal(&markup.into_string());
+        self.snippets.push(format!(
+            "var __el = document.querySelector({sel}); if (__el) {{ Idiomorph.morph(__el, {html}, {{ morphStyle: 'innerHTML' }}); }}",
+            sel = js_string_literal(selector),
+        ));
+        self
+    }
+
     pub(crate) fn raw(mut self, js: &str) -> Self {
         if !js.is_empty() {
             self.snippets.push(js.to_string());
diff --git a/server/src/html/vote.rs b/server/src/html/vote.rs
new file mode 100644
index 0000000000000000000000000000000000000000..89ed621ad861214e147add2062224fc4137ff8ad
--- /dev/null
+++ b/server/src/html/vote.rs
@@ -0,0 +1,306 @@
+//! Pairwise vote UI — `/vote?parent=` with optional `left` / `right`.
+
+use axum::{
+    extract::{Query, State},
+    response::{Html, IntoResponse},
+};
+use maud::{html, Markup};
+use serde::Deserialize;
+
+use crate::{
+    form_template::template_json_compact,
+    html::JsBuilder,
+    pair::{children_of, resolve_pair, suggest_next_pair_in_pool},
+    path_types::ItemId,
+    reducer::{GlobalTree, GroupState, NodeState, VoteData},
+    state::{parse_item_param, AppState},
+    ui_action::UI_RPC_FIELD,
+};
+
+use super::{breadcrumb_path, item_href, layout};
+
+#[derive(Debug, Deserialize)]
+pub struct VoteQuery {
+    pub parent: String,
+    #[serde(default)]
+    pub left: Option<String>,
+    #[serde(default)]
+    pub right: Option<String>,
+}
+
+pub fn vote_href(parent: &ItemId) -> String {
+    format!(
+        "/vote?parent={}",
+        urlencoding::encode(parent.as_str())
+    )
+}
+
+fn vote_compare_href(parent: &ItemId, left: &ItemId, right: &ItemId) -> String {
+    format!(
+        "/vote?parent={}&left={}&right={}",
+        urlencoding::encode(parent.as_str()),
+        urlencoding::encode(left.as_str()),
+        urlencoding::encode(right.as_str()),
+    )
+}
+
+fn display_label(id: &ItemId) -> String {
+    id.segments()
+        .last()
+        .map_or("item".into(), |v| v.to_string())
+}
+
+fn child_title(tree: &GlobalTree, id: &ItemId) -> String {
+    tree.get(id)
+        .and_then(|n| n.data.as_ref())
+        .map(|d| d.title.clone())
+        .unwrap_or_else(|| display_label(id))
+}
+
+fn ratio_pct(ratio_left: i32, ratio_right: i32) -> f64 {
+    let l = ratio_left.max(0) as f64;
+    let r = ratio_right.max(0) as f64;
+    let sum = l + r;
+    if sum <= 0.0 {
+        50.0
+    } else {
+        (l / sum) * 100.0
+    }
+}
+
+fn ratios_for_page(v: &VoteData, page_left: &ItemId, page_right: &ItemId) -> (i32, i32) {
+    match (v.a.as_str(), v.b.as_str()) {
+        (a, b) if a == page_left.as_str() && b == page_right.as_str() => {
+            (v.ratio_left, v.ratio_right)
+        }
+        (a, b) if a == page_right.as_str() && b == page_left.as_str() => {
+            (v.ratio_right, v.ratio_left)
+        }
+        _ => (v.ratio_left, v.ratio_right),
+    }
+}
+
+fn edge_votes(group: &GroupState, left: &ItemId, right: &ItemId) -> Vec<VoteData> {
+    group
+        .recent_votes
+        .iter()
+        .filter(|v| {
+            (v.a.as_str() == left.as_str() && v.b.as_str() == right.as_str())
+                || (v.a.as_str() == right.as_str() && v.b.as_str() == left.as_str())
+        })
+        .cloned()
+        .collect()
+}
+
+fn vote_edge_history(tree: &GlobalTree, group: &GroupState, left: &ItemId, right: &ItemId) -> Markup {
+    let mut votes = edge_votes(group, left, right);
+    votes.sort_by(|a, b| b.ts.cmp(&a.ts));
+    let legend_left = child_title(tree, left);
+    let legend_right = child_title(tree, right);
+    html! {
+        @if votes.is_empty() {
+            p class="muted vote-edge-empty" { "no votes on this pair yet" }
+        } @else {
+            h3 class="vote-edge-history-title" {
+                "votes on this pair"
+                span class="vote-edge-history-axis muted" { " · " (legend_left) " : " (legend_right) }
+            }
+            ul class="vote-edge-history" {
+                @for v in &votes {
+                    @let (r_left, r_right) = ratios_for_page(v, left, right);
+                    @let pct = ratio_pct(r_left, r_right);
+                    li class="vote-edge-history-row" {
+                        div class="vote-edge-meta" {
+                            span class="vote-edge-ratio" { (format!("{}:{}", r_left, r_right)) }
+                        }
+                        div class="ratio-bar vote-edge-bar" aria-hidden="true" {
+                            div class="ratio-left" style={(format!("width: {:.3}%;", pct))} {}
+                            div class="ratio-right" style={(format!("width: {:.3}%;", 100.0 - pct))} {}
+                        }
+                    }
+                }
+            }
+        }
+    }
+}
+
+fn vote_back_nav(parent: &ItemId) -> Markup {
+    html! {
+        div class="vote-compare-nav" {
+            a class="vote-compare-back muted" href=(item_href(parent)) { "← back to " (display_label(parent)) }
+        }
+    }
+}
+
+fn vote_compare_actions(parent: &ItemId, next: Option<&(ItemId, ItemId)>) -> Markup {
+    let next_href = next.map(|(l, r)| vote_compare_href(parent, l, r));
+    html! {
+        div id="vote-compare-actions" class="vote-compare-actions" {
+            button type="submit" class="btn-primary" data-testid="vote-post" { "post vote" }
+            @if let Some(href) = &next_href {
+                a class="btn-secondary vote-compare-next" data-testid="vote-next-pair" href=(href) { "next pair" }
+            } @else {
+                span class="btn-secondary vote-compare-next is-disabled" { "no next pair" }
+            }
+        }
+    }
+}
+
+/// After recording a vote on the compare page: refresh edge history and next-pair link.
+pub(crate) fn vote_recorded_morph(
+    tree: &GlobalTree,
+    parent: &ItemId,
+    left: &ItemId,
+    right: &ItemId,
+) -> JsBuilder {
+    let pool = children_of(tree, parent);
+    let empty = NodeState::default();
+    let group = tree
+        .get(parent)
+        .unwrap_or(&empty)
+        .local_ranking
+        .clone();
+    let edge_history = vote_edge_history(tree, &group, left, right);
+    let next_pair = suggest_next(&group, left, right, &pool);
+    let actions = vote_compare_actions(parent, next_pair.as_ref());
+    JsBuilder::new()
+        .morph_inner_selector("#vote-edge-history-region", edge_history)
+        .morph_selector("#vote-compare-actions", actions)
+}
+
+fn vote_compare_item_card(tree: &GlobalTree, item: &ItemId, side_class: &str) -> Markup {
+    let href = item_href(item);
+    let title = child_title(tree, item);
+    html! {
+        div class=(format!("vote-compare-side {side_class}")) {
+            a class=(format!("vote-compare-item {side_class}")) href=(href) {
+                @if let Some(row) = crate::render::reddit::child_row_markup(tree, item, &href) {
+                    (row)
+                } @else {
+                    strong { (title) }
+                }
+            }
+            @if let Some(node) = tree.get(item) {
+                @if crate::render::reddit::is_reddit_post(item) {
+                    @if let Some(data) = &node.data {
+                        @if let Some(src) = data.image_url.as_ref().or(data.thumb_url.as_ref()) {
+                            figure class="vote-compare-figure" {
+                                img class="vote-compare-image" src=(src) alt="" loading="lazy";
+                            }
+                        }
+                        @if let Some(author) = &data.author {
+                            p class="muted small" { "by " (author) }
+                        }
+                    }
+                } @else if let Some(data) = &node.data {
+                    @if let Some(body) = &data.body_html {
+                        div class="vote-compare-item-body" {
+                            (maud::PreEscaped(body))
+                        }
+                    }
+                }
+            }
+        }
+    }
+}
+
+
+fn suggest_next(group: &GroupState, left: &ItemId, right: &ItemId, pool: &[ItemId]) -> Option<(ItemId, ItemId)> {
+    suggest_next_pair_in_pool(group, pool, Some((left, right)))
+}
+
+pub async fn vote_page(
+    State(state): State<AppState>,
+    Query(q): Query<VoteQuery>,
+) -> impl IntoResponse {
+    let parent = parse_item_param(&q.parent);
+    let left_param = q.left.as_deref().map(parse_item_param);
+    let right_param = q.right.as_deref().map(parse_item_param);
+
+    let tree = state.tree.read().await;
+    let empty = NodeState::default();
+    let parent_node = tree.get(&parent).unwrap_or(&empty);
+
+    let (left, right) = match resolve_pair(
+        &tree,
+        &parent,
+        left_param.as_ref(),
+        right_param.as_ref(),
+    ) {
+        Ok(p) => p,
+        Err(e) => {
+            let (msg, status) = e.status_message();
+            return (status, msg).into_response();
+        }
+    };
+
+    let pool = children_of(&tree, &parent);
+    let group = &parent_node.local_ranking;
+    let next_pair = suggest_next(group, &left, &right, &pool);
+    let edge_history = vote_edge_history(&tree, group, &left, &right);
+
+    let rpc_json = template_json_compact(&serde_json::json!({
+        "action": "record_vote",
+        "a": left.as_str(),
+        "b": right.as_str(),
+        "ratio_left": {"$form:i32": "ratio_left"},
+        "ratio_right": {"$form:i32": "ratio_right"},
+        "scope": parent.as_str(),
+        "vote_compare": true,
+    }))
+    .expect("vote rpc json");
+
+    let title = format!(
+        "vote — {} vs {}",
+        child_title(&tree, &left),
+        child_title(&tree, &right)
+    );
+
+    let body = html! {
+        section class="vote-compare-shell" {
+            h1 { "compare" }
+            (breadcrumb_path(&parent))
+            p class="muted vote-compare-scope" {
+                "ranking children of "
+                a href=(item_href(&par

… preview truncated; 32,381 characters omitted

download full diff A

B — c_48edc893c5b0 (tommy-mor)

message

[3f35edab] progress

diff preview

diff --git a/server/src/api/mod.rs b/server/src/api/mod.rs
index a10ce662105cff8fad949c6b83f7035ce79bed18..a986f706ea4b261cbaf004c02b4cf84184b41371 100644
--- a/server/src/api/mod.rs
+++ b/server/src/api/mod.rs
@@ -3,6 +3,7 @@ mod helpers;
 mod rpc;
 mod stream;
 mod validate;
+mod ui_html;
 mod web_post;
 
 pub use auth::{
@@ -33,6 +34,7 @@ pub use stream::{get_html_stream, get_stream};
 
 pub use validate::{normalize_room_and_thread, validate_ingest_document, ValidatedIngest};
 
+pub use ui_html::post_ui_html;
 pub use web_post::{check_web_ingest, post_web_ingest, post_web_redact};
 
 #[cfg(test)]
diff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs
new file mode 100644
index 0000000000000000000000000000000000000000..2b40a72059981d558768f73d189b991f3448c257
--- /dev/null
+++ b/server/src/api/ui_html.rs
@@ -0,0 +1,139 @@
+//! Single `POST /ui` entry for browser [`crate::html::ui_action::HtmlUiAction`] (JSON in `__rpc__` + holes).
+
+use axum::{
+    body::Body,
+    extract::State,
+    http::{header, HeaderMap, StatusCode},
+    response::{IntoResponse, Response},
+    Form,
+};
+use axum_extra::extract::cookie::CookieJar;
+use std::collections::HashMap;
+
+use crate::{
+    api::{
+        auth::optional_principal,
+        web_post::{run_check_web_ingest, run_post_web_ingest, run_post_web_redact, WebPostForm, WebRedactForm},
+    },
+    html::{
+        fragment_public_new_thread_form, fragment_room_new_thread_form, login_to_post_hint_markup,
+        parse_html_ui_from_form, user_can_post_room, user_can_view_room, HtmlUiAction, JsBuilder,
+        ThreadNav,
+    },
+    state::AppState,
+};
+
+pub async fn post_ui_html(
+    State(state): State<AppState>,
+    headers: HeaderMap,
+    jar: CookieJar,
+    Form(form): Form<HashMap<String, String>>,
+) -> impl IntoResponse {
+    let action = match parse_html_ui_from_form(&form) {
+        Ok(a) => a,
+        Err(e) => return ui_js_warn(&e.to_string()).into_response(),
+    };
+
+    match action {
+        HtmlUiAction::PostIngest {
+            room,
+            thread_tag,
+            text,
+            error_target,
+            form_id,
+        } => {
+            run_post_web_ingest(
+                &state,
+                &headers,
+                &jar,
+                WebPostForm {
+                    room,
+                    thread_tag,
+                    text,
+                    error_target,
+                    form_id,
+                },
+            )
+            .await
+        }
+        HtmlUiAction::CheckIngest {
+            room,
+            thread_tag,
+            text,
+            error_target,
+            form_id,
+        } => {
+            run_check_web_ingest(
+                &state,
+                &headers,
+                &jar,
+                WebPostForm {
+                    room,
+                    thread_tag,
+                    text,
+                    error_target,
+                    form_id,
+                },
+            )
+            .await
+        }
+        HtmlUiAction::RedactPost { post_id } => {
+            run_post_web_redact(&state, &headers, &jar, WebRedactForm { post_id }).await
+        }
+        HtmlUiAction::ExpandPublicNewThreadForm => {
+            let reduced = state.reduced.read().await;
+            let user = optional_principal(&headers, &jar, &reduced);
+            drop(reduced);
+            let markup = if user.is_some() {
+                fragment_public_new_thread_form(true)
+            } else {
+                login_to_post_hint_markup()
+            };
+            JsBuilder::new()
+                .morph_selector("#public-new-thread-ui-slot", markup)
+                .into_response()
+        }
+        HtmlUiAction::ExpandRoomNewThreadForm { room_wire } => {
+            let room_wire = room_wire.trim().to_string();
+            if room_wire.is_empty() {
+                return ui_js_warn("missing room").into_response();
+            }
+            let reduced = state.reduced.read().await;
+            let user = optional_principal(&headers, &jar, &reduced);
+            if !reduced.rooms.contains(&room_wire) {
+                drop(reduced);
+                return ui_js_warn("room not found").into_response();
+            }
+            if !user_can_view_room(&reduced, &room_wire, user.as_deref()) {
+                drop(reduced);
+                return ui_js_warn("forbidden").into_response();
+            }
+            let can_post = user
+                .as_ref()
+                .map(|u| user_can_post_room(&reduced, &room_wire, u))
+                .unwrap_or(false);
+            drop(reduced);
+            let Some(nav) = ThreadNav::from_room_id(&room_wire) else {
+                return ui_js_warn("bad room").into_response();
+            };
+            let markup = if can_post {
+                fragment_room_new_thread_form(&nav, true)
+            } else {
+                login_to_post_hint_markup()
+            };
+            JsBuilder::new()
+                .morph_selector("#room-new-thread-ui-slot", markup)
+                .into_response()
+        }
+    }
+}
+
+fn ui_js_warn(msg: &str) -> Response {
+    use crate::html::js_string_literal;
+    let js = format!("console.warn({});", js_string_literal(msg));
+    Response::builder()
+        .status(StatusCode::OK)
+        .header(header::CONTENT_TYPE, "text/javascript; charset=utf-8")
+        .body(Body::from(js))
+        .unwrap()
+}
diff --git a/server/src/api/web_post.rs b/server/src/api/web_post.rs
index a64010e382d3039821c836a5529adad0fe67cce5..265025f41ff1548d05b2d2d5d84202245388053f 100644
--- a/server/src/api/web_post.rs
+++ b/server/src/api/web_post.rs
@@ -222,8 +222,18 @@ pub async fn post_web_redact(
     jar: CookieJar,
     Form(form): Form<WebRedactForm>,
 ) -> impl IntoResponse {
+    run_post_web_redact(&state, &headers, &jar, form).await
+}
+
+/// Shared with [`crate::api::ui_html::post_ui_html`].
+pub(crate) async fn run_post_web_redact(
+    state: &AppState,
+    headers: &HeaderMap,
+    jar: &CookieJar,
+    form: WebRedactForm,
+) -> Response {
     let reduced = state.reduced.read().await;
-    let Some(_username) = optional_principal(&headers, &jar, &reduced) else {
+    let Some(_username) = optional_principal(headers, jar, &reduced) else {
         drop(reduced);
         return js_redirect("/login").into_response();
     };
@@ -239,8 +249,8 @@ pub async fn post_web_redact(
         return js_redirect("/login").into_response();
     };
 
-    match rpc_post_redact(&state, &headers, form.post_id).await {
-        Ok(RpcResult::RedactPostOk {}) => redact_success_response(&state).await.into_response(),
+    match rpc_post_redact(state, headers, form.post_id).await {
+        Ok(RpcResult::RedactPostOk {}) => redact_success_response(state).await.into_response(),
         Ok(_) => (StatusCode::BAD_REQUEST, "unexpected response").into_response(),
         Err((msg, hint)) => {
             let detail = hint.as_deref().unwrap_or("");
@@ -255,8 +265,18 @@ pub async fn post_web_ingest(
     jar: CookieJar,
     Form(form): Form<WebPostForm>,
 ) -> impl IntoResponse {
+    run_post_web_ingest(&state, &headers, &jar, form).await
+}
+
+/// Shared with [`crate::api::ui_html::post_ui_html`] (`POST /ui`).
+pub(crate) async fn run_post_web_ingest(
+    state: &AppState,
+    headers: &HeaderMap,
+    jar: &CookieJar,
+    form: WebPostForm,
+) -> Response {
     let reduced = state.reduced.read().await;
-    let Some(_username) = optional_principal(&headers, &jar, &reduced) else {
+    let Some(_username) = optional_principal(headers, jar, &reduced) else {
         drop(reduced);
         return js_redirect("/login").into_response();
     };
@@ -282,8 +302,8 @@ pub async fn post_web_ingest(
             .into_response();
     }
 
-    match rpc_post_with_bearer(&state, &bearer, room.clone(), thread_tag.clone(), text).await {
-        Ok(RpcResult::PostOk { .. }) => post_success_response(&state, &form, &headers, &jar)
+    match rpc_post_with_bearer(state, &bearer, room.clone(), thread_tag.clone(), text).await {
+        Ok(RpcResult::PostOk { .. }) => post_success_response(state, &form, headers, jar)
             .await
             .into_response(),
         Ok(_) => form_js_error(&form, "unexpected response", "Post did not return PostOk.").into_response(),
@@ -297,8 +317,18 @@ pub async fn check_web_ingest(
     jar: CookieJar,
     Form(form): Form<WebPostForm>,
 ) -> impl IntoResponse {
+    run_check_web_ingest(&state, &headers, &jar, form).await
+}
+
+/// Shared with [`crate::api::ui_html::post_ui_html`] (`POST /ui`).
+pub(crate) async fn run_check_web_ingest(
+    state: &AppState,
+    headers: &HeaderMap,
+    jar: &CookieJar,
+    form: WebPostForm,
+) -> Response {
     let reduced = state.reduced.read().await;
-    let Some(_username) = optional_principal(&headers, &jar, &reduced) else {
+    let Some(_username) = optional_principal(headers, jar, &reduced) else {
         drop(reduced);
         return js_redirect("/login").into_response();
     };
@@ -324,7 +354,7 @@ pub async fn check_web_ingest(
         return js_clear_errors(&form_error_target(&form)).into_response();
     }
 
-    match rpc_check_with_bearer(&state, &bearer, room, form.text.clone()).await {
+    match rpc_check_with_bearer(state, &bearer, room, form.text.clone()).await {
         Ok(RpcResult::CheckOk { .. }) => js_clear_errors(&form_error_target(&form)).into_response(),
         Ok(_) => form_js_error(&form, "unexpected response", "Check did not return CheckOk.").into_response(),
         Err((msg, hint)) => form_js_error(&form, &msg, hint.as_deref().unwrap_or("")).into_response(),
diff --git a/server/src/form_template.rs b/server/src/form_template.rs
new file mode 100644
index 0000000000000000000000000000000000000000..3709c2c09a859da006e4af173413d5d235bc19be
--- /dev/null
+++ b/server/src/form_template.rs
@@ -0,0 +1,142 @@
+//! Plan2-style JSON templates with `{"$form": "field_name"}` holes, filled from
+//! `application/x-www-form-urlencoded` (or any `String` → `String` map) **before**
+//! deserializing into a typed struct.
+//!
+//! # Wire format
+//!
+//! Templates are **compact JSON** (`serde_json::to_string`): one line, no pretty
+//! printing, strings escaped per JSON rules (`\"`, `\n`, etc.). Embed that string
+//! in HTML attributes or text nodes with normal HTML escaping (e.g. maud), not
+//! bespoke encodings.
+//!
+//! # Power vs flat hidden fields
+//!
+//! A form is always a string→string map. You can fake depth with dotted keys (`a.b.c`),
+//! but one structured blob (`__rpc__` = compact JSON) gives you nested objects,
+//! arrays, and optional fields without inventing a new naming scheme each time.
+//!
+//! # Security
+//!
+//! Substitution runs **before** `serde` into your command type. It does not fix
+//! authorization: if the client can replace the hidden `__rpc__` value, they can
+//! change the command shape unless you validate (signed blob, server-side session
+//! context, or treat the blob as hints only). Same threat model as any hidden field.
+
+use serde::Serialize;
+use serde_json::Value;
+use std::collections::HashMap;
+
+/// Serialize a value to compact JSON for a hidden `__rpc__` (or similar) field.
+pub fn template_json_compact<T: Serialize>(v: &T) -> serde_json::Result<String> {
+    serde_json::to_string(v)
+}
+
+/// Recursively walk the JSON AST and replace `{"$form": "key"}` with the submitted
+/// string for `key` (empty if missing). Other keys are unchanged.
+pub fn substitute_form_vars(val: &mut Value, form_data: &HashMap<String, String>) {
+    match val {
+        Value::Object(map) => {
+            if map.len() == 1 {
+                if let Some(Value::String(field_name)) = map.get("$form") {
+                    let submitted = form_data
+                        .get(field_name.as_str())
+                        .map(|s| s.as_str())
+                        .unwrap_or("");
+   

… preview truncated; 13,273 characters omitted

download full diff B

Hardlinks — judgments / attempts / prompt

prompt download

judgments

attempts

Prompt text is loaded only by the download route.