{"messages":[{"content":"You are a constitutional council ranking individual git commits for ownership allocation.\n\nCompare these two commits. Decide which contributed more lasting value to the project.\n\nJudge substance, not spectacle:\n- Prefer correct, lasting design and real bugfixes over churn, formatting, renames, or generated noise.\n- Prefer clarity and necessity over sheer line count. A small precise change can beat a large diffuse one.\n- Do not favor a side merely because its patch is longer or noisier.\n- Weight what the change does for the project, not the contributor's name.\n\nReturn ONLY a JSON object: {\"winner\": \"A\" or \"B\", \"ratio\": \"N:M\", \"explanation\": \"...\"}\nThe explanation must cite concrete differences in the patches (1-3 sentences).\n\nSide A — contributor: tommy-mor\nSide A — commit message:\n[9e20d06c] Add sorterc dev tool for offline DSL compile and JSONL lint.\n\nIntroduce a workspace-only binary that validates .sorter files into ranking JSON and scans events.jsonl for corrupt or unreplayable ingests.\n\nCo-authored-by: Cursor \n\nSide A — unified diff (full patch):\ndiff --git a/Cargo.lock b/Cargo.lock\nindex bf8153d9c723af97122c9ffdd4a7cfe82e853bb6..a07734f089b466440c3ae6fc1087ce85fc24ce62 100644\n--- a/Cargo.lock\n+++ b/Cargo.lock\n@@ -1826,6 +1826,17 @@ dependencies = [\n \"windows-sys 0.60.2\",\n ]\n \n+[[package]]\n+name = \"sorterc\"\n+version = \"0.0.1\"\n+dependencies = [\n+ \"anyhow\",\n+ \"clap\",\n+ \"serde\",\n+ \"serde_json\",\n+ \"slugsocial-server\",\n+]\n+\n [[package]]\n name = \"spin\"\n version = \"0.9.8\"\ndiff --git a/Cargo.toml b/Cargo.toml\nindex 149cbf07901eab57c593184ff8719a75d530f1da..25337acdd61e44b20f354c78fed4a88caf896280 100644\n--- a/Cargo.toml\n+++ b/Cargo.toml\n@@ -1,5 +1,5 @@\n [workspace]\n-members = [\"server\", \"cli\"]\n+members = [\"server\", \"cli\", \"sorterc\"]\n resolver = \"2\"\n \n \ndiff --git a/agents.md b/agents.md\nindex d8b801e454fdf37e7ac6038b91a69f83b0746d59..ce646ed3cd7123be4732dccec4a6800467e651e7 100644\n--- a/agents.md\n+++ b/agents.md\n@@ -93,6 +93,17 @@ SLUG_GOOGLE_CLIENT_SECRET=mock\n \n After OAuth completes, the pending-session poll returns a `slug_…` bearer token for API calls.\n \n+### Dev-only offline tooling\n+\n+**`sorterc`** — workspace binary, not published via npm. Compiles `.sorter` files and lints `events.jsonl` without a server:\n+\n+```\n+cargo run -p sorterc -- compile path/to/doc.sorter [--base events.jsonl] [--room public] [--pretty]\n+cargo run -p sorterc -- scan path/to/events.jsonl [--pretty]\n+```\n+\n+`compile` validates DSL, simulates ingest against empty (or `--base`) reducer state, and prints JSON rankings. `scan` reports corrupt JSONL lines and ingests that fail DSL replay.\n+\n ### Testing\n \n - **Rust tests:** `cargo nextest run --workspace` (163 tests; requires `cargo-nextest`)\ndiff --git a/server/src/lib.rs b/server/src/lib.rs\nindex c1d477d21aea03aff00e6f0689b0b4379d0d68d2..ad8e31099c807fb5844acb16cd5086a2f19327a7 100644\n--- a/server/src/lib.rs\n+++ b/server/src/lib.rs\n@@ -10,6 +10,7 @@ pub mod form_template;\n pub mod html;\n pub mod identity;\n pub mod middleware;\n+pub mod offline;\n pub mod path_types;\n pub mod ranking;\n pub mod reducer;\ndiff --git a/server/src/offline.rs b/server/src/offline.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..54ad0ded096a305ef8454ab2cdd1c3af71b14f5d\n--- /dev/null\n+++ b/server/src/offline.rs\n@@ -0,0 +1,333 @@\n+//! Offline `.sorter` compilation and JSONL diagnostics (no network, no auth).\n+\n+use std::collections::HashSet;\n+use std::path::Path;\n+\n+use serde::Serialize;\n+use slug_types::{CheckScopeRanking, RankComponent, RankRow, paths::GardenItemUrl};\n+\n+use crate::{\n+ api::{resolve_item, validate_ingest_document},\n+ dsl,\n+ events::{Event, Ingest},\n+ path_types::ItemId,\n+ reducer::{ReducerState, ScopeId, scope_from_room_wire},\n+ scope_rank::build_children_rankings,\n+};\n+\n+#[derive(Debug, Clone, Serialize)]\n+pub struct CompileStats {\n+ pub items: usize,\n+ pub votes: usize,\n+ pub prose_blocks: usize,\n+}\n+\n+#[derive(Debug, Serialize)]\n+pub struct CompileResult {\n+ pub ok: bool,\n+ pub threads: Vec,\n+ pub rankings: Vec,\n+ pub stats: CompileStats,\n+}\n+\n+#[derive(Debug, Clone, Serialize)]\n+pub struct CompileError {\n+ pub ok: bool,\n+ pub error: String,\n+ #[serde(skip_serializing_if = \"Option::is_none\")]\n+ pub hint: Option,\n+}\n+\n+#[derive(Debug, Clone, Serialize)]\n+pub struct BadJsonLine {\n+ pub line: usize,\n+ pub message: String,\n+}\n+\n+#[derive(Debug, Clone, Serialize)]\n+pub struct MalformedIngest {\n+ pub line: usize,\n+ pub id: String,\n+ pub room_id: String,\n+ pub thread_tag: String,\n+ pub reason: String,\n+}\n+\n+#[derive(Debug, Clone, Serialize)]\n+pub struct ScanResult {\n+ pub ok: bool,\n+ pub path: String,\n+ pub total_lines: usize,\n+ pub parsed_events: usize,\n+ pub bad_json_lines: Vec,\n+ pub malformed_ingests: Vec,\n+ pub skipped_ingests: usize,\n+}\n+\n+fn document_stats(doc: &dsl::Document) -> CompileStats {\n+ let mut items = 0usize;\n+ let mut votes = 0usize;\n+ let mut prose_blocks = 0usize;\n+ for stmt in &doc.statements {\n+ match stmt {\n+ dsl::Stmt::Item { .. } => items += 1,\n+ dsl::Stmt::Vote { .. } => votes += 1,\n+ dsl::Stmt::Prose { .. } => prose_blocks += 1,\n+ }\n+ }\n+ CompileStats {\n+ items,\n+ votes,\n+ prose_blocks,\n+ }\n+}\n+\n+fn threads_in_document(text: &str) -> Vec {\n+ let mut out = HashSet::new();\n+ for line in text.lines() {\n+ let trimmed = line.trim();\n+ if !trimmed.starts_with('#') {\n+ continue;\n+ }\n+ let rest = trimmed.trim_start_matches('#').trim();\n+ if rest.is_empty() {\n+ continue;\n+ }\n+ let tag = rest.split_whitespace().next().unwrap_or(rest);\n+ let tag = tag.split(':').next().unwrap_or(tag).trim();\n+ if tag.is_empty() {\n+ continue;\n+ }\n+ out.insert(format!(\"#{}\", crate::canonical_path::canonicalize_tag(tag)));\n+ }\n+ let mut tags: Vec = out.into_iter().collect();\n+ tags.sort();\n+ tags\n+}\n+\n+fn voted_parent_scopes(doc: &dsl::Document) -> Vec {\n+ let mut parents = HashSet::new();\n+ for stmt in &doc.statements {\n+ if let dsl::Stmt::Vote { item1, item2, .. } = stmt {\n+ if let (Ok(a), Ok(b)) = (resolve_item(item1), resolve_item(item2)) {\n+ if let Some(p) = a.parent() {\n+ parents.insert(p);\n+ }\n+ if let Some(p) = b.parent() {\n+ parents.insert(p);\n+ }\n+ }\n+ }\n+ }\n+ let mut out: Vec = parents.into_iter().collect();\n+ out.sort();\n+ out\n+}\n+\n+fn rankings_for_simulated(\n+ simulated: &ReducerState,\n+ scope: &ScopeId,\n+ room_wire: &str,\n+ doc: &dsl::Document,\n+) -> Vec {\n+ voted_parent_scopes(doc)\n+ .iter()\n+ .map(|parent| {\n+ let scoped_content = simulated\n+ .content_for_scope(&scope)\n+ .unwrap_or_else(|| simulated.public());\n+ let scoped = build_children_rankings(scoped_content, parent);\n+ let components: Vec = scoped\n+ .component_rankings\n+ .into_iter()\n+ .map(|comp| RankComponent {\n+ pairs: comp.pairs,\n+ ranking: comp\n+ .ranked\n+ .into_iter()\n+ .map(|r| RankRow {\n+ item: GardenItemUrl::from_stored(&r.item, room_wire),\n+ score: r.score,\n+ percent: None,\n+ })\n+ .collect(),\n+ })\n+ .collect();\n+ CheckScopeRanking {\n+ parent: GardenItemUrl::from_stored(parent, room_wire).into_inner(),\n+ components,\n+ unranked_items: scoped\n+ .unranked_items\n+ .into_iter()\n+ .map(|it| GardenItemUrl::from_stored(&it, room_wire))\n+ .collect(),\n+ }\n+ })\n+ .collect()\n+}\n+\n+/// Validate and simulate one `.sorter` document against optional base reducer state.\n+pub fn compile_document(\n+ base: &ReducerState,\n+ room: &str,\n+ text: &str,\n+) -> Result {\n+ let room_key = room.trim();\n+ let scope = scope_from_room_wire(room_key);\n+ let validated = validate_ingest_document(base, text, &scope).map_err(|(_, message, hint)| {\n+ CompileError {\n+ ok: false,\n+ error: message,\n+ hint,\n+ }\n+ })?;\n+\n+ let event = Event::Ingest(Ingest {\n+ ts: validated.ts,\n+ id: uuid::Uuid::new_v4().to_string(),\n+ raw: validated.raw_text.clone(),\n+ principal: \"offline\".to_string(),\n+ delegate: None,\n+ room_id: room_key.to_string(),\n+ thread_tag: \"offline\".to_string(),\n+ });\n+\n+ let mut simulated = base.clone();\n+ simulated.apply_event(event);\n+\n+ Ok(CompileResult {\n+ ok: true,\n+ threads: threads_in_document(text),\n+ rankings: rankings_for_simulated(&simulated, &scope, room_key, &validated.doc),\n+ stats: document_stats(&validated.doc),\n+ })\n+}\n+\n+fn ingest_parse_error(raw: &str) -> Option {\n+ dsl::parse_full(raw).err().map(|e| e.to_string())\n+}\n+\n+fn load_events_from_jsonl(path: &Path) -> Result<(Vec<(usize, Event)>, Vec), std::io::Error> {\n+ let text = std::fs::read_to_string(path)?;\n+ let mut events = Vec::new();\n+ let mut bad_json_lines = Vec::new();\n+ for (idx, line) in text.lines().enumerate() {\n+ let line_no = idx + 1;\n+ let trimmed = line.trim();\n+ if trimmed.is_empty() {\n+ continue;\n+ }\n+ match serde_json::from_str::(trimmed) {\n+ Ok(ev) => events.push((line_no, ev)),\n+ Err(e) => bad_json_lines.push(BadJsonLine {\n+ line: line_no,\n+ message: e.to_string(),\n+ }),\n+ }\n+ }\n+ Ok((events, bad_json_lines))\n+}\n+\n+/// Replay a JSONL event log into reducer state (same rules as server boot).\n+pub fn load_reducer_from_jsonl(path: &Path) -> Result<(ReducerState, Vec), std::io::Error> {\n+ let (events, bad_json_lines) = load_events_from_jsonl(path)?;\n+ let mut state = ReducerState::default();\n+ for (_line_no, ev) in events {\n+ state.apply_event(ev);\n+ }\n+ Ok((state, bad_json_lines))\n+}\n+\n+/// Scan an events.jsonl for corrupt JSON lines and ingests that fail DSL replay.\n+pub fn scan_jsonl(path: &Path) -> Result {\n+ let text = std::fs::read_to_string(path)?;\n+ let total_lines = text.lines().count();\n+ let (events, bad_json_lines) = load_events_from_jsonl(path)?;\n+\n+ let mut malformed_ingests = Vec::new();\n+ let mut skipped_ingests = 0usize;\n+ let mut state = ReducerState::default();\n+ let parsed_events = events.len();\n+\n+ for (line_no, ev) in events {\n+ if let Event::Ingest(ref ing) = ev {\n+ if let Some(reason) = ingest_parse_error(&ing.raw) {\n+ malformed_ingests.push(MalformedIngest {\n+ line: line_no,\n+ id: ing.id.clone(),\n+ room_id: ing.room_id.clone(),\n+ thread_tag: ing.thread_tag.clone(),\n+ reason,\n+ });\n+ }\n+ let before = state.ingests_by_id.len();\n+ state.apply_event(ev);\n+ if state.ingests_by_id.len() == before {\n+ skipped_ingests += 1;\n+ }\n+ } else {\n+ state.apply_event(ev);\n+ }\n+ }\n+\n+ let ok = bad_json_lines.is_empty() && malformed_ingests.is_empty() && skipped_ingests == 0;\n+\n+ Ok(ScanResult {\n+ ok,\n+ path: path.display().to_string(),\n+ total_lines,\n+ parsed_events,\n+ bad_json_lines,\n+ malformed_ingests,\n+ skipped_ingests,\n+ })\n+}\n+\n+#[cfg(test)]\n+mod tests {\n+ use super::*;\n+\n+ const TUTORIAL: &str = include_str!(\"../tests/fixtures/tutorial.sorter\");\n+\n+ #[test]\n+ fn compile_tutorial_fixture_emits_rankings() {\n+ let result = compile_document(&ReducerState::default(), \"public\", TUTORIAL).unwrap();\n+ assert!(result.ok);\n+ assert!(!result.threads.is_empty());\n+ assert!(result.stats.items >= 6);\n+ assert!(result.stats.votes >= 6);\n+ assert!(!result.rankings.is_empty());\n+ }\n+\n+ #[test]\n+ fn compile_rejects_vote_on_missing_item() {\n+ let err = compile_document(\n+ &ReducerState::default(),\n+ \"public\",\n+ \"{ reason }\\n~/missing/a 2:1 ~/missing/b\",\n+ )\n+ .unwrap_err();\n+ assert!(!err.ok);\n+ assert!(err.error.contains(\"undefined\"));\n+ }\n+\n+ #[test]\n+ fn scan_empty_jsonl_is_ok() {\n+ let dir = tempfile::tempdir().unwrap();\n+ let path = dir.path().join(\"events.jsonl\");\n+ std::fs::write(&path, \"\").unwrap();\n+ let report = scan_jsonl(&path).unwrap();\n+ assert!(report.ok);\n+ assert!(report.bad_json_lines.is_empty());\n+ }\n+\n+ #[test]\n+ fn scan_reports_bad_json_line() {\n+ let dir = tempfile::tempdir().unwrap();\n+ let path = dir.path().join(\"events.jsonl\");\n+ std::fs::write(&path, \"{not json}\\n\").unwrap();\n+ let report = scan_jsonl(&path).unwrap();\n+ assert!(!report.ok);\n+ assert_eq!(report.bad_json_lines.len(), 1);\n+ }\n+}\ndiff --git a/sorterc/Cargo.toml b/sorterc/Cargo.toml\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..92d477aff9b53291fb1a266db83065c1c800791d\n--- /dev/null\n+++ b/sorterc/Cargo.toml\n@@ -0,0 +1,18 @@\n+[package]\n+name = \"sorterc\"\n+version = \"0.0.1\"\n+edition = \"2021\"\n+license = \"MIT\"\n+publish = false\n+description = \"Offline .sorter compiler and events.jsonl linter (dev only)\"\n+\n+[[bin]]\n+name = \"sorterc\"\n+path = \"src/main.rs\"\n+\n+[dependencies]\n+anyhow = \"1\"\n+clap = { version = \"4\", features = [\"derive\"] }\n+serde = { version = \"1\", features = [\"derive\"] }\n+serde_json = \"1\"\n+slugsocial-server = { path = \"../server\" }\ndiff --git a/sorterc/readme.md b/sorterc/readme.md\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..1ebcc3fc935541ea9e47e0458ec67a750fe19fff\n--- /dev/null\n+++ b/sorterc/readme.md\n@@ -0,0 +1,92 @@\n+# sorterc\n+\n+Dev-only offline tooling for the slug `.sorter` DSL and `events.jsonl` event log.\n+\n+`sorterc` is **not** published via npm and does not talk to slug.social. It reuses the same parser, validator, and ranking code as the server, but runs entirely on local files.\n+\n+## Build\n+\n+From the repo root:\n+\n+```bash\n+cargo build -p sorterc\n+cargo run -p sorterc -- --help\n+```\n+\n+## Commands\n+\n+### `compile` — evaluate a `.sorter` document\n+\n+Reads a `.sorter` file (or `-` for stdin), validates the DSL, simulates one ingest against reducer state, and prints JSON rankings to stdout.\n+\n+```bash\n+cargo run -p sorterc -- compile path/to/doc.sorter\n+cargo run -p sorterc -- compile path/to/doc.sorter --pretty\n+cargo run -p sorterc -- compile - --pretty # stdin\n+cargo run -p sorterc -- compile doc.sorter --base events.jsonl # seed garden from log\n+cargo run -p sorterc -- compile doc.sorter --room public # default room\n+```\n+\n+**Flags**\n+\n+| Flag | Description |\n+|------|-------------|\n+| `--base PATH` | Replay an `events.jsonl` first, then compile against that garden state |\n+| `--room ID` | Room wire id (`public` or private room id). Default: `public` |\n+| `--pretty` | Pretty-print JSON |\n+\n+**Success output** (shape):\n+\n+```json\n+{\n+ \"ok\": true,\n+ \"threads\": [\"#my-thread\"],\n+ \"rankings\": [ … ],\n+ \"stats\": { \"items\": 3, \"votes\": 2, \"prose_blocks\": 5 }\n+}\n+```\n+\n+Rankings use the same structure as the server's dry-run check: parent scope, connected components, scores, unranked items.\n+\n+**Error output** exits with code 1:\n+\n+```json\n+{\n+ \"ok\": false,\n+ \"error\": \"parse error\",\n+ \"hint\": \"…\"\n+}\n+```\n+\n+### `scan` — lint an `events.jsonl`\n+\n+Reads a JSONL event log and reports problems without starting a server.\n+\n+```bash\n+cargo run -p sorterc -- scan events.jsonl\n+cargo run -p sorterc -- scan events.jsonl --pretty\n+```\n+\n+Reports:\n+\n+- **bad JSON lines** — lines that are not valid JSON\n+- **malformed ingests** — ingest events whose `raw` DSL fails to parse\n+- **skipped ingests** — ingests dropped during replay (same behavior as server boot)\n+\n+Exits 0 when clean, 1 when any issue is found.\n+\n+## Typical uses\n+\n+- Iterate on `.sorter` files in an editor and pipe through `compile` to see rankings instantly\n+- Verify a downloaded or edited `events.jsonl` before uploading to Fly\n+- Debug \"malformed ingest\" warnings from production boot logs\n+- CI or pre-commit checks on fixture docs (no OAuth, no network)\n+\n+## What it does not do\n+\n+- Post to slug.social or append to a live log\n+- Authenticate users or bind agents\n+- Run browser/UI tests\n+- Replace `slugsocial public check` for operators who want the full RPC path against a running server\n+\n+For live server dry-run against current garden state, use `npx slugsocial public check` or `POST /try/check` in the browser.\ndiff --git a/sorterc/src/main.rs b/sorterc/src/main.rs\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..71382c180085cb0ad71043c852f8db5d3a48a284\n--- /dev/null\n+++ b/sorterc/src/main.rs\n@@ -0,0 +1,117 @@\n+use std::path::{Path, PathBuf};\n+\n+use anyhow::{bail, Context, Result};\n+use clap::{Parser, Subcommand};\n+use slugsocial_server::{\n+ offline::{self, CompileError, CompileResult, ScanResult},\n+ reducer::ReducerState,\n+};\n+\n+#[derive(Parser)]\n+#[command(\n+ name = \"sorterc\",\n+ about = \"Offline .sorter compiler and events.jsonl linter (dev only)\",\n+ version\n+)]\n+struct Cli {\n+ #[command(subcommand)]\n+ cmd: Command,\n+}\n+\n+#[derive(Subcommand)]\n+enum Command {\n+ /// Parse and simulate a .sorter document; emit ranking JSON to stdout.\n+ Compile {\n+ /// `.sorter` file, or `-` for stdin.\n+ file: PathBuf,\n+ /// Room wire id (`public` or private room id).\n+ #[arg(long, default_value = \"public\")]\n+ room: String,\n+ /// Optional events.jsonl to replay before compiling (seed garden state).\n+ #[arg(long)]\n+ base: Option,\n+ /// Pretty-print JSON.\n+ #[arg(long)]\n+ pretty: bool,\n+ },\n+ /// Scan an events.jsonl for corrupt JSON lines and malformed ingests.\n+ Scan {\n+ file: PathBuf,\n+ #[arg(long)]\n+ pretty: bool,\n+ },\n+}\n+\n+fn read_input(path: &Path) -> Result {\n+ if path.as_os_str() == \"-\" {\n+ use std::io::Read;\n+ let mut buf = String::new();\n+ std::io::stdin().read_to_string(&mut buf)?;\n+ Ok(buf)\n+ } else {\n+ std::fs::read_to_string(path)\n+ .with_context(|| format!(\"read {}\", path.display()))\n+ }\n+}\n+\n+fn load_base_state(base: Option<&Path>) -> Result {\n+ let Some(path) = base else {\n+ return Ok(ReducerState::default());\n+ };\n+ let (state, bad_lines) = offline::load_reducer_from_jsonl(path)\n+ .with_context(|| format!(\"load base jsonl {}\", path.display()))?;\n+ if !bad_lines.is_empty() {\n+ bail!(\n+ \"base jsonl has {} corrupt line(s); fix or omit --base\",\n+ bad_lines.len()\n+ );\n+ }\n+ Ok(state)\n+}\n+\n+fn print_json(value: &T, pretty: bool) -> Result<()> {\n+ if pretty {\n+ println!(\"{}\", serde_json::to_string_pretty(value)?);\n+ } else {\n+ println!(\"{}\", serde_json::to_string(value)?);\n+ }\n+ Ok(())\n+}\n+\n+fn run_compile(file: PathBuf, room: String, base: Option, pretty: bool) -> Result<()> {\n+ let text = read_input(&file)?;\n+ let base_state = load_base_state(base.as_deref())?;\n+ match offline::compile_document(&base_state, &room, &text) {\n+ Ok(result) => {\n+ print_json::(&result, pretty)?;\n+ Ok(())\n+ }\n+ Err(err) => {\n+ print_json::(&err, pretty)?;\n+ std::process::exit(1);\n+ }\n+ }\n+}\n+\n+fn run_scan(file: PathBuf, pretty: bool) -> Result<()> {\n+ let report = offline::scan_jsonl(&file)\n+ .with_context(|| format!(\"scan {}\", file.display()))?;\n+ print_json::(&report, pretty)?;\n+ if !report.ok {\n+ std::process::exit(1);\n+ }\n+ Ok(())\n+}\n+\n+fn main() -> Result<()> {\n+ let cli = Cli::parse();\n+ match cli.cmd {\n+ Command::Compile {\n+ file,\n+ room,\n+ base,\n+ pretty,\n+ } => run_compile(file, room, base, pretty),\n+ Command::Scan { file, pretty } => run_scan(file, pretty),\n+ }\n+}\n\n\nSide B — contributor: tommy-mor\nSide B — commit message:\n[6120bd96] fix redirect urls for custom hosts and deploy from staging\n\nUse HOSTNAME and window.location.origin instead of hardcoded staging.sorter.social, and trigger fly deploys on pushes to staging.\n\nCo-authored-by: Cursor \n\nSide B — unified diff (full patch):\ndiff --git a/.github/workflows/fly-deploy.yml b/.github/workflows/fly-deploy.yml\nindex 3e693915fe6f99a5c2221b2921bf8ebc305180fc..5e11e5c312f62bed34d8cc68bd4a5538f52476b9 100644\n--- a/.github/workflows/fly-deploy.yml\n+++ b/.github/workflows/fly-deploy.yml\n@@ -3,11 +3,11 @@ name: deploy to fly.io\n on:\n push:\n branches:\n- - main\n+ - staging\n workflow_dispatch:\n \n concurrency:\n- group: fly-deploy-main\n+ group: fly-deploy-staging\n cancel-in-progress: true\n \n jobs:\ndiff --git a/borter/src/app/linear.clj b/borter/src/app/linear.clj\nindex f77d8a974e0cf05f9c33233bb625bdb190d2007b..5ef0e34cf1d543826675c6facb66aec079b40561 100644\n--- a/borter/src/app/linear.clj\n+++ b/borter/src/app/linear.clj\n@@ -6,6 +6,7 @@\n [ring.util.response :as response]\n [app.database :as db]\n [app.permissions :as perms]\n+ [app.util :as util]\n [honey.sql.helpers :as h]\n [sluj.core :refer [sluj]]))\n \n@@ -13,9 +14,7 @@\n (def client-secret (System/getenv \"BORTER_LINEAR_CLIENT_SECRET\"))\n \n (defn get-hostname []\n- (case (.getCanonicalHostName (java.net.InetAddress/getLocalHost))\n- \"sorter.social\" \"https://sorter.social/api/linear/callback\"\n- \"http://localhost:3000/api/linear/callback\"))\n+ (str (util/get-base-url) \"/api/linear/callback\"))\n \n (defn code->token [code]\n (def code code)\ndiff --git a/borter/src/app/login.clj b/borter/src/app/login.clj\nindex 5d545db9bef7765ba8b3fe7d00261c8ce84e9e1a..86817f8e94bc174e5b108859cc0b342953ab7acb 100644\n--- a/borter/src/app/login.clj\n+++ b/borter/src/app/login.clj\n@@ -1,6 +1,7 @@\n (ns app.login\n (:require [crypto.password.bcrypt :as password]\n [app.database :as db]\n+ [app.util :as util]\n [honey.sql.helpers :as h]\n [hato.client :as hc]\n [clojure.data.json :as json]\n@@ -12,10 +13,7 @@\n (def environment (or (System/getenv \"ENVIRONMENT\") \"development\"))\n \n (defn get-base-url []\n- (case environment\n- \"production\" \"https://sorter.social\"\n- \"staging\" \"https://staging.sorter.social\"\n- \"development\" \"http://localhost:3000\")) ; fallback for development\n+ (util/get-base-url))\n \n (defn create-email-content\n \"Creates a standardized email structure with customizable content\"\ndiff --git a/borter/src/app/oauth.clj b/borter/src/app/oauth.clj\nindex 1166f2ee30c9e813840711c72d1ad8f1c62e1ffe..2cd0c62f1fe267f7f5f725a97bc3ba0d0889517f 100644\n--- a/borter/src/app/oauth.clj\n+++ b/borter/src/app/oauth.clj\n@@ -3,6 +3,7 @@\n [clojure.data.json :as json]\n [hato.client :as hc]\n [app.database :as db]\n+ [app.util :as util]\n [honey.sql.helpers :as h]\n [ring.util.codec :as codec])\n (:import [java.util Base64]))\n@@ -13,12 +14,7 @@\n encoded-bytes))\n \n (defn get-hostname []\n- (let [env (System/getenv \"ENVIRONMENT\")]\n- (println \"Current environment:\" env)\n- (case env\n- \"production\" \"https://sorter.social\"\n- \"staging\" \"https://staging.sorter.social\"\n- \"http://localhost:3000\")))\n+ (util/get-base-url))\n \n (defn get-origin-hostname [req]\n (let [origin (get-in req [:headers \"origin\"])\ndiff --git a/borter/src/app/spotify.clj b/borter/src/app/spotify.clj\nindex 3e11713119141812fa2707ec956fb7ed612ee69a..b38d734351a1d4f1e142d93d4435ffe7bd20c02d 100644\n--- a/borter/src/app/spotify.clj\n+++ b/borter/src/app/spotify.clj\n@@ -1,5 +1,6 @@\n (ns app.spotify\n (:require [app.oauth :as oauth]\n+ [app.util :as util]\n [hato.client :as hc]\n [clojure.data.json :as json]\n [ring.util.codec :as codec]\n@@ -47,10 +48,7 @@\n \n \n (defn get-hostname []\n- (case (System/getenv \"ENVIRONMENT\")\n- \"production\" \"https://sorter.social\"\n- \"staging\" \"https://staging.sorter.social\"\n- \"http://localhost:3000\"))\n+ (util/get-base-url))\n \n (defn create-spotify-tag\n \"Creates a tag for a Spotify entity (artist, album, track) if it doesn't exist\"\ndiff --git a/borter/src/app/twitter.clj b/borter/src/app/twitter.clj\nindex ef7b18fa1fcb82bb944b3035ffed44499181237f..b9a3fdccc15d13918a4d11d8c0443de94fd172b4 100644\n--- a/borter/src/app/twitter.clj\n+++ b/borter/src/app/twitter.clj\n@@ -1,6 +1,7 @@\n (ns app.twitter\n (:require [app.database :as db]\n [app.permissions :as perms]\n+ [app.util :as util]\n [honey.sql.helpers :as h]\n [hato.client :as hc]\n [clojure.data.json :as json]\n@@ -37,9 +38,7 @@\n (clojure.string/join \"&\" (map (fn [[k v]] (str (name k) \"=\" v)) params)))\n \n (defn get-hostname []\n- (case (.getCanonicalHostName (java.net.InetAddress/getLocalHost))\n- \"sorter.isnt.online\" \"https://sorter.isnt.online/api/twitter/callback\"\n- \"http://localhost:3000/api/twitter/callback\"))\n+ (str (util/get-base-url) \"/api/twitter/callback\"))\n \n (defn encode-b64 [s]\n (.encodeToString (java.util.Base64/getEncoder) (.getBytes s)))\ndiff --git a/borter/src/app/util.clj b/borter/src/app/util.clj\nindex 384a64306c84aa8288ec44cd5de57edc248a826d..6a8aa0875accb28dc81bf57e645e3961b0a3ace5 100644\n--- a/borter/src/app/util.clj\n+++ b/borter/src/app/util.clj\n@@ -2,6 +2,18 @@\n (:require [clojure.string :as string])\n (:import [java.net URLEncoder]))\n \n+(defn get-base-url\n+ \"Public site base URL for redirects and oauth callbacks.\"\n+ []\n+ (if-let [hostname (not-empty (System/getenv \"HOSTNAME\"))]\n+ (if (string/starts-with? hostname \"http\")\n+ (string/replace hostname #\"/$\" \"\")\n+ (str \"https://\" (string/replace hostname #\"/$\" \"\")))\n+ (case (or (System/getenv \"ENVIRONMENT\") \"development\")\n+ \"production\" \"https://sorter.social\"\n+ \"staging\" \"https://staging.sorter.social\"\n+ \"http://localhost:3000\")))\n+\n (defn urlencode-params [params]\n (clojure.string/join \"&\" (map (fn [[k v]] (str k \"=\" (URLEncoder/encode (str v) \"UTF-8\"))) params)))\n \ndiff --git a/borter/src/app/youtube.clj b/borter/src/app/youtube.clj\nindex 647ef7c6d4f2503a63a7c074d46dc815b2a23547..fc9a2f5ed516692f19e06b4c0221f510547cf8c0 100644\n--- a/borter/src/app/youtube.clj\n+++ b/borter/src/app/youtube.clj\n@@ -6,6 +6,7 @@\n [ring.util.response :as response]\n [app.database :as db]\n [app.permissions :as perms]\n+ [app.util :as util]\n [honey.sql.helpers :as h]\n [sluj.core :refer [sluj]]))\n \n@@ -32,9 +33,7 @@\n :body (json/read-str {:key-fn keyword})))\n \n (defn get-hostname []\n- (case (.getCanonicalHostName (java.net.InetAddress/getLocalHost))\n- \"localhost\" \"http://localhost:3000/api/youtube/callback\"\n- \"https://sorter.isnt.online/api/youtube/callback\"))\n+ (str (util/get-base-url) \"/api/youtube/callback\"))\n \n \n \ndiff --git a/forter/src/utils/authUtils.js b/forter/src/utils/authUtils.js\nindex 145e5db7ad6f7a6439d68c63beb4d07d31b2de08..98ed7fa671f9887f44dc1479d85569951eb4773e 100644\n--- a/forter/src/utils/authUtils.js\n+++ b/forter/src/utils/authUtils.js\n@@ -5,8 +5,11 @@ import { current_session, fetchSession } from \"../session\";\n let lastSyncTime = 0;\n const SYNC_THROTTLE_MS = 5000; // Only sync once every 5 seconds\n \n-// Get base URL based on Vite's mode\n+// Get base URL based on current origin, with build-mode fallbacks for SSR/build\n const getBaseUrl = () => {\n+ if (typeof window !== 'undefined' && window.location?.origin) {\n+ return window.location.origin;\n+ }\n switch (import.meta.env.MODE) {\n case 'production':\n return 'https://sorter.social';\n","role":"user"}],"model":"openai/gpt-chat-latest"}