constitution · epochs · watch · epoch 3

comparison

c_b21d271b1b82 (tommy-mor) vs c_45659f04aa7c (tommy-mor)

download prompt · raw event · cmp_5176bc40d56932

council reasoning

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

Side B implements a substantive, well-tested reworking of multi-repository contribution discovery (deterministic ref matching, patch-identity dedup, idempotent replay, extensive real-Git unit and stateful hypothesis tests) that fixes a real correctness/economic-integrity gap in the constitution's emission logic. Side A adds a genuinely useful GitHub external resolver and URL-normalization fixes, but includes large amounts of reformatting-only diff noise and is comparatively narrower in scope and risk-reduction value versus B's rigorous, adversarially-tested discovery mechanism underpinning payouts.

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

B replaces brittle GitHub-API commit listing with multi-repo git mirror discovery, immutable snapshots, patch-id cherry-pick dedup, force-push/replace-ref hardening, and replayable attribution wired into emissions—core constitutional infrastructure with deep unit, integration, and Hypothesis coverage. A adds real product value (URL identity policy, SystemIngest, on-demand GitHub resolver UI/tests), but much of the diff is formatting/churn around a feature layer rather than the ownership spine.

openai/gpt-chat-latest · winner B · 6:5 · permalink

Side B replaces GitHub API-based commit discovery with deterministic multi-repository Git graph discovery, adding replayable `GitDiscovery` snapshots, patch-identity deduplication, repository/ref configuration, locking, and extensive adversarial/stateful tests that strengthen attribution correctness over time. Side A adds valuable URL normalization, an on-demand GitHub external resolver, system ingests, and UI support, but much of it is feature expansion, whereas Side B establishes a more durable foundation for reproducible ownership allocation and replay semantics.

sides

A — c_b21d271b1b82 (tommy-mor)

message

[06b48801] Implement extensible URL foundation (#145)

* Implement extensible URL foundation

Co-authored-by: tommy <thmorriss@gmail.com>

* Make query params non-identity by default

Co-authored-by: tommy <thmorriss@gmail.com>

* Fix external href helper test scope

Co-authored-by: tommy <thmorriss@gmail.com>

* Avoid broken external previews for blocked hosts

Co-authored-by: tommy <thmorriss@gmail.com>

* Clarify external empty state copy

Co-authored-by: tommy <thmorriss@gmail.com>

* Add on-demand GitHub external resolver

Co-authored-by: tommy <thmorriss@gmail.com>

* Add fenced JSON bodies for GitHub resolver

Co-authored-by: tommy <thmorriss@gmail.com>

---------

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

diff preview

diff --git a/agents.md b/agents.md
index 59bd2174f4d2f972a45123fe10d408aa5881ee93..c66f33789441eea193b4354fce4c03b7fffdd639 100644
--- a/agents.md
+++ b/agents.md
@@ -55,6 +55,7 @@ Strict **CSP** that blocks `eval` would break the current app. Other projects ma
 | Ingests, grants, rooms, identity tokens, agent binds, redactions, etc. | **JSONL** | Appended in `server/src/api/rpc.rs`, `server/src/api/auth.rs` (and related paths) before updating `ReducerState` |
 | **`RoomMintInvite` links** | **RAM only** | `AppState.invites` — not appended as `InviteMinted` today; **lost on restart** (`server/src/state.rs`, `server/src/api/rpc.rs`). Event types `InviteMinted` / `InviteRedeemed` exist for replay and a possible future persisted mint (`server/src/reducer.rs`). |
 | **OAuth / pending sessions** | **RAM only** | `AppState.pending_sessions` (`server/src/state.rs`, `server/src/api/auth.rs`) |
+| **External resolver cooldowns** | **RAM only** | `AppState.resolver_runs` — debounce/rate-limit guard for on-demand resolver buttons. Resolver results themselves are durable synthetic `Ingest` events in `events.jsonl`. |
 | **Reducer projection** | **Derived** | Rebuilt from log on startup; not separately persisted |
 
 If you add a new ephemeral map or start persisting something that was RAM-only, **update this table and the code comments** (`server/src/state.rs` is a good anchor).
diff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs
index 7cbda3876451687aa7a55547fc06bbe86ac9d260..cd501ba6d4d656eabad03afed4583efdf885695d 100644
--- a/server/src/api/ui_html.rs
+++ b/server/src/api/ui_html.rs
@@ -18,14 +18,15 @@ use crate::{
         rpc::{rpc_post_redact, rpc_post_with_bearer, rpc_room_delete},
     },
     canonical_path::canonicalize_tag,
+    external_resolver::resolve_github_children,
+    html::vote_compare_post_success_js,
     html::{
-        fragment_new_thread_slot, login_to_post_hint_markup,
-        parse_html_ui_from_form, room_members_section_markup, thread_feed_html,
-        thread_feed_html_for_room, thread_feed_region_markup, thread_ui_collapse_redacted_post,
-        thread_ui_expand_post_full, thread_ui_expand_redacted_post, ui_js_warn, user_can_post_room,
-        user_can_view_room, HtmlUiAction, JsBuilder, ThreadNav,
+        fragment_new_thread_slot, login_to_post_hint_markup, parse_html_ui_from_form,
+        room_members_section_markup, thread_feed_html, thread_feed_html_for_room,
+        thread_feed_region_markup, thread_ui_collapse_redacted_post, thread_ui_expand_post_full,
+        thread_ui_expand_redacted_post, ui_js_warn, user_can_post_room, user_can_view_room,
+        HtmlUiAction, JsBuilder, ThreadNav,
     },
-    html::vote_compare_post_success_js,
     reducer::{scope_from_room_wire, ScopeId},
     state::AppState,
 };
