B ships production deployment infrastructure (Dockerfile, fly.toml, CI workflow) plus real correctness fixes (git credential injection for private mirrors, object-hash dedup by location instead of by ref, requiring OPENROUTER_API_KEY only when contested, safer SSE client removal) and a functional live-audit dashboard with tests. A is a clean, well-tested URL canonicalization graph, but it's a narrower, self-contained feature versus B's broader operational and correctness improvements that let the whole system actually run and be observed in production.
constitution · epochs · watch · epoch 3
c_9bced108c8aa (tommy-mor) vs c_7a129e904906 (tommy-mor)
download prompt · raw event · cmp_1e16178b5a229f
council reasoning
A introduces a full semantic URL DFA (graph engine, builder with link validation, parsing/normalization, and dense behavioral tests) that is core lasting product design. B mainly ships production wiring (Docker/Fly/CI), multi-repo config, and an audit/watch SSE UI—valuable operationally but more scaffolding and presentation around an existing emission pipeline than new foundational logic.
Side A adds a substantial new URL canonicalization subsystem: a graph-based traversal engine with declarative graph builder, URL parsing/normalization, generic fallback logic, breadcrumbs, and extensive tests covering Reddit, YouTube, encoding, query stripping, and traversal behavior. Side B mainly adds deployment infrastructure, production configuration, a live monitoring UI/SSE audit stream, and some robustness improvements (e.g. GitHub token support and deduplicated object verification), which are valuable operational enhancements but less foundational to the project's core behavior than the new canonicalization engine.
sides
A — c_9bced108c8aa (tommy-mor)
message
[15e1037a] url stuff
diff preview
diff --git a/server/src/url_rules/graph.rs b/server/src/url_rules/graph.rs
new file mode 100644
index 0000000000000000000000000000000000000000..f7ac0f9a551a1727cb2f9294778c283b9885b147
--- /dev/null
+++ b/server/src/url_rules/graph.rs
@@ -0,0 +1,831 @@
+//! Semantic URL graph: DFA traversal on host + path, query in context, generic fallback.
+
+use std::collections::HashMap;
+use std::sync::OnceLock;
+
+use url::Url;
+
+use super::graph_builder::GraphBuilder;
+use super::parse::{normalize_match_host, strip_tracking_query, UrlParts};
+
+#[derive(Debug, Clone, Default)]
+pub struct Context {
+ pub vars: HashMap<String, String>,
+ pub query: HashMap<String, String>,
+}
+
+pub type CanonicalFn = fn(&Context) -> Option<String>;
+
+#[derive(Clone, Copy)]
+pub enum EdgePattern {
+ Literal(&'static str),
+ Variable(&'static str),
+ /// Absorb any trailing segment without leaving this node (e.g. post title slug).
+ AbsorbAny,
+ /// Absorb segment when `cond(seg)` (e.g. subreddit listing suffix).
+ AbsorbIf(fn(&str) -> bool),
+}
+
+pub struct Edge {
+ pub pattern: EdgePattern,
+ pub target: &'static str,
+}
+
+pub struct Node {
+ pub edges: Vec<Edge>,
+ pub canonical: CanonicalFn,
+ pub parent: Option<&'static str>,
+}
+
+impl Node {
+ pub(crate) fn empty() -> Self {
+ Self {
+ edges: Vec::new(),
+ canonical: |_| None,
+ parent: None,
+ }
+ }
+}
+
+pub struct Graph {
+ pub nodes: HashMap<&'static str, Node>,
+}
+
+static GRAPH: OnceLock<Graph> = OnceLock::new();
+
+pub fn graph() -> &'static Graph {
+ GRAPH.get_or_init(build_graph)
+}
+
+impl Graph {
+ pub fn resolve_canonical(&self, parts: &UrlParts) -> Option<String> {
+ let mut query = parts.query.clone();
+ strip_tracking_query(&mut query);
+ let mut ctx = Context {
+ vars: HashMap::new(),
+ query,
+ };
+
+ if let Some(node_id) = self.traverse(parts, &mut ctx) {
+ if let Some(canon) = (self.nodes.get(node_id)?.canonical)(&ctx) {
+ return Some(canon);
+ }
+ }
+ Some(generic_canonical(parts))
+ }
+
+ pub fn breadcrumbs(&self, parts: &UrlParts) -> Vec<String> {
+ let mut query = parts.query.clone();
+ strip_tracking_query(&mut query);
+ let mut ctx = Context {
+ vars: HashMap::new(),
+ query,
+ };
+
+ if let Some(mut node_id) = self.traverse(parts, &mut ctx) {
+ let mut paths = Vec::new();
+ loop {
+ let node = match self.nodes.get(node_id) {
+ Some(n) => n,
+ None => break,
+ };
+ if let Some(url) = (node.canonical)(&ctx) {
+ if paths.last() != Some(&url) {
+ paths.push(url);
+ }
+ }
+ match node.parent {
+ Some(p) => node_id = p,
+ None => break,
+ }
+ }
+ paths.reverse();
+ if !paths.is_empty() {
+ return paths;
+ }
+ }
+ generic_breadcrumbs(parts)
+ }
+
+ fn traverse(&self, parts: &UrlParts, ctx: &mut Context) -> Option<&'static str> {
+ let host = parts.match_host();
+ let mut node_id = match host.as_str() {
+ "reddit.com" => "reddit_root",
+ "youtube.com" => "youtube_root",
+ "youtu.be" => "youtu_be_entry",
+ _ => return None,
+ };
+
+ let segs: Vec<&str> = parts.path_segments.iter().map(String::as_str).collect();
+ let mut i = 0;
+ while i < segs.len() {
+ let seg = segs[i];
+ match self.follow_edge(node_id, seg, ctx) {
+ Ok(next) => {
+ node_id = next;
+ i += 1;
+ }
+ Err(()) => {
+ if self.try_absorb(node_id, seg) {
+ i += 1;
+ continue;
+ }
+ return None;
+ }
+ }
+ }
+ Some(node_id)
+ }
+
+ fn follow_edge(
+ &self,
+ node_id: &'static str,
+ seg: &str,
+ ctx: &mut Context,
+ ) -> Result<&'static str, ()> {
+ let node = self.nodes.get(node_id).ok_or(())?;
+ for edge in &node.edges {
+ match edge.pattern {
+ EdgePattern::Literal(lit) if lit == seg => return Ok(edge.target),
+ EdgePattern::Variable(name) => {
+ ctx.vars.insert(name.to_string(), seg.to_string());
+ return Ok(edge.target);
+ }
+ EdgePattern::AbsorbAny
+ | EdgePattern::AbsorbIf(_)
+ | EdgePattern::Literal(_)
+ | EdgePattern::Variable(_) => {}
+ }
+ }
+ Err(())
+ }
+
+ fn try_absorb(&self, node_id: &'static str, seg: &str) -> bool {
+ let node = match self.nodes.get(node_id) {
+ Some(n) => n,
+ None => return false,
+ };
+ for edge in &node.edges {
+ match edge.pattern {
+ EdgePattern::AbsorbAny => return true,
+ EdgePattern::AbsorbIf(cond) if cond(seg) => return true,
+ EdgePattern::AbsorbIf(_) | EdgePattern::Literal(_) | EdgePattern::Variable(_) => {}
+ }
+ }
+ false
+ }
+
+ /// Test hook: terminal graph node and captured context after traversal.
+ #[cfg(test)]
+ pub fn traverse_terminal(&self, parts: &UrlParts) -> Option<(&'static str, Context)> {
+ let mut query = parts.query.clone();
+ strip_tracking_query(&mut query);
+ let mut ctx = Context {
+ vars: HashMap::new(),
+ query,
+ };
+ let node = self.traverse(parts, &mut ctx)?;
+ Some((node, ctx))
+ }
+}
+
+fn is_reddit_listing_suffix(seg: &str) -> bool {
+ matches!(seg, "hot" | "top" | "new" | "rising" | "controversial")
+}
+
+/// Percent-encode a path or query fragment so `&`, `?`, etc. cannot break URL structure.
+fn enc(s: &str) -> String {
+ urlencoding::encode(s).into_owned()
+}
+
+// --- Canonical formatters ---
+
+fn canon_reddit_root(_: &Context) -> Option<String> {
+ Some("https://reddit.com".to_string())
+}
+
+fn canon_reddit_r_hub(_: &Context) -> Option<String> {
+ Some("https://reddit.com/r".to_string())
+}
+
+fn canon_reddit_subreddit(ctx: &Context) -> Option<String> {
+ let sub = ctx.vars.get("subreddit")?;
+ Some(format!(
+ "https://reddit.com/r/{}",
+ enc(&sub.to_ascii_lowercase())
+ ))
+}
+
+fn canon_reddit_post(ctx: &Context) -> Option<String> {
+ let sub = ctx.vars.get("subreddit")?.to_ascii_lowercase();
+ let id = ctx.vars.get("post_id")?;
+ Some(format!(
+ "https://reddit.com/r/{}/comments/{}",
+ enc(&sub),
+ enc(id)
+ ))
+}
+
+fn canon_youtube_root(_: &Context) -> Option<String> {
+ Some("https://youtube.com".to_string())
+}
+
+fn canon_youtube_watch(ctx: &Context) -> Option<String> {
+ let v = ctx
+ .query
+ .get("v")
+ .or_else(|| ctx.vars.get("video_id"))?;
+ Some(format!("https://youtube.com/watch?v={}", enc(v)))
+}
+
+fn canon_youtu_be(ctx: &Context) -> Option<String> {
+ let v = ctx.vars.get("vid_id")?;
+ Some(format!("https://youtube.com/watch?v={}", enc(v)))
+}
+
+pub fn build_graph() -> Graph {
+ GraphBuilder::new()
+ .node("reddit_root")
+ .canonical(canon_reddit_root)
+ .edge(EdgePattern::Literal("r"), "reddit_r_hub")
+ .node("reddit_r_hub")
+ .parent("reddit_root")
+ .canonical(canon_reddit_r_hub)
+ .edge(EdgePattern::Variable("subreddit"), "reddit_subreddit")
+ .node("reddit_subreddit")
+ .parent("reddit_r_hub")
+ .canonical(canon_reddit_subreddit)
+ .edge(
+ EdgePattern::AbsorbIf(is_reddit_listing_suffix),
+ "reddit_subreddit",
+ )
+ .edge(EdgePattern::Literal("comments"), "reddit_comments_gate")
+ .node("reddit_comments_gate")
+ .parent("reddit_subreddit")
+ .canonical(canon_reddit_subreddit)
+ .edge(EdgePattern::Variable("post_id"), "reddit_post")
+ .node("reddit_post")
+ .parent("reddit_subreddit")
+ .canonical(canon_reddit_post)
+ .edge(EdgePattern::AbsorbAny, "reddit_post")
+ .node("youtube_root")
+ .canonical(canon_youtube_root)
+ .edge(EdgePattern::Literal("watch"), "youtube_watch")
+ .edge(EdgePattern::Literal("shorts"), "youtube_shorts_gate")
+ .node("youtube_watch")
+ .parent("youtube_root")
+ .canonical(canon_youtube_watch)
+ .node("youtube_shorts_gate")
+ .parent("youtube_root")
+ .canonical(canon_youtube_root)
+ .edge(EdgePattern::Variable("video_id"), "youtube_watch")
+ .node("youtu_be_entry")
+ .canonical(canon_youtube_root)
+ .edge(EdgePattern::Variable("vid_id"), "youtu_be_video")
+ .node("youtu_be_video")
+ .parent("youtube_root")
+ .canonical(canon_youtu_be)
+ .build()
+}
+
+// --- Generic internet fallback ---
+
+pub fn generic_canonical(parts: &UrlParts) -> String {
+ let host = normalize_match_host(&parts.host);
+ let path_segments: Vec<String> = parts.path_segments.clone();
+ let mut query = parts.query.clone();
+ strip_tracking_query(&mut query);
+
+ let mut url = if path_segments.is_empty() {
+ Url::parse(&format!("https://{host}"))
+ .unwrap_or_else(|_| Url::parse("https://invalid").unwrap())
+ } else {
+ let path = format!("/{}", path_segments.join("/"));
+ Url::parse(&format!("https://{host}{path}"))
+ .unwrap_or_else(|_| Url::parse("https://invalid").unwrap())
+ };
+
+ if !query.is_empty() {
+ let mut pairs: Vec<_> = query.iter().collect();
+ pairs.sort_by(|a, b| a.0.cmp(b.0));
+ url.query_pairs_mut().clear();
+ for (k, v) in pairs {
+ url.query_pairs_mut().append_pair(k, v);
+ }
+ }
+
+ let mut s = url.to_string();
+ if path_segments.is_empty() {
+ s = s.trim_end_matches('/').to_string();
+ }
+ s
+}
+
+pub fn generic_breadcrumbs(parts: &UrlParts) -> Vec<String> {
+ let host = normalize_match_host(&parts.host);
+ let n = parts.path_segments.len();
+ let mut out = Vec::new();
+
+ let base = generic_canonical(&UrlParts {
+ scheme: "https".to_string(),
+ host: host.clone(),
+ path_segments: vec![],
+ query: HashMap::new(),
+ });
+ out.push(base);
+
+ for i in 0..n {
+ let segs: Vec<String> = parts.path_segments[..=i].to_vec();
+ let url = generic_canonical(&UrlParts {
+ scheme: "https".to_string(),
+ host: host.clone(),
+ path_segments: segs,
+ query: HashMap::new(),
+ });
+ if out.last() != Some(&url) {
+ out.push(url);
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::url_rules::parse::test_parts;
+
+ fn g() -> &'static Graph {
+ graph()
+ }
+
+ fn canon(parts: &UrlParts) -> String {
+ g().resolve_canonical(parts).unwrap()
+ }
+
+ fn crumbs(parts: &UrlParts) -> Vec<String> {
+ g().breadcrumbs(parts)
+ }
+
+ fn terminal(parts: &UrlParts) -> Option<&'static str> {
+ g().traverse_terminal(parts).map(|(n, _)| n)
+ }
+
+ fn vars(parts: &UrlParts) -> HashMap<String, String> {
+ g().traverse_terminal(parts)
+ .map(|(_, c)| c.vars)
+ .unwrap_or_default()
+ }
+
+ #[test]
+ fn youtu_be_malicious_segment_encoded_not_injected() {
+ let p = test_parts("youtu.be", &["abc&t=1"], &[]);
+ assert_eq!(canon(&p
… preview truncated; 29,502 characters omittedB — 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 omittedHardlinks — judgments / attempts / prompt
judgments
attempts
Prompt text is loaded only by the download route.