constitution · epochs · watch · epoch 3

comparison

c_4772ee88dbe3 (tommy-mor) vs c_7a129e904906 (tommy-mor)

download prompt · raw event · cmp_3f80cea56c41d6

council reasoning

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

Side A is a reasonable internal refactor (async settlement worker, cache separation, removal of demo scaffolding) but touches a relatively contained area with modest complexity risk (e.g., worker batching without careful backpressure/error semantics). Side B ships substantial production infrastructure (Dockerfile, fly.toml, CI/CD deploy workflow), fixes real correctness issues (duplicate-ref commit hashing, single-contributor ranking shortcut, missing OPENROUTER_API_KEY guard), and adds a genuinely useful live-audit /watch UI with corresponding tests, representing broader lasting value to the deployed system.

~x-ai/grok-latest · winner B · 2:5 · permalink

B lands production authority (Fly Dockerfile/fly.toml, main-branch test-and-deploy CI), multi-repo/contributor roots, and a real auditable /watch+SSE/status pipeline with epoch-loop retry and ranking guards—core operational value. A’s lasting piece is the settlement worker plus cached read-path rankings and demo-counter removal, but that is a narrower sorter2 refactor versus making the constitution process deployable and observable.

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

Side A makes substantive architectural changes to the server: it removes the demo-only counter and related event type, introduces a settlement worker that batches vote persistence and ranking recomputation, adds cached ranking reads (`ranked_items_cached`) to avoid unnecessary recomputation, and switches UI paths from write locks to read locks for rendering. Side B adds valuable deployment infrastructure, a live audit dashboard, SSE status reporting, Docker/Fly configuration, and CI, but much of its patch is operational/UI surface rather than improving the project's core behavior, so A provides the stronger lasting technical foundation.

sides

A — c_4772ee88dbe3 (tommy-mor)

message

[07715165] nice

diff preview