@@ -104,26 +105,35 @@ async fn dispatch_ui_action(
                 )
                 .into_response();
             }
-            match rpc_post_with_bearer(state, &session.bearer, room.clone(), thread_tag.clone(), text).await {
-                Ok(RpcResult::PostOk { .. }) => {
-                    post_success_response(
-                        state,
-                        &room,
-                        &thread_tag,
-                        error_target.as_ref(),
-                        form_id.as_ref(),
-                        Some(session.username.as_str()),
-                    )
-                    .await
-                    .into_response()
-                }
+            match rpc_post_with_bearer(
+                state,
+                &session.bearer,
+                room.clone(),
+                thread_tag.clone(),
+                text,
+            )
+            .await
+            {
+                Ok(RpcResult::PostOk { .. }) => post_success_response(
+                    state,
+                    &room,
+                    &thread_tag,
+                    error_target.as_ref(),
+                    form_id.as_ref(),
+                    Some(session.username.as_str()),
+                )
+                .await
+                .into_response(),
                 Ok(_) => form_js_error(
                     error_target.as_ref(),
                     "unexpected response",
                     "Post did not return PostOk.",
                 )
                 .into_response(),
-                Err((msg, hint)) => form_js_error(error_target.as_ref(), &msg, hint.as_deref().unwrap_or("")).into_response(),
+                Err((msg, hint)) => {
+                    form_js_error(error_target.as_ref(), &msg, hint.as_deref().unwrap_or(""))
+                        .into_response()
+                }
             }
         }
         HtmlUiAction::CheckIngest {
@@ -150,9 +160,19 @@ async fn dispatch_ui_action(
                 return js_clear_errors(&form_error_target(error_target.as_ref())).into_response();
             }
             match rpc_check_with_bearer(state, &session.bearer, room, text.clone()).await {
-                Ok(RpcResult::CheckOk { .. }) => js_clear_errors(&form_error_target(error_target.as_ref())).into_response(),
-                Ok(_) => form_js_error(error_target.as_ref(), "unexpected response", "Check did not return CheckOk.").into_response(),
-                Err((msg, hint)) => form_js_error(error_target.as_ref(), &msg, hint.as_deref().unwrap_or("")).into_response(),
+                Ok(RpcResult::CheckOk { .. }) => {
+                    js_clear_errors(&form_error_target(error_target.as_ref())).into_response()
+                }
+                Ok(_) => form_js_error(
+                    error_target.as_ref(),
+                    "unexpected response",
+                    "Check did not return CheckOk.",
+                )
+                .into_response(),
+                Err((msg, hint)) => {
+                    form_js_error(error_target.as_ref(), &msg, hint.as_deref().unwrap_or(""))
+                        .into_response()
+                }
             }
         }
         HtmlUiAction::VoteComparePost {
@@ -167,7 +187,11 @@ async fn dispatch_ui_action(
             form_action,
         } => {
             if form_action != "/ui" {
-                return (StatusCode::BAD_REQUEST, "invalid vote_compare_post form_action").into_response();
+                return (
+                    StatusCode::BAD_REQUEST,
+                    "invalid vote_compare_post form_action",
+                )
+                    .into_response();
             }
             let Some(session) = session else {
                 return js_redirect("/login").into_response();
@@ -195,23 +219,15 @@ async fn dispatch_ui_action(
             let left_id = match crate::path_types::ItemId::parse(left_item.trim()) {
                 Some(i) => i.normalized_storage(),
                 None => {
-                    return form_js_error(
-                        err_tgt.as_ref(),
-                        "bad item",
-                        "Invalid left item path.",
-                    )
-                    .into_response();
+                    return form_js_error(err_tgt.as_ref(), "bad item", "Invalid left item path.")
+                        .into_response();
                 }
             };
             let right_id = match crate::path_types::ItemId::parse(right_item.trim()) {
                 Some(i) => i.normalized_storage(),
                 None => {
-                    return form_js_error(
-                        err_tgt.as_ref(),
-                        "bad item",
-                        "Invalid right item path.",
-                    )
-                    .into_response();
+                    return form_js_error(err_tgt.as_ref(), "bad item", "Invalid right item path.")
+                        .into_response();
                 }
             };
             let mut rl = ratio_left.trim().parse::<i32>().unwrap_or(0).max(0);
@@ -231,7 +247,15 @@ async fn dispatch_ui_action(
                 right_id.as_str()
             );
 
-            match rpc_post_with_bearer(state, &session.bearer, room.clone(), thread_tag.clone(), text).await {
+            match rpc_post_with_bearer(
+                state,
+                &session.bearer,
+                room.clone(),
+                thread_tag.clone(),
+                text,
+            )
+            .await
+            {
                 Ok(RpcResult::PostOk {
                     post_id,
                     post_index,
@@ -277,7 +301,10 @@ async fn dispatch_ui_action(
                     "Post did not return PostOk.",
                 )
                 .into_response(),
-                Err((msg, hint)) => form_js_error(err_tgt.as_ref(), &msg, hint.as_deref().unwrap_or("")).into_response(),
+                Err((msg, hint)) => {
+                    form_js_error(err_tgt.as_ref(), &msg, hint.as_deref().unwrap_or(""))
+                        .into_response()
+                }
             }
         }
         HtmlUiAction::SetGardenPin {
@@ -288,7 +315,11 @@ async fn dispatch_ui_action(
             form_action,
         } => {
             if form_action != "/ui" {
-                return (StatusCode::BAD_REQUEST, "invalid set_garden_pin form_action").into_response();
+                return (
+                    StatusCode::BAD_REQUEST,
+                    "invalid set_garden_pin form_action",
+                )
+                    .into_response();
             }
             let next_path = sanitize_garden_pin_next(&next);
             use crate::html::{encode_pin_cookie_value, GARDEN_PIN_COOKIE};
@@ -301,7 +332,11 @@ async fn dispatch_ui_action(
             if room.is_empty() {
                 return (StatusCode::BAD_REQUEST, "missing room").into_response();
             }
-            let Some(raw) = item_storage.as_ref().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) else {
+            let Some(raw) = item_storage
+                .as_ref()
+                .map(|s| s.trim().to_string())
+                .filter(|s| !s.is_empty())
+            else {
                 return (StatusCode::BAD_REQUEST, "missing item").into_response();
             };
             let Some(item) = ItemId::parse(&raw) else {
@@ -309,16 +344,65 @@ async fn dispatch_ui_action(
             };
             let item = item.normalized_storage();
             let val = encode_pin_cookie_value(&room, item.as_str());
-            let cookie = format!("{GARDEN_PIN_COOKIE}={val}; Path=/; SameSite=Lax; Max-Age=7776000");
+            let cookie =
+                format!("{GARDEN_PIN_COOKIE}={val}; Path=/; SameSite=Lax; Max-Age=7776000");
             redirect_with_pin_cookie(&cookie, &next_path)
         }
+        HtmlUiAction::ResolveExternal {
+            room_wire,
+            item_storage,
+            mode,
+            next,
+            form_action,
+        } => {
+            if form_action != "/ui" {
+                return (
+                    StatusCode::BAD_REQUEST,
+                    "invalid resolve_external form_action",
+                )
+                    .into_response();
+            }
+            let Some(session) = session else {
+                return js_redirect("/login").into_response();
+            };
+            let room = room_wire.trim();
+            if room.is_empty() {
+                return ui_js_warn("missing room").into_response();
+            }
+            let reduced = state.reduced.read().await;
+            if matches!(scope_from_room_wire(room), ScopeId::Room(_)) {
+                if !user_can_post_room(&reduced, room, &session.username) {
+                    drop(reduced);
+                    return ui_js_warn("forbidden").into_response();
+                }
+            }
+            drop(reduced);
+
+            let Some(item) = crate::path_types::ItemId::parse(item_storage.trim()) else {
+                return ui_js_warn("bad item").into_response();
+            };
+            let target = if mode.trim() == "siblings" {
+                m

… preview truncated; 74,788 characters omitted

download full diff A

B — c_45659f04aa7c (tommy-mor)

message

[1efb7222] multi-repository git discovery

Make contribution discovery deterministic across repository and branch DAGs, with replayable attribution and adversarial coverage.

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

diff preview

diff --git a/constitution.py b/constitution.py
index b535faad658c553b3b9046e2401333618e212150..4bee9f83663ab7fb36db95129b92b64b4ef57258 100644
--- a/constitution.py
+++ b/constitution.py
@@ -6,7 +6,7 @@
 #   "uvicorn",
 #   "httpx",
 #   "tenacity",
-#   "evaleval>=0.2.6",
+#   "evaleval==0.2.7",
 #   "authlib",
 #   "itsdangerous",
 #   "starlette",
@@ -29,7 +29,7 @@ from datetime import datetime, timezone
 from fastapi import FastAPI, Request, Response
 from fastapi.responses import PlainTextResponse, HTMLResponse
 from starlette.middleware.sessions import SessionMiddleware
-import json, time, os, asyncio, httpx, pathlib
+import json, time, os, asyncio, httpx, pathlib, subprocess, hashlib, re, fcntl
 import sympy as sp  # type: ignore[reportMissingImports]
 from tenacity import retry, retry_if_exception, stop_after_attempt, wait_exponential
 from evaleval import (
@@ -118,11 +118,35 @@ JSONL_PATH = pathlib.Path(os.environ.get("JSONL_PATH", "/data/ledger.jsonl"))
 
 GITHUB_CLIENT_ID = os.environ.get("GITHUB_CLIENT_ID", "")
 GITHUB_CLIENT_SECRET = os.environ.get("GITHUB_CLIENT_SECRET", "")
-REPO = os.environ.get("REPO", "tommy-mor/slug")
 
 OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY", "")
 OPENROUTER_BASE_URL = os.environ.get("OPENROUTER_BASE_URL", "https://openrouter.ai").rstrip("/")
-GITHUB_API_BASE_URL = os.environ.get("GITHUB_API_BASE_URL", "https://api.github.com").rstrip("/")
+
+# Repositories, branches, and contributor identities are constitutional inputs.
+# A ref pattern matches a complete Git ref: * stays within one path component,
+# while ** crosses slashes, so refs/heads/** includes branches on branches.
+# Environment overrides exist for deterministic integration tests and deployments
+# using the exact same source; their normalized values are committed to every
+# discovery event.
+DEFAULT_REPOSITORIES = [
+    {
+        "id": "slug",
+        "url": "https://github.com/tommy-mor/slug.git",
+        "refs": ["refs/heads/**"],
+    },
+]
+DEFAULT_CONTRIBUTORS = {
+    "tommy-mor": ["thmorriss@gmail.com"],
+}
+
+REPOSITORIES = json.loads(
+    os.environ.get("REPOSITORIES_JSON", json.dumps(DEFAULT_REPOSITORIES))
+)
+CONTRIBUTORS = json.loads(
+    os.environ.get("CONTRIBUTORS_JSON", json.dumps(DEFAULT_CONTRIBUTORS))
+)
+GIT_MIRROR_DIR = pathlib.Path(os.environ.get("GIT_MIRROR_DIR", "/data/git"))
+GIT_TIMEOUT_SECONDS = int(os.environ.get("GIT_TIMEOUT_SECONDS", "120"))
 
 # Council model IDs: slug.social garden rank under this parent (bodies = OpenRouter URLs), then top-up from OpenRouter list.
 SLUG_SOCIAL_BASE_URL = os.environ.get("SLUG_SOCIAL_BASE_URL", "https://slug.social").rstrip("/")
@@ -146,6 +170,7 @@ 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
 
 
 @event
@@ -163,6 +188,20 @@ class Redemption:
     amount: str
 
 
+@event
+class GitDiscovery:
+    schema_version: int
+    epoch: int
+    snapshot_id: str
+    timestamp_ms: int
+    config_digest: str
+    initial_snapshot: bool
+    configuration: dict
+    repositories: list
+    observations: list
+    commits: list
+
+
 store = JsonlStore(JSONL_PATH)
 
 
@@ -532,44 +571,426 @@ Side B — unified diffs (full patches):
         return json.loads(content)
 
 
-def _github_headers():
-    h = {"Accept": "application/vnd.github+json"}
-    tok = os.environ.get("GITHUB_TOKEN", "")
-    if tok:
-        h["Authorization"] = f"Bearer {tok}"
-    return h
+# ===========================================================================
+# §4b. GIT DISCOVERY — immutable reachability snapshots across repositories
+# ===========================================================================
+#
+# Git timestamps cannot prove when a branch first reached a commit. The first
+# snapshot therefore bootstraps history by committer time at GENESIS_MS. Every
+# later snapshot uses the stronger rule: a commit enters exactly once, when it
+# first becomes reachable from the union of configured refs.
+#
+# OIDs are deduplicated globally, then equivalent cherry-picks are deduplicated
+# by Git's stable patch identity. Merges and empty commits are graph structure,
+# not separately priced contributions. Discovery is all-or-nothing: if any
+# repository cannot be mirrored and verified, no snapshot is appended.
+
+GIT_DISCOVERY_SCHEMA_VERSION = 1
+PATCH_IDENTITY_VERSION = "git-patch-id-stable-v1"
+_DISCOVERY_LOCK = asyncio.Lock()
+
+
+def _normalized_discovery_config() -> dict:
+    repositories = []
+    seen_ids = set()
+    for raw in REPOSITORIES:
+        repo_id = str(raw.get("id", ""))
+        url = str(raw.get("url", ""))
+        refs = sorted(set(str(x) for x in raw.get("refs", [])))
+        if not re.fullmatch(r"[A-Za-z0-9._-]+", repo_id):
+            raise ValueError(f"invalid repository id: {repo_id!r}")
+        if repo_id in seen_ids:
+            raise ValueError(f"duplicate repository id: {repo_id}")
+        if not url or not refs or any(not r.startswith("refs/") for r in refs):
+            raise ValueError(f"repository {repo_id} requires a URL and full ref patterns")
+        seen_ids.add(repo_id)
+        repositories.append({"id": repo_id, "url": url, "refs": refs})
+
+    email_to_contributor = {}
+    contributors = {}
+    for contributor, emails in sorted(CONTRIBUTORS.items()):
+        contributor = str(contributor)
+        normalized = sorted(set(str(e).strip().lower() for e in emails))
+        if not contributor or not normalized:
+            raise ValueError("contributors require an id and at least one email")
+        for email in normalized:
+            if email in email_to_contributor:
+                raise ValueError(f"email belongs to multiple contributors: {email}")
+            email_to_contributor[email] = contributor
+        contributors[contributor] = normalized
+
+    repositories.sort(key=lambda r: r["id"])
+    return {"repositories": repositories, "contributors": contributors}
+
+
+def _config_digest(config: dict) -> str:
+    encoded = json.dumps(config, sort_keys=True, separators=(",", ":")).encode()
+    return hashlib.sha256(encoded).hexdigest()
+
+
+def _ref_pattern_regex(pattern: str) -> re.Pattern:
+    out = ""
+    i = 0
+    while i < len(pattern):
+        if pattern[i:i + 2] == "**":
+            out += ".*"
+            i += 2
+        elif pattern[i] == "*":
+            out += "[^/]*"
+            i += 1
+        elif pattern[i] == "?":
+            out += "[^/]"
+            i += 1
+        else:
+            out += re.escape(pattern[i])
+            i += 1
+    return re.compile(f"^{out}$")
+
+
+def _git(repo: pathlib.Path | None, *args: str, input_bytes: bytes | None = None) -> bytes:
+    command = [
+        "git",
+        "--no-replace-objects",
+        "-c", "core.quotepath=true",
+        "-c", "core.attributesFile=/dev/null",
+        "-c", "diff.external=",
+        "-c", "diff.renames=false",
+        "-c", "diff.algorithm=myers",
+        "-c", "diff.context=3",
+    ]
+    if repo is not None:
+        command += ["-C", str(repo)]
+    command += list(args)
+    try:
+        result = subprocess.run(
+            command,
+            input=input_bytes,
+            stdout=subprocess.PIPE,
+            stderr=subprocess.PIPE,
+            env={
+                **os.environ,
+                "GIT_CONFIG_NOSYSTEM": "1",
+                "GIT_CONFIG_GLOBAL": os.devnull,
+                "GIT_NO_REPLACE_OBJECTS": "1",
+                "LC_ALL": "C",
+                "TZ": "UTC",
+            },
+            timeout=GIT_TIMEOUT_SECONDS,
+            check=False,
+        )
+    except subprocess.TimeoutExpired as exc:
+        raise RuntimeError(f"git command timed out: {args[0]}") from exc
+    if result.returncode:
+        error = result.stderr.decode("utf-8", "replace").strip()
+        raise RuntimeError(f"git {args[0]} failed: {error}")
+    return result.stdout
+
+
+def _ensure_mirror(repo: dict) -> pathlib.Path:
+    GIT_MIRROR_DIR.mkdir(parents=True, exist_ok=True)
+    mirror = GIT_MIRROR_DIR / f"{repo['id']}.git"
+    if not mirror.exists():
+        _git(None, "clone", "--mirror", "--", repo["url"], str(mirror))
+    else:
+        actual_url = _git(mirror, "remote", "get-url", "origin").decode().strip()
+        if actual_url != repo["url"]:
+            raise RuntimeError(
+                f"mirror URL mismatch for {repo['id']}: {actual_url!r}"
+            )
+    _git(mirror, "fetch", "--prune", "origin", "+refs/*:refs/*")
+    _git(mirror, "fsck", "--connectivity-only", "--no-dangling")
+    return mirror
+
+
+def _matching_refs(mirror: pathlib.Path, patterns: list[str]) -> list[dict]:
+    regexes = [_ref_pattern_regex(p) for p in patterns]
+    lines = _git(
+        mirror, "for-each-ref", "--format=%(refname)%00%(objectname)"
+    ).decode("utf-8", "replace").splitlines()
+    selected = []
+    for line in lines:
+        if not line:
+            continue
+        ref_name, direct_oid = line.split("\x00", 1)
+        if not any(r.fullmatch(ref_name) for r in regexes):
+            continue
+        commit_oid = _git(
+            mirror, "rev-parse", "--verify", f"{ref_name}^{{commit}}"
+        ).decode().strip()
+        selected.append({
+            "name": ref_name,
+            "direct_oid": direct_oid,
+            "commit_oid": commit_oid,
+        })
+    if not selected:
+        raise RuntimeError(f"no refs matched patterns {patterns!r}")
+    return sorted(selected, key=lambda r: r["name"])
+
+
+def _commit_metadata(mirror: pathlib.Path, oid: str) -> dict:
+    raw = _git(
+        mirror,
+        "show",
+        "-s",
+        "--format=%H%x00%T%x00%P%x00%an%x00%ae%x00%at%x00%cn%x00%ce%x00%ct%x00%B",
+        oid,
+    ).decode("utf-8", "replace")
+    fields = raw.split("\x00", 9)
+    if len(fields) != 10:
+        raise RuntimeError(f"could not parse commit metadata for {oid}")
+    return {
+        "oid": fields[0],
+        "tree_oid": fields[1],
+        "parent_oids": fields[2].split() if fields[2] else [],
+        "author_name": fields[3],
+        "author_email": fields[4].strip().lower(),
+        "author_timestamp_ms": int(fields[5]) * 1000,
+        "committer_name": fields[6],
+        "committer_email": fields[7].strip().lower(),
+        "committer_timestamp_ms": int(fields[8]) * 1000,
+        "message": fields[9].rstrip("\n"),
+    }
 
 
-def unified_diff_from_commit_payload(payload: dict) -> str:
-    parts = []
-    for f in payload.get("files") or []:
-        name = f.get("filename", "?")
-        patch = f.get("patch")
-        if patch:
-            parts.append(f"--- {name}\n{patch}")
-        else:
-            parts.append(f"--- {name}\n[no textual patch: binary, submodule, or too large]\n")
-    return "\n\n".join(parts) if parts else "[no files in API response]"
+def _commit_patch(mirror: pathlib.Path, metadata: dict) -> tuple[str, str | None]:
+    parents = metadata["parent_oids"]
+    if len(parents) > 1:
+        return "", None
+    if parents:
+        args = ("diff", "--patch", "--binary", "--full-index", "--no-renames",
+                "--no-ext-diff", "--no-textconv", "--src-prefix=a/",
+                "--dst-prefix=b/", parents[0], metadata["oid"], "--")
+    else:
+        args = ("diff-tree", "--root", "--patch", "--binary", "--full-index",
+                "--no-renames", "--no-ext-diff", "--no-textconv",
+                "--src-prefix=a/", "--dst-prefix=b/", "--no-commit-id",
+                metadata["oid"], "--")
+    patch_bytes = _git(mirror, *args)
+    if not patch_bytes.strip():
+        return "", None
+    # Run patch-id outside the repository so SHA-1 and SHA-256 repositories use
+    # the same canonical patch hash algorithm.
+    patch_id_out = _git(
+        None, "patch-id", "--stable", input_bytes=patch_bytes
+    ).decode().strip()
+    if patch_id_out:
+        st

… preview truncated; 120,051 characters omitted

download full diff B

Hardlinks — judgments / attempts / prompt

prompt download

judgments

attempts

Prompt text is loaded only by the download route.