{"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[08565bea] Tokenize prose refs for garden URL links (#147)\n\n* Tokenize prose refs for garden URL links\n\nCo-authored-by: tommy \n\n* Stop prose URLs at line boundaries\n\nCo-authored-by: tommy \n\n* Require braced DSL item bodies\n\nCo-authored-by: tommy \n\n---------\n\nCo-authored-by: Cursor Agent \n\nSide A — unified diff (full patch):\ndiff --git a/server/src/dsl.rs b/server/src/dsl.rs\nindex 4203c2f59dd8825d7a91513c4023f3ccd37f1efc..b3c785674560a0b42a7f4c3aa13d80cd350f485b 100644\n--- a/server/src/dsl.rs\n+++ b/server/src/dsl.rs\n@@ -1,7 +1,5 @@\n use std::collections::HashMap;\n \n-use rand::Rng;\n-\n /// Parsed DSL document.\n #[derive(Debug, Clone, PartialEq, Eq)]\n pub struct Document {\n@@ -39,31 +37,57 @@ pub enum DslError {\n /// Matches the legacy Python parser behavior:\n /// - Supports toggle markers (open == close), e.g. ```...```\n /// - Supports nested markers (open != close), e.g. { ... { ... } ... }\n+#[derive(Debug, Clone, Copy, PartialEq, Eq)]\n+pub enum BlockKind {\n+ CodeFence,\n+ DoubleBrace,\n+ Brace,\n+}\n+\n+#[derive(Debug, Clone, PartialEq, Eq)]\n+struct MaskedBlock {\n+ kind: BlockKind,\n+}\n+\n #[derive(Debug, Default, Clone)]\n pub struct BlockMasker {\n pub replacements: HashMap,\n+ blocks: HashMap,\n+ next_id: u32,\n }\n \n impl BlockMasker {\n pub fn new() -> Self {\n Self {\n replacements: HashMap::new(),\n+ blocks: HashMap::new(),\n+ next_id: 0,\n }\n }\n \n- fn new_token(&mut self) -> String {\n- let mut rng = rand::thread_rng();\n- let n: u32 = rng.gen();\n- let token = format!(\"__BLOCK_{:08x}__\", n);\n- // Extremely unlikely collision; if it happens, regenerate.\n- if self.replacements.contains_key(&token) {\n- return self.new_token();\n+ fn new_token(&mut self, haystack: &str) -> String {\n+ loop {\n+ let token = format!(\"__BLOCK_{:08x}__\", self.next_id);\n+ self.next_id = self.next_id.wrapping_add(1);\n+ if !self.replacements.contains_key(&token) && !haystack.contains(&token) {\n+ return token;\n+ }\n }\n- token\n }\n \n /// Replace outermost balanced blocks with tokens.\n pub fn mask(&mut self, text: &str, open_marker: &str, close_marker: &str) -> String {\n+ self.mask_kind(text, open_marker, close_marker, BlockKind::Brace)\n+ }\n+\n+ /// Replace outermost balanced blocks with typed deterministic tokens.\n+ pub fn mask_kind(\n+ &mut self,\n+ text: &str,\n+ open_marker: &str,\n+ close_marker: &str,\n+ kind: BlockKind,\n+ ) -> String {\n if text.is_empty() {\n return text.to_string();\n }\n@@ -97,9 +121,10 @@ impl BlockMasker {\n // Found end of outermost block\n let s = start_idx.max(0) as usize;\n let original_block = &text[s..i];\n- let token = self.new_token();\n+ let token = self.new_token(text);\n self.replacements\n .insert(token.clone(), original_block.to_string());\n+ self.blocks.insert(token.clone(), MaskedBlock { kind });\n result_parts.push(token);\n current_idx = i;\n }\n@@ -176,13 +201,22 @@ impl BlockMasker {\n }\n token.to_string()\n }\n+\n+ pub fn block_kind(&self, token: &str) -> Option {\n+ self.blocks.get(token).map(|b| b.kind)\n+ }\n }\n \n fn mask_all(mut masker: BlockMasker, text: &str) -> (BlockMasker, String) {\n // Mask hierarchy: Code -> Double Brace -> Single Brace.\n- let t = masker.mask(text, \"```\", \"```\");\n- let t = masker.mask(&t, \"{{\", \"}}\");\n- let t = masker.mask(&t, \"{\", \"}\");\n+ let t = masker.mask_kind(text, \"```\", \"```\", BlockKind::CodeFence);\n+ let t = masker.mask_kind(&t, \"{{\", \"}}\", BlockKind::DoubleBrace);\n+ let t = masker.mask_kind(&t, \"{\", \"}\", BlockKind::Brace);\n+ (masker, t)\n+}\n+\n+fn mask_code_fences(mut masker: BlockMasker, text: &str) -> (BlockMasker, String) {\n+ let t = masker.mask_kind(text, \"```\", \"```\", BlockKind::CodeFence);\n (masker, t)\n }\n \n@@ -253,7 +287,34 @@ fn skip_ws(s: &str, mut i: usize) -> usize {\n i\n }\n \n-fn parse_item_name_at(s: &str, i: usize) -> Option<(String, usize)> {\n+#[derive(Debug, Clone, PartialEq, Eq)]\n+pub enum ProseToken {\n+ Text(String),\n+ ItemRef(String),\n+}\n+\n+fn trim_prose_item_ref_end(s: &str, mut end: usize) -> usize {\n+ while end > 0 {\n+ let Some((idx, c)) = s[..end].char_indices().next_back() else {\n+ break;\n+ };\n+ if matches!(\n+ c,\n+ '.' | ',' | ';' | ':' | '!' | '?' | ')' | ']' | '}' | '\"' | '\\''\n+ ) {\n+ end = idx;\n+ } else {\n+ break;\n+ }\n+ }\n+ end\n+}\n+\n+fn parse_item_name_at_with_mode(\n+ s: &str,\n+ i: usize,\n+ trim_trailing_punctuation: bool,\n+) -> Option<(String, usize)> {\n let bytes = s.as_bytes();\n if i >= bytes.len() {\n return None;\n@@ -263,6 +324,9 @@ fn parse_item_name_at(s: &str, i: usize) -> Option<(String, usize)> {\n if s[i..].starts_with(\"https://\") || s[i..].starts_with(\"http://\") {\n let mut j = i;\n while j < bytes.len() {\n+ if trim_trailing_punctuation && bytes[j] == b'\\n' {\n+ break;\n+ }\n if bytes[j..].starts_with(b\"__BLOCK_\") || is_ws_byte(bytes[j]) {\n break;\n }\n@@ -271,6 +335,12 @@ fn parse_item_name_at(s: &str, i: usize) -> Option<(String, usize)> {\n if j <= i {\n return None;\n }\n+ if trim_trailing_punctuation {\n+ j = trim_prose_item_ref_end(s, j);\n+ if j <= i {\n+ return None;\n+ }\n+ }\n return Some((s[i..j].to_string(), j));\n }\n \n@@ -296,6 +366,12 @@ fn parse_item_name_at(s: &str, i: usize) -> Option<(String, usize)> {\n if j <= i + 2 {\n return None;\n }\n+ if trim_trailing_punctuation {\n+ j = trim_prose_item_ref_end(s, j);\n+ if j <= i + 2 {\n+ return None;\n+ }\n+ }\n let raw = &s[i..j];\n if !is_item_name(raw) {\n return None;\n@@ -336,6 +412,46 @@ fn parse_item_name_at(s: &str, i: usize) -> Option<(String, usize)> {\n Some((format!(\"~/{}\", name), j))\n }\n \n+fn parse_item_name_at(s: &str, i: usize) -> Option<(String, usize)> {\n+ parse_item_name_at_with_mode(s, i, false)\n+}\n+\n+pub fn parse_prose_item_ref_at(s: &str, i: usize) -> Option<(String, usize)> {\n+ parse_item_name_at_with_mode(s, i, true)\n+}\n+\n+pub fn tokenize_prose_item_refs(text: &str) -> Vec {\n+ if text.is_empty() {\n+ return Vec::new();\n+ }\n+ let (masker, masked) = mask_code_fences(BlockMasker::new(), text);\n+ let mut tokens = Vec::new();\n+ let mut text_start = 0usize;\n+ let mut i = 0usize;\n+\n+ while i < masked.len() {\n+ if let Some((raw, end)) = parse_prose_item_ref_at(&masked, i) {\n+ if text_start < i {\n+ tokens.push(ProseToken::Text(masker.unmask(&masked[text_start..i])));\n+ }\n+ tokens.push(ProseToken::ItemRef(masker.unmask(&raw)));\n+ i = end;\n+ text_start = i;\n+ continue;\n+ }\n+\n+ let Some((_, c)) = masked[i..].char_indices().next() else {\n+ break;\n+ };\n+ i += c.len_utf8();\n+ }\n+\n+ if text_start < masked.len() {\n+ tokens.push(ProseToken::Text(masker.unmask(&masked[text_start..])));\n+ }\n+ tokens\n+}\n+\n fn parse_block_token_at(s: &str, i: usize) -> Option<(String, usize)> {\n let bytes = s.as_bytes();\n if i >= bytes.len() {\n@@ -401,6 +517,12 @@ fn parse_block_prefixed_statement(\n tail: &str,\n masker: &BlockMasker,\n ) -> Result {\n+ if masker.block_kind(block_token) == Some(BlockKind::CodeFence) {\n+ return Err(DslError::Parse(\n+ \"vote explanations must use `{ ... }`; code fences belong inside body blocks\"\n+ .to_string(),\n+ ));\n+ }\n // vote: block item_ref comparison item_ref\n let s = tail.trim_start();\n if s.is_empty() {\n@@ -462,6 +584,11 @@ fn parse_item_definition_statement(stripped: &str, masker: &BlockMasker) -> Resu\n }\n \n if let Some((tok, end)) = parse_block_token_at(stripped, i) {\n+ if masker.block_kind(&tok) == Some(BlockKind::CodeFence) {\n+ return Err(DslError::Parse(\n+ \"item bodies must use `{ ... }`; code fences belong inside body blocks\".to_string(),\n+ ));\n+ }\n let body = masker.extract_body(&tok);\n let tail = stripped[end..].trim();\n if !tail.is_empty() {\n@@ -572,6 +699,10 @@ pub fn parse_full(text: &str) -> Result {\n \n if let Some((tok, end)) = parse_block_token_at(stripped, 0) {\n if stripped[end..].trim().is_empty() {\n+ if masker.block_kind(&tok) == Some(BlockKind::CodeFence) {\n+ prose_buffer.push(line);\n+ continue;\n+ }\n pending_block = Some(tok);\n continue;\n }\n@@ -619,6 +750,70 @@ mod tests {\n assert_eq!(roundtrip, input);\n }\n \n+ #[test]\n+ fn blockmasker_tokens_are_deterministic_and_typed() {\n+ let input = \"x ```code``` y {body}\";\n+ let (masker, masked) = mask_all(BlockMasker::new(), input);\n+ assert!(masked.contains(\"__BLOCK_00000000__\"));\n+ assert!(masked.contains(\"__BLOCK_00000001__\"));\n+ assert_eq!(\n+ masker.block_kind(\"__BLOCK_00000000__\"),\n+ Some(BlockKind::CodeFence)\n+ );\n+ assert_eq!(\n+ masker.block_kind(\"__BLOCK_00000001__\"),\n+ Some(BlockKind::Brace)\n+ );\n+ assert_eq!(masker.unmask(&masked), input);\n+ }\n+\n+ #[test]\n+ fn prose_tokenizer_finds_tilde_dash_and_raw_url_refs() {\n+ let tokens =\n+ tokenize_prose_item_refs(\"see ~/a/b then -/example.com/x and https://Example.com/A/B.\");\n+ assert_eq!(\n+ tokens,\n+ vec![\n+ ProseToken::Text(\"see \".to_string()),\n+ ProseToken::ItemRef(\"~/a/b\".to_string()),\n+ ProseToken::Text(\" then \".to_string()),\n+ ProseToken::ItemRef(\"-/example.com/x\".to_string()),\n+ ProseToken::Text(\" and \".to_string()),\n+ ProseToken::ItemRef(\"https://Example.com/A/B\".to_string()),\n+ ProseToken::Text(\".\".to_string()),\n+ ]\n+ );\n+ }\n+\n+ #[test]\n+ fn prose_tokenizer_stops_raw_urls_at_newlines() {\n+ let tokens = tokenize_prose_item_refs(\"https://example.com/a/b.\\n-/example.com/a/b\");\n+ assert_eq!(\n+ tokens,\n+ vec![\n+ ProseToken::ItemRef(\"https://example.com/a/b\".to_string()),\n+ ProseToken::Text(\".\\n\".to_string()),\n+ ProseToken::ItemRef(\"-/example.com/a/b\".to_string()),\n+ ]\n+ );\n+ }\n+\n+ #[test]\n+ fn prose_tokenizer_does_not_linkify_inside_code_fences() {\n+ let tokens = tokenize_prose_item_refs(\n+ \"before ```json\\n{\\\"url\\\":\\\"https://example.com\\\"}\\n``` after ~/x\",\n+ );\n+ assert_eq!(\n+ tokens,\n+ vec![\n+ ProseToken::Text(\n+ \"before ```json\\n{\\\"url\\\":\\\"https://example.com\\\"}\\n``` after \".to_string()\n+ ),\n+ ProseToken::ItemRef(\"~/x\".to_string()),\n+ ]\n+ );\n+ }\n+\n #[test]\n fn parse_item_with_body_strips_outer_braces() {\n let input = \"~/rust { Systems language }\";\n@@ -633,8 +828,8 @@ mod tests {\n }\n \n #[test]\n- fn parse_item_with_fenced_json_body_preserves_braces() {\n- let input = \"~/item/in/url ```json\\n{\\\"test\\\": true}\\n```\";\n+ fn parse_item_with_braced_fenced_json_body_preserves_braces() {\n+ let input = \"~/item/in/url {\\n```json\\n{\\\"test\\\": true}\\n```\\n}\";\n let doc = parse_full(input).unwrap();\n assert_eq!(\n doc.statements,\n@@ -645,6 +840,51 @@ mod tests {\n );\n }\n \n+ #[test]\n+ fn parse_rejects_singleton_fenced_json_item_body() {\n+ let input = \"~/item/in/url ```json\\n{\\\"test\\\": true}\\n```\";\n+ let err = parse_full(input).unwrap_err().to_string();\n+ assert!(\n+ err.contains(\"item bodies must use\"),\n+ \"unexpected error: {err}\"\n+ );\n+ }\n+\n+ #[test]\n+ fn parse_keeps_standalone_code_fence_as_prose() {\n+ let input = \"```json\\n{\\\"test\\\": true}\\n```\";\n+ let doc = parse_full(input).unwrap();\n+ assert_eq!(\n+ doc.statements,\n+ vec![Stmt::Prose {\n+ text: input.to_string(),\n+ }]\n+ );\n+ }\n+\n+ #[test]\n+ fn parse_rejects_code_fence_vote_explanation() {\n+ let input = \"```json\\n{\\\"why\\\": true}\\n```\\n~/a 2:1 ~/b\";\n+ let err = parse_full(input).unwrap_err().to_string();\n+ assert!(\n+ err.contains(\"vote explanations must start\"),\n+ \"unexpected error: {err}\"\n+ );\n+ }\n+\n+ #[test]\n+ fn parse_raw_url_item_with_braced_fenced_json_body() {\n+ let input = \"https://example.com/itembody/slug {\\n```json\\n{\\\"test\\\": true}\\n```\\n}\";\n+ let doc = parse_full(input).unwrap();\n+ assert_eq!(\n+ doc.statements,\n+ vec![Stmt::Item {\n+ title: \"https://example.com/itembody/slug\".to_string(),\n+ body: Some(\"```json\\n{\\\"test\\\": true}\\n```\".to_string()),\n+ }]\n+ );\n+ }\n+\n #[test]\n fn parse_vote_ratio_and_symbols() {\n let d1 = parse_full(\"{because}\\n~/a 3:1 ~/b\").unwrap();\ndiff --git a/server/src/external_resolver.rs b/server/src/external_resolver.rs\nindex 8481f1fbff1c4265da182a225f539f97d6829002..04bc3de32b6df1aefe197d942db67de2cbdbde4f 100644\n--- a/server/src/external_resolver.rs\n+++ b/server/src/external_resolver.rs\n@@ -256,7 +256,7 @@ fn children_to_dsl(children: &[ResolvedChild]) -> String {\n .filter(|s| !s.trim().is_empty())\n .unwrap_or(child.title.as_str());\n if body.trim_start().starts_with(\"```\") {\n- out.push_str(&format!(\"{} {}\\n\\n\", child.url, body.trim()));\n+ out.push_str(&format!(\"{} {{\\n{}\\n}}\\n\\n\", child.url, body.trim()));\n } else {\n out.push_str(&format!(\n \"{} {{\\n{}\\n}}\\n\\n\",\n@@ -378,7 +378,8 @@ mod tests {\n title: \"#1 title\".into(),\n body: Some(\"```json\\n{\\\"test\\\": true}\\n```\".into()),\n }]);\n- assert!(dsl.contains(\"https://github.com/o/r/issues/1 ```json\"));\n+ assert!(dsl.contains(\"https://github.com/o/r/issues/1 {\\n```json\"));\n assert!(dsl.contains(\"{\\\"test\\\": true}\"));\n+ assert!(dsl.contains(\"```\\n}\\n\"));\n }\n }\ndiff --git a/server/src/html/breadcrumb_path.rs b/server/src/html/breadcrumb_path.rs\nindex 3e949ce2cb70de3f024f46af773a93f3f8852260..e48612d7d3c4df52c161499a11865d4caca607aa 100644\n--- a/server/src/html/breadcrumb_path.rs\n+++ b/server/src/html/breadcrumb_path.rs\n@@ -88,16 +88,12 @@ impl ExternalOntologyPath {\n .filter(|x| !x.is_empty())\n .map(|x| x.to_string())\n .collect();\n- let segments = if segments == [\".\"] {\n- vec![]\n- } else {\n- segments\n- };\n+ let segments = if segments == [\".\"] { vec![] } else { segments };\n Self { item, segments }\n }\n \n pub(super) fn is_root(&self) -> bool {\n- self.segments.len() <= 1\n+ self.segments.is_empty()\n }\n \n pub(super) fn segments(&self) -> &[String] {\n@@ -108,3 +104,28 @@ impl ExternalOntologyPath {\n self.item.as_str()\n }\n }\n+\n+#[cfg(test)]\n+mod tests {\n+ use super::*;\n+\n+ #[test]\n+ fn external_root_and_host_paths_are_distinct() {\n+ let root = ExternalOntologyPath::from_input(\"\");\n+ assert!(root.is_root());\n+ assert!(root.segments().is_empty());\n+\n+ let host = ExternalOntologyPath::from_input(\"example.com\");\n+ assert!(!host.is_root());\n+ assert_eq!(host.segments(), &[\"example.com\".to_string()]);\n+ }\n+\n+ #[test]\n+ fn external_path_keeps_each_url_segment_for_breadcrumbs() {\n+ let path = ExternalOntologyPath::from_input(\"https://example.com/a/b\");\n+ assert_eq!(\n+ path.segments(),\n+ &[\"example.com\".to_string(), \"a\".to_string(), \"b\".to_string()]\n+ );\n+ }\n+}\ndiff --git a/server/src/html/mod.rs b/server/src/html/mod.rs\nindex 8876a1a00a16ee3bf7a371f7a5ca27b5862b62cc..d5877eeb3632ed5d770f23a04cb4d1881209bc74 100644\n--- a/server/src/html/mod.rs\n+++ b/server/src/html/mod.rs\n@@ -20,27 +20,30 @@ mod search;\n pub mod ui_action;\n use breadcrumb_path::{ExternalOntologyPath, OntologyPath};\n \n-pub use auth::{auth_complete_page, auth_signed_in_fragment, choose_username_error_fragment, choose_username_page};\n+pub use auth::{\n+ auth_complete_page, auth_signed_in_fragment, choose_username_error_fragment,\n+ choose_username_page,\n+};\n pub use editor::{editor_check, editor_page};\n pub use forum::{\n home, room_page, room_thread_post_view, room_thread_view, thread_feed_html,\n thread_feed_html_for_room, thread_feed_region_markup, thread_post_view, thread_view, ThreadNav,\n };\n \n+pub use forum::user_profile_page;\n pub(crate) use forum::{\n fragment_new_thread_slot, login_to_post_hint_markup, room_members_section_markup,\n thread_ui_collapse_redacted_post, thread_ui_expand_post_full, thread_ui_expand_redacted_post,\n user_can_post_room, user_can_view_room,\n };\n+pub(crate) use garden::{encode_pin_cookie_value, vote_compare_post_success_js, GARDEN_PIN_COOKIE};\n pub use garden::{\n external_garden_index, external_ontology_path, garden_index, ontology_path,\n- room_external_garden_index, room_external_ontology_path, room_garden_index,\n- room_ontology_path, room_vote_compare_page, vote_compare_page,\n+ room_external_garden_index, room_external_ontology_path, room_garden_index, room_ontology_path,\n+ room_vote_compare_page, vote_compare_page,\n };\n-pub(crate) use garden::{encode_pin_cookie_value, vote_compare_post_success_js, GARDEN_PIN_COOKIE};\n pub use routing::RouteContext;\n pub use search::{search_page, search_results_fragment};\n-pub use forum::user_profile_page;\n pub use ui_action::{parse_html_ui_from_form, HtmlUiAction, HtmlUiParseError, UI_RPC_FIELD};\n \n /// Public profile URL path for a stored username (no `@`).\n@@ -107,8 +110,8 @@ pub struct ThemeForm {\n pub async fn post_theme(Form(form): Form) -> impl IntoResponse {\n let theme = normalize_theme(&form.theme);\n let next = sanitize_theme_next(form.next.as_deref());\n- let loc = HeaderValue::try_from(next.as_str())\n- .unwrap_or_else(|_| HeaderValue::from_static(\"/\"));\n+ let loc =\n+ HeaderValue::try_from(next.as_str()).unwrap_or_else(|_| HeaderValue::from_static(\"/\"));\n Response::builder()\n .status(StatusCode::SEE_OTHER)\n .header(header::LOCATION, loc)\n@@ -179,7 +182,9 @@ pub(crate) struct JsQueryBuilder {\n \n impl JsBuilder {\n pub(crate) fn new() -> Self {\n- Self { snippets: Vec::new() }\n+ Self {\n+ snippets: Vec::new(),\n+ }\n }\n \n pub(crate) fn morph_selector(self, selector: &str, markup: Markup) -> Self {\n@@ -195,7 +200,12 @@ impl JsBuilder {\n self.qs(selector).morph_inner(markup)\n }\n \n- pub(crate) fn morph_expr(mut self, expr: &str, markup: Markup, morph_style: Option<&str>) -> Self {\n+ pub(crate) fn morph_expr(\n+ mut self,\n+ expr: &str,\n+ markup: Markup,\n+ morph_style: Option<&str>,\n+ ) -> Self {\n let html = js_string_literal(&markup.into_string());\n let opts = morph_style\n .map(|style| format!(\", {{morphStyle: {}}}\", js_string_literal(style)))\n@@ -217,7 +227,11 @@ impl JsBuilder {\n self.qs(&format!(\"#{id}\"))\n }\n \n- pub(crate) fn if_current_path_matches(mut self, path: &str, f: impl FnOnce(JsBuilder) -> JsBuilder) -> Self {\n+ pub(crate) fn if_current_path_matches(\n+ mut self,\n+ path: &str,\n+ f: impl FnOnce(JsBuilder) -> JsBuilder,\n+ ) -> Self {\n let inner = f(JsBuilder::new()).build();\n self.snippets.push(format!(\n \"var __slugHere = window.location.pathname + window.location.search; var __slugPath = {path}; if (__slugHere === __slugPath || __slugHere.indexOf(__slugPath + '?') === 0) {{ {inner} }}\",\n@@ -226,7 +240,11 @@ impl JsBuilder {\n self\n }\n \n- pub(crate) fn if_current_path_not_matches(mut self, path: &str, f: impl FnOnce(JsBuilder) -> JsBuilder) -> Self {\n+ pub(crate) fn if_current_path_not_matches(\n+ mut self,\n+ path: &str,\n+ f: impl FnOnce(JsBuilder) -> JsBuilder,\n+ ) -> Self {\n let inner = f(JsBuilder::new()).build();\n self.snippets.push(format!(\n \"var __slugHere = window.location.pathname + window.location.search; var __slugPath = {path}; if (!(__slugHere === __slugPath || __slugHere.indexOf(__slugPath + '?') === 0)) {{ {inner} }}\",\n@@ -301,7 +319,17 @@ pub(super) fn layout(\n garden_room_wire: Option<&str>,\n garden_path_prefix: Option<&str>,\n ) -> Markup {\n- layout_embed_controls(title, view, body, views, theme, theme_next, garden_room_wire, garden_path_prefix, true)\n+ layout_embed_controls(\n+ title,\n+ view,\n+ body,\n+ views,\n+ theme,\n+ theme_next,\n+ garden_room_wire,\n+ garden_path_prefix,\n+ true,\n+ )\n }\n \n /// Minimal document shell: no bottom controls, no garden HUD data attributes (`data-garden-room` /\n@@ -315,15 +343,7 @@ pub(super) fn layout_full_bleed_chromeless(\n theme_next: &str,\n ) -> Markup {\n layout_embed_controls(\n- title,\n- view,\n- body,\n- views,\n- theme,\n- theme_next,\n- None,\n- None,\n- false,\n+ title, view, body, views, theme, theme_next, None, None, false,\n )\n }\n \n@@ -545,7 +565,58 @@ fn item_body_title_snippet(body: &str) -> Option {\n Some(format!(\"{truncated}{ellipsis}\"))\n }\n \n-/// Replace ~/path slugs in raw text with clickable links.\n+fn garden_href_for_item_ref(\n+ raw_ref: &str,\n+ garden_prefix: &str,\n+) -> Option<(crate::path_types::ItemId, String)> {\n+ let key = slug_types::canonicalize_item(raw_ref);\n+ let id = crate::path_types::ItemId::parse(&key)?;\n+ let href = if let Some(tail) = id.tilde_tail() {\n+ if tail.is_empty() {\n+ garden_prefix.trim_end_matches('/').to_string()\n+ } else {\n+ format!(\"{}/{}\", garden_prefix.trim_end_matches('/'), tail)\n+ }\n+ } else if id.as_str().starts_with(\"https://\") || id.as_str().starts_with(\"http://\") {\n+ let display = id.display_path();\n+ let rest = display.strip_prefix(\"-/\").unwrap_or(display.as_str());\n+ let ext_prefix = format!(\"{}-\", garden_prefix.trim_end_matches('~'));\n+ format!(\"{}/{}\", ext_prefix, rest)\n+ } else {\n+ return None;\n+ };\n+ Some((id, href))\n+}\n+\n+fn push_item_ref_anchor(\n+ out: &mut String,\n+ raw_ref: &str,\n+ garden_prefix: &str,\n+ item_bodies: Option<&HashMap>,\n+) -> bool {\n+ let Some((id, href)) = garden_href_for_item_ref(raw_ref, garden_prefix) else {\n+ return false;\n+ };\n+ out.push_str(r#\"');\n+ out.push_str(&escape_html(raw_ref));\n+ out.push_str(\"\");\n+ true\n+}\n+\n+/// Replace item refs in raw prose with clickable garden links.\n ///\n /// When `item_bodies` is set, matching ontology items get a `title` attribute with a truncated\n /// body preview for native browser tooltips (forum posts, item pages).\n@@ -554,53 +625,16 @@ pub(super) fn linkify_slugs_with_prefix(\n garden_prefix: &str,\n item_bodies: Option<&HashMap>,\n ) -> String {\n- let escaped = escape_html(raw);\n- let mut out = String::with_capacity(escaped.len() + 64);\n- let mut i = 0;\n- let s = escaped.as_str();\n- while i < s.len() {\n- let rest = &s[i..];\n- if let Some(after_tilde) = rest.strip_prefix(\"~/\") {\n- let path_len = after_tilde\n- .chars()\n- .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-' || *c == '/')\n- .map(|c| c.len_utf8())\n- .sum::();\n- if path_len > 0 {\n- let path = &after_tilde[..path_len];\n- out.push_str(r#\" out.push_str(&escape_html(&text)),\n+ crate::dsl::ProseToken::ItemRef(raw_ref) => {\n+ if !push_item_ref_anchor(&mut out, &raw_ref, garden_prefix, item_bodies) {\n+ out.push_str(&escape_html(&raw_ref));\n }\n- out.push('>');\n- out.push_str(\"~/\");\n- out.push_str(path);\n- out.push_str(\"\");\n- i += 2 + path_len;\n- continue;\n }\n }\n- if let Some((j, c)) = rest.char_indices().next() {\n- out.push(c);\n- i += j + c.len_utf8();\n- } else {\n- break;\n- }\n }\n out\n }\n@@ -638,7 +672,13 @@ fn spotify_embed_src(url: &str) -> Option {\n if !(host == \"open.spotify.com\" || host == \"www.open.spotify.com\") {\n return None;\n }\n- let path = tail.split('#').next().unwrap_or(tail).split('?').next().unwrap_or(tail);\n+ let path = tail\n+ .split('#')\n+ .next()\n+ .unwrap_or(tail)\n+ .split('?')\n+ .next()\n+ .unwrap_or(tail);\n let mut segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();\n if segs.first().is_some_and(|s| s.starts_with(\"intl-\")) {\n segs.remove(0);\n@@ -670,8 +710,16 @@ fn youtube_embed_src(url: &str) -> Option {\n let host = host.to_lowercase();\n \n let video_id = if host == \"youtu.be\" || host == \"www.youtu.be\" {\n- clean_media_id(tail.split(['?', '#']).next().unwrap_or(tail).trim_matches('/'))\n- } else if matches!(host.as_str(), \"youtube.com\" | \"www.youtube.com\" | \"m.youtube.com\" | \"music.youtube.com\") {\n+ clean_media_id(\n+ tail.split(['?', '#'])\n+ .next()\n+ .unwrap_or(tail)\n+ .trim_matches('/'),\n+ )\n+ } else if matches!(\n+ host.as_str(),\n+ \"youtube.com\" | \"www.youtube.com\" | \"m.youtube.com\" | \"music.youtube.com\"\n+ ) {\n let path = format!(\"/{}\", tail.split('#').next().unwrap_or(tail));\n if path.starts_with(\"/watch\") {\n clean_media_id(&query_param(url, \"v\")?)\n@@ -745,10 +793,7 @@ pub(super) fn render_linkified_with_embeds_in_scope(\n /// CLI strings are embedded in a single-quoted JS literal; they must never need escaping.\n fn assert_cli_panel_cmd_js_single_quote_safe(s: &str) {\n assert!(\n- !s.contains('\\\\')\n- && !s.contains('\\'')\n- && !s.contains('\\n')\n- && !s.contains('\\r'),\n+ !s.contains('\\\\') && !s.contains('\\'') && !s.contains('\\n') && !s.contains('\\r'),\n \"cli_panel cmd must not contain `\\\\`, `'`, or newlines (got {s:?})\"\n );\n }\n@@ -805,15 +850,40 @@ mod linkify_title_tests {\n let mut bodies = HashMap::new();\n let key = ItemId::parse(&slug_types::canonicalize_item(\"~/foo/bar\")).unwrap();\n bodies.insert(key, \"Hello world\\nline\".to_string());\n- let html = linkify_slugs_with_prefix(\n- \"see ~/foo/bar ok\",\n- \"/r/x/~\",\n- Some(&bodies),\n- );\n+ let html = linkify_slugs_with_prefix(\"see ~/foo/bar ok\", \"/r/x/~\", Some(&bodies));\n assert!(html.contains(\"title=\\\"Hello world line\\\"\"));\n assert!(html.contains(\"href=\\\"/r/x/~/foo/bar\\\"\"));\n }\n \n+ #[test]\n+ fn raw_url_links_to_public_external_garden_page() {\n+ let html = linkify_slugs_with_prefix(\"see https://example.com/z.\", \"/~\", None);\n+ assert!(html\n+ .contains(r#\"https://example.com/z.\"#));\n+ }\n+\n+ #[test]\n+ fn dash_ref_links_to_room_external_garden_page_with_title() {\n+ let mut bodies = HashMap::new();\n+ let key = ItemId::parse(&slug_types::canonicalize_item(\"-/example.com/z\")).unwrap();\n+ bodies.insert(key, \"External body\\npreview\".to_string());\n+ let html =\n+ linkify_slugs_with_prefix(\"see -/example.com/z\", \"/r/9ab12cdroom/~\", Some(&bodies));\n+ assert!(html.contains(r#\"href=\"/r/9ab12cdroom/-/example.com/z\"\"#));\n+ assert!(html.contains(r#\"title=\"External body preview\"\"#));\n+ }\n+\n+ #[test]\n+ fn code_fence_urls_are_not_linkified() {\n+ let html = linkify_slugs_with_prefix(\n+ \"```json\\n{\\\"url\\\":\\\"https://example.com/z\\\"}\\n```\\nthen https://example.com/a\",\n+ \"/~\",\n+ None,\n+ );\n+ assert!(!html.contains(r#\"href=\"/-/example.com/z\"\"#));\n+ assert!(html.contains(r#\"href=\"/-/example.com/a\"\"#));\n+ }\n+\n #[test]\n fn no_title_when_body_missing_or_empty() {\n let html = linkify_slugs_with_prefix(\"x ~/a/b y\", \"/~\", Some(&HashMap::new()));\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":"openai/gpt-chat-latest"}