constitution · epochs · watch · epoch 3

comparison

c_2595b6007624 (tommy-mor) vs c_cd965c070df3 (tommy-mor)

download prompt · raw event · cmp_1cdf83c3575c91

council reasoning

~anthropic/claude-sonnet-latest · winner A · 85:15 · permalink

Side A is a substantial architectural overhaul—introducing a unified RPC batch protocol, room/scope model, and refactoring CLI, server routes, reducer state, and tests across dozens of files—representing significant lasting design work. Side B is a small, targeted bugfix (fixing Reddit child import wiring and unranked labels) with minor test updates, useful but narrow in scope and impact compared to A's systemic changes.

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

A introduces a lasting architectural pivot: batched `/api/v0/rpc`, room-scoped content (rooms vs forum threads in events/reducer), and CLI Public/Private scoping that replaces many REST handlers. B is a valuable but narrow fix—correct Reddit children attach via `apply_entity_under_parent` and title labels in the ranking panel—without core model impact comparable to A.

openai/gpt-chat-latest · winner A · 9:1 · permalink

Side A introduces a substantial architectural change: it consolidates many REST endpoints into a batch RPC interface, adds room-scoped commands and data models (room/thread separation), updates the CLI to use the new RPC layer, and refactors validation and reducer/event handling to support room-aware behavior. Side B fixes a real Reddit import bug by attaching imported children directly under the subreddit and improving unranked labels with tree metadata, but its impact is localized compared with A's lasting API and data-model redesign.

sides

A — c_2595b6007624 (tommy-mor)

message

[96b6da05] rpc + reducer changes first pass

diff preview

diff --git a/cli/src/main.rs b/cli/src/main.rs
index 630c5dea1f78c0ec9bc53e6b96234a0dc75bb705..8d0442959f4332bafe499a2a8cdf364731a06871 100644
--- a/cli/src/main.rs
+++ b/cli/src/main.rs
@@ -21,8 +21,9 @@ struct Cli {
     cmd: Option<Command>,
 }
 
+/// Commands scoped to a room (`public` or `shortid/slug`).
 #[derive(Subcommand, Debug)]
