Side B removes a substantial legacy code path (dual GitDiscovery/Evidence projection logic across epoch/commit views), simplifying the data model to a single canonical evidence-envelope source of truth, with corresponding test updates reflecting the new invariant. Side A is a valuable but narrower bugfix (regex vs string split, request body stream fix, defensive nils, error handling) that restores test infrastructure correctness but doesn't change production architecture or reduce long-term maintenance burden as much.
constitution · epochs · watch · epoch 3
c_597d3f736194 (tommy-mor) vs c_6f04dcb2e38c (tommy-mor)
download prompt · raw event · cmp_79cd6fad529aba
council reasoning
B removes dual-path legacy GitDiscovery projection helpers and epoch/commit page fallbacks, making Emission fields required and forcing Evidence-envelope-only reads—a lasting schema cleanup that shrinks core surface area. A only patches test mocks (query split regex, getRequestBody, nil-safe token/state handling) plus minor Playwright selector tweaks so E2E auth runs again, which is useful but confined to test support.
Side B removes the legacy GitDiscovery projection path and makes the evidence model authoritative by requiring emission metadata fields, deleting fallback lookup code, and updating epoch/commit pages to rely only on Evidence events. Although it is a larger schema and UI cleanup that requires test updates, it simplifies long-term maintenance by eliminating dual code paths, whereas Side A primarily repairs OAuth test infrastructure with targeted fixes such as request parsing, redirect handling, null checks, and Playwright selector updates.
sides
A — c_597d3f736194 (tommy-mor)
message
[075d4d37] Fix OAuth test mocks so Clojure E2E auth flows work again. HttpServer handlers were crashing on query parsing and token POSTs, which broke Playwright login; also read alias/history via real CSS selectors. Co-authored-by: Cursor <cursoragent@cursor.com>
diff preview
diff --git a/test/auth_login.clj b/test/auth_login.clj
index 6f2f00d7aa7340e63d1ac465b0a2234cec7a983f..aa63b66ccb2471b710ba3d168d0461252b39fc10 100644
--- a/test/auth_login.clj
+++ b/test/auth_login.clj
@@ -14,27 +14,27 @@
(defn- type-alias! [pg text]
(page/evaluate pg
(.replace
- "(() => { const i = document.getElementById('alias-input'); const f = document.getElementById('alias-check-form'); if (!i || !f) return;
+ "(() => { const i = document.getElementById('alias-input'); const f = document.getElementById('alias-check-form'); if (!i || !f) return Promise.resolve('missing-form');
i.value = __TEXT__;
const cf = document.getElementById('alias-claim-field'); if (cf) cf.value = i.value;
return fetch(f.action, { method: 'POST', credentials: 'same-origin',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams(new FormData(f)).toString() })
.then(function (r) { return r.text(); })
- .then(function (t) { eval(t); }); })()"
+ .then(function (t) { eval(t); return document.getElementById('alias-status')?.textContent || ''; }); })()"
"__TEXT__"
- (pr-str text)))
- (Thread/sleep 400))
+ (pr-str text))))
-(defn- element-text [pg test-id]
+(defn- element-text [pg selector]
(let [raw (page/evaluate pg
- (str "document.querySelector('[data-testid=\"" test-id "\"]')?.textContent || ''"))]
+ (str "document.querySelector(" (pr-str selector) ")?.textContent || ''"))]
(when (string? raw) (str/trim raw))))
(defn- wait-for-text [pg test-id text timeout-ms]
- (let [deadline (+ (System/currentTimeMillis) timeout-ms)]
+ (let [deadline (+ (System/currentTimeMillis) timeout-ms)
+ selector (str "[data-testid=\"" test-id "\"]")]
(loop []
- (let [got (or (element-text pg test-id) "")]
+ (let [got (or (element-text pg selector) "")]
(cond
(= got text) got
(< (System/currentTimeMillis) deadline) (do (Thread/sleep 200) (recur))
diff --git a/test/support/mock_oauth.clj b/test/support/mock_oauth.clj
index 5ba7e9be3cf6d2226648e9609a09ed45f306930f..333fe08d56cb06bac2a338cad1c73894d54c4495 100644
--- a/test/support/mock_oauth.clj
+++ b/test/support/mock_oauth.clj
@@ -7,7 +7,7 @@
(defn- query-param [query key]
(when query
(some (fn [pair]
- (let [[k v] (str/split pair "=" 2)]
+ (let [[k v] (str/split pair #"=" 2)]
(when (= k key)
(URLDecoder/decode (or v "") "UTF-8"))))
(str/split query #"&"))))
@@ -31,11 +31,11 @@
(defn- send-redirect [^HttpExchange ex location]
(.set (.getResponseHeaders ex) "Location" location)
- (.sendResponseHeaders ex 302 -1)
+ (.sendResponseHeaders ex 302 0)
(.close (.getResponseBody ex)))
(defn- read-form [^HttpExchange ex]
- (let [body (slurp (.getInputStream ex))]
+ (let [body (slurp (.getRequestBody ex))]
{:code (query-param body "code")
:grant (query-param body "grant_type")}))
@@ -45,7 +45,7 @@
(str/replace #"^[Bb]earer " "")))
(defn- parse-token-user [token]
- (when (str/starts-with? token "mock:")
+ (when (and token (str/starts-with? token "mock:"))
(parse-mock-user (subs token 5))))
(defn- authorize-redirect [exchange query]
@@ -55,7 +55,7 @@
user (parse-mock-user mock-user)
code (str "mock:" (:id user) ":" (:login user))
loc (str redirect-uri "?code=" (java.net.URLEncoder/encode code "UTF-8")
- "&state=" (java.net.URLEncoder/encode state "UTF-8"))]
+ "&state=" (java.net.URLEncoder/encode (or state "") "UTF-8"))]
(send-redirect exchange loc)))
(defn start-mock-oauth
@@ -65,49 +65,56 @@
handler
(proxy [HttpHandler] []
(handle [^HttpExchange exchange]
- (let [uri (.getRequestURI exchange)
- path (.getPath uri)
- query (.getQuery uri)
- method (.getRequestMethod exchange)]
- (cond
- ;; GitHub authorize
- (str/ends-with? path "/login/oauth/authorize")
- (authorize-redirect exchange query)
+ (try
+ (let [uri (.getRequestURI exchange)
+ path (.getPath uri)
+ query (.getQuery uri)
+ method (.getRequestMethod exchange)]
+ (cond
+ ;; GitHub authorize
+ (str/ends-with? path "/login/oauth/authorize")
+ (authorize-redirect exchange query)
- ;; Reddit authorize
- (str/ends-with? path "/api/v1/authorize")
- (authorize-redirect exchange query)
+ ;; Reddit authorize
+ (str/ends-with? path "/api/v1/authorize")
+ (authorize-redirect exchange query)
- ;; GitHub token
- (and (= method "POST") (str/ends-with? path "/login/oauth/access_token"))
- (let [code (or (:code (read-form exchange)) "mock:1002:newbie")]
- (send-json exchange 200 (str "{\"access_token\":\"" code "\",\"token_type\":\"bearer\"}")))
+ ;; GitHub token
+ (and (= method "POST") (str/ends-with? path "/login/oauth/access_token"))
+ (let [code (or (:code (read-form exchange)) "mock:1002:newbie")]
+ (send-json exchange 200 (str "{\"access_token\":\"" code "\",\"token_type\":\"bearer\"}")))
- ;; Reddit token (client_credentials for import + authorization_code for login)
- (and (= method "POST") (str/ends-with? path "/api/v1/access_token"))
- (let [form (read-form exchange)
- grant (or (:grant form) "")
- code (or (:code form) "mock:t2_test:redditor")]
- (if (= grant "client_credentials")
- (send-json exchange 200 "{\"access_token\":\"app-token\",\"token_type\":\"bearer\",\"expires_in\":3600}")
- (send-json exchange 200 (str "{\"access_token\":\"" code "\",\"token_type\":\"bearer\",\"expires_in\":3600}"))))
+ ;; Reddit token (client_credentials for import + authorization_code for login)
+ (and (= method "POST") (str/ends-with? path "/api/v1/access_token"))
+ (let [form (read-form exchange)
+ grant (or (:grant form) "")
+ code (or (:code form) "mock:t2_test:redditor")]
+ (if (= grant "client_credentials")
+ (send-json exchange 200 "{\"access_token\":\"app-token\",\"token_type\":\"bearer\",\"expires_in\":3600}")
+ (send-json exchange 200 (str "{\"access_token\":\"" code "\",\"token_type\":\"bearer\",\"expires_in\":3600}"))))
- ;; GitHub user
- (= path "/user")
- (let [token (bearer-token exchange)
- user (or (parse-token-user token) {:id "1002" :login "newbie" :numeric? true})]
- (send-json exchange 200
- (str "{\"id\":" (:id user) ",\"login\":\"" (:login user) "\"}")))
+ ;; GitHub user
+ (= path "/user")
+ (let [token (bearer-token exchange)
+ user (or (parse-token-user token) {:id "1002" :login "newbie" :numeric? true})]
+ (send-json exchange 200
+ (str "{\"id\":" (:id user) ",\"login\":\"" (:login user) "\"}")))
- ;; Reddit /api/v1/me
- (str/ends-with? path "/api/v1/me")
- (let [token (bearer-token exchange)
- user (or (parse-token-user token) {:id "t2_test" :login "redditor"})]
- (send-json exchange 200
- (str "{\"id\":\"" (:id user) "\",\"name\":\"" (:login user) "\"}")))
+ ;; Reddit /api/v1/me
+ (str/ends-with? path "/api/v1/me")
+ (let [token (bearer-token exchange)
+ user (or (parse-token-user token) {:id "t2_test" :login "redditor"})]
+ (send-json exchange 200
+ (str "{\"id\":\"" (:id user) "\",\"name\":\"" (:login user) "\"}")))
- :else
- (send-json exchange 404 "{\"error\":\"not found\"}")))))]
+ :else
+ (send-json exchange 404 "{\"error\":\"not found\"}")))
+ (catch Throwable t
+ (binding [*out* *err*]
+ (println "mock-oauth handler error:" t))
+ (try
+ (send-json exchange 500 "{\"error\":\"mock-oauth internal\"}")
+ (catch Throwable _))))))]
(.createContext server "/" handler)
(.setExecutor server nil)
(.start server)
diff --git a/test/support/mock_reddit.clj b/test/support/mock_reddit.clj
index a630cf0938722193e9af88382d60e777ff371be4..faa27945b6394363914c853627a0bad1e819a5f9 100644
--- a/test/support/mock_reddit.clj
+++ b/test/support/mock_reddit.clj
@@ -12,7 +12,7 @@
(defn- query-param [query key]
(when query
(some (fn [pair]
- (let [[k v] (str/split pair "=" 2)]
+ (let [[k v] (str/split pair #"=" 2)]
(when (= k key)
(URLDecoder/decode (or v "") "UTF-8"))))
(str/split query #"&"))))
@@ -34,11 +34,11 @@
(defn- send-redirect [^HttpExchange ex location]
(.set (.getResponseHeaders ex) "Location" location)
- (.sendResponseHeaders ex 302 -1)
+ (.sendResponseHeaders ex 302 0)
(.close (.getResponseBody ex)))
(defn- read-form [^HttpExchange ex]
- (let [body (slurp (.getInputStream ex))]
+ (let [body (slurp (.getRequestBody ex))]
{:code (query-param body "code")
:grant (query-param body "grant_type")}))
@@ -48,7 +48,7 @@
(str/replace #"^[Bb]earer " "")))
(defn- parse-token-user [token]
- (when (str/starts-with? token "mock:")
+ (when (and token (str/starts-with? token "mock:"))
(parse-mock-user (subs token 5))))
(defn start-mock-reddit
@@ -72,7 +72,7 @@
user (parse-mock-user (query-param query "mock_user"))
code (str "mock:" (:id user) ":" (:login user))
loc (str redirect-uri "?code=" (java.net.URLEncoder/encode code "UTF-8")
- "&state=" (java.net.URLEncoder/encode state "UTF-8"))]
+ "&state=" (java.net.URLEncoder/encode (or state "") "UTF-8"))]
(send-redirect exchange loc))
(and (= method "POST") (str/ends-with? path "/api/v1/access_token"))
B — c_6f04dcb2e38c (tommy-mor)
message
[bda5f8aa] Remove legacy evidence projection; Evidence envelopes only. Epoch and commit pages no longer invent history from bare GitDiscovery rows. Production ledger will be wiped to re-emit under the current schema. Co-authored-by: Cursor <cursoragent@cursor.com>
diff preview
diff --git a/constitution.py b/constitution.py
index 4dd5b9dfbba231d46289c490f91b1dd5b1018bcf..26ba130e885e0e69fb7874ca5c3f07f42100a150 100644
--- a/constitution.py
+++ b/constitution.py
@@ -210,10 +210,10 @@ class Emission:
distributions: dict # author -> amount str
ranking: dict # author -> score str
models_used: list
- discovery_snapshot_id: str = "" # empty only for pre-discovery ledger history
- evidence_schema_version: int = 1
- ranking_run_id: str = ""
- ranking_event_id: str = ""
+ discovery_snapshot_id: str
+ evidence_schema_version: int
+ ranking_run_id: str
+ ranking_event_id: str
@event
@@ -502,26 +502,6 @@ def _epochs_in_ledger() -> list[int]:
return sorted(epochs)
-def _legacy_commit_row(commit_id: str) -> tuple[GitDiscovery | None, dict | None]:
- for discovery in store.read():
- if not isinstance(discovery, GitDiscovery):
- continue
- for commit in discovery.commits:
- if commit_id_for_oid(commit["oid"]) == commit_id:
- return discovery, commit
- return None, None
-
-
-def _legacy_observation(commit_id: str) -> tuple[GitDiscovery | None, dict | None]:
- for discovery in store.read():
- if not isinstance(discovery, GitDiscovery):
- continue
- for obs in discovery.observations:
- if commit_id_for_oid(obs["oid"]) == commit_id:
- return discovery, obs
- return None, None
-
-
def build_pairwise_prompt(side_a: dict, side_b: dict) -> str:
return f"""You are ranking contributions to an open source project.
Compare these two sides (each may be one or more commits). Decide which side contributed more.
@@ -2040,7 +2020,7 @@ def _strip_heavy_fields(obj: dict) -> dict:
@app.get("/api/ledger")
async def get_ledger(offset: int = 0, limit: int = 100, full: int = 0):
- """List of ledger dicts (backward-compatible). Heavy blobs stripped unless full=1."""
+ """List of ledger dicts. Heavy blobs stripped unless full=1."""
limit = max(1, min(limit, 500))
rows = []
for e in store.read()[offset:offset + limit]:
@@ -2274,23 +2254,25 @@ async def epochs_index():
epochs = _epochs_in_ledger()
rows = []
for epoch in epochs:
- discovery = _discovery_for_epoch(epoch)
emission = _emission_for_epoch(epoch)
- evidence_n = sum(
- 1 for e in evidence_by_kind() if e.epoch == epoch
+ evidence_n = sum(1 for e in evidence_by_kind() if e.epoch == epoch)
+ disc = next(
+ (
+ e for e in evidence_by_kind("git.discovery_completed")
+ if e.epoch == epoch
+ ),
+ None,
)
detail = []
- if discovery:
+ if disc:
detail.append(
- f"{len(discovery.commits)} eligible / "
- f"{len(discovery.observations)} observed"
+ f"{disc.payload.get('eligible_count', 0)} eligible / "
+ f"{disc.payload.get('observation_count', 0)} observed"
)
if emission:
detail.append(f"emitted {emission.total_emitted}")
if evidence_n:
detail.append(f"{evidence_n} evidence events")
- elif discovery or emission:
- detail.append("legacy (no Evidence envelopes)")
rows.append(["li",
_a(_evidence_path("epoch", str(epoch)), f"epoch {epoch}"),
" — ",
@@ -2307,37 +2289,37 @@ async def epochs_index():
@app.get("/epochs/{epoch}")
async def epoch_detail(epoch: int):
- discovery = _discovery_for_epoch(epoch)
emission = _emission_for_epoch(epoch)
evidence_rows = [e for e in evidence_by_kind() if e.epoch == epoch]
+ if not evidence_rows and emission is None:
+ return _evidence_page(f"epoch {epoch}", [
+ _evidence_nav(),
+ ["h1", f"epoch {epoch}"],
+ ["p.note", "No evidence for this epoch."],
+ ])
+
commit_evs = [e for e in evidence_rows if e.kind == "git.commit"]
comparison_evs = [e for e in evidence_rows if e.kind == "comparison.input"]
judgment_evs = [e for e in evidence_rows if e.kind == "llm.judgment"]
+ discovery_ev = next(
+ (e for e in evidence_rows if e.kind == "git.discovery_completed"), None
+ )
ranking_started = next(
(e for e in evidence_rows if e.kind == "ranking.started"), None
)
ranking_completed = next(
(e for e in evidence_rows if e.kind == "ranking.completed"), None
)
- legacy = not evidence_rows and (discovery is not None or emission is not None)
-
- commit_links: list[tuple[str, str]] = []
- if commit_evs:
- for e in commit_evs:
- cid = e.payload.get("commit_id") or ""
- label = (
- f"{e.payload.get('oid', cid)[:24]} "
- f"({e.payload.get('contributor', '?')})"
- )
- commit_links.append((label, _evidence_path("commit", cid)))
- elif discovery:
- for c in discovery.commits:
- cid = commit_id_for_oid(c["oid"])
- commit_links.append((
- f"{c['oid'][:24]} ({c.get('contributor', '?')})",
- _evidence_path("commit", cid),
- ))
+ commit_links = [
+ (
+ f"{e.payload.get('oid', e.payload.get('commit_id', ''))[:24]} "
+ f"({e.payload.get('contributor', '?')})",
+ _evidence_path("commit", e.payload["commit_id"]),
+ )
+ for e in commit_evs
+ if e.payload.get("commit_id")
+ ]
comparison_links = [
(
e.payload.get("summary") or e.payload.get("comparison_id", e.event_id),
@@ -2360,16 +2342,13 @@ async def epoch_detail(epoch: int):
]
excluded = []
- if discovery:
- for obs in discovery.observations:
+ if discovery_ev:
+ for obs in discovery_ev.payload.get("observations") or []:
if obs.get("eligible"):
continue
oid = obs.get("oid", "?")
reason = obs.get("exclusion_reason") or "excluded"
- excluded.append(["li",
- f"{oid[:28]} — {reason} — ",
- ["span.note", "legacy evidence unavailable"],
- ])
+ excluded.append(["li", f"{oid[:28]} — {reason}"])
ranking_nodes: list = []
if ranking_completed:
@@ -2388,21 +2367,10 @@ async def epoch_detail(epoch: int):
indent=2, sort_keys=True,
)],
]
- elif emission:
- if legacy and len(emission.ranking or {}) <= 1:
- ranking_nodes.append(["p.note",
- "Single-contributor epoch — no LLM judgments."
- ])
- ranking_nodes.extend([
- ["p", "Projected from Emission (no ranking Evidence event)."],
- ["pre.blob", json.dumps(emission.ranking, indent=2, sort_keys=True)],
- ])
+ elif ranking_started:
+ ranking_nodes = [["p.note", f"Ranking started: {ranking_started.event_id}"]]
else:
- ranking_nodes = [["p.note", "No ranking recorded."]]
- if ranking_started and not ranking_completed:
- ranking_nodes.insert(0, ["p.note",
- f"Ranking started: {ranking_started.event_id}"
- ])
+ ranking_nodes = [["p.note", "No ranking evidence."]]
if emission:
emission_node = _dl_rows([
@@ -2411,44 +2379,41 @@ async def epoch_detail(epoch: int):
("pool_after", emission.pool_after),
("discovery_snapshot_id", emission.discovery_snapshot_id),
("ranking_run_id", emission.ranking_run_id or None),
+ ("ranking_event_id", emission.ranking_event_id or None),
("models_used", ", ".join(emission.models_used or [])),
("distributions", json.dumps(emission.distributions, sort_keys=True)),
])
else:
emission_node = ["p.note", "No emission for this epoch."]
- single_contributor = False
- if discovery:
- single_contributor = len({c.get("contributor") for c in discovery.commits}) <= 1
- elif emission:
- single_contributor = len(emission.ranking or {}) <= 1
+ contributors = {
+ e.payload.get("contributor")
+ for e in commit_evs
+ if e.payload.get("contributor")
+ }
+ no_comparisons_note = "No comparisons."
+ if len(contributors) <= 1:
+ no_comparisons_note += " Single-contributor — no LLM judgments."
body = [
_evidence_nav(),
["div.eyebrow", f"epoch {epoch}"],
["h1", f"epoch {epoch}"],
]
- if legacy:
- body.append(["p.note",
- "Legacy epoch: projected from GitDiscovery/Emission without Evidence "
- "envelopes. Eligible commits use discovery patches; discarded observation "
- "metadata is marked legacy evidence unavailable. Single-contributor "
- "epochs have no LLM judgments."
- ])
- if discovery:
+ if discovery_ev:
body.extend([
["h2", "discovery"],
_dl_rows([
- ("snapshot_id", discovery.snapshot_id),
- ("config_digest", discovery.config_digest),
- ("initial_snapshot", discovery.initial_snapshot),
- ("observations", len(discovery.observations)),
- ("eligible", len(discovery.commits)),
+ ("snapshot_id", discovery_ev.payload.get("snapshot_id")),
+ ("config_digest", discovery_ev.payload.get("config_digest")),
+ ("observations", discovery_ev.payload.get("observation_count")),
+ ("eligible", discovery_ev.payload.get("eligible_count")),
+ ("event", _a(
+ _evidence_path("event", discovery_ev.event_id),
+ discovery_ev.event_id,
+ )),
]),
])
- no_comparisons_note = "No comparisons."
- if single_contributor:
- no_comparisons_note += " Single-contributor — no LLM judgments."
body.extend([
["h2", "commits"],
_link_list(commit_links),
@@ -2471,92 +2436,42 @@ async def epoch_detail(epoch: int):
@app.get("/commits/{commit_id}")
async def commit_detail(commit_id: str):
ev = find_evidence_payload("git.commit", "commit_id", commit_id)
- discovery, legacy_row = (None, None)
if not ev:
- discovery, legacy_row = _legacy_commit_row(commit_id)
- if not ev and not legacy_row:
- discovery, obs = _legacy_observation(commit_id)
- if obs is not None:
- epoch = discovery.epoch if discovery else "?"
- return _evidence_page(f"commit {commit_id[:24]}", [
- _evidence_nav(
- _a(_evidence_path("epoch", str(epoch)), f"epoch {epoch}")
- ),
- ["div.eyebrow", "commit"],
- ["h1", commit_id],
- ["p.note", "legacy evidence unavailable"],
- _dl_rows([
- ("oid", obs.get("oid")),
- ("eligible", obs.get("eligible")),
- ("exclusion_reason", obs.get("exclusion_reason")),
- ("epoch", str(epoch)),
- ]),
- ])
return _evidence_page("commit not found", [
_evidence_nav(),
["h1", "commit not found"],
["p", commit_id],
])
- if ev:
- p = ev.payload
- epoch = ev.epoch
- oid = p.get("oid", "")
- contributor = p.get("contributor", "")
- message = _blob_text(p.get("message"))
- patch = _blob_text(p.get("patch"))
- meta = _dl_rows([
+ p = ev.payload
+ epoch = ev.epoch
+ return _evidence_page(f"commit {commit_id[:24]}", [
+ _evidence_nav(_a(_evidence_path("epoch", str(epoch)), f"epoch {epoch}")),
+ ["div.eyebrow", "commit"],
+ ["h1", commit_id],
+ _dl_rows([
("commit_id", commit
… preview truncated; 7,279 characters omittedHardlinks — judgments / attempts / prompt
judgments
attempts
Prompt text is loaded only by the download route.