constitution · epochs · watch · epoch 3

comparison

c_c6beb77e8e71 (tommy-mor) vs c_48fcbcde8f88 (tommy-mor)

download prompt · raw event · cmp_d58296cab3ef55

council reasoning

~anthropic/claude-sonnet-latest · winner B · 60:40 · permalink

Side B substantially deduplicates a large amount of copy-pasted HTTP/OAuth/test-harness boilerplate across four test files into shared helpers in test.common and test.oauth, reducing maintenance burden without changing behavior—clear lasting value with low risk. Side A refactors entity-panel selectors to be per-item and reuses entity_section in vote comparisons, which is a reasonable improvement but also introduces a stray syntax artifact (`| FetchJobResult::SkippedDuplicate`) and removes some vote-compare-specific styling/markup, making it a slightly riskier and more speculative change.

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

A ships a lasting production design fix: entity sections become per-ItemId data-attribute morph targets (no shared #entity-section/#entity-panel IDs), fetch streams use entity_section_selector, and vote-compare reuses entity_section instead of a parallel card/CSS path. B only consolidates duplicated Babashka test helpers (assert/ANSI, cargo build, server env, mock Google/HTTP) into common/oauth—valuable maintainability, but no product behavior or architecture change.

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

Side A makes a functional UI architecture improvement by replacing the global `#entity-section` target with per-item `data-entity-section` selectors via `entity_section_selector`, updating all SSE morph calls accordingly, which enables correct updates for multiple entity sections and reuses `entity_section` in the voting UI. Side B is a worthwhile refactoring that centralizes duplicated test helpers, OAuth utilities, build logic, and test harness code, but it primarily improves test maintainability rather than changing core application behavior.

sides

A — c_c6beb77e8e71 (tommy-mor)

message

[8dab9b80] nice

diff preview

diff --git a/server/src/fetch/html.rs b/server/src/fetch/html.rs
index 3e0309ff1c2ac1b17923922d2340ba6710e0f9d1..dadf050515f0473943dad97df5d318032c8cb385 100644
--- a/server/src/fetch/html.rs
+++ b/server/src/fetch/html.rs
@@ -10,13 +10,18 @@ use crate::{
     ui_action::UI_RPC_FIELD,
 };
 
-fn entity_panel(node: &NodeState) -> Markup {
+/// CSS selector for Idiomorph / SSE updates of one entity block.
+pub fn entity_section_selector(item: &ItemId) -> String {
+    format!(r#"[data-entity-section="{}"]"#, item.as_str())
+}
+
+pub fn entity_panel(node: &NodeState) -> Markup {
     if let Some(markup) = crate::render::reddit::entity_markup(node) {
         return markup;
     }
     html! {
         @if let Some(data) = &node.data {
-            div id="entity-panel" class="entity-card" {
+            div class="entity-card" {
                 h2 { (data.title) }
                 @if let Some(author) = &data.author {
                     p class="muted small" { "by " (author) }
@@ -76,11 +81,11 @@ pub fn fetch_entity_panel(item: &ItemId, has_data: bool, fetching: bool) -> Mark
     }
 }
 
-/// Entity card + fetch control (target `#entity-section` for Idiomorph / SSE).
+/// Entity card + fetch control (morph target [`entity_section_selector`]).
 pub fn entity_section(item: &ItemId, node: &NodeState, fetching: bool) -> Markup {
     let has_data = node.data.is_some();
     html! {
-        section id="entity-section" class="demo-panel" {
+        section class="entity-section demo-panel" data-entity-section=(item.as_str()) {
             (entity_panel(node))
             (fetch_entity_panel(item, has_data, fetching))
         }
diff --git a/server/src/fetch/mod.rs b/server/src/fetch/mod.rs
index 35f968c21c69ca557bab7951413e3cfbbccfebfd..f5759a34a1afe4069805441cefde6474a6403550 100644
--- a/server/src/fetch/mod.rs
+++ b/server/src/fetch/mod.rs
@@ -77,8 +77,9 @@ pub fn fetch_entity_stream(
             let tree = state.tree.read().await;
             let empty = NodeState::default();
             let node = tree.get(&id).unwrap_or(&empty);
+            let sel = html::entity_section_selector(&id);
             JsBuilder::new()
-                .morph_selector("#entity-section", html::entity_section(&id, node, true))
+                .morph_selector(&sel, html::entity_section(&id, node, true))
                 .build()
         };
         yield Ok(js_event(fetching_js));
@@ -100,12 +101,13 @@ pub fn fetch_entity_stream(
             FetchJobResult::Imported(_)
             | FetchJobResult::NotFound
             | FetchJobResult::SkippedCached
-            | FetchJobResult::SkippedDuplicate => {
+            |             FetchJobResult::SkippedDuplicate => {
                 let tree = state.tree.read().await;
                 let empty = NodeState::default();
                 let node = tree.get(&id).unwrap_or(&empty);
+                let sel = html::entity_section_selector(&id);
                 let mut b = JsBuilder::new()
-                    .morph_selector("#entity-section", html::entity_section(&id, node, false));
+                    .morph_selector(&sel, html::entity_section(&id, node, false));
                 if kind == FetchKind::Children {
                     b = b.morph_selector("#ranking-panel", ranking_panel(&id, node, &tree));
                 }
@@ -115,8 +117,9 @@ pub fn fetch_entity_stream(
                 let tree = state.tree.read().await;
                 let empty = NodeState::default();
                 let node = tree.get(&id).unwrap_or(&empty);
+                let sel = html::entity_section_selector(&id);
                 let js = JsBuilder::new()
-                    .morph_selector("#entity-section", html::entity_section(&id, node, false))
+                    .morph_selector(&sel, html::entity_section(&id, node, false))
                     .raw(&error_js(&format!("Reddit rate limit — retry in {reset_secs}s.")))
                     .build();
                 yield Ok(js_event(js));
@@ -125,8 +128,9 @@ pub fn fetch_entity_stream(
                 let tree = state.tree.read().await;
                 let empty = NodeState::default();
                 let node = tree.get(&id).unwrap_or(&empty);
+                let sel = html::entity_section_selector(&id);
                 let js = JsBuilder::new()
-                    .morph_selector("#entity-section", html::entity_section(&id, node, false))
+                    .morph_selector(&sel, html::entity_section(&id, node, false))
                     .raw(&error_js(&format!("Fetch failed: {msg}")))
                     .build();
                 yield Ok(js_event(js));
diff --git a/server/src/html/vote.rs b/server/src/html/vote.rs
index 89ed621ad861214e147add2062224fc4137ff8ad..48752f4d78d4762d1badc44e8df008bf5a45bab4 100644
--- a/server/src/html/vote.rs
+++ b/server/src/html/vote.rs
@@ -8,6 +8,7 @@ use maud::{html, Markup};
 use serde::Deserialize;
 
 use crate::{
+    fetch::html::entity_section,
     form_template::template_json_compact,
     html::JsBuilder,
     pair::{children_of, resolve_pair, suggest_next_pair_in_pool},
@@ -169,37 +170,13 @@ pub(crate) fn vote_recorded_morph(
 }
 
 fn vote_compare_item_card(tree: &GlobalTree, item: &ItemId, side_class: &str) -> Markup {
-    let href = item_href(item);
-    let title = child_title(tree, item);
+    let node = tree.get(item).cloned().unwrap_or_else(|| NodeState {
+        id: item.clone(),
+        ..Default::default()
+    });
     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))
-                        }
-                    }
-                }
-            }
+            (entity_section(item, &node, false))
         }
     }
 }
@@ -270,9 +247,6 @@ pub async fn vote_page(
                 (vote_compare_item_card(&tree, &right, "vote-compare-right"))
             }
             (vote_back_nav(&parent))
-            div id="vote-edge-history-region" {
-                (edge_history)
-            }
             form id="vote-compare-form" method="POST" action="/ui" {
                 input type="hidden" name=(UI_RPC_FIELD) value=(rpc_json);
                 input type="hidden" name="ratio_left" id="vote-ratio-left" value="50";
@@ -285,6 +259,9 @@ pub async fn vote_page(
                 }
                 (vote_compare_actions(&parent, next_pair.as_ref()))
             }
+            div id="vote-edge-history-region" {
+                (edge_history)
+            }
         }
     };
 
diff --git a/server/src/render/reddit.rs b/server/src/render/reddit.rs
index 4a18de93cf57d8395ded3caa373a708f39b3f43f..c4f98fc760c32ce1b41a91bd41e97908bd198937 100644
--- a/server/src/render/reddit.rs
+++ b/server/src/render/reddit.rs
@@ -11,7 +11,7 @@ pub fn is_reddit_post(id: &ItemId) -> bool {
     id.as_str().starts_with("reddit.com/") && id.as_str().contains("/comments/")
 }
 
-/// Post detail card (`#entity-panel`).
+/// Post detail card (inside [`crate::fetch::html::entity_panel`]).
 pub fn entity_markup(node: &NodeState) -> Option<Markup> {
     if !is_reddit_post(&node.id) {
         return None;
@@ -41,7 +41,7 @@ pub fn child_row_markup(tree: &GlobalTree, id: &ItemId, href: &str) -> Option<Ma
 fn post_entity_card(data: &EntityData) -> Markup {
     let image = data.image_url.as_ref().or(data.thumb_url.as_ref());
     html! {
-        div id="entity-panel" class="entity-card reddit-post" {
+        div class="entity-card reddit-post" {
             h2 { (data.title) }
             @if let Some(author) = &data.author {
                 p class="muted small" { "by " (author) }
diff --git a/server/static/sorter.css b/server/static/sorter.css
index b95718ce463b200a5667d3014dac2119836a0bef..9379c5f41dedbd41fd8951099a118de1da2a62f4 100644
--- a/server/static/sorter.css
+++ b/server/static/sorter.css
@@ -254,38 +254,11 @@ h1 {
 }
 
 .vote-compare-side {
-  background: var(--panel);
-  border: 1px solid var(--border);
-  border-radius: 8px;
-  padding: 1rem;
   min-height: 120px;
 }
 
-.vote-compare-item {
-  color: var(--accent);
-  text-decoration: none;
-  display: block;
-}
-
-.vote-compare-item:hover {
-  text-decoration: underline;
-}
-
-.vote-compare-figure {
-  margin: 0.75rem 0 0;
-}
-
-.vote-compare-image {
-  display: block;
-  max-width: 100%;
-  height: auto;
-  border-radius: 6px;
-  border: 1px solid var(--border);
-}
-
-.vote-compare-item-body {
-  margin-top: 0.75rem;
-  font-size: 0.9rem;
+.vote-compare-side .entity-section {
+  margin: 0;
 }
 
 .vote-compare-nav {

download full diff A

B — c_48fcbcde8f88 (tommy-mor)

message

[b32c92f2] consolidated shared functions in tests (composer 2 fast)

diff preview

diff --git a/test/auth.bb b/test/auth.bb
index a67cc1de763434176d2f68e419dd37a8cd328395..78cffc875ffe83f512bca253f4a7489227311da4 100644
--- a/test/auth.bb
+++ b/test/auth.bb
@@ -3,113 +3,14 @@
   (:require [babashka.process :as p]
             [babashka.fs :as fs]
             [cheshire.core :as json]
-            [org.httpkit.server :as http]
-            [test.common :as common]))
+            [clojure.string :as str]
+            [test.common :as common]
+            [test.oauth :as oauth]))
 
-(def ^:private ansi-green "\033[32m")
-(def ^:private ansi-red   "\033[31m")
-(def ^:private ansi-reset "\033[0m")
 (def ^:private counts (atom {:pass 0 :fail 0}))
 
-(defn- pass [msg]
-  (swap! counts update :pass inc)
-  (println (str ansi-green "  ✓ " ansi-reset msg)))
-
-(defn- fail [msg]
-  (swap! counts update :fail inc)
-  (println (str ansi-red "  ✗ " ansi-reset msg)))
-
 (defn- assert! [pred msg]
-  (if pred
-    (pass msg)
-    (do (fail msg)
-        (throw (ex-info (str "FAIL: " msg) {})))))
-
-(defn- http-client []
-  (-> (java.net.http.HttpClient/newBuilder)
-      (.followRedirects java.net.http.HttpClient$Redirect/ALWAYS)
-      (.build)))
-
-(defn- http-get [url & {:keys [headers]}]
-  (let [b (java.net.http.HttpRequest/newBuilder (java.net.URI/create url))]
-    (doseq [[k v] (or headers {})]
-      (.header b k v))
-    (let [req (-> b (.GET) (.build))
-          resp (.send (http-client) req (java.net.http.HttpResponse$BodyHandlers/ofString))]
-      {:status (.statusCode resp) :body (.body resp) :headers (.map (.headers resp))})))
-
-(defn- http-post-json [url data & {:keys [headers]}]
-  (let [body (json/generate-string data)
-        b (java.net.http.HttpRequest/newBuilder (java.net.URI/create url))]
-    (.header b "Content-Type" "application/json")
-    (doseq [[k v] (or headers {})]
-      (.header b k v))
-    (let [req (-> b
-                  (.POST (java.net.http.HttpRequest$BodyPublishers/ofString body))
-                  (.build))
-          resp (.send (http-client) req (java.net.http.HttpResponse$BodyHandlers/ofString))]
-      {:status (.statusCode resp) :body (.body resp) :headers (.map (.headers resp))})))
-
-(defn- http-post-form [url form]
-  (let [pairs (->> form
-                   (map (fn [[k v]]
-                          (str (java.net.URLEncoder/encode (name k) "UTF-8")
-                               "="
-                               (java.net.URLEncoder/encode (str v) "UTF-8"))))
-                   (clojure.string/join "&"))
-        b (java.net.http.HttpRequest/newBuilder (java.net.URI/create url))]
-    (.header b "Content-Type" "application/x-www-form-urlencoded")
-    (let [req (-> b
-                  (.POST (java.net.http.HttpRequest$BodyPublishers/ofString pairs))
-                  (.build))
-          resp (.send (http-client) req (java.net.http.HttpResponse$BodyHandlers/ofString))]
-      {:status (.statusCode resp) :body (.body resp) :headers (.map (.headers resp))})))
-
-(defn- parse-query [s]
-  (into {}
-        (for [part (clojure.string/split (or s "") #"&")
-              :when (not (clojure.string/blank? part))]
-          (let [[k v] (clojure.string/split part #"=" 2)]
-            [(keyword (java.net.URLDecoder/decode k "UTF-8"))
-             (some-> v (java.net.URLDecoder/decode "UTF-8"))]))))
-
-(defn- b64url [s]
-  (-> (java.util.Base64/getUrlEncoder)
-      (.withoutPadding)
-      (.encodeToString (.getBytes s "UTF-8"))))
-
-(defn- make-id-token [sub]
-  (str (b64url "{\"alg\":\"RS256\",\"typ\":\"JWT\"}")
-       "."
-       (b64url (json/generate-string {:sub sub}))
-       ".fakesig"))
-
-(defn- start-mock-google [port]
-  (let [google-users ["google-user-1" "google-user-2"]
-        !call-count (atom 0)
-        handler
-        (fn [req]
-          (cond
-            (and (= :get (:request-method req))
-                 (= "/o/oauth2/v2/auth" (:uri req)))
-            (let [q (parse-query (:query-string req))
-                  redirect-uri (:redirect_uri q)
-                  state (:state q)
-                  loc (str redirect-uri "?code=mockcode&state=" state)]
-              {:status 302 :headers {"Location" loc} :body ""})
-
-            (and (= :post (:request-method req))
-                 (= "/token" (:uri req)))
-            (let [n   (swap! !call-count inc)
-                  sub (nth google-users (mod (dec n) (count google-users)))]
-              {:status 200
-               :headers {"Content-Type" "application/json"}
-               :body (json/generate-string {:id_token (make-id-token sub)})})
-
-            :else
-            {:status 404 :body "not found"}))
-        stop-fn (http/run-server handler {:port port})]
-    {:stop-fn stop-fn :port port}))
+  (common/test-assert! counts pred msg))
 
 (defn auth-test [& _args]
   (println "\n━━━ auth v3 integration check ━━━\n")
@@ -117,8 +18,7 @@
 
   (println "building server + CLI binaries…")
   (common/letlocals
-   (bind build @(p/process [(common/cargo-bin) "build" "--release" "-p" "slugsocial-server" "-p" "slugsocial"]
-                           {:inherit true :env common/base-env}))
+   (bind build (common/run-cargo-build-release! ["slugsocial-server" "slugsocial"]))
    (assert! (zero? (:exit build)) "cargo build succeeds")
    (bind server-bin "target/release/slugsocial-server")
    (bind cli-bin "target/release/slugsocial")
@@ -134,19 +34,10 @@
    (bind !server (atom nil))
    (bind !google (atom nil))
 
-   (bind server-env (merge common/base-env
-                           {"SLUG_DATA_DIR" tmp-dir
-                            "SLUG_KEYS"     "test:test"
-                            "PORT"          (str slug-port)
-                            "RUST_LOG"      "warn"
-                            "SLUG_PUBLIC_URL" base-url
-                            "SLUG_GOOGLE_AUTH_URL" (str google-url "/o/oauth2/v2/auth")
-                            "SLUG_GOOGLE_TOKEN_URL" (str google-url "/token")
-                            "SLUG_GOOGLE_CLIENT_ID" "mock"
-                            "SLUG_GOOGLE_CLIENT_SECRET" "mock"}))
+   (bind server-env (common/slug-server-env tmp-dir base-url google-url slug-port))
    (try
      (println (str "\nstarting mock google on :" google-port))
-     (reset! !google (start-mock-google google-port))
+     (reset! !google (oauth/start-mock-google google-port :google-users ["google-user-1" "google-user-2"]))
      (assert! (some? (:stop-fn @!google)) "mock google started")
 
      (println (str "starting server on :" slug-port))
@@ -154,34 +45,33 @@
      (assert! (common/wait-for-server base-url 10000) "server responds to /healthz")
 
      (println "\nstarting pending session…")
-     (let [start-resp (http-post-json (str base-url "/api/v0/pending-session")
-                                      {:agent "00000000-0000-0000-0000-000000000000:bb:local/dev"})
+     (let [start-resp (oauth/http-post-json (str base-url "/api/v0/pending-session")
+                                            {:agent "00000000-0000-0000-0000-000000000000:bb:local/dev"})
            _ (assert! (= 200 (:status start-resp)) "pending-session start returns 200")
            start-json (json/parse-string (:body start-resp) true)]
-       (assert! (clojure.string/starts-with? (:session start-json) "p_") "session id has p_ prefix")
-       (assert! (clojure.string/includes? (:login_url start-json) "/auth/login") "login_url provided")
+       (assert! (str/starts-with? (:session start-json) "p_") "session id has p_ prefix")
+       (assert! (str/includes? (:login_url start-json) "/auth/login") "login_url provided")
 
        (println "\nsimulating browser oauth redirects…")
-       ;; This will follow redirects: /auth/login -> mock google -> /auth/callback -> /auth/choose-username
-       (let [login-get (http-get (:login_url start-json))]
+       (let [login-get (oauth/http-get (:login_url start-json))]
          (assert! (= 200 (:status login-get)) "choose-username page reachable after oauth callback"))
 
        (println "\nchoosing username…")
-       (let [choose (http-post-form (str base-url "/auth/choose-username")
-                                    {:session (:session start-json) :username "bbuser"})]
+       (let [choose (oauth/http-post-form (str base-url "/auth/choose-username")
+                                          {:session (:session start-json) :username "bbuser"})]
          (assert! (= 200 (:status choose)) "choose-username POST returns 200"))
 
        (println "\npolling pending session…")
-       (let [poll (http-get (str base-url "/api/v0/pending-session/" (:session start-json)))]
+       (let [poll (oauth/http-get (str base-url "/api/v0/pending-session/" (:session start-json)))]
          (assert! (= 200 (:status poll)) "pending-session poll returns 200")
          (let [poll-json (json/parse-string (:body poll) true)]
            (assert! (:complete poll-json) "pending session complete=true")
            (assert! (= "bbuser" (:user poll-json)) "poll returns stored username bbuser")
-           (assert! (clojure.string/starts-with? (:token poll-json) "slug_") "poll returns bearer token")
+           (assert! (str/starts-with? (:token poll-json) "slug_") "poll returns bearer token")
 
            (println "\nwhoami…")
-           (let [who (http-get (str base-url "/api/v0/whoami")
-                               :headers {"Authorization" (str "Bearer " (:token poll-json))})]
+           (let [who (oauth/http-get (str base-url "/api/v0/whoami")
+                                     :headers {"Authorization" (str "Bearer " (:token poll-json))})]
              (assert! (= 200 (:status who)) "whoami returns 200")
              (let [who-json (json/parse-string (:body who) true)]
                (assert! (= "bbuser" (:user who-json)) "whoami user is bbuser (stored form)"))))))
@@ -195,11 +85,11 @@
                   (str "identity start exits 0 (stderr: " (:err start-proc) ")"))
          (let [start-cli (json/parse-string (:out start-proc) true)]
            (assert! (= "present_oauth_url_to_user" (:phase start-cli)) "identity start --json phase")
-           (assert! (clojure.string/starts-with? (:session start-cli) "p_") "CLI start session id")
-           (let [login-get (http-get (:login_url start-cli))]
+           (assert! (str/starts-with? (:session start-cli) "p_") "CLI start session id")
+           (let [login-get (oauth/http-get (:login_url start-cli))]
              (assert! (= 200 (:status login-get)) "CLI login_url redirect chain succeeds"))
-           (let [choose (http-post-form (str base-url "/auth/choose-username")
-                                        {:session (:session start-cli) :username "cliuser"})]
+           (let [choose (oauth/http-post-form (str base-url "/auth/choose-username")
+                                              {:session (:session start-cli) :username "cliuser"})]
              (assert! (= 200 (:status choose)) "choose-username for cliuser"))
            (let [poll-proc @(p/process [cli-bin "identity" "poll" (:session start-cli)
                                         "--poll-interval-ms" "100" "--max-wait-secs" "30" "--json"]
@@ -209,10 +99,10 @@
              (let [poll-cli (json/parse-string (:out poll-proc) true)]
                (assert! (= "complete" (:phase poll-cli)) "identity poll --json phase")
                (assert! (= "cliuser" (:user poll-cli)) "CLI poll user (stored form)")
-               (assert! (clojure.string/starts-with? (:token poll-cli) "slug_") "CLI poll token")
+               (assert! (str/starts-with? (:token poll-cli) "slug_") "CLI poll token")
                (let [token-path (str cli-home "/.config/slugsocial/token")]
                  (assert! (fs/exists? token-path) "token written under isolated HOME")
-                 (assert! (= (clojure.string/trim (slurp token-path)) (:token poll-cli))
+                 (assert! (= (str/trim (slurp token-path)) (:token poll-cli))
                           "token file matches poll JSON"))
      

… preview truncated; 24,704 characters omitted

download full diff B

Hardlinks — judgments / attempts / prompt

prompt download

judgments

attempts

Prompt text is loaded only by the download route.