{"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[09842c93] remove shell\n\nSide A — unified diff (full patch):\ndiff --git a/server/src/html/garden.rs b/server/src/html/garden.rs\nindex 8fc6be1de8dd975f9547de615809222236be4b70..76ba96e45c9e16291a6ccd8096fdd01b274c1560 100644\n--- a/server/src/html/garden.rs\n+++ b/server/src/html/garden.rs\n@@ -1321,55 +1321,53 @@ async fn vote_compare_inner(\n .expect(\"vote compare rpc json\");\n \n let body = html! {\n- section class=\"vote-compare-shell\" {\n- h2 { \"compare\" }\n- div class=\"vote-compare-pair\" {\n- a class=\"vote-compare-item\" href=(nav.garden_item_href(&left)) {\n- code { (item_display_path(left.as_str())) }\n- }\n- span class=\"vote-compare-vs\" { \"vs\" }\n- a class=\"vote-compare-item\" href=(nav.garden_item_href(&right)) {\n- code { (item_display_path(right.as_str())) }\n- }\n- }\n- div id=\"vote-edge-history-region\" {\n- (edge_history)\n- }\n- @if can_post {\n- form id=\"vote-compare-form\" method=\"POST\" action=\"/ui\" {\n- input type=\"hidden\" name=(UI_RPC_FIELD) value=(rpc_json);\n- div class=\"vote-thread-picker\" {\n- label class=\"vote-thread-picker-label\" { \"thread\" }\n- select id=\"vote-thread-select\" name=\"thread_tag\" aria-label=\"Thread to post vote into\" {\n- @if thread_tags.is_empty() {\n- option value=\"vote\" selected { \"#vote\" }\n- }\n- @for t in &thread_tags {\n- @if *t == auto_thread {\n- option value=(t) selected { \"#\" (t) }\n- } @else {\n- option value=(t) { \"#\" (t) }\n- }\n- }\n- }\n+ h2 { \"compare\" }\n+ div class=\"vote-compare-pair\" {\n+ a class=\"vote-compare-item\" href=(nav.garden_item_href(&left)) {\n+ code { (item_display_path(left.as_str())) }\n+ }\n+ span class=\"vote-compare-vs\" { \"vs\" }\n+ a class=\"vote-compare-item\" href=(nav.garden_item_href(&right)) {\n+ code { (item_display_path(right.as_str())) }\n+ }\n+ }\n+ div id=\"vote-edge-history-region\" {\n+ (edge_history)\n+ }\n+ @if can_post {\n+ form id=\"vote-compare-form\" method=\"POST\" action=\"/ui\" {\n+ input type=\"hidden\" name=(UI_RPC_FIELD) value=(rpc_json);\n+ div class=\"vote-thread-picker\" {\n+ label class=\"vote-thread-picker-label\" { \"thread\" }\n+ select id=\"vote-thread-select\" name=\"thread_tag\" aria-label=\"Thread to post vote into\" {\n+ @if thread_tags.is_empty() {\n+ option value=\"vote\" selected { \"#vote\" }\n }\n- input type=\"hidden\" name=\"ratio_left\" id=\"vote-ratio-left\" value=\"50\";\n- input type=\"hidden\" name=\"ratio_right\" id=\"vote-ratio-right\" value=\"50\";\n- label class=\"vote-compare-slider-label\" {\n- span id=\"vote-slider-left-label\" { (item_display_path(left.as_str())) }\n- input type=\"range\" id=\"vote-preference-slider\" min=\"0\" max=\"100\" value=\"50\"\n- aria-valuemin=\"0\" aria-valuemax=\"100\";\n- span id=\"vote-slider-right-label\" { (item_display_path(right.as_str())) }\n+ @for t in &thread_tags {\n+ @if *t == auto_thread {\n+ option value=(t) selected { \"#\" (t) }\n+ } @else {\n+ option value=(t) { \"#\" (t) }\n+ }\n }\n- label class=\"vote-explain-label\" { \"reason (required)\" }\n- textarea name=\"explanation\" id=\"vote-explain\" rows=\"5\" placeholder=\"why this split?\" required {}\n- div id=\"vote-compare-errors\" {}\n- p { button type=\"submit\" { \"post vote\" } }\n }\n- } @else {\n- p class=\"muted\" { a href=\"/login\" { \"log in\" } \" to post this vote.\" }\n }\n+ input type=\"hidden\" name=\"ratio_left\" id=\"vote-ratio-left\" value=\"50\";\n+ input type=\"hidden\" name=\"ratio_right\" id=\"vote-ratio-right\" value=\"50\";\n+ label class=\"vote-compare-slider-label\" {\n+ span id=\"vote-slider-left-label\" { (item_display_path(left.as_str())) }\n+ input type=\"range\" id=\"vote-preference-slider\" min=\"0\" max=\"100\" value=\"50\"\n+ aria-valuemin=\"0\" aria-valuemax=\"100\";\n+ span id=\"vote-slider-right-label\" { (item_display_path(right.as_str())) }\n+ }\n+ label class=\"vote-explain-label\" { \"reason (required)\" }\n+ textarea name=\"explanation\" id=\"vote-explain\" rows=\"5\" placeholder=\"why this split?\" required {}\n+ div id=\"vote-compare-errors\" {}\n+ p { button type=\"submit\" { \"post vote\" } }\n }\n+ } @else {\n+ p class=\"muted\" { a href=\"/login\" { \"log in\" } \" to post this vote.\" }\n+ }\n };\n \n let page = layout_full_bleed_chromeless(\ndiff --git a/server/static/theme_default.css b/server/static/theme_default.css\nindex a441c4f79d8cf88f5a8240f9992f47dbbd1ab46b..fdcde86c718eb53cce8273e45a9844c2d8041f88 100644\n--- a/server/static/theme_default.css\n+++ b/server/static/theme_default.css\n@@ -1270,8 +1270,12 @@ body.view-ontology-dark .ont-ranking-list li {\n body.view-ontology-dark .ont-ranking-list li::before {\n color: var(--meta);\n content: counter(ont-rank) \".\";\n- font-size: 11px;\n- min-width: 18px;\n+ flex-shrink: 0;\n+ font-size: 1.35rem;\n+ font-weight: 700;\n+ font-variant-numeric: tabular-nums;\n+ line-height: 1;\n+ min-width: 2.25ch;\n text-align: right;\n }\n body.view-ontology-dark .ont-rank-score {\n@@ -1424,8 +1428,12 @@ body.view-ontology-light .ont-ranking-list li {\n body.view-ontology-light .ont-ranking-list li::before {\n color: var(--meta);\n content: counter(ont-rank) \".\";\n- font-size: 11px;\n- min-width: 18px;\n+ flex-shrink: 0;\n+ font-size: 1.35rem;\n+ font-weight: 700;\n+ font-variant-numeric: tabular-nums;\n+ line-height: 1;\n+ min-width: 2.25ch;\n text-align: right;\n }\n body.view-ontology-light .ont-rank-score {\ndiff --git a/server/static/theme_retro.css b/server/static/theme_retro.css\nindex 373f15bbd75b62604cdd14b9f0fadda2d6176991..61e1448b2f66a075c0e33325d6980448712fc927 100644\n--- a/server/static/theme_retro.css\n+++ b/server/static/theme_retro.css\n@@ -135,6 +135,30 @@ body.view-ontology nav.breadcrumb a:hover {\n body.view-ontology nav.breadcrumb a.bc-current { color: #111; font-weight: 600; }\n body.view-ontology nav.breadcrumb .bc-sep { color: #888; padding: 0 2px; }\n \n+body.view-ontology ol.ont-ranking-list {\n+ counter-reset: ont-rank;\n+ list-style: none;\n+ margin: 0.5rem 0;\n+ padding: 0;\n+}\n+body.view-ontology ol.ont-ranking-list li {\n+ align-items: baseline;\n+ counter-increment: ont-rank;\n+ display: flex;\n+ gap: 0.35rem;\n+}\n+body.view-ontology ol.ont-ranking-list li::before {\n+ flex-shrink: 0;\n+ color: #666;\n+ content: counter(ont-rank) \".\";\n+ font-size: 1.35rem;\n+ font-weight: 700;\n+ font-variant-numeric: tabular-nums;\n+ line-height: 1;\n+ min-width: 2.25ch;\n+ text-align: right;\n+}\n+\n nav.breadcrumb.ont-sibling-nav {\n margin-top: 0;\n width: 100%;\ndiff --git a/server/static/theme_retro_craft.css b/server/static/theme_retro_craft.css\nindex 6eb9222184a8795d67a5d09d41de08c8ac1b148f..7da102040484c887833158a37c307d078205c701 100644\n--- a/server/static/theme_retro_craft.css\n+++ b/server/static/theme_retro_craft.css\n@@ -742,12 +742,32 @@ body.view-ontology button.ont-garden-pin-ico:focus-visible {\n outline-offset: 2px;\n }\n \n+body.view-ontology ol.ont-ranking-list {\n+ counter-reset: ont-rank;\n+ list-style: none;\n+ margin: 0;\n+ padding: 0;\n+}\n body.view-ontology ol.ont-ranking-list li,\n body.view-ontology ul.ont-group-list li {\n display: flex;\n align-items: baseline;\n gap: 0.35rem;\n }\n+body.view-ontology ol.ont-ranking-list li {\n+ counter-increment: ont-rank;\n+}\n+body.view-ontology ol.ont-ranking-list li::before {\n+ flex-shrink: 0;\n+ color: #5c574e;\n+ content: counter(ont-rank) \".\";\n+ font-size: 1.35rem;\n+ font-weight: 700;\n+ font-variant-numeric: tabular-nums;\n+ line-height: 1;\n+ min-width: 2.25ch;\n+ text-align: right;\n+}\n body.view-ontology ol.ont-ranking-list li .item-link,\n body.view-ontology ul.ont-group-list li .item-link {\n flex: 1;\n\n\nSide B — contributor: tommy-mor\nSide B — commit message:\n[4e327784] deploy live constitution dashboard\n\nExpose auditable progress and event streaming, configure the production roots and runtime, and make tested main-branch commits the deployment authority.\n\nCo-authored-by: Cursor \n\nSide B — unified diff (full patch):\ndiff --git a/.dockerignore b/.dockerignore\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..c9d63a722beba0a0297fc853089332c460ab78dd\n--- /dev/null\n+++ b/.dockerignore\n@@ -0,0 +1,7 @@\n+.git\n+.venv\n+.hypothesis\n+__pycache__\n+tests\n+*.json\n+*.bsp\ndiff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..76dcdf82d53177c1e47d86b23a54523239d232a6\n--- /dev/null\n+++ b/.github/workflows/deploy.yml\n@@ -0,0 +1,49 @@\n+name: Test and deploy\n+\n+on:\n+ push:\n+ branches: [main]\n+\n+concurrency:\n+ group: production\n+ cancel-in-progress: false\n+\n+permissions:\n+ contents: read\n+\n+jobs:\n+ test:\n+ runs-on: ubuntu-latest\n+ steps:\n+ - uses: actions/checkout@v4\n+\n+ - uses: astral-sh/setup-uv@v6\n+ with:\n+ enable-cache: true\n+\n+ - name: Run Python tests\n+ run: uv run pytest -q\n+\n+ - name: Install Babashka\n+ run: |\n+ curl -fsSL https://raw.githubusercontent.com/babashka/babashka/master/install \\\n+ | sudo bash -s -- --dir /usr/local/bin\n+\n+ - name: Run process integration tests\n+ run: bb TEST.sh\n+\n+ deploy:\n+ needs: test\n+ runs-on: ubuntu-latest\n+ environment:\n+ name: production\n+ url: https://token.slug.social\n+ steps:\n+ - uses: actions/checkout@v4\n+\n+ - uses: superfly/flyctl-actions/setup-flyctl@master\n+\n+ - name: Deploy to Fly\n+ run: flyctl deploy --remote-only\n+ env:\n+ FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }}\ndiff --git a/Dockerfile b/Dockerfile\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..c9a5c00782371c19ad5ab5c58cf6f5a8ffec0141\n--- /dev/null\n+++ b/Dockerfile\n@@ -0,0 +1,17 @@\n+FROM ghcr.io/astral-sh/uv:python3.11-bookworm-slim\n+\n+RUN apt-get update \\\n+ && apt-get install -y --no-install-recommends git ca-certificates \\\n+ && rm -rf /var/lib/apt/lists/*\n+\n+WORKDIR /app\n+COPY pyproject.toml uv.lock ./\n+RUN uv sync --frozen --no-install-project\n+\n+COPY constitution.py ./\n+\n+ENV PATH=\"/app/.venv/bin:${PATH}\" \\\n+ PYTHONUNBUFFERED=\"1\"\n+\n+EXPOSE 8080\n+CMD [\"python\", \"constitution.py\"]\ndiff --git a/constitution.py b/constitution.py\nindex 4bee9f83663ab7fb36db95129b92b64b4ef57258..a58257e1881b21d1d6fa8e68a3faa222e4f661ef 100644\n--- a/constitution.py\n+++ b/constitution.py\n@@ -24,12 +24,12 @@ A daily GitHub Action backs up the JSONL ledger to the same repo.\n Run: uv run constitution.py\n \"\"\"\n \n-from decimal import Decimal, getcontext\n+from decimal import Decimal, getcontext, DefaultContext\n from datetime import datetime, timezone\n from fastapi import FastAPI, Request, Response\n from fastapi.responses import PlainTextResponse, HTMLResponse\n from starlette.middleware.sessions import SessionMiddleware\n-import json, time, os, asyncio, httpx, pathlib, subprocess, hashlib, re, fcntl\n+import json, time, os, asyncio, httpx, pathlib, subprocess, hashlib, re, fcntl, base64\n import sympy as sp # type: ignore[reportMissingImports]\n from tenacity import retry, retry_if_exception, stop_after_attempt, wait_exponential\n from evaleval import (\n@@ -37,6 +37,7 @@ from evaleval import (\n exec_event, One, Two, Three, Selector, MORPH, PREPEND,\n )\n \n+DefaultContext.prec = 50\n getcontext().prec = 50\n \n app = FastAPI()\n@@ -129,14 +130,47 @@ OPENROUTER_BASE_URL = os.environ.get(\"OPENROUTER_BASE_URL\", \"https://openrouter.\n # using the exact same source; their normalized values are committed to every\n # discovery event.\n DEFAULT_REPOSITORIES = [\n+ {\n+ \"id\": \"constitution\",\n+ \"url\": \"https://github.com/sortersocial/constitution.git\",\n+ \"refs\": [\"refs/heads/**\"],\n+ },\n {\n \"id\": \"slug\",\n- \"url\": \"https://github.com/tommy-mor/slug.git\",\n+ \"url\": \"https://github.com/sortersocial/slug.git\",\n+ \"refs\": [\"refs/heads/**\"],\n+ },\n+ {\n+ \"id\": \"sorter\",\n+ \"url\": \"https://github.com/sorterisntonline/sorter.git\",\n+ \"refs\": [\"refs/heads/**\"],\n+ },\n+ {\n+ \"id\": \"sorter2\",\n+ \"url\": \"https://github.com/sortersocial/sorter2.git\",\n+ \"refs\": [\"refs/heads/**\"],\n+ },\n+ {\n+ \"id\": \"sorter-oldest\",\n+ \"url\": \"https://github.com/tommy-mor/sorter.git\",\n \"refs\": [\"refs/heads/**\"],\n },\n ]\n DEFAULT_CONTRIBUTORS = {\n \"tommy-mor\": [\"thmorriss@gmail.com\"],\n+ \"christopher-whitman\": [\n+ \"chris@cwwhitman.com\",\n+ \"7566903+cwwhitman@users.noreply.github.com\",\n+ ],\n+ \"jake-chvatal\": [\n+ \"jake+github@uln.industries\",\n+ \"jakechvatal@gmail.com\",\n+ \"jake@isnt.online\",\n+ ],\n+ \"lara\": [\"me@lara.lv\"],\n+ \"nat-reid\": [\"nathanielreid@gmail.com\"],\n+ \"zod\": [\"jason.p.mcel@gmail.com\", \"me@zod.tf\"],\n+ \"jovan\": [\"jovan@slug.social\", \"jovan@getcivicai.com\"],\n }\n \n REPOSITORIES = json.loads(\n@@ -147,6 +181,7 @@ CONTRIBUTORS = json.loads(\n )\n GIT_MIRROR_DIR = pathlib.Path(os.environ.get(\"GIT_MIRROR_DIR\", \"/data/git\"))\n GIT_TIMEOUT_SECONDS = int(os.environ.get(\"GIT_TIMEOUT_SECONDS\", \"120\"))\n+GITHUB_TOKEN = os.environ.get(\"GITHUB_TOKEN\", \"\")\n \n # Council model IDs: slug.social garden rank under this parent (bodies = OpenRouter URLs), then top-up from OpenRouter list.\n SLUG_SOCIAL_BASE_URL = os.environ.get(\"SLUG_SOCIAL_BASE_URL\", \"https://slug.social\").rstrip(\"/\")\n@@ -661,20 +696,30 @@ def _git(repo: pathlib.Path | None, *args: str, input_bytes: bytes | None = None\n if repo is not None:\n command += [\"-C\", str(repo)]\n command += list(args)\n+ git_env = {\n+ **os.environ,\n+ \"GIT_CONFIG_NOSYSTEM\": \"1\",\n+ \"GIT_CONFIG_GLOBAL\": os.devnull,\n+ \"GIT_NO_REPLACE_OBJECTS\": \"1\",\n+ \"LC_ALL\": \"C\",\n+ \"TZ\": \"UTC\",\n+ }\n+ if GITHUB_TOKEN:\n+ credential = base64.b64encode(\n+ f\"x-access-token:{GITHUB_TOKEN}\".encode()\n+ ).decode()\n+ git_env.update({\n+ \"GIT_CONFIG_COUNT\": \"1\",\n+ \"GIT_CONFIG_KEY_0\": \"http.https://github.com/.extraHeader\",\n+ \"GIT_CONFIG_VALUE_0\": f\"Authorization: Basic {credential}\",\n+ })\n try:\n result = subprocess.run(\n command,\n input=input_bytes,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n- env={\n- **os.environ,\n- \"GIT_CONFIG_NOSYSTEM\": \"1\",\n- \"GIT_CONFIG_GLOBAL\": os.devnull,\n- \"GIT_NO_REPLACE_OBJECTS\": \"1\",\n- \"LC_ALL\": \"C\",\n- \"TZ\": \"UTC\",\n- },\n+ env=git_env,\n timeout=GIT_TIMEOUT_SECONDS,\n check=False,\n )\n@@ -844,9 +889,15 @@ def _build_discovery(epoch_n: int, boundary_ms: int, events: list) -> GitDiscove\n canonical_location = min(\n locations[qualified_oid], key=lambda x: (x[0], x[1])\n )\n+ # One commit may be reachable from dozens of refs in the same mirror.\n+ # Verify its object once per repository, not once per source ref.\n+ object_locations = {\n+ (str(m), raw_oid): (m, raw_oid)\n+ for _, _, m, raw_oid in locations[qualified_oid]\n+ }\n object_hashes = {\n hashlib.sha256(_git(m, \"cat-file\", \"commit\", raw_oid)).hexdigest()\n- for _, _, m, raw_oid in locations[qualified_oid]\n+ for m, raw_oid in object_locations.values()\n }\n if len(object_hashes) != 1:\n raise RuntimeError(f\"conflicting Git objects share OID {qualified_oid}\")\n@@ -994,11 +1045,55 @@ async def discover_repositories(epoch_n: int, boundary_ms: int) -> GitDiscovery:\n \n \n SSE_CLIENTS = []\n+AUDIT_HISTORY = []\n+AUDIT_SEQUENCE = 0\n+PROCESS_STATE = {\n+ \"running\": False,\n+ \"phase\": \"idle\",\n+ \"progress\": 100,\n+ \"message\": \"Waiting for the next epoch\",\n+}\n+\n+\n+def _sse_event(event_name: str, payload: dict) -> str:\n+ return (\n+ f\"event: {event_name}\\n\"\n+ f\"data: {json.dumps(payload, separators=(',', ':'))}\\n\\n\"\n+ )\n+\n+\n+async def broadcast_audit(\n+ kind: str,\n+ message: str,\n+ *,\n+ progress: int | None = None,\n+ phase: str | None = None,\n+) -> dict:\n+ global AUDIT_SEQUENCE\n+ AUDIT_SEQUENCE += 1\n+ if progress is not None:\n+ PROCESS_STATE[\"progress\"] = max(0, min(100, int(progress)))\n+ if phase is not None:\n+ PROCESS_STATE[\"phase\"] = phase\n+ PROCESS_STATE[\"message\"] = message\n+ payload = {\n+ \"id\": AUDIT_SEQUENCE,\n+ \"timestamp_ms\": int(time.time() * 1000),\n+ \"kind\": kind,\n+ \"message\": message,\n+ **PROCESS_STATE,\n+ }\n+ AUDIT_HISTORY.append(payload)\n+ del AUDIT_HISTORY[:-200]\n+ wire = _sse_event(\"audit\", payload)\n+ for queue in list(SSE_CLIENTS):\n+ await queue.put(wire)\n+ return payload\n \n \n async def broadcast_js(js: str):\n \"\"\"Send a JS snippet to all connected SSE clients.\"\"\"\n- for queue in SSE_CLIENTS:\n+ for queue in list(SSE_CLIENTS):\n await queue.put(js)\n \n \n@@ -1006,10 +1101,29 @@ async def rank_commits(commits: list[dict]):\n if not commits:\n return {}, []\n \n- models = await fetch_top_models(n=3)\n contributors = sorted(set(c[\"contributor\"] for c in commits))\n- if len(contributors) > 1 and not models:\n+ if len(contributors) == 1:\n+ await broadcast_audit(\n+ \"ranking\",\n+ f\"Only {contributors[0]} is eligible; rank is 1.0\",\n+ progress=90,\n+ phase=\"finalizing\",\n+ )\n+ return {contributors[0]: Decimal(\"1\")}, []\n+ if not (OPENROUTER_API_KEY or \"\").strip():\n+ raise RuntimeError(\n+ \"OPENROUTER_API_KEY is required when multiple contributors need ranking\"\n+ )\n+\n+ models = await fetch_top_models(n=3)\n+ if not models:\n raise RuntimeError(\"no council models available for contributor ranking\")\n+ await broadcast_audit(\n+ \"council\",\n+ f\"Council selected: {', '.join(models)}\",\n+ progress=35,\n+ phase=\"ranking\",\n+ )\n await broadcast_js(exec_event(Three[Selector(\"#emission-log\")][PREPEND][\n [\"div.log-council\", f\"Council: {', '.join(models)} — {len(commits)} commits\"]\n ]))\n@@ -1035,6 +1149,11 @@ async def rank_commits(commits: list[dict]):\n \n async def compare_fn(i, j):\n a1, a2 = authors[i], authors[j]\n+ await broadcast_audit(\n+ \"comparison\",\n+ f\"Comparing {a1} with {a2}\",\n+ phase=\"ranking\",\n+ )\n await broadcast_js(exec_event(Three[Selector(\"#emission-status\")][MORPH][\n [\"div#emission-status\", f\"Comparing {a1} vs {a2}…\"]\n ]))\n@@ -1050,6 +1169,11 @@ async def rank_commits(commits: list[dict]):\n if winner_weight <= 0 or loser_weight <= 0:\n raise ValueError(\"ratio weights must be positive\")\n results.append((w, l, winner_weight, loser_weight))\n+ await broadcast_audit(\n+ \"vote\",\n+ f\"{model}: {authors[w]} over {authors[l]} ({result['ratio']})\",\n+ phase=\"ranking\",\n+ )\n await broadcast_js(exec_event(Three[Selector(\"#emission-log\")][PREPEND][\n [\"div.log-vote\",\n [\"span.model\", model], \" — \",\n@@ -1059,6 +1183,11 @@ async def rank_commits(commits: list[dict]):\n ]\n ]))\n except Exception as e:\n+ await broadcast_audit(\n+ \"error\",\n+ f\"{model} failed: {e}\",\n+ phase=\"error\",\n+ )\n await broadcast_js(exec_event(Three[Selector(\"#emission-log\")][PREPEND][\n [\"div.log-error\", f\"⚠ {model}: {e}\"]\n ]))\n@@ -1068,8 +1197,13 @@ async def rank_commits(commits: list[dict]):\n async def progress_fn(ev):\n if ev[\"phase\"] == \"spanning_tree\":\n label = f\"Spanning tree: {ev['step']}/{ev['total']}\"\n+ percent = 35 + round(35 * ev[\"step\"] / max(ev[\"total\"], 1))\n else:\n label = f\"Zip pass {ev['pass']}: {ev['step']}/{ev['total']}\"\n+ percent = 70 + round(20 * ev[\"step\"] / max(ev[\"total\"], 1))\n+ await broadcast_audit(\n+ \"progress\", label, progress=percent, phase=\"ranking\"\n+ )\n await broadcast_js(exec_event(Three[Selector(\"#emission-status\")][MORPH][\n [\"div#emission-status\", label]\n ]))\n@@ -1083,6 +1217,12 @@ async def rank_commits(commits: list[dict]):\n scores = rank_centrality(pairs)\n ranking = {authors[i]: Decimal(str(scores[i])) for i in range(len(authors))}\n ranking_rows = sorted(ranking.items(), key=lambda x: x[1], reverse=True)\n+ await broadcast_audit(\n+ \"ranking\",\n+ \"Ranking: \" + \", \".join(f\"{a} {s:.4f}\" for a, s in ranking_rows),\n+ progress=90,\n+ phase=\"finalizing\",\n+ )\n await broadcast_js(exec_event(Three[Selector(\"#emission-log\")][PREPEND][\n [\"div.log-ranking\",\n [\"b\", \"Ranking: \"],\n@@ -1104,11 +1244,33 @@ def pool_remaining(events: list) -> Decimal:\n \n \n async def run_emission(epoch_n, boundary_ms):\n+ PROCESS_STATE[\"running\"] = True\n+ await broadcast_audit(\n+ \"start\",\n+ f\"Epoch {epoch_n} emission started\",\n+ progress=2,\n+ phase=\"starting\",\n+ )\n await broadcast_js(exec_event(Three[Selector(\"#emission-log\")][PREPEND][\n [\"div.log-start\", f\"⚡ Epoch {epoch_n} emission started\"]\n ]))\n \n+ await broadcast_audit(\n+ \"discovery\",\n+ \"Fetching configured repositories and snapshotting refs\",\n+ progress=8,\n+ phase=\"discovery\",\n+ )\n discovery = await discover_repositories(epoch_n, boundary_ms)\n+ await broadcast_audit(\n+ \"discovery\",\n+ (\n+ f\"Discovered {len(discovery.observations)} new commits; \"\n+ f\"{len(discovery.commits)} are eligible\"\n+ ),\n+ progress=30,\n+ phase=\"discovery\",\n+ )\n ranking, models = await rank_commits(discovery.commits)\n \n def make_emission(events):\n@@ -1146,6 +1308,13 @@ async def run_emission(epoch_n, boundary_ms):\n \n entry = await store.atomic(make_emission)\n if entry:\n+ PROCESS_STATE[\"running\"] = False\n+ await broadcast_audit(\n+ \"complete\",\n+ f\"Epoch {entry.epoch} complete; emitted {entry.total_emitted} SLG\",\n+ progress=100,\n+ phase=\"idle\",\n+ )\n await broadcast_js(exec_event(Three[Selector(\"#emission-log\")][PREPEND][\n [\"div.log-amount\",\n f\"Pool {entry.pool_before} → emit {entry.total_emitted} → {entry.pool_after}\"]\n@@ -1189,13 +1358,24 @@ async def distribute_usdc(holdings, treasury_balance):\n async def epoch_loop():\n while True:\n epoch_n, current_start, next_boundary = current_epoch()\n+ processed = {e.epoch for e in store.read() if isinstance(e, Emission)}\n+ if epoch_n >= 0 and epoch_n not in processed:\n+ try:\n+ await run_emission(epoch_n, current_start)\n+ except Exception as exc:\n+ PROCESS_STATE[\"running\"] = False\n+ await broadcast_audit(\n+ \"error\",\n+ f\"Epoch {epoch_n} failed: {exc}; retrying in 60 seconds\",\n+ phase=\"error\",\n+ )\n+ print(f\"epoch {epoch_n} emission failed: {exc}\", flush=True)\n+ await asyncio.sleep(60)\n+ continue\n+\n now = int(time.time() * 1000)\n wait_ms = next_boundary - now\n-\n if wait_ms <= 0:\n- processed = {e.epoch for e in store.read() if isinstance(e, Emission)}\n- if epoch_n not in processed and epoch_n >= 0:\n- await run_emission(epoch_n, current_start)\n await asyncio.sleep(60)\n elif wait_ms < 86_400_000:\n await broadcast_js(exec_event(Three[Selector(\"#emission-status\")][MORPH][\n@@ -1243,6 +1423,36 @@ async def get_ranking():\n return {\"ranking\": latest.ranking, \"epoch\": latest.epoch}\n \n \n+@app.get(\"/api/status\")\n+async def get_status():\n+ events = store.read()\n+ discoveries = [e for e in events if isinstance(e, GitDiscovery)]\n+ emissions = [e for e in events if isinstance(e, Emission)]\n+ return {\n+ **PROCESS_STATE,\n+ \"epoch\": current_epoch()[0],\n+ \"openrouter_configured\": bool((OPENROUTER_API_KEY or \"\").strip()),\n+ \"sse_clients\": len(SSE_CLIENTS),\n+ \"latest_discovery\": (\n+ {\n+ \"epoch\": discoveries[-1].epoch,\n+ \"snapshot_id\": discoveries[-1].snapshot_id,\n+ \"observations\": len(discoveries[-1].observations),\n+ \"eligible_commits\": len(discoveries[-1].commits),\n+ }\n+ if discoveries else None\n+ ),\n+ \"latest_emission\": (\n+ {\n+ \"epoch\": emissions[-1].epoch,\n+ \"total_emitted\": emissions[-1].total_emitted,\n+ \"ranking\": emissions[-1].ranking,\n+ }\n+ if emissions else None\n+ ),\n+ }\n+\n+\n @app.get(\"/api/contributor/{github_username}\")\n async def get_contributor(github_username: str):\n history = [\n@@ -1306,13 +1516,6 @@ async def test_emit():\n \n # ===========================================================================\n # §9. SSE — live audit stream of the pairwise voting process\n-#\n-# TODO: the /sse emission audit page needs a real SSE-driven UI. votes arrive\n-# incrementally during rank_commits(), and the client should show a live\n-# progress bar and per-vote results as they stream in. this requires a\n-# dedicated page that connects to /sse and updates the DOM on each event\n-# (council, comparing, vote, ranking, emission_complete). defer until we\n-# have playwright tests to cover it — the incremental rendering is fiddly.\n # ===========================================================================\n \n @app.get(\"/sse\")\n@@ -1322,6 +1525,13 @@ async def sse_stream(request: Request):\n \n async def generate():\n try:\n+ yield _sse_event(\"audit\", {\n+ \"id\": AUDIT_SEQUENCE,\n+ \"timestamp_ms\": int(time.time() * 1000),\n+ \"kind\": \"connection\",\n+ \"message\": f\"Connected to epoch {current_epoch()[0]}\",\n+ **PROCESS_STATE,\n+ })\n yield exec_event(Three[Selector(\"#emission-status\")][MORPH][\n [\"div#emission-status\", f\"Connected — epoch {current_epoch()[0]}\"]\n ])\n@@ -1334,10 +1544,15 @@ async def sse_stream(request: Request):\n except asyncio.TimeoutError:\n yield \": keepalive\\n\\n\"\n finally:\n- SSE_CLIENTS.remove(queue)\n+ if queue in SSE_CLIENTS:\n+ SSE_CLIENTS.remove(queue)\n \n from starlette.responses import StreamingResponse\n- return StreamingResponse(generate(), media_type=\"text/event-stream\")\n+ return StreamingResponse(\n+ generate(),\n+ media_type=\"text/event-stream\",\n+ headers={\"Cache-Control\": \"no-cache\", \"X-Accel-Buffering\": \"no\"},\n+ )\n \n \n # ===========================================================================\n@@ -1359,6 +1574,7 @@ def _page(title: str, body: list) -> HTMLResponse:\n [\"meta\", {\"charset\": \"utf-8\"}],\n [\"meta\", {\"name\": \"viewport\", \"content\": \"width=device-width, initial-scale=1\"}],\n [\"title\", title],\n+ [\"style\", RawContent(_WATCH_CSS)],\n ],\n [\"body\",\n body,\n@@ -1367,6 +1583,387 @@ def _page(title: str, body: list) -> HTMLResponse:\n ]))\n \n \n+_WATCH_CSS = \"\"\"\n+/* ================================================================\n+ ZIGGURAT — bevel-first dark theme\n+ --spread (0→1) controls bevel depth. 0 = flat. 1 = full relief.\n+ Light source: top-left. Shadow: bottom-right.\n+ Platforms nest. Each level is raised. Nothing is rounded.\n+ ================================================================ */\n+\n+:root {\n+ color-scheme: dark;\n+ --spread: 1;\n+\n+ --g0: #080808;\n+ --g1: #131313;\n+ --g2: #1c1c1c;\n+ --g3: #252525;\n+ --g4: #2e2e2e;\n+ --g5: #383838;\n+\n+ --hi: #5e5e5e;\n+ --lo: #050505;\n+ --bv: calc(var(--spread) * 4px + 1px);\n+ --bv-lg: calc(var(--spread) * 6px + 2px);\n+\n+ --signal: #f0f0f0;\n+ --prose: #c2c2c2;\n+ --ui: #888;\n+ --meta: #4a4a4a;\n+ --link: #8899ee;\n+ --code-fg: #c8dda0;\n+\n+ --font-prose: \"Iowan Old Style\", \"Palatino Linotype\", Palatino, \"Book Antiqua\", Georgia, serif;\n+ --font-ui: system-ui, -apple-system, sans-serif;\n+ --font-code: ui-monospace, \"Cascadia Code\", \"SF Mono\", Menlo, monospace;\n+}\n+\n+*, *::before, *::after { box-sizing: border-box; }\n+html, body { margin: 0; padding: 0; }\n+\n+body {\n+ background: var(--g0);\n+ color: var(--prose);\n+ font-family: var(--font-ui);\n+ font-size: 14px;\n+ line-height: 1.6;\n+ margin: 0 auto;\n+ max-width: 560px;\n+ min-height: 100vh;\n+ padding: 0 16px 48px;\n+}\n+main { width: 100%; padding: 18px 0 48px; }\n+\n+h1, h2, h3 {\n+ color: var(--signal);\n+ font-size: 11px;\n+ font-weight: bold;\n+ letter-spacing: 0.12em;\n+ margin: 14px 0 6px;\n+ text-transform: uppercase;\n+}\n+a { color: var(--link); text-decoration: none; }\n+a:hover { color: var(--signal); }\n+.eyebrow {\n+ background: var(--g2);\n+ border: var(--bv) solid;\n+ border-color: var(--hi) var(--lo) var(--lo) var(--hi);\n+ color: var(--ui);\n+ font-size: 11px;\n+ letter-spacing: 0.12em;\n+ padding: 4px 10px;\n+ text-transform: uppercase;\n+ width: fit-content;\n+}\n+\n+/* Every dashboard section is a raised platform. */\n+.panel {\n+ background: var(--g2);\n+ border: var(--bv-lg) solid;\n+ border-color: var(--hi) var(--lo) var(--lo) var(--hi);\n+ margin: 8px 0;\n+ padding: 10px;\n+ width: 100%;\n+}\n+.status-row {\n+ align-items: center;\n+ display: flex;\n+ flex-wrap: wrap;\n+ gap: 8px;\n+ justify-content: space-between;\n+}\n+#process-status { color: var(--signal); font-family: var(--font-code); font-weight: bold; }\n+.badge {\n+ align-items: center;\n+ background: var(--g3);\n+ border: var(--bv) solid;\n+ border-color: var(--hi) var(--lo) var(--lo) var(--hi);\n+ color: var(--ui);\n+ display: inline-flex;\n+ font-size: 11px;\n+ gap: 7px;\n+ padding: 3px 8px;\n+}\n+.dot { background: var(--meta); height: 8px; width: 8px; }\n+.live .dot { background: #7acc7a; }\n+.warn .dot { background: #cc9955; }\n+\n+/* The progress track is inset; its signal is raised inside it. */\n+.progress-shell {\n+ background: var(--g1);\n+ border: var(--bv-lg) solid;\n+ border-color: var(--lo) var(--hi) var(--hi) var(--lo);\n+ height: 58px;\n+ margin: 14px 0 10px;\n+ overflow: hidden;\n+ position: relative;\n+}\n+#progress-fill {\n+ background: var(--link);\n+ border: var(--bv) solid;\n+ border-color: var(--hi) var(--lo) var(--lo) var(--hi);\n+ height: 100%;\n+ transition: width .35s steps(8, end);\n+ width: 0;\n+}\n+#progress-label {\n+ color: var(--signal);\n+ display: grid;\n+ font-family: var(--font-code);\n+ font-size: 18px;\n+ font-weight: bold;\n+ inset: 0;\n+ place-items: center;\n+ position: absolute;\n+ text-shadow: 1px 1px var(--lo);\n+}\n+\n+.controls { align-items: center; display: flex; flex-wrap: wrap; gap: 8px; }\n+button {\n+ background: var(--g5);\n+ border: var(--bv) solid;\n+ border-color: var(--hi) var(--lo) var(--lo) var(--hi);\n+ color: var(--signal);\n+ cursor: pointer;\n+ font: inherit;\n+ font-size: 12px;\n+ padding: 4px 10px;\n+}\n+button:hover { background: #404040; }\n+button:active {\n+ background: var(--g4);\n+ border-color: var(--lo) var(--hi) var(--hi) var(--lo);\n+ transform: translate(1px, 1px);\n+}\n+button:disabled { cursor: default; opacity: .4; }\n+.note { color: var(--meta); font-size: 11px; margin: 4px 0; }\n+\n+.feed-head { align-items: baseline; display: flex; justify-content: space-between; }\n+#audit-feed {\n+ background: var(--g1);\n+ border: var(--bv) solid;\n+ border-color: var(--lo) var(--hi) var(--hi) var(--lo);\n+ display: flex;\n+ flex-direction: column;\n+ gap: 5px;\n+ margin-top: 8px;\n+ padding: 6px;\n+}\n+.event {\n+ background: var(--g3);\n+ border: var(--bv) solid;\n+ border-color: var(--hi) var(--lo) var(--lo) var(--hi);\n+ display: grid;\n+ gap: 6px;\n+ grid-template-columns: 82px 88px 1fr;\n+ padding: 5px 8px;\n+}\n+.event[data-kind=\"error\"] { border-left-color: #cc5555; }\n+.event[data-kind=\"complete\"], .event[data-kind=\"ranking\"] { border-left-color: #7acc7a; }\n+.event[data-kind=\"vote\"] { border-left-color: var(--link); }\n+.event time, .event-kind { color: var(--meta); font-family: var(--font-code); font-size: 10px; }\n+.event-kind { text-transform: uppercase; }\n+.event-message { color: var(--prose); font-family: var(--font-prose); }\n+\n+code {\n+ background: var(--g1);\n+ border: 2px solid;\n+ border-color: var(--lo) var(--hi) var(--hi) var(--lo);\n+ color: var(--code-fg);\n+ font-family: var(--font-code);\n+ font-size: 12px;\n+ padding: 1px 4px;\n+}\n+\n+@media (max-width: 520px) {\n+ .event { grid-template-columns: 72px 1fr; }\n+ .event-message { grid-column: 1 / -1; }\n+}\n+\"\"\"\n+\n+\n+def _watch_initial_state() -> dict:\n+ events = store.read()\n+ feed = []\n+ for event_ in events[-40:]:\n+ if isinstance(event_, GitDiscovery):\n+ feed.append({\n+ \"id\": f\"discovery-{event_.snapshot_id}\",\n+ \"timestamp_ms\": event_.timestamp_ms,\n+ \"kind\": \"discovery\",\n+ \"message\": (\n+ f\"Epoch {event_.epoch}: observed {len(event_.observations)} commits; \"\n+ f\"{len(event_.commits)} eligible\"\n+ ),\n+ })\n+ elif isinstance(event_, Emission):\n+ feed.append({\n+ \"id\": f\"emission-{event_.epoch}\",\n+ \"timestamp_ms\": event_.timestamp_ms,\n+ \"kind\": \"complete\",\n+ \"message\": (\n+ f\"Epoch {event_.epoch}: emitted {event_.total_emitted} SLG; \"\n+ f\"ranking {event_.ranking}\"\n+ ),\n+ })\n+ feed.extend(AUDIT_HISTORY)\n+ return {\n+ \"process\": dict(PROCESS_STATE),\n+ \"openrouter_configured\": bool((OPENROUTER_API_KEY or \"\").strip()),\n+ \"epoch\": current_epoch()[0],\n+ \"feed\": feed[-200:],\n+ }\n+\n+\n+_WATCH_JS = \"\"\"\n+const initial = __INITIAL__;\n+const feed = document.querySelector('#audit-feed');\n+const processStatus = document.querySelector('#process-status');\n+const connection = document.querySelector('#connection-status');\n+const fill = document.querySelector('#progress-fill');\n+const progressLabel = document.querySelector('#progress-label');\n+const play = document.querySelector('#play');\n+const pause = document.querySelector('#pause');\n+const seen = new Set();\n+let source = null;\n+\n+function setProgress(value) {\n+ const n = Math.max(0, Math.min(100, Number(value ?? 0)));\n+ fill.style.width = `${n}%`;\n+ progressLabel.textContent = `${Math.round(n)}%`;\n+ document.querySelector('.progress-shell').setAttribute('aria-valuenow', String(n));\n+}\n+\n+function addEvent(event) {\n+ const id = String(event.id);\n+ if (seen.has(id)) return;\n+ seen.add(id);\n+ const row = document.createElement('div');\n+ row.className = 'event';\n+ row.dataset.kind = event.kind || 'event';\n+ const when = document.createElement('time');\n+ when.dateTime = new Date(event.timestamp_ms).toISOString();\n+ when.textContent = new Date(event.timestamp_ms).toLocaleTimeString();\n+ const kind = document.createElement('span');\n+ kind.className = 'event-kind';\n+ kind.textContent = event.kind || 'event';\n+ const message = document.createElement('span');\n+ message.className = 'event-message';\n+ message.textContent = event.message;\n+ row.append(when, kind, message);\n+ feed.prepend(row);\n+ while (feed.children.length > 200) feed.lastElementChild.remove();\n+}\n+\n+function applyState(event) {\n+ processStatus.textContent = event.message || 'Waiting for the next epoch';\n+ setProgress(event.progress);\n+ if (event.kind !== 'connection') addEvent(event);\n+}\n+\n+function connect() {\n+ if (source) return;\n+ source = new EventSource('/sse');\n+ connection.classList.remove('warn');\n+ connection.classList.add('live');\n+ connection.querySelector('span:last-child').textContent = 'connecting';\n+ play.disabled = true;\n+ pause.disabled = false;\n+ source.onopen = () => {\n+ connection.querySelector('span:last-child').textContent = 'live';\n+ };\n+ source.addEventListener('audit', event => applyState(JSON.parse(event.data)));\n+ source.onerror = () => {\n+ connection.classList.remove('live');\n+ connection.classList.add('warn');\n+ connection.querySelector('span:last-child').textContent = 'reconnecting';\n+ };\n+}\n+\n+function disconnect() {\n+ if (source) source.close();\n+ source = null;\n+ connection.classList.remove('live');\n+ connection.classList.add('warn');\n+ connection.querySelector('span:last-child').textContent = 'paused locally';\n+ play.disabled = false;\n+ pause.disabled = true;\n+}\n+\n+play.addEventListener('click', connect);\n+pause.addEventListener('click', disconnect);\n+initial.feed.forEach(addEvent);\n+processStatus.textContent = initial.process.message;\n+setProgress(initial.process.progress);\n+connect();\n+\"\"\"\n+\n+\n+@app.get(\"/watch\")\n+async def watch():\n+ initial = json.dumps(\n+ _watch_initial_state(), separators=(\",\", \":\")\n+ ).replace(\" 0\")\n \n- ;; 9. SSE connects and sends initial event\n+ ;; 9. watch UI exposes progress, controls, readiness, and live SSE\n+ (println \"\\nchecking /watch UI…\")\n+ (bind watch-html (slurp (str base-url \"/watch\")))\n+ (assert! (str/includes? watch-html \"role=\\\"progressbar\\\"\")\n+ \"watch page has progress bar\")\n+ (assert! (str/includes? watch-html \"id=\\\"play\\\"\")\n+ \"watch page has play control\")\n+ (assert! (str/includes? watch-html \"id=\\\"pause\\\"\")\n+ \"watch page has pause control\")\n+ (assert! (str/includes? watch-html \"OpenRouter configured\")\n+ \"watch page reports council readiness\")\n+ (bind status-resp (get-json base-url \"/api/status\"))\n+ (assert! (true? (:openrouter_configured status-resp))\n+ \"status API reports OpenRouter configuration\")\n+\n+ ;; 10. SSE connects and sends initial event\n (println \"\\nchecking /sse initial event…\")\n (bind sse-events (read-sse-events (str base-url \"/sse\") 1 5000))\n (assert! (= 1 (count sse-events)) \"received 1 SSE event\")\n (assert! (not (str/blank? (first sse-events)))\n \"initial SSE event contains executable audit data\")\n \n- ;; 10. POST /test/emit — full ranking pipeline hits mocks\n+ ;; 11. POST /test/emit — full ranking pipeline hits mocks\n (println \"\\ntriggering /test/emit (epoch 1)…\")\n (bind emit-resp (post-json! base-url \"/test/emit\"))\n (assert! (= \"emission\" (:type emit-resp)) \"emit response type is emission\")\n@@ -503,7 +518,7 @@\n (bind rank-after (get-json base-url \"/api/ranking\"))\n (assert! (= 1 (:epoch rank-after)) \"latest ranking is epoch 1\")\n \n- ;; 11. kill and restart — prove replay determinism\n+ ;; 12. kill and restart — prove replay determinism\n (println \"\\nkilling server for replay test…\")\n (.destroyForcibly (:proc server))\n (deref server)\ndiff --git a/tests/test_git_discovery.py b/tests/test_git_discovery.py\nindex 0dd31bc42a19bc8c59842dc61f193c595c474659..5a9e167e16ad2ffb25988af85820f6f19e8910cd 100644\n--- a/tests/test_git_discovery.py\n+++ b/tests/test_git_discovery.py\n@@ -393,7 +393,9 @@ def test_empty_epoch_records_zero_emission_without_burning_pool(\n monkeypatch.setattr(c, \"store\", c.JsonlStore(discovery_config / \"ledger.jsonl\"))\n \n async def discover(_epoch, _boundary):\n- return SimpleNamespace(commits=[], snapshot_id=\"empty-snapshot\")\n+ return SimpleNamespace(\n+ observations=[], commits=[], snapshot_id=\"empty-snapshot\"\n+ )\n \n async def rank(_commits):\n return {}, []\n@@ -412,7 +414,11 @@ def test_emission_distribution_sums_exactly_to_total(\n monkeypatch.setattr(c, \"store\", c.JsonlStore(discovery_config / \"ledger.jsonl\"))\n \n async def discover(_epoch, _boundary):\n- return SimpleNamespace(commits=[{\"x\": 1}], snapshot_id=\"ranked-snapshot\")\n+ return SimpleNamespace(\n+ observations=[{\"x\": 1}],\n+ commits=[{\"x\": 1}],\n+ snapshot_id=\"ranked-snapshot\",\n+ )\n \n async def rank(_commits):\n return {\n@@ -454,6 +460,7 @@ def test_any_council_failure_aborts_ranking(monkeypatch):\n \n monkeypatch.setattr(c, \"fetch_top_models\", models)\n monkeypatch.setattr(c, \"llm_pairwise_compare\", compare)\n+ monkeypatch.setattr(c, \"OPENROUTER_API_KEY\", \"test-key\")\n commits = [\n {\n \"contributor\": contributor,\n@@ -465,3 +472,54 @@ def test_any_council_failure_aborts_ranking(monkeypatch):\n ]\n with pytest.raises(RuntimeError, match=\"council model failed\"):\n asyncio.run(c.rank_commits(commits))\n+\n+\n+def test_contested_ranking_requires_openrouter_key(monkeypatch):\n+ monkeypatch.setattr(c, \"OPENROUTER_API_KEY\", \"\")\n+ commits = [\n+ {\n+ \"contributor\": contributor,\n+ \"oid\": \"sha1:\" + char * 40,\n+ \"message\": contributor,\n+ \"patch\": \"patch\",\n+ }\n+ for contributor, char in [(\"alice\", \"a\"), (\"bob\", \"b\")]\n+ ]\n+ with pytest.raises(RuntimeError, match=\"OPENROUTER_API_KEY\"):\n+ asyncio.run(c.rank_commits(commits))\n+\n+\n+def test_watch_page_has_live_controls_progress_and_key_warning(\n+ discovery_config, monkeypatch\n+):\n+ monkeypatch.setattr(c, \"store\", c.JsonlStore(discovery_config / \"ledger.jsonl\"))\n+ monkeypatch.setattr(c, \"OPENROUTER_API_KEY\", \"\")\n+ monkeypatch.setattr(c, \"current_epoch\", lambda: (3, 0, 1))\n+ response = asyncio.run(c.watch())\n+ html = response.body.decode()\n+ assert 'role=\"progressbar\"' in html\n+ assert 'id=\"play\"' in html\n+ assert 'id=\"pause\"' in html\n+ assert \"new EventSource('/sse')\" in html\n+ assert \"OpenRouter key missing\" in html\n+\n+\n+def test_audit_events_are_json_sse_and_update_process_state(monkeypatch):\n+ clients = []\n+ history = []\n+ monkeypatch.setattr(c, \"SSE_CLIENTS\", clients)\n+ monkeypatch.setattr(c, \"AUDIT_HISTORY\", history)\n+ queue = asyncio.Queue()\n+ clients.append(queue)\n+\n+ async def emit():\n+ event = await c.broadcast_audit(\n+ \"progress\", \"halfway\", progress=50, phase=\"ranking\"\n+ )\n+ return event, await queue.get()\n+\n+ event, wire = asyncio.run(emit())\n+ assert event[\"progress\"] == 50\n+ assert event[\"phase\"] == \"ranking\"\n+ assert wire.startswith(\"event: audit\\ndata: {\")\n+ assert '\"message\":\"halfway\"' in wire\n","role":"user"}],"model":"~x-ai/grok-latest"}