-enum Command {
+enum ScopedCmd {
     /// Browse the garden (ontology) — light mode, ranked by votes
     Garden {
         #[command(subcommand)]
@@ -174,6 +175,23 @@ enum Command {
         #[arg(long)]
         json: bool,
     },
+}
+
+#[derive(Subcommand, Debug)]
+enum Command {
+    /// Public site (same as room `public`)
+    Public {
+        #[command(subcommand)]
+        sub: ScopedCmd,
+    },
+    /// Private room id (`shortid/slug` from `room create`)
+    Private {
+        /// Room id, e.g. `a1b2c3d/my-project`
+        #[arg(value_name = "ROOM_ID")]
+        room: String,
+        #[command(subcommand)]
+        sub: ScopedCmd,
+    },
 
     /// Show all activity since you last posted (global feed)
     ///
@@ -628,6 +646,37 @@ fn http_client() -> Result<reqwest::Client> {
         .build()?)
 }
 
+async fn send_rpc(
+    client: &reqwest::Client,
+    base: &str,
+    bearer: Option<&str>,
+    commands: Vec<RpcCommand>,
+) -> Result<RpcBatchResponse> {
+    let url = format!("{}/api/v0/rpc", base.trim_end_matches('/'));
+    let mut req = client.post(url).json(&RpcBatch(commands));
+    if let Some(b) = bearer {
+        req = req.header("Authorization", format!("Bearer {}", b));
+    }
+    let resp = req.send().await?;
+    let status = resp.status();
+    let text = resp.text().await.unwrap_or_default();
+    if !status.is_success() {
+        return Err(anyhow!("rpc HTTP {}: {}", status, text.trim()));
+    }
+    serde_json::from_str(&text).map_err(|e| anyhow!("rpc response: {e}"))
+}
+
+fn rpc_line_ok(line: &RpcLine) -> Result<&RpcResult> {
+    if !line.ok {
+        let mut m = line.error.clone().unwrap_or_else(|| "rpc error".into());
+        if let Some(h) = &line.hint {
+            m.push_str(&format!("\nhint: {h}"));
+        }
+        return Err(anyhow!(m));
+    }
+    line.result.as_ref().ok_or_else(|| anyhow!("rpc missing result"))
+}
+
 /// Normalize ontology path for API. Accepts path with or without ~/ (shell expands ~ to $HOME).
 /// Returns a bare slug path (e.g. `languages/python`) with no leading `/` or `~/`.
 /// Call `ontology_path_for_api_query` before sending `item=` / `parent=` params so the server
@@ -729,231 +778,262 @@ fn write_secret_file(name: &str, contents: &str) -> Result<()> {
     Ok(())
 }
 
-#[tokio::main]
-async fn main() -> Result<()> {
-    let Cli { cmd, server } = Cli::parse();
-
-    // If no command provided, print the guide
-    let Some(cmd) = cmd else {
-        print!("{}", include_str!("../GUIDE.sorter"));
-        return Ok(());
-    };
-
-    let base = server.trim_end_matches('/');
-
-    match cmd {
-        Command::Healthz { json } => {
-            let client = http_client()?;
-            let url = format!("{base}/healthz");
-            let body = client.get(url).send().await?.text().await?;
-            if json {
-                // Wrap plain text response in a JSON object
-                println!("{}", serde_json::json!({ "ok": true, "body": body.trim() }));
-            } else {
-                println!("{body}");
-            }
-        }
-
-        Command::Search { query, json } => {
-            let client = http_client()?;
-            let url = format!("{base}/api/v0/search?q={}", urlencoding::encode(&query));
-            let resp: slug_types::SearchResponse = expect_json(client.get(url).send().await?).await?;
-            if json {
-                println!("{}", serde_json::to_string_pretty(&resp)?);
-            } else {
-                if !resp.items.is_empty() {
-                    println!("items ({})", resp.items.len());
-                    for item in &resp.items {
-                        print!("  {}", item.path);
-                        if let Some(body) = &item.body {
-                            let first_line = body.lines().next().unwrap_or("").trim();
-                            if !first_line.is_empty() {
-                                print!("  {}", first_line);
+async fn run_scoped(base: &str, room: &str, sub: ScopedCmd) -> Result<()> {
+    let room = room.trim();
+    let client = http_client()?;
+    match sub {
+        ScopedCmd::Garden { sub } => match sub {
+            GardenCmd::Tree { json } => {
+                let batch = send_rpc(&client, base, None, vec![RpcCommand::GetLeaves { room: room.to_string() }]).await?;
+                match rpc_line_ok(&batch.results[0])? {
+                    RpcResult::Leaves(resp) => {
+                        if json {
+                            println!("{}", serde_json::to_string_pretty(&resp)?);
+                        } else {
+                            for p in &resp.paths {
+                                println!("~/{}", p);
                             }
                         }
-                        println!();
-                    }
-                }
-                if !resp.threads.is_empty() {
-                    if !resp.items.is_empty() { println!(); }
-                    println!("threads ({})", resp.threads.len());
-                    let now_ms = std::time::SystemTime::now()
-                        .duration_since(std::time::UNIX_EPOCH)
-                        .unwrap_or_default()
-                        .as_millis() as i64;
-                    for t in &resp.threads {
-                        println!("  {}  {}n  {}", t.tag, t.post_count, slug_types::timeago::timeago(now_ms, t.last_activity));
-                    }
-                }
-                if !resp.posts.is_empty() {
-                    if !resp.items.is_empty() || !resp.threads.is_empty() { println!(); }
-                    println!("posts ({})", resp.posts.len());
-                    let now_ms = std::time::SystemTime::now()
-                        .duration_since(std::time::UNIX_EPOCH)
-                        .unwrap_or_default()
-                        .as_millis() as i64;
-                    for p in &resp.posts {
-                        let first_line = p.snippet.lines().next().unwrap_or("").trim();
-                        println!("  {} · {}  {}", p.thread, slug_types::timeago::timeago(now_ms, p.ts), first_line);
-                    }
-                }
-                if resp.items.is_empty() && resp.threads.is_empty() && resp.posts.is_empty() {
-                    println!("no results");
-                }
-            }
-        }
-
-        Command::Garden { sub } => match sub {
-            GardenCmd::Tree { json } => {
-                let client = http_client()?;
-                let url = format!("{base}/api/v0/leaves");
-                let builder = client.get(url);
-                let resp: LeavesResponse = expect_json(builder.send().await?).await?;
-                if json {
-                    println!("{}", serde_json::to_string_pretty(&resp)?);
-                } else {
-                    for p in &resp.paths {
-                        println!("~/{}", p);
                     }
+                    _ => return Err(anyhow!("unexpected RPC result")),
                 }
             }
-
             GardenCmd::Body { path, json, full } => {
                 let path = normalize_ontology_path_input(&path).map_err(anyhow::Error::msg)?;
                 let item_q = ontology_path_for_api_query(&path);
-                let client = http_client()?;
-                let mut url = format!("{base}/api/v0/item?item={}", urlencoding::encode(&item_q));
-                if full {
-                    url.push_str("&full=true");
-                }
-                let builder = client.get(url);
-                let resp: ItemResponse = expect_json(builder.send().await?).await?;
-                if json {
-                    println!("{}", serde_json::to_string_pretty(&resp)?);
-                } else {
-                    print_item_response(&resp);
+                let batch = send_rpc(
+                    &client,
+                    base,
+                    None,
+                    vec![RpcCommand::GetGardenItem {
+                        room: room.to_string(),
+                        item_path: item_q,
+                        full: Some(full),
+                    }],
+                )
+                .await?;
+                match rpc_line_ok(&batch.results[0])? {
+                    RpcResult::GardenItem(resp) => {
+                        if json {
+                            println!("{}", serde_json::to_string_pretty(&resp)?);
+                        } else {
+                            print_item_response(&resp);
+                        }
+                    }
+                    _ => return Err(anyhow!("unexpected RPC result")),
                 }
             }
-
             GardenCmd::Children { paths, depth, json } => {
                 let paths: Vec<String> = paths
                     .iter()
                     .map(|p| normalize_ontology_path_input(p).map_err(anyhow::Error::msg))
                     .collect::<Result<Vec<_>>>()?;
-                let client = http_client()?;
                 let parent_param = paths
                     .iter()
                     .map(|p| ontology_path_for_api_query(p))
                     .collect::<Vec<_>>()
                     .join(",");
-                let mut url = format!("{base}/api/v0/rank?parent={}", urlencoding::encode(&parent_param));
-                if let Some(d) = depth {
-                    url.push_str(&format!("&depth={d}"));
-                }
-                let builder = client.get(url);
-                let resp: RankResponse = expect_json(builder.send().await?).await?;
-
-                if json {
-                    println!("{}", serde_json::to_string_pretty(&resp)?);
-                } else {
-                    print_rank_response(&resp);
+                let batch = send_rpc(
+                    &client,
+                    base,
+                    None,
+                    vec![RpcCommand::GetGardenRank {
+                        room: room.to_string(),
+                        parent_path: parent_param,
+                        depth,
+                        offset: None,
+                        limit: None,
+                        percent: None,
+                    }],
+                )
+                .await?;
+                match rpc_line_ok(&batch.results[0])? {
+                    RpcResult::GardenRank(resp) => {
+                        if json {
+                            println!("{}", serde_json::to_string_pretty(&resp)?);
+                        } else {
+                            print_rank_response(&resp);
+                        }
+                    }
+                    _ => return Err(anyhow!("unexpected RPC result")),
                 }
             }
-
             GardenCmd::Pair { path, json } => {
                 let path = normalize_ontology_path_input(&path).map_err(anyhow::Error::msg)?;
                 let parent_q = ontology_path_for_api_query(&path);
-                let client = http_client()?;
-                let url = format!("{base}/api/v0/pair?parent={}", urlencoding::encode(&parent_q));
-                let builder = client.get(url);
-                let resp: PairResponse = expect_json(builder.send().await?).await?;
-                if json {
-                    println!("{}", serde_json::to_string_pretty(&resp)?);
-                } else {
-                    print_pair_response(&resp);
+                let batch = send_rpc(
+                    &client,
+                    base,
+                    None,
+                    vec![RpcCommand::GetPair {
+                        room: room.to_string(),
+                        parent_path: parent_q,
+                    }]

… preview truncated; 237,234 characters omitted

download full diff A

B — c_cd965c070df3 (tommy-mor)

message

[993d359c] Fix Reddit children import wiring and unranked child labels.

Listing imports attach posts directly under the subreddit without ensure_path
pulling comment-path segments in, and the ranking panel shows imported titles.
Update integration tests for JS SSE morphs and children fetch.

Co-authored-by: Cursor <cursoragent@cursor.com>

diff preview

diff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs
index d1defd28242fd2ca3b886adc91a7070bef75e653..e649a7d192feade465e19ce6187a829f6ec74372 100644
--- a/server/src/api/ui_html.rs
+++ b/server/src/api/ui_html.rs
@@ -58,7 +58,7 @@ pub async fn post_ui_html(
             let tree = state.tree.read().await;
             let empty = crate::reducer::NodeState::default();
             let node = tree.get(&parent).unwrap_or(&empty);
-            let panel = ranking_panel(&parent, node);
+            let panel = ranking_panel(&parent, node, &tree);
             JsBuilder::new()
                 .morph_selector("#ranking-panel", panel)
                 .into_response()
diff --git a/server/src/fetch/mod.rs b/server/src/fetch/mod.rs
index 0177bb161cea1b72a100b52efdfc5e710271c9eb..35f968c21c69ca557bab7951413e3cfbbccfebfd 100644
--- a/server/src/fetch/mod.rs
+++ b/server/src/fetch/mod.rs
@@ -107,7 +107,7 @@ pub fn fetch_entity_stream(
                 let mut b = JsBuilder::new()
                     .morph_selector("#entity-section", html::entity_section(&id, node, false));
                 if kind == FetchKind::Children {
-                    b = b.morph_selector("#ranking-panel", ranking_panel(&id, node));
+                    b = b.morph_selector("#ranking-panel", ranking_panel(&id, node, &tree));
                 }
                 yield Ok(js_event(b.build()));
             }
diff --git a/server/src/html/mod.rs b/server/src/html/mod.rs
index 27ce9118c73ec5643e04363ab1a36cf5da6101bf..e88cc43ddc9d8100f7994be6f5960ec4d8f22c55 100644
--- a/server/src/html/mod.rs
+++ b/server/src/html/mod.rs
@@ -15,7 +15,7 @@ use crate::{
     ranking::{
         connected_components_from_voted_pairs, ranked_items_subset, RankedItem, MAX_ITERS, TOL,
     },
-    reducer::NodeState,
+    reducer::{GlobalTree, NodeState},
     state::AppState,
     ui_action::UI_RPC_FIELD,
 };
@@ -182,8 +182,15 @@ fn display_label(id: &ItemId) -> String {
         .to_string()
 }
 
+fn child_label(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))
+}
+
 /// Plain (unscored) list of children that have no votes yet.
-fn unranked_list(label: &str, items: &[ItemId]) -> Markup {
+fn unranked_list(label: &str, items: &[ItemId], tree: &GlobalTree) -> Markup {
     html! {
         @if !items.is_empty() {
             h3 class="rank-heading muted small" { (label) }
@@ -191,7 +198,7 @@ fn unranked_list(label: &str, items: &[ItemId]) -> Markup {
                 @for it in items {
                     li {
                         a href=(item_href(it)) {
-                            strong { (display_label(it)) }
+                            strong { (child_label(tree, it)) }
                         }
                     }
                 }
@@ -200,7 +207,7 @@ fn unranked_list(label: &str, items: &[ItemId]) -> Markup {
     }
 }
 
-pub fn ranking_panel(item: &ItemId, node: &NodeState) -> Markup {
+pub fn ranking_panel(item: &ItemId, node: &NodeState, tree: &GlobalTree) -> Markup {
     let group = &node.local_ranking;
     let n = group.idx_to_item.len();
     let (comps, _isolates) =
@@ -248,7 +255,7 @@ pub fn ranking_panel(item: &ItemId, node: &NodeState) -> Markup {
                     @let label = if multi { format!("Ranking group {}", gi + 1) } else { "Ranking".to_string() };
                     (rank_list(&label, ranked, 1))
                 }
-                (unranked_list("Unranked", &unranked))
+                (unranked_list("Unranked", &unranked, tree))
             }
         }
     }
@@ -297,7 +304,7 @@ async fn item_page(state: AppState, uri: Uri, item: ItemId) -> Markup {
         (input_panel("", None))
         (breadcrumb_path(&item))
         (entity_section(&item, node, false))
-        (ranking_panel(&item, node))
+        (ranking_panel(&item, node, &tree))
     };
     layout("sorter2", body, views)
 }
diff --git a/server/src/reddit.rs b/server/src/reddit.rs
index a0eb688709478ee0185b953b41a5d26cc354764d..69d979bc7e4a1cb078f70114dc539bdc1986b574 100644
--- a/server/src/reddit.rs
+++ b/server/src/reddit.rs
@@ -300,9 +300,16 @@ async fn reddit_worker(
                     }
                     {
                         let mut tree = tree.write().await;
-                        apply_entity_import(&mut tree, &child_id, child_payload);
                         if kind == FetchKind::Children {
-                            tree.link_child(&fetch_id, &child_id);
+                            let view = entity_view_from_payload(&child_id, &child_payload);
+                            tree.apply_entity_under_parent(
+                                &fetch_id,
+                                &child_id,
+                                child_payload,
+                                view,
+                            );
+                        } else {
+                            apply_entity_import(&mut tree, &child_id, child_payload);
                         }
                     }
                     written += 1;
diff --git a/server/src/reducer.rs b/server/src/reducer.rs
index a36cd5c9287d61536f9f4a3f6b0df2342388857a..4e42d0369dab50bb2f8ca664aa69b628292f6c07 100644
--- a/server/src/reducer.rs
+++ b/server/src/reducer.rs
@@ -209,14 +209,24 @@ impl GlobalTree {
         }
     }
 
-    /// Directly attach `child` under `parent`, bypassing path-based nesting.
-    /// Used for imported listings (e.g. a subreddit's posts) so they show up
-    /// as children of the subreddit rather than a deep `…/comments/<id>` path.
-    pub fn link_child(&mut self, parent: &ItemId, child: &ItemId) {
+    /// Import entity data for `id` and attach it as a direct child of `parent`
+    /// without running [`Self::ensure_path`] on `id` (avoids Reddit `/comments/`
+    /// parent rules pulling intermediate path segments into the subreddit).
+    pub fn apply_entity_under_parent(
+        &mut self,
+        parent: &ItemId,
+        id: &ItemId,
+        payload: Value,
+        view: Option<EntityData>,
+    ) {
         self.ensure_path(parent);
-        self.ensure_path(child);
+        self.ensure_node(id);
+        if let Some(node) = self.nodes.get_mut(id) {
+            node.entity_raw = Some(payload);
+            node.data = view;
+        }
         if let Some(p) = self.nodes.get_mut(parent) {
-            p.children.insert(child.clone());
+            p.children.insert(id.clone());
         }
     }
 }
diff --git a/test/reddit_import.clj b/test/reddit_import.clj
index 84cbdcf7965e50290313cbce2243a16b583d2097..45a2a19f20799d77e84d8aa64735ab5e7e45f97c 100644
--- a/test/reddit_import.clj
+++ b/test/reddit_import.clj
@@ -67,6 +67,36 @@
           (do (Thread/sleep 200) (recur))
           false)))))
 
+(defn- run-reddit-fetch-assertions [app-base data-dir]
+  (let [browse-url (str app-base "/~/https://reddit.com/r/rust")
+        log-path (str data-dir "/events.jsonl")
+        before (:out (process/shell {:out :string :err :string}
+                                    "curl" "-sf" browse-url))]
+    (is (str/includes? before "Fetch from Reddit"))
+    (is (not (str/includes? before "The Rust Programming Language")))
+    (let [sse (curl-fetch-ui-sse app-base "reddit.com/r/rust" "self")]
+      (is (zero? (:exit sse)) "POST /ui fetch_entity (self) SSE succeeds")
+      (is (str/includes? (:out sse) "Idiomorph.morph"))
+      (is (str/includes? (:out sse) "The Rust Programming Language"))
+      (is (wait-event-log log-path 2000) "event log written"))
+    (let [after (:out (process/shell {:out :string :err :string}
+                                     "curl" "-sf" browse-url))
+          log (slurp (io/file log-path))]
+      (is (str/includes? after "The Rust Programming Language"))
+      (is (str/includes? log "\"type\":\"entity_imported\""))
+      (is (str/includes? log "\"subscribers\":350000"))
+      (is (str/includes? log "\"display_name\":\"rust\"")))
+    (let [children-sse (curl-fetch-ui-sse app-base "reddit.com/r/rust" "children")]
+      (is (zero? (:exit children-sse)) "POST /ui fetch_entity (children) SSE succeeds")
+      (is (str/includes? (:out children-sse) "Idiomorph.morph"))
+      (is (str/includes? (:out children-sse) "Announcing Rust 1.99")))
+    (let [after-children (:out (process/shell {:out :string :err :string}
+                                              "curl" "-sf" browse-url))
+          log2 (slurp (io/file log-path))]
+      (is (str/includes? after-children "Announcing Rust 1.99"))
+      (is (str/includes? after-children "Unranked"))
+      (is (str/includes? log2 "announcing_rust_199")))))
+
 (deftest reddit-fetch-via-mock-api
   (testing "Fetch more queues import; event log stores full payload; page shows title"
     (let [root (repo-root)
@@ -102,24 +132,7 @@
                                     bin)]
           (try
             (is (wait-health app-base 20000) "app healthz")
-            (let [browse-url (str app-base "/~/https://reddit.com/r/rust")
-                  before (:out (process/shell {:out :string :err :string}
-                                              "curl" "-sf" browse-url))]
-              (is (str/includes? before "Fetch from Reddit"))
-              (is (not (str/includes? before "The Rust Programming Language")))
-              (let [log-path (str data-dir "/events.jsonl")
-                    sse (curl-fetch-ui-sse app-base "reddit.com/r/rust")]
-                (is (zero? (:exit sse)) "POST /ui fetch_entity SSE succeeds")
-                (is (str/includes? (:out sse) "event: complete"))
-                (is (str/includes? (:out sse) "The Rust Programming Language"))
-                (is (wait-event-log log-path 2000) "event log written")
-                (let [after (:out (process/shell {:out :string :err :string}
-                                                 "curl" "-sf" browse-url))
-                      log (slurp (io/file log-path))]
-                  (is (str/includes? after "The Rust Programming Language"))
-                  (is (str/includes? log "\"type\":\"entity_imported\""))
-                  (is (str/includes? log "\"subscribers\":350000"))
-                  (is (str/includes? log "\"display_name\":\"rust\"")))))
+            (run-reddit-fetch-assertions app-base data-dir)
             (finally
               (process/destroy proc))))
         (finally
diff --git a/test/smoke.clj b/test/smoke.clj
index 11887c48282088e140d823a88ba616f6325835b3..ce9f958c84b9a89ae55e215ab519f1df6435e24b 100644
--- a/test/smoke.clj
+++ b/test/smoke.clj
@@ -49,7 +49,7 @@
           (is (wait-health base 15000) "server responds to /healthz")
           (let [home (:out (process/shell {:out :string :err :string}
                                          "curl" "-sf" (str base "/")))]
-            (is (str/includes? home "vote-panel"))
+            (is (str/includes? home "entity-section"))
             (is (str/includes? home "ranking-panel"))
             (is (str/includes? home "parser-panel"))
             (is (str/includes? home "__rpc__")))

download full diff B

Hardlinks — judgments / attempts / prompt

prompt download

judgments

attempts

Prompt text is loaded only by the download route.