{"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[c7ef287e] Rank every eligible commit with the LLM council.\n\nStop short-circuiting on a single contributor; pairwise-sort commits, roll scores up for emission payouts, and surface commit rankings on epoch pages.\n\nCo-authored-by: Cursor \n\nSide A — unified diff (full patch):\ndiff --git a/constitution.py b/constitution.py\nindex 26ba130e885e0e69fb7874ca5c3f07f42100a150..71fc46b4c9a4d7a9ea7bf319860b0db1acc4a673 100644\n--- a/constitution.py\n+++ b/constitution.py\n@@ -503,20 +503,22 @@ def _epochs_in_ledger() -> list[int]:\n \n \n def build_pairwise_prompt(side_a: dict, side_b: dict) -> str:\n- return f\"\"\"You are ranking contributions to an open source project.\n-Compare these two sides (each may be one or more commits). Decide which side contributed more.\n+ return f\"\"\"You are ranking individual git commits to an open source project.\n+Compare these two commits. Decide which commit contributed more.\n Return ONLY a JSON object: {{\"winner\": \"A\" or \"B\", \"ratio\": \"N:M\", \"explanation\": \"...\"}}\n \n-Side A — commit messages:\n+Side A — contributor: {side_a.get('contributor', '?')}\n+Side A — commit message:\n {side_a['message']}\n \n-Side A — unified diffs (full patches):\n+Side A — unified diff (full patch):\n {side_a['diff']}\n \n-Side B — commit messages:\n+Side B — contributor: {side_b.get('contributor', '?')}\n+Side B — commit message:\n {side_b['message']}\n \n-Side B — unified diffs (full patches):\n+Side B — unified diff (full patch):\n {side_b['diff']}\"\"\"\n \n \n@@ -1518,16 +1520,28 @@ async def broadcast_js(js: str):\n await queue.put(js)\n \n \n-def _author_side_for_llm(author: str, author_commits: dict) -> dict:\n- cs = author_commits[author]\n+def _commit_side_for_llm(row: dict) -> dict:\n+ oid = row[\"oid\"]\n+ short = oid.split(\":\", 1)[1][:8] if \":\" in oid else oid[:8]\n return {\n- \"message\": \"\\n\".join(f\"[{c['sha']}] {c['message']}\" for c in cs),\n- \"diff\": \"\\n\\n\".join(f\"=== {c['sha']} ===\\n{c['diff']}\" for c in cs),\n- \"commit_ids\": [c[\"commit_id\"] for c in cs],\n- \"contributor\": author,\n+ \"message\": f\"[{short}] {row['message']}\",\n+ \"diff\": row[\"patch\"] or \"\",\n+ \"commit_id\": commit_id_for_oid(oid),\n+ \"contributor\": row[\"contributor\"],\n+ \"oid\": oid,\n }\n \n \n+def _rollup_contributor_scores(\n+ ordered: list[dict], commit_scores: list[Decimal]\n+) -> dict[str, Decimal]:\n+ totals: dict[str, Decimal] = {}\n+ for row, score in zip(ordered, commit_scores):\n+ contributor = row[\"contributor\"]\n+ totals[contributor] = totals.get(contributor, Decimal(\"0\")) + score\n+ return totals\n+\n+\n def _find_judgment(comparison_id: str, model_id: str) -> dict | None:\n for e in evidence_by_kind(\"llm.judgment\"):\n p = e.payload\n@@ -1546,101 +1560,106 @@ def _find_ranking_models(ranking_run_id: str) -> list[str] | None:\n \n \n async def rank_commits(commits: list[dict], *, epoch: int = -1):\n+ \"\"\"Pairwise-rank every eligible commit; roll scores up to contributors.\"\"\"\n if not commits:\n return {}, [], {\"ranking_run_id\": \"\", \"ranking_event_id\": \"\"}\n \n- commit_ids = sorted(commit_id_for_oid(row[\"oid\"]) for row in commits)\n+ ordered = sorted(commits, key=lambda r: r[\"oid\"])\n+ commit_ids = [commit_id_for_oid(row[\"oid\"]) for row in ordered]\n ranking_run_id = _content_id(\"rank\", {\n \"epoch\": epoch,\n- \"commit_ids\": commit_ids,\n+ \"commit_ids\": sorted(commit_ids),\n })\n- contributors = sorted(set(c[\"contributor\"] for c in commits))\n+ contributors = sorted({c[\"contributor\"] for c in ordered})\n \n- if len(contributors) == 1:\n+ # Nothing to compare: a single commit (not a single contributor).\n+ if len(ordered) == 1:\n await append_evidence(epoch, \"ranking.started\", {\n \"ranking_run_id\": ranking_run_id,\n \"commit_ids\": commit_ids,\n \"contributors\": contributors,\n \"models\": [],\n- \"summary\": f\"ranking epoch {epoch}: single contributor\",\n+ \"summary\": f\"ranking epoch {epoch}: single commit\",\n })\n- ranking = {contributors[0]: Decimal(\"1\")}\n+ commit_ranking = {commit_ids[0]: \"1\"}\n+ contributor_ranking = {ordered[0][\"contributor\"]: Decimal(\"1\")}\n completed = await append_evidence(epoch, \"ranking.completed\", {\n \"ranking_run_id\": ranking_run_id,\n \"models\": [],\n- \"ranking\": {contributors[0]: \"1\"},\n+ \"commit_ranking\": commit_ranking,\n+ \"contributor_ranking\": {ordered[0][\"contributor\"]: \"1\"},\n+ \"ranking\": {ordered[0][\"contributor\"]: \"1\"},\n \"judgment_ids\": [],\n- \"summary\": f\"Only {contributors[0]} is eligible; rank is 1.0\",\n+ \"summary\": f\"Only one eligible commit; {ordered[0]['contributor']} rank 1.0\",\n })\n await broadcast_audit(\n \"ranking\",\n- f\"Only {contributors[0]} is eligible; rank is 1.0\",\n+ f\"Only one eligible commit; {ordered[0]['contributor']} rank 1.0\",\n progress=90,\n phase=\"finalizing\",\n evidence_event_id=completed.event_id,\n evidence_url=_evidence_url(\"event\", completed.event_id),\n links={\"epoch\": _evidence_url(\"epoch\", str(epoch))},\n )\n- return ranking, [], {\n+ return contributor_ranking, [], {\n \"ranking_run_id\": ranking_run_id,\n \"ranking_event_id\": completed.event_id,\n }\n \n if not (OPENROUTER_API_KEY or \"\").strip():\n raise RuntimeError(\n- \"OPENROUTER_API_KEY is required when multiple contributors need ranking\"\n+ \"OPENROUTER_API_KEY is required when multiple commits need ranking\"\n )\n \n models = _find_ranking_models(ranking_run_id)\n if models is None:\n models = await fetch_top_models(n=3)\n if not models:\n- raise RuntimeError(\"no council models available for contributor ranking\")\n+ raise RuntimeError(\"no council models available for commit ranking\")\n await append_evidence(epoch, \"ranking.started\", {\n \"ranking_run_id\": ranking_run_id,\n \"commit_ids\": commit_ids,\n \"contributors\": contributors,\n \"models\": models,\n- \"summary\": f\"Council selected: {', '.join(models)}\",\n+ \"summary\": (\n+ f\"Council selected: {', '.join(models)} — \"\n+ f\"{len(ordered)} commits\"\n+ ),\n })\n await broadcast_audit(\n \"council\",\n- f\"Council selected: {', '.join(models)}\",\n+ f\"Council selected: {', '.join(models)} — ranking {len(ordered)} commits\",\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+ [\"div.log-council\",\n+ f\"Council: {', '.join(models)} — {len(ordered)} commits\"]\n ]))\n \n- authors = contributors\n- author_commits = {a: [] for a in authors}\n- for row in sorted(commits, key=lambda r: r[\"oid\"]):\n- author_commits[row[\"contributor\"]].append({\n- \"message\": row[\"message\"],\n- \"sha\": row[\"oid\"].split(\":\", 1)[1][:8],\n- \"diff\": row[\"patch\"],\n- \"commit_id\": commit_id_for_oid(row[\"oid\"]),\n- })\n-\n+ sides = [_commit_side_for_llm(row) for row in ordered]\n judgment_ids: list[str] = []\n \n async def compare_fn(i, j):\n- a1, a2 = authors[i], authors[j]\n- side_a = _author_side_for_llm(a1, author_commits)\n- side_b = _author_side_for_llm(a2, author_commits)\n+ side_a, side_b = sides[i], sides[j]\n+ label_a = f\"{side_a['commit_id'][:16]} ({side_a['contributor']})\"\n+ label_b = f\"{side_b['commit_id'][:16]} ({side_b['contributor']})\"\n prompt = build_pairwise_prompt(side_a, side_b)\n comparison_material = {\n \"ranking_run_id\": ranking_run_id,\n \"side_a\": {\n- \"contributor\": a1,\n- \"commit_ids\": side_a[\"commit_ids\"],\n+ \"contributor\": side_a[\"contributor\"],\n+ \"commit_id\": side_a[\"commit_id\"],\n+ \"commit_ids\": [side_a[\"commit_id\"]],\n+ \"oid\": side_a[\"oid\"],\n \"message\": _bytes_blob(side_a[\"message\"]),\n \"diff\": _bytes_blob(side_a[\"diff\"]),\n },\n \"side_b\": {\n- \"contributor\": a2,\n- \"commit_ids\": side_b[\"commit_ids\"],\n+ \"contributor\": side_b[\"contributor\"],\n+ \"commit_id\": side_b[\"commit_id\"],\n+ \"commit_ids\": [side_b[\"commit_id\"]],\n+ \"oid\": side_b[\"oid\"],\n \"message\": _bytes_blob(side_b[\"message\"]),\n \"diff\": _bytes_blob(side_b[\"diff\"]),\n },\n@@ -1650,22 +1669,24 @@ async def rank_commits(commits: list[dict], *, epoch: int = -1):\n comparison_material = {\n **comparison_material,\n \"comparison_id\": comparison_id,\n- \"summary\": f\"Comparing {a1} with {a2}\",\n+ \"summary\": f\"Comparing {label_a} with {label_b}\",\n }\n cmp_ev = await append_evidence(epoch, \"comparison.input\", comparison_material)\n await broadcast_audit(\n \"comparison\",\n- f\"Comparing {a1} with {a2}\",\n+ f\"Comparing commits {label_a} vs {label_b}\",\n phase=\"ranking\",\n evidence_event_id=cmp_ev.event_id,\n evidence_url=_evidence_url(\"comparison\", comparison_id),\n links={\n \"comparison\": _evidence_url(\"comparison\", comparison_id),\n+ \"commit_a\": _evidence_url(\"commit\", side_a[\"commit_id\"]),\n+ \"commit_b\": _evidence_url(\"commit\", side_b[\"commit_id\"]),\n \"epoch\": _evidence_url(\"epoch\", str(epoch)),\n },\n )\n await broadcast_js(exec_event(Three[Selector(\"#emission-status\")][MORPH][\n- [\"div#emission-status\", f\"Comparing {a1} vs {a2}…\"]\n+ [\"div#emission-status\", f\"Comparing {label_a} vs {label_b}…\"]\n ]))\n results = []\n for model in models:\n@@ -1697,9 +1718,15 @@ async def rank_commits(commits: list[dict], *, epoch: int = -1):\n jud_id = (existing or _find_judgment(comparison_id, model) or {}).get(\n \"judgment_id\"\n )\n+ win_label = (\n+ f\"{sides[w]['commit_id'][:16]} ({sides[w]['contributor']})\"\n+ )\n+ lose_label = (\n+ f\"{sides[l]['commit_id'][:16]} ({sides[l]['contributor']})\"\n+ )\n await broadcast_audit(\n \"vote\",\n- f\"{model}: {authors[w]} over {authors[l]} ({result['ratio']})\",\n+ f\"{model}: {win_label} over {lose_label} ({result['ratio']})\",\n phase=\"ranking\",\n evidence_url=(\n _evidence_url(\"judgment\", jud_id) if jud_id else None\n@@ -1714,8 +1741,8 @@ async def rank_commits(commits: list[dict], *, epoch: int = -1):\n await broadcast_js(exec_event(Three[Selector(\"#emission-log\")][PREPEND][\n [\"div.log-vote\",\n [\"span.model\", model], \" — \",\n- [\"span.winner\", authors[w]], f\" beat \",\n- [\"span.loser\", authors[l]], f\" ({result['ratio']}) \",\n+ [\"span.winner\", win_label], f\" beat \",\n+ [\"span.loser\", lose_label], f\" ({result['ratio']}) \",\n [\"span.explanation\", result[\"explanation\"]],\n ]\n ]))\n@@ -1745,24 +1772,46 @@ async def rank_commits(commits: list[dict], *, epoch: int = -1):\n [\"div#emission-status\", label]\n ]))\n \n- pairs = await pairwise_rank(len(authors), compare_fn, progress_fn)\n+ pairs = await pairwise_rank(len(ordered), compare_fn, progress_fn)\n \n if not pairs:\n- ranking = {authors[0]: Decimal(\"1\")} if authors else {}\n+ commit_score_list = [Decimal(\"1\")]\n else:\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+ commit_score_list = [Decimal(str(scores[i])) for i in range(len(ordered))]\n+\n+ commit_ranking = {\n+ commit_ids[i]: str(commit_score_list[i]) for i in range(len(ordered))\n+ }\n+ contributor_totals = _rollup_contributor_scores(ordered, commit_score_list)\n+ contrib_rows = sorted(\n+ contributor_totals.items(), key=lambda x: x[1], reverse=True\n+ )\n+ commit_rows = sorted(\n+ ((commit_ids[i], commit_score_list[i], ordered[i][\"contributor\"])\n+ for i in range(len(ordered))),\n+ key=lambda x: x[1],\n+ reverse=True,\n+ )\n completed = await append_evidence(epoch, \"ranking.completed\", {\n \"ranking_run_id\": ranking_run_id,\n \"models\": models,\n- \"ranking\": {a: str(s) for a, s in ranking_rows},\n+ \"commit_ranking\": commit_ranking,\n+ \"contributor_ranking\": {a: str(s) for a, s in contrib_rows},\n+ \"ranking\": {a: str(s) for a, s in contrib_rows},\n \"judgment_ids\": judgment_ids,\n- \"summary\": \"Ranking: \" + \", \".join(f\"{a} {s:.4f}\" for a, s in ranking_rows),\n+ \"summary\": (\n+ \"Commit ranking: \"\n+ + \", \".join(\n+ f\"{cid[:16]}={float(s):.4f}\" for cid, s, _ in commit_rows[:12]\n+ )\n+ + (\"…\" if len(commit_rows) > 12 else \"\")\n+ ),\n })\n await broadcast_audit(\n \"ranking\",\n- \"Ranking: \" + \", \".join(f\"{a} {s:.4f}\" for a, s in ranking_rows),\n+ \"Contributor rollup: \"\n+ + \", \".join(f\"{a} {s:.4f}\" for a, s in contrib_rows),\n progress=90,\n phase=\"finalizing\",\n evidence_event_id=completed.event_id,\n@@ -1772,10 +1821,10 @@ async def rank_commits(commits: list[dict], *, epoch: int = -1):\n await broadcast_js(exec_event(Three[Selector(\"#emission-log\")][PREPEND][\n [\"div.log-ranking\",\n [\"b\", \"Ranking: \"],\n- *[[\"span.rank-entry\", f\"{a} {float(s):.3f} \"] for a, s in ranking_rows],\n+ *[[\"span.rank-entry\", f\"{a} {float(s):.3f} \"] for a, s in contrib_rows],\n ]\n ]))\n- return ranking, models, {\n+ return contributor_totals, models, {\n \"ranking_run_id\": ranking_run_id,\n \"ranking_event_id\": completed.event_id,\n }\n@@ -2352,6 +2401,23 @@ async def epoch_detail(epoch: int):\n \n ranking_nodes: list = []\n if ranking_completed:\n+ commit_ranking = ranking_completed.payload.get(\"commit_ranking\") or {}\n+ contrib_ranking = (\n+ ranking_completed.payload.get(\"contributor_ranking\")\n+ or ranking_completed.payload.get(\"ranking\")\n+ or {}\n+ )\n+ commit_rank_links = [\n+ (\n+ f\"{cid[:20]} = {score}\",\n+ _evidence_path(\"commit\", cid),\n+ )\n+ for cid, score in sorted(\n+ commit_ranking.items(),\n+ key=lambda kv: Decimal(str(kv[1])),\n+ reverse=True,\n+ )\n+ ]\n ranking_nodes = [\n [\"p\", ranking_completed.payload.get(\"summary\") or \"ranking completed\"],\n _dl_rows([\n@@ -2362,10 +2428,10 @@ async def epoch_detail(epoch: int):\n ranking_completed.event_id,\n )),\n ]),\n- [\"pre.blob\", json.dumps(\n- ranking_completed.payload.get(\"ranking\") or {},\n- indent=2, sort_keys=True,\n- )],\n+ [\"h3\", \"commit ranking\"],\n+ _link_list(commit_rank_links) if commit_rank_links else [\"p.note\", \"(none)\"],\n+ [\"h3\", \"contributor rollup\"],\n+ [\"pre.blob\", json.dumps(contrib_ranking, indent=2, sort_keys=True)],\n ]\n elif ranking_started:\n ranking_nodes = [[\"p.note\", f\"Ranking started: {ranking_started.event_id}\"]]\n@@ -2386,14 +2452,9 @@ async def epoch_detail(epoch: int):\n else:\n emission_node = [\"p.note\", \"No emission for this epoch.\"]\n \n- contributors = {\n- e.payload.get(\"contributor\")\n- for e in commit_evs\n- if e.payload.get(\"contributor\")\n- }\n no_comparisons_note = \"No comparisons.\"\n- if len(contributors) <= 1:\n- no_comparisons_note += \" Single-contributor — no LLM judgments.\"\n+ if len(commit_evs) <= 1:\n+ no_comparisons_note += \" Fewer than two eligible commits — nothing to pairwise-rank.\"\n \n body = [\n _evidence_nav(),\n@@ -2511,9 +2572,14 @@ async def comparison_detail(comparison_id: str):\n j.payload.get(\"summary\") or jid,\n _evidence_path(\"judgment\", jid),\n ))\n- commit_links = []\n- for cid in (side_a.get(\"commit_ids\") or []) + (side_b.get(\"commit_ids\") or []):\n- commit_links.append((cid, _evidence_path(\"commit\", cid)))\n+ commit_ids = []\n+ for side in (side_a, side_b):\n+ cid = side.get(\"commit_id\")\n+ if cid:\n+ commit_ids.append(cid)\n+ else:\n+ commit_ids.extend(side.get(\"commit_ids\") or [])\n+ commit_links = [(cid, _evidence_path(\"commit\", cid)) for cid in commit_ids]\n return _evidence_page(f\"comparison {comparison_id[:24]}\", [\n _evidence_nav(_a(_evidence_path(\"epoch\", str(ev.epoch)), f\"epoch {ev.epoch}\")),\n [\"div.eyebrow\", \"comparison\"],\n@@ -2522,8 +2588,8 @@ async def comparison_detail(comparison_id: str):\n (\"summary\", p.get(\"summary\")),\n (\"ranking_run_id\", p.get(\"ranking_run_id\")),\n (\"evidence_event\", _a(_evidence_path(\"event\", ev.event_id), ev.event_id)),\n- (\"side_a\", side_a.get(\"contributor\")),\n- (\"side_b\", side_b.get(\"contributor\")),\n+ (\"side_a\", f\"{side_a.get('commit_id', '?')} ({side_a.get('contributor', '?')})\"),\n+ (\"side_b\", f\"{side_b.get('commit_id', '?')} ({side_b.get('contributor', '?')})\"),\n ]),\n [\"p\", _a(f\"/comparisons/{comparison_id}/prompt\", \"download prompt\")],\n [\"h2\", \"commits\"],\n@@ -2534,12 +2600,12 @@ async def comparison_detail(comparison_id: str):\n _link_list(judgment_links),\n [\"h2\", \"prompt\"],\n _pre_blob(_blob_text(p.get(\"prompt\"))),\n- [\"h2\", f\"side A — {side_a.get('contributor', '?')}\"],\n+ [\"h2\", f\"side A — {side_a.get('commit_id', side_a.get('contributor', '?'))}\"],\n [\"h3\", \"message\"],\n _pre_blob(_blob_text(side_a.get(\"message\"))),\n [\"h3\", \"diff\"],\n _pre_blob(_blob_text(side_a.get(\"diff\"))),\n- [\"h2\", f\"side B — {side_b.get('contributor', '?')}\"],\n+ [\"h2\", f\"side B — {side_b.get('commit_id', side_b.get('contributor', '?'))}\"],\n [\"h3\", \"message\"],\n _pre_blob(_blob_text(side_b.get(\"message\"))),\n [\"h3\", \"diff\"],\n@@ -3156,9 +3222,9 @@ async def watch():\n ],\n [\"p.note\",\n (\n- \"Pairwise council voting is ready.\"\n+ \"Pairwise council ranks every eligible commit.\"\n if key_ok else\n- \"Single-contributor epochs can finalize, but contested rankings require OPENROUTER_API_KEY.\"\n+ \"Epochs with two or more eligible commits require OPENROUTER_API_KEY.\"\n )\n ],\n ],\ndiff --git a/tests/integration.clj b/tests/integration.clj\nindex 11140e95a8cd86768a661a30e6b29a3ddfc95fcc..39b2476cb5ddf80733769f61343c81ba7287a974 100644\n--- a/tests/integration.clj\n+++ b/tests/integration.clj\n@@ -507,7 +507,7 @@\n \n (bind or-state @(:state or-mock))\n (assert! (pos? (:model-requests or-state)) \"OpenRouter /models was called\")\n- (assert! (>= (:compare-requests or-state) 3) \"at least 3 pairwise LLM calls (2 authors × 3 models)\")\n+ (assert! (>= (:compare-requests or-state) 3) \"at least 3 pairwise LLM calls (2 commits × 3 models)\")\n \n (bind ledger2 (get-json base-url \"/api/ledger\"))\n (assert! (>= (count ledger2) 3)\n@@ -543,6 +543,8 @@\n \"epoch page links comparisons\")\n (assert! (str/includes? epoch-html \"/judgments/\")\n \"epoch page links judgments\")\n+ (assert! (str/includes? epoch-html \"commit ranking\")\n+ \"epoch page shows per-commit ranking\")\n (bind commit-href\n (second (re-find #\"/commits/(c_[a-f0-9]+)\" epoch-html)))\n (assert! (some? commit-href) \"found a commit id on epoch page\")\ndiff --git a/tests/test_git_discovery.py b/tests/test_git_discovery.py\nindex 00d26bfa85737b178c8822804e278211974e0efe..0f002a58bd9a122d41c5a85e32c16ed2b4404d2f 100644\n--- a/tests/test_git_discovery.py\n+++ b/tests/test_git_discovery.py\n@@ -434,7 +434,7 @@ def test_emission_distribution_sums_exactly_to_total(\n assert entry.discovery_snapshot_id == \"ranked-snapshot\"\n \n \n-def test_single_contributor_ranking_is_total_and_uses_no_pairwise_votes(\n+def test_single_commit_ranking_skips_pairwise(\n discovery_config, monkeypatch,\n ):\n monkeypatch.setattr(c, \"store\", c.JsonlStore(discovery_config / \"ledger.jsonl\"))\n@@ -454,6 +454,65 @@ def test_single_contributor_ranking_is_total_and_uses_no_pairwise_votes(\n assert info[\"ranking_event_id\"]\n \n \n+def test_same_contributor_multiple_commits_runs_pairwise(\n+ discovery_config, monkeypatch,\n+):\n+ monkeypatch.setattr(c, \"store\", c.JsonlStore(discovery_config / \"ledger.jsonl\"))\n+ calls = {\"n\": 0}\n+\n+ async def models(n=3):\n+ return [\"m1\", \"m2\", \"m3\"]\n+\n+ async def compare(model_id, side_a, side_b, **kwargs):\n+ calls[\"n\"] += 1\n+ assert \"commit_id\" in side_a and \"commit_id\" in side_b\n+ if kwargs.get(\"persist\"):\n+ attempt_id = c.attempt_id_for(kwargs[\"comparison_id\"], model_id, 1)\n+ await c.append_evidence(kwargs[\"epoch\"], \"llm.judgment\", {\n+ \"judgment_id\": c.judgment_id_for({\n+ \"attempt_id\": attempt_id,\n+ \"comparison_id\": kwargs[\"comparison_id\"],\n+ \"model_id\": model_id,\n+ \"winner\": \"A\",\n+ \"ratio\": \"2:1\",\n+ \"explanation\": \"ok\",\n+ }),\n+ \"attempt_id\": attempt_id,\n+ \"comparison_id\": kwargs[\"comparison_id\"],\n+ \"model_id\": model_id,\n+ \"winner\": \"A\",\n+ \"ratio\": \"2:1\",\n+ \"explanation\": \"ok\",\n+ \"summary\": \"ok\",\n+ })\n+ return {\"winner\": \"A\", \"ratio\": \"2:1\", \"explanation\": \"ok\"}\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\": \"alice\",\n+ \"oid\": \"sha1:\" + char * 40,\n+ \"message\": f\"msg-{char}\",\n+ \"patch\": f\"patch-{char}\",\n+ }\n+ for char in (\"a\", \"b\", \"c\")\n+ ]\n+ ranking, used, info = asyncio.run(c.rank_commits(commits, epoch=0))\n+ assert set(ranking) == {\"alice\"}\n+ assert ranking[\"alice\"] > 0\n+ assert used == [\"m1\", \"m2\", \"m3\"]\n+ assert calls[\"n\"] >= 3\n+ completed = next(\n+ e for e in c.store.read()\n+ if isinstance(e, c.Evidence) and e.kind == \"ranking.completed\"\n+ )\n+ assert len(completed.payload[\"commit_ranking\"]) == 3\n+ assert \"alice\" in completed.payload[\"contributor_ranking\"]\n+ assert info[\"ranking_event_id\"]\n+\n+\n def test_any_council_failure_aborts_ranking(discovery_config, monkeypatch):\n monkeypatch.setattr(c, \"store\", c.JsonlStore(discovery_config / \"ledger.jsonl\"))\n \n@@ -479,16 +538,16 @@ def test_any_council_failure_aborts_ranking(discovery_config, monkeypatch):\n asyncio.run(c.rank_commits(commits, epoch=0))\n \n \n-def test_contested_ranking_requires_openrouter_key(monkeypatch):\n+def test_multi_commit_ranking_requires_openrouter_key(monkeypatch):\n monkeypatch.setattr(c, \"OPENROUTER_API_KEY\", \"\")\n commits = [\n {\n- \"contributor\": contributor,\n+ \"contributor\": \"alice\",\n \"oid\": \"sha1:\" + char * 40,\n- \"message\": contributor,\n+ \"message\": char,\n \"patch\": \"patch\",\n }\n- for contributor, char in [(\"alice\", \"a\"), (\"bob\", \"b\")]\n+ for char in (\"a\", \"b\")\n ]\n with pytest.raises(RuntimeError, match=\"OPENROUTER_API_KEY\"):\n asyncio.run(c.rank_commits(commits))\n\n\nSide B — contributor: tommy-mor\nSide B — commit message:\n[c94456ff] Make feed catch-up stable and permission-aware\n\nAnchor implicit feeds to durable ingest order and cover multi-user private-room visibility so concurrent posts are not missed or leaked.\n\nCo-authored-by: Cursor \n\nSide B — unified diff (full patch):\ndiff --git a/cli/src/main.rs b/cli/src/main.rs\nindex abb5a55b49f60fe28fbfd4ec02715cb94ea0b4ec..c4f1494df3aedbd8b883aea6249579aa8336abfe 100644\n--- a/cli/src/main.rs\n+++ b/cli/src/main.rs\n@@ -878,6 +878,30 @@ mod tests {\n \"graph: 4 items, 3/6 pairs (50.0% density), 1 component, connected\"\n );\n }\n+\n+ #[test]\n+ fn feed_without_since_uses_logged_in_delegate_from_env() {\n+ let key = \"SLUG_DELEGATE\";\n+ let previous = std::env::var_os(key);\n+ let expected = \"00000000-0000-0000-0000-0000000000ee:test:local/model\";\n+ std::env::set_var(key, expected);\n+\n+ let cli = Cli::try_parse_from([\"slugsocial\", \"feed\"]).expect(\"parse feed\");\n+\n+ match previous {\n+ Some(value) => std::env::set_var(key, value),\n+ None => std::env::remove_var(key),\n+ }\n+ match cli.cmd {\n+ Some(Command::Feed {\n+ delegate, since, ..\n+ }) => {\n+ assert_eq!(delegate.as_deref(), Some(expected));\n+ assert!(since.is_none());\n+ }\n+ _ => panic!(\"expected feed command\"),\n+ }\n+ }\n }\n \n async fn run_scoped(base: &str, room: &str, sub: ScopedCmd) -> Result<()> {\n@@ -1626,7 +1650,15 @@ async fn run() -> Result<()> {\n } else {\n for p in &resp.posts {\n let ago = slug_types::timeago::timeago(now_ms, p.ts);\n- println!(\"\", p.id, ago);\n+ let thread_attr = p\n+ .thread\n+ .as_deref()\n+ .map(|thread| format!(\" thread=\\\"{thread}\\\"\"))\n+ .unwrap_or_default();\n+ println!(\n+ \"\",\n+ p.id, ago, p.room, thread_attr\n+ );\n print!(\"{}\", p.body);\n if !p.body.ends_with('\\n') { println!(); }\n println!(\"\");\ndiff --git a/server/src/api/rpc.rs b/server/src/api/rpc.rs\nindex afc4f95bef160c1e38ecff2c096d6440cd94e2b3..46d748f918d9b225acc4ecedfe5a1793089407b5 100644\n--- a/server/src/api/rpc.rs\n+++ b/server/src/api/rpc.rs\n@@ -72,6 +72,80 @@ fn can_view_scope(reduced: &ReducerState, scope: &ScopeId, principal: Option<&st\n }\n }\n \n+/// Build a feed in durable ingest order.\n+///\n+/// An implicit feed boundary is an ingest position, not only its millisecond timestamp. Two users\n+/// can post in the same millisecond, and wall-clock timestamps can move backwards during replay.\n+/// Explicit `since` remains a timestamp query for API compatibility, but scans the whole ordered\n+/// ledger rather than assuming timestamps are monotonic.\n+fn rpc_feed(\n+ reduced: &ReducerState,\n+ viewer: &str,\n+ delegate: Option,\n+ requested_since: Option,\n+ implicit_anchor: Option<(usize, i64)>,\n+ limit: usize,\n+) -> FeedResponse {\n+ let since = requested_since.or_else(|| implicit_anchor.map(|(_, ts)| ts));\n+ let implicit_anchor_index = requested_since\n+ .is_none()\n+ .then(|| implicit_anchor.map(|(index, _)| index))\n+ .flatten();\n+\n+ let matching: Vec<&str> = reduced\n+ .ingests_ordered\n+ .iter()\n+ .enumerate()\n+ .rev()\n+ .filter(|(index, id)| {\n+ reduced.ingests_by_id.get(id.as_str()).is_some_and(|ing| {\n+ match requested_since {\n+ Some(cutoff) => ing.ts > cutoff,\n+ None => implicit_anchor_index.is_none_or(|anchor| *index > anchor),\n+ }\n+ })\n+ })\n+ .map(|(_, id)| id.as_str())\n+ .filter(|id| {\n+ reduced.ingests_by_id.get(*id).is_some_and(|ing| {\n+ let scope = scope_from_room_wire(&ing.room_id);\n+ can_view_scope(reduced, &scope, Some(viewer))\n+ })\n+ })\n+ .filter(|id| !reduced.redacted_posts.contains(*id))\n+ .collect();\n+\n+ let total = matching.len();\n+ let posts = matching\n+ .into_iter()\n+ .take(limit)\n+ .filter_map(|id| reduced.ingests_by_id.get(id))\n+ .map(|ing| {\n+ let scope = scope_from_room_wire(&ing.room_id);\n+ let thread_post_index = reduced.try_thread_post_index_chronological(\n+ &scope,\n+ &ing.thread_tag,\n+ &ing.id,\n+ );\n+ FeedPost {\n+ ts: ing.ts,\n+ id: ing.id.clone(),\n+ room: ing.room_id.clone(),\n+ thread: Some(ing.thread_tag.clone()),\n+ thread_post_index,\n+ body: ing.raw.clone(),\n+ }\n+ })\n+ .collect();\n+\n+ FeedResponse {\n+ delegate,\n+ since,\n+ posts,\n+ total,\n+ }\n+}\n+\n fn principal_from_optional_bearer(headers: &HeaderMap, reduced: &ReducerState) -> Result, RpcErr> {\n if headers.contains_key(axum::http::header::AUTHORIZATION) {\n verify_bearer_principal(headers, reduced)\n@@ -1506,60 +1580,27 @@ pub async fn handle_rpc_batch(\n Some(\"this delegate is not bound to your signed-in account\".into()),\n )\n } else {\n- let since_default = reduced\n+ let implicit_anchor = reduced\n .ingests_ordered\n .iter()\n+ .enumerate()\n .rev()\n- .filter_map(|id| reduced.ingests_by_id.get(id))\n- .find(|ing| {\n- if ing.delegate.as_deref() != Some(delegate_stored.as_str()) {\n- return false;\n- }\n- let scope = scope_from_room_wire(&ing.room_id);\n- can_view_scope(&reduced, &scope, Some(viewer.as_str()))\n- })\n- .map(|ing| ing.ts);\n- let since = since.or(since_default);\n- let cutoff = since.unwrap_or(0);\n- let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT);\n- let matching: Vec<&str> = reduced.ingests_ordered.iter().rev()\n- .map(|id| id.as_str())\n- .take_while(|id| reduced.ingests_by_id.get(*id).is_some_and(|ing| ing.ts > cutoff))\n- .filter(|id| {\n- reduced.ingests_by_id.get(*id).is_some_and(|ing| {\n- let scope = scope_from_room_wire(&ing.room_id);\n- can_view_scope(&reduced, &scope, Some(viewer.as_str()))\n+ .find_map(|(index, id)| {\n+ reduced.ingests_by_id.get(id).and_then(|ing| {\n+ (ing.delegate.as_deref()\n+ == Some(delegate_stored.as_str()))\n+ .then_some((index, ing.ts))\n })\n- })\n- .filter(|id| !reduced.redacted_posts.contains(*id))\n- .collect();\n- let total = matching.len();\n- let posts: Vec = matching.into_iter()\n- .take(limit)\n- .filter_map(|id| reduced.ingests_by_id.get(id))\n- .map(|ing| {\n- let scope = scope_from_room_wire(&ing.room_id);\n- let thread_post_index = reduced\n- .try_thread_post_index_chronological(\n- &scope,\n- &ing.thread_tag,\n- &ing.id,\n- );\n- FeedPost {\n- ts: ing.ts,\n- id: ing.id.clone(),\n- thread: Some(ing.thread_tag.clone()),\n- thread_post_index,\n- body: ing.raw.clone(),\n- }\n- })\n- .collect();\n- line_ok(RpcResult::Feed(FeedResponse {\n- delegate: Some(delegate_stored),\n+ });\n+ let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT);\n+ line_ok(RpcResult::Feed(rpc_feed(\n+ &reduced,\n+ &viewer,\n+ Some(delegate_stored),\n since,\n- posts,\n- total,\n- }))\n+ implicit_anchor,\n+ limit,\n+ )))\n };\n drop(reduced);\n line\n@@ -1567,60 +1608,25 @@ pub async fn handle_rpc_batch(\n None => {\n // Session catch-up: last time *you* posted anything (delegate or not), so revisiting\n // an old chat with only a token still gets a sane cutoff.\n- let since_default = reduced\n+ let implicit_anchor = reduced\n .ingests_ordered\n .iter()\n+ .enumerate()\n .rev()\n- .filter_map(|id| reduced.ingests_by_id.get(id))\n- .find(|ing| {\n- if ing.principal != viewer {\n- return false;\n- }\n- let scope = scope_from_room_wire(&ing.room_id);\n- can_view_scope(&reduced, &scope, Some(viewer.as_str()))\n- })\n- .map(|ing| ing.ts);\n- let since = since.or(since_default);\n- let cutoff = since.unwrap_or(0);\n- let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT);\n- let matching: Vec<&str> = reduced.ingests_ordered.iter().rev()\n- .map(|id| id.as_str())\n- .take_while(|id| reduced.ingests_by_id.get(*id).is_some_and(|ing| ing.ts > cutoff))\n- .filter(|id| {\n- reduced.ingests_by_id.get(*id).is_some_and(|ing| {\n- let scope = scope_from_room_wire(&ing.room_id);\n- can_view_scope(&reduced, &scope, Some(viewer.as_str()))\n+ .find_map(|(index, id)| {\n+ reduced.ingests_by_id.get(id).and_then(|ing| {\n+ (ing.principal == viewer).then_some((index, ing.ts))\n })\n- })\n- .filter(|id| !reduced.redacted_posts.contains(*id))\n- .collect();\n- let total = matching.len();\n- let posts: Vec = matching.into_iter()\n- .take(limit)\n- .filter_map(|id| reduced.ingests_by_id.get(id))\n- .map(|ing| {\n- let scope = scope_from_room_wire(&ing.room_id);\n- let thread_post_index = reduced\n- .try_thread_post_index_chronological(\n- &scope,\n- &ing.thread_tag,\n- &ing.id,\n- );\n- FeedPost {\n- ts: ing.ts,\n- id: ing.id.clone(),\n- thread: Some(ing.thread_tag.clone()),\n- thread_post_index,\n- body: ing.raw.clone(),\n- }\n- })\n- .collect();\n- let line = line_ok(RpcResult::Feed(FeedResponse {\n- delegate: None,\n+ });\n+ let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT);\n+ let line = line_ok(RpcResult::Feed(rpc_feed(\n+ &reduced,\n+ &viewer,\n+ None,\n since,\n- posts,\n- total,\n- }));\n+ implicit_anchor,\n+ limit,\n+ )));\n drop(reduced);\n line\n }\ndiff --git a/server/tests/integration_rooms.rs b/server/tests/integration_rooms.rs\nindex a3b378267e090a016a7e663f103a0dd9f482690b..e623523ba352ce456674a399542c689505760b78 100644\n--- a/server/tests/integration_rooms.rs\n+++ b/server/tests/integration_rooms.rs\n@@ -1,6 +1,9 @@\n mod support;\n \n use slug_types::room_route_segment;\n+use slugsocial_server::events::{\n+ AgentBound, Event, GrantAdded, GrantRevoked, Ingest, RoomCreated, ThreadCapability,\n+};\n use support::*;\n \n #[tokio::test]\n@@ -473,6 +476,247 @@ async fn test_feed_without_delegate_uses_principal_last_post_including_delegate(\n );\n }\n \n+#[tokio::test]\n+async fn test_feed_uses_delegate_ingest_position_when_multi_user_timestamps_collide() {\n+ let (addr, _tmp, _log, state, _handle) = create_test_server_with_state().await;\n+ seed_test_identity(&state, \"bob\", \"bobtok\", \"bobsecret\").await;\n+ let client = reqwest::Client::new();\n+ let alice_delegate =\n+ \"00000000-0000-0000-0000-0000000000c1:feedtest:local/alice-model\";\n+ let bob_delegate =\n+ \"00000000-0000-0000-0000-0000000000c2:feedtest:local/bob-model\";\n+\n+ {\n+ let mut reduced = state.reduced.write().await;\n+ for (agent, username) in [\n+ (alice_delegate, \"testuser\"),\n+ (bob_delegate, \"bob\"),\n+ ] {\n+ reduced.apply_event(Event::AgentBound(AgentBound {\n+ ts: 1,\n+ agent: agent.to_string(),\n+ username: username.to_string(),\n+ }));\n+ }\n+ reduced.apply_event(Event::Ingest(Ingest {\n+ ts: 100,\n+ id: \"alice-anchor\".into(),\n+ raw: \"alice anchor\".into(),\n+ principal: \"testuser\".into(),\n+ delegate: Some(alice_delegate.into()),\n+ room_id: \"public\".into(),\n+ thread_tag: \"feed-order\".into(),\n+ }));\n+ reduced.apply_event(Event::Ingest(Ingest {\n+ ts: 100,\n+ id: \"bob-same-millisecond\".into(),\n+ raw: \"bob same-millisecond change\".into(),\n+ principal: \"bob\".into(),\n+ delegate: Some(bob_delegate.into()),\n+ room_id: \"public\".into(),\n+ thread_tag: \"feed-order\".into(),\n+ }));\n+ // Event-log order remains authoritative even if the wall clock moves backwards.\n+ reduced.apply_event(Event::Ingest(Ingest {\n+ ts: 99,\n+ id: \"bob-clock-rollback\".into(),\n+ raw: \"bob change after clock rollback\".into(),\n+ principal: \"bob\".into(),\n+ delegate: Some(bob_delegate.into()),\n+ room_id: \"public\".into(),\n+ thread_tag: \"feed-order\".into(),\n+ }));\n+ }\n+\n+ let feed = rpc_batch(\n+ &client,\n+ addr,\n+ Some(&test_bearer()),\n+ serde_json::json!([{\n+ \"GetFeed\": { \"delegate\": alice_delegate, \"limit\": 20 }\n+ }]),\n+ )\n+ .await;\n+ let posts = feed[\"results\"][0][\"result\"][\"Feed\"][\"posts\"]\n+ .as_array()\n+ .unwrap();\n+ let ids: Vec<&str> = posts.iter().filter_map(|p| p[\"id\"].as_str()).collect();\n+ assert_eq!(\n+ ids,\n+ [\"bob-clock-rollback\", \"bob-same-millisecond\"],\n+ \"implicit feed cutoff must use append position, not timestamp\"\n+ );\n+}\n+\n+#[tokio::test]\n+async fn test_feed_multi_user_private_room_visibility_and_revoked_anchor_access() {\n+ let (addr, _tmp, _log, state, _handle) = create_test_server_with_state().await;\n+ seed_test_identity(&state, \"bob\", \"bobtok\", \"bobsecret\").await;\n+ seed_test_identity(&state, \"carol\", \"caroltok\", \"carolsecret\").await;\n+ let client = reqwest::Client::new();\n+ let alice_delegate =\n+ \"00000000-0000-0000-0000-0000000000d1:feedtest:local/alice-model\";\n+ let bob_delegate =\n+ \"00000000-0000-0000-0000-0000000000d2:feedtest:local/bob-model\";\n+ let room_alice = \"alice01/alice-room\";\n+ let room_bob = \"bob0001/bob-room\";\n+\n+ {\n+ let mut reduced = state.reduced.write().await;\n+ for (agent, username) in [\n+ (alice_delegate, \"testuser\"),\n+ (bob_delegate, \"bob\"),\n+ ] {\n+ reduced.apply_event(Event::AgentBound(AgentBound {\n+ ts: 1,\n+ agent: agent.to_string(),\n+ username: username.to_string(),\n+ }));\n+ }\n+ for (room_id, slug, owner) in [\n+ (room_alice, \"alice-room\", \"testuser\"),\n+ (room_bob, \"bob-room\", \"bob\"),\n+ ] {\n+ reduced.apply_event(Event::RoomCreated(RoomCreated {\n+ ts: 2,\n+ room_id: room_id.to_string(),\n+ slug: slug.to_string(),\n+ owner: owner.to_string(),\n+ }));\n+ reduced.apply_event(Event::GrantAdded(GrantAdded {\n+ ts: 2,\n+ room_id: room_id.to_string(),\n+ username: owner.to_string(),\n+ capabilities: vec![ThreadCapability::View],\n+ granted_by: owner.to_string(),\n+ }));\n+ }\n+\n+ let mut add_ingest =\n+ |ts, id: &str, raw: &str, principal: &str, delegate: Option<&str>, room: &str| {\n+ reduced.apply_event(Event::Ingest(Ingest {\n+ ts,\n+ id: id.into(),\n+ raw: raw.into(),\n+ principal: principal.into(),\n+ delegate: delegate.map(str::to_string),\n+ room_id: room.into(),\n+ thread_tag: \"feed-permissions\".into(),\n+ }));\n+ };\n+ add_ingest(10, \"prehistory\", \"must remain before alice anchor\", \"carol\", None, \"public\");\n+ add_ingest(\n+ 11,\n+ \"alice-private-anchor\",\n+ \"alice last posted here\",\n+ \"testuser\",\n+ Some(alice_delegate),\n+ room_alice,\n+ );\n+ add_ingest(\n+ 12,\n+ \"bob-public-anchor\",\n+ \"bob last posted here\",\n+ \"bob\",\n+ Some(bob_delegate),\n+ \"public\",\n+ );\n+ add_ingest(13, \"alice-room-change\", \"visible only to alice\", \"carol\", None, room_alice);\n+ add_ingest(14, \"bob-room-change\", \"visible only to bob\", \"carol\", None, room_bob);\n+ add_ingest(15, \"public-change\", \"visible to everyone\", \"carol\", None, \"public\");\n+\n+ reduced.apply_event(Event::GrantRevoked(GrantRevoked {\n+ ts: 16,\n+ room_id: room_alice.into(),\n+ username: \"testuser\".into(),\n+ capabilities: vec![ThreadCapability::View],\n+ revoked_by: \"testuser\".into(),\n+ }));\n+ }\n+\n+ let alice_feed = rpc_batch(\n+ &client,\n+ addr,\n+ Some(&test_bearer()),\n+ serde_json::json!([{\n+ \"GetFeed\": { \"delegate\": alice_delegate, \"limit\": 20 }\n+ }]),\n+ )\n+ .await;\n+ let alice_posts = alice_feed[\"results\"][0][\"result\"][\"Feed\"][\"posts\"]\n+ .as_array()\n+ .unwrap();\n+ let alice_ids: Vec<&str> = alice_posts\n+ .iter()\n+ .filter_map(|p| p[\"id\"].as_str())\n+ .collect();\n+ assert_eq!(\n+ alice_ids,\n+ [\"public-change\", \"bob-public-anchor\"],\n+ \"revoked private content must be hidden without moving the delegate anchor backwards\"\n+ );\n+ assert!(!alice_ids.contains(&\"prehistory\"));\n+ assert!(\n+ alice_posts\n+ .iter()\n+ .all(|post| post[\"room\"].as_str() == Some(\"public\")),\n+ \"private posts must not leak and every feed post must identify its room\"\n+ );\n+\n+ let bob_bearer = test_bearer_for(\"bobtok\", \"bobsecret\");\n+ let bob_feed = rpc_batch(\n+ &client,\n+ addr,\n+ Some(&bob_bearer),\n+ serde_json::json!([{\n+ \"GetFeed\": { \"delegate\": bob_delegate, \"limit\": 20 }\n+ }]),\n+ )\n+ .await;\n+ let bob_ids: Vec<&str> = bob_feed[\"results\"][0][\"result\"][\"Feed\"][\"posts\"]\n+ .as_array()\n+ .unwrap()\n+ .iter()\n+ .filter_map(|p| p[\"id\"].as_str())\n+ .collect();\n+ assert_eq!(bob_ids, [\"public-change\", \"bob-room-change\"]);\n+ assert_eq!(\n+ bob_feed[\"results\"][0][\"result\"][\"Feed\"][\"posts\"][1][\"room\"],\n+ room_bob\n+ );\n+\n+ // Restoring View exposes only changes after the same stable delegate anchor.\n+ {\n+ let mut reduced = state.reduced.write().await;\n+ reduced.apply_event(Event::GrantAdded(GrantAdded {\n+ ts: 17,\n+ room_id: room_alice.into(),\n+ username: \"testuser\".into(),\n+ capabilities: vec![ThreadCapability::View],\n+ granted_by: \"testuser\".into(),\n+ }));\n+ }\n+ let restored = rpc_batch(\n+ &client,\n+ addr,\n+ Some(&test_bearer()),\n+ serde_json::json!([{\n+ \"GetFeed\": { \"delegate\": alice_delegate, \"limit\": 20 }\n+ }]),\n+ )\n+ .await;\n+ let restored_ids: Vec<&str> = restored[\"results\"][0][\"result\"][\"Feed\"][\"posts\"]\n+ .as_array()\n+ .unwrap()\n+ .iter()\n+ .filter_map(|p| p[\"id\"].as_str())\n+ .collect();\n+ assert_eq!(\n+ restored_ids,\n+ [\"public-change\", \"alice-room-change\", \"bob-public-anchor\"]\n+ );\n+}\n+\n #[tokio::test]\n async fn test_private_room_thread_urls_use_t_segment() {\n let (addr, _tmp, _log, _handle) = create_test_server().await;\ndiff --git a/server/tests/support/mod.rs b/server/tests/support/mod.rs\nindex 4a620eaa875e7a1145f2a4e82cc4ff2be21d5345..a4320e991763617c1a760efad4b621977e2b74d0 100644\n--- a/server/tests/support/mod.rs\n+++ b/server/tests/support/mod.rs\n@@ -20,8 +20,10 @@ pub fn sha256_hex(s: &str) -> String {\n \n /// Fixed bearer for integration tests (`TokenIssued` seeded into reducer in `create_test_server`).\n pub fn test_bearer() -> String {\n- let token_id = \"testtok\";\n- let secret = \"secret\";\n+ test_bearer_for(\"testtok\", \"secret\")\n+}\n+\n+pub fn test_bearer_for(token_id: &str, secret: &str) -> String {\n format!(\"slug_{token_id}_{secret}\")\n }\n \n@@ -71,19 +73,27 @@ pub async fn rpc_batch(\n }\n \n pub async fn seed_test_token(state: &AppState) {\n+ seed_test_identity(state, \"testuser\", \"testtok\", \"secret\").await;\n+}\n+\n+/// Add a distinct principal and bearer to a running integration-test server.\n+pub async fn seed_test_identity(\n+ state: &AppState,\n+ username: &str,\n+ token_id: &str,\n+ secret: &str,\n+) {\n let registered = Event::UserRegistered(UserRegistered {\n ts: 0,\n- username: \"testuser\".to_string(),\n+ username: username.to_string(),\n provider: \"test\".to_string(),\n- provider_id: \"testuser\".to_string(),\n+ provider_id: username.to_string(),\n });\n- let token_id = \"testtok\";\n- let secret = \"secret\";\n let salt = \"salt\";\n let token_hash = sha256_hex(&format!(\"{salt}:{secret}\"));\n let ev = Event::TokenIssued(TokenIssued {\n ts: 0,\n- username: \"testuser\".to_string(),\n+ username: username.to_string(),\n token_id: token_id.to_string(),\n token_hash,\n salt: salt.to_string(),\ndiff --git a/types/src/lib.rs b/types/src/lib.rs\nindex 211493935d19582607f5c87fb492faf47bdc6f53..cd6f94c60a4e1c3bfbce13bc0404b803f5f57c6d 100644\n--- a/types/src/lib.rs\n+++ b/types/src/lib.rs\n@@ -264,6 +264,9 @@ pub struct FeedResponse {\n pub struct FeedPost {\n pub ts: i64,\n pub id: String,\n+ /// Permission scope containing the post: `\"public\"` or a private room id.\n+ #[serde(default)]\n+ pub room: String,\n /// Primary thread tag (without #), if the ingest declared one.\n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub thread: Option,\n","role":"user"}],"model":"~anthropic/claude-sonnet-latest"}