diff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs
index c3c62a76f424010d77a6090c84dd0b82098f573e..da2536112faea313352624cf2ce0ddd0ab3377c1 100644
--- a/server/src/api/ui_html.rs
+++ b/server/src/api/ui_html.rs
@@ -6,7 +6,7 @@ use axum::{
 use std::collections::HashMap;
 
 use crate::{
-    html::{demo_counter_panel, js_string_literal, ranking_panel, JsBuilder},
+    html::{js_string_literal, ranking_panel, JsBuilder},
     parser::parse_reddit_url,
     parser_render::parser_panel_morph,
     state::AppState,
@@ -35,13 +35,6 @@ pub async fn post_ui_html(
     };
 
     match action {
-        HtmlUiAction::BumpDemoCounter => {
-            let count = state.bump_demo_counter().await;
-            let panel = demo_counter_panel(count, state.event_log.path().to_string_lossy().as_ref());
-            JsBuilder::new()
-                .morph_selector("#demo-counter-panel", panel)
-                .into_response()
-        }
         HtmlUiAction::RecordVote {
             a,
             b,
@@ -54,8 +47,8 @@ pub async fn post_ui_html(
             {
                 return ui_js_warn(&e).into_response();
             }
-            let mut group = state.group.write().await;
-            let panel = ranking_panel(&mut group);
+            let group = state.group.read().await;
+            let panel = ranking_panel(&group);
             JsBuilder::new()
                 .morph_selector("#ranking-panel", panel)
                 .into_response()
@@ -87,20 +80,6 @@ mod tests {
         assert!(matches!(err, HtmlUiParseError::MissingRpc));
     }
 
-    #[test]
-    fn bump_action_deserializes() {
-        let template = serde_json::json!({ "action": "bump_demo_counter" });
-        let mut form = HashMap::new();
-        form.insert(
-            UI_RPC_FIELD.to_string(),
-            serde_json::to_string(&template).unwrap(),
-        );
-        assert_eq!(
-            parse_html_ui_from_form(&form).unwrap(),
-            HtmlUiAction::BumpDemoCounter
-        );
-    }
-
     #[test]
     fn record_vote_action_deserializes() {
         let template = serde_json::json!({
diff --git a/server/src/events.rs b/server/src/events.rs
index b969242534e184d4f0a689543a479670b08a18df..eff80aef0257f706d2341f666e63d6a3d921bf6e 100644
--- a/server/src/events.rs
+++ b/server/src/events.rs
@@ -5,8 +5,6 @@ use serde::{Deserialize, Serialize};
 pub enum Event {
     /// Page view recorded (path → counter in views.json).
     ViewRecorded { path: String, ts: i64 },
-    /// Demo counter bump from `POST /ui` (persisted in the single JSONL log).
-    DemoCounterBumped { ts: i64, value: u64 },
     /// Pairwise comparison vote (replayed into [`crate::reducer::GroupState`] on boot).
     VoteRecorded {
         ts: i64,
diff --git a/server/src/html/mod.rs b/server/src/html/mod.rs
index 5b1d0b5a887d89e7e80796aa7a6c8ed5baaf2782..d69ed962b5c8625bc83c933b1825f2cc1d0868e2 100644
--- a/server/src/html/mod.rs
+++ b/server/src/html/mod.rs
@@ -13,7 +13,7 @@ use crate::{
     form_template::template_json_compact,
     parser_action::ParserAction,
     parser_render::parser_panel,
-    ranking::ranked_items,
+    ranking::ranked_items_cached,
     reducer::GroupState,
     state::AppState,
     ui_action::UI_RPC_FIELD,
@@ -199,10 +199,8 @@ fn layout(title: &str, body: Markup, views: u64, theme: &str, theme_next: &str)
     }
 }
 
-pub fn ranking_panel(group: &mut GroupState) -> Markup {
-    const MAX_ITERS: usize = 10_000;
-    const TOL: f64 = 1e-8;
-    let items = ranked_items(group, MAX_ITERS, TOL);
+pub fn ranking_panel(group: &GroupState) -> Markup {
+    let items = ranked_items_cached(group);
     html! {
         section id="ranking-panel" class="demo-panel" {
             h2 { "Ranking" }
@@ -260,35 +258,6 @@ pub fn vote_panel() -> Markup {
 }
 
 
-pub fn demo_counter_panel(count: u64, event_log_path: &str) -> Markup {
-    let rpc = template_json_compact(&serde_json::json!({ "action": "bump_demo_counter" }))
-        .expect("rpc json");
-    html! {
-        section id="demo-counter-panel" class="demo-panel" {
-            h1 { "sorter2" }
-            p class="muted" {
-                "Pairwise ranking scaffold — votes persist to JSONL and replay on boot."
-            }
-            p class="demo-count" {
-                strong { "Counter: " }
-                span id="demo-count-value" { (count) }
-            }
-            p class="muted small" {
-                "Event log: " code { (event_log_path) }
-            }
-            form method="post" action="/ui" id="demo-bump-form" {
-                input type="hidden" name=(UI_RPC_FIELD) value=(rpc);
-                button type="submit" class="btn-primary" { "Bump (POST /ui → eval JS)" }
-            }
-            p class="muted small" {
-                "Uses hidden "
-                code { "__rpc__" }
-                " JSON + Idiomorph morph — no full page reload."
-            }
-        }
-    }
-}
-
 pub async fn home(
     State(state): State<AppState>,
     jar: CookieJar,
@@ -297,16 +266,15 @@ pub async fn home(
     let path = uri.path().to_string();
     state.views.increment(path.clone());
     let views = state.views.get_views(&path);
-    let count = *state.demo_counter.read().await;
     let theme = theme_from_jar(&jar);
     let theme_next = theme_next_from_uri(&uri);
-    let mut group = state.group.write().await;
+    let group = state.group.read().await;
     let empty_action = ParserAction::suggest(String::new(), None);
     let body = html! {
+        h1 { "sorter2" }
         (parser_panel("", &empty_action))
         (vote_panel())
-        (ranking_panel(&mut group))
-        (demo_counter_panel(count, state.event_log.path().to_string_lossy().as_ref()))
+        (ranking_panel(&group))
     };
     layout("sorter2", body, views, theme, &theme_next)
 }
diff --git a/server/src/lib.rs b/server/src/lib.rs
index 6716c5b282e7980a7a0f03d63ad8b25eda61cc55..fa423640d598f4ba97a5885d228e78d7b97f7a22 100644
--- a/server/src/lib.rs
+++ b/server/src/lib.rs
@@ -9,6 +9,7 @@ pub mod parser_render;
 pub mod path_types;
 pub mod ranking;
 pub mod reducer;
+pub mod settlement;
 pub mod state;
 pub mod ui_action;
 pub mod views;
diff --git a/server/src/ranking.rs b/server/src/ranking.rs
index 89d3280126a8d8f841721ce8cb63ff735d68752a..2d706762792ba9239bb3f1c2e4974a2fde908013 100644
--- a/server/src/ranking.rs
+++ b/server/src/ranking.rs
@@ -91,6 +91,11 @@ pub fn compute_group_ranking(group: &mut GroupState, max_iters: usize, tol: f64)
 
 pub fn ranked_items(group: &mut GroupState, max_iters: usize, tol: f64) -> Vec<RankedItem> {
     compute_group_ranking(group, max_iters, tol);
+    ranked_items_cached(group)
+}
+
+/// Read cached scores without recomputing (HTTP fast path).
+pub fn ranked_items_cached(group: &GroupState) -> Vec<RankedItem> {
     let mut items: Vec<RankedItem> = group
         .idx_to_item
         .iter()
@@ -105,7 +110,12 @@ pub fn ranked_items(group: &mut GroupState, max_iters: usize, tol: f64) -> Vec<R
     items
 }
 
-fn compute_scores_from_edges(n: usize, edges: impl Iterator<Item = ((usize, usize), f64)>, max_iters: usize, tol: f64) -> Vec<f64> {
+pub fn compute_scores_from_edges(
+    n: usize,
+    edges: impl Iterator<Item = ((usize, usize), f64)>,
+    max_iters: usize,
+    tol: f64,
+) -> Vec<f64> {
     if n == 0 {
         return vec![];
     }
diff --git a/server/src/settlement.rs b/server/src/settlement.rs
new file mode 100644
index 0000000000000000000000000000000000000000..1f722ceaea62cda22c28ab71551f259fbf049b81
--- /dev/null
+++ b/server/src/settlement.rs
@@ -0,0 +1,114 @@
+use std::sync::Arc;
+
+use tokio::sync::{mpsc, oneshot, RwLock};
+
+use crate::{
+    event_log::EventLog,
+    events::Event,
+    ranking::compute_scores_from_edges,
+    reducer::{GroupState, VoteData},
+};
+
+const MAX_ITERS: usize = 10_000;
+const TOL: f64 = 1e-8;
+
+pub struct SettlementCommand {
+    pub vote: VoteData,
+    pub event: Event,
+    pub reply: oneshot::Sender<Result<(), String>>,
+}
+
+#[derive(Clone)]
+pub struct SettlementClient {
+    tx: mpsc::Sender<SettlementCommand>,
+}
+
+impl SettlementClient {
+    pub fn spawn(group: Arc<RwLock<GroupState>>, event_log: Arc<EventLog>) -> Self {
+        let (tx, rx) = mpsc::channel(64);
+        tokio::spawn(settlement_worker(rx, group, event_log));
+        Self { tx }
+    }
+
+    pub async fn record_vote(&self, vote: VoteData, event: Event) -> Result<(), String> {
+        let (reply, rx) = oneshot::channel();
+        self.tx
+            .send(SettlementCommand {
+                vote,
+                event,
+                reply,
+            })
+            .await
+            .map_err(|_| "settlement worker stopped".to_string())?;
+        rx.await
+            .map_err(|_| "settlement worker stopped".to_string())?
+    }
+}
+
+async fn settlement_worker(
+    mut rx: mpsc::Receiver<SettlementCommand>,
+    group: Arc<RwLock<GroupState>>,
+    event_log: Arc<EventLog>,
+) {
+    while let Some(first) = rx.recv().await {
+        let mut batch = vec![first];
+        while let Ok(more) = rx.try_recv() {
+            batch.push(more);
+        }
+
+        let mut disk_err: Option<String> = None;
+        for cmd in &batch {
+            if let Err(e) = event_log.append(&cmd.event).await {
+                disk_err = Some(e.to_string());
+                break;
+            }
+        }
+
+        if let Some(err) = disk_err {
+            for cmd in batch {
+                let _ = cmd.reply.send(Err(err.clone()));
+            }
+            continue;
+        }
+
+        let (edges, n) = {
+            let mut w = group.write().await;
+            for cmd in &batch {
+                w.apply_vote(cmd.vote.clone());
+            }
+            (w.edges.clone(), w.idx_to_item.len())
+        };
+
+        let new_scores = compute_scores_from_edges(
+            n,
+            edges.iter().map(|(&k, &v)| (k, v)),
+            MAX_ITERS,
+            TOL,
+        );
+
+        {
+            let mut w = group.write().await;
+            w.cached_scores = new_scores;
+            w.dirty = false;
+        }
+
+        for cmd in batch {
+            let _ = cmd.reply.send(Ok(()));
+        }
+    }
+}
+
+/// Compute ranking cache from current in-memory edges (startup replay only).
+pub fn warm_ranking_cache(group: &mut GroupState) {
+    if !group.dirty {
+        return;
+    }
+    let n = group.idx_to_item.len();
+    group.cached_scores = compute_scores_from_edges(
+        n,
+        group.edges.iter().map(|(&k, &v)| (k, v)),
+        MAX_ITERS,
+        TOL,
+    );
+    group.dirty = false;
+}
diff --git a/server/src/state.rs b/server/src/state.rs
index 8ec9902e2ecc31cf8208f7ad6365891dc5537eed..1922541a4064c2de1df2d993a461cae783320e05 100644
--- a/server/src/state.rs
+++ b/server/src/state.rs
@@ -6,6 +6,7 @@ use crate::{
     event_log::EventLog,
     events::Event,
     reducer::{GroupState, VoteData},
+    settlement::{warm_ranking_cache, SettlementClient},
     views::ViewStore,
 };
 
@@ -38,8 +39,8 @@ pub struct AppState {
     pub cfg: Arc<AppConfig>,
     pub event_log: Arc<EventLog>,
     pub views: ViewStore,
-    pub demo_counter: Arc<RwLock<u64>>,
     pub group: Arc<RwLock<GroupState>>,
+    settlement: SettlementClient,
 }
 
 impl AppState {
@@ -48,14 +49,10 @@ impl AppState {
         let views_path = format!("{}/views.json", cfg.data_dir);
         let views = ViewStore::new(&views_path);
 
-        let mut demo_counter: u64 = 0;
         let mut group = GroupState::new();
         if let Ok((events, _)) = event_log.load_all().await {
             for ev in events {
                 match ev {
-                    Event::DemoCounterBumped { value, .. } => {
-                        demo_counter = demo_counter.max(value);
-                    }
                     Event::VoteRecorded {
                         ts,
                         a,
@@ -74,30 +71,20 @@ impl AppState {
             }
         }
 
+       

… preview truncated; 6,096 characters omitted

download full diff A

B — c_7a129e904906 (tommy-mor)

message

[4e327784] deploy live constitution dashboard

Expose auditable progress and event streaming, configure the production roots and runtime, and make tested main-branch commits the deployment authority.

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

diff preview

diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000000000000000000000000000000000000..c9d63a722beba0a0297fc853089332c460ab78dd
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,7 @@
+.git
+.venv
+.hypothesis
+__pycache__
+tests
+*.json
+*.bsp
diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml
new file mode 100644
index 0000000000000000000000000000000000000000..76dcdf82d53177c1e47d86b23a54523239d232a6
--- /dev/null
+++ b/.github/workflows/deploy.yml
@@ -0,0 +1,49 @@
+name: Test and deploy
+
+on:
+  push:
+    branches: [main]
+
+concurrency:
+  group: production
+  cancel-in-progress: false
+
+permissions:
+  contents: read
+
+jobs:
+  test:
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v4
+
+      - uses: astral-sh/setup-uv@v6
+        with:
+          enable-cache: true
+
+      - name: Run Python tests
+        run: uv run pytest -q
+
+      - name: Install Babashka
+        run: |
+          curl -fsSL https://raw.githubusercontent.com/babashka/babashka/master/install \
+            | sudo bash -s -- --dir /usr/local/bin
+
+      - name: Run process integration tests
+        run: bb TEST.sh
+
+  deploy:
+    needs: test
+    runs-on: ubuntu-latest
+    environment:
+      name: production
+      url: https://token.slug.social
+    steps:
+      - uses: actions/checkout@v4
+
+      - uses: superfly/flyctl-actions/setup-flyctl@master
+
+      - name: Deploy to Fly
+        run: flyctl deploy --remote-only
+        env:
+          FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }}
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..c9a5c00782371c19ad5ab5c58cf6f5a8ffec0141
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,17 @@
+FROM ghcr.io/astral-sh/uv:python3.11-bookworm-slim
+
+RUN apt-get update \
+    && apt-get install -y --no-install-recommends git ca-certificates \
+    && rm -rf /var/lib/apt/lists/*
+
+WORKDIR /app
+COPY pyproject.toml uv.lock ./
+RUN uv sync --frozen --no-install-project
+
+COPY constitution.py ./
+
+ENV PATH="/app/.venv/bin:${PATH}" \
+    PYTHONUNBUFFERED="1"
+
+EXPOSE 8080
+CMD ["python", "constitution.py"]
diff --git a/constitution.py b/constitution.py
index 4bee9f83663ab7fb36db95129b92b64b4ef57258..a58257e1881b21d1d6fa8e68a3faa222e4f661ef 100644
--- a/constitution.py
+++ b/constitution.py
@@ -24,12 +24,12 @@ A daily GitHub Action backs up the JSONL ledger to the same repo.
 Run: uv run constitution.py
 """
 
-from decimal import Decimal, getcontext
+from decimal import Decimal, getcontext, DefaultContext
 from datetime import datetime, timezone
 from fastapi import FastAPI, Request, Response
 from fastapi.responses import PlainTextResponse, HTMLResponse
 from starlette.middleware.sessions import SessionMiddleware
-import json, time, os, asyncio, httpx, pathlib, subprocess, hashlib, re, fcntl
+import json, time, os, asyncio, httpx, pathlib, subprocess, hashlib, re, fcntl, base64
 import sympy as sp  # type: ignore[reportMissingImports]
 from tenacity import retry, retry_if_exception, stop_after_attempt, wait_exponential
 from evaleval import (
@@ -37,6 +37,7 @@ from evaleval import (
     exec_event, One, Two, Three, Selector, MORPH, PREPEND,
 )
 
+DefaultContext.prec = 50
 getcontext().prec = 50
 
 app = FastAPI()
@@ -129,14 +130,47 @@ OPENROUTER_BASE_URL = os.environ.get("OPENROUTER_BASE_URL", "https://openrouter.
 # using the exact same source; their normalized values are committed to every
 # discovery event.
 DEFAULT_REPOSITORIES = [
+    {
+        "id": "constitution",
+        "url": "https://github.com/sortersocial/constitution.git",
+        "refs": ["refs/heads/**"],
+    },
     {
         "id": "slug",
-        "url": "https://github.com/tommy-mor/slug.git",
+        "url": "https://github.com/sortersocial/slug.git",
+        "refs": ["refs/heads/**"],
+    },
+    {
+        "id": "sorter",
+        "url": "https://github.com/sorterisntonline/sorter.git",
+        "refs": ["refs/heads/**"],
+    },
+    {
+        "id": "sorter2",
+        "url": "https://github.com/sortersocial/sorter2.git",
+        "refs": ["refs/heads/**"],
+    },
+    {
+        "id": "sorter-oldest",
+        "url": "https://github.com/tommy-mor/sorter.git",
         "refs": ["refs/heads/**"],
     },
 ]
 DEFAULT_CONTRIBUTORS = {
     "tommy-mor": ["thmorriss@gmail.com"],
+    "christopher-whitman": [
+        "chris@cwwhitman.com",
+        "7566903+cwwhitman@users.noreply.github.com",
+    ],
+    "jake-chvatal": [
+        "jake+github@uln.industries",
+        "jakechvatal@gmail.com",
+        "jake@isnt.online",
+    ],
+    "lara": ["me@lara.lv"],
+    "nat-reid": ["nathanielreid@gmail.com"],
+    "zod": ["jason.p.mcel@gmail.com", "me@zod.tf"],
+    "jovan": ["jovan@slug.social", "jovan@getcivicai.com"],
 }
 
 REPOSITORIES = json.loads(
@@ -147,6 +181,7 @@ CONTRIBUTORS = json.loads(
 )
 GIT_MIRROR_DIR = pathlib.Path(os.environ.get("GIT_MIRROR_DIR", "/data/git"))
 GIT_TIMEOUT_SECONDS = int(os.environ.get("GIT_TIMEOUT_SECONDS", "120"))
+GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN", "")
 
 # Council model IDs: slug.social garden rank under this parent (bodies = OpenRouter URLs), then top-up from OpenRouter list.
 SLUG_SOCIAL_BASE_URL = os.environ.get("SLUG_SOCIAL_BASE_URL", "https://slug.social").rstrip("/")
@@ -661,20 +696,30 @@ def _git(repo: pathlib.Path | None, *args: str, input_bytes: bytes | None = None
     if repo is not None:
         command += ["-C", str(repo)]
     command += list(args)
+    git_env = {
+        **os.environ,
+        "GIT_CONFIG_NOSYSTEM": "1",
+        "GIT_CONFIG_GLOBAL": os.devnull,
+        "GIT_NO_REPLACE_OBJECTS": "1",
+        "LC_ALL": "C",
+        "TZ": "UTC",
+    }
+    if GITHUB_TOKEN:
+        credential = base64.b64encode(
+            f"x-access-token:{GITHUB_TOKEN}".encode()
+        ).decode()
+        git_env.update({
+            "GIT_CONFIG_COUNT": "1",
+            "GIT_CONFIG_KEY_0": "http.https://github.com/.extraHeader",
+            "GIT_CONFIG_VALUE_0": f"Authorization: Basic {credential}",
+        })
     try:
         result = subprocess.run(
             command,
             input=input_bytes,
             stdout=subprocess.PIPE,
             stderr=subprocess.PIPE,
-            env={
-                **os.environ,
-                "GIT_CONFIG_NOSYSTEM": "1",
-                "GIT_CONFIG_GLOBAL": os.devnull,
-                "GIT_NO_REPLACE_OBJECTS": "1",
-                "LC_ALL": "C",
-                "TZ": "UTC",
-            },
+            env=git_env,
             timeout=GIT_TIMEOUT_SECONDS,
             check=False,
         )
@@ -844,9 +889,15 @@ def _build_discovery(epoch_n: int, boundary_ms: int, events: list) -> GitDiscove
         canonical_location = min(
             locations[qualified_oid], key=lambda x: (x[0], x[1])
         )
+        # One commit may be reachable from dozens of refs in the same mirror.
+        # Verify its object once per repository, not once per source ref.
+        object_locations = {
+            (str(m), raw_oid): (m, raw_oid)
+            for _, _, m, raw_oid in locations[qualified_oid]
+        }
         object_hashes = {
             hashlib.sha256(_git(m, "cat-file", "commit", raw_oid)).hexdigest()
-            for _, _, m, raw_oid in locations[qualified_oid]
+            for m, raw_oid in object_locations.values()
         }
         if len(object_hashes) != 1:
             raise RuntimeError(f"conflicting Git objects share OID {qualified_oid}")
@@ -994,11 +1045,55 @@ async def discover_repositories(epoch_n: int, boundary_ms: int) -> GitDiscovery:
 
 
 SSE_CLIENTS = []
+AUDIT_HISTORY = []
+AUDIT_SEQUENCE = 0
+PROCESS_STATE = {
+    "running": False,
+    "phase": "idle",
+    "progress": 100,
+    "message": "Waiting for the next epoch",
+}
+
+
+def _sse_event(event_name: str, payload: dict) -> str:
+    return (
+        f"event: {event_name}\n"
+        f"data: {json.dumps(payload, separators=(',', ':'))}\n\n"
+    )
+
+
+async def broadcast_audit(
+    kind: str,
+    message: str,
+    *,
+    progress: int | None = None,
+    phase: str | None = None,
+) -> dict:
+    global AUDIT_SEQUENCE
+    AUDIT_SEQUENCE += 1
+    if progress is not None:
+        PROCESS_STATE["progress"] = max(0, min(100, int(progress)))
+    if phase is not None:
+        PROCESS_STATE["phase"] = phase
+    PROCESS_STATE["message"] = message
+    payload = {
+        "id": AUDIT_SEQUENCE,
+        "timestamp_ms": int(time.time() * 1000),
+        "kind": kind,
+        "message": message,
+        **PROCESS_STATE,
+    }
+    AUDIT_HISTORY.append(payload)
+    del AUDIT_HISTORY[:-200]
+    wire = _sse_event("audit", payload)
+    for queue in list(SSE_CLIENTS):
+        await queue.put(wire)
+    return payload
 
 
 async def broadcast_js(js: str):
     """Send a JS snippet to all connected SSE clients."""
-    for queue in SSE_CLIENTS:
+    for queue in list(SSE_CLIENTS):
         await queue.put(js)
 
 
@@ -1006,10 +1101,29 @@ async def rank_commits(commits: list[dict]):
     if not commits:
         return {}, []
 
-    models = await fetch_top_models(n=3)
     contributors = sorted(set(c["contributor"] for c in commits))
-    if len(contributors) > 1 and not models:
+    if len(contributors) == 1:
+        await broadcast_audit(
+            "ranking",
+            f"Only {contributors[0]} is eligible; rank is 1.0",
+            progress=90,
+            phase="finalizing",
+        )
+        return {contributors[0]: Decimal("1")}, []
+    if not (OPENROUTER_API_KEY or "").strip():
+        raise RuntimeError(
+            "OPENROUTER_API_KEY is required when multiple contributors need ranking"
+        )
+
+    models = await fetch_top_models(n=3)
+    if not models:
         raise RuntimeError("no council models available for contributor ranking")
+    await broadcast_audit(
+        "council",
+        f"Council selected: {', '.join(models)}",
+        progress=35,
+        phase="ranking",
+    )
     await broadcast_js(exec_event(Three[Selector("#emission-log")][PREPEND][
         ["div.log-council", f"Council: {', '.join(models)} — {len(commits)} commits"]
     ]))
@@ -1035,6 +1149,11 @@ async def rank_commits(commits: list[dict]):
 
     async def compare_fn(i, j):
         a1, a2 = authors[i], authors[j]
+        await broadcast_audit(
+            "comparison",
+            f"Comparing {a1} with {a2}",
+            phase="ranking",
+        )
         await broadcast_js(exec_event(Three[Selector("#emission-status")][MORPH][
             ["div#emission-status", f"Comparing {a1} vs {a2}…"]
         ]))
@@ -1050,6 +1169,11 @@ async def rank_commits(commits: list[dict]):
                 if winner_weight <= 0 or loser_weight <= 0:
                     raise ValueError("ratio weights must be positive")
                 results.append((w, l, winner_weight, loser_weight))
+                await broadcast_audit(
+                    "vote",
+                    f"{model}: {authors[w]} over {authors[l]} ({result['ratio']})",
+                    phase="ranking",
+                )
                 await broadcast_js(exec_event(Three[Selector("#emission-log")][PREPEND][
                     ["div.log-vote",
                         ["span.model", model], " — ",
@@ -1059,6 +1183,11 @@ async def rank_commits(commits: list[dict]):
                     ]
                 ]))
             except Exception as e:
+                await broadcast_audit(
+                    "error",
+                    f"{model} failed: {e}",
+                    phase="error",
+                )
                 await broadcast_js(exec_event(Three[Selector("#emission-log")][PREPEND][
                     ["div.log-error", f"⚠ {model}: {e}"]
                 ]))
@@ -1068,8 +1197,13 @@ async def rank_commits(commits: list[dict]):
     async def progress_fn(ev):
         if ev["phase"] == "spanning_tree":
             label = f"Spanning tree: {ev['step']}/{ev['total']}"
+    

… preview truncated; 28,089 characters omitted

download full diff B

Hardlinks — judgments / attempts / prompt

prompt download

judgments

attempts

Prompt text is loaded only by the download route.